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.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 143 | # do not remove this first line
using PkgPage
#
# Feel free to add whatever custom hfun_* or lx_*
# you might want to use in your site here
#
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 1169 | __precompile__()
module FinancialToolbox
using SpecialFunctions: erfc
using Dates, Requires, ChainRulesCore
include("dates.jl")
include("financial.jl")
include("financial_implied_volatility.jl")
include("financial_lets_be_rational.jl")
function __init__()
@require DualNumbers = "fa6b7ba4-c1ee-5f82-b5fc-ecf0adba8f74" include("financial_dual.jl")
@require ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" include("financial_forward_diff.jl")
@require ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267" include("financial_reverse_diff.jl")
@require HyperDualNumbers = "50ceba7f-c3ee-5a84-a6e8-3ad40456ec97" include("financial_hyper.jl")
@require TaylorSeries = "6aa5eb33-94cf-58f4-a9d0-e4b2c4fc25ea" include("financial_taylor.jl")
@require Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" include("financial_symbolics.jl")
end
export normcdf,
normpdf,
blsprice,
blsbin,
blkprice,
blsdelta,
blsgamma,
blsvega,
blsrho,
blstheta,
blslambda,
blsimpv,
blkimpv,
## ADDITIONAL Function
blspsi,
blsvanna,
#Dates
fromExcelNumberToDate,
daysact,
yearfrac
end#End Module
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 5035 |
function dayNumber(inDate::Date)
return Dates.date2epochdays(inDate)::Integer
end
excelcostant = 693959;
"""
From Excel Number Format to Date
Date=fromExcelNumberToDate(ExcelNumber)
Where:\n
ExcelNumber = Integer representing a date in the excel format.
Date = Date representing the input in the Julia object format.
# Example
```julia-repl
julia> fromExcelNumberToDate(45000)
2023-03-15
```
"""
function fromExcelNumberToDate(num::Integer)::Date
return Dates.Dates.epochdays2date(excelcostant + num)
end
"""
Actual Number of days between two dates
ndays=daysact(Date1,Date2)
Where:\n
Date1 = Start date.
Date2 = End date.
ndays = Actual Number of days between Start Date and End Date.
# Example
```julia-repl
julia> daysact(Date(1996,10,12),Date(1998,1,10))
455
```
"""
function daysact(Date1::Date, Date2::Date)::Integer
D1 = dayNumber(Date1)
D2 = dayNumber(Date2)
dayCount = D2 - D1
return dayCount
end
function isLastOfFebruary(inDate::Date)::Bool
return (Dates.isleapyear(Dates.year(inDate)) && (Dates.day(inDate) == 29) && (Dates.month(inDate) == 2)) || ((!Dates.isleapyear(Dates.year(inDate))) && (Dates.day(inDate) == 28) && (Dates.month(inDate) == 2))
end
currMaxImplemented = 7;
"""
Fraction of year between two Dates according the following convention
yfr=yearfrac(Date1,Date2,basis)
Where:\n
Date1 = Start date.
Date2 = End date.
basis = Integer representing the following conventions:
- 0 = (ACT/ACT)
- 1 = (30/360 SIA)
- 2 = (ACT/360)
- 3 = (ACT/365)
- 4 = (30/360 PSA)
- 5 = (30/360 ISDA)
- 6 = (30E/360)
- 7 = (ACT/365 JPN)
yfr = fraction of year between start and end date according to basis.
# Example
```julia-repl
julia> yearfrac(Date(1996,10,12),Date(1998,1,10),1)
1.2444444444444445
```
"""
function yearfrac(startDate::Date, endDate::Date, convention::Integer)::Real
if (convention < 0)
error("Negative basis are not defined, check the help")
end
if (convention > currMaxImplemented)
error("Convention not implemented yet")
end
if (startDate > endDate)
return -yearfrac(endDate, startDate, convention)
elseif (startDate == endDate)
return 0.0
end
yearFrac = 0.0
y1 = Dates.year(startDate)
m1 = Dates.month(startDate)
y2 = Dates.year(endDate)
m2 = Dates.month(endDate)
d1 = Dates.day(startDate)
d2 = Dates.day(endDate)
if (convention == 0)#(ACT/ACT)
Nday = daysact(startDate, endDate)
EndOFYear = Date(1)
if (isLastOfFebruary(startDate) && (Dates.day(startDate) == 29))
EndOFYear = Date(Dates.year(startDate) + 1, 3, 1)
else
EndOFYear = Date(Dates.year(startDate) + 1, Dates.month(startDate), Dates.day(startDate))
end
yearFrac = (Nday) / daysact(startDate, EndOFYear)
elseif (convention == 1) #(30/360 SIA)
if (isLastOfFebruary(startDate) && isLastOfFebruary(endDate))
d2 = 30
end
if (isLastOfFebruary(startDate) || Dates.day(startDate) == 31)
d1 = 30
end
if (d1 == 30 && d2 == 31)
d2 = 30
end
dy = y2 - y1
dm = m2 - m1
dd = d2 - d1
yearFrac = (360.0 * dy + 30.0 * dm + dd) / 360.0
elseif (convention == 2)#(ACT/360)
Nday = daysact(startDate, endDate)
yearFrac = (Nday) / 360.0
elseif (convention == 3)# (ACT/365)
Nday = daysact(startDate, endDate)
yearFrac = (Nday) / 365.0
elseif (convention == 4)# (30/360 PSA)
if ((Dates.day(startDate) == 31) || isLastOfFebruary(startDate))
d1 = 30
end
if ((Dates.day(startDate) == 30 || isLastOfFebruary(startDate)) && Dates.day(endDate) == 31)
d2 = 30
end
dy = y2 - y1
dm = m2 - m1
dd = d2 - d1
yearFrac = (360.0 * dy + 30.0 * dm + dd) / 360.0
elseif (convention == 5)#(30/360 ISDA)
y1 = Dates.year(startDate)
m1 = Dates.month(startDate)
y2 = Dates.year(endDate)
m2 = Dates.month(endDate)
if (Dates.day(startDate) < 31)
d1 = Dates.day(startDate)
else
d1 = 30
end
if ((Dates.day(endDate) == 31) && (d1 > 29))
d2 = 30
else
d2 = Dates.day(endDate)
end
yearFrac = (360.0 * ((y2 - y1)) + 30.0 * ((m2 - m1)) + (d2 - d1)) / 360.0
elseif (convention == 6)#(30E/360)
if (d1 == 31)
d1 = 30
end
if (d2 == 31)
d2 = 30
end
dy = y2 - y1
dm = m2 - m1
dd = d2 - d1
yearFrac = (360.0 * dy + 30.0 * dm + dd) / 360.0
elseif (convention == 7)#(ACT/365 JPN)
daydistance = [0; 31; 59; 90; 120; 151; 181; 212; 243; 273; 304; 334]
dy = y2 - y1
dd = d2 - d1
dayCount = (365.0 * dy + daydistance[m2] - daydistance[m1] + dd)
yearFrac = dayCount / 365.0
end
return yearFrac
end
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 13397 | using IrrationalConstants
const one_internal = ChainRulesCore.@ignore_derivatives(Int8(1))
const minus_one_internal = ChainRulesCore.@ignore_derivatives(Int8(-1))
const two_internal = ChainRulesCore.@ignore_derivatives(Int8(2))
"""
Cumulative Distribution Function of a Standard Gaussian Random Variable
y=normcdf(x)
Where:\n
x = point of evaluation.
y = probability that a standard gaussian random variable is below x.
# Example
```julia-repl
julia> normcdf(0.0)
0.5
```
"""
function normcdf(x)
return erfc(-x * invsqrt2) / two_internal
end
"""
Probability Distribution Function of a Standard Gaussian Random Variable
y=normpdf(x)
Where:\n
x = point of evaluation.
y = value.
# Example
```julia-repl
julia> normpdf(0.0)
0.3989422804014327
```
"""
function normpdf(x)
return exp(x^2 / (-two_internal)) * invsqrt2π
end
"""
Black Price for Binary European Options
Price=blsbin(S0,K,r,T,σ,FlagIsCall=true)
Where:\n
F0 = Value of the Forward.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility.
FlagIsCall = true for Call Options, false for Put Options.
Price = price of the Binary European Option.
# Example
```julia-repl
julia> blsbin(10.0,10.0,0.01,2.0,0.2)
0.4624714677292208
```
"""
function blsbin(S0, K, r, T, σ, d, FlagIsCall::Bool = true)
ChainRulesCore.@ignore_derivatives(FinancialToolbox.blcheck(S0, K, T, σ))
rt = r * T
dt = -d * T
sqrtT = sqrt(T)
sigma_sqrtT = σ * sqrtT
d2 = (log(S0 / K) + rt + dt) / sigma_sqrtT - sigma_sqrtT / two_internal
iscall = ChainRulesCore.@ignore_derivatives(ifelse(FlagIsCall, one_internal, minus_one_internal))
Price = exp(-rt) * normcdf(iscall * d2)
return Price
end
"""
Black & Scholes Delta for European Options
Δ=blsdelta(S0,K,r,T,σ,d=0.0,FlagIsCall=true)
Where:\n
S0 = Value of the Underlying.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility
d = Implied Dividend of the Underlying.
FlagIsCall = true for Call Options, false for Put Options.
Δ = delta of the European Option.
# Example
```julia-repl
julia> blsdelta(10.0,10.0,0.01,2.0,0.2,0.01)
0.5452173371920436
```
"""
function blsdelta(S0, K, r, T, σ, d, FlagIsCall::Bool = true)
ChainRulesCore.@ignore_derivatives(FinancialToolbox.blcheck(S0, K, T, σ))
rt = r * T
dt = -d * T
sigma_sqrtT = σ * sqrt(T)
S0_K = S0 / K
d1 = (log(S0_K) + rt + dt) / sigma_sqrtT + sigma_sqrtT / two_internal
iscall = ChainRulesCore.@ignore_derivatives(ifelse(FlagIsCall, one_internal, minus_one_internal))
Δ = exp(dt) * normcdf(iscall * d1) * iscall
return Δ
end
function blprice_impl(S0, K, T, σ, FlagIsCall::Bool = true)
iscall = ChainRulesCore.@ignore_derivatives(ifelse(FlagIsCall, one_internal, minus_one_internal))
sigma_sqrtT = σ * sqrt(T)
d1 = log(S0 / K) / sigma_sqrtT + sigma_sqrtT / two_internal
Price = iscall * (S0 * normcdf(iscall * d1) - K * normcdf(iscall * (d1 - sigma_sqrtT)))
return Price
end
function blprice(S0, K, T, σ, FlagIsCall::Bool = true)
ChainRulesCore.@ignore_derivatives(FinancialToolbox.blcheck(S0, K, T, σ))
return blprice_impl(S0, K, T, σ, FlagIsCall)
end
"""
Black & Scholes Price for European Options
Price=blsprice(S0,K,r,T,σ,d=0.0,FlagIsCall=true)
Where:\n
S0 = Value of the Underlying.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility
d = Implied Dividend of the Underlying.
FlagIsCall = true for Call Options, false for Put Options.
Price = price of the European Option.
# Example
```julia-repl
julia> blsprice(10.0,10.0,0.01,2.0,0.2,0.01)
1.1023600107733191
```
"""
function blsprice(S0, K, r, T, σ, d, FlagIsCall::Bool = true)
cv = exp(r * T)
cv2 = exp((r - d) * T)
F = S0 * cv2
return blprice(F, K, T, σ, FlagIsCall) / cv
end
"""
Black Price for European Options
Price=blkprice(F0,K,r,T,σ,FlagIsCall=true)
Where:\n
F0 = Value of the Forward.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility.
FlagIsCall = true for Call Options, false for Put Options.
Price = price of the European Option.
# Example
```julia-repl
julia> blkprice(10.0,10.0,0.01,2.0,0.2)
1.1023600107733191
```
"""
function blkprice(F0, K, r, T, σ, FlagIsCall::Bool = true)
cv = exp(r * T)
return blprice(F0, K, T, σ, FlagIsCall) / cv
end
"""
Black & Scholes Gamma for European Options
Γ=blsgamma(S0,K,r,T,σ,d=0.0,FlagIsCall=true)
Where:\n
S0 = Value of the Underlying.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility
d = Implied Dividend of the Underlying.
FlagIsCall = true for Call Options, false for Put Options.
Γ = gamma of the European Option.
# Example
```julia-repl
julia> blsgamma(10.0,10.0,0.01,2.0,0.2,0.01)
0.13687881535712826
```
"""
function blsgamma(S0, K, r, T, σ, d, ::Bool = true)
ChainRulesCore.@ignore_derivatives(FinancialToolbox.blcheck(S0, K, T, σ))
rt = r * T
dt = -d * T
sigma_sqrtT = σ * sqrt(T)
S0_K = S0 / K
d1 = (log(S0_K) + rt + dt) / sigma_sqrtT + sigma_sqrtT / two_internal
Γ = exp(dt) * normpdf(d1) / (S0 * sigma_sqrtT)
return Γ
end
function blvega_impl(S0, K, T, σ)
sqrtT = sqrt(T)
sigma_sqrtT = σ * sqrtT
d1 = log(S0 / K) / sigma_sqrtT + sigma_sqrtT / two_internal
ν = S0 * normpdf(d1) * sqrtT
return ν
end
function blvega(S0, K, T, σ)
ChainRulesCore.@ignore_derivatives(FinancialToolbox.blcheck(S0, K, T, σ))
return blvega_impl(S0, K, T, σ)
end
"""
Black & Scholes Vega for European Options
ν=blsvega(S0,K,r,T,σ,d=0.0,FlagIsCall=true)
Where:\n
S0 = Value of the Underlying.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility
d = Implied Dividend of the Underlying.
FlagIsCall = true for Call Options, false for Put Options.
ν = vega of the European Option.
# Example
```julia-repl
julia> blsvega(10.0,10.0,0.01,2.0,0.2,0.01)
5.475152614285131
```
"""
function blsvega(S0, K, r, T, σ, d, ::Bool = true)
cv = exp(r * T)
cv2 = exp(-d * T)
F = S0 * cv * cv2
return blvega(F, K, T, σ) / cv
end
"""
Black & Scholes Rho for European Options
ρ=blsrho(S0,K,r,T,σ,d=0.0,FlagIsCall=true)
Where:\n
S0 = Value of the Underlying.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility
d = Implied Dividend of the Underlying.
FlagIsCall = true for Call Options, false for Put Options.
ρ = rho of the European Option.
# Example
```julia-repl
julia> blsrho(10.0,10.0,0.01,2.0,0.2,0.01)
8.699626722294234
```
"""
function blsrho(S0, K, r, T, σ, d, FlagIsCall::Bool = true)
ChainRulesCore.@ignore_derivatives(FinancialToolbox.blcheck(S0, K, T, σ))
iscall = ChainRulesCore.@ignore_derivatives(ifelse(FlagIsCall, one_internal, minus_one_internal))
rt = r * T
dt = -d * T
sqrtT = sqrt(T)
sigma_sqrtT = σ * sqrtT
d2 = (log(S0 / K) + rt + dt) / sigma_sqrtT - sigma_sqrtT / two_internal
ρ = iscall * K * exp(-rt) * normcdf(iscall * d2) * T
return ρ
end
"""
Black & Scholes Theta for European Options
Θ=blstheta(S0,K,r,T,σ,d=0.0,FlagIsCall=true)
Where:\n
S0 = Value of the Underlying.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility
d = Implied Dividend of the Underlying.
FlagIsCall = true for Call Options, false for Put Options.
Θ = theta of the European Option.
# Example
```julia-repl
julia> blstheta(10.0,10.0,0.01,2.0,0.2,0.01)
-0.26273403060652334
```
"""
function blstheta(S0, K, r, T, σ, d, FlagIsCall::Bool = true)
ChainRulesCore.@ignore_derivatives(FinancialToolbox.blcheck(S0, K, T, σ))
rt = r * T
dt = -d * T
sqrtT = sqrt(T)
sigma_sqrtT = σ * sqrtT
d1 = (log(S0 / K) + rt + dt) / sigma_sqrtT + sigma_sqrtT / two_internal
d2 = d1 - sigma_sqrtT
S0_adj = S0 * exp(dt)
shift = -S0_adj * normpdf(d1) * σ / (sqrtT * two_internal)
t1 = r * K * exp(-rt)
t2 = d * S0_adj
iscall = ChainRulesCore.@ignore_derivatives(ifelse(FlagIsCall, one_internal, minus_one_internal))
Θ = shift - iscall * (t1 * normcdf(iscall * d2) - t2 * normcdf(iscall * d1))
return Θ
end
"""
Black & Scholes Lambda for European Options
Λ=blslambda(S0,K,r,T,σ,d=0.0,FlagIsCall=true)
Where:\n
S0 = Value of the Underlying.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility
d = Implied Dividend of the Underlying.
FlagIsCall = true for Call Options, false for Put Options.
Λ = lambda of the European Option.
# Example
```julia-repl
julia> blslambda(10.0,10.0,0.01,2.0,0.2,0.01)
4.945909973725978
```
"""
function blslambda(S0, K, r, T, σ, d, FlagIsCall::Bool = true)
ChainRulesCore.@ignore_derivatives(FinancialToolbox.blcheck(S0, K, T, σ))
rt = r * T
dt = -d * T
sigma_sqrtT = σ * sqrt(T)
S0_K = S0 / K
d1 = (log(S0_K) + rt + dt) / sigma_sqrtT + sigma_sqrtT / two_internal
d2 = d1 - sigma_sqrtT
iscall = ChainRulesCore.@ignore_derivatives(ifelse(FlagIsCall, one_internal, minus_one_internal))
Δ = exp(dt) * normcdf(iscall * d1) * iscall
Δ_adj = S0 * Δ
Price = Δ_adj - iscall * K * exp(-rt) * normcdf(iscall * d2)
Λ = Δ_adj / Price
return Λ
end
#Check input for Black Scholes Formula
function blcheck_impl(::num0, S0::num1, K::num2, T::num4, σ::num5) where {num0, num1, num2, num4, num5}
lesseq(x, y) = x <= y
if (lesseq(S0, zero(num1)))
throw(DomainError(S0, "Spot Price Cannot Be Negative"))
elseif (lesseq(K, zero(num2)))
throw(DomainError(K, "Strike Price Cannot Be Negative"))
elseif (lesseq(T, zero(num4)))
throw(DomainError(T, "Time to Maturity Cannot Be Negative"))
elseif (lesseq(σ, zero(num5)))
throw(DomainError(σ, "Volatility Cannot Be Negative"))
end
return
end
function blcheck_impl(::num0, S0::num1, K::num2, T::num4, σ::num5) where {num0 <: Complex, num1, num2, num4, num5}
lesseq(x::Complex, y::Complex) = real(x) <= real(y)
lesseq(x, y) = x <= y
if (lesseq(S0, zero(num1)))
throw(DomainError(S0, "Spot Price Cannot Be Negative"))
elseif (lesseq(K, zero(num2)))
throw(DomainError(K, "Strike Price Cannot Be Negative"))
elseif (lesseq(T, zero(num4)))
throw(DomainError(T, "Time to Maturity Cannot Be Negative"))
elseif (lesseq(σ, zero(num5)))
throw(DomainError(σ, "Volatility Cannot Be Negative"))
end
return
end
function blcheck(S0::num1, K::num2, T::num4, σ::num5) where {num1, num2, num4, num5}
zero_typed = S0 * K * T * σ
blcheck_impl(zero_typed, S0, K, T, σ)
return
end
## ADDITIONAL Functions
"""
Black & Scholes Psi for European Options
Ψ=blspsi(S0,K,r,T,σ,d=0.0,FlagIsCall=true)
Where:\n
S0 = Value of the Underlying.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility
d = Implied Dividend of the Underlying.
FlagIsCall = true for Call Options, false for Put Options.
Ψ = psi of the European Option.
# Example
```julia-repl
julia> blspsi(10.0,10.0,0.01,2.0,0.2,0.01)
-10.904346743840872
```
"""
function blspsi(S0, K, r, T, σ, d, FlagIsCall::Bool = true)
ChainRulesCore.@ignore_derivatives(FinancialToolbox.blcheck(S0, K, T, σ))
rt = r * T
dt = -d * T
sigma_sqrtT = σ * sqrt(T)
S0_K = S0 / K
d1 = (log(S0_K) + rt + dt) / sigma_sqrtT + sigma_sqrtT / two_internal
iscall = ChainRulesCore.@ignore_derivatives(ifelse(FlagIsCall, one_internal, minus_one_internal))
Ψ = -iscall * S0 * exp(dt) * normcdf(iscall * d1) * T
return Ψ
end
"""
Black & Scholes Vanna for European Options
Vanna=blsvanna(S0,K,r,T,σ,d=0.0,FlagIsCall=true)
Where:\n
S0 = Value of the Underlying.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
σ = Implied Volatility
d = Implied Dividend of the Underlying.
FlagIsCall = true for Call Options, false for Put Options.
Vanna = vanna of the European Option.
# Example
```julia-repl
julia> blsvanna(10.0,10.0,0.01,2.0,0.2,0.01)
0.2737576307142566
```
"""
function blsvanna(S0, K, r, T, σ, d, ::Bool = true)
ChainRulesCore.@ignore_derivatives(FinancialToolbox.blcheck(S0, K, T, σ))
rt = r * T
dt = -d * T
sigma_sqrtT = σ * sqrt(T)
S0_K = S0 / K
d1 = (log(S0_K) + rt + dt) / sigma_sqrtT + sigma_sqrtT / two_internal
d2 = d1 - sigma_sqrtT
Vanna = -exp(dt) * normpdf(d1) * d2 / σ
return Vanna
end
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 424 | using .DualNumbers
value__d(x::Dual) = x.value
value__d(x) = x
function blimpv_impl(::Dual, S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
S0_r = value__d(S0)
K_r = value__d(K)
T_r = value__d(T)
p_r = value__d(price_d)
σ = blimpv(S0_r, K_r, T_r, p_r, FlagIsCall, xtol, n_iter_max)
der_ = blprice_diff_impl(S0, K, T, σ, price_d, FlagIsCall) / blvega_impl(S0_r, K_r, T_r, σ)
return σ + der_
end
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 447 | using .ForwardDiff
value__d(x::ForwardDiff.Dual) = x.value
value__d(x) = x
function blimpv_impl(::ForwardDiff.Dual, S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
S0_r = value__d(S0)
K_r = value__d(K)
T_r = value__d(T)
p_r = value__d(price_d)
σ = blimpv(S0_r, K_r, T_r, p_r, FlagIsCall, xtol, n_iter_max)
der_ = blprice_diff_impl(S0, K, T, σ, price_d, FlagIsCall) / blvega_impl(S0_r, K_r, T_r, σ)
return σ + der_
end | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 610 | using .HyperDualNumbers
function blimpv_impl(::Hyper, S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
S0_r = HyperDualNumbers.value(S0)
K_r = HyperDualNumbers.value(K)
T_r = HyperDualNumbers.value(T)
pr_r = HyperDualNumbers.value(price_d)
σ = blimpv(S0_r, K_r, T_r, pr_r, FlagIsCall, xtol, n_iter_max)
vega = blvega_impl(S0_r, K_r, T_r, σ)
σ_hyper = σ + blprice_diff_impl(S0, K, T, σ, price_d, FlagIsCall) / vega
σ_hyper -= Hyper(0, 0, 0, HyperDualNumbers.eps1eps2(σ_hyper))
σ_hyper += (price_d - blprice_impl(S0, K, T, σ_hyper, FlagIsCall)) / vega
return σ_hyper
end
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 4594 | function blimpv_check(S0::num1, K::num2, T::num4) where {num1, num2, num4}
lesseq(x::Complex, y::Complex) = real(x) <= real(y)
lesseq(x, y) = x <= y
if (lesseq(S0, zero(num1)))
throw(DomainError(S0, "Spot Price Cannot Be Negative"))
elseif (lesseq(K, zero(num2)))
throw(DomainError(K, "Strike Price Cannot Be Negative"))
elseif (lesseq(T, zero(num4)))
throw(DomainError(T, "Time to Maturity Cannot Be Negative"))
end
return
end
function blimpv_impl(::AbstractFloat, S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
ChainRulesCore.ignore_derivatives() do
FinancialToolbox.blimpv_check(S0, K, T)
if xtol <= 0.0
throw(DomainError(xtol, "x tollerance cannot be negative"))
end
if n_iter_max <= 0
throw(DomainError(n_iter_max, "maximum number of iterations must be positive"))
end
max_price = ifelse(FlagIsCall, S0, K)
if max_price <= price_d
throw(DomainError(price_d, "Price is reaching maximum value"))
end
min_price = eps(zero(price_d))
if min_price >= price_d
throw(DomainError(price_d, "Price is reaching minimum value"))
end
end
return blimpv_lets_be_rational(S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
end
function blimpv(S0::num1, K::num2, T::num4, Price::num5, FlagIsCall::Bool, xtol::Real, n_iter_max::Integer) where {num1, num2, num4, num5}
zero_typed = ChainRulesCore.@ignore_derivatives(zero(promote_type(num1, num2, num4, num5)))
σ = blimpv_impl(zero_typed, S0, K, T, Price, FlagIsCall, xtol, n_iter_max)
return σ
end
"""
Black & Scholes Implied Volatility for European Options
σ=blsimpv(S0,K,r,T,Price,d=0.0,FlagIsCall=true,xtol=1e-14,ytol=1e-15)
Where:\n
S0 = Value of the Underlying.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
Price = Price of the Option.
d = Implied Dividend of the Underlying.
FlagIsCall = true for Call Options, false for Put Options.
σ = implied volatility of the European Option.
# Example
```julia-repl
julia> blsimpv(10.0,10.0,0.01,2.0,2.0)
0.3433730534290586
```
"""
function blsimpv(S0, K, r, T, Price, d = 0, FlagIsCall::Bool = true, xtol::Real = 100 * eps(Float64), n_iter_max::Integer = 4)
cv = exp(r * T)
cv2 = exp(-d * T)
adj_S0 = S0 * cv * cv2
adj_price = Price * cv
σ = blimpv(adj_S0, K, T, adj_price, FlagIsCall, xtol, n_iter_max)
return σ
end
"""
Black Implied Volatility for European Options
σ=blkimpv(F0,K,r,T,Price,FlagIsCall=true,xtol=1e-14,ytol=1e-15)
Where:\n
F0 = Value of the Forward.
K = Strike Price of the Option.
r = Zero Rate.
T = Time to Maturity of the Option.
Price = Price of the Option.
FlagIsCall = true for Call Options, false for Put Options.
σ = implied volatility of the European Option.
# Example
```julia-repl
julia> blkimpv(10.0,10.0,0.01,2.0,2.0)
0.36568658096623635
```
"""
function blkimpv(F0, K, r, T, Price, FlagIsCall::Bool = true, xtol::Real = 1e-14, n_iter_max::Integer = 4)
adj_price = Price * exp(r * T)
σ = blimpv(F0, K, T, adj_price, FlagIsCall, xtol, n_iter_max)
return σ
end
import ChainRulesCore: rrule, frule, NoTangent, @thunk, rrule_via_ad, frule_via_ad
function blprice_diff_impl(S0, K, T, σ, price_d, FlagIsCall)
return price_d - blprice_impl(S0, K, T, σ, FlagIsCall)
end
function rrule(config::RuleConfig{>:HasReverseMode}, ::typeof(blimpv), S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
σ = blimpv(S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
function update_pullback(slice)
_, pullback_blprice = ChainRulesCore.rrule_via_ad(config, blprice_impl, S0, K, T, σ, FlagIsCall)
_, der_S0, der_K, der_T, der_σ, _ = pullback_blprice(slice)
slice_mod = -inv(der_σ)
return NoTangent(), slice_mod * der_S0, slice_mod * der_K, slice_mod * der_T, -slice_mod, NoTangent(), NoTangent(), NoTangent()
end
return σ, update_pullback
end
function frule(config::RuleConfig{>:HasForwardsMode}, (_, dS, dK, dT, dprice, _, _, _), ::typeof(blimpv), S0, K, T, price_d, FlagIsCall::Bool, xtol, n_iter_max::Integer)
σ = blimpv(S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
vega = blvega_impl(S0, K, T, σ)
_, der_fwd = ChainRulesCore.frule_via_ad(config, (NoTangent(), dS, dK, dT, NoTangent(), dprice, NoTangent()), blprice_diff_impl, S0, K, T, σ, price_d, FlagIsCall)
return σ, der_fwd / vega
end | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 34637 |
using MuladdMacro
function dbl_min(::T) where {T <: Number}
return eps(zero(T))
end
function dbl_max(::T) where {T <: Number}
return prevfloat(typemax(T))
end
using IrrationalConstants
function dbl_epsilon(::T) where {T <: Number}
return eps(T)
end
function minimum_rational_cubic_control_parameter_value(x)
return -(1 - sqrt(dbl_epsilon(x)))
end
square(x) = x^2
positive_part(x::T) where {T <: Number} = max(x, zero(T))
function maximum_rational_cubic_control_parameter_value(x)
return 2 / square(dbl_epsilon(x))
end
const norm_cdf_asymptotic_expansion_first_threshold = -10;
function rational_cubic_interpolation(x, x_l, x_r, y_l, y_r, d_l, d_r, r)
h = (x_r - x_l)
if (abs(h) <= 0)
return (y_l + y_r) / 2
end
# r should be greater than -1. We do not use assert(r > -1) here in order to allow values such as NaN to be propagated as they should.
t = (x - x_l) / h
omt = 1 - t
if (!(r >= maximum_rational_cubic_control_parameter_value(r)))
t2 = square(t)
# omt2 = square(omt)
# Formula (2.4) divided by formula (2.5)
# return @muladd (y_r * t2 * t + (r * y_r - h * d_r) * t2 * omt + (r * y_l + h * d_l) * t * omt2 + y_l * omt2 * omt) / (1 + (r - 3) * t * omt)
# return @muladd (y_r * t2 * t + (r * y_r - h * d_r) * t2 * omt + omt2 * ((r * y_l + h * d_l) * t + y_l * omt)) / (1 + (r - 3) * t * omt)
return @muladd (y_r * t2 * t + omt * ((r * y_r - h * d_r) * t2 + omt * ((r * y_l + h * d_l) * t + y_l * omt))) / (1 + (r - 3) * t * omt)
end
# Linear interpolation without over-or underflow.
return y_r * t + y_l * omt
end
is_zero(x) = abs(x) < dbl_min(x);
function rational_cubic_control_parameter_to_fit_second_derivative_at_left_side(x_l, x_r, y_l, y_r, d_l, d_r, second_derivative_l)
h = (x_r - x_l)
@muladd numerator = h * second_derivative_l / 2 + d_r - d_l
zero_num = zero(numerator)
if (is_zero(numerator))
return zero_num
end
denominator = (y_r - y_l) / h - d_l
zero_typed = zero_num + zero(denominator)
if (is_zero(denominator))
return ifelse(numerator > 0, maximum_rational_cubic_control_parameter_value(zero_typed), minimum_rational_cubic_control_parameter_value(zero_typed))
end
return numerator / denominator
end
function rational_cubic_control_parameter_to_fit_second_derivative_at_right_side(x_l, x_r, y_l, y_r, d_l, d_r, second_derivative_r)
h = (x_r - x_l)
@muladd numerator = h * second_derivative_r / 2 + d_r - d_l
zero_num = zero(numerator)
if (is_zero(numerator))
return zero_num
end
denominator = d_r - (y_r - y_l) / h
zero_typed = zero_num + zero(denominator)
if (is_zero(denominator))
return ifelse(numerator > 0, maximum_rational_cubic_control_parameter_value(zero_typed), minimum_rational_cubic_control_parameter_value(zero_typed))
end
return numerator / denominator
end
function minimum_rational_cubic_control_parameter(d_l::T, d_r::U, s::V, prefer_shape_preservation_over_smoothness) where {T <: Real, U <: Real, V <: Real}
monotonic = d_l * s >= 0 && d_r * s >= 0
convex = d_l <= s && s <= d_r
concave = d_l >= s && s >= d_r
zero_typed = zero(promote_type(T, U, V))
if (!monotonic && !convex && !concave) # If 3==r_non_shape_preserving_target, this means revert to standard cubic.
return minimum_rational_cubic_control_parameter_value(zero_typed)
end
d_r_m_d_l = d_r - d_l
d_r_m_s = d_r - s
s_m_d_l = s - d_l
r1 = -dbl_max(zero_typed)
r2 = r1
# If monotonicity on this interval is possible, set r1 to satisfy the monotonicity condition (3.8).
if (monotonic)
if (!is_zero(s)) # (3.8), avoiding division by zero.
r1 = (d_r + d_l) / s # (3.8)
elseif (prefer_shape_preservation_over_smoothness) # If division by zero would occur, and shape preservation is preferred, set value to enforce linear interpolation.
r1 = maximum_rational_cubic_control_parameter_value(zero_typed) # This value enforces linear interpolation.
end
end
if (convex || concave)
if (!(is_zero(s_m_d_l) || is_zero(d_r_m_s))) # (3.18), avoiding division by zero.
r2 = max(abs(d_r_m_d_l / d_r_m_s), abs(d_r_m_d_l / s_m_d_l))
elseif (prefer_shape_preservation_over_smoothness)
r2 = maximum_rational_cubic_control_parameter_value(zero_typed) # This value enforces linear interpolation.
end
elseif (monotonic && prefer_shape_preservation_over_smoothness)
r2 = maximum_rational_cubic_control_parameter_value(zero_typed) # This enforces linear interpolation along segments that are inconsistent with the slopes on the boundaries, e.g., a perfectly horizontal segment that has negative slopes on either edge.
end
return max(minimum_rational_cubic_control_parameter_value(zero_typed), r1, r2)
end
function convex_rational_cubic_control_parameter_to_fit_second_derivative_at_left_side(x_l, x_r, y_l, y_r, d_l, d_r, second_derivative_l, prefer_shape_preservation_over_smoothness)
r = rational_cubic_control_parameter_to_fit_second_derivative_at_left_side(x_l, x_r, y_l, y_r, d_l, d_r, second_derivative_l)
r_min = minimum_rational_cubic_control_parameter(d_l, d_r, (y_r - y_l) / (x_r - x_l), prefer_shape_preservation_over_smoothness)
return max(r, r_min)
end
function convex_rational_cubic_control_parameter_to_fit_second_derivative_at_right_side(x_l, x_r, y_l, y_r, d_l, d_r, second_derivative_r, prefer_shape_preservation_over_smoothness)
r = rational_cubic_control_parameter_to_fit_second_derivative_at_right_side(x_l, x_r, y_l, y_r, d_l, d_r, second_derivative_r)
r_min = minimum_rational_cubic_control_parameter(d_l, d_r, (y_r - y_l) / (x_r - x_l), prefer_shape_preservation_over_smoothness)
return max(r, r_min)
end
function sqrt_dbl_epsilon(x)
return sqrt(dbl_epsilon(x))
end
function fourth_root_dbl_epsilon(x)
return sqrt(sqrt_dbl_epsilon(x))
end
function eighth_root_dbl_epsilon(x)
return sqrt(fourth_root_dbl_epsilon(x))
end
function sixteenth_root_dbl_epsilon(x)
return sqrt(eighth_root_dbl_epsilon(x))
end
function sqrt_dbl_min(x)
return sqrt(dbl_min(x))
end
# Set this to 0 if you want positive results for (positive) denormalised inputs, else to dbl_min.
# Note that you cannot achieve full machine accuracy from denormalised inputs!
householder_factor(newton, halley, hh3) = @muladd (1 + halley * newton / 2) / (1 + newton * (halley + hh3 * newton / 6));
# Asymptotic expansion of
#
# b = Φ(h+t)·exp(x/2) - Φ(h-t)·exp(-x/2)
# with
# h = x/s and t = s/2
# which makes
# b = Φ(h+t)·exp(h·t) - Φ(h-t)·exp(-h·t)
#
# exp(-(h²+t²)/2)
# = --------------- · [ Y(h+t) - Y(h-t) ]
# √(2π)
# with
# Y(z) := Φ(z)/φ(z)
#
# for large negative (t-|h|) by the aid of Abramowitz & Stegun (26.2.12) where Φ(z) = φ(z)/|z|·[1-1/z^2+...].
# We define
# r
# A(h,t) := --- · [ Y(h+t) - Y(h-t) ]
# t
#
# with r := (h+t)·(h-t) and give an expansion for A(h,t) in q:=(h/r)² expressed in terms of e:=(t/h)² .
function asymptotic_expansion_of_normalised_black_call(h, t)
e = square(t / h)
r = (h + t) * (h - t)
q = square(h / r)
twice_e = 2 * e
# 17th order asymptotic expansion of A(h,t) in q, sufficient for Φ(h) [and thus y(h)] to have relative accuracy of 1.64E-16 for h <= η with η:=-10.
#TODO: this is too much for "less" than Float64
@muladd asymptotic_expansion_sum = (
2 +
q * (
-6 - twice_e +
3 *
q *
(
10 +
e * (20 + twice_e) +
5 *
q *
(
-14 +
e * (-70 + e * (-42 - twice_e)) +
7 *
q *
(
18 +
e * (168 + e * (252 + e * (72 + twice_e))) +
9 *
q *
(
-22 +
e * (-330 + e * (-924 + e * (-660 + e * (-110 - twice_e)))) +
11 *
q *
(
26 +
e * (572 + e * (2574 + e * (3432 + e * (1430 + e * (156 + twice_e))))) +
13 *
q *
(
-30 +
e * (-910 + e * (-6006 + e * (-12870 + e * (-10010 + e * (-2730 + e * (-210 - twice_e)))))) +
15 *
q *
(
34 +
e * (1360 + e * (12376 + e * (38896 + e * (48620 + e * (24752 + e * (4760 + e * (272 + twice_e))))))) +
17 *
q *
(
-38 +
e * (-1938 + e * (-23256 + e * (-100776 + e * (-184756 + e * (-151164 + e * (-54264 + e * (-7752 + e * (-342 - twice_e)))))))) +
19 *
q *
(
42 +
e * (2660 + e * (40698 + e * (232560 + e * (587860 + e * (705432 + e * (406980 + e * (108528 + e * (11970 + e * (420 + twice_e))))))))) +
21 *
q *
(
-46 +
e * (-3542 + e * (-67298 + e * (-490314 + e * (-1634380 + e * (-2704156 + e * (-2288132 + e * (-980628 + e * (-201894 + e * (-17710 + e * (-506 - twice_e)))))))))) +
23 *
q *
(
50 +
e * (4600 + e * (106260 + e * (961400 + e * (4085950 + e * (8914800 + e * (10400600 + e * (6537520 + e * (2163150 + e * (354200 + e * (25300 + e * (600 + twice_e))))))))))) +
25 *
q *
(
-54 +
e * (-5850 + e * (-161460 + e * (-1776060 + e * (-9373650 + e * (-26075790 + e * (-40116600 + e * (-34767720 + e * (-16872570 + e * (-4440150 + e * (-592020 + e * (-35100 + e * (-702 - twice_e)))))))))))) +
27 * q * (58 + e * (7308 + e * (237510 + e * (3121560 + e * (20030010 + e * (69194580 + e * (135727830 + e * (155117520 + e * (103791870 + e * (40060020 + e * (8584290 + e * (950040 + e * (47502 + e * (812 + twice_e))))))))))))) + 29 * q * (-62 + e * (-8990 + e * (-339822 + e * (-5259150 + e * (-40320150 + e * (-169344630 + e * (-412506150 + e * (-601080390 + e * (-530365050 + e * (-282241050 + e * (-88704330 + e * (-15777450 + e * (-1472562 + e * (-62930 + e * (-930 - twice_e)))))))))))))) + 31 * q * (66 + e * (10912 + e * (474672 + e * (8544096 + e * (77134200 + e * (387073440 + e * (1146332880 + e * (2074316640 + e * (2333606220 + e * (1637618400 + e * (709634640 + e * (185122080 + e * (27768312 + e * (2215136 + e * (81840 + e * (1056 + twice_e))))))))))))))) + 33 * (-70 + e * (-13090 + e * (-649264 + e * (-13449040 + e * (-141214920 + e * (-834451800 + e * (-2952675600 + e * (-6495886320 + e * (-9075135300 + e * (-8119857900 + e * (-4639918800 + e * (-1668903600 + e * (-367158792 + e * (-47071640 + e * (-3246320 + e * (-104720 + e * (-1190 - twice_e))))))))))))))))) * q)))
)
)
)
)
)
)
)
)
)
)
)
)
)
)
z = exp((-(square(h) + square(t)) / 2))
b = z * (t / r) * asymptotic_expansion_sum / sqrt2π
return abs(positive_part(b))
end
const asymptotic_expansion_accuracy_threshold = -10
function normalised_black_call_using_erfcx(h, t)
# Given h = x/s and t = s/2, the normalised Black function can be written as
#
# b(x,s) = Φ(x/s+s/2)·exp(x/2) - Φ(x/s-s/2)·exp(-x/2)
# = Φ(h+t)·exp(h·t) - Φ(h-t)·exp(-h·t) . (*)
#
# It is mentioned in section 4 (and discussion of figures 2 and 3) of George Marsaglia's article "Evaluating the
# Normal Distribution" (available at http:#www.jstatsoft.org/v11/a05/paper) that the error of any cumulative normal
# function Φ(z) is dominated by the hardware (or compiler implementation) accuracy of exp(-z²/2) which is not
# reliably more than 14 digits when z is large. The accuracy of Φ(z) typically starts coming down to 14 digits when
# z is around -8. For the (normalised) Black function, as above in (*), this means that we are subtracting two terms
# that are each products of terms with about 14 digits of accuracy. The net result, in each of the products, is even
# less accuracy, and then we are taking the difference of these terms, resulting in even less accuracy. When we are
# using the asymptotic expansion asymptotic_expansion_of_normalised_black_call() invoked in the second branch at the
# beginning of this function, we are using only *one* exponential instead of 4, and this improves accuracy. It
# actually improves it a bit more than you would expect from the above logic, namely, almost the full two missing
# digits (in 64 bit IEEE floating point). Unfortunately, going higher order in the asymptotic expansion will not
# enable us to gain more accuracy (by extending the range in which we could use the expansion) since the asymptotic
# expansion, being a divergent series, can never gain 16 digits of accuracy for z=-8 or just below. The best you can
# get is about 15 digits (just), for about 35 terms in the series (26.2.12), which would result in an prohibitively
# long expression in function asymptotic expansion asymptotic_expansion_of_normalised_black_call(). In this last branch,
# here, we therefore take a different tack as follows.
# The "scaled complementary error function" is defined as erfcx(z) = exp(z²)·erfc(z). Cody's implementation of this
# function as published in "Rational Chebyshev approximations for the error function", W. J. Cody, Math. Comp., 1969, pp.
# 631-638, uses rational functions that theoretically approximates erfcx(x) to at least 18 significant decimal digits,
# *without* the use of the exponential function when x>4, which translates to about z<-5.66 in Φ(z). To make use of it,
# we write
# Φ(z) = exp(-z²/2)·erfcx(-z/√2)/2
#
# to transform the normalised black function to
#
# b = ½ · exp(-½(h²+t²)) · [ erfcx(-(h+t)/√2) - erfcx(-(h-t)/√2) ]
#
# which now involves only one exponential, instead of three, when |h|+|t| > 5.66 , and the difference inside the
# square bracket is between the evaluation of two rational functions, which, typically, according to Marsaglia,
# retains the full 16 digits of accuracy (or just a little less than that).
#
arg_minus = (t - h) / sqrt2
arg_plus = (-t - h) / sqrt2
b = exp(-(square(h) + square(t)) / 2) * (erfcx(arg_plus) - erfcx(arg_minus)) / 2
return abs(positive_part(b))
end
# Calculation of
#
# b = Φ(h+t)·exp(h·t) - Φ(h-t)·exp(-h·t)
#
# exp(-(h²+t²)/2)
# = --------------- · [ Y(h+t) - Y(h-t) ]
# √(2π)
# with
# Y(z) := Φ(z)/φ(z)
#
# using an expansion of Y(h+t)-Y(h-t) for small t to twelvth order in t.
# Theoretically accurate to (better than) precision ε = 2.23E-16 when h<=0 and t < τ with τ := 2·ε^(1/16) ≈ 0.21.
# The main bottleneck for precision is the coefficient a:=1+h·Y(h) when |h|>1 .
function small_t_expansion_of_normalised_black_call(h, t)
# Y(h) := Φ(h)/φ(h) = √(π/2)·erfcx(-h/√2)
# a := 1+h·Y(h) --- Note that due to h<0, and h·Y(h) -> -1 (from above) as h -> -∞, we also have that a>0 and a -> 0 as h -> -∞
# w := t² , h2 := h²
half_h_sqrt2 = h / sqrt2
a = 1 + sqrtπ * half_h_sqrt2 * erfcx(-half_h_sqrt2)
w = square(t)
h2 = square(h)
#TODO: this is too much for float "less" than Float64
@muladd expansion = 2 * t * (a + w * ((-1 + a * (3 + h2)) / 6 + w * ((-7 + 15 * a + h2 * (-1 + a * (10 + h2))) / 120 + w * ((-57 + 105 * a + h2 * (-18 + 105 * a + h2 * (-1 + a * (21 + h2)))) / 5040 + w * ((-561 + 945 * a + h2 * (-285 + 1260 * a + h2 * (-33 + 378 * a + h2 * (-1 + a * (36 + h2))))) / 362880 + w * ((-6555 + 10395 * a + h2 * (-4680 + 17325 * a + h2 * (-840 + 6930 * a + h2 * (-52 + 990 * a + h2 * (-1 + a * (55 + h2)))))) / 39916800 + ((-89055 + 135135 * a + h2 * (-82845 + 270270 * a + h2 * (-20370 + 135135 * a + h2 * (-1926 + 25740 * a + h2 * (-75 + 2145 * a + h2 * (-1 + a * (78 + h2))))))) * w) / 6227020800))))))
b = exp((-(h2 + w) / 2)) * expansion / sqrt2π
return abs(positive_part(b))
end
# const small_t_expansion_of_normalised_black_threshold = 2 * sixteenth_root_dbl_epsilon
function small_t_expansion_of_normalised_black_threshold(x)
return 2 * sixteenth_root_dbl_epsilon(x)
end
# b(x,s) = Φ(x/s+s/2)·exp(x/2) - Φ(x/s-s/2)·exp(-x/2)
# = Φ(h+t)·exp(x/2) - Φ(h-t)·exp(-x/2)
# with
# h = x/s and t = s/2
function normalised_black_call_using_normcdf(x, s)
h = x / s
t = s / 2
b_max = exp(x / 2)
@muladd b = normcdf(h + t) * b_max - normcdf(h - t) / b_max
return abs(positive_part(b))
end
#
# Introduced on 2017-02-18
#
# b(x,s) = Φ(x/s+s/2)·exp(x/2) - Φ(x/s-s/2)·exp(-x/2)
# = Φ(h+t)·exp(x/2) - Φ(h-t)·exp(-x/2)
# = ½ · exp(-u²-v²) · [ erfcx(u-v) - erfcx(u+v) ]
# = ½ · [ exp(x/2)·erfc(u-v) - exp(-x/2)·erfc(u+v) ]
# = ½ · [ exp(x/2)·erfc(u-v) - exp(-u²-v²)·erfcx(u+v) ]
# = ½ · [ exp(-u²-v²)·erfcx(u-v) - exp(-x/2)·erfc(u+v) ]
# with
# h = x/s , t = s/2 ,
# and
# u = -h/√2 and v = t/√2 .
#
# Cody's erfc() and erfcx() functions each, for some values of their argument, involve the evaluation
# of the exponential function exp(). The normalised Black function requires additional evaluation(s)
# of the exponential function irrespective of which of the above formulations is used. However, the total
# number of exponential function evaluations can be minimised by a judicious choice of one of the above
# formulations depending on the input values and the branch logic in Cody's erfc() and erfcx().
#
function normalised_black_call(x::T, s::V) where {T <: Real, V <: Real}
if (s <= 0)
return zero(x) # sigma=0 -> intrinsic value.
end
zero_typed = zero(promote_type(T, V))
small_t_expansion_of_normalised_black_threshold_ = small_t_expansion_of_normalised_black_threshold(zero_typed)
# Denote h := x/s and t := s/2.
# We evaluate the condition |h|>|η|, i.e., h<η && t < τ+|h|-|η| avoiding any divisions by s , where η = asymptotic_expansion_accuracy_threshold and τ = small_t_expansion_of_normalised_black_threshold .
s_2 = s / 2
s_square_mod = square(s) / 2 + x
z = x / s
s_div = s_square_mod / s
if (z < asymptotic_expansion_accuracy_threshold && s_div < (small_t_expansion_of_normalised_black_threshold_ + asymptotic_expansion_accuracy_threshold))
return asymptotic_expansion_of_normalised_black_call(z, s_2)
end
if (s_2 < small_t_expansion_of_normalised_black_threshold_)
return small_t_expansion_of_normalised_black_call(z, s_2)
end
if (s_div > 17 // 20)
return normalised_black_call_using_normcdf(x, s)
end
return normalised_black_call_using_erfcx(z, s_2)
end
function normalised_vega(x::T, s::V) where {T <: Real, V <: Real}
ax = abs(x)
zero_typed = zero(promote_type(T, V))
if (ax <= 0)
z = exp(-square(s) / 8)
return z / sqrt2π
elseif (s <= 0 || s <= ax * sqrt_dbl_min(zero_typed))
return zero_typed
end
return exp(-(square(x / s) + square(s / 2)) / 2) / sqrt2π
end
function normalised_vega_inverse(x::T, s::V) where {T <: Real, V <: Real}
ax = abs(x)
zero_typed = zero(promote_type(T, V))
if (ax <= 0)
z = exp(square(s) / 8)
return sqrt2π * z
elseif (s <= 0 || s <= ax * sqrt_dbl_min(zero_typed))
return dbl_max(zero_typed)
end
return exp((square(x / s) + square(s / 2)) / 2) * sqrt2π
end
function compute_f_lower_map_and_first_two_derivatives(x, s)
ax = abs(x)
z = ax / (sqrt3 * s)
y = square(z)
s2 = square(s)
Phi = normcdf(-z)
phi = normpdf(z)
exp_y_adj = exp(y + s2 / 8)
@muladd fpp = pi * y / (6 * s2 * s) * Phi * (8 * s * sqrt3 * ax + (3 * s2 * (s2 - 8) - 8 * square(x)) * Phi / phi) * square(exp_y_adj)
Phi2 = twoπ * square(Phi)
fp = y * Phi2 * exp_y_adj
f = ax * Phi2 / 3 * Phi / sqrt3
return f, fp, fpp
end
using SpecialFunctions
function inverse_normcdf(el)
return -erfcinv(2 * el) * sqrt2
end
function inverse_f_lower_map(x, f)
y = twoπ * abs(x) / 3
return abs(x / (sqrt3 * inverse_normcdf(cbrt(sqrt3 * f / y))))
end
function compute_f_upper_map_and_first_two_derivatives(x, s)
f = normcdf(-s / 2)
w = square(x / s)
fp = -exp(w / 2) / 2
fpp = sqrt2π * exp(w + square(s) / 8) / 2 * w / s
return f, fp, fpp
end
function inverse_f_upper_map(f)
return -2 * inverse_normcdf(f)
end
function unchecked_normalised_implied_volatility_from_a_transformed_rational_guess_with_limited_iterations(beta::T, x::V, N) where {T <: Real, V <: Real}
# Subtract intrinsic.
typed_zero = zero(promote_type(T, V))
typed_one = typed_zero + 1
b_max = exp(x / 2)
iterations = 0
direction_reversal_count = 0
dbl_max_typed = dbl_max(typed_zero)
dbl_eps_typed = dbl_epsilon(typed_zero)
dbl_min_typed = dbl_min(typed_zero)
sqrt_dbl_max_typed = sqrt(dbl_max_typed)
f = -dbl_max_typed
s = -dbl_max_typed
ds = s
ds_previous = 0
s_left = dbl_min_typed
s_right = dbl_max_typed
# The temptation is great to use the optimised form b_c = exp(x/2)/2-exp(-x/2)·Phi(sqrt(-2·x)) but that would require implementing all of the above types of round-off and over/underflow handling for this expression, too.
s_c = sqrt(abs(2 * x))
b_c = normalised_black_call(x, s_c)
v_c_inv = normalised_vega_inverse(x, s_c)
# Four branches.
if (beta < b_c)
s_l = s_c - b_c * v_c_inv
b_l = normalised_black_call(x, s_l)
if (beta < b_l)
f_lower_map_l, d_f_lower_map_l_d_beta, d2_f_lower_map_l_d_beta2 = compute_f_lower_map_and_first_two_derivatives(x, s_l)
r_ll = convex_rational_cubic_control_parameter_to_fit_second_derivative_at_right_side(typed_zero, b_l, typed_zero, f_lower_map_l, typed_one, d_f_lower_map_l_d_beta, d2_f_lower_map_l_d_beta2, true)
f = rational_cubic_interpolation(beta, typed_zero, b_l, typed_zero, f_lower_map_l, typed_one, d_f_lower_map_l_d_beta, r_ll)
if (!(f > 0)) # This can happen due to roundoff truncation for extreme values such as |x|>500.
# We switch to quadratic interpolation using f(0)≡0, f(b_l), and f'(0)≡1 to specify the quadratic.
t = beta / b_l
@muladd f = (f_lower_map_l * t + b_l * (1 - t)) * t
end
s = inverse_f_lower_map(x, f)
s_right = s_l
#
# In this branch, which comprises the lowest segment, the objective function is
# g(s) = 1/ln(b(x,s)) - 1/ln(beta)
# ≡ 1/ln(b(s)) - 1/ln(beta)
# This makes
# g' = -b'/(b·ln(b)²)
# newton = -g/g' = (ln(beta)-ln(b))·ln(b)/ln(beta)·b/b'
# halley = g''/g' = b''/b' - b'/b·(1+2/ln(b))
# hh3 = g'''/g' = b'''/b' + 2(b'/b)²·(1+3/ln(b)·(1+1/ln(b))) - 3(b''/b)·(1+2/ln(b))
#
# The Householder(3) iteration is
# s_n+1 = s_n + newton · [ 1 + halley·newton/2 ] / [ 1 + newton·( halley + hh3·newton/6 ) ]
#
while (iterations < N && abs(ds) > dbl_eps_typed * s)
iterations += 1
if (ds * ds_previous < 0)
direction_reversal_count += 1
end
if (iterations > 0 && (3 == direction_reversal_count || !(s > s_left && s < s_right)))
# If looping inefficently, or the forecast step takes us outside the bracket, or onto its edges, switch to binary nesting.
# NOTE that this can only really happen for very extreme values of |x|, such as |x| = |ln(F/K)| > 500.
s = (s_left + s_right) / 2
if (s_right - s_left <= dbl_eps_typed * s)
break
end
direction_reversal_count = 0
ds = 0
end
ds_previous = ds
b = normalised_black_call(x, s)
bp = normalised_vega(x, s)
if (b > beta && s < s_right)
s_right = s
elseif (b < beta && s > s_left)
s_left = s # Tighten the bracket if applicable.
end
if (b <= 0 || bp <= 0) # Numerical underflow. Switch to binary nesting for this iteration.
ds = (s_left + s_right) / 2 - s
else
ln_b = log(b)
ln_beta = log(beta)
bpob = bp / b
h = x / s
b_halley = square(h) / s - s / 4
newton = (ln_beta - ln_b) * ln_b / ln_beta / bpob
inv_lnb = inv(ln_b)
@muladd halley = b_halley - bpob * (1 + 2 * inv_lnb)
@muladd b_hh3 = square(b_halley) - 3 * square(h / s) - 1 // 4
@muladd hh3 = b_hh3 + 2 * square(bpob) * (1 + 3 * inv_lnb * (1 + inv_lnb)) - 3 * b_halley * bpob * (1 + 2 * inv_lnb)
ds = newton * householder_factor(newton, halley, hh3)
end
ds = max(-s / 2, ds)
s += ds
end
return s
else
v_l_inv = normalised_vega_inverse(x, s_l)
r_lm = convex_rational_cubic_control_parameter_to_fit_second_derivative_at_right_side(b_l, b_c, s_l, s_c, v_l_inv, v_c_inv, typed_zero, false)
s = rational_cubic_interpolation(beta, b_l, b_c, s_l, s_c, v_l_inv, v_c_inv, r_lm)
s_left = s_l
s_right = s_c
end
else
s_h = s_c
if (v_c_inv < dbl_max_typed)
s_h += (b_max - b_c) * v_c_inv
end
b_h = normalised_black_call(x, s_h)
if (beta <= b_h)
v_h_inv = normalised_vega_inverse(x, s_h)
r_hm = convex_rational_cubic_control_parameter_to_fit_second_derivative_at_left_side(b_c, b_h, s_c, s_h, v_c_inv, v_h_inv, typed_zero, false)
s = rational_cubic_interpolation(beta, b_c, b_h, s_c, s_h, v_c_inv, v_h_inv, r_hm)
s_left = s_c
s_right = s_h
else
f_upper_map_h, d_f_upper_map_h_d_beta, d2_f_upper_map_h_d_beta2 = compute_f_upper_map_and_first_two_derivatives(x, s_h)
if (d2_f_upper_map_h_d_beta2 > -sqrt_dbl_max_typed && d2_f_upper_map_h_d_beta2 < sqrt_dbl_max_typed)
r_hh = convex_rational_cubic_control_parameter_to_fit_second_derivative_at_left_side(b_h, b_max, f_upper_map_h, typed_zero, d_f_upper_map_h_d_beta, -typed_one * 1 // 2, d2_f_upper_map_h_d_beta2, true)
f = rational_cubic_interpolation(beta, b_h, b_max, f_upper_map_h, typed_zero, d_f_upper_map_h_d_beta, -typed_one * 1 // 2, r_hh)
end
if (f <= 0)
h = b_max - b_h
t = (beta - b_h) / h
omt = 1 - t
@muladd f = (f_upper_map_h * omt + h * t / 2) * omt # We switch to quadratic interpolation using f(b_h), f(b_max)≡0, and f'(b_max)≡-1/2 to specify the quadratic.
end
s = inverse_f_upper_map(f)
s_left = s_h
if (beta > b_max / 2) # Else we better drop through and let the objective function be g(s) = b(x,s)-beta.
#
# In this branch, which comprises the upper segment, the objective function is
# g(s) = ln(b_max-beta)-ln(b_max-b(x,s))
# ≡ ln((b_max-beta)/(b_max-b(s)))
# This makes
# g' = b'/(b_max-b)
# newton = -g/g' = ln((b_max-b)/(b_max-beta))·(b_max-b)/b'
# halley = g''/g' = b''/b' + b'/(b_max-b)
# hh3 = g'''/g' = b'''/b' + g'·(2g'+3b''/b')
# and the iteration is
# s_n+1 = s_n + newton · [ 1 + halley·newton/2 ] / [ 1 + newton·( halley + hh3·newton/6 ) ].
#
while (iterations < N && abs(ds) > dbl_eps_typed * s)
iterations += 1
if (ds * ds_previous < 0)
direction_reversal_count += 1
end
if (iterations > 0 && (3 == direction_reversal_count || !(s > s_left && s < s_right)))
# If looping inefficently, or the forecast step takes us outside the bracket, or onto its edges, switch to binary nesting.
# NOTE that this can only really happen for very extreme values of |x|, such as |x| = |ln(F/K)| > 500.
s = (s_left + s_right) / 2
if (s_right - s_left <= dbl_eps_typed * s)
break
end
direction_reversal_count = 0
ds = 0
end
ds_previous = ds
b = normalised_black_call(x, s)
bp = normalised_vega(x, s)
if (b > beta && s < s_right)
s_right = s
elseif (b < beta && s > s_left)
s_left = s # Tighten the bracket if applicable.
end
if (b >= b_max || bp <= dbl_min_typed) # Numerical underflow. Switch to binary nesting for this iteration.
ds = (s_left + s_right) / 2 - s
else
b_max_minus_b = b_max - b
g = log((b_max - beta) / b_max_minus_b)
gp = bp / b_max_minus_b
b_halley = square(x / s) / s - s / 4
@muladd b_hh3 = square(b_halley) - 3 * square(x / square(s)) - 1 // 4
newton = -g / gp
halley = b_halley + gp
@muladd hh3 = b_hh3 + gp * (2 * gp + 3 * b_halley)
ds = newton * householder_factor(newton, halley, hh3)
end
ds = max(-s / 2, ds)
s += ds
end
return s
end
end
end
# In this branch, which comprises the two middle segments, the objective function is g(s) = b(x,s)-beta, or g(s) = b(s) - beta, for short.
# This makes
# newton = -g/g' = -(b-beta)/b'
# halley = g''/g' = b''/b' = x²/s³-s/4
# hh3 = g'''/g' = b'''/b' = halley² - 3·(x/s²)² - 1/4
# and the iteration is
# s_n+1 = s_n + newton · [ 1 + halley·newton/2 ] / [ 1 + newton·( halley + hh3·newton/6 ) ].
#
while (iterations < N && abs(ds) > dbl_eps_typed * s)
iterations += 1
if (ds * ds_previous < 0)
direction_reversal_count += 1
end
if (iterations > 0 && (3 == direction_reversal_count || !(s > s_left && s < s_right)))
# If looping inefficently, or the forecast step takes us outside the bracket, or onto its edges, switch to binary nesting.
# NOTE that this can only really happen for very extreme values of |x|, such as |x| = |ln(F/K)| > 500.
s = (s_left + s_right) / 2
if (s_right - s_left <= dbl_eps_typed * s)
break
end
direction_reversal_count = 0
ds = 0
end
ds_previous = ds
b = normalised_black_call(x, s)
bp_inv = normalised_vega_inverse(x, s)
if (b > beta && s < s_right)
s_right = s
elseif (b < beta && s > s_left)
s_left = s # Tighten the bracket if applicable.
end
newton = (beta - b) * bp_inv
halley = square(x / s) / s - s / 4
hh3 = square(halley) - 3 * square(x / square(s)) - 1 // 4
ds = max(-s / 2, newton * householder_factor(newton, halley, hh3))
s += ds
end
return s
end
function blimpv_lets_be_rational(F::num1, K::num2, T::num4, price::num5, FlagIsCall::Bool, ::Real, niter::Integer) where {num1, num2, num4, num5}
x = log(F / K)
q = ifelse(FlagIsCall, 1, -1)
return unchecked_normalised_implied_volatility_from_a_transformed_rational_guess_with_limited_iterations(price / sqrt(F * K), x * q, niter) / sqrt(T)
end
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 1522 | using .ReverseDiff
# blsimpv_impl(x::ReverseDiff.TrackedReal,S0, K, r, T, price_d, d, FlagIsCall, xtol, ytol) = ReverseDiff.track(blsimpv_impl,x,S0, K, r, T, price_d, d, FlagIsCall, xtol, ytol)
# ReverseDiff.@grad function blsimpv_impl(x,S0, K, r, T, price_d, d, FlagIsCall, xtol, ytol)
# S0_r=ReverseDiff.value(S0)
# K_r=ReverseDiff.value(K)
# r_r=ReverseDiff.value(r)
# T_r=ReverseDiff.value(T)
# p_r=ReverseDiff.value(price_d)
# d_r=ReverseDiff.value(d)
# sigma = blsimpv(S0_r, K_r, r_r, T_r, p_r, d_r, FlagIsCall, xtol, ytol)
# function update_pullback(slice)
# inputs = [S0_r, K_r, r_r, T_r, sigma, d_r];
# @views fwd_grad=ReverseDiff.gradient(x -> blsprice(x[1], x[2], x[3], x[4], x[5], x[6], FlagIsCall), inputs)
# @views der_S0 = fwd_grad[1]
# @views der_K = fwd_grad[2]
# @views der_r = fwd_grad[3]
# @views der_T = fwd_grad[4]
# @views der_d = fwd_grad[6]
# @views slice_mod = -1 / fwd_grad[5]
# return 0, slice_mod * der_S0, slice_mod * der_K, slice_mod * der_r, slice_mod * der_T, -slice_mod, slice_mod * der_d, 0, 0, 0
# end
# return sigma, update_pullback
# end
function FinancialToolbox.blimpv_impl(::ReverseDiff.TrackedReal, S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
S0_r = ReverseDiff.value(S0)
K_r = ReverseDiff.value(K)
T_r = ReverseDiff.value(T)
p_r = ReverseDiff.value(price_d)
σ = blimpv(S0_r, K_r, T_r, p_r, FlagIsCall, xtol, n_iter_max)
der_ = blprice_diff_impl(S0, K, T, σ, price_d, FlagIsCall) / blvega_impl(S0_r, K_r, T_r, σ)
out = σ + der_
return out
end | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 2341 | using .Symbolics
function blcheck_impl(::num0, S0::num1, K::num2, T::num4, σ::num5) where {num0 <: Num, num1, num2, num4, num5}
return
end
@register_symbolic blimpv(S0, K, T, Price, FlagIsCall::Bool, xtol::Float64, n_iter_max::Int64)
function finalize_derivative_fwd(S0, K, T, σ, der_fwd)
vega = blvega_impl(S0, K, T, σ)
return der_fwd / vega
end
#TODO: implement derivatives
function Symbolics.derivative(::typeof(blimpv), args::NTuple{7, Any}, ::Val{1})
S0, K, T, price_d, FlagIsCall, xtol, n_iter_max = args
σ = blimpv(S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
@variables new_S0
D_S0 = Differential(new_S0)
price_diff = -blprice_impl(new_S0, K, T, σ, FlagIsCall)
der_fwd = expand_derivatives(D_S0(price_diff))
der_fwd = substitute(der_fwd, Dict(new_S0 => S0))
# der_fwd = -bldelta(S0, K, T, σ, FlagIsCall)
return finalize_derivative_fwd(S0, K, T, σ, der_fwd)
end
function Symbolics.derivative(::typeof(blimpv), args::NTuple{7, Any}, ::Val{2})
S0, K, T, price_d, FlagIsCall, xtol, n_iter_max = args
σ = blimpv(S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
@variables new_K
D_K = Differential(new_K)
price_diff = -blprice_impl(S0, new_K, T, σ, FlagIsCall)
der_fwd = expand_derivatives(D_K(price_diff))
der_fwd = substitute(der_fwd, Dict(new_K => K))
#der_fwd = bldelta(S0, K, r, T, σ, d, FlagIsCall)
return finalize_derivative_fwd(S0, K, T, σ, der_fwd)
end
function Symbolics.derivative(::typeof(blimpv), args::NTuple{7, Any}, ::Val{3})
S0, K, T, price_d, FlagIsCall, xtol, n_iter_max = args
σ = blimpv(S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
@variables new_T
D_T = Differential(new_T)
price_diff = -blprice_impl(S0, K, new_T, σ, FlagIsCall)
der_fwd = expand_derivatives(D_T(price_diff))
der_fwd = substitute(der_fwd, Dict(new_T => T))
#der_fwd = bldelta(S0, K, r, T, σ, d, FlagIsCall)
return finalize_derivative_fwd(S0, K, T, σ, der_fwd)
end
function Symbolics.derivative(::typeof(blimpv), args::NTuple{7, Any}, ::Val{4})
S0, K, T, price_d, FlagIsCall, xtol, n_iter_max = args
σ = blimpv(S0, K, T, price_d, FlagIsCall, xtol, n_iter_max)
vega = blvega_impl(S0, K, T, σ)
return inv(vega)
end
function Symbolics.derivative(::typeof(blimpv), ::NTuple{7, Any}, ::Any)
return 0
end | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 7917 | using .TaylorSeries
# function integrate_correct(a::Taylor1{T}, x::S) where {T <: Number, S <: Number}
# order = get_order(a)
# @views aa = a[0] / 1 + zero(x)
# R = typeof(aa)
# coeffs = Array{typeof(aa)}(undef, order + 2)
# # fill!(coeffs, zero(aa))
# @inbounds @views coeffs[1] = convert(R, x)
# @inbounds for i = 1:order+1
# @views coeffs[i+1] = a[i-1] / i
# end
# return Taylor1(coeffs)
# end
function mul_internal(f_der::Taylor1{T}, x::Taylor1{T}, k::Int) where {T <: Number}
k_1 = k + 1
@views @inbounds res = sum(f_der[i] * x[k_1-i] * (k_1 - i) for i = 0:k)
return res / k_1
end
function mul_and_integrate(f_der::Taylor1{T}, x::Taylor1{T}, y::S) where {T <: Number, S <: Number}
order = get_order(x)
res = Array{T}(undef, order + 1)
res_t = Taylor1(res)
@views @inbounds res_t[0] = y
@inbounds for i = 1:order
@views res_t[i] = mul_internal(f_der, x, i - 1)
end
return res_t
end
# function define_diff_rule(f, df)
# @eval function (op::typeof($f))(x::Taylor1)
# @views val = x[0]
# normpdf_res = ($df)(x)
# return FinancialToolbox.mul_and_integrate(normpdf_res, x, ($f)(val))
# end
# end
# define_diff_rule(normcdf, normpdf)
function FinancialToolbox.normcdf(x::Taylor1)
@views val = x[0]
# x_adj=Taylor1(x.co)
normpdf_res = normpdf(x)
# der = derivative(x)
return mul_and_integrate(normpdf_res, x, normcdf(val))
end
# function mul2!(c::HomogeneousPolynomial, a::HomogeneousPolynomial, b::HomogeneousPolynomial)
# (iszero(b) || iszero(a)) && return nothing
# @inbounds num_coeffs_a = size_table[a.order+1]
# @inbounds num_coeffs_b = size_table[b.order]
# @inbounds posTb = pos_table[c.order+1]
# @inbounds indTa = index_table[a.order+1]
# @inbounds indTb = index_table[b.order]
# @inbounds for na = 1:num_coeffs_a
# ca = a[na]
# # iszero(ca) && continue
# inda = indTa[na]
# @inbounds for nb = 1:num_coeffs_b
# cb = b[1+nb]
# # iszero(cb) && continue
# indb = indTb[nb]
# pos = posTb[inda+indb]
# c[pos] += ca * cb
# end
# end
# return nothing
# end
# function mul_and_integrate(f_der::TaylorN{T}, x::TaylorN{T}, y::S) where {T <: Number, S <: Number}
# order = get_order(x)
# res_t = Taylor1(order)
# @views @inbounds res_t[0] = y
# @inbounds for i = 1:order
# @views res_t[i] = mul_internal(f_der, x, i - 1)
# end
# return res_t
# end
# TODO: move to proper implementation: https://github.com/JuliaDiff/TaylorSeries.jl/issues/285
function FinancialToolbox.normcdf(x::TaylorN)
Nmax = 20000
xmin = -20.0
x_ = range(xmin, length = Nmax, stop = x)
dx = (x - xmin) / (Nmax - 1)
return sum(FinancialToolbox.normpdf.(x_)) * dx
end
# function normcdf2(x::TaylorN)
# @views val = x[0][1]
# normpdf_res = normpdf(x)
# grad = TaylorSeries.gradient(x)
# # PriceCall2-integrate(derivative(PriceCall2,3),3,PriceCall2[0][1])
# extreme_points2 = [(x - val - integrate(derivative(x, i), i)) for i in eachindex(grad)]
# # normpdf_res_adj = [(normpdf_res[0][1] + integrate(derivative(normpdf_res, i), i)) for i in eachindex(grad)]
# # @show grad
# # extreme_points2 = [sum(integrate(derivative(x, j), j) for j in eachindex(grad) if i != j) for i in eachindex(grad)]
# @show extreme_points2
# return normcdf(val) + sum(integrate(normpdf_res * grad[i], i, extreme_points2[i]) for i in eachindex(grad)) #- tmp_el
# end
# function normcdf3(x::TaylorN)
# @views val = x[0][1]
# normpdf_res = normpdf(x)
# # grad = TaylorSeries.gradient(x)
# # PriceCall2-integrate(derivative(PriceCall2,3),3,PriceCall2[0][1])
# # extreme_points = [(x - val - integrate(derivative(x, i), i)) for i in eachindex(grad)]
# # extreme_points = [(x - val - integrate(derivative(x, i), i)) for i in eachindex(grad)]
# # @show extreme_points
# # TaylorN([HomogeneousPolynomial([0.0]), HomogeneousPolynomial([0.0, 1.0, 1.0])])
# return normcdf(x[0][1]) + integrate(normpdf_res * derivative(x, 1), 1, x - integrate(derivative(x, 1), 1, x[0][1]))
# # return normcdf(val) + sum(integrate(normpdf_res * grad[i], i, extreme_points[i][0][1]) for i in eachindex(grad)) #- tmp_el
# end
value__d(x::Taylor1) = @views x[0]
value__d(x::TaylorN) = @views x[0][1]
value__d(x) = x
!hasmethod(isless, (Taylor1, Taylor1)) ? (Base.isless(x::Taylor1, y::Taylor1) = @views value__d(x) < value__d(y)) : nothing
!hasmethod(isless, (TaylorN, TaylorN)) ? (Base.isless(x::TaylorN, y::TaylorN) = @views value__d(x) < value__d(y)) : nothing
# function blsimpv_impl(::Taylor1, S0, K, r, T, price_d, d, FlagIsCall, xtol, ytol)
# S0_r = value__d(S0)
# K_r = value__d(K)
# r_r = value__d(r)
# T_r = value__d(T)
# p_r = value__d(price_d)
# d_r = value__d(d)
# sigma = blsimpv(S0_r, K_r, r_r, T_r, p_r, d_r, FlagIsCall, xtol, ytol)
# der_ = (price_d - blsprice(S0, K, r, T, sigma, d, FlagIsCall)) / blsvega(S0_r, K_r, r_r, T_r, sigma, d_r)
# out = sigma + der_
# return out
# end
get_order_adj(x::Taylor1) = get_order(x)
get_order_adj(::Any) = 0
function blimpv_impl(::Taylor1{V}, S0, K, T, price_d, FlagIsCall, xtol, n_iter_max) where {V}
S0_r = value__d(S0)
K_r = value__d(K)
T_r = value__d(T)
p_r = value__d(price_d)
sigma = blimpv(S0_r, K_r, T_r, p_r, FlagIsCall, xtol, n_iter_max)
max_order = maximum(map(x -> get_order_adj(x), (S0, K, T, price_d)))
vega = blvega_impl(S0_r, K_r, T_r, sigma)
σ_coeffs = Array{V}(undef, max_order + 1)
σ_coeffs .= NaN
@views σ_coeffs[1] = sigma
for i = 1:max_order
# @show σ_coeffs
new_c = deepcopy(σ_coeffs[1:i])
cur_sigma = Taylor1(new_c, i)
# cur_sigma += (price_d - blsprice(S0, K, r, T, cur_sigma, d, FlagIsCall))
cur_sigma += (price_d - blprice_impl(S0, K, T, cur_sigma, FlagIsCall)) / vega
# @views σ_coeffs[i+1] = cur_sigma[i] / vega
sigma_n = cur_sigma[i]
@views σ_coeffs[i+1] = sigma_n
end
return Taylor1(σ_coeffs)
end
# function blsimpv_impl(::TaylorN, S0, K, r, T, price_d, d, FlagIsCall, xtol, ytol)
# S0_r = value__d(S0)
# K_r = value__d(K)
# r_r = value__d(r)
# T_r = value__d(T)
# p_r = value__d(price_d)
# d_r = value__d(d)
# sigma = blsimpv(S0_r, K_r, r_r, T_r, p_r, d_r, FlagIsCall, xtol, ytol)
# der_ = (price_d - blsprice(S0, K, r, T, sigma, d, FlagIsCall)) / blsvega(S0_r, K_r, r_r, T_r, sigma, d_r, FlagIsCall)
# out = sigma + der_
# return out
# end
# @inline function blsimpv_impl(::TaylorN, S0, K, r, T, price_d, d, FlagIsCall, xtol, ytol)
# zero_type = S0 * K * r * T * d * price_d * 0
# S0_r = value__d(S0)
# K_r = value__d(K)
# r_r = value__d(r)
# T_r = value__d(T)
# p_r = value__d(price_d)
# d_r = value__d(d)
# sigma = blsimpv(S0_r, K_r, r_r, T_r, p_r, d_r, FlagIsCall, xtol, ytol)
# max_order = get_order(zero_type)
# vega = blsvega(S0_r, K_r, r_r, T_r, sigma, d_r)
# σ_coeffs = Array{Float64}[]
# # σ_coeffs = Array{Array{Float64}}(undef, get_order(zero_type) + 1)
# # σ_coeffs = Array{Float64}(undef, max_order + 1)
# push!(σ_coeffs, [sigma])
# # @views σ_coeffs[1] = [sigma]
# for i = 1:max_order
# @show σ_coeffs
# cur_sigma = TaylorN(HomogeneousPolynomial.(deepcopy(σ_coeffs)))
# @show cur_sigma
# @show price_d - blsprice(S0, K, r, T, cur_sigma, d, FlagIsCall)
# cur_sigma += (price_d - blsprice(S0, K, r, T, cur_sigma, d, FlagIsCall)) / vega
# @show cur_sigma
# σ_der = cur_sigma[i-1]
# push!(σ_coeffs, σ_der.coeffs)
# # @views σ_coefkfs[i+1] = σ_der
# end
# return TaylorN(HomogeneousPolynomial.(σ_coeffs))
# # return Taylor1(σ_coeffs)
# end | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 877 | function print_colored(in::String, color1)
if (VERSION.major == 0 && VERSION.minor <= 6)
return print_with_color(color1, in)
else
return printstyled(in, color = color1)
end
end
test_list = ["testRealNumbers.jl", "test_implied_volatility.jl", "test_implied_volatility_black.jl", "testComplexNumbers.jl", "testForwardDiff.jl", "testReverseDiff.jl", "testDual_.jl", "testHyperDualNumbers.jl", "testDates.jl", "testTaylor.jl", "testZygote.jl", "testDiffractor.jl", "testSymbolics.jl"]
println("Running tests:\n")
for (current_test, i) in zip(test_list, 1:length(test_list))
println("------------------------------------------------------------")
println(" * $(current_test) *")
include(current_test)
println("------------------------------------------------------------")
if (i < length(test_list))
println("")
end
end | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 5982 | if !(VERSION.major == 0 && VERSION.minor <= 6)
using Test
else
using Base.Test
end
using FinancialToolbox
print_colored("Starting Complex Number Test\n", :green)
#Test Parameters
testToll = 1e-14;
spot = 10;
K = 10;
r = 0.02;
T = 2.0;
sigma = 0.2;
d = 0.01;
assert_(value, toll) = @test abs(value) < toll
#EuropeanCall Option
PriceCall = blsprice(spot, K, r, T, sigma, d);
DeltaCall = blsdelta(spot, K, r, T, sigma, d);
ThetaCall = blstheta(spot, K, r, T, sigma, d);
LambdaCall = blslambda(spot, K, r, T, sigma, d);
RhoCall = blsrho(spot, K, r, T, sigma, d);
#EuropeanPut Option
PricePut = blsprice(spot, K, r, T, sigma, d, false);
DeltaPut = blsdelta(spot, K, r, T, sigma, d, false);
ThetaPut = blstheta(spot, K, r, T, sigma, d, false);
RhoPut = blsrho(spot, K, r, T, sigma, d, false);
LambdaPut = blslambda(spot, K, r, T, sigma, d, false);
#Equals for both Options
Gamma = blsgamma(spot, K, r, T, sigma, d);
Vega = blsvega(spot, K, r, T, sigma, d);
## Complex Test with Complex Step Approximation for European Call
#Test parameters
DerToll = 1e-13;
di = 1e-15;
df(f, x) = f(x + 1im * di) / di;
#Function definition
Fcall1(spot) = blsprice(spot, K, r, T, sigma, d);
Gcall1(r) = blsprice(spot, K, r, T, sigma, d);
Hcall1(T) = blsprice(spot, K, r, T, sigma, d);
Lcall1(sigma) = blsprice(spot, K, r, T, sigma, d);
Pcall1(spot) = blsprice(spot, K, r, T, sigma, d) * spot.re / blsprice(spot.re, K, r, T, sigma, d);
#TEST
print_colored("--- European Call Sensitivities: Complex Step Approximation\n", :yellow)
print_colored("-----Testing Delta\n", :blue);
assert_(df(Fcall1, spot).im - DeltaCall, DerToll)
print_colored("-----Testing Rho\n", :blue);
assert_(df(Gcall1, r).im - RhoCall, DerToll)
print_colored("-----Testing Theta\n", :blue);
assert_(-df(Hcall1, T).im - ThetaCall, DerToll)
print_colored("-----Testing Lambda\n", :blue);
assert_(df(Pcall1, spot).im - LambdaCall, DerToll)
## Complex Test with Complex Step Approximation for European Put
#Function definition
Fput1(spot) = blsprice(spot, K, r, T, sigma, d, false);
Gput1(r) = blsprice(spot, K, r, T, sigma, d, false);
Hput1(T) = blsprice(spot, K, r, T, sigma, d, false);
Pput1(spot) = blsprice(spot, K, r, T, sigma, d, false) * spot.re / blsprice(spot.re, K, r, T, sigma, d, false);
#TEST
print_colored("--- European Put Sensitivities: Complex Step Approximation\n", :yellow)
print_colored("-----Testing Delta\n", :blue);
assert_(df(Fput1, spot).im - DeltaPut, DerToll)
print_colored("-----Testing Rho\n", :blue);
assert_(df(Gput1, r).im - RhoPut, DerToll)
print_colored("-----Testing Theta\n", :blue);
assert_(-df(Hput1, T).im - ThetaPut, DerToll)
print_colored("-----Testing Lambda\n", :blue);
assert_(df(Pput1, spot).im - LambdaPut, DerToll)
print_colored("-----Testing Vega\n", :blue);
assert_(df(Lcall1, sigma).im - Vega, DerToll)
print_colored("Complex Number Test Passed\n", :green)
println("")
#TEST OF INPUT VALIDATION
print_colored("Starting Input Validation Test Complex\n", :magenta)
print_colored("----Testing Negative Spot Price \n", :cyan)
@test_throws(DomainError, blsprice(-spot + 1im, K, r, T, sigma, d))
@test_throws(DomainError, blkprice(-spot + 1im, K, r, T, sigma))
@test_throws(DomainError, blsdelta(-spot + 1im, K, r, T, sigma, d))
@test_throws(DomainError, blsgamma(-spot + 1im, K, r, T, sigma, d))
@test_throws(DomainError, blstheta(-spot + 1im, K, r, T, sigma, d))
@test_throws(DomainError, blsrho(-spot + 1im, K, r, T, sigma, d))
@test_throws(DomainError, blspsi(-spot + 1im, K, r, T, sigma, d))
@test_throws(DomainError, blslambda(-spot + 1im, K, r, T, sigma, d))
@test_throws(DomainError, blsvanna(-spot + 1im, K, r, T, sigma, d))
@test_throws(DomainError, blsvega(-spot + 1im, K, r, T, sigma, d))
print_colored("----Testing Negative Strike Price \n", :cyan)
@test_throws(DomainError, blsprice(spot, -K + 1im, r, T, sigma, d))
@test_throws(DomainError, blkprice(spot, -K + 1im, r, T, sigma))
@test_throws(DomainError, blsdelta(spot, -K + 1im, r, T, sigma, d))
@test_throws(DomainError, blsgamma(spot, -K + 1im, r, T, sigma, d))
@test_throws(DomainError, blstheta(spot, -K + 1im, r, T, sigma, d))
@test_throws(DomainError, blsrho(spot, -K + 1im, r, T, sigma, d))
@test_throws(DomainError, blspsi(spot, -K + 1im, r, T, sigma, d))
@test_throws(DomainError, blslambda(spot, -K + 1im, r, T, sigma, d))
@test_throws(DomainError, blsvanna(spot, -K + 1im, r, T, sigma, d))
@test_throws(DomainError, blsvega(spot, -K + 1im, r, T, sigma, d))
print_colored("----Testing Negative Time to Maturity \n", :cyan)
@test_throws(DomainError, blsprice(spot, K, r, -T + 1im, sigma, d))
@test_throws(DomainError, blkprice(spot, K, r, -T + 1im, sigma))
@test_throws(DomainError, blsdelta(spot, K, r, -T + 1im, sigma, d))
@test_throws(DomainError, blsgamma(spot, K, r, -T + 1im, sigma, d))
@test_throws(DomainError, blstheta(spot, K, r, -T + 1im, sigma, d))
@test_throws(DomainError, blsrho(spot, K, r, -T + 1im, sigma, d))
@test_throws(DomainError, blspsi(spot, K, r, -T + 1im, sigma, d))
@test_throws(DomainError, blslambda(spot, K, r, -T + 1im, sigma, d))
@test_throws(DomainError, blsvanna(spot, K, r, -T + 1im, sigma, d))
@test_throws(DomainError, blsvega(spot, K, r, -T + 1im, sigma, d))
print_colored("----Testing Negative Volatility \n", :cyan)
@test_throws(DomainError, blsprice(spot, K, r, T, -sigma + 1im, d))
@test_throws(DomainError, blkprice(spot, K, r, T, -sigma + 1im))
@test_throws(DomainError, blsdelta(spot, K, r, T, -sigma + 1im, d))
@test_throws(DomainError, blsgamma(spot, K, r, T, -sigma + 1im, d))
@test_throws(DomainError, blstheta(spot, K, r, T, -sigma + 1im, d))
@test_throws(DomainError, blsrho(spot, K, r, T, -sigma + 1im, d))
@test_throws(DomainError, blspsi(spot, K, r, T, -sigma + 1im, d))
@test_throws(DomainError, blslambda(spot, K, r, T, -sigma + 1im, d))
@test_throws(DomainError, blsvanna(spot, K, r, T, -sigma + 1im, d))
@test_throws(DomainError, blsvega(spot, K, r, T, -sigma + 1im, d))
print_colored("Complex Input Validation Test Passed\n", :magenta)
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 2923 | using FinancialToolbox
if !(VERSION.major == 0 && VERSION.minor <= 6)
using Test, Dates
else
using Base.Test
end
function yearFractionTester(StartDate, EndDate, MatlabResults, TestToll = 1e-14)
for i = 0:FinancialToolbox.currMaxImplemented
@test(abs(MatlabResults[i+1] - yearfrac(StartDate, EndDate, i)) < TestToll)
end
return
end
StartDate = Date(1992, 12, 14);
EndDate = Date(1996, 2, 28);
@test(-yearfrac(StartDate, StartDate, 0) == 0)
@test(-yearfrac(StartDate, EndDate, 0) == yearfrac(EndDate, StartDate, 0))
MatlabResults = [3.20821917808219; 3.20555555555556; 3.25277777777778; 3.20821917808219; 3.20555555555556; 3.20555555555556; 3.20555555555556; 3.20821917808219; 3.20821917808219; 3.25277777777778; 3.20821917808219; 3.20555555555556; 3.20765027322409];
yearFractionTester(StartDate, EndDate, MatlabResults);
EndDate2 = Date(1996, 2, 29);
MatlabResults2 = [3.21095890410959; 3.20833333333333; 3.25555555555556; 3.21095890410959; 3.20833333333333; 3.20833333333333; 3.20833333333333; 3.21095890410959; 3.21095890410959; 3.25555555555556; 3.21095890410959; 3.20833333333333; 3.21038251366122];
yearFractionTester(StartDate, EndDate2, MatlabResults2);
EndDate3 = Date(2026, 2, 28);
MatlabResults3 = [33.2301369863014; 33.2055555555556; 33.6916666666667; 33.2301369863014; 33.2055555555556; 33.2055555555556; 33.2055555555556; 33.2082191780822; 33.2301369863014; 33.6916666666667; 33.2301369863014; 33.2055555555556; 33.2080844374580];
TestToll = 1e-13;
yearFractionTester(StartDate, EndDate3, MatlabResults3, TestToll);
StartDate2 = Date(1992, 2, 29);
EndDate4 = Date(1996, 2, 29);
MatlabResults4 = [3.99180327868852; 4; 4.05833333333333; 4.00273972602740; 3.99722222222222; 4; 4; 4; 3.99180327868852; 4.05833333333333; 4.00273972602740; 4; 4]
yearFractionTester(StartDate2, EndDate4, MatlabResults4);
StartDate3 = Date(1992, 3, 30);
EndDate5 = Date(1996, 12, 31);
MatlabResults5 = [4.75890410958904; 4.75000000000000; 4.82500000000000; 4.75890410958904; 4.75000000000000; 4.75000000000000; 4.75000000000000; 4.75616438356164; 4.75890410958904; 4.82500000000000; 4.75890410958904; 4.75000000000000; 4.75409836065569]
yearFractionTester(StartDate3, EndDate5, MatlabResults5);
StartDate4 = Date(1992, 3, 31);
EndDate6 = Date(1996, 12, 30);
MatlabResults6 = [4.75342465753425; 4.75000000000000; 4.81944444444445; 4.75342465753425; 4.75000000000000; 4.75000000000000; 4.75000000000000; 4.75068493150685; 4.75342465753425; 4.81944444444445; 4.75342465753425; 4.75000000000000; 4.74863387978144]
yearFractionTester(StartDate4, EndDate6, MatlabResults6);
@test_throws(ErrorException, yearfrac(StartDate, EndDate3, FinancialToolbox.currMaxImplemented + 1));
@test_throws(ErrorException, yearfrac(StartDate, EndDate3, -1));
@test(daysact(Date(1992, 12, 14), Date(1992, 12, 13)) == -1)
##Excel test
@test(fromExcelNumberToDate(33952) == Date(1992, 12, 14))
println("Test Dates Passed")
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 578 | using FinancialToolbox, Diffractor, AbstractDifferentiation
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
σ = 0.2;
d = 0.01;
price = blsprice(S0, K, r, T, σ, d);
price_grad = AbstractDifferentiation.gradient(Diffractor.DiffractorForwardBackend(), x -> blsprice(x...), [S0, K, r, T, σ, d])
price_grad_r = Diffractor.reversediff(x -> blsprice(x...), [S0, K, r, T, σ, d])
sigma_grad = AbstractDifferentiation.gradient(Diffractor.DiffractorForwardBackend(), x -> blsimpv(x...), [S0, K, r, T, price, d])
sigma_grad_r = Diffractor.reversediff(x -> blsimpv(x...), [S0, K, r, T, price, d]) | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 7581 | using Test
using FinancialToolbox, DualNumbers
#Test Parameters
testToll = 1e-14;
#print_colored("Starting Standard Test\n",:green)
spot = 10;
K = 10;
r = 0.02;
T = 2.0;
sigma = 0.2;
d = 0.01;
spotDual = dual(spot, 1.0);
toll = 1e-6
#EuropeanCall Option
PriceCall = blsprice(spot, K, r, T, sigma, d);
PriceCallBlack = blkprice(spot, K, r, T, sigma);
df(f, x, dx) = (f(x + dx) - f(x)) / dx
dx = 1e-8;
assert_(value, toll) = @test abs(value) < toll
sigma1 = blsimpv(spot, K, r, T, PriceCall, d);
ResDual = blsimpv(spotDual, K, r, T, PriceCall, d);
DerDF_ = df(spot -> blsimpv(spot, K, r, T, PriceCall, d), spot, dx);
assert_(sigma1 - ResDual, toll)
assert_(DerDF_ - ResDual.epsilon, toll)
sigma1 = blkimpv(spot, K, r, T, PriceCallBlack);
ResDual = blkimpv(spotDual, K, r, T, PriceCallBlack);
DerDF_ = df(spot -> blkimpv(spot, K, r, T, PriceCallBlack), spot, dx);
assert_(sigma1 - ResDual, toll)
assert_(DerDF_ - ResDual.epsilon, toll)
print_colored("Starting DualNumbers Test\n", :green)
#Test Parameters
testToll = 1e-14;
spot = 10;
K = 10;
r = 0.02;
T = 2.0;
sigma = 0.2;
d = 0.01;
#EuropeanCall Option
PriceCall = blsprice(spot, K, r, T, sigma, d);
DeltaCall = blsdelta(spot, K, r, T, sigma, d);
ThetaCall = blstheta(spot, K, r, T, sigma, d);
RhoCall = blsrho(spot, K, r, T, sigma, d);
LambdaCall = blslambda(spot, K, r, T, sigma, d);
VannaCall = blsvanna(spot, K, r, T, sigma, d);
#EuropeanPut Option
PricePut = blsprice(spot, K, r, T, sigma, d, false);
DeltaPut = blsdelta(spot, K, r, T, sigma, d, false);
ThetaPut = blstheta(spot, K, r, T, sigma, d, false);
RhoPut = blsrho(spot, K, r, T, sigma, d, false);
LambdaPut = blslambda(spot, K, r, T, sigma, d, false);
VannaPut = blsvanna(spot, K, r, T, sigma, d, false);
#Equals for both Options
Gamma = blsgamma(spot, K, r, T, sigma, d);
Vega = blsvega(spot, K, r, T, sigma, d);
########DUAL NUMBERS
DerToll = 1e-13;
#Function definition
#Call
FcallDual(spot) = blsprice(spot, K, r, T, sigma, d);
GcallDual(r) = blsprice(spot, K, r, T, sigma, d);
HcallDual(T) = blsprice(spot, K, r, T, sigma, d);
LcallDual(sigma) = blsprice(spot, K, r, T, sigma, d);
PcallDual(spot) = blsprice(spot, K, r, T, sigma, d) * spot.value / blsprice(spot.value, K, r, T, sigma, d);
VcallDual(sigma) = blsdelta(spot, K, r, T, sigma, d);
#Put
FputDual(spot) = blsprice(spot, K, r, T, sigma, d, false);
GputDual(r) = blsprice(spot, K, r, T, sigma, d, false);
HputDual(T) = blsprice(spot, K, r, T, sigma, d, false);
PputDual(spot) = blsprice(spot, K, r, T, sigma, d, false) * spot.value / blsprice(spot.value, K, r, T, sigma, d, false);
VPutDual(sigma) = blsdelta(spot, K, r, T, sigma, d, false);
#Input
SpotDual = Dual(spot, 1.0);
rDual = Dual(r, 1.0);
TDual = Dual(T, 1.0);
SigmaDual = Dual(sigma, 1.0);
#Automatic Differentiation Test
#TEST
print_colored("--- European Call Sensitivities: DualNumbers\n", :yellow)
print_colored("-----Testing Delta\n", :blue);
assert_(FcallDual(SpotDual).epsilon - DeltaCall, DerToll)
print_colored("-----Testing Rho\n", :blue);
assert_(GcallDual(rDual).epsilon - RhoCall, DerToll)
print_colored("-----Testing Theta\n", :blue);
assert_(-HcallDual(TDual).epsilon - ThetaCall, DerToll)
print_colored("-----Testing Lambda\n", :blue);
assert_(PcallDual(SpotDual).epsilon - LambdaCall, DerToll)
print_colored("-----Testing Vanna\n", :blue);
assert_(VcallDual(SigmaDual).epsilon - VannaCall, DerToll)
#TEST
print_colored("--- European Put Sensitivities: DualNumbers\n", :yellow)
print_colored("-----Testing Delta\n", :blue);
assert_(FputDual(SpotDual).epsilon - DeltaPut, DerToll)
print_colored("-----Testing Rho\n", :blue);
assert_(GputDual(rDual).epsilon - RhoPut, DerToll)
print_colored("-----Testing Theta\n", :blue);
assert_(-HputDual(TDual).epsilon - ThetaPut, DerToll)
print_colored("-----Testing Lambda\n", :blue);
assert_(PputDual(SpotDual).epsilon - LambdaPut, DerToll)
print_colored("-----Testing Vanna\n", :blue);
assert_(VPutDual(SigmaDual).epsilon - VannaPut, DerToll)
print_colored("-----Testing Vega\n", :blue);
assert_(LcallDual(SigmaDual).epsilon - Vega, DerToll)
print_colored("Dual Numbers Test Passed\n", :green)
println("")
#TEST OF INPUT VALIDATION
print_colored("Starting Input Validation Test Dual\n", :magenta)
print_colored("----Testing Negative Spot Price \n", :cyan)
@test_throws(DomainError, blsprice(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blkprice(-SpotDual, K, r, T, sigma))
@test_throws(DomainError, blsdelta(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blsgamma(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blstheta(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blsrho(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blspsi(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blslambda(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blsvanna(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blsvega(-SpotDual, K, r, T, sigma, d))
print_colored("----Testing Negative Strike Price \n", :cyan)
KK = Dual(K, 0);
@test_throws(DomainError, blsprice(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blkprice(spot, -KK, r, T, sigma))
@test_throws(DomainError, blsdelta(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blsgamma(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blstheta(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blsrho(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blspsi(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blslambda(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blsvanna(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blsvega(spot, -KK, r, T, sigma, d))
print_colored("----Testing Negative Time to Maturity \n", :cyan)
@test_throws(DomainError, blsprice(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blkprice(spot, K, r, -TDual, sigma))
@test_throws(DomainError, blsdelta(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blsgamma(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blstheta(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blsrho(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blspsi(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blslambda(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blsvanna(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blsvega(spot, K, r, -TDual, sigma, d))
print_colored("----Testing Negative Volatility \n", :cyan)
@test_throws(DomainError, blsprice(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blkprice(spot, K, r, T, -SigmaDual))
@test_throws(DomainError, blsdelta(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blsgamma(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blstheta(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blsrho(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blspsi(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blslambda(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blsvanna(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blsvega(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blsimpv(spotDual, K, r, T, -0.2, d))
print_colored("Dual Input Validation Test Passed\n", :magenta)
price_dual = blsprice(SpotDual, K, r, T, sigma, d)
sigma_h1 = blsimpv(SpotDual, K, r, T, price_dual, d)
assert_(sigma_h1.value - sigma, DerToll)
assert_(sigma_h1.epsilon, DerToll)
price_dual2 = blsprice(SpotDual, K, r, T, SigmaDual, d)
sigma_h2 = blsimpv(SpotDual, K, r, T, price_dual2, d)
assert_(sigma_h2.value - SigmaDual.value, DerToll)
assert_(sigma_h2.epsilon - SigmaDual.epsilon, DerToll) | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 6774 | using Test
using ForwardDiff;
using FinancialToolbox
Dual_ = ForwardDiff.Dual
print_colored("Starting Forward Diff Dual Numbers Test\n", :green)
#Test Parameters
testToll = 1e-14;
spot = 10;
K = 10;
r = 0.02;
T = 2.0;
sigma = 0.2;
d = 0.01;
assert_(value, toll) = @test abs(value) < toll
#EuropeanCall Option
PriceCall = blsprice(spot, K, r, T, sigma, d);
DeltaCall = blsdelta(spot, K, r, T, sigma, d);
ThetaCall = blstheta(spot, K, r, T, sigma, d);
RhoCall = blsrho(spot, K, r, T, sigma, d);
LambdaCall = blslambda(spot, K, r, T, sigma, d);
VannaCall = blsvanna(spot, K, r, T, sigma, d);
#EuropeanPut Option
PricePut = blsprice(spot, K, r, T, sigma, d, false);
DeltaPut = blsdelta(spot, K, r, T, sigma, d, false);
ThetaPut = blstheta(spot, K, r, T, sigma, d, false);
RhoPut = blsrho(spot, K, r, T, sigma, d, false);
LambdaPut = blslambda(spot, K, r, T, sigma, d, false);
VannaPut = blsvanna(spot, K, r, T, sigma, d, false);
#Equals for both Options
Gamma = blsgamma(spot, K, r, T, sigma, d);
Vega = blsvega(spot, K, r, T, sigma, d);
########DUAL NUMBERS
DerToll = 1e-13;
#Function definition
#Call
FcallDual(spot) = blsprice(spot, K, r, T, sigma, d);
GcallDual(r) = blsprice(spot, K, r, T, sigma, d);
HcallDual(T) = blsprice(spot, K, r, T, sigma, d);
LcallDual(sigma) = blsprice(spot, K, r, T, sigma, d);
PcallDual(spot) = blsprice(spot, K, r, T, sigma, d) * spot.value / blsprice(spot.value, K, r, T, sigma, d);
VcallDual(sigma) = blsdelta(spot, K, r, T, sigma, d);
#Put
FputDual(spot) = blsprice(spot, K, r, T, sigma, d, false);
GputDual(r) = blsprice(spot, K, r, T, sigma, d, false);
HputDual(T) = blsprice(spot, K, r, T, sigma, d, false);
PputDual(spot) = blsprice(spot, K, r, T, sigma, d, false) * spot.value / blsprice(spot.value, K, r, T, sigma, d, false);
VPutDual(sigma) = blsdelta(spot, K, r, T, sigma, d, false);
#Input
SpotDual = Dual_(spot, 1.0);
rDual = Dual_(r, 1.0);
TDual = Dual_(T, 1.0);
SigmaDual = Dual_(sigma, 1.0);
#Automatic Differentiation Test
#TEST
print_colored("--- European Call Sensitivities: DualNumbers\n", :yellow)
print_colored("-----Testing Delta\n", :blue);
assert_(FcallDual(SpotDual).partials[1] - DeltaCall, DerToll)
print_colored("-----Testing Rho\n", :blue);
assert_(GcallDual(rDual).partials[1] - RhoCall, DerToll)
print_colored("-----Testing Theta\n", :blue);
assert_(-HcallDual(TDual).partials[1] - ThetaCall, DerToll)
print_colored("-----Testing Lambda\n", :blue);
assert_(PcallDual(SpotDual).partials[1] - LambdaCall, DerToll)
print_colored("-----Testing Vanna\n", :blue);
assert_(VcallDual(SigmaDual).partials[1] - VannaCall, DerToll)
#TEST
print_colored("--- European Put Sensitivities: DualNumbers\n", :yellow)
print_colored("-----Testing Delta\n", :blue);
assert_(FputDual(SpotDual).partials[1] - DeltaPut, DerToll)
print_colored("-----Testing Rho\n", :blue);
assert_(GputDual(rDual).partials[1] - RhoPut, DerToll)
print_colored("-----Testing Theta\n", :blue);
assert_(-HputDual(TDual).partials[1] - ThetaPut, DerToll)
print_colored("-----Testing Lambda\n", :blue);
assert_(PputDual(SpotDual).partials[1] - LambdaPut, DerToll)
print_colored("-----Testing Vanna\n", :blue);
assert_(VPutDual(SigmaDual).partials[1] - VannaPut, DerToll)
print_colored("-----Testing Vega\n", :blue);
assert_(LcallDual(SigmaDual).partials[1] - Vega, DerToll)
print_colored("Dual Numbers Test Passed\n", :green)
println("")
#TEST OF INPUT VALIDATION
print_colored("Starting Input Validation Test Dual\n", :magenta)
print_colored("----Testing Negative Spot Price \n", :cyan)
@test_throws(DomainError, blsprice(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blkprice(-SpotDual, K, r, T, sigma))
@test_throws(DomainError, blsdelta(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blsgamma(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blstheta(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blsrho(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blspsi(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blslambda(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blsvanna(-SpotDual, K, r, T, sigma, d))
@test_throws(DomainError, blsvega(-SpotDual, K, r, T, sigma, d))
print_colored("----Testing Negative Strike Price \n", :cyan)
KK = Dual_(K, 0);
@test_throws(DomainError, blsprice(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blkprice(spot, -KK, r, T, sigma))
@test_throws(DomainError, blsdelta(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blsgamma(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blstheta(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blsrho(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blspsi(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blslambda(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blsvanna(spot, -KK, r, T, sigma, d))
@test_throws(DomainError, blsvega(spot, -KK, r, T, sigma, d))
print_colored("----Testing Negative Time to Maturity \n", :cyan)
@test_throws(DomainError, blsprice(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blkprice(spot, K, r, -TDual, sigma))
@test_throws(DomainError, blsdelta(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blsgamma(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blstheta(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blsrho(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blspsi(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blslambda(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blsvanna(spot, K, r, -TDual, sigma, d))
@test_throws(DomainError, blsvega(spot, K, r, -TDual, sigma, d))
print_colored("----Testing Negative Volatility \n", :cyan)
@test_throws(DomainError, blsprice(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blkprice(spot, K, r, T, -SigmaDual))
@test_throws(DomainError, blsdelta(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blsgamma(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blstheta(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blsrho(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blspsi(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blslambda(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blsvanna(spot, K, r, T, -SigmaDual, d))
@test_throws(DomainError, blsvega(spot, K, r, T, -SigmaDual, d))
print_colored("Dual Input Validation Test Passed\n", :magenta)
price_dual = blsprice(SpotDual, K, r, T, sigma, d)
sigma_h1 = blsimpv(SpotDual, K, r, T, price_dual, d)
assert_(sigma_h1.value - sigma, DerToll)
assert_(sigma_h1.partials[1], DerToll)
price_dual2 = blsprice(SpotDual, K, r, T, SigmaDual, d)
sigma_h2 = blsimpv(SpotDual, K, r, T, price_dual2, d)
assert_(sigma_h2.value - SigmaDual.value, DerToll)
assert_(sigma_h2.partials[1] - SigmaDual.partials[1], DerToll) | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 8338 | if !(VERSION.major == 0 && VERSION.minor <= 6)
using Test
else
using Base.Test
end
using FinancialToolbox
print_colored("Starting Hyper Dual Numbers Test\n", :green)
#Test Parameters
testToll = 1e-14;
spot = 10;
K = 10;
r = 0.02;
T = 2.0;
sigma = 0.2;
d = 0.01;
assert_(value, toll) = @test abs(value) < toll
#EuropeanCall Option
PriceCall = blsprice(spot, K, r, T, sigma, d);
DeltaCall = blsdelta(spot, K, r, T, sigma, d);
ThetaCall = blstheta(spot, K, r, T, sigma, d);
RhoCall = blsrho(spot, K, r, T, sigma, d);
LambdaCall = blslambda(spot, K, r, T, sigma, d);
VannaCall = blsvanna(spot, K, r, T, sigma, d);
#EuropeanPut Option
PricePut = blsprice(spot, K, r, T, sigma, d, false);
DeltaPut = blsdelta(spot, K, r, T, sigma, d, false);
ThetaPut = blstheta(spot, K, r, T, sigma, d, false);
RhoPut = blsrho(spot, K, r, T, sigma, d, false);
LambdaPut = blslambda(spot, K, r, T, sigma, d, false);
VannaPut = blsvanna(spot, K, r, T, sigma, d, false);
#Equals for both Options
Gamma = blsgamma(spot, K, r, T, sigma, d);
Vega = blsvega(spot, K, r, T, sigma, d);
########HYPER DUAL NUMBERS
using HyperDualNumbers;
DerToll = 1e-13;
di = 1e-15;
#Function definition
SpotHyper = hyper(spot, 1.0, 1.0, 0.0);
rHyper = hyper(r, 1.0, 1.0, 0.0);
THyper = hyper(T, 1.0, 1.0, 0.0);
SigmaHyper = hyper(sigma, 1.0, 1.0, 0.0);
KHyper = hyper(K, 1.0, 1.0, 0.0);
#Function definition
#Call
F(spot) = blsprice(spot, K, r, T, sigma, d);
FF(spot) = blsdelta(spot, K, r, T, sigma, d);
G(r) = blsprice(spot, K, r, T, sigma, d);
H(T) = blsprice(spot, K, r, T, sigma, d);
L(sigma) = blsprice(spot, K, r, T, sigma, d);
P(spot) = blsprice(spot, K, r, T, sigma, d) * spot.value / blsprice(spot.value, K, r, T, sigma, d);
V(sigma) = blsdelta(spot, K, r, T, sigma, d);
VV(spot, sigma) = blsprice(spot, K, r, T, sigma, d);
#Put
F1(spot) = blsprice(spot, K, r, T, sigma, d, false);
FF1(spot) = blsdelta(spot, K, r, T, sigma, d, false);
G1(r) = blsprice(spot, K, r, T, sigma, d, false);
H1(T) = blsprice(spot, K, r, T, sigma, d, false);
P1(spot) = blsprice(spot, K, r, T, sigma, d, false) * spot.value / blsprice(spot.value, K, r, T, sigma, d, false);
V1(sigma) = blsdelta(spot, K, r, T, sigma, d, false);
V11(spot, sigma) = blsprice(spot, K, r, T, sigma, d, false);
#TEST
print_colored("--- European Call Sensitivities: HyperDualNumbers\n", :yellow)
print_colored("-----Testing Delta\n", :blue);
assert_(F(SpotHyper).epsilon1 - DeltaCall, DerToll)
print_colored("-----Testing Gamma\n", :blue);
assert_(FF1(SpotHyper).epsilon1 - Gamma, DerToll)
print_colored("-----Testing Gamma 2\n", :blue);
assert_(F(SpotHyper).epsilon12 - Gamma, DerToll)
print_colored("-----Testing Rho\n", :blue);
assert_(G(rHyper).epsilon1 - RhoCall, DerToll)
print_colored("-----Testing Theta\n", :blue);
assert_(-H(THyper).epsilon1 - ThetaCall, DerToll)
print_colored("-----Testing Lambda\n", :blue);
assert_(P(SpotHyper).epsilon1 - LambdaCall, DerToll)
print_colored("-----Testing Vanna\n", :blue);
assert_(V(SigmaHyper).epsilon1 - VannaCall, DerToll)
print_colored("-----Testing Vanna 2\n", :blue);
assert_(VV(hyper(spot, 1, 0, 0), hyper(sigma, 0, 1, 0)).epsilon12 - VannaCall, DerToll)
## Complex Test with Complex Step Approximation for European Put
#TEST
print_colored("--- European Put Sensitivities: HyperDualNumbers\n", :yellow)
print_colored("-----Testing Delta\n", :blue);
assert_(F1(SpotHyper).epsilon1 - DeltaPut, DerToll)
print_colored("-----Testing Rho\n", :blue);
assert_(G1(rHyper).epsilon1 - RhoPut, DerToll)
print_colored("-----Testing Theta\n", :blue);
assert_(-H1(THyper).epsilon1 - ThetaPut, DerToll)
print_colored("-----Testing Lambda\n", :blue);
assert_(P1(SpotHyper).epsilon1 - LambdaPut, DerToll)
print_colored("-----Testing Vanna\n", :blue);
assert_(V1(SigmaHyper).epsilon1 - VannaPut, DerToll)
print_colored("-----Testing Vanna 2\n", :blue);
assert_(V11(hyper(spot, 1, 0, 0), hyper(sigma, 0, 1, 0)).epsilon12 - VannaPut, DerToll)
print_colored("-----Testing Vega\n", :blue);
assert_(L(SigmaHyper).epsilon1 - Vega, DerToll)
print_colored("Hyper Dual Numbers Test Passed\n\n", :green)
#TEST OF INPUT VALIDATION
print_colored("Starting Input Validation Test Hyper Dual Numbers\n", :magenta)
print_colored("----Testing Negative Spot Price \n", :cyan)
@test_throws(DomainError, blsprice(-SpotHyper, K, r, T, sigma, d))
@test_throws(DomainError, blkprice(-SpotHyper, K, r, T, sigma))
@test_throws(DomainError, blsdelta(-SpotHyper, K, r, T, sigma, d))
@test_throws(DomainError, blsgamma(-SpotHyper, K, r, T, sigma, d))
@test_throws(DomainError, blstheta(-SpotHyper, K, r, T, sigma, d))
@test_throws(DomainError, blsrho(-SpotHyper, K, r, T, sigma, d))
@test_throws(DomainError, blspsi(-SpotHyper, K, r, T, sigma, d))
@test_throws(DomainError, blslambda(-SpotHyper, K, r, T, sigma, d))
@test_throws(DomainError, blsvanna(-SpotHyper, K, r, T, sigma, d))
@test_throws(DomainError, blsvega(-SpotHyper, K, r, T, sigma, d))
print_colored("----Testing Negative Strike Price \n", :cyan)
@test_throws(DomainError, blsprice(spot, -KHyper, r, T, sigma, d))
@test_throws(DomainError, blkprice(spot, -KHyper, r, T, sigma))
@test_throws(DomainError, blsdelta(spot, -KHyper, r, T, sigma, d))
@test_throws(DomainError, blsgamma(spot, -KHyper, r, T, sigma, d))
@test_throws(DomainError, blstheta(spot, -KHyper, r, T, sigma, d))
@test_throws(DomainError, blsrho(spot, -KHyper, r, T, sigma, d))
@test_throws(DomainError, blspsi(spot, -KHyper, r, T, sigma, d))
@test_throws(DomainError, blslambda(spot, -KHyper, r, T, sigma, d))
@test_throws(DomainError, blsvanna(spot, -KHyper, r, T, sigma, d))
@test_throws(DomainError, blsvega(spot, -KHyper, r, T, sigma, d))
print_colored("----Testing Negative Time to Maturity \n", :cyan)
@test_throws(DomainError, blsprice(spot, K, r, -THyper, sigma, d))
@test_throws(DomainError, blkprice(spot, K, r, -THyper, sigma))
@test_throws(DomainError, blsdelta(spot, K, r, -THyper, sigma, d))
@test_throws(DomainError, blsgamma(spot, K, r, -THyper, sigma, d))
@test_throws(DomainError, blstheta(spot, K, r, -THyper, sigma, d))
@test_throws(DomainError, blsrho(spot, K, r, -THyper, sigma, d))
@test_throws(DomainError, blspsi(spot, K, r, -THyper, sigma, d))
@test_throws(DomainError, blslambda(spot, K, r, -THyper, sigma, d))
@test_throws(DomainError, blsvanna(spot, K, r, -THyper, sigma, d))
@test_throws(DomainError, blsvega(spot, K, r, -THyper, sigma, d))
print_colored("----Testing Negative Volatility \n", :cyan)
@test_throws(DomainError, blsprice(spot, K, r, T, -SigmaHyper, d))
@test_throws(DomainError, blkprice(spot, K, r, T, -SigmaHyper))
@test_throws(DomainError, blsdelta(spot, K, r, T, -SigmaHyper, d))
@test_throws(DomainError, blsgamma(spot, K, r, T, -SigmaHyper, d))
@test_throws(DomainError, blstheta(spot, K, r, T, -SigmaHyper, d))
@test_throws(DomainError, blsrho(spot, K, r, T, -SigmaHyper, d))
@test_throws(DomainError, blspsi(spot, K, r, T, -SigmaHyper, d))
@test_throws(DomainError, blslambda(spot, K, r, T, -SigmaHyper, d))
@test_throws(DomainError, blsvanna(spot, K, r, T, -SigmaHyper, d))
@test_throws(DomainError, blsvega(spot, K, r, T, -SigmaHyper, d))
print_colored("Hyper Dual Input Validation Test Passed\n", :magenta)
price_dual = blsprice(SpotHyper, K, r, T, sigma, d)
sigma_h1 = blsimpv(SpotHyper, K, r, T, price_dual, d)
assert_(sigma_h1.value - sigma, DerToll)
assert_(sigma_h1.epsilon1, DerToll)
assert_(sigma_h1.epsilon12, DerToll)
price_dual2 = blsprice(SpotHyper, K, r, T, SigmaHyper, d)
sigma_h2 = blsimpv(SpotHyper, K, r, T, price_dual2, d)
assert_(sigma_h2.value - SigmaHyper.value, DerToll)
assert_(sigma_h2.epsilon1 - SigmaHyper.epsilon1, DerToll)
assert_(sigma_h2.epsilon12 - SigmaHyper.epsilon12, DerToll)
price_dual2 = blsprice(SpotHyper, KHyper, r, T, SigmaHyper, d)
sigma_h2 = blsimpv(SpotHyper, KHyper, r, T, price_dual2, d)
assert_(sigma_h2.value - SigmaHyper.value, DerToll)
assert_(sigma_h2.epsilon1 - SigmaHyper.epsilon1, DerToll)
assert_(sigma_h2.epsilon12 - SigmaHyper.epsilon12, DerToll)
SigmaHyper = hyper(sigma, 1.0, 2.0, 3.0);
price_dual2 = blsprice(SpotHyper, KHyper, r, T, SigmaHyper, d)
sigma_h2 = blsimpv(SpotHyper, KHyper, r, T, price_dual2, d)
assert_(sigma_h2.value - SigmaHyper.value, DerToll)
assert_(sigma_h2.epsilon1 - SigmaHyper.epsilon1, DerToll)
assert_(sigma_h2.epsilon2 - SigmaHyper.epsilon2, DerToll)
assert_(sigma_h2.epsilon12 - SigmaHyper.epsilon12, DerToll)
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 8130 | if !(VERSION.major == 0 && VERSION.minor <= 6)
using Test
else
using Base.Test
end
using FinancialToolbox
#Test Parameters
testToll = 1e-14;
print_colored("Starting Standard Test\n", :green)
spot = 10;
K = 10;
r = 0.02;
T = 2.0;
sigma = 0.2;
d = 0.01;
assert_(value, toll) = @test abs(value) < toll
#EuropeanCall Option
PriceCall = blsprice(spot, K, r, T, sigma, d);
PriceCallBig = blsprice(big.([spot, K, r, T, sigma, d])...);
PriceCall32 = blsprice(Float32.([spot, K, r, T, sigma, d])...);
PriceCall16 = blsprice(Float16.([spot, K, r, T, sigma, d])...);
PriceBinaryCall = blsbin(spot, K, r, T, sigma, d);
PriceCallBlack = blkprice(spot, K, r, T, sigma);
DeltaCall = blsdelta(spot, K, r, T, sigma, d);
ThetaCall = blstheta(spot, K, r, T, sigma, d);
RhoCall = blsrho(spot, K, r, T, sigma, d);
VannaCall = blsvanna(spot, K, r, T, sigma, d);
PsiCall = blspsi(spot, K, r, T, sigma, d);
LambdaCall = blslambda(spot, K, r, T, sigma, d);
SigmaCall = blsimpv(spot, K, r, T, PriceCall, d);
SigmaCallBlack = blkimpv(spot, K, r, T, PriceCallBlack);
#EuropeanPut Option
PricePut = blsprice(spot, K, r, T, sigma, d, false);
PriceBinaryPut = blsbin(spot, K, r, T, sigma, d, false);
PricePutBlack = blkprice(spot, K, r, T, sigma, false);
DeltaPut = blsdelta(spot, K, r, T, sigma, d, false);
ThetaPut = blstheta(spot, K, r, T, sigma, d, false);
VannaPut = blsvanna(spot, K, r, T, sigma, d, false);
PsiPut = blspsi(spot, K, r, T, sigma, d, false);
LambdaPut = blslambda(spot, K, r, T, sigma, d, false);
RhoPut = blsrho(spot, K, r, T, sigma, d, false);
SigmaPut = blsimpv(spot, K, r, T, PricePut, d, false);
SigmaPutBlack = blkimpv(spot, K, r, T, PricePutBlack, false);
#Equals for both Options
Gamma = blsgamma(spot, K, r, T, sigma, d);
Vega = blsvega(spot, K, r, T, sigma, d);
print_colored("--- European Call: Price and Sensitivities\n", :yellow)
#Standard Test European Call Option
print_colored("-----Testing Price\n", :blue);
assert_(PriceCall - 1.191201316999582, testToll)
assert_(PriceCall - 1.191201316999582, testToll)
assert_(PriceCall - 1.191201316999582, testToll)
print_colored("-----Testing Price Binary\n", :blue);
assert_(PriceBinaryCall - 0.4533139191104102, testToll)
print_colored("-----Testing Black Price\n", :blue);
assert_(PriceCallBlack - 1.080531820066428, testToll)
print_colored("-----Testing Delta\n", :blue);
assert_(DeltaCall - 0.572434050810368, testToll)
print_colored("-----Testing Theta\n", :blue);
assert_(ThetaCall + 0.303776337550247, testToll)
print_colored("-----Testing Rho\n", :blue);
assert_(RhoCall - 9.066278382208203, testToll)
print_colored("-----Testing Lambda\n", :blue);
assert_(LambdaCall - 4.805518955034612, testToll)
print_colored("-----Testing Implied Volatility\n", :blue);
assert_(SigmaCall - 0.2, testToll)
print_colored("-----Testing Implied Volatility Black\n", :blue);
assert_(SigmaCallBlack - 0.2, testToll)
print_colored("--- European Put: Price and Sensitivities\n", :yellow)
#Standard Test European Put Option
print_colored("-----Testing Price\n", :blue);
assert_(PricePut - 0.997108975455260, testToll)
print_colored("-----Testing Binary Price\n", :blue);
assert_(PriceBinaryPut - 0.507475520041913, testToll)
print_colored("-----Testing Price Black\n", :blue);
assert_(PricePutBlack - 1.080531820066428, testToll)
print_colored("-----Testing Delta\n", :blue);
assert_(DeltaPut + 0.407764622496387, testToll)
print_colored("-----Testing Theta\n", :blue);
assert_(ThetaPut + 0.209638317050458, testToll)
print_colored("-----Testing Rho\n", :blue);
assert_(RhoPut + 10.149510400838260, testToll)
print_colored("-----Testing Lambda\n", :blue);
assert_(LambdaPut + 4.089468980160465, testToll)
print_colored("-----Testing Implied Volatility\n", :blue);
assert_(SigmaPut - 0.2, testToll)
print_colored("-----Testing Implied Volatility Black\n", :blue);
assert_(SigmaPutBlack - 0.2, testToll)
#Standard Test for Common Sensitivities
print_colored("-----Testing Gamma\n", :blue);
assert_(Gamma - 0.135178479404601, testToll)
print_colored("-----Testing Vega\n", :blue);
assert_(Vega - 5.407139176184034, testToll)
print_colored("Standard Test Passed\n", :green)
println("")
#TEST OF INPUT VALIDATION
print_colored("Starting Input Validation Test Real\n", :magenta)
print_colored("----Testing Negative Spot Price\n", :cyan)
@test_throws(DomainError, blsprice(-spot, K, r, T, sigma, d))
@test_throws(DomainError, blkprice(-spot, K, r, T, sigma))
@test_throws(DomainError, blsdelta(-spot, K, r, T, sigma, d))
@test_throws(DomainError, blsgamma(-spot, K, r, T, sigma, d))
@test_throws(DomainError, blstheta(-spot, K, r, T, sigma, d))
@test_throws(DomainError, blsrho(-spot, K, r, T, sigma, d))
@test_throws(DomainError, blsvega(-spot, K, r, T, sigma, d));
@test_throws(DomainError, blspsi(-spot, K, r, T, sigma, d))
@test_throws(DomainError, blslambda(-spot, K, r, T, sigma, d))
@test_throws(DomainError, blsvanna(-spot, K, r, T, sigma, d))
@test_throws(DomainError, blsimpv(-spot, K, r, T, PriceCall, d))
@test_throws(DomainError, blkimpv(-spot, K, r, T, PriceCall))
print_colored("----Testing Negative Strike Price\n", :cyan)
@test_throws(DomainError, blsprice(spot, -K, r, T, sigma, d))
@test_throws(DomainError, blkprice(spot, -K, r, T, sigma))
@test_throws(DomainError, blsdelta(spot, -K, r, T, sigma, d))
@test_throws(DomainError, blsgamma(spot, -K, r, T, sigma, d))
@test_throws(DomainError, blstheta(spot, -K, r, T, sigma, d))
@test_throws(DomainError, blsrho(spot, -K, r, T, sigma, d))
@test_throws(DomainError, blsvega(spot, -K, r, T, sigma, d))
@test_throws(DomainError, blspsi(spot, -K, r, T, sigma, d))
@test_throws(DomainError, blslambda(spot, -K, r, T, sigma, d))
@test_throws(DomainError, blsvanna(spot, -K, r, T, sigma, d))
@test_throws(DomainError, blsimpv(spot, -K, r, T, PriceCall, d))
@test_throws(DomainError, blkimpv(spot, -K, r, T, PriceCall))
print_colored("----Testing Negative Time to Maturity\n", :cyan)
@test_throws(DomainError, blsprice(spot, K, r, -T, sigma, d))
@test_throws(DomainError, blkprice(spot, K, r, -T, sigma))
@test_throws(DomainError, blsdelta(spot, K, r, -T, sigma, d))
@test_throws(DomainError, blsgamma(spot, K, r, -T, sigma, d))
@test_throws(DomainError, blstheta(spot, K, r, -T, sigma, d))
@test_throws(DomainError, blsrho(spot, K, r, -T, sigma, d))
@test_throws(DomainError, blsvega(spot, K, r, -T, sigma, d))
@test_throws(DomainError, blspsi(spot, K, r, -T, sigma, d))
@test_throws(DomainError, blslambda(spot, K, r, -T, sigma, d))
@test_throws(DomainError, blsvanna(spot, K, r, -T, sigma, d))
@test_throws(DomainError, blsimpv(spot, K, r, -T, PriceCall, d))
@test_throws(DomainError, blkimpv(spot, K, r, -T, PriceCall))
print_colored("----Testing Negative Volatility\n", :cyan)
@test_throws(DomainError, blsprice(spot, K, r, T, -sigma, d))
@test_throws(DomainError, blkprice(spot, K, r, T, -sigma))
@test_throws(DomainError, blsdelta(spot, K, r, T, -sigma, d))
@test_throws(DomainError, blsgamma(spot, K, r, T, -sigma, d))
@test_throws(DomainError, blstheta(spot, K, r, T, -sigma, d))
@test_throws(DomainError, blsrho(spot, K, r, T, -sigma, d))
@test_throws(DomainError, blspsi(spot, K, r, T, -sigma, d))
@test_throws(DomainError, blslambda(spot, K, r, T, -sigma, d))
@test_throws(DomainError, blsvanna(spot, K, r, T, -sigma, d))
@test_throws(DomainError, blsvega(spot, K, r, T, -sigma, d))
print_colored("----Testing Negative Option Price\n", :cyan)
@test_throws(DomainError, blsimpv(spot, K, r, T, -PriceCall, d))
@test_throws(DomainError, blkimpv(spot, K, r, T, -PriceCall))
print_colored("----Testing Negative Tollerance\n", :cyan)
@test_throws(DomainError, blsimpv(spot, K, r, T, PriceCall, d, true, -1e-12, 1))
@test_throws(DomainError, blkimpv(spot, K, r, T, PriceCall, true, -1e-12, 1))
@test_throws(DomainError, blsimpv(spot, K, r, T, PriceCall, d, true, 1e-12, -1))
@test_throws(DomainError, blkimpv(spot, K, r, T, PriceCall, true, 1e-12, -1))
#Too low tollerance
# @test_throws(DomainError, blsimpv(spot, K, r, T, PriceCall, d, true, 0.0, 0.0))
# @test_throws(DomainError, blkimpv(spot, K, r, T, PriceCall, true, 0.0, 0.0))
print_colored("Real Input Validation Test Passed\n", :magenta)
#End of the Test
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 488 | using Test
using FinancialToolbox, ReverseDiff
#Test Parameters
spot = 10.0;
K = 10;
r = 0.02;
T = 2.0;
sigma = 0.2;
d = 0.01;
toll = 1e-4
#EuropeanCall Option
f(S0) = blsprice(S0[1], K, r, T, sigma, d);
delta_1 = blsdelta(spot, K, r, T, sigma, d);
delta_v = ReverseDiff.gradient(f, [spot])
@test(abs(delta_v[1] - delta_1) < toll)
price = f(spot)
f2(S0) = blsimpv(S0[1], K, r, T, price, d);
delta_v = ReverseDiff.gradient(f2, [spot])
@test(abs(delta_v[1] + 0.10586634302510232) < toll) | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 2795 | using Test
using FinancialToolbox, Symbolics
toll = 1e-7
@variables S0_s, r_s, d_s, T_s, sigma_s, K_s, price_s
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.2;
sigma = 0.2;
d = 0.01;
price = blsprice(S0, K, r, T, sigma, d)
dict_vals = Dict(S0_s => S0, r_s => r, d_s => d, K_s => K, T_s => T, sigma_s => sigma, price_s => price)
price_s_c = blsprice(S0_s, K_s, r_s, T_s, sigma_s, d_s)
price_v = substitute(price_s_c, dict_vals)
@test abs(price - price_v) < toll
vol_s = blsimpv(S0_s, K_s, r_s, T_s, price_s, d_s)
vol_v = substitute(vol_s, dict_vals)
vol = blsimpv(S0, K, r, T, price, d)
@test abs(vol - vol_v) < toll
#Test multiple order derivatives of blsimpv
using HyperDualNumbers
#S0
der_vol_S0 = Symbolics.derivative(vol_s, S0_s, simplify = true);
der_vol_S02 = Symbolics.derivative(der_vol_S0, S0_s, simplify = true);
@show vol_h_S0 = blsimpv(hyper(S0, 1.0, 1.0, 0.0), K, r, T, price, d)
delta = substitute(der_vol_S0, dict_vals)
@show gamma = substitute(der_vol_S02, dict_vals)
@test abs(delta - vol_h_S0.epsilon1) < toll
#K
der_vol_K = Symbolics.derivative(vol_s, K_s, simplify = true);
der_vol_K2 = Symbolics.derivative(der_vol_K, K_s, simplify = true);
vol_h_K = blsimpv(S0, hyper(K, 1.0, 1.0, 0.0), r, T, price, d)
delta_k = substitute(der_vol_K, dict_vals)
gamma_k = substitute(der_vol_K2, dict_vals)
@test abs(delta_k - vol_h_K.epsilon1) < toll
#r
der_vol_r = Symbolics.derivative(vol_s, r_s, simplify = true);
der_vol_r2 = Symbolics.derivative(der_vol_r, r_s, simplify = true);
vol_h_r = blsimpv(S0, K, hyper(r, 1.0, 1.0, 0.0), T, price, d)
delta_r = substitute(der_vol_r, dict_vals)
gamma_r = substitute(der_vol_r2, dict_vals)
@test abs(delta_r - vol_h_r.epsilon1) < toll
#T
der_vol_T = Symbolics.derivative(vol_s, T_s, simplify = true);
der_vol_T2 = Symbolics.derivative(der_vol_T, T_s, simplify = true);
vol_h_T = blsimpv(S0, K, r, hyper(T, 1.0, 1.0, 0.0), price, d)
delta_T = substitute(der_vol_T, dict_vals)
gamma_T = substitute(der_vol_T2, dict_vals)
@test abs(delta_T - vol_h_T.epsilon1) < toll
#Mixed derivative r,T
der_vol_T = Symbolics.derivative(vol_s, T_s, simplify = true);
der_vol_T_r_s = Symbolics.derivative(der_vol_T, r_s, simplify = true);
vol_h_T = blsimpv(S0, K, hyper(r, 0.0, 1.0, 0.0), hyper(T, 1.0, 0.0, 0.0), price, d)
delta_T = substitute(der_vol_T, dict_vals)
gamma_T = substitute(der_vol_T_r_s, dict_vals)
@test abs(delta_T - vol_h_T.epsilon1) < toll
println("Test First Order Passed")
@test abs(gamma - vol_h_S0.epsilon12) < toll
@test abs(gamma_k - vol_h_K.epsilon12) < toll
@test abs(gamma_r - vol_h_r.epsilon12) < toll
@test abs(gamma_T - vol_h_T.epsilon12) < toll
@test abs(gamma_T - vol_h_T.epsilon12) < toll
println("Test Second Order Passed")
inp=NTuple{7,Any}((1,2,3,4,5,6,7))
@test Symbolics.derivative(FinancialToolbox.blimpv, inp, Val(5))==0 | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 2109 | using Test
using FinancialToolbox, TaylorSeries
#Test Parameters
spot = 10.0;
K = 10;
r = 0.02;
T = 2.0;
sigma = 0.2;
d = 0.01;
spotDual = taylor_expand(identity, spot, order = 22)
toll = 1e-4
#EuropeanCall Option
PriceCall = blsprice(spotDual, K, r, T, sigma, d);
@test(abs(1.1912013169995816 - PriceCall[0]) < toll)
@test(abs(0.5724340508103682 - PriceCall[1]) < toll)
gamma_opt = blsgamma(spot, K, r, T, sigma, d);
@test(abs(gamma_opt - PriceCall[2] * 2) < toll)
dS0, dr, dsigma = set_variables("dS0 dr dsigma", order = 4)
PriceCall2 = blsprice(spot + dS0, K, r + dr, T, sigma + dsigma, d);
@test(abs(1.1912013169995816 - PriceCall2[0][1]) < toll)
@test(abs(0.5724340508103682 - PriceCall2[1][1]) < toll)
@test(abs(gamma_opt - PriceCall2[2][1] * 2) < toll)
#Broken for some reason
VolaCall = blsimpv(spotDual, K, r, T, PriceCall, d);
@test(abs(VolaCall[0] - 0.2) < toll)
# @test(abs(VolaCall[1]) < toll)
# #EuropeanCall Option
sigma_dual = taylor_expand(identity, sigma, order = 22)
PriceCall3 = blsprice(spotDual, K, r, T, sigma_dual, d);
VolaCall3 = blsimpv(spotDual, K, r, T, PriceCall3, d);
@test(abs(VolaCall3[0] - sigma_dual[0]) < toll)
@test(abs(VolaCall3[1] - sigma_dual[1]) < toll)
@test(abs(VolaCall3[2] - sigma_dual[2]) < toll)
@test(abs(VolaCall3[3] - sigma_dual[3]) < toll)
sigma_dual_new = deepcopy(PriceCall3)
sigma_dual_new[0] = sigma
PriceCall3 = blsprice(spotDual, K, r, T, sigma_dual_new, d);
VolaCall3 = blsimpv(spotDual, K, r, T, PriceCall3, d);
@show VolaCall3
@show sigma_dual_new
@test(abs(VolaCall3[0] - sigma_dual_new[0]) < toll)
@show @test(abs(VolaCall3[1] - sigma_dual_new[1]) < toll)
@test(abs(VolaCall3[2] - sigma_dual_new[2]) < toll)
@test(abs(VolaCall3[3] - sigma_dual_new[3]) < toll)
sigma_dual_new = deepcopy(PriceCall3)
sigma_dual_new[0] = sigma
PriceCall3 = blsprice(spot, K, r, T, sigma_dual_new, d);
VolaCall3 = blsimpv(spot, K, r, T, PriceCall3, d);
@test(abs(VolaCall3[0] - sigma_dual_new[0]) < toll)
@test(abs(VolaCall3[1] - sigma_dual_new[1]) < toll)
@test(abs(VolaCall3[2] - sigma_dual_new[2]) < toll)
@test(abs(VolaCall3[3] - sigma_dual_new[3]) < toll) | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 463 | using Test
using FinancialToolbox, Zygote
#Test Parameters
spot = 10.0;
K = 10;
r = 0.02;
T = 2.0;
sigma = 0.2;
d = 0.01;
toll = 1e-4
#EuropeanCall Option
f(S0) = blsprice(S0, K, r, T, sigma, d);
delta_1 = blsdelta(spot, K, r, T, sigma, d);
delta_v = Zygote.gradient(f, spot)
@test(abs(delta_v[1] - delta_1) < toll)
price = f(spot)
f2(S0) = blsimpv(S0, K, r, T, price, d);
delta_v = Zygote.gradient(f2, spot)
@test(abs(delta_v[1] + 0.10586634302510232) < toll) | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 3987 | using Test
using FinancialToolbox
#Test Parameters
testToll_float64 = 1e-10;
print_colored("Starting Implied Volatility Test\n", :green)
function test_implied_volatility_from_σ(toll, S0, K, r, T, σ, d, FlagIsCall)
price_t = blsprice(S0, K, r, T, σ, d, FlagIsCall)
σ_cp = blsimpv(S0, K, r, T, price_t, d, FlagIsCall)
@test abs(σ_cp - σ) < toll
end
function test_broken_implied_volatility_from_σ(toll, S0, K, r, T, σ, d, FlagIsCall)
price_t = blsprice(S0, K, r, T, σ, d, FlagIsCall)
new_σ = blsimpv(S0, K, r, T, price_t, d, FlagIsCall)
@test_broken abs(new_σ - σ) < toll
end
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.2;
σ = 0.2;
d = 0.01;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
K = 90.0;
d = 0.03;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
K = 120.0;
r = 0.02;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
S0 = 160.0;
r = 0.03;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
S0 = 100.0;
K = 70.0;
r = 0.02;
T = 1.2;
σ = 3.5;
d = 0.01;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
S0 = 100.0;
K = 70.0;
r = 0.02;
T = 1.2;
σ = 13.5;
d = 0.01;
test_broken_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_broken_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
σ = 13.5;
d = 0.01;
test_broken_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_broken_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
@test_throws(DomainError, blsimpv(S0, K, r, T, S0 * 10, d))
#New test from issue #21
S0 = 4753.63;
K = 4085.0;
r = 0.0525;
T = 0.13870843734533175;
price_1 = 701.3994
d = 0.0
σ = blsimpv(S0, K, r, T, price_1, d);
@test !isnan(σ)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
S0 = 100.0;
K = 10.0;
r = 0.02;
T = 1.2;
σ = 0.2;
d = 0.01;
test_broken_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true) #TODO: FIX q>0 and x >0
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
S0 = 10.0;
K = 100.0;
r = 0.02;
T = 1.2;
σ = 0.2;
d = 0.01;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_broken_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)#TODO: FIX q<0 and x <0
S0 = 100.0;
K = 100.0;
r = 0.2;
T = 1.2;
σ = 0.2;
d = 0.01;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 0.2;
σ = 0.2;
d = 0.01;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.2;
σ = 0.2;
d = 0.1;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 10.2;
σ = 0.2;
d = 0.01;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
# S0 = 1000000.0;
# K = 1.0;
# r = 0.2;
# T = 1.2;
# σ = 0.2;
# d = 0.01;
# test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, true)
# test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, d, false)
print_colored("Implied Volatility Test Passed\n", :magenta)
#End of the Test
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | code | 1927 | using Test
using FinancialToolbox
#Test Parameters
testToll_float64 = 1e-10;
print_colored("Starting Implied Volatility Test\n", :green)
function test_implied_volatility_from_σ(toll, S0, K, r, T, σ, FlagIsCall)
price_t = blkprice(S0, K, r, T, σ, FlagIsCall)
σ_cp = blkimpv(S0, K, r, T, price_t, FlagIsCall)
@test abs(σ_cp - σ) < toll
end
function test_broken_implied_volatility_from_σ(toll, S0, K, r, T, σ, FlagIsCall)
price_t = blkprice(S0, K, r, T, σ, FlagIsCall)
@test_broken abs(blkimpv(S0, K, r, T, price_t, FlagIsCall) - σ) < toll
end
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.2;
σ = 0.2;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, false)
K = 90.0;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, false)
K = 120.0;
r = 0.02;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, false)
S0 = 160.0;
r = 0.03;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, false)
S0 = 100.0;
K = 70.0;
r = 0.02;
T = 1.2;
σ = 3.5;
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, true)
test_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, false)
S0 = 100.0;
K = 70.0;
r = 0.02;
T = 1.2;
σ = 13.5;
test_broken_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, true)
test_broken_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
σ = 13.5;
test_broken_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, true)
test_broken_implied_volatility_from_σ(testToll_float64, S0, K, r, T, σ, false)
print_colored("Implied Volatility Test Passed\n", :magenta)
#End of the Test
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | docs | 2992 | # FinancialToolbox
[](https://www.repostatus.org/#active)
[](https://rcalxrc08.github.io/FinancialToolbox.jl/)
[](https://github.com/rcalxrc08/FinancialToolbox.jl/actions/workflows/CI.yml)
[](https://codecov.io/gh/rcalxrc08/FinancialToolbox.jl?branch=master)
##### This is a Julia package containing some useful Financial functions for Pricing and Risk Management under the Black and Scholes Model.
###### The syntax is the same of the Matlab Financial Toolbox.
It currently contains the following functions:
- blsprice : Black & Scholes Price for European Options.
- blsbin : Black & Scholes Price for Binary European Options.
- blkprice : Black Price for European Options.
- blsdelta : Black & Scholes Delta sensitivity for European Options.
- blsgamma : Black & Scholes Gamma sensitivity for European Options.
- blstheta : Black & Scholes Theta sensitivity for European Options.
- blsvega : Black & Scholes Vega sensitivity for European Options.
- blsrho : Black & Scholes Rho sensitivity for European Options.
- blslambda: Black & Scholes Lambda sensitivity for European Options.
- blspsi : Black & Scholes Psi sensitivity for European Options.
- blsvanna : Black & Scholes Vanna sensitivity for European Options.
- blsimpv : Black & Scholes Implied Volatility for European Options.
- blkimpv : Black Implied Volatility for European Options.
Currently supports classical numerical input and other less common like:
- Complex Numbers
- [Dual Numbers](https://github.com/JuliaDiff/DualNumbers.jl)
- [HyperDual Numbers](https://github.com/JuliaDiff/HyperDualNumbers.jl)
It also contains some functions that could be useful for the Dates Management:
- yearfrac : fraction of years between two Dates (currently only the first seven convention of Matlab are supported).
- daysact : number of days between two Dates.
The module is standalone.
## How to Install
To install the package simply type on the Julia REPL the following:
```Julia
Pkg.add("FinancialToolbox")
```
## How to Test
After the installation, to test the package type on the Julia REPL the following:
```Julia
Pkg.test("FinancialToolbox")
```
## Example of Usage
The following example is the pricing of a European Call Option with underlying varying
according to the Black Scholes Model, given the implied volatility.
After that it is possible to check the result computing the inverse of the Black Scholes formula.
```Julia
#Import the Package
using FinancialToolbox
#Define input data
spot=10;K=10;r=0.02;T=2.0;σ=0.2;d=0.01;
#Call the function
Price=blsprice(spot,K,r,T,σ,d)
#Price=1.1912013169995816
#Check the Result
Volatility=blsimpv(spot,K,r,T,Price,d)
#Volatility=0.20000000000000002
```
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | docs | 6306 | <!--
The definitions here control the layout of the page: basic geometry, colors,
and elements. To avoid errors, do not remove definitions, rather, leave them
empty. Some definitions are only used if a toggle is set.
You can add your own rules if you so desire by either:
- directly modifying `_css/custom.css`
- adding rules to `_layout/style_tuning.fcss`
The latter allows you to plug in values that you would have defined here.
-->
<!-- META DEFINITIONS
NOTE:
- prepath: this is used to specify the base URLs; if your site should be
available at `https://username.github.io/YourPackage.jl/` then the
pre-path should be `YourPackage.jl`. If your site is meant to be
hosted on a specific URL such as `https://awesomepkg.org` then set
`prepath` to an empty string. Finally, adjust this if you want the
deployed page to be in a subfolder e.g.: `YourPackage.jl/web/`.
-->
@def title = "FinancialToolbox.jl"
@def prepath = "FinancialToolbox.jl"
@def description = """
Black and Scholes utility functions.
"""
@def authors = "Nicola Scaramuzzino"
<!-- NAVBAR SPECS
NOTE:
- add_docs: whether to add a pointer to your docs website
- docs_url: the url of the docs website (ignored if add_docs=false)
- docs_name: how the link should be named in the navbar
- add_nav_logo: whether to add a logo left of the package name
- nav_logo_path: where the logo is
-->
@def add_docs = false
@def docs_url = "https://franklinjl.org/"
@def docs_name = "Docs"
@def add_nav_logo = true
@def nav_logo_path = "/assets/logo.png"
@def nav_logo_alt = "Logo"
@def nav_logo_style = """
height: 25px;
padding-right: 10px;
"""
<!-- HEADER SPECS
NOTE:
- use_header: if false, toggle the header off completely
- use_header_img: to use an image as background for the header
- header_img_path: either a path to an asset or a SVG like here. Note that
the path must be CSS-compatible.
- header_img_style: additional styling, for instance whether to repeat
or not. For a SVG pattern, use repeat, otherwise use
no-repeat.
- header_margin_top: vertical margin above the header, if <= 55px there will
be no white space, if >= 60 px, there will be white
space between the navbar and the header. (Ideally
don't pick a value between the two as the exact
look is browser dependent). When use_hero = true,
hero_margin_top is used instead.
- use_hero: if false, main bar stretches from left to right
otherwise boxed
- hero_width: width of the hero, for instance 80% will mean the
hero will stretch over 80% of the width of the page.
- hero_margin_top used instead of header_margin_top if use_hero is true
- add_github_view: whether to add a "View on GitHub" button in header
- add_github_star: whether to add a "Star this package" button in header
- github_repo: path to the GitHub repo for the GitHub button
-->
@def use_header = true
@def use_header_img = true
@def header_img_path = "url(\"assets/diagonal-lines.svg\")"
@def header_img_style = """
background-repeat: repeat;
"""
@def header_margin_top = "59px" <!-- 55-60px ~ touching nav bar -->
@def use_hero = false
@def hero_width = "90%"
@def hero_margin_top = "90px"
@def add_github_view = true
@def add_github_star = true
@def github_repo = "rcalxrc08/FinancialToolbox.jl"
<!-- SECTION LAYOUT
NOTE:
- section_width: integer number to control the default width of sections
you can also set it for individual sections by specifying
the width argument: `\begin{:section, ..., width=10}`.
-->
@def section_width = 10
<!-- COLOR PALETTE
You can use Hex, RGB or SVG color names; these tools are useful to choose:
- color wheel: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Colors/Color_picker_tool
- color names: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value
NOTE:
- header_color: background color of the header
- link_color: color of links
- link_hover_color: color of links when hovered
- section_bg_color: background color of "secondary" sections to help
visually separate between sections.
- footer_link_color: color of links in the footer
-->
@def header_color = "#3f6388"
@def link_color = "#2669DD"
@def link_hover_color = "teal"
@def section_bg_color = "#f6f8fa"
@def footer_link_color = "cornflowerblue"
<!-- CODE LAYOUT
NOTE:
- highlight_theme: theme for the code, pick one from
https://highlightjs.org/static/demo/ for instance
"github" or "atom-one-dark"; use lower case and replace
spaces with `-`.
- code_border_radius: how rounded the corners of code blocks should be
- code_output_indent: how much left-identation to add for "output blocks"
(results of the evaluation of code blocks), use 0 if
you don't want indentation.
-->
@def highlight_theme = "atom-one-dark"
@def code_border_radius = "10px"
@def code_output_indent = "15px"
<!-- YOUR DEFINITIONS
See franklinjl.org for more information on how to introduce your own
definitions and how they can be useful.
-->
<!-- INTERNAL DEFINITIONS =====================================================
===============================================================================
These definitions are important for the good functioning of some of the
commands that are defined and used in PkgPage.jl
-->
@def sections = Pair{String,String}[]
@def section_counter = 1
@def showall = true
\newcommand{\html}[1]{~~~#1~~~}
\newenvironment{center}{\html{<div style="text-align:center;">}}{\html{</div>}}
\newenvironment{columns}{\html{<div class="container"><div class="row">}}{\html{</div></div>}}
| FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 0.7.0 | 56dddf9619ef896307031c8c0515e4f7ad1da0b1 | docs | 8696 | <!-- =============================
ABOUT
============================== -->
\begin{section}{title="About this Package", name="About"}
\lead{FinancialToolbox.jl is a Julia package containing some useful Financial functions for Pricing and Risk Management under the Black and Scholes Model.}
The syntax is the same of the Matlab Financial Toolbox.
Currently supports classical numerical input and other less common like:
* Complex Numbers
* [Dual Numbers](https://github.com/JuliaDiff/DualNumbers.jl)
* [HyperDual Numbers](https://github.com/JuliaDiff/HyperDualNumbers.jl)
* [TaylorSeries.jl](https://github.com/JuliaDiff/TaylorSeries.jl)
* [TaylorDiff.jl](https://github.com/JuliaDiff/TaylorDiff.jl)
\end{section}
<!-- ==============================
GETTING STARTED
============================== -->
\begin{section}{title="Getting started"}
In order to get started, just add the package:
```
pkg> add FinancialToolbox
```
and load it:
```julia:ex__1
using FinancialToolbox
```
\end{section}
<!-- ==============================
SPECIAL COMMANDS
============================== -->
\begin{section}{title="Example of Usage"}
* [Pricing European Options in the Black and Scholes model](#blsprice)
* [Pricing European Options in the Black model](#blkprice)
* [Implied Volatility in the Black and Scholes model](#blsimpv)
* [Implied Volatility in the Black model](#blkimpv)
\label{blsprice}
**Pricing a European Option in Black and Scholes framework**:\\
According to Black and Scholes model, the price of a european option can be expressed as follows:
\begin{columns}
\begin{column}{}
**_European Call Price_**
$$ C_{bs}(S,K,r,T,\sigma,d) = S e^{-d\,T} N(d_1) - Ke^{-r\,T} N(d_2) $$
\end{column}
\begin{column}{}
**_European Put Price_**
$$ P_{bs}(S,K,r,T,\sigma,d) = Ke^{-r\,T} N(-d_2) - S e^{-d\,T} N(-d_1) $$
\end{column}
\end{columns}
where:
$$d_1 = \frac{\ln\left(\frac{S}{K}\right) + \left(r - q + \frac{\sigma^2}{2}\right) T}{\sigma\sqrt{T}}$$
$$d_2 = d_1 - \sigma\sqrt{T}$$
\\
And:
* $S$ is the underlying spot price.
* $K$ is the strike price.
* $r$ is the risk free rate.
* $T$ is the time to maturity.
* $\sigma$ is the implied volatility of the underlying.
* $d$ is the implied dividend of the underlying.
The way to compute the price in this library is:
\begin{columns}
\begin{column}{}
**_European Call Price_**
```julia:ex_7
S=100.0; K=100.0; r=0.02; T=1.2; σ=0.2; d=0.01;
Price_call=blsprice(S,K,r,T,σ,d)
```
\end{column}
\begin{column}{}
**_European Put Price_**
```julia:ex_7
S=100.0; K=100.0; r=0.02; T=1.2; σ=0.2; d=0.01;
Price_put=blsprice(S,K,r,T,σ,d,false)
```
\end{column}
\end{columns}
\\
\label{blkprice}
**Pricing a European Option in Black framework**:\\
According to Black model, the price of a european option can be expressed as follows:
\begin{columns}
\begin{column}{}
**_European Call Price_**
$$ C_{bk}(F,K,r,T,\sigma) = F e^{-r\,T} N(d_1) - Ke^{-r\,T} N(d_2) $$
\end{column}
\begin{column}{}
**_European Put Price_**
$$ P_{bk}(F,K,r,T,\sigma) = Ke^{-r\,T} N(-d_2) - F e^{-r\,T} N(-d_1) $$
\end{column}
\end{columns}
where:
$$d_1 = \frac{\ln\left(\frac{F}{K}\right) + \frac{\sigma^2}{2}T}{\sigma\sqrt{T}}$$
$$d_2 = d_1 - \sigma\sqrt{T}$$
\\
And:
* $F$ is the underlying forward price.
* $K$ is the strike price.
* $r$ is the risk free rate.
* $T$ is the time to maturity.
* $\sigma$ is the implied volatility of the underlying.
The way to compute the price in this library is:
\begin{columns}
\begin{column}{}
**_European Call Price_**
```julia:ex_7
F=100.0; K=102.0; r=0.02; T=1.2; σ=0.2;
Price_call=blkprice(S,K,r,T,σ)
```
\end{column}
\begin{column}{}
**_European Put Price_**
```julia:ex_7
F=100.0; K=102.0; r=0.02; T=1.2; σ=0.2;
Price_put=blkprice(S,K,r,T,σ,false)
```
\end{column}
\end{columns}
\\
\label{blsimpv}
**Computing Implied Volatility in a Black and Scholes framework**: Given an option price $V$, the Black and Scholes implied volatility is defined as the positive number $\sigma$ which solves:
\begin{columns}
\begin{column}{}
**_From European Call Price_**
$$ V = S e^{-d\,T} N(d_1) - Ke^{-r\,T} N(d_2) $$
\end{column}
\begin{column}{}
**_From European Put Price_**
$$ V = Ke^{-r\,T} N(-d_2) - S e^{-d\,T} N(-d_1) $$
\end{column}
\end{columns}
where:
$$d_1 = \frac{\ln\left(\frac{S}{K}\right) + \left(r - q + \frac{\sigma^2}{2}\right) T}{\sigma\sqrt{T}}$$
$$d_2 = d_1 - \sigma\sqrt{T}$$
\\
The way to compute the volatility in this library is:
\begin{columns}
\begin{column}{}
**_Implied Volatility from Call Price_**
```julia:ex_7
S=100.0; K=100.0; r=0.02; T=1.2; d=0.01;
call_price=9.169580760087896
σ=blsimpv(S,K,r,T,call_price,d)
```
\end{column}
\begin{column}{}
**_Implied Volatility from Put Price_**
```julia:ex_7
S=100.0; K=100.0; r=0.02; T=1.2; d=0.01;
put_price=7.990980449685762
σ=blsimpv(S,K,r,T,put_price,d,false)
```
\end{column}
\end{columns}
blsimpv accepts additional arguments such as the absolute tolerance and the maximum numbers of steps of the numerical inversion.
\alert{Currently blsimpv is using the rational inversion method based on [LetsBeRational](http://www.jaeckel.org/LetsBeRational.pdf) method in order to invert the relation between the price and the volatility.
If you notice something wrong with the numerical inversion, you are strongly suggested to open a issue.}
\\
\label{blkimpv}
**Computing Implied Volatility in Black framework**:\\
Given an option price $V$, the Black implied volatility is defined as the positive number $\sigma$ which solves:
\begin{columns}
\begin{column}{}
**_From European Call Price_**
$$ V = F e^{-r\,T} N(d_1) - Ke^{-r\,T} N(d_2) $$
\end{column}
\begin{column}{}
**_From European Put Price_**
$$ V = Ke^{-r\,T} N(-d_2) - F e^{-r\,T} N(-d_1) $$
\end{column}
\end{columns}
where:
$$d_1 = \frac{\ln\left(\frac{F}{K}\right) + \frac{\sigma^2}{2}T}{\sigma\sqrt{T}}$$
$$d_2 = d_1 - \sigma\sqrt{T}$$
\\
The way to compute the volatility in this library is:
\begin{columns}
\begin{column}{}
**_Implied Volatility from Call Price_**
```julia:ex_7
S=100.0; K=102.0; r=0.02; T=1.2;
call_price=7.659923984582901
σ=blkimpv(S,K,r,T,call_price)
```
\end{column}
\begin{column}{}
**_Implied Volatility from Put Price_**
```julia:ex_7
S=100.0; K=102.0; r=0.02; T=1.2;
put_price=9.612495404098706
σ=blkimpv(S,K,r,T,put_price,false)
```
\end{column}
\end{columns}
blkimpv accepts additional arguments such as the absolute tolerance and the maximum numbers of steps of the numerical inversion.
\alert{Currently blkimpv is using the rational inversion method based on [LetsBeRational](http://www.jaeckel.org/LetsBeRational.pdf) method in order to invert the relation between the price and the volatility.
If you notice something wrong with the numerical inversion, you are strongly suggested to open a issue.}
\end{section}
\begin{section}{title="Automatic Differentiation", name="AD"}
Pricers and sensitivities functions are differentiable as far as the AD engine is capable of differentiating the erfc function.\\
Implied volatility computations are fully differentiable by using ChainRulesCore.jl.
Explicit support for ForwardDiff, ReverseDiff, TaylorDiff, TaylorSeries is added.
In case your package does not support ChainRulesCore.jl APIs, please open an issue if you need the support for implied volatility differentiation.
\\
**Automatic Differentiation of Implied Volatility**: \\
In a Black and Scholes setup, let's define $f(S,K,r,T,\sigma,d)$ as follows:
\begin{columns}
\begin{column}{}
**_For European Call_**
$$ f = C_{bs}(S,K,r,T,\sigma,d) $$
\end{column}
\begin{column}{}
**_For European Put_**
$$ f = P_{bs}(S,K,r,T,\sigma,d) $$
\end{column}
\end{columns}
Let's fix a feasible option price $V$. Then we can compute the derivative of the implied volatility as follows:\\
Since $\sigma=\sigma(S,K,r,T,V,d)$ solves the inversion, then:
$$ f(S,K,r,T,\sigma(S,K,r,T,V,d),d) = V $$ <!--_-->
By differentating both sides for a generic parameter $\theta$ we get:
$$ \partial_{\theta}\sigma = \frac{\partial_{\theta}(V-f(S,K,r,T,\sigma,d))}{\partial_{\sigma}f(S,K,r,T,\sigma,d)} $$ <!--_-->
Very similar applies to Black model:
$$ \partial_{\theta}\sigma = \frac{\partial_{\theta}(V-f(F,K,r,T,\sigma))}{\partial_{\sigma}f(F,K,r,T,\sigma)} $$ <!--_-->
with:
\begin{columns}
\begin{column}{}
**_For European Call_**
$$ f = C_{bk}(F,K,r,T,\sigma) $$
\end{column}
\begin{column}{}
**_For European Put_**
$$ f = P_{bk}(F,K,r,T,\sigma) $$
\end{column}
\end{columns}
This formulation of the derivative allows to define analytically the frule and the rrule for the function blsimpv and blkimpv, without the need of differentiating the numerical solver, proving once again the superiority of automatic differentiation against numerical one.
\end{section} | FinancialToolbox | https://github.com/rcalxrc08/FinancialToolbox.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 2160 | using Documenter, Vahana
using Pkg
Pkg.status("Vahana")
using GraphMakie, Makie, DataFrames
# this is a really dirty workaround, but for whatever reason the
# sandboxing mechanism of Documenter clashes with the way Vahana
# constructs the model.
# But we do not need the sandboxing, as we can have different models
# in a single julia session.
import Documenter.get_sandbox_module!
get_sandbox_module!(_, _, _) = Main
import Literate
cd(@__DIR__)
Literate.markdown(joinpath(@__DIR__, "examples", "tutorial1.jl"), "src"; execute = false)
Literate.markdown(joinpath(@__DIR__, "examples", "predator.jl"), "src"; execute = false)
Literate.markdown(joinpath(@__DIR__, "examples", "hegselmann.jl"), "src"; execute = false)
###
makedocs(sitename="Vahana Documentation",
modules = [Vahana],
# format = Documenter.LaTeX(),
format = Documenter.HTML(prettyurls = false,
edit_link = :commit),
clean = false,
pages = [
"Introduction" => "index.md",
"Tutorials" => [
"First Steps" => "tutorial1.md",
"Utilizing Graphs.jl" => "hegselmann.md",
"Adding Spatial Information" => "predator.md"
],
"Performance Tuning" => "performance.md",
"Parallel Simulations" => "parallel.md",
"API" => [
"Model Definition" => "definition.md",
"Initialization" => "initialization.md",
"Transition Function" => "transition.md",
"Global Layer" => "global.md",
"Raster" => "raster.md",
# "REPL helpers" => "repl.md",
"Plots" => "plots.md",
"File storage" => "hdf5.md",
"Logging" => "logging.md",
"Configuration" => "config.md",
"Misc" => "misc.md",
"Index" => "apiindex.md"
],
# "Glossary" => "glossary.md",
"Change Log" => "changelog.md"
])
deploydocs(
repo = "github.com/s-fuerst/Vahana.jl.git",
devbranch = "main"
)
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 8175 | # # Utilizing Graphs.jl
# # Goal
#=
This tutorial illustrates how to integrate graphs that support the
`AbstractGraph` interface from the Graphs.jl package into a Vahana
simulation and the visualization support for Vahana graphs.
For this purpose, we implement the opinion dynamics model of
[Hegselmann and Krause
(2002)](http://jasss.soc.surrey.ac.uk/5/3/2.html). An alternative
implementation of the same model using the Agents.jl package can be found
[here](https://juliadynamics.github.io/Agents.jl/v4.0/examples/hk/).
=#
# # Agent and Edge Types
using Vahana, Statistics
# We have a finite number $n$ of agents, where the state of
# the agents are a real number $x_i(t)$ in the [0,1] interval which
# represents the opinion of that agent.
struct HKAgent
opinion::Float64
end
# This time we have only one network that determine the agents that
# will be considered when an agent updates its opinion.
struct Knows end
# Beside these two types there is a *confidence bound* $\epsilon > 0$,
# opinions with a difference greater than $\epsilon$ are ignored by
# the agents in the transition function. All agents have the same
# confidence bound, so we introduce this bound as a parameter.
const hkmodel = ModelTypes() |>
register_agenttype!(HKAgent) |>
register_edgetype!(Knows) |>
register_param!(:ϵ, 0.02) |> # the confidence bound
create_model("Hegselmann-Krause");
# # Adding a Graph
# Vahana allows adding `SimpleGraphs` and `SimpleDiGraphs` from the
# [Graphs.jl](https://juliagraphs.org/Graphs.jl/dev/) package via the
# [`add_graph!`](@ref) function. So it is possible to use e.g.
# [SNAPDatasets](https://github.com/JuliaGraphs/SNAPDatasets.jl) to
# run the opinion model on real datasets, or the SimpleGraphs module
# from Graphs.jl to create synthetic graphs.
# We demonstrate here both use cases and are creating a separate
# simulation for each one.
const cgsim = create_simulation(hkmodel);
const snapsim = create_simulation(hkmodel)
# ## SimpleGraphs
# First we will show how we can add a synthetic graph. For this we
# need to import the SimpleGraphs module. Since there are many
# functions in the Graphs.jl package with the same name as in Vahana
# (e.g. add_edge!), it is advisable to import only the needed parts of
# Graphs.jl instead of loading the whole package via `using Graphs`.
import Graphs.SimpleGraphs
# We want to add a complete graph, where each agent is connected with
# all the other agents, like in the Agents.jl implementation. We can
# create such a graph via `SimpleGraphs.complete_graph`.
g = SimpleGraphs.complete_graph(50)
# Vahana needs the information how to convert the nodes and edges of
# the SimpleGraphs object to the Vahana structure. This is done by the
# constructor functions in the third and forth arguments of
# [`add_graph!`](@ref). We do not need the Graph.vertex and Graph.edge
# arguments of this constructor functions, but for other use cases
# e.g. for bipartite graphs, it would be possible to create agents of
# different types depending on this information.
const agentids = add_graph!(cgsim,
g,
_ -> HKAgent(rand()),
_ -> Knows());
# Each agent also adds its own opinion to the calculation. We can use
# the ids returned by the [`add_graph!`](@ref) functions for this.
foreach(id -> add_edge!(cgsim, id, id, Knows()), agentids)
finish_init!(cgsim)
# ## SNAPDataset.jl
# The SNAPDataset.jl package delivers Graphs.jl formatted datasets from
# the [Stanford Large Network Dataset
# Collection](https://snap.stanford.edu/data/index.html).
using SNAPDatasets
# With this package we can use the `loadsnap` function to create the graph
# that is then added to the Vahana graph, e.g. in our example the
# facebook dataset.
const snapids = add_graph!(snapsim,
loadsnap(:facebook_combined),
_ -> HKAgent(rand()),
_ -> Knows());
# Again each agent adds its own opinion to the calculation.
foreach(id -> add_edge!(snapsim, id, id, Knows()), snapids)
finish_init!(snapsim)
# # The Transition Function
# Opinions are updated synchronously according to
# ```math
# \begin{aligned}
# x_i(t+1) &= \frac{1}{| \mathcal{N}_i(t) |} \sum_{j \in \mathcal{N}_i(t)} x_j(t)\\
# \textrm{where } \quad \mathcal{N}_i(t) &= \{ j : \| x_j(t) - x_i(t) \| \leq \epsilon \}
# \end{aligned}
# ```
# So we first filter all agents from the neighbors with an opinion
# outside of the confidence bound, and then calculate the mean of the
# opinions of the remaining agents.
function step(agent, id, sim)
ϵ = param(sim, :ϵ)
opinions = map(a -> a.opinion, neighborstates(sim, id, Knows, HKAgent))
accepted = filter(opinions) do opinion
abs(opinion - agent.opinion) < ϵ
end
HKAgent(mean(accepted))
end;
# We can now apply the transition function to the complete graph simulation
apply!(cgsim, step, HKAgent, [ HKAgent, Knows ], HKAgent)
# Or to our facebook dataset
apply!(snapsim, step, HKAgent, [ HKAgent, Knows ], HKAgent)
# # Creating Plots
# Finally, we show the visualization possibilities for graphs, and import the
# necessary packages for this and create a colormap for the nodes.
import CairoMakie, GraphMakie, NetworkLayout, Colors, Graphs, Makie
# Since the full graph is very cluttered and the Facebook dataset is
# too large, we construct a Clique graph using Graphs.jl.
const cysim = create_simulation(hkmodel) |> set_param!(:ϵ, 0.25);
const cyids = add_graph!(cysim,
SimpleGraphs.clique_graph(7, 8),
_ -> HKAgent(rand()),
_ -> Knows());
foreach(id -> add_edge!(cysim, id, id, Knows()), cyids)
finish_init!(cysim);
# Vahana implements an interactive plot function based on GraphMakie, where
# agents and edges are given different colors per type by default, and
# the state of each agent/edge is displayed via mouse hover
# actions.
vp = create_graphplot(cysim)
figure(vp)
# To modify the created plot, the Makie figure, axis and plot, can be
# accessed via the methods `figure`, `axis` and `plot`. This allows us to modify
# the graph layout and to remove the decorations.
Vahana.plot(vp).layout = NetworkLayout.Stress()
Makie.hidedecorations!(axis(vp))
figure(vp)
# To visualize the agents' opinions, we can leverage Vahana's
# integration with Makie's plotting capabilities. Instead of directly
# modifying the `node_color` property of the Makie plot, we can define
# custom visualization functions. These functions, which can have
# methods for different agent and edge types, are used by [`create_graphplot`](@ref)
# to determine various properties of nodes and edges in the plot.
# This approach not only allows for more dynamic and type-specific
# visualizations but also supports interactive plots when using GLMakie as
# the backend. We'll define a function called `modify_vis` that specifies how
# different elements should be displayed. This function will be passed to
# [`create_graphplot`](@ref) via the `update_fn` keyword argument.
colors = Colors.range(Colors.colorant"red", stop=Colors.colorant"green", length=100)
modify_vis(state::HKAgent, _ ,_) = Dict(:node_color => colors[state.opinion * 100 |> ceil |> Int],
:node_size => 15)
modify_vis(_::Knows, _, _, _) = Dict(:edge_color => :lightgrey,
:edge_width => 0.5);
function plot_opinion(sim)
vp = create_graphplot(cysim,
update_fn = modify_vis)
Vahana.plot(vp).layout = NetworkLayout.Stress()
Makie.hidedecorations!(axis(vp))
Makie.Colorbar(figure(vp)[:, 2]; colormap = colors)
figure(vp)
end;
# And now we can plot the initial state
plot_opinion(cysim)
# And then the state after 500 iterations
for _ in 1:500
apply!(cysim, step, [ HKAgent ], [ HKAgent, Knows ], [ HKAgent ])
end
plot_opinion(cysim)
# # Finish the Simulation
# As always, it is important to call `finish_simulation` at the end of the
# simulation to avoid memory leaks.
finish_simulation!(cysim);
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 19052 | # # Adding Spatial Information
#=
# Goal
This example demonstrates how spatial information can be integrated
into an agent-based model using Vahana. While Vahana's primary focus
is on graph-based simulations, it support the inclusion of spatial
information into models. It allows you to define a spatial grid,
associate agents with specific locations, and implement interactions
based on spatial proximity, even though the underlying implementation
still operates on graph structures.
It's worth noting that in its current version, Vahana may not be the
optimal choice for models that primarily depend on frequent movement
of agents across space. However, as this example will show, it is
entirely possible to implement those models.
It allows you to define a spatial grid, associate agents with specific
locations, and implement interactions based on spatial proximity, all
while leveraging Vahana's efficient graph-based computations.
For the understanding of how Vahana handles spatial information and
rasters, you may find it helpful to watch also the [corresponding
section of the Vahana.jl Juliacon
video](https://youtu.be/-318ec-kCBM?si=YNnWLrb-_7RPSEPB&t=1198). The
video provides a visual explanation of how rasters are implemented
within Vahana's graph-based framework and demonstrates some key
concepts that we'll be applying in this tutorial.
In this tutorial, we'll implement a predator-prey model with spatial
components, showcasing how Vahana's raster functionality can be used
to create a spatially-explicit ecological simulation.
The model is based on the [Predator-Prey for High-Performance
Computing](https://peerj.com/articles/cs-36/) (PPHPC) model. In
PPHPC the agents move randomly, in our implementation the prey move
to locations with grass (if one is in sight) and the predators move to
locations with prey to demonstrate how features like this can be
implemented in Vahana.
=#
# # Agent and Edge Types
using CairoMakie, Vahana, Random
Random.seed!(1); #hide
detect_stateless(true) #hide
# In our spatial predator-prey model, we define separate structures for
# predators and prey, even though they share the same fields:
struct Predator
energy::Int64
pos::CartesianIndex{2}
end
struct Prey
energy::Int64
pos::CartesianIndex{2}
end
#=
Despite their identical structure, we define them as separate types
because Vahana uses these types as tags for differentiating between
agent categories.
In the following sections, we'll use "Species" as an umbrella term to
refer to both Predator and Prey. Functions that are applicable to both
types will take the type as a parameter, which we'll denote as Species
in the function arguments.
=#
# Aside from the predator and prey agents, the spatial environment is
# represented by grid cells, which are also implemented as agents and
# consequently function as nodes within the graph structure.
struct Cell
pos::CartesianIndex{2}
countdown::Int64
end
#=
All agents maintain their position as part of their internal
state. However, a cell can only perceive the animals if they are
directly connected to the cell through an edge. Vahana facilitates the
establishment of such edges via the [`move_to!`](@ref) function.
Edges represent connections from prey or predators to cells. We define
Position as a parametric type, enabling cells to distinguish between
prey and predators based on the type of the edges.
=#
struct Position{T} end
#=
Views are also edges from the cells to the prey and predators
respectively. These edges represent the cells that are visible to a
prey or predator so that, for example, it is possible to check which
cell in the visible area contains food.
=#
struct View{T} end
# VisiblePrey edges represent connections from prey to
# predator. Currently, all edge types link animals to cells, and without
# an incoming edge from prey, a predator lacks awareness of prey
# positions. The VisiblePrey edges are generated by cells through the
# `find_prey` transition function, as cells possess knowledge of which Prey
# entities are directly located on the cell via the Position{Prey} edges,
# and consequently within the view of a predator via the View{Predator}
# edges.
struct VisiblePrey end
# The last two edge types are messages to inform the agents that they
# must die or find something to eat.
struct Die end
struct Eat end
# # Params and Globals
# We follow the parameter structure from the PPHPC model, but use
# (besides the initial population) the same parameters for Prey and Predator
# for the example run.
Base.@kwdef mutable struct SpeciesParams
init_population::Int64 = 500
gain_from_food::Int64 = 5
loss_per_turn::Int64 = 1
repro_thres::Int64 = 5
repro_prob::Int64 = 20
end
Base.@kwdef struct AllParams
raster_size::Tuple{Int64, Int64} = (100, 100)
restart::Int64 = 5
predator::SpeciesParams = SpeciesParams()
prey::SpeciesParams = SpeciesParams()
end;
params = AllParams()
params.prey.init_population = 2000;
# We are creating timeseries (in the form of `Vector`s) for the predator
# and prey population, the number of cells with food, and the average
# energy of the predators and prey.
Base.@kwdef mutable struct PPGlobals
predator_pop = Vector{Int64}()
prey_pop = Vector{Int64}()
cells_with_food = Vector{Int64}()
mean_predator_energy = Vector{Float64}()
mean_prey_energy = Vector{Float64}()
end;
# ## Create the Simulation
# We have now defined all the Julia structs needed to create the model
# and a simulation.
const ppsim = ModelTypes() |>
register_agenttype!(Predator) |>
register_agenttype!(Prey) |>
register_agenttype!(Cell) |>
register_edgetype!(Position{Predator}) |>
register_edgetype!(Position{Prey}) |>
register_edgetype!(View{Predator}) |>
register_edgetype!(View{Prey}) |>
register_edgetype!(VisiblePrey) |>
register_edgetype!(Die) |>
register_edgetype!(Eat) |>
create_model("Predator Prey") |>
create_simulation(params, PPGlobals())
# ## Initialization
# First we add the Cells to the Simulation. Therefore we define a
# constructor function for the cells. There is a 50% probability that a cell
# contains food (and in this case `countdown` is 0).
init_cell(pos::CartesianIndex) =
Cell(pos, rand() < 0.5 ? 0 : rand(1:param(ppsim, :restart)))
add_raster!(ppsim, :raster, param(ppsim, :raster_size), init_cell);
# We define a auxiliary functions to facilitate the relocation of an
# agent to a new position. These functions will add a single `Position`
# edge from the animal to the cell at the `newpos` position, and for all
# cells within a Manhattan distance of 1, `View` edges will be
# established from those cells to and from the animal, as well as to the
# cell itself.
function move!(sim, id, newpos, Species)
move_to!(sim, :raster, id, newpos, nothing, Position{Species}())
move_to!(sim, :raster, id, newpos, View{Species}(), View{Species}();
distance = 1, metric = :manhatten)
end;
# The add_animals function is a generic initializer for both predators and
# prey, taking species-specific parameters and the species type as
# arguments. It creates a specified number of agents, each with a
# random position on the raster and a random initial energy within a
# defined range, then adds them to the simulation and places them on
# the raster using the move! function.
function add_animals(params, Species)
energyrange = 1:(2*params.gain_from_food)
foreach(1:params.init_population) do _
pos = random_pos(ppsim, :raster)
id = add_agent!(ppsim, Species(rand(energyrange), pos))
move!(ppsim, id, pos, Species)
end
end
add_animals(param(ppsim, :prey), Prey)
add_animals(param(ppsim, :predator), Predator)
# At the end of the initialization phase we have to call finish_init!
finish_init!(ppsim)
# ## Transition Functions
# As mentioned in the comment for the View type, the cells are
# responsible for connecting the Prey with the Predators. So each cell
# iterate over each prey on the cell and add edges to all predators
# that can view the cell.
# The underscore (_) as the first argument in the find_prey function signifies
# that we don't need to access the state of the cell itself. This is
# because the function only needs to check for the presence of edges and create
# new connections based on those edges, without using any information from
# the cell's internal state. As a result, when we call apply! for
# find_prey, we don't include Cell in the read argument. Consequently,
# Vahana passes Val(Cell) as the first argument to find_prey for multiple
# dispatch purposes, rather than the actual cell state. This approach
# optimizes performance by avoiding unnecessary data access and allows
# the function to operate solely on the graph structure of the simulation.
function find_prey(_::Val{Cell}, id, sim)
if has_edge(sim, id, Position{Prey}) && has_edge(sim, id, View{Predator})
for preyid in neighborids(sim, id, Position{Prey})
for predid in neighborids(sim, id, View{Predator})
add_edge!(sim, preyid, predid, VisiblePrey())
end
end
end
end;
# If a predator has enough energy left to move and there is a prey in the
# predator's field of view, a random prey is selected and its position
# is used as the new position. If no prey is visible, a random cell in
# the predator's field of view is selected as the new position.
# If there is not enough energy left, the transition function returns `nothing`,
# which means that the predator dies and is no longer part of the graph.
function move(state::Predator, id, sim)
e = state.energy - param(sim, :predator).loss_per_turn
if e > 0
## we need to access the pos of the prey which is part of it's state
prey = neighborstates(sim, id, VisiblePrey, Prey)
newpos = if isnothing(prey)
nextcellid = rand(neighborids(sim, id, View{Predator}))
agentstate(sim, nextcellid, Cell).pos
else
rand(prey).pos
end
move!(sim, id, newpos, Predator)
Predator(e, newpos)
else
nothing
end
end;
# The movement logic for prey differs from that of predators in terms of
# their target. While predators seek cells containing prey, prey agents
# search for cells with available grass. In our implementation of the
# PPHPC (Predator-Prey for High-Performance Computing) model, grass
# availability is indicated by the countdown field of a
# cell. Specifically, grass is considered available for consumption when a
# cell's countdown value equals 0.
function move(state::Prey, id, sim)
e = state.energy - param(sim, :prey).loss_per_turn
if e > 0
withgrass = filter(neighborids(sim, id, View{Prey})) do id
agentstate(sim, id, Cell).countdown == 0
end
nextcellid = if length(withgrass) == 0
rand(neighborids(sim, id, View{Prey}))
else
rand(withgrass)
end
newpos = agentstate(sim, nextcellid, Cell).pos
move!(sim, id, newpos, Prey)
Prey(e, newpos)
else
nothing
end
end;
# If a cell has no grass and the countdown field is therefore > 0, the
# countdown is decreased by 1.
function grow_food(state::Cell, _, _)
Cell(state.pos, max(state.countdown - 1, 0))
end;
# The try_eat transition function simulates the predator-prey interactions and
# feeding processes within each cell. When both predators and prey
# occupy the same cell, the function generates random predator-prey pairings,
# ensuring each prey is targeted at most once and each predator consumes
# no more than one prey. These interactions are represented by creating
# Die edges from the cell to the consumed prey and Eat edges from the
# cell to the successful predators. If any prey survive this process and
# the cell contains available grass (indicated by a countdown of 0), an
# Eat edge is established between the cell and a randomly selected
# surviving prey, simulating grazing behavior.
function try_eat(state::Cell, id, sim)
predators = neighborids(sim, id, Position{Predator})
prey = neighborids(sim, id, Position{Prey})
## first the predators eat the prey, in case that both are on the cell
if ! isnothing(predators) && ! isnothing(prey)
prey = Set(prey)
for pred in shuffle(predators)
if length(prey) > 0
p = rand(prey)
add_edge!(sim, id, p, Die())
add_edge!(sim, id, pred, Eat())
delete!(prey, p)
end
end
end
## then check if there is prey left that can eat the grass
if ! isnothing(prey) && length(prey) > 0 && state.countdown == 0
add_edge!(sim, id, rand(prey), Eat())
Cell(state.pos, param(sim, :restart))
else
state
end
end;
# The reproduction mechanism for both predators and prey follows a similar
# pattern, allowing us to define a generic function applicable to both
# species. This function first determines if the animal found something to eat
# by checking for the presence of an Eat edge targeting the animal, a
# result of previous transition functions. If such an edge exists, the
# animal's energy increases.
# The function then evaluates if the animal's energy
# exceeds a specified threshold parameter. When this condition is met,
# reproduction occurs: a new offspring is introduced to the simulation
# via the add_agent call, inheriting half of its parent's energy, and is
# positioned at the same location as its parent using the move! function.
function try_reproduce_imp(state, id, sim, species_params, Species)
if has_edge(sim, id, Eat)
state = Species(state.energy + species_params.gain_from_food, state.pos)
end
if state.energy > species_params.repro_thres &&
rand() * 100 < species_params.repro_prob
energy_offspring = Int64(round(state.energy / 2))
newid = add_agent!(sim, Species(energy_offspring, state.pos))
move!(sim, newid, state.pos, Species)
Species(state.energy - energy_offspring, state.pos)
else
state
end
end;
# For the Predator we can just call the reproduce function with the necessary
# arguments.
try_reproduce(state::Predator, id, sim) =
try_reproduce_imp(state, id, sim, param(sim, :predator), Predator)
# The prey animal needs an extra step because it might have been eaten
# by a predator. So, we check if there is a `Die` edge leading to the
# prey animal, and if so, the prey animal is removed from the
# simulation (by returning nothing). Otherwise, we again just call the
# reproduce function defined above.
function try_reproduce(state::Prey, id, sim)
if has_edge(sim, id, Die)
return nothing
end
try_reproduce_imp(state, id, sim, param(sim, :prey), Prey)
end;
# We update the global values and use the `mapreduce` method to count
# the population and the number of cells with food. Based on the
# values, we can then also calculate the mean energy values.
function update_globals(sim)
push_global!(sim, :predator_pop, mapreduce(sim, _ -> 1, +, Predator; init = 0))
push_global!(sim, :prey_pop, mapreduce(sim, _ -> 1, +, Prey; init = 0))
push_global!(sim, :cells_with_food,
mapreduce(sim, c -> c.countdown == 0, +, Cell))
push_global!(sim, :mean_predator_energy,
mapreduce(sim, p -> p.energy, +, Predator; init = 0) /
last(get_global(sim, :predator_pop)))
push_global!(sim, :mean_prey_energy,
mapreduce(sim, p -> p.energy, +, Prey; init = 0) /
last(get_global(sim, :prey_pop)))
end;
# We add to our time series also the values after the initialization.
update_globals(ppsim);
# And finally we define in which order our transitions functions are called.
# Worth mentioning here are the keyword arguments in `find_prey` and
# `try_reproduce`.
# The add_existing keyword in the try_reproduce transition function signify that
# the currently existing position and view edges should not be
# removed, and only additional edges should be added, in our case the
# position of the potential offspring.
function step!(sim)
apply!(sim, move,
[ Prey ],
[ Prey, View{Prey}, Cell ],
[ Prey, View{Prey}, Position{Prey} ])
apply!(sim, find_prey,
[ Cell ],
[ Position{Prey}, View{Predator} ],
[ VisiblePrey ])
apply!(sim, move,
[ Predator ],
[ Predator, View{Predator}, Cell, Prey, VisiblePrey ],
[ Predator, View{Predator}, Position{Predator} ])
apply!(sim, grow_food, Cell, Cell, Cell)
apply!(sim, try_eat,
[ Cell ],
[ Cell, Position{Predator}, Position{Prey} ],
[ Cell, Die, Eat ])
apply!(sim, try_reproduce,
[ Predator, Prey ],
[ Predator, Prey, Die, Eat ],
[ Predator, Prey, Position{Predator}, Position{Prey},
View{Predator}, View{Prey} ];
add_existing = [ Position{Predator}, Position{Prey},
View{Predator}, View{Prey} ])
update_globals(sim)
end;
# Now we can run the simulation
for _ in 1:400 step!(ppsim) end
# ## Plots
# To visualize the results we use the Makie package.
# ### Time series
# First, we will generate a line chart for the time series data stored in
# the global state. Vahana provides the `plot_globals` function for this
# purpose. This function not only returns the Makie Figure itself but also the
# Axis and Plots, allowing for further processing of the result. If you
# wish to display the default result, you can utilize the Julia `first`
# function to extract the figure from the returned tuple.
plot_globals(ppsim, [ :predator_pop, :prey_pop, :cells_with_food ]) |> first
# ### Spatial distribution
# To visualize the spatial information we can use `heatmap` in
# combination with the Vahana's `calc_raster` function. E.g. the
# number of Position{Prey} edges connected to a cell give us the
# number of Prey individuals currently on that cell.
# It would be nice to have a colorbar for the heatmaps so we define a small
# helper function that can be used in a pipe.
function add_colorbar(hm)
Makie.Colorbar(hm.figure[:,2], hm.plot)
hm
end;
# #### Predators Positions
calc_raster(ppsim, :raster, Int64, [ Position{Predator} ]) do id
num_edges(ppsim, id, Position{Predator})
end |> heatmap |> add_colorbar
# #### Prey Positions
calc_raster(ppsim, :raster, Int64, [ Position{Prey} ]) do id
num_edges(ppsim, id, Position{Prey})
end |> heatmap |> add_colorbar
# #### Cells that contains food
calc_raster(ppsim, :raster, Int64, [ Cell ]) do id
agentstate(ppsim, id, Cell).countdown == 0
end |> heatmap |> add_colorbar
# # Finish the Simulation
# As always, it is important to call `finish_simulation` at the end of the
# simulation to avoid memory leaks.
finish_simulation!(ppsim);
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 25551 | #=
# First Steps
# Goal
In this tutorial, we will build a simple market model with multiple
buyers and sellers. Each buyer has a fixed budget and preferences for
two goods, x and y. Sellers offer these goods, and buyers purchase
from a randomly selected subset of sellers at each time step.
The model illustrates several core concepts in Vahana, including:
1. Defining agent and edge types as structs
2. Initializing a simulation with agents and edges
3. Implementing transition functions to update agent states
4. Tracking simulation results
This simple model serves as an introduction to Vahana's capabilities
for agent-based modeling. While relatively basic, it demonstrates how
to represent a multi-agent system with different types of agents,
connections between agents, and state transitions driven by agent
interactions.
# Model Overview
Our model simulates a dynamic market with $n$ buyers and $m$ sellers,
trading two types of goods: $x$ and $y$. We use good $x$ as the
numeraire, fixing its price at 1, while the price of good $y$, denoted
as $p$, is variable and adjusted by sellers over time. Each buyer in
our market has a unique preference and a constant budget $B$ for
purchasing both commodities. These preference is represented by an
individual parameter α, which determines the buyer's relative desire
for good $x$ versus good $y$. Buyers make their purchasing decisions based
on a Cobb-Douglas utility function:
```math
\max_{x,y} u(x, y) = x^\alpha \cdot y^{1 - \alpha}
```
subject to their budget constraint: $x + y · p ≤ B$. This utility
maximization leads to an optimal demand for each good:
```math
\begin{aligned}
x &= B \cdot \alpha \\
y &= \frac{B \cdot (1 - \alpha)}{p}
\end{aligned}
```
On the supply side, sellers offer both goods $x$ and $y$, which we assume
to be joint products. Their primary goal is to balance the production
and sales of these two goods. To achieve this, sellers adjust their
prices based on the aggregate demand from their customers. The price
adjustment mechanism is given by:
```math
\begin{aligned}
p_t &= \frac{d_y}{d_x} \cdot p_{t-1} \\
\textrm{where } d_x &= \sum_{b \in \textrm{buyers}}x_b ,\quad d_y = \sum_{b \in \textrm{buyers}} y_b
\end{aligned}
```
# Agent and Edge Types
Now that we understand our market model, let's implement it using
Vahana. We'll start by defining our agent types and edge types, then
create and initialize our simulation.
First, we need to import the necessary modules:
=#
using Vahana
import Random: rand
import DataFrames
#=
In Vahana, agents and the edges between them are represented by
Julia structs. However, these structs must meet specific requirements:
1. They must be immutable.
2. They must be "bitstypes".
A bitstype in Julia is a type that is composed entirely of primitive
types (like Int, Float64, Bool) or other bitstypes, and has a known,
fixed size in memory. This also implies that the type of a struct variables
must be declared.
This restrictions allows Vahana to efficiently manage and distribute
agents across processes in parallel simulations.
Let's define our agent types with these requirements in mind:
=#
struct Buyer
α::Float64 # Preference parameter
B::Float64 # Budget
end
struct Seller
p::Float64 # Current price of good y
d_y::Float64 # Total demand for good y (used for price adjustment)
end
# To facilitate agent creation with some randomization, we'll define
# custom constructors:
Buyer() = Buyer(rand(), rand((1:100)))
Seller() = Seller(rand() + 0.5, 0);
#=
These constructors create:
- Buyers with random $\alpha$ (between 0 and 1) and $B$ (between 1 and 100)
- Sellers with a random initial price $p$ (between 0.5 and 1.5) and zero initial demand.
Now, let's look at our edge types in more detail:
This `KnownSeller` network is fixed and describes the sellers known to each
buyer. In Vahana, the direction of an edge determines the flow of
information. Since buyers need price information from sellers to
calculate their demand, we define this as an edge from sellers to
buyers. We call this network KnownSeller.
The edges of the `KnownSeller` network don't carry additional
information, so we define them as an empty struct. We'll use this as a kind
of tag later to select only the edges of this type.
=#
struct KnownSeller end
#=
The Bought network represents actual transactions between buyers and
sellers. This network is dynamic, with edges created during the
simulation runtime. Each edge in the Bought network carries information
about the quantities of goods purchased in a transaction. Specifically:
=#
struct Bought
x::Float64 # Quantity of good x bought
y::Float64 # Quantity of good y bought
end
# To make working with Bought edges easier, we'll define an addition
# operation:
import Base.+
+(a::Bought, b::Bought) = Bought(a.x + b.x, a.y + b.y);
# This allows us to easily sum up multiple Bought edges, which will be
# useful when sellers calculate total demand.
# # Defining the Model Structure
#=
In Vahana, the [`ModelTypes`](@ref) constructor is the starting point
for defining the structure of your agent-based model. To populate this
instance, we use the `register_agenttype!` and `register_edgetype!`
functions. These functions tell Vahana about the types of agents and
edges in your model, allowing it to set up the necessary internal data
structures and optimizations. The |> operator can be used for function
chaining, providing a concise way to register multiple types.
=#
const modeltypes = ModelTypes() |>
register_agenttype!(Buyer) |>
register_agenttype!(Seller) |>
register_edgetype!(KnownSeller) |>
register_edgetype!(Bought);
# # Defining Model Parameters and Globals
#=
Vahana offers two ways to define parameters for your model: using
`register_param!` or creating a custom parameter struct. The `register_param!`
function allows you to register individual parameters with your
model. For example, you might use:
=#
modeltypes |>
register_param!(:numBuyer, 50) |>
register_param!(:numSeller, 5) |>
register_param!(:knownSellers, 2);
#=
With this approach, the parameters can then be set to values other
than the default value via [`set_param!`](@ref) calls until the
simulation is initialized with [`finish_init!`](@ref).
Alternatively you can define a custom parameter struct and then pass an
instance of this struct to [`create_simulation`](@ref).
In addition to parameters, Vahana allows you to manage global state
variables that can change during the simulation. This is particularly
useful for tracking aggregate statistics or maintaining shared
information across all agents. Similar to parameters, you can register
individual global variables:
=#
modeltypes |>
register_global!(:x_minus_y, Vector{Float64}()) |>
register_global!(:p, Vector{Float64}());
# Again, you could alternatively, you can define a custom struct for globals
# and pass an instance of this struct to [`create_simulation`](@ref) as
# shown in the other tutorials.
# Please note that Vahana's global state is distinct from the
# functionality of the `global` keyword in Julia programming
# language. The two concepts are unrelated and should not be conflated.
# # Create the Model and Simulation
#=
In Vahana, the term "model" is used in a somewhat unconventional way
compared to other agent-based modeling frameworks. In Vahana, a model
created via [`create_model`](@ref) does not contain any rules about
how the state of a simulation changes over time. Instead, a Vahana
model is more akin to a specification of the possible state space - it
defines the set of all possible graphs that can be created with the
specified agent and edge types.
Think of a Vahana model as a blueprint or a schema. It outlines the
structure of your simulation - what types of agents can exist, what
types of relationships (edges) can exist between them, and what global
parameters and variables are available. However, it doesn't dictate
how these elements interact or evolve over time.
A simulation, on the other hand, is a concrete realization within this
state space. It's an actual graph with specific agents and edges,
representing the current state of your simulated world at a given
point in time.
Transition functions, which we'll define later, are the mechanisms
that actually change the state of the simulation over time. These
functions operate on the current state of the simulation (the current
graph of agents and edges) and produce a new state by modifying agent
attributes, creating or removing agents and edges, and updating global
variables.
To create a model in Vahana, we use the [`create_model`](@ref) function. This
function takes the ModelTypes object we've been building through our
type registrations and parameter/globals definitions, and the name of
the model:
=#
const model = create_model(modeltypes, "Excess Demand")
# Once we have a model, we can create a simulation based on that model using
# the [`create_simulation`](@ref) function:
const sim = create_simulation(model)
#=
This function creates a new simulation instance based on our model. At this
point, the simulation is empty - it doesn't contain any agents or
edges yet. It's essentially a blank canvas ready for us to populate with
agents and edges according to our model's specifications.
# Populating the Simulation
After creating our simulation, the next step is to populate it with
agents and edges. Vahana provides [`add_agent!`](@ref),
[`add_agents!`](@ref), [`add_edge!`](@ref), and [`add_edges!`](@ref)
functions for this purpose.
The [`add_agent!`](@ref) function returns an `AgentID`, while [`add_agents!`](@ref)
returns a vector of `AgentID`s. These identifiers are unique to each
agent at the current state of the simulation.
In parallel simulations, the `AgentID` incorporates information about
the process number to which the agent is assigned. Consequently, the
ID may be modified if an agent is reassigned to a different process.
In the current implementation of Vahana, agents only change processes
during the [`finish_init!`](@ref) function. However, this design
allows for potential future implementation of dynamic load balancing.
It is also possible that the same `AgentID` is utilized
multiple times for distinct agents. Consequently, an `AgentID`
returned by a Vahana function call or passed as an argument to a
callback function (refer to the [Transition
functions](./performance.md#Transition functions) section below for
more details) is only valid within a specific scope. This scope is
limited to either the period before the finish_init! function is
invoked or until the callback/transition function has completed its
execution. After these points, the ID should not be considered
reliable for further use or reference.
If your model requires persistent identification of agents, you should
implement this yourself by adding an ID field to your agent struct. For
example:
```
struct BuyerWithID
id::UUID # created via the UUIDs standard library
α::Float64
B::Float64
end
```
You would then manage these IDs yourself, ensuring they remain
constant throughout the simulation.
In our case, we use the IDs returned by add_agents! to iterate over
all buyer IDs, randomly select `numSellers` seller IDs for each
buyer ID, and then create edges between them in the `KnownSeller`
network.
We can see in the following code snippet also how parameters of the
Simulation can be accessed via the [`param`](@ref) function.
=#
buyerids = add_agents!(sim, [ Buyer() for _ in 1:param(sim, :numBuyer)])
sellerids = add_agents!(sim, [ Seller() for _ in 1:param(sim, :numSeller)])
for b in buyerids
for s in rand(sellerids, param(sim, :knownSellers))
add_edge!(sim, s, b, KnownSeller())
end
end
sim
# As you can see from the result of the code block above, Vahana has
# "pretty print" functions for some of its data structures.
# Finally, we call [`finish_init!`](@ref). This crucial step completes
# the initialization process, setting up data structures and, in
# parallel simulations, distributing agents across processes.
finish_init!(sim)
# # Defining Transition Functions
#=
In Vahana, transition functions define how your simulation evolves
from one state to the next. They encapsulate the rules and behaviors
of your agents, determining how agents interact, make decisions, and
change their states. The transition function is called for each agent separately.
A typical transition function in Vahana has the following signature:
```julia
function transition_function(state, id, sim)
# Function body
return new_agent_state
end
```
A transition function must have three parameters. The first represents the
current state of the agent, allowing it to make decisions based on its
own attributes and conditions. The second parameter is the temporary
ID of the agent. This ID can be used within the transition function to
access other elements of the graph that are visible to the agent via
functions like [`edges`](@ref) or [`neighborstates`](@ref). It's
important to note that this ID should not be stored, as it may change
between time steps. Finally, there's `sim`, which is the simulation
object. This provides access to the global state and parameters of the
simulation. These three parameters together give the agent all the
context it needs to determine its next state.
The first transition function we are implementing calculates the
demand for the goods $x$ and $y$.
This transition function is called for all Buyers. First, the
[`neighborids`](@ref) function is used to get a vector that contains
the (temporary) IDs all the sellers known by the actual buyer.
One of the IDs of the sellers is selected using the `rand` function. For
this seller, the state is accessed via the [`agentstate`](@ref)
function. In cases where the type of the agent whose state we want to
access is unknown, it's possible to use [`agentstate_flexible`](@ref)
instead.
Then the agent calculates it's demand for the goods $x$ and $y$, and
adds an edge with the information about the demand to the `Bought`
network, which is then used in the next transition function by the
sellers to sum up the demand and calculate the new price.
=#
function calc_demand(b::Buyer, id, sim)
seller = rand(neighborids(sim, id, KnownSeller))
s = agentstate(sim, seller, Seller)
x = b.B * b.α
y = b.B * (1 - b.α) / s.p
add_edge!(sim, id, seller, Bought(x, y))
end;
#=
In the `calc_price` transition function, sellers summarize all the goods $x$
and $y$ they sold. They do this by summing the state of all incoming
Bought edges.
If a seller hasn't made any sales (i.e., no incoming Bought edges
exist), [`edgestates`](@ref) returns `nothing`, and the seller's state
remains unchanged. Otherwise, `edgestates` returns a Vector containing
the states of all relevant edges. We aggregate this vector using the
`reduce` function, leveraging the previously defined `+` operator for Bought.
Finally, we construct a new seller state. The new price is calculated
as `q.y / q.x * s.p`.
=#
function calc_price(s::Seller, id, sim)
sold = edgestates(sim, id, Bought)
if isnothing(sold)
return s
end
q = reduce(+, sold)
Seller(q.y / q.x * s.p, q.y)
end;
#=
# Applying Transition Functions
To apply these transition functions to the current state of a
simulation, Vahana provides the [`apply!`](@ref) method. This method
is the key mechanism for evolving the simulation state over time,
executing our defined transition functions across the population of
agents. Let's examine its signature and behavior in more detail:
```julia
apply!(sim, func, call, read, write; add_existing = [], with_edge = nothing)
```
`sim` is the simulation instance and `func` is the transition function to be
applied to the simulation state.
The `call` argument in `apply!` specifies which agent types the
transition function should be applied to. This can be either a single
agent type or a collection of agent types. In most cases, as in our
market model, call will contain only a single type. For example, when
we apply calc_demand, we only want to call it for Buyer
agents. However, Vahana allows for more complex scenarios where a
single transition function can be applied to multiple agent
types. This flexibility allows for more complex agent interactions and
behaviors within a single transition function, which can be
particularly useful in models where different types of agents share
similar behaviors or decision-making processes.
The `read` argument must include all agent and edge state types that
are accessed in the transition function. This is particularly
important in parallel simulations, as it ensures that all necessary
data is transmitted to the processes that need to access it. When
Vahana's assertion system is active, it checks that only these
specified types are accessed. However, if assertions are disabled via
[`enable_asserts`](@ref), forgetting to include a type in read can
lead to incorrect results without raising an error. It's worth noting
that while including unnecessary types in read doesn't cause errors,
it can negatively impact performance.
A noteworthy scenario occurs when the `call` type is excluded from the
`read` set. In these instances, the transition function's first argument is
altered. Rather than representing the agent state, it becomes a Value
Type corresponding to the 'call' type. Consequently, the state of the
agent for which the transition function is invoked becomes inaccessible within
the function itself.
The `write` collection must contain all agent and edge state types
that are modified in the transition function. Conceptually, one might think of
the resulting graph after a transition as the union of all agents and
edges returned by individual transition function calls. However, this
approach would be inefficient, requiring the reconstruction of even
stable parts of the graph. Instead, Vahana optimizes this process by
removing only the parts of the graph specified in the write
collection. This means you can only change the state of agents or
edges of a type if you're also re-adding the state of constant elements
of that type.
But in cases where you want to add new elements (like additional edges)
without modifying existing ones, you can use the optional
`add_existing` keyword. This keyword takes a single or a collection of
agent or edge state types. For all types in this collection, existing
agents or edges will be preserved, even if the type is also in the
write collection. This provides a flexible way to extend the graph
without completely rebuilding it. But there is the restriction that
agent types in `add_existing` can not be also in `call`.
The `with_edge` keyword restricts the application of the transition function
to agents that are targets of a specified edge type. It's equivalent
to manually checking for the presence of the edge for each agent
before applying the function, but allows Vahana to optimize this
operation internally. `with_edge` should only be used when a small
proportion of agents have edges of the specified type. If most agents
have this edge type, using with_edge may decrease performance compared to
a manual check inside the transition function.
The implementation process, while seemingly complex, is quite
straightforward in practice. Begin by crafting your transition function as
previously demonstrated. Then, follow these steps:
1. Identify the agent types for which the transition function should be invoked and include these types in the `call` parameter.
2. Examine the function calls, such as [`edgestates`](@ref), to determine which types are utilized. Add these types to the `read` parameter.
3. If you access the first argument of the transition function (representing the agent's state), include that type in the `read` parameter as well.
4. Should you intend to return a modified agent state, add that type to the `write` parameter.
5. If your function includes additional `add_edge!` or `add_agent!` calls, incorporate their respective types into the `write` parameter.
6. Be aware that all existing agents and edges will be removed from the simulation unless their types are also specified in the `add_existing` parameter.
Following this schema we get for our transition functions
=#
apply!(sim, calc_demand, Buyer, [ Buyer, Seller, KnownSeller ], Bought);
# and
apply!(sim, calc_price, Seller, [ Seller, Bought ], Seller);
# # Working with Globals
#=
To summarize the state of a simulation, Vahana uses the map-reduce
combination from functional programming. First, a function is applied to each
agent or edge state, and then the result is reduced using a binary function.
E.g. to calculate the excess demand we write
=#
mapreduce(sim, b -> b.x - b.y, +, Bought)
#=
The last argument of Vahana's mapreduce specifies the agent or edge
type for which the aggregation should be performed. The anonymous
function in the second position describes the assignment for each
instance of that type. In this case, the function receives an edge of
the 'Bought' type and calculates the additional quantity of good x
that was purchased. This value is then summed across all edges of the
specified type.
To calculate the average price we define a helper function
=#
function calc_average_price(sim)
m = mapreduce(sim, s -> s.p * s.d_y, +, Seller)
q = mapreduce(sim, s -> s.d_y, +, Seller)
m / q
end
calc_average_price(sim)
# And now we have all elements to run the simulation, e.g. for 5 steps:
for _ in 1:5
apply!(sim, calc_demand, Buyer, [ Buyer, Seller, KnownSeller ], Bought)
push_global!(sim, :x_minus_y, mapreduce(sim, b -> b.x - b.y, +, Bought))
apply!(sim, calc_price, Seller, [ Seller, Bought ], Seller)
push_global!(sim, :p, calc_average_price(sim))
end
# To get a resulting timeseries, we use the [`get_global`](@ref) function:
get_global(sim, :p)
# # Investigating the Simulation State
#=
Vahana offers several methods to examine the current state of your
simulation. For example, the user-defined show methods for the model
and simulation instances, which provide a quick summary of your
model/simulation:
=#
model
#
sim
# Vahana offers the `show_agent` function to inspect the state of individual
# agents. This function displays comprehensive information about a
# randomly selected agent of the specified type. Additionally, users
# have the option to specify a particular agent identifier if they wish
# to examine a specific agent. The `show_agent` function returns the
# identifier of the selected agent.
show( #hide
show_agent(sim, Seller, 1)
) #hide
#=
The `show_agent` function has an optional keyword argument, `neighborstate`,
which enables the user to examine the state of neighboring agents. The
`neighborstate` argument should be a vector of symbols representing
the field names that should be displayed.
=#
show( #hide
show_agent(sim, Seller, 1; neighborstate = [ :B ])
) #hide
#=
As mentioned in the [Agent and Edge Types](#Agent-and-Edge-Types)
section, all agent and edge types in Vahana must be of type
`bitstype`. This has the usefull side effect that the state of the agents
and edges can be nicely converted into a DataFrame.
It is important to note that the DataFrame in a parallel simulation
contains only the agents or edges of the process in which the function is
called, and not those of the complete simulation. If the latter is
required, [`all_agents`](@ref) or [`all_edges`](@ref) can be used.
=#
first(DataFrame(sim, Bought; types = true), 10)
#
# To get the DataFrame for the Globals, we call the `GlobalsDataFrame`
# function for our sim. Be aware, that only global variable that are vectors
# are added to the DataFrame.
GlobalsDataFrame(sim)
# # Finish the Simulation
#=
Vahana employs an internal C library for memory allocation during
simulations. Upon completing a simulation, it is necessary to invoke
the `finish_simulation` function to properly deallocate the memory resources
utilized. This function returns the global variables associated with the
concluded simulation.
=#
finish_simulation!(sim)
# # Understanding Vahana's Edge Structure
#=
When we define edge types like `KnownSeller` or `Bought`, you might
notice that these structs don't contain any information about the
source or target agents of the edge. This is by design in Vahana,
which uses a specific internal structure to represent edges
efficiently.
Internally, Vahana declares a parametric type for edges:
```
struct Edge{T}
from::AgentID
state::T
end
```
In this structure, `T` is the type of our edge (like `KnownSeller` or
`Bought`), and from is the ID of the agent at the source of the
edge. You might wonder why there's no to field for the target agent. The
reason lies in how Vahana stores these edges.
Vahana uses container structures (like dictionaries) to store
edges. The exact type of container depends on certain optimization
hints (see Edge Hints for more details), but a typical structure might
look like this:
`Dict{AgentID, Vector{Edge{T}}}`
This design means that the target agent's ID is implicitly stored
as the dictionary key. Adding it to the Edge struct would be redundant
and would unnecessarily consume memory and CPU cycles. As a user of
Vahana, you don't need to interact with this internal structure
directly, but understanding it can help you design more efficient
models and better understand how Vahana works under the hood.
=#
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 12731 | # The overall AgentID is composed of three parts:
#
# - The TypeID by which the AgentType of the agent can be determined.
#
# - The ProcessID, which in the rank on which the agent is currently managed.
#
# - The AgentNr is the index of the vectors where agent specific
# information is stored. Those indices can be reused when an agent dies
# (see AgentReadWrite.reusable), so at different times different agents
# can have the same AgentNr (and even AgentID).
#
# In this implementation these three values are packed into a single
# UInt64, but since the construction of the AgentID and the
# determination of the TypeID, ProcessID and AgentNr from the AgentID
# is always done using the interface defined below, this could also be
# changed to a tuple, for example (and this was also tested during
# development, but the implementation found here had a noticeable
# performance advantage and a better memory usage). It's also possible
# to change the number of bits used for the different parts by adjusting
# the following BITS_ values.
export AgentID, ProcessID#, AgentNr
export add_agent!, add_agents!, add_agent_per_process!
export agentstate, agentstate_flexible
export all_agents, all_agentids
export num_agents
const TypeID = UInt8
const BITS_TYPE = 8
const MAX_TYPES = 2 ^ BITS_TYPE
"""
ProcessID
The rank on which the agent is currently managed.
"""
const ProcessID = UInt32
const BITS_PROCESS = 20
const AgentNr = UInt64
const BITS_AGENTNR = 36
"""
AgentID
The AgentID is a combination of different (Vahana internal)
information about an agent, like e.g. the position where the agent
state is stored. It's important to understand that at different times
different agents can have the same agent id, therefore those ids can
not be used to identify an agent a simulation run. If you need this,
you must add an field to the agent state and create an unique value for
this field in the agent constructor by yourself.
"""
const AgentID = UInt64
@assert round(log2(typemax(TypeID))) >= BITS_TYPE
@assert round(log2(typemax(ProcessID))) >= BITS_PROCESS
@assert round(log2(typemax(AgentNr))) >= BITS_AGENTNR
@assert round(log2(typemax(AgentID))) >= BITS_TYPE +
BITS_PROCESS + BITS_AGENTNR
const SHIFT_TYPE = BITS_PROCESS + BITS_AGENTNR
const SHIFT_RANK = BITS_AGENTNR
function agent_id(typeID::TypeID, rank::Int64, agent_nr::AgentNr)::AgentID
@mayassert typeID <= 2 ^ BITS_TYPE
@mayassert rank <= 2 ^ BITS_PROCESS
@mayassert agent_nr <= 2 ^ BITS_AGENTNR "agent_nr $(agent_nr) is too big"
AgentID(typeID) << SHIFT_TYPE +
rank << SHIFT_RANK +
agent_nr
end
function agent_id(typeID::TypeID, agent_nr::AgentNr)::AgentID
agent_id(typeID, mpi.rank, agent_nr)
end
const process_mask = (2 ^ BITS_PROCESS - 1) << BITS_AGENTNR
remove_process(agentID::AgentID) = ~process_mask & agentID
# there are other agent_id functions specialized for each AgentType constructed
# via the construct_agent_methods with the signature
# agent_id(sim::$simsymbol, agent_nr, ::Type{$T})
function type_nr(id::AgentID)::TypeID
id >> SHIFT_TYPE
end
function type_of(sim, id::AgentID)
sim.typeinfos.nodes_types[type_nr(id)]
end
function process_nr(id::AgentID)::ProcessID
(id >> SHIFT_RANK) & (2 ^ BITS_PROCESS - 1)
end
function node_nr(id::AgentID)
fld(process_nr(id), mpi.shmsize)
end
function agent_nr(id::AgentID)::AgentNr
id & (2 ^ BITS_AGENTNR - 1)
end
@assert agent_id(TypeID(3), AgentNr(1)) |> type_nr == 3
@assert agent_id(TypeID(3), AgentNr(1)) |> agent_nr == 1
"""
add_agent!(sim, agent::T)::AgentID
Add a single agent of type T to the simulation `sim`.
T must have been previously registered by calling
[`register_agenttype!`](@ref).
`add_agent!` returns a new AgentID, which can be used to create edges
from or to this agent until [`finish_init!`](@ref) is called (in the
case that `add_agent!` is called in the initialization phase), or until
the transition funcion is finished (in the case that `add_agent!` is
called in an [`apply!`](@ref) callback). Do not use the ID
for other purposes, they are not guaranteed to be stable.
See also [`add_agents!`](@ref), [`add_edge!`](@ref) and [`add_edges!`](@ref)
"""
function add_agent!(::Simulation, agent)
if typeof(agent) == DataType
error("""
`add_agent!(sim, agent)` is called with a DataType as value for `agent`.
Maybe you forgot the `()` behind the DataType?
""")
else
error("""
`add_agent!(sim, agent)` is called for the unregistered type $(typeof(agent))
""")
end
end
"""
add_agents!(sim, agents)::Vector{AgentID}
Add multiple agents at once to the simulation `sim`.
`agents` can be any iterable set of agents, or an arbitrary number of
agents as arguments.
The types of the agents must have been previously registered by
calling [`register_agenttype!`](@ref).
`add_agents!` returns a vector of AgentIDs, which can be used to
create edges from or to this agents before [`finish_init!`](@ref) is
called (in the case that `add_agents!` is called in the initialization
phase), or before the transition funcion is finished (in the case that
`add_agents!` is called in an [`apply!`](@ref) callback). Do
not use the ID for other purposes, they are not guaranteed to be stable.
See also [`add_agent!`](@ref), [`register_agenttype!`](@ref),
[`add_edge!`](@ref) and [`add_edges!`](@ref)
"""
function add_agents!(sim, agents)
[ add_agent!(sim, a) for a in agents ]
end
function add_agents!(sim, agents...)
[ add_agent!(sim, a) for a in agents ]
end
"""
agentstate(sim, id::AgentID, ::Type{T})
Returns the state of an agent of type T.
In the case where the type T is not determinable when writing the code
(e.g. since there may be edges between agents of different types, the
function [`edges`](@ref) may also return agentIDs of different agent types),
[`agentstate_flexible`](@ref) must be used instead.
!!! warning
if agentstate is called with a Type{T} that does not match the
type of the agent with `id` and the vahana assertions are disabled via
[`enable_asserts`](@ref), then it is possible that the state of
an incorrect agent will be returned. When the assertions are active,
there is a runtime check that the agent with the ID `id` has indeed
the type T.
"""
function agentstate(::Simulation, ::AgentID, ::Type{T}) where T end
"""
agentstate_flexible(sim, id::AgentID)
Returns the state of an agent with the `id`, where the type of the
agent is determined at runtime. If the type is known at compile time,
using [`agentstate`](@ref) is preferable as this improves performance.
"""
agentstate_flexible(sim, id::AgentID) =
agentstate(sim, id, sim.typeinfos.nodes_id2type[type_nr(id)])
"""
all_agents(sim, ::Type{T}, [all_ranks=true])
This function retrieves a vector of the states for all agents of type T of the
simulation `sim`.
The `all_ranks` argument determines whether to include agents from all
ranks or just the current rank in parallel simulations. When
`all_ranks` is `true`, the function returns a vector of all agent
identifiers across all ranks.
The states and IDs of the agents returned by `all_agents` and
[`all_agentids`](@ref) are in the same order.
!!! info
`all_agents` cannot be called within a transition function if the
argument `all_ranks` is set to true.
See also [`all_agentids`](@ref), [`add_agents!`](@ref) and [`num_agents`](@ref).
"""
function all_agents(sim, ::Type{T}, all_ranks = true) where T
@mayassert (! sim.intransition) || all_ranks == false """
all_agents with all_ranks == true can not be called within a transition function
"""
@assert fieldcount(T) > 0 """\n
all_agents can be only called for agent types that have fields.
To get the number of agents, you can call num_agents instead.
"""
states = sim.initialized ?
getproperty(sim, Symbol(T)).read.state :
getproperty(sim, Symbol(T)).write.state
l = if has_hint(sim, T, :Immortal, :Agent)
states
else
died = sim.initialized ?
getproperty(sim, Symbol(T)).read.died :
getproperty(sim, Symbol(T)).write.died
[ states[i] for i in 1:length(died) if died[i] == false ]
end
if all_ranks && mpi.active
join(l)
else
l
end
end
"""
all_agentids(sim, ::Type{T}, [all_ranks=true])
This function retrieves a vector of the current ids for all agents of type T of
the simulation `sim`.
These ids are not stable and can change during parallel simulations,
e.g. by calling [`finish_init!`](@ref) (and hopefully in the future
through dynamic load balancing).
The `all_ranks` argument determines whether to include agents from all
ranks or just the current rank in parallel simulations. When
`all_ranks` is `true`, the function returns a vector of all agent
identifiers across all ranks.
The states and IDs of the agents returned by [`all_agents`](@ref) and
`all_agentids` are in the same order.
!!! info
`all_agentids` cannot be called within a transition function if the
argument `all_ranks` is set to true.
See also [`all_agents`](@ref), [`add_agents!`](@ref) and [`num_agents`](@ref).
"""
function all_agentids(sim, ::Type{T}, all_ranks = true) where T
@mayassert (! sim.intransition) || all_ranks == false """
all_agentids with all_ranks == true can not be called within a transition function
"""
# we are only interessted in the states field to get the length
# as this vector is also used for stateless agenttypes
states = sim.initialized ?
getproperty(sim, Symbol(T)).read.state :
getproperty(sim, Symbol(T)).write.state
l = if has_hint(sim, T, :Immortal, :Agent)
[ agent_id(typeid(sim, T), AgentNr(i)) for i in 1:length(states) ]
else
died = sim.initialized ?
getproperty(sim, Symbol(T)).read.died :
getproperty(sim, Symbol(T)).write.died
[ agent_id(typeid(sim, T), AgentNr(i))
for i in 1:length(died) if died[i] == false ]
end
if all_ranks
join(l)
else
l
end
end
"""
num_agents(sim, ::Type{T}, [all_ranks=true])
If `all_ranks` is `true` this function retrieves the number of agents of type T
of the simulation `sim`. When it is set to `false`, the function will return the
number of agents managed by the process.
See also [`add_agents!`] and [`all_agents`](@ref).
"""
function num_agents(sim, ::Type{T}, sum_ranks = true) where T
field = getproperty(sim, Symbol(T))
attr = sim.typeinfos.nodes_attr[T]
# independent = :Independent in attr[:hints]
local_num = if :Immortal in attr[:hints]
# we can not just access the length of read.state, as for
# types without field, we don't use the read.state vector
field.nextid - 1
else
died = sim.initialized ? readdied(sim, T) : writedied(sim, T)
count(!, values(died))
end
if sum_ranks
MPI.Allreduce(local_num, +, MPI.COMM_WORLD)
else
local_num
end
end
"""
add_agent_per_process!(sim::Simulation, agent::T) where T
Add a single agent of type `T` to each process in the simulation. This
function is designed to be used after initialization (when the
simulation is distributed to the different processes in a parallel
run) but outside of transition functions. It allows each process to
have its own dedicated agent, useful for tasks like random agent
selection or process-specific operations.
The function takes the simulation and the agent to be added as arguments. It
returns the `AgentID` of the agent created on the current process.
!!! warning
This function is not designed or optimized for adding many agents. Use
it sparingly, typically to create a single agent per process for special
purposes. For adding multiple agents, use the standard `add_agent!` or
`add_agents!` functions within the appropriate simulation phases.
See also [`add_agent!`](@ref) and [`add_agents!`](@ref).
"""
function add_agent_per_process!(sim::Simulation, agent::T) where T
# Check if the function is called correctly
@assert sim.initialized """
add_agent_per_process! can only be called after finish_init!"""
@assert !sim.intransition """
add_agent_per_process! cannot be called within a transition function"""
prepare_write!(sim, [], true, T)
# we fake that we a in a transition function, so that the assertion
# in add_agent! does not trigger
sim.intransition = true
# Add agent on each process
id = add_agent!(sim, agent)
sim.intransition = false
finish_write!(sim, T)
# return only the id of the agent created on the process
id
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 20886 | # _memcpy! moved in Julia 1.10 from Base._memcpy! to Libc.memcpy. Before
# I start to support two different versions, I just define my own _memcpy!
@inline memcpy!(dst, src, n) = ccall(:memcpy, Cvoid, (Ptr{UInt8}, Ptr{UInt8}, Csize_t), dst, src, n)
function construct_agent_methods(T::DataType, typeinfos, simsymbol)
attr = typeinfos.nodes_attr[T]
# in the case that the AgentType is stateless, we only check
# in mpi calls the value of the died entry
stateless = fieldcount(T) == 0
immortal = :Immortal in attr[:hints]
independent = :Independent in attr[:hints]
mortal = ! immortal
nompi = ! mpi.active
shmonly = mpi.size == mpi.shmsize
multinode = mpi.size > mpi.shmsize
if multinode
construct_mpi_agent_methods(T, attr, simsymbol, mortal)
end
@eval function init_field!(sim::$simsymbol, ::Type{$T})
@agentread($T) = AgentReadWrite($T)
# for independent types we only use the reusable field of the struct
@agentwrite($T) = AgentReadWrite($T)
for ET in sim.typeinfos.edges_types
@agent($T).last_transmit[ET] = -1
end
nothing
end
typeid = typeinfos.nodes_type2id[T]
@eval function _get_next_id(sim::$simsymbol, ::Type{$T})
if $mortal && length(@readreuseable($T)) > 0
nr = pop!(@readreuseable($T))
@writedied($T)[nr] = false
nr
else # immortal or no reusable row was found, use the next row
nr = @nextid($T)
# TODO AGENT: add an assertions that we have ids left
@nextid($T) = nr + 1
# this time we do not need an extra handling for the independent
# hint, as we can not resize the read array (which is a
# MPI shared array). Instead we copy in the case that the
# array increased the new elements in finish_write.
if nr > length(@writestate($T))
resize!(@writestate($T), nr)
# the length of writestate and writedied is always
# the same, so we don't need a seperate if
if $mortal
resize!(@writedied($T), nr)
end
end
if $mortal
@writedied($T)[nr] = false
end
nr
end
end
@eval function add_agent!(sim::$simsymbol, agent::$T)
@mayassert sim.initialized == false || sim.intransition """
You can call add_agent! only in the initialization phase (until
`finish_init!` is called) or within a transition function called by
`apply`.
"""
@mayassert begin
T = $T
sim.initialized == false ||
nodes_attrs(sim, $T)[:writeable]
end """
$T must be in the `write` argument of the transition function.
"""
nr = _get_next_id(sim, $T)
if $independent
if nr <= length(@readstate($T))
@inbounds @readstate($T)[nr] = agent
else
@inbounds @writestate($T)[nr] = agent
end
else
@inbounds @writestate($T)[nr] = agent
end
agent_id($typeid, nr)
end
@eval function agentstate(sim::$simsymbol, id::AgentID, ::Type{$T})
@mayassert begin
$type_nr(id) == sim.typeinfos.nodes_type2id[$T]
end "The id of the agent does not match the given type"
@mayassert begin
T = $T
@windows($T).prepared || ! config.check_readable
end """
$T must be in the `read` argument of the transition function.
"""
idrank = process_nr(id)
if $nompi
# highest priority: does the agent is still living
if $mortal
nr = agent_nr(id)
@mayassert ! @readdied($T)[nr] """
agentstate was requested for agent $id that has been removed
"""
end
# if it's living, but has no state, we can return directly
if $stateless
return $T()
end
# we haven't calculate nr in the $mortal case
# but need it now (maybe the compiler is clever enough
# to remove a second agent_nr(id) call, then this if could
# be remove
if ! $mortal
nr = agent_nr(id)
end
@inbounds @readstate($T)[nr]
else
(node, sr) = fldmod(idrank, mpi.shmsize)
if $shmonly || node == mpi.node
# same procedure as above, but with access to shared memory
if $mortal
nr = agent_nr(id)
@mayassert ! @agent($T).shmdied[sr + 1][nr] """
agentstate was requested for agent $id that has been removed
"""
end
if $stateless
return $T()
end
if ! $mortal
nr = agent_nr(id)
end
@inbounds @agent($T).shmstate[sr + 1][nr]
else
# same procedure as above, but with access to foreign nodes
if $mortal
@mayassert ! @agent($T).foreigndied[id] """
agentstate was requested for agent $id that has been removed
"""
end
if $stateless
return $T()
end
@agent($T).foreignstate[id]
end
end
end
@eval agent_id(_::$simsymbol, agent_nr, ::Type{$T}) =
agent_id($typeid, agent_nr)
@eval @inline function transition_with_write!(sim, idx, newstate, ::Type{$T})
if $immortal
@mayassert begin
newstate !== nothing
end "You can not return `nothing` for immortal agents"
if $independent
@inbounds @readstate($T)[idx] = newstate
else
@inbounds @writestate($T)[idx] = newstate
end
else
if isnothing(newstate)
push!(@writereuseable($T), idx)
@inbounds @writedied($T)[idx] = true
else
if $independent
@inbounds @readstate($T)[idx] = newstate
else
@inbounds @writestate($T)[idx] = newstate
end
end
end
end
@eval @inline function transition_without_write!(sim, idx, newstate, ::Type{$T})
@mayassert begin
T = $T
typeof(newstate) != $T
end """
The transition function returned an agent of type $T,
but $T is not in the `write` vector.
"""
end
@eval function transition_with_read!(wfunc, sim::$simsymbol, tfunc, ::Type{$T})
# an own counter (with the correct type) is faster then enumerate
idx = AgentNr(0)
for state::$T in @readstate($T)
idx += AgentNr(1)
# jump over died agents
if $mortal
@inbounds if @readdied($T)[idx]
continue
end
end
newstate = tfunc(state, agent_id($typeid, idx), sim)
wfunc(sim, idx, newstate, $T)
end
end
@eval function transition_with_read_with_edge!(wfunc,
sim::$simsymbol,
tfunc,
::Type{$T},
ET::DataType)
@mayassert !has_hint(sim, ET, :SingleType) """
Only edge types without the :SingeType hint can be added to
to the `with_edge` keyword of an apply! call, but $ET
has the :SingleType hint.
"""
for id in keys(edgeread(sim, ET))
idx = agent_nr(id)
state = @readstate($T)[idx]
@mayassert ! @readdied($T)[idx]
newstate = tfunc(state, id, sim)
wfunc(sim, idx, newstate, $T)
end
end
@eval function transition_without_read!(wfunc, sim::$simsymbol, tfunc, ::Type{$T})
# an own counter (with the correct type) is faster then enumerate
idx = AgentNr(0)
for _ in 1:length(@readstate($T))
idx += AgentNr(1)
if $mortal
@inbounds if @readdied($T)[idx]
continue
end
end
r = tfunc(Val($T), agent_id($typeid, idx), sim)
wfunc(sim, idx, r, $T)
end
end
@eval function transition_without_read_with_edge!(wfunc,
sim::$simsymbol,
tfunc,
::Type{$T},
ET::DataType)
@mayassert !has_hint(sim, ET, :SingleType) """
Only edge types without the :SingeType hint can be added to
to the `with_edge` keyword of an apply! call, but $ET has the :SingleType hint.
"""
for id in keys(edgeread(sim, ET))
idx = agent_nr(id)
@mayassert ! @readdied($T)[idx]
newstate = tfunc(Val($T), id, sim)
wfunc(sim, idx, newstate, $T)
end
end
@eval function prepare_write!(sim::$simsymbol, _, add_existing::Bool, ::Type{$T})
if $immortal
# distributing the initial graph or reading from file will
# also kill immortal agents, so we can assert this only
# after the sim is initialized.
# for agentypes in call, add_existing is always set to true
if sim.initialized
@assert begin
T = $T
add_existing == true
end """
You can add $T to the `write` argument only when $T is also
included in the `add_existing` argument, as $T has the hint :Immortal.
"""
end
end
if ! add_existing
@agentread($T) = AgentReadWrite($T)
@agentwrite($T) = AgentReadWrite($T)
@nextid($T) = 1
if $mortal
# As we start from 1, we empty the reuseable `nr`
# vector (all are reuseable now)
empty!(@readreuseable($T))
end
end
nodes_attrs(sim, $T)[:writeable] = true
end
@eval function finish_write!(sim::$simsymbol, ::Type{$T})
with_logger(sim) do
@debug("<Begin> finish_write!",
agenttype=$T, transition=sim.num_transitions)
end
must_copy_mem = length(@writestate($T)) > length(@readstate($T)) ||
! sim.initialized ||
! $independent
# copy_mem needs collective calls, so if one rank want to
# copy_mem, all must participate
must_copy_mem = MPI.Allreduce(must_copy_mem, |, MPI.COMM_WORLD)
if $mortal
network_changed = fill(false, length(sim.typeinfos.edges_types))
# in writereuseable we have collected all agents that died
# in this iteration
aids = map(nr -> agent_id($typeid, nr), @writereuseable($T))
edges_types = sim.typeinfos.edges_types
# first we remove all the edges, where the agent is in the
# target position. As those edges are stored on the same
# rank as the agent, we can do this locally.
for id in aids
for ET in edges_types
idx = findfirst(x -> x == ET, edges_types)
network_changed[idx] |=
_remove_edges_agent_target!(sim, id, ET)
end
end
# for the edges where we have the died agents on the source
# position we have the agentsontarget dicts on each process.
# So we first collect the ids of all died agents and then
# call remove_edges! for all edges stored in agentsontarget for
# the collected ids.
alldied = $nompi ? aids : join(aids)
if ! isempty(alldied)
for ET in edges_types
idx = findfirst(x -> x == ET, edges_types)
network_changed[idx] |=
_remove_edges_agent_source!(sim, alldied, ET)
end
end
MPI.Allreduce!(network_changed, |, mpi.comm)
for ET in edges_types
idx = findfirst(x -> x == ET, edges_types)
if network_changed[idx]
getproperty(sim, Symbol(ET)).last_change =
sim.num_transitions
end
end
# maybe the state has change, so we must clear the cache
empty!(@agent($T).foreigndied)
end
if ! $stateless && must_copy_mem
if $independent && sim.initialized
memcpy!(@writestate($T), @readstate($T),
length(@readstate($T)) * sizeof($T))
end
if ! isnothing(@windows($T).shmstate)
MPI.free(@windows($T).shmstate)
end
(@windows($T).shmstate, sarr) =
MPI.Win_allocate_shared(Array{$T},
length(@writestate($T)),
mpi.shmcomm)
memcpy!(sarr, @writestate($T),
length(@writestate($T)) * sizeof($T))
MPI.Win_fence(0, @windows($T).shmstate)
@readstate($T) = sarr
# maybe the state has change, so we must clear the cache
empty!(@agent($T).foreignstate)
elseif $stateless
# for stateless T this is a fast operation (25 ns), and
# we need this to detect the number of agents in the
# case that they are immortal (in this case we could use
# the died array, but to avoid code complexity, we always
# ensure that readstate is available
@readstate($T) = fill($T(), length(@writestate($T)))
end
# for the independent case, we can not set died to true directly
# in the transition function, as in the case that the reused id is
# after the id of the agent that add the agent, we will
# call the new agent already in the same iteration.
# So we have no seperate handling for the indepent case for
# the died vector.
if $mortal
if ! isnothing(@windows($T).shmdied)
MPI.free(@windows($T).shmdied)
end
(@windows($T).shmdied, sarr) =
MPI.Win_allocate_shared(Array{Bool},
length(@writedied($T)),
mpi.shmcomm)
memcpy!(sarr, @writedied($T),
length(@writedied($T)) * sizeof(Bool))
MPI.Win_fence(0, @windows($T).shmdied)
@readdied($T) = sarr
end
if ! $stateless && must_copy_mem
@agent($T).shmstate =
[ MPI.Win_shared_query(Array{$T},
@windows($T).shmstate;
rank = i - 1) for i in 1:mpi.shmsize ]
end
if $mortal
@agent($T).shmdied =
[ MPI.Win_shared_query(Array{Bool},
@windows($T).shmdied;
rank = i - 1) for i in 1:mpi.shmsize ]
end
# for the reusable vector, we merge the new reuseable indices
# (from agent died in this transition) with the unused indicies that
# are still in readreuseable.
@readreuseable($T) = [ @readreuseable($T); @writereuseable($T) ]
empty!(@writereuseable($T))
@agent($T).last_change = sim.num_transitions
nodes_attrs(sim, $T)[:writeable] = false
_log_debug(sim, "<End> finish_write!")
nothing
end
# used in copy_simulation!
@eval function copy_shm!(sim, ::Type{$T})
if ! $stateless
(@windows($T).shmstate, sarr) =
MPI.Win_allocate_shared(Array{$T},
length(@readstate($T)),
mpi.shmcomm)
memcpy!(sarr, @readstate($T),
length(@readstate($T)) * sizeof($T))
MPI.Win_fence(0, @windows($T).shmstate)
@readstate($T) = sarr
@agent($T).shmstate =
[ MPI.Win_shared_query(Array{$T},
@windows($T).shmstate;
rank = i - 1) for i in 1:mpi.shmsize ]
end
if $mortal
(@windows($T).shmdied, sarr) =
MPI.Win_allocate_shared(Array{Bool},
length(@readdied($T)),
mpi.shmcomm)
memcpy!(sarr, @readdied($T),
length(@readdied($T)) * sizeof(Bool))
MPI.Win_fence(0, @windows($T).shmdied)
@readdied($T) = sarr
@agent($T).shmdied =
[ MPI.Win_shared_query(Array{Bool},
@windows($T).shmdied;
rank = i - 1) for i in 1:mpi.shmsize ]
end
end
# this is called after the agents where distributed to the different PEs.
# In the process add_agent! is called.
@eval function finish_distribute!(sim::$simsymbol, ::Type{$T})
end
@eval function prepare_read!(sim::$simsymbol,
readable::Vector{DataType},
::Type{$T})
if $multinode
# we check in the function itself, if it's really necessary to
# transmit agentstate, but we need therefore all readable
# edgetypes without the :IgnoreFrom hint
readableET = filter(readable) do r
r in sim.typeinfos.edges_types &&
! has_hint(sim, r, :IgnoreFrom)
end
transmit_agents!(sim, readableET, $T)
end
# we use this as a check that the types are in the read
# vector, and this check should also done in an nompi run
@windows($T).prepared = true
end
# some mpi parts are in prepare_write, as we always use the shared_memory
# mpi calls, even in single process runs.
@eval function finish_read!(sim::$simsymbol, ::Type{$T})
# we use this as a check that the types are in the read
# vector, and this check should also done in an nompi run
@windows($T).prepared = false
end
@eval function agentsonthisrank(sim::$simsymbol, ::Type{$T}, write = false)
max_agents = @agent($T).nextId - 1
if $immortal
@agent($T).nextId - 1
if write
@writestate($T)
else
@readstate($T)
end
else
if write
[ @writestate($T)[i] for i in 1:min(length(@writestate($T)),
max_agents)
if ! @writedied($T)[i] ]
else
[ @readstate($T)[i] for i in 1:min(length(@readstate($T)),
max_agents)
if ! @readdied($T)[i] ]
end
end
end
@eval function mapreduce(sim::$simsymbol, f, op, ::Type{$T}; kwargs...)
with_logger(sim) do
@info "<Begin> mapreduce agents" f op agenttype=$T
end
@mayassert ! sim.intransition """
You can not call mapreduce inside of a transition function."""
emptyval = val4empty(op; kwargs...)
if $immortal
reduced = emptyval
for i in 1:(@agent($T).nextid - 1)
reduced = op(f(@readstate($T)[i]), reduced)
end
else
reduced = emptyval
for i in 1:(@agent($T).nextid - 1)
if ! @readdied($T)[i]
reduced = op(f(@readstate($T)[i]), reduced)
end
end
end
r = if $nompi
reduced
else
mpiop = get(kwargs, :mpiop, op)
MPI.Allreduce(reduced, mpiop, MPI.COMM_WORLD)
end
_log_info(sim, "<End> mapreduce agents")
r
end
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 13457 | export Edge, edgestates, edgestates_iter
export add_edge!, add_edges!, edges
export num_edges, has_edge
export neighborstates, neighborstates_flexible
export neighborstates_iter, neighborstates_flexible_iter
export neighborids, neighborids_iter
export remove_edges!
export all_edges
# For many function declared in this file, the concrete impementation depends
# on the hints of the edge type and the function itself is build via
# the construct_edge_methods function. The declaration here
# are only used for the documentation, that they come with parameters
# improves the experience with tools like LSP.
"""
struct Edge{T}
from::AgentID
state::T
end
An edge between to agents with (optionally) additional state. T can be
also a struct without any field.
The AgentID of the agent at the target of the edge is not a field of
`Edge` itself, since this information is already part of the
containers in which the edges are stored.
See also [`register_edgetype!`](@ref)
"""
struct Edge{T}
from::AgentID
state::T
end
"""
add_edge!(sim, to::AgentID, edge::Edge{T})
Add a single edge to the simulation `sim`. The edges is directed from
the agent with ID `edge.from` (the source) to the agent with ID `to`
(the target).
add_edge!(sim, from::AgentID, to::AgentID, state::T)
Add a single edge to the simulation `sim`. The edge is directed from
the agent with ID `from` (the source) to the agent with ID `to` (the
target) and has the state `state`.
`T` must have been previously registered in the simulation by calling
[`register_edgetype!`](@ref).
See also [`Edge`](@ref) [`register_edgetype!`](@ref) and [`add_edges!`](@ref)
"""
function add_edge!(::Simulation, to::AgentID, edge::Edge) end
function add_edge!(::Simulation, from::AgentID, to::AgentID, state::Edge)
error("""
`add_edge!(sim, from, to, state)` can not be called with a complete edge as state.
If `edge.from == from`, you can use `add_edge!(sim, to, edge)` instead, otherwise you
must extract the state of the edge by adding `.state` to your current `state` argument.
""")
end
function add_edge!(::Simulation, from::AgentID, to::AgentID, state::T) where T
error("add_edge! can not be called with a state of type $T")
end
"""
add_edges!(sim, to::AgentID, edges)
Add multiple `edges` at once to the simulation `sim`, with all edges
are directed to `to`.
`edges` can be any iterable set of agents, or an arbitrary number of
edges as arguments.
See also [`Edge`](@ref) [`register_edgetype!`](@ref) and [`add_edge!`](@ref)
"""
function add_edges!(sim::Simulation, to::AgentID, edges::Vector{Edge{T}}) where T
for e in edges
add_edge!(sim, to, e)
end
nothing
end
function add_edges!(::Simulation, ::AgentID)
nothing
end
function add_edges!(sim::Simulation, to::AgentID, edges::Edge{T}...) where T
for e in edges
add_edge!(sim, to, e)
end
nothing
end
"""
remove_edges!(sim::Simulation, to::AgentID, ::Type{E})
Remove all edges of type `E` where `to` is at the target position.
Can only be called within a transition function, where `E` is in the `write`
argument and also in the `add_existing` list of [`apply!`](@ref).
"""
function remove_edges!(sim::Simulation, to::AgentID, edgetype::Type)
@error "remove_edges! is called for the unregisterted edgetype $(edgetype)"
end
"""
remove_edges!(sim::Simulation, from::AgentID, to::AgentID, ::Type{E})
Removes all edges of type `E` with `from` at the source position
and `to` at the target position of an edge. `remove_edges!` in this
form (with `from` as argument) can only be called if the edge type `E`
does not have the `:IgnoreFrom` hint.
Can also only be called within a transition function, where `E` is in the `write`
argument and also in the `add_existing` list of [`apply!`](@ref).
"""
function remove_edges!(sim::Simulation, from::AgentID, to::AgentID, edgetype::Type)
@error "remove_edges! is called for the unregisterted edgetype $(edgetype)"
end
"""
edges(sim, id::AgentID, ::Type{E})
Returns the edge of type `E` with agent `id` as target if `E` has
the hint :SingleEdge, or a vector of these edges otherwise.
If there is no edge with agent `id` as target, `edges` returns `nothing`.
edges is not defined if `E` has the hint :IgnoreFrom or :Stateless.
See also [`apply!`](@ref), [`neighborids`](@ref),
[`edgestates`](@ref), [`num_edges`](@ref), [`has_edge`](@ref) and
[`neighborstates`](@ref)
"""
function edges(::Simulation, id::AgentID, edgetype::Type) end
"""
neighborids(sim, id::AgentID, ::Type{E})
Returns the ID of the agent on the source of the edge of type `E`
with agent `id` as target if `E` has the hint :SingleEdge, or otherwise
a vector of the IDs of the agents on the source side of those edges.
If there is no edge with agent `id` as target, `neighborids` returns `nothing`.
`neighborids` is not defined if `E` has the hint :IgnoreFrom.
!!! tip
If the edge type `E` does not have the :Stateless or :SingleEdge
hint, `neighborids` allocates memory for the vector of agent
ids. To avoid this allocation, you can use `neighborids_iter`
instead.
See also [`apply!`](@ref), [`edges`](@ref),
[`edgestates`](@ref), [`num_edges`](@ref), [`has_edge`](@ref)
and [`neighborstates`](@ref)
"""
function neighborids(::Simulation, id::AgentID, edgetype::Type) end
"""
neighborids_iter(sim, id::AgentID, ::Type{E})
Returns an iterator of the IDs of the agents on the source side of edges
of type `E` with agent `id` as target.
If there is no edge with agent `id` as target, the function returns `nothing`.
`neighborids` is not defined if `E` has the hint :SingleEdge or :IgnoreFrom.
See also [`apply!`](@ref), [`neighborids`](@ref), [`edges`](@ref),
[`edgestates`](@ref), [`num_edges`](@ref), [`has_edge`](@ref)
and [`neighborstates`](@ref)
"""
function neighborids_iter(::Simulation, id::AgentID, edgetype::Type) end
"""
edgestates(sim, id::AgentID, ::Type{E})
Returns the state of the edge of type `E` with agent `id` as target if `E` has
the hint :SingleEdge, or a vector of these states otherwise.
If there is no edge with agent `id` as target, `edgestates` returns `nothing`.
`edgestates` is not defined if `E` has the hint :Stateless.
!!! tip
If the edge type `E` does not have the :Stateless or :SingleEdge
hint, `edgestates` allocates memory for the vector of states. To
avoid this allocation, you can use `edgestates_iter` instead.
See also [`apply!`](@ref), [`edges`](@ref), [`neighborids`](@ref),
[`num_edges`](@ref), [`has_edge`](@ref) and [`neighborstates`](@ref)
"""
function edgestates(::Simulation, id::AgentID, edgetype::Type) end
"""
edgestates_iter(sim, id::AgentID, ::Type{E})
Returns an iterator of the states of the edges of type `E` with agent
`id` as target.
If there is no edge with agent `id` as target, the function returns
`nothing`.
`edgestates_iter` is not defined if `E` has the hint :Stateless or
:SingleEdge.
See also [`apply!`](@ref), [`edgestates`](@ref), [`edges`](@ref),
[`neighborids`](@ref), [`num_edges`](@ref), [`has_edge`](@ref) and
[`neighborstates`](@ref)
"""
function edgestates_iter(::Simulation, id::AgentID, edgetype::Type) end
"""
neighborstates(sim::Simulation, id::AgentID, ::Type{E}, ::Type{A})
Returns the state of the agent with type `A` on the source of the
edge of type `E` with agent `id` as target if `E` has the hint
:SingleEdge, or a vector of these agent states otherwise.
If there is no edge with agent `id` as target, `neighborstates`
returns `nothing`.
When the agents on the source side of the edges can have different
types, and it is impossible to determine the Type{A} you can use
[`neighborstates_flexible`](@ref) instead.
`neighborstates` is not defined if T has the hint :IgnoreFrom
!!! tip
If the edge type `E` does not have the :SingleEdge hint,
`neighborstates` allocates memory for the vector of agent
states. To avoid this allocation, you can use
`neighborstates_iter` instead.
See also [`apply!`](@ref), [`edges`](@ref), [`neighborids`](@ref),
[`num_edges`](@ref), [`has_edge`](@ref) and [`edgestates`](@ref)
"""
function neighborstates(::Simulation, id::AgentID, edgetype::Type, agenttype::Type) end
"""
neighborstates_iter(sim::Simulation, id::AgentID, ::Type{E}, ::Type{A})
Returns an iterator for the states of the agents with type `A`
on the source of the edges of type `E` with agent `id` as target.
If there is no edge with agent `id` as target, the function returns `nothing`.
When the agents on the source side of the edges can have different
types, and it is impossible to determine the Type{A} you can use
[`neighborstates_flexible_iter`](@ref) instead.
`neighborstates_iter` is not defined if T has the hint :IgnoreFrom or
:SingleEdge.
See also [`neighborstates`](@ref), [`apply!`](@ref), [`edges`](@ref),
[`neighborids`](@ref), [`num_edges`](@ref), [`has_edge`](@ref) and
[`edgestates`](@ref)
"""
function neighborstates_iter(::Simulation, id::AgentID, edgetype::Type, agenttype::Type) end
"""
neighborstates_flexible(sim::Simulation, id::AgentID, ::Type{E})
Returns the state of the agent on the source of the
edge of type `E` with agent `id` as target if `E` has the hint
:SingleEdge, or a vector of these agent states otherwise.
If there is no edge with agent `id` as target, `neighborstates_flexible`
returns `nothing`.
`neighborstates_flexible` is the type instable version of
[`neighborstates`](@ref) and should be only used in the case that the
type of agent can not be determined.
`neighborstates_flexible` is not defined if T has the hint :IgnoreFrom.
!!! tip
If the edge type `E` does not have the :SingleEdge hint,
`neighborstates_flexible` allocates memory for the vector of
agent states. To avoid this allocation, you can use
`neighborstates_flexible_iter` instead.
See also [`apply!`](@ref), [`edges`](@ref), [`neighborids`](@ref),
[`num_edges`](@ref), [`has_edge`](@ref) and [`edgestates`](@ref)
"""
function neighborstates_flexible(sim::Simulation, id::AgentID, edgetype::Type)
nids = neighborids(sim, id, edgetype)
isnothing(nids) ? nothing : map(id -> agentstate_flexible(sim, id), nids)
end
"""
neighborstates_flexible_iter(sim::Simulation, id::AgentID, ::Type{E})
Returns an iterator for the states of the agents on the source of the edges
of type `E` with agent `id` as target.
If there is no edge with agent `id` as target, the function
returns `nothing`.
`neighborstates_flexible_iter` is the type instable version of
[`neighborstates_iter`](@ref) and should be only used in the case that the
type of agent can not be determined.
`neighborstates_flexible_iter` is not defined if T has the hint
:IgnoreFrom or the hint :SingleEdge.
See also [`neighborstates_flexible`](@ref), [`apply!`](@ref),
[`edges`](@ref), [`neighborids`](@ref), [`num_edges`](@ref),
[`has_edge`](@ref) and [`edgestates`](@ref)
"""
function neighborstates_flexible_iter(sim::Simulation, id::AgentID, edgetype::Type)
nids = neighborids(sim, id, edgetype)
if nids === nothing
nothing
else
(agentstate_flexible(sim, nid) for nid in nids)
end
end
"""
num_edges(sim, id::AgentID, ::Type{E})
Returns the number of edges of type `E` with agent `id` as target.
`num_edges` is not defined if T has the hint :SingleEdge
See also [`apply!`](@ref), [`edges`](@ref),
[`neighborids`](@ref), [`edgestates`](@ref), [`has_edge`](@ref)
and [`neighborstates`](@ref)
"""
function num_edges(::Simulation, id::AgentID, edgetype::Type) end
"""
has_edge(sim, id::AgentID, ::Type{E})
Returns true if there is at least one edge of type `E` with agent `id` as
target.
`has_edge` is not defined if T has the :SingleEdge and :SingleType
hints, with the exception that it has also the :IgnoreFrom and
:Stateless hints.
See also [`apply!`](@ref), [`edges`](@ref),
[`neighborids`](@ref), [`edgestates`](@ref), [`num_edges`](@ref)
and [`neighborstates`](@ref)
"""
function has_edge(::Simulation, id::AgentID, edgetype::Type) end
"""
num_edges(sim, ::Type{T}, [sum_ranks=true])
If `all_ranks` is `true` this function retrieves the number of edges of type `T`
of the simulation `sim`. When it is set to `false`, the function will only return the
number of edges of type `T` managed by the process.
"""
function num_edges(sim, t::Type{T}, sum_ranks = true; write = nothing) where T
prepare_read!(sim, [], t)
local_num = if write === nothing
_num_edges(sim, t, ! sim.initialized)
else
_num_edges(sim, t, write)
end
finish_read!(sim, t)
if sum_ranks
MPI.Allreduce(local_num, +, MPI.COMM_WORLD)
else
local_num
end
end
"""
all_edges(sim, ::Type{T}, [all_ranks=true])
This function retrieves a vector of (AgentID, Edge) tuples for all edges of
type T of the simulation `sim`.
The AgentID in the tuple is the target of the edge. The specific form
of the edge in the tuple depends on the hints for type T.
The `all_ranks` argument determines whether to include edges from all
ranks or just the current rank in parallel simulations. When
`all_ranks` is `true`, the function returns a vector of all edges
identifiers across all ranks.
See also [`add_edge!`](@ref) and [`num_edges`](@ref).
"""
function all_edges(sim, edgetype::Type, all_ranks = true)
@error "all_edges is called for the unregisterted edgetype $(edgetype)"
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 3970 | import Base.length
import Base.iterate
# When we iterate over all edges, we have two nested iterators (the outer over
# all the agents, and one over the edges for those agents).
struct IterEdgesState{IT}
agentiter::IT # the outer agent iterator
currentagentid::AgentID # the current agent for the inner edge iterator
nextedgeidx::Int64 # the next edge of in the inner edge iterator
length::Int64
end
struct IterEdgesWrapper{SIM, FT, T}
sim::SIM
read::Bool
field::FT
end
function length(iw::IterEdgesWrapper{SIM, FT, T}) where {SIM, FT, T}
_num_edges(iw.sim, T, ! iw.read)
end
function construct_edges_iter_methods(T::DataType, attr, simsymbol, FT)
ignorefrom = :IgnoreFrom in attr[:hints]
singleedge = :SingleEdge in attr[:hints]
singletype = :SingleType in attr[:hints]
stateless = :Stateless in attr[:hints]
# for whatever reason, we cannot just use the field type in the
# :SingleType case
if singletype
IT = Base.Iterators.Stateful
else
IT = Base.Iterators.Stateful{Base.KeySet{UInt64, FT},
Union{Nothing, Tuple{UInt64, Int64}}}
end
# for the singletype case we can access the type of the agent via AT
if singletype
AT = attr[:target]
end
@eval function edges_iterator(sim::$simsymbol, ::Type{$T}, r::Bool = true)
@assert ! ($stateless && $ignorefrom)
field = r ? @edgeread($T) : @edgewrite($T)
if length(field) == 0
# we can not return nothing, but an empty vector will return nothing when
# iterate is called on it
[]
else
IterEdgesWrapper{$simsymbol, $FT, $T}(sim, r, field)
end
end
@eval function iterate(iw::IterEdgesWrapper{$simsymbol, $FT, $T})
if length(iw.field) == 0
return nothing
end
field = iw.field
ks = keys(field)
# If the agent container is a vector, remove all #undefs
if $singletype
ks = filter(i -> isassigned(field, i), ks)
end
# in the case that no key is left, we also return immediately
if length(ks) == 0
return nothing
end
# create an stateful iterator for the keys (the agentids), which
# is added the the state of the outer iterator
agentiter = Iterators.Stateful(ks)
currentagentid = Iterators.take(agentiter, 1) |> only
len = $singleedge ? 1 : length(field[currentagentid])
iterate(iw, IterEdgesState{$IT}(agentiter, currentagentid, 1, len))
end
@eval function iterate(iw::IterEdgesWrapper{$simsymbol, $FT, $T}, is::IterEdgesState{$IT})
field = iw.field
# innerisvec is false, if the edgetyspe has the hint :SingleEdge
if is.nextedgeidx <= is.length
if $singleedge
return ((is.currentagentid, field[is.currentagentid]),
IterEdgesState{$IT}(is.agentiter,
is.currentagentid,
2,
1))
else
return ((is.currentagentid, field[is.currentagentid][is.nextedgeidx]),
IterEdgesState{$IT}(is.agentiter,
is.currentagentid,
is.nextedgeidx + 1,
is.length))
end
# this code is only reached for is.nextedgeidx > len, which means
# we move on our outer iterator to the next agent and call
# the iterate function recursivly.
elseif isempty(is.agentiter)
return nothing
end
currentagentid = Iterators.take(is.agentiter, 1) |> only
len = $singleedge ? 1 : length(field[currentagentid])
iterate(iw, IterEdgesState{$IT}(is.agentiter, currentagentid, 1, len))
end
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 38022 | import Base.zero
# In the following comment:
# SType stands for the :SingleType hint
# SEdge stands for the :SingleEdge hint
# and
# Ignore stands for the :IgnoreFrom hint
#
# The overall form of the type for the edgefield is the string: A*C(B)}, where
#
# | | A | B | C(B) |
# |-----------------------------+---------------+---------------+-----------|
# | Default | Dict{AgentID, | Edge{$T} | Vector{B} |
# | SType | Vector{ | | B |
# | Stateless & !Ignore | | AgentID | |
# | Ignore & !Stateless | | $T | |
# | Stateless & Ignore & !SEdge | | | Int |
# | Stateless & Ignore & SEdge | | | Bool |
#
# The following table show all the 16 type variante for the container that can be
# constructed following the rules from the table above
#
# | | SType | Stateless | SEdge | Ignore |
# |---------------------------------+-------+-----------+-------+--------|
# | Dict{AgentID, Vector{Edge{$T}}} | | | | |
# | Dict{AgentID, Edge{$T}} | | | x | |
# | Dict{AgentID, Vector{AgentID}} | | x | | |
# | Dict{AgentID, AgentID} | | x | x | |
# | Vector{Vector{Edge{T}}} | x | | | |
# | Vector{Edge{T}} | x | | x | |
# | Vector{Vector{AgentID}} | x | x | | |
# | Vector{AgentID} | x | x | x | |
# | Dict{AgentID, Vector{$T}} | | | | x |
# | Dict{AgentID, $T} | | | x | x |
# | Dict{AgentID, Int64} | | x | | x |
# | Dict{AgentID, Bool} | | x | x | x |
# | Vector{Vector{$T}} | x | | | x |
# | Vector{$T} | x | | x | x |
# | Vector{Int64} | x | x | | x |
# | Vector{Bool} | x | x | x | x |
#
#
# C(B) alone is the type of the container stored per element. We need
# this container type in function as add_agent to construct new container in the
# case that the agent/node doesn't had any incoming edge before. So we
# return also C(B) from the construct_types function.
function construct_types(T, attr::Dict{Symbol, Any})
ignorefrom = :IgnoreFrom in attr[:hints]
singleedge = :SingleEdge in attr[:hints]
singletype = :SingleType in attr[:hints]
stateless = :Stateless in attr[:hints]
A = if singletype
"Vector{"
else
"Dict{AgentID,"
end
B = if stateless
"AgentID"
elseif ignorefrom
"Main.$T"
else
"Edge{Main.$T}"
end
C(B) = if stateless && ignorefrom && singleedge
"Bool"
elseif stateless && ignorefrom
"Int64"
elseif singleedge
B
else
"Vector{$B}"
end
A*C(B)*"}", C(B), B
end
edgefield_type(T, info) = Meta.parse(construct_types(T, info)[1])
edgefield_constructor(T, info) = Meta.parse(construct_types(T, info)[1] * "()")
# storage is used for the edges that must be send to a different rank
# as in the edge we do not store the to-id, we use the Tuple to attach this
# information
function edgestorage_type(T, info)
type_strings = construct_types(T, info)
CE = Meta.parse(type_strings[3]) |> eval
Vector{Vector{Tuple{AgentID, CE}}}
end
# We have some functions that are do only something when some edge hints
# are set and are in this case specialized for the edgetype. Here we define
# the "fallback" functions for the case that no specialized versions are needed.
_check_size!(_, _, _) = nothing
init_field!(_, _) = nothing
show_second_edge_warning = true
function _can_remove_edges(sim, to, T)
@mayassert sim.initialized == false || sim.intransition """
You can call remove_edges! only in the initialization phase (until
`finish_init!` is called) or within a transition function called by
`apply`.
"""
@mayassert begin
! config.check_readable ||
! sim.initialized ||
edge_attrs(sim, T)[:writeable] == true
end """
Edge of $T can not removed, as $T is not in the `write` argument of the transition function.
"""
@mayassert begin
! config.check_readable ||
! sim.initialized ||
edge_attrs(sim, T)[:add_existing] == true
end """
$T must be in the `add_existing` keyword of the transition function.
"""
end
function construct_edge_methods(T::DataType, typeinfos, simsymbol, immortal)
attr = typeinfos.edges_attr[T]
ignorefrom = :IgnoreFrom in attr[:hints]
singleedge = :SingleEdge in attr[:hints]
singletype = :SingleType in attr[:hints]
stateless = :Stateless in attr[:hints]
singletype_size = get(attr, :size, 0)
# FT is an abbrev. for FieldType (the type for the all the edges of a edgetype)
# CT is an abbrev. for ContainerType (the type of the container for the edges
# of a single agent). CE is an abbrev. for ContainerElement (B in the table
# above).
type_strings = construct_types(T, attr)
FT = Meta.parse(type_strings[1]) |> eval
CT = Meta.parse(type_strings[2]) |> eval
CE = Meta.parse(type_strings[3]) |> eval
# we need this when we send the edges via MPI
attr[:containerelement] = CE
# for the singletype case we can access the type of the agent via AT
AT = if singletype
attr[:target]
else
nothing
end
mpiactive = mpi.active
multinode = mpi.size > mpi.shmsize
construct_mpi_edge_methods(T, typeinfos, simsymbol, CE)
construct_edges_iter_methods(T, attr, simsymbol, FT)
#### Functions that helps to write generic versions of the edge functions
#
# The hints can be different when different models are create using
# the same types, therefore we dispatch on $simsymbol
#
# _to2idx is used to convert the AgentID to the AgentNr, in the
# case that the container for the Edges is a Vector (which is the
# case when the :SingleEdge hint is set.
if singletype
@eval _to2idx(_::$simsymbol, to::AgentID, ::Type{$T}) = agent_nr(to)
else
@eval _to2idx(_::$simsymbol, to::AgentID, ::Type{$T}) = to
end
# _valuetostore is used to retrieve the value that should be stored
# from an edge, or the (from, edgestate) combination
if stateless && ignorefrom && singleedge
@eval _valuetostore(_::$simsymbol, edge::Edge{$T}) = true
@eval _valuetostore(_::$simsymbol, from::AgentID, edgestate::$T) = true
elseif ignorefrom
@eval _valuetostore(_::$simsymbol, edge::Edge{$T}) = edge.state
@eval _valuetostore(_::$simsymbol, ::AgentID, edgestate::$T) = edgestate
elseif stateless
@eval _valuetostore(_::$simsymbol, edge::Edge{$T}) = edge.from
@eval _valuetostore(_::$simsymbol, from::AgentID, ::$T) = from
else
@eval _valuetostore(_::$simsymbol, edge::Edge{$T}) = edge
@eval _valuetostore(_::$simsymbol, from::AgentID, edgestate::$T) = Edge(from, edgestate)
end
# We must sometime construct the (per agent) containers, and those
# can be also a primitivetype when the SingleEdge hint is
# set. To have a uniform construction schema, we define zero
# methods also for the other cases, and call the constructor in this
# case.
if !isprimitivetype(CT)
@eval zero(::Type{$CT}) = $CT()
end
@eval _construct_container_func(::Type{$CT}) = () -> zero($CT)
#- init_field!, _check_size! and _check_assigned!
#
# init_field! is (and must be) called, after the field is
# constructed. If the field is a dict, init_field! is a noop, for
# it is a vector with size information (:SingleType with size
# keyword), the vector will be resized and the memory will be
# initialized to zero if necessary (= the container is a bittype).
#
# _check_size! checks for vectors with a flexible size if the vector
# is big enough for the agent that operate on this vector, and increase
# the size if necessary (for other cases it's again a noop).
if singletype
if isbitstype(CT)
#for bitstype we must initialize the new memory
if singletype_size == 0
@eval function _check_size!(field, nr::AgentNr, ::Type{$T})
s = length(field)
if (s < nr)
resize!(field, nr)
Base.securezero!(view(field, s+1:nr))
end
end
else
@eval function init_field!(sim::$simsymbol, ::Type{$T})
resize!(@edgewrite($T), $singletype_size)
Base.securezero!(@edgewrite($T))
end
@eval function _check_size!(_, ::AgentNr, ::Type{$T})
end
end
else
if singletype_size == 0
@eval function _check_size!(field, nr::AgentNr, ::Type{$T})
s = length(field)
if (s < nr)
resize!(field, nr)
end
end
else
@eval init_field!(sim::$simsymbol, ::Type{$T}) =
resize!(@edgewrite($T), $singletype_size)
end
end
else
# in the other case we must also define this method
# to ensure that we don't call an old implementation
# of a previous model with different hints
@eval function _check_size!(_, ::AgentNr, ::Type{$T})
end
@eval function init_field!(sim::$simsymbol, ::Type{$T})
end
end
#- _can_add is used to check for some singleedge cases, if it's allowed
# call add_edge! for the agent with id `to`. This should be only done maximal
# one time, except for the ignorefrom && stateless case, in which we only
# support the has_edge function, and as true && true = true, we allow multiple
# add_edge calls in this case. For the singletype case we can not
# check if add_edge! was already called reliably.
@eval function _can_add(sim, field, to::AgentID, value, ::Type{$T})
@mayassert begin
T = $T
! config.check_readable ||
! sim.initialized ||
edge_attrs(sim, $T)[:writeable] == true
end """
$T must be in the `write` argument of the transition function.
"""
if $singleedge && !$singletype && !($ignorefrom && $stateless)
if haskey(field, to) && value !== nothing
if field[to] === value && ! config.quiet
if show_second_edge_warning
global show_second_edge_warning = false
print("""
An edge of type $T with agent $to
as target was added the second time. Since the value of the edge
(after applying hints like :IgnoreFrom) is identical to that of
the first edge, this can be indented and is allowed.
This warning is only shown once is a Julia session and can be disabled
by calling suppress_warnings(true) after importing Vahana.
""")
end
true
else
false
end
else
true
end
else
true
end
end
#- _get_agent_container / _get_agent_container! unifies
# the access to the field, incl. possible needed steps like
# resizing the underlying vector. The *container version return `nothing`
# in the case, that there is no container for this agent, the *container!
# version constructs an empty container and returns this one.
# The last one should be only used for writing edges like in add_edge! and
# the first one one for read operations like edges
if singletype
@eval function _get_agent_container(sim::$simsymbol,
to::AgentID,
::Type{$T},
field)
nr = _to2idx(sim, to, $T)
@mayassert begin
t = $T
@edge($T).readable || ! config.check_readable
end """
You try to access an edge of type $(t) but the type is not in
the `read` argument of the apply! function.
"""
@mayassert begin
t = $T
at = $(attr[:target])
tnr = type_nr(to)
sim.typeinfos.nodes_id2type[tnr] == $(attr[:target])
end """
The :SingleType hint is set for $t, and the agent type is
specified as $(at).
But the type for the given agent is $(sim.typeinfos.nodes_id2type[tnr]).
"""
_check_size!(field, nr, $T)
@inbounds isassigned(field, Int64(nr)) ? field[nr] : nothing
end
@eval function _get_agent_container!(sim::$simsymbol,
to::AgentID,
::Type{$T},
field)
nr = _to2idx(sim, to, $T)
@mayassert begin
t = $T
at = $(attr[:target])
tnr = type_nr(to)
sim.typeinfos.nodes_id2type[tnr] == $(attr[:target])
end """
The :SingleType hint is set for $t, and the agent type is
specified as $(at).
But the type for the given agent is $(sim.typeinfos.nodes_id2type[tnr]).
"""
_check_size!(field, nr, $T)
if !isassigned(field, Int64(nr))
field[nr] = zero($CT)
end
@inbounds field[nr]
end
else
@eval function _get_agent_container!(sim::$simsymbol,
to::AgentID,
::Type{$T},
field)
get!(_construct_container_func($CT), field, to)
end
@eval function _get_agent_container(sim::$simsymbol, to::AgentID, ::Type{$T}, field)
@mayassert begin
t = $T
@edge($T).readable || ! config.check_readable
end """
You try to access an edge of type $(t) but the type is not in
the `read` argument of the apply! function.
"""
get(field, to, nothing)
end
end
# when all agenttypes are immortal, there is no need to check
# ! sim.model.immortal[type_nr(from)] for every add_edge
if ignorefrom || reduce(&, immortal)
@eval function _push_agentsontarget(sim, from, to, _::Type{$T})
end
else
@eval function _push_agentsontarget(sim, from, to, _::Type{$T})
if ! sim.model.immortal[type_nr(from)]
push!(get!(@agentsontarget($T), from, Vector{AgentID}()), to)
end
end
end
#### The exported functions
#- add_edge!
if stateless && ignorefrom && !singleedge
@eval function add_edge!(sim::$simsymbol, to::AgentID, _::Edge{$T})
@mayassert _can_add(sim, @edgewrite($T), to, nothing, $T)
@mayassert sim.initialized == false || sim.intransition """
You can call add_edge! only in the initialization phase (until
`finish_init!` is called) or within a transition function called by
`apply`.
"""
if $mpiactive && process_nr(to) != mpi.rank
push!(@storage($T)[process_nr(to) + 1], (to, 1))
else
nr = _to2idx(sim, to, $T)
field = @edgewrite($T)
@inbounds field[nr] = _get_agent_container!(sim, to, $T,
field) + 1
end
nothing
end
@eval function add_edge!(sim::$simsymbol, _::AgentID, to::AgentID, _::$T)
@mayassert _can_add(sim, @edgewrite($T), to, nothing, $T)
@mayassert sim.initialized == false || sim.intransition """
You can call add_edge! only in the initialization phase (until
`finish_init!` is called) or within a transition function called by
`apply`.
"""
if $mpiactive && process_nr(to) != mpi.rank
push!(@storage($T)[process_nr(to) + 1], (to, 1))
else
nr = _to2idx(sim, to, $T)
field = @edgewrite($T)
@inbounds field[nr] = _get_agent_container!(sim, to, $T,
field) + 1
end
nothing
end
elseif singleedge
@eval function add_edge!(sim::$simsymbol, to::AgentID, edge::Edge{$T})
@mayassert _can_add(sim, @edgewrite($T), to,
_valuetostore(sim, edge), $T) """
An edge has already been added to the agent with the id $to (and the
edgetype hints containing the :SingleEdge hint).
"""
_push_agentsontarget(sim, edge.from, to, $T)
if $multinode && ! $ignorefrom && node_nr(edge.from) != mpi.node
push!(@edge($T).
accessible[type_nr(edge.from)][process_nr(edge.from) + 1],
edge.from)
end
if $mpiactive && process_nr(to) != mpi.rank
push!(@storage($T)[process_nr(to) + 1],
(to, _valuetostore(sim, edge)))
else
nr = _to2idx(sim, to, $T)
field = @edgewrite($T)
_check_size!(field, nr, $T)
@inbounds field[nr] = _valuetostore(sim, edge)
end
nothing
end
@eval function add_edge!(sim::$simsymbol, from::AgentID,
to::AgentID, edgestate::$T)
@mayassert sim.initialized == false || sim.intransition """
You can call add_edge! only in the initialization phase (until
`finish_init!` is called) or within a transition function called by
`apply`.
"""
@mayassert _can_add(sim, @edgewrite($T), to,
_valuetostore(sim, from, edgestate), $T) """
An edge has already been added to the agent with the id $to (and the
edgetype hints containing the :SingleEdge hint).
"""
_push_agentsontarget(sim, from, to, $T)
if $multinode && ! $ignorefrom && node_nr(from) != mpi.node
push!(@edge($T).
accessible[type_nr(from)][process_nr(from) + 1], from)
end
if $mpiactive && process_nr(to) != mpi.rank
push!(@storage($T)[process_nr(to) + 1],
(to, _valuetostore(sim, from, edgestate)))
else
nr = _to2idx(sim, to, $T)
field = @edgewrite($T)
_check_size!(field, nr, $T)
@inbounds field[nr] = _valuetostore(sim, from, edgestate)
end
nothing
end
else
@eval function add_edge!(sim::$simsymbol, to::AgentID, edge::Edge{$T})
@mayassert _can_add(sim, @edgewrite($T), to, nothing, $T)
@mayassert sim.initialized == false || sim.intransition """
You can call add_edge! only in the initialization phase (until
`finish_init!` is called) or within a transition function called by
`apply`.
"""
_push_agentsontarget(sim, edge.from, to, $T)
if $multinode && ! $ignorefrom && node_nr(edge.from) != mpi.node
push!(@edge($T).
accessible[type_nr(edge.from)][process_nr(edge.from) + 1],
edge.from)
end
if $mpiactive && process_nr(to) != mpi.rank
push!(@storage($T)[process_nr(to) + 1],
(to, _valuetostore(sim, edge)))
else
push!(_get_agent_container!(sim, to, $T, @edgewrite($T)),
_valuetostore(sim, edge))
end
nothing
end
@eval function add_edge!(sim::$simsymbol, from::AgentID, to::AgentID,
edgestate::$T)
@mayassert _can_add(sim, @edgewrite($T), to, nothing, $T)
@mayassert sim.initialized == false || sim.intransition """
You can call add_edge! only in the initialization phase (until
`finish_init!` is called) or within a transition function called by
`apply`.
"""
_push_agentsontarget(sim, from, to, $T)
if $multinode && ! $ignorefrom && node_nr(from) != mpi.node
push!(@edge($T).
accessible[type_nr(from)][process_nr(from) + 1], from)
end
if $mpiactive && process_nr(to) != mpi.rank
push!(@storage($T)[process_nr(to) + 1],
(to, _valuetostore(sim, from, edgestate)))
else
push!(_get_agent_container!(sim, to, $T, @edgewrite($T)),
_valuetostore(sim, from, edgestate))
end
nothing
end
end
#- remove_edges!
if singletype
@eval function remove_edges!(sim::$simsymbol, to::AgentID, ::Type{$T})
_can_remove_edges(sim, to, $T)
if $mpiactive && process_nr(to) != mpi.rank
push!(@removeedges($T)[process_nr(to) + 1], (0, to))
else
nr = _to2idx(sim, to, $T)
field = @edgewrite($T)
_check_size!(field, nr, $T)
@inbounds field[nr] = zero($CT)
end
nothing
end
else
@eval function remove_edges!(sim::$simsymbol, to::AgentID, ::Type{$T})
_can_remove_edges(sim, to, $T)
if $mpiactive && process_nr(to) != mpi.rank
push!(@removeedges($T)[process_nr(to) + 1], (0, to))
else
delete!(@edgewrite($T), to)
end
nothing
end
end
if ! ignorefrom
@eval function remove_edges!(sim::$simsymbol, from::AgentID, to::AgentID,
::Type{$T})
_can_remove_edges(sim, to, $T)
if $mpiactive && process_nr(to) != mpi.rank
push!(@removeedges($T)[process_nr(to) + 1], (from, to))
else
nr = _to2idx(sim, to, $T)
if $singleedge
if ($singletype &&
length(@edgewrite($T)) >= nr) ||
(! $singletype &&
haskey(@edgewrite($T), nr))
if $stateless && @edgewrite($T)[nr] == from
remove_edges!(sim, to, $T)
elseif !$stateless && @edgewrite($T)[nr].from == from
remove_edges!(sim, to, $T)
end
end
else
if ($singletype &&
length(@edgewrite($T)) >= nr &&
isassigned(@edgewrite($T), nr) &&
length(@edgewrite($T)[nr]) > 0) ||
(! $singletype &&
haskey(@edgewrite($T), nr) &&
length(@edgewrite($T)[nr]) > 0)
if $stateless
@edgewrite($T)[nr] = filter(id -> id != from,
@edgewrite($T)[nr])
else
@edgewrite($T)[nr] = filter(e -> e.from != from,
@edgewrite($T)[nr])
end
end
end
end
end
else
@eval function remove_edges!(sim::$simsymbol, from::AgentID, to::AgentID,
::Type{$T})
@assert false """
remove_edges! with a source agent is not defined for edgetypes
with the :IgnoreFrom hint.
"""
end
end
# iterate over all edge containers for the agents on the rank,
# search for edges where on of the agents in the from vector is in
# the source position, and remove those edges.
@eval function _remove_edges_agent_source!(sim::$simsymbol,
from::Vector{AgentID}, ::Type{$T})
# when we don't know where there edges are come from, we can not
# remove them
if $ignorefrom
return false
end
network_changed = false
check_status = config.check_readable
config.check_readable = false
for f in from
if haskey(@agentsontarget($T), f)
network_changed = true
for t in @agentsontarget($T)[f]
remove_edges!(sim, f, t, $T)
end
delete!(@agentsontarget($T), f)
end
end
config.check_readable = check_status
network_changed
end
@eval function init_storage!(sim::$simsymbol, ::Type{$T})
@storage($T) = [ Tuple{AgentID, $CE}[] for _ in 1:mpi.size ]
@removeedges($T) = [ Tuple{AgentID, AgentID}[] for _ in 1:mpi.size ]
end
@eval function prepare_write!(sim::$simsymbol,
read,
add_existing::Bool,
t::Type{$T})
if add_existing
# when we can not read the types that we are writing
# there is no need to copy the elements
if $T in read
@edgewrite($T) = deepcopy(@edgeread($T))
else
@edgewrite($T) = @edgeread($T)
end
else
@edgewrite($T) = $FT()
init_field!(sim, t)
foreach(empty!, @storage($T))
for tnr in 1:length(sim.typeinfos.nodes_types)
for i in 1:mpi.size
empty!(@edge($T).accessible[tnr][i])
end
end
end
edge_attrs(sim, $T)[:writeable] = true
edge_attrs(sim, $T)[:add_existing] = add_existing
end
@eval function prepare_read!(sim::$simsymbol, _::Vector, ::Type{$T})
@edge($T).readable = true
end
@eval function finish_read!(sim::$simsymbol, ::Type{$T})
@edge($T).readable = false
end
# Important: When edges are removed because of dying agents,
# it's allowed that the edgetypes are not in the write argument
# of the apply function, and therefore prepare_write and finish_write
# is not called. Thats okay, as $edgeread = $edgewrite, and
# we update the last_change value when a edge was removed,
# but in the case that in the future additional functionallity
# is added to finish_write, keep this in mind
@eval function finish_write!(sim::$simsymbol, ::Type{$T})
@edgeread($T) = @edgewrite($T)
@edge($T).last_change = sim.num_transitions
edge_attrs(sim, $T)[:writeable] = false
end
@eval function transmit_edges!(sim::$simsymbol, ::Type{$T})
edges_alltoall!(sim, @storage($T), $T)
foreach(empty!, @storage($T))
end
@eval function transmit_remove_edges!(sim::$simsymbol, ::Type{$T})
check_status = config.check_readable
config.check_readable = false
removeedges_alltoall!(sim, @removeedges($T), $T)
foreach(empty!, @removeedges($T))
config.check_readable = check_status
end
# Rules for the edge functions:
# stateless => !mapreduce, !edges, !edgestates
# singledge => !num_edges
# ignorefrom => !edges, !neighborids
#- edges
if !stateless && !ignorefrom
@eval function edges(sim::$simsymbol, to::AgentID, ::Type{$T})
_get_agent_container(sim, to, $T, @edgeread($T))
end
else
@eval function edges(::$simsymbol, ::AgentID, t::Type{$T})
@assert false """
edges is not defined for the hint combination of $t
"""
end
end
#- neighborids
if !ignorefrom
if stateless
@eval function neighborids(sim::$simsymbol, to::AgentID, ::Type{$T})
_get_agent_container(sim, to, $T, @edgeread($T))
end
else
if singleedge
@eval function neighborids(sim::$simsymbol, to::AgentID, ::Type{$T})
ac = _get_agent_container(sim, to, $T, @edgeread($T))
isnothing(ac) ? nothing : ac.from
end
else
@eval function neighborids(sim::$simsymbol, to::AgentID, ::Type{$T})
ac = _get_agent_container(sim, to, $T, @edgeread($T))
isnothing(ac) ? nothing : map(e -> e.from, ac)
end
end
end
else
@eval function neighborids(::$simsymbol, ::AgentID, t::Type{$T})
@assert false """
neighborids is not defined for the hint combination of $t
"""
end
end
#- neighborids_iter
if singleedge || ignorefrom
@eval function neighborids_iter(sim::$simsymbol, to::AgentID, ::Type{$T})
@assert false """
neighborids_iter is not defined for edgetypes with the
:SingleEdge or :IgnoreFrom hint
"""
end
elseif stateless
@eval function neighborids_iter(sim::$simsymbol, to::AgentID, ::Type{$T})
_get_agent_container(sim, to, $T, @edgeread($T))
end
else
@eval function neighborids_iter(sim::$simsymbol, to::AgentID, ::Type{$T})
ac = _get_agent_container(sim, to, $T, @edgeread($T))
isnothing(ac) ? nothing : (e.from for e in ac)
end
end
#- neighborstates
if singleedge
@eval function neighborstates(sim::$simsymbol, id::AgentID,
edgetype::Type{$T}, agenttype::Type)
nid = neighborids(sim, id, edgetype)
isnothing(nid) ? nothing : agentstate(sim, nid, agenttype)
end
else
@eval function neighborstates(sim::$simsymbol, id::AgentID,
edgetype::Type{$T}, agenttype::Type)
nids = neighborids(sim, id, edgetype)
if nids === nothing
nothing
else
map(nid -> agentstate(sim, nid, agenttype), nids)
end
end
end
#- neighborstates_iter
if singleedge || ignorefrom
@eval function neighborstates_iter(sim::$simsymbol, id::AgentID,
edgetype::Type{$T}, agenttype::Type)
@assert false """
neighborstates_iter is not defined for edgetypes with the
:SingleEdge or :IgnoreFrom hint
"""
end
else
@eval function neighborstates_iter(sim::$simsymbol, id::AgentID,
edgetype::Type{$T}, agenttype::Type)
nids = neighborids(sim, id, edgetype)
if nids === nothing
nothing
else
(agentstate(sim, nid, agenttype) for nid in nids)
end
end
end
#- edgestates
if !stateless
if ignorefrom
@eval function edgestates(sim::$simsymbol, to::AgentID, ::Type{$T})
_get_agent_container(sim, to, $T, @edgeread($T))
end
else
if singleedge
@eval function edgestates(sim::$simsymbol, to::AgentID, ::Type{$T})
ac = _get_agent_container(sim, to, $T, @edgeread($T))
isnothing(ac) ? nothing : ac.state
end
else
@eval function edgestates(sim::$simsymbol, to::AgentID, ::Type{$T})
ac = _get_agent_container(sim, to, $T, @edgeread($T))
isnothing(ac) ? nothing : map(e -> e.state, ac)
end
end
end
else
@eval function edgestates(::$simsymbol, ::AgentID, t::Type{$T})
@assert false """
edgestates is not defined for the hint combination of $t
"""
end
end
#- edgestate_iter
if singleedge || stateless
@eval function edgestates_iter(sim::$simsymbol, to::AgentID, ::Type{$T})
@assert false """
edgestates_iter is not defined for edgetypes with the
:SingleEdge or :Stateless hint
"""
end
elseif ignorefrom
@eval function edgestates_iter(sim::$simsymbol, to::AgentID, ::Type{$T})
_get_agent_container(sim, to, $T, @edgeread($T))
end
else
@eval function edgestates_iter(sim::$simsymbol, to::AgentID, ::Type{$T})
ac = _get_agent_container(sim, to, $T, @edgeread($T))
isnothing(ac) ? nothing : (e.state for e in ac)
end
end
#- num_edges
if !singleedge
if ignorefrom && stateless
@eval function num_edges(sim::$simsymbol, to::AgentID, ::Type{$T})
n = _get_agent_container(sim, to, $T, @edgeread($T))
isnothing(n) ? 0 : n
end
else
@eval function num_edges(sim::$simsymbol, to::AgentID, ::Type{$T})
ac = _get_agent_container(sim, to, $T, @edgeread($T))
isnothing(ac) ? 0 : length(ac)
end
end
else
@eval function num_edges(::$simsymbol, ::AgentID, t::Type{$T})
@assert false """
num_edges is not defined for the hint combination of $t
"""
end
end
#- has_edge
if ignorefrom && stateless
@eval function has_edge(sim::$simsymbol, to::AgentID, ::Type{$T})
ac = _get_agent_container(sim, to, $T, @edgeread($T))
isnothing(ac) || ac == 0 ? false : true
end
elseif !singleedge
@eval function has_edge(sim::$simsymbol, to::AgentID, t::Type{$T})
num_edges(sim,to, t) >= 1
end
elseif !singletype
@eval function has_edge(sim::$simsymbol, to::AgentID, ::Type{$T})
haskey(@edgeread($T), to)
end
else
@eval function has_edge(::$simsymbol, ::AgentID, t::Type{$T})
@assert false """
has_edge is not defined for the hint combination of $t
"""
end
end
# _remove_edges (called from Vahana itself to remove the edges of
# died agents). returns true when edges where removed (and the network
# changed)
if singletype
@eval function _remove_edges_agent_target!(sim::$simsymbol, to::AgentID, ::Type{$T})
if type_of(sim, to) == $AT
nr = agent_nr(to)
if length(@edgewrite($T)) >= nr
@edgewrite($T)[nr] = zero($CT)
true
else
false
end
else
false
end
end
else
@eval function _remove_edges_agent_target!(sim::$simsymbol, to::AgentID, ::Type{$T})
if haskey(@edgewrite($T), to)
delete!(@edgewrite($T), to)
true
else
false
end
end
end
#- mapreduce incl. helper functions
if singletype
@eval _removeundef(sim::$simsymbol, ::Type{$T}) = edges -> begin
[ @inbounds edges[i] for i=1:length(edges) if isassigned(edges, i)]
end
else
@eval _removeundef(sim::$simsymbol, ::Type{$T}) = edges -> edges
end
if ignorefrom && stateless
@eval function _num_edges(sim::$simsymbol, ::Type{$T}, write = false)
field = write ? @edgewrite($T) : @edgeread($T)
if length(field) == 0
return 0
end
mapreduce(id -> field[id], +, keys(field))
end
elseif singleedge
@eval function _num_edges(sim::$simsymbol, t::Type{$T}, write = false)
field = write ? @edgewrite($T) : @edgeread($T)
# TODO: performance improvement with _countundef?
length(_removeundef(sim, t)(field))
end
else
if !singletype
@eval function _num_edges(sim::$simsymbol, ::Type{$T}, write = false)
field = write ? @edgewrite($T) : @edgeread($T)
if length(field) == 0
return 0
end
mapreduce(id -> length(field[id]), +, keys(field))
end
else
@eval function _num_edges(sim::$simsymbol, ::Type{$T}, write = false)
field = write ? @edgewrite($T) : @edgeread($T)
if length(field) == 0
return 0
end
n = 0
for i in 1:length(field)
if isassigned(field, i)
n += length(field[i])
end
end
n
end
end
end
#- mapreduce
if ! stateless
@eval function mapreduce(sim::$simsymbol, f, op, t::Type{$T}; kwargs...)
with_logger(sim) do
@info "<Begin> mapreduce edges" f op edgetype=$T
end
emptyval = val4empty(op; kwargs...)
reduced = emptyval
for e in edges_iterator(sim, $T)
if $ignorefrom
reduced = op(f(e[2]), reduced)
else
reduced = op(f(e[2].state), reduced)
end
end
mpiop = get(kwargs, :mpiop, op)
r = MPI.Allreduce(reduced, mpiop, MPI.COMM_WORLD)
_log_info(sim, "<End> mapreduce edges")
r
end
else
@eval function mapreduce(::$simsymbol, f, op, t::Type{$T}; kwargs...)
@assert false """
mapreduce is not defined for the hint combination of $t
"""
end
end
###
@eval function all_edges(sim, t::Type{$T}, all_ranks = true)
if num_edges(sim, $T) == 0
return []
end
prepare_read!(sim, [], $T)
# when we use collect on edges_iterator, we loose
# for whatever reason the type information we need to call join
c = Tuple{AgentID, $CE}[]
for e in edges_iterator(sim, $T, sim.initialized)
push!(c, e)
end
finish_read!(sim, $T)
if all_ranks && mpi.active
join(c)
else
c
end
end
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 2438 | export set_global!, get_global, push_global!, modify_global!
"""
get_global(sim::Simulation, name)
Returns the value of the field `name` of the `globals` struct for simulation `sim`.
See also [`create_simulation`](@ref), [`set_global!`](@ref) and [`push_global!`](@ref)
"""
get_global(sim, name) = getfield(sim.globals, name)
"""
set_global!(sim::Simulation, name, value)
Set the value of the field `name` of the `globals` struct for simulation `sim`.
In parallel simulations, `set_global!` must be called on all
processes, and with identical `value` across all processes.
`set_global!` must not be called within a transition function.
See also [`create_simulation`](@ref), [`mapreduce`](@ref),
[`modify_global!`](@ref) [`push_global!`](@ref) and
[`get_global`](@ref)
"""
function set_global!(sim, name, value)
sim.globals_last_change = sim.num_transitions - 1
setfield!(sim.globals, name, value)
end
"""
modify_global!(sim::Simulation, name, f)
Modify the value of the `name` field of the `globals` structure for the
simulation `sim` using the `f` function, which receives the current value as an
argument.
This is a combination of [`set_global!`](@ref) and [`get_global`](@ref):
`set_global!(sim, name, f(get_global(sim, name)))`.
`modify_global!` must not be called within a transition function.
In parallel simulations, `push_global!` must be called on all
processes, and with identical `value` across all processes.
See also [`create_simulation`](@ref), [`mapreduce`](@ref),
[`set_global!`](@ref) [`push_global!`](@ref) and
[`get_global`](@ref)
"""
function modify_global!(sim, name, f)
set_global!(sim, name, f(get_global(sim, name)))
end
"""
push_global!(sim::Simulation, name, value)
In the case that a field of the `globals` struct from the Simulation
constructor is a vector (e.g. for time series data), `push_global!` can
be used to add a value to this vector, instead of writing
`set_global!(sim, name, push!(get_global(sim, name), value)`.
In parallel simulations, `push_global!` must be called on all
processes, and with identical `value` across all processes.
`push_global!` must not be called within a transition function.
See also [`create_model`](@ref), [`mapreduce`](@ref), [`set_global!`](@ref) and
[`get_global`](@ref)
"""
function push_global!(sim, name, value)
sim.globals_last_change = sim.num_transitions - 1
push!(getfield(sim.globals, name), value)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 10120 | export add_graph!
export vahanagraph, vahanasimplegraph
import Graphs:
Graphs, edgetype, has_vertex, inneighbors, ne, nv, outneighbors, vertices, is_directed
import Base:
show, eltype
"""
add_graph!(sim::Simulation, graph, agent_constructor, edge_constructor) -> Vector{AgentID}
Adds a `graph` from the Graphs.jl package to `sim`, incl. all vertices
of `graph` as new agents.
`graph` must be a Graphs.Graph or a Graphs.DiGraph.
For each vertix of `graph` the `agent_constructor` function is called, with
the Graphs.vertix as argument. For each edge of `graph` the
`edge_constructor` function is called, with the Graphs.edge as argument.
The agent types of agents created by the `agent_constructor` must be
already registered via [`register_agenttype!`](@ref) and vis a vis the edge
type via [`register_edgetype!`](@ref).
!!! info
add_graph! is only available when the Graphs.jl package is imported
by the model implementation.
Returns a vector with the IDs of the created agents.
"""
function add_graph!(sim::Simulation, graph, agent_constructor, edge_constructor)
with_logger(sim) do
@info "<Begin> add_graph!"
end
agents = add_agents!(sim,
[ agent_constructor(v) for v in Graphs.vertices(graph) ])
for e in Graphs.edges(graph)
add_edge!(sim,
agents[Graphs.src(e)],
agents[Graphs.dst(e)],
edge_constructor(e))
if !Graphs.is_directed(graph)
add_edge!(sim,
agents[Graphs.dst(e)],
agents[Graphs.src(e)],
edge_constructor(e))
end
end
_log_info(sim, "<End> add_graph!")
agents
end
######################################## VahanaSimpleGraph
# VahanaSimpleGraph is a concrete implementation
# of an Graphs.AbstractSimpleGraph. We need this for Metis,
# as it depends on the AbstractSimpleGraph structure instead
# on the official AbstractGraph API.
struct VahanaSimpleGraph <: Graphs.AbstractSimpleGraph{Integer}
sim::Simulation
agenttypes::Vector{DataType}
networks::Vector{DataType}
g2v::Vector{AgentID}
v2g::Dict{AgentID, Int64}
# for the AbstractSimpleGraph interface
vertices::UnitRange{Integer}
fadjlist::Vector{Vector{Integer}}
ne::Integer
end
# like vahanagraph, only for the AbstractSimpleGraph, see also
# the comment of VahanaSimpleGraph above
"""
vahanasimplegraph(sim::Simulation; [agenttypes::Vector{DataType}, edgetypes::Vector{DataType}, show_ignorefrom_warning = true])
Creates a subgraph with nodes for all agents that have one of the
`agenttypes` types, and all edges that have one of the `edgetypes`
types and whose both adjacent node types are in `agenttypes`.
The default values for `agenttypes` and `edgetypes` are all registered
agents/edgetypes (see [`register_agenttype!`](@ref) and
[`register_edgetype!`](@ref)).
This subgraphs implements the AbstractSimpleGraph interface from the
Graphs.jl package.
The edge types must not have the :IgnoreFrom property. If there are
edge types with this property in the `edgetypes` vector, a warning will
be displayed and these edges will be ignored. The warning can be
suppressed by setting `show_ignorefrom_warning` to false.
!!! warning
The AbstractGraph interface allows multiple edges between
two nodes, but some function (e.g. those that convert the graph
into a binary (sparse)matrix can produce undefined results
for those graphs. So use this function with care.
"""
function vahanasimplegraph(sim::Simulation;
agenttypes::Vector{DataType} = sim.typeinfos.nodes_types,
edgetypes::Vector{DataType} = sim.typeinfos.edges_types,
show_ignorefrom_warning = true)
g2v = Vector{AgentID}()
v2g = Dict{AgentID, Int64}()
nv = 0
for t in agenttypes
for id in 1:length(readstate(sim, t))
if length(readdied(sim, t)) == 0 || readdied(sim, t)[id] == false
nv += 1
aid = agent_id(sim, AgentNr(id), t)
push!(g2v, aid)
push!(v2g, aid => nv)
end
end
end
fadjlist = [ Vector{Integer}() for _ in 1:nv ]
ne = 0
for t in edgetypes
if has_hint(sim, t, :IgnoreFrom)
if show_ignorefrom_warning
printstyled("""
Edgetype $t has the :IgnoreFrom hint, therefore edges of this
type can not added those edges to the created subgraph
"""; color = :red)
end
continue
end
for (to, e) in edges_iterator(sim, t)
if has_hint(sim, t, :Stateless)
fid = get(v2g, e, nothing)
else
fid = get(v2g, e.from, nothing)
end
tid = get(v2g, to, nothing)
if fid !== nothing && tid !== nothing
push!(fadjlist[fid], tid)
ne += 1
end
end
end
VahanaSimpleGraph(sim, agenttypes, edgetypes, g2v, v2g, 1:nv, fadjlist, ne)
end
### AbstractGraph interface for VahanaSimpleGraph
eltype(_::VahanaSimpleGraph) = Int64
edgetype(vg::VahanaSimpleGraph) = Graphs.SimpleEdge{eltype(vg)}
is_directed(::VahanaSimpleGraph) = true
is_directed(::Type{VahanaSimpleGraph}) = true
Base.show(io::IO, _::MIME"text/plain", vg::VahanaSimpleGraph) =
println(io, "VahanaSimpleGraph of $(vg.sim.name) for {$(vg.agenttypes), $(vg.networks)} {$(nv(vg)), $(ne(vg))}")
######################################## VahanaGraph
mutable struct VahanaGraph <: Graphs.AbstractGraph{Int64}
sim
agenttypes::Vector{DataType}
edgetypes::Vector{DataType}
g2v::Vector{AgentID}
v2g::Dict{AgentID, Int64}
edges::Vector{Graphs.Edge}
edgetypeidx::Vector{Int64}
end
# SingleType not supported (und IgnoreFrom sowieso nicht)
"""
vahanagraph(sim::Simulation; [agenttypes::Vector{DataType}, edgetypes::Vector{DataType}, show_ignorefrom_warning = true, drop_multiedges = false])
Creates a subgraph with nodes for all agents that have one of the
`agenttypes` types, and all edges that have one of the `edgetypes`
types and whose both adjacent agents have are of a type in `agenttypes`.
The default values for `agenttypes` and `edgetypes` are all registered
agents/edgetypes (see [`register_agenttype!`](@ref) and
[`register_edgetype!`](@ref)).
This subgraphs implements the AbstractGraph interface from the
Graphs.jl package, so that e.g. GraphMakie can be used to visualize
the subgraph. See also [`create_graphplot`](@ref).
The AbstractGraph interface allows multiple edges between two nodes,
but some functions (e.g. those that convert the graph to a binary
(sparse) matrix) may produce undefined results for these graphs,
e.g. when graphplot is called from GraphMakie.jl. If the keyword
`drop_multiedges` is true and there are multiple edges, only the edge
of the type that is first in the edgetypes vector is added to the
generated graph.
The edge types must not have the :IgnoreFrom property. If there are
edge types with this property in the `edgetypes` vector, a warning will
be displayed and these edges will be ignored. The warning can be
suppressed by setting `show_ignorefrom_warning` to false.
"""
function vahanagraph(sim;
agenttypes::Vector{DataType} = sim.typeinfos.nodes_types,
edgetypes::Vector{DataType} = sim.typeinfos.edges_types,
show_ignorefrom_warning = true,
drop_multiedges = false)
g2v = Vector{AgentID}()
v2g = Dict{AgentID, Int64}()
edgetype = Vector{Int64}()
existing = Set{Tuple{AgentID, AgentID}}()
nv = 0
for T in agenttypes
for id in 1:length(readstate(sim, T))
if length(readdied(sim, T)) == 0 || readdied(sim, T)[id] == false
nv += 1
aid = agent_id(sim, AgentNr(id), T)
push!(g2v, aid)
push!(v2g, aid => nv)
end
end
end
edges = Vector{Graphs.Edge}()
edgetypeidx = 1
for T in edgetypes
if has_hint(sim, T, :IgnoreFrom)
if show_ignorefrom_warning
printstyled("""
Edgetype $T has the :IgnoreFrom hint, therefore edges of this
type can not added those edges to the created subgraph
"""; color = :red)
end
continue
end
for (to, e) in edges_iterator(sim, T)
f = get(v2g, hasproperty(e, :from) ? e.from : e, nothing)
t = get(v2g, to, nothing)
if f !== nothing && t !== nothing
if (f, t) in existing && drop_multiedges
println("Edge $e to agent $(string(to, base=16)) will not be shown")
else
if drop_multiedges
push!(existing, (f, t))
end
push!(edges, Graphs.Edge(f, t))
push!(edgetype, edgetypeidx)
end
end
end
edgetypeidx += 1
end
VahanaGraph(sim, agenttypes, edgetypes, g2v, v2g, edges, edgetype)
end
### AbstractGraph interface for VahanaGraph
Graphs.edges(vg::VahanaGraph) = vg.edges
Base.eltype(::VahanaGraph) = Int64
edgetype(vg::VahanaGraph) = Graphs.SimpleEdge{eltype(vg)}
Graphs.has_edge(vg::VahanaGraph, s, d) = Graphs.Edge(s, d) in vg.edges
has_vertex(vg::VahanaGraph, v) = v <= length(vg.g2v)
inneighbors(vg::VahanaGraph, v) =
map(e -> e.src, filter(e -> e.dst == v, vg.edges)) |> unique
ne(vg::VahanaGraph) = length(vg.edges)
nv(vg::VahanaGraph) = length(vg.g2v)
outneighbors(vg::VahanaGraph, v) =
map(e -> e.dst, filter(e -> e.src == v, vg.edges)) |> unique
vertices(vg::VahanaGraph) = 1:length(vg.g2v)
is_directed(::VahanaGraph) = true
is_directed(::Type{VahanaGraph}) = true
Base.show(io::IO, mime::MIME"text/plain", vg::VahanaGraph) =
println(io, "VahanaGraph of $(vg.sim.name) for {$(vg.agenttypes), $(vg.edgetypes)} {$(nv(vg)), $(ne(vg))}")
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 55435 | using MPI, HDF5
import NamedTupleTools: ntfromstruct, structfromnt
import Dates: format, now
export create_h5file!, close_h5file!
export write_globals, write_agents, write_edges, write_snapshot
export read_params, read_globals, read_agents!, read_edges!, read_snapshot!
export read_agents, read_edges
export list_snapshots
export create_namedtuple_converter, create_enum_converter
export write_metadata, read_metadata, write_sim_metadata, read_sim_metadata
# hdf5 does not allow to store (unnamed) tuples, but the CartesianIndex
# are using those. The Pos2D/3D types can be used to add a Cell position
# to an agent state, with automatical conversion from an Cartesianindex.
import Base.convert
import HDF5.hdf5_type_id
"""
create_enum_converter()
The HDF5.jl library does not support Enums as fields of structs that
should be stored. This function add this support but as this involves
type piracy, this support must be enabled explicitly.
"""
function create_enum_converter()
@eval hdf5_type_id(::Type{T}, ::Val{false}) where {I, T <: Enum{I}} = hdf5_type_id(I)
@eval convert(::Type{T}, i::Int32) where { T <: Enum } = T(i)
end
# import Base.hash
# hash(model::Model) = hash(model.types.edges_attr) +
# hash(model.types.edges_types) +
# hash(model.types.nodes_attr) +
# hash(model.types.nodes_types) +
# hash(model.types.nodes_type2id)
transition_str(sim) = "t_$(sim.num_transitions-1)"
parallel_write() = HDF5.has_parallel() && mpi.active
mpio_mode() = parallel_write() ? Dict(:dxpl_mpio => :collective) : Dict()
# since fileformat 2, empty_array and last_change starts with an _
empty_array_string(fids) = attrs(fids[1])["fileformat"] == 1 ?
"empty_array" : "_empty_array"
last_change_string(fids) = attrs(fids[1])["fileformat"] == 1 ?
"last_change" : "_last_change"
# in the case that write_metadata is called before the file is created
# we store the information in the vector, so that write_metadata
# can be also called before the simulation is initialized.
_preinit_meta = Tuple{Union{Symbol, DataType}, Symbol, Symbol, Any}[]
# the same for the simulation
_preinit_meta_sim = Tuple{Symbol, Any}[]
"""
create_h5file!(sim::Simulation, [filename = sim.filename; overwrite = sim.overwrite_file])
The canonical way to create an HDF5 file is to call one of the
`write_` functions like [`write_snapshot`](@ref). If `sim` does not
already have an HDF5 file attached, such a file will then be created
automatically using the filename specified as keyword in
[`create_simulation`](@ref) or, if this keyword was not given, the
model name. But sometime it can be useful to control this manually,
e.g. after a call to [`copy_simulation`](@ref).
The `filename` argument can be used to specify a filename other than
`sim.filename`. If `overwrite` is true, existing files with this name
will be overwritten. If it is false, the filename is automatically
extended by an increasing 6-digit number, so that existing files are
not overwritten.
By default, the files are created in an `h5` subfolder, and this is
created in the current working directory. However, the path can also be
set with the function `set_hdf5_path`.
In the case that an HDF5 file was already created for the simulation
`sim`, this will be closed.
`create_h5file!` can be only called after [`finish_init!`](@ref)
See also [`close_h5file!`](@ref), [`write_agents`](@ref),
[`write_edges`](@ref), [`write_globals`](@ref),
[`read_agents!`](@ref), [`read_edges!`](@ref), [`read_globals`](@ref),
[`read_snapshot!`](@ref) and [`list_snapshots`](@ref)
"""
function create_h5file!(sim::Simulation, filename = sim.filename; overwrite = sim.overwrite_file)
#in the case that the simulation is already attached to a h5file, we relase it first
close_h5file!(sim)
@assert sim.initialized "You can only write initialized simulations"
if endswith(filename, ".h5")
filename = filename[1, end-3]
end
filename = if config.hdf5_path !== nothing
mkpath(config.hdf5_path) * "/" * filename
else
mkpath("h5") * "/" * filename
end
if ! overwrite
filename = add_number_to_file(filename)
# to avoid that rank 0 creates a file before other ranks check this
MPI.Barrier(MPI.COMM_WORLD)
end
fid = if parallel_write()
_log_info(sim, "Create hdf5 file in parallel mode")
filename = filename * ".h5"
rm(filename; force = true)
HDF5.h5open(filename, "w", mpi.comm, MPI.Info())
else
_log_info(sim, "Create hdf5 file without parallel mode")
filename = if mpi.active
filename * "_" * string(mpi.rank) * ".h5"
else
filename * ".h5"
end
rm(filename; force = true)
HDF5.h5open(filename, "w")
end
sim.h5file = fid
# attrs(fid)["modelhash"] = hash(sim.model)
# @info "wrote hash" attrs(fid)["modelhash"] hash(sim.model)
attrs(fid)["fileformat"] = 2
attrs(fid)["mpisize"] = mpi.size
attrs(fid)["mpirank"] = mpi.rank
attrs(fid)["HDF5parallel"] = parallel_write()
attrs(fid)["initialized"] = sim.initialized
attrs(fid)["last_snapshot"] = -1
# we use this to attach metadata to a simulation
mid = create_group(fid, "_meta")
attrs(mid)["simulation_name"] = sim.name
attrs(mid)["model_name"] = sim.model.name
attrs(mid)["date"] = Dates.format(Dates.now(), "yyyy-mm-dd HH:MM:SS")
pid = create_group(fid, "params")
create_group(pid, "_meta")
# See comment in write_globals.
eid = create_group(pid, "_empty_array")
if sim.params !== nothing
for k in fieldnames(typeof(sim.params))
field = getfield(sim.params, k)
if typeof(field) <: Array
if length(field) > 0
pid[string(k)] = field
attrs(pid[string(k)])["array"] = true
else
attrs(eid)[string(k)] = true
end
else
pid[string(k)] = [ field ]
attrs(pid[string(k)])["array"] = false
end
end
end
gid = create_group(fid, "globals")
create_group(gid, "_meta")
# # we create a group for each global field so that it's possible
# #
# if sim.globals !== nothing
# for k in fieldnames(typeof(sim.globals))
# create_group(gid, k)
# end
# end
rid = create_group(fid, "rasters")
_log_time(sim, "write rasters") do
for raster in keys(sim.rasters)
rid[string(raster)] = sim.rasters[raster]
end
end
aid = create_group(fid, "agents")
# also here we have the problem that the hdf5 library doesn't like
# vectors of size 0 in parallel mode and we must track those.
# The group have a subgroup for each transition, and this subgroup
# the agent types as attributes with a boolean value.
create_group(aid, "_empty_array")
foreach(sim.typeinfos.nodes_types) do T
tid = create_group(aid, string(T))
attrs(tid)[":Immortal"] = has_hint(sim, T, :Immortal, :Agent)
create_group(tid, "_meta")
end
eid = create_group(fid, "edges")
# see comment for agent
create_group(eid, "_empty_array")
foreach(sim.typeinfos.edges_types) do T
tid = create_group(eid, string(T))
attrs(tid)[":Stateless"] = has_hint(sim, T, :Stateless)
attrs(tid)[":IgnoreFrom"] = has_hint(sim, T, :IgnoreFrom)
attrs(tid)[":SingleEdge"] = has_hint(sim, T, :SingleEdge)
attrs(tid)[":SingleType"] =
has_hint(sim, T, :SingleType)
attrs(tid)[":IgnoreSourceState"] =
has_hint(sim, T, :IgnoreSourceState)
create_group(tid, "_meta")
end
create_group(fid, "snapshots")
if mpi.rank == 0
MPI.Bcast!(Ref(length(_preinit_meta)), MPI.COMM_WORLD)
else
len = Ref{Int}()
MPI.Bcast!(len, MPI.COMM_WORLD)
if mpi.rank == 1
@assert length(_preinit_meta) == len[] """
You must call write_metadata always on all ranks!
"""
end
end
for (type, field, key, value) in _preinit_meta
write_metadata(sim, type, field, key, value)
end
empty!(_preinit_meta)
if mpi.rank == 0
MPI.Bcast!(Ref(length(_preinit_meta_sim)), MPI.COMM_WORLD)
else
len = Ref{Int}()
MPI.Bcast!(len, MPI.COMM_WORLD)
if mpi.rank == 1
@assert length(_preinit_meta_sim) == len[] """
You must call write_sim_metadata always on all ranks!
"""
end
end
for (key, value) in _preinit_meta_sim
write_sim_metadata(sim, key, value)
end
empty!(_preinit_meta_sim)
fid
end
"""
close_h5file!(sim::Simulation)
Closes the HDF5 file attached to the simulation `sim`.
Be aware that a following call to one of the `write_` functions like
[`write_snapshot`](@ref) will automatically create a new file and,
depending on the `overwrite_file` argument of
[`create_simulation`](@ref) also overwrites to closed file.
"""
function close_h5file!(sim::Simulation)
if sim.h5file === nothing
return
end
_log_time(sim, "close h5file") do
close(sim.h5file)
end
sim.h5file = nothing
nothing
end
"""
write_globals(sim::Simulation, [fields])
Writes the current global values to the attached HDF5 file. If only a
subset of the fields is to be written, this subset can be specified
via the optional `fields` argument.
"""
function write_globals(sim::Simulation,
fields = sim.globals === nothing ?
nothing : fieldnames(typeof(sim.globals)))
if sim.h5file === nothing
create_h5file!(sim)
end
if fields === nothing
return
end
lcstr = last_change_string([sim.h5file])
gid = sim.h5file["globals"]
if haskey(HDF5.attributes(gid), lcstr) &&
sim.globals_last_change == attrs(gid)[lcstr]
return
end
attrs(gid)[lcstr] = sim.globals_last_change
_log_time(sim, "write globals") do
t = transition_str(sim)
tid = create_group(gid, t)
# for whatever reason parallel mpi does not like to write (and read)
# nothing and throws a "unable to modify constant message"
# in this case. Even worse, we can not access attributes of the emtpy
# dataset. So we need an additional group to store this information.
# Don't know what to say about this.
eid = create_group(tid, "_empty_array")
for k in fieldnames(typeof(sim.globals))
if k in fields
field = getfield(sim.globals, k)
if typeof(field) <: Array
if length(field) > 0
tid[string(k)] = field
attrs(tid[string(k)])["array"] = true
else
attrs(eid)[string(k)] = true
end
else
tid[string(k)] = [ field ]
attrs(tid[string(k)])["array"] = false
end
end
end
end
flush(sim.h5file)
nothing
end
function new_dset(gid, name, T, sum_size, data, create_datatype = true)
dt = if create_datatype
HDF5.Datatype(HDF5.hdf5_type_id(T))
else
T
end
# We have seperate files, so we don't need the size of all agents/edges
# but only the size of the array we want to write into this file
if ! parallel_write()
sum_size = length(data)
end
ds = if create_datatype
dataspace((sum_size,))
else
sum_size
end
if config.compression_level == 0 ||
(parallel_write() && config.no_parallel_compression)
create_dataset(gid, name, dt, ds; mpio_mode()...)
else
chunk_size = if length(data) == 0
1
else
HDF5.heuristic_chunk(data)[1]
# On a parallel system I did run into problems with the
# heuristic chunk but for whatever reason it worked with
# half the size. As I had additional esoteric problems
# like this I disabled the compression by default,
# see also VahanaConfig.no_parallel_compression.
# Int(ceil(HDF5.heuristic_chunk(data)[1]/2))
end
create_dataset(gid,
name,
dt,
ds;
chunk=(chunk_size,),
shuffle=(),
compress=config.compression_level,
mpio_mode()...)
end
end
function calc_displace(num)
vec_num = MPI.Allgather(num, mpi.comm)
vec_displace =
if parallel_write()
# we use pop to remove the overall sum of agents, which
# is not used as an offset
d = [0; cumsum(vec_num)]
pop!(d)
d
else
# in the non parallel case there are no offsets at all
# as each rank write into an own file
fill(0, mpi.size)
end
(vec_num, vec_displace)
end
"""
write_agents(sim::Simulation, [types])
Writes the current agent state to the attached HDF5 file. If only the
agents of a subset of agent types are to be written, this subset can
be specified via the optional `types` argument.
"""
function write_agents(sim::Simulation,
types::Vector{DataType} = sim.typeinfos.nodes_types)
if sim.h5file === nothing
create_h5file!(sim)
end
lcstr = last_change_string([sim.h5file])
_log_time(sim, "write agents") do
t = transition_str(sim)
eid = create_group(sim.h5file["agents"]["_empty_array"], t)
for T in types
gid = sim.h5file["agents"][string(T)]
field = getproperty(sim, Symbol(T))
if haskey(attrs(gid), lcstr) &&
field.last_change == attrs(gid)[lcstr]
continue
end
attrs(gid)[lcstr] = field.last_change
num_agents = Int64(field.nextid - 1)
(vec_num_agents, vec_displace) = calc_displace(num_agents)
sum_num_agents = sum(vec_num_agents)
tid = create_group(gid, t)
attrs(tid)[lcstr] = field.last_change
attrs(tid)["size_per_rank"] = vec_num_agents
attrs(tid)["displace"] = vec_displace
attrs(eid)[string(T)] = sum_num_agents == 0
if sum_num_agents > 0
if parallel_write()
start = vec_displace[mpi.rank + 1] + 1
last = start + vec_num_agents[mpi.rank + 1] - 1
else
start = 1
last = num_agents
end
if ! has_hint(sim, T, :Immortal, :Agent)
dset = new_dset(tid, "died", Bool,
sum_num_agents, field.read.died, false)
dset[start:last] = field.read.died
end
if fieldcount(T) > 0
dset = new_dset(tid, "state", T,
sum_num_agents, field.read.state)
dset[start:last] = field.read.state
end
end
end
end
flush(sim.h5file)
nothing
end
# We need to convert the Edges depending of the edge hints to
# different structs that will be then saved to the HDF5 file
struct CompleteEdge{T}
to::AgentID
edge::Edge{T}
end
struct StatelessEdge
to::AgentID
from::AgentID
end
struct EdgeCount
to::AgentID
count::Int64
end
struct IgnoreFromEdge{T}
to::AgentID
state::T
end
_neighbors_only(sim, T) = (has_hint(sim, T, :Stateless) ||
fieldcount(T) == 0) && has_hint(sim, T, :IgnoreFrom)
"""
write_edges(sim::Simulation, [types])
Writes the current edge states to the attached HDF5 file. If only the
edges of a subset of edge types are to be written, this subset can
be specified via the optional `types` argument.
"""
function write_edges(sim::Simulation,
types::Vector{DataType} = sim.typeinfos.edges_types)
if sim.h5file === nothing
create_h5file!(sim)
end
lcstr = last_change_string([sim.h5file])
_log_time(sim, "write edges") do
t = transition_str(sim)
eid = create_group(sim.h5file["edges"]["_empty_array"], t)
for T in types
gid = sim.h5file["edges"][string(T)]
field = getproperty(sim, Symbol(T))
if haskey(attrs(gid), lcstr) &&
field.last_change == attrs(gid)[lcstr]
continue
end
attrs(gid)[lcstr] = field.last_change
# prepare_read! triggers the distributions of the edges to the
# correct nodes
prepare_read!(sim, Vector{DataType}(), T)
edges = if _neighbors_only(sim, T)
getproperty(sim, Symbol(T)).read
else
edges_iterator(sim, T) |> collect
end
num_edges = length(edges)
(vec_num_edges, vec_displace) = calc_displace(num_edges)
sum_num_edges = sum(vec_num_edges)
# what we write depends on :Stateless, :IgnoreFrom
# and :SingleType
(converted, DT, create_dt) = if _neighbors_only(sim, T)
if has_hint(sim, T, :SingleType)
(edges, eltype(edges), false)
else
([EdgeCount(to, count) for (to, count) in edges], EdgeCount, true)
end
elseif fieldcount(T) == 0
if has_hint(sim, T, :Stateless)
(map(e -> StatelessEdge(e[1], e[2]), edges),
StatelessEdge, true)
else
(map(e -> StatelessEdge(e[1], e[2].from), edges),
StatelessEdge, true)
end
elseif has_hint(sim, T, :IgnoreFrom)
(map(e -> IgnoreFromEdge(e[1], e[2]), edges),
IgnoreFromEdge{T}, true)
else
(map(e -> CompleteEdge(e[1], e[2]), edges),
CompleteEdge{T}, true)
end
tid = if length(converted) > 0
new_dset(gid, t, DT, sum_num_edges, converted, create_dt)
else
new_dset(gid, t, DT, sum_num_edges, Vector{DT}(), create_dt)
end
attrs(tid)[lcstr] = field.last_change
attrs(tid)["size_per_rank"] = vec_num_edges
attrs(tid)["displace"] = vec_displace
if parallel_write()
start = vec_displace[mpi.rank + 1] + 1
last = start + vec_num_edges[mpi.rank + 1] - 1
else
start = 1
last = num_edges
end
attrs(eid)[string(T)] = sum_num_edges == 0
if sum_num_edges > 0
if length(converted) > 0
tid[start:last] = converted
else
tid[start:last] = Vector{DT}()
end
end
finish_read!(sim, T)
end
end
flush(sim.h5file)
nothing
end
"""
write_snapshot(sim::Simulation, [comment::String = "", ignore = []])
Writes the current state of the simulation `sim` to the attached HDF5
file. `comment` can be used to identify the snapshot via
[`list_snapshots`](@ref). `ignore` is a list of agent and/or edge
types, that should not be written.
See also [`create_h5file!`](@ref)
"""
function write_snapshot(sim::Simulation, comment::String = ""; ignore = [])
ignore = applicable(iterate, ignore) ? ignore : [ ignore ]
if sim.h5file === nothing
create_h5file!(sim)
end
fid = sim.h5file
gid = create_group(fid["snapshots"], transition_str(sim))
attrs(gid)["comment"] = comment
attrs(gid)["ignored"] = string(ignore)
attrs(fid)["last_snapshot"] = sim.num_transitions
if sim.globals !== nothing
write_globals(sim)
end
write_agents(sim, filter(t -> !(t in ignore), sim.typeinfos.nodes_types))
write_edges(sim, filter(t -> !(t in ignore), sim.typeinfos.edges_types))
end
# Returns a vector of fids (h5 file handles). The size of the vector
# is equal to mpi.size of the simulation run that created the file(s).
# In the case, that the file was stored using h5parallel, all elements
# of the vector point to the same file. So
# fid[mpi.rank][...][pe_mpi.rank] access always the data that was stored
# by mpi.rank, independent if h5parallel was used or not.
#
# IMPORTANT: the files must be closed by the caller of open_h5file
function open_h5file(sim::Union{Simulation, Nothing}, filename)
# first we sanitize the filename
if endswith(filename, ".h5")
filename = filename[1:end-3]
end
if endswith(filename, "_0")
filename = filename[1:end-2]
end
if config.hdf5_path !== nothing
filename = mkpath(config.hdf5_path) * "/" * filename
end
if ! (isfile(filename * ".h5") || isfile(filename * "_0.h5"))
filename = mkpath("h5") * "/" * filename
if ! (isfile(filename * ".h5") || isfile(filename * "_0.h5"))
println("""
No hdf5 file(s) for $(filename) found in $(pwd()) or $(pwd())/h5
""")
return []
end
end
# we can have a single file written in parallel mode, or mpi.size files
# written without parallel mode. In the later case, the filenames
# end with _0, _1 ... _mpi.size-1
parallel = isfile(filename * ".h5")
filenames::Vector{String} = if parallel
[ filename * ".h5" ]
else
# first we open file _0 to get mpi.size
fid = HDF5.h5open(filename * "_0.h5", "r")
h5mpisize = attrs(fid)["mpisize"]
close(fid)
[ filename * "_$(i).h5" for i in 0:(h5mpisize-1) ]
end
# In the case that we have seperate files for each process, we don't
# need to open the files in parallel mode
fids = if HDF5.has_parallel() && parallel && mpi.size > 1
if sim !== nothing
_log_info(sim, "Open hdf5 file in parallel mode")
end
[ HDF5.h5open(f, "r+", mpi.comm, MPI.Info()) for f in filenames ]
else
if sim !== nothing
_log_info(sim, "Open hdf5 file without parallel mode")
end
[ HDF5.h5open(f, "r+") for f in filenames ]
end
h5mpisize = attrs(fids[1])["mpisize"]
if mpi.size > 1
@assert mpi.size == h5mpisize """
The file can only be read with 1 or $(h5mpisize) processes
"""
end
length(fids) > 1 ? fids : fill(fids[1], h5mpisize)
end
function find_transition_nr(ids, transition::Int)
if length(ids) == 0
return nothing
end
only_numbers = filter(s -> s[1:2] == "t_", keys(ids))
ts = filter(<=(transition), map(s -> parse(Int64, s[3:end]), only_numbers))
if length(ts) == 0
return nothing
end
maximum(ts)
end
function find_transition_group(ids, transition::Int)
trnr = find_transition_nr(ids, transition)
if trnr === nothing
nothing
else
ids["t_$(trnr)"]
end
end
function _read_agents_restore!(sim::Simulation, field, tid, T::DataType)
with_logger(sim) do
@debug("<Begin> _read_agents_restore!", agenttype=T)
end
vec_num_agents = attrs(tid)["size_per_rank"]
vec_displace = attrs(tid)["displace"]
size = vec_num_agents[mpi.rank + 1]
start = vec_displace[mpi.rank + 1] + 1
last = start + vec_num_agents[mpi.rank + 1] - 1
field.nextid = size + 1
if ! has_hint(sim, T, :Immortal, :Agent)
if size > 0
field.write.died = HDF5.read(tid["died"],
Bool,
start:last)
else
field.write.died = Vector{Bool}()
end
end
if fieldcount(T) > 0
if size > 0
field.write.state = HDF5.read(tid["state"],
T,
start:last)
else
field.write.state = Vector{T}()
end
else
field.write.state = fill(T(), size)
end
# this move the state to the shared memory (and to read)
finish_write!(sim, T)
# We must also refresh the list of reuseable ids
empty!(field.read.reuseable)
if ! has_hint(sim, T, :Immortal, :Agent)
for i in 1:size
if field.read.died[i]
push!(field.read.reuseable, i)
end
end
end
_log_debug(sim, "<End> _read_agents_restore!")
end
# merge distributed graph into a single one.
function _read_agents_merge!(sim::Simulation, tid, T::DataType, fidx, parallel)
with_logger(sim) do
@debug("<Begin> _read_agents_merge!", agenttype=T, fidx)
end
idmapping = Dict{AgentID, AgentID}()
typeid = sim.typeinfos.nodes_type2id[T]
vec_num_agents = attrs(tid)["size_per_rank"]
vec_displace = attrs(tid)["displace"]
size = parallel ? sum(vec_num_agents) : vec_num_agents[fidx]
died = if ! has_hint(sim, T, :Immortal, :Agent)
HDF5.read(tid["died"], Bool)
else
fill(false, size)
end
state = if fieldcount(T) > 0
HDF5.read(tid["state"], T)
else
fill(T(), size)
end
if parallel
# we must reconstruct the original indices of the agents as we
# have them now in a long list.
for rank in 1:length(vec_num_agents)
agents_on_rank = vec_num_agents[rank]
offset = vec_displace[rank]
for i in 1:agents_on_rank
if !died[i + offset]
newid = add_agent!(sim, state[i + offset])
push!(idmapping,
agent_id(typeid, rank-1, AgentNr(i)) => newid)
end
end
end
else
for i in 1:size
if !died[i]
newid = add_agent!(sim, state[i])
push!(idmapping,
agent_id(typeid, fidx-1, AgentNr(i)) => newid)
end
end
end
_log_debug(sim, "<End> _read_agents_merge!")
idmapping
end
function _read_globals_or_params(hid, T, empty_array_str)
eid = hid[empty_array_str]
all_keys = map(string,
filter(k -> k[1] != '_',
[keys(hid); keys(attrs(eid))]))
unsorted = Dict(map(all_keys) do k
k => if haskey(HDF5.attributes(eid), k)
Vector{fieldtype(T, Symbol(k))}()
elseif attrs(hid[k])["array"]
hid[k][]
else
hid[k][1]
end
end)
map(n -> unsorted[string(n)], fieldnames(T))
end
"""
read_params(filename::String, T::DataType)
read_params(sim::Simulation, T::DataType)
read_params(sim::Simulation, nr::Int64, T::DataType)
Read the parameters from an HDF5 file. If `filename` is given, the
parameters are read from the file with this filename from the `h5`
subfolder of the current working directory.
If a simulation `sim` is given instead, the filename from the
[`create_simulation`](@ref) call is used.
If the `overwrite_file` argument of [`create_simulation`](@ref) is set
to true, and the file names are supplemented with a number, the number of
the meant file can be specified via the `nr` argument.
In any case, the DataType `T` of the argument `params` of
[`create_simulation`](@ref) used for the simulation that wrote the
parameters must be specified.
"""
function read_params(filename::String, T::DataType)
fids = open_h5file(nothing, filename)
if length(fids) == 0
return
end
values = _read_globals_or_params(fids[1]["params"],
T,
empty_array_string(fids))
foreach(close, fids)
T(values...)
end
read_params(sim::Simulation, T::DataType) =
read_params(sim.filename, T)
read_params(sim::Simulation, nr::Int64, T::DataType) =
read_params(add_number_to_file(sim.filename, nr), T)
"""
read_globals(name::String, T::DataType; [ transition = typemax(Int64) ])
read_globals(sim::Simulation, T::DataType; [ transition = typemax(Int64) ])
read_globals(sim::Simulation, nr::Int64, T::DataType; [ transition = typemax(Int64) ])
Read the global values from an HDF5 file. If `filename` is given, the
parameters are read from the file with this filename from the `h5`
subfolder of the current working directory.
If a simulation `sim` is given instead, the filename from the
[`create_simulation`](@ref) call is used.
If the `overwrite_file` argument of [`create_simulation`](@ref) is set
to true, and the file names are supplemented with a number, the number of
the meant file can be specified via the `nr` argument.
In any case, the DataType `T` of the argument `globals` of
[`create_simulation`](@ref) used for the simulation that wrote the
parameters must be specified.
Per default, the last written globals are read. The `transition`
keyword allows to read also earlier versions. See also [Write simulations to dics](./hdf5.md) for details.
"""
function read_globals(name::String, T::DataType; transition = typemax(Int64))
fids = open_h5file(nothing, name)
if length(fids) == 0
return
end
values = _read_globals_or_params(find_transition_group(fids[1]["globals"],
transition),
T,
empty_array_string(fids))
foreach(close, fids)
T(values...)
end
read_globals(sim, T::DataType; transition = typemax(Int64)) =
read_globals(sim.filename, T; transition)
read_globals(sim, nr::Int64, T::DataType; transition = typemax(Int64)) =
read_globals(add_number_to_file(sim.filename, nr), T; transition)
"""
read_agents(filename::String, type; transition = typemax(Int64))
Read the agentstates of type `type` from an HDF5 file with the name
`filename`. The agent are read from the `h5` subfolder of the current
working directory, or from the subfolder set with
[`set_hdf5_path`](@ref).
Per default, the last written agents are read. The `transition`
keyword allows to read also earlier versions. See also [Write
simulations to disc](./hdf5.md) for details.
Returns a vector of agentstates.
"""
function read_agents(filename::String, type; transition = typemax(Int64))
type = string(type)
fids = open_h5file(nothing, filename)
aid = fids[1]["agents"][type]
t = find_transition_nr(aid, transition)
immortal = attrs(aid)[":Immortal"]
state = map(fids) do fid
fid["agents/$(type)/t_$t/state"][]
end |> Iterators.flatten
if ! immortal
died = map(fids) do fid
fid["agents/$(type)/t_$t/died"][]
end |> Iterators.flatten
end
foreach(close, fids)
if immortal
state |> collect
else
map(z -> z[1], filter(z -> !z[2], zip(state, died) |> collect))
end
end
"""
read_agents!(sim::Simulation, [name::String = sim.filename; transition = typemax(Int64), types::Vector{DataType} ])
read_agents!(sim::Simulation, nr::Int64; [transition = typemax(Int64), types::Vector{DataType}])
Read the agents from an HDF5 file into the simulation `sim`. If `name`
is given, the agent are read from the file with this filename from the
`h5` subfolder of the current working directory, or from the subfolder
set with [`set_hdf5_path`](@ref). In the other case the filename from
the [`create_simulation`](@ref) call is used.
If the `overwrite_file` argument of [`create_simulation`](@ref) is set
to true, and the file names are supplemented with a number, the number of
the meant file can be specified via the `nr` argument.
Per default, the last written agents are read. The `transition`
keyword allows to read also earlier versions. See also [Write
simulations to dics](./hdf5.md) for details.
If only the agents of a subset of agent types are to be read, this
subset can be specified via the optional `types` argument.
When the agents from a distributed simulation is read into a single
threaded simulation, the IDs of the agents are modified.
`read_agents!` returns a dictory that contains the ID mapping.
"""
function read_agents!(sim::Simulation,
name::String = sim.filename;
transition = typemax(Int64),
types::Vector{DataType} = sim.typeinfos.nodes_types)
fids = open_h5file(sim, name)
if length(fids) == 0
return
end
original_size = attrs(fids[1])["mpisize"]
parallel = attrs(fids[1])["HDF5parallel"]
merge = original_size > mpi.size
@assert !merge || mpi.size == 1
fidxs = merge && ! parallel ? (1:original_size) : (mpi.rank+1:mpi.rank+1)
sim.intransition = true
idmapping = Dict{AgentID, AgentID}()
_log_time(sim, "read agents") do
for T in types
field = getproperty(sim, Symbol(T))
if ! haskey(fids[1]["agents"], string(T))
continue
end
t = find_transition_nr(fids[1]["agents"][string(T)], transition)
if attrs(fids[1]["agents"][empty_array_string(fids)]["t_$t"])[string(T)]
if ! has_hint(sim, T, :Immortal, :Agent)
field.write.died = Vector{Bool}()
end
if fieldcount(T) > 0
field.write.state = Vector{T}()
end
continue
end
if merge
# in prepare_write we have an immutable check that we
# must disable by setting sim.initialized temporary to false
was_initialized = sim.initialized
sim.initialized = false
prepare_write!(sim, [], false, T)
sim.initialized = was_initialized
end
for fidx in fidxs
gid = fids[fidx]["agents"]
tid = find_transition_group(gid[string(T)], transition)
if tid === nothing && fidx == 1
continue
end
if merge
merge!(idmapping,
_read_agents_merge!(sim, tid, T, fidx, parallel))
else
_read_agents_restore!(sim, field, tid, T)
end
end
if merge
finish_write!(sim, T)
end
# must be after the _read calls, as they are modifying this also
field.last_change = find_transition_nr(fids[1]["agents"][string(T)],
transition)
for ET in sim.typeinfos.edges_types
field.last_transmit[ET] = -1
end
end
end
foreach(close, fids)
sim.intransition = false
idmapping
end
read_agents!(sim::Simulation,
nr::Int64;
transition = typemax(Int64),
types::Vector{DataType} = sim.typeinfos.nodes_types) =
read_agents!(sim, add_number_to_file(sim.filename, nr);
transition, types)
"""
read_edges(filename::String, type; transition = typemax(Int64))
Read the edgestates of type T from an HDF5 file with the name
`filename`. The edgestates are read from the `h5` subfolder of the
current working directory, or from the subfolder set with
[`set_hdf5_path`](@ref).
Per default, the last written edgestates are read. The `transition`
keyword allows to read also earlier versions. See also [Write
simulations to disc](./hdf5.md) for details.
Returns a vector of edgestates.
"""
function read_edges(filename::String, type; transition = typemax(Int64))
type = string(type)
fids = open_h5file(nothing, filename)
eid = fids[1]["edges"][type]
t = find_transition_nr(eid, transition)
stateless = attrs(eid)[":Stateless"]
if stateless
error("Can not read the state of stateless edges")
end
state = map(fids) do fid
fid["edges/$(type)/t_$t"][]
end |> Iterators.flatten
foreach(close, fids)
state |> collect
end
"""
read_edges!(sim::Simulation, [name::String = sim.filename; idmapfunc = identity, transition = typemax(Int64), types::Vector{DataType}])
read_edges!(sim::Simulation, nr::Int64; [ idmapfunc = identity, transition = typemax(Int64), types::Vector{DataType} ])
Read the edges from an HDF5 file into the simulation `sim`. If
`name` is given, the edges are read from the file with this filename
from the `h5` subfolder of the current working directory. In the
other case the filename from the [`create_simulation`](@ref) call is
used.
If the `overwrite_file` argument of [`create_simulation`](@ref) is set
to true, and the file names are supplemented with a number, the number of
the meant file can be specified via the `nr` argument.
Per default, the last written edges are read. The `transition` keyword
allows to read also earlier versions. See also [Write simulations to
disc](./hdf5.md) for details.
If only the edges of a subset of edge types are to be read, this
subset can be specified via the optional `types` argument.
When the agents from a distributed simulation is read into a single
threaded simulation, the IDs of the agents are modified. The
`idmapfunc` must be a function that must return the new agent id for a
given old agent id. [`read_agents!`](@ref) returns a `Dict{AgentID,
AgentID}` that can be used for this via: `idmapfunc = (key) ->
idmapping[key]`, where `idmapping` is such a `Dict`.
"""
function read_edges!(sim::Simulation,
name::String = sim.filename;
idmapfunc = identity,
transition = typemax(Int64),
types::Vector{DataType} = sim.typeinfos.edges_types)
fids = open_h5file(sim, name)
if length(fids) == 0
return
end
@assert length(fids) == mpi.size || idmapfunc !== identity """
read_edges! can be only merging a distributed graph when an idmap is given
"""
original_size = attrs(fids[1])["mpisize"]
merge = original_size > mpi.size
@assert !merge || mpi.size == 1
fidxs = merge ? (1:original_size) : (mpi.rank+1:mpi.rank+1)
# we call add_edge! but there is a check that this is only done
# at initialization time or in a transition function
sim.intransition = true
for T in types
if ! haskey(fids[1]["edges"], string(T))
continue
end
with_logger(sim) do
@info("<Begin> read edges", edgetype = T, transition = transition)
end
prepare_write!(sim, [], false, T)
trnr = find_transition_nr(fids[1]["edges"][string(T)], transition)
if trnr === nothing
continue
end
if attrs(fids[1]["edges"][empty_array_string(fids)]["t_$(trnr)"])[string(T)]
_log_info(sim, "<End> read edges")
finish_write!(sim, T)
continue
end
for fidx in fidxs
tid = find_transition_group(fids[fidx]["edges"][string(T)],
transition)
_read_edges!(sim, tid, idmapfunc, T, fidx)
end
finish_write!(sim, T)
if trnr === nothing
getproperty(sim, Symbol(T)).last_change = 0
else
getproperty(sim, Symbol(T)).last_change = trnr
end
_log_info(sim, "<End> read edges")
end
sim.intransition = false
foreach(close, fids)
end
read_edges!(sim::Simulation,
nr::Int64;
idmapfunc = identity,
transition = typemax(Int64),
types::Vector{DataType} = sim.typeinfos.nodes_types) =
read_edges!(sim, add_number_to_file(sim.filename, nr);
idmapfunc, transition, types)
function _read_edges!(sim::Simulation, tid, idmapfunc, T, fidx)
field = getproperty(sim, Symbol(T))
vec_num_edges = attrs(tid)["size_per_rank"]
vec_displace = attrs(tid)["displace"]
start = vec_displace[fidx] + 1
last = start + vec_num_edges[fidx] - 1
if _neighbors_only(sim, T)
if has_hint(sim, T, :SingleType)
AT = sim.typeinfos.edges_attr[T][:target]
typeid = sim.typeinfos.nodes_type2id[AT]
data = if has_hint(sim, T, :SingleEdge)
HDF5.read(tid, Bool, start:last)
else
HDF5.read(tid, Int64, start:last)
end
for (idx, num_edges) in enumerate(data)
newid = idmapfunc(agent_id(typeid, fidx - 1, AgentNr(idx)))
newidx = agent_nr(newid)
# TODO: we know the size at the beginning, or?
if length(field.read) < newidx
resize!(field.write, newidx)
end
field.write[newidx] = num_edges
end
else
# EdgeCount struct
for ec in HDF5.read(tid, EdgeCount, start:last)
field.write[idmapfunc(ec.to)] = ec.count
end
end
elseif fieldcount(T) == 0 # StatelessEdge
for se in HDF5.read(tid, StatelessEdge, start:last)
add_edge!(sim, idmapfunc(se.from), idmapfunc(se.to), T())
end
elseif has_hint(sim, T, :IgnoreFrom)
# for add_edge! we need always a from id, even when it's ignored
dummy = AgentID(0)
for edge in HDF5.read(tid, IgnoreFromEdge{T}, start:last)
add_edge!(sim, dummy, idmapfunc(edge.to), edge.state)
end
else
if has_hint(sim, T, :SingleType)
totype = sim.typeinfos.edges_attr[T][:target]
totypeid = sim.typeinfos.nodes_type2id[totype]
for ce in HDF5.read(tid, CompleteEdge{T}, start:last)
add_edge!(sim,
idmapfunc(ce.edge.from),
idmapfunc(agent_id(totypeid,
fidx - 1,
ce.to)),
ce.edge.state)
end
else
for ce in HDF5.read(tid, CompleteEdge{T}, start:last)
add_edge!(sim, idmapfunc(ce.edge.from), idmapfunc(ce.to),
ce.edge.state)
end
end
end
end
function read_rasters!(sim::Simulation,
name::String = sim.filename;
idmapping)
# the rasters are immutable arrays of agents_ids. So there
# is no need to read them more then once
if length(sim.rasters) > 0
return
end
fids = open_h5file(sim, name)
if length(fids) == 0
return
end
rid = first(fids)["rasters"]
for raster in keys(rid)
sim.rasters[Symbol(raster)] =
length(idmapping) == 0 ? rid[raster][] :
map(id -> get(idmapping, id, 0), rid[raster][])
end
foreach(close, fids)
end
read_rasters!(sim::Simulation,
nr::Int64;
idmapping) =
read_rasters!(sim, add_number_to_file(sim.filename, nr);
idmapping)
"""
read_snapshot!(sim::Simulation, [name::String; transition = typemax(Int64), writeable = false, ignore_params = false])
read_snapshot!(sim::Simulation, nr::Int64; [transition = typemax(Int64), writeable = false, ignore_params = false])
Read a complete snapshot from a file into the simulation `sim`. If
`name` is given, the snapshot is read from the file with this filename
from the `h5` subfolder of the current working directory. In the
other case the filename from the [`create_simulation`](@ref) call is
used.
If the `overwrite_file` argument of [`create_simulation`](@ref) is set
to true, and the file names are supplemented with a number, the number of
the meant file can be specified via the `nr` argument.
Per default, the last written snapshot is read. The `transition`
keyword allows to read also earlier versions. See also
[Transition](./hdf5.md#Transition) for details.
If `writeable` is set to true, the file is also attached to the simulation
and following `write_` functions like [`write_snapshot`](@ref) will be
append to the file.
If `ignore_params` is set to true, the parameters of `sim` will not be
changed.
Returns false when no snapshot was found
"""
function read_snapshot!(sim::Simulation,
name::String = sim.filename;
transition = typemax(Int64),
writeable = false,
ignore_params = false)
# First we free the memory allocated by the current state of sim
_free_memory!(sim)
fids = open_h5file(sim, name)
if length(fids) == 0
return false
end
sim.initialized = attrs(fids[1])["initialized"]
sim.num_transitions = transition == typemax(Int64) ?
attrs(fids[1])["last_snapshot"] : transition
globals_last_change = find_transition_nr(fids[1]["globals"], transition)
if globals_last_change !== nothing
sim.globals_last_change = globals_last_change
end
foreach(close, fids)
if ignore_params == false && sim.params !== nothing
sim.params = read_params(name, typeof(sim.params))
end
if sim.globals !== nothing && globals_last_change !== nothing
sim.globals = read_globals(name, typeof(sim.globals); transition)
end
idmapping = read_agents!(sim, name; transition = transition)
if length(idmapping) > 0
read_edges!(sim, name; transition = transition,
idmapfunc = (key) -> idmapping[key])
read_rasters!(sim, name; idmapping)
else
read_edges!(sim, name; transition = transition)
read_rasters!(sim, name; idmapping)
end
if writeable
fids = open_h5file(sim, name)
sim.h5file = fids[mpi.rank+1]
end
true
end
read_snapshot!(sim::Simulation,
nr::Int64;
transition = typemax(Int64),
writeable = false,
ignore_params = false) =
read_snapshot!(sim, add_number_to_file(sim.filename, nr);
transition, writeable, ignore_params)
"""
list_snapshots(name::String)
list_snapshots(sim::Simulation)
list_snapshots(sim::Simulation, nr::Int64)
List all snapshots of a HDF5 file. If `name` is given, the snapshots
from the file with this filename is returned. In the other case the
filename from the [`create_simulation`](@ref) call is used.
If the `overwrite_file` argument of [`create_simulation`](@ref) is set
to true, and the file names are supplemented with a number, the number of
the meant file can be specified via the `nr` argument.
Returns a vector of tuples, where the first element is the transition
number for which a snapshot was saved, and the second element is the
comment given in the [`write_snapshot`](@ref) call.
"""
function list_snapshots(name::String)
fids = open_h5file(nothing, name)
sid = fids[1]["snapshots"]
if length(keys(sid)) == 0
return nothing
end
snapshots =
map(t -> (parse(Int64, t[3:end]), attrs(sid[t])["comment"]), keys(sid))
foreach(close, fids)
snapshots
end
list_snapshots(sim::Simulation) = list_snapshots(sim.filename)
list_snapshots(sim::Simulation, nr::Int64) =
list_snapshots(add_number_to_file(sim.filename, nr))
import Base.convert
"""
create_namedtuple_converter(T::DataType)
The HDF5.jl library does not support the storage of nested structs,
but structs can have `NamedTuples` as fields. This function creates a
convert function from a struct to a corresponding `NamedTuple` (and
also the other way around), so after calling this for a type `T`, `T`
can be the type of an agent/edge/param/global field.
"""
function create_namedtuple_converter(T::DataType)
NT = NamedTuple{fieldnames(T), Tuple{fieldtypes(T)...}}
@eval convert(::Type{$NT}, st::$T) = ntfromstruct(st)
@eval convert(::Type{$T}, nt::$NT) = structfromnt($T, nt)
end
"""
write_metadata(sim::Simulation, type::Union{Symbol, DataType}, field::Symbol, key::Symbol, value)
Attach metadata to a `field` of an agent- or edgetype or the
`globals` or `params` struct (see [`create_simulation`](@ref)) or to a
raster (in that case `field` must be the name of the raster). `type`
must be an agent- or edgetype, :Global, :Param or :Raster. Metadata is
stored via `key`, `value` pairs, so that multiple data of different
types can be attached to a single field.
See also: [`read_metadata`](@ref)
"""
function write_metadata(sim::Simulation,
type::Union{Symbol, DataType},
field::Symbol,
key::Symbol,
value)
if sim.h5file === nothing
push!(_preinit_meta, (type, field, key, value))
return
end
if value === nothing
value = "nothing"
end
field_str = String(field)
mid = if type == :Param
sim.h5file["params"]["_meta"]
elseif type == :Global
sim.h5file["globals"]["_meta"]
elseif type == :Raster
sim.h5file["rasters"]
elseif type in sim.typeinfos.nodes_types ||
type in map(Symbol, sim.typeinfos.nodes_types)
sim.h5file["agents"][String(type)]["_meta"]
elseif type in sim.typeinfos.edges_types ||
type in map(Symbol, sim.typeinfos.edges_types)
sim.h5file["edges"][String(type)]["_meta"]
else
@error """
Can not write metadata, `type` must be an agenttype or edgetype
or one of the following symbols: :Param, :Global, :Raster.
"""
end
if ! (field_str in keys(mid))
create_group(mid, field_str)
end
write_attribute(mid[field_str], String(key), value)
flush(sim.h5file)
end
"""
read_metadata(sim::Simulation, type::Union{Symbol, DataType}[, field::Symbol, key::Symbol ])
read_metadata(filename::String, type::Union{Symbol, DataType}[, field::Symbol, key::Symbol ])
Attach metadata to a `field` of an agent- or edgetype or the
`globals` or `params` struct (see [`create_simulation`](@ref)) or to a
raster (in that case `field` must be the name of the raster). `type`
must be an agent- or edgetype, :Global, :Param or :Raster. Metadata is
stored via `key`, `value` pairs, so that multiple data of different
Read metadata for a `field` of an agent- or edgetype or the `globals` or
`params` struct (see [`create_simulation`](@ref)) or to a raster (in that
case `field` must be the name of the raster). `type` must be an agent-
or edgetype :Global, :Param or :Raster. Metadata is stored via `key`,
value pairs. Multiple data of different types can be attached to a
single field, a single piece of the metadata can be retrived via the
`key` parameter. If this is not set (or set to Symbol()), a
Dict{Symbol, Any} with the complete metadata of this field is
returned.
See also: [`write_metadata`](@ref)
"""
function read_metadata(sim::Simulation,
type::Union{Symbol, DataType},
field::Symbol = Symbol(),
key::Symbol = Symbol())
if field == Symbol()
_read_metadata_all_fields(open_h5file(sim, sim.filename), type)
else
_read_metadata(open_h5file(sim, sim.filename), type, field, key, true)
end
end
function read_metadata(filename::String,
type::Union{Symbol, DataType},
field::Symbol = Symbol(),
key::Symbol = Symbol())
if field == Symbol()
_read_metadata_all_fields(open_h5file(nothing, filename), type)
else
_read_metadata(open_h5file(nothing, filename), type, field, key, true)
end
end
function _read_metadata_all_fields(fids, type::Symbol)
all = Dict()
for f in _read_metadata(fids, type, Symbol(), Symbol(), false)
all[Symbol(f)] = _read_metadata(fids, type, f, Symbol(), false)
end
foreach(close, fids)
all
end
function _read_metadata(fids, type, field, key, close_file)
if length(fids) == 0
return
end
mid = if type == :Param
fids[1]["params"]["_meta"]
elseif type == :Global
fids[1]["globals"]["_meta"]
elseif type == :Raster
fids[1]["rasters"]
elseif type in keys(fids[1]["agents"]) ||
type in map(Symbol, keys(fids[1]["agents"]))
fids[1]["agents"][String(type)]["_meta"]
elseif type in keys(fids[1]["edges"]) ||
type in map(Symbol, keys(fids[1]["edges"]))
fids[1]["edges"][String(type)]["_meta"]
else
@error """
Can not read metadata, `type` must be an agenttype or edgetype
or one of the following symbols: :Param, :Global, :Raster.
"""
end
if field == Symbol()
r = keys(mid)
if close_file
foreach(close, fids)
end
return r
end
field_str = String(field)
r = if field_str in keys(mid)
if key == Symbol()
Dict([ (Symbol(d[1]), d[2]) for d in Dict(attrs(mid[field_str])) ])
else
get(attrs(mid[field_str]), String(key), nothing)
end
else
nothing
end
if close_file
foreach(close, fids)
end
r
end
"""
write_sim_metadata(sim::Simulation, key::Symbol, value)
Attach additional metadata to a simulation.
See also: [`read_sim_metadata`](@ref)
"""
function write_sim_metadata(sim::Simulation, key::Symbol, value)
if sim.h5file === nothing
push!(_preinit_meta_sim, (key, value))
return
end
# to ensure that the user written meta data does not
# interfere with the metadata from Vahana, we
# also store this into a seperate group
write_attribute(sim.h5file["_meta"], String(key), value)
flush(sim.h5file)
end
"""
read_sim_metadata(sim::Simulation, [ key::Symbol = Symbol() ])
read_sim_metadata(filename::String, [ key::Symbol = Symbol() ])
Read metadata for a simulation or from the file `filename`. Metadata is
stored via `key`, value pairs. If `key` is not set (or set to
Symbol()), a Dict{Symbol, Any} with the complete metadata of the
simulation is returned.
The following metadata is stored automatically:
- simulation_name
- model_name
- date (in the format "yyyy-mm-dd hh:mm:ss")
See also: [`write_metadata`](@ref)
"""
function read_sim_metadata(sim::Simulation,
key::Symbol = Symbol())
read_sim_metadata(open_h5file(sim, sim.filename), key)
end
function read_sim_metadata(filename::String,
key::Symbol = Symbol())
read_sim_metadata(open_h5file(nothing, filename), key)
end
function read_sim_metadata(fids,
key::Symbol = Symbol())
if length(fids) == 0
return
end
mid = fids[1]["_meta"]
r = if key == Symbol()
Dict([ (Symbol(d[1]), d[2]) for d in Dict(attrs(mid)) ])
else
get(attrs(mid), String(key), nothing)
end
foreach(close, fids)
r
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 6045 | export checked, @rootonly, @roottime
"""
checked(f, g, itr; kwargs...)
Calls g(f, itr; kwargs...), but only if itr != nothing.
As all the Vahana functions that access the edges of a specific agent
can return nothing in the case, that there exist no incoming edge for this agent,
it's often necessery to check this case.
Example:
Instead of writing
```@example
nids = neighborids(sim, id, Contact)
if nids != nothing
foreach(nids) do nid
add_edge!(sim, id, nid, Inform()
end
end
```
you can use the checked function to write
```@example
checked(foreach, neighborids(sim, id, Contact)) do nid
add_edge!(sim, id, nid, Inform())
end
```
"""
function checked(f, g, itr; kwargs...)
if !isnothing(itr)
g(f, itr; kwargs...)
end
end
######################################## internal
# this is for the reduce operations, and tries to determine
# the default value for ranks without any agent/edge
function val4empty(op; kwargs...)
if (op == &) || (op == |)
MT = get(kwargs, :datatype, Bool)
else
MT = get(kwargs, :datatype, Int)
end
# for MPI.reduce we must ensure that each rank has a value
emptyval = get(kwargs, :init) do
if op == +
zero(MT)
elseif op == *
one(MT)
elseif op == max
-typemax(MT)
elseif op == min
typemax(MT)
elseif op == &
@assert typemax(MT) isa Int || typemax(MT) isa Bool """
The & operator is only supported for integer and boolean types
"""
typemax(MT)
elseif op == |
@assert typemax(MT) isa Int || typemax(MT) isa Bool """
The & operator is only supported for integer and boolean types
"""
typemax(MT) isa Int ? 0 : false
else
nothing
end
end
@assert emptyval !== nothing """\n
Can not derive the init value for the operator. You must add this
information via the `init` keyword.
"""
emptyval
end
##################### add_number_to_file
# when sim.overwrite is false, we automatically create filenames with
# appended numbers (for the h5 files and also the logs)
function add_number_to_file(filename, i)
if i < 999999
filename * '-' * lpad(string(i), 6, "0")
else
filename * '-' * string(i)
end
end
function add_number_to_file(filename)
i = 0
while true
i += 1
numbered = add_number_to_file(filename, i)
if ! isfile(numbered * ".h5") && ! isfile(numbered * "_0.h5") &&
! isfile(numbered * "_0.log")
return numbered
end
end
end
#################### field symbols
# create symbol for the different fields of an agent/edgetype
# TODO: adjust edgefieldfactory to macros
writefield(T) = Symbol(T).write
readfield(T) = Symbol(T).read
# nextidfield(T) = Symbol(T, "_nextid")
macro nextid(T)
field = Symbol(T)
:( sim.$(field).nextid ) |> esc
end
nextid(sim, T) = getproperty(sim, Symbol(T)).nextid
macro agent(T)
field = Symbol(T)
:( sim.$(field) ) |> esc
end
macro edge(T)
field = Symbol(T)
:( sim.$(field) ) |> esc
end
macro windows(T)
field = Symbol(T)
:( sim.$(field).mpiwindows ) |> esc
end
windows(sim, T) = getproperty(sim, Symbol(T)).mpiwindows
macro readdied(T)
field = Symbol(T)
:( sim.$(field).read.died ) |> esc
end
readdied(sim, T) = getproperty(sim, Symbol(T)).read.died
macro writedied(T)
field = Symbol(T)
:( sim.$(field).write.died ) |> esc
end
writedied(sim, T) = getproperty(sim, Symbol(T)).write.died
macro readstate(T)
field = Symbol(T)
:( sim.$(field).read.state ) |> esc
end
readstate(sim, T) = getproperty(sim, Symbol(T)).read.state
macro writestate(T)
field = Symbol(T)
:( sim.$(field).write.state ) |> esc
end
writestate(sim, T) = getproperty(sim, Symbol(T)).write.state
macro readreuseable(T)
field = Symbol(T)
:( sim.$(field).read.reuseable ) |> esc
end
readreuseable(sim, T) = getproperty(sim, Symbol(T)).read.reuseable
macro writereuseable(T)
field = Symbol(T)
:( sim.$(field).write.reuseable ) |> esc
end
writereuseable(sim, T) = getproperty(sim, Symbol(T)).write.reuseable
macro agentwrite(T)
field = Symbol(T)
:( sim.$(field).write ) |> esc
end
macro agentread(T)
field = Symbol(T)
:( sim.$(field).read ) |> esc
end
macro edgewrite(T)
field = Symbol(T)
:( sim.$(field).write ) |> esc
end
edgewrite(sim, T) = getproperty(sim, Symbol(T)).write
macro edgeread(T)
field = Symbol(T)
:( sim.$(field).read ) |> esc
end
edgeread(sim, T) = getproperty(sim, Symbol(T)).read
macro storage(T)
field = Symbol(T)
:( sim.$(field).storage ) |> esc
end
storage(sim, T) = getproperty(sim, Symbol(T)).storage
macro agentsontarget(T)
field = Symbol(T)
:( sim.$(field).agentsontarget ) |> esc
end
agentsontarget(sim, T) = getproperty(sim, Symbol(T)).agentsontarget
macro removeedges(T)
field = Symbol(T)
:( sim.$(field).removeedges ) |> esc
end
removeedges(sim, T) = getproperty(sim, Symbol(T)).removeedges
# we use this tests are for the distributed version, in this case
# the tests should be only run on the rank that the id is currently
# living
macro onrankof(aid, ex)
quote
if Vahana.process_nr($(esc(aid))) == mpi.rank
$(esc(ex))
end
end
end
macro rankonly(rank, ex)
quote
if $rank == mpi.rank
$(esc(ex))
end
end
end
macro rootonly(ex)
quote
if 0 == mpi.rank
$(esc(ex))
end
end
end
macro roottime(ex)
quote
if 0 == mpi.rank
@time $(esc(ex))
else
$(esc(ex))
end
end
end
edge_attrs(sim, T::DataType) = sim.typeinfos.edges_attr[T]
nodes_attrs(sim, T::DataType) = sim.typeinfos.nodes_attr[T]
disable_transition_checks = (disable::Bool) -> config.check_readable = ! disable
typeid(sim, T::DataType) = sim.typeinfos.nodes_type2id[T]
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 5141 | using Logging, Dates
using Base: debug_color
import Logging: with_logger, shouldlog, min_enabled_level, catch_exceptions, handle_message
export with_logger, create_logger!, log_overview
struct VahanaLogger <: Logging.AbstractLogger
stream::IO
min_level::LogLevel
debug::Bool
starttime::Float64
begintimes::Dict{String, Float64}
# store <Begin> kwargs to access them at <End> in the ! debug case
kwargs::Dict{String, Dict}
end
Logging.shouldlog(logger::VahanaLogger, level, _module, group, id) = true
Logging.min_enabled_level(logger::VahanaLogger) = logger.min_level
Logging.catch_exceptions(logger::VahanaLogger) = false
struct Log
file::Union{IOStream, Nothing}
logger::Union{VahanaLogger, Nothing}
debug::Bool
end
function Logging.handle_message(logger::VahanaLogger, level::LogLevel, message, _module,
group, id, filepath, line; kwargs...)
@nospecialize
now = time()
buf = IOBuffer()
iob = IOContext(buf, logger.stream)
msglines = split(chomp(convert(String, string(message))::String), '\n')
msg1, rest = Iterators.peel(msglines)
# check for <Begin> or <End> tags
msg1split = split(msg1, ">")
if msg1split[1] == "<End"
if logger.debug
println(iob, "Time (sec): ", now - logger.starttime)
else
kwargs = logger.kwargs[msg1split[2]]
println(iob, "Start (sec): ",
logger.begintimes[msg1split[2]] - logger.starttime)
end
println(iob, " ", logger.debug ? msg1 : msg1split[2],
" |#| Duration (ms): ",
(now - logger.begintimes[msg1split[2]]) * 1000)
elseif msg1split[1] != "<Begin" || logger.debug
println(iob, "Time (sec): ", now - logger.starttime)
println(iob, " ", msg1)
end
for msg in rest
println(iob, msg)
end
if msg1split[1] != "<Begin" || logger.debug
for (key, val) in kwargs
println(iob, " ", key, " = ", val)
end
end
write(logger.stream, take!(buf))
if logger.debug
flush(logger.stream)
end
if msg1split[1] == "<Begin"
logger.begintimes[msg1split[2]] = time()
logger.kwargs[msg1split[2]] = kwargs
end
nothing
end
function create_logger(filename, logging, debug, overwrite_file)
if logging
filename = if config.log_path === nothing
mkpath("log") * "/" * filename
else
mkpath(config.log_path) * "/" * filename
end
end
if ! overwrite_file
filename = add_number_to_file(filename)
# to avoid that rank 0 creates a file before other ranks check this
MPI.Barrier(MPI.COMM_WORLD)
end
logfile = logging ? open("""$(filename)_$(mpi.rank).log""";
write = true) :
nothing
logger = logging ?
VahanaLogger(logfile,
debug ? Logging.Debug : Logging.Info,
debug,
time(),
Dict{String, Float64}(),
Dict{String, Dict}()) :
nothing
Log(logfile, logger, debug)
end
"""
create_logger!(sim::Simulation, [debug = false, name = sim.name; overwrite = sim.overwrite_file])
The canonical way to create log files for a simulation is by setting the
logging keyword of [`create_simulation`](@ref) to true. But sometime
it can be useful to control this manually, e.g. after a call to
[`copy_simulation`](@ref).
When also `debug` is set to true, the log file contains more details and
the stream will be flushed after each write.
The `filename` argument can be used to specify a filename other than
`sim.filename`. If `overwrite` is true, existing files with this name
will be overwritten. If it is false, the filename is automatically
extended by an increasing 6-digit number, so that existing files are
not overwritten.
The files are always created in a `log` subfolder, and this one will be
create in the current working directory.
"""
function create_logger!(sim::Simulation, debug = false, filename = sim.name;
overwrite = sim.overwrite_file)
sim.logger = create_logger(filename, true, debug, overwrite)
end
"""
with_logger(f::Function, sim::Simulation)
Execute function f, directing all log messages to the logger that is attached
to simulation `sim`.
"""
function with_logger(f::Function, sim::Simulation)
if sim.logger.logger !== nothing
with_logger(f, sim.logger.logger)
end
end
_log_info(sim, text) = with_logger(() -> @info(text), sim)
_log_debug(sim, text) = with_logger(() -> @debug(text), sim)
function _log_time(f, sim, text, debug = false)
lf = debug ? _log_debug : _log_info
lf(sim, "<Begin> " * text)
r = f()
lf(sim, "<End> " * text)
r
end
"""
log_overview(sim::Simulation)
Dump an overview of the simulation `sim` to the attached logfile.
"""
function log_overview(sim::Simulation)
if sim.logger.logger !== nothing
show(sim.logger.logger.stream, MIME("text/plain"), sim)
end
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 19832 | using MPI
using Logging
# Distributing the whole graph to the different processes.
#
# This function is called from finish_init!, per default the sendmap
# is created in finish_init! by Metis, but also a external
# mapping can be used, e.g. for testing, or in the case that the
# modeller can create a better partitioning him/herself then Metis.
function distribute!(sim, sendmap::Dict{AgentID, ProcessID})
node_types = sim.typeinfos.nodes_types
edge_types = sim.typeinfos.edges_types
# We reconstruct the whole graph, so we call prepare_write for
# all agent and edgetypes
foreach(prepare_write!(sim, [], []), [ node_types; edge_types ])
MPI.Barrier(MPI.COMM_WORLD)
disable_transition_checks(true)
# we also reset the nextid count to 1 for every nodetype
foreach(node_types) do T
nextid(sim, T) = AgentNr(1)
end
# We add structure to the simple AgentID -> ProcessID mapping,
# so that we can combine all agents of a AgentTypes etc.
ssm = create_structured_send_map(sim, sendmap)
# First we send all agentstates and collect the idmapping, as the
# agent gets an new id in this process. idmapping is a Dict that
# allows to get the new id when only the old id is known.
idmapping = Dict{AgentID, AgentID}()
for T in node_types
merge!(idmapping, sendagents!(sim, ssm[T], T))
end
# Currently, a PE knows only the idmapping of the agent that was
# mapped to this PE. We collect now this information. As we can not send
# the Dict directly, we join the keys and values indepently and create
# a new dict afterwards
allkeys = join(keys(idmapping) |> collect)
allvalues = join(values(idmapping) |> collect)
idmapping = Dict(allkeys .=> allvalues)
# Till now we have distribute only the agents, and we have the mapping
# of the agents-ids. We now transfer the edges, and are updating also
# the id of the agents by this way
for T in edge_types
sendedges!(sim, sendmap, idmapping, T)
end
# we want to allow that add_raster is only called on the root rank
# but in this case the sim.rasters Dict missings the keys on the
# other ranks. So we first send the key names
if mpi.rank == 0
rasternames = String.(keys(sim.rasters))
n = length(rasternames)
MPI.Bcast!(Ref(n), MPI.COMM_WORLD)
for s in rasternames
len = length(s)
MPI.Bcast!(Ref(len), MPI.COMM_WORLD)
MPI.Bcast!(Vector{UInt8}(s), MPI.COMM_WORLD)
end
else
n = Ref{Int}()
MPI.Bcast!(n, MPI.COMM_WORLD)
for _ in 1:n[]
len = Ref{Int}()
MPI.Bcast!(len, MPI.COMM_WORLD)
buffer = Vector{UInt8}(undef, len[])
MPI.Bcast!(buffer, MPI.COMM_WORLD)
push!(sim.rasters, Symbol(String(buffer)) => AgentID[])
end
end
# we must also update and broadcast the ids for each raster. As we
# don't need the edges for that, we must not synchronize the PEs
# before.
foreach(grid -> broadcastids(sim, grid, idmapping), keys(sim.rasters))
# finish everything and return the idmapping
disable_transition_checks(false)
MPI.Barrier(MPI.COMM_WORLD)
foreach(T -> finish_distribute!(sim, T), node_types)
idmapping
end
# structured_send_map is Dict{DataType, Vector{Vector{AgentID}}, e.g.
# Buyer --- PE1 --- AgentID1
# | |- AgentID4
# | '- AgentID7
# '- PE2 --- AgentID3
# '- AgentID4
# Seller ...
#
# This map is used by sendedges!
function create_structured_send_map(sim, sendmap::Dict{AgentID, ProcessID})
_log_debug(sim, "<Begin> create_structured_send_map")
ssm = Dict{DataType, Vector{Vector{AgentID}}}()
for T in sim.typeinfos.nodes_types
ssm[T] = [ Vector{AgentID}() for _ in 1:mpi.size ]
end
for (id, p) in sendmap
push!(ssm[Vahana.type_of(sim, id)][p], id)
end
_log_debug(sim, "<End> create_structured_send_map")
ssm
end
# Distribute agents of agenttype T to the different PEs.
function sendagents!(sim, perPE::Vector{Vector{AgentID}}, T::DataType)
with_logger(sim) do
@debug "<Begin> sendagents!" agenttype=T
end
# ST is the transmitted datatype. Beside the state itself (T) we
# need also the AgentID to create the mappning from the old
# AgentID to the new AgentID
ST = Vector{Tuple{AgentID,T}}
longvec = reduce(vcat, perPE)
sendbuf = if length(longvec) > 0
agentstates = map(longvec) do id
(id, agentstate(sim, id, T))
end
VBuffer(agentstates, [ length(perPE[i]) for i in 1:mpi.size ])
else
VBuffer(ST(), [ 0 for _ in 1:mpi.size ])
end
# first we transmit the number of agents a PE want to send to the
# other PEs
sendNumElems = [ length(perPE[i]) for i in 1:mpi.size ]
recvNumElems = MPI.Alltoall(UBuffer(sendNumElems, 1), mpi.comm)
# with this information we can prepare the receive buffer
recvbuf = MPI.VBuffer(ST(undef, sum(recvNumElems)), recvNumElems)
# and then transfer the {AgentID,T (AgentState)} tuples.
MPI.Alltoallv!(sendbuf, recvbuf, mpi.comm)
# we need oldid as key and newid as value
idmapping = Dict{AgentID, AgentID}()
foreach(recvbuf.data) do (id, agent)
idmapping[id] = add_agent!(sim, agent)
end
_log_debug(sim, "<End> sendagents!")
idmapping
end
function construct_mpi_agent_methods(T::DataType, attr, simsymbol, mortal)
stateless = :Stateless in attr[:hints]
@eval function transmit_agents!(sim::$simsymbol,
readableET::Vector{DataType},
::Type{$T})
if $stateless
return
end
with_logger(sim) do
@debug "<Begin> transmit_agents!" agenttype=$T
end
for ET in readableET
if :IgnoreSourceState in sim.typeinfos.edges_attr[ET][:hints]
continue
end
edgefield = getproperty(sim, Symbol(ET))
# there are two reasons why we must transmit the agentstate:
# - the agentstates has changed since the last transmit:
# last_change >= last_transmit[ET]
# - a readable network R has changed since the last transmit
# of agents caused by this network:
# @edge($ET).last_change >= last_transmit[ET]
if @agent($T).last_transmit[ET] <= @agent($T).last_change ||
@agent($T).last_transmit[ET] <= edgefield.last_change
perPE = edgefield.accessible[sim.typeinfos.nodes_type2id[$T]]
# only access the state if it isn't already in the dict
# (the foreign dict is cleared when $T is writeable).
if ! isempty(@agent($T).foreignstate)
for i in 1:mpi.size
filter!(d -> ! haskey(@agent($T).foreignstate, d),
perPE[i])
end
end
## first we transfer all the AgentIDs for which we need the state
# for sending them via AllToAll we flatten the perPE structure
asvec = map(s -> collect(s), filter(! isempty, perPE))
sendbuf = if ! isempty(asvec)
VBuffer(reduce(vcat, asvec),
[ length(perPE[i]) for i in 1:mpi.size ])
else
VBuffer(Vector{AgentID}(), [ 0 for _ in 1:mpi.size ])
end
# transmit the number of AgentIDs the current PE want to
# send to the other PEs
sendNumElems = [ length(perPE[i]) for i in 1:mpi.size ]
recvNumElems = MPI.Alltoall(UBuffer(sendNumElems, 1), mpi.comm)
# with this information we can prepare the receive buffer
recvbuf = MPI.VBuffer(Vector{AgentID}(undef, sum(recvNumElems)),
recvNumElems)
# transmit the AgentIDs itself
_log_time(sim, "transmit_agents Alltoallv! AgentIDs", true) do
MPI.Alltoallv!(sendbuf, recvbuf, mpi.comm)
end
## now we gather the agentstate
send = if $mortal
if ! isempty(recvbuf.data)
map(recvbuf.data) do id
(id,
@readdied($T)[agent_nr(id)],
@readstate($T)[agent_nr(id)])
end
else
Vector{Tuple{AgentID, Bool, $T}}()
end
else
if ! isempty(recvbuf.data)
map(recvbuf.data) do id
(id, @readstate($T)[agent_nr(id)])
end
else
Vector{Tuple{AgentID, $T}}()
end
end
## and send this back
# recvNumElems will be now sendNumElems and vis a vis
sendbuf = VBuffer(send, recvNumElems)
recv = if $mortal
Vector{Tuple{AgentID, Bool, $T}}(undef, sum(sendNumElems))
else
Vector{Tuple{AgentID, $T}}(undef, sum(sendNumElems))
end
recvbuf = VBuffer(recv, sendNumElems)
_log_time(sim, "transmit_agents Alltoallv! state", true) do
MPI.Alltoallv!(sendbuf, recvbuf, mpi.comm)
end
## And now fill the foreign dictonaries
if $mortal
for (id, died, state) in recvbuf.data
@agent($T).foreigndied[id] = died
@agent($T).foreignstate[id] = state
end
else
for (id, state) in recvbuf.data
@agent($T).foreignstate[id] = state
end
end
@agent($T).last_transmit[ET] = sim.num_transitions
end
end
_log_debug(sim, "<End> transmit_agents!")
end
end
function construct_mpi_edge_methods(T::DataType, typeinfos, simsymbol, CE)
attr = typeinfos.edges_attr[T]
ignorefrom = :IgnoreFrom in attr[:hints]
singleedge = :SingleEdge in attr[:hints]
singletype = :SingleType in attr[:hints]
stateless = :Stateless in attr[:hints]
ST = Vector{Tuple{AgentID, CE}}
# typeid = typeinfos.edges_type2id[T]
# For sending the edges we need different versions, depending on the
# edge hints, as e.g. for the :HasEdgeOnly or :NumEdgeOnly we
# transfer only the number of edges. In overall, when we iterate over
# the container, we get the following values:
# | | Statel. | Ignore | get edges via | sending (ST below) |
# |--------------------+---------+--------+---------------+--------------------|
# | (Vector){Edge{$T}} | | | edges | [(toid, Edge{$T})] |
# | (Vector){AgentID} | x | | neighborids | [(toid, fromid)] |
# | (Vector){$T} | | x | edgestates | [(toid, $T)] |
# | Int64 | x | x | num_edges | num_edges |
@eval function sendedges!(sim::$simsymbol, sendmap::Dict{AgentID, ProcessID},
idmapping, ::Type{$T})
with_logger(sim) do
@debug "<Begin> sendedges!" edgetype=$T
end
if $singletype
AT = sim.typeinfos.edges_attr[$T][:target]
agent_typeid = sim.typeinfos.nodes_type2id[AT]
end
ST = Vector{Tuple{AgentID, sim.typeinfos.edges_attr[$T][:containerelement]}}
# We construct for each PE a vector with all the edges (incl. toid) that
# should be transmit to the PE
perPE = [ ST() for _ in 1:mpi.size ]
# The iterator for the edges depends on the hints of the edgetype
if $stateless && $ignorefrom
iter = @edgeread($T)
if $singletype
iter = enumerate(iter)
end
else
iter = edges_iterator(sim, $T)
end
# we now iterate over the edges and add them to the perPE vector
# that corresponds to the process id given in the sendmap for the
# target of the edge
for (to, e) in iter
id = if $singletype
agent_id(agent_typeid, AgentNr(to))
else
to
end
# in the default finish_init! case with an initialization
# that does not care about mpi.isroot, we have edges on
# all ranks, but on the sendmap there are only the edges
# of rank 0, as this are the only edges we want to distribute
if haskey(sendmap, id)
# in the SingleType version, we also get entries with 0 edges
# we skip them, there is no need to use bandwith for that
if $stateless && $ignorefrom && e == 0
continue
end
push!(perPE[sendmap[id]], (id, e))
end
end
updateid(id::AgentID) = idmapping[id] |> AgentID
edges_alltoall!(sim, perPE, $T, updateid)
with_logger(sim) do
@debug "<End> sendedges!"
end
end
# updateid is a func that update the ids of the agents, for the case
# that the ids have changed in the distribution process.
@eval function edges_alltoall!(sim::$simsymbol, perPE, ::Type{$T},
updateid = identity)
with_logger(sim) do
@debug "<Begin> edges_alltoall!" edgetype=$T
end
# we call add_edge! but add_edge! has an check that we
# are in the initialization phase or in a transition function.
# So we set the intranstion flag, is necessary
wasintransition = sim.intransition
sim.intransition = true
waswriteable = edge_attrs(sim, $T)[:writeable]
edge_attrs(sim, $T)[:writeable] = true
# for sending them via AllToAll we flatten the perPE structure
longvec = reduce(vcat, perPE)
sendbuf = if length(longvec) > 0
VBuffer(longvec, [ length(perPE[i]) for i in 1:mpi.size ])
else
VBuffer($ST(), [ 0 for _ in 1:mpi.size ])
end
# transmit the number of edges the current PE want to send to the
# other PEs
sendNumElems = [ length(perPE[i]) for i in 1:mpi.size ]
recvNumElems = MPI.Alltoall(UBuffer(sendNumElems, 1), mpi.comm)
# with this information we can prepare the receive buffer
recvbuf = MPI.VBuffer($ST(undef, sum(recvNumElems)),
recvNumElems)
# transmit the edges itself
MPI.Alltoallv!(sendbuf, recvbuf, mpi.comm)
# In the case that the edgetype count only the number of edges, write
# this number directly into the edges container of the receiving PE
if $stateless && $ignorefrom
for (to, numedges) in recvbuf.data
up = if $singletype
updateid(to) |> agent_nr
else
updateid(to)
end
_check_size!(@edgewrite($T), up, $T)
if $singleedge
@inbounds @edgewrite($T)[up] = true
else
if $singletype || haskey(@edgewrite($T), up)
@inbounds @edgewrite($T)[up] += numedges
else
@inbounds @edgewrite($T)[up] = numedges
end
end
end
# Else iterate of the received edges and add them via add_edge!
elseif $stateless
for (to, from) in recvbuf.data
add_edge!(sim, updateid(from), updateid(to), $T())
end
elseif $ignorefrom
for (to, edgestate) in recvbuf.data
# fromid will be ignored, so we use an dummy id
add_edge!(sim, AgentID(0), updateid(to), edgestate)
end
else
for (to, edge) in recvbuf.data
add_edge!(sim, updateid(to), Edge(updateid(edge.from),
edge.state))
end
end
@edge($T).last_transmit = sim.num_transitions
sim.intransition = wasintransition
edge_attrs(sim, $T)[:writeable] = waswriteable
_log_debug(sim, "<End> edges_alltoall!")
nothing
end
@eval function removeedges_alltoall!(sim::$simsymbol, perPE, ::Type{$T})
with_logger(sim) do
@debug "<Begin> removeedges_alltoall!" edgetype=$T
end
# we call remove_edges! but remove_edges! has an check that we
# are in the initialization phase or in a transition function.
# So we set the intranstion flag, is necessary
wasintransition = sim.intransition
sim.intransition = true
waswriteable = edge_attrs(sim, $T)[:writeable]
edge_attrs(sim, $T)[:writeable] = true
# for sending them via AllToAll we flatten the perPE structure
longvec = reduce(vcat, perPE)
sendbuf = if length(longvec) > 0
VBuffer(longvec, [ length(perPE[i]) for i in 1:mpi.size ])
else
VBuffer($ST(), [ 0 for _ in 1:mpi.size ])
end
# transmit the number of edges the current PE want to send to the
# other PEs
sendNumElems = [ length(perPE[i]) for i in 1:mpi.size ]
recvNumElems = MPI.Alltoall(UBuffer(sendNumElems, 1), mpi.comm)
# with this information we can prepare the receive buffer
recvbuf = MPI.VBuffer(fill((0,0), sum(recvNumElems)),
recvNumElems)
# transmit the information about the removed edge itself
MPI.Alltoallv!(sendbuf, recvbuf, mpi.comm)
for (source, target) in recvbuf.data
target = AgentID(target)
@mayassert process_nr(target) == mpi.rank
if source == 0
remove_edges!(sim, target, $T)
else
remove_edges!(sim, AgentID(source), target, $T)
end
end
sim.intransition = wasintransition
edge_attrs(sim, $T)[:writeable] = waswriteable
_log_debug(sim, "<End> removeedges_alltoall!")
nothing
end
end
# Join a vector that is distributed over serveral processes. vec can be [].
#
# # Example
# rank 0: vec = [1, 2]
# rank 1: vec = []
# rank 2: vec = [4]
#
# join(vec) returns [1, 2, 4] on all ranks
function join(vec::Vector{T}) where T
# transfer the vector sizes
sizes = Vector{Int32}(undef, mpi.size)
sizes[mpi.rank + 1] = length(vec)
send = MPI.VBuffer(sizes, fill(Int32(1), mpi.size),
fill(Int32(mpi.rank), mpi.size))
recv = MPI.VBuffer(sizes, fill(Int32(1), mpi.size))
MPI.Alltoallv!(send, recv, mpi.comm)
sizes = recv.data
# transfer the vector itself
displace = append!([0], cumsum(sizes)[1 : length(sizes) - 1])
values = Vector{T}(undef, sum(sizes))
values[displace[mpi.rank+1] + 1 : displace[mpi.rank+1] + sizes[mpi.rank+1]] = vec
send = MPI.VBuffer(values,
fill(Int32(sizes[mpi.rank + 1]), mpi.size),
fill(Int32(displace[mpi.rank + 1]), mpi.size))
recv = MPI.VBuffer(values, sizes)
MPI.Alltoallv!(send, recv, mpi.comm)
recv.data
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 846 | using MPI
export mpi
mutable struct VMPI
comm
rank::Int64
size::Int64
isroot::Bool
active::Bool
# shm stands for shared memory
shmcomm
shmrank::Int64
shmsize::Int64
# node
node::Int64
end
const mpi = VMPI(nothing, 0, 0, false, false, nothing, 0, 0, 0)
function mpiinit()
MPI.Init(;threadlevel = :single)
mpi.comm = MPI.COMM_WORLD
mpi.rank = MPI.Comm_rank(mpi.comm)
mpi.size = MPI.Comm_size(mpi.comm)
mpi.isroot = mpi.rank == 0
mpi.active = mpi.size > 1
mpi.shmcomm = MPI.Comm_split_type(mpi.comm, MPI.COMM_TYPE_SHARED, 0)
mpi.shmrank = MPI.Comm_rank(mpi.shmcomm)
mpi.shmsize = MPI.Comm_size(mpi.shmcomm)
(mpi.node, rank) = fldmod(mpi.rank, mpi.shmsize)
# check that the ranks are really distributed as expected
@assert mpi.shmrank == rank
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 10653 | export ModelTypes
export register_agenttype!, register_edgetype!, register_param!, register_global!
Base.@kwdef struct Param{T}
name::Symbol
default_value::T
end
Base.@kwdef struct Global{T}
name::Symbol
init_value::T
end
#Param(name, default::T) where T = Param{T}(name, default, default)
"""
ModelTypes
This struct stores all (internal) information about the agent and edge
types of the model and is therefore the starting point of the model
definition.
Call the ModelType constructor without parameters, and then use the
created object as the first parameter in [`register_agenttype!`](@ref)
and [`register_edgetype!`](@ref), whereby the |> operator can be used to
concatenate these registrations.
See also [`create_model`](@ref),
"""
Base.@kwdef struct ModelTypes
edges_attr = Dict{DataType, Dict{Symbol, Any}}()
edges_types = Vector{DataType}()
nodes_attr = Dict{DataType, Dict{Symbol, Any}}()
nodes_types = Vector{DataType}()
nodes_type2id::Dict{DataType, TypeID} = Dict{DataType, TypeID}()
nodes_id2type::Vector{DataType} = Vector{DataType}(undef, MAX_TYPES)
params::Vector{Param} = Vector{Param}()
globals::Vector{Global} = Vector{Global}()
end
"""
Model
A Model instance is created by [`create_model`](@ref) and can then be
used to create one or multiple simulations via [`create_simulation`](@ref).
"""
struct Model
types::ModelTypes
name::String
immortal::Vector{Bool}
end
"""
register_agenttype!(types::ModelTypes, ::Type{T}, [hints...])
Register an additional agent type to `types`.
An agent type is a struct that define the state space for agents of type `T`.
These structs must be "bits types", meaning the type is immutable and
contains only primitive types and other bits types.
By default, it is assumed that an agent can die (be removed from the
simulation) by returning `nothing` in the transition function (see
[`apply!`](@ref). In the case that agents are never removed, the hint
:Immortal can be given to improve the performance of the simulation.
If agents of this type never access the state of other agents of the
same type in a transition function (e.g., via agentstate or neighborstates
calls), then the :Independent hint can be given. This avoids
unnecessary copies of the agents.
A pipeable version of `register_agenttype!` is also available,
enabling the construction of a Model via a sequence of `register_*`
calls. This pipeline starts with `ModelTypes()` as the source and
terminates in the [`create_model`](@ref) function as the destination.
See also [`add_agent!`](@ref) and [`add_agents!`](@ref)
"""
function register_agenttype!(types::ModelTypes, ::Type{T}, hints...) where T
@assert !(Symbol(T) in types.nodes_types) "Type $T is already registered"
@assert isbitstype(T) "Agenttypes $T must be bitstypes"
type_number = length(types.nodes_type2id) + 1
@assert type_number < MAX_TYPES "Can not add new type,
maximal number of types already registered"
push!(types.nodes_types, T)
types.nodes_type2id[T] = type_number
types.nodes_id2type[type_number] = T
types.nodes_attr[T] = Dict{Symbol,Any}()
hints = Set{Symbol}(hints)
for hint in hints
@assert hint in [:Immortal, :Independent] """\n
The agent type hint $hint is unknown for type $T. The following hints are
supported:
:Immortal
:Independent
"""
end
types.nodes_attr[T][:hints] = hints
types
end
register_agenttype!(t::Type{T}) where T = types -> register_agenttype!(types, t)
register_agenttype!(t::Type{T}, hints...; kwargs...) where T =
types -> register_agenttype!(types, t, hints...; kwargs...)
"""
register_edgetype!(types::ModelTypes, ::Type{T}, [hints...; kwargs...])
Register an additional edge type to `types`.
An edge type T is a structure that defines the state (field) of
[`Edge{T}`](@ref). These structs must be "bit types", that is, the
type is immutable and contains only primitive types and other bit
types. Often these types T are stateless, in which case they are used
as a tag to distinguish between the existing types of edges of the
model.
The internal data structures used to store the graph in memory can be modified by
the hints parameters:
- `:IgnoreFrom`: The ID of the source agent is not stored. This
implies that the state of the agents on the source of the edge is
not accessible via e.g. the [`neighborstates`](@ref) function.
- `:Stateless`: Store only the ID of the source agent.
- `:SingleType`: All target agents have the same type, needs also keyword
`target` (see below).
- `:SingleEdge`: Each agent can be the target for max. one edge.
- `:IgnoreSourceState`: The ID of the source agent is not used to
access the state of the agent with this ID.
- `:NumEdgesOnly`: Combines `:IgnoreFrom` and `:Stateless`
- `:HasEdgeOnly`: Combines `:IgnoreFrom`, `:Stateless` and `:SingleEdge`
If `:SingleType` is set, the keyword argument `target` must be
added. The value of this argument must be the type of the target
node. If the `target` keyword exists, but the `:SingleType` hint is
not explicitly specified, it will be set implicitly
If it is known how many agents of this type exist, this can also be
specified via the optional `size` keyword. This can improve
performance, but can also increase the memory usage.
A pipeable version of `register_edgetype!` is also available,
enabling the construction of a Model via a sequence of `register_*`
calls. This pipeline starts with `ModelTypes()` as the source and
terminates in the [`create_model`](@ref) function as the destination.
See also [Edge Hints](./performance.md#Edge-Hints), [`add_edge!`](@ref) and
[`add_edges!`](@ref)
"""
function register_edgetype!(types::ModelTypes, ::Type{T}, hints...;
kwargs...) where T
@assert !(T in types.edges_types) "Type $T is already registered"
@assert isbitstype(T) "Edgetypes $T must be bitstypes"
push!(types.edges_types, T)
types.edges_attr[T] = kwargs
hints = Set{Symbol}(hints)
for hint in hints
@assert hint in [:Stateless, :IgnoreFrom, :SingleEdge, :SingleType,
:NumEdgesOnly, :HasEdgeOnly, :IgnoreSourceState] """
The edge type hint $hint is unknown for type $T. The following hints are
supported:
:Stateless
:IgnoreFrom
:SingleEdge
:SingleType
:NumEdgesOnly (which is equal to :Stateless & :IgnoreFrom)
:HasEdgeOnly (which is equal to :Stateless & :IgnoreFrom & :SingleEdge)
:IgnoreSourceState
"""
end
if :NumEdgesOnly in hints
union!(hints, Set([:Stateless, :IgnoreFrom]))
end
if :HasEdgeOnly in hints
union!(hints, Set([:Stateless, :IgnoreFrom, :SingleEdge]))
end
if :SingleType in hints
@assert haskey(kwargs, :target) """
For type $T the :SingleType hint is set, but in this
case the agent type must also be specified via the
target keyword.
"""
end
if haskey(kwargs, :target) && !(:SingleType in hints)
if ! config.quiet
@rootonly printstyled("""
Since the `target` keyword exists for type $T, the :SingleType hint is added for this type.
"""; color = :red)
end
push!(hints, :SingleType)
end
if fieldcount(T) == 0 && !(:Stateless in hints)
if config.detect_stateless
union!(hints, Set([:Stateless]))
elseif ! config.quiet
@rootonly printstyled("""
Edgetype $T is a struct without any field, so you can increase the
performance by setting the :Stateless hint. You can also
calling detect_stateless() before calling register_edgetype!,
then the :Stateless hint will be set automatically for structs without
a field.
"""; color = :red)
end
end
@assert !(:SingleType in hints && :SingleEdge in hints &&
!(:Stateless in hints && :IgnoreFrom in hints)) """\n
The hints :SingleEdge and :SingleType can be only combined
when the type $T has also the hints :Stateless and :IgnoreFrom.
"""
types.edges_attr[T][:hints] = hints
types
end
register_edgetype!(t::Type{T}, props...; kwargs...) where T =
types -> register_edgetype!(types, t, props...; kwargs...)
has_hint(sim, T::DataType, hint::Symbol, ge = :Edge) =
if ge == :Edge
hint in sim.typeinfos.edges_attr[T][:hints]
elseif ge == :Agent
hint in sim.typeinfos.nodes_attr[T][:hints]
else
@error "Unknown graph element, use :Agent or :Edge"
end
"""
register_param!(types::ModelTypes, name::Symbol, default_value::T)
There are two ways to set up parameters for a simulation. Either the
instance of a struct defined by the modeler must be passed via the `param`
argument to [`create_simulation`](@ref), or the individual parameters
are passed using `register_param!` before [`create_model`](@ref) is
called. The parameters can also be set after
[`create_simulation`](@ref) and before [`finish_init!`](@ref) is
called.
A pipeable version of `register_param!` is also available,
enabling the construction of a Model via a sequence of `register_*`
calls. This pipeline starts with `ModelTypes()` as the source and
terminates in the [`create_model`](@ref) function as the destination.
"""
function register_param!(types::ModelTypes, name::Symbol, default_value::T) where T
push!(types.params, Param{T}(name, default_value))
types
end
register_param!(name, default_value::T) where T =
types -> register_param!(types, name, default_value)
"""
register_global!(types::ModelTypes, name::Symbol, default_value::T)
There are two ways to set up globals for a simulation. Either the
instance of a struct defined by the modeler must be passed via the `globals`
argument to [`create_simulation`](@ref), or the individual parameters
are passed using `register_global!` before [`create_model`](@ref) is
called.
A pipeable version of `register_global!` is also available,
enabling the construction of a Model via a sequence of `register_*`
calls. This pipeline starts with `ModelTypes()` as the source and
terminates in the [`create_model`](@ref) function as the destination.
"""
function register_global!(types::ModelTypes, name::Symbol, init_value::T) where T
push!(types.globals, Global{T}(name, init_value))
types
end
register_global!(name, init_value::T) where T =
types -> register_global!(types, name, init_value)
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 14539 | export num_edges
export show_agent
using Printf
######################################## <: EdgeState
function Base.show(io::IO, mime::MIME"text/plain", edge::Edge{T}) where {T}
show(io, mime, edge.from)
if fieldnames(T) != ()
print(io, ": ")
show(io, mime, edge.state)
end
end
######################################## Model
function Base.show(io::IO, ::MIME"text/plain", model::Model)
printstyled(io, "\nModel Name: ", model.name; color = :magenta)
nodes_types = model.types.nodes_types
if length(nodes_types) >= 1
printstyled(io, "\nAgent(s):"; color = :cyan)
end
for T in nodes_types
node_hints = model.types.nodes_attr[T][:hints]
firsthint = true
print(io, "\n\t Type $T")
for k in node_hints
if firsthint
firsthint = false
printstyled(io, " with Hint(s): ")
print(io, "$k")
else
print(io, ", $k")
end
end
end
edges_types = model.types.edges_types
if length(edges_types) >= 1
printstyled(io, "\nEdge(s):"; color = :cyan)
end
for T in edges_types
edge_hints = model.types.edges_attr[T][:hints]
firsthint = true
print(io, "\n\t Type $T")
for k in edge_hints
if firsthint
firsthint = false
printstyled(io, " with Hint(s): ")
print(io, "$k")
else
print(io, ", $k")
end
end
if :SingleType in edge_hints
print(io, "{$(model.types.edges_attr[T][:target])}")
end
end
params = model.types.params
if length(params) >= 1
printstyled(io, "\nParameter(s) with default values:"; color = :cyan)
end
for param in model.types.params
print(io, "\n\t$(param.name): $(param.default_value)")
end
globals = model.types.globals
if length(globals) >= 1
printstyled(io, "\nGlobal(s) with init values:"; color = :cyan)
end
for g in model.types.globals
print(io, "\n\t$(g.name): $(g.init_value)")
end
end
######################################## Simulation
function construct_prettyprinting_methods(simsymbol)
@eval function Base.show(io::IO, ::MIME"text/plain", sim::$simsymbol)
function show_agent_types(io::IO, sim)
nodes_types = sim.typeinfos.nodes_types
if length(nodes_types) >= 1
printstyled(io, "\nAgent(s):"; color = :cyan)
end
for t in nodes_types
print(io, "\n\t Type $t \
with $(num_agents(sim, t)) agent(s)")
if mpi.active
print(io, " ($(num_agents(sim, t, false)) on rank $(mpi.rank))")
end
end
end
function show_edge_types(io::IO, sim)
edges_types = sim.typeinfos.edges_types
if length(edges_types) >= 1
printstyled(io, "\nEdge(s):"; color = :cyan)
end
for t in edges_types
edgetypehints = sim.typeinfos.edges_attr[t][:hints]
if (:SingleEdge in edgetypehints &&
:SingleType in edgetypehints) ||
(:SingleType in edgetypehints &&
:size in keys(sim.typeinfos.edges_attr[t]))
print(io, "\n\t Type $t with edge(s) for $(num_edges(sim, t)) agent(s)")
else
print(io, "\n\t Type $t \
with $(num_edges(sim, t)) edge(s)")
if mpi.active
print(io, " ($(num_edges(sim, t, false)) on rank $(mpi.rank))")
end
if ! (:SingleType in edgetypehints)
print(io, " for $(_show_num_a_with_e(sim, t)) agent(s)")
if mpi.active
print(io, " on this rank")
end
end
end
end
end
function show_raster(io::IO, s)
if length(s.rasters) >= 1
printstyled(io, "\nRaster(s):"; color = :cyan)
for (k,v) in sim.rasters
# print(io, "\n\t $k: $(getfield(s, k))")
print(io, "\n\t :$k with dimension $(size(v))")
end
end
end
function show_struct(io::IO, s, name)
if nfields(s) >= 1
printstyled(io, "\n$(name)(s):"; color = :cyan)
for k in typeof(s) |> fieldnames
f = getfield(s, k)
if typeof(f) <: Array
if length(f) == 0
print(io, "\n\t :$k (empty)")
else
print(io, "\n\t :$k |> last : $(last(f)) (length: $(length(f)))")
end
printstyled(io, " "; color = :yellow)
else
print(io, "\n\t :$k : $f")
end
end
end
end
printstyled(io, "\nModel Name: ", sim.model.name; color = :magenta)
printstyled(io, "\nSimulation Name: ", sim.name; color = :magenta)
show_agent_types(io, sim)
show_edge_types(io, sim)
show_struct(io, sim.params, "Parameter")
show_raster(io, sim)
# print(io, "Globals: ", sim.globals)
show_struct(io, sim.globals, "Global")
if ! sim.initialized
printstyled(io, "\nStill in initialization process!.", color = :red)
end
end
end
######################################## Collections
# In the :IgnoreFrom case we set edge.from to 0.
function _reconstruct_edge(sim, e, edgetypehints, edgeT)
if :Stateless in edgetypehints
if :IgnoreFrom in edgetypehints
Edge(AgentID(0), edgeT())
else
Edge(e, edgeT())
end
elseif :IgnoreFrom in edgetypehints
Edge(AgentID(0), e)
else
e
end
end
function _show_edge(sim, e, neighborstate, edgeT)
function show_struct(s)
if nfields(s) >= 1
for k in typeof(s) |> fieldnames
if neighborstate == true || k in neighborstate
f = getfield(s, k)
print(" $k=$f,")
end
end
end
end
edgetypehints = sim.typeinfos.edges_attr[edgeT][:hints]
e = _reconstruct_edge(sim, e, edgetypehints, edgeT)
if !(:IgnoreFrom in edgetypehints) && e.from == 0
return
end
print("\n\t")
if :IgnoreFrom in edgetypehints
print("unknown ")
else
_printid(e.from)
end
if ! (:Stateless in edgetypehints)
print(" $(e.state)")
end
if (neighborstate == true || length(neighborstate) > 0) &&
!has_hint(sim, edgeT, :IgnoreFrom)
# for the to edges we get an empty edgetype hints, as we constructed
# those edges they don't have the same hints
# But here we need the original hints, so we access them directly
if has_hint(sim, edgeT, :SingleType)
agentT = sim.typeinfos.edges_attr[edgeT][:target]
aid = agent_id(sim.typeinfos.nodes_type2id[agentT], agent_nr(e.from))
# We disable assertions to call agentstate from the REPL
# but this is only done temporary and in a newer world age
show_struct(Base.invokelatest(agentstate, sim, aid, agentT))
# print(" $(Base.invokelatest(agentstate, sim, aid, agentT))")
else
show_struct(Base.invokelatest(agentstate_flexible, sim, e.from))
# print(" $(Base.invokelatest(agentstate_flexible, sim, e.from))")
end
end
end
########################################
function _show_num_a_with_e(sim, ::Type{T}) where T
if !sim.initialized
"$(length(edgewrite(sim, T)))"
else
"$(length(edgeread(sim, T)))"
end
end
# as a convention, we print only "complete" agentid as hex
function _printid(id, nrformatted = true)
if typeof(id) == UInt32 || agent_nr(AgentID(id)) == id
if nrformatted
Printf.@printf "%18i" id
else
print(id)
end
else
Printf.@printf "0x%016x" id
end
end
"""
show_agent(sim, Type{T}, [id=0; max=5, neighborstate = []])
show_agent(sim, id=0; [max=5, neighborstate = []])
Display detailed information about the agent with ID `id`, or in the
case that id is a value < 2^36, the information of the nth agent of
type T. If `id` is 0 (the default value), a random agent of type T is
selected.
Returns the ID of the agent (which is especially useful when a random
agent is selected).
Keyword arguments:
`max` controls the maximal number of edges that are shown per network
(per direction).
If a field of an agent on the source side of an edge is listed in the
`neighborstate` vector, the value of this field will be also shown.
"""
function show_agent(sim::Simulation,
t::Type{T},
id = 0;
max::Int = 5,
neighborstate = []) where T
if !sim.initialized
println("show_agent can not be called before finish_init!.")
return
end
# find a random agent if no id is given (and no agent will ever have id 0
if id == 0
agents = readstate(sim, T) |> keys
if ! has_hint(sim, T, :Immortal, :Agent)
field = getproperty(sim, Symbol(T))
agents = [ a for a in agents if ! field.read.died[a] ]
end
if length(agents) == 0
println("No agent of type $T found.")
return
end
id = rand(agents)
end
# we want to access the agentstate outside of a transition function,
# assuming the the id is existing on the node
assert_state = asserting()
enable_asserts(false)
typeid = sim.typeinfos.nodes_type2id[T]
# id can be always the local nr, so we first ensure that id
# is the complete agent_id
id = if id <= 2 ^ BITS_AGENTNR
agent_id(typeid, AgentNr(id))
else
AgentID(id)
end
# first we print the id of the agent and the state of the agent
printstyled("Id / Local Nr: "; color = :cyan)
_printid(id, false)
print(" / $(agent_nr(id))")
# the assert modification has a newer world age
as = Base.invokelatest(agentstate, sim, id, t)
if nfields(as) > 0
printstyled("\nState:"; color = :cyan)
fnames = as |> typeof |> fieldnames
for f in fnames
printstyled("\n $f=$(getfield(as, f))")
end
end
# the all the edges for the agent
printstyled("\nEdge(s):"; color = :cyan)
for edgeT in sim.typeinfos.edges_types
edgeTheadershown = false
read_container = edgeread(sim, edgeT)
edgetypehints = sim.typeinfos.edges_attr[edgeT][:hints]
justcount = :IgnoreFrom in edgetypehints && :Stateless in edgetypehints
if (:SingleEdge in edgetypehints &&
:SingleType in edgetypehints &&
!justcount)
printstyled("\n\tIt is not possible to give reliable information " *
"about the edges of the agent when the\n\tcorresponding edgetype " *
"has the :SingleEdge and :SingleType hint combination.";
color = :red)
continue
end
# The agent_nr(id) returns wrong ids when used for agent of
# a differnt type then given in :target, so we must check this
if (!(:SingleType in edgetypehints) ||
T == sim.typeinfos.edges_attr[edgeT][:target])
# unify the agentid. For vector (:SingleAgent) types, this must
# be the index, and for dict types, the AgentID
aid = agent_id(sim.typeinfos.nodes_type2id[T], agent_nr(id))
nid = :SingleType in edgetypehints ? agent_nr(id) : aid
# this rather complex statement checks that the agent has
# edges of this type towards him. In the :SingleType case we
# check the vector for #undef entries, in the other case we use haskey
if (!(:SingleType in edgetypehints &&
!isassigned(read_container, nid)) &&
(:SingleType in edgetypehints ||
haskey(read_container, nid)))
# output the network name and derive some information
printstyled("\n $edgeT"; color = :yellow)
edgeTheadershown = true
d = read_container[nid]
if justcount
if :SingleEdge in edgetypehints
printstyled("\n\thas_edge: "; color = :green)
print("$(has_edge(sim, aid, edgeT))")
else
printstyled("\n\tnum_edges: "; color = :green)
print("$(num_edges(sim, aid, edgeT))")
end
else
# write the header for this edgetype,
printstyled("\n\tfrom: "; color = :green)
if ! (:Stateless in edgetypehints)
printstyled("edge.state:"; color = :green)
elseif neighborstate == true || length(neighborstate) > 0
printstyled("state of edge.from:"; color = :green)
end
if :SingleEdge in edgetypehints
_show_edge(sim, d, neighborstate, edgeT)
else
for e in first(d, max)
_show_edge(sim, e, neighborstate, edgeT)
end
if length(d) > max
println("\n\t... ($(length(d)-max) not shown)")
end
end
end
end
end
end
println()
# set this back to the state at the beginning of the function
enable_asserts(assert_state)
id
end
function show_agent(sim::Simulation, id; kwargs...)
# we call AgentID so that id can be also a signed value, or lower then 64bit
show_agent(sim, type_of(sim, AgentID(id)), id; kwargs...)
nothing
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 17265 | import LinearAlgebra
import StatsBase: sample, Weights
export add_raster!, connect_raster_neighbors!
export calc_raster, calc_rasterstate, rastervalues, move_to!, cellid
export random_pos, random_cell
"""
add_raster!(sim, name::Symbol, dims::NTuple{N, Int}, agent_constructor)
Adds a n-dimensional grid to `sim`, with the dimensions `dims`.
For each cell a new node/agent is added to the graph. To create the
agent, the `agent_constructor` function is called, with the cell position in
form of an `CartesianIndex` as argument.
The symbol `name` is an identifier for the created raster, as it is allowed
to add multiple rasters to `sim`.
The types of the agents created by the `agent_constructor` must be
already registered via [`register_agenttype!`](@ref).
Returns a vector with the IDs of the created agents.
Can be only called before [`finish_init!`](@ref).
See also [`calc_raster`](@ref) [`connect_raster_neighbors!`](@ref) and
[`move_to!`](@ref).
"""
function add_raster!(sim,
name::Symbol,
dims::NTuple{N, Int},
agent_constructor) where N
with_logger(sim) do
@info "<Begin> add_raster!" name dims
end
@assert ! sim.initialized "add_raster! can be only called before finish_init!"
grid = Array{AgentID, N}(undef, dims)
positions = CartesianIndices(dims)
nodeids = add_agents!(sim, [ agent_constructor(pos) for pos in positions ])
for (id, pos) in zip(nodeids, positions)
grid[pos] = id
end
_log_info(sim, "<End> add_raster!")
sim.rasters[name] = grid
end
# while distributing the Agents to the different PEs, the AgentIDs are
# changed, so the ids of the grid most be updated
function broadcastids(sim, raster, idmapping::Dict)
with_logger(sim) do
@info "<Begin> broadcastids" raster
end
if mpi.isroot
MPI.Bcast!(Ref(ndims(sim.rasters[raster])), MPI.COMM_WORLD)
MPI.Bcast!(Ref(size(sim.rasters[raster])), MPI.COMM_WORLD)
sim.rasters[raster] = map(id -> idmapping[id], sim.rasters[raster])
MPI.Bcast!(sim.rasters[raster], MPI.COMM_WORLD)
else
rndims = Ref{Int}()
MPI.Bcast!(rndims, MPI.COMM_WORLD)
rsize = Ref{NTuple{rndims[], Int64}}()
MPI.Bcast!(rsize, MPI.COMM_WORLD)
sim.rasters[raster] = Array{AgentID}(undef, rsize[])
MPI.Bcast!(sim.rasters[raster], MPI.COMM_WORLD)
end
_log_info(sim, "<End> broadcastids")
end
function _stencil_core(metric, n::Int64, distance, d::Int64)
@assert metric in [ :chebyshev, :euclidean, :manhatten ]
stencil = Iterators.product([ (-d):d for _ in 1:n ]...) |> collect
stencil = reshape(stencil, length(stencil))
# remove the zero point from the list, as we do not want to create loops
filter!(s -> s !== Tuple(zeros(Int64, n)), stencil)
if metric == :euclidean
filter!(s -> LinearAlgebra.norm(s) <= distance, stencil)
elseif metric == :manhatten
filter!(s -> mapreduce(abs, +, s) <= distance, stencil)
end
map(CartesianIndex, stencil)
end
const stencil_cache = Dict{Tuple{Symbol, Int64, Int64}, Array{CartesianIndex}}()
function stencil(metric, n::Int64, distance::Int64)
get!(stencil_cache, (metric, n, distance)) do
_stencil_core(metric, n, distance, distance)
end
end
function stencil(metric, n::Int64, distance::Float64)
d = distance |> floor |> Int
_stencil_core(metric, n, distance, d)
end
"""
connect_raster_neighbors!(sim, name::Symbol, edge_constructor; [distance::Int, metric:: Symbol, periodic::Bool])
All cells that are at most `distance` from each other (using the metric
`metric`) are connected with edges, where the edges are created with
the `edge_constructor`.
The `edge_constructor` must be a function with one argument with type
Tuple{CartesianIndex, CartesianIndex}. The first CartesianIndex is the
position of the source node, and the second CartesianIndex the
position of the target node.
Valid metrics are :chebyshev, :euclidean and :manhatten.
The keyword periodic determines whether all dimensions are cyclic
(e.g., in the two-dimensional case, the raster is a torus).
The default values of the optional keyword arguments are 1 for
`distance`, :chebyshev for `metric` and true for `periodic`. which is
equivalent to a Moore neighborhood. The :manhatten metric can be
used to connect cells in the von Neumann neighborhood.
The agent types of agents created by the `agent_constructor` must be
already registered via [`register_agenttype!`](@ref).
See also [`add_raster!`](@ref)
"""
function connect_raster_neighbors!(sim,
name::Symbol,
edge_constructor;
distance = 1,
metric::Symbol = :chebyshev,
periodic = true)
with_logger(sim) do
@info "<Begin> connect_raster_neighbors!" name
end
# before a simulation is initialized, the raster existing
# only on the root
if mpi.isroot || sim.initialized
raster = sim.rasters[name]
dims = size(raster)
st = stencil(metric, ndims(raster), distance)
for org in keys(raster)
for s in st
shifted = _checkpos(org + s, dims, periodic)
if ! isnothing(shifted)
add_edge!(sim, raster[org], raster[shifted],
edge_constructor(org, shifted))
end
end
end
end
_log_info(sim, "<End> connect_raster_neighbors!")
end
"""
calc_raster(sim, raster::Symbol, f, f_returns::DataType, accessible::Vector{DataType})
Calculate values for the raster `raster` by applying `f` to each
cell ID of the cells constructed by the `add_raster!` function.
`f_returns` must be the type returned by the function f. There must be an
implementation of the zero function for this type, and zero(returntype) | f(id)
must be equal to f(id).
`accessible` is a vector of Agent and/or Edge types. This vector must
list all types that are accessed directly (e.g. via
[`agentstate`](@ref) or indirectly (e.g. via [`neighborstates`](@ref)
in the transition function.
If the results of `calc_raster` depend only on the state of the cells
(as in the following example) and all cells have the same type,
[`calc_rasterstate`](@ref) can be used as concise alternatives.
Returns a n-dimensional array (with the same dimensions as `raster`)
with those values.
Example:
The following code from a "Game of Life" implementation generates a
boolean matrix indicating which cells are alive (and therefore
maps the internal graph structure to the usual representation of a
cellular automaton):
```@example
calc_raster(sim, :raster, id -> agentstate(sim, id, Cell).active, Bool, [ Cell ])
```
Can be only called after [`finish_init!`](@ref).
See also [`add_raster!`](@ref) and [`calc_rasterstate`](@ref)
"""
function calc_raster(sim::Simulation, raster::Symbol, f, f_returns::DataType,
accessible::Vector{DataType})
with_logger(sim) do
@info "<Begin> calc_raster!" raster
end
@assert sim.initialized "calc_raster can be only called after finish_init!"
ids = sim.rasters[raster]
idsvec = reshape(ids, length(ids))
onprocess = Vector{Tuple{Int64, f_returns}}()
foreach(T -> prepare_read!(sim, Vector{DataType}(), T), accessible)
for (idx, id) = enumerate(ids)
if process_nr(id) == mpi.rank
push!(onprocess, (idx, f(id)))
end
end
foreach(T -> finish_read!(sim, T), accessible)
all = join(onprocess)
resvec = zeros(f_returns, length(idsvec))
for (idx, val) in all
resvec[idx] = val
end
_log_info(sim, "<End> calc_raster!")
reshape(resvec, size(sim.rasters[raster]))
end
calc_raster(f, sim::Simulation, raster::Symbol, f_returns::DataType,
accessible::Vector{DataType}) =
calc_raster(sim, raster, f, f_returns, accessible)
"""
calc_rasterstate(sim, raster::Symbol, f, f_returns::DataType = Nothing, ::Type{T} = Nothing)
Combined calc_raster with agentstate for the cells of the raster.
Calculate values for the raster `raster` by applying `f` to the state of each
cell.
`f_returns` must be the type returned by the function f. There must be an
implementation of the zero function for this type, and
zero(returntype) + f(state) must be equal to f(state). In the event
that all cells in the raster returns the same `DataType`, `f_returns`
can be set to `Nothing`, in which case `f_returns` is automatically
derived.
`T` can be set to `Nothing`, this decreases the performance, but is
necessary in the unusual case that a raster contains different types of
agents (in this case `agentstate_flexible` is used instead of
`agentstate`).
Returns a n-dimensional array (with the same dimensions as `raster`)
with those values.
Example:
Instead of
```@example
calc_raster(sim, :raster, id -> agentstate(sim, id, Cell).active, Bool, [ Cell ])
```
it also possible to just write
```@example
calc_rasterstate(sim, :raster, c -> c.active, Bool, Cell)
```
Can be only called after [`finish_init!`](@ref).
See also [`add_raster!`](@ref), [`calc_rasterstate`](@ref) and [`rastervalues`](@ref)
"""
function calc_rasterstate(sim, raster::Symbol, f,
f_returns::DataType = Nothing, ::Type{T} = Nothing) where T
with_logger(sim) do
@info "<Begin> calc_rasterstate" raster
end
@assert sim.initialized """
calc_rasterstate can be only called after finish_init!"""
ids = sim.rasters[raster]
idsvec = reshape(ids, length(ids))
disable_transition_checks(true)
if f_returns == Nothing
f_returns = typeof(f(agentstate_flexible(sim, idsvec[1])))
end
onprocess = Vector{Tuple{Int64, f_returns}}()
if T != Nothing
for (idx, id) = enumerate(ids)
if Vahana.process_nr(id) == mpi.rank
push!(onprocess, (idx, f(agentstate(sim, id, T))))
end
end
else
for (idx, id) = enumerate(ids)
if Vahana.process_nr(id) == mpi.rank
push!(onprocess, (idx, f(agentstate_flexible(sim, id))))
end
end
end
disable_transition_checks(false)
all = join(onprocess)
resvec = zeros(f_returns, length(idsvec))
for (idx, val) in all
resvec[idx] = val
end
_log_info(sim, "<End> calc_rasterstate")
reshape(resvec, size(sim.rasters[raster]))
end
"""
rastervalues(sim, raster::Symbol, fieldname::Symbol)
Creates a matrix with the same dims as the raster `raster` with the
values of the field `fieldnames`. All cells of the raster must have
the same type, and also a `zeros` function must exist for the type of `fieldnames`.
Example:
Instead of
```@example
calc_rasterstate(sim, :raster, c -> c.active, Bool, Cell)
```
it also possible to just write
```@example
rastervalues(sim, :raster, :active)
```
Can be only called after [`finish_init!`](@ref).
See also [`add_raster!`](@ref) and [`calc_rasterstate`](@ref)
"""
function rastervalues(sim, raster::Symbol, field::Symbol)
with_logger(sim) do
@info "<Begin> calc_rasterstate" raster
end
@assert sim.initialized """
rastervalues can be only called after finish_init!"""
ids = sim.rasters[raster]
idsvec = reshape(ids, length(ids))
T = type_of(sim, ids[1,1])
f_returns = fieldtype(T, field)
onprocess = Vector{Tuple{Int64, f_returns}}()
disable_transition_checks(true)
for (idx, id) = enumerate(ids)
if Vahana.process_nr(id) == mpi.rank
push!(onprocess, (idx, getproperty(agentstate(sim, id, T), field)))
end
end
disable_transition_checks(false)
all = join(onprocess)
resvec = zeros(f_returns, length(idsvec))
for (idx, val) in all
resvec[idx] = val
end
_log_info(sim, "<End> calc_rasterstate")
reshape(resvec, size(sim.rasters[raster]))
end
###
###
"""
cellid(sim, name::Symbol, pos)
Returns the ID of the agent (node) from the raster `name` at the
position `pos`. `pos` must be of type CartesianIndex or a Dims{N}.
See also [`add_raster!`](@ref), [`move_to!`](@ref),
[`add_edge!`](@ref) and [`agentstate`](@ref)
"""
function cellid(sim, name::Symbol, pos)
sim.rasters[name][CartesianIndex(pos)]
end
"""
move_to!(sim, name::Symbol, id::AgentID, pos, edge_from_raster, edge_to_raster; [distance = 0, metric = :chebyshev, periodic = true])
Creates up to two edges of type between the agent with ID `id` and the cell from the raster `name` at the position `pos`.
`pos` must be of type CartesianIndex or a Dims{N}.
`edge_from_raster` is the edge that will be added with the cell as
source node and the agent as target node. `edge_from_raster` can be
`nothing`, in this case no edge will be added with the agent as target
node.
`edge_to_raster` is the edge that will be added with the agent as
source node and the cell as target node. `edge_to_raster` can be
`nothing`, in this case no edge will be added with the agent as source
node.
Using the keyword arguments, it is possible to add additional edges to
the surroundings of the cell at position `pos` in the same raster,
i.e. to all cells at distance `distance` under metric `metric`, where
valid metrics are :chebyshev, :euclidean and :manhatten`. And the
keyword `periodic` determines whether all dimensions are cyclic.
See also [`add_raster!`](@ref) and [`connect_raster_neighbors!`](@ref)
"""
function move_to!(sim,
name::Symbol,
id::AgentID,
pos,
edge_from_raster,
edge_to_raster;
distance = 0,
metric::Symbol = :chebyshev,
periodic = true)
# before a simulation is initialized, the raster existing
# only on the root
if mpi.isroot || sim.initialized
raster = sim.rasters[name]
dims = size(raster)
pos = CartesianIndex(pos)
if ! isnothing(edge_from_raster)
add_edge!(sim, raster[pos], id, edge_from_raster)
end
if ! isnothing(edge_to_raster)
add_edge!(sim, id, raster[pos], edge_to_raster)
end
if distance >= 1
for s in stencil(metric, ndims(raster), distance)
shifted = _checkpos(CartesianIndex(pos) + s, dims, periodic)
if ! isnothing(shifted)
if ! isnothing(edge_from_raster)
add_edge!(sim, raster[shifted], id, edge_from_raster)
end
if ! isnothing(edge_to_raster)
add_edge!(sim, id, raster[shifted], edge_to_raster)
end
end
end
end
end
end
function _checkpos(pos::CartesianIndex, dims, periodic)
cpos = Array{Int64}(undef, length(dims))
outofbounds = false
for i in 1:length(dims)
if pos[i] < 1 || pos[i] > dims[i]
outofbounds = true
cpos[i] = mod1(pos[i], dims[i])
else
cpos[i] = pos[i]
end
end
if ! outofbounds
pos
else
if periodic
CartesianIndex(cpos...)
else
nothing
end
end
end
"""
random_pos(sim, raster::Symbol, weights::Matrix)
Return a CartesianIndex with random position coordinates, weighted by a
probability matrix `weights`.
The likelihood of selecting a particular cell/index is proportional
to its corresponding value in the `weights` matrix.
See also [`random_pos(sim, raster)`](@ref) and [`random_cell`](@ref)
"""
function random_pos(sim, raster::Symbol, weights::Array)
dims = size(sim.rasters[raster])
@assert dims == size(weights) """
`weights` must have the same dimension as the raster :$(raster)
"""
W = Weights(vec(weights))
positions = CartesianIndices(dims) |> collect
positions[sample(eachindex(positions), W)]
end
"""
random_pos(sim, raster::Symbol)
Return a CartesianIndex with random position coordinates.
The returned index is sampled from the rasters indizies where each
index has the same probability.
See also [`random_pos(sim, raster, weights)`](@ref) and
[`random_cell`](@ref)
"""
function random_pos(sim, raster::Symbol)
dims = size(sim.rasters[raster])
positions = CartesianIndices(dims) |> collect
positions[sample(eachindex(positions))]
end
"""
random_cell(sim, raster::Symbol)
Return a random cell id of the raster `raster` from the
simulation `sim`.
"""
function random_cell(sim, name::Symbol)
rand(sim.rasters[name])
end
"""
random_cell(sim, raster::Symbol, weights::Array)
Return a random cell id of the raster `raster` from the simulation
`sim`. The likelihood of selecting a particular cell is proportional
to its corresponding value in the `weights` matrix.
See also [`random_cell(sim, raster)`](@ref) and [`random_pos`](@ref)
"""
function random_cell(sim, raster::Symbol, weights::Array)
W = Weights(vec(weights))
sample(vec(sim.rasters[raster]), W)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 29971 | import Base.deepcopy
import Logging.with_logger
import Graphs.nv
using DataFrames
export create_model
export create_simulation, finish_simulation!, copy_simulation
export finish_init!
export apply, apply!
export param, set_param!
export mapreduce
# this is mutable, as we assign write -> read in finish_write!
mutable struct AgentReadWrite{T}
state::Vector{T}
# This is a Vector of rows (AgentNr) that can be reused for the
# next agents. It is redudant to died: died[e in reuseable] == true
# Also this field is for immortal agents always just an empty vector
reuseable::Vector{AgentNr}
# This field is for immortal agents always just an empty vector
died::Vector{Bool}
end
AgentReadWrite(T::DataType) =
AgentReadWrite{T}(Vector{T}(), Vector{AgentNr}(), Vector{Bool}())
mutable struct MPIWindows
# Access via shared memory
shmstate::Union{MPI.Win, Nothing}
shmdied::Union{MPI.Win, Nothing}
# we are between prepare_read! and finished_mpi!
prepared::Bool
end
MPIWindows() = MPIWindows(nothing, nothing, false)
mutable struct AgentFields{T}
read::AgentReadWrite{T}
write::AgentReadWrite{T}
# the state of all agents on the same node
shmstate::Vector{Vector{T}}
# the died flag of all agents on the same node
shmdied::Vector{Vector{Bool}}
# the state of agents on others nodes
foreignstate::Dict{AgentID, T}
# the died flag of agents on other nodes
foreigndied::Dict{AgentID, Bool}
nextid::AgentNr
mpiwindows::MPIWindows
# the last time (in number of transitions called) that the agentstate
# was send due to the evaluation of an specific edgetype
last_transmit::Dict{DataType, Int64}
# the last time that the agenttype was writable
last_change::Int64
end
AgentFields(T::DataType) =
AgentFields(AgentReadWrite(T), # read
AgentReadWrite(T), # write
[ Vector{T}() for _ in 1:mpi.shmsize ], #shmstate
[ Vector{Bool}() for _ in 1:mpi.shmsize ], #shmdied
Dict{AgentID, T}(), # foreignstate
Dict{AgentID, Bool}(), # foreigndied
AgentNr(1), #nextid
MPIWindows(),
Dict{DataType, Int64}(), #last_transmit
0) #last_change
mutable struct EdgeFields{ET, EST}
read::ET
write::ET
# when a edge is added with target-agents on a different process
# it is stored here
storage::EST
# store which edges must be removed on other processes,
# first UInt64 is the source, second UInt64 the target
# the source is set to 0 if all edges of the target should be removed.
# the vector index is the rank+1 of the target agent.
removeedges::Vector{Vector{Tuple{AgentID, AgentID}}}
# this tracks edges with source-agents on a different node, the
# outer vector is the agenttype nr, the middle vector the process
# index. It's possible that the sets are containing agents that
# are died in the meantime, as edges/fromids can not be removed
# from the sets, only the complete sets are resetted when the
# edgetype is rewritten.
accessible::Vector{Vector{Set{AgentID}}}
# the last time (in number of transitions called) that the storage
# (incl. removeedges) was send to the other processes (via edges_alltoall!)
last_transmit::Int64
# the last time that the edgetype was writable
last_change::Int64
# is set to true, when this field is in the read vector of a
# transition function
readable::Bool
# here we track the agent on the target side of the edges, so
# that in a case that an agent died, we can call
# remove_edges! for the edges with the died agent at the source
# position. We create a dict entry only for agents that are mortal.
agentsontarget::Dict{AgentID, Vector{AgentID}}
end
"""
create_model(types::ModelTypes, name::String)
Creates a struct that is a subtype of the `Simulation` type and methods
corresponding to the type information of `types` to the Julia
session. The new structure is named `name`, and all methods are
specific to this structure using Julia's multiple dispatch concept, so
it is possible to have different models in the same Julia session (as
long as `name` is different).
Returns a [`Model`](@ref) that can be used in
[`create_simulation`](@ref) to create a concrete simulation.
"""
function create_model(typeinfos::ModelTypes, name::String)
simsymbol = Symbol(name)
edgefields = [
Expr(Symbol("="),
:($(Symbol(T))::EdgeFields{$(edgefield_type(T, typeinfos.edges_attr[T])),
$(edgestorage_type(T, typeinfos.edges_attr[T]))}),
:(EdgeFields($(edgefield_constructor(T, typeinfos.edges_attr[T])),
$(edgefield_constructor(T, typeinfos.edges_attr[T])),
$(edgestorage_type(T, typeinfos.edges_attr[T])()),
Vector{Tuple{AgentID, AgentID}}[],
[ [ Set{AgentID}() for _ in 1:mpi.size ] for _ in 1:MAX_TYPES ],
0,0,false,
Dict{AgentID, Vector{AgentID}}())))
for T in typeinfos.edges_types ]
nodefields = [
Expr(Symbol("="),
:($(Symbol(T))::AgentFields{$T}),
:(AgentFields($T)))
for T in typeinfos.nodes_types ]
fields = Expr(:block,
:(model::Model),
:(name::String),
:(filename::String),
:(overwrite_file::Bool),
:(params::P),
:(globals::G),
:(globals_last_change::Int64),
:(typeinfos::ModelTypes),
:(rasters::Dict{Symbol, Array}),
:(initialized::Bool),
:(intransition::Bool),
# after a transition this is the next transition nr
# in a transtion this is the current transtion nr
:(num_transitions::Int64),
:(logger::Log),
:(h5file::Union{HDF5.File, Nothing}),
:(external::Dict{Any, Any}),
edgefields...,
nodefields...)
# the true in the second arg makes the struct mutable
strukt = Expr(:struct, true, :($simsymbol{P, G} <: Simulation), fields)
kwdefqn = QuoteNode(Symbol("@kwdef"))
# nothing in third argument is for the expected LineNumberNode
# see also https://github.com/JuliaLang/julia/issues/43976
Expr(:macrocall, Expr(Symbol("."), :Base, kwdefqn), nothing, strukt) |> eval
immortal = [ :Immortal in typeinfos.nodes_attr[T][:hints]
for T in typeinfos.nodes_types ]
# Construct all type specific functions for the edge typeinfos
for T in typeinfos.edges_types
construct_edge_methods(T, typeinfos, simsymbol, immortal)
end
# Construct all type specific functions for the agent typeinfos
for T in typeinfos.nodes_types
construct_agent_methods(T, typeinfos, simsymbol)
end
construct_prettyprinting_methods(simsymbol)
### Parameters
paramfields = [
Expr(Symbol("="),
:($(param.name)::$(typeof(param.default_value))),
:($(param.default_value)))
for param in typeinfos.params ]
# the true in the second arg makes the struct mutable
paramstrukt = Expr(:struct, true, :($(Symbol("Params_" * String(simsymbol)))),
Expr(:block, paramfields...))
Expr(:macrocall, Expr(Symbol("."), :Base, kwdefqn), nothing, paramstrukt) |> eval
### Globals
globalfields = [
Expr(Symbol("="),
:($(g.name)::$(typeof(g.init_value))),
:($(g.init_value)))
for g in typeinfos.globals ]
# the true in the second arg makes the struct mutable
globalstrukt = Expr(:struct, true, :($(Symbol("Globals_" * String(simsymbol)))),
Expr(:block, globalfields...))
Expr(:macrocall, Expr(Symbol("."), :Base, kwdefqn), nothing, globalstrukt) |> eval
Model(typeinfos, name, immortal)
end
num_agenttypes(sim) = length(sim.typeinfos.nodes_types)
"""
create_simulation(model::Model, [params = nothing, globals = nothing; name = model.name, filename = name, overwrite_file = true, logging = false, debug = false])
Creates and return a new simulation object, which stores the complete state
of a simulation.
`model` is an `Model` instance created by [`create_model`](@ref).
`params` must be a struct (or `nothing`) that contains all parameters of a
simulation. Parameter values are constant in a simulation run and can be
retrieved via the [`param`](@ref) function.
`globals` must be a mutable struct (or `nothing`). The values of these fields are
accessible for all agents via the [`get_global`](@ref) function. The values can
be changed by calling [`set_global!`](@ref) or [`push_global!`](@ref).
The optional keyword argument `name` is used as meta-information about
the simulation and has no effect on the dynamics, since `name` is not
accessible in the transition functions. If `name` is not given, the
name of the model is used instead.
The optional `filename` keyword is a string that will be used as the
name of the hdf5 file when a simulation or a part of it is written via
e.g. [`write_snapshot`](@ref).
The file is created when a `write...` function is called for the first time,
and it is created in an `h5` subfolder. By default an existing file
with the same `filename` will be overwritten, but this behavior can be
disabled with the `overwrite_file` keyword, in which case the files
will be numbered. If `filename` is not provided, the `name` argument
is used instead.
The keywords `logging` is a boolean flag that enables an automatical
log file. The log file contains information such as the time spent in
different functions. When also `debug` is set to true, the log file
contains more details and the stream will be flushed after each write.
As with the hdf5 files, overwrite_file `the` keyword determines
whether the log files are overwritten or numbered. The numbering is
set independently from the numbering of the hdf5 files.
The simulation starts in an uninitialized state. After adding the
agents and edges for the initial state, it is necessary to call
[`finish_init!`](@ref) before applying a transition function for the first
time.
See also [`create_model`](@ref), [`param`](@ref),
[`get_global`](@ref), [`set_global!`](@ref), [`push_global!`](@ref)
and [`finish_init!`](@ref)
"""
function create_simulation(model::Model,
params::P = nothing,
globals::G = nothing;
name = model.name,
filename = name, overwrite_file = true,
logging = false, debug = false) where {P, G}
simsymbol = Symbol(model.name)
# Since v1.1 params and globals should be added to the model
# via register_param! and register_global!
# But to be backward compatible, it's still possible to
# use own Param and Global Structs
pstrukt = eval(Symbol("Params_" * model.name))
@assert(params === nothing || fieldcount(pstrukt) == 0, """\n
You can not use `register_param!` and the `param` argument of
`create_simulation` at the same time.
""")
params = if fieldcount(pstrukt) == 0
params
else
deepcopy(pstrukt())
end
gstrukt = eval(Symbol("Globals_" * model.name))
@assert(globals === nothing || fieldcount(gstrukt) == 0, """\n
You can not use `register_globals!` and the `global` argument of
`create_simulation` at the same time.
""")
globals = if fieldcount(gstrukt) == 0
globals
else
deepcopy(gstrukt())
end
sim::Simulation = @eval $(Symbol(model.name))(
model = $model,
name = $name,
filename = $filename,
overwrite_file = $overwrite_file,
params = $params,
globals = $globals,
globals_last_change = 0,
typeinfos = $(model.types),
rasters = Dict{Symbol, Array}(),
initialized = false,
intransition = false,
num_transitions = 0,
logger = create_logger($name, $logging, $debug, $overwrite_file),
h5file = nothing, # we need the sim instance to create the h5file
# allows the client to attach arbitrary information, that will
# be removed in finish_simulation.
external = Dict{Any, Any}()
)
for T in sim.typeinfos.edges_types
init_field!(sim, T)
init_storage!(sim, T)
end
for T in sim.typeinfos.nodes_types
init_field!(sim, T)
end
global show_second_edge_warning = true
with_logger(sim) do
@info "New simulation created" name params date=Dates.now() starttime=time()
end
sim
end
# pipeable versions
create_model(name::String) = types -> create_model(types, name)
create_simulation(params::P = nothing,
globals::G = nothing;
kwargs...) where {P, G} =
model -> create_simulation(model, params, globals; kwargs...)
function _create_equal_partition(part_dict, ids)
# Partitions a sequence into `n` nearly equally sized blocks.
function partition(seq, n::Int)
s, r = divrem(length(seq), n)
[ ((i - 1) * s + 1 + min(i - 1, r)) : (i * s + min(i, r)) for i in 1:n ]
end
ps = partition(1:length(ids), mpi.size)
for (i, range) in enumerate(ps)
for idx in range
part_dict[ids[idx]] = i
end
end
end
"""
finish_init!(sim::Simulation; [distribute = true,
partition::Dict{AgentID, ProcessID},
partition_algo = :Metis])
Finish the initialization phase of the simulation.
`partition` is an option keyword and allows to specify an assignment
of the agents to the individual MPI ranks. The dictonary must contain
all agentids created on the rank as key, the corresponding value is
the rank on which the agent "lives" after `finish_init!`.
In the case that no `partition` is given and `distribute` is set to true,
the Graph will be partitioned with the given `partition_algo`. Currently
two algorithms are supported:
- :Metis uses the Metis library for the graph partitioning.
- :EqualAgentNumbers just ensures that per agent type more or less
the same number of agents are distributed to each process.
`finish_init!` must be called before applying a transition function.
!!! info
When a simulation is run on multiple PEs, per default the graph
found on rank 0 will be partitioned using Metis, and distributed
to the different ranks. Which means that it's allowed to run the
initialization phase on all ranks (there is no need for a
mpi.isroot check), but then all added agents and edges on other
ranks then 0 will be discarded. If this is not intended
`distribute` must be set to false.
See also [`register_agenttype!`](@ref), [`register_edgetype!`](@ref),
[`apply!`](@ref) and [`finish_simulation!`](@ref)
"""
function finish_init!(sim;
partition = Dict{AgentID, ProcessID}(),
return_idmapping = false, partition_algo = :Metis, distribute = true)
@assert ! sim.initialized "You can not call finish_init! twice for the same simulation"
_log_info(sim, "<Begin> finish_init!")
foreach(finish_write!(sim), keys(sim.typeinfos.nodes_type2id))
foreach(finish_write!(sim), sim.typeinfos.edges_types)
if distribute
idmapping = if mpi.size > 1
# we are creating an own partition only when no partition is given
if length(partition) == 0 && mpi.isroot
if partition_algo == :Metis
_log_info(sim, ">>> Partitioning the Simulation with Metis")
vsg = _log_time(sim, "create simple graph", true) do
vahanasimplegraph(sim; show_ignorefrom_warning = false)
end
part = _log_time(sim, "call Metis.partition", true) do
# it's possible to load the graph after the initialization
# in this case we have nothing to partition here.
if Graphs.nv(vsg) > 0
Metis.partition(vsg, mpi.size; alg = :RECURSIVE)
end
end
_log_debug(sim, "<Begin> remap ids")
for (i, p) in enumerate(part)
partition[vsg.g2v[i]] = p
end
_log_debug(sim, "<End> remap ids")
elseif partition_algo == :EqualAgentNumbers
_log_info(sim, ">>> Partitioning the Simulation / equal number of nodes per type")
_log_debug(sim, "<Begin> create equal partitions")
for T in sim.typeinfos.nodes_types
ids = map(i -> agent_id(sim, AgentNr(i), T),
keys(readstate(sim, T)))
_create_equal_partition(partition, ids)
end
_log_debug(sim, "<End> create equal partitions")
else
@error "the partition_algo given is unknown"
end
end
if mpi.isroot
_log_info(sim, ">>> Distributing the Simulation")
end
_log_time(sim, "distribute!") do
distribute!(sim, partition)
end
else
if return_idmapping
idmapping = Dict{AgentID, AgentID}()
for T in sim.typeinfos.nodes_types
for id in keys(readstate(sim, T))
aid = agent_id(sim, AgentNr(id), T)
idmapping[aid] = aid
end
end
idmapping
else
nothing
end
end
foreach(finish_write!(sim), sim.typeinfos.nodes_types)
foreach(finish_write!(sim), sim.typeinfos.edges_types)
end
sim.initialized = true
sim.num_transitions = 1
_log_info(sim, "<End> finish_init!")
distribute && return_idmapping ? idmapping : nothing
end
# this function is not exported and should be only used for unit tests
function updateids(idmap, oldids)
map(oldids) do id
idmap[Vahana.remove_process(id)]
end
end
"""
copy_simulation(sim)
Create an independent copy of the simulation `sim`. Since part of the
memory is allocated via MPI, you should not use deepcopy.
Also, the copy is detached from any output or logger file so that not
sim and copy tried to write to the same file(s). If these are needed,
you can create these files for the copy by calling
[`create_h5file!`](@ref) and/or [`create_logger!`](@ref) and assigning
the results to the h5file/logging field of the returned simulation.
Returns the copy of the simulation.
"""
function copy_simulation(sim)
copy = deepcopy(sim)
# we also copied the MPI windows, so the copy points to the same
# memory as the original. So this needs to be fixed.
foreach(T -> copy_shm!(copy, T), sim.typeinfos.nodes_types)
copy.h5file = nothing
# disable logging for the copy
copy.logger = create_logger(sim.name, false, false, sim.overwrite_file)
copy
end
function _free_memory!(sim)
for T in sim.typeinfos.nodes_types
shmstatewin = getproperty(sim, Symbol(T)).mpiwindows.shmstate
if ! isnothing(shmstatewin)
MPI.free(shmstatewin)
end
shmdiedwin = getproperty(sim, Symbol(T)).mpiwindows.shmdied
if ! isnothing(shmdiedwin)
MPI.free(shmdiedwin)
end
init_field!(sim, T)
end
for T in sim.typeinfos.edges_types
empty!(edgeread(sim, T))
empty!(edgewrite(sim, T))
end
empty!(sim.rasters)
end
"""
finish_simulation!(sim)
Remove all agents/edges and rasters from the simulation to minimize
the memory footprint. The `parameters` and `globals` of the simulation
are still available, the remaining state of the simulation is
undefined.
Returns the globals of the simulation.
"""
function finish_simulation!(sim)
_log_info(sim, "<Begin> finish_simulation!")
_free_memory!(sim)
close_h5file!(sim)
empty!(sim.external)
_log_info(sim, "<End> finish_simulation!")
if sim.logger.file !== nothing
close(sim.logger.file)
end
MPI.Barrier(MPI.COMM_WORLD)
sim.globals
end
######################################## Transition
"""
param(sim::Simulation, name)
Returns the value of the field `name` of the `params` struct from the
Simulation constructor.
See also [`create_model`](@ref)
"""
param(sim, name) = getfield(sim.params, name)
"""
set_param!(sim::Simulation, param::Symbol, value)
Assign the specified `value` to the `param` parameter. This operation
is only allowed prior to calling the `finish_init!` method.
A pipeable version of `set_param!` is also available.
"""
function set_param!(sim::Simulation, param::Symbol, value)
@assert !sim.initialized """\n
You can call `set_param!` only before `finish_init!`. For values that
change while the simulation is running, register them as globals and use
`set_global!` instead.
"""
setfield!(sim.params, param, value)
end
function set_param!(param::Symbol, value)
sim -> begin
set_param!(sim, param, value)
sim
end
end
function maybeadd(coll,
id,
agent)
# the coll[id] writes into another container then
# we use for the iteration
@inbounds coll[id] = agent
nothing
end
function maybeadd(_,
::AgentNr,
::Nothing)
nothing
end
prepare_write!(sim, read, add_existing) =
t -> prepare_write!(sim, read, t in add_existing, t)
finish_write!(sim) = t -> finish_write!(sim, t)
isiterable(v) = applicable(iterate, v)
"""
apply!(sim, func, call, read, write; [add_existing, with_edge])
Apply the transition function `func` to the simulation state.
`call` must be a single agent type or a collection of agent types,
likewise `read` and `write` must be a single agent/edge type or a
collection of agent/edge types.
`call` determines for which agent types the transition function `func`
is called. Within the transition function, an agent has access to the
state of agents (including its own state) and to edges only if
their types are in the `read` collection. Accordingly, the agent
can change its own state and/or create new agents or edges only if
their types are in the `write` collection.
Assume that T is an agent type that is in `call`. In case T is also in
`read`, the transition function must have the following signature:
`transition_function(agent::T, id, sim)`, where the type declaration
of agent is optional if `call` contains only a single type. If T is
not in `read`, it must have the signature `transition_function(::Val{T},
id::AgentID, sim::Simulation)`.
If T is in `write`, the transition function must return either an agent of type T
or `nothing`. If `nothing` is returned, the agent will be removed from
the simulation, otherwise the agent with id `id` will get the returned
state after the transition function was called for all agents.
When an edge state type is in `write`, the current edges of that type
are removed from the simulation. If you want to keep the existing
edges for a specific type, you can add this type to the optional
`add_existing` collection.
Similarly, agent types that are in the `write` but not in the `call`
argument can be part of the `add_existing` collection, so that the
existing agents of this type are retained and can only be added. For
agent types in `call`, however, this is achieved by returning their
state in the transition function.
With the keyword `with_edge` it is possible to restrict the set of
agents for which the transition function is called to those agents who are on
the target side of edges of the type `with_edge`. So
```
apply!(sim, AT, ET, []) do _, id, sim
if has_edge(sim, id, ET)
do_something
end
end
```
is equivalent to
```
apply!(sim, AT, ET, []; with_edge = ET) do _, id, sim
do_something
end
```
but saves all the `has_edge` checks.
This `with_edge` keyword should only be set when a small subset of
agents possess edges of this particular type, as performance will be
adversely impacted in other scenarios. Also the keyword can only be
used for edgetypes without the :SingleType hint.
See also [`apply`](@ref) and the [Applying Transition Function section
in the tutorial](tutorial1.md#Applying-Transition-Functions)
"""
function apply!(sim::Simulation,
func::Function,
call,
read,
write;
add_existing = [],
with_edge = nothing)
@assert sim.initialized "You must call finish_init! before apply!"
@assert with_edge === nothing || !has_hint(sim, with_edge, :SingleType) """
The `with_edge` keyword can only be used for edgetypes without the
:SingleType hint.
"""
with_logger(sim) do
@info "<Begin> apply!" func transition=sim.num_transitions+1
end
# must be set to true before prepare_read! (as this calls add_edge!)
sim.intransition = true
# Do allow also just use a single type as argument, we check this
# here and convert the single type to a vector if necessary
call = applicable(iterate, call) ? call : [ call ]
read = applicable(iterate, read) ? read : [ read ]
write = applicable(iterate, write) ? write : [ write ]
add_existing = applicable(iterate, add_existing) ?
add_existing : [ add_existing ]
for c in call
@assert ! (c in add_existing) "$c can not be element of `add_existing`"
end
for ae in add_existing
@assert ae in write "$ae is in `add_existing` but not in `write`"
end
readableET = filter(w -> w in sim.typeinfos.edges_types, read)
foreach(T -> prepare_read!(sim, read, T), readableET)
readableAT = filter(w -> w in sim.typeinfos.nodes_types, read)
foreach(T -> prepare_read!(sim, read, T), readableAT)
writeableAT = filter(w -> w in sim.typeinfos.nodes_types, write)
writeableET = filter(w -> w in sim.typeinfos.edges_types, write)
for T in writeableET
if ! (T in add_existing)
empty!(agentsontarget(sim, T))
end
end
foreach(prepare_write!(sim, read, [call; add_existing]), write)
MPI.Barrier(MPI.COMM_WORLD)
for C in call
with_logger(sim) do
@debug "<Begin> tf_call!" agenttype=C transition=sim.num_transitions+1
end
wfunc = C in write ? transition_with_write! : transition_without_write!
if with_edge === nothing
rfunc = C in read ? transition_with_read! : transition_without_read!
rfunc(wfunc, sim, func, C)
else
rfunc = C in read ? transition_with_read_with_edge! :
transition_without_read_with_edge!
rfunc(wfunc, sim, func, C, with_edge)
end
_log_debug(sim, "<End> tf_call!")
end
MPI.Barrier(MPI.COMM_WORLD)
# we first remove all deleted edges, so that we can readd
# new edges to an agent in the SingleEdge case.
# This include the edges of died agents.
foreach(ET -> transmit_remove_edges!(sim, ET), writeableET)
# we must first call transmit_edges, so that they are exists
# on the correct rank instead in @storage, where they are
# not deleted in the case that an agent died
foreach(ET -> transmit_edges!(sim, ET), writeableET)
foreach(T -> finish_read!(sim, T), read)
# then we can call finish_write! for the agents, as this will
# remove the edges where are died agents are involved (and modifies
# EdgeType_write).
foreach(finish_write!(sim), writeableAT)
foreach(finish_write!(sim), writeableET)
sim.intransition = false
# must be incremented after the transition, so that read only
# functions like mapreduce tries to transfer the necessary states
# only once
sim.num_transitions = sim.num_transitions + 1
_log_info(sim, "<End> apply!")
sim
end
function apply!(func::Function,
sim::Simulation,
call,
read,
write;
kwargs ...)
apply!(sim, func, call, read, write; kwargs ...)
end
"""
apply!(sim, func, call, read, write; add_existing)
Call [`apply!`](@ref) with a copy of the simulation so that the
state of `sim` itself is not changed.
Can be very useful during development, especially if Vahana is used in
the REPL. However, for performance reasons, this function should not
be used in the final code.
Returns the copy of the simulation.
See also [`apply!`](@ref)
"""
function apply(sim::Simulation,
func::Function,
call,
read,
write;
kwargs ...)
newsim = copy_simulation(sim)
apply!(newsim, func, call, read, write; kwargs ...)
newsim
end
function apply(func::Function,
sim::Simulation,
call,
read,
write;
kwargs ...)
apply(sim, func, call, read, write; kwargs ...)
end
######################################## mapreduce
import Base.mapreduce
"""
mapreduce(sim, f, op, ::Type{T}; [kwargs ...])
Calculate an aggregated value, based on the state of all agents or
edges of type T.
`f` is applied to all of these agents or edges and then `op` is used to
reduce (aggregate) the values returned by `f`.
mapreduce is calling Base.mapreduce, `f`, `op` and `kwargs` are
passed directly to mapreduce, while `sim` and `T` are used to determine the
iterator.
"""
function mapreduce(::Simulation, f, op, ::Type; kwargs...) end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 4882 | module Vahana
using MPI, Metis, Requires
export enable_asserts, suppress_warnings, detect_stateless
export set_hdf5_path, set_log_path
function __init__()
@require Makie="ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" begin
include("optional/MakieSupport.jl")
end
@require GraphMakie="1ecd5474-83a3-4783-bb4f-06765db800d2" begin
include("optional/GraphMakieSupport.jl")
end
@require DataFrames="a93c6f00-e57d-5684-b7b6-d8193f3e46c0" begin
include("optional/DataFrames.jl")
end
mpiinit()
end
"""
enable_asserts(enable::Bool)
Vahana comes with some internal consistency checks, at the cost of
run-time performance (e.g., in [`agentstate`](@ref) there are checks
that the specified agenttype matches the agent's ID, which creates of
course some overhead). The assertions that could degrade the run
performance can be disabled by calling `enable_asssertions(false)`.
The recommended approach is therefore to leave the assertions enabled
during the development of the model, but to disable them when the
model goes "into production", e.g. before the start of a parameter
space exploration.
"""
function enable_asserts(enable::Bool)
config.asserts_enabled = enable
if enable
@eval asserting() = true
else
@eval asserting() = false
end
end
# making this a function results in code being invalidated and recompiled when
# this gets changed
asserting() = true
macro mayassert(test)
esc(:(if $(@__MODULE__).asserting()
@assert($test)
end))
end
macro mayassert(test, msgs)
esc(:(if $(@__MODULE__).asserting()
@assert($test, $msgs)
end))
end
####################
Base.@kwdef mutable struct VahanaConfig
quiet = false
detect_stateless = false
check_readable = true
asserts_enabled = true
compression_level = 3
# compression is implemented (see HDF5.jl/new_dset), but causes a lot of
# strange problem in combination with HDF5 Parallel. So this is disabled
# by default. Activate this only after careful testing (e.g.
# run the run_mpitests script in Vahana's test folder.
no_parallel_compression = true
hdf5_path = nothing
log_path = nothing
end
const config = VahanaConfig()
"""
suppress_warnings(suppress::Bool)
In some cases Vahana print some hints or warnings to the stdout. This
can be suppressed by calling the `suppress_warnings(true)` function after
importing Vahana.
"""
suppress_warnings = (suppress::Bool) -> config.quiet = suppress
####################
"""
detect_stateless(detect::Bool)
Per default, Vahana expects that the :Stateless hint is set manually.
This design decision was made so as not to confuse users, since then,
for example, the [`edges`](@ref) is not available.
This behaviour can be customized by calling `detect_stateless` before
calling [`register_edgetype!`](@ref).
"""
detect_stateless = (detect::Bool) -> config.detect_stateless = detect
"""
set_compression(level::Int, parallel_hdf5_compression = false)
Set the compression level of HDF5 files.
However, by default, HDF5 datasets are not compressed when the used
HDF5 library supports Parallel HDF5 due to encountered issues. While
the necessary code to compress datasets in the Parallel HDF5 case is
implemented, its activation via the parallel_hdf5_compression argument
is considered experimental and should be used with awareness of
potential risks and the specificities of the HDF5 implementation in
use.
"""
function set_compression(level::Int, parallel_hdf5_compression = false)
config.compression_level = level
config.no_parallel_compression = ! parallel_hdf5_compression
end
"""
set_hdf5_path(path::String)
Specify the path that is used to save and read the hdf5 files. If the
directory does not exist, it is created the first time a file is
written or tried to read.
See also [`create_h5file!`](@ref)
"""
set_hdf5_path = (path::String) -> config.hdf5_path = path
"""
set_log_path(path::String)
Specify the path that is used to save the log files. If the directory
does not exist, it is created the first time a log file is written.
Must be called before [`create_simulation`](@ref). If this is not
done, the log files are written to a subfolder `log` of the current
working directory.
"""
set_log_path = (path::String) -> config.log_path = path
######################################## include all other files
abstract type Simulation end
include("Helpers.jl")
# MPIInit must be included before Agent/Edge, and Agent/Edge before MPI
include("MPIinit.jl")
include("Agent.jl")
include("Edge.jl")
include("MPI.jl")
include("ModelTypes.jl")
include("HDF5.jl")
include("EdgeMethods.jl")
include("AgentMethods.jl")
include("Simulation.jl")
include("Global.jl")
include("EdgeIterator.jl")
include("REPL.jl")
include("Raster.jl")
include("GraphsSupport.jl")
include("Logging.jl")
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 5966 | import DataFrames: DataFrame, subset!, nrow
export DataFrame, GlobalsDataFrame
show_parallel_dataframe_usage_warning = true
"""
DataFrame(sim::Simulation, T::DataType; types = false, localnr = false)
Creates a DataFrame with the current state of agents or edges of type
`T`. By default, the ID columns show the complete
[`AgentID`](@ref). for readability (and the use of
[`show_agent`](@ref)) it may be useful to show only the lowest 36
bits, which gives a much more readable value, by setting the `localnr`
argument to true. Since for edges the type information of the source
and target agents is no longer available in this case, the `types`
argument can be used to create additional columns containing the types
of these agents.
!!! info
`DataFrame` is only available when the DataFrame.jl package is imported
by the model implementation.
!!! warning
In parallel simulations, the `DataFrame` method converts only the
local graph partition (agents or edges) residing on the current
MPI rank. It does not provide a global view of the entire
distributed graph. To obtain a complete list of all agent states
across all ranks, use the [`all_agents`](@ref) function. Similarly, for
edges, use the [`all_edges`](@ref) function to get a global view of all
edges in the distributed graph.
"""
function DataFrame(sim::Simulation, T::DataType; types = false, localnr = false)
if localnr
types = true
end
if mpi.active && mpi.rank == 0 &&
show_parallel_dataframe_usage_warning == true &&
config.quiet == false
print("""
In a parallel simulation, the `DataFrame(sim...)` function call returns only
the agents or edges corresponding to the local graph partition for each
rank.
This warning is displayed once per Julia session and can be suppressed
by invoking `suppress_warnings(true)` after importing the Vahana package.
""")
global show_parallel_dataframe_usage_warning = false
end
df = DataFrame()
tinfos = sim.typeinfos
if T in tinfos.nodes_types # Agents
read = sim.initialized ?
getproperty(sim, Symbol(T)).read :
getproperty(sim, Symbol(T)).write
tid = tinfos.nodes_type2id[T]
df.id = map(nr -> agent_id(tid, agent_nr(AgentID(nr))),
1:length(read.state))
if fieldcount(T) > 0
df = hcat(df, DataFrame(read.state))
end
if ! has_hint(sim, T, :Immortal, :Agent)
subset!(df, :id => id -> .! read.died[agent_nr.(id)])
end
if localnr
df.id = map(agent_nr, df.id)
end
elseif T in sim.typeinfos.edges_types # Networks
if sim.initialized
prepare_read!(sim, [], T)
end
read = sim.initialized ?
getproperty(sim, Symbol(T)).read :
getproperty(sim, Symbol(T)).write
# First check the Num/HasNeighborsOnly case
if has_hint(sim, T, :IgnoreFrom) && has_hint(sim, T, :Stateless)
df.to = collect(keys(read))
if has_hint(sim, T, :SingleEdge)
df.has_edge = map(>(0), values(read))
subset!(df, :has_edge => b -> b)
else
df.num_edges = collect(values(read))
subset!(df, :num_edges => n -> n .> 0)
end
else
# for the remaining hints we can use the edges iterator
edges = collect(edges_iterator(sim, T, sim.initialized))
if ! has_hint(sim, T, :IgnoreFrom)
if has_hint(sim, T, :Stateless)
df.from = last.(edges)
else
df.from = map(e -> e.from, last.(edges))
end
end
df.to = first.(edges)
if fieldcount(T) > 0
if ! has_hint(sim, T, :IgnoreFrom)
states = map(e -> e.state, last.(edges))
df = hcat(df, DataFrame(states); makeunique = true)
else
df = hcat(df, DataFrame(last.(edges)); makeunique = true)
end
end
end
# when the SingleType hint is active, we must transform the ids
# from the vector index to the correct agent id
if has_hint(sim, T, :SingleType)
totype = tinfos.edges_attr[T][:target]
totypeid = tinfos.nodes_type2id[totype]
df.to = map(id -> agent_id(totypeid, AgentNr(id)), df.to)
# if ! has_hint(sim, T, :IgnoreFrom)
# df.from = map(id -> agent_id(totypeid, AgentNr(id)), df.from)
# end
end
if types
if ! has_hint(sim, T, :IgnoreFrom)
df.from_type = map(id -> tinfos.nodes_id2type[type_nr(id)],
df.from)
end
df.to_type = map(id -> tinfos.nodes_id2type[type_nr(id)], df.to)
end
if localnr
df.to = map(agent_nr, df.to)
if ! has_hint(sim, T, :IgnoreFrom)
df.from = map(agent_nr, df.from)
end
end
if sim.initialized
finish_read!(sim, T)
end
elseif T == typeof(sim.globals)
for i in 1:fieldcount(T)
field = getfield(sim.globals, i)
if typeof(field) <: Vector
if nrow(df) > 0 && nrow(df) != length(field)
# @rootonly printstyled("""
# Length of :$(fieldname(T,i)) does not match the length of the other vectors,
# so this field will not be added to the dataframe
# """; color = :red)
else
df[!,fieldname(T,i)] = field
end
end
end
else
printstyled("Type $T is neither an agent type nor an edge type\n";
color = :red)
end
df
end
GlobalsDataFrame(sim::Simulation) = DataFrame(sim, typeof(sim.globals))
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 11613 | using GraphMakie, Makie, ColorSchemes, Colors
import Graphs, Graphs.SimpleGraphs
export create_graphplot, update_graphplot!
export plot, axis, figure
export clicked_agent
Base.@kwdef mutable struct VahanaPlot
sim::Simulation
vg::VahanaGraph
# a Vahanaplot encapsulate a GraphMakie plot
# figure, axis, plot are all returned by the graphplot function
figure
axis
plot
# the next field are AgentIDs or Edges that where clicked
# or that are actually hovered
clicked_agent = Vector{AgentID}()
# all the agenttypes where the position should be jittered
pos_jitter = Dict{DataType, Float64}()
# the offset of an agent is keeped constant, and stored in this dict
jitter_val = Dict{AgentID, NTuple{2, Float64}}()
# the function to call for updating the attributes of the graph
update_fn = nothing
end
function _set_plot_attrs!(vp, idx, attrs, aid, T)
for (k, v) in attrs
# jitter node positions
if k == :node_pos
j = get(vp.pos_jitter, T, 0.0)
jit = get!(vp.jitter_val, aid, ( rand() * j - j/2, rand() * j - j/2 ))
v = [ v[1] + jit[1], v[2] + jit[2]]
# convert name colors to color values
elseif (k == :node_color || k == :edge_color) &&
(typeof(v) == String || typeof(v) == Symbol)
v = parse(Colorant, v)
# elseif k == :edge_transparency
# # change the
# k = :edge_color
# v = HSLA(HSL(vp.plot[:edge_color][][idx]), v)
end
vp.plot[k][][idx] = v
end
end
function _set_agents_plot_attrs!(f, vp)
disable_transition_checks(true)
changed_attrs = Set{Symbol}()
for T in vp.vg.agenttypes
for id in 1:length(readstate(vp.sim, T))
if length(readdied(vp.sim, T)) == 0 || readdied(vp.sim, T)[id] == false
aid = agent_id(vp.sim, AgentNr(id), T)
state = agentstate(vp.sim, aid, T)
new::Dict{Symbol, Any} = f(state, aid, vp)
_set_plot_attrs!(vp, vp.vg.v2g[aid], new, aid, T)
foreach(a -> push!(changed_attrs, a), keys(new))
end
end
end
for a in changed_attrs
vp.plot[a][] = vp.plot[a][]
end
disable_transition_checks(false)
nothing
end
function _set_edge_plot_properties!(f, vp)
disable_transition_checks(true)
changed_attrs = Set{Symbol}()
for i in 1:Graphs.ne(vp.vg)
tid = vp.vg.edgetypeidx[i]
T = vp.sim.typeinfos.edges_types[tid]
vedge = vp.vg.edges[i]
from = vp.vg.g2v[vedge.src]
to = vp.vg.g2v[vedge.dst]
es = edges(vp.sim, to, T)
if isnothing(es) # this can happen after a state change of sim
continue
end
es = has_hint(vp.sim, T, :Stateless) ? T() : (filter(es) do edge
edge.from == from
end |> only).state
new = f(es, from, to, vp)
_set_plot_attrs!(vp, i, new, 0, T)
foreach(a -> push!(changed_attrs, a), keys(new))
end
for a in changed_attrs
vp.plot[a][] = vp.plot[a][]
end
disable_transition_checks(false)
nothing
end
import Base.display
display(vp::VahanaPlot) = Base.display(vp.figure)
obsrange(x) = 1:length(x)
"""
create_graphplot(sim; [agenttypes, edgestatetypes, update_fn, pos_jitter])
Creates an interactive Makie plot for the the simulation `sim`.
The graph can be restricted to a subgraph with the given `agentypes`
and `edgestatetypes`, see [`vahanagraph`](@ref) for details.
To modify the properties of the edges and agents a `update_fn` can be
defined. This function is called for each agent and edge (of types in agenttypes
and edgestatetypes) and must have for agents the signature
f(state, id, vp::VahanaPlot)
and for edges
f(state, source, target, vp::VahanaPlot)
The arguments of this functions are `state` for the agent or edgestate,
ID for the `id` of the agent called, `from` and `to` for the ID of the
agents at the source or target of the edge. `vp` is the struct
returned by `create_graphplot` and can be used to determine the id of
last clicked agent by calling `clicked_agent(vp)`. The function must
return a Dict with property names (as Symbol) as keys and their values
as values. The following properties are available: `node_color`,
`node_size`, `node_marker`, `nlabels`, `nlabels_align`, `nlabels_color`,
`nlabels_distance`, `nlabels_offset`, `nlabels_textsize`, `edge_color`,
`edge_width`, `elables`, `elables_align`, `elables_color`, `elables_distance`,
`elables_offset`, `elables_rotation`, `elables_shift`, `elables_side`,
`elabes_textsize`, `arrow_shift`, and `arrow_size`.
Returns a VahanaPlot structure that can be used to access the Makie
figure, axis and plot via call to the methods `figure`, `axis` and
`plot` with this struct as (single) argument.
!!! info
`create_graphplot` is only available when the GraphMakie package and a
Makie backend is imported by the client.
!!! warning
For the mouse click and hover interaction, the current state of
the simulation used to construct the VahanaGraph is accessed. In
the case that a transition function is called after the
construction of the VahanaGraph, and this transition function
modifies the structure of the Graph (add/removes nodes or edges),
then this changes are not reflected by the current implementation
and can cause errors.
See also [`vahanagraph`](@ref)
"""
function create_graphplot(sim::Simulation;
agenttypes::Vector{DataType} = sim.typeinfos.nodes_types,
edgetypes::Vector{DataType} = sim.typeinfos.edges_types,
update_fn = nothing,
pos_jitter = nothing)
vg = vahanagraph(sim;
agenttypes = agenttypes,
edgetypes = edgetypes,
drop_multiedges = true)
f, ax, p = _plot(vg)
vp = VahanaPlot(sim = sim,
vg = vg,
figure = f,
axis = ax,
plot = p,
update_fn = update_fn)
if !isnothing(pos_jitter)
vp.pos_jitter = Dict(pos_jitter)
end
function _node_click_action(idx, _, _)
vp.clicked_agent = vg.g2v[idx]
update_graphplot!(vp)
end
register_interaction!(vp.axis,
:nodeclick, NodeClickHandler(_node_click_action))
# if step_fn !== nothing
# f[2, 1] = buttongrid = GridLayout(tellwidth = false)
# buttongrid[1, 1] = resetbutton = Button(f, label="Reset")
# on(resetbutton.clicks) do _
# @info "reset"
# finish_simulation!(vp.sim)
# vp.sim = copy_simulation(vp.original)
# vp.vg = vahanagraph(vp.sim; agenttypes = agenttypes, edgetypes = edgetypes)
# update_graphplot!(vp)
# end
# buttongrid[1, 2] = stepbutton = Button(f, label="Step")
# on(stepbutton.clicks) do _
# step_fn(vp.sim)
# vp.vg = vahanagraph(vp.sim; agenttypes = agenttypes, edgetypes = edgetypes)
# update_graphplot!(vp)
# end
# end
if update_fn === nothing && pos_jitter === nothing
hidedecorations!(vp.axis)
end
update_graphplot!(vp)
end
function update_graphplot!(vp::VahanaPlot)
if ! isnothing(vp.update_fn)
_set_agents_plot_attrs!(vp.update_fn, vp)
_set_edge_plot_properties!(vp.update_fn, vp)
end
autolimits!(vp.axis)
vp
end
figure(vp::VahanaPlot) = vp.figure
axis(vp::VahanaPlot) = vp.axis
plot(vp::VahanaPlot) = vp.plot
clicked_agent(vp::VahanaPlot) = vp.clicked_agent
function _agenttostring(vg, idx)
id = vg.g2v[idx]
disable_transition_checks(true)
as = agentstate_flexible(vg.sim, id)
disable_transition_checks(false)
str = " $(typeof(as)) (Nr: $(Vahana.agent_nr(id)))"
if nfields(as) > 0
fnames = as |> typeof |> fieldnames
for f in fnames
str *= "\n $f=$(getfield(as, f))"
end
end
str
end
function _edgetostring(vg, idx) # from and to are vahanagraph indicies
vedge = vg.edges[idx]
from = vg.g2v[vedge.src]
to = vg.g2v[vedge.dst]
totype = vg.edgetypes[vg.edgetypeidx[idx]]
if :Stateless in vg.sim.typeinfos.edges_attr[totype][:hints]
return string(totype)
end
disable_transition_checks(true)
es = edges(vg.sim, to, totype)
disable_transition_checks(false)
if ! isnothing(es)
es = (filter(es) do edge
edge.from == from
end |> first).state
str = " $(typeof(es))"
if nfields(es) > 0
fnames = es |> typeof |> fieldnames
for f in fnames
str *= "\n $f=$(getfield(es, f))"
end
end
str
else
""
end
end
function _plot(vg::VahanaGraph)
edgecolors = ColorSchemes.glasbey_bw_minc_20_maxl_70_n256
agentcolors = ColorSchemes.glasbey_bw_minc_20_hue_150_280_n256
rv = 1:nv(vg)
re = 1:ne(vg)
p = graphplot(vg,
node_color = [ agentcolors[type_nr(vg.g2v[i])]
for i in rv ],
node_size = [ 12 for _ in rv ],
node_marker = [ :circle for _ in rv ],
# node_attr = [ Dict{Symbol, Observable}() for _ in rv ],
nlabels = [ "" for _ in rv ],
nlabels_align = [ (:left, :bottom) for _ in rv ],
nlabels_color = [ :black for _ in rv ],
nlabels_distance = [ 0.0 for _ in rv ],
nlabels_offset = [ Makie.Point(0, 0) for _ in rv ],
nlabels_textsize = [ 14 for _ in rv ],
edge_color = [ edgecolors[vg.edgetypeidx[i]]
for i in re ],
edge_width = [ 1.0 for _ in re ],
elabels = [ "" for _ in re ],
elabels_align = [ (:left, :bottom) for _ in re ],
elabels_color = [ :black for _ in re ],
elabels_distance = [ 0.0 for _ in re ],
elabels_offset = [ Makie.Point(0, 0) for _ in re ],
elabels_rotation = Vector{Any}([ Makie.automatic for _ in re ]),
elabels_shift = [ 0.5 for _ in re ],
elabels_side = [ :left for _ in re ],
elabels_textsize = [ 14 for _ in re ],
arrow_shift = [ 0.5 for _ in re ],
#arrow_show = [ true for _ in re ], ! supported by Makie
arrow_size = [ 12.0 for _ in re ]
)
# hidedecorations!(p.axis)
hidespines!(p.axis)
function _node_hover_action(state, idx, _, axis)
p.plot.nlabels[][idx] = state ? string(_agenttostring(vg, idx)) : ""
p.plot.nlabels[] = p.plot.nlabels[]
end
register_interaction!(p.axis, :nhover, NodeHoverHandler(_node_hover_action))
function _edge_hover_action(state, idx, _, axis)
p.plot.elabels[][idx] = state ? string(_edgetostring(vg, idx)) : ""
p.plot.elabels[] = p.plot.elabels[]
end
register_interaction!(p.axis, :ehover, EdgeHoverHandler(_edge_hover_action))
p.figure, p.axis, p.plot
end
function nodestate(vg::VahanaGraph, idx::Int64)
disable_transition_checks(true)
s = agentstate_flexible(vg.sim, vg.g2v[idx])
disable_transition_checks(false)
s
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 773 | using Makie
export plot_globals
"""
plot_globals(sim, names::Vector{Symbol})
Creates a Makie lineplot with one line for each global in `names`, wherby
those global values must be Vectors (or Iterable).
Returns figure, axis, plots. `plots` is a vector of Plots, which one plot for
element of `names`.
!!! info
`plot_globals` is only available when a Makie backend is imported
by the client.
See also [`push_global!`](@ref), [`get_global`](@ref)
"""
function plot_globals(sim, names::Vector{Symbol})
f = Figure()
ax = Axis(f[1,1])
plots = Dict{Symbol, Lines}()
for name in names
vals = get_global(sim, name)
plots[name] = lines!(ax, 1:length(vals), vals, label = String(name))
end
axislegend()
f, ax, plots
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 3763 | using Test, Vahana
detect_stateless(true)
struct ComputeAgent end
struct ConstructedAgent end
struct Connection end
function test_model(model)
sim = create_simulation(model)
computeid = add_agent!(sim, ComputeAgent())
constructedid = add_agent!(sim, ConstructedAgent())
add_edge!(sim, constructedid, computeid, Connection())
finish_init!(sim)
@test length(Vahana.agentsontarget(sim, Connection)[constructedid]) == 1
# as we have Connection in add_existing, the agentsontarget dict
# should be unchanged
apply!(sim, ComputeAgent, [], Connection;
add_existing = Connection) do _, id, sim
end
@test length(Vahana.agentsontarget(sim, Connection)[constructedid]) == 1
# add_existing is empty and we have added ConstructedAgent and
# Connection to rebuild, so after the transition function only the
# ComputeAgent exists anymore
apply!(sim,
[ ComputeAgent ],
[],
[ ConstructedAgent, Connection ]) do _, id, sim
end
@test length(Vahana.agentsontarget(sim, Connection)) == 0
@test num_agents(sim, ComputeAgent) == 1
@test num_agents(sim, ConstructedAgent) == 0
@test num_edges(sim, Connection) == 0
# this time we readd the second agent and the edge
apply!(sim, [ ComputeAgent ], [], [ ConstructedAgent, Connection ]) do _, id, sim
constructedid = add_agent!(sim, ConstructedAgent())
add_edge!(sim, constructedid, computeid, Connection())
end
@test num_agents(sim, ComputeAgent) == 1
@test num_agents(sim, ConstructedAgent) == 1
@test num_edges(sim, Connection) == 1
# and as we add now ConstructedAgent and Connection to add_existing, we should
# still have them even with this "do nothing" transition function. And thanks to
# invariant_compute, we also must not return the ComputeAgent
apply!(sim,
[ ComputeAgent ], [], [ ConstructedAgent, Connection ];
add_existing = [ ConstructedAgent, Connection ]) do _, id, sim
end
@test num_agents(sim, ConstructedAgent) == 1
@test num_agents(sim, ComputeAgent) == 1
@test num_edges(sim, Connection) == 1
finish_simulation!(sim)
end
function test_assertion(model)
sim = create_simulation(model)
computeid = add_agent!(sim, ComputeAgent())
constructedid = add_agent!(sim, ConstructedAgent())
add_edge!(sim, constructedid, computeid, Connection())
finish_init!(sim)
@test_throws AssertionError apply!(sim,
[ ComputeAgent ],
[],
[ ConstructedAgent,
Connection ]) do state, _, _
state
end
finish_simulation!(sim)
end
@testset "addexisiting" begin
model = ModelTypes() |>
register_agenttype!(ComputeAgent) |>
register_agenttype!(ConstructedAgent) |>
register_edgetype!(Connection) |>
create_model("Test add_existing")
test_model(model)
model_imm_comp = ModelTypes() |>
register_agenttype!(ComputeAgent, :Immortal) |>
register_agenttype!(ConstructedAgent) |>
register_edgetype!(Connection) |>
create_model("Test add_existing vector")
test_model(model_imm_comp)
model_imm_cons = ModelTypes() |>
register_agenttype!(ComputeAgent) |>
register_agenttype!(ConstructedAgent, :Immortal) |>
register_edgetype!(Connection) |>
create_model("Test add_existing vector")
test_assertion(model_imm_cons)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 17620 | import Vahana.@onrankof
import Vahana.@rootonly
import Vahana.disable_transition_checks
# A for Agent, Imm for Immortal
# Fixed and Oversize doesn't have a real meaning anymore, in earlier versions
# there was a size keyword that allows to give an upper bound for the size
# of the population.
struct AMortal foo::Int64 end
struct AMortalFixed foo::Int64 end
struct AImm foo::Int64 end
struct AImmFixed foo::Int64 end
struct AImmFixedOversize foo::Int64 end
struct ADefault
foo::Int64
bool::Bool
end
allagenttypes = [ AMortal, AImm, AImmFixed ]
# ES = EdgeState and ESL = EdgeStateless
struct ESDict foo::Int64 end
struct ESLDict1 end
struct ESLDict2 end
model = ModelTypes() |>
register_agenttype!(AMortal) |>
register_agenttype!(AMortalFixed) |>
register_agenttype!(AImm, :Immortal) |>
register_agenttype!(AImmFixed, :Immortal) |>
register_agenttype!(AImmFixedOversize, :Immortal) |>
register_agenttype!(ADefault) |>
register_edgetype!(ESDict) |>
register_edgetype!(ESLDict1) |>
register_edgetype!(ESLDict2, :SingleType; target = AImm) |>
create_model("Test Core")
function add_example_network!(sim)
# construct 3 AMortal agents, 10 AImm agents and 10 AImmFixed
a1id = add_agent!(sim, AMortal(1))
a2id, a3id = add_agents!(sim, AMortal(2), AMortal(3))
avids = add_agents!(sim, [ AImm(i) for i in 1:10 ])
avfids = add_agents!(sim, [ AImmFixed(i) for i in 1:10 ])
# agent with edges, used for mapreduce
add_agents!(sim, [ AImmFixedOversize(i) for i in 1:10 ])
add_agents!(sim, [ AMortalFixed(i) for i in 1:10 ])
add_agents!(sim, [ ADefault(i, true) for i in 1:10 ])
# we construct the following network for ESDict:
# a2 & a3 & avids[1] & avfids[10] -> a1
add_edge!(sim, a2id, a1id, ESDict(1))
add_edge!(sim, a3id, a1id, ESDict(2))
add_edge!(sim, avids[1], a1id, ESDict(3))
add_edge!(sim, avfids[10], a1id, ESDict(4))
# we construct the following network for ESLDict1:
# avids -> a1
add_edges!(sim, a1id, [ Edge(avids[i], ESLDict1()) for i in 1:10 ])
# we construct the following network for ESLDict2:
# avfids[i] -> avids[i]
for i in 1:10
add_edge!(sim, avfids[i], avids[i], ESLDict2())
end
(a1id, a2id, a3id, avids, avfids)
end
function create_sum_state_neighbors(edgetypeval)
function sum_state_neighbors(agent, id, sim)
# @info id edgetypeval getproperty(sim, Symbol(edgetypeval)).readable
nstates = neighborstates_flexible(sim, id, edgetypeval)
s = 0
if !isnothing(nstates)
for n in nstates
s = s + n.foo
end
end
typeof(agent)(s)
end
end
import Vahana.updateids
function test_aggregate(sim, T::DataType)
@test mapreduce(sim, a -> a.foo, +, T) == reduce(+, 1:10)
@test mapreduce(sim, a -> a.foo, *, T) == reduce(*, 1:10)
@test mapreduce(sim, a -> a.foo, &, T; datatype = Int) == reduce(&, 1:10)
@test mapreduce(sim, a -> a.foo, |, T; datatype = Int) == reduce(|, 1:10)
@test mapreduce(sim, a -> a.foo, max, T) == reduce(max, 1:10)
@test mapreduce(sim, a -> a.foo, min, T) == reduce(min, 1:10)
end
function test_aggregate_mortal(sim, T::DataType)
test_aggregate(sim, T)
# we are testing that there aggregate also works when on a rank
# no agent of this type is existing
apply!(sim, [ T ], [ T ], [ T ]) do state, _, _
mpi.isroot ? state : nothing
end
# this should not cause an assertion
mapreduce(sim, a -> a.foo, +, T)
end
function createsim()
sim = create_simulation(model; logging = true, debug = true)
(a1id, a2id, a3id, avids, avfids) = add_example_network!(sim)
idmap = finish_init!(sim; return_idmapping = true, partition_algo=:EqualAgentNumbers)
a1id, a2id, a3id =
updateids(idmap, a1id), updateids(idmap, a2id), updateids(idmap, a3id)
avids, avfids = updateids(idmap, avids), updateids(idmap, avfids)
(sim, a1id, a2id, a3id, avids, avfids)
end
@testset "Core" begin
@testset "ModelImmortal" begin
@test model.immortal[1] == false
@test model.immortal[2] == false
@test model.immortal[3] == true
@test model.immortal[4] == true
@test model.immortal[5] == true
@test model.immortal[6] == false
end
@testset "with_edge" begin
sim = create_simulation(model; logging = true, debug = true)
aids = [ add_agent!(sim, AMortal(i)) for i in 1:100 ]
add_edge!(sim, aids[1], aids[2], ESLDict1())
finish_init!(sim)
@test num_agents(sim, AMortal) == 100
sim2 = copy_simulation(sim)
# with read
apply!(sim, AMortal, AMortal, AMortal; with_edge = ESLDict1) do state,_,_
nothing
end
@test num_agents(sim, AMortal) == 99
# without read
apply!(sim2, AMortal, [], AMortal; with_edge = ESLDict1) do state,_,_
nothing
end
@test num_agents(sim, AMortal) == 99
finish_simulation!(sim)
finish_simulation!(sim2)
end
(sim, a1id, a2id, a3id, avids, avfids) = createsim()
@testset "agentstate" begin
@onrankof a2id @test_throws AssertionError agentstate(sim, a2id, AImm)
@onrankof avids[1] @test_throws AssertionError agentstate(sim, avids[1], AMortal)
enable_asserts(false)
@onrankof a1id @test agentstate(sim, a1id, AMortal) == AMortal(1)
@onrankof a1id @test agentstate_flexible(sim, a1id) == AMortal(1)
@onrankof a1id @test agentstate_flexible(sim, a1id) == AMortal(1)
@onrankof a2id @test agentstate(sim, a2id, AMortal) == AMortal(2)
@onrankof avids[1] @test agentstate(sim, avids[1], AImm) == AImm(1)
@onrankof avfids[1] @test agentstate(sim, avfids[1], AImmFixed) == AImmFixed(1)
@onrankof avids[10] @test agentstate(sim, avids[10], AImm) == AImm(10)
@onrankof avfids[10] @test agentstate(sim, avfids[10], AImmFixed) == AImmFixed(10)
# # calling agentstate with the wrong typ should throw an AssertionError
enable_asserts(true)
end
@testset "edges & neighborids" begin
Vahana.disable_transition_checks(true)
@onrankof a1id @test length(edges(sim, a1id, ESDict)) == 4
@onrankof a1id @test length(edges(sim, a1id, ESLDict1)) == 10
# # Check that we can call edges also for an empty set of neighbors
@onrankof a2id @test edges(sim, a2id, ESDict) === nothing
@onrankof a2id @test edges(sim, a2id, ESLDict1) === nothing
# we must disable the neighborids checks
@onrankof avids[1] @test length(neighborids(sim, avids[1], ESLDict2)) == 1
@onrankof avids[10] @test length(neighborids(sim, avids[10], ESLDict2)) == 1
@onrankof avids[1] @test length(neighborids_iter(sim, avids[1], ESLDict2)) == 1
@onrankof avids[10] @test length(neighborids_iter(sim, avids[10], ESLDict2)) == 1
es = edges(sim, a1id, ESLDict1)
@onrankof a1id @test (es)[1].from == avids[1]
@onrankof a1id @test (es)[10].from == avids[10]
es = neighborids(sim, avids[10], ESLDict2)
@onrankof avids[10] @test es[1] == avfids[10]
es = neighborids_iter(sim, avids[10], ESLDict2) |> collect
@onrankof avids[10] @test es[1] == avfids[10]
Vahana.disable_transition_checks(false)
end
@testset "neighborstates" begin
Vahana.disable_transition_checks(true)
@onrankof a1id @test AImm(1) in neighborstates(sim, a1id, ESLDict1, AImm)
@onrankof a1id @test AImm(1) in collect(neighborstates(sim, a1id, ESLDict1, AImm))
@onrankof a1id @test AMortal(3) in neighborstates_flexible(sim, a1id, ESDict)
@onrankof a1id @test AMortal(3) in collect(neighborstates_flexible_iter(sim, a1id, ESDict))
Vahana.disable_transition_checks(false)
end
@testset "all_agents & num_agents" begin
copy = copy_simulation(sim)
@test length(all_agents(copy, AMortalFixed)) == 10
@test length(all_agents(copy, AImm)) == 10
@test num_agents(copy, AMortalFixed) == 10
@test num_agents(copy, AImm) == 10
for i in 1:10
@test AMortalFixed(i) in all_agents(copy, AMortalFixed)
@test AImm(i) in all_agents(copy, AImm)
end
apply!(copy, AMortalFixed, AMortalFixed, AMortalFixed) do state, _, _
if state.foo < 6
state
else
nothing
end
end
@test length(all_agents(copy, AMortalFixed)) == 5
@test num_agents(copy, AMortalFixed) == 5
for i in 1:5
@test AMortalFixed(i) in all_agents(copy, AMortalFixed)
end
for i in 6:10
@test !(AMortalFixed(i) in all_agents(copy, AMortalFixed))
end
finish_simulation!(copy)
end
@testset "all_agentids" begin
sim_agentids = ModelTypes() |>
register_agenttype!(AMortal) |>
create_model("all_agentids_test") |>
create_simulation()
foreach(i -> add_agent!(sim_agentids, AMortal(i)), 1:10)
finish_init!(sim_agentids)
@test length(all_agentids(sim_agentids, AMortal)) == 10
apply!(sim_agentids, AMortal, AMortal, AMortal) do state, id, sim
state.foo % 2 == 0 ? state : nothing
end
@test length(all_agentids(sim_agentids, AMortal)) == 5
finish_simulation!(sim_agentids)
# test also for immortal agents
sim_agentids = ModelTypes() |>
register_agenttype!(AImm) |>
create_model("all_agentids_test_immortal") |>
create_simulation()
foreach(i -> add_agent!(sim_agentids, AImm(i)), 1:10)
finish_init!(sim_agentids)
allids = all_agentids(sim_agentids, AImm)
@test length(allids) == 10
finish_simulation!(sim_agentids)
end
@testset "num_edges" begin
Vahana.disable_transition_checks(true)
@onrankof a1id @test num_edges(sim, a1id, ESDict) == 4
@onrankof a2id @test num_edges(sim, a2id, ESDict) == 0
@onrankof avids[1] @test num_edges(sim, avids[1], ESLDict2) == 1
Vahana.disable_transition_checks(false)
end
finish_simulation!(sim)
@testset "transition" begin
# check that with assertion enables, it is checked that the agent types
# are in `read`.
enable_asserts(true)
(sim, a1id, a2id, a3id, avids, avfids) = createsim()
# AImmFixed is missing
@test_throws AssertionError apply!(sim, AImm, [ ESLDict2], []) do _, id, sim
neighborstates_flexible(sim, id, ESLDict2)
end
finish_simulation!(sim)
# normally it's not allowed to call add_edge! between transition
# function, but because of the @onrankof this hack works here
enable_asserts(false)
# we want to check two iterations with the sum_state_neighbors,
# so we just add an edge loop for the agents where we check the sum
(sim, a1id, a2id, a3id, avids, avfids) = createsim()
@onrankof a1id add_edge!(sim, a1id, a1id, ESLDict1())
@onrankof avids[1] add_edge!(sim, avids[1], avids[1], ESLDict2())
@onrankof avfids[1] add_edge!(sim, avfids[1], avfids[1], ESLDict1())
# for avfids[1] we need a second edge
@onrankof avfids[1] add_edge!(sim, avfids[2], avfids[1], ESLDict1())
# and also avfids[2] should keep its value
@onrankof avfids[2] add_edge!(sim, avfids[2], avfids[2], ESLDict1())
enable_asserts(true)
# now check apply! for the different nodefieldfactories
apply!(sim, create_sum_state_neighbors(ESLDict1),
[ AMortal ], [ allagenttypes; ESLDict1 ], [ AMortal ])
disable_transition_checks(true)
@onrankof a1id @test agentstate(sim, a1id, AMortal) ==
AMortal(sum(1:10) + 1)
disable_transition_checks(false)
apply!(sim, create_sum_state_neighbors(ESLDict1),
[ AMortal ], [ allagenttypes; ESLDict1 ], [ AMortal ])
disable_transition_checks(true)
@onrankof a1id @test agentstate(sim, a1id, AMortal) ==
AMortal(2 * sum(1:10) + 1)
disable_transition_checks(false)
finish_simulation!(sim)
# copyvec = deepcopy(copy)
(sim, a1id, a2id, a3id, avids, avfids) = createsim()
# @onrankof a1id add_edge!(sim, a1id, a1id, ESLDict1())
enable_asserts(false)
@onrankof avids[1] add_edge!(sim, avids[1], avids[1], ESLDict2())
enable_asserts(true)
apply!(sim, create_sum_state_neighbors(ESLDict2),
[ AImm ], [ allagenttypes; ESLDict2 ], [ AImm ])
disable_transition_checks(true)
@onrankof avids[1] @test agentstate(sim, avids[1], AImm) == AImm(2)
disable_transition_checks(false)
apply!(sim, create_sum_state_neighbors(ESLDict2),
[ AImm ], [ allagenttypes; ESLDict2 ], [ AImm ])
disable_transition_checks(true)
@onrankof avids[1] @test agentstate(sim, avids[1], AImm) == AImm(3)
disable_transition_checks(false)
apply!(sim, create_sum_state_neighbors(ESLDict2),
[ AImm ], [ allagenttypes; ESLDict2 ], [ AImm ])
disable_transition_checks(true)
@onrankof avids[1] @test agentstate(sim, avids[1], AImm) == AImm(4)
disable_transition_checks(false)
finish_simulation!(sim)
# copyvec = deepcopy(copy)
(sim, a1id, a2id, a3id, avids, avfids) = createsim()
enable_asserts(false)
# @onrankof a1id add_edge!(sim, a1id, a1id, ESLDict1())
# @onrankof avids[1] add_edge!(sim, avids[1], avids[1], ESLDict2())
@onrankof avfids[1] add_edge!(sim, avfids[1], avfids[1], ESLDict1())
# for avfids[1] we need a second edge
@onrankof avfids[1] add_edge!(sim, avfids[2], avfids[1], ESLDict1())
# and also avfids[2] should keep its value
@onrankof avfids[2] add_edge!(sim, avfids[2], avfids[2], ESLDict1())
enable_asserts(true)
apply!(sim, create_sum_state_neighbors(ESLDict1),
[ AImmFixed ], [ allagenttypes; ESLDict1 ], [ AImmFixed ])
disable_transition_checks(true)
@onrankof avfids[1] @test agentstate(sim, avfids[1], AImmFixed) ==
AImmFixed(3)
disable_transition_checks(false)
apply!(sim, create_sum_state_neighbors(ESLDict1),
[ AImmFixed ], [ allagenttypes; ESLDict1 ], [ AImmFixed ])
disable_transition_checks(true)
@onrankof avfids[1] @test agentstate(sim, avfids[1], AImmFixed) ==
AImmFixed(5)
disable_transition_checks(false)
apply!(sim, create_sum_state_neighbors(ESLDict1),
[ AImmFixed ], [ allagenttypes; ESLDict1 ], [ AImmFixed ])
disable_transition_checks(true)
@onrankof avfids[1] @test agentstate(sim, avfids[1], AImmFixed) ==
AImmFixed(7)
disable_transition_checks(false)
finish_simulation!(sim)
end
@testset "Mapreduce" begin
sim = create_simulation(model; name = "Mapreduce")
(a1id, a2id, a3id, avids, avfids) = add_example_network!(sim)
finish_init!(sim)
for T in [ AImmFixed, AImmFixedOversize ]
test_aggregate(sim, T)
end
for T in [ AMortalFixed, ADefault ]
test_aggregate_mortal(sim, T)
end
finish_simulation!(sim)
sim = create_simulation(model; name = "Mapreduce")
(a1id, a2id, a3id, avids, avfids) = add_example_network!(sim)
finish_init!(sim)
# testing the & and | for boolean
# currenty all bool of ADefault are true
@test mapreduce(sim, a -> a.bool, &, ADefault) == true
@test mapreduce(sim, a -> a.bool, |, ADefault) == true
# set all bool to false
apply!(sim, [ ADefault ], [ ADefault ], [ ADefault ]) do state, id, sim
ADefault(state.foo, false)
end
@test mapreduce(sim, a -> a.bool, &, ADefault) == false
@test mapreduce(sim, a -> a.bool, |, ADefault) == false
# every second will be true, so that && is false and || is true
apply!(sim, [ ADefault ], [ ADefault ], [ ADefault ]) do state, id, sim
ADefault(state.foo, mod(id, 2) == 1)
end
@test mapreduce(sim, a -> a.bool, &, ADefault) == false
@test mapreduce(sim, a -> a.bool, |, ADefault) == true
finish_simulation!(sim)
end
@testset "add_agent_per_process!" begin
sim = create_simulation(model)
# Add some initial agents
for i in 1:10
add_agent!(sim, AMortal(i))
end
finish_init!(sim)
# Test adding an agent per process
new_id = add_agent_per_process!(sim, AMortal(100))
# Check that the total number of agents has increased by the number of processes
@test num_agents(sim, AMortal) == 10 + mpi.size
# Test that the function cannot be called within a transition
apply!(sim, AMortal, AMortal, AMortal) do state, id, sim
@test_throws AssertionError add_agent_per_process!(sim, AMortal(200))
state
end
finish_simulation!(sim)
end
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 14656 | import Vahana: disable_transition_checks
import Graphs: SimpleGraphs
# We need a lot of edgetypes to test all the edge hint combinations
# The hints are
# (S) Stateless
# (E) SingleEdge
# (T) SingleType, which can also have a size information (Ts)
# (I) IgnoreFrom
# so EdgeET means an Edge(State) with the SingleEdge and SingleType hints
struct Agent foo::Int64 end
struct AgentB foo::Int64 end # this is used to test the removal of "dead" edges (in edgesiterator)
struct EdgeD foo::Int64 end # D for default (no hint is set)
struct EdgeS end
struct EdgeE foo::Int64 end
struct EdgeT foo::Int64 end
struct EdgeI foo::Int64 end
struct EdgeSE end
struct EdgeST end
struct EdgeSI end
struct EdgeEI foo::Int64 end
struct EdgeTI foo::Int64 end
struct EdgeSEI end
struct EdgeSTI end
struct EdgeSETI end
struct EdgeTs foo::Int64 end
struct EdgeTsI foo::Int64 end
struct EdgeSTs end
struct EdgeSTsI end
struct EdgeSETsI end
statelessEdgeTypes = [ EdgeS, EdgeSE, EdgeST, EdgeSI, EdgeSEI, EdgeSTI, EdgeSETI, EdgeSTs, EdgeSTsI, EdgeSETsI ]
statefulEdgeTypes = [ EdgeD, EdgeE, EdgeT, EdgeI, EdgeEI, EdgeTI, EdgeTs, EdgeTsI ]
allEdgeTypes = [ statelessEdgeTypes; statefulEdgeTypes ]
model_edges = ModelTypes() |>
register_agenttype!(Agent) |>
register_agenttype!(AgentB) |>
register_edgetype!(EdgeD) |>
register_edgetype!(EdgeS, :Stateless) |>
register_edgetype!(EdgeE, :SingleEdge) |>
register_edgetype!(EdgeT, :SingleType; target = Agent) |>
register_edgetype!(EdgeI, :IgnoreFrom) |>
register_edgetype!(EdgeSE, :Stateless, :SingleEdge) |>
register_edgetype!(EdgeST, :Stateless, :SingleType; target = Agent) |>
register_edgetype!(EdgeSI, :Stateless, :IgnoreFrom) |>
register_edgetype!(EdgeEI, :SingleEdge, :IgnoreFrom) |>
register_edgetype!(EdgeTI, :SingleType, :IgnoreFrom; target = Agent) |>
register_edgetype!(EdgeSEI, :Stateless, :SingleEdge, :IgnoreFrom) |>
register_edgetype!(EdgeSTI, :Stateless, :SingleType, :IgnoreFrom; target = Agent) |>
register_edgetype!(EdgeSETI, :Stateless, :SingleEdge, :SingleType, :IgnoreFrom; target = Agent) |>
register_edgetype!(EdgeTs, :SingleType; target = Agent, size = 10) |>
register_edgetype!(EdgeTsI, :SingleType, :IgnoreFrom; target = Agent, size = 10) |>
register_edgetype!(EdgeSTs, :Stateless, :SingleType; target = Agent, size = 10) |>
register_edgetype!(EdgeSTsI, :Stateless, :SingleType, :IgnoreFrom; target = Agent, size = 10) |>
register_edgetype!(EdgeSETsI, :Stateless, :SingleEdge, :SingleType, :IgnoreFrom; target = Agent, size = 10) |>
create_model("Test Edges")
hashint(type, hint::String) = occursin(hint, SubString(String(Symbol(type)), 5))
function runedgestest()
@testset "Edges" begin
sim = create_simulation(model_edges, nothing, nothing)
(a1id, a2id, a3id) = add_agents!(sim, Agent(1), Agent(2), Agent(3))
# Lets add some edges for each of the different hint combinations
# For each combination we will have
# 2 -> 3 (with state 1 for stateful edges)
# 3 -> 1 (with state 3 for stateful edges)
# and for all combination that supports multiple edges we add also
# 1 -> 3 (with state 2 for stateful edges)
for t in statelessEdgeTypes
add_edge!(sim, a2id, a3id, t())
# we can not check the "ET" combination, instead a warning
# is given when register_edgetype is called
if hashint(nameof(t), "E") && !hashint(nameof(t), "T") && !(hashint(nameof(t), "S") && hashint(nameof(t), "I"))
# and check in the case that a second edge can not be added to
# the same agent (and that this can be checked),
# that this throws an assertion
@test_throws AssertionError add_edge!(sim, a1id, a3id, t())
elseif !hashint(nameof(t), "E")
add_edge!(sim, a1id, a3id, t())
end
edge = Edge(a3id, t())
add_edge!(sim, a1id, edge)
# println(t)
# @eval println($sim.$(Symbol(nameof(t),"_write")))
# println()
end
for t in statefulEdgeTypes
add_edge!(sim, a2id, a3id, t(1))
# we can not check the "ET" combination, instead a warning
# is given when register_edgetype is called
if hashint(nameof(t), "E") && !hashint(nameof(t), "T") && !(hashint(nameof(t), "S") && hashint(nameof(t), "I"))
@test_throws AssertionError add_edge!(sim, a1id, a3id, t(2))
elseif !hashint(nameof(t), "E")
add_edge!(sim, a1id, a3id, t(2))
end
edge = Edge(a3id, t(3))
add_edge!(sim, a1id, edge)
# println(t)
# @eval println($sim.$(Symbol(t,"_write")))
# println()
end
finish_init!(sim)
# # with this apply we ensure
# apply(sim, [ Agent, AgentB ], allEdgeTypes, []) do _,_,_ end
@testset "edges" begin
disable_transition_checks(true)
for t in [EdgeD, EdgeT, EdgeTs]
e = edges(sim, a3id, t)
@test e[1] == Edge(a2id, t(1))
@test e[2] == Edge(a1id, t(2))
e = edges(sim, a2id, t)
@test e === nothing
end
for t in [EdgeE]
e = edges(sim, a3id, t)
@test e == Edge(a2id, t(1))
end
disable_transition_checks(false)
for t in [ EdgeI, EdgeEI, EdgeTI, EdgeTsI, EdgeS, EdgeSE, EdgeST, EdgeSI, EdgeSEI, EdgeSTI, EdgeSETI, EdgeSTs, EdgeSTsI, EdgeSETsI ]
@test_throws AssertionError edges(sim, a1id, t)
end
end
@testset "neighborids" begin
disable_transition_checks(true)
for t in [EdgeD, EdgeT, EdgeTs, EdgeS, EdgeST, EdgeSTs]
e = neighborids(sim, a3id, t)
@test e[1] == a2id
@test e[2] == a1id
e = neighborids(sim, a2id, t)
@test e === nothing
end
for t in [EdgeE, EdgeSE]
e = neighborids(sim, a3id, t)
@test e == a2id
end
disable_transition_checks(false)
for t in [EdgeI, EdgeTI, EdgeTsI, EdgeSI, EdgeSTI, EdgeSTsI,
EdgeEI, EdgeSEI, EdgeSETI, EdgeSETsI]
@test_throws AssertionError neighborids(sim, a1id, t)
end
end
@testset "edgestates" begin
disable_transition_checks(true)
for t in [EdgeD, EdgeT, EdgeTs, EdgeI, EdgeTI, EdgeTsI]
e = edgestates(sim, a3id, t)
@test e[1] == t(1)
@test e[2] == t(2)
e = edgestates(sim, a2id, t)
@test e === nothing
e = edgestates_iter(sim, a3id, t) |> collect
@test e[1] == t(1)
@test e[2] == t(2)
e = edgestates_iter(sim, a2id, t)
@test e === nothing
end
for t in [EdgeE, EdgeEI]
e = edgestates(sim, a3id, t)
@test e == t(1)
end
disable_transition_checks(false)
for t in [EdgeS, EdgeST, EdgeSTs, EdgeSI, EdgeSTI, EdgeSTsI,
EdgeSE, EdgeSEI, EdgeSETI, EdgeSETsI]
@test_throws AssertionError edgestates(sim, a1id, t)
@test_throws AssertionError edgestates_iter(sim, a1id, t)
end
end
@testset "num_edges" begin
disable_transition_checks(true)
for t in [EdgeD, EdgeT, EdgeTs, EdgeI, EdgeTI, EdgeTsI,
EdgeS, EdgeST, EdgeSTs, EdgeST, EdgeSTI, EdgeSTsI]
@test num_edges(sim, a1id, t) == 1
@test num_edges(sim, a2id, t) == 0
@test num_edges(sim, a3id, t) == 2
end
disable_transition_checks(false)
for t in [EdgeE, EdgeEI, EdgeSE, EdgeSETI, EdgeSETsI]
@test_throws AssertionError num_edges(sim, a1id, t)
end
end
@testset "has_edge" begin
disable_transition_checks(true)
for t in [ EdgeS, EdgeSE, EdgeST, EdgeSI, EdgeSEI, EdgeSTI, EdgeSETI,
EdgeSTs, EdgeSTsI, EdgeSETsI, EdgeD, EdgeE, EdgeT, EdgeI,
EdgeEI, EdgeTI, EdgeTs, EdgeTsI ]
@test has_edge(sim, a1id, t) == true
@test has_edge(sim, a2id, t) == false
@test has_edge(sim, a3id, t) == true
end
disable_transition_checks(false)
end
@testset "mapreduce" begin
for t in [ EdgeD, EdgeT, EdgeI, EdgeTI, EdgeTs, EdgeTsI ]
@test mapreduce(sim, a -> a.foo, +, t) == 6
end
for t in [ EdgeE, EdgeEI ]
@test mapreduce(sim, a -> a.foo, +, t) == 4
end
for t in [ EdgeS, EdgeSE, EdgeST, EdgeSI, EdgeSEI, EdgeSTI, EdgeSETI,
EdgeSTs, EdgeSTsI, EdgeSETsI ]
@test_throws AssertionError mapreduce(sim, a -> a.foo, +, t)
end
end
@testset "neighbor_states" begin
disable_transition_checks(true)
for t in [EdgeD, EdgeT, EdgeTs, EdgeS, EdgeST, EdgeSTs]
e = neighborids(sim, a3id, t)
@test e[1] == a2id
@test e[2] == a1id
e = neighborids(sim, a2id, t)
@test e === nothing
end
disable_transition_checks(false)
end
@testset "check Vahana state" begin
for t in statelessEdgeTypes
@test_throws AssertionError add_edge!(sim, AgentID(0), AgentID(0), t())
end
for t in statefulEdgeTypes
@test_throws AssertionError add_edge!(sim, AgentID(0), AgentID(0), t(0))
end
end
@testset "check edgetype in read and write" begin
Vahana.config.check_readable = true
enable_asserts(true)
for t in statelessEdgeTypes
@test_throws AssertionError apply(sim, Agent, [], []) do _, id, sim
add_edge!(sim, id, id, t())
end
apply(sim, Agent, [], t) do _, id, sim
add_edge!(sim, id, id, t())
end
end
for t in statefulEdgeTypes
@test_throws AssertionError apply(sim, Agent, [], []) do _, id, sim
add_edge!(sim, id, id, t(0))
end
apply(sim, Agent, [], t) do _, id, sim
add_edge!(sim, id, id, t(0))
end
end
for t in [ statelessEdgeTypes; statefulEdgeTypes ]
@test_throws AssertionError apply(sim, Agent, [], []) do _, id, sim
edges(sim, id, t)
end
end
end
finish_simulation!(sim)
end
@testset "num_edges" begin
sim = create_simulation(model_edges, nothing, nothing)
for t in [ statefulEdgeTypes; statelessEdgeTypes ]
@test num_edges(sim, t; write = false) == 0
end
@test num_agents(sim, Agent) == 0
# We need a gap
id1 = add_agent!(sim, Agent(0))
id2 = add_agent!(sim, Agent(0))
id3 = add_agent!(sim, Agent(0))
@test num_agents(sim, Agent) == 3
for t in [ statefulEdgeTypes; statelessEdgeTypes ]
if fieldcount(t) > 0
add_edge!(sim, id1, id1, t(0))
add_edge!(sim, id3, id3, t(0))
else
add_edge!(sim, id1, id1, t())
add_edge!(sim, id3, id3, t())
end
end
for t in [ statefulEdgeTypes; statelessEdgeTypes ]
@test num_edges(sim, t; write = true) == 2
@test num_edges(sim, t; write = false) == 0
end
finish_init!(sim)
for t in [ statefulEdgeTypes; statelessEdgeTypes ]
@test num_edges(sim, t; write = false) == 2
end
finish_simulation!(sim)
end
end
@testset "transition" begin
for ET in [ EdgeD, EdgeE, EdgeT, EdgeI, EdgeEI, EdgeTI ]
sim = create_simulation(model_edges)
if Vahana.has_hint(sim, ET, :SingleEdge)
finish_simulation!(sim)
continue
end
nagents = mpi.size * 2
add_graph!(sim,
SimpleGraphs.complete_graph(nagents),
i -> Agent(i),
e -> ET(e.dst)
)
finish_init!(sim)
apply!(sim, [ Agent ], [ ET ], []) do _, id, sim
@test num_edges(sim, id, ET) == nagents-1
end
# write was empty, so we should get the same results when doing
# the same transition again
apply!(sim, [ Agent ], [ ET ], []) do _, id, sim
@test num_edges(sim, id, ET) == nagents-1
end
# write the edges by copying them from before
apply!(sim, [ Agent ], [], [ ET ]; add_existing = [ ET ]) do _, id, sim
end
apply!(sim, [ Agent ], [ ET ], []) do _, id, sim
@test num_edges(sim, id, ET) == nagents-1
end
if ET == EdgeD
# write the edges by readding them
apply!(sim, [ Agent ], [ ET ], [ ET ]) do _, id, sim
add_edges!(sim, id, edges(sim, id, ET))
end
apply!(sim, [ Agent ], [ ET ], []) do _, id, sim
@test num_edges(sim, id, ET) == nagents-1
end
apply!(sim, [ Agent ], [], []) do _, id, sim end
# write the edges by copying and readding
apply!(sim, [ Agent ], [ ET ], [ ET ]; add_existing = [ ET ]) do _, id, sim
add_edges!(sim, id, edges(sim, id, ET))
end
# (we should have them twice after now)
apply!(sim, [ Agent ], [ ET ], []) do _, id, sim
@test num_edges(sim, id, ET) == (nagents-1) * 2
end
# this time no one adds the edges, so they should be gone afterwards
apply!(sim, [ Agent ], [], [ ET ]) do _, id, sim
end
apply!(sim, [ Agent ], [ ET ], []) do _, id, sim
@test num_edges(sim, id, ET) == 0
end
end
finish_simulation!(sim)
end
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 7335 | using Base: nothing_sentinel
# the edge types and some other stuff is defined in edges.jl
import Vahana: has_hint, @onrankof
# this test does not work with MPI, as it assumes that all edges are on one rank
if mpi.size == 1
@testset "Edges Iter" begin
function runedgesitertest(ET)
eisim = create_simulation(model_edges; logging = true, debug = true)
@test Vahana.edges_iterator(eisim, ET) |> length == 0
@test Vahana.edges_iterator(eisim, ET) |> collect |> length == 0
aids = add_agents!(eisim, [ Agent(i) for i in 1:10 ])
for id in aids
if fieldcount(ET) > 0
add_edge!(eisim, aids[1], id, ET(id))
if ! hashint(ET, "E")
add_edge!(eisim, id, aids[1], ET(id))
end
else
add_edge!(eisim, aids[1], id, ET())
if ! hashint(ET, "E")
add_edge!(eisim, id, aids[1], ET())
end
end
end
expected = hashint(ET, "E") ? 10 : 20
@test Vahana.edges_iterator(eisim, ET, false) |> length == expected
@test Vahana.edges_iterator(eisim, ET, false) |> collect |> length ==
expected
finish_init!(eisim)
@test Vahana.edges_iterator(eisim, ET) |> length == expected
@test Vahana.edges_iterator(eisim, ET) |> collect |> length ==
expected
finish_simulation!(eisim)
end
for ET in [ statelessEdgeTypes; statefulEdgeTypes ]
if ! (hashint(ET, "S") & hashint(ET, "I"))
runedgesitertest(ET)
GC.gc(true)
end
end
end
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
@testset "Edges Agg" begin
function runedgesaggregatetest(ET::DataType)
sim = create_simulation(model_edges; logging = true, debug = true)
@test mapreduce(sim, e -> e.foo, +, ET) == 0
aids = add_agents!(sim, [ Agent(i) for i in 1:10 ])
for id in aids
add_edge!(sim, aids[1], id, ET(Vahana.agent_nr(id)))
end
finish_init!(sim)
@test mapreduce(sim, e -> e.foo, +, ET) == sum(1:10)
# first we test that edges to the agents are removed
apply!(sim, [ Agent ], [], [ Agent ]) do _, id, sim
nothing
end
@test mapreduce(sim, e -> e.foo, +, ET) == 0
finish_simulation!(sim)
# we now create edges from type AgentB to Agent and remove all
# agents of type AgentB. This should also remove the edges.
sim = create_simulation(model_edges; logging = true, debug = true)
aids = add_agents!(sim, [ Agent(i) for i in 1:10 ])
bids = add_agents!(sim, [ AgentB(i) for i in 1:10 ])
for i in 1:10
add_edge!(sim, bids[i], aids[i], ET(i))
end
finish_init!(sim)
@test mapreduce(sim, e -> e.foo, +, ET) == sum(1:10)
# first we test that edges to the agents are removed
apply!(sim, [ Agent ], [], [ Agent ]) do _, id, sim
nothing
end
@test mapreduce(sim, e -> e.foo, +, ET) == 0
finish_simulation!(sim)
end
for ET in statefulEdgeTypes
runedgesaggregatetest(ET)
GC.gc(true)
end
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
@testset "Remove Edges" begin
# some remove stuff is already tested above, but here we
# use num_edges instead of mapreduce to test this for all types.
# but this does not work for distributed runs
function runremoveedgestest(ET::DataType)
# we create edges from type AgentB to Agent and remove all
# agents of type AgentB. This should also remove the edges.
sim = create_simulation(model_edges; logging = true, debug = true)
aids = add_agents!(sim, [ Agent(i) for i in 1:10 ])
bids = add_agents!(sim, [ AgentB(i) for i in 1:10 ])
for i in 1:10
if has_hint(sim, ET, :Stateless)
add_edge!(sim, bids[i], aids[i], ET())
else
add_edge!(sim, bids[i], aids[i], ET(i))
end
end
finish_init!(sim)
@test num_edges(sim, ET) == 10
# first we test that edges to the agents are removed
apply!(sim, [ Agent ], [], [ Agent ]) do _, id, sim
nothing
end
@test num_edges(sim, ET) == 0
if has_hint(sim, ET, :IgnoreFrom)
return
end
finish_simulation!(sim)
# we create edges between all agent of type AgentB and Agent
# with the same index i.
sim = create_simulation(model_edges, nothing, nothing)
aids = add_agents!(sim, [ Agent(i) for i in 1:10 ])
bids = add_agents!(sim, [ AgentB(i) for i in 1:10 ])
for i in 1:10
if has_hint(sim, ET, :Stateless)
if ! has_hint(sim, ET, :SingleEdge)
add_edge!(sim, aids[i], aids[i], ET())
if ! has_hint(sim, ET, :SingleType)
add_edge!(sim, aids[i], bids[i], ET())
end
end
# test both add_edge! variants
add_edge!(sim, aids[i], Edge(bids[i], ET()))
if ! has_hint(sim, ET, :SingleType)
add_edge!(sim, bids[i], Edge(bids[i], ET()))
end
else
if ! has_hint(sim, ET, :SingleEdge)
add_edge!(sim, aids[i], aids[i], ET(i))
if ! has_hint(sim, ET, :SingleType)
add_edge!(sim, aids[i], bids[i], ET(i))
end
end
add_edge!(sim, aids[i], Edge(bids[i], ET(i)))
if ! has_hint(sim, ET, :SingleType)
add_edge!(sim, bids[i], Edge(bids[i], ET(i)))
end
end
end
finish_init!(sim)
# And then remove every second agents of type AgentB.
apply!(sim, AgentB, AgentB, AgentB) do self, id, sim
self.foo % 2 == 0 ? self : nothing
end
# After this the:
# 10 a-a edges, (but not for :SingleEdge)
# 5 b-a edges, (! :SingleType or :SingleEdge)
# 5 b-b edges (! :SingleType)
# 5 a-b edges (always)
# should be left
count = 5
if ! has_hint(sim, ET, :SingleEdge)
count += 10
end
if ! has_hint(sim, ET, :SingleType)
count += 5
end
if (! has_hint(sim, ET, :SingleEdge) &&
! has_hint(sim, ET, :SingleType))
count += 5
end
if has_hint(sim, ET, :IgnoreFrom)
# only the edges to the agent are removed
@test num_edges(sim, ET) == 30
else
@test num_edges(sim, ET) == count
end
finish_simulation!(sim)
end
for ET in [ statefulEdgeTypes; statelessEdgeTypes ]
runremoveedgestest(ET)
end
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 399 | @testset "Globals" begin
mutable struct TestGlobals
foo::Float64
bar::Vector{Int64}
end
sim = create_simulation(model, nothing, TestGlobals(0,Vector{Int64}()))
set_global!(sim, :foo, 1.1)
push_global!(sim, :bar, 1)
push_global!(sim, :bar, 2)
@test get_global(sim, :foo) == 1.1
@test get_global(sim, :bar) == [1, 2]
finish_simulation!(sim)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 1073 | import Graphs.SimpleGraphs
struct GraphA
id::Int64
sum::Int64
end
struct GraphE end
model_graph = ModelTypes() |>
register_agenttype!(GraphA) |>
register_edgetype!(GraphE) |>
create_model("Test Graph")
@testset "Graphs" begin
# calculate the sum of all ids
function sumids(a, id, sim)
GraphA(a.id,
mapreduce(a -> a.id, +,
neighborstates_flexible(sim, id, GraphE)))
end
sim = create_simulation(model_graph, nothing, nothing)
nagents = 4
add_graph!(sim,
SimpleGraphs.complete_graph(nagents),
i -> GraphA(i, 0),
_ -> GraphE()
)
finish_init!(sim)
apply!(sim, sumids, [GraphA], [GraphA, GraphE], [GraphA])
# we have a complete graph, and all agents sum the
# ids of the neighbors (but ignoring the own)
# so in overall we have the nagents-1 times the sum of all ids
@test mapreduce(sim, a -> a.sum, +, GraphA) ==
sum(1:nagents) * (nagents - 1)
finish_simulation!(sim)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 3005 | using Vahana
using Test
suppress_warnings(true)
set_hdf5_path(tempdir())
Pos2D = NamedTuple{(:x, :y), Tuple{Int64, Int64}}
Pos3D = NamedTuple{(:x, :y, :z), Tuple{Int64, Int64, Int64}}
Pos(x, y) = (x = x, y = y)
Pos(x, y, z) = (x = x, y = y, z = z)
struct InnerStruct
f::Float64
i::Int64
end
struct Agent
inner::InnerStruct
f::Float64
end
struct RasterAgent end
struct EmptyAgentVector end
struct EdgeState
f::AgentID
t::AgentID
end
struct StatelessEdge end
struct RasterEdge
a::Int64
end
struct EmptyEdgeVector end
struct Globals
pos::Pos2D
ga::Int64
gb::Vector{Float64}
gc::Vector{Int64}
empty::Vector{Int64}
end
struct Params
pb::Int64
pa::Vector{Float64}
pos::Pos3D
end
function sumi2o(state, _, _)
Agent(state.inner, state.inner.f + state.inner.i)
end
# the test model has the following structure:
# we create mpi.size * 8 agent of type Agent
function createsim(model, distribute = true)
sim = model |>
create_simulation(Params(1, [2.0, 2.1], (x = 3, y = 4, z = 5)),
Globals(Pos(1, 2), 3, [4.0, 4.1], [5, 6, 7], []);
logging = true, debug = true)
ids = add_agents!(sim, [ Agent(InnerStruct(i,i+1),i+2) for i in 1:16 ])
for id in ids
add_edge!(sim, id, id, EdgeState(id, id))
add_edge!(sim, id, ids[2], StatelessEdge())
add_edge!(sim, id, ids[5], StatelessEdge())
add_edge!(sim, id, ids[2], EdgeState(id, ids[1]))
end
rids = add_raster!(sim, :fourdspace, (2,2,2,1), _ -> RasterAgent())
for id in ids
add_edge!(sim, id, rids[mod1(id, 8)], RasterEdge(id % 8 + 1))
end
finish_init!(sim;
partition_algo = :EqualAgentNumbers, distribute = distribute)
sim
end
function runsim(model, write)
sim = createsim(model)
if write
write_snapshot(sim, "Initial state")
end
apply!(sim, [ Agent ], [ Agent ], [ Agent ]) do state, id, sim
Agent(state.inner, state.f - 2)
end
push_global!(sim, :gb, 2.1)
push_global!(sim, :gc, 4)
if write
write_snapshot(sim)
end
apply!(sim, remove_some_rasternodes,
[ RasterAgent ],
[ RasterAgent, RasterEdge, Agent ],
[ RasterAgent, RasterEdge ])
if write
write_snapshot(sim, "Final state")
close(sim.h5file)
end
sim
end
function remove_some_rasternodes(state, id, sim)
nstate = neighborstates(sim, id, RasterEdge, Agent) |> first
e = edges(sim, id, RasterEdge) |> first
add_edge!(sim, e.from, id, RasterEdge(e.state.a * 2))
mod1(nstate.f, 8) > 4.5 ? nothing : state
end
function restore(model, sim; kwargs...)
restored = create_simulation(model,
Params(0, [0, 0], Pos(0, 0, 0)),
Globals(Pos(0, 0), 0, [0], [0], []))
read_snapshot!(restored, sim.name; kwargs...)
restored
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 4089 | include("hdf5_common.jl")
import Vahana: has_hint, type_nr, agent_id, agent_nr, AgentID, AgentNr
set_hdf5_path(joinpath(dirname(@__FILE__), "h5"))
function test_merge(model)
sim = runsim(model, false)
restored = restore(model, sim)
fids = Vahana.open_h5file(restored, sim.name)
@assert mpi.size == 1 && length(fids) > 1 """\n
this should test the merge functionality (reading a distributed
sim back to a single process), so the test should not be run
with mpi but the files should be written from a mpi simulation
"""
foreach(close, fids)
@test sim.params.pa == restored.params.pa
@test sim.params.pb == restored.params.pb
@test sim.params.pos == restored.params.pos
# @test sim.globals == restored.globals
@test sim.Agent.last_change == restored.Agent.last_change
@test sim.RasterAgent.last_change == restored.RasterAgent.last_change
function checkedges(sim_edges, restored_edges, T)
@test getproperty(sim, Symbol(T)).last_change ==
getproperty(restored, Symbol(T)).last_change
@test num_edges(sim, T) == num_edges(restored, T)
for to in keys(sim_edges)
to = AgentID(to)
AT = has_hint(sim, T, :SingleType) ?
Agent :
sim.typeinfos.nodes_id2type[type_nr(to)]
if AT == Agent
rto = filter(enumerate(restored.Agent.read.state) |>
collect) do (i, state)
state.f == sim.Agent.read.state[agent_nr(to)].f
end |> first |> first
rto = Vahana.agent_id(sim, AgentNr(rto), Agent)
if has_hint(sim, T, :IgnoreFrom) &&
has_hint(sim, T, :Stateless)
if has_hint(sim, T, :SingleType)
@test sim_edges[agent_nr(to)] ==
restored_edges[agent_nr(rto)]
else
@test sim_edges[to] == restored_edges[rto]
end
elseif ! has_hint(sim, T, :Stateless)
for edge in sim_edges[to]
if has_hint(sim, T, :IgnoreFrom)
@test edge in restored_edges[rto]
else
states = map(e -> e.state, restored_edges[rto])
@test edge.state in states
end
end
end
end
end
end
checkedges(sim.EdgeState.read, restored.EdgeState.read, EdgeState)
checkedges(sim.RasterEdge.read, restored.RasterEdge.read, RasterEdge)
checkedges(sim.StatelessEdge.read, restored.StatelessEdge.read, StatelessEdge)
end
@testset "HDF5 merge" begin
model_default = ModelTypes() |>
register_agenttype!(Agent) |>
register_agenttype!(RasterAgent) |>
register_edgetype!(EdgeState) |>
register_edgetype!(RasterEdge) |>
register_edgetype!(StatelessEdge) |>
register_agenttype!(EmptyAgentVector) |>
register_edgetype!(EmptyEdgeVector) |>
create_model("hdf5_default")
test_merge(model_default)
model_immortal = ModelTypes() |>
register_agenttype!(Agent, :Immortal) |>
register_agenttype!(RasterAgent) |>
register_edgetype!(EdgeState, :IgnoreFrom) |>
register_edgetype!(RasterEdge) |>
register_edgetype!(StatelessEdge, :Stateless) |>
create_model("hdf5_ignore_immortal")
test_merge(model_immortal)
model_neighbors = ModelTypes() |>
register_agenttype!(Agent, :Immortal) |>
register_agenttype!(RasterAgent) |>
register_edgetype!(EdgeState, :NumEdgesOnly) |>
register_edgetype!(RasterEdge) |>
register_edgetype!(StatelessEdge, :HasEdgeOnly, :SingleType; target = Agent) |>
create_model("hdf5_neighbors")
test_merge(model_neighbors)
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 6253 | include("hdf5_common.jl")
set_hdf5_path(joinpath(dirname(@__FILE__), "h5"))
function test_write_restore(model)
sim = runsim(model, true)
restored = restore(model, sim)
test(sim, restored)
apply!(sim,
remove_some_rasternodes,
[ RasterAgent ],
[ RasterAgent, RasterEdge, Agent ],
[ RasterAgent, RasterEdge ])
apply!(restored,
remove_some_rasternodes,
[ RasterAgent ],
[ RasterAgent, RasterEdge, Agent ],
[ RasterAgent, RasterEdge ])
test(sim, restored)
finish_simulation!(restored)
finish_simulation!(sim)
end
function test(sim, restored)
@test sim.Agent.read.died == restored.Agent.read.died
@test sim.Agent.read.state == restored.Agent.read.state
@test sim.Agent.read.reuseable == restored.Agent.read.reuseable
@test sim.Agent.nextid == restored.Agent.nextid
@test sim.Agent.last_change == restored.Agent.last_change
@test sim.RasterAgent.read.died == restored.RasterAgent.read.died
@test sim.RasterAgent.read.state == restored.RasterAgent.read.state
@test sim.RasterAgent.read.reuseable == restored.RasterAgent.read.reuseable
@test sim.RasterAgent.nextid == restored.RasterAgent.nextid
@test sim.RasterAgent.last_change == restored.RasterAgent.last_change
@test sim.params.pa == restored.params.pa
@test sim.params.pb == restored.params.pb
@test sim.params.pos == restored.params.pos
# @test sim.globals == restored.globals
@test sim.globals_last_change == restored.globals_last_change
function checkedges(sim_edges, restored_edges, T)
@test getproperty(sim, Symbol(T)).last_change ==
getproperty(restored, Symbol(T)).last_change
if Vahana.has_hint(sim, T, :SingleType)
@test sim_edges == restored_edges
else
for to in keys(sim_edges)
for edge in sim_edges[to]
@test edge in restored_edges[to]
end
end
end
end
checkedges(sim.EdgeState.read, restored.EdgeState.read, EdgeState)
checkedges(sim.RasterEdge.read, restored.RasterEdge.read, RasterEdge)
checkedges(sim.StatelessEdge.read, restored.StatelessEdge.read, StatelessEdge)
end
@testset "Snapshot" begin
model_default = ModelTypes() |>
register_agenttype!(Agent) |>
register_agenttype!(RasterAgent) |>
register_edgetype!(EdgeState) |>
register_edgetype!(RasterEdge) |>
register_edgetype!(StatelessEdge) |>
register_agenttype!(EmptyAgentVector) |>
register_edgetype!(EmptyEdgeVector) |>
create_model("hdf5_default")
test_write_restore(model_default)
model_immortal = ModelTypes() |>
register_agenttype!(Agent, :Immortal) |>
register_agenttype!(RasterAgent) |>
register_edgetype!(EdgeState, :IgnoreFrom) |>
register_edgetype!(RasterEdge) |>
register_edgetype!(StatelessEdge, :Stateless) |>
create_model("hdf5_ignore_immortal")
test_write_restore(model_immortal)
model_neighbors = ModelTypes() |>
register_agenttype!(Agent, :Immortal) |>
register_agenttype!(RasterAgent) |>
register_edgetype!(EdgeState, :NumEdgesOnly) |>
register_edgetype!(RasterEdge) |>
register_edgetype!(StatelessEdge, :HasEdgeOnly, :SingleType; target = Agent) |>
create_model("hdf5_neighbors")
test_write_restore(model_neighbors)
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
@testset "Metadata" begin
mutable struct ParGlo
vec::Vector{Int64}
mat::Matrix{Int64}
arr::Array{Int64, 3}
empty::Vector{Int64}
end
struct MetaDataCell end
model_arrays = ModelTypes() |>
register_agenttype!(MetaDataCell) |>
create_model("Metadata")
sim = create_simulation(model_arrays,
ParGlo([1, 2, 3], [1 2 3; 4 5 6],
ones(2,3,4), Int64[]),
ParGlo([1, 2, 3], [1 2 3; 4 5 6],
ones(2,3,4), Int64[]);
name = "Metadata_sim")
add_raster!(sim,
:grid,
(10,8),
_ -> MetaDataCell())
# check that we can also write metadata before finish_inith!
write_metadata(sim, :Param, :empty, :foo, 1)
write_metadata(sim, :Raster,:grid, :bar, 2)
write_sim_metadata(sim, :foo, 2)
finish_init!(sim; partition_algo = :EqualAgentNumbers)
write_metadata(sim, :Global, :mat, :dim1, "hhtype")
write_metadata(sim, :Global, :mat, :foo, "bar")
write_snapshot(sim)
write_metadata(sim, :Global, :mat, :dim2, "agegroup")
finish_simulation!(sim)
sim = create_simulation(model_arrays,
ParGlo(Int64[], zeros(1,1),
zeros(1,1,1), Int64[]),
ParGlo(Int64[], zeros(1,1),
zeros(1,1,1), Int64[]);
name = "Metadata_sim")
read_snapshot!(sim)
@test sim.params.vec == [1, 2, 3]
@test sim.params.mat == [1 2 3; 4 5 6]
@test sim.params.arr == ones(2,3,4)
@test sim.params.empty == Int64[]
@test sim.globals.vec == [1, 2, 3]
@test sim.globals.mat == [1 2 3; 4 5 6]
@test sim.globals.arr == ones(2,3,4)
@test sim.globals.empty == Int64[]
@test read_metadata(sim, :Param, :empty, :foo) == 1
@test read_metadata(sim, :Global, :mat, :dim1) == "hhtype"
@test read_metadata(sim, :Global, :mat, :dim2) == "agegroup"
@test read_metadata(sim, :Global, :mat, :nonsense) == nothing
@test read_metadata(sim, :Global, :nonsense, :nonsense) == nothing
@test read_metadata(sim, :Raster, :grid, :bar) == 2
asdict = read_metadata(sim, :Global, :mat)
@test asdict[:dim1] == "hhtype"
@test read_sim_metadata(sim, :foo) == 2
asdict = read_sim_metadata(sim)
asdict[:model_name] == "Metadata"
asdict[:simulation_name] == "Metadata_sim"
finish_simulation!(sim)
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 7637 | using Vahana
using Test
struct AIndependent
foo::Int64
end
struct ANotIndependent
foo::Int64
end
struct AIndependentImmortal
foo::Int64
end
struct AFooEdge
foo::Int64
end
struct AEdge end
model = ModelTypes() |>
register_agenttype!(AIndependent, :Independent) |>
register_agenttype!(ANotIndependent) |>
register_agenttype!(AIndependentImmortal, :Independent) |>
register_edgetype!(AFooEdge) |>
register_edgetype!(AEdge) |>
create_model("Test Independent")
@testset "independent" begin
sim = create_simulation(model)
simnot = create_simulation(model)
simimmortal = create_simulation(model)
ids = [ add_agent!(sim, AIndependent(i)) for i in 1:10 ]
for from in ids
for to in ids
add_edge!(sim, from, to, AEdge())
end
end
ids = [ add_agent!(simnot, ANotIndependent(i)) for i in 1:10 ]
for from in ids
for to in ids
add_edge!(simnot, from, to, AEdge())
end
end
ids = [ add_agent!(simimmortal, AIndependentImmortal(i)) for i in 1:10 ]
for from in ids
for to in ids
add_edge!(simimmortal, from, to, AEdge())
end
end
finish_init!(sim)
finish_init!(simnot)
finish_init!(simimmortal)
@test num_agents(sim, AIndependent) == 10
@test num_edges(sim, AEdge) == 10 * 10
# remove agent i, all other add edges of type AFooEdge to the neighbors
apply!(sim, AIndependent,
[AIndependent, AEdge],
[AIndependent, AFooEdge]) do state, id, sim
if state.foo == 1
nothing
else
foreach(neighborids(sim, id, AEdge)) do nid
add_edge!(sim, nid, id, AFooEdge(state.foo))
add_edge!(sim, id, nid, AFooEdge(state.foo))
end
state
end
end
apply!(simnot, ANotIndependent,
[ANotIndependent, AEdge],
[ANotIndependent, AFooEdge]) do state, id, sim
if state.foo == 1
nothing
else
foreach(neighborids(sim, id, AEdge)) do nid
add_edge!(sim, nid, id, AFooEdge(state.foo))
add_edge!(sim, id, nid, AFooEdge(state.foo))
end
state
end
end
apply!(simimmortal, AIndependentImmortal,
[AIndependentImmortal, AEdge],
[AIndependentImmortal, AFooEdge]) do state, id, sim
if state.foo == 1
nothing
else
foreach(neighborids(sim, id, AEdge)) do nid
add_edge!(sim, nid, id, AFooEdge(state.foo))
add_edge!(sim, id, nid, AFooEdge(state.foo))
end
state
end
end
@test num_agents(sim, AIndependent) == num_agents(simnot, ANotIndependent)
@test num_edges(sim, AEdge) == num_edges(simnot, AEdge)
@test num_edges(sim, AFooEdge) == num_edges(simnot, AFooEdge)
@test num_agents(simimmortal, AIndependentImmortal) == num_agents(simnot, ANotIndependent)
@test num_edges(simimmortal, AEdge) == num_edges(simnot, AEdge)
@test num_edges(simimmortal, AFooEdge) == num_edges(simnot, AFooEdge)
apply!(sim,
AIndependent,
[AIndependent, AEdge],
[AIndependent, AFooEdge]) do state, id, sim
if state.foo == 2
nothing
else
foreach(neighborids(sim, id, AEdge)) do nid
add_edge!(sim, nid, id, AFooEdge(state.foo))
add_edge!(sim, id, nid, AFooEdge(state.foo))
end
state
end
end
apply!(simnot,
ANotIndependent,
[ANotIndependent, AEdge],
[ANotIndependent, AFooEdge]) do state, id, sim
if state.foo == 2
nothing
else
foreach(neighborids(sim, id, AEdge)) do nid
add_edge!(sim, nid, id, AFooEdge(state.foo))
add_edge!(sim, id, nid, AFooEdge(state.foo))
end
state
end
end
apply!(simimmortal,
AIndependentImmortal,
[AIndependentImmortal, AEdge],
[AIndependentImmortal, AFooEdge]) do state, id, sim
if state.foo == 2
nothing
else
foreach(neighborids(sim, id, AEdge)) do nid
add_edge!(sim, nid, id, AFooEdge(state.foo))
add_edge!(sim, id, nid, AFooEdge(state.foo))
end
state
end
end
@test num_agents(sim, AIndependent) == num_agents(simnot, ANotIndependent)
@test num_edges(sim, AEdge) == num_edges(simnot, AEdge)
@test num_edges(sim, AFooEdge) == num_edges(simnot, AFooEdge)
@test num_agents(simimmortal, AIndependentImmortal) == num_agents(simnot, ANotIndependent)
@test num_edges(simimmortal, AEdge) == num_edges(simnot, AEdge)
@test num_edges(simimmortal, AFooEdge) == num_edges(simnot, AFooEdge)
apply!(sim,
AIndependent,
[AIndependent, AEdge],
[AIndependent, AFooEdge];
add_existing = AFooEdge) do state, id, sim
nid = add_agent!(sim, AIndependent(state.foo+10))
add_edge!(sim, nid, id, AFooEdge(nid))
add_edge!(sim, id, nid, AFooEdge(nid))
nid = add_agent!(sim, AIndependent(state.foo+20))
add_edge!(sim, nid, id, AFooEdge(nid))
add_edge!(sim, id, nid, AFooEdge(nid))
state
end
apply!(simnot,
ANotIndependent,
[ANotIndependent, AEdge],
[ANotIndependent, AFooEdge];
add_existing = AFooEdge) do state, id, sim
nid = add_agent!(sim, ANotIndependent(state.foo+10))
add_edge!(sim, nid, id, AFooEdge(nid))
add_edge!(sim, id, nid, AFooEdge(nid))
nid = add_agent!(sim, ANotIndependent(state.foo+20))
add_edge!(sim, nid, id, AFooEdge(nid))
add_edge!(sim, id, nid, AFooEdge(nid))
state
end
apply!(simimmortal,
AIndependentImmortal,
[AIndependentImmortal, AEdge],
[AIndependentImmortal, AFooEdge];
add_existing = AFooEdge) do state, id, sim
nid = add_agent!(sim, AIndependentImmortal(state.foo+10))
add_edge!(sim, nid, id, AFooEdge(nid))
add_edge!(sim, id, nid, AFooEdge(nid))
nid = add_agent!(sim, AIndependentImmortal(state.foo+20))
add_edge!(sim, nid, id, AFooEdge(nid))
add_edge!(sim, id, nid, AFooEdge(nid))
state
end
@test num_agents(sim, AIndependent) == num_agents(simnot, ANotIndependent)
@test num_edges(sim, AEdge) == num_edges(simnot, AEdge)
@test num_edges(sim, AFooEdge) == num_edges(simnot, AFooEdge)
@test num_agents(simimmortal, AIndependentImmortal) == num_agents(simnot, ANotIndependent)
@test num_edges(simimmortal, AEdge) == num_edges(simnot, AEdge)
@test num_edges(simimmortal, AFooEdge) == num_edges(simnot, AFooEdge)
finish_simulation!(sim)
finish_simulation!(simnot)
finish_simulation!(simimmortal)
sleep(mpi.rank * 0.05)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 480 | using Test
nprocs_str = get(ENV, "JULIA_MPI_TEST_NPROCS", "")
nprocs = nprocs_str == "" ? clamp(Sys.CPU_THREADS, 2, 4) : parse(Int, nprocs_str)
testdir = string(@__DIR__) * "/mpi"
istest(f) = endswith(f, ".jl") && startswith(f, "test_")
testfiles = sort(filter(istest, readdir(testdir)))
@testset "$f" for f in testfiles
cmd(n=nprocs) = `mpiexec -n $n $(Base.julia_cmd()) $(joinpath(testdir, f))`
#cmd(n=nprocs) = `mpirun -n 4 ls`
run(cmd(2))
@test true
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 946 | @testset "Parametric T." begin
struct PAgent{T}
t::T
end
struct PAgent2
t::Float64
end
struct PEdge{T}
t::T
end
model = ModelTypes() |>
register_agenttype!(PAgent{Float64}) |>
register_agenttype!(PAgent2) |>
register_edgetype!(PEdge{Float64}) |>
create_model("parametric types")
sim = create_simulation(model)
id1 = add_agent!(sim, PAgent(1.0))
id2 = add_agent!(sim, PAgent2(2.0))
add_edge!(sim, id1, id2, PEdge(3.0))
finish_init!(sim)
apply!(sim, PAgent2, [ PAgent{Float64}, PAgent2, PEdge{Float64} ], PAgent2) do agent, id, sim
@test (edges(sim, id, PEdge{Float64}) |> first).state.t == 3.0
@test edgestates(sim, id, PEdge{Float64}) == [ PEdge(3.0) ]
@test neighborstates(sim, id, PEdge{Float64}, PAgent{Float64}) ==
[ PAgent(1.0) ]
agent
end
finish_simulation!(sim)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 14623 | import Vahana: @onrankof, disable_transition_checks
struct GridA
pos::Tuple{Int64, Int64}
active::Bool
end
struct Grid3D
pos::Tuple{Int64, Int64, Int64}
active::Bool
end
struct GridE end
struct Position
sum::Int64
end
struct MovingAgent
value::Int64
end
struct OnPosition end
raster_model = ModelTypes() |>
register_agenttype!(GridA) |>
register_agenttype!(Grid3D) |>
register_edgetype!(GridE) |>
register_agenttype!(Position) |>
register_agenttype!(MovingAgent) |>
register_edgetype!(OnPosition) |>
create_model("Raster_Test")
@testset "Raster" begin
# calculate the sum of all ids
function diffuse(a, id, sim)
GridA(a.pos, a.active ||
mapreduce(a -> a.active, |, neighborstates(sim, id, GridE, GridA)))
end
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:grid,
(10,8),
p -> (p[1] == 10 && p[2] == 8) ? GridA(p, true) : GridA(p, false))
connect_raster_neighbors!(sim,
:grid,
(_,_) -> GridE())
finish_init!(sim)
@test mapreduce(sim, a -> a.active, +, GridA) == 1
apply!(sim, diffuse, [GridA], [GridA, GridE], [GridA])
@test mapreduce(sim, a -> a.active, +, GridA) == 9
apply!(sim, diffuse, [GridA], [GridA, GridE], [GridA])
@test mapreduce(sim, a -> a.active, +, GridA) == 25
raster = calc_rasterstate(sim, :grid, c -> c.active, Bool, GridA)
@test raster[1,3] == false
@test raster[1,1] == true
@test raster[4,4] == false
raster = calc_raster(sim, :grid, id -> agentstate(sim, id, GridA).active, Bool, [ GridA ])
@test raster[1,3] == false
@test raster[1,1] == true
@test raster[4,4] == false
finish_simulation!(sim)
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:grid,
(7,9),
p -> (p[1] == 3 && p[2] == 5) ? GridA(p, true) : GridA(p, false))
connect_raster_neighbors!(sim,
:grid,
(_,_) -> GridE())
finish_init!(sim)
@test mapreduce(sim, a -> a.active, +, GridA) == 1
apply!(sim, diffuse, [GridA], [GridA, GridE], [GridA])
@test mapreduce(sim, a -> a.active, +, GridA) == 9
apply!(sim, diffuse, [GridA], [GridA, GridE], [GridA])
@test mapreduce(sim, a -> a.active, +, GridA) == 25
# @test mapreduce(sim, GridA, a -> a.active, +) == 1
# apply!(sim, diffuse, [GridA], [GridA, GridE], [])
# @test mapreduce(sim, GridA, a -> a.active, +) == 9
# apply!(sim, diffuse, [GridA], [GridA, GridE], [])
# @test mapreduce(sim, GridA, a -> a.active, +) == 25
finish_simulation!(sim)
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:grid,
(17,6),
p -> (p[1] == 9 && p[2] == 1) ? GridA(p, true) : GridA(p, false))
connect_raster_neighbors!(sim,
:grid,
(_,_) -> GridE())
finish_init!(sim)
@test mapreduce(sim, a -> a.active, +, GridA) == 1
apply!(sim, diffuse, [GridA], [GridA, GridE], [GridA])
@test mapreduce(sim, a -> a.active, +, GridA) == 9
apply!(sim, diffuse, [GridA], [GridA, GridE], [GridA])
@test mapreduce(sim, a -> a.active, +, GridA) == 25
# @test mapreduce(sim, GridA, a -> a.active, +) == 1
# apply!(sim, diffuse, [GridA], [GridA, GridE], [])
# @test mapreduce(sim, GridA, a -> a.active, +) == 9
# apply!(sim, diffuse, [GridA], [GridA, GridE], [])
# @test mapreduce(sim, GridA, a -> a.active, +) == 25
finish_simulation!(sim)
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:grid,
(6,7),
p -> (p[1] == 1 && p[2] == 1) ? GridA(p, true) : GridA(p, false))
connect_raster_neighbors!(sim,
:grid,
(_,_) -> GridE())
finish_init!(sim)
@test mapreduce(sim, a -> a.active, +, GridA) == 1
apply!(sim, diffuse, [GridA], [GridA, GridE], [GridA])
@test mapreduce(sim, a -> a.active, +, GridA) == 9
apply!(sim, diffuse, [GridA], [GridA, GridE], [GridA])
@test mapreduce(sim, a -> a.active, +, GridA) == 25
### 3D
function diffuse3D(a, id, sim)
Grid3D(a.pos, a.active ||
mapreduce(a -> a.active, |, neighborstates(sim, id, GridE, Grid3D)))
end
finish_simulation!(sim)
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:grid,
(6,7,6),
p -> (p[1] == 1 && p[2] == 1 && p[3] == 1) ?
Grid3D(p, true) : Grid3D(p, false))
connect_raster_neighbors!(sim,
:grid,
(_,_) -> GridE())
finish_init!(sim)
@test mapreduce(sim, a -> a.active, +, Grid3D) == 1
apply!(sim, diffuse3D, [Grid3D], [Grid3D, GridE], [Grid3D])
@test mapreduce(sim, a -> a.active, +, Grid3D) == 3*3*3
apply!(sim, diffuse3D, [Grid3D], [Grid3D, GridE], [Grid3D])
@test mapreduce(sim, a -> a.active, +, Grid3D) == 5*5*5
### non-periodic
finish_simulation!(sim)
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:grid,
(6,7,6),
p -> (p[1] == 1 && p[2] == 1 && p[3] == 1) ?
Grid3D(p, true) : Grid3D(p, false))
connect_raster_neighbors!(sim,
:grid,
(_,_) -> GridE(),
periodic = false)
finish_init!(sim)
@test mapreduce(sim, a -> a.active, +, Grid3D) == 1
apply!(sim, diffuse3D, [Grid3D], [Grid3D, GridE], [Grid3D])
@test mapreduce(sim, a -> a.active, +, Grid3D) == 2*2*2
apply!(sim, diffuse3D, [Grid3D], [Grid3D, GridE], [Grid3D])
@test mapreduce(sim, a -> a.active, +, Grid3D) == 3*3*3
### distance 2
finish_simulation!(sim)
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:grid,
(6,7,6),
p -> (p[1] == 1 && p[2] == 1 && p[3] == 1) ?
Grid3D(p, true) : Grid3D(p, false))
connect_raster_neighbors!(sim,
:grid,
(_,_) -> GridE(),
periodic = false,
distance = 2)
finish_init!(sim)
@test mapreduce(sim, a -> a.active, +, Grid3D) == 1
apply!(sim, diffuse3D, [Grid3D], [Grid3D, GridE], [Grid3D])
@test mapreduce(sim, a -> a.active, +, Grid3D) == 3*3*3
apply!(sim, diffuse3D, [Grid3D], [Grid3D, GridE], [Grid3D])
@test mapreduce(sim, a -> a.active, +, Grid3D) == 5*5*5
finish_simulation!(sim)
### euclidean
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:grid,
(6,7,6),
p -> (p[1] == 1 && p[2] == 1 && p[3] == 1) ?
Grid3D(p, true) : Grid3D(p, false))
connect_raster_neighbors!(sim,
:grid,
(_,_) -> GridE();
distance = 1.5,
metric = :euclidean)
finish_init!(sim)
@test mapreduce(sim, a -> a.active, +, Grid3D) == 1
apply!(sim, diffuse3D, [Grid3D], [Grid3D, GridE], [Grid3D])
@test mapreduce(sim, a -> a.active, +, Grid3D) == 3*3*3-8
finish_simulation!(sim)
### manhatten
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:grid,
(6,7,6),
p -> (p[1] == 1 && p[2] == 1 && p[3] == 1) ?
Grid3D(p, true) : Grid3D(p, false))
connect_raster_neighbors!(sim,
:grid,
(_,_) -> GridE();
distance = 1.5,
metric = :manhatten)
finish_init!(sim)
@test mapreduce(sim, a -> a.active, +, Grid3D) == 1
apply!(sim, diffuse3D, [Grid3D], [Grid3D, GridE], [Grid3D])
@test mapreduce(sim, a -> a.active, +, Grid3D) == 7
finish_simulation!(sim)
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:grid,
(6,7,6),
p -> (p[1] == 1 && p[2] == 1 && p[3] == 1) ?
Grid3D(p, true) : Grid3D(p, false))
connect_raster_neighbors!(sim,
:grid,
(_,_) -> GridE();
periodic = false,
distance = 2,
metric = :manhatten)
finish_init!(sim)
@test mapreduce(sim, a -> a.active, +, Grid3D) == 1
apply!(sim, diffuse3D, [Grid3D], [Grid3D, GridE], [Grid3D])
@test mapreduce(sim, a -> a.active, +, Grid3D) == 10
finish_simulation!(sim)
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
@testset "Raster_NodeID" begin
# we have a raster with nodes of type Position and agents of type
# MovingAgent that are connected to this raster via edges of
# type OnPosition
# sum the value of all agents that are on the cell position
function sum_on_pos(::Val{Position}, id, sim)
nstates = neighborstates_flexible(sim, id, OnPosition)
if !isnothing(nstates)
Position(mapreduce(c -> c.value, +, nstates))
else
Position(0)
end
end
# this transition function moves the agent to the new pos, wherby the new
# pos is determined by the state of the current pos
function value_on_pos(::Val{MovingAgent}, id, sim)
# sum is not a sum operator, but a field of the agentstate of Position
value = first(neighborstates_flexible(sim, id, OnPosition)).sum
move_to!(sim, :raster, id, (value, value), OnPosition(), OnPosition())
MovingAgent(value)
end
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:raster,
(10,10),
_ -> Position(0))
connect_raster_neighbors!(sim,
:raster,
(_,_) -> GridE())
p1 = add_agent!(sim, MovingAgent(1))
p2 = add_agent!(sim, MovingAgent(2))
p3 = add_agent!(sim, MovingAgent(3))
move_to!(sim, :raster, p1, (1,1), OnPosition(), OnPosition())
move_to!(sim, :raster, p2, (2,2), OnPosition(), OnPosition())
move_to!(sim, :raster, p3, (2,2), OnPosition(), OnPosition())
finish_init!(sim)
apply!(sim, sum_on_pos, [ Position ], [ MovingAgent, OnPosition ], [ Position ])
raster = calc_rasterstate(sim, :raster, c -> c.sum, Int64, Position)
@test raster[1,1] == 1
@test raster[1,2] == 0
@test raster[2,2] == 5
@test raster[2,3] == 0
# new versions of calc_rasterstate
raster = calc_rasterstate(sim, :raster, c -> c.sum, Int64)
@test raster[1,1] == 1
@test raster[1,2] == 0
@test raster[2,2] == 5
@test raster[2,3] == 0
raster = calc_rasterstate(sim, :raster, c -> c.sum)
@test raster[1,1] == 1
@test raster[1,2] == 0
@test raster[2,2] == 5
@test raster[2,3] == 0
apply!(sim,
value_on_pos,
[ MovingAgent ],
[ Position, OnPosition ],
[ OnPosition, MovingAgent ])
apply!(sim, sum_on_pos,
[ Position ], [ MovingAgent, OnPosition ], [ Position ])
raster = calc_rasterstate(sim, :raster, c -> c.sum, Int64, Position)
@test raster[1,1] == 1
@test raster[1,2] == 0
@test raster[2,2] == 0
@test raster[5,5] == 10
finish_simulation!(sim)
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
@testset "MoveTo_Dist" begin
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:raster,
(10,10),
_ -> Position(0))
p1 = add_agent!(sim, MovingAgent(1))
p2 = add_agent!(sim, MovingAgent(1))
p3 = add_agent!(sim, MovingAgent(1))
move_to!(sim, :raster, p1, (4,4), OnPosition(), nothing;
distance = 2)
move_to!(sim, :raster, p2, (4,4), OnPosition(), nothing;
distance = 2, metric = :manhatten)
move_to!(sim, :raster, p3, (4,4), OnPosition(), nothing;
distance = 2.5, metric = :euclidean)
idmapping = finish_init!(sim, return_idmapping = true)
p1 = Vahana.updateids(idmapping, p1)
p2 = Vahana.updateids(idmapping, p2)
p3 = Vahana.updateids(idmapping, p3)
disable_transition_checks(true)
@onrankof p1 @test num_edges(sim, p1, OnPosition) == 25
@onrankof p2 @test num_edges(sim, p2, OnPosition) == 13
@onrankof p3 @test num_edges(sim, p3, OnPosition) == 21
disable_transition_checks(false)
finish_simulation!(sim)
######################################## 4D
sim = create_simulation(raster_model, nothing, nothing)
add_raster!(sim,
:raster,
(10,10,10,10),
_ -> Position(0))
p1 = add_agent!(sim, MovingAgent(1))
p2 = add_agent!(sim, MovingAgent(1))
move_to!(sim, :raster, p1, (4,4,4,4), OnPosition(), nothing;
distance = 1)
move_to!(sim, :raster, p2, (4,4,4,4), OnPosition(), nothing;
distance = 1, metric = :manhatten)
idmapping = finish_init!(sim, return_idmapping = true)
p1 = Vahana.updateids(idmapping, p1)
p2 = Vahana.updateids(idmapping, p2)
disable_transition_checks(true)
@onrankof p1 @test num_edges(sim, p1, OnPosition) == 3*3*3*3
@onrankof p2 @test num_edges(sim, p2, OnPosition) == 1+4*2
disable_transition_checks(false)
finish_simulation!(sim)
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
@testset "MoveTo_Dist" begin
sim = create_simulation(raster_model)
add_raster!(sim,
:raster,
(10,20,30),
p -> Grid3D(p, true))
finish_init!(sim)
w = zeros(10, 20, 30)
w[7, 19, 23] = 1.0
@test random_pos(sim, :raster, w) == CartesianIndex(7, 19, 23)
disable_transition_checks(true)
@test agentstate(sim, random_cell(sim, :raster, w), Grid3D).pos ==
(7, 19, 23)
disable_transition_checks(false)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 4018 | using Vahana
import Vahana.@onrankof
import Vahana.@rootonly
import Vahana.disable_transition_checks
import Graphs.SimpleGraphs
struct DAgent idx::Int64 end
struct DAgentRemove end
struct DEdgeState state::Int64 end
struct DEdge end
struct DSingleEdge end
struct DEdgeST end # ST = SingleType
model = ModelTypes() |>
register_agenttype!(DAgent) |>
register_agenttype!(DAgentRemove) |>
register_edgetype!(DEdge) |>
register_edgetype!(DEdgeState) |>
register_edgetype!(DSingleEdge, :SingleEdge) |>
register_edgetype!(DEdgeST, :SingleType; target = DAgent) |>
create_model("remove_agents")
@testset "Dying_Agents" begin
function test_edgetype(E)
sim = create_simulation(model)
ids = add_agents!(sim, [ DAgent(i) for i in 1:(mpi.size * 3)])
rids = add_agents!(sim, [ DAgentRemove() for _ in 1:mpi.size ])
# we create a network where with an edge for each agent to ids[2]
foreach(id -> add_edge!(sim, id, ids[2], E()), ids)
foreach(id -> add_edge!(sim, id, ids[2], DEdgeState(0)), rids)
# and a single edge from ids[1] to ids[3]
add_edge!(sim, ids[2], ids[3], E())
finish_init!(sim; partition_algo = :EqualAgentNumbers)
@test num_edges(sim, E) == (mpi.size * 3) + 1
@test num_edges(sim, DEdgeState) == mpi.size
# we remove all (1 per rank) agents of type DAgentRemove
apply!(sim,
[ DAgentRemove ],
[],
[ DAgentRemove ]) do _,_,_
nothing
end
@test num_edges(sim, E) == (mpi.size * 3) + 1
@test num_edges(sim, DEdgeState) == 0
apply!(sim, [ DAgent ], [ DAgent, E ], [ DAgent ]) do state, id, sim
if num_edges(sim, id, E) == 0
nothing
else
state
end
end
# the remaining edges are ids[3]->ids[2],rids[3]->ids[2],ids[2]->ids[3]
@test num_edges(sim, E) == 3
finish_simulation!(sim)
# run nearly the same test, but add the edges two times
if ! Vahana.has_hint(sim, E, :SingleEdge)
sim = create_simulation(model)
ids = add_agents!(sim, [ DAgent(i) for i in 1:(mpi.size * 3)])
rids = add_agents!(sim, [ DAgentRemove() for _ in 1:mpi.size ])
# we create a network where with an edge for each agent to ids[2]
foreach(id -> add_edge!(sim, id, ids[2], E()), ids)
foreach(id -> add_edge!(sim, id, ids[2], DEdgeState(0)), rids)
foreach(id -> add_edge!(sim, id, ids[2], E()), ids)
foreach(id -> add_edge!(sim, id, ids[2], DEdgeState(0)), rids)
# and a single edge from ids[1] to ids[3]
add_edge!(sim, ids[2], ids[3], E())
add_edge!(sim, ids[2], ids[3], E())
finish_init!(sim; partition_algo = :EqualAgentNumbers)
@test num_edges(sim, E) == ((mpi.size * 3) + 1) * 2
@test num_edges(sim, DEdgeState) == mpi.size * 2
# we remove all ADefault edges, that should also remove the ESDict edges
apply!(sim,
[ DAgentRemove ],
[],
[ DAgentRemove ]) do _,_,_
nothing
end
@test num_edges(sim, E) == ((mpi.size * 3) + 1) * 2
apply!(sim, [ DAgent ], [ DAgent, E ], [ DAgent ]) do state, id, sim
if num_edges(sim, id, E) == 0
nothing
else
state
end
end
# the remaining edges are ids[3]->ids[2],rids[3]->ids[2],ids[2]->ids[3]
@test num_edges(sim, E) == 6
finish_simulation!(sim)
end
end
test_edgetype(DEdge)
test_edgetype(DEdgeST)
# this hack should help that the output is not scrambled in the mpi test
sleep(mpi.rank * 0.05)
end
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 607 | # for whatever reason there is a pipline error when MPI.Init() is called before
# run(`mpiexec ...`), so first the mpi versions of the tests are called, before
# the single threaded versions.
#include("mpi.jl")
using Vahana
using Test
enable_asserts(true)
suppress_warnings(true)
include("core.jl")
include("remove_agents.jl")
include("addexisting.jl")
include("edges.jl")
runedgestest()
#edgesiterator depends on edges.jl
include("edgesiterator.jl")
include("parametric_types.jl")
include("independent.jl")
# depends on core
include("globals.jl")
include("raster.jl")
include("graphs.jl")
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 4935 | # This test should be run on multiple nodes, as it is designed to
# test the transfer of the agentstate between several nodes
using Test
using Vahana
using MPI
using Logging
enable_asserts(true)
suppress_warnings(true)
if mpi.size == mpi.shmsize
@rootonly println("This test is only for multi-node configurations")
exit()
end
# Logging.disable_logging(Logging.Info)
#MPI.set_errorhandler!(MPI.COMM_WORLD, MPI.ERRORS_RETURN)
# All ids are the initial ids
struct Agent
state::Int64
end
struct EdgeState
state::Int64
end
struct NewEdge
state::Int64
end
sim = ModelTypes() |>
register_agenttype!(Agent, :Immortal) |>
register_edgetype!(EdgeState, :SingleEdge) |>
register_edgetype!(NewEdge, :SingleEdge) |>
create_model("agentstatetest") |>
create_simulation()
ids = add_agents!(sim, [ Agent(i) for i in 1:mpi.size ])
for to in 2:mpi.size
add_edge!(sim, ids[to-1], ids[to], EdgeState(to-1))
end
newids = finish_init!(sim; partition_algo = :EqualAgentNumbers)
# first a check that we can read the state after initialization
apply!(sim, [ Agent ], [ Agent, EdgeState ], []) do _, id, sim
e = edges(sim, id, EdgeState)
if ! isnothing(e)
a = agentstate(sim, e.from, Agent)
@test e.state.state == a.state
end
end
# now we update the agentstate and check afterwards that the
# accessible state is also updated
apply!(sim, [ Agent ], [ Agent ], [ Agent ]) do state, _, _
Agent(state.state * 2)
end
apply!(sim, [ Agent ], [ Agent, EdgeState ], []) do _, id, sim
e = edges(sim, id, EdgeState)
if ! isnothing(e)
a = agentstate(sim, e.from, Agent)
@test e.state.state * 2 == a.state
end
end
# when we access the agentstate via the NewEdge type, this will not transfer any
# new state
apply!(sim, [ Agent ], [ Agent ], [ Agent ]) do state, _, _
Agent(state.state / 2)
end
apply!(sim, [ Agent ], [ Agent, NewEdge ], []) do _, id, sim
e = edges(sim, id, NewEdge)
@test isnothing(e)
end
# now add the NewEdges (by copying the old edges)
apply!(sim, [ Agent ], [ EdgeState ], [ NewEdge ]) do _, id, simsymbol
e = edges(sim, id, EdgeState)
if ! isnothing(e)
add_edge!(sim, e.from, id, NewEdge(e.state.state))
end
end
# and check that we get the correct agentstate via the new edges
apply!(sim, [ Agent ], [ Agent, EdgeState ], []) do _, id, sim
e = edges(sim, id, EdgeState)
if ! isnothing(e)
a = agentstate(sim, e.from, Agent)
@test e.state.state == a.state
end
end
finish_simulation!(sim)
# Test the same for mortal agents
sim = ModelTypes() |>
register_agenttype!(Agent) |>
register_edgetype!(EdgeState, :SingleEdge) |>
register_edgetype!(NewEdge, :SingleEdge) |>
create_model("agentstatetest-mortal") |>
create_simulation()
ids = add_agents!(sim, [ Agent(i) for i in 1:mpi.size ])
for to in 2:mpi.size
add_edge!(sim, ids[to-1], ids[to], EdgeState(to-1))
end
newids = finish_init!(sim; partition_algo = :EqualAgentNumbers)
# first a check that we can read the state after initialization
apply!(sim, [ Agent ], [ Agent, EdgeState ], []) do _, id, sim
e = edges(sim, id, EdgeState)
if ! isnothing(e)
a = agentstate(sim, e.from, Agent)
@test e.state.state == a.state
end
end
# call it a second time to trigger the filter of already existing keys
apply!(sim, [ Agent ], [ Agent, EdgeState ], []) do _, id, sim
e = edges(sim, id, EdgeState)
if ! isnothing(e)
a = agentstate(sim, e.from, Agent)
@test e.state.state == a.state
end
end
# now we update the agentstate and check afterwards that the
# accessible state is also updated
apply!(sim, [ Agent ], [ Agent ], [ Agent ]) do state, _, _
Agent(state.state * 2)
end
apply!(sim, [ Agent ], [ Agent, EdgeState ], []) do _, id, sim
e = edges(sim, id, EdgeState)
if ! isnothing(e)
a = agentstate(sim, e.from, Agent)
@test e.state.state * 2 == a.state
end
end
# when we access the agentstate via the NewEdge type, this will not transfer any
# new state
apply!(sim, [ Agent ], [ Agent ], [ Agent ]) do state, _, _
Agent(state.state / 2)
end
apply!(sim, [ Agent ], [ Agent, NewEdge ], []) do _, id, sim
e = edges(sim, id, NewEdge)
@test isnothing(e)
end
# now add the NewEdges (by copying the old edges)
apply!(sim, [ Agent ], [ EdgeState ], [ NewEdge ]) do _, id, simsymbol
e = edges(sim, id, EdgeState)
if ! isnothing(e)
add_edge!(sim, e.from, id, NewEdge(e.state.state))
end
end
# and check that we get the correct agentstate via the new edges
apply!(sim, [ Agent ], [ Agent, EdgeState ], []) do _, id, sim
e = edges(sim, id, EdgeState)
if ! isnothing(e)
a = agentstate(sim, e.from, Agent)
@test e.state.state == a.state
end
end
finish_simulation!(sim)
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 167 | using Test
using Vahana
using MPI
enable_asserts(true)
suppress_warnings(true)
#MPI.set_errorhandler!(MPI.COMM_WORLD, MPI.ERRORS_RETURN)
include("../core.jl")
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 198 | using Test
using Vahana
using MPI
enable_asserts(true)
suppress_warnings(true)
#MPI.set_errorhandler!(MPI.COMM_WORLD, MPI.ERRORS_RETURN)
include("../edges.jl")
include("../edgesiterator.jl")
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 15849 |
using Revise
using Test
using Vahana
import Vahana.has_hint
using MPI
using Logging
import Graphs: SimpleGraphs
enable_asserts(true)
suppress_warnings(true)
# Logging.disable_logging(Logging.Info)
#MPI.set_errorhandler!(MPI.COMM_WORLD, MPI.ERRORS_RETURN)
# All ids are the initial ids
@assert mod(mpi.size, 2) == 0 """
We need as minimum 2 PEs and also an even number of PEs"""
struct AgentState1
idx::Int64
end
struct AgentState2
idx::Int64
something::Bool
end
struct MPIEdgeD fromid::AgentID; toid::AgentID end # D for default (no hint is set)
struct MPIEdgeS end
struct MPIEdgeE fromid::AgentID; toid::AgentID end
struct MPIEdgeT fromid::AgentID; toid::AgentID end
struct MPIEdgeI fromid::AgentID; toid::AgentID end
struct MPIEdgeSE end
struct MPIEdgeST end
struct MPIEdgeSI end
struct MPIEdgeEI fromid::AgentID; toid::AgentID end
struct MPIEdgeTI fromid::AgentID; toid::AgentID end
struct MPIEdgeSEI end
struct MPIEdgeSTI end
struct MPIEdgeSETI end
struct MPIEdgeTs fromid::AgentID; toid::AgentID end
struct MPIEdgeTsI fromid::AgentID; toid::AgentID end
struct MPIEdgeSTs end
struct MPIEdgeSTsI end
struct MPIEdgeSETsI end
struct SendId end
statelessMPIEdgeTypes = [ MPIEdgeS, MPIEdgeSE, MPIEdgeST, MPIEdgeSI, MPIEdgeSEI, MPIEdgeSTI, MPIEdgeSETI, MPIEdgeSTs, MPIEdgeSTsI, MPIEdgeSETsI ]
statefulMPIEdgeTypes = [ MPIEdgeD, MPIEdgeE, MPIEdgeT, MPIEdgeI, MPIEdgeEI, MPIEdgeTI, MPIEdgeTs, MPIEdgeTsI ]
model = ModelTypes() |>
register_agenttype!(AgentState1) |>
register_agenttype!(AgentState2) |>
register_edgetype!(MPIEdgeD) |>
register_edgetype!(MPIEdgeS, :Stateless) |>
register_edgetype!(MPIEdgeE, :SingleEdge) |>
register_edgetype!(MPIEdgeT, :SingleType; target = AgentState1) |>
register_edgetype!(MPIEdgeI, :IgnoreFrom) |>
register_edgetype!(MPIEdgeSE, :Stateless, :SingleEdge) |>
register_edgetype!(MPIEdgeST, :Stateless, :SingleType; target = AgentState1) |>
register_edgetype!(MPIEdgeSI, :Stateless, :IgnoreFrom) |>
register_edgetype!(MPIEdgeEI, :SingleEdge, :IgnoreFrom) |>
register_edgetype!(MPIEdgeTI, :SingleType, :IgnoreFrom; target = AgentState1) |>
register_edgetype!(MPIEdgeSEI, :Stateless, :SingleEdge, :IgnoreFrom) |>
register_edgetype!(MPIEdgeSTI, :Stateless, :SingleType, :IgnoreFrom; target = AgentState1) |>
register_edgetype!(MPIEdgeSETI, :Stateless, :SingleEdge, :SingleType, :IgnoreFrom; target = AgentState1) |>
register_edgetype!(MPIEdgeTs, :SingleType; target = AgentState1, size = mpi.size * 2) |>
register_edgetype!(MPIEdgeTsI, :SingleType, :IgnoreFrom; target = AgentState1, size = mpi.size* 2) |>
register_edgetype!(MPIEdgeSTs, :Stateless, :SingleType; target = AgentState1, size = mpi.size * 2) |>
register_edgetype!(MPIEdgeSTsI, :Stateless, :SingleType, :IgnoreFrom; target = AgentState1, size = mpi.size * 2) |>
register_edgetype!(MPIEdgeSETsI, :Stateless, :SingleEdge, :SingleType, :IgnoreFrom; target = AgentState1, size = mpi.size * 2) |>
register_edgetype!(SendId, :SingleEdge) |>
create_model("MPI EdgeTypes");
###
# We have the following edge setup (as an example for mpi.size of 3, but
# everything is modulo mpi.size)
# AS1_1 -> AS1_2
# AS1_1 -> AS2_2
# AS1_2 -> AS1_3
# AS1_2 -> AS2_3
# AS1_3 -> AS1_1
# AS1_3 -> AS2_1
function check(ET)
(agent, id, sim) -> begin
@test has_edge(sim, id, ET)
end
end
# non reversed
function check_state(ET)
(agent, id, sim) -> begin
if has_hint(sim, ET, :SingleEdge)
@test has_edge(sim, id, ET)
if ! has_hint(sim, ET, :IgnoreFrom)
@test neighborstates(sim, id, ET, AgentState1).idx ==
mod1(agent.idx - 1, mpi.size)
end
else
@test num_edges(sim, id, ET) == 1
if ! has_hint(sim, ET, :IgnoreFrom)
@test first(neighborstates(sim, id, ET, AgentState1)).idx ==
mod1(agent.idx - 1, mpi.size)
end
end
end
end
# reversed
# AS1_1 <- AS1_2
# AS1_1 <- AS2_2
# AS1_2 <- AS1_3
# AS1_2 <- AS2_3
# AS1_3 <- AS1_1
# AS1_3 <- AS2_1
# so the edges are going only to AgentState1. The edges from AS2 are
# dropped for the :SingleEdge and :SingleType hints.
function check_state_rev1(ET)
(agent::AgentState1, id, sim) -> begin
if has_hint(sim, ET, :SingleEdge)
@test has_edge(sim, id, ET)
if ! has_hint(sim, ET, :IgnoreFrom)
@test neighborstates(sim, id, ET, AgentState1).idx ==
mod1(agent.idx + 1, mpi.size)
end
elseif has_hint(sim, ET, :SingleType)
@test num_edges(sim, id, ET) == 1
if ! has_hint(sim, ET, :IgnoreFrom)
@test first(neighborstates(sim, id, ET, AgentState1)).idx ==
mod1(agent.idx + 1, mpi.size)
end
else
@test num_edges(sim, id, ET) == 2
if ! has_hint(sim, ET, :IgnoreFrom)
@test first(neighborstates_flexible(sim, id, ET)).idx ==
mod1(agent.idx + 1, mpi.size)
end
end
end
end
# check that nothing is going to the AS2 agents anymore
function check_state_rev2(ET)
(_, id, sim) -> begin
# for the SingleType we determined that ET can only go to AS1 agents
if ! has_hint(sim, ET, :SingleType)
@test ! has_edge(sim, id, ET)
end
end
end
# we change the direction of the cycle, after the first call
# the edges are going from id to id-1 (mod mpi.size)
# as we use a hack that allows us to test also :IgnoreFrom edges,
# a second reverse does not result in the original state
function reverse_edge_direction(ET)
(state, id, sim) -> begin
# In the :SingleType case there are no edges to AgentState2
if has_hint(sim, ET, :SingleType) && typeof(state) == AgentState2
return
end
# If we would reverse the edges in the :SingleEdge case,
# two edges would point to the same agent.
if has_hint(sim, ET, :SingleEdge) && typeof(state) == AgentState2
return
end
# we are know how the edges are constructed and how ids are given
# so we use this information to create the needed ids even
# for the :IgnoreFrom case
target_rank = mod(state.idx - 2, mpi.size)
target_id = AgentID(1 << Vahana.SHIFT_TYPE +
target_rank << Vahana.SHIFT_RANK + 1)
if has_hint(sim, ET, :Stateless)
add_edge!(sim, id, target_id, ET())
else
if has_hint(sim, ET, :SingleEdge)
nstate = edgestates(sim, id, ET)
else
nstate = edgestates(sim, id, ET) |> first
end
add_edge!(sim, id, target_id, nstate)
end
end
end
function testforedgetype(ET)
sim = create_simulation(model, nothing, nothing)
part = Dict{AgentID, UInt32}()
# construct the edges as described above
if mpi.isroot
agentids = add_agents!(sim, [ AgentState1(i) for i in 1:mpi.size ])
agentids2 = add_agents!(sim, [ AgentState2(i, true) for i in 1:mpi.size ])
for i in 1:mpi.size
# the edges construct a directed cycle, going from id-1 to id
fromid = agentids[mod1(i-1, mpi.size)]
toid = agentids[i]
toid2 = agentids2[i]
if ! has_hint(sim, ET, :Stateless)
add_edge!(sim, fromid, toid, ET(fromid, toid))
if ! has_hint(sim, ET, :SingleType)
add_edge!(sim, fromid, toid2, ET(fromid, toid))
end
else
add_edge!(sim, fromid, toid, ET())
if ! has_hint(sim, ET, :SingleType)
add_edge!(sim, fromid, toid2, ET())
end
end
end
for i in 1:mpi.size
part[agentids[i]] = i
part[agentids2[i]] = mod1(i, 2)
end
end
# copy the simulation, so that we can test with an manual partition
# so that we can test that the agents/edges are moved to the expected
# nodes and also the partitioning via Metis later
@test num_agents(sim, AgentState1, false) == (mpi.isroot ? mpi.size : 0)
@test num_agents(sim, AgentState2, false) == (mpi.isroot ? mpi.size : 0)
@test num_agents(sim, AgentState1) == mpi.size
@test num_agents(sim, AgentState2) == mpi.size
num_edges_per_PE = has_hint(sim, ET, :SingleType) ? 1 : 2
@test num_edges(sim, ET; write = true) == mpi.size * num_edges_per_PE
finish_init!(sim; partition_algo = :EqualAgentNumbers)
apply!(sim, check_state(ET), [ AgentState1 ],
[ AgentState1, ET ], [])
@test num_agents(sim, AgentState1, false) == 1
@test num_agents(sim, AgentState2, false) == 1
@test num_agents(sim, AgentState1) == mpi.size
@test num_agents(sim, AgentState2) == mpi.size
@test num_edges(sim, ET; write = true) == mpi.size * num_edges_per_PE
# we are testing now that new edges in the transition functions are
# send to the correct ranks
apply!(sim, reverse_edge_direction(ET),
[ AgentState1, AgentState2 ],
[ AgentState1, AgentState2, ET ],
[ ET ])
apply!(sim, check_state_rev1(ET),
[ AgentState1 ],
[ AgentState1, AgentState2, ET ],
[])
apply!(sim, check_state_rev2(ET),
[ AgentState2 ],
[ ET ], [])
finish_simulation!(sim)
end
# @testset "EdgeTypes" begin
# CurrentEdgeType = Nothing
# if CurrentEdgeType === Nothing
# for ET in [ statelessMPIEdgeTypes; statefulMPIEdgeTypes ]
# testforedgetype(ET)
# end
# else
# testforedgetype(CurrentEdgeType)
# end
# # this hack should help that the output is not scrambled
# sleep(mpi.rank * 0.05)
# end
###
function testforedgetype_remove(ET)
sim = create_simulation(model, nothing, nothing)
# each agent has exact one neighbar
if has_hint(sim, ET, :Stateless)
add_graph!(sim,
SimpleGraphs.cycle_digraph(100),
i -> AgentState1(i),
_ -> ET())
else
add_graph!(sim,
SimpleGraphs.cycle_digraph(100),
i -> AgentState1(i),
_ -> ET(0, 0))
end
finish_init!(sim)
removed = apply(sim, AgentState1, [AgentState1, ET], ET;
add_existing = ET) do self, id, sim
if self.idx % 2 == 0
remove_edges!(sim, id, ET)
end
end
@test num_edges(removed, ET) == 50
finish_simulation!(removed)
copy = copy_simulation(sim)
if ! has_hint(sim, ET, :IgnoreFrom)
removed = apply(sim, AgentState1, [AgentState1, ET], ET;
add_existing = ET) do self, id, sim
if self.idx % 2 == 0
nid = neighborids(sim, id, ET) |> first
remove_edges!(sim, nid, ET)
end
end
@test num_edges(removed, ET) == 50
finish_simulation!(removed)
end
finish_simulation!(sim)
# remove_edges! and add_edge! for the same edge should keep the edge
# (the order depends on the handling if the send edges)
if ! has_hint(sim, ET, :IgnoreFrom)
apply!(copy, AgentState1, ET, ET; add_existing = ET) do self, id, sim
fromid = neighborids(sim, id, ET) |> first
remove_edges!(sim, fromid, id, ET)
if has_hint(sim, ET, :Stateless)
add_edge!(sim, fromid, id, ET())
else
add_edge!(sim, fromid, id, ET(0,0))
end
end
@test num_edges(copy, ET) == 100
end
finish_simulation!(copy)
end
function testforedgetype_remove_from(ET)
sim = create_simulation(model, nothing, nothing)
graph = if has_hint(sim, ET, :SingleEdge)
SimpleGraphs.cycle_digraph(100)
else
SimpleGraphs.complete_graph(100)
end
if has_hint(sim, ET, :Stateless)
add_graph!(sim,
graph,
i -> AgentState1(i),
_ -> ET())
else
add_graph!(sim,
graph,
i -> AgentState1(i),
_ -> ET(0, 0))
end
finish_init!(sim)
if has_hint(sim, ET, :SingleEdge)
@assert num_edges(sim, ET) == 100 # all 100 agents have 1 edge
else
@assert num_edges(sim, ET) == 9900 # all 100 agents have 99 edges
end
sim2 = copy_simulation(sim)
sim3 = copy_simulation(sim)
apply!(sim, AgentState1, [AgentState1, ET], ET;
add_existing = ET) do self, id, sim
nids = neighborids(sim, id, ET)
remove_edges!(sim, first(nids), id, ET)
if ! has_hint(sim, ET, :SingleEdge)
remove_edges!(sim, nids[2], id, ET)
end
end
if has_hint(sim, ET, :SingleEdge)
@test num_edges(sim, ET) == 0
else
@test num_edges(sim, ET) == 9700 # we remove for 100 agent 2 edges
end
# test also to remove the edges in the other direction
if !has_hint(sim, ET, :SingleEdge)
apply!(sim2, AgentState1, [AgentState1, ET], ET;
add_existing = ET) do self, id, sim
if self.idx % 2 == 0
nid = rand(neighborids(sim, id, ET))
remove_edges!(sim, id, nid, ET)
end
end
@test num_edges(sim2, ET) == 9850 # we remove for 50 agent 2 edges
else
apply!(sim2, AgentState1, ET, SendId) do _, id, sim
nid = neighborids(sim, id, ET)
add_edge!(sim2, id, nid, SendId())
end
apply!(sim2, AgentState1, [AgentState1, ET, SendId], ET;
add_existing = ET) do self, id, sim
if self.idx < 100
nid = neighborids(sim, id, SendId)
remove_edges!(sim, id, nid, ET)
end
end
@test num_edges(sim2, ET) == 1
end
# test that we can call it with a from value for which we did not
# have added edges
apply!(sim3, AgentState1, [], ET; add_existing = ET) do _, id, sim
remove_edges!(sim, AgentID(0), id, ET)
end
if has_hint(sim, ET, :SingleEdge)
@test num_edges(sim3, ET) == 100 # all 100 agents have 1 edge
else
@test num_edges(sim3, ET) == 9900 # all 100 agents have 99 edges
end
@test_throws AssertionError apply!(sim3, AgentState1, [], []) do _, id, sim
remove_edges!(sim, AgentID(0), id, ET)
end
@test_throws AssertionError apply!(sim3, AgentState1, [], ET) do _, id, sim
remove_edges!(sim, AgentID(0), id, ET)
end
finish_simulation!(sim)
finish_simulation!(sim2)
finish_simulation!(sim3)
end
@testset "remove edges" begin
CurrentEdgeType = Nothing
if CurrentEdgeType === Nothing
for ET in [ MPIEdgeD, MPIEdgeS, MPIEdgeE, MPIEdgeI, MPIEdgeSE,
MPIEdgeSI, MPIEdgeEI, MPIEdgeSEI, MPIEdgeSTI, MPIEdgeSETI,
MPIEdgeT, MPIEdgeST ]
testforedgetype_remove(ET)
end
else
testforedgetype_remove(CurrentEdgeType)
end
if CurrentEdgeType === Nothing
for ET in [ MPIEdgeD, MPIEdgeS, MPIEdgeE, MPIEdgeSE,
MPIEdgeT, MPIEdgeST ]
testforedgetype_remove_from(ET)
end
else
testforedgetype_remove_from(CurrentEdgeType)
end
# this hack should help that the output is not scrambled
sleep(mpi.rank * 0.05)
end
###
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 114 | using Test
using Vahana
using MPI
enable_asserts(true)
suppress_warnings(true)
include("../independent.jl")
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 169 | using Test
using Vahana
using MPI
enable_asserts(true)
suppress_warnings(true)
#MPI.set_errorhandler!(MPI.COMM_WORLD, MPI.ERRORS_RETURN)
include("../raster.jl")
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | code | 175 | using Test
using Vahana
using MPI
enable_asserts(true)
suppress_warnings(true)
#MPI.set_errorhandler!(MPI.COMM_WORLD, MPI.ERRORS_RETURN)
include("../remove_agents.jl")
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 3089 | # Vahana - A framework (not only) for large-scale agent-based models
Vahana is a high-performance, agent-based modelling library developed
in Julia, specifically (but not only) designed for large-scale
simulations of complex social networks. It leverages the power of Graph
Dynamical Systems, coupled with advanced parallel computing
methodologies, to provide a robust framework for the exploration of
network-based systems.
## Key Features
- Efficient and Scalable: Vahana uses Message Passing Interface (MPI)
for distributed memory parallelism, allowing for efficient scaling
to thousands of cores.
- Expressive Interface: Despite its high-performance capabilities,
Vahana is designed with an accessible and expressive interface,
making the construction of complex models intuitive and easy.
- Network-Oriented Approach: Vahana's design focuses on network
dynamics, making it an excellent tool for simulations involving
complex interactions and dependencies between agents.
- Graph Dynamical Systems: Leveraging the principles of Graph
Dynamical Systems, Vahana provides a solid theoretical foundation
for modelling agent-based systems.
- Integration into the Julia Ecosystem: Vahana interacts seamlessly
with other Julia libraries, such as DataFrames and Graphs.
- HDF5 Data Persistence: For efficient data storage and access, Vahana
utilises the Hierarchical Data Format version 5 (HDF5), including
optional support for parallel HDF5.
## Installation
You can install Vahana in Julia using the following command:
```
using Pkg
Pkg.add("Vahana")
```
If you want to run a simulation in parallel, it is useful to also read
the configuration/installation sections of the
[MPI.jl](https://juliaparallel.org/MPI.jl/stable/configuration/) and
[HDF5.jl](https://juliaio.github.io/HDF5.jl/stable/#Installation)
libraries.
## Documentation
Full documentation, including tutorials, guides, and API references,
is available [here](https://s-fuerst.github.io/Vahana.jl/).
A JuliaCon 2023 Pre-recorded Video about Vahana is available [here](https://www.youtube.com/watch?v=-318ec-kCBM).
The preprint of a Vahana.jl paper is available [here](https://doi.org/10.48550/arXiv.2406.14441)
## Citation
If you use this package in a publication, or simply want to refer to it, please cite the paper below:
```
@article{vahana2024,
title={Vahana.jl - A framework (not only) for large-scale agent-based models},
author={F{\"u}rst, Steffen and Conrad, Tim and Jaeger, Carlo and Wolf, Sarah},
journal={arXiv preprint arXiv:2406.14441},
year={2024},
doi={10.48550/arXiv.2406.14441},
url={https://doi.org/10.48550/arXiv.2406.14441},
eprint={2406.14441},
archivePrefix={arXiv},
primaryClass={cs.MA}
}
```
## Acknowledgments

This research has been partially funded under Germany’s Excellence
Strategy, MATH+ : The Berlin Mathematics Research Center (EXC-2046/1),
project no. 390685689
## License
Vahana is distributed under the MIT license. For more
information, please refer to the LICENSE file in this repository.
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 74 | ```@meta
CurrentModule = Vahana -->
```
```@index
Modules = [Vahana]
```
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 4379 | ```@meta
CurrentModule = Vahana
```
# Change Log
## v1.2
### Breaking changes
- The `all_ranks` default value for [`num_agents`](@ref) changed to true.
### New features
- The functions [`all_agentids`](@ref) and [`all_edges`](@ref) allows
to get the ids of all agents or the edges on the rank or the
complete simulation.
- The functions [`write_metadata`](@ref),
[`write_sim_metadata`](@ref), [`read_sim_metadata`](@ref) and
[`read_metadata`](@ref) allows to attach Metadata to the simulation
or individual parts of the model.
- Instead of writing structs for Parameters and Globals it is now also possible
to use [`register_param!`](@ref) and [`register_global!`](@ref).
- Random cells or positions of a grid can be obtained via
[`random_pos`](@ref) and [`random_cell`](@ref)
- The function [`cellid`](@ref) allows to retrieve the id of a cell on
a given position.
- The functions [`remove_edges!`](@ref) allows to remove edges between
to agents, or all edges to an agent.
- The new function [`rastervalues`](@ref) can be sometimes a useful shorter
version then [`calc_rasterstate`](@ref).
- New functions [`set_log_path`](@ref) allows to set the path for
log files.
- The keyword `with_edge` of the function [`apply`](@ref) allows to
restrict the called agents to those agents that have an edge of type
`with_edge`. - The new `:Independet` hint can be given to agent
types if agents of this type never access the state of other agents
of this type. This allows Vahana to directly modify the state of an
agent in its transition functions without having to copy all agents
of that type.
- The new hint `:Independent` can be given to agent types if agents of
this type never access the state of other agents of this type. This
allows Vahana to change the state of an agent directly in the
corresponding vector in a transition functions without copying all
agents of this type.
- For [`neighborstates`](@ref), [`neighborstates_flexible`](@ref),
[`neighborids`](@ref) and [`edgestates`](@ref) there are now
also functions that return an iterator for of states/ids instead
of a vector these states/ids. They have the same function name,
extended with `_iter`, e.g. [`neighborstates_iter`](@ref).
- The function [`add_agent_per_process!`](@ref) allows you to add a single
agent of an agent type to each process of a parallel simulation.
- New function [`modify_global!`](@ref) which is a combination of
[`set_global!`](@ref) and [`get_global`](@ref).
### Improvements
- [`read_snapshot!`](@ref) can be also used to read data that was
written via calls to [`write_agents`](@ref), [`write_edges`](@ref)
etc..
- [`calc_rasterstate`](@ref) tries to retrieve the returned type
automatically by default.
- When [`show_agent`](@ref) is called with an id, it is no longer
necessary to give also the agent type.
- Improved error messages.
- Julia 1.11 introduced a breaking change in Stateful
Iterators. Vahana's edge iterators have now been adapted to
accommodate this breaking change.
### Performance Improvements
- [`move_to!`](@ref) improvements.
- Removed an unnecessary memcpy of edges for the case that the type is
in the `add_existing` argument, but not in the `read` argument of a
transition function.
### Fixes
- When edges were removed as a consequence of removing agents, this
change was not written to the hdf5 file until also other changes to
the edges of this type happen.
- In a parallel simulation, sometime not all edges were written to the
hdf5 file.
- Fixed a compability issue with Microsofts MPI implementation.
- log folder was also created when no log file was written.
- [`show_agent`](@ref) didn't work for all agent hint combinations.
- It was necessary (and not documented) that [`add_raster!`](@ref) was
called from all ranks. Now it is possible to call it only from rank
0 (like [`add_agent!`](@ref) etc.).
## v1.1
### New features
- New functions [`set_hdf5_path`](@ref) allows to set the path for
hdf5 files.
### Improvements
- Removed usage of Base.memcpy! do be compatible with Julia 1.10.
- Improved error messages.
### Performance Improvements
- For [`calc_raster`](@ref) and [`calc_rasterstate`](@ref).
### Fixes
- Empty arrays where not supported for parameters or globals when
they where writted to a hdf5 file.
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 198 | ```@meta
CurrentModule = Vahana
```
# Configuration
The following functions allows to configure Vahana's behaviour:
```@docs
enable_asserts
suppress_warnings
detect_stateless
set_compression
```
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 3410 | ```@meta
CurrentModule = Vahana
```
# Model Definition
This page describes the functions and data structures employed to
define the model and to instantiate an uninitialized simulation. In
Vahana the simulation state and the transition functions that changes
the state are decoupled, eliminating the need to define the
transition functions prior to creating the simulation instance.
The usual workflow is as follows:
- Define the Agent and Edge types
- Create a [`ModelTypes`](@ref) instance
- Register the Agent and Edge types and optionally the Parameters and Globals
- Call [`create_model`](@ref) to create an model (state space) object
- Call [`create_simulation`](@ref) to create an uninitialized simulation of this model
The simplest example for such a workflow is:
```
struct Agent end
struct EdgeState end
const sim = ModelTypes() |>
register_agenttype!(Agent) |>
register_edgetype!(EdgeState) |>
create_model("Minimal Example") |>
create_simulation()
```
After the simulation is created, the next step is its initialization,
which is described on the [next](./initialization.md) page.
## Construct the Model
Before we can construct a model, we need to register all agent and
edge types.
```@docs
ModelTypes
register_agenttype!
register_edgetype!
```
We can then use the `ModelTypes` instance to construct the model.
Which means that optimized methods that can be used to access or
modify the simulation state during the transition function are
generated. See [Performance Tuning](./performance.md) for details.
The `ModelTypes` instance can subsequently be utilized to construct
the model. This involves that optimized methods are generated, enabling
access or modification of the simulation state during the execution of
the transition function. For comprehensive details regarding this
process, please refer to the [Performance Tuning](./performance.md)
documentation.
!!! tip
As [`create_model`](@ref) adds new methods, it increments the
["world age counter"](https://docs.julialang.org/en/v1/manual/methods/#Redefining-Methods).
This means, that you can not construct the model in the same function
as you initialize it. But you can call [`create_simulation`](@ref) in the same function so
```
const model = create_model(modeltypes, "Minimal Example")
function create_and_init()
sim = create_simulation(model, nothing, nothing)
add_agent!(sim, Agent())
end
```
is valid code.
```@docs
create_model
Model
```
## Register Parameters and Globals
Parameters are constant values used throughout the simulation, while
globals are variables that can change during the simulation run. You
can register them using `register_param!` and `register_global!`, or
by defining custom types and pass instances of this types to
[`create_simulation`](@ref).
```@docs
register_param!
register_global!
```
# Create a Simulation
Finally, create an uninitialized simulation based on your model using
```@docs
create_simulation
```
This creates a blank simulation ready for initialization.
Remember, in Vahana, a "model" specifies the possible state space,
while a simulation is a concrete realization within this
space. Transition functions, defined later, determine how the
simulation evolves over time.
By following these steps, you set up the structure of your
simulation. The next phase involves initializing the simulation with
agents and edges.
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 539 | ```@meta
CurrentModule = Vahana
```
# Modify Globals
You can add a new or additional value to the `globals` struct with:
```@docs
set_global!
push_global!
modify_global!
Vahana.mapreduce
```
!!! warning
The state of the globals struct (the `globals` argument of the
[`create_simulation`](@ref) function can not be changed
inside of a transition function, as a transition function is calculated on
a per agent basis with many evaluations in parallel, and changes to the
global layer must be a single, synchronized operation.
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 4011 | ```@meta
CurrentModule = Vahana
```
# HDF5 data storage
Vahana uses the Hierarchical Data Format version 5 (HDF5) as file
format to store simulations to disc, utilizing the HDF5.jl
libary. HDF5.jl again uses a C library, which is either installed with
HDF5.jl or can be provided by the system. Please check the [HDF5.jl
documentation](https://juliaio.github.io/HDF5.jl/stable/#Installation)
for details.
If the provided library supports Parallel HDF5, this will be used
automatically. Using Parallel HDF5 has the advantage that all
processes can write to a single file, without Parallel HDF5 multiple
files are created for a single (parallel) simulation (but the Vahana
API is the same in any case, so for the user this difference is only
visible when looking into the h5 directory with a file manager or via
the shell). But in the current Vahana version using Parallel HDF5 has
the disadvantage, that the files are not compressed (see also
[`set_compression`](@ref)).
## Write
To write into a HDF5 file, they are `attached` to a Vahama
simulation. Normally this happens automatically when the first time a
write function like [`write_snapshot`](@ref) is called. All following
`write_*` calls then add additional datasets to the file.
```@docs
set_hdf5_path
write_snapshot
create_h5file!
close_h5file!
```
Beside `write_snapshot` there exists also some more fine grained write
functions:
```@docs
write_agents
write_edges
write_globals
```
## Read
In the normal use case we call just `write_snapshot(sim, "snapshot
description")` (assuming sim is a Vahama simulation). To read such a
snapshot, we can then run another Script that creates the same model
(see [`create_model`](@ref)) and simulation (see
[`create_simulation`](@ref)) and then call
`read_snapshot!(sim)`. [`read_snapshot!`](@ref) can read also a
parallel simulation into a single (REPL) process, then the distributed
graph is merged into a single one.
```@docs
read_snapshot!
```
Also here exists also some more fine grained read functions:
```@docs
read_params
read_globals
read_agents!
read_edges!
read_agents
read_edges
```
## Transition
All `read_*` functions have a keyword called transition. If this is
not set, the last stored data of a type is always read, but via this
keyword it is also possible to read the previous state of the
simulation (or a part of it) (assuming it was written multiple times,
of course).
Vahana counts internally how many times the function [`apply!`](@ref)
is called (in the current Vahana implementation this is stored in a
field called `num_transitions` of the simulation). When a new dataset
is created by a `write_*` call, this information is stored with the
dataset.
When `read_snapshot!` is called, Vahana looks for the highest
`num_transition` that is less than or equal to the transition keyword
for the types to be read. Since the default value for the argument is
typemax(Int64), the newest dataset is read by default.
For snapshots the `list_snapshots` function returns a list of all
stored snapshots in the file.
```@docs
list_snapshots
```
## Metadata
It's possible to attach Metadata to the parameters and globals of a
simulation.
```@docs
write_metadata
write_sim_metadata
read_metadata
read_sim_metadata
```
## Restrictions and Workarounds
The exact datastructs that can be stored and read from a HDF5 depends
in the HDF5.jl implementation. E.g. before v0.16.15 Tuples where not
supported.
The following functions are workarounds for two current restrictions.
```@docs
create_namedtuple_converter
create_enum_converter
```
## Example Model
The tutorials in the documentation does not include examples for the
file storage functionality, but this
[model](https://git.zib.de/sfuerst/vahana-episim/) is a good example,
which also demonstrates checkpointing (resuming a simulation after an
interruption), and working with initial snapshots (the initialized
simulation state is stored after the graph structure is constructed
and distributed to the different processes).
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 8893 | ```@meta
EditURL = "../examples/hegselmann.jl"
```
# Utilizing Graphs.jl
# Goal
This tutorial illustrates how to integrate graphs that support the
`AbstractGraph` interface from the Graphs.jl package into a Vahana
simulation and the visualization support for Vahana graphs.
For this purpose, we implement the opinion dynamics model of
[Hegselmann and Krause
(2002)](http://jasss.soc.surrey.ac.uk/5/3/2.html). An alternative
implementation of the same model using the Agents.jl package can be found
[here](https://juliadynamics.github.io/Agents.jl/v4.0/examples/hk/).
# Agent and Edge Types
````@example hegselmann
using Vahana, Statistics
````
We have a finite number $n$ of agents, where the state of
the agents are a real number $x_i(t)$ in the [0,1] interval which
represents the opinion of that agent.
````@example hegselmann
struct HKAgent
opinion::Float64
end
````
This time we have only one network that determine the agents that
will be considered when an agent updates its opinion.
````@example hegselmann
struct Knows end
````
Beside these two types there is a *confidence bound* $\epsilon > 0$,
opinions with a difference greater than $\epsilon$ are ignored by
the agents in the transition function. All agents have the same
confidence bound, so we introduce this bound as a parameter.
````@example hegselmann
const hkmodel = ModelTypes() |>
register_agenttype!(HKAgent) |>
register_edgetype!(Knows) |>
register_param!(:ϵ, 0.02) |> # the confidence bound
create_model("Hegselmann-Krause");
nothing #hide
````
# Adding a Graph
Vahana allows adding `SimpleGraphs` and `SimpleDiGraphs` from the
[Graphs.jl](https://juliagraphs.org/Graphs.jl/dev/) package via the
[`add_graph!`](@ref) function. So it is possible to use e.g.
[SNAPDatasets](https://github.com/JuliaGraphs/SNAPDatasets.jl) to
run the opinion model on real datasets, or the SimpleGraphs module
from Graphs.jl to create synthetic graphs.
We demonstrate here both use cases and are creating a separate
simulation for each one.
````@example hegselmann
const cgsim = create_simulation(hkmodel);
const snapsim = create_simulation(hkmodel)
````
## SimpleGraphs
First we will show how we can add a synthetic graph. For this we
need to import the SimpleGraphs module. Since there are many
functions in the Graphs.jl package with the same name as in Vahana
(e.g. add_edge!), it is advisable to import only the needed parts of
Graphs.jl instead of loading the whole package via `using Graphs`.
````@example hegselmann
import Graphs.SimpleGraphs
````
We want to add a complete graph, where each agent is connected with
all the other agents, like in the Agents.jl implementation. We can
create such a graph via `SimpleGraphs.complete_graph`.
````@example hegselmann
g = SimpleGraphs.complete_graph(50)
````
Vahana needs the information how to convert the nodes and edges of
the SimpleGraphs object to the Vahana structure. This is done by the
constructor functions in the third and forth arguments of
[`add_graph!`](@ref). We do not need the Graph.vertex and Graph.edge
arguments of this constructor functions, but for other use cases
e.g. for bipartite graphs, it would be possible to create agents of
different types depending on this information.
````@example hegselmann
const agentids = add_graph!(cgsim,
g,
_ -> HKAgent(rand()),
_ -> Knows());
nothing #hide
````
Each agent also adds its own opinion to the calculation. We can use
the ids returned by the [`add_graph!`](@ref) functions for this.
````@example hegselmann
foreach(id -> add_edge!(cgsim, id, id, Knows()), agentids)
finish_init!(cgsim)
````
## SNAPDataset.jl
The SNAPDataset.jl package delivers Graphs.jl formatted datasets from
the [Stanford Large Network Dataset
Collection](https://snap.stanford.edu/data/index.html).
````@example hegselmann
using SNAPDatasets
````
With this package we can use the `loadsnap` function to create the graph
that is then added to the Vahana graph, e.g. in our example the
facebook dataset.
````@example hegselmann
const snapids = add_graph!(snapsim,
loadsnap(:facebook_combined),
_ -> HKAgent(rand()),
_ -> Knows());
nothing #hide
````
Again each agent adds its own opinion to the calculation.
````@example hegselmann
foreach(id -> add_edge!(snapsim, id, id, Knows()), snapids)
finish_init!(snapsim)
````
# The Transition Function
Opinions are updated synchronously according to
```math
\begin{aligned}
x_i(t+1) &= \frac{1}{| \mathcal{N}_i(t) |} \sum_{j \in \mathcal{N}_i(t)} x_j(t)\\
\textrm{where } \quad \mathcal{N}_i(t) &= \{ j : \| x_j(t) - x_i(t) \| \leq \epsilon \}
\end{aligned}
```
So we first filter all agents from the neighbors with an opinion
outside of the confidence bound, and then calculate the mean of the
opinions of the remaining agents.
````@example hegselmann
function step(agent, id, sim)
ϵ = param(sim, :ϵ)
opinions = map(a -> a.opinion, neighborstates(sim, id, Knows, HKAgent))
accepted = filter(opinions) do opinion
abs(opinion - agent.opinion) < ϵ
end
HKAgent(mean(accepted))
end;
nothing #hide
````
We can now apply the transition function to the complete graph simulation
````@example hegselmann
apply!(cgsim, step, HKAgent, [ HKAgent, Knows ], HKAgent)
````
Or to our facebook dataset
````@example hegselmann
apply!(snapsim, step, HKAgent, [ HKAgent, Knows ], HKAgent)
````
# Creating Plots
Finally, we show the visualization possibilities for graphs, and import the
necessary packages for this and create a colormap for the nodes.
````@example hegselmann
import CairoMakie, GraphMakie, NetworkLayout, Colors, Graphs, Makie
````
Since the full graph is very cluttered and the Facebook dataset is
too large, we construct a Clique graph using Graphs.jl.
````@example hegselmann
const cysim = create_simulation(hkmodel) |> set_param!(:ϵ, 0.25);
const cyids = add_graph!(cysim,
SimpleGraphs.clique_graph(7, 8),
_ -> HKAgent(rand()),
_ -> Knows());
foreach(id -> add_edge!(cysim, id, id, Knows()), cyids)
finish_init!(cysim);
nothing #hide
````
Vahana implements an interactive plot function based on GraphMakie, where
agents and edges are given different colors per type by default, and
the state of each agent/edge is displayed via mouse hover
actions.
````@example hegselmann
vp = create_graphplot(cysim)
figure(vp)
````
To modify the created plot, the Makie figure, axis and plot, can be
accessed via the methods `figure`, `axis` and `plot`. This allows us to modify
the graph layout and to remove the decorations.
````@example hegselmann
Vahana.plot(vp).layout = NetworkLayout.Stress()
Makie.hidedecorations!(axis(vp))
figure(vp)
````
To visualize the agents' opinions, we can leverage Vahana's
integration with Makie's plotting capabilities. Instead of directly
modifying the `node_color` property of the Makie plot, we can define
custom visualization functions. These functions, which can have
methods for different agent and edge types, are used by [`create_graphplot`](@ref)
to determine various properties of nodes and edges in the plot.
This approach not only allows for more dynamic and type-specific
visualizations but also supports interactive plots when using GLMakie as
the backend. We'll define a function called `modify_vis` that specifies how
different elements should be displayed. This function will be passed to
[`create_graphplot`](@ref) via the `update_fn` keyword argument.
````@example hegselmann
colors = Colors.range(Colors.colorant"red", stop=Colors.colorant"green", length=100)
modify_vis(state::HKAgent, _ ,_) = Dict(:node_color => colors[state.opinion * 100 |> ceil |> Int],
:node_size => 15)
modify_vis(_::Knows, _, _, _) = Dict(:edge_color => :lightgrey,
:edge_width => 0.5);
function plot_opinion(sim)
vp = create_graphplot(cysim,
update_fn = modify_vis)
Vahana.plot(vp).layout = NetworkLayout.Stress()
Makie.hidedecorations!(axis(vp))
Makie.Colorbar(figure(vp)[:, 2]; colormap = colors)
figure(vp)
end;
nothing #hide
````
And now we can plot the initial state
````@example hegselmann
plot_opinion(cysim)
````
And then the state after 500 iterations
````@example hegselmann
for _ in 1:500
apply!(cysim, step, [ HKAgent ], [ HKAgent, Knows ], [ HKAgent ])
end
plot_opinion(cysim)
````
# Finish the Simulation
As always, it is important to call `finish_simulation` at the end of the
simulation to avoid memory leaks.
````@example hegselmann
finish_simulation!(cysim);
nothing #hide
````
---
*This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 3860 | ```@meta
CurrentModule = Vahana -->
```
# Introduction
Vahana.jl is an open-source high-performance software framework for
the development of large-scale agent-based models (ABM) of complex
social systems. Vahana is based on a discrete dynamical systems
formulation referred to as a synchronous graph dynamical system
(SyGDS)[^1], which is a generalization of cellular automata (CA). In a CA
the cells can be interpreted as the agents, and when a cell/agent
updates its state according to a rule, the new state depends only on
the current state of the cell and the states of the cells in its
neighborhood. In a SyGDS, the vertices of the graph are the agents of
the model, and the (directed) edges determine the neighborhood.
Vahana extends the SyGDSs concept so that even complex models like the
Mobility Transition Model (https://github.com/CoeGSS-Project/motmo) or
MATSim Episim (https://github.com/matsim-org/matsim-episim-libs) can
be expressed as a SyGDS. The vertices are representing the agents and
may be of different types and have a state that belongs to a
type-specific state space. Edges between the agents are directed, if
a transition of agent ``a`` depends on the state of agent ``b``, an
edge from ``b`` to ``a`` is needed. Edges may also have different
types (represent different kinds of interactions) and may have also a
state. There can be multiple transition functions (which are the
equivalent of a rule in a CA), and each transition function can act on
a different subgraph.
(Discrete) spatial information can be added using Vahana functions
that insert grid cells as nodes in the graph and have access to a
mapping from the Cartesian index of the underlaying space to the
corresponding node. Since the cells are vertices of the graph, they
can be treated in the same way as other agents
To model the system's dynamic evolution, we consider discrete time
steps. At each step ``t``, there is a set of vertices which can change
their own state and also add new vertices and edges. The new state of
a node at time ``t`` is computed based only on information from the
previous step. Information from step ``t-1`` usually includes the
previous state of the agent itself, and may include states of adjacent
agents in the graph, possibly also the states of the respective edges
themselves. The underlying idea is that of a functional programming
approach: the transition cannot be implicitly affected by any other
mutable state or unintended side effects.
So expressing a model as a SyGDS has the advantage that a single
simulation can be computed in parallel. Vahana therefore allows the
simulation to be distributed across multiple nodes of a computer
cluster, enabling the simulation of large-scale models that do not fit
on a single node.
Parallelization is done through the Message Passing Interface (via the
MPI.jl package), but this is hidden to the user. Any model developed
with Vahana can be automatically computed in parallel by simply
starting the simulation via mpirun. The challenge for the user is
mainly to think about how to express the model as a SyGDS, rather than
thinking about technical details of the implementation such as which
data structure is best to use.
In addition to this documentation, Fürst et al. (2024)[^2] provides a
comprehensive discussion of the SyGDS extension for Vahana.jl. It also
includes two case studies and performance analyses.
[^1]: Adiga, A., Kuhlman, C.J., Marathe, M.V. et al. Graphical dynamical systems and their applications to bio-social systems. [https://doi.org/10.1007/s12572-018-0237-6](https://doi.org/10.1007/s12572-018-0237-6)
[^2]: Fürst, S., Conrad, T., Jaeger, C., & Wolf, S. (2024). Vahana.jl - A framework (not only) for large-scale agent-based models. arXiv:2406.14441. [https://doi.org/10.48550/arXiv.2406.14441](https://doi.org/10.48550/arXiv.2406.14441)
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 1996 | ```@meta
CurrentModule = Vahana
```
# Initialization
After we created a simulation by calling [`create_simulation`](@ref), we
must build the initial state of the simulation. As in Vahana the state
of a model is represented as a graph, this means we must add the nodes
(our agents) and edges to the graph.
```@docs
add_agent!
add_agents!
```
!!! warning
The IDs created by `add_agent(s)!` contain Vahana internal information, that can change
after an [`apply!`](@ref) or the [`finish_init!`](@ref) call. It is even possible that
different agents have the same ID at different times. This has the implication, that
the IDs can only be used temporary and should not be stored in the state of an agent or edge.
```@docs
Edge
add_edge!
add_edges!
```
## Graphs
It is also possible to use [graph
generators](https://juliagraphs.org/Graphs.jl/stable/core_functions/simplegraphs_generators/)
from the Graphs.jl package to construct the initial state. Or parts of
it, since you can combine it with all the other functions described on
this page. Since Graphs.jl has overlapping function names with Vahana,
it is advisable to import only the SimpleGraphs module from Graphs.jl.
```@docs
add_graph!
```
There is also two function with works the other way and converts the
underlying graph of an simulation (or a subset of this graph) to a
structure that fulfills the AbstractGraph or AbstractSimpleGraph
interface from the Graphs.jl package.
```@docs
vahanagraph
vahanasimplegraph
```
## Raster
The process for adding raster data to a simulation is documented
[here](raster.md).
## Set Parameters
After creating a simulation, you can modify parameter values using
[`set_param!`](@ref) until the simulation is initialized with
[`finish_init!`](@ref).
```@docs
set_param!
```
## Finish initialization
After all the initial state has been built using the functions
described above, `finish_init!` must be called before the first call
of [`apply!`](@ref)
```@docs
finish_init!
```
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 291 | ```@meta
CurrentModule = Vahana
```
# Logging
Vahana utilize Julia's Standard Logging Library to optionally create
log files with e.g. the duration of the transition functions. For each
process a seperate file is created.
```@docs
set_log_path
create_logger!
with_logger
log_overview
```
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 1170 | ```@meta
CurrentModule = Vahana
```
# Misc
Here are the remaining exported Vahana definitions that do not fit into any of the previous categories:
## Agents
```@docs
ProcessID
AgentID
all_agents
all_agentids
num_agents
add_agent_per_process!
```
## Edges
```@docs
all_edges
num_edges(sim, t::Type{T}, sum_ranks = true; write = nothing) where T
```
## REPL
Vahana has some features that support model development via Julia's
interactive command line REPL. In this case, the simulation is not
parallelized, but the same code runs later via parallelization without
requiring any (or minimal) changes.
Beside the pretty-printing of a simulation as shown in the
tutorial(s), there are also additional functions that allows to
investigate the current state of a simulation:
```@docs
show_agent
DataFrames.DataFrame(sim::Simulation, T::DataType)
```
[`apply`](@ref) can be used to calculate a transition function
without modifying the original state. This can be useful in the
development process, but for the final simulation the function should
be replaced with the modifying version `apply!`.
## Simulation
```@docs
copy_simulation
finish_simulation!
```
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 6713 | # Parallel simulations
Vahana supports parallel simulations using MPI (Message Passing
Interface), allowing for significant performance improvements when
running large-scale models. To run a Vahana simulation in parallel,
you can use the mpirun or mpiexec command, specifying the number of
processes with the -np parameter. For example:
```mpirun -np 4 julia your_model.jl```
The `-np` parameter indicates the number of processes/threads to be
used for the simulation.
This approach works without any additional changes in the model
code. However, there are ways to further optimize performance in a
parallel simulation:
## MPI.jl Integration
Vahana utilizes the MPI.jl package for its parallel computing
capabilities. While no specific MPI knowledge is required to use
Vahana's parallel features, users may find it beneficial to review the
[Configuration
section](https://juliaparallel.org/MPI.jl/stable/configuration/) of
the [MPI.jl documentation](https://juliaparallel.org/MPI.jl/stable/)
for a deeper understanding of the underlying parallel computing
framework. For advanced users or specific scenarios, it's possible to
work directly with MPI.jl functions within your Vahana model. When
using Vahana in parallel mode, MPI is automatically initialized, and
the following MPI-related variables are available:
- `mpi.comm`: The MPI communicator object.
- `mpi.rank`: An integer identifying the current process (0-based).
- `mpi.size`: The total number of processes in the parallel computation.
Remember that while direct use of MPI functions can provide additional
flexibility, it also requires careful handling to maintain consistency
across all processes and avoid potential race conditions or deadlocks.
## Partitioning
The simulation graph is partitioned and distributed in the
[`finish_init!`](@ref) call. By default, the
[Metis.jl](https://github.com/JuliaSparse/Metis.jl) package is used
for this. However, during this process, the information about the
different agent types is lost. As a result, if multiple agent types
are used, it is possible that the number of agents is unevenly
distributed for a single agent type.
To address this issue, an alternative partitioning scheme,
`:EqualAgentNumbers`, is available. However, this scheme ignores the
edges and number of cuts in the graph.
In order to optimize the partitioning for your specific model, it can
be very useful to perform your own partitioning and pass it to
[`finish_init!`](@ref). An example of this can be seen in the
`create_partition` function of the [Vahana Episim
Example](https://git.zib.de/sfuerst/vahana-episim/-/blob/main/src/init.jl).
## Using @rootonly
It's helpful to understand that in MPI programs, all processes execute
the same program code, but operate on different data. In a typical
Vahana program, up to the [`finish_init!`](@ref) call, all processes
runs the same code that creates the initial graph and therefore, if
there are `n` processes, the complete graph is generated `n`
times. However, at the [`finish_init!`](@ref) step, only the graph
from process 0 (the root process) is considered, and the graphs
constructed on all other processes are discarded.
Although this is not necessarily problematic, it can be beneficial to
construct the graph only on the root processes, especially if files
are being read during the initialization phase.
To execute instructions only on the root process, you can use the
`@rootonly` macro. For example, the [Vahana Episim
example](https://git.zib.de/sfuerst/vahana-episim) includes the
following code before the [`finish_init!`](@ref) call:
```
@rootonly begin
worldid = add_agent!(sim, World())
healthauthid = add_agent!(sim, HealthAuthority(0, 0, 0))
@info "read persons"
persons = read_persons!(config.synpop_file)
@info "read events"
read_events!(sim, config.events_all, persons, worldid, healthauthid)
@info "finish init"
end
```
Alternatively you could also check the `mpi.isroot` predicate.
It is important that [`finish_init!`](@ref) is called by all
processes and not only by the root process, and also some other
functions like e.g. [`write_snapshot`](@ref) must be called
collectively from all processes.
## Write a snapshot after `finish_init!`
If creating the initial state takes time and the process is
deterministic, it is a good idea to save the state after
[`finish_init!`](@ref) with [`write_snapshot`](@ref) and read this snapshot with
[`read_snapshot!`](@ref) instead of recreating the graph
each time.
If the process of generating the initial state is time-consuming, it
is advisable to save the state after the `finish_init!` function
completes. This can be achieved by calling the `write_snapshot`
function. Subsequently, instead of recreating the initial graph for
each simulation, you can read this snapshot using the `read_snapshot!`
function instead.
The [Vahana Episim
example](https://git.zib.de/sfuerst/vahana-episim/episim.jl) serves as
a demonstration of how to implement this approach effectively.
## The :IgnoreSourceState hint
This hint requires additional explanation about what happens
internally when [`apply!`](@ref) is called.
In a parallel simulation, at the beginning of [`apply!`](@ref), it is
checked whether the transition function needs to read the state of an
agent type that may have changed since the last state read. If this is
the case, it checks all accessible edges (specified in the `read`
argument of `apply!`) and transmits the state of agents that can be
accessed (i.e., the agent type must also be included in the `read`
argument) to the corresponding process. However, there are cases where
it is clear that only the IDs of the agents will be accessed via a
specific edge type, and not the agent state itself. To avoid the
overhead of transmitting state between agents that will never be read,
the `:IgnoreSourceState` hint can be used for those edge types.
This hint only affects parallel simulations, as there is nothing to
transmit in a serial simulation.
## Avoid agentstate calls
Instead of using [`agentstate`](@ref) to access the state of an agent,
sometimes it is possible for an agent to actively send the required
state associated with an edge to another agent that needs that
information. This can significantly improve performance, especially
when combined with the `:IgnoreSourceState` hint if necessary.
For example, in a Game of Life implementation, active cells can
generate an edge to their neighbors if the cell is active. If this
edge has the `:NumEdgesOnly` hint, it will directly trigger the
counting process of the neighbors without the need to transfer the
full state to other agents/processes.
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 8118 | # Performance Tuning
This section provides some explanations on how to fine-tune the
simulation performance.
These tips are specific to Vahana. Of course, all the generic
performance tips, such as writing `type-stable` functions, still
apply.
## Optional Assertions
Vahana includes some checks on the usage of the Vahana API that can
impact runtime performance. For example, in [`agentstate`](@ref),
there are checks to ensure that the specified agenttype matches the
agent's ID. These assertions that could degrade performance can be
disabled by calling `disable_asserts(false)`.
The recommended approach is to enable assertions during the model
development phase but disable them when the model "goes into
production", such as before starting a parameter space exploration.
## Type Hints
It is possible to provide Vahana with hints about the types of agents
or edges to improve the runtime performance and/or reduce memory
requirements. You can use either hint independently or combine them as
needed for your specific types.
Aside from the `:SingleEdge` hint, there is generally no requirement
to modify the model code when a type hint is introduced to a type. The
interface to Vahana remains consistent, with the restriction that
certain functions may be unavailable. For instance, if the
`:IgnoreFrom` hint is specified for an edge type, there is no
[`edgestates`](@ref) method available for this type, as Vahana has not
retained the identifiers of neighboring entities and, consequently,
cannot retrieve their corresponding states.
When implementing a model, it is a sensible approach to keep the
assertions active and disregard hints. Upon completing the
implementation, the next step should be to activated hints and
evaluate their impact on performance. Subsequently, after selecting
the best hint combination that does not trigger assertions, these can
be deactivated as well.
### Agent Hints
Vahana supports two hints for agent types: `:Immortal` and `:Independent`.
When an agent type is marked as `:Immortal`, it indicates that agents of
this type will never be removed from the simulation. By default,
Vahana assumes that agents can be removed (by returning
nothing in a transition function). The `:Immortal` hint allows Vahana to
skip certain checks and operations related to agent removal,
potentially improving performance.
The :Independent hint indicates that agents of this type do not access
the state of other agents of the same type during transition
functions. This information allows Vahana to optimize memory usage and
reduce unnecessary data copying.
### Edge Hints
Almost all hints can be combined in any way you prefer. For example,
the combination of `:IgnoreFrom` and `:Stateless` may seem useless at
first because no concrete edge information will be stored when
[`add_edge!`](@ref) is called. However, Vahana still keeps track of
the number of edges that have the agent as the target node. This
information alone, or combined with the `:SingleEdge` hint, can often
be sufficient. You can refer to the `Die` or `Eat` edges in the
[Predator example](predator.md) for an illustration.
The only combination that is not allowed is `:SingleType` +
`:SingleEdge`, unless you also set `:Stateless` and `:IgnoreFrom`.
Vahana supports five hints for edge types, which can be specified as
optional arguments in the [`register_edgetype!`](@ref) function:
- `:IgnoreFrom`: Excludes storage of the source node's ID.
- `:Stateless`: Stores only the source node's ID, omitting any
additional state information.
- `:SingleType`: Indicates that all target nodes are of the same type,
while source nodes can vary. This hint requires setting the target
keyword (explained below).
- `:SingleEdge`: Specifies that each agent can be the target of at
most one edge of this type. In the case that also the `:IgnoreFrom`
and `:Stateless` hint are also set, multiple edges to an agent of
this type can be created, but the only information available later
is that at least one edge exists, as only the
[has_edge](#Defined-Functions) is defined.
- `:IgnoreSourceState`: Indicates that the source agent's ID is not
used to access its state. This hint is particularly relevant for
parallel simulations and is explained
[here](./performance.md#:IgnoreSourceState).
These hints can be combined flexibly to suit your model's needs. For
instance, combining `:IgnoreFrom` and `:Stateless` might seem
redundant as it stores no explicit edge information when add_edge! is
called. However, Vahana still maintains a count of edges targeting
each agent per type. E.g. the Die and Eat edges in the [Adding Spatial
Information tutorial](performance.md) only needs the information that
such an edge exists for an agent. Therefore for both types the
`:IgnoreFrom`, `:Stateless` and `:SingleEdge` (or the
[`:HasEdgeOnly`](#Special-Hint-Combinations)) hints could be set.
Most hint combinations are permissible, with one exception:
:SingleType and :SingleEdge cannot be used together unless :Stateless
and :IgnoreFrom are also specified.
#### :SingleType `target` keyword argument
When the `:SingleType` hint is set, it is necessary to add the
`target` keyword argument to the [`register_edgetype!`](@ref)
function. The value of this argument should be the type of the target
agents.
#### Defined Functions
The following functions can be used to access the graph within
[`apply!`](@ref), but their availability depends on the edge type
hints:
| function | not available for edge type with the hint (combination) |
|:------------------------------------------|:--------------------------------------------------------|
| [`edges`](@ref) | `:IgnoreFrom` or `:Stateless` |
| [`neighborids`](@ref) | `:IgnoreFrom` |
| [`neighborstates`](@ref) | `:IgnoreFrom` |
| [`edgestates`](@ref), [`mapreduce`](@ref) | `:Stateless` |
| [`num_edges`](@ref) | `:SingleEdge` |
| [`has_edge`](@ref) | always available |
As mentioned earlier, the Vahana API differs slightly when the
`:SingleEdge` hint is set. This specifically affects the functions
listed here, with the exception of `num_edges`, `has_edges`, and
`mapreduce`. Normally, these functions return a vector containing
edges, IDs, or states (or `nothing`). However, when used in
combination with the `:SingleEdge` hint, they return only a single edge,
ID, or state (or `nothing`), as the hint implies that there can be at most
one edge of that type.
#### Special Hint Combinations
Additionally, there are two property combinations that can be set in
[`register_edgetype!`](@ref) using a single symbol, which directly
expresses the intended combination:
- `:NumEdgesOnly`: This corresponds to the combination of
`:IgnoreFrom` and `:Stateless`. In this case, only the number of
edges is counted, so only calls to [`num_edges`](@ref) and
[`has_edge`](@ref) are possible.
- `:HasEdgeOnly`: This corresponds to the combination of
`:IgnoreFrom`, `:Stateless`, and `:SingleEdge`. In this case, only
calls to [`has_edge`](@ref) are possible.
## Iterator Versions of Edge Functions
Vahana offers iterator versions of several functions used to access
edge and neighbor information, including [`neighborids_iter`](@ref),
[`edgestates_iter`](@ref), [`neighborstates_iter`](@ref), and
[`neighborstates_flexible_iter`](@ref).
The iterator functions work similarly to their non-iterator
counterparts but return an iterator instead of a vector. This approach
can be more memory-efficient as it doesn't create a full vector in
memory. Instead, values are computed on-demand, which can be faster if
you don't need to process all elements. They work well with Julia's
built-in functions like map, filter, and reduce, allowing for
efficient chaining of operations.
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 214 | ```@meta
CurrentModule = Vahana
```
# Plots
Visualization is not the main focus of Vahana, but two rudimentary auxiliary functions exist for creating plots with Makie.
```@docs
plot_globals
create_graphplot
```
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 19963 | ```@meta
EditURL = "../examples/predator.jl"
```
# Adding Spatial Information
# Goal
This example demonstrates how spatial information can be integrated
into an agent-based model using Vahana. While Vahana's primary focus
is on graph-based simulations, it support the inclusion of spatial
information into models. It allows you to define a spatial grid,
associate agents with specific locations, and implement interactions
based on spatial proximity, even though the underlying implementation
still operates on graph structures.
It's worth noting that in its current version, Vahana may not be the
optimal choice for models that primarily depend on frequent movement
of agents across space. However, as this example will show, it is
entirely possible to implement those models.
It allows you to define a spatial grid, associate agents with specific
locations, and implement interactions based on spatial proximity, all
while leveraging Vahana's efficient graph-based computations.
For the understanding of how Vahana handles spatial information and
rasters, you may find it helpful to watch also the [corresponding
section of the Vahana.jl Juliacon
video](https://youtu.be/-318ec-kCBM?si=YNnWLrb-_7RPSEPB&t=1198). The
video provides a visual explanation of how rasters are implemented
within Vahana's graph-based framework and demonstrates some key
concepts that we'll be applying in this tutorial.
In this tutorial, we'll implement a predator-prey model with spatial
components, showcasing how Vahana's raster functionality can be used
to create a spatially-explicit ecological simulation.
The model is based on the [Predator-Prey for High-Performance
Computing](https://peerj.com/articles/cs-36/) (PPHPC) model. In
PPHPC the agents move randomly, in our implementation the prey move
to locations with grass (if one is in sight) and the predators move to
locations with prey to demonstrate how features like this can be
implemented in Vahana.
# Agent and Edge Types
````@example predator
using CairoMakie, Vahana, Random
Random.seed!(1); #hide
detect_stateless(true) #hide
````
In our spatial predator-prey model, we define separate structures for
predators and prey, even though they share the same fields:
````@example predator
struct Predator
energy::Int64
pos::CartesianIndex{2}
end
struct Prey
energy::Int64
pos::CartesianIndex{2}
end
````
Despite their identical structure, we define them as separate types
because Vahana uses these types as tags for differentiating between
agent categories.
In the following sections, we'll use "Species" as an umbrella term to
refer to both Predator and Prey. Functions that are applicable to both
types will take the type as a parameter, which we'll denote as Species
in the function arguments.
Aside from the predator and prey agents, the spatial environment is
represented by grid cells, which are also implemented as agents and
consequently function as nodes within the graph structure.
````@example predator
struct Cell
pos::CartesianIndex{2}
countdown::Int64
end
````
All agents maintain their position as part of their internal
state. However, a cell can only perceive the animals if they are
directly connected to the cell through an edge. Vahana facilitates the
establishment of such edges via the [`move_to!`](@ref) function.
Edges represent connections from prey or predators to cells. We define
Position as a parametric type, enabling cells to distinguish between
prey and predators based on the type of the edges.
````@example predator
struct Position{T} end
````
Views are also edges from the cells to the prey and predators
respectively. These edges represent the cells that are visible to a
prey or predator so that, for example, it is possible to check which
cell in the visible area contains food.
````@example predator
struct View{T} end
````
VisiblePrey edges represent connections from prey to
predator. Currently, all edge types link animals to cells, and without
an incoming edge from prey, a predator lacks awareness of prey
positions. The VisiblePrey edges are generated by cells through the
`find_prey` transition function, as cells possess knowledge of which Prey
entities are directly located on the cell via the Position{Prey} edges,
and consequently within the view of a predator via the View{Predator}
edges.
````@example predator
struct VisiblePrey end
````
The last two edge types are messages to inform the agents that they
must die or find something to eat.
````@example predator
struct Die end
struct Eat end
````
# Params and Globals
We follow the parameter structure from the PPHPC model, but use
(besides the initial population) the same parameters for Prey and Predator
for the example run.
````@example predator
Base.@kwdef mutable struct SpeciesParams
init_population::Int64 = 500
gain_from_food::Int64 = 5
loss_per_turn::Int64 = 1
repro_thres::Int64 = 5
repro_prob::Int64 = 20
end
Base.@kwdef struct AllParams
raster_size::Tuple{Int64, Int64} = (100, 100)
restart::Int64 = 5
predator::SpeciesParams = SpeciesParams()
prey::SpeciesParams = SpeciesParams()
end;
params = AllParams()
params.prey.init_population = 2000;
nothing #hide
````
We are creating timeseries (in the form of `Vector`s) for the predator
and prey population, the number of cells with food, and the average
energy of the predators and prey.
````@example predator
Base.@kwdef mutable struct PPGlobals
predator_pop = Vector{Int64}()
prey_pop = Vector{Int64}()
cells_with_food = Vector{Int64}()
mean_predator_energy = Vector{Float64}()
mean_prey_energy = Vector{Float64}()
end;
nothing #hide
````
## Create the Simulation
We have now defined all the Julia structs needed to create the model
and a simulation.
````@example predator
const ppsim = ModelTypes() |>
register_agenttype!(Predator) |>
register_agenttype!(Prey) |>
register_agenttype!(Cell) |>
register_edgetype!(Position{Predator}) |>
register_edgetype!(Position{Prey}) |>
register_edgetype!(View{Predator}) |>
register_edgetype!(View{Prey}) |>
register_edgetype!(VisiblePrey) |>
register_edgetype!(Die) |>
register_edgetype!(Eat) |>
create_model("Predator Prey") |>
create_simulation(params, PPGlobals())
````
## Initialization
First we add the Cells to the Simulation. Therefore we define a
constructor function for the cells. There is a 50% probability that a cell
contains food (and in this case `countdown` is 0).
````@example predator
init_cell(pos::CartesianIndex) =
Cell(pos, rand() < 0.5 ? 0 : rand(1:param(ppsim, :restart)))
add_raster!(ppsim, :raster, param(ppsim, :raster_size), init_cell);
nothing #hide
````
We define a auxiliary functions to facilitate the relocation of an
agent to a new position. These functions will add a single `Position`
edge from the animal to the cell at the `newpos` position, and for all
cells within a Manhattan distance of 1, `View` edges will be
established from those cells to and from the animal, as well as to the
cell itself.
````@example predator
function move!(sim, id, newpos, Species)
move_to!(sim, :raster, id, newpos, nothing, Position{Species}())
move_to!(sim, :raster, id, newpos, View{Species}(), View{Species}();
distance = 1, metric = :manhatten)
end;
nothing #hide
````
The add_animals function is a generic initializer for both predators and
prey, taking species-specific parameters and the species type as
arguments. It creates a specified number of agents, each with a
random position on the raster and a random initial energy within a
defined range, then adds them to the simulation and places them on
the raster using the move! function.
````@example predator
function add_animals(params, Species)
energyrange = 1:(2*params.gain_from_food)
foreach(1:params.init_population) do _
pos = random_pos(ppsim, :raster)
id = add_agent!(ppsim, Species(rand(energyrange), pos))
move!(ppsim, id, pos, Species)
end
end
add_animals(param(ppsim, :prey), Prey)
add_animals(param(ppsim, :predator), Predator)
````
At the end of the initialization phase we have to call finish_init!
````@example predator
finish_init!(ppsim)
````
## Transition Functions
As mentioned in the comment for the View type, the cells are
responsible for connecting the Prey with the Predators. So each cell
iterate over each prey on the cell and add edges to all predators
that can view the cell.
The underscore (_) as the first argument in the find_prey function signifies
that we don't need to access the state of the cell itself. This is
because the function only needs to check for the presence of edges and create
new connections based on those edges, without using any information from
the cell's internal state. As a result, when we call apply! for
find_prey, we don't include Cell in the read argument. Consequently,
Vahana passes Val(Cell) as the first argument to find_prey for multiple
dispatch purposes, rather than the actual cell state. This approach
optimizes performance by avoiding unnecessary data access and allows
the function to operate solely on the graph structure of the simulation.
````@example predator
function find_prey(_::Val{Cell}, id, sim)
if has_edge(sim, id, Position{Prey}) && has_edge(sim, id, View{Predator})
for preyid in neighborids(sim, id, Position{Prey})
for predid in neighborids(sim, id, View{Predator})
add_edge!(sim, preyid, predid, VisiblePrey())
end
end
end
end;
nothing #hide
````
If a predator has enough energy left to move and there is a prey in the
predator's field of view, a random prey is selected and its position
is used as the new position. If no prey is visible, a random cell in
the predator's field of view is selected as the new position.
If there is not enough energy left, the transition function returns `nothing`,
which means that the predator dies and is no longer part of the graph.
````@example predator
function move(state::Predator, id, sim)
e = state.energy - param(sim, :predator).loss_per_turn
if e > 0
# we need to access the pos of the prey which is part of it's state
prey = neighborstates(sim, id, VisiblePrey, Prey)
newpos = if isnothing(prey)
nextcellid = rand(neighborids(sim, id, View{Predator}))
agentstate(sim, nextcellid, Cell).pos
else
rand(prey).pos
end
move!(sim, id, newpos, Predator)
Predator(e, newpos)
else
nothing
end
end;
nothing #hide
````
The movement logic for prey differs from that of predators in terms of
their target. While predators seek cells containing prey, prey agents
search for cells with available grass. In our implementation of the
PPHPC (Predator-Prey for High-Performance Computing) model, grass
availability is indicated by the countdown field of a
cell. Specifically, grass is considered available for consumption when a
cell's countdown value equals 0.
````@example predator
function move(state::Prey, id, sim)
e = state.energy - param(sim, :prey).loss_per_turn
if e > 0
withgrass = filter(neighborids(sim, id, View{Prey})) do id
agentstate(sim, id, Cell).countdown == 0
end
nextcellid = if length(withgrass) == 0
rand(neighborids(sim, id, View{Prey}))
else
rand(withgrass)
end
newpos = agentstate(sim, nextcellid, Cell).pos
move!(sim, id, newpos, Prey)
Prey(e, newpos)
else
nothing
end
end;
nothing #hide
````
If a cell has no grass and the countdown field is therefore > 0, the
countdown is decreased by 1.
````@example predator
function grow_food(state::Cell, _, _)
Cell(state.pos, max(state.countdown - 1, 0))
end;
nothing #hide
````
The try_eat transition function simulates the predator-prey interactions and
feeding processes within each cell. When both predators and prey
occupy the same cell, the function generates random predator-prey pairings,
ensuring each prey is targeted at most once and each predator consumes
no more than one prey. These interactions are represented by creating
Die edges from the cell to the consumed prey and Eat edges from the
cell to the successful predators. If any prey survive this process and
the cell contains available grass (indicated by a countdown of 0), an
Eat edge is established between the cell and a randomly selected
surviving prey, simulating grazing behavior.
````@example predator
function try_eat(state::Cell, id, sim)
predators = neighborids(sim, id, Position{Predator})
prey = neighborids(sim, id, Position{Prey})
# first the predators eat the prey, in case that both are on the cell
if ! isnothing(predators) && ! isnothing(prey)
prey = Set(prey)
for pred in shuffle(predators)
if length(prey) > 0
p = rand(prey)
add_edge!(sim, id, p, Die())
add_edge!(sim, id, pred, Eat())
delete!(prey, p)
end
end
end
# then check if there is prey left that can eat the grass
if ! isnothing(prey) && length(prey) > 0 && state.countdown == 0
add_edge!(sim, id, rand(prey), Eat())
Cell(state.pos, param(sim, :restart))
else
state
end
end;
nothing #hide
````
The reproduction mechanism for both predators and prey follows a similar
pattern, allowing us to define a generic function applicable to both
species. This function first determines if the animal found something to eat
by checking for the presence of an Eat edge targeting the animal, a
result of previous transition functions. If such an edge exists, the
animal's energy increases.
The function then evaluates if the animal's energy
exceeds a specified threshold parameter. When this condition is met,
reproduction occurs: a new offspring is introduced to the simulation
via the add_agent call, inheriting half of its parent's energy, and is
positioned at the same location as its parent using the move! function.
````@example predator
function try_reproduce_imp(state, id, sim, species_params, Species)
if has_edge(sim, id, Eat)
state = Species(state.energy + species_params.gain_from_food, state.pos)
end
if state.energy > species_params.repro_thres &&
rand() * 100 < species_params.repro_prob
energy_offspring = Int64(round(state.energy / 2))
newid = add_agent!(sim, Species(energy_offspring, state.pos))
move!(sim, newid, state.pos, Species)
Species(state.energy - energy_offspring, state.pos)
else
state
end
end;
nothing #hide
````
For the Predator we can just call the reproduce function with the necessary
arguments.
````@example predator
try_reproduce(state::Predator, id, sim) =
try_reproduce_imp(state, id, sim, param(sim, :predator), Predator)
````
The prey animal needs an extra step because it might have been eaten
by a predator. So, we check if there is a `Die` edge leading to the
prey animal, and if so, the prey animal is removed from the
simulation (by returning nothing). Otherwise, we again just call the
reproduce function defined above.
````@example predator
function try_reproduce(state::Prey, id, sim)
if has_edge(sim, id, Die)
return nothing
end
try_reproduce_imp(state, id, sim, param(sim, :prey), Prey)
end;
nothing #hide
````
We update the global values and use the `mapreduce` method to count
the population and the number of cells with food. Based on the
values, we can then also calculate the mean energy values.
````@example predator
function update_globals(sim)
push_global!(sim, :predator_pop, mapreduce(sim, _ -> 1, +, Predator; init = 0))
push_global!(sim, :prey_pop, mapreduce(sim, _ -> 1, +, Prey; init = 0))
push_global!(sim, :cells_with_food,
mapreduce(sim, c -> c.countdown == 0, +, Cell))
push_global!(sim, :mean_predator_energy,
mapreduce(sim, p -> p.energy, +, Predator; init = 0) /
last(get_global(sim, :predator_pop)))
push_global!(sim, :mean_prey_energy,
mapreduce(sim, p -> p.energy, +, Prey; init = 0) /
last(get_global(sim, :prey_pop)))
end;
nothing #hide
````
We add to our time series also the values after the initialization.
````@example predator
update_globals(ppsim);
nothing #hide
````
And finally we define in which order our transitions functions are called.
Worth mentioning here are the keyword arguments in `find_prey` and
`try_reproduce`.
The add_existing keyword in the try_reproduce transition function signify that
the currently existing position and view edges should not be
removed, and only additional edges should be added, in our case the
position of the potential offspring.
````@example predator
function step!(sim)
apply!(sim, move,
[ Prey ],
[ Prey, View{Prey}, Cell ],
[ Prey, View{Prey}, Position{Prey} ])
apply!(sim, find_prey,
[ Cell ],
[ Position{Prey}, View{Predator} ],
[ VisiblePrey ])
apply!(sim, move,
[ Predator ],
[ Predator, View{Predator}, Cell, Prey, VisiblePrey ],
[ Predator, View{Predator}, Position{Predator} ])
apply!(sim, grow_food, Cell, Cell, Cell)
apply!(sim, try_eat,
[ Cell ],
[ Cell, Position{Predator}, Position{Prey} ],
[ Cell, Die, Eat ])
apply!(sim, try_reproduce,
[ Predator, Prey ],
[ Predator, Prey, Die, Eat ],
[ Predator, Prey, Position{Predator}, Position{Prey},
View{Predator}, View{Prey} ];
add_existing = [ Position{Predator}, Position{Prey},
View{Predator}, View{Prey} ])
update_globals(sim)
end;
nothing #hide
````
Now we can run the simulation
````@example predator
for _ in 1:400 step!(ppsim) end
````
## Plots
To visualize the results we use the Makie package.
### Time series
First, we will generate a line chart for the time series data stored in
the global state. Vahana provides the `plot_globals` function for this
purpose. This function not only returns the Makie Figure itself but also the
Axis and Plots, allowing for further processing of the result. If you
wish to display the default result, you can utilize the Julia `first`
function to extract the figure from the returned tuple.
````@example predator
plot_globals(ppsim, [ :predator_pop, :prey_pop, :cells_with_food ]) |> first
````
### Spatial distribution
To visualize the spatial information we can use `heatmap` in
combination with the Vahana's `calc_raster` function. E.g. the
number of Position{Prey} edges connected to a cell give us the
number of Prey individuals currently on that cell.
It would be nice to have a colorbar for the heatmaps so we define a small
helper function that can be used in a pipe.
````@example predator
function add_colorbar(hm)
Makie.Colorbar(hm.figure[:,2], hm.plot)
hm
end;
nothing #hide
````
#### Predators Positions
````@example predator
calc_raster(ppsim, :raster, Int64, [ Position{Predator} ]) do id
num_edges(ppsim, id, Position{Predator})
end |> heatmap |> add_colorbar
````
#### Prey Positions
````@example predator
calc_raster(ppsim, :raster, Int64, [ Position{Prey} ]) do id
num_edges(ppsim, id, Position{Prey})
end |> heatmap |> add_colorbar
````
#### Cells that contains food
````@example predator
calc_raster(ppsim, :raster, Int64, [ Cell ]) do id
agentstate(ppsim, id, Cell).countdown == 0
end |> heatmap |> add_colorbar
````
# Finish the Simulation
As always, it is important to call `finish_simulation` at the end of the
simulation to avoid memory leaks.
````@example predator
finish_simulation!(ppsim);
nothing #hide
````
---
*This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 1110 | ```@meta
CurrentModule = Vahana
```
# Raster
Spatial information can be added to the simulation in the form of one
or more n-dimensional rasters.
```@docs
add_raster!
```
Those rasters are implemented as part of the graph structure, with
each cell represented as a node, so the cell types must be registered
like the types of agents via `register_agenttype!`.
To create edges between the cells, or between the cells and agents of
other types via the following two helper functions.
```@docs
connect_raster_neighbors!
move_to!
```
The id of a cell for a given position can be archived via `cellid`
```@docs
cellid
```
cellid id or position of a random cell can be drawn via:
```@docs
random_pos
random_cell
```
Such a raster is only a collection of nodes in the graph incl. an
Vahana internal mapping from the cartesian coordinates to the cell
IDs. Beside this mapping, cells are also just agents, but there are
some Vahana functions that utilize the internal cartesian coordinates
to create a n-dimensional representation of the state space.
```@docs
calc_raster
calc_rasterstate
rastervalues
```
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 1.2.0 | 7c9f6cde952f95ae2936cb3c8abe1989b59f2f6b | docs | 2088 | ```@meta
CurrentModule = Vahana
```
# Transition Function
After the initialization, the state of the simulation is modified by
so called transition functions. See [Defining Transition
Functions](tutorial1.md#Defining-Transition-Functions) for details.
```@docs
apply!
apply
```
!!! tip
The agent types must be immutable, but in many cases the agent
returned by a transition function will have a different state than the
agent specified as a parameter. If only one field is changed, we still
need to copy all other fields. The Setfield.jl package can be very
useful in this case.
Inside a transition function the following functions can be used to
access the state of the simulation:
## Globals and Parameters
```@docs
param
get_global
```
## Get Agent(state)
```@docs
agentstate
agentstate_flexible
```
To retrieve the states of all agents connected to a target agent
through edges of a specific type, the `neighborstates_iter` functions
can be beneficial. These functions combine the capabilities of
[`neighborids`](@ref) and [`agentstate`](@ref), allowing you to
easy access the desired information.
```@docs
neighborstates
neighborstates_flexible
neighborstates_iter
neighborstates_flexible_iter
```
## Get Edge(state)
```@docs
edges
edgestates
edgestates_iter
neighborids
neighborids_iter
num_edges(::Simulation, id::AgentID, edgetype::Type)
has_edge
```
For all the function like [`edges`](@ref) that returns `nothing` in
the case that there is no edge with the agent as target, it can be
useful to increase the readability of the code by using the `checked`
function to test for `nothing`.
```@docs
checked
```
## Add Agents/Edges
The following functions from the [Initialization] section
(initialization.md) that add new agents or edges to a simulation can
also be used inside a transition function, namely:
* [`add_agent!`](@ref) and [`add_agents!`](@ref)
* [`add_edge!`](@ref) and [`add_edges!`](@ref)
* [`connect_raster_neighbors!`](@ref)
* [`move_to!`](@ref)
## Remove Edges
Since v1.2 it's also possible to remove edges:
```@docs
remove_edges!
```
| Vahana | https://github.com/s-fuerst/Vahana.jl.git |
|
[
"MIT"
] | 0.4.0 | 72f9df4854d3ee73097ce9f89871557848692541 | code | 96 | using Coverage
cd(joinpath(@__DIR__, "..")) do
Codecov.submit(Codecov.process_folder())
end | ReadDatastores | https://github.com/BioJulia/ReadDatastores.jl.git |
|
[
"MIT"
] | 0.4.0 | 72f9df4854d3ee73097ce9f89871557848692541 | code | 608 | using Documenter, ReadDatastores
makedocs(
format = Documenter.HTML(),
sitename = "ReadDatastores.jl",
pages = [
"Home" => "index.md",
"Datastore types" => "read-datastores.md",
"Building & loading datastores" => "build-datastores.md",
"Indexing & Iteration" => "indexing.md",
"Additional Methods" => "additional-methods.md"
],
authors = "Ben J. Ward, The BioJulia Organisation and other contributors."
)
deploydocs(
repo = "github.com/BioJulia/ReadDatastores.jl.git",
deps = nothing,
make = nothing,
push_preview = true
) | ReadDatastores | https://github.com/BioJulia/ReadDatastores.jl.git |
|
[
"MIT"
] | 0.4.0 | 72f9df4854d3ee73097ce9f89871557848692541 | code | 10812 | module ReadDatastores
export
ReadDatastore,
PairedReads,
PairedReadOrientation,
FwRv,
RvFw,
LongReads,
LinkedReads,
UCDavis10x,
DatastoreBuffer,
name,
max_read_length,
orientation,
load_sequence!,
buffer,
read_tag,
stream,
@openreads,
@reads_str
using BioSequences, FASTX
const ReadDatastoreMAGIC = 0x05D5
@enum Filetype::UInt16 begin
PairedDS = 1
LongDS = 2
LinkedDS = 3
end
###
### Writing helpers
###
@inline function writestring(fd::IO, s::AbstractString)
write(fd, s) + write(fd, '\0')
end
@inline function write_flat_vector(fd::IO, v::Vector{T}) where {T}
n = UInt64(length(v))
return write(fd, n) + write(fd, v)
end
@inline function read_flat_vector!(fd::IO, v::Vector{T}) where {T}
n = read(fd, UInt64)
v = resize!(n)
unsafe_read(fd, pointer(v), n * sizeof(T))
return v
end
@inline function read_flat_vector(fd::IO, ::Type{T}) where {T}
n = read(fd, UInt64)
v = Vector{T}(undef, n)
unsafe_read(fd, pointer(v), n * sizeof(T))
return v
end
###
### Abstract ReadDatastore type
###
abstract type ReadDatastore{S<:LongSequence} end
###
### ReadDatastore custom exceptions
###
struct MissingMagicError <: Exception
filename::String
end
function Base.showerror(io::IO, e::MissingMagicError)
print(io, "MissingMagicError: the file ")
print(io, e.filename)
print(io, " does not appear to be a valid read datastore file")
print(io, ", it does not begin with the expected magic bytes.")
end
struct DatastoreTypeError{D<:ReadDatastore} <: Exception
filename::String
dstype::Filetype
end
function Base.showerror(io::IO, e::DatastoreTypeError{D}) where {D}
print(io, "DatastoreTypeError: ")
print(io, e.filename)
print(io, " contains a ")
if e.dstype === PairedDS
print(io, "paired read datastore")
elseif e.dstype === LongDS
print(io, "long read datastore")
elseif e.dstype === LinkedDS
print(io, "linked read datastore")
else
print(io, "unknown datastore type")
end
print(io, " and cannot be opened as a ")
print(io, D)
end
struct DatastoreVersionError{D<:ReadDatastore} <: Exception
version::Int
end
struct DatastoreEncodingError{D<:ReadDatastore} <: Exception
filename::String
bpe::Int
end
function Base.showerror(io::IO, e::DatastoreEncodingError{D}) where {D}
print(io, "DatastoreEncodingError: ")
print(io, e.filename)
print(io, " encodes reads using ")
print(io, e.bpe)
print(io, " bits per element and cannot be opened as a ")
print(io, D)
end
function __validate_datastore_header(io::IOStream, dstype::Type{D}) where {D<:ReadDatastore}
magic = read(io, UInt16)
dstype = reinterpret(Filetype, read(io, UInt16))
version = read(io, UInt16)
if magic !== ReadDatastoreMAGIC
throw(MissingMagicError(io.name))
end
if dstype !== __ds_type_code(D)
throw(DatastoreTypeError{D}(io.name, dstype))
end
if version !== __ds_version_code(D)
throw(DatastoreVersionError{D}(version))
end
bps = read(io, UInt64)
if bps != BioSequences.bits_per_symbol(Alphabet(eltype(D)))
throw(DatastoreEncodingError{D}(io.name, bps))
end
end
###
### Concrete ReadDatastore type definitions
###
include("short-reads.jl")
include("paired-reads.jl")
include("long-reads.jl")
include("linked-reads.jl")
include("sequence-buffer.jl")
function Base.showerror(io::IO, e::DatastoreVersionError{<:PairedReads})
print(io, "DatastoreVersionError: ")
print(io, "file format version of paired read datastore file (v")
print(io, Int(e.version))
print(io, ") is deprecated: this version of ReadDatastores.jl supports v")
print(io, Int(PairedDS_Version))
end
function Base.showerror(io::IO, e::DatastoreVersionError{<:LongReads})
print(io, "DatastoreVersionError: ")
print(io, "file format version of long read datastore file (v")
print(io, Int(e.version))
print(io, ") is deprecated: this version of ReadDatastores.jl supports v")
print(io, Int(LongDS_Version))
end
function Base.showerror(io::IO, e::DatastoreVersionError{<:LinkedReads})
print(io, "DatastoreVersionError: ")
print(io, "file format version of linked read datastore file (v")
print(io, Int(e.version))
print(io, ") is deprecated: this version of ReadDatastores.jl supports v")
print(io, Int(LinkedDS_Version))
end
###
### ReadDatastore generics
###
@inline buffer(ds::ReadDatastore, buffer_size = DEFAULT_BUF_SIZE) = DatastoreBuffer(ds, buffer_size)
# TODO: Phase out
#"Get the length of the longest sequence in the datastore"
#@inline maxseqlen(ds::ReadDatastore) = ds.max_read_len
"Get the name of the datastore"
@inline name(ds::ReadDatastore) = ds.name
"Get a reference to the underlying filestream the datastore is using"
@inline stream(ds::ReadDatastore) = ds.stream
@inline Base.firstindex(ds::ReadDatastore) = 1
@inline Base.lastindex(ds::ReadDatastore) = length(ds)
@inline Base.eachindex(ds::ReadDatastore) = Base.OneTo(lastindex(ds))
@inline Base.IteratorSize(ds::ReadDatastore) = Base.HasLength()
@inline Base.IteratorEltype(ds::ReadDatastore) = Base.HasEltype()
@inline Base.eltype(::Type{<:ReadDatastore{T}}) where {T} = T
@inline Base.close(ds::ReadDatastore) = close(stream(ds))
@inline function Base.checkbounds(ds::ReadDatastore, i::Integer)
if firstindex(ds) ≤ i ≤ lastindex(ds)
return true
end
throw(BoundsError(ds, i))
end
@inline function Base.iterate(ds::ReadDatastore, state = 1)
@inbounds if firstindex(ds) ≤ state ≤ lastindex(ds)
return ds[state], state + 1
else
return nothing
end
end
function Base.open(f::Function, ::Type{T}, filepath::AbstractString) where {T<:ReadDatastore}
ds = open(T, filepath)
try
f(ds)
finally
close(ds)
end
end
"""
_load_sequence_data!(prds::PairedReads, seq::LongSequence{DNAAlphabet{4}})
Reads the sequence data from the current position of a datastore's stream, into
a destination sequence `seq`.
This function knows how much data to read from the stream, based on the sequence's
data blob (i.e. `sizeof(BioSequences.encoded_data(seq))`).
!!! warning
Uses `unsafe_read`, makes the following assumptions - does not check any of them.
- The stream is at the correct position, such that an `unsafe_read` will
read the entirety of the sequence before hitting the end of file.
Hitting EOF should result in an error being thrown anyway so...
- The destination sequence is currently the correct size and has been resized
appropriately before this function has been called.
- The data in the stream of the datastore is encoded appropriately for the
sequence type.
"""
function _load_sequence_data!(ds::ReadDatastore{T}, seq::T) where {T<:LongSequence}
seqdata = BioSequences.encoded_data(seq)
GC.@preserve seqdata unsafe_read(stream(ds), pointer(seqdata), sizeof(seqdata))
return seq
end
function deduce_datastore_type(filename::String)::DataType
open(filename, "r") do io
seekstart(io)
mn = read(io, UInt16)
@assert mn === ReadDatastoreMAGIC
tp = reinterpret(Filetype, read(io, UInt16))
vn = read(io, UInt16)
bpn = Int64(read(io, UInt64))
if tp === PairedDS
#@assert vn === PairedDS_Version
if vn !== PairedDS_Version
throw(DatastoreVersionError{PairedReads{DNAAlphabet{bpn}}}(vn))
end
out = PairedReads{DNAAlphabet{bpn}}
elseif tp === LongDS
@assert vn === LongDS_Version
out = LongReads{DNAAlphabet{bpn}}
elseif tp === LinkedDS
@assert vn === LinkedDS_Version
out = LinkedReads{DNAAlphabet{bpn}}
else
error("Unrecognized datastore type")
end
return out
end
end
"""
@openreads filename::String
A convenience macro for opening read datastores.
The open method for ReadDatastores requires the specific type of the ReadDatastore
as the first argument.
This can be cumbersome as the specific type of the datastore may be forgotten or
not known in the first place if the user recieved the datastore from a colleague.
This macro allows you to open a datastore using only the filename.
The macro opens the file, peeks at the header and deduces the type of datastore
contained in the file. It then returns a complete and correctly formed `open`
command for the datastore. This allows the user to forget about the specific
datastore type whilst still maintaining type certainty.
"""
macro openreads(filename::String)
dstype = deduce_datastore_type(filename)
return :(open($dstype, $filename))
end
"""
@openreads filename::String name
A convenience macro for opening read datastores and assigning it a name other
than the datastore's default name.
The open method for ReadDatastores requires the specific type of the ReadDatastore
as the first argument.
This can be cumbersome as the specific type of the datastore may be forgotten or
not known in the first place if the user recieved the datastore from a colleague.
This macro allows you to open a datastore using only the filename.
The macro opens the file, peeks at the header and deduces the type of datastore
contained in the file. It then returns a complete and correctly formed `open`
command for the datastore. This allows the user to forget about the specific
datastore type whilst still maintaining type certainty.
"""
macro openreads(filename::String, name::Symbol)
dstype = deduce_datastore_type(filename)
return :(open($dstype, $filename, $(QuoteNode(name))))
end
macro openreads(filename::String, binding::Symbol, expression::Expr)
dstype = deduce_datastore_type(filename)
quote
open($dstype, $filename) do $(esc(binding))
$(esc(expression))
end
end
end
macro openreads(filename::String, name::Symbol, binding::Symbol, expression::Expr)
dstype = deduce_datastore_type(filename)
quote
open($dstype, $filename, $(QuoteNode(name))) do $(esc(binding))
$(esc(expression))
end
end
end
macro openreads(filename::String, name::Symbol, fn::Symbol)
dstype = deduce_datastore_type(filename)
return :(open($fn, $dstype, $filename, $(QuoteNode(name))))
end
macro reads_str(filename::String)
dstype = deduce_datastore_type(filename)
return open(dstype, filename)
end
macro reads_str(filename::String, flag)
dstype = deduce_datastore_type(filename)
if flag === "s"
return open(dstype, filename)
elseif flag === "d"
return :(open($dstype, $filename))
else
error("Invalid flag option")
end
end
end # module
| ReadDatastores | https://github.com/BioJulia/ReadDatastores.jl.git |
|
[
"MIT"
] | 0.4.0 | 72f9df4854d3ee73097ce9f89871557848692541 | code | 10933 | abstract type LinkedReadsFormat end
struct UCDavisTenX <: LinkedReadsFormat end
struct RawTenX <: LinkedReadsFormat end
const UCDavis10x = UCDavisTenX()
const Raw10x = RawTenX()
const LinkedTag = UInt32
mutable struct LinkedReadData{A<:DNAAlphabet}
seq1::LongSequence{A}
seq2::LongSequence{A}
seqlen1::UInt64
seqlen2::UInt64
tag::LinkedTag
end
Base.isless(a::LinkedReadData, b::LinkedReadData) = a.tag < b.tag
LinkedReadData{A}(len) where {A<:DNAAlphabet} = LinkedReadData{A}(LongSequence{A}(len), LongSequence{A}(len), zero(UInt64), zero(UInt64), zero(LinkedTag))
const LinkedDS_Version = 0x0003
function _extract_tag_and_sequences!(current_data::LinkedReadData, fwrec::FASTQ.Record, rvrec::FASTQ.Record, max_read_len::UInt64, ::UCDavisTenX)
fwid = FASTQ.identifier(fwrec)
newtag = zero(UInt32)
@inbounds for i in 1:16
newtag <<= 2
letter = fwid[i]
if letter == 'C'
newtag = newtag + 1
elseif letter == 'G'
newtag = newtag + 2
elseif letter == 'T'
newtag = newtag + 3
elseif letter != 'A'
newtag = zero(UInt32)
break
end
end
current_data.tag = newtag
current_data.seqlen1 = UInt64(min(max_read_len, FASTQ.seqlen(fwrec)))
current_data.seqlen2 = UInt64(min(max_read_len, FASTQ.seqlen(rvrec)))
copyto!(current_data.seq1, 1, fwrec, 1, current_data.seqlen1)
copyto!(current_data.seq2, 1, rvrec, 1, current_data.seqlen2)
end
struct LinkedReads{A<:DNAAlphabet} <: ShortReads{A}
filename::String # Filename datastore was opened from.
name::Symbol # Name of the datastore. Useful for other applications.
defaultname::Symbol # Default name, useful for other applications.
max_read_len::UInt64 # Maximum size of any read in this datastore.
chunksize::UInt64
readpos_offset::UInt64 #
read_tags::Vector{UInt32} #
stream::IO
end
__ds_type_code(::Type{<:LinkedReads}) = LinkedDS
__ds_version_code(::Type{<:LinkedReads}) = LinkedDS_Version
"""
LinkedReads{A}(fwq::FASTQ.Reader, rvq::FASTQ.Reader, outfile::String, name::String, format::LinkedReadsFormat, max_read_len::Integer, chunksize::Int = 1000000) where {A<:DNAAlphabet}
Construct a Linked Read Datastore from a pair of FASTQ file readers.
Paired sequencing reads typically come in the form of two FASTQ files, often
named according to a convention `*_R1.fastq` and `*_R2.fastq`.
One file contains all the "left" sequences of each pair, and the other contains
all the "right" sequences of each pair. The first read pair is made of the first
record in each file.
# Arguments
- `rdrx::FASTQ.Reader`: The reader of the `*_R1.fastq` file.
- `rdxy::FASTQ.Reader`: The reader of the `*_R2.fastq` file.
- `outfile::String`: A prefix for the datastore's filename, the full filename
will include a ".prseq" extension, which will be added automatically.
- `name::String`: A string denoting a default name for your datastore.
Naming datastores is useful for downstream applications.
- `format::LinkedReadsFormat`: Specify the linked reads format of your fastq files.
If you have plain 10x files, set format to `Raw10x`. If you have 10x reads
output in the UCDavis format, set the format to `UCDavis10x`.
- `chunksize::Int = 1000000`: How many read pairs to process per disk batch
during the tag sorting step of construction.
# Examples
```jldoctest
julia> using FASTX, ReadDatastores
julia> fqa = open(FASTQ.Reader, "test/10x_tester_R1.fastq")
FASTX.FASTQ.Reader{TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}}(BioGenerics.Automa.State{TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}}(TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}(<mode=idle>), 1, 1, false), nothing)
julia> fqb = open(FASTQ.Reader, "test/10x_tester_R2.fastq")
FASTX.FASTQ.Reader{TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}}(BioGenerics.Automa.State{TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}}(TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}(<mode=idle>), 1, 1, false), nothing)
julia> ds = LinkedReads{DNAAlphabet{2s}}(fqa, fqb, "10xtest", "ucdavis-test", UCDavis10x, 250)
[ Info: Building tag sorted chunks of 1000000 pairs
[ Info: Dumping 83 tag-sorted read pairs to chunk 0
[ Info: Dumped
[ Info: Processed 83 read pairs so far
[ Info: Finished building tag sorted chunks
[ Info: Performing merge from disk
[ Info: Leaving space for 83 read_tag entries
[ Info: Chunk 0 is finished
[ Info: Finished merge from disk
[ Info: Writing 83 read tag entries
[ Info: Created linked sequence datastore with 83 sequence pairs
Linked Read Datastore 'ucdavis-test': 166 reads (83 pairs)
```
"""
function LinkedReads{A}(fwq::FASTQ.Reader, rvq::FASTQ.Reader, outfile::String, name::Union{String,Symbol}, format::LinkedReadsFormat, max_read_len::Integer, chunksize::Int = 1000000) where {A<:DNAAlphabet}
return LinkedReads{A}(fwq, rvq, outfile, name, format, convert(UInt64, max_read_len), chunksize)
end
function LinkedReads{A}(fwq::FASTQ.Reader, rvq::FASTQ.Reader, outfile::String, name::Union{String,Symbol}, format::LinkedReadsFormat, max_read_len::UInt64, chunksize::Int = 1000000) where {A<:DNAAlphabet}
n_pairs = 0
chunk_files = String[]
@info string("Building tag sorted chunks of ", chunksize, " pairs")
fwrec = FASTQ.Record()
rvrec = FASTQ.Record()
chunk_data = [LinkedReadData{A}(max_read_len) for _ in 1:chunksize]
datachunksize = length(BioSequences.encoded_data(first(chunk_data).seq1))
while !eof(fwq) && !eof(rvq)
# Read in `chunksize` read pairs.
chunkfill = 0
while !eof(fwq) && !eof(rvq) && chunkfill < chunksize
try # TODO: Get to the bottom of why this is nessecery to fix Windows issues.
read!(fwq, fwrec)
read!(rvq, rvrec)
catch ex
if isa(ex, EOFError)
break
end
rethrow()
end
cd_i = chunk_data[chunkfill + 1]
_extract_tag_and_sequences!(cd_i, fwrec, rvrec, max_read_len, format)
if cd_i.tag != zero(UInt32)
chunkfill = chunkfill + 1
end
end
# Sort the linked reads by tag
sort!(view(chunk_data, 1:chunkfill))
# Dump the data to a chunk dump
chunk_fd = open(string("sorted_chunk_", length(chunk_files), ".data"), "w")
@info string("Dumping ", chunkfill, " tag-sorted read pairs to chunk ", length(chunk_files))
for j in 1:chunkfill
cd_j = chunk_data[j]
write(chunk_fd, cd_j.tag)
write(chunk_fd, cd_j.seqlen1)
write(chunk_fd, BioSequences.encoded_data(cd_j.seq1))
write(chunk_fd, cd_j.seqlen2)
write(chunk_fd, BioSequences.encoded_data(cd_j.seq2))
end
close(chunk_fd)
push!(chunk_files, string("sorted_chunk_", length(chunk_files), ".data"))
@info "Dumped"
n_pairs = n_pairs + chunkfill
@info string("Processed ", n_pairs, " read pairs so far")
end
close(fwq)
close(rvq)
@info "Finished building tag sorted chunks"
@info "Performing merge from disk"
read_tag = zeros(UInt32, n_pairs)
@info string("Leaving space for ", n_pairs, " read_tag entries")
bps = UInt64(BioSequences.bits_per_symbol(A()))
output = open(outfile * ".lrseq", "w")
# Write magic no, datastore type, version number, and bits per symbol.
write(output, ReadDatastoreMAGIC, LinkedDS, LinkedDS_Version, bps)
# Write the default name of the datastore.
writestring(output, String(name))
# Write the read size, chunk size.
write(output, max_read_len, datachunksize)
read_tag_offset = position(output)
write_flat_vector(output, read_tag)
# Multiway merge of chunks...
chunk_fds = map(x -> open(x, "r"), chunk_files)
openfiles = length(chunk_fds)
next_tags = Vector{UInt32}(undef, openfiles)
for i in eachindex(chunk_fds)
next_tags[i] = read(chunk_fds[i], LinkedTag)
end
filebuffer = Vector{UInt8}(undef, 16(datachunksize + 1))
empty!(read_tag)
while openfiles > 0
mintag = minimum(next_tags)
# Copy from each file until then next tag is > mintag
for i in eachindex(chunk_fds)
fd = chunk_fds[i]
while !eof(fd) && next_tags[i] == mintag
# Read from chunk file, and write to final file.
readbytes!(fd, filebuffer)
write(output, filebuffer)
push!(read_tag, mintag)
if eof(fd)
openfiles = openfiles - 1
next_tags[i] = typemax(LinkedTag)
@info string("Chunk ", i - 1, " is finished")
else
next_tags[i] = read(fd, LinkedTag)
end
end
end
end
@info "Finished merge from disk"
seek(output, read_tag_offset)
@info string("Writing ", n_pairs, " read tag entries")
write_flat_vector(output, read_tag)
readspos = position(output)
close(output)
for fd in chunk_fds
close(fd)
end
for fname in chunk_files
rm(fname)
end
@info string("Created linked sequence datastore with ", n_pairs, " sequence pairs")
return LinkedReads{A}(outfile * ".lrseq", Symbol(name), Symbol(name), max_read_len, datachunksize, readspos, read_tag, open(outfile * ".lrseq", "r"))
end
function Base.open(::Type{LinkedReads{A}}, filename::String, name::Union{Symbol,String,Nothing} = nothing) where {A<:DNAAlphabet}
fd = open(filename, "r")
__validate_datastore_header(fd, LinkedReads{A})
default_name = Symbol(readuntil(fd, '\0'))
max_read_len = read(fd, UInt64)
chunksize = read(fd, UInt64)
read_tags = read_flat_vector(fd, UInt32)
return LinkedReads{A}(filename, name === nothing ? default_name : Symbol(name), default_name, max_read_len, chunksize, position(fd), read_tags, fd)
end
@inline _read_data_begin(prds::LinkedReads) = prds.readpos_offset
@inline _bytes_per_read(prds::LinkedReads) = (prds.chunksize + 1) * sizeof(UInt64)
@inline max_read_length(prds::LinkedReads) = prds.max_read_len
@inline Base.length(lrds::LinkedReads) = length(lrds.read_tags) * 2
Base.summary(io::IO, lrds::LinkedReads) = print(io, "Linked Read Datastore '", lrds.name, "': ", length(lrds), " reads (", div(length(lrds), 2), " pairs)")
@inline inbounds_read_tag(lrds::LinkedReads, idx::Integer) = @inbounds lrds.read_tags[div(idx + 1, 2)]
"""
read_tag(lr::LinkedReads, i::Integer)
Get the tag for the i'th read
"""
function read_tag(lr::LinkedReads, i::Integer)
checkbounds(lr, i)
inbounds_readtag(lr, i)
end
| ReadDatastores | https://github.com/BioJulia/ReadDatastores.jl.git |
|
[
"MIT"
] | 0.4.0 | 72f9df4854d3ee73097ce9f89871557848692541 | code | 6924 | struct ReadPosSize
offset::UInt64
sequence_size::UInt64
end
Base.:(==)(x::ReadPosSize, y::ReadPosSize) = x.offset == y.offset && x.sequence_size == y.sequence_size
struct LongReads{A<:DNAAlphabet} <: ReadDatastore{LongSequence{A}}
filename::String
name::Symbol
default_name::Symbol
read_to_file_positions::Vector{ReadPosSize}
stream::IO
end
index(lrds::LongReads) = lrds.read_to_file_positions
"Get the length of the longest sequence in the datastore"
function max_read_length(lrds::LongReads)
max = zero(UInt64)
@inbounds for i in index(lrds)
ss = i.sequence_size
if i.sequence_size > max
max = i.sequence_size
end
end
return max
end
const LongDS_Version = 0x0003
__ds_type_code(::Type{<:LongReads}) = LongDS
__ds_version_code(::Type{<:LongReads}) = LongDS_Version
###
### LongReads Header
###
# | Field | Value | Type |
# |:-----------------------------:|:------:|:-----------:|
# | Magic number | 0x05D5 | UInt16 | 2
# | Datastore type | 0x0002 | UInt16 | 2
# | Version number | 0x0001 | UInt16 | 2
# | Number of bits used per nuc | 2 or 4 | UInt64 | 8
# | Index position in file | N/A | UInt64 | 8
# | Default name of the datastore | N/A | String | N
"""
LongReads{A}(rdr::FASTQ.Reader, outfile::String, name::String, min_size::Integer) where {A<:DNAAlphabet}
Construct a Long Read Datastore from a FASTQ file reader.
# Arguments
- `rdr::FASTQ.Reader`: The reader of the fastq formatted file.
- `outfile::String`: A prefix for the datastore's filename, the full filename
will include a ".loseq" extension, which will be added automatically.
- `name::String`: A string denoting a default name for your datastore.
Naming datastores is useful for downstream applications.
- `min_size::Integer`: A minimum read length (in base pairs). When building
the datastore, if any read sequence is shorter than this cutoff, then the read
will be discarded.
# Examples
```jldoctest
julia> using FASTX, ReadDatastores
julia> longrdr = open(FASTQ.Reader, "test/human_nanopore_tester_2D.fastq")
FASTX.FASTQ.Reader{TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}}(BioGenerics.Automa.State{TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}}(TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}(<mode=idle>), 1, 1, false), nothing)
julia> ds = LongReads{DNAAlphabet{2}}(longrdr, "human-nanopore-tester", "nanopore-test", 0)
[ Info: Building long read datastore from FASTQ file
[ Info: Writing long reads to datastore
[ Info: Done writing paired read sequences to datastore
[ Info: 0 reads were discarded due to a too short sequence
[ Info: Writing index to datastore
[ Info: Built long read datastore with 10 reads
Long Read Datastore 'nanopore-test': 10 reads
```
"""
LongReads{A}(rdr::FASTQ.Reader, outfile::String, name::Union{String,Symbol}, min_size::Integer) where {A<:DNAAlphabet} = LongReads{A}(rdr, outfile, name, convert(UInt64, min_size))
function LongReads{A}(rdr::FASTQ.Reader, outfile::String, name::Union{String,Symbol}, min_size::UInt64) where {A<:DNAAlphabet}
discarded = 0
read_to_file_position = Vector{ReadPosSize}()
ofs = open(outfile * ".loseq", "w")
bps = UInt64(BioSequences.bits_per_symbol(A()))
write(ofs, ReadDatastoreMAGIC, LongDS, LongDS_Version, bps, zero(UInt64))
writestring(ofs, String(name))
record = FASTQ.Record()
seq = LongSequence{A}(min_size)
@info "Building long read datastore from FASTQ file"
@info "Writing long reads to datastore"
while !eof(rdr)
try # TODO: Get to the bottom of why this is nessecery to fix Windows issues.
read!(rdr, record)
catch ex
if isa(ex, EOFError)
break
end
rethrow()
end
seq_len = FASTQ.seqlen(record)
if seq_len < min_size
discarded = discarded + 1
continue
end
offset = position(ofs)
resize!(seq, seq_len)
copyto!(seq, record)
push!(read_to_file_position, ReadPosSize(offset, seq_len))
write(ofs, seq.data)
end
@info "Done writing long read sequences to datastore"
@info string(discarded, " reads were discarded due to a too short sequence")
fpos = UInt64(position(ofs))
@info "Writing index to datastore"
write_flat_vector(ofs, read_to_file_position)
# Go to the top and dump the number of reads and the position of the index.
seek(ofs, sizeof(ReadDatastoreMAGIC) + sizeof(Filetype) + sizeof(LongDS_Version) + sizeof(bps))
write(ofs, fpos)
close(ofs)
@info string("Built long read datastore with ", length(read_to_file_position), " reads")
stream = open(outfile * ".loseq", "r+")
return LongReads{A}(outfile * ".loseq", Symbol(name), Symbol(name), read_to_file_position, stream)
end
function Base.open(::Type{LongReads{A}}, filename::String, name::Union{String,Symbol,Nothing} = nothing) where {A<:DNAAlphabet}
fd = open(filename, "r")
__validate_datastore_header(fd, LongReads{A})
fpos = read(fd, UInt64)
default_name = Symbol(readuntil(fd, '\0'))
seek(fd, fpos)
read_to_file_position = read_flat_vector(fd, ReadPosSize)
return LongReads{A}(filename, name === nothing ? default_name : Symbol(name), default_name, read_to_file_position, fd)
end
###
### Getting a sequence
###
Base.length(lrds::LongReads) = length(lrds.read_to_file_positions)
Base.summary(io::IO, lrds::LongReads) = print(io, "Long Read Datastore '", lrds.name, "': ", length(lrds), " reads")
function Base.show(io::IO, lrds::LongReads)
summary(io, lrds)
end
@inline _inbounds_index_of_sequence(lrds::LongReads, idx::Integer) = @inbounds lrds.read_to_file_positions[idx]
@inline function inbounds_load_sequence!(lrds::LongReads{A}, pos::ReadPosSize, seq::LongSequence{A}) where {A<:DNAAlphabet}
seek(stream(lrds), pos.offset)
resize!(seq, pos.sequence_size)
return _load_sequence_data!(lrds, seq)
end
@inline function inbounds_load_sequence!(lrds::LongReads{A}, idx::Integer, seq::LongSequence{A}) where {A<:DNAAlphabet}
pos_size = _inbounds_index_of_sequence(lrds, idx)
return inbounds_load_sequence!(lrds, pos_size, seq)
end
@inline function load_sequence!(lrds::LongReads{A}, idx::Integer, seq::LongSequence{A}) where {A<:DNAAlphabet}
checkbounds(lrds, idx)
return inbounds_load_sequence!(lrds, idx, seq)
end
@inline function Base.getindex(lrds::LongReads, idx::Integer)
@boundscheck checkbounds(lrds, idx)
pos_size = _inbounds_index_of_sequence(lrds, idx)
seq = eltype(lrds)(pos_size.sequence_size)
return inbounds_load_sequence!(lrds, pos_size, seq)
end
| ReadDatastores | https://github.com/BioJulia/ReadDatastores.jl.git |
|
[
"MIT"
] | 0.4.0 | 72f9df4854d3ee73097ce9f89871557848692541 | code | 9719 | @enum PairedReadOrientation::UInt64 FwRv=1 RvFw=2
struct PairedReads{A<:DNAAlphabet} <: ShortReads{A}
filename::String # Filename datastore was opened from.
name::Symbol # Name of the datastore. Useful for other applications.
defaultname::Symbol # Default name, useful for other applications.
max_read_len::UInt64 # Maximum size of any read in this datastore.
chunksize::UInt64 # Number of chunks (UInt64) of sequence data per read.
fragsize::UInt64 # Fragment size of library.
readpos_offset::UInt64
size::UInt64
orientation::PairedReadOrientation
stream::IOStream
end
"Get the orientation of the read pairs"
@inline orientation(prds::PairedReads) = prds.orientation
# TODO: Phase out.
#@inline BioSequences.bits_per_symbol(prds::PairedReads{A}) where {A<:DNAAlphabet} = BioSequences.bits_per_symbol(A())
###
### PairedReads Header format on disk.
###
# | Field | Value | Type |
# |:-----------------:|:------:|:-----------:|
# | Magic number | 0x05D5 | UInt16 | 2 0
# | Datastore type | 0x0001 | UInt16 | 2 2
# | Version number | 0x0001 | UInt16 | 2 4
# | Bits Per Nuc | N/A | UInt64 | 8 6
# | Default name | N/A | String | 7
# | Maximum read size | N/A | UInt64 | 8
# | Chunk size | N/A | UInt64 | 8
# | Fragment size | N/A | UInt64 | 8
# | Orientation | N/A | Orientation | 8
# | Number of Reads | N/A | UInt64 | 8
const PairedDS_Version = 0x0003
__ds_type_code(::Type{<:PairedReads}) = PairedDS
__ds_version_code(::Type{<:PairedReads}) = PairedDS_Version
"""
PairedReads{A}(rdrx::FASTQ.Reader, rdry::FASTQ.Reader, outfile::String, name::Union{String,Symbol}, minsize::Integer, maxsize::Integer, fragsize::Integer, orientation::PairedReadOrientation) where {A<:DNAAlphabet}
Construct a Paired Read Datastore from a pair of FASTQ file readers.
Paired-end sequencing reads typically come in the form of two FASTQ files, often
named according to a convention `*_R1.fastq` and `*_R2.fastq`.
One file contains all the "left" sequences of each pair, and the other contains
all the "right" sequences of each pair. The first read pair is made of the first
record in each file.
# Arguments
- `rdrx::FASTQ.Reader`: The reader of the `*_R1.fastq` file.
- `rdxy::FASTQ.Reader`: The reader of the `*_R2.fastq` file.
- `outfile::String`: A prefix for the datastore's filename, the full filename
will include a ".prseq" extension, which will be added automatically.
- `name::String`: A string denoting a default name for your datastore.
Naming datastores is useful for downstream applications.
- `minsize::Integer`: A minimum read length (in base pairs). When building
the datastore, if any pair of reads has one or both reads shorter than this
cutoff, then the pair will be discarded.
- `maxsize::Integer`: A maximum read length (in base pairs). When building
the datastore, if any read has a greater length, it will be resized to this
maximum length and added to the datastore.
- `fragsize::Integer`: The average fragment length of the paired end library
that was sequenced. This value is entirely optional, but may be important for
downstream applications.
- `orientation::PairedReadOrientation`: The orientation of the reads. Set it to
`FwRv` for building a datastore from a sequenced paired end library, and set
it to `RvFw` if you are building the datastore from reads sequenced from a
long mate pair library.
# Examples
```jldoctest
julia> using FASTX, ReadDatastores
julia> fwq = open(FASTQ.Reader, "test/ecoli_tester_R1.fastq")
FASTX.FASTQ.Reader{TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}}(BioGenerics.Automa.State{TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}}(TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}(<mode=idle>), 1, 1, false), nothing)
julia> rvq = open(FASTQ.Reader, "test/ecoli_tester_R2.fastq")
FASTX.FASTQ.Reader{TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}}(BioGenerics.Automa.State{TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}}(TranscodingStreams.TranscodingStream{TranscodingStreams.Noop,IOStream}(<mode=idle>), 1, 1, false), nothing)
julia> ds = PairedReads{DNAAlphabet{2}}(fwq, rvq, "ecoli-test-paired", "my-ecoli-test", 250, 300, 0, FwRv)
[ Info: Building paired read datastore from FASTQ files
[ Info: Writing paired reads to datastore
[ Info: Done writing paired read sequences to datastore
[ Info: 0 read pairs were discarded due to a too short sequence
[ Info: 14 reads were truncated to 300 base pairs
[ Info: Created paired sequence datastore with 10 sequence pairs
Paired Read Datastore 'my-ecoli-test': 20 reads (10 pairs)
```
"""
function PairedReads{A}(rdrx::FASTQ.Reader, rdry::FASTQ.Reader, outfile::String, name::Union{String,Symbol},
minsize::Integer, maxsize::Integer, fragsize::Integer, orientation::PairedReadOrientation) where {A<:DNAAlphabet}
return PairedReads{A}(rdrx, rdry, outfile, name, convert(UInt64, minsize),
convert(UInt64, maxsize), convert(UInt64, fragsize), orientation)
end
function PairedReads{A}(rdrx::FASTQ.Reader, rdry::FASTQ.Reader,
outfile::String, name::Union{Symbol,String},
minsize::UInt64, maxsize::UInt64,
fragsize::UInt64, orientation::PairedReadOrientation) where {A<:DNAAlphabet}
# Create and allocate the sequence and record objects.
lread = FASTQ.Record()
rread = FASTQ.Record()
lseq = LongSequence{A}(maxsize)
rseq = LongSequence{A}(maxsize)
#chunksize::UInt64 = BioSequences.seq_data_len(DNAAlphabet{4}, maxsize)
chunksize::UInt64 = length(BioSequences.encoded_data(lseq))
bps = UInt64(BioSequences.bits_per_symbol(A()))
fd = open(outfile * ".prseq", "w")
# Write magic no, datastore type, version number.
sizepos = write(fd, ReadDatastoreMAGIC, PairedDS, PairedDS_Version, bps) +
# Write the default name of the datastore.
writestring(fd, String(name)) +
# Write the read size, and chunk size.
write(fd, maxsize, chunksize, fragsize, orientation)
# Write space for size variable (or number of read pairs).
readpos = write(fd, UInt64(0)) + sizepos
pairs = discarded = truncated = 0
p = 1
@info "Building paired read datastore from FASTQ files"
@info "Writing paired reads to datastore"
while !eof(rdrx) && !eof(rdry)
# Read in the two records.
try # TODO: Get to the bottom of why this is nessecery to fix Windows issues.
read!(rdrx, lread)
read!(rdry, rread)
catch ex
if isa(ex, EOFError)
break
end
rethrow()
end
llen = UInt64(FASTQ.seqlen(lread))
rlen = UInt64(FASTQ.seqlen(rread))
# If either read is too short, discard them both.
if llen < minsize || rlen < minsize
discarded += 1
continue
end
if llen > maxsize
truncated += 1
ln = maxsize
else
ln = llen
end
if rlen > maxsize
truncated += 1
rn = maxsize
else
rn = rlen
end
pairs += 1
# Copy FASTQ records to sequence variables, thus encoding
# them in 2 bit format.
copyto!(lseq, 1, lread, 1, ln)
copyto!(rseq, 1, rread, 1, rn)
# Write the two sizes reads one after the other:
# For each sequence, write the size, and then the datachunk.
write(fd, ln)
write(fd, lseq.data)
write(fd, rn)
write(fd, rseq.data)
end
nreads::UInt64 = pairs * 2
seek(fd, sizepos)
write(fd, nreads)
flush(fd)
close(fd)
@info "Done writing paired read sequences to datastore"
@info string(discarded, " read pairs were discarded due to a too short sequence")
@info string(truncated, " reads were truncated to ", maxsize, " base pairs")
@info string("Created paired sequence datastore with ", pairs, " sequence pairs")
stream = open(outfile * ".prseq", "r+")
return PairedReads{A}(outfile * ".prseq", Symbol(name), Symbol(name), maxsize, chunksize, fragsize,
readpos, nreads, orientation, stream)
end
function Base.open(::Type{PairedReads{A}}, filename::String, name::Union{String,Symbol,Nothing} = nothing) where {A<:DNAAlphabet}
fd = open(filename, "r")
__validate_datastore_header(fd, PairedReads{A})
default_name = Symbol(readuntil(fd, '\0'))
max_read_len = read(fd, UInt64)
chunksize = read(fd, UInt64)
fragsize = read(fd, UInt64)
orientation = reinterpret(PairedReadOrientation, read(fd, UInt64))
nreads = read(fd, UInt64)
readpos_offset = position(fd)
return PairedReads{A}(filename, name === nothing ? default_name : Symbol(name), default_name,
max_read_len, chunksize, fragsize,
readpos_offset, nreads, orientation, fd)
end
@inline Base.length(prds::PairedReads) = prds.size
Base.summary(io::IO, prds::PairedReads) = print(io, "Paired Read Datastore '", prds.name, "': ", length(prds), " reads (", div(length(prds), 2), " pairs)")
@inline _read_data_begin(prds::PairedReads) = prds.readpos_offset
@inline _bytes_per_read(prds::PairedReads) = (prds.chunksize + 1) * sizeof(UInt64)
@inline max_read_length(prds::PairedReads) = prds.max_read_len
| ReadDatastores | https://github.com/BioJulia/ReadDatastores.jl.git |
|
[
"MIT"
] | 0.4.0 | 72f9df4854d3ee73097ce9f89871557848692541 | code | 6252 | const DEFAULT_BUF_SIZE = UInt64(1024 * 1024 * 30)
@inline megabytes(n::T) where {T<:Unsigned} = (T(1024) * T(1024)) * n
@inline megabytes(n::Signed) = megabytes(unsigned(n))
@inline gigabytes(n::T) where {T<:Unsigned} = (T(1024) * T(1024) * T(1024)) * n
@inline gigabytes(n::Signed) = gigabytes(unsigned(n))
mutable struct DatastoreBuffer{T<:ReadDatastore}
data_store::T
bufferdata::Vector{UInt8}
buffer_position::Int
end
function DatastoreBuffer(ds::T, buffer_size = DEFAULT_BUF_SIZE) where {T<:ReadDatastore}
return DatastoreBuffer{T}(ds, Vector{UInt8}(undef, buffer_size), typemax(Int))
end
function DatastoreBuffer(ds::ShortReads, buffer_size = DEFAULT_BUF_SIZE)
if _bytes_per_read(ds) > buffer_size
error("Desired buffer size is too small")
end
return DatastoreBuffer{typeof(ds)}(ds, Vector{UInt8}(undef, buffer_size), typemax(Int))
end
@inline buffer_len(sb::DatastoreBuffer) = length(buffer_array(sb))
@inline buffer_position(sb::DatastoreBuffer) = sb.buffer_position
@inline bufferpos!(sb::DatastoreBuffer, pos) = sb.buffer_position = pos
@inline datastore(sb::DatastoreBuffer) = sb.data_store
@inline stream(sb::DatastoreBuffer) = stream(datastore(sb))
@inline buffer_array(sb::DatastoreBuffer) = sb.bufferdata
@inline Base.eltype(sb::DatastoreBuffer) = Base.eltype(datastore(sb))
@inline Base.firstindex(sb::DatastoreBuffer) = firstindex(datastore(sb))
@inline Base.lastindex(sb::DatastoreBuffer) = lastindex(datastore(sb))
@inline Base.length(sb::DatastoreBuffer) = length(datastore(sb))
@inline Base.eachindex(sb::DatastoreBuffer) = eachindex(datastore(sb))
@inline Base.IteratorSize(sb::DatastoreBuffer) = Base.IteratorSize(datastore(sb))
@inline Base.IteratorEltype(sb::DatastoreBuffer) = Base.IteratorEltype(datastore(sb))
@inline Base.checkbounds(sb::DatastoreBuffer, i) = Base.checkbounds(datastore(sb), i)
@inline function _load_sequence_data!(seq::LongSequence{A}, sb::DatastoreBuffer, offset::Integer) where {A<:DNAAlphabet}
bufdata = buffer_array(sb)
seqdata = BioSequences.encoded_data(seq)
GC.@preserve bufdata begin
for i in eachindex(seqdata)
seqdata[i] = unsafe_load(convert(Ptr{UInt64}, pointer(bufdata, offset + 1)))
offset = offset + sizeof(UInt64)
end
end
return seq
end
# Short Reads specific buffering.
@inline function _check_for_buffer_refresh!(sb::DatastoreBuffer{<:ShortReads{<:DNAAlphabet}}, file_offset::Integer)
# IF the desired data is contained in the buffer, there's no need to refresh.
# Otherwise, there is!
buf_start = buffer_position(sb)
buf_size = buffer_len(sb)
file_end = file_offset + _bytes_per_read(datastore(sb))
if file_offset < buf_start || file_end > buf_start + buf_size
bufferpos!(sb, file_offset)
seek(stream(sb), file_offset)
readbytes!(stream(sb), buffer_array(sb), buf_size)
end
end
@inline function Base.getindex(sb::DatastoreBuffer{<:ShortReads{<:DNAAlphabet}}, idx::Integer)
@boundscheck checkbounds(sb, idx)
file_offset = _offset_of_sequence(datastore(sb), idx)
_check_for_buffer_refresh!(sb, file_offset)
buffer_offset = file_offset - buffer_position(sb)
sequence_length = unsafe_load(convert(Ptr{UInt64}, pointer(buffer_array(sb), buffer_offset + 1)))
buffer_offset = buffer_offset + sizeof(UInt64)
seq = eltype(sb)(sequence_length)
return _load_sequence_data!(seq, sb, buffer_offset)
end
@inline function inbounds_load_sequence!(sb::DatastoreBuffer{<:ShortReads{A}}, i::Integer, seq::LongSequence{A}) where {A<:DNAAlphabet}
file_offset = _offset_of_sequence(datastore(sb), i)
_check_for_buffer_refresh!(sb, file_offset)
buffer_offset = file_offset - buffer_position(sb)
sequence_length = unsafe_load(convert(Ptr{UInt64}, pointer(buffer_array(sb), buffer_offset + 1)))
buffer_offset = buffer_offset + sizeof(UInt64)
resize!(seq, sequence_length)
return _load_sequence_data!(seq, sb, buffer_offset)
end
# Long reads specific buffering
@inline function _check_for_buffer_refresh!(sb::DatastoreBuffer{LongReads{A}}, filepos::ReadPosSize) where {A<:DNAAlphabet}
# If the buffer is too small to even fit the sequence. It will need to be
# resized to be made bigger.
n_bytes_req = cld(filepos.sequence_size, div(8, BioSequences.bits_per_symbol(A())))
buf_start = buffer_position(sb)
buf_size = buffer_len(sb)
if buf_size < n_bytes_req
@info "Resizing buffer!"
resize!(sb.bufferdata, n_bytes_req)
buf_size = n_bytes_req
end
file_start = filepos.offset
file_end = file_start + n_bytes_req
if file_start < buf_start || file_end > buf_start + buf_size
bufferpos!(sb, file_start)
seek(stream(sb), file_start)
readbytes!(stream(sb), buffer_array(sb), buf_size)
end
end
@inline function inbounds_load_sequence!(sb::DatastoreBuffer{LongReads{A}}, i::Integer, seq::LongSequence{A}) where {A<:DNAAlphabet}
file_index = _inbounds_index_of_sequence(datastore(sb), i)
_check_for_buffer_refresh!(sb, file_index)
resize!(seq, file_index.sequence_size)
buffer_offset = file_index.offset - buffer_position(sb)
return _load_sequence_data!(seq, sb, buffer_offset)
end
@inline function Base.getindex(sb::DatastoreBuffer{LongReads{A}}, idx::Integer) where {A<:DNAAlphabet}
@boundscheck checkbounds(sb, idx)
file_index = _inbounds_index_of_sequence(datastore(sb), idx)
_check_for_buffer_refresh!(sb, file_index)
seq = eltype(sb)(file_index.sequence_size)
buffer_offset = file_index.offset - buffer_position(sb)
return _load_sequence_data!(seq, sb, buffer_offset)
end
@inline function load_sequence!(sb::DatastoreBuffer{DS}, i::Integer, seq::T) where {T<:LongSequence,DS<:ReadDatastore{T}}
checkbounds(sb, i)
return inbounds_load_sequence!(sb, i, seq)
end
@inline function Base.iterate(sb::DatastoreBuffer, state = 1)
@inbounds if firstindex(sb) ≤ state ≤ lastindex(sb)
return sb[state], state + 1
else
return nothing
end
end
@inline Base.summary(io::IO, sb::DatastoreBuffer) = print(io, "Buffered ", summary(datastore(sb)))
@inline Base.show(io::IO, sb::DatastoreBuffer) = summary(io, sb) | ReadDatastores | https://github.com/BioJulia/ReadDatastores.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.