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.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 851 | using JuLIP, ForwardDiff, StaticArrays, BenchmarkTools
# simple EAM potential
f(R) = sqrt( 1.0 + sum( exp(-norm(r)) for r in R ) )
nneigs = 30
R0 = [ @SVector rand(3) for n = 1:nneigs ]
f_fd(R) = ForwardDiff.gradient( T -> f(vecs(T)), mat(R)[:] ) |> vecs
function f_d(R::AbstractVector{<:JVec})
∇f = zeros(JVecF, length(R))
ρ̄ = sum( exp(-norm(r)) for r in R )
dF = 0.5 * (1.0 + ρ̄)^(-0.5)
return [ dF * (- exp(-norm(r))) * r/norm(r) for r in R ]
end
@assert f_d(R0) ≈ f_fd(R0)
@btime f($R0);
@btime f_d($R0);
@btime f_fd($R0);
# f1(R::AbstractMatrix) =
# sqrt( 1.0 + sum( exp.(-sqrt.(sum(abs2, R, 1))) ) )
# f1_rd(R::Matrix) =
# reshape(
# ReverseDiff.gradient( S -> f1(reshape(S, 3, length(S) ÷ 3)), R[:] ),
# size(R) )
# R1 = mat(R0)
# f1_rd(R1)
#
# @btime f1($R1);
# @btime f1_rd($R1);
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2858 | using BenchmarkTools
using JuLIP
using JuLIP: AbstractAtoms, AbstractCalculator
function perfbm(id::AbstractString, at::AbstractAtoms, calc::AbstractCalculator;
e = true, elist = true, f = true, flist = true)
println("--------------------------------------------------------------------------")
println(id)
if e
print("Energy Assembly (without nlist): ")
@btime energy($calc, $at)
end
if elist
print("Energy Assembly (with nlist): ")
@btime energy($calc, rattle!($at, 0.001))
end
if f
print("Force Assembly (without nlist): ")
@btime forces($calc, $at)
end
if flist
print("Force Assembly (with nlist): ")
@btime forces($calc, rattle!($at, 0.001))
end
end
println()
println("≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡")
println(" JuLIP Performance Regression Tests")
println("≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡")
println()
perfbm("LENNARD-JONES",
bulk(:Al, cubic=true) * (10,10,8),
lennardjones(r0=rnn(:Al)) )
data = joinpath(dirname(@__FILE__), "..", "data") * "/"
perfbm("EAM (Splines)",
bulk(:Fe, cubic=true) * (12,12,8),
EAM(data * "pfe.plt", data * "ffe.plt", data * "F_fe.plt") )
perfbm("STILLINGER-WEBER",
bulk(:Si, cubic=true) * (12,15,12),
StillingerWeber())
##
using BenchmarkTools
using JuLIP
using JuLIP: AbstractAtoms, AbstractCalculator
at = bulk(:Al, cubic=true) * (10,10,8)
calc = lennardjones(r0=rnn(:Al))
tmp = JuLIP.alloc_temp(calc, at)
JuLIP.energy!(tmp, calc, at)
# Performance prior to restructuring
# TODO: fix performance of PairPotentials
# --------------------------------------------------------------------------
# LENNARD-JONES
# Energy Assembly (without nlist): 66.695 ms (41653 allocations: 47.65 MiB)
# Energy Assembly (with nlist): 68.778 ms (41675 allocations: 41.52 MiB)
# Force Assembly (without nlist): 73.158 ms (41657 allocations: 43.40 MiB)
# Force Assembly (with nlist): 72.561 ms (41677 allocations: 41.59 MiB)
# --------------------------------------------------------------------------
# EAM (Splines)
# Energy Assembly (without nlist): 69.074 ms (71535 allocations: 43.47 MiB)
# Energy Assembly (with nlist): 74.438 ms (71558 allocations: 44.49 MiB)
# Force Assembly (without nlist): 83.091 ms (69237 allocations: 44.23 MiB)
# Force Assembly (with nlist): 87.327 ms (69257 allocations: 44.51 MiB)
# --------------------------------------------------------------------------
# STILLINGER-WEBER
# Energy Assembly (without nlist): 78.205 ms (402680 allocations: 65.56 MiB)
# Energy Assembly (with nlist): 86.708 ms (410401 allocations: 69.01 MiB)
# Force Assembly (without nlist): 87.153 ms (411005 allocations: 67.34 MiB)
# Force Assembly (with nlist): 91.166 ms (410672 allocations: 69.42 MiB)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 1434 |
using JuLIP, Test, Printf
using JuLIP.Testing
h0(" JuLIP Tests ")
@info("preparing the tests...")
verbose=true
## check whether on CI
isCI = haskey(ENV, "CI")
notCI = !isCI
eam_W4 = nothing
## ===== some prototype potentials ======
@info("Loading some interatomic potentials . .")
data = joinpath(dirname(pathof(JuLIP)), "..", "data") * "/"
eam_Fe = JuLIP.Potentials.EAM(data * "pfe.plt", data * "ffe.plt", data * "F_fe.plt")
print(" .")
eam_W = JuLIP.Potentials.FinnisSinclair(data*"W-pair-Wang-2014.plt", data*"W-e-dens-Wang-2014.plt")
print(" .")
global eam_W4
try
global eam_W4 = JuLIP.Potentials.EAM(data * "w_eam4.fs")
catch
global eam_W4 = nothing
end
println(" done.")
julip_tests = [
("testaux.jl", "Miscellaneous"),
("test_atoms.jl", "Atoms"),
("test_build.jl", "Build"),
("test_fio.jl", "File IO"),
("testanalyticpotential.jl", "Analytic Potential"),
("testpotentials.jl", "Potentials"),
("test_ad.jl", "AD Potentials"),
("testvarcell.jl", "Variable Cell"),
("testhessian.jl", "Hessian"),
]
# add solver tests if not on travis
if !isCI
push!(julip_tests, ("testsolve.jl", "Solve"))
else
@info("on CI : don't run solver tests")
end
# "testexpvarcell.jl"; # USE THIS TO WORK ON EXPCELL IMPLEMENTATION
@testset "JuLIP" begin
for (testfile, testid) in julip_tests
h1("Testset $(testid)")
@testset "$(testid)" begin include(testfile); end
end
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 1039 |
using JuLIP, ForwardDiff, StaticArrays, BenchmarkTools, Test, LinearAlgebra
# simple EAM-like potential
f(R) = sqrt( 1.0 + sum( exp(-norm(r)) for r in R ) )
# hand-coded gradient
function f_d(R::AbstractVector{<:JVec})
∇f = zeros(JVecF, length(R))
ρ̄ = sum( exp(-norm(r)) for r in R )
dF = 0.5 * (1.0 + ρ̄)^(-0.5)
return [ dF * (- exp(-norm(r))) * r/norm(r) for r in R ]
end
# ForwardDiff gradient
f_fd(R) = collect(ForwardDiff.gradient( T -> f(vecs(T)), collect(mat(R)[:]) ) |> vecs)
# turn it into an AD potential
V = JuLIP.Potentials.ADPotential(f, Inf)
# a test configuration
nneigs = 30
R0 = [ @SVector rand(3) for n = 1:nneigs ]
# check that all of them are the same
println(@test V(R0) == f(R0))
println(@test (@D V(R0)) == f_fd(R0))
println(@test f_d(R0) ≈ f_fd(R0))
# timings
print("Timing for f: ")
@btime f($R0);
print("Timing for V: ")
@btime V($R0);
print("Timing for f_d: ")
@btime f_d($R0);
print("Timing for f_fd: ")
@btime f_fd($R0);
print("Timing for @D V: ")
@btime (@D $V($R0));
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 1868 |
using JuLIP.Testing, ASE, PyCall
@info("These tests to compare JuLIP vs ASE implementations of some potentials")
h3("Compare JuLIP vs ASE: EAM")
# JuLIP's EMT implementation
at = set_pbc!( bulk(:Cu, cubic=true) * (2,2,2), (true,false,false) )
rattle!(at, 0.02)
emt = EMT(at)
@info("Test JuLIP vs ASE EMT implementation")
pyemt = ASE.Models.EMTCalculator()
print(" energy: ")
println(@test abs(energy(emt, at) - energy(pyemt, at)) < 1e-10)
print(" forces: ")
println(@test norm(forces(pyemt, at) - forces(emt, at), Inf) < 1e-10)
# ------------------------------------------------------------------------
h3("Compare JuLIP EAM Implementation against ASE EAM Implementation")
@pyimport ase.calculators.eam as eam
pot_file = joinpath(dirname(pathof(JuLIP)), "..", "data", "w_eam4.fs")
@info("Generate the ASE potential")
eam4_ase = eam.EAM(potential=pot_file) |> ASECalculator
@info("Generate low-, med-, high-accuracy JuLIP potential")
eam4_jl1 = EAM(pot_file)
eam4_jl2 = EAM(pot_file; s = 1e-4)
eam4_jl3 = EAM(pot_file; s = 1e-6)
at1 = rattle!(bulk(:W, cubic=true) * 3, 0.1)
at2 = deleteat!(bulk(:W, cubic=true) * 3, 1)
at1_ase = ASEAtoms(at1)
at2_ase = ASEAtoms(at2)
for (i, (at, at_ase)) in enumerate(zip([at1, at2], [at1_ase, at2_ase]))
@info("Test $i")
err_low = (energy(eam4_ase, at_ase) - energy(eam4_jl1, at)) / length(at)
err_med = (energy(eam4_ase, at_ase) - energy(eam4_jl2, at)) / length(at)
err_hi = (energy(eam4_ase, at_ase) - energy(eam4_jl3, at)) / length(at)
print(" Low Accuracy energy error:", err_low, "; ",
(@test abs(err_low) < 0.02))
print(" Low Accuracy energy error:", err_med, "; ",
(@test abs(err_med) < 0.006))
print(" Low Accuracy energy error:", err_hi, "; ",
(@test abs(err_hi) < 0.0004))
end
# ------------------------------------------------------------------------
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 1929 |
using JuLIP
using Test
using LinearAlgebra: I
h3("check that `bulk` evaluates ok...")
at = bulk(:Si)
println(@test typeof(at) == Atoms{Float64})
h3("... and that we can repeat it.")
println(@test length(at * (1,2,3)) == 6 * length(at))
h3("check deepcopy and == ...")
at = bulk(:Si)
at1 = deepcopy(at)
println(@test at == at1)
h3("Check setindex! and getindex ...")
at = bulk(:Si, cubic=true)
x = at[2]
println(@test x == JVec(1.3575, 1.3575, 1.3575))
x += 0.1
at[2] = x
X = positions(at)
println(@test !(X === at.X))
println(@test X[2] == x)
h3("set_positions ...")
at = bulk(:Si, cubic=true) * 2
X = positions(at)
println(@test !(X === at.X))
println(@test X == at.X)
X += 0.1 * rand(JVecF, length(at))
println(@test X != at.X)
set_positions!(at, X)
println(@test X == at.X)
println(@test !(X === at.X))
# TODO: set_momenta, set_masses, set_numbers
println(@test chemical_symbols(at) == fill(:Si, 64))
println(@test chemical_symbols(bulk(:W)) == [:W])
h3("test set_positions!")
Y = copy(X)
Y[3] = JVec(rand(3))
println(@test Y != positions(at))
set_positions!(at, Y)
println(@test Y == positions(at))
h3("test set_momenta!")
Nat = length(at)
Ifree = rand(collect(1:Nat), Nat * 4 ÷ 5) |> unique |> sort # prepare for test below
Iclamp = setdiff(1:Nat, Ifree)
P = rand(size(Y |> mat)...)
P[:, Iclamp] .= 0.0
P = vecs(P)
set_momenta!(at, P)
println(@test P == momenta(at))
h3("test set_dofs!, etc")
# this is making an assumptions on the ordering of dofs; since a new
# implementation of the DOF manager could change this, this test needs to be
# re-implemented if that happens.
set_free!(at, Ifree)
println(@test dofs(at) == position_dofs(at) == mat(Y)[:, Ifree][:])
println(@test momentum_dofs(at) == mat(P)[:, Ifree][:])
q = position_dofs(at)
q = rand(length(q))
set_position_dofs!(at, q)
println(@test q == position_dofs(at))
p = rand(length(q))
set_momentum_dofs!(at, p)
println(@test p == momentum_dofs(at))
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 751 |
using JuLIP, Test
using JuLIP.Testing
h3("Testing single `Atoms` <-> `Dict`")
at = bulk(:Cu, cubic=true) * 3
set_pbc!(at, (true, false, true))
rattle!(at, 0.1)
D = Dict(at)
at1 = Atoms(D)
println(@test(at == at1))
at2 = decode_dict(D)
println(@test(at == at2))
h3("Test JSON fio")
fn = tempname()
save_dict(fn, D)
D1 = load_dict(fn)
# D1 == D => this will be false so don't test it!
at3 = decode_dict(D1)
println(@test at3 == at1)
h3("Test array of Atoms <-> Dict")
ats = [ (bulk(:Cu) * rand(2:4)) for n = 1:5 ]
Ds = Dict("ats" => Dict.(ats))
ats1 = decode_dict.(Ds["ats"])
println(@test ats1 == ats)
h3("Test JSON fio for array")
fn = tempname()
save_dict(fn, Ds)
Ds1 = load_dict(fn)
ats2 = decode_dict.(Ds1["ats"])
println(@test ats == ats2)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 503 |
println("testing periodic notion of distance")
X1 = [ JVecF(0.0,0.0,0.0), JVecF(0.5,0.5,0.5)]
at = Atoms(:H, X1)
set_pbc!(at, (true, false, false))
set_cell!(at, [1.0 0.2 0.3; 0.0 1.0 0.1; 0.0 0.0 1.0])
X2 = [ X1[1], X1[2] + JVecF(1.0, 0.2, 0.3)]
X3 = [ X1[1] - JVecF(0.1, 0.0, 0.0), X1[2]]
X4 = [ X1[1], X1[2] + JVecF(0.0, 1.0, 0.1)]
@testset "dist" begin
@test JuLIP.dist(at, X1, X2) < 1e-14
@test JuLIP.dist(at, X1, X3) ≈ 0.1
@test JuLIP.dist(at, X1, X4) ≈ norm(JVecF(0.0, 1.0, 0.1))
end
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 1721 |
import JuLIP.Potentials: @pot, @D, evaluate!, evaluate_d!, PairPotential, @analytic
using LinearAlgebra: norm
using BenchmarkTools
using JuLIP, Test
h3("generate hand-coded morse potential")
mutable struct Morseold <: PairPotential
e0::Float64
A::Float64
r0::Float64
end
@pot Morseold
evaluate!(tmp, p::Morseold, r::Number) =
p.e0 * (exp(-2*p.A*(r/p.r0-1.0)) - 2.0*exp(-p.A*(r/p.r0-1.0)))
evaluate_d!(tmp, p::Morseold, r::Number) =
-2.0*p.e0*p.A/p.r0*(exp(-2*p.A*(r/p.r0-1.0)) - exp(-p.A*(r/p.r0-1.0)))
A = 4.1
e0 = 0.99
r0 = 1.05
morseold = Morseold(e0, A, r0)
h3("generate AD morse potential")
morse1 = let A = A, e0 = e0, r0 = r0
@analytic( r -> e0 * (exp(-2*A*(r/r0-1.0)) - 2.0*exp(-A*(r/r0-1.0))) )
end
@show typeof(morse1)
h3("Check consistency of hand-coded and analytic Morse potentials...")
rr = collect(range(0.9, stop=2.1, length=100))
morse_r = morse1.(rr)
morseold_r = morseold.(rr)
dmorse_r = [(@D morse1(r)) for r in rr]
dmorseold_r = [ (@D morseold(r)) for r in rr ]
println(@test norm(morse_r - morseold_r, Inf) < 1e-12)
println(@test norm(dmorse_r - dmorseold_r, Inf) < 1e-12)
function runn(f, x, N)
s = 0.0
for n = 1:N
x += 0.0001
s += f(x)
end
return s
end
function runn_d(f, x, N)
s = 0.0
for n = 1:N
x += 0.0001
s += @D f(x)
end
return s
end
h2("Performance tests: @analytic vs hand-coded")
x = 1.0+rand()
println("Evaluations of @analytic Potential")
@btime runn($morse1, $x, 1_000)
println("Evaluations hand-coded Potential")
@btime runn($morseold, $x, 1_000)
println("Grad of @analytic Potential")
@btime runn_d($morse1, $x, 1_000)
println("Grad of hand-coded Potential")
@btime runn_d($morseold, $x, 1_000)
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 279 |
h1("Test Aux")
h2("matrix <-> vec conversions")
X = rand(3, 3)
Y = vecs(X) |> mat
println(@test X == Y)
Y[1] = -1.0
println(@test X == Y)
V = rand(JVecF, 10)
A = mat(V)
B = vecs(A)
println(@test B === V)
B[1] = rand(JVecF)
println(@test B === V)
println(@test A[:, 1] == V[1])
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 2847 | using JuLIP: stress
using JuLIP.Potentials
using LinearAlgebra
println("-------------------------------------------------")
println(" Variable Cell Test")
println("-------------------------------------------------")
calc = lennardjones(r0=rnn("Al"))
at = bulk("Al") * 2 # cubic=true,
set_pbc!(at, true)
set_calculator!(at, calc)
# perturb the cell shape
set_defm!(at, defm(at) + 0.1*rand(JMatF), updatepositions=true)
# check that under this deformation the atom positions are still
# in a homogeneous lattice (i.e. they are deformed correctly with the cell)
@test maxnorm(forces(at)) < 1e-12
# now perturb the atom positions as well
rattle!(at, 0.1)
# set the constraint >>> this means the deformed cell defines F0 and X0
set_constraint!(at, ExpVariableCell(at))
# check that energy, forces, stress, dofs, gradient evaluate at all
print("check that energy, forces, stress, dofs, gradient evaluate ... ")
energy(at)
forces(at)
gradient(at)
stress(at)
println("ok.")
@test true
print("Check that setting and getting dofs is consistent ... ")
x = dofs(at)
@assert length(x) == 3 * length(at) + 6
y = x + 0.01 * rand(size(x))
set_dofs!(at, y)
z = dofs(at)
@test norm(y - z, Inf) < 1e-12
println("ok")
# perform the finite-difference test
set_dofs!(at, x)
JuLIP.Testing.fdtest(calc, at, verbose=true, rattle=0.1)
println("-------------------------------------------------")
println("Test optimisation with ExpVariableCell")
# # start with a clean `at`
at = bulk("Si") * 2 # cubic=true,
set_pbc!(at, true)
set_calculator!(at, StillingerWeber())
set_constraint!(at, ExpVariableCell(at))
#
println("For the initial state, stress is far from 0:")
@show norm(virial(at), Inf)
JuLIP.Solve.minimise!(at, verbose=2)
# dt = 1e-6
# for n = 1:100
# x = dofs(at)
# ∇E = gradient(at)
# @printf(" %3d | %4.2e \n", n, norm(∇E, Inf))
# x -= dt * ∇E
# set_dofs!(at, x)
# end
println("After optimisation, stress is 0:")
@show norm(virial(at), Inf)
# @test norm(virial(at), Inf) < 1e-4
println("Test for comparison with the standard VariableCell")
at = bulk("Si") * 2 # cubic=true,
set_pbc!(at, true)
set_calculator!(at, StillingerWeber())
set_constraint!(at, VariableCell(at))
#
println("For the initial state, stress is far from 0:")
@show norm(virial(at), Inf)
JuLIP.Solve.minimise!(at, verbose=2)
# println("-------------------------------------------------")
# println("And now with pressure . . .")
# println("-------------------------------------------------")
# set_constraint!(at, ExpVariableCell(at, pressure=10.0123))
# JuLIP.Testing.fdtest(calc, at, verbose=true, rattle=0.1)
# at = Atoms("Al", pbc=(true,true,true)) * 2 # cubic=true,
# set_calculator!(at, calc)
# set_constraint!(at, VariableCell(at, pressure=0.01))
# JuLIP.Solve.minimise!(at)
# @show norm(stress(at), Inf)
# @test norm(gradient(at), Inf) < 1e-4
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 3084 | using Test, JuLIP, StaticArrays, Printf, LinearAlgebra
using JuLIP.Potentials
using JuLIP.Testing
using JuLIP.Potentials: evaluate_d, evaluate_dd
h2("Testing pair potential hessian")
at = bulk(:Cu, cubic=true)
pp = lennardjones(r0=rnn(:Cu))
h3("test the potential (scalar) itself")
rr = 0.9*rnn(:Cu) .+ 3.0*rand(100)
ddJ = [@DD pp(r) for r in rr]
ddJh = [((@D pp(r + 1e-4)) - (@D pp(r - 1e-4))) / 2e-4 for r in rr]
println( @test (@show maximum(abs.(ddJ .- ddJh))) < 1e-4 )
h3("test `hess`; with two test vectors")
for R in ( [0.0,-3.61,-3.61], [-1.805,-1.805,-3.61] )
r = norm(R)
@show r, R
E0 = pp(r)
# f0 = grad(pp, r, JVecF(R))
f0 = evaluate_d(pp, r) * R/r
size(f0)
# df0 = hess(pp, r, JVecF(R))
df0 = evaluate_dd(pp, r) * (R/r) * (R/r)' +
(evaluate_d(pp, r)/r) * (I - (R/r) * (R/r)')
dfh = zeros(3,3)
fh = zeros(3)
for p = 2:11
h = 0.1^p
for n = 1:3
R[n] += h
# fh[n] = (evaluate(pp, norm(R)) - E0)
dfh[:, n] = (evaluate_d(pp, norm(R)) * R/norm(R) - f0) / h
# (grad(pp, r, JVecF(R)) - f0) / h
R[n] -= h
end
@printf("%1.1e | %4.2e \n", h, norm(dfh - df0, Inf))
end
@printf("-------|--------- \n")
end
h3("full finite-difference test for pairpot `hessian`")
at = at * 2
set_pbc!(at, false)
set_calculator!(at, pp)
println(@test fdtest_hessian( x->JuLIP.gradient(at, x), x->hessian(at, x), dofs(at) ))
h2("Testing EAM hessian")
# setup a geometry
at = bulk(:Fe, cubic=true) * 2
set_pbc!(at, false)
eam = eam_Fe
set_calculator!(at, eam)
rattle!(at, 0.1)
h3("test a single stencil")
r = []
R = []
for (idx, _j, R1) in sites(at, cutoff(eam))
if idx == 3
global r = r1
global R = R1
break
end
end
# evaluate site gradient and hessian
dVs = evaluate_d(eam, R)
hVs = evaluate_dd(eam, R)
# and convert them to vector form
dV = mat(dVs)[:]
hV = zeros(3*size(hVs,1), 3*size(hVs,2))
for i = 1:size(hVs,1), j = 1:size(hVs,2)
hV[3*(i-1).+(1:3), 3*(j-1).+(1:3)] = hVs[i,j]
end
matR = mat(R)
errs = []
for p = 2:9
h = 0.1^p
hVh = fill(0.0, size(hV))
for n = 1:length(matR)
matR[n] += h
r = norm.(R)
dVh = mat(evaluate_d(eam, R))[:]
hVh[:, n] = (dVh - dV) / h
matR[n] -= h
end
push!(errs, norm(hVh - hV, Inf))
@printf("%1.1e | %4.2e \n", h, errs[end])
end
println(@test /(extrema(errs)...) < 1e-3)
h3("full finite-difference test ...")
h3(" ... EAM forces")
println(@test fdtest( x -> energy(at, x), x -> JuLIP.gradient(at, x), dofs(at) ))
# h3(" ... EAM hessian")
# println(@test fdtest_hessian( x->gradient(at, x), x->hessian(at, x), dofs(at) ))
# TODO: fix EAM hessian again
h2("Testing Stillinger-Weber hessian")
# setup a geometry
at = bulk(:Si, cubic=true) * 2
rattle!(at, 0.02)
set_pbc!(at, false)
sw = StillingerWeber()
set_calculator!(at, sw)
h3("full finite-difference test ...")
h3(" ... SW forces")
println(@test fdtest( x -> energy(at, x), x -> JuLIP.gradient(at, x), dofs(at) ))
h3(" ... SW hessian")
println(@test fdtest_hessian( x->JuLIP.gradient(at, x), x->hessian(at, x), dofs(at) ))
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 3867 |
using JuLIP
using JuLIP.Potentials
using JuLIP.Testing
using LinearAlgebra
pairpotentials = [
LennardJones(1.0,1.0);
Morse(4.0,1.0,1.0);
SWCutoff(1.0, 3.0) * LennardJones(1.0,1.0);
SplineCutoff(2.0, 3.0) * LennardJones(1.0,1.0);
LennardJones(1.0, 1.0) * C2Shift(2.0);
ZBLPotential(5, 8)
]
if eam_W4 != nothing
push!(pairpotentials, eam_W4.ϕ)
end
h2("Testing pair potential implementations")
r = range(0.8, stop=4.0, length=100) |> collect
push!(r, 2.0-1e-12)
for pp in pairpotentials
h3(pp)
println(@test fdtest(pp, r, verbose=verbose))
end
h2("testing shift-cutoffs: ")
V = @analytic r -> exp(r)
Vhs = V * HS(1.0)
r1 = range(0.0, stop=1.0-1e-14, length=20)
r2 = range(1.0+1e-14, stop=3.0, length=20)
h3("HS")
println(@test Vhs.(r1) == exp.(r1))
println(@test norm(Vhs.(r2)) == 0.0)
h3("V0")
V0 = V * C0Shift(1.0)
println(@test V0.(r1) ≈ exp.(r1) .- exp(1.0))
println(@test norm(V0.(r2)) == 0.0)
h3("V1")
V1 = V * C1Shift(1.0)
println(@test V1.(r1) ≈ exp.(r1) .- exp(1.0) .- exp(1.0) .* (r1.-1.0))
println(@test norm(V1.(r2)) == 0.0)
h3("V2")
V2 = V * C2Shift(1.0)
println(@test V2.(r1) ≈ exp.(r1) .- exp(1.0) .- exp(1.0) .* (r1.-1.0) .- 0.5 .* exp(1.0) .* (r1.-1.0).^2)
println(@test norm(V2.(r2)) == 0.0)
# =============================================================
calculators = Any[]
# Basic lennard-jones calculator test
push!(calculators,
(lennardjones(r0=rnn(:Al)),
bulk(:Al, cubic=true, pbc=(true,false,false)) * (3,3,2) ) )
# ZBL Calculator
push!(calculators,
( ZBLPotential(4, 7) * SplineCutoff(6.0, 8.0),
rattle!(bulk(:W, cubic=true, pbc=false) * (3,3,2), 0.1) ) )
# Stillinger-Weber model
at3 = set_pbc!( bulk(:Si, cubic=true) * 2, (false, true, false) )
sw = StillingerWeber()
set_calculator!(at3, sw)
push!(calculators, (sw, at3))
# EAM Potential
at9 = set_pbc!( bulk(:Fe, cubic = true), false ) * 2
eam = eam_Fe
push!(calculators, (eam, at9))
if eam_W4 != nothing
# Another EAM Potential
at10 = set_pbc!( bulk(:W, cubic = true), false ) * 2
push!(calculators, (eam_W4, at10))
end
if eam_W != nothing # finnis-sinclair
at11 = set_pbc!( bulk(:W, cubic = true), false ) * 2
push!(calculators, (eam_W, at11))
end
# JuLIP's EMT implementation
at = set_pbc!( bulk(:Cu, cubic=true) * (2,2,2), (true,false,false) )
rattle!(at, 0.02)
emt = EMT(at)
push!(calculators, (EMT(at), at))
# and a multi-species EMT
at1 = bulk(:Cu, cubic=true)
at1.Z[[2,4]] .= 13 # Al
at = set_pbc!(at1 * 2, false)
rattle!(at, 0.02)
emt = EMT(at)
push!(calculators, (emt, at))
# ========== Run the finite-difference tests for all calculators ============
h2("Testing calculator implementations")
for (calc, at_) in calculators
println("--------------------------------")
h3(typeof(calc))
@show length(at_)
println(@test fdtest(calc, at_, verbose=true))
println("--------------------------------")
end
# ========== Test correct implementation of site_energy ============
# and of partial_energy
h2("Testing `site_energy` and `partial_energy` ...")
at = bulk(:Si, pbc=true, cubic=true) * 3
sw = StillingerWeber()
atsm = bulk(:Si, pbc = true)
println("checking site energy identity . . .")
println(@test abs( JuLIP.Potentials.site_energy(sw, at, 1) - energy(sw, atsm) / 2 ) < 1e-10)
rattle!(at, 0.01)
println(@test abs( energy(sw, at) - sum(site_energies(sw, at)) ) < 1e-10)
println("fd test for site_energy")
f(x) = JuLIP.Potentials.site_energy(sw, set_dofs!(at, x), 1)
df(x) = (JuLIP.Potentials.site_energy_d(sw, set_dofs!(at, x), 1) |> mat)[:]
println(@test fdtest(f, df, dofs(at); verbose=true))
println("fd test for partial energy")
Idom = [2,4,10]
f(x) = JuLIP.Potentials.energy(sw, set_dofs!(at, x); domain = Idom)
df(x) = - (JuLIP.Potentials.forces(sw, set_dofs!(at, x); domain = Idom) |> mat)[:]
println(@test fdtest(f, df, dofs(at); verbose=true))
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 3729 |
using JuLIP
using JuLIP.Testing
using JuLIP: sigvol_d
using Test
using LinearAlgebra
h2("Testing `minimise!` with equilibration with LJ calculator to lattice")
calc = lennardjones(r0=rnn(:Al))
at = bulk(:Al, cubic=true) * 10
X0 = positions(at) |> mat
at = rattle!(at, 0.02)
set_calculator!(at, calc)
x = dofs(at)
println(@test (energy(at) == energy(at, x) == energy(calc, at)
== energy(calc, at, x) )
)
minimise!(at, precond=:id, verbose=2)
X1 = positions(at) |> mat
X0 .-= X0[:, 1]
X1 .-= X1[:, 1]
F = X1 / X0
println("check that the optimiser really converged to a lattice")
@show norm(F'*F - I, Inf)
@show norm(F*X0 - X1, Inf)
@test norm(F*X0 - X1, Inf) < 1e-4
h2("same test but large and with Exp preconditioner")
at = bulk(:Al, cubic=true) * (20,20,2)
at = rattle!(at, 0.02)
set_calculator!(at, calc)
minimise!(at, precond = :exp, method = :lbfgs,
robust_energy_difference = true, verbose=2
)
h2("Variable Cell Test")
calc = lennardjones(r0=rnn(:Al))
at = set_pbc!(bulk(:Al, cubic=true), true)
set_calculator!(at, calc)
variablecell!(at)
x = dofs(at)
println(@test (energy(at) == energy(at, x) == energy(calc, at)
== energy(calc, at, x) )
)
minimise!(at, verbose = 2)
h2("FF preconditioner for StillingerWeber")
at = bulk(:Si, cubic=true) * (10,10,2)
at = set_pbc!(at, true)
at = rattle!(at, 0.02)
set_calculator!(at, StillingerWeber())
P = FF(at, StillingerWeber())
minimise!(at, precond = P, method = :lbfgs,
robust_energy_difference = true, verbose=2)
h2("FF preconditioner for EAM")
at = bulk(:W, cubic=true) * (10,10,2)
at = set_pbc!(at, true)
at = rattle!(at, 0.02)
X0 = positions(at)
##
set_positions!(at, X0)
set_calculator!(at, eam_W)
P = FF(at, eam_W)
minimise!(at, precond = P, method = :lbfgs, robust_energy_difference = true, verbose=2)
## steepest descent
set_positions!(at, X0)
set_calculator!(at, eam_W)
P = FF(at, eam_W)
minimise!(at, precond = P, method = :sd, robust_energy_difference = true, verbose=2)
##
h2("Optimise again with some different stabilisation options")
set_positions!(at, X0)
set_calculator!(at, eam_W)
P = FF(at, eam_W, stab=0.1, innerstab=0.2)
minimise!(at, precond = P, method = :lbfgs, robust_energy_difference = true, verbose=2)
##
h2("for comparison now with Exp")
set_positions!(at, X0)
minimise!(at, precond = :exp, method = :lbfgs, robust_energy_difference = true, verbose=2)
h2("Test optimisation with VariableCell")
# start with a clean `at`
at = bulk(:Al) * 2 # cubic=true,
apply_defm!(at, I + 0.02 * rand(3,3))
calc = lennardjones(r0=rnn(:Al))
set_calculator!(at, calc)
variablecell!(at)
println(@test JuLIP.Testing.fdtest(calc, at, verbose=true, rattle=0.1))
h2("For the initial state, stress/virial is far from 0:")
@show norm(virial(at), Inf)
JuLIP.Solve.minimise!(at, verbose=2)
println("After optimisation, stress/virial should be 0:")
@show norm(virial(at), Inf)
@test norm(virial(at), Inf) < 1e-4
h2("Check sigvol derivative")
println(@test fdtest(c -> JuLIP.sigvol(reshape(c, (3,3))),
c -> JuLIP.sigvol_d(reshape(c, (3,3)))[:],
rand(3,3)))
# TODO: revive this after introducing external potentials
# h2("And now with pressure . . .")
# set_constraint!(at, VariableCell(at, pressure=10.0123))
# JuLIP.Testing.fdtest(calc, at, verbose=true, rattle=0.02)
# at = bulk(:Al) * 2
# set_calculator!(at, calc)
# set_constraint!(at, VariableCell(at, pressure=0.01))
# JuLIP.Solve.minimise!(at, verbose = 2)
# @show norm(virial(at), Inf)
# @show norm(JuLIP.gradient(at), Inf)
# println(@test norm(JuLIP.gradient(at), Inf) < 1e-4)
# @info "note it is correct that virial is O(1) since we applied pressure"
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | code | 1431 |
using JuLIP, Test
using JuLIP.Potentials, JuLIP.Testing
using LinearAlgebra
calc = lennardjones(r0=rnn(:Al))
at = set_pbc!(bulk(:Al) * 2, true)
set_calculator!(at, calc)
println(@test maxnorm(forces(at)) < 1e-12)
h3("Check atoms deform correctly with the cell")
# perturb the cell shape
apply_defm!(at, I + 0.01*rand(JMatF))
# check that under this deformation the atom positions are still
# in a homogeneous lattice (i.e. they are deformed correctly with the cell)
println(@test maxnorm(forces(at)) < 1e-12)
# now perturb the atom positions as well
rattle!(at, 0.1)
# set the constraint >>> this means the deformed cell defines F0 and X0
variablecell!(at)
h3("check that energy, forces, virial, stress, dofs, gradient evaluate ... ")
energy(at)
forces(at)
gradient(at)
virial(at)
println(@test stress(at) == - virial(at) / volume(at))
h3("Check that setting and getting dofs is consistent ... ")
x = dofs(at)
@assert length(x) == 3 * length(at) + 9
y = x + 0.01 * rand(Float64, size(x))
set_dofs!(at, y)
z = dofs(at)
println(@test norm(y - z, Inf) < 1e-14)
# now perform the finite-difference test
set_dofs!(at, x)
println(@test JuLIP.Testing.fdtest(calc, at, verbose=true, rattle=0.1))
h3("Check virial for SW potential")
si = bulk(:Si, cubic=true) * 2
rattle!(si, 0.1)
apply_defm!(at, I + 0.01*rand(JMatF))
sw = StillingerWeber()
variablecell!(si)
println(@test JuLIP.Testing.fdtest(calc, si, verbose=true, rattle=0.1))
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | docs | 4126 | # JuLIP: Julia Library for Interatomic Potentials
| **Build Status** | **Social** |
|:-:|:-:|
| [![Build Status][build-img]][build-url] | [![][gitter-img]][gitter-url] |
<!-- [](https://travis-ci.org/libAtoms/JuLIP.jl) -->
A package for rapid implementation and testing of new interatomic potentials and
molecular simulation algorithms. Requires v0.5 or v0.6 of Julia. Current
development is for Julia v0.6.x. Documentation is essentially non-existent but
the inline documentations is reasonably complete.
The design of `JuLIP` is heavily inspired by [ASE](https://gitlab.com/ase/ase).
The main motivation for `JuLIP` is that, while `ASE` is pure Python and hence
relies on external software to efficiently evaluate interatomic potentials,
Julia allows the implementation of fast potentials in pure Julia, often in just
a few lines of code. `ASE` bindings compatible with `JuLIP` are provided by
[ASE.jl](https://github.com/cortner/ASE.jl.git).
Contributions are welcome, especially for producing examples and tutorials. Any
questions or suggestions, please ask on [![][gitter-img]][gitter-url].
# Installation
Install JuLIP, from the Julia REPL:
```julia
Pkg.add("JuLIP")
```
and run
```
Pkg.test("JuLIP")
```
to make sure the installation succeeded. If a test fails, please open an issue.
Most likely you will also want to ASE bindings; please see
[ASE.jl](https://github.com/cortner/ASE.jl.git) for more detail.
<!-- ## `imolecule` and dependencies
This part can be skipped if no visualisation is required; `using JuLIP` will then
simply print a warning.
`JuLIP.Visualise` uses the Python module `imolecule` to visualise atomistic
configurations in an IPython notebook. Its main dependency is
[OpenBabel](http://openbabel.org/wiki/Main_Page). Most recently, this could be installed succesfully (from the bash) using
```bash
conda install -c openbabel openbabel
pip install imolecule
``` -->
# Examples
The following are some minimal examples to just get something to run.
More intersting examples will hopefully follow soon.
## Vacancy in a bulk Si cell
```julia
using JuLIP
at = bulk(:Si, cubic=true) * 4
deleteat!(at, 1)
set_calculator!(at, StillingerWeber())
minimise!(at)
# Visualisation is current not working
# JuLIP.Visualise.draw(at) # (this will only work in a ipynb)
```
see the `BulkSilicon.ipynb` notebook under `examples` for an extended
example.
## Construction of a Buckingham potential
```julia
using JuLIP
r0 = rnn(:Al)
pot = let A = 4.0, r0 = r0
@analytic r -> 6.0 * exp(- A * (r/r0 - 1.0)) - A * (r0/r)^6
end
pot = pot * SplineCutoff(2.1 * r0, 3.5 * r0)
# `pot` can now be used as a calculator to do something interesting ...
```
## Site Potential with AD
```julia
using JuLIP
# and EAM-like site potential
f(R) = sqrt( 1.0 + sum( exp(-norm(r)) for r in R ) )
# wrap it into a site potential type => can be used as AbstractCalculator
V = ADPotential(f)
# evaluate V and ∇V
R0 = [ @SVector rand(3) for n = 1:nneigs ]
@show V(R0)
@show (@D V(R0))
```
<!-- ## An Example with TightBinding
**THIS IS PROBABLY BROKEN ON JULIA v0.6**
Similar to vacancy example but with a Tight-Binding Model. First install
`TightBinding.jl`:
```julia
Pkg.clone("https://github.com/ettersi/FermiContour.jl.git")
Pkg.clone("https://github.com/cortner/TightBinding.jl.git")
```
Then run
```julia
using JuLIP, TightBinding
TB = TightBinding
# sp model for Si (NRL-Tight Binding)
tbm = TB.NRLTB.NRLTBModel(elem=TB.NRLTB.Si_sp, nkpoints = (0,0,0))
# bulk crystal
at = bulk("Si", cubic=true) * 4
Eref = energy(tbm, at)
# create vacancy
deleteat!(at, 1)
Edef = energy(tbm, at)
# formation energy: (not really but sort of)
println("Vacancy formation energy = ", Edef - Eref * length(at)/(length(at)+1))
println("(probably this should not be negative! Increase simulation accuracy!)")
``` -->
[build-img]: https://travis-ci.org/libAtoms/JuLIP.jl.svg?branch=master
[build-url]: https://travis-ci.org/libAtoms/JuLIP.jl
[gitter-url]: https://gitter.im/libAtoms/JuLIP.jl
[gitter-img]: https://badges.gitter.im/libAtoms/JuLIP.jl.svg
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | docs | 1282 |
# Implementation Notes
TODO: these are very out of date and need an update
## Prototypes
For commonly used functions such as `set_positions!` etc, a prototype is
defined which just throws an error. The point of this prototype is that
(a) it can be imported from different packages / sub-packages, and (b)
it provides documentation. This is done using `@protofun`.
## Storage of positions, forces, etc
Atomic positions are stored either as a `Vector{Point{DIM,T}}` or as a
`Matrix{T}` of dimension `DIM x Npoints`, where normally `DIM == 3` and
`T == Float64`. The conversion between these can be done for free using
`reinterpret`.
Note that `ASE` internally stores positions as a `Npoints x DIM` matrix, but
this memory layout is not efficient for codes that can exploit fast loops.
The vector of forces (or negative forces aka gradient) is stored either
as a `Vector{Vec{DIM,T}}` or as a `Matrix{T}` or dimensions `DIM x Npoints`.
The types `Point, Vec` are from the `FixedSizeArrays` package and should in
principle allow fast linear algebra operations on small arrays without
having to write explicit loops.
## Neighbour lists
Because the `matscipy` neighbour list is so fast we don't bother ever storing
and updating the neighbourlist. Instead a calculator can just
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | docs | 201 |
# JuLIP.jl Documentation
## Introduction
## Installation
## Examples
## Further notes
* [Implementation Notes](ImplementationNotes.md)
* [Temporary Notes](tempnotes.md) that have no other place
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | docs | 3416 |
## Calculator Implementations
The most important user-oriented functions are
```{julia}
energy(calc, at)
forces(calc, at)
virial(calc, at)
```
A new calculators / model can either directly implement these, or alternatively
one of the functions that are called in their prototype implementation.
Concretely, if `calc` is an interatomic potential with a site energy, then
these outer calculators should *not* be implemented, but rather the evaluation
of the site energy and its derivatives. But e.g. for a Tight-binding model
or an interface to another library, one could or possibly must directly
implement `energy, force, virial`.
The standard implementation of `energy, forces, virial` is designed to
admit minimal or even zero allocations during these evaluations. This is
achieved as follows: first `energy, forces, virial` call in-place
versions with the calling convention
```{julia}
energy!( tmp, calc, at)
forces!(F, tmpd, calc, at)
virial!( tmp, calc, at)
```
where
```{julia}
tmp = alloc_temp( calc, at)
tmpd = alloc_temp_d(calc, at)
```
A new calculator could again implement `energy!, forces!, virial!`
directly.
### Site Potentials
However, for a site potentials one should require that
```
calc <: SitePotential
```
In that case an implementation of `energy!, forces!, virial!`
already exists, which is based on
```{julia}
evaluate!( tmp, calc, R)
evaluate_d!(dV, tmpd, calc, R)
```
where `R::AbstractVector{<:JVec}`.
Now, the temporary arrays are obtained from
```{julia}
tmp = alloc_temp(calc, N)
tmpd = alloc_temp_d(calc, N)
```
and `N` is an integer giving an upper bound on the number of neighbours
in the system. The allocating versions `energy, ...` will first generate
a neighbourlist, then calculate `N` (cf. `NeighbourLists.maxneigs`)
then allocate `tmp, tmpd` and then use that to call the non-allocating
versions `energy!, ...`.
It is *required* that `tmp` has a field `temp.R` and that
`tmpd` has fields `tmpd.dV, tmp.R` which will be used to
store the neighbourhood information and the site energy derivatives.
### Pair Potentials
For pair potentials, i.e. `calc <: PairPotential <: SitePotential`
the functions
```{julia}
evaluate!( tmp, calc, R::AbstractVector{<:JVec})
evaluate_d!(dV, tmpd, calc, R::AbstractVector{<:JVec})
```
are implemented through calls to only
```{julia}
evaluate!( tmp, calc, r::Number)
evaluate_d!(tmpd, calc, r::Number)
```
which in turn are implemented as
```
evaluate(calc, r)
evaluate_d(calc, r)
```
A new implementation of a `PairPotential` may overload these definitions
at any of these three levels of implementation.
### Hessians and Preconditioners
The hessian implementation is less concerned about memory management. The
thought is that once we are using hessians all hopes to keep memory under
control is out the window anyhow. Therefore, there is only one hessian
implementation - for `SitePotential`s at least - based on
```{julia}
hessian_pos(calc, at)
```
which allocates temporary arrays for `calc` via
```{julia}
tmpdd = alloc_temp_dd(calc, N)
```
where `N` is again the maximum number of neighbours. It also allocates a
temporary storage `hEs` for the hessian blocks. (This does *not* need to be
in `tmpdd` now!) Then the hessian assembly will call
```{julia}
evaluate_dd(hEs, tmp, calc, R::AbstractVector{<:JVec})
```
For preconditioners the framework is the same but `evaluate_dd` is
replaced by `precon`.
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.8.2 | 2a9bcb7006a0159194d54c9c54c2b933b77ea41d | docs | 2113 |
## Installing numba and llvmlite correctly
This will probably be needed to get `chemview` to run, though at the moment
it seems `ipywidgets` is the real culprit and there is little hope for
a quick fix.
```
git clone https://github.com/numba/llvmlite
cd llvmlite
LLVM_CONFIG=/Users/ortner/gits/julia/usr/tools/llvm-config python setup.py install
LLVM_CONFIG=/Users/ortner/gits/julia/usr/tools/llvm-config pip install numba
```
then start `ipython` and check that `import numba` works, then start Julia
and check that `using PyCall; @pyimport numba` works as well.
## (Old) Alternative Installation Instructions for `imolecule`
If Option 1 fails, then try the following instructions, which
were only tested on OS X.
To install `imolecule` simply type
```bash
pip install imolecule
```
in a terminal.
Installing OpenBabel is relatively straightforward; the key issue is to get
the Python bindings set up correctly, especially since there are normally
multiple Python versions on an OS X system (Apple, homebrew and anaconda).
The following instructions worked for 2.3.90, but make sure to change the SWIG version
number directories as needed:
```bash
conda install cmake lxml swig
git clone https://github.com/openbabel/openbabel.git
cd openbabel
cmake ../openbabel-2.3.2 -DPYTHON_BINDINGS=ON -DRUN_SWIG=ON -DCMAKE_INSTALL_PREFIX=~/anaconda -DPYTHON_INCLUDE_DIR=~/anaconda/include/python2.7 -DCMAKE_LIBRARY_PATH=~/anaconda/lib -DSWIG_DIR=~/anaconda/share/swig/3.0.2/ -DSWIG_EXECUTABLE=~/anaconda/bin/swig -DPYTHON_LIBRARY=~/anaconda/lib/libpython2.7.so
make
make install
```
This should have installed all libraries and python packages in `~/anaconda`
and the data files in `/usr/local/share/openbabel/2.3.90/`. To tell `babel`
where to find them, the following lines must be added to `~/.bash_profile`:
```bash
export BABEL_DATADIR="/usr/local/share/openbabel/2.3.90/"
export BABEL_LIBDIR="/Users/ortner/anaconda/lib/openbabel/2.3.90/"
```
<!--
(Update: the configuration can be written directly to a JSON file, which
ought to circumvent the need for OpenBabel. Need to test this on a clean system.)
-->
| JuLIP | https://github.com/JuliaMolSim/JuLIP.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 534 | using Documenter, BitInformation
makedocs(
format = Documenter.HTML(
prettyurls = get(ENV, "CI", nothing) == "true"),
sitename="BitInformation.jl",
authors="M Klöwer",
modules=[BitInformation],
pages=["Home"=>"index.md",
"Bitwise information"=>"bitinformation.md",
"Transformations"=>"transformations.md",
"Rounding"=>"rounding.md",
"Function index"=>"functions.md"]
)
deploydocs(
repo = "github.com/milankl/BitInformation.jl.git",
devbranch = "main"
) | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 1130 | module BitInformation
# ROUNDING
export shave, set_one, groom, halfshave,
shave!, set_one!, groom!, halfshave!, round!
# TRANSFORMATIONS
export bittranspose, bitbacktranspose,
xor_delta, unxor_delta, xor_delta!, unxor_delta!,
signed_exponent, biased_exponent,
bitarray
# INFORMATION
export bitinformation, mutual_information, redundancy, bitpattern_entropy,
bitcount, bitcount_entropy, bitpaircount, bit_condprobability,
bit_condentropy
import StatsBase: entropy
import Distributions: quantile, Normal
# Base method extensions
include("uint_types.jl")
# print and conversions
include("bitstring.jl")
include("bitarray.jl")
# transformations
include("bittranspose.jl")
include("xor_delta.jl")
include("signed_exponent.jl")
# rounding
include("round_nearest.jl")
include("shave_set_groom.jl")
# information
include("permutations.jl")
include("bitcount.jl")
include("mutual_information.jl")
include("bitpattern_entropy.jl")
include("remove_insignificant.jl")
end
| BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 1165 | function bitarray(A::AbstractArray{T}) where T
nbits = 8*sizeof(T) # number of bits in T
UIntN = Base.uinttype(T) # UInt type corresponding to T
# allocate BitArray with additional dimension for the bits
B = BitArray(undef,nbits,size(A)...)
indices = CartesianIndices(A)
for i in eachindex(A) # every element in A
a = reinterpret(UIntN,A[i]) # as UInt
mask = UIntN(1) # mask to isolate jth bit
for j in 0:nbits-1 # loop from less to more significant bits
bit = (a & mask) >> j # isolate bit (=true/false)
B[nbits-j,indices[i]] = bit # set BitArray entry to isolated bit in A
mask <<= 1 # shift mask towards more significant bit
end
end
return B
end
function bitmap(A::AbstractMatrix;dim::Int=1)
@assert dim in (1,2) "dim has to be 1 or 2, $dim provided."
#TODO bitordering for dim=2 is currently off
n,m = size(A)
B = bitarray(A)
nbits,_ = size(B)
Br = reshape(B,nbits*n,:)
Br = dim == 1 ? Br : Br'
return Br
end
| BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 7634 | """
n = bitcount(A::AbstractArray{T},i::Int) where {T<:Unsigned}
Counts the occurences of the 1-bit in bit position i across all elements of A."""
function bitcount(A::AbstractArray{T},i::Int) where {T<:Unsigned}
nbits = sizeof(T)*8 # number of bits in T
@boundscheck i <= nbits || throw(error("Can't count bit $b for $N-bit type $T."))
c = 0 # counter
shift = nbits-i # shift bit i in least significant position
mask = one(T) << shift # mask to isolate the bit in position i
@inbounds for a in A
c += (a & mask) >> shift # to have either 0x0 or 0x1 to increase counter
end
return c
end
"""
C = bitcount(A::AbstractArray{T}) where {T<:Union{Integer,AbstractFloat}}
Counts the occurences of the 1-bit in every bit position across all elements of `A`.
Returns a counter array `C::Vector{Int}` such that the first entries represents
the first bit in elements of type `T`, e.g. the sign bit for floats."""
function bitcount(A::AbstractArray{T}) where {T<:Union{Integer,AbstractFloat}}
nbits = 8*sizeof(T) # determine the size [bit] of elements in A
C = zeros(Int,nbits)
Auint = reinterpret(Base.uinttype(T),A)
# loop over bit positions and for each count through all elements in A
# outer loop: bit position, inner loop: all elements in a
# note this is faster than swapping inner & outer loop
@inbounds for i in 1:nbits
C[i] = bitcount(Auint,i)
end
return C
end
"""
H = bitcount_entropy(A::AbstractArray{T},base::Real=2) where {T<:Union{Integer,AbstractFloat}}
Returns a vector `H` of entropies for the occurence of 0,1 in every bit position in `T` across elements of `A`.
Makes use of the `bitcount` functions and calculates the entropy from the probability of the 0 and 1 bit.
The base `base` is by default 2, such that the unit of entropy is bit."""
function bitcount_entropy( A::AbstractArray{T}, # input array
base::Real=2 # entropy with base
) where {T<:Union{Integer,AbstractFloat}}
nbits = 8*sizeof(T) # number of bits in T
nelements = length(A)
C = bitcount(A) # count 1 bits for each bit position
H = zeros(nbits) # allocate entropy for each bit position
@inbounds for i in 1:nbits # loop over bit positions
p = C[i]/nelements # probability of bit 1
H[i] = entropy([p,1-p],base) # entropy based on p
end
return H
end
"""
bitpair_count!(C::Array{Int,3},a::T,b::T) where {T<:Integer}
Update counter array C of size nbits x 2 x 2 for every 00|01|10|11-bitpairing in a,b.
`nbits` is the number of bits in type `T`."""
function bitpair_count!(C::Array{Int,3},a::T,b::T) where {T<:Integer}
nbits = 8*sizeof(T)
mask = one(T) # start with least significant bit
@inbounds for i in 0:nbits-1 # loop from least to most significant bit
j = 1+((a & mask) >>> i) # isolate that bit in a,b
k = 1+((b & mask) >>> i) # and move to 0x0 or 0x1s
C[nbits-i,j,k] += 1 # to be used as index j,k to increase counter C
mask <<= 1 # shift mask to get the next significant bit
end
end
"""
C = bitpair_count(A::AbstractArray{T},B::AbstractArray{T}) where {T<:Union{Integer,AbstractFloat}}
Returns counter array C of size nbits x 2 x 2 for every 00|01|10|11-bitpairing in elements of A,B.
`nbits` is the number of bits in type `T`."""
function bitpair_count( A::AbstractArray{T},
B::AbstractArray{T}
) where {T<:Union{Integer,AbstractFloat}}
@assert size(A) == size(B) "Size of A=$(size(A)) does not match size of B=$(size(B))"
nbits = 8*sizeof(T) # number of bits in eltype(A),eltype(B)
C = zeros(Int,nbits,2,2) # array of bitpair counters
# reinterpret arrays A,B as UInt (no mem allocation required)
Auint = reinterpret(Base.uinttype(T),A)
Buint = reinterpret(Base.uinttype(T),B)
# loop over all elements in A,B pairwise, inner loop (within bitpair_count!): bit positions
# note this is faster than swapping inner & outer loop
for (a,b) in zip(Auint,Buint)
bitpair_count!(C,a,b) # count the bits and update counter array C
end
return C
end
"""
C = bitpair_count(A::AbstractArray{T},mask::AbstractArray{Bool}) where {T<:Union{Integer,AbstractFloat}}
Returns counter array C of size nbits x 2 x 2 for every 00|01|10|11-bitpairing in elements of A,B where neither
are masked as determined from `mask`. `nbits` is the number of bits in type `T`."""
function bitpair_count( A::AbstractArray{T},
mask::AbstractArray{Bool}
) where {T<:Union{Integer,AbstractFloat}}
@assert size(A) == size(mask) "Size of A=$(size(A)) does not match size of its mask=$(size(mask))"
nbits = 8*sizeof(T) # number of bits in eltype(A)
C = zeros(Int, nbits, 2, 2) # array of bitpair counters
# reinterpret arrays A,B as UInt (no mem allocation required)
Auint = reinterpret(Base.uinttype(T), A)
# always mask the last element in every column to avoid counting bitpairs across boundaries
n = size(A, 1)
@inbounds for jk in CartesianIndices(size(A)[2:end]) # 2nd, 3rd, ... dimension
for i in 1:n-1 # first dimension but skip the last element
if ~(mask[i, jk] | mask[i+1, jk]) # if neither entry is masked
bitpair_count!(C, Auint[i, jk], Auint[i+1, jk]) # count all bits and increase counter C
end
end
end
return C
end
# """Update counter array C of size nbits x 2 x 2 for every 00|01|10|11-bitpairing in a,b."""
# function bitpair_count!(C::Array{Int,3}, # counter array nbits x 2 x 2
# A::AbstractArray{T}, # input array A
# B::AbstractArray{T}, # input array B
# i::Int # bit position
# ) where {T<:Integer}
# nbits = 8*sizeof(T) # number of bits in T
# shift = nbits-i # shift bit i in least significant position
# mask = one(T) << shift # mask to isolate the bit in position i
# @inbounds for (a,b) in zip(A,B) # loop over all elements in A,B pairwise
# j = 1+((a & mask) >>> shift) # isolate bit i in a,b
# k = 1+((b & mask) >>> shift) # and move to 0x0 or 0x1
# C[i,j,k] += 1 # to be used as index j,k to increase counter C
# end
# end
# """Returns counter array C of size nbits x 2 x 2 for every 00|01|10|11-bitpairing in elements of A,B."""
# function bitpair_count( A::AbstractArray{T},
# B::AbstractArray{T}
# ) where {T<:Union{Integer,AbstractFloat}}
# @assert size(A) == size(B) "Size of A=$(size(A)) does not match size of B=$(size(B))"
# nbits = 8*sizeof(T) # number of bits in eltype(A),eltype(B)
# C = zeros(Int,nbits,2,2) # array of bitpair counters
# # reinterpret arrays A,B as UInt (no mem allocation required)
# Auint = reinterpret(Base.uinttype(T),A)
# Buint = reinterpret(Base.uinttype(T),B)
# for i in 1:nbits
# bitpair_count!(C,Auint,Buint,i) # count the bits and update counter array C
# end
# return C
# end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 2091 | """
H = bitpattern_entropy(A::AbstractArray,base::Real=2)
Calculates the bit pattern entropy `H` for an array `A` by reinterpreting the elements
as UInts and sorting them to avoid creating a histogram. The bit pattern entropy is the
entropy from occurences of every possible bitpattern in `T` in elements of `A`. The unit
of entropy is given by base `base`, such that for the default `base=2` it is bits."""
function bitpattern_entropy(A::AbstractArray{T},base::Real=2) where T
return bitpattern_entropy!(copy(A),base) # copy of array to avoid in-place changes to A
end
"""
H = bitpattern_entropy!(A::AbstractArray,base::Real=2)
Calculates the bit pattern entropy `H` for an array `A` by reinterpreting the elements
as UInts and sorting them to avoid creating a histogram. The bit pattern entropy is the
entropy from occurences of every possible bitpattern in `T` in elements of `A`. The unit
of entropy is given by base `base`, such that for the default `base=2` it is bits.
In-place version of `bitpattern_entropy` that will sort `A`. Use `bitpattern_entropy` if
changes to `A` are to be avoided."""
function bitpattern_entropy!(A::AbstractArray{T},base::Real=2) where T
# reinterpret to UInt then sort in-place for minimal memory allocation
sort!(reinterpret(Base.uinttype(T),vec(A)))
n = length(A)
E = 0.0 # entropy
m = 1 # counter, start with 1 as only bitwise-same elements are counted
for i in 1:n-1
@inbounds if A[i] == A[i+1] # check whether next entry belongs to the same bin in histogram
m += 1 # increase counter
else
p = m/n # probability/frequency of ith bit pattern
E -= p*log(p) # entropy contribution
m = 1 # start with 1, A[i+1] is already 1st element of next bin
end
end
p = m/n # complete loop for last bin
E -= p*log(p) # entropy contribution of last bin
E /= log(base) # convert to given base, 2 i.e. [bit] by default
return E
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 457 | """
s = bitstring(x::T,mode::Symbol) where {T<:AbstractFloat}
Bitstring function for floats with a split-mode for `mode=:split` that splits
the bitstring into sign, exponent and significant bits."""
function Base.bitstring(x::T,mode::Symbol) where {T<:AbstractFloat}
if mode == :split
bstr = bitstring(x)
n = Base.exponent_bits(T)
return "$(bstr[1]) $(bstr[2:n+1]) $(bstr[n+2:end])"
else
bitstring(x)
end
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 4654 | const DEFAULT_BLOCKSIZE=2^14
"""Transpose the bits (aka bit shuffle) of an array to place sign bits, etc. next to each
other in memory. Back transpose via bitbacktranspose(). Inplace version that requires a
preallocated output array At, which must contain 0 bits everywhere."""
function bittranspose!( ::Type{UIntT}, # UInt corresponding to T
At::AbstractArray{T}, # transposed array to be filled
A::AbstractArray{T}; # original array
blocksize::Int=DEFAULT_BLOCKSIZE) where {UIntT<:Unsigned,T}
@boundscheck size(A) == size(At) || throw("Input arrays must be of same size.")
@boundscheck sizeof(UIntT) == sizeof(T) || throw("Array elements do not match in bitsize.")
nbits = sizeof(T)*8
N = length(A)
# At .= zero(T) # make sure output array is zero
nblocks = (N-1) ÷ blocksize + 1 # number of blocks
@inbounds for nb in 1:nblocks
lastindex = min(nb*blocksize,N)
Ablock = view(A,(nb-1)*blocksize+1:lastindex)
Atblock = view(At,(nb-1)*blocksize+1:lastindex)
i = 0 # counter for transposed bits
for bi in 1:nbits
# mask to extract bit bi in each element of A
mask = one(UIntT) << (nbits-bi)
# walk through elements in A first, then change bit-position
# this comes with disadvantage that A has to be read nbits-times
# but allows for more natural indexing, as all the sign bits are
# read first, and so on.
for (ia,a) in enumerate(Ablock)
ui = reinterpret(UIntT,a)
# mask non-bi bits and
# (1) shift by nbits-bi >> to the right, either 0x0 or 0x1
# (2) shift by (nbits-1) - (i % nbits) << to the left
# combined this is: >> ((i % nbits)-bi+1)
bit = (ui & mask) >> ((i % nbits)-bi+1)
# the first nbits elements go into same b in B, then next b
idx = (i ÷ nbits) + 1
atui = reinterpret(UIntT,Atblock[idx])
Atblock[idx] = reinterpret(T,atui | bit)
i += 1
end
end
end
return At
end
"""Transpose the bits (aka bit shuffle) of an array to place sign bits, etc. next to each
other in memory. Back transpose via bitbacktranspose()."""
function bittranspose(A::AbstractArray{T};kwargs...) where T
UIntT = Base.uinttype(T) # get corresponding UInt to T
At = fill(reinterpret(T,zero(UIntT)),size(A)) # preallocate with zeros (essential)
bittranspose!(UIntT,At,A;kwargs...)
return At
end
"""Backtranspose of bittranspose()."""
function bitbacktranspose!( ::Type{UIntT}, # UInt equiv to T
A::AbstractArray{T}, # backtransposed output
At::AbstractArray{T}; # transposed input
blocksize::Int=DEFAULT_BLOCKSIZE) where {UIntT<:Unsigned,T}
@boundscheck size(A) == size(At) || throw("Input arrays must be of same size.")
@boundscheck sizeof(UIntT) == sizeof(T) || throw("Array elements do not match in bitsize.")
nbits = sizeof(T)*8
N = length(At)
# A .= zero(T) # make sure output array is zero
nblocks = (N-1) ÷ blocksize + 1 # number of blocks
@inbounds for nb in 1:nblocks
lastindex = min(nb*blocksize,N)
Ablock = view(A,(nb-1)*blocksize+1:lastindex)
Atblock = view(At,(nb-1)*blocksize+1:lastindex)
nelements = length(Atblock) # = blocksize except for the last
# block where usually smaller
i = 0 # counter for transposed bits
for (ia,a) in enumerate(Atblock)
ui = reinterpret(UIntT,a)
for bi in 1:nbits
# mask to extract bit bi in each element of A
mask = one(UIntT) << (nbits-bi)
# mask non-bi bits and
# (1) shift by nbits-bi >> to the right, either 0x0 or 0x1
# (2) shift by (nbits-1) - (i ÷ nblockfloat) << to the left
# combined this is: >> ((i ÷ nbits)-bi+1)
bit = (ui & mask) >> ((i ÷ nelements)-bi+1)
# the first nbits elements go into same a in A, then next a
idx = (i % nelements) + 1
aui = reinterpret(UIntT,Ablock[idx])
Ablock[idx] = reinterpret(T,aui | bit)
i += 1
end
end
end
return A
end
"""Backtranspose the bits of array A that were previously transposed with bittranspose()."""
function bitbacktranspose(At::AbstractArray{T};kwargs...) where T
UIntT = Base.uinttype(T) # get corresponding UInt to T
A = fill(reinterpret(T,zero(UIntT)),size(At)) # preallocate with zeros (essential)
bitbacktranspose!(UIntT,A,At;kwargs...)
return A
end
| BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 9306 | """Mutual information from the joint probability mass function p
of two variables X,Y. p is an nx x ny array which elements represent
the probabilities of observing x~X and y~Y."""
function mutual_information(p::AbstractArray{T,2},base::Real=2) where T
@assert sum(p) ≈ one(T) "Entries in p have to sum to 1"
@assert all(p .>= zero(T)) "Entries in p have to be >= 1"
nx,ny = size(p) # events X are 1st dim, Y is 2nd
py = sum(p,dims=1) # marginal probabilities of y
px = sum(p,dims=2) # marginal probabilities of x
M = zero(T) # mutual information M
for j in 1:ny # loop over all entries in p
for i in 1:nx
# add entropy only for non-zero entries in p
if p[i,j] > zero(T)
M += p[i,j]*log(p[i,j]/px[i]/py[j])
end
end
end
M /= log(base) # convert to given base
end
"""Mutual bitwise information of the elements in input arrays A,B.
A and B have to be of same size and eltype."""
function mutual_information(A::AbstractArray{T},
B::AbstractArray{T};
set_zero_insignificant::Bool=true,
confidence::Real=0.99
) where {T<:Union{Integer,AbstractFloat}}
nelements = length(A) # number of elements in each A and B
nbits = 8*sizeof(T) # number of bits in eltype(A),eltype(B)
C = bitpair_count(A,B) # nbits x 2 x 2 array of bitpair counters
M = zeros(nbits) # allocate mutual information array
P = zeros(2,2) # allocate joint probability mass function
@inbounds for i in 1:nbits # mutual information for every bit position
for j in 1:2, k in 1:2 # joint prob mass from counter C
P[j,k] = C[i,j,k]/nelements
end
M[i] = mutual_information(P)
end
# remove information that is insignificantly different from a random 50/50
if set_zero_insignificant
set_zero_insignificant!(M,nelements,confidence)
end
return M
end
"""
M = bitinformation(A::AbstractArray{T}) where {T<:Union{Integer,AbstractFloat}}
Bitwise real information content of array `A` calculated from the bitwise mutual information
in adjacent entries in `A`. Optional keyword arguments
- `dim::Int=1` computes the bitwise information along dimension `dim`.
- `masked_value::T=NaN` masks all entries in `A` that are equal to `masked_value`.
- `set_zero_insignificant::Bool=true` set insignificant information to zero.
- `confidence::Real=0.99` confidence level for `set_zero_insignificant`.
"""
function bitinformation(A::AbstractArray{T};
dim::Int=1,
masked_value::Union{T, Nothing}=nothing,
kwargs...) where {T<:Union{Integer, AbstractFloat}}
# create a BitArray mask if a masked_value is provided, use === to also allow NaN comparison
isnothing(masked_value) || return bitinformation(A, A .=== masked_value; dim, kwargs...)
A = permute_dim_forward(A, dim) # Permute A to take adjacent entry in dimension dim
n = size(A, 1) # n elements in dim
# create a two views on A for pairs of adjacent entries, dim is always 1st dimension after permutation
A1view = selectdim(A, 1, 1:n-1) # no adjacent entries in A array bounds
A2view = selectdim(A, 1, 2:n) # for same indices A2 is the adjacent entry to A1
return mutual_information(A1view, A2view; kwargs...)
end
"""
M = bitinformation(A::AbstractArray{T}, mask::BitArray) where {T<:Union{Integer,AbstractFloat}}
Bitwise real information content of array `A` calculated from the bitwise mutual information
in adjacent entries in A along dimension `dim` (optional keyword). Array `A` is masked through
trues in entries of the mask `mask`. Masked elements are ignored in the bitwise information calculation."""
function bitinformation(A::AbstractArray{T},
mask::BitArray;
dim::Int=1,
set_zero_insignificant::Bool=true,
confidence::Real=0.99) where {T<:Union{Integer, AbstractFloat}}
@boundscheck size(A) == size(mask) || throw(BoundsError)
nbits = 8*sizeof(T)
# Permute A and mask to take adjacent entry in dimension dim
A = permute_dim_forward(A, dim)
mask = permute_dim_forward(mask, dim)
C = bitpair_count(A, mask) # nbits x 2 x 2 array of bitpair counters
nelements = sum(view(C, 1, :, :)) # depending on mask nelements changes so obtain via C
@assert nelements > 0 "Mask has $(sum(.~mask)) unmasked values, 0 entries are adjacent."
M = zeros(nbits) # allocate mutual information array
P = zeros(2, 2) # allocate joint probability mass function
@inbounds for i in 1:nbits # mutual information for every bit position
for j in 1:2, k in 1:2 # joint prob mass from counter C
P[j,k] = C[i,j,k]/nelements
end
M[i] = mutual_information(P)
end
# remove information that is insignificantly different from a random 50/50
if set_zero_insignificant
set_zero_insignificant!(M,nelements,confidence)
end
return M
end
"""
R = redundancy(A::AbstractArray{T},B::AbstractArray{T}) where {T<:Union{Integer,AbstractFloat}}
Bitwise redundancy of two arrays A,B. Redundancy is a normalised measure of the mutual information:
1 for always identical/opposite bits, 0 for no mutual information."""
function redundancy(A::AbstractArray{T},
B::AbstractArray{T}) where {T<:Union{Integer,AbstractFloat}}
M = mutual_information(A,B) # mutual information
HA = bitcount_entropy(A) # entropy of A
HB = bitcount_entropy(B) # entropy of B
R = ones(size(M)...) # allocate redundancy R
for i in eachindex(M) # loop over bit positions
HAB = HA[i]+HB[i] # sum of entropies of A,B
if HAB > 0 # entropy = 0 means A,B are fully redundant
R[i] = 2*M[i]/HAB # symmetric redundancy
end
end
return R
end
# """Mutual bitwise information of the elements in input arrays A,B.
# A and B have to be of same size and eltype."""
# function bitinformation(A::AbstractArray{T},
# B::AbstractArray{T},
# n::Int) where {T<:Union{Integer,AbstractFloat}}
# @assert size(A) == size(B)
# nelements = length(A)
# nbits = 8*sizeof(T)
# # array of counters, first dim is from last bit to first
# C = [zeros(Int,2^min(i,n+1),2) for i in nbits:-1:1]
# for (a,b) in zip(A,B) # run through all elements in A,B pairwise
# bitcount!(C,a,b,n) # count the bits and update counter array C
# end
# # P is the join probabilities mass function
# P = [C[i]/nelements for i in 1:nbits]
# M = [mutual_information(p) for p in P]
# # filter out rounding errors
# M[isapprox.(M,0,atol=10eps(Float64))] .= 0
# return M
# end
# """Update counter array of size nbits x 2 x 2 for every
# 00|01|10|11-bitpairing in a,b."""
# function bitcount!(C::Array{Int,3},a::T,b::T) where {T<:AbstractFloat}
# uia = reinterpret(Base.uinttype(T),a)
# uib = reinterpret(Base.uinttype(T),b)
# bitcount!(C,uia,uib)
# end
# """Update counter array of size nbits x 2 x 2 for every
# 00|01|10|11-bitpairing in a,b."""
# function bitcount!(C::Vector{Matrix{Int}},a::T,b::T,n::Int) where {T<:AbstractFloat}
# uia = reinterpret(Base.uinttype(T),a)
# uib = reinterpret(Base.uinttype(T),b)
# bitcount!(C,uia,uib,n)
# end
# """Update counter array of size nbits x 2 x 2 for every
# 00|01|10|11-bitpairing in a,b."""
# function bitcount!(C::Vector{Matrix{Int}},a::T,b::T,n::Int) where {T<:Integer}
# nbits = 8*sizeof(T)
# for i = nbits:-1:1
# @boundscheck size(C[end-i+1],1) == 2^min(i,n+1) || throw(BoundsError())
# end
# maskb = one(T) << (nbits-1)
# maska = reinterpret(T,signed(maskb) >> n)
# for i in 1:nbits
# j = 1+((a & maska) >>> max(nbits-n-i,0))
# k = 1+((b & maskb) >>> (nbits-i))
# C[i][j,k] += 1
# maska >>>= 1 # shift through nbits
# maskb >>>= 1
# end
# end
# """Calculate the bitwise redundancy of two arrays A,B.
# Multi-bit predictor version which includes n lesser significant bit
# as additional predictors in A for the mutual information to account
# for round-to-nearest-induced carry bits. Redundancy is normalised
# by the entropy of A. To be used for A being the reference array
# and B an approximation of it."""
# function redundancy(A::AbstractArray{T},
# B::AbstractArray{T},
# n::Int) where {T<:Union{Integer,AbstractFloat}}
# mutinf = bitinformation(A,B,n) # mutual information
# HA = bitcount_entropy(A) # entropy of A
# R = mutinf./HA # redundancy (asymmetric)
# R[iszero.(HA)] .= 0.0 # HA = 0 creates NaN
# return R
# end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 609 | """
permute_dim_forward(A::AbstractArray,dim::Int)
Permute array `A` such that dimension `dim` is the first dimension by circular shifting its dimensions.
Returns a `PermutedDimsArray`. For `A` being a matrix this is equivalent to a transpose, for more dimensions
the dimensions are shifted circular. E.g. An array of size `(3,4,5,6,7)` and `dim=3` will return a PermutedDimsArray
of size `(5,6,7,3,4)`."""
function permute_dim_forward(A::AbstractArray,dim::Int)
A_ndims = ndims(A)
@boundscheck dim <= A_ndims || throw(BoundsError)
return PermutedDimsArray(A,circshift(1:A_ndims,-dim+1))
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 1477 | """
p₁ = binom_confidence(n::Int,c::Real)
Returns the probability `p₁` of successes in the binomial distribution (p=1/2) of
`n` trials with confidence `c`.
# Example
At c=0.95, i.e. 95% confidence, n=1000 tosses of
a coin will yield not more than
```julia
julia> p₁ = BitInformation.binom_confidence(1000,0.95)
0.5309897516152281
```
about 53.1% heads (or tails)."""
function binom_confidence(n::Int,c::Real)
p = 0.5 + quantile(Normal(),1-(1-c)/2)/(2*sqrt(n))
return min(1.0,p) # cap probability at 1 (only important for n small)
end
"""
Hf = binom_free_entropy(n::Int,c::Real,base::Real=2)
Returns the free entropy `Hf` associated with `binom_confidence`."""
function binom_free_entropy(n::Int,c::Real,base::Real=2)
p = binom_confidence(n,c)
return 1 - entropy([p,1-p],base)
end
"""
set_zero_insignificant!(H::Vector,nelements::Int,confidence::Real)
Remove binary information in the vector `H` of entropies that is insignificantly
different from a random 50/50 by setting it to zero."""
function set_zero_insignificant!(H::Vector,nelements::Int,confidence::Real)
Hfree = binom_free_entropy(nelements,confidence) # free entropy of random 50/50 at trial size
# get chance p for 1 (or 0) from binom distr
@inbounds for i in eachindex(H)
H[i] = H[i] <= Hfree ? 0 : H[i] # set zero what's insignificant
end
return H
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 6212 | const IEEEFloat_and_complex = Union{Float16,Float32,Float64,ComplexF16,ComplexF32,ComplexF64}
"""Shift integer to push the mantissa in the right position. Used to determine
round up or down in the tie case. `keepbits` is the number of mantissa bits to
be kept (i.e. not zero-ed) after rounding. Special case: shift is -1 for
keepbits == significand_bits(T) to avoid a round away from 0 where no rounding
should be applied."""
function get_shift(::Type{T},keepbits::Integer) where {T<:Base.IEEEFloat}
shift = Base.significand_bits(T) - keepbits # normal case
shift -= keepbits == Base.significand_bits(T) # to avoid round away from 0
return shift
end
"""Returns for a Float-type `T` and `keepbits`, the number of mantissa bits to be
kept/non-zeroed after rounding, half of the unit in the last place as unsigned integer.
Used in round (nearest) to add ulp/2 just before round down to achieve round nearest.
Technically ulp/2 here is just smaller than ulp/2 which rounds down the ties. For
a tie round up +1 is added in `round(T,keepbits)`."""
function get_ulp_half( ::Type{T},
keepbits::Integer
) where {T<:Base.IEEEFloat}
# convert to signed for arithmetic bitshift
# trick to push in 0s from the left and 1s from the right
return ~unsigned(signed(~Base.significand_mask(T)) >> (keepbits+1))
end
"""Returns a mask that's 1 for all bits that are kept after rounding and 0 for the
discarded trailing bits. E.g.
```
julia> get_keep_mask(Float16,5)
0xffe0
```."""
function get_keep_mask( ::Type{T},
keepbits::Integer
) where {T<:Base.IEEEFloat}
# convert to signed for arithmetic bitshift
# trick to push in 1s from the left and 0s from the right
return unsigned(signed(~Base.significand_mask(T)) >> keepbits)
end
"""Returns a mask that's `1` for a given `mantissabit` and `0` else. Mantissa bits
are positive for the mantissa (`mantissabit = 1` is the first mantissa bit), `mantissa = 0`
is the last exponent bit, and negative for the other exponent bits."""
function get_bit_mask( ::Type{T},
mantissabit::Integer
) where {T<:Base.IEEEFloat}
# push the sign mask (1000....) in the right position
return Base.sign_mask(T) >> (Base.exponent_bits(T) + mantissabit)
end
"""IEEE's round to nearest tie to even for Float16/32/64."""
function Base.round(x::T, # Float to be rounded
ulp_half::UIntT, # obtain from get_ulp_half,
shift::Integer, # get_shift, and
keepmask::UIntT # get_keep_mask
) where {T<:Base.IEEEFloat,UIntT<:Unsigned}
ui = reinterpret(UIntT,x) # bitpattern as uint
ui += ulp_half + ((ui >> shift) & one(UIntT)) # add ulp/2 with tie to even
return reinterpret(T,ui & keepmask) # set trailing bits to zero
end
function Base.round(x::Complex, # Complex float to be rounded
ulp_half::UIntT, # obtain from get_ulp_half,
shift::Integer, # get_shift, and
keepmask::UIntT # get_keep_mask
) where {UIntT<:Unsigned}
a = round(real(x),ulp_half,shift,keepmask)
b = round(imag(x),ulp_half,shift,keepmask)
return a+im*b
end
"""Scalar version of `round(::Float,keepbits)` that first obtains
`shift, ulp_half, keep_mask` and then rounds."""
function Base.round(x::T,
keepbits::Integer
) where {T<:Base.IEEEFloat}
return round(x,get_ulp_half(T,keepbits),get_shift(T,keepbits),get_keep_mask(T,keepbits))
end
function Base.round(x::Complex{T},keepbits::Integer) where T
ulp_half = get_ulp_half(T,keepbits)
shift = get_shift(T,keepbits)
keepmask = get_keep_mask(T,keepbits)
return round(x,ulp_half,shift,keepmask)
end
"""IEEE's round to nearest tie to even for a float array `X` in-place. Calculates from `keepbits`
only once the variables `ulp_half`, `shift` and `keep_mask` and loops over every element of the
array."""
function round!(X::AbstractArray{T}, # any array with element type T
keepbits::Integer # how many mantissa bits to keep
) where {T<:IEEEFloat_and_complex} # constrain element type to (complex) Float16/32/64
ulp_half = get_ulp_half(real(T),keepbits) # half of unit in last place (ulp)
shift = get_shift(real(T),keepbits) # integer used for bitshift
keep_mask = get_keep_mask(real(T),keepbits) # mask to zero trailing mantissa bits
@inbounds for i in eachindex(X) # apply rounding to each element
X[i] = round(X[i],ulp_half,shift,keep_mask)
end
return X
end
"""IEEE's round to nearest tie to even for a float array `X` which returns a rounded copy of `X`."""
function Base.round(X::AbstractArray{T}, # any array with element type T
keepbits::Integer # mantissa bits to keep
) where {T<:IEEEFloat_and_complex} # constrain element type to (complex) Float16/32/64
Xcopy = copy(X) # copy array to avoid in-place changes
round!(Xcopy,keepbits) # in-place round the copied array
return Xcopy
end
"""Checks a given `mantissabit` of `x` for eveness. 1=odd, 0=even. Mantissa bits
are positive for the mantissa (`mantissabit = 1` is the first mantissa bit), `mantissa = 0`
is the last exponent bit, and negative for the other exponent bits."""
function Base.iseven(x::T,
mantissabit::Integer
) where {T<:Base.IEEEFloat}
bitmask = get_bit_mask(T,mantissabit)
return 0x0 == reinterpret(typeof(bitmask),x) & bitmask
end
"""Checks a given `mantissabit` of `x` for oddness. 1=odd, 0=even. Mantissa bits
are positive for the mantissa (`mantissabit = 1` is the first mantissa bit), `mantissa = 0`
is the last exponent bit, and negative for the other exponent bits."""
Base.isodd(x::T,mantissabit::Integer) where {T<:Base.IEEEFloat} = ~iseven(x,mantissabit) | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 5706 | """Bitshaving for floats. Sets trailing bits to 0 (round towards zero).
`keepmask` is an unsigned integer with bits being `1` for bits to be kept,
and `0` for those that are shaved off."""
function shave( x::T,
keepmask::UIntT
) where {T<:Base.IEEEFloat,UIntT<:Unsigned}
ui = reinterpret(UIntT,x)
ui &= keepmask # set trailing bits to zero
return reinterpret(T,ui)
end
"""Halfshaving for floats. Replaces trailing bits with `1000...` a variant
of round nearest whereby the representable numbers are halfway between those
from shaving or IEEE's round nearest."""
function halfshave( x::T,
keepmask::UIntT,
bitmask::UIntT
) where {T<:Base.IEEEFloat,UIntT<:Unsigned}
ui = reinterpret(UIntT,x)
ui &= keepmask # set trailing bits to zero
ui |= bitmask # set first trailing bit to 1
return reinterpret(T,ui)
end
"""Bitsetting for floats. Replace trailing bits with `1`s (round away from zero).
`setmask` is an unsigned integer with bits being `1` for those that are set to one
and `0` otherwise, such that the bits to keep are unaffected."""
function set_one( x::T,
setmask::UIntT
) where {T<:Base.IEEEFloat,UIntT<:Unsigned}
ui = reinterpret(UIntT,x)
ui |= setmask # set trailing bits to 1
return reinterpret(T,ui)
end
"""Bitshaving of a float `x` given `keepbits` the number of mantissa bits to keep
after shaving."""
function shave(x::T,keepbits::Integer) where {T<:Base.IEEEFloat}
return shave(x,get_keep_mask(T,keepbits))
end
"""Halfshaving of a float `x` given `keepbits` the number of mantissa bits to keep
after halfshaving."""
function halfshave(x::T,keepbits::Integer) where {T<:Base.IEEEFloat}
return halfshave(x,get_keep_mask(T,keepbits),get_bit_mask(T,keepbits+1))
end
"""Bitsetting of a float `x` given `keepbits` the number of mantissa bits to keep
after setting."""
function set_one(x::T,keepbits::Integer) where {T<:Base.IEEEFloat}
return set_one(x,~get_keep_mask(T,keepbits))
end
"""In-place version of `shave` for any array `X` with floats as elements."""
function shave!(X::AbstractArray{T}, # any array with element type T
keepbits::Integer # how many mantissa bits to keep
) where {T<:Base.IEEEFloat} # constrain element type to Float16/32/64
keep_mask = get_keep_mask(T,keepbits) # mask to zero trailing mantissa bits
@inbounds for i in eachindex(X) # apply rounding to each element
X[i] = shave(X[i],keep_mask)
end
return X
end
"""In-place version of `halfshave` for any array `X` with floats as elements."""
function halfshave!(X::AbstractArray{T}, # any array with element type T
keepbits::Integer # how many mantissa bits to keep
) where {T<:Base.IEEEFloat} # constrain element type to Float16/32/64
keep_mask = get_keep_mask(T,keepbits) # mask to zero trailing mantissa bits
bit_mask = get_bit_mask(T,keepbits+1) # mask to set the first trailing bit to 1
@inbounds for i in eachindex(X) # apply rounding to each element
X[i] = halfshave(X[i],keep_mask,bit_mask)
end
return X
end
"""In-place version of `set_one` for any array `X` with floats as elements."""
function set_one!( X::AbstractArray{T}, # any array with element type T
keepbits::Integer # how many mantissa bits to keep
) where {T<:Base.IEEEFloat} # constrain element type to Float16/32/64
set_mask = ~get_keep_mask(T,keepbits) # mask to set trailing mantissa bits to 1
@inbounds for i in eachindex(X) # apply rounding to each element
X[i] = set_one(X[i],set_mask)
end
return X
end
"""Bitgrooming for a float arrays `X` keeping `keepbits` mantissa bits. In-place version
that shaves/sets the elements of `X` alternatingly."""
function groom!(X::AbstractArray{T}, # any array with element type T
keepbits::Integer # how many mantissa bits to keep
) where {T<:Base.IEEEFloat} # constrain element type to Float16/32/64
keep_mask = get_keep_mask(T,keepbits) # mask to zero trailing mantissa bits
set_mask = ~keep_mask # mask to set trailing mantissa bits to 1
n = length(X)
@inbounds for i in 1:2:n-1
X[i] = shave(X[i],keep_mask) # every second element is shaved
X[i+1] = set_one(X[i+1],set_mask) # every other 2nd element is set
end
# for arrays of uneven length shave last element (as exempted from loop)
@inbounds X[end] = n % 2 == 1 ? shave(X[end],keep_mask) : X[end]
return X
end
# Shave, halfshave, set_one, groom which returns a rounded copy of array `X` instead of
# chaning its elements in-place.
for func in (:shave,:halfshave,:set_one,:groom)
func! = Symbol(func,:!)
@eval begin
function $func( X::AbstractArray{T}, # any array with element type T
keepbits::Integer # how many mantissa bits to keep
) where {T<:Base.IEEEFloat} # constrain element type to Float16/32/64
Xcopy = copy(X) # copy to avoid in-place changes of X
$func!(Xcopy,keepbits) # in-place on X's copy
return Xcopy
end
end
end
"""Number of significant bits `nsb` given the number of significant digits `nsd`."""
nsb(nsd::Integer) = Integer(ceil(log(10)/log(2)*nsd)) | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 3743 | """In-place version of `signed_exponent(::Array)`."""
function signed_exponent!(A::AbstractArray{T}) where {T<:Base.IEEEFloat}
# sign&fraction mask
sfmask = Base.sign_mask(T) | Base.significand_mask(T)
emask = Base.exponent_mask(T)
esignmask = Base.sign_mask(T) >> 1 # exponent sign mask (1st exp bit)
sbits = Base.significand_bits(T)
bias = Base.exponent_bias(T)
@inbounds for i in eachindex(A)
ui = reinterpret(Unsigned,A[i])
sf = ui & sfmask # sign & fraction bits
e = (((ui & emask) >> sbits) % Int) - bias # de-biased exponent
eabs = abs(e) % typeof(ui) # magnitude of exponent
esign = e < 0 ? esignmask : zero(esignmask) # determine sign of exponent
esigned = esign | (eabs << sbits) # concatentate exponent
A[i] = reinterpret(T,sf | esigned) # concatenate everything back together
end
return A
end
"""In-place version of `biased_exponent(::Array)`. Inverse of `signed_exponent!"."""
function biased_exponent!(A::AbstractArray{T}) where {T<:Base.IEEEFloat}
# sign&fraction mask
sfmask = Base.sign_mask(T) | Base.significand_mask(T)
emask = Base.exponent_mask(T)
esignmask = Base.sign_mask(T) >> 1
eabsmask = emask & ~esignmask
sbits = Base.significand_bits(T)
bias = Base.uinttype(T)(Base.exponent_bias(T))
@inbounds for i in eachindex(A)
ui = reinterpret(Unsigned,A[i])
sf = ui & sfmask # sign & fraction bits
eabs = ((ui & eabsmask) >> sbits) # isolate sign-magnitude exponent
esign = (ui & esignmask) == esignmask ? true : false
ebiased = bias + (esign ? -eabs : eabs) # concatenate mag&sign and add bias
ebiased <<= sbits # shit exponent in position
# 10000..., i.e. negative zero in the sign-magintude exponent is mapped
# back to NaN/Inf to make signed_exponent fully reversible
ebiased = esign & (eabs == 0) ? emask : ebiased
A[i] = reinterpret(T,sf | ebiased) # concatenate everything back together
end
return A
end
"""
```julia
B = signed_exponent(A::AbstractArray{T}) where {T<:Base.IEEEFloat}
```
Converts the exponent bits of Float16,Float32 or Float64-arrays from its
IEEE standard biased-form into a sign-magnitude representation.
# Example
```julia
julia> bitstring(10f0,:split)
"0 10000010 01000000000000000000000"
julia> bitstring.(signed_exponent([10f0]),:split)[1]
"0 00000011 01000000000000000000000"
```
In the IEEE standard floats the exponent 3 is interpret from 0b10000010=130
via subtraction of the exponent bias of Float32 = 127. In sign-magnitude
representation the exponent is inferred from the first exponent (0) as sign bit
and a magnitude 2^1 + 2^1 = 3. NaN/Inf exponent bits are mapped to negative zero
in sign-magnitude representation which is exactly reversed with `biased_exponent`."""
function signed_exponent(A::Array{T}) where {T<:Union{Float16,Float32,Float64}}
B = copy(A)
return signed_exponent!(B)
end
function signed_exponent(f::T) where {T<:Union{Float16,Float32,Float64}}
return signed_exponent!([f])[1] # pack into array and unpack again
end
"""
```julia
B = biased_exponent(A::AbstractArray{T}) where {T<:Base.IEEEFloat}
```
Convert the signed exponents from `signed_exponent` back into the
standard biased exponents of IEEE floats."""
function biased_exponent(A::Array{T}) where {T<:Union{Float16,Float32,Float64}}
B = copy(A)
return biased_exponent!(B)
end
function biased_exponent(f::T) where {T<:Union{Float16,Float32,Float64}}
return biased_exponent!([f])[1] # pack into array and unpack again
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 747 | # define the uints for various formats
Base.uinttype(::Type{UInt8}) = UInt8
Base.uinttype(::Type{UInt16}) = UInt16
Base.uinttype(::Type{UInt32}) = UInt32
Base.uinttype(::Type{UInt64}) = UInt64
Base.uinttype(::Type{Int8}) = UInt8
Base.uinttype(::Type{Int16}) = UInt16
Base.uinttype(::Type{Int32}) = UInt32
Base.uinttype(::Type{Int64}) = UInt64
# uints for other types are identified by their byte size
Base.uinttype(::Type{T}) where T = Base.uinttype(sizeof(T)*8)
# or return the UInt type based on the number of bits
function Base.uinttype(nbits::Integer)
nbits == 8 && return UInt8
nbits == 16 && return UInt16
nbits == 32 && return UInt32
nbits == 64 && return UInt64
throw(error("Only n=8,16,32,64 bits supported."))
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 2420 | """Bitwise XOR delta. Elements include A are XORed with the previous one. The
first element is left unchanged.
E.g. [0b0011,0b0010] -> [0b0011,0b0001] """
function xor_delta!(A::Array{T,1}) where {T<:Unsigned}
a = A[1]
@inbounds for i in 2:length(A) # skip first element
b = A[i]
A[i] = a ⊻ b # XOR with prev element
a = b # make next (un-XORed) element prev for next iteration
end
end
"""Undo bitwise XOR delta. Elements include A are XORed again to reverse xor_delta.
E.g. [0b0011,0b0001] -> [0b0011,0b0010] """
function unxor_delta!(A::Array{T,1}) where {T<:Unsigned}
a = A[1]
@inbounds for i in 2:length(A) # skip first element
b = A[i]
a = a ⊻ b # un-XOR and store un-XORed a for next iteration
A[i] = a
end
end
"""Bitwise XOR delta. Elements include A are XORed with the previous one. The
first element is left unchanged.
E.g. [0b0011,0b0010] -> [0b0011,0b0001]. """
function xor_delta(A::Array{T,1}) where {T<:Unsigned}
B = copy(A)
xor_delta!(B)
return B
end
"""Undo bitwise XOR delta. Elements include A are XORed again to reverse xor_delta.
E.g. [0b0011,0b0001] -> [0b0011,0b0010] """
function unxor_delta(A::Array{T,1}) where {T<:Unsigned}
B = copy(A)
unxor_delta!(B)
return B
end
"""Bitwise XOR delta. Elements include A are XORed with the previous one. The
first element is left unchanged.
E.g. [0b0011,0b0010] -> [0b0011,0b0001]. """
function xor_delta(::Type{UIntT},A::Array{T,1}) where {UIntT<:Unsigned,T<:AbstractFloat}
B = reinterpret.(UIntT,A)
xor_delta!(B)
return reinterpret.(T,B)
end
"""Undo bitwise XOR delta. Elements include A are XORed again to reverse xor_delta.
E.g. [0b0011,0b0001] -> [0b0011,0b0010] """
function unxor_delta(::Type{UIntT},A::Array{T,1}) where {UIntT<:Unsigned,T<:AbstractFloat}
B = reinterpret.(UIntT,A)
unxor_delta!(B)
return reinterpret.(T,B)
end
"""Bitwise XOR delta. Elements include A are XORed with the previous one. The
first element is left unchanged.
E.g. [0b0011,0b0010] -> [0b0011,0b0001]. """
xor_delta(A::Array{T,1}) where {T<:AbstractFloat} = xor_delta(Base.uinttype(T),A)
"""Undo bitwise XOR delta. Elements include A are XORed again to reverse xor_delta.
E.g. [0b0011,0b0001] -> [0b0011,0b0010] """
unxor_delta(A::Array{T,1}) where {T<:AbstractFloat} = unxor_delta(Base.uinttype(T),A)
| BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 2317 | @testset "Bitcount" begin
@test bitcount(UInt8[1,2,4,8,16,32,64,128]) == ones(8)
@test bitcount(collect(0x0000:0xffff)) == 2^15*ones(16)
N = 100_000
c = bitcount(rand(N))
@test c[1] == 0 # sign always 0
@test c[2] == 0 # first expbit always 0, i.e. U(0,1) < 1
@test c[3] == N # second expont always 1
@test all(isapprox.(c[15:50],N/2,rtol=1e-1))
end
@testset "Bitcountentropy" begin
# test the PRNG on uniformity
N = 100_000
H = bitcount_entropy(rand(UInt8,N))
@test all(isapprox.(H,ones(8),rtol=5e-4))
H = bitcount_entropy(rand(UInt16,N))
@test all(isapprox.(H,ones(16),rtol=5e-4))
H = bitcount_entropy(rand(UInt32,N))
@test all(isapprox.(H,ones(32),rtol=5e-4))
H = bitcount_entropy(rand(UInt64,N))
@test all(isapprox.(H,ones(64),rtol=5e-4))
# also for random floats
H = bitcount_entropy(rand(N))
@test H[1:5] == zeros(5) # first bits never change
@test all(isapprox.(H[16:55],ones(40),rtol=1e-4))
end
import BitInformation: bitpair_count
@testset "Bit pair count" begin
for T in (Float16,Float32,Float64)
N = 10_000
A = rand(T,N)
C1 = bitpair_count(A,A) # count bitpairs with 2 equiv arrays
C2 = bitcount(A) # compare to bits counted in that array
nbits = 8*sizeof(T)
for i in 1:nbits
@test C1[i,1,2] == 0 # no 01 pair for bitpair_count(A,A)
@test C1[i,2,1] == 0 # no 10
@test C1[i,1,1] + C1[i,2,2] == N # 00 + 11 are all cases = N
@test C1[i,2,2] == C2[i] # 11 is the same as bitcount(A)
end
Auint = reinterpret(Base.uinttype(T),A)
Buint = .~Auint # flip all bits in A
C3 = bitpair_count(Auint,Auint)
@test C1 == C3 # same when called with uints
C4 = bitpair_count(Auint,Buint)
for i in 1:nbits
@test C4[i,1,2] + C4[i,2,1] == N # 01, 10 are all cases = N
@test C1[i,1,1] == C4[i,1,2] # 00 before is now 01
@test C1[i,2,2] == C4[i,2,1] # 11 before is now 10
@test C4[i,1,1] == 0 # no 00
@test C4[i,2,2] == 0 # no 11
end
end
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 655 | @testset "Bit pattern entropy" begin
for N in [100,1000,10000,100000]
# every bit pattern is only hit once, hence entropy = log2(N)
@test isapprox(log2(N),bitpattern_entropy(rand(Float32,N)),atol=1e-1)
@test isapprox(log2(N),bitpattern_entropy(rand(Float64,N)),atol=1e-1)
end
N = 1000_000 # more bit pattern than there are in 8 or 16-bit
@test isapprox(16.0,bitpattern_entropy(rand(UInt16,N)),atol=1e-1)
@test isapprox(16.0,bitpattern_entropy(rand(Int16,N)),atol=1e-1)
@test isapprox(8.0,bitpattern_entropy(rand(UInt8,N)),atol=1e-1)
@test isapprox(8.0,bitpattern_entropy(rand(Int8,N)),atol=1e-1)
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 1306 | @testset "Bitstring with split" begin
for T in (Float16,Float32,Float64)
for _ in 1:30
r = randn()
bs_split = bitstring(r,:split)
bs = bitstring(r)
@test bs == prod(split(bs_split," "))
end
end
# some individual values too
@test bitstring(Float16( 0),:split) == "0 00000 0000000000"
@test bitstring(Float16( 1),:split) == "0 01111 0000000000"
@test bitstring(Float16(-1),:split) == "1 01111 0000000000"
@test bitstring(Float16( 2),:split) == "0 10000 0000000000"
@test bitstring( 0f0,:split) == "0 00000000 00000000000000000000000"
@test bitstring( 1f0,:split) == "0 01111111 00000000000000000000000"
@test bitstring(-1f0,:split) == "1 01111111 00000000000000000000000"
@test bitstring( 2f0,:split) == "0 10000000 00000000000000000000000"
@test bitstring( 0.0,:split) ==
"0 00000000000 0000000000000000000000000000000000000000000000000000"
@test bitstring( 1.0,:split) ==
"0 01111111111 0000000000000000000000000000000000000000000000000000"
@test bitstring(-1.0,:split) ==
"1 01111111111 0000000000000000000000000000000000000000000000000000"
@test bitstring( 2.0,:split) ==
"0 10000000000 0000000000000000000000000000000000000000000000000000"
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 7236 | @testset "Bitinformation random" begin
N = 10_000
for T in (UInt8,UInt16,UInt32,UInt64)
A = rand(T,N)
@test all(bitinformation(A,set_zero_insignificant=false) .< 1e-3)
end
for T in (Float16,Float32,Float64)
A = rand(T,N)
# increase confidence to filter out more information for reliable tests...
# i.e. lower the risk of false positives
bi = bitinformation(A,confidence=0.9999)
# no bit should contain information, insignificant
# information should be filtered out
@test all(bi .== 0.0)
sort!(A) # introduce some information via sorting
@test sum(bitinformation(A)) > 9 # some bits of information (guessed)
end
end
@testset "Bitinformation dimensions" begin
for T in (Float16,Float32,Float64)
A = rand(T,30,40,50)
@test bitinformation(A) == bitinformation(A,dim=1)
bi1 = bitinformation(A,dim=1)
bi2 = bitinformation(A,dim=2)
bi3 = bitinformation(A,dim=3)
nbits = 8*sizeof(T)
for i in 1:nbits
@test bi1[i] ≈ bi2[i] atol=1e-3
@test bi2[i] ≈ bi3[i] atol=1e-3
@test bi1[i] ≈ bi3[i] atol=1e-3
end
# check that there is indeed more information in the sorted dimensions
sort!(A,dims=2)
@test sum(bitinformation(A,dim=1)) < sum(bitinformation(A,dim=2))
end
end
@testset "Mutual information" begin
N = 10_000
# equal probabilities for 00|01|10|11
@test 0.0 == mutual_information([0.25 0.25;0.25 0.25])
# every 0 or 1 in A is also a 0 or 1 in B
@test 1.0 == mutual_information([0.5 0.0;0.0 0.5])
# as before but more 1s means a lower entropy
@test entropy([0.25,0.75],2) == mutual_information([0.25 0.0;0.0 0.75])
# every bit is inverted
@test 1.0 == mutual_information([0.0 0.5;0.5 0.0])
# two independent arrays
for T in (UInt8,UInt16,UInt32,UInt64,Float16,Float32,Float64)
mutinf = mutual_information(rand(T,N),rand(T,N))
for m in mutinf
@test isapprox(0,m,atol=2e-3)
end
end
# mutual information of identical arrays
# for 0,1 occuring exactly 50/50 this is 1bit
# but so in practice slightly lower for rand(UInt),
# or clearly lower for low entropy bits in Float16/32/64
# but identical to the bitcount_entropy (up to rounding errors)
for T in (UInt8,UInt16,UInt32,UInt64,Float16,Float32,Float64)
R = rand(T,N)
mutinf = mutual_information(R,R)
@test mutinf ≈ bitcount_entropy(R)
end
end
@testset "Redundancy" begin
N = 10_000
# No redundancy in independent arrays
for T in (UInt8,UInt16,UInt32,UInt64)
redun = redundancy(rand(T,N),rand(T,N))
for r in redun
@test isapprox(0,r,atol=2e-3)
end
end
# no redundancy in the mantissa bits of rand
for T in (Float16,Float32,Float64)
redun = redundancy(rand(T,N),rand(T,N))
for r in redun[end-Base.significand_bits(T):end]
@test isapprox(0,r,atol=2e-3)
end
end
# Full redundancy in identical arrays
for T in (UInt8,UInt16,UInt32,UInt64,Float16,Float32,Float64)
A = rand(T,N)
H = bitcount_entropy(A)
R = redundancy(A,A)
for r in R
@test r ≈ 1 atol=1e-3
end
end
# Some artificially introduced redundancy PART I
for T in (UInt8,UInt16,UInt32,UInt64)
A = rand(T,N)
B = copy(A) # B is A on every second entry
B[1:2:end] .= rand(T,N÷2) # otherwise independent
# joint prob mass is therefore [0.375 0.125; 0.125 0.375]
# at 50% bits are identical, at 50% they are independent
# = 25% same, 25% opposite
p = mutual_information([0.375 0.125;0.125 0.375])
R = redundancy(A,B)
for r in R
@test r ≈ p rtol=2e-1
end
end
# Some artificially introduced redundancy PART II
for T in (UInt8,UInt16,UInt32,UInt64)
A = rand(T,N)
B = copy(A) # B is A on every fourth entry
B[1:4:end] .= rand(T,N÷4) # otherwise independent
# joint prob mass is therefore [0.4375 0.0625; 0.0625 0.4375]
# at 75% bits are identical, at 25% they are independent
# = 12.5% same, 12.5% opposite
p = mutual_information([0.4375 0.0625;0.0625 0.4375])
R = redundancy(A,B)
for r in R
@test r ≈ p rtol=2e-1
end
end
end
@testset "Mutual information with shave/round" begin
N = 10_000
for T in (Float16,Float32,Float64)
R = randn(T,N)
for keepbit in [5,10,15]
Rshaved = shave(R,keepbit)
mutinf_shave = mutual_information(R,Rshaved)
H_R = bitcount_entropy(R)
H_Rs = bitcount_entropy(Rshaved)
for (i,(s,hr,hrs)) in enumerate(zip(mutinf_shave,H_R,H_Rs))
if i <= (1+Base.exponent_bits(T)+keepbit)
@test isapprox(s,hr,atol=1e-2)
@test isapprox(s,hrs,atol=1e-2)
else
@test s == 0
@test hr > 0
@test hrs == 0
end
end
end
end
end
@testset "Masked arrays" begin
for T in (Float16, Float32, Float64)
A = rand(T, 30, 40)
sort!(A, dims=1)
# nothing is masked
mask = BitArray(undef,30,40)
fill!(mask,false)
@test bitinformation(A) == bitinformation(A, mask)
# half of the array is masked
# use view to avoid masking only a deep copy through [] indexing
fill!(@view(mask[:, 21:end]),true)
@test bitinformation(A[:, 1:20]) == bitinformation(A,mask)
# half of the array is masked
# use view to avoid masking only a deep copy through [] indexing
fill!(mask,false)
fill!(@view(mask[21:end, :]), true)
@test bitinformation(A[1:20, :]) == bitinformation(A,mask)
# mask every other value (should throw an error as no
# adjacent entries are left)
fill!(mask, false)
mask[1:2:end, 2:2:end] .= true
mask[2:2:end, 1:2:end] .= true
@test_throws AssertionError bitinformation(A,mask)
# check providing mask against providing a masked_value (mask is created internally)
masked_value = convert(T, 1/4)
A = rand(T, 30, 40)
round!(A, 1)
mask = A .== masked_value
@test bitinformation(A, mask) == bitinformation(A; masked_value)
# check that masked_value=NaN also works
A[:,2] .= NaN # put some NaNs somewhere
mask = BitArray(undef,size(A)...) # create corresponding mask
fill!(mask,false)
mask[:,2] .= true
@test bitinformation(A,mask) == bitinformation(A;masked_value=convert(T,NaN))
# only 2 in first dimension
dimss = ((2,), (2, 3), (2, 3, 4), (2, 3, 4, 5))
for dims in dimss
A = randn(T, dims...)
@test bitinformation(A) == bitinformation(A, masked_value=T(999.))
end
end
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 470 | @testset "Permute arrays" begin
A = rand(3,4,5,6,7,8)
@test A == BitInformation.permute_dim_forward(A,1)
A1 = BitInformation.permute_dim_forward(A,2)
A1 = BitInformation.permute_dim_forward(A1,6)
@test A == A1
A2 = BitInformation.permute_dim_forward(A,3)
A2 = BitInformation.permute_dim_forward(A2,5)
@test A == A2
A3 = BitInformation.permute_dim_forward(A,4)
A3 = BitInformation.permute_dim_forward(A3,4)
@test A == A3
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 3793 | @testset "iseven isodd" begin
# check sign bits
@test iseven(1f0,-8)
@test isodd(-1f0,-8)
@test iseven(1.0,-11)
@test isodd(-1.0,-11)
@test iseven(Float16(1),-5)
@test isodd(Float16(-1),-5)
@test isodd(1.5f0,1)
@test isodd(1.5,1)
@test isodd(Float16(1.5),1)
@test iseven(1.25f0,1)
@test iseven(1.25,1)
@test iseven(Float16(1.25),1)
@test isodd(1.25f0,2)
@test isodd(1.25,2)
@test isodd(Float16(1.25),2)
end
@testset "Zero rounds to zero" begin
for T in [Float16,Float32,Float64]
for k in -5:50
A = zeros(T,2,3)
Ar = round(A,k)
@test A == Ar
@test zero(T) == round(zero(T),k)
end
end
end
@testset "one rounds to one" begin
for T in [Float16,Float32,Float64]
for k in 0:50
A = ones(T,2,3)
Ar = round(A,k)
@test A == Ar
@test one(T) == round(one(T),k)
end
end
end
@testset "minus one rounds to minus one" begin
for T in [Float16,Float32,Float64]
for k in 0:50
A = -ones(T,2,3)
Ar = round(A,k)
@test A == Ar
@test -one(T) == round(-one(T),k)
end
end
end
@testset "No rounding for keepbits=10,23,52" begin
for (T,k) in zip([Float16,Float32,Float64],
[10,23,52])
A = rand(T,200,300)
Ar = round(A,k)
@test A == Ar
# and a single one
r = rand(T)
@test r == round(r,k)
end
end
@testset "Approx equal for keepbits=5,10,25" begin
for (T,k) in zip([Float16,Float32,Float64],
[5,10,25])
A = rand(T,200,300)
Ar = round(A,k)
@test A ≈ Ar
# and a single one
r = rand(T)
@test r ≈ round(r,k)
end
end
@testset "Idempotence" begin
for T in [Float16,Float32,Float64]
for k in 0:20
A = rand(T,200,300)
Ar = round(A,k)
Ar2 = round(Ar,k)
@test Ar == Ar2
end
end
end
@testset "Tie to even" begin
for T in [Float16,Float32,Float64]
@test round(1.5f0,0) == T(2)
@test round(1.25f0,1) == T(1)
@test round(1.5f0,1) == T(1.5)
@test round(1.75f0,1) == T(2)
@test round(1.125f0,2) == T(1)
@test round(1.375f0,2) == T(1.5)
@test round(1.625f0,2) == T(1.5)
@test round(1.875f0,2) == T(2)
end
for k in 1:10
m = 0x8000_0000 >> (9+k)
x = reinterpret(UInt32,one(Float32)) + m
x = reinterpret(Float32,x)
@test 1f0 == round(x,k)
end
end
@testset "Round to nearest?" begin
N = 1000
for _ in 1:N
for (T,UIntT) in zip([Float16,Float32,Float64],
[UInt16,UInt32,UInt64])
for k in 1:9
x = randn(T)
xr = round(x,k)
ulp = Base.sign_mask(T) >> (Base.exponent_bits(T)+k)
next_xr = reinterpret(T,reinterpret(UIntT,xr) + ulp)
prev_xr = reinterpret(T,reinterpret(UIntT,xr) - ulp)
@test abs(next_xr - x) >= abs(xr - x)
@test abs(prev_xr - x) >= abs(xr - x)
end
end
end
end
@testset "Round ComplexF16/32/64" begin
@testset for NF in (ComplexF16,ComplexF32,ComplexF64)
@testset for keepbits in [4,6,8]
A = randn(NF,20,30)
R = real.(A)
I = imag.(A)
Ar1 = round(R,keepbits) + im*round(I,keepbits)
Ar2 = round(A,keepbits)
@test Ar1 == Ar2
a = randn(NF)
r = real(a)
i = imag(a)
@test round(a,keepbits) == round(r,keepbits) + im*round(i,keepbits)
end
end
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 287 | using BitInformation
using Test
import StatsBase.entropy
import Random
include("bitstring.jl")
include("round_nearest.jl")
include("shave_set_groom.jl")
include("signed_exponent.jl")
include("xor_transpose.jl")
include("bitcount.jl")
include("information.jl")
include("permutations.jl") | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 2757 | @testset "Zero shaves to zero" begin
for T in [Float16,Float32,Float64]
for k in -5:50
A = zeros(T,2,3)
Ar = shave(A,k)
@test A == Ar
@test zero(T) == round(zero(T),k)
end
end
end
@testset "one shaves to one" begin
for T in [Float16,Float32,Float64]
for k in 0:50
A = ones(T,2,3)
Ar = shave(A,k)
@test A == Ar
@test one(T) == round(one(T),k)
end
end
end
@testset "minus one shaves to minus one" begin
for T in [Float16,Float32,Float64]
for k in 0:50
A = -ones(T,2,3)
Ar = shave(A,k)
@test A == Ar
@test -one(T) == round(-one(T),k)
end
end
end
@testset "No (half)shaving/setting/grooming for keepbits=10,23,52" begin
for (T,k) in zip([Float16,Float32,Float64],
[10,23,52])
A = rand(T,200,300)
Ar = shave(A,k)
@test A == Ar
Ar = halfshave(A,k)
@test A == Ar
Ar = set_one(A,k)
@test A == Ar
Ar = groom(A,k)
@test A == Ar
# and a single one
r = rand(T)
@test r == shave(r,k)
@test r == halfshave(r,k)
@test r == set_one(r,k)
end
end
@testset "Approx equal for keepbits=8,15,35" begin
for (T,k) in zip([Float16,Float32,Float64],
[8,15,35])
A = rand(T,200,300)
Ar = shave(A,k)
@test A ≈ Ar
Ar = halfshave(A,k)
@test A ≈ Ar
Ar = set_one(A,k)
@test A ≈ Ar
Ar = groom(A,k)
@test A ≈ Ar
# and a single one
r = rand(T)
@test r ≈ shave(r,k)
@test r ≈ set_one(r,k)
@test r ≈ halfshave(r,k)
end
end
@testset "Idempotence" begin
for T in [Float16,Float32,Float64]
for k in 0:20
A = rand(T,200,300)
Ar = shave(A,k)
Ar2 = shave(Ar,k)
@test Ar == Ar2
Ar = halfshave(A,k)
Ar2 = halfshave(Ar,k)
@test Ar == Ar2
Ar = set_one(A,k)
Ar2 = set_one(Ar,k)
@test Ar == Ar2
Ar = groom(A,k)
Ar2 = groom(Ar,k)
@test Ar == Ar2
end
end
end
@testset "Shave/set = round towards/away from zero?" begin
N = 1000
for _ in 1:N
for (T,UIntT) in zip([Float16,Float32,Float64],
[UInt16,UInt32,UInt64])
for k in 1:9
x = randn(T)
xr = shave(x,k)
@test abs(xr) <= abs(x)
xr = set_one(x,k)
@test abs(xr) >= abs(x)
end
end
end
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 790 | @testset "Signed/biased exponent idempotence" begin
for T in (Float16,Float32,Float64)
for _ in 1:100
A = [reinterpret(T,rand(Base.uinttype(T)))]
# call functions with array but evaluated only the element of it
# with === to allow to nan equality too
@test A[1] === biased_exponent(signed_exponent(A))[1]
# and for scalars
a = reinterpret(T,rand(Base.uinttype(T)))
@test a === biased_exponent(signed_exponent(a))
end
# special cases 0, NaN, Inf
@test [zero(T)] == biased_exponent(signed_exponent([zero(T)]))
@test isnan(biased_exponent(signed_exponent([T(NaN)]))[1])
@test isinf(biased_exponent(signed_exponent([T(Inf)]))[1])
end
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | code | 1403 | @testset "XOR reversibility UInt" begin
for T in (UInt8,UInt16,UInt32,UInt64)
A = rand(T,1000)
@test A == unxor_delta(xor_delta(A))
@test A == xor_delta(unxor_delta(A))
B = copy(A)
xor_delta!(A)
unxor_delta!(A)
@test B == A
unxor_delta!(A)
xor_delta!(A)
@test B == A
end
end
@testset "XOR reversibility Float" begin
for T in (Float32,Float64)
A = rand(T,1000)
@test A == unxor_delta(xor_delta(A))
@test A == xor_delta(unxor_delta(A))
end
end
@testset "UInt: Backtranspose of transpose" begin
for T in (UInt8,UInt16,UInt32,UInt64)
for s in (10,999,2048,9999,123123)
A = rand(T,s)
@test A == bitbacktranspose(bittranspose(A))
end
end
end
@testset "Float: Backtranspose of transpose" begin
for T in (Float32,Float64)
for s in (10,999,2048,9999,123123)
A = rand(T,s)
@test A == bitbacktranspose(bittranspose(A))
end
end
end
@testset "N-dimensional arrays" begin
A = rand(UInt32,123,234)
@test A == bitbacktranspose(bittranspose(A))
A = rand(UInt32,12,23,34)
@test A == bitbacktranspose(bittranspose(A))
A = rand(Float32,123,234)
@test A == bitbacktranspose(bittranspose(A))
A = rand(Float32,12,23,34)
@test A == bitbacktranspose(bittranspose(A))
end | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | docs | 2352 | # BitInformation.jl
[](https://github.com/milankl/BitInformation.jl/actions/workflows/CI.yml)
[](https://milankl.github.io/BitInformation.jl/dev)
[](https://doi.org/10.5281/zenodo.4774191)
BitInformation.jl is a package for bitwise information analysis and manipulation in Julia arrays.
Based on counting the occurrences of bits in floats (or generally any bits type) across various dimensions,
this package calculates quantities like the bitwise real information content, the mutual information, the
redundancy or preserved information between arrays. From v0.5 onwards masked arrays are also supported.
For bitwise manipulation, BitInformation.jl also implements various rounding modes (IEEE round,shave,set_one, etc.)
efficiently with bitwise operations for any number of bits. E.g. `round(x,i)` implements IEEE's round to nearest
tie-to-even for any float retaining `i` mantissa bits. Furthermore, transormations like XOR-delta, bittranspose
(aka bit shuffle), or signed/biased exponents are implemented.
If you'd like to propose changes, or contribute in any form create a
[pull request](https://github.com/milankl/BitInformation.jl/pulls)
or raise an [issue](https://github.com/milankl/BitInformation.jl/issues).
Contributions are highly appreciated!
## Functionality
For an overview of the functionality and explanation see the
[documentation](https://milankl.github.io/BitInformation.jl/dev).
## Installation
BitInformation.jl is registered in the Julia Registry, so just do
```
julia>] add BitInformation
```
where `]` opens the package manager. The latest version is automatically installed.
## Funding
This project is funded by the [Copernicus Programme](https://www.copernicus.eu/en/copernicus-services/atmosphere) through the [ECMWF summer of weather code 2020 and 2021](https://esowc.ecmwf.int/)
## Reference
If you use this package, please cite the following publication
> M Klöwer, M Razinger, JJ Dominguez, PD Düben and TN Palmer, 2021. *Compressing atmospheric data into its real information content*. **Nature Computational Science** 1, 713–724. [10.1038/s43588-021-00156-2](https://doi.org/10.1038/s43588-021-00156-2)
| BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | docs | 14599 | # Bitwise information content analysis
## Bit pattern entropy
An $n$-bit number format has $2^n$ bit patterns available to encode a real number.
For most data arrays, not all bit pattern occur at equal probability.
The bit pattern entropy is the
[Shannon information entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory))
$H$, in units of bits, calculated from the probability $p_i$ of each bit pattern
```math
H = -\sum_{i=1}^{2^n}p_i \log_2(p_i)
```
The bitpattern entropy is $H \leq n$ and maximised to $n$ bits for a uniform distribution,
i.e. all bit pattern occur equally frequent. The free entropy $H_f$ is the difference $n-H$.
In BitInformation.jl, the bitpattern entropy is calculated via `bitpattern_entropy(::AbstractArray)`
```julia
julia> A = rand(Float32,100000000) .+ 1;
julia> bitpattern_entropy(A)
22.938590744784577
```
Here, the entropy is about 23 bit, meaning that `9` bits are effectively unused.
This is because all elements of A are in `[1,2)`, so that the sign and exponent bits are
always `0 01111111` followed by 23 random significant bits, each contributing about 1 bit.
!!! note "Implementation details"
The function `bitpattern_entropy` is based on sorting the array `A`. While this
avoids the allocation of a bitpattern histogram (which would make the function
unsuitable for anything larger than 32 bits) it has to allocate a sorted version of `A`.
If you don't mind the sorting in-place use `bitpattern_entropy!(::AbstractArray)`.
## Bit count entropy
The Shannon information entropy $H$, in unit of bits, takes for a bitstream $b=b_1b_2...b_k...b_l$,
i.e. a sequence of bits of length $l$, the form
```math
H(b) = -p_0 \log_2(p_0) - p_1\log_2(p_1)
```
with $p_0,p_1$ being the probability of a bit $b_k$ in $b$ being 0 or 1. The entropy is maximised to
1 bit for equal probabilities $p_0 = p_1 = \tfrac{1}{2}$ in $b$. The function `bitcount(A::Array)`
counts all occurences of the 1-bit in every bit-position in every element of `A`. E.g.
```julia
julia> bitstring.(A) # 5-element Vector{UInt8}
5-element Array{String,1}:
"10001111"
"00010111"
"11101000"
"10100100"
"11101011"
julia> bitcount(A)
8-element Array{Int64,1}:
4 # number of 1-bits in the first bit of UInt8
2 # in the second bit position
3 # etc.
1
3
3
3
3
```
The first bit of elements (here: `UInt8`) in `A` is 4x `1` and hence 1x `0`.
In contrast, elements drawn from a uniform distribution U(0,1)
```julia
julia> A = rand(Float32,100000);
julia> bitcount(A)
32-element Array{Int64,1}:
0
0
100000
100000
⋮
37411
25182
0
```
have never a sign bit that is `1`, but the 2nd and third exponent bit is always `1`.
The last significant bits in `rand` do not occur at 50% chance, which is due to the
pseudo-random number generator (see a discussion
[here](https://sunoru.github.io/RandomNumbers.jl/dev/man/basics/#Conversion-to-Float)).
Once the bits in an array are counted, the respective probabilities $p_0,p_1$ can be calculated
and the entropy derived. The function `bitcount_entropy(A::Array)` does that
```julia
julia> A = rand(UInt8,100000); # entirely random bits
julia> bitcount_entropy(A)
8-element Array{Float64,1}: # entropy is for every bit position ≈ 1
0.9999998727542938
0.9999952725717266
0.9999949724904816
0.9999973408228667
0.9999937649515901
0.999992796900212
0.9999970566115759
0.9999998958374157
```
This converges to 1 for larger arrays.
## Bit pair count
The `bitpair_count(A::AbstractArray,B::AbstractArray)` function returns a `nx2x2` array,
with `n` being the number of bits elements of `A,B`. The array contains counts the
occurrences of bit pairs between A,B, i.e. `00`,`01`,`10`,`11` for all bit positions.
E.g.
```julia
julia> A = rand(UInt8,5)
julia> B = rand(UInt8,5)
julia> bitstring.(A)
5-element Array{String,1}:
"01000010"
"11110110"
"01010110"
"01111111"
"00010100"
julia> C = bitpair_count(A,B)
julia> C[1,:,:] # bitpairs of A,B in 1st bit position
2×2 Matrix{Int64}:
2 1
1 1
```
Here, among the 5 element pairs in `A,B` there are 2 which both have a `0` in the first bit
position. One element pair is `01`, one `10` and one `11`.
## Mutual information
The mutual information of two bitstreams (which can be, for example, two arrays, or adjacent
elements in one array) $r = r_1r_2...r_k...r_l$ and $s = s_1s_2...s_k...s_l$ is defined via
the joint probability mass function $p_{rs}$ which here takes the form of a 2x2 matrix
```math
p_{rs} = \begin{pmatrix}p_{00} & p_{01} \\ p_{10} & p_{11} \end{pmatrix}
```
with $p_{ij}$ being the probability that the bits are in the state $r_k=i$ and $s_k = j$
simultaneously and $p_{00}+p_{01}+p_{10}+p_{11} = 1$. The marginal probabilities follow as
column or row-wise additions in $p_{rs}$, e.g. the probability that $r_k = 0$ is
$p_{r=0} = p_{00} + p_{01}$. The mutual information $M(r,s)$ of the two bitstreams
$r,s$ is then
```math
M(r,s) = \sum_{r=0}^1 \sum_{s=0}^1 p_{rs} \log_2 \left( \frac{p_{rs}}{p_{r=r}p_{s=s}}\right)
```
The function `mutual_information(::AbstractArray,::AbstractArray)` calculates $M$ as
```julia
julia> r = rand(Float32,100_000) # [0,1) random float32s
julia> s = shave(r,15) # remove information in sbit 16-23 by setting to 0
julia> mutual_information(r,s)
32-element Vector{Float64}:
0.0
⋮
0.9999935941359982 # sbit 12: 1 bit of mutual information
0.9999912641753561 # sbit 13: same
0.9999995383375376 # sbit 14: same
0.9999954191498579 # sbit 15: same
0.0 # sbit 16: always 0 in s, but random in r: M=0 bits
0.0 # sbit 17: same
0.0
0.0
0.0
0.0
0.0
0.0 # sbit 23
```
The mutual information approaches 1 bit for unchaged bits between `r,s`, but bits that have
been shaved off do not contain any information, hence the mutual information also drops
as there is no entropy to start with.
## Real bitwise information
The mutual information of bits from adjacent bits is the `bitwise real information content` and
derived as follows. For the two bitstreams $r,s$ being the preceding and succeeding bits
(for example in space or time) in a single bitstream $b$, i.e. $r=b_1b_2...b_{l-1}$ and
$s=b_2b_3...b_l$ the unconditional entropy is then effectively $H = H(r) = H(s)$ for
$l$ being very large. We then can write the mutual information $M(r,s)$ between adjacent
bits also as
```math
I = H - q_0H_0 - q_1H_1
```
which is the real information content $I$. This definition is similar to Jeffress et al. (2017) [^1],
but avoids an additional assumption of an uncertainty measure. This defines the real information
as the entropy minus the false information. For bitstreams with either $p_0 = 1$ or $p_1 = 1$,
i.e. all bits are either 0 or 1, the entropies are zero $H = H_0 = H_1 = 0$ and we may refer to
the bits in the bitstream as being unused. In the case where $H > p_0H_0 + p_1H_1$, the preceding bit
is a predictor for the succeeding bit which means that the bitstream contains real information ($I > 0$).
The computation of $I$ is implemented in `bitinformation(::AbstractArray)`
```julia
julia> A = rand(UInt8,1000000) # fully random bits
julia> bitinformation(A)
8-element Array{Float64,1}:
0.0 # real information = 0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
```
The information of random uniform bits is 0 as the knowledge of a given bit does
not provide any information for the succeeding bits. However, correlated arrays
(which we achieve here by sorting)
```julia
julia> A = rand(Float32,1000000)
julia> sort!(A)
julia> bitinformation(A)
32-element Vector{Float64}:
0.0
0.0
0.0
0.0
0.00046647589813905157
0.06406479945998214
0.5158447841492068
0.9704486460488391
0.9150881582169795
0.996120575536068
0.9931335810218149
⋮
0.15992667263039423
0.0460430997651915
0.006067325343418917
0.0008767479258913191
0.00033132201520535975
0.0007048623462190817
0.0025481588434255187
0.0087191715755926
0.028826838913308506
0.07469492765760763
0.0
```
have only zero information in the sign (unused for random uniform distribution
U(0,1)), and in the first exponent bits (also unused due to limited range) and
in the last significant bit (flips randomly). The information is maximised to
1 bit for the last exponent and the first significant bits, as knowing the state
of such a bit one can expect the next (or previous) bit to be the same due to
the correlation.
## Multi-dimensional real information
The real information content $I_m$ for an $m$-dimensional array $A$ is the sum of the
real information along the dimensions. Let $b_j$ be a bitstream obtained by unravelling
a given bitposition in along its $j$-th dimension. Although the unconditional entropy $H$
is unchanged along the $m$-dimensions, the conditional entropies $H_0,H_1$ change as the
preceding and succeeding bit is found in another dimension, e.g. $b_2$ is obtained by
re-ordering $b_1$. Normalization by $\tfrac{1}{m}$ is applied to $I_m$ such that the
maximum information is 1 bit in $I_m^*$
```math
I_m^* = H - \frac{p_0}{m}\sum_{j=1}^mH_0(b_j) - \frac{p_1}{m}\sum_{j=1}^mH_1(b_j)
```
This is implemented in BitInformation.jl as `bitinformation(::AbstractArray,dim::int)`, e.g.
```julia
julia> A = rand(Float32,100,200,300) # a 3D array
julia> sort!(A,dims=2) # sort to create some auto-corelation
julia> bitinformation(A,dim=2) # information along 2nd dimension
32-element Vector{Float64}:
0.9284529526801016
0.12117292341467487
0.12117292341467487
0.12117292341467487
0.12097216822084497
0.11085252207817117
0.31618374026691876
0.5342647349810241
0.44490628938885407
0.2420859244356707
0.08943278228929732
0.01870979798293037
0.00221913365831955
0.0
0.0
⋮
0.0
0.0
```
The keyword `dim` will permute the dimensions in `A` to calcualte the information
in the specified dimensions. By default `dim=1`, which uses the ordering of the bits
as they are layed out in memory.
## Redundancy
Redundancy $R$ is defined as the symmetric normalised mutual information $M(r,s)$
```math
R(r,s) = \frac{2M(r,s)}{H(r) + H(s)}
```
`R` is the redundancy of information of $r$ in $s$ (and vice versa). $R = 1$ for identical
bitstreams $r = s$, but $R = 0$ for statistically independent bitstreams.
BitInformation.jl implements the redundancy calculation via `redundancy(::AbstractArray,::AbstractArray)`
where the inputs have to be of same size and element type. For example, shaving off some of
the last significant bits will set the redundancy for those to 0, but redundancy is 1 for all
bitstreams which are identical
```julia
julia> r = rand(Float32,100_000) # random data
julia> s = shave(r,7) # keep only sign, exp and sbits 1-7
julia> redundancy(r,s)
32-element Vector{Float64}:
1.0 # redundancy 1 as bitstreams are identical
1.0
1.0
1.0
0.9999999999993566 # rounding errors can yield ≈1
0.9999999999999962
1.0
1.0000000000000002
⋮
0.0 # redundancy 0 as information lost in shave
0.0
0.0
0.0
0.0
0.0
0.0
0.0
```
## Preserved information
The preserved information $P(r,s)$ between two bitstreams $r,s$ where $s$ approximates $r$
is the information-weighted redundancy $I$
```math
P(r,s) = R(r,s)I(r)
```
The information loss $L$ is $1-P$ and represents the unpreserved information of $r$ in $s$.
In most cases we are interested in the preserved information of an array $X = (x_1,x_2,...,x_q,...,x_n)$
of bitstreams when approximated by a previously compressed array $Y = (y_1,y_2,...,y_q,...,y_n)$.
For an array $A$ of floats with $n=32$ bit, for example, $x_1 is the bitstream of all sign bits
unravelled along a given dimension (e.g. longitudes) and $x_{32}$ is the bitstream of the last mantissa bits.
The redundancy $R(X,Y)$ and the real information $I(X)$ is then calculated for each bit position $q$
individually, and the preserved information $P$ is the redundancy-weighted mean of the real information
in $X$
```math
P(X,Y) = \frac{\sum_{q=1}^n R(x_q,y_q)I(x_q)}{\sum_{q=1}^n I(x_q)}
```
The quantity $\sum_{q=1}^n I(x_q)$ is the total information in $X$ and therefore also in $A$.
The redundancy is $R=1$ for bits that are unchanged during rounding and $R=0$ for bits that are
round to zero. Example
```julia
julia> r = rand(Float32,100_000) # random bits
julia> sort!(r) # sort to introduce auto-correlation & statistical dependence of bits
julia> s = shave(r,7) # s is an approximation to r, shaving off sbits 8-23
julia> R = redundancy(r,s)
julia> I = bitinformation(r)
julia> P = (R'*I)/sum(I) # preserved information of r in s
0.9087255894613658 # = 91%
```
## Significance of information
For an entirely independent and approximately equal occurrence of bits in a bitstream of length $l$,
the probabilities $p_0,p_1$ of a bit being 0 or 1 approach $p_0\approxp_1\approx\tfrac{1}{2}$, but
they are in practice not equal for $l < \infty$. Consequently, the entropy is smaller than 1,
but only insignificantly. The probability $p_1$ of successes in the binomial distribution
(with parameter $p=\tfrac{1}{2}$) with $l$ trials (using the normal approximation for large $l$) is
```math
p_1 = \frac{1}{2} + \frac{z}{2\sqrt{l}}
```
where $z$ is the $1-\tfrac{1}{2}(1-c)$ quantile at confidence level $c$ of the standard normal distribution.
For $c=0.99$, corresponding to a 99%-confidence level which is used as default here, $z=2.58$ and for $l=10^7$
a probability $\tfrac{1}{2} \leq p \leq p_1 = 0.5004$ is considered insignificantly different from equal
occurrence $p_0 = p_1$. This is implemented as `binom_confidence(l,c)`
```julia
julia> BitInformation.binom_confidence(10_000_000,0.99)
0.500407274373151
```
The associated free entropy $H_f$ in units of bits follows as
```math
H_f = 1 - p_1\log_2(p_1) - (1-p_1)\log_2(1-p_1)
```
And we consider real information below $H_f$ as insignificantly different from 0 and
set the real information $I = 0$. The calculation of $H_f$ is implemented as
`binom_free_entropy(l,c,base=2)`
```julia
julia> BitInformation.binom_free_entropy(10_000_000,0.99)
4.786066739592698e-7
```
## References
[^1]: Jeffress, S., Düben, P. & Palmer, T. _Bitwise efficiency in chaotic models_. *Proc. R. Soc. Math. Phys. Eng. Sci.* 473, 20170144 (2017).
| BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | docs | 1446 | # Index of functions in BitInformation.jl
### Information
```@docs
BitInformation.bitinformation
BitInformation.mutual_information
BitInformation.redundancy
```
### Bit counting and entropy
```@docs
BitInformation.bitpattern_entropy
BitInformation.bitpattern_entropy!
BitInformation.bitcount
BitInformation.bitcount_entropy
BitInformation.bitpair_count
```
### Significance of information
```@docs
BitInformation.binom_confidence
BitInformation.binom_free_entropy
```
### Transformations
```@docs
BitInformation.bittranspose
BitInformation.bitbacktranspose
BitInformation.xor_delta
BitInformation.xor_delta!
BitInformation.unxor_delta
BitInformation.unxor_delta!
BitInformation.signed_exponent
BitInformation.signed_exponent!
BitInformation.biased_exponent
BitInformation.biased_exponent!
```
### Rounding
```@docs
Base.round(::Base.IEEEFloat,::Integer)
BitInformation.round!
BitInformation.get_shift
BitInformation.get_ulp_half
BitInformation.get_keep_mask
BitInformation.get_bit_mask
Base.iseven(::Base.IEEEFloat,::Integer)
Base.isodd(::Base.IEEEFloat,::Integer)
```
### Shaving, halfshaving, setting and bit grooming
```@docs
BitInformation.shave
BitInformation.shave!
BitInformation.halfshave
BitInformation.halfshave!
BitInformation.set_one
BitInformation.set_one!
BitInformation.groom!
BitInformation.nsb
```
### Printing and BitArray conversion
```@docs
Base.bitstring(::Base.IEEEFloat,::Symbol)
Base.BitArray(::Matrix)
```
| BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | docs | 784 | # BitInformation.jl documentation
## Overview
[BitInformation.jl](https://github.com/milankl/BitInformation.jl) is a library for the analysis of bitwise information and
bitwise manipulation in n-dimensional Julia arrays.
## Installation
BitInformation.jl is registered in the Julia Registry, so just do
```julia
julia>] add BitInformation
```
where `]` opens the package manager. The latest version is automatically installed.
## Developers
BitInformation.jl is currently developed by [Milan Klöwer](https://github.com/milankl). Any contributions are always welcome.
## Funding
This project is funded by the [Copernicus Programme](https://www.copernicus.eu/en/copernicus-services/atmosphere)
through the [ECMWF summer of weather code 2020 and 2021](https://esowc.ecmwf.int/). | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | docs | 5343 | # Rounding
Rounding generally replaces a value $x$ with an approximation $\hat{x}$, which is from a smaller set of
representable values (e.g. with fewer decimal or binary places of accuracy). Binary rounding removes the
information in the $n$ last bits by setting them to 0 (or 1). Several rounding modes exist, and
BitInformation.jl implements them efficiently with bitwise operations, in-place or by creating a
copy of the original array.
!!! tip "Bitstring split into sign, exponent and mantissa bits"
BitInformation.jl extends `Base.bitstring` with a split option to better visualise sign, exponent
and mantissa bits for floats.
```julia
julia> bitstring(1.1f0)
"00111111100011001100110011001101"
julia> bitstring(1.1f0,:split)
"0 01111111 00011001100110011001101"
```
## Round to nearest
With binary round to nearest a full-precision number is replaced by the nearest representable float
with fewer mantissa bits by rounding the trailing bits to zero. BitInformation.jl implements this by
extending Julia's `round` to `round(::Array{T},n::Integer)` where `T` either `Float32` or `Float64`
and `n` the number of significant bits retained after rounding. Negative `n` are possible too, which
will round even the exponent bits.
Rounding
```julia
julia> # bitwise representation (split in sign, exp, sig bits) of some random numbers
julia> bitstring.(A,:split)
5-element Array{String,1}:
"0 01111101 01001000111110101001000"
"0 01111110 01010000000101001110110"
"0 01111110 01011101110110001000110"
"0 01111101 00010101010111011100000"
"0 01111001 11110000000000000000101"
```
to `n=3` significant bits via `round(A,3)` yields
```julia
julia> bitstring.(round(A,3),:split)
5-element Array{String,1}:
"0 01111101 01000000000000000000000"
"0 01111110 01100000000000000000000" # round up, flipping the third significant bit
"0 01111110 01100000000000000000000" # same here
"0 01111101 00100000000000000000000" # and here
"0 01111010 00000000000000000000000" # note how the carry bits correctly carries into the exponent
```
This rounding function is IEEE compatible as it also implements tie-to-even, meaning that `01` which is
exactly halway between `0` and `1` is round to `0` which is the *even* number (a bit sequence ending in
a `0` is even). Similarly, `11` is round up to `100` and not down to `10`. Rounding to 1 signficant bit
means that only `1,1.5,2,3,4,6...` are representable.
```julia
julia> A = Float32[1.25,1.5,1.75]
julia> bitstring.(A,:split)
3-element Vector{String}:
"0 01111111 01000000000000000000000"
"0 01111111 10000000000000000000000"
"0 01111111 11000000000000000000000"
julia> bitstring.(round(A,1),:split)
3-element Vector{String}:
"0 01111111 00000000000000000000000" # 1.25 is tie between 1.0 and 1.5, round down to even
"0 01111111 10000000000000000000000" # 1.5 is representable, no rounding
"0 10000000 00000000000000000000000" # 1.75 is tie between 1.5 and 2.0, round up to even
```
## Bit shave
In contrast to round to nearest, `shave` will always round to zero by *shaving* the trailing
significant bits off (i.e. set them to zero). This rounding mode therefore introduces
a bias towards 0 and the rounding error can be twice as large as for round to nearest.
```julia
julia> bitstring.(shave(A,3),:split)
5-element Array{String,1}:
"0 01111101 01000000000000000000000" # identical to round here
"0 01111110 01000000000000000000000" # round down here, whereas `round` would round up
"0 01111110 01000000000000000000000"
"0 01111101 00000000000000000000000"
"0 01111001 11100000000000000000000" # no carry bit for `shave`
```
## Bit set
Similar to `shave`, `set_one` will always set the trailing significant bits to `1`. This rounding
mode therefore introduces a bias away from 0 and the rounding error can be twice as large as for
round to nearest.
```julia
julia> bitstring.(set_one(A,3),:split)
5-element Array{String,1}:
"0 01111101 01011111111111111111111" # all trailing bits are always 1
"0 01111110 01011111111111111111111"
"0 01111110 01011111111111111111111"
"0 01111101 00011111111111111111111"
"0 01111001 11111111111111111111111"
```
## Bit groom
Combining `shave` and `set_one`, by alternating both removes the bias from both. This method is called
*grooming* and is implemented via the `groom` function
```julia
julia> bitstring.(groom(A,3),:split)
5-element Array{String,1}:
"0 01111101 01000000000000000000000" # shave
"0 01111110 01011111111111111111111" # set to one
"0 01111110 01000000000000000000000" # shave
"0 01111101 00011111111111111111111" # etc.
"0 01111001 11100000000000000000000"
```
## Bit halfshave
Another way to remove the bias from `shave` is to replace the trailing significant bits with `100...` which
is equivalent to round to nearest, but uses representable values that are always halfway between.
This also removes the bias of `shave` or `set_one` and yields on average a rounding error that is as
large as from round to nearest
```julia
julia> bitstring.(halfshave(A,3),:split)
5-element Array{String,1}:
"0 01111101 01010000000000000000000" # set all discarded bits to 1000...
"0 01111110 01010000000000000000000"
"0 01111110 01010000000000000000000"
"0 01111101 00010000000000000000000"
"0 01111001 11110000000000000000000"
```
| BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 0.6.3 | 2cf994e66a0886a91ba108cb3cfc044363f0bb01 | docs | 5458 | # Bit transformations
BitInformation.jl implements several bit transformations, meaning reversible, bitwise operations on scalars
or arrays that reorder or transform the bits. This is often used to pre-process the data to make it more suitable
for lossless compression algorithms.
!!! warning "Interpretation of transformed floats"
BitInformation.jl will not store the information that a transformation was applied to a value. This means
that Julia will not know about this and interpret/print a value incorrectly. You will have to explicitly execute
the backtransform (and know which one!) to undo the transformation
```julia
julia> A = [0f0,1f0] # 0 and 1
julia> At = bittranspose(A) # are transposed into 1f-35 and 0
2-element Vector{Float32}:
1.0026967f-35
0.0
julia> bitbacktranspose(At) # reverse transpose
2-element Vector{Float32}:
0.0
1.0
```
## Bit transpose (aka shuffle)
Bit shuffle operations re-order the bits or bytes in an array, such that bits or each element
in that array are placed next to each other in memory. Despite the name, this operation is
often called "shuffle", although there is nothing random about this, and it is perfectly reversible.
Here, we call it bit transpose, as for an array with $n$ elements of each $n$ bits, this is
equivalent to the matrix tranpose
```julia
julia> A = rand(UInt8,8);
julia> bitstring.(A)
8-element Array{String,1}:
"10101011"
"11100000"
"11010110"
"10001101"
"10000010"
"00011110"
"11111100"
"00011011"
julia> At = bittranspose(A);
julia> bitstring.(At)
8-element Array{String,1}:
"11111010"
"01100010"
"11000010"
"00100111"
"10010111"
"00110110"
"10101101"
"10010001"
```
In general, we can bittranspose $n$-element arrays with $m$ bits bits per element, which corresponds
to a reshaped transpose. For floats, bittranspose will place all the sign bits next to each
other in memory, then all the first exponent bits and so on. Often this creates a better
compressible array, as bits with similar meaning (and often the same state in correlated data)
are placed next to each other.
```julia
julia> A = rand(Float32,10);
julia> Ar = round(A,7);
julia> bitstring.(bittranspose(Ar))
10-element Array{String,1}:
"00000000000000000000111111111111"
"11111111111111111111111111111011"
"11111101100001011100111010000001"
"00111000001010001010100111101001"
"00000101011101110110000101100010"
"00000000000000000000000000000000"
"00000000000000000000000000000000"
"00000000000000000000000000000000"
"00000000000000000000000000000000"
"00000000000000000000000000000000"
```
Now all the sign bits are in the first row, and so on. Using `round` means that all the zeros
from rounding are now placed at the end of the array. The `bittranspose` function can be
reversed by `bitbacktranspose`:
```julia
julia> A = rand(Float32,123,234);
julia> A == bitbacktranspose(bittranspose(A))
true
```
Both accept arrays of any shape for `UInt`s as well as floats.
## XOR delta
Instead of storing every element in an array as itself, you may want to store the difference to the
previous value. For bits this "difference" generalises to the reversible xor-operation. The `xor_delta`
function applies this operation to a `UInt` or `Float` array:
```julia
julia> A = rand(UInt16,4)
4-element Array{UInt16,1}:
0x2569
0x97d2
0x7274
0x4783
julia> xor_delta(A)
4-element Array{UInt16,1}:
0x2569
0xb2bb
0xe5a6
0x35f7
```
And is reversible with `unxor_delta`.
```
julia> A == unxor_delta(xor_delta(A))
true
```
This method is interesting for correlated data, as many bits will be 0 in the XORed array:
```julia
julia> A = sort(1 .+ rand(Float32,100000));
julia> Ax = xor_delta(A);
julia> bitstring.(Ax)
100000-element Array{String,1}:
"00111111100000000000000000000101"
"00000000000000000000000010110011"
"00000000000000000000000000001000"
"00000000000000000000000001101110"
"00000000000000000000000101101001"
"00000000000000000000000001101100"
"00000000000000000000001111011000"
"00000000000000000000000010001101"
⋮
```
## Signed exponent
IEEE Floating-point numbers have a biased exponent. There are
[other ways to encode the exponent](https://en.wikipedia.org/wiki/Signed_number_representations#Comparison_table)
and BitInformation.jl implements `signed_exponent` which transforms the exponent bits of a float into a
representation where also the exponent has a sign bit (which is the first exponent bit)
```julia
julia> a = [0.5f0,1.5f0] # smaller than 1 (exp sign -1), larger than 1 (exp sign +1)
julia> bitstring.(a,:split)
2-element Vector{String}:
"0 01111110 00000000000000000000000" # biased exponent: 2^(e-bias) = 2^-1 here
"0 01111111 10000000000000000000000" # biased exponent: 2^(e-bias) = 2^0 here
julia> bitstring.(signed_exponent(a),:split)
2-element Vector{String}:
"0 10000001 00000000000000000000000" # signed exponent: sign=1, magnitude=1, i.e. 2^-1
"0 00000000 10000000000000000000000" # signed exponent: sign=0, magnitude=0, i.e. 2^0
```
The transformation `signed_exponent` can be undone with `biased_exponent`
```julia
julia> A = 0.5f0,1.5f0]
2-element Vector{Float32}:
0.5
1.5
julia> signed_exponent(A)
2-element Vector{Float32}:
4.0
5.877472f-39
julia> biased_exponent(signed_exponent(A))
2-element Vector{Float32}:
0.5
1.5
```
Both `signed_exponent` and `biased_exponent` also exist as in-place functions
`signed_exponent!` and `biased_exponent!`. | BitInformation | https://github.com/milankl/BitInformation.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 232 | using Documenter, BEAST
makedocs(
clean=false,
sitename="BEAST Documentation")
deploydocs(
# deps = Deps.pip("mkdocs", "python-markdown-math"),
repo = "github.com/krcools/BEAST.jl.git",
# julia = "1.0",
)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 3608 | using CompScienceMeshes
using BEAST
Faces = meshsphere(1.0, 0.35)
Edges = skeleton(Faces,1)
faces = barycentric_refinement(Faces)
edges = skeleton(faces,1)
# verts = skeleton(faces,0)
E = 1
Edge = cells(Edges)[1]
port_idx = numvertices(Faces) + E
ptch_idx = Edge[1]
# patch = Mesh(vertices(faces), filter(c -> ptch_idx in c, cells(faces)))
patch_idcs = Int[]
for (i,face) in enumerate(cells(faces))
if ptch_idx in face
push!(patch_idcs, i)
end
end
ptch = Mesh(vertices(faces), cells(faces)[patch_idcs])
port = Mesh(vertices(edges), filter(c -> port_idx in c, cells(boundary(ptch))))
@show numcells(ptch)
@show numcells(port)
# D, C, d, c, d0, d1,
# RT_int, RT_prt, x_int, x_prt = BEAST.buildhalfbc2(ptch, port, nothing)
#
# BF = BEAST.Shape{Float64}[]
# for (m,bf) in enumerate(RT_int.fns)
# for sh in bf
# cellid = patch_idcs[sh.cellid]
# BEAST.add!(BF,cellid, sh.refid, sh.coeff * x_int[m])
# end
# end
#
# for (m,bf) in enumerate(RT_prt.fns)
# for sh in bf
# cellid = patch_idcs[sh.cellid]
# BEAST.add!(BF,cellid, sh.refid, sh.coeff * x_prt[m])
# end
# end
# RT_prt = raviartthomas(patch, cellpairs(patch, port))
# Lx = lagrangecxd0(patch)
# @assert numfunctions(Lx) == numcells(patch)
#
# Id = BEAST.Identity()
# div_RT_prt = divergence(RT_prt)
# Z, store = BEAST.allocatestorage(Id, Lx, div_RT_prt, Val{:bandedstorage}, BEAST.LongDelays{:ignore})
# BEAST.assemble_local_mixed!(Id, Lx, div_RT_prt, store)
bcs3 = BEAST.buffachristiansen3(Faces)
bcs2 = BEAST.buffachristiansen2(Faces)
bcs1 = BEAST.buffachristiansen(Faces)
rts = BEAST.raviartthomas(Faces)
G1 = assemble(BEAST.NCross(), bcs1, rts)
Q1 = assemble(BEAST.Identity(), divergence(bcs1), divergence(bcs1))
G2 = assemble(BEAST.NCross(), bcs2, rts)
Q2 = assemble(BEAST.Identity(), divergence(bcs2), divergence(bcs2))
G3 = assemble(BEAST.NCross(), bcs3, rts)
Q3 = assemble(BEAST.Identity(), divergence(bcs3), divergence(bcs3))
using LinearAlgebra
@show cond(Matrix(G3))
using LinearAlgebra
# @assert (numcells(Faces) - 1) == (size(Q,1) - rank(Q))
@assert cond(Matrix(G1)) < 3.5
function compress!(space)
T = scalartype(space)
for (i,fn) in pairs(space.fns)
shapes = Dict{Tuple{Int,Int},T}()
for shape in fn
v = get(shapes, (shape.cellid, shape.refid), zero(T))
shapes[(shape.cellid, shape.refid)] = v + shape.coeff
# set!(shapes, (shape.cellid, shape.refid), v + shape.coeff)
end
space.fns[i] = [BEAST.Shape(k[1], k[2], v) for (k,v) in shapes]
end
end
getch(geo,i) = chart(geo, cells(geo)[i])
import PlotlyJS
function showfn(space,i)
geo = geometry(space)
T = coordtype(geo)
X = Dict{Int,T}()
Y = Dict{Int,T}()
Z = Dict{Int,T}()
U = Dict{Int,T}()
V = Dict{Int,T}()
W = Dict{Int,T}()
for sh in space.fns[i]
chrt = chart(geo, cells(geo)[sh.cellid])
nbd = center(chrt)
vals = refspace(space)(nbd)
x,y,z = cartesian(nbd)
@show vals[sh.refid].value
u,v,w = vals[sh.refid].value
# @show x, y, z
# @show u, v, w
X[sh.cellid] = x
Y[sh.cellid] = y
Z[sh.cellid] = z
U[sh.cellid] = get(U,sh.cellid,zero(T)) + sh.coeff * u
V[sh.cellid] = get(V,sh.cellid,zero(T)) + sh.coeff * v
W[sh.cellid] = get(W,sh.cellid,zero(T)) + sh.coeff * w
end
X = collect(values(X))
Y = collect(values(Y))
Z = collect(values(Z))
U = collect(values(U))
V = collect(values(V))
W = collect(values(W))
PlotlyJS.cone(x=X,y=Y,z=Z,u=U,v=V,w=W)
end
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1128 | # If you want a scatter plot of the spectra, define `plotresults = true`
# prior to running this script.
using CompScienceMeshes, BEAST
using LinearAlgebra
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
println("Mesh with $(numvertices(Γ)) vertices and $(numcells(Γ)) cells.")
X = raviartthomas(Γ)
Y = BEAST.buffachristiansen2(Γ)
κ = ω = 1.0; γ = κ*im
T = MWSingleLayer3D(γ)
N = NCross()
Txx = assemble(T,X,X); println("primal discretisation assembled.")
Tyy = assemble(T,Y,Y); println("dual discretisation assembled.")
Nxy = Matrix(assemble(N,X,Y)); println("duality form assembled.")
iNxy = inv(Nxy); println("duality form inverted.")
A = iNxy' * Tyy * iNxy * Txx
@show cond(Txx)
@show cond(Tyy)
@show cond(A)
wx, wy, wp = eigvals(Txx), eigvals(Tyy), eigvals(A); println("eigvals found.")
(@isdefined plotresults) || (plotresults = false)
if plotresults
@eval begin
using Plots
plot()
scatter!(wx,c=:blue,label="primal")
scatter!(wy,c=:red,label="dual")
scatter!(wp,c=:green,label="CMP")
plot!(xlim=(-0.5,0.5),ylim=(-10.0,10.0))
end
end
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1164 | # If you want a scatter plot of the spectra, define `plotresults = true`
# prior to running this script.
using CompScienceMeshes, BEAST
using LinearAlgebra
# Γ = readmesh(joinpath(@__DIR__,"sphere2.in"))
Γ = meshrectangle(1.0, 1.0, 0.2, 3)
println("Mesh with $(numvertices(Γ)) vertices and $(numcells(Γ)) cells.")
X = raviartthomas(Γ)
Y = BEAST.buffachristiansen3(Γ)
κ = ω = 1.0; γ = κ*im
T = MWSingleLayer3D(γ)
N = NCross()
Txx = assemble(T,X,X); println("primal discretisation assembled.")
Tyy = assemble(T,Y,Y); println("dual discretisation assembled.")
Nxy = assemble(N,X,Y); println("duality form assembled.")
iNxy = inv(Matrix(Nxy)); println("duality form inverted.")
A = iNxy' * Tyy * iNxy * Txx
@show cond(Matrix(Nxy))
@show cond(Txx)
@show cond(Tyy)
@show cond(A)
wx, wy, wp = eigvals(Txx), eigvals(Tyy), eigvals(A); println("eigvals found.")
(@isdefined plotresults) || (plotresults = false)
if plotresults
@eval begin
using Plots
plot()
scatter!(wx,c=:blue,label="primal")
scatter!(wy,c=:red,label="dual")
scatter!(wp,c=:green,label="CMP")
plot!(xlim=(-0.5,0.5),ylim=(-10.0,10.0))
end
end
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1856 | using BEAST
using CompScienceMeshes
using LinearAlgebra
# define geometry & material parameters
f₀= 3.0e6 # 3 GHz
c = 3.0e8
ϵ₀ = 8.85418782e-12
μ₀ = 1.25663706e-6
ϵᵣ=1; μᵣ=1
l = w = 1.0 #Length and width of capacitor plates
d = 0.1 #seperation of plates
h = 1/12 #size of meshes
ω = 2π*f₀
vₑ = c/sqrt(ϵᵣ)
λₑ = vₑ/f₀
η = sqrt(μ₀*μᵣ/ϵ₀*ϵᵣ)
κ = ω/vₑ
println("wavenumber = ", κ)
println("freq = ", f₀, " Hz")
println("λ = ", λₑ, "m; l = ", l ,"m")
# Build and mesh the structure
Γ₁ = meshrectangle(l,w,h);
CompScienceMeshes.translate!(Γ₁, point(0.0,0.0,d))
Γ₀ = meshrectangle(l,w,h)
γ₁ = meshsegment(l, h, 3)
CompScienceMeshes.translate!(γ₁, point(0.0,0.0,d))
γ₀ = meshsegment(l, h, 3)
Γ = weld(Γ₁, Γ₀)
# define the excitation
V₀ = 1.0
f = ScalarTrace{typeof(V₀)}(p -> V₀)
#define basis function
RT = rt_ports(Γ,[γ₁,γ₀])
# define the equations
@hilbertspace j
@hilbertspace k
T = MWSingleLayer3D(im*κ)
trc = X->ntrace(X,γ₁)
EFIE = @varform η*T[k,j] == f[trc(k)]
# discretise & solve the equation
efie = @discretise EFIE j∈RT k∈RT
u = solve(efie)
#Calculate & plot face currents
fcr,geo = facecurrents(u, RT); println("Face currents calculated")
# patch_mat(geo, fcr); println("Facecurrents plotted")
# Compute the Scalar Potential across the ports
z = range(-0.5, stop=0.5, length=100)
pts1 = point.(0.5,0.5,z)
# pts1 = [point(0.5,0.5,a) for a in range(-0.5,stop=0.5,length=100)]
volt = η*potential(MWSingleLayerPotential3D(κ), pts1, u, RT, type=ComplexF64)
# Plot the Scalar potential
using Plots
Φ = real.(getindex.(volt,1))
display(plot(z,Φ,xlabel="height",ylabel="scalar potential",label=""))
# Compare numerical capacitance with parallel plate approximation
idx = getindex_rtg(RT) #get index of global RWG
Q = norm(-u[idx]/(im*ω))
C = (ϵ₀*ϵᵣ*(l*w))/d
println("Relative different w.r.t. large plate capacitance: ", 2*abs(Q-C)/abs(Q+C))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 3242 | using BEAST
using CompScienceMeshes
using LinearAlgebra
using SparseArrays
import Plotly
import Plots
Plots.plotly()
function Base.:+(a::S, b::S) where {S<:BEAST.Space}
@assert geometry(a) == geometry(b)
S(geometry(a), [a.fns; b.fns], [a.pos; b.pos])
end
l = w = 1.0 #Length and width of capacitor plates
d = 0.1 #seperation of plates
h = 1/60 #size of meshes
Γ₀ = meshrectangle(l,w,h)
Γ₁ = CompScienceMeshes.translate(Γ₀, point(0.0,0.0,d))
γ₀ = meshsegment(l,h,3)
γ₁ = CompScienceMeshes.translate(γ₀, point(0.0,0.0,d))
Γ = weld(Γ₁, Γ₀)
κ = 2pi / 100
V₀ = 1.0
f = ScalarTrace{typeof(V₀)}(p -> V₀)
edges_all = skeleton(Γ, 1)
edges_int = submesh(!in(boundary(Γ)), edges_all)
on_γ₀ = overlap_gpredicate(γ₀)
edges_pt0 = submesh(edges_all) do m, edge
ch = chart(m, edge)
return on_γ₀(ch)
end
on_γ₁ = overlap_gpredicate(γ₁)
edges_pt1 = submesh(edges_all) do m, edge
ch = chart(m, edge)
return on_γ₁(ch)
end
RT_int = raviartthomas(Γ, edges_int)
RT_pt0 = raviartthomas(Γ, edges_pt0)
RT_pt1 = raviartthomas(Γ, edges_pt1)
verts_pt0_int = submesh(!in(boundary(edges_pt0)), skeleton(edges_pt0,0))
verts_pt1_int = submesh(!in(boundary(edges_pt1)), skeleton(edges_pt1,0))
C0 = connectivity(verts_pt0_int, edges_pt0)
C1 = connectivity(verts_pt1_int, edges_pt1)
X = RT_int
Y0 = RT_pt0 * C0
Y1 = RT_pt1 * C1
# This is ugly and will fail if the two ports are not equal...
D = sparse(reshape([fill(+1.0, length(edges_pt0)); fill(-1.0, length(edges_pt1))],length(edges_pt0)+length(edges_pt1),1))
RT_pt = RT_pt0 + RT_pt1
Z = RT_pt * D
@hilbertspace x y0 y1 z
@hilbertspace ξ η0 η1 ζ
T = Maxwell3D.singlelayer(wavenumber=κ)
trc = X->ntrace(X,γ₁)
efie = @discretise( @varform(
T[ξ,x] + T[ξ,y0] + T[ξ,y1] + T[ξ,z] +
T[η0,x] + T[η0,y0] + T[η0,y1] + T[η0,z] +
T[η1,x] + T[η1,y0] + T[η1,y1] + T[η1,z] +
T[ζ,x] + T[ζ,y0] + T[ζ,y1] + T[ζ,z] == f[trc(ζ)]),
ξ∈X, η0∈Y0, η1∈Y1, ζ∈Z,
x∈X, y0∈Y0, y1∈Y1, z∈Z)
u = solve(efie)
# assemble(efie.equation.rhs, efie.test_space_dict)
# @enter assemble(efie.equation.rhs, X + Y0 + Y1 + Z)
# assemble(efie.equation.lhs, efie.test_space_dict, efie.trial_space_dict)
# You can access the current coefficients pertaining to subspaces
# using the Hilbert space 'placeholder'
@show length(u[x])
@show length(u[y0])
@show length(u[y1])
@show length(u[z])
S = (((X + Y0) + Y1) + Z)
fcr, geo = facecurrents(u, S)
Plotly.plot(patch(geo, norm.(fcr))) |> display
# Compute the Scalar Potential across the ports. Note how a voltage
# gap of 1V comes out as a 'natural' condition on the solution.
zs = range(-0.5, stop=0.5, length=100)
pts = [point(0.5,0.5,z) for z ∈ zs]
Φ = potential(MWSingleLayerPotential3D(κ), pts, u, S; type=ComplexF64)
Plots.plot(zs, real(Φ), xlabel="height",ylabel="scalar potential",label=false) |> display
# Plot current along γ₀ and γ₁. Note: in this symmetric situation, we
# expect these to be opposite on corresponding points of the two ports.
# In general this is not true; in fact, the two ports could have different shape and size
traceS0 = ntrace(S, γ₀)
traceS1 = ntrace(S, γ₁)
fcr0, geo0 = facecurrents(u, traceS0)
fcr1, geo1 = facecurrents(u, traceS1)
Plots.plot()
Plots.plot!(imag.(fcr0))
Plots.plot!(imag.(fcr1)) |> display | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1004 | using CompScienceMeshes, BEAST
o, x, y, z = euclidianbasis(3)
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
X, Y = raviartthomas(Γ), buffachristiansen(Γ)
Δt ,Nt = 0.3, 200
T = timebasisshiftedlagrange(Δt, Nt, 2)
δ = timebasisdelta(Δt, Nt)
V = X ⊗ T
W = Y ⊗ δ
duration = 20 * Δt * 2
delay = 1.5 * duration
amplitude = 1.0
gaussian = derive(creategaussian(duration, delay, amplitude))
direction, polarisation = ẑ, x̂
Ė = BEAST.planewave(polarisation, direction, gaussian, 1.0)
Ḣ = direction × Ė
@hilbertspace j
@hilbertspace k
K̇ = TDMaxwell3D.doublelayer(speedoflight=1.0, numdiffs=1)
Nİ = BEAST.TemporalDifferentiation(NCross()⊗Identity())
@hilbertspace k
@hilbertspace j
mfie_dot = @discretise (0.5*Nİ)[k,j] + K̇[k,j] == -1.0Ḣ[k] k∈W j∈V
xmfie_dot = BEAST.motsolve(mfie_dot)
# Xmfie, Δω, ω0 = fouriertransform(xmfie, Δt, 0.0, 2)
# ω = collect(ω0 .+ (0:Nt-1)*Δω)
# _, i1 = findmin(abs.(ω .- 1.0))
#
# ω1 = ω[i1]
# um = Xmfie[:,i1] / fouriertransform(gaussian)(ω1)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1774 | using CompScienceMeshes
using BEAST
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
X = raviartthomas(Γ)
d = BEAST.CurlSingleLayerDP3D(1.0im, 1.0)
s = Helmholtz3D.singlelayer(wavenumber=1.0)
X = raviartthomas(Γ,BEAST.Continuity{:none})
Y = lagrangec0d1(Γ)
x = refspace(X)
y = refspace(Y)
charts = [chart(Γ,c) for c in Γ]
qs = BEAST.defaultquadstrat(s, x, x)
qd = quaddata(s, x, x, charts, charts, qs)
m1,m2 = 10,11
ql = quadrule(s, x, x, m1, charts[m1], m2, charts[m2], qd, qs)
@show @which quadrule(s, x, x, m1, charts[m1], m2, charts[m2], qd, qs)
@show typeof(ql)
BEAST.momintegrals!(s, x, x, charts[10], charts[20],
zeros(ComplexF64,3,3), ql)
# sop = BEAST.singularpart(s)
ctr = CompScienceMeshes.center(charts[m1])
# BEAST.momintegrals!(sop, ctr, x, x, charts[m1], charts[m1], zeros(3,3), ql, 1.0)
dvg = divergence
@hilbertspace j p
@hilbertspace k q
κ = 1.0
curlA = BEAST.ScalarTrace{ComplexF64}(((x,y,z),)->-exp(-im*κ*z)*ŷ)
ndotA = BEAST.NDotTrace{ComplexF64}(((x,y,z),)->-x*exp(-im*κ*z)*ẑ)
a = @varform s[k,j] + s[dvg(k),p] +
s[q,dvg(j)] - κ^2*s[q,p] == curlA[k]+ndotA[q]
Eq = @discretise a k∈X q∈Y j∈X p∈Y
u = solve(Eq)
# lform = Eq.equation.rhs
# @which scalartype(lform.terms[2].functional.field)
# @enter assemble(Eq.equation.rhs, Eq.test_space_dict)
# assemble(Eq.equation.lhs, Eq.test_space_dict, Eq.trial_space_dict)
# uj = u[1:numfunctions(X)]
# up = u[numfunctions(X)+1:end]
uj = u[j]
up = u[p]
xrange = range(-2.0, stop=2.0, length=40)
# xrange = [0.0]
# yrange = [0.0]
zrange = range(-2.0, stop=2.0, length=40)
pts = [point(x,0,z) for x ∈ xrange, z ∈ zrange]
A1 = BEAST.DPVectorialTerm(1.0, 1.0*im)
A2 = BEAST.DPScalarTerm(1.0, 1.0*im)
p1 = potential(A1,pts,uj,X)
p2 = potential(A2,pts,up,Y)
p = p1 + p2
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1260 | using CompScienceMeshes, BEAST
using LinearAlgebra
using Profile
using StaticArrays
function tau(x::SVector{U,T}) where {U,T}
1.0-1.0/4.0
end
ntrc = X->ntrace(X,y)
T = CompScienceMeshes.tetmeshsphere(1.0,0.25)
X = nedelecd3d(T)
y = boundary(T)
@show numfunctions(X)
ϵ, μ, ω = 1.0, 1.0, 1.0; κ, η = ω * √(ϵ*μ), √(μ/ϵ)
ϵ_r =4.0
χ = tau
K, I, B = VIE.singlelayer(wavenumber=κ, tau=χ), Identity(), VIE.boundary(wavenumber=κ, tau=χ)
E = VIE.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
H = -1/(im*κ*η)*curl(E)
@hilbertspace j
@hilbertspace k
α = 1.0/ϵ_r
eq = @varform α*I[j,k]-K[j,k]-B[ntrc(j),k] == E[j]
dbvie = @discretise eq j∈X k∈X
u = solve(dbvie)
#postprocessing
Φ, Θ = [0.0], range(0,stop=2π,length=100)
pts = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for θ in Θ for ϕ in Φ]
ffd = potential(VIE.farfield(wavenumber=κ, tau=χ), pts, u, X)
ff = im*κ*ffd
using Plots
#Farfield
plot(xlabel="theta")
plot!(Θ, norm.(ff), label="far field", title="D-VIE")
#NearField
Z = range(-1,1,length=100)
Y = range(-1,1,length=100)
nfpoints = [point(0,y,z) for y in Y, z in Z]
Enear = BEAST.grideval(nfpoints,α.*u,X)
Enear = reshape(Enear,100,100)
contour(real.(getindex.(Enear,1)))
heatmap(Z, Y, real.(getindex.(Enear,1)), clim=(0.0,1.0))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 452 | using CompScienceMeshes
using BEAST
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
X = raviartthomas(Γ)
κ, η = 1.0, 1.0
t = Maxwell3D.singlelayer(wavenumber=κ)
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n
@hilbertspace j
@hilbertspace k
efie = @discretise t[k,j]==e[k] j∈X k∈X
u, ch = BEAST.gmres_ch(efie; restart=1500)
include("utils/postproc.jl")
include("utils/plotresults.jl")
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 432 | using CompScienceMeshes
using BEAST
# Γ = readmesh(joinpath(@__DIR__,"sphere2.in"))
Γ = meshsphere(radius=1.0, h=0.1)
X = brezzidouglasmarini(Γ)
κ = 1.0
t = Maxwell3D.singlelayer(wavenumber=κ)
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n
@hilbertspace j
@hilbertspace k
efie = @discretise t[k,j]==e[k] j∈X k∈X
u = gmres(efie)
include("utils/postproc.jl")
include("utils/plotresults.jl")
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1329 | using CompScienceMeshes
using BEAST
Γ = CompScienceMeshes.meshrectangle(2.0, 2.0, 0.1; structured=:quadrilateral)
edges = skeleton(Γ, 1)
edges_bnd = boundary(Γ)
pred = !in(edges_bnd)
edges_int = submesh(pred, edges)
c = CompScienceMeshes.connectivity(edges_int, Γ, identity)
o = ones(length(edges_int))
X = raviartthomas(Γ, edges_int, c, o)
@show numfunctions(X)
κ, η = 1.0, 1.0
t = Maxwell3D.singlelayer(wavenumber=κ)
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n
@hilbertspace j
@hilbertspace k
efie = @discretise t[k,j]==e[k] j∈X k∈X
u, ch = BEAST.gmres_ch(efie; restart=1500)
Φ, Θ = [0.0], range(0,stop=π,length=100)
pts = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for ϕ in Φ for θ in Θ]
ffd = potential(MWFarField3D(wavenumber=κ), pts, u, X)
xs, y, zs = range(-4,stop=6,length=200), 1.0, range(-5,stop=5,length=200)
gridpoints = [point(x,y,z) for z in zs, x in xs]
nfd = potential(MWSingleLayerField3D(wavenumber = κ), gridpoints, u, X)
# nfd = reshape(nfd, (nx,nz))
nfd .-= E.(gridpoints)
import Plots
using LinearAlgebra
p1 = Plots.scatter(Θ, real.(norm.(ffd)))
p2 = Plots.heatmap(-clamp.(real.(getindex.(nfd,1)), -3.0, 3.0), clims=(-3,3), colormap=:viridis)
p3 = Plots.contour(-clamp.(real.(getindex.(nfd,1)), -3.0, 3.0), clims=(-3,3))
Plots.plot(p1,p2,p3,layout=(3,1))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 594 | using CompScienceMeshes
using BEAST
#Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
Γ = meshsphere(radius=1.0, h=0.2)
# Γ = CompScienceMeshes.meshmobius(h=0.035)
X = BEAST.raviartthomas2(Γ)
κ, η = 1.0, 1.0
t = Maxwell3D.singlelayer(wavenumber=κ)
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
# E = -η/(im*κ)*BEAST.CurlCurlGreen(κ, ẑ, point(2,0,0))
e = (n × E) × n
@hilbertspace j
@hilbertspace k
efie = @discretise t[k,j]==e[k] j∈X k∈X
u, ch = BEAST.gmres_ch(efie; restart=1500)
include("utils/postproc.jl")
include("utils/plotresults.jl")
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1244 | using CompScienceMeshes, BEAST
using LinearAlgebra
using Profile
using StaticArrays
function tau(x::SVector{U,T}) where {U,T}
4.0-1.0
end
ttrc = X->ttrace(X,y)
T = CompScienceMeshes.tetmeshsphere(1.0,0.25)
X = nedelecc3d(T)
y = boundary(T)
@show numfunctions(X)
ϵ, μ, ω = 1.0, 1.0, 1.0; κ, η = ω * √(ϵ*μ), √(μ/ϵ)
ϵ_r = 4.0
χ = tau
K, I, B = VIE.singlelayer2(wavenumber=κ, tau=χ), Identity(), VIE.boundary2(wavenumber=κ, tau=χ)
E = VIE.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
H = -1/(im*κ*η)*curl(E)
@hilbertspace j
@hilbertspace k
α = ϵ_r
eq = @varform α*I[j,k]-K[j,k]+B[ttrc(j),k] == E[j]
evie = @discretise eq j∈X k∈X
u = solve(evie)
#postprocessing
Φ, Θ = [0.0], range(0,stop=2π,length=100)
pts = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for θ in Θ for ϕ in Φ ]
ffe = potential(VIE.farfield(wavenumber=κ, tau=χ), pts, u, X)
ff = ffe
using Plots
#Farfield
plot(xlabel="theta")
plot!(Θ, norm.(ff), label="far field", title="E-VIE")
#Nearfield
Z = range(-1,1,length=100)
Y = range(-1,1,length=100)
nfpoints = [point(0,y,z) for y in Y, z in Z]
Enear = BEAST.grideval(nfpoints,u,X)
Enear = reshape(Enear,100,100)
contour(real.(getindex.(Enear,1)))
heatmap(Z, Y, real.(getindex.(Enear,1)), clim=(0.0,1.0))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 5930 | using CompScienceMeshes
using BEAST
using LinearAlgebra
const Id = BEAST.Identity()
function add!(fn, x, space)
for (m,bf) in enumerate(space.fns)
for sh in bf
BEAST.add!(fn, sh.cellid, sh.refid, sh.coeff * x[m])
end
end
end
function compress!(space)
T = scalartype(space)
for (i,fn) in pairs(space.fns)
shapes = Dict{Tuple{Int,Int},T}()
for shape in fn
v = get(shapes, (shape.cellid, shape.refid), zero(T))
shapes[(shape.cellid, shape.refid)] = v + shape.coeff
# set!(shapes, (shape.cellid, shape.refid), v + shape.coeff)
end
space.fns[i] = [BEAST.Shape(k[1], k[2], v) for (k,v) in shapes]
end
end
import Plotly
function showfn(space,i)
geo = geometry(space)
T = coordtype(geo)
X = Dict{Int,T}()
Y = Dict{Int,T}()
Z = Dict{Int,T}()
U = Dict{Int,T}()
V = Dict{Int,T}()
W = Dict{Int,T}()
for sh in space.fns[i]
chrt = chart(geo, cells(geo)[sh.cellid])
nbd = center(chrt)
vals = refspace(space)(nbd)
x,y,z = cartesian(nbd)
# @show vals[sh.refid].value
u,v,w = vals[sh.refid].value
# @show x, y, z
# @show u, v, w
X[sh.cellid] = x
Y[sh.cellid] = y
Z[sh.cellid] = z
U[sh.cellid] = get(U,sh.cellid,zero(T)) + sh.coeff * u
V[sh.cellid] = get(V,sh.cellid,zero(T)) + sh.coeff * v
W[sh.cellid] = get(W,sh.cellid,zero(T)) + sh.coeff * w
end
X = collect(values(X))
Y = collect(values(Y))
Z = collect(values(Z))
U = collect(values(U))
V = collect(values(V))
W = collect(values(W))
Plotly.cone(x=X,y=Y,z=Z,u=U,v=V,w=W)
end
Tetrs = CompScienceMeshes.tetmeshsphere(1.0, 0.45)
tetrs = barycentric_refinement(Tetrs)
bnd_Tetrs = boundary(Tetrs)
bnd_tetrs = boundary(tetrs)
# srt_bnd_Tetrs = sort.(bnd_Tetrs)
# srt_bnd_tetrs = sort.(bnd_tetrs)
Faces = submesh(!in(bnd_Tetrs), skeleton(Tetrs,2))
# Faces = submesh(Face -> !(sort(Face) in srt_bnd_Tetrs), skeleton(Tetrs,2))
@show length(Faces)
F = 396
Face = cells(Faces)[F]
pos = cartesian(CompScienceMeshes.center(chart(Faces, F)))
supp1 = submesh((m,tet) -> Face[1] in CompScienceMeshes.indices(m,tet), tetrs.mesh)
supp2 = submesh((m,tet) -> Face[2] in CompScienceMeshes.indices(m,tet), tetrs.mesh)
supp3 = submesh((m,tet) -> Face[3] in CompScienceMeshes.indices(m,tet), tetrs.mesh)
supp = CompScienceMeshes.union(supp1, supp2)
supp = CompScienceMeshes.union(supp, supp3)
# PlotlyJS.plot(patch(boundary(supp)))
port = skeleton(supp1, 1)
port = submesh(in(skeleton(supp2,1)), port)
port = submesh(in(skeleton(supp3,1)), port)
# port = submesh(edge -> sort(edge) in sort.(skeleton(supp2,1)), port)
# port = submesh(edge -> sort(edge) in sort.(skeleton(supp3,1)), port)
@show length(port)
@assert 1 ≤ length(port) ≤ 2
dir = submesh(in(bnd_tetrs), boundary(supp))
# dir = submesh(face -> sort(face) in srt_bnd_tetrs, boundary(supp))
rim = boundary(dir)
@show length(dir)
# srt_port = sort.(port)
# srt_dir_edges = sort.(skeleton(dir,1))
# srt_bnd_edges = sort.(skeleton(boundary(supp),1))
# srt_rim = sort.(rim)
in_port = in(port)
in_dir_edges = in(skeleton(dir,1))
in_bnd_edges = in(skeleton(boundary(supp),1))
in_rim = in(rim)
int_edges = submesh(skeleton(supp,1)) do m,edge
in_port(m,edge) && return false
in_rim(m,edge) && return false
in_dir_edges(m,edge) && return true
in_bnd_edges(m,edge) && return false
return true
end
# int_edges = submesh(skeleton(supp,1)) do edge
# sort(edge) in srt_port && return false
# sort(edge) in srt_rim && return false
# sort(edge) in srt_dir_edges && return true
# sort(edge) in srt_bnd_edges && return false
# return true
# end
@show length(int_edges)
@assert length(skeleton(supp,0)) - length(skeleton(supp,1)) +
length(skeleton(supp,2)) - length(supp) == 1
Nd_prt = BEAST.nedelecc3d(supp, port)
Nd_int = BEAST.nedelecc3d(supp, int_edges)
@show numfunctions(Nd_int)
x0 = ones(length(port)) / length(port)
for (i,edge) in enumerate(port)
tgt = tangents(CompScienceMeshes.center(chart(port,edge)),1)
if dot(normal(chart(Faces,F)), tgt) < 0
x0[i] *= -1
end
end
curl_Nd_int = curl(Nd_int)
A = Matrix(assemble(Id, curl_Nd_int, curl_Nd_int))
N = nullspace(A)
@show size(N,2)
a = -assemble(Id, curl_Nd_int, curl(Nd_prt)) * x0
x1 = pinv(A) * a
# x1 = A \ a
@show norm(N'*a)
@show norm(A*x1-a)
# srt_bnd_verts = sort.(skeleton(boundary(supp),0))
# srt_prt_verts = sort.(skeleton(port,0))
# int_verts = submesh(skeleton(supp,0)) do vert
# sort(vert) in srt_bnd_verts && return false
# sort(vert) in srt_prt_verts && return false
# return true
# end
in_bnd_verts = in(skeleton(boundary(supp),0))
in_prt_verts = in(skeleton(port,0))
int_verts = submesh(skeleton(supp,0)) do m,vert
in_bnd_verts(m,vert) && return false
in_prt_verts(m,vert) && return false
return true
end
@show length(int_verts)
L0_int = lagrangec0d1(supp, int_verts)
@show numfunctions(L0_int)
grad_L0_int = BEAST.gradient(L0_int)
@assert numfunctions(grad_L0_int) == numfunctions(L0_int)
B = assemble(Id, grad_L0_int, Nd_int)
freeze, store = BEAST.allocatestorage(Id, grad_L0_int, Nd_int,
Val{:bandedstorage}, BEAST.LongDelays{:ignore})
BEAST.assemble_local_mixed!(Id, grad_L0_int, Nd_int, store)
B2 = freeze()
@assert isapprox(B, B2, atol=1e-8)
@show rank(B2)
b = -assemble(Id, grad_L0_int, Nd_prt) * x0
p = (B*N) \ (b-B*x1)
x1 = x1 + N*p
@show norm(A*x1-a)
@show norm(B*x1-b)
fn = BEAST.Shape{Float64}[]
add!(fn, x0, Nd_prt)
add!(fn, x1, Nd_int)
Y1 = BEAST.NDLCCBasis(supp, [fn],[pos])
curlY1 = curl(Y1); compress!(curl(Y1));
include(joinpath(@__DIR__, "utils/edge_values.jl"))
EV = edge_values(Y1,1)
check_edge_values(EV)
# error("stop")
Dir = boundary(Tetrs)
Y = BEAST.dual1forms(Tetrs, Faces, Dir)
curlY = curl(Y)
CC = assemble(Id, curlY, curlY)
Plotly.plot(svdvals(Matrix(CC)))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 7755 | using CompScienceMeshes
using BEAST
using LinearAlgebra
const Id = BEAST.Identity()
const Nx = BEAST.NCross()
# function Base.in(mesh::CompScienceMeshes.AbstractMesh)
# cells_mesh = sort.(mesh)
# function f(cell)
# sort(cell) in cells_mesh
# end
# end
function add!(fn, x, space, idcs)
for (m,bf) in enumerate(space.fns)
for sh in bf
cellid = idcs[sh.cellid]
BEAST.add!(fn, cellid, sh.refid, sh.coeff * x[m])
end
end
end
function compress!(space)
T = scalartype(space)
for (i,fn) in pairs(space.fns)
shapes = Dict{Tuple{Int,Int},T}()
for shape in fn
v = get(shapes, (shape.cellid, shape.refid), zero(T))
shapes[(shape.cellid, shape.refid)] = v + shape.coeff
end
space.fns[i] = [BEAST.Shape(k[1], k[2], v) for (k,v) in shapes]
end
end
import Plotly
function showfn(space,i)
geo = geometry(space)
T = coordtype(geo)
X = Dict{Int,T}()
Y = Dict{Int,T}()
Z = Dict{Int,T}()
U = Dict{Int,T}()
V = Dict{Int,T}()
W = Dict{Int,T}()
for sh in space.fns[i]
chrt = chart(geo, cells(geo)[sh.cellid])
nbd = center(chrt)
vals = refspace(space)(nbd)
x,y,z = cartesian(nbd)
u,v,w = vals[sh.refid].value
X[sh.cellid] = x
Y[sh.cellid] = y
Z[sh.cellid] = z
U[sh.cellid] = get(U,sh.cellid,zero(T)) + sh.coeff * u
V[sh.cellid] = get(V,sh.cellid,zero(T)) + sh.coeff * v
W[sh.cellid] = get(W,sh.cellid,zero(T)) + sh.coeff * w
end
X = collect(values(X))
Y = collect(values(Y))
Z = collect(values(Z))
U = collect(values(U))
V = collect(values(V))
W = collect(values(W))
Plotly.cone(x=X,y=Y,z=Z,u=U,v=V,w=W)
end
function extend_edge_to_face(supp, dirichlet, x_prt, port_edges)
bnd_supp = boundary(supp)
supp_edges = CompScienceMeshes.skeleton_fast(supp, 1)
supp_nodes = CompScienceMeshes.skeleton_fast(supp, 0)
dir_compl_edges = submesh(!in(dirichlet), bnd_supp)
dir_compl_nodes = CompScienceMeshes.skeleton_fast(dir_compl_edges, 0)
int_edges = submesh(!in(dir_compl_edges), supp_edges)
int_nodes = submesh(!in(dir_compl_nodes), supp_nodes)
Nd_prt = BEAST.nedelec(supp, port_edges)
Nd_int = BEAST.nedelec(supp, int_edges)
Lg_int = BEAST.lagrangec0d1(supp, int_nodes)
curl_Nd_prt = divergence(n × Nd_prt)
curl_Nd_int = divergence(n × Nd_int)
grad_Lg_int = n × curl(Lg_int)
A = assemble(Id, curl_Nd_int, curl_Nd_int)
B = assemble(Id, grad_Lg_int, Nd_int)
a = -assemble(Id, curl_Nd_int, curl_Nd_prt) * x_prt
b = -assemble(Id, grad_Lg_int, Nd_prt) * x_prt
Z = zeros(eltype(b), length(b), length(b))
u = [A B'; B Z] \ [a;b]
x_int = u[1:end-length(b)]
return x_int, int_edges, Nd_int
end
function extend_face_to_tetr(supp, dirichlet, x_prt, port_edges)
bnd_supp = boundary(supp)
supp_edges = CompScienceMeshes.skeleton_fast(supp, 1)
supp_nodes = CompScienceMeshes.skeleton_fast(supp, 0)
dir_compl_faces = submesh(!in(dirichlet), bnd_supp)
dir_compl_edges = CompScienceMeshes.skeleton_fast(dir_compl_faces, 1)
dir_compl_nodes = CompScienceMeshes.skeleton_fast(dir_compl_faces, 0)
int_edges = submesh(!in(dir_compl_edges), supp_edges)
int_nodes = submesh(!in(dir_compl_nodes), supp_nodes)
Nd_prt = BEAST.nedelecc3d(supp, port_edges)
Nd_int = BEAST.nedelecc3d(supp, int_edges)
Lg_int = BEAST.lagrangec0d1(supp, int_nodes)
curl_Nd_prt = curl(Nd_prt)
curl_Nd_int = curl(Nd_int)
grad_Lg_int = BEAST.gradient(Lg_int)
A = assemble(Id, curl_Nd_int, curl_Nd_int)
B = assemble(Id, grad_Lg_int, Nd_int)
a = -assemble(Id, curl_Nd_int, curl_Nd_prt) * x_prt
b = -assemble(Id, grad_Lg_int, Nd_prt) * x_prt
Z = zeros(eltype(b), length(b), length(b))
u = [A B'; B Z] \ [a;b]
x_int = u[1:end-length(b)]
return x_int, int_edges, Nd_int
end
Tetrs = CompScienceMeshes.tetmeshsphere(1.0, 0.45)
tetrs = barycentric_refinement(Tetrs)
v2t, v2n = CompScienceMeshes.vertextocellmap(tetrs)
Bnd = boundary(Tetrs)
bnd = boundary(tetrs)
Dir = Bnd
dir = bnd
Faces = submesh(!in(Bnd), CompScienceMeshes.skeleton_fast(Tetrs,2))
@show length(Faces)
F = 396
Face = cells(Faces)[F]
pos = cartesian(CompScienceMeshes.center(chart(Faces, F)))
idcs1 = v2t[Face[1],1:v2n[Face[1]]]
idcs2 = v2t[Face[2],1:v2n[Face[2]]]
idcs3 = v2t[Face[3],1:v2n[Face[3]]]
supp1 = tetrs.mesh[idcs1]
supp2 = tetrs.mesh[idcs2]
supp3 = tetrs.mesh[idcs3]
dir1_faces = submesh(in(dir), boundary(supp1))
dir2_faces = submesh(in(dir), boundary(supp2))
dir3_faces = submesh(in(dir), boundary(supp3))
supp23 = submesh(in(boundary(supp2)), boundary(supp3))
supp31 = submesh(in(boundary(supp3)), boundary(supp1))
supp12 = submesh(in(boundary(supp1)), boundary(supp2))
dir23_edges = submesh(in(boundary(dir2_faces)), boundary(dir3_faces))
dir31_edges = submesh(in(boundary(dir3_faces)), boundary(dir1_faces))
dir12_edges = submesh(in(boundary(dir1_faces)), boundary(dir2_faces))
port_edges = boundary(supp23)
port_edges = submesh(in(boundary(supp31)), port_edges)
port_edges = submesh(in(boundary(supp12)), port_edges)
@assert 1 ≤ length(port_edges) ≤ 2
# Step 1: set port flux and extend to dual faces
x0 = ones(length(port_edges)) / length(port_edges)
for (i,edge) in enumerate(port_edges)
tgt = tangents(CompScienceMeshes.center(chart(port_edges, edge)),1)
if dot(normal(chart(Faces, F)), tgt) < 0
x0[i] *= -1
end
end
x23, supp23_int_edges = extend_edge_to_face(supp23, dir23_edges, x0, port_edges)
x31, supp31_int_edges = extend_edge_to_face(supp31, dir31_edges, x0, port_edges)
x12, supp12_int_edges = extend_edge_to_face(supp12, dir12_edges, x0, port_edges)
port1_edges = CompScienceMeshes.union(port_edges, supp31_int_edges)
port1_edges = CompScienceMeshes.union(port1_edges, supp12_int_edges)
port2_edges = CompScienceMeshes.union(port_edges, supp12_int_edges)
port2_edges = CompScienceMeshes.union(port2_edges, supp23_int_edges)
port3_edges = CompScienceMeshes.union(port_edges, supp23_int_edges)
port3_edges = CompScienceMeshes.union(port3_edges, supp31_int_edges)
x1_prt = [x0; x31; x12]
x2_prt = [x0; x12; x23]
x3_prt = [x0; x23; x31]
Nd1_prt = BEAST.nedelecc3d(supp1, port1_edges)
Nd2_prt = BEAST.nedelecc3d(supp2, port2_edges)
Nd3_prt = BEAST.nedelecc3d(supp3, port3_edges)
x1_int, _, Nd1_int = extend_face_to_tetr(supp1, dir1_faces, x1_prt, port1_edges)
x2_int, _, Nd2_int = extend_face_to_tetr(supp2, dir2_faces, x2_prt, port2_edges)
x3_int, _, Nd3_int = extend_face_to_tetr(supp3, dir3_faces, x3_prt, port3_edges)
# inject in the global space
fn = BEAST.Shape{Float64}[]
add!(fn, x1_prt, Nd1_prt, idcs1)
add!(fn, x1_int, Nd1_int, idcs1)
add!(fn, x2_prt, Nd2_prt, idcs2)
add!(fn, x2_int, Nd2_int, idcs2)
add!(fn, x3_prt, Nd3_prt, idcs3)
add!(fn, x3_int, Nd3_int, idcs3)
pos = cartesian(CompScienceMeshes.center(chart(Faces, F)))
space = BEAST.NDLCCBasis(tetrs, [fn], [pos])
tetrs, bnd, dir, v2t, v2n = BEAST.dualforms_init(Tetrs, Dir)
D1 = BEAST.dual1forms_body(Faces, tetrs, bnd, dir, v2t, v2n)
P2 = BEAST.nedelecd3d(Tetrs, Faces)
# S = BEAST.dual1forms(Tetrs, Faces[collect(396:405)], Dir)
Edges = CompScienceMeshes.skeleton_fast(Tetrs, 1)
int_Edges = submesh(!in(skeleton(boundary(Tetrs),1)), Edges)
P1 = BEAST.nedelecc3d(Tetrs, int_Edges)
curl_D1 = curl(D1)
curl_P1 = curl(P1)
div_P2 = divergence(P2)
G = assemble(Id, curl_D1, curl_D1)
GP = assemble(Id, div_P2, div_P2)
M = assemble(Id, D1, P2)
CDP = assemble(Id, D1, curl_P1)
CPD = CDP'
GDD = assemble(Id, D1, D1)
iM = inv(Matrix(M))
A1 = CPD * inv(Matrix(GDD)) * CDP;
A2 = assemble(Id, curl_P1, curl_P1)
A3 = CPD * iM' * inv(Matrix(GDD)) * iM * CDP;
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 7588 | using CompScienceMeshes
using BEAST
using LinearAlgebra
const Id = BEAST.Identity()
function add!(fn, x, space)
for (m,bf) in enumerate(space.fns)
for sh in bf
BEAST.add!(fn, sh.cellid, sh.refid, sh.coeff * x[m])
end
end
end
function compress!(space)
T = scalartype(space)
for (i,fn) in pairs(space.fns)
shapes = Dict{Tuple{Int,Int},T}()
for shape in fn
v = get(shapes, (shape.cellid, shape.refid), zero(T))
shapes[(shape.cellid, shape.refid)] = v + shape.coeff
# set!(shapes, (shape.cellid, shape.refid), v + shape.coeff)
end
space.fns[i] = [BEAST.Shape(k[1], k[2], v) for (k,v) in shapes]
end
end
Tetrs = CompScienceMeshes.tetmeshsphere(1.0, 0.15)
tetrs = barycentric_refinement(Tetrs)
cells_Bndry = [sort(c) for c in cells(skeleton(boundary(Tetrs),1))]
Bnd = boundary(Tetrs)
Neu = Bnd
Dir = Mesh(vertices(Bnd), CompScienceMeshes.celltype(Bnd)[])
bnd = boundary(tetrs)
neu = bnd
dir = Mesh(vertices(bnd), CompScienceMeshes.celltype(bnd)[])
# srt_Dir = sort.(Dir)
# Edges = submesh(skeleton(Tetrs,1)) do Edge
# sort(Edge) in srt_Dir && return false
# return true
# end
Edges = submesh(!in(Dir), skeleton(Tetrs,1))
# Edges = skeleton(Tetrs,1)
# srt_bnd_Faces = sort.(boundary(Tetrs))
# srt_neu = sort.(neu)
# Faces = submesh(skeleton(Tetrs,2)) do Face
# !(sort(Face) in srt_bnd_Faces)
# end
# srt_bnd_Nodes = sort.(skeleton(boundary(Tetrs),0))
# Nodes = submesh(skeleton(Tetrs,0)) do node
# !(sort(node) in srt_bnd_Nodes)
# end
Nodes = submesh(!in(skeleton(boundary(Tetrs),0)), skeleton(Tetrs,0))
@show numcells(Edges)
# @show length(Faces)
# pred = CompScienceMeshes.interior_tpredicate(Tetrs)
# AllFaces = skeleton(Tetrs,2)
# sm = submesh(pred, AllFaces)
E = 1
Edge = cells(Edges)[E]
pos = cartesian(CompScienceMeshes.center(chart(Edges, E)))
# v = argmin(norm.(vertices(tetrs) .- Ref(pos)))
support1 = submesh((m,tetr) -> Edge[1] in CompScienceMeshes.indices(m,tetr), tetrs.mesh)
support2 = submesh((m,tetr) -> Edge[2] in CompScienceMeshes.indices(m,tetr), tetrs.mesh)
# port = submesh(face -> v in face, boundary(support1))
# port2 = submesh(face -> v in face, boundary(support2))
# port = submesh(face -> sort(face) in sort.(boundary(support2)), boundary(support1))
port = submesh(in(boundary(support2)), boundary(support1))
# for p in port
# @assert sort(p) in sort.(port2)
# end
@show length(port)
support = CompScienceMeshes.union(support1, support2)
@assert CompScienceMeshes.isoriented(support)
@show length(support)
@assert length(skeleton(support1,2)) + length(skeleton(support2,2)) ==
length(skeleton(support,2)) + length(port)
edges = skeleton(support,1)
# cells_bnd_edges = [sort(c) for c in skeleton(boundary(support),1)]
# cells_prt_edges = [sort(c) for c in skeleton(port,1)]
# cells_dir_edges = [sort(c) for c in skeleton(boundary(tetrs),1)]
bnd_support = boundary(support)
# cells_bnd_tetrs = sort.(boundary(tetrs))
# srt_dir = sort.(dir)
# dir_cap_bnd = submesh(face -> sort(face) in sort.(dir), bnd_support)
dir_cap_bnd = submesh(in(dir), bnd_support)
# cells_bnd_dir_cap_bnd = sort.(boundary(dir_cap_bnd))
in_bnd_dir_cap_bnd = in(boundary(dir_cap_bnd))
in_dir_edges = in(skeleton(boundary(tetrs),1))
in_bnd_edges = in(skeleton(boundary(support),1))
in_prt_edges = in(skeleton(port,1))
int_edges = submesh(edges) do m,edge
in_bnd_dir_cap_bnd(m,edge) && return false
in_bnd_edges(m,edge) && return true
in_dir_edges(m,edge) && return false
in_prt_edges(m,edge) && return false
return true
end
# int_edges = submesh(edges) do edge
# sort(edge) in cells_bnd_dir_cap_bnd && return false
# sort(edge) in cells_dir_edges && return true
# sort(edge) in cells_bnd_edges && return false
# sort(edge) in cells_prt_edges && return false
# return true
# end
@show length(int_edges)
Nd_int = BEAST.nedelecc3d(support, int_edges)
Q = assemble(Id, Nd_int, Nd_int)
freeze, store = BEAST.allocatestorage(Id, Nd_int, Nd_int,
Val{:bandedstorage}, BEAST.LongDelays{:ignore})
BEAST.assemble_local_mixed!(Id, Nd_int, Nd_int, store)
Q2 = freeze()
@assert Q ≈ Q2
Q3 = assemble(Id, curl(Nd_int), curl(Nd_int))
rank(Q3)
# cells_bnd_faces = [sort(c) for c in boundary(support)]
# cells_prt_faces = [sort(c) for c in port]
# srt_dir_cap_bnd = sort.(dir_cap_bnd)
in_dir_cap_bnd = in(dir_cap_bnd)
in_bnd_faces = in(boundary(support))
in_prt_faces = in(port)
int_faces = submesh(skeleton(support,2)) do m,face
in_dir_cap_bnd(m,face) && return true
in_bnd_faces(m,face) && return false
in_prt_faces(m,face) && return false
return true
end
# int_faces = submesh(skeleton(support,2)) do face
# # sort(face) in cells_bnd_tetrs && return true
# sort(face) in srt_dir_cap_bnd && return true
# sort(face) in cells_bnd_faces && return false
# sort(face) in cells_prt_faces && return false
# return true
# end
@show length(int_faces)
@assert length(int_faces) + length(boundary(support)) + length(port) ==
length(skeleton(support,2)) + length(dir_cap_bnd)
RT_int = BEAST.nedelecd3d(support, int_faces)
for (m,fn) in enumerate(RT_int.fns)
ct = count(sh -> sh.cellid <= length(support1), fn)
# @show m, ct
@assert 0 ≤ ct ≤ 2
end
Q4 = assemble(Id, divergence(RT_int), divergence(RT_int))
numfunctions(RT_int) - rank(Q4)
RT_prt = BEAST.nedelecd3d(support, port)
for fn in RT_prt.fns
@assert count(sh -> sh.cellid <= length(support1), fn) == 1
@assert count(sh -> sh.cellid > length(support1), fn) == 1
end
Q5 = assemble(Id, divergence(RT_int), divergence(RT_int))
x0 = ones(length(port)) / length(port)
tgt = vertices(Edges)[Edge[1]] - vertices(Edges)[Edge[2]]
for (i,face) in enumerate(port)
x0[i] *= sign(dot(normal(chart(port,face)), tgt))
# if RT_prt.fns[i][1].coeff < 0
# x0[i] *= -1
# end
end
Q6 = assemble(Id, divergence(RT_int), divergence(RT_prt))
d = -Q6 * x0
x1 = pinv(Matrix(Q5)) * d
# L0 = lagrangecxd0(support)
# Q7 = assemble(Id, L0, divergence(RT_int))
# Q8 = assemble(Id, L0, L0)
# ch1 = []
# ch2 = []
# ch = [ch1; ch2]
# x1 = pinv(Q7) * ()
fn = BEAST.Shape{Float64}[]
add!(fn, x0, RT_prt)
add!(fn, x1, RT_int)
Y1 = BEAST.NDLCDBasis(support, [fn], [pos])
divY1 = divergence(Y1); compress!(divY1)
import Plotly
function showfn(space,i)
geo = geometry(space)
T = coordtype(geo)
X = Dict{Int,T}()
Y = Dict{Int,T}()
Z = Dict{Int,T}()
U = Dict{Int,T}()
V = Dict{Int,T}()
W = Dict{Int,T}()
for sh in space.fns[i]
chrt = chart(geo, cells(geo)[sh.cellid])
nbd = CompScienceMeshes.center(chrt)
vals = refspace(space)(nbd)
x,y,z = cartesian(nbd)
# @show vals[sh.refid].value
u,v,w = vals[sh.refid].value
# @show x, y, z
# @show u, v, w
X[sh.cellid] = x
Y[sh.cellid] = y
Z[sh.cellid] = z
U[sh.cellid] = get(U,sh.cellid,zero(T)) + sh.coeff * u
V[sh.cellid] = get(V,sh.cellid,zero(T)) + sh.coeff * v
W[sh.cellid] = get(W,sh.cellid,zero(T)) + sh.coeff * w
end
X = collect(values(X))
Y = collect(values(Y))
Z = collect(values(Z))
U = collect(values(U))
V = collect(values(V))
W = collect(values(W))
Plotly.cone(x=X,y=Y,z=Z,u=U,v=V,w=W)
end
# error("stop")
Dir = Mesh(vertices(Tetrs), CompScienceMeshes.celltype(int_faces)[])
# error()
tetrs, bnd, dir, v2t, v2n = BEAST.dualforms_init(Tetrs, Dir)
Y = BEAST.dual2forms_body(Edges[collect(1:10)], tetrs, bnd, dir, v2t, v2n)
# Y = BEAST.dual2forms(Tetrs, Edges, Dir)
nothing
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 3759 | using LinearAlgebra
using CompScienceMeshes
using BEAST
include("utils/showfn.jl")
Tetrs = CompScienceMeshes.meshball(radius=1.0, h=0.26)
Faces = CompScienceMeshes.skeleton_fast(Tetrs, 2)
Edges = CompScienceMeshes.skeleton_fast(Tetrs, 1)
Nodes = CompScienceMeshes.skeleton_fast(Tetrs, 0)
hemi = submesh(Tetrs) do m,Tetr
cartesian(CompScienceMeshes.center(chart(Tetrs, Tetr)))[3] < 0
end
bnd_Faces = boundary(Tetrs)
bnd_Edges = CompScienceMeshes.skeleton_fast(bnd_Faces, 1)
bnd_Nodes = CompScienceMeshes.skeleton_fast(bnd_Faces, 0)
int_Faces = submesh(!in(bnd_Faces), Faces)
int_Edges = submesh(!in(bnd_Edges), Edges)
int_Nodes = submesh(!in(bnd_Nodes), Nodes)
@show length(int_Edges)
@show length(int_Faces)
primal2 = BEAST.nedelecd3d(Tetrs, Faces)
primal1 = BEAST.nedelecc3d(Tetrs, int_Edges)
Dir = bnd_Faces
Neu = submesh(!in(Dir), bnd_Faces)
# tetrs, bnd, dir, v2t, v2n = BEAST.dualforms_init(Tetrs, Dir)
# dual1 = BEAST.dual1forms_body(Faces, tetrs, bnd, dir, v2t, v2n)
# error()
dual2 = BEAST.dual2forms(Tetrs, int_Edges, Dir)
dual1 = BEAST.dual1forms(Tetrs, Faces, Dir)
@assert numfunctions(primal1) == numfunctions(dual2)
@assert numfunctions(primal2) == numfunctions(dual1)
Id = BEAST.Identity()
G = assemble(Id, dual1, primal2)
H = assemble(Id, dual2, primal1)
TF = connectivity(Faces, Tetrs)
FE = connectivity(int_Edges, Faces)
EN = connectivity(int_Nodes, int_Edges)
@show norm(G)
@show norm(H)
@show norm(TF*G*FE)
@show norm(FE*H*EN)
# A = assemble(Id, primal2, primal2)
# B = assemble(Id, curl(primal1), curl(primal1))
# B2 = FE'*A*FE;
# @show norm(B - B2)
# EV = eigen(B)
# idx = findfirst(abs.(EV.values) .> 1e-6)
# u = real(EV.vectors[:,idx+1])
# primal1_hemi = restrict(primal1, hemi)
# trace_primal1_hemi = BEAST.ttrace(primal1_hemi, boundary(hemi))
# fcr, geo = facecurrents(u, trace_primal1_hemi)
# Plotly.plot(patch(geo, norm.(fcr)))
# tetrs, bnd, dir, v2t, v2n = BEAST.dual1forms_init(Tetrs, Dir)
# duals11 = BEAST.dual1forms_body(int_Faces[collect(1:10)], tetrs, bnd, dir, v2t, v2n)
# Ggf = assemble(Id, dual1, primal2);
Cgg = assemble(Id, dual1, curl(primal1))
# Cfg = Ggf \ Cgg;
# Conn = Matrix(connectivity(int_Edges, Faces))
# @show norm(Cfg - Conn)
Zpp = zeros(numfunctions(primal1), numfunctions(primal1))
Zdd = zeros(numfunctions(dual1), numfunctions(dual1))
ϵ = BEAST.Multiplicative(p -> 1.0)
μ = BEAST.Multiplicative(p -> 1.0)
Ipp = assemble(ϵ, primal1, primal1)
Idd = assemble(μ, dual1, dual1, storage_policy=Val{:densestorage})
Zpd = zeros(numfunctions(primal1), numfunctions(dual1))
C = [Zpp Cgg'; -Cgg Zdd];
J = [Ipp Zpd; Zpd' Idd];
γ = 1.0 * im
# P = inv(2J - C) * (2J + C);
# Q = (2J - C) * inv(2J + C);
jg = assemble(BEAST.ScalarTrace{eltype(x̂)}(p -> x̂), primal1)
mG = zeros(numfunctions(dual1))
b = [jg; mG]
u = (C - γ*J) \ b
eg = u[1:numfunctions(primal1)]
hG = u[numfunctions(primal1)+1:end]
primal1_hemi = restrict(primal1, hemi)
trace_primal1_hemi = BEAST.ttrace(primal1_hemi, boundary(hemi))
fcr, geo = facecurrents(eg, trace_primal1_hemi)
Plotly.plot(patch(geo, norm.(fcr)))
curl_primal1_hemi = BEAST.curl(primal1_hemi)
ncurl_primal1_hemi = BEAST.ntrace(curl_primal1_hemi, boundary(hemi))
fcr, geo = facecurrents(eg, ncurl_primal1_hemi)
Plotly.plot(patch(geo, norm.(fcr)))
tetrs = geometry(dual1)
bary_hemi = submesh(tetrs) do m,tetr
cartesian(CompScienceMeshes.center(chart(tetrs, tetr)))[1] < 0
end
dual1_hemi = restrict(dual1, bary_hemi)
bnd_bary_hemi = boundary(bary_hemi)
trace_dual1_hemi = BEAST.ttrace(dual1_hemi, bnd_bary_hemi)
fcr, geo = facecurrents(hG, trace_dual1_hemi)
Plotly.plot(patch(geo, norm.(fcr)))
# tetrs, bnd, dir, v2t, v2n = BEAST.dualforms_init(Tetrs, Dir)
# @profview BEAST.dual1forms_body(Faces[collect(1:10)], tetrs, bnd, dir, v2t, v2n) | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 2441 | using CompScienceMeshes
using BEAST
using SparseArrays
tetrs = CompScienceMeshes.tetmeshsphere(1.0, 0.15)
@show numcells(tetrs)
bndry = boundary(tetrs)
edges = skeleton(tetrs, 1)
interior_edges = submesh(!in(skeleton(bndry,1)), edges)
@assert numcells(interior_edges) + numcells(skeleton(bndry,1)) == numcells(edges)
X = BEAST.nedelecc3d(tetrs, interior_edges)
@assert numfunctions(X) == numcells(interior_edges)
Id = BEAST.Identity()
Y = curl(X)
A1 = assemble(Id, Y, Y)
A2 = assemble(Id, X, X)
A = A1 - A2
using LinearAlgebra
f = BEAST.ScalarTrace{typeof(x̂)}(x -> x̂)
b = assemble(f, X)
u = A \ b
using Plots
pts = [point(0.0,t,0.0) for t in range(-2,2,length=200)];
vals = BEAST.grideval(pts, u, X)
vals2 = BEAST.grideval(pts, u, Y)
vals2 = [point(0,1,0) × val for val in vals2]
plot(getindex.(real(vals),1), m=1)
plot(norm.(vals2), m=2)
# Inspect the value of a single basis function
p = 120
tet = chart(tetrs, p)
nbd = neighborhood(tet, [0.5, 0.5, 0.0])
edg = simplex(tet.vertices[1], tet.vertices[2])
tgt = normalize(edg.vertices[2] - edg.vertices[1])
vals = refspace(X)(nbd)
@assert dot(tgt,vals[1].value) ≈ 1/volume(edg) atol=1e-8
# check also the value of the raviart-thomas 3d in the center
# of their defining face
Z = BEAST.nedelecd3d(tetrs)
@assert numfunctions(Z) == numcells(skeleton(tetrs,2))
fce = simplex(tet.vertices[2], tet.vertices[3], tet.vertices[4])
nbd_rt = neighborhood(tet, [0.0, 1/3, 1/3])
vals_rt = refspace(Z)(nbd_rt)
#
dot(vals_rt[1].value, normal(fce)) * volume(fce)
o, x, y, z = euclidianbasis(3)
@assert volume(simplex(x,y,z,o)) * 6 ≈ 1
G = boundary(tetrs)
Z = BEAST.ttrace(curl(X), G)
fcr, geo = facecurrents(u, Z)
import Plotly
Plotly.plot(patch(geo, norm.(fcr)))
Dir = Mesh(vertices(tetrs), CompScienceMeshes.celltype(G)[])
# error("stop")
Xplus = BEAST.nedelecc3d(tetrs, skeleton(tetrs,1))
bnd_tetrs = boundary(tetrs)
ttXplus = BEAST.ttrace(Xplus, bnd_tetrs)
TF, Idcs = isdivconforming(ttXplus)
@show length(Idcs)
# error("stop")
# @target Q ()->BEAST.dual2forms(tetrs, skeleton(tetrs,1), Dir)
# Q = @make Q
Q = BEAST.dual2forms(tetrs, skeleton(tetrs,1), Dir)
QXplus = assemble(Id, Q, Xplus)
curlX = curl(X)
QcurlX = assemble(Id, Q, curlX)
v = QXplus \ (QcurlX * u)
fcr1, geo1 = facecurrents(v, BEAST.ttrace(Xplus, bnd_tetrs));
fcr2, geo2 = facecurrents(u, BEAST.ttrace(curl(X), bnd_tetrs));
fcr3, geo3 = facecurrents(v, divergence(ttXplus));
Plotly.plot(patch(geo, norm.(fcr)))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 2960 | using CompScienceMeshes
using BEAST
using LinearAlgebra
import Plotly
# Exterior wavenumber
κ₀ = 3.0
# This is where the number of domains enters the problem description
κ = [1.5κ₀, 2.5κ₀]
# Description of the domain boundaries
h = 0.125
Γ1 = meshcuboid(0.5, 1.0, 1.0, h)
Γ2 = -Mesh([point(-x,y,z) for (x,y,z) in vertices(Γ1)], deepcopy(cells(Γ1)))
Γ = [Γ1, Γ2]
# Beyond this point the problem description is completely independent
# of the number of domains and their relative positioning
# Incident field
Einc = Maxwell3D.planewave(direction=(x̂+ẑ)/√2, polarization=ŷ, wavenumber=κ₀)
Hinc = -1/(im*κ₀)*curl(Einc)
# Definition of the boundary integral operators
T0 = Maxwell3D.singlelayer(wavenumber=κ₀)
K0 = Maxwell3D.doublelayer(wavenumber=κ₀)
T = [Maxwell3D.singlelayer(wavenumber=κᵢ) for κᵢ ∈ κ]
K = [Maxwell3D.doublelayer(wavenumber=κᵢ) for κᵢ ∈ κ]
# Definition of per-domain bilinear forms
@hilbertspace m j
@hilbertspace k l
A0 = K0[k,m] - T0[k,j] + T0[l,m] + K0[l,j]
A = [Kᵢ[k,m] - Tᵢ[k,j] + Tᵢ[l,m] + Kᵢ[l,j] for (Tᵢ,Kᵢ) ∈ zip(T,K)]
N = BEAST.NCross()
Nᵢ = -0.5*N[k,m] - 0.5*N[l,j]
# Building the global system
p = BEAST.hilbertspace(:p, length(κ))
q = BEAST.hilbertspace(:q, length(κ))
Adiag = BEAST.Variational.DirectProductKernel(A)
Ndiag = BEAST.Variational.BlockDiagKernel(Nᵢ)
B = A0[p,q] + Adiag[p,q] + Ndiag[p,q] - Nᵢ[p,q]
# Also for the right hand side, first per domain contributions
# are constructed, followed by the global synthesis
e = (n × Einc) × n
h = (n × Hinc) × n
bᵢ = e[k] - h[l]
b = bᵢ[p]
Xₕ = raviartthomas.(Γ)
Yₕ = raviartthomas.(Γ)
Pₕ = [Xᵢ×Yᵢ for (Xᵢ,Yᵢ) ∈ zip(Xₕ,Yₕ)]
Qₕ = [Xᵢ×Yᵢ for (Xᵢ,Yᵢ) ∈ zip(Xₕ,Yₕ)]
deq = BEAST.discretise(B==b, (p .∈ Pₕ)..., (q .∈ Qₕ)...)
u = solve(deq)
# u = gmres(deq, tol=1e-4, maxiter=2500)
fcrm = [facecurrents(u[qᵢ][m], Xᵢ)[1] for (qᵢ,Xᵢ) ∈ zip(q,Xₕ)]
fcrj = [facecurrents(u[qᵢ][j], Xᵢ)[1] for (qᵢ,Xᵢ) ∈ zip(q,Xₕ)]
Plotly.plot([patch(Γᵢ, norm.(fcrᵢ), caxis=(0,2)) for (fcrᵢ,Γᵢ) ∈ zip(fcrm,Γ)])
Plotly.plot([patch(Γᵢ, norm.(fcrᵢ), caxis=(0,2)) for (fcrᵢ,Γᵢ) ∈ zip(fcrj,Γ)])
function nearfield(um,Xm,uj,Xj,κ,η,points)
K = BEAST.MWDoubleLayerField3D(wavenumber=κ)
T = BEAST.MWSingleLayerField3D(wavenumber=κ)
Em = potential(K, points, um, Xm)
Ej = potential(T, points, uj, Xj)
Hm = potential(T, points, um, Xm)
Hj = potential(K, points, uj, Xj)
return -Em + η * Ej, 1/η*Hm + Hj
end
Xs = range(-2.0,2.0,length=150)
Zs = range(-1.5,2.5,length=100)
pts = [point(x,0.5,z) for z in Zs, x in Xs]
EH0 = [nearfield(u[qᵢ][m], Xᵢ, u[qᵢ][j], Yᵢ, κ₀, 1.0, pts) for (qᵢ,Xᵢ,Yᵢ) ∈ zip(q,Xₕ,Yₕ)]
EHi = [nearfield(-u[qᵢ][m], Xᵢ, -u[qᵢ][j], Yᵢ, κᵢ, 1.0, pts) for (qᵢ,Xᵢ,Yᵢ,κᵢ) ∈ zip(q,Xₕ,Yₕ,κ)]
Eo = sum(getindex.(EH0,1)) + Einc.(pts)
Ho = sum(getindex.(EH0,2)) + Hinc.(pts)
Ei = getindex.(EHi,1)
Hi = getindex.(EHi,2)
Etot = Eo + sum(Ei)
Htot = Ho + sum(Hi)
import Plots
Plots.heatmap(Xs, Zs, clamp.(real.(getindex.(Etot,2)),-2.0,2.0); colormap=:viridis) | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 3909 | using CompScienceMeshes
using BEAST
using LinearAlgebra
trias = CompScienceMeshes.meshrectangle(1.0,1.0,0.05)
trias = CompScienceMeshes.meshcircle(1.0,0.5)
tetrs = CompScienceMeshes.tetmeshcuboid(1,1,1,0.2)
f = BEAST.ScalarTrace{Float64}(x -> sin(pi*x[1]*x[2])*sin(pi*x[2]))
f2 = BEAST.ScalarTrace{Float64}(x -> (-x[2]*sin(2*pi*(x[1]^2+x[2]^2))*sin(atan(x[2],x[1])), x[1]*sin(2*pi*(x[1]^2+x[2]^2))*sin(atan(x[2],x[1])), 0) )
g = BEAST.ScalarTrace{Float64}(x -> (sin(pi*x[1])*cos(pi*x[2]), -cos(pi*x[1])*sin(pi*x[2]), 0 ))
g = BEAST.ScalarTrace{Float64}(x -> (sin(pi*x[1])*cos(pi*x[2]), sin(pi*x[2])*cos(pi*x[2]), sin(pi*x[3])*cos(pi*x[2])))
g2 = BEAST.ScalarTrace{Float64}(x -> ( sin(pi*x[1])*cos(pi*x[3]), 0, -cos(pi*x[1])*sin(pi*x[3])))
N = 4
h = Vector(undef, N)
errorL = Vector(undef, N)
errorBDM = Vector(undef, N)
errorRT = Vector(undef, N)
for n in 1:N
h[n] = 0.5^(n)
trias = CompScienceMeshes.meshrectangle(1.0,1.0, h[n])
# trias = CompScienceMeshes.meshcircle(1.0, h[n], 3)
Z = BEAST.lagrangec0d1(trias, dirichlet=false)
Y = BEAST.brezzidouglasmarini(trias)
X = BEAST.raviartthomas(trias)
u_exact = DofInterpolate(Z,f)
b_exact = DofInterpolate(Y,f2)
r_exact = DofInterpolate(X,f2)
identity = BEAST.Identity()
M = assemble(identity, Z, Z)
b = assemble(f,Z)
u_n = M \ b
errorL[n] = sqrt((u_n-u_exact)'*M*(u_n-u_exact))
M = assemble(identity, Y, Y)
b = assemble(f2,Y)
b_n = M \ b
errorBDM[n] = sqrt((b_n-b_exact)'*M*(b_n-b_exact))
M = assemble(identity, X, X)
b = assemble(f2,X)
r_n = M \ b
errorRT[n] = sqrt((r_n-r_exact)'*M*(r_n-r_exact))
end
N = 15
delta = Vector(undef, N)
error = Vector(undef, N)
for i in 1:N
delta[i] = 0.5-0.025*i
tetrs = tetmeshcuboid(1.0,1.0,1.0, delta[i])
bndry = boundary(tetrs)
faces = skeleton(tetrs, 2)
# onbnd1 = CompScienceMeshes.in(bnd_edges)
# onbnd0 = CompScienceMeshes.in(bnd_verts)
# interior_edges = submesh(!onbnd1, all_edges)
# interior_verts = submesh(!onbnd0, all_verts)
# bndry_faces = [sort(c) for c in cells(skeleton(bndry, 2))]
# function is_interior(faces)
# !(sort(faces) in bndry_faces)
# end
onbnd = CompScienceMeshes.in(bndry)
interior_faces = submesh(!onbnd, faces)
# interior_faces = submesh(is_interior, faces)
W = BEAST.brezzidouglasmarini3d(tetrs, interior_faces)
u_exact = DofInterpolate(W,g2)
identity = BEAST.Identity()
M = assemble(identity, W, W)
b = assemble(g2,W)
u_n = M \ b
error[i] = real(sqrt((u_n-u_exact)'*M*(u_n-u_exact)))
end
N=15
delta2 = Vector(undef, N)
error2 = Vector(undef, N)
for i in 1:N
delta2[i] =0.5-0.025*i
tetrs = tetmeshcuboid(1.0,1.0,1.0, delta2[i])
bndry = boundary(tetrs)
faces = skeleton(tetrs, 2)
# bndry_faces = [sort(c) for c in cells(skeleton(bndry, 2))]
# function is_interior(faces)
# !(sort(faces) in bndry_faces)
# end
# interior_faces = submesh(is_interior, faces)
onbnd = CompScienceMeshes.in(bndry)
interior_faces = submesh(!onbnd, faces)
V = BEAST.nedelecd3d(tetrs, interior_faces)
q_exact = DofInterpolate(V,g)
identity = BEAST.Identity()
M2 = assemble(identity, V, V)
b2 = assemble(g,V)
q_n = M2 \ b2
error2[i] = real(sqrt((q_n-q_exact)'*M2*(q_n-q_exact)))
end
using Plots
p2 = plot(delta,error, label="BDM3D", title="L2-Error on [0,1]^3",xlabel="h", ylabel="Error", legend=:bottomright, xaxis=:log, yaxis=:log)
plot!(p2, delta2, error2, label="Nedelec Div", xlims=[0.075,0.55])
p1 = plot(h,real(errorL), label="Lagrange", title="L2-Error on [0,1]^2",xlabel="h", ylabel="Error", legend=:bottomright, xaxis=:log, yaxis=:log, xlims=[0.025,0.5])
plot!(p1,h,real(errorBDM),label="BDM")
plot!(p1,h,real(errorRT),label="Raviart-Thomas")
plot(p1,p2, layout=2)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 239 | using CompScienceMeshes
using BEAST
sphere = CompScienceMeshes.tetmeshsphere(1.0, 0.35)
hemi = submesh((m,tet) -> cartesian(CompScienceMeshes.center(chart(m,tet)))[3] < 0, sphere)
X = BEAST.nedelecd3d(sphere)
Y = BEAST.restrict(X, hemi)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 223 | using CompScienceMeshes
using BEAST
m = CompScienceMeshes.tetmeshsphere(1.0, 0.45)
bnd_m = boundary(m)
m1 = skeleton(m,1)
X = BEAST.nedelecc3d(m,m1)
Y = BEAST.ttrace(X,bnd_m)
@assert length(geometry(Y)) == length(bnd_m)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1284 | using CompScienceMeshes, BEAST
h = 2π / 51; Γ = meshcircle(1.0, h)
X, Y = lagrangecxd0(Γ), lagrangec0d1(Γ)
κ = 1.0
S, Dᵀ = SingleLayer(κ), DoubleLayerTransposed(κ)
D, N = DoubleLayer(κ), HyperSingular(κ)
I = Identity()
# TM scattering
E = PlaneWaveDirichlet(κ, point(1.0,0.0))
H = PlaneWaveNeumann( κ, point(1.0,0.0))
@hilbertspace u; @hilbertspace u′
@hilbertspace t; @hilbertspace t′
tm_efie = @discretise S[u′,u] == E[u′] u∈X u′∈X
tm_mfie = @discretise (0.5I + Dᵀ)[t′,u] == H[t′] u∈X t′∈X
u1, u2 = solve(tm_efie), solve(tm_mfie)
# TE scattering
E = PlaneWaveNeumann( κ, point(1.0, 0.0))
H = PlaneWaveDirichlet(κ, point(1.0, 0.0))
te_efie = @discretise N[t,t′] == E[t′] t∈Y t′∈Y
te_mfie = @discretise (0.5I - D)[t,u′] == H[u′] t∈Y u′∈Y
t1, t2 = solve(te_efie), solve(te_mfie)
using Plots
nx = numfunctions(X);
Δα = 2π/nx; α = (collect(1:nx) .- 0.5) * Δα
plt1 = Plots.plot(α, real(u1), c=:blue, label="TM-EFIE")
Plots.scatter!(α, real(u2), c=:red, m=:circle, label="TM-MFIE")
Plots.title!("current vs. angle")
ny = numfunctions(Y);
Δα = 2π/ny; α = collect(0:ny-1) * Δα
plt2 = Plots.plot(α, real(t1), c=:blue, label="TE-EFIE")
Plots.scatter!(α, real(t2), c=:red, m=:circle, label="TE-MFIE")
Plots.title!("current vs. angle")
Plots.plot(plt1,plt2)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1516 | using CompScienceMeshes, BEAST
o, x, y, z = euclidianbasis(3)
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
X = lagrangecxd0(Γ)
# X = subdsurface(Γ)
# X = raviartthomas(Γ)
@show numfunctions(X)
κ = 1.0; γ = im*κ
a = Helmholtz3D.singlelayer(wavenumber=κ)
b = Helmholtz3D.doublelayer_transposed(gamma=κ*im) +0.5Identity()
uⁱ = Helmholtz3D.planewave(wavenumber=κ, direction=z)
f = strace(uⁱ,Γ)
g = ∂n(uⁱ)
@hilbertspace u
@hilbertspace v
eq1 = @discretise a[v,u] == f[v] u∈X v∈X
eq2 = @discretise b[v,u] == g[v] u∈X v∈X
x1 = gmres(eq1)
x2 = gmres(eq2)
fcr1, geo1 = facecurrents(x1, X)
fcr2, geo2 = facecurrents(x2, X)
# include(Pkg.dir("CompScienceMeshes","examples","plotlyjs_patches.jl"))
using LinearAlgebra
using Plotly
pt1 = Plotly.plot(patch(geo1, real.(norm.(fcr1))));
pt2 = Plotly.plot(patch(geo2, real.(norm.(fcr2))));
display([pt1 pt2])
# using Test
# ## test the results
# Z = assemble(a,X,X);
# m1, m2 = 1, numfunctions(X)
# chm, chn = chart(Γ,cells(Γ)[m1]), chart(Γ,cells(Γ)[m2])
# ctm, ctn = CompScienceMeshes.center(chm), CompScienceMeshes.center(chn)
# R = norm(cartesian(ctm)-cartesian(ctn))
# G = exp(-im*κ*R)/(4π*R)
# Wmn = volume(chm) * volume(chn) * G
# @show abs(Wmn-Z[m1,m2]) / abs(Z[m1,m2])
# @test abs(Wmn-Z[m1,m2]) / abs(Z[m1,m2]) < 2.0e-3
# r = assemble(f,X)
# m1 = 1
# chm = chart(Γ,cells(Γ)[m1])
# ctm = CompScienceMeshes.center(chm)
# sm = volume(chm) * f(ctm)
# r[m1]
# @show abs(sm - r[m1]) / abs(r[m1])
# @test abs(sm - r[m1]) / abs(r[m1]) < 1e-3
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1250 | using CompScienceMeshes, BEAST
using LinearAlgebra, Pkg
Pkg.activate(@__DIR__)
# Γ = readmesh(joinpath(@__DIR__,"sphere2.in"))
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
# Γ = meshrectangle(1.0, 1.0, 0.05, 3)
X = lagrangec0d1(Γ)
@show numfunctions(X)
κ = 2π; γ = im*κ
a = -1Helmholtz3D.hypersingular(gamma=γ)
b = Helmholtz3D.doublelayer(gamma=γ) - 0.5Identity()
uⁱ = Helmholtz3D.planewave(wavenumber=κ, direction=ẑ)
f = strace(uⁱ,Γ)
g = ∂n(uⁱ)
@hilbertspace u
@hilbertspace v
eq1 = @discretise a[v,u] == g[v] u∈X v∈X
eq2 = @discretise b[v,u] == f[v] u∈X v∈X
x1 = gmres(eq1)
x2 = gmres(eq2)
# @assert norm(x1-x2)/norm(x1+x2) < 0.5e-2
fcr1, geo1 = facecurrents(x1, X)
fcr2, geo2 = facecurrents(x2, X)
using Plots
Plots.plot(title="Comparse 1st and 2nd kind eqs.")
Plots.plot!(norm.(fcr1),c=:blue,label="1st")
Plots.scatter!(norm.(fcr2),c=:red,label="2nd")
import Plotly
plt1 = Plotly.plot(patch(Γ, norm.(fcr1)))
plt2 = Plotly.plot(patch(Γ, norm.(fcr2)))
display([plt1 plt2])
ys = range(-2,2,length=200)
zs = range(-2,2,length=200)
pts = [point(0.5, y, z) for y in ys, z in zs]
nf = BEAST.HH3DDoubleLayerNear(wavenumber=κ)
near = BEAST.potential(nf, pts, x1, X, type=ComplexF64)
inc = uⁱ.(pts)
tot = near + inc
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 8372 | using BEAST
using CompScienceMeshes
using StaticArrays
using LinearAlgebra
using Plotly
## Looking at convergence
hs = [0.3, 0.2, 0.1, 0.09]#,0.08,0.07,0.06,0.04]
ir = 0.8
err_IDPSL_pot = zeros(Float64, length(hs))
err_IDPDL_pot = zeros(Float64, length(hs))
err_INPSL_pot = zeros(Float64, length(hs))
err_INPDL_pot = zeros(Float64, length(hs))
err_IDPSL_field = zeros(Float64, length(hs))
err_IDPDL_field = zeros(Float64, length(hs))
err_INPSL_field = zeros(Float64, length(hs))
err_INPDL_field = zeros(Float64, length(hs))
err_EDPSL_pot = zeros(Float64, length(hs))
err_EDPDL_pot = zeros(Float64, length(hs))
err_ENPSL_pot = zeros(Float64, length(hs))
err_ENPDL_pot = zeros(Float64, length(hs))
err_EDPSL_field = zeros(Float64, length(hs))
err_EDPDL_field = zeros(Float64, length(hs))
err_ENPSL_field = zeros(Float64, length(hs))
err_ENPDL_field = zeros(Float64, length(hs))
for (i, h) in enumerate(hs)
r = 50.0
sphere = meshsphere(r, h * r)
X0 = lagrangecxd0(sphere)
X1 = lagrangec0d1(sphere)
S = Helmholtz3D.singlelayer(; gamma=0.0)
D = Helmholtz3D.doublelayer(; gamma=0.0)
Dt = Helmholtz3D.doublelayer_transposed(; gamma=0.0)
N = Helmholtz3D.hypersingular(; gamma=0.0)
q = 100.0
ϵ = 1.0
# Interior problem
# Formulations from Sauter and Schwab, Boundary Element Methods(2011), Chapter 3.4.1.1
pos1 = SVector(r * 1.5, 0.0, 0.0)
pos2 = SVector(-r * 1.5, 0.0, 0.0)
charge1 = HH3DMonopole(position=pos1, amplitude=q/(4*π*ϵ), wavenumber=0.0)
charge2 = HH3DMonopole(position=pos2, amplitude=-q/(4*π*ϵ), wavenumber=0.0)
#Potential of point charges
Φ_inc(x) = charge1(x) + charge2(x)
gD0 = assemble(DirichletTrace(charge1), X0) + assemble(DirichletTrace(charge2), X0)
gD1 = assemble(DirichletTrace(charge1), X1) + assemble(DirichletTrace(charge2), X1)
gN = assemble(∂n(charge1), X1) + assemble(BEAST.n ⋅ grad(charge2), X1)
G = assemble(Identity(), X1, X1)
o = ones(numfunctions(X1))
#Interior Dirichlet problem - compare Sauter & Schwab
M_IDPSL = assemble(S, X0, X0)
M_IDPDL = (-1 / 2 * assemble(Identity(), X1, X1) + assemble(D, X1, X1))
#Interior Neumann problem
M_INPSL = (1 / 2 * assemble(Identity(), X1, X1) + assemble(Dt, X1, X1)) + G * o * o' * G
M_INPDL = assemble(N, X1, X1) + G * o * o' * G
ρ_IDPSL = M_IDPSL \ (-gD0)
ρ_IDPDL = M_IDPDL \ (-gD1)
ρ_INPSL = M_INPSL \ (-gN)
ρ_INPDL = M_INPDL \ (gN)
pts = meshsphere(r * ir, r * ir * 0.6).vertices
pot_IDPSL = potential(HH3DSingleLayerNear(0.0), pts, ρ_IDPSL, X0; type=ComplexF64)
pot_IDPDL = potential(HH3DDoubleLayerNear(0.0), pts, ρ_IDPDL, X1; type=ComplexF64)
pot_INPSL = potential(HH3DSingleLayerNear(0.0), pts, ρ_INPSL, X1; type=ComplexF64)
pot_INPDL = potential(HH3DDoubleLayerNear(0.0), pts, ρ_INPDL, X1; type=ComplexF64)
# Total potential inside should be zero
err_IDPSL_pot[i] = norm(pot_IDPSL + Φ_inc.(pts)) ./ norm(Φ_inc.(pts))
err_IDPDL_pot[i] = norm(pot_IDPDL + Φ_inc.(pts)) ./ norm(Φ_inc.(pts))
err_INPSL_pot[i] = norm(pot_INPSL + Φ_inc.(pts)) ./ norm(Φ_inc.(pts))
err_INPDL_pot[i] = norm(pot_INPDL + Φ_inc.(pts)) ./ norm(Φ_inc.(pts))
Efield(x) = -grad(charge1)(x) + -grad(charge2)(x)
field_IDPSL = -potential(HH3DDoubleLayerTransposedNear(0.0), pts, ρ_IDPSL, X0)
field_IDPDL = -potential(HH3DHyperSingularNear(0.0), pts, ρ_IDPDL, X1)
field_INPSL = -potential(HH3DDoubleLayerTransposedNear(0.0), pts, ρ_INPSL, X1)
field_INPDL = -potential(HH3DHyperSingularNear(0.0), pts, ρ_INPDL, X1)
# Total field inside should be zero
err_IDPSL_field[i] = norm(field_IDPSL + Efield.(pts)) / norm(Efield.(pts))
err_IDPDL_field[i] = norm(field_IDPDL + Efield.(pts)) / norm(Efield.(pts))
err_INPSL_field[i] = norm(field_INPSL + Efield.(pts)) / norm(Efield.(pts))
err_INPDL_field[i] = norm(field_INPDL + Efield.(pts)) / norm(Efield.(pts))
# Exterior problem
# formulations from Sauter and Schwab, Boundary Element Methods(2011), Chapter 3.4.1.2
pos1 = SVector(r * 0.5, 0.0, 0.0)
pos2 = SVector(-r * 0.5, 0.0, 0.0)
charge1 = HH3DMonopole(position=pos1, amplitude=q/(4*π*ϵ), wavenumber=0.0)
charge2 = HH3DMonopole(position=pos2, amplitude=-q/(4*π*ϵ), wavenumber=0.0)
gD0 = assemble(DirichletTrace(charge1), X0) + assemble(DirichletTrace(charge2), X0)
gD1 = assemble(DirichletTrace(charge1), X1) + assemble(DirichletTrace(charge2), X1)
gN = assemble(∂n(charge1), X1) + assemble(∂n(charge2), X1)
G = assemble(Identity(), X1, X1)
o = ones(numfunctions(X1))
M_EDPSL = assemble(S, X0, X0)
M_EDPDL = (1 / 2 * assemble(Identity(), X1, X1) + assemble(D, X1, X1))
M_ENPSL = (-1 / 2 * assemble(Identity(), X1, X1) + assemble(Dt, X1, X1)) + G * o * o' * G
M_ENPDL = assemble(N, X1, X1) + G * o * o' * G
ρ_EDPSL = M_EDPSL \ (-gD0)
ρ_EDPDL = M_EDPDL \ (-gD1)
ρ_ENPSL = M_ENPSL \ (-gN)
ρ_ENPDL = M_ENPDL \ (gN)
testsphere = meshsphere(r / ir, r / ir * 0.6)
pts = testsphere.vertices[norm.(testsphere.vertices) .> r]
pot_EDPSL = potential(HH3DSingleLayerNear(0.0), pts, ρ_EDPSL, X0; type=ComplexF64)
pot_EDPDL = potential(HH3DDoubleLayerNear(0.0), pts, ρ_EDPDL, X1; type=ComplexF64)
pot_ENPSL = potential(HH3DSingleLayerNear(0.0), pts, ρ_ENPSL, X1; type=ComplexF64)
pot_ENPDL = potential(HH3DDoubleLayerNear(0.0), pts, ρ_ENPDL, X1; type=ComplexF64)
err_EDPSL_pot[i] = norm(pot_EDPSL + Φ_inc.(pts)) ./ norm(Φ_inc.(pts))
err_EDPDL_pot[i] = norm(pot_EDPDL + Φ_inc.(pts)) ./ norm(Φ_inc.(pts))
err_ENPSL_pot[i] = norm(pot_ENPSL + Φ_inc.(pts)) ./ norm(Φ_inc.(pts))
err_ENPDL_pot[i] = norm(pot_ENPDL + Φ_inc.(pts)) ./ norm(Φ_inc.(pts))
field_EDPSL = -potential(HH3DDoubleLayerTransposedNear(0.0), pts, ρ_EDPSL, X0)
field_EDPDL = -potential(HH3DHyperSingularNear(0.0), pts, ρ_EDPDL, X1)
field_ENPSL = -potential(HH3DDoubleLayerTransposedNear(0.0), pts, ρ_ENPSL, X1)
field_ENPDL = -potential(HH3DHyperSingularNear(0.0), pts, ρ_ENPDL, X1)
err_EDPSL_field[i] = norm(field_EDPSL + Efield.(pts)) / norm(Efield.(pts))
err_EDPDL_field[i] = norm(field_EDPDL + Efield.(pts)) / norm(Efield.(pts))
err_ENPSL_field[i] = norm(field_ENPSL + Efield.(pts)) / norm(Efield.(pts))
err_ENPDL_field[i] = norm(field_ENPDL + Efield.(pts)) / norm(Efield.(pts))
end
##
Plotly.plot(
[
Plotly.scatter(; x=hs, y=err_IDPSL_pot[:, end], name="IDPSL"),
Plotly.scatter(; x=hs, y=err_IDPDL_pot[:, end], name="IDPDL"),
Plotly.scatter(; x=hs, y=err_INPSL_pot[:, end], name="INPSL"),
Plotly.scatter(; x=hs, y=err_INPDL_pot[:, end], name="INPDL"),
],
Layout(;
xaxis_type="log",
yaxis_type="log",
xaxis_title="h / r",
yaxis_title="rel. error",
title="Errors - potential - interior problem",
),
)
Plotly.plot(
[
Plotly.scatter(; x=hs, y=err_EDPSL_pot[:, end], name="EDPSL"),
Plotly.scatter(; x=hs, y=err_EDPDL_pot[:, end], name="EDPDL"),
Plotly.scatter(; x=hs, y=err_ENPSL_pot[:, end], name="ENPSL"),
Plotly.scatter(; x=hs, y=err_ENPDL_pot[:, end], name="ENPDL"),
],
Layout(;
xaxis_type="log",
yaxis_type="log",
xaxis_title="h / r",
yaxis_title="rel. error",
title="Errors - potential - exterior problem",
),
)
Plotly.plot(
[
Plotly.scatter(; x=hs, y=err_IDPSL_field[:, end], name="IDPSL"),
Plotly.scatter(; x=hs, y=err_IDPDL_field[:, end], name="IDPDL"),
Plotly.scatter(; x=hs, y=err_INPSL_field[:, end], name="INPSL"),
Plotly.scatter(; x=hs, y=err_INPDL_field[:, end], name="INPDL"),
],
Layout(;
xaxis_type="log",
yaxis_type="log",
xaxis_title="h / r",
yaxis_title="rel. error",
title="Errors - field - interior problem",
),
)
Plotly.plot(
[
Plotly.scatter(; x=hs, y=err_EDPSL_field[:, end], name="EDPSL"),
Plotly.scatter(; x=hs, y=err_EDPDL_field[:, end], name="EDPDL"),
Plotly.scatter(; x=hs, y=err_ENPSL_field[:, end], name="ENPSL"),
Plotly.scatter(; x=hs, y=err_ENPDL_field[:, end], name="ENPDL"),
],
Layout(;
xaxis_type="log",
yaxis_type="log",
xaxis_title="h / r",
yaxis_title="rel. error",
title="Errors - field - exterior problem",
),
) | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 2705 | using BEAST
using CompScienceMeshes
using StaticArrays
using LinearAlgebra
using Test
using Plots
using SphericalScattering
# Layered Dielectic Sphere
# MoM (Lippmann Schwinger VIE) vs. Analytical Solution (SphericalScattering)
# Environment
ε1 = 1.0*ε0
μ1 = μ0
# Layered Dielectic Sphere
ε2 = 5.0*ε0 # outer shell
μ2 = μ0
ε3 = 20.0*ε0
μ3 = μ0
ε4 = 7.0*ε0
μ4 = μ0
ε5 = 30.0*ε0 # inner core
μ5 = μ0
r = 1.0
radii = SVector(0.2*r, 0.6*r, 0.8*r, r) # inner core stops at first radius
filling = SVector(Medium(ε5, μ5), Medium(ε4, μ4), Medium(ε3, μ3), Medium(ε2, μ2))
# Mesh, Basis
h = 0.1
mesh = CompScienceMeshes.tetmeshsphere(r,h)
X = lagrangec0d1(mesh; dirichlet = false)
@show numfunctions(X)
bnd = boundary(mesh)
strc = X -> strace(X, bnd)
# VIE Operators
function generate_tau(ε_env, radii, filling)
function tau(x::SVector{U,T}) where {U,T}
for (i, radius) in enumerate(radii)
norm(x) <= radius && (return T(1.0 - filling[i].ε/ε_env))
end
#return 0.0
error("Evaluated contrast outside the sphere!")
end
return tau
end
τ = generate_tau(ε1, radii, filling) #contrast function
I = Identity()
V = VIE.hhvolume(tau = τ, wavenumber = 0.0)
B = VIE.hhboundary(tau = τ, wavenumber = 0.0)
Y = VIE.hhvolumegradG(tau = τ, wavenumber = 0.0)
# Exitation
dirE = SVector(1.0, 0.0, 0.0)
dirgradΦ = - dirE
amp = 1.0
Φ_inc = VIE.linearpotential(direction = dirgradΦ, amplitude = amp)
# Assembly
b = assemble(Φ_inc, X)
Z_I = assemble(I, X, X)
Z_V = assemble(V, X, X)
Z_B = assemble(B, strc(X), X)
Z_Y = assemble(Y, X, X)
# System matrix
Z_version1 = Z_I + Z_V + Z_B
Z_version2 = Z_I + Z_Y
# Solution of the linear system of equations
u_version1 = Z_version1 \ Vector(b)
u_version2 = Z_version2 \ Vector(b)
## Observe the potential on a x-line in dirgradΦ direction
# x-line at y0, z0 - Potential only inside the sphere mesh valid!
y0 = 0.0
z0 = 0.0
x_range = range(0.0, stop = 1.0*r, length = 200)
points_x = [point(x, y0, z0) for x in x_range]
x = collect(x_range)
# SphericalScattering solution on x-line
sp = LayeredSphere(radii = radii, filling = filling)
ex = UniformField(direction = dirE, amplitude = amp)
Φ_x = real.(field(sp, ex, ScalarPotential(points_x)))
# MoM solution on x-line
Φ_MoM_version1_x = BEAST.grideval(points_x, u_version1, X, type = Float64)
Φ_MoM_version2_x = BEAST.grideval(points_x, u_version2, X, type = Float64)
# Plot
plot(x, Φ_x, label = "SphericalScattering")
plot!(x, Φ_MoM_version1_x, label = "MoM: S=I+B+V, boundary+volume")
plot!(x, Φ_MoM_version2_x, label = "MoM: S=I+Y, gradgreen")
xlims!(0.0, 1.0) # sphere center to radius r
ylims!(-0.3, 0.0)
title!("Potential Φ(x, y0, z0)")
xlabel!("x") | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1750 | using CompScienceMeshes
using BEAST
using LinearAlgebra
width, height, h = 1.0, 0.5, 0.05
ℑ₁ = meshrectangle(width, height, h)
ℑ₂ = CompScienceMeshes.rotate(ℑ₁, 0.5π * x̂)
ℑ₃ = CompScienceMeshes.rotate(ℑ₁, 1.0π * x̂)
Γ₁ = weld(ℑ₁,-ℑ₂)
Γ₂ = weld(ℑ₂,-ℑ₃)
X₁ = raviartthomas(Γ₁)
X₂ = raviartthomas(Γ₂)
Y₁ = buffachristiansen(Γ₁)
Y₂ = buffachristiansen(Γ₂)
X = X₁ × X₂
Y = Y₁ × Y₂
@hilbertspace p
@hilbertspace q
κ = 3.0
SL = Maxwell3D.singlelayer(wavenumber=κ)
N = NCross()
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n;
import BEAST: diag, blocks
Sxx = assemble(@discretise blocks(SL)[p,q] p∈X q∈X)
ex = assemble(e, X)
# Build the preconditioner
Nxy = assemble(@discretise(BEAST.diag(N)[p,q], p∈X, q∈Y))
Dyx = BEAST.GMRESSolver(Nxy, tol=2e-12, restart=250, verbose=false)
Dxy = BEAST.GMRESSolver(transpose(Nxy), tol=2e-12, restart=250, verbose=false)
Syy = BEAST.assemble(@discretise BEAST.diag(SL)[p,q] p∈Y q∈Y)
P = Dxy * Syy * Dyx
# Solve system without and with preconditioner
u1, ch1 = solve(BEAST.GMRESSolver(Sxx,tol=2e-5, restart=250), ex)
u2, ch2 = solve(BEAST.GMRESSolver(P*Sxx, tol=2e-5, restart=250), P*ex)
# error()
# Q = P*Sxx
# S = BEAST.GMRESSolver(Q, tol=2e-5, restart=250)
# rhs = P*ex
# @run solve(S, rhs)
# Compute and visualise the far field
Φ, Θ = [0.0], range(0,stop=π,length=100)
pts = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for ϕ in Φ for θ in Θ]
near1 = potential(MWFarField3D(wavenumber=κ), pts, u1, X)
near2 = potential(MWFarField3D(wavenumber=κ), pts, u2, X)
using Plots
@show norm(u1-u2)
# Plots.plot(title="far field")
Plots.plot!(Θ, real.(getindex.(near1,1)), label="no preconditioner")
Plots.scatter!(Θ, real.(getindex.(near2,1)), label="Calderon preconditioner") | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 710 | using CompScienceMeshes, BEAST
width, height, h = 1.0, 0.5, 0.05
G1 = meshrectangle(width, height, h)
G2 = CompScienceMeshes.rotate(G1, 0.5π * x̂)
G3 = CompScienceMeshes.rotate(G1, 1.0π * x̂)
G = weld(G1, G2, G3)
X = raviartthomas(G)
κ = 1.0
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n
T = Maxwell3D.singlelayer(wavenumber=κ)
@hilbertspace j; @hilbertspace k
efie = @discretise T[k,j]==e[k] j∈X k∈X
u = gmres(efie)
Θ, Φ = range(0.0,stop=π,length=100), 0.0
ffpoints = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for θ in Θ for ϕ in Φ]
farfield = potential(MWFarField3D(wavenumber=κ), ffpoints, u, X)
using Plots
using LinearAlgebra
Plots.plot(Θ,norm.(farfield))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 620 | using CompScienceMeshes
using BEAST
using LinearAlgebra
import Plotly
m = meshsphere(radius=1.0, h=0.25)
nodes = skeleton(m,0)
edges = skeleton(m,1)
X = BEAST.lagrangec0d2(m, nodes, edges)
Y = BEAST.lagrangecxd0(m)
uⁱ = Helmholtz3D.planewave(wavenumber=1.0, direction=point(0,0,1))
f = strace(uⁱ,m)
fy = assemble(f,Y)
Id = BEAST.Identity()
qs = BEAST.SingleNumQStrat(8)
Gxy = assemble(Id, X, Y, quadstrat=qs)
Gxx = assemble(Id, X, X, quadstrat=qs)
Gyy = assemble(Id, Y, Y, quadstrat=qs)
Pxy = inv(Matrix(Gxx)) * Gxy * inv(Matrix(Gyy))
fX = Pxy * fy
fcr, geo = facecurrents(fX, X)
Plotly.plot(patch(m, real.(fcr))) | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 582 | using CompScienceMeshes, BEAST
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
X, Y = raviartthomas(Γ), buffachristiansen(Γ)
ϵ, μ, ω = 1.0, 1.0, 1.0; κ, η = ω * √(ϵ*μ), √(μ/ϵ)
K, N = Maxwell3D.doublelayer(wavenumber=κ), NCross()
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
# E = -η/(im*κ)*BEAST.CurlCurlGreen(κ, ẑ, point(2,0,0))
H = -1/(im*μ*ω)*curl(E)
h = (n × H) × n
@hilbertspace j
@hilbertspace m
mfie = @discretise (K+0.5N)[m,j] == h[m] j∈X m∈Y
u = gmres(mfie)
include("utils/postproc.jl")
include("utils/plotresults.jl")
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 666 | using CompScienceMeshes, BEAST
# Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
Γ = meshsphere(radius=1.0, h=0.1)
# X, Y = raviartthomas(Γ), buffachristiansen(Γ)
X = brezzidouglasmarini(Γ)
Y = brezzidouglasmarini(Γ)
# X = raviartthomas(Γ)
# Y = raviartthomas(Γ)
ϵ, μ, ω = 1.0, 1.0, 1.0; κ = ω * √(ϵ*μ)
# κ = 3.0
NK, Id = BEAST.DoubleLayerRotatedMW3D(1.0, im*κ), Identity()
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
H = -1/(im*μ*ω)*curl(E)
h = n × H
@hilbertspace j
@hilbertspace m
mfie = @discretise (NK-0.5Id)[m,j] == h[m] j∈X m∈Y
u = gmres(mfie)
include("utils/postproc.jl")
include("utils/plotresults.jl")
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 963 | using CompScienceMeshes, BEAST
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
X = raviartthomas(Γ)
Y = buffachristiansen(Γ)
Z = raviartthomas(Γ, BEAST.Continuity{:none})
ϵ, μ, ω = 1.0, 1.0, 1.0; κ = ω * √(ϵ*μ)
K, N = Maxwell3D.doublelayer(wavenumber=κ), NCross()
NK, Id = BEAST.DoubleLayerRotatedMW3D(im*κ), Identity()
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
H = -1/(im*μ*ω)*curl(E)
h = (n × H) × n
q = n × H
@hilbertspace j
@hilbertspace m
@hilbertspace g
mfie1 = @discretise (K+0.5N)[m,j] == h[m] j∈X m∈Y
mfie2 = @discretise (NK-0.5Id)[g,j] == q[m] j∈Z g∈Z
u1 = gmres(mfie1)
u2 = gmres(mfie2)
fcr1, _ = facecurrents(u1, X)
fcr2, _ = facecurrents(u2, Z)
using LinearAlgebra
using Plots
Plots.plot(title="Compare current density")
Plots.plot!(norm.(fcr1), label="MxMIFE")
Plots.scatter!(norm.(fcr2), label="DGMFIE", c=:red)
u = u2
X = Z
include("utils/postproc.jl")
include("utils/plotresults.jl")
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1502 | using CompScienceMeshes, BEAST
function blkdiagm(blks...)
m = sum(size(b,1) for b in blks)
n = sum(size(b,2) for b in blks)
A = zeros(eltype(first(blks)), m, n)
o1 = 1
o2 = 1
for b in blks
m1 = size(b,1)
n1 = size(b,2)
A[o1:o1+m1-1,o2:o2+n1-1] .= b
o1 += m1
o2 += n1
end
A
end
width, height, h = 1.0, 0.5, 0.05
G1 = meshrectangle(width, height, h)
G2 = CompScienceMeshes.rotate(G1, 0.5π * x̂)
G3 = CompScienceMeshes.rotate(G1, 1.0π * x̂)
G12 = weld(G1,-G2)
G23 = weld(G2,-G3)
G31 = weld(G3,-G1)
X12 = lagrangec0d1(G12)
X23 = lagrangec0d1(G23)
X31 = lagrangec0d1(G31)
Y12 = duallagrangecxd0(G12)
Y23 = duallagrangecxd0(G23)
Y31 = duallagrangecxd0(G31)
κ = 1.0
SL = Helmholtz3D.singlelayer(wavenumber=κ)
HS = Helmholtz3D.hypersingular(gamma=κ*im)
N = Identity()
X = X12 × X23 × X31
Y = Y12 × Y23 × Y31
E = Helmholtz3D.planewave(direction=ẑ, wavenumber=κ)
e = strace(E, G12)
ex = assemble(e, X)
Sxx = assemble(SL, X, X)
N1 = assemble(Identity(), X12, Y12)
N2 = assemble(Identity(), X23, Y23)
N3 = assemble(Identity(), X31, Y31)
Nxy = blkdiagm(N1,N2,N3)
Syy = assemble(HS, Y, Y)
Dyx = inv(Nxy)
Q = transpose(Dyx) * Syy * Dyx * Sxx
R = transpose(Dyx) * Syy * Dyx * ex
u1, ch1 = solve(BEAST.GMRESSolver(Sxx),ex)
u2, ch2 = solve(BEAST.GMRESSolver(Q),R)
@show ch1.iters
@show ch2.iters
using LinearAlgebra
cond(Sxx)
cond(Q)
w1 = eigvals(Sxx)
w2 = eigvals(Q)
using Plots
Plots.plot()
Plots.scatter!(w1)
Plots.scatter!(w2)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 2972 | using CompScienceMeshes, BEAST
width, height, h = 1.0, 0.5, 0.05
G1 = meshrectangle(width, height, h)
G2 = CompScienceMeshes.rotate(G1, 0.5π * x̂)
G3 = CompScienceMeshes.rotate(G1, 1.0π * x̂)
G12 = weld(G1,-G2)
G23 = weld(G2,-G3)
G31 = weld(G3,-G1)
X12 = raviartthomas(G12)
X23 = raviartthomas(G23)
X31 = raviartthomas(G31)
Y12 = buffachristiansen(G12)
Y23 = buffachristiansen(G23)
Y31 = buffachristiansen(G31)
κ = 1.0
SL = Maxwell3D.singlelayer(wavenumber=κ)
N = NCross()
X = X12 × X23 × X31
Y = Y12 × Y23 × Y31
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n
@hilbertspace j
@hilbertspace k
mtefie = @discretise(
SL[k,j] == e[k],
j ∈ X, k ∈ X)
# u = gmres(mtefie)
#
# offset = 1; u12 = u[offset:offset+numfunctions(X12)-1]
# offset += numfunctions(X12); u23 = u[offset:offset+numfunctions(X23)-1]
# offset += numfunctions(X23); u31 = u[offset:offset+numfunctions(X31)-1]
#
# fcr12, _ = facecurrents(u12, X12)
# fcr23, _ = facecurrents(u23, X23)
# fcr31, _ = facecurrents(u31, X31)
import Plotly
using LinearAlgebra
# p1 = PlotlyJS.Plot(patch(G12, norm.(fcr12)))
# p2 = PlotlyJS.Plot(patch(G23, norm.(fcr23)))
# p3 = PlotlyJS.Plot(patch(G31, norm.(fcr31)))
# PlotlyJS.plot([p1, p2, p3])
function blkdiagm(blks...)
m = sum(size(b,1) for b in blks)
n = sum(size(b,2) for b in blks)
A = zeros(eltype(first(blks)), m, n)
o1 = 1
o2 = 1
for b in blks
m1 = size(b,1)
n1 = size(b,2)
A[o1:o1+m1-1,o2:o2+n1-1] .= b
o1 += m1
o2 += n1
end
A
end
Sxx = BEAST.sysmatrix(mtefie)
N1 = assemble(N, X12, Y12)
N2 = assemble(N, X23, Y23)
N3 = assemble(N, X31, Y31)
Nxy = blkdiagm(N1,N2,N3)
Syy = assemble(SL, Y, Y)
iNxy = inv(Nxy)
# cond(Matrix(Sxx))
ex = assemble(e,X)
P = transpose(iNxy) * Syy * iNxy
Q = P * Sxx;
R = P * ex;
u1, ch1 = solve(BEAST.GMRESSolver(Sxx),ex)
u2, ch2 = solve(BEAST.GMRESSolver(Q),R)
@show ch1.iters
@show ch2.iters
# gmres()
ns = [
0,
numfunctions(X12),
numfunctions(X23),
numfunctions(X31)]
cns = cumsum(ns)
u12 = u1[cns[1]+1:cns[2]]
u23 = u1[cns[2]+1:cns[3]]
u31 = u1[cns[3]+1:cns[4]]
fcr1, geo1 = facecurrents(u12, X12)
fcr2, geo2 = facecurrents(u23, X23)
fcr3, geo3 = facecurrents(u31, X31)
p1 = patch(geo1, norm.(fcr1))
p2 = patch(geo2, norm.(fcr2))
p3 = patch(geo3, norm.(fcr3))
Plotly.plot([p1,p2,p3])
G123 = weld(G1,G2,G3)
X123 = raviartthomas(G123)
stefie = @discretise(
SL[k,j] == e[k],
j ∈ X123, k ∈ X123)
Sst = assemble(SL, X123, X123)
bst = assemble(e, X123)
ust, chst = solve(BEAST.GMRESSolver(Sst),bst)
fcrst, geost = facecurrents(ust, X123)
Plotly.plot(patch(geost, norm.(fcrst)))
Φ, Θ = [0.0], range(0,stop=π,length=100)
pts = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for ϕ in Φ for θ in Θ]
ffd_mt = potential(MWFarField3D(wavenumber=κ), pts, u1, X)
ffd_st = potential(MWFarField3D(wavenumber=κ), pts, ust, X123)
Plots.plot(norm.(ffd_mt))
Plots.scatter!(norm.(ffd_st)) | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 873 | using BEAST
using CompScienceMeshes
fn = joinpath(@__DIR__,"assets","thick_cladding.msh")
G01 = CompScienceMeshes.read_gmsh_mesh(fn, physical="Gamma01")
G02 = CompScienceMeshes.read_gmsh_mesh(fn, physical="Gamma02")
G12 = CompScienceMeshes.read_gmsh_mesh(fn, physical="Gamma12")
G = CompScienceMeshes.read_gmsh_mesh(fn)
@assert numcells(G01) + numcells(G02) + numcells(G12) == numcells(G)
# Build region boundaries with normals pointing inward:
G1 = weld(-G01, -G12)
@assert CompScienceMeshes.isoriented(G1)
G2 = weld(-G02, G12)
@assert CompScienceMeshes.isoriented(G2)
E1 = CompScienceMeshes.interior(G1)
E2 = CompScienceMeshes.interior(G2)
E = CompScienceMeshes.interior(G)
Nd = BEAST.nedelec(G, E)
Nd1 = BEAST.nedelec(G1, E1)
Nd2 = BEAST.nedelec(G2, E2)
RT1 = n × Nd1
RT2 = n × Nd2
A1 = CompScienceMeshes.embedding(E1,E)
A2 = CompScienceMeshes.embedding(E2,E)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 2104 | using CompScienceMeshes, BEAST
trc = X->ntrace(X,γ)
dvg = divergence
h1 = h2 = h3 = 1/15; h = max(h1, h2, h3)
width, height = 1.0, 0.5
Γ1 = meshrectangle(width, height, h1)
Γ2 = meshrectangle(width, height, h2); CompScienceMeshes.rotate!(Γ2, 0.5π*x̂)
Γ3 = meshrectangle(width, height, h3); CompScienceMeshes.rotate!(Γ3, 1.0π*x̂)
γ = meshsegment(width, width, 3)
κ = 1.0
S, T, I = SingleLayerTrace(κ*im), MWSingleLayer3D(κ), Identity()
St = transpose(S)
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n×E)×n
in_interior1 = CompScienceMeshes.interior_tpredicate(Γ1)
in_interior2 = CompScienceMeshes.interior_tpredicate(Γ2)
in_interior3 = CompScienceMeshes.interior_tpredicate(Γ3)
on_junction = CompScienceMeshes.overlap_gpredicate(γ)
edges1 = submesh((m,e)->in_interior1(m,e) || on_junction(chart(m,e)), skeleton(Γ1,1))
edges2 = submesh((m,e)->in_interior2(m,e) || on_junction(chart(m,e)), skeleton(Γ2,1))
edges3 = submesh((m,e)->in_interior3(m,e) || on_junction(chart(m,e)), skeleton(Γ3,1))
# edges1 = skeleton(e -> in_interior1(e) || on_junction(chart(Γ1,e)), Γ1,1)
# edges2 = skeleton(e -> in_interior2(e) || on_junction(chart(Γ2,e)), Γ2,1)
# edges3 = skeleton(e -> in_interior3(e) || on_junction(chart(Γ3,e)), Γ3,1)
X1 = raviartthomas(Γ1, edges1)
X2 = raviartthomas(Γ2, edges2)
X3 = raviartthomas(Γ3, edges3)
# X1, X2, X3 = raviartthomas(Γ1, γ), raviartthomas(Γ2, γ), raviartthomas(Γ3, γ)
X = X1 × X2 × X3
@hilbertspace j
@hilbertspace k
α, β = 1/(im*κ), log(abs(h))/(im*κ)
Eq = @varform T[k,j] + α*S[trc(k), dvg(j)] + α*St[dvg(k), trc(j)] + β*I[trc(k), trc(j)] == e[k]
eq = @discretise Eq j∈X k∈X
# trcX = trc(X)
# dvgX = dvg(X)
# Q1 = assemble(Eq.lhs.terms[2].kernel, trcX, dvgX; threading=BEAST.Threading{:single})
# Q2 = assemble(Eq.lhs.terms[3].kernel, dvgX, trcX; threading=BEAST.Threading{:single})
u = solve(eq)
Θ, Φ = range(0.0,stop=π,length=100), 0.0
ffpoints = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for θ in Θ for ϕ in Φ]
farfield = potential(MWFarField3D(wavenumber=κ), ffpoints, u, X)
using Plots
using LinearAlgebra
plot(Θ,norm.(farfield))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 5444 | using CompScienceMeshes
using BEAST
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
Γref = CompScienceMeshes.barycentric_refinement(Γ)
X = raviartthomas(Γ, BEAST.Continuity{:none})
Y = raviartthomas(Γref, BEAST.Continuity{:none})
# X = subset(X,1690:1692)
# Y = subset(Y,10141:10143)
# X = subset(X,[1692])
# Y = subset(Y,[10147])
# Y = buffachristiansen(Γ)
κ, η = 1.0, 1.0
t = Maxwell3D.singlelayer(wavenumber=κ)
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n
g = 6
# ssstrat(g) = BEAST.DoubleNumSauterQstrat(7, 6, g, g, g, g)
ssstrat(g) = BEAST.CommonFaceVertexSauterCommonEdgeWiltonPostitiveDistanceNumQStrat(
7, 6, 10, 8, g, g, g+3, g)
qs1 = ssstrat(g)
qs2 = BEAST.NonConformingIntegralOpQStrat(ssstrat(g))
A1 = assemble(t,Y,X, quadstrat=qs1, threading=BEAST.Threading{:single})
A2 = assemble(t,Y,X, quadstrat=qs2, threading=BEAST.Threading{:single})
# @enter assemble(t,Y,X, quadstrat=qs2, threading=BEAST.Threading{:single})
import Plots
Plots.plotly()
step = 1
rowidx = 10894
Plots.plot(imag.(A1[rowidx,1:step:end]))
Plots.scatter!(imag.(A2[rowidx,1:step:end]))
val, pos = findmax(abs.(A1-A2))
rowidx = Y.fns[pos[1]][1].cellid
colidx = X.fns[pos[2]][1].cellid
τ = chart(Γref, rowidx)
σ = chart(Γ, colidx)
# τ = [
# [0.18517788982868066, 0.05998671122432393, 0.9735312677690339],
# [0.1647116144395066, 0.0050896055947335095, 0.9807011064756881],
# [0.245326672427806, -0.06121735585211891, 0.9675056894602609]]
# σ = [
# [0.1133762981558132, -0.1176791567283826, 0.9865583769286949],
# [0.1647116144395066, 0.0050896055947335025, 0.9807011064756881],
# [0.08409655645120719, 0.07139656704158594, 0.9938965234911153]]
# eτ = simplex(
# point(0.1647116144395066, 0.0050896055947335095, 0.9807011064756881),
# point(0.245326672427806, -0.06121735585211891, 0.9675056894602609))
# eσ = simplex(
# point(0.1647116144395066, 0.0050896055947335025, 0.9807011064756881),
# point(0.08409655645120719, 0.07139656704158594, 0.9938965234911153))
# CompScienceMeshes.overlap(eτ, eσ)
# τ = τ.vertices
# σ = σ.vertices
import Plotly
function Plotly.mesh3d(a::Vector{<:CompScienceMeshes.Simplex}; opacity=0.5, kwargs...)
T = coordtype(a[1])
n = length(a)
X = Vector{T}(undef, 3*n)
Y = Vector{T}(undef, 3*n)
Z = Vector{T}(undef, 3*n)
for i in 1:n
X[3*(i-1)+1:3*i] = getindex.(a[i].vertices, 1)
Y[3*(i-1)+1:3*i] = getindex.(a[i].vertices, 2)
Z[3*(i-1)+1:3*i] = getindex.(a[i].vertices, 3)
end
I = collect(0:3:3*(n-1))
J = I .+ 1
K = I .+ 2
return Plotly.mesh3d(x=X,y=Y,z=Z,i=I,j=J,k=K; opacity, kwargs...)
end
m1 = Plotly.mesh3d([τ], opacity=0.5)
m2 = Plotly.mesh3d([σ], opacity=0.5)
# m1 = Plotly.mesh3d(
# x=getindex.(τ,1),
# y=getindex.(τ,2),
# z=getindex.(τ,3),
# i=[0], j=[1], k=[2])
# m2 = Plotly.mesh3d(
# x=getindex.(σ,1),
# y=getindex.(σ,2),
# z=getindex.(σ,3),
# i=[0], j=[1], k=[2])
Plotly.plot([m1,m2])
isct1, clps1 = CompScienceMeshes.intersection_keep_clippings(τ,σ)
isct2, clps2 = CompScienceMeshes.intersection_keep_clippings(σ,τ)
m3 = Plotly.mesh3d(isct1, opacity=0.5, color="blue")
m4 = Plotly.mesh3d(isct2, opacity=0.5, color="red")
Plotly.plot([m3,m4])
m5 = Plotly.mesh3d(clps2[1], opacity=0.5, color="green")
m6 = Plotly.mesh3d(clps2[1][[1]], opacity=0.5, color="yellow")
Plotly.plot([m3,m6])
p = isct1[1]
q = clps2[1][1]
for (i,λ) in pairs(faces(p))
for (j,μ) in pairs(faces(q))
if CompScienceMeshes.overlap(λ, μ)
global gi = i
global gj = j
global qr = BEAST.NonConformingTouchQRule(qs1, i, j)
end end end
𝒳 = refspace(X)
𝒴 = refspace(Y)
out10 = zeros(ComplexF64, 3, 3)
BEAST.momintegrals!(t, 𝒴, 𝒳, p, q, out10, BEAST.NonConformingTouchQRule(ssstrat(10), gi, gj))
out20 = zeros(ComplexF64, 3, 3)
BEAST.momintegrals!(t, 𝒴, 𝒳, p, q, out20, BEAST.NonConformingTouchQRule(ssstrat(20), gi, gj))
@show out10[1,1] out20[1,1]
τs, σs = BEAST._conforming_refinement_touching_triangles(p,q,2,3)
@assert length(τs) == 1
@assert length(σs) == 2
@assert volume(p) ≈ sum(volume.(τs))
@assert volume(q) ≈ sum(volume.(σs))
@assert all(volume.(τs) .> eps(Float64)*1e3)
@assert all(volume.(σs) .> eps(Float64)*1e3)
m7 = Plotly.mesh3d(τs[[1]], color="blue", opacity=0.5)
m8 = Plotly.mesh3d(σs[[1]], color="red", opacity=0.5)
Plotly.plot([m7,m8])
out1_10 = zeros(ComplexF64, 3, 3)
qs = ssstrat(10)
qd = quaddata(t, 𝒴, 𝒳, τs, σs, qs)
qr = quadrule(t, 𝒴, 𝒳, 1, τs[1], 1, σs[1], qd, qs)
BEAST.momintegrals!(t, 𝒴, 𝒳, τs[1], σs[1], out1_10, qr)
out1_20 = zeros(ComplexF64, 3, 3)
qs = ssstrat(20)
qd = quaddata(t, 𝒴, 𝒳, τs, σs, qs)
qr = quadrule(t, 𝒴, 𝒳, 1, τs[1], 1, σs[1], qd, qs)
BEAST.momintegrals!(t, 𝒴, 𝒳, τs[1], σs[1], out1_20, qr)
@show out1_10[1,1] out1_20[1,1]
out2_10 = zeros(ComplexF64, 3, 3)
qs = ssstrat(10)
qd = quaddata(t, 𝒴, 𝒳, τs, σs, qs)
qr = quadrule(t, 𝒴, 𝒳, 1, τs[1], 1, σs[2], qd, qs)
BEAST.momintegrals!(t, 𝒴, 𝒳, τs[1], σs[2], out2_10, qr)
out2_20 = zeros(ComplexF64, 3, 3)
qs = ssstrat(20)
qd = quaddata(t, 𝒴, 𝒳, τs, σs, qs)
qr = quadrule(t, 𝒴, 𝒳, 1, τs[1], 2, σs[2], qd, qs)
BEAST.momintegrals!(t, 𝒴, 𝒳, τs[1], σs[2], out2_20, qr)
@show out2_10[1,1] out2_20[1,1]
out_ref = zeros(ComplexF64, 3, 3)
qrss = BEAST.SauterSchwabQuadrature.CommonVertex(g)
BEAST.momintegrals_test_refines_trial!(out_ref, t,
Y, rowidx, p,
X, colidx, q,
qrss, qs1)
@show out_ref | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 7207 | using CompScienceMeshes
using BEAST
# Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
# Γref = CompScienceMeshes.barycentric_refinement(Γ)
# h = 0.2*0.7
# M1 = meshcuboid(0.5, 1.0, 1.0, h)
# M2 = meshcuboid(0.5, 1.0, 1.0, 1.2*h)
# M2 = CompScienceMeshes.translate(M2, point(-0.5, 0, 0))
M1 = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/assets/M1.in"))
M2 = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/assets/M2.in"))
import Plotly
Plotly.plot([
patch(M1,color="red", opacity=0.5), patch(M2,color="blue", opacity=0.5),
wireframe(M1), wireframe(M2)])
X = raviartthomas(M1, BEAST.Continuity{:none})
Y = raviartthomas(M2, BEAST.Continuity{:none})
# X = subset(X,1690:1692)
# Y = subset(Y,10141:10143)
# X = subset(X,[1692])
# Y = subset(Y,[10147])
# Y = buffachristiansen(Γ)
κ, η = 1.0, 1.0
t = Maxwell3D.singlelayer(wavenumber=κ)
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n
g = 6
# ssstrat(g) = BEAST.DoubleNumSauterQstrat(7, 6, g, g, g, g)
ssstrat(g) = BEAST.DoubleNumWiltonSauterQStrat(
7, 6, 10, 8, g, g, g+3, g)
qs1 = BEAST.DoubleNumWiltonSauterQStrat(
2, 3, 6, 7, 5, 5, 4, 3)
qs2 = BEAST.NonConformingIntegralOpQStrat(qs1)
# A1 = assemble(t,Y,X, quadstrat=qs1, threading=BEAST.Threading{:single})
A2 = assemble(t,Y,X, quadstrat=qs2, threading=BEAST.Threading{:single})
A3 = assemble(t,X,Y, quadstrat=qs2, threading=BEAST.Threading{:single})
error()
# @enter assemble(t,Y,X, quadstrat=qs2, threading=BEAST.Threading{:single})
import Plots
Plots.plotly()
step = 1
rowidx = 10894
Plots.plot(imag.(A1[rowidx,1:step:end]))
Plots.scatter!(imag.(A2[rowidx,1:step:end]))
val, pos = findmax(abs.(A1-A2))
rowidx = Y.fns[pos[1]][1].cellid
colidx = X.fns[pos[2]][1].cellid
τ = chart(Γref, rowidx)
σ = chart(Γ, colidx)
# τ = [
# [0.18517788982868066, 0.05998671122432393, 0.9735312677690339],
# [0.1647116144395066, 0.0050896055947335095, 0.9807011064756881],
# [0.245326672427806, -0.06121735585211891, 0.9675056894602609]]
# σ = [
# [0.1133762981558132, -0.1176791567283826, 0.9865583769286949],
# [0.1647116144395066, 0.0050896055947335025, 0.9807011064756881],
# [0.08409655645120719, 0.07139656704158594, 0.9938965234911153]]
# eτ = simplex(
# point(0.1647116144395066, 0.0050896055947335095, 0.9807011064756881),
# point(0.245326672427806, -0.06121735585211891, 0.9675056894602609))
# eσ = simplex(
# point(0.1647116144395066, 0.0050896055947335025, 0.9807011064756881),
# point(0.08409655645120719, 0.07139656704158594, 0.9938965234911153))
# CompScienceMeshes.overlap(eτ, eσ)
# τ = τ.vertices
# σ = σ.vertices
import Plotly
function Plotly.mesh3d(a::Vector{<:CompScienceMeshes.Simplex}; opacity=0.5, kwargs...)
T = coordtype(a[1])
n = length(a)
X = Vector{T}(undef, 3*n)
Y = Vector{T}(undef, 3*n)
Z = Vector{T}(undef, 3*n)
for i in 1:n
X[3*(i-1)+1:3*i] = getindex.(a[i].vertices, 1)
Y[3*(i-1)+1:3*i] = getindex.(a[i].vertices, 2)
Z[3*(i-1)+1:3*i] = getindex.(a[i].vertices, 3)
end
I = collect(0:3:3*(n-1))
J = I .+ 1
K = I .+ 2
return Plotly.mesh3d(x=X,y=Y,z=Z,i=I,j=J,k=K; opacity, kwargs...)
end
m1 = Plotly.mesh3d([τ], opacity=0.5)
m2 = Plotly.mesh3d([σ], opacity=0.5)
# m1 = Plotly.mesh3d(
# x=getindex.(τ,1),
# y=getindex.(τ,2),
# z=getindex.(τ,3),
# i=[0], j=[1], k=[2])
# m2 = Plotly.mesh3d(
# x=getindex.(σ,1),
# y=getindex.(σ,2),
# z=getindex.(σ,3),
# i=[0], j=[1], k=[2])
Plotly.plot([m1,m2])
isct1, clps1 = CompScienceMeshes.intersection_keep_clippings(τ,σ)
isct2, clps2 = CompScienceMeshes.intersection_keep_clippings(σ,τ)
m3 = Plotly.mesh3d(isct1, opacity=0.5, color="blue")
m4 = Plotly.mesh3d(isct2, opacity=0.5, color="red")
Plotly.plot([m3,m4])
m5 = Plotly.mesh3d(clps2[1], opacity=0.5, color="green")
m6 = Plotly.mesh3d(clps2[1][[1]], opacity=0.5, color="yellow")
Plotly.plot([m3,m6])
p = isct1[1]
q = clps2[1][1]
for (i,λ) in pairs(faces(p))
for (j,μ) in pairs(faces(q))
if CompScienceMeshes.overlap(λ, μ)
global gi = i
global gj = j
global qr = BEAST.NonConformingTouchQRule(qs1, i, j)
end end end
𝒳 = refspace(X)
𝒴 = refspace(Y)
out10 = zeros(ComplexF64, 3, 3)
BEAST.momintegrals!(t, 𝒴, 𝒳, p, q, out10, BEAST.NonConformingTouchQRule(ssstrat(10), gi, gj))
out20 = zeros(ComplexF64, 3, 3)
BEAST.momintegrals!(t, 𝒴, 𝒳, p, q, out20, BEAST.NonConformingTouchQRule(ssstrat(20), gi, gj))
@show out10[1,1] out20[1,1]
τs, σs = BEAST._conforming_refinement_touching_triangles(p,q,2,3)
@assert length(τs) == 1
@assert length(σs) == 2
@assert volume(p) ≈ sum(volume.(τs))
@assert volume(q) ≈ sum(volume.(σs))
@assert all(volume.(τs) .> eps(Float64)*1e3)
@assert all(volume.(σs) .> eps(Float64)*1e3)
m7 = Plotly.mesh3d(τs[[1]], color="blue", opacity=0.5)
m8 = Plotly.mesh3d(σs[[1]], color="red", opacity=0.5)
Plotly.plot([m7,m8])
out1_10 = zeros(ComplexF64, 3, 3)
qs = ssstrat(10)
qd = quaddata(t, 𝒴, 𝒳, τs, σs, qs)
qr = quadrule(t, 𝒴, 𝒳, 1, τs[1], 1, σs[1], qd, qs)
BEAST.momintegrals!(t, 𝒴, 𝒳, τs[1], σs[1], out1_10, qr)
out1_20 = zeros(ComplexF64, 3, 3)
qs = ssstrat(20)
qd = quaddata(t, 𝒴, 𝒳, τs, σs, qs)
qr = quadrule(t, 𝒴, 𝒳, 1, τs[1], 1, σs[1], qd, qs)
BEAST.momintegrals!(t, 𝒴, 𝒳, τs[1], σs[1], out1_20, qr)
@show out1_10[1,1] out1_20[1,1]
out2_10 = zeros(ComplexF64, 3, 3)
qs = ssstrat(10)
qd = quaddata(t, 𝒴, 𝒳, τs, σs, qs)
qr = quadrule(t, 𝒴, 𝒳, 1, τs[1], 1, σs[2], qd, qs)
BEAST.momintegrals!(t, 𝒴, 𝒳, τs[1], σs[2], out2_10, qr)
out2_20 = zeros(ComplexF64, 3, 3)
qs = ssstrat(20)
qd = quaddata(t, 𝒴, 𝒳, τs, σs, qs)
qr = quadrule(t, 𝒴, 𝒳, 1, τs[1], 2, σs[2], qd, qs)
BEAST.momintegrals!(t, 𝒴, 𝒳, τs[1], σs[2], out2_20, qr)
@show out2_10[1,1] out2_20[1,1]
out_ref = zeros(ComplexF64, 3, 3)
qrss = BEAST.SauterSchwabQuadrature.CommonVertex(g)
BEAST.momintegrals_test_refines_trial!(out_ref, t,
Y, rowidx, p,
X, colidx, q,
qrss, qs1)
@show out_ref
τ = simplex(
point(0.0, 0.0, 0.1666666666673599),
point(-0.12200846792768633, 0.0, 0.1220084679279961),
point(0.0, 0.0, 0.0))
σ = simplex(
point(0.0, 0.0, 0.1249999999997732),
point(0.0, 0.0, 0.2499999999994112),
point(0.0, 0.1038676364273151, 0.1864502994601513))
for (i,λ) in pairs(faces(τ))
for (j,μ) in pairs(faces(σ))
if CompScienceMeshes.overlap(λ, μ)
global gi = i
global gj = j
# global qr = BEAST.NonConformingTouchQRule(qs1, i, j)
end end end
τs, σs = BEAST._conforming_refinement_touching_triangles(τ,σ,gi,gj);
@assert volume(τ) ≈ sum(volume.(τs))
@assert volume(σ) ≈ sum(volume.(σs))
Plotly.plot([Plotly.mesh3d(τs, color="red"), Plotly.mesh3d(σs, color="blue")])
Plotly.plot([Plotly.mesh3d([τ], color="red"), Plotly.mesh3d([σ], color="blue")])
τ = simplex(
point(0.0, 0.893151804804907, 0.4384102834058539),
point(0.0, 0.8931541172685571, 0.4383125008447698),
point(0.0, 0.8932364620235818, 0.43836004261125),)
σ = simplex(
point(0.0, 0.893151804804907, 0.4384102834058539),
point(0.0, 0.8931541172685571, 0.4383125008447698),
point(0.0, 0.8932364620235818, 0.43836004261125),)
CompScienceMeshes.overlap(τ, σ) | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 985 | using CompScienceMeshes, BEAST
# Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
Γ = meshsphere(radius=1.0, h=0.15)
X, Y = raviartthomas(Γ), buffachristiansen(Γ)
ϵ, μ, ω = 1.0, 1.0, 1.0; κ, η = ω * √(ϵ*μ), √(μ/ϵ)
# K, N = Maxwell3D.doublelayer(wavenumber=κ), NCross()
nxK = BEAST.DoubleLayerRotatedMW3D(1.0, κ*im)
Id = BEAST.Identity()
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
# E = -η/(im*κ)*BEAST.CurlCurlGreen(κ, ẑ, point(2,0,0))
H = -1/(im*μ*ω)*curl(E)
h = (n × H) × n
nxh = n × H
h = nxh × n
@hilbertspace j
@hilbertspace m
mfie = @discretise (nxK-0.5Id)[m,j] == nxh[m] j∈X m∈X
u = solve(mfie)
include("utils/postproc.jl")
include("utils/plotresults.jl")
# freeze, store = BEAST.allocatestorage(nxK, X, X, Val{:bandedstorage}, BEAST.LongDelays{:compress})
# @enter BEAST.assemble!(nxK, X, X, store, BEAST.Threading{:single})
# Z1 = freeze()
# Z2 = assemble(Id, X, X)
# Z = Z1 - 0.5*Z2
# b = assemble(nxh, X)
# u = Z \ b
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 460 | using CompScienceMeshes
using BEAST
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
X = raviartthomas(Γ)
Y = buffachristiansen(Γ, ibscaled=true)
N = BEAST.NCross()
κ = 1.0
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n
b = assemble(e, X)
G = assemble(N, X, Y)
x = G \ b
fcr, geo = facecurrents(x, Y)
using Plotly
using LinearAlgebra
Plotly.plot(patch(geo.mesh, norm.(fcr); caxis=(0.0, 1.0)))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 3267 | using CompScienceMeshes, BEAST
using LinearAlgebra
function nearfield(um,uj,Xm,Xj,κ,η,points,
Einc=(x->point(0,0,0)),
Hinc=(x->point(0,0,0)))
K = BEAST.MWDoubleLayerField3D(wavenumber=κ)
T = BEAST.MWSingleLayerField3D(wavenumber=κ)
Em = potential(K, points, um, Xm)
Ej = potential(T, points, uj, Xj)
E = -Em + η * Ej + Einc.(points)
Hm = potential(T, points, um, Xm)
Hj = potential(K, points, uj, Xj)
H = 1/η*Hm + Hj + Hinc.(points)
return E, H
end
ϵ0 = 8.854e-12
μ0 = 4π*1e-7
c = 1/√(ϵ0*μ0)
λ = 2.9979563769321627
ω = 2π*c/λ
Ω = CompScienceMeshes.tetmeshsphere(λ,0.1*λ)
Γ = boundary(Ω)
X = raviartthomas(Γ)
@show numfunctions(X)
ϵr = 2.0
μr = 1.0
κ, η = ω/c, √(μ0/ϵ0)
κ′, η′ = κ*√(ϵr*μr), η*√(μr/ϵr)
# κ, η = π, 1.0
# κ′, η′ = 2.0κ, η/2.0
T = Maxwell3D.singlelayer(wavenumber=κ)
T′ = Maxwell3D.singlelayer(wavenumber=κ′)
K = Maxwell3D.doublelayer(wavenumber=κ)
K′ = Maxwell3D.doublelayer(wavenumber=κ′)
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
H = -1/(im*κ*η)*curl(E)
e = (n × E) × n
h = (n × H) × n
@hilbertspace j m
@hilbertspace k l
α, α′ = 1/η, 1/η′
pmchwt = @discretise(
(η*T+η′*T′)[k,j] - (K+K′)[k,m] +
(K+K′)[l,j] + (α*T+α′*T′)[l,m] == -e[k] - h[l],
j∈X, m∈X, k∈X, l∈X)
u = solve(pmchwt)
Θ, Φ = range(0.0,stop=2π,length=100), 0.0
ffpoints = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for θ in Θ for ϕ in Φ]
# Don't forget the far field comprises two contributions
ffm = potential(MWFarField3D(κ*im, η), ffpoints, u[m], X)
ffj = potential(MWFarField3D(κ*im, η), ffpoints, u[j], X)
ff = -η*im*κ*ffj + im*κ*cross.(ffpoints, ffm)
# Compare the far field and the field far
using Plots
ffradius = 100.0
E_far, H_far = nearfield(u[m],u[j],X,X,κ,η, ffradius .* ffpoints)
nxE_far = cross.(ffpoints, E_far) * (4π*ffradius) / exp(-im*κ*ffradius)
Et_far = -cross.(ffpoints, nxE_far)
Plots.plot()
Plots.plot!(Θ, norm.(ff)/η ,label="far field")
Plots.scatter!(Θ, norm.(Et_far), label="field far")
using Plots
Plots.plot(xlabel="theta")
Plots.plot!(Θ,norm.(ff),label="far field",title="PMCHWT")
import Plotly
using LinearAlgebra
fcrj, _ = facecurrents(u[j],X)
fcrm, _ = facecurrents(u[m],X)
Plotly.plot(patch(Γ, norm.(fcrj)))
Plotly.plot(patch(Γ, norm.(fcrm)))
Z = range(-6,6,length=200)
Y = range(-4,4,length=200)
nfpoints = [point(0,y,z) for z in Z, y in Y]
import Base.Threads: @spawn
task1 = @spawn nearfield(u[m],u[j],X,X,κ,η,nfpoints,E,H)
task2 = @spawn nearfield(-u[m],-u[j],X,X,κ′,η′,nfpoints)
E_ex, H_ex = fetch(task1)
E_in, H_in = fetch(task2)
E_tot = E_in + E_ex
H_tot = H_in + H_ex
Plots.contour(real.(getindex.(E_tot,1)))
Plots.contour(real.(getindex.(H_tot,2)))
Plots.heatmap(Z, Y, clamp.(real.(getindex.(E_tot,1)),-1.5,1.5))
Plots.heatmap(Z, Y, clamp.(imag.(getindex.(E_tot,1)),-1.5,1.5))
Plots.heatmap(Z, Y, real.(getindex.(H_tot,2)))
Plots.heatmap(Z, Y, imag.(getindex.(H_tot,2)))
Plots.plot(real.(getindex.(E_tot[:,51],1)))
Plots.plot(real.(getindex.(H_tot[:,51],2)))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1395 | using CompScienceMeshes
using LinearAlgebra
# function cone(p,q; sizemode="absolute", sizeref=2, kwargs...)
# x = getindex.(p,1)
# y = getindex.(p,2)
# z = getindex.(p,3)
# u = getindex.(q,1)
# v = getindex.(q,2)
# w = getindex.(q,3)
# Plotly.cone(;x,y,z,u,v,w, sizemode, sizeref, kwargs...)
# end
fn = joinpath(dirname(pathof(CompScienceMeshes)),"geos/torus.geo")
fn = joinpath(@__DIR__, "assets/rectangular_torus.geo")
h = 0.08
Γ = CompScienceMeshes.meshgeo(fn; dim=2, h)
Γ0 = skeleton(Γ,0)
Γ1 = skeleton(Γ,1)
Σ = connectivity(Γ, Γ1, sign)
Λ = connectivity(Γ0, Γ1, sign)
# using Plotly
# Plotly.plot([patch(Γ, opacity=0.5), wireframe(Γ)])
using BEAST
X = raviartthomas(Γ)
Y = buffachristiansen(Γ)
K = Maxwell3D.doublelayer(gamma=0.0)
Id = BEAST.Identity()
Nx = BEAST.NCross()
M = K + 0.5Nx
qs = BEAST.defaultquadstrat(M,Y,X)
qs[2] = BEAST.DoubleNumWiltonSauterQStrat(6, 7, 6, 7, 9, 9, 9, 9)
Myx = assemble(M, Y, X, quadstrat=qs)
using LinearAlgebra
(;U,S,V) = svd(Myx)
v0 = V[:,end]
fcr, geo = facecurrents(v0, X)
# pts = [cartesian(center(chart(Γ,p))) for p in Γ]
import Plotly
pt1 = patch(Γ,norm.(fcr), opacity=0.5)
pt2 = CompScienceMeshes.cones(Γ, fcr, sizeref=0.4)
Plotly.plot([pt1, pt2])
G = assemble(Id,X,X)
norm(v0)
norm(Σ'*v0)
norm(Λ'*G*v0)
# Dict{Any, Any} with 3 entries:
# 0.5 => 0.370836
# 0.25 => 0.315732
# 0.125 => 0.265276 | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 3888 | using BEAST, CompScienceMeshes, LinearAlgebra
using Plots
# using JLD2
setminus(A,B) = submesh(!in(B), A)
radius = 1.0
nearstrat = BEAST.DoubleNumWiltonSauterQStrat(6, 7, 6, 7, 7, 7, 7, 7)
farstrat = BEAST.DoubleNumQStrat(1,2)
dmat(op,tfs,bfs) = BEAST.assemble(op,tfs,bfs; quadstrat=nearstrat)
# hmat(op,tfs,bfs) = AdaptiveCrossApproximation.h1compress(op,tfs,bfs; nearstrat=nearstrat,farstrat=farstrat)
mat = dmat
h = [0.1, 0.05, 0.025, 0.0125]
κ = [1.0, 10.0]
h = 0.3
κ = 0.000001
γ = im*κ
# function runsim(;h, κ)
SL = Maxwell3D.singlelayer(wavenumber=κ)
WS = Maxwell3D.weaklysingular(wavenumber=κ)
HS = Maxwell3D.hypersingular(wavenumber=κ)
N = NCross()
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n;
Γ = meshsphere(;radius, h)
∂Γ = boundary(Γ)
edges = setminus(skeleton(Γ,1), ∂Γ)
verts = setminus(skeleton(Γ,0), skeleton(∂Γ,0))
Σ = Matrix(connectivity(Γ, edges, sign))
Λ = Matrix(connectivity(verts, edges, sign))
I = LinearAlgebra.I
PΣ = Σ * pinv(Σ'*Σ) * Σ'
PΛH = I - PΣ
ℙΛ = Λ * pinv(Λ'*Λ) * Λ'
ℙHΣ = I - ℙΛ
MR = γ * PΣ + PΛH
ML = PΣ + 1/γ * PΛH
MRΣ = γ * PΣ
MRΛH = PΛH
MLΣ = PΣ
MLΛH = 1/γ * PΛH
𝕄R = γ * ℙΛ + ℙHΣ
𝕄L = ℙΛ + 1/γ * ℙHΣ
X = raviartthomas(Γ)
Y = buffachristiansen(Γ)
@hilbertspace p
@hilbertspace q
SLxx = assemble(@discretise(SL[p,q], p∈X, q∈X), materialize=mat)
WSxx = assemble(@discretise(WS[p,q], p∈X, q∈X), materialize=mat)
ex = BEAST.assemble(@discretise e[p] p∈X)
sys0 = SLxx
sys1 = MLΣ * SLxx * MRΣ + MLΛH * WSxx * MRΣ + MLΣ * WSxx * MRΛH + MLΛH * WSxx * MRΛH
rhs0 = ex
rhs1 = ML * ex
u0, ch0 = solve(BEAST.GMRESSolver(sys0, tol=2e-5, restart=250), rhs0)
v1, ch1 = solve(BEAST.GMRESSolver(sys1, tol=2e-5, restart=250), rhs1)
u1 = MR * v1
# u2 = MR * v2
# error()
# @show ch1.iters
# @show ch2.iters
Φ, Θ = [0.0], range(0,stop=π,length=40)
pts = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for ϕ in Φ for θ in Θ]
near0 = potential(MWFarField3D(wavenumber=κ), pts, u0, X)
near1 = potential(MWFarField3D(wavenumber=κ), pts, u1, X)
# near2 = potential(MWFarField3D(wavenumber=κ), pts, u2, X)
# u1, ch1.iters, u2, ch2.iters, near1, near2, X
# end
plot();
plot!(Θ, norm.(near0));
scatter!(Θ, norm.(near1))
# scatter!(Θ, norm.(near2))
# error()
# using LinearAlgebra
# using Plots
# plotly()
# w0 = eigvals(Matrix(SLxx))
# w1 = eigvals(Matrix(sys))
# w2 = eigvals(Matrix(P * sys))
# plot(exp.(2pi*im*range(0,1,length=200)))
# scatter!(w0)
# scatter!(w1)
# scatter!(w2)
# function makesim(d::Dict)
# @unpack h, κ = d
# u1, ch1, u2, ch2, near1, near2, X = runsim(;h, κ)
# fulld = merge(d, Dict(
# "u1" => u1,
# "u2" => u2,
# "ch1" => ch1,
# "ch2" => ch2,
# "near1" => near1,
# "near2" => near2
# ))
# end
# method = splitext(basename(@__FILE__))[1]
# params = @strdict h κ
# dicts = dict_list(params)
# for (i,d) in enumerate(dicts)
# @show d
# f = makesim(d)
# @tagsave(datadir("simulations", method, savename(d,"jld2")), f)
# end
#' Visualise the spectrum
# mSxx = BEAST.convert_to_dense(Sxx)
# mSyy = BEAST.convert_to_dense(Syy)
# Z = mSxx
# W = iN' * mSyy * iN * mSxx;
# wZ = eigvals(Matrix(Z))
# wW = eigvals(Matrix(W))
# plot(exp.(im*range(0,2pi,length=200)))
# scatter!(wZ)
# scatter!(wW)
# Study the various kernels
# HS = Maxwell3D.singlelayer(gamma=0.0, alpha=0.0, beta=1.0)
# Id = BEAST.Identity()
# Z12 = BEAST.lagrangecxd0(G12)
# Z23 = BEAST.lagrangecxd0(Ĝ23)
# Z = Z12 × Z23
# W12 = BEAST.duallagrangecxd0(G12)
# W23 = BEAST.duallagrangecxd0(Ĝ23)
# W = W12 × W23
# DX = assemble(Id, Z, divergence(X))
# HX = assemble(HS, X, X)
# DY = assemble(Id, W, divergence(Y))
# HY = assemble(HS, Y, Y)
# Nx = BEAST.NCross()
# NYX = assemble(Nx, Y, X)
# Q = HY * iN * HX
# using AlgebraicMultigrid
# A = poisson(100)
# b = rand(100);
# solve(A, b, RugeStubenAMG(), maxiter=1, abstol=1e-6)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1302 | using CompScienceMeshes
using BEAST
Γ1 = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
Γ2 = CompScienceMeshes.translate(Γ1, [10,0,0])
SL = Maxwell3D.singlelayer(wavenumber=1.0)
X1 = raviartthomas(Γ1)
X2 = raviartthomas(Γ2)
x1 = refspace(X1)
x2 = refspace(X2)
function BEAST.quaddata(op::typeof(SL), tref::typeof(x1), bref::typeof(x2),
tels, bels, qs::BEAST.DoubleNumQStrat)
qs = BEAST.DoubleNumWiltonSauterQStrat(qs.outer_rule, qs.inner_rule, 1, 1, 1, 1, 1, 1)
BEAST.quaddata(op, tref, bref, tels, bels, qs)
end
function BEAST.quadrule(op::typeof(SL), tref::typeof(x1), bref::typeof(x2),
i ,τ, j, σ, qd, qs::BEAST.DoubleNumQStrat)
return BEAST.DoubleQuadRule(
qd.tpoints[1,i],
qd.bpoints[1,j])
end
BEAST.quadinfo(SL,X1,X2)
BEAST.quadinfo(SL,X1,X2, quadstrat=BEAST.DoubleNumQStrat(2,3))
@time Z1 = assemble(SL,X1,X2);
@time Z2 = assemble(SL,X1,X2,quadstrat=BEAST.DoubleNumQStrat(2,3));
ba1 = blockassembler(SL,X1,X2)
ba2 = blockassembler(SL,X1,X2,quadstrat=BEAST.DoubleNumQStrat(2,3))
T = scalartype(SL,X1,X2)
n1 = numfunctions(X1)
n2 = numfunctions(X2)
W1 = zeros(T,n1,n2);
W2 = zeros(T,n1,n2);
idcs1 = collect(1:n1)
idcs2 = collect(1:n2)
@time ba1(idcs1,idcs2, (v,m,n)->(W1[m,n]+=v))
@time ba2(idcs1,idcs2, (v,m,n)->(W2[m,n]+=v)); | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 517 | using CompScienceMeshes
using BEAST
fn = joinpath(dirname(@__FILE__),"assets","torus.msh")
m = CompScienceMeshes.read_gmsh_mesh(fn)
X = raviartthomas(m)
Y = buffachristiansen(m)
N = BEAST.NCross()
K = Maxwell3D.doublelayer(gamma=0.0)
verts = skeleton(m,0)
edges = skeleton(m,1)
faces = skeleton(m,2)
Λ = connectivity(verts, edges)
Σ = connectivity(faces, edges)
M = assemble(K+0.5N,Y,X)
using LinearAlgebra
s = svdvals(M)
using Plots
plot(log10.(s))
x = nullspace(M, 1.1*s[end])
norm(x)
norm(M*x)
norm(Σ'*Λ)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 928 | using CompScienceMeshes, BEAST
o, x, y, z = euclidianbasis(3)
# D, Δx = 1.0, 0.35
# Γ = meshsphere(D, Δx)
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
Γ = meshsphere(1.0, 0.45)
X = raviartthomas(Γ)
#Δt, Nt = 0.08, 400
Δt, Nt = 0.6, 200
T = timebasisc0d1(Δt, Nt)
U = timebasiscxd0(Δt, Nt)
# T = timebasisshiftedlagrange(Δt, Nt, 2)
# U = timebasisdelta(Δt, Nt)
V = X ⊗ T
W = X ⊗ U
width, delay, scaling = 8.0, 12.0, 1.0
gaussian = creategaussian(width, delay, scaling)
direction, polarisation = ẑ, x̂
E = BEAST.planewave(polarisation, direction, derive(gaussian), 1.0)
@hilbertspace j; @hilbertspace j′
T = MWSingleLayerTDIO(1.0,-1.0,-1.0,2,0)
tdefie = @discretise T[j′,j] == -1E[j′] j∈V j′∈W
xefie = solve(tdefie)
Xefie, Δω, ω0 = fouriertransform(xefie, Δt, 0.0, 2)
ω = collect(ω0 .+ (0:Nt-1)*Δω)
_, i1 = findmin(abs.(ω.-1.0))
ω1 = ω[i1]
ue = Xefie[:,i1]/ fouriertransform(gaussian)(ω1)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 980 | using CompScienceMeshes, BEAST
o, x, y, z = euclidianbasis(3)
# D, Δx = 1.0, 0.35
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
X, Y = raviartthomas(Γ), buffachristiansen(Γ)
# Δt, Nt = 0.11, 200
Δt, Nt = 0.6, 200
δ = timebasisdelta(Δt, Nt)
h = timebasisc0d1(Δt, Nt)
p = timebasiscxd0(Δt, Nt)
V = X ⊗ p
W = Y ⊗ p
width, delay, scaling = 8.0, 12.0, 1.0
gaussian = creategaussian(width, delay, scaling)
direction, polarisation = ẑ, x̂
E = BEAST.planewave(polarisation, direction, gaussian, 1.0)
# E = BEAST.planewave(polarisation, direction, derive(gaussian), 1.0)
H = direction × E
@hilbertspace j; @hilbertspace m′
K, I, N = MWDoubleLayerTDIO(1.0, 1.0, 0), Identity(), NCross()
tdmfie = @discretise (0.5*(N⊗I) + 1.0*K)[m′,j] == -1H[m′] j∈V m′∈W
xmfie = solve(tdmfie)
Xmfie, Δω, ω0 = fouriertransform(xmfie, Δt, 0.0, 2)
ω = collect(ω0 .+ (0:Nt-1)*Δω)
_, i1 = findmin(abs.(ω .- 1.0))
ω1 = ω[i1]
um = Xmfie[:,i1] / fouriertransform(gaussian)(ω1)
| BEAST | https://github.com/krcools/BEAST.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.