licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.1.7 | f58443e5ffa3df2e1b28e4ac37ad5a1f25c22454 | code | 40 | using Telegrambot
using Test
@test true
| Telegrambot | https://github.com/Moelf/Telegrambot.jl.git |
|
[
"MIT"
] | 0.1.7 | f58443e5ffa3df2e1b28e4ac37ad5a1f25c22454 | docs | 2055 | # Telegrambot.jl
A Julia Telegram Bot Api wapper
[check out telegram bot api](https://core.telegram.org/bots/api) api (mostly built around commands with text).
| **Build Status** |
|:-----------------------------------------------------------------------------------------------:|
|[](https://travis-ci.org/Moelf/Telegrambot.jl)|
## Installation
The package is registered in `METADATA.jl` and can be installed with `Pkg.add`, or in `REPL` by pressing `] add Telegrambot`.
```julia
julia> Pkg.add("Telegrambot")
```
## Basic Usage
For guide on telegram bot creation and api, check [this](https://core.telegram.org/bots#3-how-do-i-create-a-bot) out.
**NOTICE**: Due to the way `botfather` present you key, don't forget to add "bot", I shall add a warning and try to be smart.
```julia
using Telegrambot
botApi = "<your_api_key>"
welcomeMsg(incoming::AbstractString, params::Dict{String,Any}) = "Welcome to my awesome bot @" * string(params["from"]["username"])
echo(incoming::AbstractString, params::Dict{String,Any}) = incoming
txtCmds = Dict()
txtCmds["repeat_msg"] = echo #this will respond to '/repeat_msg <any thing>'
txtCmds["start"] = welcomeMsg # this will respond to '/start'
txtCmdsMessage = Dict()
txtCmdsMessage["start_response"] = welcomeMsg #this will quote reply to a message respond to '/start_response'
inlineOpts = Dict() #Title, result pair
inlineOpts["Make Uppercase"] = uppercase #this will generate an pop-up named Make Uppercase and upon tapping return uppercase(<user_input>)
#uppercase is a function that takes a string and return the uppercase version of that string
startBot(botApi; textHandle = txtCmds, textHandleReplyMessage = txtCmdsMessage, inlineQueryHandle=inlineOpts)
```
## To-Do
- [x] Add Inline query respond
- [ ] Add function to quote reply to a message
- [ ] Add function to reply with a file/image
- [ ] Add function to serve as a IRC-Tg bot
| Telegrambot | https://github.com/Moelf/Telegrambot.jl.git |
|
[
"MIT"
] | 0.4.2 | 59786d90d750f1c18029a3903e8c1bc49d0e55a8 | code | 445 | # Copyright (c) 2016: Joey Huchette and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
module PiecewiseLinearOpt
using JuMP
import LinearAlgebra
import MathOptInterface as MOI
import Random
export PWLFunction, UnivariatePWLFunction, BivariatePWLFunction, piecewiselinear
include("types.jl")
include("jump.jl")
end # module
| PiecewiseLinearOpt | https://github.com/jump-dev/PiecewiseLinearOpt.jl.git |
|
[
"MIT"
] | 0.4.2 | 59786d90d750f1c18029a3903e8c1bc49d0e55a8 | code | 43093 | # Copyright (c) 2016: Joey Huchette and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
# TODO: choose method based on problem size
defaultmethod() = :Logarithmic
mutable struct PWLData
counter::Int
PWLData() = new(0)
end
function initPWL!(m::JuMP.Model)
if !haskey(m.ext, :PWL)
m.ext[:PWL] = PWLData()
end
return
end
const VarOrAff = Union{JuMP.VariableRef,JuMP.AffExpr}
function piecewiselinear(
m::JuMP.Model,
x::VarOrAff,
d,
f::Function;
method = defaultmethod(),
)
initPWL!(m)
fd = [f(xx) for xx in d]
return piecewiselinear(m, x, d, fd; method = method)
end
function piecewiselinear(
m::JuMP.Model,
x::VarOrAff,
d,
fd;
method = defaultmethod(),
)
return piecewiselinear(m, x, UnivariatePWLFunction(d, fd); method = method)
end
function piecewiselinear(
m::JuMP.Model,
x::VarOrAff,
pwl::UnivariatePWLFunction;
method = defaultmethod(),
)
initPWL!(m)
counter = m.ext[:PWL].counter
counter += 1
m.ext[:PWL].counter = counter
d = [_x[1] for _x in pwl.x]
fd = pwl.z
n = length(d)
if n != length(fd)
error(
"You provided a different number of breakpoints ($n) and function values at the breakpoints ($(length(fd)))",
)
end
if n == 0
error(
"I don't know how to handle a piecewise linear function with no breakpoints",
)
end
z = JuMP.@variable(
m,
lower_bound = minimum(fd),
upper_bound = maximum(fd),
base_name = "z_$counter"
)
if n == 1
JuMP.@constraint(m, x == d[1])
JuMP.@constraint(m, z == fd[1])
return z
end
if method == :Incremental
δ = JuMP.@variable(
m,
[1:n],
lower_bound = 0,
upper_bound = 1,
base_name = "δ_$counter"
)
y = JuMP.@variable(m, [1:n-1], Bin, base_name = "y_$counter")
JuMP.@constraint(
m,
x == d[1] + sum(δ[i] * (d[i+1] - d[i]) for i in 1:n-1)
)
JuMP.@constraint(
m,
z == fd[1] + sum(δ[i] * (fd[i+1] - fd[i]) for i in 1:n-1)
)
for i in 1:n-1
JuMP.@constraint(m, δ[i+1] ≤ y[i])
JuMP.@constraint(m, y[i] ≤ δ[i])
end
elseif method == :MC
x̂ = JuMP.@variable(m, [1:n-1], base_name = "x̂_$counter")
ẑ = JuMP.@variable(m, [1:n-1], base_name = "ẑ_$counter")
y = JuMP.@variable(m, [1:n-1], Bin, base_name = "y_$counter")
JuMP.@constraint(m, sum(y) == 1)
JuMP.@constraint(m, sum(x̂) == x)
JuMP.@constraint(m, sum(ẑ) == z)
Δ = [(fd[i+1] - fd[i]) / (d[i+1] - d[i]) for i in 1:n-1]
for i in 1:n-1
JuMP.@constraints(
m,
begin
x̂[i] ≥ d[i] * y[i]
x̂[i] ≤ d[i+1] * y[i]
ẑ[i] == fd[i] * y[i] + Δ[i] * (x̂[i] - d[i] * y[i])
end
)
end
elseif method in (:DisaggLogarithmic, :DLog)
γ = JuMP.@variable(
m,
[i = 1:n, j = max(1, i - 1):min(n - 1, i)],
lower_bound = 0,
upper_bound = 1
)
JuMP.@constraint(m, sum(γ) == 1)
JuMP.@constraint(
m,
γ[1, 1] * d[1] +
sum((γ[i, i-1] + γ[i, i]) * d[i] for i in 2:n-1) +
γ[n, n-1] * d[n] == x
)
JuMP.@constraint(
m,
γ[1, 1] * fd[1] +
sum((γ[i, i-1] + γ[i, i]) * fd[i] for i in 2:n-1) +
γ[n, n-1] * fd[n] == z
)
r = ceil(Int, log2(n - 1))
H = reflected_gray_codes(r)
y = JuMP.@variable(m, [1:r], Bin)
for j in 1:r
JuMP.@constraint(
m,
sum((γ[i, i] + γ[i+1, i]) * H[i][j] for i in 1:(n-1)) == y[j]
)
end
else
# V-formulation methods
λ = JuMP.@variable(
m,
[1:n],
lower_bound = 0,
upper_bound = 1,
base_name = "λ_$counter"
)
JuMP.@constraint(m, sum(λ) == 1)
JuMP.@constraint(m, sum(λ[i] * d[i] for i in 1:n) == x)
JuMP.@constraint(m, sum(λ[i] * fd[i] for i in 1:n) == z)
if method in (:Logarithmic, :Log)
sos2_logarithmic_formulation!(m, λ)
elseif method in (:LogarithmicIB, :LogIB)
sos2_logarithmic_IB_formulation!(m, λ)
elseif method == :CC
sos2_cc_formulation!(m, λ)
elseif method in (:ZigZag, :ZZB)
sos2_zigzag_formulation!(m, λ)
elseif method in (:ZigZagInteger, :ZZI)
sos2_zigzag_general_integer_formulation!(m, λ)
elseif method == :GeneralizedCelaya
sos2_generalized_celaya_formulation!(m, λ)
elseif method == :SymmetricCelaya
sos2_symmetric_celaya_formulation!(m, λ)
elseif method == :SOS2
JuMP.@constraint(m, λ in MOI.SOS2([i for i in 1:n]))
else
error("Unrecognized method $method")
end
end
return z
end
function sos2_cc_formulation!(m::JuMP.Model, λ)
counter = m.ext[:PWL].counter
n = length(λ)
y = JuMP.@variable(m, [1:n-1], Bin, base_name = "y_$counter")
JuMP.@constraint(m, sum(y) == 1)
JuMP.@constraint(m, λ[1] ≤ y[1])
for i in 2:n-1
JuMP.@constraint(m, λ[i] ≤ y[i-1] + y[i])
end
JuMP.@constraint(m, λ[n] ≤ y[n-1])
return
end
# function sos2_mc_formulation!(m::JuMP.Model, λ) # not currently used
# counter = m.ext[:PWL].counter
# n = length(λ)
# γ = JuMP.@variable(m, [1:n-1, 1:n], base_name="γ_$counter")
# y = JuMP.@variable(m, [1:n-1], Bin, base_name="y_$counter")
# JuMP.@constraint(m, sum(y) == 1)
# JuMP.@constraint(m, sum(γ[i,:] for i in 1:n-1) .== λ)
# for i in 1:n-1
# JuMP.@constraint(m, γ[i,i] + γ[i,i+1] ≥ y[i])
# end
# return
# end
function sos2_logarithmic_formulation!(m::JuMP.Model, λ)
counter = m.ext[:PWL].counter
n = length(λ) - 1
k = ceil(Int, log2(n))
y = JuMP.@variable(m, [1:k], Bin, base_name = "y_$counter")
sos2_encoding_constraints!(
m,
λ,
y,
reflected_gray_codes(k),
unit_vector_hyperplanes(k),
)
return
end
function sos2_logarithmic_IB_formulation!(m::JuMP.Model, λ) # IB: independent branching
counter = m.ext[:PWL].counter
n = length(λ) - 1
k = ceil(Int, log2(n))
y = JuMP.@variable(m, [1:k], Bin, base_name = "y_$counter")
_H = reflected_gray_codes(k)
d = length(_H)
H = Dict(i => _H[i] for i in 1:d)
H[0] = H[1]
H[d+1] = H[d]
for j in 1:k
JuMP.@constraints(
m,
begin
sum(λ[i] for i in 1:(n+1) if H[i-1][j] == H[i][j] == 1) ≤ y[j]
sum(λ[i] for i in 1:(n+1) if H[i-1][j] == H[i][j] == 0) ≤
1 - y[j]
end
)
end
return
end
function sos2_zigzag_formulation!(m::JuMP.Model, λ)
counter = m.ext[:PWL].counter
n = length(λ) - 1
k = ceil(Int, log2(n))
y = JuMP.@variable(m, [1:k], Bin, base_name = "y_$counter")
sos2_encoding_constraints!(m, λ, y, zigzag_codes(k), zigzag_hyperplanes(k))
return
end
function sos2_zigzag_general_integer_formulation!(m::JuMP.Model, λ)
counter = m.ext[:PWL].counter
n = length(λ) - 1
k = ceil(Int, log2(n))
# TODO: tighter upper_bounds
y = JuMP.@variable(
m,
[i = 1:k],
Int,
lower_bound = 0,
upper_bound = 2^(k - i),
base_name = "y_$counter"
)
sos2_encoding_constraints!(
m,
λ,
y,
integer_zigzag_codes(k),
unit_vector_hyperplanes(k),
)
return
end
function sos2_generalized_celaya_formulation!(m::JuMP.Model, λ)
counter = m.ext[:PWL].counter
n = length(λ) - 1
k = ceil(Int, log2(n))
codes = generalized_celaya_codes(k)
lb = [minimum(t[i] for t in codes) for i in 1:k]
ub = [maximum(t[i] for t in codes) for i in 1:k]
y = JuMP.@variable(
m,
[i = 1:k],
Int,
lower_bound = lb[i],
upper_bound = ub[i],
base_name = "y_$counter"
)
sos2_encoding_constraints!(
m,
λ,
y,
codes,
generalized_celaya_hyperplanes(k),
)
return
end
function sos2_symmetric_celaya_formulation!(m::JuMP.Model, λ)
counter = m.ext[:PWL].counter
n = length(λ) - 1
k = ceil(Int, log2(n))
codes = symmetric_celaya_codes(k)
lb = [minimum(t[i] for t in codes) for i in 1:k]
ub = [maximum(t[i] for t in codes) for i in 1:k]
y = JuMP.@variable(
m,
[i = 1:k],
Int,
lower_bound = lb[i],
upper_bound = ub[i],
base_name = "y_$counter"
)
sos2_encoding_constraints!(m, λ, y, codes, symmetric_celaya_hyperplanes(k))
return
end
function sos2_encoding_constraints!(m, λ, y, h, B)
n = length(λ) - 1
for b in B
JuMP.@constraints(
m,
begin
LinearAlgebra.dot(b, h[1]) * λ[1] +
sum(
min(
LinearAlgebra.dot(b, h[v]),
LinearAlgebra.dot(b, h[v-1]),
) * λ[v] for v in 2:n
) +
LinearAlgebra.dot(b, h[n]) * λ[n+1] ≤ LinearAlgebra.dot(b, y)
LinearAlgebra.dot(b, h[1]) * λ[1] +
sum(
max(
LinearAlgebra.dot(b, h[v]),
LinearAlgebra.dot(b, h[v-1]),
) * λ[v] for v in 2:n
) +
LinearAlgebra.dot(b, h[n]) * λ[n+1] ≥ LinearAlgebra.dot(b, y)
end
)
end
return
end
function reflected_gray_codes(k::Int)
if k == 0
return Vector{Int}[]
elseif k == 1
return [[0], [1]]
else
codes′ = reflected_gray_codes(k - 1)
return vcat(
[vcat(code, 0) for code in codes′],
[vcat(code, 1) for code in reverse(codes′)],
)
end
end
function zigzag_codes(k::Int)
if k <= 0
error("Invalid code length $k")
elseif k == 1
return [[0], [1]]
else
codes′ = zigzag_codes(k - 1)
return vcat(
[vcat(code, 0) for code in codes′],
[vcat(code, 1) for code in codes′],
)
end
end
function integer_zigzag_codes(k::Int)
if k <= 0
error("Invalid code length $k")
elseif k == 1
return [[0], [1]]
else
codes′ = integer_zigzag_codes(k - 1)
offset = [2^(j - 2) for j in k:-1:2]
return vcat(
[vcat(code, 0) for code in codes′],
[vcat(code .+ offset, 1) for code in codes′],
)
end
end
function generalized_celaya_codes(k::Int)
if k <= 0
error("Invalid code length $k")
elseif k == 1
return [[0], [1]]
elseif k == 2
return [[0, 0], [1, 1], [1, 0], [0, 1]]
else
codes′ = generalized_celaya_codes(k - 1)
n = length(codes′)
hp = Int(n / 2)
firstcodes = [codes′[i] for i in 1:hp]
secondcodes = [codes′[i] for i in (hp+1):n]
return vcat(
[vcat(codes′[i], 0) for i in 1:n],
[vcat(codes′[i], 1) for i in 1:hp],
[vcat(codes′[i], -1) for i in (hp+1):n],
)
end
end
function symmetric_celaya_codes(k::Int)
if k <= 0
error("Invalid code length $k")
elseif k == 1
return [[0], [1]]
else
codes′ = generalized_celaya_codes(k - 1)
n = length(codes′)
hp = Int(n / 2)
firstcodes = [codes′[i] for i in 1:hp]
secondcodes = [codes′[i] for i in (hp+1):n]
return vcat(
[vcat(codes′[i], 0) for i in 1:n],
[vcat(codes′[i], 1) for i in 1:hp],
[vcat(codes′[i], -1) for i in (hp+1):n],
)
end
end
function zigzag_hyperplanes(k::Int)
hps = Vector{Int}[]
for i in 1:k
hp = zeros(Int, k)
hp[i] = 1
for j in (i+1):k
hp[j] = 2^(j - i - 1)
end
push!(hps, hp)
end
return hps
end
function unit_vector_hyperplanes(k::Int)
hps = Vector{Int}[]
for i in 1:k
hp = zeros(Int, k)
hp[i] = 1
push!(hps, hp)
end
return hps
end
function generalized_celaya_hyperplanes(k::Int)
return compute_hyperplanes(generalized_celaya_codes(k))
end
function symmetric_celaya_hyperplanes(k::Int)
return compute_hyperplanes(symmetric_celaya_codes(k))
end
function compute_hyperplanes(C::Vector{Vector{T}}) where {T<:Number}
n = length(C)
k = length(C[1])
d = zeros(n - 1, k)
for i in 1:n-1
d[i, :] = C[i+1] - C[i]
end
if k <= 1
error("Cannot process codes of length $k")
elseif k == 2
@assert n == 4
spanners = Vector{Float64}[]
for i in 1:n-1
v = canonical!(d[i, :])
v = [v[2], -v[1]]
push!(spanners, v)
end
indices = [1]
approx12 = isapprox(spanners[1], spanners[2])
approx13 = isapprox(spanners[1], spanners[3])
approx23 = isapprox(spanners[2], spanners[3])
if !approx12
push!(indices, 2)
end
if !approx13 && !(!approx12 && approx23)
push!(indices, 3)
end
return spanners[indices]
end
indices = [1, 2]
spanners = Vector{Float64}[]
while !isempty(indices)
if indices == [n - 1]
break
end
if LinearAlgebra.rank(d[indices, :]) == length(indices) &&
length(indices) <= k - 1
if length(indices) == k - 1
nullsp = LinearAlgebra.nullspace(d[indices, :])
@assert size(nullsp, 2) == 1
v = vec(nullsp)
push!(spanners, canonical!(v))
end
if indices[end] != n - 1
push!(indices, indices[end] + 1)
else
pop!(indices)
indices[end] += 1
end
else
if indices[end] != n - 1
indices[end] += 1
else
pop!(indices)
indices[end] += 1
end
end
end
keepers = [1]
for i in 2:length(spanners)
alreadyin = false
for j in keepers
if isapprox(spanners[i], spanners[j])
alreadyin = true
break
end
end
if !alreadyin
push!(keepers, i)
end
end
return spanners[keepers]
end
function canonical!(v::Vector{Float64})
LinearAlgebra.normalize!(v)
for j in 1:length(v)
if abs(v[j]) < 1e-8
v[j] = 0
end
end
sgn = sign(v[findfirst([x != 0 for x in v])])
for j in 1:length(v)
if abs(v[j]) < 1e-8
v[j] = 0
else
v[j] *= sgn
end
end
return v
end
function optimal_IB_scheme!(m::JuMP.Model, λ, pwl, subsolver) # IB: independent branching
m.ext[:OptimalIB] = Int[]
if !haskey(m.ext, :OptimalIBCache)
m.ext[:OptimalIBCache] = Dict()
end
T = pwl.T
n = maximum(maximum(t) for t in T)
J = 1:n
E = fill(false, n, n)
for t in T
for i in t, j in t
E[i, j] = true
end
end
if haskey(m.ext[:OptimalIBCache], pwl.T)
xx, yy = m.ext[:OptimalIBCache][pwl.T]
t = size(xx, 1)
else
t = ceil(Int, log2(length(T)))
xx = Array{Float64,2}(undef, 0, 0)
yy = Array{Float64,2}(undef, 0, 0)
while true
model = JuMP.Model(; solver = subsolver)
JuMP.@variable(model, x[1:t, 1:n], Bin)
JuMP.@variable(model, y[1:t, 1:n], Bin)
JuMP.@variable(model, z[1:t, 1:n, 1:n], Bin)
for j in 1:t
for r in J, s in J
if r >= s
continue
end
JuMP.@constraints(
model,
begin
z[j, r, s] <= x[j, r] + x[j, s]
z[j, r, s] <= x[j, r] + y[j, r]
z[j, r, s] <= x[j, s] + y[j, s]
z[j, r, s] <= y[j, r] + y[j, s]
z[j, r, s] >= x[j, r] + y[j, s] - 1
z[j, r, s] >= x[j, s] + y[j, r] - 1
end
)
end
for r in J
JuMP.@constraint(model, x[j, r] + y[j, r] <= 1)
end
end
for r in J, s in J
if r >= s
continue
end
if E[r, s]
JuMP.@constraint(model, sum(z[j, r, s] for j in 1:t) == 0)
else
JuMP.@constraint(model, sum(z[j, r, s] for j in 1:t) >= 1)
end
end
JuMP.@objective(model, Min, sum(x) + sum(y))
stat = JuMP.solve(model)
xx = JuMP.getvalue(x)
yy = JuMP.getvalue(y)
if any(isnan, xx) || any(isnan, yy)
t += 1
else
break
end
end
m.ext[:OptimalIBCache][pwl.T] = (xx, yy)
end
y = JuMP.@variable(m, [1:t], Bin)
dˣ = [_x[1] for _x in pwl.x]
dʸ = [_x[2] for _x in pwl.x]
uˣ, uʸ = unique(dˣ), unique(dʸ)
@assert issorted(uˣ)
@assert issorted(uʸ)
nˣ, nʸ = length(uˣ), length(uʸ)
ˣtoⁱ = Dict(uˣ[i] => i for i in 1:nˣ)
ʸtoʲ = Dict(uʸ[i] => i for i in 1:nʸ)
for i in 1:t
JuMP.@constraints(
m,
begin
sum(
λ[ˣtoⁱ[pwl.x[j][1]], ʸtoʲ[pwl.x[j][2]]] for
j in J if xx[i, j] == 1
) ≤ y[i]
sum(
λ[ˣtoⁱ[pwl.x[j][1]], ʸtoʲ[pwl.x[j][2]]] for
j in J if yy[i, j] == 1
) ≤ 1 - y[i]
end
)
end
push!(m.ext[:OptimalIB], t)
return
end
function piecewiselinear(
m::JuMP.Model,
x::VarOrAff,
y::VarOrAff,
dˣ,
dʸ,
f::Function;
method = defaultmethod(),
)
return piecewiselinear(
m,
x,
y,
BivariatePWLFunction(dˣ, dʸ, f);
method = method,
)
end
function piecewiselinear(
m::JuMP.Model,
x₁::VarOrAff,
x₂::VarOrAff,
pwl::BivariatePWLFunction;
method = defaultmethod(),
subsolver = nothing,
)
if (method == :OptimalIB) && (subsolver === nothing)
error(
"No MIP solver provided to construct optimal IB scheme. Pass a solver object to the piecewiselinear function, e.g. piecewiselinear(m, x₁, x₂, bivariatefunc, method=:OptimalIB, subsolver=GurobiSolver())",
)
end
initPWL!(m)
counter = m.ext[:PWL].counter
counter += 1
m.ext[:PWL].counter = counter
dˣ = [_x[1] for _x in pwl.x]
dʸ = [_x[2] for _x in pwl.x]
uˣ, uʸ = unique(dˣ), unique(dʸ)
@assert issorted(uˣ)
@assert issorted(uʸ)
T = pwl.T
nˣ, nʸ = length(uˣ), length(uʸ)
if nˣ == 0 || nʸ == 0
error(
"I don't know how to handle a piecewise linear function with zero breakpoints",
)
elseif nˣ == 1
@assert length(dʸ) == nʸ == length(pwl.z)
return piecewiselinear(
m,
x₂,
UnivariatePWLFunction(dʸ, [pwl.z[i] for i in 1:nʸ]),
)
elseif nʸ == 1
@assert length(dˣ) == nˣ == length(pwl.z)
return piecewiselinear(
m,
x₁,
UnivariatePWLFunction(dˣ, [pwl.z[i] for i in 1:nˣ]),
)
end
ˣtoⁱ = Dict(uˣ[i] => i for i in 1:nˣ)
ʸtoʲ = Dict(uʸ[i] => i for i in 1:nʸ)
fd = Array{Float64}(undef, nˣ, nʸ)
for (v, fv) in zip(pwl.x, pwl.z)
# i is the linear index into pwl.x...really want (i,j) pair
fd[ˣtoⁱ[v[1]], ʸtoʲ[v[2]]] = fv
end
z = JuMP.@variable(
m,
lower_bound = minimum(fd),
upper_bound = maximum(fd),
base_name = "z_$counter"
)
if method == :MC
x̂₁ = JuMP.@variable(m, [T], base_name = "x̂₁_$counter")
x̂₂ = JuMP.@variable(m, [T], base_name = "x̂₂_$counter")
ẑ = JuMP.@variable(m, [T], base_name = "ẑ_$counter")
y = JuMP.@variable(m, [T], Bin, base_name = "y_$counter")
JuMP.@constraint(m, sum(y) == 1)
JuMP.@constraint(m, sum(x̂₁) == x₁)
JuMP.@constraint(m, sum(x̂₂) == x₂)
JuMP.@constraint(m, sum(ẑ) == z)
for t in T
@assert length(t) == 3
r¹, r², r³ = pwl.x[t[1]], pwl.x[t[2]], pwl.x[t[3]]
fz¹, fz², fz³ = pwl.z[t[1]], pwl.z[t[2]], pwl.z[t[3]]
for P in ([1, 2, 3], [2, 3, 1], [3, 1, 2])
p¹, p², p³ = [r¹, r², r³][P]
# p¹, p², p³ = pwl.x[t[P[1]]], pwl.x[t[P[2]]], pwl.x[t[P[3]]]
A = [
p¹[1] p¹[2] 1
p²[1] p²[2] 1
p³[1] p³[2] 1
]
@assert LinearAlgebra.rank(A) == 3
b = [0, 0, 1]
q = A \ b
@assert isapprox(
q[1] * p¹[1] + q[2] * p¹[2] + q[3],
0,
atol = 1e-4,
)
@assert isapprox(
q[1] * p²[1] + q[2] * p²[2] + q[3],
0,
atol = 1e-4,
)
@assert isapprox(
q[1] * p³[1] + q[2] * p³[2] + q[3],
1,
atol = 1e-4,
)
JuMP.@constraint(
m,
q[1] * x̂₁[t] + q[2] * x̂₂[t] + q[3] * y[t] ≥ 0
)
end
A = [
r¹[1] r¹[2] 1
r²[1] r²[2] 1
r³[1] r³[2] 1
]
b = [fz¹, fz², fz³]
q = A \ b
@assert isapprox(
q[1] * r¹[1] + q[2] * r¹[2] + q[3],
fz¹,
atol = 1e-4,
)
@assert isapprox(
q[1] * r²[1] + q[2] * r²[2] + q[3],
fz²,
atol = 1e-4,
)
@assert isapprox(
q[1] * r³[1] + q[2] * r³[2] + q[3],
fz³,
atol = 1e-4,
)
JuMP.@constraint(
m,
ẑ[t] == q[1] * x̂₁[t] + q[2] * x̂₂[t] + q[3] * y[t]
)
end
elseif method in (:DisaggLogarithmic, :DLog)
T = pwl.T
X = pwl.x
Z = pwl.z
n = length(X)
γ = JuMP.@variable(
m,
[t = T, v = t],
lower_bound = 0,
upper_bound = 1,
base_name = "γ_$counter"
)
Tv = Dict(v => Any[] for v in 1:n)
for t in T, v in t
push!(Tv[v], t)
end
JuMP.@constraint(m, sum(γ) == 1)
JuMP.@constraint(
m,
sum(sum(γ[t, i] for t in Tv[i]) * X[i][1] for i in 1:n) == x₁
)
JuMP.@constraint(
m,
sum(sum(γ[t, i] for t in Tv[i]) * X[i][2] for i in 1:n) == x₂
)
JuMP.@constraint(
m,
sum(sum(γ[t, i] for t in Tv[i]) * Z[i] for i in 1:n) == z
)
r = ceil(Int, log2(length(T)))
H = reflected_gray_codes(r)
y = JuMP.@variable(m, [1:r], Bin, base_name = "y_$counter")
for j in 1:r
JuMP.@constraint(
m,
sum(
sum(γ[T[i], v] for v in T[i]) * H[i][j] for i in 1:length(T)
) == y[j]
)
end
else
# V-formulation methods
λ = JuMP.@variable(
m,
[1:nˣ, 1:nʸ],
lower_bound = 0,
upper_bound = 1,
base_name = "λ_$counter"
)
JuMP.@constraint(m, sum(λ) == 1)
JuMP.@constraint(m, sum(λ[i, j] * uˣ[i] for i in 1:nˣ, j in 1:nʸ) == x₁)
JuMP.@constraint(m, sum(λ[i, j] * uʸ[j] for i in 1:nˣ, j in 1:nʸ) == x₂)
JuMP.@constraint(
m,
sum(λ[i, j] * fd[i, j] for i in 1:nˣ, j in 1:nʸ) == z
)
if method == :CC
T = pwl.T
y = JuMP.@variable(m, [T], Bin, base_name = "y_$counter")
JuMP.@constraint(m, sum(y) == 1)
Ts = Dict((i, j) => Vector{Int}[] for i in 1:nˣ, j in 1:nʸ)
for t in T, ind in t
rˣ, rʸ = pwl.x[ind]
i, j = ˣtoⁱ[rˣ], ʸtoʲ[rʸ]
push!(Ts[(i, j)], t)
end
for i in 1:nˣ, j in 1:nʸ
JuMP.@constraint(m, λ[i, j] ≤ sum(y[t] for t in Ts[(i, j)]))
end
elseif method == :Incremental
error(
"Incremental formulation for bivariate functions is not currently implemented.",
)
# TODO: implement algorithm of Geissler et al. (2012)
elseif method == :OptimalIB
error(
"Optimal IB formulation has not yet been updated for JuMP v0.19.",
)
optimal_IB_scheme!(m, λ, pwl, subsolver)
else
# formulations with SOS2 along each dimension
Tx = [sum(λ[tˣ, tʸ] for tˣ in 1:nˣ) for tʸ in 1:nʸ]
Ty = [sum(λ[tˣ, tʸ] for tʸ in 1:nʸ) for tˣ in 1:nˣ]
if method in (:Logarithmic, :Log)
sos2_logarithmic_formulation!(m, Tx)
sos2_logarithmic_formulation!(m, Ty)
elseif method in (:LogarithmicIB, :LogIB)
sos2_logarithmic_IB_formulation!(m, Tx)
sos2_logarithmic_IB_formulation!(m, Ty)
elseif method in (:ZigZag, :ZZB)
sos2_zigzag_formulation!(m, Tx)
sos2_zigzag_formulation!(m, Ty)
elseif method in (:ZigZagInteger, :ZZI)
sos2_zigzag_general_integer_formulation!(m, Tx)
sos2_zigzag_general_integer_formulation!(m, Ty)
elseif method == :GeneralizedCelaya
sos2_generalized_celaya_formulation!(m, Tx)
sos2_generalized_celaya_formulation!(m, Ty)
elseif method == :SymmetricCelaya
sos2_symmetric_celaya_formulation!(m, Tx)
sos2_symmetric_celaya_formulation!(m, Ty)
elseif method == :SOS2
γˣ = JuMP.@variable(
m,
[1:nˣ],
lower_bound = 0,
upper_bound = 1,
base_name = "γˣ_$counter"
)
γʸ = JuMP.@variable(
m,
[1:nʸ],
lower_bound = 0,
upper_bound = 1,
base_name = "γʸ_$counter"
)
JuMP.@constraint(
m,
[tˣ in 1:nˣ],
γˣ[tˣ] == sum(λ[tˣ, tʸ] for tʸ in 1:nʸ)
)
JuMP.@constraint(
m,
[tʸ in 1:nʸ],
γʸ[tʸ] == sum(λ[tˣ, tʸ] for tˣ in 1:nˣ)
)
JuMP.@constraint(m, γˣ in MOI.SOS2([k for k in 1:nˣ]))
JuMP.@constraint(m, γʸ in MOI.SOS2([k for k in 1:nʸ]))
else
error("Unrecognized method $method")
end
pattern = pwl.meta[:structure]
if pattern == :UnionJack
numT = 0
minˣ, minʸ = uˣ[1], uʸ[1]
# find the index of the bottom-left point
idx = findfirst(pwl.x) do w
return w == (minˣ, minʸ)
end
for t in pwl.T
if idx in t
numT += 1
end
end
@assert 1 <= numT <= 2
w = JuMP.@variable(m, binary = true, base_name = "w_$counter")
# if numT==1, then bottom-left is contained in only one point, and so needs separating; otherwise numT==2, and need to offset by one
JuMP.@constraints(
m,
begin
sum(λ[tx, ty] for tx in 1:2:nˣ, ty in numT:2:nʸ) ≤ w
sum(λ[tx, ty] for tx in 2:2:nˣ, ty in (3-numT):2:nʸ) ≤
1 - w
end
)
elseif pattern == :K1
# assumption is that the triangulation is uniform, as defined in types.jl
w = JuMP.@variable(m, [1:2], Bin, base_name = "w_$counter")
JuMP.@constraints(
m,
begin
sum(
λ[tx, ty] for tx in 1:nˣ, ty in 1:nʸ if
mod(tx, 2) == mod(ty, 2) && (tx + ty) in 2:4:(nˣ+nʸ)
) ≤ w[1]
sum(
λ[tx, ty] for tx in 1:nˣ, ty in 1:nʸ if
mod(tx, 2) == mod(ty, 2) && (tx + ty) in 4:4:(nˣ+nʸ)
) ≤ 1 - w[1]
sum(
λ[tx, ty] for tx in 1:nˣ, ty in 1:nʸ if
mod(tx, 2) != mod(ty, 2) && (tx + ty) in 3:4:(nˣ+nʸ)
) ≤ w[2]
sum(
λ[tx, ty] for tx in 1:nˣ, ty in 1:nʸ if
mod(tx, 2) != mod(ty, 2) && (tx + ty) in 5:4:(nˣ+nʸ)
) ≤ 1 - w[2]
end
)
elseif pattern == :OptimalTriangleSelection
error(
"Optimal triangle selection formulation has not yet been updated for JuMP v0.19.",
)
m.ext[:OptimalTriSelect] = Int[]
if !haskey(m.ext, :OptimalTriSelectCache)
m.ext[:OptimalTriSelectCache] = Dict()
end
J = [(i, j) for i in 1:nˣ, j in 1:nʸ]
E = Set{Tuple{Tuple{Int,Int},Tuple{Int,Int}}}()
for t in T
@assert length(t) == 3
IJ = [(ˣtoⁱ[pwl.x[i][1]], ʸtoʲ[pwl.x[i][2]]) for i in t]
im = minimum(ij[1] for ij in IJ)
iM = maximum(ij[1] for ij in IJ)
jm = minimum(ij[2] for ij in IJ)
jM = maximum(ij[2] for ij in IJ)
@assert im < iM
@assert im < iM
if ((im, jm) in IJ) && ((iM, jM) in IJ)
push!(E, ((im, jM), (iM, jm)))
elseif ((im, jM) in IJ) && ((iM, jm) in IJ)
push!(E, ((im, jm), (iM, jM)))
else
error()
end
end
if haskey(m.ext[:OptimalTriSelectCache], E)
xx, yy = m.ext[:OptimalTriSelectCache][E]
t = JuMP.size(xx, 1)
else
if subsolver === nothing
error(
"No MIP solver provided to construct optimal triangle selection. Pass a solver object to the piecewiselinear function, e.g. piecewiselinear(m, x₁, x₂, bivariatefunc, method=:Logarithmic, subsolver=GurobiSolver())",
)
end
t = 1
xx, yy = Array(Float64, 0, 0), Array(Float64, 0, 0)
while true
subm = JuMP.Model(; solver = subsolver)
JuMP.@variable(subm, xˢᵘᵇ[1:t, J], Bin)
JuMP.@variable(subm, yˢᵘᵇ[1:t, J], Bin)
JuMP.@variable(subm, zˢᵘᵇ[1:t, J, J], Bin)
for j in 1:t
for r in J, s in J
# lexicographic ordering on points on grid
if r[1] > s[1] || (r[1] == s[1] && r[2] >= s[2])
continue
end
JuMP.@constraints(
subm,
begin
zˢᵘᵇ[j, r, s] <=
xˢᵘᵇ[j, r] + xˢᵘᵇ[j, s]
zˢᵘᵇ[j, r, s] <=
xˢᵘᵇ[j, r] + yˢᵘᵇ[j, r]
zˢᵘᵇ[j, r, s] <=
xˢᵘᵇ[j, s] + yˢᵘᵇ[j, s]
zˢᵘᵇ[j, r, s] <=
yˢᵘᵇ[j, r] + yˢᵘᵇ[j, s]
zˢᵘᵇ[j, r, s] >=
xˢᵘᵇ[j, r] + yˢᵘᵇ[j, s] - 1
zˢᵘᵇ[j, r, s] >=
xˢᵘᵇ[j, s] + yˢᵘᵇ[j, r] - 1
end
)
end
for r in J
JuMP.@constraint(
subm,
xˢᵘᵇ[j, r] + yˢᵘᵇ[j, r] <= 1
)
end
end
for r in J, s in J
# lexicographic ordering on points on grid
(r[1] > s[1] || (r[1] == s[1] && r[2] >= s[2])) &&
continue
if (r, s) in E
JuMP.@constraint(
subm,
sum(zˢᵘᵇ[j, r, s] for j in 1:t) >= 1
)
elseif max(abs(r[1] - s[1]), abs(r[2] - s[2])) == 1
JuMP.@constraint(
subm,
sum(zˢᵘᵇ[j, r, s] for j in 1:t) == 0
)
end
end
JuMP.@objective(subm, Min, sum(xˢᵘᵇ) + sum(yˢᵘᵇ))
stat = JuMP.solve(subm)
if any(isnan, subm.colVal)
t += 1
else
xx = JuMP.getvalue(xˢᵘᵇ)
yy = JuMP.getvalue(yˢᵘᵇ)
m.ext[:OptimalTriSelectCache][E] = (xx, yy)
break
end
end
end
y = JuMP.@variable(
m,
[1:t],
Bin,
base_name = "Δselect_$counter"
)
for i in 1:t
JuMP.@constraints(
m,
begin
sum(λ[v[1], v[2]] for v in J if xx[i, v] ≈ 1) ≤
y[i]
sum(λ[v[1], v[2]] for v in J if yy[i, v] ≈ 1) ≤
1 - y[i]
end
)
end
push!(m.ext[:OptimalTriSelect], t)
elseif pattern in (:Stencil, :Stencil9)
w = JuMP.@variable(m, [1:3, 1:3], Bin, base_name = "w_$counter")
for oˣ in 1:3, oʸ in 1:3
innoT = fill(true, nˣ, nʸ)
for (i, j, k) in pwl.T
xⁱ, xʲ, xᵏ = pwl.x[i], pwl.x[j], pwl.x[k]
iiˣ, iiʸ = ˣtoⁱ[xⁱ[1]], ʸtoʲ[xⁱ[2]]
jjˣ, jjʸ = ˣtoⁱ[xʲ[1]], ʸtoʲ[xʲ[2]]
kkˣ, kkʸ = ˣtoⁱ[xᵏ[1]], ʸtoʲ[xᵏ[2]]
# check to see if one of the points in the triangle falls on the grid
if (mod1(iiˣ, 3) == oˣ && mod1(iiʸ, 3) == oʸ) ||
(mod1(jjˣ, 3) == oˣ && mod1(jjʸ, 3) == oʸ) ||
(mod1(kkˣ, 3) == oˣ && mod1(kkʸ, 3) == oʸ)
innoT[iiˣ, iiʸ] = false
innoT[jjˣ, jjʸ] = false
innoT[kkˣ, kkʸ] = false
end
end
JuMP.@constraints(
m,
begin
sum(λ[i, j] for i in oˣ:3:nˣ, j in oʸ:3:nʸ) ≤
1 - w[oˣ, oʸ]
sum(
λ[i, j] for i in 1:nˣ, j in 1:nʸ if innoT[i, j]
) ≤ w[oˣ, oʸ]
end
)
end
else
@assert pattern in (:Upper, :Lower, :BestFit, :Random)
# Eⁿᵉ[i,j] = true means that we must cover the edge {(i,j),(i+1,j+1)}
Eⁿᵉ = fill(false, nˣ - 1, nʸ - 1)
for (i, j, k) in pwl.T
xⁱ, xʲ, xᵏ = pwl.x[i], pwl.x[j], pwl.x[k]
iiˣ, iiʸ = ˣtoⁱ[xⁱ[1]], ʸtoʲ[xⁱ[2]]
jjˣ, jjʸ = ˣtoⁱ[xʲ[1]], ʸtoʲ[xʲ[2]]
kkˣ, kkʸ = ˣtoⁱ[xᵏ[1]], ʸtoʲ[xᵏ[2]]
IJ = [(iiˣ, iiʸ), (jjˣ, jjʸ), (kkˣ, kkʸ)]
im = min(iiˣ, jjˣ, kkˣ)
iM = max(iiˣ, jjˣ, kkˣ)
jm = min(iiʸ, jjʸ, kkʸ)
jM = max(iiʸ, jjʸ, kkʸ)
if ((im, jM) in IJ) && ((iM, jm) in IJ)
Eⁿᵉ[im, jm] = true
else
@assert (im, jm) in IJ && (iM, jM) in IJ
end
end
# diagonal lines running from SW to NE. Grouped with an offset of 3.
wⁿᵉ = JuMP.@variable(m, [0:2], Bin, base_name = "wⁿᵉ_$counter")
for o in 0:2
Aᵒ = Set{Tuple{Int,Int}}()
Bᵒ = Set{Tuple{Int,Int}}()
for offˣ in o:3:(nˣ-2)
SWinA = true # whether we put the SW corner of the next triangle to cover in set A
for i in (1+offˣ):(nˣ-1)
j = i - offˣ
if !(1 ≤ i ≤ nˣ - 1)
continue
end
if !(1 ≤ j ≤ nʸ - 1)
continue # should never happen
end
if Eⁿᵉ[i, j] # if we need to cover the edge...
if SWinA # figure out which set we need to put it in; this depends on previous triangle in our current line
push!(Aᵒ, (i, j))
push!(Bᵒ, (i + 1, j + 1))
else
push!(Aᵒ, (i + 1, j + 1))
push!(Bᵒ, (i, j))
end
SWinA = !SWinA
end
end
end
for offʸ in (3-o):3:(nʸ-1)
SWinA = true
for j in (offʸ+1):(nʸ-1)
i = j - offʸ
if !(1 ≤ i ≤ nˣ - 1)
continue
end
if Eⁿᵉ[i, j]
if SWinA
push!(Aᵒ, (i, j))
push!(Bᵒ, (i + 1, j + 1))
else
push!(Aᵒ, (i + 1, j + 1))
push!(Bᵒ, (i, j))
end
SWinA = !SWinA
end
end
end
JuMP.@constraints(
m,
begin
sum(λ[i, j] for (i, j) in Aᵒ) ≤ wⁿᵉ[o]
sum(λ[i, j] for (i, j) in Bᵒ) ≤ 1 - wⁿᵉ[o]
end
)
end
wˢᵉ = JuMP.@variable(m, [0:2], Bin, base_name = "wˢᵉ_$counter")
for o in 0:2
Aᵒ = Set{Tuple{Int,Int}}()
Bᵒ = Set{Tuple{Int,Int}}()
for offˣ in o:3:(nˣ-2)
SEinA = true
# for i in (1+offˣ):-1:1
# j = offˣ - i + 2
for j in 1:(nʸ-1)
i = nˣ - j - offˣ
if !(1 ≤ i ≤ nˣ - 1)
continue
end
if !Eⁿᵉ[i, j]
if SEinA
push!(Aᵒ, (i + 1, j))
push!(Bᵒ, (i, j + 1))
else
push!(Aᵒ, (i, j + 1))
push!(Bᵒ, (i + 1, j))
end
SEinA = !SEinA
end
end
end
for offʸ in (3-o):3:(nʸ-1)
SEinA = true
for j in (offʸ+1):(nʸ-1)
i = nˣ - j + offʸ
if !(1 ≤ i ≤ nˣ - 1)
continue
end
if !Eⁿᵉ[i, j]
if SEinA
push!(Aᵒ, (i + 1, j))
push!(Bᵒ, (i, j + 1))
else
push!(Aᵒ, (i, j + 1))
push!(Bᵒ, (i + 1, j))
end
SEinA = !SEinA
end
end
end
JuMP.@constraints(
m,
begin
sum(λ[i, j] for (i, j) in Aᵒ) ≤ wˢᵉ[o]
sum(λ[i, j] for (i, j) in Bᵒ) ≤ 1 - wˢᵉ[o]
end
)
end
end
end
end
return z
end
| PiecewiseLinearOpt | https://github.com/jump-dev/PiecewiseLinearOpt.jl.git |
|
[
"MIT"
] | 0.4.2 | 59786d90d750f1c18029a3903e8c1bc49d0e55a8 | code | 3911 | # Copyright (c) 2016: Joey Huchette and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
struct PWLFunction{D}
x::Vector{NTuple{D,Float64}}
z::Vector{Float64}
T::Vector{Vector{Int}}
meta::Dict
end
function PWLFunction{D}(
x::Vector{NTuple{D}},
z::Vector,
T::Vector{Vector},
meta::Dict,
) where {D}
@assert length(x) == length(z)
for t in T
@assert minimum(t) > 0 && maximum(t) <= length(x)
end
return PWLFunction{D}(x, z, T, meta)
end
PWLFunction(x, z, T) = PWLFunction(x, z, T, Dict())
const UnivariatePWLFunction = PWLFunction{1}
function UnivariatePWLFunction(x, z)
@assert issorted(x)
return PWLFunction(
Tuple{Float64}[(xx,) for xx in x],
convert(Vector{Float64}, z),
[[i, i + 1] for i in 1:length(x)-1],
)
end
function UnivariatePWLFunction(x, fz::Function)
@assert issorted(x)
return PWLFunction(
Tuple{Float64}[(xx,) for xx in x],
map(t -> convert(Float64, fz(t)), x),
[[i, i + 1] for i in 1:length(x)-1],
)
end
const BivariatePWLFunction = PWLFunction{2}
function BivariatePWLFunction(
x,
y,
fz::Function;
pattern = :BestFit,
seed = hash((length(x), length(y))),
)
@assert issorted(x)
@assert issorted(y)
X = vec(collect(Base.product(x, y)))
# X = vec(Tuple{Float64,Float64}[(_x,_y) for _x in x, _y in y])
Z = map(t -> convert(Float64, fz(t...)), X)
T = Vector{Vector{Int}}()
m = length(x)
n = length(y)
mt = Random.MersenneTwister(seed)
# run for each square on [x[i],x[i+1]] × [y[i],y[i+1]]
for i in 1:length(x)-1, j in 1:length(y)-1
SWt, NWt, NEt, SEt = LinearIndices((m, n))[i, j],
LinearIndices((m, n))[i, j+1],
LinearIndices((m, n))[i+1, j+1],
LinearIndices((m, n))[i+1, j]
xL, xU, yL, yU = x[i], x[i+1], y[j], y[j+1]
@assert xL == X[SWt][1] == X[NWt][1]
@assert xU == X[SEt][1] == X[NEt][1]
@assert yL == X[SWt][2] == X[SEt][2]
@assert yU == X[NWt][2] == X[NEt][2]
SW, NW, NE, SE = Z[SWt], Z[NWt], Z[NEt], Z[SEt]
mid1 = 0.5 * (SW + NE)
mid2 = 0.5 * (NW + SE)
if pattern == :Upper
if mid1 > mid2
t1 = [SWt, NWt, NEt]
t2 = [SWt, NEt, SEt]
else
t1 = [SWt, NWt, SEt]
t2 = [SEt, NWt, NEt]
end
elseif pattern == :Lower
if mid1 > mid2
t1 = [SWt, NWt, SEt]
t2 = [SEt, NWt, NEt]
else
t1 = [SWt, NWt, NEt]
t2 = [SWt, NEt, SEt]
end
elseif pattern == :BestFit
mid3 = fz(0.5 * (xL + xU), 0.5 * (yL + yU))
if abs(mid1 - mid3) < abs(mid2 - mid3)
t1 = [SWt, NWt, NEt]
t2 = [SWt, NEt, SEt]
else
t1 = [SWt, NWt, SEt]
t2 = [SEt, NWt, NEt]
end
elseif pattern == :UnionJack
t1 = [SWt, SEt]
t2 = [NWt, NEt]
if iseven(i + j)
push!(t1, NWt)
push!(t2, SEt)
else
push!(t1, NEt)
push!(t2, SWt)
end
elseif pattern == :K1
t1 = [SEt, SWt, NWt]
t2 = [NWt, NEt, SEt]
elseif pattern == :Random
if rand(mt, Bool)
t1 = [NWt, NEt, SEt]
t2 = [SEt, SWt, NWt]
else
t1 = [SWt, NWt, NEt]
t2 = [NEt, SEt, SWt]
end
else
error("pattern $pattern not currently supported")
end
push!(T, t1)
push!(T, t2)
end
return PWLFunction{2}(X, Z, T, Dict(:structure => pattern))
end
| PiecewiseLinearOpt | https://github.com/jump-dev/PiecewiseLinearOpt.jl.git |
|
[
"MIT"
] | 0.4.2 | 59786d90d750f1c18029a3903e8c1bc49d0e55a8 | code | 4995 | # Copyright (c) 2016: Joey Huchette and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
# using Cbc # slow, not recommended
# solver = CbcSolver(logLevel=0, integerTolerance=1e-9, primalTolerance=1e-9, ratioGap=1e-8)
using Gurobi
solver = GurobiSolver(; OutputFlag = 0)
# using CPLEX
# solver = CplexSolver(CPX_PARAM_SCRIND=0)
using JuMP
using PiecewiseLinearOpt
using Base.Test
using HDF5
methods_1D = (
:CC,
:MC,
:Logarithmic,
:LogarithmicIB,
:ZigZag,
:ZigZagInteger,
:SOS2,
:GeneralizedCelaya,
:SymmetricCelaya,
:Incremental,
:DisaggLogarithmic,
)
methods_2D = (
:CC,
:MC,
:Logarithmic,
:LogarithmicIB,
:ZigZag,
:ZigZagInteger,
:SOS2,
:GeneralizedCelaya,
:SymmetricCelaya,
:DisaggLogarithmic,
)
# methods_2D = (:OptimalIB,) # very slow on all solvers
patterns_2D = (:Upper, :Lower, :UnionJack, :K1, :Random) # not :BestFit because requires function values at midpoints, :OptimalTriangleSelection and :Stencil not supported currently
# tests on network flow model with piecewise-linear objective
# instance data loaded from .h5 files
instance_data_1D = joinpath(dirname(@__FILE__), "1D-pwl-instances.h5")
instance_data_2D = joinpath(dirname(@__FILE__), "2D-pwl-instances.h5")
println("\nunivariate tests")
@testset "instance $instance" for instance in ["10104_1_concave_1"]
demand = h5read(instance_data_1D, string(instance, "/demand"))
supply = h5read(instance_data_1D, string(instance, "/supply"))
ndem = size(demand, 1)
nsup = size(supply, 1)
rawd = h5read(instance_data_1D, string(instance, "/d"))
d = rawd[1, :]
rawfd = h5read(instance_data_1D, string(instance, "/fd"))
fd = rawfd[1, :]
objval1 = NaN
@testset "1D: $method" for method in methods_1D
model = Model(; solver = solver)
@variable(model, x[1:nsup, 1:ndem] ≥ 0)
@constraint(
model,
[j in 1:ndem],
sum(x[i, j] for i in 1:nsup) == demand[j]
)
@constraint(
model,
[i in 1:nsup],
sum(x[i, j] for j in 1:ndem) == supply[i]
)
@objective(
model,
Min,
sum(
piecewiselinear(model, x[i, j], d, fd; method = method) for
i in 1:nsup, j in 1:ndem
)
)
@test solve(model) == :Optimal
if isnan(objval1)
objval1 = getobjectivevalue(model)
else
@test getobjectivevalue(model) ≈ objval1 rtol = 1e-4
end
end
end
println("\nbivariate tests")
# @testset "numpieces $numpieces, variety $variety, objective $objective" for numpieces in [4,8], variety in 1:5, objective in 1:20
@testset "numpieces $numpieces, variety $variety, objective $objective" for numpieces in
[4],
variety in 1:1,
objective in 1:1
instance = string(numpieces, "_", variety, "_", objective)
demand = h5read(instance_data_2D, string(instance, "/demand"))
supply = h5read(instance_data_2D, string(instance, "/supply"))
ndem = size(demand, 1)
nsup = size(supply, 1)
rawd = h5read(instance_data_2D, string(instance, "/d"))
d = rawd[1, :]
rawfd = h5read(instance_data_2D, string(instance, "/fd"))
fˣ = reshape(rawfd[1, :], length(d), length(d))
ˣtoⁱ = Dict(d[p] => p for p in 1:length(d))
f = (pˣ, pʸ) -> fˣ[ˣtoⁱ[pˣ], ˣtoⁱ[pʸ]]
objval1 = NaN
@testset "2D: $method, $pattern" for method in methods_2D,
pattern in patterns_2D
model = Model(; solver = solver)
@variable(model, x[1:nsup, 1:ndem] ≥ 0)
@constraint(
model,
[j in 1:ndem],
sum(x[i, j] for i in 1:nsup) == demand[j]
)
@constraint(
model,
[i in 1:nsup],
sum(x[i, j] for j in 1:ndem) == supply[i]
)
@variable(model, y[1:nsup, 1:ndem] ≥ 0)
@constraint(
model,
[j in 1:ndem],
sum(y[i, j] for i in 1:nsup) == demand[j]
)
@constraint(
model,
[i in 1:nsup],
sum(y[i, j] for j in 1:ndem) == supply[i]
)
@objective(
model,
Min,
sum(
piecewiselinear(
model,
x[i, j],
y[i, j],
BivariatePWLFunction(d, d, f; pattern = pattern);
method = method,
subsolver = solver,
) for i in 1:nsup, j in 1:ndem
)
)
@test solve(model) == :Optimal
if isnan(objval1)
objval1 = getobjectivevalue(model)
else
@test getobjectivevalue(model) ≈ objval1 rtol = 1e-4
end
end
end
| PiecewiseLinearOpt | https://github.com/jump-dev/PiecewiseLinearOpt.jl.git |
|
[
"MIT"
] | 0.4.2 | 59786d90d750f1c18029a3903e8c1bc49d0e55a8 | code | 4601 | # Copyright (c) 2016: Joey Huchette and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
using PiecewiseLinearOpt
using Test
import Cbc
import JuMP
import LinearAlgebra
import MathOptInterface as MOI
methods_1D = (
:CC,
:MC,
:Logarithmic,
:LogarithmicIB,
:ZigZag,
:ZigZagInteger,
:GeneralizedCelaya,
:SymmetricCelaya,
:Incremental,
:DisaggLogarithmic,
# :SOS2, not supported by Cbc
)
methods_2D = (
:CC,
:Logarithmic,
:LogarithmicIB,
:ZigZag,
:ZigZagInteger,
:GeneralizedCelaya,
:SymmetricCelaya,
:DisaggLogarithmic,
# :SOS2, not supported by Cbc
# TODO: Add :MC to this list, Cbc (but not Gurobi) gives a different answer
# below, only for :MC (maybe a bug in Cbc?)
)
patterns_2D = (
:Upper,
:Lower,
:BestFit,
:UnionJack,
:K1,
:Random,
# :OptimalTriangleSelection not supported currently
# :Stencil
)
optimizer = JuMP.optimizer_with_attributes(Cbc.Optimizer, MOI.Silent() => true)
@testset "Univariate tests" begin
@testset "1D: $method" for method in methods_1D
model = JuMP.Model(optimizer)
JuMP.@variable(model, x)
z = piecewiselinear(
model,
x,
range(1; stop = 2π, length = 8),
sin;
method = method,
)
JuMP.@objective(model, Max, z)
JuMP.optimize!(model)
@test JuMP.termination_status(model) == MOI.OPTIMAL
@test JuMP.value(x) ≈ 1.75474 rtol = 1e-4
@test JuMP.value(z) ≈ 0.98313 rtol = 1e-4
JuMP.@constraint(model, x ≤ 1.5z)
JuMP.optimize!(model)
@test JuMP.termination_status(model) == MOI.OPTIMAL
@test JuMP.value(x) ≈ 1.36495 rtol = 1e-4
@test JuMP.value(z) ≈ 0.90997 rtol = 1e-4
@test JuMP.objective_value(model) ≈ 0.90997 rtol = 1e-4
@test JuMP.objective_value(model) ≈ JuMP.value(z) rtol = 1e-4
end
end
@testset "Bivariate tests " begin
@testset "2D: $method, $pattern" for method in methods_2D,
pattern in patterns_2D
model = JuMP.Model(optimizer)
JuMP.@variable(model, x[1:2])
d = range(0; stop = 1, length = 8)
f = (x1, x2) -> 2 * (x1 - 1 / 3)^2 + 3 * (x2 - 4 / 7)^4
z = piecewiselinear(
model,
x[1],
x[2],
BivariatePWLFunction(d, d, f; pattern = pattern);
method = method,
)
JuMP.@objective(model, Min, z)
JuMP.optimize!(model)
@test JuMP.termination_status(model) == MOI.OPTIMAL
@test JuMP.value(x[1]) ≈ 0.285714 rtol = 1e-4
@test JuMP.value(x[2]) ≈ 0.571429 rtol = 1e-4
@test JuMP.value(z) ≈ 0.004535 rtol = 1e-3
@test JuMP.objective_value(model) ≈ 0.004535 rtol = 1e-3
@test JuMP.objective_value(model) ≈ JuMP.value(z) rtol = 1e-3
JuMP.@constraint(model, x[1] ≥ 0.6)
JuMP.optimize!(model)
@test JuMP.termination_status(model) == MOI.OPTIMAL
@test JuMP.value(x[1]) ≈ 0.6 rtol = 1e-4
@test JuMP.value(x[2]) ≈ 0.571428 rtol = 1e-4
@test JuMP.value(z) ≈ 0.148753 rtol = 1e-4
@test JuMP.objective_value(model) ≈ 0.148753 rtol = 1e-3
@test JuMP.objective_value(model) ≈ JuMP.value(z) rtol = 1e-3
end
end
# println("\nbivariate optimal IB scheme tests")
# @testset "2D: optimal IB, UnionJack" begin
# model = JuMP.Model(JuMP.with_optimizer(Cbc.Optimizer))
# JuMP.@variable(model, x)
# JuMP.@variable(model, y)
# d = range(0,stop=1,length=3)
# f = (x,y) -> 2*(x-1/3)^2 + 3*(y-4/7)^4
# z = piecewiselinear(model, x, y, BivariatePWLFunction(d, d, f, pattern=:UnionJack), method=:OptimalIB, subsolver=solver)
# JuMP.@objective(model, Min, z)
# JuMP.optimize!(model)
# @test JuMP.termination_status(model) == MOI.OPTIMAL
# @test JuMP.value(x) ≈ 0.5 rtol=1e-4
# @test JuMP.value(y) ≈ 0.5 rtol=1e-4
# @test JuMP.value(z) ≈ 0.055634 rtol=1e-3
# @test getobjectivevalue(model) ≈ 0.055634 rtol=1e-3
# @test getobjectivevalue(model) ≈ JuMP.value(z) rtol=1e-3
# JuMP.@constraint(model, x ≥ 0.6)
# JuMP.optimize!(model)
# @test JuMP.termination_status(model) == MOI.OPTIMAL
# @test JuMP.value(x) ≈ 0.6 rtol=1e-4
# @test JuMP.value(y) ≈ 0.5 rtol=1e-4
# @test JuMP.value(z) ≈ 0.222300 rtol=1e-3
# @test JuMP.objective_value(model) ≈ 0.222300 rtol=1e-3
# @test JuMP.objective_value(model) ≈ JuMP.value(z) rtol=1e-3
# end
| PiecewiseLinearOpt | https://github.com/jump-dev/PiecewiseLinearOpt.jl.git |
|
[
"MIT"
] | 0.4.2 | 59786d90d750f1c18029a3903e8c1bc49d0e55a8 | docs | 2984 | # PiecewiseLinearOpt
[](https://github.com/jump-dev/PiecewiseLinearOpt.jl/actions?query=workflow%3ACI)
[](https://codecov.io/gh/jump-dev/PiecewiseLinearOpt.jl)
A package for modeling optimization problems containing piecewise linear
functions. Current support is for (the graphs of) continuous univariate
functions.
This package is an accompaniment to a paper entitled
[_Nonconvex piecewise linear functions: Advanced formulations and simple modeling tools_](https://arxiv.org/abs/1708.00050),
by Joey Huchette and Juan Pablo Vielma.
This package offers helper functions for the
[JuMP algebraic modeling language](https://github.com/jump-dev/JuMP.jl).
Consider a piecewise linear function. The function is described in terms of the
breakpoints between pieces, and the function value at those breakpoints.
Consider a JuMP model
```julia
using JuMP, PiecewiseLinearOpt
m = Model()
@variable(m, x)
```
To model the graph of a piecewise linear function ``f(x)``, take ``d`` as some
set of breakpoints along the real line, and ``fd = [f(x) for x in d]`` as the
corresponding function values. You can model this function in JuMP using the
following function:
```julia
z = piecewiselinear(m, x, d, fd)
@objective(m, Min, z) # minimize f(x)
```
For another example, think of a piecewise linear approximation for the function
$f(x,y) = exp(x+y)$:
```julia
using JuMP, PiecewiseLinearOpt
m = Model()
@variable(m, x)
@variable(m, y)
z = piecewiselinear(m, x, y, 0:0.1:1, 0:0.1:1, (u,v) -> exp(u+v))
@objective(m, Min, z)
```
Current support is limited to modeling the graph of a continuous piecewise
linear function, either univariate or bivariate, with the goal of adding support
for the epigraphs of lower semicontinuous piecewise linear functions.
Supported univariate formulations:
* Convex combination (``:CC``)
* Multiple choice (``:MC``)
* Native SOS2 branching (``:SOS2``)
* Incremental (``:Incremental``)
* Logarithmic (``:Logarithmic``; default)
* Disaggregated Logarithmic (``:DisaggLogarithmic``)
* Binary zig-zag (``:ZigZag``)
* General integer zig-zag (``:ZigZagInteger``)
Supported bivariate formulations for entire constraint:
* Convex combination (``:CC``)
* Multiple choice (``:MC``)
* Dissaggregated Logarithmic (``:DisaggLogarithmic``)
Also, you can use any univariate formulation for bivariate functions as well.
They will be used to impose two axis-aligned SOS2 constraints, along with the
"6-stencil" formulation for the triangle selection portion of the constraint.
See the associated paper for more details. In particular, the following are also
acceptable bivariate formulation choices:
* Native SOS2 branching (``:SOS2``)
* Incremental (``:Incremental``)
* Logarithmic (``:Logarithmic``)
* Binary zig-zag (``:ZigZag``)
* General integer zig-zag (``:ZigZagInteger``)
| PiecewiseLinearOpt | https://github.com/jump-dev/PiecewiseLinearOpt.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 1199 |
using Documenter, Mango, Test, Logging
logger = Test.TestLogger(min_level=Info);
with_logger(logger) do
makedocs(
modules=[Mango],
format=Documenter.HTML(; prettyurls=get(ENV, "CI", nothing) == "true"),
authors="mango Team",
sitename="Mango.jl",
pages=Any["Home"=>"index.md",
"Getting Started"=>"getting_started.md",
"Agents"=>"agent.md",
"Container"=>"container.md",
"Roles"=>"role.md",
"Simulation"=>"simulation.md",
"Codecs"=>"encode_decode.md",
"Scheduling"=>"scheduling.md",
"Topologies"=>"topology.md",
"API"=>"api.md",
"Legals"=>"legals.md",],
repo="https://github.com/OFFIS-DAI/Mango.jl",
)
end
for record in logger.logs
@info record.message
# Check if @example blocks did not succeed -> fail then
if record.level == Warn && occursin("failed to run `@example` block", record.message)
throw("Some Documentation example did not work, check the logs and fix the error.")
end
end
deploydocs(
repo="github.com/OFFIS-DAI/Mango.jl.git",
push_preview=true,
devbranch="development"
) | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 628 | """
Placeholder for a short summary about mango.
"""
module Mango
include("util/error_handling.jl")
include("util/datastructures_util.jl")
include("util/scheduling.jl")
include("util/encode_decode.jl")
include("agent/api.jl")
include("container/api.jl")
include("agent/role.jl")
include("agent/core.jl")
include("world/core.jl")
include("container/protocol.jl")
include("container/tcp.jl")
include("container/mqtt.jl")
include("simulation/communication.jl")
include("simulation/tasks.jl")
include("container/simulation.jl")
include("container/core.jl")
include("world/topology.jl")
include("express/api.jl")
end # module
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 6130 | export Agent, send_message, send_tracked_message, reply_to, address, aid, send_and_handle_answer
"""
Supertype of all address types
"""
abstract type Address end
"""
Supertype of the Agent Base type representing an interface, on which methods
can be defined, which should be accessable from the outside, especially from
the roles contained in the specific agent.
"""
abstract type AgentInterface end
"""
Base-type for all agents in mango. Generally exists for type-safety and default
implementations across all agents.
"""
abstract type Agent <: AgentInterface end
function subscribe_message_handle(agent::AgentInterface, role::Any, condition::Any, handler::Any) end
"""
subscribe_send_handle(agent::AgentInterface, role::Any, handler::Any)
Used internally by the RoleContext to subscribe send handler to the agent.
"""
function subscribe_send_handle(agent::AgentInterface, role::Any, handler::Any) end
"""
subscribe_event_handle(agent::AgentInterface, role::Any, event_type::Any, event_handler::Any; condition::Function=(a, b) -> true)
Used internally by the RoleContext to subscribe to role agent events.
"""
function subscribe_event_handle(agent::AgentInterface, role::Any, event_type::Any, event_handler::Any; condition::Function=(a, b) -> true) end
"""
emit_event_handle(agent::AgentInterface, role::Any, event::Any; event_type::Any=nothing)
Used internally by the RoleContext to subscribe to role agent events.
"""
function emit_event_handle(agent::AgentInterface, role::Any, event::Any; event_type::Any=nothing) end
"""
get_model_handle(agent::AgentInterface, type::DataType)
Used internally by the RoleContext to subscribe to role agent events.
"""
function get_model_handle(agent::AgentInterface, type::DataType) end
"""
address(agent)
Return the agent address of the agent as [`AgentAddress`](@ref) or [`MQTTAddress`](@ref) depending on the protocol.
"""
function address(agent::AgentInterface) end
"""
aid(agent)
Return the aid of the agent.
"""
function aid(agent::AgentInterface) end
"""
send_message(
agent::AgentInterface,
content::Any,
agent_address::Address;
kwargs...,
)
Send a message with the content `content` to the agent represented by `agent_address`.
This method will always set a sender_id. Additionally, further keyword arguments can be defined to fill the
internal meta data of the message.
"""
function send_message(
agent::AgentInterface,
content::Any,
agent_address::Address;
kwargs...,
)
@warn "The API send_message definition has been called, this should never happen. There is most likely an import error."
end
"""
send_tracked_message(
agent::AgentInterface,
content::Any,
agent_address::Address;
response_handler::Function=(agent, message, meta) -> nothing,
calling_object::Any=nothing,
kwargs...,
)
Send a message with the content `content` to the agent represented by `agent_address`. This function will set
a generated tracking_id to the address, which allows the identification of the dialog.
It is possible to define a `response_handler`, to which a function can be assigned, which handles the answer
to this message call. Note that the resonding agent needs to use the same tracking id in the response, ideally
[`reply_to`](@ref) is used to achieve this automatically.
This method will always set a sender_id. Additionally, further keyword arguments can be defines to fill the
internal meta data of the message.
"""
function send_tracked_message(
agent::AgentInterface,
content::Any,
agent_address::Address;
response_handler::Function=(agent, message, meta) -> nothing,
calling_object::Any=nothing,
kwargs...,
)
@warn "The API send_tracked_message definition has been called, this should never happen. There is most likely an import error."
end
"""
send_and_handle_answer(
response_handler::Function,
agent::AgentInterface,
content::Any,
agent_address::Address;
calling_object::Any=nothing,
kwargs...)
Convenience method for sending tracked messages with response handler to the answer.
Sends a tracked message with a required response_handler to enable to use the syntax
```
send_and_handle_answer(...) do agent, message, meta
# handle the answer
end
```
"""
function send_and_handle_answer(
response_handler::Function,
agent::AgentInterface,
content::Any,
agent_address::Address;
calling_object::Any=nothing,
kwargs...)
@warn "The API send_and_handle_answer definition has been called, this should never happen. There is most likely an import error."
end
"""
reply_to(
agent::AgentInterface,
content::Any,
received_meta::AbstractDict,
)
Convenience method to reply to a received message using the meta the agent received. This reduces the regular `send_message` as response
`send_message(agent, "Pong", AgentAddress(aid=meta["sender_id"], address=meta["sender_addr"]))`
to
`reply_to(agent, "Pong", meta)`
Furthermore it guarantees that agent address (including the tracking id, which is part of the address!) is correctly passed to the mango
container.
"""
function reply_to(
agent::AgentInterface,
content::Any,
received_meta::AbstractDict,
)
@warn "The API reply_to definition has been called, this should never happen. There is most likely an import error."
end
"""
forward_to(agent, content, forward_to_address, received_meta; kwargs...)
Forward the message to a specific agent using the metadata received on handling
the message. This method essentially simply calls send_message on the input given, but
also adds and fills the correct metadata fields to mark the message as forwarded.
For this the following meta data is set.
* 'forwarded=true',
* 'forwarded_from_address=address of the original sender',
* 'forwarded_from_id=id of the original sender'
"""
function forward_to(agent::AgentInterface,
content::Any,
forward_to_address::Address,
received_meta::AbstractDict;
kwargs...)
@warn "The API forward_to definition has been called, this should never happen. There is most likely an import error."
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 15473 | export @agent,
AgentContext,
AgentRoleHandler,
handle_message,
add,
schedule,
stop_and_wait_for_all_tasks,
shutdown,
on_ready,
on_start,
roles,
forward_to,
add_forwarding_rule,
delete_forwarding_rule,
ForwardingRule,
service_of_type,
add_service!,
services
using UUIDs
using Dates: Dates
FORWARDED_FROM_ADDR = "forwarded_from_address"
FORWARDED_FROM_ID = "forwarded_from_id"
"""
Context of the agent. Represents the environment for the specific agent. Therefore it includes a
connection to the container, including all functions used for interacting with the environment
for the agent.
"""
struct AgentContext
container::ContainerInterface
end
"""
Internal data regarding the roles.
"""
struct AgentRoleHandler
roles::Vector{Role}
handle_message_subs::Vector{Tuple{Role,Function,Function}}
send_message_subs::Vector{Tuple{Role,Function}}
event_subs::Dict{Any,Vector{Tuple{Role,Function,Function}}}
models::Dict{DataType,Any}
end
struct ForwardingRule
from_address::AgentAddress
to_address::AgentAddress
forward_replies::Bool
end
"""
All baseline fields added by the @agent macro are listed in this vector.
They are added in the same order defined here.
"""
AGENT_BASELINE_FIELDS::Vector = [
:(lock::ReentrantLock = ReentrantLock()),
:(context::Union{Nothing,AgentContext} = nothing),
:(role_handler::Union{AgentRoleHandler} = AgentRoleHandler(Vector(), Vector(), Vector(), Dict(), Dict())),
:(scheduler::AbstractScheduler = Scheduler()),
:(aid::Union{Nothing,String} = nothing),
:(transaction_handler::Dict{String,Tuple} = Dict{String,Tuple}()),
:(forwarding_rules::Vector{ForwardingRule} = Vector{ForwardingRule}()),
:(services::Dict{DataType,Any} = Dict{DataType,Any}())
]
"""
Macro for defining an agent struct. Expects a struct definition
as argument.
The macro does 3 things:
1. It adds all baseline fields, defined in `AGENT_BASELINE_FIELDS`
(the agent context `context`, the role handler `role_handler`, and the `aid`)
2. It adds the supertype `Agent` to the given struct.
3. It applies [`@with_def`](@ref) for default construction, the baseline fields are assigned
to default values
# Example
For example the usage could like this.
```julia
@agent struct MyAgent
my_own_field::String
end
# results in
@with_def mutable struct MyAgent <: Agent
# baseline fields...
my_own_field::String
my_own_field_with_default::String = "Default"
end
# so you would construct your agent like this
my_agent = MyAgent("own value", my_own_field_with_default="OtherValue")
```
"""
macro agent(struct_def)
struct_head = struct_def.args[2]
struct_name = struct_head
if typeof(struct_name) != Symbol
struct_name = struct_head.args[1]
end
struct_fields = struct_def.args[3].args
# Add the agents baseline fields
for field in reverse(AGENT_BASELINE_FIELDS)
pushfirst!(struct_fields, field)
end
# Create the new struct definition
new_struct_def = Expr(:macrocall, Symbol("@with_def"), LineNumberNode(0, Symbol("none")), Expr(
:struct,
true,
Expr(:(<:), struct_head, :(Agent)),
Expr(:block, struct_fields...),
))
esc(Expr(:block, new_struct_def))
end
function build_forwarded_address_from_meta(meta::AbstractDict)
return AgentAddress(aid=meta["reply_to_forwarded_from_id"], address=meta["reply_to_forwarded_from_address"], tracking_id=get(meta, TRACKING_ID, nothing))
end
"""
Internal API used by the container to dispatch an incoming message to the agent.
In this function the message will be handed over to the different handlers in the
agent.
"""
function dispatch_message(agent::Agent, message::Any, meta::AbstractDict)
# check if auto forwarding is applicable
sender_addr = get(meta, SENDER_ADDR, nothing)
sender_id = get(meta, SENDER_ID, nothing)
forwarded = false
for rule::ForwardingRule in agent.forwarding_rules
if rule.from_address.aid == sender_id && rule.from_address.address == sender_addr
wait(forward_to(agent, message, rule.to_address, meta))
forwarded = true
end
# if reply to a forwarded message and replies shall be forwarded, forward this message to the original sender
if rule.to_address.address == sender_addr && rule.to_address.aid == sender_id && get(meta, "reply_to_forwarded", false) && rule.forward_replies
wait(forward_to(agent, message, build_forwarded_address_from_meta(meta), meta))
forwarded = true
end
end
if forwarded
return
end
lock(agent.lock) do
# check if part of a transaction
if haskey(meta, TRACKING_ID) && haskey(agent.transaction_handler, meta[TRACKING_ID])
caller, response_handler = agent.transaction_handler[meta[TRACKING_ID]]
delete!(agent.transaction_handler, meta[TRACKING_ID])
response_handler(caller, message, meta)
else
for role in agent.role_handler.roles
handle_message(role, message, meta)
end
for (role, call, condition) in agent.role_handler.handle_message_subs
if condition(message, meta)
call(role, message, meta)
end
end
handle_message(agent, message, meta)
end
end
end
"""
handle_message(agent::Agent, message::Any, meta::Any)
Defines a function for an agent, which will be called when a message is dispatched
to the agent. This methods will be called with any arriving message (according to
the multiple dispatch of julia).
"""
function handle_message(agent::Agent, message::Any, meta::Any)
# do nothing by default
end
function notify_start(agent::Agent)
on_start(agent)
for role in roles(agent)
on_start(role)
end
end
function notify_ready(agent::Agent)
on_ready(agent)
for role in roles(agent)
on_ready(role)
end
end
"""
on_start(agent::Agent)
Lifecycle Hook-in function called when the container of the agent has been started,
depending on the container type it may not be called (if there is no start at all,
f.e. the simulation container)
"""
function on_start(agent::Agent)
# do nothing by default
end
"""
on_ready(agent::Agent)
Lifecycle Hook-in function called when the agent system as a whole is ready, the
hook-in has to be manually activated using notify_ready(container::Container). If you use
the `activate` function, it is called automatically.
"""
function on_ready(agent::Agent)
# do nothing by default
end
function aid(agent::Agent)
return agent.aid
end
"""
add(agent::Agent, role::Role)
Add a role to the agent. This will add the role
to the internal RoleHandler of the agent and it
will bind the RoleContext to the role, which enables
the role to interact with its environment.
"""
function add(agent::Agent, role::Role)
push!(agent.role_handler.roles, role)
bind_context(role, RoleContext(agent))
end
"""
roles(agent)
Return all roles of the given agent
"""
function roles(agent::Agent)
return agent.role_handler.roles
end
"""
shutdown(agent)
Will be called on shutdown of the container, in which
the agent is living
"""
function shutdown(agent::Agent)
for role in agent.role_handler.roles
shutdown(role)
end
stop_and_wait_for_all_tasks(agent.scheduler)
end
function subscribe_message_handle(
agent::Agent,
role::Role,
condition::Function,
handler::Function,
)
push!(agent.role_handler.handle_message_subs, (role, condition, handler))
end
function subscribe_send_handle(agent::Agent, role::Role, handler::Function)
push!(agent.role_handler.send_message_subs, (role, handler))
end
function subscribe_event_handle(agent::Agent, role::Role, event_type::Any, event_handler::Function; condition::Function=(a, b) -> true)
if !haskey(agent.role_handler.event_subs, event_type)
agent.role_handler.event_subs[event_type] = Vector()
end
push!(agent.role_handler.event_subs[event_type], (role, condition, event_handler))
end
function emit_event_handle(agent::Agent, src::Role, event::Any; event_type::Any=nothing)
key = !isnothing(event_type) ? event_type : typeof(event)
if haskey(agent.role_handler.event_subs, key)
for (role, condition, func) in agent.role_handler.event_subs[key]
if condition(src, event)
func(role, src, event, event_type)
end
end
end
for role in roles(agent)
handle_event(role, src, event, event_type=event_type)
end
end
function get_model_handle(agent::Agent, type::DataType)
if !haskey(agent.role_handler.models, type)
agent.role_handler.models[type] = type()
end
return agent.role_handler.models[type]
end
"""
add_forwarding_rule(agent, from_addr::AgentAddress, to_address::AgentAddress, forward_replies::Bool)
Add a rule for message forwarding.
After calling the agent will auto-forward every message coming from `from_addr` to
`to_address`. If forward_replies is set, all replies from `to_address` are forwarded
back to `from_addr`.
"""
function add_forwarding_rule(agent::Agent, from_addr::AgentAddress, to_address::AgentAddress, forward_replies::Bool)
push!(agent.forwarding_rules, ForwardingRule(from_addr, to_address, forward_replies))
end
"""
delete_forwarding_rule(agent, from_addr::AgentAddress, to_address::Union{Nothing,AgentAddress})
Delete an added forwarding rule. If `to_address` is not set, all rules are removed matching
`from_addr`. If it set, both addresses need to match.
"""
function delete_forwarding_rule(agent::Agent, from_addr::AgentAddress, to_address::Union{Nothing,AgentAddress})
for i in length(agent.forwarding_rules):-1:1
rule = agent.forwarding_rules[i]
if rule.from_address == from_addr && (isnothing(to_address) || to_address == rule.to_address)
deleteat!(agent.forwarding_rules, i)
end
end
end
"""
schedule(f::Function, agent::Agent, data::TaskData)
Delegates to the scheduler `Scheduler`
"""
function schedule(f::Function, agent::Agent, data::TaskData)
schedule(f, agent.scheduler, data)
end
"""
stop_and_wait_for_all_tasks(agent::Agent)
Delegates to the scheduler `Scheduler`
"""
function stop_and_wait_for_all_tasks(agent::Agent)
stop_and_wait_for_all_tasks(agent.scheduler)
end
"""
stop_task(agent::Agent, t::Task)
Delegates to the scheduler `Scheduler`
"""
function stop_task(agent::Agent, t::Task)
stop_task(agent.scheduler, t)
end
"""
wait_for_all_tasks(agent::Agent)
Delegates to the scheduler `Scheduler`
"""
function wait_for_all_tasks(agent::Agent)
wait_for_all_tasks(agent.scheduler)
end
"""
stop_all_tasks(agent::Agent)
Delegates to the scheduler `Scheduler`
"""
function stop_all_tasks(agent::Agent)
stop_all_tasks(agent.scheduler)
end
function address(agent::Agent)
addr::Any = nothing
if !isnothing(agent.context)
addr = protocol_addr(agent.context.container)
end
return AgentAddress(aid=aid(agent), address=addr)
end
function send_message(
agent::Agent,
content::Any,
agent_adress::AgentAddress;
kwargs...,
)
for (role, handler) in agent.role_handler.send_message_subs
handler(role, content, agent_adress; kwargs...)
end
return send_message(
agent.context.container,
content,
agent_adress,
agent.aid;
kwargs...,
)
end
function send_message(
agent::Agent,
content::Any,
mqtt_address::MQTTAddress;
kwargs...,
)
for (role, handler) in agent.role_handler.send_message_subs
handler(role, content, mqtt_address; kwargs...)
end
return send_message(
agent.context.container,
content,
mqtt_address;
kwargs...,
)
end
function send_tracked_message(
agent::Agent,
content::Any,
agent_address::AgentAddress;
response_handler::Union{Function,Nothing}=nothing,
calling_object::Any=nothing,
kwargs...,
)
tracking_id = string(uuid1())
if !isnothing(agent_address.tracking_id)
tracking_id = agent_address.tracking_id
end
if !isnothing(response_handler)
caller = agent
if !isnothing(calling_object)
caller = calling_object
end
agent.transaction_handler[tracking_id] = (caller, response_handler)
end
return send_message(agent, content, AgentAddress(agent_address.aid, agent_address.address, tracking_id); kwargs...)
end
function send_and_handle_answer(
response_handler::Function,
agent::Agent,
content::Any,
agent_address::AgentAddress;
calling_object::Any=nothing,
kwargs...)
return send_tracked_message(agent, content, agent_address; response_handler=response_handler,
calling_object=calling_object, kwargs...)
end
function reply_to(agent::Agent,
content::Any,
received_meta::AbstractDict;
response_handler::Union{Function,Nothing}=nothing,
calling_object::Any=nothing,
kwargs...)
return send_tracked_message(agent, content, AgentAddress(received_meta[SENDER_ID],
received_meta[SENDER_ADDR],
get(received_meta, TRACKING_ID, nothing));
response_handler=response_handler,
calling_object=calling_object,
reply=true,
reply_to_forwarded=get(received_meta, "forwarded", false),
reply_to_forwarded_from_address=get(received_meta, FORWARDED_FROM_ADDR, nothing),
reply_to_forwarded_from_id=get(received_meta, FORWARDED_FROM_ID, nothing),
kwargs...)
end
function forward_to(agent::Agent,
content::Any,
forward_to_address::AgentAddress,
received_meta::AbstractDict;
kwargs...)
return send_message(agent, content, forward_to_address; forwarded=true,
forwarded_from_address=received_meta[SENDER_ADDR],
forwarded_from_id=received_meta[SENDER_ID])
end
"""
services(agent)::Dict{DataType,Any}
Return a list of services, which were added to the agent.
"""
function services(agent::Agent)::Dict{DataType,Any}
return agent.services
end
"""
service_of_type(agent, type::Type{T}, default=nothing)::Union{T,Nothing} where {T}
Return the current agent service of the type `type`.
If a default is set, this default service will be added to the agent as service of te type `type. The
function is especially useful if you want to extend the functionality of the agent without
having to change the internals of the agent, as this functions enables the user to add
arbitrary data to the agent on which functions can be defined.
"""
function service_of_type(agent::Agent, type::Type{T}, default::Union{T,Nothing}=nothing)::Union{T,Nothing} where {T}
for pair in services(agent)
if isa(pair[1], type) || pair[1] == type
return pair[2]
end
end
if !isnothing(default)
add_service!(agent, default)
end
return default
end
"""
add_service!(agent, service)
Add a service to the agent. Every service can exists exactly one time (stored by type).
"""
function add_service!(agent::Agent, service::Any)
agent.services[typeof(service)] = service
end
"""
Base.getindex(agent::T, index::Int) where {T<:Agent}
Return the `index`'th role of the agent.
"""
function Base.getindex(agent::T, index::Int) where {T<:Agent}
return roles(agent)[index]
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 9669 | export Role,
RoleContext,
handle_event,
@role,
@shared,
subscribe_message,
subscribe_send,
bind_context,
emit_event,
get_model,
subscribe_event,
setup
"""
Defines the type Role, which is the common base types for all roles in mango.
A Role is a bundled behavivor of an agent, which shall fulfill exactly one
responsibility of an agent - the role. Technically speaking roles are the
way to implement the composition pattern for agents, and to introduce
modular archetypes, which shall be reused in different contexts.
"""
abstract type Role end
"""
The `RoleContext` connects the role with its environment, which is
mostly its agents. This is abstracted using the `AgentInterface`.
"""
mutable struct RoleContext
agent::AgentInterface
end
"""
List of all baseline fields of every role, which will be inserted
by the macro @role.
"""
ROLE_BASELINE_FIELDS::Vector = [:(context::Union{RoleContext,Nothing} = nothing),
:(shared_vars::Vector{Any} = Vector())]
"""
Macro for defining a role struct. Expects a struct definition
as argument.
The macro does 3 things:
1. It adds all baseline fields, defined in `ROLE_BASELINE_FIELDS`
(the role context)
2. It adds the supertype `Role` to the given struct.
3. It applies [`@with_def`](@ref) for default construction, the baseline fields are assigned
to default values
For example the usage could like this.
```julia
@role struct MyRole
my_own_field::String
end
# results in
@with_def mutable struct MyRole <: Role
# baseline fields...
my_own_field::String
my_own_field_with_default::String = "Default"
end
# so youl would construct your role like this
my_roel = MyRole("own value", my_own_field_with_default="OtherValue")
```
"""
macro role(struct_def)
Base.remove_linenums!(struct_def)
struct_head = struct_def.args[2]
struct_name = struct_head
if typeof(struct_name) != Symbol
struct_name = struct_head.args[1]
end
struct_fields = struct_def.args[3].args
# Add the roles baseline fields
for field in reverse(ROLE_BASELINE_FIELDS)
pushfirst!(struct_fields, field)
end
# Remove all @shared declarations from the struct definition
shared_names = []
new_struct_fields = []
modified_struct_fields = Vector(struct_fields)
for i in length(struct_fields):-1:1
struct_field = struct_fields[i]
name = struct_field.args[1]
if name == Symbol("@shared")
struct_field = struct_fields[i+1]
field_name = struct_field.args[1]
field_type = struct_field.args[2]
# evaluates to field_name::field_type = field_type()
new_expr_decl = Expr(:(=), Expr(:(::), field_name, field_type), Expr(:call, Symbol(field_type)))
push!(new_struct_fields, new_expr_decl)
push!(shared_names, Expr(:tuple, String(field_name), field_type))
deleteat!(modified_struct_fields, i + 1)
deleteat!(modified_struct_fields, i)
end
end
struct_fields = modified_struct_fields
# Create the new struct definition
new_struct_def = Expr(:macrocall, Symbol("@with_def"), LineNumberNode(0, Symbol("none")), Expr(
:struct,
true,
Expr(:(<:), struct_head, :(Role)),
Expr(:block, cat(struct_fields, new_struct_fields, dims=(1, 1))...),
))
esc(Expr(:block, new_struct_def))
end
"""
Mark the field as shared across roles.
This only works on structs with empty default constructor. Internally the marked field will be initialized
with a model created by [`get_model`](@ref). The model will be set when the Role is added to an agent.
# Example
```julia
@kwdef struct Model
field::Int = 0
end
@role struct MyRole
@shared
my_model::Model # per agent the exact same in every agent.
end
```
"""
macro shared(field_declaration)
return esc(field_declaration)
end
"""
setup(role::Role)
Hook-in function to setup the role, after it has been
added to its agent.
"""
function setup(role::Role)
# default nothing
end
"""
Default function for arriving messages, which get dispatched to the role.
This function will be called for every message arriving at the agent of the role.
"""
function handle_message(role::Role, message::Any, meta::Any)
# do nothing by default
end
"""
handle_event(role::Role, src::Role, event::Any; event_type::Any)
Default function for arriving events, which get dispatched to the role.
"""
function handle_event(role::Role, src::Role, event::Any; event_type::Any)
# do nothing by default
end
"""
Internal function, used to initialize to role for a specified agent
"""
function bind_context(role::Role, context::RoleContext)
role.context = context
for shared_var in role.shared_vars
shared_model = get_model(role, eval(shared_var[2]))
setproperty!(role, Symbol(shared_var[1]), shared_model)
end
setup(role)
end
"""
context(role::Role)
Return the context of role
"""
function context(role::Role)
return role.context
end
function shutdown(role::Role)
# default nothing
end
function on_start(role::Role)
# do nothing by default
end
function on_ready(role::Role)
# do nothing by default
end
"""
subscribe_message(role::Role, handler::Function, condition::Function)
Subscribe a message handler function (it need to have the signature (role, message, meta))
to the message dispatching. This handler function will be called everytime the given
condition function ((message, meta) -> boolean) evaluates to true when a message arrives
at the roles agent.
"""
function subscribe_message(role::Role, handler::Function, condition::Function)
subscribe_message_handle(role.context.agent, role, handler, condition)
end
"""
subscribe_send(role::Role, handler::Function)
Subscribe a `send_message` hook in function (signature, (role, content, receiver_id, receiver_addr; kwargs...)) to the
message sending. The hook in function will be called every time a message is sent by the agent.
"""
function subscribe_send(role::Role, handler::Function)
subscribe_send_handle(role.context.agent, role, handler)
end
"""
subscribe_event(role::Role, event_type::Any, event_handler::Any, condition::Function)
Subscribe to specific types of events.
The types of events are determined by the `condition` function (accepting `src` and `event`) and
by the `event_type`.
# Example
```julia
struct MyEvent end
function custom_handler(role::Role, src::Role, event::Any, event_type::Any)
# do your thing
end
subscribe_event(my_role, MyEvent, custom_handler, (src, event) -> aid(src) == "agent0")
```
"""
function subscribe_event(role::Role, event_type::Any, event_handler::Any, condition::Function=(a, b) -> true)
subscribe_event_handle(role.context.agent, role, event_type, event_handler; condition=condition)
end
"""
emit_event(role::Role, event::Any; event_type::Any=nothing)
Emit an event to their subscriber.
"""
function emit_event(role::Role, event::Any; event_type::Any=nothing)
emit_event_handle(role.context.agent, role, event, event_type=event_type)
end
"""
get_model(role::Role, type::DataType)
Get a shared model from the pool. If the model does not exist yet, it will be created.
Only types with default constructor are allowed!
# Example
```julia
@kwdef struct ExampleModel
my_field::Int = 0
end
role = ExampleRole()
model::ExampleModel = get_model(role, ExampleModel)
model.my_field = 1
model2::ExampleModel = get_model(role, ExampleModel)
# model == model2, it will also be the same for every role!
```
"""
function get_model(role::Role, type::DataType)
get_model_handle(role.context.agent, type)
end
function schedule(f::Function, role::Role, data::TaskData)
schedule(f, role.context.agent, data)
end
function aid(role::Role)
return address(role.context.agent).aid
end
function address(role::Role)
return address(role.context.agent)
end
function add_forwarding_rule(role::Role, from_addr::AgentAddress, to_address::AgentAddress, forward_replies::Bool)
add_forwarding_rule(role.context.agent, from_addr, to_address, forward_replies)
end
function delete_forwarding_rule(role::Role, from_addr::AgentAddress, to_address::Union{Nothing,AgentAddress})
delete_forwarding_rule(role.context.agent, from_addr, to_address)
end
function send_message(
role::Role,
content::Any,
agent_adress::AgentAddress;
kwargs...,
)
return send_message(role.context.agent, content, agent_adress; kwargs...)
end
function send_tracked_message(
role::Role,
content::Any,
agent_adress::AgentAddress;
response_handler::Function=(role, message, meta) -> nothing,
kwargs...,
)
return send_tracked_message(role.context.agent, content, agent_adress; response_handler=response_handler, calling_object=role, kwargs...)
end
function send_and_handle_answer(
response_handler::Function,
role::Role,
content::Any,
agent_address::AgentAddress;
kwargs...)
return send_and_handle_answer(response_handler, role.context.agent, content, agent_address;
calling_object=role, kwargs...)
end
function reply_to(role::Role,
content::Any,
received_meta::AbstractDict;
response_handler::Function=(agent, message, meta) -> nothing,
kwargs...)
return reply_to(role.context.agent, content, received_meta; response_handler=response_handler, calling_object=role, kwargs...)
end
function forward_to(role::Role,
content::Any,
forward_to_address::AgentAddress,
received_meta::AbstractDict;
kwargs...)
return forward_to(role.context.agent, content, forward_to_address, received_meta; kwargs...)
end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 3362 |
export ContainerInterface, send_message, register, start, shutdown, protocol_addr, agents, Address, AgentAddress, MQTTAddress, SENDER_ADDR, SENDER_ID, TRACKING_ID
"""
Key for the sender address in the meta dict
"""
SENDER_ADDR::String = "sender_addr"
"""
Key for the sender in the meta dict
"""
SENDER_ID::String = "sender_id"
"""
Key for the tracking number used for dialogs in the meta dict
"""
TRACKING_ID::String = "tracking_id"
"""
Supertype of every container implementation. This acts as an interface to be used by the agents
in their contexts.
"""
abstract type ContainerInterface end
"""
Default AgentAddress base type, where the agent identifier is based on the container created agent id (aid).
Used with the TCP protocol.
"""
@kwdef struct AgentAddress <: Address
aid::Union{String,Nothing}
address::Any = nothing
tracking_id::Union{String,Nothing} = nothing
end
"""
Connection information for an MQTT topic on a given broker.
Used with the MQTT protocol.
"""
@kwdef struct MQTTAddress <: Address
broker::Any = nothing
topic::String
end
"""
send_message(
container::ContainerInterface,
content::Any,
address::Address,
sender_id::Union{Nothing,String}=nothing;
kwargs...,
)
Send a message `message` using the given container `container`
to the given address. Additionally, further keyword
arguments can be defines to fill the internal meta data of the message.
"""
function send_message(
container::ContainerInterface,
content::Any,
address::Address,
sender_id::Union{Nothing,String}=nothing;
kwargs...,
)
@warn "The API send_message definition has been called, this should never happen. There is most likely an import error."
end
"""
protocol_addr(container)
Return technical address of the container.
"""
function protocol_addr(container::ContainerInterface) end
"""
start(container)
Start the container. It is recommended to use [`activate`](@ref) instead of starting manually.
What exactly happend highly depends on the protocol and the container implmentation.
For example, for TCP the container binds on IP and port, and the listening loop started.
"""
function start(container::ContainerInterface) end
"""
shutdown(container)
Shutdown the container. Here all loops are closed, resources freed. It is recommended to use [`activate`](@ref)
instead of shutting down manually.
"""
function shutdown(container::ContainerInterface) end
"""
register(
container,
agent,
suggested_aid::Union{String,Nothing}=nothing;
kwargs...,
)
Register the agent to the container. Retun the agent itself for convenience.
Normally the aid is generated, however it is possible to suggest an aid, which will be used
if it has not been used yet and if it is not conflicting with the default naming pattern (agent0, agent1, ...)
"""
function register(
container::ContainerInterface,
agent::AgentInterface,
suggested_aid::Union{String,Nothing}=nothing;
kwargs...,
) end
"""
agents(container)
Return the agents of the container. The agents have a fixed order.
"""
function agents(container::ContainerInterface) end
"""
notify_ready(container::Container)
Mark the agent system as ready.
"""
function notify_ready(container::ContainerInterface)
for agent in values(agents(container))
notify_ready(agent)
end
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 6980 | export Container, notify_ready
using Parameters
using OrderedCollections
using Base.Threads
# id key for the receiver
RECEIVER_ID::String = "receiver_id"
# prefix for the generated aid's
AGENT_PREFIX::String = "agent"
# id key for mqtt broker
BROKER::String = "broker"
# id key for mqtt topic
TOPIC::String = "topic"
"""
The default container struct, representing the container as actor. The container is implemented
by composition. This means the container consists of different implementations of base types, which
define the behavior of the container itself. That being said, the same container generally
able to send messages via different protocols using different codecs.
"""
@kwdef mutable struct Container <: ContainerInterface
agents::OrderedDict{String,Agent} = OrderedDict()
agent_counter::Integer = 0
protocol::Union{Nothing,Protocol} = nothing
codec::Any = (encode, decode)
shutdown::Bool = false
loop::Any = nothing
tasks::Any = nothing
end
function agents(container::Container)::Vector{Agent}
return [t[2] for t in collect(container.agents)]
end
"""
Internal representation of a message in mango
"""
struct MangoMessage
content::Any
meta::Dict{String,Any}
end
"""
Process the message data after rawly receiving them.
"""
function process_message(container::Container, msg_data::Any, sender_addr::Any; receivers=nothing)
msg = container.codec[2](msg_data)
content, meta = msg["content"], msg["meta"]
if haskey(meta, SENDER_ADDR)
meta[SENDER_ADDR] = parse_id(container.protocol, meta[SENDER_ADDR])
else
meta[SENDER_ADDR] = nothing
end
forward_message(container, content, meta; receivers=receivers)
end
function protocol_addr(container::Container)
if isnothing(container.protocol)
return nothing
end
return id(container.protocol)
end
function start(container::Container)
if !isnothing(container.protocol)
container.loop, container.tasks = init(
container.protocol,
() -> container.shutdown,
(msg_data, sender_addr; receivers=nothing) -> process_message(container, msg_data, sender_addr; receivers=receivers),
)
end
for agent in values(container.agents)
notify_start(agent)
end
end
function shutdown(container::Container)
container.shutdown = true
if !isnothing(container.protocol)
close(container.protocol)
end
if !isnothing(container.tasks)
for task in container.tasks
wait(task)
end
end
for agent in values(container.agents)
shutdown(agent)
end
end
function register(
container::Container,
agent::Agent,
suggested_aid::Union{String,Nothing}=nothing;
kwargs...,
)
actual_aid::String = "$AGENT_PREFIX$(container.agent_counter)"
if !isnothing(suggested_aid) && !haskey(container.agents, suggested_aid)
actual_aid = suggested_aid
end
container.agents[actual_aid] = agent
agent.aid = actual_aid
agent.context = AgentContext(container)
container.agent_counter += 1
if !isnothing(container.protocol)
notify_register(container.protocol, actual_aid; kwargs...)
end
return agent
end
"""
Internal function of the container, which forward the message to the correct agent in the container.
At this point it has already been evaluated the message has to be routed to an agent in control of
the container.
"""
function forward_message(container::Container, msg::Any, meta::AbstractDict; receivers=nothing)
# if not multicast: single cast
if isnothing(receivers)
receivers = RECEIVER_ID in keys(meta) ? [meta[RECEIVER_ID]] : nothing
end
send_tasks = []
if isnothing(receivers)
@warn "Got a message missing an agent id!"
else
for receiver in receivers
if !haskey(container.agents, receiver)
@warn "Container at $(protocol_addr(container)) has no agent with id: $receiver. Known agents are: $(container.agents)"
else
agent = container.agents[receiver]
@debug "Dispatch a message to agent $(aid(agent))" typeof(msg) get(meta, SENDER_ID, "") protocol_addr(container)
push!(send_tasks, @spawnlog dispatch_message(agent, msg, meta))
end
end
end
# return the single wait task syncing all sends
# so we can wait for the full message action to be done outside
if isempty(send_tasks)
# return an empty finished task so this function
# can always be waited on
return @async begin end
end
return @sync(send_tasks)[1]
end
function to_external_message(content::Any, meta::AbstractDict)
return MangoMessage(content, meta)
end
function send_message(
container::Container,
content::Any,
agent_adress::AgentAddress,
sender_id::Union{Nothing,String}=nothing;
kwargs...,
)
receiver_id = agent_adress.aid
receiver_addr = agent_adress.address
tracking_id = agent_adress.tracking_id
meta = OrderedDict{String,Any}()
for (key, value) in kwargs
meta[string(key)] = value
end
meta[RECEIVER_ID] = receiver_id
meta[SENDER_ID] = sender_id
meta[TRACKING_ID] = tracking_id
if !isnothing(container.protocol)
meta[SENDER_ADDR] = id(container.protocol)
else
meta[SENDER_ADDR] = nothing
end
if isnothing(receiver_addr) || receiver_addr == id(container.protocol)
return forward_message(container, content, meta)
end
@debug "Send a message to ($receiver_id, $receiver_addr), from $sender_id" typeof(content)
return @spawnlog send(
container.protocol,
receiver_addr,
container.codec[1](to_external_message(content, meta)),
)
end
"""
send_message(
container::Container,
content::Any,
mqtt_address::MQTTAddress,
kwargs...,
)
Send message version for MQTT topics.
Note that there is no local message forwarding here because messages always get
pushed to a broker and are not directly addressed to an agennt.
"""
function send_message(
container::Container,
content::Any,
mqtt_address::MQTTAddress,
kwargs...,
)
broker = mqtt_address.broker
topic = mqtt_address.topic
meta = OrderedDict{String,Any}()
for (key, value) in kwargs
meta[string(key)] = value
end
meta[BROKER] = broker
meta[TOPIC] = topic
if !isnothing(container.protocol)
meta[SENDER_ADDR] = id(container.protocol)
end
return @spawnlog send(
container.protocol,
topic,
container.codec[1](to_external_message(content, meta)),
)
end
"""
Base.getindex(container::Container, index::String)
Return the agent indexed by `index` (aid).
"""
function Base.getindex(container::Container, index::String)
return container.agents[index]
end
function Base.getindex(container::Container, index::Int)
return agents(container)[index]
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 6268 | export MQTTProtocol,
get_messages_channel,
disconnect,
subscribe
import Mosquitto
using Mosquitto: Client, get_messages_channel, get_connect_channel, publish, disconnect
using Sockets: InetAddr
"""
Protocol that abstracts a [Mosquitto.jl](https://github.com/denglerchr/Mosquitto.jl) client for Mango agents.
# Creation
MQTTProtocol(client_id::String, broker_addr::InetAddr)
Create an MQTT client that connects to the broker at `broker_addr` with a `client_id`.
# Fields
* client - Mosquitto.jl client
* broker_addr - address of the MQTT broker to connect to
* connected - internal flag indicating connection status
* active - internal flag indicating listen loop activity
* msg_channel - message channel of the MQTT client
* conn_channel - connection channel of the MQTT client
* topic_to_aid - internal dictionary to track which registered agent is subscribed to which topic
"""
mutable struct MQTTProtocol <: Protocol{String}
client::Client
broker_addr::InetAddr
connected::Bool
active::Bool
msg_channel::Channel
conn_channel::Channel
topic_to_aid::Dict{String,Vector{String}}
function MQTTProtocol(client_id::String, broker_addr::InetAddr)
# Have to cast types for the MQTT client constructor.
c = Client(string(broker_addr.host), Int64(broker_addr.port); id=client_id)
msg_channel = get_messages_channel(c)
conn_channel = get_connect_channel(c)
return new(c, broker_addr, false, false, msg_channel, conn_channel, Dict{String,Vector{String}}())
end
end
"""
init(protocol::MQTTProtocol, stop_check::Function, data_handler::Function)
Initialize the Mosquitto looping task for the provided `protocol` and forward incoming messages to `data_handler`.
"""
function init(protocol::MQTTProtocol, stop_check::Function, data_handler::Function)
tasks = []
listen_task = errormonitor(
Threads.@spawn begin
try
run_mosquitto_loop(protocol, data_handler)
catch err
if isa(err, InterruptException) || isa(err, Base.IOError)
# nothing
else
@error "Caught an unexpected error in listen" exception =
(err, catch_backtrace())
end
finally
close(protocol)
end
end
)
return listen_task, tasks
end
"""
run_mosquitto_loop(protocol::MQTTProtocol, data_handler::Function)
Endlessly loops over incoming messages on the `msg_channel` and `conn_channel`` and process their contents.
Loop is stopped by setting the `protocol.active` flag to false.
"""
function run_mosquitto_loop(protocol::MQTTProtocol, data_handler::Function)
Mosquitto.loop_start(protocol.client)
protocol.active = true
# listen for incoming messages and run callback
while protocol.active
handle_msg_channel(protocol, data_handler)
handle_conn_channel(protocol)
yield()
end
end
"""
handle_msg_channel(protocol::MQTTProtocol, data_handler::Function)
Check `protocol.msg_channel`` for new messages and forward their contents to the `data_handler`.
"""
function handle_msg_channel(protocol::MQTTProtocol, data_handler::Function)
# handle incoming content messages
while !isempty(protocol.msg_channel)
msg = take!(protocol.msg_channel)
topic = msg.topic
message = msg.payload
# guaranteed to be a key in the dict unless something went seriously wrong on registration
@spawnlog data_handler(message, topic; receivers=protocol.topic_to_aid[topic])
end
end
"""
handle_conn_channel(protocol::MQTTProtocol)
Check `protocol.conn_chnnel` for new messages and update the protocols connection status accordingly.
"""
function handle_conn_channel(protocol::MQTTProtocol)
# handle incoming connection status updates
while !isempty(protocol.conn_channel)
conncb = take!(protocol.conn_channel)
if conncb.val == 1
protocol.connected = true
elseif conncb.val == 0
protocol.connected = false
end
end
end
"""
send(protocol::MQTTProtocol, destination::String, message::Any)
Send a `message` to topic `destination` on the clients MQTT broker.
# Returns
Return value and message id from MQTT library.
"""
function send(protocol::MQTTProtocol, destination::String, message::Any)
publish(protocol.client, destination, message)
end
"""
id(protocol::MQTTProtocol)
Return the name the client is registered with at its broker.
"""
function id(protocol::MQTTProtocol)
return protocol.client.id
end
"""
subscribe(protocol::MQTTProtocol, topic::String; qos::Int=1)
Subscribe the MQTT client of the `protocol` to `topic` with the given `qos` setting.
# Returns
The Mosquitto error code and the message id.
"""
function subscribe(protocol::MQTTProtocol, topic::String; qos::Int=1)
Mosquitto.subscribe(protocol.client, topic; qos=qos)
end
"""
close(protocol::MQTTProtocol)
Disconnect the client from the broker and stop the message loop.
"""
function close(protocol::MQTTProtocol)
if protocol.connected
disconnect(protocol.client)
Mosquitto.loop_stop(protocol.client)
end
protocol.active = false
end
"""
parse_id(_::MQTTProtocol, id::Any)::String
Return the `id` of the protocol as string (for compliance with container core).
"""
function parse_id(_::MQTTProtocol, id::Any)::String
return string(id)
end
"""
notify_register(protocol::MQTTProtocol, aid::String; kwargs...)
Notify the `protocol` MQTT client that a new agent with `aid` has been registered.
Registration expects a kwarg `topics` to subscribe the agent to.
If any topic is not yet subscribed by the client `subscribe` is called for it.
"""
function notify_register(protocol::MQTTProtocol, aid::String; kwargs...)
topics = :topics in keys(kwargs) ? kwargs[:topics] : []
for topic ∈ topics
if topic ∉ keys(protocol.topic_to_aid)
protocol.topic_to_aid[topic] = [aid]
subscribe(protocol, topic)
continue
end
if aid ∉ protocol.topic_to_aid[topic]
push!(protocol.topic_to_aid[topic], aid)
end
end
end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 2714 |
export Protocol, send, start, close, id, notify_register, init
"""
Type for all implementations of protocols, acts like an interface. A protocol defines the way message are processed and especially sent and received
to an other peer. F.E. A protocol could be to send messages using a plain TCP connection, which would indicate that an internet address (host + port)
is required for the communication.
The parameterized type T indicates type, which defines the address data of the receiver and sender.
Every protocol has to define two methods.
1. send: defines the behavior of the protocol when an agents sends a messages
2. init: defines the necessary steps to initialize (especially) the receiver loop and
therefore accepts a stop check and a data handler function to indicate when the receiver should stop,
respectively how to dispatch the received message to the correct agent
"""
abstract type Protocol{T} end
"""
send(protocol::Protocol{T}, destination::T, message::Any) where {T}
Send the message `message` to the agent known by the adress `destination`. How the message is exactly handled is
determined by the protocol invoked.
The type of the destination has to match with the protocol. The function returns a boolean indicating
whether the message was successfull sent
"""
function send(protocol::Protocol{T}, destination::T, message::Any) where {T} end
"""
init(protocol::Protocol{T}, stop_check::Function, data_handler::Function) where {T}
Initialized the protocols internal loops (if exists). In most implementation this would mean that the receiver loop is started.
To handle received messages the `data_handler` function can be passed `(msg, sender) -> your handling code`.
To control the lifetime of the loops a stop_check should be passed (() -> boolean). If the stop check is true the loops will
terminate. The exact behavior depends on the implementation though.
"""
function init(protocol::Protocol{T}, stop_check::Function, data_handler::Function) where {T} end
"""
id(protocol::Protocol{T}) where {T}
Return the external identifier associated with the protocol (e.g. it could be the host+port, dns name, ...)
"""
function id(protocol::Protocol{T}) where {T} end
"""
parse_id(protocol::Protocol{T}, id_data::Any)::T where {T}
Parse different types to the correct type (if required). Should be implemented if the id type is not trivial.
"""
function parse_id(protocol::Protocol{T}, id_data::Any)::T where {T} end
"""
notify_register(protocol::Protocol{T}, aid::String; kwargs...) where {T}
Protocol specific updates called when a new agent is registered.
"""
function notify_register(protocol::Protocol{T}, aid::String; kwargs...) where {T} end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 12856 | export SimulationContainer, register, send_message, shutdown, protocol_addr, create_simulation_container, step_simulation, SimulationResult, CommunicationSimulationResult, TaskSimulationResult, on_step
using Base.Threads
using Dates
using ConcurrentCollections
using OrderedCollections
"""
Id key for the receiver in the meta dict
"""
RECEIVER_ID::String = "receiver_id"
"""
Prefix for the generated aid's
"""
AGENT_PREFIX::String = "agent"
"""
DISCRETE EVENT STEP SIZE
"""
DISCRETE_EVENT::Real = -1
"""
create_simulation_container(start_time::DateTime; communication_sim::Union{Nothing,CommunicationSimulation}=nothing, task_sim::Union{Nothing,TaskSimulation}=nothing)
Create a simulation container. The container is intitialized with `start_time`.
Per default the [`SimpleCommunicationSimulation`](@ref) is used for communication simulation, and
[`SimpleTaskSimulation`](@ref) for simulating the tasks of agents. To replace these, `communication_sim`
and respectively `task_sim` can be set.
"""
function create_simulation_container(start_time::DateTime; communication_sim::Union{Nothing,CommunicationSimulation}=nothing, task_sim::Union{Nothing,TaskSimulation}=nothing)
container = SimulationContainer()
container.clock.simulation_time = start_time
if !isnothing(communication_sim)
container.communication_sim = communication_sim
end
if !isnothing(task_sim)
container.task_sim = task_sim
end
return container
end
"""
Represents a message data package including the arriving time of the package.
"""
struct MessageData
content::Any
meta::AbstractDict
arriving_time::DateTime
end
"""
The SimulationContainer used as a base struct to enable simulations in Mango.jl. Shall be created
using [`create_simulation_container`](@ref).
"""
@kwdef mutable struct SimulationContainer <: ContainerInterface
world::World = World()
clock::Clock = Clock(DateTime(0))
task_sim::TaskSimulation = SimpleTaskSimulation(clock=clock)
agents::OrderedDict{String,Agent} = OrderedDict()
agent_counter::Integer = 0
shutdown::Bool = false
communication_sim::CommunicationSimulation = SimpleCommunicationSimulation()
message_queue::ConcurrentQueue{MessageData} = ConcurrentQueue{MessageData}()
end
function agents(container::SimulationContainer)::Vector{Agent}
return [t[2] for t in collect(container.agents)]
end
"""
on_step(agent::Agent, world::World, clock::Clock, step_size_s::Real)
Hook-in, called on every step of the simulation container for every `agent`.
Further, the `world` is passed, which represents a common view on the environment
in which agents can interact with eachother. Besides, the `clock` and the `step_size_s`
can be used to read the current simulation time and the time which passes in the current step.
"""
function on_step(agent::Agent, world::World, clock::Clock, step_size_s::Real)
# default nothing
end
function on_step(role::Role, world::World, clock::Clock, step_size_s::Real)
# default nothing
end
"""
Internal, call on_step on all agents.
"""
function step_agent(agent::Agent, world::World, clock::Clock, step_size_s::Real)
on_step(agent, world, clock, step_size_s)
for role in roles(agent)
on_step(role, world, clock, step_size_s)
end
end
"""
Contains the result of the communication simulation and whether the state of
the container has changed
"""
struct MessagingIterationResult
communication_result::CommunicationSimulationResult
state_changed::Bool
end
"""
Result of all messaging simulation iterations.
"""
@kwdef struct MessagingSimulationResult
results::Vector{MessagingIterationResult} = Vector()
end
"""
Result of all task simulation iterations.
"""
@kwdef struct TaskSimulationResult
results::Vector{TaskIterationResult} = Vector()
end
"""
Result of one simulation step.
"""
struct SimulationResult
time_elapsed::Real
messaging_result::MessagingSimulationResult
task_result::TaskSimulationResult
simulation_step_size_s::Real
end
"""
Internal
"""
function to_message_package(message_data::MessageData)::MessagePackage
sender_aid = message_data.meta[SENDER_ID]
receiver_aid = message_data.meta[RECEIVER_ID]
return MessagePackage(sender_aid, receiver_aid, message_data.arriving_time, (message_data.content, message_data.meta))
end
"""
Internal
"""
function to_cs_input!(message_queue::ConcurrentQueue{MessageData})::Vector{MessagePackage}
messages_packages = Vector()
while true
some_message = maybepopfirst!(message_queue)
if isnothing(some_message)
break
end
message::MessageData = something(some_message)
push!(messages_packages, to_message_package(message))
end
return messages_packages
end
"""
Internal
"""
function to_cs_input(message_queue::ConcurrentQueue{MessageData})::Vector{MessagePackage}
messages_packages = Vector()
next = message_queue.head.next
while !isnothing(next)
message::MessageData = next.value
push!(messages_packages, to_message_package(message))
next = next.next
end
return messages_packages
end
"""
Internal
"""
function cs_step_iteration(container::SimulationContainer,
step_size_s::Real,
pre_communication_result::Union{Nothing,CommunicationSimulationResult})::MessagingIterationResult
message_packages = to_cs_input!(container.message_queue)
communication_result = pre_communication_result
if isnothing(communication_result)
communication_result = calculate_communication(container.communication_sim,
container.clock,
message_packages)
end
state_changed = false
@sync begin
for (mp, pr) in sort([z for z in zip(message_packages, communication_result.package_results)], by=t -> add_seconds(t[1].sent_date, t[2].delay_s))
if add_seconds(mp.sent_date, pr.delay_s) <= add_seconds(container.clock.simulation_time, step_size_s) && pr.reached
state_changed = true
@spawnlog process_message(container, mp.content[1], mp.content[2])
else
# process it later
push!(container.message_queue, MessageData(mp.content[1], mp.content[2], mp.sent_date))
end
end
end
return MessagingIterationResult(communication_result, state_changed)
end
"""
Internal
"""
function determine_time_step(container::SimulationContainer)
message_packages = to_cs_input(container.message_queue)
communication_result = calculate_communication(container.communication_sim, container.clock, message_packages)
# earliest message or -1 if no message arrives
message_arrival_times = [add_seconds(t[1].sent_date, t[2].delay_s) for t in zip(message_packages, communication_result.package_results)]
time_to_next_message_s = nothing
if length(message_arrival_times) > 0
time_to_next_message_s = (findmin(message_arrival_times)[1] - container.clock.simulation_time).value / 1000
end
@debug "Next message in $time_to_next_message_s"
# ealiest task or -1 if no task scheduled
next_event_s = determine_next_event_time(container.task_sim)
@debug "Next event in $next_event_s"
# check whether one is absent and the other is present
if isnothing(time_to_next_message_s) && isnothing(next_event_s)
return nothing, communication_result
elseif isnothing(next_event_s)
return time_to_next_message_s, communication_result
elseif isnothing(time_to_next_message_s)
return next_event_s, communication_result
end
# return earliest
return min(time_to_next_message_s, next_event_s), communication_result
end
"""
step_simulation(container::SimulationContainer, step_size_s::Real=DISCRETE_EVENT)::Union{SimulationResult,Nothing}
Step the simulation using a continous time-span or until the next event happens.
For the continous simulation a `step_size_s` can be freely chosen, for the discrete event type
DISCRETE_EVENT has to be set for the `step_size_s`.
"""
function step_simulation(container::SimulationContainer, step_size_s::Real=DISCRETE_EVENT)::Union{SimulationResult,Nothing}
# Init world if uninitialized
if !initialized(container.world)
initialize(container.world, [v for v in values(container.agents)])
end
state_changed = true
@debug "Time" container.clock
task_sim_result = TaskSimulationResult()
messaging_sim_result = MessagingSimulationResult()
first_step = true
time_step_s = step_size_s
# We are in discrete event mode, so we need to determine
# the time until the next event occurs, this time will
# be used to execute the time-based simulation
comm_result = nothing
if time_step_s == DISCRETE_EVENT
time_step_s, comm_result = determine_time_step(container)
@debug "Determined the size to be $time_step_s"
if isnothing(time_step_s)
return nothing
end
end
elapsed = @elapsed begin
# now we process everything which happened in the steps,
# tasks and previous iterations
while state_changed
@debug "Start simulation iteration"
task_iter_result = nothing
comm_iter_result = nothing
@sync begin
Threads.@spawn comm_iter_result = cs_step_iteration(container, time_step_s, first_step ? comm_result : nothing)
Threads.@spawn task_iter_result = step_iteration(container.task_sim, time_step_s, first_step)
end
first_step = false
push!(task_sim_result.results, task_iter_result)
push!(messaging_sim_result.results, comm_iter_result)
state_changed = comm_iter_result.state_changed || task_iter_result.state_changed
@debug "Finish simulation iteration" state_changed
end
# agents act on the stepping hook
for agent in values(container.agents)
step_agent(agent, container.world, container.clock, time_step_s)
end
end
@debug "The simulation step needed $elapsed seconds"
container.clock.simulation_time = add_seconds(container.clock.simulation_time, time_step_s)
@debug "new time", container.clock.simulation_time
return SimulationResult(elapsed, messaging_sim_result, task_sim_result, time_step_s)
end
function protocol_addr(container::SimulationContainer)
return nothing
end
function shutdown(container::SimulationContainer)
container.shutdown = true
for agent in values(container.agents)
shutdown(agent)
end
end
function register(
container::SimulationContainer,
agent::Agent,
suggested_aid::Union{String,Nothing}=nothing;
kwargs...,
)
actual_aid::String = "$AGENT_PREFIX$(container.agent_counter)"
if !isnothing(suggested_aid) && !haskey(container.agents, suggested_aid)
actual_aid = suggested_aid
end
container.agents[actual_aid] = agent
agent.aid = actual_aid
agent.context = AgentContext(container)
container.agent_counter += 1
if !isnothing(container.task_sim)
agent.scheduler = create_agent_scheduler(container.task_sim)
end
return agent
end
function process_message(container::SimulationContainer, msg::Any, meta::AbstractDict)
receiver_id = meta[RECEIVER_ID]
if !haskey(container.agents, meta[RECEIVER_ID])
@warn "Container $(keys(container.agents)) has no agent with id: $receiver_id" msg meta
else
agent = container.agents[receiver_id]
return dispatch_message(agent, msg, meta)
end
end
struct NonWaitable end
function Base.wait(waitable::NonWaitable) end
function forward_message(container::SimulationContainer, msg::Any, meta::AbstractDict)
push!(container.message_queue, MessageData(msg, meta, container.clock.simulation_time))
return NonWaitable()
end
function send_message(
container::SimulationContainer,
content::Any,
agent_adress::AgentAddress,
sender_id::Union{Nothing,String}=nothing;
kwargs...,
)
receiver_id = agent_adress.aid
tracking_id = agent_adress.tracking_id
meta = OrderedDict{String,Any}()
for (key, value) in kwargs
meta[string(key)] = value
end
meta[RECEIVER_ID] = receiver_id
meta[SENDER_ID] = sender_id
meta[TRACKING_ID] = tracking_id
meta[SENDER_ADDR] = nothing
@debug "Send a message to ($receiver_id), from $sender_id" typeof(content)
return forward_message(container, content, meta)
end
"""
Base.getindex(container::SimulationContainer, index::String)
Return the agent indexed by `index` (aid).
"""
function Base.getindex(container::SimulationContainer, index::String)
return container.agents[index]
end
function Base.getindex(container::SimulationContainer, index::Int)
return agents(container)[index]
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 7344 |
export TCPProtocol, init, parse_id, acquire_tcp_connection, release_tcp_connection
using Sockets:
connect,
write,
getpeername,
read,
listen,
accept,
IPAddr,
TCPSocket,
TCPServer,
@ip_str,
InetAddr
using ConcurrentUtilities: Pool, acquire, release, drain!, ReadWriteLock, readlock, readunlock, lock, unlock
using Dates: Dates
import Base.close
mutable struct AtomicCounter
@atomic counter::Int
end
"""
Describes a connection pool for tcp connections. It supports
`keep_alive_time_ms` which specifies the time a connection is kept without usage
before closing the connection.
All methods defined on the pool are thread-safe.
"""
@kwdef mutable struct TCPConnectionPool
keep_alive_time_ms::Int32
connections::Pool{InetAddr,Tuple{TCPSocket,Dates.DateTime}} =
Pool{InetAddr,Tuple{TCPSocket,Dates.DateTime}}(100)
lock::ReadWriteLock = ReadWriteLock()
closed::Bool = false
acquired_connections::AtomicCounter = AtomicCounter(0)
end
"""
Defines the tcp protocol. It holds a binding to an IP+Port and a tcp connection pool.
"""
@kwdef mutable struct TCPProtocol <: Protocol{InetAddr}
address::InetAddr
server::Union{Nothing,TCPServer} = nothing
pool::TCPConnectionPool = TCPConnectionPool(keep_alive_time_ms=100000)
end
"""
close(pool::TCPConnectionPool)
Close the pool. This closes all connections. Further, this function
will wait until all connection are released.
"""
function close(pool::TCPConnectionPool)
lock(pool.lock)
pool.closed = true
# Waiting until all acquired connections are released
wait(Threads.@spawn begin
while pool.acquired_connections.counter > 0
sleep(0.0001)
end
end)
for (_, v) in pool.connections.keyedvalues
for (connection, __) in v
close(connection)
end
end
drain!(pool.connections)
unlock(pool.lock)
end
"""
Internal, checks whether a connection shall be kept alive
"""
function is_valid(connection::Tuple{TCPSocket,Dates.DateTime}, keep_alive_time_ms::Int32)
if (Dates.now() - connection[2]).value > keep_alive_time_ms
close(connection[1])
return false
end
return true
end
"""
acquire_tcp_connection(tcp_pool::TCPConnectionPool, key::InetAddr)::Union{TCPSocket,Nothing}
Acquire a tcp connection from the pool for the key (IP+Port). Return a TCPSocket if the pool is not closed
yet, otherwise `nothing` will be returned
"""
function acquire_tcp_connection(tcp_pool::TCPConnectionPool, key::InetAddr)::Union{TCPSocket,Nothing}
readlock(tcp_pool.lock)
if tcp_pool.closed
readunlock(tcp_pool.lock)
return nothing
end
connection, _ = acquire(
tcp_pool.connections,
key,
forcenew=false,
isvalid=c -> is_valid(c, tcp_pool.keep_alive_time_ms),
) do
result = (connect(key.host, key.port), Dates.now())
return result
end
@atomic tcp_pool.acquired_connections.counter += 1
readunlock(tcp_pool.lock)
return connection
end
"""
release_tcp_connection(
tcp_pool::TCPConnectionPool,
key::InetAddr,
connection::TCPSocket,
)
Release the given tcp `connection` indexed by the `key`. This will put the connection back
to the pool.
"""
function release_tcp_connection(
tcp_pool::TCPConnectionPool,
key::InetAddr,
connection::TCPSocket,
)
release(tcp_pool.connections, key, (connection, Dates.now()))
@atomic tcp_pool.acquired_connections.counter -= 1
end
"""
send(protocol::TCPProtocol, destination::InetAddr, message::Vector{UInt8})
Send a message `message` over plain TCP using `destination` as destination address. The message has to be provided
as a form, which is writeable to an arbitrary IO-Stream.
Return true if successfull.
"""
function send(protocol::TCPProtocol, destination::InetAddr, message::Vector{UInt8})
@debug "Attempt to connect to $(destination.host):$(destination.port)"
connection = acquire_tcp_connection(protocol.pool, destination)
if isnothing(connection)
return false
end
try
length_bytes = reinterpret(UInt8, [length(message)])
write(connection, [length_bytes; message])
flush(connection)
finally
@debug "Release $(destination.host):$(destination.port)"
release_tcp_connection(protocol.pool, destination, connection)
end
return true
end
"""
parse_id(_::TCPProtocol, id::Any)::InetAddr
"""
function parse_id(_::TCPProtocol, id::Any)::InetAddr
if typeof(id) == InetAddr
return id
end
if typeof(id) == Dict{String,Any}
return InetAddr(string(id["host"]["host"]), id["port"])
end
if typeof(id) == String
ip, port = split(id, ":")
return InetAddr(ip, parse(UInt16, port))
end
end
"""
Internal function for handling incoming connections
"""
function handle_connection(data_handler::Function, connection::TCPSocket)
try
while !eof(connection)
# Get the client address
@debug "Process $connection"
client_address = getpeername(connection)
client_ip, client_port = client_address
message_length = reinterpret(Int64, read(connection, 8))[1]
message_bytes = read(connection, message_length)
data_handler(message_bytes, InetAddr(client_ip, client_port))
end
catch err
if !isa(err, Base.IOError)
@error "connection job exited with unexpected error" exception =
(err, catch_backtrace())
end
finally
close(connection)
end
end
"""
init(protocol::TCPProtocol, stop_check::Function, data_handler::Function)
Initialized the tcp protocol. This starts the receiver and stop loop. The receiver loop
will call the data_handler with every incoming message. Further it provides as sender adress
a InetAddr object.
"""
function init(protocol::TCPProtocol, stop_check::Function, data_handler::Function)
server = listen(protocol.address.host, protocol.address.port)
@debug "Listen on $(protocol.address.host):$(protocol.address.port)"
protocol.server = server
tasks = []
listen_task = errormonitor(
Threads.@spawn begin
try
while isopen(server)
connection = accept(server)
push!(
tasks,
@spawnlog handle_connection(data_handler, connection)
)
end
catch err
if isa(err, InterruptException) || isa(err, Base.IOError)
# nothing
else
@error "Caught an unexpected error in listen" exception =
(err, catch_backtrace())
end
finally
close(server)
end
end
)
return listen_task, tasks
end
"""
id(protocol::TCPProtocol)
Return the technical address of the protocol (ip + port)
"""
function id(protocol::TCPProtocol)::InetAddr
return protocol.address
end
"""
close(protocol::TCPProtocol)
Release all tcp resources (binding on port and connections in the pool).
"""
function close(protocol::TCPProtocol)
close(protocol.pool)
close(protocol.server)
end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 12905 | export create_tcp_container, create_mqtt_container, GeneralAgent, add_agent_composed_of, agent_composed_of, activate, run_in_real_time, run_in_simulation, run_with_mqtt, run_with_tcp, PrintingAgent
function _set_codec(container::Container, codec::Union{Nothing,Tuple{Function,Function}})
if !isnothing(codec)
container.codec = codec
end
end
"""
create_tcp_container(host, port; codec=nothing)
Create a container using an TCP protocol.
The `host` is expected to be the IP-adress to bind on, `port` is the port to bind on. Optionally you
can also provide a codec as tuple of functions (first encode, second decode, see
[`encode`](@ref) and [`decode`](@ref)).
# Examples
```julia
agent = create_mqtt_container("127.0.0.1", 5555, "MyClient")
```
"""
function create_tcp_container(host::String="127.0.0.1", port::Int=5555; codec::Union{Nothing,Tuple{Function,Function}}=nothing)
container = Container()
container.protocol = TCPProtocol(address=InetAddr(host, port))
_set_codec(container, codec)
return container
end
"""
create_mqtt_container(host, port, client_id; codec=nothing)
Create a container using an MQTT protocol.
The `host` is expected to be the IP-adress of the broker, `port` is the port of the broker,
the `client_id` is the id of the client which will be created and connected to the broker.
Optionally you can also provide a codec as tuple of functions (first encode, second decode, see
[`encode`](@ref) and [`decode`](@ref)).
# Examples
```julia
agent = create_mqtt_container("127.0.0.1", 5555, "MyClient")
```
"""
function create_mqtt_container(host::String="127.0.0.1", port::Int=1883, client_id::String="default"; codec::Union{Nothing,Tuple{Function,Function}}=nothing)
container = Container()
container.protocol = MQTTProtocol(client_id, InetAddr(host, port))
_set_codec(container, codec)
return container
end
@agent struct GeneralAgent
end
"""
agent_composed_of(roles::Role...; base_agent::Union{Nothing,Agent}=nothing)
Create an agent which is composed of the given roles `roles...`.
If no `base_agent` is provided the agent struct used is an empty struct, which is
only used as a container for the roles. The agent will be returned by the function.
# Examples
```julia
agent = agent_composed_of(RoleA(), RoleB(), RoleC())
```
"""
function agent_composed_of(roles::Role...; base_agent::Union{Nothing,Agent}=nothing)
agent = isnothing(base_agent) ? GeneralAgent() : base_agent
for role in roles
add(agent, role)
end
return agent
end
"""
add_agent_composed_of(container, roles::Role...; suggested_aid::Union{Nothing,String}=nothing, base_agent::Union{Nothing,Agent}=nothing)
Create an agent which is composed of the given roles `roles...` and register the agent
to the `container`.
If no `base_agent` is provided the agent struct used is an empty struct, which is
only used as a container for the roles. The agent will be returned by the function.
# Examples
```julia
agent = add_agent_composed_of(your_container, RoleA(), RoleB(), RoleC())
```
"""
function add_agent_composed_of(container::ContainerInterface, roles::Role...; suggested_aid::Union{Nothing,String}=nothing, base_agent::Union{Nothing,Agent}=nothing)
agent = agent_composed_of(roles...; base_agent=base_agent)
register(container, agent, suggested_aid)
return agent
end
"""
activate(runnable, container_list)
Actvate the container(s), which includes starting the containers and shutting them down
after the runnable has been executed.
In most cases the runnable will execute code, which starts some process
(e.g. some distributed negotiation) in the system to define the objective of the agent system.
Generally this function is a convenience function and is equivalent to starting all containers
in the list, executing the code represented by `runnable` and shuting down the container again.
Further, this function will handle errors occuring while running the `runnable` and ensure the
containers are shutting down.
# Examples
```julia
activate(your_containers) do
# Send the first message to start the system
send_message(defined_agent, "Starting somethin", address(other_defined_agent))
# wait some time
wait(some_stopping_condition)
end
```
"""
function activate(runnable_simulation_code::Function, container_list::Vector{T}) where {T<:ContainerInterface}
@sync begin
for container in container_list
Threads.@spawn start(container)
end
end
for container in container_list
notify_ready(container)
end
try
runnable_simulation_code()
catch e
@error "A nested error ocurred while running a mango simulation" exception = (e, catch_backtrace())
finally
@sync begin
for container in container_list
Threads.@spawn shutdown(container)
end
end
end
end
function activate(runnable_simulation_code::Function, container::ContainerInterface)
activate(runnable_simulation_code, [container])
end
"""
run_in_real_time(runnable::Function,
n_container::Int,
container_list_creator::Function,
agent_tuple::Tuple...)
Let the agents run in containers (real time).
Distributes the given agents contained in the `agent_tuple` to `n_container` (real time container) and execute the `runnable`
(takes the container list as argument) while the container are active to run. It is possible to
add supplementary information per agent as Tuple. For example `(Agent, :aid => "my_aid")`.
The type of the containers are determined by the `container_list_creator` (n_container as argument, has
to return a list of container with n_container entries).
"""
function run_in_real_time(runnable::Function,
n_container::Int,
container_list_creator::Function,
agent_tuples::Tuple...)
actual_number_container = n_container
if n_container > length(agent_tuples)
actual_number_container = length(agent_tuples)
end
container_list = container_list_creator(actual_number_container)
for (i, agent_tuple) in enumerate(agent_tuples)
container_id = ((i - 1) % actual_number_container) + 1
actual_agent = agent_tuple[1]
agent_params::Dict = Dict(agent_tuple[2])
register(container_list[container_id], actual_agent, get(agent_params, :aid, nothing),
topics=get(agent_params, :topics, []))
end
activate(container_list) do
runnable(container_list)
end
end
function _agents_to_agent_tuples(agents::Agent...)
return [(a, Dict()) for a in agents]
end
"""
run_in_real_time(runnable::Function,
n_container::Int,
container_list_creator::Function,
agents::Agent...)
Let the agents run in containers (real time).
Distributes the given `agents` contained in the agent_tuple to `n_container` (real time container) and execute the `runnable`
(takes the container list as argument) while the container are active to run.
"""
function run_in_real_time(runnable::Function,
n_container::Int,
container_list_creator::Function,
agents::Agent...)
return run_in_real_time(runnable, n_container, container_list_creator, _agents_to_agent_tuples(agents...)...)
end
function _create_tcp_container_list_creator(host::String, start_port::Int, codec::Union{Nothing,Tuple{Function,Function}})
return n -> [create_tcp_container(host, start_port + (i - 1), codec=codec) for i in 1:n]
end
"""
run_with_tcp(runnable::Function,
n_container::Int,
agent_tuples::Union{Tuple,Agent}...;
host::String="127.0.0.1",
start_port::Int=5555,
codec::Union{Nothing,Tuple{Function,Function}}=(encode, decode))
Let the agents run in tcp containers (real time).
Distributes the given `agent_tuples` to `n_container` (real time container) and execute the `runnable`
(takes the container list as argument) while the container are active to run. It is possible to
add supplementary information per agent as Tuple. For example `(Agent, :aid => "my_aid")`.
Here, TCP container are created on `host` starting with the port `start_port`.
"""
function run_with_tcp(runnable::Function,
n_container::Int,
agent_tuples::Tuple...;
host::String="127.0.0.1",
start_port::Int=5555,
codec::Union{Nothing,Tuple{Function,Function}}=(encode, decode))
run_in_real_time(runnable, n_container, _create_tcp_container_list_creator(host, start_port, codec), agent_tuples...)
end
"""
run_with_tcp(runnable::Function,
n_container::Int,
agents::Agent...;
host::String="127.0.0.1",
start_port::Int=5555,
codec::Union{Nothing,Tuple{Function,Function}}=(encode, decode))
Let the `agents` run in tcp containers (real time).
Distributes the given `agents` to `n_container` (real time container) and execute the `runnable`
(takes the container list as argument) while the container are active to run.
Here, TCP container are created on `host` starting with the port `start_port`.
"""
function run_with_tcp(runnable::Function,
n_container::Int,
agents::Agent...;
host::String="127.0.0.1",
start_port::Int=5555,
codec::Union{Nothing,Tuple{Function,Function}}=(encode, decode))
run_in_real_time(runnable, n_container, _create_tcp_container_list_creator(host, start_port, codec), agents...)
end
function _create_mqtt_container_list_creator(host::String, port::Int, codec::Union{Nothing,Tuple{Function,Function}})
return n -> [create_mqtt_container(host, port, "client" * string(i), codec=codec) for i in 1:n]
end
"""
run_with_mqtt(runnable::Function,
n_container::Int,
agent_tuples::Tuple...;
broker_host::String="127.0.0.1",
broker_port::Int=1883,
codec::Union{Nothing,Tuple{Function,Function}}=(encode, decode))
Let the agents run in mqtt containers (real time).
Distributes the given `agents` to `n_container` (real time container) and execute the `runnable`
(takes the container list as argument) while the container are active to run. It is possible to
add supplementary information per agent as Tuple. For example `(Agent, :aid => "my_aid", :topics => ["topic"])`.
Here, MQTT container are created with the broker on `broker_host` and at the port `broker_port`.
The containers are assignede client ids (client1 client2 ...)
"""
function run_with_mqtt(runnable::Function,
n_container::Int,
agent_tuples::Tuple...;
broker_host::String="127.0.0.1",
broker_port::Int=1883,
codec::Union{Nothing,Tuple{Function,Function}}=(encode, decode))
run_in_real_time(runnable, n_container, _create_mqtt_container_list_creator(broker_host, broker_port, codec), agent_tuples...)
end
"""
run_with_mqtt(runnable::Function,
n_container::Int,
agents::Agent...;
broker_host::String="127.0.0.1",
broker_port::Int=1883,
codec::Union{Nothing,Tuple{Function,Function}}=(encode, decode))
Let the agents run in mqtt containers (real time).
Distributes the given `agents` to `n_container` (real time container) and execute the `runnable`
(takes the container list as argument) while the container are active to run.
Here, MQTT container are created with the broker on `broker_host` and at the port `broker_port`.
The containers are assignede client ids (client1 client2 ...)
"""
function run_with_mqtt(runnable::Function,
n_container::Int,
agents::Agent...;
broker_host::String="127.0.0.1",
broker_port::Int=1883,
codec::Union{Nothing,Tuple{Function,Function}}=(encode, decode))
run_in_real_time(runnable, n_container, _create_mqtt_container_list_creator(broker_host, broker_port, codec), agents...)
end
"""
run_in_simulation(runnable::Function, agents::Agent, n_steps::Int; start_time::DateTime=DateTime(2000, 1, 1), step_size_s::Int=DISCRETE_EVENT)
Let the agents run as simulation in a simulation container.
Execute the `runnable` in [`SimulationContainer`](@ref) while the container is active to run. After the
runnable the simulation container is stepped `n_steps` time with a `step_size_s` (default is discrete event).
The start time can be specified using `start_time`.
"""
function run_in_simulation(runnable::Function, n_steps::Int, agents::Agent...; start_time::DateTime=DateTime(2000, 1, 1), step_size_s::Int=DISCRETE_EVENT, communication_sim::Union{Nothing,CommunicationSimulation}=nothing)
sim_container = create_simulation_container(start_time, communication_sim=communication_sim)
for agent in agents
register(sim_container, agent)
end
results = []
activate(sim_container) do
runnable(sim_container)
for _ in 1:n_steps
push!(results, step_simulation(sim_container, step_size_s))
end
end
return results
end
"""
Simple agent just printing every message to @info.
"""
@agent struct PrintingAgent end
function handle_message(agent::PrintingAgent, message::Any, meta::Any)
@info "Got" message, meta
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 2391 | export CommunicationSimulation, PackageResult, CommunicationSimulationResult, MessagePackage, calculate_communication, SimpleCommunicationSimulation
using Dates
"""
Interface to implement a communication simulation.
"""
abstract type CommunicationSimulation end
"""
Package result
"""
struct PackageResult
reached::Bool
delay_s::UInt64
end
"""
List of package results
"""
struct CommunicationSimulationResult
package_results::Vector{PackageResult}
end
"""
Struct describing a mesage between two agents.
"""
struct MessagePackage
sender_id::Union{String,Nothing}
receiver_id::String
sent_date::DateTime
content::Any
end
"""
calculate_communication(communication_sim::CommunicationSimulation, clock::Clock, messages::Vector{MessagePackage})::CommunicationSimulationResult
Calculate the communication using the specific communication simulation type. the current
simulation time `clock` and the message which shall be sent in this step `messages`
"""
function calculate_communication(communication_sim::CommunicationSimulation, clock::Clock, messages::Vector{MessagePackage})::CommunicationSimulationResult
throw(ErrorException("Please implement calculate_communication(...)"))
end
"""
Default Implementation Communication Sim.
Implements a default delay which determines the delay of all messages if not specified in
`delay_s_directed_edge_dict`. The dict can contain a mapping (aid_sender, aid_receiver) -> delay,
such that the delay is specified for every link between agents.
"""
@kwdef struct SimpleCommunicationSimulation <: CommunicationSimulation
default_delay_s::Real = 0
delay_s_directed_edge_dict::Dict{Tuple{Union{String,Nothing},String},Real} = Dict()
end
"""
Implementation for SimpleCommunicationSimulation
"""
function calculate_communication(communication_sim::SimpleCommunicationSimulation, clock::Clock, messages::Vector{MessagePackage})::CommunicationSimulationResult
results::Vector{PackageResult} = Vector()
for message in messages
key = (message.sender_id, message.receiver_id)
delay_s = communication_sim.default_delay_s
if haskey(communication_sim.delay_s_directed_edge_dict, key)
delay_s = communication_sim.delay_s_directed_edge_dict[key]
end
push!(results, PackageResult(true, delay_s))
end
return CommunicationSimulationResult(results)
end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 8950 | export TaskIterationResult, TaskResult, TaskSimulation, create_agent_scheduler, step_iteration, SimulationScheduler, SimpleTaskSimulation
using UUIDs
using Dates
using ConcurrentCollections
"""
Defines the result of a task.
"""
struct TaskResult
done::Bool
finish_time::DateTime
raw_result::Any
end
"""
Define the result of an whole iteration of the task
simulation
"""
@kwdef mutable struct TaskIterationResult
task_to_result::Dict{UUID,TaskResult} = Dict()
state_changed::Bool = false
end
"""
Abstract type to define a TaskSimulation
"""
abstract type TaskSimulation end
"""
create_agent_scheduler(task_sim::TaskSimulation)
Create the scheduler used in the agents by the given `task_sim`.
"""
function create_agent_scheduler(task_sim::TaskSimulation)
throw(ErrorException("Please implement create_agent_scheduler(...)"))
end
"""
step_iteration(task_sim::TaskSimulation, step_size_s::Real)::TaskIterationResult
Execute an iteration for a step of the simulation, which time is stepped with the `step_size_s`.
Can be called repeatedly if new tasks are spawn as a result of other tasks or as result of arriving messages.
"""
function step_iteration(task_sim::TaskSimulation, step_size_s::Real)::TaskIterationResult
throw(ErrorException("Please implement step_iteration(...)"))
end
"""
determine_next_event_time(task_sim::TaskSimulation)
Determines the time of the next event, which shall occur.
Used for the discrete event simulation type.
"""
function determine_next_event_time(task_sim::TaskSimulation)
throw(ErrorException("Please implement determine_next_event_time(...)"))
end
"""
Specific scheduler, defined to be injected to the agents and intercept scheduling
calls and especially the sleep calls while scheduling. This struct manages all necessary times and
events, which shall fulfill the purpose to step the tasks only for a given step_size.
"""
@kwdef struct SimulationScheduler <: AbstractScheduler
clock::Clock
events::ConcurrentDict{Task,Tuple{Base.Event,DateTime}} = ConcurrentDict{Task,Tuple{Base.Event,DateTime}}()
tasks::ConcurrentDict{Task,Tuple{TaskData,Base.Event}} = ConcurrentDict{Task,Tuple{TaskData,Base.Event}}()
queue::ConcurrentQueue{Union{Tuple{Function,TaskData,Base.Event},Task}} = ConcurrentQueue{Union{Tuple{Function,TaskData,Base.Event},Task}}()
wait_queue::ConcurrentQueue{Task} = ConcurrentQueue{Task}()
end
"""
Internal struct, signaling the state of the tasks which has been waited on.
"""
struct WaitResult
cont::Bool
result::Any
end
function determine_next_event_time_with(scheduler::SimulationScheduler, simulation_time::DateTime)
lowest = nothing
# normal queue
next = scheduler.queue.head.next
while !isnothing(next)
if isa(next.value, Tuple)
return 0
else
throw("This should not happen! Did you schedule a task with zero sleep time?")
end
next = next.next
end
# wait queue
next = scheduler.wait_queue.head.next
while !isnothing(next)
t = scheduler.events[next.value][2]
if isnothing(lowest) || t < lowest
lowest = t
end
next = next.next
end
if isnothing(lowest)
return nothing
end
return (lowest - simulation_time).value / 1000
end
function wait_for_finish_or_sleeping(scheduler::SimulationScheduler, task::Task, step_size_s::Real, timeout_s::Real=10, check_delay_s=0.001)::WaitResult
remaining = timeout_s
while remaining > 0
sleep(check_delay_s)
remaining -= check_delay_s
if !istaskdone(task)
if haskey(scheduler.events, task)
event_time = scheduler.events[task]
@debug "not done, found event" event_time[2] add_seconds(scheduler.clock.simulation_time, step_size_s)
if event_time[2] <= add_seconds(scheduler.clock.simulation_time, step_size_s)
return WaitResult(true, nothing)
else
return WaitResult(false, nothing)
end
end
else
return WaitResult(false, Some(task.result))
end
end
throw("Simulation encountered a task timeout!")
end
function now(scheduler::SimulationScheduler)
return scheduler.clock.simulation_time
end
function sleep(scheduler::SimulationScheduler, time_s::Real)
event = Base.Event()
ctime = scheduler.clock.simulation_time
if haskey(scheduler.events, current_task())
ctime = scheduler.events[current_task()][2]
end
scheduler.events[current_task()] = (event, add_seconds(ctime, time_s))
@debug "Sleep task with" current_task() event add_seconds(ctime, time_s)
wait(event)
end
function wait(scheduler::SimulationScheduler, timer::Timer, delay_s::Real)
sleep(scheduler, delay_s)
end
function tasks(scheduler::SimulationScheduler)
return scheduler.tasks
end
function schedule(f::Function, scheduler::SimulationScheduler, data::TaskData)
event = Base.Event()
push!(scheduler.queue, (f, data, event))
return event
end
function do_schedule(f::Function, scheduler::SimulationScheduler, data::TaskData, event::Base.Event)
task = Threads.@spawn execute_task(f, scheduler, data)
tasks(scheduler)[task] = (data, event)
return task
end
"""
Default implementation of the interface.
"""
@kwdef mutable struct SimpleTaskSimulation <: TaskSimulation
clock::Clock
agent_schedulers::Vector{SimulationScheduler} = Vector{SimulationScheduler}()
end
function determine_next_event_time(task_sim::SimpleTaskSimulation)
event_times = [determine_next_event_time_with(scheduler, task_sim.clock.simulation_time) for scheduler in task_sim.agent_schedulers]
event_times = event_times[event_times.!=nothing]
if length(event_times) <= 0
return nothing
end
return findmin(event_times)[1]
end
function create_agent_scheduler(task_sim::SimpleTaskSimulation)
scheduler = SimulationScheduler(clock=task_sim.clock)
push!(task_sim.agent_schedulers, scheduler)
return scheduler
end
function transfer_wait_queue(scheduler::SimulationScheduler)
while true
next_task = maybepopfirst!(scheduler.wait_queue)
if isnothing(next_task)
break
end
push!(scheduler.queue, something(next_task))
end
end
function step_iteration(task_sim::SimpleTaskSimulation, step_size_s::Real, first_step=false)::TaskIterationResult
# Transfer Tasks from the previous iteration which are still running
# Only if, this was the last iteration of a step
if first_step
for scheduler in task_sim.agent_schedulers
transfer_wait_queue(scheduler)
end
end
result = TaskIterationResult()
@sync begin
for scheduler in task_sim.agent_schedulers
# Execute all tasks subsequently until no task can or is allowed to run
# based on the simulation time
Threads.@spawn begin
while true
next_task = maybepopfirst!(scheduler.queue)
if isnothing(next_task)
break
end
# Every time a task is running the state can change, so another iteration has to be calced
result.state_changed = true
task = something(next_task)
if isa(task, Task)
@debug "Continue the old Task!" task
notify(scheduler.events[task][1])
else
@debug "Processing new Task!"
func, td, event = task
task = do_schedule(func, scheduler, td, event)
end
@debug "Waiting..."
out = wait_for_finish_or_sleeping(scheduler, task, step_size_s)
@debug "Finished..."
if !isnothing(out.result)
notify(scheduler.tasks[task][2])
result.task_to_result[uuid4()] = TaskResult(true, task_sim.clock.simulation_time, out)
# clean up task data
maybepop!(scheduler.tasks, task)
if haskey(scheduler.events, task)
maybepop!(scheduler.events, task)
end
@debug "A task has been finished" out.result
elseif out.cont
push!(scheduler.queue, task)
@debug "The task $task needs another iteration!"
else
push!(scheduler.wait_queue, task)
@debug "The task will be proccesed in the next step_iteration"
end
end
end
end
end
@debug "Done with task iteration"
return result
end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 4750 | export @with_def
using ConcurrentCollections
import Base.length
using Dates
function count_nodes(queue::ConcurrentQueue{T})::Real where {T}
next = queue.head.next
count = 0
while !isnothing(next)
next = next.next
count += 1
end
return count
end
function add_seconds(date_time::DateTime, inc_s::Real)::DateTime
return date_time + Millisecond(trunc(Int, inc_s * 1000))
end
function length(queue::ConcurrentQueue{T})::Real where {T}
return count_nodes(queue)
end
function find_tuple(tuples::Vector, index::Int, value::Any)::Union{Tuple,Nothing}
for tuple in tuples
if tuple[index] == value
return tuple
end
end
return nothing
end
function get_types(type_curly_expr::Expr)
type_args = []
type_args_full = []
for i in 2:length(type_curly_expr.args)
type_arg = type_curly_expr.args[i]
push!(type_args_full, type_arg)
if typeof(type_arg) == Symbol
push!(type_args, type_arg)
else
push!(type_args, type_arg.args[1])
end
end
return type_args, type_args_full
end
"""
This macro can be applied to struct definitions and adds the possibility to define default values on field declaration. In contrast
to @kwdef or @with_kw, this macro will create normal parameters for construction if no default value has been provided.
# Example
```julia
@with_def struct ExampleStruct
abc::Int = 0
def::String
end
# can be constructed as follows
es = ExampleStruct("mydefstring") # abc == 0
es = ExampleStruct("mydefstring", abc=3) # abc == 3
```
"""
macro with_def(struct_def)
Base.remove_linenums!(struct_def)
struct_head = struct_def.args[2]
struct_name = struct_head
type_clause = nothing
type_args = []
type_args_full = []
# If there are type parameters and/or type inheritance then the struct_name is deeper in the Expr-hierarchy
if typeof(struct_name) != Symbol
struct_name = struct_head.args[1]
# If there is a type inheritance it is one level deeper
if typeof(struct_name) != Symbol
struct_head_sub = struct_name
struct_name = struct_head_sub.args[1]
# Get the information for type arguments
if struct_head_sub.head == :curly
type_clause = struct_head_sub.args[2]
type_args, type_args_full = get_types(struct_head_sub)
end
end
# Get the information for type arguments
if struct_head.head == :curly
type_clause = struct_head.args[2]
type_args, type_args_full = get_types(struct_head)
end
end
struct_fields = struct_def.args[3].args
new_struct_field = []
new_struct_field_default = []
struct_field_names = []
struct_fields_without_def = []
# Fill the field vectors divided by having a default and don't having a default
for field in struct_fields
# has default
if field.head == :(=)
push!(new_struct_field_default, (field.args[1], field.args[2]))
push!(struct_field_names, field.args[1].args[1])
push!(struct_fields_without_def, field.args[1])
else
push!(new_struct_field, field)
push!(struct_field_names, field.args[1])
push!(struct_fields_without_def, field)
end
end
args_with_default = [
Expr(:kw,
field,
field_default)
for (field, field_default) in new_struct_field_default
]
args = new_struct_field
args_compl = length(type_args) == 0 ?
Symbol(:new) :
Expr(:curly, Symbol(:new), type_args...)
args_names_new = length(struct_field_names) == 0 ?
Expr(:call, args_compl) :
Expr(:call, args_compl, struct_field_names...)
call_clause = length(args) == 0 ? Expr(:call, Symbol(struct_name),
length(args_with_default) == 0 ? Expr(:parameters,) : Expr(:parameters, args_with_default...)
) :
Expr(:call, Symbol(struct_name),
length(args_with_default) == 0 ? Expr(:parameters,) : Expr(:parameters, args_with_default...),
args...
)
with_where_clause = length(type_args) == 0 ? call_clause : Expr(:where, call_clause, type_args_full...)
default_constructor = Expr(:function,
with_where_clause,
Expr(:block, args_names_new)
)
# Create the new struct definition
new_struct_def = Expr(
:struct,
true,
struct_head,
length(struct_fields_without_def) == 0 ? Expr(:block) : Expr(:block, struct_fields_without_def..., default_constructor),
)
esc(Expr(:block, new_struct_def))
end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 1201 | export encode, decode
using LightBSON
using OrderedCollections
"""
encode(data::OrderedDict{String,Any})
Encode `data` into a UInt8 buffer using LightBSON.
# Examples
```julia-repl
julia> data = OrderedDict(["test" => 10])
OrderedDict{String, Int64} with 1 entry:
"test" => 10
julia> encode(data)
19-element Vector{UInt8}:
0x13
0x00
0x00
0x00
0x12
⋮
0x00
0x00
0x00
0x00
0x00
```
"""
function encode(data::Any)::Vector{UInt8}
buf = Vector{UInt8}()
LightBSON.bson_write(buf, data)
return buf
end
function encode(data::OrderedDict{String,Any})::Vector{UInt8}
buf = Vector{UInt8}()
LightBSON.bson_write(buf, data)
return buf
end
"""
decode(buf::Vector{UInt8}, t::Type=OrderedDict{String, Any})
Decode the data in `buf` into an object of type `t` using `LightBSON.bson_read`.
# Examples
```julia-repl
julia> data = OrderedDict(["test" => 10])
OrderedDict{String, Int64} with 1 entry:
"test" => 10
julia> decode(encode(data))
OrderedDict{String, Any} with 1 entry:
"test" => 10
```
"""
function decode(
buf::Vector{UInt8},
t::Type=OrderedDict{String,Any},
)::Union{OrderedDict{String,Any},Any}
return LightBSON.bson_read(t, buf)
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 234 |
macro spawnlog(expr)
quote
Threads.@spawn try
$(esc(expr))
catch ex
bt = stacktrace(catch_backtrace())
showerror(stderr, ex, bt)
rethrow(ex)
end
end
end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 7362 | export TaskData,
PeriodicTaskData,
InstantTaskData,
DateTimeTaskData,
AwaitableTaskData,
ConditionalTaskData,
stop_task,
stop_all_tasks,
wait_for_all_tasks,
stop_and_wait_for_all_tasks,
schedule,
Clock,
Scheduler,
SimulationScheduler,
AbstractScheduler,
sleep_until
using Dates
using ConcurrentCollections
import Base.schedule, Base.sleep, Base.wait
"""
Abstract type of a clock, which holds the time of a simulation
"""
abstract type AbstractClock end
"""
Default clock implementation, in which a static DateTime field is used.
"""
@kwdef mutable struct Clock <: AbstractClock
simulation_time::DateTime
end
"""
Clock implmentation using the real time and therefore not holding any time information
"""
struct DateTimeClock <: AbstractClock
end
struct Stop end
struct Continue end
"""
TaskData type, which is the supertype for all data structs,
which shall describe a specific task type. Together with
a new method execute task for the inherting struct, new types
of tasks can be introduced.
# Example
```julia
struct InstantTaskData <: TaskData end
function execute_task(f::Function, scheduler::AbstractScheduler, data::InstantTaskData)
f()
end
```
"""
abstract type TaskData end
"""
Abstract type for a scheduler
"""
abstract type AbstractScheduler end
"""
now(scheduler::AbstractScheduler)
Internal, return the time on which the scheduler is working on
"""
function now(scheduler::AbstractScheduler)
return DateTime.now()
end
"""
sleep(scheduler::AbstractScheduler, time_s::Real)
Sleep for `time_s`. The way how the sleep is performed is determined
by the type of scheduler used.
"""
function sleep(scheduler::AbstractScheduler, time_s::Real)
return sleep(time_s)
end
"""
wait(scheduler::AbstractScheduler, timer::Timer, delay_s::Real)
Wait for `timer`.
"""
function wait(scheduler::AbstractScheduler, timer::Timer, delay_s::Real)
return wait(timer)
end
"""
clock(scheduler::AbstractScheduler)
Return the internal time representation, the `clock`.
"""
function clock(scheduler::AbstractScheduler)::AbstractClock
throw("unimplemented")
end
"""
tasks(scheduler::AbstractScheduler)
Return the tasks currently on schedule and managed by the scheduler.
"""
function tasks(scheduler::AbstractScheduler)
throw("unimplemented")
end
"""
Default scheduler for the real time applications of Mango.jl.
"""
@kwdef struct Scheduler <: AbstractScheduler
tasks::AbstractDict{Task,TaskData} = ConcurrentDict{Task,TaskData}()
clock::DateTimeClock = DateTimeClock()
end
function clock(scheduler::Scheduler)
return scheduler.clock
end
function tasks(scheduler::Scheduler)
return scheduler.tasks
end
function is_stopable(data::TaskData)::Bool
return false
end
function stop_single_task(data::TaskData)::Nothing
end
"""
Task data describing a periodic task.
A periodic task is defined by an `interval_s` and optionally by a `condition`. The
interval determines how long the delay is between the recurring action. The condition
is a stopping condition (no argument) which shall return true if the task shall stop.
"""
mutable struct PeriodicTaskData <: TaskData
interval_s::Real
condition::Function
timer::Timer
function PeriodicTaskData(interval_s::Real, condition::Function=() -> true)
return new(interval_s, condition, Timer(interval_s; interval=interval_s))
end
end
function is_stopable(data::PeriodicTaskData)::Bool
return true
end
function stop_single_task(data::PeriodicTaskData)::Nothing
close(data.timer)
end
"""
Instant task data. Functions scheduled with this data is scheduled instantly.
"""
struct InstantTaskData <: TaskData end
"""
Schedule the function at a specific time determined by the date::DateTime.
"""
struct DateTimeTaskData <: TaskData
date::Dates.DateTime
end
"""
Schedule the function when the given `awaitable` is finished. Can be used
with any type for which `wait` is defined.
"""
struct AwaitableTaskData <: TaskData
awaitable::Any
end
"""
Schedule the function when the `condition` is fulfilled. To check whether it is fulfilled
the condition function is called every `check_interval_s`.
"""
struct ConditionalTaskData <: TaskData
condition::Function
check_interval_s::Float64
end
function execute_task(f::Function, scheduler::AbstractScheduler, data::PeriodicTaskData)
while data.condition()
f()
wait(scheduler, data.timer, data.interval_s)
end
end
function execute_task(f::Function, scheduler::AbstractScheduler, data::InstantTaskData)
f()
end
function execute_task(f::Function, scheduler::AbstractScheduler, data::DateTimeTaskData)
sleep(scheduler, (data.date - Dates.now()).value / 1000)
f()
end
function execute_task(f::Function, scheduler::AbstractScheduler, data::AwaitableTaskData)
wait(data.awaitable)
f()
end
function execute_task(f::Function, scheduler::AbstractScheduler, data::ConditionalTaskData)
while !data.condition()
sleep(scheduler, data.check_interval_s)
end
f()
end
"""
schedule(f::Function, scheduler, data::TaskData)
Schedule a function (no arguments) using the specific scheduler (mostly the agent scheduler). The
functino `f` is scheduled using the information in `data`, which specifies the way `f` will be
scheduled.
"""
function schedule(f::Function, scheduler::AbstractScheduler, data::TaskData)
task = Threads.@spawn execute_task(f, scheduler, data)
tasks(scheduler)[task] = data
return task
end
"""
stop_task(scheduler::AbstractScheduler, t::Task)
Stop the task `t` managed by `scheduler`. This only works if the task has been scheduled
with the scheduler using a stoppable TaskData.
"""
function stop_task(scheduler::AbstractScheduler, t::Task)
data = tasks(scheduler)[t]
if is_stopable(data)
stop_single_task(data)
return
end
@warn "Attempted to stop a non-stopable task."
return
end
"""
stop_all_tasks(scheduler::AbstractScheduler)
Stopps all stoppable tasks managed by `scheduler`.
"""
function stop_all_tasks(scheduler::AbstractScheduler)
for data in values(tasks(scheduler))
if is_stopable(data)
stop_single_task(data)
end
end
end
"""
wait_for_all_tasks(scheduler::AbstractScheduler)
Wait for all tasks managed by `scheduler`.
"""
function wait_for_all_tasks(scheduler::AbstractScheduler)
for task in keys(tasks(scheduler))
try
wait(task)
catch err
if isa(task.result, InterruptException) || isa(task.result, EOFError)
# ignore, task has been interrupted by the scheduler
else
@error "An error occurred while waiting for $task" exception =
(err, catch_backtrace())
end
end
end
end
"""
stop_and_wait_for_all_tasks(scheduler::AbstractScheduler)
Stopps all stoppable tasks and then wait for all tasks in `scheduler`.
"""
function stop_and_wait_for_all_tasks(scheduler::AbstractScheduler)
stop_all_tasks(scheduler)
wait_for_all_tasks(scheduler)
end
"""
sleep_until(condition::Function)
Sleep until the condition (no args -> bool) is met.
"""
function sleep_until(condition::Function; interval_s::Real=0.01)
while !condition()
sleep(interval_s)
end
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 1473 | export World, Space, Position, Position2D, Area2D, location, move, initialize, initialized
abstract type Position end
abstract type Space{P<:Position} end
struct Position2D <: Position
x::Real
y::Real
end
@kwdef struct Area2D <: Space{Position2D}
width::Real
height::Real
to_position::Dict{String,Position2D} = Dict()
end
@kwdef struct World{S<:Space}
space::S = Area2D(width=10, height=10)
initialized::Bool = false
end
function location(space::Space{P}, agent::Agent)::P where {P<:Position}
throw("Position on the space $space not defined!")
end
function location(space::Area2D, agent::Agent)::Position2D
return space.to_position[aid(agent)]
end
function move(space::Space{P}, agent::Agent, position::P) where {P<:Position}
throw("Move on the space $space not defined!")
end
function move(space::Area2D, agent::Agent, position::Position2D)
space.to_position[aid(agent)] = position
end
function initialize(space::Space, agents::Vector{A}) where {A<:Agent}
throw("Initialization for $space is not defined!")
end
function initialize(space::Area2D, agents::Vector{A}) where {A<:Agent}
for agent in agents
space.to_position[aid(agent)] = Position2D(rand() * space.width, rand() * space.height)
end
end
function initialize(world::World{S}, agents::Vector{A}) where {S<:Space} where {A<:Agent}
initialize(world.space, agents)
end
function initialized(world::World)
return world.initialized
end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 8756 | export complete_topology, star_topology, cycle_topology, graph_topology, per_node, add!, topology_neighbors, create_topology, add_node!, add_edge!, Topology, modify_topology, choose_agent, assign_agent, NORMAL, BROKEN, INACTIVE, set_edge_state!, remove_edge!, remove_node!
using MetaGraphsNext
using Graphs
import Graphs.add_edge!
@kwdef struct Node
id::Int
agents::Vector{Agent} = Vector()
end
struct Topology
graph::MetaGraph
end
@enum State begin
NORMAL # normal neighbor
INACTIVE # neighbor link exists but link is not active (could be activated/used)
BROKEN # neighbor link exists but link is not usable (can not be activated)
end
@kwdef mutable struct TopologyService
state_to_neighbors::Dict{State,Vector{AgentAddress}} = Dict()
end
function neighbors(service::TopologyService, state::State=NORMAL)
return get(service.state_to_neighbors, state, Vector())
end
function _create_meta_graph_with(graph::AbstractGraph)
vertices_description = [i => Node(id=i) for i in vertices(graph)]
edges_description = [(e.src, e.dst) => NORMAL for e in edges(graph)]
return MetaGraph(graph, vertices_description, edges_description)
end
"""
complete_topology(number_of_nodes)
Create a fully-connected topology.
"""
function complete_topology(number_of_nodes::Int)::Topology
graph = complete_graph(number_of_nodes)
return Topology(_create_meta_graph_with(graph))
end
"""
star_topology(number_of_nodes)
Create a star topology.
"""
function star_topology(number_of_nodes::Int)
graph = star_graph(number_of_nodes)
return Topology(_create_meta_graph_with(graph))
end
"""
cycle_topology(number_of_nodes)
Create a cycle topology.
"""
function cycle_topology(number_of_nodes::Int)
graph = cycle_graph(number_of_nodes)
return Topology(_create_meta_graph_with(graph))
end
"""
graph_topology(graph)
Create a topology based on a Graphs.jl (abstract) graph.
"""
function graph_topology(graph::AbstractGraph)
return Topology(_create_meta_graph_with(graph))
end
"""
add_edge!(topology, node_id_from, node_id_to, directed=false)
Add an edge to the topology from `node_id_from` to `node_id_to`. If `directed` is true
a directed edge is added, otherwise an undirected edge is added.
"""
function add_edge!(topology::Topology, node_id_from::Int, node_id_to::Int, state::State=NORMAL; directed::Bool=false)
if directed
topology.graph[node_id_from, node_id_to] = state
else
topology.graph[node_id_to, node_id_from] = state
topology.graph[node_id_from, node_id_to] = state
end
end
"""
remove_edge!(topology::Topology, node_id_from::Int, node_id_to::Int)
Remove the edge between `node_id_from` and `node_id_to`.
"""
function remove_edge!(topology::Topology, node_id_from::Int, node_id_to::Int)
return rem_edge!(topology.graph, node_id_from, node_id_to)
end
"""
remove_node!(topology::Topology, node_id::Int)
Remove the node with the id `node_id`.
"""
function remove_node!(topology::Topology, node_id::Int)
return rem_vertex!(topology.graph, node_id)
end
"""
add_node!(topology, agents::Agent...)::Int
Add a node to the topology with a list (or a single) of agents attached.
"""
function add_node!(topology::Topology, agents::Agent...; id::Union{Int,Nothing}=nothing)::Int
vid = isnothing(id) ? nv(topology.graph) + 1 : id
topology.graph[vid] = Node(vid, [a for a in agents])
return vid
end
"""
set_state!(topology::Topology, node_id_from::Int, node_id_to::Int, state::State)
Set the state of the state of the edge `(node_id_from, node_id_to)` to `state`.
"""
function set_edge_state!(topology::Topology, node_id_from::Int, node_id_to::Int, state::State)
topology.graph[node_id_from, node_id_to] = state
end
"""
create_topology(create_runnable)::Topology
Create a topology using the `create_runnable` function which is a one-argument
function with an initially empty topology as argument.
# Example
```julia
topology = create_topology() do topology
agent = register(container, TopologyAgent())
agent2 = register(container, TopologyAgent())
agent3 = register(container, TopologyAgent())
n1 = add_node!(topology, agent)
n2 = add_node!(topology, agent2)
n3 = add_node!(topology, agent3)
add_edge!(topology, n1, n2)
add_edge!(topology, n1, n3)
end
```
"""
function create_topology(create_runnable::Function; directed::Bool=false)
topology = Topology(_create_meta_graph_with(directed ? DiGraph() : Graph()))
create_runnable(topology)
_build_neighborhoods_and_inject(topology)
return topology
end
"""
modify_topology(modify_runnable::Functino, topology::Topology)
Modify a topology using the `modify_runnable` function which is a one-argument
function with the provided topology as argument.
# Example
```julia
modify_topology(my_topology) do topology
agent = register(container, TopologyAgent())
agent2 = register(container, TopologyAgent())
agent3 = register(container, TopologyAgent())
n1 = add_node!(topology, agent)
n2 = add_node!(topology, agent2)
n3 = add_node!(topology, agent3)
add_edge!(topology, n1, n2)
add_edge!(topology, n1, n3)
end
```
"""
function modify_topology(modify_runnable::Function, topology::Topology)
modify_runnable(topology)
_build_neighborhoods_and_inject(topology)
return topology
end
function _build_neighborhoods_and_inject(topology::Topology)
# 2nd pass, build the neighborhoods and add it to agents
for label in labels(topology.graph)
node = topology.graph[label]
state_to_neighbors::Dict{State,Vector{AgentAddress}} = Dict{State,Vector{AgentAddress}}()
for n_label in neighbor_labels(topology.graph, label)
n_node = topology.graph[n_label]
state = topology.graph[node.id, n_node.id]
neighbor_addresses = get!(state_to_neighbors, state, Vector())
append!(neighbor_addresses, [address(agent) for agent in n_node.agents])
end
for agent in node.agents
topology_service = service_of_type(agent, TopologyService, TopologyService())
topology_service.state_to_neighbors = state_to_neighbors
end
end
end
"""
per_node(assign_runnable, topology)
Loops over the nodes of the `topology`, calls `assign_runnable` on every node to enable the caller
to populate the node. After the loop finished the neighborhoods are created and injected into the agent.
# Example
```julia
per_node(topology) do node
add!(node, register(container, TopologyAgent()))
end
```
"""
function per_node(assign_runnable::Function, topology::Topology)
# 1st pass, let the user assign the agents
for label in labels(topology.graph)
node = topology.graph[label]
assign_runnable(node)
end
_build_neighborhoods_and_inject(topology)
end
"""
add!(node, agent::Agent...)
Add an `agents` to the `node`.
"""
function add!(node::Node, agents::Agent...)
for a in agents
push!(node.agents, a)
end
end
"""
assign_agent(assign_condition::Function, topology::Topology, container::ContainerInterface)
Assign all agents of the `container` to the nodes based on the given `assign_condition`, this condition
takes as `Agent` and a `Node` (node.id for the identifier of the node) and shall return a boolean indicating
whether the agent shall be assigned to the node.
"""
function assign_agent(assign_condition::Function, topology::Topology, container::ContainerInterface)
per_node(topology) do node
for agent in agents(container)
if assign_condition(agent, node)
add!(node, agent)
end
end
end
end
"""
choose_agent(choose_agent_function::Function, topology::Topology)
Choose the agents, which shall be assigned to the nodes. For this the `choose_agent_function` has to be provided. This
function expects `Node` as argument and shall return an `Agent` or `Agent...`. The returned agent will be assigned to the node.
"""
function choose_agent(choose_agent_function::Function, topology::Topology)
per_node(topology) do node
agent = choose_agent_function(node)
add!(node, agent)
end
end
"""
topology_neighbors(agent)
Retrieve the neighbors of the `agent`, represented by their addresses. These vaues will be
updated when a topology is applied using `per_node` or `create_topology`.
"""
function topology_neighbors(agent::Agent, state::State=NORMAL)::Vector{AgentAddress}
return neighbors(service_of_type(agent, TopologyService, TopologyService()), state)
end
function topology_neighbors(role::Role, state::State=NORMAL)::Vector{AgentAddress}
return neighbors(service_of_type(role.context.agent, TopologyService, TopologyService()), state)
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 2126 | using Mango
using Test
using Dates
import Mango.on_step
@agent struct ModellingAgent
counter::Real
end
function on_step(agent::ModellingAgent, world::World, clock::Clock, step_size_s::Real)
agent.counter += step_size_s
end
@testset "TestAgentIsStepped" begin
container = create_simulation_container(DateTime(Millisecond(23)), communication_sim=SimpleCommunicationSimulation(default_delay_s=0))
agent1 = ModellingAgent(0)
agent2 = ModellingAgent(0)
register(container, agent1)
register(container, agent2)
stepping_result = step_simulation(container, 7.1)
shutdown(container)
@test agent1.counter == 7.1
end
@role struct ModellingRole
counter::Real
end
function on_step(role::ModellingRole, world::World, clock::Clock, step_size_s::Real)
role.counter += step_size_s
end
@testset "TestAgentIsSteppedRole" begin
container = create_simulation_container(DateTime(Millisecond(23)), communication_sim=SimpleCommunicationSimulation(default_delay_s=0))
agent = ModellingAgent(0)
role = ModellingRole(0)
register(container, agent)
add(agent, role)
stepping_result = step_simulation(container, 7.1)
shutdown(container)
@test role.counter == 7.1
end
@agent struct ModellingMovingAgent
target::Position2D
prev_position::Position2D
position::Position2D
end
function on_step(agent::ModellingMovingAgent, world::World, clock::Clock, step_size_s::Real)
agent.prev_position = location(world.space, agent)
move(world.space, agent, agent.target)
agent.position = location(world.space, agent)
end
@testset "TestAgentStepPosition" begin
container = create_simulation_container(DateTime(Millisecond(23)), communication_sim=SimpleCommunicationSimulation(default_delay_s=0))
given_initial = Position2D(-1, -1)
given_target = Position2D(1, 1)
agent = ModellingMovingAgent(given_target, given_initial, given_initial)
register(container, agent)
stepping_result = step_simulation(container, 1)
shutdown(container)
@test agent.prev_position != given_initial
@test agent.position == given_target
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 8784 | using Mango
using Test
using Parameters
using Sockets: InetAddr, @ip_str
import Mango.handle_message
@agent struct MyAgent
counter::Integer
got_msg::Bool
end
MyAgent(c::Integer) = MyAgent(c, false)
@role struct MyRole
counter::Integer
invoked::Bool
end
MyRole(counter::Integer) = MyRole(counter, false)
function handle_message(agent::MyAgent, message::Any, meta::Any)
agent.counter += 10
agent.got_msg = true
end
function handle_message(role::MyRole, message::Any, meta::Any)
role.counter += 10
end
@testset "AgentRoleMessage" begin
container = Container()
agent1 = MyAgent(0)
agent2 = MyAgent(0)
role1 = MyRole(0)
add(agent2, role1)
register(container, agent1)
register(container, agent2)
wait(send_message(container, "Hello Roles, this is RSc!", AgentAddress(aid=agent2.aid)))
@test agent2.role_handler.roles[1] === role1
@test agent2.counter == 10
@test agent2.role_handler.roles[1].counter == 10
end
function handle_specific_message(role::MyRole, message::Any, meta::Any)
role.counter += 5
end
@testset "AgentRoleSubscribe" begin
container = Container()
agent1 = MyAgent(0)
agent2 = MyAgent(0)
role1 = MyRole(0)
add(agent2, role1)
subscribe_message(role1, handle_specific_message, (msg, meta) -> typeof(msg) == String)
register(container, agent1)
register(container, agent2)
wait(send_message(container, "Hello Roles, this is RSc!", AgentAddress(aid=agent2.aid)))
@test agent2.role_handler.roles[1] === role1
@test agent2.role_handler.roles[1].counter == 15
end
function on_send_message(
role::MyRole,
content::Any,
agent_adress::AgentAddress;
kwargs...,
)
role.invoked = true
end
@testset "AgentRoleSendSubscribe" begin
container = Container()
agent1 = MyAgent(0)
agent2 = MyAgent(0)
role1 = MyRole(0)
add(agent2, role1)
subscribe_send(role1, on_send_message)
register(container, agent1)
register(container, agent2)
wait(send_message(agent2, "Hello Roles, this is RSc!", AgentAddress(aid=agent1.aid)))
@test agent2.role_handler.roles[1] === role1
@test agent2.role_handler.roles[1].invoked
end
@testset "AgentSendMessage" begin
container = Container()
agent1 = MyAgent(0)
agent2 = MyAgent(0)
register(container, agent1)
register(container, agent2)
wait(send_message(agent1, "Hello Agents, this is RSc!", AgentAddress(aid=agent2.aid)))
@test agent2.counter == 10
end
@testset "AgentSendMessageWithKwargs" begin
container = Container()
agent1 = MyAgent(0)
agent2 = MyAgent(0)
register(container, agent1)
register(container, agent2)
wait(send_message(agent1, "Hello Agents, this is RSc!", AgentAddress(aid=agent2.aid); kw=1, kw2=2))
@test agent2.counter == 10
end
@testset "RoleSendMessage" begin
container = Container()
agent1 = MyAgent(0)
agent2 = MyAgent(0)
role1 = MyRole(0)
role2 = MyRole(0)
add(agent2, role1)
add(agent1, role2)
register(container, agent1)
register(container, agent2)
wait(send_message(role2, "Hello Roles, this is RSc!", AgentAddress(aid=agent2.aid)))
@test agent2.role_handler.roles[1] === role1
@test agent2.counter == 10
@test agent2.role_handler.roles[1].counter == 10
end
@testset "AgentSchedulerInstantThread" begin
agent = MyAgent(0)
result = 0
schedule(agent, InstantTaskData()) do
result = 10
end
stop_and_wait_for_all_tasks(agent)
@test result == 10
end
@agent struct MyRespondingAgent
counter::Integer
other::AgentAddress
end
@agent struct MyTrackedAgent
counter::Integer
end
function handle_message(agent::MyRespondingAgent, message::Any, meta::Any)
agent.counter += 10
wait(reply_to(agent, "Hello Agents, this is DialogRespondingRico", meta))
end
function handle_response(agent::MyTrackedAgent, message::Any, meta::Any)
agent.counter = 1337
end
@testset "AgentDialog" begin
container = Container()
agent1 = MyTrackedAgent(0)
agent2 = MyRespondingAgent(0, AgentAddress(aid=agent1.aid))
register(container, agent1)
register(container, agent2)
wait(send_tracked_message(agent1, "Hello Agent, this is DialogRico", AgentAddress(aid=agent2.aid); response_handler=handle_response))
@test agent2.counter == 10
@test agent1.counter == 1337
end
@role struct MyTrackedRole
counter::Integer
end
@role struct MyRespondingRole
counter::Integer
end
function handle_message(role::MyRespondingRole, message::Any, meta::Any)
role.counter += 10
wait(reply_to(role, "Hello Roles, this is DialogRespondingRico", meta))
end
function handle_response(role::MyTrackedRole, message::Any, meta::Any)
role.counter = 1337
end
@testset "RoleAgentDialog" begin
container = Container()
agent1 = MyAgent(0)
agent2 = MyAgent(0)
role1 = MyTrackedRole(0)
role2 = MyRespondingRole(0)
add(agent2, role1)
add(agent1, role2)
register(container, agent1)
register(container, agent2)
wait(send_tracked_message(role1, "Hello Agent, this is DialogRico", AgentAddress(aid=aid(role2)); response_handler=handle_response))
@test role2.counter == 10
@test role1.counter == 1337
end
@testset "RoleAgentDialogWithDoSyntax" begin
container = Container()
agent1 = MyAgent(0)
agent2 = MyAgent(0)
role1 = MyTrackedRole(0)
role2 = MyRespondingRole(0)
add(agent2, role1)
add(agent1, role2)
register(container, agent1)
register(container, agent2)
wait(send_and_handle_answer(role1, "Hello Agent, this is DialogRico", AgentAddress(aid=aid(role2))) do role, message, meta
role.counter = 1111
end)
@test role2.counter == 10
@test role1.counter == 1111
end
@testset "AgentMQTTMessaging" begin
broker_addr = InetAddr(ip"127.0.0.1", 1883)
c1 = Container()
p1 = MQTTProtocol("C1", broker_addr)
c2 = Container()
p2 = MQTTProtocol("C2", broker_addr)
c1.protocol = p1
c2.protocol = p2
# topic names
ALL_AGENTS = "all"
NO_AGENTS = "no"
SET_A = "set_a"
SET_B = "set_b"
a1 = MyAgent(0)
a2 = MyAgent(0)
b1 = MyAgent(0)
# no subs agent
b2 = MyAgent(0)
register(c1, a1; topics=[SET_A, ALL_AGENTS])
register(c1, a2; topics=[SET_A, ALL_AGENTS])
register(c2, b1; topics=[SET_B, ALL_AGENTS])
register(c2, b2; topics=[])
reset_events() = begin
for a in [a1, a2, b1, b2]
a.got_msg = false
end
end
# start listen loop
wait(Threads.@spawn start(c1))
wait(Threads.@spawn start(c2))
sleep(0.5)
if !c1.protocol.connected
return
end
# check loopback message on C1 --- should reach a1 and a2
# NOTE: we sleep after send_message because handle_message logic happens on receive and there is no
# loopback shortcut for MQTT messages like there is for TCP.
# This means we have to wait for the message to return to us from the broker.
wait(send_message(a1, "Test", MQTTAddress(broker_addr, SET_A)))
timedwait(() -> a1.got_msg, 0.5)
timedwait(() -> a2.got_msg, 0.5)
reset_events()
@test (a1.counter == a1.counter == 10) && (b1.counter == b2.counter == 0)
# check SET_A message on c2
wait(send_message(b1, "Test", MQTTAddress(broker_addr, SET_A)))
timedwait(() -> a1.got_msg, 0.5)
timedwait(() -> a2.got_msg, 0.5)
reset_events()
@test (a1.counter == a1.counter == 20) && (b1.counter == b2.counter == 0)
# check SET_B message
wait(send_message(a1, "Test", MQTTAddress(broker_addr, SET_B)))
timedwait(() -> b1.got_msg, 0.5)
reset_events()
@test (a1.counter == a1.counter == 20) && b1.counter == 10 && b2.counter == 0
# check ALL_AGENTS message
wait(send_message(a1, "Test", MQTTAddress(broker_addr, NO_AGENTS)))
# check NO_AGENTS message
wait(send_message(a1, "Test", MQTTAddress(broker_addr, ALL_AGENTS)))
# both conditions checked here because for no_agents we have nothing nice to wait on
# and the resulting counts should be the same in both cases
timedwait(() -> a1.got_msg, 0.5)
timedwait(() -> a2.got_msg, 0.5)
timedwait(() -> b1.got_msg, 0.5)
reset_events()
@test (a1.counter == a1.counter == 30) && b1.counter == 20 && b2.counter == 0
# shutdown
wait(Threads.@spawn shutdown(c1))
wait(Threads.@spawn shutdown(c2))
end
@agent struct MyAgentVar{T}
counter::T
end
@agent struct MyAgentVarVar{T<:AbstractFloat,D}
other::D
the_float::T
end
@testset "TestTypedAgents" begin
agent_var = MyAgentVar(1)
@test agent_var.counter == 1
agent_var_var = MyAgentVarVar(2, 3.3)
@test agent_var_var.other == 2
@test agent_var_var.the_float == 3.3
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 5426 | using Mango
using Test
using Parameters
using Sockets: InetAddr, @ip_str
using Base.Threads
using OrderedCollections
import Mango.handle_message, Mango.on_start, Mango.on_ready
@agent struct MyAgent
counter::Integer
got_msg::Bool
end
MyAgent(c::Integer) = MyAgent(c, false)
function handle_message(agent::MyAgent, message::Any, meta::AbstractDict)
agent.counter += 10
end
@testset "InternalContainerMessaging" begin
container = Container()
agent1 = MyAgent(0)
agent2 = MyAgent(0)
register(container, agent1)
register(container, agent2)
wait(Threads.@spawn send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid)))
@test agent1.counter == 10
end
@testset "TCPContainerMessaging" begin
container = Container()
container.protocol = TCPProtocol(address=InetAddr(ip"127.0.0.1", 2939))
agent1 = MyAgent(0)
register(container, agent1)
container2 = Container()
container2.protocol = TCPProtocol(address=InetAddr(ip"127.0.0.1", 2940))
agent2 = MyAgent(0)
register(container2, agent2)
agent3 = MyAgent(0)
register(container2, agent3)
activate([container, container2]) do
wait(
send_message(
container2,
"Hello Friends2, this is RSc!",
AgentAddress(aid=agent3.aid, address=InetAddr(ip"127.0.0.1", 2940))
),
)
wait(Threads.@spawn begin
while agent3.counter != 10
sleep(1)
end
end)
end
@test agent3.counter == 10
end
@agent struct PingPongAgent
counter::Int
end
function handle_message(agent::PingPongAgent, message::Any, meta::AbstractDict)
if message == "Ping" && agent.counter < 5
agent.counter += 1
send_message(agent, "Pong", AgentAddress(aid=meta["sender_id"], address=meta["sender_addr"]))
elseif message == "Pong" && agent.counter < 5
agent.counter += 1
send_message(agent, "Ping", AgentAddress(aid=meta["sender_id"], address=meta["sender_addr"]))
end
end
@testset "TCPContainerPingPong" begin
container = Container()
container.protocol = TCPProtocol(address=InetAddr(ip"127.0.0.1", 2939))
container2 = Container()
container2.protocol = TCPProtocol(address=InetAddr(ip"127.0.0.1", 2940))
ping_agent = PingPongAgent(0)
pong_agent = PingPongAgent(0)
register(container2, ping_agent)
register(container, pong_agent)
activate([container, container2]) do
wait(send_message(ping_agent, "Ping", AgentAddress(aid=pong_agent.aid, address=InetAddr(ip"127.0.0.1", 2939))))
wait(Threads.@spawn begin
while ping_agent.counter < 5
sleep(1)
end
end)
end
@test ping_agent.counter >= 5
end
@agent struct MyRespondingAgentTCP
counter::Integer
end
@agent struct MyTrackedAgentTCP
counter::Integer
end
function handle_message(agent::MyRespondingAgentTCP, message::Any, meta::Any)
agent.counter += 10
reply_to(agent, "Hello Agents, this is DialogRespondingRico", meta)
end
function handle_response(agent::MyTrackedAgentTCP, message::Any, meta::Any)
agent.counter = 1337
end
@testset "TCPTrackedMessages" begin
container = Container()
container.protocol = TCPProtocol(address=InetAddr(ip"127.0.0.1", 2939))
container2 = Container()
container2.protocol = TCPProtocol(address=InetAddr(ip"127.0.0.1", 2940))
tracked_agent = MyTrackedAgentTCP(0)
responding_agent = MyRespondingAgentTCP(0)
register(container2, tracked_agent)
register(container, responding_agent)
activate([container, container2]) do
wait(send_tracked_message(tracked_agent, "Hello Agent, this is DialogRico", AgentAddress(aid=responding_agent.aid, address=InetAddr(ip"127.0.0.1", 2939));
response_handler=handle_response))
wait(Threads.@spawn begin
while tracked_agent.counter == 0
sleep(1)
end
end)
end
@test responding_agent.counter == 10
@test tracked_agent.counter == 1337
end
@agent struct MyHookedAgent
counter::Integer
end
@role struct MyHookedRole
counter::Integer
end
function on_start(agent::MyHookedAgent)
agent.counter += 1
end
function on_ready(agent::MyHookedAgent)
agent.counter += 10
end
function on_start(role::MyHookedRole)
role.counter += 1
end
function on_ready(role::MyHookedRole)
role.counter += 10
end
@testset "ContainerTestHookIns" begin
container = Container()
hooked_agent = MyHookedAgent(0)
hooked_role = MyHookedRole(0)
add(hooked_agent, hooked_role)
register(container, hooked_agent)
wait(Threads.@spawn start(container))
notify_ready(container)
@test hooked_agent.counter == 11
@test hooked_role.counter == 11
end
@testset "ContainerUnknownAgentForward" begin
c1_addr = InetAddr(ip"127.0.0.1", 5555)
c1 = Container()
c1.protocol = TCPProtocol(address=c1_addr)
activate(c1) do
unknown_addr = AgentAddress("unknown", c1_addr, nothing)
# send some messages
wait(send_message(c1, "hello", unknown_addr))
end
# we only care that this does not throw an exception
@test true
end
@testset "ContainerGetIndex" begin
c1_addr = InetAddr(ip"127.0.0.1", 5555)
c1 = Container()
a = MyAgent(0)
register(c1, a)
@test c1[aid(a)] == a
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 600 | using Mango
using Test
using ConcurrentCollections
@testset "TestLengthConcurrentQueue" begin
queue = ConcurrentQueue()
push!(queue, 1)
push!(queue, 2)
push!(queue, 3)
@test length(queue) == 3
end
@with_def struct ABC{T}
abc::T
i::Int = 0
end
abstract type AbstractTypeAbc end
@with_def struct ABC2 <: AbstractTypeAbc
abc::Int
i::Int = 0
end
@testset "TestSimpleTypeParam" begin
abc = ABC("H")
@test abc.abc == "H"
@test abc.i == 0
end
@testset "TestTypeInheritanceWithDef" begin
abc = ABC2(0)
@test abc.abc == 0
@test abc.i == 0
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 1938 | using Test
using LightBSON
using OrderedCollections
using Sockets: InetAddr
include("../src/util/encode_decode.jl")
import Base.==
struct MangoMessage
content::Any
meta::Dict{String,Any}
end
function ==(x::MangoMessage, y::MangoMessage)
return x.content == y.content && x.meta == y.meta
end
struct MyComposite
x::Float64
y::String
z::OrderedDict{String,Any}
end
function ==(x::MyComposite, y::MyComposite)
return x.x == y.x && x.y == y.y && x.z == y.z
end
@testset "EncodeDecode" begin
#= things that will not pass the simple equality check:
- imaginary numbers (get cast to ordered dicts with "re" and "im" keys)
- nested structures
- anything self referential
=#
test_dict1 = OrderedDict([
"1" => 1.0,
"2" => "two",
"3" => 1,
"4" => [1, 2, 3, 5, 6, 7],
"5" => [1.0, 2.0, Inf, NaN],
"6" => ["a", "b", "c", "d"],
"7" => Any["a", 1.0, NaN, Inf, zeros(Float64, 10)],
"8" => Any[OrderedDict{String,Any}(["a" => "nested"])],
])
test_dict2 = OrderedDict{String,Any}()
encoded = encode(test_dict1)
decoded = decode(encoded)
@test isequal(decoded, test_dict1)
encoded = encode(test_dict2)
decoded = decode(encoded)
@test isequal(decoded, test_dict2)
composite = MyComposite(10.0, "some string", OrderedDict(["abc" => 123, "def" => 456]))
encoded = encode(composite)
decoded = decode(encoded, MyComposite)
@test isequal(decoded, composite)
mango_msg = MangoMessage(
"some_message",
Dict(["test" => 123, "blubb" => "bla", "addr" => InetAddr(ip"127.0.0.2", 2981)]),
)
expected_output = MangoMessage(
"some_message",
Dict(["test" => 123, "blubb" => "bla", "addr" => "127.0.0.2:2981"]),
)
encoded = encode(mango_msg)
decoded = decode(encoded, MangoMessage)
@test isequal(decoded, expected_output)
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 3357 | """
This file contains all examples given in the documentation enclosed in julia testsets.
This is to catch example code breaking on changes to the framework.
"""
using Mango
using Test
using Parameters
# Define the ping pong agent
@agent struct TCPPingPongAgent
counter::Int
end
# Override the default handle_message function for ping pong agents
function Mango.handle_message(agent::TCPPingPongAgent, message::Any, meta::Any)
agent.counter += 1
if message == "Ping"
reply_to(agent, "Pong", meta)
elseif message == "Pong"
reply_to(agent, "Ping", meta)
end
end
@testset "TCP_AGENT" begin
# Create the container instances with TCP protocol
container = create_tcp_container("127.0.0.1", 5555)
container2 = create_tcp_container("127.0.0.1", 5556)
# Define the ping pong agent
# Create instances of ping pong agents
# And register the agents
ping_agent = register(container, TCPPingPongAgent(0))
pong_agent = register(container2, TCPPingPongAgent(0))
# Start the Mango.jl system. At this point the TCP-server is created and bound
# to their addresses. After that, the runnable is executed (do ... end). at the
# end the container and therefor the TCP server are shut down again. Using this
# method it is not possible to forget starting or stopping containers.
activate([container, container2]) do
# Send the first message to start the exchange
send_message(ping_agent, "Ping", address(pong_agent))
# wait for 5 messages to have been sent
sleep_until(() -> ping_agent.counter >= 5)
end
@test ping_agent.counter >= 5
end
# Define the ping pong agent
@agent struct MQTTPingPongAgent
counter::Int
end
# Override the default handle_message function for ping pong agents
function Mango.handle_message(agent::MQTTPingPongAgent, message::Any, meta::Any)
broker_addr = agent.context.container.protocol.broker_addr
if message == "Ping"
agent.counter += 1
send_message(agent, "Pong", MQTTAddress(broker_addr, "pongs"))
elseif message == "Pong"
agent.counter += 1
send_message(agent, "Ping", MQTTAddress(broker_addr, "pings"))
end
end
@testset "MQTT_AGENT" begin
c1 = create_mqtt_container("127.0.0.1", 1883, "PingContainer")
c2 = create_mqtt_container("127.0.0.1", 1883, "PongContainer")
# Define the ping pong agent
# Create instances of ping pong agents
ping_agent = register(c1, MQTTPingPongAgent(0); topics=["pongs"])
pong_agent = register(c2, MQTTPingPongAgent(0); topics=["pings"])
# register each agent to a container
# For the MQTT protocol, topics for each agent have to be passed here.
mqtt_not_test_here = false
activate([c1, c2]) do
sleep(0.5)
if !c1.protocol.connected
mqtt_not_test_here = true
return
end
# Send the first message to start the exchange
wait(send_message(ping_agent, "Ping", MQTTAddress(c1.protocol.broker_addr, "pings")))
# Wait for a moment to see the result
# In general you want to use a Condition() instead to
# Define a clear stopping signal for the agents
sleep_until(() -> ping_agent.counter >= 5)
end
if mqtt_not_test_here
return
end
@test ping_agent.counter >= 5
end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 6276 | using Mango
using Test
using Logging
import Mango.handle_message
using Sockets: InetAddr
@agent struct ExpressAgent
counter::Int
end
function handle_message(agent::ExpressAgent, content::Any, meta::Any)
agent.counter += 1
end
@testset "TestCreateTCPContainerWithActivate" begin
container = create_tcp_container("127.0.0.1", 5555, codec=(encode, decode))
container2 = create_tcp_container("127.0.0.1", 5556)
express_one = register(container, ExpressAgent(0))
express_two = register(container2, ExpressAgent(0))
activate([container, container2]) do
wait(send_message(express_one, "TestMessage", address(express_two)))
wait(Threads.@spawn begin
while express_two.counter != 1
sleep(0.01)
end
end)
end
@test express_two.counter == 1
end
@testset "TestCreateTCPContainerWithActivateError" begin
container = create_tcp_container("127.0.0.1", 5555, codec=(encode, decode))
container2 = create_tcp_container("127.0.0.1", 5556)
express_one = register(container, ExpressAgent(0))
express_two = register(container2, ExpressAgent(0))
@test_logs (:error, "A nested error ocurred while running a mango simulation") min_level = Logging.Error begin
activate([container, container2]) do
throw("MyError")
end
end
end
@role struct ExpressRole
counter::Int
end
function handle_message(role::ExpressRole, content::Any, meta::Any)
role.counter += 1
end
@testset "TestAgentComposedBaseAgent" begin
base_agent = ExpressAgent(0)
agent = agent_composed_of(ExpressRole(0), ExpressRole(0), base_agent=base_agent)
@test agent == base_agent
end
@testset "TestRoleComposedAgents" begin
container = create_tcp_container("127.0.0.1", 5555, codec=(encode, decode))
container2 = create_tcp_container("127.0.0.1", 5556)
express_one = add_agent_composed_of(container, ExpressRole(0), ExpressRole(0))
express_two = add_agent_composed_of(container2, ExpressRole(0), ExpressRole(0), suggested_aid="test")
activate([container, container2]) do
wait(send_message(express_one, "TestMessage", address(express_two)))
wait(Threads.@spawn begin
while roles(express_two)[1].counter != 1
sleep(0.01)
end
end)
end
@test roles(express_two)[1].counter == 1
@test roles(express_two)[2].counter == 1
@test aid(express_two) == "test"
end
@testset "TestRunTcpContainerExpressAPI" begin
# Create agents based on roles
express_one = agent_composed_of(ExpressRole(0), ExpressRole(0))
express_two = agent_composed_of(ExpressRole(0), ExpressRole(0))
run_with_tcp(2, express_one, express_two) do cl
wait(send_message(express_one, "TestMessage", address(express_two)))
wait(Threads.@spawn begin
while express_two[1].counter != 1
sleep(0.01)
end
end)
end
@test roles(express_two)[1].counter == 1
@test roles(express_two)[2].counter == 1
@test address(express_one).address == InetAddr("127.0.0.1", 5555)
@test address(express_two).address == InetAddr("127.0.0.1", 5556)
@test aid(express_two) == "agent0"
end
@testset "TestRunTcpContainerExpressAPICustomAIDS" begin
# Create agents based on roles
express_one = agent_composed_of(ExpressRole(0), ExpressRole(0))
express_two = agent_composed_of(ExpressRole(0), ExpressRole(0))
run_with_tcp(2, (express_one, :aid => "Ex1"), (express_two, :aid => "Ex2")) do cl
wait(send_message(express_one, "TestMessage", address(express_two)))
wait(Threads.@spawn begin
while express_two[1].counter != 1
sleep(0.01)
end
end)
end
@test aid(express_one) == "Ex1"
@test aid(express_two) == "Ex2"
end
@testset "TestRunTcpContainerExpressAPITooMuchContainer" begin
# Create agents based on roles
express_one = agent_composed_of(ExpressRole(0), ExpressRole(0))
express_two = agent_composed_of(ExpressRole(0), ExpressRole(0))
run_with_tcp(3, express_one, express_two) do cl
wait(send_message(express_one, "TestMessage", address(express_two)))
wait(Threads.@spawn begin
while express_two[1].counter != 1
sleep(0.01)
end
end)
@test length(cl) == 2
end
@test roles(express_two)[1].counter == 1
@test roles(express_two)[2].counter == 1
@test address(express_one).address == InetAddr("127.0.0.1", 5555)
@test address(express_two).address == InetAddr("127.0.0.1", 5556)
@test aid(express_two) == "agent0"
end
@testset "TestRunMQTTContainerExpressAPI" begin
# Create agents based on roles
express_one = agent_composed_of(ExpressRole(0), ExpressRole(0))
express_two = agent_composed_of(ExpressRole(0), ExpressRole(0))
agent_desc = (express_one, :topics => ["Uni"], :something => "")
agent2_desc = (express_two, :topics => ["Uni"])
container_list = nothing
mqtt_not_test_here = false
run_with_mqtt(2, agent_desc, agent2_desc, broker_port=1883) do cl
if !cl[1].protocol.connected
mqtt_not_test_here = true
return
end
wait(send_message(express_one, "TestMessage", MQTTAddress(cl[1].protocol.broker_addr, "Uni")))
wait(Threads.@spawn begin
while express_two[1].counter != 1
sleep(0.01)
end
end)
container_list = cl
end
if mqtt_not_test_here
return
end
@test roles(express_two)[1].counter == 1
@test roles(express_two)[2].counter == 1
@test container_list[1][1] == agent_desc[1]
@test container_list[2][1] == agent2_desc[1]
@test aid(express_two) == "agent0"
end
@testset "TestRunSimulationContainerExpress" begin
# Create agents based on roles
express_one = agent_composed_of(ExpressRole(0), ExpressRole(0))
express_two = agent_composed_of(ExpressRole(0), ExpressRole(0))
result = run_in_simulation(1, express_one, express_two) do container
wait(send_message(express_one, "TestMessage", address(express_two)))
end
@test length(result) == 1
@test length(result[1].messaging_result.results) == 2
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 6643 | using Mango
using Test
using Parameters
import Mango.handle_event, Mango.handle_message
@agent struct RoleTestAgent
counter::Integer
end
@role struct RoleTestRole
counter::Integer
src::Union{Role,Nothing}
end
struct TestEvent
end
function handle_event(role::Role, src::Role, event::TestEvent; event_type::Any)
role.counter = 1
role.src = src
end
@testset "RoleEmitEventSimpleHandle" begin
agent = RoleTestAgent(0)
role1 = RoleTestRole(0, nothing)
role2 = RoleTestRole(0, nothing)
add(agent, role1)
add(agent, role2)
emit_event(role1, TestEvent())
@test role1.counter == 1
@test role2.counter == 1
@test role1.src == role1
@test role2.src == role1
end
struct TestEvent2
id::Int64
end
function custom_handler(role::Role, src::Role, event::Any, event_type::Any)
role.counter += event.id
role.src = src
end
@testset "RoleEmitEventSubHandle" begin
agent = RoleTestAgent(0)
role1 = RoleTestRole(0, nothing)
role2 = RoleTestRole(0, nothing)
add(agent, role1)
add(agent, role2)
subscribe_event(role1, TestEvent2, custom_handler, (src, event) -> event.id == 2)
emit_event(role2, TestEvent2(2))
emit_event(role2, TestEvent2(3))
@test role1.counter == 2
@test role1.src == role2
end
struct TestModel
c::Int64
end
TestModel() = TestModel(42)
@testset "RoleGetModel" begin
agent = RoleTestAgent(0)
role1 = RoleTestRole(0, nothing)
role2 = RoleTestRole(0, nothing)
add(agent, role1)
add(agent, role2)
shared_model = get_model(role1, TestModel)
shared_model2 = get_model(role2, TestModel)
@test shared_model.c == 42
@test shared_model == shared_model2
end
struct SharedTestEvent
end
@role struct SharedFieldTestRole
@shared
shared_event::SharedTestEvent
end
@testset "SharedFieldTestRole" begin
agent = RoleTestAgent(0)
role1 = SharedFieldTestRole()
role2 = SharedFieldTestRole()
add(agent, role1)
add(agent, role2)
@test !isnothing(role1.shared_event)
@test role1.shared_event === role2.shared_event
end
struct SharedTestEvent2
end
@role struct SharedFieldsTestRole
@shared
shared_event::SharedTestEvent
@shared
shared_event2::SharedTestEvent2
end
@testset "SharedFieldsTestRole" begin
agent = RoleTestAgent(0)
role1 = SharedFieldsTestRole()
role2 = SharedFieldsTestRole()
add(agent, role1)
add(agent, role2)
@test !isnothing(role1.shared_event)
@test !isnothing(role1.shared_event2)
@test role1.shared_event2 === role2.shared_event2
@test role1.shared_event === role2.shared_event
end
@testset "RoleSchedulerInstantThread" begin
agent = RoleTestAgent(0)
role1 = RoleTestRole(0, nothing)
add(agent, role1)
result = 0
schedule(role1, InstantTaskData()) do
result = 10
end
stop_and_wait_for_all_tasks(agent.scheduler)
@test result == 10
end
@testset "RoleGetAddress" begin
agent = RoleTestAgent(0)
role1 = RoleTestRole(0, nothing)
add(agent, role1)
addr = address(role1)
@test addr.aid == aid(agent)
@test isnothing(addr.address)
end
@role struct ForwardingTestRole
forwarded_from::AgentAddress
forward_to::AgentAddress
forward_is_here::Bool
end
function handle_message(role::ForwardingTestRole, content::Any, meta::Any)
if !get(meta, "forwarded", false)
wait(forward_to(role, content, role.forward_to, meta))
else
role.forward_is_here = true
@test meta["forwarded_from_address"] == role.forwarded_from.address
@test meta["forwarded_from_id"] == role.forwarded_from.aid
end
end
@testset "RoleForwardMessage" begin
container = Container()
agent1 = RoleTestAgent(0)
agent2 = RoleTestAgent(0)
agent3 = RoleTestAgent(0)
register(container, agent1)
register(container, agent2)
register(container, agent3)
role1 = ForwardingTestRole(address(agent1), address(agent3), false)
role2 = ForwardingTestRole(address(agent1), address(agent3), false)
role3 = ForwardingTestRole(address(agent1), address(agent3), false)
add(agent1, role1)
add(agent2, role2)
add(agent3, role3)
wait(send_message(role1, "Hey, forward me!", address(role2)))
@test role3.forward_is_here
end
@role struct AutoForwarder
end
@role struct ForwardTarget
forward_arrived::Bool
forwarded_from::AgentAddress
end
function handle_message(role::ForwardTarget, content::Any, meta::Any)
role.forward_arrived = meta["forwarded"]
role.forwarded_from = AgentAddress(aid=meta["forwarded_from_id"],
address=meta["forwarded_from_address"])
end
@testset "RoleAutoForwardMessage" begin
container = Container()
agent1 = RoleTestAgent(0)
agent2 = RoleTestAgent(0)
agent3 = RoleTestAgent(0)
register(container, agent1)
register(container, agent2)
register(container, agent3)
role1 = AutoForwarder()
role2 = AutoForwarder()
role3 = ForwardTarget(false, address(agent3))
add(agent1, role1)
add(agent2, role2)
add(agent3, role3)
add_forwarding_rule(role2, address(role1), address(role3), false)
wait(send_message(role1, "Hey, forward me!", address(role2)))
@test role3.forward_arrived
@test role3.forwarded_from == address(role1)
end
@role struct Replier
end
function handle_message(role::Replier, content::Any, meta::Any)
wait(reply_to(role, "Reply!", meta))
end
@testset "RoleAutoForwardMessageWithReply" begin
container = Container()
agent1 = RoleTestAgent(0)
agent2 = RoleTestAgent(0)
agent3 = RoleTestAgent(0)
register(container, agent1)
register(container, agent2)
register(container, agent3)
role1 = ForwardTarget(false, address(agent1))
role2 = AutoForwarder()
role3 = ForwardTarget(false, address(agent3))
add(agent1, role1)
add(agent2, role2)
add(agent3, role3)
add(agent3, Replier())
add_forwarding_rule(role2, address(role1), address(role3), true)
wait(send_message(role1, "Hey, forward me!", address(role2)))
@test role3.forward_arrived
@test role3.forwarded_from == address(role1)
@test role1.forward_arrived
@test role1.forwarded_from == address(role3)
delete_forwarding_rule(role2, address(role1), nothing)
role3.forward_arrived = false
role1.forward_arrived = false
wait(send_message(role1, "Hey, forward me!", address(role2)))
@test !role3.forward_arrived
@test !role1.forward_arrived
end
@role struct MyRoleVar{T}
counter::T
end
@testset "TestTypedRoles" begin
role_var = MyRoleVar(1)
@test role_var.counter == 1
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 505 | using Test
using Documenter
@testset "Mango Tests" begin
include("datastructure_util_tests.jl")
include("scheduler_tests.jl")
include("agent_tests.jl")
include("role_tests.jl")
include("container_tests.jl")
include("encode_decode_tests.jl")
include("simulation_container_tests.jl")
include("examples.jl")
include("tcp_protocol_tests.jl")
include("agent_modeling_tests.jl")
include("express_api_tests.jl")
include("topology_tests.jl")
doctest(Mango)
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 1492 | using Mango
using Test
import Dates
@testset "AgentSchedulerInstantThread" begin
scheduler = Scheduler()
result = 0
schedule(scheduler, InstantTaskData()) do
result = 10
end
stop_and_wait_for_all_tasks(scheduler)
@test result == 10
end
@testset "AgentSchedulerPeriodicThread" begin
scheduler = Scheduler()
result = 0
task = schedule(scheduler, PeriodicTaskData(0.1)) do
result += 10
end
sleep(0.51)
stop_and_wait_for_all_tasks(scheduler)
# windows is kinda slow on this, but it should work better for longer delays
@test result == 60 || result == 50
end
@testset "AgentSchedulerDateTimeThread" begin
scheduler = Scheduler()
result = 0
schedule(scheduler, DateTimeTaskData(Dates.now() + Dates.Second(1))) do
result = 10
end
stop_and_wait_for_all_tasks(scheduler)
@test result == 10
end
@testset "AgentSchedulerAwaitableThread" begin
scheduler = Scheduler()
result = 0
event = Base.Event()
task = schedule(scheduler, AwaitableTaskData(event)) do
result = 10
end
yield()
notify(event)
stop_and_wait_for_all_tasks(scheduler)
@test result == 10
end
@testset "AgentSchedulerConditionalThread" begin
scheduler = Scheduler()
result = 0
r = 0
task = schedule(scheduler, ConditionalTaskData(() -> r == 1, 0.01)) do
result = 10
end
r = 1
stop_and_wait_for_all_tasks(scheduler)
@test result == 10
end
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 12895 | using Mango
using Test
using Logging
using Dates
import Mango.handle_message
@agent struct SimAgent
counter::Int
end
function handle_message(agent::SimAgent, message::Any, meta::AbstractDict)
agent.counter += 10
if haskey(meta, "test")
agent.counter += 1
end
end
@testset "SimulationContainerKwargs" begin
container = create_simulation_container(DateTime(Millisecond(23)), communication_sim=SimpleCommunicationSimulation(default_delay_s=0))
agent1 = SimAgent(0)
agent2 = SimAgent(0)
register(container, agent1)
register(container, agent2)
send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid), test=2)
stepping_result = step_simulation(container, 1)
shutdown(container)
@test agent1.counter == 11
end
@testset "SimulationContainerNoProtocolSpecificAddr" begin
container = create_simulation_container(DateTime(Millisecond(23)), communication_sim=SimpleCommunicationSimulation(default_delay_s=0))
@test isnothing(protocol_addr(container))
end
@testset "SimulationContainerNoValidTargetCustomAid" begin
container = create_simulation_container(DateTime(Millisecond(23)), communication_sim=SimpleCommunicationSimulation(default_delay_s=0))
agent1 = SimAgent(0)
agent2 = SimAgent(0)
register(container, agent1)
register(container, agent2, "a1")
send_message(container, "Hello Friends, this is RSd!", AgentAddress(aid="abc"))
@test_logs (:warn, "Container $(keys(container.agents)) has no agent with id: abc") min_level = Logging.Warn begin
stepping_result = step_simulation(container, 1)
end
@test agent1.counter == 0
@test agent2.counter == 0
@test aid(agent2) == "a1"
end
@testset "SimpleInternalSimulationWithoutDelayContainerTest" begin
container = create_simulation_container(DateTime(Millisecond(23)), communication_sim=SimpleCommunicationSimulation(default_delay_s=0))
agent1 = SimAgent(0)
agent2 = SimAgent(0)
register(container, agent1)
register(container, agent2)
send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid))
send_message(container, "Hello Friends, this is RSd!", AgentAddress(aid=agent2.aid))
stepping_result = step_simulation(container, 1)
shutdown(container)
@test agent1.counter == 10
@test agent2.counter == 10
@test container.shutdown
end
@testset "SimpleInternalSimulationDelayGreaterStepSize" begin
container = create_simulation_container(DateTime(Millisecond(23)), communication_sim=SimpleCommunicationSimulation(default_delay_s=2))
agent1 = SimAgent(0)
agent2 = SimAgent(0)
register(container, agent1)
register(container, agent2)
send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid))
send_message(container, "Hello Friends, this is RSd!", AgentAddress(aid=agent2.aid))
stepping_result = step_simulation(container, 1)
@test agent1.counter == 0
@test agent2.counter == 0
stepping_result = step_simulation(container, 1)
@test agent1.counter == 10
@test agent2.counter == 10
end
@testset "SimpleInternalSimulationDelayMixedGreaterStepSize" begin
container = create_simulation_container(DateTime(Millisecond(23)), communication_sim=SimpleCommunicationSimulation(default_delay_s=2))
agent1 = SimAgent(0)
agent2 = SimAgent(0)
register(container, agent1)
register(container, agent2)
send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid))
send_message(container, "Hello Friends, this is RSd!", AgentAddress(aid=agent2.aid))
stepping_result = step_simulation(container, 1)
@test agent1.counter == 0
@test agent2.counter == 0
send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid))
send_message(container, "Hello Friends, this is RSd!", AgentAddress(aid=agent2.aid))
stepping_result = step_simulation(container, 1)
@test agent1.counter == 10
@test agent2.counter == 10
stepping_result = step_simulation(container, 1)
@test agent1.counter == 20
@test agent2.counter == 20
end
@testset "SimpleInternalSimulationLinkSpecificDelay" begin
com_sim = SimpleCommunicationSimulation(default_delay_s=0)
container = create_simulation_container(DateTime(Millisecond(0)), communication_sim=com_sim)
agent1 = SimAgent(0)
agent2 = SimAgent(0)
register(container, agent1)
register(container, agent2)
com_sim.delay_s_directed_edge_dict[(nothing, aid(agent1))] = 1
com_sim.delay_s_directed_edge_dict[(nothing, aid(agent2))] = 2
send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid))
send_message(container, "Hello Friends, this is RSd!", AgentAddress(aid=agent2.aid))
stepping_result = step_simulation(container, 1)
@test agent1.counter == 10
@test agent2.counter == 0
stepping_result = step_simulation(container, 1)
@test agent1.counter == 10
@test agent2.counter == 10
end
@agent struct SimSchedulingAgent
counter::Int
scheduled_counter::Int
end
function handle_message(agent::SimSchedulingAgent, message::Any, meta::AbstractDict)
agent.counter += 1
end
@testset "SimulationWithSpecificDelaysAndScheduledTasks" begin
com_sim = SimpleCommunicationSimulation(default_delay_s=0)
container = create_simulation_container(DateTime(0), communication_sim=com_sim)
agent1 = SimSchedulingAgent(0, 0)
agent2 = SimSchedulingAgent(0, 0)
register(container, agent1)
register(container, agent2)
com_sim.delay_s_directed_edge_dict[(nothing, aid(agent1))] = 1
com_sim.delay_s_directed_edge_dict[(nothing, aid(agent2))] = 2
schedule(agent1, PeriodicTaskData(0.1)) do
agent1.scheduled_counter += 1
end
schedule(agent1, InstantTaskData()) do
agent1.scheduled_counter += 100
end
send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid))
send_message(container, "Hello Friends, this is RSd!", AgentAddress(aid=agent2.aid))
stepping_result = step_simulation(container, 1)
@test agent1.counter == 1
@test agent1.scheduled_counter == 111
@test agent2.counter == 0
stepping_result = step_simulation(container, 1)
@test agent1.counter == 1
@test agent1.scheduled_counter == 121
@test agent2.counter == 1
end
@agent struct ComplexSimSchedulingAgent
counter::Int
scheduled_counter::Int
end
function handle_message(agent::ComplexSimSchedulingAgent, message::Any, meta::AbstractDict)
agent.counter += 1
schedule(agent, InstantTaskData()) do
agent.scheduled_counter += 100
end
end
@testset "SimulationWithSpecificDelaysAndScheduledTasksOnHandle" begin
com_sim = SimpleCommunicationSimulation(default_delay_s=0)
container = create_simulation_container(DateTime(0), communication_sim=com_sim)
agent1 = ComplexSimSchedulingAgent(0, 0)
agent2 = ComplexSimSchedulingAgent(0, 0)
register(container, agent1)
register(container, agent2)
com_sim.delay_s_directed_edge_dict[(nothing, aid(agent1))] = 1
com_sim.delay_s_directed_edge_dict[(nothing, aid(agent2))] = 2
schedule(agent1, PeriodicTaskData(0.1)) do
agent1.scheduled_counter += 1
end
send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid))
send_message(container, "Hello Friends, this is RSd!", AgentAddress(aid=agent2.aid))
stepping_result = step_simulation(container, 1)
@test agent1.counter == 1
@test agent1.scheduled_counter == 111
@test agent2.counter == 0
@test agent2.scheduled_counter == 0
stepping_result = step_simulation(container, 1)
@test agent1.counter == 1
@test agent1.scheduled_counter == 121
@test agent2.counter == 1
@test agent2.scheduled_counter == 100
end
@agent struct MoreComplexSimSchedulingAgent
counter::Int
scheduled_counter::Int
end
function handle_message(agent::MoreComplexSimSchedulingAgent, message::Any, meta::AbstractDict)
agent.counter += 1
schedule(agent, InstantTaskData()) do
agent.scheduled_counter += 100
if message == "Hello Friends, this is RSc!"
reply_to(agent, "ABC", meta)
end
end
end
@testset "SimulationWithSpecificDelaysWithReplyOnHandle" begin
com_sim = SimpleCommunicationSimulation(default_delay_s=0)
container = create_simulation_container(DateTime(0), communication_sim=com_sim)
agent1 = MoreComplexSimSchedulingAgent(0, 0)
agent2 = MoreComplexSimSchedulingAgent(0, 0)
register(container, agent1)
register(container, agent2)
com_sim.delay_s_directed_edge_dict[(nothing, aid(agent1))] = 1
com_sim.delay_s_directed_edge_dict[(nothing, aid(agent2))] = 2
schedule(agent1, PeriodicTaskData(0.1)) do
agent1.scheduled_counter += 1
end
send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid), agent2.aid)
send_message(container, "Hello Friends, this is RSd!", AgentAddress(aid=agent2.aid))
stepping_result = step_simulation(container, 1)
@test agent1.counter == 1
@test agent1.scheduled_counter == 111
@test agent2.counter == 1
@test agent2.scheduled_counter == 100
stepping_result = step_simulation(container, 1)
@test agent1.counter == 1
@test agent1.scheduled_counter == 121
@test agent2.counter == 2
@test agent2.scheduled_counter == 200
end
@testset "SimulationWithSpecificDelaysWithReplyOnHandleDiscreteEvent" begin
com_sim = SimpleCommunicationSimulation(default_delay_s=0)
container = create_simulation_container(DateTime(0), communication_sim=com_sim)
agent1 = MoreComplexSimSchedulingAgent(0, 0)
agent2 = MoreComplexSimSchedulingAgent(0, 0)
register(container, agent1)
register(container, agent2)
com_sim.delay_s_directed_edge_dict[(aid(agent2), aid(agent1))] = 1
com_sim.delay_s_directed_edge_dict[(nothing, aid(agent2))] = 2
schedule(agent1, InstantTaskData()) do
agent1.scheduled_counter += 1
end
schedule(agent1, InstantTaskData()) do
agent1.scheduled_counter += 1
end
send_message(container, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid), agent2.aid)
send_message(container, "Hello Friends, this is RSd!", AgentAddress(aid=agent2.aid))
stepping_result = step_simulation(container)
@test stepping_result.simulation_step_size_s == 0
@test agent1.counter == 0
@test agent1.scheduled_counter == 2
@test agent2.counter == 0
@test agent2.scheduled_counter == 0
stepping_result = step_simulation(container)
@test stepping_result.simulation_step_size_s == 1
@test agent1.counter == 1
@test agent1.scheduled_counter == 102
@test agent2.counter == 1
@test agent2.scheduled_counter == 100
stepping_result = step_simulation(container)
@test stepping_result.simulation_step_size_s == 1
@test agent1.counter == 1
@test agent1.scheduled_counter == 102
@test agent2.counter == 2
@test agent2.scheduled_counter == 200
stepping_result = step_simulation(container)
@test isnothing(stepping_result)
schedule(agent1, PeriodicTaskData(0.1)) do
agent1.scheduled_counter += 1
end
schedule(agent1, PeriodicTaskData(3)) do
# nothing
end
stepping_result = step_simulation(container)
@test stepping_result.simulation_step_size_s == 0
@test agent1.counter == 1
@test agent1.scheduled_counter == 103
@test agent2.counter == 2
@test agent2.scheduled_counter == 200
stepping_result = step_simulation(container)
@test stepping_result.simulation_step_size_s == 0.1
@test agent1.counter == 1
@test agent1.scheduled_counter == 104
@test agent2.counter == 2
@test agent2.scheduled_counter == 200
end
import Mango
@testset "SimulationSchedulerDetermineError" begin
s = SimulationScheduler(clock=Clock(DateTime(0)))
push!(s.queue, Task(""))
@test_throws "This should not happen! Did you schedule a task with zero sleep time?" Mango.determine_next_event_time_with(s, DateTime(0))
end
struct TestTaskSim <: TaskSimulation
end
@testset "SimulationSchedulerDetermineNoImplent" begin
@test_throws "Please implement determine_next_event_time(...)" Mango.determine_next_event_time(TestTaskSim())
end
@testset "SimulationContainerAgentsAreOrdered" begin
container = create_simulation_container(DateTime(0))
a1 = register(container, SimAgent(0))
a2 = register(container, SimAgent(1))
a3 = register(container, SimAgent(2))
a4 = register(container, SimAgent(3))
@test agents(container)[1] == a1
@test agents(container)[2] == a2
@test agents(container)[3] == a3
@test agents(container)[4] == a4
@test container[aid(a1)] == a1
@test container[1] == a1
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 1130 | """
This file contains all examples given in the documentation enclosed in julia testsets.
This is to catch example code breaking on changes to the framework.
"""
using Mango
using Test
using Parameters
using Sockets: InetAddr, @ip_str
@testset "SEND_AFTER_CLOSE" begin
addr = InetAddr(ip"127.0.0.1", 5555)
protocol = TCPProtocol(address=addr)
loop, tasks = init(
protocol,
() -> nothing,
(msg_data, sender_addr; receivers=nothing) -> nothing,
)
close(protocol)
res = send(protocol, addr, Vector{UInt8}())
@test !res
end
@testset "CLOSE_WHILE_AC" begin
addr = InetAddr(ip"127.0.0.1", 5555)
protocol = TCPProtocol(address=addr)
loop, tasks = init(
protocol,
() -> nothing,
(msg_data, sender_addr; receivers=nothing) -> nothing,
)
connection = acquire_tcp_connection(protocol.pool, addr)
task = Threads.@spawn begin
sleep(0.1)
release_tcp_connection(protocol.pool, addr, connection)
end
close(protocol)
@test length(protocol.pool.connections.keyedvalues[InetAddr(ip"127.0.0.1", 5555)]) == 0
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | code | 6961 | using Mango
using Test
using Graphs
@agent struct TopologyAgent
end
@testset "TestTopologyInjectsService" begin
topology = complete_topology(3)
container = create_tcp_container("127.0.0.1", 3333)
agent = nothing
per_node(topology) do node
agent = register(container, TopologyAgent())
add!(node, agent)
end
activate(container) do
send_message(container, "Yo", address(agent))
end
@test topology_neighbors(agent) == [address(container[1]),
address(container[2])]
end
@testset "TestCreateTopology" begin
container = create_tcp_container("127.0.0.1", 3333)
agent = nothing
create_topology() do topology
agent = register(container, TopologyAgent())
agent2 = register(container, TopologyAgent())
agent3 = register(container, TopologyAgent())
n1 = add_node!(topology, agent)
n2 = add_node!(topology, agent2)
n3 = add_node!(topology, agent3)
add_edge!(topology, n1, n2)
add_edge!(topology, n1, n3)
end
@test topology_neighbors(agent) == [address(agents(container)[2]),
address(agents(container)[3])]
@test topology_neighbors(agents(container)[2]) == [address(agents(container)[1])]
@test topology_neighbors(agents(container)[3]) == [address(agents(container)[1])]
end
@testset "TestModifyTopology" begin
container = create_tcp_container("127.0.0.1", 3333)
agent = nothing
topology = cycle_topology(4)
modify_topology(topology) do topology
agent = register(container, TopologyAgent())
agent2 = register(container, TopologyAgent())
agent3 = register(container, TopologyAgent())
n1 = add_node!(topology, agent)
n2 = add_node!(topology, agent2)
n3 = add_node!(topology, agent3)
add_edge!(topology, n1, n2)
add_edge!(topology, n1, n3)
end
@test topology_neighbors(agent) == [address(agents(container)[2]),
address(agents(container)[3])]
@test topology_neighbors(agents(container)[2]) == [address(agents(container)[1])]
@test topology_neighbors(agents(container)[3]) == [address(agents(container)[1])]
end
@testset "TestCreateTopologyDirected" begin
container = create_tcp_container("127.0.0.1", 3333)
agent = nothing
create_topology(directed=true) do topology
agent = register(container, TopologyAgent())
agent2 = register(container, TopologyAgent())
agent3 = register(container, TopologyAgent())
n1 = add_node!(topology, agent)
n2 = add_node!(topology, agent2)
n3 = add_node!(topology, agent3)
add_edge!(topology, n1, n2, directed=true)
add_edge!(topology, n1, n3, directed=true)
end
@test topology_neighbors(agent) == [address(agents(container)[2]),
address(agents(container)[3])]
@test length(topology_neighbors(agents(container)[2])) == 0
@test length(topology_neighbors(agents(container)[3])) == 0
end
@testset "TestOtherBuiltInTopologies" begin
topology = star_topology(4)
container = create_tcp_container("127.0.0.1", 3333)
per_node(topology) do node
add!(node, register(container, TopologyAgent()))
end
topology = cycle_topology(4)
per_node(topology) do node
add!(node, register(container, TopologyAgent()))
end
@test length(topology_neighbors(agents(container)[5])) == 2
@test length(topology_neighbors(agents(container)[6])) == 2
@test length(topology_neighbors(agents(container)[7])) == 2
@test length(topology_neighbors(agents(container)[8])) == 2
end
@testset "TestCustomGraphTopology" begin
cd = complete_digraph(5)
topology = graph_topology(cd)
container = create_tcp_container("127.0.0.1", 3333)
per_node(topology) do node
add!(node, register(container, TopologyAgent()))
end
@test length(topology_neighbors(agents(container)[1])) == 4
@test length(topology_neighbors(agents(container)[2])) == 4
@test length(topology_neighbors(agents(container)[3])) == 4
@test length(topology_neighbors(agents(container)[4])) == 4
@test length(topology_neighbors(agents(container)[5])) == 4
end
@role struct TopologyRole
end
@testset "TestCustomGraphTopologyRole" begin
cd = complete_digraph(5)
topology = graph_topology(cd)
container = create_tcp_container("127.0.0.1", 3333)
tr = TopologyRole()
per_node(topology) do node
add!(node, add_agent_composed_of(container, tr))
end
@test length(topology_neighbors(tr)) == 4
end
@testset "TestTopologyChooseAgent" begin
topology = cycle_topology(4)
container = create_tcp_container("127.0.0.1", 3333)
choose_agent(topology) do node
return register(container, TopologyAgent())
end
@test length(topology_neighbors(agents(container)[1])) == 2
@test length(topology_neighbors(agents(container)[2])) == 2
@test length(topology_neighbors(agents(container)[3])) == 2
@test length(topology_neighbors(agents(container)[4])) == 2
end
@testset "TestTopologyAssignAgent" begin
topology = cycle_topology(4)
container = create_tcp_container("127.0.0.1", 3333)
register(container, TopologyAgent())
register(container, TopologyAgent())
register(container, TopologyAgent())
register(container, TopologyAgent())
assign_agent(topology, container) do agent, node
return aid(agent) == "agent" * string(node.id - 1)
end
@test length(topology_neighbors(agents(container)[1])) == 2
@test length(topology_neighbors(agents(container)[2])) == 2
@test length(topology_neighbors(agents(container)[3])) == 2
@test length(topology_neighbors(agents(container)[4])) == 2
end
@testset "TestSetEdgeState" begin
container = create_tcp_container("127.0.0.1", 3333)
agent = nothing
topology = cycle_topology(4)
modify_topology(topology) do topology
agent = register(container, TopologyAgent())
agent2 = register(container, TopologyAgent())
agent3 = register(container, TopologyAgent())
n1 = add_node!(topology, agent)
n2 = add_node!(topology, agent2)
n3 = add_node!(topology, agent3)
add_edge!(topology, n1, n2)
add_edge!(topology, n1, n3)
set_edge_state!(topology, n1, n2, BROKEN)
end
@test topology_neighbors(agent) == [address(agents(container)[3])]
@test topology_neighbors(agents(container)[2]) == []
@test topology_neighbors(agents(container)[3]) == [address(agents(container)[1])]
end
@testset "TestTopologyRemoveEdgeRemoveNode" begin
topology = complete_topology(5)
container = create_tcp_container("127.0.0.1", 3333)
per_node(topology) do node
add!(node, register(container, TopologyAgent()))
end
modify_topology(topology) do topology
remove_edge!(topology, 1, 2)
remove_node!(topology, 3)
end
@test length(topology_neighbors(container["agent0"])) == 2
end | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 3122 | # Code of Conduct - Mango.jl
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, or to ban
temporarily or permanently any contributor for other behaviors that they deem
inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at <[email protected]>.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://contributor-covenant.org/), version
[1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct/code_of_conduct.md) and
[2.0](https://www.contributor-covenant.org/version/2/0/code_of_conduct/code_of_conduct.md),
and was generated by [contributing-gen](https://github.com/bttger/contributing-gen). | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 9171 | <!-- omit in toc -->
# Contributing to Mango.jl
First off, thanks for taking the time to contribute! ❤️
All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉
> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
> - Star the project
> - Tweet about it
> - Refer this project in your project's readme
> - Mention the project at local meetups and tell your friends/colleagues
> - Send your feedback (e.g. at [email protected] or directly on github if appropriate)
<!-- omit in toc -->
## Table of Contents
- [Code of Conduct](#code-of-conduct)
- [I Have a Question](#i-have-a-question)
- [I Want To Contribute](#i-want-to-contribute)
- [Reporting Bugs](#reporting-bugs)
- [Suggesting Enhancements](#suggesting-enhancements)
- [Your First Code Contribution](#your-first-code-contribution)
- [Improving The Documentation](#improving-the-documentation)
- [Styleguide](#styleguides)
## Code of Conduct
This project and everyone participating in it is governed by the
[Mango.jl Code of Conduct](https://github.com/OFFIS-DAI/Mango.jl/blob/master/CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code. Please report unacceptable behavior
to <[email protected]>.
## I Have a Question
> If you want to ask a question, we assume that you have read the available [Documentation](https://offis-dai.github.io/Mango.jl/stable/).
Before you ask a question, it is best to search for existing [Issues](https://github.com/OFFIS-DAI/Mango.jl/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first.
If you then still feel the need to ask a question and need clarification, we recommend the following:
- Open an [Issue](https://github.com/OFFIS-DAI/Mango.jl/issues/new) with the label `question`.
- Provide as much context as you can about what you're running into.
- Provide project and platform versions (julia version, os, etc), depending on what seems relevant.
We will then take care of the issue as soon as possible.
## I Want To Contribute
> ### Legal Notice <!-- omit in toc -->
> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license.
### Reporting Bugs
<!-- omit in toc -->
#### Before Submitting a Bug Report
A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.
- Make sure that you are using the latest version.
- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://offis-dai.github.io/Mango.jl/stable/). If you are looking for support, you might want to check [this section](#i-have-a-question)).
- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/OFFIS-DAI/Mango.jl/issues?q=label%3Abug).
- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue.
- Collect information about the bug:
- Stack trace (Traceback)
- OS, Platform and Version (Windows, Linux, macOS, x86, ARM)
- Version of the julia executables, maybe dependencies, whatever seems relevant.
- Possibly your console input and the output
- Can you reliably reproduce the issue? (And can you also reproduce it with older versions?)
<!-- omit in toc -->
#### How Do I Submit a Good Bug Report?
We use GitHub issues to track bugs and errors. If you run into an issue with the project:
- Open an [Issue](https://github.com/OFFIS-DAI/Mango.jl/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)
- Explain the behavior you would expect and the actual behavior.
- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case.
- Provide the information you collected in the previous section.
Once it's filed:
- The project team will label the issue accordingly.
- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced.
- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution).
### Suggesting Enhancements
This section guides you through submitting an enhancement suggestion for Mango.jl, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions.
<!-- omit in toc -->
#### Before Submitting an Enhancement
- Make sure that you are using the latest version.
- Read the [documentation](https://offis-dai.github.io/Mango.jl/stable/) carefully and find out if the functionality is already covered, maybe by an individual configuration.
- Perform a [search](https://github.com/OFFIS-DAI/Mango.jl/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library.
<!-- omit in toc -->
#### How Do I Submit a Good Enhancement Suggestion?
Enhancement suggestions are tracked as [GitHub issues](https://github.com/OFFIS-DAI/Mango.jl/issues).
- Use a **clear and descriptive title** for the issue to identify the suggestion.
- Provide a **step-by-step description of the suggested enhancement** in as many details as possible.
- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you.
- **Explain why this enhancement would be useful** to most Mango.jl users. You may also want to point out the other projects that solved it better and which could serve as inspiration.
### Your First Code Contribution
Mango.jl follows the typical guidelines for Julia-projects and it is mainly developed using the vscode julia extension.
The necessary steps for every contribution are:
* Fork the repository.
* Make your changes, ideally connected to an issue.
* Make sure you followed the styleguide below.
* Make sure you have written unit and integration tests.
* Execute the Mango.jl tests locally! Some tests require a running MQTT broker, for details take a look at (https://github.com/OFFIS-DAI/Mango.jl/blob/development/.github/workflows/test-mango.yml).
* Create a pull request.
* Look at the output of github actions, we require that all tests pass and that the code-coverage of the diff is at least on par with the existing codebase
* If all checks look fine, a maintainer will start to handle the pull request
### Improving The Documentation
For improving the documentation you can either create an issue (advised if you would not be able to create or update the documentation yourself) or improve the documentation by yourself.
Minor documentation improvements generally do not need a separate issue. For bigger reworks it is advisable to create an issue first and discuss the changes which need to be made.
## Styleguides
Generally we follow the general julia style-guide (https://docs.julialang.org/en/v1/manual/style-guide/).
<!-- omit in toc -->
## Attribution
This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)!
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 6611 |
<p align="center">


</p>
[Docs](https://offis-dai.github.io/Mango.jl/stable)
| [GitHub](https://github.com/OFFIS-DAI/Mango.jl) | [mail](mailto:[email protected])
<!-- Tidyverse lifecycle badges, see https://www.tidyverse.org/lifecycle/ Uncomment or delete as needed. -->

[](https://github.com/OFFIS-DAI/Mango.jl/blob/development/LICENSE)
[](https://github.com/OFFIS-DAI/Mango.jl/actions/workflows/test-mango.yml)
[](https://codecov.io/gh/OFFIS-DAI/Mango.jl)
<!--





-->
Mango.jl allows the user to create simple agents with little effort and in the same time offers options to structure agents with complex behaviour.
The agents agents can run in two different ways: in **real-time**, or **simulated**. In real-time, the agents will run as fast as possible and communicate as specified by the protocol ("they run as developed"). In the simulation mode, the agent system and their specified tasks will be scheduled and stepped (continous or discrete) and the communication will be simulated using articial delays. One big unique characteristic of Mango.jl is that both ways use the same agent-api, meaning you can develop, evaluate your agent system in a controlled simulated environment and then transfer it to a real-time setting without (majorly) changing the implementation of your agents, as both execution ways use the same API with different environments (and containers).
**Note:** _This project is still in an early development stage.
We appreciate constructive feedback and suggestions for improvement._
## Features
* Container mechanism to speedup local message exchange
* Structuring complex agents with loose coupling and agent roles
* Built-in codecs
* Supports communication between agents directly via TCP and MQTT
* Built-in tasks mechanisms for proactive agent actions
* Continous and discrete stepping simulation using an external clock to rapidly run and inspect simulations designed for longer time-spans
* Integrated communication and task simulation modules
* Integrated environment with which the agents can interact in a common space
## Installation
`Mango.jl` is registered to JuliaHub.
To add it to your Julia installation or project you can use the Julia REPL by calling `]add Mango` or `import Pkg; Pkg.add("Mango")` directly:
```
> julia --project=. ✔
_
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.10.4 (2024-06-04)
_/ |\__'_|_|_|\__'_| |
|__/ |
(project_name) pkg> add Mango
Updating registry at `~/.julia/registries/General.toml`
[...]
```
## Example
The following simple showcase demonstrates how you can define agents in Mango. Jl, assign them to containers and send messages via a TCP connection. For more information on the specifics and other features (e.g. MQTT, modular agent using roles, simulation, tasks), please have a look at our [Documentation](https://offis-dai.github.io/Mango.jl/stable)!
```julia
using Mango
# Create the container instances with TCP protocol
container = create_tcp_container("127.0.0.1", 5555)
container2 = create_tcp_container("127.0.0.1", 5556)
# An agent in `Mango.jl` is a struct defined with the `@agent` macro.
# We define a `TCPPingPongAgent` that has an internal counter for incoming messages.
@agent struct TCPPingPongAgent
counter::Int
end
# Create instances of ping pong agents
ping_agent = TCPPingPongAgent(0)
pong_agent = TCPPingPongAgent(0)
# register each agent to a container and give them a name
register(container, ping_agent, "Agent_1")
register(container2, pong_agent, "Agent_2")
# When an incoming message is addressed at an agent, its container will call the `handle_message` function for it.
# Using Julias multiple dispatch, we can define a new `handle_message` method for our agent.
function Mango.handle_message(agent::TCPPingPongAgent, message::Any, meta::Any)
agent.counter += 1
println(
"$(agent.aid) got a message: $message." *
"This is message number: $(agent.counter) for me!"
)
# doing very important work
sleep(0.5)
if message == "Ping"
reply_to(agent, "Pong", meta)
elseif message == "Pong"
reply_to(agent, "Ping", meta)
end
end
# With all this in place, we can send a message to the first agent to start the repeated message exchange.
# To do this, we need to start the containers so they listen to incoming messages and send the initating message.
# The best way to start the container message loops and ensure they are correctly shut down in the end is the
# `activate(containers)` function.
activate([container, container2]) do
send_message(ping_agent, "Ping", address(pong_agent))
# wait for 5 messages to have been sent
while ping_agent.counter < 5
sleep(1)
end
end
```
## License
Mango.jl is developed and published under the MIT license.
<!-- travis-ci.com badge, uncomment or delete as needed, depending on whether you are using that service. -->
<!-- [](https://travis-ci.com/mango/mango.jl) -->
<!-- Coverage badge on codecov.io, which is used by default. -->
<!-- Documentation -- uncomment or delete as needed -->
<!--
[](https://mango.github.io/mango.jl/stable)
[](https://mango.github.io/mango.jl/dev)
-->
<!-- Aqua badge, see test/runtests.jl -->
<!-- [](https://github.com/JuliaTesting/Aqua.jl) -->
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 688 | ## Checklist
- [ ] Did you read the [contributing guide](https://github.com/OFFIS-DAI/Mango.jl/blob/contribution-guidelines/CONTRIBUTING.md)
- [ ] Do you have a meaningful commit history?
- [ ] Do follow the style guide meantioned in the contribution guidelines?
- [ ] Did you execute the tests locally?
## Description
* Reference the issue you are working on (except for minor contributions it is preferred to open an issue first before the code contributions!)
or
* **OR** Describe the issue you tackled and why it should be merged to Mango.jl
## Implementation details
Share any implementation details/decisions/reasonings you think are relevant for reviewing the pull request. | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 686 | ---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Full code to reproduce the issue
2. The console input
**The console output**
Add the full console output, especially the stack trace (if applicable)
**Expected behavior**
A clear and concise description of what you expected to happen.
**Environment (please complete the following information):**
- OS: [e.g. GNU-Linux-OS/macOS]
- OS-Version [e.g. 22]
- Julia Version: [e.g. 1.9]
**Additional context**
Add any other context about the problem here.
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 557 | ---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Statement of need**
A clear and concise description of why you think this feature is necessary.
**Additional context**
Add any other context or screenshots about the feature request here.
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 6731 | # Agents
Agents are autonomous entities that can perceive their environment, make decisions, and interact with other agents and the system they inhabit. They are the building blocks of Mango.jl, representing the individual entities or actors within a larger system.
## Agent Definition with @agent Macro
To define an agent the [`@agent`](@ref) macro can be used. It simplifies the process of defining an agent struct and automatically adds necessary baseline fields. Here's how you can define an agent:
```@example
using Mango
# Define your agent struct using @agent macro
@agent struct MyAgent
my_own_field::String
end
# Create an instance of the agent
my_agent = MyAgent("MyValue")
```
The [`@agent`](@ref) macro adds some internal baseline fields to the struct. You can initialize the agent with exclusive fields like `my_own_field` in the example.
## Role Management
Agents can have multiple roles associated with them. Roles can be added using the [`add`](@ref) function, allowing the agent to interact with its environment based on different roles. Here's how you can add roles to an agent:
```@example
using Mango
# Define your role struct using @role macro
@role struct MyRole
my_own_field::String
end
# Assume you have already defined roles using Mango.AgentRole module
role1 = MyRole("Role1")
role2 = MyRole("Role2")
# Define your agent struct using @agent macro
@agent struct MyContainerAgent end
# Create an instance of the agent
my_agent = MyContainerAgent()
# Add roles to the agent
add(my_agent, role1)
add(my_agent, role2)
# Now you can interact with the roles as neededs
```
As this can be clunky at some time, there is the possibility to create an agent using only roles and add it to the container using [`add_agent_composed_of`](@ref) or without a container [`agent_composed_of`](@ref).
```@example
using Mango
c = create_tcp_container()
@role struct RoleA end
@role struct RoleB end
@role struct RoleC end
# internally an empty agent definition is used, the roles are added and the agent
# is added to the given container
created_agent = add_agent_composed_of(c, RoleA(), RoleB(), RoleC())
```
For more information on roles, take a look at [Role definition](@ref)
## Message Handling
Agents and Roles can handle incoming messages through the [`handle_message`](@ref) function. By default, it does nothing, but you can override it to define message-specific behavior. You can also add custom message handlers for specific roles using the [`subscribe_message`](@ref) function. Here's how to handle messages:
```@example
using Mango
@agent struct MySecondContainerAgent end
@role struct MyHandlingRole end
# Override the default handle_message function for custom behavior
function Mango.handle_message(agent::MySecondContainerAgent, message::Any, meta::Any)
println("Received message @agent: ", message)
end
# Override the default handle_message function for custom behavior
function Mango.handle_message(role::MyHandlingRole, message::Any, meta::Any)
println("Received message @role: ", message)
end
# Use the express API to show the effect
run_with_tcp(1, agent_composed_of(MyHandlingRole(), base_agent=MySecondContainerAgent())) do cl
wait(send_message(cl[1], "Message", address(cl[1][1])))
sleep(0.1)
end
```
Besides the ability to handle messages, there also must be a possibility to send messages. This is implemented using the [`send_message`](@ref) function, defined on roles and agents.
```@example
using Mango
# Define your agent struct using @agent macro
@agent struct MySendingAgent
my_own_field::String
end
@role struct MySendingRole
my_own_field::String
end
agent = MySendingAgent("")
role = MySendingRole("")
run_with_tcp(1, agent_composed_of(role, base_agent=agent), PrintingAgent()) do cl
wait(send_message(agent, "Message", address(cl[1][2])))
wait(send_message(role, "Message", address(cl[1][2])))
sleep(0.1)
end
```
Further, there are several specialized methods for sending messages, (1) [`send_tracked_message`](@ref), (2) [`send_and_handle_answer`](@ref), (3) [`reply_to`](@ref), (4) [`forward_to`](@ref).
(1) This function can be used to send a message with an automatically generated tracking id (uuid1) and it also accepts a response handler, which will
automatically be called when a response arrives to the tracked message (care to include the tracking id when responding or just use [`reply_to`](@ref)).
(2) Variant of (1) which requires a response handler and enables the usage of the `do` syntax (see following code snippet).
(3) Convenience function to respond to a received message without the need to create the AgentAddress by yourself.
(4) Convenience function to forward messages to another agent. This function will set the approriate fields in the meta container to identify that a message has been forwarded and from which address it has been forwarded.
```@example
using Mango
@agent struct MyMessageAgent end
@agent struct ReplyAgent end
agent1 = MyMessageAgent()
agent2 = PrintingAgent() # defined in Mango
agent3 = ReplyAgent()
function Mango.handle_message(agent::ReplyAgent, message::Any, meta::Any)
# agent 3
reply_to(agent, "Hello Agent, this is a response", meta) # (3)
@info "Reply"
end
function handle_response(agent::MyMessageAgent, message::Any, meta::Any)
# agent 1
forward_to(agent, "Forwarded message", address(agent2), meta) # (4)
@info "Handled response and forwarded the message" message
end
run_with_tcp(1, agent1, agent2, agent3) do cl
wait(send_tracked_message(agent1, "Hello Agent, this is a tracked message", address(agent3); response_handler=handle_response)) # (1)
wait(send_and_handle_answer(agent2, "Hello Agent, this is a different tracked message", address(agent3)) do agent, message, meta # (2)
@info "Got an answer!"
end)
sleep(0.1)
end
```
There is also a possibility to enable automatic forwarding with adding so-called forwarding rules. For this you can use the function [`add_forwarding_rule`](@ref). To delete these rules the function [`delete_forwarding_rule`](@ref) exists.
## Task Scheduling
Agents can schedule tasks using the [`schedule`](@ref) function, which delegates to the [`Mango.schedule`](@ref) function. You can wait for all scheduled tasks to be completed using [`wait_for_all_tasks`](@ref). Here's how to schedule tasks:
```@example
using Mango
# Define your agent struct using @agent macro
@agent struct MyTaskAgent
my_own_field::String
end
function my_task_function()
@info "Task completed"
end
# Create an instance of the agent
my_agent = MyTaskAgent("MyValue")
# Schedule a task for the agent
wait(schedule(my_task_function, my_agent, InstantTaskData()))
```
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 1592 | # API
# Express
This part contains basic convenience functions for creating and running Mango.jl simulations.
```@autodocs
Modules = [Mango]
Private = false
Pages = ["express/api.jl"]
```
# Agent and Roles
Here, the API for the agent structs created with @agent/@role is listed.
```@autodocs
Modules = [Mango]
Private = false
Pages = ["agent/api.jl", "agent/core.jl", "agent/role.jl"]
Order = [:macro, :function, :constant, :type, :module]
```
# Real time container
This part contains the API related to the container construction, access and management.
```@autodocs
Modules = [Mango]
Private = false
Pages = ["container/api.jl", "container/core.jl", "container/mqtt.jl", "container/protocol.jl", "container/tcp.jl"]
```
# Simulation
In the following the APIs regarding the simulation container are listed.
```@autodocs
Modules = [Mango]
Private = false
Pages = ["container/simulation.jl", "simulation/communication.jl", "simulation/tasks.jl"]
```
# Scheduling
In the following the APIs for scheduling TaskData is listed.
```@autodocs
Modules = [Mango]
Private = false
Pages = ["util/scheduling.jl"]
```
# Topology
In the following the APIs for creating, aplying and using topologies is listed.
```@autodocs
Modules = [Mango]
Private = false
Pages = ["world/topology.jl"]
```
# Encoding/Decoding
In the following the built-in functions for encoding and decoding messages are listed.
```@autodocs
Modules = [Mango]
Private = false
Pages = ["util/encode_decode.jl"]
```
# Misc
```@autodocs
Modules = [Mango]
Private = false
Pages = ["util/datastructures_util.jl"]
``` | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 7170 | # Real Time Container
The real time container feature in Mango.jl allows you to create and manage a container, which acts as the communication layer within the environment. A container is responsible for handling messages, forwarding them to the appropriate agents, and managing agent registration. The real time component means that the container acts on a real time clock, and does not differentiate between a simulation time and the execution time, which essentially means everything executed withing the real time container is executed immediately as stated in the code. In contrast, there is also a "simulation" container, which maintains an interal simulation time and only executes tasks and delivers messages according to the requested step_sizes (next event time). More on the simulation container can be found under [Simulation Container](@ref). Note, that both container types implement the methods for the [`ContainerInterface`](@ref) and can therefore be drop-in replacements for the each other with slight differences in usage.
## Container Struct
The [`Container`](@ref) struct represents the container as an actor within the environment. It is implemented using composition, making it flexible to use different protocols and codecs for message communication. The key components of the [`Container`](@ref) struct are:
- `protocol`: The protocol used for message communication (e.g., TCP).
- `codec`: A pair of functions for encoding and decoding messages in the container.
## Start and Shutdown
Before using the container for message handling and agent management, you need to start the container using the [`start`](@ref) function. This function initializes the container's components and enables it to act as the communication layer. After you are done with the container, [`shutdown`](@ref) has to be called.
```@example
using Mango
# Create a container instance
container = Container()
# ... setup the container, agents, define handles, ...
# Start the container
wait(Threads.@spawn start(container))
# Execute some functionality to e.g. trigger the agent system
# Shut down the container
shutdown(container)
@info "Agent container and agents shutdown"
```
However, this approach can be error-prone for multiple reasons. Besides simply forgetting to call shutdown, an exception may occur between the start and shutdown calls on the containers, leading to resource leaks. For this reason, we recommend using [`activate`](@ref) instead. With this function, the above `start/shutdown' pair translates to...
```julia
# Start the container and shut it down after the runnable (do ... end) has been executed.
activate(container) do
# Execute some functionality to e.g. trigger the agent system
end
```
## Registering Agents
To enable the container to manage agents and handle their messaging activities, you can register agents using the [`register`](@ref) function. This function associates an agent with a unique agent ID (AID) and adds the agent to the container's internal list.
```@example
using Mango
# Create a container instance
container = Container()
# Define and create an agent
@agent struct MyAgent
# Your agent's fields and methods here
end
my_agent = MyAgent()
# Register the agent with the container
register(container, my_agent)
```
## Sending Messages
To send messages between agents within the container, you can use the [`send_message`](@ref) function. The container routes the message to the specified receiver agent based on the receiver's AID.
```@example
using Mango
# Create a container instance
container = Container()
agent = register(container, PrintingAgent())
# ... Register agents ...
# Sending a message from one agent to another
wait(send_message(container, "Hello from Agent 1!", address(agent)))
```
## TCP
This protocol allows communication over plain TCP connections, enabling message exchange between different entities within the Mango.jl simulation environment.
### Introduction
The TCP Protocol in Mango.jl is a communication protocol used to exchange messages over plain TCP connections. It enables agents within the simulation environment to communicate with each other by establishing and managing TCP connections.
### TCPProtocol Struct
The [`TCPProtocol`](@ref) struct represents the TCP Protocol within Mango.jl. It encapsulates the necessary functionalities for communication via TCP connections. Key features of the [`TCPProtocol`](@ref) struct are:
- `address`: The `InetAddr` represents the address on which the TCP server listens.
- `server`: A `TCPServer` instance used for accepting incoming connections.
### Usage
To use the tcp protocol you need to construct a TCPProtocol struct and assign it to the `protocol` field in the container.
```@example
using Mango, Sockets
container2 = Container()
container2.protocol = TCPProtocol(address=Sockets.InetAddr("127.0.0.2", 2940))
```
It is also possible to use the convenience function [`create_tcp_container`](@ref).
```@example
using Mango
container2 = create_tcp_container("127.0.0.2", 2940)
```
## MQTT
### Introduction
The MQTT protocol enables sending via an MQTT message broker.
It allows a container to subscribe to different topics on a broker and publish messages to them.
Currently, one container may only connect to a single broker.
Subscribed topics for each agent are set on agent registration and tracked by the container.
Incoming messages on these topics are distributed to the subscribing agents by the container.
### MQTTProtocol Struct
The [`MQTTProtocol`](@ref) contains the status and channels of the underlying mosquitto C library (as abstracted to Julia by the Mosquitto.jl package).
The constructor takes a `client_id` and the `broker_addr`.
Internally it also tracks the `msg_channel` and `conn_channel`, internal flags, the information to map topics to subscribing agents.
`protocol = MQTTProtocol(cliant_id, broker_addr)`
- `client_id` - `String` id the container will communicate to the MQTT broker.
- `broker_addr` - `InetAddr` of the MQTT broker
### Usage
To use the mqtt protocol you need to construct a MQTTProtocol struct and assign it to the `protocol` field in the container. Further it is possible to use a convenience function for this
It is also possible to use the convenience function [`create_mqtt_container`](@ref).
```julia
using Mango, Sockets
container2 = Container()
container2.protocol = MQTTProtocol("my_id", Sockets.InetAddr(ip"127.0.0.2", 2940))
```
!!! note "Running MQTT broker expected"
The MQTT protocol expects an MQTT broker to run at the specified host and port.
Subscribing an agent to a topic can happen only as registration time and is not allowed otherwise.
When registering a new agent to the container the topics to subscribe are passed by the `topics` keyword argument, taking a collection of `String` topic names.
NOTE: It is recommended you pass a `Vector{String}` as this is what is tested.
Other collections could work but no guarantees are given.
```julia
using Mango
container2 = create_mqtt_container("127.0.0.2", 2940, "MyMqttClient")
a1 = PrintingAgent()
register(container2, a1; topics=["topic1", "topic2"])
``` | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 985 | # Mango.jl Encoding and Decoding (codec) Feature User Documentation
Codecs provide functions for serializing and deserializing data to Mango containers.
They use [LightBSON.jl](https://github.com/ancapdev/LightBSON.jl) as their backend.
As of now, the [`encode`](@ref) and [`decode`](@ref) functions forward their inputs directly to `bson_read` and `bson_write`.
For most cases, we expect to pass messages as `OrderedDict{String, Any}`.
We also forward an optional type field when decoding that is passed to `bson_write` to make use of the existing type-casting functionality here.
For full information on what will work with this type of inference, we refer to the LightBSON.jl documentation.
For future versions, we plan on adding a more convenient (but likely slower) type inference variant of the codec that saves necessary type information when encoding and iterates the output data while decoding to restore it exactly as it was before encoding (including type information).
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 6647 | # Getting Started with Mango.jl
In this getting started guide, we will explore the essential features of Mango.jl, starting with a simple example using the express-api, followed by a more in-depth example of two ping pong agents that exchange messages in a container. Here, we will manually set up a container with the TCP protocol, define ping pong agents, and enable them to exchange messages. This way allows better customization but may need more boilerplate code.
You can also find working examples of the following code in [examples.jl](../../test/examples.jl).
## 0. Quickstart
In Mango.jl, you can define agents using a number of roles using [`@role`](@ref) and [`agent_composed_of`](@ref), or directly using [`@agent`](@ref). To define the behavior of the agents, [`handle_message`](@ref) can be defined, and messages can be send using [`send_message`](@ref). To run the agents with a specific protocol in real time the fastest way is to use [`run_with_tcp`](@ref), which will distribute the agents to tcp-containers and accepts a function in which some agent intializiation and/or trigger-code could be put. The following example illustrates the basic usage of the functions.
```jldoctest
using Mango
@role struct PrintingRole
out::Any = ""
end
function Mango.handle_message(role::PrintingRole, msg::Any, meta::AbstractDict)
role.out = msg
end
express_one = agent_composed_of(PrintingRole())
express_two = agent_composed_of(PrintingRole(), PrintingRole())
run_with_tcp(2, express_one, express_two) do container_list
wait(send_message(express_one, "Ping", address(express_two)))
sleep_until(() -> express_two[1].out == "Ping")
end
# evaluating
express_two[1].out
# output
"Ping"
```
## Step-by-step (manual container creation)
Alternatively you can create the container yourself. This is the more flexible approach, but also wordier.
### 1. Creating a Container with a TCP Protocol
we need to create a container to manage ping pong agents and facilitate communication using the TCP protocol:
```@example tcp_gs
using Mango, Sockets
# Create the container instances with TCP protocol
container = create_tcp_container("127.0.0.1", 5555)
container2 = create_tcp_container("127.0.0.1", 5556)
```
### 2. Defining Ping Pong Agents
Let's define agent structs to represent the ping pong agents. Every new agent struct should be defined using the @agent macro to ensure compatibility with the mango container:
```@example tcp_gs
# Define the ping pong agent
@agent struct TCPPingPongAgent
counter::Int
end
```
### 3. Sending and Handling Messages
Ping pong agents can exchange messages and they can keep track of the number of messages received. Let's implement message handling for the agents. To achieve this a new method [`handle_message`](@ref) from `Mango` has to be added:
```@example tcp_gs
# Override the default handle_message function for ping pong agents
function Mango.handle_message(agent::TCPPingPongAgent, message::Any, meta::Any)
agent.counter += 1
println(
"$(agent.aid) got a message: $message." *
"This is message number: $(agent.counter) for me!"
)
# doing very important work
sleep(0.5)
if message == "Ping"
reply_to(agent, "Pong", meta)
elseif message == "Pong"
reply_to(agent, "Ping", meta)
end
end
```
### 4. Sending Messages
Now let's simulate the ping pong exchange by sending messages between the ping pong agents.
Addresses are provided to the [`send_message`](@ref) function via the [`AgentAddress`](@ref) struct.
The struct consists of an `aid` and the more technical `address` field. Further an AgentAddress
can contain a `tracking_id`, which can identify the dialog agents are having.
The [`send_message`](@ref) method here will automatically insert the agent as sender:
```@example tcp_gs
# Define the ping pong agent
# Create instances of ping pong agents
ping_agent = register(container, TCPPingPongAgent(0))
pong_agent = register(container2, TCPPingPongAgent(0))
activate([container, container2]) do
# Send the first message to start the exchange
send_message(ping_agent, "Ping", address(pong_agent))
# wait for 5 messages to have been sent
sleep_until(() -> ping_agent.counter >= 5)
end
```
In this example, the ping pong agents take turns sending "Ping" and "Pong" messages to each other, incrementing their counters. After a short moment, we can see the result of the ping pong process.
### 5. Using the MQTT Protocol
To use an MQTT messsage broker instead of a direkt TCP connection, you can use the MQTT protocol. This protocol requires a running MQTT broker. For this you can, for example, use Mosquitto as broker. On most linux-based systems mosquitto exists as package in the public repostories. For example for debian systems:
```bash
sudo apt install mosquitto
sudo service mosquitto start
```
After, you can create MQTT container.
```julia
using Mango
c1 = create_mqtt_container("127.0.0.1", 1883, "PingContainer")
c2 = create_mqtt_container("127.0.0.1", 1883, "PongContainer")
```
The topics each agent subscribes to on the broker are provided during registration to the container.
All messages on these topics will then be forwarded as messages to the agent.
```julia
# Define the ping pong agent
@agent struct MQTTPingPongAgent
counter::Int
end
# Define the ping pong agent
# Create instances of ping pong agents
# register each agent to a container
# For the MQTT protocol, topics for each agent have to be passed here.
ping_agent = register(c1, MQTTPingPongAgent(0); topics=["pongs"])
pong_agent = register(c2, MQTTPingPongAgent(0); topics=["pings"])
```
Just like the TCPProtocol, the MQTTProtocol has an associated struct for providing address information:
* the broker address
* the topic
Thus, sending of the first message and the handle_message definition becomes:
Lastly, [`handle_message`](@ref) has to be altered to send the corresponding answers correctly:
```julia
# Override the default handle_message function for ping pong agents
function handle_message(agent::MQTTPingPongAgent, message::Any, meta::Any)
broker_addr = agent.context.container.protocol.broker_addr
if message == "Ping"
agent.counter += 1
send_message(agent, "Pong", MQTTAddress(broker_addr, "pongs"))
elseif message == "Pong"
agent.counter += 1
send_message(agent, "Ping", MQTTAddress(broker_addr, "pings"))
end
end
activate([c1, c2]) do
# Send the first message to start the exchange
send_message(ping_agent, "Ping", MQTTAddress(broker_addr, "pings"))
sleep_until(() -> ping_agent.counter >= 5)
end
```
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 1284 | # Mango.jl
## Welcome to mango's documentation!
Mango.jl allows the user to create simple agents with little effort and at the same time offers options to structure agents with complex behaviour. The main features of mango are listed below.
Mango.jl as a package is partly based on the ideas of [mango-agents](https://mango-agents.readthedocs.io), but will also contain new concepts and techniques. It was made with the picture of scalable agent simulations in mind.
## Features
* Container mechanism to speedup local message exchange
* Structuring complex agents with loose coupling and agent roles
* Built-in codecs
* Supports communication between agents directly via TCP and MQTT
* Built-in tasks mechanisms for proactive agent actions
* Continous and discrete stepping simulation using an external clock to rapidly run and inspect simulations designed for longer time-spans
* Integrated communication and task simulation modules
* Integrated environment with which the agents can interact in a common space
## Development state
Mango.jl is in an early development state. Feel free to try out the framework if you are interested and be aware that there might be some unexpected edges here and there.
## License
Mango.jl is developed and published under the MIT license.
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 1134 | # Legals
**Address**
OFFIS e. V.
Escherweg 2
26121 Oldenburg
Germany
Phone +49 441 9722-0
Fax +49 441 9722-102
Email: [institut [ A T ] offis.de](<[email protected]>)
Internet: [www.offis.de](http://www.offis.de)
**Board Members**
Prof. Dr. Sebastian Lehnhoff (Chairman)
Prof. Dr. techn. Susanne Boll-Westermann
Prof. Dr.-Ing. Andreas Hein
Prof. Dr.-Ing. Astrid Nieße
**Register Court**
Amtsgericht Oldenburg
Registernumber VR 1956
**VAT Identification Number**
DE 811582102
**Responsible in the sense of press law**
Dr. Ing. Jürgen Meister (Director)
OFFIS e.V.
Escherweg 2
26121 Oldenburg
**Disclaimer**
Despite careful control OFFIS assumes no liability for the content of external links. The operators of such a website are solely responsible for its content. At the time of linking the concerned sites were checked for possible violations of law. Illegal contents were not identifiable at that time. A permanent control of the linked pages is not reasonable without specific indications of a violation. Upon notification of violations, OFFIS will remove such links immediately.
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 3932 | # Roles
Roles are used to provide a mechanism for reusability and modularization of functionsalities provided/implemented by agents. Every agent can contain and unlimited number of roles, which are separate structs on which typical agent functionalitites (like send_message) can be defined. All roles of an agent share the same address and agent id, as they are part of the agent and no autonomous unit for themself.
## Role definition
A role can be defined using the [`@role`](@ref) macro. This macro adds some baselinefields to the following struct definition. The struct can be defined like any other Julia struct.
```@example
using Mango
# Define your role struct using @role macro
@role struct MyRole
my_own_field::String
end
# Assume you have already defined roles using Mango.AgentRole module
role1 = MyRole("Role1")
```
Most functions, used for agent development can also be used with roles (e.g. [`handle_message`](@ref), [`address`](@ref), [`schedule`](@ref), [`send_message`](@ref) (plus variants) and the lifecycle methods).
Additionally, roles can define the [`setup`](@ref) function to define actions to take when the roles are added to the agent. It is also possible to subscribe to specific messages using a boolean expression with the [`subscribe_message`](@ref) function. With the @role macro, the role context is added to the role, which contains the reference to the agent. However, it is recommended to use the equivalent methods defined on the role to execute actions like scheduling and sending messages. Further with roles it is possible to listen to all messages sent from within the agent. For this [`subscribe_send`](@ref) can be used.
## Role communication
Besides the message subscriptions there are functionalities to communicate/work together with other roles. There are two different mechanisms for this:
* Data sharing
* An event system
### Data sharing
The data sharing can be used using ordinary Julia structs with default constructors. There are two ways to share the data, first you can create the model you want share with
[`get_model`](@ref)
```@example model_example
using Mango
@role struct SharedModelTestRole end
struct TestModel
c::Int64
end
TestModel() = TestModel(42)
agent = agent_composed_of(SharedModelTestRole())
shared_model = get_model(agent[1], TestModel)
```
Mango.jl will create a TestModel instance and manage this instance such that every role can access it.
Although this is a straightforward method it can be very clumsy to use. For this reason there is the macro [`@shared`](@ref), which can be used within a role definition
to mark a field as shared model. Then, Mango.jl will ensure that a shared instance of the declared type will be created and assigned to the struct field.
```@example model_example
@role struct SharedFieldTestRole
@shared
test_model::TestModel
end
agent_including_test_role = agent_composed_of(SharedFieldTestRole())
agent_including_test_role[1].test_model
```
### Event system
Roles can emit events using [`emit_event`](@ref). If `event_type` is nothing, the type of `event` will be used as `event_type`. To handle these events roles can subscribe using [`subscribe_event`](@ref) or add a method to [`handle_event`](@ref).
```@example
using Mango
struct TestEvent end
function Mango.handle_event(role::Role, src::Role, event::TestEvent; event_type::Any)
@info "Event is arriving!" role.name
end
function custom_handler(role::Role, src::Role, event::Any, event_type::Any)
@info "Event is also arriving!"
end
@agent struct RoleTestAgent end
@role struct MyEventRole
name::String
end
role_emitter = MyEventRole("emitter")
role_handler = MyEventRole("handler")
agent = agent_composed_of(role_emitter, role_handler; base_agent=RoleTestAgent())
subscribe_event(role_handler, TestEvent, custom_handler, (src, event) -> true) # condition is optional
emit_event(role_emitter, TestEvent())
``` | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 4164 | # Scheduling
The `Scheduling` module exports several types and functions to facilitate task scheduling and execution. Let's briefly review the main components of this module.
## Task Data Types
The module provides different [`TaskData`](@ref) types, each catering to specific scheduling requirements:
1. [`PeriodicTaskData`](@ref): For tasks that need to be executed periodically, it holds the time interval in seconds between task executions.
2. [`InstantTaskData`](@ref): For tasks that need to be executed instantly, without any delay.
3. [`DateTimeTaskData`](@ref): For tasks that need to be executed at a specific date and time.
4. [`AwaitableTaskData`](@ref): For tasks that require waiting for an awaitable object to complete before execution.
5. [`ConditionalTaskData`](@ref): For tasks that execute based on a specific condition at regular intervals.
## Typical usage
Typically the scheduler is used within methods from the agent. To schedule a task the function [`schedule`](@ref) can be used. It takes two inputs: The agent (which forwards the call to its scheduler) and the TaskData object of the task.
```@example scheduling
using Mango
@agent struct MyAgent end
agent = MyAgent()
result = 0
t = schedule(agent, InstantTaskData()) do
# some expensive calculation
result = 10
end
wait(t)
```
[`PeriodicTaskData`](@ref) creates tasks that get executed repeatedly forever.
This means that calling `wait` on such a task will generally simply block forever.
For this reason a periodic task has to be stopped before it can be waited on.
```@example scheduling
delay_in_s = 0.1 # delay between executions of the task in seconds
result = 0
t = schedule(agent, PeriodicTaskData(delay_in_s)) do
# some expensive calculation
println("iterated")
end
sleep(0.2)
stop_task(agent, t)
wait_for_all_tasks(agent)
```
Alternatively, you can stop all `stopable` tasks simultaneously with the [`stop_all_tasks`](@ref) function.
```@example scheduling
delay_in_s = 0.1 # delay between executions of the task in seconds
for i in 1:10
schedule(agent, PeriodicTaskData(delay_in_s)) do
# some expensive calculation
println("iterated")
end
end
sleep(0.2)
stop_all_tasks(agent)
wait_for_all_tasks(agent)
```
Finally, [`stop_and_wait_for_all_tasks`](@ref) is a convenience methods combining both [`stop_all_tasks`](@ref) and [`wait_for_all_tasks`](@ref).
## Scheduler
The [`Scheduler`](@ref) type is an internal structure that holds a collection of tasks to be scheduled and executed. Every agent contains such a scheduler struct by default and implements methods for convenient delegation.
```julia
struct Scheduler
tasks::Vector{Task}
end
```
The [`execute_task`](@ref) function executes a task with a specific [`TaskData`](@ref).
```julia
execute_task(f::Function, data::PeriodicTaskData)
execute_task(f::Function, data::InstantTaskData)
execute_task(f::Function, data::DateTimeTaskData)
execute_task(f::Function, data::AwaitableTaskData)
execute_task(f::Function, data::ConditionalTaskData)
```
The [`schedule`](@ref) function adds a task to the scheduler with the specified [`TaskData`](@ref) and scheduling type.
```julia
schedule(f::Function, scheduler::Union{Scheduler,Agent}, data::TaskData, scheduling_type::SchedulingType=ASYNC)
```
The [`wait_for_all_tasks`](@ref) function waits for all the scheduled tasks in the provided scheduler to complete.
```julia
wait_for_all_tasks(scheduler::Scheduler)
```
The [`stop_task`](@ref) function sends the stop signal to a task `t`. This will result in its completion once the next execution cycle is finished. If `t` is not stopable this will output a warning.
```julia
stop_task(scheduler::Scheduler, t::Task)
```
The [`stop_all_tasks`](@ref) function sends the stop signal to all stopable tasks. This will result in their completion once the next execution cycle is finished.
```julia
stop_all_tasks(scheduler::Scheduler)
```
The [`stop_and_wait_for_all_tasks`](@ref) function sends the stop signal to all stopable tasks. It then waits for all scheduled tasks to finish.
```julia
stop_and_wait_for_all_tasks(scheduler::Scheduler)
```
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 5630 | # Simulation Container
The simulation container has the same role as the real-time container and therefore acts as communication and interaction interface to the environment. The simulation container maintains an interal simulation time and only executes tasks and delivers messages according to the requested step_sizes. It can be stepped in the continous mode or the discrete event mode. Further the container manages a common environment the agents can interact with as base structure for agent-based modeling simulations.
## Create and stepping a simulation container
To create a simulation container, it is advised to use `create_simulation_container`. This method will create a clock with the given simulation time and set default for the communication simulation and the general task simulation. In most cases the default task simulation will be what you desire. The communication simulation object (based on the abstract type `CommunicationSimulation`) is used to determine the delays of the messages in the simulation, while the task simulation determines the way the tasks are scheduled (within a time step, using parallelization etc.) in the simulation.
In the following example a simple simulation is executed.
```@example
using Mango, Dates
# Arbitrary agent definition
@agent struct SimAgent
end
# Create a communication simulator, the simple communication simulator works with static delays between specific agents and a global default, here 0
comm_sim = SimpleCommunicationSimulation(default_delay_s=0)
# Set the simulation time to an initial value
container = create_simulation_container(DateTime(Millisecond(10)), communication_sim=comm_sim)
# Creating agents and registering, no difference here to the real time container
agent1 = register(container, SimAgent())
agent2 = register(container, SimAgent())
# Send a message from agent2 to agent1, the message will be written to a queue instead of processed by some protocol
send_message(agent2, "Hello Friends, this is RSc!", AgentAddress(aid=agent1.aid))
# in this stepping call the message will be delivered and handled to/by the agent1
# step_size=1, if no size is specified the simulation will work as discrete event simulation, executing all tasks occurring on the next event time.
stepping_result = step_simulation(container, 1)
@info stepping_result.time_elapsed
@info container.clock
```
## Discrete event vs continous stepping
Mango.jl support discrete event and continous stepping. Discrete event stepping means that no advance time is provided instead the simulation jumps to the next event time and executes every tasks, delivers every message scheduled at this next event time. For example, you set up a simultion in which three tasks are in the queue at the event times 1,1,3; then the next step would execute the first two, and the following would execute the last task (given no new tasks are created). With continous stepping the user has to provide a step_size (in seconds), which will be used to execute every task until `simulation_time + step_size` ordered by the time of the individual tasks. It is also possible to mix both styles.
```julia
# function call examples for
# continous
stepping_result = step_simulation(container, 1.23)
# and
# discrete event
stepping_result = step_simulation(container)
```
If you do not require to mix both styles and you do not want to create very specific simulations containers, you might prefer to use the express way:
```@example
using Mango, Dates
# Arbitrary agent definition
@agent struct SteppingAgent
end
# number of steps, agents..., start_time=Start time of simulation
results = run_in_simulation(1, SteppingAgent(), PrintingAgent(), start_time=DateTime(2000)) do container
send_message(container, "MyMessageForTheSimulation", address(container[2]))
end
```
## Communication simulation
Mango.jl is generally designed to be extenable, this is also true for the usage of a communication simulator in a Mango.jl-Simulation. To use a custom communication simulator, you can simply set the keyword argument `communication_sim` to a struct of the abstract type `CommunicationSimulation`. To implement this type, you need to add a fitting method to `Mango.calculate_communication::CommunicationSimulation, clock::Clock, messages::Vector{MessagePackage})::CommunicationSimulationResult`. This method will then be called in the simulation loop at least once and repeatedly when new messages arrive and therefore a new state has to be determined.
The default communication simulator is [SimpleCommunicationSimulation](@ref). This simulator uses a default static delay together with a dictionary containing delays per link between individual agents.
## Agent-based modeling
The simulation container can also be used for simple agent-based modeling simulations. In agent-based modeling, units (e.g. people, cars, ...) are modeled using agents and their interaction between these agents and further units in a common world/environment. To support this the simulation container provides `on_step(agent::Agent, world::World, clock::Clock, step_size_s::Real)` (also defined on `Role`).
The `World` can contain common objects to interact with and contains a `Space` struct which can define the type of world modeled (2D/3D/Graph/...). This struct also contains the positions of all agents. Currently there is only the `Space2D` implementation with simple cartesian coordinates.
Please note that Mango.jl focuses on agent-based control, agent-based communication and therefore currently does not provide much supporting implementations for complex agent-based modeling simulations. | Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 2358 | # Topologies
In Mango.jl agents usually communicate with each other based on a topology. The topology determines which agent can communicate with which agent. To implement this, every agent has access to a neighborhood, which is the set of all agents it can communicate with.
As it can be pretty clunky to create every neighborhood-list manually, Mango.jl provides several functions to make your life easier. For this it relys on `Graphs.jl` and `MetaGraphsNext.jl` as datastructure and for graph-construction
# Creating topologies
First, there are several pre-defined topologies. It is also possible to use an arbitrary Graphs.jl graph. After the creation of the topology, the agents need to be added to the topology. This can be done with `per_node(topology) do node ... end`. In the do-block it is possible to add agents to nodes, the do-block will be executed per vertex of your graph.
```@example
using Mango, Graphs
@agent struct MyAgent end
topology = star_topology(3) # star
topology = cycle_topology(3) # cycle
topology = complete_topology(3) # fully connected
topology = graph_topology(complete_digraph(3)) # based on arbitrary Graphs.jl AbstractGraph
per_node(topology) do node
add!(node, MyAgent())
end
# resulting topology graph
topology.graph
```
However, often this approach is not feasible, because you create a specific agent system with agents which need to be linked in a very specific way, such that it is not possible to assign the same agent type to every node. For this reason you can define the topology manually:
```@example
using Mango
@agent struct TopologyAgent end
container = Container()
topology = create_topology() do topology
agent0 = register(container, TopologyAgent())
agent1 = register(container, TopologyAgent())
agent2 = register(container, TopologyAgent())
n1 = add_node!(topology, agent0)
n2 = add_node!(topology, agent1)
n3 = add_node!(topology, agent2)
add_edge!(topology, n1, n2)
add_edge!(topology, n1, n3)
end
# neighbors of `agent`
topology_neighbors(container[1])
```
# Using the topology
At this point we know how to create topologies and how to populate them. To actually use them, the function [`topology_neighbors`](@ref) exists. The function returns a vector of AgentAddress objects, which represent all other agents in the neighborhood of `agent`.
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 0.4.0 | c0d116e0108169c0bcd41928f378ead3d2c55233 | docs | 9347 | ---
title: 'Mango.jl: A Julia-Based Multi-Agent Simulation Framework'
tags:
- Julia
- Agent
- Multi-Agent System
- Simulation Framework
authors:
- name: Jens Sager
orcid: 0000-0001-6352-4213
equal-contrib: true
affiliation: "1, 2" # (Multiple affiliations must be quoted)
- name: Rico Schrage
orcid: 0000-0001-5339-6553
equal-contrib: true
affiliation: "1, 2" # (Multiple affiliations must be quoted)
affiliations:
- name: Digitalized Energy Systems Group, Carl von Ossietzky Universität Oldenburg, 26129 Oldenburg, Germany
index: 1
- name: Energy Division, OFFIS Institute for Information Technology, 26121 Oldenburg, Germany
index: 2
date: 31 July 2024
bibliography: paper.bib
# Optional fields if submitting to a AAS journal too, see this blog post:
# https://blog.joss.theoj.org/2018/12/a-new-collaboration-with-aas-publishing
# aas-doi: 10.3847/xxxxx <- update this with the DOI from AAS once you know it.
# aas-journal: Astrophysical Journal <- The name of the AAS journal.
---
# Summary
Multi-agent simulations are inherently complex, making them difficult to implement, maintain, and optimize.
An agent, as defined by [@russel:2010], is software that perceives its environment through sensors and acts upon it using actuators.
`Mango.jl` is a simulation framework for multi-agent systems implemented in Julia [@julia:2017].
It enables quick implementations of multiple communicating agents, either spanning multiple devices or in a single local environment.
For the design process, `Mango.jl` provides a general structure and a role concept to help develop modular and loosely coupled agents.
This is aided by the built-in task scheduler, with convenience methods to easily schedule timed and repeated tasks that are executed asynchronously.
Agents communicate with each other via message exchange.
Each agent is associated with a container that handles network operations for one or more agents.
Messages may be sent directly via TCP connections or indirectly using an MQTT broker.
This way, `Mango.jl` makes it easy to set up multi-agent simulations on multiple hardware devices.
Mango agents can run in real-time or using simulated time, with either discrete event or stepped time versions.
This is useful for simulations, where simulated time should run much faster than real-time. These non-real-time simulation modes also enable the user to simulate the communication to validate the robustness of multi-agent systems against communication issues.
# Statement of need
Applications of multi-agent systems can be found in various fields, such as in distributed optimization [@yang:2019], reinforcement learning [@gronauer:2022], robotics [@chen:2019] and more.
Many of these systems are highly complex and feature heterogeneous and interacting actors.
This makes them inherently difficult to model and develop.
Therefore, a structured development framework to support this process is a valuable asset.
While `Mango.jl` is a general purpose multi-agent framework, we will focus on energy systems in the following as this is the domain the authors are most familiar with.
Many of the ideas for `Mango.jl` are based on the existing Python framework `mango` [@schrage:2024].
The main reason for this julia-based version is to allow better focus on simulation performance, enabling larger scales of multi-agent simulations.
This is especially relevant in the energy domain, where an increasing amount of energy resources (e.g. batteries and PV-generators) have distributed ownership, competing goals and contribute to the same power grid.
Large scale multi-agent simulations allow researchers to study the behavior of these participants in energy markets and grid simulations.
The Python version of `mango` has already been successfully applied to various research areas in the energy domain, including coalition formation in multi-energy networks [@schrage:2023], distributed market participation of battery storage units [@tiemann:2022], distributed black start [@stark:2021], and investigating the impact of communication topologies on distributed optimization heuristics [@holly:2021].
New Julia-based projects using `Mango.jl` are in active development.
# Related Frameworks
To our knowledge, there is no Julia-based multi-agent framework with a focus on agent communication and distributed operation like `Mango.jl`.
`Agents.jl` [@agents:2022] is a multi-agent framework for modeling agent interactions in a defined space to observe emergent properties like in animal flocking behavior or the spreading of diseases.
This puts it in line with frameworks like mesa [@mesa:2020] or NetLogo [@netlogo:2004].
These have a different scope than `Mango.jl` which is more focused on agent communication and internal agent logic for software applications.
JADE [@JADE:2001] and JIAC [@jiac:2013] are Java frameworks of similar scope but are not actively developed anymore.
JACK [@jack:2005] provides a language and tools to implement communicating agents but is discontinued and proprietary.
The agentframework [@agentframework:2022] is based on JavaScript and has less focus on communication than `Mango.jl`.
Lastly, the original Python version of mango [@schrage:2024] is of course most similar in scope, but makes it more difficult to write high performance simulations, due to the use of `asyncio` and the lack of native multi-threading in Python.
# Performance

The performance of the Python and Julia versions of mango were benchmarked against each other. The results are shown in \autoref{fig:benchmark} and the relevant code is available at [mango_benchmark](https://github.com/OFFIS-DAI/mango_benchmark).
The aim of these scenarios is to measure the performance of the frameworks core features.
This mainly means it measures how efficiently tasks are scheduled and messages are sent and handled.
To achieve this, benchmark scenarios have agents set up in a small world topology communicating a fixed number of messages between each other while performing simulated workloads.
All workloads in the agents is entirely simulated by static delays.
Thus, the benchmarks assumes that workloads in Python and Julia are identical.
The main advantage of `Mango.jl` is in the ease of parallelization.
Python can in some cases reach similar performance using subprocesses for parallel execution to circumvent the limitations of the Python global interpreter lock.
Compared to native threads in Julia, however, this is more prone to issues with the operating system, because it requires large amounts of file handles to operate the subprocesses.
Overall, it is easier to get high performance from `Mango.jl`.
# Basic Example
> **_NOTE:_** All code examples were tested with Mango.jl v0.4.0
> The version also has the tag `joss_paper` on the repository.
In this example, we define two agents in two containers (i.e. at different addresses) that pass messages to each other directly via TCP.
Containers can be set up and equipped with the necessary TCP protocol.
```julia
using Mango
# Create the container instances with TCP protocol
container = create_tcp_container("127.0.0.1", 5555)
container2 = create_tcp_container("127.0.0.1", 5556)
```
Now, we need to define the agents.
An agent in `Mango.jl` is a struct defined with the `@agent` macro.
We define a `TCPPingPongAgent` that has an internal counter for incoming messages.
```julia
@agent struct TCPPingPongAgent
counter::Int
end
```
After creation, agents have to be registered to their respective container.
```julia
# Create instances of ping pong agents
ping_agent = TCPPingPongAgent(0)
pong_agent = TCPPingPongAgent(0)
# register each agent to a container and give them a name
register(container, ping_agent, "Agent_1")
register(container2, pong_agent, "Agent_2")
```
When an incoming message is addressed at an agent, its container will call the `handle_message` function for it.
Using Julia's multiple dispatch, we can define a new `handle_message` method for our agent.
```julia
# Override the default handle_message function for ping pong agents
function Mango.handle_message(agent::TCPPingPongAgent, message::Any, meta::Any)
agent.counter += 1
println(
"$(agent.aid) got a message: $message." *
"This is message number: $(agent.counter) for me!"
)
# doing very important work
sleep(0.5)
if message == "Ping"
reply_to(agent, "Pong", meta)
elseif message == "Pong"
reply_to(agent, "Ping", meta)
end
end
```
With all this in place, we can send a message to the first agent to start the repeated message exchange.
To do this, we need to start the containers so that they listen for incoming messages and send the initiating message.
The best way to start the container message loops and ensure they are correctly shut down in the end is the
`activate(containers)` function.
```julia
activate([container, container2]) do
send_message(ping_agent, "Ping", address(pong_agent))
# wait for 5 messages to have been sent
while ping_agent.counter < 5
sleep(1)
end
end
```
# Acknowledgements
This work has been partly funded by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) – 359941476.
# References
| Mango | https://github.com/OFFIS-DAI/Mango.jl.git |
|
[
"MIT"
] | 1.0.1 | 2dcb38ae6bfd59177731066c0dcdbf7c42776fff | code | 585 | using MatrixFunctionDiff
using Documenter
makedocs(;
modules=[MatrixFunctionDiff],
authors="Xue Quan <[email protected]>",
sitename="MatrixFunctionDiff.jl",
format=Documenter.HTML(;
canonical="https://xuequan818.github.io/MatrixFunctionDiff.jl",
edit_link="master",
assets=String[],
),
pages=[
"Home" => "index.md",
"Background" => "background.md",
"Examples" => "examples.md",
"API" => "api.md"
],
)
deploydocs(;
repo="github.com/xuequan818/MatrixFunctionDiff.jl",
devbranch="master",
)
| MatrixFunctionDiff | https://github.com/xuequan818/MatrixFunctionDiff.jl.git |
|
[
"MIT"
] | 1.0.1 | 2dcb38ae6bfd59177731066c0dcdbf7c42776fff | code | 205 | module MatrixFunctionDiff
using Combinatorics
using DividedDifferences
using LinearAlgebra
using PermutationSymmetricTensors
export mat_fun_frechet
include("frechet.jl")
end # module MatrixFunctionDiff
| MatrixFunctionDiff | https://github.com/xuequan818/MatrixFunctionDiff.jl.git |
|
[
"MIT"
] | 1.0.1 | 2dcb38ae6bfd59177731066c0dcdbf7c42776fff | code | 2979 | """
mat_fun_frechet(f, eigs, Ψ::AbstractMatrix, h::Vector{AbstractMatrix})
mat_fun_frechet(f, H::AbstractMatrix, h::Vector{AbstractMatrix})
Return the n-th order Fréchet derivative `d^nf(H)h[1]…h[n]`, assuming `f` is called as `f(x)`.
"""
@inline function mat_fun_frechet(f::Function, eigs::Vector{Float64},
Ψ::AbstractMatrix,
h::Vector{V};
kwargs...) where {V<:AbstractMatrix}
N = length(eigs)
order = length(h)
DD_F = DD_tensor(f, eigs, order; kwargs...)
h = map(x -> inv(Ψ) * x * Ψ, h)
# F_1 = h_1 ∘ Λ^{0,1}
if order == 1
return Ψ * (h[1] .* DD_F) * inv(Ψ)
end
N0 = N^(order - 2)
DD_F = reshape(DD_F, N, N, N, N0)
T = promote_type(eltype(Ψ), eltype(V))
val = zeros(T, N, N)
h12 = zeros(T, N, N, N)
# loop for the permutations
pert = collect(permutations(1:order))
for p in pert
@views hp = h[p]
# compute {h}^{1,2}_{:,i,:} := (h_1)_{:,i}(h_2)_{i,:}
@. h12 = zero(T)
@views for i = 1:N
h12[:, i, :] = hp[1][:, i] * transpose(hp[2][i, :])
end
# compute {F}^{0,2,…,n}_{:,:,j_3,…,j_n} := ∑_{i=1}^N ({h}^{1,2} ∘ Λ^{0,1,…,n}_{:,:,:,j_3,…,j_n})_{:,i,:}
hF = zeros(T, N, N, N0)
@views for i = 1:N0
hF[:, :, i] = dropdims(sum(h12 .* DD_F[:, :, :, i], dims=2); dims=2)
end
hF = reshape(hF, ntuple(x -> N, order))
hF = permutedims(hF, tuple(2:order..., 1))
# compute the recursion
# {F}^{m,…,n,0}_{:,j_m,…,j_n} = ∑_{i=1}^N (h_m ∘ {F}^{m-1,…,n,0}_{:,:,j_m,…,j_n})_{i,:}
for k = 3:order
Nk = N^(order + 1 - k)
DD_Fk = reshape(hF, N, N, Nk)
hF = zeros(T, N, Nk)
@views for i = 1:Nk
hF[:, i] = dropdims(sum(hp[k] .* DD_Fk[:, :, i], dims=1), dims=1)
end
end
val += hF
end
Ψ * transpose(val) * inv(Ψ)
end
@inline function mat_fun_frechet(f::Function, H::AbstractMatrix,
h::Vector{V};
kwargs...) where {V<:AbstractMatrix}
# compute the full eigen decomposition
# H = Ψ * diagm(eigs) * inv(Ψ)
eigs, Ψ = eigen(H)
# compute the frechet derivative by eigen pairs
mat_fun_frechet(f, eigs, Ψ, h; kwargs...)
end
# Generate the divided difference tensor
# DD_F = f[λ_i0, λ_i2, ..., λ_in]
# By the permutation symmetry of the divided difference,
# we just calculate the irreducible vals
function DD_tensor(f::Function, eigs::Vector{T},
order::Integer; kwargs...) where {T}
N = length(eigs)
dim = order + 1
eigs_take(ind) = map(x -> eigs[x], ind)
DD_F_sym_index = find_full_indices(N, dim)
DD_F_sym_val = @. div_diff(f, eigs_take(DD_F_sym_index); kwargs...)
DD_F = SymmetricTensor(DD_F_sym_val, Val(N), Val(dim))
return Array(DD_F)
end | MatrixFunctionDiff | https://github.com/xuequan818/MatrixFunctionDiff.jl.git |
|
[
"MIT"
] | 1.0.1 | 2dcb38ae6bfd59177731066c0dcdbf7c42776fff | code | 2381 | module FrechetTest
using Test
using MatrixFunctionDiff
using DividedDifferences
using LinearAlgebra
using Combinatorics
# compute the frechet derivative by element loop
function frechet_naive(f::Function, eigs::Vector{Float64},
Ψ::AbstractMatrix,
hs::Vector{V}; kwargs...) where {V<:AbstractMatrix}
N = length(eigs)
order = length(hs)
hs = map(x -> inv(Ψ) * x * Ψ, hs)
pert = collect(permutations(1:order))
T = promote_type(eltype(Ψ), eltype(V))
val = zeros(T, N, N)
for i = 1:N, j = 1:N
ktr = ones(Int, order - 1)
for k = 1:N^(order-1)
kind = vcat(i, ktr, j)
hval = zero(T)
for p in pert
hval += prod(l -> hs[p[l]][kind[l], kind[l+1]], 1:order)
end
ΛF = div_diff(f, eigs[kind]; kwargs...)
val[i, j] += hval * ΛF
if length(ktr) > 0
ktr[1] += 1
for ℓ = 1:order-2
if ktr[ℓ] == N + 1
ktr[ℓ] = 1
ktr[ℓ+1] += 1
end
end
end
end
end
return Ψ * val * inv(Ψ)
end
const N = 10
Funs = [ x -> 1.0 / (1.0 + exp(10*x))]
@testset "Real symmetric matrix" begin
X = rand(N, N);
H = 0.5 * (X + X');
eigs, Ψ = eigen(H);
for order in 1:4
h = [rand(N, N) for i = 1:order]
hs = [0.5 * (x + x') for x in h]
for f in Funs
fd_test = frechet_naive(f, eigs, Ψ, hs);
fd = mat_fun_frechet(f, eigs, Ψ, hs);
@test isapprox(fd_test, fd)
end
end
end
@testset "Complex hermitian matrix" begin
X = rand(ComplexF64, N, N)
H = 0.5 * (X + X')
eigs, Ψ = eigen(H)
for order in 1:4
h = [rand(ComplexF64, N, N) for i = 1:order]
hs = [0.5 * (x + x') for x in h]
for f in Funs
fd_test = frechet_naive(f, eigs, Ψ, hs)
fd = mat_fun_frechet(f, eigs, Ψ, hs)
@test isapprox(fd_test, fd)
end
end
end
@testset "Non-hermitian matrix" begin
H = 0.1.*reshape(collect(-60:39),10,10) + diagm(collect(-4:5))
eigs, Ψ = eigen(H)
for order in 1:4
h = [rand(10, 10) for i = 1:order]
for f in Funs
fd_test = frechet_naive(f, eigs, Ψ, h)
fd = mat_fun_frechet(f, eigs, Ψ, h)
@test isapprox(fd_test, fd)
end
end
end
end | MatrixFunctionDiff | https://github.com/xuequan818/MatrixFunctionDiff.jl.git |
|
[
"MIT"
] | 1.0.1 | 2dcb38ae6bfd59177731066c0dcdbf7c42776fff | code | 396 | using MatrixFunctionDiff
using Test
@testset "MatrixFunctionDiff.jl" begin
t0 = time()
@testset "Fréchet Derivative" begin
println("##### Testing Fréchet derivative functionality...")
t = @elapsed include("FrechetTest.jl")
println("##### done (took $t seconds).")
end
println("##### Running all MatrixFunctionDiff tests took $(time() - t0) seconds.")
end
| MatrixFunctionDiff | https://github.com/xuequan818/MatrixFunctionDiff.jl.git |
|
[
"MIT"
] | 1.0.1 | 2dcb38ae6bfd59177731066c0dcdbf7c42776fff | docs | 2215 | [](https://xuequan818.github.io/MatrixFunctionDiff.jl/stable/)
[](https://xuequan818.github.io/MatrixFunctionDiff.jl/dev/)
[](https://github.com/xuequan818/MatrixFunctionDiff.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/xuequan818/MatrixFunctionDiff.jl)
# MatrixFunctionDiff.jl
A julia package for computing **Fréchet derivatives** of scalar functions with matricies as variables. The higher order Fréchet derivatives are first written in a formula similar to the [Daleskii-Krein theorem](https://www.ams.org/books/trans2/047/), and then computed by the [divided difference](https://github.com/xuequan818/DividedDifferences.jl).
#### Usage
```julia
julia> using MatrixFunctionDiff
julia> using DividedDifferences
julia> f = heaviside; # Heaviside step function
julia> order = 2; # 2nd order Fréchet derivative
julia> H = 0.1 .* reshape(collect(-4:11), 4, 4) + diagm(collect(-2:1))
4×4 Matrix{Float64}:
-2.4 0.0 0.4 0.8
-0.3 -0.9 0.5 0.9
-0.2 0.2 0.6 1.0
-0.1 0.3 0.7 2.1
julia> h = map(x -> Array(reshape(x, 4, 4)) .+ diagm(0.1*ones(4)), [-0.2:0.05:0.55, -1:0.2:2]);
julia> mat_fun_frechet(f, H, h)
4×4 Matrix{Float64}:
0.00483228 -0.00766712 -0.0402159 -0.0588928
0.0098505 -0.0152527 -0.0825338 -0.0813227
0.0412279 -0.0186076 0.00722674 0.00971879
0.0189937 -0.0209538 0.00616146 0.00319365
```
MatrixFunctionDiff can also compute the Fréchet derivatives by the eigenpairs of `H`:
```julia
using LinearAlgebra
julia> eigs, Ψ = eigen(H);
julia> mat_fun_frechet(f, eigs, Ψ, h)
4×4 Matrix{Float64}:
0.00483228 -0.00766712 -0.0402159 -0.0588928
0.0098505 -0.0152527 -0.0825338 -0.0813227
0.0412279 -0.0186076 0.00722674 0.00971879
0.0189937 -0.0209538 0.00616146 0.00319365
```
For more details, please see the [documentation](https://xuequan818.github.io/MatrixFunctionDiff.jl/dev/). | MatrixFunctionDiff | https://github.com/xuequan818/MatrixFunctionDiff.jl.git |
|
[
"MIT"
] | 1.0.1 | 2dcb38ae6bfd59177731066c0dcdbf7c42776fff | docs | 185 | # Matrix Functions Differentiation API
```@meta
CurrentModule = MatrixFunctionDiff
```
## Fréchet derivatives of `f(x::Number)::Number`
```@docs
MatrixFunctionDiff.mat_fun_frechet
``` | MatrixFunctionDiff | https://github.com/xuequan818/MatrixFunctionDiff.jl.git |
|
[
"MIT"
] | 1.0.1 | 2dcb38ae6bfd59177731066c0dcdbf7c42776fff | docs | 5160 | ## Fréchet derivative of Matrix functions
Let $\mathcal{H}:=\mathbb{C}^{N\times N}_{\rm diag}$ be the vector space of $N\times N$ diagonalizable matrices. For $H\in\mathcal{H}$ and $h_1,...h_n\in\mathcal{H}$, and $f$ is an $n$ times continuously differentiable function on a subset of $\mathbb{C}$ containing the spectrum of $H+t_1h_1+\cdots + t_nh_n$, the $n$-th order Fréchet derivative of $f(H)$ is
```math
\begin{align*}
&{{\rm d}}^{n}f(H)h_1\cdots h_n =\\ &\frac{1}{2\pi i}\oint_\mathcal{C} f(z) \sum_{p\in\mathcal{P}_n}(z-H)^{-1}h_{p(1)}(z-H)^{-1}\cdots(z-H)^{-1}h_{p(n)}(z-H)^{-1}\; dz,
\end{align*}
```
where $\mathcal{C}$ is a contour in the complex plane enclosing all the eigenvalues of $H$, and $p\in\mathcal{P}_n$ is an arbitrary permutation of $\{1,\cdots,n\}$. This can be proved by induction.
For $n = 1$, we have
```math
\begin{align*}
{\rm d} f(H)h&=\lim_{t\to 0} \frac{f(H+th)-f(H)}{t}\\&=\frac{1}{2\pi i}\oint_\mathcal{C} f(z)\lim_{t\to 0}\frac{(z-H-th)^{-1}-(z-H)^{-1}}{t}\;dz.
\end{align*}
```
Note that
```math
\begin{align*}
(z-H-th)^{-1} &= (I-t(z-H)^{-1}h)^{-1}(z-H)^{-1} \\&= (I+t(z-H)^{-1}h+O(t^2))(z-H)^{-1},
\end{align*}
```
we have
```math
\begin{align*}
{\rm d} f(H)h=\frac{1}{2\pi i}\oint_\mathcal{C} f(z)(z-H)^{-1}h(z-H)^{-1}\;dz,
\end{align*}
```
which satisfies the formula.
Assume the $n-1$-th order derivative satisfies the formula. Then we have the $n$-th order derivative
```math
\begin{align*}
{{\rm d}}^{n}f(H)h_1\cdots h_n &=\lim_{t\to 0} \frac{{{\rm d}}^{n-1}f(H+th_n)h_1\cdots h_{n-1}-{{\rm d}}^{n-1}f(H)h_1\cdots h_{n-1}}{t}\\
&=\frac{1}{2\pi i}\oint_\mathcal{C} f(z)\lim_{t\to 0}\sum_{p\in\mathcal{P}_{n-1}}\frac{1}{t}\Big((z-H-th_n)^{-1}h_{p(1)}\cdots h_{p(n-1)}(z-H-th_n)^{-1}\\
&\qquad -(z-H)^{-1}h_{p(1)}\cdots h_{p(n-1)}(z-H)^{-1}\Big)\;dz.
\end{align*}
```
Similarly, we have
```math
\begin{align*}
(z&-H-th_n)^{-1}h_{p(1)}\cdots h_{p(n-1)}(z-H-th_n)^{-1}\\
&=(I+t(z-H)^{-1}h_n)(z-H)^{-1}h_{p(1)}\cdots h_{p(n-1)}(z-H)^{-1}(I+th_n(z-H)^{-1}) + O(t^2)\\
&=(z-H)^{-1}h_{p(1)}\cdots h_{p(n-1)}(z-H)^{-1} \\
&\quad+ t\Big((z-H)^{-1}h_n(z-H)^{-1}h_{p(1)}\cdots h_{p(n-1)}(z-H)^{-1}\\
&\qquad\quad+(z-H)^{-1}h_{p(1)}(z-H)^{-1}h_n\cdots h_{p(n-1)}(z-H)^{-1}\\
&\qquad\quad+(z-H)^{-1}h_{p(1)}(z-H)^{-1}h_{p(2)}\cdots h_n(z-H)^{-1}\Big) + O(t^2).
\end{align*}
```
Therefore, we can obtain the formula.
## Divided difference form
Let $H=\Phi \Lambda\Phi^{-1}=\sum_i^N\lambda_i\phi_i\phi_i^{-1}$, where $\phi_i$ is the $i$-th column of $\Phi$ and $\phi_i^{-1}$ is the $i$-th row of $\Phi^{-1}$, and assume there is no degeneration. Then for $p\in\mathcal{P}_n$ we have
```math
\begin{align*}
(z-&H)^{-1}h_{p(1)}(z-H)^{-1}\cdots(z-H)^{-1}h_{p(n)}(z-H)^{-1}\\
&=\sum_{i_0,\cdots,i_{n}=1}^N\phi_{i_0}(h_{p(1)})_{i_0,i_1}\cdots (h_{p(n)})_{i_{n-1},i_n}\phi_{i_{n}}^{-1}(z-\lambda_{i_0})^{-1}\cdots (z-\lambda_{i_{n}})^{-1},
\end{align*}
```
where $(h_{p(k)})_{i,j}=\phi_i^{-1}h_{p(k)}\phi_j$. We let
```math
(z-\lambda_{i_0})^{-1}\cdots (z-\lambda_{i_{n}})^{-1} = \sum_{k=0}^{n}C_k (z-\lambda_{i_k})^{-1},
```
then
```math
\sum_{k=0}^{n}C_k \prod_{\ell\neq k}(z-\lambda_{i_\ell})=1.
```
Let $z=\lambda_{i_k}$, we can obtain
```math
C_k = \frac{1}{\prod_{\ell\neq k}(\lambda_{i_k}-\lambda_{i_\ell})}.
```
Therefore, we have
```math
\begin{align*}
\frac{1}{2\pi i}\oint_\mathcal{C} f(z)(z-\lambda_{i_0})^{-1}\cdots (z-\lambda_{i_{n}})^{-1}\;dz = \sum_{k=0}^{n}\frac{f(\lambda_{i_k})}{\prod_{\ell\neq k}(\lambda_{i_k}-\lambda_{i_\ell})}=f[\lambda_{i_0},\cdots,\lambda_{i_{n}}].
\end{align*}
```
Finally, we obtain
```math
\begin{equation}
{{\rm d}}^{n}f(H)h_1\cdots h_n =\sum_{i_0,\cdots,i_{n}=1}^N\phi_{i_0}\Bigg(\sum_{p\in\mathcal{P}_n}(h_{p(1)})_{i_0,i_1}\cdots (h_{p(n)})_{i_{n-1},i_{n}}\Bigg)f[\lambda_{i_0},\cdots,\lambda_{i_{n}}]\phi_{i_{n}}^{-1},
\end{equation}
```
which can be also written as
```math
\begin{equation}
(\Phi^{-1}[{{\rm d}}^{n}f(H)h_1\cdots h_n]\Phi)_{k\ell}=\sum_{i_1,\cdots,i_{n-1}=1}^N\Bigg(\sum_{p\in\mathcal{P}_n}(h_{p(1)})_{k,i_1}\cdots (h_{p(n)})_{i_{n-1},\ell}\Bigg)f[\lambda_k,\lambda_{i_1},\cdots,\lambda_{i_{n-1}},\lambda_\ell].
\end{equation}
```
## Array operations
Use array operations to efficiently compute the Fréchet derivative. For simplicity, just consider the no permutation case and define
```math
(F_n)_{kℓ}:=∑_{i_1,⋯,i_{n-1}=1}^N(h_1)_{k,i_1}⋯ (h_n)_{i_{n-1},ℓ}Λ^{0,1,…,n-1,n}_{k,i_1,…,i_{n-1},ℓ},
```
where $Λ^{0,…,n}_{i_0,…,i_n} := f[λ_{i_0},⋯,λ_{i_n}]$. It is immediately to obtain that
```math
F_1 = h_1 ∘ Λ^{0,1},
```
and
```math
F_2 = ∑_{i=1}^N (\mathfrak{h}^{1,2} ∘ Λ^{0,1,2})_{:,i,:},
```
with $\mathfrak{h}^{1,2}_{:,i,:} := (h_1)_{:,i}(h_2)_{i,:}$. For $n ≥ 3$, first compute
```math
\mathfrak{F}^{0,2,…,n}_{:,:,j_3,…,j_n} := ∑_{i=1}^N (\mathfrak{h}^{1,2} ∘ Λ^{0,1,…,n}_{:,:,:,j_3,…,j_n})_{:,i,:}
```
and permute such that the $0$-dimension is at the end $\mathfrak{F}^{2,…,n,0}$. Then for $m ≥ 3$, there is the recursion
```math
\mathfrak{F}^{m,…,n,0}_{:,j_m,…,j_n} = ∑_{i=1}^N (h_m ∘ \mathfrak{F}^{m-1,…,n,0}_{:,:,j_m,…,j_n})_{i,:}
```
and $F_n = (\mathfrak{F}^{n,0})^T$.
| MatrixFunctionDiff | https://github.com/xuequan818/MatrixFunctionDiff.jl.git |
|
[
"MIT"
] | 1.0.1 | 2dcb38ae6bfd59177731066c0dcdbf7c42776fff | docs | 875 | # Examples
The [`mat_fun_frechet`](@ref) function computes the higher order Fréchet derivatives ${{\rm d}}^{n}f(H)h[1]\cdots h[n]$. It requires that the matrix `H` can be diagonalizable, the function `f` be a scalar function, and `h` be a vector consisting of diagonalizable matrices. The order of the derivative is equal to the length of `h`.
```julia
julia> using MatrixFunctionDiff
julia> f(x) = 1.0 / (1.0 + exp(100 * (x - 0.1))); # Fermi Dirac function
julia> order = 3; # 3rd order Fréchet derivative
julia> N = 10; # dimension of matrix
julia> X = rand(N, N);
julia> H = 0.5 * (X + X');
julia> h = [rand(N, N) for i = 1:order];
julia> map!(x->0.5 * (x + x'), h, h);
```
MatrixFunctionDiff can also compute the Fréchet derivatives by the eigenpairs of `H`:
```julia
using LinearAlgebra
julia> eigs, Ψ = eigen(H);
julia> mat_fun_frechet(f, eigs, Ψ, h);
```
| MatrixFunctionDiff | https://github.com/xuequan818/MatrixFunctionDiff.jl.git |
|
[
"MIT"
] | 1.0.1 | 2dcb38ae6bfd59177731066c0dcdbf7c42776fff | docs | 660 | # MatrixFunctionDiff.jl
A julia package for computing **Fréchet derivatives** of scalar functions with matricies as variables. The higher order Fréchet derivatives are first written in a formula similar to the [Daleskii-Krein theorem](https://www.ams.org/books/trans2/047/), and then computed by the [divided difference](https://github.com/xuequan818/DividedDifferences.jl).
---
## Installation
MatrixFunctionDiff.jl is a registered package, so it can be installed by running
```julia
julia> Pkg.add("MatrixFunctionDiff")
```
## Related packages
- [DividedDifferences.jl](https://github.com/xuequan818/DividedDifferences.jl): Divided difference for Julia
| MatrixFunctionDiff | https://github.com/xuequan818/MatrixFunctionDiff.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 1850 | using HighVoronoi
using Documenter
DocMeta.setdocmeta!(HighVoronoi, :DocTestSetup, :(using HighVoronoi); recursive=true)
makedocs(;
modules=[HighVoronoi],
authors="Martin Heida",
repo="https://github.com/martinheida/HighVoronoi.jl/blob/{commit}{path}#{line}",
sitename="HighVoronoi.jl",
#versions = ["dev",
# "stable",],
#version = "stable",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://martinheida.github.io/HighVoronoi.jl",
edit_link="main",
assets=String[],
),
pages=[
"Home" => "index.md",
"Manual Voronoi" => Any[
"Examples Voronoi Generation" => "man/short.md",
"man/workflowmesh.md",
"man/geometry.md",
"man/raycast.md",
"man/multithread.md",
"man/database.md",
"man/improving.md",
"man/boundaries.md",
"Advanced Options" => "man/advanced.md",
"man/periodic.md",
"man/refine.md",
"Projection operators" => "man/projection.md",
"man/metapost.md",
"Sources of errors and loss in performance" => "man/errors.md",
],
"Manual Finite Volume" => Any[
"Finite Volume Examples" => "man/finitevolumeexample.md",
"man/workflowfv.md",
"Finite Volume Tutorial" => "man/finitevolume.md",
"Functions" => "man/functions.md",
"man/integrals.md",
"man/toyfvfile.md",
],
"Intentions of use (EXAMPLES)" => "showcase.md",
],
)
deploydocs(;
repo="github.com/martinheida/HighVoronoi.jl",
devbranch="main",
devurl = "v1.3.0",#"v1.0.2",
# versions = ["stable" => "v^", "v#.#.#",],
)
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 17464 |
###########################################################################################################
## Compound Meshes...
###########################################################################################################
# Modified CompoundMesh struct
struct CompoundMesh{P <: Point, VDB <: VertexDB{P}, T <: AbstractMesh{P}, V <: Union{StaticTrue,StaticFalse,Bool}} <: AbstractMesh{P,VDB}
mesh::T
visible::V
data::CompoundData
# Modified constructor for CompoundMesh
function CompoundMesh(mesh::AbstractMesh{P}, visible=true, s=1, _s=1) where {P}
lm = length(mesh)
_lm = internal_length(mesh)
new{P,ptype(mesh),typeof(mesh), typeof(visible)}(mesh, visible, CompoundData(s, _s, lm, _lm))
end
end
@inline Base.length(m::CompoundMesh) = length(m.mesh)
@inline nodes(m::CompoundMesh) = nodes(m.mesh)
@inline internal_index(m::CM,index::Int64) where CM<:CompoundMesh = internal_index(m.mesh,index)
@inline external_index(m::CM,index::Int64) where CM<:CompoundMesh = external_index(m.mesh,index)
@inline external_index(m::CM,inds::AVI) where {CM<:CompoundMesh,AVI<:AbstractVector{Int64}} = external_index(m.mesh,inds)
@inline internal_index(m::CM,inds::AVI) where {CM<:CompoundMesh,AVI<:AbstractVector{Int64}} = internal_index(m.mesh,inds)
@inline internal_sig(mesh::CM,sig::AVI,static::StaticTrue) where {CM<:CompoundMesh,AVI<:AbstractVector{Int64}} = internal_sig(mesh.mesh,sig,static)
@inline internal_sig(mesh::CM,sig::AVI,static::StaticFalse) where {CM<:CompoundMesh,AVI<:AbstractVector{Int64}} = internal_sig(mesh.mesh,sig,static)
@inline vertices_iterator(m::CM, index::Int64, internal::StaticFalse) where CM<:CompoundMesh = vertices_iterator(m.mesh, index, internal)
@inline vertices_iterator(m::CM, index::Int64, internal::StaticTrue) where CM<:CompoundMesh = vertices_iterator(m.mesh, index, internal)
@inline all_vertices_iterator(m::CM, index::Int64, internal::StaticTrue) where CM<:CompoundMesh = all_vertices_iterator(m.mesh, index, internal)
@inline number_of_vertices(m::CM,i::Int64,static) where CM<:CompoundMesh = number_of_vertices(m.mesh,i,static)
@inline push!(mesh::CM, p::Pair{Vector{Int64},T},index) where {T<:Point,CM<:CompoundMesh{T}} = push!(mesh.mesh, p, index)
@inline push_ref!(mesh::CM, ref,index) where {T<:Point,CM<:CompoundMesh{T}} = push_ref!(mesh.mesh, ref, index)
@inline haskey(mesh::CM,sig::AbstractVector{Int64},index::Int) where CM<:CompoundMesh = haskey(mesh.mesh, sig, index)
@inline copy(cm::CM;kwargs...) where CM<:CompoundMesh = CompoundMesh(copy(cm.mesh),cm.visible,cm.data.start,cm.data._start)
###########################################################################################################
## Serial Meshes...
###########################################################################################################
# Define the SerialMesh struct CompoundData
struct SerialMesh{P <: Point, VDB <: VertexDB{P}, T , D , PARAMS,RT} <: AbstractMesh{P,VDB}
meshes::T
dimensions::D
buffer_sig::Vector{Int64}
data::MVector{1,Int64}
parameters::PARAMS
rt::RT
end
@inline copy_sig(mesh::LM,sig) where {LM<:SerialMesh} = _copy_indeces(mesh,sig,mesh.buffer_sig)
const SerialMeshVector{P <: Point, VDB <: VertexDB{P},MType,PARAMS,RT} = SerialMesh{P, VDB , Vector{MType} , Vector{CompoundData} , PARAMS,RT} where {MType <: AbstractMesh{P,VDB}}
function copy(m::SM;kwargs...) where {P,SM<:SerialMesh{P}}
crt(::Nothing) = nothing
crt(i) = copy(i)
m2 = map(x->copy(x;kwargs...),m.meshes)
for k in 1:length(m2)
if typeof(m2[k])!=typeof(m.meshes[k])
println(typeof(m2[k].mesh))
println(typeof(m.meshes[k].mesh))
error("")
end
end
dims = map(x->x.data,m2)
return SerialMesh{P,ptype(m),typeof(m2),typeof(dims),typeof(m.parameters),typeof(m.rt)}(m2, dims, Int64[],copy(m.data),m.parameters,crt(m.rt))
end
const SerialMeshTuple{P <: Point, VDB <: VertexDB{P},PARAMS,RT} = SerialMesh{P, VDB , T , D , PARAMS,RT} where {T <: Tuple{Vararg{AbstractMesh{P,VDB}}}, D <: Tuple{Vararg{CompoundData}}}
#=
#FlexibleMeshContainer(m::M) where M<:SerialMeshTuple = MeshContainer
#FlexibleMeshContainer(m::M) where M<:SerialMeshVector = ExplicitMeshContainer
function SerialMeshTuple(m::SerialMeshTuple{P,VDB}, n::AbstractMesh{P,VDB}, isvisible=true) where {P,VDB}
_l = sum(getfield(mesh, :data)._length for mesh in m.meshes)
l = sum(getfield(mesh, :data).length for mesh in m.meshes)
visible = StaticBool(isvisible)
newcompound = CompoundMesh(n, visible, l + 1, _l + 1)
set_offset(n,_l)
m2 = (m.meshes..., newcompound)
dims = (m.dimensions...,newcompound.data)
SerialMesh{P,ptype(m),typeof(m2),typeof(dims),typeof(m.parameters),typeof(m.rt)}(m2, dims, Int64[],MVector{1,Int64}([length(m)+length(newcompound)]),m.parameters,m.rt)
end
function SerialMeshTuple(m::AM, isvisible=true;parameters = nothing,references = Int64[]) where {P,VDB, AM<:AbstractMesh{P,VDB} }
visible = StaticBool(isvisible)
cm = CompoundMesh(m, StaticBool(visible), 1, 1)
meshes = (cm,)
data = (cm.data,)
SerialMesh{P,ptype(m),typeof(meshes),typeof(data),typeof(parameters),typeof(references)}(
(cm,),
(cm.data,),
Int64[],MVector{1,Int64}([length(cm)]),
parameters, references
)
end
function SerialMeshTuple(xs::HVN, visible=true;parameters = nothing,references = Int64[]) where {P, HVN<:HVNodes{P}}
m = Voronoi_MESH(xs,references,parameters)
cm = CompoundMesh(m, visible, 1, 1)
meshes = (cm,)
data = (cm.data,)
SerialMesh{P,ptype(m),typeof(meshes),typeof(data),typeof(parameters),typeof(references)}(
meshes,
data,
Int64[],MVector{1,Int64}([length(cm)]),
parameters, references
)
end
function SerialMeshTuple(m::SerialMeshTuple{P,VDB},xs::P2,isvisible=true) where {P,P2<:HVNodes,VDB}
refmode(n::Nothing) = nothing
refmode(n) = copy(n)
return SerialMeshTuple(m,Voronoi_MESH(xs,refmode(m.rt),m.parameters),isvisible)
end
@inline append(m::SerialMeshTuple,d,visible=true) = SerialMeshTuple(m,d,visible)
SearchTree(nodes::SerialNodes{P,SM},type=HVKDTree) where {P,SM<:SerialMeshTuple} = error("please implement") #HVTree(nodes,type)
=#
function SerialMeshVector(xs::HV,visible::Bool=true; parameters = nothing, references = Int64[]) where {P, HV<:HVNodes{P}}
m = Voronoi_MESH(xs,references,parameters)
SerialMeshVector(m,visible)
#= m = Voronoi_MESH(xs,references,vertex_storage=parameters)
cm = CompoundMesh(m, visible, 1, 1)
meshes = [cm]
data = [cm.data]
SerialMesh{P,ptype(m),typeof(meshes),typeof(data),typeof(parameters),typeof(references)}(
meshes,
data,
Int64[],MVector{1,Int64}([length(cm)]),
parameters, references
)=#
end
function SerialMeshVector(m::AM,visible::Bool=true) where {P, AM<:AbstractMesh{P}}
cm = CompoundMesh(m, visible, 1, 1)
meshes = [cm]
data = [cm.data]
SerialMesh{P,ptype(m),typeof(meshes),typeof(data),typeof(m.parameters),typeof(m.references)}(
meshes,
data,
Int64[],MVector{1,Int64}([length(cm)]),
m.parameters, m.references
)
end
function append!(m::SM,n::MType,visible=true) where {SM<:SerialMeshVector,MType<:AbstractMesh}#P <: Point, VDB <: VertexDB{P},MType<:AbstractMesh{P,VDB},PARAMS,RT, SM<:SerialMeshVector{P,VDB,MType,PARAMS,RT}}
_l = sum(mesh.data._length for mesh in m.meshes)
l = sum(mesh.data.length for mesh in m.meshes)
newcompound = CompoundMesh(n, visible, l + 1, _l + 1)
set_offset(n,_l)
push!(m.meshes, newcompound)
push!(m.dimensions,newcompound.data)
m.data[1] += length(n)
return m
end
@inline append(m::SerialMeshVector,d,visible=true) = append!(m,d,visible)
function append!(m::SerialMeshVector,xs::HVNodes,visible = true)# where {P <: Point, HVN<:HVNodes{P},VDB <: VertexDB{P},MType<:AbstractMesh{P,VDB},PARAMS,RT, SM<:SerialMeshVector{P,VDB,MType,PARAMS,RT}}
refmode(n::Nothing) = nothing
refmode(n) = copy(n)
append!(m,Voronoi_MESH(xs,refmode(m.rt),m.parameters),visible)
end
@inline Base.getproperty(cd::SerialMesh, prop::Symbol) = dyncast_get(cd,Val(prop))
@inline @generated dyncast_get(cd::SerialMesh, ::Val{:length}) = :(getfield(cd,:data)[1])
@inline @generated dyncast_get(cd::SerialMesh, d::Val{S}) where S = :( getfield(cd, S))
@inline @generated dyncast_get(cd::SerialMesh, d::Val{:boundary_Vertices}) where S = :( getfield(cd, :meshes)[1].mesh.boundary_Vertices)
@inline Base.setproperty!(cd::SerialMesh, prop::Symbol, val) = dyncast_set(cd,Val(prop),val)
@inline @generated dyncast_set(cd::SerialMesh, ::Val{:length},val) = :(getfield(cd,:data)[1]=val)
@inline @generated dyncast_set(cd::SerialMesh, d::Val{S},val) where S = :( setfield(cd, S,val))
@inline length(m::SM) where SM<:SerialMesh = sum(cd->cd.length,m.dimensions)#m.length
@inline internal_length(m::SM) where SM<:SerialMesh = sum(cd->cd._length,m.dimensions)
"""takes an internal index and returns the meshindex it belongs to"""
@inline @Base.propagate_inbounds function meshindex_from_internal(m::AM,index) where AM<:SerialMesh
found = 1
i=2
ld = length(m.dimensions)
while i<=ld
m.dimensions[i].start >index && break
found = i
i += 1
end
return found
end
"""takes an official index and returns the meshindex it belongs to"""
@inline function meshindex_from_external(m,index)
found = 1
for i in 2:(length(m.dimensions))
m.dimensions[i]._start >index && break
found = i
end
return found
end
function internal_index(m::SM,index::Int64) where SM<:SerialMesh
if index<=m.length
found = meshindex_from_external(m,index)
_index = index + 1 - m.dimensions[found].start
return internal_index(m.meshes[found],_index) + m.dimensions[found]._start - 1
else
return maxInt - (index - m.length)
end
end
@Base.propagate_inbounds function external_index(m::SM,index::Int64) where SM<:SerialMesh
if index<=m.length
found = meshindex_from_internal(m,index)
_index = index + 1 - m.dimensions[found]._start
return external_index(m.meshes[found],_index) + m.dimensions[found].start - 1
else
return (maxInt - index) + m.length
end
end
@inline external_index(m::SM,inds::AVI) where {SM<:SerialMesh,AVI<:AbstractVector{Int64}} = _external_indeces(m,inds,m.buffer_sig)
@inline internal_index(m::SM,inds::AVI) where {SM<:SerialMesh,AVI<:AbstractVector{Int64}} = _internal_indeces(m,inds,m.buffer_sig)
@inline internal_sig(mesh::SM,sig::AVI,static::StaticTrue) where {SM<:SerialMesh,AVI<:AbstractVector{Int64}} = sort!(_internal_indeces(mesh,sig,mesh.buffer_sig))
@inline function internal_sig(mesh::SM,sig::AVI,static::StaticFalse) where {SM<:SerialMesh,AVI<:AbstractVector{Int64}}
sig .= _internal_indeces(mesh,sig,mesh.buffer_sig)
return sort!(sig)
end
@inline external_sig(mesh::SM,sig::AVI,static::StaticTrue) where {SM<:SerialMesh,AVI<:AbstractVector{Int64}} = sort!(_external_indeces(mesh,sig,mesh.buffer_sig))
@inline function external_sig(mesh::SM,sig::AVI,static::StaticFalse) where {SM<:SerialMesh,AVI<:AbstractVector{Int64}}
sig .= _external_indeces(mesh,sig,mesh.buffer_sig)
return sig
end
#=function vertices_iterator(m::SM, index::Int64, internal::StaticFalse) where SM<:SerialMesh
found = meshindex_from_external(m,index)
_index = index + 1 - m.dimensions[found].start
return vertices_iterator(m.meshes[found],_index,internal)
end=#
@inline function get_vertex(m::SerialMesh, ref::VertexRef)
found = meshindex_from_internal(m,ref.cell)
_cell = ref.cell + 1 - m.dimensions[found]._start
get_vertex(m.meshes[found].mesh,VertexRef(_cell,ref.index))
end
@inline function mark_delete_vertex!(m::SM,sig,i,ii) where {SM<:SerialMesh}
found = meshindex_from_internal(m,i)
mark_delete_vertex!(m.meshes[found].mesh,sig,i-m.meshes[found].data._start+1,ii)
end
@inline function delete_reference(m::SM,s,ref) where SM<:SerialMesh
found = meshindex_from_internal(m,s)
delete_reference(m.meshes[found].mesh,s-m.meshes[found].data._start+1,ref)
end
@inline function cleanupfilter!(m::S,i) where S<:SerialMesh
found = meshindex_from_internal(m,i)
cleanupfilter!(m.meshes[found].mesh,i-m.meshes[found].data._start+1)
end
function vertices_iterator(m::SM, index::Int64, internal::StaticTrue) where SM<:SerialMesh
found = meshindex_from_internal(m,index)
_index = index + 1 - m.dimensions[found]._start
#println(_index," from ",index)
return vertices_iterator(m.meshes[found],_index,internal)
end
function all_vertices_iterator(m::SM, index::Int64, internal::StaticTrue) where SM<:SerialMesh
found = meshindex_from_internal(m,index)
_index = index + 1 - m.dimensions[found]._start
return all_vertices_iterator(m.meshes[found],_index,internal)
end
@inline function number_of_vertices(m::SM, index::Int64, internal::StaticTrue) where SM<:SerialMesh
found = meshindex_from_internal(m,index)
_index = index + 1 - m.dimensions[found]._start
return number_of_vertices(m.meshes[found],_index,internal)
end
#=function number_of_vertices(m::SM, index::Int64, internal::StaticFalse) where SM<:SerialMesh
found = meshindex_from_external(m,index)
_index = index + 1 - m.dimensions[found].start
return number_of_vertices(m.meshes[found],_index,internal)
end=#
function testint(mesh::SM,index) where {T<:Point,SM<:SerialMesh{T}}
found = meshindex_from_internal(mesh,index)
_index = index + 1 - mesh.dimensions[found]._start
return found,_index
end
function push!(mesh::SM, p::Pair{Vector{Int64},T},index) where {T<:Point,SM<:SerialMesh{T}}
found = meshindex_from_internal(mesh,index)
_index = index + 1 - mesh.dimensions[found]._start
push!(mesh.meshes[found],p,_index)
end
@inline function push_ref!(mesh::SM, ref,index) where {T<:Point,SM<:SerialMesh{T}}
found = meshindex_from_internal(mesh,index)
_index = index + 1 - mesh.dimensions[found]._start
#print("$index, $ref, ## $_index")
push_ref!(mesh.meshes[found],ref,_index)
#println(" ---> $(get_vertex(mesh,ref))")
end
function haskey(mesh::SM,sig::AbstractVector{Int64},index::Int) where SM<:SerialMesh
found = meshindex_from_internal(mesh,index)
_index = index + 1 - mesh.dimensions[found]._start
haskey(mesh.meshes[found],sig,_index)
end
function reset(mesh::SerialMesh)
s = 1
for i in 1:length(mesh.mesh)
m = mesh.mesh[i]
m.data.start = s
m.data.length = length(m.mesh)
s += m.data.length
end
mesh.length = sum(cd->cd.length,mesh.dimensions)
end
struct SerialMesh_Store_1{P, VDB, T , D , PARAMS,RT}
meshes::T
#dimensions::D
#buffer_sig::Vector{Int64}
data::MVector{1,Int64}
parameters::PARAMS
rt::RT
end
JLD2.writeas(::Type{SerialMesh{P, VDB, T , D , PARAMS,RT}}) where {P, VDB, T , D , PARAMS,RT} = SerialMesh_Store_1{P, VDB, T , D , PARAMS,RT}
JLD2.wconvert(::Type{SerialMesh_Store_1{P, VDB, T , D , PARAMS,RT}},m::SerialMesh{P, VDB, T , D , PARAMS,RT} ) where {P, VDB, T , D , PARAMS,RT} =
SerialMesh_Store_1{P, VDB, T , D , PARAMS,RT}(m.meshes,m.data,m.parameters,m.rt)
function JLD2.rconvert(::Type{SerialMesh{P, VDB, T , D , PARAMS,RT}},m::SerialMesh_Store_1{P, VDB, T , D , PARAMS,RT}) where {P, VDB, T , D , PARAMS,RT}
dims = map(x->x.data,m.meshes)
SerialMesh{P, VDB, T , D , PARAMS,RT}(m.meshes,dims,Int64[],m.data,m.parameters,m.rt)
end
###########################################################################################################
## Serial Nodes...
###########################################################################################################
struct SerialNodes{P<:Point,SM<:SerialMesh{P}} <: HVNodes{P}
mesh::SM
len::Int64
end
SerialNodes(m::SerialMesh) = SerialNodes{PointType(m),typeof(m)}(m,m.dimensions[end].start + m.dimensions[end].length - 1)
nodes(m::SerialMesh) = SerialNodes(m)
@inline Base.size(n::SerialNodes) = (n.len,)
function Base.getindex(nodes::SerialNodes, index)
m = nodes.mesh
found = meshindex_from_external(m,index)
_index = index + 1 - m.dimensions[found].start
getindex(HighVoronoi.nodes(m.meshes[found].mesh),_index)
end
function Base.setindex!(nodes::SerialNodes, val, index)
m = nodes.mesh
found = meshindex_from_external(m,index)
_index = index + 1 - m.dimensions[found].start
setindex!(HighVoronoi.nodes(m.meshes[found].mesh),val,_index)
end
@inline Base.length(nodes::SerialNodes) = nodes.len
#function Base.length(nodes::SerialNodes)
# d = nodes.mesh.bufferdata[end]
# return d.start+d.length-1
#end
function Base.iterate(sn::SerialNodes, state=1)
if state>length(sn)
return nothing
else
return (getindex(sn,state),state+1)
end
end
SearchTree(nodes::SerialNodes{P,SM},type=HVKDTree) where {P,SM<:SerialMeshVector} = HVTree(nodes,type)
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 7854 | module HighVoronoi
#using IterTools
using SpecialFunctions
using LinearAlgebra
using NearestNeighbors
using Printf
using IterativeSolvers
using SparseArrays
using StaticArrays
using Crayons
using JLD2
using Polyhedra
using GLPK
using Plots
using Distances
using ProgressMeter
#using Cthulhu
using Base.Threads
using Base.Threads: Atomic, atomic_cas!
#using Traceur
const maxInt = typemax(Int64)
const Point{T} = AbstractVector{T} where T<:Real
const Points{T} = AbstractVector{<:Point{T}} where T<:Real
const Sigma = AbstractVector{<:Integer} # Encoded the vertex by the ids of its generators.
const Vertex = Tuple{<:Sigma, <: Point}
const Vertices = Dict{<:Sigma, <:Point}
const ListOfVertices = AbstractVector{<:Vertices}
const SigmaView = typeof(view([1, 2, 3, 4], 2:3))
const UseNeighborFinderDimension = 3
const Edge = Vector{Int64} #SVector{S,Int64} where S
MakeVertex(sig::Sigma) = sig
"""
struct MultiThread
node_threads::Int64
sub_threads::Int64
MultiThread() = new(Threads.nthreads(), 1)
MultiThread(node_threads, sub_threads) = new(node_threads, sub_threads)
The `MultiThread` struct is used to initiate a multi-threaded computation where the grid is divided into a maximum of `node_threads` sub-grids. Each sub-grid is processed using up to `sub_threads` threads, depending on the maximum number of threads provided by Julia.
# Constructors
## `MultiThread()`
The default constructor initializes `node_threads` using the system's available number of threads and sets `sub_threads` to 1.
## `MultiThread(node_threads, sub_threads)`
This constructor allows for manual specification of `node_threads` and `sub_threads`.
"""
struct MultiThread
node_threads::Int64
sub_threads::Int64
MultiThread() = new(Threads.nthreads(),1)
#MultiThread(node_threads,sub_threads) = new(min(node_threads,Threads.nthreads()),sub_threads)
MultiThread(node_threads,sub_threads) = new(node_threads,sub_threads)
end
"""
struct SingleThread end
The `SingleThread` struct forces the computation to be performed on a single thread. The algorithm is internally optimized for single-thread execution, which is different from using `MultiThread(1, 1)`.
"""
struct SingleThread end
"""
AutoThread() -> Union{MultiThread, SingleThread}
This function automatically selects the appropriate threading strategy based on the number of threads available in Julia. If Julia provides more than one thread, the function returns a `MultiThread` instance with the number of threads set to the maximum available (`Threads.nthreads()`) and `sub_threads` set to 1. If only one thread is available, it returns a `SingleThread` instance.
This allows the computation to adapt dynamically to the threading capabilities of the system.
"""
AutoThread() = Threads.nthreads()>1 ? MultiThread(Threads.nthreads(),1) : SingleThread()
# the following methods will be overwritten vor meshes, integrals and integrators
import Base.prepend!
import Base.append!
import Base.copy
import Base.length
import Base.push!
import Base.pop!
import Base.haskey
import Base.keepat!
import Base.filter!
import Base.show
import Base.rehash!
import Base.merge
import Base.lock
import Base.unlock
import Base.delete!
struct Call_HEURISTIC_MC end
const VI_HEURISTIC_MC=Call_HEURISTIC_MC()
struct Call_HEURISTIC_INTERNAL end
const VI_HEURISTIC_INTERNAL=Call_HEURISTIC_INTERNAL()
struct Call_HEURISTIC end
const VI_HEURISTIC=Call_HEURISTIC()
struct Call_GEO end
const VI_GEOMETRY=Call_GEO()
struct Call_POLYGON end
const VI_POLYGON=Call_POLYGON()
struct Call_FAST_POLYGON end
const VI_FAST_POLYGON=Call_FAST_POLYGON()
struct Call_MC end
const VI_MONTECARLO=Call_MC()
struct Call_NO end
const VI_NOTHING=Call_NO()
#import show
#StaticBool, FunWithTuples, StaticArray-stuff
include("hvlocks.jl")
include("tools.jl")
include("sparsewrapper.jl")
include("threaddict.jl")
include("queuehashing.jl")
include("parallellocks.jl")
include("queues.jl")
include("hvdatabase.jl")
include("NearestNeighborModified/NearestNeighbors.jl")
include("edgehashing.jl")
include("indexhash.jl")
#include("staticparams.jl")
#include("database.jl")
include("quicksort.jl")
include("searchtrees.jl")
#HVView and descendant SwitchView
include("hvview.jl")
# boundary type
include("boundary.jl")
include("nodes.jl") # HVNodes, AbstractCombinedNodes, NodesContainer, UnsortedNodes,
# ExtendedNodes, SortedNodes, NodesView
include("extended.jl")
include("abstractmesh.jl") # AbstractMesh, MeshContainer
include("filter.jl")
include("vdbexplicitheap.jl")
include("vdbvertexref.jl")
include("vdbdatabaseref.jl")
include("abstractintegral.jl")
include("voronoinodes.jl")
include("voronoi_mesh.jl")
include("meshview.jl")
include("parallelmesh.jl")
include("edgeiteratebase.jl")
# only meaningful for debugging
include("exceptions.jl")
# edge iterators for periodic grids / non-general verteces
include("edgeiterate.jl")
# composing functions
include("composer.jl")
# neighbor iterator
include("neighbors.jl")
# iterator to set up distriubutions according to given density
include("densityrange.jl")
# node types
# The Voronoi mesh
include("FVmesh.jl")
# Storing integral data
include("vertexchecker.jl")
include("integral.jl")
include("serialintegral.jl")
include("parallelintegral.jl")
# handling mesh on the level of the user
include("voronoidomain.jl")
include("serialdomain.jl")
include("geometry.jl") # VoronoiGeometry
include("voronoidata.jl")
include("discretefunctions.jl")
include("substitute.jl") # refinement by substitution
# Functions for diplay of progress
include("progress.jl")
# 2D MetaPost output
include("draw.jl")
# integrate functions and volume
include("integrate.jl")
include("polyintegrator.jl")
include("fastpolyintegrator.jl")
#include("polyintegrator_general.jl")
include("heuristic.jl")
include("mcintegrator.jl")
include("heuristic_mc.jl")
include("integrator.jl")
include("cleanup_cell.jl")
# calculate voronoi mesh on the very lowes levels
include("raycast-types.jl")
include("raycast.jl")
include("sysvoronoi.jl")
#include("find_delaunay.jl")
include("improving.jl")
include("meshrefine.jl")
include("periodicmesh.jl")
include("cubicmesh.jl")
# calculations on domain level
include("domain.jl")
include("domainrefine.jl") # refinement of domains
# needed for exact and fast volume calculation in the polyintegrator algorithms
include("Leibnitzrule.jl")
# L1 projection onto subgrids
include("l1projection_new.jl")
include("R-projection.jl")
include("finitevolume.jl")
include("statistics.jl")
#include("chull.jl")
# What will be exported:
export DensityRange
export VoronoiNodes
export VoronoiNode
export VoronoiGeometry
export PeriodicVoronoiBasis
export integrate!
export Voronoi_MESH
export Voronoi_Integral
export VoronoiData
export CompactVoronoiData
export VoronoiFV
export refine!
export refine
export indeces_in_subset
export substitute!
export interactionmatrix
export memory_allocations
export Boundary
export cuboid
export center_cube
export BC_Dirichlet
export BC_Neumann
export BC_Periodic
export MetaPostBoard
export PlotBoard
export draw2D
export draw3D
export write_jld
export load_Voronoi_info
export FunctionComposer
export VoronoiFVProblem
export linearVoronoiFVProblem
export FVevaluate_boundary
export VoronoiKDTree
export StepFunction
export DiameterFunction
export InterfaceFunction
export PeriodicFunction
export FunctionFromData
export R_projection
export get_Bulkintegral
export get_Fluxintegral
export show
export VI_GEOMETRY
export VI_HEURISTIC
export VI_HEURISTIC_MC
export VI_MONTECARLO
export VI_POLYGON
export VI_FAST_POLYGON
export RaycastParameter
export RCOriginal
export RCCombined
export RCNonGeneral
export MultiThread
export SingleThread
export AutoThread
export DatabaseVertexStorage
export ClassicVertexStorage
export ReferencedVertexStorage
end # module
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 3648 | ########################################################################################################
# calculate a determinant iteratively according to the Leibnitz Minor method.
########################################################################################################
struct Minors
HASH::Matrix{Int64}
data::Vector{Vector{Float64}}
Index::Vector{Int64}
dimension::Int64
_buffer::Vector{Vector{Int64}}
function Minors(dim)
H=hash_matrix(dim)
d=Vector{Vector{Float64}}(undef,dim)
b=Vector{Vector{Int64}}(undef,dim)
for col in 1:dim
d[col]=zeros(Float64,hash_column(H,col,dim))
b[col]=zeros(Int64,col)
end
Ind=zeros(Int64,dim)
new(H,d,Ind,dim,b)
end
end
function hash_matrix(dim)
HASH=zeros(Int64,dim,dim)
for j in 1:dim HASH[1,j]=1 end
for i in 2:dim
for j in 1:(dim-(i-1))
for l in (j+1):(dim-(i-1)+1)
HASH[i,j]+=HASH[i-1,l]
end
end
end
return HASH
end
function vor_minor_determinant(minors,vectors)
for i in 1:(minors.dimension)
k_minor(minors,i,vectors[i])
#println(all_determinants[i])
end
return (minors.data[end])[1]
end
function hash_column(hash,col,dim)
_sum=0
for i in 1:dim _sum+=hash[col,i] end
return _sum
end
function k_minor(minors::Minors,k,V)
#offset=0
dim=minors.dimension
#println(k)
if k==1
data=minors.data[1]
for i in 1:dim data[i]=V[i] end
else
#for i in 1:k offset+=hash_column(minors.HASH,i,dim) end
_minor=minors._buffer[k] # This represents a minor of k rows (sorted) and the last k columns
for j in 1:k _minor[j]=j end # minor has the numbers (1,2,3,....,k)
index=1
#println(_minor)
while true
result=0.0
#println(_minor)
DATAk_m_one=(minors.data[k-1])
sign=(-1)
for j in 1:k
sign*=(-1) # same as factor (-1)^(j+1)
result+=V[_minor[j]]*(DATAk_m_one[get_minor(minors,_minor,j,k-1)])*sign
#println("V($(_minor[j]))*M($_minor,$j)=$(V[_minor[j]])*$(((minors.data[k-1])[get_minor(minors,_minor,j,k-1)]))")
end
#(minors.data[k])[get_minor(minors,_minor,0,k)]=result
(minors.data[k])[index]=result # same result, but faster....
index+=1
if !next_minor(_minor,dim) break end
end
end
end
function next_minor(minor,dim)
k=length(minor)
column=k
while true
if column<=0 return false end
minor[column]+=1
if minor[column]<=dim-k+column
for _cc in (column+1):k
minor[_cc]=minor[_cc-1]+1
end
return true
else
column-=1
end
end
end
function get_minor(minors::Minors,indeces,skip,top_col)
# minors: list of minors, indeces: array storing current indeces,
# _cancel: position in ideces which is not considered, _length: length of sublock, i.e. length(indeces)-1
index=1
storage=0
col=top_col
old_row=0
while col>0
if index==skip index+=1 end
for i in (old_row+1):indeces[index]-1
storage+=minors.HASH[col,i]
end
old_row=indeces[index]
storage+= col==1 ? 1 : 0
col-=1
index+=1
end
#println("ind: $indeces, skip: $skip, storage: $storage")
return storage
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 1101 |
R_proj_tree(tree::Nothing,VG) = VoronoiKDTree(VG)
R_proj_tree(tree,VG) = tree
R_proj_diam(diameters::Nothing,VG,tree) = DiameterFunction(VG,tree=tree)
R_proj_diam(diameters,VG,tree) = diameters
function R_projection(u::Function,VG::VoronoiGeometry; rays=100, tree=nothing, diameters=nothing, factor=1.0,only_vector=false)
tree = R_proj_tree(tree,VG)
diams = R_proj_diam(diameters,VG,tree)
factor = abs(min(1.0,factor))
points = Vector{Vector{Float64}}(undef,rays)
nodes = VG.Integrator.Integral.MESH.nodes
dim = length(nodes[1])
lmesh = length(nodes)
count = 0
while count<rays
r = randn(dim)
if norm(r)<1
count+=1
points[count] = factor*r
end
end
values = zeros(Float64,lmesh)
for i in 1:lmesh
x0 = nodes[i]
r = diams(x0)[1]
for k in 1:rays
values[i] += u(x0+r*points[k])
end
end
values ./= rays
if only_vector
return values
else
return StepFunction(VG,values,tree=tree)
end
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 11869 | abstract type HVIntegral{P<:Point} end
PointType(d::HVIntegral{P}) where P = P
@inline function enable(inte::III; neighbors=false,volume=false,integral=false,kwargs...) where III<:HVIntegral
volume |= integral
neighbors |= volume
neighbors && enable_neighbor_data(inte)
volume && enable_geo_data(inte)
integral && enable_integral_data(inte)
end
@inline dimension(i::HVI) where {P,HVI<:HVIntegral{P}} = size(P)[1]
@inline function set_neighbors(Inte::HV,i,neigh,proto_bulk,proto_interface) where HV<:HVIntegral
mInte = mesh(Inte)
set_neighbors(Inte,internal_index(mInte,i),sort!(_internal_indeces(mInte,neigh)),proto_bulk,proto_interface,staticfalse)
end
@inline function get_neighbors(Inte::HV,i) where HV<:HVIntegral
mInte = mesh(Inte)
external_index(mInte,copy(get_neighbors(Inte,internal_index(mInte,i),staticfalse)))
end
@inline hascelldata(I::HVI,_Cell) where HVI<:HVIntegral = _has_cell_data(I,internal_index(mesh(I),_Cell))
@inline function cell_data_writable(I::HVI,_Cell,vec,vecvec;printshit=false,get_integrals=statictrue) where HVI<:HVIntegral
cdw = cell_data_writable(I,internal_index(mesh(I),_Cell),vec,vecvec,staticfalse,get_integrals=get_integrals)
new_neigh = copy(cdw.neighbors)
indices = collect(1:length(cdw.neighbors))
printshit && println(new_neigh)
_external_indeces(mesh(I),new_neigh)
printshit && println(new_neigh)
quicksort!(new_neigh,indices,indices)
printshit && println(indices)
#println(typeof(cdw.area))
#println(typeof(cdw.interface_integral))
return (volumes = cdw.volumes, area = ShuffleViewVector(indices,cdw.area), bulk_integral = get_integrals==true ? cdw.bulk_integral : nothing, interface_integral=get_integrals==true ? ShuffleViewVector(indices,cdw.interface_integral) : nothing, neighbors = new_neigh,indices=indices)
end
@inline get_area(I::HV,c,n) where HV<:HVIntegral = get_area(I,c,n,staticfalse)
@inline function get_area(I::HV,c,n,::StaticFalse) where HV<:HVIntegral
m = mesh(I)
get_area(I,internal_index(m,c),internal_index(m,n),statictrue)
end
@inline get_integral(I::HV,c,n) where HV<:HVIntegral = get_integral(I,c,n,staticfalse)
@inline function get_integral(I::HV,c,n,::StaticFalse) where HV<:HVIntegral
m = mesh(I)
get_integral(I,internal_index(m,c),internal_index(m,n),statictrue)
end
@inline neighbors(i::AI,k) where AI<:HVIntegral = isassigned(i.neighbors,k) ? i.neighbors[k] : Int64[]
@inline volumes(i::AI,k) where AI<:HVIntegral = isassigned(i.volumes,k) ? i.volumes[k] : 0
@inline area(i::AI,k) where AI<:HVIntegral = isassigned(i.area,k) ? i.area[k] : Float64[]
@inline bulk_integral(i::AI,k) where AI<:HVIntegral = isassigned(i.bulk_integral,k) ? i.bulk_integral[k] : Float64[]
@inline interface_integral(i::AI,k) where AI<:HVIntegral = isassigned(i.interface_integral,k) ? i.interface_integral[k] : Vector{Vector{Float64}}()
#=
function compare(i::I1,ii::I2) where {I1<:HVIntegral,I2<:HVIntegral}
_sum(A,B) = length(B)>0 ? sum(A,B) : 0.0
result = true
if enabled_volumes(i) && enabled_volumes(ii) && length(i.volumes)==length(ii.volumes)
differ = sum(k->norm(volumes(i,k)-volumes(ii,k)),1:length(i.volumes))
result &= differ<0.1
println("Total volumes error: $differ")
elseif enabled_volumes(i) || enabled_volumes(ii)
result = false
println("i enabled volumes: $(enabled_volumes(i)), ii enabled volumes: $(enabled_volumes(ii)) ; Lengths: $(length(i.volumes)) vs. $(length(ii.volumes))")
end
if enabled_bulk(i) && enabled_bulk(ii) && length(i.bulk_integral)==length(ii.bulk_integral)
try
differ = sum(k->norm(bulk_integral(i,k)-bulk_integral(ii,k)),1:length(i.bulk_integral))
result &= differ<0.1
println("Total bulk_integral error: $differ")
catch e
if isa(e, DimensionMismatch)
println("dimensions of integrals do not match")
result = false
else
rethrow(e) # Rethrow the exception if it's not a DimensionMismatch error
end
end
elseif enabled_bulk(i) || enabled_bulk(ii)
result = false
println("i enabled bulk_integral: $(enabled_bulk(i)), ii enabled bulk_integral: $(enabled_bulk(ii)) ; Lengths: $(length(i.bulk_integral)) vs. $(length(ii.bulk_integral))")
end
neighs = true
if enabled_neighbors(i) && enabled_neighbors(ii) && length(i.neighbors)==length(ii.neighbors)
differ = sum(k->norm(neighbors(i,k)-neighbors(ii,k)),1:length(i.neighbors))
result &= differ<0.1
neighs &= differ<0.1
println("Total neighbors error: $differ")
elseif enabled_neighbors(i) || enabled_neighbors(ii)
neighs = false
result = false
println("i enabled neighbors: $(enabled_neighbors(i)), ii enabled neighbors: $(enabled_neighbors(ii)) ; Lengths: $(length(i.neighbors)) vs. $(length(ii.neighbors))")
end
if !neighs
println("Error in neighbors, cannot compare area and interface_integral")
return false
end
if enabled_area(i) && enabled_area(ii) && length(i.area)==length(ii.area)
differ = sum(k->norm(area(i,k)-area(ii,k)),1:length(i.area))
result &= differ<0.1
println("Total area error: $differ")
elseif enabled_area(i) || enabled_area(ii)
result = false
println("i enabled area: $(enabled_area(i)), ii enabled area: $(enabled_area(ii)) ; Lengths: $(length(i.area)) vs. $(length(ii.area))")
end
if enabled_interface(i) && enabled_interface(ii) && length(i.interface_integral)==length(ii.interface_integral)
try
differ = _sum(k->_sum(kk->norm(interface_integral(i,k)[kk]-interface_integral(ii,k)[kk]),1:length(interface_integral(ii,k))),1:length(i.interface_integral))
result &= differ<0.1
println("Total interface_integral error: $differ")
catch e
if isa(e, DimensionMismatch)
println("dimensions of integrals do not match")
result = false
else
rethrow(e) # Rethrow the exception if it's not a DimensionMismatch error
end
end
elseif enabled_interface(i) || enabled_interface(ii)
result = false
println("i enabled interface_integral: $(enabled_interface(i)), ii enabled interface_integral: $(enabled_interface(ii)) ; Lengths: $(length(i.interface_integral)) vs. $(length(ii.interface_integral))")
end
return result
end
=#
function resize_integrals(i::AI,_size) where AI<:HVIntegral
error("you may need to reactivate the following code")
#=if enabled_bulk(i)
for k in 1:length(i)
inte = bulk_integral(i,k)
length(inte)>0 && resize!(inte,_size)
end
end
if enabled_interface(i)
for k in 1:length(i)
inte = interface_integral(i,k)
for kk in 1:length(inte)
length(inte[kk])>0 && resize!(inte[kk],_size)
end
end
end=#
end
############################################################################################################
## NoIntegral
############################################################################################################
#=struct NoIntegral{P<:Point} <: HVIntegral{P}
end
NoIntegral(mesh::AbstractMesh{P}) where P = NoIntegral{P}()
add_virtual_points(Integral::NoIntegral, xs) = Integral
=#
############################################################################################################
## IntegralContainer
############################################################################################################
mutable struct IntegralContainer{P<:Point} <: HVIntegral{P}
integral::HVIntegral{P}
end
mutable struct ExplicitIntegralContainer{P<:Point,HI<:HVIntegral{P}} <: HVIntegral{P}
integral::HI
end
#FlexibleIntegralContainer(m::M) where M<:SerialIntegralTuple = IntegralContainer
#FlexibleIntegralContainer(m::M) where M<:SerialIntegralVector = ExplicitIntegralContainer
############################################################################################################
## IntegralView
############################################################################################################
struct IntegralView{P<:Point, HVI<:HVIntegral{P}, V<:HVView, AM<:AbstractMesh{P},SN,SV,SA,SII,SBI} <: HVIntegral{P}
neighbors::SN
volumes::SV
area::SA
interface_integral::SII
bulk_integral::SBI
data::HVI
view::V
int_data::MVector{3, Int64}
mesh::AM
end
function IntegralView(d::HVI, v::V) where {P<:Point, HVI<:HVIntegral{P}, V<:HVView}
mv = MeshView(mesh(d),v)
#new{P, HVI, V, typeof(mv)}
IntegralView(
MeshViewVector(d.neighbors,mv), # neighbors
MeshViewVector(d.volumes,mv), # volumes
MeshViewVector(d.area,mv),# area
MeshViewVector(d.interface_integral,mv), # interface
MeshViewVector(d.bulk_integral,mv), # bulk
d, # data
v, # view
MVector{3, Int64}(zeros(Int64, 3)),# int_data initialized with zeros
mv #mesh_view
)
end
#function IntegralView(d::HVIntegral, v::HV) where HV<:HVView
# IntegralView{PointType(d), typeof(d), typeof(v)}(d, v)
#end
mesh(iv::IntegralView) = iv.mesh #MeshView(mesh(iv.data), iv.view)
@inline Base.getproperty(cd::IntegralView, prop::Symbol) = dyncast_get(cd,Val(prop))
@inline @generated dyncast_get(cd::IntegralView, ::Val{:number_of_neighbors}) = :(getfield(cd,:int_data)[1])
@inline @generated dyncast_get(cd::IntegralView, ::Val{:length_neighbors}) = :(getfield(cd,:int_data)[2])
@inline @generated dyncast_get(cd::IntegralView, ::Val{:_Cell}) = :(getfield(cd,:int_data)[3])
@inline @generated dyncast_get(cd::IntegralView, d::Val{S}) where S = :( getfield(cd, S))
@inline Base.setproperty!(cd::IntegralView, prop::Symbol, val) = dyncast_set(cd,Val(prop),val)
@inline @generated dyncast_set(cd::IntegralView, ::Val{:number_of_neighbors},val) = :(getfield(cd,:int_data)[1]=val)
@inline @generated dyncast_set(cd::IntegralView, ::Val{:length_neighbors},val) = :(getfield(cd,:int_data)[2]=val)
@inline @generated dyncast_set(cd::IntegralView, ::Val{:_Cell},val) = :(getfield(cd,:int_data)[3]=val)
@inline @generated dyncast_set(cd::IntegralView, d::Val{S},val) where S = :( setfield(cd, S,val))
@inline _has_cell_data(I::IntegralView,_Cell) = _has_cell_data(I.data,_Cell)
@inline cell_data_writable(I::IntegralView,_Cell,vec,vecvec,::StaticFalse;get_integrals=statictrue) = cell_data_writable(I.data,_Cell,vec,vecvec,staticfalse,get_integrals=get_integrals)
@inline get_neighbors(I::IntegralView,_Cell,::StaticFalse) = get_neighbors(I.data,_Cell,staticfalse)
@inline set_neighbors(I::IntegralView,_Cell,new_neighbors,proto_bulk,proto_interface,::StaticFalse) = set_neighbors(I.data,_Cell,new_neighbors,proto_bulk,proto_interface,staticfalse)
@inline enable(iv::IV;kwargs...) where IV<:IntegralView = enable(iv.data;kwargs...)
@inline enabled_volumes(Integral::IntegralView) = enabled_volumes(Integral.data)
@inline enabled_area(Integral::IntegralView) = enabled_area(Integral.data)
@inline enabled_bulk(Integral::IntegralView) = enabled_bulk(Integral.data)
@inline enabled_interface(Integral::IntegralView) = enabled_interface(Integral.data)
@inline get_area(iv::IntegralView,c,n,::StaticTrue) = get_area(iv.data,c,n,statictrue)
@inline get_integral(iv::IntegralView,c,n,::StaticTrue) = get_integral(iv.data,c,n,statictrue)
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 26594 | struct VertexRef
cell::Int64
index::Int64
end
abstract type VertexDB{P <: Point} end
abstract type VertexDBExplicit{P <: Point} <: VertexDB{P} end
abstract type VertexDBReference{P <: Point} <: VertexDB{P} end
abstract type VertexDBCentral{P <: Point} <: VertexDB{P} end
@inline ptype(vdb::VertexDBExplicit{P}) where P = VertexDBExplicit{P}
@inline ptype(vdb::VertexDBReference{P}) where P = VertexDBReference{P}
@inline ptype(vdb::VertexDBCentral{P}) where P = VertexDBCentral{P}
# Abstract class AbstractMesh
abstract type AbstractMesh{P <: Point,VDB<:VertexDB{P}} end
@inline PointType(d::AbstractMesh{P}) where P = P
@inline dimension(m::AbstractMesh{P}) where P = size(P)[1]
@inline ptype(m::AbstractMesh{P, VDB}) where {P <: Point, VDB <: VertexDBExplicit{P}} = VertexDBExplicit{P}
@inline ptype(m::AbstractMesh{P, VDB}) where {P <: Point, VDB <: VertexDBReference{P}} = VertexDBReference{P}
@inline ptype(m::AbstractMesh{P, VDB}) where {P <: Point, VDB <: VertexDBCentral{P}} = VertexDBCentral{P}
@inline number_of_vertices(m::AM,i::Int64) where {AM<:AbstractMesh} = number_of_vertices(m,i,staticfalse)
@inline function number_of_vertices(m::AM,i::Int64,::StaticFalse) where {AM<:AbstractMesh}
number_of_vertices(m,internal_index(m,i),statictrue)
end
struct _IterationIndex
index::Int64
end
IterationIndex(i::II) where {II<:Int} = _IterationIndex(i)
IterationIndex(i) = nothing
IterationIndex() = nothing
#@inline internal_length(m::M) where M<:AbstractMesh = length(m)
Queue(m::AbstractMesh{P,VDB},is::Int64) where {P,VDB<:VertexDBExplicit} = VertexQueue(m,Vector{Pair{Vector{Int64},P}}(undef,0),is)
Queue(m::AbstractMesh{P,VDB},is::Int64) where {P,VDB<:VertexDBReference} = VertexQueue(m,Vector{VertexRef}(undef,0),is)
@inline get_vertex(::AbstractMesh{P},ref::Pair{AV,P}) where {P,AV<:AbstractVector{Int64}} = ref
function _copy_indeces(m::AM,inds::AVI,buffer::AVII) where {AM<:AbstractMesh,AVI<:AbstractVector{Int64},AVII<:AbstractVector{Int64}}
li = length(inds)
if (li>length(buffer))
resize!(buffer,li)
end
ret = view(buffer,1:li)
ret .= inds
return ret
end
function _external_indeces(m::AM,inds::AVI,buffer::AVII) where {AM<:AbstractMesh,AVI<:AbstractVector{Int64},AVII<:AbstractVector{Int64}}
li = length(inds)
if (li>length(buffer))
resize!(buffer,li)
end
ret = view(buffer,1:li)
for i in 1:li
ret[i] = external_index(m,inds[i])
end
return ret
end
@inline function _external_indeces_fit(m::AM,inds::AVI,buffer::AVII) where {AM<:AbstractMesh,AVI<:AbstractVector{Int64},AVII<:AbstractVector{Int64}}
li = length(inds)
#ret = buffer
for i in 1:li
buffer[i] = external_index(m,inds[i])
end
sort!(buffer)
end
@inline function _external_indeces(m::AM,inds::AVI) where {AM<:AbstractMesh,AVI<:AbstractVector{Int64}}
_external_indeces(m,inds,inds)
return inds
end
@inline function _internal_indeces(m::AM,inds::AVI) where {AM<:AbstractMesh,AVI<:AbstractVector{Int64}}
_internal_indeces(m,inds,inds)
return inds
end
function _internal_indeces(m::AM,inds::AVI,buffer::AVII) where {AM<:AbstractMesh,AVI<:AbstractVector{Int64},AVII<:AbstractVector{Int64}}
li = length(inds)
if (li>length(buffer))
resize!(buffer,li)
end
ret = view(buffer,1:li)
for i in 1:li
ret[i] = internal_index(m,inds[i])
end
return ret
end
@inline function _transform_indeces(from::AM1,to::AM2,inds::AVI,buffer::AVII) where {AM1<:AbstractMesh,AM2<:AbstractMesh,AVI<:AbstractVector{Int64},AVII<:AbstractVector{Int64}}
inds2 = _internal_indeces(from,inds,buffer)
return _external_indeces(to,inds2)
end
@inline _transform_indeces(from::AM1,to::AM2,inds::AVI) where {AM1<:AbstractMesh,AM2<:AbstractMesh,AVI<:AbstractVector{Int64}} = _transform_indeces(from,to,inds,inds)
copy_sig(m,sig) = copy(m,sig)
"""
push!(mesh::M, p::Pair{Vector{Int64},T}) where {T<:Point, M<:AbstractMesh{T}}
Add a vertex to the mesh `mesh` using the provided pair `p`, where `p` is of the form `sig => r`. The `sig` part will be transformed into internal numeration, and the resulting vertex will be stored in the mesh.
# Arguments
- `mesh::M`: The mesh to which the vertex will be added.
- `p::Pair{Vector{Int64},T}`: A pair containing a signature (`sig`) and a point (`r`) where `sig` will be transformed to internal numeration and `r` will be stored as a vertex.
# Warning
After storing the vertex, the original `sig` will be modified. If you do not want to modify the original `sig`, provide a copy using `copy!(sig)` before calling this function.
"""
@inline function push!(mesh::M, p::Pair{Vector{Int64},T}) where {T<:Point, M<:AbstractMesh{T}}
sig = internal_sig(mesh,copy(p[1])) #copy_sig(mesh,p[1]))
#=if typeof(mesh)<:MeshView
print("$(p[1]) -> $sig / $(external_sig(mesh,copy(sig),statictrue)) ; ")
end=#
ref = push!(mesh,sig=>p[2],sig[1])
i = 2
lsig = length(sig)
while i <= lsig
push_ref!(mesh,ref,sig[i])
i += 1
end
return ref
end
"""
haskey(m::AM, v::AbstractVector{Int64}) where AM<:AbstractMesh
Check whether the external representation `v` exists within the mesh `m`.
# Arguments
- `m::AM`: The mesh to search within.
- `v::AbstractVector{Int64}`: An external representation of a vertex that is being searched for within the mesh.
# Returns
- `true` if the external representation `v` exists in the mesh `m`, otherwise `false`.
This function checks if the provided external representation `v` corresponds to a vertex already present in the mesh `m` and returns `true` if found. It is a convenient way to check for the existence of vertices within the mesh based on their external representation.
"""
@inline function haskey(m::AM, v::AVI) where {AM<:AbstractMesh, AVI<:AbstractVector{Int64}}
iv = internal_sig(m,v,statictrue)
return haskey(m,iv,iv[1])
end
@inline function haskey_multithread(m::AM, v::AVI) where {AM<:AbstractMesh, AVI<:AbstractVector{Int64}}
c = copy(v)
_internal_indeces(m,v,c)
sort!(c)
return haskey(m,c,c[1])
end
"""
internal_sig(mesh::M, sig::AVI) where {M<:AbstractMesh, AVI<:AbstractVector{Int64}}
Compute the internal signature `sig` for a mesh `mesh`. Standard is a call to
`internal_sig(mesh, sig, staticfalse)`
# Arguments
- `mesh::M`: The mesh for which the internal signature is being computed.
- `sig::AVI`: An abstract vector representing the external signature.
- `static=staticfalse`: A parameter of type `StaticTrue` or `StaticFalse` to specify whether to write the modified internal signature to an internal buffer (StaticTrue) or directly into `sig` (StaticFalse). Default is `staticfalse`.
# Returns
- If `static` is StaticTrue, it returns the modified internal signature as an abstract vector.
- If `static` is StaticFalse, it modifies `sig` in place and returns nothing.
This function computes the internal signature for the given mesh `mesh` based on the external signature `sig`. The `static` parameter determines whether the modified internal signature is stored in an internal buffer (StaticTrue) or written directly within `sig` (StaticFalse). By default, it uses `staticfalse` as the default behavior.
"""
@inline internal_sig(mesh::M,sig::AVI) where {M<:AbstractMesh, AVI<:AbstractVector{Int64}} = internal_sig(mesh,sig,staticfalse)
@inline vertices_iterator(m::M, i::Int64) where {M<:AbstractMesh} = vertices_iterator(m,i,staticfalse)
@inline all_vertices_iterator(m::M,i::Int64) where {M<:AbstractMesh} = all_vertices_iterator(m,i,staticfalse)
"yields vertices iterator over all vertices of this cell in external view"
@inline vertices_iterator(m::M, i::Int64,::StaticFalse) where {M<:AbstractMesh} = begin
inind = internal_index(m,i)
VertexIterator(m,vertices_iterator(m,inind,statictrue),inind)
end
"yields iterator over vertices associated primarily with this node in external view. Call with 'statictrue' for internal view!"
@inline all_vertices_iterator(m::M, i::Int64,::StaticFalse) where {M<:AbstractMesh} = begin
inind = internal_index(m,i)
VertexIterator(m,all_vertices_iterator(m,inind,statictrue),inind)
end
@inline mark_delete_vertex!(m::AM,sig,index::U) where {AM<:AbstractMesh,U<:Union{Nothing,_IterationIndex}} = mark_delete_vertex!(m,sig,sig[1],index)
@inline function pushray!(mesh::AM,full_edge,r,u,_Cell) where AM<:AbstractMesh
push!(mesh.boundary_Vertices,_internal_indeces(mesh,full_edge)=>boundary_vertex(r,u,internal_index(mesh,_Cell)))
end
struct Public_BV_Iterator{M<:AbstractMesh}
mesh::M
buffer::Vector{Int64}
Public_BV_Iterator(m) = new{typeof(m)}(m,Int64[])
end
function Base.iterate(pbi::PBI,state=1) where {PBI<:Public_BV_Iterator}
modify(n::Nothing) = nothing
function modify(data)
(edge,info) = data[1]
edge2 = _external_indeces(pbi.mesh,edge,pbi.buffer)
return (ReadOnlyView(edge2),boundary_vertex(info.base,info.direction,external_index(pbi.mesh,info.node))), data[2]
end
return modify(iterate(pbi.mesh.boundary_Vertices, state...))
end
convert_to_vector(pbi::PBI) where {PBI<:Public_BV_Iterator} = begin
ret = Vector{Pair{Vector{Int64},boundary_vertex{PointType(pbi.mesh)}}}(undef,length(pbi.mesh.boundary_Vertices))
count = 1
for (sig,bv) in pbi.mesh.boundary_Vertices
ret[count] = copy(sig)=>bv
count += 1
end
return ret
end
function verify_mesh(mesh,boundary)
searcher = Raycast(copy(nodes(mesh)),domain=boundary)
c1 = 0
c2 = 0
for i in 1:length(mesh)
searcher.tree.active .= false
activate_cell( searcher, i, collect((searcher.lmesh+1):(searcher.lmesh+searcher.lboundary) ))
for (sig,r) in vertices_iterator(mesh,i)
if length(sig)==0 || sig[1]==0
error("")
end
if !verify_vertex(sig,r,searcher.tree.extended_xs,searcher,true)
xs = searcher.tree.extended_xs
idx = sort!(_inrange(searcher.tree,r,norm(r-xs[sig[1]])*(1+1E-8)))
neigh = Int64[]
count = 0
for (sig,r) in vertices_iterator(mesh,idx[1])
append!(neigh,sig)
count += 1
end
#unique!(sort!(neigh))
error("$i, $sig, $idx, $r, $(nn(searcher.tree.tree,r)), $count, $neigh")
c1 += 1
else
c2 += 1
end
if c1>20
return false
end
end
end
return true
end
function compare(mesh1::AM1,mesh2::AM2,full=false) where {AM1<:AbstractMesh,AM2<:AbstractMesh}
println("comparing meshes: "*(full ? "full list of vertices per cell" : "local list of vertices per cell only"))
if length(mesh1)!=length(mesh2)
println("$(length(mesh1))≠$(length(mesh2)): The meshes have different length")
return false
end
tree = SearchTree(copy(nodes(mesh2)))
mynodes = nodes(mesh2)
numberOfNodes = length(mesh2)
c=0
for i in 1:length(mesh1)
for (sig,r) in (full ? vertices_iterator(mesh1,i) : all_vertices_iterator(mesh1,i))#.All_Vertices[i]
b = false
for (sig2,r2) in (full ? vertices_iterator(mesh2,i) : all_vertices_iterator(mesh2,i))#.All_Vertices[i]
sig==sig2 && (b=true)
if b && norm(r-r2)>1E-6
println("distance violation: $sig, $(norm(r-r2))")
end
b==true && break
end
if !b
c+=1
measure = 0.0
pos = 0
for s in sig
s>numberOfNodes && break
measure = max(norm(mynodes[s]-r),measure)
pos += 1
end
idx = sort!(inrange(tree,r,(1+1.0E-8)*measure))
println("$i: $sig not in mesh2 but $idx and $(haskey(mesh2,sig)), $r")#, in mesh1: $(haskey(mesh1,sig)), $(haskey(mesh1.All_Vertices[sig[1]],sig)), $(mesh1.All_Vertices[sig[1]])")
end
end
for (sig,r) in (full ? vertices_iterator(mesh2,i) : all_vertices_iterator(mesh2,i))#.All_Vertices[i]
b = false
for (sig2,_) in (full ? vertices_iterator(mesh1,i) : all_vertices_iterator(mesh1,i))#.All_Vertices[i]
sig==sig2 && (b=true)
b==true && break
end
if !b
c+=1
println("$i: $sig not in mesh1, mesh2=$(haskey(mesh2,sig)) but mesh1=$(haskey(mesh1,sig)) ")#, in mesh1: $(haskey(mesh1,sig)), $(haskey(mesh1.All_Vertices[sig[1]],sig)), $(mesh1.All_Vertices[sig[1]])")
end
end
c>50 && break
end
return c==0
end
#=function compare(mesh1::AbstractMesh,mesh2::AbstractMesh,m3)
length(mesh1)!=length(mesh2) && return false
tree = SearchTree(nodes(mesh2))
tree3 = SearchTree(nodes(m3))
mynodes = nodes(mesh2)
numberOfNodes = length(mesh2)
delta = length(mesh1)-length(m3)
c=0
lm1 = 0
lm2 = 0
lm3 = 0
for i in 1:length(m3)
lm3 += length(m3.All_Vertices[i])
end
for i in 1:length(mesh1)
lm1 += length(mesh1.All_Vertices[i])
for (sig,r) in mesh1.All_Vertices[i]
b = false
for (sig2,_) in mesh2.All_Vertices[i]
sig==sig2 && (b=true)
b==true && break
end
if !b
c+=1
measure = 0.0
pos = 0
for s in sig
s>numberOfNodes && break
measure = max(norm(mynodes[s]-r),measure)
pos += 1
end
idx = sort!(inrange(tree,r,(1+1.0E-8)*measure))
idx3 = sort!(inrange(tree3,r,(1+1.0E-8)*measure))
sig_c = copy(sig)
sig_c .-= delta
println(sig," ",r)
#println("$sig not in mesh2 but $idx, $sig_c: $(haskey(m3,sig_c)), but $idx3 ")#, in mesh1: $(haskey(mesh1,sig)), $(haskey(mesh1.All_Vertices[sig[1]],sig)), $(mesh1.All_Vertices[sig[1]])")
end
end
lm2 += length(mesh2.All_Vertices[i])
for (sig,r) in mesh2.All_Vertices[i]
b = false
for (sig2,_) in mesh1.All_Vertices[i]
sig==sig2 && (b=true)
b==true && break
end
if !b
c+=1
#println("$i: $sig not in mesh1, mesh2=$(haskey(mesh2,sig)) but mesh1=$(haskey(mesh1,sig)) ")#, in mesh1: $(haskey(mesh1,sig)), $(haskey(mesh1.All_Vertices[sig[1]],sig)), $(mesh1.All_Vertices[sig[1]])")
end
end
# c>20 && break
end
c>0 && println("Discrepancy $c of $lm1 vs $lm2 vs $lm3")
return c==0
end
=#
# Mutable struct MeshContainer
mutable struct MeshContainer{P <: Point, VDB <: VertexDB{P}} <: AbstractMesh{P,VDB}
data::AbstractMesh{P,VDB}
end
@inline mesh(m::MeshContainer) = m.data
mutable struct ExplicitMeshContainer{P <: Point, VDB <: VertexDB{P},AM<:AbstractMesh{P,VDB}} <: AbstractMesh{P,VDB}
data::AM
end
@inline mesh(m::ExplicitMeshContainer) = m.data
###########################################################################################################
## VertexIterator
###########################################################################################################
struct BufferVertexData_Dict{VRA<:AbstractVector{VertexRef},SI}
in_cell::SI
in_mesh::VRA
end
struct BufferVertexData_Vec{VRA<:AbstractVector{VertexRef},SI<:AbstractVector{Int64}}
in_cell::SI
in_mesh::VRA
end
const BufferVertexData_Dict_Vector{VRA,SI} = BufferVertexData_Dict{VRA,SI} where {VRA<:AbstractVector{VertexRef},SI<:AbstractVector{Pair}}
BufferVertexData(c::SI,m::VRA) where {VRA<:AbstractVector{VertexRef},SI} = BufferVertexData_Dict(c,m)
BufferVertexData(c::SI,m::VRA) where {VRA<:AbstractVector{VertexRef},SI<:AbstractVector{Int64}} = BufferVertexData_Vec(c,m)
struct VertexRefIterator{AM<:AbstractMesh,AVR<:AbstractVector{VertexRef},L}
m::AM
refs::AVR
l::Int64
lock::L
function VertexRefIterator(m::AM1,r::AVR1) where {AM1,AVR1}
lock = ReadWriteLock(m)
new{AM1,AVR1,typeof(lock)}(m,r,length(r),lock)
end
end
@inline Base.length(vi::VI) where {VI<:VertexRefIterator} = vi.l
@inline Base.iterate(vi::VI, state=1) where {VI<:VertexRefIterator} = _iterate(vi,state,nothing)
@inline function _iterate(vi::VI, state,default) where {VI<:VertexRefIterator}
index = state
miss = 0
readlock(vi.lock)
while index<=vi.l
ref = vi.refs[index]
if ref.cell == 0
index += 1
continue
end
ret = get_vertex(vi.m,ref)
readunlock(vi.lock)
return ret , index+1
end
readunlock(vi.lock)
return default
end
struct VertexIndIterator{AM<:AbstractMesh,AVR<:AbstractVector{Int64},L}
m::AM
refs::AVR
l::Int64
cell::Int64
lock::L
function VertexIndIterator(m::AM1,r::AVR1,c) where {AM1,AVR1}
lock = ReadWriteLock(m)
new{AM1,AVR1,typeof(lock)}(m,r,length(r),c,lock)
end
end
@inline Base.length(vi::VI) where {VI<:VertexIndIterator} = vi.l
@inline Base.iterate(vi::VI, state=1) where {VI<:VertexIndIterator} = _iterate(vi,state,nothing)
@inline function _iterate(vi::VI, state, default) where {VI<:VertexIndIterator}
index = state
readlock(vi.lock)
while index<=vi.l
sig,r = get_vertex(vi.mesh,VertexRef(vi.cell,vi.refs[index]))
if length(sig)==0 || sig[1]==0
index += 1
continue
end
readunlock(vi.lock)
return (sig,r), index+1
end
readunlock(vi.lock)
return default
end
struct VertexDictIterator{T,AVR<:AbstractVector{Pair{Vector{Int64},T}},L}
pairs::AVR
l::Int64
lock::L
function VertexDictIterator(m,r::AVR1) where {T,AVR1<:AbstractVector{Pair{Vector{Int64},T}}}
lock = ReadWriteLock(m)
new{T,AVR1,typeof(lock)}(r,length(r),lock)
end
function VertexDictIterator(m,r::AVR1,l) where {T,AVR1<:AbstractVector{Pair{Vector{Int64},T}}}
lock = ReadWriteLock(m)
new{T,AVR1,typeof(lock)}(r,l,lock)
end
end
@inline Base.length(vi::VI) where {VI<:VertexDictIterator} = vi.l
@Base.propagate_inbounds Base.iterate(vi::VI, state=1) where {VI<:VertexDictIterator} = _iterate(vi,state,nothing)
@Base.propagate_inbounds function _iterate(vi::VI, state=1,default=nothing) where {VI<:VertexDictIterator}
index = state
miss = 0
readlock(vi.lock)
while index<=vi.l
(sig,r) = vi.pairs[index]
if length(sig)==0 || sig[1]==0
index += 1
continue
end
readunlock(vi.lock)
return (sig,r), index+1
end
readunlock(vi.lock)
return default
end
#=dictmodify(::Nothing,default) = default
dictmodify(a,default) = default
@inline function _iterate(vi::D, state=1,default=nothing) where {D<:Dict}
index = state
return dictmodify(iterate(vi,state),default)
end=#
################################################################################################################################################################
## MyFlatten
################################################################################################################################################################
#=struct MyFlatten{A,B,T,D}
iter1::A
iter2::B
mode::MVector{1,Bool}
default::D
function MyFlatten(i1::I1,i2::I2,::Type{T}) where {I1,I2,T}
d = ((Int64[-1],zeros(T)),-1)
new{I1,I2,T,typeof(d)}(i1,i2,MVector{1,Bool}([true]),d)
end
end
@inline function Base.iterate(vi::MF, state=1) where {MF<:MyFlatten}
index = state
if vi.mode[1]==true
if state<=length(vi.iter1)
return _iterate(vi.iter1,state,vi.default)
else
vi.mode[1] = false
return iterate(vi,1)
end
else
if state<=length(vi.iter2)
return _iterate(vi.iter2,state,vi.default)
else
vi.mode[1] = true
return nothing
end
end
return nothing #_iterate(vi.iter2,state,vi.default)
end
@inline Base.length(mf::MF) where {MF<:MyFlatten} = length(mf.iter1)+length(mf.iter2)
=#
@inline function VertexIterator(m::AM,i::BufferVertexData_Dict{VRA,SI}, index::Int64, s::S=statictrue) where {T,AM<:AbstractMesh{T},VRA,SI,S<:StaticBool}
#println("a")
return VertexIterator(m,Iterators.Flatten((VertexDictIterator(m,i.in_cell),VertexRefIterator(m,i.in_mesh))),index,s)
end
@inline function VertexIterator(m::AM,i::BufferVertexData_Vec{VRA,SI}, index::Int64, s::S=statictrue) where {T,AM<:AbstractMesh{T},VRA,SI,S<:StaticBool}
#println("b")
return VertexIterator(m,Iterators.Flatten((VertexIndIterator(m,i.in_cell,index),VertexRefIterator(m,i.in_mesh))),index,s)
end
@inline function VertexIterator(m::AM,i::II,index::Int64, s::S=statictrue) where {T,AM<:AbstractMesh{T},II<:AbstractVector{Int64},S<:StaticBool}
#println("c")
return VertexIterator(m,VertexIndIterator(m,i,index),index,s)
end
@inline VertexIterator(m::AM,i::II,index::Int64, s::S=statictrue) where {T,AM<:AbstractMesh{T},II,S<:StaticBool} = HeapVertexIterator(m,i,[0],s)
#=@inline VertexIterator(m::AM,i::II, index::Int64, s::S=statictrue) where {AM<:AbstractMesh,II,S<:StaticBool} = VertexIterator(m,i,index,s,eltype(i))
@inline VertexIterator(m::AM,i::II,index::Int64, s::S,::Type{P}) where {AM<:AbstractMesh,II,S<:StaticBool,SV<:StaticArray, P<: Pair{Vector{Int64},SV}} = HeapVertexIterator(m,i,Int64[],s)
@inline VertexIterator(m::AM,i::II,index::Int64, s::S,::Type{VertexRef}) where {AM<:AbstractMesh,II,S<:StaticBool} = BufferVertexIterator(m,i,Int64[])
=#
###########################################################################################################
## HeapVertexIterator
###########################################################################################################
struct HeapVertexIterator{AM<:AbstractMesh, II,S<:StaticBool}
mesh::AM
iterator::II
buffer::Vector{Int64}
readonly::S
lbuf::MVector{1,Int64}
end
@inline IterationIndex(i::HVI) where {HVI<:HeapVertexIterator} = IterationIndex(i.iterator)
#const allowwrite = StaticTrue()
HeapVertexIterator(m::AM,i::II,s::S=statictrue) where {AM<:AbstractMesh,II,S<:StaticBool} = HeapVertexIterator(m,i,[0],s,MVector{1,Int64}([1]))
HeapVertexIterator(a,b,c,d) = HeapVertexIterator(a,b,c,d,MVector{1,Int64}([1]))
@inline Base.iterate(vi::VI, state...) where {VI<:HeapVertexIterator{AM,II,StaticFalse} where {AM,II}} = iterate(vi.iterator, state...)
HVImodify(n::Nothing,vi) = nothing
HVImodify(n::Nothing,vi,a,b) = nothing
@Base.propagate_inbounds function HVImodify(data,vi,a,b)
(sig,r) = data[1]
lsig=length(sig)
bb = vi.lbuf[1]
if lsig>bb
resize!(vi.buffer,lsig+1)
vi.lbuf[1] = lsig
end
sig2 = view(vi.buffer,2:(lsig+1))
sig2 .= external_sig(vi.mesh,sig,statictrue)
#_external_indeces_fit(vi.mesh,sig,sig2)
#typeof(data[2])!=Int64 && error("Bla $(typeof(data[2])) \n $(typeof(data)) \n $(typeof(vi.iterator))")
return (ReadOnlyView(sig2),r), data[2]
end
@inline function Base.iterate(vi::VI, state...) where {VI<:HeapVertexIterator{AM,II,StaticTrue} where {AM,II}}
# Delegate to the `iterator` field's `iterate` method
#println(vi.iterator)
#println(typeof(vi.iterator))
#@descend iterate(vi.iterator, state...)
#error("")
iter = iterate(vi.iterator, state...)
# The GC flag won't vanish because it has something to do with returning `nothing`
return HVImodify(iter,vi,vi.iterator,state)
end
@inline Base.IteratorSize(::Type{HeapVertexIterator{AM, II}}) where {AM<:AbstractMesh, II} = Base.IteratorSize(II)
@inline Base.IteratorEltype(::Type{HeapVertexIterator{AM, II}}) where {AM<:AbstractMesh, II} = Base.HaseEltype()
@inline Base.eltype(::Type{HeapVertexIterator{AM, II}}) where {AM<:AbstractMesh, II} = SigmaView
@inline Base.length(vi::HeapVertexIterator) = length(vi.iterator)
################################################################################################################################################################
## ThreadsafeHeapVertexIterator
################################################################################################################################################################
#=
struct ThreadsafeHeapVertexIterator{AM<:AbstractMesh, II, S<:StaticBool}
mesh::AM
iterator::II
buffer::Vector{Int64}
readonly::S
lbuf::MVector{1,Int64}
rwl::ReadWriteLock
function ThreadsafeHeapVertexIterator(hvi::HeapVertexIterator{AM, II, S}, rwl::ReadWriteLock) where {AM<:AbstractMesh, II, S<:StaticBool}
new{AM, II, S}(hvi.mesh, hvi.iterator, hvi.buffer, hvi.readonly, hvi.lbuf, rwl)
end
end
# Inline functions and methods for ThreadsafeHeapVertexIterator
@inline Base.iterate(vi::VI, state...) where {VI<:ThreadsafeHeapVertexIterator{AM,II,StaticFalse} where {AM,II}} =
iterate(vi.iterator, state...)
@inline function Base.iterate(vi::VI, state...) where {VI<:ThreadsafeHeapVertexIterator{AM,II,StaticTrue} where {AM,II}}
id = readlock(vi.rwl)
result = HVImodify(iterate(vi.iterator, state...), vi)
readunlock(vi.rwl,id)
return result
end
@inline Base.IteratorSize(::Type{ThreadsafeHeapVertexIterator{AM, II}}) where {AM<:AbstractMesh, II} =
Base.IteratorSize(II)
@inline Base.IteratorEltype(::Type{ThreadsafeHeapVertexIterator{AM, II}}) where {AM<:AbstractMesh, II} =
Base.IteratorEltype(II)
@inline Base.eltype(::Type{ThreadsafeHeapVertexIterator{AM, II}}) where {AM<:AbstractMesh, II} =
Base.eltype(II)
@inline Base.length(vi::ThreadsafeHeapVertexIterator) = length(vi.iterator)
=#
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 17042 |
const Dirichlet=0
const Neumann=-1
import Base.in
#################################################################################################################
## struct Boundary and related operators on it
#################################################################################################################
@doc raw"""
Plane{T}
provides a 'base' vector and a 'normal' vector of type 'T' to describe a plane.
BC=Dirichlet or BC=Neumann indicate Dirichlet- resp. Neumann- boundary condition on the plane.
BC='any positive number' indicates periodic boundary conditions with the complementary plane given by the index BC
"""
struct Plane
base::Vector{Float64}
normal::Vector{Float64}
BC::Int16
function Plane(b,n,bc)
return new(b,n,bc)
end
end
function planeToString(plane::Plane)
return "[ Plane($(plane.BC)): base=$(plane.base), normal=$(plane.normal) ] "
end
function BC_Dirichlet(b,n)
return Plane(b,n,Dirichlet)
end
function BC_Neumann(b,n)
return Plane(b,n,Neumann)
end
struct BC_Periodic
up::Plane
down::Plane
function BC_Periodic(u,d)
return new(u,d)
end
function BC_Periodic(base1,base2,normal1)
return new(Plane(base1,normal1,0),Plane(base2,(-1).*normal1,0))
end
end
#################################################################################################################
## struct Boundary and related operators on it
#################################################################################################################
"""
Boundary
provides the data structure for boundaries of VoronoiGeometry. Its most important feature is the vector
planes::Vector{Plane}
which stores every flat part of the boundary as
struct Plane
base::Vector{Float64} # base of the plane
normal::Vector{Float64} # outer normal of the domain on this plane
BC::Int16 # 0 for Dirichlet, -1 for Neumann and >0 for the index of the other correspondant in case this is supposed to be periodic
end
"""
struct Boundary
planes::Vector{Plane}
convex::Bool
#childs::Vector{Vector{Int64}}
function Boundary(_planes::Vector,_convex::Bool)
return new(_planes,_convex)#,_convex,(Vector{Int64})[])
end
end
function copy(b::Boundary)
planes = Vector{Plane}(undef,length(b))
for i in 1:length(b)
planes[i] = Plane(copy(b.planes[i].base),copy(b.planes[i].normal),b.planes[i].BC)
end
return Boundary(planes,b.convex)
end
"""
Boundary(planes...)
is the constructor for Boundaries. planes... is a list of planes generated by either one of the following functions:
BC_Dirichlet(b,n)
BC_Neumann(b,n)
generating Dirichlet resp. Neumann boundaries with base `b` and normal `n`.
BC_Periodic(base1,base2,normal1)
generating two periodic boundaries with `base1` and `normal1` resp. with `base2` and `normal = -normal1`
"""
function Boundary(planes...)
count=0
for p in planes
if typeof(p)==BC_Periodic
count+=2
else
count+=1
end
end
newplanes=Vector{Plane}(undef,count)
count=1
for p in planes
if typeof(p)==BC_Periodic
newplanes[count]=Plane(p.up.base,p.up.normal,count+1)
newplanes[count+1]=Plane(p.down.base,p.down.normal,count)
count+=2
else
newplanes[count]=p
count+=1
end
end
return Boundary(newplanes,true)
end
function Boundary()
return Boundary(Plane[],true)
end
#################### OUTPUT REPRESENTATION ####################################################################
function boundaryToString(B::Boundary;offset=0)
result="\u1b[($offset)CBOUNDARY in $(length(B.planes[1].normal)) dimensions with $(length(B.planes)) planes:\n"
for i in 1:(length(B.planes))
plane=B.planes[i]
result*="\u1b[($offset)C $i: base=$(plane.base), normal=$(plane.normal) ; "
if (plane.BC==Neumann) result*="Neumann\n"
elseif plane.BC==Dirichlet result*="Dirichlet\n"
else result*="periodic with neighbor $(plane.BC)\n" end
end
return result
end
function Base.show(B::Boundary)
print(boundaryToString(B))
end
function vp_print(B::Boundary;offset=0)
vp_print(offset,"BOUNDARY:")
vp_line()
for i in 1:(length(B.planes))
plane=B.planes[i]
vp_print(offset+4,"$i: base=$(plane.base), normal=$(plane.normal) ; ")
if (plane.BC==Neumann) println("Neumann")
elseif plane.BC==Dirichlet println("Dirichlet")
else println("periodic with neighbor $(plane.BC)") end
end
end
@doc raw"""
edge_representation2D(B::Boundary)
provides a representation for each plane of 'B' in terms of two verteces
"""
function edge_representation2D(B::Boundary)
result = EmptyDictOfType(1=>(B.planes[1].base,B.planes[1].base))
for edge in 1:(length(B.planes))
intersections=EmptyDictOfType(1=>(1.0,B.planes[1].base))
x_0=B.planes[edge].base
v= [0 1;-1 0]*B.planes[edge].normal#zeros(Float64,2)
for i in 1:(length(B.planes))
i==edge && continue
new_t=intersect(B.planes[i],x_0,v)
new_t==Inf && continue
point=x_0+new_t*v
push!(intersections,i=>(dot(B.planes[i].base-point,B.planes[i].base),point)) # key always non-positive but zero only for the two intersection points at boundary
end
e1=-Inf64
e2=-Inf64
x1=copy(x_0)
x2=copy(x_0)
while length(intersections)>0
(_,(e,x))=pop!(intersections)
if e>=e1
e2=e1
e1=e
x2=x1
x1=x
end
end
push!(result,edge=>(x1,x2))
end
return result
end
####################### GEOMETRIC OPERATIONS ######################################################################
@inline reflect(node,boundary::Boundary,plane,indeces) = reflect(node,boundary::Boundary,boundary.planes[indeces[plane]])
function reflect(node,boundary::Boundary,plane)
_plane=boundary.planes[plane]
normal=_plane.normal
base=_plane.base
return node+normal .*(2*dot(normal,base.-node))
end
@doc raw"""
intersect(P::Plane,x_0,v)
calculates the scalar solution t to the problem
(y-P.base)*P.normal=0 , x_0+t*v=y
eg: (P.base-x_0)*P.normal == t v*P.normal
"""
function intersect(P::Plane,x_0,v)
return dot(P.base-x_0,P.normal)/dot(v,P.normal)
end
@doc raw"""
intersect(B::Boundary,x_0,v)
calculates intersect(P,x_0,v) for every plane P in B and returns (i,t), the index 'i' of the minimal result
as well as the minimal result 't'
"""
function intersect(B::Boundary,x_0,v,condition=(x->true))
index=0::Int64
t=Inf64::Float64
for i in 1:(length(B.planes))
if !condition(i) continue end
new_t=intersect(B.planes[i],x_0,v)
if 0<new_t<t
t=new_t
index=i
end
end
return index,t
end
function intersection_exists(B::Boundary,x_0,v)
p = intersect_point(B,x_0,v)
for i in 1:length(B.planes)
if dot(p-B.planes[i].base,B.planes[i].normal)>1.0E-5
return false
end
end
return true
end
function intersect_point(B::Boundary,x_0,v)
index, t = intersect(B,x_0,v)
return t>0 ? x_0+t*v : x_0
end
@doc raw"""
intersections(B::Boundary,x_0,v)
calculates for every plane p_i of B the value t_i with x_0+t_i*v_ in p_i . results will store a sorted list of t_i and indeces stores the corresponding list of i.
The return value is the entry i of indeces such that x_0 +0.5*(t_i + t_(i+1)) in B
"""
function intersections!(B::Boundary,x_0,v; results=zeros(Float64,length(B.planes)), indeces=collect(1:length(B.planes)), condition=(x->true))
sort!(indeces)
for i in 1:(length(B.planes))
if !condition(B.planes[i].BC) continue end
results[i]=intersect(B.planes[i],x_0,v)
end
quicksort!(results,indeces,indeces)
found=0
r=results
for i in 1:(length(results)-1)
if (results[i]>-Inf && results[i+1]<Inf)
point=x_0+0.5*(r[i]+r[i+1])*v
if point in B
found=i
break
end
end
end
return found
end
############# HANDLING BOUNDARIES ###############################
function compare(B1::Boundary,B2::Boundary,bc=false)
length(B1)==length(B2) && length(B1)==0 && (return true)
(length(B1)==0 || length(B2)==0) && (return false)
(length(B1)!=length(B2) || length(B1.planes[1].normal)!=length(B2.planes[1].normal)) && (return false)
lB = length(B1)
identified = zeros(Bool,lB)
for k in 1:lB
for i in 1:lB
identified[i] && continue
if abs(dot(B1.planes[k].normal,B2.planes[i].normal)-1.0)<1.0E-10
if abs(dot(B1.planes[k].base-B2.planes[i].base,B1.planes[k].normal))<1.0E-8
identified[i] = true
if bc
B1.planes[k].BC>0 && B2.planes[k].BC<=0 && (return false)
B1.planes[k].BC<=0 && B2.planes[k].BC>0 && (return false)
end
else
return false
end
end
end
end
return true
end
function same(boundary1::Boundary, boundary2::Boundary, i::Int)
plane1 = boundary1.planes[i]
plane2 = boundary2.planes[i]
normal_match = norm(plane1.normal - plane2.normal) < 1e-5
b1, b2 = plane1.base, plane2.base
if norm(b1 + b2) > 1e-5
base_match = norm(b1 - b2) / norm(b1 + b2) < 1e-5
else
base_match = norm(b1 - b2) < 1e-5
end
return normal_match && base_match
end
function same(boundary1::Boundary, boundary2::Boundary)
length(boundary1)!=length(boundary2) && return false
ret = true
for i in 1:length(boundary1)
ret &= same(boundary1,boundary2,i)
!ret && break
end
return ret
end
function split_boundary_indeces(B::Boundary)
inds=collect(1:length(B))
dir = keepat!(copy(inds),map(k->(B.planes[k].BC==0),inds))
neu = keepat!(copy(inds),map(k->(B.planes[k].BC<0),inds))
per = keepat!(copy(inds),map(k->!((k in dir) || (k in neu)),inds))
return per, neu, dir
end
"provides the non-periodic part of the boundary"
function reduce_periodic_part(B::Boundary)
count=0
for i in 1:length(B.planes)
if B.planes[i].BC<=0 count+=1 end
end
new_planes=Vector{Plane}(undef,count)
indeces=Vector{Int64}(undef,count)
count=0
for i in 1:length(B.planes)
if B.planes[i].BC<=0
count+=1
indeces[count]=i
new_planes[count]=B.planes[i]
end
end
return Boundary(new_planes,B.convex),indeces
end
function reduce_to_periodic(B::Boundary)
count=0
skipped=zeros(Int64,length(B.planes))
skip=0
for i in 1:length(B.planes)
if B.planes[i].BC>0
count+=1
else
skip+=1
end
skipped[i]=skip
end
new_planes=Vector{Plane}(undef,count)
count=0
for i in 1:length(B.planes)
if B.planes[i].BC>0
count+=1
new_planes[count]=Plane(B.planes[i].base,B.planes[i].normal,B.planes[i].BC-skipped[B.planes[i].BC])
end
end
return Boundary(new_planes,B.convex)
end
function remove_periodicity(B::Boundary)
new_planes = Vector{Plane}(undef,length(B.planes))
for i in 1:length(B.planes)
new_planes[i]=Plane(B.planes[i].base ,B.planes[i].normal,0)
end
return Boundary(new_planes,B.convex)
end
function extend_periodic_part(B::Boundary,xs::Points,indeces = false)
lxs = length(xs)
_indeces = collect(1:length(B))
for i in 1:length(B.planes)
if B.planes[i].BC>0
#bestpos=0
d=0.0
for j in 1:lxs
#d=max(d,dot(B.planes[i].normal, xs[j] - (bestpos==0 ? B.planes[i].base : xs[bestpos])))
d=max(d,dot(B.planes[i].normal, xs[j] - B.planes[i].base ))
end
if d>0.0
B.planes[i].base .+= (1.01*d) .* B.planes[i].normal
else
_indeces[i] = 0
end
else
_indeces[i] = 0
end
end
return keepat!(_indeces,map(x->(x!=0),_indeces))
end
function in(x,B::Boundary)
l=length(B.planes)
l==0 && return true
for i in 1:l
plane=B.planes[i]
if dot(plane.base-x,plane.normal)<0 return false end
end
return true
end
function check_boundary(nodes,b::Boundary)
for x in nodes
!(x in b) && error("$x does not lie in the domain given by the boundary object\n"*boundaryToString(b,offset=4))
end
end
@inline function adjust_boundary_vertex(x,B::Boundary,sig,lmesh,lsig=length(sig),tolerance=1.0E-10)
return x
end
function show_in(x,B::Boundary)
l=length(B.planes)
l==0 && return true
for i in 1:l
plane=B.planes[i]
if dot(plane.base-x,plane.normal)<0
println(i,": ",plane.base-x," , ",plane.normal," , ",dot(plane.base-x,plane.normal))
return false
end
end
return true
end
function project(x,B::Boundary)
x2=x
l=length(B.planes)
l==0 && return x
for i in 1:l
plane=B.planes[i]
d=dot(plane.base-x,plane.normal)
if d<0
x2=x2+d*plane.normal
end
end
return x2
end
function length(b::Boundary)
return length(b.planes)
end
function push!(boundary::Boundary,plane::Plane)
push!(boundary.planes,plane)
end
function push!(boundary::Boundary,per::BC_Periodic)
l=length(boundary.planes)
push!(boundary.planes,Plane(per.up.base,per.up.normal,l+2))
push!(boundary.planes,Plane(per.down.base,per.down.normal,l+1))
end
###################### GENERATING CUBES ###############################################
center_cube(dim,size)=cuboid(dim,dimensions=size*ones(Float64,dim),offset=-0.5*size*ones(Float64,dim))
"""
cuboid(dim;dimensions=ones(Float64,dim),periodic=collect(1:dim),neumann=Int64[],offset=zeros(Float64,dim))
or simply `cuboid(dim)` generates a cube of type `Boundary`.
- dim : This is the dimension of the cuboid
- dimensions : provides the size of the cuboid in each dimension
- periodic : this is a (sorted!!) list of dimensions in which the cube is assumed to have periodic boundary conditions
- neumann : every dimension k=1...dim which is not periodic my be put here with positive sign for the right hand side or negative sign (i.e. -k) for the left hand side
- offset : shifts the cube in space
A particular application is the following method provided by HighVoronoi.
center_cube(dim,size) = cuboid(dim,dimensions=size*ones(Float64,dim),offset=-0.5*size*ones(Float64,dim))
Relying on `cuboid(...)` it generates a cube with center `0` and edge length `size`.
"""
function cuboid(dim;dimensions=ones(Float64,dim),periodic=collect(1:dim),neumann=Int64[],offset=zeros(Float64,dim))
planes=Vector{Plane}(undef,2*dim)
unit=zeros(Float64,dim)
_zeros=zeros(Float64,dim)
for i in 1:dim
unit.*=0
unit[i]=1
if i in periodic
planes[(2*i)-1]=Plane(offset.+dimensions[i] .*unit,copy(unit),2*i)
planes[2*i]=Plane(copy(offset),(-1).*unit,(2*i)-1)
continue
end
if i in neumann
planes[(2*i)-1]=Plane(offset.+dimensions[i].*unit,copy(unit),Neumann)
else
planes[(2*i)-1]=Plane(offset.+dimensions[i].*unit,copy(unit),Dirichlet)
end
if -i in neumann
planes[2*i]=Plane(copy(offset),(-1).*unit,Neumann)
else
planes[2*i]=Plane(copy(offset),(-1).*unit,Dirichlet)
end
end
return Boundary(planes,true)
end
function testboundary()
p1 = BC_Dirichlet([1.0,0.0],[1.0,0.0])
p2 = BC_Neumann([0.0,0.0],[-1.0,0.0])
p3 = BC_Periodic([0.0,1.0],[0.0,0.0],[0.0,1.0])
b = Boundary(p1,p2,p3)
println(boundaryToString(b))
show(b)
intersections!(b,[0.5,0.5],[1.0,0.0])
c = cuboid(2,periodic=[1])
c2 = cuboid(2,periodic=[2])
show_in([0.5,0.5],c)
same(c,c2)
reduce_periodic_part(c)
reduce_to_periodic(c2)
push!(c,p1)
push!(c,p3)
return true
end | HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 4609 |
function cleanup_cell(vol,ar,bulk,inter,_Cell,iterate, calculate, data,Integrator::II) where {II<:Geometry_Integrator}
return 0.0
end
function cleanup_cell(vol,ar,bulk,inter,_Cell,iterate, calculate, data,Integrator::II) where {II<:Montecarlo_Integrator}
dfvb=data.float_vec_buffer
dfvvb=data.float_vec_vec_buffer
Integral = Integrator.Integral
cdw = cell_data_writable(Integral,_Cell,dfvb,dfvvb)
old_neighbors = cdw.neighbors
activate_data_cell(data,_Cell,old_neighbors)
xs = data.extended_xs
vector = xs[_Cell]
dim = length(vector)
V = 0.0
for i in 1:length(old_neighbors)
n = old_neighbors[i]
#hascelldata(Integrator.Integral,n)
if !(n in calculate) && hascelldata(Integrator.Integral,n)
neigh_data = cell_data_writable(Integrator.Integral,n,dfvb,dfvvb)
_Cell_index = findfirstassured(_Cell,neigh_data.neighbors)
distance=0.5*norm(vector-xs[n])
neigh_area = neigh_data.area[_Cell_index]
if neigh_area>0 # otherwise pointless
factor = distance/dim
vol2 = 0.5*( neigh_area-cdw.area[i])
vol = vol2*factor
cdw.volumes[1] += vol
neigh_data.volumes[1] -= vol
#V+=vol
cdw.area[i] += vol2
neigh_data.area[_Cell_index] -= vol2
if !(typeof(Integrator.interface)==Nothing || length(neigh_data.interface_integral)<length(neigh_data.neighbors) || Integrator.heuristic)
cdw.bulk_integral .-= cdw.interface_integral[i] .* factor
neigh_data.bulk_integral .-= neigh_data.interface_integral[_Cell_index] .* factor
cdw.interface_integral[i] .+= neigh_data.interface_integral[_Cell_index]
cdw.interface_integral[i] .*= 0.5
neigh_data.interface_integral[_Cell_index] .= cdw.interface_integral[i]
cdw.bulk_integral .+= cdw.interface_integral[i] .* factor
neigh_data.bulk_integral .+= neigh_data.interface_integral[_Cell_index] .* factor
end
end
end
end
return V
end
function cleanup_cell(vol,ar,bulk,inter,_Cell,iterate, calculate, data,Integrator::II) where {II<:Union{Polygon_Integrator,Fast_Polygon_Integrator}}
dfvb=data.float_vec_buffer
dfvvb=data.float_vec_vec_buffer
Integral = Integrator.Integral
cdw = cell_data_writable(Integral,_Cell,dfvb,dfvvb)
old_neighbors = cdw.neighbors
activate_data_cell(data,_Cell,old_neighbors)
xs = data.extended_xs
vector = xs[_Cell]
dim = length(vector)
V = 0.0
for i in 1:length(old_neighbors)
n = old_neighbors[i]
if !(n in calculate)
distance=0.5*norm(vector-xs[n])
has_area_data = cdw.area[i]>0
vol2 = has_area_data ? cdw.area[i] : get_area(Integral,n,_Cell)
vol = vol2*distance/dim
cdw.volumes[1] += vol
V+=vol
cdw.area[i] = vol2
if inter
AA = has_area_data ? cdw.interface_integral[i] : get_integral(Integral,n,_Cell)
cdw.interface_integral[i] .= AA
cdw.bulk_integral .+= AA.*(distance/dim)
end
end
end
return V
end
function cleanup_cell(vol,ar,bulk,inter,_Cell,iterate, calculate, data,Integrator::II) where {II<:Union{Heuristic_Integrator}}
dfvb=data.float_vec_buffer
dfvvb=data.float_vec_vec_buffer
Integral = Integrator.Integral
cdw = cell_data_writable(Integral,_Cell,dfvb,dfvvb)
old_neighbors = cdw.neighbors
activate_data_cell(data,_Cell,old_neighbors)
xs = data.extended_xs
vector = xs[_Cell]
dim = length(vector)
V = 0.0
for i in 1:length(old_neighbors)
n = old_neighbors[i]
if !(n in calculate) && hascelldata(Integrator.Integral,n)
distance=0.5*norm(vector-xs[n])
AA = get_integral(Integral,n,_Cell)
cdw.interface_integral[i] .= AA
cdw.bulk_integral .+= AA.*(distance/dim)
end
end
return V
end
@inline function cleanup_cell(vol,ar,bulk,inter,_Cell,iterate, calculate, data,Integrator::II) where {II<:Union{HeuristicMCIntegrator}}
cleanup_cell(vol,ar,bulk,inter,_Cell,iterate, calculate, data,Integrator.mc)
cleanup_cell(vol,ar,bulk,inter,_Cell,iterate, calculate, data,Integrator.heuristic)
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 1710 |
struct FunctionComposer{FT,LT,TT}
functions::FT
total::Int64
length_index_data::LT
Type::TT
reference_value::Vector{Float64}
end
"""
FunctionComposer(;reference_argument, super_type, _functions...)
The composer takes the following arguments:
- `_functions`: This is a list of named funcions.
- `super_type`: suppose your functions return values of type `T` and `Vector{T}` you should set `super_type=T`
- `reference_argument`: Your functions take values of type `Float` and are well defined in `0.0`? Then you can put e.g. `0.0` here.
If your function accepts `StaticArray{3,Float64}` put e.g. `SVector{3,Float64}([0.0,1.2,3.4])`
"""
function FunctionComposer(;reference_argument, super_type, _functions...)
#println(values(_functions))
join = x->vcat( super_type[], map( f->f(x), values(_functions) )... )
ref_val = join(reference_argument)
_total=length(ref_val)
counter=[1]
mylengths=map( f->_mycounter( f(reference_argument), counter ), values(_functions) )
return FunctionComposer{typeof(join),typeof(mylengths),typeof(super_type)}(join,_total,mylengths,super_type,ref_val)
end
function _data_length(FC::FunctionComposer,symbol)
return FC.length_index_data[symbol][2]
end
function _mycounter(x,counter)
l=length(x)
c=counter[1]
counter[1]+=l
return Pair(c,l)
end
function decompose(F::FunctionComposer,val;scalar=false)
if scalar
return map( inds->__simplify_discrete(view(val,(inds.first):(inds.first+inds.second-1) )) , F.length_index_data )
else
return map( inds->view(val,(inds.first):(inds.first+inds.second-1) ) , F.length_index_data )
end
end | HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 10333 |
function integrate_cube(_Cell, data,Integrator,Integral,proto,_function)
if (length(proto)==0)
return
end
cdw = cell_data_writable(Integral,_Cell,proto,[proto])
neigh = cdw.neighbors
verteces = vertices_iterator(mesh(Integral),_Cell) #
xs=data.extended_xs
dim = data.dimension # (full) Spatial dimension
activate_data_cell(data,_Cell,neigh)
inter_inte = cdw.interface_integral
bulk_inte = cdw.bulk_integral
ar = cdw.area
# get all neighbors of this current cell
_length=length(neigh)
# flexible data structure to store the sublists of verteces at each iteration step 1...dim-1
emptydict=EmptyDictOfType([0]=>xs[1]) # empty buffer-list to create copies from
# empty_vector will be used to locally store the center at each level of iteration. This saves
# a lot of "memory allocation time"
empty_vector=zeros(Float64,dim)
# do the integration
I=Integrator
heuristic_Cube_integral(_function, true, _Cell, bulk_inte, ar, inter_inte, dim, neigh,
_length,verteces,emptydict,xs[_Cell],empty_vector,xs)
return cdw.volumes[1]
end
function heuristic_Cube_integral(_function, _bulk, _Cell::Int64, y, A, Ay, dim,neigh,_length,verteces,
emptylist,vector,empty_vector,xs)
# dd will store to each remaining neighbor N a sublist of verteces which are shared with N
dd=Vector{typeof(emptylist)}(undef,_length)
for i in 1:_length dd[i]=copy(emptylist) end
for (sig,r) in verteces # iterate over all verteces
for _neigh in sig # iterate over neighbors in vertex
_neigh==_Cell && continue
index=_neigh_index(neigh,_neigh)
if index!=0 && (_neigh>_Cell || isempty(dd[index])) # make sure for every neighbor the dd-list is not empty
push!( dd[index] , sig =>r) # push vertex to the corresponding list
end
end
end
for k in 1:_length
buffer=neigh[k]
# if !(buffer in calculate) && !(_Cell in calculate) continue end
bufferlist=dd[k]
isempty(bufferlist) && continue
AREA_Int = Ay[k] # always: typeof(_function)!=Nothing
AREA_Int.*=0
_Center = midpoint_points(bufferlist,emptylist,empty_vector,vector)
_Center .+= vector # midpoint shifts the result by -vector, so we have to correct that ....
count = 0
while !(isempty(bufferlist))
_,r=pop!(bufferlist)
AREA_Int .+= _function(r)
count+=1
end
AREA_Int .*= (dim-1)/(dim*count)
AREA_Int .+= (1/dim).*_function(_Center)
thisarea = A[k]
AREA_Int .*= thisarea
distance= 0.5*norm(vector-xs[buffer]) #abs(dot(normalize(vector-xs[buffer]),vert))
_y=_function(vector)
_y.*=(thisarea/(dim+1))
_y.+=(AREA_Int*(dim/(dim+1))) # there is hidden a factor dim/dim which cancels out
_y.*=(distance/dim)
y.+=_y
end
end
########################################################################################################################################
########################################################################################################################################
## CubicVoronoiGeometry
########################################################################################################################################
########################################################################################################################################
function cubic_voronoi_copy_verteces(Integral,deviation,counter,extended_cube,get_volumes,vol1,vol2,indeces,proto)
mesh = HighVoronoi.mesh(Integral)
dim = dimension(mesh)
_NON = counter.data.number_of_nodes
lmesh = length(mesh)
# lboundary = length(extended_cube)
new_index = counter.cell_index
current_dim = 0
# the old block from which we copy....
for i in 1:length(counter.data.repeat)
if counter.cell_array[i]>2
current_dim = i
if counter.cell_array[i]<counter.data.repeat[i]
break
end
end
if counter.cell_array[i]>1 && current_dim==0
current_dim = i
end
end
old_array = copy(counter.cell_array)
old_array[current_dim] += -1
old_index = index_from_array(old_array,counter.data)
right_frame = counter.cell_array[current_dim]==counter.data.repeat[current_dim]
right_cells, count_right_cells = right_frame ? right_indeces(copy(counter.cell_array),counter.data,current_dim,dim,indeces) : (Int64[],0)
right_cells = view(indeces,1:count_right_cells)
nodeshift = ( new_index - old_index )*_NON
coordinateshift = counter.cell_offset - offset(old_array,counter.data)
if right_frame
coordinateshift[current_dim] -= deviation[current_dim]
end
c1 = lmesh+(2*current_dim-1) # RIGHT
c2 = lmesh+(2*current_dim) # LEFT
# now transfer non-affected nodes
for (sig,r) in vertices_iterator(mesh,old_index)# mesh.All_Verteces[old_index]
sig[1]!=old_index && continue
sig2 = copy(sig)
stopp = false
for ikk in 1:length(sig)
if sig2[ikk]==c2
stopp = true
end
if right_frame && sig2[ikk] in right_cells
sig2[ikk]=0
elseif sig2[ikk]<=lmesh
sig2[ikk] += nodeshift
end
end
stopp && continue
if right_frame
append!(sig2,c1)
sort!(filter!(x->x!=0,sig2))
end
r2 = adjust_boundary_vertex(r + coordinateshift,extended_cube,sig2,lmesh,length(sig2))
push!(mesh, sig2=>r2)
end
# error("")
cdw = cell_data_writable(Integral,old_index,nothing,nothing;get_integrals=staticfalse)
neigh = copy(cdw.neighbors)
area = get_volumes ? copy(cdw.area) : Float64[]
stretchright = counter.cell_array[current_dim]==counter.data.repeat[current_dim]
stretchleft = counter.cell_array[current_dim]==2
volume = 0.0
for ii in 1:length(neigh)
if neigh[ii]==c2
neigh[ii]=old_index
elseif stretchright && neigh[ii]==new_index
neigh[ii]=c1
else
stretchleft && get_volumes && neigh[ii]!=new_index && (area[ii]/=vol1[current_dim])
if neigh[ii]<=lmesh
neigh[ii] += nodeshift
end
stretchright && get_volumes && neigh[ii]!=old_index && (area[ii]*=vol2[current_dim])
end
end
quicksort!(neigh,neigh,get_volumes ? area : neigh)
set_neighbors(Integral,new_index,neigh,proto,proto)
cdw2 = cell_data_writable(Integral,new_index,nothing,nothing,get_integrals=staticfalse)
if get_volumes
volume = cdw.volumes[1]
stretchleft && (volume/=vol1[current_dim])
stretchright && (volume*=vol2[current_dim])
cdw2.volumes[1] = volume
cdw2.area .= area
end
end
function first_cube(mesh,deviation,cell_size,searcher)
xs = nodes(mesh)
dim = length(xs[1])
x0 = xs[1]-deviation-0.5*cell_size
periodicity = PeriodicData(2*ones(Int64,dim),cell_size+deviation,1,zeros(Float64,dim))
MM = x0
verteces = periodicgeodata([MM],periodicity)
left_boundary = 2*collect(1:dim)
left_boundary .+= length(xs)
activate_cell( searcher, 1, left_boundary)
for r in verteces
sig = _inrange(searcher.tree,r,norm(r-xs[1])*(1+1.0E-10))
sort!(sig)
push!(mesh,sig=>r)
end
end
function cubic_voronoi(domain,periodicity,deviation,cell_size,search,my_integrator,integrand,periodicview)
extended_cube = internal_boundary(domain)
Integral = IntegralView(HighVoronoi.integral(domain),periodicview)
mesh = HighVoronoi.mesh(Integral)
xs = copy(nodes(mesh))
dim = length(xs[1])
searcher = Raycast(xs; domain = extended_cube, options=search)
lmesh = length(xs)
area = zeros(MVector{2*size(eltype(xs))[1],Float64})
#=_I,_ = voronoi( xs, Iter=[1], searcher=searcher, intro="Calculate unit cell: ",compact=true)
Integrator = my_integrator(_I.Integral.MESH)=#
vp_print(0,"Calculate first cell...")
first_cube(mesh,deviation,cell_size,searcher)
Integrator = my_integrator(Integral)
proto = prototype_bulk(Integrator)
_function = integrand
get_volumes = enabled_volumes(Integral)
data = IntegrateData(xs,extended_cube,Integrator)
# data for first cell:
vol_vector = deviation + cell_size
vol_vector2 = cell_size - deviation
neighbors = Vector{Int64}(undef,2*dim)
index = ones(Int64,dim)
bit = BitVector(ones(Int8,dim))
for i in 1:dim
if get_volumes
bit[i] = 0
area[2*i-1] = area[2*i] = prod(view(vol_vector,bit))
bit[i]=1
end
neighbors[2*i] = lmesh + 2*i
index[i]=2
neighbors[2*i-1] = index_from_array(index,periodicity)
index[i]=1
end
set_neighbors(Integral,1,copy(neighbors),proto,proto)
quicksort!(neighbors,neighbors,area)
cdw = cell_data_writable(Integral,1,proto,[proto])
cdw.area .= area
if get_volumes
cdw.volumes[1] = prod(vol_vector)
end
integrate_cube(1, data,Integrator,Integral,proto,_function)
println(cell_data_writable(Integral,1,proto,[proto]))
pc = Periodic_Counter(periodicity)
increase(pc)
indeces = zeros(Int64,3^(dim-1))
vp_print(0,"Copy Data to cell: ")
print_count = round(Int64,pc.maxindex/100)+1
count=0
while !eol(pc)
count+=1
if count>=print_count
vp_print(20,"$(pc.cell_index)")
count=0
end
cubic_voronoi_copy_verteces(Integral,deviation,pc,extended_cube,get_volumes,vol_vector./cell_size,vol_vector2./cell_size,indeces,proto)
integrate_cube(pc.cell_index, data, Integrator,Integral,proto,_function)
increase(pc)
end
return Integrator
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 5240 | """
DensityRange{S}
provides a rectangular grid of points in a `S`-dimensional space. It is initialized as follows:
DensityRange(mr::AbstractVector{<:Integer},range)
Here, `range` can be of the following types:
- `AbstractVector{Tuple{<:Real,<:Real}}`: It is assumed that each entry of `range` is a tuple `(a_i,b_i)`
so the range is defined in the cuboid `(a_1,b_1)\times...\times(a_{dim},b_{dim})`
`mr` is assumed to have the same dimension as `range` and the interval `(a_i,b_i)` will be devided into `mr[i]` intervalls
- `AbstractVector{<:Real}`: if e.g. `range=[1.0,1.0]` this will be transferred to `range=[(0.0,1.0),(0.0,1.0)]`
and the first instance of the method is called
- `Float64`: `range` will be set `range*ones(Float64,length(mr))` and the second instance is called
- `Tuple{<:Real,<:Real}`: range will be set to an array of identical tuple entries and the first version is called
Alternatively, one may call the following method:
DensityRange(mr::Int,range,dimension=length(range))
it is assumed that `range` is an array or tuple of correct length and `mr` is replaced by `mr*ones(Int64,dimension)`.
If range is not an array, then `dimension` has to be provided the correct value.
"""
struct DensityRange{S}
dimensions::SVector{S,Float64}
number_of_cells::SVector{S,Int64}
x::MVector{S,Float64}
function DensityRange(mr::AbstractVector{<:Integer},dimensions = AbstractVector{Tuple{<:Real,<:Real}})
dim = length(mr)
length(dimensions)!=dim && error("The dimensions of first and second vector have to coincide")
for k in 1:dim
dimensions[k][2]<dimensions[k][1] && error("second entry of each coordinate needs to be larger than first entry, but $(dimensions[k][2])>=$(dimensions[k][1]) in dimension $k. ")
end
mycubes = map(k->dimensions[k][2]-dimensions[k][1],1:dim)
mycubes ./= mr
offset = map(k->dimensions[k][1]+0.5*mycubes[k],1:dim)
return new{dim}(SVector{dim,Float64}(mycubes),SVector{dim,Int64}(mr),MVector{dim,Float64}(offset))
end
function DensityRange(mr::AbstractVector{<:Integer},dimensions::AbstractVector{<:Real})
dim = length(mr)
length(dimensions)!=dim && error("The dimensions of first and second vector have to coincide")
for k in 1:dim
dimensions[k]<0 && error("second argument is only allowed to contain positive entries, contains $(dimensions[k]).")
end
return DensityRange(mr,map(k->(0.0,dimensions[k]),1:dim))
end
function DensityRange(mr::AbstractVector{<:Integer},dimensions::Float64)
return DensityRange(mr,dimensions*ones(Float64,length(mr)))
end
function DensityRange(mr::AbstractVector{<:Integer},dimensions::Tuple{<:Real,<:Real})
dim = length(mr)
dimensions[2]<dimensions[1] && error("invalid tuple $dimensions.")
return DensityRange(mr,map(k->dimensions,1:dim))
end
function DensityRange(mr::Int,b;dimension=length(b))
return DensityRange(mr*ones(Int64,dimension),b)
end
end
DIMENSION(dr::DensityRange) = typeof(dr).parameters[1]
get_density(ρ,crit,range::DensityRange) = _get_density(ρ,crit,range,1,copy(range.x))
function _get_density(ρ,crit,range::DensityRange,level,x, count = 0)
my_sum = 0.0
x0 = x[level]
for k in 1:range.number_of_cells[level]
x[level] += range.dimensions[level]
if level<DIMENSION(range)
ms, count = _get_density(ρ,crit,range,level+1,x,count)
my_sum += ms
elseif crit(x)
count += 1
my_sum += ρ(x)
end
end
x[level] = x0
if level==1
my_sum *= prod(range.dimensions)
return x->ρ(x)/my_sum
else
return my_sum, count
end
end
function _get_nodes(crit::Function,range::DensityRange,level,nodes,x,count)
x0 = x[level]
for k in 1:range.number_of_cells[level]
if level<DIMENSION(range)
_, count = _get_nodes(crit,range,level+1,nodes,x,count)
else
if rand()<crit(x)
count += 1
l = length(nodes)
if l<count
resize!(nodes,l+100)
end
y = normalize!(randn(DIMENSION(range)))
nn = x .+ (0.1 .* y .* range.dimensions)
#=for k in 1:DIMENSION(range)
if nn[k]<0 || nn[k]>1
println("$count: $nn")
break
end
end=#
nodes[count] = VoronoiNode(nn)
if count%100==0
vp_print(30,count)
end
end
end
x[level] += range.dimensions[level]
end
x[level] = x0
if level==1
return resize!(nodes,count)
else
return nodes, count
end
end
get_nodes(crit::Function,range::DensityRange) = _get_nodes(crit,range,1,VoronoiNodes(undef,DIMENSION(range),1000),copy(range.x),0)
#println()
get_nodes(mr::Int,dim::Int,crit) = get_nodes(crit,DensityRange(mr,1.0,dimension=dim))
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 7765 | ###############################################################################################################################
## Discrete functions .....
###############################################################################################################################
function periodic_projection(x,b::Boundary,buffer)
planes = b.planes
buffer .= x
for p in planes
p.BC<=0 && continue
d = dot(p.normal,x-p.base)
d<=0 && continue
width = dot(p.normal,p.base-planes[p.BC].base)
delta = -(trunc(d/width)+1)*width
buffer .+= delta .* p.normal
end
return buffer
end
function PeriodicFunction(f::Function,b::Boundary)
#length(b.planes)==0 && (return f)
dim = length(b.planes[1].base)
buffer = MVector{dim}( zeros(Float64,dim))
return x->f(periodic_projection(x,b,buffer))
end
function PeriodicFunction(f::Function,VG::VoronoiGeometry)
return PeriodicFunction(f,VG.domain.boundary)
end
struct VoronoiKDTree{T,TT}
tree::T
references::TT
offset::Int64
end
function VoronoiKDTree(VG::VoronoiGeometry;restrict_to_periodic=true)
VD = VoronoiData(VG,reduce_to_periodic=false)
tree = NearestNeighbors.KDTree(VD.nodes)#.Integral.MESH.nodes)
ref = VD.references
off = restrict_to_periodic ? length(VD.references) : 0
return VoronoiKDTree{typeof(tree),typeof(ref)}(tree,ref,off)
end
function nn_id(vt::VoronoiKDTree,x)
return VoronoiDataShift(NearestNeighbors.nn(vt.tree,x)[1],vt.offset,vt.references)
end
function nn_id(tree::NearestNeighbors.KDTree,x)
return NearestNeighbors.nn(tree,x)[1]
end
function __StepFunction(u,tree,domain,BC,project)
if BC!=nothing
return x->x in domain ? u[nn_id(tree,x)] : BC(project ? project(x,domain) : x)
else
return x->u[nn_id(tree,x)]
end
end
function StepFunction(VG::VoronoiGeometry,u::AbstractVector; tree = VoronoiKDTree(VG),BC=nothing,project=false)
vd = VoronoiData(VG,reduce_to_periodic=false)
ln = length(vd.nodes)
if length(u)!=length(vd.nodes)-length(vd.references)#.references)
@warn "number of nodes $(ln-length(vd.references)) and length of u=$(length(u)) do not match, return empty function"
return x->Float64[]
end
return __StepFunction(u,tree,vd.boundary,BC,project)
end
function StepFunction(VG::VoronoiGeometry; tree = VoronoiKDTree(VG),BC=nothing,project=false)
_val = VoronoiData(VG).bulk_integral # data without references in front
if length(_val)>0
val = Vector{Vector{Float64}}(undef,length(_val))
for i in 1:(length(val))
val[i] = copy(_val[i])
end
return StepFunction(VG,val,tree=tree,BC=BC,project=project)
else
@warn "dimensions of nodes and stored bulkintegrals do not match, return empty function"
return x->Float64[]
end
end
function StepFunction(nodes::Points,u::AbstractVector; tree = KDTree(nodes),domain=Boundary(),BC=nothing,project=false)
#=if length(u)!=length(nodes)
@warn "dimensions of nodes and u do not match, return empty function"
return x->nothing
end=#
return __StepFunction(u,tree,domain,BC,project)
end
function StepFunction(VG::VoronoiGeometry, f::Function; tree = VoronoiKDTree(VG),BC=f, project=false)
_nodes = VoronoiData(VG).nodes
return StepFunction(VG,map(x->f(x),_nodes),tree=tree,BC=BC,project=project)
end
function DiameterFunction(VG::VoronoiGeometry; tree = VoronoiKDTree(VG))
return DiameterFunction(VoronoiData(VG,reduce_to_periodic=false), tree = tree)
end
@inline function InterfaceFunction(VD::VoronoiData,range=:all,symbol=nothing;scalar=true)
return InterfaceFunction(VD.geometry,range,symbol,scalar=scalar)
end
function InterfaceFunction(VG::VoronoiGeometry,range=:all,symbol=nothing;scalar=true)
#function InterfaceFunction(nodes::Points,values,neighbors,range,symbol=nothing;scalar=true, tree = KDTree(nodes))
vd = VoronoiData(VG,reduce_to_periodic=false)#,getinterface_integral=true) # want integral values as true duplicate so I can modify them without harm
dom = vd.boundary # internal_boundary of periodic domain
xs = vd.nodes
lxs = length(xs)
lb = length(dom)
boundary_range = collect((lxs+1):(lxs+lb))
lref = length(vd.references)
xtree = ExtendedTree(copy(xs),dom)#,VI_KD)
rc_ = MiniRaycast(xtree,dom)
activate_cell(rc_,1,boundary_range) # make sure that initial "boundary nodes" are outside the internal_boundary
function _if(_x, rc, lref, vd, boundary_range,_scalar,range)
ret(n,i,j,r,::StaticTrue) = view(n[i][j],r)[1]
ret(n,i,j,r,::StaticFalse) = copy(view(n[i][j],r))
x = _x
_next = nn(rc.tree, x)[1]
if _next <= lref
x -= vd.reference_shifts[_next]
_next = vd.references[_next]
end
activate_cell(rc, _next, boundary_range)
_next2 = nn(rc.tree, x, i -> i == _next)[1]
pos = findfirst(k -> k == _next2, vd.neighbors[_next])
return ret(vd.interface_integral,_next,pos,range,_scalar)
end
le = 0
if range==:all
range = 1:length(vd.interface_integral[end][1])
end
if typeof(range)<:UnitRange{Int} || typeof(range)<:AbstractArray{Int}
le = length(range)
elseif typeof(range)<:FunctionComposer
range, le = _data_length(range,symbol)
if le>1 || scalar==false
range = range:(range+le-1)
end
elseif typeof(range)<:Int
le = 1
if scalar==false
range = range:range
end
else
error("InterfaceFunction: `range` should be UnitRange, AbstractArray or FunctionComposer. Have a look at the manual for more information.")
end
_scalar = StaticBool(scalar && length(range)==1)
# Übergabe der Parameter an _if
return x -> _if(x, rc_, lref, vd, boundary_range,_scalar,range)
end
"""
FunctionFromData(args...)
comes in to variations:
FunctionFromData(vg::VoronoiGeometry,tree=VoronoiKDTree(vg),composer=nothing; function_generator)
generates a function
x->function_generator( data=VoronoiData(vg), composer=composer, _Cell=nearest_neighbor_of(x) )
from `vg`, `tree` and a function
function_generator(;data ,composer , _Cell )
which takes `data::VoronoiData` generated from `vg`, `composer` from above and `_Cell::Int` for
the number of the current node and returns a `Float64` or a `Vector{Float64}` or anything else
if you do not plan to hand it over to the routines of `HighVoronoi`.
You can access every entry of VoronoiData to generate the value you want to be associated with the
Voronoi cell belonging to `vd.nodes[_Cell]`.
FunctionFromData(vd::VoronoiData,tree::VoronoiKDTree,composer=nothing; function_generator)
basically does the same but takes a `vd::VoronoiData` and `tree` mandatorily and
passes `vd` to the `function_generator`.
"""
function FunctionFromData(vg::VoronoiGeometry,tree=VoronoiKDTree(vg),composer=nothing; function_generator)
return FunctionFromData(VoronoiData(vg),tree,composer,function_generator=function_generator)
end
function FunctionFromData(vd::VoronoiData,tree::VoronoiKDTree,composer=nothing; function_generator)
val1 = function_generator(data=vd,composer=composer,_Cell=1)
lmesh = length(vd.nodes)
u = Vector{typeof(val1)}(undef,lmesh)
u[1] = val1
for i = 2:lmesh
u[i] = function_generator(data=vd,composer=composer,_Cell=i)
end
return StepFunction(vd.nodes,u,tree=tree)
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 14682 | ############################################################################################################################
## The following are service for other parts....
############################################################################################################################
function periodic_shifts(boundary::Boundary,dim)
numberOfPlanes = length(boundary)
shifts=Vector{Vector{Float64}}(undef,numberOfPlanes)
for i in 1:numberOfPlanes
other=boundary.planes[i].BC # other>0 iff periodic BC and points to the other part of periodic plane
if other>0
normal=boundary.planes[i].normal
base=boundary.planes[i].base
shifts[i]=round.(dot(normal,boundary.planes[other].base .- base).*normal,digits=10)
else shifts[i]=zeros(Float64,dim)
end
end
return shifts
end
## return boundary nodes for a given discrete domain
#=function get_boundary_nodes!(_bn,nodes,domain,neighbors,onboundary)
lnodes=length(nodes)
for i in 1:(length(nodes))
if neighbors[i][end]>lnodes
k=length(neighbors[i])
em=EmptyDictOfType(1=>nodes[1])
while k>0 && neighbors[i][k]>lnodes
plane=neighbors[i][k]-lnodes
if onboundary
push!(em,neighbors[i][k]=>0.5*(nodes[i]+reflect(nodes[i],boundary(domain),plane)))
else
push!(em,neighbors[i][k]=>reflect(nodes[i],boundary(domain),plane))
end
k=k-1
end
push!(_bn,i=>em)
end
end
end=#
############################################################################################################################
##
############################################################################################################################
function add_virtual_points(domain::AD,new_xs::ReflectedNodes;search_settings::RP=RaycastParameter(Float64),do_refine=statictrue,kwargs...) where {AD<:AbstractDomain,RP<:RaycastParameter}
length(new_xs)==0 && return Int64[]
expand_internal_boundary(domain,new_xs)
prepend!(domain,new_xs)
#println(references(domain))
#println(reference_shifts(domain))
retrieve_reflections(domain,new_xs)
if do_refine==true
return systematic_refine!(mesh(domain),new_xs.data,internal_boundary(domain);settings=search_settings,kwargs...)
else
return Int64[]
end
end
function periodize_mirrors(domain::VD) where VD <: AbstractDomain
known_reflections = reflections(domain)
planes = boundary(domain).planes
mesh = HighVoronoi.mesh(domain)
reference_shifts = HighVoronoi.reference_shifts(domain)
lp = length(planes)
lrs = length(reference_shifts)
mirrors=Dict{Int64,Vector{Int64}}()
myshifts=BitVector(zeros(Int8,lp))
for k in (lrs+1):length(mesh)
myshifts .= false
neigh=neighbors_of_cell(k,mesh,adjacents=true)
for n in neigh
if n in 1:lrs
myshifts .|= reference_shifts[n]
end
end
b=true
for i in 1:lp
if myshifts[i] && !known_reflections[k-lrs][planes[i].BC]
b=false
break
end
end
b && (myshifts.=false)
number_of_shifts=sum(myshifts)
if number_of_shifts>0
list=zeros(Int64,number_of_shifts)
count=0
for i in 1:lp
if myshifts[i]
count+=1
list[count]=planes[i].BC
end
end
push!(mirrors,k=>list)
end
end
return mirrors
end
function _good_vertex(sig,r,modified_planes,modified,lref,max)
track = false
#=if sig==[5, 192, 193, 196, 197, 199] || sig == [ 29, 31, 75, 191, 194, 198]
println("hier!! $modified_planes, $r")
track = true
end=#
for s in sig
if s in modified_planes
for s2 in sig
s2>lref && s2<=max && (modified[s2-lref] = true)
end
return false
end
end
return true
end
function retrieve_reflections( domain::AD,new_xs::ReflectedNodes) where {AD<:AbstractDomain}
references = HighVoronoi.references(domain)
lref = length(references)
bv = reflections(domain)
reference_shifts = HighVoronoi.reference_shifts(domain)
iterate=1:(length(new_xs))
for k in iterate
bv[references[k]-lref] .|= reference_shifts[k]
end
return bv
end
function periodize!(domain::VD,sr_offset=0;returnitems=staticfalse,iter=Int64[],search_settings=RaycastParameter(Float64)) where VD<:AbstractDomain
#known_reflections = retrieve_reflections(domain)
for _ in 1:2
lref = internaly_precise(domain) ? 0 : length(references(domain))
mesh = HighVoronoi.mesh(domain)
lint = length(mesh)
new_xs = reflect_nodes(domain,periodize_mirrors(domain))
modified_planes = expand_internal_boundary(domain,new_xs) # shifts the periodic part of the boundary such that new_xs lies completely inside the
modified_planes .+= lint
modified = falses(lint-lref)
filter!((sig,r)->_good_vertex(sig,r,modified_planes,modified,lref,lint),mesh)#,affected=1:length(domain.references))
obligatories2 = findall(modified)
#append!(iter,add_virtual_points(domain,new_xs,intro="",subroutine_offset=sr_offset, obligatories = obligatories2 ))
#println("periodize:")
new_iter = add_virtual_points(domain,new_xs,intro="Include $(length(new_xs)) new nodes",subroutine_offset=sr_offset, obligatories = obligatories2, search_settings=search_settings )
if returnitems==true
append!(iter,new_iter)
end
vp_print(sr_offset,"$(length(new_xs)) new nodes included in grid ")
println("")
end
if returnitems==true
return sort!(unique!(iter))
else
return nothing
end
end
## main routine to set up the discrete domain
function Create_Discrete_Domain(mesh,_boundary::Boundary; offset=0,intro="Adjusting mesh to boundary conditions...",search_settings=RaycastParameter(Float64))
c_offset=offset+BC_offset
vp_print(offset,intro)
vp_line()
boundary=_boundary
# mesh = HighVoronoi.mesh(Integral)
#println("first here: ",verify_mesh(mesh,_boundary))
#println(typeof(mesh))
domain = Domain(mesh,boundary)
periodic_bc=false
for i in 1:length(boundary.planes)
if boundary.planes[i].BC>0
periodic_bc=true
end
end
if periodic_bc
vp_print(c_offset,"Calculating nodes on periodic boundary part: ",c_offset+45,"...")
# reflect the boundary nodes according to boundary_cells
PN = periodic_nodes(mesh,boundary)
#println(PN)
new_xs = reflect_nodes(domain,PN)
vp_print(c_offset+45," $(length(new_xs)) new nodes to be included... ")
vp_line()
iter_BC = remove_periodic_BC_verteces!(mesh,boundary)
#println(iter_BC)
add_virtual_points(domain,new_xs,search_settings=search_settings, subroutine_offset=c_offset,obligatories=iter_BC)
#return
#systematic_refine!(Integral,new_xs,internal_boundary(domain),settings=search_settings, subroutine_offset=c_offset,obligatories=iter_BC)
periodize!(domain,c_offset,search_settings=search_settings)
else
println("No periodic boundaries....")
end
return domain
end
#####################################################################################################################################
## Manage boundary verteces
#####################################################################################################################################
# removes all verteces that lie on one of the periodic boundaries
function remove_periodic_BC_verteces!(mesh::AM,boundary::Boundary) where {AM<:AbstractMesh}
lm=length(mesh)
lb=length(boundary)
count=0
modified = BitVector(zeros(Int8,length(mesh)))
for i in 1:lb
count+=boundary.planes[i].BC>0 ? 1 : 0
end
global_list=zeros(Int64,count)
count=0
for i in 1:lb
if boundary.planes[i].BC>0
count+=1
global_list[count]=i+lm
end
end
function condition(sig,r)
for k in (length(sig)):-1:1
if (sig[k] in global_list)
for i in 1:k
sig[i]<=lm && (modified[sig[i]] = true)
end
sig[1]=0
break
elseif sig[k]<=lm
break
end
end
return sig[1]!=0
end
filter!(condition,mesh)
return keepat!(collect(1:lm),modified)
end
# returns a Dict(0=>[1]) that contains for every node all adjacent periodic boundaries
function periodic_nodes(mesh::AM,boundary::Boundary) where {AM<:AbstractMesh}
lm=length(mesh)
lb=length(boundary)
mirrors=EmptyDictOfType(0=>[1])
periodic_boundary=BitVector(zeros(Int8,lb))
for i in 1:lb
periodic_boundary[i]=boundary.planes[i].BC>0
end
this_boundary=BitVector(zeros(Int8,lb))
for i in 1:lm
this_boundary .= false
for (sig,r) in vertices_iterator(mesh,i)
for k in (length(sig)):-1:1
if sig[k]>lm
this_boundary[sig[k]-lm]=true
else
break
end
end
end
this_boundary .&= periodic_boundary # only periodic boundaries are of interest
list=zeros(Int64,sum(this_boundary))
count=1
for k in 1:lb
if this_boundary[k]
list[count]=k
count+=1
end
end
push!(mirrors, i=>list)
end
return mirrors
end
# Takes the BitVector reference_shifts to calculate a shift based on the vectorlist "shifts" """
function periodic_shift(reference_shifts,shifts)
result=zeros(Float64,length(shifts[1]))
for i in 1:length(reference_shifts)
if !reference_shifts[i] continue end
result.+=shifts[i]
end
return result
end
#####################################################################################################################################
## Reflecting Methods for points at boundaries
#####################################################################################################################################
# uses an iteration algorithm to calculate for each node all shifted versions according to reference_shifts """
function iteratively_reflected_points!(new_xs,reference,reference_shifts,current_shift,_count,shifts,planes,original_node,list,start_plane,taboo,node_index)
count=_count
#print("N->")
if start_plane<=length(planes)
for current_plane in start_plane:length(planes)
(taboo[current_plane] || !(current_plane in list)) && continue
other=planes[current_plane].BC
if other>0
taboo[other] = true
current_shift[current_plane] = true
count = iteratively_reflected_points!(new_xs,reference,reference_shifts,current_shift,count,shifts,planes,original_node,list,current_plane+1,taboo,node_index)
current_shift[current_plane] = false
taboo[other] = false
end
end
end
if start_plane>1
reference_shifts[count] = copy(current_shift)
reference[count] = node_index
shift = periodic_shift(reference_shifts[count],shifts)
new_xs[count] = original_node+shift
count += 1
end
return count
end
"""
returns a ReflectedNodes(new_xs,reference,reference_shifts), where `reference` is list of reference nodes in external representation.
"""
function reflect_nodes(domain::AD,mirrors) where AD<:AbstractDomain
numberOfNewNodes = 0
nodes = HighVoronoi.nodes(mesh(domain))
numberOfPlanes = length(boundary(domain))
shifts = HighVoronoi.shifts(domain)
for (_,sig) in mirrors
numberOfNewNodes+=(2^length(sig))-1 # this is the number of new nodes that the point _ generates
end
# println("Maximally $numberOfNewNodes new nodes will be created")
# collect in new_xs all new points
new_xs = Vector{eltype(nodes)}(undef,numberOfNewNodes)
reference = Vector{Int64}(undef,numberOfNewNodes)
reference_shifts = Vector{BitVector}(undef,numberOfNewNodes)
count=1
# Take care!: In boundary_cells[...] and in mirrors, k=1....length(xs) refer to "old points",
# while k=length(xs+1),..... refer to newly created points
taboo = BitVector(falses(numberOfPlanes))
current_shift = BitVector(falses(numberOfPlanes))
for (k,list) in mirrors
taboo .= false
current_shift .= false
#c_old=count
count = iteratively_reflected_points!(new_xs,reference,reference_shifts,current_shift,count,shifts,boundary(domain).planes, nodes[k],list,1,taboo,k)
end
resize!(new_xs,count-1)
resize!(reference,count-1)
resize!(reference_shifts,count-1)
if length(references(domain))>0
keeps = BitVector(ones(Int8,length(reference)))
oldrefs = references(domain)
l_oldrefs = length(oldrefs)
oldshifts = HighVoronoi.reference_shifts(domain)
for i in 1:length(reference)
pos=1
while pos<=l_oldrefs
while pos<=l_oldrefs && oldrefs[pos]!=reference[i]
pos += 1
end
if pos<=l_oldrefs && oldrefs[pos]==reference[i] && oldshifts[pos]==reference_shifts[i]
pos=0
break
end
pos += 1
end
keeps[i] = pos>0
end
keepat!(new_xs,keeps)
keepat!(reference,keeps)
keepat!(reference_shifts,keeps)
end
return ReflectedNodes(new_xs,reference,reference_shifts)
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 1565 |
function systematic_refine!(domain::AD,_new_xs::Points;intro="Refine discrete domain with $(length(_new_xs)) points",offset=0,short_log=true,search_settings=()) where AD<:AbstractDomain
vp_print(offset,intro)
vp_line()
sr_offset = offset+4
lnxs = length(_new_xs)
old_length = length(mesh(domain))
extended_boundary = internal_boundary(domain)# extend_periodic_part(domain.boundary,Integral.MESH.nodes[1:(length(domain.references))])
MESH = append!(domain,_new_xs)
iter = systematic_refine!(MESH,_new_xs,extended_boundary,intro="refine with $(length(_new_xs)) points: ",subroutine_offset=sr_offset)
#_internal_indeces(MESH,iter) ### `iter` already IS in INTERNAL representation!!!
#sort!(iter)
iter = periodize!(domain,sr_offset,iter =iter, returnitems=statictrue)
#return iter
return iter #_my_modified_cells(Integrator.Integral.MESH,old_length,old_references,length(domain.references),length(_new_xs))
end
## seemingly the following is no longer needed
#=function repair_periodic_structure!(domain,Integral,iter,sr_offset=0)
known_reflections = retrieve_reflections(domain,Integral)
lref1 = length( domain.references )
iter2=periodize!(domain,Integral,known_reflections,sr_offset)
lref2 = length(domain.references)
iter .+= lref2-lref1
append!(iter,iter2)
iter2=periodize!(domain,Integral,known_reflections,sr_offset)
lref3 = length( domain.references )
iter .+= lref3-lref2
append!(iter,iter2)
sort!(iter)
unique!(iter)
end
=# | HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 25607 |
struct Board2D{F1<:Function,F2<:Function,F3<:Function,F4<:Function}
_board::Boundary
draw_nodes::F1
draw_vertices::F2
draw_edges::F3
d_line::F4
end
"""
draw2D(VG::VoronoiGeometry, filename=""; board=PlotBoard(), drawNodes=true, drawVerteces=true, drawEdges=true)
Generates MetaPost of VG output in the file with name filename for a two-dimensional VoronoiGeometry.
- `board` : The `PlotBoard` or `MetaPostBoard` to be used.
- `drawNodes` : Set this value to "false" in order to not show the nodes in the output
- `drawVerteces` : Set this value to "false" in order to not show the verteces in the output
- `drawEdges` : Set this value to "false" in order to not show the edges in the output
"""
function draw2D(VG::VoronoiGeometry, filename=""; public_only=true, board=PlotBoard(board = boundary(VG.domain)), drawNodes=true, drawVerteces=true, drawEdges=true)
if filename=="" && typeof(board)!=PlotBoard
println("MetaPost makes only sense when filename is provided...")
return
end
my_boundary = boundary(VG.domain)
board_boundary = public_only ? boundary(VG.domain) : internal_boundary(VG.domain)
kwargs = (domain=my_boundary,draw_nodes=drawNodes,draw_verteces=drawVerteces,draw_edges=drawEdges)
Integral = integrate_view(VG.domain).integral
if filename!="" && typeof(board)<:MetaPostBoard
open(filename,"w") do f
draw2D(Integral,board=my_board(board,f,board_boundary);kwargs...)
end
elseif typeof(board)<:MetaPostBoard
draw2D(Integral,board=my_board(board,stdio,board_boundary);kwargs...)
else
my_plot = plot(legend = false, aspect_ratio = 1)
draw2D(Integral,board=my_board(board,board_boundary);kwargs...)
if filename!=""
try
savefig(filename)
catch
@warn "writing to file failed. Maybe use other backend for Plots."
end
end
display(my_plot)
end
end
"""
draw2D(Integral::Voronoi_Integral, filename::String; domain=nothing, board=PlotBoard(), drawNodes=true, drawVerteces=true, drawEdges=true)
Almost the same as for a `VoronoiGeometry`. It has one additional parameter:
- `domain`: A domain of type `Boundary` can be passed here. This will be shown in the color specified by `domain_color`.
"""
function draw2D(Integral::HVI; domain=nothing, board, draw_nodes=true, draw_verteces=true, draw_edges=true) where HVI<:HVIntegral
if dimension(Integral)>2
println("dimension of Integral to large to be plottet in 2D")
return
end
if draw_nodes draw_nodes_2D(Integral,board) end
if draw_edges draw_edges_2D(Integral,board) end
if draw_verteces draw_verteces_2D(Integral,board) end
draw_Boundary_2D(domain,board)
end
############################################################################################################################
## MetapostBoard
############################################################################################################################
"""
MetaPostBoard
Provides a board to display a two-dimensional `VoronoiGeometry` in MetaPost text format using draw2D.
"""
struct MetaPostBoard
n_size
v_size
scale
n_color::String
v_color::String
e_color::String
d_color::String
_board
end
function my_board(board::MetaPostBoard,f,boundary)
n = p->write(f,metapost_cross(p[1],p[2],color=board.n_color,scale=board.scale,size=board.n_size))
v = p->write(f,metapost_cross(p[1],p[2],color=board.v_color,scale=board.scale,size=board.v_size))
e = (r1,r2)->write(f,metapost_line(r1[1],r1[2],r2[1],r2[2],color=board.e_color,scale=board.scale))
d = (x1,x2)->write(f,metapost_line(x1[1],x1[2],x2[1],x2[2],scale=board.scale,color=board.d_color))
return Board2D(boundary,n,v,e,d)
end
"""
The constructor
MetaPostBoard()
Generates a MetapostBoard where the following `<:Real`-type arguments may be passed (=standard value)
- `scaling=100`: denotes a factor by which every object is magnified (also applies to the coordinates of points)
- `node_size=0.01`: nodes are drawn as a cross. This variable is the size of a cross BEFORE scaling
- `vertex_size=0.003`: same for verteces
Additionally, the following colors may be passed as a `<:String`. note that an empty string implies the usage of the MetaPost standard pen color.
- `nodes_color=""`: the color at which nodes are draw. Empty string implies standard color (typically black)
- `vertex_color="red"`: color verteces
- `edge_color="blue"`: color of edges
- `domain_color=""`: color the domain, in case a `domain` argument is passed to the `draw2D`-function. Also it displays the domain that was passed to a `VoronoiGeometry` during instatiation
- board::Boundary: provides a board: every node or vertex outside this board is not drawn
"""
function MetaPostBoard(;node_size=0.01, vertex_size=0.003, scaling=100, nodes_color="", vertex_color="red", edge_color="blue", domain_color="", board=cuboid(2,dimensions=3*ones(Float64,2),offset=-0.5*ones(Float64,2)))
return MetaPostBoard(node_size,vertex_size,scaling,nodes_color,vertex_color,edge_color,domain_color,board)
end
# For developping and testing. Only reactivate for that purpose!
#=function draw2D(Integral::Voronoi_Integral, D, filename::String; domain=nothing, board=MetaPostBoard(), draw_nodes=true, draw_verteces=true, draw_edges=true)
if dimension(Integral)>2 error("dimension of Integral to large to be plottet in 2D") end
open(filename,"w") do f
if typeof(domain)!=Nothing draw_Boundary_2D(domain,f,board,color=board.d_color)
else println("No domain provided...") end
if draw_nodes draw_nodes_2D(Integral,f,board) end
if draw_edges draw_edges_2D(Integral,f,board) end
if draw_verteces draw_verteces_2D(Integral,f,board) end
for (_,r) in D
write(f,metapost_cross(r[1],r[2],color="green",scale=board.scale,size=board.v_size))
end
end
end=#
function metapost_line(x1,y1,x2,y2;color="",scale=100)
s=""
if length(color)>0 s*=" withcolor $color; \n"
else s*="; \n" end
return "draw ($(scale*x1),$(scale*y1))--($(scale*x2),$(scale*y2))$s"
end
function metapost_cross(x1,y1;color="",scale=100,size=0.02)
return metapost_line(x1-size,y1,x1+size,y1,color=color,scale=scale)*metapost_line(x1,y1-size,x1,y1+size,color=color,scale=scale)
end
function draw_Boundary_2D(domain,board)
edges=edge_representation2D(domain)
while !isempty(edges)
(_,(x1,x2))=pop!(edges)
board.d_line(x1,x2)
end
end
function draw_nodes_2D(Integral::HVI,board,max_range=length(mesh(Integral))) where HVI<:HVIntegral
nod = nodes(mesh(Integral))
for i in 1:max_range #Integral.MESH.nodes
p = nod[i]
!(p in board._board) && continue # if p lies outside the domain _board it will not be shown
board.draw_nodes(p)
end
end
#=function draw_nodes_2D(nodes::Points,f,board::MetaPostBoard,withcolor="green")
for p in nodes
!(p in board._board) && continue # if p lies outside the domain _board it will not be shown
write(f,metapost_cross(p[1],p[2],color=withcolor,scale=board.scale,size=board.n_size))
end
end=#
function draw_verteces_2D(Integral,board,max_range=length(mesh(Integral)))
MESH = mesh(Integral)
for i in 1:max_range
V=vertices_iterator(MESH,i)
for (sig,p) in V
sig[1]!=i && continue
!(p in board._board) && continue
board.draw_vertices(p)
end
end
end
function draw_edges_2D(Integral::HVI,board) where {P,HVI<:HVIntegral{P}}
emptylist=Dict{Vector{Int64},P}()
MESH = mesh(Integral)
dd=Vector{typeof(emptylist)}(undef,1)
dd[1]=copy(emptylist)
for i in 1:(length(MESH))
_Cell=i
neigh=neighbors_of_cell(i,MESH)
_length=length(neigh)
while length(neigh)>length(dd) push!(dd,copy(emptylist)) end
for (sig,r) in vertices_iterator(MESH,i)#Iterators.flatten((verteces,verteces2)) # iterate over all verteces
for _neigh in sig # iterate over neighbors in vertex
_neigh<=_Cell && continue
index = _neigh_index(neigh,_neigh)
index!=0 && (push!( dd[index] , sig =>r)) # push vertex to the corresponding list
end
end
for k in 1:_length
neigh[k]<=_Cell && continue
s1,r1=pop!(dd[k])
if !isempty(dd[k])
s2,r2=pop!(dd[k])
if !(r1 in board._board)
r1,r2 = r2,r1
end
if !(r1 in board._board)
direction = r2-r1
if intersection_exists(board._board,r1,direction) && intersection_exists(board._board,r2,-direction)
_r1 = intersect_point(board._board,r1,direction)
_r2 = intersect_point(board._board,r2,-direction)
board.draw_edges(_r1,_r2)
end
elseif r2 in board._board
board.draw_edges(r1,r2)
else
direction = r2-r1
board.draw_edges(r1,intersect_point(board._board,r1,direction))
end
end
while !isempty(dd[k]) pop!(dd[k]) end
end
end
end
###############################################################################################################################
## PlotBoard
###############################################################################################################################
"""
PlotBoard
Provides a board to display a two-dimensional `VoronoiGeometry` in the Julia `Plots` format using `draw2D` or `draw3D`.
"""
struct PlotBoard
n_size
v_size
scale
n_color::Symbol
v_color::Symbol
e_color::Symbol
d_color::Symbol
_board
end
function my_board(board::PlotBoard,boundary)
n = p->plot_cross(p[1],p[2],color=board.n_color,scale=board.scale,size=board.n_size)
v = p->plot_cross(p[1],p[2],color=board.v_color,scale=board.scale,size=board.v_size)
e = (r1,r2)->plot_line(r1[1],r1[2],r2[1],r2[2],color=board.e_color,scale=board.scale)
d = (r1,r2)->plot_line(r1[1],r1[2],r2[1],r2[2],color=board.d_color,scale=board.scale)
return Board2D(boundary,n,v,e,d)
end
"""
The constructor
PlotBoard()
Generates a MetapostBoard where the following `<:Real`-type arguments may be passed (=standard value)
- `scaling=1`: The width argument for lines in plot. Only for compatibility with MetapostBoard
- `node_size=0.01`: nodes are drawn as a cross. This variable is the size of a cross
- `vertex_size=0.003`: same for vertices
Additionally, the following colors may be passed as a `Symbol`.
- `nodes_color=:black`: the color at which nodes are draw.
- `vertex_color=:red`: color verteces
- `edge_color=:blue`: color of edges
- `domain_color=:black`: color the domain, in case a `domain` argument is passed to the `draw2D`-function. Also it displays the domain that was passed to a `VoronoiGeometry` during instatiation
- board::Boundary: provides a board: every node or vertex outside this board is not drawn
"""
function PlotBoard(;node_size=0.01, vertex_size=0.003, scaling=1, nodes_color=:black, vertex_color=:red, edge_color=:blue, domain_color=:black, board=cuboid(2,dimensions=3*ones(Float64,2),offset=-0.5*ones(Float64,2)))
return PlotBoard(node_size,vertex_size,scaling,nodes_color,vertex_color,edge_color,domain_color,board)
end
function plot_line(x1,y1,x2,y2;color=:black,scale=1)
plot!([x1, x2], [y1, y2], seriestype = :line, line = (color, scale))
end
function plot_cross(x1,y1;color=:black,scale=1,size=0.02)
plot_line(x1-size,y1,x1+size,y1,color=color,scale=scale)
plot_line(x1,y1-size,x1,y1+size,color=color,scale=scale)
end
#########################################################################################
# 3d
#########################################################################################
function draw3D(VG::VoronoiGeometry, filename=""; board=PlotBoard(board=boundary(VG.domain)), drawNodes=true, drawVerteces=true, drawEdges=true)
draw3D(integral(VG.domain),filename,domain=boundary(VG.domain),draw_nodes=drawNodes,draw_verteces=drawVerteces,draw_edges=drawEdges, board=board)
end
"""
draw3D(Integral::Voronoi_Integral, filename::String; domain=nothing, board=MetaPostBoard(), drawNodes=true, drawVerteces=true, drawEdges=true)
Writes MetaPost code for the internal type Voronoi_Integral, which may be assessed via `VoronoiGeometry.Integrator.Integral`. It has one additional parameter:
- `domain`: A domain of type `Boundary` can be passed here. This will be shown in the color specified by `domain_color`.
"""
function draw3D(Integral::HVI, filename::String; domain=nothing, board=PlotBoard(), draw_nodes=true, draw_verteces=true, draw_edges=true) where HVI<:HVIntegral
if dimension(Integral)!=3 error("dimension of Integral should be 3, is $(dimension(Integral))") end
if typeof(board)==PlotBoard
my_plot = plot(legend = false, aspect_ratio = 1)
f = 0
if draw_nodes draw_nodes_3D(Integral,f,board) end
if draw_edges draw_edges_3D(Integral,f,board) end
if draw_verteces draw_verteces_3D(Integral,f,board) end
if filename!=""
try
savefig(filename)
catch
@warn "writing to file failed. Maybe use other backend for Plots"
end
end
display(my_plot)
else
error("works only with a PlotBoard")
end
end
function plot_line(x1,y1,z1,x2,y2,z2;color=:black,scale=1)
plot!([x1, x2], [y1, y2], [z1,z2], seriestype = :line, line = (color, scale))
end
function plot_cross(x1,y1,z1;color=:black,scale=1,size=0.02)
plot_line(x1-size,y1,z1,x1+size,y1,z1,color=color,scale=scale)
plot_line(x1,y1-size,z1,x1,y1+size,z1,color=color,scale=scale)
plot_line(x1,y1,z1-size,x1,y1,z1+size,color=color,scale=scale)
end
#=function draw_Boundary_2D(domain,f,board::PlotBoard;color=:black)
edges=edge_representation2D(domain)
while !isempty(edges)
(_,(x1,x2))=pop!(edges)
plot_line(x1[1],x1[2],x2[1],x2[2],scale=board.scale,color=color)
end
end=#
function draw_nodes_3D(Integral,f,board::PlotBoard)
for p in nodes(mesh(Integral))
!(p in board._board) && continue # if p lies outside the domain _board it will not be shown
plot_cross(p[1],p[2],p[3],color=board.n_color,scale=board.scale,size=board.n_size)
end
end
function draw_verteces_3D(Integral,f,board::PlotBoard)
MESH = mesh(Integral)
for i in 1:length(MESH)
V=vertices_iterator(MESH,i)
for (sig,p) in V
sig[1]!=i && continue
!(p in board._board) && continue
plot_cross(p[1],p[2],p[3],color=board.v_color,scale=board.scale,size=board.v_size)
end
end
end
function draw_edges_3D(Integral,f,board::PlotBoard)
MESH = mesh(Integral)
nodes = HighVoronoi.nodes(MESH)
for _Cell in 1:length(nodes)
draw_edges_3D_cell(Integral,_Cell,neighbors_of_cell(_Cell,MESH),board.e_color)
end
end
function draw_edges_3D_cell(Integral::HVI,_Cell,neighbors,color) where {P,HVI<:HVIntegral{P}}
MESH = mesh(Integral)
nodes = HighVoronoi.nodes(MESH)
dim = dimension(Integral)
# get all neighbors of this current cell
neigh=neighbors
_length=length(neigh)
verteces = vertices_iterator(MESH,_Cell)
# flexible data structure to store the sublists of verteces at each iteration step 1...dim-1
emptydict=Dict{Vector{Int64},P}() # empty buffer-list to create copies from
listarray=(typeof(emptydict))[] # will store to each remaining neighbor N a sublist of verteces
# which are shared with N
all_dd=(typeof(listarray))[]
for _ in 1:dim-1 push!(all_dd,copy(listarray)) end
# do the integration
taboo = zeros(Int64,dim)
iterative_3D_edge( _Cell, dim, dim, neigh,
_length,verteces,emptydict,emptydict,all_dd,taboo,color)
end
function iterative_3D_edge(_Cell, dim, space_dim, neigh, _length,verteces,verteces2,emptylist,all_dd,taboo,color)
if (dim==1) # this is the case if and only if we arrived at an edge
if length(verteces)>1
_,r = pop!(verteces)
_,r2 = pop!(verteces)
empty!(verteces)
plot_line(r[1],r[2],r[3],r2[1],r2[2],r2[3],color=color)
end
elseif dim==space_dim
dd=Vector{typeof(emptylist)}(undef,_length)
for i in 1:_length dd[i]=copy(emptylist) end
for (sig,r) in verteces # iterate over all verteces
for _neigh in sig # iterate over neighbors in vertex
_neigh==_Cell && continue
index=_neigh_index(neigh,_neigh)
index==0 && continue
push!( dd[index] , sig =>r) # push vertex to the corresponding list
end
end
#=for (sig,r) in verteces2 # repeat in case verteces2 is not empty
for _neigh in sig
_neigh==_Cell && continue
index=_neigh_index(neigh,_neigh)
index==0 && continue
if (_neigh>_Cell || isempty(dd[index])) # make sure for every neighbor the dd-list is not empty
push!( dd[index] , sig =>r) # push vertex to the corresponding list
end
end
end=#
taboo[dim]=_Cell
for k in 1:_length
buffer=neigh[k] # this is the (further) common node of all verteces of the next iteration
bufferlist=dd[k]
isempty(bufferlist) && continue
taboo[dim-1] = buffer
neigh[k]=0
if buffer>_Cell # in this case the interface (_Cell,buffer) has not yet been investigated
iterative_3D_edge(_Cell, dim-1, space_dim, neigh, _length,bufferlist,emptylist,emptylist,all_dd,taboo,color)
neigh[k]=buffer
else
empty!(bufferlist)
end
end
else
_count=1
for k in 1:_length
_count+=neigh[k]!=0 ? 1 : 0 # only if neigh[k] has not been treated earlier in the loop
end
_my_neigh=Vector{Int64}(undef,_count-1)
dd=all_dd[dim-1] # dd will store to each remaining neighbor N a sublist of verteces which are shared with N
while length(dd)<_count push!(dd,copy(emptylist)) end
_count=1
for k in 1:_length
if (neigh[k]!=0) # only if neigh[k] has not been treated earlier in the loop
_my_neigh[_count]=neigh[k]
_count+=1
end
end
ll=(length(verteces))
for _ii in 1:(ll) # iterate over all verteces
(sig,r) = _ii==ll ? first(verteces) : pop!(verteces)
count = 0
for _neigh in sig # iterate over neighbors in vertex
( _neigh in taboo) && continue # if _N is a valid neighbor (i.e. has not been treated in earlier recursion)
index = _neigh_index(_my_neigh,_neigh)
(index==0 || count==dim) && continue
push!( dd[index] , sig =>r) # push vertex to the corresponding list
end
end
_count=1
for k in 1:_length
buffer=neigh[k] # this is the (further) common node of all verteces of the next iteration
buffer==0 && continue
bufferlist=dd[_count]
_count+=1
isempty(bufferlist) && continue
neigh[k]=0
taboo[dim-1]=buffer
iterative_3D_edge(_Cell, dim-1, space_dim, neigh, _length,bufferlist,emptylist,emptylist,all_dd,taboo,color)
neigh[k]=buffer
taboo[dim-1]=0
if !isempty(bufferlist) empty!(bufferlist) end
end
end
end
#= emptylist=EmptyDictOfType([0]=>Integral.MESH.nodes[1])
dd=Vector{typeof(emptylist)}(undef,1)
dd[1]=copy(emptylist)
All_Verteces=Integral.MESH.All_Verteces
Buffer_Verteces=Integral.MESH.Buffer_Verteces
for i in 1:(length(Integral))
_Cell=i
neigh=neighbors_of_cell(i,Integral.MESH)
_length=length(neigh)
while length(neigh)>length(dd) push!(dd,copy(emptylist)) end
verteces=All_Verteces[i]
verteces2=Buffer_Verteces[i]
for (sig,r) in Iterators.flatten((verteces,verteces2)) # iterate over all verteces
for _neigh in sig # iterate over neighbors in vertex
#_neigh<=_Cell && continue
index = _neigh_index(neigh,_neigh)
index!=0 && (push!( dd[index] , sig =>r)) # push vertex to the corresponding list
end
end
for k in 1:_length
#neigh[k]<=_Cell && continue
s1,r1=pop!(dd[k])
if !isempty(dd[k]) #&& r1 in board._board
s2,r2=pop!(dd[k])
r2 in board._board && plot_line(r1[1],r1[2],r1[3],r2[1],r2[2],r2[3],color=board.e_color,scale=board.scale)
end
while !isempty(dd[k]) pop!(dd[k]) end
end
end
end
=#
# For developing and testing
#=
function check_2d(mesh::Voronoi_MESH)
for i in 1:length(mesh)
neigh=neighbors_of_cell(i,mesh.All_Verteces[i],mesh.Buffer_Verteces[i])
count=0
for (sig,r) in mesh.All_Verteces[i]
count+=1
end
for (sig,r) in mesh.Buffer_Verteces[i]
count+=1
end
if count!=length(neigh) println("error in $i: $(mesh.nodes[i]) , $count<>$(length(neigh))") end
end
end=#
#=
struct Draw2DLine
p1
p2
end
struct Draw2dPlotsBoard
whiteboard
scale
end
struct Draw2DCell
_Cell
verteces
end
struct Draw2DCells
All_Verteces
Buffer_Verteces
end
struct Draw2DVerteces
All_Verteces
end
function Draw2DMesh(mesh;edges=true,nodes=true,verteces=true,edgecolor=nothing,nodecolor=nothing,vertexcolor=nothing)
a=()
if edges
a = (a...,(Draw2DCells(mesh.All_Verteces,mesh.Buffer_Verteces),edgecolor))
end
if nodes
a = (a...,(mesh.nodes,nodecolor))
end
if verteces
a = (a...,(Draw2DVerteces(mesh.All_Verteces),vertexcolor))
end
return a
end
function plot_point!(B::Draw2dPlotsBoard, x, y, color=nothing)
color==nothing && (color=(0,0,0))
s=B.scale
plot!(B.whiteboard, x + s*cos.(0:0.01:2π), y + s*sin.(0:0.01:2π), fill=true, color=color)
end
function plot_line!(B::Draw2dPlotsBoard, x1, y1, x2, y2, color=nothing)
color==nothing && (color=(0,0,0))
plot!(B.whiteboard, [x1, x2], [y1, y2], color=color)
end
function Draw2D(whiteboard, args...)
emptylist=EmptyDictOfType([0]=>Integral.MESH.nodes[1])
dd=Vector{typeof(emptylist)}(undef,1)
dd[1]=copy(emptylist)
for e in args
obj = (length(e) > 1) ? e[1] : e
col = (length(e) > 1) ? e[2] : nothing
if typeof(obj)<:Point
plot_point!(B, obj[1], obj[2], col)
elseif typeof(obj)==Draw2DLine
plot_line!(B, obj.p1[1], obj.p1[2], obj.p2[1], obj.p2[2], col)
elseif typeof(obj)<:Points
for i in 1:length(obj)
plot_point!(B, obj[i][1], obj[i][2], col)
end
elseif typeof(obj)==Drwa2DCell
plot_cell!(B,obj._Cell,obj.verteces,dd,emptylist,col)
elseif typeof(obj)==Drwa2DCells
for i in 1:length(obj.All_Verteces)
plot_cell!(B,i,Iterators.flatten((obj.All_Verteces[i],obj.Buffer_Verteces[i])),dd,emptylist,col)
end
elseif typeof(obj)==Boundary
edges=edge_representation2D(obj)
while !isempty(edges)
(_,(x1,x2))=pop!(edges)
plot_line!(B, x1[1],x1[2],x2[1],x2[2], col)
end
elseif typeof(obj)==Draw2DVerteces
for i in 1:length(obj.Verteces)
for (_,r) in obj.Verteces[i]
plot_point!(B, r[1], r[2], col)
end
end
end
end
end
function plot_cell!(B,_Cell,verteces,dd,emptylist,col)
neigh = _old_neighbors_of_cell(_Cell,verteces)
_length = length(neigh)
while length(neigh)>length(dd) push!(dd,copy(emptylist)) end
for (sig,r) in verteces # iterate over all verteces
for _neigh in sig # iterate over neighbors in vertex
_neigh==_Cell && continue
index = _neigh_index(neigh,_neigh)
index!=0 && (push!( dd[index] , sig =>r)) # push vertex to the corresponding list
end
end
for k in 1:_length
neigh[k]==_Cell && continue
s1,r1=pop!(dd[k])
if !isempty(dd[k]) && r1 in board._board
s2,r2=pop!(dd[k])
r2 in board._board && plot_line!(B, r1[1], r1[2], r2[1], r2[2], col)
end
while !isempty(dd[k]) pop!(dd[k]) end
end
end
=# | HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 14168 | #following code is for using this file individually or testing
#=
@inline FNV_OFFSET_BASIS(::Type{UInt64}) = UInt64(14695981039346656037)
@inline FNV_PRIME(::Type{UInt64}) = UInt64(1099511628211)
@inline FNV_OFFSET_BASIS(::Type{UInt128}) = UInt128(144066263297769815596495629667062367629)
@inline FNV_PRIME(::Type{UInt128}) = UInt128(309485009821345068724781371)
# FNV-1a hash function
function fnv1a_hash(vec::VI,::Type{T}) where {T,VI<:AbstractVector{Int}}
hash = FNV_OFFSET_BASIS(T)
for value in vec
# XOR the bottom with the current octet
hash = xor(hash, UInt64(value))
# Multiply by the 64-bit FNV magic prime mod 2^64
hash *= FNV_PRIME(T) #& 0xFFFFFFFFFFFFFFFF
end
return hash
end
using StaticArrays
=#
next_power_of_two(n::Int64) = next_power_of_two(reinterpret(UInt64,n))
function next_power_of_two(n::UInt64)
if n == 0
return UInt64(1)
end
n -= 1
n |= n >> 1
n |= n >> 2
n |= n >> 4
n |= n >> 8
n |= n >> 16
n |= n >> 32
return n + 1
end
struct HashedEdge
value::UInt128
value2::UInt64
cell1::Int64
cell2::Int64
end
@inline HashedEdge() = HashedEdge(0,0,0,0)
# Definition der mutable EdgeHashTable Struktur für HashedEdge
mutable struct EdgeHashTable{V<:AbstractVector{HashedEdge},R}
table::V
mylength::MVector{1,UInt64}
occupied::BitVector
lock::R
function EdgeHashTable(v::A, len::Int64,lock=SingleThread()) where A
len2 = next_power_of_two(len)
resize!(v, len2)
l = locktype(lock)
#typeof(l)!=Nothing && error("")
new{A,typeof(l)}(v, MVector{1,UInt64}([len2-1]),falses(len2),l)
end
EdgeHashTable(len::Int64,lock=SingleThread()) = EdgeHashTable(Vector{HashedEdge}(undef, len), len,lock)
end
# Methode zum Einfügen in die EdgeHashTable
function pushedge!(ht::EdgeHashTable, key::K, cell::Int64, mode=true) where K
value = fnv1a_hash(key, UInt128)
value_ = UInt64(value & UInt128(0x7FFFFFFFFFFFFFFF))
index1 = value_ & ht.mylength[1]
index2 = fnv1a_hash(key, UInt64)
i = UInt64(0)
ret = false
lock(ht.lock)
#print("$value, $index2")
while true
idx = reinterpret(Int64,(index1 + i * index2) & ht.mylength[1] + 1) # try bitcast( ) instead
#print(" $idx $(ht.occupied[idx] ? 1 : 0) ")
@inbounds data = ht.occupied[idx] ? ht.table[idx] : HashedEdge()
ht.occupied[idx] = true
if data.value == 0
ht.table[idx] = HashedEdge(value, index2, cell, 0)
break #return false
elseif data.value == value && data.value2==index2 && data.cell1 == 0
ht.table[idx] = HashedEdge(value, index2, cell, 0)
break #return false
elseif data.value == value && data.value2==index2
if data.cell2 != 0
ret = true
break
end
if mode || data.cell1 != cell
ht.table[idx] = HashedEdge(value, index2, data.cell1, cell)
break #return false
else
break #return false
end
end
i += 1
if i >= ht.mylength[1]
extend(ht)
ret = pushedge!(ht, key, cell, mode)
break
end
end
unlock(ht.lock)
return ret
end
@inline clearhashvector(::Vector{HashedEdge}) = nothing
@inline similaredgehash(::Type{HashedEdge}, len2::Int64) = Vector{HashedEdge}(undef, len2)
# Funktion zum Erweitern der EdgeHashTable
function extend(ht::EdgeHashTable)
len2 = 2 * (ht.mylength[1]+1)
V2 = similaredgehash(HashedEdge, reinterpret(Int64,len2))
new_occupied = falses(len2)
len2 -= 1
pos = 0
for data in ht.table
pos += 1
!ht.occupied[pos] && continue
value_ = UInt64(data.value & UInt128(0x7FFFFFFFFFFFFFFF))
index1 = value_ & len2
index2 = data.value2
i = 0
while true
idx = reinterpret(Int64,(index1 + i * index2) & len2 + 1) # try bitcast( ) instead
i+=1
if !new_occupied[idx] #V2[idx].value==0
V2[idx] = data
new_occupied[idx] = true
break
end
end
end
clearhashvector(ht.table)
ht.table = V2
ht.occupied = new_occupied
ht.mylength[1] = len2
end
# Methode zum Leeren der EdgeHashTable
function Base.empty!(ht::EdgeHashTable)
lock(ht.lock)
fill!(ht.occupied,false)
unlock(ht.lock)
end
#=
# Methode zum Prüfen, ob ein Schlüssel in der EdgeHashTable vorhanden ist
function Base.haskey(ht::EdgeHashTable, key)
value = fnv1a_hash(key, UInt128)
index1 = Int64(value % ht.mylength[1])
index2 = fnv1a_hash(key, UInt64)
i = 0
while true
idx = (index1 + i * index2) % ht.mylength[1] + 1
data = ht.table[idx]
if data.value == 0
return false
elseif data.value == value
return true
end
i += 1
if i >= ht.mylength[1]
return false
end
end
end
=#
struct HashedVertex
value::UInt128
value2::UInt64
cell::Int64
end
@inline HashedVertex() = HashedVertex(0, 0, 0)
# Definition der mutable VertexHashTable Struktur für HashedVertex
mutable struct VertexHashTable{V<:AbstractVector{HashedVertex}}
table::V
mylength::MVector{1,UInt64}
occupied::BitVector
function VertexHashTable(v::A, len::Int64) where A
len2 = next_power_of_two(len)
resize!(v, len2)
new{A}(v, MVector{1,UInt64}([len2-1]), falses(len2))
end
VertexHashTable(len::Int64) = VertexHashTable(Vector{HashedVertex}(undef, len), len)
end
# Methode zum Einfügen in die VertexHashTable
function pushvertex!(ht::VertexHashTable, key::K, cell::Int64, mode=true) where K
value = fnv1a_hash(key, UInt128)
value_ = UInt64(value & UInt128(0x7FFFFFFFFFFFFFFF))
index1 = value_ & ht.mylength[1]
index2 = fnv1a_hash(key, UInt64)
i = UInt64(0)
while true
idx = reinterpret(Int64, (index1 + i * index2) & ht.mylength[1] + 1)
if !ht.occupied[idx]
ht.occupied[idx] = true
ht.table[idx] = HashedVertex(value, index2, cell)
return true
end
data = ht.table[idx]
if data.value == value && data.value2 == index2
return false
end
i += 1
if i >= ht.mylength[1]
extend(ht)
return pushvertex!(ht, key, cell, mode)
end
end
end
function haskey(ht::VertexHashTable, key::K, cell::Int64, mode=true) where K
value = fnv1a_hash(key, UInt128)
value_ = UInt64(value & UInt128(0x7FFFFFFFFFFFFFFF))
index1 = value_ & ht.mylength[1]
index2 = fnv1a_hash(key, UInt64)
i = UInt64(0)
while true
idx = reinterpret(Int64, (index1 + i * index2) & ht.mylength[1] + 1)
if ht.occupied[idx]
data = ht.table[idx]
if data.value == value && data.value2 == index2
return true
end
else
return false
end
i += 1
if i >= ht.mylength[1]
return false
end
end
end
@inline clearhashvector(::Vector{HashedVertex}) = nothing
@inline similarvertexhash(::Type{HashedVertex}, len2::Int64) = Vector{HashedVertex}(undef, len2)
# Funktion zum Erweitern der VertexHashTable
function extend(ht::VertexHashTable)
println("extending...")
len2 = 2 * (ht.mylength[1] + 1)
V2 = similarvertexhash(HashedVertex, reinterpret(Int64, len2))
new_occupied = falses(len2)
len2 -= 1
pos = 0
for data in ht.table
pos += 1
!ht.occupied[pos] && continue
value_ = UInt64(data.value & UInt128(0x7FFFFFFFFFFFFFFF))
index1 = value_ & len2
index2 = data.value2
i = 0
while true
idx = reinterpret(Int64, (index1 + i * index2) & len2 + 1)
i += 1
if !new_occupied[idx]
V2[idx] = data
new_occupied[idx] = true
break
end
end
end
clearhashvector(ht.table)
ht.table = V2
ht.occupied = new_occupied
ht.mylength[1] = len2
end
# Methode zum Leeren der VertexHashTable
function Base.empty!(ht::VertexHashTable)
fill!(ht.occupied, false)
end
function test_EdgeHashTable()
len = 3
ht = EdgeHashTable(len)
println(ht)
empty!(ht)
# Beispiel für das Einfügen mit Vector{Int64} keys
println(pushedge!(ht, [1, 2, 3], 1)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushedge!(ht, [1, 2, 3], 1,false)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushedge!(ht, [1, 2, 3], 2)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushedge!(ht, [1, 2, 3], 4)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushedge!(ht, [1, 2, 3], 2)) # sollte true zurückgeben, da der Schlüssel bereits vorhanden ist
println(pushedge!(ht, [4, 5, 6], 3)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushedge!(ht, [4, 7, 6], 3)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushedge!(ht, [4, 8, 6], 3)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushedge!(ht, [4, 9, 6], 3)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushedge!(ht, [4, 10, 6], 3)) # sollte false zurückgeben, da es ein neuer Eintrag ist
# Beispiel für das Prüfen mit Vector{Int64} keys
empty!(ht)
return true
end
function test_VertexHashTable()
len = 3
ht = VertexHashTable(len)
println(ht)
empty!(ht)
# Beispiel für das Einfügen mit Vector{Int64} keys
println(pushvertex!(ht, [1, 2, 3], 1)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushvertex!(ht, [1, 2, 3], 2)) # sollte true zurückgeben, da der Schlüssel bereits vorhanden ist
println(pushvertex!(ht, [4, 5, 6], 3)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushvertex!(ht, [4, 7, 6], 3)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushvertex!(ht, [4, 8, 6], 3)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushvertex!(ht, [4, 9, 6], 3)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(pushvertex!(ht, [4, 10, 6], 3)) # sollte false zurückgeben, da es ein neuer Eintrag ist
println(haskey(ht,[1,2,3],1))
println(haskey(ht,[10,2,3],10))
# Beispiel für das Prüfen mit Vector{Int64} keys
empty!(ht)
return true
end
#=
Needs following methods:
hash_entry{T}(data,mode)::T
first_hashing()::Bool
modify_hashing(data::T,_data,mode)::(T,Bool)
=#
#=
struct HashedEntry{T}
value::UInt128
value2::UInt64
data::T
HashedEntry(a,b,t::T) where T = new{T}(a,b,t)
HashedEntry{T}(v,v2,d,m) = new{T}(v,v2,hash_entry{T}(d,m))
end
@inline HashedEntry(d::T) where T = HashedEdge{T}(0,0,d)
# Definition der mutable EdgeHashTable Struktur für HashedEdge
mutable struct HashTable{T,V<:AbstractVector{HashedEdge{T}}}
table::V
mylength::MVector{1,UInt64}
occupied::BitVector
function HashTable(v::A, len::Int64) where {T,A<:AbstractVector{T}}
len2 = next_power_of_two(len)
resize!(v, len2)
new{T,A}(v, MVector{1,UInt64}([len2-1]),falses(len2))
end
HashTable(::Type{TT},len::Int64) where TT = HashTable(Vector{HashedEntry{T}}(undef, len), len)
end
# Methode zum Einfügen in die EdgeHashTable
function Base.push!(ht::HT, key::K, _data, mode=true) where {T,HT<:HashTable{T},K}
value = fnv1a_hash(key, UInt128)
value_ = UInt64(value & UInt128(0x7FFFFFFFFFFFFFFF))
index1 = value_ & ht.mylength[1]
index2 = fnv1a_hash(key, UInt64)
i = UInt64(0)
while true
idx = reinterpret(Int64,(index1 + i * index2) & ht.mylength[1] + 1) # try bitcast( ) instead
occupied = ht.occupied[idx]
@inbounds data = occupied ? ht.table[idx] : HashedEntry{T}(value, index2, _data,mode)
ht.occupied[idx] = true
if !occupied
ht.table[idx] = data
return first_hashing(data)
elseif data.value == value && data.value2==index2
t, ret = modify_hashing(data.data,_data,mode)
ht.table[idx] = HashedEntry(value,index2,t)
return ret
end
i += 1
if i >= ht.mylength[1]
extend(ht)
return push!(ht, key, _data, mode)
end
end
end
@inline clearhashvector(::Vector{HashedEntry}) = nothing
@inline similarhash(::Vector{HashedEntry}, len2::Int64) = Vector{HashedEntry}(undef, len2)
# Funktion zum Erweitern der EdgeHashTable
function extend(ht::HashTable)
len2 = 2 * (ht.mylength[1]+1)
V2 = similarhash(ht.table, reinterpret(Int64,len2))
new_occupied = falses(len2)
len2 -= 1
pos = 0
for data in ht.table
pos += 1
!ht.occupied[pos] && continue
value_ = UInt64(data.value & UInt128(0x7FFFFFFFFFFFFFFF))
index1 = value_ & len2
index2 = data.value2
i = 0
while true
idx = reinterpret(Int64,(index1 + i * index2) & len2 + 1) # try bitcast( ) instead
i+=1
if !new_occupied[idx] #V2[idx].value==0
V2[idx] = data
new_occupied[idx] = true
break
end
end
end
clearhashvector(ht.table)
ht.table = V2
ht.occupied = new_occupied
ht.mylength[1] = len2
end
# Methode zum Leeren der EdgeHashTable
function Base.empty!(ht::HashTable)
fill!(ht.occupied,false)
# @simd for i in 1:ht.mylength[1]
# @inbounds ht.table[i] = HashedEdge(0, 0, 0, 0)
# end
end
=# | HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 25720 |
VoronoiNodesM(x::Matrix) = map(MVector{size(x,1)}, eachcol(x))
VoronoiNodesM(x::Vector{<:Vector}) = map(MVector{size(eltype(x))[1]}, x)
VoronoiNodesM(x::Vector{<:MVector}) = x
VoronoiNodesM(p::AbstractVector{Float64}) = VoronoiNodesM([p])
VoronoiNodesM(p::AbstractVector{Float32}) = VoronoiNodesM([p])
const EI_valid_rays = 1
const EI_currentprimary = 2
const EI_currentsecondary = 3
const EI_currentplane = 4
struct FEIData{T,TT,TTT,TTTT,FT}
dim::Int64
current_dim::Int64
sig::Vector{Int64}
r::T
vals::Vector{FT} # seems not used, was a buffer
local_xs::TTTT #Vector{T}
local_cone::TTTT #Vector{T}
rays::TTTT #Vector{T}
new_node::Vector{Int64} # now stores indeces of active sigma
index::Vector{Int64} # index to current position in plane vector
free_nodes::Vector{Bool}
valid_nodes::Vector{Bool}
active_nodes::TT
planes::Vector{BitVector} # seems not used
current_edge::T # seems not used
proto::TTT
end
function FEIData(pp,cdim)
get_dim(i::Int) = i
get_dim(p::Point) = size(p)[1]
dim = get_dim(pp)
return FEIData{MVector{get_dim(pp),eltype(pp)},MVector{get_dim(pp),Int64},SVector{get_dim(pp),Int64},Vector{MVector{get_dim(pp),eltype(pp)}},eltype(pp)}(dim,cdim,Int64[],zeros(MVector{get_dim(pp),eltype(pp)}),eltype(pp)[],VoronoiNodesM(rand(eltype(pp),dim,dim)),VoronoiNodesM(rand(eltype(pp),dim,dim)),VoronoiNodesM(rand(eltype(pp),dim,dim)),[0],[1,0,0,0],[true],[true],zeros(MVector{dim,Int64}),[BitVector([1])],MVector{dim,eltype(pp)}(zeros(eltype(pp),dim)),zeros(SVector{dim,Int64}))
end
DimFEIData{S,FLOAT} = FEIData{MVector{S, FLOAT}, MVector{S, Int64}, SVector{S, Int64}, Vector{MVector{S, FLOAT}},FLOAT}
#FEIData{MVector{S,Float64},MVector{S,Int64}}
struct FEIStorage{TT}
index::MVector{5,Int64} # index to current position in plane vector
free_nodes::Vector{Bool}
valid_nodes::Vector{Bool}
active_nodes::TT
end
DimFEIStorage{S} = FEIStorage{MVector{S, Int64}}
function FEIStorage(sig,r)
lsig = length(sig)
index = MVector{5,Int64}(zeros(Int64,5))
free_nodes = Vector{Bool}(undef,lsig)
valid_nodes = Vector{Bool}(undef, lsig)
active_nodes = MVector{length(r), Int64}(zeros(Int64,length(r)))
return FEIStorage(index,free_nodes,valid_nodes,active_nodes)
end
function reset(f::FEIStorage)
f.index[5] = 0
return f
end
### Maybe useful in future
#=function reset(fei::FEIStorage,sig,_Cell,neighbors,sig_neigh_iterator)
reset(sig_neigh_iterator,sig,neighbors)
lsig = length(sig)
resize!(fei.free_nodes,lsig)
resize!(fei.valid_nodes,lsig)
fei.free_nodes .= false
fei.valid_nodes .= false
for (a,b) in sig_neigh_iterator
fei.valid_nodes[a] = true
end
first_index = findfirstassured(_Cell,sig)
fei.index[5] = _Cell
view(fei.index,1:4) .= 0
_swap(1,first_index,fei.valid_nodes)
fei.active_nodes[1] = 1
return fei
end=#
struct FastEdgeIterator{T,FLOAT}
iterators::T
ray_tol::FLOAT
function FastEdgeIterator(p_data,tol=1.0E-12)
get_dim(i::Int) = i
get_dim(p) = size(p)[1]
dim = get_dim(p_data)
proto = FEIData(p_data,dim)
its = Vector{typeof(proto)}(undef,dim-1)
for i in 1:(dim-1)
its[i] = FEIData(p_data,dim-i+1)
end
return new{typeof(its),typeof(tol)}(its,tol)
end
end
function ray(NF_::FastEdgeIterator{T}) where {T}
return NF_.iterators[1].rays[NF_.iterators[1].dim]
end
function Base.iterate(itr::FastEdgeIterator, state=1)
b, edge, gen = update_edge(itr)
return b ? ( (edge,gen), state+1 ) : nothing
end
function get_full_edge(sig,r,edge,NF_::FastEdgeIterator,xs)
NF=NF_.iterators[1]
fullview,count = get_full_edge(NF.rays,NF.local_cone,NF.new_node,NF.active_nodes[1],length(NF.sig),NF.dim,NF_.ray_tol)
return Vector{Int64}(view(NF.sig, fullview[1:count])), convert_SVector( -1 .* ray(NF_) )
end
#=function get_full_edge_indexing(sig,r,edge,NF_::FastEdgeIterator,xs)
NF=NF_.iterators[1]
fullview, count = get_full_edge_indexing(NF.rays,NF.local_cone,NF.new_node,NF.active_nodes[1],length(NF.sig),NF.dim,NF_.ray_tol)
return view(NF.sig, fullview[1:count])
end
=#
function update_edge(NF_::FastEdgeIterator,searcher,edge,all_edges=false)
# print("U")
# print(" ")
NF = NF_.iterators[1]
dim = NF.dim
first_entry = NF.active_nodes[1]
my_cone = NF.local_cone
my_valid_nodes = NF.valid_nodes
my_minimal = NF.active_nodes
data = NF.index
lsig = NF.sig[end]==0 ? findfirstassured(0,NF.sig)-1 : length(NF.sig)
angle_condition(x) = x>1.0E-12
nu = NF.rays
if data[EI_valid_rays]<dim-1
return false, data
end
full_edge = Int64[]
lfull_edge = 0
old_broken_index = dim+1
while lfull_edge==0
start_index = 1
if my_minimal[2]==0
my_minimal[2] = first_entry
fill_up_edge(my_minimal,my_valid_nodes,2,dim)
else
start_index = old_broken_index +1
while start_index>old_broken_index
for i in dim:-1:1
i==1 && (return false,data)
nv = next_valid(my_valid_nodes,my_minimal[i])
if (dim==i ? nv!=0 : nv!=my_minimal[i+1])
fill_up_edge(my_minimal,my_valid_nodes,i,dim)
start_index = i-1
break
end
end
end
end
# adjust orthogonal basis
nu[dim] .= my_cone[first_entry]
b = true
# print("$(my_minimal)")
for i in 1:(start_index-1)
rotate(nu,i,dim)
rotate(nu,i,dim)
end
for i in start_index:(dim-1)
nu[i] .= my_cone[my_minimal[i+1]]
if abs(dot(nu[i],nu[dim]))<1.0E-12
#print("|")
old_broken_index = i
b = false
break
end
# if i>1
rotate(nu,i,dim)
rotate(nu,i,dim)
# end
end
# print("|")
b==false && continue
# print("|")
my_angle = searcher.ray_tol # min(10*searcher.ray_tol,max_angle(nu,dim))
# error("has to change `edge` argument to disposable vector")
full_edge, lfull_edge = get_full_edge(nu,my_cone,NF.new_node,first_entry,lsig,dim,my_angle)
# length(full_edge)>0 && print("(success) ")
# length(full_edge)==0 && println()
nu[dim] .*= -1.0
end
# print("ES")
#length(full_edge)==1 && error("")
return true, view(full_edge,1:lfull_edge)
end
@inline function swap(i,j,args...)
for k in 1:length(args)
@inbounds args[k][i], args[k][j] = args[k][j], args[k][i]
end
end
@inline function _swap(i,j,args)
@inbounds args[i], args[j] = args[j], args[i]
end
@inline function ortho_project!(nu,i,range)
for j in range
if i!=j
@inbounds nu[i] .-= dot(nu[i], nu[j]) .* nu[j]
@inbounds normalize!(nu[i])
end
end
end
@inline function update_normal!(nu,i,dim)
@inbounds nor_i = dot(nu[dim],nu[i])
@inbounds nu[dim] .-= nor_i .*nu[i]
@inbounds normalize!(nu[dim])
end
@inline function ortho_project2!(nu,i,range)
for j in range
if i!=j
@inbounds nu[i] .-= dot(nu[i], nu[j]) .* nu[j]
@inbounds nu[i] .-= dot(nu[i], nu[j]) .* nu[j]
@inbounds normalize!(nu[i])
end
end
end
@inline function update_normal2!(nu,i,dim)
@inbounds nor_i = dot(nu[dim],nu[i])
@inbounds nu[dim] .-= nor_i .*nu[i]
@inbounds nor_i = dot(nu[dim],nu[i])
@inbounds nu[dim] .-= nor_i .*nu[i]
@inbounds normalize!(nu[dim])
end
function max_angle(nu,dim)
m = 0.0
for i in 1:(dim-1)
for j in (i+1):dim
@inbounds m = max(m,abs(dot(nu[i],nu[j])))
end
end
return 10*m
end
function rotate(nu,i,dim)
ortho_project!(nu,i,1:(i-1))
update_normal!(nu,i,dim)
end
function rotate2(nu,i,dim)
ortho_project2!(nu,i,1:(i-1))
update_normal2!(nu,i,dim)
end
function reset(NF_::FastEdgeIterator,_first,sig,searcher,r)
reset(NF_,sig,r,searcher.tree.extended_xs,sig[_first],searcher)
end
fraud_vertex(dim,sig,r,lsig,searcher::Nothing,xs) = false
function reset(NF_::FastEdgeIterator,sig::Sigma,r,xs,_Cell,searcher,fstore::FEIStorage=FEIStorage(sig,r),nu=0,old_cone=0,step=1;allrays = false, _Cell_first=false)
dim = NF_.iterators[1].dim
NF = NF_.iterators[step]
cdim = NF.current_dim
_Cell_entry = findfirstassured(_Cell,sig)
lsig = length(sig)
if dim==cdim && _Cell_entry>lsig-dim && !allrays
NF.index[EI_valid_rays] = 1
return false
end
if length(NF.sig)<lsig # resize data structure if necessary
lnfsig = length(NF.sig)
resize!(NF.sig,lsig)
resize!(NF.vals,lsig)
resize!(NF.local_cone,lsig)
resize!(NF.local_xs,lsig)
resize!(NF.free_nodes,lsig)
resize!(NF.valid_nodes,lsig)
#resize!(NF.index,lsig)
resize!(NF.new_node,lsig)
for i in (lnfsig+1):lsig
NF.local_cone[i] = MVector{length(NF.local_cone[1]),Float64}(zeros(Float64,length(NF.local_cone[1])))
NF.local_xs[i] = MVector{length(NF.local_cone[1]),Float64}(zeros(Float64,length(NF.local_cone[1])))
end
for k in 1:length(NF.planes)
resize!(NF.planes[k],lsig)
end
end
NF.sig[1:lsig] .= sig
if length(NF.sig)>lsig
NF.sig[(lsig+1):end] .= 0
end
_swap(1,_Cell_entry,NF.sig)
first_entry = 1 #findfirst(x->x==_Cell,sig)
resize!(NF.sig,lsig)
resize!(NF.vals,lsig)
resize!(NF.local_cone,lsig)
resize!(NF.local_xs,lsig)
resize!(NF.free_nodes,lsig)
resize!(NF.valid_nodes,lsig)
#resize!(NF.index,lsig)
resize!(NF.new_node,lsig)
my_cone = NF.local_cone
my_xs = NF.local_xs
my_vals = NF.vals
my_sig = NF.sig
my_freenodes = NF.free_nodes
my_minimal = NF.active_nodes
my_data = NF.index
#identify fraud indices far away from actual cloud
if dim==cdim && fraud_vertex(dim,sig,r,lsig,searcher,xs) # see particular fraud_vertex definition above
NF.index[EI_valid_rays] = 0
return false
end
# local coordinates for potential active nodes
if length(nu)>1
for i in 1:dim
NF.rays[i] .= nu[i]
end
for i in 1:lsig
my_cone[i] .= old_cone[my_sig[i]]
i==first_entry && continue
my_xs[i] .= xs[my_sig[i]]
end
my_cone[first_entry] .-= dot(my_cone[first_entry],nu[cdim+1]) .* nu[cdim+1]
normalize!(my_cone[first_entry])
my_cone[first_entry] .-= dot(my_cone[first_entry],nu[cdim+1]) .* nu[cdim+1]
normalize!(my_cone[first_entry])
NF.r .= r
NF.r .-= dot(NF.r,nu[cdim+1]) .* nu[cdim+1]
NF.r .-= dot(NF.r,nu[cdim+1]) .* nu[cdim+1]
else
x0 = xs[my_sig[first_entry]]
NF.r .= r .- x0
for i in 1:lsig
i==first_entry && continue
my_xs[i] .= xs[my_sig[i]] .- x0
end
# local tangential normalized vectors
for i in 1:lsig
i==first_entry && continue
my_cone[i] .= my_xs[i] #my_xs[i]
normalize!(my_cone[i])
end
my_cone[first_entry] .= NF.r # my_xs[first_entry]
my_xs[first_entry] .= 0
normalize!(my_cone[first_entry])
# set up normal vector
map!(k->abs(dot(my_cone[first_entry],my_cone[k])),my_vals,1:lsig)
vmin = minimum(view(my_vals,1:lsig))
vmin /= 10*dim
for i in 1:dim
my_cone[first_entry][i] += vmin*rand()
end
normalize!(my_cone[first_entry])
end
my_freenodes[1:lsig] .= true
my_freenodes[first_entry] = false
if fstore.index[5] == 0
my_minimal[1] = first_entry
my_data[EI_currentprimary] = 1 + first_entry
if dim==2
NF.valid_nodes .= false
max_cos = 2.0
i, j = 0, 0
for k1 in 1:(lsig-1)
k1==first_entry && continue
for k2 in k1:lsig
k2==first_entry && continue
mc2 = dot(my_cone[k1],my_cone[k2])
if mc2<max_cos
i, j, max_cos = k1, k2, mc2
end
end
end
for k in 1:lsig
if k==i || k== j
NF.valid_nodes[k] = true
end
end
elseif cdim==3
valid_nodes(NF_,NF_.ray_tol)
else
NF.valid_nodes .= false
b, edge,full_edge_count = scan_for_edge(NF,NF.new_node,NF_.ray_tol)
i = 0
while b
i+=1
lsub_sig = full_edge_count
if lsub_sig>cdim
fe = findfirstassured(first_entry,edge,1:full_edge_count)
#println("passing: $cdim -> $(NF.sub_iterator.current_dim), $(NF.rays), -- $(my_cone[first_entry]), $edge")
reset(NF_,view(edge,fe:full_edge_count),NF.r,my_xs,first_entry,searcher,fstore,NF.rays, my_cone,step+1)
NF2 = NF_.iterators[step+1]
sub_sig = view(NF2.sig,1:lsub_sig)
# Following modification saves ≈ 10-12% for the reset(...) function
for kk in eachindex(sub_sig)
NF.valid_nodes[sub_sig[kk]] = NF2.valid_nodes[kk]
end
#NF.valid_nodes[sub_sig] .|= NF2.valid_nodes[1:lsub_sig]
else
for __kk in 1:full_edge_count
NF.valid_nodes[edge[__kk]] = true
end
end
#println(off_str,NF.valid_nodes)
b, edge, full_edge_count = scan_for_edge(NF,NF.new_node,NF_.ray_tol)
#println(off_str,"$edge, $b")
end
NF.valid_nodes[first_entry] = false
end
if dim==cdim
fstore.index[5]=_Cell # important!
transfer_values!(fstore.index,NF.index,4) # actually not necessary to store any more
transfer_values!(fstore.free_nodes,NF.free_nodes,lsig) # actually not necessary to store any more
transfer_values!(fstore.valid_nodes,NF.valid_nodes,lsig)
transfer_values!(fstore.active_nodes,NF.active_nodes,dim) # ...[1]=first_entry, rest will be nullified later
end
else
transfer_values!(NF.index,fstore.index,4)
transfer_values!(NF.free_nodes,fstore.free_nodes,lsig)
transfer_values!(NF.valid_nodes,fstore.valid_nodes,lsig)
transfer_values!(NF.active_nodes,fstore.active_nodes,dim)
end
my_minimal[2:end] .= 0
if !_Cell_first
my_minimal[1] = _Cell_entry
_swap(1,_Cell_entry, NF.sig, )
_swap(1,_Cell_entry, NF.valid_nodes)
_swap(1,_Cell_entry, my_xs)
_swap(1,_Cell_entry, my_cone)
else
_Cell_entry = 1
end
my_data[EI_valid_rays] = sum(ii->NF.valid_nodes[ii],_Cell_entry:lsig)
(!allrays) && (NF.valid_nodes[1:_Cell_entry] .= false)
return true
end
function minimal_edge(NF_::FastEdgeIterator,searcher)
return NF_.iterators[1].active_nodes
end
function next_ray_try(data,my_freenodes,lsig)
while data[EI_currentprimary]<=lsig
my_freenodes[data[EI_currentprimary]] && break
data[EI_currentprimary] += 1
end
return data[EI_currentprimary]<=lsig
end
function update_edge(NF_::FastEdgeIterator)
# print("U")
# print(" ")
NF = NF_.iterators[1]
dim = NF.dim
first_entry = NF.active_nodes[1]
my_cone = NF.local_cone
my_valid_nodes = NF.valid_nodes
my_minimal = NF.active_nodes
data = NF.index
lsig = NF.sig[end]==0 ? findfirstassured(0,NF.sig)-1 : length(NF.sig)
angle_condition(x) = x>1.0E-12
nu = NF.rays
if data[EI_valid_rays]<dim-1
return false, NF.proto,0
end
full_edge = Int64[]
old_broken_index = dim+1
full_edge_count = 0
while full_edge_count==0
start_index = 1
if my_minimal[2]==0
my_minimal[2] = first_entry
fill_up_edge(my_minimal,my_valid_nodes,2,dim)
else
start_index = old_broken_index +1
while start_index>old_broken_index
for i in dim:-1:1
i==1 && (return false,NF.proto,0)
nv = next_valid(my_valid_nodes,my_minimal[i])
if (dim==i ? nv!=0 : nv!=my_minimal[i+1])
fill_up_edge(my_minimal,my_valid_nodes,i,dim)
start_index = i-1
break
end
end
end
end
# adjust orthogonal basis
nu[dim] .= my_cone[first_entry]
b = true
# print("$(my_minimal)")
for i in 1:(start_index-1)
rotate(nu,i,dim)
rotate(nu,i,dim)
end
for i in start_index:(dim-1)
my_minimal[i+1]==0 && (return false,NF.proto,0)
nu[i] .= my_cone[my_minimal[i+1]]
if abs(dot(nu[i],nu[dim]))<1.0E-12
#print("|")
old_broken_index = i
b = false
break
end
# if i>1
rotate(nu,i,dim)
rotate(nu,i,dim)
# end
end
# print("|")
b==false && continue
# print("|")
my_angle = NF_.ray_tol # min(10*searcher.ray_tol,max_angle(nu,dim))
full_edge, full_edge_count = get_full_edge(nu,my_cone,NF.new_node,first_entry,lsig,dim,my_angle)
# length(full_edge)>0 && print("(success) ")
# length(full_edge)==0 && println()
nu[dim] .*= -1.0
end
# print("ES")
#length(full_edge)==1 && error("")
dropped = 1
u = NF_.iterators[1].rays[NF_.iterators[1].dim]
t = dot(u,NF_.iterators[1].local_xs[1])
for i in eachindex(NF_.iterators[1].local_xs)
t2 = dot(u,NF_.iterators[1].local_xs[i])
dropped = t2<t ? i : dropped
t = min(t2,t)
end
return true, mystaticview(NF.sig,my_minimal,NF.proto), dropped
end
function fill_up_edge(my_minimal,my_valid_nodes,index,dim)
for i in index:dim
my_minimal[i] = next_valid(my_valid_nodes,my_minimal[i])
i<dim && (my_minimal[i+1]=my_minimal[i])
end
end
function next_valid(my_valid_nodes,index)
for i in (index+1):length(my_valid_nodes)
if my_valid_nodes[i]
return i
end
end
return 0
end
function valid_nodes(NF_::FastEdgeIterator{T},maxmaxangle::Float64) where {T}
dim = NF_.iterators[1].dim
NF = NF_.iterators[dim-2]
#dim = NF.dim
cdim = NF.current_dim
cdim!=3 && error("")
first_entry = NF.active_nodes[1]
my_cone = NF.local_cone
#println(" Free nodes: $(NF.free_nodes)")
NF.valid_nodes .= false
b, edge, full_edge_count = scan_for_edge(NF,NF.new_node,maxmaxangle,true)
while b
le = full_edge_count
i = j = 0
#println(" "^(dim-cdim+2),"edge: ",present_xs(NF.local_xs[edge]))
if le==3
NF.valid_nodes[NF.active_nodes[2]] = true
NF.valid_nodes[NF.active_nodes[3]] = true
else
max_cos = 2.0
for k1 in 1:(le-1)
edge[k1]==first_entry && continue
for k2 in k1:full_edge_count
edge[k2]==first_entry && continue
mc2 = dot(my_cone[edge[k1]],my_cone[edge[k2]])
if mc2<max_cos
i, j, max_cos = k1, k2, mc2
end
end
end
for k in 1:length(edge)
if k==i || k== j
NF.valid_nodes[edge[k]] = true
end
end
end
b, edge, full_edge_count = scan_for_edge(NF,NF.new_node,maxmaxangle,true)
end
end
function scan_for_edge(NF::FEIData,edge::Vector{Int64},maxmaxangle::Float64,all_edges=false)
dim = NF.dim
cdim = NF.current_dim
first_entry = NF.active_nodes[1]
my_cone = NF.local_cone
my_vals = NF.vals
my_sig = NF.sig
my_freenodes = NF.free_nodes
my_minimal = NF.active_nodes
data = NF.index
nu = NF.rays
lsig = NF.sig[end]==0 ? findfirstassured(0,NF.sig)-1 : length(NF.sig)
angle_condition(x) = x>1.0E-12
while true
if !next_ray_try(data,my_freenodes,lsig) # pick first/next ray candidate. If no left, terminate with false
return false, data, 0
end
nu[cdim] .= my_cone[first_entry]
nu[1] .= my_cone[data[EI_currentprimary]]
rotate2(nu,1,cdim)
#rotate(nu,1,cdim)
my_minimal[2] = data[EI_currentprimary]
cdim>2 && (my_minimal[3:end] .= 0)
active_condition(i) = !(i in my_minimal)
max_cos, max_ind = max_angle(nu,my_cone,lsig,my_vals,angle_condition,active_condition,cdim)
# positive = max_cos > 0
broken = false
for i in 2:(cdim-1)
# if (max_cos<0 && positive) || max_ind==0
# broken = true
# break
# end
nu[i] .= my_cone[max_ind]
rotate2(nu,i,cdim)
#rotate(nu,i,cdim)
my_minimal[i+1] = max_ind
max_cos, max_ind = max_angle(nu,my_cone,lsig,my_vals,angle_condition,active_condition,cdim)
# positive |= max_cos>0 # if positive only once, keep this information alive
end
# broken = broken || max_cos<0
#println(broken)
full_edge, full_edge_count = edge, 0
try
full_edge, full_edge_count = get_full_edge(nu,my_cone,edge,first_entry,lsig,cdim,max(max_angle(nu,cdim),maxmaxangle))
catch
println(get_full_edge(nu,my_cone,edge,first_entry,lsig,cdim,max(max_angle(nu,cdim),maxmaxangle)))
rethrow()
end
broken = full_edge_count==0
if broken
#= for k in 1:dim
if my_minimal[k]!=0
my_freenodes[my_minimal[k]] = false
else
break
end
end=#
my_freenodes[my_minimal[2]] = false
continue
end
#println(" $full_edge")
# view(my_freenodes,full_edge[1:full_edge_count]) .= false
for kk in 1:full_edge_count
my_freenodes[full_edge[kk]] = false
end
#println("final free nodes: $my_freenodes")
if all_edges || full_edge[1]==first_entry
nu[cdim] .*= -1
#sort!(my_minimal)
return true, full_edge, full_edge_count
end
end
end
function get_full_edge(nu,my_cone,edge,first_entry,lsig,dim,_max_angle=1.0E-12)
#println("hier")
count = 0
_max = 0.0
_min = 0.0
for k in 1:lsig
dnc = dot(nu[dim],my_cone[k])
inplane = abs(dnc)<10*_max_angle
_max = max(_max, k!=first_entry && !inplane ? dnc : 0.0)
_min = min(_min, k!=first_entry && !inplane ? dnc : 0.0)
if k==first_entry || inplane
count += 1
edge[count] = k
end
end
# print("$_max > $_min")
(_max>_max_angle) && (_min<-_max_angle) && (return Int64[],0)
if _min<-_max_angle
nu[dim] .*= -1
end
return edge, count
end
#=
function get_full_edge_indexing(nu,my_cone,edge,first_entry,lsig,dim,_max_angle=1.0E-12)
#println("hier")
count = 0
_max = 0.0
_min = 0.0
for k in 1:lsig
dnc = dot(nu[dim],my_cone[k])
inplane = abs(dnc)<10*_max_angle
_max = max(_max, k!=first_entry && !inplane ? dnc : 0.0)
_min = min(_min, k!=first_entry && !inplane ? dnc : 0.0)
if k==first_entry || inplane
count += 1
edge[count] = k
end
end
return edge, count
end
=#
@Base.propagate_inbounds function max_angle(nu,my_cone,lsig,my_vals,angle_condition,active_condition,dim)
#map!(k->dot(nu[dim],my_cone[k]),my_vals,1:lsig)
max_cos = 2.0
max_ind = 0
for i in 1:lsig
amv = dot(nu[dim],my_cone[i])#my_vals[i]
if angle_condition(abs(amv)) && active_condition(i) && amv<max_cos
max_cos = amv
max_ind = i
end
end
return max_cos, max_ind
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 4609 |
struct General_EdgeIterator{S}
sig::MVector{S,Int64}
a::Int64
b::Int64
proto::SVector{S,Int64}
end
#=
function General_EdgeIterator(_sig,_Cell)
a::Int64 = 1
sig = SVector{length(_sig),Int64}(_sig)
while sig[a]!=_Cell
a += 1
end
(a,b) = a>1 ? (a-1,1::Int64) : (2,length(_sig))
return General_EdgeIterator(sig,a,b)
end
function General_EdgeIterator(_sig,r,_Cell)
a::Int64 = 1
sig = MVector{length(r)+1,Int64}(_sig)
try
while sig[a]!=_Cell
a += 1
end
catch
println("$a, $sig, $_Cell")
rethrow()
end
(a,b) = a>1 ? (a-1,1::Int64) : (1,length(_sig))
return General_EdgeIterator(sig,a,b,SVector{length(r)+1,Int64}(_sig))
end
=#
function General_EdgeIterator(_sig,r,_Cell,EI::General_EdgeIterator{S}) where {S}
a::Int64 = 1
sig = EI.sig
if _sig[1]==_Cell
for i in 1:S
@inbounds sig[i] = _sig[i]
end
return General_EdgeIterator{S}(sig,1,S,EI.proto)
elseif _sig[2]==_Cell
for i in 1:S
@inbounds sig[i] = _sig[i]
end
return General_EdgeIterator{S}(sig,1,1,EI.proto)
else
return EI
end
end
@inline General_EdgeIterator(dim::INT) where {INT<:Integer} = General_EdgeIterator(MVector{dim+1,Int64}(zeros(Int64,dim+1)),dim+1,0,SVector{dim+1,Int64}(zeros(Int64,dim+1)))
function General_EdgeIterator(x::Point)
return General_EdgeIterator(MVector{length(x)+1,Int64}(zeros(Int64,length(x)+1)),length(x)+1,0,SVector{length(x)+1,Int64}(zeros(Int64,length(x)+1)))
end
function Base.iterate(itr::General_EdgeIterator, state=itr.a)
if state>itr.b
return nothing
else
return (_mydeleteat(itr.sig,state,itr.proto),itr.sig[state]), state+1
end
end
struct OnSysVoronoi
end
struct OnQueueEdges
end
function get_EdgeIterator(sig,r,searcher,_Cell,xs,O::OnSysVoronoi)
if (length(sig)==length(r)+1)
return General_EdgeIterator(sig,r,_Cell,searcher.general_edgeiterator)
else
my_iterator = searcher.edgeiterator
fei = get!(searcher.FEIStorage_global,sig,FEIStorage(sig,r))
HighVoronoi.reset(my_iterator,sig,r,searcher.tree.extended_xs,_Cell,searcher,fei)
return my_iterator
end
end
function get_EdgeIterator(sig,r,searcher,_Cell,xs,O::OnQueueEdges)
if (length(sig)==length(r)+1)
return General_EdgeIterator(sig,r,_Cell,searcher.find_general_edgeiterator)
else
my_iterator = searcher.edgeiterator2
#@descend get!(searcher.FEIStorage_global,sig,FEIStorage(sig,r))
#error("")
#print("P")
fei = reset(get!(searcher.FEIStorage_global,sig,FEIStorage(sig,r)))
HighVoronoi.reset(my_iterator,sig,r,searcher.tree.extended_xs,_Cell,searcher,fei)
return my_iterator
end
end
#=
function get_EdgeIterator(sig,r,searcher,_Cell,xs,neighbors) # special version for fast_polygon
if (length(sig)==length(r)+1)
return General_EdgeIterator(sig,r,_Cell,searcher.general_edgeiterator)
else
my_iterator = searcher.fast_edgeiterator
fei = reset(searcher.fei,sig,_Cell,neighbors,searcher.sig_neigh_iterator)
println(" $(fei.valid_nodes), $(fei.active_nodes)")
HighVoronoi.reset(my_iterator,sig,r,xs,_Cell,nothing,fei) # `nothing` makes sure that `fraud_vertex` will not error
return my_iterator
end
end
=#
function queue_edges_general_position(sig,r,searcher,_Cell,xs,edgecount,EI)
length(sig)==(length(r)+1) && sig[2]<_Cell && (return true)
all_edges_exist = true
for (edge,skip) in EI
all_edges_exist &= pushedge!(edgecount,edge,skip,false)
#= info = get(edgecount, edge, (0::Int64,0::Int64))
if !(skip in info) && info[2]==0
#_fulledge = get_full_edge_indexing(sig,r,edge,EI,xs)
edgecount[edge] = (skip,info[1])
end=#
end
return all_edges_exist
end
function queue_edges_OnCell(sig,r,searcher,_Cell,xs,edgecount)
EI = get_EdgeIterator(sig,r,searcher,_Cell,xs,OnQueueEdges())
queue_edges_general_position(sig,r,searcher,_Cell,xs,edgecount,EI)
end
function queue_edges_OnFind(sig,r,searcher,_Cell,xs,edgecount)
EI = get_EdgeIterator(sig,r,searcher,_Cell,xs,OnQueueEdges())
queue_edges_general_position(sig,r,searcher,_Cell,xs,edgecount,EI)
end
function lowerbound(k, d)
2 * pi^(k/2) * d^(k-1) / (k*(k+1)) * beta(d*k/2, (d-k+1)/2) ^ (-1) * (gamma(d/2) / gamma((d+1)/2))^k
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 249 | function exception_raycast(t,r,sig,edge,u,searcher)
end
function exception_walray_correct_vertex(b,vv,searcher,sig,r)
end
function exception_identify_multivertex(searcher,r,sig,measure,idx)
end
function walkray_failure_exception()
end | HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 6471 | abstract type AbstractExtendedNodes{P<:Point} <: HVNodes{P} end
#####################################################################################################################
## ExtendedNodes
#####################################################################################################################
struct ExtendedNodes{S, TT<:Point{S},T<:HVNodes{TT}} <: AbstractExtendedNodes{TT}
data::T
extended::Vector{TT}
boundary::Boundary
length_d::Int64
length_b::Int64
length::Int64
function ExtendedNodes(d,b::Boundary=Boundary())
ex = Vector{eltype(d)}(undef, length(b))
return new{eltype(eltype(d)),eltype(d),typeof(d)}(d,ex,b,length(d),length(b),length(d)+length(b))
end
end
Base.size(nodes::ExtendedNodes) = (nodes.length,)
inner_length(nodes::ExtendedNodes) = nodes.length_d
#Base.eltype(nodes::ExtendedNodes) = eltype(nodes.data)
# Get element at index i
function Base.getindex(nodes::ExtendedNodes, i::Int)
# i>nodes.length && error("no valid index $i in Vector of length $(nodes.length).")
if i <= nodes.length_d
return nodes.data[i]
else
return nodes.extended[i - nodes.length_d]
end
end
function Base.getindex(nodes::ExtendedNodes, i_vec::AbstractVector{Int})
_result = Vector{eltype(nodes)}(undef,length(i_vec))
for i in 1:length(i_vec)
_result[i] = nodes[i_vec[i]]
end
return _result
end
# Set element at index i
function Base.setindex!(nodes::ExtendedNodes, value, i)
if i <= nodes.length_d
error("ExtendedNodes currently not meant to be modified inside domain.")
nodes.data[i] = value
else
nodes.extended[i - nodes.length_d] = value
end
end
# Iterate over elements
function Base.iterate(nodes::ExtendedNodes, state=1)
if state <= nodes.length
return getindex(nodes, state), state + 1
else
return nothing
end
end
Base.length(nodes::ExtendedNodes) = nodes.length
SearchTree(nodes::ExtendedNodes,type=HVKDTree()) = ExtendedTree(nodes,type)
struct ExtendedTree{P<:Point,T<:AbstractTree{P},TTT<:AbstractExtendedNodes{P}} <: AbstractTree{P}
tree::T
extended_xs::TTT
active::BitVector
size::Int64
mirrors::Int64
function ExtendedTree(exs::ExtendedNodes,type=HVKDTree())
t = SearchTree(exs.data,type)
#println(type(t))
#println(type(exs.data))
l = length(exs.boundary)
a = BitVector(zeros(Int8,l))
return new{eltype(exs),typeof(t),typeof(exs)}(t,exs,a,inner_length(exs),l)
end
function ExtendedTree(xs::HVNodes,b::Boundary,type=HVKDTree())
exs = ExtendedNodes(xs,b)
return ExtendedTree(exs,type)
end
#=function ExtendedTree(tree::T) where {T<:ExtendedTree}
exs = ExtendedNodes(tree.extended_xs.data,tree.extended_xs.boundary)
t = tree.tree
l = length(exs.boundary)
a = BitVector(zeros(Int8,l))
return new{eltype(exs),typeof(t),typeof(exs)}(t,exs,a,inner_length(exs),l)
end=#
function ExtendedTree(old::ExtendedTree{P,T,TTT}) where {P<:Point,T<:AbstractTree{P},TTT<:AbstractExtendedNodes{P}}
return new{P,T,TTT}(UnstructuredTree(old.tree),old.extended_xs,old.active,old.size,old.mirrors)
end
end
function nn(tree::ExtendedTree,x::Point,skip=(x->false))::Tuple{Int64,Float64}
index, dist = nn(tree.tree,x,skip)
#= index2, dist2 = nn(tree.tree2,x,skip)
if index2!=index
nt = HVTree(tree.extended_xs.data.data,HVKDTree())
println(x)
println("$index vs. $index2 and $(nn(tree.tree,tree.extended_xs[index2])) - $(nn(tree.tree2,tree.extended_xs[index2])) - $(nn(tree.tree,x))")
idx , dists = nn(tree.tree.tree,x,skip)
idx2 , dists = nn(tree.tree.tree,x)
println("$idx vs $(tree.tree.nodes.view*idx) vs. $(idx2) vs. $(tree.tree.nodes.view*idx2) ")
println(nn(nt,x,skip))
println(nn(nt,x))
println(tree.extended_xs[index2])
println(tree.extended_xs[index])
println(tree.tree.nodes.data[index])
println(tree.tree.nodes.data[index2])
println(tree.tree.nodes.data[idx])
println(tree.tree.nodes.data[idx2])
for k in 1:37
println(tree.extended_xs[tree.tree.nodes.view*idx]-tree.tree.nodes.data[idx])
end
error("")
end=#
lm=tree.mirrors
if lm==0 return index, dist end
for i in 1:lm
( !tree.active[i] || skip(tree.size+i) ) && continue
d=norm(x-tree.extended_xs[i+tree.size])
if d<dist
index=i+tree.size
dist=d
end
end
return index, dist
end
#=function search_vertex(tree::ExtendedTree,point::MV,skip,idx,dist,bv) where {S,MV<:Union{MVector{S,Float64},SVector{S,Float64}}}
dist2(a,b) = sum(i->(a[i]-b[i])^2,1:S)
search_vertex(tree.tree,SVector(point),skip,idx,dist,tree.tree.data)
lm=tree.mirrors
for i in 1:lm
skip(tree.size+i)#,dist2(tree.extended_xs[tree.size+i],point))
#skip(tree.size+i,dist2(tree.extended_xs[tree.size+i],point))
end
end=#
function search_vertex2(tree::ExtendedTree,point::MV,idx,dist) where {S,FLOAT<:Real,MV<:Union{MVector{S,FLOAT},SVector{S,FLOAT}}}
#(a,b) = sum(i->(a[i]-b[i])^2,1:S)
data = tree.tree.data
exs = tree.extended_xs
s = tree.size
lm=tree.mirrors
for j in 1:lm
#b_skip(s+j)
x_new = exs[s+j]
mydist = sum(abs2, data.new_r - x_new)
skip_nodes_on_search(data,x_new,s+j,mydist,statictrue)
end
#=for j in 1:6
#b_skip(s+j)
x_new = exs[j]
mydist = sum(abs2, data.new_r - x_new)
skip_nodes_on_search(data,x_new,j,mydist,statictrue)
end=#
search_vertex(tree.tree,data.r,idx,dist,data)
return
#error("")
end
function _nn(tree::ExtendedTree,x::Point,skip=(x->false))::Tuple{Int64,Float64}
nn(tree,x,skip)
end
function _inrange(tree::ExtendedTree,x,r)
idx = inrange(tree.tree,x,r)
lm=tree.mirrors
if lm==0 return idx end
for i in 1:lm
( !tree.active[i] ) && continue
d=norm(x-tree.extended_xs[i+tree.size])
if d<r
append!(idx,i+tree.size)
end
end
return idx
end | HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 25339 | # We provide the Fast_Polygon_Integrator. It is defined and initialized similar to
# the MC
struct Fast_Polygon_Integrator{T,TT,IDC<:IterativeDimensionChecker,D}
_function::T
bulk::Bool
# If i!=nothing, then area has to be true. Otherwise values are taken as given
Integral::TT
iterative_checker::IDC
data::D
function Fast_Polygon_Integrator{T,TT,IDC}(f::T,b::Bool,I::TT,Itc::IDC) where {T,TT,IDC}
data = DictHierarchy(zeros(PointType(I)))
D = typeof(data)
return new{T,TT,IDC,D}(f,b,I,Itc,data)
end
#=function Fast_Polygon_Integrator(mesh,integrand=nothing, bulk_integral=false)
b_int=(typeof(integrand)!=Nothing) ? bulk_integral : false
i_int=(typeof(integrand)!=Nothing) ? true : false
Integ=Voronoi_Integral(mesh,integrate_bulk=b_int, integrate_interface=i_int)
idc = IterativeDimensionChecker(dimension(mesh))
PI=Fast_Polygon_Integrator{typeof(integrand),typeof(Integ),typeof(idc)}( integrand, b_int, Integ, idc )
return PI
end=#
function Fast_Polygon_Integrator(Integ::HVIntegral,integrand=nothing, bulk_integral=false)
b_int=(typeof(integrand)!=Nothing) ? bulk_integral : false
enable(Integ,volume=true,integral=b_int)
idc = IterativeDimensionChecker(dimension(mesh(Integ)))
PI=Fast_Polygon_Integrator{typeof(integrand),typeof(Integ),typeof(idc)}( integrand, b_int, Integ, idc )
return PI
end
function Fast_Polygon_Integrator(fpi::FPI,d::D) where {T,TT,IDC,FPI<:Fast_Polygon_Integrator{T,TT,IDC},D}
return new{T,TT,IDC,D}(fpi._function,fpi.bulk,fpi.Integral,fpi.iterative_checker,d)
end
end
function parallelize_integrators(myintes2::AVI) where {I<:Fast_Polygon_Integrator,AVI<:AbstractVector{I}}
meshes = map(i->mesh(i.Integral),myintes2)
tmdh = ThreadsafeMeshDictHierarchy(meshes,zeros(PointType(myintes2[1].Integral)))
return map(i->Fast_Polygon_Integrator(myintes2[i],tmdh[i]),1:length(meshes))
end
function copy(I::Fast_Polygon_Integrator)
return Fast_Polygon_Integrator{typeof(I._function),typeof(I.Integral)}(I._function,I.bulk,copy(I.Integral))
end
@inline function integrate(Integrator::Fast_Polygon_Integrator; domain, relevant, modified,progress)
_integrate(Integrator, domain=domain, calculate=modified, iterate=relevant,progress=progress)
end
function prototype_bulk(Integrator::Fast_Polygon_Integrator)
y = (typeof(Integrator._function)!=Nothing && Integrator.bulk) ? Integrator._function(nodes(mesh(Integrator.Integral))[1]) : Float64[]
return 0.0*y
end
function prototype_interface(Integrator::Fast_Polygon_Integrator)
return 0.0*(typeof(Integrator._function)!=Nothing ? Integrator._function(nodes(mesh(Integrator.Integral))[1]) : Float64[])
end
struct PolyBufferData
volume::Float64
integral::Vector{Float64}
end
struct NoPolyBuffer
end
struct MeshDict{K, V, AM<:AbstractMesh, MV, D<:AbstractDict{K, V}} <: AbstractDict{K, V}
mesh::AM
buffer::MV
dict::D
function MeshDict(mesh::AM, dict::D) where {K, V, AM<:AbstractMesh, D<:AbstractDict{K, V}}
buffer = MVector(zeros(K))
return new{K, V, AM, typeof(buffer), D}(mesh, buffer, dict)
end
end
function Base.push!(md::MeshDict{K, V, AM, MV, D}, pairs::Pair{K, V}) where {K, V, AM<:AbstractMesh, MV, D<:AbstractDict{K, V}}
md.buffer .= pairs[1]
push!(md.dict,K(sort!(_internal_indeces(md.mesh,md.buffer)))=>pairs[2])
end
function Base.haskey(md::MD, key) where {K,MD<:MeshDict{K}}
md.buffer .= key
sort!(_internal_indeces(md.mesh,md.buffer))
return haskey(md.dict,K(md.buffer))
end
function Base.getindex(md::MeshDict{K, V, AM, MV, D}, key::K) where {K, V, AM<:AbstractMesh, MV, D<:AbstractDict{K, V}}
md.buffer .= key
getindex(md.dict,K(sort!(_internal_indeces(md.mesh,md.buffer))))
end
struct DictHierarchy{D,S}
dict::D
sub::S
DictHierarchy(x::P) where {P<:Point} = DictHierarchy(x,StaticArrays.deleteat(x,1))
DictHierarchy(x::SV2) where {R<:Real,SV2<:SVector{2,R}} = DictHierarchy(x,x)
function DictHierarchy(x,dim_vec)
proto = SVector{length(x)-length(dim_vec)+2,Int64}(zeros(Int64,length(x)-length(dim_vec)+2))
facets = Dict{typeof(proto),PolyBufferData}() #Dict{typeof(proto),PolyBufferData}()
sub = DictHierarchy(x,StaticArrays.deleteat(dim_vec,1))
return new{typeof(facets),typeof(sub)}(facets,sub)
end
function DictHierarchy(x,dim_vec::SV2) where {R<:Real,SV2<:SVector{2,R}}
proto = SVector{length(x)-length(dim_vec)+2,Int64}(zeros(Int64,length(x)-length(dim_vec)+2))
facets = Dict{typeof(proto),PolyBufferData}() #Dict{typeof(proto),PolyBufferData}()
return new{typeof(facets),Nothing}(facets,nothing)
end
end
struct ThreadsafeDictHierarchy{D<:Union{AbstractDict,MultiKeyDict},S}
dict::D
sub::S
end
ThreadsafeDictHierarchy(x::P) where {P<:Point} = ThreadsafeDictHierarchy(x,StaticArrays.deleteat(x,1))
ThreadsafeDictHierarchy(x::SV2) where {R<:Real,SV2<:SVector{2,R}} = ThreadsafeDictHierarchy(x,x)
function ThreadsafeDictHierarchy(x::P,dim_vec) where {P<:Point}
proto = SVector{length(x)-length(dim_vec)+2,Int64}(zeros(Int64,length(x)-length(dim_vec)+2))
facets = ThreadsafeDict(Dict{typeof(proto),PolyBufferData}())
sub = ThreadsafeDictHierarchy(x,StaticArrays.deleteat(dim_vec,1))
return ThreadsafeDictHierarchy{typeof(facets),typeof(sub)}(facets,sub)
end
function ThreadsafeDictHierarchy(x,dim_vec::SV2) where {R<:Real,SV2<:SVector{2,R}}
proto = SVector{length(x)-length(dim_vec)+2,Int64}(zeros(Int64,length(x)-length(dim_vec)+2))
facets = ThreadsafeDict(Dict{typeof(proto),PolyBufferData}())
return ThreadsafeDictHierarchy{typeof(facets),Nothing}(facets,nothing)
end
ThreadsafeMeshDictHierarchy(meshes,x::P) where {P<:Point} = ThreadsafeMeshDictHierarchy(meshes,x,StaticArrays.deleteat(x,1))
function ThreadsafeMeshDictHierarchy(meshes,x,dim_vec)
proto = SVector{length(x)-length(dim_vec)+2,Int64}(zeros(Int64,length(x)-length(dim_vec)+2))
tsd = MultiKeyDict{typeof(proto),PolyBufferData}()
facets = map(m->MeshDict(m,tsd),meshes)
subs = ThreadsafeMeshDictHierarchy(meshes,x,StaticArrays.deleteat(dim_vec,1))
return map(i->ThreadsafeDictHierarchy{typeof(facets[i]),typeof(subs[i])}(facets[i],subs[i]),1:length(meshes))
end
function ThreadsafeMeshDictHierarchy(meshes,x,dim_vec::SV2) where {R<:Real,SV2<:SVector{2,R}}
proto = SVector{length(x)-length(dim_vec)+2,Int64}(zeros(Int64,length(x)-length(dim_vec)+2))
tsd = MultiKeyDict{typeof(proto),PolyBufferData}()
facets = map(m->MeshDict(m,tsd),meshes)
return map(i->ThreadsafeDictHierarchy{typeof(facets[i]),Nothing}(facets[i],nothing),1:length(meshes))
end
struct PolyBuffer{SUB,DIC,P,T,TT}
facets::DIC
sub::SUB
integral_buffer::Vector{Float64}
proto::P
center::T
current_path::TT
generators::BitVector
buffer_generators::BitVector
end
PolyBuffer(xs::HVN) where {P,HVN<:HVNodes{P}} = PolyBuffer(xs[1])
PolyBuffer(x::P) where {P<:Point} = PolyBuffer(x,StaticArrays.deleteat(x,1))
PolyBuffer(x::P,data) where {P<:Point} = PolyBuffer(x,StaticArrays.deleteat(x,1),data)
function PolyBuffer(x,dim_vec,data)
proto = SVector{length(x)-length(dim_vec)+2,Int64}(zeros(Int64,length(x)-length(dim_vec)+2))
current = MVector{length(x)-length(dim_vec)+2,Int64}(zeros(Int64,length(x)-length(dim_vec)+2))
facets = data.dict
return PolyBuffer(facets,PolyBuffer(x,StaticArrays.deleteat(dim_vec,1),data.sub),Float64[],proto,MVector{length(x)}(x),current,falses(2^length(x)),falses(2^length(x)))
end
function PolyBuffer(x,dim_vec::SV2,data) where {R<:Real,SV2<:SVector{2,R}}
proto = SVector{length(x)-length(dim_vec)+2,Int64}(zeros(Int64,length(x)-length(dim_vec)+2))
current = MVector{length(x)-length(dim_vec)+2,Int64}(zeros(Int64,length(x)-length(dim_vec)+2))
facets = data.dict
return PolyBuffer(facets,NoPolyBuffer(),Float64[],proto,MVector{length(x)}(x),current,falses(2^length(x)),falses(2^length(x)))
end
PolyBuffer(_,::SV1,d) where {R<:Real,SV1<:SVector{1,R}} = NoPolyBuffer()
get_Edge_Level(pb::PolyBuffer) = get_Edge_Level(pb,pb.sub)
get_Edge_Level(pb::PolyBuffer,sub::PolyBuffer) = get_Edge_Level(sub,sub.sub)
get_Edge_Level(pb::PolyBuffer,sub) = pb
get_Edge_Level(pb::NoPolyBuffer) = pb
function reset(pb::PolyBuffer,lneigh)
if lneigh>length(pb.generators)
resize!(pb.generators,lneigh)
resize!(pb.buffer_generators,lneigh)
end
reset(pb.sub,lneigh)
end
reset(pb::NoPolyBuffer,lneigh) = nothing
IntegrateData(xs::HV,dom,tt::FPI) where {P,HV<:HVNodes{P},FPI<:Fast_Polygon_Integrator} = _IntegrateData(xs,dom,PolyBuffer(zeros(P),tt.data))
function facett_identifier(dc,buffer::PolyBuffer,_Cell,facett)
current = buffer.current_path
for k in 1:(length(current)-2)
current[k] = dc.current_path[k]
end
current[length(current)-1] = facett
current[end] = _Cell
sort!(current)
return SVector{length(current),Int64}(current)
end
#=find_fast_poly_edges(dic::NoPolyBuffer,neighbors,iterator,container,xs) = nothing
function find_fast_poly_edges(dic,neighbors,iterator,container,xs) # `container ∼ searcher`
for (sig,r) in iterator
my_iterator = get_EdgeIterator(sig,r,container,_Cell,xs,neighbors)
store_edges(my_iterator,dic,neighbors,xs,sig,r)
end
end
function store_edges(my_iterator,dic,neighbors,xs,sig,r)
for (edge,skip) in my_iterator
full_edge, _ = get_full_edge(sig,r,edge,my_iterator,xs)
intersect!(full_edge,neighbors)
data = get!(dic,full_edge,FastPolyEdge(r))
dic[full_edge] = FastPolyEdge(data,r)
end
end=#
"""
initialize_integrator(xs,_Cell,verteces,edges,integrator::Fast_Polygon_Integrator)
The integrator is initialized at beginning of systematic_voronoi(....) if an MC_Function_Integrator is passed as a last argument
This buffer version of the function does nothing but return two empty arrays:
- The first for Volume integrals. The first coordinate of the vector in each node
corresponds to the volume of the Voronoi cell
- The second for Area integrals. The first coordinate of the vector on each interface
corresponds to the d-1 dimensional area of the Voronoi interface
"""
#function integrate(domain,_Cell,iter,calcul,searcher,Integrator::Fast_Polygon_Integrator)
function integrate(neighbors,_Cell,iterate, calculate, data,Integrator::Fast_Polygon_Integrator,ar,bulk_inte,inter_inte,vvvol)
Integral = Integrator.Integral
# verteces2 = Integral.MESH.Buffer_Verteces[_Cell]
verteces = vertices_iterator(mesh(Integral),_Cell)
xs=data.extended_xs
# !(typeof(data.buffer_data)<:PolyBuffer) && !(typeof(data.buffer_data)<:NoPolyBuffer) && error("")
dim = data.dimension # (full) Spatial dimension
# get all neighbors of this current cell
neigh=neighbors
_length=length(neigh)
# flexible data structure to store the sublists of verteces at each iteration step 1...dim-1
emptydict=Vector{Int64}()#EmptyDictOfType([0]=>xs[1]) # empty buffer-list to create copies from
listarray=(typeof(emptydict))[] # will store to each remaining neighbor N a sublist of verteces
# which are shared with N
all_dd=(typeof(listarray))[]
for _ in 1:dim-1 push!(all_dd,copy(listarray)) end
# create a data structure to store the minors (i.e. sub-determinants)
buffer_data = data.buffer_data
# empty_vector will be used to locally store the center at each level of iteration. This saves
# a lot of "memory allocation time"
empty_vector=zeros(Float64,dim)
# Bulk computations: V stores volumes y stores function values in a vector format
V = Vector([0.0])
# do the integration
I=Integrator
taboo = zeros(Int64,dim)
iterative_volume_fast(I,I._function, I.bulk, _Cell, V, bulk_inte, ar, inter_inte, dim, neigh,
_length,verteces,emptydict,emptydict,xs[_Cell],empty_vector,all_dd,buffer_data,calculate,Integral,xs,taboo,I.iterative_checker)
#error("")
return V[1]
end
function iterative_volume_fast(I,_function, _bulk, _Cell::Int64, V, y, A, Ay, dim,neigh,_length,verteces,verteces2,
emptylist,vector,empty_vector,all_dd,buffer_data,calculate,Full_Matrix,xs,taboo,dc,data = Vector{Pair{Vector{Int64},eltype(xs)}}())#::Tuple{Float64,Vector{Float64}}
space_dim=length(vector)
if (dim==1) # this is the case if and only if we arrived at an edge
#b, r, r2 = getedge(dc,verteces,space_dim,xs,_Cell)
#if !b
# return 0.0, Float64[]
#end
if length(verteces)<2
empty!(verteces)
return 0.0, Float64[]
end
r = data[verteces[1]][2]
r2 = data[verteces[2]][2]
vol = norm(r-r2)
#println(_Cell," vol ",vol)
A[1]+=vol
if (typeof(_function)!=Nothing)
return vol, 0.5*(_function(r)+_function(r2))*vol
end
return vol, Float64[]
elseif dim==space_dim
# get the center of the current dim-dimensional face. this center is taken
# as the new coordinate to construct the currenct triangle. The minors are stored in place space_dim-dim+1
#_Center=midpoint_points(verteces,verteces2,empty_vector,vector)
# dd will store to each remaining neighbor N a sublist of verteces which are shared with N
dd=Vector{Vector{Int64}}(undef,_length)
reset(buffer_data,length(neigh))
#println("Berechne $_Cell, $neigh")
for i in 1:_length dd[i]=Int64[] end
reset(dc,neigh,xs,_Cell,verteces,false)
for (sig2,r) in verteces # iterate over all verteces
sig = copy(sig2)
push!(data,sig=>r)
iii = length(data)
for _neigh in sig # iterate over neighbors in vertex
_neigh==_Cell && continue
index=_neigh_index(neigh,_neigh)
index==0 && continue
push!( dd[index] , iii) # push vertex to the corresponding list
end
end
taboo[dim]=_Cell
AREA=zeros(Float64,1)
vol = 0.0
base = typeof(_function)!=Nothing ? _function(vector) : Float64[]
integral = 0.0*base
for k in 1:_length
buffer=neigh[k] # this is the (further) common node of all verteces of the next iteration
# in case dim==space_dim the dictionary "bufferlist" below will contain all
# verteces that define the interface between "_Cell" and "buffer"
# However, when it comes to A and Ay, the entry "buffer" is stored in place "k".
#if !(buffer in calculate) && !(_Cell in calculate) continue end
if !(buffer in calculate)
empty!(dd[k])
continue
end
bufferlist=dd[k]
isempty(bufferlist) && continue
taboo[dim-1] = buffer
neigh[k]=0
AREA[1]=0.0
AREA_Int=(typeof(_function)!=Nothing) ? Ay[k] : Float64[]
# now get area and area integral either from calculation or from stack
if (buffer>_Cell) # in this case the interface (_Cell,buffer) has not yet been investigated
set_dimension(dc,1,_Cell,buffer)
#test_idc(dc,_Cell,buffer,1)
AREA_Int.*= (buffer in calculate) ? 0 : 1
_Center=midpoint_points_fast(bufferlist,data,empty_vector,vector)
_Center.+=vector # midpoint shifts the result by -vector, so we have to correct that ....
vol2, integral2 = iterative_volume_fast(I,_function, _bulk, _Cell, V, y, AREA, AREA_Int, dim-1, neigh, _length, bufferlist, emptylist, emptylist,vector,empty_vector,all_dd,buffer_data,nothing,Full_Matrix,xs,taboo,dc,data)
neigh[k]=buffer
# Account for dimension (i.e. (d-1)! to get the true surface volume and also consider the distance="height of cone")
empty!(bufferlist) # the bufferlist is empty
distance= 0.5*norm(vector-xs[buffer]) #abs(dot(normalize(vector-xs[buffer]),vert))
vol += vol2*distance
integral .+= integral2 .* distance
AREA_Int .= integral2
A[k] = vol2
else # the interface (buffer,_Cell) has been calculated in the systematic_voronoi - cycle for the cell "buffer"
#greife auf Full_Matrix zurück
empty!(bufferlist)
#empty!(bufferlist)
distance=0.5*norm(vector-xs[buffer])#abs(dot(normalize(vector-xs[buffer]),vert))
vol2 = get_area(Full_Matrix,buffer,_Cell)
# !!!!! if you get an error at this place, it means you probably forgot to include the boundary planes into "calculate"
vol += vol2*distance
A[k]=vol2
if typeof(_function)!=Nothing
AREA_Int.*=0
try
AREA_Int.+=get_integral(Full_Matrix,buffer,_Cell)
catch
println(neigh,buffer," k=$k, _Cell=$_Cell")
rethrow()
end
end
integral .+= AREA_Int .* distance
end
neigh[k]=buffer
end
vol /= dim
integral .+= vol .* base
integral ./= (dim+1)
V[1] = vol
y .= integral
return vol, integral
else
# the next three lines get the center of the current dim-dimensional face. this center is taken
# as the new coordinate to construct the currenct triangle. The minors are stored in place space_dim-dim+1
dd=all_dd[dim-1] # dd will store to each remaining neighbor N a sublist of verteces which are shared with N
buffer_data.center .= empty_vector
all_neighbors = dc.neighbors
lneigh = length(neigh)
_count=1
for k in 1:_length
_count+=neigh[k]!=0 ? 1 : 0 # only if neigh[k] has not been treated earlier in the loop
end
_my_neigh=Vector{Int64}(undef,_count-1)
while length(dd)<_count push!(dd,Int64[]) end
_count=1
for k in 1:_length
if (neigh[k]!=0) # only if neigh[k] has not been treated earlier in the loop
_my_neigh[_count]=neigh[k]
_count+=1
end
end
ll=(length(verteces))
for _ii in 1:(ll) # iterate over all verteces
(sig,r) = data[verteces[_ii]]
count = 0
for _neigh in sig # iterate over neighbors in vertex
(_neigh in taboo) && continue # if _N is a valid neighbor (i.e. has not been treated in earlier recursion)
index = _neigh_index(_my_neigh,_neigh)
#(index==0 ) && continue
index==0 && continue
push!( dd[index] , verteces[_ii]) # push vertex to the corresponding list
end
end
l_mn = length(_my_neigh)
for k in 1:(l_mn-1)
#neigh[k]==0 && continue
clear_double_lists_iterative_vol(buffer_data.sub,dd,k,data,_my_neigh)
end
_count=1
vol = 0.0
base = typeof(_function)!=Nothing ? _function(buffer_data.center) : Float64[]
integral = 0.0*base
next_ortho_dim = space_dim-dim+1
for k in 1:_length
buffer=neigh[k] # this is the (further) common node of all verteces of the next iteration
# in case dim==space_dim the dictionary "bufferlist" below will contain all
# verteces that define the interface between "_Cell" and "buffer"
# However, when it comes to A and Ay, the entry "buffer" is stored in place "k".
buffer==0 && continue
# bufferlist=dd[_neigh_index(_my_neigh,buffer)] # this one can be replaced by a simple counting of neigh!=0
bufferlist=dd[_count]
_count+=1
isempty(bufferlist) && continue
#clear_double_lists_iterative_vol(buffer_data.sub,dd,_count,)
valid = set_dimension(dc,next_ortho_dim,_Cell,buffer)
if !valid
empty!(bufferlist)
continue
end
fi = facett_identifier(dc,buffer_data,_Cell,buffer)
distance = projected_distance(dc,buffer_data.center,empty_vector,data[bufferlist[1]][2],next_ortho_dim) # ✓
#distance==0 && error("\n $(buffer_data.center), $(empty_vector), $(first(bufferlist)[2]), $next_ortho_dim \n $(dc.local_basis[1]), $(dc.local_basis[2])")
vol2, integral2 = 0.0, Float64[]
if !haskey(buffer_data.facets,fi)
_Center = midpoint_points_fast(bufferlist,data,empty_vector,vector) # ✓
_Center .+= vector
neigh[k]=0
taboo[dim-1]=buffer
vol2, integral2 = iterative_volume_fast(I,_function, _bulk, _Cell, V, y, A, Ay , dim-1, neigh, _length, bufferlist, emptylist, emptylist,vector,empty_vector,all_dd,buffer_data.sub,nothing,Full_Matrix,xs,taboo,dc,data)
neigh[k]=buffer
taboo[dim-1]=0
push!(buffer_data.facets,fi=>PolyBufferData(vol2,integral2))
else
pbd = buffer_data.facets[fi]
vol2 = pbd.volume
integral2 = pbd.integral
end
empty!(bufferlist)
vol += vol2*distance
if vol2!=0.0
integral .+= integral2 .* distance
end
end
vol /= dim
integral .+= vol .* base
integral ./= (dim+1)
return vol, integral
end
end
function projected_distance(dc,center,empty_vector,plane,dim)
dist = 0.0
empty_vector .= center
empty_vector .-= plane
for k in 1:dim
dist += abs2(dot(dc.local_basis[k],empty_vector))
end
return sqrt(dist)
end
function joint_neighs(vertices)
v1 = copy(first(vertices)[1])
intersect!(v1,keys(vertices)...)
return v1
end
function clear_double_lists_iterative_vol(::PolyBuffer,dd,_count,data,_my_neigh)
length(dd[_count])==0 && return
generators = copy(data[dd[_count][1]][1])
keep_similars!(generators,view(data,dd[_count]))
#intersect!(generators,keys(dd[_count])...)
# for (sig,r) in dd[_count]
# intersect!(generators,sig)
# end
v = dd[_count]
for k in (_count+1):length(_my_neigh)
( !(_my_neigh[k] in generators)) && continue
b = true
for index in dd[k]
#iii = searchsortedfirst(v, x)
#iii <= length(v) && v[iii] == x
if !(index in dd[_count])
b=false
break
end
end
b && empty!(dd[k])
end
end
function keep_similars!(sig::Vector{Int64},sig2::Vector{Int64},lsig=length(sig))
k=1
lsig2=length(sig2)
for i in 1:lsig
sig[i]==0 && continue
while k<=lsig2 && sig2[k]<sig[i]
k += 1
end
(k>lsig2 || sig[i]<sig2[k]) && (sig[i]=0)
end
return sig
end
function keep_similars!(sig::Vector{Int64},itr)
lsig = length(sig)
for tup in itr
sig2 = tup[1]
k=1
lsig2=length(sig2)
for i in 1:lsig
sig[i]==0 && continue
while k<=lsig2 && sig2[k]<sig[i]
k += 1
end
(k>lsig2 || sig[i]<sig2[k]) && (sig[i]=0)
end
end
return sig
end
function clear_double_lists_iterative_vol(::NoPolyBuffer,dd,k,data,_my_neigh)
l_mn = length(_my_neigh)
if length(dd[k])!=2
empty!(dd[k])
return
end
for i in (k+1):l_mn
length(dd[i])!=2 && continue
count = 0
for s1 in dd[k]
count += s1 in dd[i] ? 1 : 0
end
if count==2
empty!(dd[i])
end
end
end
#=
function dist_to_facett(Center,Midpoint,base)
difference=Center-Midpoint
dist=(-1)*sum(x->x^2,difference)
for i in 1:length(base)
dist+=dot(base[i],difference)^2
end
return sqrt(abs(dist))
end
=#
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 3987 | struct Filter{M <: AbstractMesh, F<:Function, II<:AbstractVector{Int64}}
mesh::M
iterate::II
affected::BitVector
condition::F
lm::Int64
lm_internal::Int64
function Filter(m::M, i::II,f::F) where {M <: AbstractMesh, F<:Function, II<:AbstractVector{Int64}}
_affected = falses(length(m))
_affected[i] .= true
new{M,F,II}(m, i, _affected, f, length(m),0)#internal_length(m))
end
end
@inline function mark_sig(_filter,sig)
for s in sig
(s>_filter.lm || s==0) && continue
_filter.affected[s] = true
end
end
function filter_data( condition, mesh,_depsig,_depr, affected)
depsig = StaticBool(_depsig)
depr = StaticBool(_depr)
parameter(sig,r,dep_sig::StaticTrue,dep_r::StaticTrue) = (sig,r)
parameter(sig,r,dep_sig::StaticTrue,dep_r::StaticFalse) = (sig,)
parameter(sig,r,dep_sig::StaticFalse,dep_r::StaticTrue) = (r,)
f = (sig,r)->condition(parameter(sig,r,depsig,depr)...)
getaffected(aff::AbstractVector{Bool},m) = view(1:length(m),aff)
getaffected(aff,m) = aff
getaffected(aff::UnitRange{Int},m) = collect(aff)
myaffected = getaffected(affected,mesh)
_filter = Filter(mesh,myaffected,condition)
return myaffected,_filter
end
#=
filtermesh!(mesh,my_affected,_filter)
cleanupfilter!(mesh,internal_index(mesh,i))
mark_sig(_filter,sig)
mark_delete_vertex!(_filter,vdb,sig)
mark_delete_bv!(mesh,edge,bv)
cleanupfilter_bv!(mesh)
boundary_vertices_iterator(mesh)
=#
@inline mark_delete_ref(_filter,sig,ref::Nothing) = nothing
#@inline mark_delete_ref(_filter,sig,ref::Int) = nothing
function mark_delete_ref(_filter,sig,ref::U) where {U<:Union{VertexRef,Int}}
il = internal_length(_filter.mesh)
for i in 2:length(sig)
s = sig[i]
s>il && continue
delete_reference(_filter.mesh,s,ref)
end
end
function filter!( condition, mesh::M,_depsig=StaticBool{true}(),_depr=StaticBool{true}(), _sig_internal=!_depsig; affected = 1:length(mesh),searcher=nothing) where {M<:AbstractMesh}
my_affected, _filter = filter_data( condition, mesh,_depsig,_depr, affected)
range = typeof(searcher)==Nothing ? (1:2) : ((length(mesh)+1):length(mesh)+length(searcher.domain))
#println("filter start")
for i in my_affected
#print("1")
activate_cell(searcher,i,range)
avi = all_vertices_iterator(_filter.mesh,internal_index(_filter.mesh,i),statictrue)
#print("2")
for (sig,r) in avi
#print("a")
ext_sig = external_sig(_filter.mesh,sig,statictrue)
#print("b")
if _sig_internal==statictrue ? !_filter.condition(sig,r) : !_filter.condition(ext_sig,r)
#print("A")
mark_sig(_filter,ext_sig)
#print("B")
ref = mark_delete_vertex!(_filter.mesh,sig,IterationIndex(avi))
#print("C")
mark_delete_ref(_filter,sig,ref)
#print("D")
end
#print("c")
end
#print("3")
end
#println("filter mitte")
for i in 1:_filter.lm
_filter.affected[i] && cleanupfilter!(mesh,internal_index(mesh,i)) # provide second arg in internal representation
end
#println("filter ende")
#return my_affected
end
""" filters verteces of `affected` according to `condition`. Does NOT reduce number of points. This must be done manually"""
function filter_bv!( condition, mesh::M,_depsig=StaticBool{true}(),_depr=StaticBool{true}(); affected = nodes_iterator(mesh) ) where {M<:AbstractMesh}
myaffected, _filter = filter_data( condition, mesh,_depsig,_depr, affected)
for (edge,bv) in boundary_vertices_iterator(mesh)
if !_filter.condition(edge,bv) # if sig consists only of affected cells
mark_delete_bv!(mesh,edge,bv)
end
end
cleanupfilter_bv!(mesh)
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 23786 | #function remove_symbol(sym, kwargs)
function FVevaluate_boundary(f)
result(;kw...)=f(kw[:x_j])
return result
end
"""
struct VoronoiFVProblem{...}
after initialization the struct contains the following information:
- `Geometry` : a `VoronoiGeometry` containing mesh and integrated information
- `Coefficients` : Not advised to be accessed by user
- `Parent` : Not advised to be accessed by user
- `projection_down` : Not advised to be accessed by user
- `projection_up` : Not advised to be accessed by user
- `parameters` : Not advised to be accessed by user
"""
struct VoronoiFVProblem{TC,TP,TPA,TDI,TDJ,VG<:VoronoiGeometry,VD<:VoronoiData}
Geometry::VG
Coefficients::TC
Parent::TP
parameters::TPA
voronoidata::VD
my_data_i::TDI
my_data_j::TDJ
end
function VoronoiFVProblem_validate(;discretefunctions=NamedTuple(), integralfunctions=NamedTuple(), fluxes=NamedTuple(), rhs_functions=NamedTuple())
if typeof(fluxes)!=Nothing
if !(typeof(fluxes)<:NamedTuple) error("The field `fluxes` must be given as a NamedTuple") end
for f in fluxes
array = typeof(f)<:Tuple && length(f)>1 ? f[2] : Int64[]
for i in array
if boundary.planes[i].BC>0 error("boundary #$i is periodic but you want to prescribe Neumann conditions there") end
end
end
end
typeof(integralfunctions)!=Nothing && !(typeof(integralfunctions)<:NamedTuple) && error("The field 'integralfunctions' must be given as a NamedTuple")
typeof(discretefunctions)!=Nothing && !(typeof(discretefunctions)<:NamedTuple) && error("The field 'discretefunctions' must be given as a NamedTuple")
end
function VoronoiFVProblem(Geo::VoronoiGeometry; discretefunctions=NamedTuple(), integralfunctions=NamedTuple(), fluxes=NamedTuple(), rhs_functions=NamedTuple(), parent=nothing, integrator=Integrator_Type(Geo.Integrator), flux_integrals=NamedTuple(), bulk_integrals=NamedTuple(), kwargs...)
VoronoiFVProblem_validate(discretefunctions=discretefunctions, integralfunctions=integralfunctions, fluxes=fluxes, rhs_functions=rhs_functions)
if !(Geo.Integrator in [VI_HEURISTIC,VI_MONTECARLO,VI_POLYGON,VI_FAST_POLYGON,VI_HEURISTIC_MC])
error("The Geometry comes up with an integrator of type $(Integrator_Name(Geo.Integrator)). This type does not provide relyable volume or area data.")
end
points=nodes(mesh(integral(Geo.domain)))#integral.MESH.nodes
#= i_functions = nothing
i_composer = undef
ref_function_length = 0
if typeof(integralfunctions)!=Nothing=#
i_composer = FunctionComposer(;(integralfunctions...,reference_argument= points[1],super_type=Float64)...)
i_functions = i_composer.functions
ref_function_length = i_composer.total #length(i_functions(points[1]))
# end
data=VoronoiData(Geo,copyall=true)
# adjust data from mean to "pointwise":
if length(data.bulk_integral)>0
for i in 1:length(data.nodes)
data.bulk_integral[i].*=(1.0/data.volume[i])
end
for i in 1:length(data.nodes) # check if integral data is OK.
if isdefined(data.bulk_integral,i)
if length(data.bulk_integral[i])!=ref_function_length
println("WARNING: length of bulk_integral[...] does not match the size of function data ...")
end
break
end
end
end
if length(data.interface_integral)>0
for i in 1:length(data.nodes)
for j in 1:length(data.area[i])
if (data.area[i][j]>0)
data.interface_integral[i][j].*=(1.0/data.area[i][j])
end
end
end
for i in 1:length(data.nodes) # check if integral data is ok
if isdefined(data.interface_integral,i) && length(data.interface_integral[i])>0
if length(data.interface_integral[i][1])!=ref_function_length
println("WARNING: length of interface_integral[...] does not match the size of function data ...")
end
break
end
end
end
# i_func = typeof(i_functions)!=Nothing ? HighVoronoi.extract_discretefunctions(data,i_composer) : (bulk=i->NamedTuple{}(),interface=(i,j)->NamedTuple{}())
# d_func = typeof(discretefunctions)!=Nothing ? HighVoronoi.extract_discretefunctions(data;discretefunctions...) : (bulk=i->NamedTuple{}(),interface=(i,j)->NamedTuple{}())
#@descend HighVoronoi.extract_discretefunctions(data,i_composer)
# i_func = HighVoronoi.extract_discretefunctions(data,i_composer)
d_func = HighVoronoi.extract_discretefunctions(data;discretefunctions...)
_bb = length(data.bulk_integral)>0
_bbb = length(data.interface_integral)>0 && length(data.interface_integral[1])>0
b_funcs = i->Base.merge(d_func[:bulk](i), map(__simplify_discrete,decompose(i_composer,_bb ? data.bulk_integral[i] : i_composer.reference_value)))
i_funcs = (i,j)->Base.merge(d_func[:interface](i,j),map(__simplify_discrete,decompose(i_composer,_bbb ? data.interface_integral[i][j] : i_composer.reference_value)) )
##=#
# b_funcs = i->merge(i_func[:bulk](i),d_func[:bulk](i))
# i_funcs = (i,j)->merge(i_func[:interface](i,j),d_func[:interface](i,j))
my_data_i(i) = get_data_i(b_funcs,i_funcs,data,i)
my_data_j(i,n) = get_data_j(b_funcs,i_funcs,data,i,n,Geo.domain.boundary.planes)
VoronoiFVProblemCoefficients(data, Geo.domain.boundary, my_data_i, my_data_j, fluxes=fluxes, functions=rhs_functions, flux_integrals=flux_integrals, bulk_integrals=bulk_integrals)
coefficients = VoronoiFVProblemCoefficients(data, Geo.domain.boundary, my_data_i, my_data_j, fluxes=fluxes, functions=rhs_functions, flux_integrals=flux_integrals, bulk_integrals=bulk_integrals)
parameters = (; kwargs..., discretefunctions=discretefunctions, integralfunctions=integralfunctions, fluxes=fluxes, rhs_functions=rhs_functions, integrator=integrator)
return VoronoiFVProblem(Geo,coefficients,parent,parameters,data,my_data_i,my_data_j)
end
function VoronoiFVProblem(points, boundary=Boundary(); discretefunctions=nothing, integralfunctions=nothing, fluxes=nothing, rhs_functions=nothing, flux_integrals=nothing, bulk_integrals=nothing, integrator=VI_POLYGON, integrand=nothing, kwargs...)
VoronoiFVProblem_validate(discretefunctions=discretefunctions, integralfunctions=integralfunctions, fluxes=fluxes, rhs_functions=rhs_functions)
!(integrator in [VI_POLYGON,VI_MONTECARLO]) && error("Calculating area or volume is not provided by $(Integrator_Name(integrator)).")
i_functions = nothing
i_composer = undef
if typeof(integralfunctions)!=Nothing
i_composer = FunctionComposer(;(integralfunctions...,reference_argument=points[1],super_type=Float64)...)
i_functions = i_composer.functions
end
Geo = VoronoiGeometry(points,boundary; kwargs..., integrand=i_functions, integrator=integrator)
return VoronoiFVProblem(Geo,discretefunctions=discretefunctions, integralfunctions=integralfunctions, fluxes=fluxes, rhs_functions=rhs_functions ; kwargs..., integrand=i_functions, integrator=integrator, flux_integrals=flux_integrals, bulk_integrals=bulk_integrals)
end
function get_Bulkintegral(VP::VoronoiFVProblem,symb)
return VP.Coefficients.bulkintegrals[symb]
end
function get_Fluxintegral(VP::VoronoiFVProblem,symb)
return VP.Coefficients.fluxintegrals[symb]
end
"""
VoronoiFVProblem(Geo::VoronoiGeometry; parent = nothing) # first variant
VoronoiFVProblem(points, boundary; integrator = VI_POLYGON, kwargs...) # second variant
Generates Finite Volume data for fluxes and right hand sides given either a `VoronoiGeometry` object or a set of points and a boundary,
which will serve to internally create a `VoronoiGeometry`. Allows for the following parameters:
- `kwargs...` : arguments that are not listed explicitly below will be passed to the VoronoiGeometry. `integrand` will be overwritten.
- `parent`: If `parent` is generated from `Geo_p` and `Geo` is a refined version of `Geo_p` this parameter will initiate the calculation
of an ``L^{1}`` projection operator between the spaces of piecewise constant functions on the respective Voronoi Tessellations.
- `discretefunctions=nothing` : A named tuple of form `(alpha=x->norm(x),f=x->-x,)`. Will be evaluated pointwise.
- `integralfunctions=nothing` : A named tuple of form `(alpha=x->norm(x),f=x->-x,)`. It will make the algoritm calculate the integrals
over the given functions or it will associate values to the list of functions based on integrated data present in `Geo`
- `fluxes=nothing` : this is assumed to be named tuple, e.g. like the following:\n
fluxes = (alpha = f1, beta = f2, eta = f3, zeta = f4, )
and every of the given fluxes `alpha`, `beta`, `eta`, `zeta`, has the following structure:
It is one single flux-function accessing the following named data (see also [here in the Documentation](@ref parameter_names)):\n
x_i, x_j, para_i, para_j, para_ij, mass_i, mass_j, mass_ij, normal
and returning two values. Functions `f1`, `f2` ... should hence be defined similar to the following:\n
function f1(;x_i,x_j,para_ij, kwargs...)
# some code
return something_i, something_j
end
Refer to the examples in the documentation.
!!! note "standard settings"
if the array of Neumann-planes is not provided, the standard list given in `boundary` resp. the boundary in `Geo` will be used.
- `rhs_functions=nothing`: same as for fluxes. However, functions can only access the variables\n
x_i, mass_i, para_i,
"""
VoronoiFVProblem()
#######################################################################################################################
## VoronoiFV_Problem_Parameters
#######################################################################################################################
struct VoronoiFVProblemCoefficients{TF,TFU,TFI,BFI,TI}
rows::Vector{Int64}
cols::Vector{Int64}
firstindex::Vector{Int64}
fluxes::TF
functions::TFU
fluxintegrals::TFI
bulkintegrals::BFI
index::TI
end
function VoronoiFVProblemCoefficients(data::VoronoiData, boundary, my_data_i, my_data_j; fluxes=NamedTuple(), functions=NamedTuple, flux_integrals=NamedTuple(), bulk_integrals=NamedTuple())
nodes = data.nodes
neighbors = data.neighbors
lnodes = length(nodes)
lboundary = length(boundary)
r=Int64[]
c=Int64[]
f=Vector{Int64}(undef,lnodes+lboundary)
neighbors_of_boundary = Vector{SparseVector{Int64,Int64}}(undef,lboundary)
for i in 1:lboundary
neighbors_of_boundary[i] = sparsevec(Int64[],Int64[],lnodes)
end
_f=1
for i in 1:lnodes
f[i] = _f
_r, _c = setindeces(i,neighbors[i],neighbors_of_boundary,lnodes) # warning: assumes that neighbors are sorted !
append!(r,_r)
append!(c,_c)
_f += length(_c)
end
for i in 1:lboundary
f[i+lnodes] = _f
_r=nonzeros(neighbors_of_boundary[i])
append!(r,_r)
append!(c,(lnodes+i).*ones(Int64,length(_r)))
_f += length(_r)
end
#println(f)
#println(c)
#println(r)
index(i,j) = get_data_index(r,c,f,i,j,lnodes,lboundary)
#_neumann_planes = split_boundary_indeces(boundary)[2]
myfluxes = map(f->conservative_flux(f,data,boundary,index,length(r),my_data_i,my_data_j),fluxes)
myrhs = map(f->right_hand_side(f,length(nodes),my_data_i),functions)
myfluxint = map(f->flux_integral(f,data,boundary,index,length(r),my_data_i,my_data_j),flux_integrals)
mybulkint = map(f->bulk_integral(f,length(nodes),my_data_i),bulk_integrals)
return VoronoiFVProblemCoefficients{typeof(myfluxes),typeof(myrhs),typeof(myfluxint),typeof(mybulkint),typeof(index)}(r,c,f,myfluxes,myrhs,myfluxint,mybulkint,index)
end
function get_data_index(rows,cols,firstindex,i,j,lnodes,lboundary)
ret = firstindex[j]
maxindex = j<lnodes+lboundary ? firstindex[j+1] : length(rows)
while rows[ret]!=i && ret<=maxindex
ret+=1
end
return ret
end
function get_data_i(bulkfunctions,interfacefunctions,data,i,j=0)
hasbulk = typeof(bulkfunctions)!=Nothing
bf_i = bulkfunctions(i)
result = (x_i=data.nodes[i], para_i=bf_i, mass_i=data.volume[i],cell=i)
return result
end
function get_data_j(bulkfunctions,interfacefunctions,data,i,n,planes)
j=data.neighbors[i][n]
nodes = data.nodes
lmesh = length(data.nodes)
hasbulk = typeof(bulkfunctions)!=Nothing
hasinterface = typeof(interfacefunctions)!=Nothing
bf_j = bulkfunctions(j<=lmesh ? j : i)
bf_ij = interfacefunctions(i,n) ## not clear if n or j is the correct choice. j fails....
b = j>lmesh
on_b = data.boundary_nodes_on_boundary
xj = b ? data.boundary_nodes[i][j] : nodes[j]
vj = b ? data.volume[i] : data.volume[j]
result = (x_j=xj, para_j=bf_j, para_ij=bf_ij,
mass_j=vj, mass_ij=data.area[i][n],normal=data.orientations[i][n],
points_onboundary=on_b, onboundary=b,neighbor=j,
bc=j>lmesh ? planes[j-lmesh].BC : 1)
return result
end
function setindeces(_Cell,neighbors,neighbors_of_boundary,lmesh)
r = zeros(Int64, length(neighbors) + 1)
for i in 1:length(neighbors)
r[i]=neighbors[i]
if neighbors[i]>lmesh
neighbors_of_boundary[neighbors[i]-lmesh][_Cell]=_Cell
end
end
r[length(neighbors)+1]=_Cell
sort!(unique!(r))
c = _Cell .* ones(Int64,length(r))
return r, c
end
function get_Int_Array(list,preset)
return typeof(list)<:Vector{Int} ? list : (typeof(list)<:Int ? [list] : Int64[])
end
function conservative_flux(my_flux,data::VoronoiData,boundary,index,size,my_data_i,my_data_j,_NEUMANN=Int64[])
nodes = data.nodes
lmesh = length(nodes)
flux = my_flux
values=zeros(Float64,size)
for i in 1:lmesh
neigh=data.neighbors[i]
_para_i = my_data_i(i)
for n in 1:length(neigh)
j=neigh[n]
if j<i continue end
_para_j = my_data_j(i,n)
part_i, part_j = flux(;_para_i...,_para_j...)
#values[index(i,i)]+=part_i
values[index(i,j)]+=(-1)*part_j
values[index(j,i)]+=(-1)*part_i
end
end
return values
end
function flux_integral(my_flux,data::VoronoiData,boundary,index,size,my_data_i,my_data_j,_NEUMANN=Int64[])
nodes = data.nodes
lmesh = length(nodes)
flux = my_flux
integral = 0.0
for i in 1:lmesh
neigh=data.neighbors[i]
_para_i = my_data_i(i)
for n in 1:length(neigh)
j=neigh[n]
if j<i continue end
_para_j = my_data_j(i,n)
integral += flux(;_para_i...,_para_j...)
end
end
return integral
end
function right_hand_side(f,size,my_data_i)
rhs(i) = f(;my_data_i(i)...)
values=Vector{typeof(rhs(1))}(undef,size)
for i in 1:size
values[i]=rhs(i)
end
return values
end
function bulk_integral(f,size,my_data_i)
rhs(i) = f(;my_data_i(i)...)
integral = 0.0 *rhs(1)
for i in 1:size
integral += rhs(i)
end
return integral
end
#######################################################################################################################
## VoronoiFVLinear
#######################################################################################################################
"extracts for each boundary index the correct neumann or dirichlet function from two normed lists"
function extract_BC(neumann,dirichlet,len)
harmonic = x->0.0
funcs = Vector{Any}(undef,len)
funcs.=harmonic
f = list->map( tup->( map( k-> ( funcs[k] = tup[2]), tup[1] ) ) ,list)
#f = list->map( tup->( println(tup) ) ,list)
f(neumann)
f(dirichlet)
return funcs
end
"""
linearVoronoiFVProblem(vd::VoronoiFVProblem;flux)
Takes a `VoronoiFVProblem` and a `flux::Symbol` and creates a linear problem. `flux` has to refer to a flux created in `vd`.
# Optional arguments
- `rhs`: a `Symbol` referring to one of the `rhs_functions` or a vector of `Float64` of the same length as the number of nodes.
If not provided, the system assumes `rhs=zeros(Float64,number_of_nodes)`.
- `Neumann`: Can be provided in the forms
* `(Int,Function,Int[.],Function,(Int[.],Function),...)`. Every `Function` depends on `(;kwargs...)`
and represents ``J*ν`` on a single boundary plane `Int` or multiple planes `Int[.]`.
* `Function` then it takes the Neumann boundaries given by the definition of the boundary of the domain, unless nothing is reinterpreted as Dirichlet boundary.
- `Dirichlet`: Can be provided in the form `(Int,Function,Int[.],Function,(Int[.],Function),...)`. Every `Function` depends on `(;kwargs...)`
and represents ``u_0`` on a single boundary plane `Int` or multiple planes `Int[.]`.
!!! note "`FVevaluate_boundary`"
Use `FVevaluate_boundary(f)` if you simply want `f` to be evaluated pointwise at the boundary nodes.
!!! note "Standard boundary conditions and consistency"
The algorithm will take zero Neumann
resp. zero Dirichlet as standard in case no other information is provided by the user. However, it is the
users responsibility to make sure there are no double specifications given in `Neumann` and `Dirichlet`.
# Return values
rows, cols, vals, rhs = linearVoronoiFVProblem(vd::VoronoiFVProblem;flux,kwargs...)
- `rows, cols, vals` are the row and coloumn indeces of values. Create e.g. `A=sparse(rows,cols,vals)` and sovle\n ``A*u=rhs``
"""
function linearVoronoiFVProblem(vd::VoronoiFVProblem;flux,rhs=nothing,Neumann=nothing,Dirichlet=nothing,bulk=(1:(length(vd.voronoidata.nodes))),enforcement_node=1)
if !(typeof(flux)<:Symbol) || !haskey(vd.Coefficients.fluxes,flux)
error("linearVoronoiFVProblem: you need to provide a flux as Symbol in the VoronoiFVProblem data. You provided flux=$flux instead.")
end
data = vd.voronoidata
myrhs=Float64[]
if typeof(rhs)<:AbstractVector && length(rhs)==length(vd.voronoidata.nodes)
myrhs=copy(rhs)
elseif typeof(rhs)==Nothing
myrhs=zeros(Float64,length(vd.voronoidata.nodes))
elseif typeof(rhs)<:Symbol && haskey(vd.Coefficients.functions,rhs)
myrhs=copy(vd.Coefficients.functions[rhs])
#mrhs.*=vd.voronoidata.volume
else
error("linearVoronoiFVProblem: if you provide `rhs` it needs to be <:AbstractVector or a Symbol in the VoronoiFVProblem data. You provided rhs=$rhs instead.")
end
values = vd.Coefficients.fluxes[flux]
index = vd.Coefficients.index
datamax = vd.Coefficients.firstindex[length(vd.voronoidata.nodes)+1]-1
myvalues = copy(view(values,1:datamax))
rows = copy(view(vd.Coefficients.rows,1:datamax))
cols = copy(view(vd.Coefficients.cols,1:datamax))
keep = map(k->(rows[k] in bulk),collect(1:length(rows)))
flux_data = vd.parameters[:fluxes][flux]
boundary = vd.Geometry.domain.boundary
lmesh = length(data.nodes)
harmonic = FVevaluate_boundary(x->0.0)
# println(Neumann)
_PERIODIC, _NEUMANN, _DIRICHLET = split_boundary_indeces(boundary)
neumann_bc, neurange = unify_BC_format(Neumann,_NEUMANN, typeof(Neumann)<:Function ? Neumann : harmonic)
dirichlet_bc, dirrange = unify_BC_format(Dirichlet,_DIRICHLET, typeof(Dirichlet)<:Function ? Dirichlet : harmonic)
# println("first:")
# println(neurange)
# println(dirrange)
deleteat!( neumann_bc[1][1], map( k->(neumann_bc[1][1][k] in dirrange), collect(1:length(neumann_bc[1][1])) ) )
deleteat!( dirichlet_bc[1][1], map( k->(dirichlet_bc[1][1][k] in neurange), collect(1:length(dirichlet_bc[1][1])) ) )
# println("second:")
# println(neurange)
# println(dirrange)
_NEUMANN = neurange
#println(neumann_bc)
#println(dirichlet_bc)
# calculate the boundary functions and store the boundary conditions in a unified sparse vector data structure
bc_functions = sparsevec(collect(1:length(boundary)).+length(data.nodes), extract_BC(neumann_bc,dirichlet_bc,length(boundary)), length(data.nodes)+length(boundary) )
bc_conditions = sparsevec(_NEUMANN.+length(data.nodes),-1.0*ones(Float64,length(_NEUMANN)),length(data.nodes)+length(boundary))
# println(bc_conditions)
#return keepat!(rows,keep), keepat!(cols,keep), keepat!(myvalues,keep) , myrhs
need_enforcement = true
for k in 1:length(boundary)
if !((k in _PERIODIC) || (bc_conditions[lmesh+k]<0))
need_enforcement = false
break
end
end
for i in 1:length(vd.voronoidata.nodes)
neighbors = vd.voronoidata.neighbors[i]
my_i = vd.my_data_i(i)
index_ii = index(i,i)
for j in 1:length(neighbors)
n = neighbors[j]
if (n in bulk)
#println(values[index(n,i)])
# print("|$(round(values[index(n,i)]))")
myvalues[index_ii] += (-1)*values[index(n,i)]
continue
end
my_j = vd.my_data_j(i,j)
u = (-1)*(bc_functions[n])(;my_i...,my_j...)
if bc_conditions[n]<0 # Neumann case
myrhs[i] += u * my_j[:mass_ij]
#print("|$u $(round(values[index(n,i)]))")
#myvalues[index_ii] += (-1)*values[index(n,i)]
else #Dirichlet case
# abs(u)!=0 && println("$u, $(values[index(i,n)])")
myrhs[i] += values[index(i,n)] * u
# n==401 && print("*$(round(values[index(i,n)] * u)) $(round(values[index(n,i)]))")
myvalues[index_ii] += (-1)*values[index(n,i)]
end
end
end
if need_enforcement
neighbors = vd.voronoidata.neighbors[enforcement_node]
for i in neighbors
i==enforcement_node && continue
myvalues[index(i,enforcement_node)] = 0.0
myvalues[index(enforcement_node,i)] = 0.0
end
myvalues[index(enforcement_node,enforcement_node)] = 1.0
myrhs[enforcement_node] = 0.0
end
return keepat!(rows,keep), keepat!(cols,keep), keepat!(myvalues,keep) , myrhs
end
"takes a tuple of form ([1], x->0.0, ([3],x->x^2), ) and returns a formated tuple of type ( ( [1], x->0.0 ), ). Also prepends a (range,standard) tuple."
function unify_BC_format(BC,range,standard)
list = ((range,standard),)
myrange = Int64[]
if typeof(BC)<:Tuple
for i in 1:length(BC)
if typeof(BC[i])<:Tuple && length(BC[i])>1
!(typeof(BC[i][2])<:Function) && continue
my_BC = typeof(BC[i][1])<:Vector{Int} ? BC[i][1] : [BC[i][1]]
list = (list...,(my_BC,BC[i][2]))
append!(myrange,my_BC)
elseif length(BC)>i && typeof(BC[i+1])<:Function
my_BC = typeof(BC[i])<:Vector{Int} ? BC[i] : (typeof(BC[i])<:Int ? [BC[i]] : continue)
list = (list...,(my_BC,BC[i+1]))
append!(myrange,my_BC)
end
end
end
return list, myrange
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 31706 | """
VoronoiGeometry{T}
This is the fundamental struct to store information about the generated Voronoi grid. The geometric data can be accessed using the type `VoronoiData`.
However, there is always the possibility to access the data also via the following fields:
- Integrator.Integral: stores the integrated values in terms of a `Voronoi_Integral`
- basic_mesh: stores the fundamental data of nodes and verteces. also stored in Integrator.Integral.MESH
- nodes: direct reference to the nodes. Also provided in basic_mesh.nodes
!!! warning "Avoid direct access to the data"
Accessing the data directly, that is without calling `VoronoiData`, is likely to cause confusion or to provide "wrong" information.
The reason is that particularly for periodic boundary conditions, the mesh is enriched by a periodization of the boundary nodes.
These nodes are lateron dropped by the VoronoiData-Algorithm.
"""
struct VoronoiGeometry{T,TT,SNP,DT,MC,HVF}#<:Union{HVFile,NoFile}}
Integrator::T
adress::Vector{Int64}
domain::DT
integrand::TT
status::Vector{Bool}
searcher::SNP
mc_accurate::MC
file::HVF
function VoronoiGeometry(Integrator,domain,integrand,searcher,mc_accurate,file)
return new{typeof(Integrator),typeof(integrand),typeof(searcher),typeof(domain),typeof(mc_accurate),typeof(file)}(Integrator,[0],domain,integrand,[false],searcher,mc_accurate,file)
end
end
const PGeometry{P} = VoronoiGeometry{T,TT,SNP,DT,MC,HVF} where {P,T,TT,SNP,DT<:AbstractDomain{P},MC,HVF}
const ClassicGeometry = VoronoiGeometry{T,TT,SNP,DT,MC,HVF} where {T,TT,SNP,DT<:Voronoi_Domain,MC,HVF}
@inline Base.getproperty(cd::VoronoiGeometry, prop::Symbol) = dyncast_get(cd,Val(prop))
@inline @generated dyncast_get(cd::VoronoiGeometry, ::Val{:nodes}) = :(nodes(mesh(integral(getfield(cd,:domain)))))
@inline @generated dyncast_get(cd::VoronoiGeometry, ::Val{:mesh}) = :(mesh(integral(getfield(cd,:domain))))
@inline @generated dyncast_get(cd::VoronoiGeometry, ::Val{:integral}) = :(integral(getfield(cd,:domain)))
@inline @generated dyncast_get(cd::VoronoiGeometry, ::Val{:refined}) = :(getfield(cd,:status)[1])
@inline @generated dyncast_get(cd::VoronoiGeometry, d::Val{S}) where S = :( getfield(cd, S))
@inline Base.setproperty!(cd::VoronoiGeometry, prop::Symbol, val) = dyncast_set(cd,Val(prop),val)
@inline @generated dyncast_set(cd::VoronoiGeometry, ::Val{:refined},val) = :(getfield(cd,:status)[1]=val)
@inline @generated dyncast_set(cd::VoronoiGeometry, d::Val{S},val) where S = :( setfield(cd, S,val))
@inline mesh(vg::VoronoiGeometry) = mesh(vg.domain)
@inline integral(vg::VoronoiGeometry) = integral(vg.domain)
@inline function Base.open(func::Function,vg::VG) where {VG<:VoronoiGeometry}
#open(vg.file) do ff
func(vg)
#end
end
function show(vg::VoronoiGeometry)
lrf = length(vg.refined)
println("VoronoiGeometry with Integrator ",Integrator_Name(vg.Integrator)," on $(length(vg.Integrator.Integral.MESH.nodes)-lrf) nodes.")
println(" $lrf additional internal nodes.")
println(" search options: ", vg.searcher)
println(boundaryToString(vg.domain.boundary,offset=5))
end
"""
VoronoiGeometry(xs::Points,b::Boundary)
This creates a Voronoi mesh from the points `xs` given e.g. as an array of `SVector` and a boundary `b` that might be constructed using
the commands in the Boundaries section.
You have the following optional commands:
- `silence`: Suppresses output to the command line when `true`. The latter will speed up the algorithm by a few percent. default is `false`.
- `integrator`: can be either one of the following values:
* `VI_GEOMETRY`: Only the basic properties of the mesh are provided: the verteces implying a List of neighbors of each node
* `VI_MONTECARLO`: Volumes, interface areas and integrals are calculated using a montecarlo algorithm.
This particular integrator comes up with the following additional paramters:
+ `mc_accurate=(int1,int2,int3)`: Montecarlo integration takes place in `int1` directions, over `int2`
volumetric samples (vor volume integrals only). It reuses the same set of directions `int3`-times to save memory allocation time.
Standard setting is: `(1000,100,20)`.
* `VI_POLYGON`: We use the polygon structure of the mesh to calculate the exact values of interface area and volume. The
integral over functions is calculated using the values at the center, the verteces and linear interpolation between.
* `VI_HEURISTIC`: When this integrator is chosen, you need to provide a fully computed Geometry including volumes and interface areas.
`VI_HEURISTIC` will then use this information to derive the integral values.
* `VI_HEURISTIC_MC`: This combines directly `VI_MONTECARLO` calculations of volumes and interfaces and calculates integral values
of functions based on those volumes and areas. In particular, it also relies on `mc_accurate`!
- `integrand`: This is a function `f(x)` depending on one spatial variable `x` returning a `Vector{Float64}`.
The integrated values will be provided for each cell and for each pair of neighbors, i.e. for each interface
- `periodic_grid`: This will initiate a special internal routine to fastly create a periodic grid. Look up the section in the documentation.
# With density distribution:
VoronoiGeometry(number::Int,b=Boundary();density, kwargs...)
this call genertates a distribution of approsximately `number` nodes and generates a `VoronoiGeometry`. It takes as parameters all of the
above mentioned keywords (though `periodic_grid` makes no sense) and all keywords valid for a call of VoronoiNodes(number;domain=b,density=density, ....)
In future versions, there will be an implementation of the parameter `cubic=true`, where the grid will be generated based on a distribution of "cubic" cells. In the current version there will be a warning that this is not yet implemented.
# Advanced methods
VoronoiGeometry(file::String)
VoronoiGeometry(VG::VoronoiGeometry)
Loads a Voronoi mesh from the `file` or copies it from the original data `VG`. If `integrator` is not provided, it will use the original integrator stored to the file.
In the second case, if integrand is not provided explicitly, it will use `integrand = VG.integrand` as standard.
Additionally it has the following options:
- `_myopen=jldopen`: the method to use to open the file. See the section on `write_jld`.
- `vertex_storage`: Defines the way data is stored internally. standard is the most recent and most efficient method `DatabaseVertexStorage()`. Other options are the
`ReferencedVertexStorage()` which is slower but may be useful in low dimensions and the `ClassicVertexStorage()` which is fast for integration algorithms in
low dimensions and which was the first database structure underlying the computations. This parameter can of course only be set upon the very first creation of
the geometry and cannot be modified afterwards.
- `search_settings`: a `NamedTuple` mostly to provide `(method = ... ,threading = ...)` where `method` chooses the Raycast method and `threading` provides information
on the multithreading
- `offset`: See the section on `write_jld`.
- `integrate=false`: This will or will not call the integration method after loading/copying the data. Makes sense for using `VI_HEURISTIC` together with
`volume=true`, `area=true` and providing values for `integrand` and `integrand`. If `integrand != nothing` but `bulk==false` or `interface==false`
this parameter will internally be set `true`.
- `volume=true`: Load volume data from file
- `area=true`: Load interface area data from file
- `bulk=false`: Load integrated function values on the cell volumes from file. When set `true` and `integrand=f` is provided
the method will compare the dimension of `f` and of the stored data.
- `interface=false`: Load integrated function values on the interfaces. When set `true` and `integrand=f` is provided
the method will compare the dimension of `f` and of the stored data.
"""
VoronoiGeometry()
function VoronoiGeometry(number::Int,b=Boundary();cubic=false,bounding_box=Boundary(),criterium = x->true, density=x->1.0, range=nothing ,periodic_grid=nothing,kwargs...)
if cubic
@warn "cubic mesh generation based on density currently not implemented"
end
return VoronoiGeometry(VoronoiNodes(number,domain=b,bounding_box=bounding_box,criterium = criterium, density=density, range=range),b;kwargs...)
end
function cast_mesh(gs,xs::HVNodes{P}) where {P}
__get_refs(::Nothing) = nothing
__get_refs(i) = Int64[]
mesh = Voronoi_MESH(xs,__get_refs(gs),gs)
#println(typeof(mesh.references))
get_mesh(::Nothing,m) = m
get_mesh(i,m) = SerialMeshVector(m)
return get_mesh(gs,mesh)
end
function VoronoiGeometry(xs::Points,b=Boundary(); vertex_storage=DatabaseVertexStorage(),improving=(max_iterations=0, tolerance=1.0,), search_settings::NamedTuple=NamedTuple(), integrator=VI_GEOMETRY,integrand=nothing,mc_accurate=(1000,5,20),periodic_grid=nothing,silence=false,printevents=false,integrate=true)
oldstd = stdout
result = nothing
check_boundary(xs,b)
#xs=UnsortedNodes(xs)
try
if typeof(periodic_grid)!=Nothing
return PeriodicVoronoiGeometry(xs,vertex_storage=vertex_storage, integrator=integrator,integrand=integrand,mc_accurate=mc_accurate,search_settings=search_settings,silence=silence;periodic_grid...)
else
myintegrator = replace_integrator(IntegratorType(integrator))
redirect_stdout(silence ? devnull : oldstd)
#vertex_storage = haskey(search_settings,:threading) ? change_db_type(vertex_storage,search_settings.threading) : vertex_storage
!silence && println(Crayon(foreground=:red,underline=true), "Initialize bulk mesh with $(length(xs)) points",Crayon(reset=true))
search=RaycastParameter(eltype(eltype(xs));search_settings...)
#println(typeof(search))
mmm = cast_mesh(vertex_storage,copy(xs))
voronoi(mmm,searcher=Raycast(xs;domain=b,options=search),intro="",printsearcher=printevents, silence=silence)
d2 = Create_Discrete_Domain(mmm,b,intro="",search_settings=search) # periodized version including all boundary data
improve_mesh(d2; improving..., printevents=printevents,search=search)
lboundary = length(b)
integrate_geo(integrate,d2,myintegrator,integrand,mc_accurate,collect(1:public_length(d2)),collect(1:(length(mesh(d2))+lboundary)),silence)
result = VoronoiGeometry(myintegrator,d2,integrand,search,mc_accurate,nothing)#NoFile())
end
catch err
redirect_stdout(oldstd)
rethrow()
end
redirect_stdout(oldstd)
return result
end
function integrate_geo(threading::MultiThread,d2,myintegrator,integrand,mc_accurate,relevant,modified,silence=false)
integral = integrate_view(d2).integral
ref_mesh = mesh(integral)
_threads = create_multithreads(threading,true)
list , tops = partition_indices(length(relevant),_threads)
# new views on integral for parallel computation
integrals = map(i->IntegralView(integral,SwitchView(list[i],tops[i])),1:length(_threads)) # pulls the current nodes list[i]...tops[i] to the first places
parallel_integrals = Parallel_Integrals(integrals,myintegrator)
# transformation of relevants for respective computation
relevants = map(i->copy(view(relevant,list[i]:tops[i])),1:length(list))
#println(relevants)
map(i->sort!(_transform_indeces(ref_mesh,mesh(integrals[i]),relevants[i])),1:length(relevants))
#println(relevants)
#list2 = copy(list)
#list2 .= modified[1]
# transformation of modifieds for respective computation
m1 = modified[1]
tops2 = copy(tops)
for i in 1:(length(list)-1)
tops2[i] = searchsortedlast(modified,relevant[tops[i]])
end
modifieds_ = map(i->copy(view(modified,m1:tops2[i])),1:length(tops2))
rest = copy(view(modified,(tops2[end]+1):length(modified)))
#println(modifieds_)
#println(rest)
modifieds = map(i->CombinedSortedVector(sort!(_transform_indeces(ref_mesh,mesh(integrals[i]),modifieds_[i])),rest),1:length(modifieds_))
#println(modifieds)
add_sync(synchronizer(parallel_integrals[1]),length(parallel_integrals)) # this sets the number of sync waits to the number of threads that will be called.
II2s = map(inte->Integrator(inte,myintegrator,integrand=integrand,mc_accurate=mc_accurate),parallel_integrals)
myintes2 = map(ii2->backup_Integrator(ii2,true),II2s)
myintes = parallelize_integrators(myintes2)
intro="$(Integrator_Name(myintes[1]))-integration over $(length(relevant)) cells:"
progress = ThreadsafeProgressMeter(2*length(relevant),silence,intro)
Threads.@threads for i in 1:length(parallel_integrals)
#for i in 4:-1:1
HighVoronoi.integrate(myintes[i],domain=internal_boundary(d2),relevant=relevants[i],modified=modifieds[i],progress=progress)
end
end
parallelize_integrators(myintes2) = myintes2
@inline integrate_geo(integrate::SingleThread,d2,myintegrator,integrand,mc_accurate,relevant,modified,silence=false) = integrate_geo(true,d2,myintegrator,integrand,mc_accurate,relevant,modified,silence)
@inline function integrate_geo(integrate::Bool,d2,myintegrator,integrand,mc_accurate,relevant,modified,silence=false)
!integrate && return
II2=Integrator(integrate_view(d2).integral,myintegrator,integrand=integrand,mc_accurate=mc_accurate)
myinte=backup_Integrator(II2,true)
intro="$(Integrator_Name(myinte))-integration over $(length(relevant)) cells:"
HighVoronoi.integrate(myinte,domain=internal_boundary(d2),relevant=relevant,modified=modified,progress=ThreadsafeProgressMeter(2*length(relevant),false,intro))
end
function VoronoiGeometry(file::String,proto=nothing; _myopen=jldopen, offset="", search_settings=(__useless=0,), integrate=false, volume=true,area=true,bulk=false,interface=false,integrator=VI_GEOMETRY,integrand=nothing,mc_accurate=(1000,100,20),periodic_grid=nothing,silence=false)
oldstd = stdout
result = nothing
try
if typeof(periodic_grid)!=Nothing
@warn "The parameter 'periodic_grid' makes no sense when a geometry is loaded..."
end
println(Crayon(foreground=:red,underline=true), "Load geometry from file $file:",Crayon(reset=true))
myintegrator = replace_integrator(IntegratorType(integrator))
I2=UndefInitializer
_domain=UndefInitializer
xs=UndefInitializer
mesh=UndefInitializer
_myopen(file, "r") do myfile
if read(myfile, offset*"version")!=1
error("The version of this file format is not compatible with your HighVoronoi distribution. It is recommended to update your version.")
end
mesh=load_MESH(myfile,offset,proto)
xs=mesh._nodes
println(" mesh with $(length(xs)) nodes loaded")
_domain=load_Domain(myfile,mesh,offset)
vp_print(_domain.boundary,offset=4)
println(" Load Data: ", volume ? "volumes, " : "", area ? "areas, " : "", bulk ? "bulk integrals, " : "", interface ? "interface integrals, " : "")
redirect_stdout(silence ? devnull : oldstd)
load_Integral(myfile,_domain._integral,volume,area,bulk,interface,offset)
end
d2 = _domain
b = boundary(_domain)
II2=Integrator(integrate_view(d2).integral,myintegrator,integrand=integrand,mc_accurate=mc_accurate)
lboundary = length(b)
myinte = backup_Integrator(II2,true)
integrate && HighVoronoi.integrate(myinte,domain=internal_boundary(d2),relevant=collect(1:public_length(d2)),modified=collect(1:(length(mesh(d2))+lboundary)))
result = VoronoiGeometry(myintegrator,d2,integrand,RaycastParameter(Float64),mc_accurate,nothing)#NoFile())
redirect_stdout(oldstd)
catch
redirect_stdout(oldstd)
rethrow()
end
return result
end
@inline Base.copy(VG::VoronoiGeometry) = VoronoiGeometry(VG,silence=true,integrate=false)
function VoronoiGeometry(VG::VoronoiGeometry; search_settings=NamedTuple(), periodic_grid=nothing, integrate=false, volume=true,area=true,bulk=false,interface=false, integrator=VG.Integrator,integrand=VG.integrand,mc_accurate=VG.mc_accurate,silence=false)
oldstd = stdout
result = nothing
try
if typeof(periodic_grid)!=Nothing
warning("feature 'periodic_grid' not implemented for 'VoronoiGeometry(VG::VoronoiGeometry;kwargs...)'. I will simply ignore this...")
end
search = merge(VG.searcher,search_settings)
myintegrator = replace_integrator(IntegratorType(integrator))
println(Crayon(foreground=:red,underline=true), "Copy geometry ...",Crayon(reset=true))
_integrate = integrate # || (typeof(integrand)!=Nothing )
println(" mesh with $(length(mesh(VG.domain))) nodes copied")
d2 = deepcopy(VG.domain)
b = boundary(d2)
vp_print(boundary(d2),offset=4)
redirect_stdout(silence ? devnull : oldstd)
II2=Integrator(integrate_view(d2).integral,myintegrator,integrand=integrand,mc_accurate=mc_accurate)
lboundary = length(b)
myinte=backup_Integrator(II2,true)
integrate && HighVoronoi.integrate(myinte,domain=internal_boundary(d2),relevant=collect(1:public_length(d2)),modified=collect(1:(length(mesh(d2))+lboundary)))
result = VoronoiGeometry(myintegrator,d2,integrand,search,mc_accurate,VG.file)
redirect_stdout(oldstd)
catch
redirect_stdout(oldstd)
rethrow()
end
return result
end
#=function VoronoiGeometry(NON::Int,ρ;search_settings=[], periodic_grid=nothing, integrate=false, integrator=VI_GEOMETRY,return_unkown=false, integrand=nothing,mc_accurate=(1000,100,20),silence=false)
samplenodes = VoronoiNodes()
end
=#
###############################################################################################################################
## Memory usage inside VoronoiGeometry .....
###############################################################################################################################
#=function memory_allocations(vg::VoronoiGeometry;verbose=false)
return memory_usage(vg,verbose)
end
function memory_usage(x,verbose=false,step=0)
size = sizeof(x)
typeof(x)==HighVoronoi.Boundary && (verbose=false)
mystring = ""
if typeof(x) <: AbstractArray # Check if it's an array
for item in x
size += memory_usage(item,verbose,step+1)[1]
end
elseif typeof(x) <: AbstractDict # Check if it's a dictionary
for (key, value) in x
size += memory_usage(key,verbose,step+1)[1]
size += memory_usage(value,verbose,step+1)[1]
end
elseif isstructtype(typeof(x)) # Check if it's a struct
for field in fieldnames(typeof(x))
mysize = 0
newstring = ""
if field==:Buffer_Verteces
bv = getfield(x, field)
mysize = sizeof(bv)+2*length(bv)*8
elseif field==:searcher
mysize = sizeof(getfield(x, field))
else
mysize, newstring = memory_usage(getfield(x, field),verbose,step+1)
end
size += mysize
mystring *= verbose ? (" "^step)*"$field: $mysize \n"*newstring : ""
end
end
if step==0
verbose && println("Total size: $size")
verbose && println(mystring)
return size
end
return size, mystring
end
=#
###############################################################################################################################
## Refine, Integrate, Copy .....
###############################################################################################################################
function refine!(VG::VoronoiGeometry,xs::Points,update=true;silence=false,search_settings=NamedTuple())
println(Crayon(foreground=:red,underline=true), "Refine discrete geometry with $(length(xs)) points:",Crayon(reset=true))
domain = VG.domain
oldstd = stdout
old_length = public_length(VG.domain)
redirect_stdout(silence ? devnull : oldstd)
try
my_settings = RaycastParameter(VG.searcher,search_settings)
_modified=systematic_refine!(domain,xs,intro="",search_settings=my_settings)
VG.refined=true
if typeof(update)<:Union{SingleThread,MultiThread} || (update==true)
println("updating...")
println(Crayon(foreground=:red,underline=true), "Start integration on refined cells:",Crayon(reset=true))
MESH, Integral = integrate_view(domain)
sort!(_external_indeces(MESH,_modified))
lmesh = length(MESH)
append!(_modified,collect((1+lmesh):(lmesh+length(boundary(domain)))),collect((old_length+1):(old_length+length(xs))))
sort!(unique!(_modified))
_relevant=Base.intersect(_modified,collect(1:public_length(domain)))
sort!(_relevant)
integrate_geo(update,VG.domain,VG.Integrator,VG.integrand,VG.mc_accurate,_relevant,_modified,silence)
VG.refined=false
end
catch
redirect_stdout(oldstd)
rethrow()
end
redirect_stdout(oldstd)
return VG
end
function refine(VG::VoronoiGeometry,xs::Points,update=true;silence=false,search_settings=(__useless=0,))
return refine!(copy(VG),xs,update,silence=silence,search_settings=search_settings)
end
function periodic_bc_filterfunction(sig,periodic)
for i in length(sig):-1:1
# (sig[i]<periodic[1]) && (return true)
(sig[i] in periodic) && (return false)
end
return true
end
"""
indeces_in_subset(VG::VoronoiGeometry,B::Boundary)
returns all indeces of `VG` lying within `B`.
"""
function indeces_in_subset(VG::VoronoiGeometry,B::Boundary)
nodes = HighVoronoi.nodes(mesh(VG.domain))#Integrator.Integral.MESH.nodes
lref = length(VG.domain.references)
li = length(nodes)
indeces = collect(1:(li-lref))
for i in (lref+1):li
(!(nodes[i] in B)) && (indeces[i-lref] = 0)
end
return filter!(i->i!=0,indeces)
end
function shift_boundarynodes(sig,lmesh,offset)
for k in 1:length(sig)
n = sig[k]
if n> lmesh
sig[k] += offset
end
end
end
function integrate!(VG::VoronoiGeometry)
integrate(backup_Integrator(VG.Integrator,VG.refined[1]),domain=VG.domain.boundary,relevant=(1+length(VG.domain.references)):(length(VG.Integrator.Integral)+length(VG.domain.boundary)))
VG.refined[1]=false
end
function copy_Integral_content(Inte,I2,volume,area,bulk,interface)
Inte2=I2.Integral
empty!(Inte2.neighbors)
append!(Inte2.neighbors,deepcopy(Inte.neighbors))
if volume
empty!(Inte2.volumes)
append!(Inte2.volumes,copy(Inte.volumes))
end
# println(Inte.area)
if area
empty!(Inte2.area)
append!(Inte2.area,deepcopy(Inte.area))
end
#println(Inte2.area)
if bulk
empty!(Inte2.bulk_integral)
append!(Inte2.bulk_integral,deepcopy(Inte.bulk_integral))
end
if interface
empty!(Inte2.interface_integral)
append!(Inte2.interface_integral,deepcopy(Inte.interface_integral))
end
end
###############################################################################################################################
## Store and Load Data
###############################################################################################################################
"""
The data can be stored using the `write_jld` method:
write_jld(Geo::VoronoiGeometry,filename,offset="";_myopen=jldopen)
write_jld(Geo::VoronoiGeometry,file,offset="")
stores the complete information of a VoronoiGeometry object to a file. This information can later be retrieved using the `VoronoiGeometry(file::String, args...)` function.
- `Geo`: The Voronoi geometry object to be stored
- `filename`: name of file to store in
- `file`: A file given in a format supporting `write(file,"tagname",content)` and `read(file,"tagname",content)`
- `offset`: If several Geometry objects are to be stored in the same file, this will be the possibility to identify each one by a unique name. In particular, this is the key to store several objects in one single file.
- `_myopen`: a method that allows the syntax `_myopen(filename,"w") do myfile ....... end`. By default the method uses the `JLD2` library as this (at the point of publishing this package) has the least problems with converting internal data structure to an output format.
!!! warning "Filname extension"
If you want to use the default method, then the filename should end on `.jld`. Otherwise there might be confusion by the abstract built in julia loading algorithm.
"""
function write_jld()
end
function write_jld(Geo::ClassicGeometry,filename::String,offset="";_myopen=jldopen)
_myopen(filename, "w") do file
write_jld(Geo,file,offset)
end
end
function write_jld(Geo::ClassicGeometry,file,offset="")
#_myopen(filename, "w") do file
I=integral(Geo.domain)
storevalues=BitVector([length(I.volumes)>0,length(I.area)>0,length(I.bulk_integral)>0,length(I.interface_integral)>0])
write(file,offset*"version",1)
write(file, offset*"type", Integrator_Number(Geo.Integrator))
write(file, offset*"compactdata", CompactVoronoiData(length(mesh(integral(Geo.domain)))-length(references(Geo.domain)),length(references(Geo.domain)),length(dimension(Geo.domain)),1))
#write(file, "onenode", I.MESH.nodes[1])
write(file, offset*"nodes", I.MESH._nodes)
write(file, offset*"All_Verteces", I.MESH.All_Vertices)
write(file, offset*"neighbors", I.neighbors)
write(file, offset*"storevalues", storevalues)
write(file, offset*"volumes", I.volumes)
write(file, offset*"area", I.area)
write(file, offset*"bulk_integral", I.bulk_integral)
write(file, offset*"interface_integral", I.interface_integral)
write(file, offset*"boundary", Geo.domain.boundary)
write(file, offset*"boundary_Verteces", I.MESH.boundary_Vertices)
write(file, offset*"internal_boundary", Geo.domain.internal_boundary)
write(file, offset*"shifts", Geo.domain.shifts)
write(file, offset*"reference_shifts", Geo.domain.reference_shifts)
write(file, offset*"references", Geo.domain.references)
end
"""
If you want to make sure that the data you load will be rich enough, compact information can be retrieved as follows:
load_Voronoi_info(filname,offset="")
This will print out compact information of the data stored in file `filename` and the offset `offset`. Yields dimension, number of nodes, number of internal nodes and the dimension of the stored integrated data.
Note that the latter information is of particular importance since here is the highest risk for the user to mess up stored data with the algorithm.
"""
function load_Voronoi_info(filename::String,offset="")
l = nothing
jldopen(filename, "r") do myfile
l = load_Voronoi_info(myfile,offset)
end
return l
end
""" returns CompactData on stored Geometry """
load_Voronoi_info(file,offset="") = read(file, offset*"compactdata")
function load_MESH(file,offset="",proto=nothing)
return load_MESH(file,offset)
end
function load_MESH(file,offset::String)
nodes = read(file, offset*"nodes")
av = read(file, offset*"All_Verteces")
bv = VectorOfDict([0]=>nodes[1],length(nodes))
bounV = read(file, offset*"boundary_Verteces")
mesh = _ClassicMesh(nodes, av, bv, bounV)
return mesh
end
function load_Boundary(file,str)::Boundary
return read(file, str)
end
function load_Domain(filename::String,mesh,offset="",_myopen=jldopen)
domain = UndefInitializer
_myopen(filename, "r") do file
domain = load_Domain(file,mesh,offset)
end
return domain
end
function load_Domain(file,mesh,offset="")
return Voronoi_Domain(mesh,load_Boundary(file, offset*"boundary"), read(file, offset*"shifts"), read(file, offset*"reference_shifts"), read(file, offset*"references"), load_Boundary(file, offset*"internal_boundary"))
end
function load_Integral(filename::String,I2,volume,area,bulk,interface,offset="")
Inte=I2.Integral
jldopen(filename, "r") do file
Inte = load_Integral(file,I2,volume,area,bulk,interface,offset)
end
return Inte
end
function load_Integral(file,Inte,volume,area,bulk,interface,offset="")
empty!(Inte.neighbors)
append!(Inte.neighbors,read(file,offset*"neighbors"))
storevalues=read(file,offset*"storevalues")
if volume
if !(storevalues[1])
println(" WARNING: you want to load volumes but there are no volumes stored")
else
vol=read(file,offset*"volumes")
empty!(Inte.volumes)
append!(Inte.volumes,vol)
end
end
if area
if !(storevalues[2])
println(" WARNING: you want to load areas but there are no areas stored")
else
ar=read(file,offset*"area")
empty!(Inte.area)
append!(Inte.area,ar)
end
end
if bulk
if !(storevalues[3])
println(" WARNING: you want to load bulk integral data but there are no such data stored")
else
bu=read(file,offset*"bulk_integral")
empty!(Inte.bulk_integral)
append!(Inte.bulk_integral,bu)
end
end
if interface
if !(storevalues[4])
println(" WARNING: you want to load interface integral data but there are no such data stored")
else
bu=read(file,offset*"interface_integral")
empty!(Inte.interface_integral)
append!(Inte.interface_integral,bu)
end
end
return Inte
end
###############################################################################################################################
## CompactData
###############################################################################################################################
struct CompactVoronoiData
numberOfNodes::Int64
numberOfInternalNodes::Int64
dimension::Int64
integrand::Int64
end
function Base.show(io::IO, C::CompactVoronoiData)
println(io," entry ",offset,":")
println(io," dimension: $(C.dimension) ; nodes: $(C.numberOfNodes) ; internal nodes: $(C.numberOfInternalNodes) ; dimension of integral data: $(C.integrand) ")
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 7455 | # We provide the Heuristic_Integrator. It is defined and initialized similar to
# the MC
struct Heuristic_Integrator{T,TT}
_function::T
bulk::Bool
Integral::TT
function Heuristic_Integrator{T,TT}(f::T,b::Bool,I::TT) where {T,TT}
return new(f,b,I)
end
#=function Heuristic_Integrator(mesh::AbstractMesh,integrand=nothing, bulk_integral=false)
b_int=(typeof(integrand)!=Nothing) ? bulk_integral : false
i_int=(typeof(integrand)!=Nothing) ? true : false
Integ=Voronoi_Integral(mesh,integrate_bulk=b_int, integrate_interface=i_int)
PI=Heuristic_Integrator{typeof(integrand),typeof(Integ)}( integrand, b_int, Integ )
return PI
end=#
function Heuristic_Integrator(Integ::HVIntegral,integrand=nothing, bulk_integral=false)
b_int = bulk_integral || (typeof(integrand) != Nothing)
enable(Integ,integral=b_int)
PI=Heuristic_Integrator{typeof(integrand),typeof(Integ)}( integrand, b_int, Integ )
return PI
end
end
function backup_Integrator(I::Heuristic_Integrator,b)
return b ? Polygon_Integrator(I._function,I.bulk,I.Integral) : I
end
function copy(I::Heuristic_Integrator)
return Heuristic_Integrator{typeof(I._function),typeof(I.Integral)}(I._function,I.bulk,copy(I.Integral))
end
@inline function integrate(Integrator::Heuristic_Integrator; progress=ThreadsafeProgressMeter(0,true,""), domain=Boundary(), relevant=1:(length(Integrator.Integral)+length(domain)), modified=1:(length(Integrator.Integral)))
_integrate(Integrator; domain=domain, calculate=modified, iterate=relevant,progress=progress)
end
#function integrate(Integrator::Heuristic_Integrator; domain=Boundary(), relevant=1:(length(Integrator.Integral)+length(domain)), modified=1:(length(Integrator.Integral)))
#println("PolyInt: ")#$(length(relevant)), $(length(modified))")
# _integrate(Integrator; domain=domain, calculate=relevant, iterate=Base.intersect(union(modified,relevant),1:(length(Integrator.Integral))))
#end
function prototype_bulk(Integrator::Heuristic_Integrator)
y = (typeof(Integrator._function)!=Nothing && Integrator.bulk) ? Integrator._function(nodes(mesh(Integrator.Integral))[1]) : Float64[]
y.*= 0.0
return y
end
function prototype_interface(Integrator::Heuristic_Integrator)
return 0.0*(typeof(Integrator._function)!=Nothing ? Integrator._function(nodes(mesh(Integrator.Integral))[1]) : Float64[])
end
"""
initialize_integrator(xs,_Cell,verteces,edges,integrator::Heuristic_Integrator)
The integrator is initialized at beginning of systematic_voronoi(....) if an MC_Function_Integrator is passed as a last argument
This buffer version of the function does nothing but return two empty arrays:
- The first for Volume integrals. The first coordinate of the vector in each node
corresponds to the volume of the Voronoi cell
- The second for Area integrals. The first coordinate of the vector on each interface
corresponds to the d-1 dimensional area of the Voronoi interface
"""
#function integrate(domain,_Cell,iter,calcul,searcher,Integrator::Heuristic_Integrator)
function integrate(neighbors,_Cell,iterate, calculate, data,Integrator::Heuristic_Integrator,ar,bulk_inte,inter_inte,_)
#println(bulk_inte)
#println(inter_inte)
#println(ar)
Integral = Integrator.Integral
(typeof(Integrator._function) == Nothing) && (return Integral.volumes[_Cell])
verteces = vertices_iterator(mesh(Integral),_Cell)
#println(verteces)
xs=data.extended_xs
dim = data.dimension # (full) Spatial dimension
# get all neighbors of this current cell
neigh=neighbors
_length=length(neigh)
# flexible data structure to store the sublists of verteces at each iteration step 1...dim-1
emptydict=EmptyDictOfType([0]=>xs[1]) # empty buffer-list to create copies from
# empty_vector will be used to locally store the center at each level of iteration. This saves
# a lot of "memory allocation time"
empty_vector=zeros(Float64,dim)
# do the integration
I=Integrator
bulk_inte .= 0.0
_heuristic_integral(I._function, I.bulk, _Cell, bulk_inte, ar, inter_inte, dim, neigh,
_length,verteces,emptydict,xs[_Cell],empty_vector,calculate,Integral,xs)
#println(bulk_inte)
#println(inter_inte)
#println(ar)
try
cdw = cell_data_writable(Integral,_Cell,nothing,nothing,get_integrals=staticfalse)
return cdw.volumes[1]
catch
return 0.0
end
end
function _heuristic_integral(_function, _bulk, _Cell::Int64, y, A, Ay, dim,neigh,_length,verteces,
emptylist,vector,empty_vector,calculate,Full_Matrix,xs)
# dd will store to each remaining neighbor N a sublist of verteces which are shared with N
dd=Vector{typeof(emptylist)}(undef,_length)
for i in 1:_length dd[i]=copy(emptylist) end
for (sig,r) in verteces # iterate over all verteces
for _neigh in sig # iterate over neighbors in vertex
_neigh==_Cell && continue
index=_neigh_index(neigh,_neigh)
index==0 && continue #(push!( dd[index] , sig =>r)) # push vertex to the corresponding list
if (_neigh>_Cell || isempty(dd[index])) # make sure for every neighbor the dd-list is not empty
push!( dd[index] , sig =>r) # push vertex to the corresponding list
end
end
end
#= for (sig,r) in verteces2 # repeat in case verteces2 is not empty
for _neigh in sig
_neigh==_Cell && continue
index=_neigh_index(neigh,_neigh)
index==0 && continue
if (_neigh>_Cell || isempty(dd[index])) # make sure for every neighbor the dd-list is not empty
push!( dd[index] , sig =>r) # push vertex to the corresponding list
end
end
end=#
for k in 1:_length
buffer=neigh[k]
if !(buffer in calculate)
empty!(dd[k])
continue
end
bufferlist=dd[k]
isempty(bufferlist) && continue
AREA_Int = Ay[k] # always: typeof(_function)!=Nothing
AREA_Int.*=0
_Center = midpoint_points(bufferlist,emptylist,empty_vector,vector)
_Center .+= vector # midpoint shifts the result by -vector, so we have to correct that ....
count = 0
while !(isempty(bufferlist))
_,r=pop!(bufferlist)
AREA_Int .+= _function(r)
count+=1
end
AREA_Int .*= (dim-1)/(dim*count)
AREA_Int .+= (1/dim).*_function(_Center)
#println(AREA_Int)
data = cell_data_writable(Full_Matrix,_Cell,nothing,nothing,get_integrals=staticfalse)
thisarea = data.area[k]
AREA_Int .*= thisarea
# print("*")
if _bulk # and finally the bulk integral, if whished
# print("b")
distance= 0.5*norm(vector-xs[buffer]) #abs(dot(normalize(vector-xs[buffer]),vert))
_y=_function(vector)
_y.*=(thisarea/(dim+1))
_y.+=(AREA_Int*(dim/(dim+1))) # there is hidden a factor dim/dim which cancels out
_y.*=(distance/dim)
y.+=_y
end
end
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 2379 | struct HeuristicMCIntegrator{T,I1,I2<:Heuristic_Integrator,I3<:Montecarlo_Integrator}
Integral::I1
heuristic::I2
mc::I3
f::T
end
function HeuristicMCIntegrator(mesh::Voronoi_MESH,f, mc_accurate=(1000,1,20))
mc_accurate = (mc_accurate[1],1,mc_accurate[3])
mc = Integrator(mesh,VI_MONTECARLO,mc_accurate=mc_accurate,integrand=nothing)
heu = Integrator(mesh,VI_HEURISTIC_INTERNAL,integrand=f,mc_accurate=mc_accurate,integral=mc.Integral)
lmesh = length(mesh)
resize!(mc.Integral.interface_integral,lmesh)
resize!(mc.Integral.bulk_integral,lmesh)
resize!(mc.Integral.area,lmesh)
return HeuristicMCIntegrator(mc.Integral,heu,mc,f)
end
function HeuristicMCIntegrator(Inte::HVIntegral,f, mc_accurate=(1000,1,20))
mc_accurate = (mc_accurate[1],1,mc_accurate[3])
mc = Integrator(Inte,VI_MONTECARLO,mc_accurate=mc_accurate,integrand=f)
heu = Integrator(Inte,VI_HEURISTIC_INTERNAL,integrand=f,mc_accurate=mc_accurate)
return HeuristicMCIntegrator(Inte,heu,mc,f)
end
backup_Integrator(I::HeuristicMCIntegrator,b) = I
function copy(I::HeuristicMCIntegrator)
mc2 = copy(I.mc)
heu2 = Integrator(mc.Integral,type=VI_HEURISTIC_INTERNAL,integrand=I.f)
return HeuristicMCIntegrator{typeof(I.f)}(mc2.Integral,heu2,mc2,I.f)
end
function integrate(Integrator::HeuristicMCIntegrator; progress=ThreadsafeProgressMeter(0,true,""), domain=Boundary(), relevant=1:(length(Integrator.Integral)+length(domain)), modified=1:(length(Integrator.Integral)))
_integrate(Integrator; domain=domain, calculate=modified, progress=progress, iterate=relevant)
end
function prototype_bulk(Integrator::HeuristicMCIntegrator)
return prototype_bulk(Integrator.heuristic)
end
function prototype_interface(Integrator::HeuristicMCIntegrator)
return prototype_interface(Integrator.heuristic)
end
@inline function integrate(neighbors,_Cell,iterate, calculate, data,Integrator::HeuristicMCIntegrator,ar,bulk_inte,inter_inte,vol)
#=println(neighbors)
println(ar)
println(inter_inte)=#
vol[1] = integrate(neighbors,_Cell,iterate, calculate, data,Integrator.mc,ar,bulk_inte,inter_inte,vol)
#println(ar)
#println(inter_inte)
return integrate(neighbors,_Cell,iterate, calculate, data,Integrator.heuristic,ar,bulk_inte,inter_inte,vol)
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 6715 |
# Definiere einen abstrakten Datentyp HVDataBase
abstract type HVDataBase{P<:Point, IV<:AbstractVector{Int64}} end
PointType(::Type{HVD}) where {P, IV, HVD<:HVDataBase{P, IV}} = P
VectorType(::Type{HVD}) where {P, IV, HVD<:HVDataBase{P, IV}} = IV
PointType(::HVD) where {P, IV, HVD<:HVDataBase{P, IV}} = P
VectorType(::HVD) where {P, IV, HVD<:HVDataBase{P, IV}} = IV
blocksize(::Type{HVD}) where {P, IV, HVD<:HVDataBase{P, IV}} = begin
dimension = size(P)[1]
return (1+2*dimension) * round(Int,lowerbound(dimension,dimension))
end
blocksize(::HVD) where {P, IV, HVD<:HVDataBase{P, IV}} = begin
dimension = size(P)[1]
return (1+2*dimension) * round(Int,lowerbound(dimension,dimension))
end
################ Expected Functionality:
## push!(::HKD, sig=>r) : returns Int64 - Index
## get(::HKD, index) : returns sig=>r for index
## haskey(::HKD, sig) : returns whether has key or not.
##############################################################################################################################################################
##############################################################################################################################################################
## HeapDataBase
##############################################################################################################################################################
##############################################################################################################################################################
mutable struct HeapDataBase{P, RI, Q<:QueueHashTable} <: HVDataBase{P, Vector{Int64}}
data::Vector{Vector{Int64}}
floatview::Vector{RI}
keys::Q
blocksize::Int64
position::Int64
buffer_sig::Vector{Vector{Int64}}
buffer_r::Vector{Vector{Float64}}
lock::ReadWriteLock
nthreads::Int64
# Konstruktor für HeapDataBase
function HeapDataBase(::Type{P},_blocksize::Int64) where {P}
data = Vector{Vector{Int64}}() # Initialisiere leeres data
RI = typeof(Base.reinterpret(Float64,Int64[]))
floatview = Vector{RI}() # Initialisiere leeres floatview
queue = QueueHashTable(_blocksize,SingleThread())
nth = Threads.nthreads()
#new{P, RI, typeof(queue)}(data, floatview, queue, _blocksize,_blocksize #=position=blocksize??=#,[Int64[] for i in 1:nth],[Float64[] for i in 1:nth],ReadWriteLock(),nth)
new{P, RI, typeof(queue)}(data, floatview, queue, _blocksize,_blocksize,[Int64[] for i in 1:nth],[Float64[] for i in 1:nth],ReadWriteLock(),nth)
end
end
indexvector(::HDB) where {HDB<:HeapDataBase} = Vector{Int64}()
@inline function push_entry!(hdb::HDB,d::Float64) where {HDB<:HeapDataBase}
hdb.position +=1
if hdb.position>hdb.blocksize
push!(hdb.data,Vector{Int64}(undef,hdb.blocksize))
push!(hdb.floatview,Base.reinterpret(Float64,hdb.data[end]))
hdb.position = 1
end
hdb.floatview[end][hdb.position] = d
end
@inline function push_entry!(hdb::HDB,d::Int64) where {HDB<:HeapDataBase}
hdb.position +=1
if hdb.position>hdb.blocksize
push!(hdb.data,Vector{Int64}(undef,hdb.blocksize))
push!(hdb.floatview,Base.reinterpret(Float64,hdb.data[end]))
hdb.position = 1
end
hdb.data[end][hdb.position] = d
end
function push!(hdb::HDB,d::AV) where {HDB<:HeapDataBase,R<:Real,AV<:AbstractVector{R}}
@inline db(::Type{Float64},hd) = hd.floatview[end]
@inline db(::Type{Int64},hd) = hd.data[end]
l = length(d)
if (l>hdb.blocksize-hdb.position)
for dd in d
push_entry!(hdb,dd)
end
else
mydb = db(R,hdb)
view(mydb,(hdb.position+1):(hdb.position+l)) .= d
hdb.position += l
end
end
function push!(hdb::HDB,pair::P) where {HDB<:HeapDataBase,P<:Pair}
sig = pair[1]
r = pair[2]
writelock(hdb.lock)
pushqueue!(hdb.keys,sig)
push_entry!(hdb,length(sig))
pos = hdb.position + hdb.blocksize*(length(hdb.data)-1)
push!(hdb,sig)
push!(hdb,r)
writeunlock(hdb.lock)
if pos==0
open("protokol.txt","a") do f
write(f,"hier geht's shon los in push!(HDB) \n")
end
end
return pos
end
@inline haskey(hdb::HDB,key::K) where {HDB<:HeapDataBase,K} = begin
readlock(hdb.lock)
r = haskey(hdb.keys,key)
readunlock(hdb.lock)
return r
end
function read_from_db(data,buffer_,pos,block,l,blocksize)
if length(buffer_)<l
resize!(buffer_,l)
end
sig = view(buffer_,1:l)
l1 = blocksize-pos
if (l<=l1)
sig .= view(data[block],(pos+1):(pos+l))
else
view(buffer_,1:l1) .= view(data[block],(pos+1):(pos+l1))
#try
view(buffer_,(l1+1):l) .= view(data[block+1],1:(l-l1))
#catch
# error("$(length(data[block+1])), $blocksize")
#end
end
return sig
end
function rescale_db(hdb::HDB) where {P,HDB<:HeapDataBase{P}}
writelock(hdb.lock)
nth = Threads.nthreads()
resize(hdb.buffer_sig,nth)
resize(hdb.buffer_r,nth)
for i in (hdb.nthreads+1):nth
hdb.buffer_sig = Int64[]
hdb.buffer_r = Float64[]
end
hdb.nthreads = nth
writeunlock(hdb.lock)
end
function get_entry(hdb::HDB,index) where {P,HDB<:HeapDataBase{P}}
id = Threads.threadid()
id>hdb.nthreads && rescale_db(hdb)
pos = mod(index,hdb.blocksize)
block = div(index,hdb.blocksize)+1
if pos==0
pos = hdb.blocksize
block -= 1
end
readlock(hdb.lock)
#if pos==0 || block==0
# open("protokol.txt","a") do f
# write(f,"Pos: $pos, Block: $block, Index: $index \n")
# end
#end
@inbounds l = hdb.data[block][pos]
if l<0
readunlock(hdb.lock)
return (view(hdb.buffer_sig[id],1:0),zeros(P))
end
sig = read_from_db(hdb.data,hdb.buffer_sig[id],pos,block,l,hdb.blocksize)
pos2 = pos + l
if (pos2>=hdb.blocksize)
pos2 -= hdb.blocksize
block += 1
end
r = P(read_from_db(hdb.floatview,hdb.buffer_r[id],pos2,block,length(P),hdb.blocksize))
readunlock(hdb.lock)
return (sig,r)
end
function Base.delete!(hdb::HDB,index,key) where {P,HDB<:HeapDataBase{P}}
pos = mod(index,hdb.blocksize)
block = div(index,hdb.blocksize)+1
if pos==0
pos = hdb.blocksize
block -= 1
end
#print("*")
writelock(hdb.lock)
hdb.data[block][pos]*=-1
delete!(hdb.keys,key)
writeunlock(hdb.lock)
#print("/")
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 7880 | Base.islocked(::Nothing) = false
@inline function active_wait(i)
ii = 0
for _ in 1:rand(1:min(i,10))
ii+=1
end
end
struct BusyLock
locked::Atomic{Bool}
function BusyLock()
new(Atomic{Bool}(false))
end
end
# @inline Base.lock
@inline function Base.lock(bl::BusyLock)
ii = UInt64(0)
while atomic_cas!(bl.locked, false, true)
for j in (1:(rand(1:100)))
ii+=1
end
end
end
# @inline Base.unlock
@inline function Base.unlock(bl::BusyLock)
bl.locked[] = false
end
# @inline Base.trylock
@inline function Base.trylock(bl::BusyLock)
return !atomic_cas!(bl.locked, false, true)
end
# @inline Base.islocked
@inline function Base.islocked(bl::BusyLock)
return bl.locked[]
end
struct BusyFIFOLock
head::Atomic{Int64}
tail::Atomic{Int64}
function BusyFIFOLock()
new(Atomic{Int64}(0), Atomic{Int64}(0))
end
end
@inline function Base.lock(bfl::BusyFIFOLock)
#speedlock(bfl.lock)
#lock(bfl.lock)
my_tail = atomic_add!(bfl.tail, 1)
i = 1
while (my_tail != bfl.head[])
active_wait(100*i)
i += 1
end
#unlock(bfl.lock)
end
@inline function Base.unlock(bfl::BusyFIFOLock)
#speedlock(bfl.lock)
bfl.head[] += 1
#unlock(bfl.lock)
end
@inline function Base.trylock(bfl::BusyFIFOLock)
#speedlock(bfl.lock)
if bfl.tail[] == bfl.head[]
tail = atomic_add!(bfl.tail, 1)
if (bfl.head[] != tail)
atomic_add!(bfl.head, 1)
end
# unlock(bfl.lock)
return true
else
# unlock(bfl.lock)
return false
end
end
@inline function Base.islocked(bfl::BusyFIFOLock)
return bfl.head[]<bfl.tail[]
end
#_abbort::Threads.Atomic{Bool} = Threads.Atomic{Bool}(false)
const _abbort = Threads.Atomic{Bool}(false)
un_abbort() = atomic_and!(_abbort,false)
abbort() = atomic_or!(_abbort,true)
const _threads_waiting = Threads.Atomic{Int64}(0)
const number_of_locks = Threads.Atomic{Int64}(0)
function reset_lock_counter()
atomic_xchg!(_threads_waiting,0)
atomic_xchg!(number_of_locks,0)
end
#=struct ReadWriteLock
lock::ReentrantLock
ReadWriteLock() = new(ReentrantLock())
end
@inline readlock(r::ReadWriteLock) = lock(r.lock)
@inline writelock(r::ReadWriteLock) = lock(r.lock)
@inline Base.lock(r::ReadWriteLock) = lock(r.lock)
@inline readunlock(r::ReadWriteLock) = unlock(r.lock)
@inline writeunlock(r::ReadWriteLock) = unlock(r.lock)
@inline Base.unlock(r::ReadWriteLock) = unlock(r.lock)=#
const RWLCounter = Threads.Atomic{Int64}(1)
struct RWLTrace
thread::Int64
OP::Int64
all::Int64
end
Base.show(io::IO, trace::RWLTrace) = print(io, "(", trace.thread, ",", trace.OP, ",", trace.all, ")")
struct ReadWriteLock
head::Threads.Atomic{Int64}
tail::Threads.Atomic{Int64}
reads_count::Threads.Atomic{Int64}
all::Threads.Atomic{Int64}
index::Int64
trace::Vector{RWLTrace}
lock::SpinLock
#counts_read::Vector{Threads.Atomic{Int64}}
#counts_write::Vector{Threads.Atomic{Int64}}
#lock::ReentrantLock
end
@inline readlock(::Nothing) = nothing
@inline readunlock(::Nothing) = nothing
@inline writelock(::Nothing) = nothing
@inline writeunlock(::Nothing) = nothing
@inline ReadWriteLock(::T) where T = nothing
function ReadWriteLock()
#nn = Threads.nthreads()
#cr = [Threads.Atomic{Int64}(0) for i in 1:nn]
#cw = [Threads.Atomic{Int64}(0) for i in 1:nn]
return ReadWriteLock(Threads.Atomic{Int64}(0),Threads.Atomic{Int64}(0),Threads.Atomic{Int64}(0),Threads.Atomic{Int64}(0),atomic_add!(HighVoronoi.RWLCounter,1),Vector{RWLTrace}(undef,100),SpinLock())#,cr,cw,ReentrantLock())
end
@inline function readlock(rwl::ReadWriteLock)
#check(rwl)
# lock(rwl.lock)
ti = time_ns()
this_tail = atomic_add!(rwl.tail,1)
# a = atomic_add!(rwl.all,1)
# rwl.trace[mod(a,100)+1] = RWLTrace(Threads.threadid(),1,a)
# unlock(rwl.lock)
ii = 0
while atomic_add!(rwl.head,0)<this_tail
active_wait(100)
ii += 1
mod(ii,100)==0 && yield()
if time_ns()-ti>1000000000
# lock(rwl.lock)
# a = atomic_add!(rwl.all,1)
# rwl.trace[mod(a,100)+1] = RWLTrace(Threads.threadid(),-1,a)
# s = "$(rwl.index): $(atomic_add!(rwl.head,0)), $(this_tail), $(atomic_add!(rwl.reads_count,0)), $ti \n", rwl.trace,"\n"
# unlock(rwl.lock)
error(s)
end
end
atomic_add!(rwl.reads_count,1)
atomic_add!(rwl.head,1)
end
@inline function writelock(rwl::ReadWriteLock)
#check(rwl)
# lock(rwl.lock)
ti = time_ns()
this_tail = atomic_add!(rwl.tail,1)
#print("$this_tail, $(rwl.head[]), $(rwl.reads_count[])")
# a = atomic_add!(rwl.all,1)
# rwl.trace[mod(a,100)+1] = RWLTrace(Threads.threadid(),3,a)
# unlock(rwl.lock)
ii = 0
while atomic_add!(rwl.head,0)<this_tail || atomic_add!(rwl.reads_count,0)>0
active_wait(100)
ii += 1
mod(ii,100)==0 && yield()
if time_ns()-ti>1000000000
# lock(rwl.lock)
# a = atomic_add!(rwl.all,1)
# rwl.trace[mod(a,100)+1] = RWLTrace(Threads.threadid(),-3,a)
# s = "$(rwl.index): $(atomic_add!(rwl.head,0)), $(this_tail), $(atomic_add!(rwl.reads_count,0)), $ti \n", rwl.trace,"\n"
# unlock(rwl.lock)
error(s)
end
#atomic_fence()
end
end
@inline function readunlock(rwl::ReadWriteLock)
# lock(rwl.lock)
atomic_sub!(rwl.reads_count,1)
# a = atomic_add!(rwl.all,1)
# rwl.trace[mod(a,100)+1] = RWLTrace(Threads.threadid(),2,a)
# unlock(rwl.lock)
#atomic_sub!(rwl.counts_read[Threads.threadid()],1)
end
@inline function writeunlock(rwl::ReadWriteLock)
# lock(rwl.lock)
atomic_add!(rwl.head,1)
# a = atomic_add!(rwl.all,1)
# rwl.trace[mod(a,100)+1] = RWLTrace(Threads.threadid(),4,a)
# unlock(rwl.lock)
#atomic_sub!(rwl.counts_write[Threads.threadid()],1)
end
@inline Base.lock(rwl::ReadWriteLock) = writelock(rwl)
@inline Base.unlock(rwl::ReadWriteLock) = writeunlock(rwl)
#=
@inline function check(rwl::ReadWriteLock)
cw = rwl.counts_write[Threads.threadid()][]
cr = rwl.counts_read[Threads.threadid()][]
if cw>0
lock(rwl.lock)
println("Fehler write")
atomic_sub!(rwl.counts_write[Threads.threadid()],cw)
unlock(rwl.lock)
end
if cr>0
lock(rwl.lock)
println("Fehler read")
atomic_sub!(rwl.counts_read[Threads.threadid()],cr)
unlock(rwl.lock)
end
end
=#
#=struct SyncLock
locks::Threads.Atomic{Int64}
SyncLock() = new(Threads.Atomic{Int64}(0))
end
@inline add_sync(lock::SyncLock,i) = atomic_add!(lock.locks,i)
@inline add_sync(::Nothing,_) = nothing
@inline sync(::Nothing) = nothing
@inline sync(lock::SyncLock) = begin
a = atomic_sub!(lock.locks,1)
println("Thread $(Threads.threadid()), $a vs. $(lock.locks[])",)
while lock.locks[]>0
active_wait(100)
end
return a
end=#
struct SyncLock
locks::Threads.Atomic{Int64}
event::Event
SyncLock() = new(Threads.Atomic{Int64}(0),Event())
end
@inline add_sync(lock::SyncLock,i) = atomic_add!(lock.locks,i)
@inline add_sync(::Nothing,_) = nothing
@inline sync(::Nothing) = nothing
@inline sync(lock::SyncLock) = begin
a = atomic_sub!(lock.locks,1)
if a<=1
notify(lock.event)
else
wait(lock.event)
end
# println("Thread $(Threads.threadid()), $a vs. $(lock.locks[])",)
# while lock.locks[]>0
# active_wait(100)
# end
return a
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 7928 | abstract type HVView{T} end
# `length` Methode: Definiert die Länge des SwitchView als 1.
@inline Base.length(v::SVT) where {T<:Int, SVT<:HVView{T}} = 1
# `getindex` Methode: Gibt das Objekt selbst zurück, da `SwitchView` als Ganzes behandelt wird.
@inline Base.getindex(v::SVT, i::Int) where {T<:Int, SVT<:HVView{T}} = v
# `broadcastable` Methode: Behandelt `SwitchView` als Skalare, um korrektes Broadcasting zu ermöglichen.
@inline Base.broadcastable(v::SVT) where {T<:Int, SVT<:HVView{T}} = Ref(v) # Behandelt SwitchView als Skalare und verhindert unerwünschtes Broadcasting
@inline Base.:*(v::SVT, indices::AbstractVector{T}) where {T<:Int, SVT<:HVView{T}} = [v * i for i in indices]
@inline Base.:/(v::SVT, indices::AbstractVector{T}) where {T<:Int, SVT<:HVView{T}} = [v / i for i in indices]
function Base.:*(v::SVT, indices_and_output::Tuple{AbstractVector{T}, AbstractVector{T}}) where {T<:Int, SVT<:HVView{T}}
indices, output = indices_and_output
@inbounds for i in eachindex(indices)
output[i] = v * indices[i]
end
return output
end
function Base.:/(v::SVT, indices_and_output::Tuple{AbstractVector{T}, AbstractVector{T}}) where {T<:Int, SVT<:HVView{T}}
indices, output = indices_and_output
@inbounds for i in eachindex(indices)
output[i] = v / indices[i]
end
return output
end
function copy(v::HVV) where {HVV<:HVView}
error("copy is not implemented for type $(typeof(v))")
end
#############################################################################################################################
## SwitchView
#############################################################################################################################
struct SwitchView{T<:Int} <: HVView{T}
b1::T
b2::T
b3::T
function SwitchView{T}(b1::T, b2::T) where T<:Int
if b2 < b1
error("b2 must be greater than b1")
end
new{T}(b1-1, b2, b2 - b1+1)
end
end
SwitchView(b1::T, b2::T) where T<:Int = SwitchView{T}(b1,b2)
@inline Base.:*(v::SwitchView{T}, i::T) where T<:Int = i<=v.b2 ? (i > v.b1 ? i - v.b1 : i + v.b3) : i
@inline Base.:/(v::SwitchView{T}, i::T) where T<:Int = i<=v.b2 ? ( i > v.b3 ? i - v.b3 : i + v.b1) : i
@inline copy(sv::SwitchView{T}) where T = SwitchView{T}(sv.b1, sv.b2)
#############################################################################################################################
## SortedView
#############################################################################################################################
struct ShiftData{T}
old_start::T
old_end::T
new_start::T
new_end::T
shift::T
end
#=function process_compound_meshes(A) #::Tuple{Vararg{CompoundMesh}})
start_visible = start_invisible = 1
#bv = falses(length(A))
new_inds = [Int64[0, 0] for _ in 1:length(A)]
for i in 1:length(A)
a = A[i]
if a.visible==true
new_inds[i][1] = start_visible
new_inds[i][2] = start_visible + a.data.length - 1
start_visible += a.data.length
else
new_inds[i][1] = start_invisible
new_inds[i][2] = start_invisible + a.data.length - 1
start_invisible += a.data.length
end
end
start_invisible -= 1
for i in 1:length(A)
a = A[i]
if a.visible==true
new_inds[i] .+= start_invisible
end
end
data = map(1:length(A)) do i
a = A[i]
ShiftData(a.data.start, a.data.start + a.data.length - 1, new_inds[i][1], new_inds[i][2], new_inds[i][1] - a.data.start)
end
#println(data)
return Tuple(data), start_invisible
end=#
function process_compound_meshes(A) #::Tuple{Vararg{CompoundMesh}})
start_visible = start_invisible = 1
#bv = falses(length(A))
new_inds = [Int64[0, 0] for _ in 1:length(A)]
for i in 1:length(A)
a = A[i]
if a.visible==true
new_inds[i][1] = start_visible
new_inds[i][2] = start_visible + a.data.length - 1
start_visible += a.data.length
else
new_inds[i][2] = -start_invisible
new_inds[i][1] = -start_invisible - a.data.length + 1
start_invisible += a.data.length
end
end
for i in 1:length(A)
if new_inds[i][1]<0
new_inds[i][1] += start_invisible
new_inds[i][2] += start_invisible
end
end
start_invisible -= 1
for i in 1:length(A)
a = A[i]
if a.visible==true
new_inds[i] .+= start_invisible
end
end
data = map(1:length(A)) do i
a = A[i]
ShiftData(a.data.start, a.data.start + a.data.length - 1, new_inds[i][1], new_inds[i][2], new_inds[i][1] - a.data.start)
end
#println(data)
return data
end
function process_compound_meshes2(A) #::Tuple{Vararg{CompoundMesh}})
d = process_compound_meshes(A)
return Tuple(d)
end
struct SortedView{T, TUP<:Union{Tuple{Vararg{ShiftData{T}}},Vector{ShiftData{T}}}} <: HVView{T}
data::TUP
SortedView(m) = SortedView(process_compound_meshes(m))
SortedView(m::TUPP) where {T2, TUPP<:Union{Tuple{Vararg{ShiftData{T2}}},Vector{ShiftData{T2}}}} = new{T2,TUPP}(m)
end
const SortedViewTuple{T} = SortedView{T,TUP} where {T,TUP<:Tuple{Vararg{ShiftData{T}}}}
const SortedViewVector{T} = SortedView{T,Vector{ShiftData{T}}} where {T}
SortedViewTuple(m) = SortedView(process_compound_meshes2(m))
SortedViewVector(m) = SortedView(process_compound_meshes(m))
function update(sv::SV,A) where SV<:SortedViewVector
empty!(sv.data)
append!(sv.data,process_compound_meshes(A))
end
function Base.:*(v::SortedView{T}, val::T) where T<:Int
for shift_data in v.data
if shift_data.old_start <= val <= shift_data.old_end
return val + shift_data.shift
end
end
return val #error("Value not within any shift range")
end
@Base.propagate_inbounds function Base.:/(v::SortedView{T}, val::T) where T<:Int
len = length(v.data)
i = 1
while i<=len
shift_data = v.data[i]
i+=1
if shift_data.new_start <= val <= shift_data.new_end
return val - shift_data.shift
end
end
return val #error("Value not within any shift range")
end
#############################################################################################################################
## CombinedView
#############################################################################################################################
struct CombinedView{T,T1, T2 } <: HVView{T}
outer::T1
inner::T2
end
CombinedView(outer::T1,inner::T2) where {T, T1<:HVView{T}, T2<:HVView{T}}= CombinedView{T,typeof(outer),typeof(inner)}(outer,inner)
@inline Base.:*(cv::CV,val::T) where {T,CV<:CombinedView{T}} = cv.outer*(cv.inner*val)
@inline Base.:/(cv::CV,val::T) where {T,CV<:CombinedView{T}} = cv.inner/(cv.outer/val)
################################################################################################################
## ShuffleView
################################################################################################################
struct ShuffleView{T,T1, T2 } <: HVView{T}
externalindices::T1
internalindices::T2
lmesh::Int64
ShuffleView(external::T1,internal::T2,l=length(external)) where {T,T1<:AbstractVector{T},T2<:AbstractVector{T}} = new{T,T1,T2}(external,internal,l)
end
@inline Base.:*(cv::CV,val::T) where {T,CV<:ShuffleView{T}} = val<=cv.lmesh ? cv.externalindices[val] : val
@inline Base.:/(cv::CV,val::T) where {T,CV<:ShuffleView{T}} = val<=cv.lmesh ? cv.internalindices[val] : val
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
|
[
"MIT"
] | 1.3.1 | bc1b8bfb168b8850d28c935b20a545882a9a078e | code | 4347 | ###############################################################################################################################
## Mesh improving .....
###############################################################################################################################
function improve_mesh(_domain; max_iterations=0, tolerance=1.0, printevents,search)
b = internal_boundary(_domain)
mesh, integral = integrate_view(_domain)
Integrator = HighVoronoi.Integrator(integral,VI_GEOMETRY)
nodes = HighVoronoi.nodes(mesh)
dim = length(nodes[1])
lmesh = length(mesh)
plmesh = public_length(_domain)
official_mesh = HighVoronoi.mesh(_domain)
references = HighVoronoi.references(_domain)
ref_shifts = reference_shifts(_domain)
shifts = HighVoronoi.shifts(_domain)
for iter in 1:max_iterations
nodes = HighVoronoi.nodes(mesh)
official_nodes = HighVoronoi.nodes(official_mesh)
modified = zeros(Bool,lmesh)
modified_i = zeros(Bool,lmesh)
buffer = zeros(Float64,dim)
integrate(Integrator,domain=b,relevant=1:plmesh,modified=1:plmesh)
for i in 1:plmesh
modified_i .= false
buffer .= 0.0
count = 0
x_0 = nodes[i]
for (sig,r) in vertices_iterator(mesh,i)
buffer .+= r
count+=1
for s in sig
s>lmesh && break
modified_i[s] = true
end
end
buffer /= count
neighs = get_neighbors(integral,i)
dist = Inf64
for n in neighs
n>lmesh && break
dist = min(dist,norm(nodes[n]-x_0))
end
dist *= 0.5
norm(buffer-x_0)/dist <= tolerance && continue
nodes[i] = VoronoiNode(buffer)
modified[i] = true
#modified .|= modified_i
end
if sum(modified)==0
break
end
# make a list of all "modified" nodes in official numbering
modified_nodes = keepat!(collect(1:lmesh),modified)
_internal_indeces(mesh,modified_nodes)
_external_indeces(official_mesh,modified_nodes)
modified .= false
modified[modified_nodes] .= true
for i in 1:length(references)
if modified[references[i]]
modified[i] = true
official_nodes[i] = official_nodes[references[i]]+periodic_shift(ref_shifts[i],shifts)
end
end
modified_nodes = keepat!(collect(1:lmesh),modified)
modified_planes = expand_internal_boundary(_domain,view(official_nodes,modified))
modified_planes .+= lmesh
append!(modified_nodes,modified_planes)
searcher = Raycast(copy(official_nodes);domain=b,options=search)
function condition(sig,r,searcher)
keep = true
for s in sig
!keep && break
(s in modified_nodes) && (keep=false)
end
if keep
#=n,_ = nn(searcher.tree, r)
lsig = length(sig)
keep &= (n in sig) && vertex_variance(sig,r,searcher.tree.extended_xs,lsig-1,view(searcher.ts,1:lsig))<1E-20
=#
idx = _inrange(searcher.tree, r,norm(r-searcher.tree.extended_xs[sig[1]]))
lsig = length(sig)
keep &= (sig==sort!(idx)) && vertex_variance(sig,r,searcher.tree.extended_xs,lsig-1,view(searcher.ts,1:lsig))<1E-20
#keep &= verify_vertex(sig,r,searcher.tree.extended_xs,searcher)
end
if !keep
for s in sig
s>lmesh && break
modified[s] = true
end
end
return keep
end
filter!((sig,r)->condition(sig,r,searcher),official_mesh,searcher=searcher)
verify_mesh(official_mesh,b)
voronoi(official_mesh,Iter = keepat!(collect(1:lmesh),modified),searcher=searcher,intro="IMPROVING MESH: Iteration $iter of $max_iterations",printsearcher=printevents)
verify_mesh(official_mesh,b)
end
end
| HighVoronoi | https://github.com/martinheida/HighVoronoi.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.