licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 585 | struct IfElseMeasure{B,T,F} <: AbstractMeasure
b::B
t::T
f::F
end
using MeasureBase: istrue
insupport(d::IfElseMeasure, x) = istrue(insupport(d.t, x)) || istrue(insupport(d.f, x))
function logdensity_def(d::IfElseMeasure, x)
p = mean(d.b)
logdensity_def(p * d.t + (1 - p) * d.f, x)
end
basemeasure(d::IfElseMeasure) = d.t + d.f
@inline function Base.rand(rng::AbstractRNG, ::Type{T}, m::IfElseMeasure) where {T}
c = rand(rng, T, m.b)
result = ifelse(c, m.t, m.f)
rand(rng, T, result)
end
IfElse.ifelse(b::Bernoulli, t, f) = IfElseMeasure(b, t, f)
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1003 |
using MappedArrays
# function as(d::ProductMeasure{Returns{T},F,A}) where {T,F,A<:AbstractArray}
# as(Array, as(d.f.f.value), size(d.xs))
# end
@inline function Base.rand(
rng::AbstractRNG,
::Type{T},
d::ProductMeasure{A},
) where {T,A<:AbstractArray}
mar = marginals(d)
# Distributions doens't (yet) have the three-argument form
elT = typeof(rand(rng, T, first(mar)))
sz = size(mar)
x = Array{elT,length(sz)}(undef, sz)
@inbounds @simd for j in eachindex(mar)
x[j] = rand(rng, T, mar[j])
end
x
end
# # e.g. set(Normal(μ=2)^5, params, randn(5))
# function Accessors.set(
# d::ProductMeasure{A},
# ::typeof(params),
# p::AbstractArray,
# ) where {A<:AbstractArray}
# set.(marginals(d), params, p)
# end
# function Accessors.set(
# d::ProductMeasure{A},
# ::typeof(params),
# p,
# ) where {A<:AbstractArray}
# mar = marginals(d)
# par = eltype(mar)(p)
# ProductMeasure(d.f, Fill(par, size(mar)))
# end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 3418 | using TransformVariables: AbstractTransform, CallableTransform, CallableInverse
export Pushforward
export Pullback
struct Pushforward{F,M,L} <: AbstractMeasure
f::F
μ::M
logjac::L
end
insupport(d::Pushforward, x) = insupport(d.μ, inverse(d.f)(x))
Pushforward(f, μ) = Pushforward(f, μ, True())
function Pretty.tile(pf::Pushforward{<:TV.CallableTransform})
Pretty.list_layout(Pretty.tile.([pf.f.t, pf.μ, pf.logjac]); prefix = :Pushforward)
end
function Pretty.tile(pf::Pushforward)
Pretty.list_layout(Pretty.tile.([pf.f, pf.μ, pf.logjac]); prefix = :Pushforward)
end
struct Pullback{F,M,L} <: AbstractMeasure
f::F
ν::M
logjac::L
end
Pullback(f, ν) = Pullback(f, ν, True())
insupport(d::Pullback, x) = insupport(d.ν, d.f(x))
function Pretty.tile(pf::Pullback{<:TV.CallableTransform})
Pretty.list_layout(Pretty.tile.([pf.f.t, pf.ν, pf.logjac]); prefix = :Pullback)
end
function Pretty.tile(pf::Pullback)
Pretty.list_layout(Pretty.tile.([pf.f, pf.ν, pf.logjac]); prefix = :Pullback)
end
@inline function logdensity_def(pb::Pullback{F,M,True}, x) where {F<:CallableTransform,M}
f = pb.f
ν = pb.ν
y, logJ = TV.transform_and_logjac(f.t, x)
return logdensity_def(ν, y) + logJ
end
@inline function logdensity_def(pb::Pullback{F,M,False}, x) where {F<:CallableTransform,M}
f = pb.f
ν = pb.ν
y = f(x)
return logdensity_def(ν, y)
end
@inline function logdensity_def(pf::Pushforward{F,M,True}, y) where {F<:CallableTransform,M}
f = pf.f
μ = pf.μ
x = TV.inverse(f.t)(y)
_, logJ = TV.transform_and_logjac(f.t, x)
return logdensity_def(μ, x) - logJ
end
@inline function logdensity_def(
pf::Pushforward{F,M,False},
y,
) where {F<:CallableTransform,M}
f = pf.f
μ = pf.μ
x = TV.inverse(f.t)(y)
return logdensity_def(μ, x)
end
Pullback(f::AbstractTransform, ν, logjac = True()) = Pullback(TV.transform(f), ν, logjac)
function Pushforward(f::AbstractTransform, ν, logjac = True())
Pushforward(TV.transform(f), ν, logjac)
end
Pullback(f::CallableInverse, ν, logjac = True()) = Pushforward(TV.transform(f.t), ν, logjac)
Pushforward(f::CallableInverse, ν, logjac = True()) = Pullback(TV.transform(f.t), ν, logjac)
Base.rand(rng::AbstractRNG, T::Type, ν::Pushforward) = ν.f(rand(rng, T, ν.μ))
Base.rand(rng::AbstractRNG, T::Type, μ::Pullback) = μ.f(rand(rng, T, μ.ν))
testvalue(ν::Pushforward) = TV.transform(ν.f, testvalue(ν.μ))
testvalue(μ::Pullback) = TV.transform(TV.inverse(μ.f), testvalue(μ.ν))
basemeasure(μ::Pullback) = Pullback(μ.f, basemeasure(μ.ν), False())
basemeasure(ν::Pushforward) = Pushforward(ν.f, basemeasure(ν.μ), False())
as(ν::Pushforward) = ν.f ∘ as(ν.μ)
as(μ::Pullback) = TV.inverse(μ.f) ∘ μ.ν
as(::Lebesgue) = asℝ
# TODO: Make this work for affine embeddings
as(d::AffinePushfwd) = _as_affine(_firstval(d))
_firstval(d::AffinePushfwd) = first(values(getfield(getfield(d, :f), :par)))
_as_affine(x::Real) = asℝ
_as_affine(x::AbstractArray) = as(Vector, size(x, 1))
function basemeasure(
::Pushforward{TV.CallableTransform{T},Lebesgue{ℝ}},
) where {T<:TV.ScalarTransform}
Lebesgue(ℝ)
end
function basemeasure(
::Pullback{TV.CallableTransform{T},Lebesgue{ℝ}},
) where {T<:TV.ScalarTransform}
Lebesgue(ℝ)
end
# t = as𝕀
# μ = Normal()
# ν = Pushforward(t, μ)
# x = rand(μ)
# julia> logdensity_def(μ, x) ≈ logdensity_def(Pushforward(inverse(t), ν), x)
# true
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 45 |
as(μ::AbstractWeightedMeasure) = as(μ.base)
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1713 | # Bernoulli distribution
export Bernoulli
import Base
@parameterized Bernoulli()
@kwstruct Bernoulli()
@kwstruct Bernoulli(p)
@kwstruct Bernoulli(logitp)
Bernoulli(p) = Bernoulli((p = p,))
basemeasure(::Bernoulli) = CountingBase()
testvalue(::Bernoulli) = true
insupport(::Bernoulli, x) = x == true || x == false
@inline function logdensity_def(d::Bernoulli{(:p,)}, y)
p = d.p
y == true ? log(p) : log1p(-p)
end
function density_def(::Bernoulli{()}, y)
return 0.5
end
@inline function logdensity_def(d::Bernoulli{()}, y)
return -logtwo
end
function density_def(d::Bernoulli{(:p,)}, y)
p = d.p
return 2 * p * y - p - y + 1
end
densityof(d::Bernoulli, y) = density_def(d, y)
unsafe_densityof(d::Bernoulli, y) = density_def(d, y)
@inline function logdensity_def(d::Bernoulli{(:logitp,)}, y)
x = d.logitp
return y * x - log1pexp(x)
end
function density_def(d::Bernoulli{(:logitp,)}, y)
exp_x = exp(d.logitp)
return exp_x^y / (1 + exp_x)
end
gentype(::Bernoulli) = Bool
Base.rand(rng::AbstractRNG, T::Type, d::Bernoulli{()}) = rand(rng, T) < one(T) / 2
Base.rand(rng::AbstractRNG, T::Type, d::Bernoulli{(:p,)}) = rand(rng, T) < d.p
function Base.rand(rng::AbstractRNG, T::Type, d::Bernoulli{(:logitp,)})
rand(rng, T) < logistic(d.logitp)
end
function smf(b::B, x::X) where {B<:Bernoulli,X}
T = Core.Compiler.return_type(densityof, Tuple{B,X})
x < zero(x) && return zero(T)
x ≥ one(x) && return one(T)
return densityof(b, zero(x))
end
function invsmf(b::Bernoulli, p)
p0 = densityof(b, 0)
p ≤ p0 ? 0 : 1
end
proxy(d::Bernoulli{(:p,)}) = Dists.Bernoulli(d.p)
proxy(d::Bernoulli{(:logitp,)}) = Dists.Bernoulli(logistic(d.logitp))
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 757 | # Beta distribution
export Beta
@parameterized Beta(α, β)
@kwstruct Beta(α, β)
@kwalias Beta [
a => α
alpha => α
b => β
beta => β
]
@inline function logdensity_def(d::Beta{(:α, :β),Tuple{A,B}}, x::X) where {A,B,X}
return xlogy(d.α - 1, x) + xlog1py(d.β - 1, -x)
end
@inline function basemeasure(d::Beta{(:α, :β)})
ℓ = -logbeta(d.α, d.β)
weightedmeasure(ℓ, LebesgueBase())
end
Base.rand(rng::AbstractRNG, T::Type, μ::Beta) = rand(rng, Dists.Beta(μ.α, μ.β))
insupport(::Beta, x) = in𝕀(x)
insupport(::Beta) = in𝕀
function smf(d::Beta{(:α, :β)}, x::Real)
StatsFuns.betacdf(d.α, d.β, x)
end
function invsmf(d::Beta{(:α, :β)}, p)
StatsFuns.betainvcdf(d.α, d.β, p)
end
proxy(d::Beta{(:α, :β)}) = Dists.Beta(d.α, d.β)
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 829 | # Beta-Binomial distribution
export BetaBinomial
import Base
using SpecialFunctions
@parameterized BetaBinomial(n, α, β)
basemeasure(d::BetaBinomial) = CountingBase()
testvalue(::BetaBinomial) = 0
@kwstruct BetaBinomial(n, α, β)
function Base.rand(rng::AbstractRNG, ::Type{T}, d::BetaBinomial{(:n, :α, :β)}) where {T}
k = rand(rng, T, Beta(d.α, d.β))
return rand(rng, T, Binomial(d.n, k))
end
@inline function insupport(d::BetaBinomial, x)
isinteger(x) && 0 ≤ x ≤ d.n
end
@inline function logdensity_def(d::BetaBinomial{(:n, :α, :β)}, y)
(n, α, β) = (d.n, d.α, d.β)
logbinom = -log1p(n) - logbeta(y + 1, n - y + 1)
lognum = logbeta(y + α, n - y + β)
logdenom = logbeta(α, β)
return logbinom + lognum - logdenom
end
proxy(d::BetaBinomial{(:n, :α, :β)}) = Dists.BetaBinomial(d.n, d.α, d.β)
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 2480 | # Binomial distribution
export Binomial
import Base
using SpecialFunctions
probit(p) = Φinv(p)
@parameterized Binomial(n, p)
basemeasure(d::Binomial) = CountingBase()
testvalue(::Binomial) = 0
@kwstruct Binomial()
@inline function logdensity_def(d::Binomial{()}, y)
return -logtwo
end
@inline function insupport(d::Binomial{()}, x)
x ∈ (0, 1)
end
function Base.rand(rng::AbstractRNG, ::Type{T}, d::Binomial{(:n, :p)}) where {T}
rand(rng, T, Dists.Binomial(d.n, d.p))
end
Binomial(n) = Binomial(n, 0.5)
###############################################################################
@kwstruct Binomial(n, p)
@inline function insupport(d::Binomial, x)
isinteger(x) && 0 ≤ x ≤ d.n
end
@inline function logdensity_def(d::Binomial{(:n, :p)}, y)
(n, p) = (d.n, d.p)
return -log1p(n) - logbeta(n - y + 1, y + 1) + xlogy(y, p) + xlog1py(n - y, -p)
end
function Base.rand(
rng::AbstractRNG,
::Type,
d::Binomial{(:n, :p),Tuple{I,A}},
) where {I<:Integer,A}
rand(rng, Dists.Binomial(d.n, d.p))
end
###############################################################################
@kwstruct Binomial(n, logitp)
@inline function logdensity_def(d::Binomial{(:n, :logitp)}, y)
n = d.n
x = d.logitp
return -log1p(n) - logbeta(n - y + 1, y + 1) + y * x - n * log1pexp(x)
end
function Base.rand(
rng::AbstractRNG,
::Type,
d::Binomial{(:n, :logitp),Tuple{I,A}},
) where {I<:Integer,A}
rand(rng, Dists.Binomial(d.n, logistic(d.logitp)))
end
###############################################################################
@kwstruct Binomial(n, probitp)
@inline function logdensity_def(d::Binomial{(:n, :probitp)}, y)
n = d.n
z = d.probitp
return -log1p(n) - logbeta(n - y + 1, y + 1) + xlogy(y, Φ(z)) + xlogy(n - y, Φ(-z))
end
function Base.rand(
rng::AbstractRNG,
::Type,
d::Binomial{(:n, :probitp),Tuple{I,A}},
) where {I<:Integer,A}
rand(rng, Dists.Binomial(d.n, Φ(d.probitp)))
end
proxy(d::Binomial{(:n, :p),Tuple{I,A}}) where {I<:Integer,A} = Dists.Binomial(d.n, d.p)
function proxy(d::Binomial{(:n, :logitp),Tuple{I,A}}) where {I<:Integer,A}
Dists.Binomial(d.n, logistic(d.logitp))
end
function proxy(d::Binomial{(:n, :probitp),Tuple{I,A}}) where {I<:Integer,A}
Dists.Binomial(d.n, Φ(d.probitp))
end
function smf(μ::Binomial{(:n, :p)}, k)
α = max(0, floor(k) + 1)
β = max(0, μ.n - floor(k))
beta_smf = smf(Beta(α, β), μ.p)
one(beta_smf) - beta_smf
end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1301 |
# Cauchy distribution
export Cauchy, HalfCauchy
@parameterized Cauchy(μ, σ)
@kwstruct Cauchy()
@kwstruct Cauchy(μ)
@kwstruct Cauchy(σ)
@kwstruct Cauchy(μ, σ)
@kwstruct Cauchy(λ)
@kwstruct Cauchy(μ, λ)
logdensity_def(d::Cauchy, x) = logdensity_def(proxy(d), x)
basemeasure(d::Cauchy) = WeightedMeasure(static(-logπ), LebesgueBase())
# @affinepars Cauchy
@inline function logdensity_def(d::Cauchy{()}, x)
return -log1p(x^2)
end
function density_def(d::Cauchy{()}, x)
return inv(1 + x^2)
end
Base.rand(rng::AbstractRNG, T::Type, μ::Cauchy{()}) = randn(rng, T) / randn(rng, T)
Base.rand(::FixedRNG, ::Type{T}, ::Cauchy{()}) where {T} = zero(T)
for N in AFFINEPARS
@eval begin
proxy(d::Cauchy{$N}) = affine(params(d), Cauchy())
@useproxy Cauchy{$N}
function rand(rng::AbstractRNG, ::Type{T}, d::Cauchy{$N}) where {T}
rand(rng, T, affine(params(d), Cauchy()))
end
end
end
≪(::Cauchy, ::Lebesgue{X}) where {X<:Real} = true
@half Cauchy
HalfCauchy(σ) = HalfCauchy(σ = σ)
Base.rand(::FixedRNG, ::Type{T}, μ::Half{<:Cauchy}) where {T} = one(T)
insupport(::Cauchy, x) = true
function smf(::Cauchy{()}, x)
invπ * atan(x) + 0.5
end
function invsmf(::Cauchy{()}, p)
tan(π * (p - 0.5))
end
proxy(d::Cauchy{()}) = Dists.Cauchy()
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1023 | # Dirichlet distribution
using MeasureBase: Simplex
export Dirichlet
using FillArrays
@parameterized Dirichlet(α)
@inline function basemeasure(μ::Dirichlet{(:α,)})
α = μ.α
# TODO: We can make this traverse α only once. Is that faster?
logw = loggamma(sum(α)) - sum(loggamma, α)
return WeightedMeasure(logw, Lebesgue(Simplex()))
end
@kwstruct Dirichlet(α)
Dirichlet(k::Integer, α) = Dirichlet(Fill(α, k))
@inline function logdensity_def(d::Dirichlet{(:α,)}, x)
sum(zip(d.α, x)) do (αj, xj)
xlogy(αj - 1, xj)
end
# `mapreduce` is slow for this case
# mapreduce(+, d.α, x) do αj, xj
# xlogy(αj - 1, xj)
# end
end
Base.rand(rng::AbstractRNG, T::Type, μ::Dirichlet) = rand(rng, Dists.Dirichlet(μ.α))
function testvalue(::Type{T}, d::Dirichlet{(:α,)}) where {T}
n = length(d.α)
Fill(inv(convert(T, n)), n)
end
@inline function insupport(d::Dirichlet{(:α,)}, x)
length(x) == length(d.α) && sum(x) ≈ 1.0
end
as(μ::Dirichlet) = TV.UnitSimplex(length(μ.α))
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1948 |
# Exponential distribution
export Exponential
@parameterized Exponential(β)
insupport(::Exponential, x) = x ≥ 0
basemeasure(::Exponential) = LebesgueBase()
@kwstruct Exponential()
@inline function logdensity_def(d::Exponential{()}, x)
return -x
end
Base.rand(rng::AbstractRNG, T::Type, μ::Exponential{()}) = randexp(rng, T)
##########################
# Scale β
@kwstruct Exponential(β)
function Base.rand(rng::AbstractRNG, T::Type, d::Exponential{(:β,)})
randexp(rng, T) * d.β
end
@inline function logdensity_def(d::Exponential{(:β,)}, x)
z = x / d.β
return logdensity_def(Exponential(), z) - log(d.β)
end
proxy(d::Exponential{(:β,)}) = Dists.Exponential(d.β)
##########################
# Log-Scale logβ
@kwstruct Exponential(logβ)
function Base.rand(rng::AbstractRNG, T::Type, d::Exponential{(:logβ,)})
randexp(rng, T) * exp(d.logβ)
end
@inline function logdensity_def(d::Exponential{(:logβ,)}, x)
z = x * exp(-d.logβ)
return logdensity_def(Exponential(), z) - d.logβ
end
proxy(d::Exponential{(:logβ,)}) = Dists.Exponential(exp(d.logβ))
##########################
# Rate λ
@kwstruct Exponential(λ)
function Base.rand(rng::AbstractRNG, T::Type, d::Exponential{(:λ,)})
randexp(rng, T) / d.λ
end
@inline function logdensity_def(d::Exponential{(:λ,)}, x)
z = x * d.λ
return logdensity_def(Exponential(), z) + log(d.λ)
end
proxy(d::Exponential{(:λ,)}) = Dists.Exponential(1 / d.λ)
##########################
# Log-Rate logλ
@kwstruct Exponential(logλ)
function Base.rand(rng::AbstractRNG, T::Type, d::Exponential{(:logλ,)})
randexp(rng, T) * exp(-d.logλ)
end
@inline function logdensity_def(d::Exponential{(:logλ,)}, x)
z = x * exp(d.logλ)
return logdensity_def(Exponential(), z) + d.logλ
end
proxy(d::Exponential{(:logλ,)}) = Dists.Exponential(exp(-d.logλ))
smf(::Exponential{()}, x) = smf(StdExponential(), x)
invsmf(::Exponential{()}, p) = invsmf(StdExponential(), p)
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1366 |
# Gamma distribution
export Gamma
@parameterized Gamma()
@kwstruct Gamma()
proxy(::Gamma{()}) = Exponential()
@useproxy Gamma{()}
@kwstruct Gamma(k)
@inline function logdensity_def(d::Gamma{(:k,)}, x)
return xlogy(d.k - 1, x) - x
end
function basemeasure(d::Gamma{(:k,)})
ℓ = -loggamma(d.k)
weightedmeasure(ℓ, LebesgueBase())
end
@kwstruct Gamma(k, σ)
Gamma(k, σ) = Gamma((k = k, σ = σ))
@useproxy Gamma{(:k, :σ)}
function proxy(d::Gamma{(:k, :σ)})
affine((σ = d.σ,), Gamma((k = d.k,)))
end
@kwstruct Gamma(k, λ)
@useproxy Gamma{(:k, :λ)}
function proxy(d::Gamma{(:k, :λ)})
affine(NamedTuple{(:λ,)}(d.λ), Gamma((k = d.k,)))
end
Base.rand(rng::AbstractRNG, T::Type, μ::Gamma{()}) = rand(rng, T, Exponential())
Base.rand(rng::AbstractRNG, T::Type, μ::Gamma{(:k,)}) = rand(rng, Dists.Gamma(μ.k))
insupport(::Gamma, x) = x > 0
@kwstruct Gamma(μ, ϕ)
@inline function logdensity_def(d::Gamma{(:μ, :ϕ)}, x)
x_μ = x / d.μ
inv(d.ϕ) * (log(x_μ) - x_μ) - log(x)
end
function basemeasure(d::Gamma{(:μ, :ϕ)})
ϕ = d.ϕ
ϕinv = inv(ϕ)
ℓ = -ϕinv * log(ϕ) - first(logabsgamma(ϕinv))
weightedmeasure(ℓ, LebesgueBase())
end
function basemeasure(d::Gamma{(:μ, :ϕ),Tuple{M,StaticFloat64{ϕ}}}) where {M,ϕ}
ϕinv = inv(ϕ)
ℓ = static(-ϕinv * log(ϕ) - first(logabsgamma(ϕinv)))
weightedmeasure(ℓ, LebesgueBase())
end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 875 | # Gumbel distribution
export Gumbel
@parameterized Gumbel()
basemeasure(::Gumbel{()}) = LebesgueBase()
@kwstruct Gumbel()
@kwstruct Gumbel(β)
@kwstruct Gumbel(μ, β)
# map affine names to those more common for Gumbel
for N in [(:μ,), (:σ,), (:μ, :σ)]
G = tuple(replace(collect(N), :σ => :β)...)
@eval begin
proxy(d::Gumbel{$G}) = affine(NamedTuple{$N}(values(params(d))), Gumbel())
logdensity_def(d::Gumbel{$G}, x) = logdensity_def(proxy(d), x)
basemeasure(d::Gumbel{$G}) = basemeasure(proxy(d))
end
end
@inline function logdensity_def(d::Gumbel{()}, x)
return -exp(-x) - x
end
import Base
function Base.rand(rng::AbstractRNG, ::Type{T}, d::Gumbel{()}) where {T}
u = rand(rng, T)
-log(-log(u))
end
≪(::Gumbel, ::Lebesgue{X}) where {X<:Real} = true
insupport(::Gumbel, x) = true
proxy(::Gumbel{()}) = Dists.Gumbel()
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 495 |
# InverseGamma distribution
export InverseGamma
@parameterized InverseGamma(shape) ≃ Lebesgue(ℝ₊)
@inline function logdensity_def(μ::InverseGamma{(:shape,)}, x)
α = μ.shape
xinv = 1 / x
return xlogy(α + 1, xinv) - xinv - loggamma(α)
end
function Base.rand(rng::AbstractRNG, T::Type, μ::InverseGamma{(:shape,)})
rand(rng, Dists.InverseGamma(μ.shape))
end
≪(::InverseGamma, ::Lebesgue{X}) where {X<:Real} = true
as(::InverseGamma) = asℝ₊
# @μσ_methods InverseGamma(shape)
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1298 | # InverseGaussian distribution
export InverseGaussian
@parameterized InverseGaussian()
# @kwstruct InverseGaussian()
# @kwstruct InverseGaussian(μ)
# @kwstruct InverseGaussian(μ, λ)
# InverseGaussian(μ) = InverseGaussian((μ = μ,))
# InverseGaussian(μ, λ) = InverseGaussian((μ = μ, λ = λ))
# @useproxy InverseGaussian{(:k, :θ)}
# function logdensity_def(d::InverseGaussian{()}, x)
# return (-3log(x) - (x - 1)^2 / x) / 2
# end
# function logdensity_def(d::InverseGaussian{(:μ,)}, x)
# μ = d.μ
# return (-3log(x) - (x - μ)^2 / (μ^2 * x)) / 2
# end
# function logdensity_def(d::InverseGaussian{(:μ, :λ)}, x)
# μ, λ = d.μ, d.λ
# return (log(λ) - 3log(x) - λ * (x - μ)^2 / (μ^2 * x)) / 2
# end
# function basemeasure(::InverseGaussian)
# ℓ = static(-log2π / 2)
# weightedmeasure(ℓ, Lebesgue())
# end
Base.rand(rng::AbstractRNG, T::Type, d::InverseGaussian) = rand(rng, proxy(d))
insupport(::InverseGaussian, x) = x > 0
# GLM parameterization
@kwstruct InverseGaussian(μ, ϕ)
function logdensity_def(d::InverseGaussian{(:μ, :ϕ)}, x)
μ, ϕ = d.μ, d.ϕ
return (-3log(x) - (x - μ)^2 / (ϕ * μ^2 * x)) / 2
end
function basemeasure(d::InverseGaussian{(:μ, :ϕ)})
ℓ = static(-0.5) * (static(float(log2π)) + log(d.ϕ))
weightedmeasure(ℓ, LebesgueBase())
end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 897 |
# Laplace distribution
export Laplace
@parameterized Laplace()
@kwstruct Laplace()
@kwstruct Laplace(μ)
@kwstruct Laplace(σ)
@kwstruct Laplace(μ, σ)
@kwstruct Laplace(λ)
@kwstruct Laplace(μ, λ)
for N in AFFINEPARS
@eval begin
proxy(d::Laplace{$N}) = affine(params(d), Laplace())
@useproxy Laplace{$N}
end
end
insupport(::Laplace, x) = true
@inline function logdensity_def(d::Laplace{()}, x)
return -abs(x)
end
Laplace(μ, σ) = Laplace((μ = μ, σ = σ))
basemeasure(::Laplace{()}) = WeightedMeasure(static(-logtwo), LebesgueBase())
# @affinepars Laplace
function Base.rand(rng::AbstractRNG, ::Type{T}, μ::Laplace{()}) where {T}
sign = rand(rng, Bool)
absx = randexp(rng, T)
sign == true ? absx : -absx
end
Base.rand(rng::AbstractRNG, ::Type{T}, μ::Laplace) where {T} = Base.rand(rng, T, proxy(μ))
≪(::Laplace, ::Lebesgue{X}) where {X<:Real} = true
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 3674 | # Modified from
# https://github.com/tpapp/AltDistributions.jl
# See also the Stan manual (the "Stanual", though nobody calls it that)
# https://mc-stan.org/docs/2_27/reference-manual/cholesky-factors-of-correlation-matrices-1.html
export LKJCholesky
using PositiveFactorizations
const CorrCholeskyUpper = TV.CorrCholeskyFactor
@doc """
LKJCholesky(k=3, η=1.0)
LKJCholesky(k=3, logη=0.0)
`LKJCholesky(k, ...)` gives the `k×k` LKJ distribution (Lewandowski et al 2009)
expressed as a Cholesky decomposition. As a special case, for
`C = rand(LKJCholesky(k=K, η=1.0))` (or equivalently
`C=rand(LKJCholesky{k}(k=K, logη=0.0))`), `C.L * C.U` is uniform over the set of
all `K×K` correlation matrices. Note, however, that in this case `C.L` and `C.U`
are **not** sampled uniformly (because the multiplication is nonlinear).
The `logdensity` method for this measure applies for `LowerTriangular`,
`UpperTriangular`, or `Diagonal` matrices, and will "do the right thing". The
`logdensity` **does not check if `L*U` yields a valid correlation matrix**.
Valid values are ``η > 0``. When ``η > 1``, the distribution is unimodal with a
peak at `I`, while ``0 < η < 1`` yields a trough. ``η = 2`` is recommended as a vague prior.
Adapted from
https://github.com/tpapp/AltDistributions.jl
""" LKJCholesky
@parameterized LKJCholesky(k, η)
@kwstruct LKJCholesky(k, η)
@kwstruct LKJCholesky(k, logη)
LKJCholesky(k::Integer) = LKJCholesky(k, 1.0)
# Modified from
# https://github.com/tpapp/AltDistributions.jl
using LinearAlgebra
logdensity_def(d::LKJCholesky, C::Cholesky) = logdensity_def(d, C.UL)
@inline function logdensity_def(
d::LKJCholesky{(:k, :η)},
L::Union{LinearAlgebra.AbstractTriangular,Diagonal},
)
η = d.η
# z = diag(L)
# sum(log.(z) .* ((k:-1:1) .+ 2*(η-1)))
# Note: https://github.com/JuliaMath/MeasureTheory.jl/issues/100#issuecomment-852428192
c = d.k + 2(η - 1)
n = size(L, 1)
s = sum(1:n) do i
(c - i) * @inbounds log(L[i, i])
end
return s
end
@inline function logdensity_def(
d::LKJCholesky{(:k, :logη)},
L::Union{LinearAlgebra.AbstractTriangular,Diagonal},
)
c = d.k + 2 * expm1(d.logη)
n = size(L, 1)
s = sum(1:n) do i
(c - i) * @inbounds log(L[i, i])
end
return s
end
as(d::LKJCholesky) = CorrCholesky(d.k)
@inline function basemeasure(d::LKJCholesky{(:k, :η)})
t = as(d)
base = Pushforward(t, LebesgueBase()^TV.dimension(t), False())
WeightedMeasure(Dists.lkj_logc0(d.k, d.η), base)
end
@inline function basemeasure(d::LKJCholesky{(:k, :logη)})
t = as(d)
η = exp(d.logη)
base = Pushforward(t, LebesgueBase()^TV.dimension(t), False())
WeightedMeasure(Dists.lkj_logc0(d.k, η), base)
end
# TODO: Fix this
insupport(::LKJCholesky, x) = true
# Note (from @sethaxen): this can be done without the cholesky decomposition, by randomly
# sampling the canonical partial correlations, as in the LKJ paper, and then
# mapping them to the cholesky factor instead of the correlation matrix. Stan
# implements* this. But that can be for a future PR.
#
# * https://github.com/stan-dev/math/blob/develop/stan/math/prim/prob/lkj_corr_cholesky_rng.hpp
function Base.rand(rng::AbstractRNG, ::Type, d::LKJCholesky{(:k, :η)})
return cholesky(Positive, rand(rng, Dists.LKJ(d.k, d.η)))
end;
function testvalue(d::LKJCholesky)
t = CorrCholesky(d.k)
return TV.transform(t, zeros(TV.dimension(t)))
end
function Base.rand(rng::AbstractRNG, ::Type, d::LKJCholesky{(:k, :logη)})
return cholesky(Positive, rand(rng, Dists.LKJ(d.k, exp(d.logη))))
end;
ConstructionBase.constructorof(::Type{L}) where {L<:LKJCholesky} = LKJCholesky
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1153 | # Multinomial distribution
export Multinomial
@parameterized Multinomial(n, p)
basemeasure(d::Multinomial) = CountingBase()
@inline function insupport(d::Multinomial{(:n, :p)}, x)
length(x) == length(d.p) || return false
all(isinteger, x) || return false
sum(x) == d.n || return false
return true
end
@kwstruct Multinomial(n, p)
@inline function logdensity_def(d::Multinomial{(:n, :p)}, x)
p = d.p
s = 0.0
for j in eachindex(x)
s += xlogy(x[j], p[j])
end
return s
end
function Base.rand(rng::AbstractRNG, T::Type, μ::Multinomial)
rand(rng, Dists.Multinomial(μ.n, μ.p))
end
proxy(d::Multinomial{(:p,)}) = Dists.Multinomial(d.n, d.p)
# Based on
# https://github.com/JuliaMath/Combinatorics.jl/blob/c2114a71ccfc93052efb9a9379e62b81b9388ef8/src/factorials.jl#L99
function logmultinomial(k)
s = 0
result = 1
@inbounds for i in k
s += i
(Δresult, _) = logabsbinomial(s, i)
result += Δresult
end
result
end
function testvalue(d::Multinomial{(:n, :p)})
n = d.n
l = length(d.p)
q, r = divrem(n, l)
x = fill(q, l)
x[1] += r
return x
end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1887 |
# Multivariate Normal distribution
export MvNormal
@parameterized MvNormal(μ, σ)
# MvNormal(;kwargs...) = MvNormal(kwargs)
@kwstruct MvNormal(μ)
@kwstruct MvNormal(σ)
@kwstruct MvNormal(λ)
@kwstruct MvNormal(μ, σ)
@kwstruct MvNormal(μ, λ)
@kwstruct MvNormal(Σ)
@kwstruct MvNormal(Λ)
@kwstruct MvNormal(μ, Σ)
@kwstruct MvNormal(μ, Λ)
for N in setdiff(AFFINEPARS, [(:μ,)])
@eval begin
function as(d::MvNormal{$N})
p = proxy(d)
if rank(getfield(p, :f)) == only(supportdim(d))
return as(Array, supportdim(d))
else
@error "Not yet implemented"
end
end
end
end
supportdim(d::MvNormal) = supportdim(params(d))
supportdim(nt::NamedTuple{(:Σ,)}) = size(nt.Σ, 1)
supportdim(nt::NamedTuple{(:μ, :Σ)}) = size(nt.Σ, 1)
supportdim(nt::NamedTuple{(:Λ,)}) = size(nt.Λ, 1)
supportdim(nt::NamedTuple{(:μ, :Λ)}) = size(nt.Λ, 1)
@useproxy MvNormal
for N in [(:Σ,), (:μ, :Σ), (:Λ,), (:μ, :Λ)]
@eval basemeasure_depth(d::MvNormal{$N}) = static(2)
end
proxy(d::MvNormal) = affine(params(d), Normal()^supportdim(d))
rand(rng::AbstractRNG, ::Type{T}, d::MvNormal) where {T} = rand(rng, T, proxy(d))
insupport(d::MvNormal, x) = insupport(proxy(d), x)
# Note: (C::Cholesky).L may or may not make a copy, depending on C.uplo, which is not included in the type
@inline function proxy(d::MvNormal{(:Σ,),Tuple{C}}) where {C<:Cholesky}
affine((σ = d.Σ.L,), Normal()^supportdim(d))
end
@inline function proxy(d::MvNormal{(:Λ,),Tuple{C}}) where {C<:Cholesky}
affine((λ = d.Λ.L,), Normal()^supportdim(d))
end
@inline function proxy(d::MvNormal{(:μ, :Σ),Tuple{T,C}}) where {T,C<:Cholesky}
affine((μ = d.μ, σ = d.Σ.L), Normal()^supportdim(d))
end
@inline function proxy(d::MvNormal{(:μ, :Λ),Tuple{T,C}}) where {T,C<:Cholesky}
affine((μ = d.μ, λ = d.Λ.L), Normal()^supportdim(d))
end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 2473 | # NegativeBinomial distribution
export NegativeBinomial
import Base
@parameterized NegativeBinomial(r, p)
insupport(::NegativeBinomial, x) = isinteger(x) && x ≥ 0
basemeasure(::NegativeBinomial) = CountingBase()
testvalue(::NegativeBinomial) = 0
function Base.rand(rng::AbstractRNG, ::Type{T}, d::NegativeBinomial) where {T}
rand(rng, proxy(d))
end
###############################################################################
@kwstruct NegativeBinomial(r, p)
NegativeBinomial(n) = NegativeBinomial(n, 0.5)
@inline function logdensity_def(d::NegativeBinomial{(:r, :p)}, y)
(r, p) = (d.r, d.p)
return -log(y + r) - logbeta(r, y + 1) + xlogy(y, p) + xlog1py(r, -p)
end
proxy(d::NegativeBinomial{(:r, :p)}) = Dists.NegativeBinomial(d.r, d.p)
###############################################################################
@kwstruct NegativeBinomial(r, logitp)
@inline function logdensity_def(d::NegativeBinomial{(:r, :logitp)}, y)
(r, logitp) = (d.r, d.logitp)
return -log(y + r) - logbeta(r, y + 1) - y * log1pexp(-logitp) - r * log1pexp(logitp)
end
proxy(d::NegativeBinomial{(:n, :logitp)}) = Dists.NegativeBinomial(d.n, logistic(d.logitp))
###############################################################################
@kwstruct NegativeBinomial(r, λ)
# mean λ, as in Poisson
# Converges to Poisson as r→∞
@inline function logdensity_def(d::NegativeBinomial{(:r, :λ)}, y)
(r, λ) = (d.r, d.λ)
return -log(y + r) - logbeta(r, y + 1) + xlogy(y, λ) + xlogx(r) - xlogy(y + r, r + λ)
end
function proxy(d::NegativeBinomial{(:r, :λ)})
p = d.λ / (d.r + d.λ)
return Dists.NegativeBinomial(d.r, p)
end
# # https://en.wikipedia.org/wiki/Negative_binomial_distribution#Gamma%E2%80%93Poisson_mixture
# function Base.rand(rng::AbstractRNG, d::NegativeBinomial{(:r,:λ)})
# r = d.r
# λ = d.λ
# μ = rand(rng, Dists.Gamma(r, λ/r))
# return rand(rng, Dists.Poisson(μ))
# end
###############################################################################
@kwstruct NegativeBinomial(r, logλ)
@inline function logdensity_def(d::NegativeBinomial{(:r, :logλ)}, y)
(r, logλ) = (d.r, d.logλ)
λ = exp(logλ)
return -log(y + r) - logbeta(r, y + 1) + y * logλ + xlogx(r) - xlogy(y + r, r + λ)
end
function proxy(d::NegativeBinomial{(:r, :logλ)})
λ = exp(d.logλ)
p = λ / (d.r + λ)
return Dists.NegativeBinomial(d.r, p)
end
###############################################################################
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 6551 | using StatsFuns
export Normal, HalfNormal
# The `@parameterized` macro below does three things:
# 1. Defines the `Normal` struct
#
# struct Normal{N, T} <: (ParameterizedMeasure){N}
# par::MeasureTheory.NamedTuple{N, T}
# end
#
# (Note that this is the same form required by the `@kwstruct` in the
# KeywordCalls package.)
#
# 2. Sets the base measure
#
# basemeasure(::Normal) = (1 / sqrt2π) * Lebesgue(ℝ)
#
# This just means that (log-)densities will be defined relative to this.
# Including the `(1 / sqrt2π)` in the base measure allows us to avoid
# carrying around the normalization constant.
#
# 3. Sets up a method for a call with two unnamed arguments,
#
# Normal(μ, σ) = Normal((μ=μ, σ=σ))
#
@parameterized Normal()
massof(::Normal) = static(1.0)
for N in AFFINEPARS
@eval begin
proxy(d::Normal{$N,T}) where {T} = affine(params(d), Normal())
@useproxy Normal{$N,T} where {T}
end
end
insupport(d::Normal, x) = True()
insupport(d::Normal) = Returns(True())
@inline logdensity_def(d::Normal{()}, x) = -muladd(x, x, log2π) / 2;
@inline basemeasure(::Normal{()}) = LebesgueBase()
@kwstruct Normal(μ)
@kwstruct Normal(σ)
@kwstruct Normal(μ, σ)
@kwstruct Normal(λ)
@kwstruct Normal(μ, λ)
params(::Type{N}) where {N<:Normal} = ()
Normal(μ::M, σ::S) where {M,S} = Normal((μ = μ, σ = σ))::Normal{(:μ, :σ),Tuple{M,S}}
# Normal(nt::NamedTuple{N,Tuple{Vararg{AbstractArray}}}) where {N} = MvNormal(nt)
# `@kwalias` defines some alias names, giving users flexibility in the names
# they use. For example, σ² is standard notation for the variance parameter, but
# it's a lot to type. Some users might prefer to just use `var` and have us do
# the conversion (at compile time).
@kwalias Normal [
mean => μ
mu => μ
std => σ
sigma => σ
var => σ²
ϕ => σ²
]
# It's often useful to be able to map into the parameter space for a given
# measure. We (currently, at least) do this *independently* per parameter. This
# allows us to do things like, e.g.
#
# julia> transform(asparams(Normal(2,3)))(randn(2))
# (μ = -0.6778046205440658, σ = 3.7357686957861898)
#
# julia> transform(asparams(Normal(μ=-3,logσ=2)))(randn(2))
# (μ = 0.3995295982002209, logσ = -1.3902312393777492)
#
# Or using types:
# julia> transform(asparams(Normal{(:μ,:σ²)}))(randn(2))
# (μ = -0.4548087051528626, σ² = 11.920775478312793)
#
# And of course, you can apply `Normal` to any one of the above.
# Rather than try to reimplement everything in Distributions, measures can have
# a `proxy` method. This just delegates some methods to the corresponding
# Distributions.jl methods. For example,
#
# julia> entropy(Normal(2,4))
# 2.805232894324563
#
proxy(d::Normal{()}) = Dists.Normal()
###############################################################################
# Some distributions have a "standard" version that takes no parameters
@kwstruct Normal()
# Instead of setting default values, the `@kwstruct` call above makes a
# parameter-free instance available. The log-density for this is very efficient.
Base.rand(rng::Random.AbstractRNG, ::Type{T}, ::Normal{()}) where {T} = randn(rng, T)
Base.rand(rng::Random.AbstractRNG, ::Type{T}, μ::Normal) where {T} = rand(rng, T, proxy(μ))
###############################################################################
# `μ` and `σ` parameterizations are so common, we have a macro to make them easy
# to build. Note that `μ` and `σ` are *not* always mean and standard deviation,
# but instead should be considered "location" and "scale" parameters,
# respectively. Also, it's valid to have existing parameters here as a starting
# point, in particular a "shape parameter" is very common. See `StudentT` for an
# example of this.
#
# This defines methods for `logdensity` and `Base.rand`. The latter works out
# especially nicely, because it lets us do things like
#
# julia> using Symbolics
# [ Info: Precompiling Symbolics [0c5d862f-8b57-4792-8d23-62f2024744c7]
#
# julia> @variables μ σ
# 2-element Vector{Num}:
# μ
# σ
#
# julia> rand(Normal(μ,σ))
# μ + 1.2517620265570832σ
#
# @μσ_methods Normal()
###############################################################################
# The `@half` macro takes a symmetric univariate measure and efficiently creates
# a truncated version.
@half Normal
# A single unnamed parameter for `HalfNormal` should be interpreted as a `σ`
HalfNormal(σ) = HalfNormal((σ = σ,))
###############################################################################
@kwstruct Normal(σ²)
@kwstruct Normal(μ, σ²)
@inline function logdensity_def(d::Normal{(:σ²,)}, x)
-0.5 * x^2 / d.σ²
end
@inline function basemeasure(d::Normal{(:σ²,)})
ℓ = static(-0.5) * (static(float(log2π)) + log(d.σ²))
weightedmeasure(ℓ, LebesgueBase())
end
proxy(d::Normal{(:μ, :σ²)}) = affine((μ = d.μ,), Normal((σ² = d.σ²,)))
@useproxy Normal{(:μ, :σ²)}
###############################################################################
@kwstruct Normal(τ)
@kwstruct Normal(μ, τ)
@inline function logdensity_def(d::Normal{(:τ,)}, x)
-0.5 * x^2 * d.τ
end
@inline function basemeasure(d::Normal{(:τ,)})
ℓ = static(-0.5) * (static(float(log2π)) - log(d.τ))
weightedmeasure(ℓ, LebesgueBase())
end
proxy(d::Normal{(:μ, :τ)}) = affine((μ = d.μ,), Normal((τ = d.τ,)))
@useproxy Normal{(:μ, :τ)}
###############################################################################
@kwstruct Normal(μ, logσ)
@inline function logdensity_def(d::Normal{(:μ, :logσ)}, x)
μ = d.μ
logσ = d.logσ
-0.5(exp(-2 * logσ) * ((x - μ)^2))
end
function basemeasure(d::Normal{(:μ, :logσ)})
ℓ = static(-0.5) * (static(float(log2π)) + static(2.0) * d.logσ)
weightedmeasure(ℓ, LebesgueBase())
end
function logdensity_def(p::Normal, q::Normal, x)
μp = mean(p)
σp = std(p)
μq = mean(q)
σq = std(q)
# Result is (((x - μq) / σq)^2 - ((x - μp) / σp)^2 + log(abs(σq / σp))) / 2
# We'll write the difference of squares as sqdiff, then divide that by 2 at
# the end
if σp == σq
return (2x - μq - μp) * (μp - μq) / (2 * σp^2)
else
zp = (x - μp) / σp
zq = (x - μq) / σq
return ((zq + zp) * (zq - zp)) / 2 + log(abs(σq / σp))
end
end
MeasureBase.transport_origin(::Normal) = StdNormal()
MeasureBase.to_origin(::Normal{()}, y) = y
MeasureBase.from_origin(::Normal{()}, x) = x
MeasureBase.smf(::Normal{()}, x) = Φ(x)
MeasureBase.invsmf(::Normal{()}, p) = Φinv(p)
@smfAD Normal{()}
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 927 | # Poisson distribution
export Poisson
import Base
using SpecialFunctions: loggamma
@parameterized Poisson()
@kwstruct Poisson()
@kwstruct Poisson(λ)
Poisson(λ) = Poisson((λ = λ,))
basemeasure(::Poisson) = Counting(BoundedInts(static(0), static(Inf)))
@inline function logdensity_def(d::Poisson{()}, y::T) where {T}
return y - one(T) - loggamma(one(T) + y)
end
@inline function logdensity_def(d::Poisson{(:λ,)}, y)
λ = d.λ
return y * log(λ) - λ - loggamma(1 + y)
end
@kwstruct Poisson(logλ)
@inline function logdensity_def(d::Poisson{(:logλ,)}, y)
return y * d.logλ - exp(d.logλ) - loggamma(1 + y)
end
gentype(::Poisson) = Int
Base.rand(rng::AbstractRNG, T::Type, d::Poisson{(:λ,)}) = rand(rng, Dists.Poisson(d.λ))
function Base.rand(rng::AbstractRNG, T::Type, d::Poisson{(:logλ,)})
rand(rng, Dists.Poisson(exp(d.logλ)))
end
@inline function insupport(::Poisson, x)
isinteger(x) && x ≥ 0
end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 741 |
# Snedecor's F distribution
export SnedecorF
@parameterized SnedecorF(ν1, ν2)
@kwstruct SnedecorF(ν1, ν2)
@inline function logdensity_def(d::SnedecorF{(:ν1, :ν2)}, y)
ν1, ν2 = d.ν1, d.ν2
ν1ν2 = ν1 / ν2
val = (xlogy(ν1, ν1ν2) + xlogy(ν1 - 2, y) - xlogy(ν1 + ν2, 1 + ν1ν2 * y)) / 2
return val
end
@inline function basemeasure(d::SnedecorF{(:ν1, :ν2)})
ℓ = -logbeta(d.ν1 / 2, d.ν2 / 2)
weightedmeasure(ℓ, LebesgueBase())
end
Base.rand(rng::AbstractRNG, T::Type, d::SnedecorF) = rand(rng, proxy(d))
proxy(d::SnedecorF{(:ν1, :ν2)}) = Dists.FDist(d.ν1, d.ν2)
insupport(::SnedecorF, x) = x > 0
# cdf(d::SnedecorF, x) = StatsFuns.fdistcdf(d.ν1, d.ν2, x)
# ccdf(d::SnedecorF, x) = StatsFuns.fdistccdf(d.ν1, d.ν2, x)
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1771 |
# StudentT distribution
export StudentT, HalfStudentT
@parameterized StudentT(ν)
@kwstruct StudentT(ν)
@kwstruct StudentT(ν, μ)
@kwstruct StudentT(ν, σ)
@kwstruct StudentT(ν, λ)
@kwstruct StudentT(ν, μ, σ)
@kwstruct StudentT(ν, μ, λ)
for N in AFFINEPARS
@eval begin
function proxy(d::StudentT{(:ν, $N...)})
affine(NamedTuple{$N}(params(d)), StudentT((ν = d.ν,)))
end
end
end
logdensity_def(d::StudentT, x) = logdensity_def(proxy(d), x)
basemeasure(d::StudentT) = basemeasure(proxy(d))
Base.rand(rng::AbstractRNG, ::Type{T}, μ::StudentT) where {T} = rand(rng, T, proxy(μ))
# @affinepars StudentT
StudentT(ν, μ, σ) = StudentT((ν = ν, μ = μ, σ = σ))
@kwalias StudentT [
df => ν
nu => ν
location => μ
mean => μ # Doesn't really always exist, but ok fine
mu => μ
scale => σ
sigma => σ
]
@inline function logdensity_def(d::StudentT{(:ν,),Tuple{T}}, x::Number) where {T<:Number}
ν = d.ν
return xlog1py((ν + 1) / (-2), x^2 / ν)
end
@inline function logdensity_def(d::StudentT{(:ν,)}, x)
ν = d.ν
return (ν + 1) / (-2) * log1p(x^2 / ν)
end
@inline function basemeasure(d::StudentT{(:ν,)})
ℓ = loggamma((d.ν + 1) / 2) - loggamma(d.ν / 2) - log(π * d.ν) / 2
weightedmeasure(ℓ, LebesgueBase())
end
Base.rand(rng::AbstractRNG, T::Type, μ::StudentT{(:ν,)}) = rand(rng, Dists.TDist(μ.ν))
@half StudentT
HalfStudentT(ν, σ) = HalfStudentT((ν = ν, σ = σ))
insupport(::StudentT, x) = true
insupport(::StudentT) = Returns(true)
proxy(d::StudentT{(:ν,)}) = Dists.TDist(d.ν)
smf(d::StudentT, x) = smf(proxy(d), x)
invsmf(d::StudentT, p) = invsmf(proxy(d), p)
smf(d::StudentT{(:ν,)}, x) = cdf(proxy(d), x)
invsmf(d::StudentT{(:ν,)}, p) = quantile(proxy(d), p)
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1004 |
# Uniform distribution
export Uniform
@parameterized Uniform()
@kwstruct Uniform()
@kwstruct Uniform(a, b)
###############################################################################
# Standard Uniform
insupport(::Uniform{()}) = in𝕀
insupport(::Uniform{()}, x) = in𝕀(x)
@inline basemeasure(::Uniform{()}) = LebesgueBase()
density_def(::Uniform{()}, x) = 1.0
logdensity_def(d::Uniform{()}, x) = 0.0
Base.rand(rng::AbstractRNG, T::Type, μ::Uniform{()}) = rand(rng, T)
###############################################################################
# Uniform
@inline insupport(d::Uniform{(:a, :b)}, x) = d.a ≤ x ≤ d.b
Uniform(a, b) = Uniform((a = a, b = b))
proxy(d::Uniform{(:a, :b)}) = affine((μ = d.a, σ = d.b - d.a), Uniform())
@useproxy Uniform{(:a, :b)}
Base.rand(rng::Random.AbstractRNG, ::Type{T}, μ::Uniform) where {T} = rand(rng, T, proxy(μ))
smf(::Uniform{()}, x) = smf(StdUniform(), x)
invsmf(::Uniform{()}, p) = invsmf(StdUniform(), p)
proxy(::Uniform{()}) = Dists.Uniform()
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 616 | struct OrthoTransform{I,N,T} <: TV.AbstractTransform
dim::I
par::NamedTuple{N,T}
end
TV.dimension(t::OrthoTransform) = t.dim
TV.inverse_eltype(t::OrthoTransform, y::AbstractVector) = extended_eltype(y)
function TV.inverse_at!(
x::AbstractVector,
index,
t::OrthoTransform{(:σ,)},
y::AbstractVector,
) end
function TV.transform_with(
flag::LogJacFlag,
t::OrthoTransform{(:σ,)},
x::AbstractVector,
index,
)
ylen, xlen = size(d.σ)
T = extended_eltype(x)
ℓ = logjac_zero(flag, T)
y = d.σ * view(x, index, index + xlen - 1)
index += xlen
y, ℓ, index
end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1755 | # Adapted from https://github.com/tpapp/TransformVariables.jl/blob/master/src/special_arrays.jl
export CorrCholesky
"""
CorrCholesky(n)
Cholesky factor of a correlation matrix of size `n`.
Transforms ``n(n-1)/2`` real numbers to an ``n×n`` lower-triangular matrix `L`, such that
`L*L'` is a correlation matrix (positive definite, with unit diagonal).
# Notes
If
- `z` is a vector of `n` IID standard normal variates,
- `σ` is an `n`-element vector of standard deviations,
- `C` is obtained from `CorrCholesky(n)`,
then `Diagonal(σ) * C.L * z` is a zero-centered multivariate normal variate with the standard deviations `σ` and
correlation matrix `C.L * C.U`.
"""
struct CorrCholesky <: TV.VectorTransform
n::Int
end
TV.dimension(t::CorrCholesky) = TV.dimension(CorrCholeskyUpper(t.n))
# TODO: For now we just transpose the CorrCholeskyUpper result. We should
# consider whether it can help performance to implement this directly for the
# lower triangular case
function TV.transform_with(flag::TV.LogJacFlag, t::CorrCholesky, x::AbstractVector, index)
U, ℓ, index = TV.transform_with(flag, CorrCholeskyUpper(t.n), x, index)
return Cholesky(U, 'U', 0), ℓ, index
end
TV.inverse_eltype(t::CorrCholesky, x::AbstractMatrix) = eltype(x)
TV.inverse_eltype(t::CorrCholesky, x::Cholesky) = eltype(x)
function TV.inverse_at!(x::AbstractVector, index, t::CorrCholesky, L::LowerTriangular)
return TV.inverse_at!(x, index, CorrCholeskyUpper(t.n), L')
end
function TV.inverse_at!(x::AbstractVector, index, t::CorrCholesky, U::UpperTriangular)
return TV.inverse_at!(x, index, CorrCholeskyUpper(t.n), U)
end
function TV.inverse_at!(x::AbstractVector, index, t::CorrCholesky, C::Cholesky)
return TV.inverse_at!(x, index, t, C.UL)
end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 1519 | # Adapted from https://github.com/tpapp/TransformVariables.jl/blob/master/src/special_arrays.jl
using LinearAlgebra
const CorrCholeskyUpper = CorrCholeskyFactor
export CorrCholeskyLower
"""
CorrCholeskyLower(n)
Lower Cholesky factor of a correlation matrix of size `n`.
Transforms ``n(n-1)/2`` real numbers to an ``n×n`` lower-triangular matrix `L`, such that
`L*L'` is a correlation matrix (positive definite, with unit diagonal).
# Notes
If
- `z` is a vector of `n` IID standard normal variates,
- `σ` is an `n`-element vector of standard deviations,
- `L` is obtained from `CorrCholeskyLower(n)`,
then `Diagonal(σ) * L * z` is a zero-centered multivariate normal variate with the standard deviations `σ` and
correlation matrix `L * L'`.
"""
struct CorrCholeskyLower <: TV.VectorTransform
n::Int
end
TV.dimension(t::CorrCholeskyLower) = TV.dimension(CorrCholeskyUpper(t.n))
# TODO: For now we just transpose the CorrCholeskyUpper result. We should
# consider whether it can help performance to implement this directly for the
# lower triangular case
function TV.transform_with(
flag::TV.LogJacFlag,
t::CorrCholeskyLower,
x::AbstractVector,
index,
)
U, ℓ, index = TV.transform_with(flag, CorrCholeskyUpper(t.n), x, index)
return U', ℓ, index
end
TV.inverse_eltype(t::CorrCholeskyLower, L::LowerTriangular) = eltype(L)
function TV.inverse_at!(x::AbstractVector, index, t::CorrCholeskyLower, L::LowerTriangular)
return TV.inverse_at!(x, index, CorrCholeskyUpper(t.n), L')
end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 2597 | # abstract type AbstractOrderedVector{T} <: AbstractVector{T} end
# struct OrderedVector{T} <: AbstractOrderedVector{T}
# data::Vector{T}
# end
# as(::Type{OrderedVector}, transformation::TV.AbstractTransform, dim::Int) =
# Ordered(transformation, dim)
export Ordered
struct Ordered{T<:TV.AbstractTransform} <: TV.VectorTransform
transformation::T
dim::Int
end
TV.dimension(t::Ordered) = t.dim
addlogjac(ℓ, Δℓ) = ℓ + Δℓ
addlogjac(::TV.NoLogJac, Δℓ) = TV.NoLogJac()
using MappedArrays
bounds(t::TV.ShiftedExp{true}) = (t.shift, TV.∞)
bounds(t::TV.ShiftedExp{false}) = (-TV.∞, t.shift)
bounds(t::TV.ScaledShiftedLogistic) = (t.shift, t.scale + t.shift)
bounds(::TV.Identity) = (-TV.∞, TV.∞)
const OrderedΔx = -8.0
# See https://mc-stan.org/docs/2_27/reference-manual/ordered-vector.html
function TV.transform_with(flag::TV.LogJacFlag, t::Ordered, x, index::T) where {T}
transformation, len = (t.transformation, t.dim)
@assert TV.dimension(transformation) == 1
y = similar(x, len)
(lo, hi) = bounds(transformation)
x = mappedarray(xj -> xj + OrderedΔx, x)
@inbounds (y[1], ℓ, _) = TV.transform_with(flag, as(Real, lo, hi), x, index)
index += 1
@inbounds for i in 2:len
(y[i], Δℓ, _) = TV.transform_with(flag, as(Real, y[i-1], hi), x, index)
ℓ = addlogjac(ℓ, Δℓ)
index += 1
end
return (y, ℓ, index)
end
TV.inverse_eltype(t::Ordered, y::AbstractVector) = eltype(y)
Ordered(n::Int) = Ordered(asℝ, n)
function TV.inverse_at!(x::AbstractVector, index, t::Ordered, y::AbstractVector)
(lo, hi) = bounds(t.transformation)
@inbounds x[index] = TV.inverse(as(Real, lo, hi), y[1]) - OrderedΔx
index += 1
@inbounds for i in 2:length(y)
x[index] = TV.inverse(as(Real, y[i-1], hi), y[i]) - OrderedΔx
index += 1
end
return index
end
export Sorted
struct Sorted{M} <: AbstractMeasure
μ::M
n::Int
end
logdensity_def(s::Sorted, x) = logdensity_def(s.μ^s.n, x)
xform(s::Sorted) = Ordered(xform(s.μ), s.n)
function Random.rand!(rng::AbstractRNG, d::Sorted, x::AbstractArray)
rand!(rng, d.μ^d.n, x)
sort!(x)
return x
end
function Base.rand(rng::AbstractRNG, T::Type, d::Sorted)
# TODO: Use `gentype` for this
elT = typeof(rand(rng, T, d.μ))
x = Vector{elT}(undef, d.n)
rand!(rng, d, x)
end
# logdensity_def(d, rand(d))
# TV.transform_with(TV.LogJac(), Ordered(asℝ, 4), zeros(4), 1)
# TV.transform_with(TV.LogJac(), Ordered(asℝ, 4), randn(4), 1)
# d = Pushforward(Ordered(10), Normal()^10, false)
# logdensity_def(Lebesgue(ℝ)^10, rand(d))
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | code | 17468 | using Test
using StatsFuns
using Base.Iterators: take
using Random
using LinearAlgebra
# using DynamicIterators: trace, TimeLift
using TransformVariables: transform, as𝕀
using FillArrays
using MeasureTheory
using MeasureBase.Interface
using MeasureTheory: kernel
using Aqua
using IfElse
# Aqua._test_ambiguities(
# Aqua.aspkgids(MeasureTheory);
# exclude = [Random.AbstractRNG],
# # packages::Vector{PkgId};
# # color::Union{Bool, Nothing} = nothing,
# # exclude::AbstractArray = [],
# # # Options to be passed to `Test.detect_ambiguities`:
# # detect_ambiguities_options...,
# )
Aqua.test_all(MeasureBase; ambiguities = false)
function draw2(μ)
x = rand(μ)
y = rand(μ)
while x == y
y = rand(μ)
end
return (x, y)
end
x = randn(10, 3)
Σ = cholesky(x' * x)
Λ = cholesky(inv(Σ))
σ = MeasureTheory.getL(Σ)
λ = MeasureTheory.getL(Λ)
test_measures = Any[
# Chain(x -> Normal(μ=x), Normal(μ=0.0))
For(3) do j
Normal(σ = j)
end
For(2, 3) do i, j
Normal(i, j)
end
Normal()^3
Normal()^(2, 3)
3 * Normal()
Bernoulli(0.2)
Beta(2, 3)
Binomial(10, 0.3)
BetaBinomial(10, 2, 3)
Cauchy()
Dirichlet(ones(3))
Exponential()
Gumbel()
Laplace()
LKJCholesky(3, 2.0)
Multinomial(n = 10, p = [0.2, 0.3, 0.5])
NegativeBinomial(5, 0.2)
Normal(2, 3)
Poisson(3.1)
StudentT(ν = 2.1)
MvNormal(σ = [1 0; 0 1; 1 1])
MvNormal(λ = [1 0 1; 0 1 1])
MvNormal(Σ = Σ)
MvNormal(Λ = Λ)
MvNormal(σ = σ)
MvNormal(λ = λ)
Uniform()
Dirac(0.0) + Normal()
]
@testset "testvalue" begin
for μ in test_measures
@info "testing $μ"
test_interface(μ)
end
@testset "testvalue(::Chain)" begin
mc = Chain(x -> Normal(μ = x), Normal(μ = 0.0))
r = testvalue(mc)
@test logdensity_def(mc, Iterators.take(r, 10)) isa AbstractFloat
end
end
@testset "Parameterized Measures" begin
@testset "Binomial" begin
D = Binomial{(:n, :p)}
par = merge((n = 20,), transform(asparams(D, (n = 20,)), randn(1)))
d = D(par)
(n, p) = (par.n, par.p)
logitp = logit(p)
probitp = norminvcdf(p)
y = rand(d)
ℓ = logdensity_def(Binomial(; n, p), y)
@test ℓ ≈ logdensity_def(Binomial(; n, logitp), y)
@test ℓ ≈ logdensity_def(Binomial(; n, probitp), y)
rng = ResettableRNG(Random.MersenneTwister())
@test rand(rng, Binomial(n=0, p=1.0)) == 0
@test rand(rng, Binomial(n=10, p=1.0)) == 10
@test_broken logdensity_def(Binomial(n, p), CountingBase(ℤ[0:n]), x) ≈
binomlogpdf(n, p, x)
end
@testset "Exponential" begin
r = rand(MersenneTwister(123), Exponential(2))
@test r ≈ rand(MersenneTwister(123), Exponential(β = 2))
@test r ≈ rand(MersenneTwister(123), Exponential(λ = 0.5))
@test r ≈ rand(MersenneTwister(123), Exponential(logβ = log(2)))
@test r ≈ rand(MersenneTwister(123), Exponential(logλ = log(0.5)))
ℓ = logdensity_def(Exponential(2), r)
@test ℓ ≈ logdensity_def(Exponential(β = 2), r)
@test ℓ ≈ logdensity_def(Exponential(λ = 0.5), r)
@test ℓ ≈ logdensity_def(Exponential(logβ = log(2)), r)
@test ℓ ≈ logdensity_def(Exponential(logλ = log(0.5)), r)
end
@testset "NegativeBinomial" begin
D = NegativeBinomial{(:r, :p)}
par = transform(asparams(D), randn(2))
d = D(par)
(r, p) = (par.r, par.p)
logitp = logit(p)
λ = p * r / (1 - p)
logλ = log(λ)
y = rand(d)
ℓ = logdensity_def(NegativeBinomial(; r, p), y)
@test ℓ ≈ logdensity_def(NegativeBinomial(; r, logitp), y)
@test ℓ ≈ logdensity_def(NegativeBinomial(; r, λ), y)
@test ℓ ≈ logdensity_def(NegativeBinomial(; r, logλ), y)
sample1 = rand(MersenneTwister(123), NegativeBinomial(; r, λ))
sample2 = rand(MersenneTwister(123), NegativeBinomial(; r, logλ))
@test sample1 == sample2
@test_broken logdensity_def(Binomial(n, p), CountingBase(ℤ[0:n]), x) ≈
binomlogpdf(n, p, x)
end
@testset "Poisson" begin
sample1 = rand(MersenneTwister(123), Poisson(; logλ = log(100)))
sample2 = rand(MersenneTwister(123), Poisson(; λ = 100))
@test sample1 == sample2
end
@testset "Normal" begin
D = Normal{(:μ, :σ)}
par = transform(asparams(D), randn(2))
d = D(par)
@test params(d) == par
μ = par.μ
σ = par.σ
σ² = σ^2
τ = 1 / σ²
logσ = log(σ)
y = rand(d)
ℓ = logdensityof(Normal(; μ, σ), y)
@test ℓ ≈ logdensityof(Normal(; μ, σ²), y)
@test ℓ ≈ logdensityof(Normal(; μ, τ), y)
@test ℓ ≈ logdensityof(Normal(; μ, logσ), y)
end
@testset "LKJCholesky" begin
D = LKJCholesky{(:k, :η)}
par = transform(asparams(D, (k = 4,)), randn(1))
d = D(merge((k = 4,), par))
# @test params(d) == par
η = par.η
logη = log(η)
y = rand(d)
η = par.η
ℓ = logdensity_def(LKJCholesky(4, η), y)
@test ℓ ≈ logdensity_def(LKJCholesky(k = 4, logη = logη), y)
end
end
@testset "TransitionKernel" begin
κ = kernel(Dirac)
@test rand(κ(1.1)) == 1.1
k1 = kernel() do x
Normal(x, x^2)
end
k2 = kernel(Normal) do x
(μ = x, σ = x^2)
end
k3 = kernel(Normal; μ = identity, σ = abs2)
k4 = kernel(Normal; μ = first, σ = last) do x
(x, x^2)
end
@test k1(3) == k2(3) == k3(3) == k4(3) == Normal(3, 9)
end
@testset "For" begin
FORDISTS = [
For(1:10) do j
Normal(μ = j)
end
For(4, 3) do μ, σ
Normal(μ, σ)
end
For(1:4, 1:4) do μ, σ
Normal(μ, σ)
end
For(eachrow(rand(4, 2))) do x
Normal(x[1], x[2])
end
For(rand(4), rand(4)) do μ, σ
Normal(μ, σ)
end
]
for d in FORDISTS
@info "testing $d"
@test logdensity_def(d, rand(d)) isa Float64
end
end
import MeasureTheory: ⋅
function ⋅(μ::Normal, kernel)
m = kernel(μ)
Normal(μ = m.μ.μ, σ = sqrt(m.μ.σ^2 + m.σ^2))
end
struct AffinePushfwdMap{S,T}
B::S
β::T
end
(a::AffinePushfwdMap)(x) = a.B * x + a.β
function (a::AffinePushfwdMap)(p::Normal)
Normal(μ = a.B * mean(p) + a.β, σ = sqrt(a.B * p.σ^2 * a.B'))
end
@testset "DynamicFor" begin
mc = Chain(Normal(μ = 0.0)) do x
Normal(μ = x)
end
r = rand(mc)
# Check that `r` is now deterministic
@test logdensity_def(mc, take(r, 100)) == logdensity_def(mc, take(r, 100))
d2 = For(r) do x
Normal(μ = x)
end
@test let r2 = rand(d2)
logdensity_def(d2, take(r2, 100)) == logdensity_def(d2, take(r2, 100))
end
end
@testset "Product of Diracs" begin
x = randn(3)
t = as(productmeasure(Dirac.(x)))
@test transform(t, []) == x
end
using DynamicIterators: trace, TimeLift
# @testset "Univariate chain" begin
# ξ0 = 1.
# x = 1.2
# P0 = 1.0
# Φ = 0.8
# β = 0.1
# Q = 0.2
# μ = Normal(μ=ξ0, σ=sqrt(P0))
# kernel = MeasureTheory.kernel(Normal; μ=AffinePushfwdMap(Φ, β), σ=MeasureTheory.AsConst(Q))
# @test (μ ⋅ kernel).μ == Normal(μ = 0.9, σ = 0.824621).μ
# chain = Chain(kernel, μ)
# dyniterate(iter::TimeLift, ::Nothing) = dyniterate(iter, 0=>nothing)
# tr1 = trace(TimeLift(chain), nothing, u -> u[1] > 15)
# tr2 = trace(TimeLift(rand(Random.GLOBAL_RNG, chain)), nothing, u -> u[1] > 15)
# collect(Iterators.take(chain, 10))
# collect(Iterators.take(rand(Random.GLOBAL_RNG, chain), 10))
# end
@testset "rootmeasure/logpdf" begin
x = rand(Normal())
@test logdensity_rel(Normal(), rootmeasure(Normal()), x) ≈ logdensityof(Normal(), x)
end
@testset "Transforms" begin
t = as𝕀
@testset "Pushforward" begin
μ = Normal()
ν = Pushforward(t, μ)
x = rand(μ)
@test logdensity_def(μ, x) ≈ logdensity_def(Pushforward(TV.inverse(t), ν), x)
end
@testset "Pullback" begin
ν = Uniform()
μ = Pullback(t, ν)
y = rand(ν)
@test logdensity_def(ν, y) ≈ logdensity_def(Pullback(TV.inverse(t), μ), y)
end
end
@testset "Likelihood" begin
dps = [(Normal(), 2.0)
# (Pushforward(as((μ=asℝ,)), Normal()^1), (μ=2.0,))
]
ℓs = [
Likelihood(Normal{(:μ,)}, 3.0),
# Likelihood(kernel(Normal, x -> (μ=x, σ=2.0)), 3.0)
]
for (d, p) in dps
for ℓ in ℓs
@test logdensityof(d ⊙ ℓ, p) ≈ logdensityof(d, p) + logdensityof(ℓ.k(p), ℓ.x)
end
end
end
@testset "Reproducibility" begin
# NOTE: The `test_broken` below are mostly because of the change to `AffinePushfwd`.
# For example, `Normal{(:μ,:σ)}` is now `AffinePushfwd{(:μ,:σ), Normal{()}}`.
# The problem is not really with these measures, but with the tests
# themselves.
#
# We should instead probably be doing e.g.
# `D = typeof(Normal(μ=0.3, σ=4.1))`
function repro(D, args, nt = NamedTuple())
t = asparams(D{args}, nt)
d = D(transform(t, randn(t.dimension)))
r(d) = rand(Random.MersenneTwister(1), d)
logdensity_def(d, r(d)) == logdensity_def(d, r(d))
end
@testset "Bernoulli" begin
@test repro(Bernoulli, (:p,))
end
@testset "Binomial" begin
@test repro(Binomial, (:n, :p), (n = 10,))
end
@testset "Beta" begin
@test repro(Beta, (:α, :β))
end
@testset "BetaBinomial" begin
@test repro(BetaBinomial, (:n, :α, :β), (n = 10,))
end
@testset "Cauchy" begin
@test_broken repro(Cauchy, (:μ, :σ))
end
@testset "Dirichlet" begin
@test_broken repro(Dirichlet, (:p,))
end
@testset "Exponential" begin
@test repro(Exponential, (:λ,))
end
@testset "Gumbel" begin
@test_broken repro(Gumbel, (:μ, :σ))
end
@testset "InverseGamma" begin
@test_broken repro(InverseGamma, (:p,))
end
@testset "Laplace" begin
@test_broken repro(Laplace, (:μ, :σ))
end
@testset "LKJCholesky" begin
@test repro(LKJCholesky, (:k, :η), (k = 3,))
end
@testset "Multinomial" begin
@test_broken repro(Multinomial, (:n, :p))
end
@testset "MvNormal" begin
@test_broken repro(MvNormal, (:μ,))
σ = LowerTriangular(randn(3, 3))
Σ = σ * σ'
d = MvNormal(σ = σ)
x = rand(d)
@test logdensityof(d, x) ≈ logdensityof(Dists.MvNormal(Σ), x)
@test logdensityof(MvNormal(zeros(3), σ), x) ≈ logdensityof(d, x)
end
@testset "NegativeBinomial" begin
@test repro(NegativeBinomial, (:r, :p))
end
@testset "Normal" begin
@test repro(Normal, (:μ, :σ))
end
@testset "Poisson" begin
@test repro(Poisson, (:λ,))
end
@testset "StudentT" begin
@test_broken repro(StudentT, (:ν, :μ))
end
@testset "Uniform" begin
@test repro(Uniform, ())
end
end
@testset "ProductMeasure" begin
d = For(1:10) do j
Poisson(exp(j))
end
x = Vector{Int16}(undef, 10)
@test rand!(d, x) isa Vector
@test rand(d) isa Vector
@testset "Indexed by Generator" begin
d = For((j^2 for j in 1:10)) do i
Poisson(i)
end
x = Vector{Int16}(undef, 10)
@test rand!(d, x) isa Vector
@test rand(d) isa MeasureTheory.RealizedSamples
end
@testset "Indexed by multiple Ints" begin
d = For(2, 3) do μ, σ
Normal(μ, σ)
end
x = Matrix{Float16}(undef, 2, 3)
@test rand!(d, x) isa Matrix
@test_broken rand(d) isa Matrix{Float16}
end
end
@testset "Show methods" begin
@testset "PowerMeasure" begin
@test repr(Lebesgue(ℝ)^5) == "Lebesgue(ℝ) ^ 5"
@test repr(Lebesgue(ℝ)^(3, 2)) == "Lebesgue(ℝ) ^ (3, 2)"
end
end
@testset "Half measures" begin
@testset "HalfNormal" begin
d = Normal(σ = 3)
h = HalfNormal(3)
x = rand(h)
@test densityof(h, x) ≈ 2 * densityof(d, x)
end
@testset "HalfCauchy" begin
d = Cauchy(σ = 3)
h = HalfCauchy(3)
x = rand(h)
@test densityof(h, x) ≈ 2 * densityof(d, x)
end
@testset "HalfStudentT" begin
d = StudentT(ν = 2, σ = 3)
h = HalfStudentT(2, 3)
x = rand(h)
@test densityof(h, x) ≈ 2 * densityof(d, x)
end
end
@testset "MvNormal" begin
Q, R = qr(randn(4, 2))
D = Diagonal(sign.(diag(R)))
Q = Matrix(Q) * D
R = D * R
z = randn(2)
ℓ = logdensityof(MvNormal((σ = R,)), z)
@test ℓ ≈ logdensityof(Dists.MvNormal(R * R'), z)
@test ℓ ≈ logdensityof(MvNormal((σ = Q * R,)), Q * z)
end
@testset "AffinePushfwd" begin
testmeasures = [
(Normal, NamedTuple())
(Cauchy, NamedTuple())
(Laplace, NamedTuple())
(StudentT, (ν = 3,))
]
using Test
function test_noerrors(d)
x = rand(d)
@test logdensityof(d, x) isa Real
@test logdensity_def(d, x) isa Real
end
for (M, nt) in testmeasures
for p in [(μ = 1,), (μ = 1, σ = 2), (μ = 1, λ = 2), (σ = 2,), (λ = 2,)]
d = M(merge(nt, p))
@info "Testing $d"
test_noerrors(d)
end
# for n in 1:3
# @show n
# for k in 1:n
# @show k
# pars = [(μ=randn(n),), (μ=randn(n),σ=randn(n,k)), (μ=randn(n),λ=randn(k,n)), (σ=randn(n,k),), (λ=randn(k,n),)]
# for p in pars
# @show p
# d = M(merge(nt, p))
# test_noerrors(d)
# end
# end
# end
end
end
@testset "AffineTransform" begin
f = AffineTransform((μ = 3, σ = 2))
@test f(inverse(f)(1)) == 1
@test inverse(f)(f(1)) == 1
f = AffineTransform((μ = 3, λ = 2))
@test f(inverse(f)(1)) == 1
@test inverse(f)(f(1)) == 1
f = AffineTransform((σ = 2,))
@test f(inverse(f)(1)) == 1
@test inverse(f)(f(1)) == 1
f = AffineTransform((λ = 2,))
@test f(inverse(f)(1)) == 1
@test inverse(f)(f(1)) == 1
f = AffineTransform((μ = 3,))
@test f(inverse(f)(1)) == 1
@test inverse(f)(f(1)) == 1
f = AffineTransform((σ = [1 2; 2 1],))
@test f(inverse(f)([1 2; 2 1])) == [1 2; 2 1]
@test inverse(f)(f([1 2; 2 1])) == [1 2; 2 1]
end
@testset "AffinePushfwd" begin
unif = ∫(x -> 0 < x < 1, Lebesgue(ℝ))
f1 = AffineTransform((μ = 3.0, σ = 2.0))
f2 = AffineTransform((μ = 3.0, λ = 2.0))
f3 = AffineTransform((μ = 3.0,))
f4 = AffineTransform((σ = 2.0,))
f5 = AffineTransform((λ = 2.0,))
for f in [f1, f2, f3, f4, f5]
par = getfield(f, :par)
@test AffinePushfwd(par)(unif) == AffinePushfwd(f, unif)
@test densityof(AffinePushfwd(f, AffinePushfwd(inverse(f), unif)), 0.5) == 1
end
d = ∫exp(x -> -x^2, Lebesgue(ℝ))
μ = randn(3)
# σ = LowerTriangular(randn(3, 3))
σ = let x = randn(10, 3)
cholesky(x' * x).L
end
λ = inv(σ)
x = randn(3)
@test logdensity_def(AffinePushfwd((μ = μ, σ = σ), d^3), x) ≈
logdensity_def(AffinePushfwd((μ = μ, λ = λ), d^3), x)
@test logdensity_def(AffinePushfwd((σ = σ,), d^3), x) ≈
logdensity_def(AffinePushfwd((λ = λ,), d^3), x)
@test logdensity_def(AffinePushfwd((μ = μ,), d^3), x) ≈ logdensity_def(d^3, x - μ)
d = ∫exp(x -> -x^2, Lebesgue(ℝ))
a = AffinePushfwd((σ = [1 0]',), d^1)
x = randn(2)
y = randn(1)
@test logdensityof(a, x) ≈ logdensityof(d, inverse(a.f)(x)[1])
@test logdensityof(a, a.f(y)) ≈ logdensityof(d^1, y)
b = AffinePushfwd((λ = [1 0]'',), d^1)
@test logdensityof(b, x) ≈ logdensityof(d, inverse(b.f)(x)[1])
@test logdensityof(b, b.f(y)) ≈ logdensityof(d^1, y)
end
@testset "IfElseMeasure" begin
p = rand()
x = randn()
@test let
a = logdensityof(IfElse.ifelse(Bernoulli(p), Normal(), Normal()), x)
b = logdensityof(Normal(), x)
a ≈ b
end
@test let
a = logdensityof(IfElse.ifelse(Bernoulli(p), Normal(2, 3), Normal()), x)
b = logdensityof(p * Normal(2, 3) + (1 - p) * Normal(), x)
a ≈ b
end
end
@testset "https://github.com/JuliaMath/MeasureTheory.jl/issues/217" begin
d = For(rand(3), rand(3)) do x, y
Normal(x, y)
end
x = rand(d)
@test logdensityof(d, x) isa Real
end
@testset "Normal smf" begin
@test smf(Normal(0, 1), 0) == 0.5
@test smf.((Normal(0, 1),), [0, 0]) == [0.5, 0.5]
end
affinepars_1d = [
(;)
(μ = randn(),)
(σ = randn(),)
(λ = randn(),)
(μ = randn(), σ = randn())
(μ = randn(), λ = randn())
]
smf_measures =
[
[Bernoulli(), Bernoulli(rand()), Bernoulli(logitp = randn())]
[Beta(rand(), rand())]
# [BetaBinomial(rand(5:20), 2 * rand(), 2 * rand())]
# [Binomial(rand(5:20), rand())]
Cauchy.(affinepars_1d)
Normal.(affinepars_1d)
StudentT.(merge.(Ref((ν = 1 + 2 * rand(),)), affinepars_1d))
] |> vcat
@testset "smf" begin
for μ in smf_measures
test_smf(μ)
end
end
@testset "more interface tests" begin
for μ in smf_measures
test_interface(μ)
end
end
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | docs | 2871 | # MeasureTheory
[](https://JuliaMath.github.io/MeasureTheory.jl/stable)
[](https://JuliaMath.github.io/MeasureTheory.jl/dev)
[](https://github.com/JuliaMath/MeasureTheory.jl/actions)
[](https://codecov.io/gh/JuliaMath/MeasureTheory.jl)
[](https://doi.org/10.21105/jcon.00092)
`MeasureTheory.jl` is a package for building and reasoning about measures.
## Why?
Probabilistic programming and statistical computing are vibrant areas in the development of the Julia programming language, but the underlying infrastructure dramatically predates recent developments. The goal of MeasureTheory.jl is to provide Julia with the right vocabulary and tools for these tasks. In this package we introduce a well-chosen foundational primitives centered around the notion of measure, density and conditional probability with powerful combinators and transforms intended to power and unify work on probabilistic programming and statistical computing within Julia. Check out our [JuliaCon 2021 article](https://doi.org/10.21105/jcon.00092) detailing our ideas for and with this package.
## Getting started
To install `MeasureTheory.jl`, open the Julia Pkg REPL (by typing `]` in the standard REPL) and run
```julia
pkg> add MeasureTheory
```
To get an idea of the possibilities offered by this package, go to the [documentation](https://JuliaMath.github.io/MeasureTheory.jl/stable).
## Coordination and support
For interaction and shorter usage questions, there is the dedicated channel [#measuretheory on Julia's Zulip chat julialang.zulipchat.com](https://julialang.zulipchat.com/#narrow/stream/259730-measuretheory.2Ejl) and the #measuretheory channel on the [Julia language Slack chat](https://julialang.org/slack/) and for broader discussions [Julia's discourse forum](https://discourse.julialang.org).
Development takes place on Github with [Github's issue ticker](https://github.com/JuliaMath/MeasureTheory.jl/issues) for bug reports and coordination.
We adhere to the [community standards set forward by the Julia community.](https://julialang.org/community/standards/)
## Support
[<img src=https://user-images.githubusercontent.com/1184449/140397787-9b7e3eb7-49cd-4c63-8f3c-e5cdc41e393d.png width="49%">](https://informativeprior.com/) [<img src=https://planting.space/sponsor/PlantingSpace-sponsor-3.png width=49%>](https://planting.space)
## Stargazers over time
[](https://starchart.cc/JuliaMath/MeasureTheory.jl)
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | docs | 5130 | # Adding a New Measure
## Parameterized Measures
This is by far the most common kind of measure, and is especially useful as a way to describe families of probability distributions.
### Declaring a Parameterized Measure
To start, declare a `@parameterized`. For example, `Normal` is declared as
```julia
@parameterized Normal(μ,σ) ≪ (1/sqrt2π) * Lebesgue(ℝ)
```
[`ℝ` is typed as `\bbR <TAB>`]
A `ParameterizedMeasure` can have multiple parameterizations, which as dispatched according to the names of the parameters. The `(μ,σ)` here specifies names to assign if none are given. So for example,
```julia
julia> Normal(-3.0, 2.1)
Normal(μ = -3.0, σ = 2.1)
```
The right side, `(1/sqrt2π) * Lebesgue(ℝ)`, gives the _base measure_. `Lebesgue` in this case is the technical name for the measure associating an interval of real numbers to its length. The `(1/sqrt2π)` comes from the normalization constant in the probability density function,
```math
f_{\text{Normal}}(x|μ,σ) = \frac{1}{σ \sqrt{2 \pi}} e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2}\ \ .
```
Making this part of the base measure allows us to avoid including it in every computation.
The `≪` (typed as `\ll <TAB>`) can be read "is dominated by". This just means that any set for which the base measure is zero must also have zero measure in what we're defining.
### Defining a Log Density
Most computations involve log-densities rather than densities themselves, so these are our first priority. `density(d,x)` will default to `exp(logdensity_def(d,x))`, but you can add a separate method if it's more efficient.
The definition is simple:
```julia
logdensity_def(d::Normal{()} , x) = - x^2 / 2
```
There are a few things here worth noting.
First, we dispatch by the names of `d` (here there are none), and the type of `x` is not specified.
Also, there's nothing here about `μ` and `σ`. These _location-scale parameters_ behave exactly the same across lots of distributions, so we have a macro to add them:
```julia
@μσ_methods Normal()
```
Let's look at another example, the Beta distribution. Here the base measure is `Lebesgue(𝕀)` (support is the unit interval). The log-density is
```julia
@inline function logdensity_def(d::Beta{(:α, :β)}, x)
return (d.α - 1) * log(x) + (d.β - 1) * log(1 - x) - logbeta(d.α, d.β)
end
```
Note that when possible, we avoid extra control flow for checking that `x` is in the support. In applications, log-densities are often evaluated only on the support by design. Such checks should be implemented at a higher level whenever there is any doubt.
Finally, note that in both of these examples, the log-density has a relatively direct algebraic form. It's imnportant to have this whenever possible to allow for symbolic manipulation (using libraries like `SymolicUtils.jl`) and efficient automatic differentiation.
### Random Sampling
For univariate distributions, you should define a `Base.rand` method that uses three arguments:
- A `Random.AbstractRNG` to use for randomization,
- A type to be returned, and
- The measure to sample from.
For our `Normal` example, this is
```julia
Base.rand(rng::Random.AbstractRNG, T::Type, d::Normal{()}) = randn(rng, T)
```
Again, for location-scale families, other methods are derived automatically.
For multivariate distributions (or anything that requires heap allocation), you should instead define a `Random.rand!` method. This also takes three arguments, different from `rand`:
- The `Random.AbstractRNG`,
- The measure to sample from, and
- Where to store the result.
For example, here's the implementation for `ProductMeasure`:
```julia
@propagate_inbounds function Random.rand!(rng::AbstractRNG, d::ProductMeasure, x::AbstractArray)
@boundscheck size(d.data) == size(x) || throw(BoundsError)
@inbounds for j in eachindex(x)
x[j] = rand(rng, eltype(x), d.data[j])
end
x
end
```
Note that in this example, `d.data[j]` might itself require allocation. This implementation is likely to change in the future to make it easier to define nested structures without any need for ongoing allocation.
## Primitive Measures
Most measures are defined in terms of a `logdensity` with respect to some other measure, its `basemeasure`. But how is _that_ measure defined? It can't be "densities all the way down"; at some point, the chain has to stop.
A _primitive_ measure is just a measure that has itself as its own base measure. Note that this also means its log-density is always zero.
Here's the implementation of `Lebesgue`:
```julia
struct Lebesgue{X} <: AbstractMeasure end
Lebesgue(X) = Lebesgue{X}()
basemeasure(μ::Lebesgue) = μ
isprimitive(::Lebesgue) = true
gentype(::Lebesgue{ℝ}) = Float64
gentype(::Lebesgue{ℝ₊}) = Float64
gentype(::Lebesgue{𝕀}) = Float64
logdensity_def(::Lebesgue, x) = zero(float(x))
```
We haven't yet talked about `gentype`. When you call `rand` without specifying a type, there needs to be a default. That default is the `gentype`. This only needs to be defined for primitive measures, because others will fall back on
```julia
gentype(μ::AbstractMeasure) = gentype(basemeasure(μ))
```
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | docs | 5265 | # Affine Transformations
It's very common for measures to use parameters `μ` and `σ`, for example as in `Normal(μ=3, σ=4)` or `StudentT(ν=1, μ=3, σ=4)`. In this context, `μ` and `σ` need not always refer to the mean and standard deviation (the `StudentT` measure specified above is equivalent to a [Cauchy](https://en.wikipedia.org/wiki/Cauchy_distribution) measure, so both mean and standard deviation are undefined).
In general, `μ` is a "location parameter", and `σ` is a "scale parameter". Together these parameters determine an affine transformation.
```math
f(z) = σ z + μ
```
Starting with the above definition, we'll use ``z`` to represent an "un-transformed" variable, typically coming from a measure which has neither a location nor a scale parameter, for example `Normal()`.
Affine transformations are often ambiguously referred as "linear transformations". In fact, an affine transformation is ["the composition of two functions: a translation and a linear map"](https://en.wikipedia.org/wiki/Affine_transformation#Representation) in the stricter algebraic sense: For a function `f` to be linear requires
``f(ax + by) == a f(x) + b f(y)``
for scalars ``a`` and ``b``. For an affine function
``f(z) = σ * z + μ``, where the linear map is defined as ``σ`` and the translation defined as ``μ``,
linearity holds only if the translation component ``μ`` is equal to zero.
## Cholesky-based parameterizations
If the "un-transformed" `z` is univariate, things are relatively simple. But it's important our approach handle the multivariate case as well.
In the literature, it's common for a multivariate normal distribution to be parameterized by a mean `μ` and covariance matrix `Σ`. This is mathematically convenient, but leads to an ``O(n^3)`` [Cholesky decomposition](https://en.wikipedia.org/wiki/Cholesky_decomposition), which becomes a significant bottleneck to compute as ``n`` gets large.
While MeasureTheory.jl includes (or will include) a parameterization using `Σ`, we prefer to work in terms of its Cholesky decomposition ``σ``.
To see the relationship between our ``σ`` parameterization and the likely more familiar ``Σ`` parameterization, let ``σ`` be a lower-triangular matrix satisfying
```math
σ σᵗ = Σ
```
Then given a (multivariate) standard normal ``z``, the covariance matrix of ``σ z + μ`` is
```math
𝕍[σ z + μ] = Σ
```
The one-dimensional case where we have
```math
𝕍[σ z + μ] = σ²
```
shows that the lower Cholesky factor of the covariance generalizes the concept of standard deviation, completing the link between ``σ`` and `Σ`.
## The "Cholesky precision" parameterization
The ``(μ,σ)`` parameterization is especially convenient for random sampling. Any measure `z ~ Normal()` determines an `x ~ Normal(μ,σ)` through the affine transformation
```math
x = σ z + μ
```
The log-density transformation of a `Normal` with parameters μ, σ does not follow as directly. Starting with an ``x``, we need to find ``z`` using
```math
z = σ⁻¹ (x - μ)
```
so the log-density is
```julia
logdensity_def(d::Normal{(:μ,:σ)}, x) = logdensity_def(d.σ \ (x - d.μ)) - logdet(d.σ)
```
Here the `- logdet(σ)` is the "log absolute Jacobian", required to account for the stretching of the space.
The above requires solving a linear system, which adds some overhead. Even with the convenience of a lower triangular system, it's still not quite as efficient as multiplication.
In addition to the covariance ``Σ``, it's also common to parameterize a multivariate normal by its _precision matrix_, defined as the inverse of the covariance matrix, ``Ω = Σ⁻¹``. Similar to our use of ``σ`` for the lower Cholesky factor of `Σ`, we'll use ``λ`` for the lower Cholesky factor of ``Ω``.
This parameterization enables more efficient calculation of the log-density using only multiplication and addition,
```julia
logdensity_def(d::Normal{(:μ,:λ)}, x) = logdensity_def(d.λ * (x - d.μ)) + logdet(d.λ)
```
## `AffineTransform`
Transforms like ``z → σ z + μ`` and ``z → λ \ z + μ`` can be specified in MeasureTheory.jl using an `AffineTransform`. For example,
```julia
julia> f = AffineTransform((μ=3.,σ=2.))
AffineTransform{(:μ, :σ), Tuple{Float64, Float64}}((μ = 3.0, σ = 2.0))
julia> f(1.0)
5.0
```
In the univariate case this is relatively simple to invert. But if `σ` is a matrix, matrix inversion becomes necessary. This is not always possible as lower triangular matrices are not closed under matrix inversion and as such are not guaranteed to exist.
With multiple parameterizations of a given family of measures, we can work around these issues. The inverse transform of a ``(μ,σ)`` transform will be in terms of ``(μ,λ)``, and vice-versa. So
```julia
julia> f⁻¹ = inverse(f)
AffineTransform{(:μ, :λ), Tuple{Float64, Float64}}((μ = -1.5, λ = 2.0))
julia> f(f⁻¹(4))
4.0
julia> f⁻¹(f(4))
4.0
```
## `AffinePushfwd`
Of particular interest (the whole point of all of this, really) is to have a natural way to work with affine transformations of measures. In accordance with the principle of "common things should have shorter names", we call this `AffinePushfwd`.
The structure of `AffinePushfwd` is relatively simple:
```julia
struct AffinePushfwd{N,M,T} <: AbstractMeasure
f::AffineTransform{N,T}
parent::M
end
``` | MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | docs | 59 | # MeasureBase API
```@autodocs
Modules = [MeasureBase]
``` | MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | docs | 63 | # MeasureTheory API
```@autodocs
Modules = [MeasureTheory]
``` | MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | docs | 1132 | ```@meta
CurrentModule = MeasureTheory
```
# Home
`MeasureTheory.jl` is a package for building and reasoning about measures.
## Why?
A distribution (as provided by `Distributions.jl`) is also called a _probability measure_, and carries with it the constraint of adding (or integrating) to one. Statistical work usually requires this "at the end of the day", but enforcing it at each step of a computation can have considerable overhead. For instance, Bayesian modeling often requires working with unnormalized posterior densities or improper priors.
As a generalization of the concept of volume, measures also have applications outside of probability theory.
## Getting started
To install `MeasureTheory.jl`, open the Julia Pkg REPL (by typing `]` in the standard REPL) and run
```julia
pkg> add MeasureTheory
```
To get an idea of the possibilities offered by this package, go to the [documentation](https://cscherrer.github.io/MeasureTheory.jl/stable).
To know more about the underlying theory and its applications to probabilistic programming, check out our [JuliaCon 2021 submission](https://arxiv.org/abs/2110.00602). | MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 0.19.0 | 923a7b76a9d4be260d4225db1703cd30472b60cc | docs | 7848 | # MeasureTheory
[](https://cscherrer.github.io/MeasureTheory.jl/stable)
[](https://cscherrer.github.io/MeasureTheory.jl/dev)
[](https://github.com/JuliaMath/MeasureTheory.jl/actions)
[](https://codecov.io/gh/JuliaMath/MeasureTheory.jl)
Check out our [JuliaCon submission](https://github.com/JuliaMath/MeasureTheory.jl/blob/paper/paper/paper.pdf)
`MeasureTheory.jl` is a package for building and reasoning about measures.
## Why?
A distribution (as in Distributions.jl) is also called a _probability measure_, and carries with it the constraint of adding (or integrating) to one. Statistical work usually requires this "at the end of the day", but enforcing it at each step of a computation can have considerable overhead.
As a generalization of the concept of volume, measures also have applications outside of probability theory.
## Goals
### Distributions.jl Compatibility
Distirbutions.jl is wildly popular, and is large enough that replacing it all at once would be a major undertaking.
Instead, we should aim to make any Distribution easily usable as a Measure. We'll most likely implement this using an `IsMeasure` trait.
### Absolute Continuity
For two measures μ, ν on a set X, we say μ is _absolutely continuous_ with respect to ν if ν(A)=0 implies μ(A)=0 for every measurable subset A of X.
The following are equivalent:
1. μ ≪ ν
2. μ is absolutely continuous wrt ν
3. There exists a function f such that μ = ∫f dν
So we'll need a `≪` operator. Note that `≪` is not antisymmetric; it's common for both `μ ≪ ν` and `ν ≪ μ` to hold.
If `μ ≪ ν` and `ν ≪ μ`, we say μ and ν are _equivalent_ and write `μ ≃ ν`. (This is often written as `μ ~ ν`, but we reserve `~` for random variables following a distribution, as is common in the literature and probabilistic programming languages.)
If we collapse the equivalence classes (under ≃), `≪` becomes a partial order.
_We need ≃ and ≪ to be fast_. If the support of a measure can be determined statically from its type, we can define ≃ and ≪ as generated functions.
### Radon-Nikodym Derivatives
One of the equivalent conditions above was "There exists a function f such that μ = ∫f dν". In this case, `f` is called a _Radon-Nikodym derivative_, or (less formally) a _density_. In this case we often write `f = dμ/dν`.
For any measures μ and ν with μ≪ν, we should be able to represent this.
### Integration
More generally, we'll need to be able to represent change of measure as above, `∫f dν`. We'll need an `Integral` type
```julia
struct Integral{F,M}
f::F
μ::M
end
```
Then we'll have a function `∫`. For cases where μ = ∫f dν, `∫(f, ν)` will just return `μ` (we can do this based on the types). For unknown cases (which will be most of them), we'll return `∫(f, ν) = Integral(f, ν)`.
### Measure Combinators
It should be very easy to build new measures from existing ones. This can be done using, for example,
- restriction
- product measure
- superposition
- pushforward
There's also function spaces, but this gets much trickier. We'll need to determine a good way to reason about this.
### More???
This is very much a work in progress. If there are things you think we should have as goals, please add an issue with the `goals` label.
------------------
## Old Stuff
**WARNING: The current README is very developer-oriented. Casual use will be much simpler**
For an example, let's walk through the construction of `src/probability/Normal`.
First, we have
```julia
@measure Normal
```
this is just a little helper function, and is equivalent to
> TODO: Clean up
```julia
quote
#= /home/chad/git/Measures.jl/src/Measures.jl:55 =#
struct Normal{var"#10#P", var"#11#X"} <: Measures.AbstractMeasure{var"#11#X"}
#= /home/chad/git/Measures.jl/src/Measures.jl:56 =#
par::var"#10#P"
end
#= /home/chad/git/Measures.jl/src/Measures.jl:59 =#
function Normal(var"#13#nt"::Measures.NamedTuple)
#= /home/chad/git/Measures.jl/src/Measures.jl:59 =#
#= /home/chad/git/Measures.jl/src/Measures.jl:60 =#
var"#12#P" = Measures.typeof(var"#13#nt")
#= /home/chad/git/Measures.jl/src/Measures.jl:61 =#
return Normal{var"#12#P", Measures.eltype(Normal{var"#12#P"})}
end
#= /home/chad/git/Measures.jl/src/Measures.jl:64 =#
Normal(; var"#14#kwargs"...) = begin
#= /home/chad/git/Measures.jl/src/Measures.jl:64 =#
Normal((; var"#14#kwargs"...))
end
#= /home/chad/git/Measures.jl/src/Measures.jl:66 =#
(var"#8#basemeasure"(var"#15#μ"::Normal{var"#16#P", var"#17#X"}) where {var"#16#P", var"#17#X"}) = begin
#= /home/chad/git/Measures.jl/src/Measures.jl:66 =#
Lebesgue{var"#17#X"}
end
#= /home/chad/git/Measures.jl/src/Measures.jl:68 =#
(var"#9#≪"(::Normal{var"#19#P", var"#20#X"}, ::Lebesgue{var"#20#X"}) where {var"#19#P", var"#20#X"}) = begin
#= /home/chad/git/Measures.jl/src/Measures.jl:68 =#
true
end
end
```
Next we have
```julia
Normal(μ::Real, σ::Real) = Normal(μ=μ, σ=σ)
```
This defines a default. If we just give two numbers as arguments (but no names), we'll assume this parameterization.
Next need to define a `eltype` function. This takes a constructor (here `Normal`) and a parameter, and tells us the space for which this defines a measure. Let's define this in terms of the types of the parameters,
```julia
eltype(::Type{Normal}, ::Type{NamedTuple{(:μ, :σ), Tuple{A, B}}}) where {A,B} = promote_type(A,B)
```
That's still kind of boring, so let's build the density. For this, we need to implement the trait
```julia
@trait Density{M,X} where {X = domain{M}} begin
basemeasure :: [M] => Measure{X}
logdensity :: [M, X] => Real
end
```
A density doesn't exist by itself, but is defined relative to some _base measure_. For a normal distribution this is just Lebesgue measure on the real numbers. That, together with the usual Gaussian log-density, gives us
```julia
@implement Density{Normal{X,P},X} where {X, P <: NamedTuple{(:μ, :σ)}} begin
basemeasure(d) = Lebesgue(X)
logdensity_def(d, x) = - (log(2) + log(π)) / 2 - log(d.par.σ) - (x - d.par.μ)^2 / (2 * d.par.σ^2)
end
```
Now we can compute the log-density:
```julia
julia> logdensity_def(Normal(0.0, 0.5), 1.0)
-2.2257913526447273
```
And just to check that our default is working,
```julia
julia> logdensity_def(Normal(μ=0.0, σ=0.5), 1.0)
-2.2257913526447273
```
What about other parameterizations? Sure, no problem. Here's a way to write this for mean `μ` (as before), but using the _precision_ (inverse of the variance) instead of standard deviation:
```julia
eltype(::Type{Normal}, ::Type{NamedTuple{(:μ, :τ), Tuple{A, B}}}) where {A,B} = promote_type(A,B)
@implement Density{Normal{X,P},X} where {X, P <: NamedTuple{(:μ, :τ)}} begin
basemeasure(d) = Lebesgue(X)
logdensity_def(d, x) = - (log(2) + log(π) - log(d.par.τ) + d.par.τ * (x - d.par.μ)^2) / 2
end
```
And another check:
```julia
julia> logdensity_def(Normal(μ=0.0, τ=4.0), 1.0)
-2.2257913526447273
```
We can combine measures in a few ways, for now just _scaling_ and _superposition_:
```julia
julia> 2.0*Lebesgue(Float64) + Normal(0.0,1.0)
SuperpositionMeasure{Float64,2}((MeasureTheory.WeightedMeasure{Float64,Float64}(2.0, Lebesgue{Float64}()), Normal{NamedTuple{(:μ, :σ),Tuple{Float64,Float64}},Float64}((μ = 0.0, σ = 1.0))))
```
---
For an easy way to find expressions for the common log-densities, see [this gist](https://gist.github.com/cscherrer/47f0fc7597b4ffc11186d54cc4d8e577)
| MeasureTheory | https://github.com/JuliaMath/MeasureTheory.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 6647 | ######### Jags program example ###########
using StatsPlots, Jags, Statistics
ProjDir = joinpath(dirname(@__FILE__))
cd(ProjDir) do
bones = "
model {
for (i in 1:nChild) {
theta[i] ~ dnorm(0.0, 0.001);
for (j in 1:nInd) {
# Cumulative probability of > grade k given theta
for (k in 1:(ncat[j]-1)) {
logit(Q[i,j,k]) <- delta[j]*(theta[i] - gamma[j,k]);
}
Q[i,j,ncat[j]] <- 0;
}
for (j in 1:nInd) {
# Probability of observing grade k given theta
p[i,j,1] <- 1 - Q[i,j,1];
for (k in 2:ncat[j]) {
p[i,j,k] <- Q[i,j,(k-1)] - Q[i,j,k];
}
grade[i,j] ~ dcat(p[i,j,1:ncat[j]]);
}
}
}
"
data = Dict{String, Any}()
data["nChild"] = 13
data["nInd"] = 34
data["gamma"] = reshape([
0.7425, 10.267, 10.5215, 9.3877, 0.2593, -0.5998,
10.5891, 6.6701, 8.8921, 12.4275, 12.4788, 13.7778, 5.8374, 6.9485,
13.7184, 14.3476, 4.8066, 9.1037, 10.7483, 0.3887, 3.2573, 11.6273,
15.8842, 14.8926, 15.5487, 15.4091, 3.9216, 15.475, 0.4927, 1.3059,
1.5012, 0.8021, 5.0022, 4.0168, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1.0153, 7.0421, 14.4242,
17.4685, 16.7409, 16.872, 17.0061, 5.2099, 16.9406, 1.3556, 1.8793,
1.8902, 2.3873, 6.3704, 5.1537, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, 17.4944, 2.3016, 2.497, 2.3689, 3.9525, 8.2832, 7.1053,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 3.2535, 3.2306,
2.9495, 5.3198, 10.4988, 10.3038], 34, 4)
data["delta"] = [
2.9541, 0.6603, 0.7965, 1.0495, 5.7874, 3.8376, 0.6324, 0.8272,
0.6968, 0.8747, 0.8136, 0.8246, 0.6711, 0.978, 1.1528, 1.6923,
1.0331, 0.5381, 1.0688, 8.1123, 0.9974, 1.2656, 1.1802, 1.368,
1.5435, 1.5006, 1.6766, 1.4297, 3.385, 3.3085, 3.4007, 2.0906,
1.0954, 1.5329]
data["ncat"] = [
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3,
3, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5]
data["grade"] = reshape([
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, NaN,
2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
1, 1, 1, 1, 1, 1, 2, 2, 2, NaN, 2, 2, 1, 1, 1, 1, 1, 2, 1, 2,
2, 2, 2, 2, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1,
1, 1, 1, NaN, NaN, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, NaN, NaN, 1,
1, NaN, 2, NaN, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, NaN, 2, 2, 1, 1, 1,
NaN, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2,
2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, NaN, 2, 2, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, NaN, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,
2, 2, 1, 1, 1, 1, 1, NaN, NaN, 2, 1, NaN, 1, 2, 2, 1, 1, 1, 1, 1,
1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
1, 1, 1, 1, 2, 2, 3, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, NaN, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, NaN, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, NaN, NaN, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 2, NaN, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1,
1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 4, 2, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 3, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 1, 1, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2,
2, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 2, 3, 3, 3, 4,
5, 5, 5, 5, 1, 1, 1, 1, 3, 3, 3, 4, 4, 5, 5, 5, 5], 13, 34)
inits = Dict{String, Any}()
inits["theta"] = [0.5, 1, 2, 3, 5, 6, 7, 8, 9, 12, 13, 16, 18]
inits["grade"] = reshape([
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, 1,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, 1, NaN, NaN, 1,
NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN, NaN, NaN,
NaN, NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, 1, 1, NaN, NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, 1, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN], 13, 34)
monitors = Dict{String, Bool}("theta" => true)
jagsmodel = Jagsmodel(name="bones1",
model=bones,
monitor=monitors,
#ncommands=4, nchains=1,
#adapt=1000, nsamples=10000, thin=1,
#deviance=true, dic=true, popt=true,
#updatedatafile=true, updateinitfiles=true,
#pdir=ProjDir
);
println("\nJagsmodel that will be used:")
jagsmodel |> display
@time sim = jags(jagsmodel, data, [inits], ProjDir)
println()
## Plotting
p = plot(sim)
end #cd
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 7219 | ######### Jags program example ###########
using StatsPlots, Jags, Statistics
ProjDir = dirname(@__FILE__)
cd(ProjDir) do
bones = "
model {
for (i in 1:nChild) {
theta[i] ~ dnorm(0.0, 0.001);
for (j in 1:nInd) {
# Cumulative probability of > grade k given theta
for (k in 1:(ncat[j]-1)) {
logit(Q[i,j,k]) <- delta[j]*(theta[i] - gamma[j,k]);
}
Q[i,j,ncat[j]] <- 0;
}
for (j in 1:nInd) {
# Probability of observing grade k given theta
p[i,j,1] <- 1 - Q[i,j,1];
for (k in 2:ncat[j]) {
p[i,j,k] <- Q[i,j,(k-1)] - Q[i,j,k];
}
grade[i,j] ~ dcat(p[i,j,1:ncat[j]]);
}
}
}
"
data = Dict{String, Any}()
data["nChild"] = 13
data["nInd"] = 34
data["gamma"] = reshape([
0.7425, 10.267, 10.5215, 9.3877, 0.2593, -0.5998,
10.5891, 6.6701, 8.8921, 12.4275, 12.4788, 13.7778, 5.8374, 6.9485,
13.7184, 14.3476, 4.8066, 9.1037, 10.7483, 0.3887, 3.2573, 11.6273,
15.8842, 14.8926, 15.5487, 15.4091, 3.9216, 15.475, 0.4927, 1.3059,
1.5012, 0.8021, 5.0022, 4.0168, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1.0153, 7.0421, 14.4242,
17.4685, 16.7409, 16.872, 17.0061, 5.2099, 16.9406, 1.3556, 1.8793,
1.8902, 2.3873, 6.3704, 5.1537, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, 17.4944, 2.3016, 2.497, 2.3689, 3.9525, 8.2832, 7.1053,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 3.2535, 3.2306,
2.9495, 5.3198, 10.4988, 10.3038], 34, 4)
data["delta"] = [
2.9541, 0.6603, 0.7965, 1.0495, 5.7874, 3.8376, 0.6324, 0.8272,
0.6968, 0.8747, 0.8136, 0.8246, 0.6711, 0.978, 1.1528, 1.6923,
1.0331, 0.5381, 1.0688, 8.1123, 0.9974, 1.2656, 1.1802, 1.368,
1.5435, 1.5006, 1.6766, 1.4297, 3.385, 3.3085, 3.4007, 2.0906,
1.0954, 1.5329]
data["ncat"] = [
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3,
3, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5]
data["grade"] = reshape([
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, NaN,
2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
1, 1, 1, 1, 1, 1, 2, 2, 2, NaN, 2, 2, 1, 1, 1, 1, 1, 2, 1, 2,
2, 2, 2, 2, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1,
1, 1, 1, NaN, NaN, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, NaN, NaN, 1,
1, NaN, 2, NaN, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, NaN, 2, 2, 1, 1, 1,
NaN, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2,
2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, NaN, 2, 2, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, NaN, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,
2, 2, 1, 1, 1, 1, 1, NaN, NaN, 2, 1, NaN, 1, 2, 2, 1, 1, 1, 1, 1,
1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
1, 1, 1, 1, 2, 2, 3, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, NaN, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, NaN, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, NaN, NaN, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 2, NaN, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1,
1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 4, 2, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 3, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 1, 1, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2,
2, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 2, 3, 3, 3, 4,
5, 5, 5, 5, 1, 1, 1, 1, 3, 3, 3, 4, 4, 5, 5, 5, 5], 13, 34)
grade = reshape([
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, 1,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, 1, NaN, NaN, 1,
NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN, NaN, NaN,
NaN, NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, 1, 1, NaN, NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, 1, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN], 13, 34)
inits = [
Dict("theta" => [0.5, 1, 2, 3, 5, 6, 7, 8, 9, 12, 13, 16, 18],
"grade" => grade, ".RNG.name" => "base::Wichmann-Hill");
Dict("theta" => [0.5, 1, 2, 3, 5, 6, 7, 8, 9, 12, 13, 16, 18],
"grade" => grade, ".RNG.name" => "base::Marsaglia-Multicarry");
Dict("theta" => [0.5, 1, 2, 3, 5, 6, 7, 8, 9, 12, 13, 16, 18],
"grade" => grade, ".RNG.name" => "base::Super-Duper");
Dict("theta" => [0.5, 1, 2, 3, 5, 6, 7, 8, 9, 12, 13, 16, 18],
"grade" => grade, ".RNG.name" => "base::Mersenne-Twister");
]
monitors = Dict{String, Bool}(
"theta" => true
)
jagsmodel = Jagsmodel(name="bones2",
model=bones,
monitor=monitors,
ncommands=4, nchains=1,
#adapt=1000, nsamples=10000, thin=1,
#deviance=true, dic=true, popt=true,
#updatedatafile=true, updateinitfiles=true,
#pdir=ProjDir
);
println("\nJagsmodel that will be used:")
jagsmodel |> display
@time sim = jags(jagsmodel, data, [inits;], ProjDir)
## Plotting
p = plot(sim)
end #cd
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 1459 | ######### Jags batch program example ###########
using StatsPlots, Jags, Statistics
ProjDir = @__DIR__
cd(ProjDir)
dyes = "
model {
for (i in 1:BATCHES) {
for (j in 1:SAMPLES) {
y[i,j] ~ dnorm(mu[i], tau.within);
}
mu[i] ~ dnorm(theta, tau.between);
}
theta ~ dnorm(0.0, 1.0E-10);
tau.within ~ dgamma(0.001, 0.001);
s2.within <- 1/tau.within;
tau.between ~ dgamma(0.001, 0.001);
s2.between <- 1/tau.between;
s2.total <- s2.within + s2.between;
f.within <- s2.within/s2.total;
f.between <- s2.between/s2.total;
}
"
data = Dict{String, Any}()
data["y"] = reshape([
1545, 1540, 1595, 1445, 1595,
1520, 1440, 1555, 1550, 1440,
1630, 1455, 1440, 1490, 1605,
1595, 1515, 1450, 1520, 1560,
1510, 1465, 1635, 1480, 1580,
1495, 1560, 1545, 1625, 1445
], 6, 5)
data["BATCHES"] = 6
data["SAMPLES"] = 5
inits = [
Dict{String, Any}(
"theta" => 1500,
"tau.within" => 1,
"tau.between" => 1
)
]
monitors = Dict{String, Any}(
"theta" => true,
"s2.within" => true,
"s2.between" => true
)
jagsmodel = Jagsmodel(name="dyes", model=dyes,
ncommands=3, nchains=4,
monitor=monitors)
println("\nJagsmodel that will be used:")
jagsmodel |> display
println("Input observed data dictionary:")
data |> display
println("\nInput initial values dictionary:")
inits |> display
println()
@time sim = jags(jagsmodel, data, inits, ProjDir)
show(sim)
println()
## Plotting
#p = plot(sim)
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 1261 | ######### Jags line program example ###########
using StatsPlots, Jags, Statistics, Random
Random.seed!(0)
ProjDir = @__DIR__
cd(ProjDir)
line = "
model {
for (i in 1:n) {
mu[i] <- alpha + beta*(x[i] - x.bar);
y[i] ~ dnorm(mu[i],tau);
}
x.bar <- mean(x[]);
alpha ~ dnorm(0.0,1.0E-4);
beta ~ dnorm(0.0,1.0E-4);
tau ~ dgamma(1.0E-3,1.0E-3);
sigma <- 1.0/sqrt(tau);
}
"
monitors = Dict(
"alpha" => true,
"beta" => true,
"tau" => true,
"sigma" => true
)
jagsmodel = Jagsmodel(
name="line1",
model=line,
ncommands=1,
nchains=4,
monitor=monitors,
deviance=true, dic=true, popt=true,
pdir=ProjDir
);
println("\nJagsmodel that will be used:")
jagsmodel |> display
data = Dict(
"x" => [1, 2, 3, 4, 5],
"y" => [1, 3, 3, 3, 5],
"n" => 5
)
inits = [
Dict("alpha" => 0,"beta" => 0,"tau" => 1),
Dict("alpha" => 1,"beta" => 2,"tau" => 1),
Dict("alpha" => 3,"beta" => 3,"tau" => 2),
Dict("alpha" => 5,"beta" => 2,"tau" => 5)
]
println("Input observed data dictionary:")
data |> display
println("\nInput initial values dictionary:")
inits |> display
println()
sim = jags(jagsmodel, data, inits, ProjDir)
show(sim)
println()
## Plotting
p = plot(sim)
savefig(p, "sim_plot.png")
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 2114 | ######### Jags line program example ###########
using StatsPlots, Jags, Statistics
ProjDir = joinpath(dirname(@__FILE__))
cd(ProjDir) do
line = "
model {
for (i in 1:n) {
mu[i] <- alpha + beta*(x[i] - x.bar);
y[i] ~ dnorm(mu[i],tau);
}
x.bar <- mean(x[]);
alpha ~ dnorm(0.0,1.0E-4);
beta ~ dnorm(0.0,1.0E-4);
tau ~ dgamma(1.0E-3,1.0E-3);
sigma <- 1.0/sqrt(tau);
}
"
monitors = Dict(
"alpha" => true,
"beta" => true,
"tau" => true,
"sigma" => true
)
jagsmodel = Jagsmodel(
name="line2",
model=line,
monitor=monitors,
ncommands=4,
#ncommands=1,
nchains=4,
#deviance=true, dic=true, popt=true,
pdir=ProjDir
);
println("\nJagsmodel that will be used:")
jagsmodel |> display
data = Dict{String, Any}(
"x" => [1, 2, 3, 4, 5],
"y" => [1, 3, 3, 3, 5],
"n" => 5
)
inits = [
Dict("alpha" => 0,"beta" => 0,"tau" => 1),
Dict("alpha" => 1,"beta" => 2,"tau" => 1),
Dict("alpha" => 3,"beta" => 3,"tau" => 2),
Dict("alpha" => 5,"beta" => 2,"tau" => 5)
]
#=
inits = [
Dict("alpha" => 0,"beta" => 0,"tau" => 1,".RNG.name" => "base::Mersenne-Twister"),
Dict("alpha" => 1,"beta" => 2,"tau" => 1,".RNG.name" => "base::Mersenne-Twister"),
Dict("alpha" => 3,"beta" => 3,"tau" => 2,".RNG.name" => "base::Mersenne-Twister"),
Dict("alpha" => 5,"beta" => 2,"tau" => 5,".RNG.name" => "base::Mersenne-Twister")
]
=#
#=
inits = [
Dict("alpha" => 0,"beta" => 0,"tau" => 1,".RNG.name" => "base::Wichmann-Hill"),
Dict("alpha" => 1,"beta" => 2,"tau" => 1,".RNG.name" => "base::Marsaglia-Multicarry"),
Dict("alpha" => 3,"beta" => 3,"tau" => 2,".RNG.name" => "base::Super-Duper"),
Dict("alpha" => 5,"beta" => 2,"tau" => 5,".RNG.name" => "base::Mersenne-Twister")
]
=#
println("Input observed data dictionary:")
data |> display
println("\nInput initial values dictionary:")
inits |> display
println()
global sim = jags(jagsmodel, data, inits, ProjDir)
println()
## Plotting
p = plot(sim)
end #cd
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 1324 | ######### Jags line program example ###########
using StatsPlots, Jags, Statistics
ProjDir = joinpath(dirname(@__FILE__))
cd(ProjDir) do
line = "
model {
for (i in 1:n) {
mu[i] <- alpha + beta*(x[i] - x.bar);
y[i] ~ dnorm(mu[i],tau);
}
x.bar <- mean(x[]);
alpha ~ dnorm(0.0,1.0E-4);
beta ~ dnorm(0.0,1.0E-4);
tau ~ dgamma(1.0E-3,1.0E-3);
sigma <- 1.0/sqrt(tau);
}
"
monitors = Dict(
"alpha" => true,
"beta" => true,
"tau" => true,
"sigma" => true
)
jagsmodel = Jagsmodel(
name="line3",
model=line,
monitor=monitors,
deviance=true, dic=true, popt=true,
jagsthin=10, thin=1,
pdir=ProjDir
);
println("\nJagsmodel that will be used:")
jagsmodel |> display
data = Dict(
"x" => [1, 2, 3, 4, 5],
"y" => [1, 3, 3, 3, 5],
"n" => 5
)
inits = [
Dict("alpha" => 0,"beta" => 0,"tau" => 1),
Dict("alpha" => 1,"beta" => 2,"tau" => 1),
Dict("alpha" => 3,"beta" => 3,"tau" => 2),
Dict("alpha" => 5,"beta" => 2,"tau" => 5)
]
println("Input observed data dictionary:")
data |> display
println("\nInput initial values dictionary:")
inits |> display
println()
sim = jags(jagsmodel, data, inits, ProjDir)
println()
## Plotting
p = plot(sim)
end #cd
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 1325 | ######### Jags line program example ###########
using StatsPlots, Jags, Statistics
ProjDir = joinpath(dirname(@__FILE__))
cd(ProjDir) do
line = "
model {
for (i in 1:n) {
mu[i] <- alpha + beta*(x[i] - x.bar);
y[i] ~ dnorm(mu[i],tau);
}
x.bar <- mean(x[]);
alpha ~ dnorm(0.0,1.0E-4);
beta ~ dnorm(0.0,1.0E-4);
tau ~ dgamma(1.0E-3,1.0E-3);
sigma <- 1.0/sqrt(tau);
}
"
monitors = Dict(
"alpha" => true,
"beta" => true,
"tau" => true,
"sigma" => true
)
jagsmodel = Jagsmodel(
name="line4",
model=line,
monitor=monitors,
deviance=false, dic=true, popt=true,
jagsthin=10, thin=1,
pdir=ProjDir
);
println("\nJagsmodel that will be used:")
jagsmodel |> display
data = Dict(
"x" => [1, 2, 3, 4, 5],
"y" => [1, 3, 3, 3, 5],
"n" => 5
)
inits = [
Dict("alpha" => 0,"beta" => 0,"tau" => 1),
Dict("alpha" => 1,"beta" => 2,"tau" => 1),
Dict("alpha" => 3,"beta" => 3,"tau" => 2),
Dict("alpha" => 5,"beta" => 2,"tau" => 5)
]
println("Input observed data dictionary:")
data |> display
println("\nInput initial values dictionary:")
inits |> display
println()
sim = jags(jagsmodel, data, inits, ProjDir)
println()
## Plotting
p = plot(sim)
end #cd
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 2982 | using StatsPlots, Jags, Statistics
ProjDir = dirname(@__FILE__)
cd(ProjDir) do
## Data
rats = Dict{String, Any}(
"Y" =>
[151 199 246 283 320;
145 199 249 293 354;
147 214 263 312 328;
155 200 237 272 297;
135 188 230 280 323;
159 210 252 298 331;
141 189 231 275 305;
159 201 248 297 338;
177 236 285 350 376;
134 182 220 260 296;
160 208 261 313 352;
143 188 220 273 314;
154 200 244 289 325;
171 221 270 326 358;
163 216 242 281 312;
160 207 248 288 324;
142 187 234 280 316;
156 203 243 283 317;
157 212 259 307 336;
152 203 246 286 321;
154 205 253 298 334;
139 190 225 267 302;
146 191 229 272 302;
157 211 250 285 323;
132 185 237 286 331;
160 207 257 303 345;
169 216 261 295 333;
157 205 248 289 316;
137 180 219 258 291;
153 200 244 286 324],
"x" => [8.0, 15.0, 22.0, 29.0, 36.0]
)
rats["N"] = size(rats["Y"], 1)
rats["T"] = size(rats["Y"], 2)
rats["x.bar"] = mean(rats["x"])
ratsmodel = "
model {
for (i in 1:N) {
for (j in 1:T) {
mu[i,j] <- alpha[i] + beta[i]*(x[j] - x.bar);
Y[i,j] ~ dnorm(mu[i,j], tau.c)
}
alpha[i] ~ dnorm(alpha.c, tau.alpha);
beta[i] ~ dnorm(beta.c, tau.beta);
}
alpha.c ~ dnorm(0, 1.0E-4);
beta.c ~ dnorm(0, 1.0E-4);
tau.c ~ dgamma(1.0E-3, 1.0E-3);
tau.alpha ~ dgamma(1.0E-3, 1.0E-3);
tau.beta ~ dgamma(1.0E-3, 1.0E-3);
sigma <- 1.0/sqrt(tau.c);
alpha0 <- alpha.c - beta.c*x.bar;
}
"
## Initial Values
inits = [
Dict{String,Any}("alpha" => fill(250, 30), "beta" => fill(6, 30),
"alpha.c" => 100, "beta.c" => 2, "tau.c" => 1, "tau.alpha" => 1, "tau.beta" => 1),
Dict{String,Any}("alpha" => fill(150, 30), "beta" => fill(3, 30),
"alpha.c" => 150, "beta.c" => 2, "tau.c" => 1, "tau.alpha" => 1, "tau.beta" => 1),
Dict{String,Any}("alpha" => fill(200, 30), "beta" => fill(6, 30),
"alpha.c" => 200, "beta.c" => 1, "tau.c" => 1, "tau.alpha" => 1, "tau.beta" => 1),
Dict{String,Any}("alpha" => fill(150, 30), "beta" => fill(3, 30),
"alpha.c" => 250, "beta.c" => 1, "tau.c" => 1, "tau.alpha" => 1,"tau.beta" => 1)
]
monitors = Dict{String, Bool}(
"alpha0" => true,
"beta.c" => true,
"sigma" =>true
)
jagsmodel = Jagsmodel(
name="rats",
model=ratsmodel,
monitor=monitors,
#ncommands=4, nchains=1,
adapt=1000, nsamples=10000, thin=10,
#deviance=true, dic=true, popt=true,
pdir=ProjDir);
println("Jagsmodel that will be used:")
jagsmodel |> display
println("Input observed data dictionary:")
rats |> display
println("\nInput initial values dictionary:")
inits |> display
println()
@time sim = jags(jagsmodel, rats, inits, ProjDir)
println()
## Plotting
p = plot(sim)
end #cd
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 1546 | module Jags
using Compat, CSV, Pkg, Documenter, DelimitedFiles, Unicode, MCMCChains
using PrecompileTools
#### Includes ####
include("jagsmodel.jl")
include("jagscode.jl")
if !isdefined(Main, :Stanmodel)
include("utilities.jl")
end
if VERSION >= v"1.9"
include("precompile.jl")
@compile_workload begin
Jags.precompile_model()
end
end
"""The directory which contains the executable `bin/stanc`. Inferred
from `Main.JAGS_HOME` or `ENV["JAGS_HOME"]` when available. Use
`set_jags_home!` to modify."""
JAGS_HOME=""
function __init__()
global JAGS_HOME = if isdefined(Main, :JAGS_HOME)
getproperty(Main, :JAGS_HOME)
elseif haskey(ENV, "JAGS_HOME")
ENV["JAGS_HOME"]
else
try # finding Jags in path
jags_home = ""
if Sys.iswindows()
jags_home = splitdir(strip(read(`where jags`, String)))[1]
elseif Sys.isunix()
jags_home = splitdir(strip(read(`which jags`, String)))[1]
end
set_jags_home!(jags_home)
catch
@warn("Did not find JAGS in the PATH.")
@warn("Environment variable JAGS_HOME not found. Use set_jags_home!.")
end
""
end
end
"""Set the path for `Jags`.
Example: `set_jags_home!(homedir() * "/src/src/cmdstan-2.11.0/")`
"""
set_jags_home!(path) = global JAGS_HOME=path
#### Exports ####
export
# From this file
set_jags_home!,
# From Jags.jl
JAGS_HOME,
# From jagsmodel.jl
Jagsmodel,
# From jagscode.jl
jags
end # module
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 8416 | function mis2str(x::Missing) return "NA" end
function mis2str(x::Char) return x end
function mis2str(x) return string(x) end
function jags(
model::Jagsmodel,
data = Dict{String, Any}(),
init = Dict{String, Any}(),
ProjDir=pwd();
updatedatafile::Bool=true,
updateinitfiles::Bool=true
)
try
if updatedatafile
if length(keys(data)) > 0
print("\nCreating data file $(model.name)-data.R - ")
@time update_R_file(joinpath(model.tmpdir, "$(model.name)-data.R"), data)
end
else
println("\nData file not updated.")
end
if updateinitfiles
if size(init, 1) > 0
update_init_files(model, init)
end
else
println("\nInit files not updated.")
end
println()
println("Executing $(model.ncommands) command(s), each with $(model.nchains) chain(s) took:")
@time run(pipeline(par(model.command), stdout="$(model.name)-run.log"))
sim = mchain(model)
return(sim)
catch e
println(e)
end
end
#### Update data and init files
function update_init_files(model::Jagsmodel, init)
println()
k = length(init)
m = max(model.nchains, model.ncommands)
indx = filter(x -> x!=0, [%(i, (k+1)) for i in 1:2m])
for i in 1:m
print("Creating init file $(model.name)-inits$(i).R - ")
@time update_R_file(joinpath(model.tmpdir, "$(model.name)-inits$(i).R"), init[indx[i]])
end
end
function update_R_file(file::String, dct; replaceNaNs::Bool=true)
isfile(file) && rm(file)
strmout = open(file, "w")
str = ""
for entry in dct
str = "\""*entry[1]*"\""*" <- "
val = entry[2]
if replaceNaNs
if typeof(entry[2]) == Array{Float64, 1}
if true in isnan.(entry[2])
val = convert(Array{Union{Float64,Missing}},entry[2])
for i in 1:length(val)
if isnan(val[i])
val[i] = NA
end
end
end
end
if typeof(entry[2]) == Array{Float64, 2}
if true in isnan.(entry[2])
val = convert(Array{Union{Float64,Missing}},entry[2])
k,l = size(val)
for i in 1:k
for j in 1:l
if isnan(val[i, j])
val[i, j] = missing
end
end
end
end
end
end
if typeof(val) <: String
str = str*"\"$(val)\"\n"
elseif length(val)==1 && length(size(val))==0
# Scalar
str = str * mis2str(val) * "\n"
elseif length(val)>=1 && length(size(val))==1
# Vector
str = str*"structure(c("
for i in 1:length(val)
str = str*"$(mis2str(val[i]))"
if i < length(val)
str = str*", "
end
end
str = str*"), .Dim=c($(length(val))))\n"
elseif length(val)>1 && length(size(val))>1
# Array
str = str*"structure(c("
for i in 1:length(val)
str = str*"$(mis2str(val[i]))"
if i < length(val)
str = str*", "
end
end
dimstr = "c"*string(size(val))
str = str*"), .Dim=$(dimstr))\n"
end
write(strmout, str)
end
close(strmout)
end
#### use readdlm to read in all chains and create a Dict
function read_jagsfiles(model::Jagsmodel)
index = readdlm(joinpath(model.tmpdir, "$(model.name)-cmd1-index.txt"), header=false)
idxdct = Dict{String, Any}()
for row in 1:size(index)[1]
idxdct[index[row, 1]]=[Int(index[row, 2]), Int(index[row, 3])]
end
## Collect the results of a chain in an array ##
chainarray = Dict{String, Any}[]
## Each chain dictionary can contain up to 4 types of results ##
result_type_files = ["samples"]
rtdict = Dict{String, Any}()
res_type = result_type_files[1]
## tdict contains the arrays of values ##
tdict = Dict{String, Any}()
println()
for i in 1:model.ncommands
tdict = Dict{String, Any}()
for j in 1:model.nchains
if isfile(joinpath(model.tmpdir, "$(model.name)-cmd$(i)-chain$(j).txt"))
println("Reading $(model.name)-cmd$(i)-chain$(j).txt")
res = readdlmcsv(joinpath(model.tmpdir, "$(model.name)-cmd$(i)-chain$(j).txt"))
for key in index[:, 1]
indx1 = idxdct[key][1]
indx2 = idxdct[key][2]
if length(keys(tdict)) == 0
tdict = Dict(key => res[indx1:indx2, 2])
else
tdict = merge(tdict, Dict(key => res[indx1:indx2, 2]))
end
end
## End of processing result type file ##
## If any keys were found, merge it in the rtdict ##
if length(keys(tdict)) > 0
#println("Merging $(convert(Symbol, res_type)) with keys $(keys(tdict))")
rtdict[res_type]=tdict
tdict = Dict{String, Any}()
end
end
## If rtdict has keys, push it to the chain array ##
if length(keys(rtdict)) > 0
#println("Pushing the rtdict with keys $(keys(rtdict))")
push!(chainarray, rtdict)
rtdict = Dict{String, Any}()
end
end
end
(idxdct, chainarray)
end
#### Create a MCMCChains::Chains result
function mchain(model::Jagsmodel)
println()
local totalnchains, curchain
index = readdlm(joinpath(model.tmpdir, "$(model.name)-cmd1-index.txt"),
header=false)
# Correct model.adapt for jagsthin != 1
# if jagsthin != 1, adaptation samples are not included.
if model.jagsthin != 1
model.adapt = 1
end
cnames = String[]
for i in 1:size(index)[1]
append!(cnames, [index[i]])
end
totalnchains = model.nchains * model.ncommands
a3d = fill(0.0, Int(index[1, 3]),
size(index, 1), totalnchains);
for i in 1:model.ncommands
for j in 1:model.nchains
if isfile(joinpath(model.tmpdir, "$(model.name)-cmd$(i)-chain$(j).txt"))
println("Reading $(model.name)-cmd$(i)-chain$(j).txt")
res = readdlmcsv(joinpath(model.tmpdir, "$(model.name)-cmd$(i)-chain$(j).txt"))
curchain = (i-1)*model.nchains + j
#println(curchain)
k = 0
for key in cnames
k += 1
a3d[:, k, curchain] = res[index[k, 2]:index[k, 3], 2]
end
end
end
end
println()
MCMCChains.Chains(a3d,cnames)
end
#### Read DIC related results
function read_pDfile(model::Jagsmodel)
index = readdlm(joinpath(model.tmpdir, "$(model.name)-cmd1-index0.txt"), header=false);
idxdct = Dict{String, Any}()
for row in 1:size(index)[1]
idxdct[index[row, 1]]=[Int(index[row, 2]), Int(index[row, 3])]
end
## Collect the results of a chain in an array ##
chainarray = Dict{String, Any}[]
## Each chain dictionary can contain up to 4 types of results ##
result_type_files = ["samples"]
rtdict = Dict{String, Any}()
res_type = result_type_files[1]
## tdict contains the arrays of values ##
tdict = Dict{String, Any}()
for i in 0:0
tdict = Dict{String, Any}()
if isfile(joinpath(model.tmpdir, "$(model.name)-cmd1-chain$(i).txt"))
println("Reading $(model.name)-cmd1-chain$(i).txt")
res = readdlmcsv(joinpath(model.tmpdir, "$(model.name)-cmd1-chain$(i).txt"))
for key in index[:, 1]
indx1 = idxdct[key][1]
indx2 = idxdct[key][2]
if length(keys(tdict)) == 0
tdict = Dict(key => res[indx1:indx2, 2])
else
tdict = merge(tdict, Dict(key => res[indx1:indx2, 2]))
end
end
## End of processing result type file ##
## If any keys were found, merge it in the rtdict ##
if length(keys(tdict)) > 0
#println("Merging $(convert(Symbol, res_type)) with keys $(keys(tdict))")
rtdict = merge(rtdict, Dict(res_type => tdict))
tdict = Dict{String, Any}()
end
end
## If rtdict has keys, push it to the chain array ##
if length(keys(rtdict)) > 0
#println("Pushing the rtdict with keys $(keys(rtdict))")
push!(chainarray, rtdict)
rtdict = Dict{String, Any}()
end
end
(idxdct, chainarray)
end
function read_table_file(model::Jagsmodel, len::Int)
pdpopt = Dict{String, Any}[]
if model.dic && model.popt
numrows = 2len
else
numrows = len
end
res = readdlmcsv(joinpath(model.tmpdir, "$(model.name)-cmd1-table0.txt"))
if model.dic && model.popt
pdpopt = Dict("pD.mean" => res[1:len, 2])
pdpopt = merge(pdpopt, Dict("popt" => res[len+1:2len, 2]))
else
if model.dic
pdpopt = Dict("pD.mean" => res[1:len, 2])
else
pdpopt = Dict("popt" => res[1:len, 2])
end
end
pdpopt
end
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 7720 | import Base: show
mutable struct Jagsmodel
name::String
ncommands::Int
nchains::Int
adapt::Int
nsamples::Int
thin::Int
jagsthin::Int
monitor::Dict
deviance::Bool
dic::Bool
popt::Bool
model::String
model_file::String
data::Dict{String,Any}
data_file::String
init::Array{Dict{String,Any},1}
command::Array{Base.AbstractCmd, 1}
tmpdir::String
end
function Jagsmodel(;
name::String="Noname",
model::String="",
model_file::String="",
ncommands::Int=1,
nchains::Int=4,
adapt::Int=1000,
nsamples::Int=10000,
thin::Int=1,
jagsthin::Int=1,
monitor=Dict{String,Any}(),
deviance::Bool=false,
dic::Bool=false,
popt::Bool=false,
updatejagsfile::Bool=true,
pdir::String=pwd())
tmpdir = joinpath(pdir, "tmp")
@show tmpdir
if !isdir(tmpdir)
mkdir(tmpdir)
end
# Check if .bugs file needs to be updated.
if length(model) > 0
update_bugs_file(joinpath(tmpdir, "$(name).bugs"), strip(model))
elseif length(model) == 0 && length(model_file) >0 && isfile(model_file)
cp(model_file, joinpath(tmpdir, "$(name).bugs"))
else
println("No proper model defined.")
end
model_file = joinpath(pdir, "$(name).bugs")
# Remove old files created by previous runs
for i in 1:ncommands
isfile(joinpath(tmpdir, "$(name)-cmd$(i)-index0.txt")) &&
rm(joinpath(tmpdir, "$(name)-cmd$(i)-index0.txt"));
isfile(joinpath(tmpdir, "$(name)-cmd$(i)-table0.txt")) &&
rm(joinpath(tmpdir, "$(name)-cmd$(i)-table0.txt"));
for j in 0:nchains
isfile(joinpath(tmpdir, "$(name)-cmd$(i)-chain$(j).R")) &&
rm(joinpath(tmpdir, "$(name)-cmd$(i)-chain$(j).R"));
end
end
# Create the command array which will be executed in parallel
cmdarray = fill(``, ncommands)
for i in 1:ncommands
jfile = joinpath(tmpdir, "$(name)-cmd$(i).jags")
cmdarray[i] = @static Sys.iswindows() ? `cmd /c jags $(jfile)` : `jags $(jfile)`
end
# DIC needs at least 2 chains
if (dic || popt) && nchains < 2
nchains = 2
end
data = Dict{String, Any}()
init = Dict{String, Any}[]
if length(monitor) == 0
println("No monitors defined!")
end
data_file = joinpath(tmpdir, "$(name)-data.R")
jm = Jagsmodel(name,
ncommands, nchains,
adapt, nsamples,
thin, jagsthin,
monitor,
deviance, dic, popt,
model, model_file,
data,
data_file,
init,
cmdarray,
tmpdir);
if ncommands == 1
updatejagsfile && update_jags_file(jm)
else
for i in 1:ncommands
updatejagsfile && update_jags_file(jm, i)
end
end
jm
end
#### Function to update the bugs, init and data files
function update_bugs_file(file::AbstractString, str::AbstractString)
str2 = ""
if isfile(file)
str2 = read(file,String)
str != str2 && rm(file)
end
if str != str2
println("\nFile $(file) will be updated.")
strmout = open(file, "w")
write(strmout, str)
close(strmout)
else
println("\nFile $(file) not updated.")
end
end
#### Function to update the jags file for ncommand == 1
function update_jags_file(model::Jagsmodel)
jagsstr = "/*\n\tGenerated $(model.name).jags command file\n*/\n"
if model.deviance || model.dic || model.popt
jagsstr = jagsstr*"load dic\n"
end
modelfile = joinpath(model.tmpdir, basename(model.model_file))
jagsstr = jagsstr* "model in \"$(modelfile)\"\n"
jagsstr = jagsstr*"data in \"$(joinpath(model.tmpdir, model.data_file))\"\n"
jagsstr = jagsstr*"compile, nchains($(model.nchains))\n"
for i in 1:model.nchains
fname = "$(model.name)-inits$(i).R"
jagsstr = jagsstr*"parameters in \"$(joinpath(model.tmpdir, fname))\", chain($(i))\n"
end
jagsstr = jagsstr*"initialize\n"
jagsstr = jagsstr*"update $(model.adapt)\n"
if model.deviance
jagsstr = jagsstr*"monitor deviance, thin($(model.jagsthin))\n"
end
if model.dic
jagsstr = jagsstr*"monitor pD\n"
jagsstr = jagsstr*"monitor pD, type(mean)\n"
end
if model.popt
jagsstr = jagsstr*"monitor popt, type(mean)\n"
end
for entry in model.monitor
if entry[2]
jagsstr = jagsstr*"monitor $(string(entry[1])), thin($(model.jagsthin))\n"
end
end
jagsstr = jagsstr*"update $(model.nsamples)\n"
jagsstr = jagsstr*"coda *, stem(\"$(joinpath(model.tmpdir, model.name))-cmd1-\")\n"
jagsstr = jagsstr*"exit\n"
check_jags_file(joinpath(model.tmpdir, "$(model.name)-cmd1.jags"), jagsstr)
end
#### Function to update the jags file for ncommand > 1
function update_jags_file(model::Jagsmodel, cmd::Int)
m = max(model.nchains, model.ncommands)
indx = filter(x -> x!=0, [%(i, (m+1)) for i in 1:3m])
indx = indx[cmd:length(indx)]
jagsstr = "/*\n\tGenerated $(model.name).jags command file\n*/\n"
if model.deviance || model.dic || model.popt
jagsstr = jagsstr*"load dic\n"
end
jagsstr = jagsstr* "model in \"" * joinpath(model.tmpdir, basename(model.model_file)) * "\"\n"
jagsstr = jagsstr*"data in \"$(joinpath(model.tmpdir, model.data_file))\"\n"
jagsstr = jagsstr*"compile, nchains($(model.nchains))\n"
for i in 1:model.nchains
fname = joinpath(model.tmpdir, "$(model.name)-inits$(indx[i]).R")
jagsstr = jagsstr*"parameters in \"$(fname)\", chain($(i))\n"
end
jagsstr = jagsstr*"initialize\n"
jagsstr = jagsstr*"update $(model.adapt)\n"
if model.deviance
jagsstr = jagsstr*"monitor deviance\n"
end
if model.dic
jagsstr = jagsstr*"monitor pD\n"
jagsstr = jagsstr*"monitor pD, type(mean)\n"
end
if model.popt
jagsstr = jagsstr*"monitor popt, type(mean)\n"
end
for entry in model.monitor
if entry[2]
jagsstr = jagsstr*"monitor $(string(entry[1])), thin($(model.jagsthin))\n"
end
end
jagsstr = jagsstr*"update $(model.nsamples)\n"
jagsstr = jagsstr*"coda *, stem(\"$(joinpath(model.tmpdir, model.name))-cmd$(cmd)-\")\n"
jagsstr = jagsstr*"exit\n"
check_jags_file(joinpath(model.tmpdir, "$(model.name)-cmd$(cmd).jags"), jagsstr)
end
function check_jags_file(file::String, str::String)
str2 = ""
if isfile(file)
str2 = read(file,String)
str != str2 && rm(file)
end
if str != str2
println("File $(file) will be updated.")
strmout = open(file, "w")
write(strmout, str)
close(strmout)
else
println("File $(file) not updated.")
end
end
function model_show(io::IO, m::Jagsmodel, compact::Bool=false)
if compact==true
println("Jagsmodel(", m.name, ", ",
m.ncommands, ", ", m.nchains, ", ",
m.adapt, ", ", m.nsamples, ", ",
m.thin, ", ", m.jagsthin, ", ",
m.monitor, ", ",
m.deviance, ", ", m.dic, ", ", m.popt, ", ",
m.model_file, ", ", m.data_file, ", ", m.tmpdir, ")")
else
println(" name = \"$(m.name)\"")
println(" ncommands = $(m.ncommands)")
println(" nchains = $(m.nchains)")
println(" adapt = $(m.adapt)")
println(" nsamples = $(m.nsamples)")
println(" thin = $(m.thin)")
println(" jagsthin = $(m.jagsthin)")
println(" monitor = $(m.monitor)")
println(" deviance = $(m.deviance)")
println(" dic = $(m.dic)")
println(" popt = $(m.popt)")
#println(" model = $(model)")
println(" model_file = $(m.model_file)")
#println(" data = $(data)")
println(" data_file = $(m.data_file)")
#println(" init = $(init)")
println(" tmpdir = $(m.tmpdir)")
end
end
show(io::IO, m::Jagsmodel) = model_show(io, m, false)
showcompact(io::IO, m::Jagsmodel) = model_show(io, m, true)
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 1370 | function precompile_model()
redirect_stdout(devnull) do
ProjDir = tempdir()
cd(ProjDir) do
line = "
model {
for (i in 1:n) {
mu[i] <- alpha + beta*(x[i] - x.bar);
y[i] ~ dnorm(mu[i],tau);
}
x.bar <- mean(x[]);
alpha ~ dnorm(0.0,1.0E-4);
beta ~ dnorm(0.0,1.0E-4);
tau ~ dgamma(1.0E-3,1.0E-3);
sigma <- 1.0/sqrt(tau);
}
"
monitors = Dict("alpha" => true, "beta" => true, "tau" => true, "sigma" => true)
jagsmodel = Jagsmodel(
name = "line4",
model = line,
monitor = monitors,
deviance = false,
dic = true,
popt = true,
jagsthin = 10,
thin = 1,
pdir = ProjDir,
)
println("\nJagsmodel that will be used:")
jagsmodel |> display
data = Dict("x" => [1, 2, 3, 4, 5], "y" => [1, 3, 3, 3, 5], "n" => 5)
inits = [
Dict("alpha" => 0, "beta" => 0, "tau" => 1),
Dict("alpha" => 1, "beta" => 2, "tau" => 1),
Dict("alpha" => 3, "beta" => 3, "tau" => 2),
Dict("alpha" => 5, "beta" => 2, "tau" => 5),
];
sim = jags(jagsmodel, data, inits, ProjDir)
println(sim)
end
end
end | Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 1545 | #=
import Base: *
if !isdefined(Main, :Stan)
function *(c1::Cmd, c2::Cmd)
res = deepcopy(c1)
for i in 1:length(c2.exec)
push!(res.exec, c2.exec[i])
end
res
end
function *(c1::Cmd, sa::Array{String, 1})
res = deepcopy(c1)
for i in 1:length(sa)
push!(res.exec, sa[i])
end
res
end
function *(c1::Cmd, s::String)
res = deepcopy(c1)
push!(res.exec, s)
res
end
end
=#
"""
# par
Rewrite dct to R format in file.
### Method
```julia
par(cmds)
```
### Required arguments
```julia
* `cmds::Array{Base.AbstractCmd,1}` : Multiple commands to concatenate
or
* `cmd::Base.AbstractCmd` : Single command to be
* `n::Number` inserted n times into cmd
or
* `cmd::Array{String, 1}` : Array of cmds as Strings
```
"""
function par(cmds::Array{Base.AbstractCmd,1})
if length(cmds) > 2
return(par([cmds[1:(length(cmds)-2)];
Base.AndCmds(cmds[length(cmds)-1], cmds[length(cmds)])]))
elseif length(cmds) == 2
return(Base.AndCmds(cmds[1], cmds[2]))
else
return(cmds[1])
end
end
function par(cmd::Base.AbstractCmd, n::Number)
res = deepcopy(cmd)
if n > 1
for i in 2:n
res = Base.AndCmds(res, cmd)
end
end
res
end
function par(cmd::Array{String, 1})
res = `$(cmd[1])`
for i in 2:length(cmd)
res = `$res $(cmd[i])`
end
res
end
function readdlmcsv(fn)
tmp = CSV.File(fn; header=0, delim=' ', ignorerepeated=true, types=Float64)
return hcat(tmp.Column1, tmp.Column2)
end
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 901 | println("Running tests for Jags-j1.7-v3.1.0")
using Compat, Jags
using Test
code_tests = ["test_cmd.jl"]
println("Run execution_tests only if Jags is available")
execution_tests = [
"test_line1.jl",
#"test_line2.jl",
"test_line3.jl",
"test_line4.jl",
"test_rats.jl",
"test_bones1.jl",
"test_bones2.jl",
"test_dyes.jl"
]
if isdefined(Main, :JAGS_HOME) && length(JAGS_HOME) > 0
for my_test in code_tests
println("\n * $(my_test) *")
include(my_test)
end
@testset "Jags.jl" begin
for my_test in code_tests
println("\n\n\n * $(my_test) *")
include(my_test)
end
for my_test in execution_tests
println("\n\n\n * $(my_test) *")
include(my_test)
end
println("\n")
end
else
println("\n\nJAGS_HOME not found.")
println("Skipping all tests that depend on the Jags executable!\n")
end
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 238 | ProjDir = joinpath(dirname(@__FILE__), "..", "Examples", "Bones1")
tmpdir = joinpath(ProjDir, "tmp")
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
include(joinpath(ProjDir, "jbones1.jl"))
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 199 | ProjDir = joinpath(dirname(@__FILE__), "..", "Examples", "Bones2")
isfile(tmpdir) &&
rm(tmpdir);
include(joinpath(ProjDir, "jbones2.jl"))
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 761 | using Jags, StatsPlots, Random, Distributions
ProjDir = @__DIR__
Random.seed!(3431)
y = rand(Normal(0,1),50)
Model = "
model {
for (i in 1:length(y)) {
y[i] ~ dnorm(mu,sigma);
}
mu ~ dnorm(0, 1/sqrt(10));
sigma ~ dt(0,1,1) T(0, );
}
"
monitors = Dict(
"mu" => true,
"sigma" => true,
)
jagsmodel = Jagsmodel(
name="Gaussian",
model=Model ,
monitor=monitors,
ncommands=2,
nchains=2,
nsamples=2000,
#deviance=true, dic=true, popt=true,
pdir=ProjDir
)
data = Dict{String, Any}(
"y" => y,
)
inits = [
Dict("mu" => 0.0,"sigma" => 1.0,
".RNG.name" => "base::Mersenne-Twister",
".RNG.seed" => 314159,
)
]
sim = jags(jagsmodel, data, inits, ProjDir)
show(sim)
println()
#plot(sim)
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 1234 | using Jags, StatsPlots, Random, Distributions
cd(@__DIR__)
ProjDir = pwd()
Random.seed!(3431)
y = rand(Normal(0,1),50)
Model = "
model {
for (i in 1:length(y)) {
y[i] ~ dnorm(mu[i],sigma);
}
for(i in 1:length(y)){
mu[i] ~ dnorm(0, 1/sqrt(10));
}
sigma ~ dt(0,1,1) T(0, );
}
"
monitors = Dict(
"mu" => true,
"sigma" => true,
)
inits = [
Dict("mu"=>.0,"sigma"=>1.0)
]
jagsmodel = Jagsmodel(
name="Gaussian",
model=Model ,
monitor=monitors,
ncommands=1, nchains=4
,
#deviance=true, dic=true, popt=true,
pdir=ProjDir
)
println("\nJagsmodel that will be used:")
jagsmodel |> display
data = Dict{String, Any}(
"y" => y,
)
inits = [
Dict("mu" => 0.0,"sigma" => 1.0,
".RNG.name" => "base::Mersenne-Twister")
]
println("Input observed data dictionary:")
data |> display
println("\nInput initial values dictionary:")
inits |> display
println()
#######################################################################################
# Estimate Parameters
#######################################################################################
sim = jags(jagsmodel, data, inits, ProjDir)
sim = sim[5001:end,:,:]
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 1724 | ProjDir = dirname(@__FILE__)
tmpdir = joinpath(ProjDir, "tmp")
inits1 = [
Dict("alpha" => 0,"beta" => 0,"tau" => 1),
Dict("alpha" => 1,"beta" => 2,"tau" => 1),
Dict("alpha" => 3,"beta" => 3,"tau" => 2),
Dict("alpha" => 5,"beta" => 2,"tau" => 5)
]
function test(init::Array{Dict{String, Int64},1})
res = map((x)->convert(Dict{String, Any}, x), init)
end
function test(init::Array{Dict{String, Float64},1})
res = map((x)->convert(Dict{String, Any}, x), init)
end
function test(init::Array{Dict{String, Number},1})
res = map((x)->convert(Dict{String, Any}, x), init)
end
function test(init::Array{Dict{String, Any},1})
res = map((x)->convert(Dict{String, Any}, x), init)
end
line = "
model {
for (i in 1:n) {
mu[i] <- alpha + beta*(x[i] - x.bar);
y[i] ~ dnorm(mu[i],tau);
}
x.bar <- mean(x[]);
alpha ~ dnorm(0.0,1.0E-4);
beta ~ dnorm(0.0,1.0E-4);
tau ~ dgamma(1.0E-3,1.0E-3);
sigma <- 1.0/sqrt(tau);
}
"
data = Dict{String, Any}()
data["x"] = [1, 2, 3, 4, 5]
data["y"] = [1, 3, 3, 3, 5]
data["n"] = 5
inits = test(inits1)
monitors = Dict{String, Bool}(
"alpha" => true,
"beta" => true,
"tau" => true,
"sigma" => true,
)
jagsmodel = Jagsmodel(name="line1", model=line, monitor=monitors,
ncommands=1, nchains=4, adapt=1000, nsamples=10000, thin=1,
deviance=true, dic=true, popt=true, pdir=ProjDir);
println("\nJagsmodel that will be used:")
jagsmodel |> display
println("Input observed data dictionary:")
data |> display
println("\nInput initial values dictionary:")
inits |> display
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 244 | ProjDir = joinpath(dirname(@__FILE__), "..", "Examples", "Dyes")
tmpdir = joinpath(ProjDir, "tmp")
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
include(joinpath(ProjDir, "jdyes.jl"))
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 248 | ProjDir = joinpath(dirname(@__FILE__), "..", "Examples", "Line1")
tmpdir = joinpath(ProjDir, "tmp")
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
include(joinpath(ProjDir, "jline1.jl"))
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 250 | ProjDir = joinpath(dirname(@__FILE__), "..", "Examples", "Line2")
tmpdir = joinpath(ProjDir, "tmp")
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
include(joinpath(ProjDir, "jline2.jl"))
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 247 | ProjDir = joinpath(dirname(@__FILE__), "..", "Examples", "Line3")
tmpdir = joinpath(ProjDir, "tmp")
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
include(joinpath(ProjDir, "jline3.jl"))
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 248 | ProjDir = joinpath(dirname(@__FILE__), "..", "Examples", "Line4")
tmpdir = joinpath(ProjDir, "tmp")
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
include(joinpath(ProjDir, "jline4.jl"))
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | code | 248 | ProjDir = joinpath(dirname(@__FILE__), "..", "Examples", "Rats")
tmpdir = joinpath(ProjDir, "tmp")
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
include(joinpath(ProjDir, "jrats.jl"))
isdir(tmpdir) &&
rm(tmpdir, recursive=true);
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 3.1.3 | 5f26d17cdefa50947df734e5b43fc6d5a1ebf524 | docs | 8741 | # Jags
![][CI-build]
[CI-build]: https://github.com/jagsjulia/Jags.jl/workflows/CI/badge.svg?branch=master
## Purpose
A package to use Jags (as an external program) from Julia. Jags.jl has been moved to JagsJulia.
For more info on Jags, please go to <http://mcmc-jags.sourceforge.net>.
## What's new
### Version 3.2.0 (unfinished)
1. Attempting to fix issue #23.
Warning: I have seen many cases where the Jags binary simply hangs. This happens
immediatiately after the line "Executing `n` command(s), each with `m` chain(s) took:".
### Version 3.1.0
1. Reactivate Github actions.
### Version 3.0.3
1. Please note that version 3.0.2 `allows` MCMCChains v 4.0 which can introduce breaking changes in handling of Chains. If this is a problem, please force usage of Jags@3.0.1.
### Version 3.0.0
1. MCMCChains for storage and diagnostics (thanks to Chris Fisher)
2. No longer depends on Mamba and Gadfly
### Version 2.0.1 (tagged Jan 2019)
1. Fixed issues with REQUIRE.
### Version 2.0.0 (tagged Jan 2019)
1. Thanks to Hellema Jags.jl has been updated for Julia 1.
### Version 1.0.5 (tagged Jan 2018)
1. Added an option to specify thinning by Jags. Jagsmodel() now accepts a jagsthin arguments. Default is jagsthin=1. Thanks to @hellemo. See examples Line3 and Line4.
2. Further updates by Hellemo (e.g. to improve readdlm performance).
3. Tested on Julia 0.6. Not yet on Julia 0.7-.
### Version 1.0.2
1. Requires Julia v"0.5.0-rc3".
2. Updated .travis.yml to jsut test on Julia 0.5
### Version 1.0.0
1. Updated for Julia 0.5
### Version 0.2.0
1. Added badges for Julia package listing
2. Exported JAGS_HOME in Jags.jl
3. Updated for to also run Julia 0.4 pre-releases
### Version 0.1.5
1. Updated .travis.yml
2. The runtests.jl script now prints package version
### Version 0.1.4
1. Allowed JAGS_HOME and JULIA_SVG_BROWSER to be set from either ~/.juliarc.jl or as an evironment variable. Updated README accordingly.
### Version 0.1.3
1. Removed upper bound on Julia in REQUIRE.
### Version 0.1.2
1. Fix for access to environment variables on Windows.
### Version 0.1.1
1. Stores Jags's input & output files in a subdirectory of the working directory.
2. Added Bones2 example.
### Version 0.1.0
The two most important features introduced in version 0.1.0 are:
1. Using Mamba to display and diagnose simulation results. The call to jags() to sample now returns a Mamba Chains object (previously it returned a dictionary).
2. Added the ability to specify RNGs in the initializations file for running simulations in parallel.
### Version 0.0.4
1. Added the ability to start multiple Jags scripts in parallel.
### Version 0.0.3 and earlier
1. Parsing structure for input arguments to Stan.
2. Single process execution of a Jags simulations.
3. Read created output files by Jags back into Julia.
## Requirements
This version of the Jags.jl package assumes that:
1. Jags is installed and the jags binary is on $PATH. The variable JAGS_HOME is currently initialized either from ~/.juliarc.jl or from an environment variable JAGS_HOME. JAGS_HOME currently only used in runtests.jl to disable attempting to run tests that need the Jags executable on $PATH.
To test and run the examples:
**julia >** ``Pkg.test("Jags")``
## A walk through example
As in the Jags.jl setting, the Jags program consumes and produces files in a 'tmp' subdirectory of the current directory, it is useful to control the current working directory and restore the original directory at the end of the script.
```
using Jags
ProjDir = dirname(@__FILE__)
cd(ProjDir)
```
Variable `line` holds the model which will be writtten to a file named `$(model.name).bugs` in the 'tmp' subdirectory. The value of model.name is set later on, see the call to Jagsmodel() below.
```
line = "
model {
for (i in 1:n) {
mu[i] <- alpha + beta*(x[i] - x.bar);
y[i] ~ dnorm(mu[i],tau);
}
x.bar <- mean(x[]);
alpha ~ dnorm(0.0,1.0E-4);
beta ~ dnorm(0.0,1.0E-4);
tau ~ dgamma(1.0E-3,1.0E-3);
sigma <- 1.0/sqrt(tau);
}
"
```
Next, define which variables should be monitored (if => true).
```
monitors = (String => Bool)[
"alpha" => true,
"beta" => true,
"tau" => true,
"sigma" => true,
]
```
The next step is to create and initialize a Jagsmodel:
```
jagsmodel = Jagsmodel(
name="line1",
model=line,
monitor=monitors,
#ncommands=1, nchains=4,
#deviance=true, dic=true, popt=true,
pdir=ProjDir);
println("\nJagsmodel that will be used:")
jagsmodel |> display
```
Notice that by default a single command with 4 chains is created. It is possible to run each of the 4 chains in a separate process which has advantages. Using the Bones example as a testcase, on my machine running 1 command simulating a single chain takes 6 seconds, 4 (parallel) commands each simulating 1 chain takes about 9 seconds and a single command simulating 4 chains takes about 25 seconds. Of course this is dependent on the number of available cores and assumes the drawing of samples takes a reasonable chunk of time vs. running a command in a new shell.
Running chains in separate commands does need additional data to be passed in through the initialization data and is demonstrated in Examples/Line2. Some more details are given below.
If nchains is set to 1, this is updated in Jagsmodel() if dic and/or popt is requested. Jags needs minimally 2 chains to compute those.
The input data for the line example is in below data dictionary:
```
data = Dict(
"x" => [1, 2, 3, 4, 5],
"y" => [1, 3, 3, 3, 5],
"n" => 5
)
println("Input observed data dictionary:")
data |> display
```
Next define an array of dictionaries with initial values for parameters. If the array of dictionaries has not enough elements, the elements will be recycled for chains/commands:
```
inits = [
Dict("alpha" => 0,"beta" => 0,"tau" => 1),
Dict("alpha" => 1,"beta" => 2,"tau" => 1),
Dict("alpha" => 3,"beta" => 3,"tau" => 2),
Dict("alpha" => 5,"beta" => 2,"tau" => 5)
]
#### Note: Multiple init sets is the best option to get independent chains.
println("\nInput initial values dictionary:")
inits |> display
println()
```
Run the mcmc simulation, passing in the model, the data, the initial values and the working directory. If 'inits' is a single dictionary, it needs to be passed in as '[inits]', see the Bones example.
```
sim = jags(jagsmodel, data, inits, ProjDir)
describe(sim)
println()
```
## Running a Jags script, some details
Jags.jl really only consists of 2 functions, Jagsmodel() and jags().
Jagsmodel() is used to define and set up the basic structure to run a simulation.
The full signature of Jagsmodel() is:
```
function Jagsmodel(;
name="Noname",
model="",
ncommands=1,
nchains=4,
adapt=1000,
nsamples=10000,
thin=10,
jagsthin=1,
monitor=Dict(),
deviance=false,
dic=false,
popt=false,
updatejagsfile=true,
pdir=pwd())
```
All arguments are keyword arguments and have default values, although usually at least the name and model arguments will be provided.
After a Jagsmodel has been created, the workhorse function jags() is called to run the simulation, passing in the Jagsmodel, the data and the initialization for the chains.
As Jags needs quite a few input files and produces several output files, these are all stored in a subdirectory of the working directory, typically called 'tmp'.
The full signature of jags() is:
```
function jags(
model::Jagsmodel,
data::Dict{String, Any}=Dict{String, Any}(),
init::Array{Dict{String, Any}, 1} = Dict{String, Any}[],
ProjDir=pwd();
updatedatafile::Bool=true,
updateinitfiles::Bool=true
)
```
All parameters to compile and run the Jags script are implicitly passed in through the model argument.
The Line2 example shows how to run multiple Jags simulations in parallel. The most simple case, e.g. 4 commands, each with a single chain, can be initialized with an 'inits' like shown below:
```
inits = [
Dict("alpha" => 0,"beta" => 0,"tau" => 1,".RNG.name" => "base::Wichmann-Hill"),
Dict("alpha" => 1,"beta" => 2,"tau" => 1,".RNG.name" => "base::Marsaglia-Multicarry"),
Dict("alpha" => 3,"beta" => 3,"tau" => 2,".RNG.name" => "base::Super-Duper"),
Dict("alpha" => 5,"beta" => 2,"tau" => 5,".RNG.name" => "base::Mersenne-Twister")
]
```
The first entry in the 'inits' array will be passed into the first chain in the first command process, the second entry to the second process, etc. A second chain in the first command would be initialized with the second entry, etc.
## To do
More features will be added as requested by users and as time permits. Please file an issue/comment/request.
**Note 1:** In order to support platforms other than OS X, help is needed to test on such platforms.
| Jags | https://github.com/JagsJulia/Jags.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2997 | #
# ======================================================================
# Import some chemistry and materials science data tables from
# ASE. Without this data, JuLIP can do very little!
# ======================================================================
#
using PyCall, JSON
@pyimport ase.data as ase_data
asedata = Dict(
:symbols => ase_data.chemical_symbols,
:masses => ase_data.atomic_masses,
:refstates => ase_data.reference_states
)
write(@__DIR__() * "/asedata.json", JSON.json(asedata, 0))
# ======================================================================
# NOTE:
# some other data that we could consider adding
# asedata.atomic_numbers
# ase_data.atomic_names
# ase_data.covalent_radii
# ase_data.ground_state_magnetic_moments
# ase_data.vdw_radii
# can we get some more stuff like electron affinity somewhere?
# function rnn_old(species::Symbol)
# X = positions(bulk(species) * 2)
# return minimum( norm(X[n]-X[m]) for n = 1:length(X) for m = n+1:length(X) )
# end
#
# _rnn = fill(-1.0, length(_symbols))
# for n = 2:length(_symbols)
# z = n-1
# try
# _rnn[n] = rnn_old(JuLIP.Chemistry.chemical_symbol(z))
# catch
# end
# end
# ======================================================================
# get access to the atomic numbers
ase_emt = pyimport("ase.calculators.emt")
ase_data = pyimport("ase.data")
function emt_default_parameters()
# import everything we need from ASE
Bohr = ase_emt.Bohr
# get_atomic_numbers(id::AbstractString) = ase_data.atomic_numbers[id]
ase_parameters = ase_emt.parameters
beta = ase_emt.beta
# convert ASE style Dict to a new Dict where parameters
# are stored in a type instead of tuple.
params = Dict{String, Dict{String,Float64}}()
maxseq = maximum([par[2] for par in values(ase_parameters)]) * Bohr # ✓
rc = beta * maxseq * 0.5 * (sqrt(3) + sqrt(4)) # ✓
rr = rc * 2 * sqrt(4) / (sqrt(3) + sqrt(4)) # ✓
acut = log(9999.0) / (rr - rc) # ✓
for (key, p) in ase_parameters # p is a tuple of parameters, key a species
s0 = p[2] * Bohr
eta2 = p[4] / Bohr
kappa = p[5] / Bohr
x = eta2 * beta * s0
gamma1 = 0.0
gamma2 = 0.0
for (i, n) in enumerate([12; 6; 24])
r = s0 * beta * sqrt(i)
x = n / (12.0 * (1.0 + exp(acut * (r - rc))))
gamma1 += x * exp(-eta2 * (r - beta * s0))
gamma2 += x * exp(-kappa / beta * (r - beta * s0))
end
params[key] = Dict{String, Float64}(
"E0" => p[1], "s0" => s0, "V0" => p[3], "η2" => eta2,
"κ" => kappa, "λ" => p[6] / Bohr, "n0" => p[7] / Bohr^3,
"γ1" => gamma1, "γ2" => gamma2 )
par = params[key]
par["Cpair"] = -0.5 * par["V0"] / par["γ2"] / par["n0"]
end
return Dict("params" => params, "acut" => acut, "rc" => rc, "beta" => beta)
end
emt_data = emt_default_parameters()
write(@__DIR__() * "/emt.json", JSON.json(emt_data, 0))
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 485 | using Documenter, JuLIP
makedocs(
modules = [JuLIP],
clean = false,
format = Documenter.Formats.HTML,
sitename = "JuLIP.jl",
pages = [
"Home" => "index.md",
"Implementation Notes" => "ImplementationNotes.md",
"Temporary Notes" => "tempnotes.md"
]
)
# deploydocs(
# julia = "nightly",
# repo = "github.com/JuliaDocs/Documenter.jl.git",
# target = "build",
# deps = nothing,
# make = nothing,
# )
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 3472 | using JuLIP, BenchmarkTools, ReverseDiff
using JuLIP.Potentials: evaluate_d!
const r0 = rnn(:Cu)
const rcut = 2.5 * r0
# --------------- EAM Potential based on ForwardDiff -------------------
eam1 = let r0 = r0, rcut = rcut
ρ(r) = exp(-3*(r/r0-1.0)) - exp(-3*(rcut/r0-1.0) ) +
3 * exp( - 3 * (rcut/r0 - 1.0) ) * (r/r0 - rcut/r0)
Rs -> sqrt(sum(ρ ∘ norm, R))
end
V_fd = ADPotential(eam1, rcut)
# --------------- EAM Potential based on ReverseDiff -------------------
# Still need to figure out how to incorporate ReverseDiff into
# JuLIP, so there are no convenience wrappers for this
eam_mat = let r0 = r0, rcut = rcut
ρ(r) = exp(-3*(r/r0-1.0)) - exp(-3*(rcut/r0-1.0) ) +
3 * exp( - 3 * (rcut/r0 - 1.0) ) * (r/r0 - rcut/r0)
Rs -> sqrt(sum(ρ(norm(@view Rs[:, n])) for n = 1:size(Rs, 2)))
end
eam_rd = Rs -> eam_mat(mat(Rs))
eam_rd_d = Rs -> ReverseDiff.gradient(
s -> eam_mat(reshape(s, (3, length(s) ÷ 3))), mat(Rs)[:]) |> vecs
# --------------- EAM Potential based on JuLIP Machinery -------------------
# hand-coded EAM, only ρ, ϕ, √ are differentiated symbolically
# (i.e. source code transformation, and NOT ForwardDiff / ReverseDiff)
V_j = EAM( ZeroPairPotential(),
(@analytic r -> exp(-3*(r/r0-1.0))) * C1Shift(rcut),
(@analytic t -> sqrt(t)) )
R = []
F = []
println("Timing of Site-Potential Calls")
for N in [10, 20, 40, 80]
println("$N neighbours")
R = r0 + rand(JVecF, N)
F = similar(R)
r = norm.(R)
@assert V_fd(R) ≈ V_j(r, R)
print(" ForwardDiff: V: ")
@btime V_fd($R)
print(" ReverseDiff: V: ")
@btime eam_rd($R)
print(" JuLIP: V: ")
@btime V_j($R)
print(" ForwardDiff: ∇V: ")
@btime (@D V_fd($R))
print(" ReverseDiff: ∇V: ")
@btime eam_rd_d($R)
print(" JuLIP: ∇V: ")
@btime evaluate_d!($F, $V_j, $r, $R)
end
# Timing of Site-Potential Calls
# 10 neighbours
# ForwardDiff: V: 1.262 μs (44 allocations: 1.16 KiB)
# ReverseDiff: V: 1.123 μs (45 allocations: 1.11 KiB)
# JuLIP: V: 197.062 ns (2 allocations: 176 bytes)
# ForwardDiff: ∇V: 15.068 μs (147 allocations: 7.89 KiB)
# ReverseDiff: ∇V: 346.711 μs (1593 allocations: 49.69 KiB)
# JuLIP: ∇V: 324.797 ns (4 allocations: 112 bytes)
# 20 neighbours
# ForwardDiff: V: 2.126 μs (84 allocations: 2.17 KiB)
# ReverseDiff: V: 2.052 μs (85 allocations: 2.05 KiB)
# JuLIP: V: 319.104 ns (2 allocations: 256 bytes)
# ForwardDiff: ∇V: 25.205 μs (522 allocations: 19.86 KiB)
# ReverseDiff: ∇V: 727.735 μs (3164 allocations: 98.28 KiB)
# JuLIP: ∇V: 574.875 ns (4 allocations: 112 bytes)
# 40 neighbours
# ForwardDiff: V: 3.914 μs (164 allocations: 4.25 KiB)
# ReverseDiff: V: 3.900 μs (165 allocations: 3.92 KiB)
# JuLIP: V: 584.110 ns (2 allocations: 464 bytes)
# ForwardDiff: ∇V: 61.363 μs (1992 allocations: 60.78 KiB)
# ReverseDiff: ∇V: 1.429 ms (6305 allocations: 195.53 KiB)
# JuLIP: ∇V: 1.062 μs (4 allocations: 112 bytes)
# 80 neighbours
# ForwardDiff: V: 7.824 μs (324 allocations: 8.28 KiB)
# ReverseDiff: V: 7.654 μs (325 allocations: 7.67 KiB)
# JuLIP: V: 1.093 μs (2 allocations: 752 bytes)
# ForwardDiff: ∇V: 192.137 μs (7813 allocations: 209.86 KiB)
# ReverseDiff: ∇V: 2.900 ms (12586 allocations: 389.66 KiB)
# JuLIP: ∇V: 2.049 μs (4 allocations: 112 bytes)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2947 |
# testing performance of AD
# conclusion is that it scales linearly with dimension;
# however it is a factor 100 slower than the objective.
using BenchmarkTools
using ReverseDiff: GradientTape, GradientConfig, gradient, gradient!, compile
import ForwardDiff
ϕ(r) = exp( - 6 * (abs(r)-1)) - 2 * exp( - 3 * (abs(r)-1))
dϕ(r) = ForwardDiff.derivative(ϕ, r)
ρ(r) = exp( - 4 * (abs(r)-1) )
dρ(r) = ForwardDiff.derivative(ρ, r)
ψ(t) = sqrt(t)
dψ(t) = ForwardDiff.derivative(ψ, t)
function get_rho(x)
N = length(x)
rho = zeros(eltype(x), N)
for n = 2:N
t = ρ(x[n]-x[n-1])
rho[n-1] += t
rho[n] += 1
end
for n = 3:N
t = ρ(x[n] - x[n-2])
rho[n] += t
rho[n-2] += t
end
return rho
end
function F(x)
N = length(x)
E = 0.0
for j = 1:2, n = (1+j):N
E += ϕ(x[n]-x[n-j])
end
return E + sum(ψ, get_rho(x))
end
function dF(x)
N = length(x)
dE = zeros(N)
F = ψ.(get_rho(x))
for j = 1:2, n = (1+j):N
dϕ_ = dϕ(x[n]-x[n-j])
dρ_ = dρ(x[n]-x[n-j])
a = dϕ_ + (F[n] - F[n-j]) * dρ_
dE[n] += a
dE[n-j] -= a
end
return dE
end
x = gresult = compiled_f_tape = nothing
for N in (100, 400, 1600)
# pre-record a GradientTape for `F` using inputs with Float64 elements
f_tape = GradientTape(F, rand(N))
# compile `f_tape` into a more optimized representation
compiled_f_tape = compile(f_tape)
# some inputs and work buffers to play around with
gresult = zeros(N)
x = collect(1:N) + rand(N)
println("N = $N")
print(" Time for F: ")
@btime F($x)
print(" Time for DF (ForwardDiff): ")
@btime ForwardDiff.gradient($F, $x)
print(" Time for DF (ReverseDiff): ")
@btime gradient!($gresult, $compiled_f_tape, $x)
print(" Time for DF(manual): ")
@btime dF($x)
end
# RESULTS 03/04/2018, MacBook Pro, Julia v0.6.2,
# - ForwardDiff 0.7.4
# - ReverseDiff 0.2.0
#
# N = 8000
# Time for F:
# 564.137 μs (2 allocations: 62.58 KiB)
# Time for DF (ForwardDiff):
# N = 100
# Time for F: 6.191 μs (1 allocation: 896 bytes)
# Time for DF (ForwardDiff): 409.391 μs (6043 allocations: 659.25 KiB)
# Time for DF (ReverseDiff): 451.058 μs (0 allocations: 0 bytes)
# Time for DF(manual): 17.426 μs (3 allocations: 2.63 KiB)
# N = 400
# Time for F: 26.206 μs (1 allocation: 3.25 KiB)
# Time for DF (ForwardDiff): 6.538 ms (96204 allocations: 10.17 MiB)
# Time for DF (ReverseDiff): 1.999 ms (0 allocations: 0 bytes)
# Time for DF(manual): 63.400 μs (3 allocations: 9.75 KiB)
# N = 1600
# Time for F: 109.590 μs (1 allocation: 12.63 KiB)
# Time for DF (ForwardDiff): 155.275 ms (1536804 allocations: 162.25 MiB)
# Time for DF (ReverseDiff): 15.896 ms (0 allocations: 0 bytes)
# Time for DF(manual): 260.063 μs (3 allocations: 37.88 KiB)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 1838 |
module MultiLJ
using JuLIP
using JuLIP.Potentials: pairs
using LinearAlgebra: I
import JuLIP: energy, forces, cutoff
export MLJ
struct MLJ{T} <: AbstractCalculator
Z2idx::Vector{Int}
V::Matrix{T}
rcut::Float64
end
@pot MLJ
cutoff(V::MLJ) = V.rcut
function MLJ(Z, ϵ, σ; rcutfact = 2.5)
@assert length(Z) == length(unique(Z))
# create a mapping from atomic numbers to indices
Z2idx = zeros(Int, maximum(Z))
Z2idx[Z] = 1:length(Z)
# generate the potential
rcut = maximum(σ) * rcutfact
V = [ LennardJones(σ[a,b], ϵ[a, b]) * C2Shift(σ[a,b] * rcutfact)
for a = 1:length(Z), b = 1:length(Z) ]
return MLJ(Z2idx, V, rcut)
end
function energy(V::MLJ, at::Atoms)
E = 0.0
for (i, j, r, R) in pairs(at, cutoff(V))
a = V.Z2idx[at.Z[i]]
b = V.Z2idx[at.Z[j]]
E += 0.5 * V.V[a, b](r)
end
return E
end
function forces(V::MLJ, at::Atoms)
F = zeros(JVecF, length(at))
for (i, j, r, R) in pairs(at, cutoff(V))
a = V.Z2idx[at.Z[i]]
b = V.Z2idx[at.Z[j]]
f = 0.5 * grad(V.V[a,b], r, R)
F[i] += f
F[j] -= f
end
return F
end
end
# --------------
# test code
# --------------
using JuLIP, MultiLJ, StaticArrays
# parameters from PHYS REV B, VOLUME 64, 184201
# Crystals of binary Lennard-Jones solids
# T F Middleton, J Hernandez-Rojas, P N Mortenson, D J Wales
ϵ = [1.0 1.5; 1.5 0.5]
σ = [1.0 0.8; 0.8 0.88]
z = [1, 2]
V = MultiLJ.MLJ(z, ϵ, σ)
#
n = 2
x, o = 0:n, ones(n)
X = [ kron(x, o, o)[:]'; kron(o, x, o)'; kron(o, o, x)' ]
X = vecs( X + 0.05 * rand(size(X)) )
Nat = length(X)
at = Atoms(X, zeros(X), ones(Nat), rand(z, Nat), 5 * Matrix(1.0I, 3,3), false; calc = V)
# check that energy and forces evaluate ok
energy(V, at)
forces(V, at)
# finite-difference test
JuLIP.Testing.fdtest(V, at)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 7619 | # TODO: switch all cell(at)' to cell(at) and store cells
"""
`module Constraints`
TODO: write documentation
"""
module Constraints
using JuLIP: Dofs, AbstractConstraint, AbstractAtoms, AbstractCalculator,
mat, vecs, JMat, JVec,
set_positions!, set_cell!, virial, cell,
forces, momenta, set_momenta!,
constraint, rnn, calculator, hessian_pos
import JuLIP: position_dofs, project!, set_position_dofs!, positions,
momentum_dofs, set_momentum_dofs!, dofs,
set_dofs!, positions, energy, gradient, hessian
export FixedCell, VariableCell, InPlaneFixedCell, AntiPlaneFixedCell, atomdofs
using SparseArrays: SparseMatrixCSC, nnz, sparse, findnz
using LinearAlgebra: rmul!, det
# ========================================================================
# FIXED CELL IMPLEMENTATION
# ========================================================================
"""
`FixedCell`: no constraints are placed on the motion of atoms, but the
cell shape is fixed
Constructor:
```julia
FixedCell(at::AbstractAtoms; free=..., clamp=..., mask=...)
```
Set at most one of the kwargs:
* no kwarg: all atoms are free
* `free` : list of free atom indices (not dof indices)
* `clamp` : list of clamped atom indices (not dof indices)
* `mask` : 3 x N Bool array to specify individual coordinates to be clamped
"""
struct FixedCell <: AbstractConstraint
ifree::Vector{Int}
end
FixedCell(at::AbstractAtoms; clamp = nothing, free=nothing, mask=nothing) =
FixedCell(analyze_mask(at, free, clamp, mask))
position_dofs(at::AbstractAtoms, cons::FixedCell) = mat(positions(at))[cons.ifree]
set_position_dofs!(at::AbstractAtoms, cons::FixedCell, x::Dofs) =
set_positions!(at, positions(at, cons.ifree, x))
momentum_dofs(at::AbstractAtoms, cons::FixedCell) = mat(momenta(at))[cons.ifree]
set_momentum_dofs!(at::AbstractAtoms, cons::FixedCell, p::Dofs) =
set_momenta!(at, zeros_free(3 * length(at), p, cons.ifree) |> vecs)
project!(at::AbstractAtoms, cons::FixedCell) = at
gradient(calc::AbstractCalculator, at::AbstractAtoms, cons::FixedCell) =
rmul!(mat(forces(at))[cons.ifree], -1.0)
energy(calc::AbstractCalculator, at::AbstractAtoms, cons::FixedCell) =
energy(calc, at)
hessian(calc::AbstractCalculator, at::AbstractAtoms, cons::FixedCell) =
project(cons, _pos_to_dof(hessian_pos(calculator(at), at), at))
# TODO: this is a temporary hack, and I think we need to
# figure out how to do this for more general constraints
# maybe not too terrible
project(cons::FixedCell, A::SparseMatrixCSC) = A[cons.ifree, cons.ifree]
# ===========================
# 2D FixedCell Constraints
# ===========================
"""
preliminary implementation of a Constraint, restricting a
simulation to 2D in-plane motion
"""
function InPlaneFixedCell(at::AbstractAtoms; clamp = Int[], free = nothing)
if free == nothing
free = setdiff(1:length(at), clamp)
end
mask = fill(false, (3, length(at)))
mask[:, free] = true
mask[3, :] = false
return FixedCell(at, mask = mask)
end
"""
preliminary implementation of a Constraint, restricting a
simulation to 2D out-of-plane motion
"""
function AntiPlaneFixedCell(at::AbstractAtoms; free = Int[])
mask = fill(false, (3, length(at)))
mask[:, free] = true
mask[1:2, :] = false
return FixedCell(at, mask = mask)
end
# ========================================================================
# VARIABLE CELL IMPLEMENTATION
# ========================================================================
"""
`VariableCell`: both atom positions and cell shape are free;
**WARNING:** (1) before manipulating the dof-vectors returned by a `VariableCell`
constraint, read *meaning of dofs* instructions at bottom of help text!
(2) The `volume` field is a signed volume.
Constructor:
```julia
VariableCell(at::AbstractAtoms; free=..., clamp=..., mask=..., fixvolume=false)
```
Set at most one of the kwargs:
* no kwarg: all atoms are free
* `free` : list of free atom indices (not dof indices)
* `clamp` : list of clamped atom indices (not dof indices)
* `mask` : 3 x N Bool array to specify individual coordinates to be clamped
### Meaning of dofs
On call to the constructor, `VariableCell` stored positions and deformation
`X0, F0`, dofs are understood *relative* to this initial configuration.
`dofs(at, cons::VariableCell)` returns a vector that represents a pair
`(Y, F1)` of a displacement and a deformation matrix. These are to be understood
*relative* to the reference `X0, F0` stored in `cons` as follows:
* `F = F1` (the cell is then `F'`)
* `X = [F1 * (F0 \\ y) for y in Y)]`
One aspect of this definition is that clamped atom positions still change via
`F`
"""
struct VariableCell{T} <: AbstractConstraint
ifree::Vector{Int}
X0::Vector{JVec{T}}
F0::JMat{T}
pressure::T
fixvolume::Bool
volume::T # this is meaningless if `fixvolume == false`
end
function VariableCell(at::AbstractAtoms;
free=nothing, clamp=nothing, mask=nothing,
pressure = 0.0, fixvolume=false)
if pressure != 0.0 && fixvolume
@warn("the pressure parameter will be ignored when `fixvolume==true`")
end
return VariableCell( analyze_mask(at, free, clamp, mask),
positions(at), cell(at)',
pressure, fixvolume, det(cell(at)) )
end
# reverse map:
# F -> F
# X[n] = F * F^{-1} X0[n]
function position_dofs(at::AbstractAtoms, cons::VariableCell)
X = positions(at)
F = cell(at)'
A = cons.F0 * inv(F)
U = [A * x for x in X] # switch to broadcast!
return [mat(U)[cons.ifree]; Matrix(F)[:]]
end
posdofs(x) = x[1:end-9]
celldofs(x) = x[end-8:end]
function set_position_dofs!(at::AbstractAtoms{T}, cons::VariableCell, x::Dofs
) where {T}
F = JMat{T}(celldofs(x))
A = F * inv(cons.F0)
Y = copy(cons.X0)
mat(Y)[cons.ifree] = posdofs(x)
for n = 1:length(Y)
Y[n] = A * Y[n]
end
set_positions!(at, Y)
set_cell!(at, F')
return at
end
# for a variation x^t_i = (F+tU) F_0^{-1} (u_i + t v_i)
# ~ U F^{-1} F F0^{-1} u_i + F F0^{-1} v_i
# we get
# dE/dt |_{t=0} = U : (S F^{-T}) - < (F * inv(F0))' * frc, v>
#
# this is nice because there is no contribution from the stress to
# the positions component of the gradient
"""
`sigvol` : signed volume
"""
sigvol(C::AbstractMatrix) = det(C)
sigvol(at::AbstractAtoms) = sigvol(cell(at))
"""
`sigvol_d` : derivative of signed volume
"""
sigvol_d(C::AbstractMatrix) = sigvol(C) * inv(C)'
sigvol_d(at::AbstractAtoms) = sigvol_d(cell(at))
# sigvol_d(at::AbstractAtoms) = sigvol(at) * inv(cell(at))
function gradient(calc::AbstractCalculator, at::AbstractAtoms, cons::VariableCell)
F = cell(at)'
A = F * inv(cons.F0)
G = forces(at)
for n = 1:length(G)
G[n] = - A' * G[n]
end
S = - virial(at) * inv(F)' # ∂E / ∂F
S += cons.pressure * sigvol_d(at)' # applied stress
return [ mat(G)[cons.ifree]; Array(S)[:] ]
end
energy(calc::AbstractCalculator, at::AbstractAtoms, cons::VariableCell) =
energy(calc, at) + cons.pressure * sigvol(at)
# TODO: fix this once we implement the volume constraint ??????
# => or just disallow the volume constraint for now?
project!(at::AbstractAtoms, cons::VariableCell) = at
# TODO: CONTINUE WITH EXPCELL IMPLEMENTATION
# include("expcell.jl")
# convenience function to return DoFs associated with a particular atom
atomdofs(a::AbstractAtoms, I::Integer) = findall(in(3*I-2:3*I), constraint(a).ifree)
end # module
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2138 | """
`module Experimental`
TODO: write documentation
"""
module Experimental
using JuLIP: AbstractAtoms, dofs, set_dofs!, atomdofs
using JuLIP.Potentials
using ForwardDiff
export newton!, constrained_bond_newton!
function newton(x, g, h; maxsteps=10, tol=1e-5)
for i in 1:maxsteps
gi = g(x)
norm(gi, Inf) < tol && break
x = x - h(x) \ gi
@show i, norm(gi, Inf)
end
return x
end
function newton!(a::AbstractAtoms; maxsteps=20, tol=1e-10)
x = newton(dofs(a),
x -> gradient(a, x),
x -> hessian(a, x))
set_dofs!(a, x)
return x
end
function constrained_bond_newton!(a::AbstractAtoms, i::Integer, j::Integer,
bondlength::AbstractFloat;
maxsteps=20, tol=1e-10)
I1 = atomdofs(a, i)
I2 = atomdofs(a, j)
I1I2 = [I1; I2]
# bondlength of target bond
blen(x) = norm(x[I2] - x[I1])
# constraint function
c(x) = blen(x) - bondlength
# gradient of constraint
function dc(x)
r = zeros(length(x))
r[I1] = (x[I1]-x[I2])/blen(x)
r[I2] = (x[I2]-x[I1])/blen(x)
return r
end
# define some auxiliary index arrays that start at 1 to
# allow the ForwardDiff hessian to be done only on relevent dofs, x[I1I2]
_I1 = 1:length(I1)
_I2 = length(I1)+1:length(I1)+length(I2)
_blen(x) = norm(x[_I2] - x[_I1])
_c(x) = _blen(x) - bondlength
function ddc(x)
s = spzeros(length(x), length(x))
s[I1I2, I1I2] = ForwardDiff.hessian(_c, x[I1I2])
return s
end
# Define Lagrangian L(x, λ) = E - λC and its gradient and hessian
L(x, λ) = energy(a, x) - λ*c(x)
L(z) = L(z[1:end-1], z[end])
dL(x, λ) = [gradient(a, x) - λ * dc(x); -c(x)]
dL(z) = dL(z[1:end-1], z[end])
ddL(x, λ) = [(hessian(a, x) - λ * ddc(x)) -dc(x); -dc(x)' 0.]
ddL(z) = ddL(z[1:end-1], z[end])
# Use Newton scheme to find saddles L where ∇L = 0
z = [dofs(a); -10.0*c(dofs(a))]
z = newton(z, dL, ddL, maxsteps=maxsteps, tol=tol)
set_dofs!(a, z[1:end-1])
return z
end
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2391 |
"""
`JuLIP.FIO` : provides some basis file IO. All sub-modules and derived
packages should use these interface functions so that the file formats
can be changed later. This submodule provides
- load_dict
- save_dict
- decode_dict
"""
module FIO
using JSON
export load_dict, save_dict, decode_dict, save_json, load_json
#######################################################################
# Conversions to and from Dict
#######################################################################
# eventually we want to be able to serialise all JuLIP types to Dict
# and back and those Dicts may only contain elementary data types
# this will then allow us to load them back via decode_dict without
# having to know the type in the code
"""
`decode_dict(D::Dict) -> ?`
Looks for a key `__id__` in `D` whose value is used to dynamically dispatch
the decoding to
```julia
convert(Val(Symbol(D["__id__"])))
```
That is, a user defined type must implement this `convert(::Val, ::Dict)`
utility function. The typical code would be
```julia
module MyModule
struct MyStructA
a::Float64
end
Dict(A::MyStructA) = Dict( "__id__" -> "MyModule_MyStructA",
"a" -> a )
MyStructA(D::Dict) = A(D["a"])
Base.convert(::Val{:MyModule_MyStructA})
end
```
The user is responsible for choosing an id that is sufficiently unique.
The purpose of this function is to enable the loading of more complex JSON files
and automatically converting the parsed Dict into the appropriate composite
types. It is intentional that a significant burden is put on the user code
here. This will maximise flexibiliy, e.g., by introducing version numbers,
and being able to read old version in the future.
"""
function decode_dict(D::Dict)
if !haskey(D, "__id__")
@error("JuLIP.IO.decode_dict: `D` has no key `__id__`")
end
return convert(Val(Symbol(D["__id__"])), D)
end
#######################################################################
# JSON
#######################################################################
function load_dict(fname::AbstractString)
return JSON.parsefile(fname)
end
function save_dict(fname::AbstractString, D::Dict; indent=2)
f = open(fname, "w")
JSON.print(f, D, indent)
close(f)
return nothing
end
save_json = save_dict
load_json = load_dict
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 1252 |
# JuLIP.jl master file.
module JuLIP
using Reexport
@reexport using NeighbourLists
# quickly switch between Matrices and Vectors of SVectors, etc
include("arrayconversions.jl")
# File IO
include("FIO.jl")
@reexport using JuLIP.FIO
# define types and abstractions of generic functions
include("abstractions.jl")
include("chemistry.jl")
@reexport using JuLIP.Chemistry
# the main atoms type
include("atoms.jl")
include("dofmanagement.jl")
# how to build some simple domains
include("build.jl")
@reexport using JuLIP.Build
# a few auxiliary routines
include("utils.jl")
@reexport using JuLIP.Utils
# interatomic potentials prototypes and some example implementations
include("Potentials.jl")
@reexport using JuLIP.Potentials
# basic preconditioning capabilities
include("preconditioners.jl")
@reexport using JuLIP.Preconditioners
# some solvers
include("Solve.jl")
@reexport using JuLIP.Solve
# experimental features
include("Experimental.jl")
@reexport using JuLIP.Experimental
# the following are some sub-modules that are primarily used
# to create further abstractions to be shared across several
# modules in the JuLIP-verse.
include("mlips.jl")
include("nbody.jl")
# codes to facilitate testing
include("Testing.jl")
end # module
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 6928 | """
## module Potentials
### Summary
This module implements some basic interatomic potentials in pure Julia, as well
as provides building blocks and prototypes for further implementations
The implementation is done in such a way that they can be used either in "raw"
form or withinabstractframeworks.
### Types
### `evaluate`, `evaluate_d`, `evaluate_dd`, `grad`
### The `@D`, `@DD`, `@GRAD` macros
TODO: write documentation
"""
module Potentials
using JuLIP: AbstractAtoms, AbstractCalculator,
JVec, mat, vec, JMat, SVec, vecs, SMat,
positions, set_positions!
using StaticArrays: @SMatrix
using NeighbourLists
using LinearAlgebra: norm
using SparseArrays: sparse
import JuLIP: energy, forces, cutoff, virial, hessian_pos, hessian,
site_energies, r_sum,
site_energy, site_energy_d,
energy!, forces!, virial!,
alloc_temp, alloc_temp_d, alloc_temp_dd
export PairPotential, SitePotential, ZeroSitePotential
# the following are prototypes for internal functions around which IPs are
# defined
function evaluate end
function evaluate_d end
function evaluate_dd end
function evaluate! end
function evaluate_d! end
function evaluate_dd! end
function grad end
function precond end
include("potentials_base.jl")
# * @pot, @D, @DD, @GRAD and related things
"""
`SitePotential`:abstractsupertype for generic site potentials
"""
abstract type SitePotential <: AbstractCalculator end
"""
`PairPotential`:abstractsupertype for pair potentials
Can also be used as a constructor for analytic pair potentials, e.g.,
```julia
lj = @analytic r -> r^(-12) - 2 * r^(-6)
```
"""
abstract type PairPotential <: SitePotential end
evaluate(V::SitePotential, R) =
evaluate!(alloc_temp(V, length(R)), V, R)
evaluate_d(V::SitePotential, R::AbstractVector{JVec{T}}) where {T} =
evaluate_d!(zeros(JVec{T}, length(R)),
alloc_temp_d(V, length(R)),
V, R)
evaluate_dd(V::SitePotential, R::AbstractVector{JVec{T}}) where {T} =
evaluate_dd!(zeros(JMat{T}, length(R), length(R)),
alloc_temp_dd(V, length(R)),
V, R)
evaluate(V::PairPotential, r::Number) = evaluate!(alloc_temp(V, 1), V, r)
evaluate_d(V::PairPotential, r::Number) = evaluate_d!(alloc_temp_d(V, 1), V, r)
evaluate_dd(V::PairPotential, r::Number) = evaluate_dd!(alloc_temp_d(V, 1), V, r)
NeighbourLists.sites(at::AbstractAtoms, rcut::AbstractFloat) =
sites(neighbourlist(at, rcut))
NeighbourLists.pairs(at::AbstractAtoms, rcut::AbstractFloat) =
pairs(neighbourlist(at, rcut))
"a site potential that just returns zero"
mutable struct ZeroSitePotential <: SitePotential
end
@pot ZeroSitePotential
cutoff(::ZeroSitePotential) = Bool(0)
energy(V::ZeroSitePotential, at::AbstractAtoms{T}; kwargs...) where T = zero(T)
forces(V::ZeroSitePotential, at::AbstractAtoms{T}; kwargs...) where T = zeros(JVec{T}, length(at))
evaluate!(tmp, p::ZeroSitePotential, args...) = Bool(0)
evaluate_d!(dEs, tmp, V::ZeroSitePotential, args...) = fill!(dEs, zero(eltype(dEs)))
evaluate_dd!(hEs, tmp, V::ZeroSitePotential, args...) = fill!(hEs, zero(eltype(hEs)))
# Implementation of a generic site potential
# ================================================
alloc_temp(V::SitePotential, at::AbstractAtoms) =
alloc_temp(V, maxneigs(neighbourlist(at, cutoff(V))))
alloc_temp(V::SitePotential, N::Integer) = ( R = zeros(JVecF, N), )
alloc_temp_d(V::SitePotential, at::AbstractAtoms) =
alloc_temp_d(V, maxneigs(neighbourlist(at, cutoff(V))))
alloc_temp_d(V::SitePotential, N::Integer) = ( R = zeros(JVecF, N),
dV = zeros(JVecF, N) )
alloc_temp_dd(V::SitePotential, N::Integer) = nothing
energy(V::SitePotential, at::AbstractAtoms; kwargs...) =
energy!(alloc_temp(V, at), V, at; kwargs...)
virial(V::SitePotential, at::AbstractAtoms; kwargs...) =
virial!(alloc_temp_d(V, at), V, at; kwargs...)
forces(V::SitePotential, at::AbstractAtoms{T}; kwargs...) where {T} =
forces!(zeros(JVec{T}, length(at)), alloc_temp_d(V, at), V, at; kwargs...)
function energy!(tmp, V::SitePotential, at::AbstractAtoms{T};
domain=1:length(at)) where {T}
E = zero(T)
nlist = neighbourlist(at, cutoff(V))
for i in domain
_j, R = neigs!(tmp.R, nlist, i)
E += evaluate!(tmp, V, R)
end
return E
end
function forces!(frc, tmp, V::SitePotential, at::AbstractAtoms{T};
domain=1:length(at), reset=true) where {T}
if reset; fill!(frc, zero(JVec{T})); end
nlist = neighbourlist(at, cutoff(V))
for i in domain
j, R = neigs!(tmp.R, nlist, i)
evaluate_d!(tmp.dV, tmp, V, R)
for a = 1:length(j)
frc[j[a]] -= tmp.dV[a]
frc[i] += tmp.dV[a]
end
end
return frc
end
site_virial(dV, R::AbstractVector{JVec{T}}) where {T} = (
length(R) > 0 ? (- sum( dVi * Ri' for (dVi, Ri) in zip(dV, R) ))
: zero(JMat{T}) )
function virial!(tmp, V::SitePotential, at::AbstractAtoms{T};
domain=1:length(at)) where {T}
vir = zero(JMat{T})
nlist = neighbourlist(at, cutoff(V))
for i in domain
_j, R = neigs!(tmp.R, nlist, i)
evaluate_d!(tmp.dV, tmp, V, R)
vir += site_virial(tmp.dV, R)
end
return vir
end
site_energies(V::SitePotential, at::AbstractAtoms{T}; kwargs...) where {T} =
site_energies!(zeros(T, length(at)), alloc_temp(V, at), V, at)
function site_energies!(Es, tmp, V::SitePotential, at::AbstractAtoms{T};
domain = 1:length(at)) where {T}
nlist = neighbourlist(at, cutoff(V))
for i in domain
_j, R = neigs!(tmp.R, nlist, i)
Es[i] = evaluate!(tmp, V, R)
end
return Es
end
site_energy(V::SitePotential, at::AbstractAtoms, i0::Integer) =
energy(V, at; domain = (i0,))
site_energy_d(V::SitePotential, at::AbstractAtoms, i0::Integer) =
rmul!(forces(V, at; domain = (i0,)), -one(eltype(at)))
# ------------------------------------------------
# specialisation for Pair potentials
include("analyticpotential.jl")
# * AnalyticFunction
# * F64fun, WrappedAnalyticFunction
include("cutoffs.jl")
# * SWCutoff
# * ShiftCutoff
# * SplineCutoff
include("pairpotentials.jl")
# * PairCalculator
# * LennardJonesPotential
# * MorsePotential
# * SimpleExponential
# * WrappedPairPotential
include("adsite.jl")
# * ADPotential : Site potential using ForwardDiff
include("stillingerweber.jl")
# * type StillingerWeber
include("splines.jl")
include("eam.jl")
# EAM, FinnisSinclair
include("onebody.jl")
# code for 1-body functions ; TODO: move into `nbody`
include("hessians.jl")
# code for hessians of site potentials
include("multi.jl")
# experimental multi-species code
# -> eventually this is to be integrated into all the main codebase
include("emt.jl")
# a simple analytic EAM potential. (EMT -> embedded medium theory)
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 4721 | """
`module JuLIP.Solve`
Contains a few geometry optimisation routines, for now see
the help for these:
* `minimise!`
"""
module Solve
import Optim
import LineSearches
using Optim: OnceDifferentiable, optimize, ConjugateGradient, LBFGS
using LineSearches: BackTracking
using LinearAlgebra: I
using JuLIP: AbstractAtoms, update!,
dofs, energy, gradient, set_dofs!, site_energies,
Dofs, calculator, AbstractCalculator, r_sum, fixedcell
using JuLIP.Potentials: SitePotential
using JuLIP.Preconditioners: Exp
export minimise!
Ediff(V::AbstractCalculator, at::AbstractAtoms, Es0::Vector) =
r_sum(site_energies(V, at) - Es0)
Ediff(at::AbstractAtoms, Es0::Vector, x::Dofs) =
Ediff(calculator(at), set_dofs!(at, x), Es0)
"""
`minimise!(at::AbstractAtoms)`: geometry optimisation
`at` must have a calculator and a constraint attached.
## Keyword arguments:
* `precond = :auto` : preconditioner; more below
* `gtol = 1e-6` : gradient tolerance (max-norm)
* `ftol = 1e-32` : objective tolerance
* `Optimiser = :auto`, `:auto` should always work, at least on the master
branch of `Optim`; `:lbfgs` needs the `extraplbfgs2` branch, which is not
yet merged. Other options might be introduced in the future.
* `verbose = 1`: 0 : no output, 1 : final, 2 : iteration and final
* `robust_energy_difference = false` : if true use Kahan summation of site energies
* `store_trace = false` : store history of energy and norm of forces
* `extended_trace = false`: also store full history of postions and forces
* `maxstep = Inf`: maximum step size, useful if initial gradient is very large
* `callback`: callback function to pass to `optimize()`, e.g. to use alternate convergence criteria
## Preconditioner
`precond` may be a valid preconditioner, e.g., `I` or `Exp(at)`, or one of
the following symbols
* `:auto` : the code will make the best choice it can with the avilable
information
* `:exp` : will use `Exp(at)`
* `:id` : will use `I`
"""
function minimise!(at::AbstractAtoms;
precond = :auto,
method = :auto,
gtol=1e-5, ftol=1e-32,
verbose = 1,
robust_energy_difference = false,
store_trace = false,
extended_trace = false,
maxstep = Inf,
callback = nothing,
g_calls_limit = 1_000)
# create an objective function
if robust_energy_difference
Es0 = site_energies(at)
obj_f = x -> Ediff(at, Es0, x)
else
obj_f = x->energy(at, x)
end
obj_g! = (g, x) -> copyto!(g, gradient(at, x))
# create a preconditioner
if isa(precond, Symbol)
if precond == :auto
if fixedcell(at)
precond = :exp
else
precond = :id
end
end
if precond == :exp
if method == :lbfgs
precond = Exp(at, energyscale = :auto)
else
precond = Exp(at)
end
elseif precond == :id
precond = I
else
error("unknown symbol for precond")
end
end
# choose the optimisation method Optim.jl
if method == :auto || method == :cg
if precond == I
optimiser = ConjugateGradient(linesearch = BackTracking(order=2, maxstep=maxstep))
else
optimiser = ConjugateGradient( P = precond,
precondprep = (P, x) -> update!(P, at, x),
linesearch = BackTracking(order=2, maxstep=maxstep) )
end
elseif method == :lbfgs
optimiser = LBFGS( P = precond,
precondprep = (P, x) -> update!(P, at, x),
alphaguess = LineSearches.InitialHagerZhang(),
linesearch = BackTracking(order=2, maxstep=maxstep) )
elseif method == :sd
optimiser = Optim.GradientDescent( P = precond,
precondprep = (P, x) -> update!(P, at, x),
linesearch = BackTracking(order=2, maxstep=maxstep) )
else
error("JuLIP.Solve.minimise!: unknown `method` option")
end
results = optimize( obj_f, obj_g!, dofs(at), optimiser,
Optim.Options( f_tol = ftol, g_tol = gtol,
g_calls_limit = g_calls_limit,
store_trace = store_trace,
extended_trace = extended_trace,
callback = callback,
show_trace = (verbose > 1)) )
set_dofs!(at, Optim.minimizer(results))
# analyse the results
if verbose > 0
println(results)
end
return results
end
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 5761 |
"""
This module supplies some functions for testing of the implementation.
Look at `?` for
* `fdtest` : general finite-difference test
* `fdtest_R2R`: fd test for F : ℝ → ℝ
"""
module Testing
using Test
using JuLIP: AbstractCalculator, AbstractAtoms, energy, gradient, forces,
calculator, set_positions!, dofs,
mat, vecs, positions, rattle!, set_dofs!, set_calculator!
using JuLIP.Potentials: PairPotential, evaluate, evaluate_d, grad, @D
using Printf
using LinearAlgebra: norm
export fdtest, fdtest_hessian, h0, h1, h2, h3, print_tf
"""
first-order finite-difference test for scalar F
* `fdtest(F::Function, dF::Function, x)`
* `fdtest(V::PairPotential, r::Vector{Float64})`
* `fdtest(calc::AbstractCalculator, at::AbstractAtoms)`
"""
function fdtest(F::Function, dF::Function, x; verbose=true)
errors = Float64[]
E = F(x)
dE = dF(x)
# loop through finite-difference step-lengths
@printf("---------|----------- \n")
@printf(" h | error \n")
@printf("---------|----------- \n")
for p = 2:11
h = 0.1^p
dEh = copy(dE)
for n = 1:length(dE)
x[n] += h
dEh[n] = (F(x) - E) / h
x[n] -= h
end
push!(errors, norm(dE - dEh, Inf))
@printf(" %1.1e | %4.2e \n", h, errors[end])
end
@printf("---------|----------- \n")
if minimum(errors) <= 1e-3 * maximum(errors)
if verbose
println("passed")
end
return true
else
@warn("""It seems the finite-difference test has failed, which indicates
that there is an inconsistency between the function and gradient
evaluation. Please double-check this manually / visually. (It is
also possible that the function being tested is poorly scaled.)""")
return false
end
end
function fdtest_hessian(F::Function, dF::Function, x; verbose=true)
errors = Float64[]
F0 = F(x)
dF0 = dF(x)
dFh = copy(Matrix(dF0))
@assert size(dFh) == (length(F0), length(x))
# loop through finite-difference step-lengths
@printf("---------|----------- \n")
@printf(" h | error \n")
@printf("---------|----------- \n")
for p = 2:11
h = 0.1^p
for n = 1:length(x)
x[n] += h
dFh[:, n] = (F(x) - F0) / h
x[n] -= h
end
push!(errors, norm(dFh - dF0, Inf))
@printf(" %1.1e | %4.2e \n", h, errors[end])
end
@printf("---------|----------- \n")
if minimum(errors) <= 1e-3 * maximum(errors)
println("passed")
return true
else
@warn("""It seems the finite-difference test has failed, which indicates
that there is an inconsistency between the function and gradient
evaluation. Please double-check this manually / visually. (It is
also possible that the function being tested is poorly scaled.)""")
return false
end
end
"finite-difference test for a function V : ℝ → ℝ"
function fdtest_R2R(F::Function, dF::Function, x::Vector{Float64};
verbose=true)
errors = Float64[]
E = [ F(t) for t in x ]
dE = [ dF(t) for t in x ]
# loop through finite-difference step-lengths
if verbose
@printf("---------|----------- \n")
@printf(" h | error \n")
@printf("---------|----------- \n")
end
for p = 2:11
h = 0.1^p
dEh = ([F(t+h) for t in x ] - E) / h
push!(errors, norm(dE - dEh, Inf))
if verbose
@printf(" %1.1e | %4.2e \n", h, errors[end])
end
end
if verbose
@printf("---------|----------- \n")
end
if minimum(errors) <= 1e-3 * maximum(errors[1:2])
println("passed")
return true
else
@warn("""is seems the finite-difference test has failed, which indicates
that there is an inconsistency between the function and gradient
evaluation. Please double-check this manually / visually. (It is
also possible that the function being tested is poorly scaled.)""")
return false
end
end
fdtest(V::PairPotential, r::AbstractVector; kwargs...) =
fdtest_R2R(s -> V(s), s -> (@D V(s)), collect(r); kwargs...)
function fdtest(calc::AbstractCalculator, at::AbstractAtoms;
verbose=true, rattle=0.01)
X0 = copy(positions(at))
calc0 = calculator(at)
set_calculator!(at, calc)
# random perturbation to positions (and cell for VariableCell)
# perturb atom positions a bit to get out of equilibrium states
# Don't use `rattle!` here which screws up the `VariableCell` constraint
# test!!! (but why?!?!?)
x = dofs(at)
x += rattle * rand(length(x))
# call the actual FD test
result = fdtest( x -> energy(at, x), x -> gradient(at, x), x )
# restore original atom positions
set_positions!(at, X0)
set_calculator!(at, calc0)
return result
end
function h0(str)
dashes = "≡"^(length(str)+4)
printstyled(dashes, color=:magenta); println()
printstyled(" "*str*" ", bold=true, color=:magenta); println()
printstyled(dashes, color=:magenta); println()
end
function h1(str)
dashes = "="^(length(str)+2)
printstyled(dashes, color=:magenta); println()
printstyled(" " * str * " ", bold=true, color=:magenta); println()
printstyled(dashes, color=:magenta); println()
end
function h2(str)
dashes = "-"^length(str)
printstyled(dashes, color=:magenta); println()
printstyled(str, bold=true, color=:magenta); println()
printstyled(dashes, color=:magenta); println()
end
h3(str) = (printstyled(str, bold=true, color=:magenta); println())
print_tf(::Test.Pass) = printstyled("+", bold=true, color=:green)
print_tf(::Test.Fail) = printstyled("-", bold=true, color=:red)
print_tf(::Tuple{Test.Error,Bool}) = printstyled("x", bold=true, color=:magenta)
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 3638 |
module Visualise
using PyCall, JSON
using JuLIP: set_pbc!, positions, neighbourlist
using JuLIP.ASE: AbstractAtoms, ASEAtoms, write, rnn, chemical_symbols
export draw
@pyimport IPython.display as ipydisp
@pyimport imolecule
"""
### KW-args (copied from imolecule)
* `size`: Starting dimensions of visualization, in pixels, e.g., `(500,500)`
* `drawing_type`: Specifies the molecular representation. Can be 'ball and
stick', "wireframe", or 'space filling'.
* `camera_type`: Can be 'perspective' or 'orthographic'.
* `shader`: Specifies shading algorithm to use. Can be 'toon', 'basic',
'phong', or 'lambert'.
* `display_html`: If True (default), embed the html in a IPython display.
If False, return the html as a string.
* `element_properties`: A dictionary providing color and radius information
for custom elements or overriding the defaults in imolecule.js
* `show_save`: If True, displays a save icon for rendering molecule as an
image.
## More kwargs:
* bonds: :babel, :auto
* cutoff: :auto or a number
"""
function draw(at::AbstractAtoms; bonds=:babel, box=:auto,
camera_type="perspective", size=(500,500), display_html=false,
cutoff=:auto,
kwargs...)
# TODO: implement box (ignore for now)
# TODO: check whether we are in a notebook or REPL
if bonds == :babel
# in this case we assume that OpenBabel and in particular `pybel` is
# installed; we write the atoms object as xyz and let `pybel`
# do the rest
fn = "$(tempname()).xyz"
write(fn, at)
out = ipydisp.HTML(
imolecule.draw( fn, format="xyz", camera_type=camera_type,
size=size, display_html=false, kwargs...) )
rm(fn)
return out
elseif bonds == :auto
# TODO: bonds = autobondlenghts(at)
elseif !isa(bonds, Dict)
error("""draw(at ...) : at the momement, `bonds` must be
`:babel`, `:auto` or a `Dict` containing the bonds-length
information""")
end
# we have a `Dict` that contains all the bond-length information
# (which we guessed really; this needs more work)
# we can therefore write a JSON file with atom positions + connectivity
# and let `imolecule` load that; this never needs to import `pybel` so it
# will work even if OpenBabel is not installed.
# TODO: bond-length guesses for multiple species
# TODO: bounding box especially with PBCs
# TODO: check which other information imolecule accepts
# temporarily assume there is a single species!
# and make the bond length 120% of the NN-length
if cutoff == :auto
bondlength = 1.2 * rnn( chemical_symbols(at)[1] )
else
bondlength = cutoff
end
# we need to turn of PBC otherwise we get weird bonds
set_pbc!(at, (false, false, false))
atoms = [Dict("element" => e, "location" => Vector(x))
for (e, x) in zip(chemical_symbols(at), positions(at)) ]
nlist = neighbourlist(at, bondlength)
# we are assuming that nlist is the Matscipy nlist
ij = unique(sort([nlist.i nlist.j], 2), 1) - 1
bondlist = [Dict("atoms" => [ij[n,1];ij[n,2]], "order" => 1)
for n = 1:Base.size(ij, 1)]
molecule_data = Dict("atoms" => atoms, "bonds" => bondlist)
# write to a temporary file
fn = "$(tempname()).json"
fio = open(fn, "w")
print(fio, JSON.json(molecule_data))
close(fio)
# plot
out = ipydisp.HTML(
imolecule.draw(fn, format="json", camera_type=camera_type,
size=size, display_html=false, kwargs...) )
rm(fn)
return out
end
end # module Visualise
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 14529 |
import LinearAlgebra: ldiv!, mul!
using LinearAlgebra: det, UniformScaling
import Base: length, getindex, setindex!, deleteat!
import NeighbourLists: cutoff
# function defined primarily on AbstractAtoms
export positions, get_positions, set_positions!,
momenta, get_momenta, set_momenta!,
masses, get_masses, set_masses,
cell, get_cell, set_cell!, is_cubic, cell_vecs,
pbc, get_pbc, set_pbc!,
set_data!, get_data, has_data,
set_calculator!, calculator, get_calculator,
neighbourlist, cutoff,
apply_defm!,
energy, potential_energy, forces, gradient, hessian,
site_energies,
site_energy, partial_energy,
site_energy_d, partial_energy_d,
stress, virial, site_virials,
position_dofs, set_position_dofs!,
momentum_dofs, set_momentum_dofs!,
dofs, set_dofs!,
preconditioner,
volume,
chemical_symbols,
atomic_numbers,
AbstractAtoms, AbstractCalculator
# temporary prototypes while rewriting
# todo: prototype and document these here
function chemical_symbols end
function atomic_numbers end
function site_energy_d end
function partial_energy_d end
# -----
# here we define and document the prototypes that are implemented
"""
`AbstractAtoms{T}`
the abstract supertype for storing atomistic configurations. A basic
implementation might simply store a list of positions, see e.g. `Atoms`.
Some Base functions that should be overloaded for atoms objects:
- length
- deleteat
- getindex
- setindex!
"""
abstract type AbstractAtoms{T} end
abstract type AbstractConstraint end
"""
`AbstractCalculator`: theabstractsupertype of calculators. These
store model information, and are linked to the implementation of energy,
forces, and so forth.
"""
abstract type AbstractCalculator end
"""
`Dofs{T}`: dof vector; simply an alias for `Vector{T}`
"""
const Dofs{T} = Vector{T}
"""
`positions(at)` : Return copy of positions of all atoms as a `Vector{JVec}`
"""
function positions end
"alias for `positions`"
get_positions = positions
"`set_positions!(at, X) -> at` : Set positions of all atoms"
function set_positions! end
set_positions!(at::AbstractAtoms, p::AbstractMatrix) = set_positions!(at, vecs(p))
set_positions!(at::AbstractAtoms, x, y, z) = set_positions!(at, [x'; y'; z'])
# this is already documented at its first definition in `arrayconversions`?
xyz(at::AbstractAtoms) = xyz(positions(at))
"`momenta(at)` : Return copy of momenta of all atoms as a `Vector{<:JVec}`."
function momenta end
"alias for `momenta`"
get_momenta = momenta
"`set_momenta!(at, P) -> at` : Set momenta of all atoms"
function set_momenta! end
set_momenta!(at::AbstractAtoms, p::AbstractMatrix) = set_momenta!(at, vecs(p))
"`masses` : return vector of all masses"
function masses end
"`get_masses` : alias for `masses`"
get_masses = masses
"`set_masses!(at, M) -> at` : set the atom masses"
function set_masses! end
"`cell(at) -> JMat` : get computational cell (the rows are the lattice vectors)"
function cell end
"alias for `cell`"
get_cell = cell
"`set_cell!(at, C) -> at` : set computational cell; cf. `?cell`"
function set_cell! end
"""
`cell_vecs(at) -> (SVec, SVec, SVec)` : return the three cell vectors
"""
function cell_vecs(at::AbstractAtoms)
C = cell(at)
@assert size(C) == (3,3)
return C[1,:], C[2,:], C[3,:]
end
"`volume(at)` : return volume of computational cell"
volume(at) = abs(det(cell(at)))
"""
`apply_defm!(at, F, t = zero(JVec)) -> at` : for a 3 x 3 matrix `F` and
`at::AbstractAtoms` the affine deformation `x -> Fx + t` is applied
to the configuration, modifying `at` inplace and returning it. This
modifies both the cell and the positions.
"""
function apply_defm!(at::AbstractAtoms{T}, F::AbstractMatrix,
t::AbstractVector = zero(JVec{T})) where {T}
@assert size(F) == (3,3)
@assert length(t) == 3
C = cell(at)
X = positions(at)
Cnew = C * F'
for n = 1:length(X)
# TODO: project back into the cell?
X[n] = F * X[n] + t
end
set_cell!(at, Cnew)
set_positions!(at, X)
return at
end
"`set_pbc!(at, p) -> at` : set periodic boundary conditions"
function set_pbc! end
set_pbc!(at::AbstractAtoms, p::Bool) = set_pbc!(at, (p,p,p))
"`pbc(at)` : get array or tuple determining which directions are periodic"
function pbc end
"`get_pbc(at)` : alias for `pbc`"
get_pbc = pbc
"""
`is_cubic(at) -> Bool` : determines whether a cubic cell is used
(i.e. cell is a diagonal matrix)
"""
is_cubic(a::AbstractAtoms) = isdiag(cell(a))
"""
`set_data!(at, name, value)`:
associate some data with `at`; to be stored in a Dict within `at`
if `name::Union{Symbol, AbstractString}`, then `setindex!` is an alias
for `set_data!`, i.e., we may write `at[:id] = val`
"""
function set_data! end
setindex!(at::AbstractAtoms, value,
name::Union{Symbol, AbstractString}) = set_data!(at, name, value)
"""
`get_data(at, name)`:
obtain some data stored with `set_data!`
if `name::Union{Symbol, AbstractString}`, then `getindex` is an alias
for `get_data`.
"""
function get_data end
getindex(at::AbstractAtoms,
name::Union{Symbol, AbstractString}) = get_data(at, name)
"`has_data(at, key)` : check whether some data with id `key` is already stored"
function has_data end
"alias for `deleteat!`"
delete_atom! = deleteat!
"`calculator(at)` : return an attached calculator"
function calculator end
"`set_calculator!(at, calc) -> at` : attach a calculator"
function set_calculator! end
"""
`neighbourlist(at, rcut)`
construct a suitable neighbourlist for this atoms object. `rcut` should
be allowed to be either a scalar or a vector.
"""
function neighbourlist end
"""
`static_neighbourlist(at::AbstractAtoms, cutoff; key = :staticnlist)`
This function first checks whether a static neighbourlist already exists
with cutoff `cutoff` and if it does then it returns the existing list.
If it does not, then it computes a new neighbour list with the current
configuration, stores it for later use and returns it.
"""
function static_neighbourlist(at::AbstractAtoms, cutoff; key=:staticnlist)
recompute = false
if has_data(at, key)
nlist = get_data(at, key)
if cutoff(nlist) != cutoff
recompute = true
end
else
recompute = true
end
if recompute
set_data!( at, key, neighbourlist(at, cutoff) )
end
return get_data(at, key)
end
static_neighbourlist(at::AbstractAtoms) = static_neighbourlist(at, cutoff(at))
#######################################################################
# CALCULATOR
#######################################################################
"""
`cutoff(calc)` : Returns the cut-off radius of the attached potential.
`cutoff(at)` : returns the cutoff of the attached calculator
"""
function cutoff end
cutoff(at::AbstractAtoms) = cutoff(calculator(at))
"""
`energy(calc, at)`: Return the total potential energy of a configuration of
atoms `at`, using the calculator `calc`. In addition, `energy` can be
called in the following ways:
* `energy(calc, at)`: base definition; this is normally the only method that
needs to be overloaded when a new calculator is implemented.
* `energy(at)`: if a calculator is attached to `at`
* `energy(calc, at, const, dof)`
* `energy(calc, at, dof)`
* `energy(at, dofs)`
"""
function energy end
potential_energy = energy
"""
`site_energy(calc, at, n)` : return site energy at atom idx `n`
"""
function site_energy end
site_energy(at::AbstractAtoms, n::Integer) = site_energy(calculator(at), at, n)
"""
`site_energies(calc, at)` : return vector of all site energies
"""
function site_energies end
site_energies(a::AbstractAtoms) = site_energies(calculator(a), a)
"""
`partial_energy(calc, at, subset)` : return energy contained in a `subset` of the
configuration
"""
function partial_energy end
partial_energy(at::AbstractAtoms, subset) =
partial_energy(calculator(at), at, subset)
"""
`forces(calc, at)` : forces as `Vector{<:JVec}` (negative gradient w.r.t. atom positions only)
"""
function forces end
forces(at::AbstractAtoms) = forces(calculator(at), at)
"""
`hessian_pos(calc, at):` block-hessian with respect to all atom positions
"""
function hessian_pos end
hessian_pos(at::AbstractAtoms) = hessian_pos(calculator(at), at)
"""
* `virial(c::AbstractCalculator, a::AbstractAtoms) -> JMat`
* `virial(a::AbstractAtoms) -> JMat`
returns virial, (- ∂E / ∂F) where `F = cell(a)'`
"""
function virial end
virial(at::AbstractAtoms) = virial(calculator(at), at)
"""
* `stress(c::AbstractCalculator, a::AbstractAtoms) -> JMatF`
* `stress(a::AbstractAtoms) -> JMatF`
stress = - virial / volume; this function should *not* be overloaded;
instead overload virial
"""
stress(calc::AbstractCalculator, at::AbstractAtoms) =
- virial(calc, at) / volume(at)
stress(at::AbstractAtoms) = stress(calculator(at), at)
#######################################################################
# Constraints and DoF Handling
#######################################################################
"""
`position_dofs(at::AbstractAtoms) -> Dofs`
`dofs(at::AbstractAtoms) -> Dofs`
Take an atoms object `at` and return a Dof-vector that fully describes the
state given the potential constraints placed on it.
"""
function position_dofs end
"""
`dofs` is an alias for `position_dofs`
"""
dofs = position_dofs
"""
* `set_position_dofs!(at::AbstractAtoms, cons::AbstractConstraint, x::Dofs) -> at`
* `set_position_dofs!(at::AbstractAtoms, x::Dofs) -> at`
* `set_dofs!(at::AbstractAtoms, cons::AbstractConstraint, x::Dofs) -> at`
* `set_dofs!(at::AbstractAtoms, cons::AbstractConstraint) -> at`
change configuration stored in `at` according to `cons` and `x`.
"""
function set_position_dofs! end
"""
`set_dofs!` is an alias for `set_position_dofs!`
"""
set_dofs! = set_position_dofs!
"""
`momentum_dofs(at::AbstractAtoms) -> Dofs`
Take an atoms object `at` and return a Dof-vector that fully describes the
momenta (given any constraints placed on `at`)
"""
function momentum_dofs end
"""
* `set_momentum_dofs!(at::AbstractAtoms, cons::AbstractConstraint, p::Dofs) -> at`
* `set_momentum_dofs!(at::AbstractAtoms, p::Dofs) -> at`
change configuration stored in `at` according to `cons` and `p`.
"""
function set_momentum_dofs! end
"""
* `project!(at::AbstractAtoms) -> at`
project the `at` onto the constraint manifold.
"""
function project! end
# converting calculator functionality
# The following lines define variants of the `energy` function, which
# get around the issue that energy may or may not include an external
# potential; the rule is as follows:
# - a new calculator must implement `energy(calc, at)`
# - a new constraint must implement `energy(calc, at, cons)`
# and at the end *must* use `energy(calc, at)` but may not call any
# other variants of `energy`.
"""
* `energy(at, x::Dofs) -> Float64`
`potential_energy`; with potentially added cell terms, e.g., if there is
applied stress or applied pressure.
"""
energy(at::AbstractAtoms, x::Dofs) =
energy(set_dofs!(at, x))
energy(calc::AbstractCalculator, at::AbstractAtoms, x::Dofs) =
energy(calc, set_dofs!(at, x))
energy(at::AbstractAtoms) =
energy(calculator(at), at)
"""
* `gradient(calc, at, cons::AbstractConstraint, c::Dofs) -> Dofs`
* `gradient(at) -> Dofs`
* `gradient(at, x::Dofs) -> Dofs`
gradient of `potential_energy` in dof-format;
depending on the constraint this could include e.g. a gradient w.r.t. cell
shape; normally only the form `gradient(calc, at, cons)` should be
overloaded by an `AbstractConstraints` object.
"""
function gradient end
gradient(at::AbstractAtoms, x::Dofs) =
gradient(set_dofs!(at, x))
gradient(calc::AbstractCalculator, at::AbstractAtoms, x::Dofs) =
gradient(calc, set_dofs!(at, x))
gradient(at::AbstractAtoms) =
gradient(calculator(at), at)
"""
`hessian`: compute hessian of total energy with respect to DOFs!
same as gradient, just returns the hessian; new constraints should only
overload `hessian(calc, at, cons)`
"""
function hessian end
hessian(at::AbstractAtoms, x::Dofs) =
hessian(set_dofs!(at, x))
hessian(calc::AbstractCalculator, at::AbstractAtoms, x::Dofs) =
hessian(calc, set_dofs!(at, x))
hessian(at::AbstractAtoms) =
hessian(calculator(at), at)
#######################################################################
# PRECONDITIONER
# we don't create an abstract type, but somewhere we should
# document that a preconditioner must implement the following
# operations:
# - update!(precond, at)
# - ldiv!(out, P, f)
# - mul!)(out, P, x)
#######################################################################
"""
`update!(precond, at)`
Update the preconditioner with the new geometry information.
"""
function update! end
update!(precond, at::AbstractAtoms, x::Dofs) =
update!(precond, set_dofs!(at, x))
# TODO: make a Julia PR? do this in-place
ldiv!(out::Dofs, P::UniformScaling, x::Dofs) =
copyto!(out, P \ x)
# mul! is already correctly defined -> no need to define it here.
update!(P::UniformScaling, at::AbstractAtoms) = P
"""
construct a preconditioner suitable for this atoms object
default is `I`
"""
preconditioner(at::AbstractAtoms) =
preconditioner(at, calculator(at)) # should be preconditioner(calc, at) ???
preconditioner(at::AbstractAtoms, calc::AbstractCalculator) = I
#######################################################################
## Experimental Prototypes for in-place versions
#######################################################################
"""
`alloc_temp(args...)` : allocate temporary arrays for the evaluation of
some calculator or potential; see developer docs for more information
"""
alloc_temp(args...) = nothing
"""
`alloc_temp_d(args...)` : allocate temporary arrays for the evaluation of
some calculator or potential; see developer docs for more information
"""
alloc_temp_d(args...) = nothing
alloc_temp_dd(args...) = nothing
"""
`energy!`: non-allocating version of `energy`
"""
energy!(calc::AbstractCalculator, at::AbstractAtoms, temp::Nothing) =
energy(calc, at)
"""
`energy!`: non-allocating version of `forces`
"""
forces!(F::AbstractVector{JVec{T}}, calc::AbstractCalculator,
at::AbstractAtoms{T}, temp::Nothing) where {T} =
copy!(F, forces(calc, at))
"""
`energy!`: non-allocating version of `virial`
"""
virial!(calc::AbstractCalculator, at::AbstractAtoms, temp::Nothing) =
virial(calc, at)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 3754 |
import ForwardDiff
using JuLIP: vecs, mat, JVec
export ADPotential
# Implementation of a ForwardDiff site potential
# ================================================
"""
`abstract FDPotential <: SitePotential`
To implement a site potential that uses ForwardDiff.jl for AD, create
a concrete type and overload `JuLIP.Potentials.ad_evaluate`.
Example
```julia
mutable struct P1 <: FDPotential
end
@pot P1
JuLIP.Potentials.ad_evaluate(pot::P1, R::Matrix{T}) where {T<:Real} =
sum( exp(-norm(R[:,i])) for i = 1:size(R,2) )
```
Notes:
* For an `FDPotential`, the argument to `ad_evaluate` will be
`R::Matrix` rather than `R::Vector{<:JVec}`; this is an unfortunate current limitation of
`ForwardDiff`. Hopefully it can be fixed.
* TODO: allow arguments `(r, R)` then use chain-rule to combine them.
"""
struct ADPotential{TV, T, FR} <: SitePotential
V::TV
rcut::T
gradfun::FR
end
@pot ADPotential
ADPotential(V, rcut) = ADPotential(V, rcut, ForwardDiff.gradient)
cutoff(V::ADPotential) = V.rcut
evaluate!(tmp, V::ADPotential, R::AbstractVector{<: JVec}) = V.V(R)
function evaluate_d!(dEs, tmp, V::ADPotential, R::AbstractVector{<: JVec})
dV = V.gradfun( S -> V.V(vecs(S)), collect(mat(R)[:]) ) |> vecs
copyto!(dEs, dV)
return dEs
end
####### Prototype AD Hessian Implementation
# using JuLIP, JuLIP.Potentials
# using JuLIP.Potentials: evaluate_d
# JJ = JuLIP
# JPP = JuLIP.Preconditioners
#
# function ad_grad(V::SitePotential, S)
# R = reshape(S, 3, length(S) ÷ 3) |> vecs
# r = [norm(u) for u in R]
# dV = evaluate_d(V, r, R)
# return mat(dV)[:]
# end
#
# ad_hess(V::SitePotential, S::Vector{Float64}) = ForwardDiff.jacobian( S_ -> ad_grad(V, S_), S )
#
# ad_hess(V, R::AbstractVector{JVecF}) = ad_hess(V, mat(R)[:])
#
# atind2lininds(i::Integer) = (i-1) * 3 + [1,2,3]
#
# localinds(j::Integer) = 3 * (j-1) + [1,2,3]
#
# function ad_hessian(V, at::AbstractAtoms)
# I = Int[]; J = Int[]; Z = Float64[]
# for (i0, neigs, r, R, _) in sites(at, cutoff(V))
# ii = atind2lininds(i0)
# jj = [atind2lininds(j_) for j_ in neigs]
# # compute positive version of hessian of V(R)
# hV = ad_hess(V, R)
#
# nneigs = length(neigs)
# for j1 = 1:nneigs, j2 = 1:nneigs
# LJ1, LJ2 = localinds(j1), localinds(j2) # local indices
# GJ1, GJ2 = jj[j1], jj[j2] # global indices
# H = view(hV, LJ1, LJ2)
# for a = 1:3, b = 1:3
# append!(I, [ GJ1[a], ii[a], GJ1[a], ii[a] ])
# append!(J, [ GJ2[b], GJ2[b], ii[b], ii[b] ])
# append!(Z, [ H[a,b], - H[a,b], -H[a,b], H[a,b] ])
# end
# end
# end
# N = 3*length(at)
# return sparse(I, J, Z, N, N)
# end
#
# ad_hessian(at::AbstractAtoms, x::Vector) =
# ad_hessian(calculator(at), set_dofs!(at, x))
#
# # ========= STUFF FOR FF Preconditioner =============
#
# """
# `ADP`: this computes a basic FF preconditioner by AD-ing the site
# energy derivatives. It is slow and most of the time not as effective as
# the hand-coded ones.
# """
# type ADP{VT <: SitePotential} <: SitePotential
# V::VT
# end
# cutoff(V::ADP) = cutoff(V.V)
#
# function _ad_grad(V::SitePotential, S)
# R = reshape(S, 3, length(S) ÷ 3) |> vecs
# r = [norm(u) for u in R]
# dV = evaluate_d(V, r, R)
# return mat(dV)[:]
# end
#
# _ad_hess(V::SitePotential, S) = ForwardDiff.jacobian( S_ -> _ad_grad(V, S_), S )
#
# function precon(Vad::ADP, r, R)
# V = Vad.V
# hV = _ad_hess(V, mat(R)[:])
# # positive factorisation
# hV = 0.5 * (hV + hV')
# L = cholfact(Positive, hV)[:L]
# H = L * L'
# return 0.9 * H + 0.1 * maximum(diag(H)) * eye(size(L,1))
# end
#
# hinds(j) = 3 * (j-1) + [1,2,3]
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 3676 |
"""
`EMT`: a re-implementation of the `EMT` calculator (a variant of EAM) os ASE
in Julia, largely for fun and comparison with Python, but also to demonstrate
how to implement a multi-component calculator in JuLIP
"""
struct AnalyticEAM <: MSitePotential
pair::Vector{WrappedPairPotential}
rho::Vector{WrappedPairPotential}
embed::Vector{WrappedAnalyticFunction}
z2ind::Dict{Int, Int}
end
cutoff(calc::AnalyticEAM) = min(cutoff(calc.pair), cutoff(calc.rho))
AnalyticEAM(N::Integer) =
AnalyticEAM( Vector{WrappedPairPotential}(undef, N),
Vector{WrappedPairPotential}(undef, N),
Vector{WrappedAnalyticFunction}(undef, N),
Dict{Int, Int}() )
function evaluate!(tmp, calc::AnalyticEAM, 𝐑, 𝐙, z0)
ρ̄ = 0.0
Es = 0.0
i0 = calc.z2ind[z0]
for (R, Z) in zip(𝐑, 𝐙)
i = calc.z2ind[Z]
r = norm(R)
Es += calc.pair[i](r)
ρ̄ += calc.rho[i](r)
end
Es += calc.embed[i0](ρ̄)
return Es
end
function evaluate_d!(dEs, tmp, calc::EMT, 𝐑, 𝐙, z0)
ρ̄ = 0.0
i0 = calc.z2ind[z0]
for (R, Z) in zip(𝐑, 𝐙)
i = calc.z2ind[Z]
r = norm(R)
ρ̄ += calc.rho[i](r)
end
dF = @D calc.embed[i0](ρ̄)
for (j, (R, Z)) in enumerate(zip(𝐑, 𝐙))
i = calc.z2ind[Z]
r = norm(R)
R̂ = R/r
dpair = @D calc.pair[i](r)
drho = @D calc.rho[i](r)
dEs[j] = (dpair + dF * drho) * R̂
end
return dEs
end
"embedding function for the Gupta potential"
mutable struct GuptaEmbed <: SimpleFunction
xi
end
evaluate(p::GuptaEmbed, r) = p.xi * sqrt(r)
evaluate_d(p::GuptaEmbed, r) = 0.5*p.xi ./ sqrt(r)
"""`GuptaPotential`:
E_i = A ∑_{j ≠ i} v(r_ij) - ξ ∑_i √ ρ_i
v(r_ij) = exp[ -p (r_ij/r0 - 1) ]
ρ_i = ∑_{j ≠ i} exp[ -2q (r_ij / r0 - 1) ]
"""
GuptaPotential(A, xi, p, q, r0, TC::Type, TCargs...) =
EAMPotential( TC( SimpleExponential(A, p, r0), TCargs... ), # V
TC( SimpleExponential(1.0, 2*q, r0), TCargs...), # rho
GuptaEmbed( xi ) ) # embed
gupta_parameters = Dict(
# a D α R₀ <<< Gupta notation
:Cu => (3.6147, 0.3446, 1.3921, 2.838),
:Ag => (4.0862, 0.3294, 1.3939, 3.096),
:Au => (4.0785, 0.4826, 1.6166, 3.004),
:Ni => (3.5238, 0.4279, 1.3917, 2.793)
)
function GuptaEAM()
end
# # data Johnson & Oh (1989)
#
# johnson_params = Dict(
# # species a (Å) Ec(eV) ΩB(eV) ΩG(eV) A
# :Li => (3.5087, 1.65, 1.63, 0.77, 8.52),
# :Na => (4.2906, 1.13, 1.63, 0.68, 7.16),
# :K => (5.344, 0.941, 1.58, 0.59, 6.71),
# :V => (3.0399, 5.30, 13.62, 4.17, 0.78),
# :Nb => (3.3008, 7.47, 19.08, 4.43, 0.52),
# :Ta => (3.3026, 8.089, 21.66, 7.91, 1.57),
# :Cr => (2.8845, 4.10, 11.77, 8.71, 0.71),
# :Mo => (3.150, 6.810, 25.68, 12.28, 0.78),
# :W => (3.16475, 8.66, 30.65, 15.84, 1.01),
# :Fe => (2.86645, 4.29, 12.26, 6.53, 2.48)
# )
#
# function JohnsonEAM(sym::Symbol)
# if !haskey(johnson_params, sym)
# error("""The Johnson & Oh EAM model does is not defined for $(sym);
# only the chemical symbols $(keys(johnson_params)) are
# available""" )
# end
# a, Ec, ΩB, ΩG, A = johnson_params[sym]
# c1 = - 15 * ΩG / (3*A + 2)
# K3 = c1 * (3/4*A - 0.5*S) # (6)
# K2 = c1 * (15/16*A - 3/4*S - 9/8*A*S + 7/8)
# K1 = - 15 * ΩG * (7/8 - 3/4*S)
# K0 =
# V =
# f = @analytic r ->
# F = @analytic ρ -> - (Ec-EUF) * (1 - log((ρ/ρe)^n)) * (ρ/ρe)^n
# end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2931 |
using MacroTools: @capture, prewalk
using Calculus: differentiate
using CommonSubexpressions
import FunctionWrappers
import FunctionWrappers: FunctionWrapper
export AnalyticFunction, @analytic
const ScalarFun{T} = FunctionWrapper{T, Tuple{T}}
"""
`F64fun`: `FunctionWrapper` to wrap many different potentials within a single
type. Can be used as `F64fun(::Function)` or as
`F64fun(::AnalyticFunction)`
"""
const F64fun = ScalarFun{Float64}
"""
take an expression of the form `r -> f(r)` and return the expression
`r -> f'(r)`
"""
function fdiff( ex, ndiff )
@assert 1 <= ndiff <= 2
@assert @capture(ex, var_ -> expr_)
d_ex = differentiate(expr.args[2], var)
if ndiff == 2
d_ex = differentiate(d_ex, var)
end
d_ex = CommonSubexpressions.cse(d_ex)
return :( $var -> $d_ex )
end
"""
auxiliary function to allow expression substitution from `@Analytic`;
see `?@Analytic` for more detail
"""
function substitute(args)
subs = Dict{Symbol,Union{Expr, Symbol}}()
for i = 2:length(args)
@assert @capture(args[i], var_ = sub_)
subs[var] = sub
end
prewalk(expr -> get(subs, expr, expr), args[1])
end
# ================== Analytical Potentials ==========================
abstract type SimplePairPotential <: PairPotential end
"""
`struct AnalyticFunction`: described an analytic function, allowing to
evaluate at least 2 derivatives.
Formally, `AnalyticFunction <: PairPotential`, which simplifies dispatch,
but it an `AnalyticFunction` should normally **not be used as a Calculator**!
This type hierarchy may need to be revisited.
### Usage:
```julia
lj = @analytic r -> r^(-12) - 2.0*r^(-6)
morse = let A = 4.0, r0 = 1.234
@analytic r -> exp(-2.0*A*(r/r0-1.0)) - 2.0*exp(-A*(r/r0-1.0))
end
To create a "wrapped" AnalyticFunction{F64fun, ...} , use
```
lj_wrapped = F64fun(lj)
```
if an formula for an analytic function contains a sub-expression that
occurs multiple time, then this can be constructed as follows:
```
V = @analytic( r -> exp(s) * s, s = r^2 )
# is the same as
V = @analytic r -> exp(r^2) * r^2
```
"""
struct AnalyticFunction{F0,F1,F2} <: SimplePairPotential
f::F0
f_d::F1
f_dd::F2
end
@pot AnalyticFunction
F64fun(p::AnalyticFunction) =
AnalyticFunction(F64fun(p.f), F64fun(p.f_d), F64fun(p.f_dd))
cutoff(V::AnalyticFunction) = Inf
const WrappedAnalyticFunction = AnalyticFunction{F64fun,F64fun,F64fun}
"""
`@analytic`: generate C2 function from symbol
"""
macro analytic(args...)
fexpr = substitute(args)
quote
AnalyticFunction(
$(Base.FastMath.make_fastmath(esc(fexpr))),
$(Base.FastMath.make_fastmath(esc(fdiff(fexpr, 1)))),
$(Base.FastMath.make_fastmath(esc(fdiff(fexpr, 2))))
)
end
end
evaluate!(tmp, p::SimplePairPotential, r::Number) = p.f(r)
evaluate_d!(tmp, p::SimplePairPotential, r::Number) = p.f_d(r)
evaluate_dd!(tmp, p::SimplePairPotential, r::Number) = p.f_dd(r)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2698 |
using StaticArrays
using Base: ReinterpretArray, ReshapedArray
using LinearAlgebra: norm
import Base.convert
export mat, vecs, xyz
export SVec, SMat, JVec, JVecF, JMat, JMatF
export maxdist, maxnorm
"typealias fora static vector type; currently `StaticArrays.SVector`"
const SVec = SVector
"typealias fora static matrix type; currently `StaticArrays.SMatrix`"
const SMat = SMatrix
"`JVec{T}` : 3-dimensional immutable vector"
const JVec{T} = SVec{3,T}
const JVecF = JVec{Float64}
const JVecI = JVec{Int}
"`JMat{T}` : 3 × 3 immutable matrix"
const JMat{T} = SMatrix{3,3,T,9}
const JMatF = SMatrix{3,3,Float64,9}
const JMatI = JMat{Int}
#
"""
`vecs(V)` : convert (as reference) a `3 x N` matrix or `3*N` vector representing
N vectors (e.g. positions or forces) in R³ to a vector of `JVec` vectors.
If `V` is obtained from a call to `mat(X)` where `X::Vector{JVec{T}}` then
`vecs(V) === X`.
"""
vecs(V::AbstractMatrix{T}) where {T} = (@assert size(V,1) == 3;
reinterpret(JVec{T}, vec(V)))
vecs(V::AbstractVector{T}) where {T} = reinterpret(JVec{T}, V)
vecs(M::ReshapedArray{T,2,ReinterpretArray{T,1,JVec{T},Array{JVec{T},1}},Tuple{}}
) where {T} = M.parent.parent
"""
`mat(X)`: convert (as reference) a vector of
`SVec` to a 3 x N matrix representing those.
### Usage:
```
X = positions(at) # returns a Vector{<: JVec}
M = positions(at) |> mat # returns an AbstractMatrix
X === vecs(M)
```
"""
mat(V::AbstractVector{SVec{N,T}}) where {N,T} =
reshape( reinterpret(T, V), (N, length(V)) )
# mat(X::Base.ReinterpretArray) = reshape(X.parent, 3, :)
"""
convert a Vector{JVec{T}} or a 3 x N Matrix{T} into a 3-tuple
(x, y, z). E.g.,
```
x, y, z = positions(at) |> xyz
```
a short-cut is
```
x, y, z = xyz(at)
```
Conversely, `set_positions!(at, x, y, z)` is also allowed.
"""
function xyz(V::AbstractMatrix)
@assert size(V, 1) == 3
return (view(V, 1, :), view(V, 2, :), view(V, 3, :))
end
xyz(V::AbstractVector{JVec{T}}) where {T} = xyz(mat(V))
"""
`maxdist(A, B): ` maximum of distances between two ordered sets of objects,
typically positions. `maximum(norm(a - b) for (a,b) in zip(A,B))`
"""
function maxdist(x::AbstractArray, y::AbstractArray)
@assert length(x) == length(y)
return maximum( norm(a-b) for (a,b) in zip(x,y) )
end
"""
`maxdist(X, y): ` maximum of distance of `y` to all items of `X`;
`maximum( norm(x - y) for x in X)`
"""
maxdist(X::AbstractArray{T}, y::T) where {T} = maximum(norm(x - y) for x in X)
maxdist(x::T, X::AbstractArray{T}) where {T} = maxdist(X, x)
"`maximum(norm(y) for y in x);` typically, x is a vector of forces"
maxnorm(X::AbstractVector) = maximum( norm(x) for x in X )
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 7987 |
import Base.Dict
export Atoms
"""
`JData`: datatype for storing any data
some data which needs to be updated if the configuration (positions only!) has
changed too much.
"""
mutable struct JData{T}
max_change::T # how much X may change before recomputing
accum_change::T # how much has it changed already
data::Any
end
struct LinearConstraint{T}
C::Matrix{T}
b::Vector{T}
desc::String # description of the constraint
end
mutable struct DofManager{T}
variablecell::Bool
xfree::Vector{Int}
lincons::Vector{LinearConstraint{T}}
# ----
X0::Vector{JVec{T}}
F0::JMat{T}
end
"""
`Atoms{T <: AbstractFloat} <: AbstractAtoms`
The main type storing information about atomic configurations. This is
not normally constructed directly by calling `Atoms`, but using one of the
utility functions such as `bulk`.
## Constructors
TODO
## Convenience functions
* `bulk`
# Getters and Setters
* `positions`, `set_positions!`
* `momenta`, `set_momenta!`
* `masses`, `set_masses!`
* `numbers`, `set_numbers!`
* `cell`, `set_cell!`
* `pbc`, `set_pbc!`
* `calculator`, `set_calculator!`
* `get_data`, `set_data!`
"""
mutable struct Atoms{T <: AbstractFloat} <: AbstractAtoms{T}
X::Vector{JVec{T}} # positions
P::Vector{JVec{T}} # momenta (or velocities?)
M::Vector{T} # masses
Z::Vector{Int16} # atomic numbers
cell::JMat{T} # cell
pbc::JVec{Bool} # boundary condition
calc::Union{Nothing, AbstractCalculator}
dofmgr::DofManager
data::Dict{Any,JData{T}}
end
Atoms(X::Vector{JVec{T}}, P::Vector{JVec{T}}, M::Vector{T},
Z::Vector{Int16}, cell::JMat{T}, pbc::JVec{Bool},
calc::Union{Nothing, AbstractCalculator} = nothing) where {T} =
Atoms(X, P, M, Z, cell, pbc, calc,
DofManager(length(X), T), Dict{Any,JData{T}}())
Base.eltype(::Atoms{T}) where {T} = T
# derived properties
length(at::Atoms) = length(at.X)
getindex(at::Atoms, i::Integer) = at.X[i]
function setindex!(at::Atoms{T}, val, i::Integer) where {T}
u = norm(at.X[i] - val)
at.X[i] = convert(JVec{T}, val)
update_data!(at, u)
return val
end
# ------------------------ access to struct fields ----------------------
# ----- getters
positions(at::Atoms) = copy(at.X)
momenta(at::Atoms) = copy(at.P)
masses(at::Atoms) = copy(at.M)
numbers(at::Atoms) = copy(at.Z)
atomic_numbers(at::Atoms) = copy(at.Z)
cell(at::Atoms) = at.cell
pbc(at::Atoms) = at.pbc
calculator(at::Atoms) = at.calc
chemical_symbols(at::Atoms) = Chemistry.chemical_symbol.(at.Z)
# ----- setters
function set_positions!(at::Atoms{T}, X::AbstractVector{JVec{T}}) where T
update_data!(at, dist(at, X))
at.X .= X
return at
end
function set_momenta!(at::Atoms{T}, P::AbstractVector{JVec{T}}) where T
at.P .= P
return at
end
function set_masses!(at::Atoms{T}, M::AbstractVector{T}) where T
update_data!(at, Inf)
at.M .= M
return at
end
function set_numbers!(at::Atoms, Z::AbstractVector{<:Integer})
update_data!(at, Inf)
at.Z .= Z
return at
end
function set_cell!(at::Atoms{T}, C::AbstractMatrix) where T
update_data!(at, Inf)
at.cell = JMat{T}(C)
return at
end
function set_pbc!(at::Atoms, p::Union{AbstractVector, Tuple})
q = JVec{Bool}(p...)
if at.pbc != q
update_data!(at, Inf)
at.pbc = q
end
return at
end
function set_calculator!(at::Atoms, calc::Union{AbstractCalculator, Nothing})
at.calc = calc
return at
end
# --------------- equality tests -------------------
import Base.==
==(at1::Atoms{T}, at2::Atoms{T}) where T = (
isapprox(at1, at2, tol = 0.0) &&
(at1.data == at2.data) &&
(at1.calc == at2.calc) &&
(at1.dofmgr == at2.dofmgr) )
import Base.isapprox
function isapprox(at1::Atoms{T}, at2::Atoms{T}; tol = sqrt(eps(T))) where {T}
if length(at1) != length(at2)
return false
end
if tol > 0
ndigits = floor(Int, abs(log10(tol)))
X1 = [round.(x, ndigits) for x in at1.X]
X2 = [round.(x, ndigits) for x in at2.X]
else
X1, X2 = at1.X, at2.X
end
p1 = sortperm(X1)
p2 = sortperm(X2)
return (maxdist(at1.X[p1], at2.X[p2]) <= tol) &&
(maxdist(at1.P[p1], at2.P[p2]) <= tol) &&
(norm(at1.M[p1] - at2.M[p2], Inf) <= tol) &&
(at1.Z[p1] == at2.Z[p2]) &&
(norm(at1.cell - at2.cell, Inf) <= tol) &&
(at1.pbc == at2.pbc)
end
# --------------- some aliases for easier / direct access --------------
# and some access not covered above
function neighbourlist(at::Atoms{T}, rcut::AbstractFloat;
recompute=false, key="nlist:default",
int_type = Int32, kwargs...) where {T}
# we are allowed to use a stored list
if !recompute
if has_data(at, key)
nlist = get_data(at, key)::PairList{T, int_type}
if cutoff(nlist) >= rcut
return nlist
end
end
end
# we are either forces to recompute, or no nlist exists or is not
# suitable for the request.
nlist = PairList(positions(at), rcut, cell(at), pbc(at);
int_type=int_type, kwargs...)::PairList{T, int_type}
set_data!(at, key, nlist, 0.0)
return nlist
end
# function neighbourlist(at::Atoms{T}, rcut::AbstractFloat;
# recompute=false, key="nlist:default", kwargs...) where {T}
# return PairList(positions(at), rcut, cell(at), pbc(at); kwargs...)
# end
neighbourlist(at::Atoms) = neighbourlist(at, cutoff(at))
# --------------- data Dict handling ------------------
"""
`has_data(at::Atoms, key)`: checks whether `at` is storing a datum with key `key`; see also `set_data!`
"""
has_data(at::Atoms, key) = haskey(at.data, key)
"""
`get_data(at::Atoms, key)`: retrieves a datum;
see also `set_data!`. Unlike `get_positions`, etc, this returns the original
datum, not a copy (unless it is immutable).
"""
get_data(at::Atoms, key) = (at.data[key]).data
"""
`set_data!(a::Atoms, key, value, max_change=Inf)`:
Stores `value` under an arbitrary key `key` inside `at`. The entry is paired
with an updatemeasure `chg`. Whenever atom positions or the cell change by a
distance `d`, the counter is incremented `chg += d`. When `chg > max_change`,
the entry is deleted from the dictionary.
The two most common uses are with `max_change = Inf` (default) - in this case
the entry will never be deleted; and `max_change = 0.0` - in this case the entry
will be deleted whenever atom positions or the cell change.
The change counter is used, e.g., for neighbourlists with buffer, and for
preconditioners so that the list need not be recomputed each time the
configuration changes.
"""
function set_data!(at::Atoms, key, value, max_change=Inf)
at.data[key] = JData(max_change, 0.0, value)
return at
end
"""
`function set_transient!(a::Atoms, key, value, max_change=0.0)`: this is an
alias for `set_data!` but with default `max_change = 0.0` instead of `max_change =
Inf`.
"""
set_transient!(at::Atoms, key, value, max_change=0.0) =
set_data!(at, key, value, max_change)
"""
`update_data!(at::Atoms, r::Real)`:
increment the change counter in all stored data and delete the
expired ones.
"""
function update_data!(at::Atoms, r::Real)
for (key, t) in at.data
t.accum_change += r
if t.accum_change >= t.max_change
delete!(at.data, key)
end
end
return at
end
# ------------------------ FIO ----------------------
Dict(at::Atoms) =
Dict( "__id__" => "JuLIP_Atoms",
"X" => at.X,
"P" => at.P,
"M" => at.M,
"Z" => at.Z,
"cell" => at.cell,
"pbc" => at.pbc,
"calc" => nothing,
"data" => nothing )
Atoms(D::Dict) = Atoms(D["X"], D["P"], D["M"], D["Z"], D["cell"], D["pbc"])
# calc = D["calc"],
# cons = D["cons"],
# data = D["data"] )
Base.convert(::Val{:JuLIP_Atoms}, D) = Atoms(D)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 1048 |
# field symbol name is array
fields = [ (:X, "positions", true),
(:P, "momenta", true),
(:M, "masses", true),
(:Z, "numbers", true),
(:cell, "cell", false),
(:calc, "calculator", false),
(:cons, "constraint", false),
(:pbc, "pbc", false),
]
for (S, name, isarray) in fields
set_name = Meta.parse("set_$(name)!")
get_name = Meta.parse("$name")
if isarray
@eval begin
function $(get_name)(at::Atoms)
return copy(at.$S)
end
function $(set_name)(at::Atoms, Q)
if length(at.$S) != length(Q)
at.$S = copy(Q)
else
at.$S .= Q
end
return at
end
end
else
function $(get_name)(at::Atoms)
return at.$S
end
function $(set_name)(at::Atoms, Q)
at.$S = Q
return at
end
end
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 10113 |
"""
`module Build` : this is a very poor man's version of `ase.build`. At the moment
only a subset of the `bulk` functionality is supported.
"""
module Build
import JuLIP
using ..Chemistry
using JuLIP: JVec, JMat, JVecF, JMatF, mat,
Atoms, cell, cell_vecs, positions, momenta, masses, numbers, pbc,
chemical_symbols, set_cell!, set_pbc!, update_data!,
apply_defm!
using LinearAlgebra: I, Diagonal, isdiag, norm
import Base: union
import JuLIP: Atoms
export repeat, bulk, cluster, autocell!, append
_auto_pbc(pbc::Tuple{Bool, Bool, Bool}) = JVec(pbc...)
_auto_pbc(pbc::Bool) = JVec(pbc, pbc, pbc)
_auto_pbc(pbc::AbstractVector) = JVec(pbc...)
_auto_cell(cell) = cell
_auto_cell(cell::AbstractMatrix) = JMat(cell)
_auto_cell(C::AbstractVector{T}) where {T <: Real} = (
length(C) == 3 ? JMatF(C[1], 0.0, 0.0, 0.0, C[2], 0.0, 0.0, 0.0, C[3]) :
JMatF(C...) ) # (case 2 requires that length(C) == 0
_auto_cell(C::AbstractVector{T}) where {T <: AbstractVector} = JMatF([ C[1] C[2] C[3] ])
_auto_cell(C::AbstractVector) = _auto_cell([ c for c in C ])
"""
`autocell!(at::Atoms) -> Atoms`
generates cell vectors that contain all atom positions + a small buffer,
sets the cell of `at` accordingly (in-place) and returns the same atoms objet
with the new cell.
"""
autocell!(at::Atoms) = set_cell!(at, _autocell(positions(at)))
function _autocell(X::Vector{JVec{T}}) where T
ext = extrema(mat(X), dims = (2,))
C = Diagonal([ e[2] - e[1] + 1.0 for e in ext ][:])
return JMat{T}(C)
end
# if we have no clue about X just return it and see what happens
_auto_X(X) = X
# if the elements of X weren't inferred, try to infer before reading
# TODO: this might lead to a stack overflow!!
_auto_X(X::AbstractVector) = _auto_X( [x for x in X] )
# the cases where we know what to do ...
_auto_X(X::AbstractVector{T}) where {T <: AbstractVector} = [ JVecF(x) for x in X ]
_auto_X(X::AbstractVector{T}) where {T <: Real} = _auto_X(reshape(X, 3, :))
_auto_X(X::AbstractMatrix) = (@assert size(X)[1] == 3;
[ JVecF(X[:,n]) for n = 1:size(X,2) ])
_auto_M(M::AbstractVector{T}) where {T <: AbstractFloat} = Vector{T}(M)
_auto_M(M::AbstractVector) = Vector{Float64}(M)
_auto_Z(Z::AbstractVector) = Vector{Int16}(Z)
Atoms(; kwargs...) = Atoms{Float64}(; kwargs...)
Atoms{T}(; X = JVec{T}[],
P = JVec{T}[],
M = T[],
Z = Int16[],
cell = zero(JMat{T}),
pbc = JVec(false, false, false),
calc = nothing ) where {T} =
Atoms(X, P, M, Z, cell, pbc, calc)
Atoms(X, P, M, Z, cell, pbc, calc=nothing) =
Atoms(_auto_X(X), _auto_X(P), _auto_M(M), _auto_Z(Z),
_auto_cell(cell), _auto_pbc(pbc), calc)
Atoms(Z::Vector{Int16}, X::Vector{JVec{T}}; kwargs...) where {T} =
Atoms{T}(; Z=Z, X=X, kwargs...)
"""
simple way to construct an atoms object from just positions
"""
Atoms(s::Symbol, X::Vector{JVec{T}}; kwargs...) where {T} =
Atoms{T}(; X = X,
M = fill(one(T), length(X)),
P = zeros(JVec{T}, length(X)),
Z = fill(atomic_number(s), length(X)),
cell = _autocell(X),
pbc = (false, false, false), kwargs... )
Atoms(s::Symbol, X::Matrix{Float64}) = Atoms(s, vecs(X))
const _unit_cells = Dict( # (positions, cell matrix, factor of a)
:fcc => ( [ [0 0 0], ],
[0 1 1; 1 0 1; 1 1 0], 0.5),
:bcc => ( [ [0.0,0.0,0.0], ],
[-1 1 1; 1 -1 1; 1 1 -1], 0.5),
:diamond => ( [ [0.0, 0.0, 0.0], [0.5, 0.5, 0.5] ],
[0 1 1; 1 0 1; 1 1 0], 0.5)
)
const _cubic_cells = Dict( # (positions, factor of a)
:fcc => ( [ [0 0 0], [0 1 1], [1 0 1], [1 1 0] ], 0.5 ),
:bcc => ( [ [0 0 0], [1 1 1] ], 0.5 ),
:diamond => ( [ [0 0 0], [1 1 1], [0 2 2], [1 3 3], [2 0 2],
[3 1 3], [2 2 0], [3 3 1] ], 0.25 )
)
_simple_structures = [:fcc, :bcc, :diamond]
function _simple_bulk(sym::Symbol, cubic::Bool)
if cubic
X, scal = _cubic_cells[symmetry(sym)]
C = Matrix(1.0I, 3, 3) / scal
else
X, C, scal = _unit_cells[symmetry(sym)]
end
a = lattice_constant(sym)
return [ JVecF(x) * a * scal for x in X ], JMatF(C * a * scal)
end
function _bulk_hcp(sym::Symbol)
D = Chemistry.refstate(sym)
a = D["a"]
c = a * D["c/a"]
return [JVecF(0.0, 0.0, 0.0), JVecF(0.0, a / sqrt(3), c / 2)],
JMatF( [a, -a / 2, 0.0, 0.0, a * sqrt(3)/2, 0.0, 0.0, 0.0, c] )
end
_convert_pbc(pbc::NTuple{3, Bool}) = pbc
_convert_pbc(pbc::Bool) = (pbc, pbc, pbc)
function bulk(sym::Symbol; T=Float64, cubic = false, pbc = (true,true,true))
symm = symmetry(sym)
if symm in _simple_structures
X, C = _simple_bulk(sym, cubic)
elseif symm == :hcp
X, C = _bulk_hcp(sym) # cubic parameter is irrelevant for hcp
end
m = atomic_mass(sym)
z = atomic_number(sym)
nat = length(X)
return Atoms( convert(Vector{JVec{T}}, X),
fill(zero(JVec{T}), nat),
fill(T(m), nat),
fill(UInt16(z), nat),
convert(JMat{T}, C),
_convert_pbc(pbc) )
end
"""
auxiliary function to convert a general cell to a cubic one; this is a bit of
a hack, so to not make a mess of things, this will only work in very restrictive
circumstances and otherwise throw an error. But it could be revisited.
"""
function _cubic_cell(atu::Atoms{T}) where {T}
@assert length(atu) == 1
ru = JuLIP.rmin(atu)
at = bulk(chemical_symbol(atu.Z[1]), cubic=true)
r = JuLIP.rmin(at)
return apply_defm!(at, (ru/r) * one(JMat{T}))
end
"""
`cluster(args...; kwargs...) -> at::AbstractAtoms`
Produce a cluster of approximately radius R. The center
atom is always at index 1.
## Methods
```
cluster(atu::AbstractAtoms, R::Real) # specify unit cell
cluster(sym::Symbol, R::Real) # atu = bulk(sym; cubic=true)
```
Both methods assume that there is only a single species, and both require
the use of an orthorhombic unit cell (for now).
* `sym`: chemical symbol of the atomic species
* `R` : length-scale, meaning depends on shape of the cluster
## Keyword Arguments:
* `dims` : dimension into which the cluster is extended, typically
`(1,2,3)` for 3D point defects and `(1,2)` for 2D dislocations, in the
remaining dimension(s) the b.c. will be periodic.
* `shape` : shape of the cluster, at the moment only `:ball` is allowed
## todo
* lift the restriction of single species
* allow other shapes
"""
function cluster(atu::Atoms{T}, R::Real;
dims = [1,2,3], shape = :ball, x0=nothing) where {T}
sym = chemical_symbols(atu)[1]
# check that the cell is orthorombic
if !isdiag(cell(atu))
if length(atu) > 1
error("""`JuLIP.cluster` requires as argument either a cubic cell or a
one-atom cell.""")
end
atu = _cubic_cell(atu)
end
# # check that the first index is the centre
# @assert norm(atu[1]) == 0.0
# determine by how much to multiply in each direction
Fu = cell(atu)'
L = [ j ∈ dims ? 2 * (ceil(Int, R/Fu[j,j])+3) : 1 for j = 1:3]
# multiply
at = atu * L
# find point closest to centre
x̄ = sum( x[dims] for x in at.X ) / length(at.X)
i0 = findmin( [norm(x[dims] - x̄) for x in at.X] )[2]
if x0 == nothing
x0 = at[i0]
else
x0 += at[i0]
end
# swap positions
X = positions(at)
X[1], X[i0] = X[i0], X[1]
F = Diagonal([Fu[j,j]*L[j] for j = 1:3])
# carve out a cluster with mini-buffer to account for round-off
r = [ norm(x[dims] - x0[dims]) for x in X ]
IR = findall( r .<= R+sqrt(eps(T)) )
# generate new positions
Xcluster = X[IR]
# generate the cluster
at_cluster = Atoms(sym, Xcluster)
set_cell!(at_cluster, F')
# take open boundary in all directions specified in dims, periodic in the rest
set_pbc!(at_cluster, [ !(j ∈ dims) for j = 1:3 ])
# return the cluster and the index of the center atom
return at_cluster
end
cluster(sym::Symbol, R::Real; kwargs...) =
cluster( bulk(sym, cubic=true), R; kwargs... )
"""
```
repeat(at::Atoms, n::NTuple{3}) -> Atoms
repeat(at::Atoms, n::Integer) = repeat(at, (n,n,n))
```
Takes an `Atoms` configuration / cell and repeats it n_j times
into the j-th cell-vector direction. For example,
```
at = repeat(bulk("C"), (3,2,4))
```
creates 3 x 2 x 4 unit cells of carbon.
The same can be achieved by `*`:
```
at = bulk("C") * (3, 2, 4)
```
"""
function Base.repeat(at::Atoms, n::NTuple{3})
C0 = cell(at)
c1, c2, c3 = cell_vecs(at)
X0, P0, M0, Z0 = positions(at), momenta(at), masses(at), numbers(at)
nrep = n[1] * n[2] * n[3]
nat0 = length(at)
X = Base.repeat(X0, outer=nrep)
P = Base.repeat(P0, outer=nrep)
M = Base.repeat(M0, outer=nrep)
Z = Base.repeat(Z0, outer=nrep)
i = 0
for a in CartesianIndices( (1:n[1], 1:n[2], 1:n[3]) )
b = c1 * (a[1]-1) + c2 * (a[2]-1) + c3 * (a[3]-1)
X[i+1:i+nat0] = [b+x for x in X0]
i += nat0
end
return Atoms(X, P, M, Z, Diagonal(collect(n)) * cell(at), pbc(at))
end
Base.repeat(at::Atoms, n::Integer) = repeat(at, (n,n,n))
Base.repeat(at::Atoms, n::AbstractArray) = repeat(at, (n...,))
import Base.*
*(at::Atoms, n) = repeat(at, n)
*(n, at::Atoms) = repeat(at, n)
"""
`deleteat!(at::Atoms, n) -> at`:
returns the same atoms object `at`, but with the atom(s) specified by `n`
removed.
"""
function Base.deleteat!(at::Atoms, n)
deleteat!(at.X, n)
deleteat!(at.P, n)
deleteat!(at.M, n)
deleteat!(at.Z, n)
update_data!(at, Inf)
return at
end
union(at1::Atoms, at2::Atoms) =
Atoms( X = union(at1.X, at2.X),
P = union(at1.P, at2.P),
M = union(at1.M, at2.M),
Z = union(at1.Z, at2.Z),
cell = cell(at1),
pbc = pbc(at1) )
append(at::Atoms, X::AbstractVector{<:JVec}) =
Atoms( X = union(at.X, X),
P = union(at.P, zeros(JVecF, length(X))),
M = union(at.M, zeros(length(X))),
Z = union(at.Z, zeros(Int, length(X))),
cell = cell(at),
pbc = pbc(at) )
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 1392 |
module Chemistry
using JuLIP.FIO: load_dict
export atomic_number,
chemical_symbol,
atomic_mass,
symmetry,
lattice_constant,
rnn
data = load_dict(@__DIR__()[1:end-3] * "data/asedata.json")
const _rnn = [Float64(d) for d in data["rnn"]]
const _symbols = [Symbol(s) for s in data["symbols"]]
const _masses = [Float64(m) for m in data["masses"]]
const _refstates = Dict{String, Any}[ d == nothing ? Dict{String, Any}() : d
for d in data["refstates"]]
const _numbers = Dict{Symbol, Int16}()
for (n, sym) in enumerate(_symbols)
_numbers[sym] = Int16(n - 1)
end
atomic_number(sym::Symbol) = _numbers[sym]
chemical_symbol(z::Integer) = _symbols[z+1]
atomic_mass(z::Integer) = _masses[z+1]
atomic_mass(sym::Symbol) = atomic_mass(atomic_number(sym))
element_name(z::Integer) = _names[z+1]
element_name(sym::Symbol) = element_name(atomic_number(sym))
rnn(z::Integer) = _rnn[z+1] # >>> TODO: move to utils ?? bulk as well??
rnn(sym::Symbol) = rnn(atomic_number(sym))
symmetry(z::Integer) = Symbol(_refstates[z+1]["symmetry"])
symmetry(sym::Symbol) = symmetry(atomic_number(sym))
lattice_constant(z::Integer) = Float64( _refstates[z+1]["a"] )
lattice_constant(sym::Symbol) = lattice_constant(atomic_number(sym))
refstate(z::Integer) = _refstates[z+1]
refstate(sym::Symbol) = refstate(atomic_number(sym))
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 6292 |
import Base.*
export SWCutoff, SplineCutoff, Shift, HS, C0Shift, C1Shift, C2Shift
# this file is include from Potentials.jl
# i.e. it is part of JuLIP.Potentials
# it implements three types of cutoff potentials.
######################## Stillinger-Weber type cutoff
"""
`cutsw(r, Rc, Lc)`
Implementation of the C^∞ Stillinger-Weber type cut-off potential
1.0 / ( 1.0 + exp( lc / (Rc-r) ) )
`d_cutinf` implements the first derivative
"""
@inline cutsw(r::T, Rc, Lc) where {T} =
T(1) / ( T(1) + exp( Lc / ( max(Rc-r, T(0)) + T(1e-2) ) ) )
"derivative of `cutsw`"
@inline function cutsw_d(r::T, Rc, Lc) where {T}
t = T(1) / ( max(Rc-r, T(0)) + T(1e-2) ) # a numerically stable (Rc-r)^{-1}
e = T(1) / (T(1) + exp(Lc * t)) # compute exponential only once
return - Lc * (T(1) - e) * e * t^2
end
"""
`type SWCutoff`: SW type cut-off potential with C^∞ regularity
1.0 / ( 1.0 + exp( Lc / (Rc-r) ) )
This is not very optimised: one could speed up `evaluate_d` significantly
by avoiding multiple evaluations.
### Parameters
* `Rc` : cut-off radius
* `Lc` : scale
"""
struct SWCutoff{T} <: PairPotential
Rc::T
Lc::T
e0::T
end
@pot SWCutoff
evaluate(p::SWCutoff, r::Number) = p.e0 * cutsw(r, p.Rc, p.Lc)
evaluate_d(p::SWCutoff, r::Number) = p.e0 * cutsw_d(r, p.Rc, p.Lc)
cutoff(p::SWCutoff) = p.Rc
# simplified constructor to ensure compatibility
SWCutoff(Rc, Lc) = SWCutoff(Rc, Lc, one(typeof(Rc)))
# kw-constructor (original SW parameters, pair term)
SWCutoff(; Rc=1.8, Lc=1.0, e0=1.0) = SWCutoff(Rc, Lc, e0)
######################## Shift-Cutoff:
"""
`Shift{ORD}` : a shift-cutoff function
It is not technically a cut-off function but a cut-off operator. Let
`f(r)` with real arguments and range, then
```
g = f * Shift(o, rcut)
```
creates a new function `g(r) = (f(r) - p(r)) * (r < rcut)` where
`p(r)` is a polynomial of order `o` such that all derivatives of `g` up
to order `o` vanish at `r = rcut`. There order must be an integer
between -1 and 2. Choosing `o=-1` creates a Heaviside function.
### Equivalent constructors:
```
HS(r::Float64) = Shift(-1, r)
C0Shift(r::Float64) = Shift(0, r)
C1Shift(r::Float64) = Shift(1, r)
C2Shift(r::Float64) = Shift(2, r)
```
### Example:
```
lj = LennardJones() # standard lennad-jones potential
V = lj * C2Shift(2.5)
```
Now `V` is a C2-continuous `PairPotential` with support (0, 2.5]."""
struct Shift{ORD, TV, T} <: PairPotential
ord::Val{ORD}
V::TV
rcut::T
Vcut::T
dVcut::T
ddVcut::T
end
@pot Shift
const HS{TV} = Shift{-1, TV}
const C0Shift{TV} = Shift{0, TV}
const C1Shift{TV} = Shift{1, TV}
const C2Shift{TV} = Shift{2, TV}
cutoff(p::Shift) = p.rcut
# the basic constructors
"see documentation for `Shift`"
HS(r::AbstractFloat) = Shift(-1, r)
"see documentation for `Shift`"
C0Shift(r::AbstractFloat) = Shift(0, r)
"see documentation for `Shift`"
C1Shift(r::AbstractFloat) = Shift(1, r)
"see documentation for `Shift`"
C2Shift(r::AbstractFloat) = Shift(2, r)
Shift(o::Int, r::AbstractFloat) = Shift(Val(o), nothing, r, 0.0, 0.0, 0.0)
Shift(V, p::Shift{-1}) = Shift(p.ord, V, p.rcut, 0.0, 0.0, 0.0)
Shift(V, p::Shift{0}) = Shift(p.ord, V, p.rcut, V(p.rcut), 0.0, 0.0)
Shift(V, p::Shift{1}) = Shift(p.ord, V, p.rcut, V(p.rcut), (@D V(p.rcut)), 0.0)
Shift(V, p::Shift{2}) = Shift(p.ord, V, p.rcut, V(p.rcut), (@D V(p.rcut)), (@DD V(p.rcut)))
*(V::PairPotential, p::Shift{ORD, Nothing}) where {ORD} = Shift(V, p)
*(p::Shift{ORD, Nothing}, V::PairPotential) where {ORD} = Shift(V, p)
@inline evaluate(p::Shift{-1}, r::Number) = r < p.rcut ? p.V(r) : 0.0
@inline evaluate_d(p::Shift{-1}, r::Number) = r < p.rcut ? (@D p.V(r)) : 0.0
@inline evaluate_dd(p::Shift{-1}, r::Number) = r < p.rcut ? (@DD p.V(r)) : 0.0
@inline evaluate(p::Shift{0}, r::Number) = r < p.rcut ? (p.V(r) - p.Vcut) : 0.0
@inline evaluate_d(p::Shift{0}, r::Number) = r < p.rcut ? (@D p.V(r)) : 0.0
@inline evaluate_dd(p::Shift{0}, r::Number) = r < p.rcut ? (@DD p.V(r)) : 0.0
@inline evaluate(p::Shift{1}, r::Number) = r >= p.rcut ? 0.0 :
(p.V(r) - p.Vcut - p.dVcut * (r - p.rcut))
@inline evaluate_d(p::Shift{1}, r::Number) = r < p.rcut ? ((@D p.V(r)) - p.dVcut) : 0.0
@inline evaluate_dd(p::Shift{1}, r::Number) = r < p.rcut ? (@DD p.V(r)) : 0.0
@inline evaluate(p::Shift{2}, r::Number) = r >= p.rcut ? 0.0 :
(p.V(r) - p.Vcut - p.dVcut * (r - p.rcut) - 0.5 * p.ddVcut * (r-p.rcut)^2)
@inline evaluate_d(p::Shift{2}, r::Number) = r >= p.rcut ? 0.0 :
((@D p.V(r)) - p.dVcut - p.ddVcut * (r - p.rcut))
@inline evaluate_dd(p::Shift{2}, r::Number) = r >= p.rcut ? 0.0 :
((@DD p.V(r)) - p.ddVcut)
######################## Quintic Spline cut-off:
# TODO: switch to general types ?
@inline function fcut(r, r0, r1)
s = 1.0 - (r-r0) / (r1-r0)
return (s >= 1.0) + (0.0 < s < 1.0) * (@fastmath 6.0 * s^5 - 15.0 * s^4 + 10.0 * s^3)
end
"Derivative of `fcut`; see documentation of `fcut`."
@inline function fcut_d(r, r0, r1)
s = 1-(r-r0) / (r1-r0)
return -(0 < s < 1) * (@fastmath (30*s^4 - 60 * s^3 + 30 * s^2) / (r1-r0))
end
"Second order derivative of `fcut`; see documentation of `fcut`."
function fcut_dd(r, r0, r1)
s = 1-(r-r0) / (r1-r0)
return (0 < s < 1) * (@fastmath (120*s^3 - 180 * s^2 + 60 * s) / (r1-r0)^2)
end
"""
`SplineCutoff` : Piecewise quintic C^{2,1} regular polynomial.
Parameters:
* r0 : inner cut-off radius
* r1 : outer cut-off radius.
"""
mutable struct SplineCutoff <: PairPotential
r0::Float64
r1::Float64
end
@pot SplineCutoff
@inline evaluate(p::SplineCutoff, r::Number) = fcut(r, p.r0, p.r1)
@inline evaluate_d(p::SplineCutoff, r::Number) = fcut_d(r, p.r0, p.r1)
evaluate_dd(p::SplineCutoff, r::Number) = fcut_dd(r, p.r0, p.r1)
cutoff(p::SplineCutoff) = p.r1
Base.string(p::SplineCutoff) = "SplineCutoff(r0=$(p.r0), r1=$(p.r1))"
# ============ DRAFT: cos-based cutoff ============
@inline function coscut(r::T, r0, r1) where {T <: AbstractFloat}
if r <= r0
return T(1.0)
elseif r > r1
return T(0.0)
else
return @fastmath T(0.5) * (cos( π * (r-r0) / (r1-r0) ) + T(1.0))
end
end
@inline function coscut_d(r::T, r0, r1) where {T <: AbstractFloat}
if r0 < r < r1
return @fastmath - π/(2*(r1-r0)) * sin( π * (r-r0) / (r1-r0) )
else
return T(0.0)
end
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 8986 |
export atomdofs, variablecell, fixedcell, dofmgr_resetref!, variablecell!,
fixedcell!, set_clamp!, set_free!, set_mask!, reset_clamp!
using SparseArrays: SparseMatrixCSC, nnz, sparse, findnz
using LinearAlgebra: rmul!, det
# ========================================================================
# AUXILIARY FUNCTIONS
# ========================================================================
function zeros_free(n::Integer, x::AbstractVector, free)
z = zeros(eltype(x), n)
z[free] = x
return z
end
function insert_free!(p::AbstractArray, x::AbstractVector, free)
p[free] = x
return p
end
# a helper function to get a valid positions array from a dof-vector
positions(at::AbstractAtoms,
ifree::AbstractVector{<:Integer},
dofs::Dofs) =
insert_free!(positions(at) |> mat, dofs, ifree) |> vecs
"""
`_pos_to_dof` : a helper function that will convert a positions-based
block-hessian into a classical dof-based hessian with the standard JuLIP
ordering of dofs.
"""
function _pos_to_dof(Hpos::SparseMatrixCSC, at::AbstractAtoms{T}) where {T}
I, J, Z = Int[], Int[], T[]
for C in (I, J, Z); sizehint!(C, 9 * nnz(Hpos)); end
Nat = length(at)
@assert Nat == size(Hpos, 2)
# TODO: this findnz creates an extra copy of all data, which we should avoid
for (iat, jat, zat) in zip(findnz(Hpos)...)
for a = 1:3, b = 1:3
push!(I, 3 * (iat-1) + a)
push!(J, 3 * (jat-1) + b)
push!(Z, zat[a,b])
end
end
return sparse(I, J, Z, 3*Nat, 3*Nat)
end
# TODO: this is a temporary hack, and I think we need to
# figure out how to do this for more general constraints
# maybe not too terrible
projectxfree(at::Atoms, A::SparseMatrixCSC) =
A[at.dofmgr.xfree, at.dofmgr.xfree]
"""
`analyze_mask` : helper function to generate list of dof indices from
lists of atom indices indicating free and clamped atoms
"""
function analyze_mask(at, free, clamp, mask)
if length(findall((free != nothing, clamp != nothing, mask != nothing))) > 1
error("FixedCell: only one of `free`, `clamp`, `mask` may be provided")
elseif all( (free == nothing, clamp == nothing, mask == nothing) )
# in this case (default) all atoms are free
return collect(1:3*length(at))
end
# determine free dof indices
Nat = length(at)
if clamp != nothing
# revert to setting free
free = setdiff(1:Nat, clamp)
end
if free != nothing
# revert to setting mask
mask = fill(false, 3, Nat)
if !isempty(free)
mask[:, free] .= true
end
end
return findall(mask[:])
end
analyze_mask(at, free::Colon, clamp::Nothing, mask::Nothing) =
collect(1:3*length(at))
analyze_mask(at, free::Nothing, clamp::Colon, mask::Nothing) =
Int[]
# ========================================================================
# MAIN DOF MANAGER INTERFACE
# ========================================================================
"""
`VariableCell`: both atom positions and cell shape are free;
**WARNING:** (1) before manipulating the dof-vectors returned by a `VariableCell`
constraint, read *meaning of dofs* instructions at bottom of help text!
(2) The `volume` field is a signed volume.
Constructor:
```julia
VariableCell(at::AbstractAtoms; free=..., clamp=..., mask=..., fixvolume=false)
```
Set at most one of the kwargs:
* no kwarg: all atoms are free
* `free` : list of free atom indices (not dof indices)
* `clamp` : list of clamped atom indices (not dof indices)
* `mask` : 3 x N Bool array to specify individual coordinates to be clamped
### Meaning of dofs
On call to the constructor, `VariableCell` stored positions and deformation
`X0, F0`, dofs are understood *relative* to this initial configuration.
`dofs(at, cons::VariableCell)` returns a vector that represents a pair
`(Y, F1)` of a displacement and a deformation matrix. These are to be understood
*relative* to the reference `X0, F0` stored in `cons` as follows:
* `F = F1` (the cell is then `F'`)
* `X = [F1 * (F0 \\ y) for y in Y)]`
One aspect of this definition is that clamped atom positions still change via
`F`
"""
DofManager(at::AbstractAtoms) = DofManager(length(at), eltype(at))
DofManager(Nat::Integer, T = Float64) =
DofManager( false, # variablecell
collect(1:3*Nat), # xfree
LinearConstraint{T}[], # lincons
JVec{T}[], # X0
zero(JMat{T}) ) # F0
import Base.==
==(d1::DofManager, d2::DofManager) =
(d1.variablecell == d2.variablecell) && (d1.xfree == d2.xfree)
# TODO: potential need to add equality about the constraints?
# is xfree even relevant for equality?
variablecell(at::Atoms) = at.dofmgr.variablecell
fixedcell(at::Atoms) = !variablecell(at::Atoms)
function dofmgr_resetref!(at)
at.dofmgr.X0 = copy(positions(at))
at.dofmgr.F0 = cell(at)'
return at
end
# convenience function to return DoFs associated with a particular atom
atomdofs(at::Atoms, i::Integer) =
findall(in(3*i-2:3*i), at.dofmgr.xfree)
"""
`variablecell!(at)` : make the cell-shape variable
"""
variablecell!(at) = set_variablecell!(at, true)
"""
`fixedcell!(at)` : freeze the cell shape
"""
fixedcell!(at) = set_variablecell!(at, false)
"""
`set_variablecell!` : specify whether cell shape is variable or fixed
"""
function set_variablecell!(at::AbstractAtoms, tf::Bool)
at.dofmgr.variablecell = tf
if tf
dofmgr_resetref!(at)
end
return at
end
set_clamp!(at::Atoms, Iclamp::AbstractVector{<: Integer}) =
set_clamp!(at; clamp = Iclamp)
set_free!(at::Atoms, Ifree::AbstractVector{<: Integer}) =
set_clamp!(at; free = Ifree)
set_mask!(at::Atoms, mask) =
set_clamp!(at; mask=mask)
reset_clamp!(at) = set_clamp!(at; free = :)
function set_clamp!(at::Atoms; free=nothing, clamp=nothing, mask=nothing)
at.dofmgr.xfree = analyze_mask(at, free, clamp, mask)
return at
end
# reverse map:
# F -> F
# X[n] = F * F^{-1} X0[n]
function position_dofs(at::Atoms)
if fixedcell(at)
return mat(at.X)[at.dofmgr.xfree]
end
# variable cell case:
X = positions(at)
F = cell(at)'
A = at.dofmgr.F0 * inv(F)
U = [A * x for x in X] # switch to broadcast!
return [mat(U)[at.dofmgr.xfree]; Matrix(F)[:]]
end
posdofs(x) = x[1:end-9]
celldofs(x) = x[end-8:end]
function set_position_dofs!(at::AbstractAtoms{T}, x::Dofs) where {T}
if fixedcell(at)
return set_positions!(at, positions(at, at.dofmgr.xfree, x))
end
# variable cell case:
F = JMat{T}(celldofs(x))
A = F * inv(at.dofmgr.F0)
Y = copy(at.dofmgr.X0)
mat(Y)[at.dofmgr.xfree] = posdofs(x)
for n = 1:length(Y)
Y[n] = A * Y[n]
end
set_positions!(at, Y)
set_cell!(at, F')
return at
end
function momentum_dofs(at::AbstractAtoms)
if fixedcell(at)
return mat(momenta(at))[at.dofmgr.xfree]
end
@error("`momentum_dofs` is not yet implmement for variable cells")
return nothing
end
function set_momentum_dofs!(at::AbstractAtoms, p::Dofs)
if fixedcell(at)
return set_momenta!(at, zeros_free(3 * length(at), p, at.dofmgr.xfree) |> vecs)
end
@error("`set_momentum_dofs!` is not yet implmement for variable cells")
return nothing
end
# for a variation x^t_i = (F+tU) F_0^{-1} (u_i + t v_i)
# ~ U F^{-1} F F0^{-1} u_i + F F0^{-1} v_i
# we get
# dE/dt |_{t=0} = U : (S F^{-T}) - < (F * inv(F0))' * frc, v>
#
# this is nice because there is no contribution from the stress to
# the positions component of the gradient
"""
`sigvol` : signed volume
"""
sigvol(C::AbstractMatrix) = det(C)
sigvol(at::AbstractAtoms) = sigvol(cell(at))
"""
`sigvol_d` : derivative of signed volume
"""
sigvol_d(C::AbstractMatrix) = sigvol(C) * inv(C)'
sigvol_d(at::AbstractAtoms) = sigvol_d(cell(at))
function gradient(calc::AbstractCalculator, at::Atoms)
if fixedcell(at)
return rmul!(mat(forces(at))[at.dofmgr.xfree], -1.0)
end
F = cell(at)'
A = F * inv(at.dofmgr.F0)
G = forces(at)
for n = 1:length(G)
G[n] = - A' * G[n]
end
S = - virial(at) * inv(F)' # ∂E / ∂F
# S += at.dofmgr.pressure * sigvol_d(at)' # applied stress TODO: revive this!
return [ mat(G)[at.dofmgr.xfree]; Array(S)[:] ]
end
function hessian(calc::AbstractCalculator, at::AbstractAtoms)
if fixedcell(at)
H = _pos_to_dof(hessian_pos(calculator(at), at), at)
return projectxfree(at, H)
end
@error("`hessian` is not yet implmement for variable cells")
return nothing
end
# TODO:
# - in-plane, anti-plane
# - pressure
# - fixvolume
# - once we add an external potential we need to think about terminology
# should energy -> potential_energy?; total_energy a new one?
# total_energy(calc::AbstractCalculator, at::AbstractAtoms, cons::VariableCell) =
# energy(calc, at) + cons.pressure * sigvol(at)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 6413 |
using NeighbourLists
using DelimitedFiles: readdlm
using JuLIP: r_sum
using LinearAlgebra: rmul!
export EAM
# =================== General Single-Species EAM Potential ====================
"""
`struct EAM1`
Generic Single-species EAM potential, to specify it, one needs to
specify the pair potential ϕ, the electron density ρ and the embedding
function F.
The most convenient constructor is likely via tabulated values,
more below.
# Constructors:
```
EAM(pair::PairPotential, eden::PairPotential, embed)
EAM(fpair::AbstractString, feden::AbstractString, fembed::AbstractString; kwargs...)
```
## Constructing an EAM potential from tabulated values
At the moment only the .plt format is implemented. Files can e.g. be
obtained from
* [NIST](https://www.ctcms.nist.gov/potentials/)
Use the `EAM(fpair, feden, fembed)` constructure. The keyword arguments specify
details of how the tabulated values are fitted; see
`?SplinePairPotential` for more details.
TODO: implement other file formats.
"""
struct EAM1{T1, T2, T3, T4} <: SitePotential
ϕ::T1 # pair potential
ρ::T2 # electron density potential
F::T3 # embedding function
info::T4
end
@pot EAM1
EAM1(ϕ, ρ, F) = EAM1(ϕ, ρ, F, nothing)
cutoff(V::EAM1) = max(cutoff(V.ϕ), cutoff(V.ρ))
function evaluate!(tmp, V::EAM1, R::AbstractVector{JVec{T}}) where {T}
if length(R) == 0
return V.F(T(0.0))
else
return V.F(sum(V.ρ ∘ norm, R)) + T(0.5) * sum(V.ϕ ∘ norm, R)
end
end
function evaluate_d!(dEs::AbstractVector{JVec{T}}, tmp, V::EAM1, Rs) where {T}
if length(Rs) == 0; return dEs; end
ρ̄ = sum(V.ρ ∘ norm, Rs)
dF = @D V.F(ρ̄)
for (i, R) in enumerate(Rs)
r = norm(R)
dEs[i] = ((T(0.5) * (@D V.ϕ(r)) + dF * (@D V.ρ(r))) / r) * R
end
return dEs
end
alloc_temp_dd(V::EAM1, N::Integer) =
( ∇ρ = zeros(JVecF, N),
r = zeros(Float64, N) )
evaluate_dd!(hEs, tmp, V::EAM1, R) = _hess_!(hEs, tmp, V, R, identity)
# ff preconditioner specification for EAM potentials
# (just replace id with abs and hess with precon in the hessian code)
precon!(hEs, tmp, V::EAM1, R, stab=0.0) = _hess_!(hEs, tmp, V, R, abs, stab)
function _hess_!(hEs, tmp, V::EAM1, R::AbstractVector{JVec{T}}, fabs, stab=T(0)
) where {T}
for i = 1:length(R)
r = norm(R[i])
tmp.r[i] = r
tmp.∇ρ[i] = grad(V.ρ, r, R[i])
end
# precompute some stuff
ρ̄ = sum(V.ρ, tmp.r)
dF = @D V.F(ρ̄)
ddF = @DD V.F(ρ̄)
# assemble
for i = 1:length(R)
for j = 1:length(R)
hEs[i,j] = (1-stab) * fabs(ddF) * tmp.∇ρ[i] * tmp.∇ρ[j]'
end
r = tmp.r[i]
S = R[i] / r
dϕ = @D V.ϕ(r)
dρ = @D V.ρ(r)
ddϕ = @DD V.ϕ(r)
ddρ = @DD V.ρ(r)
a = fabs(0.5 * ddϕ + dF * ddρ)
b = fabs((0.5 * dϕ + dF * dρ) / r)
hEs[i,i] += ( (1-stab) * ( (a-b) * S * S' + b * I )
+ stab * ( (a+b) * I ) )
end
return hEs
end
# implementation of EAM models using data files
function EAM(fpair::AbstractString, feden::AbstractString,
fembed::AbstractString; kwargs...)
pair = SplinePairPotential(fpair; kwargs...)
eden = SplinePairPotential(feden; kwargs...)
embed = SplinePairPotential(feden; fixcutoff = false, kwargs...)
return EAM1(pair, eden, embed)
end
#
# Load EAM file from .fs file format
#
function EAM(fname::AbstractString; kwargs...)
if fname[end-3:end] == ".eam"
error(".eam is not yet implemented, please file an issue")
elseif fname[end-6:end] == ".eam.fs"
error(".eam.fs is not yet implemented, please file an issue")
elseif fname[end-2:end] == ".fs"
return eam_from_fs(fname; kwargs...)
end
error("unknwon EAM file format, please file an issue")
end
# ================= Finnis-Sinclair Potential =======================
mutable struct FSEmbed end
@pot FSEmbed
evaluate(V::FSEmbed, ρ̄) = - sqrt(ρ̄)
evaluate_d(V::FSEmbed, ρ̄::T) where {T} = - T(0.5) / sqrt(ρ̄)
evaluate_dd(V::FSEmbed, ρ̄::T) where {T} = T(0.25) * ρ̄^(T(-3/2))
"""
`FinnisSinclair`: constructs an EAM potential with embedding function
-√ρ̄.
"""
FinnisSinclair(pair::PairPotential, eden::PairPotential) =
EAM1(pair, eden, FSEmbed())
function FinnisSinclair(fpair::AbstractString, feden::AbstractString; kwargs...)
pair = SplinePairPotential(fpair; kwargs...)
eden = SplinePairPotential(feden; kwargs...)
return FinnisSinclair(pair, eden)
end
# ================= Various File Loaders =======================
"""
`eam_from_fs(fname; kwargs...) -> EAM`
Read a `.fs` file specifying and EAM / Finnis-Sinclair potential.
"""
function eam_from_fs(fname; kwargs...)
F, ρfun, ϕfun, ρ, r, info = read_fs(fname)
return EAM1( SplinePairPotential(r, ϕfun; kwargs...) * (@analytic r -> 1/r),
SplinePairPotential(r, ρfun; kwargs...),
SplinePairPotential(ρ, F; fixcutoff= false, kwargs...),
info )
end
"""
`read_fs(fname)` -> F, ρfun, ϕfun, ρ, r, info
Read a `.fs` file specifying and EAM / Finnis-Sinclair potential.
The description of the file format is taken from
http://lammps.sandia.gov/doc/pair_eam.html
see also
https://sites.google.com/a/ncsu.edu/cjobrien/tutorials-and-guides/eam
"""
function read_fs(fname)
f = open(fname)
# ignore the first three lines
for n = 1:3
readline(f)
end
# line 4: Nelements Element1 Element2 ... ElementN
L4 = readline(f) |> chomp |> IOBuffer |> readdlm
if L4[1] != 1
error("""`read_fs`: the file `$fname` is for alloys, but only
the single species potential is implemented so far.""")
end
info = Dict()
info[:species] = L4[2]
# line 5: Nrho, drho, Nr, dr, cutoff
L5 = readline(f) |> IOBuffer |> readdlm
Nrho, drho, Nr, dr, cutoff = Int(L5[1]), L5[2], Int(L5[3]), L5[4], L5[5]
info[:cutoff] = cutoff
# line 6: atomic number, mass, lattice constant, lattice type (e.g. FCC)
L6 = readline(f) |> IOBuffer |> readdlm
info[:number], info[:mass], info[:a0], info[:lattice] = tuple(L6...)
# all the data
data = readdlm(f)
@assert length(data) == Nrho+2*Nr
ρ = range(0, stop=(Nrho-1)*drho, length=Nrho)
r = range(cutoff - (Nr-1)*dr, stop=cutoff, length=Nr)
# embedding function
F = data[1:Nrho]
# density function
ρfun = data[Nrho+1:Nrho+Nr]
# interatomic potential
ϕfun = data[Nrho+Nr+1:Nrho+2*Nr]
return F, ρfun, ϕfun, ρ, r, info
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 3479 |
using JuLIP.FIO: load_json
using JuLIP: chemical_symbol, atomic_number
using JuLIP.Potentials: WrappedAnalyticFunction, F64fun, @D
import JuLIP.Potentials: evaluate!, evaluate_d!
export EMT
"""
`EMT`: a re-implementation of the `EMT` calculator (a variant of EAM) os ASE
in Julia, largely for fun and comparison with Python, but also to demonstrate
how to implement a multi-component calculator in JuLIP
"""
struct EMT <: MSitePotential
pair::Vector{WrappedPairPotential}
Cpair::Vector{Float64}
rho::Vector{WrappedPairPotential}
embed::Vector{WrappedAnalyticFunction}
z2ind::Dict{Int, Int}
rc::Float64
end
cutoff(calc::EMT) = calc.rc + 0.5
# ========================== Initialisation ============================
function _load_emt()
D = load_json( joinpath(@__DIR__(), "..", "data", "emt.json") )
return D["params"], D["acut"], D["rc"], D["beta"]
end
EMT(at::Atoms) = EMT(unique(at.Z))
EMT(sym::Vector{Symbol}) = EMT(atomic_number.(sym))
function EMT(Z::Vector{<:Integer})
# load all the parameters
params, acut, rc, β = _load_emt()
rcplus = rc + 0.5 # the actual cutoff
# get unique Z numbers and use them to allocate the EMT calculator
Z = unique(Z)
nZ = length(Z)
emt = EMT(Vector{WrappedPairPotential}(undef, nZ), # pair
Vector{Float64}(undef, nZ), # Cpair
Vector{WrappedPairPotential}(undef, nZ), # rho
Vector{WrappedAnalyticFunction}(undef, nZ), # embed
Dict{Int,Int}(),
rc)
# loop through unique symbols/Z and for each compute the relevant potentials
for (i, z) in enumerate(Z)
# store Z -> i maps
emt.z2ind[z] = i
sym = chemical_symbol(z)
p = params[String(sym)]
# cut-off: this is a FD function; this is AWFUL! replace with spline???
# Θ = 1.0 / (1.0 + exp($acut * (r - $rc) ))
# pair potential
n0, κ, s0 = p["n0"], p["κ"], p["s0"]
emt.pair[i] = WrappedPairPotential(
@analytic(r -> n0 * exp( -κ * (r / β - s0) ) * θ,
θ = 1.0 / (1.0 + exp(acut * (r - rc) )) ), rcplus)
emt.Cpair[i] = p["Cpair"]
# radial electron density function
η2, γ1 = p["η2"], p["γ1"]
emt.rho[i] = WrappedPairPotential(
@analytic(
r -> n0 * exp( -η2 * (r - (β*s0)) ) * θ,
θ = 1.0 / (1.0 + exp(acut * (r - rc) )) ), rcplus)
# embedding function
E0, V0, λ = p["E0"], p["V0"], p["λ"]
emt.embed[i] = F64fun( @analytic(
ρ̄-> E0 * ((1.0 + λ * DS) * exp(-λ * DS) - 1.0) + 6.0 * V0 * exp(-κ * DS),
DS = - log( (1.0/(12.0*γ1*n0)) * ρ̄ ) / (β * η2) ) )
end
return emt
end
# ========================== Main Functionality ============================
function evaluate!(tmp, emt::EMT, 𝐑, 𝐙, z0)
ρ̄ = 0.0
Es = 0.0
i0 = emt.z2ind[z0]
for (R, Z) in zip(𝐑, 𝐙)
i = emt.z2ind[Z]
r = norm(R)
Es += emt.Cpair[i0] * emt.pair[i](r)
ρ̄ += emt.rho[i](r)
end
Es += emt.embed[i0](ρ̄)
return Es
end
function evaluate_d!(dEs, tmp, emt::EMT, 𝐑, 𝐙, z0)
ρ̄ = 0.0
i0 = emt.z2ind[z0]
for (R, Z) in zip(𝐑, 𝐙)
i = emt.z2ind[Z]
r = norm(R)
ρ̄ += emt.rho[i](r)
end
dF = @D emt.embed[i0](ρ̄)
for (j, (R, Z)) in enumerate(zip(𝐑, 𝐙))
i = emt.z2ind[Z]
r = norm(R)
R̂ = R/r
dpair = emt.Cpair[i0] * (@D emt.pair[i](r))
drho = @D emt.rho[i](r)
dEs[j] = (dpair + dF * drho) * R̂
end
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 3769 | # ========================================================================
# EXP VARIABLE CELL IMPLEMENTATION
# ========================================================================
#
# F = exp(U) F0
# x = F * F0^{-1} z = exp(U) z
#
# ϕ( exp(U+tV) (z+tv) ) ~ ϕ'(x) ⋅ (exp(U) V) + ϕ'(x) ⋅ ( L(U, V) exp(-U) exp(U) z )
# >>> ∂E(U) : V = [S exp(-U)'] : L(U,V)
# = L'(U, S exp(-U)') : V
# = L(U', S exp(-U)') : V
# = L(U, S exp(-U)) : V (provided U = U')
# define expm for StaticArrays since it is not provided (anymre?)
import StaticArrays
using LinearAlgebra: det
_expm(A::StaticArrays.SMatrix{N,N,T}) where {N,T} =
StaticArrays.SMatrix{N,N,T}(exp(Array(A)))
mutable struct ExpVariableCell <: AbstractConstraint
ifree::Vector{Int}
X0::Vector{JVecF}
F0::JMatF
pressure::Float64
fixvolume::Bool
end
function ExpVariableCell(at::AbstractAtoms;
free=nothing, clamp=nothing, mask=nothing,
pressure = 0.0, fixvolume=false)
if pressure != 0.0 && fixvolume
warning("the pressure setting will be ignored when `fixvolume==true`")
end
return ExpVariableCell( analyze_mask(at, free, clamp, mask),
positions(at), defm(at), pressure, fixvolume )
end
function logm_defm(at::AbstractAtoms, cons::ExpVariableCell)
F = defm(at)
# remove the reference deformation (F = expm(U) * F0)
expU = F * inv(cons.F0)
# expU should be spd, but roundoff (or other things) might mess this up
# do we need an extra check here?
U = log(expU |> Array) |> JMat
U = real(0.5 * (U + U'))
# check that expm(U) * F0 ≈ F (if not, then something has gone horribly wrong)
if norm(F - _expm(U) * cons.F0, Inf) > 1e-12
@show F
@show _expm(U) * cons.F0
error("something has gone wrong; U is not symmetric?")
end
return U, F
end
expposdofs(x) = x[1:end-6]
expcelldofs(x) = x[end-5:end]
U2dofs(U) = U[(1,2,3,5,6,9)]
dofs2U(x) = JMat(expcelldofs(x)[(1,2,3,2,4,5,3,5,6)])
function position_dofs(at::AbstractAtoms, cons::ExpVariableCell)
X = positions(at)
U, _ = logm_defm(at, cons)
# tranform the positions back to the reference cell (F0)
broadcast!(x -> _expm(-U) * x, X, X)
# construct dof vector
return [mat(X)[cons.ifree]; U2dofs(U)]
end
function set_position_dofs!(at::AbstractAtoms, cons::ExpVariableCell, x::Dofs)
U = dofs2U(x)
expU = _expm(U)
F = expU * cons.F0
Z = copy(cons.X0)
mat(Z)[cons.ifree] = expposdofs(x)
broadcast!(z -> expU * z, Z, Z)
set_positions!(at, Z)
set_defm!(at, F)
return at
end
"""
Directional derivative of matrix exponential. See Theorem 2.1 in
AL-MOHY, HIGHAM SIAM J. Matrix Anal. Appl. 30, 2009.
"""
function dexpm_3x3(X::AbstractMatrix, E::AbstractMatrix)
@assert size(X) == size(E) == (3, 3)
return _expm([ X E; zeros(3,3) X ])[1:3, 4:6]
end
function gradient(at::AbstractAtoms, cons::ExpVariableCell)
U, F = logm_defm(at, cons)
G = forces(at)
broadcast!(g -> - (_expm(U) * g), G, G) # G[n] <- -exp(U) * G[n]
T = dexpm_3x3(U, - virial(at) * _expm(-U))
# add the forces acting on the upper diagonal of U to the lower diagonal
# this way we ensure that T : V = U2dofs(T) : U2dofs(V)
T[[2,3,6]] += T[[4,7,8]]
# add the pressure component
T[[1,5,9]] += cons.pressure * exp(trace(U)) * U[[1,5,9]]
return [ mat(G)[cons.ifree]; U2dofs(T) ]
end
energy(at::AbstractAtoms, cons::ExpVariableCell) =
energy(at) + cons.pressure * det(defm(at)) / det(cons.F0)
# >>>>>> exp(trace(U)) <<<<< (tested)
# TODO: fix this once we implement the volume constraint ??????
project!(at::AbstractAtoms, cons::ExpVariableCell) = at
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 4264 |
hessian_pos(V::SitePotential, at::AbstractAtoms) =
_precon_or_hessian_pos(V, at, evaluate_dd!)
# implementation of a generic assembly of a global block-hessian from
# local site-hessians
function _precon_or_hessian_pos(V, at::AbstractAtoms{T}, hfun) where {T}
nlist = neighbourlist(at, cutoff(V))
maxN = maxneigs(nlist)
hEs = zeros(JMat{T}, maxN, maxN)
tmp = alloc_temp_dd(V, maxN)
I, J, Z = Int[], Int[], JMat{T}[]
# a crude size hint
for C in (I, J, Z); sizehint!(C, npairs(nlist)); end
for (i, neigs, R) in sites(nlist)
nneigs = length(neigs)
# [1] the "off-centre" component of the hessian:
# h[a, b] = ∂_{Ra} ∂_{Rb} V (this is a nneigs x nneigs block-matrix)
fill!(hEs, zero(JMat{T}))
hfun(hEs, tmp, V, R)
for a = 1:nneigs, b = 1:nneigs
# if norm(hEs[a,b], Inf) > 0
push!(I, neigs[a])
push!(J, neigs[b])
push!(Z, hEs[a,b])
# end
end
# [2] the ∂_{Ri} ∂_{Ra} terms
# hib = ∂_{Ri} ∂_{Rb} V = - ∑_a ∂_{Ra} ∂_{Rb} V
# also at the same time we pre-compute the centre-centre term:
# hii = ∂_{Ri} ∂_{Ri} V = - ∑_a ∂_{Ri} ∂_{Ra} V
hii = zero(JMat{T})
for b = 1:nneigs
hib = -sum( hEs[a, b] for a = 1:nneigs )
# if norm(hib, Inf) > 0
hii -= hib
append!(I, (i, neigs[b] ))
append!(J, (neigs[b], i ))
append!(Z, (hib, hib' ))
# end
end
# and finally add the ∂_{Ri}^2 term, which is precomputed above
# if norm(hii, Inf) > 0
push!(I, i)
push!(J, i)
push!(Z, hii)
# end
end
return sparse(I, J, Z, length(at), length(at))
end
# ====== TODO: revisit the FD hessians =========
# """
# `fd_hessian(V, R, h) -> H`
#
# If `length(R) = N` and `length(R[i]) = d` then `H` is an N × N `Matrix{SMatrix}` with
# each element a d × d static array.
# """
# function fd_hessian(V::SitePotential, R::Vector{SVec{D,T}}, h) where {D,T}
# N = length(R)
# H = zeros(SMat{D, D, T}, N, N)
# return fd_hessian!(H, V, R, h)
# end
#
# """
# `fd_hessian!(H, V, R, h) -> H`
#
# Fill `H` with the hessian entries; cf `fd_hessian`.
# """
# function fd_hessian!(H, V::SitePotential, R::Vector{SVec{D,T}}, h) where {D,T}
# N = length(R)
# # convert R into a long vector and H into a big matrix (same part of memory!)
# Rvec = mat(R)[:]
# Hmat = zeros(N*D, N*D) # reinterpret(T, H, (N*D, N*D))
# # now re-define ∇V as a function of a long vector (rather than a vector of SVecs)
# dV(r) = (evaluate_d(V, r |> vecs) |> mat)[:]
# # compute the hessian as a big matrix
# for i = 1:N*D
# Rvec[i] +=h
# dVp = dV(Rvec)
# Rvec[i] -= 2*h
# dVm = dV(Rvec)
# Hmat[:, i] = (dVp - dVm) / (2 * h)
# Rvec[i] += h
# end
# Hmat = 0.5 * (Hmat + Hmat')
# # convert to a block-matrix
# for i = 1:N, j = 1:N
# Ii = (i-1) * D + (1:D)
# Ij = (j-1) * D + (1:D)
# H[i, j] = SMat{D,D}(Hmat[Ii, Ij])
# end
# return H
# end
#
# function fd_hessian(calc::AbstractCalculator, at::AbstractAtoms{T}, h) where {T}
# N = length(at)
# H = zeros(JMat{T}, N, N)
# return fd_hessian!(H, calc, at, h)
# end
#
#
# """
# `fd_hessian!{D,T}(H, calc, at, h) -> H`
#
# Fill `H` with the hessian entries; cf `fd_hessian`.
# """
# function fd_hessian!(H, calc::AbstractCalculator, at::AbstractAtoms, h)
# D = 3
# N = length(at)
# X = positions(at) |> mat
# x = X[:]
# # convert R into a long vector and H into a big matrix (same part of memory!)
# Hmat = zeros(N*D, N*D)
# # now re-define ∇V as a function of a long vector (rather than a vector of SVecs)
# dE(x_) = (site_energy_d(calc, set_positions!(at, reshape(x_, D, N)), 1) |> mat)[:]
# # compute the hessian as a big matrix
# for i = 1:N*D
# x[i] += h
# dEp = dE(x)
# x[i] -= 2*h
# dEm = dE(x)
# Hmat[:, i] = (dEp - dEm) / (2 * h)
# x[i] += h
# end
# Hmat = 0.5 * (Hmat + Hmat')
# # convert to a block-matrix
# for i = 1:N, j = 1:N
# Ii = (i-1) * D + (1:D)
# Ij = (j-1) * D + (1:D)
# H[i, j] = SMat{D,D}(Hmat[Ii, Ij])
# end
# return H
# end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 5097 |
"""
Prototype for IPs based on "Machine-Learning", to be imported by
modules that either define basis sets or regression methods
"""
module MLIPs
using JuLIP: AbstractCalculator, AbstractAtoms
using JuLIP.FIO: decode_dict
import JuLIP: energy, forces, virial, site_energy, site_energy_d
import Base: Dict, convert, ==
export IPSuperBasis, IPCollection, combine
"""
`abstract type IPBasis` : A type derived from `IPBasis` defines
not an IP as such but a collection of IPs that can be understood as
a basis set. E.g., a 2B-potential could be obtained from
polynomials,
```
ϕ(r) = ∑_k c_k exp(-k r)
```
then the `B::IPBasis` might specify the basis functions {r -> exp(-kr)} as
a collection of `PairPotential`s.
Then, `energy(at, B)` does not return a single energy but a vector
of energies.
## Developer Notes
* `length(basis::IPBasis)` must return the number of basis functions
"""
abstract type IPBasis end
# ========== wrap one more more calculators into a basis =================
struct IPCollection{T} <: IPBasis
coll::Vector{T}
end
IPCollection(args...) = IPCollection([args...])
Base.length(coll::IPCollection) = length(coll.coll)
combine(basis::IPCollection, coeffs::AbstractVector{<:Number}) =
SumIP([ c * b for (c, b) in zip(coeffs, basis.coll) ])
energy(coll::IPCollection, at::AbstractAtoms) =
[ energy(B, at) for B in coll.coll ]
forces(coll::IPCollection, at::AbstractAtoms) =
[ forces(B, at) for B in coll.coll ]
virial(coll::IPCollection, at::AbstractAtoms) =
[ virial(B, at) for B in coll.coll ]
site_energy(coll::IPCollection, at::AbstractAtoms, i0::Integer) =
[ site_energy(V, at, i0) for V in coll.coll ]
site_energy_d(coll::IPCollection, at::AbstractAtoms, i0::Integer) =
[ site_energy_d(V, at, i0) for V in coll.coll ]
Dict(coll::IPCollection) = Dict(
"__id__" => "JuLIP_IPCollection",
"coll" => Dict.(coll.coll) )
IPCollection(D::Dict) = IPCollection( decode_dict.( D["coll"] ) )
convert(::Val{:JuLIP_IPCollection}, D::Dict) = IPCollection(D)
import Base.==
==(B1::IPCollection, B2::IPCollection) = all(B1.coll .== B2.coll)
# ========== IPSuperBasis : combine multiple sub-basis =================
"""
`struct IPSuperBasis:` a collection of IP basis sets, re-interpreted
as a large basis
"""
struct IPSuperBasis{TB <: IPBasis} <: IPBasis
BB::Vector{TB}
end
_convert_basis_(b::IPBasis) = b
_convert_basis_(b::AbstractCalculator) = IPCollection(b)
_convert_basis_(b::AbstractVector) = IPCollection(b)
IPSuperBasis(args...) = IPSuperBasis([_convert_basis_(b) for b in args])
Base.length(super::IPSuperBasis) = sum(length.(super.BB))
function combine(basis::IPSuperBasis, coeffs::AbstractVector{<:Number})
i0 = 0
components = []
for B in basis.BB
lenB = length(B)
push!(components, combine(B, coeffs[i0+1:i0+lenB]))
i0 += lenB
end
return SumIP(components)
end
energy(superB::IPSuperBasis, at::AbstractAtoms) =
vcat([ energy(B, at) for B in superB.BB ]...)
forces(superB::IPSuperBasis, at::AbstractAtoms) =
vcat([ forces(B, at) for B in superB.BB ]...)
virial(superB::IPSuperBasis, at::AbstractAtoms) =
vcat([ virial(B, at) for B in superB.BB ]...)
site_energy(superB::IPSuperBasis, at::AbstractAtoms, i0::Integer) =
vcat([ site_energy(B, at, i0) for B in superB.BB ]...)
site_energy_d(superB::IPSuperBasis, at::AbstractAtoms, i0::Integer) =
vcat([ site_energy_d(B, at, i0) for B in superB.BB ]...)
Dict(superB::IPSuperBasis) = Dict(
"__id__" => "JuLIP_IPSuperBasis",
"components" => Dict.(superB.BB) )
IPSuperBasis(D::Dict) = IPSuperBasis( decode_dict.( D["components"] ) )
convert(::Val{:JuLIP_IPSuperBasis}, D::Dict) = IPSuperBasis(D)
import Base.==
==(B1::IPSuperBasis, B2::IPSuperBasis) = all(B1.BB .== B2.BB)
# ========== SumIP =================
# a sum of several IPs.
struct SumIP{T} <: AbstractCalculator
components::Vector{T}
end
SumIP(args...) = SumIP([args...])
energy(sumip::SumIP, at::AbstractAtoms; kwargs...) =
sum(energy(calc, at; kwargs...) for calc in sumip.components)
forces(sumip::SumIP, at::AbstractAtoms; kwargs...) =
sum(forces(calc, at; kwargs...) for calc in sumip.components)
virial(sumip::SumIP, at::AbstractAtoms; kwargs...) =
sum(virial(calc, at; kwargs...) for calc in sumip.components)
site_energy(sumip::SumIP, at::AbstractAtoms, i0::Integer) =
sum(site_energy(V, at, i0) for V in sumip.components)
site_energy_d(sumip::SumIP, at::AbstractAtoms, i0::Integer) =
sum(site_energy_d(V, at, i0) for V in sumip.components)
Dict(sumip::SumIP) = Dict(
"__id__" => "JuLIP_SumIP",
"components" => Dict.(sumip.components) )
SumIP(D::Dict) = SumIP( decode_dict.( D["components"] ) )
convert(::Val{:JuLIP_SumIP}, D::Dict) = SumIP(D)
SumIP(V::AbstractCalculator, sumip::SumIP) =
SumIP( [ [V]; sumip.components ] )
SumIP(sumip::SumIP, V::AbstractCalculator) =
SumIP( [ sumip.components; [V] ] )
SumIP(sum1::SumIP, sum2::SumIP) =
SumIP( [ sum1.components; sum2.components ] )
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 3402 | using JuLIP.Chemistry: atomic_number
using JuLIP: Atoms
abstract type MSitePotential <: AbstractCalculator end
# Experimental Multi-component codes
"""
`neigsz!(tmp, nlist::PairList, at::Atoms, i::Integer) -> j, R Z`
requires a temporary storage array `tmp` with fields
`tmp.R, tmp.Z`.
"""
function neigsz!(tmp, nlist::PairList, at::Atoms, i::Integer)
j, R = neigs!(tmp.R, nlist, i)
Z = tmp.Z
for n = 1:length(j)
Z[n] = at.Z[j[n]]
end
return j, R, (@view Z[1:length(j)])
end
struct MPairPotential <: MSitePotential
Z2V::Dict{Tuple{Int16,Int16}, WrappedPairPotential}
end
MPairPotential() =
MPairPotential(Dict{(Int16, Int16), WrappedPairPotential}())
function MPairPotential(args...)
Vm = MPairPotential()
for p in args
@assert p isa Pair
z, V = _convert_multi_pp(sym::Symbol, p)
Vm.Z2V[z] = V
end
return Vm
end
F64fun(V::F64fun) = V
_convert_multi_pp(sym::Tuple{Symbol, Symbol}, V) =
_convert_multi_pp(atomic_number.(sym), V)
_convert_multi_pp(z::Tuple{<:Integer,<:Integer}, V) =
Int16.(z), V
cutoff(V::MPairPotential) =
maximum( cutoff(V) for (key, V) in V.Z2V )
alloc_temp(V::MSitePotential, at::AbstractAtoms) =
alloc_temp(V, maxneigs(neighbourlist(at, cutoff(V))))
alloc_temp(V::MSitePotential, N::Integer) =
( R = zeros(JVecF, N),
Z = zeros(Int16, N), )
alloc_temp_d(V::MSitePotential, at::AbstractAtoms) =
alloc_temp_d(V, maxneigs(neighbourlist(at, cutoff(V))))
alloc_temp_d(V::MSitePotential, N::Integer) =
(dV = zeros(JVecF, N),
R = zeros(JVecF, N),
Z = zeros(Int16, N), )
energy(V::MSitePotential, at::AbstractAtoms; kwargs...) =
energy!(alloc_temp(V, at), V, at; kwargs...)
virial(V::MSitePotential, at::AbstractAtoms; kwargs...) =
virial!(alloc_temp_d(V, at), V, at; kwargs...)
forces(V::MSitePotential, at::AbstractAtoms{T}; kwargs...) where {T} =
forces!(zeros(JVec{T}, length(at)), alloc_temp_d(V, at), V, at; kwargs...)
function energy!(tmp, calc::MSitePotential, at::Atoms{T};
domain=1:length(at)) where {T}
E = 0.0
nlist = neighbourlist(at, cutoff(calc))
for i in domain
j, R, Z = neigsz!(tmp, nlist, at, i)
E += evaluate!(tmp, calc, R, Z, Int16(at.Z[i]))
end
return E
end
function forces!(frc, tmp, calc::MSitePotential, at::Atoms{T};
domain=1:length(at), reset=true) where {T}
if reset; fill!(frc, zero(JVec{T})); end
nlist = neighbourlist(at, cutoff(calc))
for i in domain
j, R, Z = neigsz!(tmp, nlist, at, i)
evaluate_d!(tmp.dV, tmp, calc, R, Z, Int16(at.Z[i]))
for a = 1:length(j)
frc[j[a]] -= tmp.dV[a]
frc[i] += tmp.dV[a]
end
end
return frc
end
function virial!(tmp, calc::MSitePotential, at::Atoms{T};
domain=1:length(at)) where {T}
nlist = neighbourlist(at, cutoff(calc))
vir = zero(JMat{T})
for i in domain
j, R, Z = neigsz!(tmp, nlist, at, i)
evaluate_d!(tmp.dV, tmp, calc, R, Z, Int16(at.Z[i]))
vir += site_virial(tmp.dV, R)
end
return vir
end
evaluate(V::MSitePotential, R, Z, z) =
evaluate!(alloc_temp(V, length(R)), V, R, Z, z)
evaluate_d(V::MSitePotential, R::AbstractVector{JVec{T}}, Z, z) where {T} =
evaluate_d!(zeros(JVec{T}, length(R)),
alloc_temp_d(V, length(R)),
V, R, Z, z)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2572 |
import Base: convert, ==
# import JuLIP: energy, virial, site_energies, forces
# import JuLIP.Potentials: evaluate
using JuLIP: JVec, JMat, chemical_symbols
export OneBody, MOneBody
"""
`mutable struct OneBody{T} <: NBodyFunction{1}`
this should not normally be constructed by a user, but instead E0 should be
passed to the relevant lsq functions, which will construct it.
"""
mutable struct OneBody{T} <: AbstractCalculator
E0::T
end
@pot OneBody
evaluate(V::OneBody) = V.E0
site_energies(V::OneBody, at::AbstractAtoms) = fill(V(), length(at))
energy(V::OneBody, at::AbstractAtoms; domain = 1:length(at)) = length(domain) * V()
forces(V::OneBody, at::AbstractAtoms{T}; kwargs...) where {T} = zeros(JVec{T}, length(at))
virial(V::OneBody, at::AbstractAtoms{T}; kwargs...) where {T} = zero(JMat{T})
site_energy(V::OneBody, at::AbstractAtoms, i0::Integer) = V()
site_energy_d(V::OneBody, at::AbstractAtoms{T}, i0::Integer) where {T} =
zeros(JVec{T}, length(at))
Dict(V::OneBody) = Dict("__id__" => "OneBody", "E0" => V.E0)
OneBody(D::Dict) = OneBody(D["E0"])
convert(::Val{:OneBody}, D::Dict) = OneBody(D)
==(V1::OneBody, V2::OneBody) = (V1.E0 == V2.E0)
import Base: *
*(c::Real, V::OneBody) = OneBody(V.E0 * c)
*(V::OneBody, c::Real) = c * V
"""
`mutable struct MOneBody{T} <: NBodyFunction{1}`
this should not normally be constructed by a user, but instead E0 should be
passed to the relevant lsq functions, which will construct it.
This structure deals with multi-species configurations.
"""
mutable struct MOneBody{T} <: AbstractCalculator
E0::Dict{Symbol, T}
end
@pot MOneBody
evaluate(V::MOneBody,sp) = V.E0[sp]
function site_energies(V::MOneBody{T}, at::AbstractAtoms) where {T}
E = zeros(T, length(at))
for i in 1:length(at)
E[i] = V(chemical_symbols(at)[i])
end
return E
end
energy(V::MOneBody, at::AbstractAtoms) = sum(site_energies(V,at))
forces(V::MOneBody, at::AbstractAtoms{T}) where {T} = zeros(JVec{T}, length(at))
virial(V::MOneBody, at::AbstractAtoms{T}) where {T} = zero(JMat{T})
Dict(V::MOneBody) = Dict("__id__" => "MOneBody", "E0" => V.E0)
function convert_str_2_symb(D::Dict{String,T}) where {T}
Dout = Dict{Symbol,T}()
for key in keys(D)
Dout[Symbol(key)] = D[key]
end
return Dout
end
convert_str_2_symb(D::Dict{Symbol,T}) where {T} = D #already in the correct form
MOneBody(D::Dict{String, T}) where {T} = MOneBody(convert_str_2_symb(D["E0"]))
convert(::Val{:MOneBody}, D::Dict) = MOneBody(convert_str_2_symb(D["E0"]))
==(V1::MOneBody, V2::MOneBody) = (V1.E0 == V2.E0)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 8125 | # included from Potentials.jl
# part of the module JuLIP.Potentials
using JuLIP: JVec, JMat, neighbourlist
using LinearAlgebra: I
using JuLIP.Chemistry: atomic_number
using NeighbourLists
export ZeroPairPotential, PairSitePotential, ZBLPotential,
LennardJones, lennardjones,
Morse, morse
## TODO: kill this one?
grad(V::PairPotential, r::Real, R::JVec) = ((@D V(r)) / r) * R
evaluate!(tmp, V::PairPotential, r::Union{Number, JVec}) = V(r)
evaluate_d!(tmp, V::PairPotential, r::Union{Number, JVec}) = @D V(r)
evaluate_dd!(tmp, V::PairPotential, r::Union{Number, JVec}) = @DD V(r)
function evaluate!(tmp, V::PairPotential, R::AbstractVector{JVec{T}}) where {T}
Es = zero(T)
for i = 1:length(R)
Es += T(0.5) * evaluate!(tmp, V, norm(R[i]))
end
return Es
end
function evaluate_d!(dEs, tmp, V::PairPotential, R::AbstractVector{JVec{T}}) where {T}
for i = 1:length(R)
r = norm(R[i])
dEs[i] = (T(0.5) * evaluate_d!(tmp, V, r) / r) * R[i]
end
return dEs
end
function evaluate_dd!(hEs, tmp, V::PairPotential, R::AbstractVector{<: JVec})
n = length(R)
for i = 1:n
hEs[i,i] = 0.5 * _hess!(tmp, V, norm(R[i]), R[i])
end
return hEs
end
function _hess!(tmp, V::PairPotential, r::Number, R::JVec)
R̂ = R/r
P = R̂ * R̂'
dV = evaluate_d!(tmp, V, r) / r
ddV = evaluate_dd!(tmp, V, r)
return (ddV - dV) * P + dV * I
end
function precon!(hEs, tmp, V::PairPotential, R::AbstractVector{<: JVec}, innerstab=T(0.0))
n = length(R)
for i = 1:n
hEs[i,i] = precon!(tmp, V, norm(R[i]), R[i], innerstab)
end
return hEs
end
# an FF preconditioner for pair potentials
function precon!(tmp, V::PairPotential, r::T, R::JVec{T}, innerstab=T(0.1)
) where {T <: Number}
r = norm(R)
dV = evaluate_d!(tmp, V, r)
ddV = evaluate_dd!(tmp, V, r)
R̂ = R/r
return (1-innerstab) * (abs(ddV) * R̂ * R̂' + abs(dV / r) * (I - R̂ * R̂')) +
innerstab * (abs(ddV) + abs(dV / r)) * I
end
"""
`LennardJones(σ, e0):` constructs the 6-12 Lennard-Jones potential [wiki](https://en.wikipedia.org/wiki/Lennard-Jones_potential)
e0 * 4 * ( (σ/r)¹² - (σ/r)⁶ )
Constructor with kw arguments: `LennardJones(; kwargs...)`
* `e0, σ` : standard LJ parameters, default `e0 = 1.0, σ = 1.0`
* `r0` : equilibrium distance - if `r0` is specified then `σ` is ignored
* `a0` : FCC lattice parameter, if `a0` is specified then `σ` is ignored
(`r0, a0` cannot both be specified at the same time)
"""
LennardJones(σ, e0) = (@analytic r -> e0 * 4.0 * ((σ/r)^(12) - (σ/r)^(6)))
function ljparams(; σ=1.0, e0=1.0, r0 = nothing, a0 = nothing)
if r0 != nothing && a0 != nothing
error("`LenndardJones`: cannot specify both `r0` and `a0`")
end
if a0 != nothing # r0 = nn-dist = a0/sqrt(2) in FCC
r0 = a0 / sqrt(2)
end
if r0 != nothing # standard LJ is minimised at r = 2^(1/6)
σ = r0 / 2^(1/6)
end
return σ, e0
end
LennardJones(; kwargs...) = LennardJones(ljparams(;kwargs...)...)
"""
`lennardjones(; kwargs...)`
simplified constructor for `LennardJones` (note this is type unstable!)
In addition to the `kwargs` of `LennardJones`, this accepts also
* `rcut` : default `:auto` which gives `rcut = (1.9*σ, 2.7*σ)`. Use
`nothing` or `Inf` to specify no cutoff, or specify a tuple or
array with two elements specifying the lower and upper cut-off radii to be
used with `SplineCutoff`.
"""
function lennardjones(; rcut = :auto, kwargs...)
σ, e0 = ljparams(; kwargs...)
if (rcut == nothing || rcut == Inf)
return LennardJones(σ, e0)
elseif rcut == :auto
rcut = (1.9*σ, 2.7*σ)
end
return SplineCutoff(rcut[1], rcut[2]) * LennardJones(σ, e0)
end
"""
`Morse(A, e0, r0)` or `Morse(;A=4.0, e0=1.0, r0=1.0)`: constructs a
`PairPotential` for
```
e0 ( exp( -2 A (r/r0 - 1) ) - 2 exp( - A (r/r0 - 1) ) )
```
"""
Morse(A, e0, r0) = @analytic(
r -> e0 * ( exp(-(2.0*A) * (r/r0 - 1.0)) - 2.0 * exp(-A * (r/r0 - 1.0)) ) )
Morse(;A=4.0, e0=1.0, r0=1.0) = Morse(A, e0, r0)
"""
`morse(A=4.0, e0=1.0, r0=1.0, rcut=(1.9*r0, 2.7*r0))`
simplified constructor for `Morse` (type unstable)
"""
morse(;A=4.0, e0=1.0, r0=1.0, rcut=(1.9*r0, 2.7*r0)) = (
(rcut == nothing || rcut == Inf)
? Morse(A, e0, r0)
: SplineCutoff(rcut[1], rcut[2]) * Morse(A, e0, r0) )
"""
`ZeroPairPotential()`: creates a potential that just returns zero
"""
struct ZeroPairPotential <: PairPotential end
@pot ZeroPairPotential
evaluate(p::ZeroPairPotential, r::T) where {T <: Number} = T(0.0)
evaluate_d(p::ZeroPairPotential, r::T) where {T <: Number} = T(0.0)
evaluate_dd(p::ZeroPairPotential, r::T) where {T <: Number} = T(0.0)
cutoff(p::ZeroPairPotential) = Bool(0) # the weakest number type
# ------------------------------------------------------------------------
# TODO: write more docs + tests for ZBL
"""
Implementation of the ZBL potential to model close approach.
"""
struct ZBLPotential{TV} <: PairPotential
Z1::Int
Z2::Int
V::TV # analytic
end
@pot ZBLPotential
evaluate(V::ZBLPotential, r::Number) = evaluate(V.V, r::Number)
evaluate_d(V::ZBLPotential, r::Number) = evaluate_d(V.V, r::Number)
cutoff(::ZBLPotential) = Inf
ZBLPotential(Z1::Integer, Z2::Integer) =
let Z1=Z1, Z2=Z2
au = 0.8854 * 0.529 / (Z1^0.23 + Z2^0.23)
ϵ0 = 0.00552634940621
C = Z1*Z2/(4*π*ϵ0)
E1, E2, E3, E4 = 0.1818, 0.5099, 0.2802, 0.02817
A1, A2, A3, A4 = 3.2/au, 0.9423/au, 0.4028/au, 0.2016/au
V = @analytic(r -> C * (E1*exp(-A1*r) + E2*exp(-A2*r) +
E3*exp(-A4*r) + E4*exp(-A4*r) ) / r)
ZBLPotential(Z1, Z2, V)
end
ZBLPotential(Z::Integer) = ZBLPotential(Z, Z)
ZBLPotential(s1::Symbol, s2::Symbol) = ZBLPotential(atomic_number(s1), atomic_number(s2))
ZBLPotential(s::Symbol) = ZBLPotential(s, s)
Dict(V::ZBLPotential) = Dict("__id__" => "JuLIP_ZBLPotential",
"Z1" => V.Z1,
"Z2" => Z.Z2)
ZBLPotential(D::Dict) = ZBLPotential(D["Z1"], D["Z2"])
Base.convert(::Val{:JuLIP_ZBLPotential}, D::Dict) = ZBLPotential(D)
# ====================================================================
# A product of two pair potentials: primarily used for cutoff mechanisms
"product of two pair potentials"
mutable struct ProdPot{P1, P2} <: PairPotential
p1::P1
p2::P2
end
@pot ProdPot
import Base.*
*(p1::PairPotential, p2::PairPotential) = ProdPot(p1, p2)
@inline evaluate(p::ProdPot, r::Number) = p.p1(r) * p.p2(r)
evaluate_d(p::ProdPot, r::Number) = (p.p1(r) * (@D p.p2(r)) + (@D p.p1(r)) * p.p2(r))
evaluate_dd(p::ProdPot, r::Number) = (p.p1(r) * (@DD p.p2(r)) +
2 * (@D p.p1(r)) * (@D p.p2(r)) + (@DD p.p1(r)) * p.p2(r))
cutoff(p::ProdPot) = min(cutoff(p.p1), cutoff(p.p2))
# ====================================================================
"""
`struct WrappedPairPotential`
wraps a pairpotential using `FunctionWrappers` in order to allow
type-stable storage of multiple potentials. This is the main technique
required at the moment to work with multi-component systems.
Otherwise, this is not advisable since it disables a range of
possible compiler optimisations.
"""
struct WrappedPairPotential <: SimplePairPotential
f::F64fun
f_d::F64fun
f_dd::F64fun
rcut::Float64
end
@pot WrappedPairPotential
cutoff(V::WrappedPairPotential) = V.rcut
# evaluate, etc are all derived from SimplePairPotential
function WrappedPairPotential(V::AnalyticFunction, rcut)
@assert (0 < rcut < Inf)
f, f_d, f_dd = let V=V, rc = rcut
(F64fun(r -> evaluate(V, r) * (r<rc)),
F64fun(r -> evaluate_d(V, r) * (r<rc)),
F64fun(r -> evaluate_dd(V, r) * (r<rc)))
end
return WrappedPairPotential(f, f_d, f_dd, cutoff(V))
end
function WrappedPairPotential(V::PairPotential)
@assert (0 < cutoff(V) < Inf)
f, f_d, f_dd = let V=V, rc = cutoff(V)
(F64fun(r -> evaluate(V, r) * (r<rc)),
F64fun(r -> evaluate_d(V, r) * (r<rc)),
F64fun(r -> evaluate_dd(V, r) * (r<rc)))
end
return WrappedPairPotential(f, f_d, f_dd, cutoff(V))
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2792 |
export @D, @DD, @GRAD, @pot
# ===========================================================================
# implement some fun little macros for easier access
# to the potentials
# ===========================================================================
# REMARK on @pot:
# ---------------
# Julia 0.4 version:
# call(pp::Potential, varargs...) = evaluate(pp, varargs...)
# call(pp::Potential, ::Type{Val{:D}}, varargs...) = evaluate_d(pp, varargs...)
# call(pp::Potential, ::Type{Val{:DD}}, varargs...) = evaluate_dd(pp, varargs...)
# call(pp::Potential, ::Type{Val{:GRAD}}, varargs...) = grad(pp, varargs...)
# unfortunately, in 0.5 `call` doesn't take anabstractargument anymore,
# which means that we need to specify for every potential how to
# create this syntactic sugar. This is what `@pot` is for.
"""
Annotate a type with `@pot` to setup the syntax sugar
for `evaluate, evaluate_d, evaluate_dd, grad`.
## Usage:
For example, the declaration
```julia
"documentation for `LennardJones`"
mutable struct LennardJones <: PairPotential
r0::Float64
end
@pot LennardJones
```
creates the following aliases:
```julia
lj = LennardJones(1.0)
lj(args...) = evaluate(lj, args...)
@D lj(args...) = evaluate_d(lj, args...)
@DD lj(args...) = evaluate_dd(lj, args...)
@GRAD lj(args...) = grad(lj, args...)
```
Usage of `@pot` is not restricted to pair potentials, but can be applied to
*any* type.
"""
macro pot(fsig)
@assert fsig isa Symbol
sym = esc(:x)
tsym = esc(fsig)
quote
@inline ($sym::$tsym)(args...) = evaluate($sym, args...)
@inline ($sym::$tsym)(::Type{Val{:D}}, args...) = evaluate_d($sym, args...)
@inline ($sym::$tsym)(::Type{Val{:DD}}, args...) = evaluate_dd($sym, args...)
@inline ($sym::$tsym)(::Type{Val{:GRAD}}, args...) = grad($sym, args...)
end
end
# --------------------------------------------------------------------------
# next create macros that translate
"""
`@D`: Use to evaluate the derivative of a potential. E.g., to compute the
Lennard-Jones potential,
```julia
lj = LennardJones()
r = 1.0 + rand(10)
ϕ = lj(r)
ϕ' = @D lj(r)
```
see also `@DD`.
"""
macro D(fsig::Expr)
@assert fsig.head == :call
insert!(fsig.args, 2, Val{:D})
for n = 1:length(fsig.args)
fsig.args[n] = esc(fsig.args[n])
end
return fsig
end
"`@DD` : analogous to `@D`"
macro DD(fsig::Expr)
@assert fsig.head == :call
for n = 1:length(fsig.args)
fsig.args[n] = esc(fsig.args[n])
end
insert!(fsig.args, 2, Val{:DD})
return fsig
end
"`@GRAD` : analogous to `@D`, but escapes to `grad`"
macro GRAD(fsig::Expr)
@assert fsig.head == :call
for n = 1:length(fsig.args)
fsig.args[n] = esc(fsig.args[n])
end
insert!(fsig.args, 2, Val{:GRAD})
return fsig
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 7856 |
module Preconditioners
using AlgebraicMultigrid
using JuLIP: AbstractAtoms, Dofs, maxdist,
cutoff, positions, forces, mat, vecs,
set_positions!, chemical_symbols, rnn, JVec, JMat ,
AbstractCalculator, calculator, cell,
fixedcell, projectxfree, _pos_to_dof
using JuLIP.Potentials: @pot, @analytic, evaluate, evaluate_d, PairPotential, HS,
SitePotential, sites, C0Shift, _precon_or_hessian_pos
using SparseArrays: SparseMatrixCSC
using LinearAlgebra: cholesky, I, Symmetric, norm
import SuiteSparse
import JuLIP: update!
import JuLIP.Potentials: precon!, cutoff
import Base: *, \, size
import LinearAlgebra: ldiv!, mul!, dot
export Exp, FF
"""
`IPPrecon`: the standard preconditioner type for JuLIP
`IPPrecon` stores a field `p <: AbstractCalculator` which is
should implement `precon(p, r, R)` which is a block matrix analogue of
`hess(p, r, R)` and is used to assemble the preconditioner matrix via
```julia
precon_matrix(P, at::AbstractAtoms)
```
If `p` should be updated in response to an update of `at` then
the type can overload `JuLIP.Preconditioners.update_inner!`.
## Constructor:
```
IPPrecon(p::AbstractCalculator, at::AbstractAtoms; kwargs...)
```
## Keyword arguments:
* `updatedist`: determines after how much movement of the atoms, the
preconditioner is updated
* `tol`: solver tolerance if AMG is used
* `updatefreq`: after how many iterations do we force an update {10}
* `stab`: stabilisation constant {0.01}, add `stab * I` to `P`
* `solve`: which solver to used, `:amg` or `:chol`, default is `:amg`
"""
mutable struct IPPrecon{TV, TS, T <: AbstractFloat, TI <: Integer}
p::TV
solver::TS
A::SparseMatrixCSC{T, TI}
oldX::Vector{JVec{T}}
updatedist::T
tol::T
updatefreq::TI
skippedupdates::TI
stab::T
innerstab::T
end
function IPPrecon(p, at::AbstractAtoms;
updatedist=0.2 * rnn(at), tol=1e-7, updatefreq=10, stab=0.01,
solver = :chol, innerstab=0.0)
# make sure we don't use this in a context it is not intended for!
@assert fixedcell(at)
A = AlgebraicMultigrid.poisson(12)
if solver == :amg
solver = ruge_stuben(A)
elseif solver in [:chol, :direct]
solver = cholesky(A)
else
error("`IPPrecon` : unknown solver $(solver)")
end
P = IPPrecon(p, solver, A, positions(at), updatedist, tol, updatefreq, 0, stab, innerstab)
# the force_update! makes the first assembly pass.
return force_update!(P, at)
end
# some standard Base functionality lifted to IPPrecon
ldiv!(out::Dofs, P::IPPrecon{TV, TS}, f::Dofs) where TV where TS <: AlgebraicMultigrid.MultiLevel =
copyto!(out, solve(P.solver, f, 200, AlgebraicMultigrid.V(), P.tol))
ldiv!(out::Dofs, P::IPPrecon{TV, TS}, f::Dofs) where TV where TS <: SuiteSparse.CHOLMOD.Factor =
copyto!(out, P.solver \ f)
mul!(out::Dofs, P::IPPrecon, x::Dofs) = mul!(out, P.A, x)
dot(x, P::IPPrecon, y) = dot(x, P * y)
*(P::IPPrecon, x::AbstractVector) = P.A * x
\(P::IPPrecon, x::AbstractVector) = ldiv!(zeros(length(x)), P, x)
Base.size(P::IPPrecon) = size(P.A)
need_update(P::IPPrecon, at::AbstractAtoms) =
(P.skippedupdates > P.updatefreq) ||
(maxdist(positions(at), P.oldX) >= P.updatedist)
update!(P::IPPrecon, at::AbstractAtoms) =
need_update(P, at) ? force_update!(P, at) : (P.skippedupdates += 1; P)
update_solver!(P::IPPrecon{TV, TS}) where TV where TS <: SuiteSparse.CHOLMOD.Factor =
cholesky(Symmetric(P.A))
update_solver!(P::IPPrecon{TV, TS}) where TV where TS <: AlgebraicMultigrid.MultiLevel =
ruge_stuben(P.A)
function force_update!(P::IPPrecon, at::AbstractAtoms)
# perform updates of the potential p (if needed; usually not)
P.p = update_inner!(P.p, at)
# construct the preconditioner matrix ...
Pmat = precon_matrix(P.p, at, P.innerstab)
Pmat = Pmat + P.stab * I
Pmat = projectxfree(at, Pmat)
# and the AMG solver
P.A = Pmat
P.solver = update_solver!(P)
# remember the atom positions
copyto!(P.oldX, positions(at))
# and remember that we just did a full update
P.skippedupdates = 0
return P
end
# ============== Implementation of some concrete types ======================
# default implementation of update_inner!;
# most of the time no inner update is required
"update `IPPrecon.p`, must return updated `p`"
update_inner!(p::Any, at::AbstractAtoms) = p
"return the three linear indices associated with an atom index"
atind2lininds(i::Integer) = (i-1) * 3 + [1;2;3]
"""
build the preconditioner matrix associated with the potential V
"""
precon_matrix(V, at::AbstractAtoms, innerstab = 0.1;
preconmap = (hEs, tmp, V, R) -> precon!(hEs, tmp, V, R, innerstab)) =
_pos_to_dof(_precon_or_hessian_pos(V, at, preconmap), at)
"""
A variant of the `Exp` preconditioner; see
### Constructor: `Exp(at::AbstractAtoms)`
Keyword arguments:
* `A`: stiffness of potential {default 3.0}
* `r0`: nn distance estimate {default is an automicatic estimate}
* `cutoff_mult`: cut-off is `r0 * cutoff_mult` {default 2.2}
* `kwargs...`: `IPPrecon` parameters
### Reference
D. Packwood, J. Kermode, L. Mones, N. Bernstein, J. Woolley, N. I. M. Gould,
C. Ortner, and G. Csanyi. A universal preconditioner for simulating condensed
phase materials. J. Chem. Phys., 144, 2016.
"""
mutable struct Exp{T, TV}
Vexp::TV
energyscale::T
end
cutoff(P::Exp) = cutoff(P.Vexp)
function precon!(hEs, tmp, P::Exp{T}, R::AbstractVector{<: JVec}, innerstab=0) where {T}
n = length(R)
for i = 1:n
hEs[i,i] = (P.energyscale * P.Vexp(norm(R[i]))+innerstab) * one(JMat{T})
end
return hEs
end
function Exp(at::AbstractAtoms{T};
A=T(3.0), r0=rnn(at), cutoff_mult=T(2.2), energyscale = T(1.0),
kwargs...) where {T}
e0 = energyscale == :auto ? T(1.0) : energyscale
rcut = r0 * cutoff_mult
Vexp = let A=A, r0=r0
@analytic r -> exp( - A * (r/r0 - 1))
end * C0Shift(rcut)
P = IPPrecon(Exp(Vexp, e0), at; kwargs...)
if energyscale == :auto
P.p.energyscale = estimate_energyscale(at, P)
force_update!(P, at)
end
return P
end
# want μ * <P v, v> ~ <∇E(x+hv) - ∇E(x), v> / h
function estimate_energyscale(at::AbstractAtoms{T}, P) where {T}
# get the P-matrix at current configuration
A = precon_matrix(P.p, at)
# determine direction in which the cell is maximal
F = Matrix(cell(at)')
X0 = positions(at)
_, i = maximum( (norm(F[:, j]), j) for j = 1:3 ) # hack to make findmax work again
Fi = JVec{T}(F[:, i])
# an associated perturbation
V = [sin(2*pi * dot(Fi, x)/dot(Fi,Fi)) * Fi for x in X0]
# compute gradient at current positions
f0 = forces(at) |> mat
# compute gradient at perturbed positions
h = 1e-3
set_positions!(at, X0 + h * V)
f1 = forces(at) |> mat
# return the estimated value for the energyscale
V = mat(V)
μ = - dot((f1 - f0)/h, V) / dot(A * V[:], V[:])
if μ < 0.1 || μ > 100.0
warn("""
e0 = $(μ) in `estimate_energyscale`; this is likely due to a poor
starting guess in an optimisation, probably best to set the
energyscale manually, or use CG instead of LBFGS.
""")
end
return μ
end
"""
`FF`: defines a preconditioner based on a force-field; implementation
is close to the paper where this idea is described:
Preconditioners for the geometry optimisation and saddle point search of
molecular systems; Letif Mones, Christoph Ortner & Gábor Csányi;
Scientific Reports 8, Article number: 13991 (2018)
Each potential has to define a `precon` method from which the preconditioner
is build.
"""
FF(at::AbstractAtoms, V::AbstractCalculator; kwargs...) =
IPPrecon(V, at; kwargs...)
FF(at::AbstractAtoms; kwargs...) =
FF(at, calculator(at); kwargs...)
end # end module Preconditioners
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2919 | #
# implementation of Spline-based pair potentials
# and other functionality
#
import Dierckx
using Dierckx: Spline1D
# https://github.com/kbarbary/Dierckx.jl
"""
`type SplinePairPotential`
Pair potential defined via splines. In the construction of these splines
atomic units (Angstrom) are assumed. If this is used in different units,
then something will probably break.
### Constructors:
```
SplinePairPotential(xdat, ydat; kwargs...) # fit spline from data points
SplinePairPotential(fname; kwargs...) # load data points from file
```
Keyword arguments:
* `s = 1e-2`: balances smoothness versus fit; basically an error bound, see Dierckx website for more info
* `fixcutoff = true`: if true, then the fit will be artificially modified at the cut-off to ensure that the transition to zero is smooth
* `order = 3`: can use lower or higher order splines (0 <= order <= 5) but only 3 is tested
* `w = (1.0 + ydat).^(-2)`: this gives relative weights to datapoints to ensure a good in the important regions; the intuition behind the default choice is that is prevents overfitting at very high energies which are not physical anyhow, but ensure that sufficient data points are used in the low energy region.
"""
mutable struct SplinePairPotential <: PairPotential
spl::Spline1D # The actual spline object
rcut::Float64 # cutoff radius (??? could just use spl.t[end] ???)
wrk::Vector{Float64} # a work array for faster evaluation of derivatives
end
@pot SplinePairPotential
SplinePairPotential(spl::Spline1D) =
SplinePairPotential(spl, maximum(spl.t), Vector{Float64}(undef, length(spl.t)))
cutoff(V::SplinePairPotential) = V.rcut
evaluate(V::SplinePairPotential, r::Number) = V.spl(r)
evaluate_d(V::SplinePairPotential, r::Number) = _deriv(V, r, 1)
evaluate_dd(V::SplinePairPotential, r::Number) = _deriv(V, r, 2)
_deriv(V::SplinePairPotential, r, nu) =
Dierckx.derivative(V.spl, r, nu)
function SplinePairPotential(xdat, ydat; s = 1e-2, fixcutoff=true, order=3,
w = (1.0 .+ abs.(ydat)).^(-2))
# this creates a "fit" with s determining the balance between smoothness
# and fitting the data (basically an error bound)
spl = Spline1D(xdat, ydat; bc = "zero", s = s, k = order, w = w)
# set the last few spline data-points to 0 to get a guaranteed
# smooth transition to 0 at the cutoff.
if fixcutoff
spl.c[end-order+1:end] .= 0.0
end
return SplinePairPotential(spl)
end
SplinePairPotential(fname::AbstractString; kwargs...) =
SplinePairPotential(load_ppfile(fname)...; kwargs...)
function load_ppfile(fname::AbstractString)
if fname[end-3:end] == ".plt"
return load_plt(fname)
else
error("unknown file type: $(fname[end-3:end])")
end
nothing
end
function load_plt(fname::AbstractString)
data = readdlm(fname, Float64; comments=true)
return data[:, 1], data[:, 2]
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 7788 | # NOTE: this is a quick and dirty implementation of the Stillinger-Weber model;
# in the future it will be good to do this more elegantly / more efficiently
# there is huge overhead in this code that can be
# significantly improved in terms of performance, but for now we just
# want a correct and readable code
# [Stillinger/Weber, PRB 1985]
# ---------------------------------------------------
# v2 = ϵ f2(r_ij / σ); f2(r) = A (B r^{-p} - r^{-q}) exp( (r-a)^{-1} )
# v3 = ϵ f3(ri/σ, rj/σ, rk/σ); f3 = h(rij, rij, Θjik) + ... + ...
# h(rij, rik, Θjik) = λ exp[ γ (rij-a)^{-1} + γ (rik-a)^{-1} ] * (cosΘjik+1/3)^2
# >>>
# V2 = 0.5 * ϵ * A (B r^{-p} - r^{-q}) * exp( (r-a)^{-1} )
# V3 = √ϵ * λ exp[ γ (r-a)^{-1} ]
#
# Parameters from QUIP database:
# -------------------------------
# <per_pair_data atnum_i="14" atnum_j="14" AA="7.049556277" BB="0.6022245584"
# p="4" q="0" a="1.80" sigma="2.0951" eps="2.1675" />
# <per_triplet_data atnum_c="14" atnum_j="14" atnum_k="14" lambda="21.0"
# gamma="1.20" eps="2.1675" />
using ForwardDiff
using LinearAlgebra: dot
using JuLIP: JVecF
export StillingerWeber
"""
`bondangle(S1, S2) -> (dot(S1, S2) + 1.0/3.0)^2`
* not this assumes that `S1, S2` are normalised
* see `bondangle_d` for the derivative
"""
bondangle(S1, S2) = (dot(S1, S2) + 1.0/3.0)^2
"""
`b := bondangle(S1, S2)` then
`bondangle_d(S1, S2, r1, r2) -> b, db1, db2`
where `dbi` is the derivative of `b` w.r.t. `Ri` where `Si= Ri/ri`.
"""
function bondangle_d(S1, S2, r1, r2)
d = dot(S1, S2)
b1 = (1.0/r1) * S2 - (d/r1) * S1
b2 = (1.0/r2) * S1 - (d/r2) * S2
return (d+1.0/3.0)^2, 2.0*(d+1.0/3.0)*b1, 2.0*(d+1.0/3.0)*b2
end
function _ad_bondangle_(R)
R1, R2 = R[1:3], R[4:6]
r1, r2 = norm(R1), norm(R2)
return bondangle(R1/r1, R2/r2)
end
# TODO: need a faster implementation of bondangle_dd
function bondangle_dd(R1, R2)
R = [R1; R2]
hh = ForwardDiff.hessian(_ad_bondangle_, R)
h = zeros(JMatF, 2,2)
h[1,1] = JMatF(hh[1:3,1:3])
h[1,2] = JMatF(hh[1:3, 4:6])
h[2,1] = JMatF(hh[4:6,1:3])
h[2,2] = JMatF(hh[4:6, 4:6])
return h
end
"""
Stillinger-Weber potential with parameters for Si.
Functional form and default parameters match the original SW potential
from [Stillinger/Weber, PRB 1985].
The `StillingerWeber` type can also by "abused" to generate arbitrary
bond-angle potentials of the form
∑_{i,j} V2(rij) + ∑_{i,j,k} V3(rij) V3(rik) (cos Θijk + 1/3)^2
Constructor admits the following key-word parameters:
`ϵ=2.1675, σ = 2.0951, A=7.049556277, B=0.6022245584,
p = 4, a = 1.8, λ=21.0, γ=1.20`
which enter the potential as follows:
```
V2(r) = 0.5 * ϵ * A * (B * (r/σ)^(-p) - 1.0) * exp(1.0 / (r/σ - a))
V3(r) = sqrt(ϵ * λ) * exp(γ / (r/σ - a))
```
"""
struct StillingerWeber{P1,P2} <: SitePotential
V2::P1
V3::P2
end
@pot StillingerWeber
cutoff(calc::StillingerWeber) = max(cutoff(calc.V2), cutoff(calc.V3))
function StillingerWeber(; brittle = false,
ϵ=2.1675, σ = 2.0951, A=7.049556277, B=0.6022245584,
p = 4, a = 1.8, λ = brittle ? 42.0 : 21.0, γ=1.20 )
cutoff = a*σ-1e-2
V2 = @analytic(r -> (ϵ*A) * (B*(r/σ)^(-p) - 1.0) * exp(1.0/(r/σ - a))) *
HS(cutoff)
V3 = @analytic(r -> sqrt(ϵ * λ) * exp( γ / (r/σ - a) )) * HS(cutoff)
return StillingerWeber(V2, V3)
end
alloc_temp(V::StillingerWeber, N::Integer) =
( R = zeros(JVecF, N),
S = zeros(JVecF, N),
V3 = zeros(Float64, N) )
function evaluate!(tmp, calc::StillingerWeber, R)
Es = 0.0
# three-body contributions
for i = 1:length(R)
r = norm(R[i])
tmp.S[i] = R[i] / r
tmp.V3[i] = calc.V3(r)
Es += 0.5 * calc.V2(r)
end
for i1 = 1:(length(R)-1), i2 = (i1+1):length(R)
Es += tmp.V3[i1] * tmp.V3[i2] * bondangle(tmp.S[i1], tmp.S[i2])
end
return Es
end
alloc_temp_d(V::StillingerWeber, N::Integer, T = Float64) =
( dV = zeros(JVec{T}, N),
R = zeros(JVecF, N),
r = zeros(T, N),
S = zeros(JVec{T}, N),
V3 = zeros(T, N),
gV3 = zeros(JVec{T}, N) )
alloc_temp_dd(V::StillingerWeber, N::Integer) =
( r = zeros(Float64, N),
S = zeros(JVecF, N),
V3 = zeros(Float64, N),
gV3 = zeros(JVecF, N) )
function evaluate_d!(dEs, tmp, calc::StillingerWeber, R::AbstractVector{<:JVec})
for i = 1:length(R)
tmp.r[i] = r = norm(R[i])
tmp.S[i] = R[i] / r
tmp.V3[i] = calc.V3(r)
tmp.gV3[i] = grad(calc.V3, r, R[i])
dEs[i] = 0.5 * grad(calc.V2, r, R[i])
end
for i1 = 1:(length(R)-1), i2 = (i1+1):length(R)
a, b1, b2 = bondangle_d(tmp.S[i1], tmp.S[i2], tmp.r[i1], tmp.r[i2])
dEs[i1] += (tmp.V3[i1] * tmp.V3[i2]) * b1 + (tmp.V3[i2] * a) * tmp.gV3[i1]
dEs[i2] += (tmp.V3[i1] * tmp.V3[i2]) * b2 + (tmp.V3[i1] * a) * tmp.gV3[i2]
end
return dEs
end
function _ad_dV(V::StillingerWeber, R_dofs)
R = vecs( reshape(R_dofs, 3, length(R_dofs) ÷ 3) )
r = norm.(R)
dV = zeros(eltype(R), length(R))
tmpd = alloc_temp_d(V, length(R), eltype(R[1]))
evaluate_d!(dV, tmpd, V, R)
return mat(dV)[:]
end
function _ad_ddV!(hEs, V::StillingerWeber, R::AbstractVector{JVec{T}}) where {T}
ddV = ForwardDiff.jacobian( Rdofs -> _ad_dV(V, Rdofs), mat(R)[:] )
# convert into a block-format
n = length(R)
for i = 1:n, j = 1:n
hEs[i, j] = ddV[ ((i-1)*3).+(1:3), ((j-1)*3).+(1:3) ]
end
return hEs
end
evaluate_dd!(hEs, tmp, V::StillingerWeber, R) = _ad_ddV!(hEs, V, R)
# function hess(V::StillingerWeber, r, R)
# n = length(r)
# hV = zeros(JMatF, n, n)
#
# # two-body contributions
# for (i, (r_i, R_i)) in enumerate(zip(r, R))
# hV[i,i] += hess(V.V2, r_i, R_i)
# end
#
# # three-body terms
# S = [ R1/r1 for (R1,r1) in zip(R, r) ]
# V3 = [ V.V3(r1) for r1 in r ]
# dV3 = [ grad(V.V3, r1, R1) for (r1, R1) in zip(r, R) ]
# hV3 = [ hess(V.V3, r1, R1) for (r1, R1) in zip(r, R) ]
#
# for i1 = 1:(length(r)-1), i2 = (i1+1):length(r)
# # Es += V3[i1] * V3[i2] * bondangle(S[i1], S[i2])
# # precompute quantities
# ψ, Dψ_i1, Dψ_i2 = bondangle_d(S[i1], S[i2], r[i1], r[i2])
# Hψ = bondangle_dd(R[i1], R[i2]) # <<<< this should be SLOW (AD)
# # assemble local hessian contributions
# hV[i1,i1] +=
# hV3[i1] * V3[i2] * ψ + dV3[i1] * V3[i2] * Dψ_i1' +
# Dψ_i1 * V3[i2] * dV3[i1]' + V3[i1] * V3[i2] * Hψ[1,1]
# hV[i2,i2] +=
# V3[i2] * hV3[i2] * ψ + V3[i1] * dV3[i2] * Dψ_i2' +
# Dψ_i2 * V3[i1] * dV3[i2]' + V3[i1] * V3[i2] * Hψ[2,2]
# hV[i1,i2] +=
# dV3[i1] * dV3[i2]' * ψ + V3[i1] * Dψ_i1 * dV3[i2]' +
# dV3[i1] * V3[i2] * Dψ_i2' + V3[i1] * V3[i2] * Hψ[1,2]
# hV[i2, i1] +=
# dV3[i2] * dV3[i1]' * ψ + V3[i1] * Dψ_i2 * dV3[i1]' +
# dV3[i2] * V3[i1] * Dψ_i1' + V3[i1] * V3[i2] * Hψ[2,1]
# end
# return hV
# end
function precon!(hEs, tmp, V::StillingerWeber, R::AbstractVector{JVec{T}}, innerstab=0.0
) where {T}
n = length(R)
r = tmp.r
V3 = tmp.V3
S = tmp.S
# two-body contributions
for (i, R1) in enumerate(R)
r[i] = norm(R1)
V3[i] = V.V3(r[i])
S[i] = R1 / r[i]
hEs[i,i] += precon!(nothing, V.V2, r[i], R1)
end
# three-body terms
for i1 = 1:(n-1), i2 = (i1+1):n
Θ = dot(S[i1], S[i2])
dΘ1 = (T(1.0)/r[i1]) * S[i2] - (Θ/r[i1]) * S[i1]
dΘ2 = (T(1.0)/r[i2]) * S[i1] - (Θ/r[i2]) * S[i2]
# ψ = (Θ + 1/3)^2, ψ' = (Θ + 1/3), ψ'' = 2.0
a = abs((V3[i1] * V3[i2] * T(2.0)))
hEs[i1,i2] += a * dΘ1 * dΘ2'
hEs[i1,i1] += a * dΘ1 * dΘ1'
hEs[i2, i2] += a * dΘ2 * dΘ2'
hEs[i2, i1] += a * dΘ2 * dΘ1'
end
return hEs
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 4831 |
module Utils
import JuLIP.Chemistry: rnn
using JuLIP: AbstractAtoms, JVec, positions, set_positions!,
chemical_symbols, cell, pbc, mat, dofs, set_dofs!,
fixedcell, variablecell
using LinearAlgebra: norm
export rattle!, r_sum, r_dot,
swapxy!, swapxz!, swapyz!,
dist, displacement, rmin, wrap_pbc!
############################################################
### Some useful utility functions
############################################################
### Robust Summation and Dot Products
############################################################
# SWITCH TO KAHAN?
"Robust summation."
r_sum(a) = sum(a)
# NOTE: if I see this correctly, then r_dot allocates a temporary
# vector, which is likely quite a performance overhead.
# probably, we want to re-implement this.
"Robust inner product. Defined as `r_dot(a, b) = r_sum(a .* b)`"
r_dot(a, b) = r_sum(a[:] .* b[:])
"""
`rattle!(at::AbstractAtoms, r::Float64; rnn = 1.0, respect_constraint = true)
-> at`
randomly perturbs the atom positions
* `r`: magnitude of perturbation
* `rnn` : nearest-neighbour distance
* `respect_constraint`: set false to also perturb the constrained atom positions
"""
function rattle!(at::AbstractAtoms, r::AbstractFloat; rnn = 1.0)
# TODO: revive the respect_constraint keyword!
# respect_constraint = (constraint(at) != nothing))
# if respect_constraint
# x = dofs(at)
# x += r * rnn * 2.0/sqrt(3) * (rand(Float64, length(x)) .- 0.5)
# set_dofs!(at, x)
# else
X = positions(at) |> mat
X .+= r * rnn * 2.0/sqrt(3) * (rand(Float64, size(X)) .- 0.5)
set_positions!(at, X)
if variablecell(at)
apply_defm!(at, I + (r/rnn) * (rand(JMatF) .- 0.5))
end
return at
end
"""
swap x and y position coordinates
"""
function swapxy!(at::AbstractAtoms)
X = positions(at) |> mat
X[[2,1],:] = X[[1,2],:]
set_positions!(at, X)
return at
end
"""
swap x and z position coordinates
"""
function swapxz!(at::AbstractAtoms)
X = positions(at) |> mat
X[[3,1],:] = X[[1,3],:]
set_positions!(at, X)
return at
end
"""
swap y and z position coordinates
"""
function swapyz!(at::AbstractAtoms)
X = positions(at) |> mat
X[[3,2],:] = X[[2,3],:]
set_positions!(at, X)
return at
end
"""
`dist(at, X1, X2, p = Inf)`
`dist(at1, at2, p = Inf)`
Returns the maximum distance (p = Inf) or alternatively a p-norm of
distances between the two configurations `X1, X2` or `at1, at2`.
This implementation accounts for periodic boundary conditions (in those
coordinate directions where they are set to `true`)
"""
function dist(at::AbstractAtoms,
X1::AbstractVector{<:JVec}, X2::AbstractVector{<:JVec},
p = Inf)
@assert length(X1) == length(X2) == length(at)
F = cell(at)'
Finv = inv(F)
bcrem = [ p ? 1.0 : Inf for p in pbc(at) ]
d = [ norm(_project_pbc_(F, Finv, bcrem, x1 - x2))
for (x1, x2) in zip(X1, X2) ]
return norm(d, p)
end
dist(at::AbstractAtoms, X::AbstractVector) = dist(at, positions(at), X)
function dist(at1::AbstractAtoms, at2::AbstractAtoms, p = Inf)
@assert norm(cell(at1) - cell(at2), Inf) < 1e-14
return dist(at1, positions(at1), positions(at2), p)
end
function _project_pbc_(F, Finv, bcrem, x)
λ = Finv * x # convex coordinates
# convex coords projected to the unit
λp = JVec(rem(λ[1], bcrem[1]), rem(λ[2], bcrem[2]), rem(λ[3], bcrem[3]))
return F * λp # convert back to real coordinates
end
function _project_coord_min_(λ, p)
if !p
return λ
end
λ = mod(λ, 1.0) # project to cell
if λ > 0.5 # periodic image with minimal length
λ = λ - 1.0
end
return λ
end
function _project_pbc_min_(F, Finv, p, x)
λ = Finv * x # convex coordinates
# convex coords projected to the unit
λp = _project_coord_min_.(λ, JVec{Bool}(p...))
return F * λp # convert back to real coordinates
end
function displacement(at::AbstractAtoms,
X1::AbstractVector{<:JVec},
X2::AbstractVector{<:JVec})
@assert length(X1) == length(X2) == length(at)
F = cell(at)'
Finv = inv(F)
p = pbc(at)
U = [ _project_pbc_min_(F, Finv, p, x2-x1)
for (x1, x2) in zip(X1, X2) ]
return U
end
project_min(at, u) = _project_pbc_min_(cell(at)', inv(cell(at)'), pbc(at), u)
function rnn(at::AbstractAtoms)
syms = unique(chemical_symbols(at))
return minimum(rnn.(syms))
end
function wrap_pbc!(at)
X = positions(at)
F = cell(at)'
X = [_project_pbc_min_(F, inv(F), pbc(at), x) for x in X]
set_positions!(at, X)
end
function rmin(at::AbstractAtoms)
at2 = at * 2
X = positions(at2)
r = norm(X[1]-X[2])
for n = 1:length(X)-1, m = n+1:length(X)
r = min(r, norm(X[n]-X[m]))
end
return r
end
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.