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.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | code | 2187 | import .Unitful: Quantity, FreeUnits, unit, upreferred
function to_num_str(p::AbstractParticles{T}, d=3, ds=d-1) where T <: Quantity
s = pstd(p)
if s.val < eps(p)
string(pmean(p))
else
string(pmean(p), " ± ", s)
end
end
Unitful.unit(v::AbstractParticles{T}) where T = unit(T)
Unitful.upreferred(v::AbstractParticles) = Unitful.uconvert(upreferred(unit(v)), v)
function Base.show(io::IO, ::MIME"text/plain", p::AbstractParticles{T,N}) where {T <: Unitful.Quantity, N}
sPT = MonteCarloMeasurements.shortform(p)
compact = get(io, :compact, false)
if compact
print(io, MonteCarloMeasurements.to_num_str(p, 6, 3))
else
print(io, MonteCarloMeasurements.to_num_str(p, 6, 3), " $(typeof(p))\n")
end
end
for PT in ParticleSymbols
@eval begin
function Base.promote_rule(::Type{Quantity{S,D,U}}, ::Type{$PT{T,N}}) where {S, D, U, T, N}
NT = promote_type(Quantity{S,D,U},T)
$PT{NT,N}
end
function Base.convert(::Type{$PT{Quantity{S,D,U},N}}, y::Quantity) where {S, D, U, N}
$PT{Quantity{S,D,U},N}(fill(y, N))
end
function Unitful.uconvert(a::Unitful.FreeUnits, y::$PT)
$PT(Unitful.uconvert.(a, y.particles))
end
end
for op in (*, /)
f = nameof(op)
@eval begin
function Base.$f(p::$PT{T,N}, y::Quantity{S,D,U}) where {S, D, U, T, N}
NT = promote_type(T, S)
$PT{Quantity{NT,D,U},N}($(op).(p.particles , y))
end
function Base.$f(p::$PT{T,N}, y::Quantity{S,D,U}) where {S, D, U, T <: Quantity, N}
QT = Base.promote_op($op, T, typeof(y))
$PT{QT,N}($(op).(p.particles, y))
end
# Below is just the reverse signature of above
function Base.$f(y::Quantity{S,D,U}, p::$PT{T,N}) where {S, D, U, T <: Quantity, N}
QT = Base.promote_op($op, typeof(y), T)
$PT{QT,N}($(op).(y, p.particles))
end
function Base.$f(p::$PT, y::FreeUnits)
$PT($(op).(p.particles, y))
end
end
end
end
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | code | 34578 | @info "Running tests"
using MonteCarloMeasurements, Distributions
using Test, LinearAlgebra, Statistics, Random, GenericSchur
import MonteCarloMeasurements: ⊗, gradient, optimize, DEFAULT_NUM_PARTICLES
@info "import Plots, Makie"
import Plots
import Makie
@info "import plotting packages done"
Random.seed!(0)
@testset "MonteCarloMeasurements.jl" begin
@info "Testing MonteCarloMeasurements"
# σ/√N = σm
@time @testset "sampling" begin
@info "Testing sampling"
for _ = 1:10
@test -3 < mean(systematic_sample(100))*sqrt(100) < 3
@test -3 < mean(systematic_sample(10000))*sqrt(10000) < 3
@test -0.9 < std(systematic_sample(100)) < 1.1
@test -0.9 < std(systematic_sample(10000)) < 1.1
end
params = Distributions.params
@test systematic_sample(10000, Normal(1,1)) |> Base.Fix1(fit, Normal) |> params |> x-> all(isapprox.(x,(1,1), atol=0.1))
systematic_sample(10000, Gamma(1,1)) #|> Base.Fix1(fit, Gamma)
systematic_sample(10000, TDist(1)) #|> Base.Fix1(fit, TDist)
@test systematic_sample(10000, Beta(1,1)) |> Base.Fix1(fit, Beta) |> params |> x-> all(isapprox.(x,(1,1), atol=0.1))
for i = 1:100
@test MonteCarloMeasurements.ess(Particles(10000)) > 7000
x = randn(5000)
v = vec([x';x'])
@test 3000 < MonteCarloMeasurements.ess(Particles(v)) < 5300
end
end
@time @testset "Basic operations" begin
@info "Creating the first StaticParticles"
@test 0 ∓ 1 isa StaticParticles
@test [0,0] ∓ 1. isa MonteCarloMeasurements.MvParticles
@test [0,0] ∓ [1.,1.] isa MonteCarloMeasurements.MvParticles
@test -50 ⊞ Normal(0,1) ≈ -50 ± 1
@test 10 ⊠ Normal(0,1) ≈ 10*Particles(Normal(0,1))
@info "Done"
PT = Particles
for PT = (Particles, StaticParticles)
@testset "$(repr(PT))" begin
@info "Running tests for $PT"
p = PT(100)
@test_nowarn MonteCarloMeasurements.shortform(p)
@test_nowarn println(p)
@test (p+p+p).particles ≈ 3p.particles # Test 3arg operator
@test (p+p+1).particles ≈ 1 .+ 2p.particles # Test 3arg operator
@test (1+p+1).particles ≈ 2 .+ p.particles # Test 3arg operator
@test (p+1+p).particles ≈ 1 .+ 2p.particles # Test 3arg operator
@test 0 ± 1 ≈ p
@test ± 1 ≈ p
@test 0 ∓ 1 ≈ p
@test ∓ 1 ≈ p
@test sum(p) ≈ 0
@test pcov(p) ≈ 1 atol=0.2
@test pstd(p) ≈ 1 atol=0.2
@test pvar(p) ≈ 1 atol=0.2
@test meanvar(p) ≈ 1/(nparticles(p)) atol=5e-3
@test meanstd(p) ≈ 1/sqrt(nparticles(p)) atol=5e-3
@test minmax(1+p,p) == (p, 1+p)
b = PT(100)
uvec = unique([p, p, b, p, b, b]) # tests hash
@test length(uvec) == 2
@test p ∈ uvec
@test b ∈ uvec
@test PT(100, Normal(0.0)) isa PT{Float64, 100}
@test PT(100, Normal(0.0f0)) isa PT{Float32, 100}
@test PT(100, Uniform(0.0f0, 1.0f0)) isa PT{Float32, 100}
@test !(p ≲ p)
@test !(p ≳ p)
@test (p ≲ 2.1)
@test !(p ≲ 1.9)
@test (p ≳ -2.1)
@test !(p ≳ -1.9)
@test (-2.1 ≲ p)
@test !(-1.9 ≲ p)
@test (2.1 ≳ p)
@test !(1.9 ≳ p)
@test p ≈ p
@test p ≈ 0
@test 0 ≈ p
@test p != 0
@test p != 2p
@test p ≈ 1.9pstd(p)
@test !(p ≈ 2.1pstd(p))
@test !(p ≉ p)
@test !(pmean(p) ≉ p)
@test p ≉ 2.1pstd(p)
@test !(p ≉ 1.9pstd(p))
@test (5 ± 0.1) ≳ (1 ± 0.1)
@test (1 ± 0.1) ≲ (5 ± 0.1)
a = rand()
pa = Particles([a])
@test a == pa
@test a ≈ pa
@test pa ≈ a
v = randn(5)
@test Vector(PT(v)) == v
@test Array(PT(v)) == v
@testset "unsafe comparisons" begin
unsafe_comparisons(false)
@test_throws ErrorException p<p
@test_throws ErrorException p>p
@test_throws ErrorException p>=p
@test_throws ErrorException p<=p
for mode in (:montecarlo, :reduction, :safe)
@show mode
unsafe_comparisons(mode, verbose=false)
@test p<100+p
@test p+100>p
@test p+100>=p
@test p<=100+p
@test p<100
@test 100>p
@test 100>=p
@test p<=100
@unsafe begin
@test -10 < p
@test p <= p
@test p >= p
@test !(p < p)
@test !(p > p)
@test (p < 1+p)
@test (p+1 > p)
end
end
@test_throws ErrorException p<p
@test_throws ErrorException p>p
@test_throws ErrorException @unsafe error("") # Should still be safe after error
@test_throws ErrorException p>=p
@test_throws ErrorException p<=p
unsafe_comparisons(:montecarlo, verbose=false)
@test p>=p
@test p<=p
@test !(p<p)
@test !(p>p)
@test_throws ErrorException p < Particles(p.particles[randperm(nparticles(p))])
unsafe_comparisons(false)
@unsafe tv = 2
@test tv == 2
@unsafe tv1,tv2 = 1,2
@test (tv1,tv2) == (1,2)
@unsafe tv3,tv4 = range(1, stop=3, length=5), range(1, stop=3, length=5)
@test (tv3,tv4) == (range(1, stop=3, length=5),range(1, stop=3, length=5))
@test MonteCarloMeasurements.COMPARISON_FUNCTION[] == pmean
set_comparison_function(pmedian)
@test MonteCarloMeasurements.COMPARISON_FUNCTION[] == pmedian
cp = PT(10)
cmp = @unsafe p < cp
@test cmp == (pmedian(p) < pmedian(cp))
set_comparison_function(pmean)
end
f = x -> 2x + 10
@test 9.6 < pmean(f(p)) < 10.4
# @test 9.6 < f(p) < 10.4
@test f(p) ≈ 10
@test !(f(p) ≲ 11)
@test f(p) ≲ 15
@test 5 ≲ f(p)
@test 1 ≲ 2
@test Normal(f(p)).μ ≈ pmean(f(p))
@test fit(Normal, f(p)).μ ≈ pmean(f(p))
f = x -> x^2
p = PT(100)
@test 0.9 < pmean(f(p)) < 1.1
@test 0.9 < pmean(f(p)) < 1.1
@test f(p) ≈ 1
@test !(f(p) ≲ 1)
@test f(p) ≲ 5
@test -3 ≲ f(p)
@test MvNormal([f(p),p]) isa MvNormal
A = randn(3,3) .+ [PT(100) for i = 1:3, j = 1:3]
a = [PT(100) for i = 1:3]
b = [PT(100) for i = 1:3]
@test sum(a.*b) ≈ 0
@test all(A*b .≈ [0,0,0])
@test A*b .+ 1 ≈ [1,1,1]
@test [1,1,1] ≈ A*b .+ 1
@test all(A\b .≈ zeros(3))
@test_nowarn @unsafe qr(A)
@test_nowarn Particles(100, MvNormal(2,1)) ./ Particles(100, Normal(2,1))
pn = Particles(100, Normal(2,1), systematic=false)
@test pn ≈ 2
@test !issorted(pn.particles)
@test !issorted(p.particles)
pn = Particles(100, Normal(2,1), systematic=true, permute=false)
@test pn ≈ 2
@test issorted(pn.particles)
rng = MersenneTwister(657)
pn1 = Particles(rng, 100, Normal(2,1), systematic=true, permute=true)
rng = MersenneTwister(657)
pn2 = Particles(rng, 100, Normal(2,1), systematic=true, permute=true)
@test pn1 == pn2
rng = MersenneTwister(27)
pn1 = Particles(rng, Normal(2,1), systematic=true, permute=true)
rng = MersenneTwister(27)
pn2 = Particles(rng, Normal(2,1), systematic=true, permute=true)
@test pn1 == pn2
rng = MersenneTwister(932)
pn1 = Particles(rng, 100, systematic=true, permute=true)
rng = MersenneTwister(932)
pn2 = Particles(rng, 100, systematic=true, permute=true)
@test pn1 == pn2
@test PT(Float32) isa PT{Float32}
@test PT(Float64) isa PT{Float64}
@test PT(Float32, 250) isa PT{Float32, 250}
@test PT(Float32, 250, Normal(0.1f0)) isa PT{Float32, 250}
@test_throws ArgumentError PT(Float32, 250, Gamma(0.1))
@info "Tests for $PT done"
p = PT{Float64,10}(2)
@test p isa PT{Float64,10}
@test all(p.particles .== 2)
@test Particles(100) + Particles(randn(Float32, 100)) ≈ 0
@test_throws MethodError p + Particles(randn(Float32, 200)) # Npart and Float type differ
@test_throws MethodError p + Particles(200) # Npart differ
mp = MvParticles([randn(10) for _ in 1:3])
@test length(mp) == 10
@test nparticles(mp) == 3
v = [(1,2), (3,4)]
pv = MvParticles(v)
@test length(pv) == 2
@test pv[1].particles[1] == v[1][1]
@test pv[1].particles[2] == v[2][1]
@test pv[2].particles[1] == v[1][2]
@test pv[2].particles[2] == v[2][2]
@test length(pv) == 2
v = [(a=1,b=randn(2)), (a=3,b=randn(2))]
pv = MvParticles(v)
@test length(pv) == 2
@test pv.a.particles[1] == v[1].a
@test pv.a.particles[2] == v[2].a
@test pv.b == Particles([v[1].b v[2].b]')
@test length(pv) == 2
@testset "discrete distributions" begin
p = PT(Poisson(50))
@test p isa PT{Int}
@test (p^2 - 1) isa PT{Int}
@test exp(p) isa PT{Float64}
# mainly just test that printing PT{Int} doesn't error
io = IOBuffer()
show(io, p)
s = String(take!(io))
@test occursin('±', s)
# issue #50
@test 2.5 * p isa PT{Float64}
@test p / 3 isa PT{Float64}
@test sqrt(p) isa PT{Float64}
end
end
end
end
@time @testset "Multivariate Particles" begin
for PT = (Particles, StaticParticles)
@testset "$(repr(PT))" begin
@info "Running tests for multivariate $PT"
p = PT(100, MvNormal(2,1))
@test_nowarn sum(p)
@test pcov(p) ≈ I atol=0.6
@test pcor(p) ≈ I atol=0.6
@test pmean(p) ≈ [0,0] atol=0.2
m = Matrix(p)
@test size(m) == (100,2)
# @test m[1,2] == p[1,2]
p = PT(100, MvNormal(2,2))
@test pcov(p) ≈ 4I atol=2
@test [0,0] ≈ pmean(p) atol=1
@test size(Matrix(p)) == (100,2)
p = PT(100, MvNormal(2,2))
@test fit(MvNormal, p).μ ≈ pmean(p)
@test MvNormal(p).μ ≈ pmean(p)
@test cov(MvNormal(p)) ≈ pcov(p)
@info "Tests for multivariate $PT done"
end
end
end
@testset "sigmapoints" begin
@info "Testing sigmapoints"
m = 1
Σ = 3
s = sigmapoints(m,Σ)
@test var(s) ≈ Σ
@test mean(s) == m
@test sigmapoints(Normal(m,√(Σ))) == s
m = [1,2]
Σ = [3. 1; 1 4]
s = sigmapoints(m,Σ)
@test cov(s) ≈ Σ
@test mean(s, dims=1)' ≈ m
@test sigmapoints(MvNormal(m,Σ)) == s
end
@testset "transform_moments" begin
m, Σ = [1,2], [2 1; 1 4] # Desired mean and covariance
C = randn(2,2)
C = cholesky(C'C + 5I).L
particles = transform_moments((C*randn(2,DEFAULT_NUM_PARTICLES))', m, Σ)
@test mean(particles, dims=1)[:] ≈ m
@test cov(particles) ≈ Σ
particles = transform_moments((C*randn(2,DEFAULT_NUM_PARTICLES))', m, Σ, preserve_latin=true)
@test mean(particles, dims=1)[:] ≈ m
@test Diagonal(cov(particles)) ≈ Diagonal(Σ) atol=2
end
@time @testset "gradient" begin
@info "Testing gradient"
e = 0.001
p = 3 ± e
f = x -> x^2
fp = f(p)
@test gradient(f,p)[1] ≈ 6 atol=1e-4
@test gradient(f,p)[2] ≈ 2e atol=1e-4
# @test gradient(f,3) > 6 # Convex function
@test gradient(f,3) ≈ 6
A = randn(3,3)
H = A'A
h = randn(3)
c = randn()
@assert isposdef(H)
f = x -> (x'H*x + h'x) + c
j = x -> H*x + h
e = 0.001
x = randn(3)
xp = x ± e
g = 2H*x + h
@test MonteCarloMeasurements.gradient(f,xp) ≈ g atol = 0.1
@test MonteCarloMeasurements.jacobian(j,xp) ≈ H
end
@time @testset "leastsquares" begin
@info "Testing leastsquares"
n, m = 10000, 3
A = randn(n,m)
x = randn(m)
y = A*x
σ = 0.1
yn = y .+ σ.*randn()
# xh = A\y
C1 = σ^2*inv(A'A)
yp = yn .+ σ.*Particles.(2000)
xhp = (A'A)\(A'yp)
@test xhp ≈ A\yp
@test sum(abs, tr((pcov(xhp) .- C1) ./ abs.(C1))) < 0.2
@test norm(pcov(xhp) .- C1) < 1e-7
@test xhp ≈ x
@test pmean(xhp) ≈ x atol=3sum(sqrt.(diag(C1)))
yp = nothing; GC.gc(true) # make sure this big matrix is deallocated
end
@time @testset "misc" begin
@info "Testing misc"
p = 0 ± 1
@test MonteCarloMeasurements.particletypetuple(p) == (Float64, DEFAULT_NUM_PARTICLES, Particles)
@test MonteCarloMeasurements.particletypetuple(typeof(p)) == (Float64, DEFAULT_NUM_PARTICLES, Particles)
@test_nowarn display(p)
@test_nowarn println(p)
@test_nowarn show(stdout, MIME"text/x-latex"(), p); println()
@test_nowarn println(0p)
@test_nowarn show(stdout, MIME"text/x-latex"(), 0p); println()
@test_nowarn show(stdout, MIME"text/x-latex"(), p + im*p); println()
@test_nowarn show(stdout, MIME"text/x-latex"(), p - im*p); println()
@test_nowarn show(stdout, MIME"text/x-latex"(), im*p); println()
@test_nowarn show(stdout, MIME"text/x-latex"(), -im*p); println()
@test_nowarn show(stdout, MIME"text/plain"(), p); println()
@test_nowarn println(0p)
@test_nowarn show(stdout, MIME"text/plain"(), 0p); println()
@test_nowarn show(stdout, MIME"text/plain"(), p + im*p); println()
@test_nowarn show(stdout, MIME"text/plain"(), p - im*p); println()
@test_nowarn show(stdout, MIME"text/plain"(), im*p); println()
@test_nowarn show(stdout, MIME"text/plain"(), -im*p -10im); println()
@test_nowarn display([p, p])
@test_nowarn println([p, p])
@test_nowarn println([p, 0p])
@test Particles{Float64,DEFAULT_NUM_PARTICLES}(p) == p
@test Particles{Float64,5}(0) == 0*Particles(5)
@test length(Particles(100, MvNormal(2,1))) == 2
@test nparticles(p) == DEFAULT_NUM_PARTICLES
@test ndims(p) == 0
@test particleeltype(p) == Float64
@test eltype(typeof(p)) == typeof(p)
@test eltype(p) == typeof(p)
@test convert(Int, 0p) == 0
@test promote_type(Particles{Float64,10}, Float64) == Particles{Float64,10}
@test promote_type(Particles{Float64,10}, Int64) == Particles{Float64,10}
@test promote_type(Particles{Float64,10}, ComplexF64) == Complex{Particles{Float64,10}}
@test promote_type(Particles{Float64,10}, Missing) == Union{Particles{Float64,10},Missing}
@testset "promotion of $PT" for PT in (Particles, StaticParticles)
@test promote_type(PT{Float64,10}, PT{Float64,10}) == PT{Float64,10}
@test promote_type(PT{Float64,10}, PT{Int,10}) == PT{Float64,10}
@test promote_type(PT{Int,5}, PT{Float64,10}) == PT
@test promote_type(PT{Float64,10}, PT{Float32,10}) == PT{Float64,10}
@test promote_type(StaticParticles{Float64,10}, PT{Float32,10}) == StaticParticles{Float64,10}
end
@test promote_type(Particles{Float64,10}, StaticParticles{Float64,10}) == StaticParticles{Float64,10}
@test promote_type(Particles{Int,10}, StaticParticles{Float64,10}) == StaticParticles{Float64,10}
@test promote_type(Particles{Float64,10}, StaticParticles{Float32,10}) == StaticParticles{Float64,10}
@test promote_type(Particles{Int,10}, StaticParticles{Float32,10}) == StaticParticles{Float32,10}
@test convert(Float64, 0p) isa Float64
@test convert(Float64, 0p) == 0
@test convert(Int, 0p) isa Int
@test convert(Int, 0p) == 0
@test convert(Particles{Float64,100}, Particles(randn(Float32, 100))) isa Particles{Float64,100}
@test_throws ArgumentError convert(Int, p)
@test_throws ArgumentError AbstractFloat(p)
@test AbstractFloat(0p) == 0.0
@test Particles(500) + Particles(randn(Float32, 500)) isa typeof(Particles(500))
@test isfinite(p)
@test iszero(0p)
@test iszero(p, 0.1)
@test !iszero(p)
@test !(!p)
@test !(0p)
@test round(p) == Particles(round.(p.particles))
@test round(Int,0.001p) == 0
@test round(Int,p) isa Particles{Int, nparticles(p)}
@test sincos(p) == (sin(p), cos(p))
@test norm(p) == abs(p)
@test pmean(norm([p,p]) - sqrt(2p^2)) < sqrt(eps()) # ≈ with atol fails on mac
@test pmean(LinearAlgebra.norm2([p,p]) - sqrt(2p^2)) < sqrt(eps()) # ≈ with atol fails on mac
@test MvNormal(Particles(500, MvNormal(2,1))) isa MvNormal
@test eps(typeof(p)) == eps(Float64)
@test eps(p) == eps(Float64)
A = randn(2,2)
B = A .± 0
@test sum(pmean, exp(A) .- exp(B)) < 1e-9
@test sum(pmean, LinearAlgebra.exp!(copy(A)) .- LinearAlgebra.exp!(copy(B))) < 1e-9
@test sum(pmean, abs.(log(A)) .- abs.(log(B))) < 1e-9
@test sum(pmean, abs.(eigvals(A)) .- abs.(eigvals(B))) < 1e-9
@test @unsafe pmean(sum(abs, sort(eigvals([0 1 ± 0.001; -1. 0]), by=imag) - [ 0.0 - (1.0 ± 0.0005)*im
0.0 + (1.0 ± 0.0005)*im])) < 0.002
e = eigvals([1 ± 0.001 0; 0 1.])
@test e isa Vector{Complex{Particles{Float64, DEFAULT_NUM_PARTICLES}}}
@test all(isapprox.(e, [1.0 ± 0.00058, 1.0 ± 0.00058], atol=1e-2))
## Complex matrix ops
A = randn(ComplexF64, 2, 2)
B = complex.(Particles.(fill.(real.(A), 10)), Particles.(fill.(imag.(A), 10)))
show(B)
@test sum(pmean, abs.(exp(A) .- exp(B))) < 1e-9
@test sum(pmean, abs.(LinearAlgebra.exp!(copy(A)) .- LinearAlgebra.exp!(copy(B)))) < 1e-9
@test sum(pmean, abs.(log(A) .- log(B))) < 1e-9
@test abs(det(A) - det(B)) < 1e-9
@test sum(pmean, svdvals(A) .- svdvals(B)) < 1e-9
@test sum(pmean, abs.(eigvals(A) .- eigvals(B))) < 1e-9
@test (1 .. 2) isa Particles
@test std(diff(sort((1 .. 2).particles))) < sqrt(eps())
@test pmaximum((1 .. 2)) <= 2
@test pminimum((1 .. 2)) >= 1
pp = [1. 0; 0 1] .± 0.0
@test lyap(pp,pp) == lyap([1. 0; 0 1],[1. 0; 0 1])
@test intersect(p,p) == union(p,p)
@test nparticles(intersect(p, 1+p)) < 2nparticles(p)
@test nparticles(union(p, 1+p)) == 2nparticles(p)
p = 2 ± 0
q = 3 ± 0
@test sqrt(complex(p,p)) == sqrt(complex(2,2))
@test exp(complex(p,p)) == exp(complex(2,2))
@test sqrt!(fill(complex(1.,1.), DEFAULT_NUM_PARTICLES), complex(p,p)) == sqrt(complex(2,2))
@test exp!(fill(complex(1.,1.), DEFAULT_NUM_PARTICLES), complex(p,p)) == exp(complex(2,2))
y = Particles(100)
@test exp(im*y) ≈ cos(y) + im*sin(y)
@test complex(p,p)/complex(q,q) == complex(2,2)/complex(3,3)
@test p/complex(q,q) == 2/complex(3,3)
@test Base.FastMath.div_fast(p, complex(q,q)) == Base.FastMath.div_fast(2, complex(3,3))
@test 2/complex(q,q) == 2/complex(3,3)
@test !isinf(complex(p,p))
@test isfinite(complex(p,p))
z = complex(1 ± 0.1, 1 ± 0.1)
@unsafe @test abs(sqrt(z ^ 2) - z) < eps()
@unsafe @test abs(sqrt(z ^ 2.0) - z) < eps()
@test z/z ≈ 1
z = complex(1 ± 0.1, 0 ± 0.1)
@test real(2 ^ z) ≈ 2 ^ real(z)
@test real(2.0 ^ z) ≈ 2.0 ^ real(z)
@test real(z ^ z) ≈ real(z) ^ real(z)
p = 2 ± 0.1
q = 3 ± 0.1
@test wasserstein(p,p,1) == 0
@test wasserstein(p,q,1) >= 0
@test bootstrap(p) ≈ p
rng = MersenneTwister(453)
p1 = bootstrap(rng,p)
rng = MersenneTwister(453)
p2 = bootstrap(rng,p)
@test p1 == p2
@test nparticles(bootstrap(p, 10)) == 10
@test_nowarn bootstrap([p; p])
dict = Dict(:a => p, :b => q, :c => 1)
dictvec = MonteCarloMeasurements.particle_dict2dict_vec(dict)
@test length(dictvec) == nparticles(p)
@test dictvec[1] == Dict(:a => p.particles[1], :b => q.particles[1], :c => 1)
@test dictvec[2] == Dict(:a => p.particles[2], :b => q.particles[2], :c => 1)
end
@time @testset "mutation" begin
@info "Testing mutation"
function adder!(x)
for i = eachindex(x)
x[i] += 1
end
x
end
x = (1:5) .± 1
adder!(x)
@test x ≈ ((2:6) .± 1)
end
@time @testset "outer_product" begin
@info "Testing outer product"
d = 2
μ = zeros(d)
σ = ones(d)
p = μ ⊗ σ
@test length(p) == 2
@test nparticles(p[1]) <= 100_000
@test pcov(p) ≈ I atol=1e-1
p = μ ⊗ 1
@test length(p) == 2
@test nparticles(p[1]) <= 100_000
@test pcov(p) ≈ I atol=1e-1
p = 0 ⊗ σ
@test length(p) == 2
@test nparticles(p[1]) <= 100_000
@test pcov(p) ≈ I atol=1e-1
rng = MersenneTwister(38)
p1 = outer_product(rng, Normal.(μ,σ))
rng = MersenneTwister(38)
p2 = outer_product(rng, Normal.(μ,σ))
@test p1 == p2
end
@time @testset "plotting" begin
@info "Testing plotting"
p = Particles(100)
v = randn(3) .+ Particles.(10)
M = randn(3,2) .+ [-1 1] .+ Particles.(10)
@test_nowarn Plots.plot(p)
@test_nowarn Plots.plot(v)
@test_nowarn Plots.plot(M)
@test_nowarn Plots.plot(M .+ 5) # This plot should have 4 different colored bands
@test_nowarn Plots.plot(v, ri=false)
@test_nowarn Plots.plot(v, N=0)
@test_nowarn Plots.plot(M, N=0)
@test_nowarn Plots.plot(v, N=8)
@test_nowarn Plots.plot(M, N=10)
@test_nowarn Plots.plot(x->x^2,v)
@test_nowarn Plots.plot(v,v)
@test_nowarn Plots.plot(v,v, N=10)
@test_nowarn Plots.plot(v,v; points=true)
@test_nowarn Plots.plot(v,ones(3))
@test_nowarn Plots.plot(1:3,v)
@test_nowarn Plots.plot(1:3,v, ri=false)
@test_nowarn Plots.plot(1:3, v, N=5)
@test_nowarn Plots.plot(1:3, M, N=5)
@test_nowarn Plots.plot!(1:3, M .+ 5, N=5) # This plot should have 4 different colored bands
@test_nowarn Plots.plot((1:3) .* [1 1], M, N=10)
@test_nowarn Plots.plot(1:3, M, N=5, ri=false)
@test_nowarn Plots.plot!(1:3, M .+ 5, N=5, ri=false) # This plot should have 4 different colored mclines
@test_nowarn Plots.plot(1:3, v, N=0)
@test_nowarn Plots.plot(1:3, M, N=0)
@test_nowarn Plots.plot!(1:3, M .+ 5, N=0) # This plot should have 4 different colored bands
@test_nowarn Plots.plot((1:3) .* [1 1], M, N=0)
@test_nowarn errorbarplot(1:3,v)
@test_nowarn errorbarplot(1:3,[v v])
@test_nowarn mcplot(1:3,v)
@test_nowarn mcplot(1:3,v, 10)
@test_nowarn mcplot(1:3,[v v])
@test_nowarn ribbonplot(1:3,v)
@test_nowarn ribbonplot(1:3,v,(0.1,0.9))
@test_nowarn errorbarplot(v)
@test_nowarn errorbarplot([v v])
@test_nowarn mcplot(v)
@test_nowarn mcplot(v, 10)
@test_nowarn mcplot([v v])
@test_nowarn ribbonplot(v)
@test_nowarn ribbonplot(v,(0.1,0.9))
@test_nowarn ribbonplot(v, N = 2)
@test_nowarn errorbarplot(v, 0.1)
@test_nowarn errorbarplot([v v], 0.1)
@test_nowarn mcplot(v, 0.1)
@test_nowarn ribbonplot(v, 0.1)
@test_throws ArgumentError errorbarplot(1:3, (1:3) .± 0.1, 1,1)
@test_nowarn MonteCarloMeasurements.print_functions_to_extend()
end
VERSION ≥ v"1.9" && @time @testset "Makie" begin
p1 = Particles(10^2)
Makie.hist(p1)
Makie.density(p1)
xs = 1:20
ys = Particles.(Normal.(sqrt.(1:20), sqrt.(1:20)./5))
Makie.scatter(xs, ys)
Makie.scatter(tuple.(xs, ys))
Makie.band(xs, ys)
Makie.band(tuple.(xs, ys); q=0.01)
Makie.rangebars(tuple.(xs, ys); q=0.16)
Makie.series(xs, ys)
Makie.series(tuple.(xs, ys); N=5)
end
@time @testset "optimize" begin
@info "Testing optimization"
function rosenbrock2d(x)
return (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
end
@test any(1:10) do i
p = -1ones(2) .+ 2 .*Particles.(200) # Optimum is in [1,1]
popt = optimize(rosenbrock2d, deepcopy(p))
popt ≈ [1,1]
end
p = -1ones(2) .+ 2 .*Particles.(200) # Optimum is in [1,1]
rng = MersenneTwister(876)
popt1 = optimize(rng, rosenbrock2d, deepcopy(p))
rng = MersenneTwister(876)
popt2 = optimize(rng, rosenbrock2d, deepcopy(p))
@test popt1 == popt2
end
@testset "Particle BLAS" begin
@info "Testing Particle BLAS"
p = ones(10) .∓ 1
A = randn(20,10)
@test pmean(sum(abs, A*p - MonteCarloMeasurements._pgemv(A,p))) < 1e-12
@test pmean(sum(abs, A*Particles.(p) - A*p)) < 1e-12
v = randn(10)
@test pmean(sum(abs, v'p - MonteCarloMeasurements._pdot(v,p))) < 1e-12
@test pmean(sum(abs, p'v - MonteCarloMeasurements._pdot(v,p))) < 1e-12
@test pmean(sum(abs, v'*Particles.(p) - v'p)) < 1e-12
@test pmean(sum(abs, axpy!(2.0,Matrix(p),copy(Matrix(p))) - Matrix(copy(axpy!(2.0,p,copy(p)))))) < 1e-12
@test pmean(sum(abs, axpy!(2.0,Matrix(p),copy(Matrix(p))) - Matrix(copy(axpy!(2.0,p,copy(p)))))) < 1e-12
y = randn(20) .∓ 1
@test pmean(sum(abs, mul!(y,A,p) - mul!(Particles.(y),A,Particles.(p)))) < 1e-12
for PT in (Particles, StaticParticles)
for x in (1.0, 1 + PT()), y in (1.0, 1 + PT()), z in (1.0, 1 + PT())
x == y == z == 1.0 && continue
@test (x*y+z).particles ≈ muladd(x,y,z).particles
end
end
#
# @btime $A*$p
# @btime _pgemv($A,$p)
#
# @btime sum($A*$p)
# @btime sum(_pgemv($A,$p))
#
# @btime $v'*$p
# @btime _pdot($v,$p)
#
# @btime sum($v'*$p)
# @btime sum(_pdot($v,$p))
# @btime mul!($y,$A,$p)
# @btime MonteCarloMeasurements.pmul!($y,$A,$p)
# 178.373 μs (6 allocations: 336 bytes)
# 22.320 μs (0 allocations: 0 bytes)
# 3.705 μs (0 allocations: 0 bytes)
end
@time @testset "bymap" begin
@info "Testing bymap"
p = 0 ± 1
ps = 0 ∓ 1
f(x) = 2x
f(x,y) = 2x + y
@test f(p) ≈ bymap(f,p)
@test f(p) ≈ @bymap f(p)
@test typeof(f(p)) == typeof(@bymap(f(p)))
@test typeof(f(ps)) == typeof(@bymap(f(ps)))
@test f(p,p) ≈ @bymap f(p,p)
@test f(p,10) ≈ @bymap f(p,10)
@test !(f(p,10) ≈ @bymap f(p,-10))
@test f(p) ≈ @bypmap f(p)
@test f(p,p) ≈ @bypmap f(p,p)
@test f(p,10) ≈ @bypmap f(p,10)
@test !(f(p,10) ≈ @bypmap f(p,-10))
g(x,y) = sum(x) + sum(y)
@test g([p,p], [p,p]) ≈ @bymap g([p,p], [p,p])
@test g([p,p], p) ≈ @bymap g([p,p], p)
@test g([p p], [p,p]) ≈ @bymap g([p p], [p,p])
@test g([p,p], [p,p]) ≈ @bypmap g([p,p], [p,p])
@test g([p,p], p) ≈ @bypmap g([p,p], p)
@test g([p p], [p,p]) ≈ @bypmap g([p p], [p,p])
h(x,y) = x .* y'
Base.Cartesian.@nextract 4 p d-> 0±1
@test all(h([p_1,p_2], [p_3,p_4]) .≈ bymap(h, [p_1,p_2], [p_3,p_4]))
@test all(h([p_1,p_2], [p_3,p_4]) .≈ bypmap(h, [p_1,p_2], [p_3,p_4]))
h2(x,y) = x .* y
Base.Cartesian.@nextract 4 p d-> 0±1
@test h2([p_1,p_2], [p_3,p_4]) ≈ @bymap h2([p_1,p_2], [p_3,p_4])
@test h2([p_1,p_2], [p_3,p_4]) ≈ @bypmap h2([p_1,p_2], [p_3,p_4])
g(nt::NamedTuple) = nt.x^2 + nt.y^2
@test g((x=p_1, y=p_2)) == p_1^2 + p_2^2
g2(a,nt::NamedTuple) = a + nt.x^2 + nt.y^2
@test g2(p_3, (x=p_1, y=p_2)) == p_3 + p_1^2 + p_2^2
@test_throws ErrorException bymap(x->ones(3,3,3,3), p)
@test_throws ErrorException bypmap(x->ones(3,3,3,3), p)
@test MonteCarloMeasurements.arggetter(1,1) == 1
@test MonteCarloMeasurements.particletype(p) == Particles{Float64,DEFAULT_NUM_PARTICLES}
@test MonteCarloMeasurements.particletype(Particles{Float64,DEFAULT_NUM_PARTICLES}) == Particles{Float64,DEFAULT_NUM_PARTICLES}
@test MonteCarloMeasurements.particletype([p,p]) == Particles{Float64,DEFAULT_NUM_PARTICLES}
@test nparticles(p) == DEFAULT_NUM_PARTICLES
@testset "@prob" begin
@info "Testing @prob"
p = Particles()
q = Particles()
@test mean((p).particles .< 1) == @prob p < 1
@test mean((p+2).particles .< 1) == @prob p+2 < 1
@test mean((2+p).particles .< 1) == @prob 2+p < 1
@test mean((p+p).particles .< 1) == @prob p+p < 1
@test mean((p).particles .< p.particles) == @prob p < p
@test mean((p+1).particles .< p.particles) == @prob p+1 < p
@test mean((p+q).particles .< 1) == @prob p+q < 1
@test mean((p).particles .< q.particles) == @prob p < q
@test mean((p+1).particles .< q.particles) == @prob p+1 < q
@test mean((p+q).particles .> 1) == @prob p+q > 1
@test mean((p).particles .> q.particles) == @prob p > q
@test mean((p+1).particles .> q.particles) == @prob p+1 > q
@test mean((p+q).particles .>= 1) == @prob p+q >= 1
@test mean((p).particles .>= q.particles) == @prob p >= q
@test mean((p+1).particles .>= q.particles) == @prob p+1 >= q
@test mean((abs(p)).particles .> sin(q).particles) == @prob abs(p) > sin(q)
end
end
@testset "inference" begin
@inferred zero(Particles{Float64,1})
@inferred zeros(Particles{Float64,1}, 5)
@inferred bymap(sin, 1 ± 2)
end
@testset "nominal values" begin
@info "Testing nominal values"
p = 1 ± 0.1
n = 0
pn = with_nominal(p, n)
@test nominal(pn) == pn.particles[1] == n
@test nominal(p) != n
p = [p, p]
n = [0, 1]
pn = with_nominal(p, n)
@test nominal(pn) == MonteCarloMeasurements.vecindex.(pn, 1) == n
@test nominal(p) != n
p = 1 ∓ 0.1
n = 0
pn = with_nominal(p, n)
@test nominal(pn) == pn.particles[1] == n
@test nominal(p) != n
p = [p, p]
n = [0, 1]
pn = with_nominal(p, n)
@test nominal(pn) == MonteCarloMeasurements.vecindex.(pn, 1) == n
@test nominal(p) != n
P = complex(1 ± 0.1, 2 ± 0.1)
@test nominal(P) == complex(real(P).particles[1], imag(P).particles[1])
end
include("test_unitful.jl")
include("test_forwarddiff.jl")
include("test_deconstruct.jl")
include("test_sleefpirates.jl")
include("test_measurements.jl")
end
# These can not be inside a testset, causes "testf not defined"
testf(x,y) = sum(x+y)
@test_nowarn register_primitive(testf)
p = 1 ± 0.1
@test testf(p,p) == sum(p+p)
# Integration tests and bechmarks
# using BenchmarkTools
# A = [StaticParticles(100) for i = 1:3, j = 1:3]
# B = similar(A, Float64)
# @btime qr($(copy(A)))
# @btime map(_->qr($B), 1:100);
#
# # Benchmark and comparison to Measurements.jl
# using BenchmarkTools, Printf, ControlSystems
# using MonteCarloMeasurements, Measurements
# using Measurements: ±
# using MonteCarloMeasurements: ∓
# w = exp10.(LinRange(-0.7,0.3,50))
#
# p = 1 ± 0.1
# ζ = 0.3 ± 0.1
# ω = 1 ± 0.1
# Gm = tf([p*ω], [1, 2ζ*ω, ω^2])
# # tm = @belapsed bode($Gm,$w)
#
# p = 1 ∓ 0.1
# ζ = 0.3 ∓ 0.1
# ω = 1 ∓ 0.1
# Gmm = tf([p*ω], [1, 2ζ*ω, ω^2])
# # tmm = @belapsed bode($Gmm,$w)
#
# σquant = 1-(cdf(Normal(0,1), 1)-cdf(Normal(0,1), -1))
#
# magm = bode(Gm,w)[1][:]
# magmm = bode(Gmm,w)[1][:]
# errorbarplot(w,magmm, σquant/2, xscale=:log10, yscale=:log10, lab="Particles", linewidth=2)
# plot!(w,magm, lab="Measurements")
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | code | 5022 | using MonteCarloMeasurements
using Test, LinearAlgebra, Statistics, Random
import MonteCarloMeasurements: ±, ∓
using MonteCarloMeasurements: nakedtypeof, build_container, build_mutable_container, has_particles, particle_paths
using ControlSystemsBase, Test, GenericSchur
ControlSystemsBase.TransferFunction(matrix::Array{<:ControlSystemsBase.SisoRational,2}, Ts, ::Int64, ::Int64) = TransferFunction(matrix,Ts)
Continuous = ControlSystemsBase.Continuous
@testset "deconstruct" begin
@info "Testing deconstruct"
unsafe_comparisons()
N = 50
P = ss(tf(1 +0.1StaticParticles(N), [1, 1+0.1StaticParticles(N)]))
f = x->c2d(x,0.1)
w = Workspace(f,P)
@time Pd = w(P)
@test !MonteCarloMeasurements.has_mutable_particles(Pd)
@test MonteCarloMeasurements.has_mutable_particles(MonteCarloMeasurements.build_mutable_container(Pd))
# See benchmarks below
# @profiler Workspace(P)
tt = function (P)
f = x->c2d(x,0.1)
w = Workspace(f,P)
@time Pd = w(P)
end
@test_throws MethodError tt(P) # This causes a world-age problem. If this tests suddenly break, it would be nice and we can get rid of the intermediate workspace object.
tt = function (P)
f = x->c2d(x,0.1)
w = Workspace(f,P)
@time Pd = w(P,true)
end
@test tt(P) == Pd == with_workspace(f,P)
p = 1 ± 0.1
@test mean_object(p) == pmean(p)
@test mean_object([p,p]) == pmean.([p,p])
@test mean_object(P) ≈ ss(tf(tf(1,[1,1]))) atol=1e-2
@test nakedtypeof(P) == StateSpace
@test nakedtypeof(typeof(P)) == StateSpace
P2 = build_container(P)
@test typeof(P2) == StateSpace{Continuous, Float64}
@test typeof(build_mutable_container(P)) == StateSpace{Continuous, Particles{Float64, N}}
@test has_particles(P)
@test has_particles(P.A)
# P = tf(1 ± 0.1, [1, 1±0.1])
# @benchmark foreach(i->c2d($(tf(1.,[1., 1])),0.1), 1:N) # 1.7 ms 1.2 Mb
bP = bode(P, exp10.(LinRange(-3, log10(10π), 50)))[1] |> vec
bPd = bode(Pd, exp10.(LinRange(-3, log10(10π), 50)))[1] |> vec
@test mean(abs2, pmean.(bP) - pmean.(bPd)) < 1e-4
A = randn(2,2)
Ap = A .± 0.1
hfun = A->Matrix(hessenberg(A))
@test all(ℝⁿ2ℝⁿ_function(hfun, Ap) .≈ Matrix(hessenberg(A)))
Ap = A .+ 0.1 .* StaticParticles(1)
@test_nowarn hessenberg(Ap)
# bodeplot(P, exp10.(LinRange(-3, log10(10π), 50)))
# bodeplot!(Pd, exp10.(LinRange(-3, log10(10π), 50)), linecolor=:blue)
let paths = particle_paths(P), P2 = build_container(P), buffersetter = MonteCarloMeasurements.get_buffer_setter(paths)
Pres = @unsafe build_mutable_container(f(P)) # Auto-created result buffer
resultsetter = MonteCarloMeasurements.get_result_setter(Pres)
@test all(1:paths[1][3]) do i
buffersetter(P,P2,i)
P.A[1].particles[i] == P2.A[1] && P.A[1].particles[i] == P2.A[1]
P2res = f(P2)
resultsetter(Pres, P2res, i)
Pres.A[1].particles[i] == P2res.A[1] && Pres.A[1].particles[i] == P2res.A[1]
end
end
@test mean_object(complex(1. ± 0.1, 1.)) isa ComplexF64
@test mean_object(complex(1. ± 0.1, 1.)) ≈ complex(1,1) atol=1e-3
Ps = MonteCarloMeasurements.make_scalar(P)
@test MonteCarloMeasurements.particletypetuple(Ps.A[1]) == (Float64,1,Particles)
@test MonteCarloMeasurements.particletypetuple(MonteCarloMeasurements.restore_scalar(Ps,50).A[1]) == (Float64,50,Particles)
unsafe_comparisons(false)
N = 50
P = ss(tf(1 +0.1StaticParticles(N), [1, 1+0.1StaticParticles(N)]))
f = x->c2d(x,0.1)
res = MonteCarloMeasurements.array_of_structs(f, P)
@test length(res) == N
@test res isa Vector{<:StateSpace}
end
# julia> @benchmark Pd = w(f) # different world age
# BenchmarkTools.Trial:
# memory estimate: 1.63 MiB
# allocs estimate: 19178
# --------------
# minimum time: 2.101 ms (0.00% GC)
# median time: 2.199 ms (0.00% GC)
# mean time: 2.530 ms (10.36% GC)
# maximum time: 7.969 ms (53.42% GC)
# --------------
# samples: 1973
# evals/sample: 1
# julia> @benchmark Pd = w(f) # invokelatest
# BenchmarkTools.Trial:
# memory estimate: 1.64 MiB
# allocs estimate: 19378
# --------------
# minimum time: 2.204 ms (0.00% GC)
# median time: 2.742 ms (0.00% GC)
# mean time: 3.491 ms (13.77% GC)
# maximum time: 17.103 ms (80.96% GC)
# --------------
# samples: 1429
# evals/sample: 1
#
# julia> @benchmark with_workspace($f,$P) # It seems the majority of the time is spent building the workspace object, so invokelatest really isn't that expensive.
# BenchmarkTools.Trial:
# memory estimate: 7.90 MiB
# allocs estimate: 148678
# --------------
# minimum time: 158.073 ms (0.00% GC)
# median time: 165.134 ms (0.00% GC)
# mean time: 165.842 ms (1.75% GC)
# maximum time: 180.133 ms (4.80% GC)
# --------------
# samples: 31
# evals/sample: 1
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | code | 2321 | using MonteCarloMeasurements, ForwardDiff, Test
const FD = ForwardDiff
@testset "forwarddiff" begin
@info "Testing ForwardDiff"
c = 1 + 0.1Particles(500) # These are the uncertain parameters
d = 1 + 0.1Particles(500) # These are the uncertain parameters
# In the cost function below, we ensure that $cx+dy > 10 \; ∀ \; c,d ∈ P$ by looking at the worst case
function cost(params)
x,y = params
-(3x+2y) + 10000sum(params .< 0) + 10000*(pmaximum(c*x+d*y) > 10)
end
params = [1., 2] # Initial guess
paramsp = [1., 2] .+ 0.001 .* Particles(500) # Initial guess
@test cost(params) == -7 # Try the cost function
@test FD.gradient(cost, params) == @unsafe FD.gradient(cost, paramsp)
@test FD.gradient(sum, params) == FD.gradient(sum, paramsp)
@test all(FD.gradient(prod, params) .≈ FD.gradient(prod, paramsp))
unsafe_comparisons(false)
@test FD.gradient(x -> params'x, params) == params
@test FD.gradient(x -> paramsp'x, params) == paramsp
@test FD.gradient(x -> params'x, paramsp) == params
r = FD.gradient(x -> paramsp'x, paramsp)
@test pmean(pmean(r[1])) ≈ params[1] atol=1e-2
@test pmean(pmean(r[2])) ≈ params[2] atol=1e-2
@test FD.jacobian(x -> params+x, params) == I
@test FD.jacobian(x -> paramsp+x, params) == I
@test FD.jacobian(x -> params+x, paramsp) == I
@test FD.jacobian(x -> params-x, params) == -I
@test FD.jacobian(x -> paramsp-x, params) == -I
@test FD.jacobian(x -> params-x, paramsp) == -I
@test FD.jacobian(x -> x-params, params) == I
@test FD.jacobian(x -> x-paramsp, params) == I
@test FD.jacobian(x -> x-params, paramsp) == I
function strange(x,y)
(x.^2)'*(y.^2)
end
ref = FD.gradient(x->strange(x,params), params)
@test FD.gradient(x->strange(x,params), paramsp) != ref
@test FD.gradient(x->strange(x,params), paramsp) ≈ ref
@test FD.gradient(x->strange(x,paramsp), params) != ref
@test FD.gradient(x->strange(x,paramsp), params) ≈ ref
r = FD.gradient(x->strange(x,paramsp), paramsp) # maybe this is a bit overkill
@test pmean(pmean(r[1])) ≈ ref[1] atol=1e-2
@test pmean(pmean(r[2])) ≈ ref[2] atol=1e-2
@test pmean(pmean(r[1])) != ref[1]
@test pmean(pmean(r[2])) != ref[2]
unsafe_comparisons(false)
end
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | code | 931 |
@testset "Measurements" begin
@info "Testing Measurements"
import Measurements
m = Measurements.measurement(1,2)
@test Particles(m) isa Particles{Float64, MonteCarloMeasurements.DEFAULT_NUM_PARTICLES}
@test StaticParticles(m) isa StaticParticles{Float64, MonteCarloMeasurements.DEFAULT_STATIC_NUM_PARTICLES}
@test Particles(10, m) isa Particles{Float64, 10}
@test StaticParticles(10, m) isa StaticParticles{Float64, 10}
@test Particles.([m, m]) isa Vector{Particles{Float64, MonteCarloMeasurements.DEFAULT_NUM_PARTICLES}}
@test StaticParticles.([m, m]) isa Vector{StaticParticles{Float64, MonteCarloMeasurements.DEFAULT_STATIC_NUM_PARTICLES}}
@test Particles(m) ≈ 1 ± 2
@test pstd(Particles(m)) ≈ 2 atol=1e-3
@test pmean(Particles(m)) ≈ 1 atol=1e-3
@test Measurements.uncertainty(Particles(m)) ≈ 2 atol=1e-3
@test Measurements.value(Particles(m)) ≈ 1 atol=1e-3
end
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | code | 801 | @testset "SLEEFPirates" begin
@info "Testing SLEEFPirates"
using SLEEFPirates
a = rand(100)
@test map(exp, a) ≈ exp(Particles(a)).particles
@test map(log, a) ≈ log(Particles(a)).particles
@test map(cos, a) ≈ cos(Particles(a)).particles
@test map(exp, a) ≈ exp(StaticParticles(a)).particles
@test map(log, a) ≈ log(StaticParticles(a)).particles
@test map(cos, a) ≈ cos(StaticParticles(a)).particles
a = rand(Float32, 100)
@test map(exp, a) ≈ exp(Particles(a)).particles
@test map(log, a) ≈ log(Particles(a)).particles
@test map(cos, a) ≈ cos(Particles(a)).particles
@test map(exp, a) ≈ exp(StaticParticles(a)).particles
@test map(log, a) ≈ log(StaticParticles(a)).particles
@test map(cos, a) ≈ cos(StaticParticles(a)).particles
end
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | code | 2057 | using Unitful
function unitful_testfunction(Vi)
if Vi ≤ 0.0u"V"
return 0.0u"V"
elseif Vi ≥ 1.0u"V"
return 1.0u"V"
else
return Vi
end
end
register_primitive(unitful_testfunction) # must be outside testset
@testset "Unitful" begin
@info "Testing Unitful"
PT = Particles
for PT in (Particles, StaticParticles)
p1 = PT(100, Uniform(-0.5,1.5)) * 1u"V"
p2 = PT(100, Uniform(-0.5,1.5)) * u"V"
@test_nowarn println(p1)
@test_nowarn display(p1)
@test_nowarn println(0p1)
@test_nowarn display(0p1)
@test typeof(p1) == typeof(p2)
p3 = unitful_testfunction(p1)
@test pextrema(p3) == (0.0u"V", 1.0u"V")
@test (1 ± 0.5)u"m" * (1 ± 0)u"kg" ≈ (1 ± 0.5)u"kg*m"
@test (1 ± 0.5)u"m" * 1u"kg" ≈ (1 ± 0.5)u"kg*m"
@test (1 ± 0.5)u"m" / (1 ± 0)u"kg" ≈ (1 ± 0.5)u"m/kg"
@test (1 ± 0.5)u"m" / 1u"kg" ≈ (1 ± 0.5)u"m/kg"
@test (1 ± 0.5)u"m" + (1 ± 0)u"m" ≈ (2 ± 0.5)u"m"
@test (1 ± 0.5)u"m" + 1u"m" ≈ (2 ± 0.5)u"m"
@test 1u"m" * (1 ± 0.5)u"kg" ≈ (1 ± 0.5)u"kg*m"
@test 1u"m" / (1 ± 0.5)u"kg" ≈ (1 ± 0.5)u"m/kg"
@test 1u"m" + (1 ± 0.5)u"m" ≈ (2 ± 0.5)u"m"
typeof(promote(1u"V", (1.0 ± 0.1)u"V")) <: Tuple{Particles{<:Quantity}, Particles{<:Quantity}}
@test muladd(p1, 1, p1) == p1 + p1
@test muladd(p1, 1, p2) == p1 + p2
@test muladd(1, p1, p2) == p1 + p2
@test muladd(p1, 1/p1, 1) == 2
ρ = (2.7 ± 0.2)u"g/cm^3"
mass = (250 ± 10)u"g"
width = (30.5 ± 0.2)u"cm"
l = (14.24 ± 0.2)u"m"
thickness = u"μm"(mass/(ρ*width*l))
@test thickness ≈ (21.3 ± 1.8)u"μm"
@test ustrip(mass) ≈ 250 ± 10
@test ustrip(mass) isa Particles
a = (200 + 20*PT())u"ms"
@test unit(a) == unit(1u"ms")
b = ustrip(a)
c = uconvert(u"s", a)
@test c ≈ (0.200 + 0.020*PT())u"s"
d1 = upreferred(a)
@test d1 ≈ (0.200 + 0.020*PT())u"s"
end
end
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | docs | 5777 | 
[](https://github.com/baggepinnen/MonteCarloMeasurements.jl/actions)
[](https://codecov.io/gh/baggepinnen/MonteCarloMeasurements.jl)
[](https://baggepinnen.github.io/MonteCarloMeasurements.jl/stable)
[](https://baggepinnen.github.io/MonteCarloMeasurements.jl/latest)
[](https://arxiv.org/abs/2001.07625)
*Imagine you had a type that behaved like your standard `Float64` but it really represented a probability distribution like `Gamma(0.5)` or `MvNormal(m, S)`. Then you could call `y=f(x)` and have `y` be the probability distribution `y=p(f(x))`. This package gives you such a type.*
This package facilitates working with probability distributions by means of Monte-Carlo methods, in a way that allows for propagation of probability distributions through functions. This is useful for, e.g., nonlinear [uncertainty propagation](https://en.wikipedia.org/wiki/Propagation_of_uncertainty). A variable or parameter might be associated with uncertainty if it is measured or otherwise estimated from data. We provide two core types to represent probability distributions: `Particles` and `StaticParticles`, both `<: Real`. (The name "Particles" comes from the [particle-filtering](https://en.wikipedia.org/wiki/Particle_filter) literature.) These types all form a Monte-Carlo approximation of the distribution of a floating point number, i.e., the distribution is represented by samples/particles. **Correlated quantities** are handled as well, see [multivariate particles](https://baggepinnen.github.io/MonteCarloMeasurements.jl/stable/#Multivariate-particles-1) below.
Although several interesting use cases for doing calculations with probability distributions have popped up (see [Examples](https://baggepinnen.github.io/MonteCarloMeasurements.jl/stable/examples)), the original goal of the package is similar to that of [Measurements.jl](https://github.com/JuliaPhysics/Measurements.jl), to propagate the uncertainty from input of a function to the output. The difference compared to a `Measurement` is that `Particles` represent the distribution using a vector of unweighted particles, and can thus represent arbitrary distributions and handle nonlinear uncertainty propagation well. Functions like `f(x) = x²`, `f(x) = sign(x)` at `x=0` and long-time integration, are examples that are not handled well using linear uncertainty propagation ala [Measurements.jl](https://github.com/JuliaPhysics/Measurements.jl). MonteCarloMeasurements also support correlations between quantities.
A number of type `Particles` behaves just as any other `Number` while partaking in calculations. Particles also behave like a distribution, so after a calculation, an approximation to the **complete distribution** of the output is captured and represented by the output particles. `mean`, `std` etc. can be extracted from the particles using the corresponding functions `pmean` and `pstd`. `Particles` also interact with [Distributions.jl](https://github.com/JuliaStats/Distributions.jl), so that you can call, e.g., `Normal(p)` and get back a `Normal` type from distributions or `fit(Gamma, p)` to get a `Gamma`distribution. Particles can also be asked for `maximum/minimum`, `quantile` etc. using functions with a prefix `p`, i.e., `pmaximum`. If particles are plotted with `plot(p)`, a histogram is displayed. This requires Plots.jl. A kernel-density estimate can be obtained by `density(p)` is StatsPlots.jl is loaded.
Below, we show an example where an input uncertainty is propagated through `σ(x)`

In the figure above, we see the probability-density function of the input `p(x)` depicted on the x-axis. The density of the output `p(y) = f(x)` is shown on the y-axis. Linear uncertainty propagation does this by linearizing `f(x)` and using the equations for an affine transformation of a Gaussian distribution, and hence produces a Gaussian approximation to the output density. The particles form a sampled approximation of the input density `p(x)`. After propagating them through `f(x)`, they form a sampled approximation to `p(y)` which correspond very well to the true output density, even though only 20 particles were used in this example. The figure can be reproduced by `examples/transformed_densities.jl`.
## Quick start
```julia
using MonteCarloMeasurements, Plots
a = π ± 0.1 # Construct Gaussian uncertain parameters using ± (\\pm)
# Particles{Float64,2000}
# 3.14159 ± 0.1
b = 2 ∓ 0.1 # ∓ (\\mp) creates StaticParticles (with StaticArrays)
# StaticParticles{Float64,100}
# 2.0 ± 0.0999
pstd(a) # Ask about statistical properties
# 0.09999231528930486
sin(a) # Use them like any real number
# Particles{Float64,2000}
# 1.2168e-16 ± 0.0995
plot(a) # Plot them
b = sin.(1:0.1:5) .± 0.1; # Create multivariate uncertain numbers
plot(b) # Vectors of particles can be plotted
using Distributions
c = Particles(500, Poisson(3.)) # Create uncertain numbers distributed according to a given distribution
# Particles{Int64,500}
# 2.882 ± 1.7
```
For further help, see the [documentation](https://baggepinnen.github.io/MonteCarloMeasurements.jl/stable), the [examples folder](https://github.com/baggepinnen/MonteCarloMeasurements.jl/tree/master/examples) or the [arXiv paper](https://arxiv.org/abs/2001.07625).
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | docs | 552 | # Advanced usage
Several non-exported functions that may facilitate working with structures that contain uncertain parameters (struct-of-arrays, SoA) exist. These are not to be considered part of the API and are subject to breakage at any time, but may nevertheless be of use in special situations.
```@docs
MonteCarloMeasurements.mean_object
MonteCarloMeasurements.replace_particles
MonteCarloMeasurements.has_particles
MonteCarloMeasurements.build_mutable_container
MonteCarloMeasurements.build_container
MonteCarloMeasurements.array_of_structs
```
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | docs | 262 | # Exported functions and types
## Index
```@index
```
```@autodocs
Modules = [MonteCarloMeasurements]
Private = false
```
```@docs
Base.:(≈)(p::AbstractParticles, a::AbstractParticles)
MonteCarloMeasurements.:(≉)(a::AbstractParticles, b::AbstractParticles)
```
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | docs | 5045 |
# Comparison between linear uncertainty propagation and Monte-Carlo sampling
This page will highlight some situations in which linear uncertainty propagation breaks down by showing the input density along the x-axis and the various approximations to the output density on the y-axis. The figures will be similar to the one below, but we'll leave out some of the guiding lines and particles for clarity

All examples will use Gaussian input densities since linear uncertainty propagation is only applicable in this case.
We start by defining a function that plots everything for us
```@example comparison
using MonteCarloMeasurements, Measurements, Plots, Distributions
using Measurements: value, uncertainty
function plot_dens(f, d, l, r, N=10_000; kwargs...)
xr = LinRange(l,r,100) # x values for plotting
yr = f.(xr)
# Estimate the output density corresponding to the particles
x = Particles(N,d) # Create particles distributed according to d, sort for visualization
yp = f(x)
y = yp.particles # corresponding output particles
edges1, edges2 = Plots._hist_edges((xr,y), 30)
histogram(fill(l, length(y)), y , bins=edges2, orientation=:h, alpha=0.4, normalize=true, lab="Particle density")
fig = plot!(xr.-l, yr, legend=:right, xlims=(0,r-l), axis=false, grid=false, lab="f(x)", xlabel="Input space", ylabel="Output space", l=(3,:blue))
idens = pdf.(d,xr)
idens .*= maximum(yr)/maximum(idens)
plot!(xr.-l,idens; lab="Input dens.", l=(:orange, ), kwargs...)
# This is the output density as approximated by linear uncertainty propagation
my = f(Measurements.:±(mean(d), std(d))) # output measurement
if uncertainty(my) == 0 # Draw a stick
plot!([0,0+(r-l)/3], [value(my),value(my)], m=(:o,), lab="Linear Gaussian propagation")
else
yxr = LinRange(value(my)-2.5uncertainty(my),value(my)+2.5uncertainty(my),100)
dm = Normal(value(my), uncertainty(my)) # Output density according to Measurements
ym = pdf.(dm,yxr)
ym .*= 0+(r-l)/3/maximum(ym)
plot!(0 .+ ym, yxr, lab="Linear Gaussian propagation")
end
fig
end
```
The first example we'll look at is the quadratic parabola. This function will be poorly approximated by a linear function around $x=0$.
```@example comparison
plot_dens(x->x^2+3, Normal(0,1), -3, 3, legend=:top)
savefig("parabola.html"); nothing # hide
```
```@raw html
<object type="text/html" data="../parabola.html" style="width:100%;height:450px;"></object>
```
as we can see, the linear method outputs a Dirac distribution (no uncertainty) at $x=0$, while there should clearly be a lot of uncertainty in the output. The histogram displays the output density as approximated by the particles. The histogram does not go below zero, and tapers off as values increase. The problem here is that the uncertainty is large in relation to the curvature of the function. As the uncertainty decreases, the true output density becomes closer and closer to a DIrac distribution.
The next function has a discontinuity (≈ infinite curvature)
```@example comparison
plot_dens(x->sign(x)+1, Normal(0.5,1), -3, 3, legend=:bottomright)
savefig("sign.html"); nothing # hide
```
```@raw html
<object type="text/html" data="../sign.html" style="width:100%;height:450px;"></object>
```
once again, linear uncertainty propagation outputs a distribution with zero uncertainty. The true output distribution has two modes since the input distribution places mass on both sides of the discontinuity. This is captured in the particle distribution, where most particles end up at the right side of the discontinuity, while a smaller proportion of the particles end up to the left. If the input density would have its mean at 0, half of the particles would end up in each of the output locations. Any function containing an if-statement where the chosen branch depends on an uncertain value falls into this category.
Next, we consider a periodic function
```@example comparison
plot_dens(x->sin(x)+2, Normal(0.5,1), -3, 3, legend=:topright)
savefig("sin.html"); nothing # hide
```
```@raw html
<object type="text/html" data="../sin.html" style="width:100%;height:450px;"></object>
```
Once again, the uncertainty is large in relation to the curvature of the function and linear uncertainty propagation places significant mass outside the interval $[-1, 1]$ which is the range of the $\sin$ function. The particle histogram respects this range. If we increase the uncertainty in the input further, the linear approximation to the function becomes increasingly worse
```@example comparison
plot_dens(x->sin(x)+2, Normal(0.5,5), -15, 15, legend=:topright)
savefig("sin_wide.html"); nothing # hide
```
```@raw html
<object type="text/html" data="../sin_wide.html" style="width:100%;height:450px;"></object>
```
## Pendulum simulation
The example [Differential Equations](@ref) shows how linear/Monte-Carlo uncertainty propagation through a nonlinear ODE works. | MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | docs | 12069 | # Examples
## [Control systems](https://github.com/baggepinnen/MonteCarloMeasurements.jl/blob/master/examples/controlsystems.jl)
This example shows how to simulate control systems (using [ControlSystems.jl](https://github.com/JuliaControl/ControlSystems.jl)) with uncertain parameters. We calculate and display Bode diagrams, Nyquist diagrams and time-domain responses. We also illustrate how the package [ControlSystemIdentification.jl](https://github.com/baggepinnen/ControlSystemIdentification.jl) interacts with MonteCarloMeasurements to facilitate the creation and analysis of uncertain systems.
We also perform some limited benchmarks.
The package [RobustAndOptimalControl.jl](https://juliacontrol.github.io/RobustAndOptimalControl.jl/dev/) contains lots of additional tools to work with linear systems with uncertainty represented as `Particles`. See the documentation on [Uncertainty modeling](https://juliacontrol.github.io/RobustAndOptimalControl.jl/dev/uncertainty/) for several examples.
## [Latin Hypercube Sampling](https://github.com/baggepinnen/MonteCarloMeasurements.jl/blob/master/examples/lhs.jl)
We show how to initialize particles with LHS and how to make sure the sample gets the desired moments. We also visualize the statistics of the sample.
## [How MC uncertainty propagation works](https://github.com/baggepinnen/MonteCarloMeasurements.jl/blob/master/examples/transformed_densities.jl)
We produce the first figure in this readme and explain in visual detail how different forms of uncertainty propagation propagates a probability distribution through a nonlinear function. Also see [Comparison between linear uncertainty propagation and Monte-Carlo sampling](@ref) for more visual examples.
## [Robust probabilistic optimization](https://github.com/baggepinnen/MonteCarloMeasurements.jl/blob/master/examples/robust_controller_opt.jl)
Here, we use MonteCarloMeasurements to perform [robust optimization](https://en.wikipedia.org/wiki/Robust_optimization). With robust and probabilistic, we mean that we place some kind of bound on a quantile of an uncertain value, or otherwise make use of the probability distribution of some value that depend on the optimized parameters.
The application we consider is optimization of a PID controller. Normally, we are interested in controller performance and robustness against uncertainty. The robustness is often introduced by placing an upper bound on the, so called, sensitivity function. When the system to be controlled is parameterized by `Particles`, we can penalize both variance in the performance measure as well as the 90:th quantile of the maximum of the sensitivity function. This example illustrates how easy it is to incorporate probabilistic constrains or cost functions in an optimization problem using `Particles`.
## [Autodiff and Robust optimization](https://github.com/baggepinnen/MonteCarloMeasurements.jl/blob/master/examples/autodiff_robust_opt.jl)
Another example using MonteCarloMeasurements to perform [robust optimization](https://en.wikipedia.org/wiki/Robust_optimization), this time with automatic differentiation. We use Optim.jl to solve a linear program with probabilistic constraints using 4 different methods, two gradient free, one first-order and one second-order method. We demonstrate calculation of gradients of uncertain functions with uncertain inputs using both Zygote.jl and ForwardDiff.jl.
## Unitful interaction
Particles with units can be created using the package [Unitful.jl](https://github.com/PainterQubits/Unitful.jl) for uncertainty propagation with automatic unit checks. The interaction is only supported through the construct `Particles{Quantity}`, whereas the reverse construct `Quantity{Particles}` is likely to result in problems. Unitful particles are thus created like this
```@repl
using MonteCarloMeasurements, Unitful
(1 ± 0.1)u"V"
(1..2)u"m"
```
### Example: Solar collector energy transfer
The following example estimates the amount of thermal power transferred from a solar collector embedded in a concrete floor, to a water reservoir. The power is computed by measuring the temperature difference, $\Delta T$, between the solar collectors circulating warm water going into the collector tank and the colder returning water. Using the mass-flow rate and the specific heat capacity of water, we can estimate the power transfer. No flow meter is installed, so the flow is estimated and subject to large uncertainty.
```@example solar
using MonteCarloMeasurements
using Unitful
using Unitful: W, kW, m, mm, hr, K, g, J, l, s
ΔT = (3.5 ± 0.8)K # The temperature difference varies slightly between different flow circuits.
specific_heat_water = 4.19J/(g*K)
density_water = 1e6g/m^3
flow = 8*(1..2.5)*l/(60s) # 8 solar collector circuits, each with an estimated flow rate of between 1 and 2.5 l/minute
mass_flow = flow * density_water |> upreferred # Water flow in mass per second
power = uconvert(W, mass_flow * specific_heat_water * ΔT) # Power in Watts
```
Some power is lost to the ground in which the heat-exchanger circuits are embedded, we estimate this to be between 10 and 50% of the total power.
```@example solar
ground_losses = (0.1..0.5) * power # Between 10-50% power loss to ground
reservoir_volume = 7m*3m*1.5m
```
The energy transfered during 6hrs solar collection can be estimated as
```@example solar
energy_6_hrs = (power - ground_losses)*6hr
```
and this energy transfer will increase the temperature in the reservoir by
```@example solar
ΔT_reservoir_6hr = energy_6_hrs/(reservoir_volume*density_water*specific_heat_water) |> upreferred
```
Finally, we visualize the distributions associated with the estimated quantities:
```@example solar
using Plots
figh = plot(ΔT_reservoir_6hr, xlabel="\$ΔT [K]\$", ylabel="\$P(ΔT)\$", title="Temperature increase 6hrs sun")
qs = 0:0.01:1
Qs = pquantile.(ΔT_reservoir_6hr, qs)
figq = plot(qs, Qs, xlabel="∫\$P(ΔT)\$")
plot(figh, figq)
```
## Monte-Carlo sampling properties
The variance introduced by Monte-Carlo sampling has some fortunate and some unfortunate properties. It decreases as 1/N, where N is the number of particles/samples. This unfortunately means that to get half the standard deviation in your estimate, you need to quadruple the number of particles. On the other hand, this variance does not depend on the dimension of the space, which is very fortunate.
In this package, we perform [*systematic sampling*](https://arxiv.org/pdf/cs/0507025.pdf) whenever possible. This approach exhibits lower variance than standard random sampling. Below, we investigate the variance of the mean estimator of a random sample from the normal distribution. The variance of the estimate of the mean is known to decrease as 1/N
```julia
default(l=(3,))
N = 1000
svec = round.(Int, exp10.(LinRange(1, 3, 50)))
vars = map(svec) do i
var(mean(randn(i)) for _ in 1:1000)
end
plot(svec, vars, yscale=:log10, xscale=:log10, lab="Random sampling", xlabel="\$N\$", ylabel="Variance")
plot!(svec, N->1/N, lab="\$1/N\$", l=(:dash,))
vars = map(svec) do i
var(mean(systematic_sample(i)) for _ in 1:1000)
end
plot!(svec, vars, lab="Systematic sampling")
plot!(svec, N->1/N^2, lab="\$1/N^2\$", l=(:dash,))
```

As we can see, the variance of the standard random sampling decreases as expected. We also see that the variance for the systematic sample is considerably lower, and also scales as (almost) 1/N².
A simplified implementation of the systematic sampler is given below
```julia
function systematic_sample(N, d=Normal(0,1))
e = rand()/N
y = e:1/N:1
map(x->quantile(d,x), y)
end
```
~~As we can see, a single random number is generated to seed the entire sample.~~ (This has been changed to `e=0.5/N` to have a correct mean.) The samples are then drawn deterministically from the quantile function of the distribution.
## Variational inference
See [blog post](https://cscherrer.github.io/post/variational-importance-sampling/) by [@cscherrer](https://github.com/cscherrer) for an example of variational inference using `Particles`
## Differential Equations
[The tutorial](http://tutorials.juliadiffeq.org/html/type_handling/02-uncertainties.html) for solving differential equations using `Measurement` works for `Particles` as well. A word of caution for actually using Measurements.jl in this example: while solving the pendulum on short time scales, linear uncertainty propagation works well, as evidenced by the below simulation of a pendulum with uncertain properties
```julia
function sim(±, tspan, plotfun=plot!; kwargs...)
g = 9.79 ± 0.02; # Gravitational constant
L = 1.00 ± 0.01; # Length of the pendulum
u₀ = [0 ± 0, π / 3 ± 0.02] # Initial speed and initial angle
#Define the problem
function simplependulum(du,u,p,t)
θ = u[1]
dθ = u[2]
du[1] = dθ
du[2] = -(g/L) * sin(θ)
end
prob = ODEProblem(simplependulum, u₀, tspan)
sol = solve(prob, Tsit5(), reltol = 1e-6)
plotfun(sol.t, getindex.(sol.u, 2); kwargs...)
end
tspan = (0.0, 5)
plot()
sim(Measurements.:±, tspan, label = "Linear", xlims=(tspan[2]-5,tspan[2]))
sim(MonteCarloMeasurements.:±, tspan, label = "MonteCarlo", xlims=(tspan[2]-5,tspan[2]))
```

The mean and errorbars for both Measurements and MonteCarloMeasurements line up perfectly when integrating over 5 seconds.
However, the uncertainty in the pendulum coefficients implies that the frequency of the pendulum oscillation is uncertain, when solving on longer time scales, this should result in the phase being completely unknown, something linear uncertainty propagation does not handle
```julia
tspan = (0.0, 200)
plot()
sim(Measurements.:±, tspan, label = "Linear", xlims=(tspan[2]-5,tspan[2]))
sim(MonteCarloMeasurements.:±, tspan, label = "MonteCarlo", xlims=(tspan[2]-5,tspan[2]))
```

We now integrated over 200 seconds and look at the last 5 seconds. This result maybe looks a bit confusing, the linear uncertainty propagation is very sure about the amplitude at certain points but not at others, whereas the Monte-Carlo approach is completely unsure. Furthermore, the linear approach thinks that the amplitude at some points is actually much higher than the starting amplitude, implying that energy somehow has been added to the system! The picture might become a bit more clear by plotting the individual trajectories of the particles
```julia
plot()
sim(Measurements.:±, tspan, label = "Linear", xlims=(tspan[2]-5,tspan[2]), l=(5,))
sim(MonteCarloMeasurements.:∓, tspan, mcplot!, label = "", xlims=(tspan[2]-5,tspan[2]), l=(:black,0.1))
```

It now becomes clear that each trajectory has a constant amplitude (although individual trajectories amplitudes vary slightly due to the uncertainty in the initial angle), but the phase is all mixed up due to the slightly different frequencies!
These problems grow with increasing uncertainty and increasing integration time. In fact, the uncertainty reported by Measurements.jl goes to infinity as the integration time does the same.
Of course, the added accuracy from using MonteCarloMeasurements does not come for free, as it costs some additional computation. We have the following timings for integrating the above system 100 seconds using three different uncertainty representations
```julia
Measurements.:± 14.596 ms (729431 allocations: 32.43 MiB) # Measurements.Measurement
MonteCarloMeasurements.:∓ 25.115 ms (25788 allocations: 24.68 MiB) # 100 StaticParticles
MonteCarloMeasurements.:± 345.730 ms (696212 allocations: 838.50 MiB) # 500 Particles
```
# MCMC inference using Turing.jl
[Turing.jl](https://github.com/TuringLang/Turing.jl/) is a probabilistic programming language, and an interface between Turing and MonteCarloMeasurements is provided by
[Turing2MonteCarloMeasurements.jl](https://github.com/baggepinnen/Turing2MonteCarloMeasurements.jl) with instructions and examples in the readme.
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | docs | 25591 |

[](https://github.com/baggepinnen/MonteCarloMeasurements.jl/actions)
[](https://codecov.io/gh/baggepinnen/MonteCarloMeasurements.jl)
[](https://arxiv.org/abs/2001.07625)
# MonteCarloMeasurements
> Imagine you had a type that behaved like your standard `Float64` but it really represented a probability distribution like `Gamma(0.5)` or `MvNormal(m, S)`. Then you could call `y=f(x)` and have `y` be the probability distribution `y=p(f(x))`. This package gives you such a type.
This package facilitates working with probability distributions as if they were regular real numbers, by means of Monte-Carlo methods, in a way that allows for propagation of probability distributions through functions. This is useful for, e.g., nonlinear and possibly non-Gaussian [uncertainty propagation](https://en.wikipedia.org/wiki/Propagation_of_uncertainty). A variable or parameter might be associated with uncertainty if it is measured or otherwise estimated from data. We provide two core types to represent probability distributions: `Particles` and `StaticParticles`, both `<: Real`. (The name "Particles" comes from the [particle-filtering](https://en.wikipedia.org/wiki/Particle_filter) literature.) These types all form a Monte-Carlo approximation of the distribution of a floating point number, i.e., the distribution is represented by samples/particles. **Correlated quantities** are handled as well, see [multivariate particles](https://github.com/baggepinnen/MonteCarloMeasurements.jl#multivariate-particles) below.
Although several interesting use cases for doing calculations with probability distributions have popped up (see [Examples](https://github.com/baggepinnen/MonteCarloMeasurements.jl#examples-1)), the original goal of the package is similar to that of [Measurements.jl](https://github.com/JuliaPhysics/Measurements.jl), to propagate the uncertainty from input of a function to the output. The difference compared to a `Measurement` is that `Particles` represent the distribution using a vector of unweighted particles, and can thus represent arbitrary distributions and handle nonlinear uncertainty propagation well. Functions like `f(x) = x²`, `f(x) = sign(x)` at `x=0` and long-time integration, are examples that are not handled well using linear uncertainty propagation à la [Measurements.jl](https://github.com/JuliaPhysics/Measurements.jl). MonteCarloMeasurements also support arbitrary correlations (and arbitrary dependencies such as conservation laws etc.) between variables.
A number of type `Particles` behaves just as any other `Number` while partaking in calculations. Particles also behave like a distribution,
so after a calculation, an approximation to the **complete distribution** of the output is captured and represented by the output particles.
`mean`, `std` etc. can be extracted from the particles using the corresponding functions `pmean` and `pstd`. `Particles` also interact with
[Distributions.jl](https://github.com/JuliaStats/Distributions.jl), so that you can call, e.g., `Normal(p)` and get back a `Normal` type from
distributions or `fit(Gamma, p)` to get a `Gamma`distribution. Particles can also be asked for `maximum/minimum`, `quantile` etc. using functions
with a prefix `p`, i.e., `pmaximum`. If particles are plotted with `plot(p)`, a histogram is displayed. This requires Plots.jl. A kernel-density
estimate can be obtained by `density(p)` if StatsPlots.jl is loaded. A `Measurements.Measurements` can be converted to particles by calling the
`Particles` constructor.
Below, we show an example where an input uncertainty is propagated through `σ(x)`

In the figure above, we see the probability-density function of the input `p(x)` depicted on the x-axis. The density of the output `p(y) = f(x)` is shown on the y-axis. Linear uncertainty propagation does this by linearizing `f(x)` and using the equations for an affine transformation of a Gaussian distribution, and hence produces a Gaussian approximation to the output density. The particles form a sampled approximation of the input density `p(x)`. After propagating them through `f(x)`, they form a sampled approximation to `p(y)` which corresponds very well to the true output density, even though only 20 particles were used in this example. The figure can be reproduced by `examples/transformed_densities.jl`.
For a comparison of uncertainty propagation and nonlinear filtering, see [notes](https://github.com/baggepinnen/MonteCarloMeasurements.jl#comparison-to-nonlinear-filtering) below.
# Basic Examples
```julia
using MonteCarloMeasurements, Distributions
julia> 1 ± 0.1
Particles{Float64,2000}
1.0 ± 0.1
julia> p = StaticParticles(100)
StaticParticles{Float64,100}
0 ± 0.999
julia> 1 ⊞ Binomial(3) # Shorthand for 1 + Particles(Binomial(1)) (\boxplus)
Particles{Int64, 2000}
2.504 ± 0.864
julia> 3 ⊠ Gamma(1) # Shorthand for 3 * Particles(Gamma(1)) (\boxtimes)
Particles{Float64, 2000}
2.99948 ± 3.0
julia> 2 + 0.5StaticParticles(Float32, 25) # Constructor signatures are similar to randn
StaticParticles{Float64,25}
2.0 ± 0.498
julia> pstd(p)
0.9986403042113866
julia> pvar(p)
0.9972824571954108
julia> pmean(p)
-6.661338147750939e-17
julia> f = x -> 2x + 10
#27 (generic function with 1 method)
julia> f(p) ≈ 10 # ≈ determines if f(p) is within 2σ of 10
true
julia> f(p) ≲ 15 # ≲ (\lesssim) tests if f(p) is significantly less than 15
true
julia> Normal(f(p)) # Fits a normal distribution
Normal{Float64}(μ=10.000000000000002, σ=1.9972806084227737)
julia> fit(Normal, f(p)) # Same as above
Normal{Float64}(μ=10.000000000000002, σ=1.9872691137573264)
julia> Particles(100, Uniform(0,2)) # A distribution can be supplied
Particles{Float64,100}
1.0 ± 0.58
julia> Particles(1000, MvNormal([0,0],[2. 1; 1 4])) # A multivariate distribution will cause a vector of correlated particles
2-element Array{Particles{Float64,1000},1}:
-0.0546 ± 1.4
-0.128 ± 2.0
```
# Why a package
Convenience. Also, the benefit of using this number type instead of manually calling a function `f` with perturbed inputs is that, at least in theory, each intermediate operation on `Particles` can exploit SIMD, since it's performed over a vector. If the function `f` is called several times, however, the compiler might not be smart enough to SIMD the entire thing. Further, any dynamic dispatch is only paid for once, whereas it would be paid for `N` times if doing things manually. The same goes for calculations that are done on regular input arguments without uncertainty, these will only be done once for `Particles` whereas they will be done `N` times if you repeatedly call `f`. One could perhaps also make an argument for cache locality being favorable for the `Particles` type, but I'm not sure this holds for all examples. Below, we show a small benchmark example (additional [Benchmark](@ref)) where we calculate a QR factorization of a matrix using `Particles` and compare it to manually doing it many times
```julia
using MonteCarloMeasurements, BenchmarkTools
unsafe_comparisons(true)
A = [randn() + Particles(1000) for i = 1:3, j = 1:3]
B = pmean.(A)
@btime qr($A);
# 119.243 μs (257 allocations: 456.58 KiB)
@btime foreach(_->qr($B), 1:1000); # Manually do qr 1000 times
# 3.916 ms (4000 allocations: 500.00 KiB)
```
that's about a 30-fold reduction in time, and the repeated `qr` didn't even bother to sample new input points or store and handle the statistics of the result.
The type `StaticParticles` contains a statically sized, stack-allocated vector from [StaticArrays.jl](https://github.com/JuliaArrays/StaticArrays.jl). This type is suitable if the number of particles is small, say < 500 ish (but expect long compilation times if > 100, especially on julia < v1.1).
```julia
A = [randn() + StaticParticles(100) for i = 1:3, j = 1:3]
B = pmean.(A)
@btime qr($(A));
# 8.392 μs (16 allocations: 18.94 KiB)
@btime map(_->qr($B), 1:100);
# 690.590 μs (403 allocations: 50.92 KiB)
# Over 80 times faster
# Bigger matrix
A = [randn() + StaticParticles(100) for i = 1:30, j = 1:30]
B = pmean.(A)
@btime qr($(A));
# 1.823 ms (99 allocations: 802.63 KiB)
@btime map(_->qr($B), 1:100);
# 75.068 ms (403 allocations: 2.11 MiB)
# 40 times faster
```
[`StaticParticles`](@ref) allocate much less memory than regular [`Particles`](@ref), but are more stressful for the compiler to handle.
# Constructors
The most basic constructor of [`Particles`](@ref) acts more or less like `randn(N)`, i.e., it creates a particle cloud with distribution `Normal(0,1)`. To create a particle cloud with distribution `Normal(μ,σ)`, you can call `μ + σ*Particles(N)`, or `Particles(N, Normal(μ,σ))`. This last constructor works with any distribution from which one can sample.
One can also call (`Particles/StaticParticles`)
- `Particles(v::Vector)` pre-sampled particles
- `Particles(N = 2000, d::Distribution = Normal(0,1))` samples `N` particles from the distribution `d`.
- The [`±`](@ref) operator (`\pm`) (similar to [Measurements.jl](https://github.com/JuliaPhysics/Measurements.jl)). We have `μ ± σ = μ + σ*Particles(DEFAULT_NUM_PARTICLES)`, where the global constant `DEFAULT_NUM_PARTICLES = 2000`. You can change this if you would like, or simply define your own `±` operator like `±(μ,σ) = μ + σ*Particles(my_default_number, my_default_distribution)`. The upside-down operator [`∓`](@ref) (`\mp`) instead creates a `StaticParticles(100)`.
- The `..` binary infix operator creates uniformly sampled particles, e.g., `2..3 = Particles(Uniform(2,3))`
**Common univariate distributions are sampled systematically**, meaning that a single random number is drawn and used to seed the sample. This will reduce the variance of the sample. If this is not desired, call `Particles(N, [d]; systematic=false)` The systematic sample can maintain its originally sorted order by calling `Particles(N, permute=false)`, but the default is to permute the sample so as to not have different `Particles` correlate strongly with each other.
Construction of `Particles` as [sigma points](https://en.wikipedia.org/wiki/Unscented_transform#Sigma_points) or by [latin hypercube sampling](https://en.wikipedia.org/wiki/Latin_hypercube_sampling) is detailed [below](https://github.com/baggepinnen/MonteCarloMeasurements.jl#sigma-points).
# Multivariate particles
The constructors can be called with multivariate distributions, returning `v::Vector{Particle}` where particles are sampled from the desired multivariate distribution. Once `v` is propagated through a function `v2 = f(v)`, the results can be analyzed by, e.g., asking for `pmean(v2)` and `pcov(v2)`, or by fitting a multivariate distribution, e.g., `MvNormal(v2)`.
A `v::Vector{Particle}` can be converted into a `Matrix` by calling `Matrix(v)` and this will have a size of `N × dim`. ~~You can also index into `v` like it was already a matrix.~~([This was a bad idea](https://discourse.julialang.org/t/show-for-vector-type-that-defines-matrix-getindex/23732/2?u=baggepinnen))
Broadcasting the ±/∓ operators works as you would expect, `zeros(3) .± 1` gives you a three-vector of *independent* particles, so does `zeros(3) .+ Particles.(N)`.
Independent multivariate systematic samples can be created using the function [`outer_product`](@ref) or the non-exported operator ⊗ (`\otimes`).
### Examples
The following example creates a vector of two `Particles`. Since they were created independently of each other, they are independent and uncorrelated and have the covariance matrix `Σ = Diagonal([1², 2²])`. The linear transform with the matrix `A` should in theory change this covariance matrix to `AΣAᵀ`, which we can verify be asking for the covariance matrix of the output particles.
```julia
julia> p = [1 ± 1, 5 ± 2]
2-element Array{Particles{Float64,2000},1}:
1.0 ± 1.0
5.0 ± 2.0
julia> A = randn(2,2)
2×2 Array{Float64,2}:
-1.80898 -1.24566
1.41308 0.196504
julia> y = A*p
2-element Array{Particles{Float64,2000},1}:
-8.04 ± 3.1
2.4 ± 1.5
julia> pcov(y)
2×2 Array{Float64,2}:
9.61166 -3.59812
-3.59812 2.16701
julia> A*Diagonal([1^2, 2^2])*A'
2×2 Array{Float64,2}:
9.4791 -3.53535
-3.53535 2.15126
```
To create particles that exhibit a known covariance/correlation, use the appropriate constructor, e.g.,
```julia
julia> p = Particles(2000, MvLogNormal(MvNormal([2, 1],[2. 1;1 3])))
2-element Array{Particles{Float64,2000},1}:
19.3 ± 48.0
11.9 ± 43.0
julia> pcov(log.(p))
2×2 Array{Float64,2}:
1.96672 1.0016
1.0016 2.98605
julia> pmean(log.(p))
2-element Array{Float64,1}:
1.985378409751101
1.000702538699887
```
# Sigma points
The [unscented transform](https://en.wikipedia.org/wiki/Unscented_transform#Sigma_points) uses a small number of points called *sigma points* to propagate the first and second moments of a probability density. We provide a function `sigmapoints(μ, Σ)` that creates a `Matrix` of `2n+1` sigma points, where `n` is the dimension. This can be used to initialize any kind of `AbstractParticles`, e.g.:
```julia
julia> m = [1,2]
julia> Σ = [3. 1; 1 4]
julia> p = StaticParticles(sigmapoints(m,Σ))
2-element Array{StaticParticles{Float64,5},1}:
1.0 ± 1.7 # 2n+1 = 5 particles
2.0 ± 2.0
julia> pcov(p) ≈ Σ
true
julia> pmean(p) ≈ m
true
```
[`sigmapoints`](@ref) also accepts a `Normal/MvNormal` object as input.
!!! danger "Caveat"
If you are creating several one-dimensional uncertain values using sigmapoints independently, they will be strongly correlated. Use the multidimensional constructor! Example:
```julia
p = StaticParticles(sigmapoints(1, 0.1^2)) # Wrong!
ζ = StaticParticles(sigmapoints(0.3, 0.1^2)) # Wrong!
ω = StaticParticles(sigmapoints(1, 0.1^2)) # Wrong!
p,ζ,ω = StaticParticles(sigmapoints([1, 0.3, 1], 0.1^2)) # Correct
```
# Latin hypercube sampling
We do not provide functionality for [latin hypercube sampling](https://en.wikipedia.org/wiki/Latin_hypercube_sampling), rather, we show how to use the package [LatinHypercubeSampling.jl](https://github.com/MrUrq/LatinHypercubeSampling.jl) to initialize particles.
```julia
# import Pkg; Pkg.add("LatinHypercubeSampling")
using MonteCarloMeasurements, LatinHypercubeSampling
ndims = 2
N = 100 # Number of particles
ngen = 2000 # How long to run optimization
X, fit = LHCoptim(N,ndims,ngen)
m, Σ = [1,2], [2 1; 1 4] # Desired mean and covariance
particle_matrix = transform_moments(X,m,Σ)
p = Particles(particle_matrix) # These are our LHS particles with correct moments
plot(scatter(eachcol(particles)..., title="Sample"), plot(fit, title="Fitness vs. iteration"))
julia> pmean(p)
2-element Array{Float64,1}:
1.0
2.0
julia> pcov(p)
2×2 Array{Float64,2}:
2.0 1.0
1.0 4.0
```
Latin hypercube sampling creates an approximately uniform sample in `ndims` dimensions. The applied transformation gives the particles the desired mean and covariance.
*Caveat:* Unfortunately, endowing the sampled latin hypercube with a desired *non-diagonal* covariance matrix destroys the latin properties for all dimensions but the first. This is less of a problem for diagonal covariance matrices provided that the latin optimizer was run sufficiently long.
The statistics of the sample can be visualized:
```julia
using StatsPlots
corrplot(particles)
plot(density(p[1]), density(p[2]))
```
see also `examples/lhs.jl`.
# Plotting
An instance of `p::Particles` can be plotted using `plot(p)`, that creates a histogram by default. If [`StatsPlots.jl`](https://github.com/JuliaPlots/StatsPlots.jl) is available, one can call `density(p)` to get a slightly different visualization.
For arrays of particles, `plot` takes a number of keyword arguments, indicated here by the available custom plot signatures
```julia
plot(y::Array{Particles}, q=0.025; N=true, ri = true, quantile=nothing) # Applies to matrices and vectors
plot(x::Array{Particles}, y::Array{Particles}, q=0.025; points=false, quantile=nothing)
```
- `q` and `quantile` denotes the quantiles used for ribbons.
- `ri` indicates whether or not to plot ribbons.
- `N` indicates the number of sample trajectories to plot on top of the ribbon. If `N=true`, a maximum of 50 trajectories are plotted.
- `points` indicates whether or not to plot the individual particles as points. If `false`, error bars are shown instead.
Vectors of particles can also be plotted using one of the custom functions
- `errorbarplot(x,y,[q=0.025])`: `q` determines the quantiles, set to `0` for max/min. You can also specify both bounds, e.g., `q = (0.01, 0.99)`.
- `mcplot(x,y)`: Plots all trajectories
- `ribbonplot(x,y,[q=0.025]; N=true)`: Plots with shaded area from quantile `q` to `1-q`. You can also specify both bounds, e.g., `q = (0.01, 0.99)`.
- Plot recipes from [`StatsPlots.jl`](https://github.com/JuliaPlots/StatsPlots.jl) that do not work with `Particles` or vectors of `Particles` can often be made to work by converting the particles to an array, e.g., `violin(Array([1±0.5, 4±1, 2±0.1]))`.
All plots that produce an output with a ribbon also accept a keyword argument `N` that indicates a number of sample trajectories to be shown on top of the ribbon. The default `N=true` plots a maximum of 50 trajectories.
Below is an example using [ControlSystems.jl](https://github.com/JuliaControl/ControlSystems.jl)
```julia
using ControlSystems, MonteCarloMeasurements, StatsPlots
p = 1 ± 0.1
ζ = 0.3 ± 0.1
ω = 1 ± 0.1
G = tf([p*ω], [1, 2ζ*ω, ω^2]) # Transfer function with uncertain parameters
dc = dcgain(G)[]
# Part500(1.01 ± 0.147)
density(dc, title="Probability density of DC-gain")
```

```julia
w = exp10.(LinRange(-1,1,200)) # Frequency vector
mag, phase = bode(G,w) .|> vec
errorbarplot(w,mag, yscale=:log10, xscale=:log10)
```

```julia
mcplot(w,mag, yscale=:log10, xscale=:log10, alpha=0.2)
```

```julia
ribbonplot(w,mag, yscale=:log10, xscale=:log10, alpha=0.2)
```

## Makie support
!!! danger "Experimental"
The support for plotting with Makie is currently experimental and at any time subject to breaking changes or removal **not** respecting semantic versioning.
Basic support for plotting with Makie exists as well, try any of the following functions with uncertain numbers
- `Makie.scatter(xs, ys)`
- `Makie.scatter(tuple.(xs, ys))`
- `Makie.band(xs, ys)`
- `Makie.band(tuple.(xs, ys); q=0.01)`
- `Makie.rangebars(tuple.(xs, ys); q=0.16)`
- `Makie.series(xs, ys)`
- `Makie.series(tuple.(xs, ys); N=5)`
# Limitations
One major limitation is functions that contain control flow, where the branch is decided by an uncertain value. Consider the following case
```julia
function negsquare(x)
x > 0 ? x^2 : -x^2
end
p = 0 ± 1
```
Ideally, half of the particles should turn out negative and half positive when applying `negsquare(p)`. However, this will not happen as the `x > 0` is not defined for uncertain values. To circumvent this, define `negsquare` as a primitive using [`register_primitive`](@ref) described in [Overloading a new function](@ref). Particles will then be propagated one by one through the entire function `negsquare`. Common such functions from `Base`, such as `max/min` etc. are already registered.
## Comparison mode
Some functions perform checks like `if error < tol`. If `error isa Particles`, this will use a very conservative check by default by checking that all particles ∈ `error` fulfill the check. There are a few different options available for how to compare two uncertain quantities, chosen by specifying a comparison mode. The modes are chosen by `unsafe_comparisons(mode)` and the options are
- `:safe`: the default described above, throws an error if uncertain values share support.
- `:montecarlo`: slightly less conservative than `:safe`, checks if either all pairwise particles fulfill the comparison, *or* all pairwise particles fail the comparison. If some pairs pass and some fail, an error is thrown.
- `:reduction`: Reduce uncertain values to a single number, e.g. by calling `pmean` (default) before performing the comparison, never throws an error.
To sum up, if two uncertain values are compared, and they have no mutual support, then all comparison modes are equal. If they share support, `:safe` will error and `:montecarlo` will work if the all pairwise particles either pass or fail the comparison. `:reduction` will always work, but is maximally unsafe in the sense that it might not perform a meaningful check for your application.
### Calculating probability
If you would like to calculate the empirical probability that a value represented by `Particles` fulfils a condition, you may use the macro [`@prob`](@ref):
```julia
julia> p = Particles()
Particles{Float64,2000}
0 ± 1.0
julia> @prob p < 1
0.8415
julia> mean(p.particles .< 1)
0.8415
```
# When to use what?
This table serves as a primitive guide to selecting an uncertainty propagation strategy. If you are unsure about the properties of your function, also have a look at [Comparison between linear uncertainty propagation and Monte-Carlo sampling](@ref)
| Situation | Action |
|-----------------|--------------|
| Linear functions | Use linear uncertainty propagation, i.e., Measurements.jl |
| Highly nonlinear/discountinuous functions | Use MonteCarloMeasurements |
| Correlated quantities | Use MonteCarloMeasurements |
| Large uncertainties in input | Use MonteCarloMeasurements |
| Small uncertainties in input in relation to the curvature of the function | Use Measurements |
| Interested in low probability events / extremas | Use MonteCarloMeasurements / [IntervalArithmetic.jl](https://github.com/JuliaIntervals/IntervalArithmetic.jl)|
| Limited computational budget | Use Measurements or [`StaticParticles`](@ref) with [`sigmapoints`](https://github.com/baggepinnen/MonteCarloMeasurements.jl#sigma-points). See benchmark below. |
| Non-Gaussian input distribution | Use MonteCarloMeasurements |
| Calculate tail integrals accurately | This requires some form of [importance sampling](https://en.wikipedia.org/wiki/Importance_sampling#Application_to_simulation), not yet fully supported |
Due to [Jensen's inequality](https://en.wikipedia.org/wiki/Jensen%27s_inequality), linear uncertainty propagation will always underestimate the mean of nonlinear convex functions and overestimate the mean of concave functions. From wikipedia
> In its simplest form the inequality states that the convex transformation of a mean is less than or equal to the mean applied after convex transformation; it is a simple corollary that the opposite is true of concave transformations.
Linear uncertainty propagation does thus not allow you to upperbound/lowerbound the output uncertainty of a convex/concave function, and will be conservative in the reverse case.
## Benchmark
The benchmark results below comes from [`examples/controlsystems.jl`](https://github.com/baggepinnen/MonteCarloMeasurements.jl/blob/master/examples/controlsystems.jl) The benchmark consists of calculating the Bode curves for a linear system with uncertain parameters
```julia
w = exp10.(LinRange(-1,1,200)) # Frequency vector
p = 1 ± 0.1
ζ = 0.3 ± 0.1
ω = 1 ± 0.1
G = tf([p*ω], [1, 2ζ*ω, ω^2])
t1 = @belapsed bode($G,$w)
⋮
```
| Benchmark | Result |
|-----------|--------|
| Time with 500 particles | 1.3632ms |
| Time with regular floating point | 0.0821ms |
| Time with Measurements | 0.1132ms |
| Time with 100 static part. | 0.2375ms |
| Time with static sigmapoints. | 0.0991ms |
| 500×floating point time | 41.0530ms |
| Speedup factor vs. Manual | 30.1x |
| Slowdown factor vs. Measurements | 12.0x |
| Slowdown static vs. Measurements | 2.1x |
| Slowdown sigma vs. Measurements | 0.9x|
The benchmarks show that using `Particles` is much faster than doing the Monte-Carlo sampling manually. We also see that we're about 12 times slower than linear uncertainty propagation with Measurements.jl if we are using standard `Particles`, `StaticParticles` are within a factor of 2 of Measurements and `StaticParticles` with [`sigmapoints`](@ref) are actually 10% faster than Measurements (this is because 7 sigmapoints fit well into two of the processors SIMD registers, making the extra calculations very cheap).
## Comparison to nonlinear filtering
The table below compares methods for uncertainty propagation with their parallel in nonlinear filtering.
| Uncertainty propagation | Dynamic filtering | Method |
| -------------------------|-------------------------|------------------------|
| Measurements.jl | Extended Kalman filter | Linearization |
| `Particles(sigmapoints)` | Unscented Kalman Filter | Unscented transform |
| `Particles` | [Particle Filter](https://github.com/baggepinnen/LowLevelParticleFilters.jl) | Monte Carlo (sampling) |
# Citing
See [CITATION.bib](https://github.com/baggepinnen/MonteCarloMeasurements.jl/blob/master/CITATION.bib)
ArXiv article [MonteCarloMeasurements.jl: Nonlinear Propagation of Arbitrary Multivariate Distributions by means of Method Overloading](https://arxiv.org/abs/2001.07625)
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | docs | 5384 | # Supporting new functions
## Overloading a new function
If a method for `Particles` is not implemented for your function `yourfunc`, the pattern to register your function looks like this
```julia
register_primitive(yourfunc)
```
This defines both a one-argument method and a multi-arg method for both `Particles` and `StaticParticles`. If you only want to define one of these, see [`register_primitive_single`](@ref)/[`register_primitive_multi`](@ref). If the function is from base or stdlib, you can just add it to the appropriate list in the source and submit a PR :)
## Monte-Carlo simulation by `map/pmap`
Some functions will not work when the input arguments are of type `Particles`. For this kind of function, we provide a fallback onto a traditional `map(f,p.particles)`. The only thing you need to do is to decorate the function call with the function [`bymap`](@ref) or the macro [`@bymap`](@ref) like so:
```julia
f(x) = 3x^2
p = 1 ± 0.1
r = @bymap f(p) # bymap(f,p) may give better error traces
```
We further provide the macro [`@bypmap`](@ref) (and [`bypmap`](@ref)) which does exactly the same thing, but with a `pmap` (parallel map) instead, allowing you to run several invocations of `f` in a distributed fashion.
These utilities will map the function `f` over each element of `p::Particles{T,N}`, such that `f` is only called with arguments of type `T`, e.g., `Float64`. This handles arguments that are multivaiate particles `<: Vector{<:AbstractParticles}` as well.
These utilities will typically be slower than calling `f(p)`. If `f` is very expensive, [`@bypmap`](@ref) might prove prove faster than calling `f` with `p`, it's worth a try. The usual caveats for distributed computing applies, all code must be loaded on all workers etc.
## Array-to-array functions
These functions might not work with `Particles` out of the box. Special cases are currently implemented for
- `exp : ℝ(n×n) → ℝ(n×n)` matrix exponential
- `log : ℝ(n×n) → C(n×n)` matrix logarithm
- `eigvals : ℝ(n×n) → C(n)` **warning**: eigenvalues are sorted, when two eigenvalues cross, this function is nondifferentiable. Eigenvalues can thus appear to have dramatically widened distributions. Make sure you interpret the result of this call in the right way.
The function [`ℝⁿ2ℝⁿ_function`](@ref)`(f::Function, p::AbstractArray{T})` applies `f : ℝⁿ → ℝⁿ` to an array of particles. See also [`ℝⁿ2ℂⁿ_function`](@ref) which is used to implement, e.g., `log,eigvals`
## Complex functions
These functions do not work with `Particles` out of the box. Special cases are currently implemented for
- `sqrt`, `exp`, `sin`, `cos`
We also provide in-place versions of the above functions, e.g.,
- `sqrt!(out, p)`, `exp!(out, p)`, `sin!(out, p)`, `cos!(out, p)`
The function [`ℂ2ℂ_function`](@ref)`(f::Function, z)` (`ℂ2ℂ_function!(f::Function, out, z)`) applies `f : ℂ → ℂ ` to `z::Complex{<:AbstractParticles}`.
## Difficult cases
Sometimes, defining a primitive function can be difficult, such as when the uncertain parameters are baked into some object. In such cases, we can call the function [`unsafe_comparisons`](@ref)`(true)`, which defines all comparison operators for uncertain values to compare using the `mean`. Note however that this enabling this is somewhat *unsafe* as this corresponds to a fallback to linear uncertainty propagation, why it's turned off by default. We also provide the macro
`@unsafe ex` to enable mean comparisons only locally in the expression `ex`.
In some cases, defining a primitive is not possible but allowing unsafe comparisons are not acceptable. One such case is functions that internally calculate eigenvalues of uncertain matrices. The eigenvalue calculation makes use of comparison operators. If the uncertainty is large, eigenvalues might change place in the sorted list of returned eigenvalues, completely ruining downstream computations. For this we recommend, in order of preference
1. Use [`bymap`](@ref). Applicable if all uncertain values appears as arguments to your entry function.
2. Create a [`Workspace`](@ref) object and call it using your entry function. Applicable if uncertain parameters appear nested in an object that is an argument to your entry function:
```julia
# desired computation: y = f(obj), obj contains uncertain parameters inside
y = with_workspace(f, obj)
# or equivalently
w = Workspace(f,obj) # This is somewhat expensive and can be reused
use_invokelatest = true # Set this to false to gain 0.1-1 ms, at the expense of world-age problems if w is created and used in the same function.
w(obj, use_invokelatest)
```
This interface is so far not tested very well and may throw strange errors. Some care has been taken to make error messages informative.
Internally, a `w::Workspace` object is created that tries to automatically construct an object identical to `obj`, but where all uncertain parameters are replaced by conventional `Real`. If the heuristics used fail, an error message is displayed detailing which method you need to implement to make it work. When called, `w` populates the internal buffer object with particle `i`, calls `f` using a `Particles`-free `obj` and stores the result in an output object at particle index `i`. This is done for `i ∈ 1:N` after which the output is returned. Some caveats include: [`Workspace`](@ref) must not be created or used inside a `@generated` function.
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 1.2.1 | 36ccc5e09dbba9aea61d78cd7bc46c5113e6ad84 | docs | 2236 | # Performance tips
By using this package in favor of the naive way of performing Monte-Carlo propagation, you are already likely to to see a performance increase. Nevertheless, there are some things that can increase your performance further. Some of these tips are discussed in greater detail in the paper, ["MonteCarloMeasurements.jl: Nonlinear Propagation of Arbitrary Multivariate Distributions by means of Method Overloading"](https://arxiv.org/abs/2001.07625).
## Consider using `StaticParticles` and/or `sigmapoints`
If you want to propagate a small number of samples, less than about 300, [`StaticParticles`](@ref) are *much* faster than regular `Particles`. Above 300 samples, the compilation time starts exploding.
Using [Sigma points](@ref) is a way to reduce the number of samples required, but they come with some caveats and also reduce the fidelity of the propagated distribution significantly.
## Use a smaller float type
While performing Monte-Carlo propagation, it is very likely that the numerical precision offered by `Float64` is overkill, and that `Float32` will do just as well. All forms of `AbstractParticles` are generic with respect to the inner float type, and thus allow you to construct, e.g., `Particles{Float32,N}`. Since a large contributing factor to the speedup offered by this package comes from the utilization of SIMD instructions, switching to `Float32` will almost always give you a clean 2x performance improvement. Some examples on how to create `Float32` particles:
```@repl
using MonteCarloMeasurements # hide
1.0f0 ∓ 0.1f0
Particles(Normal(1f0, 0.1f0))
Particles(randn(Float32, 500))
```
## Try GPU particles
If you are propagating a very large number of samples, say 10⁵-10⁷, you may want to try utilizing a GPU. Unfortunately, supporting GPU particles on the main branch has proven difficult since the CuArrays package is a heavy dependency and very hard to test on available CI infrastructure. We thus maintain a separate branch with this functionality. To install it, do
```julia
using Pkg
pkg"add MonteCarloMeasurements#gpu"
```
after which you will have access to a new particle type, `CuParticles`. These act just like ordinary particles, but perform all computations on the GPU.
| MonteCarloMeasurements | https://github.com/baggepinnen/MonteCarloMeasurements.jl.git |
|
[
"MIT"
] | 0.2.0 | 3e1c2e1206f2c614edcdd048cd929ee26ee6abf8 | code | 1665 | module PearsonHash
using Random: shuffle!
export hash8, hashn, hashn!
_table = shuffle!(collect(0:255))
"""
hash8(data::Vector{UInt8}; seed::UInt8 = zero(UInt8))
hash8(data::AbstractString; seed::UInt8 = zero(UInt8))
Compute the Pearson 8-bit hash for `data` (optionally specify `seed`).
"""
function hash8(data::Vector{UInt8}; seed::UInt8 = zero(UInt8))
h = seed
for byte in data
h = _table[xor(h, byte) + one(UInt8)]
end
return h
end
hash8(data::AbstractString; seed::UInt8 = zero(UInt8)) = hash8(Vector{UInt8}(data); seed = seed)
"""
hashn!([T = UInt128], data::Vector{UInt8}; seed::UInt8 = 0)::T where T
Compute a (`8*n`)-bit hash for data where `n == sizeof(T)` (optionally specify `seed`).
*Note:* `data` will be mutated in-place. See `hashn` for version without mutation.
"""
function hashn!(::Type{T}, data::Vector{UInt8}; seed::UInt8 = zero(UInt8))::T where T
h = zero(T)
n = sizeof(T)
firstbyte = data[1]
for i in 0:(n - 1)
data[1] = UInt8((firstbyte + i) % 256)
h |= T(hash8(data; seed = seed)) << (i * 8)
end
return h
end
hashn!(data::Vector{UInt8}; seed::UInt8 = zero(UInt8)) = hashn!(UInt128, data; seed = seed)
"""
hashn([T = UInt128], data; seed::UInt8 = zero(UInt8))::T where T
Compute a (`8*n`)-bit hash for `Vector{UInt8}(data)` where `n == sizeof(T)` (optionally specify `seed`).
*Note:* `data` is copied to prevent mutation (resulting in extra allocations).
"""
hashn(::Type{T}, data; seed::UInt8 = zero(UInt8)) where T = hashn!(T, Vector{UInt8}(data); seed = seed)
hashn(data; seed::UInt8 = zero(UInt8)) = hashn(UInt128, data; seed = seed)
end # module
| PearsonHash | https://github.com/darsnack/PearsonHash.jl.git |
|
[
"MIT"
] | 0.2.0 | 3e1c2e1206f2c614edcdd048cd929ee26ee6abf8 | code | 292 | using Random
Random.seed!(1234)
using PearsonHash
using Test
@testset "PearsonHash.jl" begin
@test hash8("Test") == hash8("Test")
@test hash8("Test") == hashn(UInt8, "Test")
@test typeof(hashn(UInt32, "Test")) == UInt32
@test hashn("Test") != hashn("Test"; seed = 0xFF)
end
| PearsonHash | https://github.com/darsnack/PearsonHash.jl.git |
|
[
"MIT"
] | 0.2.0 | 3e1c2e1206f2c614edcdd048cd929ee26ee6abf8 | docs | 706 | # PearsonHash

This package provides utility functions for [Pearson hashing](https://en.wikipedia.org/wiki/Pearson_hashing). You can use the standard 8-bit hash function:
```julia
julia> hash8("Test")
77
```
Or use `hashn` to get multiple of 8 bits (i.e. (`8*n`)-bit hash) where `n` is based on the return type specified):
```julia
julia> hashn(UInt16, "Test")
0x424d
```
Note that `hashn` converts the data passed in using `Vector{UInt8}(data)`. This will result in extra allocations if `data` is mutable.
## Documentation
For this simple package, just use the REPL:
```julia
julia> ?hash8
julia> ?hashn!
julia> ?hashn | PearsonHash | https://github.com/darsnack/PearsonHash.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | code | 797 | # push!(LOAD_PATH,"../src/")
using AVSfldIO
using Documenter
DocMeta.setdocmeta!(AVSfldIO, :DocTestSetup, :(using AVSfldIO); recursive=true)
makedocs(;
modules = [AVSfldIO],
authors = "Jeff Fessler <[email protected]> and contributors",
repo = "https://github.com/JeffFessler/AVSfldIO.jl/blob/{commit}{path}#{line}",
sitename = "AVSfldIO.jl",
format = Documenter.HTML(;
prettyurls = get(ENV, "CI", "false") == "true",
# canonical = "https://JeffFessler.github.io/AVSfldIO.jl/stable",
# assets = String[],
),
pages = [
"Home" => "index.md",
],
)
deploydocs(;
repo = "github.com/JeffFessler/AVSfldIO.jl.git",
devbranch = "main",
# devurl = "dev",
# versions = ["stable" => "v^", "dev" => "dev"],
# push_preview = true,
)
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | code | 720 | """
AVSfldIO
module for AVS .fld file IO
"""
module AVSfldIO
using FileIO: File, @format_str
include("fld-read.jl")
include("fld-write.jl")
# the two key methods that will be used by FileIO:
"""
data = load(ff::File{format"AVSfld"} ; kwargs...)
AVSfld load method
"""
load(ff::File{format"AVSfld"} ; kwargs...) =
fld_read(ff.filename ; kwargs...)
"""
save(ff::File{format"AVSfld"}, data::AbstractArray{<:Real} ; kwargs...)
AVSfld save method
"""
save(ff::File{format"AVSfld"}, data::AbstractArray{<:Real} ; kwargs...) =
fld_write(ff.filename, data ; kwargs...)
save(ff::File{format"AVSfld"}, data ; kwargs...) =
throw(ArgumentError("data must be an array of reals for AVSfld"))
end # module
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | code | 8629 | #=
fld-read.jl
Jeff Fessler and David Hong
=#
export fld_open, fld_header, fld_read
"""
head, is_external_file, fid = fld_open(file ; dir::String="", chat=false)
Read header data from AVS format `.fld` file.
Leaves file open for more reading.
in
- `file::String` file name, usually ending in `.fld`
option
- `dir::String` prepend file name with this directory; default ""
- `chat::Bool` verbose? default: `false`
out
- `head::String` array of header information
- `is_external_file::Bool` true if AVS external format
- `fid::IOstream`
"""
function fld_open(
file::AbstractString ;
dir::String = "",
chat::Bool = false,
)
file = joinpath(dir, file)
fid = open(file)
formfeed = '\f' # form feed
newline = '\n'
is_external_file = false
# read header until we find the end of file or the 1st form feed
header = ""
while true
# end of file means external file (or error)
if eof(fid)
if occursin("file=", header)
is_external_file = true
break # end of header file!
else
chat && @info(header)
throw("end of file before form feeds?")
end
end
inchar = read(fid, Char) # read one character
# form feed means embedded file
if inchar == formfeed
eof(fid) && throw("end of file before 2nd form feed?")
inchar = read(fid, Char)
(inchar != formfeed) && throw("not two form feeds?")
chat && @info("embedded data file")
break
end
# otherwise append this character to header string
header *= inchar
end
header = string_to_array(header) # convert to array
chat && @info(header)
return header, is_external_file, fid
end
"""
head = fld_header(file::String ; dir::String="", chat=false)
Read header data from AVS format `.fld` file, then close file.
in
- `file::String` file name, usually ending in `.fld`
option
- `dir::String` prepend file name with this directory; default ""
- `chat::Bool` verbose? default: `false`
out
- `head::String` array of header information
"""
function fld_header(file::AbstractString ; kwargs...)
header, _, fid = fld_open(file ; kwargs...)
close(fid)
return header
end
# todo:
# + [ ] 'raw' 0|1 1: return raw data class (default), 0: return doubles
# + [ ] 'slice' int specify which slice to read from 3D file. (0 ... nz-1)
# + [ ] 'chat' 0|1 enable verbosity
# + [ ] 'dim_only' 0|1 returns dims. data and coord are equal to [].
# + [ ] 'coord' 0|1 returns coordinates too (default: 0)
# + [ ] 'coord_format' default: 'n'; see fopen() for machine format options
# (needed for some UM .fld files with 'vaxd' coordinates)
# + [ ] multi files
# + [ ] short datatype
"""
data = fld_read(file::String ; dir::String="", chat=false)
Read data from AVS format `.fld` file
in
- `file` file name, usually ending in `.fld`
option
- `dir::String` prepend file name with this directory; default ""
- `chat::Bool` verbose?
out
- `data` Array (1D - 5D) in the data type of the file itself
"""
function fld_read(
file::AbstractString ;
dir::String = "",
chat::Bool = false,
)
file = joinpath(dir, file)
header, is_external_file, fid = fld_open(file ; chat)
chat && @info("is_external_file = $is_external_file")
# parse header to determine data dimensions and type
ndim = arg_get(header, "ndim")
dims = [arg_get(header, "dim$ii") for ii in 1:ndim]
fieldtype = arg_get(header, "field", false)
datatype = arg_get(header, "data", false)
(arg_get(header, "veclen") != 1) && throw("only veclen=1 done")
chat && @info("ndim=$ndim")
chat && @info("dims=$dims")
# external file (binary data in another file)
_skip = 0
if is_external_file
close(fid)
extfile = arg_get(header, "file", false)
filetype = arg_get(header, "filetype", false)
chat && @info("Current file = '$file', External file = '$extfile', type='$filetype'")
_skip = occursin("skip=",prod(header)) ?
arg_get([prod(header)], "skip", false) : 0
if filetype == "ascii"
tmp = dirname(file)
extfile = joinpath(tmp, extfile)
chat && @info("extfile = $extfile")
isfile(extfile) || throw("no ascii file $extfile")
format, _, _ = datatype_fld_to_mat(datatype)
return fld_read_ascii(extfile, (dims...,), format)
elseif filetype != "multi"
if !isfile(extfile)
fdir = file
slash = findlast(isequal('/'), fdir) # todo: windows?
isnothing(slash) && throw("cannot find external file $extfile")
fdir = fdir[1:slash]
extfile = fdir * extfile # add directory
!isfile(extfile) && throw("no external ref file $extfile")
end
else
throw("multi not supported yet") # todo
end
else
filetype = ""
extfile = ""
end
# finally, read the binary data
format, endian, bytes = datatype_fld_to_mat(datatype)
# single file reading
data = fld_read_single(file, fid, dims, datatype, fieldtype,
is_external_file, extfile, format, endian, bytes, _skip)
close(fid)
return data
end
# todo: currently supports only one entry per line (see fld_read.m)
function fld_read_ascii(extfile::AbstractString, dims::Dims, datatype::DataType)
data = zeros(datatype, dims)
open(extfile, "r") do fid
for i in 1:length(data)
tmp = readline(fid)
data[i] = parse(Float64, tmp)
end
end
return data
end
function fld_read_single(
file, fid, dims, datatype, fieldtype,
is_external_file, extfile, format::DataType, endian, bytes, _skip,
)
# reopen file to same position, with appropriate endian too.
if is_external_file
fid = open(extfile)
end
skip(fid,_skip)
rdims = dims # from handling slice option
# read binary data and reshape appropriately
data = Array{format}(undef, rdims...)
try
read!(fid, data)
catch
@info("rdims=$rdims")
throw("file count != data count")
end
return endian === :le ? htol.(data) :
endian === :be ? hton.(data) :
throw("bug $endian")
end
"""
header = string_to_array(header_lines)
Convert long string with embedded newlines into string array.
"""
function string_to_array(header_lines::String)
newline = '\n'
# ensure there is a newline at end, since dumb editors can forget...
if header_lines[end] != newline
header_lines *= newline
end
ends = findall(isequal(newline), header_lines)
(length(ends) <= 0) && throw("no newlines?")
header = split(header_lines, newline, keepempty=false)
# strip comments (lines that begin with #)
header = filter(line -> line[1] != '#', header)
return header
end
"""
arg_get(head, name, toint)
Parse an argument from header, of the `name=value` form
"""
function arg_get(head::Array{<:AbstractString}, name::String, toint::Bool=true)
for line in head
start = findfirst(name * '=',line)
if !isnothing(start)
!isnothing(findnext(name*'=',line,start[end]+1)) && throw("bug: multiples?")
line = line[(start[end]+1):end]
arg = split(line)[1]
toint && (arg = parse(Int,arg))
return arg
end
end
throw("could not find $name in header")
end
"""
format, endian, bytes = datatype_fld_to_mat(datatype)
Determine data format from `.fld` header datatype.
"""
function datatype_fld_to_mat(datatype::AbstractString)
dict = Dict([
("byte", (UInt8, :be, 1)), # :be irrelevant
("short_be", (UInt16, :be, 2)),
("short_sun", (UInt16, :be, 2)),
("xdr_short", (UInt16, :be, 2)),
("short_le", (UInt16, :le, 2)),
("int", (Int32, "", 4)), # native int - not portable
("int_le", (Int32, :le, 4)),
("int_be", (Int32, :be, 4)),
("xdr_int", (Int32, :be, 4)),
("float", (Float32, "", 4)), # native float - not portable
("float_le", (Float32, :le, 4)),
("float_be", (Float32, :be, 4)),
("xdr_float", (Float32, :be, 4)),
("double", (Float64, "", 8)), # native 64oat - not portable
("double_le", (Float64, :le, 8)),
("double_be", (Float64, :be, 8)),
("xdr_double", (Float64, :be, 8)),
])
return dict[datatype] # format, endian, bytes
end
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | code | 4079 | #=
fld-write.jl
write AVS .fld to file
2019-05-12, Jeff Fessler, University of Michigan
=#
export fld_write
"""
fld_write(file, data ; kwargs...)
Write data into AVS format `.fld` file.
See README for file format.
in
- `file` name of file typically ending in `.fld`
- `data` real data array
option
- `check::Bool` report error if file exists; default `true`
- `dir::String` directory name to prepend file name; default `""`
- `endian::`Symbol` `:le` little endian (default), `:be` big endian
- `head::Array{String}` comment information for file header
- `raw::Bool` put raw data in `name.raw`, header in `name.fld`
where `file` = `name.fld`; default `false`
"""
function fld_write(
file::String,
data::AbstractArray{<:Real} ;
check::Bool = true,
dir::String = "",
endian::Symbol = :le,
head::Array{String} = empty([""]),
warn::Bool = true,
raw::Bool = false,
)
data = fld_write_data_fix(data ; warn) # make data suitable for writing in .fld
endian != :le && endian != :be && throw("endian '$endian' unknown")
typedict = Dict([
(Float32, endian === :le ? "float_le" : "xdr_float"),
(Float64, endian === :le ? "double_le" : "xdr_double"),
(UInt8, "byte"),
(Int16, endian === :le ? "short_le" : "short_be"),
(Int32, endian === :le ? "int_le" : "xdr_int"),
])
datatype = typedict[eltype(data)] # throws error if not there
file = joinpath(dir, file)
# @show file
check && isfile(file) && throw("file '$file' exists")
if raw # if writing data to separate ".raw" file, ensure it does not exist
fileraw = file[1:(end-3)] * "raw"
check && isfile(fileraw) && throw("file $fileraw exists")
end
# write header to IOBuffer
io = IOBuffer()
ndim = ndims(data)
println(io, "# AVS field file ($(basename(@__FILE__)))")
for line in head
println(io, "# $line")
end
println(io, "ndim=$ndim")
for ii=1:ndim
println(io, "dim$ii=$(size(data,ii))")
end
println(io, "nspace=$ndim")
println(io, "veclen=1")
println(io, "data=$datatype")
println(io, "field=uniform")
if raw
println(io, "variable 1 file=$fileraw filetype=binary")
else
write(io, "\f\f") # two form feeds: char(12)
end
# determine how to write the binary data
host_is_le = () -> ENDIAN_BOM == 0x04030201
fun = (host_is_le() == (endian === :le)) ?
identity : # host/file same endian
(host_is_le() && (endian === :be)) ?
hton :
(!host_is_le() && (endian === :le)) ?
htol :
throw("not done")
# write header from IO buffer to file
open(file, "w") do fid
write(fid, take!(io))
end
# write binary data to file or fileraw
if raw
open(fileraw, "w") do fraw
write(fraw, fun.(data))
end
else
open(file, "a") do fid
write(fid, fun.(data))
end
end
return nothing
end
"""
data = fld_write_data_fix(data)
Convert data to format suitable for writing to `.fld` file.
"""
function fld_write_data_fix(data::AbstractArray{BigFloat} ; warn::Bool=true)
warn && (@warn "BigFloat downgraded to Float64")
return Float64.(data)
end
function fld_write_data_fix(data::AbstractArray{Float16} ; warn::Bool=true)
warn && (@warn "Float16 promoted to Float32")
return Float32.(data)
end
function fld_write_data_fix(
data::AbstractArray{T} ;
warn::Bool=true,
) where {T <: Union{BigInt, Int64}}
warn && (@warn "$T downgraded to Int32")
return Int32.(data)
end
function fld_write_data_fix(data::AbstractArray{Bool} ; warn::Bool=true)
warn && (@warn "Bool promoted to UInt8")
return UInt8.(data)
end
@inline fld_write_data_fix(data::AbstractArray{T} ; warn::Bool=true) where
{T <: Union{Float32, Float64, UInt8, Int16, Int32}} = data
fld_write_data_fix(data::AbstractArray{T} ; warn::Bool=true) where {T <: Any} =
throw(ArgumentError("unsupported type $T"))
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | code | 476 | #=
file-io.jl
test AVSfldIO through FileIO
=#
using FileIO: File, @format_str
using FileIO: add_format, load, save, UUID
#using FileIO: info, unknown, query
#using AVSfldIO
data1 = reshape(Int32.(1:20), 4, 5)
file = tempname() * ".fld"
#ff = File{format"AVSfld"}(file)
#query(ff)
add_format(format"AVSfld", "# AVS", ".fld",
[:AVSfldIO => UUID("b6189060-daf9-4c28-845a-cc0984b81781")])
save(file, data1)
data2 = load(file)
@assert data2 == data1
rm(file, force=true)
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | code | 2348 | # fld-read.jl
using AVSfldIO: fld_open, fld_header, fld_read
import AVSfldIO: arg_get, string_to_array, fld_read_single
using Test: @test, @testset, @test_throws
dir = mktempdir()
@testset "fld eof" begin
file = joinpath(dir, "fld-read-eof-test.fld")
open(file, "w") do fid
# @show fid
println(fid, "# AVS field file eof test")
end
@test_throws String fld_read(file)
open(file, "r") do fid
@test_throws String fld_read_single(
file, fid,
(99,), Float32, fieldtype,
false, # is_external_file,
"", # extfile,
Float32, "ieee-le", 0, 0,
)
end
end
@testset "fld misc" begin
@test_throws String arg_get(["1", "2"], "3")
@test string_to_array("0") isa AbstractArray{<:AbstractString}
end
@testset "fld ascii" begin
tdir = mktempdir()
file = joinpath(tdir, "fld-read-test.fld")
extfilename = "fld-read-test.txt"
chat = isinteractive()
data = Float32.(1:5)
head = [
"# AVS field file"
"ndim=1"
"dim1=5"
"nspace=1"
"veclen=1"
"data=float"
"field=uniform"
"variable 1 file=$extfilename filetype=ascii"
]
open(file, "w") do fid
for line in head
println(fid, line)
end
end
@test fld_header(file) isa Array{<:AbstractString}
# ensure that it throws if no extfile
@test_throws String tmp = fld_read(file)
# write ascii and test
extfile = joinpath(tdir, extfilename)
open(extfile, "w") do fid
for d in data
println(fid, d)
end
end
# run(`op range $file`)
tmp = fld_read(file ; chat=chat)
@test tmp == data
@test eltype(tmp) == Float32
rm(file)
rm(extfile)
end
@testset "read no ext" begin # missing extfile
tdir = mktempdir()
file = joinpath(tdir, "fld-read-test.fld")
head = [
"# AVS field file"
"ndim=1"
"dim1=4"
"nspace=1"
"veclen=1"
"data=float"
"field=uniform"
"variable 1 file=bad.txt filetype=binary"
]
open(file, "w") do fid
for line in head
println(fid, line)
end
end
@test_throws String fld_read(file)
rm(file)
end
# todo: test read slices when that feature is added
# fld_write ...
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | code | 3038 | # fld-write.jl
using AVSfldIO: fld_write, fld_read
import AVSfldIO: fld_write_data_fix
using Test: @test, @testset, @test_throws, @inferred
"""
fld_write_test1(file, data, ...)
"""
function fld_write_test1(file, data ;
raw::Bool=false,
warn::Bool=false,
chat::Bool=false, kwarg...
)
@inferred fld_write(file, data ; raw, warn, kwarg...)
tmp = fld_read(file ; chat)
tmp != data && throw("test failed for file = $file")
rm(file)
if raw
tmp = file[1:(end-4)] * ".raw"
try # because of windows failure here
rm(tmp)
catch
@warn "could not rm raw file $tmp"
@show isfile(tmp)
end
end
true
end
# test writing and reading AVS `.fld` files of all key types
chat = isinteractive()
@testset "write std" begin
dir = mktempdir()
for dtype in (UInt8, Int16, Int32, Float32, Float64)
for endian in (:le, :be)
for raw in (false, true)
chat && @info "dtype=$dtype endian=$endian raw=$raw"
data = convert.(dtype, [5:8; 1:4])
# kludge so windows gets new file name every test:
file = joinpath(dir, "fld-write-test-$dtype-$endian-$raw.fld")
@test fld_write_test1(file, data ; endian, raw,
head = ["dtype=$dtype endian=$endian raw=$raw",],
check=true, chat=false)
end
end
end
end
@testset "write odd" begin
for T in (BigFloat, Float16, BigInt, Int64, Bool)
data = T.([1 0 1])
file = joinpath(dir, "fld-write-test-$T.fld")
@test fld_write_test1(file, data ; check=true, chat=false)
end
end
@testset "fld convert" begin
#=
pairs = (
(BigFloat, Float64),
(Float16, Float32),
(BigInt, Int32),
(Int64, Int32),
(Bool, UInt8),
)
for (in, out) in pairs
data = in.([1 0 1])
@test eltype(fld_write_data_fix(data)) == out
end
=#
@test_throws ArgumentError fld_write_data_fix(Rational.([1 0 1]))
end
# for future testing of reading "multi" external files
@testset "write multi" begin
# file = "../tmp2.fld"
# file = "tmp.fld"
file = joinpath(dir, "fld-write-test-multi.fld")
data = rand(Float32, 7, 9, 2)
file1 = "$(basename(file)).part1"
file2 = "$(basename(file)).part2"
head = [
"# AVS field file"
"ndim=3"
"dim1=7"
"dim2=9"
"dim3=2"
"nspace=3"
"veclen=1"
"data=float"
"field=uniform"
"variable 1 file=2 filetype=multi skip=0"
file1
file2
]
open(file, "w") do fid
for line in head
println(fid, line)
end
end
file1 = joinpath(dirname(file), file1)
file2 = joinpath(dirname(file), file2)
write(file1, data[:,:,1])
write(file2, data[:,:,2])
#=
run(`cat $file`)
run(`ls -l $file1`)
run(`op range $file`)
=#
@test_throws String tmp = fld_read(file) # todo some day...
end
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | code | 265 | # test/runtests.jl
using AVSfldIO
using Test: @test, @testset, detect_ambiguities
list = [
"fld-read.jl"
"fld-write.jl"
"test-io.jl"
]
for file in list
@testset "$file" begin
include(file)
end
end
@test length(detect_ambiguities(AVSfldIO)) == 0
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | code | 553 | #=
test-io.jl
test AVSfldIO. through FileIO
=#
using FileIO: File, @format_str
using Test: @test, @testset, @test_throws
import AVSfldIO
@testset "loadsave" begin
data1 = reshape(Int32.(1:20), 4, 5)
file = tempname() * ".fld"
ff = File{format"AVSfld"}(file)
AVSfldIO.save(ff, data1)
data2 = AVSfldIO.load(ff)
@test data2 == data1
rm(file, force=true)
end
@testset "save type" begin
file = tempname() * ".fld"
ff = File{format"AVSfld"}(file)
@test_throws ArgumentError AVSfldIO.save(ff, "string")
end
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | docs | 8491 | # AVSfldIO
[![action status][action-img]][action-url]
[![pkgeval status][pkgeval-img]][pkgeval-url]
[![codecov][codecov-img]][codecov-url]
[![license][license-img]][license-url]
[![docs stable][docs-stable-img]][docs-stable-url]
[![docs dev][docs-dev-img]][docs-dev-url]
https://github.com/JeffFessler/AVSfldIO.jl.git
File IO for AVS format "field" data files
with extension `.fld`
for the
[Julia language](https://julialang.org),
in conjunction with the
[FileIO package](https://github.com/JuliaIO/FileIO.jl).
This data format supports N-dimensional arrays of real numbers.
## Methods
Following the
[FileIO API](https://juliaio.github.io/FileIO.jl/stable/implementing),
this package provides (but does not export) methods
* `AVSfldIO.load(filename)`
* `AVSfldIO.save(filename, data)`
It does export the following methods:
* `header, is_external_file, fid = fld_open(file ; dir="", chat=false)`
* `header = fld_header(file::String ; dir="", chat=false)`
* `data = fld_read(file::String ; dir="", chat=false)`
* `fld_write(file, data ; kwargs...)`
Use `chat=true` for verbose debugging output.
Use `dir=somepath` to prepend a path to `file`.
See docstrings for more details.
## Usage
Most users will simply use the `FileIO` `load` and `save` methods
as follows.
```julia
using FileIO # need version ≥ 1.9
data1 = rand(6,7,8) # random 3D data
file = "test.fld"
save(file, data1) # will throw error if the file exists already
data2 = load(file)
@assert data1 == data2
```
## File format overview
The AVS `.fld` data format
comes in two flavors.
In the AVS "internal" format:
* an ASCII header is at the top of the file,
* the header is followed by two "form-feed" (`^L`) characters,
* which are then followed by the data in binary format.
In the AVS "external" format,
the header and the data are in separate files,
and the ASCII header file includes the name of the data file.
The data file can contain either ASCII or binary data.
### AVS internal format
For a `128 × 64` array
(first dimension varies fastest)
consisting of short integers
(`Int16` in Julia),
the format of the AVS internal header would be:
```
# AVS field file
ndim=2
dim1=128
dim2=64
nspace=2
veclen=1
data=short
field=uniform
```
followed by the two form feeds,
and then the `128 × 64` short integers
in binary format.
For a 3D array of size `128 × 64 × 20`
of 32-bit floating point numbers
with the host CPU endianness,
the header is
```
# AVS field file
ndim=3
dim1=128
dim2=64
dim3=20
nspace=3
veclen=1
data=float
field=uniform
```
The `save` method in this library
writes to the AVS internal format by default,
and the filename must end with the extension `.fld`.
### AVS external format
Now suppose you have stored the above array data
in a binary file named, say, `sino.dat`
with some home-brew header in it that consists
of, say, 1999 bytes.
And suppose you do not want to convert from home-brew format
to AVS internal format.
Then you can use the AVS external format
by creating an ASCII file named, say,
`sino.fld`
containing:
```
# AVS field file
ndim=2
dim1=128
dim2=64
nspace=2
veclen=1
data=short
field=uniform
variable 1 file=sino.dat filetype=binary skip=1999
```
You can add additional comments
to these headers
using lines that begin with `#`.
The `skip=1999` option
indicates that there is a `1999` byte header to be skipped
before reading the binary data.
This format does not allow for additional headers buried within the data.
If there is no binary header,
then you can omit the `skip=0` line altogether.
If your data is in ASCII format (hopefully not),
then replace
`filetype=binary`
with
`filetype=ascii`.
However,
for ASCII data,
the `skip=` option
refers to ASCII entries, not bytes.
See table below
for supported types in the
`data=...`
line.
The complete AVS `.fld` format
includes other features
that almost certainly are not supported
by this IO library.
This library supports
some extensions that are not standard AVS
but are very handy,
like a single 3D header file
that points to multiple 2D files
that get treated as a single entity.
More documentation coming on request.
## Magic bytes
It is convention that an AVS `.fld` file begins with
`# AVS` in the first line,
as illustrated in the examples above,
so the interface to this library
in
[FileIO.jl](https://github.com/JuliaIO/FileIO.jl)
uses that 5-byte string
as the
["magic bytes"](https://en.wikipedia.org/wiki/List_of_file_signatures)
or
["magic number"](https://en.wikipedia.org/wiki/File_format#Magic_number)
for this file type.
If you have a file that does not have that string as the start of its header,
then simply add it with an editor
(including a newline at the end).
## Data types
The following table shows the supported options
for the `data=` field in the header.
The options that end in `_le` or `_be` or `_sun` are "extensions"
designed for portability, because options like `int`
are not portable between hosts with different
[endianness](https://en.wikipedia.org/wiki/Endianness).
| format | Julia type | endian | bytes |
| :--- | :--- | :---: | :---: |
| `byte` | `UInt8` | n/a | `1` |
| `short_be` | `UInt16` | `be` | `2` |
| `short_sun` | `UInt16` | `be` | `2` |
| `xdr_short` | `UInt16` | `be` | `2` |
| `short_le` | `UInt16` | `le` | `2` |
| `int` | `Int32` | `?` | `4` |
| `int_le` | `Int32` | `le` | `4` |
| `int_be` | `Int32` | `be` | `4` |
| `xdr_int` | `Int32` | `be` | `4` |
| `float` | `Float32` | `?` | `4` |
| `float_le` | `Float32` | `le` | `4` |
| `float_be` | `Float32` | `be` | `4` |
| `xdr_float` | `Float32` | `be` | `4` |
| `double` | `Float64` | `?` | `8` |
| `double_le` | `Float64` | `le` | `8` |
| `double_be` | `Float64` | `be` | `8` |
| `xdr_double` | `Float64` | `be` | `8` |
Entries with `?` are native to the host CPU and thus not portable.
The `byte` format is unsigned 8 bits.
The following table shows the saved output `data=` field
for various input Julia data fields,
assuming little endian (`:le`) default
to `AVSfldIO.fld_write`.
| Julia type | `data` | note |
| :--- | :--- | :--- |
| `Bool` | `byte` | |
| `UInt8` | `byte` | |
| `Int16` | `short_le` | |
| `Int32` | `int_le` | |
| `Int64` | `int_le` | (downgraded) |
| `Float16` | `float_le` | (upgraded) |
| `Float32` | `float_le` |
| `Float64` | `double_le` |
| `BigFloat` | `double_le` | (downgraded) |
## History
The "application visualization system" (AVS)
https://www.avs.com
was an interactive graphics and computation framework
developed in the early 1990s
and used widely in the medical imaging community.
See the article at https://doi.org/10.1109/38.31462 for an overview.
AVS data files have the extension `.fld`
and many software frameworks provide file IO support
for this format.
* https://doi.org/10.1109/38.31462
* https://www.ks.uiuc.edu/Research/vmd/plugins/molfile/avsplugin.html
* https://dav.lbl.gov/archive/NERSC/Software/express/help6.1/help/reference/dvmac/Field_Fi.htm
* http://paulbourke.net/dataformats/field/
* http://surferhelp.goldensoftware.com/subsys/subsys_avs_field_file_desc.htm
* https://lanl.github.io/LaGriT/pages/docs/read_avs.html
## Authors
[Jeff Fessler](https://web.eecs.umich.edu/~fessler)
and his group at the University of Michigan.
<!-- URLs -->
[action-img]: https://github.com/JeffFessler/AVSfldIO.jl/workflows/Unit%20test/badge.svg
[action-url]: https://github.com/JeffFessler/AVSfldIO.jl/actions
[build-img]: https://github.com/JeffFessler/AVSfldIO.jl/workflows/CI/badge.svg?branch=main
[build-url]: https://github.com/JeffFessler/AVSfldIO.jl/actions?query=workflow%3ACI+branch%3Amain
[pkgeval-img]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/A/AVSfldIO.svg
[pkgeval-url]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/A/AVSfldIO.html
[codecov-img]: https://codecov.io/github/JeffFessler/AVSfldIO.jl/coverage.svg?branch=main
[codecov-url]: https://codecov.io/github/JeffFessler/AVSfldIO.jl?branch=main
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://JeffFessler.github.io/AVSfldIO.jl/stable
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[docs-dev-url]: https://JeffFessler.github.io/AVSfldIO.jl/dev
[license-img]: http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat
[license-url]: LICENSE
<!--
[![coveralls][coveralls-img]][coveralls-url]
[coveralls-img]: https://coveralls.io/repos/JeffFessler/AVSfldIO.jl/badge.svg?branch=main
[coveralls-url]: https://coveralls.io/github/JeffFessler/AVSfldIO.jl?branch=main
-->
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.2.1 | f47f9477b6aaf284212bd6745ed7050616bdaec4 | docs | 303 | ```@meta
CurrentModule = AVSfldIO
```
# AVSfldIO.jl Documentation
## Contents
```@contents
```
## Overview
File I/O routines for AVS `.fld` format data files;
see
[(AVSfldIO)](https://github.com/JeffFessler/AVSfldIO.jl)
## Index
```@index
```
## Functions
```@autodocs
Modules = [AVSfldIO]
```
| AVSfldIO | https://github.com/JeffFessler/AVSfldIO.jl.git |
|
[
"MIT"
] | 0.1.1 | 05c1471a9064419e22743e97453bb42773d2f07d | code | 48635 | ### A Pluto.jl notebook ###
# v0.19.36
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try
Base.loaded_modules[Base.PkgId(
Base.UUID("6e696c72-6542-2067-7265-42206c756150"),
"AbstractPlutoDingetjes",
)].Bonds.initial_value
catch
b -> missing
end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ 126a6f2e-adfc-11ee-2def-eb30c37b09cc
begin
using DataFrames
using Measures
using MetOfficeStationData
using Plots
using PlutoUI
using Statistics
end
# ╔═╡ 813f69f9-be5a-418a-ad0a-4e9c9aae79c3
md"""# Met Office Historic Station Data
Please select a station:"""
# ╔═╡ 8c7f0c97-73e2-48e9-875d-9c33e7ada588
md"## Rainfall"
# ╔═╡ 2e4459fe-4764-4595-bad5-bf20b3d5e3e8
md"## Temperature"
# ╔═╡ 22a0b724-684c-4bc0-96bb-5821b17df97c
md"## Wettest years"
# ╔═╡ 661decfd-f455-42a2-a81c-d2ceba154609
metadata = MetOfficeStationData.get_station_metadata();
# ╔═╡ 1c694257-113b-4ec2-8d77-12dbe67e30f3
@bind short_name Select(metadata[!, :short_name])
# ╔═╡ 6efbcc3e-5054-4267-88d2-ea7641c51879
begin
row = only(filter(:short_name => ==(short_name), metadata))
md"""
- **Station**: $(row[:name])
- **Location (lat, lon)**: $(row[:lat]), $(row[:lon])
- **First data**: $(row[:year_start])
"""
end
# ╔═╡ e5f8d573-3859-41cf-8573-f70633dfab39
frame = MetOfficeStationData.get_frame(short_name);
# ╔═╡ deb3e2d5-53dc-4849-b40d-1180817bd17f
annual_rain = dropmissing(combine(groupby(frame, :yyyy), :rain => sum => :rain));
# ╔═╡ 81b8172a-8ce9-470e-8103-71c7c0f3d9f4
let
p1 = begin
plot(; xlabel="Month", ylabel="Cumulative rainfall / mm", legend=:topleft)
g = groupby(frame, :yyyy; sort=true)
for (i, key) in enumerate(keys(g))
year = only(key)
df = g[key]
c, alpha, lw, ls, label = if i == length(g)
:blue, 1, 3, :solid, year
elseif i == (length(g) - 1)
:purple, 1, 2, :dash, year
elseif i == (length(g) - 2)
:red, 1, 2, :dashdot, year
elseif i == (length(g) - 3)
:orange, 1, 2, :dashdotdot, year
elseif i == (length(g) - 4)
:grey, 0.3, 1, :solid, "<$(year + 1)"
else
:grey, 0.3, 1, :solid, nothing
end
plot!(
vcat([0], df[!, :mm]),
vcat([0], cumsum(df[!, :rain]));
lw,
ls,
c,
alpha,
label,
xticks=1:12,
yminorgrid=true,
)
end
Plots.current()
end
p2 = plot(
annual_rain[!, :yyyy],
annual_rain[!, :rain];
xlabel="Year",
ylabel="Annual rainfall / mm",
legend=nothing,
)
plot(p1, p2; size=(800, 400), margin=3mm)
end
# ╔═╡ 1da54919-2eae-4da5-9149-f361fcbda082
first(sort(annual_rain, :rain; rev=true), 5)
# ╔═╡ b72a765b-d0be-46a5-9137-e5e10d80ab3d
annual_temp = dropmissing(
combine(groupby(frame, :yyyy), :tmax => mean => :tmax, :tmin => mean => :tmin)
);
# ╔═╡ d708347b-a84a-4b17-bfb6-6cdaec4c5e01
let
p1 = begin
plot(;
title="Temperature seasonality",
xlabel="Month",
ylabel="Mean temperature / °C",
legend=:topleft,
)
g = groupby(frame, :yyyy; sort=true)
for (i, key) in enumerate(keys(g))
year = only(key)
df = g[key]
c, alpha, lw, ls, label = if i == length(g)
:blue, 1, 3, :solid, year
elseif i == (length(g) - 1)
:purple, 1, 2, :dash, year
elseif i == (length(g) - 2)
:red, 1, 2, :dashdot, year
elseif i == (length(g) - 3)
:orange, 1, 2, :dashdotdot, year
elseif i == (length(g) - 4)
:grey, 0.3, 1, :solid, "<$(year + 1)"
else
:grey, 0.3, 1, :solid, nothing
end
plot!(
vcat([0], df[!, :mm]),
vcat([0], (df[!, :tmin] .+ df[!, :tmax]) / 2);
lw,
ls,
c,
alpha,
label,
xticks=1:12,
yminorgrid=true,
)
end
Plots.current()
end
p2 = begin
plot(
annual_temp[!, :yyyy],
annual_temp[!, :tmin];
title="Annual mean temperature",
xlabel="Year",
ylabel="Mean temperature / °C",
label="Daily minimum",
)
plot!(annual_temp[!, :yyyy], annual_temp[!, :tmax]; label="Daily maximum")
end
plot(p1, p2; size=(800, 400), margin=3mm)
end
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
Measures = "442fdcdd-2543-5da2-b0f3-8c86c306513e"
MetOfficeStationData = "33561aa0-85d4-466e-be0d-17c227566225"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[compat]
DataFrames = "~1.6.1"
Measures = "~0.3.2"
MetOfficeStationData = "~0.1.0"
Plots = "~1.39.0"
PlutoUI = "~0.7.54"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.10.0"
manifest_format = "2.0"
project_hash = "f265973d5e261d8392e40c69fc3ec21873b9ce05"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "c278dfab760520b8bb7e9511b968bf4ba38b7acc"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.2.3"
[[deps.AbstractTrees]]
git-tree-sha1 = "faa260e4cb5aba097a73fab382dd4b5819d8ec8c"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.4.4"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.BitFlags]]
git-tree-sha1 = "2dc09997850d68179b69dafb58ae806167a32b1b"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.8"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"
[[deps.CSV]]
deps = ["CodecZlib", "Dates", "FilePathsBase", "InlineStrings", "Mmap", "Parsers", "PooledArrays", "PrecompileTools", "SentinelArrays", "Tables", "Unicode", "WeakRefStrings", "WorkerUtilities"]
git-tree-sha1 = "679e69c611fff422038e9e21e270c4197d49d918"
uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
version = "0.10.12"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "4b859a208b2397a7a623a03449e4636bdb17bcf2"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.16.1+1"
[[deps.Cascadia]]
deps = ["AbstractTrees", "Gumbo"]
git-tree-sha1 = "c0769cbd930aea932c0912c4d2749c619a263fc1"
uuid = "54eefc05-d75b-58de-a785-1a3403f0919f"
version = "1.0.2"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "cd67fc487743b2f0fd4380d4cbd3a24660d0eec8"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.3"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"]
git-tree-sha1 = "67c1f244b991cad9b0aa4b7540fb758c2488b129"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.24.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.4"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "Requires", "Statistics", "TensorCore"]
git-tree-sha1 = "a1f44953f2382ebb937d60dafbe2deea4bd23249"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.10.0"
[deps.ColorVectorSpace.extensions]
SpecialFunctionsExt = "SpecialFunctions"
[deps.ColorVectorSpace.weakdeps]
SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "fc08e5930ee9a4e03f84bfb5211cb54e7769758a"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.10"
[[deps.Compat]]
deps = ["TOML", "UUIDs"]
git-tree-sha1 = "75bd5b6fc5089df449b5d35fa501c846c9b6549b"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.12.0"
weakdeps = ["Dates", "LinearAlgebra"]
[deps.Compat.extensions]
CompatLinearAlgebraExt = "LinearAlgebra"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.0.5+1"
[[deps.ConcurrentUtilities]]
deps = ["Serialization", "Sockets"]
git-tree-sha1 = "8cfa272e8bdedfa88b6aefbbca7c19f1befac519"
uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb"
version = "2.3.0"
[[deps.Contour]]
git-tree-sha1 = "d05d9e7b7aedff4e5b51a029dced05cfb6125781"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.6.2"
[[deps.Crayons]]
git-tree-sha1 = "249fe38abf76d48563e2f4556bebd215aa317e15"
uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
version = "4.1.1"
[[deps.DataAPI]]
git-tree-sha1 = "8da84edb865b0b5b0100c0666a9bc9a0b71c553c"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.15.0"
[[deps.DataFrames]]
deps = ["Compat", "DataAPI", "DataStructures", "Future", "InlineStrings", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrecompileTools", "PrettyTables", "Printf", "REPL", "Random", "Reexport", "SentinelArrays", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"]
git-tree-sha1 = "04c738083f29f86e62c8afc341f0967d8717bdb8"
uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
version = "1.6.1"
[[deps.DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "ac67408d9ddf207de5cfa9a97e114352430f01ed"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.16"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.DelimitedFiles]]
deps = ["Mmap"]
git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae"
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
version = "1.9.1"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.3"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.EpollShim_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "8e9441ee83492030ace98f9789a654a6d0b1f643"
uuid = "2702e6a9-849d-5ed8-8c21-79e8b8f9ee43"
version = "0.0.20230411+0"
[[deps.ExceptionUnwrapping]]
deps = ["Test"]
git-tree-sha1 = "dcb08a0d93ec0b1cdc4af184b26b591e9695423a"
uuid = "460bff9d-24e4-43bc-9d9f-a8973cb893f4"
version = "0.1.10"
[[deps.Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "4558ab818dcceaab612d1bb8c19cee87eda2b83c"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.5.0+0"
[[deps.ExprTools]]
git-tree-sha1 = "27415f162e6028e81c72b82ef756bf321213b6ec"
uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04"
version = "0.1.10"
[[deps.FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.1"
[[deps.FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "PCRE2_jll", "Zlib_jll", "libaom_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "466d45dc38e15794ec7d5d63ec03d776a9aff36e"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.4.4+1"
[[deps.FilePathsBase]]
deps = ["Compat", "Dates", "Mmap", "Printf", "Test", "UUIDs"]
git-tree-sha1 = "9f00e42f8d99fdde64d40c8ea5d14269a2e2c1aa"
uuid = "48062228-2e41-5def-b9a4-89aafe57970f"
version = "0.9.21"
[[deps.FileWatching]]
uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee"
[[deps.FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[deps.Fontconfig_jll]]
deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "21efd19106a55620a188615da6d3d06cd7f6ee03"
uuid = "a3f928ae-7b40-5064-980b-68af3947d34b"
version = "2.13.93+0"
[[deps.Formatting]]
deps = ["Printf"]
git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8"
uuid = "59287772-0a20-5a39-b81b-1366585eb4c0"
version = "0.4.2"
[[deps.FreeType2_jll]]
deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Zlib_jll"]
git-tree-sha1 = "d8db6a5a2fe1381c1ea4ef2cab7c69c2de7f9ea0"
uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7"
version = "2.13.1+0"
[[deps.FriBidi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91"
uuid = "559328eb-81f9-559d-9380-de523a88c83c"
version = "1.0.10+0"
[[deps.Future]]
deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"
[[deps.GLFW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Xorg_libXcursor_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll"]
git-tree-sha1 = "ff38ba61beff76b8f4acad8ab0c97ef73bb670cb"
uuid = "0656b61e-2033-5cc2-a64a-77c0f6c09b89"
version = "3.3.9+0"
[[deps.GR]]
deps = ["Artifacts", "Base64", "DelimitedFiles", "Downloads", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Pkg", "Preferences", "Printf", "Random", "Serialization", "Sockets", "TOML", "Tar", "Test", "UUIDs", "p7zip_jll"]
git-tree-sha1 = "27442171f28c952804dede8ff72828a96f2bfc1f"
uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71"
version = "0.72.10"
[[deps.GR_jll]]
deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "FreeType2_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Qt6Base_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "025d171a2847f616becc0f84c8dc62fe18f0f6dd"
uuid = "d2c73de3-f751-5644-a686-071e5b155ba9"
version = "0.72.10+0"
[[deps.Gettext_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "9b02998aba7bf074d14de89f9d37ca24a1a0b046"
uuid = "78b55507-aeef-58d4-861c-77aaff3498b1"
version = "0.21.0+0"
[[deps.Glib_jll]]
deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE2_jll", "Zlib_jll"]
git-tree-sha1 = "e94c92c7bf4819685eb80186d51c43e71d4afa17"
uuid = "7746bdde-850d-59dc-9ae8-88ece973131d"
version = "2.76.5+0"
[[deps.Graphite2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "344bf40dcab1073aca04aa0df4fb092f920e4011"
uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472"
version = "1.3.14+0"
[[deps.Grisu]]
git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2"
uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe"
version = "1.0.2"
[[deps.Gumbo]]
deps = ["AbstractTrees", "Gumbo_jll", "Libdl"]
git-tree-sha1 = "a1a138dfbf9df5bace489c7a9d5196d6afdfa140"
uuid = "708ec375-b3d6-5a57-a7ce-8257bf98657a"
version = "0.8.2"
[[deps.Gumbo_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "29070dee9df18d9565276d68a596854b1764aa38"
uuid = "528830af-5a63-567c-a44a-034ed33b8444"
version = "0.10.2+0"
[[deps.HTTP]]
deps = ["Base64", "CodecZlib", "ConcurrentUtilities", "Dates", "ExceptionUnwrapping", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "OpenSSL", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"]
git-tree-sha1 = "abbbb9ec3afd783a7cbd82ef01dcd088ea051398"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "1.10.1"
[[deps.HarfBuzz_jll]]
deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg"]
git-tree-sha1 = "129acf094d168394e80ee1dc4bc06ec835e510a3"
uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566"
version = "2.8.1+1"
[[deps.Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.4"
[[deps.HypertextLiteral]]
deps = ["Tricks"]
git-tree-sha1 = "7134810b1afce04bbc1045ca1985fbe81ce17653"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.5"
[[deps.IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "d75853a0bdbfb1ac815478bacd89cd27b550ace6"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.3"
[[deps.InlineStrings]]
deps = ["Parsers"]
git-tree-sha1 = "9cc2baf75c6d09f9da536ddf58eb2f29dedaf461"
uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48"
version = "1.4.0"
[[deps.InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[deps.InvertedIndices]]
git-tree-sha1 = "0dc7b50b8d436461be01300fd8cd45aa0274b038"
uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f"
version = "1.3.0"
[[deps.IrrationalConstants]]
git-tree-sha1 = "630b497eafcc20001bba38a4651b327dcfc491d2"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.2.2"
[[deps.IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"
[[deps.JLFzf]]
deps = ["Pipe", "REPL", "Random", "fzf_jll"]
git-tree-sha1 = "a53ebe394b71470c7f97c2e7e170d51df21b17af"
uuid = "1019f520-868f-41f5-a6de-eb00f4b6a39c"
version = "0.1.7"
[[deps.JLLWrappers]]
deps = ["Artifacts", "Preferences"]
git-tree-sha1 = "7e5d6779a1e09a36db2a7b6cff50942a0a7d0fca"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.5.0"
[[deps.JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.4"
[[deps.JpegTurbo_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "60b1194df0a3298f460063de985eae7b01bc011a"
uuid = "aacddb02-875f-59d6-b918-886e6ef4fbf8"
version = "3.0.1+0"
[[deps.LAME_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "f6250b16881adf048549549fba48b1161acdac8c"
uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d"
version = "3.100.1+0"
[[deps.LERC_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "bf36f528eec6634efc60d7ec062008f171071434"
uuid = "88015f11-f218-50d7-93a8-a6af411a945d"
version = "3.0.0+1"
[[deps.LLVMOpenMP_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "d986ce2d884d49126836ea94ed5bfb0f12679713"
uuid = "1d63c593-3942-5779-bab2-d838dc0a180e"
version = "15.0.7+0"
[[deps.LZO_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e5b909bcf985c5e2605737d2ce278ed791b89be6"
uuid = "dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac"
version = "2.10.1+0"
[[deps.LaTeXStrings]]
git-tree-sha1 = "50901ebc375ed41dbf8058da26f9de442febbbec"
uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
version = "1.3.1"
[[deps.Latexify]]
deps = ["Formatting", "InteractiveUtils", "LaTeXStrings", "MacroTools", "Markdown", "OrderedCollections", "Printf", "Requires"]
git-tree-sha1 = "f428ae552340899a935973270b8d98e5a31c49fe"
uuid = "23fbe1c1-3f47-55db-b15f-69d7ec21a316"
version = "0.16.1"
[deps.Latexify.extensions]
DataFramesExt = "DataFrames"
SymEngineExt = "SymEngine"
[deps.Latexify.weakdeps]
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
SymEngine = "123dc426-2d89-5057-bbad-38513e3affd8"
[[deps.LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
version = "0.6.4"
[[deps.LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
version = "8.4.0+0"
[[deps.LibGit2]]
deps = ["Base64", "LibGit2_jll", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[deps.LibGit2_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll"]
uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5"
version = "1.6.4+0"
[[deps.LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
version = "1.11.0+1"
[[deps.Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[deps.Libffi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "0b4a5d71f3e5200a7dff793393e09dfc2d874290"
uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490"
version = "3.2.2+1"
[[deps.Libgcrypt_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgpg_error_jll", "Pkg"]
git-tree-sha1 = "64613c82a59c120435c067c2b809fc61cf5166ae"
uuid = "d4300ac3-e22c-5743-9152-c294e39db1e4"
version = "1.8.7+0"
[[deps.Libglvnd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll", "Xorg_libXext_jll"]
git-tree-sha1 = "6f73d1dd803986947b2c750138528a999a6c7733"
uuid = "7e76a0d4-f3c7-5321-8279-8d96eeed0f29"
version = "1.6.0+0"
[[deps.Libgpg_error_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c333716e46366857753e273ce6a69ee0945a6db9"
uuid = "7add5ba3-2f88-524e-9cd5-f83b8a55f7b8"
version = "1.42.0+0"
[[deps.Libiconv_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "f9557a255370125b405568f9767d6d195822a175"
uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531"
version = "1.17.0+0"
[[deps.Libmount_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "9c30530bf0effd46e15e0fdcf2b8636e78cbbd73"
uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9"
version = "2.35.0+0"
[[deps.Libtiff_jll]]
deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "LERC_jll", "Libdl", "XZ_jll", "Zlib_jll", "Zstd_jll"]
git-tree-sha1 = "2da088d113af58221c52828a80378e16be7d037a"
uuid = "89763e89-9b03-5906-acba-b20f662cd828"
version = "4.5.1+1"
[[deps.Libuuid_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "7f3efec06033682db852f8b3bc3c1d2b0a0ab066"
uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700"
version = "2.36.0+0"
[[deps.LinearAlgebra]]
deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[deps.LogExpFunctions]]
deps = ["DocStringExtensions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "7d6dd4e9212aebaeed356de34ccf262a3cd415aa"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.26"
[deps.LogExpFunctions.extensions]
LogExpFunctionsChainRulesCoreExt = "ChainRulesCore"
LogExpFunctionsChangesOfVariablesExt = "ChangesOfVariables"
LogExpFunctionsInverseFunctionsExt = "InverseFunctions"
[deps.LogExpFunctions.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
ChangesOfVariables = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112"
[[deps.Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[deps.LoggingExtras]]
deps = ["Dates", "Logging"]
git-tree-sha1 = "c1dd6d7978c12545b4179fb6153b9250c96b0075"
uuid = "e6f89c97-d47a-5376-807f-9c37f3926c36"
version = "1.0.3"
[[deps.MIMEs]]
git-tree-sha1 = "65f28ad4b594aebe22157d6fac869786a255b7eb"
uuid = "6c6e2e6c-3030-632d-7369-2d6c69616d65"
version = "0.1.4"
[[deps.MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "b211c553c199c111d998ecdaf7623d1b89b69f93"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.12"
[[deps.Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[deps.MbedTLS]]
deps = ["Dates", "MbedTLS_jll", "MozillaCACerts_jll", "NetworkOptions", "Random", "Sockets"]
git-tree-sha1 = "c067a280ddc25f196b5e7df3877c6b226d390aaf"
uuid = "739be429-bea8-5141-9913-cc70e7f3736d"
version = "1.1.9"
[[deps.MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
version = "2.28.2+1"
[[deps.Measures]]
git-tree-sha1 = "c13304c81eec1ed3af7fc20e75fb6b26092a1102"
uuid = "442fdcdd-2543-5da2-b0f3-8c86c306513e"
version = "0.3.2"
[[deps.MetOfficeStationData]]
deps = ["CSV", "Cascadia", "DataFrames", "Downloads", "Gumbo", "Mocking"]
git-tree-sha1 = "065886e3cfc18051727ad8bd29a376c1e3b859cd"
uuid = "33561aa0-85d4-466e-be0d-17c227566225"
version = "0.1.0"
[[deps.Missings]]
deps = ["DataAPI"]
git-tree-sha1 = "f66bdc5de519e8f8ae43bdc598782d35a25b1272"
uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28"
version = "1.1.0"
[[deps.Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[deps.Mocking]]
deps = ["Compat", "ExprTools"]
git-tree-sha1 = "4cc0c5a83933648b615c36c2b956d94fda70641e"
uuid = "78c3b35d-d492-501b-9361-3d52fe80e533"
version = "0.7.7"
[[deps.MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
version = "2023.1.10"
[[deps.NaNMath]]
deps = ["OpenLibm_jll"]
git-tree-sha1 = "0877504529a3e5c3343c6f8b4c0381e57e4387e4"
uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3"
version = "1.0.2"
[[deps.NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
version = "1.2.0"
[[deps.Ogg_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "887579a3eb005446d514ab7aeac5d1d027658b8f"
uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051"
version = "1.3.5+1"
[[deps.OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"
version = "0.3.23+2"
[[deps.OpenLibm_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "05823500-19ac-5b8b-9628-191a04bc5112"
version = "0.8.1+2"
[[deps.OpenSSL]]
deps = ["BitFlags", "Dates", "MozillaCACerts_jll", "OpenSSL_jll", "Sockets"]
git-tree-sha1 = "51901a49222b09e3743c65b8847687ae5fc78eb2"
uuid = "4d8831e6-92b7-49fb-bdf8-b643e874388c"
version = "1.4.1"
[[deps.OpenSSL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "cc6e1927ac521b659af340e0ca45828a3ffc748f"
uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95"
version = "3.0.12+0"
[[deps.Opus_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "51a08fb14ec28da2ec7a927c4337e4332c2a4720"
uuid = "91d4177d-7536-5919-b921-800302f37372"
version = "1.3.2+0"
[[deps.OrderedCollections]]
git-tree-sha1 = "dfdf5519f235516220579f949664f1bf44e741c5"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.6.3"
[[deps.PCRE2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "efcefdf7-47ab-520b-bdef-62a2eaa19f15"
version = "10.42.0+1"
[[deps.Parsers]]
deps = ["Dates", "PrecompileTools", "UUIDs"]
git-tree-sha1 = "8489905bcdbcfac64d1daa51ca07c0d8f0283821"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.8.1"
[[deps.Pipe]]
git-tree-sha1 = "6842804e7867b115ca9de748a0cf6b364523c16d"
uuid = "b98c9c47-44ae-5843-9183-064241ee97a0"
version = "1.3.0"
[[deps.Pixman_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "LLVMOpenMP_jll", "Libdl"]
git-tree-sha1 = "64779bc4c9784fee475689a1752ef4d5747c5e87"
uuid = "30392449-352a-5448-841d-b1acce4e97dc"
version = "0.42.2+0"
[[deps.Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
version = "1.10.0"
[[deps.PlotThemes]]
deps = ["PlotUtils", "Statistics"]
git-tree-sha1 = "1f03a2d339f42dca4a4da149c7e15e9b896ad899"
uuid = "ccf2f8ad-2431-5c83-bf29-c5338b663b6a"
version = "3.1.0"
[[deps.PlotUtils]]
deps = ["ColorSchemes", "Colors", "Dates", "PrecompileTools", "Printf", "Random", "Reexport", "Statistics"]
git-tree-sha1 = "862942baf5663da528f66d24996eb6da85218e76"
uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043"
version = "1.4.0"
[[deps.Plots]]
deps = ["Base64", "Contour", "Dates", "Downloads", "FFMPEG", "FixedPointNumbers", "GR", "JLFzf", "JSON", "LaTeXStrings", "Latexify", "LinearAlgebra", "Measures", "NaNMath", "Pkg", "PlotThemes", "PlotUtils", "PrecompileTools", "Preferences", "Printf", "REPL", "Random", "RecipesBase", "RecipesPipeline", "Reexport", "RelocatableFolders", "Requires", "Scratch", "Showoff", "SparseArrays", "Statistics", "StatsBase", "UUIDs", "UnicodeFun", "UnitfulLatexify", "Unzip"]
git-tree-sha1 = "ccee59c6e48e6f2edf8a5b64dc817b6729f99eb5"
uuid = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
version = "1.39.0"
[deps.Plots.extensions]
FileIOExt = "FileIO"
GeometryBasicsExt = "GeometryBasics"
IJuliaExt = "IJulia"
ImageInTerminalExt = "ImageInTerminal"
UnitfulExt = "Unitful"
[deps.Plots.weakdeps]
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
GeometryBasics = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a"
ImageInTerminal = "d8c32880-2388-543b-8c61-d9f865259254"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
[[deps.PlutoUI]]
deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "FixedPointNumbers", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "MIMEs", "Markdown", "Random", "Reexport", "URIs", "UUIDs"]
git-tree-sha1 = "bd7c69c7f7173097e7b5e1be07cee2b8b7447f51"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.54"
[[deps.PooledArrays]]
deps = ["DataAPI", "Future"]
git-tree-sha1 = "36d8b4b899628fb92c2749eb488d884a926614d3"
uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720"
version = "1.4.3"
[[deps.PrecompileTools]]
deps = ["Preferences"]
git-tree-sha1 = "03b4c25b43cb84cee5c90aa9b5ea0a78fd848d2f"
uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a"
version = "1.2.0"
[[deps.Preferences]]
deps = ["TOML"]
git-tree-sha1 = "00805cd429dcb4870060ff49ef443486c262e38e"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.4.1"
[[deps.PrettyTables]]
deps = ["Crayons", "LaTeXStrings", "Markdown", "PrecompileTools", "Printf", "Reexport", "StringManipulation", "Tables"]
git-tree-sha1 = "88b895d13d53b5577fd53379d913b9ab9ac82660"
uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d"
version = "2.3.1"
[[deps.Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[deps.Qt6Base_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Fontconfig_jll", "Glib_jll", "JLLWrappers", "Libdl", "Libglvnd_jll", "OpenSSL_jll", "Vulkan_Loader_jll", "Xorg_libSM_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Xorg_libxcb_jll", "Xorg_xcb_util_cursor_jll", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_keysyms_jll", "Xorg_xcb_util_renderutil_jll", "Xorg_xcb_util_wm_jll", "Zlib_jll", "libinput_jll", "xkbcommon_jll"]
git-tree-sha1 = "37b7bb7aabf9a085e0044307e1717436117f2b3b"
uuid = "c0090381-4147-56d7-9ebc-da0b1113ec56"
version = "6.5.3+1"
[[deps.REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[deps.Random]]
deps = ["SHA"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[deps.RecipesBase]]
deps = ["PrecompileTools"]
git-tree-sha1 = "5c3d09cc4f31f5fc6af001c250bf1278733100ff"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "1.3.4"
[[deps.RecipesPipeline]]
deps = ["Dates", "NaNMath", "PlotUtils", "PrecompileTools", "RecipesBase"]
git-tree-sha1 = "45cf9fd0ca5839d06ef333c8201714e888486342"
uuid = "01d81517-befc-4cb6-b9ec-a95719d0359c"
version = "0.6.12"
[[deps.Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[deps.RelocatableFolders]]
deps = ["SHA", "Scratch"]
git-tree-sha1 = "ffdaf70d81cf6ff22c2b6e733c900c3321cab864"
uuid = "05181044-ff0b-4ac5-8273-598c1e38db00"
version = "1.0.1"
[[deps.Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.3.0"
[[deps.SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
version = "0.7.0"
[[deps.Scratch]]
deps = ["Dates"]
git-tree-sha1 = "3bac05bc7e74a75fd9cba4295cde4045d9fe2386"
uuid = "6c6a2e73-6563-6170-7368-637461726353"
version = "1.2.1"
[[deps.SentinelArrays]]
deps = ["Dates", "Random"]
git-tree-sha1 = "0e7508ff27ba32f26cd459474ca2ede1bc10991f"
uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c"
version = "1.4.1"
[[deps.Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[deps.Showoff]]
deps = ["Dates", "Grisu"]
git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de"
uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f"
version = "1.0.3"
[[deps.SimpleBufferStream]]
git-tree-sha1 = "874e8867b33a00e784c8a7e4b60afe9e037b74e1"
uuid = "777ac1f9-54b0-4bf8-805c-2214025038e7"
version = "1.1.0"
[[deps.Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[deps.SortingAlgorithms]]
deps = ["DataStructures"]
git-tree-sha1 = "66e0a8e672a0bdfca2c3f5937efb8538b9ddc085"
uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c"
version = "1.2.1"
[[deps.SparseArrays]]
deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
version = "1.10.0"
[[deps.Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
version = "1.10.0"
[[deps.StatsAPI]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "1ff449ad350c9c4cbc756624d6f8a8c3ef56d3ed"
uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0"
version = "1.7.0"
[[deps.StatsBase]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"]
git-tree-sha1 = "1d77abd07f617c4868c33d4f5b9e1dbb2643c9cf"
uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
version = "0.34.2"
[[deps.StringManipulation]]
deps = ["PrecompileTools"]
git-tree-sha1 = "a04cabe79c5f01f4d723cc6704070ada0b9d46d5"
uuid = "892a3eda-7b42-436c-8928-eab12a02cf0e"
version = "0.3.4"
[[deps.SuiteSparse_jll]]
deps = ["Artifacts", "Libdl", "libblastrampoline_jll"]
uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c"
version = "7.2.1+1"
[[deps.TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
version = "1.0.3"
[[deps.TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"
[[deps.Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "OrderedCollections", "TableTraits"]
git-tree-sha1 = "cb76cf677714c095e535e3501ac7954732aeea2d"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.11.1"
[[deps.Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
version = "1.10.0"
[[deps.TensorCore]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6"
uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50"
version = "0.1.1"
[[deps.Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[deps.TranscodingStreams]]
git-tree-sha1 = "1fbeaaca45801b4ba17c251dd8603ef24801dd84"
uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"
version = "0.10.2"
weakdeps = ["Random", "Test"]
[deps.TranscodingStreams.extensions]
TestExt = ["Test", "Random"]
[[deps.Tricks]]
git-tree-sha1 = "eae1bb484cd63b36999ee58be2de6c178105112f"
uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775"
version = "0.1.8"
[[deps.URIs]]
git-tree-sha1 = "67db6cc7b3821e19ebe75791a9dd19c9b1188f2b"
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
version = "1.5.1"
[[deps.UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[deps.Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[deps.UnicodeFun]]
deps = ["REPL"]
git-tree-sha1 = "53915e50200959667e78a92a418594b428dffddf"
uuid = "1cfade01-22cf-5700-b092-accc4b62d6e1"
version = "0.4.1"
[[deps.Unitful]]
deps = ["Dates", "LinearAlgebra", "Random"]
git-tree-sha1 = "3c793be6df9dd77a0cf49d80984ef9ff996948fa"
uuid = "1986cc42-f94f-5a68-af5c-568840ba703d"
version = "1.19.0"
[deps.Unitful.extensions]
ConstructionBaseUnitfulExt = "ConstructionBase"
InverseFunctionsUnitfulExt = "InverseFunctions"
[deps.Unitful.weakdeps]
ConstructionBase = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112"
[[deps.UnitfulLatexify]]
deps = ["LaTeXStrings", "Latexify", "Unitful"]
git-tree-sha1 = "e2d817cc500e960fdbafcf988ac8436ba3208bfd"
uuid = "45397f5d-5981-4c77-b2b3-fc36d6e9b728"
version = "1.6.3"
[[deps.Unzip]]
git-tree-sha1 = "ca0969166a028236229f63514992fc073799bb78"
uuid = "41fe7b60-77ed-43a1-b4f0-825fd5a5650d"
version = "0.2.0"
[[deps.Vulkan_Loader_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Wayland_jll", "Xorg_libX11_jll", "Xorg_libXrandr_jll", "xkbcommon_jll"]
git-tree-sha1 = "2f0486047a07670caad3a81a075d2e518acc5c59"
uuid = "a44049a8-05dd-5a78-86c9-5fde0876e88c"
version = "1.3.243+0"
[[deps.Wayland_jll]]
deps = ["Artifacts", "EpollShim_jll", "Expat_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "7558e29847e99bc3f04d6569e82d0f5c54460703"
uuid = "a2964d1f-97da-50d4-b82a-358c7fce9d89"
version = "1.21.0+1"
[[deps.Wayland_protocols_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "93f43ab61b16ddfb2fd3bb13b3ce241cafb0e6c9"
uuid = "2381bf8a-dfd0-557d-9999-79630e7b1b91"
version = "1.31.0+0"
[[deps.WeakRefStrings]]
deps = ["DataAPI", "InlineStrings", "Parsers"]
git-tree-sha1 = "b1be2855ed9ed8eac54e5caff2afcdb442d52c23"
uuid = "ea10d353-3f73-51f8-a26c-33c1cb351aa5"
version = "1.4.2"
[[deps.WorkerUtilities]]
git-tree-sha1 = "cd1659ba0d57b71a464a29e64dbc67cfe83d54e7"
uuid = "76eceee3-57b5-4d4a-8e66-0e911cebbf60"
version = "1.6.1"
[[deps.XML2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Zlib_jll"]
git-tree-sha1 = "801cbe47eae69adc50f36c3caec4758d2650741b"
uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a"
version = "2.12.2+0"
[[deps.XSLT_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgcrypt_jll", "Libgpg_error_jll", "Libiconv_jll", "Pkg", "XML2_jll", "Zlib_jll"]
git-tree-sha1 = "91844873c4085240b95e795f692c4cec4d805f8a"
uuid = "aed1982a-8fda-507f-9586-7b0439959a61"
version = "1.1.34+0"
[[deps.XZ_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "522b8414d40c4cbbab8dee346ac3a09f9768f25d"
uuid = "ffd25f8a-64ca-5728-b0f7-c24cf3aae800"
version = "5.4.5+0"
[[deps.Xorg_libICE_jll]]
deps = ["Libdl", "Pkg"]
git-tree-sha1 = "e5becd4411063bdcac16be8b66fc2f9f6f1e8fe5"
uuid = "f67eecfb-183a-506d-b269-f58e52b52d7c"
version = "1.0.10+1"
[[deps.Xorg_libSM_jll]]
deps = ["Libdl", "Pkg", "Xorg_libICE_jll"]
git-tree-sha1 = "4a9d9e4c180e1e8119b5ffc224a7b59d3a7f7e18"
uuid = "c834827a-8449-5923-a945-d239c165b7dd"
version = "1.2.3+0"
[[deps.Xorg_libX11_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxcb_jll", "Xorg_xtrans_jll"]
git-tree-sha1 = "afead5aba5aa507ad5a3bf01f58f82c8d1403495"
uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc"
version = "1.8.6+0"
[[deps.Xorg_libXau_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "6035850dcc70518ca32f012e46015b9beeda49d8"
uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec"
version = "1.0.11+0"
[[deps.Xorg_libXcursor_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll", "Xorg_libXrender_jll"]
git-tree-sha1 = "12e0eb3bc634fa2080c1c37fccf56f7c22989afd"
uuid = "935fb764-8cf2-53bf-bb30-45bb1f8bf724"
version = "1.2.0+4"
[[deps.Xorg_libXdmcp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "34d526d318358a859d7de23da945578e8e8727b7"
uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05"
version = "1.1.4+0"
[[deps.Xorg_libXext_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "b7c0aa8c376b31e4852b360222848637f481f8c3"
uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3"
version = "1.3.4+4"
[[deps.Xorg_libXfixes_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "0e0dc7431e7a0587559f9294aeec269471c991a4"
uuid = "d091e8ba-531a-589c-9de9-94069b037ed8"
version = "5.0.3+4"
[[deps.Xorg_libXi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXfixes_jll"]
git-tree-sha1 = "89b52bc2160aadc84d707093930ef0bffa641246"
uuid = "a51aa0fd-4e3c-5386-b890-e753decda492"
version = "1.7.10+4"
[[deps.Xorg_libXinerama_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll"]
git-tree-sha1 = "26be8b1c342929259317d8b9f7b53bf2bb73b123"
uuid = "d1454406-59df-5ea1-beac-c340f2130bc3"
version = "1.1.4+4"
[[deps.Xorg_libXrandr_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll"]
git-tree-sha1 = "34cea83cb726fb58f325887bf0612c6b3fb17631"
uuid = "ec84b674-ba8e-5d96-8ba1-2a689ba10484"
version = "1.5.2+4"
[[deps.Xorg_libXrender_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "19560f30fd49f4d4efbe7002a1037f8c43d43b96"
uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa"
version = "0.9.10+4"
[[deps.Xorg_libpthread_stubs_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "8fdda4c692503d44d04a0603d9ac0982054635f9"
uuid = "14d82f49-176c-5ed1-bb49-ad3f5cbd8c74"
version = "0.1.1+0"
[[deps.Xorg_libxcb_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "XSLT_jll", "Xorg_libXau_jll", "Xorg_libXdmcp_jll", "Xorg_libpthread_stubs_jll"]
git-tree-sha1 = "b4bfde5d5b652e22b9c790ad00af08b6d042b97d"
uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b"
version = "1.15.0+0"
[[deps.Xorg_libxkbfile_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"]
git-tree-sha1 = "730eeca102434283c50ccf7d1ecdadf521a765a4"
uuid = "cc61e674-0454-545c-8b26-ed2c68acab7a"
version = "1.1.2+0"
[[deps.Xorg_xcb_util_cursor_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_jll", "Xorg_xcb_util_renderutil_jll"]
git-tree-sha1 = "04341cb870f29dcd5e39055f895c39d016e18ccd"
uuid = "e920d4aa-a673-5f3a-b3d7-f755a4d47c43"
version = "0.1.4+0"
[[deps.Xorg_xcb_util_image_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "0fab0a40349ba1cba2c1da699243396ff8e94b97"
uuid = "12413925-8142-5f55-bb0e-6d7ca50bb09b"
version = "0.4.0+1"
[[deps.Xorg_xcb_util_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll"]
git-tree-sha1 = "e7fd7b2881fa2eaa72717420894d3938177862d1"
uuid = "2def613f-5ad1-5310-b15b-b15d46f528f5"
version = "0.4.0+1"
[[deps.Xorg_xcb_util_keysyms_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "d1151e2c45a544f32441a567d1690e701ec89b00"
uuid = "975044d2-76e6-5fbe-bf08-97ce7c6574c7"
version = "0.4.0+1"
[[deps.Xorg_xcb_util_renderutil_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "dfd7a8f38d4613b6a575253b3174dd991ca6183e"
uuid = "0d47668e-0667-5a69-a72c-f761630bfb7e"
version = "0.3.9+1"
[[deps.Xorg_xcb_util_wm_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "e78d10aab01a4a154142c5006ed44fd9e8e31b67"
uuid = "c22f9ab0-d5fe-5066-847c-f4bb1cd4e361"
version = "0.4.1+1"
[[deps.Xorg_xkbcomp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxkbfile_jll"]
git-tree-sha1 = "330f955bc41bb8f5270a369c473fc4a5a4e4d3cb"
uuid = "35661453-b289-5fab-8a00-3d9160c6a3a4"
version = "1.4.6+0"
[[deps.Xorg_xkeyboard_config_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xkbcomp_jll"]
git-tree-sha1 = "691634e5453ad362044e2ad653e79f3ee3bb98c3"
uuid = "33bec58e-1273-512f-9401-5d533626f822"
version = "2.39.0+0"
[[deps.Xorg_xtrans_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "e92a1a012a10506618f10b7047e478403a046c77"
uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10"
version = "1.5.0+0"
[[deps.Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
version = "1.2.13+1"
[[deps.Zstd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "49ce682769cd5de6c72dcf1b94ed7790cd08974c"
uuid = "3161d3a3-bdf6-5164-811a-617609db77b4"
version = "1.5.5+0"
[[deps.eudev_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "gperf_jll"]
git-tree-sha1 = "431b678a28ebb559d224c0b6b6d01afce87c51ba"
uuid = "35ca27e7-8b34-5b7f-bca9-bdc33f59eb06"
version = "3.2.9+0"
[[deps.fzf_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "a68c9655fbe6dfcab3d972808f1aafec151ce3f8"
uuid = "214eeab7-80f7-51ab-84ad-2988db7cef09"
version = "0.43.0+0"
[[deps.gperf_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3516a5630f741c9eecb3720b1ec9d8edc3ecc033"
uuid = "1a1c6b14-54f6-533d-8383-74cd7377aa70"
version = "3.1.1+0"
[[deps.libaom_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3a2ea60308f0996d26f1e5354e10c24e9ef905d4"
uuid = "a4ae2306-e953-59d6-aa16-d00cac43593b"
version = "3.4.0+0"
[[deps.libass_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "5982a94fcba20f02f42ace44b9894ee2b140fe47"
uuid = "0ac62f75-1d6f-5e53-bd7c-93b484bb37c0"
version = "0.15.1+0"
[[deps.libblastrampoline_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850b90-86db-534c-a0d3-1478176c7d93"
version = "5.8.0+1"
[[deps.libevdev_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "141fe65dc3efabb0b1d5ba74e91f6ad26f84cc22"
uuid = "2db6ffa8-e38f-5e21-84af-90c45d0032cc"
version = "1.11.0+0"
[[deps.libfdk_aac_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "daacc84a041563f965be61859a36e17c4e4fcd55"
uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280"
version = "2.0.2+0"
[[deps.libinput_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "eudev_jll", "libevdev_jll", "mtdev_jll"]
git-tree-sha1 = "ad50e5b90f222cfe78aa3d5183a20a12de1322ce"
uuid = "36db933b-70db-51c0-b978-0f229ee0e533"
version = "1.18.0+0"
[[deps.libpng_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Zlib_jll"]
git-tree-sha1 = "93284c28274d9e75218a416c65ec49d0e0fcdf3d"
uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f"
version = "1.6.40+0"
[[deps.libvorbis_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll", "Pkg"]
git-tree-sha1 = "b910cb81ef3fe6e78bf6acee440bda86fd6ae00c"
uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a"
version = "1.3.7+1"
[[deps.mtdev_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "814e154bdb7be91d78b6802843f76b6ece642f11"
uuid = "009596ad-96f7-51b1-9f1b-5ce2d5e8a71e"
version = "1.1.6+0"
[[deps.nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
version = "1.52.0+1"
[[deps.p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
version = "17.4.0+2"
[[deps.x264_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4fea590b89e6ec504593146bf8b988b2c00922b2"
uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a"
version = "2021.5.5+0"
[[deps.x265_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "ee567a171cce03570d77ad3a43e90218e38937a9"
uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76"
version = "3.5.0+0"
[[deps.xkbcommon_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Wayland_jll", "Wayland_protocols_jll", "Xorg_libxcb_jll", "Xorg_xkeyboard_config_jll"]
git-tree-sha1 = "9c304562909ab2bab0262639bd4f444d7bc2be37"
uuid = "d8fb68d0-12a3-5cfd-a85a-d49703b185fd"
version = "1.4.1+1"
"""
# ╔═╡ Cell order:
# ╟─813f69f9-be5a-418a-ad0a-4e9c9aae79c3
# ╟─1c694257-113b-4ec2-8d77-12dbe67e30f3
# ╟─6efbcc3e-5054-4267-88d2-ea7641c51879
# ╟─8c7f0c97-73e2-48e9-875d-9c33e7ada588
# ╟─81b8172a-8ce9-470e-8103-71c7c0f3d9f4
# ╟─2e4459fe-4764-4595-bad5-bf20b3d5e3e8
# ╟─d708347b-a84a-4b17-bfb6-6cdaec4c5e01
# ╟─22a0b724-684c-4bc0-96bb-5821b17df97c
# ╟─1da54919-2eae-4da5-9149-f361fcbda082
# ╠═126a6f2e-adfc-11ee-2def-eb30c37b09cc
# ╟─661decfd-f455-42a2-a81c-d2ceba154609
# ╟─e5f8d573-3859-41cf-8573-f70633dfab39
# ╟─deb3e2d5-53dc-4849-b40d-1180817bd17f
# ╟─b72a765b-d0be-46a5-9137-e5e10d80ab3d
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
| MetOfficeStationData | https://github.com/tpgillam/MetOfficeStationData.jl.git |
|
[
"MIT"
] | 0.1.1 | 05c1471a9064419e22743e97453bb42773d2f07d | code | 4043 | module MetOfficeStationData
using Cascadia: @sel_str
using CSV: CSV
using DataFrames: DataFrame, Not, select!
using Downloads: download
using Gumbo: Gumbo
using Gumbo: parsehtml
using Mocking
function _data_url(short_name::AbstractString)
return "https://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/$(short_name)data.txt"
end
"""Download the file for `short_name` to an in-memory buffer."""
function _download_as_string(short_name::AbstractString)
return String(take!(download(_data_url(short_name), IOBuffer())))
end
"""
get_frame(short_name) -> DataFrame
Get the data from the station specified by `short_name`.
The column names and units match the raw form provided at
https://www.metoffice.gov.uk/research/climate/maps-and-data/historic-station-data
# Returns
A dataframe with the following columns:
- yyyy (Int64): Year
- mm (Int64): Month
- tmax (Float64?): Mean daily maximum temperature / °C
- tmin (Float64?): Mean daily minimum temperature / °C
- af (Int64?): Days of air frost / days
- rain (Float64?): Total rainfall / mm
- sun (Float64?): Total sunshine duration / hours
"""
function get_frame(short_name::AbstractString)
csv_str = (@mock _download_as_string(short_name))
# Skip the prelude, and jump to where the data starts.
# TODO: We then remove known "annotations" that means we can parse the data smoothly.
# Potentially it would be desirable to maintain these annotations somehow.
i_start = first(findfirst(r"\s+yyyy", csv_str))
cleaned_csv_str = replace(
csv_str[i_start:end],
r"\s+Provisional" => "",
"*" => "",
"#" => "",
"\$" => "",
"|" => "", # This appears in `nairndata.txt`... no explanation given.
r"all\s+data\s+from\s+[\S\s]+" => "",
r"Change\s+to[\S\s]+" => "",
"Site Closed" => "",
)
# TODO: parse some of the header information.
# NOTE: we cannot use threaded parsing here, since splitting the file into chunks results in us
# failing to find the correct number of columns sometimes.
# HACK: silencing warnings is a bit disgusting. The problem is that some stations, e.g. aberporth,
# don't have any 'sun' data, so there is a whole missing column, even though the header is present.
# CSV.jl doesn't see a delimeter after the value for the penultimate column, and hence complains.
return CSV.read(
IOBuffer(cleaned_csv_str),
DataFrame;
header=[1], # Skip the units... if we try to parse them it goes wrong.
skipto=3,
delim=' ',
ignorerepeated=true,
missingstring="---",
ntasks=1,
silencewarnings=true,
)
end
_get_value(x::Gumbo.HTMLText) = x.text
_get_value(x::Gumbo.HTMLElement{:a}) = x.attributes["href"]
_get_value(x::Gumbo.HTMLElement{:th}) = _get_value(only(x.children))
_get_value(x::Gumbo.HTMLElement{:td}) = _get_value(only(x.children))
"""
get_station_metadata() -> DataFrame
Get all known stations along with metadata as a DataFrame.
"""
function get_station_metadata()
doc = parsehtml(
String(
take!(
download(
"https://www.metoffice.gov.uk/research/climate/maps-and-data/historic-station-data",
IOBuffer(),
),
),
),
)
table = only(eachmatch(sel"table", doc.root))
return DataFrame(
map(eachmatch(sel"tbody tr", table)) do row
name, lon_lat, year_str, url = map(_get_value, eachmatch(sel"td", row))
year_start = parse(Int, year_str)
lon, lat = map(split(lon_lat, ", ")) do x
parse(Float64, x)
end
short_name = only(
match(
r"https://www\.metoffice\.gov\.uk/pub/data/weather/uk/climate/stationdata/([a-z]+)data\.txt",
url,
),
)
(; name, lat, lon, year_start, short_name)
end,
)
end
end
| MetOfficeStationData | https://github.com/tpgillam/MetOfficeStationData.jl.git |
|
[
"MIT"
] | 0.1.1 | 05c1471a9064419e22743e97453bb42773d2f07d | code | 1471 | using Aqua
using DataFrames
using MetOfficeStationData
using Mocking
using Test
Mocking.activate()
function _mock_download(short_name::AbstractString)
return String(
open(read, joinpath(dirname(@__FILE__), "reference", "$(short_name)data.txt"))
)
end
@testset "MetOfficeStationData.jl" begin
@testset "aqua" begin
Aqua.test_all(MetOfficeStationData; ambiguities=false)
Aqua.test_ambiguities(MetOfficeStationData)
end
patch = @patch MetOfficeStationData._download_as_string(short_name::AbstractString) =
_mock_download(short_name)
apply(patch) do
for short_name in
("aberporth", "cambridge", "lowestoft", "nairn", "ringway", "whitby")
@testset "check $short_name" begin
df = MetOfficeStationData.get_frame(short_name)
@test isa(df, DataFrame)
@test ncol(df) == 7
@test names(df) == ["yyyy", "mm", "tmax", "tmin", "af", "rain", "sun"]
@test eltype(df[!, :yyyy]) == Int64
@test eltype(df[!, :mm]) == Int64
@test eltype(df[!, :tmax]) <: Union{Float64,Missing}
@test eltype(df[!, :tmin]) <: Union{Float64,Missing}
@test eltype(df[!, :af]) <: Union{Int64,Missing}
@test eltype(df[!, :rain]) <: Union{Float64,Missing}
@test eltype(df[!, :sun]) <: Union{Float64,Missing}
end
end
end
end
| MetOfficeStationData | https://github.com/tpgillam/MetOfficeStationData.jl.git |
|
[
"MIT"
] | 0.1.1 | 05c1471a9064419e22743e97453bb42773d2f07d | docs | 3020 | # MetOfficeStationData
[](https://github.com/tpgillam/MetOfficeStationData.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/tpgillam/MetOfficeStationData.jl)
[](https://github.com/invenia/BlueStyle)
[](https://github.com/SciML/ColPrac)
Access the [Met Office Historic station data](https://www.metoffice.gov.uk/research/climate/maps-and-data/historic-station-data).
These are monthly summaries of weather from across the UK, with long histories.
## Usage
If you know the `short_name` of a station, you can obtain the data like so:
```julia
using MetOfficeStationData
MetOfficeStationData.get_frame("cambridge")
```
```
779×7 DataFrame
Row │ yyyy mm tmax tmin af rain sun
│ Int64 Int64 Float64 Float64 Int64 Float64? Float64?
─────┼─────────────────────────────────────────────────────────────
1 │ 1959 1 4.4 -1.4 20 missing 78.1
2 │ 1959 2 7.5 1.2 9 missing 66.0
3 │ 1959 3 11.5 3.8 0 missing 98.0
4 │ 1959 4 14.3 5.4 0 missing 146.1
5 │ 1959 5 18.1 6.5 0 missing 224.8
6 │ 1959 6 21.6 10.1 0 missing 252.4
...
```
To obtain metadata for all stations, including the `short_name`s needed for `MetOfficeStationData.get_frame`:
```julia
MetOfficeStationData.get_station_metadata()
```
```
37×5 DataFrame
Row │ name lat lon year_start short_name
│ String Float64 Float64 Int64 SubString…
─────┼───────────────────────────────────────────────────────────────────────────
1 │ Aberporth 52.139 -4.57 1941 aberporth
2 │ Armagh 54.352 -6.649 1853 armagh
3 │ Ballypatrick Forest 55.181 -6.153 1961 ballypatrick
4 │ Bradford 53.813 -1.772 1908 bradford
5 │ Braemar No 2 57.011 -3.396 1959 braemar
...
```
## Example
Run the [example Pluto.jl notebook](./examples/pluto_plots.jl) for a simple interactive visualsation of the data.
For example, for the Cambridge Niab station, as of January 2024:


## Limitations
The data files given by the Met Office include various annotations, e.g. noting the types of sensor used, or whether data is preliminary, or even if a station changed location.
We do not preserve any of this!
| MetOfficeStationData | https://github.com/tpgillam/MetOfficeStationData.jl.git |
|
[
"MIT"
] | 0.1.5 | 9b6360885ae561b9652f32f7e4d83838e8e23e1b | code | 535 | using MetaUtils
using Documenter
makedocs(;
modules=[MetaUtils],
authors="genkuroki <[email protected]> and contributors",
repo="https://github.com/genkuroki/MetaUtils.jl/blob/{commit}{path}#L{line}",
sitename="MetaUtils.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://genkuroki.github.io/MetaUtils.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/genkuroki/MetaUtils.jl",
)
| MetaUtils | https://github.com/genkuroki/MetaUtils.jl.git |
|
[
"MIT"
] | 0.1.5 | 9b6360885ae561b9652f32f7e4d83838e8e23e1b | code | 8285 | """
MetaUtils
contains utilities for metaprogramming in Julia.
```julia
export @show_sexpr,
@show_tree,
print_subtypes,
show_expr, @show_expr,
show_texpr, @show_texpr,
texpr2expr, teval, @teval
```
"""
module MetaUtils
export @show_sexpr,
@show_tree,
print_subtypes,
show_expr, @show_expr,
show_texpr, @show_texpr,
texpr2expr, teval, @teval
using InteractiveUtils: InteractiveUtils, subtypes
using AbstractTrees
"""
@show_sexpr(expr, linenums=false)
shows the lisp style S-expression of `expr` and prints the line number nodes if `linenums` is true. This is the macro version of `Meta.show_sexpr`.
## Example
```julia
julia> @show_sexpr 2x+1
(:call, :+, (:call, :*, 2, :x), 1)
```
`teval` function can evaluate the output of `@show_sexpr`.
```julia
julia> x = 10; (:call, :+, (:call, :*, 2, :x), 1) |> teval
21
```
"""
macro show_sexpr(expr, linenums=false)
linenums || Base.remove_linenums!(expr)
:(Meta.show_sexpr($(QuoteNode(expr))))
end
### 2022-03-14: AbstractTrees.printnode(io::IO, expr::Expr) is already defined in
### AbstractTrees/src/builtins.jl:14
###
### Warning: The following line is type piracy!
#AbstractTrees.printnode(io::IO, expr::Expr) = show(io, expr.head)
"""
@show_tree(expr, maxdepth=10, linenums=false)
shows the tree form of the expression `expr` with maxdepth and prints the line number nodes if `linenums` is true.
## Example
```julia
julia> @show_tree 2x+1
:call
├─ :+
├─ :call
│ ├─ :*
│ ├─ 2
│ └─ :x
└─ 1
```
"""
macro show_tree(expr, maxdepth=10, linenums=false)
linenums || Base.remove_linenums!(expr)
:(print_tree($(QuoteNode(expr)); maxdepth = $(esc(maxdepth))))
end
### Warning: The following line is type piracy!
#AbstractTrees.children(T::Type) = subtypes(T)
### Wrap types in Box to prevent type piracy
###
struct TypeBox{T} x::T end
Base.parent(b::TypeBox) = b.x
Base.show(io::IO, b::TypeBox) = Base.show(io::IO, parent(b))
InteractiveUtils.subtypes(b::TypeBox{<:Type}) = TypeBox.(subtypes(parent(b)))
AbstractTrees.children(b::TypeBox{<:Type}) = subtypes(b)
AbstractTrees.printnode(io::IO, b::TypeBox) = show(io, parent(b))
"""
print_subtypes(T::Type; kwargs...)
print_subtypes(io::IO, T::Type; kwargs...)
print_subtypes(f, io::IO, T::Type; kwargs...)
prints the subtypes of `T` by `AbstractTrees.print_tree`.
## Example
```julia
julia> print_subtypes(AbstractRange)
AbstractRange
├─ LinRange
├─ OrdinalRange
│ ├─ AbstractUnitRange
│ │ ├─ Base.IdentityUnitRange
│ │ ├─ Base.OneTo
│ │ ├─ Base.Slice
│ │ └─ UnitRange
│ └─ StepRange
└─ StepRangeLen
```
"""
print_subtypes(T::Type; kwargs...) = print_tree(TypeBox(T); kwargs...)
print_subtypes(io::IO, T::Type; kwargs...) = print_tree(io, TypeBox(T); kwargs...)
print_subtypes(f, io::IO, T::Type; kwargs...) = print_tree(f, io::IO, TypeBox(T); kwargs...)
"""
const expr_indent = 4
is the default indent of showing expressions.
"""
const expr_indent = 4
"""
show_expr([io::IO,], ex)
shows expression `ex` as a Julia style expression.
# Examples
```julia
julia> show_expr(:(f(x, g(y, z))))
Expr(:call, :f, :x,
Expr(:call, :g, :y, :z))
```
"""
show_expr(io::IO, ex, inner; indent=expr_indent, head="Expr") = show(io, ex)
show_expr(io::IO, ex; indent=expr_indent, head="Expr") = show_expr(io, ex, 0; indent, head)
show_expr(ex; indent=expr_indent, head="Expr") = show_expr(stdout, ex; indent, head)
function show_expr(io::IO, ex::LineNumberNode, inner; indent=expr_indent, head="Expr")
print(io, "LineNumberNode(")
show(io, ex.line); print(io, ", ")
show(io, ex.file); print(io, ')')
end
# See https://github.com/JuliaLang/julia/issues/6104#issuecomment-37262662
function show_expr(io::IO, ex::QuoteNode, inner; indent=expr_indent, head="Expr")
print(io, "QuoteNode", "(")
show_expr(io, ex.value, inner+indent; indent, head)
print(io, ')')
end
function show_expr(io::IO, ex::Expr, inner; indent=expr_indent, head="Expr")
iszero(inner) || print(io, "\n")
print(io, " "^inner, head, "(")
show_expr(io, ex.head, inner+indent; indent, head)
for arg in ex.args
print(io, ", ")
show_expr(io, arg, inner+indent; indent, head)
end
isempty(ex.args) && print(io, ',')
print(io, ')')
end
"""
@show_expr(expr, linenums=false)
shows the Juia style expression of `expr` and prints the line number nodes if `linenums` is true. This is the macro version of `show_expr`.
## Example
```julia
julia> @show_expr 2x+1
Expr(:call, :+,
Expr(:call, :*, 2, :x), 1)
```
`eval` function can evaluate the output of `@show_expr`.
```julia
julia> x = 10; Expr(:call, :+,
Expr(:call, :*, 2, :x), 1) |> eval
21
```
"""
macro show_expr(expr, linenums=false)
linenums || Base.remove_linenums!(expr)
:(show_expr($(QuoteNode(expr))))
end
"""
show_texpr([io::IO,], ex)
Yet another `Meta.show_sexpr`. It shows expression `ex` as a lisp style expression.
Remark: The indentation is different from `Meta.show_sexpr`.
# Examples
```julia
julia> show_texpr(:(f(x, g(y, z))))
Expr(:call, :f, :x,
Expr(:call, :g, :y, :z))
```
"""
show_texpr(io::IO, ex; indent=expr_indent) = show_expr(io, ex; indent, head="")
show_texpr(ex; indent=expr_indent) = show_texpr(stdout, ex; indent)
"""
@show_texpr(expr, linenums=false)
Yet another `@show_sexpr`. It shows the lisp style S-expression of `expr` and prints the line number nodes if `linenums` is true.
Remark: The indentation is different from `@show_sexpr`.
## Example
```julia
julia> @show_texpr 2x+1
(:call, :+,
(:call, :*, 2, :x), 1)
```
`teval` function can evaluate the output of `@show_texpr`.
```julia
julia> x = 10; (:call, :+,
(:call, :*, 2, :x), 1) |> teval
21
```
"""
macro show_texpr(expr, linenums=false)
linenums || Base.remove_linenums!(expr)
:(show_texpr($(QuoteNode(expr))))
end
"""
texpr2expr(x, m::Module=Main)
converts a lisp-like tuple expression `x` to the executable expression of Julia.
Example: The expression of `sin(π/6)`
```julia
julia> texpr2expr((:call, :sin, (:call, :/, π, 6)))
:(sin(π / 6))
```
"""
texpr2expr(x, m::Module=Main) = x
texpr2expr(q::QuoteNode, m::Module=Main) = QuoteNode(texpr2expr(q.value))
function texpr2expr(t::Tuple, m::Module=Main)
isempty(t) && return :(())
@assert t[1] isa Symbol "The first element of "*sprint(show, t)*" is not a Symbol."
e = texpr2expr.(t, Ref(m))
if isdefined(Main, e[1])
f = Core.eval(m, e[1])
!isa(f, Core.Builtin) && isa(f, Function) && return Expr(:call, e...)
end
Expr(e...)
end
"""
teval(texpr, m::Module=Main)
evaluates the lisp-like tuple expression `texpr`.
Example: Calculation of `sin(π/6)`
```julia
julia> (:call, :sin, (:call, :/, π, 6)) |> teval
0.49999999999999994
```
In some cases, you can omit `:call`.
```julia
julia> (:sin, (:/, π, 6)) |> teval
0.49999999999999994
```
"""
teval(texpr, m::Module=Main) = Core.eval(m, texpr2expr(texpr, m))
"""
@teval texpr
evaluates the lisp-like tuple expression `texpr`.
Example: Calculation of `sin(π/6)`
```julia
julia> @teval (:call, :sin, (:call, :/, π, 6))
0.49999999999999994
```
In some cases, you can omit `:call`.
```julia
julia> @teval (:sin, (:/, π, 6))
0.49999999999999994
```
"""
macro teval(texpr)
esc(texpr2expr(Core.eval(__module__, texpr)))
end
"""
MetaUtils.@t texpr
shows the Julia expression and the value of the lisp-like tuple expression `texpr`.
Example:
```julia
julia> MetaUtils.@t (:call, :sin, (:call, :/, π, 6))
:(sin(π / 6))
→ 0.49999999999999994
```
"""
macro t(x)
expr = texpr2expr(Core.eval(__module__, x))
show(expr); print("\n→ "); show(Core.eval(__module__, expr))
print("\n")
end
"""
MetaUtils.@T texpr
shows `show(texpr)`, `show_texpr(texpr)`, the Julia expression, and the value of the lisp-like tuple expression `texpr`.
Example:
```julia
julia> MetaUtils.@T (:call, :sin, (:call, :/, π, 6))
(:call, :sin, (:call, :/, π, 6))
→ (:call, :sin,
(:call, :/, π, 6))
→ :(sin(π / 6))
→ 0.49999999999999994
```
"""
macro T(x)
code = Core.eval(__module__, x)
expr = texpr2expr(code)
show(code)
print("\n→ "); show_texpr(expr); print("\n→ ")
show(expr); print("\n→ "); show(Core.eval(__module__, expr))
print("\n")
end
end
| MetaUtils | https://github.com/genkuroki/MetaUtils.jl.git |
|
[
"MIT"
] | 0.1.5 | 9b6360885ae561b9652f32f7e4d83838e8e23e1b | code | 663 | using MetaUtils
using Test
x = 10
@testset "MetaUtils.jl" begin
@test (@teval (:call, :+, (:call, :*, 2, :x), 1)) == 21
@test (@teval (:+, (:*, 2, :x), 1)) == 21
@test sprint(show_expr, :(2x + 1)) ==
"Expr(:call, :+, \n Expr(:call, :*, 2, :x), 1)"
@test sprint(show_texpr, :(2x + 1)) ==
"(:call, :+, \n (:call, :*, 2, :x), 1)"
@test sprint(print_subtypes, AbstractFloat) ==
"AbstractFloat\n├─ BigFloat\n├─ Float16\n├─ Float32\n└─ Float64\n"
@test sprint(print_subtypes, Ref) ==
"Ref\n├─ Base.CFunction\n├─ Base.RefArray\n├─ Base.RefValue\n├─ Core.Compiler.RefValue\n├─ Core.LLVMPtr\n└─ Ptr\n"
end
| MetaUtils | https://github.com/genkuroki/MetaUtils.jl.git |
|
[
"MIT"
] | 0.1.5 | 9b6360885ae561b9652f32f7e4d83838e8e23e1b | docs | 10935 | ---
jupyter:
jupytext:
formats: ipynb,md
text_representation:
extension: .md
format_name: markdown
format_version: '1.1'
jupytext_version: 1.2.1
kernelspec:
display_name: Julia 1.7.0-DEV depwarn -O3
language: julia
name: julia-1.7-depwarn-o3
---
# MetaUtils
* Author: Gen Kuroki
* Date: 2020-10-11~2020-10-17, 2021-03-20~2021-03-26
* Repository: https://github.com/genkuroki/MetaUtils.jl
* File: https://nbviewer.jupyter.org/github/genkuroki/MetaUtils.jl/blob/master/MetaUtils.ipynb
<!-- #region {"toc": true} -->
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Explanatory-examples" data-toc-modified-id="Explanatory-examples-1"><span class="toc-item-num">1 </span>Explanatory examples</a></span></li><li><span><a href="#Miscellaneous-examples-of-@show_texpr,-etc." data-toc-modified-id="Miscellaneous-examples-of-@show_texpr,-etc.-2"><span class="toc-item-num">2 </span>Miscellaneous examples of @show_texpr, etc.</a></span><ul class="toc-item"><li><span><a href="#for-loop" data-toc-modified-id="for-loop-2.1"><span class="toc-item-num">2.1 </span>for loop</a></span></li><li><span><a href="#subtype-trees" data-toc-modified-id="subtype-trees-2.2"><span class="toc-item-num">2.2 </span>subtype trees</a></span></li><li><span><a href="#function-definition" data-toc-modified-id="function-definition-2.3"><span class="toc-item-num">2.3 </span>function definition</a></span></li><li><span><a href="#macro-and-LineNumberNode" data-toc-modified-id="macro-and-LineNumberNode-2.4"><span class="toc-item-num">2.4 </span>macro and LineNumberNode</a></span></li><li><span><a href="#QuoteNode" data-toc-modified-id="QuoteNode-2.5"><span class="toc-item-num">2.5 </span>QuoteNode</a></span></li></ul></li><li><span><a href="#Evaluation-of-Lisp-like-tuple-expressions" data-toc-modified-id="Evaluation-of-Lisp-like-tuple-expressions-3"><span class="toc-item-num">3 </span>Evaluation of Lisp-like tuple expressions</a></span></li><li><span><a href="#Plot-example" data-toc-modified-id="Plot-example-4"><span class="toc-item-num">4 </span>Plot example</a></span></li><li><span><a href="#Documents" data-toc-modified-id="Documents-5"><span class="toc-item-num">5 </span>Documents</a></span></li></ul></div>
<!-- #endregion -->
```julia
VERSION
```
```julia
if isfile("Project.toml")
using Pkg
Pkg.activate(".")
using Revise
end
```
```julia
using MetaUtils
```
## Explanatory examples
```julia
@show_sexpr 2x+1
```
```julia
x = 10; (:call, :+, (:call, :*, 2, :x), 1) |> teval
```
```julia
@show_tree 2x+1
```
```julia
print_subtypes(AbstractRange)
```
```julia
show_expr(:(f(x, g(y, z))))
```
```julia
@show_expr 2x+1
```
```julia
x = 10; Expr(:call, :+,
Expr(:call, :*, 2, :x), 1) |> eval
```
```julia
show_texpr(:(f(x, g(y, z))))
```
```julia
@show_texpr 2x+1
```
```julia
x = 10; (:call, :+,
(:call, :*, 2, :x), 1) |> teval
```
```julia
texpr2expr((:call, :sin, (:call, :/, π, 6)))
```
```julia
(:call, :sin, (:call, :/, π, 6)) |> teval
```
```julia
@teval (:call, :sin, (:call, :/, π, 6))
```
```julia
MetaUtils.@t (:call, :sin, (:call, :/, π, 6))
```
```julia
MetaUtils.@T (:call, :sin, (:call, :/, π, 6))
```
```julia
(:sin, (:/, π, 6)) |> teval
```
```julia
@teval (:sin, (:/, π, 6))
```
```julia
MetaUtils.@t (:sin, (:/, π, 6))
```
```julia
MetaUtils.@T (:sin, (:/, π, 6))
```
## Miscellaneous examples of @show_texpr, etc.
### for loop
```julia
@show_texpr for k in 1:10
x = k*(k+1) ÷ 2
println("k(k+1)/2 = ", x)
end
```
```julia
@show_texpr for k in 1:10
x = k*(k+1) ÷ 2
println("k(k+1)/2 = ", x)
end true
```
```julia
@show_tree for k in 1:10
x = k*(k+1) ÷ 2
println("k(k+1)/2 = ", x)
end 2
```
```julia
@show_tree for k in 1:10
x = k*(k+1) ÷ 2
println("k(k+1)/2 = ", x)
end
```
```julia
@show_tree for k in 1:10
x = k*(k+1) ÷ 2
println("k(k+1)/2 = ", x)
end 10 true
```
```julia
Meta.@dump for k in 1:10
x = k*(k+1) ÷ 2
println("k(k+1)/2 = ", x)
end
```
```julia
@show_expr for k in 1:10
x = k*(k+1) ÷ 2
println("k(k+1)/2 = ", x)
end
```
```julia
@show_texpr for k in 1:10
x = k*(k+1) ÷ 2
println("k(k+1)/2 = ", x)
end
```
### subtype trees
```julia
print_subtypes(AbstractRange)
```
```julia
print_subtypes(Number)
```
```julia
print_subtypes(AbstractVector)
```
### function definition
```julia
@show_texpr function f(x::T) where T<:Number
sin(x)
end
```
```julia
@show_tree function f(x::T) where T<:Number
sin(x)
end
```
```julia
@show_expr function f(x::T) where T<:Number
sin(x)
end
```
```julia
@show_texpr function f(x::T) where T<:Number
sin(x)
end
```
### macro and LineNumberNode
```julia
@show_tree @show float(π)
```
```julia
@show_sexpr @show float(π)
```
```julia
@teval (:macrocall, Symbol("@show"), :(#= In[34]:1 =#), (:call, :float, :π))
```
```julia
@show_expr @show float(π)
```
```julia
Expr(:macrocall, Symbol("@show"), LineNumberNode(@__LINE__, @__FILE__),
Expr(:call, :float, :π)) |> show_expr
```
```julia
Expr(:macrocall, Symbol("@show"), LineNumberNode(@__LINE__, @__FILE__),
Expr(:call, :float, :π)) |> eval
```
```julia
@show_texpr @show float(π)
```
```julia
(:macrocall, Symbol("@show"), LineNumberNode(@__LINE__, @__FILE__),
(:call, :float, :π)) |> teval
```
```julia
@teval (:macrocall, Symbol("@show"), LineNumberNode(@__LINE__, @__FILE__),
(:call, :float, :π))
```
### QuoteNode
```julia
QuoteNode(:(sin(x)))
```
```julia
QuoteNode(:(sin(x))) |> Meta.show_sexpr
```
```julia
QuoteNode(:(sin(x))) |> show_expr
```
```julia
QuoteNode(:(sin(x))) |> show_texpr
```
```julia
QuoteNode(
(:call, :sin, :x)) |> texpr2expr == QuoteNode(:(sin(x)))
```
```julia
@teval QuoteNode(
(:call, :sin, :x))
```
## Evaluation of Lisp-like tuple expressions
If you want more Lisp-like examamples, see [LispLikeEval.ipynb](https://nbviewer.jupyter.org/github/genkuroki/LispLikeEval.jl/blob/master/LispLikeEval.ipynb).
```julia
using MetaUtils: @t, @T
```
```julia
# Define and run a function f(x) = sin(x)
@t (:(=), :(f(x)), (:sin, :x))
println()
@t (:f, (:/, π, 6))
```
```julia
# Define and run a function f(x) = sin(x)
@T (:(=), :(f(x)), (:sin, :x))
println()
@T (:f, (:/, π, 6))
```
```julia
# Define and run a function g(x) = sin(x)
@t (:block,
(:function, :(g(x)), (:sin, :x)),
(:call, :g, (:/, π, 6)))
```
```julia
# Define and run a function g(x) = sin(x)
@T (:block,
(:function, :(g(x)), (:sin, :x)),
(:call, :g, (:/, π, 6)))
```
```julia
# Calculation of pi by the Monte Carlo method
@t (:block,
(:function, :(pi_mc(N)),
(:block,
(:(=), :c, 0),
(:for, (:(=), :i, (:(:), 1, :N)),
(:block,
(:+=, :c,
(:call, :ifelse,
(:≤, (:+, (:^, (:rand,), 2), (:^, (:rand,), 2)), 1),
1, 0)))),
(:/, (:*, 4, :c), :N))),
(:call, :pi_mc, (:^, 10, 8)))
```
```julia
# quote
@t (:quote, (:sin, :x))
```
```julia
# tuple
@t (:tuple, 1, 2, 3)
```
## Plot example
```julia
begin
using Plots
n = 20
x = range(-π, π; length=20)
noise = 0.3randn(n)
y = sin.(x) + noise
X = hcat((x.^k for k in 0:3)...)
b = X\y
f(x) = sum(b[k+1]*x^k for k in 0:3)
xs = range(-π, π; length=400)
plot(; legend=:topleft)
scatter!(x, y; label="sample")
plot!(xs, sin.(xs); label="sin(x)", color=:blue, ls=:dash)
plot!(xs, f.(xs); label="degree-3 polynomial", color=:red, lw=2)
end
```
```julia
@show_texpr begin
using Plots
n = 20
x = range(-π, π; length=20)
noise = 0.3randn(n)
y = sin.(x) + noise
X = hcat((x.^k for k in 0:3)...)
b = X\y
f(x) = sum(b[k+1]*x^k for k in 0:3)
xs = range(-π, π; length=400)
plot(; legend=:topleft)
scatter!(x, y; label="sample")
plot!(xs, sin.(xs); label="sin(x)", color=:blue, ls=:dash)
plot!(xs, f.(xs); label="degree-3 polynomial", color=:red, lw=2)
end
```
```julia
@teval (:block,
(:using, (:., :Plots)),
(:(=), :n, 20),
(:(=), :x, (:range, (:parameters, (:kw, :length, 20)), (:-, :π), :π)),
(:(=), :noise, (:*, 0.3, (:randn, :n))),
(:(=), :y, (:+, (:., :sin, (:tuple, :x)), :noise)),
(:(=), :X,
(:hcat, (:..., (:generator, (:call, :.^, :x, :k), (:(=), :k, (:(:), 0, 3)))))),
(:(=), :b, (:\, :X, :y)),
(:(=), (:call, :f, :x),
(:sum, (:generator, (:*, (:ref, :b, (:+, :k, 1)), (:^, :x, :k)),
(:(=), :k, (:(:), 0, 3))))),
(:(=), :xs, (:range, (:parameters, (:kw, :length, 400)), (:-, :π), :π)),
(:plot, (:parameters, (:kw, :legend, QuoteNode(:topleft)))),
(:scatter!, (:parameters, (:kw, :label, "sample")), :x, :y),
(:plot!, (:parameters,
(:kw, :label, "sin(x)"),
(:kw, :color, QuoteNode(:blue)),
(:kw, :ls, QuoteNode(:dash))),
:xs, (:., :sin, (:tuple, :xs))),
(:plot!, (:parameters,
(:kw, :label, "degree-3 polynomial"),
(:kw, :color, QuoteNode(:red)),
(:kw, :lw, 2)),
:xs, (:., :f, (:tuple, :xs))))
```
```julia
(:block,
(:using, (:., :Plots)),
(:(=), :n, 20),
(:(=), :x, (:range, (:parameters, (:kw, :length, 20)), (:-, :π), :π)),
(:(=), :noise, (:*, 0.3, (:randn, :n))),
(:(=), :y, (:+, (:., :sin, (:tuple, :x)), :noise)),
(:(=), :X,
(:hcat, (:..., (:generator, (:call, :.^, :x, :k), (:(=), :k, (:(:), 0, 3)))))),
(:(=), :b, (:\, :X, :y)),
(:(=), (:call, :f, :x),
(:sum, (:generator, (:*, (:ref, :b, (:+, :k, 1)), (:^, :x, :k)),
(:(=), :k, (:(:), 0, 3))))),
(:(=), :xs, (:range, (:parameters, (:kw, :length, 400)), (:-, :π), :π)),
(:plot, (:parameters, (:kw, :legend, QuoteNode(:topleft)))),
(:scatter!, (:parameters, (:kw, :label, "sample")), :x, :y),
(:plot!, (:parameters,
(:kw, :label, "sin(x)"),
(:kw, :color, QuoteNode(:blue)),
(:kw, :ls, QuoteNode(:dash))),
:xs, (:., :sin, (:tuple, :xs))),
(:plot!, (:parameters,
(:kw, :label, "degree-3 polynomial"),
(:kw, :color, QuoteNode(:red)),
(:kw, :lw, 2)),
:xs, (:., :f, (:tuple, :xs)))) |> texpr2expr |>
x -> display("text/markdown", "```julia\n$x\n```")
```
## Documents
```julia
@doc MetaUtils
```
```julia
@doc @show_sexpr
```
```julia
@doc @show_tree
```
```julia
@doc print_subtypes
```
```julia
@doc show_expr
```
```julia
@doc @show_expr
```
```julia
@doc show_texpr
```
```julia
@doc @show_texpr
```
```julia
@doc teval
```
```julia
@doc @teval
```
```julia
@doc MetaUtils.@t
```
```julia
@doc MetaUtils.@T
```
```julia
```
| MetaUtils | https://github.com/genkuroki/MetaUtils.jl.git |
|
[
"MIT"
] | 0.1.5 | 9b6360885ae561b9652f32f7e4d83838e8e23e1b | docs | 2695 | # MetaUtils - Utilities for metaprogramming in Julia
<!--
[](https://genkuroki.github.io/MetaUtils.jl/stable)
-->
[](https://genkuroki.github.io/MetaUtils.jl/dev)
[](https://travis-ci.com/genkuroki/MetaUtils.jl)
This package provides the utilities not found in InteractiveUtils and Meta modules. This is the renamed and enhanced version of the deprecated package [InteractiveUtilsPlus.jl](https://github.com/genkuroki/InteractiveUtilsPlus.jl).
## Installation
Add this package by REPL package manager:
```julia
julia> ]
pkg> add https://github.com/genkuroki/MetaUtils.jl
```
Or, add this package using Pkg.jl.
```julia
julia> using Pkg; Pkg.add(url="https://github.com/genkuroki/MetaUtils.jl")
```
## Examples
For the detaild usage, see the Jupyter notebook [MetaUtils.ipynb](https://nbviewer.jupyter.org/github/genkuroki/MetaUtils.jl/blob/master/MetaUtils.ipynb).
```julia
julia> using MetaUtils
```
```julia
julia> @show_sexpr 2x+1
(:call, :+, (:call, :*, 2, :x), 1)
```
```julia
julia> x = 10; (:call, :+, (:call, :*, 2, :x), 1) |> teval
21
```
```julia
julia> @show_tree 2x+1
:call
├─ :+
├─ :call
│ ├─ :*
│ ├─ 2
│ └─ :x
└─ 1
```
```julia
julia> print_subtypes(AbstractRange)
AbstractRange
├─ LinRange
├─ OrdinalRange
│ ├─ AbstractUnitRange
│ │ ├─ Base.IdentityUnitRange
│ │ ├─ Base.OneTo
│ │ ├─ Base.Slice
│ │ └─ UnitRange
│ └─ StepRange
└─ StepRangeLen
```
```julia
julia> show_expr(:(f(x, g(y, z))))
Expr(:call, :f, :x,
Expr(:call, :g, :y, :z))
```
```julia
julia> @show_expr 2x+1
Expr(:call, :+,
Expr(:call, :*, 2, :x), 1)
```
```julia
julia> x = 10; Expr(:call, :+,
Expr(:call, :*, 2, :x), 1) |> eval
21
```
```julia
julia> show_texpr(:(f(x, g(y, z))))
Expr(:call, :f, :x,
Expr(:call, :g, :y, :z))
```
```julia
julia> @show_texpr 2x+1
(:call, :+,
(:call, :*, 2, :x), 1)
```
```julia
julia> x = 10; (:call, :+,
(:call, :*, 2, :x), 1) |> teval
21
```
```julia
julia> (:call, :sin, (:call, :/, π, 6)) |> teval
0.49999999999999994
```
```julia
julia> @teval (:call, :sin, (:call, :/, π, 6))
0.49999999999999994
```
```julia
julia> (:sin, (:/, π, 6)) |> teval
0.49999999999999994
```
```julia
julia> @teval (:sin, (:/, π, 6))
0.49999999999999994
```
```julia
julia> MetaUtils.@t (:call, :sin, (:call, :/, π, 6))
:(sin(π / 6))
→ 0.49999999999999994
```
```julia
julia> MetaUtils.@T (:call, :sin, (:call, :/, π, 6))
(:call, :sin, (:call, :/, π, 6))
→ (:call, :sin,
(:call, :/, π, 6))
→ :(sin(π / 6))
→ 0.49999999999999994
```
| MetaUtils | https://github.com/genkuroki/MetaUtils.jl.git |
|
[
"MIT"
] | 0.1.5 | 9b6360885ae561b9652f32f7e4d83838e8e23e1b | docs | 107 | ```@meta
CurrentModule = MetaUtils
```
# MetaUtils
```@index
```
```@autodocs
Modules = [MetaUtils]
```
| MetaUtils | https://github.com/genkuroki/MetaUtils.jl.git |
|
[
"MIT"
] | 0.2.0 | b988b82bbde556f2d50243b8defd685dea9ebcd7 | code | 6144 | module PositionVelocityTime
using CoordinateTransformations,
DocStringExtensions,
Geodesy,
GNSSDecoder,
GNSSSignals,
LinearAlgebra,
Parameters,
AstroTime,
LsqFit,
StaticArrays,
Tracking,
Unitful,
Statistics
using Unitful: s, Hz
const SPEEDOFLIGHT = 299792458.0
export calc_pvt,
PVTSolution,
SatelliteState,
get_LLA,
get_num_used_sats,
calc_satellite_position,
calc_satellite_position_and_velocity,
get_sat_enu,
get_gdop,
get_pdop,
get_hdop,
get_vdop,
get_tdop,
get_frequency_offset
"""
Struct of decoder, code- and carrierphase of satellite
"""
@with_kw struct SatelliteState{CP<:Real}
decoder::GNSSDecoder.GNSSDecoderState
system::AbstractGNSS
code_phase::CP
carrier_doppler::typeof(1.0Hz)
carrier_phase::CP = 0.0
end
function SatelliteState(
decoder::GNSSDecoder.GNSSDecoderState,
tracking_results::Tracking.TrackingResults,
)
SatelliteState(
decoder,
get_system(tracking_results),
get_code_phase(tracking_results),
get_carrier_doppler(tracking_results),
get_carrier_phase(tracking_results),
)
end
"""
Dilution of Precision (DOP)
"""
struct DOP
GDOP::Float64
PDOP::Float64
VDOP::Float64
HDOP::Float64
TDOP::Float64
end
struct SatInfo
position::ECEF
time::Float64
end
"""
PVT solution including DOP, used satellites and satellite
positions.
"""
@with_kw struct PVTSolution
position::ECEF = ECEF(0, 0, 0)
velocity::ECEF = ECEF(0, 0, 0)
time_correction::Float64 = 0
time::Union{TAIEpoch{Float64},Nothing} = nothing
relative_clock_drift::Float64 = 0
dop::Union{DOP,Nothing} = nothing
sats::Dict{Int, SatInfo} = Dict{Int, SatInfo}()
end
function get_num_used_sats(pvt_solution::PVTSolution)
length(pvt_solution.used_sats)
end
#Get methods for single DOP values
function get_gdop(pvt_sol::PVTSolution)
return pvt_sol.dop.GDOP
end
function get_pdop(pvt_sol::PVTSolution)
return pvt_sol.dop.PDOP
end
function get_vdop(pvt_sol::PVTSolution)
return pvt_sol.dop.VDOP
end
function get_hdop(pvt_sol::PVTSolution)
return pvt_sol.dop.HDOP
end
function get_tdop(pvt_sol::PVTSolution)
return pvt_sol.dop.TDOP
end
"""
Calculates East-North-Up (ENU) coordinates of satellite in spherical
form (azimuth and elevation).
$SIGNATURES
user_pos_ecef: user position in ecef coordinates
sat_pos_ecef: satellite position in ecef coordinates
"""
function get_sat_enu(user_pos_ecef::ECEF, sat_pos_ecef::ECEF)
sat_enu = ENUfromECEF(user_pos_ecef, wgs84)(sat_pos_ecef)
SphericalFromCartesian()(sat_enu)
end
"""
Calculates Position Velocity and Time (PVT).
Note: Estimation of velocity still needs to be implemented.
$SIGNATURES
`system`: GNSS system
`states`: Vector satellite states (SatelliteState)
`prev_pvt` (optionally): Previous PVT solution to accelerate calculation of next
PVT.
"""
function calc_pvt(
states::AbstractVector{<:SatelliteState},
prev_pvt::PVTSolution = PVTSolution(),
)
length(states) < 4 &&
throw(ArgumentError("You'll need at least 4 satellites to calculate PVT"))
all(state -> state.system == states[1].system, states) ||
ArgumentError("For now all satellites need to be base on the same GNSS")
system = first(states).system
healthy_states = filter(x -> is_sat_healthy(x.decoder), states)
if length(healthy_states) < 4
return prev_pvt
end
prev_ξ = [prev_pvt.position; prev_pvt.time_correction]
healthy_prns = map(state -> state.decoder.prn, healthy_states)
times = map(state -> calc_corrected_time(state), healthy_states)
sat_positions_and_velocities = map(
(state, time) -> calc_satellite_position_and_velocity(state.decoder, time),
healthy_states,
times,
)
sat_positions = map(get_sat_position, sat_positions_and_velocities)
pseudo_ranges, reference_time = calc_pseudo_ranges(times)
ξ, rmse = user_position(sat_positions, pseudo_ranges)
user_velocity_and_clock_drift =
calc_user_velocity_and_clock_drift(sat_positions_and_velocities, ξ, healthy_states)
position = ECEF(ξ[1], ξ[2], ξ[3])
velocity = ECEF(
user_velocity_and_clock_drift[1],
user_velocity_and_clock_drift[2],
user_velocity_and_clock_drift[3],
)
relative_clock_drift = user_velocity_and_clock_drift[4] / SPEEDOFLIGHT
time_correction = ξ[4]
corrected_reference_time = reference_time + time_correction / SPEEDOFLIGHT
week = get_week(first(healthy_states).decoder)
start_time = get_system_start_time(first(healthy_states).decoder)
time = TAIEpoch(
week * 7 * 24 * 60 * 60 + floor(Int, corrected_reference_time) + start_time.second,
corrected_reference_time - floor(Int, corrected_reference_time),
)
sat_infos = SatInfo.(
sat_positions,
times
)
dop = calc_DOP(calc_H(reduce(hcat, sat_positions), ξ))
if dop.GDOP < 0
return prev_pvt
end
PVTSolution(
position,
velocity,
time_correction,
time,
relative_clock_drift,
dop,
Dict(healthy_prns .=> sat_infos)
)
end
function get_frequency_offset(pvt::PVTSolution, base_frequency)
pvt.relative_clock_drift * base_frequency
end
function get_system_start_time(
decoder::GNSSDecoder.GNSSDecoderState{<:GNSSDecoder.GPSL1Data},
)
TAIEpoch(1980, 1, 6, 0, 0, 19.0) # There were 19 leap seconds at 01/06/1999 compared to UTC
end
function get_system_start_time(
decoder::GNSSDecoder.GNSSDecoderState{<:GNSSDecoder.GalileoE1BData},
)
TAIEpoch(1999, 8, 22, 0, 0, (32 - 13.0)) # There were 32 leap seconds at 08/22/1999 compared to UTC
end
function get_week(decoder::GNSSDecoder.GNSSDecoderState{<:GNSSDecoder.GPSL1Data})
2048 + decoder.data.trans_week
end
function get_week(decoder::GNSSDecoder.GNSSDecoderState{<:GNSSDecoder.GalileoE1BData})
decoder.data.WN
end
function get_LLA(pvt::PVTSolution)
LLAfromECEF(wgs84)(pvt.position)
end
include("user_position.jl")
include("sat_time.jl")
include("sat_position.jl")
end
| PositionVelocityTime | https://github.com/JuliaGNSS/PositionVelocityTime.jl.git |
|
[
"MIT"
] | 0.2.0 | b988b82bbde556f2d50243b8defd685dea9ebcd7 | code | 7259 | function calc_eccentric_anomaly(mean_anomaly, eccentricity)
Ek = mean_anomaly
for k = 1:30
Et = Ek
Ek = mean_anomaly + eccentricity * sin(Ek)
if abs(Ek - Et) <= 1e-12
break
end
end
return Ek
end
function calc_eccentric_anomaly(decoder::GNSSDecoder.GNSSDecoderState, t)
data = decoder.data
computed_mean_motion = sqrt(decoder.constants.μ) / data.sqrt_A^3
time_from_ephemeris_reference_epoch = correct_week_crossovers(t - data.t_0e)
corrected_mean_motion = computed_mean_motion + data.Δn
mean_anomaly = data.M_0 + corrected_mean_motion * time_from_ephemeris_reference_epoch
calc_eccentric_anomaly(mean_anomaly, data.e)
end
"""
Calculates satellite position at time instance t
$SIGNATURES
`decoder`: GNSS decoder state
`t`: time at satellite in system time
"""
function calc_satellite_position(decoder::GNSSDecoder.GNSSDecoderState, t)
pos_and_vel = calc_satellite_position_and_velocity(decoder, t)
pos_and_vel.position
end
function calc_satellite_position_and_velocity(decoder::GNSSDecoder.GNSSDecoderState, t)
data = decoder.data
constants = decoder.constants
semi_major_axis = data.sqrt_A^2
time_from_ephemeris_reference_epoch = correct_week_crossovers(t - data.t_0e)
computed_mean_motion = sqrt(decoder.constants.μ) / data.sqrt_A^3
corrected_mean_motion = computed_mean_motion + data.Δn
eccentric_anomaly = calc_eccentric_anomaly(decoder, t)
eccentric_anomaly_dot = corrected_mean_motion / (1.0 - data.e * cos(eccentric_anomaly))
β = data.e / (1 + sqrt(1 - data.e^2))
true_anomaly =
eccentric_anomaly +
2 * atan(β * sin(eccentric_anomaly) / (1 - β * cos(eccentric_anomaly)))
true_anomaly_dot =
sin(eccentric_anomaly) *
eccentric_anomaly_dot *
(1.0 + data.e * cos(true_anomaly)) /
(sin(true_anomaly) * (1.0 - data.e * cos(eccentric_anomaly)))
argument_of_latitude = true_anomaly + data.ω
argrument_of_latitude_correction =
data.C_us * sin(2 * argument_of_latitude) +
data.C_uc * cos(2 * argument_of_latitude)
radius_correction =
data.C_rs * sin(2 * argument_of_latitude) +
data.C_rc * cos(2 * argument_of_latitude)
inclination_correction =
data.C_is * sin(2 * argument_of_latitude) +
data.C_ic * cos(2 * argument_of_latitude)
corrected_argument_of_latitude = argument_of_latitude + argrument_of_latitude_correction
corrected_radius =
semi_major_axis * (1 - data.e * cos(eccentric_anomaly)) + radius_correction
corrected_inclination =
data.i_0 + inclination_correction + data.i_dot * time_from_ephemeris_reference_epoch
corrected_argument_of_latitude_dot =
true_anomaly_dot +
2 *
(
data.C_us * cos(2 * corrected_argument_of_latitude) -
data.C_uc * sin(2 * corrected_argument_of_latitude)
) *
true_anomaly_dot
corrected_radius_dot =
semi_major_axis * data.e * sin(eccentric_anomaly) * corrected_mean_motion /
(1.0 - data.e * cos(eccentric_anomaly)) +
2 *
(
data.C_rs * cos(2 * corrected_argument_of_latitude) -
data.C_rc * sin(2 * corrected_argument_of_latitude)
) *
true_anomaly_dot
corrected_inclination_dot =
data.i_dot +
(
data.C_is * cos(2 * corrected_argument_of_latitude) -
data.C_ic * sin(2 * corrected_argument_of_latitude)
) *
2 *
true_anomaly_dot
x_position_in_orbital_plane = corrected_radius * cos(corrected_argument_of_latitude)
y_position_in_orbital_plane = corrected_radius * sin(corrected_argument_of_latitude)
x_position_in_orbital_plane_dot =
corrected_radius_dot * cos(corrected_argument_of_latitude) -
y_position_in_orbital_plane * corrected_argument_of_latitude_dot
y_position_in_orbital_plane_dot =
corrected_radius_dot * sin(corrected_argument_of_latitude) +
x_position_in_orbital_plane * corrected_argument_of_latitude_dot
corrected_longitude_of_ascending_node =
data.Ω_0 + (data.Ω_dot - constants.Ω_dot_e) * time_from_ephemeris_reference_epoch -
constants.Ω_dot_e * data.t_0e
corrected_longitude_of_ascending_node_dot = data.Ω_dot - constants.Ω_dot_e
position = SVector(
x_position_in_orbital_plane * cos(corrected_longitude_of_ascending_node) -
y_position_in_orbital_plane *
cos(corrected_inclination) *
sin(corrected_longitude_of_ascending_node),
x_position_in_orbital_plane * sin(corrected_longitude_of_ascending_node) +
y_position_in_orbital_plane *
cos(corrected_inclination) *
cos(corrected_longitude_of_ascending_node),
y_position_in_orbital_plane * sin(corrected_inclination),
)
velocity = SVector(
(
x_position_in_orbital_plane_dot -
y_position_in_orbital_plane *
cos(corrected_inclination) *
corrected_longitude_of_ascending_node_dot
) * cos(corrected_longitude_of_ascending_node) -
(
x_position_in_orbital_plane * corrected_longitude_of_ascending_node_dot +
y_position_in_orbital_plane_dot * cos(corrected_inclination) -
y_position_in_orbital_plane *
sin(corrected_inclination) *
corrected_inclination_dot
) * sin(corrected_longitude_of_ascending_node),
(
x_position_in_orbital_plane_dot -
y_position_in_orbital_plane *
cos(corrected_inclination) *
corrected_longitude_of_ascending_node_dot
) * sin(corrected_longitude_of_ascending_node) +
(
x_position_in_orbital_plane * corrected_longitude_of_ascending_node_dot +
y_position_in_orbital_plane_dot * cos(corrected_inclination) -
y_position_in_orbital_plane *
sin(corrected_inclination) *
corrected_inclination_dot
) * cos(corrected_longitude_of_ascending_node),
y_position_in_orbital_plane_dot * sin(corrected_inclination) +
y_position_in_orbital_plane *
cos(corrected_inclination) *
corrected_inclination_dot,
)
(position = position, velocity = velocity)
end
"""
Calculates satellite position at transmission time based on code phase and number of bits since TOW.
$SIGNATURES
`system`: GNSS system
`state`: Satellite state (SatelliteState)
"""
function calc_satellite_position(state::SatelliteState)
pos_and_vel = calc_satellite_position_and_velocity(state)
pos_and_vel.position
end
function calc_satellite_position_and_velocity(state::SatelliteState)
t = calc_corrected_time(state)
calc_satellite_position_and_velocity(state.decoder, t)
end
"""
Computes pseudo ranges
$SIGNATURES
`sat_state`: satellite state, combining decoded data, code- and carrierphase
Computes relative pseudo ranges of satellite vehicles.
The algorithm is based on the common reception method.
"""
function calc_pseudo_ranges(times)
t_ref = maximum(times)
reference_times = map(time -> t_ref - time, times)
pseudoranges = reference_times .* SPEEDOFLIGHT
return pseudoranges, t_ref
end | PositionVelocityTime | https://github.com/JuliaGNSS/PositionVelocityTime.jl.git |
|
[
"MIT"
] | 0.2.0 | b988b82bbde556f2d50243b8defd685dea9ebcd7 | code | 1957 | function correct_week_crossovers(t)
half_week = 302400 #Half of Week in Seconds
t + (t > half_week ? -2 * half_week : (t < -half_week ? 2 * half_week : 0.0))
end
function calc_uncorrected_time(state::SatelliteState)
system = state.system
t_tow = state.decoder.data.TOW
t_bits =
state.decoder.num_bits_after_valid_syncro_sequence /
GNSSSignals.get_data_frequency(system) * Hz
t_code_phase = state.code_phase / GNSSSignals.get_code_frequency(system) * Hz
t_carrier_phase = state.carrier_phase / GNSSSignals.get_center_frequency(system) * Hz
t_tow + t_bits + t_code_phase + t_carrier_phase
end
function calc_relativistic_correction(decoder::GNSSDecoder.GNSSDecoderState, t)
E = calc_eccentric_anomaly(decoder, t)
decoder.constants.F * decoder.data.e * decoder.data.sqrt_A * sin(E)
end
function correct_clock(decoder::GNSSDecoder.GNSSDecoderState, t)
Δtr = calc_relativistic_correction(decoder, t)
Δt =
decoder.data.a_f0 +
decoder.data.a_f1 * (t - decoder.data.t_0c) +
decoder.data.a_f2 * (t - decoder.data.t_0c)^2 +
Δtr
t - correct_by_group_delay(decoder, Δt)
end
function calc_satellite_clock_drift(decoder::GNSSDecoder.GNSSDecoderState, t)
decoder.data.a_f1 +
decoder.data.a_f2 * t * 2
end
function calc_satellite_clock_drift(state::SatelliteState)
approximated_time = calc_uncorrected_time(state)
calc_satellite_clock_drift(state.decoder, approximated_time)
end
function correct_by_group_delay(
decoder::GNSSDecoder.GNSSDecoderState{<:GNSSDecoder.GPSL1Data},
t,
)
t - decoder.data.T_GD
end
function correct_by_group_delay(
decoder::GNSSDecoder.GNSSDecoderState{<:GNSSDecoder.GalileoE1BData},
t,
)
t - decoder.data.broadcast_group_delay_e1_e5b
end
function calc_corrected_time(state::SatelliteState)
approximated_time = calc_uncorrected_time(state)
correct_clock(state.decoder, approximated_time)
end | PositionVelocityTime | https://github.com/JuliaGNSS/PositionVelocityTime.jl.git |
|
[
"MIT"
] | 0.2.0 | b988b82bbde556f2d50243b8defd685dea9ebcd7 | code | 3741 |
"""
Computes ̂ρ, the distance between the satellite and the estimated user position
$SIGNATURES
`ξ`: Combination of estimated user position and time correction
`sat_positions`: Satellite Positions
"""
function calc_ρ_hat(sat_positions, ξ)
rₙ = ξ[1:3]
tc = ξ[4]
map(eachcol(sat_positions)) do sat_pos
travel_time = norm(sat_pos - rₙ) / SPEEDOFLIGHT
rotated_sat_pos = rotate_by_earth_rotation(sat_pos, travel_time)
norm(rotated_sat_pos - rₙ) + tc
end
end
function rotate_by_earth_rotation(sat_pos, Δt)
ω_e = 7.2921151467e-5
α = ω_e * Δt
Rz = @SMatrix [
cos(α) sin(α) 0
-sin(α) cos(α) 0
0 0 1
]
Rz * sat_pos
end
"""
Computes e, the direction vector from satellite to user
$SIGNATURES
`ξ`: Combination of estimated user position and time correction
`sat_pos`: Single satellite positions
"""
function calc_e(sat_pos, ξ)
rₙ = ξ[1:3]
travel_time = norm(sat_pos - rₙ) / SPEEDOFLIGHT
rotated_sat_pos = rotate_by_earth_rotation(sat_pos, travel_time)
(rₙ - rotated_sat_pos) / norm(rₙ - rotated_sat_pos)
end
"""
Computes Geometry Matrix H
$SIGNATURES
`ξ`: Combination of estimated user position and time correction
`sat_positions`: Matrix of satellite positions
"""
function calc_H(sat_positions, ξ)
mapreduce(sat_pos -> [transpose(calc_e(sat_pos, ξ)) 1], vcat, eachcol(sat_positions))
end
"""
Calculates the dilution of precision for a given geometry matrix H
$SIGNATURES
`H_GEO`: Geometry matrix
"""
function calc_DOP(H_GEO)
D = inv(Symmetric(collect(H_GEO' * H_GEO)))
if D[4, 4] < 0 ||
D[3, 3] < 0 ||
D[1, 1] + D[2, 2] < 0 ||
D[1, 1] + D[2, 2] + D[3, 3] < 0 ||
sum(diag(D)) < 0
# Something has gone wrong
# This could probably be detected somewhere else
# more efficiently.
return DOP(-1, -1, -1, -1, -1)
end
TDOP = sqrt(D[4, 4]) # temporal dop
VDOP = sqrt(D[3, 3]) # vertical dop
HDOP = sqrt(D[1, 1] + D[2, 2]) # horizontal dop
PDOP = sqrt(D[1, 1] + D[2, 2] + D[3, 3]) # position dop
GDOP = sqrt(sum(diag(D))) # geometrical dop
return DOP(GDOP, PDOP, VDOP, HDOP, TDOP)
end
"""
Computes user position
$SIGNATURES
sat_positions: Array of satellite positions. Needs 3 values per satellite (xyz), size must be (3, N)")
`ρ`: Array of pseudo ranges
Calculates the user position by least squares method. The algorithm is based on the common reception method.
"""
function user_position(sat_positions, ρ, prev_ξ = zeros(4))
sat_positions_mat = reduce(hcat, sat_positions)
ξ_fit_ols = curve_fit(calc_ρ_hat, calc_H, sat_positions_mat, ρ, collect(prev_ξ))
# wt = 1 ./ (ξ_fit_ols.resid .^ 2)
# ξ_fit_wls = curve_fit(ρ_hat, H, sat_positions_mat, ρ, wt, collect(prev_ξ))
rmse = sqrt(mean(ξ_fit_ols.resid .^ 2))
return ξ_fit_ols.param, rmse
end
"""
Computes user velocity
$SIGNATURES
Calculates the user velocity and clock drift
"""
function calc_user_velocity_and_clock_drift(sat_positions_and_velocities, ξ, states)
sat_positions = map(get_sat_position, sat_positions_and_velocities)
sat_positions_mat = reduce(hcat, sat_positions)
sat_clock_drifts = map(calc_satellite_clock_drift, states)
sat_dopplers = map(x -> upreferred(x.carrier_doppler / Hz), states)
H = collect(calc_H(sat_positions_mat, ξ))
center_frequency = get_center_frequency(first(states).system)
λ = SPEEDOFLIGHT / upreferred(center_frequency / Hz)
y =
sat_dopplers * λ -
sat_clock_drifts * SPEEDOFLIGHT -
map(x -> dot(calc_e(get_sat_position(x), ξ), get_sat_velocity(x)), sat_positions_and_velocities)
H \ y
end
get_sat_position(x) = x.position
get_sat_velocity(x) = x.velocity | PositionVelocityTime | https://github.com/JuliaGNSS/PositionVelocityTime.jl.git |
|
[
"MIT"
] | 0.2.0 | b988b82bbde556f2d50243b8defd685dea9ebcd7 | code | 51240 | BitIntegers.@define_integers 288
BitIntegers.@define_integers 320
@testset "PVT Galileo E1B with frequency offset of $freq_offset" for freq_offset in (0.0Hz, 500Hz, -1000Hz)
galileo_e1b = GalileoE1B()
states = [
SatelliteState(;
decoder = GNSSDecoderState(
2,
uint288"0x4001ec23bff8485200005ec5ff7a895805f4d37fe877968040ae99fffd20b00d205dcf80",
uint288"0xd2a6aec5828003d8477ff090a40000bd8bfef512b00be9a6ffd0ef2d00815d33fffa4160",
GNSSDecoder.GalileoE1BData(
1136,
132769,
132000.0,
1.885093958164237,
0.0002336719771847129,
5440.601516723633,
0.43151849653459906,
0.9782668574498574,
0.18081747042485646,
-3.6965825489294766e-10,
-5.353794435599309e-9,
3.053341469642328e-9,
1.9334256649017334e-6,
8.616596460342407e-6,
163.65625,
40.46875,
-4.284083843231201e-8,
7.264316082000732e-8,
132000.0,
0.00022286397870630026,
2.5721647034515627e-12,
0.0,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
5,
GNSSDecoder.signal_ok,
GNSSDecoder.signal_ok,
GNSSDecoder.navigation_data_valid,
GNSSDecoder.navigation_data_valid,
-1.6298145055770874e-9,
-2.0954757928848267e-9,
),
GNSSDecoder.GalileoE1BData(
1136,
132769,
132000.0,
1.885093958164237,
0.0002336719771847129,
5440.601516723633,
0.43151849653459906,
0.9782668574498574,
0.18081747042485646,
-3.6965825489294766e-10,
-5.353794435599309e-9,
3.053341469642328e-9,
1.9334256649017334e-6,
8.616596460342407e-6,
163.65625,
40.46875,
-4.284083843231201e-8,
7.264316082000732e-8,
132000.0,
0.00022286397870630026,
2.5721647034515627e-12,
0.0,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
5,
GNSSDecoder.signal_ok,
GNSSDecoder.signal_ok,
GNSSDecoder.navigation_data_valid,
GNSSDecoder.navigation_data_valid,
-1.6298145055770874e-9,
-2.0954757928848267e-9,
),
GNSSDecoder.GalileoE1BConstants(
250,
0x0160,
10,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986004418e14,
-4.442807309e-10,
),
GNSSDecoder.GalileoE1BCache(0x00000c5cffc5722165040e1212147505),
49,
1549,
false,
),
system = galileo_e1b,
carrier_doppler = 1617.3312825078192Hz + freq_offset,
code_phase = 2216.5793761534956,
carrier_phase = -1.461823180908076,
),
SatelliteState(;
decoder = GNSSDecoderState(
4,
uint288"0xc3ffc21fe800f025ffffeba64010c2fcff43fd5002fd6eaff7f228c000c1e9fe5bc6460f",
uint288"0xd158f0c583c003de017ff0fda00001459bfef3d0300bc02affd029150080dd73fff3e160",
GNSSDecoder.GalileoE1BData(
1136,
132769,
128400.0,
1.1883716376830096,
0.0003440612927079201,
5440.625782012939,
-1.666444269041331,
0.9544851798532423,
-1.401875745066068,
4.318037006430664e-10,
-5.442726711414135e-9,
3.016554223020131e-9,
-2.2649765014648438e-6,
9.763985872268677e-6,
128.46875,
-51.40625,
5.029141902923584e-8,
-2.2351741790771484e-8,
128400.0,
-0.0007824758649803698,
-8.01492205937393e-12,
0.0,
0x0000000000000056,
0x0000000000000056,
0x0000000000000056,
0x0000000000000056,
5,
GNSSDecoder.signal_ok,
GNSSDecoder.signal_ok,
GNSSDecoder.navigation_data_valid,
GNSSDecoder.navigation_data_valid,
-3.026798367500305e-9,
-3.4924596548080444e-9,
),
GNSSDecoder.GalileoE1BData(
1136,
132769,
128400.0,
1.1883716376830096,
0.0003440612927079201,
5440.625782012939,
-1.666444269041331,
0.9544851798532423,
-1.401875745066068,
4.318037006430664e-10,
-5.442726711414135e-9,
3.016554223020131e-9,
-2.2649765014648438e-6,
9.763985872268677e-6,
128.46875,
-51.40625,
5.029141902923584e-8,
-2.2351741790771484e-8,
128400.0,
-0.0007824758649803698,
-8.01492205937393e-12,
0.0,
0x0000000000000056,
0x0000000000000056,
0x0000000000000056,
0x0000000000000056,
5,
GNSSDecoder.signal_ok,
GNSSDecoder.signal_ok,
GNSSDecoder.navigation_data_valid,
GNSSDecoder.navigation_data_valid,
-3.026798367500305e-9,
-3.4924596548080444e-9,
),
GNSSDecoder.GalileoE1BConstants(
250,
0x0160,
10,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986004418e14,
-4.442807309e-10,
),
GNSSDecoder.GalileoE1BCache(0x00000c56ffc47920fefb40147a100ff9),
46,
1546,
true,
),
system = galileo_e1b,
carrier_doppler = 4055.9318556579988Hz + freq_offset,
code_phase = 48.75149191469789,
carrier_phase = -2.3877702498883373,
),
SatelliteState(;
decoder = GNSSDecoderState(
11,
uint288"0x8007b086ffe1b77000036397fde280e017a75dffa08a320100aa47ffeec2c03481373e00",
uint288"0xd4878bc5834003d8437ff0dbb80001b1cbfef140700bd3aeffd0451900805523fff76160",
GNSSDecoder.GalileoE1BData(
1136,
132769,
132000.0,
0.7593379982069668,
0.0005043556448072195,
5440.614900588989,
2.515118401165434,
0.9919634586882758,
0.7810709950849496,
-1.821504444400032e-11,
-5.659164298336962e-9,
2.699398155054008e-9,
6.221234798431396e-7,
2.125278115272522e-6,
311.3125,
12.25,
-2.9802322387695312e-8,
5.4016709327697754e-8,
132000.0,
0.005911215674132109,
-4.936850928061176e-11,
0.0,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
5,
GNSSDecoder.signal_ok,
GNSSDecoder.signal_ok,
GNSSDecoder.navigation_data_valid,
GNSSDecoder.navigation_data_valid,
-1.3271346688270569e-8,
-1.4435499906539917e-8,
),
GNSSDecoder.GalileoE1BData(
1136,
132769,
132000.0,
0.7593379982069668,
0.0005043556448072195,
5440.614900588989,
2.515118401165434,
0.9919634586882758,
0.7810709950849496,
-1.821504444400032e-11,
-5.659164298336962e-9,
2.699398155054008e-9,
6.221234798431396e-7,
2.125278115272522e-6,
311.3125,
12.25,
-2.9802322387695312e-8,
5.4016709327697754e-8,
132000.0,
0.005911215674132109,
-4.936850928061176e-11,
0.0,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
5,
GNSSDecoder.signal_ok,
GNSSDecoder.signal_ok,
GNSSDecoder.navigation_data_valid,
GNSSDecoder.navigation_data_valid,
-1.3271346688270569e-8,
-1.4435499906539917e-8,
),
GNSSDecoder.GalileoE1BConstants(
250,
0x0160,
10,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986004418e14,
-4.442807309e-10,
),
GNSSDecoder.GalileoE1BCache(0x00000c5cffc21b1d86014e047526ea01),
51,
1551,
false,
),
system = galileo_e1b,
carrier_doppler = 209.7024609093128Hz + freq_offset,
code_phase = 69.54389556899758,
carrier_phase = -1.4138935647217596,
),
SatelliteState(;
decoder = GNSSDecoderState(
25,
uint288"0x7fff0d5ea003cad0ffffe78900422343fd0b07400be9b7bfdf65a700010ba7f96fe9183f",
uint288"0xd1dbd245820003ca857ff0d4bc000061dbfef772f00bd3e2ffd0592100826963fffbd160",
GNSSDecoder.GalileoE1BData(
1136,
132769,
132000.0,
-2.0355462626837646,
0.00014415336772799492,
5440.611436843872,
0.42869178039052547,
0.9778386598651378,
-1.4136735049701232,
-3.982308736286344e-10,
-5.379866950195624e-9,
3.036555056135112e-9,
1.9241124391555786e-6,
8.305534720420837e-6,
172.59375,
40.625,
-7.450580596923828e-8,
3.3527612686157227e-8,
132000.0,
-0.000535494415089488,
-1.2221335055073723e-12,
0.0,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
5,
GNSSDecoder.signal_ok,
GNSSDecoder.signal_ok,
GNSSDecoder.navigation_data_valid,
GNSSDecoder.navigation_data_valid,
3.4924596548080444e-9,
3.958120942115784e-9,
),
GNSSDecoder.GalileoE1BData(
1136,
132769,
132000.0,
-2.0355462626837646,
0.00014415336772799492,
5440.611436843872,
0.42869178039052547,
0.9778386598651378,
-1.4136735049701232,
-3.982308736286344e-10,
-5.379866950195624e-9,
3.036555056135112e-9,
1.9241124391555786e-6,
8.305534720420837e-6,
172.59375,
40.625,
-7.450580596923828e-8,
3.3527612686157227e-8,
132000.0,
-0.000535494415089488,
-1.2221335055073723e-12,
0.0,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
5,
GNSSDecoder.signal_ok,
GNSSDecoder.signal_ok,
GNSSDecoder.navigation_data_valid,
GNSSDecoder.navigation_data_valid,
3.4924596548080444e-9,
3.958120942115784e-9,
),
GNSSDecoder.GalileoE1BConstants(
250,
0x0160,
10,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986004418e14,
-4.442807309e-10,
),
GNSSDecoder.GalileoE1BCache(0x00000c5cffc52921360409116b159305),
48,
1548,
true,
),
system = galileo_e1b,
carrier_doppler = -974.6289079820336Hz + freq_offset,
code_phase = 1701.8894620076721,
carrier_phase = -1.721713905186919,
),
SatelliteState(;
decoder = GNSSDecoderState(
30,
uint288"0xa7ff845f3001e40b7fffe54480215fd1fe85d2a005fd7cdfefff5b800197d3fcb7a08c1f",
uint288"0xd3f0160582c003dd067ff0dfa40000d5dbfef501700bd16affd0141900800523fff34160",
GNSSDecoder.GalileoE1BData(
1136,
132769,
132000.0,
0.43031807277213097,
0.00031052413396537304,
5440.595668792725,
0.43339143836728705,
0.9757531121479899,
0.869054289656611,
-3.9465929628667357e-10,
-5.42129724736237e-9,
3.102986394695584e-9,
2.089887857437134e-6,
8.553266525268555e-6,
162.5,
45.375,
8.754432201385498e-8,
8.195638656616211e-8,
132000.0,
0.002901351428590715,
-3.0667024475405924e-11,
0.0,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
5,
GNSSDecoder.signal_ok,
GNSSDecoder.signal_ok,
GNSSDecoder.navigation_data_valid,
GNSSDecoder.navigation_data_valid,
1.6298145055770874e-9,
1.6298145055770874e-9,
),
GNSSDecoder.GalileoE1BData(
1136,
132769,
132000.0,
0.43031807277213097,
0.00031052413396537304,
5440.595668792725,
0.43339143836728705,
0.9757531121479899,
0.869054289656611,
-3.9465929628667357e-10,
-5.42129724736237e-9,
3.102986394695584e-9,
2.089887857437134e-6,
8.553266525268555e-6,
162.5,
45.375,
8.754432201385498e-8,
8.195638656616211e-8,
132000.0,
0.002901351428590715,
-3.0667024475405924e-11,
0.0,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
0x000000000000005c,
5,
GNSSDecoder.signal_ok,
GNSSDecoder.signal_ok,
GNSSDecoder.navigation_data_valid,
GNSSDecoder.navigation_data_valid,
1.6298145055770874e-9,
1.6298145055770874e-9,
),
GNSSDecoder.GalileoE1BConstants(
250,
0x0160,
10,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986004418e14,
-4.442807309e-10,
),
GNSSDecoder.GalileoE1BCache(0x00000c5cffc4b521f0046211f0145005),
47,
1547,
true,
),
system = galileo_e1b,
carrier_doppler = 4089.415808665647Hz + freq_offset,
code_phase = 4015.495436832823,
carrier_phase = -2.8554107708683047,
),
]
pvt = calc_pvt(states)
@test get_LLA(pvt) ≈
LLA(; lat = 50.778851672464015, lon = 6.065568885758519, alt = 289.4069805158367)
@test pvt.time ≈ TAIEpoch(2021, 5, 31, 12, 53, 14.1183385390904732)
@test pvt.velocity ≈ ECEF(0.0, 0.0, 0.0) atol = 9
@test get_frequency_offset(pvt, get_center_frequency(galileo_e1b)) ≈ (1675.63Hz + freq_offset) atol = 0.01Hz
end
@testset "PVT GPS L1 with frequency offset of $freq_offset" for freq_offset in (0.0Hz, 500Hz, -1000Hz)
gpsl1 = GPSL1()
states = [
SatelliteState(;
decoder = GNSSDecoderState(
7,
uint320"0xe2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c07090f36c308b01c020ace4d54",
uint320"0x0048b01c020ace2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c07090f36c308b",
GNSSDecoder.GPSL1Data(
4,
false,
nothing,
false,
true,
112,
1,
2.0,
"000000",
"0001000110",
false,
-1.1175870895385742e-8,
136800,
0.0,
1.0231815394945443e-11,
0.0001659449189901352,
"01000110",
14.90625,
4.9980653323400095e-9,
-1.5018856847786306,
8.065253496170044e-7,
0.014979799510911107,
6.051734089851379e-6,
5153.747692108154,
136800,
false,
31,
3.110617399215698e-7,
-0.42148546787582664,
-5.21540641784668e-8,
0.9517858648559379,
250.375,
-2.331033772387461,
-8.050692486513945e-9,
"01000110",
1.657211886669833e-10,
),
GNSSDecoder.GPSL1Data(
3,
false,
132768,
false,
true,
112,
1,
2.0,
"000000",
"0001000110",
false,
-1.1175870895385742e-8,
136800,
0.0,
1.0231815394945443e-11,
0.0001659449189901352,
"01000110",
14.90625,
4.9980653323400095e-9,
-1.5018856847786306,
8.065253496170044e-7,
0.014979799510911107,
6.051734089851379e-6,
5153.747692108154,
136800,
false,
31,
3.110617399215698e-7,
-0.42148546787582664,
-5.21540641784668e-8,
0.9517858648559379,
250.375,
-2.331033772387461,
-8.050692486513945e-9,
"01000110",
1.657211886669833e-10,
),
GNSSDecoder.GPSL1Constants(
300,
0x8b,
8,
30,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986005e14,
-4.442807633e-10,
),
GNSSDecoder.GPSL1Cache(),
60,
360,
false,
),
system = gpsl1,
carrier_doppler = 2669.8440799388595Hz + freq_offset,
code_phase = 4876.431542382193,
carrier_phase = 0.09402551301430394,
),
SatelliteState(;
decoder = GNSSDecoderState(
8,
uint320"0xe2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c07090f36c308b01c020ace4d54",
uint320"0xaf88b01c020ace2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c07090f36c308b",
GNSSDecoder.GPSL1Data(
4,
false,
nothing,
false,
true,
112,
1,
2.0,
"000000",
"0001100111",
false,
5.122274160385132e-9,
136800,
0.0,
-1.4779288903810084e-12,
-2.3324042558670044e-5,
"01100111",
84.21875,
4.435899058715372e-9,
1.3315461632138303,
4.639849066734314e-6,
0.006349898059852421,
6.3907355070114136e-6,
5153.606374740601,
136800,
false,
31,
6.891787052154541e-8,
1.6470055929195884,
7.450580596923828e-8,
0.9671090437449873,
257.125,
0.05450158504406715,
-8.087122575401946e-9,
"01100111",
-1.353627812603161e-10,
),
GNSSDecoder.GPSL1Data(
3,
false,
132768,
false,
true,
112,
1,
2.0,
"000000",
"0001100111",
false,
5.122274160385132e-9,
136800,
0.0,
-1.4779288903810084e-12,
-2.3324042558670044e-5,
"01100111",
84.21875,
4.435899058715372e-9,
1.3315461632138303,
4.639849066734314e-6,
0.006349898059852421,
6.3907355070114136e-6,
5153.606374740601,
136800,
false,
31,
6.891787052154541e-8,
1.6470055929195884,
7.450580596923828e-8,
0.9671090437449873,
257.125,
0.05450158504406715,
-8.087122575401946e-9,
"01100111",
-1.353627812603161e-10,
),
GNSSDecoder.GPSL1Constants(
300,
0x8b,
8,
30,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986005e14,
-4.442807633e-10,
),
GNSSDecoder.GPSL1Cache(),
60,
360,
false,
),
system = gpsl1,
carrier_doppler = 4704.3549972665805Hz + freq_offset,
code_phase = 8455.107739656896,
carrier_phase = 2.7614518715603946,
),
SatelliteState(;
decoder = GNSSDecoderState(
10,
uint320"0x1d3db86b3655d4396b13e1f30d99b57860edf0be15870e004a0193f8f59c1513374fe3fdf531b2ab",
uint320"0xdf48b01c020ace2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c070a63eaecc8b",
GNSSDecoder.GPSL1Data(
4,
false,
nothing,
false,
true,
112,
1,
2.0,
"000000",
"0000101000",
false,
2.3283064365386963e-9,
136800,
0.0,
-7.617018127348274e-12,
-0.0001329910010099411,
"00101000",
-89.25,
4.016595878769169e-9,
-2.941058160546095,
-4.645437002182007e-6,
0.006653358926996589,
7.499009370803833e-6,
5153.6786251068115,
136800,
false,
20,
-3.5390257835388184e-8,
-2.5268399079275254,
-6.146728992462158e-8,
0.969412731565689,
239.09375,
-2.5641372296478258,
-7.765323456891273e-9,
"00101000",
3.893019302737323e-11,
),
GNSSDecoder.GPSL1Data(
3,
false,
132768,
false,
true,
112,
1,
2.0,
"000000",
"0000101000",
false,
2.3283064365386963e-9,
136800,
0.0,
-7.617018127348274e-12,
-0.0001329910010099411,
"00101000",
-89.25,
4.016595878769169e-9,
-2.941058160546095,
-4.645437002182007e-6,
0.006653358926996589,
7.499009370803833e-6,
5153.6786251068115,
136800,
false,
20,
-3.5390257835388184e-8,
-2.5268399079275254,
-6.146728992462158e-8,
0.969412731565689,
239.09375,
-2.5641372296478258,
-7.765323456891273e-9,
"00101000",
3.893019302737323e-11,
),
GNSSDecoder.GPSL1Constants(
300,
0x8b,
8,
30,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986005e14,
-4.442807633e-10,
),
GNSSDecoder.GPSL1Cache(),
60,
360,
true,
),
system = gpsl1,
carrier_doppler = 4603.179391134832Hz + freq_offset,
code_phase = 10510.15670303955,
carrier_phase = -0.7447786034769108,
),
SatelliteState(;
decoder = GNSSDecoderState(
15,
uint320"0xe2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c07084f478988b01c020ace4d54",
uint320"0x4fc8b01c020ace2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c07084f478988b",
GNSSDecoder.GPSL1Data(
4,
false,
nothing,
false,
true,
112,
1,
2.0,
"000000",
"0001011001",
false,
-1.0710209608078003e-8,
136800,
0.0,
2.6147972675971687e-12,
-0.00014561135321855545,
"01011001",
-30.5625,
5.182001565450993e-9,
0.38753804422936994,
-1.471489667892456e-6,
0.013163934461772442,
9.061768651008606e-6,
5153.620079040527,
136800,
false,
31,
-1.695007085800171e-7,
-1.5933596086804434,
1.6205012798309326e-7,
0.9286304727294836,
190.6875,
0.98557755063243,
-8.41785063726752e-9,
"01011001",
3.010839699272994e-10,
),
GNSSDecoder.GPSL1Data(
3,
false,
132768,
false,
true,
112,
1,
2.0,
"000000",
"0001011001",
false,
-1.0710209608078003e-8,
136800,
0.0,
2.6147972675971687e-12,
-0.00014561135321855545,
"01011001",
-30.5625,
5.182001565450993e-9,
0.38753804422936994,
-1.471489667892456e-6,
0.013163934461772442,
9.061768651008606e-6,
5153.620079040527,
136800,
false,
31,
-1.695007085800171e-7,
-1.5933596086804434,
1.6205012798309326e-7,
0.9286304727294836,
190.6875,
0.98557755063243,
-8.41785063726752e-9,
"01011001",
3.010839699272994e-10,
),
GNSSDecoder.GPSL1Constants(
300,
0x8b,
8,
30,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986005e14,
-4.442807633e-10,
),
GNSSDecoder.GPSL1Cache(),
60,
360,
false,
),
system = gpsl1,
carrier_doppler = 3144.174219887768Hz + freq_offset,
code_phase = 3618.5099300503684,
carrier_phase = -0.22375187424152987,
),
SatelliteState(;
decoder = GNSSDecoderState(
16,
uint320"0xe2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c07084f478988b01c020ace4d54",
uint320"0x9d88b01c020ace2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c07084f478988b",
GNSSDecoder.GPSL1Data(
4,
false,
nothing,
false,
true,
112,
1,
2.0,
"000000",
"0000100010",
false,
-1.0244548320770264e-8,
136800,
0.0,
-6.0254023992456496e-12,
-0.0003338884562253952,
"00100010",
37.0,
4.26732060817482e-9,
2.20050848506247,
1.8272548913955688e-6,
0.012199128163047135,
9.119510650634766e-6,
5153.70516204834,
136800,
false,
22,
-2.3655593395233154e-7,
0.7074087615001045,
-1.30385160446167e-7,
0.9738089978878275,
212.75,
0.6779943621465904,
-7.692463279115272e-9,
"00100010",
-2.95012288445966e-10,
),
GNSSDecoder.GPSL1Data(
3,
false,
132768,
false,
true,
112,
1,
2.0,
"000000",
"0000100010",
false,
-1.0244548320770264e-8,
136800,
0.0,
-6.0254023992456496e-12,
-0.0003338884562253952,
"00100010",
37.0,
4.26732060817482e-9,
2.20050848506247,
1.8272548913955688e-6,
0.012199128163047135,
9.119510650634766e-6,
5153.70516204834,
136800,
false,
22,
-2.3655593395233154e-7,
0.7074087615001045,
-1.30385160446167e-7,
0.9738089978878275,
212.75,
0.6779943621465904,
-7.692463279115272e-9,
"00100010",
-2.95012288445966e-10,
),
GNSSDecoder.GPSL1Constants(
300,
0x8b,
8,
30,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986005e14,
-4.442807633e-10,
),
GNSSDecoder.GPSL1Cache(),
60,
360,
false,
),
system = gpsl1,
carrier_doppler = 595.7926881306387Hz + freq_offset,
code_phase = 17600.66651489137,
carrier_phase = 2.59152430602131,
),
SatelliteState(;
decoder = GNSSDecoderState(
18,
uint320"0x1d3db86b3655d4396b13e1f30d99b57860edf0be15870e004a0193f8f729761f374fe3fdf531b2ab",
uint320"0x9b08b01c020ace2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c0708d689e0c8b",
GNSSDecoder.GPSL1Data(
4,
false,
nothing,
false,
true,
112,
1,
2.0,
"000000",
"1111100001",
false,
-8.381903171539307e-9,
136800,
0.0,
-1.3642420526593924e-12,
0.0003486964851617813,
"11100001",
-15.3125,
4.35303846438188e-9,
-0.6041391930737793,
-8.717179298400879e-7,
0.0014569575432687998,
3.339722752571106e-6,
5153.662895202637,
136800,
false,
31,
2.60770320892334e-8,
2.733796625968394,
-4.284083843231201e-8,
0.9683542210973364,
321.59375,
2.894680446328142,
-8.184269479103281e-9,
"11100001",
-1.0071848104329588e-10,
),
GNSSDecoder.GPSL1Data(
3,
false,
132768,
false,
true,
112,
1,
2.0,
"000000",
"1111100001",
false,
-8.381903171539307e-9,
136800,
0.0,
-1.3642420526593924e-12,
0.0003486964851617813,
"11100001",
-15.3125,
4.35303846438188e-9,
-0.6041391930737793,
-8.717179298400879e-7,
0.0014569575432687998,
3.339722752571106e-6,
5153.662895202637,
136800,
false,
31,
2.60770320892334e-8,
2.733796625968394,
-4.284083843231201e-8,
0.9683542210973364,
321.59375,
2.894680446328142,
-8.184269479103281e-9,
"11100001",
-1.0071848104329588e-10,
),
GNSSDecoder.GPSL1Constants(
300,
0x8b,
8,
30,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986005e14,
-4.442807633e-10,
),
GNSSDecoder.GPSL1Cache(),
60,
360,
true,
),
system = gpsl1,
carrier_doppler = -794.0022484221436Hz + freq_offset,
code_phase = 14504.587373634655,
carrier_phase = -0.7416765461612318,
),
SatelliteState(;
decoder = GNSSDecoderState(
23,
uint320"0x1d3db86b3655d4396b13e1f30d99b57860edf0be15870e004a0193f8f6f0c93cf74fe3fdf531b2ab",
uint320"0x8fc8b01c020ace2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c07090f36c308b",
GNSSDecoder.GPSL1Data(
4,
false,
nothing,
false,
true,
112,
1,
2.0,
"000000",
"0011101110",
false,
-8.381903171539307e-9,
136800,
0.0,
-3.751665644813329e-12,
0.00010169018059968948,
"11101110",
-92.40625,
4.153030133232073e-9,
-1.3144457890174628,
-4.732981324195862e-6,
0.0012323472183197737,
7.256865501403809e-6,
5153.657176971436,
136800,
false,
31,
-9.872019290924072e-8,
-2.5503370450318865,
2.9802322387695312e-8,
0.9644177455387573,
242.5,
2.603874239368067,
-7.890328663859904e-9,
"11101110",
3.107272287505937e-11,
),
GNSSDecoder.GPSL1Data(
3,
false,
132768,
false,
true,
112,
1,
2.0,
"000000",
"0011101110",
false,
-8.381903171539307e-9,
136800,
0.0,
-3.751665644813329e-12,
0.00010169018059968948,
"11101110",
-92.40625,
4.153030133232073e-9,
-1.3144457890174628,
-4.732981324195862e-6,
0.0012323472183197737,
7.256865501403809e-6,
5153.657176971436,
136800,
false,
31,
-9.872019290924072e-8,
-2.5503370450318865,
2.9802322387695312e-8,
0.9644177455387573,
242.5,
2.603874239368067,
-7.890328663859904e-9,
"11101110",
3.107272287505937e-11,
),
GNSSDecoder.GPSL1Constants(
300,
0x8b,
8,
30,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986005e14,
-4.442807633e-10,
),
GNSSDecoder.GPSL1Cache(),
60,
360,
true,
),
system = gpsl1,
carrier_doppler = 2826.783251528247Hz + freq_offset,
code_phase = 14394.465193705755,
carrier_phase = -0.7597910878699417,
),
SatelliteState(;
decoder = GNSSDecoderState(
26,
uint320"0x1d3db86b3655d4396b13e1f30d99b57860edf0be15870e004a0193f8f729761f374fe3fdf531b2ab",
uint320"0x3ac8b01c020ace2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c0708d689e0c8b",
GNSSDecoder.GPSL1Data(
4,
false,
nothing,
false,
true,
112,
1,
2.0,
"000000",
"0001101110",
false,
6.984919309616089e-9,
136800,
0.0,
4.888534022029489e-12,
9.242305532097816e-5,
"01101110",
29.53125,
5.002351225150362e-9,
3.0615288470223163,
1.5329569578170776e-6,
0.00589060562197119,
8.42846930027008e-6,
5153.568691253662,
136800,
false,
31,
-1.043081283569336e-7,
0.5730118600154152,
1.30385160446167e-8,
0.942073253292395,
208.875,
0.3072108597425673,
-8.057478483463671e-9,
"01101110",
-3.328710082707509e-10,
),
GNSSDecoder.GPSL1Data(
3,
false,
132768,
false,
true,
112,
1,
2.0,
"000000",
"0001101110",
false,
6.984919309616089e-9,
136800,
0.0,
4.888534022029489e-12,
9.242305532097816e-5,
"01101110",
29.53125,
5.002351225150362e-9,
3.0615288470223163,
1.5329569578170776e-6,
0.00589060562197119,
8.42846930027008e-6,
5153.568691253662,
136800,
false,
31,
-1.043081283569336e-7,
0.5730118600154152,
1.30385160446167e-8,
0.942073253292395,
208.875,
0.3072108597425673,
-8.057478483463671e-9,
"01101110",
-3.328710082707509e-10,
),
GNSSDecoder.GPSL1Constants(
300,
0x8b,
8,
30,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986005e14,
-4.442807633e-10,
),
GNSSDecoder.GPSL1Cache(),
60,
360,
true,
),
system = gpsl1,
carrier_doppler = -1083.2317687377372Hz + freq_offset,
code_phase = 13905.233170289455,
carrier_phase = -2.1444956909602526,
),
SatelliteState(;
decoder = GNSSDecoderState(
27,
uint320"0xe2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c070a63eaecc8b01c020ace4d54",
uint320"0x75c8b01c020ace2c24794c9aa2bc694ec1e0cf2664a879f120f41ea78f1ffb5fe6c070a63eaecc8b",
GNSSDecoder.GPSL1Data(
4,
false,
nothing,
false,
true,
112,
1,
2.0,
"000000",
"0001001110",
false,
1.862645149230957e-9,
136800,
0.0,
-6.366462912410498e-12,
-0.0001393994316458702,
"01001110",
82.25,
4.257677349351526e-9,
1.25128819523303,
4.505738615989685e-6,
0.00944566575344652,
6.81169331073761e-6,
5153.686637878418,
136800,
false,
31,
-5.029141902923584e-8,
1.66429757866306,
1.601874828338623e-7,
0.9756900633046096,
257.375,
0.6281523291801417,
-8.07676500111026e-9,
"01001110",
-1.2286226056345314e-10,
),
GNSSDecoder.GPSL1Data(
3,
false,
132768,
false,
true,
112,
1,
2.0,
"000000",
"0001001110",
false,
1.862645149230957e-9,
136800,
0.0,
-6.366462912410498e-12,
-0.0001393994316458702,
"01001110",
82.25,
4.257677349351526e-9,
1.25128819523303,
4.505738615989685e-6,
0.00944566575344652,
6.81169331073761e-6,
5153.686637878418,
136800,
false,
31,
-5.029141902923584e-8,
1.66429757866306,
1.601874828338623e-7,
0.9756900633046096,
257.375,
0.6281523291801417,
-8.07676500111026e-9,
"01001110",
-1.2286226056345314e-10,
),
GNSSDecoder.GPSL1Constants(
300,
0x8b,
8,
30,
3.1415926535898,
7.2921151467e-5,
2.99792458e8,
3.986005e14,
-4.442807633e-10,
),
GNSSDecoder.GPSL1Cache(),
60,
360,
false,
),
system = gpsl1,
carrier_doppler = 3393.7445379085816Hz + freq_offset,
code_phase = 16861.02713837273,
carrier_phase = -0.9185401811870872,
),
]
pvt = calc_pvt(states)
@test get_LLA(pvt) ≈
LLA(; lat = 50.77885249310784, lon = 6.0656199911189175, alt = 291.95658091689086)
@test pvt.time ≈ TAIEpoch(2021, 5, 31, 12, 53, 14.1491024351271335)
@test pvt.velocity ≈ ECEF(0.0, 0.0, 0.0) atol = 2.5
@test get_frequency_offset(pvt, get_center_frequency(gpsl1)) ≈ (1632.59Hz + freq_offset) atol = 0.01Hz
end | PositionVelocityTime | https://github.com/JuliaGNSS/PositionVelocityTime.jl.git |
|
[
"MIT"
] | 0.2.0 | b988b82bbde556f2d50243b8defd685dea9ebcd7 | code | 152 |
using Test, PositionVelocityTime, GNSSDecoder, AstroTime, BitIntegers, GNSSSignals, Geodesy
using Unitful: Hz
include("sat_time.jl")
include("pvt.jl") | PositionVelocityTime | https://github.com/JuliaGNSS/PositionVelocityTime.jl.git |
|
[
"MIT"
] | 0.2.0 | b988b82bbde556f2d50243b8defd685dea9ebcd7 | code | 265 | @testset "Week crossover" begin
@test PositionVelocityTime.correct_week_crossovers(0) == 0
@test PositionVelocityTime.correct_week_crossovers(350000) == 350000 - 604800
@test PositionVelocityTime.correct_week_crossovers(-350000) == 604800 - 350000
end | PositionVelocityTime | https://github.com/JuliaGNSS/PositionVelocityTime.jl.git |
|
[
"MIT"
] | 0.2.0 | b988b82bbde556f2d50243b8defd685dea9ebcd7 | docs | 1194 |
# PositionVelocityTime.jl
Calculates position and time by using GNSS data
## Features
* Estimation of user position and time
* Calculates satellite position
* Precision estimation (GDOP)
## Preparing
### Install
```julia
julia> ]
pkg> PositionVelocityTime.jl
```
Decoded data and code phase of satellite must be combined in the provided `SatelliteState` struct.
```julia
using PositionVelocityTime, GNSSSignals, GNSSDecoder
# decode satellite
gpsl1 = GPSL1()
sat_state = SatelliteState(
decoder = decoder,
system = gpsl1,
code_phase = code_phase,
carrier_phase = carrier_phase # optional
)
```
The declaration of `carrier_phase` is optional due to its small effect on the user position.
Alternatively, the tracking result can be passed to `SatelliteState` instead of `system`, `code_phase` and `carrier_phase`:
```julia
using Tracking
# track and decode satellite
sat_state = SatelliteState(decoder, tracking_result)
```
For user position computation at least 4 decoded satellites must be provided.
## Usage
### User position calculation
The function
```julia
# You need at least 4 satellite states
calc_PVT(sat_states)
```
provides a complete position calculation. | PositionVelocityTime | https://github.com/JuliaGNSS/PositionVelocityTime.jl.git |
|
[
"MIT"
] | 0.1.0 | 60fdd400b93c98848d2360230b1e770910543f93 | code | 5123 | module TestAbstractTypes
using Test
const niters = 1 #TODO 100
function generator end
export generator
################################################################################
function generator(::Type{Char})
function gen(channel::Channel{Char})
yield!(x) = put!(channel, x)
while true
case = rand(1:20)
if case == 1
yield!('a')
elseif case == 2
yield!("β")
elseif case == 3
yield!(' ')
elseif case == 4
yield!('\0')
elseif case == 5
yield!(Char(127))
elseif case == 6
yield!(Char(128))
elseif case ≤ 10
yield!(Char(rand(0:127)))
else
len = rand(0:20)
yield!(rand(Char))
end
end
end
return Channel{Char}(gen)
end
function testAbstractChar(::Type{T}, ch::AbstractChannel{T}) where {T}
@testset "testAbstractChar($T)" begin
@test T <: AbstractChar
next!() = take!(ch)::T
for iter in 1:niters
x = next!()
y = next!()
if x == y
@test cmp(x, y) == 0
elseif x < y
@test cmp(x, y) == -1
elseif x > y
@test cmp(x, y) == 1
else
@test false
end
xp = codepoint(x)
@test xp isa Integer
xc = T(xp)
@test xc isa T
@test xc == x
end
end
end
export testAbstractChar
################################################################################
function generator(::Type{String})
function gen(channel::Channel{String})
yield!(x) = put!(channel, x)
while true
case = rand(1:20)
if case == 1
yield!("")
elseif case == 2
yield!("a")
elseif case == 3
yield!("abc")
elseif case == 4
yield!("β")
elseif case == 5
yield!(" ")
elseif case == 6
yield!("\0")
elseif case == 7
yield!("\0abc")
elseif case ≤ 10
yield!(string(rand(Char)))
elseif case ≤ 19
len = rand(0:20)
yield!(String(rand(Char, len)))
else
len = rand(10000:20000)
yield!(String(rand(Char, len)))
end
end
end
return Channel{String}(gen)
end
function generator(::Type{SubString})
function gen(channel::Channel{SubString})
source = generator(String)
while true
str = take!(source)::String
len = ncodeunits(str)
if len == 0
put!(channel, SubString(str))
else
i = thisind(str, rand(1:len))
j = thisind(str, rand(1:len))
if i ≤ j
put!(channel, SubString(str, i, j))
end
end
end
end
return Channel{SubString}(gen)
end
function testAbstractString(::Type{T}, ch::AbstractChannel{T}) where {T}
@testset "testAbstractString($T)" begin
@test T <: AbstractString
next!() = take!(ch)::T
unit = T("")
@test unit isa T
@test length(unit) == 0
for iter in 1:niters
x = next!()
y = next!()
z = next!()
# Equality
@test unit == unit
@test x == x
# Unit
@test unit * unit == unit
@test unit * x == x
@test x * unit == x
# Associativity
@test (x * y) * z == x * (y * z)
# Exponentiation
@test x^0 == unit
@test x^1 == x
@test x^2 == x * x
n = rand(3:10)
@test x^n == *((x for i in 1:n)...)
# Lengths
@test length(x) isa Int
@test length(x * y) == length(x) + length(y)
@test isempty(x) == (length(x) == 0)
@test ncodeunits(x) isa Int
@test ncodeunits(x * y) == ncodeunits(x) + ncodeunits(y)
@test isempty(x) == (ncodeunits(x) == 0)
# Elements
# Find all possible indices
inds = Int[]
ind = firstindex(x)
while ind ≤ lastindex(x)
push!(inds, ind)
ind = nextind(x, ind)
end
@test length(inds) == length(x)
if !isempty(x)
pos = inds[rand(1:length(inds))]
@test eltype(x) isa Type
@test x[pos] isa eltype(x)
@test (x * y)[pos] == x[pos]
@test (y * x)[ncodeunits(y) + pos] == x[pos]
end
# codeunit, codeunits
# firstindex, lastindex, thisind, nextind, prevind, isvalid
# cmp
end
close(ch)
end
end
export testAbstractString
end
| TestAbstractTypes | https://github.com/eschnett/TestAbstractTypes.jl.git |
|
[
"MIT"
] | 0.1.0 | 60fdd400b93c98848d2360230b1e770910543f93 | code | 340 | using Random
using TestAbstractTypes
# Set reproducible random number seed
Random.seed!(0)
testAbstractChar(Char, generator(Char))
# Set reproducible random number seed
Random.seed!(0)
testAbstractString(String, generator(String))
# Set reproducible random number seed
Random.seed!(0)
testAbstractString(SubString, generator(SubString))
| TestAbstractTypes | https://github.com/eschnett/TestAbstractTypes.jl.git |
|
[
"MIT"
] | 0.1.0 | 60fdd400b93c98848d2360230b1e770910543f93 | docs | 379 | # TestAbstractTypes.jl
[](https://github.com/eschnett/TestAbstractTypes.jl/actions?query=workflow%3A%22CI%22+branch%3Amain)
Provide functions to test whether a type correctly implements the
interface expected by a certain abstract type (e.g. `AbstractString`,
`AbstractVector`).
| TestAbstractTypes | https://github.com/eschnett/TestAbstractTypes.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | code | 274 | using Documenter, StanVariational
makedocs(
modules = [StanVariational],
format = Documenter.HTML(),
checkdocs = :exports,
sitename = "StanVariational.jl",
pages = Any["index.md"]
)
deploydocs(
repo = "github.com/goedman/StanVariational.jl.git",
)
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | code | 595 | ######### StanVariational Bernoulli example ###########
using StanVariational
bernoulli_model = "
data {
int<lower=1> N;
array[N] int<lower=0,upper=1> y;
}
parameters {
real<lower=0,upper=1> theta;
}
model {
theta ~ beta(1,1);
y ~ bernoulli(theta);
}
";
data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1])
# Keep tmpdir across multiple runs to prevent re-compilation
tmpdir = joinpath(@__DIR__, "tmp")
sm = VariationalModel("bernoulli", bernoulli_model, tmpdir)
rc = stan_variational(sm; data, test=5)
if success(rc)
(samples, names) = read_variational(sm)
end | StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | code | 904 | """
$(SIGNATURES)
Helper infrastructure to compile and sample models using `cmdstan`.
"""
module StanVariational
using Reexport
using CSV, DelimitedFiles, Unicode
using NamedTupleTools, Parameters
using DataFrames
using DocStringExtensions: FIELDS, SIGNATURES, TYPEDEF
@reexport using StanBase
import StanBase: update_model_file, par, handle_keywords!
import StanBase: executable_path, ensure_executable, stan_compile
import StanBase: update_json_files
import StanBase: data_file_path, init_file_path, sample_file_path
import StanBase: generated_quantities_file_path, log_file_path
import StanBase: diagnostic_file_path, setup_diagnostics
include("stanmodel/VariationalModel.jl")
include("stanrun/stan_run.jl")
include("stanrun/cmdline.jl")
include("stansamples/read_variational.jl")
stan_variational = stan_run
export
VariationalModel,
stan_variational,
read_variational
end # module
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | code | 5675 | import Base: show
mutable struct VariationalModel <: CmdStanModels
name::AbstractString; # Name of the Stan program
model::AbstractString; # Stan language model program
# Sample fields
num_chains::Int64; # Number of chains
num_threads::Int64; # Number of threads
seed::Int; # Seed section of cmd to run cmdstan
refresh::Int; # Display progress in output files
init_bound::Int; # Bound for initial param values
# Algorithm fields
algorithm::Symbol; # :meanfield or :fullrank
iter::Int; # Maximum no of ADVI iterations
grad_samples::Int; # Number of draws to compute gradient
elbo_samples::Int; # Number of draws for ELBO estimate
eta::Float64; # Stepsize scaling parameter
# Adapt fields
engaged::Bool; # Eta adaptation active
adapt_iter::Int; # No of iterations for eta adaptation
tol_rel_obj::Float64; # Tolerance for convergence
eval_elbo::Int; # No of iterations between ELBO evaluations
output_samples::Int; # Approximate no of posterior draws to save
output_base::AbstractString; # Used for file paths to be created
tmpdir::AbstractString; # Holds all created files
exec_path::AbstractString; # Path to the cmdstan excutable
data_file::Vector{AbstractString}; # Array of data files input to cmdstan
init_file::Vector{AbstractString}; # Array of init files input to cmdstan
cmds::Vector{Cmd}; # Array of cmds to be spawned/pipelined
sample_file::Vector{String}; # Sample file array (.csv)
log_file::Vector{String}; # Log file array
diagnostic_file::Vector{String}; # Diagnostic file array
cmdstan_home::AbstractString; # Directory where cmdstan can be found
end
"""
# VariationalModel
Create a VariationalModel and compile the Stan Language Model..
### Required arguments
```julia
* `name::AbstractString` : Name for the model
* `model::AbstractString` : Stan model source
```
### Optional positional argument
```julia
`tmpdir::AbstractString` : Directory where output files are stored
```
"""
function VariationalModel(
name::AbstractString,
model::AbstractString,
tmpdir = mktempdir())
!isdir(tmpdir) && mkdir(tmpdir)
update_model_file(joinpath(tmpdir, "$(name).stan"), strip(model))
output_base = joinpath(tmpdir, name)
exec_path = executable_path(output_base)
cmdstan_home = CMDSTAN_HOME
error_output = IOBuffer()
is_ok = cd(cmdstan_home) do
success(pipeline(
`$(make_command()) -f $(cmdstan_home)/makefile -C $(cmdstan_home) $(exec_path)`;
stderr = error_output))
end
if !is_ok
throw(StanModelError(model, String(take!(error_output))))
end
VariationalModel(name, model,
# num_chains, num_threads
4, 4,
# seed, refresh, init_bound
-1, 100, 2,
# Variational settings
:meanfield, # algorithm
10000, # iter (ADVI)
1, # grad_samples
100, # elbo_samples
1.0, # eta
# Adaption
true, # engaged
50, # adapt_iter
0.01, # tol_rel_obj
100, # eval_elbo
1000, # output_samples
output_base, # Path to output files
tmpdir, # Tmpdir settings
exec_path, # Exec_path
AbstractString[], # Data files
AbstractString[], # Init files
Cmd[], # Command lines
String[], # Sample .csv files
String[], # Log files
String[], # Diagnostic files
cmdstan_home)
end
function Base.show(io::IO, ::MIME"text/plain", m::VariationalModel)
println(io, "\nVariational section:")
println(io, " name = ", m.name)
println(io, " num_chains = ", m.num_chains)
println(io, " num_threads = ", m.num_threads)
println(io, " seed = ", m.seed)
println(io, " refresh = ", m.refresh)
println(io, " init_bound = ", m.init_bound)
println(io, "\nAlgorithm section:")
println(io, " algorithm = ", m.algorithm)
println(io, " iter = ", m.iter)
println(io, " grad_samples = ", m.grad_samples)
println(io, " elbo_samples = ", m.elbo_samples)
println(io, " eta = ", m.eta)
println(io, "\nAdapt section:")
println(io, " engaged = ", m.engaged)
println(io, " adapt_iter = ", m.adapt_iter)
println(io, "\nCompletion section:")
println(io, " tol_rel_obj = ", m.tol_rel_obj)
println(io, " eval_elbo = ", m.eval_elbo)
println(io, " output_samples = ", m.output_samples)
println(io, "\nOther:")
println(io, " output_base = ", m.output_base)
println(io, " tmpdir = ", m.tmpdir)
end
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | code | 1979 | """
# cmdline
Recursively parse the model to construct command line.
### Method
```julia
cmdline(m)
```
### Required arguments
```julia
* `m::VariationalModel` : VariationalModel
```
"""
function cmdline(m::VariationalModel, id)
#=
`/Users/rob/.julia/dev/StanVariational/examples/Bernoulli/tmp/bernoulli
variational algorithm=meanfield grad_samples=1 elbo_samples=100
iter=10000 tol_rel_obj=0.01 eval_elbo=100 output_samples=10000
random seed=-1 init=2 id=1
data file=/Users/rob/.julia/dev/StanVariational/examples/Bernoulli/tmp/bernoulli_data_1.R
output file=/Users/rob/.julia/dev/StanVariational/examples/Bernoulli/tmp/bernoulli_chain_1.csv
refresh=100`
=#
cmd = ``
# Handle the model name field for unix and windows
cmd = `$(m.exec_path)`
# Variational() specific portion of the model
cmd = `$cmd variational algorithm=$(string(m.algorithm))`
cmd = `$cmd iter=$(m.iter)`
cmd = `$cmd grad_samples=$(m.grad_samples) elbo_samples=$(m.elbo_samples)`
cmd = `$cmd eta=$(m.eta)`
if m.engaged
cmd = `$cmd adapt engaged=1 iter=$(m.adapt_iter)`
end
cmd = `$cmd tol_rel_obj=$(m.tol_rel_obj)`
cmd = `$cmd eval_elbo=$(m.eval_elbo) output_samples=$(m.output_samples)`
cmd = `$cmd id=$(id)`
# Data file required?
if length(m.data_file) > 0 && isfile(m.data_file[id])
cmd = `$cmd data file=$(m.data_file[id])`
end
# Init file required?
if length(m.init_file) > 0 && isfile(m.init_file[id])
cmd = `$cmd init=$(m.init_file[id])`
else
cmd = `$cmd init=$(m.init_bound)`
end
cmd = `$cmd random seed=$(m.seed)`
# Output options
cmd = `$cmd output`
if length(m.sample_file) > 0
cmd = `$cmd file=$(m.sample_file[id])`
end
if length(m.diagnostic_file) > 0
cmd = `$cmd diagnostic_file=$(m.diagnostic_file)`
end
cmd = `$cmd refresh=$(m.refresh)`
cmd
end
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | code | 3295 | """
stan_variational()
Sample from a StanJulia VariationalModel (<: CmdStanModel.)
## Required argument
```julia
* `m::VariationalModel` # VariationalModel.
* `use_json=true` # Use JSON3 for data and init files
```
### Most frequently used keyword arguments
```julia
* `data` # Observations Dict or NamedTuple.
* `init` # Init Dict or NT (default: -2 to +2).
```
### Returns
```julia
* `rc` # Return code, 0 is success.
```
See extended help for other keyword arguments ( `??stan_sample` ).
# Extended help
### Additional configuration keyword arguments
```julia
* `num_chains=4` # Update number of chains.
* `num_threads=8` # Update number of threads.
* `seed=-1` # Set seed value.
* `refresh=100` # Strem to output.
* `init_bound=2` # Bound for initial values.
* `algorithm=:meanfield` # :menafield or :fullrank
* `iter=10000` # Maximim no of ADVI iterations
* `grad_samples=1` # Number of draws to compute gradient
* `elbo_samples=100` # Number of draws for ELBO estimate
* `eta=1.0` # Stepsize scaling parameter
* `engaged=true` # Eta adaptation active
* `adapt_iter=50` # No of iterations for eta adaptation
* `tol_rel_obj=0.01` # Tolerance for convergence
* `eval_elbo=100` # No of iterations between ELBO evaluations
* `output_samples=1000` # Approximate no of posterior draws to save
```
"""
function stan_run(m::T, use_json=true; kwargs...) where {T <: CmdStanModels}
handle_keywords!(m, kwargs)
# Diagnostics files requested?
diagnostics = false
if :diagnostics in keys(kwargs)
diagnostics = kwargs[:diagnostics]
setup_diagnostics(m, m.num_chains)
end
# Remove existing sample files
for id in 1:m.num_chains
sfile = sample_file_path(m.output_base, id)
isfile(sfile) && rm(sfile)
end
if use_json
:init in keys(kwargs) && update_json_files(m, kwargs[:init],
m.num_chains, "init")
:data in keys(kwargs) && update_json_files(m, kwargs[:data],
m.num_chains, "data")
else
:init in keys(kwargs) && update_R_files(m, kwargs[:init],
m.num_chains, "init")
:data in keys(kwargs) && update_R_files(m, kwargs[:data],
m.num_chains, "data")
end
m.cmds = [stan_cmds(m, id; kwargs...) for id in 1:m.num_chains]
#println(typeof(m.cmds))
#println()
#println(m.cmds)
run(pipeline(par(m.cmds), stdout=m.log_file[1]))
end
"""
Generate a cmdstan command line (a run `cmd`).
$(SIGNATURES)
Internal, not exported.
"""
function stan_cmds(m::T, id::Integer; kwargs...) where {T <: CmdStanModels}
append!(m.sample_file, [sample_file_path(m.output_base, id)])
append!(m.log_file, [log_file_path(m.output_base, id)])
if length(m.diagnostic_file) > 0
append!(m.diagnostic_file, [diagnostic_file_path(m.output_base, id)])
end
cmdline(m, id)
end
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | code | 1381 | """
# read_variational
Read variational sample output files created by cmdstan.
### Method
```julia
read_variational(m::VariationalModelodel)
```
### Required arguments
```julia
* `m::VariationalModel` : VariationalModel object
```
"""
function read_variational(m::VariationalModel)
local a3d, index, idx, indvec
ftype = "chain"
for i in 1:m.num_chains
if isfile("$(m.output_base)_$(ftype)_$(i).csv")
instream = open("$(m.output_base)_$(ftype)_$(i).csv")
skipchars(isspace, instream, linecomment='#')
line = Unicode.normalize(readline(instream), newline2lf=true)
idx = split(strip(line), ",")
index = [idx[k] for k in 1:length(idx)]
indvec = 1:length(index)
if i == 1
a3d = fill(0.0, m.output_samples, length(indvec), m.num_chains)
end
skipchars(isspace, instream, linecomment='#')
for j in 1:m.output_samples
skipchars(isspace, instream, linecomment='#')
line = Unicode.normalize(readline(instream), newline2lf=true)
if eof(instream) && length(line) < 2
close(instream)
break
else
flds = parse.(Float64, (split(strip(line), ",")))
flds = reshape(flds[indvec], 1, length(indvec))
a3d[j,:,i] = flds
end
end
end
end
cnames = convert.(String, idx[indvec])
(a3d, cnames)
end
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | code | 1195 | using StanVariational
using Statistics, Test
if haskey(ENV, "JULIA_CMDSTAN_HOME") || haskey(ENV, "CMDSTAN")
bernoulli_model = "
data {
int<lower=1> N;
array[N] int<lower=0,upper=1> y;
}
parameters {
real<lower=0,upper=1> theta;
}
model {
theta ~ beta(1,1);
y ~ bernoulli(theta);
}
";
bernoulli_data = Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1])
stanmodel = VariationalModel("bernoulli", bernoulli_model)
rc = stan_variational(stanmodel; data=bernoulli_data)
if success(rc)
@testset "Bernoulli variational example" begin
# Read sample summary (in ChainDataFrame format)
samples, cnames = read_variational(stanmodel)
ms = mean(samples; dims=1)
#ms |> display
#ms[1, 2, 1] |> display
@test ms[1, 2, 1] ≈ -8.2 atol=0.3
@test ms[1, 2, 2] ≈ -8.2 atol=0.3
@test ms[1, 2, 3] ≈ -8.2 atol=0.3
@test ms[1, 2, 4] ≈ -8.2 atol=0.3
@test ms[1, 3, 1] ≈ -0.5 atol=0.1
@test ms[1, 3, 2] ≈ -0.5 atol=0.1
@test ms[1, 3, 3] ≈ -0.5 atol=0.1
@test ms[1, 3, 4] ≈ -0.5 atol=0.1
end
end
else
println("\nCMDSTAN or JULIA_CMDSTAN_HOME not set. Skipping tests")
end
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | code | 363 | ####
#### Coverage summary, printed as "(percentage) covered".
####
#### Useful for CI environments that just want a summary (eg a Gitlab setup).
####
using Coverage
cd(joinpath(@__DIR__, "..", "..")) do
covered_lines, total_lines = get_summary(process_folder())
percentage = covered_lines / total_lines * 100
println("($(percentage)%) covered")
end
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | code | 266 | # only push coverage from one bot
get(ENV, "TRAVIS_OS_NAME", nothing) == "linux" || exit(0)
get(ENV, "TRAVIS_JULIA_VERSION", nothing) == "1.1" || exit(0)
using Coverage
cd(joinpath(@__DIR__, "..", "..")) do
Codecov.submit(Codecov.process_folder())
end
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | docs | 1561 | # StanVariational.jl
| **Project Status** | **Build Status** |
|:---------------------------:|:-----------------:|
|![][project-status-img] | ![][CI-build] |
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[docs-dev-url]: https://stanjulia.github.io/StanVariational.jl/latest
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://stanjulia.github.io/StanVariational.jl/stable
[CI-build]: https://github.com/stanjulia/StanVariational.jl/workflows/CI/badge.svg?branch=master
[issues-url]: https://github.com/stanjulia/StanVariational.jl/issues
[project-status-img]: https://img.shields.io/badge/lifecycle-stable-green.svg
## Important note
### Refactoring CmdStan.jl v6. Maybe this is an ok approach.
## Installation
This package is registered. Install with
```julia
pkg> add StanVariational.jl
```
You need a working [cmdstan](https://mc-stan.org/users/interfaces/cmdstan.html) installation, the path of which you should specify either in `CMDSTAN` or `JULIA_CMDSTAN_HOME`, eg in your `~/.julia/config/startup.jl` have a line like
```julia
# CmdStan setup
ENV["CMDSTAN"] = expanduser("~/src/cmdstan-2.35.0/") # replace with your path
```
## Usage
It is recommended that you start your Julia process with multiple worker processes to take advantage of parallel sampling, eg
```sh
julia -p auto
```
Otherwise, `stan_sample` will use a single process.
Use this package like this:
```julia
using StanVariational
```
See the docstrings (in particular `?StanVariational`) for more.
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 4.5.1 | 55e582663b8a5c9b367a814cdae484cefa0b4342 | docs | 46 | # StanVariational
*Documentation goes here.*
| StanVariational | https://github.com/StanJulia/StanVariational.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 146 | # execute this file in the docs directory with this
# julia --color=yes --project make.jl
using Documenter, Posets
makedocs(; sitename="Posets")
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 4895 | module SimpleGraphAlgorithms
using SimpleGraphs
using JuMP
using ChooseOptimizer
function __init__()
set_solver_verbose(false)
end
export max_indep_set, max_clique, max_matching, min_dom_set
export min_vertex_cover, min_edge_cover
import SimpleGraphs.cache_save
"""
`max_indep_set(G)` returns a maximum size independent set of a
`UndirectedGraph`.
"""
function max_indep_set(G::UG)
if cache_check(G, :max_indep_set)
return cache_recall(G, :max_indep_set)
end
VV = vlist(G)
EE = elist(G)
n = NV(G)
m = NE(G)
MOD = Model(get_solver())
@variable(MOD, x[VV], Bin)
for e in EE
u, v = e
@constraint(MOD, x[u] + x[v] <= 1)
end
@objective(MOD, Max, sum(x[v] for v in VV))
optimize!(MOD)
X = value.(x)
A = Set([v for v in VV if X[v] > 0.1])
cache_save(G, :max_indep_set, A)
return A
end
"""
`min_vertex_cover(G)` returns a smallest vertex cover `S` of `G`.
This is a smallest possible set of vertices such that every edge
of `G` has one or both end points in `S`.
`min_vertex_cover(G,k)` returns the smallest set of vertices `S`
such that at least `k` edges are indicent with a vertex in `S`.
"""
min_vertex_cover(G) = setdiff(G.V, max_indep_set(G))
function min_vertex_cover(G::UG, k::Int)
MOD = Model(get_solver())
Vs = vlist(G)
Es = elist(G)
@variable(MOD, x[v in Vs], Bin)
@variable(MOD, y[f in Es], Bin)
# edge constraints
for f in Es
u, v = f
@constraint(MOD, x[u] + x[v] >= y[f])
end
# assure proper size
@constraint(MOD, sum(y[f] for f in Es) >= k)
# we want to minimize the sum of the x[v]'s
@objective(MOD, Min, sum(x[v] for v in Vs))
optimize!(MOD)
status = Int(termination_status(MOD))
if status != 1
error("Cannot find such a minimum vertex cover")
end
XX = value.(x)
A = Set([v for v in Vs if XX[v] > 0.1])
return A
end
"""
`max_clique(G)` returns a maximum size clique of a `UndirectedGraph`.
"""
function max_clique(G::UG)
if cache_check(G, :max_clique)
return cache_recall(G, :max_clique)
end
result = max_indep_set(G')
cache_save(G, :max_clique, result)
return result
end
"""
`max_matching(G)` returns a maximum matching of a `UndirectedGraph`.
"""
function max_matching(G::UG)
if cache_check(G, :max_matching)
return cache_recall(G, :max_matching)
end
VV = vlist(G)
EE = elist(G)
n = NV(G)
m = NE(G)
MOD = Model(get_solver())
@variable(MOD, x[EE], Bin)
for v in VV
star = [e for e in EE if e[1] == v || e[2] == v]
@constraint(MOD, sum(x[e] for e in star) <= 1)
end
@objective(MOD, Max, sum(x[e] for e in EE))
optimize!(MOD)
X = value.(x)
M = Set([e for e in EE if X[e] > 0.1])
cache_save(G, :max_matching, M)
return M
end
"""
`min_edge_cover(G)` finds a smallest subset `F` of the edges such that
every vertex of `G` is the end point of at least one edge in `F`. An
error is raised if `G` has a vertex of degree 0.
"""
function min_edge_cover(G::UG)
if cache_check(G, :min_edge_cover)
return cache_recall(G, :min_edge_cover)
end
if NV(G) == 0
T = eltype(G)
S = Tuple{T,T}
return Set{S}()
end
if minimum(deg(G)) == 0
error("Graph has an isolated vertex; no minimum edge cover exists.")
end
VV = vlist(G)
EE = elist(G)
n = NV(G)
m = NE(G)
MOD = Model(get_solver())
@variable(MOD, x[EE], Bin)
for v in VV
star = [e for e in EE if e[1] == v || e[2] == v]
@constraint(MOD, sum(x[e] for e in star) >= 1)
end
@objective(MOD, Min, sum(x[e] for e in EE))
optimize!(MOD)
X = value.(x)
A = Set([e for e in EE if X[e] > 0.1])
cache_save(G, :min_edge_cover, A)
return A
end
"""
`min_dom_set(G)` returns a smallest dominating set of a
`UG`. That is, a smallest set `S` with the property that
every vertex of `G` either is in `S` or is adjacent to a vertex of
`S`.
"""
function min_dom_set(G::UG)
if cache_check(G, :min_dom_set)
return cache_recall(G, :min_dom_set)
end
n = NV(G)
if n == 0
T = eltype(G)
return Set{T}()
end
VV = vlist(G)
MOD = Model(get_solver())
@variable(MOD, x[VV], Bin)
for v in VV
Nv = G[v]
push!(Nv, v)
@constraint(MOD, sum(x[w] for w in Nv) >= 1)
end
@objective(MOD, Min, sum(x[v] for v in VV))
optimize!(MOD)
X = value.(x)
S = Set(v for v in VV if X[v] > 0.1)
cache_save(G, :min_dom_set, S)
return S
end
include("iso.jl")
include("hom.jl")
include("vertex-coloring.jl")
include("chrome_poly.jl")
include("edge-coloring.jl")
include("mad.jl")
include("kfactor.jl")
include("connectivity.jl")
include("fmatch.jl")
include("frac_iso.jl")
end # of module SimpleGraphAlgorithms
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 4822 | using SimplePolynomials, SimplePartitions
import Base.length, Base.setindex!, Base.getindex
export chromatic_poly, reset_cpm, size_cpm
const CPM_pair = Tuple{UG,SimplePolynomial}
const CPM_dict = Dict{UInt64,Vector{CPM_pair}}
# This is a device to record previously computed chromatic polynomials
mutable struct ChromePolyMemo
D::CPM_dict
function ChromePolyMemo()
new(CPM_dict())
end
end
_CPM = ChromePolyMemo()
"""
`reset_cpm()` clears the datastructure of previously computed
chromatic polynomials.
"""
function reset_cpm()
global _CPM = ChromePolyMemo()
return true
end
"""
`size_cpm()` reports the number of graphs held in the datastructure of
previously computed chromatic polynomials.
"""
function size_cpm()
return length(_CPM)
end
function show(io::IO, CPM::ChromePolyMemo)
print(io, "ChromePolyMemo with $(length(CPM)) graphs")
end
function length(CPM::ChromePolyMemo)
result = 0
for ds in keys(CPM.D)
result += length(CPM.D[ds])
end
return result
end
"""
`remember!(CPM,G,P)` save the polynomial `P` associated with `G` in
this data structure (if it wasn't in there already).
Short form: `CPM[G] = P`.
"""
function remember!(CPM::ChromePolyMemo, G::UG, P::SimplePolynomial)
index::Int128 = uhash(G) # get the signature for this graph
# have we seen this graph's uhash before?
# if no, create a new entry in the Memo
if !haskey(CPM.D, index)
CPM.D[index] = [(G, P)]
return
end
# Otherwise, look through the values associated with this uhash to
# see if we've seen this graph (or one isomorphic to it) before.
# Recall those graphs with matching uhash
for (H, Q) in CPM.D[index]
if is_iso(G, H) # if isomorphic, nothing to add
return
end
end
# otherwise, add this polynomial to the end of the list
push!(CPM.D[index], (G, P))
end
setindex!(CPM::ChromePolyMemo, P::SimplePolynomial, G::UG) = remember!(CPM, G, P)
"""
`recall(CPM,G)` look up in CPM to see if we have already computed the
chromatic polynomial of this graph (or something isomorphic to it).
Short form: `P = CPM[G]`.
"""
function recall(CPM::ChromePolyMemo, G::UG)
ds = uhash(G)
SG = CPM.D[ds] # This may throw an error if not found. That's good.
for (H, Q) in SG
if is_iso(G, H)
return Q
end
end
# Not found, so it's an error
error("Graph not found")
end
getindex(CPM::ChromePolyMemo, G::UG) = recall(CPM, G)
"""
`chromatic_poly(G)` computes the chromatic polynomial of the graph `G`.
If `G` is a directe graph, this returns the chromatic polynomial of
`G`'s underlying simple graph.
This function builds a datastructure to prevent computing the
chromatic polynomial of the same graph twice. To do this, it uses
frequent isomorphism checks.
See `size_cpm` and `reset_cpm`.
"""
function chromatic_poly(G::UG) #, CPM::ChromePolyMemo = _CPM)
if cache_check(G, :chrome_poly)
return G.cache[:chrome_poly]
end
n::Int = NV(G)
m::Int = NE(G)
# Special case: no vertices
if n == 0
return SimplePolynomial([1])
end
# Special case: no edges
if m == 0
x = getx()
return x^n
end
# Special case: complete graph
if 2m == n * (n - 1)
x = getx()
return prod(x - k for k = 0:n-1)
# return fromroots(0:n-1)
end
# Special case: disconnected graph
comps = parts(components(G))
if length(comps) > 1
result = SimplePolynomial([1])
for A in comps
H = induce(G, A)
result *= chromatic_poly(H)
end
return result
end
# Special case: Tree
if m == n - 1
return SimplePolynomial([0, 1]) * SimplePolynomial([-1, 1])^(n - 1)
end
# See if we've computed this chromatic polynomial of this graph before
try
P = _CPM[G]
return P
catch
end
# Resort to inclusion/exclusion
# Find a vertex u of minimum degree
min_d = minimum(deg(G))
smalls = filter(v -> deg(G, v) == min_d, G.V)
u = first(smalls)
# And choose any neighbor
v = first(G[u])
# Special case to speed up handling leaves
if min_d == 1
GG = deepcopy(G)
delete!(GG, u)
p1 = chromatic_poly(GG)
P = p1 * SimplePolynomial([-1, 1])
_CPM[G] = P
return P
end
# p1 is chrome_poly of G-e
GG = deepcopy(G)
delete!(GG, u, v)
p1 = chromatic_poly(GG)
# p2 is chrome_poly of G/e
GG = deepcopy(G)
contract!(GG, u, v)
p2 = chromatic_poly(GG)
P = p1 - p2
_CPM[G] = P # save in case we see this graph again
G.cache[:chrome_poly] = P # and save in graph's cache too
return P
end
chromatic_poly(G::DG) = chromatic_poly(simplify(G))
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 4802 | export edge_connectivity, min_edge_cut
export connectivity, min_cut
# min_cut(G,s,t) -- min cut separating s and t
# min_cut(G) -- min cut separating the graph
# flag == true means we want s/t cut
"""
`min_cut(G)` returns a minimum size set of vertices that disconnects `G`.
`min_cut(G,s,t)` returns a minimum size cut that separates `s` and `t`.
"""
function min_cut(G::UG{T}, s::T, t::T, flag::Bool = true)::Set{T} where {T}
n = NV(G)
m = NE(G)
n * (n - 1) != 2m || error("Graph must not be complete")
if flag
has(G, s) || error("$s is not a vertex of this graph")
has(G, t) || error("$t is not a vertex of this graph")
s != t || error("two vertices must be different")
!has(G, s, t) || error("vertices $s and $t cannot be adjacent")
else
if cache_check(G, :min_cut)
return cache_recall(G, :min_cut)
end
if !is_connected(G)
X = Set{T}()
cache_save(G, :min_cut, X)
return X
end
end
VV = vlist(G)
EE = elist(G)
MOD = Model(get_solver())
@variable(MOD, a[VV], Bin) # in part 1
@variable(MOD, b[VV], Bin) # in part 2
@variable(MOD, c[VV], Bin) # in cut set
for v in VV
@constraint(MOD, a[v] + b[v] + c[v] == 1)
end
if flag
@constraint(MOD, a[s] == 1)
@constraint(MOD, b[t] == 1)
end
@constraint(MOD, sum(a[v] for v in VV) >= 1)
@constraint(MOD, sum(b[v] for v in VV) >= 1)
for e in EE
v, w = e
@constraint(MOD, a[v] + b[w] <= 1)
@constraint(MOD, a[w] + b[v] <= 1)
end
@objective(MOD, Min, sum(c[v] for v in VV))
optimize!(MOD)
status = Int(termination_status(MOD))
C = value.(c)
X = Set(v for v in VV if C[v] > 0.5)
if !flag
cache_save(G, :min_cut, X)
end
return X
end
function min_cut(G::UG)::Set
n = NV(G)
n > 1 || error("Graph must have at least two vertices")
s = first(G.V)
return min_cut(G, s, s, false)
end
"""
`connectivity(G)` returns the (vertex) connectivity of `G`, i.e.,
the minimum size of a vertex cut set. If `G` is a complete graph with
`n` vertices, the connectivity is `n-1` (or `0` for the empty graph).
"""
function connectivity(G::UG)::Int
n = NV(G)
m = NE(G)
if n * (n - 1) == 2m # graph is complete
return max(n - 1, 0) # what is the connectivity of K_0?
end
return length(min_cut(G))
end
# min_edge_cut(G,s,t) -- min edge cut separating s and t
# min_edge_cut(G) -- min edge cut separating the graph
# flag == true means we want s/t cut
"""
`min_edge_cut(G)` returns a minimum size set of edges whose removal
disconnects `G`. The graph must have at least two vertices.
`min_edge_cut(G,s,t)` is a minimum size set of edges whose removal
separates vertices `s` and `t`.
"""
function min_edge_cut(G::UG{T}, s::T, t::T, flag::Bool = true)::Set{Tuple{T,T}} where {T}
n = NV(G)
n > 1 || error("Graph must have at least two vertices")
if flag
has(G, s) || error("$s is not a vertex of this graph")
has(G, t) || error("$t is not a vertex of this graph")
s != t || error("vertices must not be the same")
else
if cache_check(G, :min_edge_cut)
return cache_recall(G, :min_edge_cut)
end
if !is_connected(G)
X = Set{Tuple{T,T}}()
cache_save(G, :min_edge_cut, X)
return X
end
end
VV = vlist(G)
EE = elist(G)
MOD = Model(get_solver())
@variable(MOD, a[VV], Bin) # in part 1
@variable(MOD, b[VV], Bin) # in part 2
@variable(MOD, c[EE], Bin) # span between the parts
for v in VV
@constraint(MOD, a[v] + b[v] == 1)
end
@constraint(MOD, sum(a[v] for v in VV) >= 1)
@constraint(MOD, sum(b[v] for v in VV) >= 1)
if flag
@constraint(MOD, a[s] == 1)
@constraint(MOD, b[t] == 1)
end
for e in EE
u, v = e
@constraint(MOD, a[u] + b[v] - 1 <= c[e])
@constraint(MOD, a[v] + b[u] - 1 <= c[e])
end
@objective(MOD, Min, sum(c[e] for e in EE))
optimize!(MOD)
status = Int(termination_status(MOD))
C = value.(c)
X = Set(e for e in EE if C[e] > 0.5)
if !flag
cache_save(G, :min_edge_cut, X)
end
return X
end
function min_edge_cut(G::UG)::Set
n = NV(G)
n > 1 || error("Graph must have at least two vertices")
s = first(G.V)
return min_edge_cut(G, s, s, false)
end
"""
`edge_connectivity(G)` returns the size of a minimum edge cut of `G`.
`edge_connectivity(G,s,t)` determines the minimum size of an edge cut
separating `s` and `t`.
"""
edge_connectivity(G::UG)::Int = length(min_edge_cut(G))
edge_connectivity(G::UG, s, v) = length(min_edge_cut(G, s, t))
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 1891 | export edge_color, edge_chromatic_number
"""
`edge_color(G,k)` returns a proper `k`-edge coloring of `G` or
throws an error if one does not exist.
"""
function edge_color(G::UG, k::Int)
err_msg = "This graph is not $k-edge colorable"
Delta = maximum(deg(G))
if k < Delta
error(err_msg)
end
M = max_matching(G) # this isn't that expensive
if NE(G) > length(M) * k
error(err_msg)
end
VV = vlist(G)
EE = elist(G)
n = NV(G)
m = NE(G)
VT = eltype(G)
ET = Tuple{VT,VT}
result = Dict{ET,Int}()
MOD = Model(get_solver())
@variable(MOD, x[EE, 1:k], Bin)
# Every edge must have exactly one color
for ed in EE
@constraint(MOD, sum(x[ed, i] for i = 1:k) == 1)
end
# Two edges incident with the same vertex must have different colors
for i = 1:m-1
for j = i+1:m
e1 = EE[i]
e2 = EE[j]
meet = intersect(Set(e1), Set(e2))
if length(meet) > 0
for t = 1:k
@constraint(MOD, x[e1, t] + x[e2, t] <= 1)
end
end
end
end
optimize!(MOD)
status = Int(termination_status(MOD))
if status != 1
error(err_msg)
end
X = value.(x)
for ee in EE
for t = 1:k
if X[ee, t] > 0
result[ee] = t
end
end
end
return result
end
"""
`edge_chromatic_number(G)` returns the edge chromatic number
of the graph `G`.
"""
function edge_chromatic_number(G::UG)::Int
if cache_check(G, :edge_chromatic_number)
return cache_recall(G, :edge_chromatic_number)
end
d = maximum(deg(G))
try
f = edge_color(G, d)
cache_save(G, :edge_chromatic_number, d)
return d
catch
end
cache_save(G, :edge_chromatic_number, d + 1)
return d + 1
end
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 875 | export fractional_matching
"""
`fractional_matching(G)` returns a maximum fractional matching in the form of
a dictionary mapping edges of `G` to rational values. These values are
in the set `{0, 1/2, 1}`.
"""
function fractional_matching(G::UG{T}) where {T}
if cache_check(G, :fractional_matching)
return cache_recall(G, :fractional_matching)
end
m = Model(get_solver())
@variable(m, w[G.E], Int)
for e in G.E
@constraint(m, 0 <= w[e] <= 2)
end
for v in G.V
star = [e for e in G.E if e[1] == v || e[2] == v]
@constraint(m, sum(w[e] for e in star) <= 2)
end
@objective(m, Max, sum(w[e] for e in G.E))
optimize!(m)
wts = Int.(value.(w))
d = Dict{Tuple{T,T},Rational{Int}}()
for e in G.E
d[e] = wts[e] // 2
end
cache_save(G, :fractional_matching, d)
return d
end
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 1498 | export frac_iso, is_frac_iso
"""
frac_iso(G,H)
Find a doubly stochastic matrix `S` so that `AS=SB` where `A` and `B`
are the adjacency matrices of `G` and `H` respectively.
"""
function frac_iso(G::UG, H::UG)
if deg(G) != deg(H) || degdeg(G) != degdeg(H) # quick basic check before LP
error("The graphs are not fractionally isomorphic")
end
A = adjacency(G)
B = adjacency(H)
return frac_iso(A, B)
end
function frac_iso(A::Matrix, B::Matrix)
n, c = size(A)
nn, cc = size(B)
@assert n == c && nn == cc "Matrices must be square"
@assert n == nn "Matrices must have the same size"
m = Model(get_solver())
@variable(m, S[1:n, 1:n])
for i = 1:n
for k = 1:n
@constraint(
m,
sum(A[i, j] * S[j, k] for j = 1:n) == sum(S[i, j] * B[j, k] for j = 1:n)
)
end
@constraint(m, sum(S[i, j] for j = 1:n) == 1)
@constraint(m, sum(S[j, i] for j = 1:n) == 1)
end
for i = 1:n
for j = 1:n
@constraint(m, S[i, j] >= 0)
end
end
optimize!(m)
status = Int(termination_status(m))
if status != 1
error("The graphs are not fractionally isomorphic")
end
return value.(S)
end
"""
is_frac_iso(G,H)
Test if two graphs are fractionally isomorphic.
"""
function is_frac_iso(G::UG, H::UG)::Bool
try
f = frac_iso(G, H)
return true
catch
return false
end
false
end
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 1130 | export hom, hom_check
"""
`hom_check(G,H,d)` checks if the dictionary `d` is a graph homomorphism
from `G` to `H`.
"""
function hom_check(G::UG, H::UG, d::Dict)::Bool
for e in G.E
v, w = e
x = d[v]
y = d[w]
if !H[x, y]
return false
end
end
return true
end
"""
`hom(G,H)` finds a graph homomorphism from `G` to `H`.
"""
function hom(G::UG{S}, H::UG{T}) where {S,T}
m = Model(get_solver())
@variable(m, P[G.V, H.V], Bin)
for v in G.V
@constraint(m, sum(P[v, x] for x in H.V) == 1)
end
for e in G.E
u, v = e
for x in H.V
for y in H.V
if !H[x, y]
@constraint(m, P[u, x] + P[v, y] <= 1)
end
end
end
end
optimize!(m)
status = Int(termination_status(m))
if status != 1
error("No homomorphism")
end
PP = Int.(value.(P))
result = Dict{S,T}()
for v in G.V
for x in H.V
if PP[v, x] > 0
result[v] = x
end
end
end
return result
end
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 8842 | export iso, iso2, iso_matrix, is_iso, info_map, uhash, degdeg, fast_iso_test
const iso_err_msg = "The graphs are not isomorphic"
"""
`iso_matrix(G,H)` returns a permutation matrix `P` such that
`A*P==P*B` where `A` is the adjacency matrix of `G` and `B` is the
adjacency matrix of `H`. If the graphs are not isomorphic, an
error is raised.
"""
function iso_matrix(G::UG, H::UG)
n = NV(G)
if !fast_iso_test_basic(G, H)
error(iso_err_msg)
end
m = Model(get_solver())
@variable(m, P[1:n, 1:n], Bin)
A = adjacency(G)
B = adjacency(H)
for i = 1:n
for k = 1:n
@constraint(
m,
sum(A[i, j] * P[j, k] for j = 1:n) == sum(P[i, j] * B[j, k] for j = 1:n)
)
end
@constraint(m, sum(P[i, j] for j = 1:n) == 1)
@constraint(m, sum(P[j, i] for j = 1:n) == 1)
end
optimize!(m)
status = Int(termination_status(m))
if status != 1
error(iso_err_msg)
end
return Int.(value.(P))
end
"""
`is_iso(G,H,d)` checks if `d` is an isomorphism from `G` to `H`.
"""
function is_iso(G::UG, H::UG, d::Dict)::Bool
n = NV(G)
# standard quick check
if n != NV(H) || NE(G) != NE(H) || deg(G) != deg(H) || length(d) != n
return false
end
# check keys and values in d match VG and VH, respectively
for k in keys(d)
if !has(G, k)
return false
end
end
for v in values(d)
if !has(H, v)
return false
end
end
# Check edges match. Only need to go one way since we determined
# that the two graphs have the same number of edges.
EE = elist(G)
for e in EE
v = e[1]
w = e[2]
if !has(H, d[v], d[w])
return false
end
end
return true
end
"""
`is_iso(G,H)` returns `true` if the two graphs are isomorphic and `false`
otherwise.
"""
function is_iso(G::UG, H::UG)::Bool
try
f = iso(G, H)
catch
return false
end
return true
end
"""
`fast_iso_test_basic(G,H)` is a very quick test to rule out graphs being
isomorphic by considering the number of vertices, number of edges, and
degree sequences. Returns `false` if the graphs fail this very basic
test of isomorphism. A `true` result does *not* imply the graphs are
isomorphic.
"""
function fast_iso_test_basic(G::UG, H::UG)::Bool
if NV(G) != NV(H) || NE(G) != NE(H) || deg(G) != deg(H)
return false
end
return true
end
"""
`fast_iso_test(G,H)` applies various heuristics to see if
the graphs *might* be isomorphic. A `false` return certifies the
graphs are **not** isomorphic; a `true` result indicates the
graphs might be (indeed, likely are) isomorphic.
"""
function fast_iso_test(G::UG, H::UG)::Bool
return fast_iso_test_basic(G, H) && uhash(G) == uhash(H)
end
"""
`degdeg(G)` creates an n-by-n matrix where the nonzero entries in a
row are the degrees of the neighbors of that vertex. The rows are
lexicographically sorted.
"""
function degdeg(G::UG)
if cache_check(G, :degdeg)
return cache_recall(G, :degdeg)
end
n = NV(G)
result = zeros(Int, n, n)
VV = vlist(G)
for k = 1:n
v = VV[k]
dv = [deg(G, w) for w in G[v]]
dv = sort(dv)
dv = [dv; zeros(Int, n - deg(G, v))]
result[k, :] = dv
end
result = sortslices(result, dims = 1)
cache_save(G, :degdeg, result)
return result
end
"""
`info_map(G)`:
We create a dictionary mapping the vertices of `G` to 128-bit integer
values in such a way that twin vertices *will* have the same value
but, we hope, nontwin vertices will have different values. (By *twin*
we mean a pair of vertices such that there is an automorphism of the
graph mapping one to the other.)
"""
function info_map(G::UG)
if cache_check(G, :info_map)
return cache_recall(G, :info_map)
end
n = NV(G)
VV = vlist(G)
H = G'
# Section 1: Neighborhood degrees
M1 = zeros(Int, n, n - 1)
for k = 1:n
v = VV[k]
rv = [deg(G, w) for w in G[v]]
rv = [sort(rv); zeros(Int, n - 1 - deg(G, v))]
M1[k, :] = rv
end
# Section 2: Complement degrees
M2 = zeros(Int, n, n - 1)
for k = 1:n
v = VV[k]
rv = [deg(H, w) for w in H[v]]
rv = [sort(rv); zeros(Int, n - 1 - deg(H, v))]
M2[k, :] = rv
end
# Section 3: Distances
M3 = zeros(Int, n, n - 1)
for k = 1:n
v = VV[k]
dv = dist(G, v)
M3[k, :] = sort(collect(values(dv)))[1:n-1]
end
# Section 4: Distances in complement
M4 = zeros(Int, n, n - 1)
for k = 1:n
v = VV[k]
dv = dist(H, v)
M4[k, :] = sort(collect(values(dv)))[1:n-1]
end
M = [M1 M2 M3 M4]
# println(sortrows(M)) # debug
T = eltype(G)
d = Dict{T,Int128}()
for k = 1:n
v = VV[k]
d[v] = Int128(hash(M[k, :]))
end
cache_save(G, :info_map, d)
return d
end
"""
`iso(G,H)` finds an isomorphism from `G` to `H` (or throws an error if
the graphs are not isomorphic). Returns a dictionary mapping the
vertices of `G` to `H`.
See also: `iso2`.
"""
function iso(G::UG, H::UG)
# quickly rule out some easily detected nonisomorphic graphs
if !fast_iso_test(G, H) || uhash(G) != uhash(H)
error(iso_err_msg)
end
VG = vlist(G)
VH = vlist(H)
n = NV(G)
TG = eltype(G)
TH = eltype(H)
dG = info_map(G)
dH = info_map(H)
# Create mappings from vertex key values back to the vertices themselves
xG = Dict{Int128,Set{TG}}()
xH = Dict{Int128,Set{TH}}()
valsG = sort(collect(values(dG)))
valsH = sort(collect(values(dH)))
for x in valsG
xG[x] = Set{TG}()
xH[x] = Set{TH}()
end
for v in VG
x = dG[v]
push!(xG[x], v)
end
for v in VH
x = dH[v]
push!(xH[x], v)
end
MOD = Model(get_solver())
@variable(MOD, x[VG, VH], Bin)
for v in VG
@constraint(MOD, sum(x[v, VH[k]] for k = 1:n) == 1)
end
for w in VH
@constraint(MOD, sum(x[VG[k], w] for k = 1:n) == 1)
end
for v in VG
for w in VH
@constraint(
MOD,
sum(has(G, v, VG[k]) * x[VG[k], w] for k = 1:n) ==
sum(x[v, VH[k]] * has(H, VH[k], w) for k = 1:n)
)
end
end
# Add contraints based on vertex numbers
for val in unique(valsG)
SG = collect(xG[val])
SH = collect(xH[val])
s = length(SG)
@constraint(MOD, sum(x[u, v] for u in SG for v in SH) == s)
end
optimize!(MOD)
status = Int(termination_status(MOD))
if status != 1
error(iso_err_msg)
end
X = value.(x)
result = Dict{eltype(G),eltype(H)}()
for v in VG
for w in VH
if X[v, w] > 0
result[v] = w
end
end
end
return result
end
"""
`iso2(G,H)` is another version of `iso(G,H)` that does much less preprocessing.
It may be faster for highly symmetric graphs (e.g., vertex transitive graphs).
"""
function iso2(G::UG{S}, H::UG{T}) where {S,T}
if NV(G) != NV(H)
error(iso_err_msg)
end
m = Model(get_solver())
@variable(m, P[G.V, H.V], Bin)
for v in G.V
for x in H.V
@constraint(
m,
sum(G[v, w] * P[w, x] for w in G.V) == sum(P[v, y] * H[y, x] for y in H.V)
)
end
end
for v in G.V
@constraint(m, sum(P[v, x] for x in H.V) == 1)
end
for x in H.V
@constraint(m, sum(P[v, x] for v in G.V) == 1)
end
optimize!(m)
status = Int(termination_status(m))
if status != 1
error(iso_err_msg)
end
PP = Int.(value.(P))
result = Dict{S,T}()
for v in G.V
for x in H.V
if PP[v, x] > 0
result[v] = x
end
end
end
return result
end
using LinearAlgebra
function matrix_moments(A, max_exp::Int = 10)
result = zeros(Int, max_exp)
B = copy(A)
for t = 1:max_exp
B = A * B
result[t] = tr(B)
end
return result
end
"""
`uhash(G)` creates an `UInt64` hash of the graph such that isomorphic
graphs will produce the same value. We hope that nonisomorphic graphs
will create different values, but, alas, that need not be the case.
"""
function uhash(G::UG)
if cache_check(G, :uhash)
return cache_recall(G, :uhash)
end
v1 = sort(collect(values(info_map(G))))
A = adjacency(G)
B = deepcopy(A)
depth = min(10, NV(G))
v2 = matrix_moments(adjacency(G))
v3 = matrix_moments(laplace(G))
vv = [v1; v2; v3]
x = hash(vv)
cache_save(G, :uhash, x)
return x
end
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 803 | export kfactor
"""
`kfactor(G,k=1)` returns a `k`-factor of `G`. This is a set of edges
with the property that every vertex of `G` is incident with exactly `k`
edges in the set. An error is thrown if no such set exists.
"""
function kfactor(G::UG, k::Int = 1)
@assert k > 0 "The parameter k must be positive"
VV = vlist(G)
EE = elist(G)
n = NV(G)
m = NE(G)
MOD = Model(get_solver())
@variable(MOD, x[EE], Bin)
for v in VV
star = [get_edge(G, v, w) for w in G[v]]
@constraint(MOD, sum(x[e] for e in star) == k)
end
optimize!(MOD)
status = Int(termination_status(MOD))
if status != 1
error("This graph does not have a $k-factor")
end
X = value.(x)
result = Set(e for e in EE if X[e] > 0.5)
return result
end
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 2512 | export ad, mad, mad_core
"""
`mad_model(G)` returns the solved linear program whose optimum
value is `mad(G)`.
"""
function mad_model(G::UG)
EE = elist(G)
VV = vlist(G)
n = length(VV)
m = length(EE)
MOD = Model(get_solver())
# variables
@variable(MOD, z >= 0)
@variable(MOD, x[i = 1:n, j = 1:m; in(VV[i], EE[j])] >= 0)
# vertex constraints
for i = 1:n
v = VV[i]
# get all edges that have v as an end point
j_iterator = (j for j = 1:m if EE[j][1] == v || EE[j][2] == v)
j_list = collect(j_iterator)
@constraint(MOD, sum(x[i, j] for j in j_list) <= z)
end
# edge constraints
for j = 1:m
v, w = EE[j]
i1 = first(findall(x -> x == v, VV))
i2 = first(findall(x -> x == w, VV))
@constraint(MOD, x[i1, j] + x[i2, j] == 2)
end
@objective(MOD, Min, z)
optimize!(MOD)
return MOD, x, VV, EE
end
"""
`mad(G)` computes the maximum average degree of `G`.
See also `mad_core`.
"""
function mad(G::UG)
if cache_check(G, :mad)
return cache_recall(G, :mad)
end
MOD, x, VV, EE = mad_model(G)
mval = objective_value(MOD)
cache_save(G, :mad, mval)
return mval
end
"""
`ad(G)` is the average degree of a vertex in `G`.
"""
ad(G::UG) = 2 * NE(G) / NV(G)
"""
`mad_core(G)` returns a subgraph `H` of `G` for which
`ad(H)==mad(G)`.
"""
function mad_core(G::UG)
if cache_check(G, :mad_core)
return cache_recall(G, :mad_core)
end
T = eltype(G)
GG = deepcopy(G)
while true
if NV(GG) == 0
error("Bad graph or something went wrong")
end
# solve the LP for GG
MOD, x, VV, EE = mad_model(GG)
n = length(VV)
m = length(EE)
err = 0.1 / n
mval = objective_value(MOD)
# if balanced, return
if abs(ad(GG) - mval) <= err
cache_save(G, :mad_core, GG)
return GG
end
# otherwise, find and destroy defective vertices
for i = 1:n
v = VV[i]
total = 0.0
for j = 1:m
e = EE[j]
if in(v, e)
val = value(x[i, j])
total += val
end
end
if total < mval - err # this is a defective vertex
delete!(GG, v)
end
end
end # end while
error("This can't happen (but it did)")
cache_save(G, :mad_core, GG)
return GG
end
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 3393 | export vertex_color, chromatic_number
"""
`vertex_color(G,k)`: Return a `k`-coloring of `G` (or error if none exists).
If `k` is omitted, the chromatic number of `G` is used.
"""
function vertex_color(G::UG, k::Int)
VV = vlist(G)
EE = elist(G)
n = NV(G)
m = NE(G)
if k < 1
error("Number of colors must be positive")
end
err_msg = "This graph is not " * string(k) * " colorable"
# Special cases that don't require integer programming
# see if we know the chromatic number already
if cache_check(G, :chromatic_number)
chi = cache_recall(G, :chromatic_number)
if k < chi
error(err_msg)
end
end
result = Dict{eltype(G),Int}()
if k == 1
if NE(G) > 0
error(err_msg)
end
for v in VV
result[v] = 1
end
return result
end
if k == 2
return two_color(G)
end
MOD = Model(get_solver())
@variable(MOD, x[VV, 1:k], Bin)
for v in VV
@constraint(MOD, sum(x[v, i] for i = 1:k) == 1)
end
for e in EE
u = e[1]
v = e[2]
for i = 1:k
@constraint(MOD, x[u, i] + x[v, i] <= 1)
end
end
optimize!(MOD)
status = Int(termination_status(MOD))
if status != 1
error(err_msg)
end
X = value.(x)
for v in VV
for c = 1:k
if X[v, c] > 0
result[v] = c
end
end
end
return result
end
vertex_color(G::UG) = vertex_color(G, chromatic_number(G))
"""
`vertex_color(G,a,b)` returns an `a:b`-coloring of the graph `G`.
This is a mapping from the vertices of `G` to `b`-element subsets of
`{1,2,...,a}` such that adjacent vertices are assigned disjoint sets.
An error is thrown if no such coloring exists.
"""
function vertex_color(G::UG, a::Int, b::Int)
if a < 0 || b < 0
error("Arguments in vertex_color(G,$a,$b) must be nonnegative")
end
try
return hom(G, Kneser(a, b))
catch
error("This graph does not have a $a:$b coloring")
end
end
function chromatic_number(G::UG, verb::Bool = false)::Int
if cache_check(G, :chromatic_number)
return cache_recall(G, :chromatic_number)
end
if NV(G) == 0
return 0
end
if NE(G) == 0
return 1
end
# lower bound: larger of clique size or n/alpha
n = NV(G)
alf = length(max_indep_set(G))
lb1 = Int(floor(n / alf))
lb2 = length(max_clique(G))
lb = max(lb1, lb2)
# upper bound: try a random greedy coloring
f = greedy_color(G)
ub = maximum(values(f))
k = chromatic_number_work(G, lb, ub, verb)
cache_save(G, :chromatic_number, k)
return k
end
function chromatic_number_work(G::UG, lb::Int, ub::Int, verb::Bool)::Int
if verb
print("$lb ≤ χ ≤ $ub")
end
if lb == ub
if verb
println("\tand we're done")
end
return lb
end
mid = Int(floor((ub + lb) / 2))
if verb
print("\tlooking for a $mid coloring")
end
try
f = vertex_color(G, mid) # success
if verb
println("\tfound")
end
return chromatic_number_work(G, lb, mid, verb)
catch
end
if verb
println("\tno such coloring")
end
return chromatic_number_work(G, mid + 1, ub, verb)
end
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | code | 2044 | using Test
using SimpleGraphs, SimpleGraphAlgorithms, Polynomials
# use_GLPK()
# G = Paley(17)
# Cliques and independent sets
@testset "Clique/Indep" begin
G = Paley(17)
A = max_clique(G)
B = max_indep_set(G)
@test length(A) == length(B)
end
# Isomorphism
@testset "Isomorphism" begin
G = Paley(17)
f = iso(G, G')
@test length(f) == 17
@test is_iso(G, G')
# fractional Isomorphism
G = Dodecahedron()
H = RandomRegular(20, 3)
@test is_frac_iso(G, H)
H = RandomRegular(20, 4)
@test !is_frac_iso(G, H)
d = hom(Cube(3), Complete(2))
@test d["000"] != d["001"]
end
# Edge matching
@testset "Matching" begin
G = Paley(17)
M = max_matching(G)
@test length(M) == 8
d = fractional_matching(Cycle(5))
@test sum(values(d)) == 5 // 2
H = Dodecahedron()
X = kfactor(H, 3)
@test length(X) == 30
end
# Vertex coloring
@testset "Coloring" begin
G = Cycle(7)
f = vertex_color(G, 6)
@test length(f) == NV(G)
# Edge coloring
@test edge_chromatic_number(G) == 3
f = edge_color(G, 3)
@test length(f) == NE(G)
end
# Domination
@testset "Domination/Covering" begin
G = Paley(17)
A = min_dom_set(G)
@test length(A) == 3
# Covering
A = min_vertex_cover(G)
@test length(A) == 14
A = min_vertex_cover(G, 10)
@test length(A) == 2
A = min_edge_cover(G)
@test length(A) == 9
# MAD
@test mad(G) == maximum(deg(G))
end
@testset "Coloring" begin
# Chromatic Polynomial
f = chromatic_poly(Cycle(5))
@test f(2) == 0
@test f(3) == 30
# Chromatic number
@test chromatic_number(Petersen()) == 3
G = Spindle()
add!(G, 4, 0)
H = Spindle()
add!(H, 7, 0)
@test fast_iso_test(G, H)
d = vertex_color(Spindle(), 7, 2)
@test length(d[1] ∩ d[2]) == 0
end
# edge and vertex connectivity
@testset "Connectivity" begin
G = Complete(8, 8)'
add!(G, 1, 9)
add!(G, 1, 10)
@test edge_connectivity(G) == 2
@test connectivity(G) == 1
end
| SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | docs | 7125 | # SimpleGraphAlgorithms
This module provides additional functions for the `SimpleGraphs`
module that rely on integer programming. In addition to requiring the
`SimpleGraphs` module, it also requires `JuMP` and `ChooseOptimizer` to
select an integer programming solver (defaults to `HiGHS`).
> **New in version 0.6**: The functions `use_Gurobi` and `use_Cbc` have been removed. The default solver is now `HiGHS`. To change solvers, use the `set_solver` function from `ChooseOptimizer`.
## Cliques and Independent Sets
* `max_indep_set(G)` returns a maximum size independent set of an
`UndirectedGraph`.
* `max_clique(G)` returns a maximum size clique of an `UndirectedGraph`.
* `max_matching(G)` returns a maximum size matching of an
`UndirectedGraph`.
* `fractional_matching(G)` returns a (maximum) fractional matching of the
graph `G`. This is presented a dictionary mapping edges of `G` to rational values
in `{0, 1/2, 1}`.
* `kfactor(G,k)` returns a `k`-factor of `G`. This is a set of edges
with the property that every vertex of `G` is incident with exactly `k`
edges of the set. An error is thrown if no such set exists.
(When `k==1` this returns a perfect matching.)
## Covering and Domination
* `min_dom_set(G)` returns a smallest dominating set of an
`UndirectedGraph`. That is, a smallest set `S` with the property that
every vertex of `G` either is in `S` or is adjacent to a vertex of
`S`.
* `min_vertex_cover(G)` returns a smallest vertex cover of `G`. This
is a set of vertices `S` such that every edge of `G` has at least
one end point in `S`.
* `min_edge_cover(G)` returns a smallest edge cover of `G`. This is
a set of edges `F` such that every vertex of `G` is the end point
of at least one edge in `F`. **Note**: If `G` has an isolated
vertex, then no edge cover is possible and error is generated.
## Isomorphism
* `iso(G,H)` finds an isomorphism between graphs `G` and
`H`. Specifically, it finds a `Dict` mapping the vertices of `G` to
the vertices of `H` that gives the isomorphism. If the graphs are
not isomorphic, an error is raised.
* `iso2(G,H)` has the same functionality as `iso` but omits various
preliminary checks. This may be faster for highly symmetric graphs
(e.g., for vertex transitive graphs).
* `is_iso(G,H)` checks if the two graphs are isomorphic.
* `is_iso(G,H,d)` checks if the dictionary `d` is an isomorphism
from `G` to `H`.
* `iso_matrix(G,H)` finds an isomorphism between graphs `G` and
`H`. Specifically, it finds a permutation matrix `P` such that
`A*P==P*B` where `A` and `B` are the adjacency matrices of the
graphs `G` and `H`, respectively. If the graphs are not isomorphic,
an error is raised.
* `frac_iso(G,H)` finds a fractional isomorphism between the graphs. Specifically,
if `A` and `B` are the adjacency matrices of the two graphs, then produce a
doubly stochastic matrix `S` such that `A*S == S*B`, or throw an error if
no such matrix exists.
* `is_frac_iso(G,H)` returns `true` if the graphs are fractionally isomorphic
and `false` if not.
* `hom(G,H)` finds a graph homomorphism from `G` to `H`. This is a mapping `f`
(dictionary) with the property that if `{u,v}` is an edge of `G` then
`{f[u],f[v]}` is an edge of `H`. If no homomorphism exists an error is raised.
* `hom_check(G,H,d)` determines if `d` is a homomorphism from `G` to `H`.
* `info_map(G)` creates a mapping from the vertices of `G` to 128-bit
integers. If there is an automorphism between a pair of vertices,
then they will map to the same value, and the converse is *likely*
to be true.
* `uhash(G)` creates a hash value for the graph `G` with the property
that isomorphic graphs have the same hash value.
## Coloring
* `vertex_color(G,k)` returns a `k`-coloring of `G` (or throws an error if no
such coloring exists). If `k` is omitted, the number of colors is `χ(G)`
(chromatic number).
* `vertex_color(G,a,b)` returns an `a:b`-coloring of `G` (or throws an error
if no such coloring exists). An `a:b`-coloring is a mapping from the vertices of
`G` to `b`-element subsets of `{1,2,...,a}` such that adjacent vertices are
assigned disjoint sets.
* `chromatic_number(G)` returns the least `k` such that `G` is `k`-colorable.
* `chromatic_poly(G)` computes the chromatic polynomial of `G`. (See the
`help` message for more information.)
* `edge_color(G,k)` returns a `k`-edge-coloring of `G`.
* `edge_chromatic_number(G)` returns the edge chromatic number of `G`.
## Connectivity
* `min_cut(G)` returns a minimum size (vertex) cut set. `min_cut(G,s,t)`
return a smallest set of vertices that separate `s` and `t`.
* `connectivity(G)` or `connectivity(G,s,t)` returns the size of such a cut set.
* `min_edge_cut(G)` returns a minimum size edge cut set.
`min_edge_cut(G,s,t)` returns a minimum set of edges that separate vertices
`s` and `t`.
* `edge_connectivity(G)` or `edge_connectivity(G,s,t)` returns the size of
such an edge cut set.
## Maximum Average Degree
* `ad(G)` returns the average degree of `G`.
* `mad(G)` returns the maximum average degree of `G`.
* `mad_core(G)` returns a subgraph `H` of `G` for which `ad(H)==mad(G)`.
## Examples
```
julia> using SimpleGraphs; using SimpleGraphAlgorithms; using ChooseOptimizer; using ShowSet
julia> set_solver_verbose(false)
[ Info: Setting verbose option for Cbc to false
julia> G = Paley(17)
Paley (n=17, m=68)
julia> max_indep_set(G)
{1,4,7}
julia> max_clique(G)
{3,4,5}
julia> min_dom_set(G)
{3,6,9}
julia> max_matching(G)
{(1, 16),(2, 4),(3, 12),(5, 9),(6, 15),(7, 8),(10, 11),(13, 14)}
julia> vertex_color(G,6)
Dict{Int64,Int64} with 17 entries:
2 => 3
16 => 1
11 => 4
0 => 4
7 => 6
9 => 2
10 => 1
8 => 3
6 => 4
4 => 6
3 => 5
5 => 3
13 => 1
14 => 5
15 => 2
12 => 2
1 => 6
```
Petersen's graph can be described as either the 5,2-Kneser graph or as
the complement of the line graph of K(5).
```
julia> G = Kneser(5,2);
julia> H = complement(line_graph(Complete(5)));
julia> iso(G,H)
Dict{Set{Int64},Tuple{Int64,Int64}} with 10 entries:
{1,4} => (1, 5)
{2,4} => (1, 4)
{2,5} => (3, 4)
{1,3} => (2, 5)
{3,4} => (1, 2)
{1,2} => (4, 5)
{3,5} => (2, 3)
{4,5} => (1, 3)
{2,3} => (2, 4)
{1,5} => (3, 5)
julia> iso_matrix(G,H)
10×10 Array{Int64,2}:
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 0 0
```
## Using `SimpleGraphAlgorithms` with `Graphs`
`SimpleGraphAlgorithms` is built to work with `UndirectedGraph` objects as defined in `SimpleGraphs`.
To apply these functions to graphs from Julia's `Graphs` module, you can use `SimpleGraphConverter` like this:
```
julia> using Graphs, SimpleGraphAlgorithms, SimpleGraphs, SimpleGraphConverter
julia> g = circular_ladder_graph(9)
{18, 27} undirected simple Int64 graph
julia> chromatic_number(UG(g))
3
``` | SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.6.0 | e333fd8f96c9e61b3beac3968b06c87d5f849d99 | docs | 7125 | # SimpleGraphAlgorithms
This module provides additional functions for the `SimpleGraphs`
module that rely on integer programming. In addition to requiring the
`SimpleGraphs` module, it also requires `JuMP` and `ChooseOptimizer` to
select an integer programming solver (defaults to `HiGHS`).
> **New in version 0.6**: The functions `use_Gurobi` and `use_Cbc` have been removed. The default solver is now `HiGHS`. To change solvers, use the `set_solver` function from `ChooseOptimizer`.
## Cliques and Independent Sets
* `max_indep_set(G)` returns a maximum size independent set of an
`UndirectedGraph`.
* `max_clique(G)` returns a maximum size clique of an `UndirectedGraph`.
* `max_matching(G)` returns a maximum size matching of an
`UndirectedGraph`.
* `fractional_matching(G)` returns a (maximum) fractional matching of the
graph `G`. This is presented a dictionary mapping edges of `G` to rational values
in `{0, 1/2, 1}`.
* `kfactor(G,k)` returns a `k`-factor of `G`. This is a set of edges
with the property that every vertex of `G` is incident with exactly `k`
edges of the set. An error is thrown if no such set exists.
(When `k==1` this returns a perfect matching.)
## Covering and Domination
* `min_dom_set(G)` returns a smallest dominating set of an
`UndirectedGraph`. That is, a smallest set `S` with the property that
every vertex of `G` either is in `S` or is adjacent to a vertex of
`S`.
* `min_vertex_cover(G)` returns a smallest vertex cover of `G`. This
is a set of vertices `S` such that every edge of `G` has at least
one end point in `S`.
* `min_edge_cover(G)` returns a smallest edge cover of `G`. This is
a set of edges `F` such that every vertex of `G` is the end point
of at least one edge in `F`. **Note**: If `G` has an isolated
vertex, then no edge cover is possible and error is generated.
## Isomorphism
* `iso(G,H)` finds an isomorphism between graphs `G` and
`H`. Specifically, it finds a `Dict` mapping the vertices of `G` to
the vertices of `H` that gives the isomorphism. If the graphs are
not isomorphic, an error is raised.
* `iso2(G,H)` has the same functionality as `iso` but omits various
preliminary checks. This may be faster for highly symmetric graphs
(e.g., for vertex transitive graphs).
* `is_iso(G,H)` checks if the two graphs are isomorphic.
* `is_iso(G,H,d)` checks if the dictionary `d` is an isomorphism
from `G` to `H`.
* `iso_matrix(G,H)` finds an isomorphism between graphs `G` and
`H`. Specifically, it finds a permutation matrix `P` such that
`A*P==P*B` where `A` and `B` are the adjacency matrices of the
graphs `G` and `H`, respectively. If the graphs are not isomorphic,
an error is raised.
* `frac_iso(G,H)` finds a fractional isomorphism between the graphs. Specifically,
if `A` and `B` are the adjacency matrices of the two graphs, then produce a
doubly stochastic matrix `S` such that `A*S == S*B`, or throw an error if
no such matrix exists.
* `is_frac_iso(G,H)` returns `true` if the graphs are fractionally isomorphic
and `false` if not.
* `hom(G,H)` finds a graph homomorphism from `G` to `H`. This is a mapping `f`
(dictionary) with the property that if `{u,v}` is an edge of `G` then
`{f[u],f[v]}` is an edge of `H`. If no homomorphism exists an error is raised.
* `hom_check(G,H,d)` determines if `d` is a homomorphism from `G` to `H`.
* `info_map(G)` creates a mapping from the vertices of `G` to 128-bit
integers. If there is an automorphism between a pair of vertices,
then they will map to the same value, and the converse is *likely*
to be true.
* `uhash(G)` creates a hash value for the graph `G` with the property
that isomorphic graphs have the same hash value.
## Coloring
* `vertex_color(G,k)` returns a `k`-coloring of `G` (or throws an error if no
such coloring exists). If `k` is omitted, the number of colors is `χ(G)`
(chromatic number).
* `vertex_color(G,a,b)` returns an `a:b`-coloring of `G` (or throws an error
if no such coloring exists). An `a:b`-coloring is a mapping from the vertices of
`G` to `b`-element subsets of `{1,2,...,a}` such that adjacent vertices are
assigned disjoint sets.
* `chromatic_number(G)` returns the least `k` such that `G` is `k`-colorable.
* `chromatic_poly(G)` computes the chromatic polynomial of `G`. (See the
`help` message for more information.)
* `edge_color(G,k)` returns a `k`-edge-coloring of `G`.
* `edge_chromatic_number(G)` returns the edge chromatic number of `G`.
## Connectivity
* `min_cut(G)` returns a minimum size (vertex) cut set. `min_cut(G,s,t)`
return a smallest set of vertices that separate `s` and `t`.
* `connectivity(G)` or `connectivity(G,s,t)` returns the size of such a cut set.
* `min_edge_cut(G)` returns a minimum size edge cut set.
`min_edge_cut(G,s,t)` returns a minimum set of edges that separate vertices
`s` and `t`.
* `edge_connectivity(G)` or `edge_connectivity(G,s,t)` returns the size of
such an edge cut set.
## Maximum Average Degree
* `ad(G)` returns the average degree of `G`.
* `mad(G)` returns the maximum average degree of `G`.
* `mad_core(G)` returns a subgraph `H` of `G` for which `ad(H)==mad(G)`.
## Examples
```
julia> using SimpleGraphs; using SimpleGraphAlgorithms; using ChooseOptimizer; using ShowSet
julia> set_solver_verbose(false)
[ Info: Setting verbose option for Cbc to false
julia> G = Paley(17)
Paley (n=17, m=68)
julia> max_indep_set(G)
{1,4,7}
julia> max_clique(G)
{3,4,5}
julia> min_dom_set(G)
{3,6,9}
julia> max_matching(G)
{(1, 16),(2, 4),(3, 12),(5, 9),(6, 15),(7, 8),(10, 11),(13, 14)}
julia> vertex_color(G,6)
Dict{Int64,Int64} with 17 entries:
2 => 3
16 => 1
11 => 4
0 => 4
7 => 6
9 => 2
10 => 1
8 => 3
6 => 4
4 => 6
3 => 5
5 => 3
13 => 1
14 => 5
15 => 2
12 => 2
1 => 6
```
Petersen's graph can be described as either the 5,2-Kneser graph or as
the complement of the line graph of K(5).
```
julia> G = Kneser(5,2);
julia> H = complement(line_graph(Complete(5)));
julia> iso(G,H)
Dict{Set{Int64},Tuple{Int64,Int64}} with 10 entries:
{1,4} => (1, 5)
{2,4} => (1, 4)
{2,5} => (3, 4)
{1,3} => (2, 5)
{3,4} => (1, 2)
{1,2} => (4, 5)
{3,5} => (2, 3)
{4,5} => (1, 3)
{2,3} => (2, 4)
{1,5} => (3, 5)
julia> iso_matrix(G,H)
10×10 Array{Int64,2}:
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 0 0
```
## Using `SimpleGraphAlgorithms` with `Graphs`
`SimpleGraphAlgorithms` is built to work with `UndirectedGraph` objects as defined in `SimpleGraphs`.
To apply these functions to graphs from Julia's `Graphs` module, you can use `SimpleGraphConverter` like this:
```
julia> using Graphs, SimpleGraphAlgorithms, SimpleGraphs, SimpleGraphConverter
julia> g = circular_ladder_graph(9)
{18, 27} undirected simple Int64 graph
julia> chromatic_number(UG(g))
3
``` | SimpleGraphAlgorithms | https://github.com/scheinerman/SimpleGraphAlgorithms.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 631 | module Smoothers
using Dierckx
import Base: filter
export filter, hma, loess, sma, stl
# Methods
include("filter.jl")
include("hma.jl")
include("loess.jl")
include("sma.jl")
include("stl.jl")
"""
Collection of smoothing heuristics, models and smoothing related applications. The current available smoothers and applications are:
`filter`: Linear Time-invariant Difference Equation Filter (Matlab/Octave)
`hma`: Henderson Moving Average Filter
`loess`: Locally Estimated Scatterplot Smoothing
`sma`: Simple Moving Average
`stl`: Seasonal and Trend decomposition based on Loess
"""
Smoothers
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 1944 | """
Package: Smoothers
filter(b,a,x,si)
Apply a digital filter to x using the following linear, time-invariant difference equation
```math
y(n) = \\sum_{k=0}^M d_{k+1} \\cdot x_{n-k}-\\sum_{k=1}^N c_{k+1} \\cdot y_{n-k}
\\\\ \\forall n | 1\\le n \\le \\left\\| x \\right\\| | c=a/a_1, d=b/a_1
```
The implementation follows the description of [Octave filter function](https://octave.sourceforge.io/octave/function/filter.html)
# Arguments
- `a`: Vector of numerator coefficients for the filter rational transfer function.
- `b`: Vector of denominator coefficients for the filter rational transfer function.
- `x`: Vector of data.
- `si`: Vector of initial states.
# Returns
Vector of filtered data
# Examples
```julia-repl
using Plots
t = Array(LinRange(-pi,pi,100));
x = sin.(t) .+ 0.25*rand(length(t));
# Moving Average Filter
w = 5;
b = ones(w)/w;
a = [1];
plot(t,x,label="sin(x)",legend=:bottomright)
y1 = filter(b,a,x)
si = x[1:4] .+ .1;
y2 = filter(b,a,x,si)
plot!(t,y1,label="MA")
plot!(t,y2,label="MA with si")
```
"""
@inline function filter(b::AbstractVector{A},
a::AbstractVector{B},
x::AbstractVector{C},
si::AbstractVector{D}=zeros(C,max(length(a),length(b))-1)
) where {A<:Real,B<:Real,C<:Real,D<:Real}
@assert a[1] != 0 "a[1] must not be zero"
T = Base.promote_op(/,C,Base.promote_op(/,B,A))
a,b,x,si,_ = Base.promote(a,b,x,si,[T(1.0)])
Na,Nb,Nx = length(a),length(b),length(x)
Nsi = max(Na,Nb)-1
@assert Nsi == length(si) "length(si) must be max(length(a),length(b))-1)"
N,M = Na-1,Nb-1
c,d = a/a[1],b/a[1]
y = zeros(T,Nx)
y[1:Nsi] = si
for n in 1:Nx
for k in 0:min(n-1,M)
@inbounds y[n] += d[k+1]*x[n-k]
end
for k in 1:min(n-1,N)
@inbounds y[n] -= c[k+1]*y[n-k]
end
end
return y
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 5784 | # MIT License
# Copyright (c) 2021 Fran Urbano
# Copyright (c) 2021 Val Lyashov
# Copyright (c) 2020 Bryan Palmer
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Package: Forecast
hma(x, n)
Applies the Henderson moving average filter to dataset `x` with `n`-term.
"Henderson moving averages are filters which were derived by Robert Henderson in 1916
for use in actuarial applications. They are trend filters, commonly used in time series
analysis to smooth seasonally adjusted estimates in order to generate a trend estimate.
They are used in preference to simpler moving averages because they can reproduce
polynomials of up to degree 3, thereby capturing trend turning points.
The ABS uses Henderson moving averages to produce trend estimates from a seasonally
adjusted series. The trend estimates published by the ABS are typically derived using
a 13 term Henderson filter for monthly series, and a 7 term Henderson filter for quarterly series.
Henderson filters can be either symmetric or asymmetric. Symmetric moving averages can be applied
at points which are sufficiently far away from the ends of a time series. In this case, the
smoothed value for a given point in the time series is calculated from an equal number of values
on either side of the data point." - Australian Bureau of Statistics (www.abs.gov.au)
# Arguments
- `x`: Observations' support.
- `n`: Observation values, tipically 13 or 7 for quarterly data.
# Returns
An array of Henderson filter smoothed values provided in `s`.
# Examples
```julia-repl
julia> hma(rand(1000), 303)
1000-element Vector{Float64}}:
[...]
```
"""
@inline function hma(x::AbstractVector{<:T}, n::Integer) where T<:Real
if !isodd(n)
@warn "Henderson moving averages only accepts odds values for 'n';\nreturning instead the average of hma(x,"*string(n)*"-1) and hma(x,"*string(n)*"+1)"
hma1 = hma(x,n-1)
hma2 = hma(x,n+1)
return (hma1 + hma2) / 2
end
@assert n >= 5 "n must be greater or equal 5"
@assert (lx = length(x)) >= n "length(s) must be greater or equal to n"
# Promotion to Float type
P = Base.promote_op(/,T,T)
x,_ = Base.promote(collect(x),[P(1.0)])
w = hmaSymmetricWeights(n,P)
m = (n-1) ÷ 2
ic = n < 13 ? P(1.0) : (13 <= n < 15 ? P(3.5) : P(4.5))
b2s2 = P(4.0)/P(pi)/ic^2
function hmai(i)
if i - 1 < m
u = hmaAsymmetricWeights(m + i, w, b2s2)[end:-1:1]
sum(x[1:i + m] .* u)
elseif i - 1 + m >= lx
u = hmaAsymmetricWeights(m + lx - i + 1, w, b2s2)
sum(x[i-m:lx] .* u)
else
sum(x[i-m:i+m] .* w)
end
end
hmav = similar(x)
for i in 1:lx
@inbounds hmav[i] = hmai(i)
end
hmav
end
"""
package: Smoothers
hmaSymmetricWeights(n,P)
Caluclate the hma symmetric weights for 'n'
# Arguments
- `n`: Number of symmetric weights
# Returns
Vector of symmetrical hma weights with type related to the bit size of `n`
# Refenrences
- "A Guide to Interpreting Time Series" ABS (2003), page 41.
"""
@inline function hmaSymmetricWeights(n::Integer,P::DataType)
m = (P(n)-1)÷2
m1 = (m+1)^2
m2 = (m+2)^2
m3 = (m+3)^2
logd = log(m+2)+log(m2-1)+log(4*m2-1)+log(4*m2-9)+log(4*m2-25)
d = 315/(8*exp(logd))
w = Vector{P}(undef,Int(m)+2)
for (i,v) in enumerate(0:m+1)
@inbounds w[i] = real(exp(log(m1-v^2)+log(m2-v^2)+log(m3-v^2)+
log(complex(P(3.0)*m2-P(11.0)*v^2-P(16.0)))+log(d)))
end
u = vcat(w[end-1:-1:1],w[2:end-1])
return mod(n, 2) != 0 ? u : vcat(u, missing)
end
"""
package: Smoothers
hmaAsymmetricWeights(m,w)
Calculate the hma asymmetric end-weights for 'm' given 'w'
# Arguments
- `m`: Number of asymmetric weights (m < length(w))
- `w`: Vector of symmetrical hma weights
# Returns
Vector of asymmetrical hma weights
# References
- Mike Doherty (2001), "The Surrogate Henderson Filters in X-11",Aust, NZ J of Stat. 43(4), 2001, 385–392
"""
@inline function hmaAsymmetricWeights(m::Integer, w::AbstractVector{<:T}, b2s2::T) where T<:Real
n = length(w)
# @assert m <= n "The m argument must be less than w"
# @assert m >= (n-1)÷2 "The m argument must be greater than (n-1)/2"
sumResidual = sum(w[range(m + 1, n, step = 1)]) / T(m)
sumEnd = T(0.0)
m12 = (m+T(1.0))/T(2.0)
for i in m+1:n
@inbounds sumEnd += (i-m12)*w[i]
end
denominator = T(1.0) + ((m*(m-T(1.0))*(m+T(1.0)) / T(12.0) ) * b2s2)
aw = Vector{T}(undef,m)
for r in 1:m
numerator = (T(r) - (m+T(1.0)) / T(2.0)) * b2s2
@inbounds aw[r] = w[r] + sumResidual + numerator / denominator * sumEnd
end
aw
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 5895 | """
Package: Forecast
loess(xv, yv;
d = 0,
q = 3*sum((!ismissing).(yv))÷4,
rho = fill(1.0,length(yv)),
exact = [], extra = [])
loess(yv;
d = 0,
q = 3*sum((!ismissing).(yv))÷4,
rho = fill(1.0,length(yv)),
exact = [], extra = [])
Return a funcion to smooth a vector of observations using locally weighted regressions.
Although loess can be used to smooth observations for any given number of independent variables, this implementation is univariate. The speed of loess can be greatly increased by using fast aproximations for the linear fitting calculations, however this implementation calculates allows as well for exact results.
The loess functionality and nomenclature follows the descriptions in:
"STL: A Seasonal, Trend Decomposition Procedure Based on Loess"
Robert B. Cleveland, William S. Cleveland, Jean E. McRae, and Irma Terpenning.
Journal of Official Statistics Vol. 6. No. 1, 1990, pp. 3-73 (c) Statistics Sweden.
# Arguments
- `xv`: Observations' support, if not provided 1:length(yv) is used instead.
- `yv`: Observation values.
- `d`: Degree of the linear fit, it accepts values 0, 1 or 2, if 0 an estimation of `d` is calculated.
- `q`: As q increases loess becomes smoother, when q tends to infinity loess tends to an ordinary least square poynomial fit of degree `d`. It defaults to the rounding of 3/4 of xv's non-missing values length.
- `rho`: Weights expressing the reliability of the observations (e.g. if yi had variances σ^2*ki where ki where known, the rhoi could be 1/ki). It defaults to 1.
- `exact`: Vector containing support values where exact loess will be calculated, the least values the faster will be loess. It defaults to an emtpy array. For series of 10 values or less exact loess is guaranteed.
- `extra`: Vector containing support values where, besideds those values chosen by the heuristic, exact loess will be calculated.
# Returns
A function returning the exact loess for the values contained in `exact` and either exact loess or fast approximations for the rest.
# Examples
```julia-repl
n = 1000
x = sort(rand(n)*2*pi);
y = sin.(x) + randn(n);
f = Smoothers.loess(x,y)
isapprox(f(pi),0;atol=0.1) #true
[...]
```
"""
loess
function loess(yv::AbstractVector{<:Union{Missing,T}};
d::Integer=0, # 0 -> auto
q::Integer=3*length(yv)÷4,
rho::AbstractVector{<:Union{Missing,T}}=fill(T(1),length(yv)),
exact::AbstractVector{T}=T[],
extra::AbstractVector{T}=T[]) where {T<:Real,S<:Real}
loess(T(1):length(yv),yv;d,q,rho,exact,extra)
end
function loess(xv::AbstractVector{R},
yv::AbstractVector{<:Union{Missing,T}};
d::Integer=0,
q::Integer=3*length(yv)÷4,
rho::AbstractVector{<:Union{Missing,T}}=fill(T(1.0),length(xv)),
exact::AbstractVector{R}=R[],
extra::AbstractVector{R}=R[]) where {R<:Real,T<:Real}
@assert issorted(xv) "xv values must be sorted"
@assert d in 0:2 "Linear Regression must be of degree 1 or 2 or 0 (auto)"
@assert length(xv) == length(yv) "xv and yv must have the same length"
# Removing missing values
myi = findall(x -> !ismissing(x),yv)
@assert length(myi) > 0 "at least one yv value must be non missing"
q = Int(floor(q*length(myi)/length(yv)))
xv = xv[myi]
yv = Vector{T}(yv[myi])
rho = rho[myi]
length(xv) == 1 && return x -> repeat([yv[1]],length(x))
length(xv) == 2 && begin d=(yv[2]-yv[1])/(xv[2]-xv[1]); return x -> @. d*x+(yv[1]-d*xv[1]) end
# Promote to same Float type
xv,yv,rho,exact,extra,_ = Base.promote(xv,yv,rho,collect(exact),collect(extra),
[Base.promote_op(/,T,T)(1.0)])
## Ax = b prediction
P = eltype(xv)
A = hcat(xv,fill(P(1.0),length(xv)))
b = yv
## Order Estimation
d = (d == 0) ? min(khat(yv),2) : d # loess accepts 1 or 2
d == 2 && (A = hcat(xv .^ 2, A))
# Select collection
predictx = exact
if isempty(exact)
N = length(xv)
n = 2*sr(N)*N÷q
m,M = extrema(xv)
gap = P((M-m)/n)
#exact = vcat(exact, xv[Int64.(round.(LinRange(1,length(xv),20)))])
predict = sort(unique(vcat(collect(m:gap:M),M,extra)))
predictx = vcat(m-P(10.0)*gap,m-gap,
predict,
M+gap,M+P(10.0)*gap)
else
@assert length(exact) > d "length(exact) should be greater than d"
end
# Predict collection
res = similar(predictx)
for (i,xi) in enumerate(predictx)
res[i] = ghat(xi;A,b,d,q,rho)
end
Spline1D(predictx, res; k=d, bc="extrapolate",s=0)
end
# loess estimation
function ghat(x::T;
A::AbstractMatrix{T},
b::AbstractVector{T},
d::Integer,
q::Integer,
rho::AbstractVector{T}) where T<:Real
xv = A[:,d]
yv = b
## λ_q
n = length(xv)
xvx = @. abs(xv-x)
qidx = sortperm(xvx)[1:min(q,n)]
qdist = abs(xv[last(qidx)]-x)*max(T(1),q/n)
## upsilon
w = zeros(n)
for wi in qidx
aq = abs(xv[wi]-x)/qdist
w[wi] = max((1-aq^3)^3,T(0))
end
A = @. A*(w*rho)
b = @. b*(w*rho)
lsq_x = A\b
d == 1 ? sum([x,T(1)].*lsq_x) : sum([x^2,x,T(1)].*lsq_x)
end
#Sturges' Rule
sr(n) = Int(round(1+3.322*log(n)))
# absolute standard deviation
function astd(x::AbstractVector{<:Real})
n = length(x)
sum(abs.(x.-sum(x)/n))/n
end
# k order estimation for Splines
function khat(y)
dy = diff(y); ady = astd(dy)
ady < 1e-10 && return 1
mi = 1
for i in 1:3
dy = diff(dy)
nady = astd(dy); nady < 1e-10 && break
mi += (ady > nady) ? 1 : break
ady = nady
end
mi+1
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 971 | """
Package: Smoothers
sma(x, n, center=false)
Smooth a vector of data using a simple moving average
# Arguments
- `x`: Vector of data.
- `n`: Size of the moving average.
- `center`: returns a vector of the same size of x with missing values on the tails.
# Returns
Vector of moving average values
# Examples
```julia-repl
julia> sma(1:5,3)
3-element Vector{Float64}:
2.0
3.0
4.0
julia> sma(1:5,3,true)
5-element Vector{Union{Missing, Float64}}:
missing
2.0
3.0
4.0
missing
```
"""
@inline function sma(x::AbstractVector{T}, n::Integer, center::Bool=false) where T<:Real
n == 1 && return x
N = length(x)
@assert 1 <= n <= N
V = Base.promote_op(/, T, T)
res = Vector{V}(undef, N-n+1)
# initial moving average value
res[1] = ma = sum(x[1:n])/n
for i in 1:N-n
@inbounds res[1+i] = ma += (x[n+i] - x[i]) / T(n)
end
center ? vcat(repeat([missing], n÷2),res,repeat([missing], n-n÷2-1)) : res
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 7377 | """
Package: Smoothers
stl(Yv, np; robust=false,
nl=nextodd(np),
ns=10*length(Yv)+1,
nt=nextodd(1.5*np/(1-1.5/ns)),
ni=robust ? 1 : 2,
no=0,
spm=false,
qsmp=max(div(np,7),2),
cth = 0.01,
verbose=false)
Decompose a time series into trend, seasonal, and remainder components.
"STL has a simple design that consists of a sequence of applications of the loess smoother; the simplicity allows analysis of the properties of the procedure and allows fast computation, even for very long time series and large amounts of trend and seasonal smoothing. Other features of STL are specification of amounts of seasonal and trend smoothing that range, in a nearly continous way, from very small amount of smoothing to a very large amount; robust estimates of the trend and seasonal components that are not distorted by aberrant behavior in the data; specification of the period of the seasonal component to any intenger multiple of the time sampling interval greater than one; and the ability to decompose time series with missing values."*
All default values are chosen following the recommendations of the original paper when those were recommended. `ns` is recommended to be chosen of the basis of knowledge of the time series and on the basis of diagnostic methods; it must nonethelessbe always odd and at least 7.
for `no` the authors advise 5 ("safe value") or 10 ("near certainty of convergence") cycles or a convergence criterion when robustness is required, in this case when `robust` is true computations stop when convergence is achieved in trend and seasonality.
for `qsmp` the authors do not advise a default but they use a value close to div(`np`,7).
* STL: A Seasonal, Trend Decomposition Procedure Based on Loess" Robert B. Cleveland, William S. Cleveland, Jean E. McRae, and Irma Terpenning. Journal of Official Statistics Vol. 6. No. 1, 1990, pp. 3-73 (c) Statistics Sweden.
# Arguments
- `Yv`: Time series.
- `np`: Seasonality.
- `robust`: Robust stl.
- `nl`: Smoothing parameter of the low-pass filter.
- `ns`: Smoothing parameter for the seasonal component.
- `nt`: Smoothing parameter for the trend decomposition.
- `ni`: Number of inner loop cycles.
- `no`: Number of outer loop cycles.
- `spm`: Seasonal post-smoothing.
- `qsmp`: Loess q window for Seasonal post-smoothing.
- `cth`: Corvengence threshold for Seasonal and Trend.
- `verbose`: If true shows updates for the Seasonal and Trend convergence.
# Returns
A three columns matrix with the Seasonal, Trend and Remainder values for Yv.
# Examples
```julia-repl
x = stl(rand(100),10)
100×3 Matrix{Float64}:
0.0659717 0.512964 -0.3029
-0.0822641 0.502129 0.0710054
0.217383 0.491153 0.145449
[...]
```
"""
function stl(Yv::AbstractVector{<:Union{Missing,T}},
np::Integer;
robust=true,
nl=nextodd(np),
ns=7,
nt=nextodd(1.5*np/(1-1.5/ns)),
ni=robust ? 1 : 2,
no=0,
spm=true,
qsmp=max(div(np,7),2),
cth = 0.01,
verbose=false) where {T<:Real}
@assert mod(ns,2)==1 & (ns>=7) "`ns` is chosen on the knowledge of the time series and diagnostic methods; must always be odd and at least 7"
function B(u)
(u < 1) & !ismissing(u) ? (1.0-u^2)^2 : 0.0
end
N = length(Yv)
# initial robustness weights
rhov = ones(T,N)
# intial trend
Tv = Tv0 = zeros(T,N)
Sv = Sv0 = zeros(Union{Missing,T},N)
Rv = Vector{T}(undef,N)
Cv = Vector{T}(undef,N+2*np)
scnv = false # seasonal convergence flag
tcnv = false # trend convergence flag
#for o in 0:no
o = 0
while robust | (o <= no)
for k in 1:ni
# Updating sesonal and trend components
## 1. Detrending (Yv = Tv + Sv)
Sv = Yv - Tv
### Seasonal convergence criterion
Md = maximum(abs.(skipmissing(Sv-Sv0)))
M0 = maximum(skipmissing(Sv0))
m0 = minimum(skipmissing(Sv0))
scnv = (Md/(M0-m0) < cth)
if verbose
println("Outer loop: " * string(o) * " - " * "Inner loop: " * string(k))
println("Seasonal Convergence: " * string(Md/(M0-m0)))
end
Sv0 = Sv
# Seasonal Smoothing 2,3,4
## 2. Cycle-subseries Smoothing
for csi in 1:np
srange = csi:np:N
floess = loess(srange,Sv[srange];q=ns,d=1,rho=rhov[srange])
Cv[csi:np:N+2*np] = floess(csi-np:np:N+np)
end
## 3. Low-Pass Filtering of Smoothed Cycle-Subseries
### centered support instead 1:N to balance out machine error
floess = loess((1:N).-N÷2,sma(sma(sma(Cv,np),np),3),d=1,q=nl,rho=rhov)
Lv = floess((1:N).-N÷2)
## 4. Detreending of Smoothed Cycle-Subseries
### Lv is substracted to prevent low-frenquency power
### from entering the seasonal component.
Sv = Cv[np+1:end-np] - Lv
## 5. Deseasonalizing
Dv = Yv - Sv
# Trend Smoothing
## 6. Trend Smoothing
### centered support instead 1:N to balance out machine error
### (floor isntead ceil like in Lv to balance out even lengths)
floess = loess((1:N).-N÷2,Dv,q=nt,d=1,rho=rhov)
Tv = floess((1:N).-N÷2)
### Trend convergence criterion
Md = maximum(abs.(skipmissing(Tv-Tv0)))
M0 = maximum(skipmissing(Tv0))
m0 = minimum(skipmissing(Tv0))
tcnv = (Md/(M0-m0) < cth)
if verbose
println("Trend Convergence: " * string(Md/(M0-m0)) * "\n")
end
Tv0 = Tv
scnv & tcnv ? break : nothing
end
# Computation of robustness weights
## These new weights will reduce the influence of transient behaviour
## on the trend and seasonal components.
# Tv and Sv defined everywhere but Rv is not defined
# where Yv has missing values
Rv = Yv - Tv - Sv
if scnv & tcnv
@info "Corvengence achieved (< " * string(cth) * "); Stopping computation..."
break
end
if 0 < o <= no
smRv = skipmissing(Rv)
h = 6*median(abs.(smRv))
rhov = B.(abs.(Rv)/h)
end
o += 1
end
if spm
# Using div(np,7) as default to approximate
# the q=51 for a np=365 chosen in the original paper
floess = loess((1:N).-N÷2,Sv; d=2, q=qsmp, exact = (1:N).-N÷2)
Sv = floess((1:N).-N÷2)
Rv = Yv - Tv - Sv
end
if !scnv
@warn "Seasonal convergence not achieved (>= " * string(cth) * ")
Consider a robust estimation"
end
if !tcnv
@warn "Trend convergence not achieved (>= " * string(cth) * ")
Consider a robust estimation"
end
[Sv Tv Rv]
end
"""
Package: Smoothers
nextodd(x)
Return the smallest odd integer greater than or equal to `x`.
"""
function nextodd(x::Real)::Integer
cx = Integer(ceil(x))
mod(cx,2) == 0 ? cx+1 : cx
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 798 | using Test
using Smoothers
import Smoothers: filter
@testset "filter" begin
# Moving Average Filter
w = 3;
b = ones(w)/w;
a = [1];
x = [1,2,3,4,5];
# Types' promotion
fx = filter(Float16.(b),Float16.(a),Float16.(x));
@test eltype(fx) == Float16
fx = filter(Float32.(b),Float32.(a),Float32.(x));
@test eltype(fx) == Float32
fx = filter(BigFloat.(b),BigFloat.(a),BigFloat.(x));
@test eltype(fx) == BigFloat
fx = filter(Float16.(b),Int32.(a),Float64.(x))
@test eltype(fx) == Float64
# Standard
fx = filter(b,a,x)
@test eltype(fx) == Float64
@test fx[1:2] ≈ [1/3,1]
@test fx[3:5] ≈ sma(x,3)
# Initial State
si = [1/3,1]
fx = filter(b,a,x,si)
@test fx[1:2] ≈ [2/3,2]
@test fx[3:5] ≈ sma(x,3)
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 1074 | using Test
using Smoothers
import Smoothers: hmaSymmetricWeights
@testset "hma" begin
# Types' promotion
fx = hma(Float32.(1:10),7);
@test eltype(fx) == Float32
fx = hma(Float64.(1:10),7);
@test eltype(fx) == Float64
fx = hma(BigFloat.(1:10),7);
@test eltype(fx) == BigFloat
fx = hma(1:10,7);
@test eltype(fx) == Float64
# weights
w = hmaSymmetricWeights(8,Float64)
@test ismissing(w[end])
w = hmaSymmetricWeights(7,Float64)
@test sum(w) ≈ 1.0
w = hmaSymmetricWeights(13,Float64)
@test sum(w) ≈ 1.0
# (https://www.mathworks.com/help/econ/seasonal-adjustment-using-snxd7m-seasonal-filters.html)
@test length(w) == 13
@test round.(w,digits=3) == [-0.019, -0.028, 0.0, 0.065, 0.147, 0.214, 0.24,
0.214, 0.147, 0.065, 0.0, -0.028, -0.019]
# 13-term moving average
x = hma(sin.(1:100), 13)
@test length(x) == 100
@test first(x) ≈ 0.5636212576875559
@test last(x) ≈ -0.6658500507547161
@test x[50] ≈ -0.043655947941143455
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 1019 | using Test
using Smoothers
@testset "loess" begin
# AssertionsErrors
@test_throws AssertionError loess(rand(5),rand(5); d=3)
# Standard
fx = loess(sort(rand(10)),rand(10))
x = fx(rand(20));
@test length(x) == 20
fx = loess(sort(rand(10)), rand(10); d=1)
x = fx(rand(20));
@test length(x) == 20
xv = sort(sin.(collect(1:5.)))
fx = loess(xv,sin.(collect(1:5.)); d=2)
x = fx(xv);
@test isapprox(x,[0.8414709848078966, 0.9095525828909523, 0.1420295878550277, -0.7350481509902661, -0.9589242746631387]; atol=.1)
xv = sort(sin.(collect(1:5.)))
fx = loess(xv,sin.(collect(1:5.)); d=1)
x = fx(xv);
@test isapprox(x,[0.8414709848078965, 0.9092974268256818, 0.14112000805986713, -0.7568024953079286, -0.9589242746631383]; atol=.1)
fx = loess(1:100,rand(1:100,100))
x = fx(Int64.(round.(100*rand(20))));
@test length(x) == 20
fx = loess(1:2:200, vcat(rand(80),repeat([missing],20)))
x = fx(1.:2:40)
@test length(x) == 20
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 411 | using Smoothers
using Test
using Random
using Logging
const tests = [
"filter",
"hma",
"loess",
"sma",
"stl",
]
printstyled("\nTest Summary List:\n", color=:underline)
Random.seed!(36)
Base.disable_logging(Base.CoreLogging.Error) # disable warnings
for t in tests
@testset "Test $t" begin
Random.seed!(36)
include("$t.jl")
println()
end
end
println()
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 398 | using Test
using Smoothers
@testset "sma" begin
@test_throws AssertionError sma(1:5,10)
x = sma(1:5,3)
@test length(x) == 3
@test x == [2.0, 3.0, 4.0]
x = sma(1:5,3,true)
@test length(x) == 5
@test ismissing.(x) == Bool[1,0,0,0,1]
@test x[2:4] == [2.0, 3.0, 4.0]
x = sma(1:5,3,false)
@test length(x) == 3
@test x == [2.0, 3.0, 4.0]
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | code | 198 | using Test
using Smoothers
@testset "stl" begin
@test_throws AssertionError stl(rand(100),10; ns=5)
x = stl(rand(100),10)
@test x isa Matrix
@test size(x) == (100,3)
end
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.1.3 | fab44b0ca72bc5e44606fa37762850e6952b3a3a | docs | 2197 | # Smoothers
The package Smoothers provides a collection of smoothing heuristics, models and smoothing related applications. The current available smoothers and applications are:
* Henderson Moving Average Filter (**hma**)
* Linear Time-invariant Difference Equation Filter — Matlab/Octave (**filter**)
* Locally Estimated Scatterplot Smoothing (**loess**)
* Seasonal and Trend decomposition based on Loess (**stl**)
* Simple Moving Average (**sma**)
<img src="./docs/src/images/smoothers.png">
## Quick Examples
```julia
using Smoothers, Plots
t = Array(LinRange(-pi,pi,100));
x = sin.(t) .+ 0.25*rand(length(t));
# Data
w = 21; sw = string(w)
plot(t,x,label="sin(t)+ϵ",linewidth=10,alpha=.3,
xlabel = "t", ylabel = "x",
title="Smoothers",legend=:bottomright)
# Henderson Moving Average Filter
plot!(t,hma(x,w), label ="hma(x,"*sw*")")
# Locally Estimated Scatterplot Smoothing
plot!(t,loess(t,x;q=w)(t), label ="loess(t,x;q="*sw*")(t)")
# Moving Average Filter with Matlab/Octave 'filter'
b = ones(w)/w; a = [1];
plot!(t,filter(b,a,x), label ="filter(1,[1/"*sw*",...],x)")
# Simple Moving Average
plot!(t, sma(x,w,true), label = "sma(x,"*sw*",true)")
```
<img src="./docs/src/images/smoothers_examples.png">
## References
* [Cleveland et al. 1990] Cleveland, R. B.; Cleveland, W. S.;McRae, J. E.; and Terpenning, I. 1990. STL: A seasonal-trend decomposition procedure based on loess. Journal of Official Statistics 6(1):3–73.
* Henderson, R. (1916). Note on graduation by adjusted average. Transactions of the Actuarial Society of America, 17:43-48. [Australian Bureau of Statistics: What Are Henderson Moving Averages?](https://www.abs.gov.au/websitedbs/d3310114.nsf/4a256353001af3ed4b2562bb00121564/5fc845406def2c3dca256ce100188f8e!OpenDocument#:~:text=WHAT%20ARE%20HENDERSON%20MOVING%20AVERAGES%3F)
* Octave Forge: [filter function](https://octave.sourceforge.io/octave/function/filter.html)
[](https://github.com/viraltux/Smoothers.jl/actions)
[](https://codecov.io/gh/viraltux/Smoothers.jl)
| Smoothers | https://github.com/viraltux/Smoothers.jl.git |
|
[
"MIT"
] | 0.2.0 | 48e5cfba99403037e35a4ca9eb6c56aaea9c8a12 | code | 3631 | using BinDeps
using Compat
@BinDeps.setup
libnames = ["libCLBlast", "libclblast", "clblast"]
libCLBlast = library_dependency("libCLBlast", aliases = libnames)
version = "1.4.1"
if Compat.Sys.iswindows()
if Sys.ARCH == :x86_64
uri = URI("https://github.com/CNugteren/CLBlast/releases/download/" *
version * "/CLBlast-" * version * "-Windows-x64.zip")
basedir = @__DIR__
provides(
Binaries, uri,
libCLBlast, unpacked_dir = ".",
installed_libpath = joinpath(basedir, "libCLBlast", "lib"), os = :Windows
)
else
error("Only 64 bit windows supported with automatic build.")
end
end
if Compat.Sys.islinux()
#=if Sys.ARCH == :x86_64
name, ext = splitext(splitext(basename(baseurl * "Linux-x64.tar.gz"))[1])
uri = URI(baseurl * "Linux-x64.tar.gz")
basedir = joinpath(@__DIR__, name)
provides(
Binaries, uri,
libCLBlast, unpacked_dir = basedir,
installed_libpath = joinpath(basedir, "lib"), os = :Linux
)
else
error("Only 64 bit linux supported with automatic build.")
end=#
provides(Sources, URI("https://github.com/CNugteren/CLBlast/archive/" * version * ".tar.gz"),
libCLBlast, unpacked_dir="CLBlast-" * version)
builddir = joinpath(@__DIR__, "src", "CLBlast-" * version, "build")
libpath = joinpath(builddir, "libclblast.so")
provides(BuildProcess,
(@build_steps begin
GetSources(libCLBlast)
CreateDirectory(builddir)
FileRule(libpath, @build_steps begin
ChangeDirectory(builddir)
`cmake -DSAMPLES=OFF -DTESTS=OFF -DTUNERS=OFF -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ ..`
`make -j 4`
end)
end),
libCLBlast, installed_libpath=libpath, os=:Linux)
end
if Compat.Sys.isapple()
using Homebrew
provides(Homebrew.HB, "homebrew/core/clblast", libCLBlast, os = :Darwin)
end
if Compat.Sys.islinux()
# BinDeps.jl seems to be broken, cf. https://github.com/JuliaLang/BinDeps.jl/issues/172
wd = pwd()
sourcedir = joinpath(@__DIR__, "CLBlast-" * version)
builddir = joinpath(sourcedir, "build")
libpath = joinpath(builddir, "libclblast.so")
if !isdir(sourcedir)
url = "https://github.com/CNugteren/CLBlast/archive/" * version * ".tar.gz"
download_finished = false
try
run(pipeline(`wget -q -O - $url`, `tar xzf -`))
global download_finished = true
catch e
println(e)
end
if download_finished == false
try
run(pipeline(`curl -L $url`, `tar xzf -`))
global download_finished = true
catch e
println(e)
end
end
end
isdir(builddir) || mkdir(builddir)
cd(builddir)
run(`cmake -DSAMPLES=OFF -DTESTS=OFF -DTUNERS=OFF -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ ..`)
run(`make -j 4`)
cd(wd)
open(joinpath(@__DIR__, "deps.jl"), "w") do file
write(file,
"""
if VERSION >= v"0.7.0-DEV.3382"
using Libdl
end
# Macro to load a library
macro checked_lib(libname, path)
if Libdl.dlopen_e(path) == C_NULL
error("Unable to load \n\n\$libname (\$path)\n\nPlease ",
"re-run Pkg.build(CLBlast), and restart Julia.")
end
quote
const \$(esc(libname)) = \$path
end
end
# Load dependencies
@checked_lib libCLBlast "$libpath"
""")
end
else
@BinDeps.install Dict(:libCLBlast => :libCLBlast)
end
| CLBlast | https://github.com/JuliaGPU/CLBlast.jl.git |
|
[
"MIT"
] | 0.2.0 | 48e5cfba99403037e35a4ca9eb6c56aaea9c8a12 | code | 1830 | using OpenCL, CLBLAS, CLBlast, BenchmarkTools
@static if VERSION < v"0.7-"
LA = Base.LinAlg
else
using LinearAlgebra, Random, Printf
LA = LinearAlgebra
end
CLBLAS.setup()
function run_gbmv(m::Integer, n::Integer, kl::Integer, ku::Integer, T=Float32)
srand(12345)
A = rand(T, kl+ku+1, n)
y = rand(T, m)
x = rand(T, n)
α = rand(T)
β = rand(T)
@printf("\nm = %d, n = %d, kl = %d, ku = %d, eltype = %s\n", m, n, kl, ku, T)
println("BLAS:")
y_true = copy(y)
LinAlg.BLAS.gbmv!('N', m, kl, ku, α, A, x, β, y_true)
yy = copy(y)
display(@benchmark LinAlg.BLAS.gbmv!($('N'), $m, $kl, $ku, $α, $A, $x, $β, $yy))
println()
for device in cl.devices()
println("-"^70)
@printf("Platform name : %s\n", device[:platform][:name])
@printf("Platform version: %s\n", device[:platform][:version])
@printf("Device name : %s\n", device[:name])
@printf("Device type : %s\n", device[:device_type])
println()
ctx = cl.Context(device)
queue = cl.CmdQueue(ctx)
println("CLBLAS:")
A_cl = cl.CLArray(queue, A)
y_cl = cl.CLArray(queue, y)
x_cl = cl.CLArray(queue, x)
CLBLAS.gbmv!('N', m, kl, ku, α, A_cl, x_cl, β, y_cl)
@assert cl.to_host(y_cl) ≈ y_true
display(@benchmark CLBLAS.gbmv!($('N'), $m, $kl, $ku, $α, $A_cl, $x_cl, $β, $y_cl))
println()
println("CLBlast:")
A_cl = cl.CLArray(queue, A)
y_cl = cl.CLArray(queue, y)
x_cl = cl.CLArray(queue, x)
CLBlast.gbmv!('N', m, kl, ku, α, A_cl, x_cl, β, y_cl)
@assert cl.to_host(y_cl) ≈ y_true
display(@benchmark CLBlast.gbmv!($('N'), $m, $kl, $ku, $α, $A_cl, $x_cl, $β, $y_cl))
println()
end
end
run_gbmv(2^10, 2^10, 5, 5, Float32)
| CLBlast | https://github.com/JuliaGPU/CLBlast.jl.git |
|
[
"MIT"
] | 0.2.0 | 48e5cfba99403037e35a4ca9eb6c56aaea9c8a12 | code | 1476 | using OpenCL, CLBLAS, CLBlast, BenchmarkTools
@static if VERSION < v"0.7-"
LA = Base.LinAlg
else
using LinearAlgebra, Random, Printf
LA = LinearAlgebra
end
CLBLAS.setup()
function run_dot(n::Integer, T=Float32::Union{Type{Float32},Type{Float64}})
srand(12345)
y = rand(T, n)
x = rand(T, n)
@printf("\nn = %d, eltype = %s\n", n, T)
println("BLAS:")
res_true = LinAlg.BLAS.dot(n, x, 1, y, 1)
display(@benchmark LinAlg.BLAS.dot($n, $x, $1, $y, $1))
println()
for device in cl.devices()
println("-"^70)
@printf("Platform name : %s\n", device[:platform][:name])
@printf("Platform version: %s\n", device[:platform][:version])
@printf("Device name : %s\n", device[:name])
@printf("Device type : %s\n", device[:device_type])
println()
ctx = cl.Context(device)
queue = cl.CmdQueue(ctx)
println("CLBLAS:")
y_cl = cl.CLArray(queue, y)
x_cl = cl.CLArray(queue, x)
res_cl = CLBLAS.dot(n, x_cl, 1, y_cl, 1)
@assert res_cl ≈ res_true
display(@benchmark CLBLAS.dot($n, $x_cl, $1, $y_cl, $1))
println()
println("CLBlast:")
y_cl = cl.CLArray(queue, y)
x_cl = cl.CLArray(queue, x)
res_cl = CLBlast.dot(n, x_cl, 1, y_cl, 1)
@assert res_cl ≈ res_true
display(@benchmark CLBlast.dot($n, $x_cl, $1, $y_cl, $1))
println()
end
end
run_dot(2^16, Float32)
| CLBlast | https://github.com/JuliaGPU/CLBlast.jl.git |
|
[
"MIT"
] | 0.2.0 | 48e5cfba99403037e35a4ca9eb6c56aaea9c8a12 | code | 1331 | using OpenCL, CLBLAS, CLBlast, BenchmarkTools
@static if VERSION < v"0.7-"
LA = Base.LinAlg
else
using LinearAlgebra, Random, Printf
LA = LinearAlgebra
end
CLBLAS.setup()
function run_nrm2(n::Integer, T=Float32::Union{Type{Float32},Type{Float64}})
srand(12345)
x = rand(T, n)
@printf("\nn = %d, eltype = %s\n", n, T)
println("BLAS:")
res_true = LA.BLAS.nrm2(n, x, 1)
display(@benchmark LA.BLAS.nrm2($n, $x, $1))
println()
for device in cl.devices()
println("-"^70)
@printf("Platform name : %s\n", device[:platform][:name])
@printf("Platform version: %s\n", device[:platform][:version])
@printf("Device name : %s\n", device[:name])
@printf("Device type : %s\n", device[:device_type])
println()
ctx = cl.Context(device)
queue = cl.CmdQueue(ctx)
println("CLBLAS:")
x_cl = cl.CLArray(queue, x)
res_cl = CLBLAS.nrm2(n, x_cl, 1)
@assert res_cl ≈ res_true
display(@benchmark CLBLAS.nrm2($n, $x_cl, $1))
println()
println("CLBlast:")
x_cl = cl.CLArray(queue, x)
res_cl = CLBlast.nrm2(n, x_cl, 1)
@assert res_cl ≈ res_true
display(@benchmark CLBlast.nrm2($n, $x_cl, $1))
println()
end
end
run_nrm2(2^16, Float32)
| CLBlast | https://github.com/JuliaGPU/CLBlast.jl.git |
|
[
"MIT"
] | 0.2.0 | 48e5cfba99403037e35a4ca9eb6c56aaea9c8a12 | code | 1766 | using OpenCL, CLBLAS, CLBlast, BenchmarkTools
@static if VERSION < v"0.7-"
LA = Base.LinAlg
else
using LinearAlgebra, Random, Printf
LA = LinearAlgebra
end
CLBLAS.setup()
function run_gemm(m::Integer, n::Integer, k::Integer, T=Float32)
srand(12345)
A = rand(T, m, k)
B = rand(T, k, n)
C = rand(T, m, n)
α = rand(T)
β = rand(T)
@printf("\nm = %d, n = %d, k = %d, eltype = %s\n", m, n, k, T)
println("BLAS:")
C_true = copy(C)
LinAlg.BLAS.gemm!('N', 'N', α, A, B, β, C_true)
CC = copy(C)
display(@benchmark LinAlg.BLAS.gemm!($('N'), $('N'), $α, $A, $B, $β, $CC))
println()
for device in cl.devices()
println("-"^70)
@printf("Platform name : %s\n", device[:platform][:name])
@printf("Platform version: %s\n", device[:platform][:version])
@printf("Device name : %s\n", device[:name])
@printf("Device type : %s\n", device[:device_type])
println()
ctx = cl.Context(device)
queue = cl.CmdQueue(ctx)
println("CLBLAS:")
A_cl = cl.CLArray(queue, A)
B_cl = cl.CLArray(queue, B)
C_cl = cl.CLArray(queue, C)
CLBLAS.gemm!('N', 'N', α, A_cl, B_cl, β, C_cl)
@assert cl.to_host(C_cl) ≈ C_true
display(@benchmark CLBLAS.gemm!($('N'), $('N'), $α, $A_cl, $B_cl, $β, $C_cl))
println()
println("CLBlast:")
A_cl = cl.CLArray(queue, A)
B_cl = cl.CLArray(queue, B)
C_cl = cl.CLArray(queue, C)
CLBlast.gemm!('N', 'N', α, A_cl, B_cl, β, C_cl)
@assert cl.to_host(C_cl) ≈ C_true
display(@benchmark CLBlast.gemm!($('N'), $('N'), $α, $A_cl, $B_cl, $β, $C_cl))
println()
end
end
run_gemm(2^10, 2^10, 2^10, Float32)
| CLBlast | https://github.com/JuliaGPU/CLBlast.jl.git |
|
[
"MIT"
] | 0.2.0 | 48e5cfba99403037e35a4ca9eb6c56aaea9c8a12 | code | 1691 | using OpenCL, CLBLAS, CLBlast, BenchmarkTools
@static if VERSION < v"0.7-"
LA = Base.LinAlg
else
using LinearAlgebra, Random, Printf
LA = LinearAlgebra
end
CLBLAS.setup()
function run_gemv(m::Integer, n::Integer, T=Float32)
srand(12345)
A = rand(T, m, n)
y = rand(T, m)
x = rand(T, n)
α = rand(T)
β = rand(T)
@printf("\nm = %d, n = %d, eltype = %s\n", m, n, T)
println("BLAS:")
y_true = copy(y)
LinAlg.BLAS.gemv!('N', α, A, x, β, y_true)
yy = copy(y)
display(@benchmark LinAlg.BLAS.gemv!($('N'), $α, $A, $x, $β, $yy))
println()
for device in cl.devices()
println("-"^70)
@printf("Platform name : %s\n", device[:platform][:name])
@printf("Platform version: %s\n", device[:platform][:version])
@printf("Device name : %s\n", device[:name])
@printf("Device type : %s\n", device[:device_type])
println()
ctx = cl.Context(device)
queue = cl.CmdQueue(ctx)
println("CLBLAS:")
A_cl = cl.CLArray(queue, A)
y_cl = cl.CLArray(queue, y)
x_cl = cl.CLArray(queue, x)
CLBLAS.gemv!('N', α, A_cl, x_cl, β, y_cl)
@assert cl.to_host(y_cl) ≈ y_true
display(@benchmark CLBLAS.gemv!($('N'), $α, $A_cl, $x_cl, $β, $y_cl))
println()
println("CLBlast:")
A_cl = cl.CLArray(queue, A)
y_cl = cl.CLArray(queue, y)
x_cl = cl.CLArray(queue, x)
CLBlast.gemv!('N', α, A_cl, x_cl, β, y_cl)
@assert cl.to_host(y_cl) ≈ y_true
display(@benchmark CLBlast.gemv!($('N'), $α, $A_cl, $x_cl, $β, $y_cl))
println()
end
end
run_gemv(2^10, 2^10, Float32)
| CLBlast | https://github.com/JuliaGPU/CLBlast.jl.git |
|
[
"MIT"
] | 0.2.0 | 48e5cfba99403037e35a4ca9eb6c56aaea9c8a12 | code | 1459 | using OpenCL, CLBLAS, CLBlast, BenchmarkTools
@static if VERSION < v"0.7-"
LA = Base.LinAlg
else
using LinearAlgebra, Random, Printf
LA = LinearAlgebra
end
CLBLAS.setup()
function run_axpy(n::Integer, T=Float32)
srand(12345)
y = rand(T, n)
x = rand(T, n)
α = rand(T)
@printf("\nn = %d, eltype = %s\n", n, T)
println("BLAS:")
y_true = copy(y)
LinAlg.BLAS.axpy!(α, x, y_true)
yy = copy(y)
display(@benchmark LinAlg.BLAS.axpy!($α, $x, $yy))
println()
for device in cl.devices()
println("-"^70)
@printf("Platform name : %s\n", device[:platform][:name])
@printf("Platform version: %s\n", device[:platform][:version])
@printf("Device name : %s\n", device[:name])
@printf("Device type : %s\n", device[:device_type])
println()
ctx = cl.Context(device)
queue = cl.CmdQueue(ctx)
println("CLBLAS:")
y_cl = cl.CLArray(queue, y)
x_cl = cl.CLArray(queue, x)
CLBLAS.axpy!(α, x_cl, y_cl)
@assert cl.to_host(y_cl) ≈ y_true
display(@benchmark CLBLAS.axpy!($α, $x_cl, $y_cl))
println()
println("CLBlast:")
y_cl = cl.CLArray(queue, y)
x_cl = cl.CLArray(queue, x)
CLBlast.axpy!(α, x_cl, y_cl)
@assert cl.to_host(y_cl) ≈ y_true
display(@benchmark CLBlast.axpy!($α, $x_cl, $y_cl))
println()
end
end
run_axpy(2^10, Float32)
| CLBlast | https://github.com/JuliaGPU/CLBlast.jl.git |
|
[
"MIT"
] | 0.2.0 | 48e5cfba99403037e35a4ca9eb6c56aaea9c8a12 | code | 1413 | using OpenCL, CLBLAS, CLBlast, BenchmarkTools
@static if VERSION < v"0.7-"
LA = Base.LinAlg
else
using LinearAlgebra, Random, Printf
LA = LinearAlgebra
end
CLBLAS.setup()
function run_scal(n::Integer, T=Float32)
srand(12345)
x = rand(T, n)
α = rand(T)
@printf("\nn = %d, eltype = %s\n", n, T)
println("BLAS:")
x_true = copy(x)
LinAlg.BLAS.scal!(n, α, x_true, 1)
xx = copy(x)
display(@benchmark LinAlg.BLAS.scal!($n, $α, $xx, $1))
println()
for device in cl.devices()
println("-"^70)
@printf("Platform name : %s\n", device[:platform][:name])
@printf("Platform version: %s\n", device[:platform][:version])
@printf("Device name : %s\n", device[:name])
@printf("Device type : %s\n", device[:device_type])
println()
ctx = cl.Context(device)
queue = cl.CmdQueue(ctx)
println("CLBLAS:")
x_cl = cl.CLArray(queue, x)
CLBLAS.scal!(n, α, x_cl, 1)
@assert cl.to_host(x_cl) ≈ x_true
display(@benchmark CLBLAS.scal!($n, $α, $x_cl, $1))
println()
println("CLBlast:")
x_cl = cl.CLArray(queue, x)
CLBlast.scal!(n, α, x_cl, 1)
# or CLBlast.scal!(α, x_cl)
@assert cl.to_host(x_cl) ≈ x_true
display(@benchmark CLBlast.scal!($n, $α, $x_cl, $1))
println()
end
end
run_scal(2^10, Float32)
| CLBlast | https://github.com/JuliaGPU/CLBlast.jl.git |
|
[
"MIT"
] | 0.2.0 | 48e5cfba99403037e35a4ca9eb6c56aaea9c8a12 | code | 437 | __precompile__(true)
module CLBlast
using Compat
using OpenCL.cl
depsfile = joinpath(dirname(@__FILE__), "..", "deps", "deps.jl")
if isfile(depsfile)
include(depsfile)
else
error("CLBlast not properly installed. Please run Pkg.build(\"CLBlast\") then restart Julia.")
end
include("constants.jl")
include("error.jl")
include("auxiliary_functions.jl")
include("L1/L1.jl")
include("L2/L2.jl")
include("L3/L3.jl")
end # module
| CLBlast | https://github.com/JuliaGPU/CLBlast.jl.git |
|
[
"MIT"
] | 0.2.0 | 48e5cfba99403037e35a4ca9eb6c56aaea9c8a12 | code | 791 | """
clear_cache()
CLBlast stores binaries of compiled kernels into a cache in case the same kernel
is used later on for thesame device. This cache can be cleared to free up system
memory or it can be useful in case of debugging.
"""
@compat function clear_cache()
err = ccall((:CLBlastClearCache, libCLBlast), cl.CL_int, ())
if err != cl.CL_SUCCESS
println(stderr, "Calling function `clear_cache` failed!")
throw(cl.CLError(err))
end
return err
end
@compat function fill_cache(device::cl.Device)
err = ccall((:CLBlastFillCache, libCLBlast), cl.CL_int, (cl.CL_device_id,), pointer(device))
if err != cl.CL_SUCCESS
println(stderr, "Calling function `fill_cache($device)` failed!")
throw(cl.CLError(err))
end
return err
end
| CLBlast | https://github.com/JuliaGPU/CLBlast.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.