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" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1100
using CompScienceMeshes, BEAST, LinearAlgebra Γ = readmesh(joinpath(@__DIR__,"sphere2.in")) Γ = meshsphere(radius=1.0, h=0.25) X = raviartthomas(Γ) Δt = 0.1 Nt = 200 T = timebasisshiftedlagrange(Δt, Nt, 3) U = timebasisdelta(Δt, Nt) V = X ⊗ T W = X ⊗ U duration = 2 * 20 * Δt delay = 1.5 * duration amplitude = 1.0 gaussian = creategaussian(duration, delay, amplitude) direction, polarisation = ẑ, x̂ E = planewave(polarisation, direction, derive(gaussian), 1.0) @hilbertspace j @hilbertspace j′ SL = TDMaxwell3D.singlelayer(speedoflight=1.0, numdiffs=1) # BEAST.@defaultquadstrat (SL, W, V) BEAST.OuterNumInnerAnalyticQStrat(7) tdefie = @discretise SL[j′,j] == -1.0E[j′] j∈V j′∈W xefie = BEAST.motsolve(tdefie) import Plots Plots.plot(xefie[1,:]) import Plotly fcr, geo = facecurrents(xefie[:,125], X) Plotly.plot(patch(geo, norm.(fcr))) 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) fcr, geo = facecurrents(ue, X) Plotly.plot(patch(geo, norm.(fcr)))
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
693
using CompScienceMeshes, BEAST, StaticArrays, LinearAlgebra, Plots Γ = meshsphere(radius=1.0, h=0.45) X = raviartthomas(Γ) sol = 1.0 Δt, Nt = 10.0, 200 (A, b, c) = butcher_tableau_radau_3stages() T = StagedTimeStep(Δt, Nt, c, A, b, 10, 1.0001) V = X ⊗ T duration = 2 * 20 * Δt delay = 1.5 * duration amplitude = 1.0 gaussian = creategaussian(duration, delay, amplitude) direction, polarisation = ẑ , x̂ E = planewave(polarisation, direction, derive(gaussian), sol) T = TDMaxwell3D.singlelayer(speedoflight=1.0, numdiffs=1) @hilbertspace j @hilbertspace j′ tdefie_irk = @discretise T[j′,j] == -1E[j′] j∈V j′∈V xefie_irk = solve(tdefie_irk) import Plots Plots.plot(xefie_irk[1,:])
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1415
using CompScienceMeshes, BEAST o, x, y, z = euclidianbasis(3) sol = 5.0 #Δt, Nt = 0.08/sol,400 Δt, Nt = 0.120000123/sol,400 #D, Δx = 1.0, 0.25 D, Δx = 1.0, 0.1 #Γ = meshsphere(D, Δx) Γ = meshrectangle(D,D,Δx,3) #γ = boundary(Γ) γ1 = meshsegment(D,D,3) γ2 = CompScienceMeshes.translate(γ1, point(0,D,0)) #X = raviartthomas(Γ,weld(γ1,γ2)) X = rt_ports(Γ,(γ1,γ2)) X.fns = X.fns[1:281] numfunctions(X) T = timebasisshiftedlagrange(Δt, Nt, 3) U = timebasisdelta(Δt, Nt) V = X ⊗ T W = X ⊗ U duration, delay, amplitude = 8.0/sol, 12.0/sol, 1.0 gaussian = creategaussian(duration, delay, duration) direction, polarisation = z, x E = planewave(polarisation, direction, derive(gaussian), sol) T = MWSingleLayerTDIO(sol,-1/sol,-sol,2,0) #Z = assemble(T,W,V); @hilbertspace j @hilbertspace j′ tdefie = @discretise T[j′,j] == -1E[j′] j∈V j′∈W xefie = solve(tdefie) using Plotly # include(Pkg.dir("CompScienceMeshes","examples","matlab_patches.jl")) Xefie, Δω, ω0 = fouriertransform(xefie, Δt, 0.0, 2) ω = collect(ω0 .+ (0:Nt-1)*Δω) _, i1 = findmin(abs.(ω.-sol)) ω1 = ω[i1] ue = Xefie[:,i1] / fouriertransform(gaussian)(ω1) using LinearAlgebra fcre, geo = facecurrents(ue, X) t2 = patch(geo, real.(norm.(fcre))) Plotly.plot(t2) fcr_td, geo = facecurrents(xefie[:,end], X) # fcr_ch, geo = facecurrents(xefie[:,end], divergence(X)) t3 = patch(Γ,real.(norm.(fcr_td))) Plotly.plot(t3) # jmatlab_quiver(Γ, fcr_td)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
882
using CompScienceMeshes, BEAST # Γ = readmesh(joinpath(@__DIR__,"sphere2.in")) Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in")) # Γ = meshsphere(radius=1.0, h=0.4) X = raviartthomas(Γ) Δt, Nt = 0.1, 200 T = timebasisshiftedlagrange(Δt, Nt, 1) U = timebasisdelta(Δt, Nt) V = X ⊗ T W = X ⊗ U duration = 20 * Δt delay = 1.5 * duration amplitude = 1.0 gaussian = creategaussian(duration, delay, amplitude) direction, polarisation = ẑ, x̂ E = BEAST.planewave(polarisation, direction, gaussian, 1.0) SL = TDMaxwell3D.singlelayer(speedoflight=1.0) @hilbertspace j @hilbertspace j′ efie_nodot = @discretise SL[j′,j] == E[j′] j∈V j′∈W # error() xefie_nodot = solve(efie_nodot) Xefie, Δω, ω0 = fouriertransform(xefie_nodot, Δ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
1063
# This script solved the TD-EFIE and TD-MFIE 'at the same time'. It verifies # the code dealing with systems of time domain equations in the special case # of a block diagonal system. using CompScienceMeshes, BEAST Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in")) X = raviartthomas(Γ) Y = buffachristiansen(Γ) Δt, Nt = 0.6, 200 δ = timebasisdelta(Δt, Nt) T0 = timebasiscxd0(Δt, Nt) T1 = timebasisshiftedlagrange(Δt,Nt,1) T2 = timebasisshiftedlagrange(Δt, Nt, 2) T3 = timebasisshiftedlagrange(Δt, Nt, 3) duration = 20 * Δt delay = 1.5 * duration amplitude = 1.0 gaussian = creategaussian(duration, delay, amplitude) direction, polarisation = ẑ, x̂ E = BEAST.planewave(polarisation, direction, gaussian, 1.0) H = direction × E SL = TDMaxwell3D.singlelayer(speedoflight=1.0, numdiffs=0) DL = TDMaxwell3D.doublelayer(speedoflight=1.0) I = Identity() N = NCross() @hilbertspace k l @hilbertspace j m emfie = @discretise( (0.5(N⊗I) + 1.0DL)[k,j] + SL[l,m] == -1.0H[k] - E[l], k∈Y⊗δ, l∈X⊗δ, j∈X⊗T1, m∈X⊗T1) xemfie = motsolve(emfie)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
989
using CompScienceMeshes, BEAST Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in")) Γ = meshsphere(radius=1.0, h=0.25) X = raviartthomas(Γ) Y = buffachristiansen(Γ) Δt, Nt = 0.1, 200 T = timebasisshiftedlagrange(Δt, Nt, 2) δ = timebasisdelta(Δt, Nt) V = X ⊗ T W = Y ⊗ δ duration = 2 * 20 * Δt delay = 1.5 * duration amplitude = 1.0 gaussian = creategaussian(duration, delay, amplitude) direction, polarisation = ẑ, x̂ E = BEAST.planewave(polarisation, direction, gaussian, 1.0) H = direction × E DL = TDMaxwell3D.doublelayer(speedoflight=1.0) I = Identity() N = NCross() @hilbertspace k @hilbertspace j mfie = @discretise ((0.5*N)⊗I)[k,j] + 1.0DL[k,j] == -1.0H[k] k∈W j∈V xmfie = BEAST.motsolve(mfie) 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) import Plotly fcr, geo = facecurrents(um, X) Plotly.plot(patch(geo, norm.(fcr)))
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1312
using CompScienceMeshes, BEAST # Γ = readmesh(joinpath(@__DIR__,"sphere2.in")) Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in")) # Γ = meshsphere(1.0, 0.4) @show length(Γ) X = raviartthomas(Γ) Y = buffachristiansen(Γ) Δt, Nt = 0.6, 200 T0 = timebasisshiftedlagrange(Δt, Nt, 0) T1 = timebasisshiftedlagrange(Δt, Nt, 1) iT0 = integrate(T0) iT1 = integrate(T1) δ = timebasisdelta(Δt, Nt) # V = X ⊗ T # iV = X ⊗ iT # W = Y ⊗ δ duration = 20 * Δt delay = 1.5 * duration amplitude = 1.0 gaussian = creategaussian(duration, delay, amplitude) int_gaussian = integrate(gaussian) direction, polarisation = ẑ, x̂ E = BEAST.planewave(polarisation, direction, gaussian, 1.0) iE = BEAST.planewave(polarisation, direction, int_gaussian, 1.0) H = direction × E iH = direction × iE DL = TDMaxwell3D.doublelayer(speedoflight=1.0) I = Identity() N = NCross() M = 0.5*N⊗I + 1.0*DL iM = integrate(M) NI = N ⊗ I iNI = integrate(NI) # error() @hilbertspace k @hilbertspace j # mfie = @discretise (0.5(N⊗I) + 1.0DL)[k,j] == -1.0H[k] k∈W j∈V mfie = @discretise iM[k,j] == -1.0iH[k] k∈(Y⊗δ) j∈(X⊗T0) xmfie_int = solve(mfie) Xmfie, Δω, ω0 = fouriertransform(xmfie_int, Δ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
972
using CompScienceMeshes, BEAST Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in")) # Γ = meshsphere(1.0, 0.4) X = raviartthomas(Γ) Y = BEAST.nedelec(Γ) Δt, Nt = 0.1, 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 = creategaussian(duration, delay, amplitude) direction, polarisation = ẑ, x̂ E = BEAST.planewave(polarisation, direction, gaussian, 1.0) H = direction × E DL = TDMaxwell3D.doublelayer(speedoflight=1.0) I = Identity() N = NCross() @hilbertspace k @hilbertspace j mfie = @discretise (0.5(N⊗I) + 1.0DL)[k,j] == -1.0H[k] k∈W j∈V # Kyx = assemble(DL, W, V) # Nyx = assemble(N⊗I, W, V) xmfie_sym = solve(mfie) # xmfie_sym = xmfie Xmfie_sym, Δω, ω0 = fouriertransform(xmfie_sym, Δt, 0.0, 2) ω = collect(ω0 .+ (0:Nt-1)*Δω) _, i1 = findmin(abs.(ω .- 1.0)) ω1 = ω[i1] um = Xmfie_sym[:,i1] / fouriertransform(gaussian)(ω1)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2945
# using Pkg # Pkg.activate(@__DIR__) # Pkg.instantiate() using CompScienceMeshes, BEAST using LinearAlgebra # Γ = meshcuboid(1.0, 1.0, 1.0, 0.25) # h = 0.3 # fn = joinpath(dirname(pathof(CompScienceMeshes)),"geos/torus.geo") # Γ = CompScienceMeshes.meshgeo(fn; dim=2, h=1.0) Γ = meshsphere(radius=1.0, h=0.25) X = raviartthomas(Γ) Y = buffachristiansen(Γ) sol = 1.0 T = TDMaxwell3D.singlelayer(speedoflight=sol, numdiffs=1) K = TDMaxwell3D.doublelayer(speedoflight=sol, numdiffs=1) Δt, Nt = 0.1, 300 δ = timebasisdelta(Δt, Nt) T0 = timebasiscxd0(Δt, Nt) T1 = timebasisshiftedlagrange(Δt,Nt,1) T2 = timebasisshiftedlagrange(Δt, Nt, 2) T3 = timebasisshiftedlagrange(Δt, Nt, 3) duration = 40 * Δt delay = 1.5 * duration amplitude = 1.0 gaussian = creategaussian(duration, delay, amplitude) direction, polarisation = ẑ, x̂ E = BEAST.planewave(polarisation, direction, derive(gaussian), 1.0) H = direction × E @hilbertspace j m @hilbertspace k l # pmchwt = @discretise( # 2.0T[k,j] + 2.0K[k,m] - # 2.0K[l,j] + 2.0T[l,m] == H[k] + E[l], # j∈X⊗T2, m∈Y⊗T2, k∈X⊗δ, l∈Y⊗δ) BEAST.@defaultquadstrat (T, X⊗δ, X⊗T2) BEAST.OuterNumInnerAnalyticQStrat(7) BEAST.@defaultquadstrat (K, X⊗δ, X⊗T2) BEAST.OuterNumInnerAnalyticQStrat(7) pmchwt = @discretise( 2.0T[k,j] + 2.0K[k,m] - 2.0K[l,j] + 2.0T[l,m] == H[k] + E[l], j∈X⊗T2, m∈X⊗T2, k∈X⊗δ, l∈X⊗δ) # Z = BEAST.td_assemble(pmchwt.equation.lhs, pmchwt.test_space_dict, pmchwt.trial_space_dict); # w = BEAST.ConvolutionOperators.polyvals(Z) # error() u = BEAST.motsolve(pmchwt) Z = BEAST.sysmatrix(pmchwt) using Plots scatter!(u[1,:]) nothing # nX = numfunctions(X) # uj = u[1:nX] # um = u[nX+1:end] # Θ, Φ = range(0.0,stop=2π,length=100), 0.0 # ffpoints = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for θ in Θ for ϕ in Φ] # # # Don't forgt the far field comprises two contributions # κ, η = 1.0, 1.0 # ffm = potential(MWFarField3D(κ*im), ffpoints, um, X) # ffj = potential(MWFarField3D(κ*im), ffpoints, uj, X) # ff = η*im*κ*ffj + im*κ*cross.(ffpoints, ffm) # # using Plots # plot(xlabel="theta") # plot!(Θ,norm.(ffm),label="far field") # # import PlotlyJS # using LinearAlgebra # fcrj, _ = facecurrents(uj,X) # PlotlyJS.plot(patch(Γ, norm.(fcrj))) # Study the pmchwt static nullspace # pmchwt = @discretise( # 2.0T[k,j] + 2.0K[k,m] - # 2.0K[l,j] + 2.0T[l,m] == H[k] + E[l], # j∈X⊗T2, m∈X⊗T2, k∈X⊗δ, l∈X⊗δ) # Z = BEAST.td_assemble(pmchwt.equation.lhs, pmchwt.test_space_dict, pmchwt.trial_space_dict) # function cast(Z) # # kmax = maximum(length.(Z)) # kmax = size(Z,3) # Q = zeros(eltype(eltype(Z)), size(Z)..., kmax) # for m in axes(Q,1) # for n in axes(Q,2) # for k in eachindex(Z[m,n]) # Q[m,n,k] = Z[m,n][k] # end # end # end # return Q # end # Q = cast(Z) # C = companion(Q) # w = eigvals(C) # using Plots # plotly() # plot(exp.(im*range(0,2pi,length=200))) # scatter!(w)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
3060
# using Pkg # Pkg.activate(@__DIR__) # Pkg.instantiate() using CompScienceMeshes, BEAST using LinearAlgebra # Γ = meshcuboid(1.0, 1.0, 1.0, 0.25) # h = 0.3 fn = joinpath(dirname(pathof(CompScienceMeshes)),"geos/torus.geo") Γ = CompScienceMeshes.meshgeo(fn; dim=2, h=1.0) Γ = meshsphere(radius=1.0, h=0.25) X = raviartthomas(Γ) Y = buffachristiansen(Γ, ibscaled=false) sol = 1.0 T = TDMaxwell3D.singlelayer(speedoflight=sol, numdiffs=0) K = TDMaxwell3D.doublelayer(speedoflight=sol, numdiffs=0) Δt, Nt = 0.1, 300 δ = timebasisdelta(Δt, Nt) T0 = timebasiscxd0(Δt, Nt) T1 = timebasisshiftedlagrange(Δt,Nt,1) T2 = timebasisshiftedlagrange(Δt, Nt, 2) T3 = timebasisshiftedlagrange(Δt, Nt, 3) duration = 40 * Δt delay = 1.5 * duration amplitude = 1.0 gaussian = creategaussian(duration, delay, amplitude) direction, polarisation = ẑ, x̂ E = BEAST.planewave(polarisation, direction, gaussian, 1.0) H = direction × E @hilbertspace j m @hilbertspace k l # pmchwt = @discretise( # 2.0T[k,j] + 2.0K[k,m] - # 2.0K[l,j] + 2.0T[l,m] == H[k] + E[l], # j∈X⊗T2, m∈Y⊗T2, k∈X⊗δ, l∈Y⊗δ) pmchwt = @discretise( 2.0T[k,j] + 2.0K[k,m] - 2.0K[l,j] + 2.0T[l,m] == H[k] + E[l], j∈X⊗T1, m∈X⊗T1, k∈X⊗δ, l∈X⊗δ) # Z = BEAST.td_assemble(pmchwt.equation.lhs, pmchwt.test_space_dict, pmchwt.trial_space_dict); # error() function cones(mesh, arrows; sizeref=2) centers = [cartesian(CompScienceMeshes.center(chart(mesh,cell))) for cell in mesh] x = getindex.(centers,1) y = getindex.(centers,2) z = getindex.(centers,3) u = getindex.(arrows,1) v = getindex.(arrows,2) w = getindex.(arrows,3) Plotly.cone(x=x,y=y,z=z,u=u,v=v,w=w,sizemode="absolute", sizeref=sizeref) end u = solve(pmchwt) error() # nX = numfunctions(X) # uj = u[1:nX] # um = u[nX+1:end] # Θ, Φ = range(0.0,stop=2π,length=100), 0.0 # ffpoints = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for θ in Θ for ϕ in Φ] # # # Don't forgt the far field comprises two contributions # κ, η = 1.0, 1.0 # ffm = potential(MWFarField3D(κ*im), ffpoints, um, X) # ffj = potential(MWFarField3D(κ*im), ffpoints, uj, X) # ff = η*im*κ*ffj + im*κ*cross.(ffpoints, ffm) # # using Plots # plot(xlabel="theta") # plot!(Θ,norm.(ffm),label="far field") # # import PlotlyJS # using LinearAlgebra # fcrj, _ = facecurrents(uj,X) # PlotlyJS.plot(patch(Γ, norm.(fcrj))) # Study the pmchwt static nullspace pmchwt = @discretise( 2.0T[k,j] + 2.0K[k,m] - 2.0K[l,j] + 2.0T[l,m] == H[k] + E[l], j∈X⊗T2, m∈X⊗T2, k∈X⊗δ, l∈X⊗δ) # Z = BEAST.td_assemble(pmchwt.equation.lhs, pmchwt.test_space_dict, pmchwt.trial_space_dict) # function cast(Z) # # kmax = maximum(length.(Z)) # kmax = size(Z,3) # Q = zeros(eltype(eltype(Z)), size(Z)..., kmax) # for m in axes(Q,1) # for n in axes(Q,2) # for k in eachindex(Z[m,n]) # Q[m,n,k] = Z[m,n][k] # end # end # end # return Q # end # Q = cast(Z) # C = companion(Q) # w = eigvals(C) # using Plots # plotly() # plot(exp.(im*range(0,2pi,length=200))) # scatter!(w)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
878
using BEAST, CompScienceMeshes, MieSeries Θ = range(0, stop=π, length=100) Φ = 0.0 P = [ [cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)] for θ in Θ for ϕ in Φ] ## Solve the scatering problem using BEM Γ = readmesh(joinpath(dirname(@__FILE__),"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 = gmres(efie) A = Maxwell3D.farfield(wavenumber=κ) farbem = 1/(4pi)* norm.(potential(A, P, u, X)) ## Solve the scattering problem by computing the Mie series radius = 1.0; ϵ = μ = 1.0 sphere = PECSphere(radius, ϵ, μ) exc = excite(sphere, ω, :x) farmie = [norm(collect(farfield(sphere, exc, p)[1:3])) for p in P] # Compare @show norm(farmie - farbem) / norm(farmie)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1135
using CompScienceMeshes using BEAST Γ1 = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in")) Γ2 = CompScienceMeshes.SComplex2D(Γ1) # Y = raviartthomas(Γ1) Nd1 = BEAST.nedelec(Γ1) Nd2 = BEAST.nedelec(Γ2) RT1 = n × Nd1 RT2 = n × Nd2 N1 = skeleton(Γ1,0) N2 = skeleton(Γ2,0) for (n1,n2) in zip(N1.faces, N2.nodes) @assert n1[1] == n2[1] end E1 = skeleton(Γ1,1) E2 = skeleton(Γ2,1) using LinearAlgebra for (e1,e2) in zip(E1.faces, E2.edges) q = getindex.(Ref(E2.nodes), e2) @assert q[1][1] == e1[1] @assert q[2][1] == e1[2] ctr1 = cartesian(CompScienceMeshes.center(chart(E1, e1))) ctr2 = cartesian(CompScienceMeshes.center(chart(E2, e2))) if norm(ctr1-ctr2) > 1e-8 @show ctr1 @show ctr2 error("stop") end end κ = 1.0 t = Maxwell3D.singlelayer(wavenumber=κ) E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ) e = (n × E) × n Z1 = assemble(t,RT1,RT1) Z2 = assemble(t,RT2,RT2) @hilbertspace j @hilbertspace k efie = @discretise t[k,j]==e[k] j∈RT2 k∈RT2 u = gmres(efie) Γ = Γ2 X = RT2 include("utils/postproc.jl") include("utils/plotresults.jl")
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1048
using CompScienceMeshes using BEAST G = meshsphere(1.0, 0.25) c = 1.0 S = BEAST.HH3DSingleLayerTDBIO(c) width, delay, scaling = 8.0, 12.0, 1.0 gaussian = creategaussian(width, delay, scaling) e = BEAST.planewave(point(0,0,1), c, gaussian) X = lagrangecxd0(G) Δt, Nt = 0.08, 300 #T = timebasisshiftedlagrange(Δt, Nt, 0) #T = timebasiscxd0(Δt, Nt) T = timebasisc0d1(Δt, Nt) U = timebasisdelta(Δt, Nt) V = X ⊗ T # trial space W = X ⊗ U # test space b = assemble(e, W) Z = assemble(S, W, V) iZ1 = inv(Z[:,:,1]) u = marchonintime(iZ1,Z,-b,Nt) U, Δω, ω0 = fouriertransform(u, Δt, 0.0, 2) ω = collect(ω0 .+ (0:Nt-1)*Δω) _, i1 = findmin(abs.(ω.-1.0)); ω1 = ω[i1] U1 = U[:,i1] fgaussian = fouriertransform(gaussian) U1 /= fgaussian(ω1) Fcr, geo = facecurrents(U1, X) #A = [real(norm(f)) for f in Fcr] d = joinpath(dirname(pathof(CompScienceMeshes)),"..","examples","plotlyjs_patches.jl") include(d) # include(Pkg.dir("CompScienceMeshes","examples","plotlyjs_patches.jl")) using LinearAlgebra p = patch(geo, real.(norm.(Fcr))) #PlotlyJS.plot([p])
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1060
using CompScienceMeshes using BEAST G = meshsphere(1.0, 0.25) c = 1.0 # S = BEAST.HH3DSingleLayerTDBIO(c) S = BEAST.HH3DHyperSingularTDBIO(speed_of_light=c, numdiffs=1) width, delay, scaling = 8.0, 12.0, 1.0 gaussian = creategaussian(width, delay, scaling) e = BEAST.planewave(point(0,0,1), c, gaussian) # X = lagrangecxd0(G) X = lagrangec0d1(G) Δt, Nt = 0.08, 300 T = timebasisc0d1(Δt, Nt) U = timebasiscxd0(Δt, Nt) V = X ⊗ T # trial space W = X ⊗ U # test space nbd = center(chart(G, first(cells(G)))) refs = refspace(X) vals = refs(nbd) Z = assemble(S, W, V) h = dot(n,BEAST.gradient(e)) b = assemble(h, W) iZ1 = inv(Z[:,:,1]) u = marchonintime(iZ1,Z,-b,Nt) U, Δω, ω0 = fouriertransform(u, Δt, 0.0, 2) ω = collect(ω0 .+ (0:Nt-1)*Δω) _, i1 = findmin(abs.(ω.-1.0)); ω1 = ω[i1] U1 = U[:,i1] fgaussian = fouriertransform(gaussian) U1 /= fgaussian(ω1) Fcr, geo = facecurrents(U1, X) include(joinpath(dirname(pathof(CompScienceMeshes)),"..","examples","plotlyjs_patches.jl")) using LinearAlgebra p = patch(geo, real.(norm.(Fcr))) #PlotlyJS.plot([p])
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1952
using CompScienceMeshes using BEAST using LinearAlgebra # G = meshsphere(1.0, 0.25) G = meshsphere(1.0, 0.30) c = 1.0 S = BEAST.HH3DSingleLayerTDBIO(c) D = BEAST.HH3DDoubleLayerTDBIO(speed_of_light=c) Id = BEAST.Identity() # width, delay, scaling = 24.0, 36.0, 1.0 width, delay, scaling = 16.0, 24.0, 1.0 gaussian = creategaussian(width, delay, scaling) fgaussian = fouriertransform(gaussian) e = BEAST.planewave(point(0,0,1), c, gaussian) de = BEAST.planewave(point(0,0,1), c, derive(gaussian)) h = BEAST.gradient(e) # X = lagrangecxd0(G) X = lagrangecxd0(G) Y = duallagrangec0d1(G) # Y = lagrangecxd0(G) # X = duallagrangecxd0(G, boundary(G)) # Y = lagrangec0d1(G) # Δt, Nt = 0.9032321, 301 # Δt, Nt = 1.2032321, 301 Δt, Nt = 0.16, 300 # T = timebasisc0d1(Δt, Nt) P = timebasiscxd0(Δt, Nt) H = timebasisc0d1(Δt, Nt) δ = timebasisdelta(Δt, Nt) # assemble the right hand side bd = assemble(n⋅h, X ⊗ P) Z1d = assemble(Id ⊗ Id, X ⊗ P, X ⊗ P, Val{:bandedstorage}) Z0d = assemble(D, X ⊗ P, X ⊗ P, Val{:bandedstorage}) Zd = Z0d + (-0.5)*Z1d u = marchonintime(inv(Zd[:,:,1]), Zd, bd, Nt) bs = assemble(e, X ⊗ δ) Zs = assemble(S, X ⊗ δ, X ⊗ P, Val{:bandedstorage}) v = marchonintime(inv(Zs[:,:,1]), Zs, -bs, Nt) U, Δω, ω0 = fouriertransform(u, Δt, 0.0, 2) V, Δω, ω0 = fouriertransform(v, Δt, 0.0, 2) ω = collect(ω0 .+ (0:Nt-1)*Δω) _, i1 = findmin(abs.(ω.-1.0)); ω1 = ω[i1] U_td = U[:,i1] / fgaussian(ω1) V_td = V[:,i1] / fgaussian(ω1) fd_S = Helmholtz3D.singlelayer(wavenumber=1.0) fd_e = Helmholtz3D.planewave(wavenumber=1.0, direction=ẑ) fd_eh = assemble(strace(fd_e,G), X) fd_Sh = assemble(fd_S, X, X) U_fd = fd_Sh \ fd_eh fcru_td, _ = facecurrents(U_td, X) fcrv_td, _ = facecurrents(V_td, X) fcru_fd, _ = facecurrents(U_fd, X) using Plots plot() plot!(u[1,:]) plot!(v[1,:]) # import PlotlyJS # ptch = patch(G, norm.(fcru_fd)) # PlotlyJS.plot(ptch) Sstatic = Helmholtz3D.singlelayer(gamma=0.0) Zstatic = assemble(Sstatic, X, X)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
889
using BEAST Δt, Nt = 1.0, 200 T0 = timebasisshiftedlagrange(Δt, Nt, 0) T1 = timebasisshiftedlagrange(Δt, Nt, 1) T2 = timebasisshiftedlagrange(Δt, Nt, 2) T3 = timebasisshiftedlagrange(Δt, Nt, 3) iT0 = integrate(T0) iT1 = integrate(T1) iT2 = integrate(T2) iT3 = integrate(T3) δ = timebasisdelta(Δt, Nt) Id = BEAST.Identity() Z = assemble(Id, δ, iT1) Z = reshape(Z,1,1,length(Z)) taxis = range(0, step=Δt, length=Nt) width, delay = 2.0, 6.0 f(t) = -2*(t-delay)/width^2*exp(-((t-delay)/width)^2) F(t) = exp(-((t-delay)/width)^2) b = F.(taxis)' u = marchonintime(inv(Z[:,:,1]), Z, b, Nt) plot(taxis, u[1,:]) taxis2 = range(-3Δt, 5Δt, length=200) plot() plot!(taxis2, iT3.(taxis2)) kmax = 2 cv = BEAST.ConvOp( reshape(Z[1,1,1:kmax],kmax,1,1), fill(1,(1,1)), fill(kmax,(1,1)), fill(1.0,(1,1)), Nt) w, Q = BEAST.polyeig(cv) u2 = marchonintime(inv(Z[:,:,1]), cv, b, Nt)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1771
using CompScienceMeshes, BEAST fn = joinpath(dirname(pathof(BEAST)),"../examples/assets/torus.msh") m = CompScienceMeshes.read_gmsh_mesh(fn) @show numcells(m) X = raviartthomas(m) @show numfunctions(X) Y = buffachristiansen(m) @show numfunctions(Y) verts = skeleton(m,0) edges = skeleton(m,1) faces = skeleton(m,2) Λ = connectivity(verts, edges) Σᵀ = connectivity(edges, faces) @assert all(sum(Σᵀ,dims=1) .== 0) κ = 1.0e-5 S = Maxwell3D.singlelayer(wavenumber=κ) D = Maxwell3D.doublelayer(wavenumber=κ) C = BEAST.DoubleLayerRotatedMW3D(im*κ) J = BEAST.Identity() N = BEAST.NCross() # Sxx = assemble(S,X,X) # Myx = assemble(D+0.5N,Y,X) # Mxx = assemble(C-0.5J,X,X) using JLD2 @load "temp/matrices.jld2" using LinearAlgebra norm(Σᵀ*Myx*Λ) ϵ, μ = 1.0, 1.0 ω = κ / √(ϵ*μ) E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ) H = -1/(im*μ*ω)*curl(E) e = (n × E) × n h = (n × H) × n ex = assemble(e, X) hy = assemble(h, Y) hx = assemble(n × H,X) u1 = Sxx \ ex u2 = Myx \ hy u3 = Mxx \ hx Φ, Θ = [0.0], range(0,stop=π,length=100) pts = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for ϕ in Φ for θ in Θ] ff1 = potential(MWFarField3D(wavenumber=κ), pts, u1, X) ff2 = potential(MWFarField3D(wavenumber=κ), pts, u2, X) ff3 = potential(MWFarField3D(wavenumber=κ), pts, u3, X) #Why: projectors Σ = copy(transpose(Σᵀ)) Ps = Σ*pinv(Array(Σᵀ*Σ))*Σᵀ Pl = I - Ps u1s = Ps*u1 u2s = Ps*u2 u3s = Ps*u3 u1l = Pl*u1 u2l = Pl*u2 u3l = Pl*u3 # s = svdvals(M) # h = nullspace(M,s[end]*1.0001) # # fcr, geo = facecurrents(h[:,end],X) # # V,F = vertexarray(m), cellarray(m) # B = [real(f[i]) for f in fcr, i in 1:3] # using MATLAB # mat"mesh = Mesh($V,$F)" # mat"[C,N] = faceNormals(mesh)" # mat"figure; hold on" # mat"patch(mesh,$(norm.(fcr)))" # mat"quiver3x(C,$B)"
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1078
using SparseArrays function edge_values(space, m) rs = refspace(space) supp = geometry(space) edgs = skeleton(supp,1) Conn = copy(transpose(connectivity(edgs, supp, identity))) Vals = zeros(scalartype(space), length(supp), length(edgs)) for (i,sh) in enumerate(space.fns[m]) tet_id = sh.cellid tet = chart(supp, tet_id) for k in nzrange(Conn, tet_id) edg_id = rowvals(Conn)[k] edge = chart(edgs, edg_id) ctr = CompScienceMeshes.center(edge) tgt = tangents(ctr,1) ctr1 = neighborhood(tet, carttobary(tet, cartesian(ctr))) vals = rs(ctr1) val = vals[sh.refid].value Vals[tet_id, edg_id] += dot(sh.coeff * val, tgt) end end return Vals end function check_edge_values(EV) for i in axes(EV,2) ev = [x for x in EV[:,i] if abs(x) > 1e-8] uev = unique(x -> round(x, digits=5), ev) if !(length(uev) <= 1) @show i @show uev error("stop") end end end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
473
@isdefined(plotresults) || (plotresults = false) if plotresults postproc || error("Cannot plot results without going through post-processing.") @eval begin import Plots using LinearAlgebra p1 = Plots.scatter(Θ, real.(norm.(ffd))) p2 = Plots.heatmap(clamp.(real.(norm.(nfd)), 0.0, 2.0), clims=(0,2)) p3 = Plots.contour(clamp.(real.(norm.(nfd)), 0.0, 2.0), clims=(0,2)) Plots.plot(p1,p2,p3,layout=(3,1)) end end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
650
@isdefined(postproc) || (postproc = false) @isdefined(plotresults) || (plotresults = false) plotresults && (postproc = true) if postproc Φ, Θ = [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) fcr, geo = facecurrents(u, X) nx, nz = 50, 100 x = 0.0 ys, zs = range(-2,stop=2,length=nx), range(-4,stop=4,length=nz) gridpoints = [point(x,y,z) for y in ys, z in zs] nfd = potential(MWSingleLayerField3D(wavenumber = κ), gridpoints, u, X) nfd = reshape(nfd, (nx,nz)) nfd .-= E.(gridpoints) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1464
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 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
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1006
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
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
7097
module BEAST using Distributed using LinearAlgebra using SharedArrays using SparseArrays using FillArrays using BlockArrays using ExtendableSparse using ConvolutionOperators using SauterSchwabQuadrature using SauterSchwab3D using FastGaussQuadrature using LinearMaps using LiftedMaps using AbstractTrees using NestedUnitRanges using Infiltrator using TestItems import LinearAlgebra: cross, dot import LinearAlgebra: ×, ⋅ import SharedArrays: sdata export dot export planewave export RefSpace, numfunctions, coordtype, scalartype, assemblydata, geometry, refspace, valuetype export lagrangecxd0, lagrangec0d1, duallagrangec0d1, unitfunctioncxd0, unitfunctionc0d1 export duallagrangecxd0 export lagdimension export restrict export raviartthomas, raowiltonglisson, positions export brezzidouglasmarini export brezzidouglasmarini3d export nedelecd3d export nedelecc3d export portcells, rt_ports, getindex_rtg, subset export StagedTimeStep, numstages export subdsurface, subdBasis, assemblydata, refspace export spatialbasis, temporalbasis export ⊗ export timebasisc0d1 export timebasiscxd0 export timebasisdelta export timebasisshiftedlagrange export TimeBasisDeltaShifted export ntrace export strace export ttrace export SingleLayer export DoubleLayer export DoubleLayerTransposed export HyperSingular export HH3DSingleLayerTDBIO export HH3DDoubleLayerTDBIO export ∂n, grad export HH3DHyperSingularFDBIO export DirichletTrace export HH3DMonopole, gradHH3DMonopole export HH3DLinearPotential export HH3DSingleLayerNear export HH3DDoubleLayerNear export HH3DDoubleLayerTransposedNear export HH3DHyperSingularNear export NitscheHH3 export MWSingleLayerTDIO export MWDoubleLayerTDIO export MWFarField3DTD export MWFarField3D export MWSingleLayer3D, MWHyperSingular, MWWeaklySingular export MWDoubleLayer3D export PlaneWaveMW export dipolemw3d, DipoleMW export TangTraceMW, CrossTraceMW export curl export gradient export MWSingleLayerField3D export SingleLayerTrace export DoubleLayerRotatedMW3D, MWDoubleLayerRotatedFarField3D export MWSingleLayerPotential3D export VIEOperator export gmres export @hilbertspace, @varform, @discretise export solve export convolve export marchonintime export RungeKuttaConvolutionQuadrature export laplace_to_z, inverse_z_transform, real_inverse_z_transform export butcher_tableau_radau_2stages export butcher_tableau_radau_3stages export creategaussian export derive, integrate export fouriertransform export assemble export Identity export shapevals export NCross export quadrule, elements export blockassembler export localoperator export localoperator2 export assemble export facecurrents export potential export get_scatter_parameters export quaddata export DofInterpolate export kernelvals export integrand export shapevals export ScalarTrace export PlaneWaveDirichlet export PlaneWaveNeumann struct NormalVector end using CompScienceMeshes using Combinatorics using FFTW using SparseArrays function convolve end include("utils/polynomial.jl") include("utils/specialfns.jl") include("utils/combinatorics.jl") include("utils/linearspace.jl") include("utils/zeromap.jl") include("utils/rank1map.jl") include("bases/basis.jl") include("bases/lincomb.jl") include("bases/trace.jl") include("bases/restrict.jl") include("bases/divergence.jl") include("bases/local/laglocal.jl") include("bases/local/rtlocal.jl") include("bases/local/rt2local.jl") include("bases/local/ndlocal.jl") include("bases/local/nd2local.jl") include("bases/local/bdmlocal.jl") include("bases/local/ncrossbdmlocal.jl") include("bases/local/ndlcclocal.jl") include("bases/local/ndlcdlocal.jl") include("bases/local/bdm3dlocal.jl") include("bases/local/rtqlocal.jl") include("bases/lagrange.jl") include("bases/rtspace.jl") include("bases/rt2space.jl") include("bases/rtxspace.jl") include("bases/bcspace.jl") include("bases/ndspace.jl") include("bases/nd2space.jl") include("bases/bdmdiv.jl") include("bases/ncrossbdmspace.jl") include("bases/ndlccspace.jl") include("bases/ndlcdspace.jl") include("bases/dual3d.jl") include("bases/bdm3dspace.jl") include("bases/rtqspace.jl") include("bases/subdbasis.jl") include("bases/stagedtimestep.jl") include("bases/timebasis.jl") include("bases/tensorbasis.jl") include("operator.jl") include("quadrature/quadstrats.jl") include("excitation.jl") include("localop.jl") include("multiplicativeop.jl") include("identityop.jl") include("integralop.jl") include("dyadicop.jl") include("interpolation.jl") include("quadrature/doublenumqstrat.jl") include("quadrature/doublenumsauterqstrat.jl") include("quadrature/doublenumwiltonsauterqstrat.jl") include("quadrature/doublenumwiltonbogaertqstrat.jl") include("quadrature/selfsauterdnumotherwiseqstrat.jl") include("quadrature/nonconformingintegralopqstrat.jl") include("quadrature/commonfaceoverlappingedgeqstrat.jl") include("quadrature/strategies/cfcvsautercewiltonpdnumqstrat.jl") include("quadrature/doublenumints.jl") include("quadrature/singularityextractionints.jl") include("quadrature/sauterschwabints.jl") include("quadrature/nonconformingoverlapqrule.jl") include("quadrature/nonconformingtouchqrule.jl") include("postproc.jl") include("postproc/segcurrents.jl") include("postproc/farfield.jl") include("timedomain/tdintegralop.jl") include("timedomain/tdexcitation.jl") include("timedomain/motlu.jl") include("timedomain/tdtimeops.jl") include("timedomain/rkcq.jl") include("timedomain/zdomain.jl") include("timedomain/td_symmetric_quadstrat.jl") # Support for Maxwell equations include("maxwell/mwexc.jl") include("maxwell/mwops.jl") include("maxwell/nxdbllayer.jl") include("maxwell/wiltonints.jl") include("maxwell/nitsche.jl") include("maxwell/farfield.jl") include("maxwell/nearfield.jl") include("maxwell/spotential.jl") include("maxwell/maxwell.jl") include("maxwell/sourcefield.jl") # Support for the Helmholtz equation include("helmholtz2d/helmholtzop.jl") include("helmholtz3d/hh3dexc.jl") include("helmholtz3d/hh3dops.jl") include("helmholtz3d/nitsche.jl") include("helmholtz3d/hh3dnear.jl") include("helmholtz3d/hh3dfar.jl") include("helmholtz3d/hh3d_sauterschwabqr.jl") include("helmholtz3d/helmholtz3d.jl") include("helmholtz3d/wiltonints.jl") #suport for Volume Integral equation include("volumeintegral/vie.jl") include("volumeintegral/vieexc.jl") include("volumeintegral/vieops.jl") include("volumeintegral/farfield.jl") include("volumeintegral/sauterschwab_ints.jl") include("decoupled/dpops.jl") include("decoupled/potentials.jl") include("helmholtz3d/timedomain/tdhh3dops.jl") include("helmholtz3d/timedomain/tdhh3dexc.jl") include("helmholtz3d/timedomain/tdhh3dpp.jl") include("maxwell/timedomain/mwtdops.jl") include("maxwell/timedomain/mwtdexc.jl") include("maxwell/timedomain/tdfarfield.jl") include("utils/butchertableau.jl") include("utils/variational.jl") include("solvers/solver.jl") include("solvers/lusolver.jl") include("solvers/itsolver.jl") include("utils/plotlyglue.jl") const x̂ = point(1, 0, 0) const ŷ = point(0, 1, 0) const ẑ = point(0, 0, 1) export x̂, ŷ, ẑ const n = NormalVector() export n end # module
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1052
struct DyadicOp{T,F,G} <: Operator α::T f::F g::G end function DyadicOp(f::F, g::G) where {F,G} T = scalartype(f,g) DyadicOp{T,F,G}(one(T), f, g) end Base.:*(b::Number, op::DyadicOp) = DyadicOp(b * op.α, op.f, op.g) scalartype(op::DyadicOp) = promote_type(scalartype(op.α), scalartype(op.f), scalartype(op.g)) defaultquadstrat(op::DyadicOp, testspace, refspace) = nothing function allocatestorage(op::DyadicOp, test_functions, trial_functions, storage_trait, longdelays_trait) T = scalartype(op, test_functions, trial_functions) M = length(test_functions) N = length(trial_functions) u = zeros(T,M) v = zeros(T,N) A = BEAST.Rank1Map{T}(u,v) store() = A freeze() = A return freeze, store end function assemble!(biop::DyadicOp, tfs::Space, bfs::Space, store, threading::Type{BEAST.Threading{:multi}}; quadstrat=defaultquadstrat(biop, tfs, bfs)) u = assemble(biop.f, tfs) v = assemble(biop.g, bfs) A = store() A.u .= biop.α * u A.v .= adjoint.(v) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
3241
abstract type Functional end defaultquadstrat(fn::Functional, basis) = SingleNumQStrat(8) quaddata(fn::Functional, refs, cells, qs::SingleNumQStrat) = quadpoints(refs, cells, [qs.quad_rule]) quadrule(fn::Functional, refs, p, cell, qd, qs::SingleNumQStrat) = qd[1,p] """ assemble(fn, tfs) Assemble the vector of test coefficients corresponding to functional `fn` and test functions `tfs`. """ function assemble(field::Functional, tfs; quadstrat=defaultquadstrat(field, tfs)) R = scalartype(tfs) b = zeros(Complex{R}, numfunctions(tfs)) store(v,m) = (b[m] += v) assemble!(field, tfs, store; quadstrat) return b end function assemble!(field::Functional, tfs::DirectProductSpace, store; quadstrat=defaultquadstrat(field, tfs)) I = Int[0] for s in tfs.factors push!(I, last(I) + numfunctions(s)) end for (i,s) in enumerate(tfs.factors) store1(v,m) = store(v, m + I[i]) assemble!(field, s, store1; quadstrat) end end function assemble!(field::Functional, tfs::Space, store; quadstrat=defaultquadstrat(field, tfs)) tels, tad = assemblydata(tfs) trefs = refspace(tfs) qd = quaddata(field, trefs, tels, quadstrat) for (t, tcell) in enumerate(tels) # compute the testing with the reference elements qr = quadrule(field, trefs, t, tcell, qd, quadstrat) blocal = celltestvalues(trefs, tcell, field, qr) for i in 1 : numfunctions(trefs) for (m,a) in tad[t,i] store(a*blocal[i], m) end end end end function assemble!(field::Functional, tfs::subdBasis, store; quadstrat=defaultquadstrat(field, tfs)) tels, tad = assemblydata(tfs) trefs = refspace(tfs) qd = quaddata(field, trefs, tels) for (t, tcell) in enumerate(tels) # compute the testing with the reference elements qr = quadrule(field, trefs, t, tcell, qd, quadstrat) blocal = celltestvalues(trefs, tcell, field, qr, quadstrat) for i in 1 : length(tad[t]) for (m,a) in tad[t][i] store(a*blocal[i], m) end end end end function celltestvalues(tshs::RefSpace{T,NF}, tcell, field, qr) where {T,NF} num_tshs = numfunctions(tshs) interactions = zeros(Complex{T}, num_tshs) num_oqp = length(qr) for p in 1 : num_oqp mp = qr[p].point dx =qr[p].weight fval = field(mp) tvals = qr[p].value for m in 1 : num_tshs tval = tvals[m] igd = integrand(field, tval, fval) interactions[m] += igd * dx end end return interactions end function celltestvalues(tshs::subReferenceSpace{T,D}, tcell, field, qr) where {T,D} num_oqp = length(qr) num_tshs = length(qr[1].value[1]) interactions = (Complex{T}, num_tshs) for p in 1 : num_oqp mp = qr[p].point dx =qr[p].weight fval = field(mp) tvals = qr[p].value interactions = zeros(Complex{T}, num_tshs) for m in 1 : num_tshs tval = tvals[1][m] igd = integrand(field, tval, fval) interactions[m] += igd * dx end end return interactions end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
3691
struct Identity <: LocalOperator end kernelvals(biop::Identity, x) = nothing integrand(op::Identity, kernel, x, g, f) = dot(f[1], g[1]) scalartype(op::Identity) = Union{} struct NCross <: LocalOperator end kernelvals(op::NCross, mp) = nothing integrand(op::NCross, kernel, x, g, f) = dot(g[1], normal(x) × f[1]) scalartype(op::NCross) = Union{} function _alloc_workspace(qd, g, f, tels, bels) q = qd[1] τ = tels[1] w, p = q[1], neighborhood(τ,q[2]) a = (w, p, g(p), f(p)) A = Vector{typeof(a)}(undef,length(qd)) end const LinearRefSpaceTriangle = Union{RTRefSpace, RT2RefSpace, NDRefSpace, ND2RefSpace, BDMRefSpace, NCrossBDMRefSpace} defaultquadstrat(::LocalOperator, ::LinearRefSpaceTriangle, ::LinearRefSpaceTriangle) = SingleNumQStrat(6) function quaddata(op::LocalOperator, g::LinearRefSpaceTriangle, f::LinearRefSpaceTriangle, tels, bels, qs::SingleNumQStrat) u, w = trgauss(qs.quad_rule) qd = [(w[i],SVector(u[1,i],u[2,i])) for i in 1:length(w)] A = _alloc_workspace(qd, g, f, tels, bels) return qd, A end defaultquadstrat(::LocalOperator, ::subReferenceSpace, ::subReferenceSpace) = SingleNumQStrat(6) function quaddata(op::LocalOperator, g::subReferenceSpace, f::subReferenceSpace, tels, bels, qs::SingleNumQStrat) u, w = trgauss(qs.quad_rule) qd = [(w[i],SVector(u[1,i],u[2,i])) for i in 1:length(w)] A = _alloc_workspace(qd, g, f, tels, bels) return qd, A end const LinearRefSpaceTetr = Union{NDLCCRefSpace, NDLCDRefSpace, BDM3DRefSpace} defaultquadstrat(::LocalOperator, ::LinearRefSpaceTetr, ::LinearRefSpaceTetr) = SingleNumQStrat(3) function quaddata(op::LocalOperator, g::LinearRefSpaceTetr, f::LinearRefSpaceTetr, tels, bels, qs::SingleNumQStrat) o, x, y, z = CompScienceMeshes.euclidianbasis(3) reftet = simplex(x,y,z,o) qps = quadpoints(reftet, qs.quad_rule) qd = [(w, parametric(p)) for (p,w) in qps] A = _alloc_workspace(qd, g, f, tels, bels) return qd, A end defaultquadstrat(::LocalOperator, ::LagrangeRefSpace{T,D1,2}, ::LagrangeRefSpace{T,D2,2}) where {T,D1,D2} = SingleNumQStrat(6) function quaddata(op::LocalOperator, g::LagrangeRefSpace{T,Deg,2} where {T,Deg}, f::LagrangeRefSpace, tels::Vector, bels::Vector, qs::SingleNumQStrat) U = typeof(tels[1].volume) u, w = legendre(qs.quad_rule, 0.0, 1.0) qd = [(w[i],u[i]) for i in eachindex(w)] A = _alloc_workspace(Tuple{U,U}.(qd), g, f, tels, bels) return qd, A end defaultquadstrat(::LocalOperator, ::LagrangeRefSpace{T,D1,3}, ::LagrangeRefSpace{T,D2,3}) where {T,D1,D2} = SingleNumQStrat(6) function quaddata(op::LocalOperator, g::LagrangeRefSpace{T,Deg,3} where {T,Deg}, f::LagrangeRefSpace, tels::Vector, bels::Vector, qs::SingleNumQStrat) u, w = trgauss(qs.quad_rule) qd = [(w[i], SVector(u[1,i], u[2,i])) for i in 1:length(w)] A = _alloc_workspace(qd, g, f, tels, bels) return qd, A end defaultquadstrat(::LocalOperator, ::LagrangeRefSpace{T,D1,4}, ::LagrangeRefSpace{T,D2,4}) where {T,D1,D2} = SingleNumQStrat(6) function quaddata(op::LocalOperator, g::LagrangeRefSpace{T,Deg,4} where {T,Deg}, f::LagrangeRefSpace, tels::Vector, bels::Vector, qs::SingleNumQStrat) o, x, y, z = CompScienceMeshes.euclidianbasis(3) reftet = simplex(x,y,z,o) qps = quadpoints(reftet, qs.quad_rule) qd = [(w, parametric(p)) for (p,w) in qps] A = _alloc_workspace(qd, g, f, tels, bels) return qd, A end function quadrule(op::LocalOperator, ψ::RefSpace, ϕ::RefSpace, τ, (qd,A), qs::SingleNumQStrat) for i in eachindex(qd) q = qd[i] w, p = q[1], neighborhood(τ,q[2]) A[i] = (w, p, ψ(p), ϕ(p)) end return A end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
24223
abstract type IntegralOperator <: Operator end defaultquadstrat(op::IntegralOperator, tfs::RefSpace, bfs::RefSpace) = DoubleNumSauterQstrat(2,3,5,5,4,3) """ blockassembler(operator, test_space, trial_space) -> assembler Return a callable object for the creation of blocks within a BEM matrix. This function performs all tasks common to the assembly of several blocks within a single boundary element matrix. The return value can be used to generate blocks by calling it as follows: assembler(I,J,storefn) where `I` and `J` are arrays of indices in `test_space` and `trial_space`, respectively, corresponding to the rows and columns of the desired block. Note that the block will be constructed in compressed form, i.e. the rows and columns of the store that are written into are the positions within `I` and `J` (as opposed to the positions within `1:numfunctions(test_space)` and `1:numfunctions(trial_space)`). In particular the size of the constructed block will be `(length(I), length(J))`. This last property allows the assembly of permutations of the BEM matrix by supplying for `I` and `J` permutations of `1:numfunctions(test_space)` and `1:numfunctions(trial_space)`. """ function blockassembler end # """ # quadrule(operator,test_refspace,trial_refspace,p,test_element,q_trial_element, qd) # Returns an object that contains all the dynamic (runtime) information that # defines the integration strategy that will be used by `momintegrals!` to compute # the interactions between the local test/trial functions defined on the specified # geometric elements. The indices `p` and `q` refer to the position of the test # and trial elements as encountered during iteration over the output of # `geometry`. # The last argument `qd` provides access to all precomputed data required for # quadrature. For example it might be desirable to precompute all the quadrature # points for all possible numerical quadrature schemes that can potentially be # required during matrix assembly. This makes sense, since the number of point is # order N (where N is the number of faces) but these points will appear in N^2 # computations. Precomputation requires some extra memory but can save a lot on # computation time. # """ # function quadrule end """ elements(geo) Create an iterable collection of the elements stored in `geo`. The order in which this collection produces the elements determines the index used for lookup in the data structures returned by `assemblydata` and `quaddata`. """ elements(geo) = [chart(geo,cl) for cl in geo] elements(sp::Space) = elements(geometry(sp)) """ assemblechunk!(biop::IntegralOperator, tfs, bfs, store) Computes the matrix of operator biop wrt the finite element spaces tfs and bfs """ function assemblechunk!(biop::IntegralOperator, tfs::Space, bfs::Space, store; quadstrat=defaultquadstrat(biop, tfs, bfs)) # test_elements, tad, tcells = assemblydata(tfs) # bsis_elements, bad, bcells = assemblydata(bfs) tr = assemblydata(tfs); tr == nothing && return br = assemblydata(bfs); br == nothing && return test_elements, tad, tcells = tr bsis_elements, bad, bcells = br tshapes = refspace(tfs); num_tshapes = numfunctions(tshapes) bshapes = refspace(bfs); num_bshapes = numfunctions(bshapes) tgeo = geometry(tfs) bgeo = geometry(bfs) qd = quaddata(biop, tshapes, bshapes, test_elements, bsis_elements, quadstrat) zlocal = zeros(scalartype(biop, tfs, bfs), 2num_tshapes, 2num_bshapes) if CompScienceMeshes.refines(tgeo, bgeo) assemblechunk_body_test_refines_trial!(biop, tfs, test_elements, tad, tcells, bfs, bsis_elements, bad, bcells, qd, zlocal, store; quadstrat) elseif CompScienceMeshes.refines(bgeo, tgeo) assemblechunk_body_trial_refines_test!(biop, tfs, test_elements, tad, tcells, bfs, bsis_elements, bad, bcells, qd, zlocal, store; quadstrat) else assemblechunk_body!(biop, tshapes, test_elements, tad, bshapes, bsis_elements, bad, qd, zlocal, store; quadstrat) end end function assemblechunk_body!(biop, test_shapes, test_elements, test_assembly_data, trial_shapes, trial_elements, trial_assembly_data, qd, zlocal, store; quadstrat) myid = Threads.threadid() myid == 1 && print("dots out of 10: ") todo, done, pctg = length(test_elements), 0, 0 for (p,tcell) in enumerate(test_elements) for (q,bcell) in enumerate(trial_elements) fill!(zlocal, 0) qrule = quadrule(biop, test_shapes, trial_shapes, p, tcell, q, bcell, qd, quadstrat) # @show "integralop" qrule momintegrals!(biop, test_shapes, trial_shapes, tcell, bcell, zlocal, qrule) I = length(test_assembly_data[p]) J = length(trial_assembly_data[q]) for j in 1 : J, i in 1 : I zij = zlocal[i,j] for (n,b) in trial_assembly_data[q][j] zb = zij*b for (m,a) in test_assembly_data[p][i] store(a*zb, m, n) end end end end done += 1 new_pctg = round(Int, done / todo * 100) if new_pctg > pctg + 9 myid == 1 && print(".") pctg = new_pctg end end myid == 1 && println("") end function assemblechunk_body_test_refines_trial!(biop, test_functions, test_charts, test_assembly_data, test_cells, trial_functions, trial_charts, trial_assembly_data, trial_cells, qd, zlocal, store; quadstrat) test_shapes = refspace(test_functions) trial_shapes = refspace(trial_functions) myid = Threads.threadid() myid == 1 && print("dots out of 10: ") todo, done, pctg = length(test_charts), 0, 0 for (p,(tcell,tchart)) in enumerate(zip(test_cells, test_charts)) for (q,(bcell,bchart)) in enumerate(zip(trial_cells, trial_charts)) fill!(zlocal, 0) qrule = quadrule(biop, test_shapes, trial_shapes, p, tchart, q, bchart, qd, quadstrat) # @show ("1", qrule) momintegrals_test_refines_trial!(zlocal, biop, test_functions, tcell, tchart, trial_functions, bcell, bchart, qrule, quadstrat) I = length(test_assembly_data[p]) J = length(trial_assembly_data[q]) for j in 1 : J, i in 1 : I zij = zlocal[i,j] for (n,b) in trial_assembly_data[q][j] zb = zij*b for (m,a) in test_assembly_data[p][i] store(a*zb, m, n) end end end end done += 1 new_pctg = round(Int, done / todo * 100) if new_pctg > pctg + 9 myid == 1 && print(".") pctg = new_pctg end end myid == 1 && println("") end function assemblechunk_body_trial_refines_test!(biop, test_functions, test_charts, test_assembly_data, test_cells, trial_functions, trial_charts, trial_assembly_data, trial_cells, qd, zlocal, store; quadstrat) test_shapes = refspace(test_functions) trial_shapes = refspace(trial_functions) myid = Threads.threadid() myid == 1 && print("dots out of 10: ") todo, done, pctg = length(test_charts), 0, 0 for (p,(tcell,tchart)) in enumerate(zip(test_cells, test_charts)) for (q,(bcell,bchart)) in enumerate(zip(trial_cells, trial_charts)) fill!(zlocal, 0) qrule = quadrule(biop, test_shapes, trial_shapes, p, tchart, q, bchart, qd, quadstrat) momintegrals_trial_refines_test!(zlocal, biop, test_functions, tcell, tchart, trial_functions, bcell, bchart, qrule, quadstrat) I = length(test_assembly_data[p]) J = length(trial_assembly_data[q]) for j in 1 : J, i in 1 : I zij = zlocal[i,j] for (n,b) in trial_assembly_data[q][j] zb = zij*b for (m,a) in test_assembly_data[p][i] store(a*zb, m, n) end end end end done += 1 new_pctg = round(Int, done / todo * 100) if new_pctg > pctg + 9 myid == 1 && print(".") pctg = new_pctg end end myid == 1 && println("") end function blockassembler(biop::IntegralOperator, tfs::Space, bfs::Space; quadstrat=defaultquadstrat(biop, tfs, bfs)) test_elements, test_assembly_data, trial_elements, trial_assembly_data, quadrature_data, zlocals = assembleblock_primer(biop, tfs, bfs; quadstrat) tgeo = geometry(tfs) bgeo = geometry(bfs) if CompScienceMeshes.refines(tgeo, bgeo) return (test_ids, trial_ids, store) -> begin assembleblock_body_test_refines_trial!(biop, tfs, test_ids, test_elements, test_assembly_data, bfs, trial_ids, trial_elements, trial_assembly_data, quadrature_data, zlocals, store; quadstrat) end elseif CompScienceMeshes.refines(bgeo, tgeo) return (test_ids, trial_ids, store) -> begin assembleblock_body_trial_refines_test!(biop, tfs, test_ids, test_elements, test_assembly_data, bfs, trial_ids, trial_elements, trial_assembly_data, quadrature_data, zlocals, store; quadstrat) end else return (test_ids, trial_ids, store) -> begin assembleblock_body!(biop, tfs, test_ids, test_elements, test_assembly_data, bfs, trial_ids, trial_elements, trial_assembly_data, quadrature_data, zlocals, store; quadstrat) end end end function assembleblock(operator::AbstractOperator, test_functions, trial_functions; quadstrat=defaultquadstrat(operator, test_functions, trial_functions)) Z, store = allocatestorage(operator, test_functions, trial_functions) assembleblock!(operator, test_functions, trial_functions, store; quadstrat) sdata(Z) end function assembleblock!(biop::IntegralOperator, tfs::Space, bfs::Space, store; quadstrat=defaultquadstrat(biop, tfs, bfs)) test_elements, tad, trial_elements, bad, quadrature_data, zlocals = assembleblock_primer(biop, tfs, bfs; quadstrat) active_test_dofs = collect(1:numfunctions(tfs)) active_trial_dofs = collect(1:numfunctions(bfs)) assembleblock_body!(biop, tfs, active_test_dofs, test_elements, tad, bfs, active_trial_dofs, trial_elements, bad, quadrature_data, zlocals, store; quadstrat) end function assembleblock_primer(biop, tfs, bfs; quadstrat=defaultquadstrat(biop, tfs, bfs)) test_elements, tad = assemblydata(tfs; onlyactives=false) bsis_elements, bad = assemblydata(bfs; onlyactives=false) tshapes = refspace(tfs); num_tshapes = numfunctions(tshapes) bshapes = refspace(bfs); num_bshapes = numfunctions(bshapes) qd = quaddata(biop, tshapes, bshapes, test_elements, bsis_elements, quadstrat) zlocals = Matrix{scalartype(biop, tfs, bfs)}[] for i in 1:Threads.nthreads() push!(zlocals, zeros(scalartype(biop, tfs, bfs), num_tshapes, num_bshapes)) end return test_elements, tad, bsis_elements, bad, qd, zlocals end function assembleblock_body!(biop::IntegralOperator, tfs, test_ids, test_elements, test_assembly_data, bfs, trial_ids, bsis_elements, trial_assembly_data, quadrature_data, zlocals, store; quadstrat) test_shapes = refspace(tfs) trial_shapes = refspace(bfs) # Enumerate all the active test elements active_test_el_ids = Vector{Int}() active_trial_el_ids = Vector{Int}() test_id_in_blk = Dict{Int,Int}() trial_id_in_blk = Dict{Int,Int}() for (i,m) in enumerate(test_ids); test_id_in_blk[m] = i; end for (i,m) in enumerate(trial_ids); trial_id_in_blk[m] = i; end for m in test_ids, sh in tfs.fns[m]; push!(active_test_el_ids, sh.cellid); end for m in trial_ids, sh in bfs.fns[m]; push!(active_trial_el_ids, sh.cellid); end active_test_el_ids = unique!(sort!(active_test_el_ids)) active_trial_el_ids = unique!(sort!(active_trial_el_ids)) @assert length(active_test_el_ids) <= length(test_elements) @assert length(active_trial_el_ids) <= length(bsis_elements) @assert maximum(active_test_el_ids) <= length(test_elements) "$(maximum(active_test_el_ids)), $(length(test_elements))" @assert maximum(active_trial_el_ids) <= length(bsis_elements) "$(maximum(active_trial_el_ids)), $(length(bsis_elements))" for p in active_test_el_ids tcell = test_elements[p] for q in active_trial_el_ids bcell = bsis_elements[q] fill!(zlocals[Threads.threadid()], 0) qrule = quadrule(biop, test_shapes, trial_shapes, p, tcell, q, bcell, quadrature_data, quadstrat) momintegrals!(biop, test_shapes, trial_shapes, tcell, bcell, zlocals[Threads.threadid()], qrule) for j in 1 : size(zlocals[Threads.threadid()],2) for i in 1 : size(zlocals[Threads.threadid()],1) for (n,b) in trial_assembly_data[q,j] n′ = get(trial_id_in_blk, n, 0) n′ == 0 && continue for (m,a) in test_assembly_data[p,i] m′ = get(test_id_in_blk, m, 0) m′ == 0 && continue store(a*zlocals[Threads.threadid()][i,j]*b, m′, n′) end end end end end end end function assembleblock_body_trial_refines_test!(biop::IntegralOperator, tfs, test_ids, test_elements, test_assembly_data, bfs, trial_ids, bsis_elements, trial_assembly_data, quadrature_data, zlocals, store; quadstrat) test_shapes = refspace(tfs) trial_shapes = refspace(bfs) # Enumerate all the active test elements active_test_el_ids = Vector{Int}() active_trial_el_ids = Vector{Int}() test_id_in_blk = Dict{Int,Int}() trial_id_in_blk = Dict{Int,Int}() for (i,m) in enumerate(test_ids); test_id_in_blk[m] = i; end for (i,m) in enumerate(trial_ids); trial_id_in_blk[m] = i; end for m in test_ids, sh in tfs.fns[m]; push!(active_test_el_ids, sh.cellid); end for m in trial_ids, sh in bfs.fns[m]; push!(active_trial_el_ids, sh.cellid); end active_test_el_ids = unique!(sort!(active_test_el_ids)) active_trial_el_ids = unique!(sort!(active_trial_el_ids)) @assert length(active_test_el_ids) <= length(test_elements) @assert length(active_trial_el_ids) <= length(bsis_elements) @assert maximum(active_test_el_ids) <= length(test_elements) "$(maximum(active_test_el_ids)), $(length(test_elements))" @assert maximum(active_trial_el_ids) <= length(bsis_elements) "$(maximum(active_trial_el_ids)), $(length(bsis_elements))" for p in active_test_el_ids tcell = test_elements[p] for q in active_trial_el_ids bcell = bsis_elements[q] fill!(zlocals[Threads.threadid()], 0) qrule = quadrule(biop, test_shapes, trial_shapes, p, tcell, q, bcell, quadrature_data, quadstrat) momintegrals_trial_refines_test!(zlocals[Threads.threadid()], biop, tfs, p, tcell, bfs, q, bcell, qrule, quadstrat) for j in 1 : size(zlocals[Threads.threadid()],2) for i in 1 : size(zlocals[Threads.threadid()],1) for (n,b) in trial_assembly_data[q,j] n′ = get(trial_id_in_blk, n, 0) n′ == 0 && continue for (m,a) in test_assembly_data[p,i] m′ = get(test_id_in_blk, m, 0) m′ == 0 && continue store(a*zlocals[Threads.threadid()][i,j]*b, m′, n′) end end end end end end end function assembleblock_body_test_refines_trial!(biop::IntegralOperator, tfs, test_ids, test_elements, test_assembly_data, bfs, trial_ids, bsis_elements, trial_assembly_data, quadrature_data, zlocals, store; quadstrat) test_shapes = refspace(tfs) trial_shapes = refspace(bfs) # Enumerate all the active test elements active_test_el_ids = Vector{Int}() active_trial_el_ids = Vector{Int}() test_id_in_blk = Dict{Int,Int}() trial_id_in_blk = Dict{Int,Int}() for (i,m) in enumerate(test_ids); test_id_in_blk[m] = i; end for (i,m) in enumerate(trial_ids); trial_id_in_blk[m] = i; end for m in test_ids, sh in tfs.fns[m]; push!(active_test_el_ids, sh.cellid); end for m in trial_ids, sh in bfs.fns[m]; push!(active_trial_el_ids, sh.cellid); end active_test_el_ids = unique!(sort!(active_test_el_ids)) active_trial_el_ids = unique!(sort!(active_trial_el_ids)) @assert length(active_test_el_ids) <= length(test_elements) @assert length(active_trial_el_ids) <= length(bsis_elements) @assert maximum(active_test_el_ids) <= length(test_elements) "$(maximum(active_test_el_ids)), $(length(test_elements))" @assert maximum(active_trial_el_ids) <= length(bsis_elements) "$(maximum(active_trial_el_ids)), $(length(bsis_elements))" for p in active_test_el_ids tcell = test_elements[p] for q in active_trial_el_ids bcell = bsis_elements[q] fill!(zlocals[Threads.threadid()], 0) qrule = quadrule(biop, test_shapes, trial_shapes, p, tcell, q, bcell, quadrature_data, quadstrat) momintegrals_test_refines_trial!(zlocals[Threads.threadid()], biop, tfs, p, tcell, bfs, q, bcell, qrule, quadstrat) for j in 1 : size(zlocals[Threads.threadid()],2) for i in 1 : size(zlocals[Threads.threadid()],1) for (n,b) in trial_assembly_data[q,j] n′ = get(trial_id_in_blk, n, 0) n′ == 0 && continue for (m,a) in test_assembly_data[p,i] m′ = get(test_id_in_blk, m, 0) m′ == 0 && continue store(a*zlocals[Threads.threadid()][i,j]*b, m′, n′) end end end end end end end # function assembleblock_body_nested!(biop::IntegralOperator, # tfs, test_ids, test_elements, test_assembly_data, # bfs, trial_ids, bsis_elements, trial_assembly_data, # quadrature_data, zlocals, store; quadstrat) # test_shapes = refspace(tfs) # trial_shapes = refspace(bfs) # # Enumerate all the active test elements # active_test_el_ids = Vector{Int}() # active_trial_el_ids = Vector{Int}() # test_id_in_blk = Dict{Int,Int}() # trial_id_in_blk = Dict{Int,Int}() # for (i,m) in enumerate(test_ids); test_id_in_blk[m] = i; end # for (i,m) in enumerate(trial_ids); trial_id_in_blk[m] = i; end # for m in test_ids, sh in tfs.fns[m]; push!(active_test_el_ids, sh.cellid); end # for m in trial_ids, sh in bfs.fns[m]; push!(active_trial_el_ids, sh.cellid); end # active_test_el_ids = unique(sort(active_test_el_ids)) # active_trial_el_ids = unique(sort(active_trial_el_ids)) # for p in active_test_el_ids # tcell = test_elements[p] # for q in active_trial_el_ids # bcell = bsis_elements[q] # fill!(zlocals[Threads.threadid()], 0) # qrule = quadrule(biop, test_shapes, trial_shapes, p, tcell, q, bcell, quadrature_data, quadstrat) # momintegrals_test_refines_trial!(zlocals[Threads.threadid()], biop, # tfs, p, tcell, # bfs, q, bcell, # qrule, quadstrat) # # momintegrals_test_refines_trial!(biop, test_shapes, trial_shapes, tcell, bcell, zlocals[Threads.threadid()], qrule, quadstrat) # for j in 1 : size(zlocals[Threads.threadid()],2) # for i in 1 : size(zlocals[Threads.threadid()],1) # for (n,b) in trial_assembly_data[q,j] # n′ = get(trial_id_in_blk, n, 0) # n′ == 0 && continue # for (m,a) in test_assembly_data[p,i] # m′ = get(test_id_in_blk, m, 0) # m′ == 0 && continue # store(a*zlocals[Threads.threadid()][i,j]*b, m′, n′) # end end end end end end end function assemblerow!(biop::IntegralOperator, test_functions::Space, trial_functions::Space, store; quadstrat=defaultquadstrat(biop, test_functions, trial_functions)) test_elements = elements(geometry(test_functions)) trial_elements, trial_assembly_data = assemblydata(trial_functions) test_shapes = refspace(test_functions) trial_shapes = refspace(trial_functions) num_test_shapes = numfunctions(test_shapes) num_trial_shapes = numfunctions(trial_shapes) quadrature_data = quaddata(biop, test_shapes, trial_shapes, test_elements, trial_elements, quadstrat) zlocal = zeros(scalartype(biop, test_functions, trial_functions), num_test_shapes, num_trial_shapes) @assert length(trial_elements) == numcells(geometry(trial_functions)) @assert numfunctions(test_functions) == 1 assemblerow_body!(biop, test_functions, test_elements, test_shapes, trial_assembly_data, trial_elements, trial_shapes, zlocal, quadrature_data, store; quadstrat) end function assemblerow_body!(biop, test_functions, test_elements, test_shapes, trial_assembly_data, trial_elements, trial_shapes, zlocal, quadrature_data, store; quadstrat) test_function = test_functions.fns[1] for shape in test_function p = shape.cellid i = shape.refid a = shape.coeff tcell = test_elements[p] for (q,bcell) in enumerate(trial_elements) fill!(zlocal, 0) qrule = quadrule(biop, test_shapes, trial_shapes, p, tcell, q, bcell, quadrature_data, quadstrat) momintegrals!(biop, test_shapes, trial_shapes, tcell, bcell, zlocal, qrule) for j in 1:size(zlocal,2) for (n,b) in trial_assembly_data[q,j] store(a*zlocal[i,j]*b, 1, n) end end end end end function assemblecol!(biop::IntegralOperator, test_functions::Space, trial_functions::Space, store; quadstrat=defaultquadstrat(biop, test_functions, trial_functions)) test_elements, test_assembly_data = assemblydata(test_functions) trial_elements = elements(geometry(trial_functions)) test_shapes = refspace(test_functions) trial_shapes = refspace(trial_functions) num_test_shapes = numfunctions(test_shapes) num_trial_shapes = numfunctions(trial_shapes) quadrature_data = quaddata(biop, test_shapes, trial_shapes, test_elements, trial_elements, quadstrat) zlocal = zeros( scalartype(biop, test_functions, trial_functions), num_test_shapes, num_trial_shapes) @assert length(test_elements) == numcells(geometry(test_functions)) @assert numfunctions(trial_functions) == 1 assemblecol_body!(biop, test_assembly_data, test_elements, test_shapes, trial_functions, trial_elements, trial_shapes, zlocal, quadrature_data, store; quadstrat) end function assemblecol_body!(biop, test_assembly_data, test_elements, test_shapes, trial_functions, trial_elements, trial_shapes, zlocal, quadrature_data, store; quadstrat) trial_function = trial_functions.fns[1] for shape in trial_function q = shape.cellid j = shape.refid b = shape.coeff bcell = trial_elements[q] for (p,tcell) in enumerate(test_elements) fill!(zlocal, 0) qrule = quadrule(biop, test_shapes, trial_shapes, p, tcell, q, bcell, quadrature_data, quadstrat) momintegrals!(biop, test_shapes, trial_shapes, tcell, bcell, zlocal, qrule) for i in 1:size(zlocal,1) for (m,a) in test_assembly_data[p,i] store(a*zlocal[i,j]*b, m, 1) end end end end end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
7036
function DofInterpolate(basis::LagrangeBasis, field) T = promote_type(scalartype(basis), scalartype(field)) num_bfs = numfunctions(basis) res = Vector{T}(undef, num_bfs) for b in 1 : num_bfs bfs = basis.fns[b] shape = bfs[1] cellid = shape.cellid refid = shape.refid cell = cells(basis.geo)[cellid] tria = chart(basis.geo, cellid) vid = cell[refid] if refid == 1 v = neighborhood(tria, [1, 0]) elseif refid == 2 v = neighborhood(tria, [0, 1]) else v = neighborhood(tria, [0, 0]) end res[b] = field(v) end return res end ### Piecewise constant elements require separate treatment ### TODO: Probably a rewrite is advisable to also take into account ### dual elements properly. function DofInterpolate(basis::LagrangeBasis{0,-1,M,T,NF,P}, field) where {M, T, NF, P} TT = promote_type(scalartype(basis), scalartype(field)) num_bfs = numfunctions(basis) res = Vector{TT}(undef, num_bfs) for b in 1 : num_bfs bfs = basis.fns[b] basis.pos[b] shape = bfs[1] cellid = shape.cellid tria = chart(basis.geo, cellid) v = neighborhood(tria, [1/3, 1/3]) res[b] = field(v) end return res end function DofInterpolate(basis::RTBasis, field) T = promote_type(scalartype(basis), scalartype(field)) num_bfs = numfunctions(basis) res = Vector{T}(undef, num_bfs) for b in 1 : num_bfs bfs = basis.fns[b] shape = bfs[1] cellid = shape.cellid refid = shape.refid coeff = shape.coeff cell = cells(basis.geo)[cellid] e = refid v1 = cell[mod1(e+1,3)] v2 = cell[mod1(e+2,3)] edge = simplex(basis.geo.vertices[[v1,v2]]...) t = tangents(center(edge),1) tria = chart(basis.geo, cellid) n = normal(center(tria)) bn = normalize(cross(n,t)) v = center(edge) res[b] = volume(edge)*coeff*dot(field(v),bn) end return [r for r in res] end function DofInterpolate(basis::BDMBasis, field) T = promote_type(scalartype(basis), scalartype(field)) num_bfs = numfunctions(basis) res = Vector{T}(undef, num_bfs) for b in 1 : num_bfs bfs = basis.fns[b] shape = bfs[2] cellid = shape.cellid refid = shape.refid coeff = shape.coeff cell = cells(basis.geo)[cellid] e = (refid-1)÷2+1 v1 = cell[mod1(e+1,3)] v2 = cell[mod1(e+2,3)] edge = simplex(basis.geo.vertices[[v1,v2]]...) t = tangents(center(edge),1) tria = chart(basis.geo, cellid) n = normal(center(tria)) bn = normalize(cross(n,t)) if refid == 1 v = neighborhood(tria, [0, 1]) elseif refid == 2 v = neighborhood(tria, [0, 0]) elseif refid == 3 v = neighborhood(tria, [0, 0]) elseif refid == 4 v = neighborhood(tria, [1, 0]) elseif refid == 5 v = neighborhood(tria, [1, 0]) else v = neighborhood(tria, [0, 1]) end res[b] = volume(edge)*coeff*dot(field(v),bn) end return res end function DofInterpolate(basis::NDLCDBasis, field) T = promote_type(scalartype(basis), scalartype(field)) num_bfs = numfunctions(basis) res = Vector{T}(undef, num_bfs) for b in 1 : num_bfs bfs = basis.fns[b] shape = bfs[1] cellid = shape.cellid refid = shape.refid coeff = shape.coeff cell = cells(basis.geo)[cellid] f = refid v1 = cell[mod1(f+1,4)] v2 = cell[mod1(f+2,4)] v3 = cell[mod1(f+3,4)] v4 = cell[mod1(f,4)] face = simplex(basis.geo.vertices[[v1,v2,v3]]...) n = normal(center(face)) inside = dot(n, basis.geo.vertices[v4]-basis.geo.vertices[v1]) n *= -sign(inside) v = center(face) res[b] = volume(face)*coeff*dot(field(v),n) end return res end function DofInterpolate(basis::BEAST.BDM3DBasis, field) T = promote_type(scalartype(basis), scalartype(field)) num_bfs = numfunctions(basis) res = Vector{T}(undef, num_bfs) for b in 1 : num_bfs bfs = basis.fns[b] shape = bfs[1] cellid = shape.cellid refid = shape.refid coeff = shape.coeff cell = cells(basis.geo)[cellid] f = (refid-1)÷3+1 v1 = cell[mod1(f+1,4)] v2 = cell[mod1(f+2,4)] v3 = cell[mod1(f+3,4)] v4 = cell[mod1(f,4)] face = simplex(basis.geo.vertices[[v1,v2,v3]]...) n = normal(center(face)) inside = dot(n, basis.geo.vertices[v4]-basis.geo.vertices[v1]) n *= -sign(inside) tet = simplex(basis.geo.vertices[cell]...) if refid == 1 v = neighborhood(tet, [0, 1, 0]) elseif refid == 2 v = neighborhood(tet, [0, 0, 1]) elseif refid == 3 v = neighborhood(tet, [0, 0, 0]) elseif refid == 4 v = neighborhood(tet, [0, 0, 1]) elseif refid == 5 v = neighborhood(tet, [0, 0, 0]) elseif refid == 6 v = neighborhood(tet, [1, 0, 0]) elseif refid == 7 v = neighborhood(tet, [0, 0, 0]) elseif refid == 8 v = neighborhood(tet, [1, 0, 0]) elseif refid == 9 v = neighborhood(tet, [0, 1, 0]) elseif refid == 10 v = neighborhood(tet, [1, 0, 0]) elseif refid == 11 v = neighborhood(tet, [0, 1, 0]) else v = neighborhood(tet, [0, 0, 1]) end res[b] = volume(face)*coeff*dot(field(v),n) end return res end function Centervalues(mesh::Mesh,f::Functional) num_cells = numcells(mesh) T = coordtype(mesh) res = Vector{SVector{3,Complex{T}}}(undef, num_cells) for i in 1:num_cells cell = cells(mesh)[i] tet = chart(mesh, cell) v = center(tet) res[i] = f(v) end return res end function EvalCenter(basis::Space, coeff) mesh = basis.geo T = coordtype(mesh) num_cells = numcells(mesh) num_bfs = numfunctions(basis) ref_space = refspace(basis) res = Vector{SVector{3,Complex{T}}}(undef, num_cells) for i in 1:num_cells res[i] = [0,0,0] end for b in 1 : num_bfs bfs = basis.fns[b] for shape in bfs cellid = shape.cellid refid = shape.refid a = shape.coeff cell = cells(mesh)[cellid] tet = chart(mesh, cell) v = center(tet) local_bfs = ref_space(v) res[cellid] += a*coeff[b]*local_bfs[refid].value end end return res end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
10385
using CollisionDetection abstract type LocalOperator <: Operator end function allocatestorage(op::LocalOperator, test_functions, trial_functions, storage_trait::Type{Val{:bandedstorage}}) T = scalartype(op, test_functions, trial_functions) M = Int[] N = Int[] V = T[] function store(v,m,n) push!(M,m) push!(N,n) push!(V,v) end function freeze() nrows = numfunctions(test_functions) ncols = numfunctions(trial_functions) return sparse(M,N,V, nrows, ncols) end return freeze, store end function allocatestorage(op::LocalOperator, testfunctions, trialfunctions, storage_trait::Type{Val{:sparsedicts}}) T = scalartype(op, testfunctions, trialfunctions) m = numfunctions(testfunctions) n = numfunctions(trialfunctions) Z = ExtendableSparseMatrix(T,m,n) store(v,m,n) = (Z[m,n] += v) freeze() = SparseArrays.SparseMatrixCSC(Z) return freeze, store end function allocatestorage(op::LocalOperator, test_functions, trial_functions, storage_trait::Type{Val{:densestorage}}) T = scalartype(op, test_functions, trial_functions) Z = zeros(T, numfunctions(test_functions), numfunctions(trial_functions)) store(v,m,n) = (Z[m,n] += v) freeze() = Z return freeze, store end function assemble!(biop::LocalOperator, tfs::Space, bfs::Space, store, threading::Type{Threading{:multi}}; quadstrat=defaultquadstrat(biop, tfs, bfs)) if geometry(tfs) == geometry(bfs) return assemble_local_matched!(biop, tfs, bfs, store; quadstrat) end if CompScienceMeshes.refines(geometry(tfs), geometry(bfs)) return assemble_local_refines!(biop, tfs, bfs, store; quadstrat) end return assemble_local_mixed!(biop, tfs, bfs, store; quadstrat) end function assemble!(biop::LocalOperator, tfs::Space, bfs::Space, store, threading::Type{Threading{:single}}; quadstrat=defaultquadstrat(biop, tfs, bfs)) if geometry(tfs) == geometry(bfs) return assemble_local_matched!(biop, tfs, bfs, store; quadstrat) end if CompScienceMeshes.refines(geometry(tfs), geometry(bfs)) return assemble_local_refines!(biop, tfs, bfs, store; quadstrat) end return assemble_local_mixed!(biop, tfs, bfs, store; quadstrat) end function assemble_local_matched!(biop::LocalOperator, tfs::Space, bfs::Space, store; quadstrat=defaultquadstrat(biop, tfs, bfs)) tels, tad, ta2g = assemblydata(tfs) bels, bad, ba2g = assemblydata(bfs) bg2a = zeros(Int, length(geometry(bfs))) for (i,j) in enumerate(ba2g) bg2a[j] = i end trefs = refspace(tfs) brefs = refspace(bfs) qd = quaddata(biop, trefs, brefs, tels, bels, quadstrat) verbose = length(tels) > 10_000 verbose && print("dots out of 20: ") todo, done, pctg = length(tels), 0, 0 locmat = zeros(scalartype(biop, trefs, brefs), numfunctions(trefs), numfunctions(brefs)) for (p,cell) in enumerate(tels) P = ta2g[p] q = bg2a[P] q == 0 && continue qr = quadrule(biop, trefs, brefs, cell, qd, quadstrat) fill!(locmat, 0) cellinteractions_matched!(locmat, biop, trefs, brefs, cell, qr) for i in 1 : size(locmat, 1), j in 1 : size(locmat, 2) for (m,a) in tad[p,i], (n,b) in bad[q,j] store(a * locmat[i,j] * b, m, n) end end new_pctg = round(Int, (done += 1) / todo * 100) verbose && new_pctg > pctg + 4 && (print("."); pctg = new_pctg) end end function assemble_local_refines!(biop::LocalOperator, tfs::Space, bfs::Space, store; quadstrat=defaultquadstrat(biop, tfs, bfs)) println("Using 'refines' algorithm for local assembly:") tgeo = geometry(tfs) bgeo = geometry(bfs) @assert CompScienceMeshes.refines(tgeo, bgeo) trefs = refspace(tfs) brefs = refspace(bfs) tels, tad, ta2g = assemblydata(tfs) bels, bad, ba2g = assemblydata(bfs) bg2a = zeros(Int, length(geometry(bfs))) for (i,j) in enumerate(ba2g) bg2a[j] = i end qd = quaddata(biop, trefs, brefs, tels, bels, quadstrat) print("dots out of 10: ") todo, done, pctg = length(tels), 0, 0 for (p,tcell) in enumerate(tels) P = ta2g[p] Q = CompScienceMeshes.parent(tgeo, P) q = bg2a[Q] bcell = bels[q] @assert overlap(tcell, bcell) isct = intersection(tcell, bcell) for cell in isct P = restrict(brefs, bcell, cell) Q = restrict(trefs, tcell, cell) qr = quadrule(biop, trefs, brefs, cell, qd, quadstrat) zlocal = cellinteractions(biop, trefs, brefs, cell, qr) zlocal = Q * zlocal * P' for i in 1 : numfunctions(trefs) for j in 1 : numfunctions(brefs) for (m,a) in tad[p,i] for (n,b) in bad[q,j] store(a * zlocal[i,j] * b, m, n) end # next basis function this cell supports end # next test function this cell supports end # next refshape on basis side end # next refshape on test side end # next cell in intersection done += 1 new_pctg = round(Int, done / todo * 100) if new_pctg > pctg + 9 print(".") pctg = new_pctg end end # next cell in the test geometry println("") end function assemble_local_matched!(biop::LocalOperator, tfs::subdBasis, bfs::subdBasis, store; quadstrat=defaultquadstrat(biop, tfs, bfs)) tels, tad = assemblydata(tfs) bels, bad = assemblydata(bfs) trefs = refspace(tfs) brefs = refspace(bfs) qd = quaddata(biop, trefs, brefs, tels, bels, quadstrat) for (p,cell) in enumerate(tels) qr = quadrule(biop, trefs, brefs, cell, qd, quadstrat) locmat = cellinteractions(biop, trefs, brefs, cell, qr) for i in 1 : size(locmat, 1), j in 1 : size(locmat, 2) for (m,a) in tad[p][i], (n,b) in bad[p][j] store(a * locmat[i,j] * b, m, n) end end end end function elementstree(elements) nverts = dimension(eltype(elements)) + 1 ncells = length(elements) @assert !isempty(elements) P = eltype(elements[1].vertices) T = coordtype(eltype(elements)) points = zeros(P, ncells) radii = zeros(T, ncells) for i in 1 : ncells verts = elements[i].vertices bary = verts[1] for j in 2:length(verts) bary += verts[j] end points[i] = bary / nverts for j in 1 : nverts radii[i] = max(radii[i], norm(verts[j]-points[i])) end end return Octree(points, radii) end """ assemble_local_mixed(biop::LocalOperator, tfs, bfs) For use when basis and test functions are defined on different meshes """ function assemble_local_mixed!(biop::LocalOperator, tfs::Space{T}, bfs::Space{T}, store; quadstrat=defaultquadstrat(biop, tfs, bfs)) where {T} tol = sqrt(eps(T)) trefs = refspace(tfs) brefs = refspace(bfs) tels, tad = assemblydata(tfs) bels, bad = assemblydata(bfs) qd = quaddata(biop, trefs, brefs, tels, bels, quadstrat) # store the bcells in an octree tree = elementstree(bels) print("dots out of 10: ") todo, done, pctg = length(tels), 0, 0 for (p,tcell) in enumerate(tels) tc, ts = boundingbox(tcell.vertices) pred = (c,s) -> boxesoverlap(c,s,tc,ts) for box in boxes(tree, pred) for q in box bcell = bels[q] if overlap(tcell, bcell) isct = intersection(tcell, bcell) for cell in isct volume(cell) < tol && continue P = restrict(brefs, bcell, cell) Q = restrict(trefs, tcell, cell) qr = quadrule(biop, trefs, brefs, cell, qd, quadstrat) zlocal = cellinteractions(biop, trefs, brefs, cell, qr) zlocal = Q * zlocal * P' for i in 1 : numfunctions(trefs) for j in 1 : numfunctions(brefs) for (m,a) in tad[p,i] for (n,b) in bad[q,j] store(a * zlocal[i,j] * b, m, n) end # next basis function this cell supports end # next test function this cell supports end # next refshape on basis side end # next refshape on test side end # next cell in intersection end # if overlap end # next cell in the basis geometry end # next box in the octree done += 1 new_pctg = round(Int, done / todo * 100) if new_pctg > pctg + 9 print(".") pctg = new_pctg end end # next cell in the test geometry println("") end function cellinteractions_matched!(zlocal, biop, trefs, brefs, cell, qr) num_tshs = length(qr[1][3]) num_bshs = length(qr[1][4]) # zlocal = zeros(Float64, num_tshs, num_bshs) for q in qr w, mp, tvals, bvals = q[1], q[2], q[3], q[4] j = w * jacobian(mp) kernel = kernelvals(biop, mp) for n in 1 : num_bshs bval = bvals[n] for m in 1 : num_tshs tval = tvals[m] igd = integrand(biop, kernel, mp, tval, bval) zlocal[m,n] += j * igd end end end return zlocal end function cellinteractions(biop, trefs::U, brefs::V, cell, qr) where {U<:RefSpace{T},V<:RefSpace{T}} where {T} num_tshs = length(qr[1][3]) num_bshs = length(qr[1][4]) zlocal = zeros(T, num_tshs, num_bshs) for q in qr w, mp, tvals, bvals = q[1], q[2], q[3], q[4] j = w * jacobian(mp) kernel = kernelvals(biop, mp) for m in 1 : num_tshs tval = tvals[m] for n in 1 : num_bshs bval = bvals[n] igd = integrand(biop, kernel, mp, tval, bval) zlocal[m,n] += j * igd end end end return zlocal end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
235
struct Multiplicative{f} <: LocalOperator field::f end kernelvals(biop::Multiplicative, x) = nothing integrand(op::Multiplicative, kernel, x, g, f) = dot(f[1], op.field(cartesian(x))*g[1]) scalartype(op::Multiplicative) = Float64
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
10228
using .LinearSpace struct LongDelays{T} end struct Threading{T} end import Base: transpose, +, -, * abstract type AbstractOperator end #@linearspace AbstractOperator{T} T """ *Atomic operator*: one that assemblechunk can deal with """ abstract type Operator <: AbstractOperator end mutable struct TransposedOperator <: AbstractOperator op::AbstractOperator end scalartype(op::TransposedOperator) = scalartype(op.op) defaultquadstrat(op::TransposedOperator, tfs::Space, bfs::Space) = defaultquadstrat(op.op, tfs, bfs) mutable struct LinearCombinationOfOperators{T} <: AbstractOperator coeffs::Vector{T} ops::Vector end function scalartype(op::LinearCombinationOfOperators{T}) where T W = promote_type(T, scalartype(op.ops[1])) for i in 2:length(op.ops) W = promote_type(W, scalartype(op.ops[i])) end W end function derive(a::LinearCombinationOfOperators) coeffs = copy(a.coeffs) ops = [derive(op) for op in a.ops] return LinearCombinationOfOperators(coeffs, ops) end function +(a::LinearCombinationOfOperators, b::AbstractOperator) LinearCombinationOfOperators( [a.coeffs;[1.0]], [a.ops;[b]] ) end function +(a::LinearCombinationOfOperators, b::LinearCombinationOfOperators) LinearCombinationOfOperators( [a.coeffs; b.coeffs], [a.ops; b.ops] ) end +(a::AbstractOperator, b::LinearCombinationOfOperators) = b + a +(a::AbstractOperator, b::Number) = a + (b * Identity()) +(a::Number, b::AbstractOperator) = b + a *(a::Number, b::AbstractOperator) = LinearCombinationOfOperators([a], [b]) *(a::Number, b::LinearCombinationOfOperators) = LinearCombinationOfOperators(a * b.coeffs, b.ops) -(a::AbstractOperator, b::AbstractOperator) = a + (-1.0) * b -(a::AbstractOperator) = (-1.0) * a function +(a::AbstractOperator, b::AbstractOperator) LinearCombinationOfOperators( [1.0, 1.0], [a, b] ) end transpose(op::TransposedOperator) = op.op transpose(op::Operator) = TransposedOperator(op) defaultquadstrat(lc::LinearCombinationOfOperators, tfs, bfs) = [defaultquadstrat(op,tfs,bfs) for op in lc.ops] function assemble(operator::AbstractOperator, test_functions, trial_functions; storage_policy = Val{:bandedstorage}, # long_delays_policy = LongDelays{:compress}, threading = Threading{:multi}, quadstrat=defaultquadstrat(operator, test_functions, trial_functions)) Z, store = allocatestorage(operator, test_functions, trial_functions, storage_policy) assemble!(operator, test_functions, trial_functions, store, threading; quadstrat) return Z() end function assemble(A::Matrix, testfns, trialfns) @assert numfunctions(testfns) == size(A,1) @assert numfunctions(trialfns) == size(A,2) return A end function assemblerow(operator::AbstractOperator, test_functions, trial_functions, storage_policy = Val{:bandedstorage}, long_delays_policy = LongDelays{:ignore}; quadstrat=defaultquadstrat(operator, test_functions, trial_functions)) Z, store = allocatestorage(operator, test_functions, trial_functions, storage_policy, long_delays_policy) assemblerow!(operator, test_functions, trial_functions, store; quadstrat) Z() end function assemblecol(operator::AbstractOperator, test_functions, trial_functions, storage_policy = Val{:bandestorage}, long_delays_policy = LongDelays{:ignore}; quadstrat=defaultquadstrat(operator, test_functions, trial_functions)) Z, store = allocatestorage(operator, test_functions, trial_functions, storage_policy, long_delays_policy) assemblecol!(operator, test_functions, trial_functions, store; quadstrat) Z() end function allocatestorage(operator::AbstractOperator, test_functions, trial_functions, storage_trait=nothing, longdelays_trait=nothing) T = promote_type( scalartype(operator) , scalartype(test_functions) , scalartype(trial_functions), ) Z = Matrix{T}(undef, numfunctions(test_functions), numfunctions(trial_functions), ) fill!(Z, 0) store(v,m,n) = (Z[m,n] += v) return ()->Z, store end function allocatestorage(operator::LinearCombinationOfOperators, test_functions::SpaceTimeBasis, trial_functions::SpaceTimeBasis, storage_policy::Type{Val{:bandedstorage}}, long_delays_policy::Type{LongDelays{:ignore}}) # This works when are terms in the LC can share storage return allocatestorage(operator.ops[end], test_functions, trial_functions, storage_policy, long_delays_policy) end function allocatestorage(operator::LinearCombinationOfOperators, test_functions::SpaceTimeBasis, trial_functions::SpaceTimeBasis, storage_policy::Type{Val{S}}, long_delays_policy::Type{LongDelays{L}}) where {L,S} # This works when are terms in the LC can share storage return allocatestorage(operator.ops[end], test_functions, trial_functions, storage_policy, long_delays_policy) end struct _OffsetStore{F} store::F row_offset::Int col_offset::Int end (f::_OffsetStore)(v,m,n) = f.store(v,m + f.row_offset, n + f.col_offset) function assemble!(operator::Operator, test_functions::Space, trial_functions::Space, store, threading::Type{Threading{:multi}}; quadstrat=defaultquadstrat(operator, test_functions, trial_functions)) P = Threads.nthreads() numchunks = P @assert numchunks >= 1 splits = [round(Int,s) for s in range(0, stop=numfunctions(test_functions), length=numchunks+1)] Threads.@threads for i in 1:P lo, hi = splits[i]+1, splits[i+1] lo <= hi || continue test_functions_p = subset(test_functions, lo:hi) store1 = _OffsetStore(store, lo-1, 0) assemblechunk!(operator, test_functions_p, trial_functions, store1, quadstrat=quadstrat) end end function assemble!(operator::Operator, test_functions::Space, trial_functions::Space, store, threading::Type{Threading{:single}}; quadstrat=defaultquadstrat(operator, test_functions, trial_functions)) assemblechunk!(operator, test_functions, trial_functions, store; quadstrat) end function assemble!(op::TransposedOperator, tfs::Space, bfs::Space, store, threading = Threading{:multi}; quadstrat=defaultquadstrat(op, tfs, bfs)) store1(v,m,n) = store(v,n,m) assemble!(op.op, bfs, tfs, store1, threading; quadstrat) end function assemble!(op::LinearCombinationOfOperators, tfs::AbstractSpace, bfs::AbstractSpace, store, threading = Threading{:multi}; quadstrat=defaultquadstrat(op, tfs, bfs)) for (a,A,qs) in zip(op.coeffs, op.ops, quadstrat) store1(v,m,n) = store(a*v,m,n) assemble!(A, tfs, bfs, store1, threading; quadstrat=qs) end end # Support for direct product spaces function assemble!(op::AbstractOperator, tfs::DirectProductSpace, bfs::Space, store, threading = Threading{:multi}; quadstrat=defaultquadstrat(op, tfs[1], bfs)) I = Int[0] for s in tfs.factors push!(I, last(I) + numfunctions(s)) end for (i,s) in enumerate(tfs.factors) store1(v,m,n) = store(v,m + I[i], n) assemble!(op, s, bfs, store1, threading; quadstrat) end end function assemble!(op::AbstractOperator, tfs::Space, bfs::DirectProductSpace, store, threading=Threading{:multi}; quadstrat=defaultquadstrat(op, tfs, bfs[1])) J = Int[0] for s in bfs.factors push!(J, last(J) + numfunctions(s)) end for (j,s) in enumerate(bfs.factors) store1(v,m,n) = store(v,m,n + J[j]) assemble!(op, tfs, s, store1, threading; quadstrat) end end function assemble!(op::AbstractOperator, tfs::DirectProductSpace, bfs::DirectProductSpace, store, threading=Threading{:multi}; quadstrat=defaultquadstrat(op, tfs[1], bfs[1])) I = Int[0] for s in tfs.factors push!(I, last(I) + numfunctions(s)) end for (i,s) in enumerate(tfs.factors) store1(v,m,n) = store(v,m + I[i],n) assemble!(op, s, bfs, store1, threading; quadstrat) end end # TODO: Remove BlockDiagonalOperator in favour of manipulations # on the level of bilinear forms. # Discretisation and assembly of these operators # will respect the direct product structure of the # HilbertSpace/FiniteElmeentSpace struct BlockDiagonalOperator <: AbstractOperator op::AbstractOperator end diag(op::AbstractOperator) = BlockDiagonalOperator(op) scalartype(op::BlockDiagonalOperator) = scalartype(op.op) defaultquadstrat(op::BlockDiagonalOperator, U::DirectProductSpace, V::DirectProductSpace) = defaultquadstrat(op.op, U, V) allocatestorage(op::BlockDiagonalOperator, X, Y, storage_trait, longdelays_trait) = allocatestorage(op.op, X, Y, storage_trait, longdelays_trait) function assemble!(op::BlockDiagonalOperator, U::DirectProductSpace, V::DirectProductSpace, store, threading=Threading{:multi}; quadstrat = defaultquadstrat(op, U, V)) @assert length(U.factors) == length(V.factors) I = Int[0]; for u in U.factors push!(I, last(I) + numfunctions(u)) end J = Int[0]; for v in V.factors push!(J, last(J) + numfunctions(v)) end for (k,(u,v)) in enumerate(zip(U.factors, V.factors)) store1(v,m,n) = store(v, I[k] + m, J[k] + n) assemble!(op.op, u, v, store1, threading; quadstrat) end end # BlockFull is default so not sure when this exists -> remove struct BlockFullOperators <: AbstractOperator op::AbstractOperator end blocks(op::AbstractOperator) = BlockFullOperators(op) scalartype(op::BlockFullOperators) = scalartype(op.op) defaultquadstrat(op::BlockFullOperators, U::DirectProductSpace, V::DirectProductSpace) = defaultquadstrat(op.op, U, V) function assemble!(op::BlockFullOperators, U::DirectProductSpace, V::DirectProductSpace, store, threading; quadstrat = defaultquadstrat(op, U, V)) I = Int[0]; for u in U.factors push!(I, last(I) + numfunctions(u)) end J = Int[0]; for v in V.factors push!(J, last(J) + numfunctions(v)) end for (k,u) in enumerate(U.factors) for (l,v) in enumerate(V.factors) store1(x,m,n) = store(x, I[k]+m, J[l]+n) assemble!(op.op, u, v, store1, threading; quadstrat) end end end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
6385
""" fcr, geo = facecurrents(coeffs, basis) Compute the value of the function with the given collection of coeffient in the provided basis in all the centroids of the mesh underlying the basis. The mesh is returned together with the currents. """ function facecurrents(coeffs, basis) T = eltype(coeffs) RT = real(T) refs = refspace(basis) numrefs = numfunctions(refs) cells, tad, a2g = assemblydata(basis) mesh = geometry(basis) D = dimension(mesh) # U = D+1 U = 3 # TODO: remove ugliness vals = refs(center(first(cells))) PT = typeof(first(coeffs)*vals[1][1]) fcr = zeros(PT, numcells(mesh)) for (t,cell) in enumerate(cells) mps = neighborhood(cell, ones(RT,D)/(D+1)) vals = refs(mps) # assemble in the right hand side vector for i in 1 : numrefs fx = vals[i][1] for (m,a) in tad[t,i] # fcr[t] += coeffs[m] * a * fx fcr[a2g[t]] += coeffs[m] * a * fx end end end return fcr, geometry(basis) end function facecurrents(coeffs, basis::SpaceTimeBasis) space_basis = basis.space time_basis = basis.time Nt = numfunctions(time_basis) Δt = timestep(time_basis) refs = refspace(space_basis) trefs = refspace(time_basis) numrefs = numfunctions(refs) tnumrefs = numfunctions(trefs) cells, ad = assemblydata(space_basis) tcells, tad = assemblydata(time_basis) mesh = geometry(space_basis) T = eltype(coeffs) D = dimension(mesh) U = D+1 # TODO: express relative to input types PT = SVector{U, T} fcr = zeros(PT, numcells(mesh), Nt) for (k,tcell) in enumerate(tcells) tmps = neighborhood(tcell,1) tvals = trefs(tmps) for (p,cell) in enumerate(cells) mps = center(cell) vals = refs(mps) # assemble for i in 1:numrefs fx = vals[i][1] for j in 1:tnumrefs tfx = tvals[j] for (m,a) in ad[p,i] for (n,b) in tad[k,j] fcr[p,k] += (coeffs[m,n] * tfx * b) * a * fx end end end end end end return fcr, geometry(space_basis) end function facecurrents(u, X1, Xs...) offset = 0 n = numfunctions(X1) fcrs = [ facecurrents(u[offset .+ (1:n)], X1)[1] ] offset += n for i in 1:length(Xs) n = numfunctions(Xs[i]) push!(fcrs, facecurrents(u[offset .+ (1:n)], Xs[i])[1]) offset += n end fcrs end function facecurrents(u, X::DirectProductSpace) if length(X.factors) == 1 return facecurrents(u, X.factors[1]), geometry(X.factors[1])[1] end fcrs = facecurrents(u, X.factors...) #fcr = append!(fcrs...) fcr = vcat(fcrs...) m = weld([geometry(x) for x in X.factors]...) fcr, m end function potential(op, points, coeffs, basis; type=SVector{3,ComplexF64}, quadstrat=defaultquadstrat(op, basis)) ff = zeros(type, size(points)) store(v,m,n) = (ff[m] += v*coeffs[n]) potential!(store, op, points, basis; type, quadstrat) return ff end function potential(op, points,coeffs, basis::SpaceTimeBasis) T = SVector{3,eltype(coeffs)} ff = zeros(T, length(points), size(coeffs)[2]) store(v,m,n,k,o) = (ff[m,k] += v*coeffs[n,o]) potential!(store, op, points, basis) return ff end function potential(op, points, coeffs, space::DirectProductSpace; type=SVector{3,ComplexF64}, quadstrat=defaultquadstrat(op,space)) ff = zeros(type, size(points)) @assert length(coeffs) == numfunctions(space) offset = 0 for fct in space.factors store(v,m,n) = (ff[m] += v*coeffs[offset+n]) potential!(store, op, points, fct; type, quadstrat) offset += numfunctions(fct) end ff end function potential!(store, op, points, basis; type=SVector{3,ComplexF64}, quadstrat=defaultquadstrat(op, basis)) z = zeros(type,length(points)) els, ad = assemblydata(basis) rs = refspace(basis) zlocal = Array{type}(undef,numfunctions(rs)) qdata = quaddata(op,rs,els,quadstrat) print("dots out of 10: ") todo, done, pctg = length(points), 0, 0 for (p,y) in enumerate(points) for (q,el) in enumerate(els) fill!(zlocal,zero(type)) qr = quadrule(op,rs,p,y,q,el,qdata,quadstrat) farfieldlocal!(zlocal,op,rs,y,el,qr) # assemble from local contributions for (r,z) in enumerate(zlocal) for (n,b) in ad[q,r] store(z*b,p,n) end end end done += 1 new_pctg = round(Int, done / todo * 100) if new_pctg > pctg + 9 #println(todo," ",done," ",new_pctg) print(".") pctg = new_pctg end end println("") end function potential!(store, op, points, basis::SpaceTimeBasis) space_basis = basis.space tb = time_basis = basis.time Nt = numfunctions(time_basis) Δt = timestep(time_basis) T = SVector{3,Complex{eltype(eltype(points))}} refs = refspace(space_basis) trefs = refspace(time_basis) numrefs = numfunctions(refs) tnumrefs = numfunctions(trefs) els, ad = assemblydata(space_basis) tels, tad = assemblydata(time_basis) zlocal = Array{T}(numrefs,Nt) qdata = quaddata(op,refs,trefs,els,tels) #println("Computing nearfield.") print("dots out of 10: ") todo, done, pctg = Nt, 0, 0 for (k,tel) in enumerate(tels) for (p,y) in enumerate(points) for (q,el) in enumerate(els) fill!(zlocal,zero(T)) qr = quadrule(op,refs,trefs,p,y,q,el,k,tel,qdata) farfieldlocal!(zlocal,op,refs,trefs,p,y,q,el,k,tel,tb,qr) # assemble from local contributions for r in 1:numrefs for s in 1:Nt for (n,b) in ad[q,r] store(zlocal[r,s]*b,p,n,k,s) # end end end end end end done += 1 new_pctg = round(Int, done / todo * 100) if new_pctg > pctg + 9 #println(todo," ",done," ",new_pctg) print(".") pctg = new_pctg end end println("") end function farfieldlocal!(zlocal,op,refspace,y,el,qr) for q in qr x = q.point F = q.value dx = q.weight krn = kernelvals(op, y, x) for r in 1 : length(zlocal) zlocal[r] += integrand(op,krn,y,F[r],x) * dx end end end function farfieldlocal!(zlocal,op,trialrefs, timerefs, p, testel, q, trialel, k, timeel, tb,quadrule) M,N = size(zlocal) Δt = tb.timestep for qr in quadrule[1] x = qr.point F = qr.value dx = qr.weight krn = kernelvals(op, testel, x) for r = 1:M for l = 1:N t = (k - l)*Δt zlocal[r,l] += integrand(op,krn,testel,F[r], t, tb) * dx end end end end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
10318
abstract type RefSpace{T,D} end abstract type DivRefSpace{T,D} <: RefSpace{T,D} end abstract type AbstractSpace end abstract type Space{T} <: AbstractSpace end Base.length(s::AbstractSpace) = numfunctions(s) Base.in(x, s::AbstractSpace) = (x => s) """ scalartype(s) The scalar field over which the argument to a basis function or operator's integration kernel are defined. This is always a salar data type, even if the function or kernel is defined over a multi-dimensional space. """ scalartype(s::RefSpace{T}) where {T} = T scalartype(s::Space{T}) where {T} = T """ refspace(basis) Returns the ReferenceSpace of local shape functions on which the basis is built. """ function refspace end """ numfunctions(r) Return the number of functions in a `Space` or `RefSpace`. """ numfunctions(rs::RefSpace{T,D}) where {T,D} = D """ scalartype(x) The scalar field over which the values of a global or local basis function, or an operator are defined. This should always be a scalar type, even if the basis or operator takes on values in a vector or tensor space. This data type is used to determine the `eltype` of assembled discrete operators. """ function scalartype end scalartype(x1, xs...) = Base.promote_type(scalartype(x1), scalartype(xs...)) scalartype(x1::Number) = typeof(x1) scalartype(T::Type, x) = Base.promote_type(T, scalartype(x)) """ geometry(basis) Returns an iterable collection of geometric elements on which the functions in `basis` are defined. The order the elements are encountered needs correspond to the element indices used in the data structure returned by `assemblydata`. """ geometry(s::Space) = s.geo basisfunction(s::Space, i) = s.fns[i] numfunctions(space::Space) = length(space.fns) struct DirectProductSpace{T,S<:AbstractSpace} <: AbstractSpace factors::Vector{S} end function DirectProductSpace(factors::Vector{S}) where {S<:AbstractSpace} @assert !isempty(factors) T = scalartype(factors...) return DirectProductSpace{T,S}(factors) end Base.getindex(dps::DirectProductSpace, i) = dps.factors[i] defaultquadstrat(op, tfs::DirectProductSpace, bfs::DirectProductSpace) = defaultquadstrat(op, tfs.factors[1], bfs.factors[1]) defaultquadstrat(op, tfs::Space, bfs::DirectProductSpace) = defaultquadstrat(op, tfs, bfs.factors[1]) defaultquadstrat(op, tfs::DirectProductSpace, bfs::Space) = defaultquadstrat(op, tfs.factors[1], bfs) # defaultquadstrat(op, tfs::DirectProductSpace, bfs::DirectProductSpace) = defaultquadstrat(op, tfs.factors[1], bfs.factors[1]) # defaultquadstrat(op, tfs::RefSpace, bfs::DirectProductSpace) = defaultquadstrat(op, tfs, bfs.factors[1]) # defaultquadstrat(op, tfs::DirectProductSpace, bfs::RefSpace) = defaultquadstrat(op, tfs.factors[1], bfs) # scalartype(sp::DirectProductSpace{T}) where {T} = T # export cross, × export × function Base.:+(x::AbstractSpace...) T = scalartype(x...) return DirectProductSpace{T, AbstractSpace}([x...]) end cross(a::Space{T}, b::Space{T}) where {T} = DirectProductSpace{T,Space{T}}(Space{T}[a,b]) cross(a::DirectProductSpace{T}, b::Space{T}) where {T} = DirectProductSpace{T,Space{T}}([a.factors; b]) numfunctions(S::DirectProductSpace) = sum([numfunctions(s) for s in S.factors]) Base.length(S::DirectProductSpace) = numfunctions(S) scalartype(s::DirectProductSpace{T}) where {T} = T geometry(x::DirectProductSpace) = weld(x.geo...) AbstractTrees.children(x::AbstractSpace) = () AbstractTrees.children(x::DirectProductSpace) = x.factors Base.iterate(x::DirectProductSpace) = iterate(x.factors) Base.iterate(x::DirectProductSpace, state) = iterate(x.factors, state) struct Shape{T} cellid::Int refid::Int coeff::T end struct AssemblyData{T} data::Array{Tuple{Int,T},3} end Base.getindex(ad::AssemblyData, c, r) = ADIterator(c,r,size(ad.data,1),ad) struct AssemblyDataEl{T} element_index::Int ad::AssemblyData{T} end Base.length(adp::AssemblyDataEl) = size(adp.ad.data,2) Base.getindex(ad::AssemblyData, c) = AssemblyDataEl(c,ad) function Base.getindex(adp::AssemblyDataEl, r) ad = adp.ad ADIterator(adp.element_index,r,size(ad.data,1),ad) end struct ADIterator{T} c::Int r::Int I::Int ad::AssemblyData{T} end function Base.iterate(it::ADIterator, i = 1) (it.I < i || it.ad.data[i,it.r,it.c][1] < 1) && return nothing (it.ad.data[i,it.r,it.c], i+1) end function add!(bf::Vector{Shape{T}}, cellid, refid, coeff) where T for (i,sh) in pairs(bf) if sh.cellid == cellid && sh.refid == refid bf[i] = Shape(cellid, refid, sh.coeff + T(coeff)) return nothing end end push!(bf, Shape(cellid, refid, T(coeff))) return nothing end """ charts, admap = assemblydata(basis) Given a Basis this function returns a data structure containing the information required for matrix assemble. More precise the following expressions are valid for the returned object `ad`: ``` ad[c,r,i].globalindex ad[c,r,i].coefficient ``` Here, `c` and `r` are indices in the iterable set of geometric elements and the set of local shape functions on each element. `i` ranges from 1 to the maximum number of basis functions local shape function `r` on element `r` contributes to. For a triplet `(c,r,i)`, `globalindex` is the index in the Basis of the `i`-th basis function that has a contribution from local shape function `r` on element `r`. `coefficient` is the coefficient of that contribution in the linear combination defining that basis function in terms of local shape function. *Note*: the indices `c` correspond to the position of the corresponding element whilst iterating over `geometry(basis)`. """ function assemblydata(basis::Space; onlyactives=true) @assert numfunctions(basis) != 0 T = scalartype(basis) geo = geometry(basis) num_cells = numcells(geo) num_bfs = numfunctions(basis) num_refs = numfunctions(refspace(basis)) # # determine the maximum number of function defined over a given cell celltonum = make_celltonum(num_cells, num_refs, num_bfs, basis) # mark the active elements, i.e. elements over which # at least one function is defined. if onlyactives active, index_among_actives, num_active_cells, act_to_global = index_actives(num_cells, celltonum) else active = trues(num_cells) num_active_cells = num_cells index_among_actives = collect(1:num_cells) act_to_global = collect(1:num_cells) end num_active_cells == 0 && return nothing elements = instantiate_charts(geo, num_active_cells, active) max_celltonum = maximum(celltonum) fill!(celltonum, 0) data = fill((0,zero(T)), max_celltonum, num_refs, num_active_cells) for b in 1 : num_bfs for shape in basisfunction(basis, b) c = shape.cellid l = index_among_actives[c] @assert 0 < l <= num_active_cells r = shape.refid w = shape.coeff k = (celltonum[c,r] += 1) data[k,r,l] = (b,w) end end return elements, AssemblyData(data), act_to_global end function make_celltonum(num_cells, num_refs, num_bfs, basis) celltonum = zeros(Int, num_cells, num_refs) for b in 1 : num_bfs basisfunc = basisfunction(basis, b) for shape in basisfunc c = shape.cellid r = shape.refid celltonum[c,r] += 1 end end return celltonum end function index_actives(num_cells, celltonum) @assert num_cells == size(celltonum,1) active = falses(num_cells) index_among_actives = fill(0, num_cells) act_to_global = fill(0, num_cells) num_active_cells = 0 for i in 1:num_cells if maximum(@view celltonum[i,:]) > 0 num_active_cells += 1 active[i] = true index_among_actives[i] = num_active_cells act_to_global[num_active_cells] = i end end resize!(act_to_global, num_active_cells) return active, index_among_actives, num_active_cells, act_to_global end function instantiate_charts(geo, num_active_cells, active) @assert length(geo) != 0 E = typeof(chart(geo, first(geo))) elements = Vector{E}(undef,num_active_cells) j = 1 for (i,p) in enumerate(geo) active[i] || continue elements[j] = chart(geo, p) j += 1 end return elements end using SparseArrays function Base.:*(space::Space, A::SparseMatrixCSC) fns = similar(space.fns, size(A,2)) pos = similar(space.pos, size(A,2)) rows = rowvals(A) vals = nonzeros(A) for i in axes(A,2) fns[i] = Shape{scalartype(space)}[] for k in nzrange(A,i) m = rows[k] c = vals[k] for (s,sh) in enumerate(space.fns[m]) add!(fns[i], sh.cellid, sh.refid, sh.coeff * c) end pos[i] += space.pos[m] end pos[i] /= length(nzrange(A,i)) end return (typeof(space))(space.geo, fns, pos) end function addf!(fn::Vector{<:Shape}, x::Vector, space::Space, idcs::Vector{Int}) 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 support(s::BEAST.AbstractSpace, index::Int) geo = geometry(s) s1 = subset(s,[index]) charts, ad, activecells = BEAST.assemblydata(s1) return geo[activecells] end function functionvals(s::BEAST.Space, index::Int, n=3) s1 = subset(s,[index]) charts, ad, a2g = BEAST.assemblydata(s1) support = geometry(s)[a2g] vals = Any[] ctrs = Any[] refs = refspace(s) for (p,ch) in enumerate(charts) for i in 1:n-1 for j in 1:n-1 i+j < n || continue val = zero(BEAST.valuetype(refs, typeof(ch))) ct = CompScienceMeshes.neighborhood(ch, (i/n,j/n)) fx = refs(ct) for r in eachindex(fx) for (m,a) in ad[p,r] @assert m == 1 val += a * fx[r].value end end push!(ctrs, cartesian(ct)) push!(vals, val) end end end return ctrs, vals end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
22087
export buffachristiansen """ Move the s-th element right after the d-th """ function move_after!(p,n,s,d) n[d] == s && return t1 = n[d] t2 = n[s] t3 = p[s] n[d] = s n[s] = t1 p[s] == 0 || (n[p[s]] = t2) p[s] = d t1 == 0 || (p[t1] = s) t2 == 0 || (p[t2] = t3) end function move_before!(p, n, s, d) p[d] == s && return t1 = p[d] t2 = p[s] t3 = n[s] p[d] = s p[s] = t1 n[s] == 0 || (p[n[s]] = t2) n[s] = d t1 == 0 || (n[t1] = s) t2 == 0 || (n[t2] = t3) end function sortneighbors(a, pred) n = collect(2:length(a)+1); n[end] = 0 p = collect(0:length(a)-1); p[1] = 0 last = 1 while last != 0 cand = n[last] while cand != 0 pred(a[last], a[cand]) && break cand = n[cand] end cand == 0 && break move_after!(p, n, cand, last) last = cand end first = 1 while last != 0 cand = n[last] while cand != 0 pred(a[cand], a[first]) && break cand = n[cand] end cand == 0 && break move_before!(p, n, cand, first) first = cand end b = similar(a) i, j = last, length(n) while true b[j] = a[i] i = p[i] i == 0 && break j -= 1 end return b end isclosed(a, pred) = length(a)>2 && pred(a[end], a[1]) """ buffachristiansen(Γ, γ) Construct the set of Buffa-Christiansen functions subject to mesh Γ and only enforcing zero normal components on ∂Γ ∖ γ. """ function buffachristiansen(Γ, γ=mesh(coordtype(Γ),1,3); ibscaled=false, sort=:spacefillingcurve, edges=:all) @assert CompScienceMeshes.isoriented(Γ) T = coordtype(Γ) P = vertextype(Γ) in_interior = interior_tpredicate(Γ) on_junction = overlap_gpredicate(γ) # edges = skeleton(Γ, 1; sort) if edges == :all edges = skeleton(Γ, 1; sort) edges = submesh(edges) do edges, edge ch = chart(edges, edge) !in_interior(edges, edge) && !on_junction(ch) && return false return true end end @assert edges isa CompScienceMeshes.AbstractMesh @assert dimension(edges) == 1 fine = if ibscaled CompScienceMeshes.lineofsight_refinement(Γ) else barycentric_refinement(Γ; sort) end # # first pass to determine the number of functions # numfuncs = 0 # for edge in edges # ch = chart(edges, edge) # !in_interior(edge) && !on_junction(ch) && continue # numfuncs += 1 # end vtof, vton = vertextocellmap(fine) jct_pred = overlap_gpredicate(γ) bcs, k = Vector{Vector{Shape{T}}}(undef,length(edges)), 1 pos = Vector{P}(undef,length(edges)) for (i,e) in enumerate(edges) edge = CompScienceMeshes.indices(edges,e) ch = chart(edges, e) ln = volume(ch) # !in_interior(edge) && !on_junction(ch) && continue # index of edge center in fine's vertexbuffer v = edge[1] n = vton[v] F = vtof[v,1:n] supp = fine[F] bnd = boundary(supp) bnd_nodes = skeleton(bnd,0) p = 0 for bn in bnd_nodes node = CompScienceMeshes.indices(bnd_nodes, bn) vert1 = vertices(Γ)[edge[1]] vert2 = vertices(Γ)[edge[2]] vert = vertices(fine)[node[1]] dist = norm(vert-vert1) node[1] == edge[1] && continue if dot(vert-vert1,vert2-vert1) ≈ dist*ln p = node[1] break end end @assert p != 0 # p = numvertices(edges) + i pos[k] = vertices(fine)[p] # sanity check edge_ctr = cartesian(center(ch)) fine_vtx = vertices(fine)[p] @assert all(carttobary(ch, edge_ctr) .≥ 0) @assert norm(cross(edge_ctr - ch.vertices[1], fine_vtx - ch.vertices[1])) ≤ 1e-8 v = edge[1] n = vton[v] F = vec(vtof[v,1:n]) supp = cells(fine)[F] bc1 = buildhalfbc(fine, F, v, p, jct_pred, ibscaled) v = edge[2] n = vton[v] F = vec(vtof[v,1:n]) supp = cells(fine)[F] bc2 = buildhalfbc(fine, F, v, p, jct_pred, ibscaled) bc2 = Shape{T}[Shape(s.cellid, s.refid, -s.coeff) for s in bc2] bcs[k] = [bc1; bc2] k += 1 end return RTBasis(fine, bcs, pos) end """ buildhalfbc(fine, supp::Array{SVector{3,Int},1}, v, p) """ function buildhalfbc(fine, S, v, p, onjunction, ibscaled) T = coordtype(fine) @assert v != 0 @assert p != 0 @assert length(S) >= 2 @assert mod(length(S), 2) == 0 @assert all(0 .< S .<= numcells(fine)) @assert all([v in cells(fine)[s] for s in S]) bf = Shape{T}[] n = length(S) N = n ÷ 2 modn(i) = mod1(i,n) # sort the fine faces making up the domain share_edge(i,j) = length(intersect(cells(fine)[i],cells(fine)[j])) == 2 S = sortneighbors(S, share_edge) @assert all(0 .< S .<= numcells(fine)) port_faces = findall(i -> p in cells(fine)[i], S) port_edges = [something(findfirst(isequal(v), cells(fine)[S[i]]),0) for i in port_faces] c_on_boundary = !share_edge(S[end], S[1]) || length(S) == 2 e_on_boundary = length(port_faces) == 1 @assert c_on_boundary || !e_on_boundary # if there are two ports (c must be interior), we want to iterate # the support starting with one and ending with the other. This # might require reordering the ports we just discovered. if !e_on_boundary @assert length(port_faces) == 2 "$port_faces, $n" if port_faces[2] == modn(port_faces[1]+1) reverse!(port_faces) reverse!(port_edges) end @assert port_faces[1] == modn(port_faces[2]+1) end port_lengths = [begin face = cells(fine)[S[j]] v1 = vertices(fine)[face[mod1(i+1,3)]] v2 = vertices(fine)[face[mod1(i+2,3)]] norm(v2-v1) end for (j,i) in zip(port_faces, port_edges)] num_ports = length(port_faces) port_fluxes = if ibscaled total_length = sum(port_lengths) port_lengths / total_length else ones(T,num_ports) / num_ports end @assert sum(port_fluxes) ≈ 1 @assert length(port_faces) < 3 # Detect the boundary edges bnd_faces = Int[] bnd_edges = Int[] if c_on_boundary bnd_faces = [1,n] p1 = x -> x in cells(fine)[S[2]] && x != v p2 = x -> x in cells(fine)[S[n-1]] && x != v e1 = findfirst(p1, cells(fine)[S[1]]) e2 = findfirst(p2, cells(fine)[S[n]]) bnd_edges = [e1, e2] end # Detect the junction edges num_junctions = 0 jct_idxes = Int[] if c_on_boundary for i in 1:length(bnd_faces) f, e = bnd_faces[i], bnd_edges[i] a = vertices(fine)[cells(fine)[S[f]][mod1(e+1,3)]] b = vertices(fine)[cells(fine)[S[f]][mod1(e+2,3)]] seg = simplex(a,b) if onjunction(seg) push!(jct_idxes, i) #push!(jct_edges, e) end end num_junctions = length(jct_idxes) end # This charge needs to be compensated by interior divergence total_charge = (!c_on_boundary || num_junctions == 2) ? 1 : 0 charges = if ibscaled face_areas = [volume(chart(fine, s)) for s in S] face_areas / sum(face_areas) else fill(total_charge/n, n) end @assert sum(charges) ≈ 1 || isapprox(sum(charges), 0, atol=1e-8) # add the port contributions for (f, e, w) in zip(port_faces, port_edges, port_fluxes) add!(bf, S[f], e, w) charges[f] -= w end bnd_fluxes = T[] if c_on_boundary if num_junctions == 0 ibscaled && error("IB scaled BCs for mesh with boundary not implemented!") bnd_fluxes = T[-(n-port_faces[2])/n, -port_faces[2]/n] elseif num_junctions == 1 bnd_fluxes = -ones(T,2) bnd_fluxes[jct_idxes[1]] = 0 else bnd_fluxes = zeros(T,2) end end @assert length(bnd_faces) == length(bnd_edges) == length(bnd_fluxes) for (f, e, w) in zip(bnd_faces, bnd_edges, bnd_fluxes) add!(bf, S[f], e, w) charges[f] -= w end # The remaining fluxes can be computed based on port and boundary # influx, and the knowledge of the charge density by recursion. # Iterate beginning with port 0: start_face = c_on_boundary ? 1 : port_faces[1] for i in 1 : n-1 # cyclic port_face[1]-based indexing j0 = modn(i + start_face - 1) j1 = modn(j0+1) # get the indices of the faces in fine.faces f0, f1 = S[j0], S[j1] # what are the local indices of the common edge? e0, e1 = getcommonedge(cells(fine)[f0], cells(fine)[f1]) # add the two half Raviart-Thomas shape functions add!(bf, S[j0], abs(e0), +charges[j0]) add!(bf, S[j1], abs(e1), -charges[j0]) # update the charge bookkeeping charges[j1] += charges[j0] end # Add a multiple of the zero-divergence pattern such that the result # is orthogonal to the zero-divergence pattern if ibscaled β = zero(T) for shape in bf f = shape.cellid @assert f in S face = cells(fine)[f] i = something(findfirst(==(v),face), 0) @assert i != 0 ch = chart(fine, f) area = volume(ch) qps = quadpoints(ch, 3) @assert sum(w for (p,w) in qps) ≈ area for (p,w) in qps vals = RTRefSpace{T}()(p) bfp = shape.coeff * vals[shape.refid].value i1 = mod1(i+1,3) i2 = mod1(i+2,3) dfp = 0.5/area * (ch.vertices[i2] - ch.vertices[i1]) @assert dfp ≈ vals[i1].value - vals[i2].value β += w * dot(bfp, dfp) end end γ = zero(T) for f in S face = cells(fine)[f] i = something(findfirst(==(v), face), 0) @assert i != 0 ch = chart(fine, f) area = volume(ch) vct = ch.vertices[mod1(i+2,3)] - ch.vertices[mod1(i+1,3)] γ += 0.25/area * dot(vct,vct) end α = -β/γ for f in S face = cells(fine)[f] i = something(findfirst(==(v), face), 0) @assert i != 0 add!(bf, f, mod1(i+1,3), α) add!(bf, f, mod1(i+2,3), -α) end β = zero(T) for shape in bf f = shape.cellid @assert f in S face = cells(fine)[f] i = something(findfirst(==(v),face), 0) @assert i != 0 ch = chart(fine, f) area = volume(ch) qps = quadpoints(ch, 3) @assert sum(w for (p,w) in qps) ≈ area for (p,w) in qps vals = RTRefSpace{T}()(p) bfp = shape.coeff * vals[shape.refid].value i1 = mod1(i+1,3) i2 = mod1(i+2,3) dfp = 0.5/area * (ch.vertices[i2] - ch.vertices[i1]) @assert dfp ≈ vals[i1].value - vals[i2].value β += w * dot(bfp, dfp) end end @assert isapprox(β,0, atol=1e-8) end return bf end using LinearAlgebra function buildhalfbc2(patch, port, dirichlet, prt_fluxes) # println() edges = skeleton(patch,1) verts = skeleton(patch,0) bndry = boundary(patch) in_bndry = in(bndry) dirbnd = submesh(dirichlet) do m,edge in_bndry(m,edge) # edge in cells(bndry) && return true # reverse(edge) in cells(bndry) && return true # return false end # @show numcells(patch) # @show numcells(dirbnd) @assert numcells(dirbnd) ≤ 4 bnd_dirbnd = boundary(dirbnd) nodes_dirbnd = skeleton(dirbnd,0) in_bnd_dirbnd = in(bnd_dirbnd) int_nodes_dirbnd = submesh(nodes_dirbnd) do m,node # node in cells(bnd_dirbnd) && return false # return true return !in_bnd_dirbnd(m, node) end # @show numcells(int_nodes_dirbnd) @assert numcells(int_nodes_dirbnd) ≤ 2 int_pred = interior_tpredicate(patch) num_edges_on_port = 0 num_edges_on_dirc = 0 # @show numcells(edges) # for edge in cells(edges) # println(edge) # end # println() # for edge in cells(dirbnd) # println(edge) # end # println() # for edge in cells(port) # println(edge) # end in_port = in(port) in_dirbnd = in(dirbnd) int_edges = submesh(edges) do m,edge in_port(m,edge) && (num_edges_on_port+=1; return false) in_dirbnd(m,edge) && (num_edges_on_dirc+=1; return true) !int_pred(m,edge) && return false return true # (edge in cells(port)) && (num_edges_on_port+=1 ; return false) # (reverse(edge) in cells(port)) && (num_edges_on_port+=1 ; return false) # edge in cells(dirbnd) && (num_edges_on_dirc+=1; return true) # reverse(edge) in cells(dirbnd) && (num_edges_on_dirc+=1; return true) # (!int_pred(edge)) && return false # return true end # println() # for edge in cells(int_edges) # println(edge) # end # @show numcells(int_edges) # @show num_edges_on_port # @show num_edges_on_dirc bnd_verts = skeleton(bndry,0) prt_verts = skeleton(port,0) # function isonboundary(node) # node in cells(bnd_verts) # end # int_verts = submesh(!isonboundary, verts) # dirichlet_nodes = skeleton(dirichlet,0) in_int_nodes_dirbnd = in(int_nodes_dirbnd) in_bnd_verts = in(bnd_verts) in_prt_verts = in(prt_verts) int_verts = submesh(verts) do m,node in_int_nodes_dirbnd(m,node) && return true in_bnd_verts(m,node) && return false in_prt_verts(m,node) && return false return true # node in cells(int_nodes_dirbnd) && return true # node in cells(bnd_verts) && return false # node in cells(prt_verts) && return false # return true end # @show numcells(int_verts) RT_int = raviartthomas(patch, cellpairs(patch, int_edges)) RT_prt = raviartthomas(patch, cellpairs(patch, port)) vertex_list = [c[1] for c in cells(int_verts)] L0_int = lagrangec0d1(patch, vertex_list, Val{3}) Id = BEAST.Identity() D = assemble(Id, divergence(RT_int), divergence(RT_int)) Q = assemble(Id, divergence(RT_int), divergence(RT_prt)) d = -Q * prt_fluxes # @show numfunctions(L0_int) @assert numfunctions(L0_int) in [1,2] C = assemble(Id, curl(L0_int), RT_int) curl_L0_int = curl(L0_int) c = real(assemble(Id, curl_L0_int, RT_prt)) * prt_fluxes mD = Matrix(D) x1 = pinv(mD) * d N = nullspace(mD) # @show size(N) # @show size(C) p = (C*N) \ (c - C*x1) x = x1 + N*p @assert D*x ≈ d atol=1e-8 if !isapprox(C*x, c, atol=1e-8) @show norm(C*x-c) error("error") end return RT_int, RT_prt, x, prt_fluxes end # Use the algebraic construction also used in dual3d function buffachristiansen2(Faces::CompScienceMeshes.AbstractMesh{U,D1,T}) where {U,D1,T} faces = barycentric_refinement(Faces) Edges = skeleton(Faces,1) Bndry = boundary(Faces) inBndry = in(Bndry) Edges = submesh(Edges) do m,Edge return !inBndry(m,Edge) # Edge in cells(Bndry) && return false # reverse(Edge) in cells(Bndry) && return false # return true end #T = Float64 bfs = Vector{Vector{Shape{T}}}(undef, numcells(Edges)) pos = Vector{vertextype(Faces)}(undef, numcells(Edges)) dirichlet = boundary(faces) for (E,Edge) in enumerate(Edges) EdgeInds = CompScienceMeshes.indices(Edges, Edge) # @show Edge bfs[E] = Vector{Shape{T}}() pos[E] = cartesian(center(chart(Edges,Edge))) # port_vertex_idx = numvertices(Faces) + E port_vertex_idx = argmin(norm.(vertices(faces) .- Ref(pos[E]))) # pos[E] = vertices(faces)[port_vertex_idx] # @show carttobary(chart(Edges,Edge),pos[E]) # @show pos[E] # @show (Faces.vertices[Edge[1]]+Faces.vertices[Edge[2]])/2 # Build the plus-patch ptch_vert_idx = EdgeInds[1] ptch_face_idcs = [i for (i,face) in enumerate(cells(faces)) if ptch_vert_idx in face] patch = Mesh(vertices(faces), cells(faces)[ptch_face_idcs]) patch_bnd = boundary(patch) # @show numcells(patch_bnd) port = Mesh(vertices(faces), filter(c->port_vertex_idx in c, cells(patch_bnd))) # @show numcells(patch) # @show numcells(port) # @assert numcells(patch) >= 6 @assert numcells(port) == 2 prt_fluxes = [0.5, 0.5] RT_int, RT_prt, x_int, x_prt = buildhalfbc2(patch, port, dirichlet, prt_fluxes) for (m,bf) in enumerate(RT_int.fns) for sh in bf cellid = ptch_face_idcs[sh.cellid] BEAST.add!(bfs[E], cellid, sh.refid, sh.coeff * x_int[m]) end end for (m,bf) in enumerate(RT_prt.fns) for sh in bf cellid = ptch_face_idcs[sh.cellid] BEAST.add!(bfs[E],cellid, sh.refid, sh.coeff * x_prt[m]) end end # Build the minus-patch ptch_vert_idx = EdgeInds[2] ptch_face_idcs = [i for (i,face) in enumerate((faces)) if ptch_vert_idx in CompScienceMeshes.indices(faces, face)] patch = Mesh(vertices(faces), cells(faces)[ptch_face_idcs]) port = Mesh(vertices(faces), filter(c->port_vertex_idx in c, cells(boundary(patch)))) # @assert numcells(patch) >= 6 @assert numcells(port) == 2 prt_fluxes = [-0.5, -0.5] RT_int, RT_prt, x_int, x_prt = buildhalfbc2(patch, port, dirichlet, prt_fluxes) for (m,bf) in enumerate(RT_int.fns) for sh in bf cellid = ptch_face_idcs[sh.cellid] BEAST.add!(bfs[E], cellid, sh.refid, sh.coeff * x_int[m]) end end for (m,bf) in enumerate(RT_prt.fns) for sh in bf cellid = ptch_face_idcs[sh.cellid] BEAST.add!(bfs[E],cellid, sh.refid, sh.coeff * x_prt[m]) end end end RTBasis(faces, bfs, pos) end # Extend into both dual faces in a single call to buildhalfbc2 (aka extend_2_form) function buffachristiansen3(Faces::CompScienceMeshes.AbstractMesh{U,D1,T}) where {U,D1,T} faces = barycentric_refinement(Faces) Edges = skeleton(Faces,1) Bndry = boundary(Faces) inBndry = in(Bndry) Edges = submesh(Edges) do m,Edge inBndry(m,Edge) && return false # reverse(Edge) in cells(Bndry) && return false return true end #T = Float64 bfs = Vector{Vector{Shape{T}}}(undef, numcells(Edges)) pos = Vector{vertextype(Faces)}(undef, numcells(Edges)) dirichlet = boundary(faces) for (E,Edge) in enumerate(Edges) bfs[E] = Vector{Shape{T}}() # port_vertex_idx = numvertices(Faces) + E # pos[E] = vertices(faces)[port_vertex_idx] pos[E] = cartesian(center(chart(Edges,Edge))) # port_vertex_idx = numvertices(Faces) + E port_vertex_idx = argmin(norm.(vertices(faces) .- Ref(pos[E]))) # Build the dual support EdgeInds = CompScienceMeshes.indices(Edges, Edge) ptch_face_idcs1 = [i for (i,face) in enumerate(faces) if EdgeInds[1] in CompScienceMeshes.indices(faces,face)] ptch_face_idcs2 = [i for (i,face) in enumerate(faces) if EdgeInds[2] in CompScienceMeshes.indices(faces,face)] patch1 = Mesh(vertices(faces), cells(faces)[ptch_face_idcs1]) patch2 = Mesh(vertices(faces), cells(faces)[ptch_face_idcs2]) patch_bnd = boundary(patch1) port = Mesh(vertices(faces), filter(c->port_vertex_idx in c, cells(patch_bnd))) patch = CompScienceMeshes.union(patch1, patch2) # @show numcells(patch_bnd) # @show numcells(patch) # @show numcells(port) # @assert numcells(skeleton(patch,1))+2 == numcells(skeleton(patch1,1)) + numcells(skeleton(patch2,1)) @assert numcells(patch) >= 6 @assert numcells(port) == 2 prt_fluxes = [0.5, -0.5] RT_int, RT_prt, x_int, x_prt = buildhalfbc2(patch, port, dirichlet, prt_fluxes) ptch_face_idcs = vcat(ptch_face_idcs1, ptch_face_idcs2) for (m,bf) in enumerate(RT_int.fns) for sh in bf cellid = ptch_face_idcs[sh.cellid] BEAST.add!(bfs[E], cellid, sh.refid, sh.coeff * x_int[m]) end end for (m,bf) in enumerate(RT_prt.fns) for sh in bf cellid = ptch_face_idcs[sh.cellid] BEAST.add!(bfs[E],cellid, sh.refid, sh.coeff * x_prt[m]) end end # # Build the minus-patch # ptch_vert_idx = Edge[2] # ptch_face_idcs = [i for (i,face) in enumerate(cells(faces)) if ptch_vert_idx in face] # patch = Mesh(vertices(faces), cells(faces)[ptch_face_idcs]) # port = Mesh(vertices(faces), filter(c->port_vertex_idx in c, cells(boundary(patch)))) # @assert numcells(patch) >= 6 # @assert numcells(port) == 2 # RT_int, RT_prt, x_int, x_prt = buildhalfbc2(patch, port, nothing) # for (m,bf) in enumerate(RT_int.fns) # for sh in bf # cellid = ptch_face_idcs[sh.cellid] # BEAST.add!(bfs[E], cellid, sh.refid, -1.0 * sh.coeff * x_int[m]) # end # end # for (m,bf) in enumerate(RT_prt.fns) # for sh in bf # cellid = ptch_face_idcs[sh.cellid] # BEAST.add!(bfs[E],cellid, sh.refid, -1.0 * sh.coeff * x_prt[m]) # end # end end RTBasis(faces, bfs, pos) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
3948
mutable struct BDM3DBasis{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end refspace(s::BDM3DBasis{T}) where {T} = BDM3DRefSpace{T}() function brezzidouglasmarini3d(mesh, faces) T = coordtype(mesh) P = vertextype(mesh) num_faces = numcells(faces) C = connectivity(faces, mesh, identity) #println(C) rows = rowvals(C) vals = nonzeros(C) #println(rows) fns = Vector{Vector{Shape{T}}}(undef, 3*num_faces) pos = Vector{P}(undef, 3*num_faces) #println(cells(faces)) for (i,face) in enumerate(faces) fns[3*(i-1)+1] = Vector{Shape{T}}() fns[3*(i-1)+2] = Vector{Shape{T}}() fns[3*(i-1)+3] = Vector{Shape{T}}() pos[3*(i-1)+1] = cartesian(center(chart(faces,face))) pos[3*(i-1)+2] = cartesian(center(chart(faces,face))) pos[3*(i-1)+3] = cartesian(center(chart(faces,face))) #println( cartesian(center(chart(faces,face)))) #println(face) # add shape function for each cell to the basis for k in nzrange(C,i) #Cell index j = rows[k] #face index (sign gives local orientation) s = vals[k] cell = cells(mesh)[j] #local face index lf = abs(s); #local vertex index lv1 = mod1(lf+1,4) lv2 = mod1(lf+2,4) lv3 = mod1(lf+3,4) #println("\t",lv1," ",lv2," ",lv3) #println("\t=>",cell[lv1]," ",cell[lv2]," ",cell[lv3]) #global vertex index gv1 = cell[lv1] gv2 = cell[lv2] gv3 = cell[lv3] if (gv1 < gv2) && (gv2 < gv3) push!(fns[3*(i-1)+1], Shape{T}(j, 3*(abs(s)-1)+1, sign(s))) push!(fns[3*(i-1)+2], Shape{T}(j, 3*(abs(s)-1)+2, sign(s))) push!(fns[3*(i-1)+3], Shape{T}(j, 3*(abs(s)-1)+3, sign(s))) #println("Case 1") elseif (gv1 < gv3) && (gv3 < gv2) push!(fns[3*(i-1)+1], Shape{T}(j, 3*(abs(s)-1)+1, sign(s))) push!(fns[3*(i-1)+2], Shape{T}(j, 3*(abs(s)-1)+3, sign(s))) push!(fns[3*(i-1)+3], Shape{T}(j, 3*(abs(s)-1)+2, sign(s))) #println("Case 2") elseif (gv2 < gv1) && (gv1 < gv3) push!(fns[3*(i-1)+1], Shape{T}(j, 3*(abs(s)-1)+2, sign(s))) push!(fns[3*(i-1)+2], Shape{T}(j, 3*(abs(s)-1)+1, sign(s))) push!(fns[3*(i-1)+3], Shape{T}(j, 3*(abs(s)-1)+3, sign(s))) #println("Case 3") elseif (gv2 < gv3) && (gv3 < gv1) push!(fns[3*(i-1)+1], Shape{T}(j, 3*(abs(s)-1)+2, sign(s))) push!(fns[3*(i-1)+2], Shape{T}(j, 3*(abs(s)-1)+3, sign(s))) push!(fns[3*(i-1)+3], Shape{T}(j, 3*(abs(s)-1)+1, sign(s))) #println("Case 4") elseif (gv3 < gv2) && (gv2 < gv1) push!(fns[3*(i-1)+1], Shape{T}(j, 3*(abs(s)-1)+3, sign(s))) push!(fns[3*(i-1)+2], Shape{T}(j, 3*(abs(s)-1)+2, sign(s))) push!(fns[3*(i-1)+3], Shape{T}(j, 3*(abs(s)-1)+1, sign(s))) #println("Case 5") elseif (gv3 < gv1) && (gv1 < gv2) push!(fns[3*(i-1)+1], Shape{T}(j, 3*(abs(s)-1)+3, sign(s))) push!(fns[3*(i-1)+2], Shape{T}(j, 3*(abs(s)-1)+1, sign(s))) push!(fns[3*(i-1)+3], Shape{T}(j, 3*(abs(s)-1)+2, sign(s))) #println("Case 6") end #println(s) #push!(fns[3*(i-1)+1], Shape{T}(j, 3*(abs(s)-1)+1, sign(s))) #push!(fns[3*(i-1)+2], Shape{T}(j, 3*(abs(s)-1)+2, sign(s))) #push!(fns[3*(i-1)+3], Shape{T}(j, 3*(abs(s)-1)+3, sign(s))) end end BDM3DBasis(mesh, fns, pos) end function brezzidouglasmarini3d(mesh) faces = skeleton(mesh, 2) brezzidouglasmarini3d(mesh, faces) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1607
struct BDMBasis{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end BDMBasis(geo, fns) = BDMBasis(geo, fns, Vector{vertextype(geo)}(undef,length(fns))) refspace(s::BDMBasis{T}) where {T} = BDMRefSpace{T}() subset(s::BDMBasis,I) = BDMBasis(s.geo, s.fns[I], s.pos[I]) function brezzidouglasmarini(mesh) edges = skeleton(mesh, 1) cps = cellpairs(mesh, edges, dropjunctionpair=true) ids = findall(x -> x>0, cps[2,:]) brezzidouglasmarini(mesh, cps[:,ids]) end function brezzidouglasmarini(mesh, cellpairs::Array{Int,2}) @warn "brezzidouglasmarini(mesh, cellpairs) assumes mesh is oriented" @assert size(cellpairs,1) == 2 T = coordtype(mesh) P = vertextype(mesh) S = Shape{T} F = Vector{Shape{T}} nf = 2*size(cellpairs,2) fns = Vector{F}(undef, nf) pos = Vector{P}(undef, nf) for i in axes(cellpairs)[2] c1, c2 = cellpairs[:,i] cell1 = cells(mesh)[c1] cell2 = cells(mesh)[c2] e1, e2 = getcommonedge(cell1, cell2) @assert e1*e2 < 0 e1, e2 = abs(e1), abs(e2) fns[2*(i-1)+1] = [ S(c1, 2*(e1-1)+1 ,+1.0), S(c2, 2*(e2-1)+2,-1.0)] fns[2*(i-1)+2] = [ S(c1, 2*(e1-1)+2 ,+1.0), S(c2, 2*(e2-1)+1,-1.0)] v1 = cell1[mod1(e1+1,3)] v2 = cell1[mod1(e1+2,3)] edge = simplex(mesh.vertices[[v1,v2]]...) cntr = cartesian(center(edge)) pos[2*(i-1)+1] = cntr pos[2*(i-1)+2] = cntr end BDMBasis(mesh, fns, pos) end divergence(X::BDMBasis, geo, fns) = LagrangeBasis{0,-1,1}(geo, fns, deepcopy(positions(X)))
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1489
export divergence function divergence(X::DirectProductSpace{T}) where T x = Space{T}[divergence(s) for s in X.factors] DirectProductSpace(x) end """ divergence(x) Compute the divergence of a finite element space. """ function divergence(x::Space) ref = refspace(x) geo = geometry(x) els = elements(geo) fns = x.fns dvs = similar(fns) for (i,fn) in enumerate(fns) dvs[i] = similar(fns[i]) for (j,sh) in enumerate(fn) el = els[sh.cellid] dvs[i][j] = divergence(ref, sh, el) end end divergence(x, geo, dvs) end """ curl(X) Compute the curl of a finite element basis. The resulting set of functions might be linearly dependent because of the kernel of the curl operator. """ function curl(x::Space) ref = refspace(x) geo = geometry(x) els = elements(geo) crl = similar(x.fns) for (i,fn) in enumerate(x.fns) crl[i] = similar(x.fns[i], 0) for (j,sh) in enumerate(fn) el = els[sh.cellid] append!(crl[i], curl(ref, sh, el)) end end curl(x, geo, crl) end function gradient(x::Space) ref = refspace(x) geo = geometry(x) els = elements(geo) crl = similar(x.fns) for (i,fn) in enumerate(x.fns) crl[i] = similar(x.fns[i], 0) for (j,sh) in enumerate(fn) el = els[sh.cellid] append!(crl[i], gradient(ref, sh, el)) end end gradient(x, geo, crl) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
9195
using LinearAlgebra # function addf!(fn::Vector{<:Shape}, x::Vector, space::Space, idcs::Vector{Int}) # 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 dual2forms_body(Edges, tetrs, bnd, dir, v2t, v2n) T = coordtype(tetrs) bfs = Vector{Vector{Shape{T}}}(undef, numcells(Edges)) pos = Vector{vertextype(Edges)}(undef, numcells(Edges)) Cells = cells(Edges) num_threads = Threads.nthreads() Threads.@threads for F in eachindex(Cells) Edge = Cells[F] myid = Threads.threadid() myid == 1 && (F % 20 == 0) && println("Constructing dual 2-forms: $(F*num_threads) out of $(length(Edges)).") idcs1 = v2t[Edge[1],1:v2n[Edge[1]]] idcs2 = v2t[Edge[2],1:v2n[Edge[2]]] supp1 = tetrs.mesh[idcs1] supp2 = tetrs.mesh[idcs2] bnd_supp1 = boundary(supp1) bnd_supp2 = boundary(supp2) dir1_faces = submesh(in(dir), bnd_supp1) dir2_faces = submesh(in(dir), bnd_supp2) port_faces = bnd_supp1 port_faces = submesh(in(bnd_supp2), port_faces) x0 = zeros(length(port_faces)) total_vol = sum(volume(chart(port_faces, fc)) for fc in port_faces) tgt = tangents(center(chart(Edges, F)),1) for (i,face) in enumerate(port_faces) chrt = chart(port_faces, face) nrm = normal(chrt) vol = volume(chrt) sgn = sign(dot(nrm, tgt)) x0[i] = sgn * vol / total_vol end RT1_prt = BEAST.raviartthomas(supp1, port_faces) RT2_prt = BEAST.raviartthomas(supp2, port_faces) x1_int, _, RT1_int = extend_2_form(supp1, dir1_faces, x0, port_faces) x2_int, _, RT2_int = extend_2_form(supp2, dir2_faces, x0, port_faces) bfs[F] = Vector{Shape{T}}() pos[F] = cartesian(center(chart(Edges,F))) addf!(bfs[F], x1_int, RT1_int, idcs1) addf!(bfs[F], x0, RT1_prt, idcs1) addf!(bfs[F], x2_int, RT2_int, idcs2) addf!(bfs[F], x0, RT2_prt, idcs2) end NDLCDBasis(tetrs, bfs, pos) end function extend_1_form(supp, dirichlet, x_prt, port_edges) Id = BEAST.Identity() bnd_supp = boundary(supp) supp_edges = CompScienceMeshes.skeleton_fast(supp, 1) supp_nodes = CompScienceMeshes.skeleton_fast(supp, 0) dir_compl = submesh(!in(dirichlet), bnd_supp) dir_compl_edges = CompScienceMeshes.skeleton_fast(dir_compl, 1) dir_compl_nodes = CompScienceMeshes.skeleton_fast(dir_compl, 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) curl_Nd_prt = curl(Nd_prt) curl_Nd_int = curl(Nd_int) A = assemble(Id, curl_Nd_int, curl_Nd_int, threading=Threading{:single}) a = -assemble(Id, curl_Nd_int, curl_Nd_prt, threading=Threading{:single}) * x_prt if length(int_nodes) > 0 Lg_int = BEAST.lagrangec0d1(supp, int_nodes) grad_Lg_int = gradient(Lg_int) B = assemble(Id, grad_Lg_int, Nd_int, threading=Threading{:single}) b = -assemble(Id, grad_Lg_int, Nd_prt, threading=Threading{:single}) * x_prt Z = zeros(eltype(b), length(b), length(b)) S = [A B'; B Z] u = S \ [a;b] else u = A \ a end x_int = u[1:numfunctions(Nd_int)] return x_int, int_edges, Nd_int end function extend_2_form(supp, dirichlet, x_prt, port_faces) Id = BEAST.Identity() bnd_supp = boundary(supp) supp_faces = CompScienceMeshes.skeleton_fast(supp, 2) supp_edges = CompScienceMeshes.skeleton_fast(supp, 1) supp_nodes = CompScienceMeshes.skeleton_fast(supp, 0) dir_compl = submesh(!in(dirichlet), bnd_supp) dir_compl_faces = CompScienceMeshes.skeleton_fast(dir_compl, 2) dir_compl_edges = CompScienceMeshes.skeleton_fast(dir_compl, 1) dir_compl_nodes = CompScienceMeshes.skeleton_fast(dir_compl, 0) int_faces = submesh(!in(dir_compl_faces), supp_faces) int_edges = submesh(!in(dir_compl_edges), supp_edges) int_nodes = submesh(!in(dir_compl_nodes), supp_nodes) if length(int_nodes) > 0 @assert length(int_nodes) == 1 int_edges = int_edges[collect(1:length(int_edges)-length(int_nodes))] end RT_prt = BEAST.raviartthomas(supp, port_faces) RT_int = BEAST.raviartthomas(supp, int_faces) Nd_int = BEAST.nedelec(supp, int_edges) div_RT_prt = divergence(RT_prt) div_RT_int = divergence(RT_int) curl_Nd_int = curl(Nd_int) A = assemble(Id, div_RT_int, div_RT_int) B = assemble(Id, curl_Nd_int, RT_int) a = -assemble(Id, div_RT_int, div_RT_prt) * x_prt b = -assemble(Id, curl_Nd_int, RT_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_faces, RT_int end function dual1forms(Tetrs, Faces, Dir) tetrs, bnd, dir, v2t, v2n = dualforms_init(Tetrs, Dir) dual1forms_body(Faces, tetrs, bnd, dir, v2t, v2n) end function dual2forms(Tetrs, Faces, Dir) tetrs, bnd, dir, v2t, v2n = dualforms_init(Tetrs, Dir) dual2forms_body(Faces, tetrs, bnd, dir, v2t, v2n) end function dual1forms_body(Faces, tetrs, bnd, dir, v2t, v2n) @assert dimension(Faces) == 2 T = coordtype(tetrs) bfs = Vector{Vector{Shape{T}}}(undef, length(Faces)) pos = Vector{vertextype(Faces)}(undef, length(Faces)) Cells = cells(Faces) num_threads = Threads.nthreads() Threads.@threads for F in 1:length(Faces) Face = Cells[F] Chart = chart(Faces, F) myid = Threads.threadid() myid == 1 && F % 20 == 0 && println("Constructing dual 1-forms: $(F*num_threads) out of $(length(Faces)).") 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] bnd_supp1 = boundary(supp1) bnd_supp2 = boundary(supp2) bnd_supp3 = boundary(supp3) dir1_faces = submesh(in(dir), bnd_supp1) dir2_faces = submesh(in(dir), bnd_supp2) dir3_faces = submesh(in(dir), bnd_supp3) bnd_dir1 = boundary(dir1_faces) bnd_dir2 = boundary(dir2_faces) bnd_dir3 = boundary(dir3_faces) supp23 = submesh(in(bnd_supp2), bnd_supp3) supp31 = submesh(in(bnd_supp3), bnd_supp1) supp12 = submesh(in(bnd_supp1), bnd_supp2) dir23_edges = submesh(in(bnd_dir2), bnd_dir3) dir31_edges = submesh(in(bnd_dir3), bnd_dir1) dir12_edges = submesh(in(bnd_dir1), bnd_dir2) 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 = zeros(length(port_edges)) total_vol = sum(volume(chart(port_edges, edge)) for edge in port_edges) nrm = normal(Chart) for (i,edge) in enumerate(port_edges) cht = chart(port_edges, edge) tgt = tangents(center(cht),1) vol = volume(cht) sgn = sign(dot(nrm, tgt)) x0[i] = sgn * vol / total_vol end x23, supp23_int_edges, _ = extend_1_form(supp23, dir23_edges, x0, port_edges) x31, supp31_int_edges, _ = extend_1_form(supp31, dir31_edges, x0, port_edges) x12, supp12_int_edges, _ = extend_1_form(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.nedelec(supp1, port1_edges) Nd2_prt = BEAST.nedelec(supp2, port2_edges) Nd3_prt = BEAST.nedelec(supp3, port3_edges) x1_int, _, Nd1_int = extend_1_form(supp1, dir1_faces, x1_prt, port1_edges) x2_int, _, Nd2_int = extend_1_form(supp2, dir2_faces, x2_prt, port2_edges) x3_int, _, Nd3_int = extend_1_form(supp3, dir3_faces, x3_prt, port3_edges) # inject in the global space fn = BEAST.Shape{Float64}[] addf!(fn, x1_prt, Nd1_prt, idcs1) addf!(fn, x1_int, Nd1_int, idcs1) addf!(fn, x2_prt, Nd2_prt, idcs2) addf!(fn, x2_int, Nd2_int, idcs2) addf!(fn, x3_prt, Nd3_prt, idcs3) addf!(fn, x3_int, Nd3_int, idcs3) pos[F] = cartesian(CompScienceMeshes.center(Chart)) bfs[F] = fn end NDLCCBasis(tetrs, bfs, pos) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
27205
""" The dimension of the space of Lagrange shape functions of degree d over a simplex of dimension n is binom(n+d,d) == binom(n+d,n) """ function lagdimension end # D: degree # C: continuity # M: mesh type # T: field type # NF: number of local shape functions mutable struct LagrangeBasis{D,C,M,T,NF,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end # Constructor that automatically deduces MeshType and ScalarType but requires specification # of the Degree, Cont, and NumFns type parameters function LagrangeBasis{D,C,N}(mesh::M, fns::Vector{Vector{Shape{T}}}, pos::Vector{P}) where {P,T,M,N,C,D} LagrangeBasis{D,C,M,T,N,P}(mesh, fns, pos) end refspace(space::LagrangeBasis{D,C,M,T,NF}) where {D,C,M,T,NF} = LagrangeRefSpace{T,D,dimension(geometry(space))+1,NF}() subset(s::S,I) where {S <: Space} = S(s.geo, s.fns[I], s.pos[I]) function lagrangecxd0(mesh) U = universedimension(mesh) D1 = dimension(mesh)+1 T = coordtype(mesh) geometry = mesh num_cells = numcells(mesh) # create the local shapes fns = Vector{Vector{Shape{T}}}(undef,num_cells) pos = Vector{vertextype(mesh)}(undef,num_cells) for (i,cell) in enumerate(mesh) fns[i] = [Shape(i, 1, T(1.0))] pos[i] = cartesian(center(chart(mesh, cell))) end NF = 1 LagrangeBasis{0,-1,NF}(geometry, fns, pos) end """ unitfunctioncxd0(mesh) Constructs a constant function with value 1 on `mesh`. """ function unitfunctioncxd0(mesh) T = coordtype(mesh) geometry = mesh # create the local shapes fns = Vector{Vector{Shape{T}}}(undef, 1) pos = Vector{vertextype(mesh)}(undef, 1) fns[1] = [Shape(i, 1, T(1.0)) for (i, cell) in enumerate(mesh)] # Arguably, the position is fairly meaningless # in case of a global function. Might be replaced by something # more useful. # For now, we fill it with the average position of the shape functions p = vertextype(mesh)(0.0, 0.0, 0.0) for cell in mesh p += cartesian(center(chart(mesh, cell))) end pos[1] = p ./ numcells(mesh) NF = 1 LagrangeBasis{0,-1,NF}(geometry, fns, pos) end """ unitfunctionc0d1(mesh) Constructs a constant function with value 1 on `mesh` consisting of linear shapes. For dirichlet=true goes to zero on the boundary. """ function unitfunctionc0d1(mesh; dirichlet=true) if dirichlet == false return unitfunctionc0d1(mesh, skeleton(mesh,0)) else return unitfunctionc0d1_dirichlet(mesh) end end function unitfunctionc0d1_dirichlet(mesh) T = coordtype(mesh) verts = skeleton(mesh, 0) detached = trues(numvertices(mesh)) for v in cells(verts) detached[v] = false end bnd = boundary(mesh) bndverts = skeleton(bnd, 0) notonbnd = trues(numvertices(mesh)) for v in cells(bndverts) notonbnd[v] = false end vertexlist = findall(notonbnd .& .!detached) cellids, ncells = vertextocellmap(mesh) Cells = cells(mesh) Verts = vertices(mesh) # create the local shapes fns = Vector{Vector{Shape{T}}}(undef, 1) pos = Vector{vertextype(mesh)}(undef, 1) numshapes = sum(ncells[vertexlist]) shapes = Vector{Shape{T}}(undef,numshapes) n = 0 for v in vertexlist nshapes = ncells[v] nshapes == 0 && continue for s in 1: nshapes c = cellids[v,s] cell = Cells[c] localid = something(findfirst(isequal(v), cell),0) @assert localid != 0 shapes[s+n] = Shape(c, localid, T(1.0)) end n += nshapes end fns[1] = shapes p = sum(mesh.vertices[vertexlist])/length(vertexlist) pos[1] = p NF = 3 LagrangeBasis{1,0,NF}(mesh, fns, pos) end function unitfunctionc0d1(mesh, nodes::CompScienceMeshes.AbstractMesh{U,1} where {U}) Conn = connectivity(nodes, mesh, abs) rows = rowvals(Conn) vals = nonzeros(Conn) T = coordtype(mesh) P = vertextype(mesh) S = Shape{T} fns = Vector{Vector{Shape{T}}}(undef, 1) pos = Vector{vertextype(mesh)}(undef, 1) fn = Vector{S}() for (i,node) in enumerate(nodes) for k in nzrange(Conn,i) cellid = rows[k] refid = vals[k] push!(fn, Shape(cellid, refid, T(1.0))) end end fns[1] = fn p = sum(nodes.vertices)/length(nodes.vertices) pos[1] = p NF = dimension(mesh) + 1 LagrangeBasis{1,0,NF}(mesh, fns, pos) end """ lagrangec0d1(mesh[, bnd]) Construct the basis of continuous, piecewise linear basis functions subordinate to mesh `mesh`. Basis functions are constructed at vertices in the interionr of the mesh and on the closure of 'bnd'. In particular, leaving out the second argument creates a finite element space subject to homogeneous Dirichlet boundary conditions. """ function lagrangec0d1_dirichlet(mesh) verts = skeleton(mesh, 0) detached = trues(numvertices(mesh)) for v in cells(verts) detached[v] = false end bnd = boundary(mesh) bndverts = skeleton(bnd, 0) notonbnd = trues(numvertices(mesh)) for v in cells(bndverts) notonbnd[v] = false end vertexlist = findall(notonbnd .& .!detached) lagrangec0d1(mesh, vertexlist, Val{dimension(mesh)+1}) end function interior_and_junction_vertices(mesh, jct) verts = skeleton(mesh, 0) detached = trues(numvertices(mesh)) for v in cells(verts) detached[v] = false end bndfaces = boundary(mesh) bndverts = skeleton(bndfaces, 0) notonbnd = trues(numvertices(mesh)) for v in cells(bndverts) notonbnd[v] = false end onjct = broadcast(!, notonbnd) overlap_with_junction = overlap_gpredicate(jct) for indices in cells(bndfaces) bndface = simplex(vertices(bndfaces, indices)) if overlap_with_junction(bndface) continue else for v in indices onjct[v] = false end end end vertexlist = findall(broadcast(|, onjct, notonbnd) .& broadcast(!,detached)) end """ duallagrangecxd0(mesh, jct) -> basis Build dual Lagrange piecewise constant elements. Boundary nodes are only considered if they are in the interior of `jct`. The default dual function (`interpolatory=false`) is similar to the one depicted in Figure 3 of Buffa et al (doi: 10.1090/S0025-5718-07-01965-5), with the difference that each individual shape function is normalized with respect to the area so that overall the integral over the dual function is one. When `interpolatory=true` is used, the function value is one on the support, and thus, it gives rise to a partition of unity. """ function duallagrangecxd0(mesh, jct=CompScienceMeshes.mesh(coordtype(mesh), dimension(mesh)-1); interpolatory=false) vertexlist = interior_and_junction_vertices(mesh, jct) duallagrangecxd0(mesh, vertexlist; interpolatory=interpolatory) end function duallagrangecxd0(mesh, vertexlist::Vector{Int}; interpolatory=false) T = coordtype(mesh) fns = Vector{Vector{Shape{T}}}(undef,length(vertexlist)) pos = Vector{vertextype(mesh)}() fine = barycentric_refinement(mesh) vtoc, vton = vertextocellmap(fine) verts = vertices(mesh) for (k,v) in enumerate(vertexlist) n = vton[v] F = vtoc[v,1:n] fns[k] = singleduallagd0(fine, F, v, interpolatory=interpolatory) push!(pos, verts[v]) end NF = 1 LagrangeBasis{0,-1,NF}(fine, fns, pos) end function duallagrangecxd0(mesh, vertices::CompScienceMeshes.AbstractMesh{U,1}; interpolatory=false) where {U} # vertexlist = Int[v[1] for v in vertices] vertexlist =Int[CompScienceMeshes.indices(vertices, v)[1] for v in vertices] return duallagrangecxd0(mesh, vertexlist; interpolatory=interpolatory) end """ singleduallagd0(fine, F, v; interpolatory=false) Build a single dual constant Lagrange element a mesh `fine`. `F` contains the indices to cells in the support and v is the index in the vertex list of the defining vertex. The default dual function (`interpolatory=false`) is similar to the one depicted in Figure 3 of Buffa et al (doi: 10.1090/S0025-5718-07-01965-5), with the difference that each individual shape function is normalized with respect to the area so that overall the integral over the dual function is one. When `interpolatory=true` is used, the function value is one on the support, and thus, it gives rise to a partition of unity. """ function singleduallagd0(fine, F, v; interpolatory=false) T = coordtype(fine) fn = Shape{T}[] for cellid in F # cell = cells(fine)[cellid] ptch = chart(fine, cellid) coeff = interpolatory ? T(1.0) : 1 / volume(ptch) / length(F) refid = 1 push!(fn, Shape(cellid, refid, coeff)) end return fn end """ lagrangec0d1(mesh; dirichlet=[true|false]) -> basis Build lagrangec0d1 elements, including (dirichlet=false) or excluding (dirichlet=true) those attached to boundary vertices. """ function lagrangec0d1(mesh; dirichlet::Bool=true) if dirichlet == false # return lagrangec0d1(mesh, boundary(mesh)) return lagrangec0d1(mesh, skeleton(mesh,0)) else return lagrangec0d1_dirichlet(mesh) end end function lagrangec0d1(mesh, jct) vertexlist = interior_and_junction_vertices(mesh, jct) lagrangec0d1(mesh, vertexlist, Val{dimension(mesh)+1}) end # build continuous linear Lagrange elements on a 2D manifold function lagrangec0d1(mesh, vertexlist::Vector, ::Type{Val{3}}) T = coordtype(mesh) U = universedimension(mesh) cellids, ncells = vertextocellmap(mesh) Cells = cells(mesh) Verts = vertices(mesh) # create the local shapes fns = Vector{Shape{T}}[] pos = Vector{vertextype(mesh)}() sizehint!(fns, length(vertexlist)) sizehint!(pos, length(vertexlist)) for v in vertexlist numshapes = ncells[v] numshapes == 0 && continue shapes = Vector{Shape{T}}(undef,numshapes) for s in 1: numshapes c = cellids[v,s] # cell = mesh.faces[c] cell = Cells[c] localid = something(findfirst(isequal(v), cell),0) @assert localid != 0 shapes[s] = Shape(c, localid, T(1.0)) end push!(fns, shapes) push!(pos, Verts[v]) end NF = 3 LagrangeBasis{1,0,NF}(mesh, fns, pos) end # for manifolds of dimension 1 function lagrangec0d1(mesh, vertexlist, ::Type{Val{2}}) T = coordtype(mesh) U = universedimension(mesh) P = vertextype(mesh) geometry = mesh cellids, ncells = vertextocellmap(mesh) # create the local shapes numverts = numvertices(mesh) fns = Vector{Vector{Shape{T}}}() pos = Vector{P}() sizehint!(fns, length(vertexlist)) sizehint!(pos, length(vertexlist)) for v in vertexlist numshapes = ncells[v] numshapes == 0 && continue # skip detached vertices shapes = Vector{Shape{T}}(undef,numshapes) for s in 1: numshapes c = cellids[v,s] cell = mesh.faces[c] if cell[1] == v shapes[s] = Shape(c, 1, T(1.0)) elseif cell[2] == v shapes[s] = Shape(c, 2, T(1.0)) else error("Junctions not supported") end end push!(fns, shapes) push!(pos, mesh.vertices[v]) end NF = 2 LagrangeBasis{1,0,NF}(geometry, fns, pos) end function lagrangec0d1(mesh, nodes::CompScienceMeshes.AbstractMesh{U,1} where {U}) Conn = connectivity(nodes, mesh, abs) rows = rowvals(Conn) vals = nonzeros(Conn) T = coordtype(mesh) P = vertextype(mesh) S = Shape{T} fns = Vector{Vector{S}}() pos = Vector{P}() for (i,node) in enumerate(nodes) fn = Vector{S}() for k in nzrange(Conn,i) cellid = rows[k] refid = vals[k] push!(fn, Shape(cellid, refid, T(1.0))) end push!(fns,fn) push!(pos,cartesian(center(chart(nodes,node)))) end NF = dimension(mesh) + 1 LagrangeBasis{1,0,NF}(mesh, fns, pos) end function lagrangec0d2(mesh::CompScienceMeshes.AbstractMesh{U,3}, nodes::CompScienceMeshes.AbstractMesh{U,1}, edges::CompScienceMeshes.AbstractMesh{U,2}) where {U} Conn = connectivity(nodes, mesh, abs) rows = rowvals(Conn) vals = nonzeros(Conn) T = coordtype(mesh) P = vertextype(mesh) S = Shape{T} fns = Vector{Vector{S}}() pos = Vector{P}() for (i,node) in enumerate(nodes) fn = Vector{S}() for k in nzrange(Conn,i) cellid = rows[k] refid = vals[k] push!(fn, Shape(cellid, refid, T(1.0))) end push!(fns,fn) push!(pos,cartesian(center(chart(nodes,node)))) end Conn = connectivity(edges, mesh, abs) rows = rowvals(Conn) vals = nonzeros(Conn) for (i,edge) in enumerate(edges) fn = Vector{S}() for k in nzrange(Conn,i) cellid = rows[k] refid = vals[k] push!(fn, Shape(cellid, 3+refid, T(1.0))) end push!(fns,fn) push!(pos,cartesian(center(chart(edges,edge)))) end NF = 6 LagrangeBasis{2,0,NF}(mesh, fns, pos) end duallagrangec0d1(mesh) = duallagrangec0d1(mesh, barycentric_refinement(mesh), x->false, Val{dimension(mesh)+1}) function duallagrangec0d1(mesh, jct) jct_pred = inclosure_gpredicate(jct) refined = barycentric_refinement(mesh) duallagrangec0d1(mesh, refined, jct_pred, Val{dimension(mesh)+1}) end function duallagrangec0d1(mesh, refined, jct_pred, ::Type{Val{3}}) T = coordtype(mesh) num_faces = dimension(mesh)+1 fns = Vector{Vector{Shape{T}}}(undef,numcells(mesh)) pos = Vector{vertextype(mesh)}() # store the fine mesh's vertices in an octree for fast retrieval fine_vertices = Octree(vertices(refined)) uv_ctr = ones(dimension(mesh))/(dimension(mesh)+1) vtoc, vton = vertextocellmap(refined) for (i,p) in enumerate(mesh) coarse_idcs = CompScienceMeshes.indices(mesh, p) coarse_chart = chart(mesh,p) fns[i] = Vector{Shape{T}}() push!(pos, cartesian(center(coarse_chart))) # It is assumed the vertices of this cell have the same index # mesh and its refinement. # coarse_cell = chart(mesh, coarse_idcs) # get the index in fine.vertices of the centroid of coarse_cell centroid = barytocart(coarse_chart, uv_ctr) I = CollisionDetection.find(fine_vertices, centroid) @assert length(I) == 1 centroid_id = I[1] # get the indx in fine.vertices of the centroid of the faces of coarse_cell face_center_ids = Vector{Int}(undef,num_faces) for f in 1:num_faces # prepare the barycentric coordinate uv_face_ctr = ones(dimension(mesh)+1)/(dimension(mesh)) uv_face_ctr[f] = 0 uv_face_ctr = uv_face_ctr[1:end-1] face_ctr = barytocart(coarse_chart, uv_face_ctr) I = CollisionDetection.find(fine_vertices, face_ctr) @assert length(I) == 1 face_center_ids[f] = I[1] end n = vton[centroid_id] for c in vtoc[centroid_id,1:n] fine_idcs = cells(refined)[c] local_id = something(findfirst(isequal(centroid_id), fine_idcs), 0) @assert local_id != 0 shape = Shape(c, local_id, 1.0) push!(fns[i], shape) end for f in 1:num_faces v = face_center_ids[f] jct_pred(vertices(refined)[v]) && continue n = vton[v] for c in vtoc[v,1:n] fine_idcs = cells(refined)[c] local_id = something(findfirst(isequal(v), fine_idcs),0) @assert local_id != 0 shape = Shape(c, local_id, 1/n/2) push!(fns[i], shape) end end for f in 1:length(coarse_idcs) v = coarse_idcs[f] jct_pred(vertices(refined)[v]) && continue n = vton[v] for c in vtoc[v,1:n] fine_idcs = cells(refined)[c] local_id = something(findfirst(isequal(v), fine_idcs),0) @assert local_id != 0 shape = Shape(c, local_id, 1/n/2) push!(fns[i], shape) end end end @assert length(fns) == length(pos) NF = 3 return LagrangeBasis{1,0,NF}(refined, fns, pos) end """ duallagrangec0d1(originalmesh, refinedmesh) It is the user responsibility to provide two meshes representing the same object. The second mesh needs to be obtained using "barycentric_refinement(originalmesh)". This basis function creats the dual Lagrange basis function and return an object that contains array of shapes [fns] It also return a gemoetry containing the refined mesh. """ function duallagrangec0d1(mesh, mesh2, pred, ::Type{Val{2}}) T = coordtype(mesh) U = universedimension(mesh) # get the information about number of vertices, number of faces , and the maping between vertices and faces for the original mesh numverts1 = numvertices(mesh) num_cells1 = numcells(mesh) cellids1, ncells1=vertextocellmap(mesh) # get the information about number of vertices, number of faces , and the maping between vertices and faces for the refined mesh num_cells2 = numcells(mesh2) numverts2 = numvertices(mesh2) geometry = mesh2 cellids2, ncells2 = vertextocellmap(mesh2) fns = Vector{Vector{Shape{T}}}(undef,num_cells1) pos = Vector{vertextype(mesh)}() # We will iterate over the coarse mesh segments to assign all the functions to it. for segment_coarse in 1 : num_cells1 # For the dual Lagrange there is a 6 shapes per segment numshapes = (ncells1[segment_coarse]*4) -2 shapes = Vector{Shape{T}}(undef,numshapes) # Now we will get all the smaller faces within the coarse segment #i.e The coose segment will have two points, and these tow points are connected to two segmesnts in the finer mesh # This will give us a 4 smaller faces per Dual lagrange basis, we store them first in all_faces all_faces= Array{SVector{2,Int}}(undef,4) # faces in the original segment (4) # the follwoing code get the verteciec for each coarse segment # then it looks for the two faces connected to each point in the finer mesh # if for example the segment would connect to more than two faces we will have # mesh.faces[segment_coarse][1],n] and iterate over how many segments [n] are connected all_faces[1]=mesh2.faces[cellids2[mesh.faces[segment_coarse][1],1]] all_faces[2]=mesh2.faces[cellids2[mesh.faces[segment_coarse][1],2]] all_faces[3]=mesh2.faces[cellids2[mesh.faces[segment_coarse][2],1]] all_faces[4]=mesh2.faces[cellids2[mesh.faces[segment_coarse][2],2]] # now we now the first point of the corse segment will have the left hand side basis # and we know that that point is connected to faces 1,2 in the array all_faces # but now we want to which one of them is inner segment and which one is at the edge # as both of these two faces are in left hand side # The inner face will have the left hand side corase point in its first place for example # we have original point 2,3 , and the coarse segment (2,3) # after refinment we will have for example points 20,2,21,3,22 with four faces (20,2),(2,21),(21,3),(3,22) # so the faces to the left (20,2),(2,21) we can decide the inner one if the original point(2) is at first index # same for right hand side faces (21,3),(3,22) if the original point(3) is in the second index # then the inner faces are (2,21) and (21,3) # the following code does the same checking process and assign the shapes for the dual lagragne right away # For the Left hand side faces if(all_faces[1][1] == mesh.faces[segment_coarse][1]) shapes[1]= Shape(cellids2[mesh.faces[segment_coarse][1],2],1,0.5) shapes[2]= Shape(cellids2[mesh.faces[segment_coarse][1],1],2,0.5) shapes[3]= Shape(cellids2[mesh.faces[segment_coarse][1],1],1,1.0) elseif(all_faces[2][1] == mesh.faces[segment_coarse][1]) shapes[1]= Shape(cellids2[mesh.faces[segment_coarse][1],2],1,1.0) shapes[2]= Shape(cellids2[mesh.faces[segment_coarse][1],2],2,0.5) shapes[3]= Shape(cellids2[mesh.faces[segment_coarse][1],1],1,0.5) end # For the Right hand side faces if(all_faces[3][2] == mesh.faces[segment_coarse][2]) shapes[4]= Shape(cellids2[mesh.faces[segment_coarse][2],1],2,1.0) shapes[5]= Shape(cellids2[mesh.faces[segment_coarse][2],1],1,0.5) shapes[6]= Shape(cellids2[mesh.faces[segment_coarse][2],2],2,0.5) elseif(all_faces[4][2] == mesh.faces[segment_coarse][2]) shapes[4]= Shape(cellids2[mesh.faces[segment_coarse][2],2],2,1.0) shapes[5]= Shape(cellids2[mesh.faces[segment_coarse][2],2],1,0.5) shapes[6]= Shape(cellids2[mesh.faces[segment_coarse][2],1],2,0.5) end # Now assign all of these shapes to the relevent segment in the coarse mesh fns[segment_coarse]=shapes push!(pos, cartesian(center(chart(mesh, segment_coarse)))) end NF = 2 LagrangeBasis{1,0,NF}(geometry, fns, pos) end gradient(space::LagrangeBasis{1,0}, geo, fns) = NDLCCBasis(geo, fns) # gradient(space::LagrangeBasis{1,0}, geo::CompScienceMeshes.AbstractMesh{U,3} where {U}, fns) = NDBasis(geo, fns) curl(space::LagrangeBasis{1,0}, geo, fns) = RTBasis(geo, fns) curl(space::LagrangeBasis{2,0}, geo, fns) = BDMBasis(geo, fns) gradient(space::LagrangeBasis{1,0,<:CompScienceMeshes.AbstractMesh{<:Any,2}}, geo, fns) = LagrangeBasis{0,-1,1}(geo, fns, space.pos) gradient(space::LagrangeBasis{1,0,<:CompScienceMeshes.AbstractMesh{<:Any,3}}, geo, fns) = NDBasis(geo, fns, space.pos) # # Sclar trace for Laggrange element based spaces # function strace(X::LagrangeBasis{1,0}, geo, fns::Vector) # dimension of the boundary n = dimension(geo) # degree of the space d = 1 # number of local shape functions NF = binomial(n+d,n) trpos = deepcopy(positions(X)) LagrangeBasis{1,0,NF}(geo, fns, trpos) end function extend_0_form(supp, dirichlet, x_prt, Lg_prt) Id = BEAST.Identity() bnd_supp = boundary(supp) supp_nodes = CompScienceMeshes.skeleton_fast(supp, 0) dir_compl = submesh(!in(dirichlet), bnd_supp) dir_compl_nodes = CompScienceMeshes.skeleton_fast(dir_compl, 0) int_nodes = submesh(!in(dir_compl_nodes), supp_nodes) if length(int_nodes) == 0 T = scalartype(Id, Lg_prt, Lg_prt) S = typeof(Lg_prt) P = eltype(Lg_prt.pos) return T[], int_nodes, S(supp, Vector{Vector{Shape{T}}}(), Vector{P}()) end Lg_int = BEAST.lagrangec0d1(supp, int_nodes) grad_Lg_prt = gradient(Lg_prt) grad_Lg_int = gradient(Lg_int) A = assemble(Id, grad_Lg_int, grad_Lg_int, threading=Threading{:single}) a = -assemble(Id, grad_Lg_int, grad_Lg_prt, threading=Threading{:single}) * x_prt x_int = A \ a return x_int, int_nodes, Lg_int end function dualforms_init(Supp, Dir) tetrs = barycentric_refinement(Supp) v2t, v2n = CompScienceMeshes.vertextocellmap(tetrs) bnd = boundary(tetrs) gpred = CompScienceMeshes.overlap_gpredicate(Dir) dir = submesh((m,face) -> gpred(chart(m,face)), bnd) return tetrs, bnd, dir, v2t, v2n end function duallagrangec0d1(mesh::CompScienceMeshes.AbstractMesh{<:Any,3}, nodes, dirbnd) refd, bnd, dir, v2t, v2n = dualforms_init(mesh, dirbnd) dual0forms_body(mesh, refd, bnd, dir, v2t, v2n) end function dual0forms_body(mesh::CompScienceMeshes.AbstractMesh{<:Any,3}, refd, bnd, dir, v2t, v2n) T = coordtype(refd) S = Shape{T} V = vertextype(mesh) bfs = Vector{Vector{S}}(undef, length(mesh)) pos = Vector{V}(undef, length(mesh)) # Cells = cells(mesh) Cells = [c for c in mesh] num_threads = Threads.nthreads() for F in 1:length(mesh) # Cell = Cells[F] Cell = CompScienceMeshes.indices(mesh, Cells[F]) myid = Threads.threadid() # myid == 1 && F % 20 == 0 && # println("Constructing dual 1-forms: $(F) out of $(length(mesh)).") idcs1 = v2t[Cell[1],1:v2n[Cell[1]]] idcs2 = v2t[Cell[2],1:v2n[Cell[2]]] idcs3 = v2t[Cell[3],1:v2n[Cell[3]]] supp1 = refd[idcs1] # 2D supp2 = refd[idcs2] supp3 = refd[idcs3] bnd_supp1 = boundary(supp1) # 1D bnd_supp2 = boundary(supp2) bnd_supp3 = boundary(supp3) supp23 = submesh(in(bnd_supp2), bnd_supp3) # 1D supp31 = submesh(in(bnd_supp3), bnd_supp1) supp12 = submesh(in(bnd_supp1), bnd_supp2) port = boundary(supp23) # 0D port = submesh(in(boundary(supp31)), port) port = submesh(in(boundary(supp12)), port) @assert length(port) == 1 in_dir = in(dir) dir1_edges = submesh(in_dir, bnd_supp1) # 1D dir2_edges = submesh(in_dir, bnd_supp2) dir3_edges = submesh(in_dir, bnd_supp3) bnd_dir1 = boundary(dir1_edges) # 0D bnd_dir2 = boundary(dir2_edges) bnd_dir3 = boundary(dir3_edges) dir23_nodes = submesh(in(bnd_dir2), bnd_dir3) # 0D dir31_nodes = submesh(in(bnd_dir3), bnd_dir1) dir12_nodes = submesh(in(bnd_dir1), bnd_dir2) # Step 1: set port flux and extend to dual faces x0 = ones(T,1) Lg12_prt = BEAST.lagrangec0d1(supp12, port) Lg23_prt = BEAST.lagrangec0d1(supp23, port) Lg31_prt = BEAST.lagrangec0d1(supp31, port) x23, supp23_int_nodes, _ = extend_0_form(supp23, dir23_nodes, x0, Lg23_prt) x31, supp31_int_nodes, _ = extend_0_form(supp31, dir31_nodes, x0, Lg31_prt) x12, supp12_int_nodes, _ = extend_0_form(supp12, dir12_nodes, x0, Lg12_prt) port1_nodes = union(port, supp31_int_nodes, supp12_int_nodes) port2_nodes = union(port, supp12_int_nodes, supp23_int_nodes) port3_nodes = union(port, supp23_int_nodes, supp31_int_nodes) x1_prt = [x0; x31; x12] x2_prt = [x0; x12; x23] x3_prt = [x0; x23; x31] Lg1_prt = BEAST.lagrangec0d1(supp1, port1_nodes) Lg2_prt = BEAST.lagrangec0d1(supp2, port2_nodes) Lg3_prt = BEAST.lagrangec0d1(supp3, port3_nodes) x1_int, _, Lg1_int = extend_0_form(supp1, dir1_edges, x1_prt, Lg1_prt) x2_int, _, Lg2_int = extend_0_form(supp2, dir2_edges, x2_prt, Lg2_prt) x3_int, _, Lg3_int = extend_0_form(supp3, dir3_edges, x3_prt, Lg3_prt) # inject in the global space fn = BEAST.Shape{T}[] addf!(fn, x1_prt, Lg1_prt, idcs1) addf!(fn, x1_int, Lg1_int, idcs1) addf!(fn, x2_prt, Lg2_prt, idcs2) addf!(fn, x2_int, Lg2_int, idcs2) addf!(fn, x3_prt, Lg3_prt, idcs3) addf!(fn, x3_int, Lg3_int, idcs3) pos[F] = cartesian(CompScienceMeshes.center(chart(mesh, Cells[F]))) bfs[F] = fn end LagrangeBasis{1,0,3}(refd, bfs, pos) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1053
function Base.:*(A::AbstractArray, s::Space) where {Space} @assert ndims(A) == 2 @assert size(A,2) == numfunctions(s) F = eltype(s.fns) fns = [similar(F,0) for i in axes(A,1)] geo = s.geo for i in axes(A,1) for j in axes(A,2) A[i,j] == 0 && continue shapes = [Shape(sh.cellid, sh.refid, A[i,j]*sh.coeff) for sh in s.fns[j]] append!(fns[i], shapes) end fns[i] = collapse_shapes(fns[i]) end pos = fill(zero(eltype(s.pos)), length(fns)) return Space(geo, fns, pos) end function collapse_shapes(shapevec) ids = unique([(sh.cellid,sh.refid) for sh in shapevec]) S = eltype(shapevec) collapsed = [S(id..., 0) for id in ids] for sh in shapevec pos = findfirst(isequal((sh.cellid, sh.refid)), ids) @assert pos != nothing old = collapsed[pos] @assert old.cellid == sh.cellid @assert old.refid == sh.refid collapsed[pos] = S(old.cellid, old.refid, old.coeff+sh.coeff) end collapsed end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1456
struct NCrossBDMBasis{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end NCrossBDMBasis(geo, fns) = NCrossBDMBasis(geo, fns, Vector{vertextype(geo)}(undef,length(fns))) refspace(s::NCrossBDMBasis{T}) where {T} = NCrossBDMRefSpace{T}() function ncrossbdm(mesh) edges = skeleton(mesh, 1) cps = cellpairs(mesh, edges, dropjunctionpair=true) ids = findall(x -> x>0, cps[2,:]) ncrossbdm(mesh, cps[:,ids]) end function ncrossbdm(mesh, cellpairs::Array{Int,2}) @warn "brezzidouglasmarini(mesh, cellpairs) assumes mesh is oriented" @assert size(cellpairs,1) == 2 T = coordtype(mesh) P = vertextype(mesh) S = Shape{T} F = Vector{Shape{T}} nf = 2*size(cellpairs,2) fns = Vector{F}(undef, nf) pos = Vector{P}(undef, nf) for i in axes(cellpairs)[2] c1, c2 = cellpairs[:,i] cell1 = cells(mesh)[c1] cell2 = cells(mesh)[c2] e1, e2 = getcommonedge(cell1, cell2) @assert e1*e2 < 0 e1, e2 = abs(e1), abs(e2) fns[2*(i-1)+1] = [ S(c1, 2*(e1-1)+1 ,+1.0), S(c2, 2*(e2-1)+2,-1.0)] fns[2*(i-1)+2] = [ S(c1, 2*(e1-1)+2 ,+1.0), S(c2, 2*(e2-1)+1,-1.0)] v1 = cell1[mod1(e1+1,3)] v2 = cell1[mod1(e1+2,3)] edge = simplex(mesh.vertices[[v1,v2]]...) cntr = cartesian(center(edge)) pos[2*(i-1)+1] = cntr pos[2*(i-1)+2] = cntr end NCrossBDMBasis(mesh, fns, pos) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2527
mutable struct ND2Basis{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end ND2Basis(geo, fns) = ND2Basis(geo, fns, Vector{vertextype(geo)}(undef,length(fns))) refspace(space::ND2Basis{T}) where T = ND2RefSpace{T}() """ nedelec2(mesh, edges) Constructs the 2nd degree Nedelec basis of the first kind i.e. H(curl). Returns an object of type 'ND2Basis'. """ function nedelec2(surface, edges=skeleton(surface,1)) T = coordtype(surface) P = vertextype(surface) num_edges = numcells(edges) C = connectivity(edges, surface, identity) rows = rowvals(C) vals = nonzeros(C) Cells = cells(surface) num_cells = size(Cells,1) fns = Vector{Vector{Shape{T}}}(undef,2*(num_edges+num_cells)) pos = Vector{P}(undef,2*(num_edges+num_cells)) chooseref1(x) = if x<0 return 0 else return -1 end chooseref2(x) = if x<0 return -1 else return 0 end for (i,edge) in enumerate(edges) fns[2*i-1] = Vector{Shape{T}}() fns[2*i] = Vector{Shape{T}}() pos[2*i-1] = cartesian(center(chart(edges,edge))) pos[2*i] = cartesian(center(chart(edges,edge))) sgn = 1.0 for k in nzrange(C,i) j = rows[k] # j is the index of a cell adjacent to edge s = vals[k] # s contains the oriented (signed) local index of edge[i] in cell[j] # i == 3 && @show s push!(fns[2*i-1], Shape{T}(j, 2*abs(s)+chooseref1(sign(s)), T(sgn))) sgn *= -1 end sgn = 1.0 for k in nzrange(C,i) j = rows[k] # j is the index of a cell adjacent to edge s = vals[k] # s contains the oriented (signed) local index of edge[i] in cell[j] # i == 3 && @show s push!(fns[2*i], Shape{T}(j, 2*abs(s)+chooseref2(sign(s)), T(sgn))) sgn *= -1 end end for (i,cell) in enumerate(Cells) fns[2*num_edges+2*i-1] = Vector{Shape{T}}() fns[2*num_edges+2*i] = Vector{Shape{T}}() push!(fns[2*num_edges+2*i-1], Shape{T}(i, 7, T(1.0))) push!(fns[2*num_edges+2*i], Shape{T}(i, 8, T(1.0))) ctr = cartesian(center(chart(surface,i))) pos[2*num_edges+2*i-1] = ctr pos[2*num_edges+2*i] = ctr end ND2Basis(surface, fns, pos) end function LinearAlgebra.cross(::NormalVector, s::ND2Basis) # @assert CompScienceMeshes.isoriented(s.geo) return raviartthomas2(s.geo) end #= function curl(space::ND2Basis) divergence(n × space) end =#
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1506
mutable struct NDLCCBasis{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end NDLCCBasis(geo, fns) = NDLCCBasis(geo, fns, Vector{vertextype(geo)}(undef,length(fns))) refspace(space::NDLCCBasis{T}) where {T} = NDLCCRefSpace{T}() Base.similar(space::NDLCCBasis{T,M,P} where {T,M,P}, geo, fns, pos) = NDLCCBasis(geo, fns, pos) """ nedelecc3d(mesh, edges::Array{SArray{Tuple{2},Int64,1,2},1}) returns an object of the type NDLCCBasis. """ function nedelecc3d(mesh, edges) T = coordtype(mesh) P = vertextype(mesh) num_edges = numcells(edges) C = connectivity(edges, mesh, identity) rows = rowvals(C) vals = nonzeros(C) fns = Vector{Vector{Shape{T}}}(undef,num_edges) pos = Vector{P}(undef,num_edges) for (i,e) in enumerate(edges) fns[i] = Vector{Shape{T}}() pos[i] = cartesian(center(chart(edges,e))) for k in nzrange(C,i) j = rows[k] s = vals[k] push!(fns[i], Shape{T}(j, abs(s), sign(s))) end end NDLCCBasis(mesh, fns, pos) end """ nedelecc3d(mesh) returns an object of type NDLCCBasis """ function nedelecc3d(mesh) edges = skeleton(mesh,1) nedelecc3d(mesh, edges) end function nedelec(mesh::CompScienceMeshes.AbstractMesh{U,4} where {U}, edges=skeleton(mesh,1)) nedelecc3d(mesh, edges) end curl(space::NDLCCBasis, geo, fns) = NDLCDBasis(geo, fns, space.pos) ttrace(X::NDLCCBasis, geo, fns) = RTBasis(geo, fns, deepcopy(X.pos))
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1429
mutable struct NDLCDBasis{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end NDLCDBasis(geo, fns) = NDLCDBasis(geo, fns, Vector{vertextype(geo)}(undef,length(fns))) refspace(space::NDLCDBasis{T}) where {T} = NDLCDRefSpace{T}() Base.similar(space::NDLCDBasis{T,M,P} where {T,M,P}, geo, fns, pos) = NDLCDBasis(geo, fns, pos) function nedelecd3d(mesh, faces) T = coordtype(mesh) P = vertextype(mesh) num_faces = numcells(faces) C = connectivity(faces, mesh, identity) rows = rowvals(C) vals = nonzeros(C) fns = Vector{Vector{Shape{T}}}(undef,num_faces) pos = Vector{P}(undef,num_faces) for (i,face) in enumerate(faces) fns[i] = Vector{Shape{T}}() pos[i] = cartesian(center(chart(faces,face))) for k in nzrange(C,i) j = rows[k] s = vals[k] push!(fns[i], Shape{T}(j, abs(s), sign(s))) end end NDLCDBasis(mesh, fns, pos) end function nedelecd3d(mesh) faces = skeleton(mesh,2) nedelecd3d(mesh, faces) end function raviartthomas(m::CompScienceMeshes.AbstractMesh{U,4} where {U}, faces=skeleton(m,2)) nedelecd3d(m, faces) end ntrace(X::NDLCDBasis, geo, fns) = LagrangeBasis{0,-1,1}(geo, fns, deepcopy(X.pos)) ttrace(X::NDLCDBasis, geo, fns) = NDBasis{}(geo, fns, deepcopy(X.pos)) divergence(space::NDLCDBasis, geo, fns) = LagrangeBasis{0,-1,1}(geo, fns, space.pos)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1271
struct NDBasis{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end NDBasis(geo, fns) = NDBasis(geo, fns, Vector{vertextype(geo)}(undef,length(fns))) refspace(s::NDBasis) = NDRefSpace{scalartype(s)}() function nedelec(surface, edges=skeleton(surface,1)) T = coordtype(surface) # P = eltype(surface.vertices) P = vertextype(surface) num_edges = numcells(edges) C = connectivity(edges, surface, identity) rows = rowvals(C) vals = nonzeros(C) fns = Vector{Vector{Shape{T}}}(undef,num_edges) pos = Vector{P}(undef,num_edges) for (i,edge) in enumerate(edges) fns[i] = Vector{Shape{T}}() pos[i] = cartesian(center(chart(edges,edge))) for k in nzrange(C,i) j = rows[k] # j is the index of a cell adjacent to edge s = vals[k] # s contains the oriented (signed) local index of edge[i] in cell[j] # i == 3 && @show s push!(fns[i], Shape{T}(j, abs(s), sign(s))) end end NDBasis(surface, fns, pos) end function LinearAlgebra.cross(::NormalVector, s::NDBasis) # @assert CompScienceMeshes.isoriented(s.geo) RTBasis(s.geo, s.fns, s.pos) end function curl(space::NDBasis) divergence(n × space) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
820
""" restrict(refspace, element1, element2) Computes the restriction of a set of local shape functions on `element1` as linear combinations of the set of local shape functions on `element2`. More precisely `restrict` returns an `NxM` matrix `P` such that the `i`-th local shape ``g_i`` function on element2 can be written as: ``g_i = sum_{j=1}^{M} P_{ij} f_j`` """ function restrict end function restrict(sp::Space, submesh::CompScienceMeshes.AbstractMesh) fns = similar(sp.fns) S = eltype(eltype(fns)) for (i,fn) in pairs(sp.fns) fns[i] = Vector{S}() for sh in fn cell = CompScienceMeshes.restrict(submesh, sh.cellid) cell == 0 && continue push!(fns[i], S(cell, sh.refid, sh.coeff)) end end similar(sp, submesh, fns, sp.pos) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
4578
mutable struct RT2Basis{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end RT2Basis(geo, fns) = RT2Basis(geo, fns, Vector{vertextype(geo)}(undef,length(fns))) #= positions(rt) = rt.pos =# refspace(space::RT2Basis{T}) where {T} = RT2RefSpace{T}() subset(rt::RT2Basis,I) = RT2Basis(rt.geo, rt.fns[I], rt.pos[I]) #= mutable struct ValDiv end =# """ raviartthomas2(mesh, cellpairs::Array{Int,2}) Constructs the RT2 basis on the input `mesh`. The i-th RT2 basis function will represent a current distribution flowing from cell `cellpairs[1,i]` to `cellpairs[2,i]` on the mesh. Returns an object of type `RT2Basis`, which comprises both the mesh and pairs of Shape objects which corresponds to the cell pairs, containing the necsessary coefficients and indices to compute the exact basis functions when required by the solver. """ function raviartthomas2(mesh::CompScienceMeshes.AbstractMesh{U,D1,T}, cellpairs::Array{Int,2}) where {U,D1,T} # combine now the pairs of monopolar RWGs in div-conforming RWGs numpairs = size(cellpairs,2) Cells = cells(mesh) numcells = size(Cells,1) functions = Vector{Vector{Shape{T}}}(undef,2*(numpairs+numcells)) positions = Vector{vertextype(mesh)}(undef,2*(numpairs+numcells)) chooseref1(x) = if x<0 return 0 else return -1 end chooseref2(x) = if x<0 return -1 else return 0 end for i in 1:numpairs if cellpairs[2,i] > 0 c1 = cellpairs[1,i]; # cell1 = Cells[c1] #mesh.faces[c1] c2 = cellpairs[2,i]; # cell2 = Cells[c2] #mesh.faces[c2] cell1 = CompScienceMeshes.indices(mesh, c1) cell2 = CompScienceMeshes.indices(mesh, c2) e1, e2 = getcommonedge(cell1, cell2) functions[2*i-1] = [ Shape{T}(c1, 2*abs(e1)+chooseref1(sign(e1)), T(+1.0)), Shape{T}(c2, 2*abs(e2)+chooseref1(sign(e2)), T(-1.0))] functions[2*i] = [ Shape{T}(c1, 2*abs(e1)+chooseref2(sign(e1)), T(+1.0)), Shape{T}(c2, 2*abs(e2)+chooseref2(sign(e2)), T(-1.0))] isct = intersect(cell1, cell2) @assert length(isct) == 2 @assert !(cell1[abs(e1)] in isct) @assert !(cell2[abs(e2)] in isct) ctr1 = cartesian(center(chart(mesh, c1))) ctr2 = cartesian(center(chart(mesh, c2))) positions[2*i-1] = (ctr1 + ctr2) / 2 positions[2*i] = (ctr1 + ctr2) / 2 else c1 = cellpairs[1,i] e1 = cellpairs[2,i] functions[i] = [ Shape(c1, abs(e1), T(+1.0))] positions[i] = cartesian(center(chart(mesh, c1))) end end for (i,cell) in enumerate(Cells) functions[2*numpairs+2*i-1] = [ Shape{T}(i, 7, T(+1.0))] functions[2*numpairs+2*i] = [ Shape{T}(i, 8, T(+1.0))] ctr1 = cartesian(center(chart(mesh, i))) positions[2*numpairs+2*i-1] = ctr1 positions[2*numpairs+2*i] = ctr1 end geo = mesh RT2Basis(geo, functions, positions) end function raviartthomas2(mesh, edges::CompScienceMeshes.AbstractMesh{U,2} where {U}) cps = CompScienceMeshes.cellpairs(mesh, edges) # ids = findall(x -> x>0, cps[2,:]) raviartthomas2(mesh, cps) end function raviartthomas2(mesh::CompScienceMeshes.AbstractMesh{U,3} where {U}) bnd = boundary(mesh) edges = submesh(!in(bnd), skeleton(mesh,1)) return raviartthomas2(mesh, edges) end """ raviartthomas2(mesh) Conducts pre-processing on the input `mesh` by extracting the cell edges, cell pairs and indices required to construct the RT2 basis on the `mesh`. Calls raviartthomas2(mesh::Mesh, cellpairs::Array{Int,2}), which constructs the RT2 basis on the `mesh`, using the cell pairs identified. Returns the RT2 basis object. """ function raviartthomas2(mesh; sort=:spacefillingcurve) edges = skeleton(mesh, 1; sort) cps = cellpairs(mesh, edges, dropjunctionpair=true) ids = findall(x -> x>0, cps[2,:]) raviartthomas2(mesh, cps[:,ids]) end #= divergence(X::RT2Basis, geo, fns) = LagrangeBasis{0,-1,1}(geo, fns, deepcopy(positions(X))) ntrace(X::RT2Basis, geo, fns) = LagrangeBasis{0,-1,1}(geo, fns, deepcopy(positions(X))) =# #= function LinearAlgebra.cross(::NormalVector, s::RT2Basis) @assert CompScienceMeshes.isoriented(s.geo) fns = similar(s.fns) for (i,fn) in pairs(s.fns) fns[i] = [Shape(sh.cellid, sh.refid, -sh.coeff) for sh in fn] end ND2Basis(s.geo, fns, s.pos) end =#
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2188
struct RTQSpace{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end # RTQSpace(g::M, fns::Vector{}) function positions(s::RTQSpace) s.pos end function refspace(s::RTQSpace{T}) where {T} RTQuadRefSpace{T}() end function subset(rt::RTQSpace,I) RTQSpace(rt.geo, rt.fns[I], rt.pos[I]) end function raviartthomas( mesh::CompScienceMeshes.QuadMesh{T}, edges::CompScienceMeshes.AbstractMesh{3,2,T}, connectivity, orientations) where {T<:Any} fns = Vector{Vector{Shape{T}}}(undef, length(edges)) pos = Vector{SVector{3,T}}(undef, length(edges)) rows = rowvals(connectivity) vals = nonzeros(connectivity) for (i,edge) in enumerate(edges) σ = orientations[i] fn = map(zip(nzrange(connectivity, i),(σ,-σ))) do (j, α) Shape{T}(rows[j], abs(vals[j]), α) end fns[i] = fn pos[i] = cartesian(CompScienceMeshes.center(chart(edges, edge))) end return RTQSpace(mesh, fns, pos) end @testitem "RTQSpace construction" begin using CompScienceMeshes m = CompScienceMeshes.meshrectangle(2.0, 2.0, 1.0; structured=:quadrilateral) edges = skeleton(m, 1) edges_bnd = boundary(m) # @show length(edges_bnd) @test length(edges_bnd) == 8 pred = !in(edges_bnd) edges_int = submesh(pred, edges) c = CompScienceMeshes.connectivity(edges_int, m, identity) @test size(c) == (length(m), length(edges_int)) o = ones(length(edges_int)) s = raviartthomas(m, edges_int, c, o) @test numfunctions(s) == 4 end @testitem "RTQSpace assembly data" begin using CompScienceMeshes m = CompScienceMeshes.meshrectangle(2.0, 2.0, 1.0; structured=:quadrilateral) edges = skeleton(m, 1) edges_bnd = boundary(m) pred = !in(edges_bnd) edges_int = submesh(pred, edges) c = CompScienceMeshes.connectivity(edges_int, m, identity) o = ones(length(edges_int)) s = raviartthomas(m, edges_int, c, o) num_cells = numcells(m) num_bfs = numfunctions(s) r = refspace(s) num_refs = numfunctions(r) celltonum = BEAST.make_celltonum(num_cells, num_refs, num_bfs, s) els, ad, a2g = BEAST.assemblydata(s) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
8417
mutable struct RTBasis{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} end RTBasis(geo, fns) = RTBasis(geo, fns, Vector{vertextype(geo)}(undef,length(fns))) positions(rt) = rt.pos refspace(space::RTBasis{T}) where {T} = RTRefSpace{T}() subset(rt::RTBasis,I) = RTBasis(rt.geo, rt.fns[I], rt.pos[I]) mutable struct ValDiv end """ raviartthomas(mesh, cellpairs::Array{Int,2}) Constructs the RT basis on the input `mesh`. The i-th RT basis function will represent a current distribution flowing from cell `cellpairs[1,i]` to `cellpairs[2,i]` on the mesh. Returns an object of type `RTBasis`, which comprises both the mesh and pairs of Shape objects which corresponds to the cell pairs, containing the necsessary coefficients and indices to compute the exact basis functions when required by the solver. """ function raviartthomas(mesh::CompScienceMeshes.AbstractMesh{U,D1,T}, cellpairs::Array{Int,2}) where {U,D1,T} # combine now the pairs of monopolar RWGs in div-conforming RWGs numpairs = size(cellpairs,2) functions = Vector{Vector{Shape{T}}}(undef,numpairs) positions = Vector{vertextype(mesh)}(undef,numpairs) # Cells = cells(mesh) for i in 1:numpairs if cellpairs[2,i] > 0 c1 = cellpairs[1,i]; # cell1 = Cells[c1] #mesh.faces[c1] c2 = cellpairs[2,i]; # cell2 = Cells[c2] #mesh.faces[c2] cell1 = CompScienceMeshes.indices(mesh, c1) cell2 = CompScienceMeshes.indices(mesh, c2) e1, e2 = getcommonedge(cell1, cell2) functions[i] = [ Shape{T}(c1, abs(e1), T(+1.0)), Shape{T}(c2, abs(e2), T(-1.0))] isct = intersect(cell1, cell2) @assert length(isct) == 2 @assert !(cell1[abs(e1)] in isct) @assert !(cell2[abs(e2)] in isct) ctr1 = cartesian(center(chart(mesh, c1))) ctr2 = cartesian(center(chart(mesh, c2))) positions[i] = (ctr1 + ctr2) / 2 else c1 = cellpairs[1,i] e1 = cellpairs[2,i] functions[i] = [ Shape(c1, abs(e1), T(+1.0))] positions[i] = cartesian(center(chart(mesh, c1))) end end geo = mesh RTBasis(geo, functions, positions) end function raviartthomas(mesh, edges::CompScienceMeshes.AbstractMesh{U,2} where {U}) cps = CompScienceMeshes.cellpairs(mesh, edges) # ids = findall(x -> x>0, cps[2,:]) raviartthomas(mesh, cps) end function raviartthomas(mesh::CompScienceMeshes.AbstractMesh{U,3} where {U}) bnd = boundary(mesh) edges = submesh(!in(bnd), skeleton(mesh,1)) return raviartthomas(mesh, edges) end """ raviartthomas(mesh) Conducts pre-processing on the input `mesh` by extracting the cell edges, cell pairs and indices required to construct the RT basis on the `mesh`. Calls raviartthomas(mesh::Mesh, cellpairs::Array{Int,2}), which constructs the RT basis on the `mesh`, using the cell pairs identified. Returns the RT basis object. """ function raviartthomas(mesh; sort=:spacefillingcurve) edges = skeleton(mesh, 1; sort) cps = cellpairs(mesh, edges, dropjunctionpair=true) ids = findall(x -> x>0, cps[2,:]) raviartthomas(mesh, cps[:,ids]) end # """ # raviartthomas(Γ; neumann) # Constructs the RT space relative to boundary `neumann` of an open surface, only # selecting cell pairs whose common edge does lie on `γ` . (This prevents # the calculation of physically-impossible surface currents, such as those # flowing 'off the edge' of a surface.) # """ # function raviartthomas(Γ; neumann) # γ = neumann # in_interior = interior_tpredicate(Γ) # on_junction = overlap_gpredicate(γ) # pred = c -> (in_interior(c) || on_junction(chart(Γ,c))) # edges = skeleton(pred, Γ, 1) # cps = cellpairs(Γ, edges, dropjunctionpair=true) # raviartthomas(Γ, cps) # end # raowiltonglisson = raviartthomas """ portcells(Γ::Mesh, γ::Mesh) returns an array containing cell pairs of mesh Γ around a boundary edge that overlaps with mesh γ """ function portcells(Γ, γ) in_interior = interior_tpredicate(Γ) overlaps = overlap_gpredicate(γ) on_junction = (m,c) -> overlaps(chart(m,c)) pred = (m,x) -> (!in_interior(m,x) && on_junction(m,x)) #check only for exterior overlapping edges # - if γ is defined to overlap within the structure Γ, this isn't considered a port - # edges = skeleton(pred, Γ, 1) #Take only exterior edges overlapping γ segment edges = submesh(pred, skeleton(Γ,1)) cps = cellpairs(Γ, edges, dropjunctionpair=true) return cps end """ rt_cedge(cps::Array{Int,2}, weight) Computes single basis function with equally distributed constant current leaving or entering port defined by cellpairs cps. weight defines the total current over the port and its direction (+ve = out, -ve = in) """ function rt_cedge(cps::Array{Int,2}, weight) T=typeof(weight) numpairs = size(cps,2) @assert numpairs > 0 weight = weight / numpairs #total current leaving and entering equal 1 functions = Vector{Shape{T}}(undef,numpairs) #note: not a Vector{Vector} for i in 1:numpairs c1 = cps[1,i] e1 = cps[2,i] functions[i] = Shape(c1, abs(e1), weight) # this assumes cellpairs will be adjacent eachother through the loop end functions end """ rt_vedge(cps::Array{Int,2}, weight) Computes n-1 basis function with oscillating current in(leaving and entering) pairs of half triangles defined over port specified by cellpairs cps. weight defines the magnitude of individual current in and out the half triangles, and it's polarity simply defines whether to start with in or out """ function rt_vedge(cps::Array{Int,2}, weight) T=typeof(weight) numpairs = size(cps,2) @assert numpairs > 0 #adjacent cells are considered a pair, so we have one less numpairs functions = Vector{Vector{Shape{T}}}(undef,numpairs - 1) for i in 1:numpairs if i < numpairs # stop when on last cellpair c1 = cps[1,i]; e1 = cps[2,i] c2 = cps[1,i+1]; e2 = cps[2,i+1] functions[i] = [ Shape(c1, abs(e1), weight), Shape(c2, abs(e2), -weight)] # this assumes cellpairs will be adjacent eachother through the loop end end functions end """ rt_ports(Γ::Mesh, γ::Mesh ...) Constructs the RT space on `Γ`, relative to boundary pairs in `γ`. `γ` expects any number of pairs-of-ports as arguments and accepts tuples, arrays, vectors etc. e.g `rt_ports(Γ, a, b ...);` where a = [γ₁ γ₂], b = (γ₃,γ₄) etc. `rt_ports` with no pair of ports supplied i.e `rt_ports(Γ)` reduces to the `raviartthomas(Γ)` function. The RT space ensures current continuity in each pair of ports. i.e. current leaving mesh Γ through γ₁ is accounted for in γ₂. Returns the RT basis object. """ function rt_ports(Γ, γ...) #TODO: can include an extra argument for polarity applied to ports T = coordtype(Γ) internal = raviartthomas(Γ) fns = internal.fns pos = internal.pos for i = 1:length(γ) #loop through pairs of ports port1 = portcells(Γ, γ[i][1]) port2 = portcells(Γ, γ[i][2]) ce1 = rt_cedge(port1, T(+1.0)) ce2 = rt_cedge(port2, T(-1.0)) ffs = Vector{Shape{T}}(undef,length(ce1) + length(ce2)) ffs = [ce1;ce2] ve1 = rt_vedge(port1, T(+1.0)) ve2 = rt_vedge(port2, T(-1.0)) fns = [fns;[ffs];ve1;ve2] end RTBasis(Γ, fns) end """ getindex_rtg(RT::RTBasis) Returns the indices of the global half RWGs present in `RT`. `RT` is typically gotten from `rt_ports` """ function getindex_rtg(RT::RTBasis) #TODO: use more reasonable condition to extract indices # or have rt_ports return indices with RTBasis idx=[] A = RT.fns for i in 1:length(A) if size(A[i])[1] > 2 push!(idx,i) end end idx end divergence(X::RTBasis, geo, fns) = LagrangeBasis{0,-1,1}(geo, fns, deepcopy(positions(X))) ntrace(X::RTBasis, geo, fns) = LagrangeBasis{0,-1,1}(geo, fns, deepcopy(positions(X))) function LinearAlgebra.cross(::NormalVector, s::RTBasis) @assert CompScienceMeshes.isoriented(s.geo) fns = similar(s.fns) for (i,fn) in pairs(s.fns) fns[i] = [Shape(sh.cellid, sh.refid, -sh.coeff) for sh in fn] end NDBasis(s.geo, fns, s.pos) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
799
abstract type Continuity{T} end function raviartthomas(mesh, ::Type{Continuity{:none}}) @assert dimension(mesh) == 2 P = vertextype(mesh) S = Shape{coordtype(mesh)} F = Vector{S} nf = 3*numcells(mesh) functions = Vector{F}(undef, nf) positions = Vector{P}(undef, nf) for i in 1:numcells(mesh) functions[3*(i-1)+1] = [S(i,1,+1.0)] functions[3*(i-1)+2] = [S(i,2,+1.0)] functions[3*(i-1)+3] = [S(i,3,+1.0)] I = CompScienceMeshes.indices(mesh,i) V = CompScienceMeshes.vertices(mesh,I) ctr = sum(V)/3 # ctr = sum(mesh.vertices[mesh.faces[i]])/3 positions[3*(i-1)+1] = ctr positions[3*(i-1)+2] = ctr positions[3*(i-1)+3] = ctr end return RTBasis(mesh, functions, positions) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
690
""" StagedTimeStep{T,N,NN} T: the value type of the basis function. N: the number of stages. NN: the number of stages squared Each time step has intermediary stages given by the vertor c in a Butcher tableau (A,b,c) """ struct StagedTimeStep{T, N, NN, I} Δt :: T Nt :: I c :: SVector{N,T} A :: SArray{Tuple{N,N},T,2,NN} b :: SVector{N,T} zTransformedTermCount :: I contourRadius :: T end scalartype(sts :: StagedTimeStep{T, N, NN, I}) where {T, N, NN, I} = T temporalbasis(sts :: StagedTimeStep{T, N, NN, I}) where {T, N, NN, I} = timebasisdelta(sts.Δt, sts.Nt) numfunctions(s::StagedTimeStep) = s.Nt numstages(s) = 1 numstages(s::StagedTimeStep) = size(s.c,1)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2198
import CompScienceMeshes.chart,CompScienceMeshes.subd_chart,CompScienceMeshes.GSubdMesh,CompScienceMeshes.subdMesh mutable struct subdBasis{T,M,P} <: Space{T} geo::M fns::Vector{Vector{Shape{T}}} pos::Vector{P} data::Tuple{Array{subd_chart},Array{Array{Array{Tuple}}}} end function subset(s::S,I) where {S<:subdBasis} @warn "No parallel assembly supported when using subdivision bases!" return s end mutable struct subReferenceSpace{T,D} <: RefSpace{T,D} end refspace(s::subdBasis{T,M,P}) where {T,M,P} = subReferenceSpace{T,12}() # 12 only for regular case function (rs::subReferenceSpace)(nbhd) # u = parametric(nbhd) # x = cartesian(nbhd) s = shapefuns(nbhd) scurl = get_shape_curl(nbhd) # TODO: this needs fixing, stat! return s #,scurl end function subdsurface(mesh::Mesh{U,D1,T}) where {U,D1,T} subd_mesh = GSubdMesh(mesh) vertices = mesh.vertices subd_elements = subd_mesh.elements nvertices = length(vertices) nelem = length(subd_elements) funs=Array{Vector{BEAST.Shape{T}}}(undef,nvertices) for i = 1 : nvertices funs[i] = [] end for ie = 1:nelem inodes = subd_elements[ie].RingNodes N = length(inodes) for ib = 1:N nodeid = inodes[ib] coeff = 1.0 ifun = BEAST.Shape{T}(ie,ib,coeff) push!(funs[nodeid], ifun) end end data = assembly(subd_mesh) return subdBasis(mesh,funs,vertices,data) end function assemblydata(subdB::subdBasis) return subdB.data end function assembly(subdG::subdMesh) nelem = length(subdG.elements) assemblydata = Array{Array{Array{Tuple}}}(undef,nelem) ElementCharts = Array{subd_chart}(undef,nelem) for e = 1:nelem cha = chart(subdG,e) ringnodes = cha.RingNodes nnodes = length(ringnodes) line=Array{Array{Tuple}}(undef,nnodes) for inode = 1:nnodes Node = ringnodes[inode] entries=[] entry=tuple(Node,1.0) push!(entries,entry) line[inode] = entries end assemblydata[e] = line ElementCharts[e] = cha end return(ElementCharts,assemblydata) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
893
struct SpaceTimeBasis{S,T,U} <: Space{U} space::S time::T end function SpaceTimeBasis(space, time) S = typeof(space) T = typeof(time) U = scalartype(space,time) return SpaceTimeBasis{S,T,U}(space,time) end spatialbasis(s) = s spatialbasis(s::SpaceTimeBasis) = s.space function spatialbasis(s::DirectProductSpace) r = [spatialbasis(ch) for ch in s.factors] return DirectProductSpace(r) end temporalbasis(s::SpaceTimeBasis) = s.time ⊗(a, b) = SpaceTimeBasis(a,b) numfunctions(S::SpaceTimeBasis) = numfunctions(S.space) * numfunctions(S.time) scalartype(st::SpaceTimeBasis) = promote_type(scalartype(st.space), scalartype(st.time)) function tensordim(s::SpaceTimeBasis,i) i == 1 && return numfunctions(s.space) i == 2 && return numfunctions(s.time) return 1 end function tensordim(s, i) i == 1 && return numfunctions(s) return 1 end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
11293
using Compat mutable struct MonomialBasis{T,Degree,NF} <: RefSpace{T,NF} end valuetype(::MonomialBasis{T}) where {T} = T degree(::MonomialBasis{T,D}) where {T,D} = D numfunctions(x::MonomialBasis) = degree(x)+1 function (x::MonomialBasis)(p) t = cartesian(p)[1] valuetype(x)[t^d for d in 0 : degree(x)] end abstract type AbstractTimeBasisFunction end """ TimeBasisFunction{N,D} T: the value type of the time basis function N: the number of intervals in the support (this included the semi infinite interval stretching to +∞) D1: the degree of the TBF restricted to each of the intervals **plus one** """ mutable struct TimeBasisFunction{T,N,D1,D} <: AbstractTimeBasisFunction timestep::T numfunctions::Int polys::SVector{N,Polynomial{D1,T}} end function derive(tbf::TimeBasisFunction{T,N,D1,D}) where {T,N,D1,D} dpolys = Polynomial{D1-1,T}[ derive(p) for p in tbf.polys ] TimeBasisFunction{T,N,D1-1,D-1}( tbf.timestep, tbf.numfunctions, SVector{N,Polynomial{D1-1,T}}(dpolys...) ) end function integrate(tbf::TimeBasisFunction{T,NI,D1,D}) where {T,NI,D1,D} timestep = tbf.timestep numfunctions = tbf.numfunctions polys = Vector{Polynomial{D1+1,T}}(undef, length(tbf.polys)) c = zero(timestep) for i in 1:length(polys) t0 = (i-2) * timestep t1 = (i-1) * timestep polys[i] = integrate(tbf.polys[i],t0,c) c = polys[i](t1) end TimeBasisFunction{T,NI,D1+1,D+1}( tbf.timestep, tbf.numfunctions, SVector(polys...) ) end mutable struct TimeBasisDelta{T} <: AbstractTimeBasisFunction timestep::T numfunctions::Int end mutable struct DiracBoundary{T} <: RefSpace{T,1} end numfunctions(x::DiracBoundary) = 1 scalartype(x::TimeBasisDelta{T}) where {T} = T numfunctions(x::TimeBasisDelta) = x.numfunctions refspace(x::TimeBasisDelta{T}) where {T} = DiracBoundary{T}() timestep(x::TimeBasisDelta) = x.timestep numintervals(x::TimeBasisDelta) = 1 timebasisdelta(dt, Nt)= TimeBasisDelta(dt, Nt) numintervals(tbf::TimeBasisFunction{T,N,D1,D}) where {T,N,D1,D} = N degree(tbf::TimeBasisFunction{T,N,D1,D}) where {T,N,D1,D} = D timestep(tbf::TimeBasisFunction) = tbf.timestep scalartype(tbf::TimeBasisFunction{T,N,D1,D}) where {T,N,D1,D} = T numfunctions(t::TimeBasisFunction) = t.numfunctions refspace(t::TimeBasisFunction{T,N,D1,D}) where {T,N,D1,D} = MonomialBasis{T,D,D1}() function truncatetail(t::TimeBasisFunction{T,N,D1,D}) where {T,N,D1,D} P = Polynomial{D1,T} S = SVector{N,P} R = SVector{D1,T} out = deepcopy(t) polys = [p for p in t.polys] polys[end] = P(zero(R)) out.polys = S(polys) return out end geometry(t::AbstractTimeBasisFunction) = [SegmentedAxis(timestep(t), numfunctions(t)+numintervals(t)-3)] """ timebasisc0d1(type, timestep, numfunctions) Build the space of continuous, piecewise linear time basis functions. The DoFs are the time steps. `numfunctions` basis functions will be built in total. """ function timebasisc0d1(timestep, numfunctions, T::Type=Float64) i, z = one(T), zero(T) polys = SVector( Polynomial(SVector(i, i/timestep)), # 1 + t Polynomial(SVector(i, -i/timestep)), # 1 - t Polynomial(SVector(z, z)) ) TimeBasisFunction{T,3,2,1}(timestep, numfunctions, polys) end """ timebasiscxd0(timestep, numfunctions, T::Type=Float64) Create a temporal basis based on shifted copies of the nodal continuous, piecewise linear interpolant. """ function timebasiscxd0(timestep, numfunctions, T::Type=Float64) i, z = one(T), zero(T) polys = SVector( Polynomial(i), # 1 Polynomial(z), # 0 ) TimeBasisFunction{T,2,1,0}(timestep, numfunctions, polys) end """ timebasisspline2(timestep, numfunctions, T::Type=Float64) Create a temporal basis based on shifted copies of the quadratic spline. The spline is the convolution of a cxd0 and a c0d1 basis function. """ function timebasisspline2(dt, numfunctions, T::Type=typeof(dt)) i, z = one(T), zero(T) polys = SVector{4,Polynomial{3,T}}( Polynomial(SVector(i/2, i/dt, i/2/dt/dt)), Polynomial(SVector(i/2, i/dt, -i/dt/dt)), Polynomial(SVector(2*i, -2*i/dt, i/2/dt/dt)), Polynomial(SVector(z, z, z)) ) TimeBasisFunction{T,4,3,2}(dt, numfunctions, polys) end function timebasisshiftedlagrange(dt, numfunctions, degree, T::Type=typeof(dt)) z, i = zero(T), one(T) c = Polynomial(SVector(i)) t = Polynomial(SVector(z,i/dt)) polys = Polynomial{degree+1,T}[] for k = 0:degree f = c for i in 1:k f = T(1/i) * f * (i - t) end g = c for i in 1:(degree-k) g = T.(1/i) * g * (i + t) end push!(polys, f*g) end push!(polys, 0*Base.power_by_squaring(t, degree)) @assert length(polys) == degree+2 polys = SVector{degree+2,Polynomial{degree+1,T}}(polys...) TimeBasisFunction{T,degree+2,degree+1,degree}(dt, numfunctions, polys) end function (f::TimeBasisFunction)(t::Real) dt = timestep(f) ni = numintervals(f) t < -dt && return zero(t) i = floor(Int, (t/dt)) + 2 p = i <= ni ? f.polys[i] : f.polys[end] return p(t) end function assemblydata(tbf::TimeBasisFunction) T = scalartype(tbf) Δt = timestep(tbf) z = (0, zero(T)) t = Polynomial(zero(T), one(T)) num_cells = numfunctions(tbf) num_refs = degree(tbf)+1 max_num_funcs = numintervals(tbf) numfuncs = zeros(Int, num_cells, num_refs) data = fill(z, max_num_funcs, num_refs, num_cells) els = [ simplex(point((i-1)*Δt),point(i*Δt)) for i in 1:num_cells ] for k in 1 : numfunctions(tbf) tk = (k-1) * Δt for i in 1 : numintervals(tbf) # Focus on interval [(i-2)Δt,(i-1)Δt] p = tbf.polys[i] q = substitute(p,t-tk) c = k + i - 2 1 <= c <= num_cells || continue for d = 0 : degree(q) r = d + 1 w = q[d] j = (numfuncs[c,r] += 1) data[j,r,c] = (k,w) end end end return els, AssemblyData(data) end function temporalassemblydata(tbf; kmax=typemax(Int)) T = scalartype(tbf) Δt = timestep(tbf) t = Polynomial(zero(T), one(T)) num_cells = numfunctions(tbf) num_refs = degree(tbf)+1 has_zero_tail = all(tbf.polys[end].data .== 0) # @show has_zero_tail if has_zero_tail max_num_funcs = numintervals(tbf) # 3 else max_num_funcs = min(kmax, numfunctions(tbf)) end numfuncs = zeros(Int, num_cells, num_refs) data = fill((0,zero(T)), max_num_funcs, num_refs, num_cells) for k in 1 : min(kmax, numfunctions(tbf)) tk = (k-1) * Δt for i in 1 : numintervals(tbf)-1 p = tbf.polys[i] q = substitute(p,t+tk) c = k - i + 1 c < 1 && continue for d = 0 : degree(q) r = d + 1 w = q[d] j = (numfuncs[c,r] += 1) data[j,r,c] = (k,w) end end # Treat the half-open interval separately if !has_zero_tail p = tbf.polys[numintervals(tbf)] q = substitute(p, t+tk) c = k - numintervals(tbf) + 1 while c > 0 for d = 0 : degree(q) r = d+1 w = q[d] j = (numfuncs[c,r] += 1) data[j,r,c] = (k,w) end c = c-1 end end end return AssemblyData(data) end function assemblydata(tbf::TimeBasisDelta) T = scalartype(tbf) Δt = timestep(tbf) z = zero(scalartype(tbf)) w = one(scalartype(tbf)) num_cells = numfunctions(tbf) num_refs = 1 max_num_funcs = 1 num_funcs = zeros(Int, num_cells, num_refs) data = fill((0,z), max_num_funcs, num_refs, num_cells) els = [ simplex(point((i-0)*Δt),point((i+1)*Δt)) for i in 1:num_cells ] for k in 1 : numfunctions(tbf)-1 data[1,1,k] = (k+1,w) end return els, AssemblyData(data) end function convolve(f::TimeBasisFunction, g::TimeBasisFunction) # @info "BEAST.convolve: computing quadratic spline out of a pulse and a hat" dt = timestep(f) fg = timebasisspline2(dt, numfunctions(f), scalartype(f)) fg.polys = dt * fg.polys return fg end # function convolve(f::TimeBasisFunction{T,2,1,0}, g::TimeBasisFunction{T,2,1,0}) where {T} # @info "Convolving two pulses into a hat" # dt = timestep(f) # fg = timebasisshiftedlagrange(dt, numfunctions(f), 1, scalartype(f)) # fg.polys = dt * fg.polys # return fg # end function convolve(δ::TimeBasisDelta, g::TimeBasisFunction) # @info "Computing the trivial convolution between a delta and something else" return g end function convolve(f::TimeBasisFunction{T,2,1,0}, g::TimeBasisFunction{T,2,1,0}) where {T} # @info "Convolving two pulses into a hat" dt = BEAST.timestep(f) fg = timebasisshiftedlagrange(dt, numfunctions(f), 1, scalartype(f)) fg.polys = dt * fg.polys return fg end function BEAST.convolve( f::TimeBasisFunction{T,2,1,0}, g::TimeBasisFunction{T,N,D1,D}) where {T,N,D1,D} # @info "Convolving a left-of-origin pulse with a piecewise poly" @assert degree(f.polys[1]) == 0 @assert timestep(f) ≈ timestep(g) # The result of convolving with a LoO pulse extends the support # by Δt to the right. Δt = timestep(f) P = Polynomial{D1+1,T} polys = Vector{P}(undef, N+1) t = Polynomial{2,T}(SVector{2,T}(0, 1)) # Treat the leftmost interval separately polys[1] = integrate(g.polys[1], -Δt, 0) for i in 2:N q1 = -1 * substitute(integrate(g.polys[i-1], (i-2)*Δt, 0), t-Δt) q2 = integrate(g.polys[i], (i-2)*Δt, 0) polys[i] = q1 + q2 end q1 = -1 * substitute(integrate(g.polys[N], (N-1)*Δt, 0), t-Δt) q2 = integrate(g.polys[N], (N-1)*Δt, 0) polys[N+1] = q1 + q2 TimeBasisFunction{T,N+1,D1+1,D+1}( g.timestep, g.numfunctions, polys) end """ TimeBasisDeltaShifted{T} Represents a TimeBasisDelta{T} retarded by a fraction of the time step. """ struct TimeBasisDeltaShifted{T} <: AbstractTimeBasisFunction tbf :: TimeBasisDelta{T} shift :: T end scalartype(x::TimeBasisDeltaShifted) = scalartype(x.tbf) numfunctions(x::TimeBasisDeltaShifted) = numfunctions(x.tbf) refspace(x::TimeBasisDeltaShifted) = refspace(x.tbf) timestep(x::TimeBasisDeltaShifted) = timestep(x.tbf) numintervals(x::TimeBasisDeltaShifted) = numintervals(x.tbf) function assemblydata(tbds::TimeBasisDeltaShifted) tbf = tbds.tbf T = scalartype(tbf) Δt = timestep(tbf) z = zero(scalartype(tbf)) w = one(scalartype(tbf)) num_cells = numfunctions(tbf) num_refs = 1 max_num_funcs = 1 num_funcs = zeros(Int, num_cells, num_refs) data = fill((0,z), max_num_funcs, num_refs, num_cells) els = [ simplex(point((i-0+tbds.shift)*Δt),point((i+1+tbds.shift)*Δt)) for i in 1:num_cells ] for k in 1 : numfunctions(tbf) data[1,1,k] = (k,w) end return els, AssemblyData(data) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
7322
using SparseArrays """ ntrace(X::Space, γ::Mesh) Compute the normal trace of basis X on mesh γ. γ is assumed to be part of the boundary of geometry(X). """ function ntrace(X::DirectProductSpace{T}, γ) where T x = Space{T}[ntrace(s, γ) for s in X.factors] return DirectProductSpace(x) end function strace(X::DirectProductSpace{T}, γ) where T x = Space{T}[strace(s,γ) for s in X.factors] return DirectProductSpace(x) end function ntrace(X::Space, γ) # on_target = overlap_gpredicate(γ) # ad = assemblydata(X) x = refspace(X) E, ad, P = assemblydata(X) igeo = geometry(X) @assert dimension(γ) == dimension(igeo)-1 # Γ = geo # Dγ = dimension(γ) # Σ = skeleton(Γ,Dγ) ogeo = boundary(igeo) on_target = overlap_gpredicate(γ) ogeo = submesh(ogeo) do m,f ch = chart(m,f) on_target(ch) end # D = copy(transpose(connectivity(ogeo, igeo, abs))) D = connectivity(igeo, ogeo, abs) rows, vals = rowvals(D), nonzeros(D) T = scalartype(X) S = Shape{T} fns = [Vector{S}() for i in 1:numfunctions(X)] for (p,el) in enumerate(E) for (q,fc) in enumerate(faces(el)) on_target(fc) || continue # print(Q) # @assert norm(Q,Inf) != 0 r = 0 for k in nzrange(D,P[p]) vals[k] == q && (r = rows[k]; break) end @assert r != 0 fc1 = chart(ogeo, r) Q = ntrace(x, el, q, fc1) for i in 1:size(Q,1) for j in 1:size(Q,2) for (m,a) in ad[p,j] # j == q && println("bingo",j,q) v = a*Q[i,j] isapprox(v,0,atol=sqrt(eps(T))) && continue push!(fns[m], Shape(r, i, v)) end end end end end ntrace(X, ogeo, fns) end strace(X::Space, γ::Mesh) = strace(X, γ, Val{dimension(γ)+1}) function strace(X::Space, γ, dim1::Type{Val{2}}) x = refspace(X) on_target = overlap_gpredicate(γ) E, ad = assemblydata(X) geo = geometry(X) Γ = geo Σ = skeleton(Γ,1) # Allows for quick retrieval of the faces in Σ in a given cell of Γ. D = copy(transpose(connectivity(Σ, Γ, abs))) rows, vals = rowvals(D), nonzeros(D) T = scalartype(X) @assert numfunctions(X) != 0 fns = [Shape{T}[] for i in 1:numfunctions(X)] for (p,el) in enumerate(E) for q in 1:dimension(Γ)+1 # find the global index in Σ of the q-th face of the p-element e = 0 for k in nzrange(D,p) if vals[k] == q e = rows[k] break end end @assert e != 0 # make sure we use fc as oriented in Σ cell = CompScienceMeshes.indices(Σ,e) #Σ.faces[e] fc = chart(Σ, e) on_target(fc) || continue Q = strace(x,el,q,fc) for i in 1:size(Q,1) for j in 1:size(Q,2) for (m,a) in ad[p,j] v = a*Q[i,j] v == 0 && continue push!(fns[m], Shape(e, i, v)) end end end end end strace(X, Σ, fns) end function strace(X::Space, γ, dim1::Type{Val{3}}) x = refspace(X) E, ad, P = assemblydata(X) igeo = geometry(X) @assert dimension(γ) == dimension(igeo)-1 ogeo = boundary(igeo) on_target = overlap_gpredicate(γ) ogeo = submesh(ogeo) do m,f ch = chart(m,f) on_target(ch) end D = connectivity(igeo, ogeo, abs) rows, vals = rowvals(D), nonzeros(D) T = scalartype(X) S = Shape{T} fns = [Vector{S}() for i in 1:numfunctions(X)] for (p,el) in enumerate(E) for (q,fc) in enumerate(faces(el)) on_target(fc) || continue r = 0 for k in nzrange(D,P[p]) vals[k] == q && (r = rows[k]; break) end @assert r != 0 fc1 = chart(ogeo, r) Q = strace(x, el, q, fc1) for i in 1:size(Q,1) for j in 1:size(Q,2) for (m,a) in ad[p,j] v = a*Q[i,j] isapprox(v,0,atol=sqrt(eps(T))) && continue push!(fns[m], Shape(r, i, v)) end end end end end strace(X, ogeo, fns) end """ currently not working! """ # function ttrace(X::Space, γ) # # x = refspace(X) # on_target = overlap_gpredicate(γ) # # ad = assemblydata(X) # E, ad = assemblydata(X) # # geo = geometry(X) # Γ = geo # Dγ = dimension(γ) # Σ = skeleton(Γ,Dγ) # # D = copy(transpose(connectivity(Σ, Γ, abs))) # rows, vals = rowvals(D), nonzeros(D) # # T = scalartype(X) # fns = [Shape{T}[] for i in 1:numfunctions(X)] # # for (p,el) in enumerate(E) # # for (q,fc) in enumerate(faces(el)) # # on_target(fc) || (println("skip"); continue) # # print("\n") # Q = ttrace(x,el,q,fc) # # print(Q,q) # # find the global index in Σ of the q-th face of the p-element # r = 0 # for k in nzrange(D,p) # vals[k] == q && (r = rows[k]; break) # end # @assert r != 0 # for i in 1:size(Q,1) # for j in 1:size(Q,2) # for (m,a) in ad[p,j] # # if j == q # # # print("bingo",a,Q[i,j]) # # end # v = a*Q[i,j] # v == 0 && continue # push!(fns[m], Shape(r, i, v)) # end # end # end # # end # # end # # ttrace(X, Σ, fns) # end function ttrace(X::Space, γ) x = refspace(X) E, ad = assemblydata(X) igeo = geometry(X) @assert dimension(γ) == dimension(igeo)-1 ogeo = boundary(igeo) on_target = overlap_gpredicate(γ) ogeo = submesh(ogeo) do m,face ch = chart(m,face) on_target(ch) end D = connectivity(igeo, ogeo, abs) rows, vals = rowvals(D), nonzeros(D) T = scalartype(X) S = Shape{T} fns = [Vector{S}() for i in 1:numfunctions(X)] for (p,el) in enumerate(E) for (q,fc) in enumerate(faces(el)) on_target(fc) || continue r = 0 for k in nzrange(D,p) vals[k] == q && (r = rows[k]; break) end @assert r != 0 fc1 = chart(ogeo, r) @assert cartesian(center(fc)) ≈ cartesian(center(fc1)) Q = ttrace(x, el, q, fc1) for i in 1:size(Q,1) for j in 1:size(Q,2) for (m,a) in ad[p,j] v = a*Q[i,j] isapprox(v,0,atol=sqrt(eps(T))) && continue push!(fns[m], Shape(r, i, v)) end end end end end ttrace(X, ogeo, fns) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
902
struct BDM3DRefSpace{T} <: RefSpace{T,12} end function (f::BDM3DRefSpace)(p) u,v,w = parametric(p) tu = tangents(p,1) tv = tangents(p,2) tw = tangents(p,3) j = jacobian(p) d=1/j return SVector(( (value= 2*(-v*tu+v*tv)/j , divergence= 2*d), (value= 2*(-w*tu+w*tw)/j , divergence= 2*d), (value= 2*((u+v+w-1)*tu)/j , divergence= 2*d), (value= 2*(-w*tv+w*tw)/j , divergence= 2*d), (value= 2*((u+v+w-1)*tv)/j , divergence= 2*d), (value= 2*(u*tu-u*tv)/j , divergence= 2*d), (value= 2*((u+v+w-1)*tw)/j , divergence= 2*d), (value= 2*(u*tu-u*tw)/j , divergence= 2*d), (value= 2*(v*tv-v*tw)/j , divergence= 2*d), (value= 2*(u*tu)/j , divergence= 2*d), (value= 2*(v*tv)/j , divergence= 2*d), (value= 2*(w*tw)/j , divergence= 2*d) )) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2366
struct BDMRefSpace{T} <: RefSpace{T,6} end function (f::BDMRefSpace)(p) u,v = parametric(p) tu = tangents(p,1) tv = tangents(p,2) j = jacobian(p) d = 1/j return @SVector[ (value=(-v*tu+v*tv)/j, divergence=d), (value=(u+v-1)*tu/j, divergence=d), (value=(u+v-1)*tv/j, divergence=d), (value=(u*tu-u*tv)/j, divergence=d), (value=u*tu/j, divergence=d), (value=v*tv/j, divergence=d),] end divergence(ref::BDMRefSpace, sh, el) = Shape(sh.cellid, 1, sh.coeff/(2*volume(el))) const _vert_perms_bdm = [ (1,2,3), (2,3,1), (3,1,2), (2,1,3), (1,3,2), (3,2,1), ] const _dof_perms_bdm = [ (1,2,3,4,5,6), (5,6,1,2,3,4), (3,4,5,6,1,2), (4,3,2,1,6,5), (2,1,6,5,4,3), (6,5,4,3,2,1), ] function dof_permutation(::BDMRefSpace, vert_permutation) i = findfirst(==(tuple(vert_permutation...)), _vert_perms_bdm) return _dof_perms_bdm[i] end function dof_perm_matrix(::BDMRefSpace, vert_permutation) i = findfirst(==(tuple(vert_permutation...)), _vert_perms_bdm) return _dof_bdmperm_matrix[i] end dimtype(::BDMRefSpace, ::CompScienceMeshes.Simplex{U,2}) where {U} = Val{6} const _dof_bdmperm_matrix = [ @SMatrix[1 0 0 0 0 0; #1. {1,2,3} 0 1 0 0 0 0; 0 0 1 0 0 0; 0 0 0 1 0 0; 0 0 0 0 1 0; 0 0 0 0 0 1], @SMatrix[0 0 0 0 1 0; #2. {2,3,1} 0 0 0 0 0 1; 1 0 0 0 0 0; 0 1 0 0 0 0; 0 0 1 0 0 0; 0 0 0 1 0 0], @SMatrix[0 0 1 0 0 0; #3. {3,1,2} 0 0 0 1 0 0; 0 0 0 0 1 0; 0 0 0 0 0 1; 1 0 0 0 0 0; 0 1 0 0 0 0], @SMatrix[0 0 0 1 0 0; #4. {2,1,3} 0 0 1 0 0 0; 0 1 0 0 0 0; 1 0 0 0 0 0; 0 0 0 0 0 1; 0 0 0 0 1 0], @SMatrix[0 1 0 0 0 0; #5. {1,3,2} 1 0 0 0 0 0; 0 0 0 0 0 1; 0 0 0 0 1 0; 0 0 0 1 0 0; 0 0 1 0 0 0], @SMatrix[0 0 0 0 0 1; #6. {3,2,1} 0 0 0 0 1 0; 0 0 0 1 0 0; 0 0 1 0 0 0; 0 1 0 0 0 0; 1 0 0 0 0 0] ]
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
9141
# T: coeff type # Degree: degree # Dim1: dimension of the support + 1 mutable struct LagrangeRefSpace{T,Degree,Dim1,NF} <: RefSpace{T,NF} end numfunctions(s::LagrangeRefSpace{T,D,2}) where {T,D} = D+1 numfunctions(s::LagrangeRefSpace{T,0,3}) where {T} = 1 numfunctions(s::LagrangeRefSpace{T,1,3}) where {T} = 3 numfunctions(s::LagrangeRefSpace{T,2,3}) where {T} = 6 valuetype(ref::LagrangeRefSpace{T}, charttype) where {T} = SVector{numfunctions(ref), Tuple{T,T}} # Evaluate constant lagrange elements on anything (ϕ::LagrangeRefSpace{T,0})(tp) where {T} = SVector(((value=one(T), derivative=zero(T)),)) # Evaluate linear Lagrange elements on a segment function (f::LagrangeRefSpace{T,1,2})(mp) where T u = mp.bary[1] j = jacobian(mp) SVector( (value= u, derivative=-1/j), (value=1-u, derivative= 1/j)) end # Evaluete linear lagrange elements on a triangle function (f::LagrangeRefSpace{T,1,3})(t) where T u,v,w, = barycentric(t) # SVector( # (value=u,), # (value=v,), # (value=w,)) j = jacobian(t) p = t.patch σ = sign(dot(normal(t), cross(p[1]-p[3],p[2]-p[3]))) SVector( (value=u, curl=σ*(p[3]-p[2])/j), (value=v, curl=σ*(p[1]-p[3])/j), (value=w, curl=σ*(p[2]-p[1])/j)) end """ f(tangent_space, Val{:withcurl}) Compute the values of the shape functions together with their curl. """ # function (f::LagrangeRefSpace{T,1,3})(t, ::Type{Val{:withcurl}}) where T # # Evaluete linear Lagrange elements on a triange, together with their curl # j = jacobian(t) # u,v,w, = barycentric(t) # p = t.patch # σ = sign(dot(normal(t), cross(p[1]-p[3],p[2]-p[3]))) # SVector( # (value=u, curl=σ*(p[3]-p[2])/j), # (value=v, curl=σ*(p[1]-p[3])/j), # (value=w, curl=σ*(p[2]-p[1])/j) # ) # end # Evaluate constant Lagrange elements on a triangle, with their curls function (f::LagrangeRefSpace{T,0,3})(t, ::Type{Val{:withcurl}}) where T i = one(T) z = zero(cartesian(t)) SVector(((value=i, curl=z,),)) end function curl(ref::LagrangeRefSpace{T,1,3} where {T}, sh, el) sh1 = Shape(sh.cellid, mod1(sh.refid+1,3), -sh.coeff) sh2 = Shape(sh.cellid, mod1(sh.refid+2,3), +sh.coeff) return [sh1, sh2] end function gradient(ref::LagrangeRefSpace{T,1,4}, sh, tet) where {T} this_vert = tet.vertices[sh.refid] # other_verts = deleteat(tet.vertices, sh.refid) # opp_face = simplex(other_verts...) opp_face = faces(tet)[sh.refid] ctr_opp_face = center(opp_face) n = normal(ctr_opp_face) h = -dot(this_vert - cartesian(ctr_opp_face), n) @assert h > 0 gradval = -(1/h)*n output = Vector{Shape{T}}() for (i,edge) in enumerate(CompScienceMeshes.edges(tet)) ctr_edge = center(edge) tgt = tangents(ctr_edge,1) tgt = normalize(tgt) lgt = volume(edge) cff = -lgt * dot(tgt, gradval) isapprox(cff, 0, atol=sqrt(eps(T))) && continue push!(output, Shape(sh.cellid, i, sh.coeff * cff)) end return output end function gradient(ref::LagrangeRefSpace{T,1,3} where {T}, sh, el) sh1 = Shape(sh.cellid, mod1(sh.refid+1,3), +sh.coeff) sh2 = Shape(sh.cellid, mod1(sh.refid+2,3), -sh.coeff) return [sh1, sh2] end function gradient(ref::LagrangeRefSpace{T,1,2}, sh, seg) where {T} sh.refid == 1 && return [Shape(sh.cellid, 1, +sh.coeff/volume(seg))] @assert sh.refid == 2 return [Shape(sh.cellid, 1, -sh.coeff/volume(seg))] end function strace(x::LagrangeRefSpace, cell, localid, face) Q = zeros(scalartype(x),2,3) p1 = neighborhood(face, 1) p2 = neighborhood(face, 0) u1 = carttobary(cell, cartesian(p1)) u2 = carttobary(cell, cartesian(p2)) P1 = neighborhood(cell, u1) P2 = neighborhood(cell, u2) vals1 = x(P1) vals2 = x(P2) for j in 1:numfunctions(x) Q[1,j] = vals1[j].value Q[2,j] = vals2[j].value end Q end function strace(x::LagrangeRefSpace{T, 1, 4, 4}, cell, localid, face) where {T} #T = scalartype(x) t = zeros(T, 3, 4) for (k,fvert) in enumerate(face.vertices) for (l,cvert) in enumerate(cell.vertices) nrm = norm(fvert - cvert) if isapprox(nrm, 0, atol=sqrt(eps(T))) t[k,l] = T(1.0) break end end end return t end function restrict(refs::LagrangeRefSpace{T,0}, dom1, dom2) where T #Q = eye(T, numfunctions(refs)) Q = Matrix{T}(I, numfunctions(refs), numfunctions(refs)) end function restrict(f::LagrangeRefSpace{T,1}, dom1, dom2) where T D = numfunctions(f) Q = zeros(T, D, D) # for each point of the new domain for i in 1:D v = dom2.vertices[i] # find the barycentric coordinates in dom1 uvn = carttobary(dom1, v) # evaluate the shape functions in this point x = neighborhood(dom1, uvn) fx = f(x) for j in 1:D Q[j,i] = fx[j][1] end end return Q end ## Quadratic Lagrange element on a triangle function (f::LagrangeRefSpace{T,2,3})(t) where T u,v,w, = barycentric(t) j = jacobian(t) p = t.patch #curl=(p[3]-p[2])/j), # (value=v, curl=(p[1]-p[3])/j), # (value=w, curl=(p[2]-p[1])/j) σ = sign(dot(normal(t), cross(p[1]-p[3],p[2]-p[3]))) SVector( (value=u*(2*u-1), curl=σ*(p[3]-p[2])*(4u-1)/j), (value=v*(2*v-1), curl=σ*(p[1]-p[3])*(4v-1)/j), (value=w*(2*w-1), curl=σ*(p[2]-p[1])*(4w-1)/j), (value=4*v*w, curl=4*σ*(w*(p[1]-p[3])+v*(p[2]-p[1]))/j), (value=4*w*u, curl=4*σ*(w*(p[3]-p[2])+u*(p[2]-p[1]))/j), (value=4*u*v, curl=4*σ*(u*(p[1]-p[3])+v*(p[3]-p[2]))/j), ) end # function (f::LagrangeRefSpace{T,2,3})(t, ::Type{Val{:withcurl}}) where T # # Evaluete quadratic Lagrange elements on a triange, together with their curl # j = jacobian(t) # u,v,w, = barycentric(t) # p = t.patch # σ = sign(dot(normal(t), cross(p[1]-p[3],p[2]-p[3]))) # SVector( # (value=u*(2*u-1), curl=σ*(p[3]-p[2])*(4u-1)/j), # (value=v*(2*v-1), curl=σ*(p[1]-p[3])*(4v-1)/j), # (value=w*(2*w-1), curl=σ*(p[2]-p[1])*(4w-1)/j), # (value=4*v*w, curl=4*σ*(w*(p[1]-p[3])+v*(p[2]-p[1]))/j), # (value=4*w*u, curl=4*σ*(w*(p[3]-p[2])+u*(p[2]-p[1]))/j), # (value=4*u*v, curl=4*σ*(u*(p[1]-p[3])+v*(p[3]-p[2]))/j), # ) # end function curl(ref::LagrangeRefSpace{T,2,3} where {T}, sh, el) #curl of lagc0d2 as combination of bdm functions z=zero(typeof(sh.coeff)) if sh.refid < 4 sh1 = Shape(sh.cellid, mod1(2*sh.refid+1,6), +sh.coeff) sh2 = Shape(sh.cellid, mod1(2*sh.refid+2,6), -3*sh.coeff) sh3 = Shape(sh.cellid, mod1(2*sh.refid+3,6), +3*sh.coeff) sh4 = Shape(sh.cellid, mod1(2*sh.refid+4,6), -sh.coeff) else sh1 = Shape(sh.cellid, mod1(2*sh.refid+4,6), z*sh.coeff) sh2 = Shape(sh.cellid, mod1(2*sh.refid+5,6), -4*sh.coeff) sh3 = Shape(sh.cellid, mod1(2*sh.refid+6,6), +4*sh.coeff) sh4 = Shape(sh.cellid, mod1(2*sh.refid+7,6), z*sh.coeff) end return [sh1, sh2, sh3, sh4] end const _vert_perms_lag = [ (1,2,3), (2,3,1), (3,1,2), (2,1,3), (1,3,2), (3,2,1), ] const _dof_perms_lag0 = [ (1), (1), (1), (1), (1), (1), ] const _dof_perms_lag1 = [ (1,2,3), (3,1,2), (2,3,1), (2,1,3), (1,3,2), (3,2,1), ] function dof_permutation(::LagrangeRefSpace{<:Any,0}, vert_permutation) i = findfirst(==(tuple(vert_permutation...)), _vert_perms_lag) return _dof_perms_lag0[i] end function dof_permutation(::LagrangeRefSpace{<:Any,1}, vert_permutation) i = findfirst(==(tuple(vert_permutation...)), _vert_perms_lag) return _dof_perms_lag1[i] end function dof_perm_matrix(::LagrangeRefSpace{<:Any,0}, vert_permutation) i = findfirst(==(tuple(vert_permutation...)), _vert_perms_rt) @assert i != nothing return _dof_lag0perm_matrix[i] end function dof_perm_matrix(::LagrangeRefSpace{<:Any,1}, vert_permutation) i = findfirst(==(tuple(vert_permutation...)), _vert_perms_rt) @assert i != nothing return _dof_rtperm_matrix[i] end const _dof_lag0perm_matrix = [ @SMatrix[1], # 1. {1,2,3} @SMatrix[1], # 2. {2,3,1} @SMatrix[1], # 3. {3,1,2} @SMatrix[1], # 4. {2,1,3} @SMatrix[1], # 5. {1,3,2} @SMatrix[1] # 6. {3,2,1} ] function (ϕ::LagrangeRefSpace{T, 1, 4, 4})(lag) where T u, v, w = parametric(lag) tu = tangents(lag, 1) tv = tangents(lag, 2) tw = tangents(lag, 3) B = [tu tv tw] A = inv(transpose(B)) # gradient in u,v,w (unit tetrahedron) gr1=SVector{3, T}(1.0, 0.0, 0.0) gr2=SVector{3, T}(0.0, 1.0, 0.0) gr3=SVector{3, T}(0.0, 0.0, 1.0) gr4=SVector{3, T}(-1.0, -1.0, -1.0) return SVector(( (value = u, gradient = A*gr1), (value = v, gradient = A*gr2), (value = w, gradient = A*gr3), (value = T(1.0)-u-v-w, gradient = A*gr4) )) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
524
struct NCrossBDMRefSpace{T} <: RefSpace{T,6} end function (f::NCrossBDMRefSpace{T})(p) where T u,v = parametric(p) n = normal(p) tu = tangents(p,1) tv = tangents(p,2) j = jacobian(p) d = 1/j return @SVector[ (value= n × (-v*tu+v*tv)/j, curl=d), (value= n × ((u+v-1)*tu)/j, curl=d), (value= n × ((u+v-1)*tv) /j, curl=d), (value= n × (u*tu-u*tv)/j, curl=d), (value= n × (u*tu)/j, curl=d), (value= n × (v*tv)/j, curl=d),] end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1035
mutable struct ND2RefSpace{T} <: RefSpace{T,8} end function (ϕ::ND2RefSpace)(nbd) u, v = parametric(nbd) n = normal(nbd) j = jacobian(nbd) tu = tangents(nbd,1) tv = tangents(nbd,2) d = 2/j inv_j = 1/j return SVector(( (value= n × ((8*u^2+8*u*v-12*u-6*v+4)*tu + (2*v*(4*u+4*v-3))*tv)*inv_j, curl=(24*u+24*v-18)*inv_j), (value= n × ((-8*u*v+2*u+6*v-2)*tu + (4*v*(-2*v+1))*tv)*inv_j, curl=(6-24*v)*inv_j), (value= n × ((4*u*(1-2*u))*tu + (-8*u*v+6*u+2*v-2)*tv)*inv_j, curl=(6-24*u)*inv_j), (value= n × ((2*u*(4*u+4*v-3))*tu + (8*u*v-6*u+8*v^2-12*v+4)*tv)*inv_j, curl=(24*u+24*v-18)*inv_j), (value= n × ((2u*(1-4v))*tu + (4v*(1-2v))*tv)*inv_j, curl=(6-24*v)*inv_j), (value= n × ((4u*(1-2u))*tu + (2v*(1-4u))*tv)*inv_j, curl=(6-24*u)*inv_j), (value= n × ((8*u*(-2*u-v+2))*tu + (8*v*(-2*u-v+1))*tv)*inv_j, curl=(-48*u-24*v+24)*inv_j), (value= n × ((8*u*(-u-2*v+1))*tu + (8*v*(-u-2*v+2))*tv)*inv_j, curl=(-24*u-48*v+24)*inv_j) )) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
5181
struct NDLCCRefSpace{T} <: RefSpace{T,6} end function valuetype(ref::NDLCCRefSpace{T}, charttype::Type) where {T} SVector{universedimension(charttype),T} end function (ϕ::NDLCCRefSpace)(ndlc) u,v,w = parametric(ndlc) j = jacobian(ndlc) tu = tangents(ndlc,1) tv = tangents(ndlc,2) tw = tangents(ndlc,3) #B = [tv-tu tw-tu -tu] B = [tu tv tw] BMT = transpose(inv(B)) du = SVector{3}(BMT[:,1]) dv = SVector{3}(BMT[:,2]) dw = SVector{3}(BMT[:,3]) #Choose 1-(0,0,0), 2-(1,0,0), 3-(0,1,0), 4-(0,0,1) #Now it is listed as: #(1,2) [1-v-w,u,u] (direction: from 1 to 2) #(1,3) [v,1-u-w,v] #(1,4) [w,w,1-u,v] #(2,3) [-v,u,0] #(2,4) [-w,0,u] #(3,4) [0,-w,v] # return SVector(( # (value=(BMT*[-v,u,0]) ,curl=(B*[0,0,2])/j) , # (value=(BMT*[-w,0,u]) ,curl=(B*[0,-2,0])/j), # (value=(BMT*[(w+v-1),-u,-u]),curl=(B*[0,2,-2])/j), # (value=(BMT*[0,-w,v]) ,curl=(B*[2,0,0])/j) , # (value=(BMT*[-v,(u+w-1),-v]),curl=(B*[-2,0,2])/j), # (value=(BMT*[-w,-w,(u+v-1)]),curl=(B*[2,-2,0])/j) # )) return SVector(( (value=-v*du + u*dv, curl=(2*tw)/j), (value=-w*du + u*dw, curl=(-2*tv)/j), (value=(w+v-1)*du - u*dv - u*dw, curl=(2*tv - 2*tw)/j), (value=-w*dv + v*dw, curl=(2*tu)/j), (value=-v*du + (u+w-1)*dv -v*dw, curl=(-2*tu + 2*tw)/j), (value=-w*du -w*dv + (u+v-1)*dw, curl=(2*tu -2*tv)/j), )) ## return SVector(( ## (value=(BMT*[(w+v-1),-u,-u]),curl=(B*[0,2,-2])/j), ## (value=(BMT*[-v,(u+w-1),-v]) ,curl=(B*[-2,0,2])/j), ## (value=(BMT*[-w,-w,(u+v-1)]) ,curl=(B*[2,-2,0])/j), ## (value=(BMT*[-v,u,0]) ,curl=(B*[0,0,2])/j) , ## (value=(BMT*[-w,0,u]) ,curl=(B*[0,-2,0])/j), ## (value=(BMT*[0,-w,v]) ,curl=(B*[2,0,0])/j) ## )) end #check orientation function curl(ref::NDLCCRefSpace, sh, el) a = [4,2,3,4,1,2]##[2,1,1,1,2,4]#[2,1,4,4,3,2]#[4,2,3,4,1,2] b = [3,4,2,1,3,1]##[3,2,4,3,4,3]#[4,3,3,1,2,1]#[3,4,2,1,3,1] sh1 = Shape(sh.cellid, b[sh.refid], -sh.coeff) sh2 = Shape(sh.cellid, a[sh.refid], sh.coeff) return [sh1,sh2] end function restrict(ϕ::NDLCCRefSpace{T}, dom1, dom2) where {T} # dom2 is the smaller of the domains K = numfunctions(ϕ) D = dimension(dom1) @assert K == 6 @assert D == 3 @assert D == dimension(dom2) Q = zeros(T,K,K) for (i,edge) in enumerate(CompScienceMeshes.edges(dom2)) p = center(edge) c = cartesian(p) A = volume(edge) t = tangents(p,1) t = normalize(t) u = carttobary(dom1, c) x = neighborhood(dom1, u) y = ϕ(x) for j in 1:K Q[j,i] = -dot(y[j].value, t) * A end end return Q end function ttrace(x::NDLCCRefSpace, el, q, fc) # el: the supporting chart of the input # q: the local index of the face of el on which we compute the trace # fc: the chart on which we compute the trace el_ctr = cartesian(center(el)) fc_ctr = cartesian(center(fc)) T = scalartype(x) y = BEAST.RTRefSpace{T}() t = zeros(scalartype(x),3,6) for (j,edgej) in enumerate(CompScienceMeshes.edges(el)) for (i,edgei) in enumerate(CompScienceMeshes.edges(fc)) nbdi = center(edgei) nbdj = neighborhood(el, carttobary(el, cartesian(nbdi))) @assert isapprox(cartesian(nbdi), cartesian(nbdj), atol=1e-4) xval = x(nbdj)[j].value # yval = y(nbdi)[i].value tgt = -tangents(nbdi,1) nrm = normal(fc) bnr = cross(normalize(tgt), nrm) @assert dot(bnr, cartesian(nbdi)-fc_ctr) > 0 @assert norm(bnr) ≈ 1 dot(nrm, fc_ctr - el_ctr) < 0 && (nrm = -nrm) t[i,j] = dot(bnr, nrm × xval) * volume(edgei) end end return t # # # fa = SArray{Tuple{2},Int,1,2} # # te = SArray{Tuple{3},Int,1,3} # j = 0 # y = BEAST.NDRefSpace{scalartype(x)}() # n = normal(fc) # for fac in faces(el) # j += 1 # j == q && continue # # fac != fc || continue # #vind locale index (i) in fc van de edge die in zowel fc als fac ligt # A = setdiff(fc.vertices,setdiff(fc.vertices,fac.vertices)) # # @show length(A) # @assert length(A) == 2 # edg = fa([findfirst(isequal(A[1]), fc.vertices),findfirst(isequal(A[2]), fc.vertices)]) # i = abs(CompScienceMeshes.relorientation(edg,te([1,2,3]))) # #i = findfirst(isequal(setdiff(fcv,facv)[1]), fcv) # edg_chart = simplex(fc.vertices[edg[1]], fc.vertices[edg[2]]) # edg_centr = cartesian(center(edg_chart)) # p = neighborhood(fc, carttobary(fc, edg_centr)) # r = neighborhood(el, carttobary(el, edg_centr)) # yp = y(p)[i].value # xr = x(r)[j].value # tgt = edg_chart.vertices[1] - edg_chart.vertices[2] # ypt = dot(yp, tgt) # xrt = dot(n × xr, tgt) # # t[i,j] = volume(el)/(volume(fac)*norm(A[1]-A[2])) # t[i,j] = xrt / ypt # end # return t end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
3259
struct NDLCDRefSpace{T} <: RefSpace{T,4} end function valuetype(ref::NDLCDRefSpace{T}, charttype::Type) where {T} SVector{universedimension(charttype),T} end function (ϕ::NDLCDRefSpace)(ndlc) u,v,w = parametric(ndlc) j = jacobian(ndlc) tu = tangents(ndlc,1) tv = tangents(ndlc,2) tw = tangents(ndlc,3) # B = [tu tv tw] # return SVector(( # (value=(2*B*[(u-1),v,w]/j),divergence=(6/j)), # (value=(2*B*[u,(v-1),w]/j),divergence=(6/j)), # (value=(2*B*[u,v,(w-1)]/j),divergence=(6/j)), # (value=(2*B*[u,v,w]/j) ,divergence=(6/j)) # )) return SVector(( (value=(2*((u-1)*tu + v*tv + w*tw)/j), divergence=(6/j)), (value=(2*(u*tu + (v-1)*tv + w*tw)/j), divergence=(6/j)), (value=(2*(u*tu + v*tv + (w-1)*tw)/j),divergence=(6/j)), (value=(2*(u*tu + v*tv + w*tw)/j) ,divergence=(6/j)) )) end function ntrace(x::NDLCDRefSpace, el, q, fc) t = zeros(scalartype(x),1,4) t[q] = 1 / volume(fc) return t end """ Does not give the correct result for an imput basis with non-vanishing input basis on the boundary """ function ttrace(x::NDLCDRefSpace, el, q, fc) # el: the supporting chart of the input # q: the local index of the face of el on which we compute the trace # fc: the chart on which we compute the trace t = zeros(scalartype(x),3,4) fa = SArray{Tuple{2},Int,1,2} te = SArray{Tuple{3},Int,1,3} j = 0 y = BEAST.NDRefSpace{scalartype(x)}() n = normal(fc) for fac in faces(el) j += 1 j == q && continue # fac != fc || continue #vind locale index (i) in fc van de edge die in zowel fc als fac ligt A = setdiff(fc.vertices,setdiff(fc.vertices,fac.vertices)) # @show length(A) @assert length(A) == 2 edg = fa([findfirst(isequal(A[1]), fc.vertices),findfirst(isequal(A[2]), fc.vertices)]) i = abs(CompScienceMeshes.relorientation(edg,te([1,2,3]))) #i = findfirst(isequal(setdiff(fcv,facv)[1]), fcv) edg_chart = simplex(fc.vertices[edg[1]], fc.vertices[edg[2]]) edg_centr = cartesian(center(edg_chart)) p = neighborhood(fc, carttobary(fc, edg_centr)) r = neighborhood(el, carttobary(el, edg_centr)) yp = y(p)[i].value xr = x(r)[j].value tgt = edg_chart.vertices[1] - edg_chart.vertices[2] ypt = dot(yp, tgt) xrt = dot(n × xr, tgt) # t[i,j] = volume(el)/(volume(fac)*norm(A[1]-A[2])) t[i,j] = xrt / ypt end return t end divergence(ref::NDLCDRefSpace, sh, el) = Shape(sh.cellid, 1, sh.coeff/volume(el)) function restrict(ϕ::NDLCDRefSpace{T}, dom1, dom2) where {T} # dom2 is the smaller of the domains K = numfunctions(ϕ) D = dimension(dom1) @assert K == 4 @assert D == 3 @assert D == dimension(dom2) Q = zeros(T,K,K) for (i,face) in enumerate(faces(dom2)) p = center(face) c = cartesian(p) A = volume(face) m = normal(p) # u = carttobary(dom1,cartesian(p)) u = carttobary(dom1, c) x = neighborhood(dom1, u) y = ϕ(x) for j in 1:K Q[j,i] = dot(y[j].value, m) * A end end return Q end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1676
""" Local shape function `r` is the one whose field lines straddle local edge `r`, which is the edge adjacent to vertex `r`. This is not the edge starting at vertex `r`. The downside of this local numbering scheme is that it cannot be extended to cells that are not simplices because there is no well defined concept of adjacent-ness. """ mutable struct NDRefSpace{T} <: RefSpace{T,3} end function (ϕ::NDRefSpace)(nbd) u, v = parametric(nbd) n = normal(nbd) j = jacobian(nbd) tu = tangents(nbd,1) tv = tangents(nbd,2) d = 2/j return SVector(( (value = n × (tu*(u-1) + tv*v ) / j, curl = d), (value = n × (tu*u + tv*(v-1)) / j, curl = d), (value = n × (tu*u + tv*v ) / j, curl = d) )) end function restrict(ϕ::NDRefSpace{T}, dom1, dom2) where T K = numfunctions(ϕ) D = dimension(dom1) @assert K == 3 @assert D == 2 @assert D == dimension(dom2) Q = zeros(T,K,K) for i in 1:K # find the center of edge i of dom2 a = dom2.vertices[mod1(i+1,D+1)] b = dom2.vertices[mod1(i+2,D+1)] c = (a + b) / 2 # find the tangent in this point to the edge t = b - a # l = norm(t) # n = dom2.normals[1] # m = cross(t, n) / l # dom1 : the smaller domain on which the reference functions are def'd # dom2 : the larger domain on which the function to be restrcited is def'd u = carttobary(dom1, c) x = neighborhood(dom1, u) y = ϕ(x) for j in 1:K # Q[j,i] = dot(y[j][1], m) * l Q[j,i] = dot(y[j][1], t) end end return Q end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
5938
struct RT2RefSpace{T} <: RefSpace{T,8} end function (f::RT2RefSpace)(p) u, v = parametric(p) j = jacobian(p) tu = tangents(p,1) tv = tangents(p,2) inv_j = 1/j # return SVector( # (value=-(4u*(1-2u))*tu - (2v*(1-4u))*tv, divergence=inv_j), # (value=-(2u*(1-4v))*tu - (4v*(1-2v))*tv, divergence=inv_j), # (value=(-8*u^2-8*u*v+12*u+6*v-4)*tu + (2*v*(-4*u-4*v+3))*tv, divergence=inv_j), # (value=(8*u*v-2*u-6*v+2)*tu + (4*v*(2*v-1))*tv, divergence=inv_j), # (value=-(2*u*(4*u+4*v-3))*tu - (8*u*v-6*u+8*v^2-12*v+4)*tv, divergence=inv_j), # (value=-(4*u*(1-2*u))*tu - (-8*u*v+6*u+2*v-2)*tv, divergence=inv_j), # (value=(8*u*(-2*u-v+2))*tu + (8*v*(-2*u-v+1))*tv, divergence=inv_j), # (value=(8*u*(-u-2*v+1))*tu + (8*v*(-u-2*v+2))*tv, divergence=inv_j), # ) return SVector( (value=((8*u^2+8*u*v-12*u-6*v+4)*tu + (2*v*(4*u+4*v-3))*tv)*inv_j, divergence=(24*u+24*v-18)*inv_j), (value=((-8*u*v+2*u+6*v-2)*tu + (4*v*(-2*v+1))*tv)*inv_j, divergence=(6-24*v)*inv_j), (value=((4*u*(1-2*u))*tu + (-8*u*v+6*u+2*v-2)*tv)*inv_j, divergence=(6-24*u)*inv_j), (value=((2*u*(4*u+4*v-3))*tu + (8*u*v-6*u+8*v^2-12*v+4)*tv)*inv_j, divergence=(24*u+24*v-18)*inv_j), (value=((2u*(1-4v))*tu + (4v*(1-2v))*tv)*inv_j, divergence=(6-24*v)*inv_j), (value=((4u*(1-2u))*tu + (2v*(1-4u))*tv)*inv_j, divergence=(6-24*u)*inv_j), (value=((8*u*(-2*u-v+2))*tu + (8*v*(-2*u-v+1))*tv)*inv_j, divergence=(-48*u-24*v+24)*inv_j), (value=((8*u*(-u-2*v+1))*tu + (8*v*(-u-2*v+2))*tv)*inv_j, divergence=(-24*u-48*v+24)*inv_j) ) end function interpolate(fields, interpolant::BEAST.RT2RefSpace, chart) T = coordtype(chart) Q = Any[] refchart = CompScienceMeshes.domain(chart).simplex nfields = length(fields(center(chart))) for (edge, refedge) in zip(faces(chart), faces(refchart)) l0 = zeros(T,nfields) l1 = zeros(T,nfields) qps = CompScienceMeshes.quadpoints(edge,4) for (p_edge,w) in qps s = parametric(p_edge) # x = cartesian(p_edge) # u = carttobary(chart, x) p_refedge = neighborhood(refedge,s) u = cartesian(p_refedge) p_refchart = neighborhood(refchart, u) t_refedge = tangents(p_refedge,1) m_refedge = point(-t_refedge[2], t_refedge[1]) m_refedge /= norm(m_refedge) q0ref = (-1) * (1-s[1]) * m_refedge q1ref = (-1) * s[1] * m_refedge nxq0ref = point(-q0ref[2], q0ref[1]) nxq1ref = point(-q1ref[2], q1ref[1]) p_chart = neighborhood(chart, u) n_chart = normal(p_chart) J_chart = jacobian(p_chart) t1 = tangents(p_chart,1) t2 = tangents(p_chart,2) q0 = -n_chart × (nxq0ref[1]*t1 + nxq0ref[2]*t2) / J_chart q1 = -n_chart × (nxq1ref[1]*t1 + nxq1ref[2]*t2) / J_chart vals = fields(p_chart) J_edge = jacobian(p_edge) J_refedge = jacobian(p_refedge) l0 .+= [w * dot(f,q0) * J_chart / J_edge * J_refedge for f in vals] l1 .+= [w * dot(f,q1) * J_chart / J_edge * J_refedge for f in vals] end push!(Q,l0) push!(Q,l1) end l6 = zeros(T,nfields) l7 = zeros(T,nfields) qps = CompScienceMeshes.quadpoints(chart, 4) for (p,w) in qps q6ref = point(1,0) q7ref = point(0,1) nxq6ref = point(-q6ref[2], q6ref[1]) nxq7ref = point(-q7ref[2], q7ref[1]) J_chart = jacobian(p) n_chart = normal(p) t1 = tangents(p,1) t2 = tangents(p,2) q6 = -n_chart × (nxq6ref[1] * t1 + nxq6ref[2] * t2) / J_chart q7 = -n_chart × (nxq7ref[1] * t1 + nxq7ref[2] * t2) / J_chart vals = fields(p) l6 .+= [w * dot(f,q6) for f in vals] l7 .+= [w * dot(f,q7) for f in vals] end push!(Q,l6) push!(Q,l7) return hcat(Q...) end function dof_perm_matrix(::RT2RefSpace, vert_permutation) i = findfirst(==(tuple(vert_permutation...)), _vert_perms_rt) @assert i != nothing return _dof_rt2perm_matrix[i] end const _dof_rt2perm_matrix = [ @SMatrix[1 0 0 0 0 0 0 0; #1. {1,2,3} 0 1 0 0 0 0 0 0; 0 0 1 0 0 0 0 0; 0 0 0 1 0 0 0 0; 0 0 0 0 1 0 0 0; 0 0 0 0 0 1 0 0; 0 0 0 0 0 0 1 0; 0 0 0 0 0 0 0 1], @SMatrix[0 0 0 0 1 0 0 0; #2. {2,3,1} 0 0 0 0 0 1 0 0; 1 0 0 0 0 0 0 0; 0 1 0 0 0 0 0 0; 0 0 1 0 0 0 0 0; 0 0 0 1 0 0 0 0; 0 0 0 0 0 0 0 -1; 0 0 0 0 0 0 1 -1], @SMatrix[0 0 1 0 0 0 0 0; #3. {3,1,2} 0 0 0 1 0 0 0 0; 0 0 0 0 1 0 0 0; 0 0 0 0 0 1 0 0; 1 0 0 0 0 0 0 0; 0 1 0 0 0 0 0 0; 0 0 0 0 0 0 -1 1; 0 0 0 0 0 0 -1 0], @SMatrix[0 0 0 1 0 0 0 0; #4. {2,1,3} 0 0 1 0 0 0 0 0; 0 1 0 0 0 0 0 0; 1 0 0 0 0 0 0 0; 0 0 0 0 0 1 0 0; 0 0 0 0 1 0 0 0; 0 0 0 0 0 0 0 1; 0 0 0 0 0 0 1 0], @SMatrix[0 1 0 0 0 0 0 0; #5. {1,3,2} 1 0 0 0 0 0 0 0; 0 0 0 0 0 1 0 0; 0 0 0 0 1 0 0 0; 0 0 0 1 0 0 0 0; 0 0 1 0 0 0 0 0; 0 0 0 0 0 0 1 -1; 0 0 0 0 0 0 0 -1], @SMatrix[0 0 0 0 0 1 0 0; #6. {3,2,1} 0 0 0 0 1 0 0 0; 0 0 0 1 0 0 0 0; 0 0 1 0 0 0 0 0; 0 1 0 0 0 0 0 0; 1 0 0 0 0 0 0 0; 0 0 0 0 0 0 -1 0; 0 0 0 0 0 0 -1 1] ]
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
4358
struct RTRefSpace{T} <: DivRefSpace{T,3} end # valuetype(ref::RTRefSpace{T}, charttype) where {T} = SVector{3,Tuple{SVector{universedimension(charttype),T},T}} function valuetype(ref::RTRefSpace{T}, charttype::Type) where {T} SVector{universedimension(charttype),T} end function (ϕ::RTRefSpace)(mp) u, v = parametric(mp) j = jacobian(mp) tu = tangents(mp,1) tv = tangents(mp,2) inv_j = 1/j d = 2 * inv_j u_tu = u*tu v_tv = v*tv return SVector(( (value=(u_tu-tu + v_tv )*inv_j, divergence=d), (value=(u_tu + v_tv-tv)*inv_j, divergence=d), (value=(u_tu + v_tv )*inv_j, divergence=d) )) end divergence(ref::RTRefSpace, sh, el) = Shape(sh.cellid, 1, sh.coeff/volume(el)) """ ntrace(refspace, element, localindex, face) Compute the normal trace of all local shape functions on `elements` belonging to `refspace` on `face`. This function returns a matrix expressing the traces of local shape functions in `refspace` as linear combinations of functions in the local trace space. Cf. `restrict`. `localindex` is the index of `face` in the enumeration of faces of `elements`. In many special cases knowing this index allows for highly optimised implementations. """ function ntrace(x::RTRefSpace, el, q, fc) t = zeros(scalartype(x),1,3) t[q] = 1 / volume(fc) return t end const _vert_perms_rt = [ (1,2,3), (2,3,1), (3,1,2), (2,1,3), (1,3,2), (3,2,1), ] const _dof_perms_rt = [ (1,2,3), (3,1,2), (2,3,1), (2,1,3), (1,3,2), (3,2,1), ] function dof_permutation(::RTRefSpace, vert_permutation) i = something(findfirst(==(tuple(vert_permutation...)), _vert_perms_rt),0) @assert i != 0 return _dof_perms_rt[i] end function dof_perm_matrix(::RTRefSpace, vert_permutation) i = findfirst(==(tuple(vert_permutation...)), _vert_perms_rt) @assert i != nothing return _dof_rtperm_matrix[i] end """ interpolate(interpolant::RefSpace, chart1, interpolee::RefSpace, chart2) Computes by interpolation approximations of the local shape functions for `interpolee` on `chart2` in terms of the local shape functions for `interpolant` on `chart1`. The returned value is a matrix `Q` such that ```math \\phi_i \\approx \\sum_j Q_{ij} \\psi_j ``` with ``\\phi_i`` the i-th local shape function for `interpolee` and ``\\psi_j`` the j-th local shape function for `interpolant`. """ function interpolate(interpolant::RefSpace, chart1, interpolee::RefSpace, chart2) function fields(p) x = cartesian(p) v = carttobary(chart2, x) r = neighborhood(chart2, v) fieldvals = [f.value for f in interpolee(r)] end interpolate(fields, interpolant, chart1) end function interpolate(interpolant::RefSpace, chart1, interpolee::RefSpace, chart2, ch1toch2) function fields(p1) u1 = parametric(p1) u2 = cartesian(ch1toch2, u1) p2 = neighborhood(chart2, u2) fieldvals = [f.value for f in interpolee(p2)] end interpolate(fields, interpolant, chart1) end function interpolate(fields, interpolant::RTRefSpace, chart) Q = map(faces(chart)) do face p = center(face) x = cartesian(p) u = carttobary(chart, x) q = neighborhood(chart, u) n = normal(q) # minus because in CSM the tangent points towards vertex[1] t = -tangents(p,1) m = cross(t,n) fieldvals = fields(q) q = [dot(fv,m) for fv in fieldvals] end return hcat(Q...) end function restrict(ϕ::RefSpace, dom1, dom2) interpolate(ϕ, dom2, ϕ, dom1) end function restrict(ϕ::RefSpace, dom1, dom2, dom2todom1) interpolate(ϕ, dom2, ϕ, dom1, dom2todom1) end const _dof_rtperm_matrix = [ @SMatrix[1 0 0; # 1. {1,2,3} 0 1 0; 0 0 1], @SMatrix[0 0 1; # 2. {2,3,1} 1 0 0; 0 1 0], @SMatrix[0 1 0; # 3. {3,1,2} 0 0 1; 1 0 0], @SMatrix[0 1 0; # 4. {2,1,3} 1 0 0; 0 0 1], @SMatrix[1 0 0; # 5. {1,3,2} 0 0 1; 0 1 0], @SMatrix[0 0 1; # 6. {3,2,1} 0 1 0; 1 0 0] ] # Support for zeroth order elements on quadrilaterals
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
3564
struct RTQuadRefSpace{T} <: DivRefSpace{T,4} end function (ϕ::RTQuadRefSpace{T})(p) where {T} u, v = parametric(p) j = jacobian(p) D = tangents(p) eu = point(T,1,0) ev = point(T,0,1) i = one(T) vals = SVector( (value=(v-1)*ev, divergence=i), (value=u*eu, divergence=i), (value=v*ev, divergence=i), (value=(u-1)*eu, divergence=i), ) map(vals) do f (value=D*f.value/j, divergence=f.divergence/j) end end function interpolate(fields, interpolant::RTQuadRefSpace{T}, chart) where {T} refchart = domain(chart) Q = map(zip(faces(chart), faces(refchart))) do (edge,refedge) s = T(0.5) p_edge = neighborhood(edge, s) p_refedge = neighborhood(refedge, s) p_refchart = neighborhood(refchart, cartesian(p_refedge)) p_chart = neighborhood(chart, cartesian(p_refchart)) n_chart = normal(p_chart) t_edge = tangents(p_edge, 1) m_edge = -cross(t_edge, n_chart) fieldvals = fields(p_chart) map(fv -> dot(fv,m_edge), fieldvals) end return hcat(Q...) end @testitem "interpolate" begin using CompScienceMeshes p1 = point(0,0,0) p2 = point(2,0,0) p3 = point(2,4,0) p4 = point(0,4,0) quad = CompScienceMeshes.Quadrilateral(p1,p2,p3,p4) f(p) = (x = cartesian(p); return [point(x[1]+2, -x[2]-3, 0)]) rtq = BEAST.RTQuadRefSpace{Float64}() Q = BEAST.interpolate(f, rtq, quad) p = neighborhood(quad, point(0.5, 0.5)) val1 = f(p)[1] val2 = sum(Q[1,i] * ϕ.value for (i,ϕ) in zip(axes(Q,2), rtq(p))) @show val1 @show val2 @test val1 ≈ val2 end const _vrtperm_matrix_rtq = [ (1,2,3,4), (2,3,4,1), (3,4,1,2), (4,1,2,3), (2,1,4,3), (1,4,3,2), (4,3,2,1), (3,2,1,4), ] const _dofperm_matrix_rtq = [ @SMatrix[1.0 0.0 0.0 0.0; 0.0 1.0 0.0 0.0; 0.0 0.0 1.0 0.0; 0.0 0.0 0.0 1.0], @SMatrix[0.0 0.0 0.0 1.0; 1.0 0.0 0.0 0.0; 0.0 1.0 0.0 0.0; 0.0 0.0 1.0 0.0], @SMatrix[0.0 0.0 1.0 0.0; 0.0 0.0 0.0 1.0; 1.0 0.0 0.0 0.0; 0.0 1.0 0.0 0.0], @SMatrix[0.0 1.0 0.0 0.0; 0.0 0.0 1.0 0.0; 0.0 0.0 0.0 1.0; 1.0 0.0 0.0 0.0], @SMatrix[1.0 0.0 0.0 0.0; 0.0 0.0 0.0 1.0; 0.0 0.0 1.0 0.0; 0.0 1.0 0.0 0.0], @SMatrix[0.0 0.0 0.0 1.0; 0.0 0.0 1.0 0.0; 0.0 1.0 0.0 0.0; 1.0 0.0 0.0 0.0], @SMatrix[0.0 0.0 1.0 0.0; 0.0 1.0 0.0 0.0; 1.0 0.0 0.0 0.0; 0.0 0.0 0.0 1.0], @SMatrix[0.0 1.0 0.0 0.0; 1.0 0.0 0.0 0.0; 0.0 0.0 0.0 1.0; 0.0 0.0 1.0 0.0], ] function dof_perm_matrix(::RTQuadRefSpace, vert_permutation) i = findfirst(==(tuple(vert_permutation...)), _vrtperm_matrix_rtq) @assert i != nothing return _dofperm_matrix_rtq[i] end @testitem "restrict RTQ0" begin using CompScienceMeshes using Combinatorics ref_vertices = [ point(0,0), point(1,0), point(1,1), point(0,1)] vertices = [ point(0,0,0), point(1,0,0), point(1,1,0), point(0,1,0)] chart1 = CompScienceMeshes.Quadrilateral(vertices...) for I in BEAST._vrtperm_matrix_rtq @show I chart2 = CompScienceMeshes.Quadrilateral( vertices[I[1]], vertices[I[2]], vertices[I[3]], vertices[I[4]]) chart2tochart1 = CompScienceMeshes.Quadrilateral(ref_vertices[collect(I)]...) rs = BEAST.RTQuadRefSpace{Float64}() Q1 = BEAST.dof_perm_matrix(rs, I) Q2 = BEAST.restrict(rs, chart1, chart2, chart2tochart1) @test Q1 ≈ Q1 end end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1971
struct CurlSingleLayerDP3D{T,U} <: MaxwellOperator3D{U,T} gamma::T alpha::U end function integrand(op::CurlSingleLayerDP3D, kernel_vals, test_vals, test_nbhd, trial_vals, trial_nbhd) α = op.alpha gx = test_vals.value fy = trial_vals.value ∇G = kernel_vals.gradgreen nx = normal(test_nbhd) return -α * dot(nx × gx, ∇G * fy) end function momintegrals!(op::CurlSingleLayerDP3D, test_local_space::RTRefSpace, trial_local_space::LagrangeRefSpace, test_triangular_element, trial_triangular_element, out, strat::SauterSchwabStrategy) I, J, K, L = SauterSchwabQuadrature.reorder( test_triangular_element.vertices, trial_triangular_element.vertices, strat) test_triangular_element = simplex(test_triangular_element.vertices[I]...) trial_triangular_element = simplex(trial_triangular_element.vertices[J]...) function igd(u,v) α = op.alpha γ = op.gamma x = neighborhood(test_triangular_element,u) y = neighborhood(trial_triangular_element,v) nx = normal(x) r = cartesian(x) - cartesian(y) R = norm(r) G = exp(-γ*R)/(4π*R) GG = -(γ + 1/R) * G / R * r f = test_local_space(x) g = trial_local_space(y) jx = jacobian(x) jy = jacobian(y) j = jx*jy αjGG = α*j*GG R = @SVector[αjGG*g[i].value for i in 1:3] return @SMatrix[dot(f[i].value × nx, R[j]) for i in 1:3, j in 1:3] end Q = sauterschwab_parameterized(igd, strat) for j ∈ 1:3 for i ∈ 1:3 out[i,j] += Q[K[i],L[j]] end end nothing end function quadrule(op::BEAST.CurlSingleLayerDP3D, test_local_space::BEAST.RTRefSpace, trial_local_space::BEAST.RTRefSpace, test_index, test_chart, trial_index, trial_chart, quadrature_data) qrdf(op, test_local_space, trial_local_space, test_index, test_chart, trial_index, trial_chart, quadrature_data) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1121
struct DPVectorialTerm{A,K} alpha::A gamma::K end struct DPScalarTerm{A,K} alpha::A gamma::K end const DPTerm = Union{DPVectorialTerm, DPScalarTerm} quaddata(pot::DPTerm, local_space, charts) = quadpoints(local_space, charts, (2,)) quadrule(pot::DPTerm, local_space, test_index, test_point, trial_index, trial_chart, quad_data) = quad_data[1,trial_index] function kernelvals(pot::DPTerm, test_point, trial_neighborhood) γ = pot.gamma α = pot.alpha r = test_point - cartesian(trial_neighborhood) R = norm(r) γR = γ*R expn = exp(-γR) green = expn / (4π*R) gradgreen = -(γ + 1/R) * green / R * r return (vector=r, distance=R, green=green, gradgreen=gradgreen) end function integrand(pot::DPVectorialTerm, kernel_values, test_point, trial_values, trial_neighborhood) α = pot.alpha G = kernel_values.green f = trial_values.value return α*G*f end function integrand(pot::DPScalarTerm, kernel_values, test_point, trial_values, trial_neighborhood) α = pot.alpha ∇G = kernel_values.gradgreen f = trial_values.value return α*∇G*f end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
4041
import SpecialFunctions: hankelh2 abstract type HelmholtzOperator2D <: IntegralOperator end scalartype(::HelmholtzOperator2D) = ComplexF64 struct SingleLayer{T} <: HelmholtzOperator2D wavenumber::T end struct HyperSingular{T} <: HelmholtzOperator2D wavenumber::T end struct DoubleLayer{T} <: HelmholtzOperator2D wavenumber::T end struct DoubleLayerTransposed{T} <: HelmholtzOperator2D wavenumber::T end function cellcellinteractions!(biop::HelmholtzOperator2D, tshs, bshs, tcell, bcell, z) regularcellcellinteractions!(biop, tshs, bshs, tcell, bcell, z) end function testfunc1() print("test function!") end defaultquadstrat(op::HelmholtzOperator2D, tfs, bfs) = DoubleNumWiltonSauterQStrat(4,3,4,3,4,4,4,4) function quaddata(op::HelmholtzOperator2D, g::LagrangeRefSpace, f::LagrangeRefSpace, tels, bels, qs::DoubleNumWiltonSauterQStrat) tqd = quadpoints(g, tels, (qs.outer_rule_far,)) bqd = quadpoints(f, bels, (qs.inner_rule_far,)) return (tpoints=tqd, bpoints=bqd) end function quadrule(op::HelmholtzOperator2D, g::LagrangeRefSpace, f::LagrangeRefSpace, i, τ, j, σ, qd, qs::DoubleNumWiltonSauterQStrat) DoubleQuadRule( qd.tpoints[1,i], qd.bpoints[1,j] ) end mutable struct KernelValsHelmholtz2D wavenumber vect dist green gradgreen txty end function kernelvals(biop::HelmholtzOperator2D, tgeo, bgeo) k = biop.wavenumber r = tgeo.cart - bgeo.cart R = norm(r) kr = k * R hankels = hankelh2.([0 1], kr) green = -im / 4 * hankels[1] gradgreen = k * im / 4 * hankels[2] * r / R txty = dot(normal(tgeo), normal(bgeo)) KernelValsHelmholtz2D(k, r, R, green, gradgreen, txty) end shapevals(op::HelmholtzOperator2D, ϕ, ts) = shapevals(ValDiff(), ϕ, ts) function integrand(biop::SingleLayer, kerneldata, tvals, tgeo, bvals, bgeo) gx = tvals[1] fy = bvals[1] gx * kerneldata.green * fy end function integrand(biop::HyperSingular, kernel, tvals, tgeo, bvals, bgeo) gx = tvals[1] fy = bvals[1] dgx = tvals[2] dfy = bvals[2] k = kernel.wavenumber G = kernel.green txty = kernel.txty (dgx * dfy - k*k * txty * gx * fy) * G end function integrand(biop::DoubleLayer, kernel, fp, mp, fq, mq) nq = normal(mq) fp[1] * dot(nq, -kernel.gradgreen) * fq[1] end function integrand(biop::DoubleLayerTransposed, kernel, fp, mp, fq, mq) np = normal(mp) fp[1] * dot(np, kernel.gradgreen) * fq[1] end mutable struct PlaneWaveDirichlet{T,P} <: Functional wavenumber::T direction::P end scalartype(x::PlaneWaveDirichlet{T}) where {T} = complex(T) mutable struct PlaneWaveNeumann{T,P} <: Functional wavenumber::T direction::P end scalartype(x::PlaneWaveNeumann{T}) where {T} = complex(T) mutable struct ScalarTrace{T,F} <: Functional field::F end ScalarTrace(f::F) where {F} = ScalarTrace{scalartype(f), F}(f) ScalarTrace{T}(f::F) where {T,F} = ScalarTrace{T,F}(f) strace(f, mesh::Mesh) = ScalarTrace(f) (s::ScalarTrace)(x) = s.field(cartesian(x)) integrand(s::ScalarTrace, tx, fx) = dot(tx.value, fx) scalartype(s::ScalarTrace{T}) where {T} = T shapevals(f::Functional, ϕ, ts) = shapevals(ValOnly(), ϕ, ts) function (field::PlaneWaveDirichlet)(mp) wavenumber = field.wavenumber direction = field.direction cart = cartesian(mp) exp(-im * wavenumber * dot(direction, cart)) end function(field::PlaneWaveNeumann)(mp) wavenumber = field.wavenumber direction = field.direction cart = cartesian(mp) norm = normal(mp) wave = exp(-im * wavenumber * dot(direction, cart)) grad = -im * wavenumber * direction * wave d = norm[1] * grad[1] for i in 2:length(norm) d += norm[i] * grad[i] end return d end function integrand(pw::PlaneWaveDirichlet, sv, fx) tx = sv[1] return dot(tx, fx) end function integrand(pw::PlaneWaveNeumann, sv, fx) tx = sv[1] d = tx[1] * fx[1] for i in 2:length(tx) d += tx[i]*fx[i] end return d end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
3156
module Helmholtz3D using ..BEAST const Mod = BEAST using LinearAlgebra function singlelayer(; alpha=nothing, gamma=nothing, wavenumber=nothing ) alpha, gamma = Mod.operator_parameter_handler(alpha, gamma, wavenumber) return Mod.HH3DSingleLayerFDBIO(alpha,gamma) end function doublelayer(; alpha=nothing, gamma=nothing, wavenumber=nothing ) alpha, gamma = Mod.operator_parameter_handler(alpha, gamma, wavenumber) return Mod.HH3DDoubleLayerFDBIO(alpha, gamma) end function doublelayer_transposed(; alpha=nothing, gamma=nothing, wavenumber=nothing ) alpha, gamma = Mod.operator_parameter_handler(alpha, gamma, wavenumber) return Mod.HH3DDoubleLayerTransposedFDBIO(alpha, gamma) end function hypersingular(; alpha=nothing, beta=nothing, gamma=nothing, wavenumber=nothing ) gamma, wavenumber = Mod.gamma_wavenumber_handler(gamma, wavenumber) if alpha === nothing if Mod.isstatic(gamma) #static case alpha = 0.0 # In the long run, this should probably be rather 'nothing' else alpha = gamma^2 end end if beta === nothing if Mod.isstatic(gamma) #static case beta = one(alpha) else beta = one(gamma) end end return Mod.HH3DHyperSingularFDBIO(alpha, beta, gamma) end function planewave(; direction=error("direction is a required argument"), gamma=nothing, wavenumber=nothing, amplitude=one(eltype(direction))) gamma, wavenumber = Mod.gamma_wavenumber_handler(gamma, wavenumber) # Note: Unlike for the operators, there seems little benefit in # explicitly declaring a Laplace-Type excitation. Mod.isstatic(gamma) && (gamma = zero(amplitude)) return Mod.HH3DPlaneWave(direction, gamma, amplitude) end function linearpotential(; direction=SVector(1, 0, 0), amplitude=1.0) return Mod.HH3DLinearPotential(direction ./ norm(direction), amplitude) end function grad_linearpotential(; direction=SVector(0.0, 0.0, 0.0), amplitude=1.0) return Mod.gradHH3DLinearPotential(direction, amplitude) end function monopole(; position=SVector(0.0, 0.0, 0.0), gamma=nothing, wavenumber=nothing, amplitude=1.0 ) gamma, wavenumber = Mod.gamma_wavenumber_handler(gamma, wavenumber) Mod.isstatic(gamma) && (gamma = zero(amplitude)) return Mod.HH3DMonopole(position, gamma, amplitude) end function grad_monopole(; position=SVector(0.0, 0.0, 0.0), gamma=nothing, wavenumber=nothing, amplitude=1.0 ) gamma, wavenumber = Mod.gamma_wavenumber_handler(gamma, wavenumber) Mod.isstatic(gamma) && (gamma = zero(amplitude)) return Mod.gradHH3DMonopole(position, gamma, amplitude) end end export Helmholtz3D
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
8473
# function pulled_back_integrand(op::HH3DSingleLayerFDBIO, # test_local_space::LagrangeRefSpace, # trial_local_space::LagrangeRefSpace, # test_chart, trial_chart) # (u,v) -> begin # x = neighborhood(test_chart,u) # y = neighborhood(trial_chart,v) # f = test_local_space(x) # g = trial_local_space(y) # j = jacobian(x) * jacobian(y) # α = op.alpha # γ = gamma(op) # R = norm(cartesian(x)-cartesian(y)) # G = exp(-γ*R)/(4*π*R) # αjG = α*G*j # SMatrix{length(f),length(g)}((f[j].value * αjG * g[i].value for i in 1:length(g) for j in 1:length(f) )...) # end # end # function pulled_back_integrand(op::HH3DHyperSingularFDBIO, # test_local_space::LagrangeRefSpace, # trial_local_space::LagrangeRefSpace, # test_chart, trial_chart) # (u,v) -> begin # x = neighborhood(test_chart,u) # y = neighborhood(trial_chart,v) # nx = normal(x) # ny = normal(y) # f = test_local_space(x) # g = trial_local_space(y) # j = jacobian(x) * jacobian(y) # α = op.alpha # β = op.beta # γ = gamma(op) # R = norm(cartesian(x)-cartesian(y)) # G = exp(-γ*R)/(4*π*R) # αjG = ny*α*G*j # βjG = β*G*j # A = SA[(αjG*g[i].value for i in 1:length(g))...] # B = SA[(βjG*g[i].curl for i in 1:length(g))...] # SMatrix{length(f),length(g)}((((dot(nx*f[j].value,A[i])+dot(f[j].curl,B[i])) for i in 1:length(g) for j in 1:length(f))...)) # end # end # function pulled_back_integrand(op::HH3DDoubleLayerFDBIO, # test_local_space::LagrangeRefSpace, # trial_local_space::LagrangeRefSpace, # test_chart, trial_chart) # (u,v) -> begin # x = neighborhood(test_chart,u) # y = neighborhood(trial_chart,v) # ny = normal(y) # f = test_local_space(x) # g = trial_local_space(y) # j = jacobian(x) * jacobian(y) # α = op.alpha # γ = gamma(op) # r = cartesian(x) - cartesian(y) # R = norm(r) # G = exp(-γ*R)/(4*π*R) # inv_R = 1/R # ∇G = -(γ + inv_R) * G * inv_R * r # αnyj∇G = dot(ny,-α*∇G*j) # SMatrix{length(f),length(g)}((f[j].value * αnyj∇G * g[i].value for i in 1:length(g) for j in 1:length(f))...) # end # end # function pulled_back_integrand(op::HH3DDoubleLayerTransposedFDBIO, # test_local_space::LagrangeRefSpace, # trial_local_space::LagrangeRefSpace, # test_chart, trial_chart) # (u,v) -> begin # x = neighborhood(test_chart,u) # y = neighborhood(trial_chart,v) # nx = normal(x) # f = test_local_space(x) # g = trial_local_space(y) # j = jacobian(x) * jacobian(y) # α = op.alpha # γ = gamma(op) # r = cartesian(x) - cartesian(y) # R = norm(r) # G = exp(-γ*R)/(4*π*R) # inv_R = 1/R # ∇G = -(γ + inv_R) * G * inv_R * r # αnxj∇G = dot(nx,α*∇G*j) # SMatrix{length(f),length(g)}((f[j].value * αnxj∇G * g[i].value for i in 1:length(g) for j in 1:length(f))...) # end # end # function momintegrals!(op::Helmholtz3DOp, # test_local_space::LagrangeRefSpace{<:Any,0}, trial_local_space::LagrangeRefSpace{<:Any,0}, # test_triangular_element, trial_triangular_element, out, strat::SauterSchwabStrategy) # I, J, K, L = SauterSchwabQuadrature.reorder( # test_triangular_element.vertices, # trial_triangular_element.vertices, strat) # test_triangular_element = simplex( # test_triangular_element.vertices[I[1]], # test_triangular_element.vertices[I[2]], # test_triangular_element.vertices[I[3]]) # trial_triangular_element = simplex( # trial_triangular_element.vertices[J[1]], # trial_triangular_element.vertices[J[2]], # trial_triangular_element.vertices[J[3]]) # test_sign = Combinatorics.levicivita(I) # trial_sign = Combinatorics.levicivita(J) # σ = momintegrals_sign(op, test_sign, trial_sign) # igd = pulled_back_integrand(op, test_local_space, trial_local_space, # test_triangular_element, trial_triangular_element) # G = SauterSchwabQuadrature.sauterschwab_parameterized(igd, strat) # out[1,1] += G[1,1] * σ # nothing # end # function momintegrals!(op::Helmholtz3DOp, # test_local_space::LagrangeRefSpace, trial_local_space::LagrangeRefSpace, # test_triangular_element, trial_triangular_element, out, strat::SauterSchwabStrategy) # I, J, K, L = SauterSchwabQuadrature.reorder( # test_triangular_element.vertices, # trial_triangular_element.vertices, strat) # test_triangular_element = simplex( # test_triangular_element.vertices[I[1]], # test_triangular_element.vertices[I[2]], # test_triangular_element.vertices[I[3]]) # trial_triangular_element = simplex( # trial_triangular_element.vertices[J[1]], # trial_triangular_element.vertices[J[2]], # trial_triangular_element.vertices[J[3]]) # test_sign = Combinatorics.levicivita(I) # trial_sign = Combinatorics.levicivita(J) # σ = momintegrals_sign(op, test_sign, trial_sign) # igd = pulled_back_integrand(op, test_local_space, trial_local_space, # test_triangular_element, trial_triangular_element) # G = SauterSchwabQuadrature.sauterschwab_parameterized(igd, strat) # for j ∈ 1:3, i ∈ 1:3 # out[i,j] += G[K[i],L[j]] * σ # end # nothing # end # function momintegrals!(op::Helmholtz3DOp, # test_local_space::LagrangeRefSpace{<:Any,0}, trial_local_space::LagrangeRefSpace{<:Any,1}, # test_triangular_element, trial_triangular_element, out, strat::SauterSchwabStrategy) # I, J, K, L = SauterSchwabQuadrature.reorder( # test_triangular_element.vertices, # trial_triangular_element.vertices, strat) # test_triangular_element = simplex( # test_triangular_element.vertices[I[1]], # test_triangular_element.vertices[I[2]], # test_triangular_element.vertices[I[3]]) # trial_triangular_element = simplex( # trial_triangular_element.vertices[J[1]], # trial_triangular_element.vertices[J[2]], # trial_triangular_element.vertices[J[3]]) # test_sign = Combinatorics.levicivita(I) # trial_sign = Combinatorics.levicivita(J) # σ = momintegrals_sign(op, test_sign, trial_sign) # igd = pulled_back_integrand(op, test_local_space, trial_local_space, # test_triangular_element, trial_triangular_element) # G = SauterSchwabQuadrature.sauterschwab_parameterized(igd, strat) # for i ∈ 1:3 # out[1,i] += G[L[i]] * σ # end # nothing # end # function momintegrals!(op::Helmholtz3DOp, # test_local_space::LagrangeRefSpace{<:Any,1}, trial_local_space::LagrangeRefSpace{<:Any,0}, # test_triangular_element, trial_triangular_element, out, strat::SauterSchwabStrategy) # I, J, K, L = SauterSchwabQuadrature.reorder( # test_triangular_element.vertices, # trial_triangular_element.vertices, strat) # test_triangular_element = simplex( # test_triangular_element.vertices[I[1]], # test_triangular_element.vertices[I[2]], # test_triangular_element.vertices[I[3]]) # trial_triangular_element = simplex( # trial_triangular_element.vertices[J[1]], # trial_triangular_element.vertices[J[2]], # trial_triangular_element.vertices[J[3]]) # test_sign = Combinatorics.levicivita(I) # trial_sign = Combinatorics.levicivita(J) # σ = momintegrals_sign(op, test_sign, trial_sign) # igd = pulled_back_integrand(op, test_local_space, trial_local_space, # test_triangular_element, trial_triangular_element) # G = SauterSchwabQuadrature.sauterschwab_parameterized(igd, strat) # for i ∈ 1:3 # out[i,1] += G[K[i]] * σ # end # nothing # end # function momintegrals_sign(op::HH3DSingleLayerFDBIO, test_sign, trial_sign) # return 1 # end # function momintegrals_sign(op::HH3DDoubleLayerFDBIO, test_sign, trial_sign) # return trial_sign # end # function momintegrals_sign(op::HH3DDoubleLayerTransposedFDBIO, test_sign, trial_sign) # return test_sign # end # function momintegrals_sign(op::HH3DHyperSingularFDBIO, test_sign, trial_sign) # return test_sign * trial_sign # end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
4648
struct HH3DPlaneWave{P,K,T} direction::P gamma::K amplitude::T end function (f::HH3DPlaneWave)(r) d = f.direction γ = f.gamma a = f.amplitude return a * exp(-γ*dot(d,r)) end function (f::HH3DPlaneWave)(r::CompScienceMeshes.MeshPointNM) return f(cartesian(r)) end scalartype(f::HH3DPlaneWave{P,K,T}) where {P,K,T} = promote_type(eltype(P), K, T) """ HH3DLinearPotential A potential that linearly increases in `direction` with scaling coefficient `amplitude`. Its negative gradient will be a uniform vector field pointing in the opposite direction. """ struct HH3DLinearPotential{P,T} direction::P amplitude::T end scalartype(f::HH3DLinearPotential{P,T}) where {P,T} = promote_type(eltype(P), T) function (f::HH3DLinearPotential)(r) d = f.direction a = f.amplitude return a * dot(d, r) end function (f::HH3DLinearPotential)(r::CompScienceMeshes.MeshPointNM) return f(cartesian(r)) end struct gradHH3DLinearPotential{T,P} direction::P amplitude::T end function (f::gradHH3DLinearPotential)(r) d = f.direction a = f.amplitude return a * d end function (f::gradHH3DLinearPotential)(r::CompScienceMeshes.MeshPointNM) r = cartesian(mp) return dot(normal(mp), f(r)) end function grad(m::HH3DLinearPotential) return gradHH3DLinearPotential(m.direction, m.amplitude) end *(a::Number, m::HH3DLinearPotential) = HH3DLinearPotential(m.direction, a * m.amplitude) *(a::Number, m::gradHH3DLinearPotential) = gradHH3DLinearPotential(m.direction, a * m.amplitude) dot(::NormalVector, m::gradHH3DLinearPotential) = NormalDerivative(HH3DLinearPotential(m.direction, m.amplitude)) """ HH3DMonopole Potential of a monopole-type point source (e.g., of an electric charge) """ struct HH3DMonopole{P,K,T} position::P gamma::K amplitude::T end scalartype(x::HH3DMonopole{P,K,T}) where {P,K,T} = promote_type(eltype(P), K, T) function (f::HH3DMonopole)(r::CompScienceMeshes.MeshPointNM) return f(cartesian(r)) end function (f::HH3DMonopole)(r) γ = f.gamma p = f.position a = f.amplitude return a*exp(-γ * norm(r - p)) / (norm(r - p)) end struct gradHH3DMonopole{P,K,T} position::P gamma::K amplitude::T end scalartype(x::gradHH3DMonopole{P,K,T}) where {P,K,T} = promote_type(eltype(P), K, T) function (f::gradHH3DMonopole)(r) a = f.amplitude γ = f.gamma p = f.position vecR = r - p R = norm(vecR) return -a * vecR * exp(-γ * R) / R^2 * (γ + 1 / R) end function (f::gradHH3DMonopole)(mp::CompScienceMeshes.MeshPointNM) r = cartesian(mp) return dot(normal(mp), f(r)) end function grad(m::HH3DMonopole) return gradHH3DMonopole(m.position, m.gamma, m.amplitude) end *(a::Number, m::HH3DMonopole) = HH3DMonopole(m.position, m.gamma, a * m.amplitude) *(a::Number, m::gradHH3DMonopole) = gradHH3DMonopole(m.position, m.gamma, a * m.amplitude) dot(::NormalVector, m::gradHH3DMonopole) = NormalDerivative(HH3DMonopole(m.position, m.gamma, m.amplitude)) mutable struct DirichletTrace{T,F} <: Functional field::F end DirichletTrace(f::F) where {F} = DirichletTrace{scalartype(f), F}(f) DirichletTrace{T}(f::F) where {T,F} = DirichletTrace{T,F}(f) scalartype(s::DirichletTrace{T}) where {T} = T function (ϕ::DirichletTrace)(p) F = ϕ.field x = cartesian(p) return F(x) end integrand(::DirichletTrace, test_vals, field_vals) = dot(test_vals[1], field_vals) struct NormalDerivative{T,F} <: Functional field::F end NormalDerivative(f::F) where {F} = NormalDerivative{scalartype(f), F}(f) NormalDerivative{T}(f::F) where {T,F} = NormalDerivative{T,F}(f) scalartype(s::NormalDerivative{T}) where {T} = T const ∂n = Val{:normalderivative} (::Type{Val{:normalderivative}})(f) = NormalDerivative(f) function (f::NormalDerivative)(nbd) x = cartesian(nbd) g = gradient(f.field)(x) n = normal(nbd) return dot(n,g) end function (f::NormalDerivative{T,F})(manipoint) where {T,F<:HH3DPlaneWave} d = f.field.direction γ = f.field.gamma a = f.field.amplitude n = normal(manipoint) r = cartesian(manipoint) return -γ*a * dot(d,n) * exp(-γ*dot(d,r)) end function (f::NormalDerivative{T,F})(manipoint) where {T,F<:HH3DLinearPotential} gradient = f.field.amplitude * f.field.direction n = normal(manipoint) return dot(n, gradient) end function (f::NormalDerivative{T,F})(manipoint) where {T,F<:HH3DMonopole} m = f.field grad_m = grad(m) n = normal(manipoint) r = cartesian(manipoint) return dot(n, grad_m(r)) end integrand(::NormalDerivative, test_vals, field_vals) = dot(test_vals[1], field_vals)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
515
struct HH3DFarField{K} gamma::K end function HH3DFarField(;wavenumber=error("wavenumber is a required argument")) if iszero(real(wavenumber)) HH3DFarField(-imag(wavenumber)) else HH3DFarField(wavenumber*im) end end quaddata(op::HH3DFarField,rs,els) = quadpoints(rs,els,(3,)) quadrule(op::HH3DFarField,refspace,p,y,q,el,qdata) = qdata[1,q] kernelvals(op::HH3DFarField,y,p) = exp(op.gamma*dot(y,cartesian(p))) function integrand(op::HH3DFarField,krn,y,f,p) krn * f.value end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2453
struct HH3DDoubleLayerNear{K} gamma::K end struct HH3DSingleLayerNear{K} gamma::K end struct HH3DHyperSingularNear{K} gamma::K end struct HH3DDoubleLayerTransposedNear{K} gamma::K end function HH3DDoubleLayerNear(;wavenumber=error("wavenumber is a required argument")) if iszero(real(wavenumber)) HH3DDoubleLayerNear(-imag(wavenumber)) else HH3DDoubleLayerNear(wavenumber*im) end end function HH3DSingleLayerNear(;wavenumber=error("wavenumber is a required argument")) if iszero(real(wavenumber)) HH3DSingleLayerNear(-imag(wavenumber)) else HH3DSingleLayerNear(wavenumber*im) end end function HH3DHyperSingularNear(;wavenumber=error("wavenumber is a required argument")) if iszero(real(wavenumber)) HH3DHyperSingularNear(-imag(wavenumber)) else HH3DHyperSingularNear(wavenumber*im) end end function HH3DDoubleLayerTransposedNear(;wavenumber=error("wavenumber is a required argument")) if iszero(real(wavenumber)) HH3DDoubleLayerTransposedNear(-imag(wavenumber)) else HH3DDoubleLayerTranposedNear(wavenumber*im) end end HH3DNear = Union{HH3DSingleLayerNear, HH3DDoubleLayerNear, HH3DDoubleLayerTransposedNear, HH3DHyperSingularNear} defaultquadstrat(op::HH3DNear, basis) = SingleNumQStrat(3) quaddata(op::HH3DNear,rs,els,qs::SingleNumQStrat) = quadpoints(rs,els,(qs.quad_rule,)) quadrule(op::HH3DNear,refspace,p,y,q,el,qdata,qs::SingleNumQStrat) = qdata[1,q] function kernelvals(op::HH3DNear,y,p) γ = op.gamma x = cartesian(p) r = y - x R = norm(r) γR = γ*R inv_R = 1/R expn = exp(-γR) green = expn * inv_R * inv_4pi gradgreen = -(γ + inv_R) * green * inv_R * r nx = normal(p) (;γ, r, R, green, gradgreen, nx) end function integrand(op::HH3DDoubleLayerNear,krn,y,f,p) ∇G = -krn.gradgreen nx = krn.nx fx = f.value ∂G∂n = nx ⋅ ∇G return ∂G∂n * fx end function integrand(op::HH3DSingleLayerNear, krn, y, f, p) G = krn.green fx = f.value return G * fx end function integrand(op::HH3DDoubleLayerTransposedNear, krn, y, f, p) ∇G = krn.gradgreen fx = f.value return ∇G * fx end function integrand(op::HH3DHyperSingularNear, krn, y, f, p) G = krn.green nx = krn.nx γ = krn.γ invR = 1/krn.R fx = f.value r = krn.r # returns ∇ᵣn̂'∇ᵣ'G - strong singularity, probably makes problems for small distances R return (nx * G * invR * (γ + invR) - r * dot(nx,r) * G * invR^2 * (γ^2 + 3 * γ * invR + 3 * invR^2)) * fx end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
4864
abstract type Helmholtz3DOp{T,K} <: MaxwellOperator3D{T,K} end abstract type Helmholtz3DOpReg{T,K} <: MaxwellOperator3DReg{T,K} end """ ``` ∫_Γ dx ∫_Γ dy \\left(α G g(x) n_x ⋅ n_y f(y) + β G \\mbox{curl} g(x) ⋅ \\mbox{curl} f(y) \\right) ``` with ``G(x,y) = \\frac{e^{-γ |x-y|}}{4 π |x-y|}`` """ struct HH3DHyperSingularFDBIO{T,K} <: Helmholtz3DOp{T,K} "coefficient of the weakly singular term" alpha::T "coefficient of the hyper singular term" beta::T "`im*κ` with `κ` the wave number" gamma::K end function sign_upon_permutation(op::HH3DHyperSingularFDBIO, I, J) return Combinatorics.levicivita(I) * Combinatorics.levicivita(J) end struct HH3DHyperSingularReg{T,K} <: Helmholtz3DOpReg{T,K} "coefficient of the weakly singular term" alpha::T "coefficient of the hyper singular term" beta::T "`im*κ` with `κ` the wave number" gamma::K end struct HH3DHyperSingularSng{T,K} <: Helmholtz3DOp{T,K} "coefficient of the weakly singular term" alpha::T "coefficient of the hyper singular term" beta::T "`im*κ` with `κ` the wave number" gamma::K end HH3DHyperSingularFDBIO(gamma) = HH3DHyperSingularFDBIO(gamma^2, one(gamma), gamma) """ ```math a(u,v) = α ∬_{Γ×Γ} u(x) G_{γ}(|x-y|) v(y) ``` with ``G_{γ}(r) = \\frac{e^{-γr}}{4πr}``. """ struct HH3DSingleLayerFDBIO{T,K} <: Helmholtz3DOp{T,K} alpha::T gamma::K end struct HH3DSingleLayerReg{T,K} <: Helmholtz3DOpReg{T,K} alpha::T gamma::K end struct HH3DSingleLayerSng{T,K} <: Helmholtz3DOp{T,K} alpha::T gamma::K end struct HH3DDoubleLayerFDBIO{T,K} <: Helmholtz3DOp{T,K} alpha::T gamma::K end struct HH3DDoubleLayerReg{T,K} <: Helmholtz3DOpReg{T,K} alpha::T gamma::K end struct HH3DDoubleLayerSng{T,K} <: Helmholtz3DOp{T,K} alpha::T gamma::K end struct HH3DDoubleLayerTransposedFDBIO{T,K} <: Helmholtz3DOp{T,K} alpha::T gamma::K end struct HH3DDoubleLayerTransposedReg{T,K} <: Helmholtz3DOpReg{T,K} alpha::T gamma::K end struct HH3DDoubleLayerTransposedSng{T,K} <: Helmholtz3DOp{T,K} alpha::T gamma::K end defaultquadstrat(::Helmholtz3DOp, ::LagrangeRefSpace, ::LagrangeRefSpace) = DoubleNumWiltonSauterQStrat(2,3,2,3,4,4,4,4) defaultquadstrat(::Helmholtz3DOp, ::subReferenceSpace, ::subReferenceSpace) = DoubleNumWiltonSauterQStrat(4,7,4,7,4,4,4,4) regularpart(op::HH3DHyperSingularFDBIO) = HH3DHyperSingularReg(op.alpha, op.beta, op.gamma) singularpart(op::HH3DHyperSingularFDBIO) = HH3DHyperSingularSng(op.alpha, op.beta, op.gamma) function (igd::Integrand{<:HH3DHyperSingularFDBIO})(x,y,f,g) α = igd.operator.alpha β = igd.operator.beta γ = gamma(igd.operator) r = cartesian(x) - cartesian(y) R = norm(r) iR = 1 / R green = exp(-γ*R)*(i4pi*iR) nx = normal(x) ny = normal(y) _integrands(f,g) do fi, gi α*dot(nx,ny)*gi.value*fi.value*green + β*dot(gi.curl,fi.curl)*green end end HH3DSingleLayerFDBIO(gamma) = HH3DSingleLayerFDBIO(one(gamma), gamma) regularpart(op::HH3DSingleLayerFDBIO) = HH3DSingleLayerReg(op.alpha, op.gamma) singularpart(op::HH3DSingleLayerFDBIO) = HH3DSingleLayerSng(op.alpha, op.gamma) function (igd::Integrand{<:HH3DSingleLayerFDBIO})(x,y,f,g) α = igd.operator.alpha γ = gamma(igd.operator) r = cartesian(x) - cartesian(y) R = norm(r) iR = 1 / R green = exp(-γ*R)*(i4pi*iR) αG = α * green _integrands(f,g) do fi, gi dot(gi.value, αG*fi.value) end end HH3DDoubleLayerFDBIO(gamma) = HH3DDoubleLayerFDBIO(one(gamma), gamma) regularpart(op::HH3DDoubleLayerFDBIO) = HH3DDoubleLayerReg(op.alpha, op.gamma) singularpart(op::HH3DDoubleLayerFDBIO) = HH3DDoubleLayerSng(op.alpha, op.gamma) function (igd::Integrand{<:HH3DDoubleLayerFDBIO})(x,y,f,g) γ = gamma(igd.operator) α = igd.operator.alpha r = cartesian(x) - cartesian(y) R = norm(r) iR = 1/R green = exp(-γ*R)*(iR*i4pi) gradgreen = -(γ + iR) * green * (iR * r) αgradgreen = α * gradgreen n = normal(y) fvalue = getvalue(f) gvalue = getvalue(g) return _krondot(fvalue,gvalue) * dot(n, -αgradgreen) end HH3DDoubleLayerTransposedFDBIO(gamma) = HH3DDoubleLayerTransposedFDBIO(one(gamma), gamma) regularpart(op::HH3DDoubleLayerTransposedFDBIO) = HH3DDoubleLayerTransposedReg(op.alpha, op.gamma) singularpart(op::HH3DDoubleLayerTransposedFDBIO) = HH3DDoubleLayerTransposedSng(op.alpha, op.gamma) function (igd::Integrand{<:HH3DDoubleLayerTransposedFDBIO})(x,y,f,g) γ = gamma(igd.operator) α = igd.operator.alpha r = cartesian(x) - cartesian(y) R = norm(r) iR = 1/R green = exp(-γ*R)*(iR*i4pi) gradgreen = -(γ + iR) * green * (iR * r) αgradgreen = α * gradgreen n = normal(x) fvalue = getvalue(f) gvalue = getvalue(g) return _krondot(fvalue,gvalue) * dot(n, αgradgreen) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1625
mutable struct NitscheHH3{T} <: MaxwellOperator3D{T,T} gamma::T end defaultquadstrat(::NitscheHH3, ::LagrangeRefSpace, ::LagrangeRefSpace) = DoubleNumWiltonSauterQStrat(10,8,10,8,3,3,3,3) function quaddata(operator::NitscheHH3, localtestbasis::LagrangeRefSpace, localtrialbasis::LagrangeRefSpace, testelements, trialelements, qs::DoubleNumWiltonSauterQStrat) tqd = quadpoints(localtestbasis, testelements, (qs.outer_rule_far,)) bqd = quadpoints(x -> localtrialbasis(x), trialelements, (qs.inner_rule_far,)) #return QuadData(tqd, bqd) return (tpoints=tqd, bpoints=bqd) end function quadrule(op::NitscheHH3, g::LagrangeRefSpace, f::LagrangeRefSpace, i, τ, j, σ, qd, qs::DoubleNumWiltonSauterQStrat) DoubleQuadRule( qd.tpoints[1,i], qd.bpoints[1,j] ) end struct KernelValsMaxwell3D{T,U,P,Q} "gamma = im * wavenumber" gamma::U vect::P dist::T green::U gradgreen::Q end const inv_4pi = 1/(4pi) function kernelvals(biop::MaxwellOperator3D, p, q) γ = gamma(biop) r = cartesian(p) - cartesian(q) T = eltype(r) R = norm(r) γR = γ*R inv_R = 1/R expn = exp(-γR) green = expn * inv_R * T(inv_4pi) gradgreen = -(γ + inv_R) * green * inv_R * r KernelValsMaxwell3D(γ, r, R, green, gradgreen) end function integrand(op::NitscheHH3, kernel, test_vals, test_point, trial_vals, trial_point) Gxy = kernel.green @assert length(test_point.patch.tangents) == 1 tx = normalize(tangents(test_point, 1)) gx = test_vals[1] curlfy = trial_vals[2] return gx*dot(tx, Gxy * curlfy) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
14224
# single layer function (igd::Integrand{<:HH3DSingleLayerReg})(x,y,f,g) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(igd.operator) α = igd.operator.alpha r = cartesian(x) - cartesian(y) R = norm(r) iR = 1 / R green = (expm1(-γ*R) - 0.5*γ^2*R^2) / (4pi*R) αG = α * green _integrands(f,g) do fi, gi dot(gi.value, αG*fi.value) end end function innerintegrals!(op::HH3DSingleLayerSng, test_neighborhood, test_refspace::LagrangeRefSpace{T,0} where {T}, trial_refspace::LagrangeRefSpace{T,0} where {T}, test_elements, trial_element, zlocal, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = trial_element.vertices x = cartesian(test_neighborhood) n = normalize((s1-s3)×(s2-s3)) ρ = x - dot(x - s1, n) * n scal, vec = WiltonInts84.wiltonints(s1, s2, s3, x, Val{1}) ∫G = (scal[2] + 0.5*γ^2*scal[4]) / (4π) zlocal[1,1] += α * ∫G * dx return nothing end # single layer with patch basis and pyramid testing function innerintegrals!(op::HH3DSingleLayerSng, test_neighborhood, test_refspace::LagrangeRefSpace{T,1} where {T}, trial_refspace::LagrangeRefSpace{T,0} where {T}, test_elements, trial_element, zlocal, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = trial_element.vertices t1, t2, t3 = test_elements.vertices x = cartesian(test_neighborhood) n = normalize((s1-s3)×(s2-s3)) ρ = x - dot(x - s1, n) * n scal, vec = WiltonInts84.wiltonints(s1, s2, s3, x, Val{1}) ∫G = (scal[2] + 0.5*γ^2*scal[4]) / (4π) Atot = 1/2*norm(cross(t3-t1,t3-t2)) for i in 1:numfunctions(test_refspace) Ai = 1/2*norm(cross(test_elements.vertices[mod1(i-1,3)]-x,test_elements.vertices[mod1(i+1,3)]-x)) g = Ai/Atot for j in 1:numfunctions(trial_refspace) zlocal[i,j] += α * ∫G * g * dx end end return nothing end # single layer with pyramid basis and patch testing function innerintegrals!(op::HH3DSingleLayerSng, test_neighborhood, test_refspace::LagrangeRefSpace{T,0} where {T}, trial_refspace::LagrangeRefSpace{T,1} where {T}, test_elements, trial_element, zlocal, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = trial_element.vertices x = cartesian(test_neighborhood) n = normalize((s1-s3)×(s2-s3)) ρ = x - dot(x - s1, n) * n ∫Rⁿ, ∫RⁿN = WiltonInts84.higherorder(s1,s2,s3,x,3) ∫G = (∫RⁿN[2] + 0.5*γ^2*∫RⁿN[3]) / (4π) for i in 1:numfunctions(trial_refspace) zlocal[1,i] += α * ∫G[i] * dx end return nothing end #single layer with pyramid basis and pyramid testing function innerintegrals!(op::HH3DSingleLayerSng, test_neighborhood, test_refspace::LagrangeRefSpace{T,1} where {T}, trial_refspace::LagrangeRefSpace{T,1} where {T}, test_elements, trial_element, zlocal, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = trial_element.vertices t1, t2, t3 = test_elements.vertices x = cartesian(test_neighborhood) n = normalize((s1-s3)×(s2-s3)) ρ = x - dot(x - s1, n) * n ∫Rⁿ, ∫RⁿN = WiltonInts84.higherorder(s1,s2,s3,x,3) ∫G = (∫RⁿN[2] + 0.5*γ^2*∫RⁿN[3]) / (4π) Atot = 1/2*norm(cross(t3-t1,t3-t2)) for i in 1:numfunctions(test_refspace) Ai = 1/2*norm(cross(test_elements.vertices[mod1(i-1,3)]-x,test_elements.vertices[mod1(i+1,3)]-x)) g = Ai/Atot for j in 1:numfunctions(trial_refspace) zlocal[i,j] += α * ∫G[j] * g * dx end end return nothing end # double layer transposed function (igd::Integrand{<:HH3DDoubleLayerTransposedReg})(x,y,f,g) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(igd.operator) r = cartesian(x) - cartesian(y) R = norm(r) iR = 1/R γR = γ*R expo = exp(-γR) gradgreen = ( -(γR + 1)*expo + (1 - 0.5*γR^2) ) * (i4pi*iR^3) * r n = normal(x) fvalue = getvalue(f) gvalue = getvalue(g) return _krondot(fvalue,gvalue) * dot(n, gradgreen) end #double layer transposed with patch basis and pyramid testing function innerintegrals!(op::HH3DDoubleLayerTransposedSng, test_neighborhood, test_refspace::LagrangeRefSpace{T,0,3,1} where {T}, trial_refspace::LagrangeRefSpace{T,0,3,1} where {T}, test_elements, trial_element, zlocal, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = trial_element.vertices t1, t2, t3 = test_elements.vertices x = cartesian(test_neighborhood) n = normalize((t1-t3)×(t2-t3)) ρ = x - dot(x - s1, n) * n scal, vec, grad = WiltonInts84.wiltonints(s1, s2, s3, x, Val{1}) ∫∇G = -(grad[1]+0.5*γ^2*grad[3])/(4π) ∫n∇G = dot(n,∫∇G) for i in 1:numfunctions(test_refspace) for j in 1:numfunctions(trial_refspace) zlocal[i,j] += α * ∫n∇G * dx end end return nothing end #double layer transposed with patch basis and pyramid testing function innerintegrals!(op::HH3DDoubleLayerTransposedSng, test_neighborhood, test_refspace::LagrangeRefSpace{T,1,3,3} where {T}, trial_refspace::LagrangeRefSpace{T,0,3,1} where {T}, test_elements, trial_element, zlocal, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = trial_element.vertices t1, t2, t3 = test_elements.vertices x = cartesian(test_neighborhood) n = normalize((t1-t3)×(t2-t3)) ρ = x - dot(x - s1, n) * n scal, vec, grad = WiltonInts84.wiltonints(s1, s2, s3, x, Val{1}) ∫∇G = -(grad[1]+0.5*γ^2*grad[3])/(4π) ∫n∇G = dot(n,∫∇G) Atot = 1/2*norm(cross(t3-t1,t3-t2)) for i in 1:numfunctions(test_refspace) Ai = 1/2*norm(cross(test_elements.vertices[mod1(i-1,3)]-x,test_elements.vertices[mod1(i+1,3)]-x)) g = Ai/Atot for j in 1:numfunctions(trial_refspace) zlocal[i,j] += α * ∫n∇G * g * dx end end return nothing end #double layer transposed with pyramid basis and patch testing function innerintegrals!(op::HH3DDoubleLayerTransposedSng, test_neighborhood, test_refspace::LagrangeRefSpace{T,0,3,1} where {T}, trial_refspace::LagrangeRefSpace{T,1,3,3} where {T}, test_elements, trial_element, zlocal, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = trial_element.vertices t1, t2, t3 = test_elements.vertices x = cartesian(test_neighborhood) n = normalize((t1-t3)×(t2-t3)) ρ = x - dot(x - s1, n) * n _, _, _, grad = WiltonInts84.higherorder(s1,s2,s3,x,3) ∫∇G = -(grad[1] + 0.5*γ^2*grad[2]) / (4π) for i in 1:numfunctions(test_refspace) for j in 1:numfunctions(trial_refspace) ∫n∇G = dot(n,∫∇G[j]) zlocal[i,j] += α * ∫n∇G * dx end end return nothing end #double layer transposed with pyramid basis and pyramid testing function innerintegrals!(op::HH3DDoubleLayerTransposedSng, test_neighborhood, test_refspace::LagrangeRefSpace{T,1,3,3} where {T}, trial_refspace::LagrangeRefSpace{T,1,3,3} where {T}, test_elements, trial_element, zlocal, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = trial_element.vertices t1, t2, t3 = test_elements.vertices x = cartesian(test_neighborhood) n = normalize((t1-t3)×(t2-t3)) ρ = x - dot(x - s1, n) * n _, _, _, grad = WiltonInts84.higherorder(s1,s2,s3,x,3) ∫∇G = -(grad[1] + 0.5*γ^2*grad[2]) / (4π) Atot = 1/2*norm(cross(t3-t1,t3-t2)) for i in 1:numfunctions(test_refspace) Ai = 1/2*norm(cross(test_elements.vertices[mod1(i-1,3)]-x,test_elements.vertices[mod1(i+1,3)]-x)) g = Ai/Atot for j in 1:numfunctions(trial_refspace) ∫n∇G = dot(n,∫∇G[j]) zlocal[i,j] += α * ∫n∇G * g * dx end end return nothing end # double layer function (igd::Integrand{<:HH3DDoubleLayerReg})(x,y,f,g) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(igd.operator) r = cartesian(x) - cartesian(y) R = norm(r) iR = 1/R γR = γ*R expo = exp(-γR) gradgreen = ( -(γR + 1)*expo + (1 - 0.5*γR^2) ) * (i4pi*iR^3) * r n = normal(y) fvalue = getvalue(f) gvalue = getvalue(g) return _krondot(fvalue,gvalue) * dot(n, -gradgreen) end #double layer with pyramid basis and pyramid testing function innerintegrals!(op::HH3DDoubleLayerSng, p, g::LagrangeRefSpace{T,1} where {T}, f::LagrangeRefSpace{T,1} where {T}, t, s, z, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = s.vertices t1, t2, t3 = t.vertices x = cartesian(p) n = normalize((s1-s3)×(s2-s3)) ρ = x - dot(x - s1, n) * n _, _, _, grad = WiltonInts84.higherorder(s1,s2,s3,x,3) ∫∇G = -(grad[1] + 0.5*γ^2*grad[2]) / (4π) Atot = 1/2*norm(cross(t3-t1,t3-t2)) for i in 1:numfunctions(g) Ai = 1/2*norm(cross(t.vertices[mod1(i-1,3)]-x,t.vertices[mod1(i+1,3)]-x)) g = Ai/Atot for j in 1:numfunctions(f) z[i,j] += α * dot(n,-∫∇G[j]) * g * dx end end return nothing end #double layer with patch basis and pyramid testing function innerintegrals!(op::HH3DDoubleLayerSng, p, g::LagrangeRefSpace{T,0} where {T}, f::LagrangeRefSpace{T,0} where {T}, t, s, z, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = s.vertices t1, t2, t3 = t.vertices x = cartesian(p) n = normalize((s1-s3)×(s2-s3)) ρ = x - dot(x - s1, n) * n scal, vec, grad = WiltonInts84.wiltonints(s1, s2, s3, x, Val{1}) ∫∇G = -(grad[1]+0.5*γ^2*grad[3])/(4π) for i in 1:numfunctions(g) for j in 1:numfunctions(f) z[i,j] += α * dot(n,-∫∇G) * dx #why the minus? end end return nothing end #double layer with patch basis and pyramid testing function innerintegrals!(op::HH3DDoubleLayerSng, p, g::LagrangeRefSpace{T,1} where {T}, f::LagrangeRefSpace{T,0} where {T}, t, s, z, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = s.vertices t1, t2, t3 = t.vertices x = cartesian(p) n = normalize((s1-s3)×(s2-s3)) ρ = x - dot(x - s1, n) * n scal, vec, grad = WiltonInts84.wiltonints(s1, s2, s3, x, Val{1}) ∫∇G = -(grad[1]+0.5*γ^2*grad[3])/(4π) Atot = 1/2*norm(cross(t3-t1,t3-t2)) for i in 1:numfunctions(g) Ai = 1/2*norm(cross(t.vertices[mod1(i-1,3)]-x,t.vertices[mod1(i+1,3)]-x)) g = Ai/Atot for j in 1:numfunctions(f) z[i,j] += α * dot(n,-∫∇G) * g * dx end end return nothing end #double layer with pyramid basis and patch testing function innerintegrals!(op::HH3DDoubleLayerSng, p, g::LagrangeRefSpace{T,0} where {T}, f::LagrangeRefSpace{T,1} where {T}, t, s, z, quadrature_rule::WiltonSERule, dx) # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) α = op.alpha s1, s2, s3 = s.vertices x = cartesian(p) n = normalize((s1-s3)×(s2-s3)) ρ = x - dot(x - s1, n) * n _, _, _, grad = WiltonInts84.higherorder(s1,s2,s3,x,3) ∫∇G = -(grad[1] + 0.5*γ^2*grad[2]) / (4π) for i in 1:numfunctions(g) for j in 1:numfunctions(f) z[i,j] += α * dot(n,-∫∇G[j]) * dx end end return nothing end function (igd::Integrand{<:HH3DHyperSingularReg})(x,y,f,g) α = igd.operator.alpha β = igd.operator.beta # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(igd.operator) r = cartesian(x) - cartesian(y) R = norm(r) iR = 1 / R green = (expm1(-γ*R) - 0.5*γ^2*R^2) / (4pi*R) nx = normal(x) ny = normal(y) _integrands(f,g) do fi, gi α*dot(nx,ny)*gi.value*fi.value*green + β*dot(gi.curl,fi.curl)*green end end function innerintegrals!(op::HH3DHyperSingularSng, p, g::LagrangeRefSpace{T,1} where {T}, f::LagrangeRefSpace{T,1} where {T}, t, s, z, quadrature_rule::WiltonSERule, dx) α = op.alpha β = op.beta # TODO: It is better to dispatch on γ # to handle the static case more efficiently γ = gamma(op) s1, s2, s3 = s.vertices t1, t2, t3 = t.vertices x = cartesian(p) nx = normalize((s1-s3)×(s2-s3)) ny = normalize((t1-t3)×(t2-t3)) ∫Rⁿ, ∫RⁿN = WiltonInts84.higherorder(s1,s2,s3,x,3) greenconst = (∫Rⁿ[2] + 0.5*γ^2*∫Rⁿ[3]) / (4π) greenlinear = (∫RⁿN[2] + 0.5*γ^2*∫RⁿN[3] ) / (4π) jt = volume(t) * factorial(dimension(t)) js = volume(s) * factorial(dimension(s)) curlt = [(t3-t2)/jt,(t1-t3)/jt,(t2-t1)/jt] curls = [(s3-s2)/js,(s1-s3)/js,(s2-s1)/js] Atot = 1/2*norm(cross(t3-t1,t3-t2)) for i in 1:numfunctions(g) Ai = 1/2*norm(cross(t.vertices[mod1(i-1,3)]-x,t.vertices[mod1(i+1,3)]-x)) g = Ai/Atot for j in 1:numfunctions(f) z[i,j] += β * dot(curlt[i],curls[j])*greenconst*dx + α*dot(nx,ny) * greenlinear[j]*g*dx end end end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1093
struct PlaneWaveHH3DTD{T,P,F} <: TDFunctional{T} direction::P speed_of_light::T signature::F amplitude::T end function planewave(direction, speedoflight::Number, signature, amplitude=one(speedoflight)::Number) PlaneWaveHH3DTD(direction, speedoflight, signature, amplitude) end *(a, f::PlaneWaveHH3DTD) = PlaneWaveHH3DTD(f.direction, f.speed_of_light, f.signature, a*f.amplitude) function(f::PlaneWaveHH3DTD)(r,t) k = f.direction u = sum(k[i]*r[i] for i in 1:length(k)) #u = dot(f.direction, r) a = f.amplitude c = f.speed_of_light h = f.signature a * h(c*cartesian(t)[1] - u) end function gradient(f::PlaneWaveHH3DTD) @assert f.amplitude ≈ 1 PlaneWaveMWTD( f.direction, -f.direction, f.speed_of_light, derive(f.signature) ) end struct DotTraceHH{T,F} <: TDFunctional{T} field::F end dot(::NormalVector, field::TDFunctional) = DotTraceHH{scalartype(field), typeof(field)}(field) function (f::DotTraceHH)(p,t) n = normal(p) x = cartesian(p) return dot(n, f.field(x,t)) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
7130
abstract type HH3DTDBIO{T} <: RetardedPotential{T} end struct HH3DSingleLayerTDBIO{T} <: HH3DTDBIO{T} "speed of light" speed_of_light::T "number of temporal differentiations" num_diffs::Int end HH3DSingleLayerTDBIO(c) = HH3DSingleLayerTDBIO(c, 0) struct HH3DHyperSingularTDBIO{T} <: HH3DTDBIO{T} speed_of_light::T weight_of_weakly_singular_term::T weight_of_hyper_singular_term::T num_diffs_on_weakly_singular_term::Int num_diffs_on_hyper_singular_term::Int end function HH3DHyperSingularTDBIO(;speed_of_light, numdiffs) id = one(speed_of_light) HH3DHyperSingularTDBIO(speed_of_light, id, id, numdiffs+1, numdiffs-1) end struct HH3DDoubleLayerTDBIO{T} <: HH3DTDBIO{T} speed_of_light::T weight::T num_diffs::Int end HH3DDoubleLayerTDBIO(;speed_of_light) = HH3DDoubleLayerTDBIO(speed_of_light,one(speed_of_light),0) defaultquadstrat(::HH3DTDBIO, tfs, bfs) = nothing # See: ?BEAST.quaddata for help function quaddata(operator::HH3DTDBIO, test_local_space, trial_local_space, time_local_space, test_element, trial_element, time_element, quadstrat::Nothing) dmax = numfunctions(time_local_space)-1 bn = binomial.((0:dmax),(0:dmax)') V = eltype(test_element[1].vertices) ws = WiltonInts84.workspace(V) order = 4 @show order quadpoints(test_local_space, test_element, (order,)), bn, ws end # See: ?BEAST.quadrule for help function quadrule(operator::HH3DTDBIO, test_local_space, trial_local_space, time_local_space, p, test_element, q, trial_element, r, time_element, quad_data, quadstrat::Nothing) # WiltonInts84Strat(quad_data[1,p]) qd = quad_data WiltonInts84Strat(qd[1][1,p],qd[2],qd[3]) end function innerintegrals!(zlocal, operator::HH3DSingleLayerTDBIO, test_point, test_local_space, trial_local_space, time_local_space, test_element, trial_element, time_element, quad_rule, quad_weight) # error("Here!!!") dx = quad_weight x = cartesian(test_point) # n = normal(test_point) # a = trial_element[1] # ξ = x - dot(x -a, n) * n r = time_element[1] R = time_element[2] @assert r < R N = max(degree(time_local_space), 1) ∫G, ∫vG, ∫∇G = WiltonInts84.wiltonints( trial_element[1], trial_element[2], trial_element[3], x, r, R, Val{2}, quad_rule.workspace) a = dx / (4*pi) D = operator.num_diffs @assert D == 0 @assert numfunctions(test_local_space) == 1 @assert numfunctions(trial_local_space) == 1 @inline function tmRoR_sl(d, iG) sgn = isodd(d) ? -1 : 1 r = sgn * iG[d+2] end # bns = quad_rule.binomials @assert D == 0 for k in 1 : numfunctions(time_local_space) d = k - 1 d < D && continue q = reduce(*, d-D+1:d ,init=1) zlocal[1,1,k] += a * q * tmRoR_sl(d-D, ∫G) end # k end function innerintegrals!(zlocal, operator::HH3DHyperSingularTDBIO, test_point, test_local_space, trial_local_space, time_local_space, test_element, trial_element, time_element, quad_rule, quad_weight) dx = quad_weight x = cartesian(test_point) nx = normal(test_point) ny = normal(trial_element) ndotn = dot(nx,ny) a = trial_element[1] ξ = x - dot(x -a, ny) * ny r = time_element[1] R = time_element[2] @assert r < R N = max(degree(time_local_space), 1) ∫G, ∫Gξy, = WiltonInts84.wiltonints( trial_element[1], trial_element[2], trial_element[3], x, r, R, Val{N-1},quad_rule.workspace) @assert numfunctions(test_local_space) <= 3 @assert numfunctions(trial_local_space) == 3 @inline function tmRoR(d, iG) r = (isodd(d) ? -1 : 1) * iG[d+2] end @inline function tmRoRf(d, ∫G, ∫Gξy, bξ, h, m) (isodd(d) ? -1 : 1) * ((1 - h*dot(m,bξ)) * ∫G[d+2] - h*dot(m, ∫Gξy[d+2])) end test_values = test_local_space(test_point) trial_values = trial_local_space(center(trial_element)) # weakly singular term α = dx / (4π) * operator.weight_of_weakly_singular_term Ds = operator.num_diffs_on_weakly_singular_term for i in 1 : numfunctions(test_local_space) g, curlg = test_values[i] for j in 1 : numfunctions(trial_local_space) b = trial_element[j] opp_edge = trial_element[mod1(j+2,3)] - trial_element[mod1(j+1,3)] h = norm(opp_edge)/2/volume(trial_element) m = normalize(cross(opp_edge, ny)) for k in 1 : numfunctions(time_local_space) d = k-1 d < Ds && continue q = reduce(*, d-Ds+1:d ,init=1) zlocal[i,j,k] += α * q * g * ndotn * tmRoRf(d-Ds, ∫G, ∫Gξy, ξ-b, h, m) end end end # Hyper-singular term β = dx / (4π) * operator.weight_of_hyper_singular_term Dh = operator.num_diffs_on_hyper_singular_term for i in 1 : numfunctions(test_local_space) g, curlg = test_values[i] for j in 1 : numfunctions(trial_local_space) _, curlf = trial_values[j] for k in 1 : numfunctions(time_local_space) d = k - 1 d < Dh && continue q = reduce(*, d-Dh+1:d ,init=1) zlocal[i,j,k] += β * q * dot(curlg, curlf) * tmRoR(d-Dh, ∫G) end end end end function innerintegrals!(zlocal, operator::HH3DDoubleLayerTDBIO, test_point, test_local_space, trial_local_space, time_local_space, test_element, trial_element, time_element, quad_rule, quad_weight) @assert numfunctions(test_local_space) <= 3 @assert numfunctions(trial_local_space) == 1 dx = quad_weight x = cartesian(test_point) nx = normal(test_point) # a = trial_element[1] # ξ = x - dot(x -a, ny) * ny r = time_element[1] R = time_element[2] @assert r < R N = max(degree(time_local_space), 1) ∫G, ∫Gξy, ∫∇G = WiltonInts84.wiltonints( trial_element[1], trial_element[2], trial_element[3], x, r, R, Val{N-1},quad_rule.workspace) @inline function grad_tmRoR(d,∇G) σ = isodd(d) ? -1 : 1 return σ * ∇G[d+1] end test_values = test_local_space(test_point) trial_values = trial_local_space(center(trial_element)) @assert all(getindex.(trial_values,1) .≈ [1]) # @assert all(getindex.(trial_values,2) .≈ Ref([0,0,0])) # weakly singular term α = dx / (4π) * operator.weight D = operator.num_diffs for i in 1 : numfunctions(test_local_space) g, curlg = test_values[i] for j in 1 : numfunctions(trial_local_space) f, curlf = trial_values[j] for k in 1 : numfunctions(time_local_space) d = k-1 d < D && continue q = reduce(*, d-D+1:d ,init=1) @assert q == 1 zlocal[i,j,k] += α * q * g * dot(nx, grad_tmRoR(d-D, ∫∇G)) * f end end end # @assert all(zlocal[:,:,2] .≈ 0) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
58
struct TDHH3DSingleLayerNear{T} speed_of_light::T end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2358
function momintegrals!(op::MWSingleLayer3D, g::RTRefSpace, f::RTRefSpace, t, s, z, strat::BogaertStrategy) T, GG = GetIntegrals(t, s, op.gamma, strat) # Get the (u,v,w) → (x,y,z) tf matrix for tcell == bcell P = @SMatrix [ t[1][1] t[2][1] t[3][1] t[1][2] t[2][2] t[3][2] t[1][3] t[2][3] t[3][3] ] R = @SMatrix [ s[1][1] s[2][1] s[3][1] s[1][2] s[2][2] s[3][2] s[1][3] s[2][3] s[3][3] ] ∫G = sum(T) Q = P*T ∫xG = @SVector [ Q[1,1]+Q[1,2]+Q[1,3], Q[2,1]+Q[2,2]+Q[2,3], Q[3,1]+Q[3,2]+Q[3,3], ] Q = R*transpose(T) ∫Gy = @SVector [ Q[1,1]+Q[1,2]+Q[1,3], Q[2,1]+Q[2,2]+Q[2,3], Q[3,1]+Q[3,2]+Q[3,3] ] Q = P*T*transpose(R) ∫xGy = Q[1,1] + Q[2,2] + Q[3,3] c₁ = op.α c₂ = op.β # Now build the shape-shape interactions from these α = 1 / volume(t) / volume(s) / 4 γ = op.gamma for i in 1:3 a = t[i] for j in 1:3 b = s[j] z[i,j] = α*c₁*(∫xGy - dot(a,∫Gy) - dot(b,∫xG) + dot(a,b)*∫G) + 4α*c₂*∫G end end end function momintegrals!(op::MWDoubleLayer3D, g::RTRefSpace, f::RTRefSpace, τ, σ, z, strat::BogaertStrategy) # Get the primitives r = τ.vertices s = σ.vertices G, GG = GetIntegrals(τ, σ, op.gamma, strat) # representation of RT elements in terms of # the tangents tu, tv and coordinates u,v,w # f_1 = [ (-v-w) t_u + v t_v ] / j # f_2 = [ u t_u + (-u-w) t_v ] / j # f_3 = [ u t_u + v t_v ] / j α = @SMatrix [ 0 -1 -1 1 0 0 1 0 0] β = @SMatrix [ 0 1 0 -1 0 -1 0 1 0] duu = τ.tangents[1] × σ.tangents[1] duv = τ.tangents[1] × σ.tangents[2] dvu = τ.tangents[2] × σ.tangents[1] dvv = τ.tangents[2] × σ.tangents[2] J = 4 * volume(σ) * volume(τ) for i in 1:3 for j in 1:3 Iuu = sum([α[i,p] * GG[p,q] * α[j,q] for p in 1:3, q in 1:3]) Iuv = sum([α[i,p] * GG[p,q] * β[j,q] for p in 1:3, q in 1:3]) Ivu = sum([β[i,p] * GG[p,q] * α[j,q] for p in 1:3, q in 1:3]) Ivv = sum([β[i,p] * GG[p,q] * β[j,q] for p in 1:3, q in 1:3]) z[i,j] = (dot(duu, Iuu) + dot(duv, Iuv) + dot(dvu, Ivu) + dot(dvv, Ivv)) / J end end end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2853
abstract type MWFarField <: FarField end """ Operator to compute the far field of a current distribution. In particular, given the current distribution ``j`` this operator allows for the computation of ```math A j = n × ∫_Γ e^{γ ̂x ⋅ y} dy ``` where ``̂x`` is the unit vector in the direction of observation. Note that the assembly routing expects the observation directions to be normalised by the caller. """ struct MWFarField3D{K, U} <: MWFarField gamma::K amplitude::U end struct MWDoubleLayerFarField3D{K, U} <: MWFarField gamma::K amplitude::U end struct MWDoubleLayerRotatedFarField3D{K,U} <: MWFarField gamma::K amplitude::U end function MWFarField3D(; gamma=nothing, wavenumber=nothing, amplitude=nothing ) gamma, _ = gamma_wavenumber_handler(gamma, wavenumber) @assert !isstatic(gamma) amplitude === nothing && (amplitude = 1.0) return MWFarField3D(gamma, amplitude) end MWFarField3D(op::MWSingleLayer3D{T,U}) where {T,U} = MWFarField3D(op.gamma, sqrt(op.α*op.β)) function MWDoubleLayerFarField3D(; gamma=nothing, wavenumber=nothing, amplitude=nothing ) gamma, _ = gamma_wavenumber_handler(gamma, wavenumber) @assert !isstatic(gamma) amplitude === nothing && (amplitude = 1.0) return MWDoubleLayerFarField3D(gamma, amplitude) end MWDoubleLayerFarField3D(op::MWDoubleLayer3D{T}) where {T} = MWDoubleLayerFarField3D(op.gamma, 1.0) # quaddata(op::MWFarField,rs,els) = quadpoints(rs,els,(3,)) # quadrule(op::MWFarField,refspace,p,y,q,el,qdata) = qdata[1,q] kernelvals(op::MWFarField,y,p) = exp(op.gamma*dot(y,cartesian(p))) function integrand(op::MWFarField3D,krn,y,f,p) op.amplitude*(y × (krn * f[1])) × y end function integrand(op::MWDoubleLayerFarField3D,krn,y,f,p) op.amplitude*(y × (krn * f[1])) end struct MWFarField3DDropConstant{K, U} <: MWFarField gamma::K coeff::U end kernelvals(op::MWFarField3DDropConstant,y,p) = expm1(op.gamma*dot(y,cartesian(p))) function integrand(op::MWFarField3DDropConstant,krn,y,f,p) op.coeff*(y × (krn * f[1])) × y end function MWDoubleLayerRotatedFarField3D(; gamma=nothing, wavenumber=nothing, amplitude=nothing ) gamma, _ = gamma_wavenumber_handler(gamma, wavenumber) @assert !isstatic(gamma) amplitude === nothing && (amplitude = 1.0) return MWDoubleLayerRotatedFarField3D(gamma, amplitude) end MWDoubleLayerRotatedFarField3D(op::DoubleLayerRotatedMW3D{T,U}) where {T,U} = MWDoubleLayerRotatedFarField3D(op.gamma, T(1)) function integrand(op::MWDoubleLayerRotatedFarField3D, krn, y, f, p) op.amplitude * (y × ((krn * f[1]) × normal(p))) end LinearAlgebra.cross(::NormalVector, a::MWDoubleLayerFarField3D) = MWDoubleLayerRotatedFarField3D(a.gamma, a.amplitude) LinearAlgebra.cross(::NormalVector, a::MWDoubleLayerRotatedFarField3D) = MWDoubleLayerFarField3D(a.gamma, -a.amplitude)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2203
module Maxwell3D using ..BEAST Mod = BEAST """ singlelayer(;gamma, alpha, beta) singlelayer(;wavenumber, alpha, beta) Bilinear form given by: ```math α ∬_{Γ×Γ} j(x)⋅k(y) G_{γ}(x,y) + β ∬_{Γ×Γ} div j(x) div k(y) G_{γ}(x,y) ``` with ``G_{γ} = e^{-γ|x-y|} / 4π|x-y|``. """ function singlelayer(; gamma=nothing, wavenumber=nothing, alpha=nothing, beta=nothing) gamma, wavenumber = Mod.gamma_wavenumber_handler(gamma, wavenumber) if Mod.isstatic(gamma) # static case @assert !(isnothing(alpha)) && !(isnothing(beta)) end alpha === nothing && (alpha = -gamma) beta === nothing && (beta = -1/gamma) Mod.MWSingleLayer3D(gamma, alpha, beta) end weaklysingular(;wavenumber) = singlelayer(;wavenumber, alpha=-im*wavenumber, beta=zero(im*wavenumber)) hypersingular(;wavenumber) = singlelayer(; wavenumber, alpha=zero(im*wavenumber), beta=-1/(im*wavenumber)) """ doublelayer(;gamma) doublelaher(;wavenumber) Bilinear form given by: ```math α ∬_{Γ^2} k(x) ⋅ (∇G_γ(x-y) × j(y)) ``` with ``G_γ = e^{-γ|x-y|} / 4π|x-y|`` """ function doublelayer(; alpha=nothing, gamma=nothing, wavenumber=nothing) gamma, wavenumber = Mod.gamma_wavenumber_handler(gamma, wavenumber) if isnothing(alpha) if Mod.isstatic(gamma) # static case alpha = 1.0 # Default to double precision else alpha = one(gamma) end end Mod.MWDoubleLayer3D(alpha, gamma) end planewave(; direction = error("missing arguement `direction`"), polarization = error("missing arguement `polarization`"), wavenumber = error("missing arguement `wavenumber`"), amplitude = one(real(typeof(wavenumber)))) = Mod.PlaneWaveMW(direction, polarization, wavenumber*im, amplitude) farfield(; wavenumber = error("missing argument: `wavenumber`")) = Mod.MWFarField3D(wavenumber=wavenumber) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
6166
mutable struct PlaneWaveMW{T,P} direction::P polarisation::P gamma::T amplitude::T end function PlaneWaveMW(d,p,γ,a = 1) T = promote_type(eltype(d), eltype(p), typeof(γ), typeof(a)) P = similar_type(typeof(d), T) PlaneWaveMW{T,P}(d,p,γ,a) end scalartype(x::PlaneWaveMW{T,P}) where {T,P} = promote_type(T, eltype(P)) """ planewavemw3d(;direction, polarization, wavenumber, gamma[, amplitude=1]) Create a plane wave solution to Maxwell's equations. """ function planewavemw3d(; direction = error("missing arguement `direction`"), polarization = error("missing arguement `polarization`"), wavenumber = nothing, gamma = nothing, amplitude = 1, ) gamma, wavenumber = gamma_wavenumber_handler(gamma, wavenumber) isstatic(gamma) && (gamma = zero(eltype(direction))) return PlaneWaveMW(direction, polarization, gamma, amplitude) end function (e::PlaneWaveMW)(x) γ = e.gamma d = e.direction u = e.polarisation a = e.amplitude a * exp(-γ * dot(d, x)) * u end function curl(field::PlaneWaveMW) γ = field.gamma d = field.direction u = field.polarisation a = field.amplitude v = d × u b = -a * γ PlaneWaveMW(d, v, γ, b) end *(a::Number, e::PlaneWaveMW) = PlaneWaveMW(e.direction, e.polarisation, e.gamma, a*e.amplitude) abstract type Dipole end mutable struct DipoleMW{T,P} <: Dipole location::P orientation::P gamma::T end function DipoleMW(l,o,γ) T = promote_type(eltype(l), eltype(o), typeof(γ)) P = similar_type(typeof(l), T) DipoleMW{T,P}(l,o,γ) end scalartype(x::DipoleMW{T,P}) where {T,P} = promote_type(T, eltype(P)) mutable struct curlDipoleMW{T,P} <: Dipole location::P orientation::P gamma::T end function curlDipoleMW(l,o,γ) T = promote_type(eltype(l), eltype(o), typeof(γ)) P = similar_type(typeof(l), T) curlDipoleMW{T,P}(l,o,γ) end scalartype(x::curlDipoleMW{T,P}) where {T,P} = promote_type(T, eltype(P)) """ dipolemw3d(;location, orientation, wavenumber) Create an electric dipole solution to Maxwell's equations representing the electric field part. Implementation is based on (9.18) of Jackson's “Classical electrodynamics”, with the notable difference that the ``\exp(ikr)`` is used. """ function dipolemw3d(; location = error("missing arguement `location`"), orientation = error("missing arguement `orientation`"), wavenumber = nothing, gamma = nothing ) gamma, wavenumber = gamma_wavenumber_handler(gamma, wavenumber) isstatic(gamma) && (gamma = zero(eltype(orientation))) return DipoleMW(location, orientation, gamma) end function (d::DipoleMW)(x; isfarfield=false) γ = d.gamma x_0 = d.location p = d.orientation if isfarfield # postfactor (4*π*im)/k = (-4*π)/γ to be consistent with BEAST far field computation # and, of course, adapted phase factor exp(im*k*dot(n,x_0)) with # respect to (9.19) of Jackson's Classical Electrodynamics r = norm(x) n = x/r return cross(cross(n,1/(4*π)*(-γ^2*cross(cross(n,p),n))*exp(γ*dot(n,x_0))*(-4*π)/γ),n) else r = norm(x-x_0) n = (x - x_0)/r return 1/(4*π)*exp(-γ*r)*(-γ^2/r*cross(cross(n,p),n) + (1/r^3 + γ/r^2)*(3*n*dot(n,p) - p)) end end function (d::curlDipoleMW)(x; isfarfield=false) γ = d.gamma x_0 = d.location p = d.orientation if isfarfield # postfactor (4*π*im)/k to be consistent with BEAST far field computation r = norm(x) n = x/r return (-γ)*(-γ^2)/(4*π)*cross(n,p)*(-4*π)/γ*exp(γ*dot(n,x_0)) else r = norm(x-x_0) n = (x - x_0)/r return γ^3/(4*π)*cross(n,p)*exp(-γ*r)/r*(1 + 1/(γ*r)) end end function curl(d::DipoleMW) return curlDipoleMW(d.location, d.orientation, d.gamma) end *(a::Number, d::DipoleMW) = DipoleMW(d.location, a .* d.orientation, d.gamma) *(a::Number, d::curlDipoleMW) = curlDipoleMW(d.location, a .* d.orientation, d.gamma) mutable struct CrossTraceMW{F} <: Functional field::F end scalartype(x::CrossTraceMW) = scalartype(x.field) mutable struct TangTraceMW{F} <: Functional field::F end scalartype(t::TangTraceMW) = scalartype(t.field) cross(::NormalVector, p::Function) = CrossTraceMW(p) cross(::NormalVector, p::PlaneWaveMW) = CrossTraceMW(p) cross(::NormalVector, p::Dipole) = CrossTraceMW(p) cross(t::CrossTraceMW, ::NormalVector) = TangTraceMW(t.field) function (ϕ::CrossTraceMW)(p) F = ϕ.field x = cartesian(p) n = normal(p) return n × F(x) end function (ϕ::TangTraceMW)(p) F = ϕ.field x = cartesian(p) n = normal(p) return (n × F(x)) × n end integrand(::TangTraceMW, gx, ϕx) = gx[1] ⋅ ϕx integrand(::CrossTraceMW, test_vals, field_val) = test_vals[1] ⋅ field_val struct NDotTrace{T,F} <: Functional field::F end NDotTrace(f::F) where {F} = NDotTrace{scalartype(f), F}(f) NDotTrace{T}(f::F) where {T,F} = NDotTrace{T,F}(f) scalartype(s::NDotTrace{T}) where {T} = T (ϕ::NDotTrace)(p) = dot(normal(p), ϕ.field(cartesian(p))) integrand(::NDotTrace, g, ϕ) = dot(g.value, ϕ) LinearAlgebra.dot(::NormalVector, f) = NDotTrace(f) mutable struct CurlGreen{T,U,V} wavenumber::T source::U position::V end function (f::CurlGreen)(x) γ = im * f.wavenumber r = x-f.position R = norm(r) g = exp(-γ*R)/(4π*R) j = f.source return -γ/R * (1 + 1/(γ*R)) * g * (r × j) end mutable struct CurlCurlGreen{T,U,V} wavenumber::T source::U position::V end cross(::NormalVector, p::CurlGreen) = CrossTraceMW(p) cross(::NormalVector, p::CurlCurlGreen) = CrossTraceMW(p) function (f::CurlCurlGreen)(x) γ = im * f.wavenumber r = x - f.position R = norm(r) g = exp(-γ*R)/(4π*R) j = f.source return (-γ^2/R^2 * (r × j) × r + (1/R^2 + γ/R)/R^2 * (3r * dot(r,j) - R^2 * j)) * g end curl(f::CurlGreen) = CurlCurlGreen(f.wavenumber, f.source, f.position) function curl(f::CurlCurlGreen) κ = f.wavenumber j = κ^2 * f.source x = f.position return CurlGreen(κ, j, x) end Base.:*(a::Number, f::CurlGreen) = CurlGreen(f.wavenumber, a*f.source, f.position) Base.:*(a::Number, f::CurlCurlGreen) = CurlCurlGreen(f.wavenumber, a*f.source, f.position)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
7678
abstract type MaxwellOperator3D{T,K} <: IntegralOperator end abstract type MaxwellOperator3DReg{T,K} <: MaxwellOperator3D{T,K} end scalartype(op::MaxwellOperator3D{T,K}) where {T, K <: Val{0}} = T scalartype(op::MaxwellOperator3D{T,K}) where {T, K} = promote_type(T, K) gamma(op::MaxwellOperator3D{T,Val{0}}) where {T} = zero(T) gamma(op::MaxwellOperator3D{T,K}) where {T, K} = op.gamma struct MWSingleLayer3D{T,U} <: MaxwellOperator3D{T,U} gamma::T α::U β::U end gamma(op::MWSingleLayer3D{Val{0}, U}) where {U} = zero(U) scalartype(op::MWSingleLayer3D{T,U}) where {T,U} = promote_type(T,U) # sign_upon_permutation(op::MWSingleLayer3D, I, J) = 1 MWSingleLayer3D(gamma) = MWSingleLayer3D(gamma, -gamma, -1/(gamma)) MWWeaklySingular(gamma) = MWSingleLayer3D(gamma, 1, 0) MWHyperSingular(gamma) = MWSingleLayer3D(gamma, 0, 1) export Maxwell3D struct MWSingleLayer3DReg{T,U} <: MaxwellOperator3DReg{T,U} gamma::T α::U β::U end struct MWSingleLayer3DSng{T,U} <: MaxwellOperator3D{T,U} gamma::T α::U β::U end regularpart(op::MWSingleLayer3D) = MWSingleLayer3DReg(op.gamma, op.α, op.β) singularpart(op::MWSingleLayer3D) = MWSingleLayer3DSng(op.gamma, op.α, op.β) function _legendre(n,a,b) x, w = FastGaussQuadrature.gausslegendre(n) w .*= (b-a)/2 x .= (x.+1)/2*(b-a).+a collect(zip(x,w)) end # defaultquadstrat(op::MaxwellOperator3D, tfs::Space, bfs::Space) = DoubleNumWiltonSauterQStrat(2,3,6,7,5,5,4,3) defaultquadstrat(op::MaxwellOperator3D, tfs::RTRefSpace, bfs::RTRefSpace) = DoubleNumWiltonSauterQStrat(2,3,6,7,5,5,4,3) # defaultquadstrat(op::MaxwellOperator3D, tfs::RefSpace, bfs::RefSpace) = DoubleNumWiltonSauterQStrat(2,3,6,7,5,5,4,3) struct MWDoubleLayer3D{T,K} <: MaxwellOperator3D{T,K} alpha::T gamma::K end # sign_upon_permutation(op::MWDoubleLayer3D, I, J) = 1 struct MWDoubleLayer3DSng{T,K} <: MaxwellOperator3D{T,K} alpha::T gamma::K end struct MWDoubleLayer3DReg{T,K} <: MaxwellOperator3DReg{T,K} alpha::T gamma::K end MWDoubleLayer3D(gamma) = MWDoubleLayer3D(1.0, gamma) # For legacy purposes regularpart(op::MWDoubleLayer3D) = MWDoubleLayer3DReg(op.alpha, op.gamma) singularpart(op::MWDoubleLayer3D) = MWDoubleLayer3DSng(op.alpha, op.gamma) # function quadrule(op::MaxwellOperator3D, g::BDMRefSpace, f::BDMRefSpace, i, τ, j, σ, qd, # qs::DoubleNumWiltonSauterQStrat) # hits = 0 # dtol = 1.0e3 * eps(eltype(eltype(τ.vertices))) # dmin2 = floatmax(eltype(eltype(τ.vertices))) # for t in τ.vertices # for s in σ.vertices # d2 = LinearAlgebra.norm_sqr(t-s) # dmin2 = min(dmin2, d2) # hits += (d2 < dtol) # end # end # hits == 3 && return SauterSchwabQuadrature.CommonFace(qd.gausslegendre[3]) # hits == 2 && return SauterSchwabQuadrature.CommonEdge(qd.gausslegendre[2]) # hits == 1 && return SauterSchwabQuadrature.CommonVertex(qd.gausslegendre[1]) # h2 = volume(σ) # xtol2 = 0.2 * 0.2 # k2 = abs2(gamma(op)) # return DoubleQuadRule( # qd.tpoints[1,i], # qd.bpoints[1,j],) # end # function qrdf(op::MaxwellOperator3D, g::RTRefSpace, f::RTRefSpace, i, τ, j, σ, qd) # # defines coincidence of points # dtol = 1.0e3 * eps(eltype(eltype(τ.vertices))) # # decides on whether to use singularity extraction # xtol = 0.2 # k = norm(gamma(op)) # hits = 0 # xmin = xtol # for t in τ.vertices # for s in σ.vertices # d = norm(t-s) # xmin = min(xmin, k*d) # if d < dtol # hits +=1 # break # end # end # end # xmin < xtol && return WiltonSERule( # qd.tpoints[1,i], # DoubleQuadRule( # qd.tpoints[2,i], # qd.bpoints[2,j], # ), # ) # return DoubleQuadRule( # qd.tpoints[1,i], # qd.bpoints[1,j], # ) # end ################################################################################ # # Kernel definitions # ################################################################################ const i4pi = 1 / (4pi) function (igd::Integrand{<:MWSingleLayer3D})(x,y,f,g) α = igd.operator.α β = igd.operator.β γ = igd.operator.gamma r = cartesian(x) - cartesian(y) R = norm(r) iR = 1 / R green = exp(-γ*R)*(i4pi*iR) αG = α * green βG = β * green _integrands(f,g) do fi,gj αG * dot(fi.value, gj.value) + βG * dot(fi.divergence, gj.divergence) end end function (igd::Integrand{<:MWSingleLayer3DReg})(x,y,f,g) α = igd.operator.α β = igd.operator.β γ = igd.operator.gamma r = cartesian(x) - cartesian(y) R = norm(r) γR = γ*R # iR = 1 / R green = (expm1(-γR) + γR - 0.5*γR^2) / (4pi*R) αG = α * green βG = β * green _integrands(f,g) do fi,gj αG * dot(fi.value, gj.value) + βG * dot(fi.divergence, gj.divergence) end end function (igd::Integrand{<:MWDoubleLayer3D})(x,y,f,g) γ = igd.operator.gamma r = cartesian(x) - cartesian(y) R = norm(r) iR = 1/R green = exp(-γ*R)*(iR*i4pi) gradgreen = -(γ + iR) * green * (iR * r) fvalue = getvalue(f) gvalue = getvalue(g) G = cross.(Ref(gradgreen), gvalue) return _krondot(fvalue, G) end function (igd::Integrand{<:MWDoubleLayer3DReg})(x,y,f,g) γ = igd.operator.gamma r = cartesian(x) - cartesian(y) R = norm(r) γR = γ*R iR = 1/R expo = exp(-γR) green = (expo - 1 + γR - 0.5*γR^2) * (i4pi*iR) gradgreen = ( -(γR + 1)*expo + (1 - 0.5*γR^2) ) * (i4pi*iR^3) * r fvalue = getvalue(f) gvalue = getvalue(g) G = cross.(Ref(gradgreen), gvalue) return _krondot(fvalue, G) end ################################################################################ # # Handling of operator parameters (Helmholtz and Maxwell) # ################################################################################ """ gamma_wavenumber_handler(gamma, wavenumber) This function handles the input of `gamma` and `wavenumber`. It throws an error if both `gamma` and `wavenumber` are provided. If neither is provided, it assumes a static problem and returns `Val(0)` for `gamma` and `wavenumber`. # Arguments - `gamma`: `im` * `wavenumber` or `nothing`. - `wavenumber`: `wavenumber` or `nothing`. # Returns - `gamma` and `wavenumber`: Appropriate pair `gamma` and `wavenumber`. """ function gamma_wavenumber_handler(gamma, wavenumber) if !isnothing(gamma) && !isnothing(wavenumber) error("Supplying both gamma and wavenumber is not supported.") elseif isnothing(gamma) && isnothing(wavenumber) # if neither gamma nor wavenumber is supplied, we are assuming a static problem return Val(0), Val(0) end if isnothing(gamma) && !isnothing(wavenumber) if iszero(real(wavenumber)) gamma = -imag(wavenumber) else gamma = im*wavenumber end end return gamma, wavenumber end """ isstatic(gamma) This function checks if the provided `gamma` value represents a static problem. It returns true if `gamma` is of type `Val{0}` indicating a static problem. # Arguments - `gamma`: `gamma` value. # Returns - A boolean indicating whether the problem is static or not. """ function isstatic(gamma) return typeof(gamma) == Val{0} end function isstatic(op::MaxwellOperator3D) return isstatic(op.gamma) end function operator_parameter_handler(alpha, gamma, wavenumber) gamma, wavenumber = gamma_wavenumber_handler(gamma, wavenumber) if alpha === nothing if isstatic(gamma) # static problem alpha = 1.0 # default to double precision else alpha = one(real(typeof(gamma))) end end return alpha, gamma end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2032
mutable struct MWSingleLayerField3D{T, U} gamma::T α::U β::U end mutable struct MWDoubleLayerField3D{T} gamma::T end """ MWSingleLayerField3D(;gamma, wavenumber, alpha, beta) Create the single layer near field operator, for use with `potential`. """ function MWSingleLayerField3D(; gamma=nothing, wavenumber=nothing, alpha=nothing, beta=nothing ) gamma, _ = gamma_wavenumber_handler(gamma, wavenumber) @assert !isstatic(gamma) alpha === nothing && (alpha = -gamma) beta === nothing && (beta = -1/gamma) MWSingleLayerField3D(gamma, alpha, beta) end MWSingleLayerField3D(op::MWSingleLayer3D{T,U}) where {T,U} = MWSingleLayerField3D(op.gamma, op.α, op.β) """ MWDoubleLayerField3D(; gamma, wavenumber) Create the double layer near field operator, for use with `potential`. """ function MWDoubleLayerField3D(; gamma=nothing, wavenumber=nothing ) gamma, _ = gamma_wavenumber_handler(gamma, wavenumber) @assert !isstatic(gamma) MWDoubleLayerField3D(gamma) end MWDoubleLayerField3D(op::MWDoubleLayer3D) = MWDoubleLayerField3D(op.gamma) const MWField3D = Union{MWSingleLayerField3D,MWDoubleLayerField3D} defaultquadstrat(op::MWField3D, basis) = SingleNumQStrat(2) quaddata(op::MWField3D,rs,els,qs::SingleNumQStrat) = quadpoints(rs,els,(qs.quad_rule,)) quadrule(op::MWField3D,refspace,p,y,q,el,qdata,qs::SingleNumQStrat) = qdata[1,q] function kernelvals(op::MWField3D,y,p) γ = op.gamma r = y - cartesian(p) R = norm(r) γR = γ*R expn = exp(-γR) green = expn / (4pi*R) gradgreen = -(γ + 1/R) * green / R * r krn = (trans=r, dist=R, green=green, gradgreen=gradgreen) end function integrand(op::MWSingleLayerField3D, krn, y, fp, p) γ = op.gamma j = fp.value ρ = fp.divergence G = krn.green ∇G = krn.gradgreen op.α*G*j - op.β*∇G*ρ end function integrand(op::MWDoubleLayerField3D, krn, y, fp, p) j = fp.value ∇G = krn.gradgreen ∇G × j end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1143
""" Describe a single layer operator from the surface to a line. ```math <v, Su> = ∫_γ dx v(x) ∫_Γ dy \frac{e^{-ikR}}{4πR} u(y) ``` """ mutable struct SingleLayerTrace{T} <: MaxwellOperator3D{T,T} gamma::T end defaultquadstrat(::SingleLayerTrace, ::LagrangeRefSpace, ::LagrangeRefSpace) = DoubleNumWiltonSauterQStrat(10,8,10,8,3,3,3,3) function quaddata(operator::SingleLayerTrace, localtestbasis::LagrangeRefSpace, localtrialbasis::LagrangeRefSpace, testelements, trialelements, qs::DoubleNumWiltonSauterQStrat) tqd = quadpoints(localtestbasis, testelements, (qs.outer_rule_far,)) bqd = quadpoints(localtrialbasis, trialelements, (qs.outer_rule_near,)) #return QuadData(tqd, bqd) return (tpoints=tqd, bpoints=bqd) end # Use numerical quadrature for now # Note: basis integral is over triangle, test over line function quadrule(op::SingleLayerTrace, g::LagrangeRefSpace, f::LagrangeRefSpace, i, τ, j, σ, qd, qs::DoubleNumWiltonSauterQStrat) DoubleQuadRule( qd.tpoints[1,i], qd.bpoints[1,j] ) end integrand(op::SingleLayerTrace, kernel, g, τ, f, σ) = f[1]*g[1]*kernel.green
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1108
""" struct DoubleLayerRotatedMW3D{T,K} <: MaxwellOperator3D{T,K} Bilinear form given by: ```math α ∬_{Γ^2} k(x) ⋅ [n̂(x) × (∇G_γ(x-y) × j(y))] ``` with ``G_γ = e^{-γ|x-y|} / 4π|x-y|`` # Fields - `alpha::T`: Factor in front of bilinear form. - `gamma::K`: imaginary unit times the wavenumber. """ struct DoubleLayerRotatedMW3D{T,K} <: MaxwellOperator3D{T,K} alpha::T gamma::K end # defaultquadstrat(op::DoubleLayerRotatedMW3D, tfs::Space, bfs::Space) = DoubleNumSauterQstrat(6,7,5,5,4,3) defaultquadstrat(op::DoubleLayerRotatedMW3D, tfs::Space, bfs::Space) = DoubleNumQStrat(6,7) LinearAlgebra.cross(::NormalVector, a::MWDoubleLayer3D) = DoubleLayerRotatedMW3D(a.alpha, a.gamma) function (igd::Integrand{<:DoubleLayerRotatedMW3D})(x,y,f,g) nx = normal(x) r = cartesian(x) - cartesian(y) R = norm(r) iR = 1/R γ = gamma(igd.operator) G = exp(-γ*R)/(4π*R) K = -(γ + iR) * G * (iR * r) fvalue = getvalue(f) gvalue = getvalue(g) Kg = cross.(Ref(K), gvalue) nxKg = cross.(Ref(nx), Kg) return _krondot(fvalue, nxKg) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
156
struct SourceField{F} <: Functional field::F end (s::SourceField)(p) = s.f(cartesian(p)) integrand(f::SourceField, tval, fval) = dot(fval, tval.value)
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
702
mutable struct MWSingleLayerPotential3D{K} wavenumber::K end #quaddata(op::MWSingleLayerPotential3D,rs,els) = quaddata(rs,els,(2,)) quaddata(op::MWSingleLayerPotential3D,rs,els) = quadpoints(rs,els,(3,)) quadrule(op::MWSingleLayerPotential3D,refspace,p,y,q,el,qdata) = qdata[1,q] function kernelvals(op::MWSingleLayerPotential3D,y,p) k = op.wavenumber r = y - cartesian(p) R = norm(r) expn = exp(im * k * R) green = expn / (4pi*R) gradgreen = -(im*k + 1/R) * green / R * r KernelValsMaxwell3D(im*k, r, R, green, gradgreen) end function integrand(op::MWSingleLayerPotential3D, krn, y, fp, p) divJ = fp[2] γ = krn.gamma G = krn.green -G*divJ/γ end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2059
import WiltonInts84 mutable struct WiltonSERule{P,Q} <: SingularityExtractionRule outer_quad_points::P regularpart_quadrule::Q end function innerintegrals!(op::MWSingleLayer3DSng, p, g, f, t, s, z, strat::WiltonSERule, dx) γ = op.gamma T = typeof(γ) x = cartesian(p) n = cross(s[1]-s[3],s[2]-s[3]) n /= norm(n) ρ = x - ((x-s[1]) ⋅ n) * n scal, vec = WiltonInts84.wiltonints(s[1], s[2], s[3], x, Val{1}) # \int \frac{1}{4 \pi R} ∫G = (scal[2] - γ*scal[3] + 0.5*γ^2*scal[4]) / (4π) # \int \frac{y}{4 \pi R} ∫Gy = SVector(( (vec[2][1] + scal[2]*ρ[1] - γ*(vec[3][1]+scal[3]*ρ[1]) + 0.5*γ^2*(vec[4][1]+scal[4]*ρ[1]))/(4π), (vec[2][2] + scal[2]*ρ[2] - γ*(vec[3][2]+scal[3]*ρ[2]) + 0.5*γ^2*(vec[4][2]+scal[4]*ρ[2]))/(4π), (vec[2][3] + scal[2]*ρ[3] - γ*(vec[3][3]+scal[3]*ρ[3]) + 0.5*γ^2*(vec[4][3]+scal[4]*ρ[3]))/(4π), )) c₁ = op.α c₂ = op.β α = 1 / volume(t) / volume(s) / 4 for i in 1 : numfunctions(g) a = t[i] g = x - a dg = 2 for j in 1 : numfunctions(f) b = s[j] ∫Gf = SVector(∫Gy[1]-∫G*b[1], ∫Gy[2]-∫G*b[2], ∫Gy[3]-∫G*b[3]) ∫Gdf = 2 * ∫G dg∫Gf = g[1]*∫Gf[1] + g[2]*∫Gf[2] + g[3]*∫Gf[3] z[i,j] += ( α*c₁*dg∫Gf + α*c₂*dg*∫Gdf ) * dx end # next j end # end function innerintegrals!(op::MWDoubleLayer3DSng, p, g, f, t, s, z, strat::WiltonSERule, dx) γ = op.gamma T=typeof(γ) x = cartesian(p) n = cross(s[1]-s[3],s[2]-s[3]) n /= norm(n) ρ = x - ((x-s[1]) ⋅ n) * n scal, vec, grad = WiltonInts84.wiltonints(s[1], s[2], s[3], x, Val{1}) # \int \nabla G_s with G_s = \nabla (1/R + 0.5*γ^2*R) / (4\pi) ∫∇G = T.((-grad[1] - 0.5*γ^2*grad[3]) / (4π)) α = 1 / volume(t) / volume(s) / 4 for i in 1 : numfunctions(g) a = t[i] g = (x - a) for j in 1 : numfunctions(f) b = s[j] z[i,j] += ( α * ( (x-b) × g ) ⋅ ∫∇G ) * dx end # next j end # end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1365
mutable struct PlaneWaveMWTD{T,F,P} <: TDFunctional{T} direction::P polarisation::P speedoflight::T amplitude::F end function planewave(polarisation,direction,amplitude,speedoflight) PlaneWaveMWTD(direction,polarisation,speedoflight,amplitude) end planewave(;signature, polarization, direction, speedoflight) = PlaneWaveMWTD(direction, polarization, speedoflight, signature) scalartype(p::PlaneWaveMWTD) = eltype(p.polarisation) *(a, pw::PlaneWaveMWTD) = PlaneWaveMWTD( pw.direction, a * pw.polarisation, pw.speedoflight, pw.amplitude ) cross(k, pw::PlaneWaveMWTD) = PlaneWaveMWTD( pw.direction, k × pw.polarisation, pw.speedoflight, pw.amplitude ) function (f::PlaneWaveMWTD)(r,t) t = cartesian(t)[1] r = cartesian(r) dr = zero(typeof(t)) for i in 1 : 3 dr += r[i]*f.direction[i] end f.polarisation * f.amplitude(t - dr/f.speedoflight) end function integrate(f::BEAST.PlaneWaveMWTD) planewave( signature = integrate(f.amplitude), direction = f.direction, polarization = f.polarisation, speedoflight = f.speedoflight) end function differentiate(f::BEAST.PlaneWaveMWTD) planewave( signature = derive(f.amplitude), direction = f.direction, polarization = f.polarisation, speedoflight = f.speedoflight) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
9673
mutable struct MWSingleLayerTDIO{T} <: RetardedPotential{T} "speed of light in medium" speed_of_light::T "weight of the weakly singular term" ws_weight::T "weight of the hypersingular term" hs_weight::T "number of temporal differentiations in the weakly singular term" ws_diffs::Int "number of temporal differentiations in the hyper singular term" hs_diffs::Int end function Base.:*(a::Number, op::MWSingleLayerTDIO) @info "scalar product a * op (SL)" MWSingleLayerTDIO( op.speed_of_light, a * op.ws_weight, a * op.hs_weight, op.ws_diffs, op.hs_diffs) end mutable struct MWDoubleLayerTDIO{T} <: RetardedPotential{T} speed_of_light::T weight::T num_diffs::Int end function Base.:*(a::Number, op::MWDoubleLayerTDIO) @info "scalar product a * op (DL)" MWDoubleLayerTDIO( op.speed_of_light, a * op.weight, op.num_diffs) end mutable struct MWDoubleLayerTransposedTDIO{T} <: RetardedPotential{T} speed_of_light::T weight::T num_diffs::Int end function Base.:*(a::Number, op::MWDoubleLayerTransposedTDIO) @info "scalar product a * op (DL)" MWDoubleLayerTransposedTDIO( op.speed_of_light, a * op.weight, op.num_diffs) end MWSingleLayerTDIO(;speedoflight) = MWSingleLayerTDIO(speedoflight,-1/speedoflight,-speedoflight,2,0) MWDoubleLayerTDIO(;speedoflight) = MWDoubleLayerTDIO(speedoflight, one(speedoflight), 0) module TDMaxwell3D import ...BEAST function singlelayer(;speedoflight, numdiffs=0) @assert numdiffs >= 0 numdiffs == 0 && return BEAST.integrate(BEAST.MWSingleLayerTDIO(speedoflight,-1/speedoflight,-speedoflight,2,0)) return BEAST.MWSingleLayerTDIO(speedoflight,-1/speedoflight,-speedoflight,2+numdiffs-1,numdiffs-1) end function doublelayer(;speedoflight, numdiffs=0) @assert numdiffs >= -1 numdiffs == -1 && BEAST.integrate(BEAST.MWDoubleLayerTDIO(speedoflight,1.0,0)) return BEAST.MWDoubleLayerTDIO(speedoflight,1.0,numdiffs) end end # module TDMaxwell3D export TDMaxwell3D defaultquadstrat(::MWSingleLayerTDIO, tfs, bfs) = OuterNumInnerAnalyticQStrat(3) function quaddata(op::MWSingleLayerTDIO, testrefs, trialrefs, timerefs, testels, trialels, timeels, quadstrat::OuterNumInnerAnalyticQStrat) dmax = numfunctions(timerefs)-1 bn = binomial.((0:dmax),(0:dmax)') V = eltype(testels[1].vertices) ws = WiltonInts84.workspace(V) # quadpoints(testrefs, testels, (3,)), bn, ws quadpoints(testrefs, testels, (quadstrat.outer_rule,)), bn, ws end quadrule(op::MWSingleLayerTDIO, testrefs, trialrefs, timerefs, p, testel, q, trialel, r, timeel, qd, ::OuterNumInnerAnalyticQStrat) = WiltonInts84Strat(qd[1][1,p],qd[2],qd[3]) struct TransposedStorage{F} store::F end @inline (f::TransposedStorage)(v,m,n,k) = f.store(v,n,m,k) function assemble!(dl::MWDoubleLayerTDIO, W::SpaceTimeBasis, V::SpaceTimeBasis, store, threading::Type{Threading{:multi}}; quadstrat=defaultquadstrat(dl,W,V)) X, T = spatialbasis(W), temporalbasis(W) Y, U = spatialbasis(V), temporalbasis(V) if CompScienceMeshes.refines(geometry(Y), geometry(X)) @assert !CompScienceMeshes.refines(geometry(X), geometry(Y)) W = Y⊗T V = X⊗U op = MWDoubleLayerTransposedTDIO(dl.speed_of_light, dl.weight, dl.num_diffs) assemble!(op, W, V, store) return end P = Threads.nthreads() Y, S = spatialbasis(W), temporalbasis(W) splits = [round(Int,s) for s in range(0, stop=numfunctions(Y), length=P+1)] @info "Starting assembly with $P threads:" Threads.@threads for i in 1:P lo, hi = splits[i]+1, splits[i+1] lo <= hi || continue Y_p = subset(Y, lo:hi) store2 = (v,m,n,k) -> store(v,lo+m-1,n,k) assemble_chunk!(dl, Y_p ⊗ S, V, store2; quadstrat) end # return assemble_chunk!(dl, W, V, store1) end defaultquadstrat(::MWDoubleLayerTDIO, tfs, bfs) = OuterNumInnerAnalyticQStrat(3) function quaddata(op::MWDoubleLayerTDIO, testrefs, trialrefs, timerefs, testels, trialels, timeels, quadstrat::OuterNumInnerAnalyticQStrat) dmax = numfunctions(timerefs)-1 bn = binomial.((0:dmax),(0:dmax)') V = eltype(testels[1].vertices) ws = WiltonInts84.workspace(V) quadpoints(testrefs, testels, (quadstrat.outer_rule,)), bn, ws end quadrule(op::MWDoubleLayerTDIO, testrefs, trialrefs, timerefs, p, testel, q, trialel, r, timeel, qd, quadstrat::OuterNumInnerAnalyticQStrat) = WiltonInts84Strat(qd[1][1,p],qd[2],qd[3]) defaultquadstrat(::MWDoubleLayerTransposedTDIO, tfs, bfs) = OuterNumInnerAnalyticQStrat(3) function quaddata(op::MWDoubleLayerTransposedTDIO, testrefs, trialrefs, timerefs, testels, trialels, timeels, quadstrat::OuterNumInnerAnalyticQStrat) dmax = numfunctions(timerefs)-1 bn = binomial.((0:dmax),(0:dmax)') V = eltype(testels[1].vertices) ws = WiltonInts84.workspace(V) quadpoints(testrefs, testels, (quadstrat.outer_rule,)), bn, ws end quadrule(op::MWDoubleLayerTransposedTDIO, testrefs, trialrefs, timerefs, p, testel, q, trialel, r, timeel, qd, quadstrat::OuterNumInnerAnalyticQStrat) = WiltonInts84Strat(qd[1][1,p],qd[2],qd[3]) function momintegrals!(z, op::MWDoubleLayerTransposedTDIO, g, f, T, τ, σ, ι, qr::WiltonInts84Strat) op1 = MWDoubleLayerTDIO(op.speed_of_light, op.weight, op.num_diffs) momintegrals!(z, op1, g, f, T, τ, σ, ι, qr::WiltonInts84Strat) w = similar(z) permutedims!(w, z, [2,1,3]) end @inline function tmRoR(d, iG, bns) sgn = isodd(d) ? -1 : 1 r = sgn * iG[d+2] end # build # ``\int (D-R)^d/R (y-b) dy`` from # ``(ξ-b) \int R^k dy`` and # ``\int R^k (y-ξ) dy`` @inline function tmRoRf(d, iG, iGξy, bξ, bns) sgn = isodd(d) ? -1 : 1 iGf = iGξy[d+2] + bξ * iG[d+2] r = sgn * iGf end """ Q = qd(T,dh,::Val{N}) Q[k] is the factor in front resulting from differentiating t^(k-1) dh times. """ @generated function qh(::Type{T},dh,n::Type{Val{N}}) where {N,T} xp = quote end for k in 1:N qk = Symbol(:q,k) d = k-1 xp1 = quote $(qk) = one($T) for v in 0 : dh-1 $(qk) *= ($d-v) end end append!(xp.args, xp1.args) end xp1 = :(()) for k in 1:N qk = Symbol(:q,k) push!(xp1.args, :($qk)) end push!(xp.args, xp1) return xp end function innerintegrals!(zl, op::MWSingleLayerTDIO, p, # test_point, test_time U, V, W, # local_test_space, local_trial_space, local_temporal_space τ, σ, ι, # test_element, trial_element, spherial_shell qr, w) # inner_quadrature_rule, outer_quadrature_weight T = typeof(w) sol = op.speed_of_light #Rmax = sol * tmax dx = w x = cartesian(p) n = cross(σ[1]-σ[3],σ[2]-σ[3]) n /= norm(n) ξ = x - ((x-σ[1]) ⋅ n) * n r = ι[1] R = ι[2] @assert r < R @assert degree(W) <= 3 ∫G, ∫Gξy, = WiltonInts84.wiltonints(σ[1],σ[2],σ[3],x,r,R,Val{2},qr.workspace) αg = 1 / volume(τ) / 2 αf = 1 / volume(σ) / 2 αG = 1 / 4π α = αg * αf * αG * op.ws_weight * dx β = 4 * αg * αf * αG * op.hs_weight * dx ds = op.ws_diffs dh = op.hs_diffs qhs = qh(T,dh,Val{4}) qss = qh(T,ds,Val{4}) bn = qr.binomials #solpowers = collect(sol^p for p ∈ 0:numfunctions(W)-1) sol2 = sol*sol sol3 = sol2*sol sol4 = sol3*sol sol5 = sol4*sol solpowers = (one(sol), sol, sol2, sol3, sol4, sol5) for i in 1 : numfunctions(U) a = τ[i] g = (x-a) for j in 1 : numfunctions(V) b = σ[j]; bξ = ξ-b for k in 1 : numfunctions(W) d = k-1 # ranges from 0 to numfunctions(W)-1 sgn = isodd(d) ? -1 : 1 # hyper singular contribution if d >= dh @assert dh == 0 q = qhs[k] Ih = tmRoR(d-dh, ∫G, bn) # \int (cTmax-R)^(d-dh)/R dy #zl[i,j,k] += β * q * Ih / sol^(d-dh) zl[i,j,k] += β * q * Ih / solpowers[d-dh+1] end # weakly singular contribution if d >= ds q = qss[k] Is = tmRoRf(d-ds, ∫G, ∫Gξy, bξ, bn) # \int (cTmax-R)^(d-ds)/R (y-b) dy #zl[i,j,k] += α * q * (g ⋅ Is) / sol^(d-ds) zl[i,j,k] += α * q * (g ⋅ Is) / solpowers[d-ds+1] end end end end end function innerintegrals!(z, op::MWDoubleLayerTDIO, p, U, V, W, τ, σ, ι, qr, w) T = typeof(w) sol = op.speed_of_light dx = w x = cartesian(p) n = cross(σ[1]-σ[3],σ[2]-σ[3]) n /= norm(n) ξ = x - ((x-σ[1]) ⋅ n) * n r = ι[1] R = ι[2] @assert r < R @assert degree(W) <= 3 #N = max(degree(W), 0) ∫G, ∫Gξy, ∫∇G = WiltonInts84.wiltonints(σ[1],σ[2],σ[3],x,r,R,Val{2},qr.workspace) @assert isapprox(∫∇G[2] , point(0,0,0), atol=1e-8) αg = 1 / volume(τ) / 2 αf = 1 / volume(σ) / 2 αG = 1 / 4 / π α = αG * op.weight * dx # * αg * αf ds = op.num_diffs @inline function tmGRoR(d, iGG) sgn = isodd(d) ? -1 : 1 r = sgn * iGG[d+1] end Ux = U(p) Vx = αf * @SVector[(x-σ[1]), (x-σ[2]), (x-σ[3])] for i in 1 : numfunctions(U) # a = τ[i] # g = αg * (x-τ[i]) g = Ux[i].value for j in 1 : numfunctions(V) # b = σ[j] # f = αf * (x-σ[j]) # f = Vx[j].value f = Vx[j] fxg = f × g for k in 1 : numfunctions(W) d = k-1 sgn = isodd(d) ? -1 : 1 if d >= ds q = one(T) for p in 0 : ds-1 q *= (d-p) end # @assert q == 1 z[i,j,k] += -α * q * ( fxg ⋅ tmGRoR(d-ds, ∫∇G) ) / sol^(d-ds) end end end end end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
976
""" Operator to compute the far field of a current distribution in the time domain. In particular, given the current distribution ``j`` this operator allows for the computation of ```math R = ̂x ⋅ y ffd = n × ∫_Γ j(r', t - R/c} dy ``` where ``̂x`` is the unit vector in the direction of observation. Note that the assembly routing expects the observation directions to be normalised by the caller. """ mutable struct MWFarField3DTD{K} sol::K end function quaddata(op::MWFarField3DTD, trialrefs, timerefs, trialels, timeels) trialqd = quadpoints(trialrefs, trialels, (3,)) trialqd, nothing end function quadrule(op::MWFarField3DTD,trialrefs, timerefs, p, testel, q, trialel, r, timeel, qd) qd[1][1,q], nothing end kernelvals(op::MWFarField3DTD,test,source) = dot(test,cartesian(source))/op.sol function integrand(op::MWFarField3DTD,krn,testels, trialvals, t, T) τ = krn timevals = T(t - τ) testels × (trialvals[1] * timevals) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
353
abstract type FarField end defaultquadstrat(op::FarField, basis) = SingleNumQStrat(3) defaultquadstrat(op::FarField, basis::DirectProductSpace) = defaultquadstrat(op, basis.factors[1]) quaddata(op::FarField,rs,els,qs::SingleNumQStrat) = quadpoints(rs,els,(qs.quad_rule,)) quadrule(op::FarField,refspace,p,y,q,el,qdata,qs::SingleNumQStrat) = qdata[1,q]
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
1494
function octree(charts::Vector{S} where {S <: CompScienceMeshes.Simplex}) ncells = length(charts) T = coordtype(charts[1]) P = eltype(charts[1].vertices) points = zeros(P, ncells) radii = zeros(T, ncells) for (i,ch) in enumerate(charts) points[i] = cartesian(center(ch)) radii[i] = maximum(norm(v-points[i]) for v in ch.vertices) end return Octree(points, radii) end """ grideval(points, coeffs, basis; type=nothing) """ function grideval(points, coeffs, basis; type=nothing) # charts: active charts # ad: assembly data (active_cell_idx, local_shape_idx) -> [dof1, dfo2, ...] # ag: active_cell_idx -> global_cell_idx charts, ad, ag = assemblydata(basis) refs = refspace(basis) V = valuetype(refs, eltype(charts)) T = promote_type(eltype(coeffs), eltype(V)) P = similar_type(V, T) type != nothing && (P = type) values = zeros(P, size(points)) chart_tree = BEAST.octree(charts) for (j,point) in enumerate(points) i = CompScienceMeshes.findchart(charts, chart_tree, point) if i != nothing # @show i chart = charts[i] u = carttobary(chart, point) vals = refs(neighborhood(chart,u)) for r in 1 : numfunctions(refs) for (m,w) in ad[i, r] values[j] += w * coeffs[m] * vals[r][1] end end continue end end return values end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
837
struct CommonFaceOverlappingEdgeQStrat{S} conforming_qstrat::S end function quaddata(a, X, Y, tels, bels, qs::CommonFaceOverlappingEdgeQStrat) return quaddata(a, X, Y, tels, bels, qs.conforming_qstrat) end function quadrule(a, 𝒳, 𝒴, i, τ, j, σ, qd, qs::CommonFaceOverlappingEdgeQStrat) if CompScienceMeshes.overlap(τ, σ) return quadrule(a, 𝒳, 𝒴, i, τ, j, σ, qd, qs.conforming_qstrat) end for (i,λ) in pairs(faces(τ)) for (j,μ) in pairs(faces(σ)) if CompScienceMeshes.overlap(λ, μ) return NonConformingTouchQRule(qs.conforming_qstrat, i, j) end end end # Either positive distance, common face, or common vertex, which can # be handled directly by the parent quadrature strategy return quadrule(a, 𝒳, 𝒴, i, τ, j, σ, qd, qs.conforming_qstrat) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
956
struct DoubleQuadRule{P,Q} outer_quad_points::P inner_quad_points::Q end """ momintegrals!(biop, tshs, bshs, tcell, bcell, interactions, strat) Function for the computation of moment integrals using simple double quadrature. """ function momintegrals!(biop, tshs, bshs, tcell, bcell, z, strat::DoubleQuadRule) igd = Integrand(biop, tshs, bshs, tcell, bcell) womps = strat.outer_quad_points wimps = strat.inner_quad_points for womp in womps tgeo = womp.point tvals = womp.value M = length(tvals) jx = womp.weight for wimp in wimps bgeo = wimp.point bvals = wimp.value N = length(bvals) jy = wimp.weight j = jx * jy z1 = j * igd(tgeo, bgeo, tvals, bvals) for n in 1:N for m in 1:M z[m,n] += z1[m,n] end end end end return z end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
757
function quaddata(operator::IntegralOperator, local_test_basis::RefSpace, local_trial_basis::RefSpace, test_elements, trial_elements, qs::DoubleNumQStrat) test_quad_data = quadpoints(local_test_basis, test_elements, (qs.outer_rule,)) trial_quad_data = quadpoints(local_trial_basis, trial_elements, (qs.inner_rule,)) return test_quad_data, trial_quad_data end function quadrule(operator::IntegralOperator, local_test_basis::RefSpace, local_trial_basis::RefSpace, test_id, test_element, trial_id, trial_element, quad_data, qs::DoubleNumQStrat) test_quad_rules = quad_data[1] trial_quad_rules = quad_data[2] DoubleQuadRule( test_quad_rules[1,test_id], trial_quad_rules[1,trial_id] ) end
BEAST
https://github.com/krcools/BEAST.jl.git
[ "MIT" ]
2.5.0
757efc563022d39e95f751b7e5a29d020a57e049
code
2429
struct DoubleNumSauterQstrat{R,S} outer_rule::R inner_rule::R sauter_schwab_common_tetr::S sauter_schwab_common_face::S sauter_schwab_common_edge::S sauter_schwab_common_vert::S end function quaddata(op::IntegralOperator, test_local_space::RefSpace, trial_local_space::RefSpace, test_charts, trial_charts, qs::DoubleNumSauterQstrat) T = coordtype(test_charts[1]) tqd = quadpoints(test_local_space, test_charts, (qs.outer_rule,)) bqd = quadpoints(trial_local_space, trial_charts, (qs.inner_rule,)) leg = ( convert.(NTuple{2,T},_legendre(qs.sauter_schwab_common_vert,0,1)), convert.(NTuple{2,T},_legendre(qs.sauter_schwab_common_edge,0,1)), convert.(NTuple{2,T},_legendre(qs.sauter_schwab_common_face,0,1)), convert.(NTuple{2,T},_legendre(qs.sauter_schwab_common_tetr,0,1)), ) return (tpoints=tqd, bpoints=bqd, gausslegendre=leg) end function quadrule(op::IntegralOperator, g::RefSpace, f::RefSpace, i, τ::CompScienceMeshes.Simplex{<:Any, 2}, j, σ::CompScienceMeshes.Simplex{<:Any, 2}, qd, qs::DoubleNumSauterQstrat) hits = _numhits(τ, σ) @assert hits <= 3 hits == 3 && return SauterSchwabQuadrature.CommonFace(qd.gausslegendre[3]) hits == 2 && return SauterSchwabQuadrature.CommonEdge(qd.gausslegendre[2]) hits == 1 && return SauterSchwabQuadrature.CommonVertex(qd.gausslegendre[1]) return DoubleQuadRule( qd.tpoints[1,i], qd.bpoints[1,j],) end function quadrule(op::IntegralOperator, g::RefSpace, f::RefSpace, i, τ::CompScienceMeshes.Quadrilateral, j, σ::CompScienceMeshes.Quadrilateral, qd, qs::DoubleNumSauterQstrat) hits = _numhits(τ, σ) @assert hits != 3 @assert hits <= 4 hits == 4 && return SauterSchwabQuadrature.CommonFaceQuad(qd.gausslegendre[3]) hits == 2 && return SauterSchwabQuadrature.CommonEdgeQuad(qd.gausslegendre[2]) hits == 1 && return SauterSchwabQuadrature.CommonVertexQuad(qd.gausslegendre[1]) return DoubleQuadRule( qd.tpoints[1,i], qd.bpoints[1,j],) end function _numhits(τ, σ) T = coordtype(τ) hits = 0 dtol = 1.0e3 * eps(T) dmin2 = floatmax(T) for t in vertices(τ) for s in vertices(σ) d2 = LinearAlgebra.norm_sqr(t-s) d = norm(t-s) dmin2 = min(dmin2, d2) hits += (d < dtol) end end return hits end
BEAST
https://github.com/krcools/BEAST.jl.git