licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.1.1
72e4eeb7ecb32cb134bfde2b4f7686eb816cc0c7
code
329
Random.seed!(0) #sig = [1 2; 2 2] #sig = [1 1; 2 3] sig = [2 3] #sig = [2 2] #sig = [3 2; 2 3] S = random_S0Graph(sig) Sthin = complement(forget_S0(complement(S))) w = random_bounded(S.n) @time opt1 = dsw(Sthin, w, eps=solver_eps, verbose=1)[1] @time opt2 = dsw(S, Ψ(S, w), eps=solver_eps)[1] @test opt1 ≈ opt2*S.n atol=tol
NoncommutativeGraphs
https://github.com/dstahlke/NoncommutativeGraphs.jl.git
[ "MIT" ]
0.1.1
72e4eeb7ecb32cb134bfde2b4f7686eb816cc0c7
code
327
Random.seed!(0) #sig = [1 2; 2 2] #sig = [1 1; 2 3] sig = [2 3] #sig = [2 2] #sig = [3 2; 2 3] S = random_S0Graph(sig) w = random_bounded(S.n) U = random_S1_unitary(sig); SU = S0Graph(S.sig, U * S.S * U') @time opt1 = dsw(S, w, eps=solver_eps)[1] @time opt2 = dsw(SU, U*w*U', eps=solver_eps)[1] @test opt1 ≈ opt2 atol=tol
NoncommutativeGraphs
https://github.com/dstahlke/NoncommutativeGraphs.jl.git
[ "MIT" ]
0.1.1
72e4eeb7ecb32cb134bfde2b4f7686eb816cc0c7
docs
1478
NoncommitativeGraphs.jl - Non-commutative graphs in Julia ========================================================= This package provides support for non-commutative graphs, a quantum analogue of graphs, as defined in Duan, Severini, Winter, *Zero-error communication via quantum channels, non-commutative graphs and a quantum Lovasz theta function*, [arXiv:1002.2514](https://arxiv.org/abs/1002.2514). Aside from a data structure for holding such graphs, we provide functions for computing the weighted Lovasz theta function as defined in Stahlke, *Weighted theta functions for non-commutative graphs*, [arXiv:2101.00162](https://arxiv.org/abs/2101.00162). ## Example ```julia julia> using NoncommutativeGraphs, Random julia> Random.seed!(0); julia> sig = [3 2; 2 3]; # S₀ algebra is M₃⊗I₂ ⊕ M₂⊗I₃ julia> S = random_S0Graph(sig) S0Graph{S0=[3 2; 2 3] S=Subspace{ComplexF64} size (12, 12) dim 83} julia> S.S0 # vertex C*-algebra Subspace{ComplexF64} size (12, 12) dim 13 julia> T = complement(S) # T = perp(S) + S₀ S0Graph{S0=[3 2; 2 3] S=Subspace{ComplexF64} size (12, 12) dim 74} julia> W = randn(ComplexF64, S.n, S.n); W = W' * W; # random weight operator julia> opt1 = dsw(S, W, eps=1e-7).λ # compute weighted theta 133.57806623525727 julia> opt2 = dsw_via_complement(complement(S), W, eps=1e-7).λ # compute weighted θ via the complement graph, using theorem 29 of arxiv:2101.00162. 133.57806730600717 julia> abs(opt1 - opt2) / abs(opt1 + opt2) < 1e-6 true ```
NoncommutativeGraphs
https://github.com/dstahlke/NoncommutativeGraphs.jl.git
[ "MIT" ]
0.1.1
72e4eeb7ecb32cb134bfde2b4f7686eb816cc0c7
docs
1512
NoncommitativeGraphs.jl - Non-commutative graphs in Julia ========================================================= This package provides support for non-commutative graphs, a quantum analogue of graphs, as defined in Duan, Severini, Winter, *Zero-error communication via quantum channels, non-commutative graphs and a quantum Lovasz theta function*, [arXiv:1002.2514](https://arxiv.org/abs/1002.2514). Aside from a data structure for holding such graphs, we provide functions for computing the weighted Lovasz theta function as defined in Stahlke, *Weighted theta functions for non-commutative graphs*, [arXiv:2101.00162](https://arxiv.org/abs/2101.00162). ## Example ```jldoctest; filter = r"^[0-9]+\.[0-9]+$" julia> using NoncommutativeGraphs, Random julia> Random.seed!(0); julia> sig = [3 2; 2 3]; # S₀ algebra is M₃⊗I₂ ⊕ M₂⊗I₃ julia> S = random_S0Graph(sig) S0Graph{S0=[3 2; 2 3] S=Subspace{ComplexF64} size (12, 12) dim 83} julia> S.S0 # vertex C*-algebra Subspace{ComplexF64} size (12, 12) dim 13 julia> T = complement(S) # T = perp(S) + S₀ S0Graph{S0=[3 2; 2 3] S=Subspace{ComplexF64} size (12, 12) dim 74} julia> W = randn(ComplexF64, S.n, S.n); W = W' * W; # random weight operator julia> opt1 = dsw(S, W, eps=1e-7).λ # compute weighted theta 133.57806623525727 julia> opt2 = dsw_via_complement(complement(S), W, eps=1e-7).λ # compute weighted θ via the complement graph, using theorem 29 of arxiv:2101.00162. 133.57806730600717 julia> abs(opt1 - opt2) / abs(opt1 + opt2) < 1e-6 true ```
NoncommutativeGraphs
https://github.com/dstahlke/NoncommutativeGraphs.jl.git
[ "MIT" ]
0.1.1
72e4eeb7ecb32cb134bfde2b4f7686eb816cc0c7
docs
87
Reference ========= ```@autodocs Modules = [NoncommutativeGraphs] Private = false ```
NoncommutativeGraphs
https://github.com/dstahlke/NoncommutativeGraphs.jl.git
[ "MIT" ]
1.0.0
f8b7fb25ab3b0691ebb1c5fadab4bbaa167eb156
code
18113
module BlockEnums import Core.Intrinsics.bitcast export BlockEnum, @blockenum, add!, @add, blocklength, setblocklength!, getmodule, namemap, numblocks, addblocks!, add_in_block!, maxvalind, @addinblock, blockindex, basetype, blockrange, inblock, gtblock, geblock, ltblock, leblock """ namemap(::Type{<:BlockEnum}) Return the `Dict` mapping all values to name symbols. Perhaps this should not be advertized or exposed. """ function namemap end namemap(arg::Any) = throw(MethodError(namemap, (arg,))) """ getmodule(t::Type{<:BlockEnum}) Get the module in which `t` is defined. """ function getmodule end """ blocklength(t::Type{<:BlockEnum}) Get the length of blocks that the range of values of `t` is partitioned into. """ function blocklength end """ blockindex(v::BlockEnum) Get the index of the block of values `v` belongs to. """ function blockindex end """ setblocklength!(t::Type{<:BlockEnum}, block_length) Set the length of each block in the partition of the values of `t`. This can only be called once. In order to use the blocks you must first set up bookkeeping by calling `addblocks!`. These blocks are called "active". """ function setblocklength! end """ numblocks(t::Type{<:BlockEnum{T}}) where T <: Integer Return the number of blocks for which bookkeeping has been set up. The set of values of `t` is the nonzero values of `T`, which is typically very large. Bookkeeping of blocks requires storage. So you can only set up some of the blocks for use. """ function numblocks end """ addblocks!(t::Type{<:BlockEnum}), nblocks::Integer) Add and initialize `nblocks` blocks to the bookkeeping for `t`. The number of active blocks for the type is returned. """ function addblocks! end """ compact_show(t::Type{<:BlockEnum}) Return `true` if compact show was set when `t` was defined. This omits printing the corresponding integer when printing. To enable compact show, include the key/val pair `compactshow=true` when defining `t`. """ function compact_show end """ maxvalind(t::Type{<:BlockEnum}, block_num::Integer) Return the largest index for which a name has been assigned in the `block_num`th block `t`. This number is constrained to be within the values in the block. """ function maxvalind end function _incrmaxvalind! end function blocklength1 end """ BlockEnum{T<:Integer} The abstract supertype of all enumerated types defined with [`@blockenum`](@ref). """ abstract type BlockEnum{T<:Integer} end """ basetype(V::Type{<:BlockEnum{T}}) Return `T`, which is the bitstype whose values are bitcast to the type `V`. This is the type of the value returned by `Integer(x::V)`. The type is in a sense the underlying type of `V`. """ basetype(::Type{<:BlockEnum{T}}) where {T<:Integer} = T """ val(x::BlockEnum{T}) Return `x` bitcast to type `T`. """ val(x::BlockEnum{T}) where T = bitcast(T, x) (::Type{T})(x::BlockEnum{T2}) where {T<:Integer,T2<:Integer} = T(bitcast(T2, x))::T Base.cconvert(::Type{T}, x::BlockEnum{T2}) where {T<:Integer,T2<:Integer} = T(x) Base.write(io::IO, x::BlockEnum{T}) where {T<:Integer} = write(io, T(x)) Base.read(io::IO, ::Type{T}) where {T<:BlockEnum} = T(read(io, basetype(T))) Base.isless(x::T, y::T) where {T<:BlockEnum} = isless(basetype(T)(x), basetype(T)(y)) Base.Symbol(x::BlockEnum)::Symbol = _symbol(x) Base.length(t::Type{<:BlockEnum}) = length(namemap(t)) Base.typemin(t::Type{<:BlockEnum}) = minimum(keys(namemap(t))) Base.typemax(t::Type{<:BlockEnum}) = maximum(keys(namemap(t))) """ instances(t::Type{<:BlockEnum}) Return a `Tuple` of all of the named values of `t`. """ Base.instances(t::Type{<:BlockEnum}) = (sort!(Any[t(v) for v in keys(namemap(t))])...,) """ blockrange(t::Type{<:BlockEnum}, blockind) Return the range of values of `t` in block number `blockind`. """ function blockrange(t::Type{<:BlockEnum}, blockind) _blockind = Integer(blockind) (_blockind <= numblocks(t) && _blockind >= 1) || throw(ArgumentError("Block index $blockind is out of bounds")) blen = BlockEnums.blocklength(t) start = blen * (_blockind - 1) + 1 stop = blen * _blockind return start:stop end function inblock(el::BlockEnum, blockind) return BlockEnums.val(el) in blockrange(typeof(el), blockind) end function gtblock(el::BlockEnum, blockind) return BlockEnums.val(el) > last(blockrange(typeof(el), blockind)) end function ltblock(el::BlockEnum, blockind) return BlockEnums.val(el) < first(blockrange(typeof(el), blockind)) end function geblock(el::BlockEnum, blockind) return BlockEnums.val(el) >= first(blockrange(typeof(el), blockind)) end function leblock(el::BlockEnum, blockind) return BlockEnums.val(el) <= last(blockrange(typeof(el), blockind)) end function _symbol(x::BlockEnum) names = namemap(typeof(x)) x = Integer(x) get(() -> Symbol("<invalid #$x>"), names, x)::Symbol end Base.print(io::IO, x::BlockEnum) = print(io, _symbol(x)) function Base.show(io::IO, x::BlockEnum) sym = _symbol(x) if !(get(io, :compact, false)::Bool) from = get(io, :module, Main) def = typeof(x).name.module if from === nothing || !Base.isvisible(sym, def, from) show(io, def) print(io, ".") end end print(io, sym) end function Base.show(io::IO, ::MIME"text/plain", x::BlockEnum) print(io, x, "::") show(IOContext(io, :compact => true), typeof(x)) compact_show(typeof(x)) && return print(io, " = ") show(io, Integer(x)) end function Base.show(io::IO, m::MIME"text/plain", t::Type{<:BlockEnum}) if isconcretetype(t) print(io, "BlockEnum ") Base.show_datatype(io, t) print(io, ":") for x in instances(t) print(io, "\n", Symbol(x), " = ") show(io, Integer(x)) end else invoke(show, Tuple{IO, MIME"text/plain", Type}, io, m, t) end end # give BlockEnum types scalar behavior in broadcasting Base.broadcastable(x::BlockEnum) = Ref(x) @noinline enum_argument_error(typename, x) = throw(ArgumentError(string("invalid value for BlockEnum $(typename): $x"))) # Following values of `s` and what is returned # `syname` returns (:syname, nothing) # `syname = 3` returns `(:syname, 3)` # `s` a LineNumberNode returns `(nothing, nothing)` function _sym_and_number(typename, _module, basetype, s) s isa LineNumberNode && return (nothing, nothing) if isa(s, Symbol) i = nothing elseif isa(s, Expr) && # For example `a = 1` (s.head === :(=) || s.head === :kw) && # IIRC may be :(=) or :kw depending on Julia version length(s.args) == 2 && isa(s.args[1], Symbol) i = Core.eval(_module, s.args[2]) # allow exprs, e.g. uint128"1" if !isa(i, Integer) throw(ArgumentError("invalid value for BlockEnum $typename, $s; values must be integers")) end i = convert(basetype, i) s = s.args[1] # Set `s` to just the symbol else throw(ArgumentError(string("invalid argument for BlockEnum ", typename, ": ", s))) end if !Base.isidentifier(s) throw(ArgumentError("invalid name for BlockEnum $typename; \"$s\" is not a valid identifier")) end return (s, i) end function _check_begin_block(syms) if length(syms) == 1 && syms[1] isa Expr && syms[1].head === :block syms = syms[1].args end return syms end function _parse_block_length(blen) isa(blen, Integer) && return blen isa(blen, Expr) || throw(ArgumentError("blocklength must be an Integer or an expression.")) args = blen.args if blen.head === :call && length(args) == 3 && args[1] === :(^) && isa(args[2], Int) && isa(args[3], Int) return args[2] ^ args[3] else throw(ArgumentError("Invalid expression for blocklength $(blen)")) end end """ @blockenum BlockEnumName[::BaseType] value1[=x] value2[=y] Create an `BlockEnum{BaseType}` subtype with name `BlockEnumName` and enum member values of `value1` and `value2` with optional assigned values of `x` and `y`, respectively. `BlockEnumName` can be used just like other types and enum member values as regular values, such as # Examples ```jldoctest fruitenum julia> @blockenum Fruit apple=1 orange=2 kiwi=3 julia> f(x::Fruit) = "I'm a Fruit with value: \$(Int(x))" f (generic function with 1 method) julia> f(apple) "I'm a Fruit with value: 1" julia> Fruit(1) apple::Fruit = 1 ``` Values can also be specified inside a `begin` block, e.g. ```julia @blockenum BlockEnumName begin value1 value2 end ``` `BaseType`, which defaults to [`Int32`](@ref), must be a primitive subtype of `Integer`. Member values can be converted between the enum type and `BaseType`. `read` and `write` perform these conversions automatically. In case the enum is created with a non-default `BaseType`, `Integer(value1)` will return the integer `value1` with the type `BaseType`. To list all the instances of an enum use `instances`, e.g. ```jldoctest fruitenum julia> instances(Fruit) (apple, orange, kiwi) ``` It is possible to construct a symbol from an enum instance: ```jldoctest fruitenum julia> Symbol(apple) :apple ``` """ macro blockenum(T0::Union{Symbol,Expr}, syms...) local modname = :nothing # Default, do not create a new module. Use module that is in scope. local typename local _blocklength::Int = 0 local init_num_blocks::Int = 0 _compact_show=false if isa(T0, Expr) && T0.head === :tuple # (modulename, blockenumname) length(T0.args) >= 1 || throw(ArgumentError("If first argument is a Tuple, it must have at least one element")) T = T0.args[1] # `T` is the name of the new subtype of BlockEnum for i in 2:lastindex(T0.args) expr = T0.args[i] (isa(expr, Expr) && expr.head === :(=)) || throw(ArgumentError(string("Expecting `=` expression as $(i)th item in init tuple."))) (keyw, val) = (expr.args[1], expr.args[2]) if keyw === :blocklength _blocklength = _parse_block_length(val) elseif keyw === :mod # Symbols in this module. TODO, how to allow :module here? It is recognized as Julia reserved word modname = val elseif keyw === :numblocks init_num_blocks = val elseif keyw === :compactshow _compact_show = val else throw(ArgumentError(string("Unexpected keyword $(expr.args[1])"))) end end else T = T0 end if init_num_blocks > 0 && ! (_blocklength > 0) throw(ArgumentError(string("If numblocks is set then blocklength must be set."))) end basetype = Int32 # default. We may change this below. typename = T if isa(T, Expr) && T.head === :(::) && length(T.args) == 2 && isa(T.args[1], Symbol) typename = T.args[1] basetype = Core.eval(__module__, T.args[2]) if !isa(basetype, DataType) || !(basetype <: Integer) || !isbitstype(basetype) throw(ArgumentError("invalid base type for BlockEnum $typename, $T=::$basetype; base type must be an integer primitive type")) end elseif !isa(T, Symbol) throw(ArgumentError("invalid type expression for enum $T")) end # The new subtype of BlockEnum is now `typename`. No longer use `T`. T = nothing # Do this to signal intent and uncover bugs values = Vector{basetype}() seen = Set{Symbol}() namemap = Dict{basetype,Symbol}() block_max_ind = Vector{Int}(undef, init_num_blocks) for i in 1:init_num_blocks block_max_ind[i] = (i - 1) * _blocklength end lo = hi = 0 i = zero(basetype) hasexpr = false # Symbols (and their values if present) may be wrapped in `begin`, `end` syms = _check_begin_block(syms) for s in syms (s, _i) = _sym_and_number(typename, __module__, basetype, s) s === nothing && continue # Got a LineNumberNode if _i === nothing && i == typemin(basetype) && !isempty(values) throw(ArgumentError("overflow in value \"$s\" of BlockEnum $typename")) end if _i !== nothing hasexpr = true i = _i end s = s::Symbol if hasexpr && haskey(namemap, i) throw(ArgumentError("both $s and $(namemap[i]) have value $i in BlockEnum $typename; values must be unique")) end namemap[i] = s push!(values, i) if s in seen throw(ArgumentError("name \"$s\" in BlockEnum $typename is not unique")) end push!(seen, s) if length(values) == 1 lo = hi = i else lo = min(lo, i) hi = max(hi, i) end i += oneunit(i) end blk = quote # enum definition Base.@__doc__(primitive type $(esc(typename)) <: BlockEnum{$(basetype)} $(sizeof(basetype) * 8) end) function $(esc(typename))(x::Integer) if x > typemax($basetype) || x < typemin($basetype) enum_argument_error($(Expr(:quote, typename)), x) end return bitcast($(esc(typename)), convert($(basetype), x)) end BlockEnums.namemap(::Type{$(esc(typename))}) = $(esc(namemap)) BlockEnums.blocklength(::Type{$(esc(typename))}) = $(esc(_blocklength)) BlockEnums.numblocks(::Type{$(esc(typename))}) = length($(esc(block_max_ind))) function BlockEnums.addblocks!(::Type{$(esc(typename))}, n::Integer) blklen = $(esc(_blocklength)) if iszero(blklen) throw(ArgumentError("This BlockEnum was not initialized with blocks.")) end bmaxind = $(esc(block_max_ind)) curlen = length(bmaxind) resize!(bmaxind, curlen + n) for i in (curlen + 1):(curlen + n) bmaxind[i] = (i - 1) * blklen end return length(bmaxind) end function BlockEnums.maxvalind(::Type{$(esc(typename))}, block::Integer) return $(esc(block_max_ind))[block] end function BlockEnums._incrmaxvalind!(::Type{$(esc(typename))}, block::Integer) mbi = $(esc(block_max_ind)) mbi[block] += 1 return return mbi[block] end function BlockEnums.blockindex(x::$(esc(typename))) $(esc(_blocklength)) > 0 || return 0 blknum = div(Int(x), $(esc(_blocklength)), RoundUp) return blknum end function BlockEnums.compact_show(::Type{$(esc(typename))}) return $(esc(_compact_show)) end # JET complains about the fallback calls to array_subpadding when calling # reinterpret(basetype, ::Vector{typename}). So we define these. Base.array_subpadding(::Type{$(esc(typename))}, ::Type{$basetype}) = true Base.array_subpadding(::Type{$basetype}, ::Type{$(esc(typename))}) = true end @show __module__ if isa(typename, Symbol) if modname !== :nothing push!(blk.args, :(module $(esc(modname)); end)) else modname = __module__ end push!(blk.args, :(BlockEnums.getmodule(::Type{$(esc(typename))}) = $(esc(modname)))) push!(blk.args, :(BlockEnums._bind_vars($(esc(typename))))) end push!(blk.args, :nothing) blk.head = :toplevel return blk end function _bind_vars(etype) for (i, sym) in namemap(etype) _bind_var(getmodule(etype), sym, etype(i)) end end _bind_var(mod, sym, instance) = mod.eval(:(const $sym = $instance; export $sym)) function add!(a, syms...) nmap = BlockEnums.namemap(a) nextnum = length(a) == 0 ? 0 : maximum(keys(nmap)) + 1 local na _module = getmodule(a) count_assigned = 0 for sym in syms (sym, _i) = _sym_and_number(Symbol(a), _module, basetype(a), sym) sym in values(nmap) && throw(ArgumentError("Key $sym already defined in $a.")) if _i !== nothing nextnum = _i end na = a(nextnum) nmap[nextnum] = sym _bind_var(_module, sym, na) nextnum += 1 count_assigned += 1 end if iszero(count_assigned) throw(ArgumentError("No symbols defined in enum!")) end return na end function _get_qsyms(syms) syms = _check_begin_block(syms) return (QuoteNode(sym) for sym in syms if ! isa(sym, LineNumberNode)) end macro add(a, syms...) qsyms = _get_qsyms(syms) :(BlockEnums.add!($(esc(a)), $(qsyms...))) end function add_in_block!(a, _block::Union{Integer, BlockEnum}, syms...) block = Int(_block) nmap = BlockEnums.namemap(a) nextnum = maxvalind(a, block) + 1 local na _module = getmodule(a) for sym in syms blocklim = blocklength(a) * block if nextnum > blocklim throw(ArgumentError("Attempting to set enum value above block limit $blocklim")) end (sym, _i) = _sym_and_number(Symbol(a), _module, basetype(a), sym) sym in values(nmap) && throw(ArgumentError("Key $sym already defined in $a.")) if _i !== nothing throw(ArgumentError("Setting number explicitly not allowed in block mode.")) end na = a(nextnum) nmap[nextnum] = sym _bind_var(_module, sym, na) nextnum += 1 _incrmaxvalind!(a, block) end return na end macro addinblock(a, block, syms...) qsyms = _get_qsyms(syms) :(BlockEnums.add_in_block!($(esc(a)), $(esc(block)), $(qsyms...))) end # Since we don't guarantee continguous values of instances, this does not work # It is taken from the code for Enum # generate code to test whether expr is in the given set of values # function membershiptest(expr, values) # lo, hi = extrema(values) # if length(values) == hi - lo + 1 # :($lo <= $expr <= $hi) # elseif length(values) < 20 # foldl((x1,x2)->:($x1 || ($expr == $x2)), values[2:end]; init=:($expr == $(values[1]))) # else # :($expr in $(Set(values))) # end # end end # module BlockEnums
BlockEnums
https://github.com/jlapeyre/BlockEnums.jl.git
[ "MIT" ]
1.0.0
f8b7fb25ab3b0691ebb1c5fadab4bbaa167eb156
code
376
using BlockEnums using BlockEnums: blocklength, setblocklength!, numblocks, addblocks!, maxvalind, @addinblock, blockindex, blockrange, inblock, ltblock, gtblock, leblock, geblock using Test @static if Base.VERSION >= v"1.7" if get(ENV,"BLOCKENUMS_JET_TEST","")=="true" include("test_jet.jl") end end include("test_aqua.jl") include("test_blockenums.jl")
BlockEnums
https://github.com/jlapeyre/BlockEnums.jl.git
[ "MIT" ]
1.0.0
f8b7fb25ab3b0691ebb1c5fadab4bbaa167eb156
code
701
using BlockEnums using Aqua: Aqua @testset "aqua unbound_args" begin Aqua.test_unbound_args(BlockEnums) end @testset "aqua undefined exports" begin Aqua.test_undefined_exports(BlockEnums) end @testset "aqua test ambiguities" begin Aqua.test_ambiguities([BlockEnums, Core, Base]) end @testset "aqua piracy" begin Aqua.test_piracy(BlockEnums) end @testset "aqua project extras" begin Aqua.test_project_extras(BlockEnums) end @testset "aqua state deps" begin Aqua.test_stale_deps(BlockEnums) end @testset "aqua deps compat" begin Aqua.test_deps_compat(BlockEnums) end @testset "aqua project toml formatting" begin Aqua.test_project_toml_formatting(BlockEnums) end
BlockEnums
https://github.com/jlapeyre/BlockEnums.jl.git
[ "MIT" ]
1.0.0
f8b7fb25ab3b0691ebb1c5fadab4bbaa167eb156
code
3245
module Wrap1 using BlockEnums: @blockenum @blockenum A3 a3 b3 c3 @blockenum (A4, mod=A4mod) a4 b4 end # module Wrap1 # JET does not like this reinterpret. But JET does not # examine this code. @testset "reinterpret" begin @blockenum ZZ zz1 zz2 zz3 v1 = [zz1, zz2, zz3] v2 = reinterpret(BlockEnums.basetype(ZZ), v1) @test eltype(v2) === BlockEnums.basetype(ZZ) @test all(x->isa(x, BlockEnums.basetype(ZZ)), v2) end @testset "blocks" begin @blockenum (Z, blocklength=3) @test numblocks(Z) == 0 @test blocklength(Z) == 3 addblocks!(Z, 10) @test numblocks(Z) == 10 addblocks!(Z, 10) @test numblocks(Z) == 20 @test maxvalind(Z, 1) == 0 @test maxvalind(Z, 2) == 3 @addinblock Z 1 a b c @test_throws ArgumentError @addinblock Z 1 d @addinblock Z 2 x y z @test maxvalind(Z, 1) == 3 @test maxvalind(Z, 2) == 6 @test blockindex(a) == 1 @test blockindex(x) == 2 @test inblock(x, 2) @test inblock(z, 2) @test ! inblock(z, 1) @test inblock(a, 1) @test blockrange(Z, 2) === 4:6 @test ltblock(a, 2) @test leblock(a, 2) @test leblock(z, 2) @test geblock(a, 1) @test geblock(z, 1) @test leblock(a, 1) @test ! leblock(z, 1) @blockenum ZZ @test_throws ArgumentError addblocks!(ZZ, 5) @blockenum (YY, blocklength=10^6) @test blocklength(YY) == 1000000 end @testset "BlockEnums.jl" begin @blockenum A1 a1 b1 c1 @test Int.((a1, b1, c1)) == (0, 1, 2) @test BlockEnums.val.((a1, b1, c1)) == (0, 1, 2) @test A1(1) == b1 @test length(A1) == 3 @test Base.cconvert(Int, a1) === Int(a1) @test instances(A1) == (a1, b1, c1) @test BlockEnums.getmodule(A1) == Main # Base.Enum will throw an error with the following @test Integer(A1(111)) == 111 @test isless(a1, b1) @test a1 < b1 @test basetype(A1) == Int32 @blockenum A1_64::Int64 @test basetype(A1_64) == Int64 @blockenum (A2, mod=A2mod) a2 b2 c2 @test Int.((A2mod.a2, A2mod.b2, A2mod.c2)) == (0, 1, 2) @test_throws UndefVarError a2 == 0 @test BlockEnums.getmodule(A2) == A2mod @test Int(Wrap1.a3) == 0 @test_throws UndefVarError a3 == 0 @test Int(Wrap1.A4mod.b4) == 1 @test_throws UndefVarError Wrap1.b4 == 0 @test_throws UndefVarError b4 == 0 @test BlockEnums.getmodule(Wrap1.A4) == Wrap1.A4mod @add A1 z1 y1 @test Int(z1) == 3 @add A2 z2 y2 @test Int(A2mod.z2) == 3 @add Wrap1.A3 z3 @test Int(Wrap1.z3) == 3 @test Wrap1.A3(3) == Wrap1.z3 @add Wrap1.A4 z4 @test Int(Wrap1.A4mod.z4) == 2 @test Wrap1.A4(2) == Wrap1.A4mod.z4 # This *is* how we want scoping to work. @test instances(Wrap1.A4) == (Wrap1.A4mod.a4, Wrap1.A4mod.b4, Wrap1.A4mod.z4) @test_throws ArgumentError @add A1 z1 @blockenum (A5, mod=A5mod) a5=2 b5=3 c5 @test Int(A5mod.c5) == 4 @add A5 d5 e5=11 f5 @test Int(A5mod.d5) == 5 @test Int(A5mod.e5) == 11 @test Int(A5mod.f5) == 12 @test_throws ArgumentError add!(A5, Symbol("1q")) @blockenum A6 begin a6 b6 c6 end @test Int(c6) == 2 @blockenum A7 begin a7 = 10 b7 c7 end @test Int(c7) == 12 end
BlockEnums
https://github.com/jlapeyre/BlockEnums.jl.git
[ "MIT" ]
1.0.0
f8b7fb25ab3b0691ebb1c5fadab4bbaa167eb156
code
1232
# Borrowed from QuantumOpticsBase using Test using BlockEnums using JET using JET: ReportPass, BasicPass, InferenceErrorReport, UncaughtExceptionReport # Custom report pass that ignores `UncaughtExceptionReport` # Too coarse currently, but it serves to ignore the various # "may throw" messages for runtime errors we raise on purpose # (mostly on malformed user input) struct MayThrowIsOk <: ReportPass end # ignores `UncaughtExceptionReport` analyzed by `JETAnalyzer` (::MayThrowIsOk)(::Type{UncaughtExceptionReport}, @nospecialize(_...)) = return # forward to `BasicPass` for everything else function (::MayThrowIsOk)(report_type::Type{<:InferenceErrorReport}, @nospecialize(args...)) BasicPass()(report_type, args...) end @testset "jet single calls" begin @blockenum XX xx1 xx2 v = [xx1, xx2] result = @report_call reinterpret(BlockEnums.basetype(XX), v) @show result @test length(JET.get_reports(result)) == 0 end @testset "jet on package" begin rep = report_package( "BlockEnums"; report_pass=MayThrowIsOk(), # TODO have something more fine grained than a generic "do not care about thrown errors" ) @show rep @test length(JET.get_reports(rep)) == 0 end # testset
BlockEnums
https://github.com/jlapeyre/BlockEnums.jl.git
[ "MIT" ]
1.0.0
f8b7fb25ab3b0691ebb1c5fadab4bbaa167eb156
docs
2250
# BlockEnums [![Build Status](https://github.com/jlapeyre/BlockEnums.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/jlapeyre/BlockEnums.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/jlapeyre/BlockEnums.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/jlapeyre/BlockEnums.jl) [![Aqua QA](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl) [![JET QA](https://img.shields.io/badge/JET.jl-%E2%9C%88%EF%B8%8F-%23aa4444)](https://github.com/aviatesk/JET.jl) <!-- [![deps](https://juliahub.com/docs/BlockEnums/deps.svg)](https://juliahub.com/ui/Packages/BlockEnums/2Dg1l?t=2) --> <!-- [![version](https://juliahub.com/docs/BlockEnums/version.svg)](https://juliahub.com/ui/Packages/BlockEnums/2Dg1l) --> BlockEnums is like the built-in Enums. The main differences are * Enumerated types are mutable in the sense that instances may be added after the type is created. * The enumeration may be partitioned into blocks of values. For example `@addinblock A 2 x` would add the instance `x` to type `A` in the second block of indices. ```julia julia> using BlockEnums julia> @blockenum Fruit apple banana julia> Fruit BlockEnum Fruit: apple = 0 banana = 1 julia> @add Fruit pear pear::Fruit = 2 julia> Fruit BlockEnum Fruit: apple = 0 pear = 2 banana = 1 ``` Some block features ```julia julia> using BlockEnums julia> @blockenum (Myenum, mod=MyenumMod, blocklength=100, numblocks=10, compactshow=false) julia> @addinblock Myenum 1 a b c c::Myenum = 3 julia> @addinblock Myenum 3 x y z z::Myenum = 203 julia> BlockEnums.blockindex(MyenumMod.y) 3 ``` ### Methods for functions in `Base` Methods for the following functions in `Base` are defined and follow the established semantics. * `cconvert` * `write`, converts to the underlying bitstype before writing. * `read` , reads a value from the bitstype and converts to the `BlockEnum` * `isless` * `Symbol` * `length` * `typemin`, `typemax` These are the min and max of values with names bound to them. * `instances` * `print` ### Testing BlockEnums passes [JET.jl](https://github.com/aviatesk/JET.jl) and [Aqua.jl](https://github.com/JuliaTesting/Aqua.jl) tests.
BlockEnums
https://github.com/jlapeyre/BlockEnums.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
566
using Documenter using GilaElectromagnetics push!(LOAD_PATH,"../src/") makedocs(sitename="GilaElectromagnetics.jl Documentation", pages = [ "Index" => "index.md", "An other page" => "docIndex.md", ], format = Documenter.HTML(prettyurls = false) ) # Documenter can also automatically deploy documentation to gh-pages. # See "Hosting Documentation" and deploydocs() in the Documenter manual # for more information. deploydocs( repo = "github.com/moleskySean/GilaElectromagnetics.jl.git", devbranch = "main" )
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
4029
""" GilaElectromagnetics implements single (complex) frequency electromagnetic Green functions between generalized source and target cuboid ``volumes''. Technical details are available in the supporting document files. Author: Sean Molesky Distribution: The code distributed under GNU LGPL. """ module GilaElectromagnetics using AbstractFFTs, FFTW, LinearAlgebra, FastGaussQuadrature, Cubature, CUDA, Base.Threads, ThreadsX #= glaMem defines the memory structures used in Gila. exported definitions -------------------- GlaVol---basic cuboid memory: relative cell number and size, grid values, etc. genGlaVol---generator for GlaVol memory structure. GlaKerOpt---hardware options for Green function protocol (egoOpr!), switch between CPU and GPU resources, define number of available compute threads, etc. GlaOprMem---container for the volume interaction elements (as well as internal information) used in computing the Green function interaction between a pair of volumes. GlaOprMem is effectively a stored Green function. GlaOprMem---generate operator memory structure, from a volume or pair of volumes, for use by egoOpr! notable internal definitions ---------------------------- GlaExtInf---memory structure for translating between distinct grid layouts. glaVolEveGen---regenerate and scale a GlaVol to have even number of cells. =# include("glaMem.jl") export GlaVol, GlaKerOpt, GlaOprMem, GlaExtInf #= glaInt contains support functions for numerical (real space) integration of the cuboid interactions described by the electromagnetic Green function. This code is mostly translated from DIRECTFN_E by Athanasios Polimeridis. Reference: Polimeridis AG, Vipiana F, Mosig JR, Wilton DR. DIRECTFN: Fully numerical algorithms for high precision computation of singular integrals in Galerkin SIE methods. IEEE Transactions on Antennas and Propagation. 2013; 61(6):3112-22. exported definitions -------------------- notable internal definitions ---------------------------- =# include("glaInt.jl") #= glaGen calculates the unique elements of the electromagnetic Green functions, embedded in circulant form, via calls to the code contained in glaInt. Integration tolerances ultimately used by glaInt.jl are introduced in this file. exported definitions -------------------- notable internal definitions ---------------------------- genEgoSlf!---computation of interaction elements for sources within one volume. genEgoExt!---computation of interaction elements between a source and target volume. The source and target volume are allowed to touch and have cell scales that differ by integer factors. =# include("glaGen.jl") #= glaAct contains the package protocol for computing matrix vector products---the action of the electromagnetic Green function on a specified current distribution---for a given volume or pair of volumes. exported definitions -------------------- egoOpr!---given a GlaOprMem structure and source current distribution, yield the resulting electromagnetic fields. GlaOpr---a struct that wraps `egoOpr!` for easy use of the Greens function glaSze---like `size`, but gives the size of the input/output arrays for a GreensOperator in tensor form isadjoint---returns true if the operator is the adjoint of the Greens operator isselfoperator---returns true if the operator is a self operator isexternaloperator---returns true if the operator is an external operator notable internal definitions ---------------------------- =# include("glaAct.jl") export egoOpr!, GlaOpr, glaSze, isadjoint, isselfoperator, isexternaloperator #= glaEgoMat provides direct computation of the dense matrix defined by the electromagnetic Green function in free space. The code is only written for self volumes. glaEgoMat includes glaLinAlg, which allows the Green function to act a matrix for many LinearAlgebra applications. notable internal definitions ---------------------------- genEgoMat---return the dense matrix of a self Green function. =# include("../utl/glaEgoMat.jl") end
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
11602
###MEMORY #= GlaOprMem(cmpInf::GlaKerOpt, trgVol::GlaVol, srcVol::Union{GlaVol,Nothing}=nothing, egoFur::Union{AbstractArray{<:AbstractArray{T}}, Nothing}=nothing)::GlaOprMem where T<:Union{ComplexF64,ComplexF32} Prepare memory for green function operator---when called with a single GlaVol, or identical source and target volumes, the function yields the self green function construction. GlaOpr(celSrc::NTuple{3, Int}, sclSrc::NTuple{3, Rational}, orgSrc::NTuple{3, Rational}, celTrg::NTuple{3, Int}, sclTrg::NTuple{3, Rational}, orgTrg::NTuple{3, Rational}; useGpu::Bool=false, setType::DataType=ComplexF64) Construct an external Green's operator. =# include("glaMemSup.jl") ###PROCEDURE """ egoOpr!(egoMem::GlaOprMem, actVec::AbstractArray{T})::AbstractArray{T} where T<:Union{ComplexF64,ComplexF32} Applies the electric Green function to actVec (current), returning the output field. actVec is internally modified by egoOpr! to reduce needed allocation. """ #= egoOpr! has no internal check for NaN entries---checks are done by GlaOprMem. =# function egoOpr!(egoMem::GlaOprMem, actVec::AbstractArray{T})::AbstractArray{T} where T<:Union{ComplexF64,ComplexF32} # check that actVec is the correct size if (egoMem.mixInf.srcCel..., 3) == size(actVec) # device execution if prod(egoMem.cmpInf.devMod) return egoBrnDev!(egoMem, 0, 0, actVec) else return egoBrnHst!(egoMem, 0, 0, actVec) end else error("Size of input vector does not match size of source volume. Required data layout is (srcCelX, srcCelY, srcCelZ, 3).") return actVec end end # Support functions for operator action include("glaActSup.jl") """ egoBrnHst!(egoMem::GlaOprMem, lvl::Integer, bId::Integer, actVec::AbstractArray{T})::AbstractArray{T} where T<:Union{ComplexF64,ComplexF32} Head branching function implementing Green function action on host. """ function egoBrnHst!(egoMem::GlaOprMem, lvl::Integer, bId::Integer, actVec::AbstractArray{T})::AbstractArray{T} where T<:Union{ComplexF64,ComplexF32} # generate branch pair to initiate operator # size of circulant vector brnSze = div.(egoMem.mixInf.trgCel .+ egoMem.mixInf.srcCel, 2) # number of source partitions parNumSrc = prod(egoMem.mixInf.srcDiv) # number of target partitions parNumTrg = prod(egoMem.mixInf.trgDiv) # if necessary, reshape source vector into partitions if lvl == 0 && sum(egoMem.mixInf.srcCel .!= size(actVec)[1:3]) > 0 # reshape current vector # orgVec and actVec share the same underlying data orgVec = genPrtHst(egoMem.mixInf, egoMem.cmpInf, parNumSrc, actVec) elseif lvl == 0 orgVec = reshape(actVec, egoMem.mixInf.srcCel..., 3, parNumSrc) else # partitions have been created, simply rename memory orgVec = actVec end # perform forward Fourier transform if lvl > 0 # forward FFT # possibility of changing vector size accounted for in FFT plans egoMem.fftPlnFwd[lvl] * orgVec end # split branch if lvl < length(egoMem.dimInf) # check if size of current active vector dimension is compatible if size(orgVec)[lvl + 1] == brnSze[lvl + 1] prgVec = similar(orgVec) # split branch: perform phase shift sptBrnHst!(size(orgVec)[1:3], prgVec, lvl + 1, egoMem.phzInf[lvl + 1], parNumSrc, orgVec, egoMem.cmpInf) # rename vectors for consistent convention with general branching prgVecEve = orgVec prgVecOdd = prgVec # size of progeny vectors must be changed else # current and progeny vector sizes curSze = size(orgVec) prgSze = ntuple(x -> x == (lvl + 1) ? brnSze[x] : curSze[x], 3) # allocate progeny vectors prgVecEve = Array{eltype(orgVec)}(undef, prgSze..., 3, parNumSrc) prgVecOdd = Array{eltype(orgVec)}(undef, prgSze..., 3, parNumSrc) # memory previously associated with orgVec is freed internally sptBrnHst!(prgVecEve, prgVecOdd, lvl + 1, egoMem.phzInf[lvl + 1], egoMem.mixInf, parNumSrc, orgVec, egoMem.cmpInf) end end # branch until depth of block structure if lvl < length(egoMem.dimInf) # !create external handles for sync---!not sure why this is needed! eveVec = prgVecEve oddVec = prgVecOdd # execute split branches---!asynchronous CPU is fine + some speed up! @sync begin # origin branch Base.Threads.@spawn eveVec = egoBrnHst!(egoMem, lvl + 1, bId, prgVecEve) # phase modified branch Base.Threads.@spawn oddVec = egoBrnHst!(egoMem, lvl + 1, nxtBrnId(length(egoMem.dimInf), lvl, bId), prgVecOdd) end # check if size of vector must change on merge if size(eveVec)[lvl + 1] == egoMem.mixInf.trgCel[lvl + 1] # merge branches, includes phase operation and stream sync mrgBrnHst!(egoMem.mixInf, eveVec, lvl + 1, parNumTrg, egoMem.phzInf[lvl + 1], oddVec, egoMem.cmpInf) # rename eveVec to match return name used elsewhere retVec = eveVec # merge and resize else # size of current vector curSze = size(eveVec) # size of cartesian indices of merged vector mrgSze = ntuple(x -> x == (lvl + 1) ? egoMem.mixInf.trgCel[x] : curSze[x], 3) # allocate memory for merge if sum(egoMem.cmpInf.devMod) == true retVec = CuArray{eltype(eveVec)}(undef, mrgSze..., 3, parNumTrg) else retVec = Array{eltype(eveVec)}(undef, mrgSze..., 3, parNumTrg) end # merge branches, even and odd vectors are freed, stream synced mrgBrnHst!(egoMem.mixInf, retVec, lvl + 1, parNumTrg, egoMem.phzInf[lvl + 1], eveVec, oddVec, egoMem.cmpInf) end else retVec = zeros(eltype(orgVec), brnSze..., 3, parNumTrg) # multiply by Toeplitz vector, avoid race condition DO NOT SPAWN! for trgItr in eachindex(1:parNumTrg) for srcItr in eachindex(1:parNumSrc) mulBrnHst!(egoMem.mixInf, bId, selectdim(retVec, 5, trgItr), view(egoMem.egoFur[bId + 1], :, :, :, :, srcItr, trgItr), selectdim(orgVec, 5, srcItr), egoMem.cmpInf) end end end # perform reverse Fourier transform if lvl > 0 # inverse FFT # possibility of changing vector size accounted for in FFT plans egoMem.fftPlnRev[lvl] * retVec end # terminate task and return control to previous level # zero level return if lvl == 0 # check if there are partitions that need to be merged if parNumTrg == 1 return reshape(retVec, egoMem.mixInf.trgCel..., 3) else return mrgPrtHst(egoMem.mixInf, egoMem.cmpInf, parNumTrg, retVec) end end return retVec end """ egoBrnDev!(egoMem::GlaOprMem, lvl::Integer, bId::Integer, actVec::AbstractArray{T})::AbstractArray{T} where T<:Union{ComplexF64,ComplexF32} Head branching function implementing Green function action on device. """ function egoBrnDev!(egoMem::GlaOprMem, lvl::Integer, bId::Integer, actVec::AbstractArray{T})::AbstractArray{T} where T<:Union{ComplexF64,ComplexF32} # generate branch pair to initiate operator # size of circulant vector brnSze = div.(egoMem.mixInf.trgCel .+ egoMem.mixInf.srcCel, 2) # number of source partitions parNumSrc = prod(egoMem.mixInf.srcDiv) # number of target partitions parNumTrg = prod(egoMem.mixInf.trgDiv) # if necessary, reshape source vector into partitions if lvl == 0 && sum(egoMem.mixInf.srcCel .!= size(actVec)[1:3]) > 0 # reshape current vector # orgVec and actVec share the same underlying data orgVec = genPrtDev(egoMem.mixInf, egoMem.cmpInf, parNumSrc, actVec) elseif lvl == 0 orgVec = reshape(actVec, egoMem.mixInf.srcCel..., 3, parNumSrc) else # partitions have been created, simply rename memory orgVec = actVec end # perform forward Fourier transform if lvl > 0 # forward FFT # possibility of changing vector size accounted for in FFT plans egoMem.fftPlnFwd[lvl] * orgVec # wait for completion of FFT CUDA.synchronize(CUDA.stream()) end # split branch if lvl < length(egoMem.dimInf) # check if size of current active vector dimension is compatible if size(orgVec)[lvl + 1] == brnSze[lvl + 1] prgVec = CuArray{eltype(orgVec)}(undef, size(orgVec)[1:3]..., 3, parNumSrc) # split branch, includes phase operation and stream sync sptBrnDev!(size(orgVec)[1:3], prgVec, lvl + 1, egoMem.phzInf[lvl + 1], parNumSrc, orgVec, egoMem.cmpInf) # rename vectors for consistent convention with general branching prgVecEve = orgVec prgVecOdd = prgVec # size of progeny vectors must be changed else # current and progeny vector sizes curSze = size(orgVec) prgSze = ntuple(x -> x == (lvl + 1) ? brnSze[x] : curSze[x], 3) # allocate progeny vectors prgVecEve = CuArray{eltype(orgVec)}(undef, prgSze..., 3, parNumSrc) prgVecOdd = CuArray{eltype(orgVec)}(undef, prgSze..., 3, parNumSrc) CUDA.synchronize(CUDA.stream()) # memory previously associated with orgVec is freed internally sptBrnDev!(prgVecEve, prgVecOdd, lvl + 1, egoMem.phzInf[lvl + 1], egoMem.mixInf, parNumSrc, orgVec, egoMem.cmpInf) end end # branch until depth of block structure if lvl < length(egoMem.dimInf) # execute split branches---!async causes errors + no speed up! # even branch eveVec = egoBrnDev!(egoMem, lvl + 1, bId, prgVecEve) # !wait for even branch to return, functionality choice! if lvl < length(egoMem.dimInf) - 1 CUDA.synchronize(CUDA.stream()) end # phase modified branch oddVec = egoBrnDev!(egoMem, lvl + 1, nxtBrnId(length(egoMem.dimInf), lvl, bId), prgVecOdd) # check if size of vector must change on merge if size(eveVec)[lvl + 1] == egoMem.mixInf.trgCel[lvl + 1] # merge branches, includes phase operation and stream sync mrgBrnDev!(egoMem.mixInf, eveVec, lvl + 1, parNumTrg, egoMem.phzInf[lvl + 1], oddVec, egoMem.cmpInf) # rename eveVec to match return name used elsewhere retVec = eveVec # merge and resize else # size of current vector curSze = size(eveVec) # size of cartesian indices of merged vector mrgSze = ntuple(x -> x == (lvl + 1) ? egoMem.mixInf.trgCel[x] : curSze[x], 3) # allocate memory for merge if sum(egoMem.cmpInf.devMod) == true retVec = CuArray{eltype(eveVec)}(undef, mrgSze..., 3, parNumTrg) else retVec = Array{eltype(eveVec)}(undef, mrgSze..., 3, parNumTrg) end # merge branches, even and odd vectors are freed, stream synced mrgBrnDev!(egoMem.mixInf, retVec, lvl + 1, parNumTrg, egoMem.phzInf[lvl + 1], eveVec, oddVec, egoMem.cmpInf) end else retVec = CUDA.zeros(eltype(orgVec), brnSze..., 3, parNumTrg) CUDA.synchronize(CUDA.stream()) # multiply by Toeplitz vector, avoid race condition DO NOT SPAWN! for trgItr in eachindex(1:parNumTrg) for srcItr in eachindex(1:parNumSrc) # CUDA stream is synchronized inside mulBrn! mulBrnDev!(egoMem.mixInf, bId, selectdim(retVec, 5, trgItr), view(egoMem.egoFur[bId + 1], :, :, :, :, srcItr, trgItr), selectdim(orgVec, 5, srcItr), egoMem.cmpInf) end end # free orgVec CUDA.synchronize(CUDA.stream()) CUDA.unsafe_free!(orgVec) CUDA.synchronize(CUDA.stream()) end # perform reverse Fourier transform if lvl > 0 # inverse FFT # possibility of changing vector size accounted for in FFT plans egoMem.fftPlnRev[lvl] * retVec CUDA.synchronize(CUDA.stream()) end # terminate task and return control to previous level CUDA.synchronize(CUDA.stream()) # zero level return if lvl == 0 # check if there are partitions that need to be merged if parNumTrg == 1 return reshape(retVec, egoMem.mixInf.trgCel..., 3) else return mrgPrtDev(egoMem.mixInf, egoMem.cmpInf, parNumTrg, retVec) end end return retVec end ###INTEGRATION #= Basic linear algebra definitions for egoOpr, allowing integration and simplified use. =# include("glaLinAlg.jl")
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
36249
#= restructure input vector to match partitioned Green function data =# function genPrtHst(mixInf::GlaExtInf, cmpInf::GlaKerOpt, parNum::Integer, actVec::AbstractArray{T,4})::AbstractArray{T,5} where T<:Union{ComplexF64,ComplexF32} # create partitioned vector orgVec = Array{eltype(actVec)}(undef, mixInf.srcCel..., 3, parNum) # break into partitions @threads for itr ∈ CartesianIndices(orgVec) # copy partition data @inbounds orgVec[itr] = actVec[CartesianIndex((Tuple(itr)[1:3] .- (1,1,1)) .* mixInf.srcDiv) + CartesianIndex(1,1,1) + mixInf.srcPar[itr[5]], itr[4]] end return orgVec end #= split into host and device functions to clarify type inference =# function genPrtDev(mixInf::GlaExtInf, cmpInf::GlaKerOpt, parNum::Integer, actVec::AbstractArray{T,4})::AbstractArray{T,5} where T<:Union{ComplexF64,ComplexF32} # memory for partitioned vector orgVec = CuArray{eltype(actVec)}(undef, mixInf.srcCel..., 3, parNum) CUDA.synchronize(CUDA.stream()) # perform partitioning for parItr ∈ eachindex(1:parNum) for dirItr ∈ eachindex(1:3) @cuda threads=cmpInf.numTrd blocks=cmpInf.numBlk genPrtKer!( size(orgVec)[1:3]..., mixInf.srcDiv..., Tuple(mixInf.srcPar[parItr])..., dirItr, parItr, orgVec, actVec) end end # release active vector to reduce memory pressure CUDA.synchronize(CUDA.stream()) CUDA.unsafe_free!(actVec) CUDA.synchronize(CUDA.stream()) return orgVec end #= device source vector partitioning kernel =# function genPrtKer!(maxX::Integer, maxY::Integer, maxZ::Integer, stpX::Integer, stpY::Integer, stpZ::Integer, offX::Integer, offY::Integer, offZ::Integer, dirItr::Integer, parItr::Integer, orgVec::AbstractArray{T,5}, actVec::AbstractArray{T,4})::Nothing where T<:Union{ComplexF64,ComplexF32} # grid strides strX = gridDim().x * blockDim().x strY = gridDim().y * blockDim().y strZ = gridDim().z * blockDim().z # thread indices idX = threadIdx().x + (blockIdx().x - 0x1) * blockDim().x idY = threadIdx().y + (blockIdx().y - 0x1) * blockDim().y idZ = threadIdx().z + (blockIdx().z - 0x1) * blockDim().z # copy partition data @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX orgVec[itrX,itrY,itrZ,dirItr,parItr] = actVec[(itrX - 1) * stpX + offX + 1, (itrY - 1) * stpY + offY + 1, (itrZ -1) * stpZ + offZ + 1, dirItr] end return nothing end #= split a branch so that even and odd Fourier coefficients are independent =# function sptBrnHst!(vecSze::NTuple{3,Integer}, prgVec::AbstractArray{T,5}, sptDir::Integer, phzVec::AbstractVector{T}, parNum::Integer, orgVec::AbstractArray{T,5}, cmpInf::GlaKerOpt=GlaKerOpt(false))::Nothing where T<:Union{ComplexF64,ComplexF32} @threads for itr ∈ CartesianIndices(orgVec) @inbounds prgVec[itr] = phzVec[itr[sptDir]] * orgVec[itr] end return nothing end #= host and device code split to clarify code operation =# function sptBrnDev!(vecSze::NTuple{3,Integer}, prgVec::AbstractArray{T,5}, sptDir::Integer, phzVec::AbstractVector{T}, parNum::Integer, orgVec::AbstractArray{T,5}, cmpInf::GlaKerOpt=GlaKerOpt(false))::Nothing where T<:Union{ComplexF64,ComplexF32} for parItr ∈ eachindex(1:parNum) @cuda threads=cmpInf.numTrd blocks=cmpInf.numBlk sptKer!(vecSze..., prgVec, sptDir, phzVec, parItr, orgVec) end CUDA.synchronize(CUDA.stream()) return nothing end #= device kernel for sptBrn! =# function sptKer!(maxX::Integer, maxY::Integer, maxZ::Integer, prgVec::AbstractArray{T,5}, sptDir::Integer, phzVec::AbstractVector{T}, parItr::Integer, orgVec::AbstractArray{T,5})::Nothing where T<:Union{ComplexF64,ComplexF32} # grid strides strX = gridDim().x * blockDim().x strY = gridDim().y * blockDim().y strZ = gridDim().z * blockDim().z # thread indices idX = threadIdx().x + (blockIdx().x - 0x1) * blockDim().x idY = threadIdx().y + (blockIdx().y - 0x1) * blockDim().y idZ = threadIdx().z + (blockIdx().z - 0x1) * blockDim().z # multiplication loop selected based on phase transformation direction if sptDir == 1 # x phase---phzVec[itrX] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX # x direction prgVec[itrX,itrY,itrZ,1,parItr] = phzVec[itrX] * orgVec[itrX,itrY,itrZ,1,parItr] # y direction prgVec[itrX,itrY,itrZ,2,parItr] = phzVec[itrX] * orgVec[itrX,itrY,itrZ,2,parItr] # z direction prgVec[itrX,itrY,itrZ,3,parItr] = phzVec[itrX] * orgVec[itrX,itrY,itrZ,3,parItr] end elseif sptDir == 2 # y phase---phzVec[itrY] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX # x direction prgVec[itrX,itrY,itrZ,1,parItr] = phzVec[itrY] * orgVec[itrX,itrY,itrZ,1,parItr] # y direction prgVec[itrX,itrY,itrZ,2,parItr] = phzVec[itrY] * orgVec[itrX,itrY,itrZ,2,parItr] # z direction prgVec[itrX,itrY,itrZ,3,parItr] = phzVec[itrY] * orgVec[itrX,itrY,itrZ,3,parItr] end else # z phase---phzVec[itrZ] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX # x direction prgVec[itrX,itrY,itrZ,1,parItr] = phzVec[itrZ] * orgVec[itrX,itrY,itrZ,1,parItr] # y direction prgVec[itrX,itrY,itrZ,2,parItr] = phzVec[itrZ] * orgVec[itrX,itrY,itrZ,2,parItr] # z direction prgVec[itrX,itrY,itrZ,3,parItr] = phzVec[itrZ] * orgVec[itrX,itrY,itrZ,3,parItr] end end return nothing end #= split branches for external Green function =# function sptBrnHst!(prgVecEve::AbstractArray{T,5}, prgVecOdd::AbstractArray{T,5}, dirSpt::Integer, phzVec::AbstractVector{T}, mixInf::GlaExtInf, parNum::Integer, orgVec::AbstractArray{T,5}, cmpInf::GlaKerOpt=GlaKerOpt(false))::Nothing where T<:Union{ComplexF64,ComplexF32} # final branch size brnSze = div.(mixInf.trgCel .+ mixInf.srcCel, 2) # current and progeny vector sizes curSze = size(orgVec) prgSze = ntuple(x -> x == dirSpt ? brnSze[x] : curSze[x], 3) # spill over of source vector into embedding extension ovrCpy = map(UnitRange, (1,1,1), mixInf.srcCel .- brnSze) # copy ranges ovrRng = ntuple(x -> x == dirSpt ? ovrCpy[x] : 1:prgSze[x], 3) # range for standard copy stdCpy = map(UnitRange, getproperty.(ovrRng, :stop) .+ (1,1,1), min.(mixInf.srcCel, brnSze)) stdRng = ntuple(x -> x == dirSpt ? stdCpy[x] : 1:prgSze[x], 3) # range for zero copy zroCpy = map(UnitRange, getproperty.(stdRng, :stop) .+ (1,1,1), brnSze) zroRng = ntuple(x -> x == dirSpt ? zroCpy[x] : 1:prgSze[x], 3) # offset for over range ovrOff = ntuple(x -> x == dirSpt ? brnSze[dirSpt] : 0, 3) # spill over indices splRng = CartesianIndices(ovrRng) .+ CartesianIndex(ovrOff) # perform split # copy range where source vector spills over brnSze @threads for crtItr ∈ CartesianIndices((ovrRng..., 1:3, 1:parNum)) # even branch @inbounds prgVecEve[crtItr] = orgVec[crtItr] + orgVec[splRng[crtItr[1],crtItr[2],crtItr[3]],crtItr[4], crtItr[5]] # odd branch @inbounds prgVecOdd[crtItr] = phzVec[crtItr[dirSpt]] * (orgVec[crtItr] - orgVec[splRng[crtItr[1],crtItr[2],crtItr[3]],crtItr[4], crtItr[5]]) end # standard copy range @threads for crtItr ∈ CartesianIndices((stdRng..., 1:3, 1:parNum)) # even branch @inbounds prgVecEve[crtItr] = orgVec[crtItr] # odd branch @inbounds prgVecOdd[crtItr] = phzVec[crtItr[dirSpt]] * orgVec[crtItr] end # zero copy range @threads for crtItr ∈ CartesianIndices((zroRng..., 1:3, 1:parNum)) # even branch @inbounds prgVecEve[crtItr] = 0.0 + 0.0 * im # odd branch @inbounds prgVecOdd[crtItr] = 0.0 + 0.0 * im end return nothing end #= split host and device code to clarify functionality =# function sptBrnDev!(prgVecEve::AbstractArray{T,5}, prgVecOdd::AbstractArray{T,5}, dirSpt::Integer, phzVec::AbstractVector{T}, mixInf::GlaExtInf, parNum::Integer, orgVec::AbstractArray{T,5}, cmpInf::GlaKerOpt=GlaKerOpt(false))::Nothing where T<:Union{ComplexF64,ComplexF32} # final branch size brnSze = div.(mixInf.trgCel .+ mixInf.srcCel, 2) # current and progeny vector sizes curSze = size(orgVec) prgSze = ntuple(x -> x == dirSpt ? brnSze[x] : curSze[x], 3) # spill over of source vector into embedding extension ovrCpy = map(UnitRange, (1,1,1), mixInf.srcCel .- brnSze) # copy ranges ovrRng = ntuple(x -> x == dirSpt ? ovrCpy[x] : 1:prgSze[x], 3) # range for standard copy stdCpy = map(UnitRange, getproperty.(ovrRng, :stop) .+ (1,1,1), min.(mixInf.srcCel, brnSze)) stdRng = ntuple(x -> x == dirSpt ? stdCpy[x] : 1:prgSze[x], 3) # range for zero copy zroCpy = map(UnitRange, getproperty.(stdRng, :stop) .+ (1,1,1), brnSze) zroRng = ntuple(x -> x == dirSpt ? zroCpy[x] : 1:prgSze[x], 3) # offset for over range ovrOff = ntuple(x -> x == dirSpt ? brnSze[dirSpt] : 0, 3) # spill over indices splRng = CartesianIndices(ovrRng) .+ CartesianIndex(ovrOff) # perform split # copy range where source vector spills over brnSze if !isempty(CartesianIndices(ovrRng)) for parItr ∈ eachindex(1:parNum) for dirItr ∈ eachindex(1:3) @cuda threads=cmpInf.numTrd blocks=cmpInf.numBlk sptBrnOvrKer!( prgVecEve, prgVecOdd, getproperty.(ovrRng, :stop)..., getproperty.(ovrRng, :start)..., sum(ovrOff), dirSpt, dirItr, parItr, phzVec, orgVec) end end end # standard copy range for parItr ∈ eachindex(1:parNum) for dirItr ∈ eachindex(1:3) @cuda threads=cmpInf.numTrd blocks=cmpInf.numBlk sptBrnStdKer!( prgVecEve, prgVecOdd, getproperty.(stdRng, :stop)..., getproperty.(stdRng, :start)..., dirSpt, dirItr, parItr, phzVec, orgVec) end end # zero copy range if !isempty(CartesianIndices(zroRng)) for parItr ∈ eachindex(1:parNum) for dirItr ∈ eachindex(1:3) @cuda threads=cmpInf.numTrd blocks=cmpInf.numBlk sptBrnZroKer!( prgVecEve, prgVecOdd, getproperty.(zroRng, :stop)..., getproperty.(zroRng, :start)..., dirItr, parItr, orgVec) end end end # release original vector to reduce memory pressure CUDA.synchronize(CUDA.stream()) CUDA.unsafe_free!(orgVec) CUDA.synchronize(CUDA.stream()) return nothing end #= kernel for source spill over portion =# function sptBrnOvrKer!(prgVecEve::AbstractArray{T,5}, prgVecOdd::AbstractArray{T,5}, endX::Integer, endY::Integer, endZ::Integer, begX::Integer, begY::Integer, begZ::Integer, ovrOff::Integer, dirSpt::Integer, dirItr::Integer, parItr::Integer, phzVec::AbstractVector{T}, orgVec::AbstractArray{T,5})::Nothing where T<:Union{ComplexF64,ComplexF32} # grid strides strX = gridDim().x * blockDim().x strY = gridDim().y * blockDim().y strZ = gridDim().z * blockDim().z # thread indices idX = threadIdx().x + (begX - 0x1) + (blockIdx().x - 0x1) * blockDim().x idY = threadIdx().y + (begY - 0x1) + (blockIdx().y - 0x1) * blockDim().y idZ = threadIdx().z + (begZ - 0x1) + (blockIdx().z - 0x1) * blockDim().z # multiplication loop selected based on phase transformation direction if dirSpt == 1 # x phase---phzVec[itrX] @inbounds for itrZ = idZ:strZ:endZ, itrY = idY:strY:endY, itrX = idX:strX:endX # even branch prgVecEve[itrX,itrY,itrZ,dirItr,parItr] = orgVec[itrX,itrY,itrZ,dirItr,parItr] + orgVec[itrX + ovrOff,itrY,itrZ,dirItr,parItr] # odd branch prgVecOdd[itrX,itrY,itrZ,dirItr,parItr] = phzVec[itrX] * (orgVec[itrX,itrY,itrZ,dirItr,parItr] - orgVec[itrX + ovrOff,itrY,itrZ,dirItr,parItr]) end elseif dirSpt == 2 # y phase---phzVec[itrY] @inbounds for itrZ = idZ:strZ:endZ, itrY = idY:strY:endY, itrX = idX:strX:endX # even branch prgVecEve[itrX,itrY,itrZ,dirItr,parItr] = orgVec[itrX,itrY,itrZ,dirItr,parItr] + orgVec[itrX,itrY + ovrOff,itrZ,dirItr,parItr] # odd branch prgVecOdd[itrX,itrY,itrZ,dirItr,parItr] = phzVec[itrY] * (orgVec[itrX,itrY,itrZ,dirItr,parItr] - orgVec[itrX,itrY + ovrOff,itrZ,dirItr,parItr]) end else # z phase---phzVec[itrZ] @inbounds for itrZ = idZ:strZ:endZ, itrY = idY:strY:endY, itrX = idX:strX:endX # even branch prgVecEve[itrX,itrY,itrZ,dirItr,parItr] = orgVec[itrX,itrY,itrZ,dirItr,parItr] + orgVec[itrX,itrY,itrZ + ovrOff,dirItr,parItr] # odd branch prgVecOdd[itrX,itrY,itrZ,dirItr,parItr] = phzVec[itrZ] * (orgVec[itrX,itrY,itrZ,dirItr,parItr] - orgVec[itrX,itrY,itrZ + ovrOff,dirItr,parItr]) end end return nothing end #= kernel for standard branching copy =# function sptBrnStdKer!(prgVecEve::AbstractArray{T,5}, prgVecOdd::AbstractArray{T,5}, endX::Integer, endY::Integer, endZ::Integer, begX::Integer, begY::Integer, begZ::Integer, dirSpt::Integer, dirItr::Integer, parItr::Integer, phzVec::AbstractVector{T}, orgVec::AbstractArray{T,5})::Nothing where T<:Union{ComplexF64,ComplexF32} # grid strides strX = gridDim().x * blockDim().x strY = gridDim().y * blockDim().y strZ = gridDim().z * blockDim().z # thread indices idX = threadIdx().x + (begX - 0x1) + (blockIdx().x - 0x1) * blockDim().x idY = threadIdx().y + (begY - 0x1) + (blockIdx().y - 0x1) * blockDim().y idZ = threadIdx().z + (begZ - 0x1) + (blockIdx().z - 0x1) * blockDim().z # multiplication loop selected based on phase transformation direction if dirSpt == 1 # x phase---phzVec[itrX] @inbounds for itrZ = idZ:strZ:endZ, itrY = idY:strY:endY, itrX = idX:strX:endX # even branch prgVecEve[itrX,itrY,itrZ,dirItr,parItr] = orgVec[itrX,itrY,itrZ,dirItr,parItr] # odd branch prgVecOdd[itrX,itrY,itrZ,dirItr,parItr] = phzVec[itrX] * orgVec[itrX,itrY,itrZ,dirItr,parItr] end elseif dirSpt == 2 # y phase---phzVec[itrY] @inbounds for itrZ = idZ:strZ:endZ, itrY = idY:strY:endY, itrX = idX:strX:endX # even branch prgVecEve[itrX,itrY,itrZ,dirItr,parItr] = orgVec[itrX,itrY,itrZ,dirItr,parItr] # odd branch prgVecOdd[itrX,itrY,itrZ,dirItr,parItr] = phzVec[itrY] * orgVec[itrX,itrY,itrZ,dirItr,parItr] end else # z phase---phzVec[itrZ] @inbounds for itrZ = idZ:strZ:endZ, itrY = idY:strY:endY, itrX = idX:strX:endX # even branch prgVecEve[itrX,itrY,itrZ,dirItr,parItr] = orgVec[itrX,itrY,itrZ,dirItr,parItr] # odd branch prgVecOdd[itrX,itrY,itrZ,dirItr,parItr] = phzVec[itrZ] * orgVec[itrX,itrY,itrZ,dirItr,parItr] end end return nothing end #= kernel for additional embedding =# function sptBrnZroKer!(prgVecEve::AbstractArray{T,5}, prgVecOdd::AbstractArray{T,5}, endX::Integer, endY::Integer, endZ::Integer, begX::Integer, begY::Integer, begZ::Integer, dirItr::Integer, parItr::Integer, orgVec::AbstractArray{T,5})::Nothing where T<:Union{ComplexF64,ComplexF32} # grid strides strX = gridDim().x * blockDim().x strY = gridDim().y * blockDim().y strZ = gridDim().z * blockDim().z # thread indices idX = threadIdx().x + (begX - 0x1) + (blockIdx().x - 0x1) * blockDim().x idY = threadIdx().y + (begY - 0x1) + (blockIdx().y - 0x1) * blockDim().y idZ = threadIdx().z + (begZ - 0x1) + (blockIdx().z - 0x1) * blockDim().z # zero appropriate elements @inbounds for itrZ = idZ:strZ:endZ, itrY = idY:strY:endY, itrX = idX:strX:endX # even branch prgVecEve[itrX,itrY,itrZ,dirItr,parItr] = 0.0 + 0.0 * im # odd branch prgVecOdd[itrX,itrY,itrZ,dirItr,parItr] = 0.0 + 0.0 * im end return nothing end #= merge two branches, eliminating unused coefficients =# function mrgBrnHst!(mixInf::GlaExtInf, orgVec::AbstractArray{T,5}, mrgDir::Integer, parNumTrg::Integer, phzVec::AbstractVector{T}, prgVec::AbstractArray{T,5}, cmpInf::GlaKerOpt=GlaKerOpt(false))::Nothing where T<:Union{ComplexF64,ComplexF32} @threads for itr ∈ CartesianIndices(orgVec) @inbounds orgVec[itr] = 0.5 * (orgVec[itr] + conj(phzVec[itr[mrgDir]]) * prgVec[itr]) end return nothing end #= split host and device code to clarify functionality =# function mrgBrnDev!(mixInf::GlaExtInf, orgVec::AbstractArray{T,5}, mrgDir::Integer, parNumTrg::Integer, phzVec::AbstractVector{T}, prgVec::AbstractArray{T,5}, cmpInf::GlaKerOpt=GlaKerOpt(false))::Nothing where T<:Union{ComplexF64,ComplexF32} for prtItr ∈ eachindex(1:parNumTrg) for dirItr ∈ eachindex(1:3) @cuda threads = cmpInf.numTrd blocks = cmpInf.numBlk mrgKer!( size(orgVec)[1:3]..., orgVec, mrgDir, phzVec, dirItr, prtItr, prgVec) end end CUDA.synchronize(CUDA.stream()) CUDA.unsafe_free!(prgVec) CUDA.synchronize(CUDA.stream()) return nothing end #= device kernel for mrgBrn! =# function mrgKer!(maxX::Integer, maxY::Integer, maxZ::Integer, orgVec::AbstractArray{T,5}, mrgDir::Integer, phzVec::AbstractVector{T}, dirItr::Integer, prtItr::Integer, prgVec::AbstractArray{T,5})::Nothing where T<:Union{ComplexF64,ComplexF32} # grid strides strX = gridDim().x * blockDim().x strY = gridDim().y * blockDim().y strZ = gridDim().z * blockDim().z # thread indices idX = threadIdx().x + (blockIdx().x - 0x1) * blockDim().x idY = threadIdx().y + (blockIdx().y - 0x1) * blockDim().y idZ = threadIdx().z + (blockIdx().z - 0x1) * blockDim().z # multiplication loop selected based on phase transformation direction if mrgDir == 1 # x phase---phzVec[itrX] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX orgVec[itrX,itrY,itrZ,dirItr,prtItr] = 0.5 * (orgVec[itrX,itrY,itrZ,dirItr,prtItr] + conj(phzVec[itrX]) * prgVec[itrX,itrY,itrZ,dirItr,prtItr]) end elseif mrgDir == 2 # y phase---phzVec[itrY] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX orgVec[itrX,itrY,itrZ,dirItr,prtItr] = 0.5 * (orgVec[itrX,itrY,itrZ,dirItr,prtItr] + conj(phzVec[itrY]) * prgVec[itrX,itrY,itrZ,dirItr,prtItr]) end else # z phase---phzVec[itrZ] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX orgVec[itrX,itrY,itrZ,dirItr,prtItr] = 0.5 * (orgVec[itrX,itrY,itrZ,dirItr,prtItr] + conj(phzVec[itrZ]) * prgVec[itrX,itrY,itrZ,dirItr,prtItr]) end end return nothing end #= generalized host merge allowing for different output size =# function mrgBrnHst!(mixInf::GlaExtInf, mrgVec::AbstractArray{T,5}, mrgDir::Integer, parNumTrg::Integer, phzVec::AbstractVector{T}, eveVec::AbstractArray{T,5}, oddVec::AbstractArray{T,5}, cmpInf::GlaKerOpt=GlaKerOpt(false))::Nothing where T<:Union{ComplexF64,ComplexF32} # size of current and merged vectors mrgSze = size(mrgVec) curSze = size(eveVec) # range for top half of merge vector topRng = ntuple(x -> x == mrgDir ? (1:min(mrgSze[x], curSze[x])) : (1:mrgSze[x]), 3) # range for bottom half of merge vector botRng = ntuple(x -> x == mrgDir ? (1:(mrgSze[x] - getproperty(topRng[x], :stop))) : (1:mrgSze[x]), 3) # offset for merge vector offSet = ntuple(x -> x == mrgDir ? (getproperty(botRng[x], :stop) > 0 ? getproperty(topRng[x], :stop) : 0) : 0, 5) # merge top range @threads for itr ∈ CartesianIndices((topRng..., 1:3, 1:mrgSze[5])) @inbounds mrgVec[itr] = 0.5 * (eveVec[itr] + conj(phzVec[itr[mrgDir]]) * oddVec[itr]) end # check if merge vector is filled if getproperty(botRng[mrgDir], :stop) > 0 @threads for itr ∈ CartesianIndices((botRng..., 1:3, 1:mrgSze[5])) @inbounds mrgVec[itr + CartesianIndex(offSet)] = 0.5 * (eveVec[itr] - conj(phzVec[itr[mrgDir]]) * oddVec[itr]) end end return nothing end #= device merge allowing for different output size =# function mrgBrnDev!(mixInf::GlaExtInf, mrgVec::AbstractArray{T,5}, mrgDir::Integer, parNumTrg::Integer, phzVec::AbstractVector{T}, eveVec::AbstractArray{T,5}, oddVec::AbstractArray{T,5}, cmpInf::GlaKerOpt=GlaKerOpt(false))::Nothing where T<:Union{ComplexF64,ComplexF32} # size of current and merged vectors mrgSze = size(mrgVec) curSze = size(eveVec) # range for top half of merge vector topRng = ntuple(x -> x == mrgDir ? (1:min(mrgSze[x], curSze[x])) : (1:mrgSze[x]), 3) # range for bottom half of merge vector botRng = ntuple(x -> x == mrgDir ? (1:(mrgSze[x] - getproperty(topRng[x], :stop))) : (1:mrgSze[x]), 3) # offset for merge vector offSet = ntuple(x -> x == mrgDir ? (getproperty(botRng[x], :stop) > 0 ? getproperty(topRng[x], :stop) : 0) : 0, 5) # merge top range for prtItr ∈ eachindex(1:parNumTrg) for dirItr ∈ eachindex(1:3) @cuda threads = cmpInf.numTrd blocks = cmpInf.numBlk mrgTopKer!( mrgVec, getproperty.(topRng, :stop)..., mrgDir, phzVec, dirItr, prtItr, eveVec, oddVec) end end # check if merge vector is filled if getproperty(botRng[mrgDir], :stop) > 0 for prtItr ∈ eachindex(1:parNumTrg) for dirItr ∈ eachindex(1:3) @cuda threads = cmpInf.numTrd blocks = cmpInf.numBlk mrgBotKer!( mrgVec, getproperty.(botRng, :stop)..., offSet[mrgDir], mrgDir, phzVec, dirItr, prtItr, eveVec, oddVec) end end end # free liberated memory CUDA.synchronize(CUDA.stream()) CUDA.unsafe_free!(eveVec) CUDA.unsafe_free!(oddVec) CUDA.synchronize(CUDA.stream()) return nothing end #= device kernel for top half of generalized mrgBrn! =# function mrgTopKer!(mrgVec::AbstractArray{T,5}, maxX::Integer, maxY::Integer, maxZ::Integer, mrgDir::Integer, phzVec::AbstractVector{T}, dirItr::Integer, prtItr::Integer, eveVec::AbstractArray{T,5}, oddVec::AbstractArray{T,5})::Nothing where T<:Union{ComplexF64,ComplexF32} # grid strides strX = gridDim().x * blockDim().x strY = gridDim().y * blockDim().y strZ = gridDim().z * blockDim().z # thread indices idX = threadIdx().x + (blockIdx().x - 0x1) * blockDim().x idY = threadIdx().y + (blockIdx().y - 0x1) * blockDim().y idZ = threadIdx().z + (blockIdx().z - 0x1) * blockDim().z # multiplication loop selected based on phase transformation direction if mrgDir == 1 # x phase---phzVec[itrX] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX mrgVec[itrX,itrY,itrZ,dirItr,prtItr] = 0.5 * (eveVec[itrX,itrY,itrZ,dirItr,prtItr] + conj(phzVec[itrX]) * oddVec[itrX,itrY,itrZ,dirItr,prtItr]) end elseif mrgDir == 2 # y phase---phzVec[itrY] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX mrgVec[itrX,itrY,itrZ,dirItr,prtItr] = 0.5 * (eveVec[itrX,itrY,itrZ,dirItr,prtItr] + conj(phzVec[itrY]) * oddVec[itrX,itrY,itrZ,dirItr,prtItr]) end else # z phase---phzVec[itrZ] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX mrgVec[itrX,itrY,itrZ,dirItr,prtItr] = 0.5 * (eveVec[itrX,itrY,itrZ,dirItr,prtItr] + conj(phzVec[itrZ]) * oddVec[itrX,itrY,itrZ,dirItr,prtItr]) end end return nothing end #= device kernel for bottom half of generalized mrgBrn! =# function mrgBotKer!(mrgVec::AbstractArray{T,5}, maxX::Integer, maxY::Integer, maxZ::Integer, mrgOff::Integer, mrgDir::Integer, phzVec::AbstractVector{T}, dirItr::Integer, prtItr::Integer, eveVec::AbstractArray{T,5}, oddVec::AbstractArray{T,5})::Nothing where T<:Union{ComplexF64,ComplexF32} # grid strides strX = gridDim().x * blockDim().x strY = gridDim().y * blockDim().y strZ = gridDim().z * blockDim().z # thread indices idX = threadIdx().x + (blockIdx().x - 0x1) * blockDim().x idY = threadIdx().y + (blockIdx().y - 0x1) * blockDim().y idZ = threadIdx().z + (blockIdx().z - 0x1) * blockDim().z # multiplication loop selected based on phase transformation direction if mrgDir == 1 # x phase---phzVec[itrX] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX mrgVec[itrX + mrgOff,itrY,itrZ,dirItr,prtItr] = 0.5 * (eveVec[itrX,itrY,itrZ,dirItr,prtItr] - conj(phzVec[itrX]) * oddVec[itrX,itrY,itrZ,dirItr,prtItr]) end elseif mrgDir == 2 # y phase---phzVec[itrY] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX mrgVec[itrX,itrY + mrgOff,itrZ,dirItr,prtItr] = 0.5 * (eveVec[itrX,itrY,itrZ,dirItr,prtItr] - conj(phzVec[itrY]) * oddVec[itrX,itrY,itrZ,dirItr,prtItr]) end else # z phase---phzVec[itrZ] @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX mrgVec[itrX,itrY,itrZ + mrgOff,dirItr,prtItr] = 0.5 * (eveVec[itrX,itrY,itrZ,dirItr,prtItr] - conj(phzVec[itrZ]) * oddVec[itrX,itrY,itrZ,dirItr,prtItr]) end end return nothing end #= execute Hadamard product step =# function mulBrnHst!(mixInf::GlaExtInf, bId::Integer, prdVec::AbstractArray{T,4}, vecMod::AbstractArray{T,4}, orgVec::AbstractArray{T,4}, cmpInf::GlaKerOpt=GlaKerOpt(false))::Nothing where T<:Union{ComplexF64,ComplexF32} # size of branch brnSze = (mixInf.trgCel .+ mixInf.srcCel) .÷ 2 # unique information of Green function egoSze = size(vecMod)[1:3] # zero if branch is even in that direction, one if branch is odd brnSym = Bool.([mod(div(bId, ^(2, 3 - k)), 2) for k ∈ 1:3]) # declare memory dirSymHst = Array{Float32}(undef, 3, 8) # selection ranges for Green function and vector modRng = Array{StepRange}(undef, 3, 8) vecRng = Array{StepRange}(undef, 3, 8) # sign symmetry for Green function multiplication symSgn = Array{Float32}(undef, 3, 8) # perform Hadamard---forward and reverse operation in each direction @sync begin for divItr ∈ 0:7 # one for reverse direction, zero for forward revSwt = [mod(div(divItr, ^(2, k - 1)), 2) for k ∈ 1:3] # set copy ranges for dirItr ∈ 1:3 # switch between full and partial stored information cases if egoSze[dirItr] == brnSze[dirItr] if revSwt[dirItr] == 0 # Green function range modRng[dirItr,divItr + 1] = 1:1:brnSze[dirItr] vecRng[dirItr,divItr + 1] = 1:1:brnSze[dirItr] symSgn[dirItr, divItr + 1] = 1.0 else modRng[dirItr,divItr + 1] = 1:1:0 vecRng[dirItr,divItr + 1] = 1:1:0 symSgn[dirItr, divItr + 1] = 0.0 end # partial information case else # switch between even and odd branch cases if brnSym[dirItr] == 0 # switch between source and target portions if revSwt[dirItr] == 0 begInd = 1 endInd = Integer.(ceil.(mixInf.trgCel[dirItr] / 2)) + iseven(mixInf.trgCel[dirItr]) # source coefficients else begInd = 2 endInd = Integer.(floor.(mixInf.srcCel[dirItr] / 2)) + 1 - iseven(mixInf.trgCel[dirItr]) end # odd coefficient branch else begInd = 1 # target coefficients if revSwt[dirItr] == 0 endInd = Integer.(ceil.(mixInf.trgCel[dirItr] / 2)) # source coefficients else endInd = Integer.(floor.(mixInf.srcCel[dirItr] / 2)) end end # Green function range modRng[dirItr,divItr + 1] = begInd:1:endInd # vector range if revSwt[dirItr] == 0 vecRng[dirItr,divItr + 1] = 1:1:(1 + endInd - begInd) else vecRng[dirItr,divItr + 1] = brnSze[dirItr]:-1:(brnSze[dirItr] - endInd + begInd) end # sign symmetry for Green function multiplication symSgn[dirItr, divItr + 1] = 1.0 - 2.0 * revSwt[dirItr] end end # check that range is not empty if !isempty(CartesianIndices(tuple(modRng[:,divItr + 1]...))) copyto!(view(dirSymHst, :, divItr + 1), eltype(dirSymHst).([symSgn[1,divItr + 1] * symSgn[2,divItr + 1], symSgn[1,divItr + 1] * symSgn[3,divItr + 1], symSgn[2,divItr + 1] * symSgn[3,divItr + 1]])) Base.Threads.@spawn mulKerHst!( getproperty.(modRng[:,divItr + 1], :stop) .- getproperty.(modRng[:,divItr + 1], :start) .+ 1, view(dirSymHst, :, divItr + 1), view(prdVec, vecRng[:,divItr + 1]..., :), view(vecMod, modRng[:,divItr + 1]..., :), view(orgVec, vecRng[:,divItr + 1]..., :)) end end end return nothing end #= execute Hadamard product step on device =# function mulBrnDev!(mixInf::GlaExtInf, bId::Integer, prdVec::AbstractArray{T,4}, vecMod::AbstractArray{T,4}, orgVec::AbstractArray{T,4}, cmpInf::GlaKerOpt=GlaKerOpt(false))::Nothing where T<:Union{ComplexF64,ComplexF32} # size of branch brnSze = (mixInf.trgCel .+ mixInf.srcCel) .÷ 2 # unique information of Green function egoSze = size(vecMod)[1:3] # zero if branch is even in that direction, one if branch is odd brnSym = Bool.([mod(div(bId, ^(2, 3 - k)), 2) for k ∈ 1:3]) # declare memory dimInfDev = CuArray{Int32}(undef, 3, 8) dirSymDev = CuArray{Float32}(undef, 3, 8) # selection ranges for Green function and vector modRng = Array{StepRange}(undef, 3, 8) vecRng = Array{StepRange}(undef, 3, 8) # sign symmetry for Green function multiplication symSgn = Array{Float32}(undef, 3, 8) # perform Hadamard---forward and reverse operation in each direction @sync begin for divItr ∈ 0:7 # one for reverse direction, zero for forward revSwt = [mod(div(divItr, ^(2, k - 1)), 2) for k ∈ 1:3] # set copy ranges for dirItr ∈ 1:3 # switch between full and partial stored information cases if egoSze[dirItr] == brnSze[dirItr] if revSwt[dirItr] == 0 # Green function range modRng[dirItr,divItr + 1] = 1:1:brnSze[dirItr] vecRng[dirItr,divItr + 1] = 1:1:brnSze[dirItr] symSgn[dirItr, divItr + 1] = 1.0 else modRng[dirItr,divItr + 1] = 1:1:0 vecRng[dirItr,divItr + 1] = 1:1:0 symSgn[dirItr, divItr + 1] = 0.0 end # partial information case else # switch between even and odd branch cases if brnSym[dirItr] == 0 # switch between source and target portions if revSwt[dirItr] == 0 begInd = 1 endInd = Integer.(ceil.(mixInf.trgCel[dirItr] / 2)) + iseven(mixInf.trgCel[dirItr]) # source coefficients else begInd = 2 endInd = Integer.(floor.(mixInf.srcCel[dirItr] / 2)) + 1 - iseven(mixInf.trgCel[dirItr]) end # odd coefficient branch else begInd = 1 # target coefficients if revSwt[dirItr] == 0 endInd = Integer.(ceil.(mixInf.trgCel[dirItr] / 2)) # source coefficients else endInd = Integer.(floor.(mixInf.srcCel[dirItr] / 2)) end end # Green function range modRng[dirItr,divItr + 1] = begInd:1:endInd # vector range if revSwt[dirItr] == 0 vecRng[dirItr,divItr + 1] = 1:1:(1 + endInd - begInd) else vecRng[dirItr,divItr + 1] = brnSze[dirItr]:-1:(brnSze[dirItr] - endInd + begInd) end # sign symmetry for Green function multiplication symSgn[dirItr, divItr + 1] = 1.0 - 2.0 * revSwt[dirItr] end end # check that range is not empty if !isempty(CartesianIndices(tuple(modRng[:,divItr + 1]...))) # number of elements copyto!(view(dimInfDev, :, divItr + 1), getproperty.(modRng[:, divItr + 1], :stop) .- getproperty.(modRng[:, divItr + 1], :start) .+ 1) # symmetry information copyto!(view(dirSymDev, :, divItr + 1), eltype(dirSymDev).([symSgn[1,divItr + 1] * symSgn[2,divItr + 1], symSgn[1,divItr + 1] * symSgn[3,divItr + 1], symSgn[2,divItr + 1] * symSgn[3,divItr + 1]])) # launch kernel @cuda threads=cmpInf.numTrd blocks=cmpInf.numBlk mulKerDev!( view(dimInfDev, :, divItr + 1), view(dirSymDev, :, divItr + 1), view(prdVec, vecRng[:,divItr + 1]..., :), view(vecMod, modRng[:,divItr + 1]..., :), view(orgVec, vecRng[:,divItr + 1]..., :)) end end end # synchronize CUDA.synchronize(CUDA.stream()) CUDA.unsafe_free!(dimInfDev) CUDA.unsafe_free!(dirSymDev) CUDA.synchronize(CUDA.stream()) return nothing end #= host kernel for mulBrn! =# function mulKerHst!(dimInf::AbstractArray{<:Integer}, dirSym::AbstractArray{<:Real}, prdVec::AbstractArray{T,4}, vecMod::AbstractArray{T,4}, orgVec::AbstractArray{T,4},)::Nothing where T<:Union{ComplexF64,ComplexF32} @threads for itr ∈ CartesianIndices((1:dimInf[1], 1:dimInf[2], 1:dimInf[3])) # vecMod follows ii, jj, kk, ij, ik, jk storage format @inbounds prdVec[itr,1] += vecMod[itr,1] * orgVec[itr,1] + dirSym[1] * vecMod[itr,4] * orgVec[itr,2] + dirSym[2] * vecMod[itr,5] * orgVec[itr,3] # j vector direction @inbounds prdVec[itr,2] += dirSym[1] * vecMod[itr,4] * orgVec[itr,1] + vecMod[itr,2] * orgVec[itr,2] + dirSym[3] * vecMod[itr,6] * orgVec[itr,3] # k vector direction @inbounds prdVec[itr,3] += dirSym[2] * vecMod[itr,5] * orgVec[itr,1] + dirSym[3] * vecMod[itr,6] * orgVec[itr,2] + vecMod[itr,3] * orgVec[itr,3] end end #= device kernel for mulBrn! =# function mulKerDev!(dimInf::AbstractVector{<:Integer}, dirSym::AbstractVector{<:Real}, prdVec::AbstractArray{T,4}, vecMod::AbstractArray{T,4}, orgVec::AbstractArray{T,4})::Nothing where T<:Union{ComplexF64,ComplexF32} # grid strides strX = gridDim().x * blockDim().x strY = gridDim().y * blockDim().y strZ = gridDim().z * blockDim().z # thread indices idX = threadIdx().x + (blockIdx().x - 0x1) * blockDim().x idY = threadIdx().y + (blockIdx().y - 0x1) * blockDim().y idZ = threadIdx().z + (blockIdx().z - 0x1) * blockDim().z # multiplication loops @inbounds for itrZ = idZ:strZ:dimInf[3], itrY = idY:strY:dimInf[2], itrX = idX:strX:dimInf[1] # vecMod follows ii, jj, kk, ij, ik, jk storage format prdVec[itrX,itrY,itrZ,1] += vecMod[itrX,itrY,itrZ,1] * orgVec[itrX,itrY,itrZ,1] + dirSym[1] * vecMod[itrX,itrY,itrZ,4] * orgVec[itrX,itrY,itrZ,2] + dirSym[2] * vecMod[itrX,itrY,itrZ,5] * orgVec[itrX,itrY,itrZ,3] # j vector direction prdVec[itrX,itrY,itrZ,2] += dirSym[1] * vecMod[itrX,itrY,itrZ,4] * orgVec[itrX,itrY,itrZ,1] + vecMod[itrX,itrY,itrZ,2] * orgVec[itrX,itrY,itrZ,2] + dirSym[3] * vecMod[itrX,itrY,itrZ,6] * orgVec[itrX,itrY,itrZ,3] # k vector direction prdVec[itrX,itrY,itrZ,3] += dirSym[2] * vecMod[itrX,itrY,itrZ,5] * orgVec[itrX,itrY,itrZ,1] + dirSym[3] * vecMod[itrX,itrY,itrZ,6] * orgVec[itrX,itrY,itrZ,2] + vecMod[itrX,itrY,itrZ,3] * orgVec[itrX,itrY,itrZ,3] end return nothing end #= merge partitions and return output vector =# function mrgPrtHst(mixInf::GlaExtInf, cmpInf::GlaKerOpt, parNum::Integer, prtVec::AbstractArray{T,5})::AbstractArray{T,4} where T<:Union{ComplexF64,ComplexF32} # restructure partitioned vector mrgVec = Array{eltype(prtVec)}(undef, (mixInf.trgDiv .* mixInf.trgCel)..., 3) # break into partitions @threads for itr ∈ CartesianIndices(prtVec) # copy partition data @inbounds mrgVec[CartesianIndex((Tuple(itr)[1:3] .- (1,1,1)) .* mixInf.trgDiv) + CartesianIndex(1,1,1) + mixInf.trgPar[itr[5]], itr[4]] = prtVec[itr] end return mrgVec end #= device code separated to clarify functionality and type inference =# function mrgPrtDev(mixInf::GlaExtInf, cmpInf::GlaKerOpt, parNum::Integer, prtVec::AbstractArray{T,5})::AbstractArray{T,4} where T<:Union{ComplexF64,ComplexF32} # restructure partitioned vector mrgVec = CuArray{eltype(prtVec)}(undef, (mixInf.trgDiv .* mixInf.trgCel)..., 3) CUDA.synchronize(CUDA.stream()) # perform partitioning for parItr ∈ eachindex(1:parNum) for dirItr ∈ eachindex(1:3) @cuda threads=cmpInf.numTrd blocks=cmpInf.numBlk mrgPrtKer!( size(prtVec)[1:3]..., mixInf.trgDiv..., Tuple(mixInf.trgPar[parItr])..., dirItr, parItr, mrgVec, prtVec) end end # release active vector to reduce memory pressure CUDA.synchronize(CUDA.stream()) CUDA.unsafe_free!(prtVec) CUDA.synchronize(CUDA.stream()) return mrgVec end #= device kernel to merge target vector partitions =# function mrgPrtKer!(maxX::Integer, maxY::Integer, maxZ::Integer, stpX::Integer, stpY::Integer, stpZ::Integer, offX::Integer, offY::Integer, offZ::Integer, dirItr::Integer, parItr::Integer, mrgVec::AbstractArray{T,4}, prtVec::AbstractArray{T,5})::Nothing where T<:Union{ComplexF64,ComplexF32} # grid strides strX = gridDim().x * blockDim().x strY = gridDim().y * blockDim().y strZ = gridDim().z * blockDim().z # thread indices idX = threadIdx().x + (blockIdx().x - 0x1) * blockDim().x idY = threadIdx().y + (blockIdx().y - 0x1) * blockDim().y idZ = threadIdx().z + (blockIdx().z - 0x1) * blockDim().z # copy partition data @inbounds for itrZ = idZ:strZ:maxZ, itrY = idY:strY:maxY, itrX = idX:strX:maxX mrgVec[(itrX - 1) * stpX + offX + 1, (itrY - 1) * stpY + offY + 1, (itrZ - 1) * stpZ + offZ + 1, dirItr] = prtVec[itrX,itrY,itrZ,dirItr,parItr] end return nothing end #= binary branch indexing =# @inline function nxtBrnId(maxLvl::Integer, lvl::Integer, bId::Integer)::Integer return bId + ^(2, maxLvl - (lvl + 1)) end
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
24817
# settings for cubature integral evaluation: relative tolerance and absolute # tolerance const cubRelTol = 1e-6; # const cubRelTol = 1e-3; const cubAbsTol = 1e-9; # const cubAbsTol = 1e-3; # tolerance for cell contact const cntTol = 1e-8; """ genEgoExt!(egoCrcExt::AbstractArray{T,5}, trgVol::GlaVol, srcVol::GlaVol, cmpInf::GlaKerOpt)::Nothing where T<:Union{ComplexF64,ComplexF32} Calculate circulant vector for the Green function between a target volume, trgVol, and source volume, srcVol. """ function genEgoExt!(egoCrcExt::AbstractArray{T,5}, trgVol::GlaVol, srcVol::GlaVol, cmpInf::GlaKerOpt)::Nothing where T<:Union{ComplexF64,ComplexF32} facLst = facPar() trgFac = Float64.(cubFac(trgVol.scl)) srcFac = Float64.(cubFac(srcVol.scl)) sepGrdTrg = sepGrd(trgVol, srcVol, 0) sepGrdSrc = sepGrd(trgVol, srcVol, 1) # calculate Green function values genEgoCrcExt!(egoCrcExt, trgVol, srcVol, sepGrdTrg, sepGrdSrc, trgFac, srcFac, facLst, cmpInf) return nothing end """ genEgoSlf!(egoCrc::Array{ComplexF64}, slfVol::GlaVol, cmpInf::GlaKerOpt)::Nothing Calculate circulant vector of the Green function on a single domain. """ function genEgoSlf!(egoCrcSlf::AbstractArray{T,5}, slfVol::GlaVol, cmpInf::GlaKerOpt)::Nothing where T<:Union{ComplexF64,ComplexF32} facLst = facPar() trgFac = Float64.(cubFac(slfVol.scl)) srcFac = Float64.(cubFac(slfVol.scl)) srcGrd = sepGrd(slfVol, slfVol, 0) # calculate Green function values genEgoCrcSlf!(slfVol, egoCrcSlf, srcGrd, trgFac, srcFac, facLst, cmpInf) return nothing end #= Generate the circulant vector of the Green function between a pair of distinct domains, checking for possible domain contact. For the procedure to function correctly, whenever the domains are in contact, the ratio of scales between the source and target volumes must all be integers, and cell corners must match up. =# function genEgoCrcExt!(egoCrcExt::AbstractArray{T,5}, trgVol::GlaVol, srcVol::GlaVol, sepGrdTrg::Array{<:StepRange,1}, sepGrdSrc::Array{<:StepRange,1}, trgFac::Array{<:Number,3}, srcFac::Array{<:Number,3}, facPar::Array{<:Integer,2}, cmpInf::GlaKerOpt)::Nothing where T<:Union{ComplexF64,ComplexF32} ## calculate domain separation # grid scales of source and target volumes srcGrdScl = getproperty.(srcVol.grd, :step) trgGrdScl = getproperty.(trgVol.grd, :step) # upper and lower edges of the source volume srcEdg = (getproperty.(srcVol.grd, :start) .- (srcVol.scl .//2), getproperty.(srcVol.grd, :stop) .+ (srcVol.scl .//2)) # upper and lower edges of the target volume trgEdg = (getproperty.(trgVol.grd, :start) .- (trgVol.scl .//2), getproperty.(trgVol.grd, :stop) .+ (trgVol.scl .//2)) # check for volume coincidence cinChk = prod((srcEdg[1] .<= trgEdg[1]) .* (trgEdg[1] .<= srcEdg[2])) || prod((srcEdg[1] .<= trgEdg[2]) .* (trgEdg[2] .<= srcEdg[2])) # check for volume overlap ovrChk = sum((srcEdg[1] .< trgEdg[1]) .* (trgEdg[1] .< srcEdg[2])) + sum((srcEdg[1] .< trgEdg[2]) .* (trgEdg[2] .< srcEdg[2])) if cinChk if ovrChk > 0 error("Source and target volumes are overlapping.") end # generate self Green function for contact cells cntVol = genCntVol(trgVol, srcVol) egoCrcCnt = Array{eltype(egoCrcExt)}(undef, 3, 3, (2 .* cntVol.cel)...) genEgoSlf!(egoCrcCnt, cntVol, cmpInf) # pull values for cells in contact @threads for posItr ∈ CartesianIndices(egoCrcExt[1,1,:,:,:]) egoFunExtCnt!(cntVol, view(egoCrcExt, :, :, posItr), egoCrcCnt, posItr, trgVol.cel, sepGrdTrg, sepGrdSrc, trgVol.scl, srcVol.scl, trgFac, srcFac, facPar, cmpInf) end else @threads for posItr ∈ CartesianIndices(egoCrcExt[1,1,:,:,:]) egoFunExt!(view(egoCrcExt, :, :, posItr), posItr, trgVol.cel, sepGrdTrg, sepGrdSrc, trgVol.scl, srcVol.scl, trgFac, srcFac, facPar, cmpInf) end end return nothing end #= Generate circulant vector for self Green function. =# function genEgoCrcSlf!(slfVol::GlaVol, egoCrc::AbstractArray{T,5}, srcGrd::Array{<:StepRange,1}, trgFac::Array{<:AbstractFloat,3}, srcFac::Array{<:AbstractFloat,3}, facPar::Array{<:Integer,2}, cmpInf::GlaKerOpt)::Nothing where T<:Union{ComplexF64,ComplexF32} # allocate intermediate storage for Toeplitz interaction vector egoToe = Array{eltype(egoCrc)}(undef, 3, 3, slfVol.cel...) # write Green function, ignoring weakly singular integrals @threads for crtItr ∈ CartesianIndices(egoToe[1,1,:,:,:]) @inbounds egoFunInn!(egoToe, crtItr, srcGrd, slfVol.scl, trgFac, srcFac, facPar, cmpInf) end # Gauss-Legendre quadrature glQud = gauQud(cmpInf.intOrd) # correction values for singular integrals # return order of normal faces is xx yy zz wS = (^(prod(slfVol.scl), -1) .* wekS(slfVol.scl, glQud, cmpInf)) # return order of normal faces is xxY xxZ yyX yyZ zzX zzY xy xz yz wE = (^(prod(slfVol.scl), -1) .* wekE(slfVol.scl, glQud, cmpInf)) # return order of normal faces is xx yy zz xy xz yz wV = (^(prod(slfVol.scl), -1) .* wekV(slfVol.scl, glQud, cmpInf)) # correct singular integrals for coincident and adjacent cells for posItr ∈ CartesianIndices(ntuple(itr -> min(slfVol.cel[itr], 2), 3)) egoFunSng!(view(egoToe, :, :, posItr), posItr, wS, wE, wV, srcGrd, slfVol, trgFac, srcFac, facPar, cmpInf) end # include identity component egoToe[1,1,1,1,1] -= 1 / (cmpInf.frqPhz^2) egoToe[2,2,1,1,1] -= 1 / (cmpInf.frqPhz^2) egoToe[3,3,1,1,1] -= 1 / (cmpInf.frqPhz^2) # embed self Toeplitz vector into a circulant vector @threads for crtItr ∈ CartesianIndices(egoCrc[1,1,:,:,:]) @inbounds egoToeCrc!(view(egoCrc, :, :, crtItr), egoToe, crtItr, div.(size(egoCrc)[3:5], 2)) end return nothing end #= Generate circulant self Green function from Toeplitz self Green function. The implemented mask takes into account the relative flip in the assumed dipole direction under a coordinate reflection. =# function egoToeCrc!(egoCrc::AbstractArray{T,2}, egoToe::AbstractArray{T,5}, posInd::CartesianIndex{3}, indSpt::Tuple{Vararg{Integer}})::Nothing where T<:Union{ComplexF64,ComplexF32} if posInd[1] == (indSpt[1] + 1) || posInd[2] == (indSpt[2] + 1) || posInd[3] == (indSpt[3] + 1) egoCrc[:,:] .= zeros(eltype(egoCrc), 3, 3) else # flip field under coordinate reflection fi = indFlp(posInd[1], indSpt[1]) fj = indFlp(posInd[2], indSpt[2]) fk = indFlp(posInd[3], indSpt[3]) # embedding egoCrc[:,:] .= view(egoToe, :, :, indSel(posInd[1], indSpt[1]), indSel(posInd[2], indSpt[2]), indSel(posInd[3], indSpt[3])) .* [1.0 (fi * fj) (fi * fk); (fj * fi) 1.0 (fj * fk); (fk * fi) (fk * fj) 1.0] end return nothing end #= Write Green function element for a pair of cubes in distinct domains. Recall that grids span the separations between a pair of volumes. No field flips are required when calculating an external Green function. =# @inline function egoFunExt!(egoCrcExt::AbstractArray{T,2}, posInd::CartesianIndex{3}, indSpt::Union{Array{<:Integer,1},NTuple{3,Integer}}, sepGrdTrg::Array{<:StepRange,1}, sepGrdSrc::Array{<:StepRange,1}, sclTrg::NTuple{3,Number}, sclSrc::NTuple{3,Number}, trgFac::Array{<:Number,3}, srcFac::Array{<:AbstractFloat,3}, facPar::Array{<:Integer,2}, cmpInf::GlaKerOpt)::Nothing where T<:Union{ComplexF64,ComplexF32} if posInd[1] == (indSpt[1] + 1) || posInd[2] == (indSpt[2] + 1) || posInd[3] == (indSpt[3] + 1) egoCrcExt[:,:] .= zeros(eltype(egoCrcExt), 3, 3) else egoFunOut!(egoCrcExt, [grdSel(posInd[1], indSpt[1], 1, sepGrdTrg, sepGrdSrc), grdSel(posInd[2], indSpt[2], 2, sepGrdTrg, sepGrdSrc), grdSel(posInd[3], indSpt[3], 3, sepGrdTrg, sepGrdSrc)], sclTrg, sclSrc, trgFac, srcFac, facPar, cmpInf) end return nothing end #= Write Green element for a pair of cubes in distinct domains, checking for the possibility of contact. Separation grids span the separations between the pair of volumes. No field flip is required for external Green function. =# function egoFunExtCnt!(cntVol::GlaVol, egoCrc::AbstractArray{T,2}, egoCrcCnt::AbstractArray{T,5}, posInd::CartesianIndex{3}, indSpt::NTuple{3,Integer}, sepGrdTrg::Array{<:StepRange,1}, sepGrdSrc::Array{<:StepRange,1}, sclTrg::NTuple{3,Number}, sclSrc::NTuple{3,Number}, trgFac::Array{<:AbstractFloat,3}, srcFac::Array{<:AbstractFloat,3}, facPar::Array{<:Integer,2}, cmpInf::GlaKerOpt)::Nothing where T<:Union{ComplexF64,ComplexF32} # separation vector sepVec = [grdSel(posInd[1], indSpt[1], 1, sepGrdTrg, sepGrdSrc), grdSel(posInd[2], indSpt[2], 2, sepGrdTrg, sepGrdSrc), grdSel(posInd[3], indSpt[3], 3, sepGrdTrg, sepGrdSrc)] # absolute separation absSep = abs.(sepVec) # branch between contact and non-contact cases # contact case if prod(absSep .< (ones(3) .* cntTol .+ ((sclTrg .+ sclSrc) ./ 2.0))) if posInd[1] == (indSpt[1] + 1) || posInd[2] == (indSpt[2] + 1) || posInd[3] == (indSpt[3] + 1) egoCrc[:,:] .= zeros(eltype(egoCrc), 3, 3) else egoCntOut!(cntVol, egoCrcCnt, egoCrc, posInd, sclTrg, sclSrc, sepVec) end # non-contact case else if posInd[1] == (indSpt[1] + 1) || posInd[2] == (indSpt[2] + 1) || posInd[3] == (indSpt[3] + 1) egoCrc[:,:] .= zeros(eltype(egoCrc), 3, 3) else egoFunOut!(egoCrc, sepVec, sclTrg, sclSrc, trgFac, srcFac, facPar, cmpInf) end end return nothing end #= General external Green function interaction element. =# function egoFunOut!(egoCrc::AbstractArray{T,2}, grd::Array{<:AbstractFloat,1}, sclTrg::NTuple{3,Number}, sclSrc::NTuple{3,Number}, trgFac::Array{<:AbstractFloat,3}, srcFac::Array{<:AbstractFloat,3}, facPar::Array{<:Integer,2}, cmpInf::GlaKerOpt)::Nothing where T<:Union{ComplexF64,ComplexF32} srfMat = zeros(eltype(egoCrc), 36) # calculate interaction contributions between all cube faces egoSrfAdp!(grd[1], grd[2], grd[3], srfMat, trgFac, srcFac, 1:36, facPar, srfScl(sclTrg, sclSrc), cmpInf) # sum contributions depending on source and target current orientation srfSum!(egoCrc, srfMat) return nothing end #= Compute Green function element for cells in contact. =# function egoCntOut!(cntVol::GlaVol, egoCrcCnt::Array{T,5}, egoCrc::AbstractArray{T,2}, posInd::CartesianIndex{3}, sclTrg::NTuple{3,Number}, sclSrc::NTuple{3,Number}, sepVec::Array{<:AbstractFloat,1})::Nothing where T<:Union{ComplexF64,ComplexF32} # safety zero local section of the Green function egoCrc[:,:] .= zeros(ComplexF64, 3, 3) # contact cell locations srcCellLocs = [[1,1,1], [Int(sclSrc[dir] / cntVol.scl[dir]) for dir ∈ 1:3]] trgCellSpan = [Int(sclTrg[dir] / cntVol.scl[dir]) for dir ∈ 1:3] trgCellLocs = [[1,1,1], [1,1,1]] sepCellSpan = [sepVec[dir] / Float64(cntVol.scl[dir]) for dir ∈ 1:3] # positions of target cells # lower cell boundaries trgCellLocs[1] = Int.(round.(sepCellSpan + (srcCellLocs[2] ./ 2.0) - (trgCellSpan ./ 2.0))) + [1,1,1] # upper cell boundaries trgCellLocs[2] = Int.(round.(sepCellSpan + (srcCellLocs[2] ./ 2.0) + (trgCellSpan ./ 2.0))) # shift cell locations into contact volume for dir ∈ 1:3 if trgCellLocs[1][dir] < 1 # must update target cell lower bound last for ind ∈ 1:2 srcCellLocs[ind][dir] = srcCellLocs[ind][dir] + abs(trgCellLocs[1][dir]) + 1 end # target cells for ind ∈ 2:-1:1 trgCellLocs[ind][dir] = trgCellLocs[ind][dir] + abs(trgCellLocs[1][dir]) + 1 end end end # loop over contact cells for indSrc ∈ CartesianIndices((srcCellLocs[1][1]:srcCellLocs[2][1], srcCellLocs[1][2]:srcCellLocs[2][2], srcCellLocs[1][3]:srcCellLocs[2][3])) for indTrg ∈ CartesianIndices((trgCellLocs[1][1]:trgCellLocs[2][1], trgCellLocs[1][2]:trgCellLocs[2][2], trgCellLocs[1][3]:trgCellLocs[2][3])) # add result to element calculation egoCrc[:,:] .+= egoCrcCnt[:,:, crcIndClc(cntVol, indTrg, indSrc)] end end totTrgCells = (trgCellLocs[2][3] - trgCellLocs[1][3] + 1) * (trgCellLocs[2][2] - trgCellLocs[1][2] + 1) * (trgCellLocs[2][1] - trgCellLocs[1][1] + 1) egoCrc[:,:] .= egoCrc[:,:] ./ totTrgCells return nothing end #= Create contact volume for self Green function calculations. =# function genCntVol(trgVol::GlaVol, srcVol::GlaVol)::GlaVol # scale for greatest common division of source and target cells cntScl = min.(trgVol.scl, srcVol.scl) # divisions of target and source cells trgDiv = Integer.(trgVol.scl ./ cntScl) srcDiv = Integer.(srcVol.scl ./ cntScl) # create padded self interaction domain for simplification of code cntCel = (trgDiv[1] + srcDiv[1], trgDiv[2] + srcDiv[2], trgDiv[3] + srcDiv[3]) return GlaVol(cntCel, cntScl, (0//1, 0//1, 0//1)) end #= General self Green function interaction element. =# function egoFunInn!(egoToe::AbstractArray{T,5}, posInd::CartesianIndex{3}, srcGrd::Array{<:StepRange,1}, scl::NTuple{3,Number}, trgFac::Array{<:AbstractFloat,3}, srcFac::Array{<:AbstractFloat,3}, facPar::Array{<:Integer,2}, cmpInf::GlaKerOpt)::Nothing where T<:Union{ComplexF64,ComplexF32} srfMat = zeros(eltype(egoToe), 36) # calculate interaction contributions between all cube faces if (posInd[1] > 2) || (posInd[2] > 2) || (posInd[3] > 2) egoSrfAdp!(Float64(srcGrd[1][posInd[1]]), Float64(srcGrd[2][posInd[2]]), Float64(srcGrd[3][posInd[3]]), srfMat, trgFac, srcFac, 1:36, facPar, Float64.(srfScl(scl, scl)), cmpInf) # add contributions based on source and target current orientation srfSum!(view(egoToe, :, :, posInd), srfMat) end return nothing end #= Calculate Green function elements for adjacent cubes, assumed to be in the same domain. wS, wE, and wV refer to self-intersecting, edge intersecting, and vertex intersecting cube face integrals respectively. In the wE and wV cases, the first value returned is for in-plane faces, and the second value is for ``cornered'' faces. The convention by which facePairs are generated begins by looping over the source faces. Because of this choice, the transpose of the mask follows the standard source to target matrix convention used elsewhere. =# function egoFunSng!(egoCrc::AbstractArray{T,2}, posInd::CartesianIndex{3}, wS::Vector{R}, wE::Vector{R}, wV::Vector{R}, srcGrd::Array{<:StepRange,1}, slfVol::GlaVol, trgFac::Array{<:AbstractFloat,3}, srcFac::Array{<:AbstractFloat,3}, facPar::Array{<:Integer,2}, cmpInf::GlaKerOpt)::Nothing where {T<:Union{ComplexF64,ComplexF32}, R<:Union{ComplexF64,ComplexF32}} srfMat = zeros(eltype(egoCrc), 36) # linear index conversion linCon = LinearIndices((1:6, 1:6)) # face convention yzL yzU (x-faces) xzL xzU (y-faces) xyL xyU (z-faces) # index based corrections. if posInd == CartesianIndex(1, 1, 1) corVal = [ wS[1] 0.0 wE[7] wE[7] wE[8] wE[8] 0.0 wS[1] wE[7] wE[7] wE[8] wE[8] wE[7] wE[7] wS[2] 0.0 wE[9] wE[9] wE[7] wE[7] 0.0 wS[2] wE[9] wE[9] wE[8] wE[8] wE[9] wE[9] wS[3] 0.0 wE[8] wE[8] wE[9] wE[9] 0.0 wS[3]] mask =[ 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1] elseif posInd == CartesianIndex(2, 1, 1) && slfVol.scl[1] == getproperty(slfVol.grd[1], :step) corVal = [ 0.0 wS[1] wE[7] wE[7] wE[8] wE[8] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 wE[7] wE[3] 0.0 wV[6] wV[6] 0.0 wE[7] 0.0 wE[3] wV[6] wV[6] 0.0 wE[8] wV[6] wV[6] wE[5] 0.0 0.0 wE[8] wV[6] wV[6] 0.0 wE[5]] mask = [ 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 0 1 1 0 1 0 1 1 1 0 1 1 1 1 0 0 1 1 1 0 1] elseif posInd == CartesianIndex(2, 1, 2) && slfVol.scl[1] == getproperty(slfVol.grd[1], :step) && slfVol.scl[3] == getproperty(slfVol.grd[3], :step) corVal = [ 0.0 wE[2] wV[4] wV[4] 0.0 wE[8] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 wV[4] wV[2] 0.0 0.0 wV[6] 0.0 wV[4] 0.0 wV[2] 0.0 wV[6] 0.0 wE[8] wV[6] wV[6] 0.0 wE[5] 0.0 0.0 0.0 0.0 0.0 0.0] mask = [ 0 1 1 1 0 1 0 0 0 0 0 0 0 1 1 0 0 1 0 1 0 1 0 1 0 1 1 1 0 1 0 0 0 0 0 0] elseif posInd == CartesianIndex(1, 1, 2) && slfVol.scl[3] == getproperty(slfVol.grd[3], :step) corVal = [ wE[2] 0.0 wV[4] wV[4] 0.0 wE[8] 0.0 wE[2] wV[4] wV[4] 0.0 wE[8] wV[4] wV[4] wE[4] 0.0 0.0 wE[9] wV[4] wV[4] 0.0 wE[4] 0.0 wE[9] wE[8] wE[8] wE[9] wE[9] 0.0 wS[3] 0.0 0.0 0.0 0.0 0.0 0.0] mask = [ 1 0 1 1 0 1 0 1 1 1 0 1 1 1 1 0 0 1 1 1 0 1 0 1 1 1 1 1 0 1 0 0 0 0 0 0] elseif posInd == CartesianIndex(1, 2, 1) && slfVol.scl[2] == getproperty(slfVol.grd[2], :step) corVal = [ wE[1] 0.0 0.0 wE[7] wV[5] wV[5] 0.0 wE[1] 0.0 wE[7] wV[5] wV[5] wE[7] wE[7] 0.0 wS[2] wE[9] wE[9] 0.0 0.0 0.0 0.0 0.0 0.0 wV[5] wV[5] 0.0 wE[9] wE[6] 0.0 wV[5] wV[5] 0.0 wE[9] 0.0 wE[6]] mask = [ 1 0 0 1 1 1 0 1 0 1 1 1 1 1 0 1 1 1 0 0 0 0 0 0 1 1 0 1 1 0 1 1 0 1 0 1] elseif posInd == CartesianIndex(2, 2, 1) && slfVol.scl[1] == getproperty(slfVol.grd[1], :step) && slfVol.scl[2] == getproperty(slfVol.grd[2], :step) corVal = [ 0.0 wE[1] 0.0 wE[7] wV[5] wV[5] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 wE[7] 0.0 wE[3] wV[6] wV[6] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 wV[5] 0.0 wV[6] wV[3] 0.0 0.0 wV[5] 0.0 wV[6] 0.0 wV[3]] mask = [ 0 1 0 1 1 1 0 0 0 0 0 0 0 1 0 1 1 1 0 0 0 0 0 0 0 1 0 1 1 0 0 1 0 1 0 1] elseif posInd == CartesianIndex(1, 2, 2) && slfVol.scl[2] == getproperty(slfVol.grd[2], :step) && slfVol.scl[3] == getproperty(slfVol.grd[3], :step) corVal = [ wV[1] 0.0 0.0 wV[4] 0.0 wV[5] 0.0 wV[1] 0.0 wV[4] 0.0 wV[5] wV[4] wV[4] 0.0 wE[4] 0.0 wE[9] 0.0 0.0 0.0 0.0 0.0 0.0 wV[5] wV[5] 0.0 wE[9] 0.0 wE[6] 0.0 0.0 0.0 0.0 0.0 0.0] mask = [ 1 0 0 1 0 1 0 1 0 1 0 1 1 1 0 1 0 1 0 0 0 0 0 0 1 1 0 1 0 1 0 0 0 0 0 0] elseif posInd == CartesianIndex(2, 2, 2) && slfVol.scl[1] == getproperty(slfVol.grd[1], :step) && slfVol.scl[2] == getproperty(slfVol.grd[2], :step) && slfVol.scl[3] == getproperty(slfVol.grd[3], :step) corVal = [ 0.0 wV[1] 0.0 wV[4] 0.0 wV[5] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 wV[4] 0.0 wV[2] 0.0 wV[6] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 wV[5] 0.0 wV[6] 0.0 wV[3] 0.0 0.0 0.0 0.0 0.0 0.0] mask = [ 0 1 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0] else println("empty case selected.") corVal = [ 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0] mask = [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] end # include uncorrected surface integrals pairListUn = linCon[findall(iszero, transpose(mask))] egoSrfAdp!(Float64(srcGrd[1][posInd[1]]), Float64(srcGrd[2][posInd[2]]), Float64(srcGrd[3][posInd[3]]), srfMat, trgFac, srcFac, pairListUn, facPar, Float64.(srfScl(slfVol.scl, slfVol.scl)), cmpInf) # correct values of srfMat where needed for fp ∈ 1:36 if mask[facPar[fp,1], facPar[fp,2]] == 1 srfMat[fp] = corVal[facPar[fp,1], facPar[fp,2]] end end # overwrite problematic elements of Green function matrix srfSum!(egoCrc, srfMat) return nothing end #= Update egoCrc to hold Green function interactions. The storage format of egoCrc is [[ii, ji, ki]^{T}; [ij, jj, kj]^{T}; [ik, jk, kk]^{T}]. See documentation for explanation. =# function srfSum!(egoCrc::AbstractArray{T,2}, srfMat::Array{T,1})::Nothing where T<:Union{ComplexF64,ComplexF32} # ii egoCrc[1,1] = srfMat[15] - srfMat[16] - srfMat[21] + srfMat[22] + srfMat[29] - srfMat[30] - srfMat[35] + srfMat[36] # ji egoCrc[2,1] = - srfMat[13] + srfMat[14] + srfMat[19] - srfMat[20] # ki egoCrc[3,1] = - srfMat[25] + srfMat[26] + srfMat[31] - srfMat[32] # ij egoCrc[1,2] = - srfMat[3] + srfMat[4] + srfMat[9] - srfMat[10] # jj egoCrc[2,2] = srfMat[1] - srfMat[2] - srfMat[7] + srfMat[8] + srfMat[29] - srfMat[30] - srfMat[35] + srfMat[36] # kj egoCrc[3,2] = - srfMat[27] + srfMat[28] + srfMat[33] - srfMat[34] # ik egoCrc[1,3] = - srfMat[5] + srfMat[6] + srfMat[11] - srfMat[12] # jk egoCrc[2,3] = - srfMat[17] + srfMat[18] + srfMat[23] - srfMat[24] # kk egoCrc[3,3] = srfMat[1] - srfMat[2] - srfMat[7] + srfMat[8] + srfMat[15] - srfMat[16] - srfMat[21] + srfMat[22] return nothing end #= Adaptive integration of the Green function over face pairs. =# function egoSrfAdp!(grdX::AbstractFloat, grdY::AbstractFloat, grdZ::AbstractFloat, srfMat::Array{T,1}, trgFac::Array{<:AbstractFloat,3}, srcFac::Array{<:AbstractFloat,3}, pairList::Union{UnitRange{<:Integer},Array{<:Integer,1}}, facPar::Array{<:Integer,2}, srfScales::Array{<:AbstractFloat,1}, cmpInf::GlaKerOpt)::Nothing where T<:Union{ComplexF64,ComplexF32} # container for intermediate integral evaluation intVal = [0.0,0.0] @inbounds for fp ∈ pairList srfMat[fp] = 0.0 + 0.0im # define integration kernel intKer = (ordVec::Array{<:AbstractFloat,1}, vals::Array{<:AbstractFloat,1}) -> srfKer(ordVec, vals, grdX, grdY, grdZ, fp, trgFac, srcFac, facPar, cmpInf) # surface integration intVal[:] = hcubature(2, intKer, [0.0,0.0,0.0,0.0], [1.0,1.0,1.0,1.0], reltol = cubRelTol, abstol = cubAbsTol, maxevals = 0, error_norm = Cubature.INDIVIDUAL)[1]; srfMat[fp] = intVal[1] + im * intVal[2] # scaling correction srfMat[fp] *= srfScales[fp] end return nothing end #= Integration kernel for Green function surface integrals. =# function srfKer(ordVec::Array{<:AbstractFloat,1}, vals::Array{<:AbstractFloat,1}, grdX::AbstractFloat, grdY::AbstractFloat, grdZ::AbstractFloat, fp::Integer, trgFac::Array{<:AbstractFloat,3}, srcFac::Array{<:AbstractFloat,3}, facPar::Array{<:Integer,2}, cmpInf::GlaKerOpt)::Nothing # value of scalar Green function z = sclEgo(dstMag( cubVecAltAdp(1, ordVec, fp, trgFac, srcFac, facPar) + grdX, cubVecAltAdp(2, ordVec, fp, trgFac, srcFac, facPar) + grdY, cubVecAltAdp(3, ordVec, fp, trgFac, srcFac, facPar) + grdZ), cmpInf.frqPhz) vals[:] = [real(z),imag(z)] return nothing end #= Create grid of spanning separations for a pair of volumes. The flipped separation grid is used when generating the circulant vector. =# function sepGrd(trgVol::GlaVol, srcVol::GlaVol, flip::Integer)::Array{<:StepRange,1} # grid over the source volume if flip == 1 sep = getproperty.(srcVol.grd, :step) str = getproperty.(trgVol.grd, :start) .- getproperty.(srcVol.grd, :stop) stp = getproperty.(trgVol.grd, :start) .- getproperty.(srcVol.grd, :start) # grid over the target volume else sep = getproperty.(trgVol.grd, :step) str = getproperty.(trgVol.grd, :start) .- getproperty.(srcVol.grd, :start) stp = getproperty.(trgVol.grd, :stop) .- getproperty.(srcVol.grd, :start) end # match step to separation orientation for dir ∈ 1:3 if stp[dir] < str[dir] sep[dir] *= -1 end end return map(StepRange, str, sep, stp) end #= Return the separation between two elements from circulant embedding indices and domain grids. =# @inline function grdSel(ind::Integer, indSpt::Integer, dir::Integer, trgGrd::Array{<:StepRange,1}, srcGrd::Array{<:StepRange,1})::Float64 if ind <= indSpt return Float64(trgGrd[dir][ind]) else if ind > (1 + indSpt) ind -= 1 end return Float64(srcGrd[dir][ind - indSpt]) end end #= Return a reference index relative to the embedding index of the Green function. =# @inline function indSel(posInd::T, indSpt::R)::CartesianIndex where {T<:Union{CartesianIndex, Tuple{Vararg{Integer}}, Integer}, R<:Union{CartesianIndex, Tuple{Vararg{Integer}}, Integer}} return CartesianIndex(map((x, y) -> x <= y ? x : (x == y + 1 ? 2 * y - x + 1 : 2 * y - x + 2), Tuple(posInd), Tuple(indSpt))) end #= Flip dipole direction based on index values. =# @inline function indFlp(posInd::Integer, indSpt::Integer)::Float64 return posInd <= indSpt ? 1.0 : -1.0 end #= Calculate circulant index for self Green function vector =# @inline function crcIndClc(cntVol::GlaVol, trgInd::CartesianIndex{3}, srcInd::CartesianIndex{3})::CartesianIndex{3} # separation in terms of cells cellInd = trgInd - srcInd # cellInd[dir] is always added because the value is negative if true return cellInd + CartesianIndex(ntuple(itr -> (cellInd[itr] < 0) * 2 * cntVol.cel[itr] + 1, 3)) end #= Returns locations and weights for 1D Gauss-Legendre quadrature. Order must be an integer between 1 and 64. The first column of the returned array is positions, on the interval [-1,1], the second column contains the associated weights. Options: gausschebyshev(), gausslegendre(), gaussjacobi(), gaussradau(), gausslobatto(), gausslaguerre(), gausshermite() =# function gauQud(ord::Int64)::Array{Float64,2} pos, val = gausslegendre(ord) return [pos ;; val] end
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
20744
#= Conventions for the values returned by the weak functions. Small letters correspond to normal face directions; capital letters correspond to grid increment directions. Self xx yy zz 1 2 3 Edge xxY xxZ yyX yyZ zzX zzY xy xz yz 1 2 3 4 5 6 7 8 9 Vertex xx yy zz xy xz yz 1 2 3 4 5 6 GilaWInt contains all necessary support functions for numerical integration of the electromagnetic Green function. This code is translated from DIRECTFN_E by Athanasios Polimeridis, and is distributed under the GNU LGPL. Author: Sean Molesky Reference: Polimeridis AG, Vipiana F, Mosig JR, Wilton DR. DIRECTFN: Fully numerical algorithms for high precision computation of singular integrals in Galerkin SIE methods. IEEE Transactions on Antennas and Propagation. 2013; 61(6):3112-22. In what follows the word weak is used in reference to the fact that the scalar Green function surface integral is weakly singular: the integrand exhibits a singularity proportional to the inverse of the separation distance. The letters S, E and V refer, respectively, to integration over self-adjacent triangles, edge-adjacent triangles, and vertex-adjacent triangles. The article cited above contains useful error comparison plots for the number evaluation points considered. =# const π = 3.1415926535897932384626433832795028841971693993751058209749445923 #= Returns the scalar (Helmholtz) Green function. The separation dstMag is assumed to be scaled by wavelength. =# @inline function sclEgo(dstMag::AbstractFloat, frqPhz::T)::ComplexF64 where T<:Union{ComplexF64,ComplexF32} return exp(2im * π * dstMag * frqPhz) / (4 * π * dstMag * frqPhz^2) end #= Returns the scalar (Helmholtz) Green function with the singularity removed. The separation distance dstMag is assumed to be scaled by the wavelength. The function is used in the included glaIntSup.jl code to improve the convergence of all weakly singular integrals. =# @inline function sclEgoN(dstMag::AbstractFloat, frqPhz::T)::ComplexF64 where T<:Union{ComplexF64,ComplexF32} if dstMag > 1e-7 return (exp(2im * π * dstMag * frqPhz) - 1) / (4 * π * dstMag * frqPhz^2) else return ((im / frqPhz) - π * dstMag) / 2 end end #= Returns the three dimensional Euclidean norm of a vector. =# @inline function dstMag(v1::AbstractFloat, v2::AbstractFloat, v3::AbstractFloat)::Float64 return sqrt(v1^2 + v2^2 + v3^2) end #= Head function for integration over coincident square panels. The scl vector contains the characteristic lengths of a cuboid voxel relative to the wavelength. glQud1 is an array of Gauss-Legendre quadrature weights and positions. The cmpInf parameter determines the level of precision used for integral calculations. Namely, cmpInf.intOrd is used internally in all weakly singular integral computations. =# function wekS(scl::NTuple{3,Number}, glQud1::Array{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::Array{ComplexF64,1} grdPts = Array{Float64}(undef, 3, 18) # weak self integrals for the three characteristic faces of a cuboid # dir = 1 -> xy face (z-nrm) dir = 2 -> xz face (y-nrm) # dir = 3 -> yz face (x-nrm) return [wekSDir(3, scl, grdPts, glQud1, cmpInf) + rSrfSlf(Float64(scl[2]), Float64(scl[3]), cmpInf); wekSDir(2, scl, grdPts, glQud1, cmpInf) + rSrfSlf(Float64(scl[1]), Float64(scl[3]), cmpInf); wekSDir(1, scl, grdPts, glQud1, cmpInf) + rSrfSlf(Float64(scl[1]), Float64(scl[2]), cmpInf)] end #= Weak self-integral of a particular face. =# function wekSDir(dir::Integer, scl::NTuple{3,Number}, grdPts::Array{<:AbstractFloat,2}, glQud1::Array{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::ComplexF64 wekGrdPts!(dir, scl, grdPts) return ((( wekSInt(hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5]), glQud1, cmpInf) + wekSInt(hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4]), glQud1, cmpInf) + wekEInt(hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,1], grdPts[:,5], grdPts[:,4]), glQud1, cmpInf) + wekEInt(hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,1], grdPts[:,2], grdPts[:,5]), glQud1, cmpInf)) + ( wekSInt(hcat(grdPts[:,4], grdPts[:,1], grdPts[:,2]), glQud1, cmpInf) + wekSInt(hcat(grdPts[:,4], grdPts[:,2], grdPts[:,5]), glQud1, cmpInf) + wekEInt(hcat(grdPts[:,4], grdPts[:,1], grdPts[:,2], grdPts[:,4], grdPts[:,2], grdPts[:,5]), glQud1, cmpInf) + wekEInt(hcat(grdPts[:,4], grdPts[:,2], grdPts[:,5], grdPts[:,4], grdPts[:,1], grdPts[:,2]), glQud1, cmpInf))) / 2.0) end #= Head function for integration over edge adjacent square panels. See wekS for input parameter descriptions. =# function wekE(scl::NTuple{3,Number}, glQud1::Array{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::Array{ComplexF64,1} grdPts = Array{Float64,2}(undef, 3, 18) # labels are panelDir-panelDir-gridIncrement vals = wekEDir(3, scl, grdPts, glQud1, cmpInf) # lower case letters reference the normal directions of the rectangles # upper case letter reference the increasing axis direction when necessary # first set xxY = vals[1] + rSrfEdgFlt(Float64(scl[3]), Float64(scl[2]), cmpInf) xxZ = vals[3] + rSrfEdgFlt(Float64(scl[2]), Float64(scl[3]), cmpInf) xyA = vals[2] + rSrfEdgCrn(Float64(scl[3]), Float64(scl[2]), Float64(scl[1]), cmpInf) xzA = vals[4] + rSrfEdgCrn(Float64(scl[2]), Float64(scl[3]), Float64(scl[1]), cmpInf) vals = wekEDir(2, scl, grdPts, glQud1, cmpInf) # second set yyZ = vals[1] + rSrfEdgFlt(Float64(scl[1]), Float64(scl[3]), cmpInf) yyX = vals[3] + rSrfEdgFlt(Float64(scl[3]), Float64(scl[1]), cmpInf) yzA = vals[2] + rSrfEdgCrn(Float64(scl[1]), Float64(scl[3]), Float64(scl[2]), cmpInf) xyB = vals[4] + rSrfEdgCrn(Float64(scl[3]), Float64(scl[2]), Float64(scl[1]), cmpInf) vals = wekEDir(1, scl, grdPts, glQud1, cmpInf) # third set zzX = vals[1] + rSrfEdgFlt(Float64(scl[2]), Float64(scl[1]), cmpInf) zzY = vals[3] + rSrfEdgFlt(Float64(scl[1]), Float64(scl[2]), cmpInf) xzB = vals[2] + rSrfEdgCrn(Float64(scl[2]), Float64(scl[3]), Float64(scl[1]), cmpInf) yzB = vals[4] + rSrfEdgCrn(Float64(scl[1]), Float64(scl[3]), Float64(scl[2]), cmpInf) return [xxY; xxZ; yyX; yyZ; zzX; zzY; (xyA + xyB) / 2.0; (xzA + xzB) / 2.0; (yzA + yzB) / 2.0] end #= Weak edge integrals for a given face as specified by dir. dir = 1 -> z face -> [y-edge (++ gridX): zz(x), xz(x); x-edge (++ gridY) zz(y) yz(y)] dir = 2 -> y face -> [x-edge (++ gridZ): yy(z), yz(z); z-edge (++ gridX) yy(x) xy(x)] dir = 3 -> x face -> [z-edge (++ gridY): xx(y), xy(y); y-edge (++ gridZ) xx(z) xz(z)] =# function wekEDir(dir::Integer, scl::NTuple{3,Number}, grdPts::Array{<:AbstractFloat,2}, glQud1::Array{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::Array{ComplexF64,1} wekGrdPts!(dir, scl, grdPts) return [wekEInt(hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,2], grdPts[:,3], grdPts[:,5]), glQud1, cmpInf) + wekVInt(true, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,3], grdPts[:,6], grdPts[:,5]), glQud1, cmpInf) + wekVInt(true, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,2], grdPts[:,3], grdPts[:,5]), glQud1, cmpInf) + wekVInt(true, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,3], grdPts[:,6], grdPts[:,5]), glQud1, cmpInf); wekEInt(hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,2], grdPts[:,11], grdPts[:,5]), glQud1, cmpInf) + wekVInt(true, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,11], grdPts[:,14], grdPts[:,5]), glQud1, cmpInf) + wekVInt(true, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,2], grdPts[:,11], grdPts[:,5]), glQud1, cmpInf) + wekVInt(true, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,11], grdPts[:,14], grdPts[:,5]), glQud1, cmpInf); wekVInt(true, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,4], grdPts[:,5], grdPts[:,7]), glQud1, cmpInf) + wekVInt(true, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,5], grdPts[:,8], grdPts[:,7]), glQud1, cmpInf) + wekEInt(hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,4], grdPts[:,5], grdPts[:,7]), glQud1, cmpInf) + wekVInt(true, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,5], grdPts[:,8], grdPts[:,7]), glQud1, cmpInf); wekVInt(true, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,4], grdPts[:,5], grdPts[:,13]), glQud1, cmpInf) + wekVInt(true, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,5], grdPts[:,14], grdPts[:,13]), glQud1, cmpInf) + wekEInt(hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,4], grdPts[:,5], grdPts[:,13]), glQud1, cmpInf) + wekVInt(true, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,5], grdPts[:,14], grdPts[:,13]), glQud1, cmpInf)] end #= Head function returning integral values for the Ego function over vertex adjacent square panels. See wekS for input parameter descriptions. =# function wekV(scl::NTuple{3,Number}, glQud1::Array{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::Array{ComplexF64,1} grdPts = Array{Float64,2}(undef,3,18) # vertex integrals for x-normal face vals = wekVDir(3, scl, grdPts, glQud1, cmpInf) xxO = vals[1] xyA = vals[2] xzA = vals[3] # vertex integrals for y-normal face vals = wekVDir(2, scl, grdPts, glQud1, cmpInf) yyO = vals[1] yzA = vals[2] xyB = vals[3] # vertex integrals for z-normal face vals = wekVDir(1, scl, grdPts, glQud1, cmpInf) zzO = vals[1] xzB = vals[2] yzB = vals[3] return[xxO; yyO; zzO; (xyA + xyB) / 2.0; (xzA + xzB) / 2.0; (yzA + yzB) / 2.0] end #= Weak edge integrals for a given face as specified by dir. dir = 1 -> z face -> [zz zx zy] dir = 2 -> y face -> [yy yz yx] dir = 3 -> x face -> [xx xy xz] =# function wekVDir(dir::Integer, scl::NTuple{3,Number}, grdPts::Array{<:AbstractFloat,2}, glQud1::Array{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::Array{ComplexF64,1} wekGrdPts!(dir, scl, grdPts) return [wekVInt(false, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,5], grdPts[:,6], grdPts[:,9]), glQud1, cmpInf) + wekVInt(false, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,5], grdPts[:,9], grdPts[:,8]), glQud1, cmpInf) + wekVInt(false, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,5], grdPts[:,6], grdPts[:,9]), glQud1, cmpInf) + wekVInt(false, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,5], grdPts[:,9], grdPts[:,8]), glQud1, cmpInf); wekVInt(false, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,5], grdPts[:,17], grdPts[:,14]), glQud1, cmpInf) + wekVInt(false, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,5], grdPts[:,8], grdPts[:,17]), glQud1, cmpInf) + wekVInt(false, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,5], grdPts[:,17], grdPts[:,14]), glQud1, cmpInf) + wekVInt(false, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,5], grdPts[:,8], grdPts[:,17]), glQud1, cmpInf); wekVInt(false, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,5], grdPts[:,15], grdPts[:,14]), glQud1, cmpInf) + wekVInt(false, hcat(grdPts[:,1], grdPts[:,2], grdPts[:,5], grdPts[:,5], grdPts[:,6], grdPts[:,15]), glQud1, cmpInf) + wekVInt(false, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,5], grdPts[:,15], grdPts[:,14]), glQud1, cmpInf) + wekVInt(false, hcat(grdPts[:,1], grdPts[:,5], grdPts[:,4], grdPts[:,5], grdPts[:,6], grdPts[:,15]), glQud1, cmpInf)] end #= Generate all unique pairs of cube faces. =# function facPar()::Array{Integer,2} fPairs = Array{Integer,2}(undef, 36, 2) for i ∈ 1:6, j ∈ 1:6 k = (i - 1) * 6 + j fPairs[k,1] = i fPairs[k,2] = j end return fPairs end #= Determine scaling factors for surface integrals. =# function srfScl(sclT::NTuple{3,Number}, sclS::NTuple{3,Number})::Array{Float64,1} srcScl = 1.0 trgScl = 1.0 srfScl = Array{Float64,1}(undef, 36) for srcFId ∈ 1 : 6 if srcFId == 1 || srcFId == 2 srcScl = sclS[2] * sclS[3] elseif srcFId == 3 || srcFId == 4 srcScl = sclS[1] * sclS[3] else srcScl = sclS[1] * sclS[2] end # target scaling has been switched to source scaling for trgFId ∈ 1 : 6 if trgFId == 1 || trgFId == 2 trgScl = sclT[1] elseif trgFId == 3 || trgFId == 4 trgScl = sclT[2] else trgScl = sclT[3] end srfScl[(srcFId - 1) * 6 + trgFId] = Float64(srcScl / trgScl) end end return srfScl end #= Generate array of cuboid faces based from a characteristic size, l[]. L and U reference relative positions on the corresponding normal axis. Points are number in a counter-clockwise convention when viewing the face from the exterior of the cube. =# function cubFac(size::NTuple{3,Number})::Array{Float64,3} yzL = hcat([-size[1], -size[2], -size[3]], [-size[1], size[2], -size[3]], [-size[1], size[2], size[3]], [-size[1], -size[2], size[3]]) ./ 2 yzU = hcat([size[1], -size[2], -size[3]], [size[1], -size[2], size[3]], [size[1], size[2], size[3]], [size[1], size[2], -size[3]]) ./ 2 xzL = hcat([-size[1], -size[2], -size[3]], [-size[1], -size[2], size[3]], [size[1], -size[2], size[3]], [size[1], -size[2], -size[3]]) ./ 2 xzU = hcat([-size[1], size[2], -size[3]], [size[1], size[2], -size[3]], [size[1], size[2], size[3]], [-size[1], size[2], size[3]]) ./ 2 xyL = hcat([-size[1], -size[2], -size[3]], [size[1], -size[2], -size[3]], [size[1], size[2], -size[3]], [-size[1], size[2], -size[3]]) ./ 2 xyU = hcat([-size[1], -size[2], size[3]], [-size[1], size[2], size[3]], [size[1], size[2], size[3]], [size[1], -size[2], size[3]]) ./ 2 return cat(yzL, yzU, xzL, xzU, xyL, xyU, dims = 3) end #= Determine a directional component, set by dir, of the separation vector for a pair points, as determined by ord, which may take on values between zero and one. The first pair of entries are coordinates in the source surface, the second pair of entries are coordinates in the target surface. =# @inline function cubVecAltAdp(dir::Integer, ordVec::Array{<:AbstractFloat,1}, fp::Integer, trgFaces::Array{<:AbstractFloat,3}, srcFaces::Array{<:AbstractFloat,3}, fPairs::Array{<:Integer,2})::Float64 return (trgFaces[dir,1,fPairs[fp,1]] + ordVec[3] * (trgFaces[dir,2,fPairs[fp,1]] - trgFaces[dir,1,fPairs[fp,1]]) + ordVec[4] * (trgFaces[dir,4,fPairs[fp,1]] - trgFaces[dir,1,fPairs[fp,1]])) - (srcFaces[dir,1,fPairs[fp,2]] + ordVec[1] * (srcFaces[dir,2,fPairs[fp,2]] - srcFaces[dir,1,fPairs[fp,2]]) + ordVec[2] * (srcFaces[dir,4,fPairs[fp,2]] - srcFaces[dir,1,fPairs[fp,2]])) end #= Create grid point system for calculation for calculation of weakly singular integrals. =# function wekGrdPts!(dir::Integer, scl::NTuple{3,Number}, grdPts::Array{<:AbstractFloat,2})::Nothing if dir == 1 # standard orientation gridX = Float64(scl[1]) gridY = Float64(scl[2]) gridZ = Float64(scl[3]) elseif dir == 2 # single coordinate rotation gridX = Float64(scl[3]) gridY = Float64(scl[1]) gridZ = Float64(scl[2]) elseif dir == 3 # double coordinate rotation gridX = Float64(scl[2]) gridY = Float64(scl[3]) gridZ = Float64(scl[1]) else error("Invalid direction selection.") end grdPts[:,1] = [0.0; 0.0; 0.0] grdPts[:,2] = [gridX; 0.0; 0.0] grdPts[:,3] = [2.0 * gridX; 0.0; 0.0] grdPts[:,4] = [0.0; gridY; 0.0] grdPts[:,5] = [gridX; gridY; 0.0] grdPts[:,6] = [2.0 * gridX; gridY; 0.0] grdPts[:,7] = [0.0; 2.0 * gridY; 0.0] grdPts[:,8] = [gridX; 2.0 * gridY; 0.0] grdPts[:,9] = [2.0 * gridX; 2.0 * gridY; 0.0] grdPts[:,10] = [0.0; 0.0; gridZ] grdPts[:,11] = [gridX; 0.0; gridZ] grdPts[:,12] = [2.0 * gridX; 0.0; gridZ] grdPts[:,13] = [0.0; gridY; gridZ] grdPts[:,14] = [gridX; gridY; gridZ] grdPts[:,15] = [2.0 * gridX; gridY; gridZ] grdPts[:,16] = [0.0; 2.0 * gridY; gridZ] grdPts[:,17] = [gridX; 2.0 * gridY; gridZ] grdPts[:,18] = [2.0 * gridX; 2.0 * gridY; gridZ] return nothing end #= The code contained in glaIntSup evaluates the integrands called by the wekS, wekE, and wekV head functions using a series of variable transformations and analytic integral evaluations---reducing the four dimensional surface integrals performed for ``standard'' cells to chains of one dimensional integrals. No comments are included in this low level code, which is simply a julia translation of DIRECTFN_E by Athanasios Polimeridis with added support for multi-threading. For a complete description of the steps being performed see the article cited above and references included therein. =# include("glaIntSup.jl") #= Direct evaluation of 1 / (4 * π * dstMag) integral for a square panel with itself. la and lb are the edge lengths. =# @inline function rSrfSlf(la::AbstractFloat, lb::AbstractFloat, cmpInf::GlaKerOpt)::ComplexF64 return (1 / (48 * π * cmpInf.frqPhz^2)) * (8 * la^3 + 8 * lb^3 - 8 * la^2 * sqrt(la^2 + lb^2) - 8 * lb^2 * sqrt(la^2 + lb^2) - 3 * la^2 * lb * (2 * log(la) + 2 * log(la + lb - sqrt(la^2 + lb^2)) + log(sqrt(la^2 + lb^2) - lb) - 5 * log(lb + sqrt(la^2 + lb^2)) - 2 * log(lb - la + sqrt(la^2 + lb^2)) - 2 * log(la + 2 * lb - sqrt(la^2 + 4 * lb^2)) + log(sqrt(la^2 + 4 * lb^2) - 2 * lb) + 2 * log(la - 2 * lb + sqrt(la^2 + 4 * lb^2)) + log(2 * lb + sqrt(la^2 + 4 * lb^2)) + 2 * log(2 * lb - la + sqrt(la^2 + 4 * lb^2)) - 2 * log(la + 2 * lb + sqrt(la^2 + 4 * lb^2))) + 6 * la * lb^2 * (log(64) + 4 * log(lb) + 2 * log(sqrt(la^2 + lb^2) - la) + 3 * log(la + sqrt(la^2 + lb^2)) - 3 * log(sqrt(la^2 + 4 * lb^2) - la) - 3 * log(sqrt(la^4 + 5 * la^2 * lb^2 + 4 * lb^4) + la * (sqrt(la^2 + lb^2) - la - sqrt(la^2 + 4 * lb^2))))) end #= Direct evaluation of 1 / (4 * π * dstMag) integral for a pair of cornered edge panels. la, lb, and lc are the edge lengths, and la is assumed to be common to both panels. =# @inline function rSrfEdgCrn(la::AbstractFloat, lb::AbstractFloat, lc::AbstractFloat, cmpInf::GlaKerOpt)::ComplexF64 return (1 / (48 * π * cmpInf.frqPhz^2)) * (8 * lb * lc * sqrt(lb^2 + lc^2) - 8 * lb * lc * sqrt(la^2 + lb^2 + lc^2) - 12 * la^3 * acot(la * lc / (la^2 + lb^2 - lb * sqrt(la^2 + lb^2 + lc^2))) + 12 * la^3 * atan(la / lc) - 12 * la * lc^2 * atan(la * lb / (lc * sqrt(la^2 + lb^2 + lc^2))) - 12 * la * lb^2 * atan(la * lc / (lb * sqrt(la^2 + lb^2 + lc^2))) - 16 * la^3 * atan(lb * lc / (la * sqrt(la^2 + lb^2 + lc^2))) + 6 * lc^3 * atanh(lb / sqrt(lb^2 + lc^2)) - 6 * lc * (la^2 + lc^2) * atanh(lb / sqrt(la^2 + lb^2 + lc^2)) - 15 * la^2 * lc * log(la^2 + lc^2) - lc^3 * log(la^2 + lc^2) + 2 * lc^3 * log(lc / (lb + sqrt(lb^2 + lc^2))) + 6 * la^2 * lc * log(sqrt(la^2 + lb^2 + lc^2) - lb) + 24 * la^2 * lc * log(sqrt(la^2 + lb^2 + lc^2) + lb) + 2 * lc^3 * log(sqrt(la^2 + lb^2 + lc^2) + lb) + 6 * la * lb * (-2 * la * log(la^2 + lb^2) - lc * log((lb^2 + lc^2) * (sqrt(la^2 + lb^2 + lc^2) - la)) + 3 * lc * log(la + sqrt(la^2 + lb^2 + lc^2)) + la * log(sqrt(la^2 + lb^2 + lc^2) - lc) + 3 * la * log(sqrt(la^2 + lb^2 + lc^2) + lc)) + 2 * lb^3 * ( log((sqrt(la^2 + lb^2 + lc^2) - lc) / (lc + sqrt(la^2 + lb^2 + lc^2))) + log(1 + (2 * lc * (lc + sqrt(lb^2 + lc^2))) / lb^2))) end #= Direct evaluation of 1 / (4 * π * dstMag) integral for a pair of flat edge panels. la and lb are the edge lengths, and lb is assumed to be ``doubled''. =# @inline function rSrfEdgFlt(la::AbstractFloat, lb::AbstractFloat, cmpInf::GlaKerOpt)::ComplexF64 return (1 / (12 * π * cmpInf.frqPhz^2)) * (-la^3 + 2 * lb^2 * (3 * lb + sqrt(la^2 + lb^2) - 2 * sqrt(la^2 + 4 * lb^2)) + la^2 * (2 * sqrt(la^2 + lb^2) - sqrt(la^2 + 4 * lb^2))) + (1 / (64 * π)) * la * lb * (lb * (-62 * log(2) - 5 * log(-la + sqrt(la^2 + lb^2)) + 4 * log(8 * lb^2 * (-la + sqrt(la^2 + lb^2))) - 33 * log(la + sqrt(la^2 + lb^2)) + 17 * log(-la + sqrt(la^2 + 4 * lb^2)) - 24 * log(lb * (-la + sqrt(la^2 + 4 * lb^2))) + 57 * log(la + sqrt(la^2 + 4 * lb^2))) + 4 * la * (-8 * asinh(lb / la) + 6 * asinh(2 * lb / la) + 6 * atanh(lb / sqrt(la^2 + lb^2)) + 12 * log(la) - 13 * log(-lb + sqrt(la^2 + lb^2)) + log((-lb + sqrt(la^2 + lb^2)) / la) + log(la / (lb + sqrt(la^2 + lb^2))) - 7 * log(lb + sqrt(la^2 + lb^2)) - 2 * log((lb + sqrt(la^2 + lb^2))/la) - 3 * log(-(((lb + sqrt(la^2 + lb^2)) * (2 * lb - sqrt(la^2 + 4 * lb^2))) / (la^2))) - 3 * log((-lb + sqrt(la^2 + lb^2)) / (-2 * lb + sqrt(la^2 + 4 * lb^2))) + 11 * log(-2 * lb + sqrt(la^2 + 4 * lb^2)) - 3 * log((lb + sqrt(la^2 + lb^2)) / (2 * lb + sqrt(la^2 + 4 * lb^2))) + log(2 * lb + sqrt(la^2 + 4 * lb^2)) + 9 * log((2 * lb + sqrt(la^2 + 4 * lb^2)) / (lb + sqrt(la^2 + lb^2))) - 2 * log(la^2 + 2 * lb * (lb - sqrt(la^2 + lb^2))))) end
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
14836
#= glaIntsup evaluates the integrands called by the weakS, weakE, and weakV head functions using a series of variable transformations and analytic integral evaluations---reducing the four dimensional surface integrals performed for ``standard'' cells to one dimensional integrals. Minimal comments are included in this code, which is mostly a julia translation of DIRECTFN_E by Athanasios Polimeridis. For a complete description of the steps being performed see the article cited above and references included therein. =# #= Weak integral evaluation for a panel interacting with itself. =# function wekSInt(rPts::AbstractArray{<:AbstractFloat,2}, glQud::AbstractArray{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::ComplexF64 glqOrd = size(glQud)[1] # integral as reduction return eqvJacS(rPts) * ThreadsX.mapreduce(x -> wekSIntKer(x, glqOrd, rPts, glQud, cmpInf), +, CartesianIndices((1:3, 1:8, 1:glqOrd)); init = 0.0 + im * 0.0) end #= Kernel function for self panel integrals. =# function wekSIntKer(slvInd::CartesianIndex{3}, glqOrd::Integer, rPts::AbstractArray{<:AbstractFloat,2}, glQud::AbstractArray{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::ComplexF64 (ψA, ψB) = ψlimS(slvInd[2]) θ = θf(ψA, ψB, glQud[slvInd[3],1]) (ηA, ηB) = ηlimS(slvInd[2], θ) intVal = 0.0 + im * 0.0 # component contribution @inbounds for itr ∈ 1:glqOrd intVal += glQud[itr,2] * nS(slvInd[1], slvInd[2], θ, θf(ηA, ηB, glQud[itr,1]), rPts, glQud, cmpInf) end return 0.25 * intVal * glQud[slvInd[3],2] * (ψB - ψA) * (ηB - ηA) * sin(θ) end #= Weak integral evaluation for two panels sharing an edge. =# function wekEInt(rPts::AbstractArray{<:AbstractFloat,2}, glQud::AbstractArray{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::ComplexF64 glqOrd = size(glQud)[1] # integral implemented as reduction return eqvJacEV(rPts) * ThreadsX.mapreduce(x -> wekEIntKer(x, glqOrd, rPts, glQud, cmpInf), +, CartesianIndices((1:6, 1:glqOrd)); init = 0.0 + im * 0.0) end #= Kernel for edge panel reduction. =# function wekEIntKer(slvInd::CartesianIndex{2}, glqOrd::Integer, rPts::AbstractArray{<:AbstractFloat,2}, glQud::AbstractArray{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::ComplexF64 (ψA, ψB) = ψlimE(slvInd[1]) θB = θf(ψA, ψB, glQud[slvInd[2], 1]) (ηA, ηB) = ηlimE(slvInd[1], θB) θA = 0.0 + im * 0.0 intVal = 0.0 + im * 0.0 # component contribution @inbounds for itr ∈ 1:glqOrd θA = θf(ηA, ηB, glQud[itr, 1]) intVal += glQud[itr, 2] * cos(θA) * (nE(slvInd[1], 1, θA, θB, rPts, glQud, cmpInf) + nE(slvInd[1], -1, θA, θB, rPts, glQud, cmpInf)) end return 0.25 * intVal * glQud[slvInd[2], 2] * (ψB - ψA) * (ηB - ηA) end #= Weak integral for panels sharing a vertex. =# function wekVInt(sngMod::Bool, rPts::AbstractArray{<:AbstractFloat,2}, glQud::AbstractArray{<:AbstractFloat,2}, cmpInf::GlaKerOpt)::ComplexF64 glqOrd = size(glQud)[1] # integral as mapreduction return eqvJacEV(rPts) * ^(π,2) * ThreadsX.mapreduce(x -> wekVIntKer(x, glqOrd, sngMod, rPts, glQud, cmpInf), +, CartesianIndices((1:glqOrd, 1:glqOrd, 1:glqOrd,)); init = 0.0 + im * 0.0) / 144.0 end #= Kernel for weak vertex integral. =# function wekVIntKer(slvInd::CartesianIndex{3}, glqOrd::Integer, sngMod::Bool, rPts::AbstractArray{<:AbstractFloat,2}, glQud::AbstractArray{<:AbstractFloat,2}, cmpInf::GlaKerOpt) xPts = Array{Float64,2}(undef, 3, 2) θA = θf(0.0, π / 3.0, glQud[slvInd[1],1]) LA = 2.0 * sqrt(3.0) / (sin(θA) + sqrt(3.0) * cos(θA)) θB = θf(0.0, π / 3.0, glQud[slvInd[2],1]) LB = 2.0 * sqrt(3.0) / (sin(θB) + sqrt(3.0) * cos(θB)) θC = θf(0.0, atan(LB / LA), glQud[slvInd[3],1]) θD = θf(atan(LB / LA), π / 2.0, glQud[slvInd[3],1]) intValC = 0.0 + im * 0.0 intValD = 0.0 + im * 0.0 θX = 0.0 # select kernel mode if sngMod == true # loop D @inbounds for itrC ∈ 1:glqOrd θX = θf(0.0, LA / cos(θC), glQud[itrC,1]) spxV!(xPts, θX, θC, θB, θA) intValC += glQud[itrC,2] * (θX^3) * kerEVN(rPts, xPts, cmpInf.frqPhz) end # loop E @inbounds for itrD ∈ 1:glqOrd θX = θf(0.0, LB / sin(θD), glQud[itrD,1]) spxV!(xPts, θX, θD, θB, θA) intValD += glQud[itrD,2] * (θX^3) * kerEVN(rPts, xPts, cmpInf.frqPhz) end else # loop D @inbounds for itrC ∈ 1:glqOrd θX = θf(0.0, LA / cos(θC), glQud[itrC,1]) spxV!(xPts, θX, θC, θB, θA) intValC += glQud[itrC,2] * (θX^3) * kerEV(rPts, xPts, cmpInf.frqPhz) end # loop E @inbounds for itrD ∈ 1:glqOrd θX = θf(0.0, LB / sin(θD), glQud[itrD,1]) spxV!(xPts, θX, θD, θB, θA) intValD += glQud[itrD,2] * (θX^3) * kerEV(rPts, xPts, cmpInf.frqPhz) end end return glQud[slvInd[1],2] * glQud[slvInd[2],2] * glQud[slvInd[3],2] * (atan(LB / LA) * (LA * sin(θC) * intValC - LB * cos(θD) * intValD) + 0.5 * π * LB * cos(θD) * intValD) end @inline function ψlimS(idf::Integer)::Tuple{Float64,Float64} if idf == 1 || idf == 5 || idf == 6 return (0.0, π / 3.0) elseif idf == 2 || idf == 7 return (π / 3.0, 2.0 * π / 3.0) elseif idf == 3 || idf == 4 || idf == 8 return (2.0 * π / 3.0, π) else error("Unrecognized identifier.") end end @inline function ψlimE(idf::Integer)::Tuple{Float64,Float64} if idf == 1 return (0.0, π / 3.0) elseif idf == 2 || idf == 3 return (π / 3.0, π / 2.0) elseif idf == 4 || idf == 6 return (π / 2.0, π) elseif idf == 5 return (0.0, π / 2.0) else error("Unrecognized identifier.") end end @inline function ηlimS(idf::Integer, θ::AbstractFloat)::Tuple{Float64,Float64} if idf == 1 || idf == 2 return (0.0, 1.0) elseif idf == 3 return ((sqrt(3.0) - tan(π - θ)) / (sqrt(3.0) + tan(π - θ)), 1.0) elseif idf == 4 return (0.0, (sqrt(3.0) - tan(π - θ)) / (sqrt(3.0) + tan(π - θ))) elseif idf == 5 return ((tan(θ) - sqrt(3.0)) / (sqrt(3.0) + tan(θ)), 0.0) elseif idf == 6 return (-1.0, (tan(θ) - sqrt(3.0)) / (sqrt(3.0) + tan(θ))) elseif idf == 7 || idf == 8 return (-1.0, 0.0) else error("Unrecognized identifier.") end end @inline function ηlimE(idf::Integer, θ::AbstractFloat)::Tuple{Float64,Float64} if idf == 1 return (0.0, atan(sin(θ) + sqrt(3.0) * cos(θ))) elseif idf == 2 return (atan(sin(θ) - sqrt(3.0) * cos(θ)), atan(sin(θ) + sqrt(3.0) * cos(θ))) elseif idf == 3 || idf == 4 return (0.0, atan(sin(θ) - sqrt(3.0) * cos(θ))) elseif idf == 5 return (atan(sin(θ) + sqrt(3.0) * cos(θ)), 0.5 * π) elseif idf == 6 return (atan(sin(θ) - sqrt(3.0) * cos(θ)), 0.5 * π) else error("Unrecognized identifier.") end end function nS(dir::Integer, idf::Integer, θ1::T, θB::T, rPts::Array{T,2}, glQud::Array{T,2}, cmpInf::GlaKerOpt)::ComplexF64 where T<:AbstractFloat int = 0.0 + 0.0im glqOrd = size(glQud)[1] if idf == 1 || idf == 5 for n ∈ 1:glqOrd int += glQud[n,2] * aS(rPts, θ1, θB, θf(0.0, (1.0 - θB) / cos(θ1), glQud[n,1]), dir, glQud, cmpInf) end return (1.0 - θB) / (2.0 * cos(θ1)) * int elseif idf == 2 || idf == 3 for n ∈ 1:glqOrd int += glQud[n,2] * aS(rPts, θ1, θB, θf(0.0, sqrt(3.0) * (1.0 - θB) / sin(θ1), glQud[n,1]), dir, glQud, cmpInf) end return sqrt(3.0) * (1.0 - θB) / (2.0 * sin(θ1)) * int elseif idf == 6 || idf == 7 for n ∈ 1:glqOrd int += glQud[n,2] * aS(rPts, θ1, θB, θf(0.0, sqrt(3.0) * (1.0 + θB) / sin(θ1), glQud[n,1]), dir, glQud, cmpInf) end return sqrt(3.0) * (1.0 + θB) / (2.0 * sin(θ1)) * int elseif idf == 4 || idf == 8 for n ∈ 1:glqOrd int += glQud[n,2] * aS(rPts, θ1, θB, θf(0.0, -(1.0 + θB) / cos(θ1), glQud[n,1]), dir, glQud, cmpInf) end return -(1.0 + θB) / (2.0 * cos(θ1)) * int else error("Unrecognized identifier.") end end function nE(idf1::Integer, idf2::Integer, θB::T, θ1::T, rPts::Array{T,2}, glQud::Array{T,2}, cmpInf::GlaKerOpt)::ComplexF64 where T<:AbstractFloat γ = 0.0 intVal1 = 0.0 + 0.0im intVal2 = 0.0 + 0.0im glqOrd = size(glQud)[1] if idf1 == 1 || idf1 == 2 γ = (sin(θ1) + sqrt(3.0) * cos(θ1) - tan(θB)) / (sin(θ1) + sqrt(3.0) * cos(θ1) + tan(θB)) for n ∈ 1:glqOrd intVal1 += glQud[n, 2] * intNE(n, 1, γ, θB, θ1, rPts, glQud, idf2, cmpInf) intVal2 += glQud[n, 2] * intNE(n, 2, γ, θB, θ1, rPts, glQud, idf2, cmpInf) end return 0.5 * intVal2 + γ * 0.5 * (intVal1-intVal2) elseif idf1 == 3 γ = sqrt(3.0) / tan(θ1) for n ∈ 1:glqOrd intVal1 += glQud[n, 2] * intNE(n, 1, γ, θB, θ1, rPts, glQud, idf2, cmpInf) intVal2 += glQud[n, 2] * intNE(n, 3, γ, θB, θ1, rPts, glQud, idf2, cmpInf) end return 0.5 * intVal2 + 0.5 * γ * (intVal1 - intVal2) elseif idf1 == 4 for n ∈ 1:glqOrd intVal1 += glQud[n, 2] * intNE(n, 4, 1.0, θB, θ1, rPts, glQud, idf2, cmpInf) end return 0.5 * intVal1 elseif idf1 == 5 || idf1 == 6 for n ∈ 1:glqOrd intVal1 += glQud[n, 2] * intNE(n, 5, 1.0, θB, θ1, rPts, glQud, idf2, cmpInf) end return 0.5 * intVal1 else error("Unrecognized identifier.") end end @inline function intNE(n::Integer, idf1::Integer, γ::T, θB::T, θ1::T, rPts::Array{T,2}, glQud::Array{T,2}, idf2::Integer, cmpInf::GlaKerOpt)::ComplexF64 where T <: AbstractFloat if idf1 == 1 η = θf(0.0, γ, glQud[n,1]) λ = sqrt(3.0) * (1 + η) / (cos(θB) * (sin(θ1) + sqrt(3.0) * cos(θ1))) elseif idf1 == 2 η = θf(γ, 1.0, glQud[n,1]) λ = sqrt(3.0) * (1.0 - abs(η)) / sin(θB) elseif idf1 == 3 η = θf(γ, 1.0, glQud[n,1]) λ = sqrt(3.0) * (1.0 - abs(η)) / (cos(θB) * (sin(θ1) - sqrt(3.0) * cos(θ1))) elseif idf1 == 4 η = θf(0.0, 1.0, glQud[n,1]) λ = sqrt(3.0) * (1.0 - abs(η)) / (cos(θB) * (sin(θ1) - sqrt(3.0) * cos(θ1))) elseif idf1 == 5 η = θf(0.0, 1.0, glQud[n,1]) λ = sqrt(3.0) * (1.0 - η) / sin(θB) else error("Unrecognized identifier.") end return aE(rPts, λ, η, θB, θ1, glQud, idf2, cmpInf) end function aS(rPts::Array{T,2}, θ1::T, θB::T, θ::T, dir::Integer, glQud::Array{T,2}, cmpInf::GlaKerOpt)::ComplexF64 where T<:AbstractFloat xPts = Array{Float64,2}(undef, 3, 2) glqOrd = size(glQud)[1] aInt = 0.0 + 0.0im η1 = 0.0 η2 = 0.0 ξ1 = 0.0 @inbounds for n ∈ 1:glqOrd (η1, ξ1) = subTri(θB, θ * sin(θ1), dir) (η2, ξ2) = subTri(θf(0.0, θ, glQud[n,1]) * cos(θ1) + θB, (θ - θf(0.0, θ, glQud[n,1])) * sin(θ1), dir) spx!(xPts, η1, η2, ξ1, ξ2) aInt += glQud[n,2] * θf(0.0, θ, glQud[n,1]) * kerSN(rPts, xPts, cmpInf.frqPhz) end return 0.5 * θ * aInt end function aE(rPts::Array{T,2}, λ::T, η::T, θB::T, θ1::T, glQud::Array{T,2}, idf::Integer, cmpInf::GlaKerOpt)::ComplexF64 where T<:AbstractFloat xPts = Array{Float64,2}(undef, 3, 2) glqOrd = size(glQud)[1] intVal = 0.0 + 0.0im ζ = 0.0 @inbounds for n ∈ 1:glqOrd ζ = θf(0.0, λ, glQud[n,1]) spxE!(xPts, ζ, η, θB, θ1, idf) intVal += glQud[n,2] * ζ * ζ * kerEVN(rPts, xPts, cmpInf.frqPhz) end return 0.5 * λ * intVal end @inline function subTri(λ1::AbstractFloat, λ2::AbstractFloat, dir::Integer)::Tuple{Float64,Float64} if dir == 1 return (λ1, λ2) elseif dir == 2 return (0.5 * (1.0 - λ1 - λ2 * sqrt(3)), 0.5 * (sqrt(3.0) + λ1 * sqrt(3.0) - λ2)) elseif dir == 3 return (0.5 * (- 1.0 - λ1 + λ2 * sqrt(3)), 0.5 * (sqrt(3.0) - λ1 * sqrt(3.0) - λ2)) else error("Unrecognized identifier.") end end @inline function eqvJacEV(rPts::Array{T,2})::Float64 where T<:AbstractFloat return sqrt(dot(cross(rPts[:,2] - rPts[:,1], rPts[:,3] - rPts[:,1]), cross(rPts[:,2] - rPts[:,1], rPts[:,3] - rPts[:,1]))) * sqrt(dot(cross(rPts[:,5] - rPts[:,4], rPts[:,6] - rPts[:,4]), cross(rPts[:,5] - rPts[:,4], rPts[:,6] - rPts[:,4]))) / 12.0 end @inline function eqvJacS(rPts::Array{T,2})::Float64 where T<:AbstractFloat return dot(cross(rPts[:,1] - rPts[:,2], rPts[:,3] - rPts[:,1]), cross(rPts[:,1] - rPts[:,2], rPts[:,3] - rPts[:,1])) / 12.0 end @inline function θf(θa::T, θb::T, pos::T)::Float64 where T<:AbstractFloat return 0.5 * ((θb - θa) * pos + θa + θb) end function spxV!(xPts::Array{T,2}, θ4::T, θ3::T, θB::T, θ1::T)::Nothing where T <: AbstractFloat spx!(xPts, θ4 * cos(θ3) * cos(θ1) - 1.0, θ4 * sin(θ3) * cos(θB) - 1.0, θ4 * cos(θ3) * sin(θ1), θ4 * sin(θ3) * sin(θB)) return nothing end function spxE!(xPts::Array{T,2}, λ::T, η::T, θB::T, θ1::T, idf::Integer)::Nothing where T<:AbstractFloat if idf == 1 spx!(xPts, η, λ * cos(θB) * cos(θ1) - η , λ * sin(θB), λ * cos(θB) * sin(θ1)) elseif idf == - 1 spx!(xPts, -η, -(λ * cos(θB) * cos(θ1) - η) , λ * sin(θB), λ * cos(θB) * sin(θ1)) else error("Unrecognized identifier.") end return nothing end #= Two versions of the simplex function. =# @inline function spx!(xPts::Array{T,2}, η1::T, η2::T, ξ1::T, ξ2::T)::Nothing where T <: AbstractFloat xPts[1,1] = (sqrt(3.0) * (1.0 - η1) - ξ1) / (2.0 * sqrt(3.0)) xPts[2,1] = (sqrt(3.0) * (1.0 + η1) - ξ1) / (2.0 * sqrt(3.0)) xPts[3,1] = ξ1 / sqrt(3.0) xPts[1,2] = (sqrt(3.0) * (1.0 - η2) - ξ2) / (2.0 * sqrt(3.0)) xPts[2,2] = (sqrt(3.0) * (1.0 + η2) - ξ2) / (2.0 * sqrt(3.0)) xPts[3,2] = ξ2 / sqrt(3.0) return nothing end @inline function kerEV(rPts::Array{T,2}, xPts::AbstractArray{T,2}, frqPhz::Union{ComplexF64,ComplexF32})::ComplexF64 where T<:AbstractFloat return sclEgo(dstMag(xPts[1,1] * rPts[1,1] + xPts[2,1] * rPts[1,2] + xPts[3,1] * rPts[1,3] - (xPts[1,2] * rPts[1,4] + xPts[2,2] * rPts[1,5] + xPts[3,2] * rPts[1,6]), xPts[1,1] * rPts[2,1] + xPts[2,1] * rPts[2,2] + xPts[3,1] * rPts[2,3] - (xPts[1,2] * rPts[2,4] + xPts[2,2] * rPts[2,5] + xPts[3,2] * rPts[2,6]), xPts[1,1] * rPts[3,1] + xPts[2,1] * rPts[3,2] + xPts[3,1] * rPts[3,3] - (xPts[1,2] * rPts[3,4] + xPts[2,2] * rPts[3,5] + xPts[3,2] * rPts[3,6])), frqPhz) end @inline function kerEVN(rPts::Array{T,2}, xPts::AbstractArray{T,2}, frqPhz::Union{ComplexF64,ComplexF32})::ComplexF64 where T<:AbstractFloat return sclEgoN(dstMag(xPts[1,1] * rPts[1,1] + xPts[2,1] * rPts[1,2] + xPts[3,1] * rPts[1,3] - (xPts[1,2] * rPts[1,4] + xPts[2,2] * rPts[1,5] + xPts[3,2] * rPts[1,6]), xPts[1,1] * rPts[2,1] + xPts[2,1] * rPts[2,2] + xPts[3,1] * rPts[2,3] - (xPts[1,2] * rPts[2,4] + xPts[2,2] * rPts[2,5] + xPts[3,2] * rPts[2,6]), xPts[1,1] * rPts[3,1] + xPts[2,1] * rPts[3,2] + xPts[3,1] * rPts[3,3] - (xPts[1,2] * rPts[3,4] + xPts[2,2] * rPts[3,5] + xPts[3,2] * rPts[3,6])), frqPhz) end @inline function kerSN(rPts::Array{T,2}, xPts::Array{T,2}, frqPhz::Union{ComplexF64,ComplexF32})::ComplexF64 where T<:AbstractFloat return sclEgoN(dstMag(xPts[1,1] * rPts[1,1] + xPts[2,1] * rPts[1,2] + xPts[3,1] * rPts[1,3] - (xPts[1,2] * rPts[1,1] + xPts[2,2] * rPts[1,2] + xPts[3,2] * rPts[1,3]), xPts[1,1] * rPts[2,1] + xPts[2,1] * rPts[2,2] + xPts[3,1] * rPts[2,3] - (xPts[1,2] * rPts[2,1] + xPts[2,2] * rPts[2,2] + xPts[3,2] * rPts[2,3]), xPts[1,1] * rPts[3,1] + xPts[2,1] * rPts[3,2] + xPts[3,1] * rPts[3,3] - (xPts[1,2] * rPts[3,1] + xPts[2,2] * rPts[3,2] + xPts[3,2] * rPts[3,3])), frqPhz) end
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
3995
#= Basic linear transformation properties =# Base.eltype(opr::GlaOpr) = eltype(eltype(opr.mem.egoFur)) Base.size(opr::GlaOpr) = (3 * prod(opr.mem.trgVol.cel), 3 * prod(opr.mem.srcVol.cel)) Base.size(opr::GlaOpr, dim::Int) = (3 * prod(opr.mem.trgVol.cel), 3 * prod(opr.mem.srcVol.cel))[dim] LinearAlgebra.issymmetric(::GlaOpr) = false LinearAlgebra.isposdef(::GlaOpr) = false LinearAlgebra.ishermitian(::GlaOpr) = false LinearAlgebra.isdiag(::GlaOpr) = false #= Create operator adjoint. =# function Base.adjoint(opr::GlaOpr)::GlaOpr cmpInfCpy = deepcopy(opr.mem.cmpInf) frqPhz, intOrd, adjMod, devMod, numTrd, numBlk = cmpInfCpy.frqPhz, cmpInfCpy.intOrd, cmpInfCpy.adjMod, cmpInfCpy.devMod, cmpInfCpy.numTrd, cmpInfCpy.numBlk adjOpt = GlaKerOpt(frqPhz, intOrd, !adjMod, devMod, numTrd, numBlk) memCpy = deepcopy(opr.mem) trgVol, srcVol, mixInf, dimInf, egoFur, fftPlnFwd, fftPlnRev, phzInf = memCpy.trgVol, memCpy.srcVol, memCpy.mixInf, memCpy.dimInf, memCpy.egoFur, memCpy.fftPlnFwd, memCpy.fftPlnRev, memCpy.phzInf adjMem = GlaOprMem(adjOpt, srcVol, trgVol, mixInf, dimInf, egoFur, fftPlnFwd, fftPlnRev, phzInf) return GlaOpr(adjMem) end #= Call egoOpr! via * symbol, tensor definition of input vector. =# function Base.:*(opr::GlaOpr, innVec::AbstractArray{T, 4})::AbstractArray{T,4} where T <: Complex @assert T <: eltype(opr) "Input array must have the same element type as the operator. eltype(opr) = $(eltype(opr))" if opr.mem.cmpInf.devMod && !(innVec isa CuArray) @warn "Input array is not a CuArray. Copying data to GPU." innVec = CuArray(innVec) end # egoOpr! is mutating, so we need to copy the input return egoOpr!(opr.mem, deepcopy(innVec)) end #= Call egoOpr! via * symbol, flattened definition of input vector. =# function Base.:*(opr::GlaOpr, innVec::AbstractArray{T})::AbstractArray{T} where T <: Complex innVecArr = reshape(innVec, glaSze(opr, 2)) outVec = opr * innVecArr if prod(size(innVec)) == prod(glaSze(opr, 1)) return reshape(outVec, size(innVec)) elseif ndims(innVec) == 1 return vec(outVec) end return reshape(outVec, glaSze(opr, 1)) end #= Call egoOpr! via mul. =# function LinearAlgebra.mul!(outVec::AbstractArray{T}, opr::GlaOpr, innVec::AbstractArray{T}, α::Number, β::Number)::AbstractArray{T} where T <: Complex resVec = opr * innVec rmul!(resVec, α) rmul!(outVec, β) outVec .+= resVec return outVec end """ isadjoint(opr::GlaOpr) Returns true if the operator is the adjoint of the Greens operator. # Arguments - `opr::GlaOpr`: The operator to check. # Returns - `true` if the operator is the adjoint, `false` otherwise. """ isadjoint(opr::GlaOpr) = opr.mem.cmpInf.adjMod """ isselfoperator(opr::GlaOpr) Returns true if the operator is a self Greens operator. # Arguments - `opr::GlaOpr`: The operator to check. # Returns - `true` if the operator is a self Greens operator, `false` otherwise. """ isselfoperator(opr::GlaOpr) = opr.mem.srcVol == opr.mem.trgVol """ isexternaloperator(opr::GlaOpr) Returns true if the operator is an external Greens operator. # Arguments - `opr::GlaOpr`: The operator to check. # Returns - `true` if the operator is an external Greens operator, `false` otherwise. """ isexternaloperator(opr::GlaOpr) = !isselfoperator(opr) function Base.show(io::IO, opr::GlaOpr) if isadjoint(opr) print(io, "Adjoint ") end if isselfoperator(opr) print(io, "Self ") else print(io, "External ") end print(io, "GlaOpr for ") if isselfoperator(opr) print(io, "a $(eltype(opr)) (" * join(opr.mem.srcVol.cel, "×") * ") volume ") print(io, "of size (" * join(opr.mem.srcVol.scl, "×") * ")λ") else print(io, "$(eltype(opr)) (" * join(opr.mem.srcVol.cel, "×") * ") -> (" * join(opr.mem.trgVol.cel, "×") * ") volumes ") print(io, "of sizes (" * join(opr.mem.srcVol.scl, "×") * ")λ -> (" * join(opr.mem.trgVol.scl, "×") * ")λ ") print(io, "with separation (" * join(opr.mem.trgVol.org .- opr.mem.srcVol.org, ", ") * ")λ") end end
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
6747
""" GlaVol Basic spatial memory structure. .cel---tuple of cells in rectangular prism .scl--relative side length of a cuboid voxel compared to the wavelength .org---center position of the domain .grd---spatial location of the center of each cell contained in the volume """ #= To simply code operation Gila internally enforces an even number of cells during the memory preparation phase---see GlaOprMem in glaMemSup.jl. =# struct GlaVol cel::NTuple{3,Integer} scl::NTuple{3,Rational} org::NTuple{3,Rational} grd::Array{<:StepRange,1} # boundary conditions here? end #= GlaExtInf Information for mapping between general source and target volumes. .minScl---common minimum cell size .srcDiv---divisions in each Cartesian index of source volume .trgDiv---divisions in each Cartesian index of target volume .trgCel---cells in a target partition .srcCel---cells in a source partition .trgPar---identification of volume partition with grid offsets in target volume .srcPar---identification of volume partition with grid offsets in source volume =# struct GlaExtInf minScl::NTuple{3,Rational} trgDiv::NTuple{3,Integer} srcDiv::NTuple{3,Integer} trgCel::NTuple{3,Integer} srcCel::NTuple{3,Integer} trgPar::CartesianIndices srcPar::CartesianIndices end """ GlaKerOpt Green function operator assembly and kernel operation options. .frqPhz---multiplicative scaling factor allowing for complex frequencies .intOrd---Gauss-Legendre integration order for cells in contact .adjMod---flip between operator and operator adjoint .devMod---boolean vector representing activation of GPUs .numTrd---number of threads to use when running GPU kernels .numBlk---number of threads to use when running GPU kernels """ #= If intConTest.jl was failed the default intOrd used in the simplified constructor may not be sufficient to insure that all integral values are properly converged. It may be prudent to create the associated GlaKerOpt with higher order. =# struct GlaKerOpt frqPhz::Number intOrd::Integer adjMod::Bool devMod::Union{Bool,Array{<:Bool,1}} numTrd::Union{Tuple{},NTuple{3,Integer}} numBlk::Union{Tuple{},NTuple{3,Integer}} end """ GlaOprMem Storage structure for a Green function operator. .cmpInf---computation information see GlaKerOpt .trgVol---target volume of Green function .srcVol---source volume of Green function .mixInf---information for matching source and target grids, see GlaExtInf .dimInfC---dimension information for Green function volumes, host side .dimInfD---dimension information for Green function volumes, device side .egoFur---unique Fourier transform data for circulant Green function .fftPlnFwd---forward Fourier transform plans .fftPlnRev---reverse Fourier transform plans .phzInf---phase vector for splitting Fourier transforms """ struct GlaOprMem cmpInf::GlaKerOpt trgVol::GlaVol srcVol::GlaVol mixInf::GlaExtInf dimInf::NTuple{3,Integer} egoFur::AbstractArray{<:AbstractArray{T},1} where T<:Union{ComplexF64,ComplexF32} fftPlnFwd::AbstractArray{<:AbstractFFTs.Plan,1} fftPlnRev::AbstractArray{<:AbstractFFTs.ScaledPlan,1} phzInf::AbstractArray{<:AbstractArray{T},1} where T<:Union{ComplexF64,ComplexF32} end """ GlaOpr Abstraction wrapper for GlaOprMem. # Fields - `mem::GlaOprMem`: Data to process the Green function. """ struct GlaOpr mem::GlaOprMem end #= Constructors =# """ GlaVol(cel::Array{<:Integer,1}, celScl::NTuple{3,Rational}, org::NTuple{3,Rational}, grdScl::NTuple{3,Rational}=celScl)::GlaVol Constructor for Gila Volumes. """ function GlaVol(cel::Union{Array{<:Integer,1},NTuple{3,Integer}}, celScl::NTuple{3,Rational}, org::NTuple{3,Rational}, grdScl::NTuple{3,Rational}=celScl)::GlaVol if !prod(celScl .<= grdScl) error("The cell scale must be smaller than the grid scale to avoid partially overlapping basis elements.") end brd = grdScl .* (Rational.(floor.(cel ./ 2)) .- (iseven.(cel) .// 2)) grd = map(StepRange, org .- brd, grdScl, org .+ brd) return GlaVol(Tuple(cel), celScl, org, [grd...]) end #= Regenerate a GlaVol enforcing that the number of cells is even. Called in GlaOprMem constructor. =# function glaVolEveGen(glaVol::GlaVol)::GlaVol # check that the number of cells in each Cartesian dimension is even celParVec = iseven.(glaVol.cel) # number of cells is odd in some direction if prod(celParVec) != 1 # warn user that the volume is being regenerated. println("Warning! A volume has been regenerated to have an even number of cells---the size of a cell has changed. The sum of the number of source and target cells must be even for the algorithm to function.") # determine dimensions where cells will be scaled. parVec = map(!, celParVec) # adjust number of cells newCelNum = glaVol.cel .+ parVec # adjust size of cells newCelScl = map(//, numerator.(glaVol.scl) .* glaVol.cel, denominator.(glaVol.scl) .* newCelNum) # adjust grid scale oldGrdScl = Rational.(step.(glaVol.grd)) newGrdScl = map(//, numerator.(oldGrdScl) .* glaVol.cel, denominator.(oldGrdScl) .* newCelNum) # regenerate volume return GlaVol(Tuple(newCelNum), newCelScl, glaVol.org, Tuple(newGrdScl)) # otherwise, everything is fine else return glaVol end end #= Internal constructor for external pair information, treating grid mismatch. =# function GlaExtInf(trgVol::GlaVol, srcVol::GlaVol)::GlaExtInf # test that cell scales are compatible if prod(isinteger.(srcVol.scl ./ trgVol.scl) .+ isinteger.(trgVol.scl ./ srcVol.scl)) == 0 error("Volume pair must share a common scale grid.") end # common scale minScl = gcd.(srcVol.scl, trgVol.scl) # maximal scale maxScl = lcm.(srcVol.scl, trgVol.scl) # grid divisions for the source and target volumes trgDivGrd = ntuple(itr -> maxScl[itr] .÷ trgVol.scl[itr], 3) srcDivGrd = ntuple(itr -> maxScl[itr] .÷ srcVol.scl[itr], 3) # number of cells in each source (target) division trgDivCel = Tuple(trgVol.cel .÷ trgDivGrd) srcDivCel = Tuple(srcVol.cel .÷ srcDivGrd) # confirm subdivision of source and target volumes if prod(trgDivCel) == 0 || prod(srcDivCel) == 0 error("Volume sizes are incompatible---volume smaller than cell.") end # association of volume partition with grid offset trgPar = CartesianIndices(tuple(trgDivGrd...)) .- CartesianIndex(1, 1, 1) srcPar = CartesianIndices(tuple(srcDivGrd...)) .- CartesianIndex(1, 1, 1) # create transfer information return GlaExtInf(minScl, trgDivGrd, srcDivGrd, trgDivCel, srcDivCel, trgPar, srcPar) end """ GlaKerOpt(devStt::Bool) Simplified GlaKerOpt constructor. """ function GlaKerOpt(devStt::Bool) if devStt == true return GlaKerOpt(1.0 + 0.0im, 32, false, true, (128, 2, 1), (1, 128, 256)) else return GlaKerOpt(1.0 + 0.0im, 32, false, false, (), ()) end end
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
14511
""" function GlaOprMem(cmpInf::GlaKerOpt, trgVol::GlaVol, srcVol::Union{GlaVol,Nothing}=nothing, egoFur::Union{AbstractArray{<:AbstractArray{T}}, Nothing}=nothing)::GlaOprMem where T<:Union{ComplexF64,ComplexF32} Prepare memory for green function operator---when called with a single GlaVol, or identical source and target volumes, yields the self construction. """ function GlaOprMem(cmpInf::GlaKerOpt, trgVol::GlaVol, srcVol::Union{GlaVol,Nothing}=nothing; egoFur::Union{AbstractArray{<:AbstractArray{T}, 1}, Nothing}=nothing, setTyp::DataType=ComplexF64)::GlaOprMem where T<:Union{ComplexF64,ComplexF32} # check functionality if device computation has been requested if cmpInf.devMod == true && !CUDA.functional() error("Device computation requested, but CUDA is not functional. For CPU computation use GlaKerOpt(false)---devMod = false---when declaring compute options.") end # flag for self green function case slfFlg = 0 # self green function case if isnothing(srcVol) || trgVol == srcVol slfFlg = 1 srcVol = trgVol mixInf = GlaExtInf(trgVol, srcVol) # external green function case else # ensure that sum number of cells is even, regenerate if not if sum(mod.(trgVol.cel .+ srcVol.cel, 2)) != 0 # regenerate target volume so that number of cells is even trgVol = glaVolEveGen(trgVol) # regenerate source volume so that number of cells is even srcVol = glaVolEveGen(srcVol) end # useful information for aligning source and target volumes mixInf = GlaExtInf(trgVol, srcVol) end # total cells in circulant totCelCrc = mixInf.trgCel .+ mixInf.srcCel # total number of target and source partitions totParTrg = prod(mixInf.trgDiv) totParSrc = prod(mixInf.srcDiv) # branching depth of multiplication lvl = 3 # number of multiplication branches eoDim = ^(2, lvl) # generate circulant green function, from glaGen if isnothing(egoFur) # memory for circulant green function vector egoCrc = Array{ComplexF64}(undef, 3, 3, totCelCrc..., totParSrc, totParTrg) # self green function case if slfFlg == 1 genEgoSlf!(selectdim(selectdim(egoCrc, 7, 1), 6, 1), trgVol, cmpInf) # external green function case else # partition source and target for consistent distance offsets for trgItr ∈ eachindex(1:totParTrg) # target grid offset trgGrdOff = Tuple(mixInf.trgPar[trgItr]) # offset of center of partition from center of volume trgOrgOff = Rational.((trgGrdOff .- (mixInf.trgDiv .- 1) .// 2) .* trgVol.scl .+ trgVol.org) # grid scale of partition trgGrdScl = mixInf.trgDiv .* trgVol.scl # create target volume partition trgVolPar = GlaVol(mixInf.trgCel, trgVol.scl, trgOrgOff, trgGrdScl) for srcItr ∈ eachindex(1:totParSrc) # relative grid position srcGrdOff = Tuple(mixInf.srcPar[srcItr]) # offset of center of partition from center of volume srcOrgOff = Rational.((srcGrdOff .- (mixInf.srcDiv .- 1) .// 2) .* srcVol.scl .+ srcVol.org) # grid scale of partition srcGrdScl = mixInf.srcDiv .* srcVol.scl # create target volume partition srcVolPar = GlaVol(mixInf.srcCel, srcVol.scl, srcOrgOff, srcGrdScl) # generate green function information for partition pair genEgoExt!(selectdim(selectdim(egoCrc, 7, trgItr), 6, srcItr), trgVolPar, srcVolPar, cmpInf) end end end # verify that egoCrc contains numeric values if maximum(isnan.(egoCrc)) == 1 || maximum(isinf.(egoCrc)) == 1 error("Computed circulant contains non-numeric values.") end # Fourier transform of circulant green function egoFurPrp = Array{eltype(egoCrc)}(undef, totCelCrc..., 6, totParSrc, totParTrg) # plan Fourier transform fftCrcOut = plan_fft(egoCrc[1,1,:,:,:,1,1], (1, 2, 3)) # Fourier transform of the green function, making use of real space # symmetry under transposition--entries are xx, yy, zz, xy, xz, yz for trgItr ∈ eachindex(1:totParTrg), srcItr ∈ eachindex(1:totParSrc), colItr ∈ eachindex(1:3), rowItr ∈ eachindex(1:colItr) # vector direction moved to outer volume index---largest stride egoFurPrp[:,:,:,blkEgoItr(3 * (colItr - 1) + rowItr), srcItr, trgItr] = fftCrcOut * egoCrc[rowItr,colItr,:,:,:,srcItr,trgItr] end # verify integrity of Fourier transform data if maximum(isnan.(egoFurPrp)) == 1 || maximum(isinf.(egoFurPrp)) == 1 error("Fourier transform of circulant contains non-numeric values.") end # number of unique green function blocks ddDim = 6 # Green function construction information mixInf = GlaExtInf(trgVol, srcVol) # determine whether source or target volume contains more cells srcDomDir = map(<, mixInf.trgCel, mixInf.srcCel) trgDomDir = map(!, srcDomDir) # number of unique elements in each cartesian index for a branch truInf = Array{Int}(undef,3) for dirItr ∈ eachindex(1:3) # row and column entries are symmetric or anti-symmetric if mixInf.trgCel[dirItr] == mixInf.srcCel[dirItr] && prod(mixInf.srcDiv) == 1 && prod(mixInf.trgDiv) == 1 && trgVol.org[dirItr] == srcVol.org[dirItr] # store only necessary information truInf[dirItr] = max(Integer(ceil(mixInf.trgCel[dirItr] / 2)) + iseven(mixInf.trgCel[dirItr]), 2) # glaVolEveGen enforces that number of cells is even else truInf[dirItr] = totCelCrc[dirItr] ÷ 2 end end # information copy indicies cpyRng = tuple(map(UnitRange, ones(Int,3), truInf)...) # final Fourier coefficients for a given branch egoFur = Array{Array{setTyp}}(undef, eoDim) # intermediate storage egoFurInt = Array{setTyp}(undef, max.(div.(totCelCrc, 2), (2,2,2))..., ddDim, totParSrc, totParTrg) # only one one eighth of the green function is unique for eoItr ∈ 0:(eoDim - 1) # odd / even branch extraction egoFur[eoItr + 1] = Array{setTyp}(undef, truInf..., ddDim, totParSrc, totParTrg) # first division is along smallest stride -> largest binary division egoFurInt[:,:,:,:,:,:] .= setTyp.(egoFurPrp[(1 + mod(div(eoItr, 4), 2)):2:(end - 1 + mod(div(eoItr, 4), 2)), (1 + mod(div(eoItr, 2), 2)):2:(end - 1 + mod(div(eoItr, 2), 2)), (1 + mod(eoItr, 2)):2:(end - 1 + mod(eoItr, 2)),:,:,:]) # extract unique information @threads for cpyItr ∈ CartesianIndices(cpyRng) egoFur[eoItr + 1][cpyItr,:,:,:] .= egoFurInt[cpyItr,:,:,:] end end end # verify that egoCrc contains numeric values for eoItr ∈ eachindex(1:eoDim) if maximum(isnan.(egoFur[eoItr])) == 1 || maximum(isinf.(egoFur[eoItr])) == 1 error("Fourier information contains non-numeric values.") end end if cmpInf.devMod == true return GlaOprPrp(egoFur, trgVol, srcVol, mixInf, cmpInf, setTyp) else setTyp = eltype(eltype(egoFur)) return GlaOprPrp(egoFur, trgVol, srcVol, mixInf, cmpInf, setTyp) end end #= Memory preparation sub-protocol. =# function GlaOprPrp(egoFur::AbstractArray{<:AbstractArray{T}}, trgVol::GlaVol, srcVol::GlaVol, mixInf::GlaExtInf, cmpInf::GlaKerOpt, setTyp::DataType)::GlaOprMem where T<:Union{ComplexF64,ComplexF32} ###MEMORY DECLARATION # number of embedding levels---dimensionality of ambient space lvls = 3 # operator dimensions---unique vector information does not typically # match operator size for distinct source and target volumes # sum of source and target volumes being divisible by 2 is guaranteed by # glaVolEveGen in GlaOprMemGen brnSze = div.(mixInf.trgCel .+ mixInf.srcCel, 2) # binary indexing system of even and odd coefficient extraction eoDim = ^(2, lvls) # phase transformations (internal for block Toeplitz transformations) phzInf = Array{Array{setTyp}}(undef, lvls) # Fourier transform plans if cmpInf.devMod == true egoFurDev = Array{CuArray{setTyp}}(undef, eoDim) phzInfDev = Array{CuArray{setTyp}}(undef, lvls) fftPlnFwdDev = Array{CUDA.CUFFT.cCuFFTPlan}(undef, lvls) fftPlnRevDev = Array{AbstractFFTs.ScaledPlan}(undef, lvls) else fftPlnFwd = Array{FFTW.cFFTWPlan}(undef, lvls) fftPlnRev = Array{FFTW.ScaledPlan}(undef, lvls) end ###MEMORY PREPARATION # initialize Fourier transform plans if cmpInf.devMod == true for dir ∈ eachindex(1:lvls) # size of vector changes throughout application for external Green vecSzeFwd = ntuple(x -> x <= dir ? brnSze[x] : mixInf.srcCel[x], 3) vecSzeRev = ntuple(x -> x > dir ? mixInf.trgCel[x] : brnSze[x], 3) # Fourier transform planning area fftWrkFwdDev = CuArray{setTyp}(undef, vecSzeFwd..., lvls, prod(mixInf.srcDiv)) fftWrkRevDev = CuArray{setTyp}(undef, vecSzeRev..., lvls, prod(mixInf.trgDiv)) # create Fourier transform plans @CUDA.sync fftPlnFwdDev[dir] = plan_fft!(fftWrkFwdDev, [dir]) @CUDA.sync fftPlnRevDev[dir] = plan_ifft!(fftWrkRevDev, [dir]) end else for dir ∈ eachindex(1:lvls) # size of vector changes throughout application for external Green vecSzeFwd = ntuple(x -> x <= dir ? brnSze[x] : mixInf.srcCel[x], 3) vecSzeRev = ntuple(x -> x > dir ? mixInf.trgCel[x] : brnSze[x], 3) # Fourier transform planning area fftWrkFwd = Array{setTyp}(undef, vecSzeFwd..., lvls, prod(mixInf.srcDiv)) fftWrkRev = Array{setTyp}(undef, vecSzeRev..., lvls, prod(mixInf.trgDiv)) # create Fourier transform plans fftPlnFwd[dir] = plan_fft!(fftWrkFwd, [dir]; flags = FFTW.MEASURE) fftPlnRev[dir] = plan_ifft!(fftWrkRev, [dir]; flags = FFTW.MEASURE) end end # computation of phase transformation for itr ∈ eachindex(1:lvls) # allows calculation odd coefficient numbers phzInf[itr] = setTyp.([exp(-im * pi * k / brnSze[itr]) for k ∈ 0:(brnSze[itr] - 1)]) # active GPU if cmpInf.devMod == true phzInfDev[itr] = CuArray{setTyp}(undef, brnSze...) copyto!(selectdim(phzInfDev, 1, itr), selectdim(phzInf, 1, itr)) end end # number of unique green function blocks ddDim = 2 * lvls # total number of target and source partitions totParTrg = prod(mixInf.trgDiv) totParSrc = prod(mixInf.srcDiv) # number of unique memory elements truInf = div.(max.(mixInf.trgCel, mixInf.srcCel), 2) .+ 1 # transfer Fourier coefficients to GPU if active if cmpInf.devMod == true # active GPU for eoItr ∈ 0:(eoDim - 1), ddItr ∈ eachindex(1:6) egoFurDev[eoItr + 1] = CuArray{setTyp}(undef, truInf..., ddDim, totParSrc, totParTrg) copyto!(selectdim(egoFurDev, 1, eoItr + 1), selectdim(egoFur, 1, eoItr + 1)) end end # wait for completion of GPU operation, create memory structure if cmpInf.devMod == true CUDA.synchronize(CUDA.stream()) GlaOprMem(cmpInf, trgVol, srcVol, mixInf, brnSze, egoFurDev, fftPlnFwdDev, fftPlnRevDev, phzInfDev) else return GlaOprMem(cmpInf, trgVol, srcVol, mixInf, brnSze, egoFur, fftPlnFwd, fftPlnRev, phzInf) end end #= Block index for a given Cartesian index. =# @inline function blkEgoItr(crtInd::Integer)::Integer if crtInd == 1 return 1 elseif crtInd == 2 || crtInd == 4 return 4 elseif crtInd == 5 return 2 elseif crtInd == 7 || crtInd == 3 return 5 elseif crtInd == 8 || crtInd == 6 return 6 elseif crtInd == 9 return 3 else error("Improper use case, there are only nine blocks.") return 0 end end """ GlaOpr(cel::NTuple{3, Int}, scl::NTuple{3, Rational}, org::NTuple{3, Rational}=(0//1, 0//1, 0//1); useGpu::Bool=false, setTyp::DataType=ComplexF64) Construct a self Green operator. # Arguments - `cel::NTuple{3, Int}`: The number of cells in each dimension. - `scl::NTuple{3, Rational}`: The size of each cell in each dimension (in units of wavelength). - `org::NTuple{3, Rational}=(0//1, 0//1, 0//1)`: The origin of the volume in each dimension (in units of wavelength). - `useGpu::Bool=false`: Whether to use the GPU (true) or CPU (false). - `setTyp::DataType=ComplexF64`: The element type of the operator. Must be a subtype of `Complex`. """ function GlaOpr(cel::NTuple{3, Int}, scl::NTuple{3, Rational}, org::NTuple{3, Rational}=(0//1, 0//1, 0//1); useGpu::Bool=false, setTyp::DataType=ComplexF64)::GlaOpr if !(setTyp <: Complex) throw(ArgumentError("setTyp must be a subtype of Complex")) end options = GlaKerOpt(useGpu) slfVol = GlaVol(cel, scl, org) slfMem = GlaOprMem(options, slfVol, setTyp=setTyp) return GlaOpr(slfMem) end """ GlaOpr(celSrc::NTuple{3, Int}, sclSrc::NTuple{3, Rational}, orgSrc::NTuple{3, Rational}, celTrg::NTuple{3, Int}, sclTrg::NTuple{3, Rational}, orgTrg::NTuple{3, Rational}; useGpu::Bool=false, setTyp::DataType=ComplexF64) Construct an external Green's operator. # Arguments - `celSrc::NTuple{3, Int}`: The number of cells in each dimension of the source volume. - `sclSrc::NTuple{3, Rational}`: The size of each cell in each dimension of the source volume (in units of wavelength). - `orgSrc::NTuple{3, Rational}`: The origin of the source volume in each dimension (in units of wavelength). - `celTrg::NTuple{3, Int}`: The number of cells in each dimension of the target volume. - `sclTrg::NTuple{3, Rational}`: The size of each cell in each dimension of the target volume (in units of wavelength). - `orgTrg::NTuple{3, Rational}`: The origin of the target volume in each dimension (in units of wavelength). - `useGpu::Bool=false`: Whether to use the GPU (true) or CPU (false). - `setTyp::DataType=ComplexF64`: The element type of the operator. Must be a subtype of `Complex`. """ function GlaOpr(celSrc::NTuple{3, Int}, sclSrc::NTuple{3, Rational}, orgSrc::NTuple{3, Rational}, celTrg::NTuple{3, Int}, sclTrg::NTuple{3, Rational}, orgTrg::NTuple{3, Rational}; useGpu::Bool=false, setTyp::DataType=ComplexF64)::GlaOpr if !(setTyp <: Complex) throw(ArgumentError("set_type must be a subtype of Complex")) end opt = GlaKerOpt(useGpu) volSrc = GlaVol(celSrc, sclSrc, orgSrc) volTrg = GlaVol(celTrg, sclTrg, orgTrg) extMem = GlaOprMem(opt, volTrg, volSrc, setTyp=setTyp) return GlaOpr(extMem) end """ glaSze(opr::GlaOpr) Returns the size of the input/output arrays for a GlaOpr in tensor form. # Arguments - `op::GlaOpr`: The operator to check. # Returns - A tuple of the sizes of the input and output arrays in tensor form. """ glaSze(opr::GlaOpr) = ((opr.mem.trgVol.cel..., 3), (opr.mem.srcVol.cel..., 3)) """ glaSze(op::GlaOpr, dim::Int) Returns the size of the input/output arrays for a GlaOpr in tensor form. # Arguments - `op::GlaOpr`: The operator to check. - `dim::Int`: The length of the dimension to check. # Returns - The size of the input/output arrays for a GlaOpr in tensor form. """ glaSze(opr::GlaOpr, dim::Int) = ((opr.mem.trgVol.cel..., 3), (opr.mem.srcVol.cel..., 3))[dim]
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
4309
#= Compare self Green function against analytic form =# const π = 3.1415926535897932384626433832795028841971693993751058209749445923 const sepTol = 1.0e-9 const lowTol = 1.0e-12 #= egoAna is the analytic Green function. =# function egoAna!(anaOut::AbstractArray{T}, slfVol::GlaVol, trgRng::Vector{<:StepRange}, dipPos::Vector{<:Rational}, dipVec::Vector{T})::Nothing where T<:Union{ComplexF64,ComplexF64} # memory allocation linItr = zeros(Int,3) egoCel = Array{eltype(anaOut)}(undef, slfVol.cel..., 3) # separation magnitude and unit vector sep = 0.0 sH = zeros(eltype(anaOut),3) # operators components sHs = zeros(eltype(anaOut), 3, 3) id = [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0] egoPar = zeros(eltype(anaOut), 3, 3) # Green function computation for crtItr ∈ CartesianIndices(tuple(length.(trgRng)...)) # index positions for dirItr ∈ 1:3 linItr[dirItr] = LinearIndices(egoCel)[crtItr, dirItr] end # separation vector sep = 2.0 * π * sqrt((trgRng[1][crtItr[1]] - dipPos[1])^2 + (trgRng[2][crtItr[2]] - dipPos[2])^2 + (trgRng[3][crtItr[3]] - dipPos[3])^2) # separation too small, use self-point approximation if sep < sepTol mul!(view(anaOut, linItr), (2.0 * ^(π, 2.0) * 2.0 * im / 3.0) .* id, dipVec) else sH = (2 * π) .* (trgRng[1][crtItr[1]] - dipPos[1], trgRng[2][crtItr[2]] - dipPos[2], trgRng[3][crtItr[3]] - dipPos[3]) ./ sep sHs = [(sH[1] * sH[1]) (sH[1] * sH[2]) (sH[1] * sH[3]); (sH[2] * sH[1]) (sH[2] * sH[2]) (sH[2] * sH[3]); (sH[3] * sH[1]) (sH[3] * sH[2]) (sH[3] * sH[3])] egoPar = (2.0 * ^(π, 2.0) * exp(im * sep) / sep) .* (((1.0 + (im * sep - 1.0) / ^(sep, 2.0)) .* id) .- ((1.0 + 3.0 * (im * sep - 1.0) / ^(sep, 2.0)) .* sHs)) LinearAlgebra.mul!(view(anaOut, linItr), egoPar, dipVec) end end return nothing end # compare against analytic discrete dipole solution dipVec = zeros(ComplexF64, 3) relErr = zeros(Float64, 3) anaOut = Array{ComplexF64}(undef, 3 * prod(oprSlfHst.srcVol.cel)) numOut = Array{ComplexF64}(undef, oprSlfHst.srcVol.cel..., 3) difMat = Array{Float64}(undef, oprSlfHst.srcVol.cel..., 3) innVecHst = Array{eltype(oprSlfHst.egoFur[1])}(undef, oprSlfHst.srcVol.cel..., 3) # window to remove for field comparisons winSze = 4 * minimum(oprSlfHst.srcVol.scl) winInt = minimum([Int(div(1//2 * winSze, minimum(oprSlfHst.srcVol.scl))), minimum(oprSlfHst.srcVol.cel)]) # check window size if winInt > minimum(oprSlfHst.srcVol.cel) error("Excluded window is too large for slfVolume.") end winSze = winInt * minimum(oprSlfHst.srcVol.scl) # cartesian direction loop for dipDir ∈ eachindex(1:3) dipLoc = Int.([div(oprSlfHst.srcVol.cel[1], 2), div(oprSlfHst.srcVol.cel[1], 2), div(oprSlfHst.srcVol.cel[1], 2)]) # dipole direction and location dipVec[:] .= 0.0 + 0.0im dipVec[dipDir] = 1.0 + 0.0im local dipPos = [oprSlfHst.srcVol.grd[1][dipLoc[1]], oprSlfHst.srcVol.grd[2][dipLoc[2]], oprSlfHst.srcVol.grd[3][dipLoc[3]]] # output range for discrete dipole computation local trgRng = copy(oprSlfHst.srcVol.grd) # preform computations innVecHst[:,:,:,:] .= 0.0 + 0.0im; innVecHst[dipLoc[1], dipLoc[2], dipLoc[2], dipDir] = (1.0 + 0.0im) / prod(oprSlfHst.srcVol.scl) outVecHst = egoOpr!(oprSlfHst, innVecHst); copyto!(numOut, outVecHst); egoAna!(anaOut, oprSlfHst.srcVol, trgRng, dipPos, dipVec); global anaOut = reshape(anaOut, oprSlfHst.srcVol.cel..., 3); # comparison array fldDif = 0.0; for crtItr ∈ CartesianIndices((oprSlfHst.srcVol.cel..., 3)) # field difference fldDif = abs(anaOut[crtItr] - numOut[crtItr]) difMat[crtItr] = min(fldDif, fldDif / max(abs(numOut[crtItr]), lowTol)) end # remove points adjacent to dipole for comparison difMat[(dipLoc[1] - winInt):(dipLoc[1] + winInt), (dipLoc[2] - winInt):(dipLoc[2] + winInt), (dipLoc[3] - winInt):(dipLoc[3] + winInt), :] .= 0.0 + 0.0im; # record maximum relative error in remaining vectors global relErr[dipDir] = maximum(difMat) # reset for further tests copyto!(innVecHst, zeros(eltype(innVecHst), oprSlfHst.srcVol.cel..., 3)); global anaOut = reshape(anaOut, 3 * prod(oprSlfHst.srcVol.cel)); end global anaOut = reshape(anaOut, oprSlfHst.srcVol.cel..., 3); println("Maximum relative field difference outside of ", winSze, " exclusion window.") @show relErr;
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
1991
#= Compare external and self Green functions =# ## verify agreement of host and device computation # input vector for merged Green function innVecMrgHst = zeros(useTyp, celU..., 3) # source current limited to celA half rand!(view(innVecMrgHst, :, 1:celA[2], :, :)) # prepare device computation if CUDA is functional if CUDA.functional() innVecMrgDev = CUDA.zeros(useTyp, celU..., 3) # transfer information to GPU copyto!(innVecMrgDev, innVecMrgHst) # confirm host and device computation give equivalent results outVecMrgHst = egoOpr!(oprMrgHst, innVecMrgHst) outVecMrgDev = egoOpr!(oprMrgDev, innVecMrgDev) println("Host device self compute agreement: ", @test all(outVecMrgHst .≈ Array(outVecMrgDev))) end ## verify agreement of self and merged external Green function # input vector for merged Green function innVecMrgHst = zeros(useTyp, celU..., 3) # source current limited to celA half rand!(view(innVecMrgHst, :, 1:celA[2], :, :)) # input vector for host external Green function innVecExtHst = zeros(useTyp, celA..., 3) # transfer information to external Green function copyto!(innVecExtHst, view(innVecMrgHst, 1:celA[1], 1:celA[2], 1:celA[3], :)) if CUDA.functional() # input vector for device external Green function innVecExtDev = CUDA.zeros(useTyp, celA..., 3) # transfer information to external device Green function copyto!(innVecExtDev, innVecExtHst) # confirm host and device computation give equivalent results outVecExtDev = egoOpr!(oprExtDev, innVecExtDev) end outVecMrgHst = egoOpr!(oprMrgHst, innVecMrgHst) outVecExtHst = egoOpr!(oprExtHst, innVecExtHst) # confirm host and device computation give equivalent results if CUDA.functional() println("Host device external compute agreement: ", @test all(outVecExtHst .≈ Array(outVecExtDev))) end # confirm external and self computation give equivalent results println("Self external compute agreement: ", @test all(view(outVecMrgHst, 1:celB[1], (celB[2] + 1):celU[2], 1:celB[3], :) .≈ outVecExtHst))
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
1402
const cubRelTol = 1e-8; const cubAbsTol = 1e-12; #= verify that increasing quadrature order does not change integral values. =# function wekIntChk(scl::NTuple{3,<:Rational}, glOrd::Integer)::Array{Float64,1} opts = GlaKerOpt(false) # weak integral values for internally set quadrature order ws1 = GilaElectromagnetics.wekS(scl, GilaElectromagnetics.gauQud(glOrd), opts) we1 = GilaElectromagnetics.wekE(scl, GilaElectromagnetics.gauQud(glOrd), opts) wv1 = GilaElectromagnetics.wekV(scl, GilaElectromagnetics.gauQud(glOrd), opts) # weak integral values for additional quadrature points ws2 = GilaElectromagnetics.wekS(scl, GilaElectromagnetics.gauQud(glOrd + 8), opts) we2 = GilaElectromagnetics.wekE(scl, GilaElectromagnetics.gauQud(glOrd + 8), opts) wv2 = GilaElectromagnetics.wekV(scl, GilaElectromagnetics.gauQud(glOrd + 8), opts) # differences intDifS = real(maximum(abs.(ws1 .- ws2) ./ abs.(ws2))) intDifE = real(maximum(abs.(we1 .- we2) ./ abs.(we2))) intDifV = real(maximum(abs.(wv1 .- wv2) ./ abs.(wv2))) return [intDifS, intDifE, intDifV] end # perform test intDif = wekIntChk(oprSlfHst.srcVol.scl, oprSlfHst.cmpInf.intOrd) if maximum(abs.(intDif)) < cubRelTol println("Integration convergence test passed for self volume.") else println("Integration convergence test failed. Default GlaKerOpt integration order may be insufficient, consult glaMem.jl.") end
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
3729
using Test # Make sure the constructors throw if the type is not a subtype of Complex @test_throws ArgumentError GlaOpr((1, 1, 1), (1//1, 1//1, 1//1), (0//1, 0//1, 0//1), setTyp=Float64) self_operator_host = GlaOpr(oprSlfHst) external_operator_host = GlaOpr(oprExtHst) merge_operator_host = GlaOpr(oprMrgHst) if CUDA.functional() external_operator_device = GlaOpr(oprExtDev) merge_operator_device = GlaOpr(oprMrgDev) end function generic_tests(opr::GlaOpr) # Make sure the eltype is complex @test eltype(opr) <: Complex # Create some data to feed to Gila x = ones(eltype(opr), size(opr, 2)) x_gilashape = reshape(x, glaSze(opr, 2)) x_gilashape_copy = deepcopy(x_gilashape) if opr.mem.cmpInf.devMod x_gilashape_copy = CuArray(x_gilashape_copy) end reference_acted_x = egoOpr!(opr.mem, x_gilashape_copy) # Make sure the tensor multiplication is correct acted_x_gilashape = opr * x_gilashape @test acted_x_gilashape ≈ reference_acted_x # Make sure the input vector is not mutated @test x_gilashape == reshape(ones(eltype(opr), size(opr, 2)), glaSze(opr, 2)) # Make sure the vector multiplication is correct acted_x = opr * x @test acted_x ≈ vec(reference_acted_x) # Make sure the input vector is not mutated @test x == ones(eltype(opr), size(opr, 2)) # Make sure we can't multiply by the wrong complex type t = eltype(opr) <: ComplexF32 ? ComplexF64 : ComplexF32 bad_input = ones(t, size(opr, 2)) @test_throws AssertionError opr * bad_input # Make sure we get an error if the size of the input vector is wrong bad_input = ones(eltype(opr), size(opr, 2) + 1) @test_throws DimensionMismatch opr * bad_input # Make sure the adjoint of the adjoint is the original operator adj = adjoint(opr) adj_adj = adjoint(adj) @test adjoint(adj).mem.egoFur == opr.mem.egoFur @test adj_adj * x ≈ opr * x @test isadjoint(opr) == false @test isadjoint(adj) == true # Some proprerties @test issymmetric(opr) == false @test isposdef(opr) == false @test ishermitian(opr) == false @test isdiag(opr) == false end @testset "Self operator host" begin @test size(self_operator_host) == (16*16*16*3, 16*16*16*3) @test glaSze(self_operator_host) == ((16, 16, 16, 3), (16, 16, 16, 3)) @test isselfoperator(self_operator_host) == true @test isexternaloperator(self_operator_host) == false generic_tests(self_operator_host) end @testset "External operator host" begin @test size(external_operator_host) == (16*16*16*3, 16*16*16*3) @test glaSze(external_operator_host) == ((16, 16, 16, 3), (16, 16, 16, 3)) @test isselfoperator(external_operator_host) == false @test isexternaloperator(external_operator_host) == true generic_tests(external_operator_host) end @testset "Merge operator host" begin @test size(merge_operator_host) == (16*32*16*3, 16*32*16*3) @test glaSze(merge_operator_host) == ((16, 32, 16, 3), (16, 32, 16, 3)) @test isselfoperator(merge_operator_host) == true @test isexternaloperator(merge_operator_host) == false generic_tests(merge_operator_host) end if CUDA.functional() @testset "External operator device" begin @test size(external_operator_device) == (16*16*16*3, 16*16*16*3) @test glaSze(external_operator_device) == ((16, 16, 16, 3), (16, 16, 16, 3)) @test isselfoperator(external_operator_device) == false @test isexternaloperator(external_operator_device) == true generic_tests(external_operator_device) end @testset "Merge operator device" begin @test size(merge_operator_device) == (16*32*16*3, 16*32*16*3) @test glaSze(merge_operator_device) == ((16, 32, 16, 3), (16, 32, 16, 3)) @test isselfoperator(merge_operator_device) == true @test isexternaloperator(merge_operator_device) == false generic_tests(merge_operator_device) end end
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
1296
# memory declaration global linItr = 0 innVecHst = zeros(eltype(oprSlfHst.egoFur[1]), oprSlfHst.srcVol.cel..., 3) egoCel = Array{eltype(innVecHst)}(undef, oprSlfHst.srcVol.cel..., 3) egoDenMat = Array{eltype(innVecHst)}(undef, 3 * prod(oprSlfHst.srcVol.cel), 3 * prod(oprSlfHst.srcVol.cel)) egoDenMatAsm = Array{eltype(innVecHst)}(undef, 3 * prod(oprSlfHst.srcVol.cel), 3 * prod(oprSlfHst.srcVol.cel)) # fill Green function matrix for crtItr ∈ CartesianIndices(tuple(oprSlfHst.srcVol.cel..., 3)) # linear index global linItr = LinearIndices(egoCel)[crtItr] # set source innVecHst[crtItr] = (1.0 + 0.0im) # calculate resulting field outVecHst = egoOpr!(oprSlfHst, innVecHst) # save field result copyto!(view(egoDenMat, :, linItr), outVecHst) # reset input vector copyto!(innVecHst, zeros(eltype(innVecHst), oprSlfHst.srcVol.cel..., 3)) end # compute anti-symmetric component adjoint!(egoDenMatAsm, egoDenMat); lmul!((0.0 + 0.5im) * conj(cmpInfHst.frqPhz)^2, egoDenMatAsm); axpy!((0.0 - 0.5im) * (cmpInfHst.frqPhz)^2, egoDenMat, egoDenMatAsm); # numerical eigenvalues of anti-symmetric component of the Green function sVals = eigvals(egoDenMatAsm); println("Computed minimum eigenvalue of ", minimum(sVals), ".") println("A minimal value greater than -1.0e-6 is considered normal.")
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
695
# get number of active threads threads = nthreads() # Set the number of BLAS threads. The number of Julia threads is set as an # environment variable. The total number of threads is Julia threads + BLAS # threads. Gila is does not call BLAS libraries during threaded operations, # so both thread counts can be set near the available number of cores. BLAS.set_num_threads(threads) # analogous comments apply to FFTW threads FFTW.set_num_threads(threads) # confirm thread counts blasThreads = BLAS.get_num_threads() fftwThreads = FFTW.get_num_threads() println("GilaTest environment initialized with ", nthreads(), " Julia threads, $blasThreads BLAS threads, and $fftwThreads FFTW threads.")
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
3973
###UTILITY LOADING using CUDA, AbstractFFTs, FFTW, Base.Threads, LinearAlgebra, LinearAlgebra.BLAS, Random, GilaElectromagnetics, Test, Serialization, Scratch include("preamble.jl") ###SETTINGS # type for tests useTyp = ComplexF32 # number of cells in each volume # to run external operator test, celU should be the union of celA and celB celB = (16, 16, 16) celA = (16, 16, 16) celU = (16, 32, 16) # size of cells relative to wavelength # to run external operator test, the scales of the three volumes should match sclB = (1//50, 1//50, 1//50) sclA = (1//50, 1//50, 1//50) sclU = (1//50, 1//50, 1//50) # center position of volumes # to run external operator test, volA should touch (but not overlap!) volB orgB = (0//1, 16//50, 0//1) orgA = (0//1, 0//1, 0//1) orgU = (0//1, 0//1, 0//1) ## compute settings # use for host execution cmpInfHst = GlaKerOpt(false) # use for device execution if CUDA.functional() cmpInfDev = GlaKerOpt(true) end ###PREP # build Gila volumes volB = GlaVol(celB, sclB, orgB) volA = GlaVol(celA, sclA, orgA) volU = GlaVol(celU, sclU, orgU) ###OPERATOR MEMORY println("Green function construction started.") function getFur(fname) preload_dir = @get_scratch!("preload") if isfile(joinpath(preload_dir, fname)) return deserialize(joinpath(preload_dir, fname)) end return nothing end function writeFur(fur, fname) preload_dir = @get_scratch!("preload") serialize(joinpath(preload_dir, fname), fur) end # generate from scratch---new circulant matrices furSlfHst = getFur("slfHst.fur") if isnothing(furSlfHst) oprSlfHst = GlaOprMem(cmpInfHst, volA, setTyp = useTyp) writeFur(oprSlfHst.egoFur, "slfHst.fur") furSlfHst = oprSlfHst.egoFur else oprSlfHst = GlaOprMem(cmpInfHst, volA, egoFur = furSlfHst, setTyp = useTyp) end furExtHst = getFur("extHst.fur") if isnothing(furExtHst) oprExtHst = GlaOprMem(cmpInfHst, volB, volA, setTyp = useTyp) furExtHst = oprExtHst.egoFur writeFur(furExtHst, "extHst.fur") else oprExtHst = GlaOprMem(cmpInfHst, volB, volA, egoFur = furExtHst, setTyp = useTyp) end # merged domains to check validity of external operator construction furMrgHst = getFur("mrgHst.fur") if isnothing(furMrgHst) oprMrgHst = GlaOprMem(cmpInfHst, volU, setTyp = useTyp) writeFur(oprMrgHst.egoFur, "mrgHst.fur") furMrgHst = oprMrgHst.egoFur else oprMrgHst = GlaOprMem(cmpInfHst, volU, egoFur = furMrgHst, setTyp = useTyp) end # run same test on device if CUDA.functional() furExtDev = getFur("extDev.fur") if isnothing(furExtDev) oprExtDev = GlaOprMem(cmpInfDev, volB, volA, setTyp = useTyp) writeFur(oprExtDev.egoFur, "extDev.fur") furExtDev = oprExtDev.egoFur else oprExtDev = GlaOprMem(cmpInfDev, volB, volA, egoFur = furExtDev, setTyp = useTyp) end furMrgDev = getFur("mrgDev.fur") if isnothing(furMrgDev) oprMrgDev = GlaOprMem(cmpInfDev, volU, setTyp = useTyp) writeFur(oprMrgDev.egoFur, "mrgDev.fur") furMrgDev = oprMrgDev.egoFur else oprMrgDev = GlaOprMem(cmpInfDev, volU, egoFur = furMrgDev, setTyp = useTyp) end end # serialize / deserialize to reuse Fourier information println("Green function construction completed.") ###TESTS ## integral convergence # println("Integral convergence test started.") # include("intConTest.jl") # println("Integral convergence test completed.") # ## analytic agreement test on self operator # println("Analytic test started.") # include("anaTest.jl") # println("Analytic test completed.") # ## positive semi-definite test on self operator # # test becomes very slow for domains larger than [16,16,16] # println("Semi-definiteness test started.") # include("posDefTest.jl") # println("Semi-definiteness test completed.") ## test external Green function using self Green function println("External operator test started.") include("extSlfTest.jl") println("External operator test completed.") #test the GreensOperator structs println("GlaOpr test started.") include("oprTest.jl") println("GlaOpr test completed.") println("Testing complete.")
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
code
4142
###UTILITY LOADING using GilaElectromagnetics #= Basic code to generate the (dense) matrix of a self Green function. For a standard desktop computer, memory issues will likely begin around a thousand cells---16^3 is 4096. =# """ function genEgoMat(celScl::{3,<:Rational}, celNum::Ntuple{3,<:Integer})::Array{ComplexF64,2} Generate dense matrix of a Green function. """ function genEgoMat(celScl::NTuple{3,<:Rational}, celNum::NTuple{3,<:Integer})::Array{ComplexF64,2} # copy tolerance---do not copy values if below threshold cpyTol = 1.0e-15 # boiler plate compute information, alter to tighten tolerances cmpInf = GlaKerOpt(false) # create self volume at the origin volOrg = (0//1, 0//1, 0//1) slfVol = GlaVol(celNum, celScl, volOrg) # interaction information mixInf = GlaExtInf(slfVol, slfVol) # generate circulant green function---GilaCrc module egoCrc = Array{ComplexF64}(undef, 3, 3, (mixInf.trgCel .+ mixInf.srcCel)...) GilaElectromagnetics.genEgoSlf!(egoCrc, slfVol, cmpInf) # verify that egoCrc contains numeric values if maximum(isnan.(egoCrc)) == 1 || maximum(isinf.(egoCrc)) == 1 error("Computed circulant contains non-numeric values.") end # allocate matrix memory---mixInf.srcCel == mixInf.trgCel egoMat = zeros(ComplexF64, 3 .* prod(mixInf.srcCel), 3 .* prod(mixInf.srcCel)) # linear indices, offset by 1, for accessing matrix linInd = LinearIndices(mixInf.srcCel) .- 1 # copy seed Toeplitz information into matrix @threads for crtInd ∈ CartesianIndices(Tuple(mixInf.srcCel)) # linear offset off = 3 * linInd[crtInd] #xx if abs(egoCrc[1,1,crtInd]) > cpyTol egoMat[1 + off, 1] = egoCrc[1,1,crtInd] end #xy if abs(egoCrc[1,2,crtInd]) > cpyTol egoMat[1 + off, 2] = egoCrc[1,2,crtInd] end #xz if abs(egoCrc[1,3,crtInd]) > cpyTol egoMat[1 + off, 3] = egoCrc[1,3,crtInd] end #yx egoMat[2 + off, 1] = egoMat[1 + off, 2] #yy if abs(egoCrc[2,2,crtInd]) > cpyTol egoMat[2 + off, 2] = egoCrc[2,2,crtInd] end #yz if abs(egoCrc[2,3,crtInd]) > cpyTol egoMat[2 + off, 3] = egoCrc[2,3,crtInd] end #zx egoMat[3 + off, 1] = egoMat[1 + off, 3] #zy egoMat[3 + off, 2] = egoMat[2 + off, 3] if abs(egoCrc[3,3,crtInd]) > cpyTol egoMat[3 + off, 3] = egoCrc[3,3,crtInd] end end #expand block Toeplitz structure for dimItr ∈ eachindex(1:3) wrtSymToeBlc!(egoMat, (3 * prod(celNum[1:(dimItr - 1)]), 3 * prod(celNum[1:(dimItr - 1)])), celNum[dimItr]) end return egoMat end #= Utility function adding a level of (symmetric) block Toeplitz structure. blcSze is the number of low-level data elements contained in a entry of the current structure. blcDim is the the dimension of the current structure. =# function wrtSymToeBlc!(toeMat::Array{<:Number,2}, blcSze::NTuple{2,<:Integer}, blcDim::Integer)::Nothing # size of a copy unit untSze = blcSze[1] * blcDim # number of block partitions contained in matrix numPrt = size(toeMat)[1] / untSze # check that result is sensible if !isinteger(numPrt) error("Proposed dimensions are not logically consistent.") end numPrt = Integer(numPrt) # unit copy loop for supItr ∈ range(0, (numPrt - 1)) untOff = untSze * supItr # dimension copy loop for dimItr ∈ eachindex(1:(blcDim - 1)) rowOff = blcSze[1] * dimItr colOff = blcSze[2] * dimItr # offset source range srcCrtRngStd = CartesianIndices(( (1 + untOff):(untOff + untSze - rowOff), blcSze[2])) # modulo source range srcCrtRngMod = CartesianIndices(( (1 + untOff + untSze - rowOff):(untOff + untSze), blcSze[2])) # offset copy range cpyCrtRngStd = CartesianIndices(( (1 + rowOff + untOff):(untOff + untSze), (1 + colOff):(colOff + blcSze[2]))) # modulo copy range cpyCrtRngMod = CartesianIndices(( (1 + untOff):(rowOff + untOff), (1 + colOff):(colOff + blcSze[2]))) # standard element copy loop for (cpyItr, srcItr) ∈ zip(cpyCrtRngStd, srcCrtRngStd) toeMat[cpyItr] = toeMat[srcItr] end # shifted element copy loop for (cpyItr, srcItr) ∈ zip(cpyCrtRngMod, srcCrtRngMod) toeMat[cpyItr] = toeMat[srcItr] end end end return nothing end
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
docs
657
Incomplete documentation of the package can be found in the doc folder. [![Build status (Github Actions)](https://github.com/moleskySean/GilaElectromagnetics.jl/workflows/CI/badge.svg)](https://github.com/moleskySean/GilaElectromagnetics.jl/actions) [![codecov.io](http://codecov.io/github/moleskySean/GilaElectromagnetics.jl/coverage.svg?branch=main)](http://codecov.io/github/moleskySean/GilaElectromagnetics.jl?branch=main) [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://YOUR_USERNAME.github.io/MyAwesomePackage.jl/stable) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://YOUR_USERNAME.github.io/MyAwesomePackage.jl/dev)
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
docs
296
# The GilaElectromagnetics Module ```@docs GilaElectromagnetics ``` ## Module Index ```@index Modules = [GilaElectromagnetics] Order = [:constant, :type, :function, :macro] ``` ## Detailed API ```@autodocs Modules = [GilaElectromagnetics] Order = [:constant, :type, :function, :macro] ```
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
1.0.3
6201cfe749b49afbd3572b05f49b13b3dc7cdd55
docs
123
# GilaElectromagnetics.jl Documentation for GilaElectromagnetics.jl https://github.com/moleskySean/GilaElectromagnetics.jl
GilaElectromagnetics
https://github.com/moleskySean/GilaElectromagnetics.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
494
push!(LOAD_PATH,"../src/") using Documenter, ImplicitArrays const pages = [ "Home" => "index.md" ] makedocs( modules = [ImplicitArrays], clean = true, doctest = true, linkcheck = true, checkdocs = :all, pages = pages, format = Documenter.HTML(), sitename = "ImplicitArrays.jl", repo = Remotes.GitHub("tkemmer", "ImplicitArrays.jl") ) deploydocs(; repo = "github.com/tkemmer/ImplicitArrays.jl.git", devbranch = "master" )
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
351
module ImplicitArrays include("compat.jl") include("block.jl") export BlockMatrix include("interaction.jl") export ConstInteractionFunction, GenericInteractionFunction, InteractionFunction, InteractionMatrix include("fixedvalue.jl") export FixedValueArray include("rowprojection.jl") export RowProjectionMatrix, RowProjectionVector end # module
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
2910
""" BlockMatrix{T} <: AbstractArray{T, 2} Implicit block matrix of equally-sized matrices with elements of type `T`. # Constructors BlockMatrix(blocks) BlockMatrix{T}(blocks) BlockMatrix{T}(rows, cols[, blocks...]) BlockMatrix(rows, cols, first_block[, more_blocks...]) Create a new block matrix from the given matrix of matrices. Alternatively, create the block matrix from a sequence of matrices, given the number of `rows` and `cols`. # Examples ```jldoctest; setup = :(using ImplicitArrays) julia> A = [1 2; 3 4]; B = zeros(Int, 2, 2); julia> C = [x * y for x in 2:3, y in 3:4]; julia> BlockMatrix(1, 4, A, B, B, C) 2×8 BlockMatrix{Int64}: 1 2 0 0 0 0 6 8 3 4 0 0 0 0 9 12 ``` !!! note This type is not suitable for high-performance purposes, as matrix blocks are stored in an abstract container to allow the composition of arbitrary matrix types. For more details, please refer to the [performance tips](https://docs.julialang.org/en/v1/manual/performance-tips/) in the official Julia documentation. """ struct BlockMatrix{T} <: AbstractArray{T, 2} "Dimensions of the (equally-sized) matrix blocks" bdims::NTuple{2, Int} "Matrix blocks" blocks::Array{AbstractArray{T, 2}, 2} function BlockMatrix{T}( blocks::Array{AbstractArray{T, 2}, 2} ) where T bdims = (1, 1) for (i, block) ∈ enumerate(blocks) i > 1 && @assert( size(block) == bdims, "invalid block dimensions (block $i expected $bdims, got $(size(block)))" ) bdims = size(block) end new(bdims, blocks) end end @inline BlockMatrix( blocks::Array{AbstractArray{T, 2}, 2} ) where T = BlockMatrix{T}(blocks) function BlockMatrix{T}( rows::Int, cols::Int, blocks::Vararg{AbstractArray{T, 2}} ) where T @assert( rows * cols == length(blocks), "invalid number of blocks given (expected $(rows * cols), got $(length(blocks)))" ) B = Array{AbstractArray{T, 2}, 2}(undef, rows, cols) for (i, b) in enumerate(blocks) B[Int(ceil(i/cols)), (i - 1) % cols + 1] = b end BlockMatrix{T}(B) end @inline BlockMatrix( rows::Int, cols::Int, block::AbstractArray{T, 2}, blocks::Vararg{AbstractArray{T, 2}} ) where T = BlockMatrix{T}(rows, cols, block, blocks...) @inline Base.size( M::BlockMatrix ) = M.bdims .* size(M.blocks) @inline Base.getindex( M::BlockMatrix, I::Vararg{Int, 2} ) = getindex( M.blocks[Int(ceil(I[1]/M.bdims[1])), Int(ceil(I[2]/M.bdims[2]))], (I[1] - 1) % M.bdims[1] + 1, (I[2] - 1) % M.bdims[2] + 1 ) @inline Base.setindex!( M::BlockMatrix, v::Any, I::Vararg{Int, 2} ) = setindex!( M.blocks[Int(ceil(I[1]/M.bdims[1])), Int(ceil(I[2]/M.bdims[2]))], v, (I[1] - 1) % M.bdims[1] + 1, (I[2] - 1) % M.bdims[2] + 1 )
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
300
# CanonicalIndexError (since Julia 1.8) # https://github.com/JuliaLang/julia/pull/43852 function _throw_canonical_error(fun::String, T::Type) @static if isdefined(Base, :CanonicalIndexError) throw(CanonicalIndexError(fun, T)) else error("$fun not defined for $T") end end
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
1767
""" FixedValueArray{T, N} <: AbstractArray{T, N} Implicit and arbitrarily-sized array with a common value of type `T` for all elements. # Constructors FixedValueArray(val, dims) FixedValueArray(val, dims...) Create a new matrix of the given dimensions `dims`, where each element is represented by the given value `val`. # Examples ```jldoctest; setup = :(using ImplicitArrays) julia> FixedValueArray(0, (2, 5)) 2×5 FixedValueArray{Int64, 2}: 0 0 0 0 0 0 0 0 0 0 julia> FixedValueArray("(^_^) Hi!", 1, 2) 1×2 FixedValueArray{String, 2}: "(^_^) Hi!" "(^_^) Hi!" julia> FixedValueArray(FixedValueArray(5.0, (1, 2)), (1, 3)) 1×3 FixedValueArray{FixedValueArray{Float64, 2}, 2}: [5.0 5.0] [5.0 5.0] [5.0 5.0] julia> length(FixedValueArray(1, 1_000_000_000, 1_000_000_000)) 1000000000000000000 ``` """ struct FixedValueArray{T, N} <: AbstractArray{T, N} "Value representing all matrix elements" val::T "Array dimensions" dims::NTuple{N, Int} end @inline FixedValueArray(val::Any, dims::Int...) = FixedValueArray(val, dims) @inline Base.size(A::FixedValueArray) = A.dims @inline function Base.getindex(A::FixedValueArray, i::Int) @boundscheck checkbounds(A, i) A.val end @inline function Base.getindex(A::FixedValueArray{T, N}, I::Vararg{Int, N}) where {T, N} @boundscheck checkbounds(A, I...) A.val end @inline function Base.setindex!(A::FixedValueArray, ::Any, ::Int) _throw_canonical_error("setindex!", typeof(A)) end # This one is required to have setindex! at index [] throw a CanonicalIndexError instead # of a BoundsError (which is used for all other indices). @inline function Base.setindex!(A::FixedValueArray, ::Any, ::Vararg{Int}) _throw_canonical_error("setindex!", typeof(A)) end
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
4432
""" InteractionFunction{R, C, T} Abstract base type of all interaction functions `R × C → T`. """ abstract type InteractionFunction{R, C, T} end """ struct ConstInteractionFunction{R, C, T} <: InteractionFunction{R, C, T} Interaction function `R × C → T` that ignores its arguments and returns a fixed value. # Constructor ConstInteractionFunction{R, C, T}(val) Create a constant interaction function that always returns `val`. # Examples ```jldoctest; setup = :(using ImplicitArrays) julia> f = ConstInteractionFunction{Float64, Float64, Int64}(42); julia> f(1.0, 1.5) 42 ``` """ struct ConstInteractionFunction{R, C, T} <: InteractionFunction{R, C, T} val::T end @inline (f::ConstInteractionFunction{R, C})(::R, ::C) where {R, C} = f.val """ GenericInteractionFunction{R, C, T} <: InteractionFunction{R, C, T} Interaction function `R × C → T` acting as a type-safe wrapper for a given function. # Constructor GenericInteractionFunction{R, C, T}(fun) Create an interaction function from the given function `fun`. # Examples ```jldoctest; setup = :(using ImplicitArrays) julia> f = GenericInteractionFunction{Int64, Int64, Int64}(+); f(9, 3) 12 julia> g = GenericInteractionFunction{Int64, Int64, Float64}(/); g(9, 3) 3.0 julia> h = GenericInteractionFunction{String, Int64, String}(repeat); h("abc", 3) "abcabcabc" ``` !!! note The interaction function can only be evaluated if there is a method `fun(::R, ::C)` that returns a value of type `T`. Otherwise, a `MethodError` or `TypeError` is thrown. """ struct GenericInteractionFunction{R, C, T} <: InteractionFunction{R, C, T} f::Function end @inline (f::GenericInteractionFunction{R, C, T})(x::R, y::C) where {R, C, T} = f.f(x, y)::T """ InteractionMatrix{T, R, C, F <: InteractionFunction{R, C, T}} <: AbstractArray{T, 2} Interaction matrix with elements of type `T`, generated from row elements of type `R`, column elements of type `C`, and an interaction function `F: R × C → T`. # Constructors InteractionMatrix(rowelems, colelems, interact) InteractionMatrix{T}(rowelems, colelems, interact) Create an interaction matrix for the given row and column element arrays as well as an interaction function. InteractionMatrix(rowelems, colelems, val) Create an interaction matrix for the given (yet unused) row and column element arrays and a constant interaction function always returning `val`. In this form, the interaction matrix acts as a replacement for a two-dimensional [`FixedValueArray`](@ref). # Examples ```jldoctest; setup = :(using ImplicitArrays) julia> InteractionMatrix{Int64}([1, 2, 3], [10, 20, 30], +) 3×3 InteractionMatrix{Int64, Int64, Int64, GenericInteractionFunction{Int64, Int64, Int64}}: 11 21 31 12 22 32 13 23 33 julia> InteractionMatrix([1, 2, 3], [10, 20, 30], 42) 3×3 InteractionMatrix{Int64, Int64, Int64, ConstInteractionFunction{Int64, Int64, Int64}}: 42 42 42 42 42 42 42 42 42 julia> struct DivFun <: InteractionFunction{Int, Int, Float64} end julia> (::DivFun)(x::Int, y::Int) = x / y julia> InteractionMatrix([10, 20, 30], [5, 2, 1], DivFun()) 3×3 InteractionMatrix{Float64, Int64, Int64, DivFun}: 2.0 5.0 10.0 4.0 10.0 20.0 6.0 15.0 30.0 ``` """ struct InteractionMatrix{T, R, C, F <: InteractionFunction{R, C, T}} <: AbstractArray{T, 2} rowelems::Array{R, 1} colelems::Array{C, 1} interact::F @inline function InteractionMatrix( rowelems::Array{R, 1}, colelems::Array{C, 1}, interact::F ) where {T, R, C, F <: InteractionFunction{R, C, T}} new{T, R, C, F}(rowelems, colelems, interact) end end @inline InteractionMatrix{T}( rowelems::Array{R, 1}, colelems::Array{C, 1}, interact::Function ) where {T, R, C} = InteractionMatrix( rowelems, colelems, GenericInteractionFunction{R, C, T}(interact) ) @inline InteractionMatrix( rowelems::Array{R, 1}, colelems::Array{C, 1}, val::T ) where {T, R, C} = InteractionMatrix( rowelems, colelems, ConstInteractionFunction{R, C, T}(val) ) @inline Base.size( A::InteractionMatrix ) = (length(A.rowelems), length(A.colelems)) @inline Base.getindex( A::InteractionMatrix{T}, I::Vararg{Int, 2} ) where T = A.interact(A.rowelems[I[1]], A.colelems[I[2]])::T @inline Base.setindex!( A::InteractionMatrix, ::Any, ::Int ) = _throw_canonical_error("setindex!", typeof(A))
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
4469
""" RowProjectionVector{T} <: AbstractArray{T, 1} Implicit vector projecting a sequence of rows of a given vector with elements of type `T`. # Constructors RowProjectionVector(base, rows) RowProjectionVector(base, rows...) RowProjectionVector{T}(base, rows) Create a new row-projected vector from the given `base` vector and a list or sequence of `rows` corresponding to it. Rows can be used multiple times and in any order. # Examples ```jldoctest; setup = :(using ImplicitArrays) julia> v = [10, 20, 30, 40, 50]; julia> RowProjectionVector(v, [1, 3, 5]) 3-element RowProjectionVector{Int64, Vector{Int64}}: 10 30 50 julia> RowProjectionVector(v, 2, 3, 2) 3-element RowProjectionVector{Int64, Vector{Int64}}: 20 30 20 ``` !!! note Changing an element through `RowProjectionVector` actually changes the element in the underlying array. The changes are still reflected in the `RowProjectionVector`. Thus, caution is advised when changing elements of rows that are contained multiple times in the projection, in order to avoid unwanted side effects. """ struct RowProjectionVector{T, A <: AbstractArray{T, 1}} <: AbstractArray{T, 1} "Base vector from which the projection is created" base::A "Rows used for the projection" rows::Vector{Int} function RowProjectionVector{T, A}( base::A, rows::Vector{Int} ) where {T, A <: AbstractArray{T, 1}} @boundscheck _checkrowbounds(base, rows) new(base, rows) end end @inline RowProjectionVector( base::A, rows::Vector{Int} ) where {T, A <: AbstractArray{T, 1}} = RowProjectionVector{T, A}(base, rows) @inline RowProjectionVector( base::AbstractVector, rows::Vararg{Int} ) = RowProjectionVector(base, collect(Int, rows)) @inline Base.IndexStyle(::Type{<: RowProjectionVector}) = IndexLinear() @inline Base.size( M::RowProjectionVector ) = (length(M.rows),) @inline Base.getindex( M::RowProjectionVector, i::Int ) = getindex(M.base, getindex(M.rows, i)) @inline Base.setindex!( M::RowProjectionVector, v::Any, i::Int ) = setindex!(M.base, v, getindex(M.rows, i)) """ RowProjectionMatrix{T} <: AbstractArray{T, 2} Implicit matrix projecting a sequence of rows of a given matrix with elements of type `T`. # Constructors RowProjectionMatrix(base, rows) RowProjectionMatrix(base, rows...) RowProjectionMatrix{T}(base, rows) Create a new row-projected matrix from the given `base` matrix and a list or sequence of `rows` corresponding to it. Rows can be used multiple times and in any order. # Examples ```jldoctest; setup = :(using ImplicitArrays) julia> M = [10 20 30; 40 50 60; 70 80 90]; julia> RowProjectionMatrix(M, [1, 3]) 2×3 RowProjectionMatrix{Int64, Matrix{Int64}}: 10 20 30 70 80 90 julia> RowProjectionMatrix(M, 2, 3, 2) 3×3 RowProjectionMatrix{Int64, Matrix{Int64}}: 40 50 60 70 80 90 40 50 60 ``` !!! note Changing an element through `RowProjectionMatrix` actually changes the element in the underlying array. The changes are still reflected in the `RowProjectionMatrix`. Thus, caution is advised when changing elements of rows that are contained multiple times in the projection, in order to avoid unwanted side effects. """ struct RowProjectionMatrix{T, A <: AbstractArray{T, 2}} <: AbstractArray{T, 2} "Base matrix from which the projection is created" base::A "Rows used for the projection" rows::Vector{Int} function RowProjectionMatrix{T, A}( base::A, rows::Vector{Int} ) where {T, A <: AbstractArray{T, 2}} @boundscheck _checkrowbounds(base, rows) new(base, rows) end end @inline RowProjectionMatrix( base::A, rows::Vector{Int} ) where {T, A <: AbstractArray{T, 2}} = RowProjectionMatrix{T, A}(base, rows) @inline RowProjectionMatrix( base::AbstractMatrix, rows::Vararg{Int} ) = RowProjectionMatrix(base, collect(Int, rows)) @inline Base.size( M::RowProjectionMatrix ) = (length(M.rows), size(M.base, 2)) @inline Base.getindex( M::RowProjectionMatrix, I::Vararg{Int, 2} ) = getindex(M.base, getindex(M.rows, I[1]), I[2]) @inline Base.setindex!( M::RowProjectionMatrix, v::Any, I::Vararg{Int, 2} ) = setindex!(M.base, v, getindex(M.rows, I[1]), I[2]) @inline function _checkrowbounds( base::AbstractArray, rows::Vector{Int} ) for row ∈ rows checkbounds(base, row, :) end end
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
339
@testitem "Aqua" begin using Aqua # Current workaround to avoid failing tests due to ambiguity in dependencies # https://github.com/JuliaTesting/Aqua.jl/issues/77 @testset "Method ambiguity" begin Aqua.test_ambiguities(ImplicitArrays) end Aqua.test_all(ImplicitArrays; ambiguities=false ) end
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
16085
@testitem "BlockMatrix" begin @testset "empty matrix" begin @test_throws MethodError BlockMatrix(0, 0) for A in [ BlockMatrix(Array{AbstractArray{Int, 2}, 2}(undef, 0, 0)), BlockMatrix{Int}(Array{AbstractArray{Int, 2}, 2}(undef, 0, 0)), BlockMatrix{Int}(0, 0) ] @test A isa AbstractArray{Int, 2} @test size(A) == (0, 0) @test length(A) == 0 @test_throws BoundsError A[] @test_throws BoundsError A[] = 42 @test_throws BoundsError A[1] @test_throws BoundsError A[1] = 42 end @test_throws AssertionError BlockMatrix(0, 0, zeros(Int, 2, 2)) @test_throws AssertionError BlockMatrix{Int}(0, 0, zeros(Int, 2, 2)) @test_throws MethodError BlockMatrix{Int}(0, 0, zeros(2, 2)) end @testset "no rows" begin for A in [ BlockMatrix(Array{AbstractArray{Int, 2}, 2}(undef, 0, 2)), BlockMatrix{Int}(Array{AbstractArray{Int, 2}, 2}(undef, 0, 2)), BlockMatrix{Int}(0, 2) ] @test A isa AbstractArray{Int, 2} @test size(A) == (0, 2) @test length(A) == 0 @test_throws BoundsError A[] @test_throws BoundsError A[] = 42 @test_throws BoundsError A[1] @test_throws BoundsError A[1] = 42 end @test_throws AssertionError BlockMatrix(0, 2, zeros(Int, 2, 2)) @test_throws AssertionError BlockMatrix{Int}(0, 2, zeros(Int, 2, 2)) @test_throws MethodError BlockMatrix{Int}(0, 2, zeros(2, 2)) end @testset "no cols" begin for A in [ BlockMatrix(Array{AbstractArray{Int, 2}, 2}(undef, 2, 0)), BlockMatrix{Int}(Array{AbstractArray{Int, 2}, 2}(undef, 2, 0)), BlockMatrix{Int}(2, 0) ] @test A isa AbstractArray{Int, 2} @test size(A) == (2, 0) @test length(A) == 0 @test_throws BoundsError A[] @test_throws BoundsError A[] = 42 @test_throws BoundsError A[1] @test_throws BoundsError A[1] = 42 end @test_throws AssertionError BlockMatrix(2, 0, zeros(Int, 2, 2)) @test_throws AssertionError BlockMatrix{Int}(2, 0, zeros(Int, 2, 2)) @test_throws MethodError BlockMatrix{Int}(2, 0, zeros(2, 2)) end @testset "single element" begin B11 = 42 .* ones(Int, 1, 1) B = Array{AbstractArray{Int, 2}, 2}(undef, 1, 1) B[1] = B11 for (i, A) in enumerate([ BlockMatrix(B), BlockMatrix{Int}(B), BlockMatrix(1, 1, B11), BlockMatrix{Int}(1, 1, B11) ]) @test A isa AbstractArray{Int, 2} @test size(A) == (1, 1) @test length(A) == 1 A[] = 42 + i @test A[] isa Int @test A[] == B11[] == 42 + i A[1] = 43 + i @test A[1] isa Int @test A[1] == B11[1] == 43 + i A[1, 1] = 44 + i @test A[1, 1] isa Int @test A[1, 1] == B11[1, 1] == 44 + i @test_throws BoundsError A[0] @test_throws BoundsError A[0, 0] @test_throws BoundsError A[0, 1] @test_throws BoundsError A[1, 0] @test_throws BoundsError A[2] @test_throws BoundsError A[1, 2] @test_throws BoundsError A[2, 1] @test_throws BoundsError A[2, 2] @test_throws BoundsError A[0] = 42 @test_throws BoundsError A[0, 0] = 42 @test_throws BoundsError A[0, 1] = 42 @test_throws BoundsError A[1, 0] = 42 @test_throws BoundsError A[2] = 42 @test_throws BoundsError A[1, 2] = 42 @test_throws BoundsError A[2, 1] = 42 @test_throws BoundsError A[2, 2] = 42 end @test_throws AssertionError BlockMatrix{Int}(1, 1) @test_throws AssertionError BlockMatrix(1, 1, B11, B11) @test_throws AssertionError BlockMatrix{Int}(1, 1, B11, B11) @test_throws MethodError BlockMatrix{Float64}(1, 1, B11) end @testset "single row" begin B11 = [1 2] B12 = [3 4] B = Array{AbstractArray{Int, 2}, 2}(undef, 1, 2) B[1] = B11 B[2] = B12 for (i, A) in enumerate([ BlockMatrix(B), BlockMatrix{Int}(B), BlockMatrix(1, 2, B11, B12), BlockMatrix{Int}(1, 2, B11, B12) ]) @test A isa AbstractArray{Int, 2} @test size(A) == (1, 4) @test length(A) == 4 for j in 1:4 A[j] = 42i + j @test A[j] isa Int @test A[j] == 42i + j A[1, j] = 42i + j + 1 @test A[1, j] isa Int @test A[1, j] == 42i + j + 1 end @test_throws BoundsError A[] @test_throws BoundsError A[0] @test_throws BoundsError A[0, 0] @test_throws BoundsError A[0, 1] @test_throws BoundsError A[1, 0] @test_throws BoundsError A[5] @test_throws BoundsError A[1, 5] @test_throws BoundsError A[2, 1] @test_throws BoundsError A[] = 42 @test_throws BoundsError A[0] = 42 @test_throws BoundsError A[0, 0] = 42 @test_throws BoundsError A[0, 1] = 42 @test_throws BoundsError A[1, 0] = 42 @test_throws BoundsError A[5] = 42 @test_throws BoundsError A[1, 5] = 42 @test_throws BoundsError A[2, 1] = 42 end @test_throws AssertionError BlockMatrix{Int}(1, 2) @test_throws AssertionError BlockMatrix(1, 2, B11) @test_throws AssertionError BlockMatrix{Int}(1, 2, B11) @test_throws AssertionError BlockMatrix(1, 2, B11, B12, B12) @test_throws AssertionError BlockMatrix{Int}(1, 2, B11, B12, B12) @test_throws MethodError BlockMatrix{Float64}(1, 2, B11) end @testset "single col" begin B11 = reshape([1, 2], (2, 1)) B21 = reshape([3, 4], (2, 1)) B = Array{AbstractArray{Int, 2}, 2}(undef, 2, 1) B[1] = B11 B[2] = B21 for (i, A) in enumerate([ BlockMatrix(B), BlockMatrix{Int}(B), BlockMatrix(2, 1, B11, B21), BlockMatrix{Int}(2, 1, B11, B21) ]) @test A isa AbstractArray{Int, 2} @test size(A) == (4, 1) @test length(A) == 4 for j in 1:4 A[j] = 42i + j @test A[j] isa Int @test A[j] == 42i + j A[j, 1] = 42i + j + 1 @test A[j, 1] isa Int @test A[j, 1] == 42i + j + 1 end @test_throws BoundsError A[] @test_throws BoundsError A[0] @test_throws BoundsError A[0, 0] @test_throws BoundsError A[0, 1] @test_throws BoundsError A[1, 0] @test_throws BoundsError A[5] @test_throws BoundsError A[5, 1] @test_throws BoundsError A[1, 2] @test_throws BoundsError A[] = 42 @test_throws BoundsError A[0] = 42 @test_throws BoundsError A[0, 0] = 42 @test_throws BoundsError A[0, 1] = 42 @test_throws BoundsError A[1, 0] = 42 @test_throws BoundsError A[5] = 42 @test_throws BoundsError A[5, 1] = 42 @test_throws BoundsError A[1, 2] = 42 end @test_throws AssertionError BlockMatrix{Int}(2, 1) @test_throws AssertionError BlockMatrix(2, 1, B11) @test_throws AssertionError BlockMatrix{Int}(2, 1, B11) @test_throws AssertionError BlockMatrix(2, 1, B11, B21, B21) @test_throws AssertionError BlockMatrix{Int}(2, 1, B11, B21, B21) @test_throws MethodError BlockMatrix{Float64}(2, 1, B11) end @testset "single block" begin B11 = [1 2 3; 4 5 6] B = Array{AbstractArray{Int, 2}, 2}(undef, 1, 1) B[1] = B11 for (i, A) in enumerate([ BlockMatrix(B), BlockMatrix{Int}(B), BlockMatrix(1, 1, B11), BlockMatrix{Int}(1, 1, B11) ]) @test A isa AbstractArray{Int, 2} @test size(A) == (2, 3) @test length(A) == 6 for row in 1:2 for col in 1:3 A[row * col] = 42i + row * col @test A[row * col] isa Int @test A[row * col] == 42i + row * col A[row, col] = 42i + row * col + 1 @test A[row, col] isa Int @test A[row, col] == 42i + row * col + 1 end end @test_throws BoundsError A[] @test_throws BoundsError A[0] @test_throws BoundsError A[0, 0] @test_throws BoundsError A[0, 1] @test_throws BoundsError A[1, 0] @test_throws BoundsError A[7] @test_throws BoundsError A[1, 4] @test_throws BoundsError A[3, 1] @test_throws BoundsError A[] = 42 @test_throws BoundsError A[0] = 42 @test_throws BoundsError A[0, 0] = 42 @test_throws BoundsError A[0, 1] = 42 @test_throws BoundsError A[1, 0] = 42 @test_throws BoundsError A[7] = 42 @test_throws BoundsError A[1, 4] = 42 @test_throws BoundsError A[3, 1] = 42 end @test_throws AssertionError BlockMatrix{Int}(1, 1) @test_throws AssertionError BlockMatrix(1, 1, B11, B11) @test_throws AssertionError BlockMatrix{Int}(1, 1, B11, B11) @test_throws MethodError BlockMatrix{Float64}(1, 1, B11) end @testset "single block row" begin B11 = [1 2 3; 7 8 9] B12 = [4 5 6; 10 11 12] B = Array{AbstractArray{Int, 2}, 2}(undef, 1, 2) B[1] = B11 B[2] = B12 for (i, A) in enumerate([ BlockMatrix(B), BlockMatrix{Int}(B), BlockMatrix(1, 2, B11, B12), BlockMatrix{Int}(1, 2, B11, B12) ]) @test A isa AbstractArray{Int, 2} @test size(A) == (2, 6) @test length(A) == 12 for row in 1:2 for col in 1:6 A[row * col] = 42i + row * col @test A[row * col] isa Int @test A[row * col] == 42i + row * col A[row, col] = 42i + row * col + 1 @test A[row, col] isa Int @test A[row, col] == 42i + row * col + 1 end end @test_throws BoundsError A[] @test_throws BoundsError A[0] @test_throws BoundsError A[0, 0] @test_throws BoundsError A[0, 1] @test_throws BoundsError A[1, 0] @test_throws BoundsError A[13] @test_throws BoundsError A[1, 7] @test_throws BoundsError A[3, 1] @test_throws BoundsError A[] = 42 @test_throws BoundsError A[0] = 42 @test_throws BoundsError A[0, 0] = 42 @test_throws BoundsError A[0, 1] = 42 @test_throws BoundsError A[1, 0] = 42 @test_throws BoundsError A[13] = 42 @test_throws BoundsError A[1, 7] = 42 @test_throws BoundsError A[3, 1] = 42 end @test_throws AssertionError BlockMatrix(1, 2, B11) @test_throws AssertionError BlockMatrix{Int}(1, 2, B11) @test_throws AssertionError BlockMatrix(1, 2, B11, B12, B12) @test_throws AssertionError BlockMatrix{Int}(1, 2, B11, B12, B12) @test_throws MethodError BlockMatrix{Float64}(1, 2, B11, B12) end @testset "single block col" begin B11 = [1 2 3; 4 5 6] B21 = [7 8 9; 10 11 12] B = Array{AbstractArray{Int, 2}, 2}(undef, 2, 1) B[1] = B11 B[2] = B21 for (i, A) in enumerate([ BlockMatrix(B), BlockMatrix{Int}(B), BlockMatrix(2, 1, B11, B21), BlockMatrix{Int}(2, 1, B11, B21) ]) @test A isa AbstractArray{Int, 2} @test size(A) == (4, 3) @test length(A) == 12 for row in 1:4 for col in 1:3 A[row * col] = 42i + row * col @test A[row * col] isa Int @test A[row * col] == 42i + row * col A[row, col] = 42i + row * col + 1 @test A[row, col] isa Int @test A[row, col] == 42i + row * col + 1 end end @test_throws BoundsError A[] @test_throws BoundsError A[0] @test_throws BoundsError A[0, 0] @test_throws BoundsError A[0, 1] @test_throws BoundsError A[1, 0] @test_throws BoundsError A[13] @test_throws BoundsError A[1, 4] @test_throws BoundsError A[5, 1] @test_throws BoundsError A[] = 42 @test_throws BoundsError A[0] = 42 @test_throws BoundsError A[0, 0] = 42 @test_throws BoundsError A[0, 1] = 42 @test_throws BoundsError A[1, 0] = 42 @test_throws BoundsError A[13] = 42 @test_throws BoundsError A[1, 4] = 42 @test_throws BoundsError A[5, 1] = 42 end @test_throws AssertionError BlockMatrix(2, 1, B11) @test_throws AssertionError BlockMatrix{Int}(2, 1, B11) @test_throws AssertionError BlockMatrix(2, 1, B11, B21, B21) @test_throws AssertionError BlockMatrix{Int}(2, 1, B11, B21, B21) @test_throws MethodError BlockMatrix{Float64}(2, 1, B11, B21) end @testset "ordinary" begin B11 = [1 2 3; 7 8 9] B12 = [4 5 6; 10 11 12] B21 = [13 14 15; 19 20 21] B22 = [16 17 18; 22 23 24] B = Array{AbstractArray{Int, 2}, 2}(undef, 2, 2) B[1] = B11 B[2] = B21 B[3] = B12 B[4] = B22 for (i, A) in enumerate([ BlockMatrix(B), BlockMatrix{Int}(B), BlockMatrix(2, 2, B11, B12, B21, B22), BlockMatrix{Int}(2, 2, B11, B12, B21, B22) ]) @test A isa AbstractArray{Int, 2} @test size(A) == (4, 6) @test length(A) == 24 for row in 1:4 for col in 1:6 A[row * col] = 42i + row * col @test A[row * col] isa Int @test A[row * col] == 42i + row * col A[row, col] = 42i + row * col + 1 @test A[row, col] isa Int @test A[row, col] == 42i + row * col + 1 end end @test_throws BoundsError A[] @test_throws BoundsError A[0] @test_throws BoundsError A[0, 0] @test_throws BoundsError A[0, 1] @test_throws BoundsError A[1, 0] @test_throws BoundsError A[25] @test_throws BoundsError A[1, 7] @test_throws BoundsError A[5, 1] @test_throws BoundsError A[] = 42 @test_throws BoundsError A[0] = 42 @test_throws BoundsError A[0, 0] = 42 @test_throws BoundsError A[0, 1] = 42 @test_throws BoundsError A[1, 0] = 42 @test_throws BoundsError A[25] = 42 @test_throws BoundsError A[1, 7] = 42 @test_throws BoundsError A[5, 1] = 42 end @test_throws AssertionError BlockMatrix(2, 2, B11, B12, B21) @test_throws AssertionError BlockMatrix{Int}(2, 2, B11, B12, B21) @test_throws AssertionError BlockMatrix(2, 2, B11, B12, B21, B22, B22) @test_throws AssertionError BlockMatrix{Int}(2, 2, B11, B12, B21, B22, B22) @test_throws MethodError BlockMatrix{Float64}(2, 2, B11, B12, B21, B22) end end
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
189
# CanonicalIndexError (since Julia 1.8) # https://github.com/JuliaLang/julia/pull/43852 @static if !isdefined(Base, :CanonicalIndexError) const CanonicalIndexError = ErrorException end
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
3491
@testitem "FixedValueArray" begin include("compat.jl") @testset "empty arrays" begin A = FixedValueArray(Nothing, 0) @test A isa FixedValueArray{DataType, 1} @test size(A) == (0,) @test length(A) == 0 @test_throws BoundsError A[] @test_throws BoundsError A[1] A = FixedValueArray(Nothing, 0, 0) @test A isa FixedValueArray{DataType, 2} @test size(A) == (0, 0) @test length(A) == 0 @test_throws BoundsError A[] @test_throws BoundsError A[1] A = FixedValueArray(Nothing, 0, 1) @test A isa FixedValueArray{DataType, 2} @test size(A) == (0, 1) @test length(A) == 0 @test_throws BoundsError A[] @test_throws BoundsError A[1] A = FixedValueArray(Nothing, 1, 0) @test A isa FixedValueArray{DataType, 2} @test size(A) == (1, 0) @test length(A) == 0 @test_throws BoundsError A[] @test_throws BoundsError A[1] A = FixedValueArray(Nothing, 0, 0, 0) @test A isa FixedValueArray{DataType, 3} @test size(A) == (0, 0, 0) @test length(A) == 0 @test_throws BoundsError A[] @test_throws BoundsError A[1] end @testset "0-dimensional arrays" begin A = FixedValueArray(Nothing) @test A isa FixedValueArray{DataType, 0} @test size(A) == () @test length(A) == 1 @test_throws BoundsError A[0] @test A[] == Nothing @test_throws CanonicalIndexError A[] = Nothing @test A[1] == Nothing @test_throws CanonicalIndexError A[1] = Nothing @test_throws BoundsError A[2] end @testset "1-dimensional arrays" begin A = FixedValueArray(42, 3) @test A isa FixedValueArray{Int, 1} @test size(A) == (3,) @test length(A) == 3 @test_throws BoundsError A[] @test_throws CanonicalIndexError A[] = 41 @test_throws BoundsError A[0] @test_throws CanonicalIndexError A[0] = 41 for e ∈ A @test e == 42 end for i ∈ eachindex(A) @test A[i] == 42 @test_throws CanonicalIndexError A[i] = 41 end @test_throws BoundsError A[4] @test_throws CanonicalIndexError A[4] = 41 end @testset "2-dimensional arrays" begin A = FixedValueArray(42, 2, 3) @test A isa FixedValueArray{Int, 2} @test size(A) == (2, 3) @test length(A) == 6 @test_throws BoundsError A[] @test_throws CanonicalIndexError A[] = 41 @test_throws BoundsError A[0] @test_throws CanonicalIndexError A[0] = 41 @test_throws BoundsError A[0, 1] @test_throws CanonicalIndexError A[0, 1] = 41 @test_throws BoundsError A[1, 0] @test_throws CanonicalIndexError A[1, 0] = 41 for e ∈ A @test e == 42 end for i ∈ eachindex(A) @test A[i] == 42 @test_throws CanonicalIndexError A[i] = 41 end for i ∈ axes(A, 1), j ∈ axes(A, 2) @test A[i, j] == 42 @test_throws CanonicalIndexError A[i, j] = 42 end @test_throws BoundsError A[7] @test_throws CanonicalIndexError A[7] = 41 @test_throws BoundsError A[3, 1] @test_throws CanonicalIndexError A[0, 1] = 41 @test_throws BoundsError A[1, 4] @test_throws CanonicalIndexError A[1, 0] = 41 end end
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
10497
@testitem "InteractionMatrix" begin include("compat.jl") @testset "empty matrix" begin A = InteractionMatrix(Int[], Int[], 11) @test A isa AbstractArray{Int, 2} @test size(A) == (0, 0) @test_throws BoundsError A[] @test_throws BoundsError A[1] A = InteractionMatrix{Int}(Int[], Int[], +) @test A isa AbstractArray{Int, 2} @test size(A) == (0, 0) @test_throws BoundsError A[] @test_throws BoundsError A[1] A = InteractionMatrix{Float64}(Int[], Int[], /) @test A isa AbstractArray{Float64, 2} @test size(A) == (0, 0) @test_throws BoundsError A[] @test_throws BoundsError A[1] end @testset "no rowelems" begin A = InteractionMatrix(Int[], Int[42, 40, 47], 11) @test A isa AbstractArray{Int, 2} @test size(A) == (0, 3) @test_throws BoundsError A[] @test_throws BoundsError A[1] A = InteractionMatrix{Int}(Int[], Int[42, 40, 47], +) @test A isa AbstractArray{Int, 2} @test size(A) == (0, 3) @test_throws BoundsError A[] @test_throws BoundsError A[1] A = InteractionMatrix{Float64}(Int[], Int[42, 40, 47], /) @test A isa AbstractArray{Float64, 2} @test size(A) == (0, 3) @test_throws BoundsError A[] @test_throws BoundsError A[1] end @testset "no colelems" begin A = InteractionMatrix(Int[42, 40, 47], Int[], 11) @test A isa AbstractArray{Int, 2} @test size(A) == (3, 0) @test_throws BoundsError A[] @test_throws BoundsError A[1] A = InteractionMatrix{Int}(Int[42, 40, 47], Int[], +) @test A isa AbstractArray{Int, 2} @test size(A) == (3, 0) @test_throws BoundsError A[] @test_throws BoundsError A[1] A = InteractionMatrix{Float64}(Int[42, 40, 47], Int[], /) @test A isa AbstractArray{Float64, 2} @test size(A) == (3, 0) @test_throws BoundsError A[] @test_throws BoundsError A[1] end @testset "single value" begin A = InteractionMatrix(Int[2], Int[42], 11) @test A isa AbstractArray{Int, 2} @test size(A) == (1, 1) @test A[] isa Int @test A[] == 11 @test A[1] isa Int @test A[1] == 11 @test A[1, 1] isa Int @test A[1, 1] == 11 @test_throws BoundsError A[2] @test_throws BoundsError A[1, 2] @test_throws BoundsError A[2, 1] @test_throws BoundsError A[2, 2] @test_throws CanonicalIndexError A[] = 13 @test_throws CanonicalIndexError A[1] = 13 @test_throws CanonicalIndexError A[1, 1] = 13 A = InteractionMatrix{Int}(Int[2], Int[42], -) @test A isa AbstractArray{Int, 2} @test size(A) == (1, 1) @test A[] isa Int @test A[] == -40 @test A[1] isa Int @test A[1] == -40 @test A[1, 1] isa Int @test A[1, 1] == -40 @test_throws BoundsError A[2] @test_throws BoundsError A[1, 2] @test_throws BoundsError A[2, 1] @test_throws BoundsError A[2, 2] @test_throws CanonicalIndexError A[] = 13 @test_throws CanonicalIndexError A[1] = 13 @test_throws CanonicalIndexError A[1, 1] = 13 A = InteractionMatrix{Int}(Int[42], Int[2], -) @test A[1] == 40 A = InteractionMatrix{Int}(Int[42], Int[2], /) @test_throws TypeError A[1] A = InteractionMatrix{Float64}(Int[42], Int[2], /) @test A isa AbstractArray{Float64, 2} @test A[1] isa Float64 @test A[1] == 21.0 end @testset "single rowelem" begin A = InteractionMatrix(Int[2], Int[42, 40, 47], 11) @test A isa AbstractArray{Int, 2} @test size(A) == (1, 3) @test_throws BoundsError A[] @test A[1] isa Int @test A[1] == 11 @test A[2] isa Int @test A[2] == 11 @test A[3] isa Int @test A[3] == 11 @test A[1, 1] isa Int @test A[1, 1] == 11 @test A[1, 2] isa Int @test A[1, 2] == 11 @test A[1, 3] isa Int @test A[1, 3] == 11 @test_throws BoundsError A[4] @test_throws BoundsError A[1, 4] @test_throws BoundsError A[2, 1] A = InteractionMatrix{Int}(Int[2], Int[42, 40, 47], -) @test A isa AbstractArray{Int, 2} @test size(A) == (1, 3) @test_throws BoundsError A[] @test A[1] isa Int @test A[1] == -40 @test A[2] isa Int @test A[2] == -38 @test A[3] isa Int @test A[3] == -45 @test A[1, 1] isa Int @test A[1, 1] == -40 @test A[1, 2] isa Int @test A[1, 2] == -38 @test A[1, 3] isa Int @test A[1, 3] == -45 @test_throws BoundsError A[4] @test_throws BoundsError A[1, 4] @test_throws BoundsError A[2, 1] A = InteractionMatrix{Int}(Int[2], Int[42, 40, 47], \) @test_throws TypeError A[1] @test_throws TypeError A[2] @test_throws TypeError A[3] @test_throws TypeError A[1, 1] @test_throws TypeError A[1, 2] @test_throws TypeError A[1, 3] A = InteractionMatrix{Float64}(Int[2], Int[42, 40,47], \) @test A[1] isa Float64 @test A[1] == 21.0 @test A[2] isa Float64 @test A[2] == 20.0 @test A[3] isa Float64 @test A[3] == 23.5 @test A[1, 1] isa Float64 @test A[1, 1] == 21.0 @test A[1, 2] isa Float64 @test A[1, 2] == 20.0 @test A[1, 3] isa Float64 @test A[1, 3] == 23.5 end @testset "single colelem" begin A = InteractionMatrix(Int[42, 40, 47], Int[2], 11) @test A isa AbstractArray{Int, 2} @test size(A) == (3, 1) @test_throws BoundsError A[] @test A[1] isa Int @test A[1] == 11 @test A[2] isa Int @test A[2] == 11 @test A[3] isa Int @test A[3] == 11 @test A[1, 1] isa Int @test A[1, 1] == 11 @test A[2, 1] isa Int @test A[2, 1] == 11 @test A[3, 1] isa Int @test A[3, 1] == 11 @test_throws BoundsError A[4] @test_throws BoundsError A[4, 1] @test_throws BoundsError A[1, 2] A = InteractionMatrix{Int}(Int[42, 40, 47], Int[2], -) @test A isa AbstractArray{Int, 2} @test size(A) == (3, 1) @test_throws BoundsError A[] @test A[1] isa Int @test A[1] == 40 @test A[2] isa Int @test A[2] == 38 @test A[3] isa Int @test A[3] == 45 @test A[1, 1] isa Int @test A[1, 1] == 40 @test A[2, 1] isa Int @test A[2, 1] == 38 @test A[3, 1] isa Int @test A[3, 1] == 45 @test_throws BoundsError A[4] @test_throws BoundsError A[4, 1] @test_throws BoundsError A[1, 2] A = InteractionMatrix{Int}(Int[42, 40, 47], Int[2], /) @test_throws TypeError A[1] @test_throws TypeError A[2] @test_throws TypeError A[3] @test_throws TypeError A[1, 1] @test_throws TypeError A[2, 1] @test_throws TypeError A[3, 1] A = InteractionMatrix{Float64}(Int[42, 40,47], Int[2], /) @test A[1] isa Float64 @test A[1] == 21.0 @test A[2] isa Float64 @test A[2] == 20.0 @test A[3] isa Float64 @test A[3] == 23.5 @test A[1, 1] isa Float64 @test A[1, 1] == 21.0 @test A[2, 1] isa Float64 @test A[2, 1] == 20.0 @test A[3, 1] isa Float64 @test A[3, 1] == 23.5 end @testset "ordinary" begin A = InteractionMatrix(Int[2, 5], Int[42, 40], 11) @test A isa AbstractArray{Int, 2} @test size(A) == (2, 2) @test_throws BoundsError A[] @test A[1] isa Int @test A[1] == 11 @test A[2] isa Int @test A[2] == 11 @test A[3] isa Int @test A[3] == 11 @test A[4] isa Int @test A[4] == 11 @test A[1, 1] isa Int @test A[1, 1] == 11 @test A[2, 1] isa Int @test A[2, 1] == 11 @test A[1, 2] isa Int @test A[1, 2] == 11 @test A[2, 2] isa Int @test A[2, 2] == 11 A = InteractionMatrix{Int}(Int[2, 5], Int[42, 40], -) @test A isa AbstractArray{Int, 2} @test size(A) == (2, 2) @test_throws BoundsError A[] @test A[1] isa Int @test A[1] == -40 @test A[2] isa Int @test A[2] == -37 @test A[3] isa Int @test A[3] == -38 @test A[4] isa Int @test A[4] == -35 @test A[1, 1] isa Int @test A[1, 1] == -40 @test A[2, 1] isa Int @test A[2, 1] == -37 @test A[1, 2] isa Int @test A[1, 2] == -38 @test A[2, 2] isa Int @test A[2, 2] == -35 A = InteractionMatrix{Int}(Int[42, 40], Int[2, 5], -) @test A isa AbstractArray{Int, 2} @test size(A) == (2, 2) @test_throws BoundsError A[] @test A[1] isa Int @test A[1] == 40 @test A[2] isa Int @test A[2] == 38 @test A[3] isa Int @test A[3] == 37 @test A[4] isa Int @test A[4] == 35 @test A[1, 1] isa Int @test A[1, 1] == 40 @test A[2, 1] isa Int @test A[2, 1] == 38 @test A[1, 2] isa Int @test A[1, 2] == 37 @test A[2, 2] isa Int @test A[2, 2] == 35 A = InteractionMatrix{Int}(Int[42, 40], Int[2, 5], /) @test_throws TypeError A[1] @test_throws TypeError A[2] @test_throws TypeError A[3] @test_throws TypeError A[4] @test_throws TypeError A[1, 1] @test_throws TypeError A[2, 1] @test_throws TypeError A[1, 2] @test_throws TypeError A[2, 2] A = InteractionMatrix{Float64}(Int[42, 40], Int[2, 5], /) @test A[1] isa Float64 @test A[1] == 21.0 @test A[2] isa Float64 @test A[2] == 20.0 @test A[3] isa Float64 @test A[3] == 8.4 @test A[4] isa Float64 @test A[4] == 8.0 @test A[1, 1] isa Float64 @test A[1, 1] == 21.0 @test A[2, 1] isa Float64 @test A[2, 1] == 20.0 @test A[1, 2] isa Float64 @test A[1, 2] == 8.4 @test A[2, 2] isa Float64 @test A[2, 2] == 8.0 end end
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
8802
@testitem "RowProjectionVector" begin @testset "invalid row bounds" begin v = [1, 2, 3] @test_throws BoundsError RowProjectionVector(v, 0) @test_throws BoundsError RowProjectionVector(v, 4) end @testset "empty projection" begin v = [1, 2, 3] u = RowProjectionVector(v, Int[]) @test u isa RowProjectionVector{Int} @test size(u) == (0,) @test length(u) == 0 @test_throws BoundsError u[] @test_throws BoundsError u[] = 41 @test_throws BoundsError u[0] @test_throws BoundsError u[0] = 41 @test_throws BoundsError u[1] @test_throws BoundsError u[1] = 41 @test_throws BoundsError u[2] @test_throws BoundsError u[2] = 41 u = RowProjectionVector(v) @test u isa RowProjectionVector{Int} @test size(u) == (0,) @test length(u) == 0 @test_throws BoundsError u[] @test_throws BoundsError u[] = 41 @test_throws BoundsError u[0] @test_throws BoundsError u[0] = 41 @test_throws BoundsError u[1] @test_throws BoundsError u[1] = 41 @test_throws BoundsError u[2] @test_throws BoundsError u[2] = 41 end @testset "single row" begin v = [1, 2, 3] for row ∈ eachindex(v) u = RowProjectionVector(v, row) @test u isa RowProjectionVector{Int} @test size(u) == (1,) @test length(u) == 1 @test_throws BoundsError u[0] @test_throws BoundsError u[0] = 41 @test u[] == v[row] @test u[1] == v[row] u[] = 10 + row @test u[] == 10 + row u[1] = 100 + row @test u[1] == 100 + row @test_throws BoundsError u[length(u) + 1] @test_throws BoundsError u[length(u) + 1] = 41 end end @testset "row subset" begin v = [1, 2, 3] u = RowProjectionVector(v, 3, 1) @test u isa RowProjectionVector{Int} @test size(u) == (2,) @test length(u) == 2 @test_throws BoundsError u[0] @test_throws BoundsError u[0] = 41 @test u[1] == v[3] u[1] = 11 @test u[1] == v[3] == 11 @test u[2] == v[1] u[2] = 12 @test u[2] == v[1] == 12 @test_throws BoundsError u[length(u) + 1] @test_throws BoundsError u[length(u) + 1] = 41 end @testset "row bag" begin v = [1, 2, 3] u = RowProjectionVector(v, 2, 2) @test u isa RowProjectionVector{Int} @test size(u) == (2,) @test length(u) == 2 @test_throws BoundsError u[0] @test_throws BoundsError u[0] = 41 @test u[1] == u[2] == v[2] u[1] = 11 @test u[1] == u[2] == v[2] == 11 u[2] = 12 @test u[1] == u[2] == v[2] == 12 @test_throws BoundsError u[length(u) + 1] @test_throws BoundsError u[length(u) + 1] = 41 end @testset "full projection" begin v = [1, 2, 3] u = RowProjectionVector(v, 1, 2, 3) @test u isa RowProjectionVector{Int} @test size(u) == size(v) @test length(u) == length(v) @test_throws BoundsError u[0] @test_throws BoundsError u[0] = 41 @test u == v for row in eachindex(v) u[row] = 10 + row @test u[row] == 10 + row @test v[row] == 10 + row end @test u == v @test_throws BoundsError u[length(u) + 1] @test_throws BoundsError u[length(u) + 1] = 41 end end @testitem "RowProjectionMatrix" begin @testset "invalid row bounds" begin M = [1 2 3; 4 5 6; 7 8 9] @test_throws BoundsError RowProjectionMatrix(M, 0) @test_throws BoundsError RowProjectionMatrix(M, 0, 1) @test_throws BoundsError RowProjectionMatrix(M, 1, 0) @test_throws BoundsError RowProjectionMatrix(M, 4) @test_throws BoundsError RowProjectionMatrix(M, 1, 4) @test_throws BoundsError RowProjectionMatrix(M, 4, 1) end @testset "empty projection" begin M = [1 2 3; 4 5 6; 7 8 9] A = RowProjectionMatrix(M, Int[]) @test A isa RowProjectionMatrix{Int} @test size(A) == (0, size(M, 2)) @test length(A) == 0 @test_throws BoundsError A[] @test_throws BoundsError A[] = 41 @test_throws BoundsError A[0] @test_throws BoundsError A[0] = 41 @test_throws BoundsError A[1] @test_throws BoundsError A[1] = 41 @test_throws BoundsError A[1, 1] @test_throws BoundsError A[1, 1] = 41 @test_throws BoundsError A[2] @test_throws BoundsError A[2] = 41 A = RowProjectionMatrix(M) @test A isa RowProjectionMatrix{Int} @test size(A) == (0, size(M, 2)) @test length(A) == 0 @test_throws BoundsError A[] @test_throws BoundsError A[] = 41 @test_throws BoundsError A[0] @test_throws BoundsError A[0] = 41 @test_throws BoundsError A[1] @test_throws BoundsError A[1] = 41 @test_throws BoundsError A[1, 1] @test_throws BoundsError A[1, 1] = 41 @test_throws BoundsError A[2] @test_throws BoundsError A[2] = 41 end @testset "single row" begin M = [1 2 3; 4 5 6; 7 8 9] for row ∈ axes(M, 1) A = RowProjectionMatrix(M, row) @test A isa RowProjectionMatrix{Int} @test size(A) == (1, size(M, 2)) @test length(A) == size(M, 1) @test_throws BoundsError A[] @test_throws BoundsError A[] = 41 @test_throws BoundsError A[0] @test_throws BoundsError A[0] = 41 for col ∈ axes(M, 2) @test A[col] == M[row, col] @test A[1, col] == M[row, col] A[col] = row + col @test A[col] == row + col @test A[1, col] == row + col @test M[row, col] == row + col A[1, col] = 10 + row + col @test A[col] == 10 + row + col @test A[1, col] == 10 + row + col @test M[row, col] == 10 + row + col M[row, col] = 100 + row + col @test A[col] == 100 + row + col @test A[1, col] == 100 + row + col end @test_throws BoundsError A[length(A) + 1] @test_throws BoundsError A[length(A) + 1] = 41 end end @testset "row subset" begin M = [1 2 3; 4 5 6; 7 8 9] A = RowProjectionMatrix(M, 3, 1) @test A isa RowProjectionMatrix{Int} @test size(A) == (2, size(M, 2)) @test length(A) == 2 * size(M, 2) @test_throws BoundsError A[] @test_throws BoundsError A[] = 41 @test_throws BoundsError A[0] @test_throws BoundsError A[0] = 41 @test A[1, :] == M[3, :] A[1, :] .= [11, 12, 13] @test A[1, :] == M[3, :] == [11, 12, 13] @test A[2, :] == M[1, :] A[2, :] .= [21, 22, 23] @test A[2, :] == M[1, :] == [21, 22, 23] @test_throws BoundsError A[length(A) + 1] @test_throws BoundsError A[length(A) + 1] = 41 end @testset "row bag" begin M = [1 2 3; 4 5 6; 7 8 9] A = RowProjectionMatrix(M, 2, 2) @test A isa RowProjectionMatrix{Int} @test size(A) == (2, size(M, 2)) @test length(A) == 2 * size(M, 2) @test_throws BoundsError A[] @test_throws BoundsError A[] = 41 @test_throws BoundsError A[0] @test_throws BoundsError A[0] = 41 @test A[1, :] == A[2, :] == M[2, :] A[1, :] .= [11, 12, 13] @test A[1, :] == A[2, :] == M[2, :] == [11, 12, 13] A[2, :] .= [21, 22, 23] @test A[1, :] == A[2, :] == M[2, :] == [21, 22, 23] @test_throws BoundsError A[length(A) + 1] @test_throws BoundsError A[length(A) + 1] = 41 end @testset "full projection" begin M = [1 2 3; 4 5 6; 7 8 9] A = RowProjectionMatrix(M, 1, 2, 3) @test A isa RowProjectionMatrix{Int} @test size(A) == size(M) @test length(A) == length(M) @test_throws BoundsError A[] @test_throws BoundsError A[] = 41 @test_throws BoundsError A[0] @test_throws BoundsError A[0] = 41 @test A == M for row ∈ axes(M, 1) for col ∈ axes(M, 2) @test A[row, col] == M[row, col] A[row, col] = 10 + row + col @test A[row, col] == 10 + row + col @test M[row, col] == 10 + row + col end end @test_throws BoundsError A[length(A) + 1] @test_throws BoundsError A[length(A) + 1] = 41 end end
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
code
54
using TestItemRunner @run_package_tests verbose=true
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
docs
1766
# Implicit arrays for Julia [![](https://img.shields.io/github/actions/workflow/status/tkemmer/ImplicitArrays.jl/CI.yml?branch=master&style=for-the-badge)](https://github.com/tkemmer/ImplicitArrays.jl/actions/workflows/CI.yml) [![](https://img.shields.io/github/license/tkemmer/ImplicitArrays.jl?style=for-the-badge)](https://github.com/tkemmer/ImplicitArrays.jl/blob/master/LICENSE) [![](https://img.shields.io/badge/docs-stable-blue.svg?style=for-the-badge)](https://tkemmer.github.io/ImplicitArrays.jl/stable) [![](https://img.shields.io/badge/docs-dev-blue.svg?style=for-the-badge)](https://tkemmer.github.io/ImplicitArrays.jl/dev) The `ImplicitArrays.jl` package provides multiple implicit array types for the [Julia](https://julialang.org) programming language. ## Implicit array types A full list of implicit array types provided by this package (along with code examples) is available in the [documentation](https://tkemmer.github.io/ImplicitArrays.jl/dev). ## Installation This package version requires Julia 1.6 or above. In the Julia shell, switch to the `Pkg` shell by pressing `]` and enter the following command: ```sh pkg> add ImplicitArrays ``` ## Testing `ImplicitArrays.jl` provides tests for most of its functions. You can run the test suite with the following command in the `Pkg` shell: ```sh pkg> test ImplicitArrays ``` ## Citing If you use `ImplicitArrays.jl` in your research, please cite the following publication: > Kemmer, T (2021). Space-efficient and exact system representations for the nonlocal protein > electrostatics problem. Ph. D. thesis, Johannes Gutenberg University Mainz. Mainz, Germany. Citation items for BibTeX can be found in [CITATION.bib](https://github.com/tkemmer/ImplicitArrays.jl/blob/master/CITATION.bib).
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
0.2.3
a9e896d663c5a02d019fd95ac786bf14920175b5
docs
1842
```@meta CurrentModule = ImplicitArrays ``` # ImplicitArrays.jl The `ImplicitArrays.jl` package provides multiple implicit array types for the [Julia](https://julialang.org) programming language. In many situations, the implicit array types can be used as drop-in replacements for regular Julia arrays, while carrying a smaller memory footprints as their explicit counterparts. ## Block matrices This section presents a [block matrix](https://en.wikipedia.org/wiki/Block_matrix) type for equally-sized blocks (sharing a common element type). The `BlockMatrix` type can be used to encapsulate and mix different matrix blocks, e.g., regular matrices and implicit matrices at the same time. ```@docs BlockMatrix ``` ## Fixed-value arrays Fixed-value arrays "replicate" a single value across arbitrary array dimensions. The resulting arrays have a constant memory footprint (i.e., the represented value and the array dimensions) and can only be read from. ```@docs FixedValueArray ``` ## Interaction matrices An interaction matrix `M` of size `n × m` consist of a list of `n` elements `rᵢ ∈ R` (*row elements*), a list of `m` elements `cⱼ ∈ C` (*column elements*), and a *interaction function* `f: R × C → T`, such that each element `Mᵢⱼ` of the matrix can be computed as `f(rᵢ, cⱼ)`. ### Interaction functions ```@docs InteractionFunction ConstInteractionFunction GenericInteractionFunction ``` ### Interaction matrices ```@docs InteractionMatrix ``` ## Row-projection arrays Row-projection arrays represent views on existing vectors or matrices, where the projections are created from a sequence of valid row indices corresponding to the vector or matrix. Row indices can occur multiple times and at arbitrary positions in the sequence. ```@docs RowProjectionVector RowProjectionMatrix ```
ImplicitArrays
https://github.com/tkemmer/ImplicitArrays.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
1111
cd(@__DIR__) using TimeseriesSurrogates, StatsAPI pages = [ "Documentation" => "index.md", "man/whatisasurrogate.md", "Example applications" => [ "Shuffle-based" => "methods/randomshuffle.md", "Fourier-based" => "methods/fourier_surrogates.md", "Wavelet-based" => "methods/wls.md", "Pseudo-periodic" => "methods/pps.md", "Pseudo-periodic twin" => "methods/ppts.md", "Multidimensional surrogates" => "methods/multidim.md", "Surrogates for irregular timeseries" => "collections/irregular_surrogates.md", "Surrogates for nonstationary timeseries" => "collections/nonstationary_surrogates.md" ], "man/exampleprocesses.md", "contributor_guide.md" ] import Downloads Downloads.download( "https://raw.githubusercontent.com/JuliaDynamics/doctheme/master/build_docs_with_style.jl", joinpath(@__DIR__, "build_docs_with_style.jl") ) include("build_docs_with_style.jl") build_docs_with_style(pages, TimeseriesSurrogates, StatsAPI; expandfirst = ["index.md"], authors = "Kristian Agasøster Haaga, George Datseris", )
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
492
module TimeseriesSurrogatesUncertainData using TimeseriesSurrogates import UncertainData: UncertainDataset, UncertainIndexDataset, UncertainValueDataset, resample TimeseriesSurrogates.surrogate(x::UncertainDataset, method::Surrogate) = surrogate(resample(x), method) TimeseriesSurrogates.surrogate(x::UncertainValueDataset, method::Surrogate) = surrogate(resample(x), method) TimeseriesSurrogates.surrogate(x::UncertainIndexDataset, method::Surrogate) = surrogate(resample(x), method) end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
1390
module TimeseriesSurrogatesVisualizations using TimeseriesSurrogates, Makie function TimeseriesSurrogates.surroplot!(fig, x, a; cx="#191E44", cs=("#7143E0", 0.9), nbins=50, kwargs... ) t = 1:length(x) # make surrogate timeseries (allow possibility for `a` to be a timeseries or method) s = a isa Surrogate ? surrogate(x, a) : a # Time series ax1, _ = Makie.lines(fig[1, 1], t, x; color=cx, linewidth=2) Makie.lines!(ax1, t, s; color=cs, linewidth=2) # Binned multitaper periodograms p, psurr = TimeseriesSurrogates.DSP.mt_pgram(x), TimeseriesSurrogates.DSP.mt_pgram(s) ax3 = Makie.Axis(fig[2, 1]; yscale=log10) Makie.lines!(ax3, p.freq, p.power; color=cx, linewidth=3) Makie.lines!(ax3, psurr.freq, psurr.power; color=cs, linewidth=3) # Histograms ax4 = Makie.Axis(fig[3, 1]) Makie.hist!(ax4, x; label="original", bins=nbins, color=cx) Makie.hist!(ax4, s; label="surrogate", bins=nbins, color=cs) Makie.axislegend(ax4) ax1.xlabel = "time step" ax1.ylabel = "value" ax3.xlabel = "frequency" ax3.ylabel = "power" ax4.xlabel = "binned value" ax4.ylabel = "histogram" return fig end function TimeseriesSurrogates.surroplot(x, s; cx="#191E44", cs=("#7143E0", 0.9), nbins=50, kwargs...) fig = Makie.Figure(size=(500, 500), kwargs...) surroplot!(fig, x, s; cx, cs, nbins) end end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
2701
# Activate the current directory and load packages. using Pkg; Pkg.activate(@__DIR__) Pkg.instantiate() using DelimitedFiles, TimeseriesSurrogates, BenchmarkTools, Plots, Distributions, DynamicalSystems, Random, StatsPlots; # Use GR backend for plotting. gr() x = readdlm("$(@__DIR__)/timeseries.csv")[:, 1] # Reproducibility (note: this is not possible using Lancaster et al.'s MATLAB code.) rng = Random.MersenneTwister(1234); # Pre-initialize all different surrogate types # ------------------------------------------ # Shuffle based surrogates rs = surrogenerator(x, RandomShuffle(), rng) rp = surrogenerator(x, RandomFourier(true), rng) aaft = surrogenerator(x, AAFT(), rng) iaaft = surrogenerator(x, IAAFT(), rng) # Pseudoperiodic surrogates (PPS). Here, as in "timings.m", we use a subset of 500 time # series points. x_pps = x[1:1000] τ = estimate_delay(x_pps, "ac_min") d = findmin(delay_fnn(x_pps, τ))[2] ρ = noiseradius(x_pps, d, τ, 0.025:0.025:0.5) pps = surrogenerator(x_pps, PseudoPeriodic(d, τ, ρ, true)) # Collect surrogate generators and run once to trigger precompilation surrogens = [rs, rp, aaft, iaaft, pps]; surrogates = [s() for s in surrogens]; # Define labels for plot. methods = ["RandomShuffle()", "RandomFourier(true)", "AAFT()", "IAAFT()", "PseudoPeriodic()"]; n_methods = length(methods) function generate_surrs(surrogenerator, n) for i = 1:n surrogenerator() end end """ time_n(methods; n = 100) Compute `n` surrogates using each pre-initialized `Surrogenerator` in `methods` and compute the mean time to generate a surrogate. """ function time_n(methods; n = 100) benchmarks = zeros(length(methods)) for (i, surrogen) in enumerate(methods) benchmarks[i] = @belapsed generate_surrs($surrogen, $n) end return benchmarks ./ n end time_n(surrogens, n = 1); # Like in `timings.m`, compute average time to generate surrogate over 500 # realizations of each surrogate type timings = time_n(surrogens, n = 500); # Import the timings we generated using the `timings.m` MATLAB script. # The ordering in that file is [rp, ft, aaft, iaaft, pps]; matlab_timings = readdlm("$(@__DIR__)/matlab_timings.csv")[:, 1] # Plot the results x = repeat(methods, outer = 2) gp = repeat(["TimeseriesSurrogates.jl", "MATLAB"], inner = 5) c = repeat(["Black", "Red"], inner = 5) groupedbar( [timings matlab_timings], group = gp, c = c, xrotation = 45, ylabel = "Mean runtime (s)", yaxis = :log10, yticks = [10.0^(i) for i = -6:0.5:-1], ylims = (10^-6, 10^-1), xticks = (1:5, ["rp", "ft", "aaft", "iaaft", "pps"]), legend = :topleft, ) savefig("$(@__DIR__)/../../figs/timings.png")
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
1216
module TimeseriesSurrogates # Use the README as the module docs @doc let path = joinpath(dirname(@__DIR__), "README.md") include_dependency(path) read(path, String) end TimeseriesSurrogates using Random using Distributions using Distances # Will be used by the LombScargle method using AbstractFFTs using DSP using Interpolations using Wavelets using StateSpaceSets export standardize include("core/api.jl") include("core/surrogate_test.jl") include("utils/testsystems.jl") include("plotting/surrogate_plot.jl") # The different surrogate routines include("methods/randomshuffle.jl") include("methods/large_shuffle.jl") include("methods/randomfourier.jl") include("methods/aaft.jl") include("methods/iaaft.jl") include("methods/truncated_fourier.jl") include("methods/partial_randomization.jl") include("methods/relative_partial_randomization.jl") include("methods/spectral_partial_randomization.jl") include("methods/wavelet_based.jl") include("methods/pseudoperiodic.jl") include("methods/pseudoperiodic_twin.jl") include("methods/multidimensional.jl") include("methods/ar.jl") include("methods/trend_based.jl") # Methods for irregular time series include("methods/lombscargle.jl") end # module
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
2390
export surrogate, surrogenerator, Surrogate """Supertype of all surrogate methods.""" abstract type Surrogate end struct SurrogateGenerator{S<:Surrogate, X, Y, A, R<:AbstractRNG} method::S # method with its input parameters x::X # input timeseries s::Y # surrogate (usually same type as `x`, but not always) init::A # pre-initialized things that speed up process rng::R # random number generator object end """ surrogenerator(x, method::Surrogate [, rng]) → sgen::SurrogateGenerator Initialize a generator that creates surrogates of `x` on demand, based on the given `method`. This is more efficient than [`surrogate`](@ref), because for most methods some things can be initialized and reused for every surrogate. Optionally you can provide an `rng::AbstractRNG` object that will control the random number generation and hence establish reproducibility of the generated surrogates. By default `Random.default_rng()` is used. The generated surrogates overwrite, in-place, a common vector container. Use `copy` if you need to actually store multiple surrogates. To generate a surrogate, call `sgen` as a function with no arguments, e.g.: ```julia sgen = surrogenerator(x, method) s = sgen() ``` You can use the generator syntax of Julia to map over surrogates generated by `sg`. For example, let `q` be a function returning a discriminatory statistic. To test some null hypothesis with TimeseriesSurrogates.jl you'd do ```julia using TimeseriesSurrogates q, x # inputs method = RandomFourier() # some example method sgen = surrogenerator(x, method) siter = (sgen() for _ in 1:1000) qx = q(x) qs = map(q, siter) # compare `qx` with quantiles using Statistics: quantile q01, q99 = quantile(qs, [0.01, 0.99]) q01 ≤ qx ≤ q99 # if false, hypothesis can be rejected! ``` """ function surrogenerator end function Base.show(io::IO, sg::SurrogateGenerator) println(io, "Surrogate generator for input timeseries $(summary(sg.x)) with method:") show(io, sg.method) end """ surrogate(x, method::Surrogate [, rng]) → s Create a single surrogate timeseries `s` from `x` based on the given `method`. If you want to generate multiple surrogates from `x`, you should use [`surrogenerator`](@ref) for better performance. """ function surrogate(x, method::Surrogate, rng = Random.default_rng()) sg = surrogenerator(x, method, rng) sg() end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
4437
using Random: AbstractRNG import StatsAPI: HypothesisTest, pvalue export SurrogateTest, pvalue, fill_surrogate_test! using Base.Threads """ SurrogateTest(f::Function, x, method::Surrogate; kwargs...) → test Initialize a surrogate test for input data `x`, which can be used in [`pvalue`](@ref). The tests requires as input a function `f` that given a timeseries (like `x`) it outputs a real number, and a method of how to generate surrogates. `f` is the function that computes the discriminatory statistic. Once called with [`pvalue`](@ref), the `test` estimates and then stores the real value `rval` and surrogate values `vals` of the discriminatory statistic in the fields `rval, vals` respectively. Alternatively, you can use [`fill_surrogate_test!`](@ref) directly if you don't care about the p-value. `SurrogateTest` automates the process described in the documentation page [Performing surrogate hypothesis tests](@ref). `SurrogateTest` subtypes `HypothesisTest` and is part of the StatsAPI.jl interface. ## Keywords - `rng = Random.default_rng()`: a random number generator. - `n::Int = 10_000`: how many surrogates to generate and compute `f` on. - `threaded = true`: Whether to parallelize looping over surrogate computations in to the available threads (`Threads.nthreads()`). """ struct SurrogateTest{F<:Function, S<:SurrogateGenerator, X<:Real} <: HypothesisTest f::F sgens::Vector{S} # fields that are filled whenever a function is called # for pretty printing or for keeping track of results rval::X vals::Vector{X} threaded::Bool end function SurrogateTest(f::F, x, s::Surrogate; rng = Random.default_rng(), n = 10_000, threaded = true ) where {F<:Function} if threaded seeds = rand(rng, 1:typemax(Int), Threads.nthreads()) sgens = [surrogenerator(x, s, Random.Xoshiro(seed)) for seed in seeds] else sgens = [surrogenerator(x, s, rng)] end rval = f(x) X = typeof(rval) vals = zeros(X, n) return SurrogateTest{F, typeof(first(sgens)), X}(f, sgens, rval, vals, threaded) end # Pretty printing function Base.show(io::IO, ::MIME"text/plain", test::SurrogateTest) descriptors = [ "discr. statistic" => nameof(test.f), "surrogate method" => nameof(typeof(first(test.sgens).method)), "input timeseries" => summary(test.sgens[1].x), "# of surrogates" => length(test.vals), ] padlen = maximum(length(d[1]) for d in descriptors) + 3 print(io, "SurrogateTest") for (desc, val) in descriptors print(io, '\n', rpad(" $(desc): ", padlen), val) end return end """ fill_surrogate_test!(test::SurrgateTest) → rval, vals Perform the computations foreseen by `test` and return the value of the discriminatory statistic for the real data `rval` and the distribution of values for the surrogates `vals`. This function is called by `pvalue`. """ function fill_surrogate_test!(test::SurrogateTest) if test.threaded @inbounds Threads.@threads for i in eachindex(test.vals) sgen = test.sgens[Threads.threadid()] test.vals[i] = test.f(sgen()) end else sgen = first(sgens) @inbounds for i in eachindex(test.vals) test.vals[i] = test.f(sgen()) end end return test.rval, test.vals end """ pvalue(test::SurrogateTest; tail = :left) Return the [p-value](https://en.wikipedia.org/wiki/P-value) corresponding to the given [`SurrogateTest`](@ref), optionally specifying what kind of tail test to do (one of `:left, :right, :both`). For [`SurrogateTest`](@ref), the p-value is simply the proportion of surrogate statistics that exceed (for `tail = :right`) or subseed (`tail = :left`) the discriminatory statistic computed from the input data. The default value of `tail` assumes that the surrogate data are expected to have higher discriminatory statistic values. This is the case for statistics that quantify entropy. For statistics that quantify autocorrelation, use `tail = :right` instead. """ function pvalue(test::SurrogateTest; tail = :left) rval, vals = fill_surrogate_test!(test) if tail == :right p = count(v -> v ≥ rval, vals) elseif tail == :left p = count(v -> v ≤ rval, vals) else pr = count(v -> v ≥ rval, vals) pl = count(v -> v ≤ rval, vals) p = 2min(pr, pl) end return p/length(vals) end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
1700
export AAFT """ AAFT() An amplitude-adjusted-fourier-transform (AAFT) surrogate[^Theiler1991]. AAFT surrogates have the same linear correlation, or periodogram, and also preserves the amplitude distribution of the original data. AAFT surrogates can be used to test the null hypothesis that the data come from a monotonic nonlinear transformation of a linear Gaussian process (also called integrated white noise)[^Theiler1991]. [^Theiler1991]: J. Theiler, S. Eubank, A. Longtin, B. Galdrikian, J. Farmer, Testing for nonlinearity in time series: The method of surrogate data, Physica D 58 (1–4) (1992) 77–94. """ struct AAFT <: Surrogate end function surrogenerator(x, method::AAFT, rng = Random.default_rng()) n = length(x) m = mean(x) forward = plan_rfft(x) inverse = plan_irfft(forward * x, n) 𝓕 = forward * (x .- m) init = ( x_sorted = sort(x), ix = zeros(Int, n), inverse = inverse, m = m, 𝓕 = 𝓕, r = abs.(𝓕), ϕ = angle.(𝓕), shuffled𝓕 = similar(𝓕), coeffs = zero(𝓕), n = n, ) return SurrogateGenerator(method, x, similar(x), init, rng) end function (sg::SurrogateGenerator{<:AAFT})() s, rng = sg.s, sg.rng init_fields = (:x_sorted, :ix, :inverse, :m, :r, :ϕ, :shuffled𝓕, :coeffs, :n) x_sorted, ix, inverse, m, r, ϕ, shuffled𝓕, coeffs, n = getfield.(Ref(sg.init), init_fields) coeffs .= rand(rng, Uniform(0, 2π), length(shuffled𝓕)) shuffled𝓕 .= r .* exp.(coeffs .* 1im) s .= (inverse * shuffled𝓕) .+ m # Rescale back to original values to obtain AAFT surrogate. sortperm!(ix, s) s[ix] .= x_sorted return s end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
1861
using DSP, Random export AutoRegressive """ AutoRegressive(n, method = LPCLevinson()) Autoregressive surrogates of order-`n`. The autoregressive coefficients `φ` are estimated using `DSP.lpc(x, n, method)`, and thus see the documentation of DSP.jl for possible `method`s. While these surrogates are obviously suited to test the null hypothesis whether the data are coming from a autoregressive process, the Fourier Transform-based surrogates are probably a better option. The current method is more like an explicit way to produce surrogates for the same hypothesis by fitting a model. It can be used as a convenient way to estimate autoregressive coefficients and automatically generate surrogates based on them. The coefficients φ of the autoregressive fit can be found by doing ```julia sg = surrogenerator(x, AutoRegressive(n)) φ = sg.init.φ ``` """ struct AutoRegressive{M} <: Surrogate n::Int m::M end AutoRegressive(n::Int) = AutoRegressive(n, LPCLevinson()) function surrogenerator(x, method::AutoRegressive, rng = Random.default_rng()) φ, e = lpc(x, method.n, method.m) N, f = length(x), length(φ) d = Normal(0, std(x)) init = ( d = d, φ = φ, N = N, ) # The surrogate T = typeof(d).parameters[1] s = zeros(T, N + f) return SurrogateGenerator(method, x, s, init, rng) end function (sg::SurrogateGenerator{<:AutoRegressive})() N, φ, d = sg.init.N, sg.init.φ, sg.init.d return autoregressive!(sg.s, d, N, φ, sg.rng) end function autoregressive!(s, d::Normal{T}, N, φ, rng) where {T} f = length(φ) @inbounds for i in 1:f; s[i] = rand(rng, d); end @inbounds for i in f+1:length(s) s̃ = zero(T) for j in 1:f s̃ += φ[j] * s[i - j] end s̃ += rand(rng, d) s[i] = s̃ end return view(s, f+1:N+f) end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
4271
export IAAFT include("../utils/powerspectrum.jl") include("../utils/interpolation.jl") export IAAFT """ IAAFT(M = 100, tol = 1e-6, W = 75) An iteratively adjusted amplitude-adjusted-fourier-transform surrogate[^SchreiberSchmitz1996]. IAAFT surrogates have the same linear correlation, or periodogram, and also preserves the amplitude distribution of the original data, but are improved relative to AAFT through iterative adjustment (which runs for a maximum of `M` steps). During the iterative adjustment, the periodograms of the original signal and the surrogate are coarse-grained and the powers are averaged over `W` equal-width frequency bins. The iteration procedure ends when the relative deviation between the periodograms is less than `tol` (or when `M` is reached). IAAFT, just as AAFT, can be used to test the null hypothesis that the data come from a monotonic nonlinear transformation of a linear Gaussian process. [^SchreiberSchmitz1996]: T. Schreiber; A. Schmitz (1996). "Improved Surrogate Data for Nonlinearity Tests". [Phys. Rev. Lett. 77 (4)](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.77.635) """ struct IAAFT <: Surrogate M::Int tol::Real W::Int function IAAFT(;M::Int = 100, tol::Real = 1e-6, W::Int = 75) new(M, tol, W) end end Base.show(io::IO, x::IAAFT) = print(io, "IAAFT(M = $(x.M), tol = $(x.tol), W = $(x.W))") function interpolated_spectrum(spectrum, n) intp_spectrum = zeros(n) interpolated_spectrum!(intp_spectrum, spectrum, n) end function interpolated_spectrum!(intp_spectrum, spectrum, n) t = 1:length(spectrum) r = getrange(t, n) iₓ = itp(spectrum) intp_spectrum .= iₓ.(r) return intp_spectrum end function surrogenerator(x, method::IAAFT, rng = Random.default_rng()) m = mean(x) x_sorted = sort(x) forward = plan_rfft(x) inverse = plan_irfft(forward * x, length(x)) 𝓕 = forward * x r = abs.(𝓕) ϕ = abs.(𝓕) ix = zeros(Int, length(x)) # Periodograms 𝓕p = prepare_spectrum(x, forward) xpower = similar(𝓕) .|> real; powerspectrum!(𝓕p, xpower, x, forward) spower = copy(xpower) # Binned periodograms xpowerᵦ = interpolated_spectrum(xpower, method.W) spowerᵦ = interpolated_spectrum(spower, method.W) init = ( forward = forward, inverse = inverse, 𝓕 = 𝓕, 𝓕p = 𝓕p, r = r, ϕ = ϕ, m = m, x_sorted = x_sorted, xpower = xpower, spower = spower, xpowerᵦ = xpowerᵦ, spowerᵦ = spowerᵦ, ix = ix, ) return SurrogateGenerator(method, x, similar(x), init, rng) end using LinearAlgebra function (sg::SurrogateGenerator{<:IAAFT})() init_fields = (:forward, :inverse, :𝓕, :𝓕p, :r, :ϕ, :m, :x_sorted, :xpower, :spower, :xpowerᵦ, :spowerᵦ, :ix) forward, inverse, 𝓕, 𝓕p, r, ϕ, m, x_sorted, xpower, spower, xpowerᵦ, spowerᵦ, ix = getfield.(Ref(sg.init), init_fields) x, s, rng = sg.x, sg.s, sg.rng M, W = sg.method.M, sg.method.W tol = sg.method.tol # Surrogate starts out as a random permutation of `x` n = length(x) s .= x[sample(rng, 1:n, n)] sum_old, sum_new = 0.0, 0.0 iter = 1 while iter <= M mul!(𝓕, forward, s) ϕ .= angle.(𝓕) 𝓕 .= r .* exp.(ϕ .* 1im) # TODO: Unfortunately, we can't simply do ldiv! here to avoid allocations. # But, although FFTW does not yet have irfft!, it will probably have. # See https://github.com/JuliaMath/FFTW.jl/pull/222. # Once that PR is merged, we should replace the following line with # the in-place version. ###################################################################### s .= inverse * 𝓕 sortperm!(ix, s) s[ix] .= x_sorted powerspectrum!(𝓕p, spower, s, forward) interpolated_spectrum!(spowerᵦ, spower, W) if iter == 1 sum_old = sum((xpowerᵦ .- xpowerᵦ) .^ 2) / sum(xpowerᵦ .^ 2) else sum_new = sum((xpowerᵦ .- spowerᵦ) .^ 2) / sum(xpowerᵦ .^ 2) if abs(sum_old - sum_new) < tol iter = M + 1 else sum_old = sum_new end end iter += 1 end return s end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
7265
export BlockShuffle, CycleShuffle, CircShift ######################################################################### # BlockSuffle ######################################################################### function get_uniform_blocklengths(L::Int, n::Int) # Compute block lengths N = floor(Int, L/n) R = L % n blocklengths = [N for i = 1:n] for i = 1:R blocklengths[i] += 1 end return blocklengths end """ BlockShuffle(n::Int; shift = false) A block shuffle surrogate constructed by dividing the time series into `n` blocks of roughly equal width at random indices (end blocks are wrapped around to the start of the time series). If `shift` is `true`, then the input signal is circularly shifted by a random number of steps prior to picking blocks. Block shuffle surrogates roughly preserve short-range temporal properties in the time series (e.g. correlations at lags less than the block length), but break any long-term dynamical information (e.g. correlations beyond the block length). Hence, these surrogates can be used to test any null hypothesis aimed at comparing short-range dynamical properties versus long-range dynamical properties of the signal. """ struct BlockShuffle{I <: Integer, B <: Bool} <: Surrogate n::I shift::B function BlockShuffle(n::I; shift::B = false) where {I <: Integer, B <: Bool} return new{I, B}(n, shift) end # Split time series into 10 pieces by default. Shifting disabled by default. function BlockShuffle() return new{Int, Bool}(10, false) end end function surrogenerator(x::AbstractVector, bs::BlockShuffle, rng = Random.default_rng()) bs.n < length(x) || error("The number of blocks exceeds number of available points") # The lengths of the blocks (one block will have a differing length if length of # time series in not a multiple of the number of blocks, so ) blocklengths = get_uniform_blocklengths(length(x), bs.n) # The start index of each block. startinds = vcat(1, cumsum(blocklengths) .+ 1) # The data from which we will sample. This array may be circularly shifted. x_rotated = copy(x) # The order in which we will draw the blocks. Will be shuffled every time # a new surrogate is generated. draw_order = collect(1:bs.n) init = ( blocklengths = blocklengths, startinds = startinds, x_rotated = x_rotated, draw_order = draw_order, ) # The surrogate. s = similar(x) return SurrogateGenerator(bs, x, s, init, rng) end function (sg::SurrogateGenerator{<:BlockShuffle})() init_fields = (:blocklengths, :startinds, :x_rotated, :draw_order) blocklengths, startinds, x_rotated, draw_order = getfield.(Ref(sg.init), init_fields) x, s, n = sg.x, sg.s, sg.method.n # Circular shift, if desired if sg.method.shift circshift!(x_rotated, x, rand(sg.rng, 1:length(x))) end # Shuffle blocks shuffle!(sg.rng, draw_order) k = 1 npts_sampled = 0 for i in draw_order # The index of the data point which this block starts (in `x_rotated`) sᵢ = startinds[i] # The length of this block. l = blocklengths[i] # Indices of the block which is sampled. ix_from = sᵢ:(sᵢ + l - 1) # Indices in `s` into which this block will be placed. ix_into = (npts_sampled + 1):(npts_sampled + 1 + l - 1) # Do the assignment in-place behind a code barrier. This about # 3x as efficient as doing an elementwise assignment and # doesn't allocate. assign_block_to_surrogate!(s, x_rotated, ix_into, ix_from) npts_sampled += l end #@assert all(sort(s) .== sort(x_rotated)) return s end function assign_block_to_surrogate!(s, x_rotated, ix_into, ix_from) @assert length(ix_into) == length(ix_from) n = length(ix_into) @inbounds for k = 1:n ito = ix_into[k] ifr = ix_from[k] s[ito] = x_rotated[ifr] end end ######################################################################### # CycleShuffle ######################################################################### """ CycleShuffle(n::Int = 7, σ = 0.5) Cycle shuffled surrogates[^Theiler1994] that identify successive local peaks in the data and shuffle the cycles in-between the peaks. Similar to [`BlockShuffle`](@ref), but here the "blocks" are defined as follows: 1. The timeseries is smoothened via convolution with a Gaussian (`DSP.gaussian(n, σ)`). 2. Local maxima of the smoothened signal define the peaks, and thus the blocks in between them. 3. The first and last index of timeseries can never be peaks and thus signals that should have peaks very close to start or end of the timeseries may not perform well. In addition, points before the first or after the last peak are never shuffled. 3. The defined blocks are randomly shuffled as in [`BlockShuffle`](@ref). CSS are used to test the null hypothesis that the signal is generated by a periodic oscillator with no dynamical correlation between cycles, i.e. the evolution of cycles is not deterministic. See also [`PseudoPeriodic`](@ref). [^Theiler1994]: J. Theiler, On the evidence for low-dimensional chaos in an epileptic electroencephalogram, [Phys. Lett. A 196](https://doi.org/10.1016/0375-9601(94)00856-K) """ struct CycleShuffle{T <: AbstractFloat} <: Surrogate n::Int σ::T end CycleShuffle(n = 7, σ = 0.5) = CycleShuffle{typeof(σ)}(n, σ) function surrogenerator(x::AbstractVector, cs::CycleShuffle, rng = Random.default_rng()) n, N = cs.n, length(x) g = DSP.gaussian(n, cs.σ) smooth = DSP.conv(x, g) r = length(smooth) - N smooth = iseven(r) ? smooth[r÷2+1:end-r÷2] : smooth[r÷2+1:end-r÷2-1] peaks = findall(i -> smooth[i-1] < smooth[i] && smooth[i] > smooth[i+1], 2:N-1) blocks = [collect(peaks[i]:peaks[i+1]-1) for i in 1:length(peaks)-1] init = (blocks = blocks, peak1 = peaks[1]) s = copy(x) SurrogateGenerator(cs, x, s, init, rng) end function (sg::SurrogateGenerator{<:CycleShuffle})() blocks, peak1 = sg.init x = sg.x s = sg.s shuffle!(sg.rng, blocks) i = peak1 for b in blocks s[(0:length(b)-1) .+ i] .= @view x[b] i += length(b) end return s end ######################################################################### # Timeshift ######################################################################### random_shift(n::Integer, rng) = n random_shift(n::AbstractVector{<:Integer}, rng) = rand(rng, n) """ CircShift(n) Surrogates that are circularly shifted versions of the original timeseries. `n` can be an integer (the surrogate is the original time series shifted by `n` indices), or any vector of integers, which which means that each surrogate is shifted by an integer selected randomly among the entries in `n`. """ struct CircShift{N} <: Surrogate n::N end function surrogenerator(x, sd::CircShift, rng = Random.default_rng()) return SurrogateGenerator(sd, x, similar(x), nothing, rng) end function (sg::SurrogateGenerator{<:CircShift})() x, s = sg.x, sg.s shift = random_shift(sg.method.n, sg.rng) circshift!(s, x, shift) return s end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
4618
using LombScargle, Distances export IrregularLombScargle """ IrregularLombScargle(t; tol = 1, n_total = 100000, n_acc = 50000, q = 1) [`IrregularLombScargle`](@ref) surrogates for unevenly sampled time series with supporting time steps `t`, generated using the simulated annealing algorithm described in [^SchreiberSchmitz1999]. [`IrregularLombScargle`](@ref) surrogates (given enough iterations and a low enough tolerance) preserve the periodogram and the amplitude distribution of the original signal. For time series with equidistant time steps, surrogates generated by this method result in surrogates similar to those produced by the [`IAAFT`](@ref) method. This algorithm starts with a random permutation of the original data. Then it iteratively approaches the power spectrum of the original data by swapping two randomly selected values in the surrogate data if the Minkowski distance of order `q` between the power spectrum of the surrogate data and the original data is less than before. The iteration procedure ends when the relative deviation between the periodograms is less than `tol` or when `n_total` number of tries or `n_acc` number of actual swaps is reached. [^SchmitzSchreiber1999]: A.Schmitz T.Schreiber (1999). "Testing for nonlinearity in unevenly sampled time series" [Phys. Rev E](https://journaIrregularLombScargle.aps.org/pre/pdf/10.1103/PhysRevE.59.4044) """ struct IrregularLombScargle{T<:AbstractVector, S<:Real} <: Surrogate t::T tol::S n_total::Int n_acc::Int q::Int end IrregularLombScargle(t; tol = 1.0, n_total = 100000, n_acc = 50000, q = 1) = IrregularLombScargle(t, tol, n_total, n_acc, q) function surrogenerator(x, method::IrregularLombScargle, rng = Random.default_rng()) # Plan Lombscargle periodogram. Use default flags. lsplan = LombScargle.plan(method.t, x, fit_mean = false) # Compute initial periodogram. x_ls = lombscargle(lsplan) # We have to copy the power vector here, because we are reusing `lsplan` later on xpower = copy(x_ls.power) # Use Minkowski distance of order q dist = Distances.Minkowski(method.q) # When re-computing the Lomb-Scargle periodogram, we will use the # `_periodogram!` method, which re-uses the lsplan with a shuffled # time vector. This is the same as shuffling the signal, so the # surrogate starts out as a shuffled version of `t`. s = shuffle(rng, method.t) # Initialize a candidate surrogate. candidate = zero(s) init = ( lsplan = lsplan, xpower = xpower, n = length(x), dist = dist, candidate = candidate, ) return SurrogateGenerator(method, x, s, init, rng) end function (sg::SurrogateGenerator{<:IrregularLombScargle})() lsplan, xpower, n, dist, candidate = sg.init t, tol = sg.method.t, sg.method.tol x, s, rng = sg.x, sg.s, sg.rng # Power spectrum for the randomly shuffled signal. spower = LombScargle._periodogram!(lsplan.P, s, lsplan) # Compare power spectra for original (`xpower`) and randomly shuffled signal (`spower`). lossold = Distances.evaluate(dist, xpower, spower) range = 1:n i = j = 0 while i < sg.method.n_total && j < sg.method.n_acc if mod(i, 2000) == 0 @info "iterations: $i, swaps: $j, loss: $lossold" end # Initially, the new surrogate is identical to the existing surrogate. copy!(candidate, s) # Swap two random points and re-compute power spectrum for the candidate. swap_elements!(candidate, s, rng, range) # This is the bottleneck. spower = LombScargle._periodogram!(lsplan.P, candidate, lsplan) # If spectra are more similar after the swap, accept the new # surrogate. Otherwise, do a new swap. lossnew = evaluate(dist, xpower, spower) if lossnew < lossold lossnew <= tol && break s = copy(candidate) lossold = lossnew j += 1 end i += 1 end @info "Terminated simulated annealing process after $i iterations and $j swaps. Loss: $lossold" # Use the permutation of the time vector to permute the signal vector # This gives us the inverse permutation from t to perm perm = sortperm(sortperm(s)) # Check if this worked as expected @assert t[perm] == s # Re-scale back to original time series values. return x[perm] end function swap_elements!(candidate, s, rng, range) k = sample(rng, range) l = sample(rng, range) candidate[k] = s[l] candidate[l] = s[k] end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
935
using StateSpaceSets, Random export ShuffleDimensions """ ShuffleDimensions() Multidimensional surrogates of input `StateSpaceSet`s from StateSpaceSets.jl. Each point in the set is individually shuffled, but the points themselves are not shuffled. These surrogates destroy the state space structure of the dataset and are thus suited to distinguish deterministic datasets from high dimensional noise. """ struct ShuffleDimensions <: Surrogate end function surrogenerator(x, sd::ShuffleDimensions, rng = Random.default_rng()) if !(x isa AbstractStateSpaceSet) error("input `x` must be `AbstractStateSpaceSet` for `ShuffleDimensions`") end s = copy(x) return SurrogateGenerator(sd, x, s, nothing, rng) end function (sg::SurrogateGenerator{<:ShuffleDimensions})() s = sg.s for i in eachindex(s) @inbounds s[i] = shuffle(sg.rng, s[i]) end return s end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
3471
export PartialRandomization, PartialRandomizationAAFT """ PartialRandomization(α = 0.5) `PartialRandomization` surrogates[^Ortega1998] are similar to [`RandomFourier`](@ref) phase surrogates, but during the phase randomization step, instead of drawing phases from `[0, 2π]`, phases are drawn from `[0, 2π]*α`, where `α ∈ [0, 1]`. The authors refers to `α` as the "degree" of phase randomization, where `α = 0` means `0 %` randomization and `α = 1` means `100 %` randomization. See [`RelativePartialRandomization`](@ref) and [`SpectralPartialRandomization`](@ref) for alternative partial-randomization algorithms [^Ortega1998]: Ortega, Guillermo J.; Louis, Enrique (1998). Smoothness Implies Determinism in Time Series: A Measure Based Approach. Physical Review Letters, 81(20), 4345–4348. doi:10.1103/PhysRevLett.81.4345 """ struct PartialRandomization{T} <: Surrogate α::T function PartialRandomization(α::T=0.5) where T <: Real 0 <= α <= 1 || throw(ArgumentError("α must be between 0 and 1")) return new{T}(α) end end function surrogenerator(x::AbstractVector, rf::PartialRandomization, rng = Random.default_rng()) forward = plan_rfft(x) inverse = plan_irfft(forward*x, length(x)) m = mean(x) 𝓕 = forward*(x .- m) shuffled𝓕 = zero(𝓕) s = similar(x) n = length(𝓕) r = abs.(𝓕) ϕ = angle.(𝓕) coeffs = zero(r) init = (inverse = inverse, m = m, coeffs = coeffs, n = n, r = r, ϕ = ϕ, shuffled𝓕 = shuffled𝓕) return SurrogateGenerator(rf, x, s, init, rng) end function (sg::SurrogateGenerator{<:PartialRandomization})() inverse, m, coeffs, n, r, ϕ, shuffled𝓕 = getfield.(Ref(sg.init), (:inverse, :m, :coeffs, :n, :r, :ϕ, :shuffled𝓕)) s, rng = sg.s, sg.rng α = sg.method.α coeffs .= rand(rng, Uniform(0, 2π), n) shuffled𝓕 .= r .* exp.(coeffs .* 1im .* α) s .= inverse * shuffled𝓕 .+ m return s end """ PartialRandomizationAAFT(α = 0.5) `PartialRandomizationAAFF` surrogates are similar to [`PartialRandomization`](@ref) surrogates[^Ortega1998], but adds a rescaling step, so that the surrogate has the same values as the original time series (analogous to the rescaling done for [`AAFT`](@ref) surrogates). Partial randomization surrogates have, to the package authors' knowledge, not been published in scientific literature. [^Ortega1998]: Ortega, Guillermo J.; Louis, Enrique (1998). Smoothness Implies Determinism in Time Series: A Measure Based Approach. Physical Review Letters, 81(20), 4345–4348. doi:10.1103/PhysRevLett.81.4345 """ struct PartialRandomizationAAFT{T} <: Surrogate α::T function PartialRandomizationAAFT(α::T=0.5) where T <: Real 0 <= α <= 1 || throw(ArgumentError("α must be between 0 and 1")) return new{T}(α) end end function surrogenerator(x::AbstractVector, rf::PartialRandomizationAAFT, rng = Random.default_rng()) init = ( gen = surrogenerator(x, PartialRandomization(rf.α), rng), ix = zeros(Int, length(x)), x_sorted = sort(x), ) s = similar(x) return SurrogateGenerator(rf, x, s, init, rng) end function (sg::SurrogateGenerator{<:PartialRandomizationAAFT})() gen, ix, x_sorted = sg.init.gen, sg.init.ix, sg.init.x_sorted s = sg.s # Surrogate starts out as a PartialRandomization surrogate s .= gen() # Rescale to obtain a AAFT-like surrogate sortperm!(ix, s) s[ix] .= x_sorted return s end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
4508
using DelayEmbeddings, LinearAlgebra export PseudoPeriodic, noiseradius """ PseudoPeriodic(d, τ, ρ, shift = true) Create surrogates suitable for pseudo-periodic signals. They retain the periodic structure of the signal, while inter-cycle dynamics that are either deterministic or correlated noise are destroyed (for appropriate `ρ` choice). Therefore these surrogates are suitable to test the null hypothesis that the signal is a periodic orbit with uncorrelated noise[^Small2001]. Arguments `d, τ, ρ` are as in the paper, the embedding dimension, delay time and noise radius. The method works by performing a delay coordinates embedding from DelayEmbeddings.jl (see that docs for choosing appropriate `d, τ`). For `ρ`, we have implemented the method proposed in the paper in the function [`noiseradius`](@ref). The argument `shift` is not discussed in the paper. If `shift=false` we adjust the algorithm so that there is little phase shift between the periodic component of the original and surrogate data. See also [`CycleShuffle`](@ref). [^Small2001]: Small et al., Surrogate test for pseudoperiodic time series data, [Physical Review Letters, 87(18)](https://doi.org/10.1103/PhysRevLett.87.188101) """ struct PseudoPeriodic{T<:Real} <: Surrogate d::Int τ::Int ρ::T shift::Bool end PseudoPeriodic(d, t, r) = PseudoPeriodic(d, t, r, true) function surrogenerator(x::AbstractVector, pp::PseudoPeriodic, rng = Random.default_rng()) # in the following symbol `y` stands for `s` of the paper d, τ = getfield.(Ref(pp), (:d, :τ)) N = length(x) z = embed(x, d, τ) Ñ = length(z) w = zeros(eltype(z), Ñ-1) # weights vector y = StateSpaceSet([z[1] for i in 1:N]) s = similar(x) init = (y = y, w = w, z = z) return SurrogateGenerator(pp, x, s, init, rng) end function (sg::SurrogateGenerator{<:PseudoPeriodic})() y, z, w = getfield.(Ref(sg.init), (:y, :z, :w)) ρ, shift = getfield.(Ref(sg.method), (:ρ, :shift)) pseudoperiodic!(sg.s, y, sg.x, z, w, ρ, shift, sg.rng) end # Low-level method, also used in `noiseradius` function pseudoperiodic!(s, y, x, z, w, ρ, shift, rng) N, Ñ = length.((x, z)) y[1] = shift ? rand(rng, z.data) : z[1] @inbounds for i in 1:N-1 w .= (exp(-norm(z[t] - y[i])/ρ) for t in 1:Ñ-1) j = sample(rng, 1:Ñ-1, pweights(w)) y[i+1] = z[j+1] end for (i, p) in enumerate(y); s[i] = p[1]; end return s end """ noiseradius(x::AbstractVector, d::Int, τ, ρs, n = 1) → ρ Use the proposed* algorithm of[^Small2001] to estimate optimal `ρ` value for [`PseudoPeriodic`](@ref) surrogates, where `ρs` is a vector of possible `ρ` values. *The paper is ambiguous about exactly what to calculate. Here we count how many times we have pairs of length-2 that are identical in `x` and its surrogate, but **are not** also part of pairs of length-3. This function directly returns the arg-maximum of the evaluated distribution of these counts versus `ρ`, use `TimeseriesSurrogates._noiseradius` with same arguments to get the actual distribution. `n` means to repeat τhe evaluation `n` times, which increases accuracy. [^Small2001]: Small et al., Surrogate test for pseudoperiodic time series data, [Physical Review Letters, 87(18)](https://doi.org/10.1103/PhysRevLett.87.188101) """ function noiseradius(x::AbstractVector, d::Int, τ, ρs, n = 1) l2n = _noiseradius(x, d, τ, ρs, n) return ρs[argmax(l2n)] end function _noiseradius(x::AbstractVector, d::Int, τ, ρs, n = 1) l2n = noiseradius(surrogenerator(x, PseudoPeriodic(d, τ, ρs[1])), ρs, n) end function noiseradius(sg::SurrogateGenerator{<:PseudoPeriodic}, ρs, n = 1) l2n = zero(ρs) # length-2 number of points existing in both timeseries y, z, w = getfield.(Ref(sg.init), (:y, :z, :w)) x, s = sg.x, sg.s N = length(sg.x) @inbounds for _ in 1:n for (ℓ, ρ) in enumerate(ρs) s̄ = pseudoperiodic!(s, y, x, z, w, ρ, sg.method.shift, sg.rng) for i in 1:N-1 # TODO: This can be optimized heavily: checking x[i+2] already tells us # that we shouldn't check x[i+1] on the next iteration. l2n[ℓ] += count(j -> s̄[j]==x[i] && s̄[j+1]==x[i+1] && s̄[j+2]!=x[i+2], 1:N-2) end end end # TODO: here we can directly find maximum and return it as a single number return l2n end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
6455
export PseudoPeriodicTwin export embed using StatsBase: sample, pweights using Distances: Euclidean, PreMetric, pairwise using DelayEmbeddings: embed """ PseudoPeriodicTwin(d::Int, τ::Int, δ = 0.2, ρ = 0.1, metric = Euclidean()) PseudoPeriodicTwin(δ = 0.2, ρ = 0.1, metric = Euclidean()) A pseudoperiodic twin surrogate[^Miralles2015], which is a fusion of the twin surrogate[^Thiel2006] and the pseudo-periodic surrogate[^Small2001]. ## Input parameters A delay reconstruction of the input timeseries is constructed using embedding dimension `d` and embedding delay `τ`. The threshold `δ ∈ (0, 1]` determines which points are "close" (neighbors) or not, and is expressed as a fraction of the attractor diameter, as determined by the input data. The authors of the original twin surrogate paper recommend `0.05 ≤ δ ≤ 0.2`[^Thiel2006]. If you have pre-embedded your timeseries, and timeseries is already a `::StateSpaceSet`, use the three-argument constructor (so that no delay reconstruction is performed). If you want a surrogate for a scalar-valued timeseries, use the five-argument constructor to also provide the embedding delay `τ` and embedding dimension `d`. ## Null hypothesis Pseudo-periodic twin surrogates generate signals similar to the original data if the original signal is (quasi-)periodic. If the original signal is not (quasi-)periodic, then these surrogates will have different recurrence plots than the original signal, but preserve the overall shape of the attractor. Thus, `PseudoPeriodicTwin` surrogates can be used to test null hypothesis that the observed timeseries (or orbit) is consistent with a quasi-periodic orbit[^Miralles2015]. ## Returns A `d`-dimensional surrogate orbit (a `StateSpaceSet`) is returned. Sample the first column of this dataset if a scalar-valued surrogate is desired. [^Small2001]: Small et al., Surrogate test for pseudoperiodic timeseries data, [Physical Review Letters, 87(18)](https://doi.org/10.1103/PhysRevLett.87.188101) [^Thiel2006]: Thiel, Marco, et al. "Twin surrogates to test for complex synchronisation." EPL (Europhysics Letters) 75.4 (2006): 535. [^Miralles2015]: Miralles, R., et al. "Characterization of the complexity in short oscillating timeseries: An application to seismic airgun detonations." The Journal of the Acoustical Society of America 138.3 (2015): 1595-1603. """ struct PseudoPeriodicTwin{T<:Real, P<:Real, D<:PreMetric} <: Surrogate d::Union{Nothing, Int} τ::Union{Nothing, Int} δ::T ρ::P metric::D function PseudoPeriodicTwin(d::Int, τ::Int, δ::T = 0.2, ρ::P = 0.1, metric::D = Euclidean()) where {T, P, D} new{T, P, D}(d, τ, δ, ρ, metric) end function PseudoPeriodicTwin(δ::T = 0.2, ρ::P = 0.1, metric::D = Euclidean()) where {T, P, D} new{T, P, D}(nothing, nothing, δ, ρ, metric) end end """ _prepare_embed(x::AbstractVector, d, τ) → StateSpaceSet _prepare_embed(x::StateSpaceSet, d, τ) → StateSpaceSet Prepate input data for surrogate generation. If input is a vector, embed it using the provided parameters. If input as a dataset, we assume it already represents an orbit. """ function _prepare_embed end _prepare_embed(x::AbstractVector, d, τ) = embed(x, d, τ) _prepare_embed(x::StateSpaceSet, d, τ) = x function surrogenerator(x::Union{AbstractVector, StateSpaceSet}, pp::PseudoPeriodicTwin, rng = Random.default_rng()) d, τ, δ, metric = getfield.(Ref(pp), (:d, :τ, :δ, :metric)) ρ = getfield.(Ref(pp), (:ρ)) pts = _prepare_embed(x, d, τ) Nx = length(x) Npts = length(pts) dists = pairwise(metric, Matrix(pts), dims = 1) normalisedδ = δ*maximum(dists) T = eltype(pts) R = zeros(T, Npts, Npts) # Recurrence matrix for j = 1:Npts for i = 1:Npts R[i, j] = normalisedδ - dists[i, j] >= 0 ? 1.0 : 0.0 end end # Identify twins #println("R contains $(count(R .== 1)/length(R)*100)% black dots") twins_i = Vector{Int}(undef, 0) twins_j = Vector{Int}(undef, 0) for j = 1:Npts for i = 1:Npts if i !== j && all(R[:, i] .≈ R[:, j]) push!(twins_i, i) push!(twins_j, j) end end end #println("Found $(length(twins)) twins") twins = Dict{Int,Vector{Int}}() # For every point that has a twin, store the indices of all of its twins for twi in unique(twins_i) twins[twi] = twins_j[findall(twins_i .== twi)] end for twj in unique(twins_j) twins[twj] = twins_i[findall(twins_j .== twj)] end # Sampling weights (exclude the point itself) W = [pweights(exp.(-dists[setdiff(1:Npts, i), i] / ρ)) for i = 1:Npts] # The surrogate will be a vector of vectors (if pts is a StateSpaceSet, then # the eltype is SVector). PT = eltype(pts.data) s = Vector{PT}(undef, Nx) init = (pts = pts, Nx = Nx, Npts = Npts, dists = dists, R = R, twins = twins, W = W) return SurrogateGenerator(pp, x, s, init, rng) end function (sg::SurrogateGenerator{<:PseudoPeriodicTwin})() pts, Nx, Npts, twins, W = getfield.(Ref(sg.init), (:pts, :Nx, :Npts, :twins, :W)) ρ = getfield.(Ref(sg.method), (:ρ)) s = sg.s # Randomly pick a point from the state space as the starting point for the surrogate. n = 1 i = rand(sg.rng, 1:Npts) s[n] = pts[i] while n < Nx # Look for possible twins of the point xᵢ. If any twin exists, jump to one of them # with probability 1/nⱼ, where nⱼ are the number of twins for the point xᵢ. if haskey(twins, i) # sample uniformly (with probability 1/ntargettwins) over possible target twins j = twins[i][rand(sg.rng, 1:length(twins[i]))] s[n] = pts[j] i = j n += 1 end # The orbit moves on from the current point xᵢ to a randomly selected point # on the attractor. Closer points are more likely to be selected, and points # further away are less likely to be selected. The sampling probability # of the next point xⱼ decreases exponentially with increasing distance # from the current point xᵢ. Probabilities for jumping from xᵢ to any other # point have been pre-computed, and are stored in W[i]. j = sample(sg.rng, 1:Npts, W[i]) s[n] = pts[j] i = j n += 1 end s[Nx] = pts[sample(1:Npts, W[i])[1]] return StateSpaceSet(s) end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
2125
using Random using LinearAlgebra export RandomFourier, FT """ RandomFourier(phases = true) A surrogate that randomizes the Fourier components of the signal in some manner. If `phases==true`, the phases are randomized, otherwise the amplitudes are randomized. `FT` is an alias for `RandomFourier`. Random Fourier phase surrogates[^Theiler1991] preserve the autocorrelation function, or power spectrum, of the original signal. Random Fourier amplitude surrogates preserve the mean and autocorrelation function but do not preserve the variance of the original. Random amplitude surrogates are not common in the literature, but are provided for convenience. Random phase surrogates can be used to test the null hypothesis that the original signal was produced by a linear Gaussian process [^Theiler1991]. [^Theiler1991]: J. Theiler, S. Eubank, A. Longtin, B. Galdrikian, J. Farmer, Testing for nonlinearity in time series: The method of surrogate data, Physica D 58 (1–4) (1992) 77–94. """ struct RandomFourier <: Surrogate phases::Bool end RandomFourier() = RandomFourier(true) const FT = RandomFourier function surrogenerator(x::AbstractVector, rf::RandomFourier, rng = Random.default_rng()) forward = plan_rfft(x) inverse = plan_irfft(forward*x, length(x)) m = mean(x) 𝓕 = forward*(x .- m) shuffled𝓕 = zero(𝓕) s = similar(x) n = length(𝓕) r = abs.(𝓕) ϕ = angle.(𝓕) coeffs = zero(r) init = (inverse = inverse, m = m, coeffs = coeffs, n = n, r = r, ϕ = ϕ, shuffled𝓕 = shuffled𝓕) return SurrogateGenerator(rf, x, s, init, rng) end function (sg::SurrogateGenerator{<:RandomFourier})() inverse, m, coeffs, n, r, ϕ, shuffled𝓕 = getfield.(Ref(sg.init), (:inverse, :m, :coeffs, :n, :r, :ϕ, :shuffled𝓕)) s, rng, phases = sg.s, sg.rng, sg.method.phases if phases rand!(rng, Uniform(0, 2π), coeffs) shuffled𝓕 .= r .* exp.(coeffs .* 1im) else coeffs .= r .* rand(rng, Uniform(0, 2π), n) shuffled𝓕 .= coeffs .* exp.(ϕ .* 1im) end mul!(s, inverse, shuffled𝓕) s .+= m return s end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
1552
using Random export RandomShuffle """ RandomShuffle() <: Surrogate A random constrained surrogate, generated by shifting values around. Random shuffle surrogates preserve the mean, variance and amplitude distribution of the original signal. Properties not preserved are *any temporal information*, such as the power spectrum and hence linear correlations. The null hypothesis this method can test for is whether the data are uncorrelated noise, possibly measured via a nonlinear function. Specifically, random shuffle surrogate can test the null hypothesis that the original signal is produced by independent and identically distributed random variables[^Theiler1991, ^Lancaster2018]. *Beware: random shuffle surrogates do not cover the case of correlated noise*[^Lancaster2018]. [^Theiler1991]: J. Theiler, S. Eubank, A. Longtin, B. Galdrikian, J. Farmer, Testing for nonlinearity in time series: The method of surrogate data, Physica D 58 (1–4) (1992) 77–94. """ struct RandomShuffle <: Surrogate end function surrogenerator(x::AbstractVector, rf::RandomShuffle, rng = Random.default_rng()) n = length(x) idxs = collect(1:n) init = ( permutation = zeros(Int, n), idxs = idxs, ) return SurrogateGenerator(rf, x, similar(x), init, rng) end function (sg::SurrogateGenerator{<:RandomShuffle})() x, s, rng = sg.x, sg.s, sg.rng permutation, idxs = getfield.(Ref(sg.init), (:permutation, :idxs)) sample!(rng, idxs, permutation; replace = false) s .= x[permutation] return s end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
2834
export RelativePartialRandomization, RelativePartialRandomizationAAFT """ RelativePartialRandomization(α = 0.5) `RelativePartialRandomization` surrogates are similar to [`PartialRandomization`](@ref) phase surrogates, but instead of drawing phases uniformly from `[0, 2π]`, phases are drawn from `ϕ + [0, 2π]*α`, where `α ∈ [0, 1]` and `ϕ` is the original Fourier phase. See the documentation for a detailed comparison between partial randomization algorithms. """ struct RelativePartialRandomization{T} <: Surrogate α::T function RelativePartialRandomization(α::T=0.5) where T <: Real 0 <= α <= 1 || throw(ArgumentError("α must be between 0 and 1")) return new{T}(α) end end function surrogenerator(x::AbstractVector, rf::RelativePartialRandomization, rng = Random.default_rng()) forward = plan_rfft(x) inverse = plan_irfft(forward*x, length(x)) m = mean(x) 𝓕 = forward*(x .- m) shuffled𝓕 = zero(𝓕) s = similar(x) n = length(𝓕) r = abs.(𝓕) ϕ = angle.(𝓕) coeffs = zero(r) init = (; inverse, m, coeffs, n, r, ϕ, shuffled𝓕) return SurrogateGenerator(rf, x, s, init, rng) end function (sg::SurrogateGenerator{<:RelativePartialRandomization})() inverse, m, coeffs, n, r, ϕ, shuffled𝓕 = getfield.(Ref(sg.init), (:inverse, :m, :coeffs, :n, :r, :ϕ, :shuffled𝓕)) s, rng = sg.s, sg.rng α = sg.method.α coeffs .= rand(rng, Uniform(0, 2π), n) coeffs .= (ϕ .+ coeffs.*α) shuffled𝓕 .= r .* cis.(coeffs) s .= inverse * shuffled𝓕 .+ m return s end """ RelativePartialRandomizationAAFT(α = 0.5) `RelativePartialRandomizationAAFT` surrogates are similar to [`RelativePartialRandomization`](@ref) surrogates, but add a rescaling step, so that the surrogate has the same values as the original time series (analogous to the rescaling done for [`AAFT`](@ref) surrogates). """ struct RelativePartialRandomizationAAFT{T} <: Surrogate α::T function RelativePartialRandomizationAAFT(α::T=0.5) where T <: Real 0 <= α <= 1 || throw(ArgumentError("α must be between 0 and 1")) return new{T}(α) end end function surrogenerator(x::AbstractVector, rf::RelativePartialRandomizationAAFT, rng = Random.default_rng()) init = ( gen = surrogenerator(x, RelativePartialRandomization(rf.α), rng), ix = zeros(Int, length(x)), x_sorted = sort(x), ) s = similar(x) return SurrogateGenerator(rf, x, s, init, rng) end function (sg::SurrogateGenerator{<:RelativePartialRandomizationAAFT})() gen, ix, x_sorted = sg.init.gen, sg.init.ix, sg.init.x_sorted s = sg.s # Surrogate starts out as a RelativePartialRandomization surrogate s .= gen() # Rescale to obtain a AAFT-like surrogate sortperm!(ix, s) s[ix] .= x_sorted return s end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
3075
export SpectralPartialRandomization, SpectralPartialRandomizationAAFT """ SpectralSpectralPartialRandomization(α = 0.5) `SpectralPartialRandomization` surrogates are similar to [`PartialRandomization`](@ref) phase surrogates, but instead of drawing phases uniformly from `[0, 2π]`, phases of the highest frequency components responsible for a proportion `α` of power are replaced by random phases drawn from `[0, 2π]` See the documentation for a detailed comparison between partial randomization algorithms. """ struct SpectralPartialRandomization{T} <: Surrogate α::T function SpectralPartialRandomization(α::T=0.5) where T <: Real 0 <= α <= 1 || throw(ArgumentError("α must be between 0 and 1")) return new{T}(α) end end function surrogenerator(x::AbstractVector, rf::SpectralPartialRandomization, rng = Random.default_rng()) forward = plan_rfft(x) inverse = plan_irfft(forward*x, length(x)) m = mean(x) 𝓕 = forward*(x .- m) shuffled𝓕 = zero(𝓕) s = similar(x) n = length(𝓕) r = abs.(𝓕) ϕ = angle.(𝓕) coeffs = zero(r) S = r.^2 S = S ./ sum(S[2:end]) # Ignore power due to the mean, S[1] fthresh = findfirst(cumsum(S) .> 1 - rf.α) isnothing(fthresh) && (fthresh = n+1) init = (; inverse, m, coeffs, n, r, ϕ, shuffled𝓕, fthresh) return SurrogateGenerator(rf, x, s, init, rng) end function (sg::SurrogateGenerator{<:SpectralPartialRandomization})() inverse, m, coeffs, n, r, ϕ, shuffled𝓕, fthresh = getfield.(Ref(sg.init), (:inverse, :m, :coeffs, :n, :r, :ϕ, :shuffled𝓕, :fthresh)) s, rng = sg.s, sg.rng coeffs .= rand(rng, Uniform(0, 2π), n) coeffs[1:fthresh-1] .= 0 coeffs .= (ϕ .+ coeffs) shuffled𝓕 .= r .* cis.(coeffs) s .= inverse * shuffled𝓕 .+ m return s end """ SpectralPartialRandomizationAAFT(α = 0.5) `SpectralPartialRandomizationAAFT` surrogates are similar to [`PartialRandomization`](@ref) surrogates, but add a rescaling step, so that the surrogate has the same values as the original time series (analogous to the rescaling done for [`AAFT`](@ref) surrogates). """ struct SpectralPartialRandomizationAAFT{T} <: Surrogate α::T function SpectralPartialRandomizationAAFT(α::T=0.5) where T <: Real 0 <= α <= 1 || throw(ArgumentError("α must be between 0 and 1")) return new{T}(α) end end function surrogenerator(x::AbstractVector, rf::SpectralPartialRandomizationAAFT, rng = Random.default_rng()) init = ( gen = surrogenerator(x, SpectralPartialRandomization(rf.α), rng), ix = zeros(Int, length(x)), x_sorted = sort(x), ) s = similar(x) return SurrogateGenerator(rf, x, s, init, rng) end function (sg::SurrogateGenerator{<:SpectralPartialRandomizationAAFT})() gen, ix, x_sorted = sg.init.gen, sg.init.ix, sg.init.x_sorted s = sg.s # Surrogate starts out as a SpectralPartialRandomization surrogate s .= gen() # Rescale to obtain a AAFT-like surrogate sortperm!(ix, s) s[ix] .= x_sorted return s end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
9267
using LinearAlgebra export TFTDRandomFourier, TFTD, TFTDAAFT, TFTDIAAFT # Efficient linear regression formula from dmbates julia discourse post (nov 2019) # https://discourse.julialang.org/t/efficient-way-of-doing-linear-regression/31232/27?page=2 function linreg(x, y) (N = length(x)) == length(y) || throw(DimensionMismatch()) ldiv!(cholesky!(Symmetric([float(N) sum(x); 0.0 sum(abs2, x)], :U)), [sum(y), dot(x, y)]) end function linear_trend(x) l = linreg(0.0:1.0:length(x)-1.0 |> Vector{eltype(x)}, x) return [l[1] + l[2]*a for a in x] end """ TFTD(phases::Bool = true, fϵ = 0.05) The `TFTDRandomFourier` (or just `TFTD` for short) surrogate was proposed by Lucio et al. (2012)[^Lucio2012] as a combination of truncated Fourier surrogates[^Nakamura2006] ([`TFTS`](@ref)) and detrend-retrend surrogates. The `TFTD` part of the name comes from the fact that it uses a combination of truncated Fourier transforms (TFT) and de-trending and re-trending (D) the time series before and after surrogate generation. Hence, it can be used to generate surrogates also from (strongly) nonstationary time series. ## Implementation details Here, a best-fit linear trend is removed/added from the signal prior to and after generating the random Fourier signal. In principle, any trend can be removed, but so far, we only provide the linear option. See also: [`TFTDAAFT`](@ref), [`TFTDIAAFT`](@ref). [^Nakamura2006]: Nakamura, Tomomichi, Michael Small, and Yoshito Hirata. "Testing for nonlinearity in irregular fluctuations with long-term trends." Physical Review E 74.2 (2006): 026205. [^Lucio2012]: Lucio, J. H., Valdés, R., & Rodríguez, L. R. (2012). Improvements to surrogate data methods for nonstationary time series. Physical Review E, 85(5), 056202. """ struct TFTDRandomFourier <: Surrogate phases::Bool fϵ function TFTDRandomFourier(phases::Bool, fϵ = 0.05) if !(0 < fϵ ≤ 1) throw(ArgumentError("`fϵ` must be on the interval (0, 1] (indicates fraction of lowest frequencies to be preserved)")) end new(phases, fϵ) end end const TFTD = TFTDRandomFourier TFTD() = TFTD(true) TFTD(fϵ::Real) = TFTDRandomFourier(true, fϵ) function surrogenerator(x::AbstractVector, rf::TFTD, rng = Random.default_rng()) # Detrended time series m = mean(x) trend = linear_trend(x) x̂ = x .- m .- trend # Pre-plan and allocate Fourier transform forward = plan_rfft(x̂) inverse = plan_irfft(forward * x̂, length(x̂)) 𝓕 = forward * x̂ n = length(𝓕) # Polar coordinate representation of the Fourier transform rx = abs.(𝓕) ϕx = angle.(𝓕) ϕs = similar(ϕx) permutation = zeros(Int, length(x)) idxs = collect(1:length(x)) # Initialize surrogate s = similar(x) init = (forward = forward, inverse = inverse, rx = rx, ϕx = ϕx, n = n, m = m, 𝓕 = 𝓕, ϕs = ϕs, trend = trend, x̂ = x̂, permutation, idxs) return SurrogateGenerator(rf, x, s, init, rng) end function (sg::SurrogateGenerator{<:TFTD})() fϵ = sg.method.fϵ s = sg.s init_fields = (:forward, :inverse, :rx, :ϕx, :n, :m, :𝓕, :ϕs, :trend, :x̂, :permutation, :idxs) forward, inverse, rx, ϕx, n, m, 𝓕, ϕs, trend, x̂, permutation, idxs = getfield.(Ref(sg.init), init_fields) # Surrogate starts out as a random permutation of x̂ sample!(sg.rng, idxs, permutation; replace = false) s .= @view x̂[permutation] mul!(𝓕, forward, s) ϕs .= angle.(𝓕) # Frequencies are ordered from lowest when taking the Fourier # transform, so by keeping the 1:n_preserve first phases intact, # we are only randomizing the high-frequency components of the # signal. n_preserve = ceil(Int, abs(fϵ * n)) ϕs[1:n_preserve] .= @view ϕx[1:n_preserve] # Updated spectrum is the old amplitudes with the mixed phases. 𝓕 .= rx .* exp.(ϕs .* 1im) # TODO: Unfortunately, we can't do inverse transform in-place yet, but # this is an open PR in FFTW. s .= inverse*𝓕 .+ m .+ trend return s end """ TFTDAAFT(fϵ = 0.05) [`TFTDAAFT`](@ref)[^Lucio2012] are similar to [`TFTD`](@ref) surrogates, but also re-scales back to the original values of the time series. `fϵ ∈ (0, 1]` is the fraction of the powerspectrum corresponding to the lowermost frequencies to be preserved. See also: [`TFTD`](@ref), [`TFTDIAAFT`](@ref). [^Lucio2012]: Lucio, J. H., Valdés, R., & Rodríguez, L. R. (2012). Improvements to surrogate data methods for nonstationary time series. Physical Review E, 85(5), 056202. """ struct TFTDAAFT <: Surrogate fϵ function TFTDAAFT(fϵ = 0.05) if !(0 < fϵ ≤ 1) throw(ArgumentError("`fϵ` must be on the interval (0, 1] (indicates fraction of lowest frequencies to be preserved)")) end new(fϵ) end end function surrogenerator(x::AbstractVector, method::TFTDAAFT, rng = Random.default_rng()) init = ( gen = surrogenerator(x, TFTS(method.fϵ), rng), ix = zeros(Int, length(x)), x_sorted = sort(x), ) s = similar(x) return SurrogateGenerator(method, x, s, init, rng) end function (sg::SurrogateGenerator{<:TFTDAAFT})() s = sg.s tfts_gen, ix, x_sorted = sg.init.gen, sg.init.ix, sg.init.x_sorted s .= tfts_gen() sortperm!(ix, s) s[ix] .= x_sorted return s end """ TFTDIAAFT(fϵ = 0.05; M::Int = 100, tol::Real = 1e-6, W::Int = 75) [`TFTDIAAFT`](@ref)[^Lucio2012] are similar to [`TFTDAAFT`](@ref), but adds an iterative procedure to better match the periodograms of the surrogate and the original time series, analogously to how [`IAAFT`](@ref) improves upon [`AAFT`](@ref). `fϵ ∈ (0, 1]` is the fraction of the powerspectrum corresponding to the lowermost frequencies to be preserved. `M` is the maximum number of iterations. `tol` is the desired maximum relative tolerance between power spectra. `W` is the number of bins into which the periodograms are binned when comparing across iterations. See also: [`TFTD`](@ref), [`TFTDAAFT`](@ref). [^Lucio2012]: Lucio, J. H., Valdés, R., & Rodríguez, L. R. (2012). Improvements to surrogate data methods for nonstationary time series. Physical Review E, 85(5), 056202. """ struct TFTDIAAFT <: Surrogate fϵ M::Int tol::Real W::Int function TFTDIAAFT(fϵ = 0.05; M::Int = 100, tol::Real = 1e-6, W::Int = 75) if !(0 < fϵ ≤ 1) throw(ArgumentError("`fϵ` must be on the interval (0, 1] (indicates fraction of lowest frequencies to be preserved)")) end new(fϵ, M, tol, W) end end function surrogenerator(x::AbstractVector, method::TFTDIAAFT, rng = Random.default_rng()) # Surrogate starts out as a TFTDRandomFourier surrogate gen = surrogenerator(x, TFTDRandomFourier(true, method.fϵ), rng) # Pre-allocate forward transform for periodogram; can be re-used. 𝓕, x̂, forward = gen.init.𝓕, gen.init.x̂, gen.init.forward 𝓕p = prepare_spectrum(x̂, forward) # Initial power spectra and their interpolated versions. xpower = similar(𝓕) .|> real; powerspectrum!(𝓕p, xpower, x̂, forward) spower = copy(xpower) xpowerᵦ = interpolated_spectrum(xpower, method.W) spowerᵦ = interpolated_spectrum(spower, method.W) init = ( gen = gen, ix = zeros(Int, length(x)), x_sorted = sort(x), 𝓕p = 𝓕p, xpower = xpower, spower = spower, xpowerᵦ = xpowerᵦ, spowerᵦ = spowerᵦ, ) s = similar(x) return SurrogateGenerator(method, x, s, init, rng) end function (sg::SurrogateGenerator{<:TFTDIAAFT})() x, s, rng = sg.x, sg.s, sg.rng fϵ, M, W, tol = sg.method.fϵ, sg.method.M, sg.method.W, sg.method.tol n_preserve = ceil(Int, abs(fϵ * length(x))) tftd_gen = sg.init.gen 𝓕, forward, ϕs, ϕx, rx, trend, x̂ = getfield.(Ref(tftd_gen.init), (:𝓕, :forward, :ϕx, :ϕs, :rx, :trend, :x̂) ) x_sorted, ix, 𝓕p, xpower, spower, xpowerᵦ, spowerᵦ = getfield.(Ref(sg.init), (:x_sorted, :ix, :𝓕p, :xpower, :spower, :xpowerᵦ, :spowerᵦ) ) sum_old, sum_new = 0.0, 0.0 iter = 1 # Surrogate starts out as a TFTDRandomFourier realization of `x`. s .= tftd_gen() while iter <= M # Detrend and take transform (steps (vii-viii) in Lucio et al.) s .= s .- trend mul!(𝓕, forward, s) # Rescaling the power spectrum, keeping some percentage of lowermost # frequencies, then re-trending (steps vii-x in Lucio et al.) ϕs .= angle.(𝓕) ϕs[1:n_preserve] .= @view ϕx[1:n_preserve] 𝓕 .= rx .* exp.(ϕs .* 1im) s .= s .+ trend # Adjusting amplitudes sortperm!(ix, s) s[ix] .= x_sorted # Compare power spectra powerspectrum!(𝓕p, spower, s, forward) interpolated_spectrum!(spowerᵦ, spower, W) if iter == 1 sum_old = sum((xpowerᵦ .- xpowerᵦ) .^ 2) / sum(xpowerᵦ .^ 2) else sum_new = sum((xpowerᵦ .- spowerᵦ) .^ 2) / sum(xpowerᵦ .^ 2) if abs(sum_old - sum_new) < tol iter = M + 1 else sum_old = sum_new end end iter += 1 end return s end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
6746
export TFTS, TAAFT using StatsBase: sample, sample! """ TFTS(fϵ::Real) A truncated Fourier transform surrogate[^Nakamura2006] (TFTS). TFTS surrogates are generated by leaving some frequencies untouched when performing the phase shuffling step (as opposed to randomizing all frequencies, like for [`RandomFourier`](@ref) surrogates). These surrogates were designed to deal with data with irregular fluctuations superimposed over long term trends (by preserving low frequencies)[^Nakamura2006]. Hence, TFTS surrogates can be used to test the null hypothesis that the signal is a stationary linear system generated the irregular fluctuations part of the signal[^Nakamura2006]. ## Controlling the truncation of the spectrum The truncation parameter `fϵ ∈ [-1, 0) ∪ (0, 1]` controls which parts of the spectrum are preserved. - If `fϵ > 0`, then `fϵ` indicates the ratio of high frequency domain to the entire frequency domain. For example, `fϵ = 0.5` preserves 50% of the frequency domain (randomizing the higher frequencies, leaving low frequencies intact). - If `fϵ < 0`, then `fϵ` indicates ratio of low frequency domain to the entire frequency domain. For example, `fϵ = -0.2` preserves 20% of the frequency domain (leaving higher frequencies intact, randomizing the lower frequencies). - If `fϵ ± 1`, then all frequencies are randomized. The method is then equivalent to [`RandomFourier`](@ref). The appropriate value of `fϵ` strongly depends on the data and time series length, and must be manually determined[^Nakamura2006], for example by comparing periodograms for the time series and the surrogates. [^Nakamura2006]: Nakamura, Tomomichi, Michael Small, and Yoshito Hirata. "Testing for nonlinearity in irregular fluctuations with long-term trends." Physical Review E 74.2 (2006): 026205. """ struct TFTS <: Surrogate fϵ::Real function TFTS(fϵ::Real) if !(0 < fϵ ≤ 1) && !(-1 ≤ fϵ < 0) throw(ArgumentError("`fϵ` must be on the interval [-1, 0) ∪ (0, 1] (positive if preserving high frequencies, negative if preserving low frequencies)")) end new(fϵ) end end function surrogenerator(x, method::TFTS, rng = Random.default_rng()) # Pre-plan Fourier transforms forward = plan_rfft(x) inverse = plan_irfft(forward*x, length(x)) # Pre-compute 𝓕 𝓕 = forward * x # Polar coordinate representation of the Fourier transform rx = abs.(𝓕) ϕx = angle.(𝓕) n = length(𝓕) # These are updated during iteration procedure 𝓕new = Vector{Complex{Float64}}(undef, length(𝓕)) 𝓕s = Vector{Complex{Float64}}(undef, length(𝓕)) ϕs = Vector{Complex{Float64}}(undef, length(𝓕)) init = (forward = forward, inverse = inverse, rx = rx, ϕx = ϕx, n = n, 𝓕new = 𝓕new, 𝓕s = 𝓕s, ϕs = ϕs) return SurrogateGenerator(method, x, similar(x), init, rng) end function (sg::SurrogateGenerator{<:TFTS})() x, s = sg.x, sg.s fϵ = sg.method.fϵ L = length(x) init_fields = (:forward, :inverse, :rx, :ϕx, :n, :𝓕new, :𝓕s, :ϕs) forward, inverse, rx, ϕx, n, 𝓕new, 𝓕s, ϕs = getfield.(Ref(sg.init), init_fields) # Surrogate starts out as a random permutation of x s .= x[sample(sg.rng, 1:L, L; replace = false)] 𝓕s .= forward * s ϕs .= angle.(𝓕s) # Updated spectrum is the old amplitudes with the mixed phases. if fϵ > 0 # Frequencies are ordered from lowest when taking the Fourier # transform, so by keeping the 1:n_ni first phases intact, # we are only randomizing the high-frequency components of the # signal. n_preserve = ceil(Int, abs(fϵ * n)) ϕs[1:n_preserve] .= ϕx[1:n_preserve] elseif fϵ < 0 # Do the exact opposite to preserve high-frequencies n_preserve = ceil(Int, abs(fϵ * n)) ϕs[end-n_preserve+1:end] .= ϕx[end-n_preserve+1:end] end 𝓕new .= rx .* exp.(ϕs .* 1im) s .= inverse * 𝓕new return s end """ TAAFT(fϵ) An truncated version of the amplitude-adjusted-fourier-transform surrogate[^Theiler1991][^Nakamura2006]. The truncation parameter and phase randomization procedure is identical to [`TFTS`](@ref), but here an additional step of rescaling back to the original data is performed. This preserves the amplitude distribution of the original data. [^Theiler1991]: J. Theiler, S. Eubank, A. Longtin, B. Galdrikian, J. Farmer, Testing for nonlinearity in time series: The method of surrogate data, Physica D 58 (1–4) (1992) 77–94. [^Nakamura2006]: Nakamura, Tomomichi, Michael Small, and Yoshito Hirata. "Testing for nonlinearity in irregular fluctuations with long-term trends." Physical Review E 74.2 (2006): 026205. """ struct TAAFT <: Surrogate fϵ::Real function TAAFT(fϵ::Real) fϵ != 0 || throw(ArgumentError("`fϵ` must be on the interval [-1, 0) ∪ (0, 1] (positive if preserving high frequencies, negative if preserving low frequencies)")) new(fϵ) end end function surrogenerator(x, method::TAAFT, rng = Random.default_rng()) init = ( gen = surrogenerator(x, TFTS(method.fϵ), rng), x_sorted = sort(x), idxs = collect(1:length(x)), perm = zeros(Int, length(x)), ) s = similar(x) return SurrogateGenerator(method, x, s, init, rng) end function (taaft::SurrogateGenerator{<:TAAFT})() sg = taaft.init.gen x_sorted, idxs, perm = taaft.init.x_sorted, taaft.init.idxs, taaft.init.perm x, s = sg.x, sg.s fϵ = sg.method.fϵ L = length(x) init_fields = (:forward, :inverse, :rx, :ϕx, :n, :𝓕new, :𝓕s, :ϕs) forward, inverse, rx, ϕx, n, 𝓕new, 𝓕s, ϕs = getfield.(Ref(sg.init), init_fields) # Surrogate starts out as a random permutation of x sample!(sg.rng, idxs, perm, replace = false) permuted_x_into_s!(s, x, perm) 𝓕s .= forward * s ϕs .= angle.(𝓕s) # Updated spectrum is the old amplitudes with the mixed phases. if fϵ > 0 # Frequencies are ordered from lowest when taking the Fourier # transform, so by keeping the 1:n_ni first phases intact, # we are only randomizing the high-frequency components of the # signal. n_preserve = ceil(Int, abs(fϵ * n)) ϕs[1:n_preserve] .= @view ϕx[1:n_preserve] elseif fϵ < 0 # Do the exact opposite to preserve high-frequencies n_preserve = ceil(Int, abs(fϵ * n)) ϕs[end-n_preserve+1:end] .= @view ϕx[end-n_preserve+1:end] end 𝓕new .= rx .* exp.(ϕs .* 1im) s .= inverse * 𝓕new s[sortperm(s)] .= x_sorted return s end function permuted_x_into_s!(s, x, perm) k = 1 for i in perm s[k] = x[i] k += 1 end end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
13924
export WLS, RandomCascade using Wavelets, Statistics """ WLS(shufflemethod::Surrogate = IAAFT(); f::Union{Nothing, Function} = Statistics.cor, rescale::Bool = true, wt::Wavelets.WT.OrthoWaveletClass = Wavelets.WT.Daubechies{16}()) A wavelet surrogate generated by the following procedure: 1. Compute the wavelet transform of the signal. This results in a set of detail coefficients over a set of dyadic scales. As in Keylock (2006), we here use the maximal overlap discrete wavelet transform, or MODWT, so that the number of coefficients at each scale are the same. 2. Shuffle the detail coefficients at each dyadic scale using the provided `shufflemethod`. See "Shuffling methods" below for alternatives. 3. Apply the inverse wavelet transform to the shuffled detail coefficients to obtain a surrogate time series. ## Shuffling methods You may choose to use any surrogate from this package to perform the randomization of the detail coefficients at each dyadic scale. The following methods have been discussed in the literature (more may exist): - Random permutations of wavelet coefficients within each scale (Breakspear et al., 2003). To get this behaviour, use `WLS(x, RandomShuffle(), rescale = false, f = nothing)`. - Cyclic rotation of wavelet coefficients within each scale (Breakspear et al., 2003). To get this behaviour, use `WLS(x, Circshift(1:length(x)), rescale = false, f = nothing)`. - Block resampling of wavelet coefficients within each scale (Breakspear et al., 2003). To get this behaviour, use `WLS(x, BlockShuffle(nblocks, randomize = true), rescale = false, f = nothing)`. - IAAFT resampling of wavelet coefficients within each scale (Keylock, 2006). To get this behaviour, use `WLS(x, IAAFT(), rescale = true, f = Statistics.cor)`. This method preserves the local mean and variance structure of the signal, but randomises nonlinear properties of the signal (i.e. Hurst exponents)[^Keylock2006]. These surrogates can therefore be used to test for changes in nonlinear properties of the original signal. In contrast to IAAFT surrogates, the IAAFT-wavelet surrogates also preserves nonstationarity. Using other `shufflemethod`s does not necessarily preserve nonstationarity. To deal with nonstationary signals, Keylock (2006) recommends using a wavelet with a high number of vanishing moments. Thus, our default is to use a Daubechies wavelet with 16 vanishing moments. *Note: The iterative procedure after the rank ordering step (step [v] in [^Keylock2006]) is not performed in this implementation.* The default method and parameters replicate the behaviour of Keylock (2006)'s IAAFT wavelet surrogates. ## Error minimization For the [`IAAFT`](@ref) approach introduced in Keylock (2006), detail coefficients at each level are circularly rotated to minimize an error function. The methods introduced in Breakspear et al. (2003) do not apply this error minimization. In our implementation, you can turn this option on/off using the `f` parameter of the `WLS` constructor. If `f = nothing` turns off error minization. If `f` is set to a two-argument function that computes some statistic, for example `f = Statistics.cor`, then detail coefficients at each scale are circularly rotated until that function is maximized (and hence the "error" minimized). If you want to *minimize* some error function, then instead provide an appropriate transform of your function. For example, if using the root mean squared deviation, define `rmsd_inv(x, y) = 1 - StatsBase.rmsd(x, y)` and set `f = rmsd_inv`. ## Rescaling If `rescale == true`, then surrogate values are mapped onto the values of the original time series, as in the [`AAFT`](@ref) algorithm. If `rescale == false`, surrogate values are not constrained to the original time series values. If [`AAFT`](@ref) or [`IAAFT`](@ref) shuffling is used, `rescale` should be set to `true`. For other methods, it does not necessarily need to be. [^Breakspear2003]: Breakspear, M., Brammer, M., & Robinson, P. A. (2003). Construction of multivariate surrogate sets from nonlinear data using the wavelet transform. Physica D: Nonlinear Phenomena, 182(1-2), 1-22. [^Keylock2006]: C.J. Keylock (2006). "Constrained surrogate time series with preservation of the mean and variance structure". Phys. Rev. E. 73: 036707. doi:10.1103/PhysRevE.73.036707. """ struct WLS{WT <: Wavelets.WT.OrthoWaveletClass, S <: Surrogate, E <: Union{Nothing, Function}} <: Surrogate shufflemethod::Surrogate # should preserve values of the original series rescale::Bool f::E wt::WT function WLS(method::S = IAAFT(); rescale::Bool = true, wt::WT = Wavelets.WT.Daubechies{16}(), f::E = Statistics.cor) where {S <: Surrogate, WT <: Wavelets.WT.OrthoWaveletClass, E <: Union{Nothing, Function}} new{WT, S, E}(method, rescale, f, wt) end end # Initialize without error minimization. function get_init_noerrorminimize(x, method, rng = Random.default_rng()) wl = wavelet(method.wt) L = length(x) x_sorted = sort(x) # Wavelet coefficients (step [i] in Keylock) W = modwt(x, wl) T = eltype(W) R = zeros(size(W)) Nscales = ndyadicscales(L) # Will contain surrogate realizations of the wavelet coefficients # at each scale (step [ii] in Keylock). sW = zeros(T, size(W)) # Surrogate generators for each set of coefficients sgs = [surrogenerator(W[:, i], method.shufflemethod, rng) for i = 1:Nscales] init = ( wl = wl, W = W, Nscales = Nscales, sW = sW, sgs = sgs, x_sorted = x_sorted, R = R, ) return init end # Initialize error minimization, as in Keylock (2006). function get_init_errorminimize(x, method::WLS, rng = Random.default_rng()) wl = wavelet(method.wt) L = length(x) x_sorted = sort(x) # Wavelet coefficients (step [i] in Keylock) W = modwt(x, wl) T = eltype(W) Nscales = ndyadicscales(L) # Will contain surrogate realizations of the wavelet coefficients # at each scale (step [ii] in Keylock). sW = zeros(T, size(W)) # We will also need a matrix to store the mirror images of the # surrogates (last part of step [ii]) sWmirr = zeros(T, size(W)) # Surrogate generators for each set of coefficients sgs = [surrogenerator(W[:, i], method.shufflemethod, rng) for i = 1:Nscales] # Temporary array for the circular shift error minimizing step circshifted_s = zeros(T, size(W)) circshifted_smirr = zeros(T, size(W)) R = zeros(size(W)) s = similar(x) init = (wl = wl, W = W, Nscales = Nscales, L = L, sW = sW, sgs = sgs, sWmirr = sWmirr, circshifted_s = circshifted_s, circshifted_smirr = circshifted_smirr, x_sorted = x_sorted, R = R, ) return init end function surrogenerator(x::AbstractVector{T}, method::WLS, rng = Random.default_rng()) where T init = isnothing(method.f) ? get_init_noerrorminimize(x, method, rng) : get_init_errorminimize(x, method, rng) s = similar(x) return SurrogateGenerator(method, x, s, init, rng) end function (sg::SurrogateGenerator{<:WLS})() if isnothing(sg.method.f) wls_noerrorminimize(sg) else wls_errorminimize(sg) end end function wls_noerrorminimize(sg::SurrogateGenerator{<:WLS}) s = sg.s fds = (:wl, :W, :Nscales, :sW, :sgs, :x_sorted, :R) wl, W, Nscales, sW, sgs, x_sorted, R = getfield.(Ref(sg.init), fds) for λ in 1:Nscales sW[:, λ] .= sgs[λ]() end s .= imodwt(sW, wl) if sg.method.rescale s[sortperm(s)] .= x_sorted end return s end function wls_errorminimize(sg::SurrogateGenerator{<:WLS}) s = sg.s # Error minimization function (if we reached this function, # f is never `Nothing`), so we can use it safely. f = sg.method.f fds = (:wl, :W, :Nscales, :L, :sW, :sgs, :sWmirr, :circshifted_s, :circshifted_smirr, :x_sorted, :R) wl, W, Nscales, L, sW, sgs, sWmirr, circshifted_s, circshifted_smirr, x_sorted, R = getfield.(Ref(sg.init), fds) # Create surrogate versions of detail coefficients at each dyadic scale [first part of step (ii) in Keylock] for λ in 1:Nscales sW[:, λ] .= sgs[λ]() end # Mirror the surrogate coefficients [last part of step (ii) in Keylock] sWmirr .= reverse(sW, dims = 1) # In the original paper, surrogates and mirror images are matched to original # detail coefficients in a circular manner until some error criterion is # minimized. Then, the surrogate or its mirror image, depending on which provides # the best fit to the original coefficients, is chosen as the representative # for a particular dyadic scale. Here, we instead use maximal correlation as # the criterion for matching. optimal_shifts = zeros(Int, Nscales) optimal_shifts_mirr = zeros(Int, Nscales) maxcorrs = zeros(Nscales) maxcorrs_mirr = zeros(Nscales) for i in 0:L-1 circshift!(circshifted_s, sW, (i, 0)) circshift!(circshifted_smirr, sWmirr, (i, 0)) for λ in 1:Nscales origW = W[:, λ] c = f(origW, circshifted_s[:, λ]) if c > maxcorrs[λ] maxcorrs[λ] = c optimal_shifts[λ] = i end c_mirr = f(origW, circshifted_smirr[:, λ]) if c_mirr > maxcorrs_mirr[λ] maxcorrs_mirr[λ] = c_mirr optimal_shifts_mirr[λ] = i end end end # Decide which coefficients are retained (either surrogate or mirror surrogate coefficients) for λ in 1:Nscales if maxcorrs[λ] >= maxcorrs_mirr[λ] R[:, λ] .= circshift(sW[:, λ], optimal_shifts[λ]) else R[:, λ] .= circshift(sWmirr[:, λ], optimal_shifts_mirr[λ]) end end s .= imodwt(R, wl) if sg.method.rescale s[sortperm(s)] .= x_sorted end return s end """ RandomCascade(paddingmode::String = "zeros") A random cascade multifractal wavelet surrogate (Paluš, 2008)[^Paluš2008]. If the input signal length is not a power of 2, the signal must be padded before the surrogate is constructed. `paddingmode` determines how the signal is padded. Currently supported padding modes: `"zeros"`. The final surrogate (constructed from the padded signal) is subset to match the length of the original signal. Random cascade surrogate preserve multifractal properties of the input time series, that is, interactions among dyadic scales and nonlinear dependencies[^Paluš2008]. [^Paluš2008]: Paluš, Milan (2008). Bootstrapping Multifractals: Surrogate Data from Random Cascades on Wavelet Dyadic Trees. Physical Review Letters, 101(13), 134101–. doi:10.1103/PhysRevLett.101.134101 """ struct RandomCascade{WT <: Wavelets.WT.OrthoWaveletClass} <: Surrogate wt::WT paddingmode::String function RandomCascade(; wt::WT = Wavelets.WT.Daubechies{16}(), paddingmode::String = "zeros") where {WT <: Wavelets.WT.OrthoWaveletClass} new{WT}(wt, paddingmode) end end function surrogenerator(x::AbstractVector{T}, method::RandomCascade, rng = Random.default_rng()) where T nlevels = ndyadicscales(length(x)) mode = method.paddingmode # Pad input so that input to discrete wavelet transform has length which is a power of 2 x̃ = zeros(2^(nlevels + 1)) pad!(x̃, x, mode) wl = wavelet(method.wt) # Wavelet coefficients (step [i] in Keylock) c = dwt(x̃, wl, nlevels) # Surrogate coefficients will be partly identical to original coefficients, # so we simply copy them and replace the necessary coefficients later. cₛ = copy(c) # Multiplication factors and index vectors can be pre-allocated for # levels 2:nlevels-1; they are overwritten for each new surrogate. Ms = [zeros(dyadicdetailn(j-1)) for j = 2:nlevels-1] ixs = [zeros(Int, dyadicdetailn(j-1)) for j = 2:nlevels-1] init = ( wl = wl, c = c, cₛ = cₛ, nlevels = nlevels, s̃ = similar(x̃), Ms = Ms, ixs = ixs, ) return SurrogateGenerator(method, x, similar(x), init, rng) end function (sg::SurrogateGenerator{<:RandomCascade})() s, rng = sg.s, sg.rng c, cₛ, s̃, wl, nlevels, Ms, ixs = sg.init.c, sg.init.cₛ, sg.init.s̃, sg.init.wl, sg.init.nlevels, sg.init.Ms, sg.init.ixs cₛ[dyadicdetailrange(0)] = @view c[dyadicdetailrange(0)] cₛ[dyadicdetailrange(1)] = @view c[dyadicdetailrange(1)] for (l, j) = enumerate(2:nlevels-1) cⱼ₋₁ = @view c[dyadicdetailrange(j - 1)] cⱼ = @view c[dyadicdetailrange(j)] M = Ms[l] ct = 1 @inbounds for k = 1:length(cⱼ₋₁) if k % 2 == 0 M[ct] = cⱼ[2*k] / cⱼ₋₁[k] else M[ct] = cⱼ[2*(k+1)] / cⱼ₋₁[k+1] end ct += 1 end shuffle!(rng, M) new_coeffs!(M, cⱼ₋₁) ix = ixs[l] sortperm!(ix, M) cₛ[dyadicdetailrange(j-1)] .= @view cⱼ₋₁[ix] end s̃ .= idwt(cₛ, wl, nlevels) # Surrogate length must match length of original signal. s .= @view s̃[1:length(s)] return s end function pad!(x̃, x, mode) if mode == "zeros" copyto!(x̃, x) elseif mode == "constant" copyto!(x̃, x) x̃[length(x)+1:end] .= x[end] elseif mode == "linear" copyto!(x̃, x) for i = length(x)+1:length(x̃) x̃[i] = 2*x̃[i-1] - x̃[i-2] end else throw(ArgumentError("""`paddingmode` must be one of ["zeros", "constant", "linear"]""")) end end function new_coeffs!(M, cⱼ₋₁) @inbounds for k = 1:length(cⱼ₋₁) M[k] = M[k] * cⱼ₋₁[k] end end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
710
""" surroplot(x, s; kwargs...) → fig surroplot(x, method::Surrogate; kwargs...) → fig surroplot!(fig_or_gridlayout, x, method::Surrogate) Plot a timeseries `x` along with its surrogate realization `s`, and compare the power spectrum and histogram of the two time series. If given a method to generate surrogates, create a surrogate from `x` and plot it. ## Keyword arguments - `cx` and `cs`: Colors of the original and the surrogate time series, respectively. - `nbins`: The number of bins for the histograms. - `kwargs...`: Propagated to `Makie.Figure`. - `resolution`: A tuple giving the resolution of the figure. """ function surroplot end function surroplot! end export surroplot, surroplot!
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
1011
getrange(t, n) = range(minimum(t); stop = maximum(t), length = n) itp(x) = LinearInterpolation(1:length(x), x) interp(itp, tᵢ) = itp() """ Linearly interpolates two vectors x and y on a linear grid consisting of `nsteps`. """ function interp(x::Vector, y::Vector, nsteps::Int) # Interpolate itp = interpolate((x,), y, Gridded(Linear())) # Interpolate at the given resolution x_fills = LinRange(minimum(x), maximum(x), nsteps) y_fills = itp(x_fills) return collect(x_fills), y_fills end """ Linearly interpolates two vector x and y on a linear grid consisting of `nsteps`. """ function interp(x, y, range::LinRange) itp = interpolate((x,), y, Gridded(Linear())) # Interpolate at the given resolution return itp(range) end """ interp!(ȳ::Vector, itp) Interpolate using the pre-computed interpolation instance `itp` into the pre-allocated vector `ȳ`. """ function interp!(ȳ::Vector, itp) y_fills .= itp(x_fills) return collect(x_fills), y_fills end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
3602
# This file consists of code that is simplified/modified/inspired by/from # the DSP.jl package. The purpose of these functions is to speed up repeated # power spectrum computations for real-valued 1D vectors, by utilizing fft-plans # and in-place computations. # # The DSP module is distributed under the MIT license. # Copyright 2012-2021 DSP.jl contributors # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software withspectrum restriction, including withspectrum limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using DSP using LinearAlgebra: mul! """ prepare_spectrum(s, plan) → y::Vector Pre-allocate a vector that will hold the one-sided power spectrum for a signal `s`, taking into account the number of points that will be used for the Fourier transform. """ function prepare_spectrum(s, plan) return plan * s end """ _powerspectrum_from_fft!( spectrum::AbstractArray{T}, ℱ::AbstractVector{Complex{T}}, nfft::Int, r::Real, offset::Int = 0 ) where T Compute one-sided power spectrum from a pre-computed Fourier transform `ℱ` of a signal, into a pre-allocated `spectrum vector``. `nfft` is the number of points used for the Fourier transform. `n` is the length of the signal, """ function _powerspectrum_from_fft!( spectrum::AbstractArray{T}, ℱ::AbstractVector{Complex{T}}, nfft::Int, n::Real, offset::Int = 0 ) where T l = length(ℱ) m1, m2 = convert(T, 1 / n), convert(T, 2 / n) for i = 2:l-1 @inbounds spectrum[offset + i] += abs2(ℱ[i]) * m2 end @inbounds spectrum .+= abs2.(ℱ) .* m2 @inbounds spectrum[offset + l] += abs2(ℱ[end]) * ifelse(iseven(nfft), m1, m2) return spectrum end """ powerspectrum_onesided!(spectrum, signal, forward) Let `n = DSP.nextfastfft(length(s))`. Modifies `spectrum` in-place, so `spectrum` is reset to all zeros every time this function is called. - `forward` is a forward fft-plan for the signal. - `spectrum` is a pre-allocated `AbstractVector{<:Real}` that will hold the spectrum. Has the length of the Fourier transform resulting from `forward * signal`. - `signal` is the signal, a `AbstractVector{<:Real}` of length `n`. """ function powerspectrum!(ℱp, spectrum, signal, forward) # Fourier transform of the signal, based on pre-computed plan `forward`. mul!(ℱp, forward, signal) #ℱp = forward * signal l = length(signal) # Reset spectrum, since we're doing multiple in-place additions to it. spectrum .= 0.0 # In-place computation of spectrum based on the transform `ℱ` n = nextfastfft(l) _powerspectrum_from_fft!(spectrum, ℱp, n, l) return spectrum end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
4332
export NLNS, NSAR2, AR1, randomwalk, SNLST, random_cycles, colored_noise """ AR1(; n_steps, x₀, k, rng) Simple AR(1) model given by the following map: ```math x(t+1) = k x(t) + a(t), ``` where ``a(t)`` is a draw from a normal distribution with zero mean and unit variance. `x₀` sets the initial condition and `k` is the tunable parameter in the map. `rng` is a random number generator """ function AR1(n_steps, x₀, k, rng) a = rand(rng, Normal(), n_steps) x = Vector{Float64}(undef, n_steps) x[1] = x₀ for i = 2:n_steps x[i] = k*x[i-1] + a[i] end x end AR1(;n_steps = 500, x₀ = rand(), k = rand(), rng = Random.default_rng()) = AR1(n_steps, x₀, k, rng) """ NSAR2(n_steps, x₀, x₁) Cyclostationary AR(2) process[^1]. ## References [^1]: Lucio et al., Phys. Rev. E *85*, 056202 (2012). [https://journals.aps.org/pre/abstract/10.1103/PhysRevE.85.056202](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.85.056202) """ function NSAR2(n_steps, x₀, x₁) T₀ = 50.0 τ = 10.0 M = 5.5 Tmod = 250 σ₀ = 1.0 a_1_0 = 2*cos(2*π/T₀)*exp(-1/τ) a₂ = -exp(-2 / τ) a = rand(Normal(), n_steps) x = Vector{Float64}(undef, n_steps) x[1], x[2] = x₀, x₁ for i = 3:n_steps T_t = T₀ + M*sin(2*π*i / Tmod) a₁_t = 2*cos(2*π/T_t) * exp(-1 / τ) σ = σ₀^2/(1 - a_1_0^2 - a₂^2 - (2*(a_1_0^2) * a₂)/(1 - a₂)) * (1 - a₁_t - a₂^2 - (2*(a₁_t^2) * a₂)/(1 - a₂)) x[i] = a₁_t * x[i-1] + a₂*x[i-2] + rand(Normal(0, sqrt(σ))) end x end """ randomwalk(n_steps, x₀) Linear random walk (AR(1) process with a unit root)[^1]. This is an example of a nonstationary linear process. # References [^1]: Lucio et al., Phys. Rev. E *85*, 056202 (2012). [https://journals.aps.org/pre/abstract/10.1103/PhysRevE.85.056202](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.85.056202) """ function randomwalk(n_steps, x₀) a = rand(Normal(), n_steps) x = Vector{Float64}(undef, n_steps) x[1] = x₀ for i = 2:n_steps x[i] = x[i-1] + a[i] end x end """ SNLST(n_steps, x₀, k) Dynamically linear process transformed by a strongly nonlinear static transformation (SNLST)[^1]. ## Equations The system is by the following map: ```math x(t) = k x(t-1) + a(t) ``` with the transformation ``s(t) = x(t)^3``. # References [^1]: Lucio et al., Phys. Rev. E *85*, 056202 (2012). [https://journals.aps.org/pre/abstract/10.1103/PhysRevE.85.056202](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.85.056202) """ function SNLST(n_steps, x₀, k) a = rand(Normal(), n_steps) x = Vector{Float64}(undef, n_steps) x[1] = x₀ for i = 2:n_steps x[i] = k*x[i-1] + a[i] end x.^3 end # Keyword versions of the functions SNLST(;n_steps = 500, x₀ = rand(), k = rand()) = SNLST(n_steps, x₀, k) randomwalk(;n_steps = 500, x₀ = rand()) = randomwalk(n_steps, x₀) NSAR2(;n_steps = 500, x₀ = rand(), x₁ = rand()) = NSAR2(n_steps, x₀, x₁) """ random_cycles(; periods=10 dt=π/20, σ = 0.05, frange = (0.8, 2.0)) Make a timeseries that is composed of `period` full sine wave periods, each with a random frequency in the range given by `frange`, and added noise with std `σ`. The sampling time is `dt`. """ function random_cycles(rng = Random.default_rng(); periods=10, dt=π/20, σ = 0.05, frange = (1.0, 1.6)) dt = π/20 x = Float64[] for i in 1:periods f = (frange[1]-frange[2])*rand(rng) + frange[1] T = 2π/f t = 0:dt:T append!(x, sin.(f .* t)) end N = length(x) x .+= randn(N)/20 return x end """ colored_noise(rng = Random.default_rng(); n::Int = 500, ρ, σ = 0.1, transform = true) Generate `n` points of colored noise. `ρ` is the desired correlation between adjacent samples. The noise is drawn from a normal distribution with zero mean and standard deviation `σ`. If `transform = true`, then transform data using aquadratic nonlinear static distortion. """ function colored_noise(rng = Random.default_rng(); n::Int = 500, ρ = 0.8, σ = 0.1, transform = true) 𝒩 = Normal(0, σ) x = zeros(n) x[1] = rand(rng, 𝒩) for i = 2:n x[i] = ρ*x[i-1] + sqrt(1 - ρ^2)*rand(rng, 𝒩) end if transform x .= x .* sqrt.(x .^ 2) end return x .- mean(x) end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
8037
using Test using TimeseriesSurrogates using TimeseriesSurrogates.AbstractFFTs using TimeseriesSurrogates.Statistics using TimeseriesSurrogates.Random N = 500 ts = cumsum(randn(N)) ts_nan = cumsum(randn(N)) ts_nan[1] = NaN x = cos.(range(0, 20π, length = N)) .+ randn(N)*0.05 @testset "LombScargle" begin t = sort((0:N-1) + rand(N)) tol = 10 ls = IrregularLombScargle(t, tol = 10, n_total = 20000, n_acc = 5000) s = surrogate(x, ls) @test all(sort(s) .== sort(x)) end @testset "WLS" begin wts_norescale = WLS(AAFT(), rescale = false) wts_rescale = WLS(AAFT()) s_norescale = surrogate(x, wts_norescale) s_rescale = surrogate(x, wts_rescale) @test length(s_norescale) == length(x) @test length(s_rescale) == length(x) # If rescaling, the surrogate will have the same values as the original @test sort(x) ≈ sort(s_rescale) end @testset "PartialRandomization" begin Random.seed!(32) # Absolute randomization, Ortega pr = PartialRandomization(0.2) s = surrogate(x, pr) @test length(s) == length(x) @test_throws ArgumentError PartialRandomization(-0.01) @test_throws ArgumentError PartialRandomization(1.01) pr = PartialRandomization(0.0) s = surrogate(x, pr) @test s |> rfft .|> angle |> std |> ≈(0, atol=1e-5) end @testset "RelativePartialRandomization" begin Random.seed!(32) pr = RelativePartialRandomization(1.0) s = surrogate(x, pr) @test s |> rfft .|> angle |> std |> ≈(π/sqrt(3), atol=1e-1) # Relative randomization pr = RelativePartialRandomization(0.2) s = @test_nowarn surrogate(x, pr) @test length(s) == length(x) pr = RelativePartialRandomization(0.0) s = @test_nowarn surrogate(x, pr) @test s |> ≈(x, rtol=1e-2) # No randomization, so the surrogate should be close to the original pr = RelativePartialRandomization(1.0) s = surrogate(cos.(0:0.1:1000).^2, pr) @test s |> rfft .|> angle |> std |> ≈(π/sqrt(3), atol=1e-1) end @testset "SpectralPartialRandomization" begin Random.seed!(32) # Randomization based on the spectrum pr = SpectralPartialRandomization(0.2) s = @test_nowarn surrogate(x, pr) pr = SpectralPartialRandomization(0.0) s = @test_nowarn surrogate(x, pr) @test s |> ≈(x, rtol=1e-2) pr = SpectralPartialRandomization(1.0) s = surrogate(cos.(0:0.1:1000).^2, pr) @test s |> rfft .|> angle |> std |> ≈(π/sqrt(3), atol=1e-1) end @testset "PartialRandomizationAAFT" begin praaft = PartialRandomizationAAFT(0.5) s = surrogate(x, praaft) @test length(s) == length(x) @test sort(x) ≈ sort(s) @test_throws ArgumentError PartialRandomizationAAFT(-0.01) @test_throws ArgumentError PartialRandomizationAAFT(1.01) end @testset "RelativePartialRandomization" begin praaft = RelativePartialRandomizationAAFT(0.2) s = @test_nowarn surrogate(x, praaft) @test sort(x) ≈ sort(s) end @testset "SpectralPartialRandomization" begin praaft = SpectralPartialRandomizationAAFT(0.2) s = @test_nowarn surrogate(x, praaft) @test sort(x) ≈ sort(s) end @testset "RandomCascade" begin randomcascade = RandomCascade() s = surrogate(x, randomcascade) @test length(s) == length(x) @testset "Padding modes" begin x̃ = zeros(2^(TimeseriesSurrogates.ndyadicscales(length(x)) + 1)) TimeseriesSurrogates.pad!(x̃, x, "zeros") @test all(x̃[length(x)+1:end] .== 0.0) TimeseriesSurrogates.pad!(x̃, x, "constant") @test all(x̃[length(x)+1:end] .== x[end]) TimeseriesSurrogates.pad!(x̃, x, "linear") dx = x[end] - x[end-1] for i = length(x)+1:length(x̃) @test x̃[i] - x̃[i-1] ≈ dx end @test_throws ArgumentError surrogate(x, RandomCascade(; paddingmode="ones")) end end @testset "Periodic" begin pp = PseudoPeriodic(3, 25, 0.05) s = surrogate(x, pp) @test length(s) == length(ts) @test all(s[i] ∈ x for i in 1:N) # Perhaps a more advanced test, e.g. that both components have Fourier peak at # the same frequency, should be considered. #TODO: Test for noiseradius end @testset "PeriodicTwin" begin # A better test based on recurrence plots should be considered. d, τ = 2, 6 δ = 0.2 ρ = noiseradius(x, d, τ, 0.02:0.02:0.5) method = PseudoPeriodicTwin(d, τ, δ, ρ) sg = surrogenerator(x, method) s = sg()[:, 1] @test length(s) == length(ts) @test all(s[i] ∈ x for i in 1:N) end @testset "BlockShuffle" begin bs1 = BlockShuffle() bs2 = BlockShuffle(4) s1 = surrogate(x, bs1) s2 = surrogate(x, bs2) @test length(s1) == length(x) @test length(s2) == length(x) @test all([s1[i] ∈ x for i = 1:N]) @test all([s2[i] ∈ x for i = 1:N]) end @testset "RandomShuffle" begin rs = RandomShuffle() s = surrogate(x, rs) @test length(s) == length(x) @test all([s[i] ∈ x for i = 1:N]) end @testset "AutoRegressive" begin y = TimeseriesSurrogates.AR1(; n_steps = 2000, x₀ = 0.1, k = 0.5) sg = surrogenerator(y, AutoRegressive(1)) @test 0.4 ≤ abs(sg.init.φ[1]) ≤ 0.6 s = sg() @test length(s) == length(y) end @testset "AAFT" begin aaft = AAFT() s = surrogate(x, aaft) @test length(s) == length(x) @test all([s[i] ∈ x for i = 1:N]) end @testset "IAAFT" begin iaaft = IAAFT() s = surrogate(x, iaaft) @test length(s) == length(x) @test all([s[i] ∈ x for i = 1:N]) end @testset "TFTS" begin method_preserve_lofreq = TFTS(0.05) method_preserve_hifreq = TFTS(-0.05) s = surrogate(x, method_preserve_lofreq) @test length(s) == length(x) s = surrogate(x, method_preserve_hifreq) @test length(s) == length(x) @test_throws ArgumentError TFTS(0) end @testset "TFTDAAFT" begin tftdaaft = TFTDAAFT(0.03) s = surrogate(x, tftdaaft) @test length(s) == length(x) @test sort(x) ≈ sort(s) @test_throws ArgumentError TFTD(0) @test_throws ArgumentError TFTD(1.2) end @testset "TFTDIAAFT" begin tftdiaaft = TFTDAAFT(0.05) s = surrogate(x, tftdiaaft) @test length(s) == length(x) @test sort(x) ≈ sort(s) @test_throws ArgumentError TFTD(0) @test_throws ArgumentError TFTD(1.2) end @testset "TAAFT" begin method_preserve_lofreq = TAAFT(0.05) method_preserve_hifreq = TAAFT(-0.05) s = surrogate(x, method_preserve_lofreq) @test length(s) == length(x) @test all([s[i] ∈ x for i = 1:N]) s = surrogate(x, method_preserve_hifreq) @test length(s) == length(x) @test all([s[i] ∈ x for i = 1:N]) @test_throws ArgumentError TAAFT(0) end @testset "RandomFourier" begin @testset "random phases" begin phases = true rf = RandomFourier(phases) s = surrogate(x, rf) @test length(s) == length(x) # test that power spectrum is conserved psx = abs2.(rfft(x)) pss = abs2.(rfft(s)) # For some reason I don't understand the last element of the spectrum # is way off what is should be. @test all(isapprox.(psx[1:end-1], pss[1:end-1]; atol = 1e-8)) end @testset "random amplitudes" begin phases = false rf = RandomFourier(phases) s = surrogate(x, rf) @test length(s) == length(x) end end @testset "TFTDRandomFourier" begin @testset "random phases" begin phases = true rf = TFTDRandomFourier(phases) s = surrogate(x, rf) @test length(s) == length(x) end @testset "random amplitudes" begin phases = false rf = TFTDRandomFourier(phases) s = surrogate(x, rf) @test length(s) == length(x) end end @testset "Circ/Cycle shuffle" begin x = random_cycles() s = surrogate(x, CycleShuffle()) for a in s @test a ∈ x end s = surrogate(x, CircShift(1:length(x))) for a in s @test a ∈ x end end using DelayEmbeddings @testset "ShufleDims" begin X = StateSpaceSet(rand(100, 3)) Y = surrogate(X, ShuffleDimensions()) for i in 1:100 @test sort(X[i]) == sort(Y[i]) end end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
1608
using Random, Statistics N = 500 ts = cumsum(randn(N)) ts_nan = cumsum(randn(N)) ts_nan[1] = NaN x = cos.(range(0, 20π, length = N)) .+ randn(N)*0.05 xf = x .|> Float32 t = (0:N-1) + rand(N) all_conceivable_methods = [ PartialRandomization(0.3) PartialRandomization(0.8) WLS(rescale = false) WLS(AAFT(), rescale = true) WLS(rescale = false) WLS(CircShift(N), f = nothing) WLS(BlockShuffle(10), f = Statistics.cor) RandomCascade() PseudoPeriodic(3, 25, 0.05) BlockShuffle() BlockShuffle(4) RandomShuffle() AutoRegressive(1) AAFT() IAAFT() TFTS(0.05) TFTS(-0.05) TAAFT(0.05) TAAFT(-0.05) RandomFourier(true) RandomFourier(false) TFTD() TFTD(0.05) TFTDAAFT(0.03) TFTDIAAFT(0.03) CycleShuffle() IrregularLombScargle(t; tol = 10, n_total = 20000, n_acc = 5000) ] methodnames = [string(nameof(typeof(x))) for x in all_conceivable_methods] @testset "Reproducibility (rng)" begin @testset "$n" for (i, n) in enumerate(methodnames) method = all_conceivable_methods[i] rng = Random.MersenneTwister(1234) y = surrogate(x, method, rng) rng = Random.MersenneTwister(1234) z = surrogate(x, method, rng) @test y == z end end @testset "Float32 handling" begin @testset "$n" for (i, n) in enumerate(methodnames) method = all_conceivable_methods[i] rng = Random.MersenneTwister(1234) y = surrogate(xf, method, rng) rng = Random.MersenneTwister(1234) z = surrogate(xf, method, rng) @test y == z end end
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
123
using Test using TimeseriesSurrogates include("all_method_tests.jl") include("reproducibility.jl") include("test_test.jl")
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
560
using Test using TimeseriesSurrogates using Random using StatsBase: autocor n = 400 # timeseries length rng = Xoshiro(1234567) x = TimeseriesSurrogates.AR1(; n_steps = n, k = 0.25, rng) q(x) = sum(autocor(x, 0:10)) test = SurrogateTest(q, x, RandomFourier(); n = 1000, rng) # the AR1 process is much more correlated than its surrogates! p = pvalue(test) @test p > 0.9 p = pvalue(test; tail = :right) @test p < 0.1 test = SurrogateTest(q, x, RandomFourier(); n = 1000, rng) rval, vals = fill_surrogate_test!(test) @test minimum(vals) ≤ rval ≤ maximum(vals)
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
code
1655
L = 50 D = UncertainDataset([UncertainValue(Normal, rand(), rand()) for i = 1:L]) V = UncertainValueDataset([UncertainValue(Normal, rand(), rand()) for i = 1:L]) I = UncertainIndexDataset([UncertainValue(Normal, rand(), rand()) for i = 1:L]) @test randomshuffle(D) isa Vector{Float64} @test randomshuffle(V) isa Vector{Float64} @test randomshuffle(I) isa Vector{Float64} @test randomphases(D) isa Vector{Float64} @test randomphases(V) isa Vector{Float64} @test randomphases(I) isa Vector{Float64} @test randomamplitudes(D) isa Vector{Float64} @test randomamplitudes(V) isa Vector{Float64} @test randomamplitudes(I) isa Vector{Float64} @test aaft(D) isa Vector{Float64} @test aaft(V) isa Vector{Float64} @test aaft(I) isa Vector{Float64} @test iaaft(D) isa Vector{Float64} @test iaaft(V) isa Vector{Float64} @test iaaft(I) isa Vector{Float64} method_AAFT = AAFT() method_IAAFT = IAAFT() method_RandomShuffle = RandomShuffle() method_RandomFourier = RandomFourier() @test surrogate(D, method_AAFT) isa Vector{Float64} @test surrogate(D, method_IAAFT) isa Vector{Float64} @test surrogate(D, method_RandomShuffle) isa Vector{Float64} @test surrogate(D, method_RandomFourier) isa Vector{Float64} @test surrogate(V, method_AAFT) isa Vector{Float64} @test surrogate(V, method_IAAFT) isa Vector{Float64} @test surrogate(V, method_RandomShuffle) isa Vector{Float64} @test surrogate(V, method_RandomFourier) isa Vector{Float64} @test surrogate(I, method_AAFT) isa Vector{Float64} @test surrogate(I, method_IAAFT) isa Vector{Float64} @test surrogate(I, method_RandomShuffle) isa Vector{Float64} @test surrogate(I, method_RandomFourier) isa Vector{Float64}
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
2279
*Changelog is kept with respect to version 1.0. This software follows SymVer2.0* # 2.7 The function `fill_surrogate_test!` that was already in the source code and used by `pvalue` is now exported, so that if the users just want a parallelized estimation of surrogate discriminatory statistic they can just use this function. # 2.6 - Added surrogate methods: `RelativePartialRandomization`, `SpectralPartialRandomization`, `RelativePartialRandomizationAAFT`, and `SpectralPartialRandomizationAAFT`. # 2.5 - Moved to Julia extensions (requiring julia v1.9). # 2.4 - Calling `pvalue` with `SurrogateTest` is now parallelized over available threads. # 2.3 - `pvalue` is now correctly overloaded from StatsAPI.jl. # 2.2 - Implemented API for automating surrogate hypothesis tests using the new exported names `SurrogateTest` and `pvalue`. - New documentation section with an educative example of surrogate testing. # 2.1 - Added more padding modes to `RandomCascade` # 2.0 ## API changes - `SurrogateGenerator`s now have a field `s` into which surrogates are generated, avoiding unnecessary memory allocations. The - The wavelet (`WLS`) surrogate constructor now uses keywords arguments instead of positional arguments for some parameters. ## New features - New surrogate methods: `PartialRandomization`, `PartialRandomizationAAFT`, `TFTDAAFT`, `TFTDIAAFT`, and `RandomCascade`. - Using the `f` keyword, it is now possible to select whether circular shifting at each wavelet coefficient level should be performed for `WLS` surrogates. # 1.3 ## New features - The API now allows random number generator to be specified for all methods, enabling reproducibility - New surrogate methods: `PseudoPeriodicTwin`, `IrregularLombScargle` and `TFTDRandomFourier`. ## Bug fixes - Fixed error in `RandomFourier(true)` and `AAFT` surrogates, where phases were not correctly computed, leading to surrogates whose power spectra didn't match the power spectrum of the original signal as well as they should. No other Fourier-based surrogate were affected by this bug. # 1.2 - New surrogate methods: `AutoRegressive` # 1.1 - New surrogate methods: `CycleShuffle`, `ShuffleDimensions`, `CircShift`
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
2054
# TimeseriesSurrogates.jl [![docsdev](https://img.shields.io/badge/docs-dev-lightblue.svg)](https://juliadynamics.github.io/DynamicalSystemsDocs.jl/timeseriessurrogates/dev/) [![docsstable](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliadynamics.github.io/DynamicalSystemsDocs.jl/timeseriessurrogates/stable/) [![](https://img.shields.io/badge/DOI-10.21105/joss.04414-purple)](https://doi.org/10.21105/joss.04414) [![CI](https://github.com/JuliaDynamics/TimeseriesSurrogates.jl/workflows/CI/badge.svg)](https://github.com/JuliaDynamics/TimeseriesSurrogates.jl/actions?query=workflow%3ACI) [![codecov](https://codecov.io/gh/JuliaDynamics/TimeseriesSurrogates.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/JuliaDynamics/TimeseriesSurrogates.jl) [![Package Downloads](https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/TimeseriesSurrogates)](https://pkgs.genieframework.com?packages=TimeseriesSurrogates) A Julia package for generating timeseries surrogates. TimeseriesSurrogates.jl is the fastest and most featureful open source code for generating timeseries surrogates. It can be used as a standalone package, or as part of other projects in JuliaDynamics such as DynamicalSystems.jl or CausalityTools.jl. To install it, run `import Pkg; Pkg.add("TimeseriesSurrogates")`. All further information is provided in the documentation, which you can either find online or build locally by running the `docs/make.jl` file. ## Citing Please use the following BiBTeX entry, or DOI, to cite TimeseriesSurrogates.jl: DOI: https://doi.org/10.21105/joss.04414 BiBTeX: ```latex @article{TimeseriesSurrogates.jl, doi = {10.21105/joss.04414}, url = {https://doi.org/10.21105/joss.04414}, year = {2022}, publisher = {The Open Journal}, volume = {7}, number = {77}, pages = {4414}, author = {Kristian Agasøster Haaga and George Datseris}, title = {TimeseriesSurrogates.jl: a Julia package for generating surrogate data}, journal = {Journal of Open Source Software} } ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
422
--- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **Minimal Working Example** Please provide a piece of code that leads to the bug you encounter. If the code is **runnable**, it will help us identify the problem faster. **TimeseriesSurrogates.jl version** Please provide the version you use!
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
502
--- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered.
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
1936
# Contributing ## Reporting issues If you are having issues with the code, find bugs or otherwise want to report something about the package, please submit an issue at our [GitHub repository](https://github.com/JuliaDynamics/TimeseriesSurrogates.jl/issues). ## Feature requests If you have requests for a new method but can't implement it yourself, you can also report it as an [issue](https://github.com/JuliaDynamics/TimeseriesSurrogates.jl/issues). The package developers or other volunteers might be able to help with the implementation. Please mark method requests clearly as "Method request: my new method...", and provide a reference to a scientific publication that outlines the algorithm. ## Pull requests Pull requests for new surrogate methods are very welcome. Ideally, your implementation should use the same API as the existing methods: - Create a `struct` for your surrogate method, e.g. `struct MyNewSurrogateMethod <: Surrogate`, that contain the parameters for the method. The docstring for the method should contain a reference to scientific publications detailing the algorithm, as well as the intended purpose of the method, and potential implementation details that differ from the original algorithm. - Implement `surrogenerator(x, method::MyNewSurrogateMethod)`, where you pre-compute things for efficiency and return a `SurrogateGenerator` instance. - Implement the `SurrogateGenerator{<:MyNewSurrogateMethod}` functor that produces surrogate time series on demand. This is where the precomputed things are used, and the actual algorithm is implemented. - Then `surrogate(x, method::Surrogate)` will "just work". If you find this approach difficult and already have a basic implementation of a new surrogate method, the package maintainers may be able to help structuring the code. Let us know in an [issue](https://github.com/JuliaDynamics/TimeseriesSurrogates.jl/issues) or in a pull request!
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
3142
# TimeseriesSurrogates.jl ![](surroplot.png) `TimeseriesSurrogates` is a Julia package for generating surrogate timeseries. It is part of [JuliaDynamics](https://juliadynamics.github.io/JuliaDynamics/), a GitHub organization dedicated to creating high quality scientific software. If you are new to this method of surrogate timeseries, feel free to read the [Crash-course in timeseries surrogate testing](@ref) page. Please note that timeseries surrogates should not be confused with [surrogate models](https://en.wikipedia.org/wiki/Surrogate_model), such as those provided by [Surrogates.jl](https://github.com/SciML/Surrogates.jl). ## Installation TimeseriesSurrogates.jl is a registered Julia package. To install the latest version, run the following code: ```julia import Pkg; Pkg.add("TimeseriesSurrogates") ``` ## API TimeseriesSurrogates.jl API is composed by four names: [`surrogate`](@ref), [`surrogenerator`](@ref), [`SurrogateTest`](@ref), and [`pvalue`](@ref). They dispatch on the method to generate surrogates, which is a subtype of [`Surrogate`](@ref). It is recommended to standardize the signal before using these functions, i.e. subtract mean and divide by standard deviation. The function `standardize` does this. ### Generating surrogates ```@docs surrogate surrogenerator ``` ### Hypothesis testing ```@docs SurrogateTest fill_surrogate_test! pvalue(::SurrogateTest) ``` ## Surrogate methods ```@docs Surrogate ``` ```@index Order = [:type] ``` ### Shuffle-based ```@docs RandomShuffle BlockShuffle CycleShuffle CircShift ``` ### Fourier-based ```@docs RandomFourier TFTDRandomFourier PartialRandomization PartialRandomizationAAFT RelativePartialRandomization RelativePartialRandomizationAAFT SpectralPartialRandomization SpectralPartialRandomizationAAFT AAFT TAAFT IAAFT ``` ### Non-stationary ```@docs TFTS TFTD TFTDAAFT TFTDIAAFT ``` ### Pseudo-periodic ```@docs PseudoPeriodic PseudoPeriodicTwin ``` ### Wavelet-based ```@docs WLS RandomCascade ``` ### Other ```@docs AutoRegressive ShuffleDimensions IrregularLombScargle ``` ### Utilities ```@docs noiseradius ``` ## Visualization TimeseriesSurrogates.jl has defined a simple function `surroplot(x, s)`. This comes into scope when `using Makie` (you also need a plotting backend). This functionality requires you to be using Julia 1.9 or later versions. Example: ```@example MAIN using TimeseriesSurrogates using CairoMakie x = AR1() # create a realization of a random AR(1) process fig = surroplot(x, AAFT()) save("surroplot.png", fig); # hide ``` ## Citing Please use the following BiBTeX entry, or DOI, to cite TimeseriesSurrogates.jl: DOI: https://doi.org/10.21105/joss.04414 BiBTeX: ```latex @article{TimeseriesSurrogates.jl, doi = {10.21105/joss.04414}, url = {https://doi.org/10.21105/joss.04414}, year = {2022}, publisher = {The Open Journal}, volume = {7}, number = {77}, pages = {4414}, author = {Kristian Agasøster Haaga and George Datseris}, title = {TimeseriesSurrogates.jl: a Julia package for generating surrogate data}, journal = {Journal of Open Source Software} } ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
1592
# Surrogates for unevenly sampled time series To derive a surrogate for unevenly sampled time series, we can use surrogate methods which which does not explicitly use the time axis like [`RandomShuffle`](@ref) or [`BlockShuffle`](@ref), or we need to use algorithms that take the irregularity of the time axis into account. ## Lomb-Scargle based surrogate The [`IrregularLombScargle`](@ref) surrogate is a form of a constrained surrogate which takes the Lomb-Scargle periodogram, which works on irregularly spaced data, to derive surrogates with similar phase distribution as the original time series. This function uses the simulated annealing algorithm[^SchmitzSchreiber1999] to minimize the Minkowski distance between the original periodogram and the surrogate periodogram. ```@example MAIN using TimeseriesSurrogates, CairoMakie, Random # Example data: random AR1 process with a time axis with unevenly # spaced time steps rng = Random.MersenneTwister(1234) x = AR1(n_steps = 300) N = length(x) t = (1:N) - rand(N) # Use simulated annealing based on convergence of Lomb-Scargle periodograms # The time series is relatively long, so set tolerance a bit higher than default. ls = IrregularLombScargle(t, n_total = 100000, n_acc = 50000, tol = 5.0) s = surrogate(x, ls, rng) fig, ax = lines(t, x; label = "original") lines!(ax, t, s; label = "surrogate") axislegend(ax) fig ``` [^SchmitzSchreiber1999]: A.Schmitz T.Schreiber (1999). "Testing for nonlinearity in unevenly sampled time series" [Phys. Rev E](https://journaIrregularLombScargle.aps.org/pre/pdf/10.1103/PhysRevE.59.4044)
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
4692
# Surrogates for nonstationary time series Several of the methods provided by TimeseriesSurrogates.jl can be used to construct surrogates for nonstationary time series, which the following examples illustrate. ## Truncated Fourier surrogates ### [`TFTS`](@ref) By retaining the lowermost frequencies of the frequency spectrum, ([`TFTS`](@ref)) surrogates preserve long-term trends in the signals. ```@example using TimeseriesSurrogates n = 300; a = 0.7; A = 20; σ = 15 x = cumsum(randn(n)) .+ [(1 + a*i) .+ A*sin(2π/10*i) for i = 1:n] .+ [A^2*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2; # Preserve 5 % lowermost frequencies. surroplot(x, surrogate(x, TFTS(0.05))) ``` ### [`TAAFT`](@ref) Truncated AAFT surrogates ([`TAAFT`](@ref)) are similar to TFTS surrogates, but also rescales back to the original values of the signal, so that the original signal and the surrogates consists of the same values. This, however, may introduce some bias, as demonstrated below. ```@example using TimeseriesSurrogates # Example signal n = 300; a = 0.7; A = 20; σ = 15 x = cumsum(randn(n)) .+ [(1 + a*i) .+ A*sin(2π/10*i) for i = 1:n] .+ [A^2*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2; # Preserve 5% of the power spectrum corresponding to the lowest frequencies s_taaft_lo = surrogate(x, TAAFT(0.05)) surroplot(x, s_taaft_lo) ``` ```@example using TimeseriesSurrogates # Example signal n = 300; a = 0.7; A = 20; σ = 15 x = cumsum(randn(n)) .+ [(1 + a*i) .+ A*sin(2π/10*i) for i = 1:n] .+ [A^2*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2; # Preserve 20% of the power spectrum corresponding to the highest frequencies s_taaft_hi = surrogate(x, TAAFT(-0.2)) surroplot(x, s_taaft_hi) ``` ## Truncated FT surrogates with trend removal/addition One solution is to combine truncated Fourier surrogates with detrending/retrending. For time series with strong trends, Lucio et al. (2012)[^Lucio2012] proposes variants of the truncated Fourier-based surrogates wherein the trend is removed prior to surrogate generation, and then added to the surrogate again after it has been generated. This yields surrogates quite similar to those obtained when using truncated Fourier surrogates (e.g. [`TFTS`](@ref)), but reducing the effects of endpoint mismatch that affects regular truncated Fourier transform based surrogates. In principle, any trend could be removed/added to the signal. For now, the only option is to remove a best-fit linear trend obtained by ordinary least squares regression. ### [`TFTD`](@ref) The [`TFTD`](@ref) surrogate is a random Fourier surrogate where the lowest frequencies are preserved during surrogate generation, and a linear trend is removed during preprosessing and added again after the surrogate has been generated. The [`TFTD`](@ref) surrogates do a decent job at preserving long term trends. ```@example using TimeseriesSurrogates # Example signal n = 300; a = 0.7; A = 20; σ = 15 x = cumsum(randn(n)) .+ [(1 + a*i) .+ A*sin(2π/10*i) for i = 1:n] .+ [A^2*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2; s = surrogate(x, TFTDRandomFourier(true, 0.02)) surroplot(x, s) ``` [^Lucio2012]: Lucio, J. H., Valdés, R., & Rodríguez, L. R. (2012). Improvements to surrogate data methods for nonstationary time series. Physical Review E, 85(5), 056202. ### [`TFTDAAFT`](@ref) The detrend-retrend extension of [`TAAFT`](@ref) is the [`TFTDAAFT`](@ref) method. The [`TFTDAAFT`](@ref) method adds a rescaling step to the [`TFTD`](@ref) method, ensuring that the surrogate and the original time series consist of the same values. Long-term trends in the data are also decently preserved by [`TFTDAAFT`](@ref), but like [`TFTDAAFT`](@ref), there is some bias. ```@example using TimeseriesSurrogates # Example signal n = 300; a = 0.7; A = 20; σ = 15 x = cumsum(randn(n)) .+ [(1 + a*i) .+ A*sin(2π/10*i) for i = 1:n] .+ [A^2*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2; # Keep 2 % of lowermost frequencies. s = surrogate(x, TFTDAAFT(0.02)) surroplot(x, s) ``` ### [`TFTDIAAFT`](@ref) [`TFTDIAAFT`](@ref)[^Lucio2012] surrogates are similar to [`TFTDAAFT`](@ref) surrogates, but the [`TFTDIAAFT`](@ref)[^Lucio2012] method also uses an iterative process to better match the power spectra of the original signal and the surrogate (analogous to how the [`IAAFT`](@ref) method improves upon the [`AAFT`](@ref) method). ```@example using TimeseriesSurrogates # Example signal n = 300; a = 0.7; A = 20; σ = 15 x = cumsum(randn(n)) .+ [(1 + a*i) .+ A*sin(2π/10*i) for i = 1:n] .+ [A^2*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2; # Keep 5% of lowermost frequences s = surrogate(x, TFTDIAAFT(0.05)) surroplot(x, s) ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
73
# Utility systems ```@docs SNLST randomwalk NSAR2 AR1 random_cycles ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
4621
# Crash-course in timeseries surrogate testing !!! note The summary here follows Sect. 7.4 from [Nonlinear Dynamics](https://link.springer.com/book/10.1007/978-3-030-91032-7) by Datseris and Parlitz. ## What is a surrogate timeseries? A surrogate of a timeseries `x` is another timeseries `s` of equal length to `x`. This surrogate `s` is generated from `x` so that it roughly preserves one or many pre-defined properties of `x`, but is otherwise randomized. The upper panel in the figure below shows an example of a timeseries and one surrogate realization that preserves its both power spectrum and its amplitude distribution (histogram). Because of this preservation, the time series look similar. ```@example MAIN using TimeseriesSurrogates, CairoMakie x = LinRange(0, 20π, 300) .+ 0.05 .* rand(300) ts = sin.(x./rand(20:30, 300) + cos.(x)) s = surrogate(ts, IAAFT()) surroplot(ts, s) ``` ## Performing surrogate hypothesis tests A surrogate test is a statistical test of whether a given timeseries satisfies or not a given hypothesis regarding its properties or origin. For example, the first surrogate methods were created to test the hypothesis, whether a given timeseries `x` that appears noisy may be the result of a linear stochastic process or not. If not, it may be a nonlinear process contaminated with observational noise. For the suitable hypothesis to test for, see the documentation strings of provided `Surrogate` methods or, even better, the review from Lancaster et al. (2018)[^Lancaster2018]. To perform such a surrogate test, you need to: 1. Decide what hypothesis to test against 2. Pick a surrogate generating `method` that satisfies the chosen hypothesis 3. Pick a suitable discriminatory statistic `q` with `q(x) ∈ Real`. It must be a statistic that would obtain sufficiently different values for timeseries satisfying, or not, the chosen hypothesis. 4. Compute `q(s)` for thousands of surrogate realizations `s = surrogate(x, method)` 5. Compare `q(x)` with the distribution of `q(s)`. If `q(x)` is significantly outside the e.g., 5-95 confidence interval of the distribution, the hypothesis is rejected. This whole process is automated by [`SurrogateTest`](@ref), see the example below. [^Lancaster2018]: Lancaster, G., Iatsenko, D., Pidde, A., Ticcinelli, V., & Stefanovska, A. (2018). Surrogate data for hypothesis testing of physical systems. Physics Reports, 748, 1–60. doi:10.1016/j.physrep.2018.06.001 ## An educative example Let's put everything together now to showcase how one would use this package to e.g., distinguish deterministic chaos contaminated with noise from actual stochastic timeseries, using the permutation entropy as a discriminatory statistic. First, let's visualize the timeseries ```@example MAIN using TimeseriesSurrogates # for surrogate tests using DynamicalSystemsBase # to simulate logistic map using ComplexityMeasures # to compute permutation entropy using Random: Xoshiro # for reproducibility using CairoMakie # for plotting # AR1 n = 400 # timeseries length rng = Xoshiro(1234567) x = TimeseriesSurrogates.AR1(; n_steps = n, k = 0.25, rng) # Logistic logistic_rule(x, p, n) = @inbounds SVector(p[1]*x[1]*(1 - x[1])) ds = DeterministicIteratedMap(logistic_rule, [0.4], [4.0]) Y, t = trajectory(ds, n-1) y = standardize(Y[:, 1]) .+ 0.5randn(rng, n) # 50% observational noise # Plot fig, ax1 = lines(y) ax2, = lines(fig[2,1], x, color = Cycled(2)) ax1.title = "deterministic + 50%noise" ax2.title = "stochastic AR1" fig ``` Then, let's compute surrogate distributions for both timeseries using the permutation entropy as the discriminatory statistic and [`RandomFourier`](@ref) as the surrogate generation method ```@example MAIN perment(x) = entropy_normalized(SymbolicPermutation(; m = 3), x) method = RandomFourier() fig = Figure() axs = [Axis(fig[1, i]) for i in 1:2] Nsurr = 1000 for (i, z) in enumerate((y, x)) sgen = surrogenerator(z, method) qx = perment(z) qs = map(perment, (sgen() for _ in 1:Nsurr)) hist!(axs[i], qs; label = "pdf of q(s)", color = Cycled(i)) vlines!(axs[i], qx; linewidth = 5, label = "q(x)", color = Cycled(3)) axislegend(axs[i]) end fig ``` we clearly see that the discriminatory value for the deterministic signal is so far out of the distribution that the null hypothesis that the timeseries is stochastic can be discarded with ease. This whole process can be easily automated with [`SurrogateTest`](@ref) as follows: ```@example MAIN test = SurrogateTest(perment, y, method; n = 1000, rng) p = pvalue(test) p < 0.001 # 99.9-th quantile confidence ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
5967
# Fourier-based Fourier based surrogates are a form of constrained surrogates created by taking the Fourier transform of a time series, then shuffling either the phase angles or the amplitudes of the resulting complex numbers. Then, we take the inverse Fourier transform, yielding a surrogate time series. ## Random phase ```@example MAIN using TimeseriesSurrogates, CairoMakie ts = AR1() # create a realization of a random AR(1) process phases = true s = surrogate(ts, RandomFourier(phases)) surroplot(ts, s) ``` ## Random amplitude ```@example MAIN using TimeseriesSurrogates, CairoMakie ts = AR1() # create a realization of a random AR(1) process phases = false s = surrogate(ts, RandomFourier(phases)) surroplot(ts, s) ``` ## Partial randomization ### Without rescaling [`PartialRandomization`](@ref) surrogates are similar to random phase surrogates, but allow for tuning the "degree" of phase randomization. [`PartialRandomization`](@ref) use an algorithm introduced by Ortega et al., which draws random phases as: $$\phi \to \alpha \xi , \quad \xi \sim \mathcal{U}(0, 2\pi),$$ where $\phi$ is a Fourier phase and $\mathcal{U}(0, 2\pi)$ is a uniform distribution. Tuning the randomization parameter, $\alpha$, produces a set of time series with varying degrees of randomness in their Fourier phases. ```@example MAIN using TimeseriesSurrogates, CairoMakie ts = AR1() # create a realization of a random AR(1) process # 50 % randomization of the phases s = surrogate(ts, PartialRandomization(0.5)) surroplot(ts, s) ``` In addition to [`PartialRandomization`](@ref), we provide two other algorithms for producing partially randomized surrogates, outlined below. ### Relative partial randomization The [`PartialRandomization`](@ref) algorithm corresponds to assigning entirely new phases to the Fourier spectrum with some degree of randomness, regardless of any deterministic structure in the original phases. As such, even for $\alpha = 0$ the surrogate time series can differ drastically from the original time series. By contrast, the [`RelativePartialRandomization`](@ref) procedure draws phases as: $$\phi \to \phi + \alpha \xi, \quad \xi \sim \mathcal{U}(0, 2\pi).$$ With this algorithm, phases are progressively corrupted by higher values of $\alpha$: surrogates are identical to the original time series for $\alpha = 0$, equivalent to random noise for $\alpha = 1$, and retain some of the structure of the original time series when $0 < \alpha < 1$. This procedure is particularly useful for controlling the degree of chaoticity and non-linearity in surrogates of chaotic systems. ### Spectral partial randomization Both of the algorithms above randomize phases at all frequency components to the same degree. To assess the contribution of different frequency components to the structure of a time series, the [`SpectralPartialRandomization`](@ref) algorithm only randomizes phases above a frequency threshold. The threshold is chosen as the lowest frequency at which the power spectrum of the original time series drops below a fraction $1-\alpha$ of its maximum value (such that the power contained above the frequency threshold is a proportion $\alpha$ of the total power, excluding the zero frequency). See the figure below for a comparison of the three partial randomization algorithms: ```@example MAIN using DynamicalSystemsBase # hide function surrocompare(x, surr_types, params; color = ("#7143E0", 0.9), N=1000, linewidth=3, # hide transient=0, kwargs...) # hide fig = Makie.Figure(resolution = (1080, 480), fontsize=22, kwargs...) # hide for (j, a) in enumerate(surr_types) # hide for (i, p) in enumerate(params) # hide ax = Makie.Axis(fig[i,j]) # hide hidedecorations!(ax) # hide ax.ylabelvisible = true # hide lines!(ax, surrogate(x, a(p...))[transient+1:transient+N]; color, linewidth) # hide j == 1 && (ax.ylabel = "α = $(p)"; ax.ylabelfont = :bold) # hide i == 1 && (ax.title = string(a)) # hide end # hide end # hide colgap!(fig.layout, 30) # hide rowgap!(fig.layout, 30) # hide return fig # hide end # hide @inbounds function lorenz_rule!(du, u, p, t) # hide σ = p[1]; ρ = p[2]; β = p[3] # hide du[1] = σ*(u[2]-u[1]) # hide du[2] = u[1]*(ρ-u[3]) - u[2] # hide du[3] = u[1]*u[2] - β*u[3] # hide return nothing # hide end # hide u0 = [0, 10.0, 0] # hide p0 = [10, 28, 8/3] # hide diffeq = (; abstol = 1e-9, reltol = 1e-9) # hide lorenz = CoupledODEs(lorenz_rule!, u0, p0; diffeq) # hide x = trajectory(lorenz, 1000; Ttr=500, Δt=0.025)[1][:, 1] # hide surr_types = [PartialRandomization, RelativePartialRandomization, SpectralPartialRandomization] # hide params = [0.0, 0.1, 0.25] # hide surrocompare(x, surr_types, params; transient=1000) # hide ``` ### With rescaling [`PartialRandomizationAAFT`](@ref) adds a rescaling step to the [`PartialRandomization`](@ref) surrogates to obtain surrogates that contain the same values as the original time series. AAFT versions of [`RelativePartialRandomization`](@ref) and [`SpectralPartialRandomization`](@ref) are also available. ```@example MAIN using TimeseriesSurrogates, CairoMakie ts = AR1() # create a realization of a random AR(1) process # 50 % randomization of the phases s = surrogate(ts, PartialRandomizationAAFT(0.7)) surroplot(ts, s) ``` ## Amplitude adjusted Fourier transform (AAFT) ```@example MAIN using TimeseriesSurrogates, CairoMakie ts = AR1() # create a realization of a random AR(1) process s = surrogate(ts, AAFT()) surroplot(ts, s) ``` ## Iterative AAFT (IAAFT) The IAAFT surrogates add an iterative step to the AAFT algorithm to improve similarity of the power spectra of the original time series and the surrogates. ```@example MAIN using TimeseriesSurrogates, CairoMakie ts = AR1() # create a realization of a random AR(1) process s = surrogate(ts, IAAFT()) surroplot(ts, s) ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
1275
# Multidimensional surrogates Multidimensional surrogates operate typically on input `StateSpaceSet`s and output the same type. ## Shuffle dimensions This surrogate was made to distinguish multidimensional data with *structure in the state space* from multidimensional noise. Here is a simple application that shows that the distinction is successful for a system that we know a-priori is deterministic and has structure in the state space (a chaotic attractor). ```@example MAIN using TimeseriesSurrogates using DynamicalSystemsBase using FractalDimensions: correlationsum using CairoMakie # Create a trajectory from the towel map function towel_rule(x, p, n) @inbounds x1, x2, x3 = x[1], x[2], x[3] SVector( 3.8*x1*(1-x1) - 0.05*(x2+0.35)*(1-2*x3), 0.1*( (x2+0.35)*(1-2*x3) - 1 )*(1 - 1.9*x1), 3.78*x3*(1-x3)+0.2*x2 ) end to = DeterministicIteratedMap(towel_rule, [0.1, -0.1, 0.1]) X = trajectory(to, 10_000; Ttr = 100)[1] e = 10.0 .^ range(-1, 0; length = 10) CX = correlationsum(X, e; w = 5) le = log10.(e) fig, ax = lines(le, log10.(CX)) sg = surrogenerator(X, ShuffleDimensions()) for i in 1:10 Z = sg() CZ = correlationsum(Z, e) lines!(ax, le, log.(CZ); color = ("black", 0.8)) end ax.xlabel = "log(e)"; ax.ylabel = "log(C)" fig ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
341
# Pseudo-periodic ```@example MAIN using TimeseriesSurrogates t = 0:0.05:20π x = @. 4 + 7cos(t) + 2cos(2t + 5π/4) x .+= randn(length(x))*0.2 # Optimal d, τ values deduced using DelayEmbeddings.jl d, τ = 3, 31 # For ρ you can use `noiseradius` ρ = 0.11 method = PseudoPeriodic(d, τ, ρ, false) s = surrogate(x, method) surroplot(x, s) ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
1173
# Pseudo-periodic twin surrogates ```@example MAIN using TimeseriesSurrogates, CairoMakie # Example system from the original paper n, Δt = 500, 0.05 f₁, f₂ = sqrt(3), sqrt(5) x = [8*sin(2π*f₁*t) + 4*sin(2π*f₂*t) for t = 0:Δt:Δt*n] # Embedding parameter, neighbor threshold and noise radius d, τ = 2, 6 δ = 0.15 ρ = noiseradius(x, d, τ, 0.02:0.02:0.5) method = PseudoPeriodicTwin(d, τ, δ, ρ) # Generate the surrogate, which is a `d`-dimensional dataset. surr_orbit = surrogate(x, method) # Get scalar surrogate time series from first and second column. s1, s2 = surr_orbit[:, 1], surr_orbit[:, 2] # Scalar time series versus surrogate time series fig = Figure() ax_ts = Axis(fig[1,1:2]; xlabel = "time", ylabel = "value") lines!(ax_ts, s1; color = :red) lines!(ax_ts, x; color = :black) # Embedding versus surrogate embedding X = embed(x, d, τ) ax2 = Axis(fig[2, 1]; xlabel = "x(t)", ylabel = "x(t-$τ)") lines!(ax2, X[:, 1], X[:, 2]; color = :black) scatter!(ax2, X[:, 1], X[:, 2]; color = :black, markersize = 4) ps = Axis(fig[2,2]; xlabel= "s(t)", ylabel = "s(t-$τ)") lines!(ps, s1, s2; color = :red) scatter!(ps, s1, s2; color = :black, markersize = 4) fig ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
1227
# Shuffle-based ## Random shuffle (RS) Randomly shuffled surrogates are simply permutations of the original time series. Thus, they break any correlations in the signal. ```@example MAIN using TimeseriesSurrogates, CairoMakie x = AR1() # create a realization of a random AR(1) process s = surrogate(x, RandomShuffle()) surroplot(x, s) ``` ## Block shuffle (BS) Randomly shuffled surrogates are generated by dividing the original signal into blocks, then permuting those blocks. Block positions are randomized, and blocks at the end of the signal gets wrapped around to the start of the time series. Thus, they keep short-term correlations within blocks, but destroy any long-term dynamical information in the signal. ```@example MAIN using TimeseriesSurrogates, CairoMakie x = NSAR2(n_steps = 300) # We want to divide the signal into 8 blocks. s = surrogate(x, BlockShuffle(8)) p = surroplot(x, s) ``` ## Cycle shuffle (CSS) ```@example MAIN using TimeseriesSurrogates, CairoMakie x = random_cycles() s = surrogate(x, CycleShuffle()) p = surroplot(x, s) ``` ## Circular shift ```@example MAIN using TimeseriesSurrogates, CairoMakie x = random_cycles() s = surrogate(x, CircShift(1:length(x))) p = surroplot(x, s) ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
4386
# Wavelet surrogates ## `WLS` [`WLS`](@ref) surrogates are constructed by taking the maximal overlap discrete wavelet transform (MODWT) of the signal, shuffling detail coefficients across dyadic scales, then inverting the transform to obtain the surrogate. ### Wavelet-IAAFT (WIAAFT) surrogates In [Keylock (2006)](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.73.036707), IAAFT shuffling is used, yielding surrogates that preserve the local mean and variance of the original signal, but randomizes nonlinear properties of the signal. This also preserves nonstationarities in the signal. To construct WIAAFT surrogates, rescaling must be enabled. *Note: the final iterative procedure of the WIAAFT surrogate method, after the rescaling step, is not performed in our current implementation, so surrogates might differ a bit from results in Keylock (2006). For now, you have to do the iterative rescaling manually if desired.*. ```@example MAIN using TimeseriesSurrogates, Random Random.seed!(5040) n = 500 σ = 30 x = cumsum(randn(n)) .+ [20*sin(2π/30*i) for i = 1:n] .+ [20*cos(2π/90*i) for i = 1:n] .+ [50*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2 .+ [0.5*t for t = 1:n]; # Rescale surrogate back to original values method = WLS(IAAFT(), rescale = true) s = surrogate(x, method); p = surroplot(x, s) ``` Even without rescaling, IAAFT shuffling also yields surrogates with local properties very similar to the original signal. ```@example MAIN using TimeseriesSurrogates, Random Random.seed!(5040) n = 500 σ = 30 x = cumsum(randn(n)) .+ [20*sin(2π/30*i) for i = 1:n] .+ [20*cos(2π/90*i) for i = 1:n] .+ [50*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2 .+ [0.5*t for t = 1:n]; # Don't rescale back to original time series. method = WLS(IAAFT(), rescale = false) s = surrogate(x, method); p = surroplot(x, s) ``` ### Other shuffling methods The choice of coefficient shuffling method determines how well and which properties of the original signal are retained by the surrogates. There might be use cases where surrogates do not need to perfectly preserve the autocorrelation of the original signal, so additional shuffling methods are provided for convenience. Using random shuffling of the detail coefficients does not preserve the autocorrelation structure of the original signal. ```@example MAIN using TimeseriesSurrogates, Random Random.seed!(5040) n = 500 σ = 30 x = cumsum(randn(n)) .+ [20*sin(2π/30*i) for i = 1:n] .+ [20*cos(2π/90*i) for i = 1:n] .+ [50*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2 .+ [0.5*t for t = 1:n]; method = WLS(RandomShuffle(), rescale = false) s = surrogate(x, method); p = surroplot(x, s) ``` Block shuffling the detail coefficients better preserve local properties because the shuffling is not completely random, but still does not preserve the autocorrelation of the original signal. ```@example MAIN using TimeseriesSurrogates, Random Random.seed!(5040) n = 500 σ = 30 x = cumsum(randn(n)) .+ [20*sin(2π/30*i) for i = 1:n] .+ [20*cos(2π/90*i) for i = 1:n] .+ [50*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2 .+ [0.5*t for t = 1:n]; s = surrogate(x, WLS(BlockShuffle(10), rescale = false)); p = surroplot(x, s) ``` Random Fourier phase shuffling the detail coefficients does a decent job at preserving the autocorrelation. ```@example MAIN using TimeseriesSurrogates, Random Random.seed!(5040) n = 500 σ = 30 x = cumsum(randn(n)) .+ [20*sin(2π/30*i) for i = 1:n] .+ [20*cos(2π/90*i) for i = 1:n] .+ [50*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2 .+ [0.5*t for t = 1:n]; s = surrogate(x, WLS(RandomFourier(), rescale = false)); surroplot(x, s) ``` To generate surrogates that preserve linear properties of the original signal, AAFT or IAAFT shuffling is required. ## `RandomCascade` [`RandomCascade`](@ref) surrogates is another wavelet-based method that uses the regular discrete wavelet transform to generate surrogates. ```@example MAIN using TimeseriesSurrogates, Random Random.seed!(5040) n = 500 σ = 30 x = cumsum(randn(n)) .+ [20*sin(2π/30*i) for i = 1:n] .+ [20*cos(2π/90*i) for i = 1:n] .+ [50*sin(2π/2*i + π) for i = 1:n] .+ σ .* rand(n).^2 .+ [0.2*t for t = 1:n]; s = surrogate(x, RandomCascade()); surroplot(x, s) ```
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
9239
--- title: 'TimeseriesSurrogates.jl: a Julia package for generating surrogate data' tags: - Julia - surrogate data - time series - nonlinear time series analysis - hypothesis testing authors: - name: Kristian Agasøster Haaga orcid: 0000-0001-6880-8725 affiliation: "1, 2, 3" - name: George Datseris orcid: 0000-0002-6427-2385 affiliation: "4" affiliations: - name: Department of Earth Science, University of Bergen, Bergen, Norway index: 1 - name: K. G. Jebsen Centre for Deep Sea Research, Bergen, Norway index: 2 - name: Bjerknes Centre for Climate Research, Bergen, Norway index: 3 - name: Max Planck Institute for Meteorology, Hamburg, Germany index: 4 date: 9 March 2020 bibliography: paper.bib --- # Introduction The method of surrogate data is a way to generate data that preserve one or more statistical or dynamical properties of a given timeseries, but are otherwise randomized. Surrogate time series methods have widespread use in null hypothesis testing in nonlinear dynamics, for null hypothesis testing in causal inference, or for the more general case of producing synthetic data with similar statistical properties as an original signal. Originally introduced by @Theiler:1992 to test for nonlinearity in time series, numerous surrogate methods aimed preserving different properties of the original signal have since emerged; for a review, see @Lancaster:2018. A simple example of an application of surrogates would be to distinguish whether a given timeseries `x` can be represented via a linear noise process, or not. The latter case can be an indication that the timeseries may represent deterministic nonlinear dynamics with additional noise. A simple way to test for this hypothesis would be to generate new timeseries from `x` that conserve the power spectrum of `x` (which is a defining feature of linear stochastic processes). Then, a discriminatory statistic, such as the correlation dimension or the auto-mutual-information [@Lancaster:2018] is computed for `x`, but also for thousands of surrogates from `x`. The discriminatory statistic of the surrogates provides a distribution of possible values, and if the value for `x` is well within the distribution spread, then `x` satisfies the null hypothesis (here, that `x` can be approximated as a linear stochastic process). # Statement of need Surrogate data has been used in several thousand publications so far (the citation number of @Theiler:1992 is more than 4,000) and hence the community is in clear need of such methods. Existing software packages for surrogate generation provide much fewer methods than available in the literature, with less-than optimal performance (see Comparison section below), and without allowing reproducible generation of surrogates. TimeseriesSurrogates.jl provides more than double the amount of methods given by other packages, with runtimes similar to and up to an order of magnitude faster than existing surrogate packages in other languages. Equally importantly, TimeseriesSurrogates.jl provides a framework that is tested via continuous integration, and is easy to extend via open source contributions. # Available surrogate methods | Method | Description | Reference | |---|---|---| | `AutoRegressive` | Autoregressive model based surrogates. | | | `RandomShuffling` | Random shuffling of individual data points. | @Theiler:1992 | | `BlockShuffle` | Random shuffling of blocks of data points. | @Theiler:1992 | | `CircShift` | Circularly shift the signal. | | | `RandomFourier` | Randomization of phases of Fourier transform of the signal. | @Theiler:1992 | | `PartialRandomization` | Fourier randomization, but tuning of the "degree" of randomization.| @Ortega:1998 | | `PartialRandomizationAAFT` | Partial Fourier randomization, but rescaling back to original values. | This paper. | | `CycleShuffle` | Randomization of phases of Fourier transform of the signal. | @Theiler:1994 | | `ShuffleDimensions` | Circularly shift the signal. | This paper. | | `AAFT` | Amplitude adjusted `RandomFourier`. | @Theiler:1992 | | `IAAFT` | Iterative amplitude adjusted `RandomFourier`. | @SchreiberSchmitz:1996 | | `TFTS` | Truncated Fourier transform surrogates. | @Miralles2015 | | `TAAFT` | Truncated AAFT surrogates. | @Nakamura:2006 | | `TFTDRandomFourier` | Detrended and retrended truncated Fourier surrogates. | @Lucio:2012 | | `TFTDAAFT` | Detrended and retrended truncated AAFT surrogates. | @Lucio:2012 | | `TFTDIAAFT` | Detrended and retrended truncated AAFT surrogates with iterative adjustment. | @Lucio:2012 | | `WLS` | Flexible wavelet-based methods using maximal overlap discrete wavelet transforms. | @Keylock:2006 | | `RandomCascade` | Random cascade multifractal surrogates. | @Palus:2008 | | `WIAAFT` | Wavelet-based iterative amplitude adjusted transforms. | @Keylock:2006 | | `PseudoPeriodic` | Randomization of phases of Fourier transform of the signal. | @Small:2001 | | `PseudoPeriodicTwin` | Combination of pseudoperiodic and twin surrogates. | @Miralles2015 | | `LS` | Lomb-Scargle periodogram based surrogates for irregular time grids | @Schmitz:1999 Documentation strings for the various methods describe the usage intended by the original authors of the methods. Example applications are showcased in the [package documentation](https://juliadynamics.github.io/TimeseriesSurrogates.jl/dev/). # Design of TimeseriesSurrogates.jl TimeseriesSurrogates.jl has been designed to be as performant as possible and as simple to extend as possible. At a first level, we offer a function ```julia using TimeseriesSurrogates, Random method = RandomShuffle() # can be any valid method rng = MersenneTwister(1234) # optional random number generator s = surrogate(x, method, rng) ``` which creates a surrogate `s` based on the input `x` and the given method (any of the methods mentioned in the above table). This interface is easily extendable because it uses Julia's multiple dispatch on the given `method`. Thus, any new contribution of a new method uses the exact same interface, but introduces a new method type, e.g. ```julia m = NewContributedMethod(args...) s = surrogate(x, method, rng) ``` The function `surrogate` is straight-forward to use, but it does not allow maximum performance. The reason for this is that when trying to make a second surrogate from `x` and the same method, there are many structures and computations that could be pre-initialized and/or reused for all surrogates. This is especially relevant for real-world applications where one typically makes thousands of surrogates with a given method. To address this, we provide a second level of interface, the `surrogenerator` function. It works as follows: first the user initializes a "surrogate generator" structure: ```julia method = RandomShuffle() sg = surrogenerator(x, method, rng) ``` The structure `sg` can generate surrogates of `x` on demand in the most performant manner possible for the given inputs `x, method`. It can be used like so: ```julia for i in 1:100 s = sg() # generate a surrogate # code... end ``` # Comparison The average time to generate surrogates in TimeseriesSurrogates.jl is in the best case about an order of magnitude faster than, and in the worst case roughly equivalent to, the MATLAB surrogate code provided by @Lancaster:2018, though comparisons are not exact, due to differing implementations and tuning options. Moreover, the code of @Lancaster:2018 is not an actual package, but rather scripts that have been written and circulated. As such, they lack a test suite tested via continuous integration. Timings for commonly used surrogate methods that are common to both libraries are shown in Figure 1. Additionally, because TimeseriesSurrogates.jl provides many more methods not implemented in other packages, a comprehensive comparison of runtimes is not possible, but due to our optimized surrogate generators, we expect good performance relative to future implementations in other languages. ![Figure 1: Mean time (in seconds, based on 500 surrogate time series realizations) to generate a 2000-point random permutation (rp), Fourier transform (ft), amplitude-adjusted Fourier transform (aaft), iterated aaft (iaaft) and pseudoperiodic (pps) surrogate using a pre-initialized generators with default parameters, and using a maximum of 100 iterations for the IAAFT algorithm. MATLAB timings are generated using the code provided by @Lancaster:2018. Note: timings for the pseudoperiodic surrogates in MATLAB include embedding lag and dimension finding, which has been included in the preprocessing step in the Julia version. Scripts to reproduce Julia and MATLAB timings are available in the GitHub repo for this paper. ](figs/timings.png) # Acknowledgements KAH acknowledges funding by the Trond Mohn Foundation (previously Bergen Research Foundation) (Bergen, Norway) and a fast-track initiative grant from Bjerknes Centre for Climate Research (Bergen, Norway). GD acknowledges continuous support from Bjorn Stevens and the Max Planck Society. We thank Felix Cremer for the initial pull-request for the simulated annealing based (Lomb-Scargle) surrogate method. # References
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
2.7.2
dbba9d7e04a28e3945f9194a6577bf816b34ed70
docs
679
# Instructions ## 1. Run the `timings.m` script in MATLAB This will: - Generate a test time series. - Benchmark the Lancaster et al.'s code on that time series using five different surrogate methods that also exist in TimeseriesSurrogates.jl. - Export the results as `timeseries.csv` and `matlab_timings.csv`. ## 2. Run the `timings.jl` script in Julia This will: - Import the `timeseries.csv` file generated in step 1. - Benchmark TimeseriesSurrogates.jl on that time series, using the same surrogate methods as for the MATLAB run. - Generate a bar plot that compares the timings. - Export the bar plots as a .png file in the "TimeseriesSurrogates.jl/paper/figs/" folder.
TimeseriesSurrogates
https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git
[ "MIT" ]
0.1.1
98fea05b931563024ba7559a3d9e3cc498cf814a
code
363
using Documenter using SQLDataFrameTools using Dates using Documenter, SQLDataFrameTools makedocs( modules = [SQLDataFrameTools], sitename="SQLDataFrameTools.jl", authors = "Matt Lawless", format = Documenter.HTML(), ) deploydocs( repo = "github.com/lawless-m/SQLDataFrameTools.jl.git", devbranch = "main", push_preview = true, )
SQLDataFrameTools
https://github.com/lawless-m/SQLDataFrameTools.jl.git
[ "MIT" ]
0.1.1
98fea05b931563024ba7559a3d9e3cc498cf814a
code
5836
module SQLDataFrameTools using DataFrameTools using SHA using DBInterface using Dates using DataFrames using Distributed export QueryCache, df_cached, select_fn, expired, fetch_and_combine, Dfetch_and_combine """ QueryCache(sql, select, dir, format; subformat=nothing, dictencode=true) is the Data Structure used in this module. # Arguments - `sql` is the SQL Query - `select` is the function used to retrieve the dataset (which can be created with [`select_fn`](@ref)) - `dir` is the directory in which to store the cache file - `format` is one of the file formats supported. See DataFrameTools.df_formats() for the list. - `subformat` and `dictencode` are optional parameters for DataFrameTools.df_write # Examples query = QueryCache("SELECT 1", select_fn(MySQL.Connection, SERVER, USER, PASSWORD), ".", :jdf) """ struct QueryCache sql select cachepath subformat::Union{Nothing,Symbol} dictencode::Bool QueryCache(sql, select, dir, format; subformat=nothing, dictencode=true) = new(sql, select, cachepath(dir, bytes2hex(sha256(sql)), format), subformat, dictencode) end cachepath(dir, hash, sformat) = joinpath(dir, hash * '.' * string(sformat)) """ expired(q::QueryCache, expires::Dates.DateTime) expired(q::QueryCache, ttl::Dates.Period) Has the cache file expired? If the file doesn't exist always return true, otherwise check the mtime against the given time. # Arguments - `q` a QueryCache struct - `expires` a DateTime to check against the current time. - `ttl` a time period to compare the current time to the mtime of the cache + ttl # Examples expired(query, Dates.Day(3)) # returns a bool of whether the cache is more than 3 days old expired(query, Dates.Minute(30)) # returns a bool of whether the cache is more than 30 minutes old expired(query, Dates.DateTime(2021, 1, 1, 1, 2, 3)) # returns a bool compared to the given time """ expired(q::QueryCache, expires::DateTime) = expires <= now() || stat(q.cachepath).device == 0 expired(q::QueryCache, ttl::Period) = expired(q, unix2datetime(mtime(q.cachepath)) + ttl) """ df_cached(q::QueryCache, ttl_e::Union{Dates.Period, Dates.DateTime}; noisy::Bool=false) # Arguments - `q` a QueryCache - `ttl_e` is either a DataTime or Period specifying how long the cache should be live. If the cached version of the DataFrame is still live, return it from disk. If it has expired, call the Query's sql_function with the sql, write the DataFrame to disk in the specified formats and return the DataFrame. The noisy flag indicates whether to print to stderr where the data is coming from. # Examples Always retreive the SQL from the server df = df_cached(query, now()) Get the cached version, if it exists, or is less than 7 days old Print "From Server" or "From Cache" on stderr, depending where it came from, with the filename / sql snippet df = df_cached(query, Dates.Day(7), noisy=true) """ function df_cached(q::QueryCache, ttl_e; noisy=false) if expired(q, ttl_e) if noisy println(stderr, "($(Threads.threadid())) From Server - ", q.sql[1:(length(q.sql) < 40 ? end : 40)]) end df = q.select(q.sql) df_write(q.cachepath, df, subformat=q.subformat, dictencode=q.dictencode) return df else if noisy println(stderr, "($(Threads.threadid())) From Cache - ", splitpath(q.cachepath)[end]) end df_read(q.cachepath) end end """ select_fn(connection, args...; kw...) Return a function which will `execute` the Query's sql on the supplied connection # Arguments - `connection` the appropriate Connection data structure from some other module - `args` splatted arguments to use in DBInterface.connect - `kw` splatted kwarguments to use in DBInterface.connect # Examples sql_fn = select_fn(MySQL.Connection, SERVER, USER, PASSWORD) """ select_fn(connection, args...; kw...) = sql->DBInterface.execute(DBInterface.connect(connection, args...; kw...), sql) |> DataFrame """ fetch_and_combine(queries; ttl:Union{Dates.Period, Dates.DateTime}, noisy::Bool) Given an iterable collection of queries, fetch them and combine them into a single DataFrame using as many threads as available. # Arguments - `queries` iterable collection of QueryCache - `ttl` Time To Live, a Period or DateTime (default 7 days) - `noisy` if so, report on stderr where the data is coming from (default false) # Example If we have a long_view that times out on a single connection then split it into 3 and re-combine them. This is my actual use case for this Module. I'm querying from MySQL on AWS and only get 300 seconds. If the network is busy, my queries risk being terminated, so I break them into chunks. df = fetch_and_combine([ QueryCache("SELECT long_view WHERE created BETWEEN '2019-01-01' AND '2019-12-13'", sql_fn, ".", :arrow), QueryCache("SELECT long_view WHERE created BETWEEN '2020-01-01' AND '2020-12-13'", sql_fn, ".", :arrow), QueryCache("SELECT long_view WHERE created BETWEEN '2021-01-01' AND '2021-12-13'", sql_fn, ".", :arrow), ]) """ function fetch_and_combine(queries; ttl=Day(7), noisy=false) dfs = Vector{DataFrame}(undef, length(queries)) Threads.@threads for i in 1:length(queries) dfs[i] = df_cached(queries[i], ttl, noisy=noisy) end reduce((adf, df)->append!(adf, df), dfs[2:end], init=dfs[1]) end #fetch_and_combine(queries; ttl=Day(7), noisy=false) = reduce((adf, query)->append!(adf, df_cached(query, ttl, noisy=noisy)), queries, init=DataFrame()) """ Dfetch_and_combine(queries; ttl:Union{Dates.Period, Dates.DateTime}, noisy::Bool) The same as [fetch\\_and\\_combine][@ref] but use a different process for each Query, spawning at :any. """ Dfetch_and_combine(queries; ttl=Day(7), noisy=false) = reduce((adf, future)->append!(adf, fetch(future)), [@spawnat :any df_cached(query, ttl, noisy=noisy) for query in queries], init=DataFrame()) ### end
SQLDataFrameTools
https://github.com/lawless-m/SQLDataFrameTools.jl.git