licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
2933
module BenchAssemble using BenchmarkTools using LinearAlgebra using SparseArrays using Bcube suite = BenchmarkGroup() function basic_bilinear() suite = BenchmarkGroup() degree = 1 degquad = 2 * degree + 1 mesh = rectangle_mesh(251, 11; xmax = 1.0, ymax = 0.1) Uspace = TrialFESpace(FunctionSpace(:Lagrange, degree), mesh; size = 2) Vspace = TestFESpace(Uspace) dΩ = Measure(CellDomain(mesh), degquad) a(u, v) = ∫(u ⋅ v)dΩ m(u, v) = ∫(∇(u) ⋅ ∇(v))dΩ #warmup assemble_bilinear(a, Uspace, Vspace) assemble_bilinear(m, Uspace, Vspace) suite["mass matrix"] = @benchmarkable assemble_bilinear($a, $Uspace, $Vspace) suite["stiffness matrix"] = @benchmarkable assemble_bilinear($m, $Uspace, $Vspace) return suite end avg(u) = 0.5 * (side⁺(u) + side⁻(u)) function poisson_dg() suite = BenchmarkGroup() degree = 3 degree_quad = 2 * degree + 1 γ = degree * (degree + 1) n = 4 Lx = 1.0 h = Lx / n uₐ = PhysicalFunction(x -> 3 * x[1] + x[2]^2 + 2 * x[1]^3) f = PhysicalFunction(x -> -2 - 12 * x[1]) g = uₐ # Build mesh meshParam = (nx = n + 1, ny = n + 1, lx = Lx, ly = Lx, xc = 0.0, yc = 0.0) tmp_path = "tmp.msh" gen_rectangle_mesh(tmp_path, :quad; meshParam...) mesh = read_msh(tmp_path) rm(tmp_path) # Choose degree and define function space, trial space and test space fs = FunctionSpace(:Lagrange, degree) U = TrialFESpace(fs, mesh, :discontinuous) V = TestFESpace(U) # Define volume and boundary measures dΩ = Measure(CellDomain(mesh), degree_quad) dΓ = Measure(InteriorFaceDomain(mesh), degree_quad) dΓb = Measure(BoundaryFaceDomain(mesh), degree_quad) nΓ = get_face_normals(dΓ) nΓb = get_face_normals(dΓb) a_Ω(u, v) = ∫(∇(v) ⋅ ∇(u))dΩ l_Ω(v) = ∫(v * f)dΩ function a_Γ(u, v) ∫( -jump(v, nΓ) ⋅ avg(∇(u)) - avg(∇(v)) ⋅ jump(u, nΓ) + γ / h * jump(v, nΓ) ⋅ jump(u, nΓ), )dΓ end fa_Γb(u, ∇u, v, ∇v, n) = -v * (∇u ⋅ n) - (∇v ⋅ n) * u + (γ / h) * v * u a_Γb(u, v) = ∫(fa_Γb ∘ map(side⁻, (u, ∇(u), v, ∇(v), nΓb)))dΓb fl_Γb(v, ∇v, n, g) = -(∇v ⋅ n) * g + (γ / h) * v * g l_Γb(v) = ∫(fl_Γb ∘ map(side⁻, (v, ∇(v), nΓb, g)))dΓb a(u, v) = a_Ω(u, v) + a_Γ(u, v) + a_Γb(u, v) l(v) = l_Ω(v) + l_Γb(v) suite["a_Ω(u, v)"] = @benchmarkable assemble_bilinear($a_Ω, $U, $V) suite["a_Γ(u, v)"] = @benchmarkable assemble_bilinear($a_Γ, $U, $V) suite["a_Γb(u, v)"] = @benchmarkable assemble_bilinear($a_Γb, $U, $V) suite["l_Ω(v)"] = @benchmarkable assemble_linear($l_Ω, $V) suite["l_Γb(v)"] = @benchmarkable assemble_linear($l_Γb, $V) suite["AffineFESystem"] = @benchmarkable Bcube.AffineFESystem($a, $l, $U, $V) return suite end suite = BenchmarkGroup() suite["basic bilinear"] = basic_bilinear() suite["poisson DG"] = poisson_dg() end # module BenchAssemble.suite
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
533
module BenchCovo_Quad using StaticArrays using BenchmarkTools ENV["BenchmarkMode"] = "true" include("./covo.jl") include("./driver_bench_covo.jl") suite = run_covo() end # module module BenchCovo_TriQuad using StaticArrays using BenchmarkTools ENV["BenchmarkMode"] = "true" ENV["MeshConfig"] = "triquad" include("./covo.jl") include("./driver_bench_covo.jl") suite = run_covo() end # module suiteCovo = BenchmarkGroup() suiteCovo["Quad"] = BenchCovo_Quad.suite suiteCovo["TriQuad"] = BenchCovo_TriQuad.suite suiteCovo
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
406
module BenchEntities using StaticArrays using BenchmarkTools using Bcube suite = BenchmarkGroup() tri = Tri3_t() ind = @SVector [10, 20, 30] suite["nnodes"] = @benchmarkable Bcube.f2n_from_c2n($tri, $ind) suite["nodes"] = @benchmarkable Bcube.nodes($tri) suite["nedges"] = @benchmarkable Bcube.nedges($tri) suite["edges2nodes"] = @benchmarkable Bcube.edges2nodes($tri) end # module BenchEntities.suite
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
146
module BenchMesh using BenchmarkTools using Bcube suite = BenchmarkGroup() suite["todo"] = @benchmarkable a = 1 end # module BenchMesh.suite
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
229
using BenchmarkTools SUITE = BenchmarkGroup() for file in readdir(@__DIR__) if startswith(file, "bench_") && endswith(file, ".jl") SUITE[file[(length("bench_") + 1):(end - length(".jl"))]] = include(file) end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
11973
module Covo #hide println("Running covo example...") #hide const dir = string(@__DIR__, "/") using Bcube using LinearAlgebra using StaticArrays using WriteVTK # only for 'VTKCellData' using Profile using StaticArrays using InteractiveUtils using BenchmarkTools using UnPack function compute_residual(_u, V, params, cache) u = get_fe_functions(_u) # alias on measures @unpack dΩ, dΓ, dΓ_perio_x, dΓ_perio_y = params # face normals for each face domain (lazy, no computation at this step) nΓ = get_face_normals(dΓ) nΓ_perio_x = get_face_normals(dΓ_perio_x) nΓ_perio_y = get_face_normals(dΓ_perio_y) # flux residuals from faces for all variables function l(v) ∫(flux_Ω(u, v))dΩ + -∫(flux_Γ(u, v, nΓ))dΓ + -∫(flux_Γ(u, v, nΓ_perio_x))dΓ_perio_x + -∫(flux_Γ(u, v, nΓ_perio_y))dΓ_perio_y end rhs = assemble_linear(l, V) return cache.mass \ rhs end """ flux_Ω(u, v) Compute volume residual using the lazy-operators approach """ flux_Ω(u, v) = _flux_Ω ∘ cellvar(u, v) cellvar(u, v) = (u, map(∇, v)) function _flux_Ω(u, ∇v) ρ, ρu, ρE, ϕ = u ∇λ_ρ, ∇λ_ρu, ∇λ_ρE, ∇λ_ϕ = ∇v vel = ρu ./ ρ ρuu = ρu * transpose(vel) p = pressure(ρ, ρu, ρE, γ) flux_ρ = ρu flux_ρu = ρuu + p * I flux_ρE = (ρE + p) .* vel flux_ϕ = ϕ .* vel return ∇λ_ρ ⋅ flux_ρ + ∇λ_ρu ⊡ flux_ρu + ∇λ_ρE ⋅ flux_ρE + ∇λ_ϕ ⋅ flux_ϕ end """ flux_Γ(u,v,n) Flux at the interface is defined by a composition of two functions: * facevar(u,v,n) defines the input states which are needed for the riemann flux using operator notations * flux_roe(w) defines the Riemann flux (as usual) """ flux_Γ(u, v, n) = flux_roe ∘ (side⁻(u), side⁺(u), jump(v), side⁻(n)) """ flux_roe(w) """ function flux_roe(ui, uj, δv, nij) # destructuring inputs given by `facevar` function nx, ny = nij ρ1, ρu1, ρE1, ϕ1 = ui ρ2, ρu2, ρE2, ϕ2 = uj δλ_ρ1, δλ_ρu1, δλ_ρE1, δλ_ϕ1 = δv ρux1, ρuy1 = ρu1 ρux2, ρuy2 = ρu2 # Closure u1 = ρux1 / ρ1 v1 = ρuy1 / ρ1 u2 = ρux2 / ρ2 v2 = ρuy2 / ρ2 p1 = pressure(ρ1, ρu1, ρE1, γ) p2 = pressure(ρ2, ρu2, ρE2, γ) H2 = (γ / (γ - 1)) * p2 / ρ2 + (u2 * u2 + v2 * v2) / 2.0 H1 = (γ / (γ - 1)) * p1 / ρ1 + (u1 * u1 + v1 * v1) / 2.0 R = √(ρ1 / ρ2) invR1 = 1.0 / (R + 1) uAv = (R * u1 + u2) * invR1 vAv = (R * v1 + v2) * invR1 Hav = (R * H1 + H2) * invR1 cAv = √(abs((γ - 1) * (Hav - (uAv * uAv + vAv * vAv) / 2.0))) ecAv = (uAv * uAv + vAv * vAv) / 2.0 λ1 = nx * uAv + ny * vAv λ3 = λ1 + cAv λ4 = λ1 - cAv d1 = ρ1 - ρ2 d2 = ρ1 * u1 - ρ2 * u2 d3 = ρ1 * v1 - ρ2 * v2 d4 = ρE1 - ρE2 # computation of the centered part of the flux flu11 = nx * ρ2 * u2 + ny * ρ2 * v2 flu21 = nx * p2 + flu11 * u2 flu31 = ny * p2 + flu11 * v2 flu41 = H2 * flu11 # Temp variables rc1 = (γ - 1) / cAv rc2 = (γ - 1) / cAv / cAv uq41 = ecAv / cAv + cAv / (γ - 1) uq42 = nx * uAv + ny * vAv fdc1 = max(λ1, 0.0) * (d1 + rc2 * (-ecAv * d1 + uAv * d2 + vAv * d3 - d4)) fdc2 = max(λ1, 0.0) * ((nx * vAv - ny * uAv) * d1 + ny * d2 - nx * d3) fdc3 = max(λ3, 0.0) * ( (-uq42 * d1 + nx * d2 + ny * d3) / 2.0 + rc1 * (ecAv * d1 - uAv * d2 - vAv * d3 + d4) / 2.0 ) fdc4 = max(λ4, 0.0) * ( (uq42 * d1 - nx * d2 - ny * d3) / 2.0 + rc1 * (ecAv * d1 - uAv * d2 - vAv * d3 + d4) / 2.0 ) duv1 = fdc1 + (fdc3 + fdc4) / cAv duv2 = uAv * fdc1 + ny * fdc2 + (uAv / cAv + nx) * fdc3 + (uAv / cAv - nx) * fdc4 duv3 = vAv * fdc1 - nx * fdc2 + (vAv / cAv + ny) * fdc3 + (vAv / cAv - ny) * fdc4 duv4 = ecAv * fdc1 + (ny * uAv - nx * vAv) * fdc2 + (uq41 + uq42) * fdc3 + (uq41 - uq42) * fdc4 v₁₂ = 0.5 * ((u1 + u2) * nx + (v1 + v2) * ny) fluxϕ = max(0.0, v₁₂) * ϕ1 + min(0.0, v₁₂) * ϕ2 return ( δλ_ρ1 * (flu11 + duv1) + δλ_ρu1 ⋅ (SA[flu21 + duv2, flu31 + duv3]) + δλ_ρE1 * (flu41 + duv4) + δλ_ϕ1 * (fluxϕ) ) end """ Time integration of `f(q, t)` over a timestep `Δt`. """ forward_euler(q, f::Function, t, Δt) = get_dof_values(q) .+ Δt .* f(q, t) """ rk3_ssp(q, f::Function, t, Δt) `f(q, t)` is the function to integrate. """ function rk3_ssp(q, f::Function, t, Δt) stepper(q, t) = forward_euler(q, f, t, Δt) _q0 = get_dof_values(q) _q1 = stepper(q, Δt) set_dof_values!(q, _q1) _q2 = (3 / 4) .* _q0 .+ (1 / 4) .* stepper(q, t + Δt) set_dof_values!(q, _q2) _q1 .= (1 / 3) * _q0 .+ (2 / 3) .* stepper(q, t + Δt / 2) return _q1 end """ pressure(ρ, ρu, ρE, γ) Computes pressure from perfect gaz law """ function pressure(ρ::Number, ρu::AbstractVector, ρE::Number, γ) vel = ρu ./ ρ ρuu = ρu * transpose(vel) p = (γ - 1) * (ρE - tr(ρuu) / 2) return p end """ Init field with a vortex (for the COVO test case) """ function covo!(q, dΩ) # Intermediate vars Cₚ = γ * r / (γ - 1) r²(x) = ((x[1] .- xvc) .^ 2 + (x[2] .- yvc) .^ 2) ./ Rc^2 # Temperature T(x) = T₀ .- β^2 * U₀^2 / (2 * Cₚ) .* exp.(-r²(x)) # Velocity ux(x) = U₀ .- β * U₀ / Rc .* (x[2] .- yvc) .* exp.(-r²(x) ./ 2) uy(x) = V₀ .+ β * U₀ / Rc .* (x[1] .- xvc) .* exp.(-r²(x) ./ 2) # Density ρ(x) = ρ₀ .* (T(x) ./ T₀) .^ (1.0 / (γ - 1)) # momentum ρu(x) = SA[ρ(x) * ux(x), ρ(x) * uy(x)] # Energy ρE(x) = ρ(x) * ((Cₚ / γ) .* T(x) + (ux(x) .^ 2 + uy(x) .^ 2) ./ 2) # Passive scalar ϕ(x) = Rc^2 * r²(x) < 0.01 ? exp(-r²(x) ./ 2) : 0.0 f = map(PhysicalFunction, (ρ, ρu, ρE, ϕ)) projection_l2!(q, f, dΩ) return nothing end """ Tiny struct to ease the VTK output """ mutable struct VtkHandler basename::Any ite::Any VtkHandler(basename) = new(basename, 0) end """ Write solution to vtk Wrapper for `write_vtk` """ function append_vtk(vtk, mesh, vars, t, params) ρ, ρu, ρE, ϕ = vars mesh_degree = 1 vtk_degree = maximum(x -> get_degree(Bcube.get_function_space(get_fespace(x))), vars) vtk_degree = max(1, mesh_degree, vtk_degree) _ρ = var_on_nodes_discontinuous(ρ, mesh, vtk_degree) _ρu = var_on_nodes_discontinuous(ρu, mesh, vtk_degree) _ρE = var_on_nodes_discontinuous(ρE, mesh, vtk_degree) _ϕ = var_on_nodes_discontinuous(ϕ, mesh, vtk_degree) _p = pressure.(_ρ, _ρu, _ρE, γ) dict_vars_dg = Dict( "rho" => (_ρ, VTKPointData()), "rhou" => (_ρu, VTKPointData()), "rhoE" => (_ρE, VTKPointData()), "phi" => (_ϕ, VTKPointData()), "p" => (_p, VTKPointData()), ) Bcube.write_vtk_discontinuous( vtk.basename * "_DG", vtk.ite, t, mesh, dict_vars_dg, vtk_degree; append = vtk.ite > 0, ) # Update counter vtk.ite += 1 end # Settings if get(ENV, "BenchmarkMode", "false") == "false" #hide const cellfactor = 1 const nx = 32 * cellfactor + 1 const ny = 32 * cellfactor + 1 const fspace = :Lagrange const timeScheme = :ForwardEuler else #hide const nx = 128 + 1 #hide const ny = 128 + 1 #hide const fspace = :Lagrange const timeScheme = :ForwardEuler end #hide const nperiod = 1 # number of turn const CFL = 0.1 const degree = 1 # FunctionSpace degree const degquad = 2 * degree + 1 const γ = 1.4 const β = 0.2 # vortex intensity const r = 287.15 # Perfect gaz constant const T₀ = 300 # mean-flow temperature const P₀ = 1e5 # mean-flow pressure const M₀ = 0.5 # mean-flow mach number const ρ₀ = 1.0 # mean-flow density const xvc = 0.0 # x-center of vortex const yvc = 0.0 # y-center of vortex const Rc = 0.005 # Charasteristic vortex radius const c₀ = √(γ * r * T₀) # Sound velocity const U₀ = M₀ * c₀ # mean-flow velocity const V₀ = 0.0 # mean-flow velocity const ϕ₀ = 1.0 const l = 0.05 # half-width of the domain const Δt = CFL * 2 * l / (nx - 1) / ((1 + β) * U₀ + c₀) / (2 * degree + 1) #const Δt = 5.e-7 const nout = 100 # Number of time steps to save const outputpath = "../myout/covo/" const output = joinpath(@__DIR__, outputpath, "covo_deg$degree") const nite = Int(floor(nperiod * 2 * l / (U₀ * Δt))) + 1 function run_covo() println("Starting run_covo...") # Build mesh meshParam = (nx = nx, ny = ny, lx = 2l, ly = 2l, xc = 0.0, yc = 0.0) tmp_path = "tmp.msh" if get(ENV, "BenchmarkMode", "false") == "false" #hide gen_rectangle_mesh(tmp_path, :quad; meshParam...) else #hide if get(ENV, "MeshConfig", "quad") == "triquad" #hide gen_rectangle_mesh_with_tri_and_quad(tmp_path; meshParam...) #hide else #hide gen_rectangle_mesh(tmp_path, :quad; meshParam...) #hide end #hide end #hide mesh = read_msh(tmp_path) rm(tmp_path) # Define variables and test functions fs = FunctionSpace(fspace, degree) U_sca = TrialFESpace(fs, mesh, :discontinuous; size = 1) # DG, scalar U_vec = TrialFESpace(fs, mesh, :discontinuous; size = 2) # DG, vectoriel V_sca = TestFESpace(U_sca) V_vec = TestFESpace(U_vec) U = MultiFESpace(U_sca, U_vec, U_sca, U_sca) V = MultiFESpace(V_sca, V_vec, V_sca, V_sca) u = FEFunction(U) @show Bcube.get_ndofs(U) # Define measures for cell and interior face integrations dΩ = Measure(CellDomain(mesh), degquad) dΓ = Measure(InteriorFaceDomain(mesh), degquad) # Declare periodic boundary conditions and # create associated domains and measures periodicBCType_x = PeriodicBCType(Translation(SA[-2l, 0.0]), ("East",), ("West",)) periodicBCType_y = PeriodicBCType(Translation(SA[0.0, 2l]), ("South",), ("North",)) Γ_perio_x = BoundaryFaceDomain(mesh, periodicBCType_x) Γ_perio_y = BoundaryFaceDomain(mesh, periodicBCType_y) dΓ_perio_x = Measure(Γ_perio_x, degquad) dΓ_perio_y = Measure(Γ_perio_y, degquad) params = (dΩ = dΩ, dΓ = dΓ, dΓ_perio_x = dΓ_perio_x, dΓ_perio_y = dΓ_perio_y) # Init vtk isdir(joinpath(@__DIR__, outputpath)) || mkpath(joinpath(@__DIR__, outputpath)) vtk = VtkHandler(output) # Init solution t = 0.0 covo!(u, dΩ) # cache mass matrices cache = (mass = factorize(Bcube.build_mass_matrix(U, V, dΩ)),) if get(ENV, "BenchmarkMode", "false") == "true" #hide return u, U, V, params, cache end # Write initial solution append_vtk(vtk, mesh, u, t, params) # Time loop for i in 1:nite println("") println("") println("Iteration ", i, " / ", nite) ## Step forward in time rhs(u, t) = compute_residual(u, V, params, cache) if timeScheme == :ForwardEuler unew = forward_euler(u, rhs, time, Δt) elseif timeScheme == :RK3 unew = rk3_ssp(u, rhs, time, Δt) else error("Unknown time scheme: $timeScheme") end set_dof_values!(u, unew) t += Δt # Write solution to file if (i % Int(max(floor(nite / nout), 1)) == 0) println("--> VTK export") append_vtk(vtk, mesh, u, t, params) end end # Summary and benchmark # ndofs total = 20480 _rhs(u, t) = compute_residual(u, V, params, cache) @btime forward_euler($u, $_rhs, $time, $Δt) # 5.639 ms (1574 allocations: 2.08 MiB) # stepper = w -> explicit_step(w, params, cache, Δt) # RK3_SSP(stepper, (u, v), cache) # @btime RK3_SSP($stepper, ($u, $v), $cache) println("ndofs total = ", Bcube.get_ndofs(U)) Profile.init(; n = 10^7) # returns the current settings Profile.clear() Profile.clear_malloc_data() @profile begin for i in 1:100 forward_euler(u, _rhs, time, Δt) end end @show Δt, U₀, U₀ * t @show boundary_names(mesh) return nothing end if get(ENV, "BenchmarkMode", "false") == "false" mkpath(outputpath) run_covo() end end #hide
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1003
function run_covo() suite = BenchmarkGroup() # alias _u, U, V, params, cache = Covo.run_covo() u = Covo.Bcube.get_fe_functions(_u) dΓ = params.dΓ dΩ = params.dΩ nΓ = Covo.Bcube.get_face_normals(dΓ) Δt = Covo.Δt l_vol(v) = Covo.Bcube.∫(Covo.flux_Ω(u, v))dΩ l_Γ(v) = Covo.Bcube.∫(Covo.flux_Γ(u, v, nΓ))dΓ b_vol = zeros(Covo.Bcube.get_ndofs(U)) b_fac = zeros(Covo.Bcube.get_ndofs(U)) # warmup (force precompilation of @generated functions if necessary) Covo.Bcube.assemble_linear!(b_vol, l_vol, V) Covo.Bcube.assemble_linear!(b_fac, l_Γ, V) _rhs(u, t) = Covo.compute_residual(u, V, params, cache) Covo.forward_euler(_u, _rhs, 0.0, Δt) suite["integral_volume"] = @benchmarkable Covo.Bcube.assemble_linear!($b_vol, $l_vol, $V) suite["integral_surface"] = @benchmarkable Covo.Bcube.assemble_linear!($b_fac, $l_Γ, $V) suite["explicit_step"] = @benchmarkable Covo.forward_euler($_u, $_rhs, 0.0, $Δt) return suite end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
2020
# This file was adapted from Transducers.jl and ProximalOperators.jl # which are available under an MIT license (see LICENSE). using ArgParse using PkgBenchmark using Markdown using Pkg Pkg.develop(PackageSpec(; path = pwd())) Pkg.instantiate() function displayresult(result) md = sprint(export_markdown, result) md = replace(md, ":x:" => "❌") md = replace(md, ":white_check_mark:" => "✅") display(Markdown.parse(md)) end function printnewsection(name) println() println() println() printstyled("▃"^displaysize(stdout)[2]; color = :blue) println() printstyled(name; bold = true) println() println() end function parse_commandline() s = ArgParseSettings() @add_arg_table! s begin "--target" help = "the branch/commit/tag to use as target" default = "HEAD" "--baseline" help = "the branch/commit/tag to use as baseline" default = "main" "--retune" help = "force re-tuning (ignore existing tuning data)" action = :store_true end return parse_args(s) end function main() parsed_args = parse_commandline() @show parsed_args function mkconfig(; kwargs...) BenchmarkConfig(; env = Dict("JULIA_NUM_THREADS" => "1"), kwargs...) end target = parsed_args["target"] group_target = benchmarkpkg( dirname(@__DIR__), mkconfig(; id = target); resultfile = joinpath(@__DIR__, "result-$(target).json"), retune = parsed_args["retune"], ) baseline = parsed_args["baseline"] group_baseline = benchmarkpkg( dirname(@__DIR__), mkconfig(; id = baseline); resultfile = joinpath(@__DIR__, "result-$(baseline).json"), ) printnewsection("Target result") displayresult(group_target) printnewsection("Baseline result") displayresult(group_baseline) judgement = judge(group_target, group_baseline) printnewsection("Judgement result") displayresult(judgement) end main()
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1370
push!(LOAD_PATH, "../src/") using Bcube using Documenter using Literate makedocs(; modules = [Bcube], authors = "Ghislain Blanchard, Lokman Bennani and Maxime Bouyges", sitename = "Bcube", clean = true, doctest = false, format = Documenter.HTML(; prettyurls = get(ENV, "CI", "false") == "true", canonical = "https://bcube-project.github.io/Bcube.jl", assets = String[], ), checkdocs = :none, pages = [ "Home" => "index.md", "Manual" => Any[ "manual/conventions.md", "manual/geometry.md", "manual/integration.md", "manual/cellfunction.md", "manual/function_space.md", "manual/operator.md", ], "API Reference" => Any[ "api/mesh/mesh.md", "api/mesh/gmsh_utils.md", "api/mesh/mesh_generator.md", "api/interpolation/shape.md", "api/interpolation/function_space.md", "api/interpolation/fespace.md", "api/mapping/mapping.md", "api/integration/integration.md", # "api/operator/operator.md", "api/dof/dof.md", "api/output/vtk.md", ], "How to... (FAQ)" => "howto/howto.md", ], ) deploydocs(; repo = "github.com/bcube-project/Bcube.jl.git", push_preview = true)
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
109
module HDF5Ext using Bcube using HDF5 include("./common.jl") include("./read.jl") include("./write.jl") end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
2469
const BCUBE_ENTITY_TO_CGNS_ENTITY = Dict( Bcube.Node_t => 2, Bcube.Bar2_t => 3, Bcube.Bar3_t => 4, Bcube.Tri3_t => 5, Bcube.Tri6_t => 6, Bcube.Tri9_t => 25, Bcube.Tri10_t => 26, Bcube.Quad4_t => 7, Bcube.Quad8_t => 8, Bcube.Quad9_t => 9, Bcube.Quad16_t => 27, Bcube.Tetra4_t => 10, Bcube.Tetra10_t => 11, Bcube.Pyra5_t => 12, Bcube.Penta6_t => 14, Bcube.Hexa8_t => 17, Bcube.Hexa27_t => 27, ) const CGNS_ENTITY_TO_BCUBE_ENTITY = Dict(v => k for (k, v) in BCUBE_ENTITY_TO_CGNS_ENTITY) function bcube_entity_to_cgns_entity(::T) where {T <: Bcube.AbstractEntityType} BCUBE_ENTITY_TO_CGNS_ENTITY[T] end cgns_entity_to_bcube_entity(code::Integer) = CGNS_ENTITY_TO_BCUBE_ENTITY[code]() function get_child(parent; name = "", type = "") child_name = findfirst(child -> child_match(child, name, type), parent) return isnothing(child_name) ? nothing : parent[child_name] end function get_children(parent; name = "", type = "") child_names = findall(child -> child_match(child, name, type), parent) return map(child_name -> parent[child_name], child_names) end function child_match(child, name, type) if get_name(child) == name if length(name) > 0 && length(type) > 0 (get_cgns_type(child) == type) && (return true) elseif length(name) > 0 return true end end if get_cgns_type(child) == type if length(name) > 0 && length(type) > 0 (get_name(child) == name) && (return true) elseif length(type) > 0 return true end end return false end get_name(obj) = String(last(split(HDF5.name(obj), '/'))) get_data_type(obj) = attributes(obj)["type"][] get_cgns_type(obj) = haskey(attributes(obj), "label") ? attributes(obj)["label"][] : nothing function get_value(obj) data_type = get_data_type(obj) data = read(obj[" data"]) if data_type == "C1" return String(UInt8.(data)) elseif data_type in ("I4", "I8", "R4", "R8") return data else error("Datatype '$(data_type)' not handled") end end function get_cgns_base(obj) cgnsBases = get_children(obj; type = "CGNSBase_t") if length(cgnsBases) == 0 error("Could not find any CGNSBase_t node in the file") elseif length(cgnsBases) > 1 error("The file contains several CGNSBase_t nodes, only one base is supported") end return first(cgnsBases) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
16113
function Bcube.read_file( ::Bcube.HDF5IoHandler, filepath::String; domainNames = String[], varnames = nothing, topodim = 0, spacedim = 0, verbose = false, kwargs..., ) # Open the file file = h5open(filepath, "r") root = file # Read (unique) CGNS base cgnsBase = get_cgns_base(root) # Read base dimensions (topo and space) dims = get_value(cgnsBase) topodim = topodim > 0 ? topodim : dims[1] zone_space_dim = dims[2] verbose && println("topodim = $topodim, spacedim = $(zone_space_dim)") # Find the list of Zone_t zones = get_children(cgnsBase; type = "Zone_t") if length(zones) == 0 error("Could not find any Zone_t node in the file") elseif length(zones) > 1 error("The file contains several Zone_t nodes, only one zone is supported for now") end zone = first(zones) # Read zone zoneCGNS = read_zone(zone, varnames, topodim, zone_space_dim, spacedim, verbose) # Close the file close(file) # Build Bcube Mesh mesh = cgns_mesh_to_bcube_mesh(zoneCGNS) # Build Bcube MeshCellData & MeshPointData if !isnothing(varnames) data = flow_solutions_to_bcube_data(zoneCGNS.fSols) else data = nothing end # Should we return something when pointData and/or cellData is nothing? Or remove it completely from the returned Tuple? return (; mesh, data) end """ Read a CGNS Zone node. Return a NamedTuple with node coordinates, cell-to-type connectivity (type is a integer), cell-to-node connectivity, boundaries (see `read_zoneBC`), and a dictionnary of flow solutions (see `read_solutions`) -> (; coords, c2t, c2n, bcs, fSols) Note : the `zone_space_dim` is the number of spatial dimension according to the CGNS "Zone" node; whereas `usr_space_dim` is the number of spatial dimensions asked by the user (0 to select automatic detection). """ function read_zone(zone, varnames, topo_dim, zone_space_dim, usr_space_dim, verbose) # Preliminary check zoneType = get_value(get_child(zone; type = "ZoneType_t")) @assert zoneType == "Unstructured" "Only unstructured zone are supported" # Number of elements nvertices, ncells, nbnd = get_value(zone) verbose && println("nvertices = $nvertices, ncells = $ncells") # Read GridCoordinates gridCoordinates = get_child(zone; type = "GridCoordinates_t") coordXNode = get_child(gridCoordinates; name = "CoordinateX") X = get_value(coordXNode) coords = zeros(eltype(X), nvertices, zone_space_dim) coords[:, 1] .= X suffixes = ["X", "Y", "Z"] for (idim, suffix) in enumerate(suffixes[1:zone_space_dim]) node = get_child(gridCoordinates; name = "Coordinate" * suffix) coords[:, idim] .= get_value(node) end # Resize the `coords` array if necessary _space_dim = usr_space_dim > 0 ? usr_space_dim : compute_space_dim(topo_dim, coords) coords = coords[:, 1:_space_dim] # Read all elements elts = map(read_connectivity, get_children(zone; type = "Elements_t")) # Filter "volumic" elements to build the volumic connectivities arrays volumicElts = filter(elt -> is_volumic_entity(first(elt.c2t), topo_dim), elts) c2t = mapreduce(elt -> elt.c2t, vcat, volumicElts) c2n = mapreduce(elt -> elt.c2n, vcat, volumicElts) # Read all BCs and then keep only the ones whose topo dim is equal to the base topo dim minus 1 bcs = read_zoneBC(zone, elts, verbose) if !isnothing(bcs) filter!(bc -> (bc.bcdim == topo_dim - 1) || (bc.bcdim == -1), bcs) end # Read FlowSolutions if !isnothing(varnames) fSols = read_solutions(zone, varnames, verbose) else fSols = nothing end # @show coords # @show c2t # @show c2n # @show bcs # @show fSols return (; coords, c2t, c2n, bcs, fSols) end """ Read an "Elements_t" node and returns a named Tuple of three elements: * `erange`, the content of the `ElementRange` node * `c2t`, the cell -> entity_type connectivity * `c2n`, the cell -> node connectivity, flattened if `reshape = false`, as an array (nelts, nnodes_by_elt) if `reshape = true` * `name`, only for dbg """ function read_connectivity(node, reshape = false) @assert get_cgns_type(node) == "Elements_t" # Build cell to (cgns) type code, _ = get_value(node) erange = get_value(get_child(node; name = "ElementRange")) nelts = erange[2] - erange[1] + 1 c2t = fill(code, nelts) # Build cell to node and reshapce c2n = get_value(get_child(node; name = "ElementConnectivity")) nnodes_by_elt = nnodes(cgns_entity_to_bcube_entity(code)) reshape && (c2n = reshape(c2n, nelts, nnodes_by_elt)) return (; erange, c2t, c2n, name = get_name(node)) end """ Read the "ZoneBC_t" node to build bnd connectivities. See `read_bc` for more information of what is returned. """ function read_zoneBC(zone, elts, verbose) zoneBC = get_child(zone; type = "ZoneBC_t") # Premature exit if no ZoneBC is present isnothing(zoneBC) && (return nothing) # Read each BC bcs = map(bc -> read_bc(bc, elts, verbose), get_children(zoneBC; type = "BC_t")) return bcs end """ Read a BC node. Return a named Tuple (bcname, bcnodes, bcdim) where bcnodes is an array of the nodes belonging to this BC. """ function read_bc(bc, elts, verbose) # BC name familyName = get_child(bc; type = "FamilyName_t") bcname = isnothing(familyName) ? get_name(bc) : get_value(familyName) verbose && println("Reading BC '$bcname'") # BC connectivity bc_type = get_value(get_child(bc; type = "GridLocation_t")) indexRange = get_child(bc; type = "IndexRange_t") pointList = get_child(bc; type = "IndexArray_t") # BC topodim : it's not always possible to determine it, so it's negative by default bcdim = -1 if bc_type in ["CellCenter", "FaceCenter"] if !isnothing(indexRange) verbose && println("GridLocation is $(bc_type) with IndexRange") # This is a bit complex because nothing prevents an IndexRange to span over multiples Elements_t erange = get_value(indexRange) # Allocate the array of node indices corresponding to the BC nelts_bc = erange[2] - erange[1] + 1 T = eltype(first(elts).c2n[1]) bcnodes = T[] sizehint!(bcnodes, nelts_bc * 4) # we assume 4 nodes by elements nelts_found = 0 # Loop over all the Elements_t 'nodes' for elt in elts # verbose && println("Searching for elements in Elements_t '$(elt.name)'") i1, i2 = elt.erange etype = cgns_entity_to_bcube_entity(first(elt.c2t)) nnodes_by_elt = nnodes(etype) if i1 <= erange[1] <= i2 # Compute how many nodes are concerned in this Elements_t, # and the offset in the connectivity nelts_concerned = min(i2, erange[2]) - erange[1] + 1 nnodes_concerned = nelts_concerned * nnodes_by_elt offset = (erange[1] - i1) * nnodes_by_elt push!(bcnodes, elt.c2n[(1 + offset):(offset + nnodes_concerned)]...) nelts_found += nelts_concerned verbose && println("$(nelts_concerned) elts found in '$(elt.name)'") bcdim = Bcube.topodim(etype) # Check if we've found all the elements in this connectivity (erange[2] <= i2) && break end if i1 <= erange[2] <= i2 # Compute how many nodes are concerned in this Elements_t, # and the offset in the connectivity nelts_concerned = erange[2] - max(i1, erange[1]) + 1 nnodes_concerned = nelts_concerned * nnodes_by_elt offset = (max(i1, erange[1]) - i1) * nnodes_by_elt push!(bcnodes, elt.c2n[(1 + offset):(offset + nnodes_concerned)]...) nelts_found += nelts_concerned verbose && println("$(nelts_concerned) elts found in '$(elt.name)'") bcdim = Bcube.topodim(etype) end end @assert nelts_found == nelts_bc "Missing elements for BC" # Once we've found all the nodes, we must remove duplicates # Note : using sort! + unique! is much more efficient than calling "unique" sort!(bcnodes) unique!(bcnodes) elseif !isnothing(pointList) # Elements indices elts_ind = vec(get_value(pointList)) sort!(elts_ind) # Allocate the array of node indices corresponding to the BC nelts_bc = length(elts_ind) T = eltype(first(elts).c2n[1]) bcnodes = T[] sizehint!(bcnodes, nelts_bc * 4) # we assume 4 nodes by elements icurr = 1 for elt in elts verbose && println("Searching for elements in Elements_t '$(elt.name)'") i1, i2 = elt.erange etype = cgns_entity_to_bcube_entity(first(elt.c2t)) nnodes_by_elt = nnodes(etype) (icurr < i1) && continue (icurr > i2) && continue if elts_ind[end] >= i2 iEnd = i2 else iEnd = findfirst(i -> i > i2, view(elts_ind, icurr:nelts_bc)) - 1 end offset = (elts_ind[icurr] - i1) * nnodes_by_elt push!(bcnodes, elt.c2n[(1 + offset):(nnodes_by_elt * (iEnd - i1 + 1))]...) icurr = iEnd + 1 (icurr > nelts_bc) && break # Element-wise version (OK, but very slow) # while i1 <= elts_ind[icurr] <= i2 # offset = (elts_ind[icurr] - i1) * nnodes_by_elt # push!(bcnodes, elt.c2n[(1 + offset):(offset + nnodes_by_elt)]...) # (icurr == nelts_bc) && break # icurr += 1 # end end @assert icurr >= nelts_bc else error("Could not find either the PointRange nor the PointList") end elseif bc_type == "Vertex" if !isnothing(pointList) bcnodes = get_value(pointList) elseif !isnothing(indexRange) erange = get_value(indexRange) bcnodes = collect(erange[1]:erange[2]) else error("Could not find either the PointRange nor the PointList") end # TODO : we could try to guess `bcdim` by search the Elements_t containing # the points of the PointList else error("BC GridLocation '$(bc_type)' not implemented") end return (; bcname, bcnodes, bcdim) end """ Read all the flow solutions in the Zone, filtering data arrays whose name is not in the `varnames` list # TODO : check if all varnames have been found """ function read_solutions(zone, varnames, verbose) # fSols = # map(fs -> read_solution(fs, varnames), get_children(zone; type = "FlowSolution_t")) # n_vertex_fsol = count(fs -> fs.gridLocation == "Vertex", fSols) # n_cell_fsol = count(fs -> fs.gridLocation == "CellCenter", fSols) # if verbose # (n_vertex_fsol > 1) && println( # "WARNING : found more than one Vertex FlowSolution, reading them all...", # ) # (n_cell_fsol > 1) && println( # "WARNING : found more than one CellCenter FlowSolution, reading them all...", # ) # end fSols = Dict( get_name(fs) => read_solution(zone, fs, varnames) for fs in get_children(zone; type = "FlowSolution_t") ) return fSols end """ Read a FlowSolution node. Return a NamedTuple with flow solution name, grid location and array of vectors. """ function read_solution(zone, fs, varnames) # Read GridLocation : we could deal with a missing GridLocation node, by later comparing # the length of the DataArray to the number of cells / nodes of the zone. Let's do this # later. node = get_child(fs; type = "GridLocation_t") if isnothing(node) _nnodes, _ncells, _ = get_zone_dims(zone) dArray = get_child(fs; type = "DataArray_t") err_msg = "Could not determine GridLocation in FlowSolution '$(get_name(fs))'" @assert !isnothing(dArray) err_msg x = get_value(dArray) if length(x) == _nnodes gridLocation = "Vertex" elseif length(x) == _ncells gridLocation = "CellCenter" else error(err_msg) end @warn "Missing GridLocation in FlowSolution '$(get_name(fs))', autoset to '$gridLocation'" else gridLocation = get_value(node) end # Read variables matching asked "varnames" dArrays = get_children(fs; type = "DataArray_t") if varnames != "*" # filter to obtain only the desired variables names filter!(dArray -> get_name(dArray) in varnames, dArrays) end data = Dict(get_name(dArray) => get_value(dArray) for dArray in dArrays) # Flow solution name name = get_name(fs) return (; name, gridLocation, data) end """ Convert CGNS Zone information into a Bcube `Mesh`. """ function cgns_mesh_to_bcube_mesh(zoneCGNS) nodes = [Bcube.Node(zoneCGNS.coords[i, :]) for i in 1:size(zoneCGNS.coords, 1)] # nodes = map(row -> Bcube.Node(row), eachrow(zoneCGNS.coords)) # problem with Node + Slice c2n = Int.(zoneCGNS.c2n) c2t = map(cgns_entity_to_bcube_entity, zoneCGNS.c2t) c2nnodes = map(nnodes, c2t) if isnothing(zoneCGNS.bcs) return Bcube.Mesh(nodes, c2t, Bcube.Connectivity(c2nnodes, c2n)) else bc_names = Dict(i => bc.bcname for (i, bc) in enumerate(zoneCGNS.bcs)) bc_nodes = Dict(i => Int.(bc.bcnodes) for (i, bc) in enumerate(zoneCGNS.bcs)) return Bcube.Mesh(nodes, c2t, Bcube.Connectivity(c2nnodes, c2n); bc_names, bc_nodes) end end """ The input `fSols` is suppose to be a dictionnary FlowSolutionName => (gridlocation, Dict(varname => array)) The output is a dictionnary FlowSolutionName => dictionnary(varname => MeshData) """ function flow_solutions_to_bcube_data(fSols) # length(fSols) == 0 && (return Dict(), Dict()) # pointSols = filter(fs -> fs.gridLocation == "Vertex", fSols) # cellSols = filter(fs -> fs.gridLocation == "CellCenter", fSols) # pointDicts = [fs.data for fs in pointSols] # cellDicts = [fs.data for fs in cellSols] # pointDict = merge(pointDicts) # cellDict = merge(cellDicts) # pointDict = Dict(key => MeshPointData(val) for (key, val) in pointDict) # cellDict = Dict(key => MeshCellData(val) for (key, val) in cellDict) # return pointDict, cellDict return Dict( fname => Dict( varname => t.gridLocation == "Vertex" ? MeshPointData(array) : MeshCellData(array) for (varname, array) in t.data ) for (fname, t) in fSols ) end function compute_space_dim(topodim, coords, tol = 1e-15, verbose = true) spacedim = size(coords, 2) xmin, xmax = extrema(view(coords, :, 1)) lx = xmax - xmin ly = lz = 0.0 if spacedim > 1 ymin, ymax = extrema(view(coords, :, 2)) ly = ymax - ymin end if spacedim > 2 zmin, zmax = extrema(view(coords, :, 3)) lz = zmax - zmin end return Bcube._compute_space_dim(topodim, lx, ly, lz, tol, verbose) end """ Indicate if the Elements node contains "volumic" entities (with respect to the `topo_dim` argument) """ function is_volumic_entity(obj, topo_dim) @assert get_cgns_type(obj) == "Elements_t" code, _ = get_value(obj) return is_volumic_entity(code, topo_dim) end function is_volumic_entity(code::Integer, topo_dim) Bcube.topodim(cgns_entity_to_bcube_entity(code)) == topo_dim end """ Return nnodes, ncells, nbnd """ function get_zone_dims(zone) d = get_value(zone) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
18586
function Bcube.write_file( ::Bcube.HDF5IoHandler, basename::String, mesh::Bcube.AbstractMesh, U_export::Bcube.AbstractFESpace, data = nothing, it::Integer = -1, time::Real = 0.0; collection_append = false, verbose = false, update_mesh = false, skip_iterative_data = false, kwargs..., ) @assert is_fespace_supported(U_export) "Export FESpace not supported yet" mode = collection_append ? "r+" : "w" fcpl = HDF5.FileCreateProperties(; track_order = true) # fcpl = HDF5.FileCreateProperties() h5open(basename, mode; fcpl) do file if collection_append append_to_cgns_file( file, mesh, data, U_export, it, time; verbose, update_mesh, skip_iterative_data, ) else create_cgns_file( file, mesh, data, U_export, it, time; verbose, skip_iterative_data, ) end end end """ Append data to an existing file. """ function append_to_cgns_file( file, mesh, data, U_export, it, time; verbose = false, update_mesh = false, skip_iterative_data, ) @assert !update_mesh "Mesh update not implemented yet" # Read (unique) CGNS base cgnsBase = get_cgns_base(file) # Find the list of Zone_t zones = get_children(cgnsBase; type = "Zone_t") if length(zones) == 0 error("Could not find any Zone_t node in the file") elseif length(zones) > 1 error("The file contains several Zone_t nodes, only one zone is supported for now") end zone = first(zones) # If it >= 0, update/create BaseIterativeData if it >= 0 && !skip_iterative_data append_to_base_iterative_data(cgnsBase, get_name(zone), it, time) else verbose && println("Skipping BaseIterativeData because iteration < 0 or asked to skip it") end # Append solution create_flow_solutions(mesh, zone, data, U_export, it, true; verbose) # Append to ZoneIterativeData if it >= 0 && !skip_iterative_data append_to_zone_iterative_data(zone, it; verbose) end end """ Create the whole file from scratch """ function create_cgns_file( file, mesh, data, U_export, it, time; verbose, skip_iterative_data, ) # @show file.id # @show HDF5.API.h5i_get_file_id(file) # HDF5.API.h5f_set_libver_bounds( # # file.id, # file, # HDF5.API.H5F_LIBVER_V18, # HDF5.API.H5F_LIBVER_LATEST, # ) # HDF5.API.h5f_flush(file.id) # Root element set_cgns_root!(file) # Library version create_cgns_node( file, "CGNSLibraryVersion", "CGNSLibraryVersion_t"; type = "R4", value = Float32[3.2], ) # Base cgnsBase = create_cgns_node( file, "Base", "CGNSBase_t"; value = Int32[Bcube.topodim(mesh), Bcube.spacedim(mesh)], ) # Zone zone = create_cgns_node( cgnsBase, "Zone", "Zone_t"; value = reshape(Int32[nnodes(mesh), ncells(mesh), 0], 1, 3), ) # ZoneType create_cgns_node( zone, "ZoneType", "ZoneType_t"; value = Int8.(Vector{UInt8}("Unstructured")), type = "C1", ) # GridCoordinates gridCoordinates = create_cgns_node(zone, "GridCoordinates", "GridCoordinates_t"; type = "MT") suffixes = ("X", "Y", "Z") for idim in 1:Bcube.spacedim(mesh) create_cgns_node( gridCoordinates, "Coordinate$(suffixes[idim])", "DataArray_t"; type = "R8", value = [get_coords(node, idim) for node in get_nodes(mesh)], ) end # Write elements create_cgns_elements(mesh, zone; write_bnd_faces = false, verbose) # Write BCs create_cgns_bcs(mesh, zone; verbose) # Write solution if !isnothing(data) create_flow_solutions(mesh, zone, data, U_export, it, false; verbose) end # Base and zone iterative data if it >= 0 && !skip_iterative_data verbose && println("Creating BaseIterativeData and ZoneIterativeData") create_cgns_base_iterative_data(cgnsBase, get_name(zone), it, time) create_cgns_zone_iterative_data(zone, it; verbose) end end """ Special stuff for the root node Adapted from Maia : https://github.com/onera/Maia/blob/3a5030aa3b0696cdbae0c9dd08ac641842be33a3/maia/io/hdf/_hdf_cgns.py#L95 """ function set_cgns_root!(root) # fcpl = HDF5.get_create_properties(root) # HDF5.set_track_order!(fcpl, true) add_cgns_string_attr!(root, "label", "Root Node of HDF5 File", 33) add_cgns_string_attr!(root, "name", "HDF5 MotherNode", 33) add_cgns_string_attr!(root, "type", "MT", 3) v = HDF5.libversion version = "HDF5 Version $(v.major).$(v.minor).$(v.patch)" root[" hdf5version"] = str2int8_with_fixed_length(version, 33) # @show HDF5.API.H5T_NATIVE_DOUBLE # @show HDF5.API.H5T_NATIVE_FLOAT # @show HDF5.API.H5T_IEEE_F32BE # @show HDF5.API.H5T_IEEE_F32LE # @show HDF5.API.H5T_IEEE_F64BE # @show HDF5.API.H5T_IEEE_F64LE if HDF5.API.H5T_NATIVE_FLOAT == HDF5.API.H5T_IEEE_F32BE format = "IEEE_BIG_32" elseif HDF5.API.H5T_NATIVE_FLOAT == HDF5.API.H5T_IEEE_F32LE format = "IEEE_LITTLE_32" elseif HDF5.API.H5T_NATIVE_FLOAT == HDF5.API.H5T_IEEE_F64BE format = "IEEE_BIG_64" elseif HDF5.API.H5T_NATIVE_FLOAT == HDF5.API.H5T_IEEE_F64LE format = "IEEE_LITTLE_64" else @warn "Could determine float type, assuming IEEE_LITTLE_32" format = "IEEE_LITTLE_32" end root[" format"] = str2int8(format) end function create_cgns_elements(mesh, zone; write_bnd_faces = false, verbose = false) @assert !write_bnd_faces "not implemented yet" verbose && println("Writing elements") # Found the different type of cells in the mesh celltypes = union_types(eltype(Bcube.entities(mesh, :cell))) # Count number of elements for each type typeCount = Dict(ct => 0 for ct in celltypes) foreach(ct -> typeCount[typeof(ct)] += 1, Bcube.cells(mesh)) # Allocate connectivity array for each type conn = Dict(ct => zeros(typeCount[ct], nnodes(ct)) for ct in celltypes) offset = Dict(ct => 1 for ct in celltypes) # Fill it for cInfo in Bcube.DomainIterator(CellDomain(mesh)) ct = typeof(Bcube.celltype(cInfo)) i = offset[ct] conn[ct][i, :] .= Bcube.get_nodes_index(cInfo) offset[ct] += 1 end # Create Elements nodes i = 0 for ct in celltypes eltsName = string(ct) eltsName = replace(eltsName, "Bcube." => "") eltsName = eltsName[1:(end - 2)] verbose && println("Writing $eltsName") elts = create_cgns_node( zone, eltsName, "Elements_t"; value = Int32[BCUBE_ENTITY_TO_CGNS_ENTITY[ct], 0], ) create_cgns_node( elts, "ElementRange", "IndexRange_t"; value = Int32[i + 1, i + typeCount[ct]], ) create_cgns_node( elts, "ElementConnectivity", "DataArray_t"; value = Int32.(vec(transpose(conn[ct]))), ) i += typeCount[ct] end end """ Create the ZoneBC node and the associated BC nodes. For now, BCs are defined by a list of nodes. We could implement a version where BCs are defined by a list of faces (this necessitates faces nodes in the Elements_t part). """ function create_cgns_bcs(mesh, zone; verbose = false) zoneBC = create_cgns_node(zone, "ZoneBC", "ZoneBC_t"; type = "MT") for (tag, name) in boundary_names(mesh) # for (name, nodes) in zip(boundary_names(mesh), Bcube.boundary_nodes(mesh)) bcnodes = Bcube.boundary_nodes(mesh, tag) bc = create_cgns_node(zoneBC, name, "BC_t"; type = "C1", value = str2int8("BCWall")) create_grid_location(bc, "Vertex") create_cgns_node( bc, "PointList", "IndexArray_t"; type = "I4", value = Int32.(transpose(bcnodes)), ) end end """ `append` indicates if the FlowSolution(s) may already exist (and hence completed) or not. """ function create_flow_solutions(mesh, zone, data, U_export, it, append; verbose = false) if valtype(data) <: Dict verbose && println("Named FlowSolution(s) detected") for (fname, _data) in data # Then, we create a flowsolution create_flow_solutions(mesh, zone, _data, U_export, fname, it, append; verbose) end else create_flow_solutions(mesh, zone, data, U_export, "", it, append; verbose) end end """ This function is a trick to refactor some code """ function create_flow_solutions( mesh, zone, data, U_export, fname, it, append; verbose = false, ) cellCenter = filter(((name, var),) -> var isa Bcube.MeshData{Bcube.CellData}, data) _fname = isempty(fname) ? "FlowSolutionCell" : fname (it >= 0) && (_fname *= iteration_to_string(it)) create_flow_solution( zone, cellCenter, _fname, false, Base.Fix2(var_on_centers, mesh), append; verbose, ) nodeCenter = filter(((name, var),) -> !(var isa Bcube.MeshData{Bcube.CellData}), data) _fname = isempty(fname) ? "FlowSolutionVertex" : fname (it >= 0) && (_fname *= iteration_to_string(it)) create_flow_solution( zone, nodeCenter, _fname, true, Base.Fix2(var_on_vertices, mesh), append; verbose, ) end """ WARNING : vector variables are not supported for now !! """ function create_flow_solution(zone, data, fname, isVertex, projection, append; verbose) isempty(data) && return verbose && println("Writing FlowSolution '$fname'") # Try to get an existing node. If it exists and append=true, # an error is raised. # Otherwise, a new node is created. fnode = get_child(zone; name = fname, type = "FlowSolution_t") if !isnothing(fnode) && !append error("The node '$fname' already exists") else fnode = create_cgns_node(zone, fname, "FlowSolution_t"; type = "MT") gdValue = isVertex ? "Vertex" : "CellCenter" create_grid_location(fnode, gdValue) end for (name, var) in data y = projection(var) if ndims(y) == 1 # Scalar field create_cgns_node(fnode, name, "DataArray_t"; type = "R8", value = y) elseif ndims(y) == 2 && size(y, 2) <= 3 # Vector field for (col, suffix) in zip(eachcol(y), ("X", "Y", "Z")) create_cgns_node( fnode, name * suffix, "DataArray_t"; type = "R8", value = col, ) end else error("wrong dimension for y") end end return fnode end function create_cgns_node(parent, name, label; type = "I4", value = nothing) child = create_group(parent, name; track_order = true) set_cgns_attr!(child, name, label, type) if !isnothing(value) append_cgns_data(child, value) end return child end function create_grid_location(parent, value) return create_cgns_node( parent, "GridLocation", "GridLocation_t"; type = "C1", value = str2int8(value), ) end function is_fespace_supported(U) Bcube.is_discontinuous(U) && return false fs = Bcube.get_function_space(U) if Bcube.get_type(fs) <: Bcube.Lagrange && Bcube.get_degree(fs) <= 1 return true elseif Bcube.get_type(fs) <: Bcube.Taylor && Bcube.get_degree(fs) <= 0 return true end return false end function create_cgns_base_iterative_data(parent, zonename, it, time) bid = create_cgns_node( parent, "BaseIterativeData", "BaseIterativeData_t"; type = "I4", value = Int32(1), ) create_cgns_node(bid, "NumberOfZones", "DataArray_t"; type = "I4", value = Int32(1)) create_cgns_node(bid, "TimeValues", "DataArray_t"; type = "R8", value = time) create_cgns_node(bid, "IterationValues", "DataArray_t"; type = "I4", value = Int32(it)) str = str2int8_with_fixed_length(zonename, 32) create_cgns_node( bid, "ZonePointers", "DataArray_t"; type = "C1", value = reshape(str, 32, 1, 1), ) return bid end """ # Warnings * CGNS also allows for a "TimeDurations" node instead of "IterationValues" * a unique zone is assumed """ function append_to_base_iterative_data(cgnsBase, zonename, it, time) bid = get_child(cgnsBase; type = "BaseIterativeData_t") # Check if node exists, if not -> create it if isnothing(bid) verbose && println("BaseIterativeData not found, creating it") return create_cgns_base_iterative_data(cgnsBase, zonename, it, time) end # First, we check if the given iteration is not already known from the # BaseIterativeData. If it is the case, we don't do anything. # Note that in the maia example, the node IterationValues does not exist, # hence we skip this part if the node is not found. iterationValues = get_child(bid; name = "IterationValues") if !isnothing(iterationValues) iterations = get_value(iterationValues) (it ∈ iterations) && return # Append iteration to the list of iteration values push!(iterations, it) update_cgns_data(iterationValues, iterations) # Increase the number of iterations stored in this BaseIterativeData update_cgns_data(bid, length(iterations)) end numberOfZones = get_child(bid; name = "NumberOfZones") data = get_value(numberOfZones) nsteps = length(data) push!(data, 1) update_cgns_data(numberOfZones, data) timeValues = get_child(bid; name = "TimeValues") data = push!(get_value(timeValues), time) update_cgns_data(timeValues, data) zonePointers = get_child(bid; name = "ZonePointers") data = read(zonePointers[" data"]) new_data = zeros(eltype(data), (32, 1, nsteps + 1)) str = str2int8_with_fixed_length(zonename, 32) for i in 1:nsteps new_data[:, 1, i] .= data[:, 1, i] end new_data[:, 1, end] .= str update_cgns_data(zonePointers, new_data) end """ Call to this function must be performed AFTER the FlowSolution creation """ function create_cgns_zone_iterative_data(zone, it; verbose) # Find the FlowSolution name that matches the iteration fsname = "NotFound" for fs in get_children(zone; type = "FlowSolution_t") _fsname = get_name(fs) if endswith(_fsname, iteration_to_string(it)) fsname = _fsname break end end verbose && println("Attaching iteration $it to FlowSolution '$fsname'") # Create node zid = create_cgns_node(zone, "ZoneIterativeData", "ZoneIterativeData_t"; type = "MT") str = str2int8_with_fixed_length(fsname, 32) create_cgns_node( zid, "FlowSolutionPointers", "DataArray_t"; type = "C1", value = reshape(str, 32, 1), ) return zid end """ Call to this function must be performed AFTER the FlowSolution creation # Warning CGNS does seem to allow multiple FlowSolution nodes for one time step in a Zone. """ function append_to_zone_iterative_data(zone, it; verbose) # Find the FlowSolution name that matches the iteration fsname = "NotFound" for fs in get_children(zone; type = "FlowSolution_t") _fsname = get_name(fs) if endswith(_fsname, iteration_to_string(it)) fsname = _fsname break end end verbose && println("Attaching iteration $it to FlowSolution '$fsname'") # Get ZoneIterativeData node (or create it) zid = get_child(zone; type = "ZoneIterativeData_t") isnothing(zid) && (return create_cgns_zone_iterative_data(zone, it)) # Append to FlowSolutionPointers fsPointers = get_child(zid; name = "FlowSolutionPointers") data = read(fsPointers[" data"]) n = size(data, 2) new_data = zeros(eltype(data), (32, n + 1)) str = str2int8_with_fixed_length(fsname, 32) for i in 1:n new_data[:, i] .= data[:, i] end new_data[:, end] .= str update_cgns_data(fsPointers, new_data) end function append_cgns_data(obj, data) _data = data isa AbstractArray ? data : [data] dset = create_dataset(obj, " data", eltype(_data), size(_data)) write(dset, _data) end function update_cgns_data(obj, data) delete_object(obj, " data") append_cgns_data(obj, data) end function set_cgns_attr!(obj, name, label, type) attributes(obj)["flags"] = Int32[1] add_cgns_string_attr!(obj, "label", label, 33) add_cgns_string_attr!(obj, "name", name, 33) add_cgns_string_attr!(obj, "type", type, 3) end """ It is not trivial to match the exact datatype for attributes. https://discourse.julialang.org/t/hdf5-jl-variable-length-string/98808/11 TODO : now that I know that even with the correct datatype the file is not correct according to cgnscheck, once I've solved the cgnscheck problem I should check that the present function is still necessary. """ function add_cgns_string_attr!(obj, name, value, length = sizeof(value)) dtype = build_cgns_string_dtype(length) attr = create_attribute(obj, name, dtype, HDF5.dataspace(value)) try write_attribute(attr, dtype, value) catch exc delete_attribute(obj, name) rethrow(exc) finally close(attr) close(dtype) end end function build_cgns_string_dtype(length) type_id = HDF5.API.h5t_copy(HDF5.hdf5_type_id(String)) HDF5.API.h5t_set_size(type_id, length) HDF5.API.h5t_set_cset(type_id, HDF5.API.H5T_CSET_ASCII) dtype = HDF5.Datatype(type_id) # @show d return dtype end str2int8(str) = return Int8.(Vector{UInt8}(str)) function str2int8_with_fixed_length(str, n) buffer = zeros(UInt8, n) buffer[1:length(str)] .= Vector{UInt8}(str) return Int8.(buffer) end union_types(x::Union) = (x.a, union_types(x.b)...) union_types(x::Type) = (x,) iteration_to_string(it) = "#$it"
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
104
module JLD2Ext using Bcube using JLD2 include("common.jl") include("read.jl") include("write.jl") end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
3370
""" Wrapper for the JLD2.Group struct to keep track of the attributes associated to a Group without needing the parent. """ struct Node{T} node::T name::String attrs::Dict{Symbol, String} end get_wrapped_node(n::Node) = n.node get_attribute(n::Node, name::Symbol) = haskey(n.attrs, name) ? n.attrs[name] : nothing get_cgns_type(n::Node) = get_attribute(n, :label) get_data_type(n::Node) = get_attribute(n, :type) get_cgns_name(n::Node) = get_attribute(n, :name) get_name(n::Node) = n.name function Node(root::JLD2.JLDFile) attrs = parse_attributes(root, "") return Node{typeof(root)}(root, "root", attrs) end function Node(parent, node_name::String) attrs = parse_attributes(parent, node_name) node = parent[node_name] return Node{typeof(node)}(parent[node_name], node_name, attrs) end Node(parent::Node, node_name::String) = Node(get_wrapped_node(parent), node_name) function parse_attributes(parent, node_name) raw_attrs = JLD2.load_attributes(parent, node_name) attrs = Dict{Symbol, String}() attrs_keys = (:name, :label, :type) for (key, val) in raw_attrs if key in attrs_keys attrs[key] = first(split(val, "\0")) end end return attrs end """ We could make this function type-stable by converting the "type" attribute to a type-parameter of `Node` """ function get_value(n::Node) data_type = get_data_type(n) data = get_wrapped_node(n)[" data"] if data_type == "C1" return String(UInt8.(data)) elseif data_type in ("I4", "I8", "R4", "R8") return data else error("Datatype '$(data_type)' not handled") end end function get_child(parent; name = "", type = "") for child_name in keys(get_wrapped_node(parent)) child = Node(parent, child_name) child_match(child, name, type) && (return child) end end function get_children(parent; name = "", type = "") filtered = filter( child_name -> child_match(Node(parent, child_name), name, type), keys(get_wrapped_node(parent)), ) map(child_name -> Node(parent, child_name), filtered) end function child_match(child, name, type) if get_name(child) == name if length(name) > 0 && length(type) > 0 (get_cgns_type(child) == type) && (return true) elseif length(name) > 0 return true end end if get_cgns_type(child) == type if length(name) > 0 && length(type) > 0 (get_name(child) == name) && (return true) elseif length(type) > 0 return true end end return false end const BCUBE_ENTITY_TO_CGNS_ENTITY = Dict( Bcube.Node_t => 2, Bcube.Bar2_t => 3, Bcube.Bar3_t => 4, Bcube.Tri3_t => 5, Bcube.Tri6_t => 6, Bcube.Tri9_t => 25, Bcube.Tri10_t => 26, Bcube.Quad4_t => 7, Bcube.Quad8_t => 8, Bcube.Quad9_t => 9, Bcube.Quad16_t => 27, Bcube.Tetra4_t => 10, Bcube.Tetra10_t => 11, Bcube.Pyra5_t => 12, Bcube.Penta6_t => 14, Bcube.Hexa8_t => 17, Bcube.Hexa27_t => 27, ) const CGNS_ENTITY_TO_BCUBE_ENTITY = Dict(v => k for (k, v) in BCUBE_ENTITY_TO_CGNS_ENTITY) function bcube_entity_to_cgns_entity(::T) where {T <: Bcube.AbstractEntityType} BCUBE_ENTITY_TO_CGNS_ENTITY[T] end cgns_entity_to_bcube_entity(code::Integer) = CGNS_ENTITY_TO_BCUBE_ENTITY[code]()
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
14709
function Bcube.read_file( ::Bcube.JLD2IoHandler, filepath::String; domainNames = String[], varnames = nothing, topodim = 0, spacedim = 0, verbose = false, ) # Preliminary check @assert length(domainNames) == 0 "domainNames arg is not supported for now, leave it empty" # Open the file f = jldopen(filepath, "r") root = Node(f) # Find the list of CGNSBase_t cgnsBases = get_children(root; type = "CGNSBase_t") if length(cgnsBases) == 0 error("Could not find any CGNSBase_t node in the file") elseif length(cgnsBases) > 1 error("The file contains several CGNSBase_t nodes, only one base is supported") end cgnsBase = first(cgnsBases) # Read base dimensions (topo and space) dims = get_value(cgnsBase) topodim = topodim > 0 ? topodim : dims[1] spacedim = spacedim > 0 ? spacedim : dims[2] verbose && println("topodim = $topodim, spacedim = $spacedim") # Find the list of Zone_t zones = get_children(cgnsBase; type = "Zone_t") if length(zones) == 0 error("Could not find any Zone_t node in the file") elseif length(zones) > 1 error("The file contains several Zone_t nodes, only one zone is supported for now") end zone = first(zones) # Read zone zoneCGNS = read_zone(zone, varnames, topodim, spacedim, verbose) # Close the file close(f) # Build Bcube Mesh mesh = cgns_mesh_to_bcube_mesh(zoneCGNS) # Build Bcube MeshCellData & MeshPointData if !isnothing(varnames) data = flow_solutions_to_bcube_data(zoneCGNS.fSols) else data = nothing end # Should we return something when pointData and/or cellData is nothing? Or remove it completely from the returned Tuple? return (; mesh, data) end """ Convert CGNS Zone information into a Bcube `Mesh`. """ function cgns_mesh_to_bcube_mesh(zoneCGNS) nodes = [Bcube.Node(zoneCGNS.coords[i, :]) for i in 1:size(zoneCGNS.coords, 1)] # nodes = map(row -> Bcube.Node(row), eachrow(zoneCGNS.coords)) # problem with Node + Slice c2n = Int.(zoneCGNS.c2n) c2t = map(cgns_entity_to_bcube_entity, zoneCGNS.c2t) c2nnodes = map(nnodes, c2t) bc_names = Dict(i => bc.bcname for (i, bc) in enumerate(zoneCGNS.bcs)) bc_nodes = Dict(i => Int.(bc.bcnodes) for (i, bc) in enumerate(zoneCGNS.bcs)) return Bcube.Mesh(nodes, c2t, Bcube.Connectivity(c2nnodes, c2n); bc_names, bc_nodes) end """ The input `fSols` is suppose to be a dictionnary FlowSolutionName => (gridlocation, Dict(varname => array)) The output is a dictionnary FlowSolutionName => dictionnary(varname => MeshData) """ function flow_solutions_to_bcube_data(fSols) # length(fSols) == 0 && (return Dict(), Dict()) # pointSols = filter(fs -> fs.gridLocation == "Vertex", fSols) # cellSols = filter(fs -> fs.gridLocation == "CellCenter", fSols) # pointDicts = [fs.data for fs in pointSols] # cellDicts = [fs.data for fs in cellSols] # pointDict = merge(pointDicts) # cellDict = merge(cellDicts) # pointDict = Dict(key => MeshPointData(val) for (key, val) in pointDict) # cellDict = Dict(key => MeshCellData(val) for (key, val) in cellDict) # return pointDict, cellDict return Dict( fname => Dict( varname => t.gridLocation == "Vertex" ? MeshPointData(array) : MeshCellData(array) for (varname, array) in t.data ) for (fname, t) in fSols ) end """ Read a CGNS Zone node. Return a NamedTuple with node coordinates, cell-to-type connectivity (type is a integer), cell-to-node connectivity, boundaries (see `read_zoneBC`), and a dictionnary of flow solutions (see `read_solutions`) -> (; coords, c2t, c2n, bcs, fSols) """ function read_zone(zone, varnames, topo_dim, space_dim, verbose) # Preliminary check zoneType = get_value(get_child(zone; type = "ZoneType_t")) @assert zoneType == "Unstructured" "Only unstructured zone are supported" # Number of elements nvertices, ncells, nbnd = get_value(zone) verbose && println("nvertices = $nvertices, ncells = $ncells") # Read GridCoordinates gridCoordinates = get_child(zone; type = "GridCoordinates_t") coordXNode = get_child(gridCoordinates; name = "CoordinateX") X = get_value(coordXNode) coords = zeros(eltype(X), nvertices, space_dim) coords[:, 1] .= X suffixes = ["X", "Y", "Z"] for (idim, suffix) in enumerate(suffixes[1:space_dim]) node = get_child(gridCoordinates; name = "Coordinate" * suffix) coords[:, idim] .= get_value(node) end # Read all elements elts = map(read_connectivity, get_children(zone; type = "Elements_t")) # Filter "volumic" elements to build the volumic connectivities arrays volumicElts = filter(elt -> is_volumic_entity(first(elt.c2t), topo_dim), elts) c2t = mapreduce(elt -> elt.c2t, vcat, volumicElts) c2n = mapreduce(elt -> elt.c2n, vcat, volumicElts) # Read all BCs and then keep only the ones whose topo dim is equal to the base topo dim minus 1 bcs = read_zoneBC(zone, elts, verbose) filter!(bc -> (bc.bcdim == topo_dim - 1) || (bc.bcdim == -1), bcs) # Read FlowSolutions if !isnothing(varnames) fSols = read_solutions(zone, varnames, verbose) else fSols = nothing end # @show coords # @show c2t # @show c2n # @show bcs # @show fSols return (; coords, c2t, c2n, bcs, fSols) end """ Read the "ZoneBC_t" node to build bnd connectivities. See `read_bc` for more information of what is returned. """ function read_zoneBC(zone, elts, verbose) zoneBC = get_child(zone; type = "ZoneBC_t") bcs = map(bc -> read_bc(bc, elts, verbose), get_children(zoneBC; type = "BC_t")) return bcs end """ Read a BC node. Return a named Tuple (bcname, bcnodes, bcdim) where bcnodes is an array of the nodes belonging to this BC. """ function read_bc(bc, elts, verbose) # BC name familyName = get_child(bc; type = "FamilyName_t") bcname = isnothing(familyName) ? get_name(bc) : get_value(familyName) verbose && println("Reading BC '$bcname'") # BC connectivity bc_type = get_value(get_child(bc; type = "GridLocation_t")) indexRange = get_child(bc; type = "IndexRange_t") pointList = get_child(bc; type = "IndexArray_t") # BC topodim : it's not always possible to determine it, so it's negative by default bcdim = -1 if bc_type in ["CellCenter", "FaceCenter"] if !isnothing(indexRange) verbose && println("GridLocation is $(bc_type) with IndexRange") # This is a bit complex because nothing prevents an IndexRange to span over multiples Elements_t erange = get_value(indexRange) # Allocate the array of node indices corresponding to the BC nelts_bc = erange[2] - erange[1] + 1 T = eltype(first(elts).c2n[1]) bcnodes = T[] sizehint!(bcnodes, nelts_bc * 4) # we assume 4 nodes by elements nelts_found = 0 # Loop over all the Elements_t 'nodes' for elt in elts # verbose && println("Searching for elements in Elements_t '$(elt.name)'") i1, i2 = elt.erange etype = cgns_entity_to_bcube_entity(first(elt.c2t)) nnodes_by_elt = nnodes(etype) if i1 <= erange[1] <= i2 # Compute how many nodes are concerned in this Elements_t, # and the offset in the connectivity nelts_concerned = min(i2, erange[2]) - erange[1] + 1 nnodes_concerned = nelts_concerned * nnodes_by_elt offset = (erange[1] - i1) * nnodes_by_elt push!(bcnodes, elt.c2n[(1 + offset):(offset + nnodes_concerned)]...) nelts_found += nelts_concerned verbose && println("$(nelts_concerned) elts found in '$(elt.name)'") bcdim = Bcube.topodim(etype) # Check if we've found all the elements in this connectivity (erange[2] <= i2) && break end if i1 <= erange[2] <= i2 # Compute how many nodes are concerned in this Elements_t, # and the offset in the connectivity nelts_concerned = erange[2] - max(i1, erange[1]) + 1 nnodes_concerned = nelts_concerned * nnodes_by_elt offset = (max(i1, erange[1]) - i1) * nnodes_by_elt push!(bcnodes, elt.c2n[(1 + offset):(offset + nnodes_concerned)]...) nelts_found += nelts_concerned verbose && println("$(nelts_concerned) elts found in '$(elt.name)'") bcdim = Bcube.topodim(etype) end end @assert nelts_found == nelts_bc "Missing elements for BC" # Once we've found all the nodes, we must remove duplicates # Note : using sort! + unique! is much more efficient than calling "unique" sort!(bcnodes) unique!(bcnodes) elseif !isnothing(pointList) # Elements indices elts_ind = vec(get_value(pointList)) sort!(elts_ind) # Allocate the array of node indices corresponding to the BC nelts_bc = length(elts_ind) T = eltype(first(elts).c2n[1]) bcnodes = T[] sizehint!(bcnodes, nelts_bc * 4) # we assume 4 nodes by elements icurr = 1 for elt in elts verbose && println("Searching for elements in Elements_t '$(elt.name)'") i1, i2 = elt.erange etype = cgns_entity_to_bcube_entity(first(elt.c2t)) nnodes_by_elt = nnodes(etype) (icurr < i1) && continue (icurr > i2) && continue if elts_ind[end] >= i2 iEnd = i2 else iEnd = findfirst(i -> i > i2, view(elts_ind, icurr:nelts_bc)) - 1 end offset = (elts_ind[icurr] - i1) * nnodes_by_elt push!(bcnodes, elt.c2n[(1 + offset):(nnodes_by_elt * (iEnd - i1 + 1))]...) icurr = iEnd + 1 (icurr > nelts_bc) && break # Element-wise version (OK, but very slow) # while i1 <= elts_ind[icurr] <= i2 # offset = (elts_ind[icurr] - i1) * nnodes_by_elt # push!(bcnodes, elt.c2n[(1 + offset):(offset + nnodes_by_elt)]...) # (icurr == nelts_bc) && break # icurr += 1 # end end @assert icurr >= nelts_bc else error("Could not find either the PointRange nor the PointList") end elseif bc_type == "Vertex" if !isnothing(pointList) bcnodes = get_value(pointList) elseif !isnothing(indexRange) erange = get_value(indexRange) bcnodes = collect(erange[1]:erange[2]) else error("Could not find either the PointRange nor the PointList") end # TODO : we could try to guess `bcdim` by search the Elements_t containing # the points of the PointList else error("BC GridLocation '$(bc_type)' not implemented") end return (; bcname, bcnodes, bcdim) end """ Read all the flow solutions in the Zone, filtering data arrays whose name is not in the `varnames` list # TODO : check if all varnames have been found """ function read_solutions(zone, varnames, verbose) # fSols = # map(fs -> read_solution(fs, varnames), get_children(zone; type = "FlowSolution_t")) # n_vertex_fsol = count(fs -> fs.gridLocation == "Vertex", fSols) # n_cell_fsol = count(fs -> fs.gridLocation == "CellCenter", fSols) # if verbose # (n_vertex_fsol > 1) && println( # "WARNING : found more than one Vertex FlowSolution, reading them all...", # ) # (n_cell_fsol > 1) && println( # "WARNING : found more than one CellCenter FlowSolution, reading them all...", # ) # end fSols = Dict( get_name(fs) => read_solution(fs, varnames) for fs in get_children(zone; type = "FlowSolution_t") ) return fSols end """ Read a FlowSolution node. Return a NamedTuple with flow solution name, grid location and array of vectors. """ function read_solution(fs, varnames) # Read GridLocation : we could deal with a missing GridLocation node, by later comparing # the length of the DataArray to the number of cells / nodes of the zone. Let's do this # later. node = get_child(fs; type = "GridLocation_t") @assert !isnothing(node) "Missing GridLocation in FlowSolution '$(get_name(fs))'" gridLocation = get_value(node) # Read variables matching asked "varnames" dArrays = get_children(fs; type = "DataArray_t") if varnames != "*" # filter to obtain only the desired variables names filter!(dArray -> get_name(dArray) in varnames, dArrays) end data = Dict(get_name(dArray) => get_value(dArray) for dArray in dArrays) # Flow solution name name = get_name(fs) return (; name, gridLocation, data) end """ Indicate if the Elements node contains "volumic" entities (with respect to the `topo_dim` argument) """ function is_volumic_entity(node::Node, topo_dim) @assert get_cgns_type(node) == "Elements_t" code, _ = get_value(node) return is_volumic_entity(code, topo_dim) end function is_volumic_entity(code, topo_dim) Bcube.topodim(cgns_entity_to_bcube_entity(code)) == topo_dim end """ Read an "Elements_t" node and returns a named Tuple of three elements: * `erange`, the content of the `ElementRange` node * `c2t`, the cell -> entity_type connectivity * `c2n`, the cell -> node connectivity, flattened if `reshape = false`, as an array (nelts, nnodes_by_elt) if `reshape = true` * `name`, only for dbg """ function read_connectivity(node, reshape = false) @assert get_cgns_type(node) == "Elements_t" # Build cell to (cgns) type code, _ = get_value(node) erange = get_value(get_child(node; name = "ElementRange")) nelts = erange[2] - erange[1] + 1 c2t = fill(code, nelts) # Build cell to node and reshapce c2n = get_value(get_child(node; name = "ElementConnectivity")) nnodes_by_elt = nnodes(cgns_entity_to_bcube_entity(code)) reshape && (c2n = reshape(c2n, nelts, nnodes_by_elt)) return (; erange, c2t, c2n, name = get_name(node)) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
506
function Bcube.write_file( ::Bcube.JLD2IoHandler, basename::String, mesh::Bcube.AbstractMesh, vars::Dict{String, F} = Dict{String, Bcube.AbstractLazy}(), U_export::Bcube.AbstractFESpace = SingleFESpace(FunctionSpace(:Lagrange, 1), mesh), it::Integer = -1, time::Real = 0.0; collection_append = false, kwargs..., ) where {F <: Bcube.AbstractLazy} error("not implemented yet") mode = collection_append ? "a+" : "w" jldopen(basename, mode) do file end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
3755
module Bcube using Base using Base: @propagate_inbounds using StaticArrays using SparseArrays using FEMQuad using FastGaussQuadrature using ForwardDiff using LinearAlgebra using WriteVTK using Printf # just for tmp vtk, to be removed # import LinearSolve: solve, solve!, LinearProblem import LinearSolve using Symbolics # used for generation of Lagrange shape functions const MAX_LENGTH_STATICARRAY = (10^6) include("LazyOperators/LazyOperators.jl") using .LazyOperators import .LazyOperators: materialize, materialize_args, AbstractLazyOperator, get_args, get_operator, unwrap export lazy_compose include("utils.jl") include("./mesh/transformation.jl") export Translation, Rotation include("./mesh/boundary_condition.jl") export BoundaryCondition, PeriodicBCType include("./mesh/entity.jl") export Node_t, Bar2_t, Bar3_t, Tri3_t, Quad4_t, Quad9_t, Tetra4_t, Hexa8_t, Pyra5_t, Poly2_t, Poly3_t, Node, get_coords include("./mesh/shape.jl") include("./mesh/connectivity.jl") include("./mesh/mesh.jl") export ncells, nnodes, boundary_names, nboundaries, boundary_tag, get_nodes include("./mesh/mesh_generator.jl") export basic_mesh, one_cell_mesh, line_mesh, rectangle_mesh, hexa_mesh, ncube_mesh, circle_mesh, scale, scale!, transform, transform!, translate, translate! include("./mesh/gmsh_utils.jl") export read_msh, read_msh_with_cell_names, gen_line_mesh, gen_rectangle_mesh, gen_hexa_mesh, gen_disk_mesh, gen_star_disk_mesh, gen_cylinder_mesh, read_partitions, gen_rectangle_mesh_with_tri_and_quad include("./mesh/domain.jl") export AbstractDomain, CellDomain, InteriorFaceDomain, BoundaryFaceDomain, get_mesh, get_face_normals include("./quadrature/quadrature.jl") export QuadratureLobatto, QuadratureLegendre, QuadratureUniform, Quadrature, QuadratureRule include("./function_space/function_space.jl") export FunctionSpace, get_degree include("./function_space/lagrange.jl") include("./function_space/taylor.jl") include("./mapping/mapping.jl") include("./mapping/ref2phys.jl") export get_cell_centers include("./cellfunction/eval_point.jl") include("./cellfunction/cellfunction.jl") export PhysicalFunction, ReferenceFunction, side_p, side_n, side⁺, side⁻, jump include("./cellfunction/meshdata.jl") export MeshCellData, MeshFaceData, MeshPointData, get_values, set_values! include("./fespace/dofhandler.jl") include("./fespace/fespace.jl") export TestFESpace, TrialFESpace, MultiplierFESpace, MultiFESpace, get_ndofs, get_fespace include("./fespace/fefunction.jl") export FEFunction, set_dof_values!, get_dof_values, get_fe_functions include("./fespace/eval_shape_function.jl") include("./integration/measure.jl") export AbstractMeasure, Measure, get_domain include("./integration/integration.jl") export ∫ include("./algebra/gradient.jl") export ∇, ∇ₛ include("./algebra/algebra.jl") export FaceNormal, otimes, ⊗, dcontract, ⊡ include("./assembler/assembler.jl") export assemble_bilinear, assemble_linear, assemble_linear! include("./assembler/dirichlet_condition.jl") export assemble_dirichlet_vector, apply_dirichlet_to_matrix!, apply_dirichlet_to_vector!, apply_homogeneous_dirichlet_to_vector! include("./assembler/affine_fe_system.jl") export AffineFESystem include("./feoperator/projection_newapi.jl") export projection_l2! include("./feoperator/projection.jl") export var_on_centers, var_on_vertices, var_on_nodes_discontinuous, var_on_bnd_nodes_discontinuous include("./feoperator/limiter.jl") export linear_scaling_limiter include("./io/io_interface.jl") export read_file, read_mesh, write_file include("./writers/vtk.jl") export write_vtk end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
5854
""" densify(a::AbstractVector, [permute_back=false]) Remap values of `a`, i.e if `length(a) = n`, make sure that every value of `a` belongs to [1,n] (in other words, eliminate holes in values of `a`). """ function densify(a::AbstractVector{T}; permute_back::Bool = false) where {T <: Integer} _a = unique(a) remap = Dict{eltype(a), eltype(a)}(_a[i] => i for i in 1:length(_a)) #zeros(eltype(a), maximum(_a)) dense_a = [remap[aᵢ] for aᵢ in a] permute_back ? (return dense_a, remap) : (return dense_a) end function densify!(a::AbstractVector{T}) where {T <: Integer} a .= densify(a) end """ myrand(n, xmin = 0., xmax = 1.) Create a random vector of size `n` with `xmin` and `xmax` as bounds. Use `xmin` and `xmax` either as scalars or as vectors of size `n`. """ myrand(n, xmin = 0.0, xmax = 1.0) = (xmax .- xmin) .* rand(n) .+ xmin """ rawcat(x) Equivalent to `reduce(vcat,vec.(x))` """ function rawcat( x::Union{NTuple{N, A}, Vector{A}}, ) where {N, A <: Union{AbstractArray{T}, Tuple{Vararg{T}}}} where {T} isempty(x) && return T[] n = sum(length, x) y = Vector{T}(undef, n) i = 0 for x1 in x, x2 in x1 i += 1 @inbounds y[i] = x2 end @assert i == n "Dimension mismatch" return y end rawcat(x::Vector{T}) where {T} = x """ matrix_2_vector_of_SA(a) """ matrix_2_vector_of_SA(a) = vec(reinterpret(SVector{size(a, 1), eltype(a)}, a)) """ convert_to_vector_of_union(a::Vector{T}) where T Convert a vector 'a', whose the element type is abstract, to a vector whose the element type is a 'Union' of concrete types (if it is possible) """ function convert_to_vector_of_union(a::Vector{T}) where {T} if !isconcretetype(T) types = unique(typeof, a) a_ = Union{typeof.(types)...}[a...] return a_ else return a end end function _soft_max(x, y, k) m = min(x, y) M = max(x, y) return M + log(1.0 + exp((m - M) * k)) / k end #soft_max(x::ForwardDiff.Dual, y::ForwardDiff.Dual, k=10) = _soft_max(x,y,k) #soft_max(x, y, k=10) = _soft_max(x,y,k) soft_max(x, y) = max(x, y) #default _soft_min(x, y, k) = -log(exp(-k * x) + exp(-k * y)) / k #soft_min(x::ForwardDiff.Dual, y::ForwardDiff.Dual, k=10) = min(x,y)#_soft_min(x,y,k) #soft_min(x,y, k=10) = _soft_min(x,y,k) soft_min(x, y) = min(x, y) #default _soft_abs(x, k) = √(x^2 + k^2) #soft_abs(x, k=0.001) = abs(x) #_soft_abs(x,k) #soft_abs(x::ForwardDiff.Dual, k=0.001) = _soft_abs(x,k)# x*tanh(x/k) soft_abs(x) = abs(x) soft_extrema(itr) = soft_extrema(identity, itr) function soft_extrema(f, itr) y = iterate(itr) y === nothing && throw(ArgumentError("collection must be non-empty")) (v, s) = y vmin = vmax = f(v) while true y = iterate(itr, s) y === nothing && break (x, s) = y fx = f(x) vmax = soft_max(fx, vmax) vmin = soft_min(fx, vmin) end return (vmin, vmax) end # warning : it relies on julia internal! raw_unzip(a) = a.is """ WiddenAsUnion{T} Type used internally by `map_and_widden_as_union`. """ struct WiddenAsUnion{T} a::T end function Base.promote_typejoin( ::Type{WiddenAsUnion{T1}}, ::Type{WiddenAsUnion{T2}}, ) where {T1, T2} return Union{WiddenAsUnion{T1}, WiddenAsUnion{T2}} end function Base.promote_typejoin( ::Type{Union{WiddenAsUnion{T1}, T2}}, ::Type{WiddenAsUnion{T3}}, ) where {T1, T2, T3} return Union{WiddenAsUnion{T1}, T2, WiddenAsUnion{T3}} end unwrap(x::WiddenAsUnion) = x.a unwrap(::Type{WiddenAsUnion{T}}) where {T} = T unwrap(::Type{Union{WiddenAsUnion{T1}, T2}}) where {T1, T2} = Union{unwrap(T1), unwrap(T2)} """ map_and_widden_as_union(f, c...) Transform collection `c` by applying `f` to each element. For multiple collection arguments, apply `f` elementwise, and stop when any of them is exhausted. The difference with [`map`](@ref) comes from the type of the result: `map_and_widden_as_union` uses `Union` to widden the type of the resulting collection and potentially reduce type instabilities. # Examples ```jldoctest julia> map_and_widden_as_union(x -> x * 2, [1, 2, [3,4]]) 3-element Vector{Union{Int64, Vector{Int64}}}: 2 4 [6, 8] ``` instead of: ```jldoctest julia> map(x -> x * 2, [1, 2, [3,4]]) 3-element Vector{Any}: 2 4 [6, 8] ``` # Implementation When `f` is applied to one element of `c`, the result is wrapped in a type `WrapAsUnion` on which specific `promote_typejoin` rules are applied. When `map_and_widden_as_union` is applied to collections of heterogeneous elements, these rules help to infer the type of the resulting collection as a `Union` of different types instead of a widder (abstract) type. """ function map_and_widden_as_union(f, c...) g(x...) = WiddenAsUnion(f(x...)) a = map(g, c...) T = unwrap(eltype(a)) return T[unwrap(x) for x in a] end """ myfindfirst(predicate::Function, t::Tuple) Function equivalent to `Base.findfirst(predicate::Function, A)`. This version is optimized to work better on `Tuple` by avoiding type instabilities. # source: https://discourse.julialang.org/t/why-does-findfirst-t-on-a-tuple-of-typed-only-constant-fold-for-the-first/68893/3 """ myfindfirst(predicate::Function, t::Tuple) = _findfirst(predicate, 1, t) _findfirst(f, i, x) = f(first(x)) ? i : _findfirst(f, i + 1, Base.tail(x)) _findfirst(f, i, ::Tuple{}) = nothing # see : https://discourse.julialang.org/t/why-doesnt-the-compiler-infer-the-type-of-this-function/35005/3 @inline function tuplemap(f, t1::Tuple{Vararg{Any, N}}, t2::Tuple{Vararg{Any, N}}) where {N} (f(first(t1), first(t2)), tuplemap(f, Base.tail(t1), Base.tail(t2))...) end @inline function tuplemap(f, t::Tuple{Vararg{Any, N}}) where {N} (f(first(t)), tuplemap(f, Base.tail(t))...) end @inline tuplemap(f, ::Tuple{}) = () @inline tuplemap(f, ::Tuple{}, ::Tuple{}) = ()
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1017
module LazyOperators import Base: *, /, +, -, ^, max, min, sqrt, abs, tan, sin, cos, tanh, sinh, cosh, atan, asin, acos, zero, one, materialize using LinearAlgebra import LinearAlgebra: dot, transpose, tr export AbstractLazy export AbstractLazyWrap export AbstractLazyOperator export LazyOperator export LazyWrap export unwrap export materialize export show_lazy_operator export print_tree_prefix export pretty_name_style export pretty_name export NullOperator export lazy_compose export LazyMapOver export MapOver any_of_type(a::T, ::Type{T}) where {T} = Val(true) any_of_type(a, ::Type{T}) where {T} = Val(false) @generated function any_of_type(a::Tuple, ::Type{T}) where {T} _T = fieldtypes(a) if any(map(x -> isa(x, Type{<:T}), _T)) return :(Val(true)) else return :(Val(false)) end end function lazy_compose end include("lazy_operator.jl") include("algebra.jl") include("mapover.jl") end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
3350
############################################################### # Define rules for binary operators ############################################################### const LazyBinaryOp = (:*, :/, :+, :-, :^, :max, :min, :dot) for f in LazyBinaryOp @eval ($f)(a::AbstractLazy, b::AbstractLazy) = LazyOperator($f, a, b) @eval ($f)(a::AbstractLazy, b) = ($f)(a, LazyWrap(b)) @eval ($f)(a, b::AbstractLazy) = ($f)(LazyWrap(a), b) end ############################################################### # Define rules for unary operators ############################################################### const LazyUnaryOp = ( :+, :-, :transpose, :tr, :sqrt, :abs, :tan, :sin, :cos, :tanh, :sinh, :cosh, :atan, :asin, :acos, :zero, :one, ) for f in LazyUnaryOp @eval ($f)(a::AbstractLazy) = LazyOperator($f, a) @eval ($f)(::NullOperator) = NullOperator() end ############################################################### # Define rules with `NullOperator` ############################################################### # For binary `+` and `-`: for f in (:+, :-) @eval ($f)(a, ::NullOperator) = a @eval ($f)(::NullOperator, b) = ($f)(b) @eval ($f)(::NullOperator, ::NullOperator) = NullOperator() @eval ($f)(a::AbstractLazy, ::NullOperator) = a @eval ($f)(::NullOperator, b::AbstractLazy) = ($f)(b) end # For binary `*` and `dot`: for f in (:*, :dot) @eval ($f)(a, ::NullOperator) = NullOperator() @eval ($f)(::NullOperator, b) = NullOperator() @eval ($f)(::NullOperator, ::NullOperator) = NullOperator() @eval ($f)(::AbstractLazy, ::NullOperator) = NullOperator() @eval ($f)(::NullOperator, ::AbstractLazy) = NullOperator() end # For binary `/`: Base.:/(a, ::NullOperator) = error("Division by an AbstractNullOperator is not allowed.") Base.:/(a::NullOperator, b) = a Base.:/(::NullOperator, ::NullOperator) = NullOperator() # For binary `^`: Base.:^(a, ::NullOperator) = error("Undefined") Base.:^(a::NullOperator, b) = a Base.:^(::NullOperator, ::NullOperator) = NullOperator() # or "I" ? Base.:^(a::AbstractLazy, ::NullOperator) = error("Undefined") Base.:^(a::NullOperator, b::AbstractLazy) = a ############################################################### # Define rules with `broadcasted` ############################################################### function Base.broadcasted(f, a::AbstractLazy...) f_broacasted(x...) = broadcast(f, x...) LazyOperator(f_broacasted, a...) end Base.broadcasted(f, a::AbstractLazy, b) = Base.broadcasted(f, a, LazyWrap(b)) Base.broadcasted(f, a, b::AbstractLazy) = Base.broadcasted(f, LazyWrap(a), b) ############################################################### # Define rules with composition ############################################################### lazy_compose(a, b...) = lazy_compose(a, b) lazy_compose(a, b::Tuple) = LazyOperator(lazy_compose, LazyWrap(a), LazyWrap(b...)) # trigger lazy composition for `f∘tuple(a...)` if in the tuple # there is an `AbtractLazy` at first position, Base.:∘(a::Function, b::AbstractLazy) = lazy_compose(a, (b,)) function Base.:∘(a::Function, b::Tuple{AbstractLazy, Vararg{Any}}) lazy_compose(a, b) end function Base.:∘(a::Function, b::Tuple{Tuple{AbstractLazy, Vararg{Any}}, Vararg{Any}}) lazy_compose(a, b) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
9593
""" abstract type AbstractLazy end Subtypes must implement: - `materialize(a::AbstractLazy, x)` and optionally: - `pretty_name(a::AbstractLazy)` - `show_lazy_operator(a::AbstractLazy; level=1, indent=4, islast=(true,))` """ abstract type AbstractLazy end # default rule : materialize of `a` is `a` materialize(a, x0, x1...) = a # default rule on tuple is to apply materialize on each element of the tuple materialize(t::Tuple, x::Vararg{Any, N}) where {N} = LazyWrap(_materialize(t, x...)) function _materialize(t::Tuple, x::Vararg{Any, N}) where {N} (materialize(first(t), x...), _materialize(Base.tail(t), x...)...) end _materialize(::Tuple{}, ::Vararg{Any, N}) where {N} = () pretty_name(a) = string(typeof(a)) pretty_name(a::Number) = string(a) pretty_name(a::Base.Fix1) = "Fix1: (f=" * pretty_name(a.f) * ", x=" * pretty_name(a.x) * ")" pretty_name(a::Base.Fix2) = "Fix2: (f=" * pretty_name(a.f) * ", x=" * pretty_name(a.x) * ")" pretty_name_style(a) = Dict(:color => :normal) function show_lazy_operator( a; level = 1, indent = 4, islast = (true,), printTupleOp::Bool = false, ) print_tree_prefix(level, indent, islast) printstyled(pretty_name(a) * " \n"; pretty_name_style(a)...) end function print_tree_prefix(level, indent = 4, islast = (true,)) _color = map(x -> x ? :light_black : :normal, islast) motif = "│" * join(fill(" ", max(0, indent - 1))) if level > 1 for lev in 2:(level - 1) printstyled(motif; color = _color[lev]) end prefix = "└" * join(fill("─", max(0, indent - 2))) * " " printstyled(prefix; color = :normal) end end function pretty_name(f::Function) name = string(typeof(f)) delimiter = '"' if contains(name, delimiter) splitname = split(name, delimiter) name = splitname[1] * delimiter * splitname[2] * delimiter end return name end pretty_name_style(::Function) = Dict(:color => :light_green) pretty_name(::Nothing) = "" """ AbstractLazyWrap{A} <: AbstractLazy Subtypes must implement: - `get_args(a::AbstractLazyWrap)` and optionally: - `unwrap(a::AbstractLazyWrap)` - `pretty_name(a::AbstractLazyWrap)` - `pretty_name_style(::AbstractLazyWrap) ` - `show_lazy_operator(a::AbstractLazyWrap; level=1, indent=4, islast=(true,))` """ abstract type AbstractLazyWrap{A} <: AbstractLazy end function get_args(a::AbstractLazyWrap) error("Function `get_args` is not defined for type $(typeof(a))") end function materialize(a::AbstractLazyWrap, x::Vararg{Any, N}) where {N} args = materialize_args(get_args(a), x...) may_unwrap_tuple(args) end unwrap(a) = a unwrap(a::AbstractLazyWrap) = get_args(a) may_unwrap_tuple(t::Tuple) = t may_unwrap_tuple(t::Tuple{T}) where {T} = first(t) pretty_name(a::AbstractLazyWrap) = "$(typeof(a))" pretty_name_style(::AbstractLazyWrap) = Dict(:color => :light_black) function show_lazy_operator( a::AbstractLazyWrap; level = 1, indent = 4, islast = (true,), printTupleOp::Bool = false, ) level == 1 && println("\n---------------") print_tree_prefix(level, indent, islast) printstyled(pretty_name(a) * " \n"; pretty_name_style(a)...) _islast = (islast..., true) show_lazy_operator( get_args(a); level = (level + 1), islast = _islast, printTupleOp = printTupleOp, ) level == 1 && println("---------------") end struct LazyWrap{A <: Tuple} <: AbstractLazyWrap{A} args::A end LazyWrap(args...) = LazyWrap{typeof(args)}(args) get_args(a::LazyWrap) = a.args pretty_name(::LazyWrap) = "LazyWrap" """ Subtypes must implement: - `get_args(op::AbstractLazyOperator)` - `get_operator(op::AbstractLazyOperator)` - `materialize(Op::AbstractLazyOperator, x)` Subtypes can implement: - `show_lazy_op` """ abstract type AbstractLazyOperator{O, A} <: AbstractLazy end get_type_operator(::Type{<:AbstractLazyOperator{O}}) where {O} = O get_type_operator(op::AbstractLazyOperator) = get_type_operator(typeof(op)) get_type_args(::Type{<:AbstractLazyOperator{O, A}}) where {O, A} = fieldtypes(a) get_type_args(op::AbstractLazyOperator) = get_type_args(typeof(op)) function get_args(op::AbstractLazyOperator) error("Function `get_args` is not defined for type $(typeof(op))") end function get_operator(op::AbstractLazyOperator) error("Function `get_operator` is not defined for type $(typeof(op))") end pretty_name(::Type{<:AbstractLazyOperator}) = "AbstractLazyOperator" pretty_name(op::AbstractLazyOperator) = string(nameof(typeof(op))) pretty_name_style(::Type{<:AbstractLazyOperator}) = Dict(:color => :red) pretty_name_style(op::AbstractLazyOperator) = pretty_name_style(typeof(op)) function materialize(lOp::AbstractLazyOperator, x::Vararg{Any, N}) where {N} op = get_operator(lOp) args = materialize_args(get_args(lOp), x...) materialize_op(op, args...) end # default materialize_op(op::O, args::Vararg{Any, N}) where {O, N} = op(args...) # specific operator materialization for composition: # if `args` contains one `AbstractLazy` type at least then: # the result is still a lazy composition # else: # the result is the application of the function (i.e args1) # to its args. @inline function materialize_op(op::typeof(lazy_compose), args::Vararg{Any, N}) where {N} _materialize_op_compose(op, args...) end @inline function _materialize_op_compose( op::O, arg1::T, args::Vararg{Any, N}, ) where {O, T, N} _materialize_op_compose(any_of_type(args..., AbstractLazy), op, arg1, args...) end @inline function _materialize_op_compose( ::Val{true}, op::O, args::Vararg{Any, N}, ) where {O, N} op(args...) end @inline function _materialize_op_compose( ::Val{false}, op, arg1::T1, args::Vararg{Any, N}, ) where {T1, N} _may_apply_on_splat(arg1, args...) end _may_apply_on_splat(f, a::Tuple) = f(a...) _may_apply_on_splat(f, a) = f(a) # avoid: # @inline materialize_args(args::Tuple, x ) = map(Base.Fix2(materialize, x), args) # as inference seems to fail rapidely materialize_args(args::Tuple, x::Vararg{Any, N}) where {N} = _materialize_args(args, x...) function _materialize_args(args::Tuple, x::Vararg{Any, N}) where {N} (materialize(first(args), x...), _materialize_args(Base.tail(args), x...)...) end _materialize_args(args::Tuple{}, x::Vararg{Any, N}) where {N} = () # @generated materialize_args(args::Tuple, x...) = _materialize_args_impl(args) # function _materialize_args_impl(::Type{<:Tuple{Vararg{Any,N}}}) where {N} # exprs = [:(materialize(args[$i], x...)) for i in 1:N] # return :(tuple($(exprs...))) # end # function show_lazy_operator(op; level=1, indent=4, prefix="") # println(prefix*string(typeof(op))) # end function show_lazy_operator( op::AbstractLazyOperator; level = 1, indent = 4, islast = (true,), ) level == 1 && println("\n---------------") print_tree_prefix(level, indent, islast) printstyled(pretty_name(op) * ": "; pretty_name_style(op)...) printstyled( pretty_name(get_operator(op)) * " \n"; pretty_name_style(get_operator(op))..., ) args = get_args(op) show_lazy_operator(args; level = (level + 1), islast = islast, printTupleOp = false) level == 1 && println("---------------") end _rm_first_character(a::String) = last(a, length(a) - 1) function _select_character(a::String, range) a[collect(eachindex(a))[first(range):min(last(range), length(a))]] end pretty_name(::Tuple) = "Tuple:" pretty_name_style(::Tuple) = Dict(:color => :light_black) function show_lazy_operator( t::Tuple; level = 1, indent = 4, islast = (true,), printTupleOp::Bool = true, ) _show_lazy_operator(Val(printTupleOp), t; level = level, islast = islast) end function _show_lazy_operator(::Val{true}, t::Tuple; level = 1, indent = 4, islast = (true,)) level == 1 && println("\n---------------") print_tree_prefix(level, indent, islast) printstyled(pretty_name(t) * ": \n"; pretty_name_style(t)...) _show_lazy_operator( Val(false), t; level = level + 1, indent = indent, islast = (islast...,), ) level == 1 && println("---------------") nothing end function _show_lazy_operator( ::Val{false}, t::Tuple; level = 1, indent = 4, islast = (true,), ) for (i, x) in enumerate(t) _islast = (islast..., i == length(t)) show_lazy_operator(x; level = level, indent = indent, islast = _islast) end nothing end (lOp::AbstractLazyOperator)(x::Vararg{Any, N}) where {N} = materialize(lOp, x...) struct LazyOperator{O, A <: Tuple} <: AbstractLazyOperator{O, A} operator::O args::A end LazyOperator(op, args...) = LazyOperator{typeof(op), typeof(args)}(op, args) get_args(op::LazyOperator) = op.args get_operator(op::LazyOperator) = op.operator abstract type AbstractNullOperator <: AbstractLazy end struct NullOperator <: AbstractNullOperator end pretty_name(::NullOperator) = "∅" get_operator(a::NullOperator) = nothing get_args(a::NullOperator) = (nothing,) materialize(a::NullOperator, x) = a # Base.length(::NullOperator) = 1 # Base.iterate(a::NullOperator) = (a, nothing) # Base.iterate(a::NullOperator, state) = nothing Base.map(f, a::NullOperator) = f(a) function show_lazy_operator(op::NullOperator; level = 1, indent = 4, islast = (true,)) level == 1 && println("\n---------------") print_tree_prefix(level, indent, islast) printstyled(pretty_name(op) * "\n"; pretty_name_style(op)...) level == 1 && println("---------------") end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
6895
""" AbtractLazyMapOver{A} <: AbstractLazyWrap{A} Subtypes must implement: - `get_args(lmap::AbtractLazyMapOver)` and optionally: - `pretty_name(a::AbtractLazyMapOver)` - `pretty_name_style(::AbtractLazyMapOver)` - `show_lazy_operator(a::AbtractLazyMapOver; level=1, indent=4, islast=(true,))` """ abstract type AbstractLazyMapOver{A} <: AbstractLazyWrap{A} end """ LazyMapOver{A} <: AbstractLazyMapOver{A} Type used to wrap data (of type `A`) on which functions must be mapped over it. """ struct LazyMapOver{A} <: AbstractLazyMapOver{A} args::A end LazyMapOver(args::Tuple) = LazyMapOver{typeof(args)}(args) LazyMapOver(args...) = LazyMapOver{typeof(args)}(args) get_args(a::LazyMapOver) = a.args pretty_name(::LazyMapOver) = "LazyMapOver" pretty_name_style(::LazyMapOver) = Dict(:color => :blue) materialize(a::LazyMapOver, x) = LazyMapOver(lazy_map_over(Base.Fix2(materialize, x), a)) materialize(f::F, a::LazyMapOver) where {F <: Function} = lazy_map_over(f, a) (a::LazyMapOver)(x::Vararg{Any, N}) where {N} = materialize(a, x...) function lazy_map_over(f::F, a::Vararg{LazyMapOver, N}) where {F <: Function, N} _tuplemap(f, _tuplemap(get_args, a)...) end # Specialize the previous method for two levels of LazyMapOver # in order to help compiler inference to deal with recursion. function lazy_map_over( f::F, a::Vararg{LazyMapOver{<:NTuple{N1, LazyMapOver}}, N}, ) where {F <: Function, N, N1} _tuplemap(f, _tuplemap(get_args, a)...) end """ _tuplemap(f::F, t::Vararg{NTuple{N1, Any}, N}) Transform (multi-)tuple `t` by applying `f` (elementwise) to each element, similarly to `Base.map(f, t...)`. This method is implemented recursively to help inference and improve performance. """ @inline function _tuplemap(f::F, t::Vararg{NTuple{N1, Any}, N}) where {F, N, N1} @inline heads = map(first, t) tails = map(Base.tail, t) (f(heads...), _tuplemap(f, tails...)...) end @inline _tuplemap(f::F, ::Vararg{Tuple{}, N}) where {F, N} = () # _first(a::NTuple{N}, b::Vararg{NTuple{N}}) where {N} = (first(a), _first(b)...) # _tail(a::NTuple{N}, b::Vararg{NTuple{N}}) where {N} = (first(a), _first(b)...) # function _tuplemap(f::F, t1::Tuple{Vararg{Any, N}}, t2::Tuple{Vararg{Any, N}}) where {F, N} # (f(first(t1), first(t2)), _tuplemap(f, Base.tail(t1), Base.tail(t2))...) # end # function _tuplemap(f::F, t::Tuple{Vararg{Any, N}}) where {F, N} # (f(first(t)), _tuplemap(f, Base.tail(t))...) # end # _tuplemap(f, ::Tuple{}) = () # _tuplemap(f, ::Tuple{}, ::Tuple{}) = () abstract type AbstractMapOver{A} end get_basetype(::Type{<:T}) where {T <: AbstractMapOver} = error("to be defined") get_basetype(a::AbstractMapOver) = get_basetype(typeof(a)) unwrap(a::AbstractMapOver) = a.args unwrap(a::Tuple{Vararg{Any, N}}) where {N} = _unwrap_map_over(a) _unwrap_map_over(a::Tuple{}) = () _unwrap_map_over(a::Tuple{T}) where {T} = (unwrap(first(a)),) _unwrap_map_over(a::Tuple) = (unwrap(first(a)), _unwrap_map_over(Base.tail(a))...) (a::AbstractMapOver)(x::Vararg{Any, N}) where {N} = evaluate(a, x...) function evaluate(a::T, x::Vararg{Any, N}) where {T <: AbstractMapOver, N} map_over(Base.Fix2(evaluate, x), a) end evaluate(a, x::AbstractMapOver) = map_over(Base.Fix1(evaluate, a), x) Base.map(f::F, a::Vararg{AbstractMapOver, N}) where {F <: Function, N} = map_over(f, a...) for f in LazyBinaryOp @eval ($f)(a::AbstractMapOver, b::AbstractMapOver) = map_over($f, a, b) @eval ($f)(a::AbstractMapOver, b) = map_over(Base.Fix2($f, b), a) @eval ($f)(a, b::AbstractMapOver) = map_over(Base.Fix1($f, a), b) #fix ambiguity #@eval ($f)(a::AbstractMapOver, b::AbstractLazy) = map_over(Base.Fix2($f, b), a) #@eval ($f)(a::AbstractLazy, b::AbstractMapOver) = map_over(Base.Fix1($f, a), b) end for f in LazyUnaryOp @eval ($f)(a::AbstractMapOver) = map_over($f, a) end # remove ambiguity: Base.:*(::AbstractMapOver, ::NullOperator) = NullOperator() Base.:*(::NullOperator, ::AbstractMapOver) = NullOperator() Base.:/(::AbstractMapOver, ::NullOperator) = error("Invalid operation") Base.:/(::NullOperator, b::AbstractMapOver) = NullOperator() Base.:+(a::AbstractMapOver, ::NullOperator) = a Base.:+(::NullOperator, b::AbstractMapOver) = b Base.:-(a::AbstractMapOver, ::NullOperator) = a Base.:-(::NullOperator, b::AbstractMapOver) = -b Base.:^(::AbstractMapOver, ::NullOperator) = error("Undefined") Base.:^(::NullOperator, ::AbstractMapOver) = NullOperator() Base.max(a::AbstractMapOver, ::NullOperator) = a Base.max(::NullOperator, b::AbstractMapOver) = b Base.min(a::AbstractMapOver, ::NullOperator) = a Base.min(::NullOperator, b::AbstractMapOver) = b LinearAlgebra.dot(::AbstractMapOver, ::NullOperator) = NullOperator() LinearAlgebra.dot(::NullOperator, ::AbstractMapOver) = NullOperator() """ map_over(f, args::AbstractMapOver...) Similar to `Base.map(f, args...)`. To help inference and improve performance, this method is implemented recursively and is based on method `_tuplemap` """ function map_over( f::F, args::Vararg{AbstractMapOver{<:Tuple{Vararg{Number}}}, N}, ) where {F <: Function, N} f_a = _tuplemap(f, _tuplemap(unwrap, args)...) T = get_basetype(typeof(first(args))) T(f_a) end function map_over(f::F, args::Vararg{AbstractMapOver, N}) where {F <: Function, N} f_a = _map_over(f, _tuplemap(unwrap, args)...) T = get_basetype(typeof(first(args))) T(f_a) end function _map_over(f::F, a::Vararg{Tuple, N}) where {F <: Function, N} _heads = Base.heads(a...) _tails = Base.tails(a...) (__map_over(f, _heads...), _map_over(f, _tails...)...) end _map_over(f::F, a::Vararg{Tuple{}, N}) where {F <: Function, N} = () function _map_over(::Val{0}, f::F, a::Vararg{Tuple, N}) where {F <: Function, N} _tuplemap(f, a...) end __map_over(f::F, a::Vararg{Any, N}) where {F, N} = f(a...) __map_over(f::F, a::Vararg{AbstractMapOver, N}) where {F, N} = map_over(f, a...) pretty_name(a::AbstractMapOver) = string(get_basetype(a)) pretty_name_style(a::AbstractMapOver) = Dict(:color => :blue) function show_lazy_operator(a::AbstractMapOver; level = 1, indent = 4, islast = (true,)) print_tree_prefix(level, indent, islast) printstyled(pretty_name(a) * ": "; pretty_name_style(a)...) printstyled(pretty_name(a) * " \n"; pretty_name_style(a)...) args = unwrap(a) for (i, arg) in enumerate(args) _islast = (islast..., i == length(args)) arg ≠ nothing && show_lazy_operator(arg; level = (level + 1), islast = _islast) end end """ MapOver{A} <: AbstractMapOver{A} A container used to wrap data for which all materialized operators on that data must be map over it. This corresponds to the non-lazy version of `LazyMapOver`. """ struct MapOver{A <: Tuple} <: AbstractMapOver{A} args::A end MapOver(args::Vararg{Any, N}) where {N} = MapOver{typeof(args)}(args) get_basetype(::Type{<:MapOver}) = MapOver
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
3466
otimes(x::AbstractVector, y::AbstractVector) = x * y' otimes(x::AbstractVector) = otimes(x, x) const ⊗ = otimes """ Tensors double contraction between third order tensor and second order tensor # Implementation Only valid for a tensor of dimension 3 with a tensor of dimension 2 for now: A[i,j,k] : B[l,m] = C[i] such as C[i] = A[i,j,k] * B[j,k] (Einstein sum) """ function dcontract(A::AbstractArray{T1, 3}, B::AbstractArray{T2, 2}) where {T1, T2} [sum(A[i, :, :] .* B) for i in 1:size(A)[1]] end dcontract(A::AbstractArray{T1, 2}, B::AbstractArray{T2, 3}) where {T1, T2} = dcontract(B, A) """ Tensors double contraction between second order tensors # Implementation A[i,j] : B[l,m] = c such as c = A[i,j] * B[i,j] (Einstein sum) """ dcontract(A::AbstractMatrix, B::AbstractMatrix) = sum(A .* B) """ Tensors double contraction between the identity tensor and a second order tensor # Implementation I : B = dot(I, B) B : I = dot(B, I) """ dcontract(I::UniformScaling, B::AbstractMatrix) = dot(I, B) dcontract(B::AbstractMatrix, I::UniformScaling) = dot(B, I) """ Tensors double contraction for third order tensors # Implementation A[i,j,k] : B[l,m,n] = C[i,l] such as C[i,l] = A[i,j,k] * B[l,j,k] (Einstein sum) """ function dcontract(A::AbstractArray{T1, 3}, B::AbstractArray{T2, 3}) where {T1, T2} sA = size(A) sB = size(B) C = zeros(sA[1], sB[1]) for i in 1:sA[1] for j in 1:sB[1] C[i, j] = sum(A[i, :, :] .* B[j, :, :]) end end return C end # dcontract for static arrays function dcontract( A::SArray{<:Tuple{I1, J, K}, T1, 3, L1}, B::SMatrix{J, K, T2, L2}, ) where {I1, J, K, T1, T2, L1, L2} return SVector{I1}(sum(A[i, :, :] .* B) for i in 1:I1) end function dcontract( B::SMatrix{J, K, T2, L2}, A::SArray{<:Tuple{I1, J, K}, T1, 3, L1}, ) where {I1, J, K, T1, T2, L1, L2} dcontract(A, B) end function dcontract( A::SArray{<:Tuple{I1, J, K}, T1, 3, L1}, B::SArray{<:Tuple{I2, J, K}, T2, 3, L2}, ) where {I1, J, K, I2, T1, T2, L1, L2} return SMatrix{I1, I2}(sum(A[i, :, :] .* B[j, :, :]) for i in 1:I1, j in 1:I2) end const ⊡ = dcontract ############################################################### # Extend LazyOperators behaviors with newly defined operators ############################################################### # GENERIC PART (it can be applied to all newly defined operators) for f in (:otimes, :dcontract) # deal with `AbstractLazy` @eval ($f)(a::AbstractLazy, b::AbstractLazy) = LazyOperator($f, a, b) @eval ($f)(a::AbstractLazy, b) = ($f)(a, LazyWrap(b)) @eval ($f)(a, b::AbstractLazy) = ($f)(LazyWrap(a), b) # deal with `MapOver` @eval ($f)(a::MapOver, b::MapOver) = LazyOperators.map_over($f, a, b) @eval ($f)(a::MapOver, b) = LazyOperators.map_over(Base.Fix2($f, b), a) @eval ($f)(a, b::MapOver) = LazyOperators.map_over(Base.Fix1($f, a), b) end # SPECIFIC PART : rules depend on how `NullOperator` acts with each operator. # Both `otimes` and `dcontract` follow the same # rule when they are applied to a `NullOperator`, # which is a "absorbing element" in this case. for f in (:otimes, :dcontract) @eval ($f)(a, ::NullOperator) = NullOperator() @eval ($f)(::NullOperator, b) = NullOperator() @eval ($f)(::NullOperator, ::NullOperator) = NullOperator() @eval ($f)(::AbstractLazy, ::NullOperator) = NullOperator() @eval ($f)(::NullOperator, ::AbstractLazy) = NullOperator() end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
11752
""" The `GradientStyle` helps distinguishing between "classic" gradient and a tangentiel gradient. # Implementation Note that the whole point of the `GradientStyle` is to allow two distinct symbols (∇ and ∇ₛ) for the classic and tangential gradient. Otherwise, the dispatch between classic / tangential could be done only in `ref2phys.jl`. """ abstract type AbstractGradientStyle end struct VolumicGradientStyle <: AbstractGradientStyle end struct TangentialGradientStyle <: AbstractGradientStyle end """ `GS` is the `AbstractGradientStyle` """ struct Gradient{O, A, GS} <: AbstractLazyOperator{O, A} args::A # `args` represent a Tuple containing the function whom gradient is computed end LazyOperators.get_args(lOp::Gradient) = lOp.args LazyOperators.get_operator(lOp::Gradient) = lOp Gradient(args::Tuple, gs::AbstractGradientStyle) = Gradient{Nothing, typeof(args), gs}(args) Gradient(f, gs::AbstractGradientStyle) = Gradient((f,), gs) Gradient(::NullOperator, ::AbstractGradientStyle) = NullOperator() Gradient(f) = Gradient(f, VolumicGradientStyle()) @inline gradient_style(::Gradient{O, A, GS}) where {O, A, GS} = GS const ∇ = Gradient TangentialGradient(f) = Gradient(f, TangentialGradientStyle()) const ∇ₛ = TangentialGradient """ Materialization of a `Gradient` on a `CellPoint`. Only valid for a function and a `CellPoint` defined on the reference domain. # Implementation The user writes mathematical expressions in the PhysicalDomain. So the gradient always represents the derivation with respect to the physical domain spatial coordinates, even if evaluated on a point expressed in the ReferenceDomain. The current Gradient implementation consists in applying ForwardDiff on the given operator 'u', on a point in the ReferenceDomain. That is to say, we compute ForwarDiff.derivative(ξ -> u ∘ F, ξ) (where F is the identity if u is defined is the ReferenceDomain). This gives ∇(u ∘ F)(ξ) = t∇(F)(ξ) * ∇(u)(F(x)). However, we only want ∇(u)(F(x)) : that's why a multiplication by the transpose of the inverse mapping jacobian is needed. An alternative approach would be to apply ForwardDiff in the PhysicalDomain : ForwarDiff.derivative(x -> u ∘ F^-1, x). The problem is that the inverse mapping F^-1 is not always defined. # Maths notes We use the following convention for any function f:R^n->R^p : ∇f is a tensor/matrix equal to ∂fi/∂xj. However when f is a scalar function, i.e f:R^n -> R, then ∇f is a column vector (∂f/∂x1, ∂f/∂x2, ...). That being said: - if λ is a scalar function, then ∇λ = transpose(J^(-1)) ̂∇̂λ - if λ is a vector function, then ∇λ = ̂∇̂λ J^(-1) Rq : note that the two formulae are different because we decided to break our own convention by writing, for a scalar function, ∇f as a column vector instead of a row vector. ## Proof (to be also written in Latex) x are the physical coords, X the reference coords. F(X) = x the mapping ref -> phys To compute an integral such as ∫g(x)dx, we map the integral on a ref element: ∫g(x)dx = ∫g∘F(X)dX 1) vector case : λ is a vector function if g(x) = ∇λ(x); i.e g(x) = ∂λi/∂xj, then we are looking for ∂λi/∂xj ∘ F. We now that λi = ̂λi ∘ F^-1, so (∂λi/∂xj)(x) = (∂(̂λi∘F^-1)/∂xj)(x) = (∂Fk^-1/∂xj)(x)*(∂̂λi/∂Xk)(X), hence ∂λi/∂xj = (∂Fk^-1/∂xj) * (∂̂λi/∂Xk ∘ F^-1) So if we compose with `F` to obtain the seeked term: (∂λi/∂xj) ∘ F = [(∂Fk^-1/∂xj) ∘ F] * (∂̂λi/∂Xk) Now, we define (J^-1)_kj as [(∂Fk^-1/∂xj) ∘ F]. Note that J^-1 is a function of X, whereas ∂Fk^-1/∂xj is a function of x... For the matrix-matrix product to be realised, we have to commute (J^-1)_kj and ∂̂λi/∂Xk (which is possible since we are working on scalar quantities thanks to Einstein convention): (∂λi/∂xj) ∘ F = (∂̂λi/∂Xk) * [(∂Fk^-1/∂xj) ∘ F] ∇λ_ij ∘ F = ̂∇̂λ_ik (J^-1)_kj To conclude, when we want to integrate ∇λ we need to calculate ∇λ ∘ F and this term is equal to ̂∇̂λ J^-1 2) scalar case : λ is a scalar function What has been said in 1 remains true (except i = 1 only). So we have: (∂λ/∂xj) ∘ F = [(∂Fk^-1/∂xj) ∘ F] * (∂̂λ/∂Xk), which could be written as ∇λ_j ∘ F = (J^-1)_kj * ∇λ_k However, because of the convention retained for gradient of a scalar function, (∂̂λ/∂Xk) is a column-vector so to perform a matrix-(column-vector) product, we need to transpose J^-1: ∇λ_j ∘ F = transpose(J^-1)_jk * ∇λ_k # Dev notes * The signature used to be `lOp::Gradient{O,<:Tuple{AbstractCellFunction{ReferenceDomain}}}`, but for some reason I don't understand, it didn't work for vector-valued shape functions. * We have an `if` because the formulae is sligthly different for a scalar function or a vector function (see maths section) TODO: * improve formulae with a reshape * Specialize for a ShapeFunction to use the hardcoded version instead of ForwardDiff """ function gradient( op::AbstractLazy, cPoint::CellPoint{ReferenceDomain}, gs::AbstractGradientStyle, ) f(_ξ) = op(CellPoint(_ξ, get_cellinfo(cPoint), ReferenceDomain())) ξ = get_coords(cPoint) valS = _size_codomain(f, ξ) cInfo = get_cellinfo(cPoint) cnodes = nodes(cInfo) ctype = celltype(cInfo) return ∂fξ_∂x(gs, f, valS, ctype, cnodes, ξ) # ForwarDiff applied in the PhysicalDomain : not viable because # the inverse mapping is not always known. # cPoint_phys = change_domain(cPoint, PhysicalDomain()) # f(ξ) = op(CellPoint(ξ, get_cellinfo(cPoint_phys), PhysicalDomain())) # fx = f(get_coords(cPoint_phys)) # return _gradient_or_jacobian(Val(length(fx)), f, get_coords(cPoint_phys)) end ∂fξ_∂x(::VolumicGradientStyle, args...) = ∂fξ_∂x(args...) ∂fξ_∂x(::TangentialGradientStyle, args...) = ∂fξ_∂x_hypersurface(args...) _size_codomain(f, x) = Val(length(f(x))) _size_codomain(f::AbstractCellFunction, x) = Val(get_size(f)) function gradient( op::AbstractLazy, cPoint::CellPoint{PhysicalDomain}, ::VolumicGradientStyle, ) # Fow now this version is "almost" never used because we never evaluate functions # in the physical domain (at least in (bi)linear forms). f(x) = op(CellPoint(x, cPoint.cellinfo, PhysicalDomain())) valS = _size_codomain(f, get_coords(cPoint)) return _gradient_or_jacobian(valS, f, get_coords(cPoint)) end # dispatch on codomain size (this is only used for functions evaluated on the physical domain) _gradient_or_jacobian(::Val{1}, f, x) = ForwardDiff.gradient(f, x) _gradient_or_jacobian(::Val{S}, f, x) where {S} = ForwardDiff.jacobian(f, x) function gradient( cellFunction::AbstractCellShapeFunctions{<:ReferenceDomain}, cPoint::CellPoint{ReferenceDomain}, gs::AbstractGradientStyle, ) cnodes = get_cellnodes(cPoint) ctype = get_celltype(cPoint) ξ = get_coords(cPoint) fs = get_function_space(cellFunction) n = Val(get_size(cellFunction)) MapOver(_grad_shape_functions(gs, fs, n, ctype, cnodes, ξ)) end ∂λξ_∂x(::VolumicGradientStyle, args...) = ∂λξ_∂x(args...) ∂λξ_∂x(::TangentialGradientStyle, args...) = ∂λξ_∂x_hypersurface(args...) function _grad_shape_functions( gs::AbstractGradientStyle, fs::AbstractFunctionSpace, n::Val{1}, ctype, cnodes, ξ, ) grad = ∂λξ_∂x(gs, fs, n, ctype, cnodes, ξ) _reshape_gradient_shape_function_impl(grad, n) end @generated function _reshape_gradient_shape_function_impl( a::SMatrix{Ndof, Ndim}, ::Val{1}, ) where {Ndof, Ndim} _exprs = [[:(a[$i, $j]) for j in 1:Ndim] for i in 1:Ndof] exprs = [:(SA[$(_expr...)]) for _expr in _exprs] return :(tuple($(exprs...))) end function _grad_shape_functions( gs::AbstractGradientStyle, fs::AbstractFunctionSpace, n::Val{N}, ctype, cnodes, ξ, ) where {N} # Note that the code below is identical to _grad_shape_functions(gs, fs, ::Val{1}, (...)) # However, for some space we might want a different implementation (for a different function space) # and this specific version (::Val{n}) will be the one to specialize. Whereas the scalar one will # always be true. grad = ∂λξ_∂x(gs, fs, Val(1), ctype, cnodes, ξ) _reshape_gradient_shape_function_impl(grad, n) end @generated function _reshape_gradient_shape_function_impl( a::SMatrix{Ndof_sca, Ndim, T}, ::Val{Ncomp}, ) where {Ndof_sca, Ndim, T, Ncomp} z = zero(T) exprs_tot = [] exprs = Matrix{Any}(undef, Ncomp, Ndim) for icomp in 1:Ncomp for idof_sca in 1:Ndof_sca for i in 1:Ncomp for j in 1:Ndim exprs[i, j] = i == icomp ? :(a[$idof_sca, $j]) : :($z) end end push!(exprs_tot, :(SMatrix{$Ncomp, $Ndim, $T}($(exprs...)))) end end :(tuple($(exprs_tot...))) end """ Materialization of a Gradient on a cellinfo is itself a Gradient, but with its function materialized """ function LazyOperators.materialize(lOp::Gradient, cInfo::CellInfo) Gradient(LazyOperators.materialize_args(get_args(lOp), cInfo), gradient_style(lOp)) end function LazyOperators.materialize( lOp::Gradient{O, <:Tuple{Vararg{AbstractCellFunction}}}, cPoint::CellPoint, ) where {O} f, = get_args(lOp) gradient(f, cPoint, gradient_style(lOp)) end function LazyOperators.materialize( lOp::Gradient{O, <:Tuple{AbstractLazy}}, cPoint::CellPoint, ) where {O} f, = get_args(lOp) gradient(f, cPoint, gradient_style(lOp)) end function LazyOperators.materialize( lOp::Gradient{O, <:Tuple}, sideInfo::AbstractSide, ) where {O} arg = LazyOperators.materialize_args(get_args(lOp), sideInfo) return Gradient(arg, gradient_style(lOp)) end """ Using MultiFESpace, we may want to compute Gradient(v) where v = (v1,v2,...). So `v` is a Tuple of LazyMapOver since v1, v2 are LazyMapOver (i.e they represent all the shape functions at once) """ function LazyOperators.materialize( lOp::Gradient{O, <:Tuple{LazyMapOver}}, cPoint::CellPoint, ) where {O} ∇x = tuplemap( x -> materialize(Gradient(x, gradient_style(lOp)), cPoint), get_args(get_args(lOp)...), ) return MapOver(∇x) end # Specialize the previous method when `Gradient` is applied # to two levels of LazyMapOver in order to help compiler inference # to deal with recursion. # This may be used by `bilinear_assemble` when a bilinear form # containing a `Gradient` is evaluated at a `CellPoint` function LazyOperators.materialize( lOp::Gradient{O, <:Tuple{LazyMapOver{<:NTuple{N, LazyMapOver}}}}, cPoint::CellPoint, ) where {O, N} ∇x = tuplemap( x -> materialize(Gradient(x, gradient_style(lOp)), cPoint), get_args(get_args(lOp)...), ) return MapOver(∇x) end function LazyOperators.materialize( lOp::Gradient{O, <:Tuple{LazyMapOver{<:CellShapeFunctions}}}, cPoint::CellPoint, ) where {O} return materialize(Gradient(get_args(get_args(lOp)...), gradient_style(lOp)), cPoint) end function LazyOperators.materialize( lOp::Gradient{O, <:Tuple{LazyMapOver{<:CellShapeFunctions}}}, sidePoint::AbstractSide{Nothing, <:Tuple{FacePoint}}, ) where {O} op_side = get_operator(sidePoint) cellPoint = op_side(get_args(sidePoint)...) return materialize(Gradient(get_args(get_args(lOp)...), gradient_style(lOp)), cellPoint) end function LazyOperators.materialize( lOp::Gradient{O, <:Tuple{LazyMapOver}}, sidePoint::AbstractSide{Nothing, <:Tuple{FacePoint}}, ) where {O} ∇x = tuplemap( x -> materialize(Gradient(x, gradient_style(lOp)), sidePoint), get_args(get_args(lOp)...), ) return MapOver(∇x) end function LazyOperators.materialize( lOp::Gradient{O, <:Tuple{Vararg{AbstractCellFunction}}}, sidePoint::AbstractSide{Nothing, <:Tuple{FacePoint}}, ) where {O} op_side = get_operator(sidePoint) cellPoint = op_side(get_args(sidePoint)...) materialize(lOp, cellPoint) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
3031
""" Represent the affine system associated to a(u,v) = l(v), where `a` is bilinear, with eventual Dirichlet conditions on `u` # Dev notes * we could avoid having `mesh` as an attribute by storing one (or the two) form : `a` and/or `l`. Then the mesh can be retrieved from those two forms. """ struct AffineFESystem{T <: Number, Mat <: AbstractMatrix{<:Number}, TriFE, TesFE} A::Mat b::Vector{T} U::TriFE V::TesFE mesh::Mesh function AffineFESystem( A::AbstractMatrix{<:Number}, b::Vector{T}, U, V, mesh::Mesh, ) where {T} new{T, typeof(A), typeof(U), typeof(V)}(A, b, U, V, mesh) end end """ Build an AffineFESystem from the bilinear form a and the linear form v. `U` and `V` are the test FESpace and the trial FESpace respectively. # Warning For now, `U` and `V` must be defined with the same FESpace(s) ("Petrov-Galerkin" not authorised) """ function AffineFESystem(a, l, U, V) # Preliminary check to ensure same FESpace if U isa MultiFESpace @assert all((_U, _V) -> parent(_U) isa typeof(parent(_V)), zip(U, V)) "U and V must be defined on same FEspace" else @assert parent(U) isa typeof(parent(V)) end # Assemble the system A = assemble_bilinear(a, U, V) b = assemble_linear(l, V) # Retrieve Mesh from `a` op = a(NullOperator(), NullOperator()) if op isa MultiIntegration measures = map(get_measure, (op...,)) domains = map(get_domain, measures) meshes = map(get_mesh, domains) @assert all(x -> x == meshes[1], meshes) "All integrations must be defined on the same mesh" mesh = meshes[1] else measure = get_measure(op) domain = get_domain(measure) mesh = get_mesh(domain) end return AffineFESystem(A, b, U, V, mesh) end _get_arrays(system::AffineFESystem) = (system.A, system.b) _get_fe_spaces(system::AffineFESystem) = (system.U, system.V) """ Solve the AffineFESystem, i.e invert the Ax=b system taking into account the dirichlet conditions. # Dev notes * should we return an FEFunction instead of a Vector? * we need to enable other solvers """ function solve(system::AffineFESystem, t::Number = 0.0; alg = nothing) U, _ = _get_fe_spaces(system) # Create FEFunction to hold the result u = FEFunction(U) # Solve solve!(u, system, t; alg) return u end function solve!( u::SingleFieldFEFunction, system::AffineFESystem, t::Number = 0.0; alg = nothing, ) A, b = _get_arrays(system) U, V = _get_fe_spaces(system) # Create the "Dirichlet" vector d = assemble_dirichlet_vector(U, V, system.mesh, t) # "step" the solution with dirichlet values b0 = b - A * d # Apply homogeneous dirichlet on A and b apply_homogeneous_dirichlet!(A, b0, U, V, system.mesh) # Inverse linear system prob = LinearSolve.LinearProblem(A, b0) sol = LinearSolve.solve(prob, alg) # Update FEFunction set_dof_values!(u, sol.u .+ d) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
28353
""" assemble_bilinear(a::Function, U, V) Assemble the (sparse) Matrix corresponding to the given bilinear form `a` on the trial and test finite element spaces `U` and `V`. For the in-place version, check-out [`assemble_bilinear!`](@ref). # Arguments - `a::Function` : function of two variables (u,v) representing the bilinear form - `U` : trial finite element space (for `u`) - `V` : test finite element space (for `v`) # Examples ```jldoctest julia> mesh = rectangle_mesh(3,3) julia> U = TrialFESpace(FunctionSpace(:Lagrange, 0), mesh) julia> V = TestFESpace(U) julia> dΩ = Measure(CellDomain(mesh), 3) julia> a(u, v) = ∫(u * v)dΩ julia> assemble_bilinear(a, U, V) 4×4 SparseArrays.SparseMatrixCSC{Float64, Int64} with 4 stored entries: 0.25 ⋅ ⋅ ⋅ ⋅ 0.25 ⋅ ⋅ ⋅ ⋅ 0.25 ⋅ ⋅ ⋅ ⋅ 0.25 ``` """ function assemble_bilinear( a::Function, U::Union{TrialFESpace, AbstractMultiFESpace{N, <:Tuple{Vararg{TrialFESpace, N}}}}, V::Union{TestFESpace, AbstractMultiFESpace{N, <:Tuple{Vararg{TestFESpace, N}}}}; T = Float64, ) where {N} # Prepare sparse matrix allocation I = Int[] J = Int[] X = T[] # TODO : could be ComplexF64 or Dual # Compute assemble_bilinear!(I, J, X, a, U, V) nrows = get_ndofs(V) ncols = get_ndofs(U) return sparse(I, J, X, nrows, ncols) end function assemble_bilinear!(I, J, X, a, U, V) return_type_a = a(_null_operator(U), _null_operator(V)) _assemble_bilinear!(I, J, X, a, U, V, return_type_a) return nothing end function _assemble_bilinear!( I::Vector{Int}, J::Vector{Int}, X::Vector, a::Function, U, V, integration::Integration, ) f(u, v) = get_function(get_integrand(a(u, v))) measure = get_measure(integration) assemble_bilinear!(I, J, X, f, measure, U, V) return nothing end function _assemble_bilinear!( I::Vector{Int}, J::Vector{Int}, X::Vector, a::Function, U, V, multiIntegration::MultiIntegration{N}, ) where {N} for i in 1:N ival = Val(i) aᵢ(u, v) = a(u, v)[ival] _assemble_bilinear!(I, J, X, aᵢ, U, V, multiIntegration[ival]) end nothing end """ assemble_bilinear!( I::Vector{Int}, J::Vector{Int}, X::Vector{T}, f::Function, measure::Measure, U::TrialFESpace, V::TestFESpace, ) In-place version of [`assemble_bilinear`](@ref). """ function assemble_bilinear!( I::Vector{Int}, J::Vector{Int}, X::Vector, f::Function, measure::Measure, U::TrialFESpace, V::TestFESpace, ) # Alias quadrature = get_quadrature(measure) domain = get_domain(measure) # Loop over cells for elementInfo in DomainIterator(domain) λu, λv = blockmap_bilinear_shape_functions(U, V, elementInfo) g1 = materialize(f(λu, λv), elementInfo) values = integrate_on_ref_element(g1, elementInfo, quadrature) _append_contribution!(X, I, J, U, V, values, elementInfo, domain) end return nothing end function assemble_bilinear!( I::Vector{Int}, J::Vector{Int}, X::Vector, f::Function, measure::Measure, U::AbstractMultiFESpace{N, <:Tuple{Vararg{TrialFESpace, N}}}, V::AbstractMultiFESpace{N, <:Tuple{Vararg{TestFESpace, N}}}, ) where {N} # Loop over all combinations for (j, _U) in enumerate(U) for (i, _V) in enumerate(V) # Materialize function for `(..., uj, ...), (...,vi,...)` tuple_u = _get_tuple_var(Val(N), j) tuple_v = _get_tuple_var(Val(N), i) _f(uj, vi) = f(tuple_u(uj), tuple_v(vi)) # Skip computation if there is nothing to compute isa(_f(maywrap(_U), maywrap(_V)), NullOperator) && continue # Local indices / values _I = Int[] _J = Int[] n = _count_n_elts(U, V, get_domain(measure)) sizehint!.((_I, _J), n) # Perform assembly on SingleFESpace assemble_bilinear!(_I, _J, X, _f, measure, _U, _V) # Update global indices push!(I, get_mapping(V, i)[_I]...) push!(J, get_mapping(U, j)[_J]...) end end return nothing end """ assemble_linear(l::Function, V::Union{TestFESpace, AbstractMultiTestFESpace}) Assemble the vector corresponding to a linear form `l` on the finite element space `V` For the in-place version, checkout [`assemble_linear!`](@ref). # Arguments - `l::Function` : linear form to assemble, a function of one variable `l(v)` - `V` : test finite element space # Examples ```jldoctest julia> mesh = rectangle_mesh(3,3) julia> U = TrialFESpace(FunctionSpace(:Lagrange, 0), mesh) julia> V = TestFESpace(U) julia> dΩ = Measure(CellDomain(mesh), 3) julia> l(v) = ∫(v)dΩ julia> assemble_linear(l, V) 4-element Vector{Float64}: 0.25 0.25 0.25 0.25 ``` """ function assemble_linear( l::Function, V::Union{TestFESpace, AbstractMultiTestFESpace}; T = Float64, ) b = allocate_dofs(V, T) assemble_linear!(b, l, V) return b end """ assemble_linear!(b::AbstractVector, l::Function, V::Union{TestFESpace, AbstractMultiTestFESpace}) In-place version of [`assemble_linear`](@ref). """ function assemble_linear!( b::AbstractVector, l::Function, V::Union{TestFESpace, AbstractMultiTestFESpace}, ) # apply `l` on `NullOperator` to get the type # of the result of `l` and use it for dispatch # (`Integration` or `MultiIntegration` case). _assemble_linear!(b, l, V, l(_null_operator(V))) return nothing end """ _assemble_linear!(b, l, V, integration::Integration) _assemble_linear!(b, l, V, integration::MultiIntegration{N}) where {N} These functions act as a function barrier in order to: * get the function corresponding to the operand in the linear form * reshape `b` internally to deal with cases when `V` is a `AbstractMultiTestFESpace` * call `__assemble_linear!` to apply dispatch on the type of `measure` of the integration and improve type stability during the assembling loop. ## Dev note: The case `integration::MultiIntegration{N}` is treated by looping over each `Integration` contained in the `MultiIntegration` """ function _assemble_linear!(b, l, V, integration::Integration) f(v) = get_function(get_integrand(l(v))) measure = get_measure(integration) __assemble_linear!(_may_reshape_b(b, V), f, V, measure) return nothing end function _assemble_linear!(b, l, V, integration::MultiIntegration{N}) where {N} ival = Val(N) lᵢ(v) = l(v)[ival] _assemble_linear!(b, lᵢ, V, integration[ival]) if N > 1 # recursive calls _assemble_linear!(b, l, V, MultiIntegration(Base.front(integration.integrations))) end return nothing end """ # Dev notes Two levels of "LazyMapOver" because first we LazyMapOver the Tuple of argument of the linear form, and the for each item of this Tuple we LazyMapOver the shape functions. """ function __assemble_linear!(b, f, V, measure::Measure) # Alias quadrature = get_quadrature(measure) domain = get_domain(measure) for elementInfo in DomainIterator(domain) # Materialize the operation to perform on the current element vₑ = blockmap_shape_functions(V, elementInfo) fᵥ = materialize(f(vₑ), elementInfo) values = integrate_on_ref_element(fᵥ, elementInfo, quadrature) _update_b!(b, V, values, elementInfo, domain) end nothing end _null_operator(::AbstractFESpace) = NullOperator() _null_operator(::AbstractMultiFESpace{N}) where {N} = ntuple(i -> NullOperator(), Val(N)) """ For `AbstractMultiTestFESpace`, it creates a Tuple (of views) of the different "destination" in the vector: one for each FESpace """ _may_reshape_b(b::AbstractVector, V::TestFESpace) = b function _may_reshape_b(b::AbstractVector, V::AbstractMultiTestFESpace) ntuple(i -> view(b, get_mapping(V, i)), Val(get_n_fespace(V))) end """ bilinear case """ function _append_contribution!(X, I, J, U, V, values, elementInfo::CellInfo, domain) icell = cellindex(elementInfo) nU = Val(get_ndofs(U, shape(celltype(elementInfo)))) nV = Val(get_ndofs(V, shape(celltype(elementInfo)))) Udofs = get_dofs(U, icell, nU) # columns correspond to the TrialFunction Vdofs = get_dofs(V, icell, nV) # lines correspond to the TestFunction unwrapValues = _unwrap_cell_integrate(V, values) matrixvalues = _pack_bilinear_cell_contribution(unwrapValues, Udofs, Vdofs) _append_bilinear!(I, J, X, Vdofs, Udofs, matrixvalues) return nothing end function _append_contribution!(X, I, J, U, V, values, elementInfo::FaceInfo, domain) cellinfo_n = get_cellinfo_n(elementInfo) cellinfo_p = get_cellinfo_p(elementInfo) cellindex_n = cellindex(cellinfo_n) cellindex_p = cellindex(cellinfo_p) unwrapValues = _unwrap_face_integrate(U, V, values) nU_n = Val(get_ndofs(U, shape(celltype(cellinfo_n)))) nV_n = Val(get_ndofs(V, shape(celltype(cellinfo_n)))) nU_p = Val(get_ndofs(U, shape(celltype(cellinfo_p)))) nV_p = Val(get_ndofs(V, shape(celltype(cellinfo_p)))) col_dofs_U_n = get_dofs(U, cellindex_n, nU_n) # columns correspond to the TrialFunction on side⁻ row_dofs_V_n = get_dofs(V, cellindex_n, nV_n) # lines correspond to the TestFunction on side⁻ col_dofs_U_p = get_dofs(U, cellindex_p, nU_p) # columns correspond to the TrialFunction on side⁺ row_dofs_V_p = get_dofs(V, cellindex_p, nV_p) # lines correspond to the TestFunction on side⁺ matrixvalues = _pack_bilinear_face_contribution( unwrapValues, col_dofs_U_n, row_dofs_V_n, col_dofs_U_p, row_dofs_V_p, ) for (k, (row, col)) in enumerate( Iterators.product((row_dofs_V_n, row_dofs_V_p), (col_dofs_U_n, col_dofs_U_p)), ) _append_bilinear!(I, J, X, row, col, matrixvalues[k]) end return nothing end function _append_bilinear!(I, J, X, row, col, vals) _rows, _cols = _cartesian_product(row, col) @assert length(_rows) == length(_cols) == length(vals) append!(I, _rows) append!(J, _cols) append!(X, vec(vals)) end _append_bilinear!(I, J, X, row, col, vals::NullOperator) = nothing function _append_bilinear!( I, J, X, row, col, vals::Union{T, SMatrix{M, N, T}}, ) where {M, N, T <: NullOperator} nothing end function _pack_bilinear_cell_contribution( values, col_dofs_U::SVector{NU}, row_dofs_V::SVector{NV}, ) where {NU, NV} return SMatrix{NV, NU}(values[j][i] for i in 1:NV, j in 1:NU) end function _pack_bilinear_face_contribution( values, col_dofs_U_n::SVector{NUn}, row_dofs_V_n::SVector{NVn}, col_dofs_U_p::SVector{NUp}, row_dofs_V_p::SVector{NVp}, ) where {NUn, NVn, NUp, NVp} a11 = SMatrix{NVn, NUn}(values[1][j][i] for i in 1:NVn, j in 1:NUn) a21 = SMatrix{NVp, NUn}(values[2][j][i] for i in 1:NVp, j in 1:NUn) a12 = SMatrix{NVn, NUp}(values[3][j][i] for i in 1:NVn, j in 1:NUp) a22 = SMatrix{NVp, NUp}(values[4][j][i] for i in 1:NVp, j in 1:NUp) return a11, a21, a12, a22 end Base.getindex(::Bcube.LazyOperators.NullOperator, i) = NullOperator() function _unwrap_face_integrate( ::Union{TrialFESpace, AbstractMultiTrialFESpace}, ::Union{TestFESpace, AbstractMultiTestFESpace}, a, ) return _recursive_unwrap(a) end _recursive_unwrap(a::LazyOperators.AbstractMapOver) = map(_recursive_unwrap, unwrap(a)) _recursive_unwrap(a) = unwrap(a) function _update_b!(b, V, values, elementInfo::CellInfo, domain) idofs = get_dofs(V, cellindex(elementInfo)) unwrapValues = _unwrap_cell_integrate(V, values) _update_b!(b, idofs, unwrapValues) end _unwrap_cell_integrate(::TestFESpace, a) = map(unwrap, unwrap(a)) _unwrap_cell_integrate(::AbstractMultiTestFESpace, a) = map(unwrap, unwrap(a)) function _update_b!(b, V, values, elementInfo::FaceInfo, domain) # First, we get the values from the integration on the positive/negative side # Then, if the face has two side, we seek the values from the opposite side unwrapValues = _unwrap_face_integrate(V, values) values_i = map(identity, map(identity, map(first, unwrapValues))) idofs = get_dofs(V, cellindex(get_cellinfo_n(elementInfo))) _update_b!(b, idofs, values_i) if (domain isa InteriorFaceDomain) || (domain isa BoundaryFaceDomain{<:AbstractMesh, <:PeriodicBCType}) values_j = map(identity, map(identity, map(last, unwrapValues))) jdofs = get_dofs(V, cellindex(get_cellinfo_p(elementInfo))) _update_b!(b, jdofs, values_j) end end function _unwrap_face_integrate(::Union{TestFESpace, AbstractMultiTestFESpace}, a) return unwrap(unwrap(unwrap(a))) end function _update_b!( b::Tuple{Vararg{Any, N}}, idofs::Tuple{Vararg{Any, N}}, intvals::Tuple{Vararg{Any, N}}, ) where {N} map(_update_b!, b, idofs, intvals) nothing end function _update_b!(b::AbstractVector, idofs, intvals::Tuple{Vararg{Tuple, N}}) where {N} map(x -> _update_b!(b, idofs, x), intvals) nothing end function _update_b!(b::AbstractVector, dofs, vals) for (i, val) in zip(dofs, vals) b[i] += val end nothing end _update_b!(b::AbstractVector, dofs, vals::NullOperator) = nothing """ _count_n_elts( U::TrialFESpace, V::TestFESpace, domain::CellDomain{M, IND}, ) where {M, IND} function _count_n_elts( U::AbstractMultiFESpace{N, Tu}, V::AbstractMultiFESpace{N, Tv}, domain::AbstractDomain, ) where {N, Tu <: Tuple{Vararg{TrialFESpace}}, Tv <: Tuple{Vararg{TestFESpace}}} function _count_n_elts( U::TrialFESpace, V::TestFESpace, domain::BoundaryFaceDomain{M, BC, L, C}, ) where {M, BC, L, C} Count the (maximum) number of elements in the matrix corresponding to the bilinear assembly of U, V on a domain. # Arguments - `U::TrialFESpace` : TrialFESpace associated to the first argument of the bilinear form. - `V::TestFESpace` : TestFESpace associated to the second argument of the bilinear form. - `domain`::AbstractDomain : domain of integration of the bilinear form. # Warning TO DO: for the moment this function is not really implemented for a BoundaryFaceDomain. This requires to be able to distinguish between the usual TrialsFESpace and MultiplierFESpace. """ function _count_n_elts( U::TrialFESpace, V::TestFESpace, domain::CellDomain{M, IND}, ) where {M, IND} return sum( icell -> length(get_dofs(U, icell)) * length(get_dofs(V, icell)), indices(domain), ) end function _count_n_elts( U::AbstractMultiFESpace{N, Tu}, V::AbstractMultiFESpace{N, Tv}, domain::AbstractDomain, ) where {N, Tu <: Tuple{Vararg{TrialFESpace}}, Tv <: Tuple{Vararg{TestFESpace}}} n = 0 for _U in U for _V in V n += _count_n_elts(_U, _V, domain) end end return n end function _count_n_elts( U::TrialFESpace, V::TestFESpace, domain::BoundaryFaceDomain{M, BC, L, C}, ) where {M, BC, L, C} return 1 end maywrap(x) = LazyWrap(x) maywrap(x::AbstractLazyOperator) = x function _get_tuple_var(::Val{N}, k) where {N} x -> ntuple(i -> i == k ? x : NullOperator(), Val(N)) end _get_tuple_var(λ::Tuple, k) = x -> ntuple(i -> i == k ? x : NullOperator(), length(λ)) #ntuple(i->i==k ? λ[k] : NullOperator(), length(λ)) _get_tuple_var(λ, k) = identity function _get_tuple_var_impl(k, N) exprs = [i == k ? :(diag[$i]) : :(b) for i in 1:N] return :(tuple($(exprs...))) end @generated function _get_tuple_var(x, ::Val{I}, ::Val{N}) where {I, N} _get_tuple_var_impl(I, N) end function _get_all_tuple_var_impl(N) exprs = [_get_tuple_var_impl(i, N) for i in 1:N] return :(tuple($(exprs...))) end """ _diag_tuples(diag::Tuple{Vararg{Any,N}}, b) where N Return `N` tuples of length `N`. For each tuple `tᵢ`, its values are defined so that `tᵢ[k]=diag[k]` if `k==i`, `tᵢ[k]=b` otherwise. The result can be seen as a dense diagonal-like array using tuple. # Example for `N=3`: (diag[1], b, b ), (b, diag[2], b ), (b, b, diag[3])) """ @generated function _diag_tuples(diag::Tuple{Vararg{Any, N}}, b) where {N} _get_all_tuple_var_impl(N) end function _diag_tuples(n::Val{N}, ::Val{i}, a, b) where {N, i} _diag_tuples(ntuple(k -> a, n), b)[i] end """ For N=3 for example: (LazyMapOver((LazyMapOver(V[1]), NullOperator(), NullOperator())), LazyMapOver((NullOperator(), LazyMapOver(V[2]), NullOperator())), LazyMapOver((NullOperator(), NullOperator(), LazyMapOver(V[3])))) """ function _get_multi_tuple_var(V::Tuple{Vararg{Any, N}}) where {N} map(LazyMapOver, _diag_tuples(map(LazyMapOver, V), NullOperator())) end _get_multi_tuple_var(a::LazyMapOver) = _get_multi_tuple_var(unwrap(a)) """ blockmap_shape_functions(fespace::AbstractFESpace, cellinfo::AbstractCellInfo) Return all shape functions `a = LazyMapOver((λ₁, λ₂, …, λₙ))` corresponding to `fespace` in cell `cellinfo`. These shape functions are wrapped by a `LazyMapOver` so that for a function `f` it gives: `f(a) == map(f, a)` """ function blockmap_shape_functions(fespace::AbstractFESpace, cellinfo::AbstractCellInfo) cshape = shape(celltype(cellinfo)) λ = get_cell_shape_functions(fespace, cshape) LazyMapOver(λ) end """ blockmap_shape_functions(multiFESpace::AbstractMultiFESpace, cellinfo::AbstractCellInfo) Return all shape functions corresponding to each `fespace` in `multiFESSpace` for cell `cellinfo` : ```math ((v₁, ∅, ∅, …), (∅, v₂, ∅, …), …, ( …, ∅, ∅, vₙ)) ``` where: * vᵢ = (λᵢ_₁, λᵢ_₂, …, λᵢ_ₘ) are the shapes functions of the i-th fespace in the cell. * ∅ are `NullOperator`s Note that the `LazyMapOver` is used to wrap recursively the result. """ function blockmap_shape_functions( multiFESpace::AbstractMultiFESpace, cellinfo::AbstractCellInfo, ) cshape = shape(celltype(cellinfo)) λ = map(LazyMapOver, get_cell_shape_functions(multiFESpace, cshape)) map(LazyMapOver, _diag_tuples(λ, NullOperator())) end """ # Dev note : Materialize the integrand function on all the different possible Tuples of `v=(v1,0,0,...), (0,v2,0,...), ..., (..., vi, ...)` """ function blockmap_shape_functions(feSpace, faceinfo::FaceInfo) cshape_i = shape(celltype(get_cellinfo_n(faceinfo))) cshape_j = shape(celltype(get_cellinfo_p(faceinfo))) _cellpair_blockmap_shape_functions(feSpace, cshape_i, cshape_j) end function _cellpair_blockmap_shape_functions( multiFESpace::AbstractMultiFESpace, cshape_i::AbstractShape, cshape_j::AbstractShape, ) λi = get_cell_shape_functions(multiFESpace, cshape_i) λj = get_cell_shape_functions(multiFESpace, cshape_j) λij = map(FaceSidePair, map(LazyMapOver, λi), map(LazyMapOver, λj)) map(LazyMapOver, _diag_tuples(λij, NullOperator())) end function _cellpair_blockmap_shape_functions( feSpace::AbstractFESpace, cshape_i::AbstractShape, cshape_j::AbstractShape, ) λi = get_cell_shape_functions(feSpace, cshape_i) λj = get_cell_shape_functions(feSpace, cshape_j) λij = FaceSidePair(LazyMapOver(λi), LazyMapOver(λj)) LazyMapOver((λij,)) end """ # Dev notes: Return `blockU` and `blockV` to be able to compute the local matrix corresponding to the bilinear form : ```math A[i,j] = a(λᵤ[j], λᵥ[i]) ``` where `λᵤ` and `λᵥ` are the shape functions associated with the trial `U` and the test `V` function spaces respectively. In a "map-over" version, it can be written : ```math A = a(blockU, blockV) ``` where `blockU` and `blockV` correspond formally to the lazy-map-over matrices : ```math ∀k, blockU[k,j] = λᵤ[j], blockV[i,k] = λᵥ[i] ``` """ function blockmap_bilinear_shape_functions( U::AbstractFESpace, V::AbstractFESpace, cellinfo::AbstractCellInfo, ) cshape = shape(celltype(cellinfo)) λU = get_shape_functions(U, cshape) λV = get_shape_functions(V, cshape) blockV, blockU = _blockmap_bilinear(λV, λU) blockU, blockV end function blockmap_bilinear_shape_functions( U::AbstractFESpace, V::AbstractFESpace, cellinfo_u::AbstractCellInfo, cellinfo_v::AbstractCellInfo, ) λU = get_shape_functions(U, shape(celltype(cellinfo_u))) λV = get_shape_functions(V, shape(celltype(cellinfo_v))) blockV, blockU = _blockmap_bilinear(λV, λU) blockU, blockV end function blockmap_bilinear_shape_functions( U::AbstractFESpace, V::AbstractFESpace, faceinfo::FaceInfo, ) cellinfo_n = get_cellinfo_n(faceinfo) cellinfo_p = get_cellinfo_p(faceinfo) U_nn, V_nn = blockmap_bilinear_shape_functions(U, V, cellinfo_n, cellinfo_n) U_pn, V_pn = blockmap_bilinear_shape_functions(U, V, cellinfo_n, cellinfo_p) U_np, V_np = blockmap_bilinear_shape_functions(U, V, cellinfo_p, cellinfo_n) U_pp, V_pp = blockmap_bilinear_shape_functions(U, V, cellinfo_p, cellinfo_p) return ( LazyWrap(BilinearTrialFaceSidePair(U_nn, U_pn, U_np, U_pp)), LazyWrap(BilinearTestFaceSidePair(V_nn, V_pn, V_np, V_pp)), ) end """ From tuples ``a=(a_1, a_2, …, a_i, …, a_m)`` and ``b=(b_1, b_2, …, b_j, …, b_n)``, it builds `A` and `B` which correspond formally to the following two matrices : ```math A \\equiv \\begin{pmatrix} a_1 & a_1 & ⋯ & a_1\\\\ a_2 & a_2 & ⋯ & a_2\\\\ ⋮ & ⋮ & ⋮ & ⋮ \\\\ a_m & a_m & ⋯ & a_m \\end{pmatrix} \\qquad and \\qquad B \\equiv \\begin{pmatrix} b_1 & b_2 & ⋯ & b_n\\\\ b_1 & b_2 & ⋯ & b_n\\\\ ⋮ & ⋮ & ⋮ & ⋮ \\\\ b_1 & b_2 & ⋯ & b_n \\end{pmatrix} ``` `A` and `B` are wrapped in `LazyMapOver` structures so that all operations on them are done elementwise by default (in other words, it can be considered that the operations are automatically broadcasted). # Dev note : Both `A` and `B` are stored as a tuple of tuples, wrapped by `LazyMapOver`, where inner tuples correspond to each columns of a matrix. This hierarchical structure reduces both inference and compile times by avoiding the use of large tuples. """ function _blockmap_bilinear(a::NTuple{N1}, b::NTuple{N2}) where {N1, N2} _a = ntuple(j -> begin LazyMapOver(ntuple(i -> a[i], Val(N1))) end, Val(N2)) _b = ntuple(j -> begin LazyMapOver(ntuple(i -> b[j], Val(N1))) end, Val(N2)) LazyMapOver(_a), LazyMapOver(_b) end function _cartesian_product(a::NTuple{N1}, b::NTuple{N2}) where {N1, N2} _a, _b = _cartesian_product(SVector{N1}(a), SVector{N2}(b)) Tuple(_a), Tuple(_b) end function _cartesian_product(a::SVector{N1}, b::SVector{N2}) where {N1, N2} # Return `_a` and `__b` defined as : # _a = SVector{N1 * N2}(a[i] for i in 1:N1, j in 1:N2) # __b = SVector{N1 * N2}(b[j] for i in 1:N1, j in 1:N2) _a = repeat(a, Val(N2)) _b = repeat(b, Val(N1)) __b = vec(permutedims(reshape(_b, Size(N2, N1)))) _a, __b end Base.repeat(a::SVector, ::Val{N}) where {N} = reduce(vcat, ntuple(i -> a, Val(N))) """ compute(integration::Integration) Compute an integral, independently from a FEM/DG framework (i.e without FESpace) Return a `SparseVector`. The indices of the domain elements are used to store the result of the integration in this sparse vector. # Example Compute volume of each cell and each face. ```julia mesh = rectangle_mesh(2, 3) dΩ = Measure(CellDomain(mesh), 1) dΓ = Measure(BoundaryFaceDomain(mesh), 1) f = PhysicalFunction(x -> 1) @show Bcube.compute(∫(f)dΩ) @show Bcube.compute(∫(side⁻(f))dΓ) ``` """ function compute(integration::Integration) measure = get_measure(integration) domain = get_domain(measure) f = get_function(get_integrand(integration)) quadrature = get_quadrature(measure) values = map(DomainIterator(domain)) do elementInfo _f = materialize(f, elementInfo) integrate_on_ref_element(_f, elementInfo, quadrature) end return SparseVector(_domain_to_mesh_nelts(domain), collect(indices(domain)), values) end _domain_to_mesh_nelts(domain::AbstractCellDomain) = ncells(get_mesh(domain)) _domain_to_mesh_nelts(domain::AbstractFaceDomain) = nfaces(get_mesh(domain)) """ AbstractFaceSidePair{A} <: AbstractLazyWrap{A} # Interface: * `side_n(a::AbstractFaceSidePair)` * `side_p(a::AbstractFaceSidePair)` """ abstract type AbstractFaceSidePair{A} <: AbstractLazyWrap{A} end LazyOperators.get_args(a::AbstractFaceSidePair) = a.data LazyOperators.pretty_name(::AbstractFaceSidePair) = "AbstractFaceSidePair" LazyOperators.pretty_name_style(::AbstractFaceSidePair) = Dict(:color => :yellow) struct FaceSidePair{A} <: AbstractFaceSidePair{A} data::A end FaceSidePair(a, b) = FaceSidePair((a, b)) LazyOperators.pretty_name(::FaceSidePair) = "FaceSidePair" side_n(a::FaceSidePair) = Side⁻(LazyMapOver((a.data[1], NullOperator()))) side_p(a::FaceSidePair) = Side⁺(LazyMapOver((NullOperator(), a.data[2]))) function LazyOperators.materialize(a::FaceSidePair, cPoint::CellPoint) _a = (materialize(a.data[1], cPoint), materialize(a.data[2], cPoint)) return MapOver(_a) end function LazyOperators.materialize(a::FaceSidePair, side::Side⁻{Nothing, <:Tuple{FaceInfo}}) return FaceSidePair(materialize(a.data[1], side), NullOperator()) end function LazyOperators.materialize(a::FaceSidePair, side::Side⁺{Nothing, <:Tuple{FaceInfo}}) return FaceSidePair(NullOperator(), materialize(a.data[2], side)) end function LazyOperators.materialize( a::FaceSidePair, side::Side⁻{Nothing, <:Tuple{FacePoint}}, ) return MapOver(materialize(a.data[1], side), NullOperator()) end function LazyOperators.materialize( a::FaceSidePair, side::Side⁺{Nothing, <:Tuple{FacePoint}}, ) return MapOver(NullOperator(), materialize(a.data[2], side)) end function LazyOperators.materialize( a::Gradient{O, <:Tuple{AbstractFaceSidePair}}, point::AbstractSide{Nothing, <:Tuple{FacePoint}}, ) where {O} _args, = get_operator(point)(get_args(a)) __args, = get_args(_args) return materialize(∇(__args), point) end """ AbstractBilinearFaceSidePair{A} <: AbstractLazyWrap{A} # Interface: * get_args_bilinear(a::AbstractBilinearFaceSidePair) """ abstract type AbstractBilinearFaceSidePair{A} <: AbstractLazyWrap{A} end LazyOperators.pretty_name_style(::AbstractBilinearFaceSidePair) = Dict(:color => :yellow) get_args(a::AbstractBilinearFaceSidePair) = a.data get_basetype(a::AbstractBilinearFaceSidePair) = get_basetype(typeof(a)) get_basetype(::Type{<:AbstractBilinearFaceSidePair}) = error("To be defined") function LazyOperators.materialize( a::AbstractBilinearFaceSidePair, point::AbstractSide{Nothing, <:Tuple{FacePoint}}, ) args = tuplemap(x -> materialize(x, point), get_args(a)) return MapOver(args) end function LazyOperators.materialize( a::Gradient{Nothing, <:Tuple{AbstractBilinearFaceSidePair}}, point::AbstractSide{Nothing, <:Tuple{FacePoint}}, ) op_side = get_operator(point) args, = get_args(op_side(get_args(a))...) return materialize(∇(args), point) end function LazyOperators.materialize( a::AbstractBilinearFaceSidePair, side::AbstractSide{Nothing, <:Tuple{FaceInfo}}, ) T = get_basetype(a) return T(tuplemap(x -> materialize(x, side), get_args(a))) end struct BilinearTrialFaceSidePair{A} <: AbstractBilinearFaceSidePair{A} data::A end BilinearTrialFaceSidePair(a...) = BilinearTrialFaceSidePair(a) LazyOperators.pretty_name(::BilinearTrialFaceSidePair) = "BilinearTrialFaceSidePair" get_basetype(::Type{<:BilinearTrialFaceSidePair}) = BilinearTrialFaceSidePair function side_n(a::BilinearTrialFaceSidePair) Side⁻(LazyMapOver((a.data[1], a.data[2], NullOperator(), NullOperator()))) end function side_p(a::BilinearTrialFaceSidePair) Side⁺(LazyMapOver((NullOperator(), NullOperator(), a.data[3], a.data[4]))) end struct BilinearTestFaceSidePair{A} <: AbstractBilinearFaceSidePair{A} data::A end BilinearTestFaceSidePair(a...) = BilinearTestFaceSidePair(a) LazyOperators.pretty_name(::BilinearTestFaceSidePair) = "BilinearTestFaceSidePair" get_basetype(::Type{<:BilinearTestFaceSidePair}) = BilinearTestFaceSidePair function side_n(a::BilinearTestFaceSidePair) Side⁻(LazyMapOver((a.data[1], NullOperator(), a.data[3], NullOperator()))) end function side_p(a::BilinearTestFaceSidePair) Side⁺(LazyMapOver((NullOperator(), a.data[2], NullOperator(), a.data[4]))) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
8064
""" Assemble a vector of zeros dofs except on boundary dofs where they take the Dirichlet values. """ function assemble_dirichlet_vector( U, V, mesh::AbstractMesh, t::Number = 0.0; dt_derivative_order::Int = 0, ) d = allocate_dofs(U) apply_dirichlet_to_vector!(d, U, V, mesh, t; dt_derivative_order) return d end """ Apply homogeneous Dirichlet condition on vector `b` Dirichlet values are applied on dofs lying on a Dirichlet boundary. """ function apply_homogeneous_dirichlet_to_vector!( b::AbstractVector{<:Number}, U, V, mesh::AbstractMesh, ) # Define callback to apply on `b` callback!(array, iglob, _, _) = array[iglob] = 0.0 _apply_dirichlet!((b,), (callback!,), U, V, mesh) end """ Apply a homogeneous "dirichlet" condition on the input matrix. The rows and columns corresponding to each Dirichlet dof are canceled (with a 1 on the diag term). If you don't want the cols to be canceled, use `apply_dirichlet_to_matrix!`. """ function apply_homogeneous_dirichlet_to_matrix!( matrix::AbstractMatrix, U, V, mesh::AbstractMesh; diag_value::Number = 1.0, ) apply_homogeneous_dirichlet_to_matrix!( (matrix,), U, V, mesh; diag_values = (diag_value,), ) end """ Same as above, but with a Tuple of matrix """ function apply_homogeneous_dirichlet_to_matrix!( matrices::Tuple{Vararg{AbstractMatrix, N}}, U, V, mesh::AbstractMesh; diag_values::Tuple{Vararg{Number, N}} = ntuple(i -> 1.0, N), ) where {N} callbacks = ntuple( i -> callback!(array, iglob, _, _) = begin array[iglob, :] .= 0.0 array[:, iglob] .= 0.0 array[iglob, iglob] = diag_values[i] end, N, ) _apply_dirichlet!(matrices, callbacks, U, V, mesh) end """ Apply homogeneous Dirichlet condition on `A` and `b` assuming the linear system Ax=b. Dirichlet values are applied on dofs lying on a Dirichlet boundary. """ function apply_homogeneous_dirichlet!( A::AbstractMatrix{<:Number}, b::AbstractVector{<:Number}, U, V, mesh::AbstractMesh, ) # Define callback to apply on `A` callback_A!(array, iglob, _, _) = begin array[iglob, :] .= 0.0 array[:, iglob] .= 0.0 array[iglob, iglob] = 1.0 end # Define callback to apply on `b` callback_b!(array, iglob, _, _) = array[iglob] = 0.0 _apply_dirichlet!((A, b), (callback_A!, callback_b!), U, V, mesh) end """ Apply Dirichlet condition on vector `b`. Dirichlet values are applied on dofs lying on a Dirichlet boundary. TODO : add `dt_derivative_order` """ function apply_dirichlet_to_vector!( b::AbstractVector{<:Number}, U, V, mesh::AbstractMesh, t::Number = 0.0; dt_derivative_order::Int = 0, ) @assert dt_derivative_order == 0 "`dt_derivative_order` > 0 not implemented yet" # sizeU = get_size(U) # Define callback to apply on `b` callback!(array, iglob, icomp, values) = begin # if (values isa Number && sizeU > 1) # # here we should consider that we have a condition of the type u ⋅ n # error("Dirichlet condition with scalar product with normal not supported yet") # end array[iglob] = values[icomp] end _apply_dirichlet!((b,), (callback!,), U, V, mesh, t) end """ Apply a "dirichlet" condition on the input matrix. The columns corresponding to each Dirichlet dof are NOT canceled. If you want them to be canceled, use `apply_homogeneous_dirichlet_to_matrix!`. """ function apply_dirichlet_to_matrix!( matrix::AbstractMatrix, U, V, mesh::AbstractMesh; diag_value::Number = 1.0, ) apply_dirichlet_to_matrix!((matrix,), U, V, mesh; diag_values = (diag_value,)) end """ Same as above, but with a Tuple of matrix """ function apply_dirichlet_to_matrix!( matrices::Tuple{Vararg{AbstractMatrix, N}}, U, V, mesh::AbstractMesh; diag_values::Tuple{Vararg{Number, N}} = ntuple(i -> 1.0, N), ) where {N} callbacks = ntuple( i -> callback!(array, iglob, _, _) = begin array[iglob, :] .= 0.0 array[iglob, iglob] = diag_values[i] end, N, ) _apply_dirichlet!(matrices, callbacks, U, V, mesh) end function _apply_dirichlet!( arrays::Tuple{Vararg{AbstractVecOrMat, N}}, callbacks::NTuple{N, Function}, U::TrialFESpace{S, FE}, V::TestFESpace{S, FE}, mesh::AbstractMesh, t::Number = 0.0, ) where {N, S, FE} m = collect(1:get_ndofs(U)) _apply_dirichlet!(arrays, callbacks, m, U, V, mesh, t) end """ Version for MultiFESpace """ function _apply_dirichlet!( arrays::Tuple{Vararg{AbstractVecOrMat, P}}, callbacks::NTuple{P, Function}, U::AbstractMultiFESpace{N, Tu}, V::AbstractMultiFESpace{N, Tv}, mesh::AbstractMesh, t::Number = 0.0, ) where {P, N, Tu <: Tuple{Vararg{TrialFESpace}}, Tv <: Tuple{Vararg{TestFESpace}}} for (i, (_U, _V)) in enumerate(zip(U, V)) _apply_dirichlet!(arrays, callbacks, get_mapping(U, i), _U, _V, mesh, t) end end """ `m` is the dof mapping (if SingleFESpace, m = Id; otherwise m = get_mapping(...)) # Warning We assume same FESpace for U and V # Dev notes * we could passe a view of the arrays instead of passing the mapping """ function _apply_dirichlet!( arrays::Tuple{Vararg{AbstractVecOrMat, N}}, callbacks::NTuple{N, Function}, m::Vector{Int}, U::TrialFESpace{S, FE}, V::TestFESpace{S, FE}, mesh::AbstractMesh, t::Number, ) where {S, FE, N} # Alias _mesh = parent(mesh) # fs_U = get_function_space(U) fs_V = get_function_space(V) dhl_V = _get_dhl(V) # Loop over the boundaries for bndTag in get_dirichlet_boundary_tags(U) # Function to apply, giving the Dirichlet value(s) on each node f = get_dirichlet_values(U, bndTag) f_t = Base.Fix2(f, t) # Loop over the face of the boundary for kface in boundary_faces(_mesh, bndTag) _apply_dirichlet_on_face!(arrays, callbacks, kface, _mesh, fs_V, dhl_V, m, f_t) end end end """ Apply dirichlet condition on `kface`. `m` is the dof mapping to obtain global dof id (in case of MultiFESpace) `f_t` is the Dirichlet function evaluated in `t`: f_t = x -> f(x,t) `callbacks` is the Tuple of functions of (array, idof_glo, icomp, values) that must be applied to each array of `arrays` # Dev notes * we could passe a view of the arrays instead of passing the mapping """ function _apply_dirichlet_on_face!( arrays::Tuple{Vararg{AbstractVecOrMat, N}}, callbacks::NTuple{N, Function}, kface::Int, mesh::Mesh, fs_V::AbstractFunctionSpace, dhl_V::DofHandler, m::Vector{Int}, f_t::Function, ) where {N} # Alias sizeV = get_ncomponents(dhl_V) c2n = connectivities_indices(mesh, :c2n) f2n = connectivities_indices(mesh, :f2n) f2c = connectivities_indices(mesh, :f2c) cellTypes = cells(mesh) # Interior cell icell = f2c[kface][1] ctype = cellTypes[icell] _c2n = c2n[icell] cnodes = get_nodes(mesh, _c2n) side = cell_side(ctype, c2n[icell], f2n[kface]) cshape = shape(ctype) ξcell = get_coords(fs_V, cshape) # ref coordinates of the FunctionSpace in the cell F = mapping(ctype, cnodes) # local indices of dofs lying on the face (assuming scalar FE) idofs_loc = idof_by_face_with_bounds(fs_V, shape(ctype))[side] # Loop over the dofs concerned by the Dirichlet condition for idof_loc in idofs_loc ξ = ξcell[idof_loc] values = f_t(F(ξ)) # dirichlet value(s) # Loop over components for icomp in 1:sizeV # Absolute number of the dof for this component idof_glo = m[get_dof(dhl_V, icell, icomp, idof_loc)] # Apply condition on each array according to the corresponding callback for (array, callback!) in zip(arrays, callbacks) callback!(array, idof_glo, icomp, values) end end end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
19536
""" AbstractCellFunction{DS,S} Abstract type to represent a function defined in specific domain `DS`, which could be a `ReferenceDomain` or a `PhysicalDomain`. `S` is the size of the codomain (i.e `S=length(f(x))`) where `f` is the `AbstractCellFunction`. # Subtypes should implement : * `get_function(f::AbstractCellFunction)` """ abstract type AbstractCellFunction{DS, S} <: AbstractLazy end """ DomainStyle(f::AbstractCellFunction) """ DomainStyle(f::AbstractCellFunction{DS}) where {DS} = DS() get_size(::AbstractCellFunction{DS, S}) where {DS, S} = S """ get_function(f::AbstractCellFunction) """ function get_function(f::AbstractCellFunction) error("`get_function` is not defined for $(typeof(f))") end """ (f::AbstractCellFunction)(x) Make `AbstractCellFunction` callable. Return `f(x)` by calling `evaluate(f, x)`. """ (f::AbstractCellFunction)(x) = evaluate(f, x) """ evaluate(f::AbstractCellFunction, x) Return the value `f(x)` by mapping `x` to the domain of `f` if necessary. """ evaluate(f::AbstractCellFunction, x) = evaluate(f, x, same_domain(f, x)) function evaluate(f::AbstractCellFunction, x, samedomain::Val{false}) evaluate(f, change_domain(x, DomainStyle(f))) end function evaluate(f::AbstractCellFunction, x, samedomain::Val{true}) get_function(f)(x) end function evaluate(f::AbstractCellFunction, x::CellPoint, samedomain::Val{true}) evaluate_at_cellpoint(get_function(f), x) end """ When a CellFunction is directly applied on a `FacePoint`, (i.e without the use of the `side_n` or `side_p` operators), it means that the side of the face does matter (for instance for a PhysicalFunction). Hence we just convert the FacePoint into a CellPoint (of the negative side of the face) before evaluating it """ evaluate(f::AbstractCellFunction, x::FacePoint) = evaluate(f, side_n(x)) function LazyOperators.pretty_name(a::AbstractCellFunction) "CellFunction{" * pretty_name(DomainStyle(a)) * "," * pretty_name(get_function(a)) * "}" end LazyOperators.pretty_name_style(::AbstractCellFunction) = Dict(:color => :light_green) """ Implement function `materialize` of the `AbstractLazy` interface. TODO : define default behavior when things are stabilized : `LazyOperators.materialize(f::AbstractCellFunction, x) = f` """ LazyOperators.materialize(f::AbstractCellFunction, x::CellInfo) = f LazyOperators.materialize(f::AbstractCellFunction, x::CellPoint) = f(x) """ abstract type AbstractShapeFunction{DS,S,FS} <: AbstractCellFunction{DS,S} end Abstract type to represent a shape function defined in specific domain `DS`, which could be a `ReferenceDomain` or a `PhysicalDomain`. `S` is the size of the codomain (i.e `S=length(λ(x))`) and `FS` is the type of `FunctionSpace`. # Interface Subtypes should implement `AbstractCellFunction`: * `get_function(f::AbstractShapeFunction)` and its own specitic interface: [empty] """ abstract type AbstractShapeFunction{DS, S, FS} <: AbstractCellFunction{DS, S} end get_function_space(::AbstractShapeFunction{DS, S, FS}) where {DS, S, FS} = FS() """ ShapeFunction{DS,S,F<:Function} <: AbstractShapeFunction{DS,S} Subtype of [`AbstractShapeFunction`](@ref) used to wrap a function defined on a domain of style` `DS` in the cell """ struct ShapeFunction{DS, S, FS, F <: Function} <: AbstractShapeFunction{DS, S, FS} f::F end """ ShapeFunction(f::Function, domainstyle::DomainStyle, ::Val{S}) where S """ function ShapeFunction(f::Function, ds::DomainStyle, ::Val{S}, fs::FunctionSpace) where {S} ShapeFunction{typeof(ds), S, typeof(fs), typeof(f)}(f) end get_function(f::ShapeFunction) = f.f function LazyOperators.pretty_name(a::ShapeFunction) "ShapeFunction{" * pretty_name(DomainStyle(a)) * "," * string(get_size(a)) * "," * pretty_name(get_function(a)) * "}" end LazyOperators.pretty_name_style(a::ShapeFunction) = Dict(:color => :light_green) """ abstract type AbstractMultiShapeFunction{N,DS} end Abstract type to represent a "set" of `ShapeFunction`. `N` is the number of `ShapeFunction` contained in this `AbstractMultiShapeFunction`. Note that all shape functions must have the same domain style `DS`. """ abstract type AbstractMultiShapeFunction{N, DS} end struct MultiShapeFunction{N, DS, F <: Tuple{Vararg{AbstractShapeFunction, N}}} <: AbstractMultiShapeFunction{N, DS} shapeFunctions::F end """ MultiShapeFunction(f::NTuple{N,AbstractShapeFunction{DS}}) where {N,DS} """ function MultiShapeFunction( shapeFunctions::Tuple{Vararg{AbstractShapeFunction{DS}, N}}, ) where {N, DS} MultiShapeFunction{N, DS, typeof(shapeFunctions)}(shapeFunctions) end get_shape_functions(f::MultiShapeFunction) = f.shapeFunctions abstract type AbstractCellShapeFunctions{DS, S, FS, CS} <: AbstractShapeFunction{DS, S, FS} end get_cell_shape(::AbstractCellShapeFunctions{DS, S, FS, CS}) where {DS, S, FS, CS} = CS() """ CellShapeFunctions{DS,S,FS,CS} <: AbstractCellShapeFunctions{DS,S,FS,CS} Subtype of [`AbstractCellShapeFunctions`](@ref) used to wrap a shape functions defined on a domain of style `DS` in the cell. The function `f` (of type `F`) must return all shape functions `λᵢ` associated to the function space of type `FS` defined on cell shape `CS`, so that: - λᵢ(x) = f(x)[i] and: - f(x) = (λ₁(x), …, λ₁(x), …, λₙ(x)) """ struct CellShapeFunctions{DS, S, FS, CS} <: AbstractCellShapeFunctions{DS, S, FS, CS} end """ CellShapeFunctions(domainstyle::DomainStyle, ::Val{S}, fs::FunctionSpace, shape::Shape) where S """ function CellShapeFunctions( ds::DomainStyle, ::Val{S}, fs::FunctionSpace, shape::AbstractShape, ) where {S} CellShapeFunctions{typeof(ds), S, typeof(fs), typeof(shape)}() end function get_function(f::CellShapeFunctions) valS = Val(get_size(f)) λ = _reshape_cell_shape_functions ∘ shape_functions(get_function_space(f), valS, get_cell_shape(f)) end @generated function _reshape_cell_shape_functions(a::SMatrix{Ndof, Ndim}) where {Ndof, Ndim} _exprs = [[:(a[$i, $j]) for j in 1:Ndim] for i in 1:Ndof] exprs = [:(SA[$(_expr...)]) for _expr in _exprs] return :(tuple($(exprs...))) end _reshape_cell_shape_functions(a::SVector) = Tuple(a) function LazyOperators.pretty_name(a::CellShapeFunctions) "CellShapeFunctions{" * pretty_name(DomainStyle(a)) * "," * string(get_size(a)) * "," * pretty_name(get_function(a)) * "}" end LazyOperators.pretty_name_style(a::CellShapeFunctions) = Dict(:color => :light_green) """ CellFunction{DS,S,F<:Function} <: AbstractCellFunction{DS,S} Subtype of [`AbstractCellFunction`](@ref) used to wrap a function defined on a domain of style` `DS` in the cell """ struct CellFunction{DS, S, F <: Function} <: AbstractCellFunction{DS, S} f::F end """ CellFunction(f::Function, domainstyle::DomainStyle, ::Val{S}) where {S} `S` is the codomain size of `f`. """ function CellFunction(f::F, ds::DomainStyle, ::Val{S}) where {F <: Function, S} CellFunction{typeof(ds), S, typeof(f)}(f) end get_function(f::CellFunction) = f.f """ PhysicalFunction(f::Function, [size::Union{Integer, Tuple{Integer, Vararg{Integer}}} = 1]) PhysicalFunction(f::Function, ::Val{size}) where {size} Return a [`CellFunction`](@ref) defined on a `PhysicalDomain`. `size` is the size of the codomain of `f`. ## Note: Using a `Val` to prescribe the size a of `PhysicalFunction` is recommended to improve type-stability and performance. """ function PhysicalFunction( f::Function, size::Union{Integer, Tuple{Integer, Vararg{Integer}}} = 1, ) CellFunction(f, PhysicalDomain(), Val(size)) end function PhysicalFunction(f::Function, s::Val{size}) where {size} CellFunction(f, PhysicalDomain(), s) end """ ReferenceFunction(f::Function, [size::Union{Integer, Tuple{Integer, Vararg{Integer}}} = 1]) ReferenceFunction(f::Function, ::Val{size}) where {size} Return a [`CellFunction`](@ref) defined on a `ReferenceDomain`. `size` is the size of the codomain of `f`. ## Note: Using a `Val` to prescribe the size a of `ReferenceFunction` is recommended to improve type-stability and performance. """ function ReferenceFunction( f::Function, size::Union{Integer, Tuple{Integer, Vararg{Integer}}} = 1, ) CellFunction(f, ReferenceDomain(), Val(size)) end function ReferenceFunction(f::Function, s::Val{size}) where {size} CellFunction(f, ReferenceDomain(), s) end ## TEMPORARY : should be moved in files where each function space is defined ! DomainStyle(fs::FunctionSpace{<:Lagrange}) = ReferenceDomain() DomainStyle(fs::FunctionSpace{<:Taylor}) = ReferenceDomain() #specific rules: LazyOperators.materialize(a::LazyMapOver{<:AbstractCellShapeFunctions}, x::CellInfo) = a function LazyOperators.materialize( a::LazyMapOver{<:AbstractCellShapeFunctions}, x::CellPoint, ) f = get_args(a) MapOver(f(x)) end function LazyOperators.lazy_map_over( f::Function, a::LazyMapOver{<:AbstractCellShapeFunctions}, ) f(get_args(a)) end function LazyOperators.materialize(a::LazyMapOver, x::CellPoint) MapOver(LazyOperators.lazy_map_over(Base.Fix2(materialize, x), a)) end #LazyOperators.materialize(a::LazyMapOver{<:CellShapeFunctions}, x::CellPoint) = a """ Represent the side a of face between two cells. @ghislainb : to be moved to `domain.jl` ? """ side_p(t::Tuple) = map(side_p, t) side_n(t::Tuple) = map(side_n, t) side_p(fInfo::FaceInfo) = get_cellinfo_p(fInfo) side_n(fInfo::FaceInfo) = get_cellinfo_n(fInfo) const side⁺ = side_p const side⁻ = side_n jump(a) = side⁻(a) - side⁺(a) jump(a::Tuple) = map(jump, a) jump(a, n) = side⁺(a) * side⁺(n) + side⁻(a) * side⁻(n) abstract type AbstractSide{O, A <: Tuple} <: AbstractLazyOperator{O, A} end function LazyOperators.get_operator(a::AbstractSide) error("`get_operator` is not defined for $(typeof(a))") end LazyOperators.get_args(side::AbstractSide) = side.args struct Side⁺{O, A} <: AbstractSide{O, A} args::A end Side⁺(args...) = Side⁺{Nothing, typeof(args)}(args) LazyOperators.get_operator(::Side⁺) = side_p struct Side⁻{O, A} <: AbstractSide{O, A} args::A end Side⁻(args...) = Side⁻{Nothing, typeof(args)}(args) LazyOperators.get_operator(::Side⁻) = side_n function LazyOperators.materialize(side::AbstractSide, fInfo::FaceInfo) op_side = get_operator(side) return op_side(materialize_args(get_args(side), wrap_side(side, fInfo))...) end # function LazyOperators.materialize(side::AbstractSide, fInfo::FaceInfo) # op_side = get_operator(side) # return op_side(materialize_args(get_args(side), wrap_side(side, fInfo))...) # end wrap_side(::Side⁻, a::Side⁺) = error("invalid : cannot `Side⁺` with `Side⁻`") wrap_side(::Side⁺, a::Side⁻) = error("invalid : cannot `Side⁻` with `Side⁺`") wrap_side(::Side⁺, a) = Side⁺(a) wrap_side(::Side⁻, a) = Side⁻(a) wrap_side(::Side⁻, a::Side⁻) = a wrap_side(::Side⁺, a::Side⁺) = a function LazyOperators.materialize(a::AbstractCellFunction, sidefInfo::AbstractSide) op_side = get_operator(sidefInfo) return materialize(a, op_side(get_args(sidefInfo)...)) end function materialize(a::LazyMapOver, x::AbstractSide{Nothing, <:Tuple{FaceInfo}}) LazyMapOver(LazyOperators.lazy_map_over(Base.Fix2(materialize, x), a)) end function materialize(a::LazyMapOver, x::AbstractSide{Nothing, <:Tuple{FacePoint}}) MapOver(LazyOperators.lazy_map_over(Base.Fix2(materialize, x), a)) end materialize(::NullOperator, ::AbstractSide) = NullOperator() function LazyOperators.materialize(side::AbstractSide, x) a = materialize_args(get_args(side), wrap_side(side, x)) return LazyOperators.may_unwrap_tuple(a) end side_p(a::AbstractLazy) = Side⁺(a) side_n(a::AbstractLazy) = Side⁻(a) side_p(a::Side⁺) = a side_p(a::Side⁻) = error("invalid : cannot apply `side_p` on `Side⁻`") side_n(a::Side⁺) = error("invalid : cannot apply `side_n` on `Side⁺`") side_n(a::Side⁻) = a side_p(::NullOperator) = NullOperator() side_n(::NullOperator) = NullOperator() side_p(n) = Side⁺(n) side_n(n) = Side⁻(n) """ Represent the face normal of a face """ struct FaceNormal <: AbstractLazy end """ At the `CellInfo` level, the `FaceNormal` doesn't really have a materialization and stays lazy @ghislainb : I wonder if there is a way to avoid declaring this function ? """ LazyOperators.materialize(n::FaceNormal, ::CellInfo) = n function LazyOperators.materialize( n::FaceNormal, ::AbstractSide{Nothing, <:Tuple{<:FaceInfo}}, ) n end function LazyOperators.materialize( ::FaceNormal, sideFacePoint::Side⁺{Nothing, <:Tuple{<:FacePoint}}, ) fPoint, = get_args(sideFacePoint) fInfo = get_faceinfo(fPoint) ξface = get_coords(fPoint) cInfo = get_cellinfo_p(fInfo) kside = get_cell_side_p(fInfo) cnodes = nodes(cInfo) ctype = celltype(cInfo) return normal(ctype, cnodes, kside, ξface) end function LazyOperators.materialize( ::FaceNormal, sideFacePoint::Side⁻{Nothing, <:Tuple{<:FacePoint}}, ) fPoint, = get_args(sideFacePoint) fInfo = get_faceinfo(fPoint) ξface = get_coords(fPoint) cInfo = get_cellinfo_n(fInfo) kside = get_cell_side_n(fInfo) cnodes = nodes(cInfo) ctype = celltype(cInfo) return normal(ctype, cnodes, kside, ξface) end """ Hypersurface "face" operator that rotates around the face-axis to virtually bring back the two adjacent cells in the same plane. """ struct CoplanarRotation <: AbstractLazy end function LazyOperators.materialize( R::CoplanarRotation, ::AbstractSide{Nothing, <:Tuple{<:FaceInfo}}, ) R end function _unpack_face_point(sideFacePoint) fPoint, = get_args(sideFacePoint) fInfo = get_faceinfo(fPoint) cInfo_n = get_cellinfo_n(fInfo) cnodes_n = nodes(cInfo_n) ctype_n = celltype(cInfo_n) ξ_n = get_coords(side_n(fPoint)) cInfo_p = get_cellinfo_p(fInfo) cnodes_p = nodes(cInfo_p) ctype_p = celltype(cInfo_p) ξ_p = get_coords(side_p(fPoint)) return cnodes_n, cnodes_p, ctype_n, ctype_p, ξ_n, ξ_p end function LazyOperators.materialize( ::CoplanarRotation, sideFacePoint::Side⁻{Nothing, <:Tuple{<:FacePoint}}, ) cnodes_n, cnodes_p, ctype_n, ctype_p, ξ_n, ξ_p = _unpack_face_point(sideFacePoint) # We choose to use `cell_normal` instead of `normal`, # but we could do the same with the latter. ν_n = cell_normal(ctype_n, cnodes_n, ξ_n) ν_p = cell_normal(ctype_p, cnodes_p, ξ_p) return _coplanar_rotation(ν_n, ν_p) end function LazyOperators.materialize( cr::CoplanarRotation, sideFacePoint::Side⁺{Nothing, <:Tuple{<:FacePoint}}, ) fPoint, = get_args(sideFacePoint) materialize(cr, Side⁻(opposite_side(fPoint))) end function _coplanar_rotation(ν_n::SVector{2}, ν_p::SVector{2}) _cos = ν_p ⋅ ν_n _sin = ν_p[1] * ν_n[2] - ν_p[2] * ν_n[1] # 2D-vector cross-product R = SA[_cos (-_sin); _sin _cos] return R end function _coplanar_rotation(ν_n::SVector{3}, ν_p::SVector{3}) _cos = ν_p ⋅ ν_n _sin = cross(ν_p, ν_n) # this is not really a 'sinus', it is (sinus x u) # u = _sin / ||_sin|| # So we must ensure that `_sin` is not 0, otherwise we return the null vector norm_sin = norm(_sin) u = norm_sin > eps(norm_sin) ? _sin ./ norm_sin : _sin _R = _cos * I + _cross_product_matrix(_sin) + (1 - _cos) * (u ⊗ u) return _R end """ The cross product between two vectors 'a' and 'b', a × b, can be expressed as a matrix-vector product between the "cross-product-matrix" of 'a' and the vector 'b'. """ function _cross_product_matrix(a) @assert size(a) == (3,) SA[ 0 (-a[3]) a[2] a[3] 0 (-a[1]) (-a[2]) a[1] 0 ] end """ Normal of a facet of a hypersurface. See [`cell_normal`]@ref for the computation method. """ struct CellNormal <: AbstractLazy function CellNormal(mesh::AbstractMesh) @assert topodim(mesh) < spacedim(mesh) "CellNormal has only sense when dealing with hypersurface, maybe you confused it with FaceNormal?" return new() end end LazyOperators.materialize(ν::CellNormal, ::CellInfo) = ν function LazyOperators.materialize(::CellNormal, cPoint::CellPoint{ReferenceDomain}) ctype = get_celltype(cPoint) cnodes = get_cellnodes(cPoint) ξ = get_coords(cPoint) return cell_normal(ctype, cnodes, ξ) end function LazyOperators.materialize( ν::CellNormal, ::AbstractSide{Nothing, <:Tuple{<:FaceInfo}}, ) ν end function LazyOperators.materialize( ::CellNormal, sideFacePoint::Side⁻{Nothing, <:Tuple{<:FacePoint}}, ) fPoint, = get_args(sideFacePoint) fInfo = get_faceinfo(fPoint) cInfo = get_cellinfo_n(fInfo) cnodes = nodes(cInfo) ctype = celltype(cInfo) ξcell = get_coords(side_n(fPoint)) return cell_normal(ctype, cnodes, ξcell) end function LazyOperators.materialize( ::CellNormal, sideFacePoint::Side⁺{Nothing, <:Tuple{<:FacePoint}}, ) fPoint, = get_args(sideFacePoint) fInfo = get_faceinfo(fPoint) cInfo = get_cellinfo_p(fInfo) cnodes = nodes(cInfo) ctype = celltype(cInfo) ξcell = get_coords(side_p(fPoint)) return cell_normal(ctype, cnodes, ξcell) end _tangential_projector(ν) = I - (ν ⊗ ν) tangential_projector(mesh) = _tangential_projector ∘ CellNormal(mesh) LazyOperators.materialize(f::Function, ::CellInfo) = f LazyOperators.materialize(f::Function, ::CellPoint) = f LazyOperators.materialize(f::Function, ::FaceInfo) = f LazyOperators.materialize(f::Function, ::FacePoint) = f LazyOperators.materialize(a::AbstractArray{<:Number}, ::CellInfo) = a LazyOperators.materialize(a::AbstractArray{<:Number}, ::FaceInfo) = a LazyOperators.materialize(a::AbstractArray{<:Number}, ::CellPoint) = a LazyOperators.materialize(a::AbstractArray{<:Number}, ::FacePoint) = a LazyOperators.materialize(a::Number, ::CellInfo) = a LazyOperators.materialize(a::Number, ::FaceInfo) = a LazyOperators.materialize(a::Number, ::CellPoint) = a LazyOperators.materialize(a::Number, ::FacePoint) = a LazyOperators.materialize(a::LinearAlgebra.UniformScaling, ::CellInfo) = a LazyOperators.materialize(a::LinearAlgebra.UniformScaling, ::FaceInfo) = a LazyOperators.materialize(a::LinearAlgebra.UniformScaling, ::CellPoint) = a LazyOperators.materialize(a::LinearAlgebra.UniformScaling, ::FacePoint) = a LazyOperators.materialize(f::Function, ::AbstractLazy) = f LazyOperators.materialize(a::AbstractArray{<:Number}, ::AbstractLazy) = a LazyOperators.materialize(a::Number, ::AbstractLazy) = a LazyOperators.materialize(a::LinearAlgebra.UniformScaling, ::AbstractLazy) = a """ get_return_type_and_codim(f::AbstractLazy, elementInfo::AbstractDomainIndex) get_return_type_and_codim(f::AbstractLazy, domain::AbstractDomain) get_return_type_and_codim(f::AbstractLazy, mesh::AbstractMesh) Evaluate the returned type and the codimension of `materialize(f,x)` where `x` is a `ElementPoint` from `elementInfo` (or `domain`/`mesh`). The returned codimension is always a Tuple, even for a scalar. """ function get_return_type_and_codim(f::AbstractLazy, elementInfo::AbstractDomainIndex) fₑ = materialize(f, elementInfo) elementPoint = get_dummy_element_point(elementInfo) value = materialize(fₑ, elementPoint) N = value isa Number ? (1,) : size(value) T = eltype(value) return T, N end function get_return_type_and_codim(f::AbstractLazy, domain::AbstractDomain) get_return_type_and_codim(f, first(DomainIterator(domain))) end function get_return_type_and_codim(f::AbstractLazy, mesh::AbstractMesh) get_return_type_and_codim(f, CellInfo(mesh, 1)) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
8513
abstract type DomainStyle end LazyOperators.pretty_name(a::DomainStyle) = string(typeof(a)) """ ReferenceDomain() Subtype of [`DomainStyle`](@ref) used to describe function that are defined on reference shape of the corresponding cell. """ struct ReferenceDomain <: DomainStyle end """ PhysicalDomain() Subtype of [`DomainStyle`](@ref) used to describe function that are defined on the physical cell. """ struct PhysicalDomain <: DomainStyle end """ DomainStyle(a) Return the domain style of `a` (reference or local) """ function DomainStyle(a) error("`DomainStyle` is not defined for $(typeof(a))") end """ change_domain(a, target_domain::DomainStyle) """ function change_domain(a, target_domain::DomainStyle) change_domain(a, DomainStyle(a), target_domain) end change_domain(a, input_domain::T, target_domain::T) where {T <: DomainStyle} = a function change_domain(a, input_domain::DomainStyle, target_domain::DomainStyle) error("`change_domain` is not defined for $(typeof(f))") end """ same_domain(a, b) Return `Val(true)` if `a` and `b` have the same `DomainStyle`. Return `Val(false)` otherwise. """ same_domain(a, b) = same_domain(DomainStyle(a), DomainStyle(b)) same_domain(a::DS, b::DS) where {DS <: DomainStyle} = Val(true) same_domain(a::DomainStyle, b::DomainStyle) = Val(false) """ common_target_domain(a, b) Return a commom target `DomainStyle` for `a` and `b`. """ common_target_domain(a, b) = common_target_domain(DomainStyle(a), DomainStyle(b)) common_target_domain(a::DS, b::DS) where {DS <: DomainStyle} = DS() common_target_domain(a, b, c...) = common_target_domain(common_target_domain(a, b), c...) # make `PhysicalDomain` "wins" by default : common_target_domain(a::ReferenceDomain, b::PhysicalDomain) = PhysicalDomain() common_target_domain(a::PhysicalDomain, b::ReferenceDomain) = PhysicalDomain() """ AbstractCellPoint{DS} Abstract type to represent a point defined in a cell. # Subtypes should implement : * `get_coords(p::AbstractCellPoint)` * `change_domain(p::AbstractCellPoint, ds::DomainStyle)` """ abstract type AbstractCellPoint{DS} end DomainStyle(p::AbstractCellPoint{DS}) where {DS} = DS() function get_coords(p::AbstractCellPoint) error("`get_coords` is not defined for $(typeof(p))") end change_domain(p::AbstractCellPoint{DS}, ::DS) where {DS <: DomainStyle} = p function change_domain(p::AbstractCellPoint, ds::DomainStyle) error("`change_domain` is not defined for $(typeof(p)) and $(typeof(ds))") end struct CellPoint{DS, T, C} <: AbstractCellPoint{DS} x::T cellinfo::C end """ CellPoint(x, c::CellInfo, ds::DomainStyle) Subtype of [`AbstractCellPoint`](@ref) used to defined of point in a cell. An `AbstractCellFunction` can be easily and efficiently evaluated at a `CellPoint`. `x` can be a tuple or an array of several coordinates of points. """ function CellPoint(x::T, c::C, ds::DS) where {T, C <: CellInfo, DS <: DomainStyle} CellPoint{DS, T, C}(x, c) end get_coords(p::CellPoint) = p.x get_cellinfo(p::CellPoint) = p.cellinfo get_cellnodes(p::CellPoint) = nodes(get_cellinfo(p)) get_celltype(p::CellPoint) = celltype(get_cellinfo(p)) function change_domain(p::CellPoint{ReferenceDomain}, target_domain::PhysicalDomain) m(x) = mapping(celltype(p.cellinfo), nodes(p.cellinfo), x) x_phy = _apply_mapping(m, get_coords(p)) CellPoint(x_phy, p.cellinfo, target_domain) end function change_domain(p::CellPoint{PhysicalDomain}, target_domain::ReferenceDomain) m(x) = mapping_inv(celltype(p.cellinfo), nodes(p.cellinfo), x) x_ref = _apply_mapping(m, get_coords(p)) CellPoint(x_ref, p.cellinfo, target_domain) end """ Apply mapping function `f` on a coordinates of a point or on a tuple/array of several coordinates `x`. """ _apply_mapping(f, x) = f(x) _apply_mapping(f, x::AbstractArray{<:AbstractArray}) = map(f, x) _apply_mapping(f, x::Tuple{Vararg{AbstractArray}}) = map(f, x) evaluate_at_cellpoint(f::Function, x::CellPoint) = _evaluate_at_cellpoint(f, get_coords(x)) _evaluate_at_cellpoint(f, x) = f(x) _evaluate_at_cellpoint(f, x::AbstractArray{<:AbstractArray}) = map(f, x) _evaluate_at_cellpoint(f, x::Tuple{Vararg{AbstractArray}}) = map(f, x) """ A `FacePoint` represent a point on a face. A face is a interface between two cells (except on the boundary). A `FacePoint` is a `CellPoint` is the sense that its coordinates can always be expressed in the reference coordinate of one of its adjacent cells. """ struct FacePoint{DS, T, F} <: AbstractCellPoint{DS} x::T faceInfo::F end get_coords(facePoint::FacePoint) = facePoint.x get_faceinfo(facePoint::FacePoint) = facePoint.faceInfo """ Constructor """ function FacePoint(x, faceInfo::FaceInfo, ds::DomainStyle) FacePoint{typeof(ds), typeof(x), typeof(faceInfo)}(x, faceInfo) end """ Return the opposite side of the `FacePoint` """ function opposite_side(fPoint::FacePoint) return FacePoint( get_coords(fPoint), opposite_side(get_faceinfo(fPoint)), DomainStyle(fPoint), ) end """ Return the `CellPoint` corresponding to the `FacePoint` on negative side """ function side_n(facePoint::FacePoint{ReferenceDomain}) faceInfo = get_faceinfo(facePoint) cellinfo_n = get_cellinfo_n(faceInfo) f = mapping_face(shape(celltype(cellinfo_n)), get_cell_side_n(faceInfo)) return CellPoint(f(get_coords(facePoint)), cellinfo_n, ReferenceDomain()) end """ Return the `CellPoint` corresponding to the `FacePoint` on positive side """ function side_p(facePoint::FacePoint{ReferenceDomain}) faceInfo = get_faceinfo(facePoint) cellinfo_n = get_cellinfo_n(faceInfo) cellinfo_p = get_cellinfo_p(faceInfo) # get global indices of nodes on the face from cell of side_n cshape_n = shape(celltype(cellinfo_n)) cside_n = get_cell_side_n(faceInfo) c2n_n = get_nodes_index(cellinfo_n) f2n_n = c2n_n[faces2nodes(cshape_n, cside_n)] # assumption: shape nodes can be directly indexed in entity nodes ## @bmxam ## NOTE : f2n_n == get_nodes_index(faceInfo) is not true in general # get global indices of nodes on the face from cell of side⁺ cshape_p = shape(celltype(cellinfo_p)) cside_p = get_cell_side_p(faceInfo) c2n_p = get_nodes_index(cellinfo_p) f2n_p = c2n_p[faces2nodes(cshape_p, cside_p)] # assumption: shape nodes can be directly indexed in entity nodes # types-stable version of `indexin(f2n_p, f2n_n)` # which return an array of `Int` instead of `Union{Int,Nothing}`` permut = map(f2n_p) do j for (i, k) in enumerate(f2n_n) k === j && return i end return -1 # this must never happen end f = mapping_face(cshape_p, cside_p, permut) return CellPoint(f(get_coords(facePoint)), cellinfo_p, ReferenceDomain()) end function side_n(facePoint::FacePoint{PhysicalDomain}) return CellPoint( get_coords(facePoint), get_cellinfo_n(get_faceinfo(facePoint)), PhysicalDomain(), ) end function side_p(facePoint::FacePoint{PhysicalDomain}) return CellPoint( get_coords(facePoint), get_cellinfo_p(get_faceinfo(facePoint)), PhysicalDomain(), ) end """ @ghislainb : I feel like you could write only on common function for both CellPoint and FacePoint """ function change_domain(p::FacePoint{ReferenceDomain}, ::PhysicalDomain) faceInfo = get_faceinfo(p) m(x) = mapping(facetype(faceInfo), nodes(faceInfo), x) x_phy = _apply_mapping(m, get_coords(p)) FacePoint(x_phy, faceInfo, PhysicalDomain()) end ElementPoint(x, elementInfo::CellInfo, ds) = CellPoint(x, elementInfo, ds) ElementPoint(x, elementInfo::FaceInfo, ds) = FacePoint(x, elementInfo, ds) """ get_dummy_element_point(elementInfo::AbstractDomainIndex) get_dummy_element_point(domain::AbstractDomain) Return a `CellPoint` (or a `FacePoint` depending on the type of `elementInfo`) whose coordinates are equals to the center of the reference shape of the element. For a `domain` argument, the point is built from its firt element. # Devs notes: These utility functions can be used to easily materialize a `CellFunction` and get the type of the result for example. """ function get_dummy_element_point(elementInfo::AbstractDomainIndex) x = center(shape(get_element_type(elementInfo))) ElementPoint(x, elementInfo, ReferenceDomain()) end function get_dummy_element_point(domain::AbstractDomain) elementInfo = first(DomainIterator(domain)) get_dummy_element_point(elementInfo) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
2115
abstract type AbstractMeshDataLocation end struct CellData <: AbstractMeshDataLocation end struct FaceData <: AbstractMeshDataLocation end struct PointData <: AbstractMeshDataLocation end """ Represent a data whose values are known inside each cell/node/face of the mesh. Note that the "values" can be anything : an vector of scalar (conductivity by cell), an array of functions, etc. # Example ```julia n = 10 mesh = line_mesh(n) data = MeshCellData(rand(n)) data = MeshCellData([PhysicalFunction(x -> i*x) for i in 1:n]) ``` """ struct MeshData{L <: AbstractMeshDataLocation, T <: AbstractVector} <: AbstractLazy values::T end function MeshData(location::AbstractMeshDataLocation, values::AbstractVector) MeshData{typeof(location), typeof(values)}(values) end get_values(data::MeshData) = data.values set_values!(data::MeshData, values::Union{Number, AbstractVector}) = data.values .= values get_location(::MeshData{L}) where {L} = L() function LazyOperators.materialize(data::MeshData{CellData}, cInfo::CellInfo) value = get_values(data)[cellindex(cInfo)] return _wrap_value(value) end function LazyOperators.materialize( data::MeshData{CellData}, side::Side⁻{Nothing, <:Tuple{<:FaceInfo}}, ) fInfo = get_args(side)[1] cInfo_n = get_cellinfo_n(fInfo) return materialize(data, cInfo_n) end function LazyOperators.materialize( data::MeshData{CellData}, side::Side⁺{Nothing, <:Tuple{<:FaceInfo}}, ) fInfo = get_args(side)[1] cInfo_p = get_cellinfo_p(fInfo) return materialize(data, cInfo_p) end function LazyOperators.materialize( data::MeshData{FaceData}, side::AbstractSide{Nothing, <:Tuple{<:FaceInfo}}, ) fInfo = get_args(side)[1] value = get_values(data)[faceindex(fInfo)] return _wrap_value(value) end _wrap_value(value) = value _wrap_value(value::Union{Number, AbstractArray}) = ReferenceFunction(ξ -> value, Val(1)) MeshCellData(values::AbstractVector) = MeshData(CellData(), values) MeshFaceData(values::AbstractVector) = MeshData(FaceData(), values) MeshPointData(values::AbstractVector) = MeshData(PointData(), values)
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
10114
# REF: # https://www.brown.edu/research/projects/scientific-computing/sites/brown.edu.research.projects.scientific-computing/files/uploads/Maximum-principle-satisfying%20and%20positivity-preserving.pdf function linear_scaling_limiter_coef( v::SingleFieldFEFunction, dω::Measure, bounds, DMPrelax, periodicBCs::Union{Nothing, NTuple{N, <:BoundaryFaceDomain{Me, BC}}}, ) where {N, Me, BC <: PeriodicBCType} @assert is_discontinuous(get_fespace(v)) "LinearScalingLimiter only support discontinuous variables" mesh = get_mesh(get_domain(dω)) mean = get_values(cell_mean(v, dω)) limiter = similar(mean) minval = similar(mean) minval .= typemax(eltype(minval)) maxval = similar(mean) maxval .= -minval _minmax_cells!(minval, maxval, v, dω) _minmax_faces!(minval, maxval, v, dω) if !isnothing(periodicBCs) for domain in periodicBCs _minmax_faces_periodic!(minval, maxval, v, degquad, domain) end end minval_mean = similar(mean) minval_mean .= typemax(eltype(minval)) maxval_mean = similar(mean) maxval_mean .= -minval_mean _mean_minmax_cells!(minval_mean, maxval_mean, mean, mesh) if !isnothing(periodicBCs) for domain in periodicBCs _mean_minmax_cells_periodic!(minval_mean, maxval_mean, mean, domain) end end # relax DMP @. minval_mean = minval_mean - DMPrelax @. maxval_mean = maxval_mean + DMPrelax # impose strong physical bounds if !isnothing(bounds) @. minval_mean = max(minval_mean, bounds[1]) @. maxval_mean = min(maxval_mean, bounds[2]) end for i in 1:ncells(mesh) limiter[i] = _compute_scalar_limiter( mean[i], minval[i], maxval[i], minval_mean[i], maxval_mean[i], ) end MeshCellData(limiter), MeshCellData(mean) end """ _mean_minmax_cells!(minval_mean, maxval_mean, mean, mesh) For each cell, compute the min and max of mean values (in the `mean` array) of the neighbor cells. So `minval_mean[i]` is the minimum of the mean values of cells surrounding cell `i`. """ function _mean_minmax_cells!(minval_mean, maxval_mean, mean, mesh) f2c = connectivities_indices(mesh, :f2c) minval_mean .= mean maxval_mean .= mean for kface in 1:nfaces(mesh) _f2c = f2c[kface] if length(_f2c) > 1 i = _f2c[1] j = _f2c[2] minval_mean[i] = min(mean[j], minval_mean[i]) maxval_mean[i] = max(mean[j], maxval_mean[i]) minval_mean[j] = min(mean[i], minval_mean[j]) maxval_mean[j] = max(mean[i], maxval_mean[j]) end end return nothing end function _mean_minmax_cells_periodic!(minval_mean, maxval_mean, mean, periodicBcDomain) error("TODO") # # TODO : add a specific API for the domain cache: # perio_cache = get_cache(periodicBcDomain) # _1, _2, _3, bnd_f2c, _5, _6 = perio_cache # for kface in axes(bnd_f2c,1) # i = bnd_f2c[kface, 1] # j = bnd_f2c[kface, 2] # minval_mean[i] = min(mean[j], minval_mean[i]) # maxval_mean[i] = max(mean[j], maxval_mean[i]) # minval_mean[j] = min(mean[i], minval_mean[j]) # maxval_mean[j] = max(mean[i], maxval_mean[j]) # end return nothing end function _minmax_cells(v, mesh, quadrature) c2n = connectivities_indices(mesh, :c2n) cellTypes = cells(mesh) val = map(1:ncells(mesh)) do i # mᵢ, Mᵢ : min/max at cell quadrature points ctypeᵢ = cellTypes[i] cnodesᵢ = get_nodes(mesh, c2n[i]) cᵢ = CellInfo(i, ctypeᵢ, cnodesᵢ) vᵢ = materialize(v, cᵢ) fᵢ(ξ) = vᵢ(CellPoint(ξ, cᵢ, ReferenceDomain())) quadrule = QuadratureRule(shape(ctypeᵢ), quadrature) mᵢ, Mᵢ = _minmax(fᵢ, quadrule) mᵢ, Mᵢ end return val end """ _minmax_cells!(minval, maxval, v, dω) Compute the min and max values of `v` in each cell of `dω` """ function _minmax_cells!(minval, maxval, v, dω) domain = get_domain(dω) quadrature = get_quadrature(dω) for (i, cellInfo) in enumerate(DomainIterator(domain)) # mᵢ, Mᵢ : min/max at cell quadrature points vᵢ = materialize(v, cellInfo) fᵢ(ξ) = vᵢ(CellPoint(ξ, cellInfo, ReferenceDomain())) quadrule = QuadratureRule(shape(celltype(cellInfo)), quadrature) mᵢ, Mᵢ = _minmax(fᵢ, quadrule) minval[i] = min(mᵢ, minval[i]) maxval[i] = max(Mᵢ, maxval[i]) end return nothing end function _minmax_faces!(minval, maxval, v, dω::AbstractMeasure{<:AbstractCellDomain}) dΓ = Measure(AllFaceDomain(get_mesh(get_domain(dω))), get_quadrature(dω)) _minmax_faces!(minval, maxval, v, dΓ) end function _minmax_faces!(minval, maxval, v, dω::AbstractMeasure{<:AbstractFaceDomain}) quadrature = get_quadrature(dω) for faceInfo in DomainIterator(get_domain(dω)) i = cellindex(get_cellinfo_n(faceInfo)) j = cellindex(get_cellinfo_p(faceInfo)) mᵢⱼ, Mᵢⱼ, mⱼᵢ, Mⱼᵢ = _minmax_on_face( side_n(v), quadrature, facetype(faceInfo), faceInfo, opposite_side(faceInfo), ) minval[i] = min(mᵢⱼ, minval[i]) maxval[i] = max(Mᵢⱼ, maxval[i]) minval[j] = min(mⱼᵢ, minval[j]) maxval[j] = max(Mⱼᵢ, maxval[j]) end return nothing end function _minmax_faces_periodic!(minval, maxval, v, degquad, periodicBcDomain) error("TODO") # mesh = get_mesh(v) # c2n = connectivities_indices(mesh,:c2n) # f2n = connectivities_indices(mesh,:f2n) # f2c = connectivities_indices(mesh,:f2c) # # TODO : add a specific API for the domain cache: # perio_cache = get_cache(periodicBcDomain) # A = transformation(get_bc(periodicBcDomain)) # bndf2f, bnd_f2n1, bnd_f2n2, bnd_f2c, bnd_ftypes, bnd_n2n = perio_cache # cellTypes = cells(mesh) # faceTypes = faces(mesh) # for kface in axes(bnd_f2c,1) # ftype = faceTypes[kface] # _f2c = f2c[kface] # # Neighbor cell i # i = bnd_f2c[kface, 1] # cnodesᵢ = get_nodes(mesh, c2n[i]) # ctypeᵢ = cellTypes[i] # # Neighbor cell j # j = bnd_f2c[kface, 2] # cnodesⱼ = get_nodes(mesh, c2n[j]) # cnodesⱼ = map(n->Node(A(get_coords(n))), cnodesⱼ) # ctypeⱼ = cellTypes[j] # mᵢⱼ, Mᵢⱼ, mⱼᵢ, Mⱼᵢ = _minmax_on_face_periodic(v, degquad, i, j, kface, ftype, ctypeᵢ, ctypeⱼ, bnd_f2n1, bnd_f2n2, c2n, cnodesᵢ, cnodesⱼ, bnd_n2n) # minval[i] = min(mᵢⱼ, minval[i]) # maxval[i] = max(Mᵢⱼ, maxval[i]) # minval[j] = min(mⱼᵢ, minval[j]) # maxval[j] = max(Mⱼᵢ, maxval[j]) # end return nothing end function _minmax_on_face(v, quadrature, ftype, finfo_ij, finfo_ji) quadrule = QuadratureRule(shape(ftype), quadrature) face_map_ij(ξ) = FacePoint(ξ, finfo_ij, ReferenceDomain()) face_map_ji(ξ) = FacePoint(ξ, finfo_ji, ReferenceDomain()) v_ij = materialize(v, finfo_ij) m_ij, M_ij = _minmax(v_ij ∘ face_map_ij, quadrule) v_ji = materialize(v, finfo_ji) m_ji, M_ji = _minmax(v_ji ∘ face_map_ji, quadrule) return m_ij, M_ij, m_ji, M_ji end function _minmax_on_face_periodic( v, quadrature, i, j, faceᵢⱼ, ftypeᵢⱼ, ctypeᵢ, ctypeⱼ, bnd_f2n1, bnd_f2n2, c2n, cnodesᵢ, cnodesⱼ, bnd_n2n, ) c2nᵢ = c2n[i, Val(nnodes(ctypeᵢ))] c2nⱼ = c2n[j, Val(nnodes(ctypeⱼ))] c2nⱼ_perio = map(k -> get(bnd_n2n, k, k), c2nⱼ) sideᵢ = cell_side(ctypeᵢ, c2nᵢ, bnd_f2n1[faceᵢⱼ]) csᵢ = CellSide(i, sideᵢ, ctypeᵢ, cnodesᵢ, c2nᵢ) sideⱼ = cell_side(ctypeⱼ, c2nⱼ, bnd_f2n2[faceᵢⱼ]) csⱼ = CellSide(j, sideⱼ, ctypeⱼ, cnodesⱼ, c2nⱼ_perio) fp = FaceParametrization() quadrule = QuadratureRule(shape(ftypeᵢⱼ), quadrature) vᵢⱼ = (v ∘ fp)[Side(Side⁻(), (csᵢ, csⱼ))] mᵢⱼ, Mᵢⱼ = _minmax(vᵢⱼ, quadrule) vⱼᵢ = (v ∘ fp)[Side(Side⁻(), (csⱼ, csᵢ))] mⱼᵢ, Mⱼᵢ = _minmax(vⱼᵢ, quadrule) return mᵢⱼ, Mᵢⱼ, mⱼᵢ, Mⱼᵢ end # here we assume that f is define in ref. space _minmax(f, quadrule::AbstractQuadratureRule) = extrema(f(ξ) for ξ in get_nodes(quadrule)) """ _compute_scalar_limiter(v̅ᵢ, mᵢ, Mᵢ, m, M) v̅ᵢ = mean mᵢ = minval Mᵢ = maxval m = minval_mean M = maxval_mean """ function _compute_scalar_limiter(v̅ᵢ, mᵢ, Mᵢ, m, M) (Mᵢ - v̅ᵢ) < -10eps() && error("Invalid max value : Mᵢ=$Mᵢ, v̅ᵢ=$v̅ᵢ") (v̅ᵢ - mᵢ) < -10eps() && error("Invalid min value : mᵢ=$mᵢ, v̅ᵢ=$v̅ᵢ") (Mᵢ - v̅ᵢ) < eps() && return zero(v̅ᵢ) (v̅ᵢ - mᵢ) < eps() && return zero(v̅ᵢ) #abs(Mᵢ-v̅ᵢ) > 10*eps(typeof(M)) ? coef⁺ = abs((M-v̅ᵢ)/(Mᵢ-v̅ᵢ)) : coef⁺ = zero(M) #abs(v̅ᵢ-mᵢ) > 10*eps(typeof(M)) ? coef⁻ = abs((v̅ᵢ-m)/(v̅ᵢ-mᵢ)) : coef⁻ = zero(M) min(_ratio(M - v̅ᵢ, Mᵢ - v̅ᵢ), _ratio(v̅ᵢ - m, v̅ᵢ - mᵢ), 1.0) end _ratio(x, y) = abs(x / (y + eps(y))) """ linear_scaling_limiter( u::SingleFieldFEFunction, dω::Measure; bounds::Union{Tuple{<:Number, <:Number}, Nothing} = nothing, DMPrelax = 0.0, periodicBCs::Union{Nothing, NTuple{N, <:BoundaryFaceDomain{Me, BC}}} = nothing, mass = nothing, ) where {N, Me, BC <: PeriodicBCType} Apply the linear scaling limiter (see "Maximum-principle-satisfying and positivity-preserving high order schemes for conservation laws: Survey and new developments", Zhang & Shu). `u_limited = u̅ + lim_u * (u - u̅)` The first returned argument is the coefficient `lim_u`, and the second is `u_limited`. """ function linear_scaling_limiter( u::SingleFieldFEFunction, dω::Measure; bounds::Union{Tuple{<:Number, <:Number}, Nothing} = nothing, DMPrelax = 0.0, periodicBCs::Union{Nothing, NTuple{N, <:BoundaryFaceDomain{Me, BC}}} = nothing, mass = nothing, ) where {N, Me, BC <: PeriodicBCType} lim_u, u̅ = linear_scaling_limiter_coef(u, dω, bounds, DMPrelax, periodicBCs) u_lim = FEFunction(get_fespace(u), get_dof_type(u)) projection_l2!(u_lim, u̅ + lim_u * (u - u̅), dω; mass = mass) lim_u, u_lim end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
6455
""" var_on_vertices(f::AbstractFEFunction, mesh::Mesh) Interpolate solution on mesh vertices. The result is a (nnodes, ncomps) matrix if ncomps > 1, or a (nnodes) vector otherwise. WARNING : for now, the contribution to one vertice is the arithmetic mean of all the data obtained from the neighbor cells of this node. We could use the surface area (among other possible choices). """ function var_on_vertices(f::AbstractLazy, mesh::Mesh) T, N = get_return_type_and_codim(f, mesh) @assert length(N) <= 1 "N = $(length(N)) > 1 not supported yet" values = zeros(T, nnodes(mesh), N[1]) _var_on_vertices!(values, f, mesh) return N[1] == 1 ? vec(values) : values end function _var_on_vertices!(values, f::AbstractLazy, mesh::Mesh) # Alias c2n = connectivities_indices(mesh, :c2n) cellTypes = cells(mesh) # Number of contributions per nodes ncontributions = zeros(Int, nnodes(mesh)) # Loop over cells for icell in 1:ncells(mesh) # Cell information ctype = cellTypes[icell] cshape = shape(ctype) _c2n = c2n[icell] cnodes = get_nodes(mesh, _c2n) cInfo = CellInfo(icell, ctype, cnodes) # Materialize function on CellInfo _f = materialize(f, cInfo) # Loop over the cell nodes (in ref element) for (inode, ξ) in zip(_c2n, get_coords(cshape)) cPoint = CellPoint(ξ, cInfo, ReferenceDomain()) ncontributions[inode] += 1 values[inode, :] .+= materialize(_f, cPoint) end end # Arithmetic mean for ic in axes(values, 2) values[:, ic] .= values[:, ic] ./ ncontributions end end """ var_on_centers(f::AbstractLazy, mesh::AbstractMesh) Interpolate solution on mesh centers. The result is a (ncells, ncomps) matrix if ncomps > 1, or a (ncells) vector otherwise. """ function var_on_centers(f::AbstractLazy, mesh::AbstractMesh) T, N = get_return_type_and_codim(f, mesh) @assert length(N) <= 1 "N = $(length(N)) > 1 not supported yet" values = zeros(T, ncells(mesh), N[1]) _var_on_centers!(values, f, mesh) return N[1] == 1 ? vec(values) : values end function _var_on_centers!(values, f::AbstractLazy, mesh::AbstractMesh) # Alias c2n = connectivities_indices(mesh, :c2n) celltypes = cells(mesh) # Loop over cells for icell in 1:ncells(mesh) ctype = celltypes[icell] cnodes = get_nodes(mesh, c2n[icell]) cInfo = CellInfo(icell, ctype, cnodes) _f = materialize(f, cInfo) ξc = center(shape(celltypes[icell])) cPoint = CellPoint(ξc, cInfo, ReferenceDomain()) values[icell, :] .= materialize(_f, cPoint) end end """ var_on_nodes_discontinuous(f::AbstractLazy, mesh::AbstractMesh, degree::Integer) var_on_nodes_discontinuous(f::AbstractFEFunction, mesh::AbstractMesh) Returns an array containing the values of `f` interpolated to new DoFs. The DoFs correspond to those of a discontinuous cell variable with a `:Lagrange` function space of selected `degree`. If `f` is an `AbstractFEFunction` and no degree is provided, the degree is deduced from the associated space. """ function var_on_nodes_discontinuous(f::AbstractLazy, mesh::AbstractMesh, degree::Integer) @assert degree ≥ 1 "degree must be ≥ 1" fs = FunctionSpace(:Lagrange, degree) # here, we suppose that the mesh is composed of Lagrange elements only _var_on_nodes_discontinuous(f, mesh, fs) end function var_on_nodes_discontinuous(f::AbstractFEFunction, mesh::AbstractMesh) var_on_nodes_discontinuous( f, mesh, max(1, get_degree(get_function_space(get_fespace(f)))), ) end """ Apply the AbstractLazy on the nodes of the mesh using the `FunctionSpace` representation for the cells. """ function _var_on_nodes_discontinuous(f::AbstractLazy, mesh::AbstractMesh, fs::FunctionSpace) celltypes = cells(mesh) c2n = connectivities_indices(mesh, :c2n) # Loop on mesh cells values = map(1:ncells(mesh)) do icell ctype = celltypes[icell] cnodes = get_nodes(mesh, c2n[icell]) cInfo = CellInfo(icell, ctype, cnodes) _f = materialize(f, cInfo) return map(get_coords(fs, shape(ctype))) do ξ cPoint = CellPoint(ξ, cInfo, ReferenceDomain()) materialize(_f, cPoint) end end return rawcat(values) end """ var_on_bnd_nodes_discontinuous(f::AbstractLazy, fdomain::BoundaryFaceDomain, degree::Integer) var_on_bnd_nodes_discontinuous(f::AbstractFEFunction, fdomain::BoundaryFaceDomain) Returns an array containing the values of `f` interpolated to new DoFs on `fdomain`. The DoFs locations on `fdomain` correspond to those of a discontinuous `FESpace` with a `:Lagrange` function space of selected `degree`. """ function var_on_bnd_nodes_discontinuous( f::AbstractLazy, fdomain::BoundaryFaceDomain, degree::Integer, ) @assert degree ≥ 1 "degree must be ≥ 1" fs = FunctionSpace(:Lagrange, degree) # here, we suppose that the mesh is composed of Lagrange elements only _var_on_bnd_nodes_discontinuous(f, fdomain, fs) end function var_on_bnd_nodes_discontinuous(f::AbstractFEFunction, fdomain::BoundaryFaceDomain) var_on_bnd_nodes_discontinuous( f, fdomain, max(1, get_degree(get_function_space(get_fespace(f)))), ) end """ Apply the AbstractLazy on the nodes of the `fdomain` using the `FunctionSpace` representation for the cells. """ function _var_on_bnd_nodes_discontinuous( f::AbstractLazy, fdomain::BoundaryFaceDomain, fs::FunctionSpace, ) mesh = get_mesh(fdomain) celltypes = cells(mesh) c2n = connectivities_indices(mesh, :c2n) f2n = connectivities_indices(mesh, :f2n) f2c = connectivities_indices(mesh, :f2c) bndfaces = get_cache(fdomain) values = map(bndfaces) do iface icell = f2c[iface][1] ctype = celltypes[icell] _c2n = c2n[icell] cnodes = get_nodes(mesh, _c2n) cinfo = CellInfo(icell, ctype, cnodes, _c2n) _f = materialize(f, cinfo) side = cell_side(ctype, _c2n, f2n[iface]) localfacedofs = idof_by_face_with_bounds(fs, shape(ctype))[side] ξ_on_face = get_coords(fs, shape(ctype))[localfacedofs] return map(ξ_on_face) do ξ cPoint = CellPoint(ξ, cinfo, ReferenceDomain()) materialize(_f, cPoint) end end return rawcat(values) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
4329
""" projection_l2!(u::AbstractSingleFieldFEFunction, f, mesh::AbstractMesh, [degree::Int]) projection_l2!( u::AbstractSingleFieldFEFunction, f, mesh::AbstractMesh, degree::Int; kwargs..., ) projection_l2!(u::AbstractSingleFieldFEFunction, f, dΩ::Measure; mass = nothing) projection_l2!(u::MultiFieldFEFunction, f, args...; mass = nothing) Compute dof values of `u` from a projection L2 so that: ```math ∫(u ⋅ v)dΩ = ∫(f ⋅ v)dΩ ``` where `dΩ` is the measure defined on the `CellDomain` of the `mesh` with a degree `D` If `degree` is not given, the default value is set to `2d+1` where `d` is the degree of the `function_space` of `u`. Keyword argument `mass` could be used to give a precomputed matrix for the left-hand term ``∫(u ⋅ v)dΩ``. """ function projection_l2!(u::AbstractSingleFieldFEFunction, f, mesh::AbstractMesh; kwargs...) degree = 2 * get_degree(get_function_space(get_fespace(u))) + 1 projection_l2!(u, f, mesh, degree; kwargs...) end function projection_l2!( u::AbstractSingleFieldFEFunction, f, mesh::AbstractMesh, degree::Int; kwargs..., ) dΩ = Measure(CellDomain(mesh), degree) projection_l2!(u, f, dΩ; kwargs...) end function projection_l2!(u::AbstractSingleFieldFEFunction, f, dΩ::Measure; mass = nothing) @assert f isa AbstractLazy "`f` must be <:AbstractLazy : a `PhysicalFunction` for instance" U = get_fespace(u) V = TestFESpace(U) if isa(mass, Nothing) a(u, v) = ∫(u ⋅ v)dΩ A = assemble_bilinear(a, U, V) else A = mass end l(v) = ∫(f ⋅ v)dΩ T, = get_return_type_and_codim(f, get_domain(dΩ)) b = assemble_linear(l, V; T = T) x = A \ b set_dof_values!(u, x) return nothing end function projection_l2!(u::MultiFieldFEFunction, f, args...; mass = nothing) _mass = isa(mass, Nothing) ? ntuple(i -> nothing, length((u...,))) : mass foreach(u, f, _mass) do uᵢ, fᵢ, mᵢ projection_l2!(uᵢ, fᵢ, args...; mass = mᵢ) end end struct CellMeanCache{FE, M, MM} feSpace::FE measure::M massMatrix::MM end get_fespace(cache::CellMeanCache) = cache.feSpace get_measure(cache::CellMeanCache) = cache.measure get_mass_matrix(cache::CellMeanCache) = cache.massMatrix function build_cell_mean_cache(u::AbstractSingleFieldFEFunction, dΩ::Measure) mesh = get_mesh(get_domain(dΩ)) fs = FunctionSpace(:Lagrange, 0) ncomp = get_ncomponents(get_fespace(u)) Umean = TrialFESpace(fs, mesh, :discontinuous; size = ncomp) Vmean = TestFESpace(Umean) mass = factorize(build_mass_matrix(Umean, Vmean, dΩ)) return CellMeanCache(Umean, dΩ, mass) end function build_cell_mean_cache(u::MultiFieldFEFunction, dΩ::Measure) return map(Base.Fix2(build_cell_mean_cache, dΩ), get_fe_functions(u)) end """ cell_mean(q::MultiFieldFEFunction, dω::Measure) cell_mean(q::SingleFieldFEFunction, dω::Measure) Return a vector containing mean cell values of `q` computed according quadrature rules defined by measure `dω`. # Dev note * This function should be moved to a better file **(TODO)** """ function cell_mean(u, dΩ::Measure) cache = build_cell_mean_cache(u, dΩ) return cell_mean(u, cache) end function cell_mean(u::MultiFieldFEFunction, cache::Tuple{Vararg{CellMeanCache}}) return map(get_fe_functions(u), cache) do uᵢ, cacheᵢ cell_mean(uᵢ, cacheᵢ) end end function cell_mean(u::AbstractFEFunction, cache::CellMeanCache) Umean = get_fespace(cache) u_mean = FEFunction(Umean, get_dof_type(u)) projection_l2!(u_mean, u, get_measure(cache); mass = get_mass_matrix(cache)) values = _reshape_cell_mean(u_mean, Val(get_size(Umean))) return MeshCellData(values) end function _reshape_cell_mean(u::SingleFieldFEFunction, ncomp::Val{N}) where {N} ncell = Int(length(get_dof_values(u)) / N) map(1:ncell) do i _may_scalar(get_dof_values(u, i, ncomp)) end end _may_scalar(a::SVector{1}) = a[1] _may_scalar(a) = a cell_mean(u::MeshData{CellData}, ::Measure) = u function build_mass_matrix(u::AbstractFEFunction, dΩ::AbstractMeasure) U = get_fespace(u) V = TestFESpace(U) return build_mass_matrix(U, V, dΩ) end function build_mass_matrix(U, V, dΩ::AbstractMeasure) m(u, v) = ∫(u ⋅ v)dΩ return assemble_bilinear(m, U, V) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
18258
""" The `DofHandler` handles the degree of freedom numbering. To each degree of freedom is associated a unique integer. """ struct DofHandler # N : number of components # Naturally, `iglob` would be a (ndofs, ncell) array. Since # the first dimension, the number of dofs in a cell, depends on the cell # (ex tri vs quad), a flattened array is used. So here `iglob` is Vector # whose size is the total number of dofs of the problem. # Warning : for a complete discontinous discretization, `iglob` is simply # `iglob = 1:ndofs_tot`, # but if a continous variable is present, `iglob` reflects that two dofs # of different cells can share the same global index. iglob::Vector{Int} # Array of size (ncell, ncomps) indicating the positions in `iglob` of the # global dof indices for a given cell and a given component (=1 for scalar). # So `offset[icell,icomp] + idof` is the position, in `iglob` of the `idof` # local dof for the component `icomp` in cell `icell` offset::Matrix{Int} # Number of dofs in each cell for each component. This can be computed from `offset` # but easily. It's faster and easier to store the information in this (ncells, ncomps) ndofs::Matrix{Int} # Total number of unique DoFs ndofs_tot::Int end """ DofHandler(mesh::Mesh, fSpace::AbstractFunctionSpace, ncomponents::Int, isContinuous::Bool) Constructor of a DofHandler for a `SingleFESpace` on a `Mesh`. """ function DofHandler( mesh::Mesh, fSpace::AbstractFunctionSpace, ncomponents::Int, isContinuous::Bool, ) # Get cell types celltypes = cells(mesh) # Allocate # `offset` indicates, for each cell, the "position" of the dofs of the cell in the `iglob` vector # `_ndofs` indicates the number of dofs of each cell offset = zeros(Int, ncells(mesh), ncomponents) _ndofs = zeros(Int, ncells(mesh), ncomponents) # First we assume a "discontinuous" type ndofs_tot = sum(cell -> ncomponents * get_ndofs(fSpace, shape(cell)), cells(mesh)) iglob = collect(1:ndofs_tot) curr = 0 # Current offset value. Init to obtain '0' as the first element of `offset` next = 0 # Next offset value for icell in 1:ncells(mesh) for icomp in 1:ncomponents # Fill offset offset[icell, icomp] = curr + next curr = offset[icell, icomp] next = get_ndofs(fSpace, shape(celltypes[icell])) # Fill ndofs _ndofs[icell, icomp] = get_ndofs(fSpace, shape(celltypes[icell])) end end # At this point, we have everything we need for the DofHandler of a discontinuous variable. # The lines below handle the case of a continuous variable, if isContinuous # We get some connectivites c2n = connectivities_indices(mesh, :c2n) # cell -> node # Create dictionnaries (explanations to be completed) # Dict([kvar, Set(inodes)] => [icell, Set(idofs_g)]) # dict : key = set of global indices of nodes of a face, values = (cell index, global indices of dofs) dict_n = Dict{Tuple{Int, Int}, Tuple{Int, Vector{Int}}}() dict_e = Dict{Tuple{Int, Set{Int}}, Tuple{Int, Vector{Int}}}() dict_f = Dict{Tuple{Int, Set{Int}}, Tuple{Int, Vector{Int}}}() # Below, a '_l' suffix means "local" by opposition with the '_g' suffix meaning "global" # Loop on mesh cells for icell in 1:ncells(mesh) # Global indices of the cell's nodes inodes_g = c2n[icell] # Cell type and shape ct = celltypes[icell] s = shape(ct) # Cell edges, defined by tuples of absolute number indices # @ghislainb the second line should be improved, I just want to map the "local indices" # tuple of tuple ((1,2), (3,4)) into global indices array of arrays [[23,109],[948, 653]] # (arrays instead of tuples because your function "oriented_cell_side" need arrays) _e2n = edges2nodes(ct) e2n_g = [[inodes_g[i] for i in edge] for edge in _e2n] # Cell faces, defined by tuples of absolute number indices _f2n = faces2nodes(ct) f2n_g = [[inodes_g[i] for i in face] for face in _f2n] # Loop over the variables for icomp in 1:ncomponents # Remark : we need to distinguish vertices, edges, faces because two cells # can share dofs with an edge without having a face in common. #--- Deal with dofs on vertices _deal_with_dofs_on_vertices!( dict_n, iglob, offset, icell, inodes_g, s, icomp, fSpace, ) #--- Deal with dofs on edges (topodim(mesh) > 1) && _deal_with_dofs_on_edges!( dict_e, iglob, offset, c2n, celltypes, icell, e2n_g, s, icomp, fSpace, ) #--- Deal with dofs on faces (topodim(mesh) > 2) && _deal_with_dofs_on_faces!( dict_f, iglob, offset, c2n, celltypes, icell, f2n_g, s, fSpace, icomp, ) end end end # Create a cell number remapping to ensure a dense numbering densify!(iglob) ndofs_tot = length(unique(iglob)) return DofHandler(iglob, offset, _ndofs, ndofs_tot) end @inline get_offset(dhl::DofHandler) = dhl.offset @inline get_offset(dhl::DofHandler, icell::Int, icomp::Int) = dhl.offset[icell, icomp] @inline get_iglob(dhl::DofHandler, i) = dhl.iglob[i] @inline get_iglob(dhl::DofHandler) = dhl.iglob """ deal_with_dofs_on_vertices!(dict, iglob, offset, icell::Int, inodes_g, s::AbstractShape, kvar::Int, fs) Function dealing with dofs shared by different cell through a vertex connection. TODO : remove kvar # Arguments - `dict` may be modified by this routine - `iglob` may be modified by this routine - `offset` may be modified by this routine - `fs` : FunctionSpace of var `kvar` - `icell` : cell index - `kvar` : var index - `s` : shape of `icell`-th cell - `inodes_g` : global indices of nodes of `icell` """ function _deal_with_dofs_on_vertices!( dict::Dict{Tuple{Int, Int}, Tuple{Int, Vector{Int}}}, iglob, offset, icell::Int, inodes_g, s::AbstractShape, kvar::Int, fs::AbstractFunctionSpace, ) # Local indices of the dofs on each vertex of the shape idofs_array_l = idof_by_vertex(fs, s) # Exit prematurely if there are no dof on any vertex of the shape length(idofs_array_l[1]) > 0 || return # Loop over shape vertices for i in 1:nvertices(s) inode_g = inodes_g[i] # This is an Int idofs_l = idofs_array_l[i] # This is an Array of Int (local indices of dofs of node 'i') key = (kvar, inode_g) # If the dict already contains the vertex : # - we get the neighbour cell index # - we copy all the global indices of dofs of `jcell` in the corresponding # global indices of `icell` dofs (`jcell` is useless here actually...) if haskey(dict, key) jcell, jdofs_g = dict[key] for d in 1:length(jdofs_g) iglob[offset[icell, kvar] + idofs_l[d]] = jdofs_g[d] end # If the dict doesn't contain this vertex, we add the global indices # of `icell` else idofs_g = iglob[offset[icell, kvar] .+ idofs_l] dict[key] = (icell, idofs_g) end end end """ deal_with_dofs_on_edges!(dict, iglob, offset, c2n, celltypes, icell::Int, inodes_g, e2n_g, s::AbstractShape, kvar::Int, fs) Function dealing with dofs shared by different cell through an edge connection (excluding bord vertices). TODO : remove kvar # Arguments - `dict` may be modified by this routine - `iglob` may be modified by this routine - `offset` may be modified by this routine - `fs` : FunctionSpace of var `kvar` - `icell` : cell index - `kvar` : var index - `s` : shape of `icell`-th cell - `inodes_g` : global indices of nodes of `icell` """ function _deal_with_dofs_on_edges!( dict::Dict{Tuple{Int, Set{Int}}, Tuple{Int, Vector{Int}}}, iglob, offset, c2n, celltypes, icell::Int, e2n_g, s::AbstractShape, kvar::Int, fs::AbstractFunctionSpace, ) # Local indices of the dofs on each edges of the shape idofs_array_l = idof_by_edge(fs, s) # Exit prematurely if there are no dof on any edge of the shape length(idofs_array_l[1]) > 0 || return etypes = edgetypes(celltypes[icell]) # Loop over the cell edges for iedge in 1:nedges(s) inodes_g = e2n_g[iedge] # This is a Tuple of Int (global indices of nodes defining the edge) idofs_l = idofs_array_l[iedge] # This is an Array of Int (local indices of dofs of edge 'i') key = (kvar, Set(inodes_g)) # If the dict already contains the edge : # - we get the neighbour cell index # - we find the local index of the shared edge in jcell # - we copy all the global indices of dofs of `jcell` in the corresponding # global indices of `icell` dofs if haskey(dict, key) jcell, jdofs_g = dict[key] # Retrieve local index of the edge in jcell jside = oriented_cell_side(celltypes[jcell], c2n[jcell], inodes_g) # Reverse dofs array if jside is negative jdofs_reordered_g = (jside > 0) ? jdofs_g : reverse(jdofs_g) # Copy global indices for d in 1:length(jdofs_g) iglob[offset[icell, kvar] + idofs_l[d]] = jdofs_reordered_g[d] end # If the dict doesn't contain this edge, we add the global indices # of `icell` else idofs_g = iglob[offset[icell, kvar] .+ idofs_l] dict[key] = (icell, idofs_g) end end end """ TODO : remove kvar # Arguments - f2n_g : local face index -> global nodes indices """ function _deal_with_dofs_on_faces!( dict, iglob, offset, c2n, celltypes, icell::Int, f2n_g::Vector{Vector{Int}}, s::AbstractShape, fs::AbstractFunctionSpace, kvar::Int, ) # Local indices of the dofs on each face of the shape, excluding the boundary (nodes and/or edges) idofs_array_l = idof_by_face(fs, s) # This is a Tuple of Vector{Int} # Exit prematurely if there are no dof on any face of the shape sum(length.(idofs_array_l)) > 0 || return # Loop over cell faces for iface_l in 1:nfaces(s) ne = nedges(s) iface_nodes_g = f2n_g[iface_l] # This is a Tuple of Int (global indices of nodes defining the face) idofs_l = idofs_array_l[iface_l] # This is an Array of Int (local indices of dofs of face 'i') # Create a Set from the global indices of the face nodes to "tag" the face. key = (kvar, Set(iface_nodes_g)) # If the dict already contains the face : # - we get the neighbour cell index # - we find the local index of the shared face in jcell # - we find the permutation between the two faces # - we copy all the global indices of dofs of `jcell` in the corresponding # global indices of `icell` dofs if haskey(dict, key) jcell, jdofs_g = dict[key] # Cell nodes and type jcell_nodes_g = c2n[jcell] jct = celltypes[jcell] # Retrieve local index of the face in jcell jside = oriented_cell_side(jct, jcell_nodes_g, iface_nodes_g) jface_l = abs(jside) # local index of the face of `jcell` corresponding to `iface` # Global indices of the face nodes and mapping between `iface` and `jface` jface_nodes_g = [jcell_nodes_g[j] for j in faces2nodes(jct, jface_l)] i2j = indexin(iface_nodes_g, jface_nodes_g) # jface_nodes_g[i2j] == iface_nodes_g # Number of dofs "by edge" (= "by node") (these dofs are not on a edge, we are just looking # for a multiple of the number of edges). # Note the use of `÷` because if there is a center dof, we want to exclude it nd_by_edge = length(jdofs_g) ÷ ne # We want to loop inside `jdofs_g`, but starting with the dofs "corresponding" to the first # node of face i. If the faces starts with the same node, offset is 0. If "iface-node-1" # corresponds to "jface-node-3", we want to skip the 3*nd_by_edge first dofs. i_offset = nd_by_edge * (i2j[1] - 1) # Reorder dofs # `jdofs_reordered_g` is similar to jdofs_g, but reordered in the same way as "idofs_g" jdofs_reordered_g = Int[] # we know the final size, but it is easier to init it like this sizehint!(jdofs_reordered_g, length(jdofs_g)) if (nd_by_edge > 0) # need this check (for instance only a center dof) otherwise error is raised with iterator iterator = Iterators.cycle(jdofs_g[1:(nd_by_edge * ne)]) # this removes, eventually, any "center dof" (jside < 0) && (iterator = Iterators.reverse(iterator)) iterator = Iterators.rest(iterator, i_offset) for (j, jdof_g) in enumerate(iterator) push!(jdofs_reordered_g, jdof_g) (j == length(jdofs_reordered_g)) && break end end # Add any remaining center dofs (skipped if not needed) for j in (length(jdofs_reordered_g) + 1):length(jdofs_g) push!(jdofs_reordered_g, jdofs_g[j]) end # Copy global indices for d in 1:length(jdofs_reordered_g) iglob[offset[icell, kvar] + idofs_l[d]] = jdofs_reordered_g[d] end # If the dict doesn't contain this face, we add the global indices # of `icell` else idofs_g = iglob[offset[icell, kvar] .+ idofs_l] dict[key] = (icell, idofs_g) end end end # """ # _max_ndofs(mesh, var) # Count maximum number of dofs per cell. # # Warning # Only working for an array of SCALAR vars # """ # function _max_ndofs(mesh, var) # @assert size(var) == 1 "Only SCALAR vars are supported" # max_ndofs = 0 # for cell in cells(mesh) # max_ndofs = max(max_ndofs, get_ndofs(function_space(var), shape(cell))) # end # return max_ndofs # end """ max_ndofs(dhl::DofHandler) Count maximum number of dofs per cell, all components mixed """ max_ndofs(dhl::DofHandler) = maximum(dhl.ndofs) """ get_ndofs(dhl, icell, kvar::Int) Number of dofs for a given variable in a given cell. # Example ```julia mesh = one_cell_mesh(:line) dhl = DofHandler(mesh, Variable(:u, FunctionSpace(:Lagrange, 1))) @show get_ndofs(dhl, 1, 1) ``` """ @inline get_ndofs(dhl::DofHandler, icell, kvar::Int) = dhl.ndofs[icell, kvar] """ get_ndofs(dhl, icell, icomp::Vector{Int}) Number of dofs for a given set of components in a given cell. # Example ```julia mesh = one_cell_mesh(:line) dhl = DofHandler(mesh, Variable(:u, FunctionSpace(:Lagrange, 1); size = 2)) @show get_ndofs(dhl, 1, [1, 2]) ``` """ @inline function get_ndofs(dhl::DofHandler, icell, icomp::AbstractVector{Int}) sum(dhl.ndofs[icell, icomp]) end @inline function get_ndofs(dhl::DofHandler, icell, icomp::UnitRange{Int}) sum(view(dhl.ndofs, icell:icell, icomp)) end """ get_ndofs(dhl::DofHandler, icell) Number of dofs for a given cell. Note that for a vector variable, the total (accross all components) number of dofs is returned. # Example ```julia mesh = one_cell_mesh(:line) dhl = DofHandler(mesh, Variable(:u, FunctionSpace(:Lagrange, 1))) @show get_ndofs(dhl, 1, :u) ``` """ get_ndofs(dhl::DofHandler, icell) = sum(view(dhl.ndofs, icell, :)) """ get_ndofs(dhl::DofHandler) Total number of dofs. This function takes into account that dofs can be shared by multiple cells. # Example ```julia mesh = one_cell_mesh(:line) dhl = DofHandler(mesh, Variable(:u, FunctionSpace(:Lagrange, 1))) @show get_ndofs(dhl::DofHandler) ``` """ get_ndofs(dhl::DofHandler) = dhl.ndofs_tot """ get_dof(dhl::DofHandler, icell, icomp::Int, idof::Int) Global index of the `idof` local degree of freedom of component `icomp` in cell `icell`. # Example ```julia mesh = one_cell_mesh(:line) dhl = DofHandler(mesh, Variable(:u, FunctionSpace(:Lagrange, 1))) @show get_dof(dhl, 1, 1, 1) ``` """ function get_dof(dhl::DofHandler, icell, icomp::Int, idof::Int) dhl.iglob[dhl.offset[icell, icomp] + idof] end """ get_dof(dhl::DofHandler, icell, icomp::Int) Global indices of all the dofs of a given component in a given cell # Example ```julia mesh = one_cell_mesh(:line) dhl = DofHandler(mesh, Variable(:u, FunctionSpace(:Lagrange, 1))) @show get_dof(dhl, 1, 1) ``` """ function get_dof(dhl::DofHandler, icell, icomp::Int) view(dhl.iglob, dhl.offset[icell, icomp] .+ (1:get_ndofs(dhl, icell, icomp))) end function get_dof(dhl::DofHandler, icell) view(dhl.iglob, dhl.offset[icell, 1] .+ (1:get_ndofs(dhl, icell))) end function get_dof(dhl::DofHandler, icell, ::Val{N}) where {N} dhl.iglob[dhl.offset[icell, 1] .+ SVector{N}(1:N)] end function get_dof(dhl::DofHandler, icell::UnitRange) view( dhl.iglob, dhl.offset[first(icell), 1] .+ (1:(dhl.offset[last(icell), 1] + get_ndofs(dhl, last(icell)))), ) end function get_dof(dhl::DofHandler, icell, icomp::Int, ::Val{N}) where {N} @assert N == get_ndofs(dhl, icell, icomp) "error N ≠ ndofs" dhl.iglob[dhl.offset[icell, icomp] .+ SVector{N}(1:N)] end """ Number of components handled by a DofHandler """ get_ncomponents(dhl::DofHandler) = size(dhl.offset, 2)
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
3192
""" shape_functions(fs::AbstractFunctionSpace, n::Val{N}, quadrule::AbstractQuadratureRule) where {N} shape_functions(fs::AbstractFunctionSpace, n::Val{N}, quadnode::QuadratureNode) where {N} Return values of shape functions corresponding to a function space `fs` evaluated at a given `quadnode` position or at all quadrature nodes of a given `quadrule`. """ function _shape_functions_on_quadrule_gen( fs::AbstractFunctionSpace, n::Val{N}, quadrule::AbstractQuadratureRule, ) where {N} shape = get_shape(quadrule)() λ = [shape_functions(fs, n, shape, ξ) for ξ in get_nodes(quadrule)] return :(SA[$(λ...)]) end @generated function _shape_functions_on_quadrule( fs::AbstractFunctionSpace, ::Val{N}, ::AbstractQuadratureRule{S, Q}, ) where {N, S, Q} _quadrule = QuadratureRule(S(), Q()) _shape_functions_on_quadrule_gen(fs(), Val(N), _quadrule) end function shape_functions( fs::AbstractFunctionSpace, n::Val{N}, quadnode::QuadratureNode, ) where {N} quadrule = get_quadrature_rule(quadnode) _shape_functions_on_quadrule(fs, n, quadrule)[get_index(quadnode)] end function shape_functions( fs::AbstractFunctionSpace, n::Val{N}, quadrule::AbstractQuadratureRule, ) where {N} _shape_functions_on_quadrule(fs, n, quadrule) end # Alias for scalar case function shape_functions(fs::AbstractFunctionSpace, quadrule::AbstractQuadratureRule) shape_functions(fs, Val(1), quadrule) end """ ∂λξ_∂ξ(::AbstractFunctionSpace, n::Val{N}, quadnode::QuadratureNode) where N Gradient of shape functions for any function space. The result is an array whose values are the gradient of each shape functions evaluated at `quadnode` position. `N` is the size of the finite element space. # Implementation Default version using automatic differentiation. Specialize to increase performance. """ function ∂λξ_∂ξ(fs::AbstractFunctionSpace, n::Val{N}, quadnode::QuadratureNode) where {N} quadrule = get_quadrature_rule(quadnode) ∂λξ_∂ξ(fs, n, quadrule)[get_index(quadnode)] end function _∂λξ_∂ξ_gen( fs::AbstractFunctionSpace, ::Val{N}, quadrule::AbstractQuadratureRule, ) where {N} shape = get_shape(quadrule)() ξ = get_nodes(quadrule) ∇λ = map(_ξ -> ∂λξ_∂ξ(fs, Val(N), shape, _ξ), ξ) if isa(∇λ[1], SArray) expr_∇λ = [:($(typeof(_∇λ))($(_∇λ...))) for _∇λ in ∇λ] else expr_∇λ = [:($_∇λ) for _∇λ in ∇λ] end return :(SA[$(expr_∇λ...)]) end @generated function _∂λξ_∂ξ( fs::AbstractFunctionSpace, ::Val{N}, ::AbstractQuadratureRule{S, Q}, ) where {N, S, Q} _quadrule = QuadratureRule(S(), Q()) _∂λξ_∂ξ_gen(fs(), Val(N), _quadrule) end function ∂λξ_∂ξ( fs::AbstractFunctionSpace, n::Val{N}, quadrule::AbstractQuadratureRule{S, Q}, ) where {N, S, Q} _∂λξ_∂ξ(fs, n, quadrule) end # fix ambiguity function ∂λξ_∂ξ( fs::AbstractFunctionSpace, n::Val{1}, quadrule::AbstractQuadratureRule{S, Q}, ) where {S, Q} _∂λξ_∂ξ(fs, n, quadrule) end # alias for scalar case function ∂λξ_∂ξ( fs::AbstractFunctionSpace, quadrule::AbstractQuadratureRule{S, Q}, ) where {S, Q} ∂λξ_∂ξ(fs, Val(1), quadrule) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
6645
""" AbstractFEFunction{S} `S` is the size of the associated `FESpace` # Interface Subtypes should implement: - `get_fespace(f::AbstractFEFunction)` """ abstract type AbstractFEFunction{S} <: AbstractLazy end function show_type_tree(f::AbstractFEFunction; level = 1, indent = 4, prefix = "") println(prefix * string(get_name(f))) end @inline get_name(::AbstractFEFunction) = "FEFunction" function get_fespace(f::AbstractFEFunction) error("`get_fespace` is not defined for $(typeof(f))") end function get_dof_type(f::AbstractFEFunction) error("`get_dof_type` is not defined for type $(typeof(f))") end function get_dof_values(f::AbstractFEFunction) error("`get_dof_values` is not defined for type $(typeof(f))") end function get_dof_values(f::AbstractFEFunction, icell) error("`get_dof_values` is not defined for type $(typeof(f))") end function get_dof_values(f::AbstractFEFunction, icell, n::Val{N}) where {N} error("`get_dof_values` is not defined for type $(typeof(f))") end function Base.getindex(f::AbstractFEFunction{S}, i::CellInfo) where {S} feSpace = get_fespace(f) fSpace = get_function_space(feSpace) domainStyle = DomainStyle(fSpace) cshape = shape(celltype(i)) λ = shape_functions(fSpace, cshape) # shape functions for one scalar component ndofs = get_ndofs(feSpace, cshape) # total number of dofs for this shape (all components included) ncomps = get_ncomponents(feSpace) q₀ = get_dof_values(f, cellindex(i), Val(ndofs)) fcell = _interpolate(Val(ncomps), q₀, λ) CellFunction(fcell, domainStyle, Val(S)) end # scalar case: _reshape_dofs_for_interpolate(::Val{1}, q) = transpose(q) _reshape_dofs_for_interpolate(::Val{1}, q::SVector) = transpose(q) # remove ambiguity # vector case: function _reshape_dofs_for_interpolate(::Val{N}, q::AbstractVector) where {N} transpose(reshape(q, :, N)) end function _reshape_dofs_for_interpolate(::Val{N}, q::SVector{N2}) where {N, N2} transpose(reshape(q, Size(Int(N2 / N), N))) end function _interpolate(n::Val{N}, q::AbstractVector, λ) where {N} x -> _reshape_dofs_for_interpolate(n, q) * λ(x) end """ materialize(f::AbstractFEFunction, x) Implement function `materialize` of the `AbstractLazy` interface. """ LazyOperators.materialize(f::AbstractFEFunction, i::CellInfo) = f[i] function LazyOperators.materialize(f::AbstractFEFunction, side::AbstractSide) op_side = get_operator(side) return materialize(f, op_side(get_args(side)...)) end """ dev notes : introduced for BcubeParallel """ abstract type AbstractSingleFieldFEFunction{S} <: AbstractFEFunction{S} end struct SingleFieldFEFunction{S, FE <: AbstractFESpace, V} <: AbstractSingleFieldFEFunction{S} feSpace::FE dofValues::V end function SingleFieldFEFunction(feSpace::AbstractFESpace, dofValues) size = get_size(feSpace) FE = typeof(feSpace) V = typeof(dofValues) return SingleFieldFEFunction{size, FE, V}(feSpace, dofValues) end function FEFunction(feSpace::AbstractFESpace, dofValues) SingleFieldFEFunction(feSpace, dofValues) end function FEFunction(feSpace::AbstractFESpace, T::Type{<:Number} = Float64) dofValues = allocate_dofs(feSpace, T) FEFunction(feSpace, dofValues) end function FEFunction(feSpace::AbstractFESpace, constant::Number) feFunction = FEFunction(feSpace, typeof(constant)) feFunction.dofValues .= constant return feFunction end get_fespace(f::SingleFieldFEFunction) = f.feSpace get_ncomponents(f::SingleFieldFEFunction) = get_ncomponents(get_fespace(f)) get_dof_type(f::SingleFieldFEFunction) = eltype(get_dof_values(f)) get_dof_values(f::SingleFieldFEFunction) = f.dofValues function get_dof_values(f::SingleFieldFEFunction, icell) feSpace = get_fespace(f) idofs = get_dofs(feSpace, icell) return view(f.dofValues, idofs) end function get_dof_values(f::SingleFieldFEFunction, icell, n::Val{N}) where {N} feSpace = get_fespace(f) idofs = get_dofs(feSpace, icell, n) return f.dofValues[idofs] end @inline function set_dof_values!(f::SingleFieldFEFunction, values::AbstractArray) f.dofValues .= values end """ Represent a Tuple of FEFunction associated to a MultiFESpace """ struct MultiFieldFEFunction{ S, FEF <: Tuple{Vararg{AbstractSingleFieldFEFunction}}, MFE <: AbstractMultiFESpace, } <: AbstractFEFunction{S} feFunctions::FEF mfeSpace::MFE function MultiFieldFEFunction(f, space) new{ ntuple(i -> get_size(get_fespace(space, i)), get_n_fespace(space)), typeof(f), typeof(space), }( f, space, ) end end @inline get_fe_functions(mfeFunc::MultiFieldFEFunction) = mfeFunc.feFunctions @inline function get_fe_function(mfeFunc::MultiFieldFEFunction, iSpace::Int) mfeFunc.feFunctions[iSpace] end @inline _get_mfe_space(mfeFunc::MultiFieldFEFunction) = mfeFunc.mfeSpace function get_dof_type(mfeFunc::MultiFieldFEFunction) mapreduce(get_dof_type, promote, (mfeFunc...,)) end """ Update the vector `u` with the values of each `FEFunction` composing this MultiFieldFEFunction. The mapping of the associated MultiFESpace is respected. """ function get_dof_values!(u::AbstractVector{<:Number}, mfeFunc::MultiFieldFEFunction) for (iSpace, feFunction) in enumerate(get_fe_functions(mfeFunc)) u[get_mapping(_get_mfe_space(mfeFunc), iSpace)] .= get_dof_values(feFunction) end end function get_dof_values(mfeFunc::MultiFieldFEFunction) u = mapreduce(get_dof_values, vcat, (mfeFunc...,)) get_dof_values!(u, mfeFunc) return u end """ Constructor for a FEFunction built on a MultiFESpace. All dofs are initialized to zero by default, but an array `dofValues` can be passed. """ function FEFunction( mfeSpace::AbstractMultiFESpace, dofValues::AbstractVector = allocate_dofs(mfeSpace), ) feFunctions = ntuple( iSpace -> FEFunction( get_fespace(mfeSpace, iSpace), view(dofValues, get_mapping(mfeSpace, iSpace)), ), get_n_fespace(mfeSpace), ) return MultiFieldFEFunction(feFunctions, mfeSpace) end """ Update the dofs of each FEFunction composing the MultiFieldFEFunction """ function set_dof_values!(mfeFunc::MultiFieldFEFunction, u::AbstractVector) for (iSpace, feFunction) in enumerate(get_fe_functions(mfeFunc)) set_dof_values!(feFunction, view(u, get_mapping(_get_mfe_space(mfeFunc), iSpace))) end end Base.iterate(mfeFunc::MultiFieldFEFunction) = iterate(get_fe_functions(mfeFunc)) function Base.iterate(mfeFunc::MultiFieldFEFunction, state) iterate(get_fe_functions(mfeFunc), state) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
26878
const AOS_DEFAULT = true # default value for Array Of Struct / Struct of Array """ Abstract type to represent an finite-element space of size `S`. See `SingleFESpace` for more details about what looks like a finite-element space. # Devs notes All subtypes should implement the following functions: * `get_function_space(feSpace::AbstractFESpace)` * `get_shape_functions(feSpace::AbstractFESpace, shape::AbstractShape)` * `get_cell_shape_functions(feSpace::AbstractFESpace, shape::AbstractShape)` * `get_ndofs(feSpace::AbstractFESpace)` * `is_continuous(feSpace::AbstractFESpace)` Alternatively, you may define a "parent" to your structure by implementing the `Base.parent` function. Then, all the above functions will be redirected to the "parent" FESpace. """ abstract type AbstractFESpace{S} end """ Return the size `S` associated to `AbstractFESpace{S}`. """ get_size(::AbstractFESpace{S}) where {S} = S """ Return the size `S`(= number of components) associated to `AbstractFESpace{S}`. """ get_ncomponents(feSpace::AbstractFESpace) = get_size(feSpace) """ Return the `FunctionSpace` (eventually multiple spaces) associated to the `AbstractFESpace`. """ function get_function_space(feSpace::AbstractFESpace) get_function_space(parent(feSpace)) end """ Return the shape functions associated to the `AbstractFESpace`. """ function get_shape_functions(feSpace::AbstractFESpace, shape::AbstractShape) get_shape_functions(parent(feSpace), shape) end """ Return the shape functions associated to the `AbstractFESpace` in "packed" form: λ(x) = (λ₁(x),...,λᵢ(x),...λₙ(x)) for the `n` dofs. """ function get_cell_shape_functions(feSpace::AbstractFESpace, shape::AbstractShape) get_cell_shape_functions(parent(feSpace), shape) end """ Return the total number of dofs of the FESpace, taking into account the continuous/discontinuous type of the space. If the FESpace contains itself several FESpace (see MultiFESpace), the sum of all dofs is returned. """ get_ndofs(feSpace::AbstractFESpace) = get_ndofs(parent(feSpace)) function get_ndofs(feSpace::AbstractFESpace, shape::AbstractShape) get_ndofs(get_function_space(feSpace), shape) * get_ncomponents(feSpace) end function get_dofs(feSpace::AbstractFESpace, icell::Int, n::Val{N}) where {N} get_dofs(parent(feSpace), icell, n) end """ Return the dofs indices for the cell `icell` Result is an array of integers. """ get_dofs(feSpace::AbstractFESpace, icell::Int) = get_dofs(parent(feSpace), icell) is_continuous(feSpace::AbstractFESpace) = is_continuous(parent(feSpace)) is_discontinuous(feSpace::AbstractFESpace) = !is_continuous(feSpace) _get_dof_handler(feSpace::AbstractFESpace) = _get_dof_handler(parent(feSpace)) _get_dhl(feSpace::AbstractFESpace) = _get_dof_handler(feSpace) """ Return the boundary tags where a Dirichlet condition applies """ function get_dirichlet_boundary_tags(feSpace::AbstractFESpace) get_dirichlet_boundary_tags(parent(feSpace)) end """ allocate_dofs(feSpace::AbstractFESpace, T = Float64) Allocate a vector with a size equal to the number of dof of the FESpace, with the type `T`. For a MultiFESpace, a vector of the total size of the space is returned (and not a Tuple of vectors) """ function allocate_dofs(feSpace::AbstractFESpace, T = Float64) allocate_dofs(parent(feSpace), T) end abstract type AbstractSingleFESpace{S, FS} <: AbstractFESpace{S} end """ An finite-element space (FESpace) is basically a function space, associated to degrees of freedom (on a mesh). A FESpace can be either scalar (to represent a Temperature for instance) or vector (to represent a Velocity). In case of a "vector" `SingleFESpace`, all the components necessarily share the same `FunctionSpace`. """ struct SingleFESpace{S, FS <: AbstractFunctionSpace} <: AbstractSingleFESpace{S, FS} fSpace::FS # function space dhl::DofHandler # degrees of freedom of this FESpace isContinuous::Bool # finite-element or discontinuous-galerkin dirichletBndTags::Vector{Int} # mesh boundary tags where Dirichlet condition applies end Base.parent(feSpace::SingleFESpace) = feSpace get_function_space(feSpace::SingleFESpace) = feSpace.fSpace function get_shape_functions(feSpace::SingleFESpace, shape::AbstractShape) fSpace = get_function_space(feSpace) domainstyle = DomainStyle(fSpace) _λs = shape_functions_vec(fSpace, Val(get_size(feSpace)), shape) λs = map( f -> ShapeFunction(f, domainstyle, Val(get_size(feSpace)), fSpace), _svector_to_tuple(_λs), ) return λs end _svector_to_tuple(a::SVector{N}) where {N} = ntuple(i -> a[i], Val(N)) function get_cell_shape_functions(feSpace::SingleFESpace, shape::AbstractShape) fSpace = get_function_space(feSpace) domainstyle = DomainStyle(fSpace) return CellShapeFunctions(domainstyle, Val(get_size(feSpace)), fSpace, shape) end function get_multi_shape_function(feSpace::SingleFESpace, shape::AbstractShape) return MultiShapeFunction(get_shape_functions(feSpace, shape)) end get_ncomponents(feSpace::SingleFESpace) = get_size(feSpace) is_continuous(feSpace::SingleFESpace) = feSpace.isContinuous _get_dof_handler(feSpace::SingleFESpace) = feSpace.dhl get_dofs(feSpace::SingleFESpace, icell::Int) = get_dof(feSpace.dhl, icell) function get_dofs(feSpace::SingleFESpace, icell::Int, n::Val{N}) where {N} get_dof(feSpace.dhl, icell, n) end get_ndofs(feSpace::SingleFESpace) = get_ndofs(_get_dhl(feSpace)) get_dirichlet_boundary_tags(feSpace::SingleFESpace) = feSpace.dirichletBndTags """ SingleFESpace( fSpace::AbstractFunctionSpace, mesh::AbstractMesh, dirichletBndNames = String[]; size::Int = 1, isContinuous::Bool = true, kwargs... ) Build a finite element space (scalar or vector) from a `FunctionSpace` and a `Mesh`. # Arguments - `fSpace::AbstractFunctionSpace` : the function space associated to the `FESpace` - `mesh::AbstractMesh` : the mesh on which the `FESpace` is discretized - `dirichletBndNames = String[]` : list of mesh boundary labels where a Dirichlet condition applies # Keywords - `size::Int = 1` : the number of components of the `FESpace` - `isContinuous::Bool = true` : if `true`, a continuous dof numbering is created. Otherwise, dof lying on cell nodes or cell faces are duplicated, not shared (discontinuous dof numbering) - `kwargs` : for things such as parallel cache (internal/dev usage only) """ function SingleFESpace( fSpace::AbstractFunctionSpace, mesh::AbstractMesh, dirichletBndNames = String[]; size::Int = 1, isContinuous::Bool = true, kwargs..., ) dhl = DofHandler(mesh, fSpace, size, isContinuous) # Rq : cannot use a "map" here because `dirichletBndNames` can be a Set dirichletBndTags = Int[] bndNames = values(boundary_names(mesh)) for name in dirichletBndNames @assert name ∈ bndNames "Error with the Dirichlet condition on '$name' : this is not a boundary name. Boundary names are : $bndNames" push!(dirichletBndTags, boundary_tag(mesh, name)) end return SingleFESpace{size, typeof(fSpace)}(fSpace, dhl, isContinuous, dirichletBndTags) end @inline allocate_dofs(feSpace::SingleFESpace, T = Float64) = zeros(T, get_ndofs(feSpace)) """ A TrialFESpace is basically a SingleFESpace plus other attributes (related to boundary conditions) # Dev notes * we cannot directly store Dirichlet values on dofs because the Dirichlet values needs "time" to apply """ struct TrialFESpace{S, FE <: AbstractSingleFESpace} <: AbstractFESpace{S} feSpace::FE dirichletValues::Dict{Int, Function} # <boundary tag> => <dirichlet value (function of x, t)> end """ TrialFESpace(feSpace, dirichletValues) TrialFESpace( fSpace::AbstractFunctionSpace, mesh::AbstractMesh, dirichlet::Dict{String} = Dict{String, Any}(); size::Int = 1, isContinuous::Bool = true, kwargs... ) TrialFESpace( fSpace::AbstractFunctionSpace, mesh::AbstractMesh, type::Symbol, dirichlet::Dict{String} = Dict{String, Any}(); size::Int = 1, kwargs... ) Build a trial finite element space. See [`SingleFESpace`](@ref) for hints about the function arguments. Only arguments specific to `TrialFESpace` are detailed below. # Arguments - `dirichlet::Dict{String} = Dict{String, Any}()` : dictionnary specifying the Dirichlet valued-function (or function) associated to each mesh boundary label. The function `f(x,t)` to apply is expressed in the physical coordinate system. Alternatively, a constant value can be provided instead of a function. - `type::Symbol` : `:continuous` or `:discontinuous` # Warning For now the Dirichlet condition can only be applied to nodal bases. # Examples ```julia-repl julia> mesh = one_cell_mesh(:line) julia> fSpace = FunctionSpace(:Lagrange, 2) julia> U = TrialFESpace(fSpace, mesh) julia> V = TrialFESpace(fSpace, mesh, :discontinuous; size = 3) julia> W = TrialFESpace(fSpace, mesh, Dict("North" => 3., "South" => (x,t) -> t .* x)) ``` """ function TrialFESpace( fSpace::AbstractFunctionSpace, mesh::AbstractMesh, dirichlet::Dict{String} = Dict{String, Any}(); size::Int = 1, isContinuous::Bool = true, kwargs..., ) # Build FESpace feSpace = SingleFESpace(fSpace, mesh, keys(dirichlet); size, isContinuous, kwargs...) # Transform any constant value into a function of (x,t) dirichletValues = Dict( boundary_tag(mesh, k) => (v isa Function ? v : (x, t) -> v) for (k, v) in dirichlet ) return TrialFESpace(feSpace, dirichletValues) end function TrialFESpace(feSpace, dirichletValues) TrialFESpace{get_size(feSpace), typeof(feSpace)}(feSpace, dirichletValues) end function TrialFESpace( fSpace::AbstractFunctionSpace, mesh::AbstractMesh, type::Symbol, dirichlet::Dict{String} = Dict{String, Any}(); size::Int = 1, kwargs..., ) @assert type ∈ (:continuous, :discontinuous) "Invalid variable type. Must be ':continuous' or ':discontinuous'" TrialFESpace( fSpace, mesh, dirichlet; size, isContinuous = type == :continuous, kwargs..., ) end """ A MultiplierFESpace can be viewed as a set of independant P0 elements. It is used to define Lagrange multipliers and assemble the associated augmented system (the system that adds the multipliers as unknowns). """ function MultiplierFESpace(mesh::AbstractMesh, size::Int = 1, kwargs...) fSpace = FunctionSpace(:Lagrange, 0) iglob = collect(1:size) offset = zeros(ncells(mesh), size) for i in 1:size offset[:, i] .= i - 1 end ndofs = ones(ncells(mesh), size) ndofs_tot = length(unique(iglob)) dhl = DofHandler(iglob, offset, ndofs, ndofs_tot) feSpace = SingleFESpace{size, typeof(fSpace)}(fSpace, dhl, true, Int[]) return TrialFESpace{size, typeof(feSpace)}(feSpace, Dict{Int, Function}()) end """ Return the values associated to a Dirichlet condition """ get_dirichlet_values(feSpace::TrialFESpace) = feSpace.dirichletValues get_dirichlet_values(feSpace::TrialFESpace, ibnd::Int) = feSpace.dirichletValues[ibnd] """ A TestFESpace is basically a SingleFESpace plus other attributes (related to boundary conditions) """ struct TestFESpace{S, FE <: AbstractSingleFESpace} <: AbstractFESpace{S} feSpace::FE end """ TestFESpace(trialFESpace::TrialFESpace) TestFESpace( fSpace::AbstractFunctionSpace, mesh::AbstractMesh, dirichletBndNames = String[]; size::Int = 1, isContinuous::Bool = true, kwargs..., ) Build a test finite element space. A `TestFESpace` can be built from a `TrialFESpace`. See [`SingleFESpace`](@ref) for hints about the function arguments. Only arguments specific to `TrialFESpace` are detailed below. # Examples ```julia-repl julia> mesh = one_cell_mesh(:line) julia> fSpace = FunctionSpace(:Lagrange, 2) julia> U = TrialFESpace(fSpace, mesh) julia> V = TestFESpace(U) ``` """ function TestFESpace( fSpace::AbstractFunctionSpace, mesh::AbstractMesh, dirichletBndNames = String[]; size::Int = 1, isContinuous::Bool = true, kwargs..., ) # Build FESpace feSpace = SingleFESpace(fSpace, mesh, dirichletBndNames; size, isContinuous, kwargs...) return TestFESpace(feSpace) end TestFESpace(feSpace) = TestFESpace{get_size(feSpace), typeof(feSpace)}(feSpace) TestFESpace(trialFESpace::TrialFESpace) = TestFESpace(parent(trialFESpace)) const TrialOrTest{S, FE} = Union{TrialFESpace{S, FE}, TestFESpace{S, FE}} Base.parent(tfeSpace::TrialOrTest) = tfeSpace.feSpace """ # Devs notes All subtypes should implement the following functions: * `get_fespace(mfeSpace::AbstractMultiFESpace)` * `get_mapping(mfeSpace::AbstractMultiFESpace)` * `get_dofs(mfeSpace::AbstractMultiFESpace, icell::Int)` * `get_shape_functions(mfeSpace::AbstractMultiFESpace, shape::AbstractShape)` * `get_cell_shape_functions(mfeSpace::AbstractMultiFESpace, shape::AbstractShape)` """ abstract type AbstractMultiFESpace{N, FE} end """ get_fespace(mfeSpace::AbstractMultiFESpace, iSpace) get_fespace(mfeSpace::AbstractMultiFESpace) Return the i-th FESpace composing this `AbstractMultiFESpace`. If no index is provided, the tuple of FESpace composing this `AbstractMultiFESpace`` is returnted. """ get_fespace(mfeSpace::AbstractMultiFESpace) = get_fespace(parent(mfeSpace)) get_fespace(mfeSpace::AbstractMultiFESpace, iSpace) = get_fespace(mfeSpace)[iSpace] """ get_mapping(mfeSpace::AbstractMultiFESpace, iSpace) get_mapping(mfeSpace::AbstractMultiFESpace) Return the mapping for the ith `FESpace` composing the `MultiFESpace`. If no index is provided, the tuple of mapping for each `FESpace`` is returnted. """ get_mapping(mfeSpace::AbstractMultiFESpace) = get_mapping(parent(mfeSpace)) get_mapping(mfeSpace::AbstractMultiFESpace, iSpace) = get_mapping(mfeSpace)[iSpace] """ Number of `FESpace` composing the `MultiFESpace` """ get_n_fespace(::AbstractMultiFESpace{N}) where {N} = N _is_AoS(mfeSpace::AbstractMultiFESpace) = _is_AoS(parent(mfeSpace)) Base.iterate(mfeSpace::AbstractMultiFESpace) = iterate(get_fespace(mfeSpace)) Base.iterate(mfeSpace::AbstractMultiFESpace, state) = iterate(get_fespace(mfeSpace), state) Base.length(mfeSpace::AbstractMultiFESpace) = get_n_fespace(mfeSpace) get_dofs(mfeSpace::AbstractMultiFESpace, icell::Int) = get_dofs(parent(mfeSpace), icell) function get_shape_functions(mfeSpace::AbstractMultiFESpace, shape::AbstractShape) get_shape_functions(parent(mfeSpace), shape) end function get_cell_shape_functions(mfeSpace::AbstractMultiFESpace, shape::AbstractShape) get_cell_shape_functions(parent(mfeSpace), shape) end """ A `MultiFESpace` represents a "set" of TrialFESpace or TestFESpace. This structure provides a global dof numbering for each FESpace. `N` is the number of FESpace contained in this `MultiFESpace`. Note that the FESpace can be different from each other (one continous, one discontinuous; one scalar, one vector...) """ struct MultiFESpace{N, FE <: Tuple{Vararg{AbstractFESpace, N}}} <: AbstractMultiFESpace{N, FE} feSpaces::FE mapping::NTuple{N, Vector{Int}} arrayOfStruct::Bool end const AbstractMultiTestFESpace{N} = AbstractMultiFESpace{N, <:Tuple{Vararg{TestFESpace, N}}} const AbstractMultiTrialFESpace{N} = AbstractMultiFESpace{N, <:Tuple{Vararg{TrialFESpace, N}}} Base.parent(mfeSpace::MultiFESpace) = mfeSpace """ Return the tuple of FESpace composing this MultiFESpace """ get_fespace(mfeSpace::MultiFESpace) = mfeSpace.feSpaces get_mapping(mfeSpace::MultiFESpace) = mfeSpace.mapping _is_AoS(mfeSpace::MultiFESpace) = mfeSpace.arrayOfStruct """ Total number of dofs contained in this MultiFESpace """ function get_ndofs(mfeSpace::AbstractMultiFESpace) sum(feSpace -> get_ndofs(feSpace), get_fespace(mfeSpace)) end """ get_dofs(feSpace::MultiFESpace, icell::Int) Return the dofs indices for the cell `icell` for each single-feSpace. Result is a tuple of array of integers, where each array of integers are the indices relative to the numbering of each singleFESpace. # Warning: Combine `get_dofs` with `get_mapping` if global dofs indices are needed. """ function get_dofs(feSpace::MultiFESpace, icell::Int) map(Base.Fix2(get_dofs, icell), get_fespace(feSpace)) end function get_shape_functions(feSpace::MultiFESpace, shape::AbstractShape) map(Base.Fix2(get_shape_functions, shape), get_fespace(feSpace)) end function get_cell_shape_functions(feSpace::MultiFESpace, shape::AbstractShape) map(Base.Fix2(get_cell_shape_functions, shape), get_fespace(feSpace)) end """ Low-level constructor """ function _MultiFESpace( feSpaces::Tuple{Vararg{TrialOrTest, N}}; arrayOfStruct::Bool = AOS_DEFAULT, ) where {N} # Trick to avoid providing "mesh" as an argument: we read the number # of cells in an array of the DofHandler whose size is this number _get_ncells_from_fespace = feSpace::TrialOrTest -> size(_get_dhl(feSpace).offset, 1) # TODO : use getters ncells = _get_ncells_from_fespace(feSpaces[1]) # Ensure all SingleFESpace are define on the "same mesh" (checking # only the number of cells though...) all(feSpace -> _get_ncells_from_fespace(feSpace) == ncells, feSpaces) # Build global numbering _, mapping = if arrayOfStruct _build_mapping_AoS(feSpaces, ncells) else _build_mapping_SoA(feSpaces, ncells) end return MultiFESpace{N, typeof(feSpaces)}(feSpaces, mapping, arrayOfStruct) end """ MultiFESpace( feSpaces::Tuple{Vararg{TrialOrTest, N}}; arrayOfStruct::Bool = AOS_DEFAULT, ) where {N} MultiFESpace( feSpaces::AbstractArray{FE}; arrayOfStruct::Bool = AOS_DEFAULT, ) where {FE <: TrialOrTest} MultiFESpace(feSpaces::Vararg{TrialOrTest}; arrayOfStruct::Bool = AOS_DEFAULT) Build a finite element space representing several sub- finite element spaces. This is particulary handy when several variables are in play since it provides a global dof numbering (for the whole system). The finite element spaces composing the `MultiFESpace` can be different from each other (some continuous, some discontinuous, some scalar, some vectors...). # Arguments - `feSpaces` : the finite element spaces composing the `MultiFESpace`. Note that they must be of type `TrialFESpace` or `TestFESpace`. # Keywords - `arrayOfStruct::Bool = AOS_DEFAULT` : indicates if the dof numbering should be of type "Array of Structs" (AoS) or "Struct of Arrays" (SoA). """ function MultiFESpace( feSpaces::Tuple{Vararg{TrialOrTest, N}}; arrayOfStruct::Bool = AOS_DEFAULT, ) where {N} _MultiFESpace(feSpaces; arrayOfStruct) end function MultiFESpace( feSpaces::AbstractArray{FE}; arrayOfStruct::Bool = AOS_DEFAULT, ) where {FE <: TrialOrTest} MultiFESpace((feSpaces...,); arrayOfStruct) end function MultiFESpace(feSpaces::Vararg{TrialOrTest}; arrayOfStruct::Bool = AOS_DEFAULT) MultiFESpace(feSpaces; arrayOfStruct = arrayOfStruct) end """ Build a global numbering using an Array-Of-Struct strategy """ function _build_mapping_AoS(feSpaces::Tuple{Vararg{TrialOrTest}}, ncells::Int) # mapping = ntuple(i -> zeros(Int, get_ndofs(_get_dhl(feSpaces[i]))), length(feSpaces)) # mapping = ntuple(i -> zeros(Int, get_ndofs(feSpaces[i])), N) mapping = ntuple(i -> zeros(Int, get_ndofs(feSpaces[i])), length(feSpaces)) ndofs = 0 for icell in 1:ncells for (ivar, feSpace) in enumerate(feSpaces) for d in get_dofs(feSpace, icell) if mapping[ivar][d] == 0 ndofs += 1 mapping[ivar][d] = ndofs end end end end @assert all(map(x -> all(x .≠ 0), mapping)) "invalid mapping" return ndofs, mapping end """ Build a global numbering using an Struct-Of-Array strategy """ function _build_mapping_SoA(feSpaces::Tuple{Vararg{TrialOrTest}}, ncells::Int) # mapping = ntuple(i -> zeros(Int, get_ndofs(_get_dhl(feSpaces[i]))), length(feSpaces)) # mapping = ntuple(i -> zeros(Int, get_ndofs(feSpaces[i])), N) mapping = ntuple(i -> zeros(Int, get_ndofs(feSpaces[i])), length(feSpaces)) ndofs = 0 for (ivar, feSpace) in enumerate(feSpaces) for icell in 1:ncells for d in get_dofs(feSpace, icell) if mapping[ivar][d] == 0 ndofs += 1 mapping[ivar][d] = ndofs end end end end @assert all(map(x -> all(x .≠ 0), mapping)) "invalid mapping" return ndofs, mapping end function build_jacobian_sparsity_pattern(u::AbstractMultiFESpace, mesh::AbstractMesh) build_jacobian_sparsity_pattern(parent(u), parent(mesh)) end function build_jacobian_sparsity_pattern(u::MultiFESpace, mesh::Mesh) if _is_AoS(u) return _build_jacobian_sparsity_pattern_AoS(u, mesh) else return _build_jacobian_sparsity_pattern_SoA(u, mesh) end end function _build_jacobian_sparsity_pattern_AoS(u::AbstractMultiFESpace, mesh) I = Int[] J = Int[] f2c = connectivities_indices(mesh, :f2c) c2f = connectivities_indices(mesh, :c2f) for ic in 1:ncells(mesh) for (j, uj) in enumerate(u) for (i, ui) in enumerate(u) if true #varsDependency[i, j] for jdof in get_mapping(u, j)[get_dofs(uj, ic)] for idof in get_mapping(u, i)[get_dofs(ui, ic)] push!(I, idof) push!(J, jdof) end end end end end for ifa in c2f[ic] for ic2 in f2c[ifa] ic2 == ic && continue for (j, uj) in enumerate(u) for (i, ui) in enumerate(u) if true #varsDependency[i, j] for jdof in get_mapping(u, j)[get_dofs(uj, ic2)] for idof in get_mapping(u, i)[get_dofs(ui, ic)] push!(I, idof) push!(J, jdof) end end end end end end end end return sparse(I, J, 1.0) end function _build_jacobian_sparsity_pattern_SoA(u::MultiFESpace, mesh) error("Function `_build_jacobian_sparsity_pattern_SoA` is not implemented yet") end allocate_dofs(mfeSpace::MultiFESpace, T = Float64) = zeros(T, get_ndofs(mfeSpace)) # WIP # """ # Check the `FESpace` `DofHandler` numbering by looking at shared dofs using geometrical criteria. # Only compatible with Lagrange and Taylor elements for now (no Hermite for instance). For a discontinuous # variable, simply checks that the dofs are all unique. # # Example # ```julia # mesh = rectangle_mesh(4, 4) # fes = SingleFESpace(FunctionSpace(:Lagrange, 1), mesh, :continuous) # @show Bcube.check_numbering(fes, mesh) # ``` # """ # function check_numbering(space::SingleFESpace, mesh::Mesh; rtol=1e-3, verbose=true, exit_on_error=true) # # Track number of errors # nerrors = 0 # # Cell variable infos # dhl = _get_dhl(space) # fs = get_function_space(space) # # For discontinuous, each dof must be unique # if is_discontinuous(space) # if length(unique(dhl.iglob)) != length(dhl.iglob) # nerrors += 1 # verbose && println("ERROR : two dofs share the same identifier whereas it is a discontinuous variable") # exit_on_error && error("DofHandler.check_numbering exited prematurely") # end # # Exit prematurely # return nerrors # end # # Mesh infos # celltypes = cells(mesh) # c2n = connectivities_indices(mesh, :c2n) # c2c = connectivity_cell2cell_by_nodes(mesh) # # Loop over cell # for icell in 1:ncells(mesh) # # Cell infos # ct_i = celltypes[icell] # cnodes_i = get_nodes(mesh, c2n[icell]) # shape_i = shape(ct_i) # # Check that all the dofs in this cell are unique # iglobs = get_dof(dhl, icell) # if length(unique(iglobs)) != length(iglobs) # nerrors += 1 # verbose && println("ERROR : two dofs in the same cell share the same identifier") # exit_on_error && error("DofHandler.check_numbering exited prematurely") # end # # Compute tolerance : cell diagonal divided by 100 # min_xyz = get_coords(cnodes_i[1]) # max_xyz = min_xyz # for node in cnodes_i # max_xyz = max.(max_xyz, get_coords(node)) # min_xyz = min.(min_xyz, get_coords(node)) # end # atol = norm(max_xyz - min_xyz) * rtol # # Coordinates of dofs in cell i for this FunctionSpace # coords_i = [mapping(cnodes_i, ct_i, ξ) for ξ in get_coords(fs, shape_i)] # # Loop over neighbor cells # for jcell in c2c[icell] # # Cell infos # ct_j = celltypes[jcell] # cnodes_j = get_nodes(mesh, c2n[jcell]) # shape_j = shape(ct_j) # # Coordinates of dofs in cell j for this FunctionSpace # coords_j = [mapping(cnodes_j, ct_j, ξ) for ξ in get_coords(fs, shape_j)] # # n-to-n comparison # for (idof_loc, xi) in enumerate(coords_i), (jdof_loc, xj) in enumerate(coords_j) # coincident = norm(xi - xj) < atol # for kcomp in 1:ncomponents(cv) # iglob = get_dof(dhl, icell, kcomp, idof_loc) # jglob = get_dof(dhl, jcell, kcomp, jdof_loc) # msg = "" # # Coordinates are identical but dof numbers are different # if coincident && (iglob != jglob) # msg = "ERROR : two dofs share the same location but have different identifiers" # # Coordinates are different but dof numbers are the same # elseif !coincident && (iglob == jglob) # msg = "ERROR : two dofs share the same number but have different location" # end # # Error encountered? # if length(msg) > 0 # nerrors += 1 # verbose && println(msg) # verbose && println("icell=$icell, jcell=$jcell, xi=$xi, xj=$xj, iglob=$iglob, jglob=$jglob") # exit_on_error && error("DofHandler.check_numbering exited prematurely") # end # end # end # end # loop on jcells # end # loop on icells # return nerrors # end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
10214
""" Abstract structure for the different types of function space, for instance the Lagrange function space, the Taylor function space etc. # Devs notes All subtypes should implement the following functions: * `get_ndofs(::AbstractFunctionSpace, ::AbstractShape)` * `_scalar_shape_functions(::AbstractFunctionSpace, ::AbstractShape, ξ)` * `idof_by_vertex(::AbstractFunctionSpace, ::AbstractShape)` * `idof_by_edge(::AbstractFunctionSpace, ::AbstractShape)` * `idof_by_edge_with_bounds(::AbstractFunctionSpace, ::AbstractShape)` * `idof_by_face(::AbstractFunctionSpace, ::AbstractShape)` * `idof_by_face_with_bounds(::AbstractFunctionSpace, ::AbstractShape)` """ abstract type AbstractFunctionSpaceType end abstract type AbstractFunctionSpace{type, degree} end """ get_type(::AbstractFunctionSpace{type}) Getter for the `type` of the `AbstractFunctionSpace` """ get_type(::AbstractFunctionSpace{type}) where {type} = type """ get_degree(::AbstractFunctionSpace{type, degree}) where{type, degree} Return the `degree` associated to the `AbstractFunctionSpace`. """ get_degree(::AbstractFunctionSpace{type, degree}) where {type, degree} = degree struct FunctionSpace{type, degree} <: AbstractFunctionSpace{type, degree} end """ FunctionSpace(fstype::Symbol, degree::Integer) FunctionSpace(fstype::AbstractFunctionSpaceType, degree::Integer) Build a `FunctionSpace` of the designated `FunctionSpaceType` and `degree`. # Examples ```jldoctest julia> FunctionSpace(:Lagrange, 2) FunctionSpace{Bcube.Lagrange{:Uniform}, 2}() ``` """ function FunctionSpace(fstype::AbstractFunctionSpaceType, degree::Integer) FunctionSpace{typeof(fstype), degree}() end FunctionSpace(fstype::Symbol, degree::Integer) = FunctionSpace(Val(fstype), degree) """ shape_functions(::AbstractFunctionSpace, ::Val{N}, shape::AbstractShape, ξ) where N shape_functions(::AbstractFunctionSpace, shape::AbstractShape, ξ) Return the list of shape functions corresponding to a `FunctionSpace` and a `Shape`. `N` is the size of the finite element space (default: `N=1` if the argument is not provided). The result is a vector of all the shape functions evaluated at position ξ, and not a tuple of the different shape functions. This choice is optimal for performance. Note : `λ = ξ -> shape_functions(fs, shape, ξ); λ(ξ)[i]` is faster than `λ =shape_functions(fs, shape); λ[i](ξ)` # Implementation Default version, should be overriden for each concrete FunctionSpace. """ function shape_functions(::AbstractFunctionSpace, ::Val{N}, ::AbstractShape, ξ) where {N} error("Function 'shape_functions' not implemented") end function shape_functions( fs::AbstractFunctionSpace, n::Val{N}, shape::AbstractShape, ) where {N} ξ -> shape_functions(fs, n, shape, ξ) end function shape_functions(fs::AbstractFunctionSpace, shape::AbstractShape, ξ) shape_functions(fs, Val(1), shape, ξ) end function shape_functions(fs::AbstractFunctionSpace, shape::AbstractShape) ξ -> shape_functions(fs, Val(1), shape, ξ) end """ shape_functions_vec(fs::AbstractFunctionSpace, ::Val{N}, shape::AbstractShape, ξ) where {N} Return all the shape functions of FunctionSpace on a Shape evaluated in ξ as a vector. `N` is the the size (number of components) of the finite element space. --- shape_functions_vec(fs::AbstractFunctionSpace{T,D}, n::Val{N}, shape::AbstractShape) where {T,D, N} The shape functions are returned as a vector of functions. # Implementation This is implementation is not always valid, but it is for Lagrange and Taylor spaces (the only two spaces available up to 20/01/23). """ function shape_functions_vec( fs::AbstractFunctionSpace, n::Val{N}, shape::AbstractShape, ξ, ) where {N} _ndofs = get_ndofs(fs, shape) if N == 1 return SVector{_ndofs}( _scalar_shape_functions(fs, shape, ξ)[idof] for idof in 1:_ndofs ) else λs = shape_functions(fs, n, shape, ξ) ndofs_tot = N * _ndofs return SVector{ndofs_tot}(SVector{N}(λs[i, j] for j in 1:N) for i in 1:ndofs_tot) end end function shape_functions_vec( fs::AbstractFunctionSpace, n::Val{N}, shape::AbstractShape, ) where {N} _ndofs = get_ndofs(fs, shape) if N == 1 return SVector{_ndofs}( ξ -> _scalar_shape_functions(fs, shape, ξ)[idof] for idof in 1:_ndofs ) else ndofs_tot = N * _ndofs return SVector{ndofs_tot}( ξ -> begin a = shape_functions(fs, n, shape, ξ) SVector{N}(a[i, j] for j in 1:N) end for i in 1:ndofs_tot ) end end """ ∂λξ_∂ξ(::AbstractFunctionSpace, ::Val{N}, shape::AbstractShape) where N Gradient, with respect to the reference coordinate system, of shape functions for any function space. The result is an array whose elements are the gradient of each shape functions. `N` is the size of the finite element space. # Implementation Default version using automatic differentiation. Specialize to increase performance. """ function ∂λξ_∂ξ end function ∂λξ_∂ξ(fs::AbstractFunctionSpace, n::Val{N}, shape::AbstractShape) where {N} ξ -> ∂λξ_∂ξ(fs, n, shape, ξ) end # default : rely on forwarddiff _diff(f, x::AbstractVector{<:Number}) = ForwardDiff.jacobian(f, x) _diff(f, x::Number) = ForwardDiff.derivative(f, x) function ∂λξ_∂ξ(fs::AbstractFunctionSpace, n::Val{1}, shape::AbstractShape, ξ) _diff(shape_functions(fs, n, shape), ξ) end # alias for scalar case function ∂λξ_∂ξ(fs::AbstractFunctionSpace, shape::AbstractShape, ξ) ∂λξ_∂ξ(fs, Val(1), shape, ξ) end function ∂λξ_∂ξ(fs::AbstractFunctionSpace, shape::AbstractShape, ξ::AbstractVector) ∂λξ_∂ξ(fs, Val(1), shape, ξ) end function ∂λξ_∂ξ(fs::AbstractFunctionSpace, shape::AbstractShape) ξ -> ∂λξ_∂ξ(fs, Val(1), shape, ξ) end """ idof_by_face(::AbstractFunctionSpace, ::AbstractShape) Return the local indices of the dofs lying on each face of the `Shape`. Dofs lying on the face edges are excluded, only "face-interior" dofs are considered. The result is a Tuple of arrays of integers. Arrays maybe be empty. See `Lagrange` interpolation for simple examples. """ function idof_by_face(::AbstractFunctionSpace, ::AbstractShape) error("Function 'idof_by_face' is not defined for this FunctionSpace and Shape") end """ idof_by_face_with_bounds(::AbstractFunctionSpace, ::AbstractShape) Return the local indices of the dofs lying on each face of the `Shape`. Dofs lying on the face edges are included The result is a Tuple of arrays of integers. Arrays maybe be empty. See `Lagrange` interpolation for simple examples. """ function idof_by_face_with_bounds(::AbstractFunctionSpace, ::AbstractShape) error( "Function 'idof_by_face_with_bounds' is not defined for this FunctionSpace and Shape", ) end """ idof_by_edge(::AbstractFunctionSpace, ::AbstractShape) Return the local indices of the dofs lying on each edge of the `Shape`. Dofs lying on the edge vertices are excluded. The result is a Tuple of arrays of integers. Arrays maybe be empty. See `Lagrange` interpolation for simple examples. """ function idof_by_edge(::AbstractFunctionSpace, ::AbstractShape) error("Function 'idof_by_edge' is not defined for this FunctionSpace and Shape") end """ idof_by_edge_with_bounds(::AbstractFunctionSpace, ::AbstractShape) Return the local indices of the dofs lying on each edge of the `Shape`. Dofs lying on the edge vertices are included. The result is a Tuple of arrays of integers. Arrays maybe be empty. See `Lagrange` interpolation for simple examples. """ function idof_by_edge_with_bounds(::AbstractFunctionSpace, ::AbstractShape) error( "Function 'idof_by_edge_with_bounds' is not defined for this FunctionSpace and Shape", ) end """ idof_by_vertex(::AbstractFunctionSpace, ::AbstractShape) Return the local indices of the dofs lying on each vertex of the `Shape`. Beware that we are talking about the `Shape`, not the `EntityType`. So 'interior' vertices of the `EntityType` are not taken into account for instance. See `Lagrange` interpolation for simple examples. """ function idof_by_vertex(::AbstractFunctionSpace, ::AbstractShape) error("Function 'idof_by_vertex' is not defined") end """ get_ndofs(fs::AbstractFunctionSpace, shape::AbstractShape) Number of dofs associated to the given interpolation. """ function get_ndofs(fs::AbstractFunctionSpace, shape::AbstractShape) error( "Function 'ndofs' is not defined for the given FunctionSpace $fs and shape $shape", ) end """ get_coords(fs::AbstractFunctionSpace,::AbstractShape) Return node coordinates in the reference space for associated function space and shape. """ function get_coords(fs::AbstractFunctionSpace, ::AbstractShape) error("Function 'get_coords' is not defined") end abstract type AbtractBasisFunctionsStyle end struct NodalBasisFunctionsStyle <: AbtractBasisFunctionsStyle end struct ModalBasisFunctionsStyle <: AbtractBasisFunctionsStyle end """ basis_functions_style(fs::AbstractFunctionSpace) Return the style (modal or nodal) corresponding to the basis functions of the 'fs'. """ function basis_functions_style(fs::AbstractFunctionSpace) error("'basis_functions_style' is not defined for type : $(typeof(fs))") end get_quadrature(fs::AbstractFunctionSpace) = get_quadrature(basis_functions_style(fs), fs) function get_quadrature(::ModalBasisFunctionsStyle, fs::AbstractFunctionSpace) error("'get_quadrature' is not invalid for modal basis functions") end function get_quadrature(::NodalBasisFunctionsStyle, fs::AbstractFunctionSpace) error("'get_quadrature' is not defined for type : $(typeof(fs))") end # `collocation` does not apply to modal basis functions. function is_collocated(::ModalBasisFunctionsStyle, fs::AbstractFunctionSpace, quad) IsNotCollocatedStyle() end function is_collocated( ::NodalBasisFunctionsStyle, fs::AbstractFunctionSpace, quad::AbstractQuadratureRule, ) return is_collocated(get_quadrature(fs), get_quadrature(quad)()) end function is_collocated(fs::AbstractFunctionSpace, quad) is_collocated(basis_functions_style(fs), fs, quad) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
28618
# This file gathers all Lagrange-related interpolations struct Lagrange{T} <: AbstractFunctionSpaceType end function Lagrange(type) @assert type ∈ (:Uniform, :Legendre, :Lobatto) "Lagrange type=$type is not supported" Lagrange{type}() end Lagrange() = Lagrange(:Uniform) # default Lagrange constructor when `type` is not prescribed FunctionSpace(::Val{:Lagrange}, degree::Integer) = FunctionSpace(Lagrange(), degree) lagrange_quadrature_type(::Lagrange{T}) where {T} = error("No quadrature type is associated with Lagrange type $T") lagrange_quadrature_type(::Lagrange{:Uniform}) = QuadratureUniform() lagrange_quadrature_type(::Lagrange{:Legendre}) = QuadratureLegendre() lagrange_quadrature_type(::Lagrange{:Lobatto}) = QuadratureLobatto() function lagrange_quadrature_type(fs::FunctionSpace{<:Lagrange}) lagrange_quadrature_type(get_type(fs)()) end function lagrange_quadrature(fs::FunctionSpace{<:Lagrange}) return Quadrature(lagrange_quadrature_type(fs), get_degree(fs)) end get_quadrature(fs::FunctionSpace{<:Lagrange}) = lagrange_quadrature(fs) function get_quadrature(::NodalBasisFunctionsStyle, fs::FunctionSpace{<:Lagrange}) return lagrange_quadrature(fs) end #default: function is_collocated( ::ModalBasisFunctionsStyle, ::FunctionSpace{<:Lagrange}, ::Quadrature, ) IsNotCollocatedStyle() end function is_collocated( ::NodalBasisFunctionsStyle, fs::FunctionSpace{<:Lagrange}, quad::Quadrature, ) return is_collocated(lagrange_quadrature(fs), quad) end basis_functions_style(::FunctionSpace{<:Lagrange}) = NodalBasisFunctionsStyle() function _lagrange_poly(j, ξ, nodes) coef = 1.0 / prod((nodes[j] - nodes[k]) for k in eachindex(nodes) if k ≠ j) return coef * prod((ξ - nodes[k]) for k in eachindex(nodes) if k ≠ j) end function __shape_functions_symbolic(quadrule::AbstractQuadratureRule, ::Type{T}) where {T} nodes = get_nodes(quadrule) @variables ξ::eltype(T) l = [_lagrange_poly(j, ξ, nodes) for j in eachindex(nodes)] expr_l = Symbolics.toexpr.((l)) return :(SA[$(expr_l...)]) end @generated function _shape_functions_symbolic( ::Line, ::Q, ξ::T, ) where {Q <: AbstractQuadrature, T} quadrule = QuadratureRule(Line(), Q()) __shape_functions_symbolic(quadrule, T) end """ shape_functions_symbolic(fs::FunctionSpace{<:Lagrange, D}, ::Shape, ξ) where {D, Shape<:Line} ∂λξ_∂ξ_symbolic(fs::FunctionSpace{<:Lagrange, D}, ::Shape, ξ) where {D, Shape<:Line} # Implementation Based on `Symbolic.jl`. First tests show that this version is slower than the implementation based on `meta` when `D` is greater. Further investigations are needed to understand this behavior. `shape_functions_symbolic` uses a "generated" function named `_shape_functions_symbolic`. The core of the generated function is an `Expression` that is created by `__shape_functions_symbolic`. This latter function uses the `Symbolics` package and the lagrange polynomials (defined in `_lagrange_poly`). """ function shape_functions_symbolic(fs::FunctionSpace{<:Lagrange, D}, ::Line, ξ) where {D} quadtype = lagrange_quadrature_type(fs) quad = Quadrature(quadtype, Val(D)) _shape_functions_symbolic(Line(), quad, ξ[1]) end function _shape_functions_symbolic_square( l1::SVector{N1, T}, l2::SVector{N2, T}, ) where {N1, N2, T} N = N1 * N2 if N < MAX_LENGTH_STATICARRAY return SVector{N, T}(l1[i] * l2[j] for i in 1:N1, j in 1:N2) else _l1 = Array(l1) _l2 = Array(l2) return vec([i * j for i in _l1, j in _l2]) end end function shape_functions_symbolic(fs::FunctionSpace{<:Lagrange, D}, ::Square, ξ) where {D} l1 = shape_functions_symbolic(fs::FunctionSpace{<:Lagrange, D}, Line(), ξ[1]) l2 = shape_functions_symbolic(fs::FunctionSpace{<:Lagrange, D}, Line(), ξ[2]) return _shape_functions_symbolic_square(l1, l2) end function shape_functions_symbolic(fs::FunctionSpace{<:Lagrange, D}, ::Cube, ξ) where {D} l1 = shape_functions_symbolic(fs::FunctionSpace{<:Lagrange, D}, Line(), ξ[1]) l2 = shape_functions_symbolic(fs::FunctionSpace{<:Lagrange, D}, Line(), ξ[2]) l3 = shape_functions_symbolic(fs::FunctionSpace{<:Lagrange, D}, Line(), ξ[3]) quadtype = lagrange_quadrature_type(fs) quadrule = QuadratureRule(Cube(), Quadrature(quadtype, Val(D))) N = length(quadrule) if N < MAX_LENGTH_STATICARRAY return SVector{N}(i * j * k for i in l1, j in l2, k in l3) else _l1 = Array(l1) _l2 = Array(l2) _l3 = Array(l3) return vec([i * j * k for i in _l1, j in _l2, k in _l3]) end end # ######### NOT USED ########## function __∂λξ_∂ξ_symbolic( ::Line, ::Val{D}, qt::AbstractQuadratureType, ::Type{T}, ) where {D, T} quadrule = QuadratureRule(Line(), Quadrature(qt, Val(D))) nodes = get_nodes(quadrule) @variables ξ::eltype(T) l = [_lagrange_poly(j, ξ, nodes) for j in eachindex(nodes)] Diff = Differential(ξ) dl = expand_derivatives.(Diff.(l)) expr_l = Symbolics.toexpr.(simplify.(dl)) return :(SA[$(expr_l...)]) end @generated function _∂λξ_∂ξ_symbolic( ::Line, ::Val{D}, qt::AbstractQuadratureType, ξ::T, ) where {D, T} __∂λξ_∂ξ_symbolic(Line(), Val(D), qt, T) end function ∂λξ_∂ξ_symbolic(fs::FunctionSpace{<:Lagrange, D}, ::Line, ξ) where {D} quadtype = lagrange_quadrature_type(fs) _∂λξ_∂ξ_symbolic(Line(), Val(D), quadtype, ξ) end # ############################# function get_ndofs(fs::FunctionSpace{<:Lagrange, D}, shape::AbstractShape) where {D} quadtype = lagrange_quadrature_type(fs) quadrule = QuadratureRule(shape, Quadrature(quadtype, Val(D))) return length(quadrule) end function _scalar_shape_functions( fs::FunctionSpace{<:Lagrange, D}, shape::AbstractShape, ξ, ) where {D} shape_functions_symbolic(fs, shape, ξ) end """ shape_functions(::FunctionSpace{<:Lagrange}, :: Val{N}, ::AbstractShape, ξ) where {N} # Implementation For N > 1, the default version consists in "replicating" the shape functions. If `shape_functions` returns the vector `[λ₁; λ₂; λ₃]`, and if the `FESpace` is of size `2`, then this default behaviour consists in returning the matrix `[λ₁ 0; λ₂ 0; λ₃ 0; 0 λ₁; 0 λ₂; 0 λ₃]`. # Triangle ## Order 1 ```math \\hat{\\lambda}_1(\\xi, \\eta) = 1 - \\xi - \\eta \\hspace{1cm} \\hat{\\lambda}_2(\\xi, \\eta) = \\xi \\hspace{1cm} \\hat{\\lambda}_3(\\xi, \\eta) = \\eta ``` ## Order 2 ```math \\begin{aligned} & \\hat{\\lambda}_1(\\xi, \\eta) = (1 - \\xi - \\eta)(1 - 2 \\xi - 2 \\eta) \\\\ & \\hat{\\lambda}_2(\\xi, \\eta) = \\xi (2\\xi - 1) \\\\ & \\hat{\\lambda}_3(\\xi, \\eta) = \\eta (2\\eta - 1) \\\\ & \\hat{\\lambda}_{12}(\\xi, \\eta) = 4 \\xi (1 - \\xi - \\eta) \\\\ & \\hat{\\lambda}_{23}(\\xi, \\eta) = 4 \\xi \\eta \\\\ & \\hat{\\lambda}_{31}(\\xi, \\eta) = 4 \\eta (1 - \\xi - \\eta) \\end{aligned} ``` # Prism ## Order 1 ```math \\begin{aligned} \\hat{\\lambda}_1(\\xi, \\eta, \\zeta) = (1 - \\xi - \\eta)(1 - \\zeta)/2 \\hspace{1cm} \\hat{\\lambda}_2(\\xi, \\eta, \\zeta) = \\xi (1 - \\zeta)/2 \\hspace{1cm} \\hat{\\lambda}_3(\\xi, \\eta, \\zeta) = \\eta (1 - \\zeta)/2 \\hspace{1cm} \\hat{\\lambda}_5(\\xi, \\eta, \\zeta) = (1 - \\xi - \\eta)(1 + \\zeta)/2 \\hspace{1cm} \\hat{\\lambda}_6(\\xi, \\eta, \\zeta) = \\xi (1 + \\zeta)/2 \\hspace{1cm} \\hat{\\lambda}_7(\\xi, \\eta, \\zeta) = \\eta (1 + \\zeta)/2 \\hspace{1cm} \\end{aligned} ``` """ function shape_functions( fs::FunctionSpace{<:Lagrange, D}, ::Val{N}, shape::AbstractShape, ξ, ) where {D, N} if N == 1 return _scalar_shape_functions(fs, shape, ξ) elseif N < MAX_LENGTH_STATICARRAY return kron(SMatrix{N, N}(1I), _scalar_shape_functions(fs, shape, ξ)) else return kron(Diagonal([1.0 for i in 1:N]), _scalar_shape_functions(fs, shape, ξ)) end end function shape_functions( fs::FunctionSpace{<:Lagrange, D}, n::Val{N}, shape::AbstractShape, ) where {D, N} ξ -> shape_functions(fs, n, shape, ξ) end # Lagrange function for degree = 0 _scalar_shape_functions(::FunctionSpace{<:Lagrange, 0}, ::Line, ξ) = SA[one(eltype(ξ))] get_ndofs(::FunctionSpace{<:Lagrange, 0}, ::Line) = 1 """ ∂λξ_∂ξ(::FunctionSpace{<:Lagrange}, ::Val{1}, ::AbstractShape, ξ) # Triangle ## Order 0 ```math \\nabla \\hat{\\lambda}(\\xi, \\eta) = \\begin{pmatrix} 0 \\\\ 0 \\end{pmatrix} ``` ## Order 1 ```math \\begin{aligned} & \\nabla \\hat{\\lambda}_1(\\xi, \\eta) = \\begin{pmatrix} -1 \\\\ -1 \\end{pmatrix} \\\\ & \\nabla \\hat{\\lambda}_2(\\xi, \\eta) = \\begin{pmatrix} 1 \\\\ 0 \\end{pmatrix} \\\\ & \\nabla \\hat{\\lambda}_3(\\xi, \\eta) = \\begin{pmatrix} 0 \\\\ 1 \\end{pmatrix} \\\\ \\end{aligned} ``` ## Order 2 ```math \\begin{aligned} & \\nabla \\hat{\\lambda}_1(\\xi, \\eta) = \\begin{pmatrix} -3 + 4 (\\xi + \\eta) \\\\ -3 + 4 (\\xi + \\eta) \\end{pmatrix} \\\\ & \\nabla \\hat{\\lambda}_2(\\xi, \\eta) = \\begin{pmatrix} -1 + 4 \\xi \\\\ 0 \\end{pmatrix} \\\\ & \\nabla \\hat{\\lambda}_3(\\xi, \\eta) = \\begin{pmatrix} 0 \\\\ -1 + 4 \\eta \\end{pmatrix} \\\\ & \\nabla \\hat{\\lambda}_{12}(\\xi, \\eta) = 4 \\begin{pmatrix} 1 - 2 \\xi - \\eta \\\\ - \\xi \\end{pmatrix} \\\\ & \\nabla \\hat{\\lambda}_{23}(\\xi, \\eta) = 4 \\begin{pmatrix} \\eta \\\\ \\xi \\end{pmatrix} \\\\ & \\nabla \\hat{\\lambda}_{31}(\\xi, \\eta) = 4 \\begin{pmatrix} - \\eta \\\\ 1 - 2 \\eta - \\xi \\end{pmatrix} \\\\ \\end{aligned} ``` # Square ## Order 0 ```math \\nabla \\hat{\\lambda}(\\xi, \\eta) = \\begin{pmatrix} 0 \\\\ 0 \\end{pmatrix} ``` """ function ∂λξ_∂ξ(::FunctionSpace{<:Lagrange, 0}, ::Val{1}, ::Line, ξ::Number) SA[zero(ξ)] end # Functions for Triangle shape _scalar_shape_functions(::FunctionSpace{<:Lagrange, 0}, ::Triangle, ξ) = SA[one(eltype(ξ))] get_ndofs(::FunctionSpace{<:Lagrange, 0}, ::Triangle) = 1 function ∂λξ_∂ξ(::FunctionSpace{<:Lagrange, 0}, ::Val{1}, ::Triangle, ξ) _zero = zero(eltype(ξ)) return SA[_zero _zero] end function _scalar_shape_functions(::FunctionSpace{<:Lagrange, 1}, ::Triangle, ξ) return SA[ 1 - ξ[1] - ξ[2] ξ[1] ξ[2] ] end function ∂λξ_∂ξ(::FunctionSpace{<:Lagrange, 1}, ::Val{1}, ::Triangle, ξ) return SA[ -1.0 -1.0 1.0 0.0 0.0 1.0 ] end get_ndofs(::FunctionSpace{<:Lagrange, 1}, ::Triangle) = 3 function _scalar_shape_functions(::FunctionSpace{<:Lagrange, 2}, ::Triangle, ξ) return SA[ (1 - ξ[1] - ξ[2]) * (1 - 2ξ[1] - 2ξ[2]) # = (1 - x - y)(1 - 2x - 2y) ξ[1] * (2ξ[1] - 1) # = x (2x - 1) ξ[2] * (2ξ[2] - 1) # = y (2y - 1) 4ξ[1] * (1 - ξ[1] - ξ[2]) # = 4x (1 - x - y) 4ξ[1] * ξ[2] 4ξ[2] * (1 - ξ[1] - ξ[2]) # = 4y (1 - x - y) ] end function ∂λξ_∂ξ(::FunctionSpace{<:Lagrange, 2}, ::Val{1}, ::Triangle, ξ) return SA[ -3+4(ξ[1] + ξ[2]) -3+4(ξ[1] + ξ[2]) -1+4ξ[1] 0.0 0.0 -1+4ξ[2] 4(1 - 2ξ[1] - ξ[2]) -4ξ[1] 4ξ[2] 4ξ[1] -4ξ[2] 4(1 - 2ξ[2] - ξ[1]) ] end get_ndofs(::FunctionSpace{<:Lagrange, 2}, ::Triangle) = 6 function _scalar_shape_functions(::FunctionSpace{<:Lagrange, 3}, ::Triangle, ξ) λ1 = 1 - ξ[1] - ξ[2] λ2 = ξ[1] λ3 = ξ[2] return SA[ 0.5 * (3 * λ1 - 1) * (3 * λ1 - 2) * λ1 0.5 * (3 * λ2 - 1) * (3 * λ2 - 2) * λ2 0.5 * (3 * λ3 - 1) * (3 * λ3 - 2) * λ3 4.5 * λ1 * λ2 * (3 * λ1 - 1) 4.5 * λ1 * λ2 * (3 * λ2 - 1) 4.5 * λ2 * λ3 * (3 * λ2 - 1) 4.5 * λ2 * λ3 * (3 * λ3 - 1) 4.5 * λ3 * λ1 * (3 * λ3 - 1) 4.5 * λ3 * λ1 * (3 * λ1 - 1) 27 * λ1 * λ2 * λ3 ] end get_ndofs(::FunctionSpace{<:Lagrange, 3}, ::Triangle) = 10 # Functions for Square shape _scalar_shape_functions(::FunctionSpace{<:Lagrange, 0}, ::Square, ξ) = SA[one(eltype(ξ))] get_ndofs(::FunctionSpace{<:Lagrange, 0}, ::Square) = 1 function ∂λξ_∂ξ(::FunctionSpace{<:Lagrange, 0}, ::Val{1}, ::Square, ξ) _zero = zero(eltype(ξ)) return SA[_zero _zero] end # Tetra _scalar_shape_functions(::FunctionSpace{<:Lagrange, 0}, ::Tetra, ξ) = SA[one(eltype(ξ))] function grad_shape_functions(::FunctionSpace{<:Lagrange, 0}, ::Val{1}, ::Tetra, ξ) _zero = zero(eltype(ξ)) return SA[_zero _zero _zero] end get_ndofs(::FunctionSpace{<:Lagrange, 0}, ::Tetra) = 1 """ shape_functions(::FunctionSpace{<:Lagrange, 1}, ::Tetra, ξ) Shape functions for Tetra Lagrange element of degree 1 in a 3D space. ```math \\hat{\\lambda}_1(\\xi, \\eta, \\zeta) = (1 - \\xi - \\eta - \\zeta) \\hspace{1cm} \\hat{\\lambda}_2(\\xi, \\eta, \\zeta) = \\xi \\hspace{1cm} \\hat{\\lambda}_3(\\xi, \\eta, \\zeta) = \\eta \\hspace{1cm} \\hat{\\lambda}_5(\\xi, \\eta, \\zeta) = \\zeta \\hspace{1cm} ``` """ function _scalar_shape_functions(::FunctionSpace{<:Lagrange, 1}, ::Tetra, ξηζ) ξ, η, ζ = ξηζ return SA[ 1 - ξ - η - ζ ξ η ζ ] end function grad_shape_functions(::FunctionSpace{<:Lagrange, 1}, ::Val{1}, ::Tetra, ξηζ) return SA[ -1 -1 -1 1 0 0 0 1 0 0 0 1 ] end get_ndofs(::FunctionSpace{<:Lagrange, 1}, ::Tetra) = 4 # Functions for Cube shape _scalar_shape_functions(::FunctionSpace{<:Lagrange, 0}, ::Cube, ξ) = SA[one(eltype(ξ))] get_ndofs(::FunctionSpace{<:Lagrange, 0}, ::Cube) = 1 function ∂λξ_∂ξ(::FunctionSpace{<:Lagrange, 0}, ::Val{1}, ::Cube, ξ) _zero = zero(eltype(ξ)) SA[_zero _zero _zero] end # Prism _scalar_shape_functions(::FunctionSpace{<:Lagrange, 0}, ::Prism, ξ) = SA[one(eltype(ξ))] function ∂λξ_∂ξ(::FunctionSpace{<:Lagrange, 0}, ::Val{1}, ::Prism, ξ) _zero = zero(eltype(ξ)) SA[_zero _zero _zero] end get_ndofs(::FunctionSpace{<:Lagrange, 0}, ::Prism) = 1 function _scalar_shape_functions(::FunctionSpace{<:Lagrange, 1}, ::Prism, ξηζ) ξ, η, ζ = ξηζ return SA[ (1 - ξ - η) * (1 - ζ) ξ * (1 - ζ) η * (1 - ζ) (1 - ξ - η) * (1 + ζ) ξ * (1 + ζ) η * (1 + ζ) ] ./ 2.0 end function ∂λξ_∂ξ(::FunctionSpace{<:Lagrange, 1}, ::Val{1}, ::Prism, ξηζ) ξ, η, ζ = ξηζ return SA[ (-(1 - ζ)) (-(1 - ζ)) (-(1 - ξ - η)) ((1-ζ)) (0.0) (-ξ) (0.0) ((1-ζ)) (-η) (-(1 + ζ)) (-(1 + ζ)) ((1 - ξ-η)) ((1+ζ)) (0.0) (ξ) (0.0) ((1+ζ)) (η) ] ./ 2.0 end get_ndofs(::FunctionSpace{<:Lagrange, 1}, ::Prism) = 6 # Pyramid _scalar_shape_functions(::FunctionSpace{<:Lagrange, 0}, ::Pyramid, ξ) = SA[one(eltype(ξ))] get_ndofs(::FunctionSpace{<:Lagrange, 0}, ::Pyramid) = 1 function ∂λξ_∂ξ(::FunctionSpace{<:Lagrange, 0}, ::Val{1}, ::Pyramid, ξ) _zero = zero(eltype(ξ)) SA[_zero _zero _zero] end function _scalar_shape_functions(::FunctionSpace{<:Lagrange, 1}, ::Pyramid, ξηζ) ξ = ξηζ[1] η = ξηζ[2] ζ = ξηζ[3] # to avoid a singularity in z = 1, we replace (1-ζ) (which is always a # positive quantity), by (1 + ε - ζ). ε = eps() return SA[ (1 - ξ - ζ) * (1 - η - ζ) / (4 * (1 + ε - ζ)) (1 + ξ - ζ) * (1 - η - ζ) / (4 * (1 + ε - ζ)) (1 + ξ - ζ) * (1 + η - ζ) / (4 * (1 + ε - ζ)) (1 - ξ - ζ) * (1 + η - ζ) / (4 * (1 + ε - ζ)) ζ ] end get_ndofs(::FunctionSpace{<:Lagrange, 1}, ::Pyramid) = 5 # bmxam/remark : I first tried to write "generic" functions covering multiple case. But it's easy to # forget some case and think they are already covered. In the end, it's easier to write them all explicitely, # except for the one I wrote that are very intuitive (at least for me). # Nevertheless, it is indeed possible to write functions working for every Lagrange element: # for degree > 1, one dof per vertex # for degree > 2, (degree - 1) dof per edge # (...) # Moreover, it's easier to gather them all in one place instead of mixing them with `shape_functions` definitions # Generic rule 1 : no dof per vertex, edge or face for any Lagrange element of degree 0 function idof_by_vertex(::FunctionSpace{<:Lagrange, 0}, shape::AbstractShape) ntuple(i -> SA[], nvertices(shape)) end function idof_by_edge(::FunctionSpace{<:Lagrange, 0}, shape::AbstractShape) ntuple(i -> SA[], nedges(shape)) end function idof_by_edge_with_bounds(::FunctionSpace{<:Lagrange, 0}, shape::AbstractShape) ntuple(i -> SA[], nedges(shape)) end function idof_by_face(::FunctionSpace{<:Lagrange, 0}, shape::AbstractShape) ntuple(i -> SA[], nfaces(shape)) end function idof_by_face_with_bounds(::FunctionSpace{<:Lagrange, 0}, shape::AbstractShape) ntuple(i -> SA[], nfaces(shape)) end # Generic rule 2 (for non tensorial elements): one dof per vertex for any Lagrange element of degree > 0 function idof_by_vertex( ::FunctionSpace{<:Lagrange, degree}, shape::AbstractShape, ) where {degree} ntuple(i -> SA[i], nvertices(shape)) end function _idof_by_vertex(fs::FunctionSpace{<:Lagrange, degree}, shape::Line) where {degree} quadtype = lagrange_quadrature_type(fs) quadrule = QuadratureRule(shape, Quadrature(quadtype, Val(degree))) n = _get_num_nodes_per_dim(quadrule) return :(SA[1], SA[$n]) end function _idof_by_vertex( fs::FunctionSpace{<:Lagrange, degree}, shape::Square, ) where {degree} quadtype = lagrange_quadrature_type(fs) quadrule = QuadratureRule(shape, Quadrature(quadtype, Val(degree))) n1, n2 = _get_num_nodes_per_dim(quadrule) I = LinearIndices((1:n1, 1:n2)) p1, p2, p3, p4 = I[1, 1], I[n1, 1], I[n1, n2], I[1, n2] return :(SA[$p1], SA[$p2], SA[$p3], SA[$p4]) end function _idof_by_vertex(fs::FunctionSpace{<:Lagrange, degree}, shape::Cube) where {degree} quadtype = lagrange_quadrature_type(fs) quadrule = QuadratureRule(shape, Quadrature(quadtype, Val(degree))) n1, n2, n3 = _get_num_nodes_per_dim(quadrule) I = LinearIndices((1:n1, 1:n2, 1:n3)) p1, p2, p3, p4 = I[1, 1, 1], I[n1, 1, 1], I[n1, n2, 1], I[1, n2, 1] p5, p6, p7, p8 = I[1, 1, n3], I[n1, 1, n3], I[n1, n2, n3], I[1, n2, n3] return :(SA[$p1], SA[$p2], SA[$p3], SA[$p4], SA[$p5], SA[$p6], SA[$p7], SA[$p8]) end function idof_by_vertex(::FunctionSpace{<:Lagrange, 0}, shape::Union{Line, Square, Cube}) ntuple(i -> SA[], nvertices(shape)) end @generated function idof_by_vertex( fs::FunctionSpace{<:Lagrange}, shape::Union{Line, Square, Cube}, ) return _idof_by_vertex(fs(), shape()) end # Generic rule 3 : for `AbstractShape` of topology dimension less than `3`, `idof_by_face` alias `idof_by_edge` const AbstractShape_1_2 = Union{AbstractShape{1}, AbstractShape{2}} function idof_by_face( fs::FunctionSpace{type, degree}, shape::AbstractShape_1_2, ) where {type, degree} idof_by_edge(fs, shape) end function idof_by_face_with_bounds( fs::FunctionSpace{type, degree}, shape::AbstractShape_1_2, ) where {type, degree} idof_by_edge_with_bounds(fs, shape) end # Line function idof_by_edge(::FunctionSpace{<:Lagrange, degree}, shape::Line) where {degree} ntuple(i -> SA[], nedges(shape)) end function idof_by_edge_with_bounds( fs::FunctionSpace{<:Lagrange, degree}, shape::Line, ) where {degree} idof_by_vertex(fs, shape) end # Triangle function idof_by_edge(::FunctionSpace{<:Lagrange, 1}, shape::Triangle) ntuple(i -> SA[], nedges(shape)) end function idof_by_edge_with_bounds(::FunctionSpace{<:Lagrange, 1}, shape::Triangle) (SA[1, 2], SA[2, 3], SA[3, 1]) end idof_by_edge(::FunctionSpace{<:Lagrange, 2}, ::Triangle) = (SA[4], SA[5], SA[6]) function idof_by_edge_with_bounds(::FunctionSpace{<:Lagrange, 2}, ::Triangle) (SA[1, 2, 4], SA[2, 3, 5], SA[3, 1, 6]) end idof_by_edge(::FunctionSpace{<:Lagrange, 3}, ::Triangle) = (SA[4, 5], SA[6, 7], SA[8, 9]) function idof_by_edge_with_bounds(::FunctionSpace{<:Lagrange, 3}, ::Triangle) (SA[1, 2, 4, 5], SA[2, 3, 6, 7], SA[3, 1, 8, 9]) end #for Quad function __idof_by_edge(n1, n2, range1, range2) I = LinearIndices((1:n1, 1:n2)) e1 = I[range1, 1] # edge x⁻ e2 = I[n1, range2] # edge y⁺ e3 = I[reverse(range1), n2] # edge x⁺ e4 = I[1, reverse(range2)] # edge y⁻ return e1, e2, e3, e4 end # for Cube function __idof_by_edge(n1, n2, n3, range1, range2, range3) I = LinearIndices((1:n1, 1:n2, 1:n3)) e1 = I[range1, 1, 1] e2 = I[n1, range2, 1] e3 = I[reverse(range1), n2, 1] e4 = I[1, reverse(range2), 1] e5 = I[1, 1, range3] e6 = I[n1, 1, range3] e7 = I[n1, n2, range3] e8 = I[1, n2, range3] e9 = I[range1, 1, n3] e10 = I[n1, range2, n3] e11 = I[reverse(range1), n2, n3] e12 = I[1, reverse(range2), n3] return e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12 end function _idof_by_edge( fs::FunctionSpace{<:Lagrange, degree}, shape::Union{Square, Cube}, ) where {degree} quadtype = lagrange_quadrature_type(fs) quadrule = QuadratureRule(shape, Quadrature(quadtype, Val(degree))) n = _get_num_nodes_per_dim(quadrule) range = ntuple(i -> 2:(n[i] - 1), length(n)) e = __idof_by_edge(n..., range...) expr = [:(SA[$(x...)]) for x in e] return :(tuple($(expr...))) end function idof_by_edge(::FunctionSpace{<:Bcube.Lagrange, 0}, shape::Union{Cube, Square}) ntuple(i -> SA[], nedges(shape)) end @generated function idof_by_edge( fs::FS, shape::Shape, ) where {FS <: FunctionSpace{<:Lagrange}, Shape <: Union{Square, Cube}} return _idof_by_edge(fs(), shape()) end function _idof_by_edge_with_bounds( fs::FunctionSpace{<:Lagrange, degree}, shape::Union{Square, Cube}, ) where {degree} quadtype = lagrange_quadrature_type(fs) quadrule = QuadratureRule(shape, Quadrature(quadtype, Val(degree))) n = _get_num_nodes_per_dim(quadrule) range = ntuple(i -> 1:n[i], length(n)) e = __idof_by_edge(n..., range...) # put extrema nodes at first and second position : # e = map(e) do x # length(x) == 2 && return x # return [x[1],x[end],x[2:end-1]...] # end expr = [:(SA[$(x...)]) for x in e] return :(tuple($(expr...))) end @generated function idof_by_edge_with_bounds( fs::FS, shape::Shape, ) where {FS <: FunctionSpace{<:Lagrange}, Shape <: Union{Square, Cube}} return _idof_by_edge_with_bounds(fs(), shape()) end # for Cube function __idof_by_face(n1, n2, n3, range1, range2, range3) I = LinearIndices((1:n1, 1:n2, 1:n3)) f5 = I[1, range2, range3] # face x⁻ f3 = I[n1, range2, range3] # face x⁺ f2 = I[range1, 1, range3] # face y⁻ f4 = I[range1, n2, range3] # face y⁺ f1 = I[range1, range2, 1] # face z⁻ f6 = I[range1, range2, n3] # face z⁺ return f1, f2, f3, f4, f5, f6 end function _idof_by_face(fs::FunctionSpace{<:Lagrange, degree}, shape::Cube) where {degree} quadtype = lagrange_quadrature_type(fs) quadrule = QuadratureRule(shape, Quadrature(quadtype, Val(degree))) n = _get_num_nodes_per_dim(quadrule) range = ntuple(i -> 2:(n[i] - 1), length(n)) f = vec.(__idof_by_face(n..., range...)) expr = [:(SA[$(x...)]) for x in f] return :(tuple($(expr...))) end function idof_by_face(::FunctionSpace{<:Bcube.Lagrange, 0}, shape::Cube) ntuple(i -> SA[], nedges(shape)) end @generated function idof_by_face(fs::FunctionSpace{<:Lagrange}, shape::Union{Cube}) return _idof_by_face(fs(), shape()) end function _idof_by_face_with_bounds( fs::FunctionSpace{<:Lagrange, degree}, shape::Cube, ) where {degree} quadtype = lagrange_quadrature_type(fs) quadrule = QuadratureRule(shape, Quadrature(quadtype, Val(degree))) n = _get_num_nodes_per_dim(quadrule) range = ntuple(i -> 1:n[i], length(n)) f = vec.(__idof_by_face(n..., range...)) expr = [:(SA[$(x...)]) for x in f] return :(tuple($(expr...))) end @generated function idof_by_face_with_bounds(fs::FunctionSpace{<:Lagrange}, shape::Cube) return _idof_by_face_with_bounds(fs(), shape()) end # Tetra function idof_by_edge(::FunctionSpace{<:Lagrange, 1}, shape::Tetra) ntuple(i -> SA[], nedges(shape)) end function idof_by_edge_with_bounds(::FunctionSpace{<:Lagrange, 1}, shape::Tetra) (SA[1, 2], SA[2, 3], SA[3, 1], SA[1, 4], SA[2, 4], SA[3, 4]) end function idof_by_face(::FunctionSpace{<:Lagrange, 1}, shape::Tetra) ntuple(i -> SA[], nfaces(shape)) end function idof_by_face_with_bounds(::FunctionSpace{<:Lagrange, 1}, shape::Tetra) (SA[1, 3, 2], SA[1, 2, 4], SA[2, 3, 4], SA[3, 1, 4]) end # Prism function idof_by_edge(::FunctionSpace{<:Lagrange, 1}, shape::Prism) ntuple(i -> SA[], nedges(shape)) end function idof_by_edge_with_bounds(::FunctionSpace{<:Lagrange, 1}, shape::Prism) ( SA[1, 2], SA[2, 3], SA[3, 1], SA[1, 4], SA[2, 5], SA[3, 6], SA[4, 5], SA[5, 6], SA[6, 4], ) end function idof_by_face(::FunctionSpace{<:Lagrange, 1}, shape::Prism) ntuple(i -> SA[], nfaces(shape)) end function idof_by_face_with_bounds(::FunctionSpace{<:Lagrange, 1}, shape::Prism) (SA[1, 2, 5, 4], SA[2, 3, 6, 5], SA[3, 1, 4, 6], SA[1, 3, 2], SA[4, 5, 6]) end # Pyramid function idof_by_edge(::FunctionSpace{<:Lagrange, 1}, shape::Pyramid) ntuple(i -> SA[], nedges(shape)) end function idof_by_edge_with_bounds(::FunctionSpace{<:Lagrange, 1}, shape::Pyramid) (SA[1, 2], SA[2, 3], SA[3, 4], SA[4, 1], SA[1, 5], SA[2, 5], SA[3, 5], SA[4, 5]) end function idof_by_face(::FunctionSpace{<:Lagrange, 1}, shape::Pyramid) ntuple(i -> SA[], nfaces(shape)) end function idof_by_face_with_bounds(::FunctionSpace{<:Lagrange, 1}, shape::Pyramid) (SA[1, 4, 3, 2], SA[1, 2, 5], SA[2, 3, 5], SA[3, 4, 5], SA[4, 1, 5]) end # Generic versions for Lagrange 0 and 1 (any shape) get_coords(::FunctionSpace{<:Lagrange, 0}, shape::AbstractShape) = (center(shape),) get_coords(::FunctionSpace{<:Lagrange, 1}, shape::AbstractShape) = get_coords(shape) # Line, Square, Cube function _make_staticvector(x) if isa(x, SVector) || !(length(x) < MAX_LENGTH_STATICARRAY) return x else return SA[x] end end function _coords_gen_impl(shape::AbstractShape, quad::AbstractQuadrature) quadrule = QuadratureRule(shape, quad) nodes = _make_staticvector.(get_nodes(quadrule)) return :(tuple($(nodes...))) end @generated function _coords_gen( ::Shape, ::Quad, ) where {Shape <: AbstractShape, Quad <: AbstractQuadrature} _coords_gen_impl(Shape(), Quad()) end function _get_coords( fs::FunctionSpace{<:Lagrange, D}, shape::Union{Line, Square, Cube}, ) where {D} quadtype = lagrange_quadrature_type(fs) quad = Quadrature(quadtype, Val(D)) _coords_gen(shape, quad) end get_coords(::FunctionSpace{<:Lagrange, 0}, shape::Line) = (center(shape),) get_coords(::FunctionSpace{<:Lagrange, 0}, shape::Square) = (center(shape),) get_coords(::FunctionSpace{<:Lagrange, 0}, shape::Cube) = (center(shape),) get_coords(fs::FunctionSpace{<:Lagrange, 1}, shape::Line) = _get_coords(fs, shape) get_coords(fs::FunctionSpace{<:Lagrange, 1}, shape::Square) = _get_coords(fs, shape) get_coords(fs::FunctionSpace{<:Lagrange, 1}, shape::Cube) = _get_coords(fs, shape) get_coords(fs::FunctionSpace{<:Lagrange, D}, shape::Line) where {D} = _get_coords(fs, shape) function get_coords(fs::FunctionSpace{<:Lagrange, D}, shape::Square) where {D} _get_coords(fs, shape) end get_coords(fs::FunctionSpace{<:Lagrange, D}, shape::Cube) where {D} = _get_coords(fs, shape) # Triangle function get_coords(::FunctionSpace{<:Lagrange, 2}, shape::Triangle) ( get_coords(shape)..., sum(get_coords(shape, [1, 2])) / 2, sum(get_coords(shape, [2, 3])) / 2, sum(get_coords(shape, [3, 1])) / 2, ) end function get_coords(::FunctionSpace{<:Lagrange, 3}, shape::Triangle) ( get_coords(shape)..., (2 / 3) * get_coords(shape, 1) + (1 / 3) * get_coords(shape, 2), (1 / 3) * get_coords(shape, 1) + (2 / 3) * get_coords(shape, 2), (2 / 3) * get_coords(shape, 2) + (1 / 3) * get_coords(shape, 3), (1 / 3) * get_coords(shape, 2) + (2 / 3) * get_coords(shape, 3), (2 / 3) * get_coords(shape, 3) + (1 / 3) * get_coords(shape, 1), (1 / 3) * get_coords(shape, 3) + (2 / 3) * get_coords(shape, 1), sum(get_coords(shape)) / 3, ) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
4343
# This file gathers all Taylor-related interpolations struct Taylor <: AbstractFunctionSpaceType end FunctionSpace(::Val{:Taylor}, degree::Integer) = FunctionSpace(Taylor(), degree) basis_functions_style(::FunctionSpace{<:Taylor}) = ModalBasisFunctionsStyle() """ shape_functions(::FunctionSpace{<:Taylor}, ::AbstractShape, ξ) # Implementation For N > 1, the default version consists in "replicating" the shape functions. If `shape_functions` returns the vector `[λ₁; λ₂; λ₃]`, and if the `FESpace` is of size `2`, then this default behaviour consists in returning the matrix `[λ₁ 0; λ₂ 0; λ₃ 0; 0 λ₁; 0 λ₂; 0 λ₃]`. # Any shape, order 0 ``\\hat{\\lambda}(\\xi) = 1`` # Line ## Order 1 ```math \\hat{\\lambda}_1(\\xi) = 1 \\hspace{1cm} \\hat{\\lambda}_1(\\xi) = \\frac{\\xi}{2} ``` # Square ## Order 1 ```math \\begin{aligned} & \\hat{\\lambda}_1(\\xi, \\eta) = 0 \\\\ & \\hat{\\lambda}_2(\\xi, \\eta) = \\frac{\\xi}{2} \\\\ & \\hat{\\lambda}_3(\\xi, \\eta) = \\frac{\\eta}{2} \\end{aligned} ``` """ function shape_functions( fs::FunctionSpace{<:Taylor}, ::Val{N}, shape::AbstractShape, ξ, ) where {N} #::Union{T,AbstractVector{T}} ,T<:Number if N == 1 return _scalar_shape_functions(fs, shape, ξ) elseif N < MAX_LENGTH_STATICARRAY return kron(SMatrix{N, N}(1I), _scalar_shape_functions(fs, shape, ξ)) else return kron(Diagonal([1.0 for i in 1:N]), _scalar_shape_functions(fs, shape, ξ)) end end function shape_functions( fs::FunctionSpace{<:Taylor, D}, n::Val{N}, shape::AbstractShape, ) where {D, N} ξ -> shape_functions(fs, n, shape, ξ) end # Shared functions for all Taylor elements of some kind function _scalar_shape_functions(::FunctionSpace{<:Taylor, 0}, ::AbstractShape, ξ) return SA[one(eltype(ξ))] end # Functions for Line shape """ ∂λξ_∂ξ(::FunctionSpace{<:Taylor}, ::Val{1}, ::AbstractShape, ξ) # Line ## Order 0 ``\\nabla \\hat{\\lambda}(\\xi) = 0`` ## Order 1 ```math \\nabla \\hat{\\lambda}_1(\\xi) = 0 \\hspace{1cm} \\nabla \\hat{\\lambda}_1(\\xi) = \\frac{1}{2} ``` # Square ## Order 0 ```math \\hat{\\lambda}_1(\\xi, \\eta) = \\begin{pmatrix} 0 \\\\ 0 \\end{pmatrix} ``` ## Order 1 ```math \\begin{aligned} & \\nabla \\hat{\\lambda}_1(\\xi, \\eta) = \\begin{pmatrix} 0 \\\\ 0 \\end{pmatrix} \\\\ & \\nabla \\hat{\\lambda}_2(\\xi, \\eta) = \\begin{pmatrix} \\frac{1}{2} \\\\ 0 \\end{pmatrix} \\\\ & \\nabla \\hat{\\lambda}_3(\\xi, \\eta) = \\begin{pmatrix} 0 \\\\ \\frac{1}{2} \\end{pmatrix} \\end{aligned} ``` """ function ∂λξ_∂ξ(::FunctionSpace{<:Taylor, 0}, ::Val{1}, ::Line, ξ) return SA[zero(eltype(ξ))] end function _scalar_shape_functions(::FunctionSpace{<:Taylor, 1}, ::Line, ξ) return SA[ 1.0 ξ[1] / 2 ] end function ∂λξ_∂ξ(::FunctionSpace{<:Taylor, 1}, ::Val{1}, ::Line, ξ) return SA[ 0.0 1.0 / 2.0 ] end # Functions for Square shape function ∂λξ_∂ξ(::FunctionSpace{<:Taylor, 0}, ::Val{1}, ::Union{Square, Triangle}, ξ) _zero = zero(eltype(ξ)) return SA[_zero _zero] end function _scalar_shape_functions(::FunctionSpace{<:Taylor, 1}, ::Square, ξ) return SA[ 1.0 ξ[1] / 2 ξ[2] / 2 ] end function ∂λξ_∂ξ(::FunctionSpace{<:Taylor, 1}, ::Val{1}, ::Square, ξ) return SA[ 0.0 0.0 1.0/2 0.0 0.0 1.0/2 ] end # Number of dofs get_ndofs(::FunctionSpace{<:Taylor, N}, ::Line) where {N} = N + 1 get_ndofs(::FunctionSpace{<:Taylor, 0}, ::Union{Square, Triangle}) = 1 get_ndofs(::FunctionSpace{<:Taylor, 1}, ::Union{Square, Triangle}) = 3 # For Taylor base there are never any dof on vertex, edge or face function idof_by_vertex(::FunctionSpace{<:Taylor, N}, shape::AbstractShape) where {N} fill(Int[], nvertices(shape)) end function idof_by_edge(::FunctionSpace{<:Taylor, N}, shape::AbstractShape) where {N} ntuple(i -> SA[], nedges(shape)) end function idof_by_edge_with_bounds( ::FunctionSpace{<:Taylor, N}, shape::AbstractShape, ) where {N} ntuple(i -> SA[], nedges(shape)) end function idof_by_face(::FunctionSpace{<:Taylor, N}, shape::AbstractShape) where {N} ntuple(i -> SA[], nfaces(shape)) end function idof_by_face_with_bounds( ::FunctionSpace{<:Taylor, N}, shape::AbstractShape, ) where {N} ntuple(i -> SA[], nfaces(shape)) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
10158
abstract type AbstractComputeQuadratureStyle end #struct BroadcastComputeQuadratureStyle <: AbstractComputeQuadratureStyle end struct MapComputeQuadratureStyle <: AbstractComputeQuadratureStyle end ComputeQuadratureStyle(::Type{<:Any}) = MapComputeQuadratureStyle() #default ComputeQuadratureStyle(op) = ComputeQuadratureStyle(typeof(op)) """ integrate_on_ref_element(g, cellinfo::CellInfo, quadrature::AbstractQuadrature, [::T]) where {N,[T<:AbstractComputeQuadratureStyle]} integrate_on_ref_element(g, faceinfo::FaceInfo, quadrature::AbstractQuadrature, [::T]) where {N,[T<:AbstractComputeQuadratureStyle]} Integrate a function `g` over a cell/face described by `cellinfo`/`faceinfo`. The function `g` can be expressed in the reference or the physical space corresponding to the cell, both cases are automatically handled by applying necessary mapping when needed. If the last argument is given, computation is optimized according to the given concrete type `T<:AbstractComputeQuadratureStyle`. """ function integrate_on_ref_element(g, eltInfo, quadrature::AbstractQuadrature) integrate_on_ref_element(g, eltInfo, quadrature, ComputeQuadratureStyle(g)) end function integrate_on_ref_element( g, elementInfo::Union{CellInfo, FaceInfo}, quadrature::AbstractQuadrature, mapstyle::MapComputeQuadratureStyle, ) _g(ξ) = g(ElementPoint(ξ, elementInfo, ReferenceDomain())) integrate_on_ref_element( _g, get_element_type(elementInfo), nodes(elementInfo), quadrature, mapstyle, ) end function integrate_on_ref_element( g, ctype, cnodes, quadrature::AbstractQuadrature, mapstyle::MapComputeQuadratureStyle, ) f = Base.Fix1(_apply_metric, (g, ctype, cnodes)) int = apply_quadrature(f, ctype, cnodes, quadrature, mapstyle) return int end # Integration on a node is immediate function integrate_on_ref_element( g, ::AbstractEntityType{0}, cnodes, ::AbstractQuadrature, ::MapComputeQuadratureStyle, ) # Whatever the "reference coordinate" ξ that we choose, it will always map to the correct # node physical coordinate. So we chose to evaluate in ξ = 0. return g(0.0) end function _apply_metric(g_and_c::T, qnode::T1) where {T, T1} g, ctype, cnodes = g_and_c ξ = get_coords(qnode) m = mapping_det_jacobian(topology_style(ctype, cnodes), ctype, cnodes, ξ) m * g(ξ) end """ apply_quadrature( g_ref, shape::AbstractShape, quadrature::AbstractQuadrature, ::MapComputeQuadratureStyle, ) Apply quadrature rule to function `g_ref` expressed on reference shape `shape`. Computation is optimized according to the given concrete type `T<:AbstractComputeQuadratureStyle`. """ function apply_quadrature( g_ref, shape::AbstractShape, quadrature::AbstractQuadrature, ::MapComputeQuadratureStyle, ) quadrule = QuadratureRule(shape, quadrature) # --> TEMPORARY: ALTERING THE QUADNODES TO BYPASS OPERATORS / TestFunctionInterpolator quadnodes = map(get_coords, get_quadnodes(quadrule)) # <-- TEMPORARY: _apply_quadrature(g_ref, get_weights(quadrule), quadnodes, g_ref(quadnodes[1])) end # splitting the previous function to have function barrier... @inline function _apply_quadrature(g_ref, ω, xq::SVector{N}, ::T) where {N, T} u = map(g_ref, xq)::SVector{N, T} _apply_quadrature1(ω, u) end @inline function _apply_quadrature1(ω, u) wu = map(_mapquad, ω, u) _apply_quadrature2(wu) end _apply_quadrature2(wu) = reduce(_mapsum, wu) _mapsum(a, b) = map(+, a, b) _mapsum(a::NullOperator, b::NullOperator) = a _mapquad(ω, u) = map(Base.Fix1(*, ω), u) """ apply_quadrature_v2( g_ref, shape::AbstractShape, quadrature::AbstractQuadrature, ::MapComputeQuadratureStyle, ) Alternative version of `apply_quadrature` thats seems to be more efficient for face integration (this observation is not really understood) """ function apply_quadrature_v2( g_ref::G, shape::AbstractShape, quadrature::AbstractQuadrature, ::MapComputeQuadratureStyle, ) where {G} quadrule = QuadratureRule(shape, quadrature) # --> TEMPORARY: ALTERING THE QUADNODES TO BYPASS OPERATORS / TestFunctionInterpolator quadnodes = map(get_coords, get_quadnodes(quadrule)) # <-- TEMPORARY: _apply_quadrature_v2(g_ref, get_weights(quadrule), quadnodes) end # splitting the previous function to have function barrier... function _apply_quadrature_v2(g_ref, ω, xq) fquad(w, x) = _mapquad(w, g_ref(x)) mapreduce(fquad, _mapsum, ω, xq) end # Below are "dispatch functions" to select the more appropriate quadrature function function apply_quadrature( g::G, ctype::AbstractEntityType, cnodes::CN, quadrature::AbstractQuadrature, qStyle::AbstractComputeQuadratureStyle, ) where {G, CN} apply_quadrature(topology_style(ctype, cnodes), g, shape(ctype), quadrature, qStyle) end function apply_quadrature( ::isVolumic, g, shape::AbstractShape, quadrature::AbstractQuadrature, qStyle::MapComputeQuadratureStyle, ) apply_quadrature(g, shape, quadrature, qStyle) end function apply_quadrature( ::isSurfacic, g::G, shape::AbstractShape, quadrature::AbstractQuadrature, qStyle::MapComputeQuadratureStyle, ) where {G} apply_quadrature_v2(g, shape, quadrature, qStyle) end function apply_quadrature( ::isCurvilinear, g, shape::AbstractShape, quadrature::AbstractQuadrature, qStyle::MapComputeQuadratureStyle, ) apply_quadrature_v2(g, shape, quadrature, qStyle) end struct Integrand{N, F} f::F end Integrand(f::Tuple) = Integrand{length(f), typeof(f)}(f) Integrand(f) = Integrand{1, typeof(f)}(f) get_function(integrand::Integrand) = integrand.f Base.getindex(integrand::Integrand, i) = get_function(integrand)[i] @inline function Base.getindex(integrand::Integrand{N, F}, i) where {N, F <: Tuple} map(_f -> _f[i], get_function(integrand)) end const ∫ = Integrand """ -(a::Integrand) Soustraction on an `Integrand` is treated as a multiplication by "(-1)" : `-a ≡ ((-1)*a)` """ Base.:-(a::Integrand) = Integrand((-1) * get_function(a)) Base.:+(a::Integrand) = a struct Integration{I <: Integrand, M <: Measure} integrand::I measure::M end get_integrand(integration::Integration) = integration.integrand get_measure(integration::Integration) = integration.measure Base.getindex(integration::Integration, i) = get_integrand(integration)[i] Base.:*(integrand::Integrand, measure::Measure) = Integration(integrand, measure) """ *(a::Number, b::Integration) *(a::Integration, b::Number) Multiplication of an `Integration` is based on a rewriting rule following the linearity rules of integration : `k*∫(f(x))dx => ∫(k*f(x))dx` """ function Base.:*(a::Number, b::Integration) Integration(Integrand(a * get_function(get_integrand(b))), get_measure(b)) end function Base.:*(a::Integration, b::Number) Integration(Integrand(get_function(get_integrand(a)) * b), get_measure(a)) end """ -(a::Integration) Soustraction on an `Integration` is treated as a multiplication by "(-1)" : `-a ≡ ((-1)*a)` """ Base.:-(a::Integration) = (-1) * a Base.:+(a::Integration) = a struct MultiIntegration{N, I <: Tuple{Vararg{Integration, N}}} integrations::I end # implement AbstractLazy inteface: LazyOperators.pretty_name(a::Integration) = "Integration: " * pretty_name(get_measure(a)) LazyOperators.pretty_name_style(a::Integration) = Dict(:color => :yellow) function LazyOperators.show_lazy_operator( a::Integration; level = 1, indent = 4, islast = (true,), ) level == 1 && println("\n---------------") print_tree_prefix(level, indent, islast) printstyled(pretty_name(a) * " \n"; pretty_name_style(a)...) show_lazy_operator( get_function(get_integrand(a)); level = level + 1, indent = indent, islast = (islast..., true), ) level == 1 && println("---------------") end function MultiIntegration(a::NTuple{N, <:Integration}) where {N} MultiIntegration{length(a), typeof(a)}(a) end function MultiIntegration(a::Integration, b::Vararg{Integration, N}) where {N} MultiIntegration((a, b...)) end Base.getindex(a::MultiIntegration, ::Val{I}) where {I} = a.integrations[I] Base.iterate(a::MultiIntegration, i) = iterate(a.integrations, i) Base.iterate(a::MultiIntegration) = iterate(a.integrations) # rewriting rules to deal with the additions of several `Integration` Base.:+(a::Integration, b::Integration) = MultiIntegration(a, b) Base.:+(a::MultiIntegration, b::Integration) = MultiIntegration(a.integrations..., b) Base.:+(a::Integration, b::MultiIntegration) = MultiIntegration(a, b.integrations...) function Base.:+(a::MultiIntegration, b::MultiIntegration) MultiIntegration((a.integrations..., b.integrations...)) end Base.:+(a::MultiIntegration) = a Base.:-(a::Integration, b::Integration) = MultiIntegration(a, -b) Base.:-(a::MultiIntegration, b::Integration) = MultiIntegration(a.integrations..., -b) function Base.:-(a::Integration, b::MultiIntegration) MultiIntegration(a, map(-, b.integrations)...) end function Base.:-(a::MultiIntegration, b::MultiIntegration) MultiIntegration((a.integrations..., map(-, b.integrations)...)) end Base.:-(a::MultiIntegration) = MultiIntegration(map(-, a.integrations)...) # implement AbstractLazy inteface: LazyOperators.pretty_name(::MultiIntegration{N}) where {N} = "MultiIntegration: (N=$N)" LazyOperators.pretty_name_style(a::MultiIntegration) = Dict(:color => :yellow) function LazyOperators.show_lazy_operator( multiIntegration::MultiIntegration; level = 1, indent = 4, islast = (true,), ) level == 1 && println("\n---------------") print_tree_prefix(level, indent, islast) printstyled( pretty_name(multiIntegration) * ": \n"; pretty_name_style(multiIntegration)..., ) show_lazy_operator( multiIntegration.integrations; level = level + 1, islast = islast, printTupleOp = false, ) level == 1 && println("---------------") nothing end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1615
abstract type AbstractMeasure{D <: AbstractDomain, Q <: AbstractQuadrature} end get_domain_type(::AbstractMeasure{D}) where {D} = D get_quadrature_type(::AbstractMeasure{D, Q}) where {D, Q} = Q get_domain(m::AbstractMeasure) = m.domain get_quadrature(m::AbstractMeasure) = m.quadrature function LazyOperators.pretty_name(m::AbstractMeasure) "Measure(domain = " * pretty_name(get_domain(m)) * ", quadrature type = " * string(get_quadrature_type(m)) * ")" end """ A `Measure` is geometrical domain of integration associated to a way to integrate on it (i.e a quadrature rule). `Q` is the quadrature type used to integrate expressions using this measure. """ struct Measure{D <: AbstractDomain, Q <: AbstractQuadrature} <: AbstractMeasure{D, Q} domain::D quadrature::Q end """ Measure(domain::AbstractDomain, degree::Integer) Measure(domain::AbstractDomain, ::Val{degree}) where {degree} Build a `Measure` on the designated `AbstractDomain` with a default quadrature of degree `degree`. # Arguments - `domain::AbstractDomain` : the domain to integrate over - `degree` : the degree of the quadrature rule (`Legendre` quadrature type by default) # Examples ```julia-repl julia> mesh = line_mesh(10) julia> Ω = CellDomain(mesh) julia> dΩ = Measure(Ω, 2) ``` """ Measure(domain::AbstractDomain, degree::Integer) = Measure(domain, Val(degree)) function Measure(domain::AbstractDomain, degree::Val{D}) where {D} Measure(domain, Quadrature(degree)) end """ Return a LazyOperator representing a face normal """ get_face_normals(::Measure{<:AbstractFaceDomain}) = FaceNormal()
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
5215
abstract type AbstractIoHandler end struct GMSHIoHandler <: AbstractIoHandler end struct HDF5IoHandler <: AbstractIoHandler end struct JLD2IoHandler <: AbstractIoHandler end struct VTKIoHandler <: AbstractIoHandler end """ read_file([handler::AbstractIoHandler,] filepath::String; domainNames = nothing, varnames = nothing, topodim = 0, kwargs...,) Read the mesh and associated data in the given file. Returns a NamedTuple with the following keys: * mesh -> the Bcube mesh * data -> dictionnary of FlowSolutionName => (dictionnary of VariableName => MeshData) * to be defined : stuff related to subdomains If `domainNames` is an empty list/array, all the domains found will be read and merged. Otherwise, `domainNames` can be a filtered list/array of the domain names to retain. If `varnames` is set to `nothing`, no variables will be read, which is the behavior of `read_mesh`. To read all the variables, `varnames` must be set to `"*"`. The argument `topodim` can be used to force and/or select the elements of this topological dimension to be interpreted as "volumic". Leave it to `0` to let the reader determines the topological dimension automatically. The same goes for `spacedim`. # Example ```julia result = read_file("file.cgns"; varnames = ["Temperature", "Density"], verbose = true) @show ncells(result.mesh) @show keys(result.data) """ function read_file( handler::AbstractIoHandler, filepath::String; domainNames = String[], varnames = nothing, topodim = 0, spacedim = 0, kwargs..., ) error( "'read_file' is not implemented for $(typeof(handler)). Have you loaded the extension?", ) end function read_file(filepath::String; domainNames = String[], varnames = nothing, kwargs...) read_file(_filename_to_handler(filepath), filepath; domainNames, varnames, kwargs...) end """ Similar as `read_file`, but return only the mesh. """ function read_mesh( handler::AbstractIoHandler, filepath::String, domainNames = String[], kwargs..., ) res = read_file(handler, filepath; domainNames, kwargs...) return res.mesh end function read_mesh(filepath::String; kwargs...) read_mesh(_filename_to_handler(filepath), filepath; kwargs...) end """ write_file( [handler::AbstractIoHandler,] basename::String, mesh::AbstractMesh, data = nothing, it::Integer = -1, time::Real = 0.0; mesh_degree::Integer = 1, functionSpaceType::AbstractFunctionSpaceType = Lagrange(), discontinuous::Bool = true, collection_append::Bool = false, kwargs..., ) Write a set of `AbstractLazy` to a file. `data` can be provided as a `Dict{String, AbstractLazy}` if they share the same "container" (~FlowSolution), or as a `Dict{String, T}` where T is the previous Dict type described. To write cell-centered data, wrapped your input into a `MeshCellData` (for instance using Bcube.cell_mean). # Implementation To specialize this method, please specialize: write_file( handler::AbstractIoHandler, basename::String, mesh::AbstractMesh, U_export::AbstractFESpace, data = nothing, it::Integer = -1, time::Real = 0.0; collection_append::Bool = false, kwargs..., ) """ function write_file( handler::AbstractIoHandler, basename::String, mesh::AbstractMesh, data = nothing, it::Integer = -1, time::Real = 0.0; mesh_degree::Integer = 1, functionSpaceType::AbstractFunctionSpaceType = Lagrange(), discontinuous::Bool = true, collection_append::Bool = false, kwargs..., ) # Build FESpace corresponding to asked degree, func space and discontinuous U_export = TrialFESpace( FunctionSpace(functionSpaceType, mesh_degree), mesh; isContinuous = !discontinuous, ) # Call version with U_export write_file( handler, basename, mesh, U_export, data, it, time; collection_append, kwargs..., ) end function write_file( handler::AbstractIoHandler, basename::String, mesh::AbstractMesh, U_export::AbstractFESpace, data = nothing, it::Integer = -1, time::Real = 0.0; collection_append::Bool = false, kwargs..., ) error("'write_file' is not implemented for $(typeof(handler))") end function write_file(basename::String, args...; kwargs...) write_file(_filename_to_handler(basename), basename, args...; kwargs...) end """ check_input_file([handler::AbstractIoHandler,] filepath::String) Check that the input file is compatible with the Bcube reader, and print warnings and/or errors if it's not. """ function check_input_file(handler::AbstractIoHandler, filepath::String) end check_input_file(filename::String) = check_input_file(_filename_to_handler(filename)) function _filename_to_handler(filename::String) ext = last(splitext(filename)) if ext in (".msh",) return GMSHIoHandler() elseif ext in (".pvd", ".vtk", ".vtu") return VTKIoHandler() elseif ext in (".cgns", ".hdf", ".hdf5") return HDF5IoHandler() end error("Could not find a handler for the filename $filename") end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
29889
# COMMON """ mapping(ctype::AbstractEntityType, cnodes, ξ) mapping(cshape::AbstractShape, cnodes, ξ) Map the reference shape on the local shape. # Implementation This function must be implemented for all shape. # `::Bar2_t` Map the reference 2-nodes bar [-1,1] on the local bar: ```math F(\\xi) = \\dfrac{x_r - x_l}{2} \\xi + \\dfrac{x_r + x_l}{2} ``` # `::Tri3_t` Map the reference 3-nodes Triangle [0,1] x [0,1] on the local triangle. ```math F(\\xi \\\\ \\eta) = (1 - \\xi - \\eta) M_1 + x M_2 + y M_3 ``` # `::Quad4_t` Map the reference 4-nodes square [-1,1] x [-1,1] on the 4-quadrilateral. # `::Tri6_t` Map the reference 6-nodes triangle [0,1] x [0,1] on the P2 curved-triangle. `` F(\\xi) = \\sum \\lambda_i(\\xi) x_i `` where ``\\lambda_i`` are the Lagrange P2 shape functions and ``x_i`` are the local curved-triangle vertices' coordinates. # `::Quad9_t` Map the reference 4-nodes square [-1,1] x [-1,1] on the P2 curved-quadrilateral. `` F(\\xi) = \\sum \\lambda_i(\\xi) x_i `` where ``\\lambda_i`` are the Lagrange P2 shape functions and ``x_i`` are the local curved-quadrilateral vertices' coordinates. # `::Hexa8_t` Map the reference 8-nodes cube [-1,1] x [-1,1] x [-1,1] on the 8-hexa. # `::Hexa27_t` Map the reference 8-nodes cube [-1,1] x [-1,1] x [-1,1] on the 27-hexa. # `::Penta6_t` Map the reference 6-nodes prism [0,1] x [0,1] x [-1,1] on the 6-penta (prism). # `::Pyra5_t` Map the reference 5-nodes pyramid [-1,1] x [-1,1] x [0,1] on the 5-pyra. See https://www.math.u-bordeaux.fr/~durufle/montjoie/pyramid.php """ function mapping(type_or_shape, cnodes, ξ) error("Function 'mapping' is not defined for $(typeof(type_or_shape))") end mapping(type_or_shape, cnodes) = ξ -> mapping(type_or_shape, cnodes, ξ) """ mapping_inv(::AbstractEntityType, cnodes, x) Map the local shape on the reference shape. # Implementation This function does not have to be implemented for all shape. # `::Bar2_t` Map the local bar on the reference 2-nodes bar [-1,1]: ``F^{-1}(x) = \\dfrac{2x - x_r - x_l}{x_r - x_l}`` # `::Tri3_t` Map the local triangle on the reference 3-nodes Triangle [0,1] x [0,1]. TODO: check this formulae with SYMPY ```math F^{-1} \\begin{pmatrix} x \\\\ y \\end{pmatrix} = \\frac{1}{x_1(y_2-y_3) + x_2(y_3-y_1) + x_3(y_1-y_2)} \\begin{pmatrix} (y_3-y_1)x + (x_1 - x_3)y + (x_3 y_1 - x_1 y_3) \\\\ (y_1-y_2)x + (x_2 - x_1)x + (x_1 y_2 - x_2 y_1) \\end{pmatrix} ``` # ::`Quad4_t` Map the PARALLELOGRAM quadrilateral on the reference 4-nodes square [-1,1] x [-1,1]. Warning : this mapping is only corrects for parallelogram quadrilateral, not for any quadrilateral. ----- TODO: check this formulae with SYMPY ----- ```math F^{-1} \\begin{pmatrix} x \\\\ y \\end{pmatrix} = \\begin{pmatrix} a_1 x + b_1 y + c_1 \\\\ a_2 x + b_2 y + c_2 \\end{pmatrix} ``` with ```math \\begin{aligned} a_1 & = \\dfrac{-2 (y_3-y_2)}{\\Delta} \\\\ b_1 & = \\dfrac{2 (x_3-x_2)}{\\Delta} \\\\ c_1 & = -1 - a_1 x_1 - b_1 y_1 \\\\ a_2 & = \\dfrac{-2 (y_1-y_2)}{\\Delta} \\\\ b_2 & = \\dfrac{2 (x_1 - x_2)}{\\Delta} \\\\ c_2 & = -1 - a_2 x_1 - b_2 y_1 \\end{aligned} ``` where `` \\Delta = (x_1 - x_2)(y_3 - y_2) - (x_3 - x_2)(y_1 - y_2)`` """ function mapping_inv(::AbstractEntityType, cnodes, x) error("Function 'mapping_inv' is not defined") end mapping_inv(ctype::AbstractEntityType, cnodes) = x -> mapping_inv(ctype, cnodes, x) """ mapping_jacobian(ctype::AbstractEntityType, cnodes, ξ) Jacobian matrix of the mapping : ``\\dfrac{\\partial F_i}{\\partial \\xi_j}``. # Implementation Default version using ForwardDiff, but can be specified for each shape. # `::Bar2_t` Mapping's jacobian matrix for the reference 2-nodes bar [-1, 1] to the local bar. ``\\dfrac{\\partial F}{\\partial \\xi} = \\dfrac{x_r - x_l}{2}`` # `::Bar3_t` Mapping's jacobian matrix for the reference 2-nodes bar [-1, 1] to the local bar. ``\\dfrac{\\partial F}{\\partial \\xi} = \\frac{1}{2} \\left( (2\\xi - 1) M_1 + (2\\xi + 1)M_2 - 4 \\xi M_3\\right) # `::Tri3_t` Mapping's jacobian matrix for the reference 3-nodes Triangle [0,1] x [0,1] to the local triangle mapping. ```math \\dfrac{\\partial F_i}{\\partial \\xi_j} = \\begin{pmatrix} M_2 - M_1 & M_3 - M_1 \\end{pmatrix} ``` # `::Quad4_t` Mapping's jacobian matrix for the reference square [-1,1] x [-1,1] to the 4-quadrilateral ```math \\frac{\\partial F}{\\partial \\xi} = -M_1 + M_2 + M_3 - M_4 + \\eta (M_1 - M_2 + M_3 - M_4) ``` ```math \\frac{\\partial F}{\\partial \\eta} = -M_1 - M_2 + M_3 + M_4 + \\xi (M_1 - M_2 + M_3 - M_4) ``` """ function mapping_jacobian(ctype::AbstractEntityType, cnodes, ξ) ForwardDiff.jacobian(η -> mapping(ctype, cnodes, η), ξ) end """ mapping_jacobian_inv(ctype::AbstractEntityType, cnodes, ξ) Inverse of the mapping jacobian matrix. This is not exactly equivalent to the `mapping_inv_jacobian` since this function is evaluated in the reference element. # Implementation Default version using ForwardDiff, but can be specified for each shape. # `::Bar2_t` Inverse of mapping's jacobian matrix for the reference 2-nodes bar [-1, 1] to the local bar. ```math \\dfrac{\\partial F}{\\partial \\xi}^{-1} = \\dfrac{2}{x_r - x_l} ``` # `::Bar3_t` Inverse of mapping's jacobian matrix for the reference 2-nodes bar [-1, 1] to the local bar. ```math \\dfrac{\\partial F}{\\partial \\xi}^{-1} = \\frac{2}{(2\\xi - 1) M_1 + (2\\xi + 1)M_2 - 4 \\xi M_3} ``` # `::Tri3_t` Inverse of mapping's jacobian matrix for the reference 3-nodes Triangle [0,1] x [0,1] to the local triangle mapping. ```math \\dfrac{\\partial F_i}{\\partial \\xi_j}^{-1} = \\frac{1}{(x_1 - x_2)(y_1 - y_3) - (x_1 - x_3)(y_1 - y_2)} \\begin{pmatrix} -y_1 + y_3 & x_1 - x_3 \\\\ y_1 - y_2 & -x_1 + x_2 \\end{pmatrix} ``` # `::Quad4_t` Inverse of mapping's jacobian matrix for the reference square [-1,1] x [-1,1] to the 4-quadrilateral """ function mapping_jacobian_inv(ctype::AbstractEntityType, cnodes, ξ) inv(ForwardDiff.jacobian(mapping(ctype, cnodes), ξ)) end """ mapping_inv_jacobian(ctype::AbstractEntityType, cnodes, x) Jacobian matrix of the inverse mapping : ``\\dfrac{\\partial F_i^{-1}}{\\partial x_j}`` Contrary to `mapping_jacobian_inv`, this function is not always defined because the inverse mapping, F^-1, is not always defined. # Implementation Default version using LinearAlgebra to inverse the matrix, but can be specified for each shape (if it exists). # `::Bar2_t` Mapping's jacobian matrix for the local bar to the reference 2-nodes bar [-1, 1]. ```math \\dfrac{\\partial F^{-1}}{\\partial x} = \\dfrac{2}{x_r - x_l} ``` # `::Tri3_t` Mapping's jacobian matrix for the local triangle to the reference 3-nodes Triangle [0,1] x [0,1] mapping. ----- TODO: check this formulae with SYMPY ----- ```math \\frac{\\partial F_i^{-1}}{\\partial x_j} = \\frac{1}{x_1 (y_2 - y_3) + x_2 (y_3 - y_1) + x_3 (y_1 - y_2)} \\begin{pmatrix} y_3 - y_1 & x_1 - x_3 \\\\ y_1 - y_2 & x_2 - x_1 \\end{pmatrix} ``` """ function mapping_inv_jacobian(ctype::AbstractEntityType, cnodes, x) inv(mapping_jacobian(ctype, cnodes, mapping_inv(ctype, cnodes, x))) end """ mapping_det_jacobian(ctype::AbstractEntityType, cnodes, ξ) mapping_det_jacobian(::TopologyStyle, ctype::AbstractEntityType, cnodes, ξ) Absolute value of the determinant of the mapping Jacobian matrix, expressed in the reference element. # Implementation For a volumic cell (line in 1D, quad in 2D, cube in 3D), the default version uses `mapping_jacobian`, but the function can be specified for each shape. For a curvilinear cell (line in 2D, or in 3D), the formula is always J = ||F'|| where F is the mapping. Hence we always fallback to the "standard" version, like for the volumic case. Finally, the surfacic cell (quad in 3D) needs a special treatment, see [`mapping_jacobian_hypersurface`](@ref). # `::Bar2_t` Absolute value of the determinant of the mapping Jacobian matrix for the reference 2-nodes bar [-1,1] to the local bar mapping. ``|det(J(\\xi))| = \\dfrac{|x_r - x_l|}{2}`` # `::Tri3_t` Absolute value of the determinant of the mapping Jacobian matrix for the the reference 3-nodes Triangle [0,1] x [0,1] to the local triangle mapping. ``|J| = |(x_2 - x_1) (y_3 - y_1) - (x_3 - x_1) (y_2 - y_1)|`` """ function mapping_det_jacobian(ctype::AbstractEntityType, cnodes, ξ) abs(det(mapping_jacobian(ctype, cnodes, ξ))) end function mapping_det_jacobian(::isSurfacic, ctype, cnodes, ξ) jac = mapping_jacobian_hypersurface(ctype, cnodes, ξ) return abs(det(jac)) end function mapping_det_jacobian(::Union{isCurvilinear, isVolumic}, ctype, cnodes, ξ) mapping_det_jacobian(ctype, cnodes, ξ) end """ mapping_jacobian_hypersurface(ctype, cnodes, ξ) "Augmented" jacobian matrix of the mapping. Let's consider a ``\\mathbb{R}^2`` surface in ``\\mathbb{R}^3``. The mapping ``F_\\Gamma(\\xi, \\eta)`` maps the reference coordinate system to the physical coordinate system. It's jacobian ``J_\\Gamma`` is not squared. We can 'extend' this mapping to reach any point in ``\\mathbb{R}^3`` (and not only the surface) using ```math F(\\xi, \\eta, \\zeta) = F_\\Gamma(\\xi, \\eta) + \\zeta \\nu ``` where ``\\nu`` is the conormal. Then the restriction of the squared jacobian of ``F`` to the surface is simply ```math J|_\\Gamma = (J_\\Gamma~~\\nu) ``` """ function mapping_jacobian_hypersurface(ctype, cnodes, ξ) Jref = mapping_jacobian(ctype, cnodes, ξ) ν = cell_normal(ctype, cnodes, ξ) J = hcat(Jref, ν) return J end """ mapping_face(cshape::AbstractShape, side) mapping_face(cshape::AbstractShape, side, permutation) Build a mapping from the face reference element (corresponding to the `side`-th face of `cshape`) to the cell reference element (i.e the `cshape`). Build a mapping from the face reference element (corresponding to the `side`-th face of `cshape`) to the cell reference element (i.e the `cshape`). If `permutation` is present, the mapping is built using this permutation. """ function mapping_face(cshape::AbstractShape, side) f2n = faces2nodes(cshape, side) _coords = get_coords(cshape, f2n) fnodes = map(Node, _coords) return MappingFace(mapping(face_shapes(cshape, side), fnodes), nothing) end function mapping_face(cshape::AbstractShape, side, permutation) f2n = faces2nodes(cshape, side)[permutation] _coords = get_coords(cshape, f2n) fnodes = Node.(_coords) return MappingFace(mapping(face_shapes(cshape, side), fnodes), nothing) end struct MappingFace{F1, F2} f1::F1 f2::F2 end (m::MappingFace)(x) = m.f1(x) CallableStyle(::Type{<:MappingFace}) = IsCallableStyle() #---------------- POINT : this may seem stupid, but it is usefull for coherence mapping(::Node_t, cnodes, ξ) = cnodes[1].x mapping(::Point, cnodes, ξ) = mapping(Node_t(), cnodes, ξ) #---------------- LINE mapping(::Line, cnodes, ξ) = mapping(Bar2_t(), cnodes, ξ) function mapping_det_jacobian(ctype::AbstractEntityType{1}, cnodes, ξ) norm(mapping_jacobian(ctype, cnodes, ξ)) end function mapping(::Bar2_t, cnodes, ξ) (cnodes[2].x - cnodes[1].x) / 2.0 .* ξ + (cnodes[2].x + cnodes[1].x) / 2.0 end function mapping_inv(::Bar2_t, cnodes, x) SA[(2 * x[1] - cnodes[2].x[1] - cnodes[1].x[1]) / (cnodes[2].x[1] - cnodes[1].x[1])] end function mapping_jacobian(::Bar2_t, cnodes, ξ) axes(cnodes) == (Base.OneTo(2),) || error("Invalid number of nodes") @inbounds (cnodes[2].x .- cnodes[1].x) ./ 2.0 end function mapping_jacobian_inv(::Bar2_t, cnodes, ξ) @SMatrix[2.0 / (cnodes[2].x[1] .- cnodes[1].x[1])] end mapping_inv_jacobian(::Bar2_t, cnodes, x) = 2.0 / (cnodes[2].x[1] - cnodes[1].x[1]) mapping_det_jacobian(::Bar2_t, cnodes, ξ) = norm(cnodes[2].x - cnodes[1].x) / 2.0 function mapping(::Bar3_t, cnodes, ξ) ξ .* (ξ .- 1) / 2 .* cnodes[1].x .+ ξ .* (ξ .+ 1) / 2 .* cnodes[2].x .+ (1 .- ξ) .* (1 .+ ξ) .* cnodes[3].x end function mapping_jacobian(::Bar3_t, cnodes, ξ) (cnodes[1].x .* (2 .* ξ .- 1) + cnodes[2].x .* (2 .* ξ .+ 1) - cnodes[3].x .* 4 .* ξ) ./ 2 end function mapping_jacobian_inv(::Bar3_t, cnodes, ξ) 2.0 / (cnodes[1].x .* (2 .* ξ .- 1) + cnodes[2].x .* (2 .* ξ .+ 1) - cnodes[3].x .* 4 .* ξ) end #---------------- TRIANGLE P1 mapping(::Triangle, cnodes, ξ) = mapping(Tri3_t(), cnodes, ξ) function mapping(::Tri3_t, cnodes, ξ) return (1 - ξ[1] - ξ[2]) .* cnodes[1].x + ξ[1] .* cnodes[2].x + ξ[2] .* cnodes[3].x end function mapping_inv(::Tri3_t, cnodes, x) # Alias (should be inlined, but waiting for Ghislain's modification of Node) x1 = cnodes[1].x[1] x2 = cnodes[2].x[1] x3 = cnodes[3].x[1] y1 = cnodes[1].x[2] y2 = cnodes[2].x[2] y3 = cnodes[3].x[2] return SA[ (y3 - y1) * x[1] + (x1 - x3) * x[2] + (x3 * y1 - x1 * y3), (y1 - y2) * x[1] + (x2 - x1) * x[2] + (x1 * y2 - x2 * y1), ] / (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) end function mapping_jacobian(::Tri3_t, cnodes, ξ) return hcat(cnodes[2].x - cnodes[1].x, cnodes[3].x - cnodes[1].x) end function mapping_jacobian_inv(::Tri3_t, cnodes, ξ) x1 = cnodes[1].x[1] x2 = cnodes[2].x[1] x3 = cnodes[3].x[1] y1 = cnodes[1].x[2] y2 = cnodes[2].x[2] y3 = cnodes[3].x[2] return SA[ -y1+y3 x1-x3 y1-y2 -x1+x2 ] ./ ((x1 - x2) * (y1 - y3) - (x1 - x3) * (y1 - y2)) end function mapping_inv_jacobian(::Tri3_t, cnodes, x) x1 = cnodes[1].x[1] x2 = cnodes[2].x[1] x3 = cnodes[3].x[1] y1 = cnodes[1].x[2] y2 = cnodes[2].x[2] y3 = cnodes[3].x[2] return SA[ (y3-y1) (x1-x3) (y1-y2) (x2-x1) ] / (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) end function mapping_det_jacobian(::Tri3_t, cnodes, ξ) x1 = cnodes[1].x[1] x2 = cnodes[2].x[1] x3 = cnodes[3].x[1] y1 = cnodes[1].x[2] y2 = cnodes[2].x[2] y3 = cnodes[3].x[2] return abs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) end #---------------- Quad P1 mapping(::Square, cnodes, ξ) = mapping(Quad4_t(), cnodes, ξ) function mapping(::Quad4_t, cnodes, ξ) return ( (ξ[1] - 1) * (ξ[2] - 1) .* cnodes[1].x - (ξ[1] + 1) * (ξ[2] - 1) .* cnodes[2].x + (ξ[1] + 1) * (ξ[2] + 1) .* cnodes[3].x - (ξ[1] - 1) * (ξ[2] + 1) .* cnodes[4].x ) ./ 4 end function mapping_inv(::Quad4_t, cnodes, x) # Alias (should be inlined, but waiting for Ghislain's modification of Node) x1 = cnodes[1].x[1] x2 = cnodes[2].x[1] x3 = cnodes[3].x[1] y1 = cnodes[1].x[2] y2 = cnodes[2].x[2] y3 = cnodes[3].x[2] # Copied from fortran delta = (x1 - x2) * (y3 - y2) - (x3 - x2) * (y1 - y2) a = SA[-2.0 * (y3 - y2), -2.0 * (y1 - y2)] ./ delta b = SA[2.0 * (x3 - x2), 2.0 * (x1 - x2)] ./ delta c = SA[-1.0 - a[1] * x1 - b[1] * y1, -1.0 - a[2] * x1 - b[2] * y1] return a .* x[1] + b .* x[2] + c end function mapping_jacobian(::Quad4_t, cnodes, ξ) return hcat( -cnodes[1].x + cnodes[2].x + cnodes[3].x - cnodes[4].x + ξ[2] .* (cnodes[1].x - cnodes[2].x + cnodes[3].x - cnodes[4].x), -cnodes[1].x - cnodes[2].x + cnodes[3].x + cnodes[4].x + ξ[1] .* (cnodes[1].x - cnodes[2].x + cnodes[3].x - cnodes[4].x), ) ./ 4 end function mapping_jacobian_inv(::Quad4_t, cnodes::AbstractArray{<:Node{2, T}}, ξη) where {T} # Alias axes(cnodes) == (Base.OneTo(4),) || error("Invalid number of nodes") axes(ξη) == (Base.OneTo(2),) || error("Invalid number of coordinates") @inbounds begin x1, y1 = cnodes[1].x x2, y2 = cnodes[2].x x3, y3 = cnodes[3].x x4, y4 = cnodes[4].x ξ = ξη[1] η = ξη[2] end return 4 .* SA[ (1 - ξ) * (y1 - y4)+(1 + ξ) * (y2 - y3) (1 - ξ) * (x4 - x1)+(1 + ξ) * (x3 - x2) (1 - η) * (y2 - y1)+(1 + η) * (y3 - y4) (1 - η) * (x1 - x2)+(1 + η) * (x4 - x3) ] ./ ( ((1 - ξ) * (x4 - x1) + (1 + ξ) * (x3 - x2)) * ((1 - η) * (y2 - y1) + (1 + η) * (y3 - y4)) - ((1 - η) * (x2 - x1) + (1 + η) * (x3 - x4)) * ((1 - ξ) * (y4 - y1) + (1 + ξ) * (y3 - y2)) ) end function mapping_det_jacobian(::Quad4_t, cnodes::AbstractArray{<:Node{2, T}}, ξη) where {T} axes(cnodes) == (Base.OneTo(4),) || error("Invalid number of nodes") axes(ξη) == (Base.OneTo(2),) || error("Invalid number of coordinates") @inbounds begin x1, y1 = cnodes[1].x x2, y2 = cnodes[2].x x3, y3 = cnodes[3].x x4, y4 = cnodes[4].x ξ = ξη[1] η = ξη[2] end return abs( -((1 - ξ) * (x4 - x1) + (1 + ξ) * (x3 - x2)) * ((1 - η) * (y2 - y1) + (1 + η) * (y3 - y4)) + ((1 - η) * (x2 - x1) + (1 + η) * (x3 - x4)) * ((1 - ξ) * (y4 - y1) + (1 + ξ) * (y3 - y2)), ) / 16.0 end #---------------- TRIANGLE P2 function mapping(::Tri6_t, cnodes, ξ) # Shape functions λ₁ = (1 - ξ[1] - ξ[2]) * (1 - 2 * ξ[1] - 2 * ξ[2]) # = (1 - x - y)(1 - 2x - 2y) λ₂ = ξ[1] * (2 * ξ[1] - 1) # = x (2x - 1) λ₃ = ξ[2] * (2 * ξ[2] - 1) # = y (2y - 1) λ₁₂ = 4 * ξ[1] * (1 - ξ[1] - ξ[2]) # = 4x (1 - x - y) λ₂₃ = 4 * ξ[1] * ξ[2] λ₃₁ = 4 * ξ[2] * (1 - ξ[1] - ξ[2]) # = 4y (1 - x - y) # Is there a way to write this with a more consise way? # something like sum( (lambda, n) -> lambda * n, zip(lambda, nodes)) # Note that the use of parenthesis is mandatory here otherwise only the first line is returned return ( λ₁ .* cnodes[1].x + λ₂ .* cnodes[2].x + λ₃ .* cnodes[3].x + λ₁₂ .* cnodes[4].x + λ₂₃ .* cnodes[5].x + λ₃₁ .* cnodes[6].x ) end #---------------- PARAQUAD P2 function mapping(::Quad9_t, cnodes, ξ) # Shape functions λ₁ = ξ[1] * ξ[2] * (1 - ξ[1]) * (1 - ξ[2]) / 4 # = xy (1 - x)(1 - y) / 4 λ₂ = -ξ[1] * ξ[2] * (1 + ξ[1]) * (1 - ξ[2]) / 4 # = - xy (1 + x)(1 - y) / 4 λ₃ = ξ[1] * ξ[2] * (1 + ξ[1]) * (1 + ξ[2]) / 4 # = xy (1 + x)(1 + y) / 4 λ₄ = -ξ[1] * ξ[2] * (1 - ξ[1]) * (1 + ξ[2]) / 4 # = - xy (1 - x)(1 + y) / 4 λ₁₂ = -(1 + ξ[1]) * (1 - ξ[1]) * ξ[2] * (1 - ξ[2]) / 2 # = - (1 + x)(1 -x)y(1 - y) / 2 λ₂₃ = ξ[1] * (1 + ξ[1]) * (1 - ξ[2]) * (1 + ξ[2]) / 2 # = x(1 + x)(1 - y)(1 + y) / 2 λ₃₄ = (1 - ξ[1]) * (1 + ξ[1]) * ξ[2] * (1 + ξ[2]) / 2 # = (1 - x)(1 + x)y(1 + y) /2 λ₄₁ = -ξ[1] * (1 - ξ[1]) * (1 - ξ[2]) * (1 + ξ[2]) / 2 # = - x(1 - x)(1 - y)(1 + y) / 2 λ₁₂₃₄ = (1 - ξ[1]) * (1 + ξ[1]) * (1 - ξ[2]) * (1 + ξ[2]) # = (1 - x)(1 + x)(1 - y)(1 + y) # Is there a way to write this with a more consise way? # something like sum( (lambda, n) -> lambda * n, zip(lambda, nodes)) # Note that the use of parenthesis is mandatory here otherwise only the first line is returned return ( λ₁ .* cnodes[1].x + λ₂ .* cnodes[2].x + λ₃ .* cnodes[3].x + λ₄ .* cnodes[4].x + λ₁₂ .* cnodes[5].x + λ₂₃ .* cnodes[6].x + λ₃₄ .* cnodes[7].x + λ₄₁ .* cnodes[8].x + λ₁₂₃₄ .* cnodes[9].x ) end function __ordered_lagrange_shape_fns(::Type{Bcube.Quad16_t}) refCoords = [-1.0, -1.0 / 3.0, 1.0 / 3.0, 1.0] # Lagrange nodes ordering (index in `refCoords`) I_to_ij = [ 1 1 # 1 4 1 # 2 4 4 # 3 1 4 # 4 2 1 # 5 3 1 # 6 4 2 # 7 4 3 # 8 3 4 # 9 2 4 # 10 1 3 # 11 1 2 # 12 2 2 # 13 3 2 # 14 3 3 # 15 2 3 # 16 ] @variables ξ[1:2] _ξ = ξ[1] _η = ξ[2] _λs = [ _lagrange_poly(I_to_ij[k, 1], _ξ, refCoords) * _lagrange_poly(I_to_ij[k, 2], _η, refCoords) for k in 1:16 ] expr_λs = Symbolics.toexpr.((_λs)) return :(SA[$(expr_λs...)]) end @generated function _ordered_lagrange_shape_fns(entity::AbstractEntityType, ξ) __ordered_lagrange_shape_fns(entity) end # Warning : only valid for "tensor" "Lagrange" entities function mapping(ctype::Union{Quad16_t}, cnodes, ξ) λs = _ordered_lagrange_shape_fns(ctype, ξ) return sum(((λ, node),) -> λ .* get_coords(node), zip(λs, cnodes)) end #---------------- Hexa8 mapping(::Cube, cnodes, ξ) = mapping(Hexa8_t(), cnodes, ξ) function mapping(::Hexa8_t, cnodes, ξηζ) ξ = ξηζ[1] η = ξηζ[2] ζ = ξηζ[3] return ( (1 - ξ) * (1 - η) * (1 - ζ) .* cnodes[1].x # = (1 - x) * (1 - y) * (1 - z) / 8 + (1 + ξ) * (1 - η) * (1 - ζ) .* cnodes[2].x # = (1 + x) * (1 - y) * (1 - z) / 8 + (1 + ξ) * (1 + η) * (1 - ζ) .* cnodes[3].x # = (1 + x) * (1 + y) * (1 - z) / 8 + (1 - ξ) * (1 + η) * (1 - ζ) .* cnodes[4].x # = (1 - x) * (1 + y) * (1 - z) / 8 + (1 - ξ) * (1 - η) * (1 + ζ) .* cnodes[5].x # = (1 - x) * (1 - y) * (1 + z) / 8 + (1 + ξ) * (1 - η) * (1 + ζ) .* cnodes[6].x # = (1 + x) * (1 - y) * (1 + z) / 8 + (1 + ξ) * (1 + η) * (1 + ζ) .* cnodes[7].x # = (1 + x) * (1 + y) * (1 + z) / 8 + (1 - ξ) * (1 + η) * (1 + ζ) .* cnodes[8].x # = (1 - x) * (1 + y) * (1 + z) / 8 ) ./ 8 end function mapping_jacobian(::Hexa8_t, cnodes, ξηζ) ξ = ξηζ[1] η = ξηζ[2] ζ = ξηζ[3] M1 = cnodes[1].x M2 = cnodes[2].x M3 = cnodes[3].x M4 = cnodes[4].x M5 = cnodes[5].x M6 = cnodes[6].x M7 = cnodes[7].x M8 = cnodes[8].x return hcat( ((M2 - M1) * (1 - η) + (M3 - M4) * (1 + η)) * (1 - ζ) + ((M6 - M5) * (1 - η) + (M7 - M8) * (1 + η)) * (1 + ζ), ((M4 - M1) * (1 - ξ) + (M3 - M2) * (1 + ξ)) * (1 - ζ) + ((M8 - M5) * (1 - ξ) + (M7 - M6) * (1 + ξ)) * (1 + ζ), ((M5 - M1) * (1 - ξ) + (M6 - M2) * (1 + ξ)) * (1 - η) + ((M8 - M4) * (1 - ξ) + (M7 - M3) * (1 + ξ)) * (1 + η), ) ./ 8.0 end #---------------- Hexa27 function mapping(::Hexa27_t, cnodes, ξηζ) ξ = ξηζ[1] η = ξηζ[2] ζ = ξηζ[3] return ( ξ * η * ζ * (ξ - 1) * (η - 1) * (ζ - 1) / 8.0 .* cnodes[1].x + ξ * η * ζ * (ξ + 1) * (η - 1) * (ζ - 1) / 8.0 .* cnodes[2].x + ξ * η * ζ * (ξ + 1) * (η + 1) * (ζ - 1) / 8.0 .* cnodes[3].x + ξ * η * ζ * (ξ - 1) * (η + 1) * (ζ - 1) / 8.0 .* cnodes[4].x + ξ * η * ζ * (ξ - 1) * (η - 1) * (ζ + 1) / 8.0 .* cnodes[5].x + ξ * η * ζ * (ξ + 1) * (η - 1) * (ζ + 1) / 8.0 .* cnodes[6].x + ξ * η * ζ * (ξ + 1) * (η + 1) * (ζ + 1) / 8.0 .* cnodes[7].x + ξ * η * ζ * (ξ - 1) * (η + 1) * (ζ + 1) / 8.0 .* cnodes[8].x + -η * ζ * (ξ^2 - 1) * (η - 1) * (ζ - 1) / 4.0 .* cnodes[9].x + -ξ * ζ * (ξ + 1) * (η^2 - 1) * (ζ - 1) / 4.0 .* cnodes[10].x + -η * ζ * (ξ^2 - 1) * (η + 1) * (ζ - 1) / 4.0 .* cnodes[11].x + -ξ * ζ * (ξ - 1) * (η^2 - 1) * (ζ - 1) / 4.0 .* cnodes[12].x + -ξ * η * (ξ - 1) * (η - 1) * (ζ^2 - 1) / 4.0 .* cnodes[13].x + -ξ * η * (ξ + 1) * (η - 1) * (ζ^2 - 1) / 4.0 .* cnodes[14].x + -ξ * η * (ξ + 1) * (η + 1) * (ζ^2 - 1) / 4.0 .* cnodes[15].x + -ξ * η * (ξ - 1) * (η + 1) * (ζ^2 - 1) / 4.0 .* cnodes[16].x + -η * ζ * (ξ^2 - 1) * (η - 1) * (ζ + 1) / 4.0 .* cnodes[17].x + -ξ * ζ * (ξ + 1) * (η^2 - 1) * (ζ + 1) / 4.0 .* cnodes[18].x + -η * ζ * (ξ^2 - 1) * (η + 1) * (ζ + 1) / 4.0 .* cnodes[19].x + -ξ * ζ * (ξ - 1) * (η^2 - 1) * (ζ + 1) / 4.0 .* cnodes[20].x + ζ * (ξ^2 - 1) * (η^2 - 1) * (ζ - 1) / 2.0 .* cnodes[21].x + η * (ξ^2 - 1) * (η - 1) * (ζ^2 - 1) / 2.0 .* cnodes[22].x + ξ * (ξ + 1) * (η^2 - 1) * (ζ^2 - 1) / 2.0 .* cnodes[23].x + η * (ξ^2 - 1) * (η + 1) * (ζ^2 - 1) / 2.0 .* cnodes[24].x + ξ * (ξ - 1) * (η^2 - 1) * (ζ^2 - 1) / 2.0 .* cnodes[25].x + ζ * (ξ^2 - 1) * (η^2 - 1) * (ζ + 1) / 2.0 .* cnodes[26].x + -(ξ^2 - 1) * (η^2 - 1) * (ζ^2 - 1) .* cnodes[27].x ) end """ mapping(nodes, ::Tetra4_t, ξ) Map the reference 4-nodes Tetraahedron [0,1] x [0,1] x [0,1] on the local triangle. ``` """ function mapping(::Tetra4_t, cnodes, ξ) return (1 - ξ[1] - ξ[2] - ξ[3]) .* cnodes[1].x + ξ[1] .* cnodes[2].x + ξ[2] .* cnodes[3].x + ξ[3] .* cnodes[4].x end #---------------- Penta6 mapping(::Prism, cnodes, ξ) = mapping(Penta6_t(), cnodes, ξ) function mapping(::Penta6_t, cnodes, ξηζ) ξ = ξηζ[1] η = ξηζ[2] ζ = ξηζ[3] return ( (1 - ξ - η) * (1 - ζ) .* cnodes[1].x + ξ * (1 - ζ) .* cnodes[2].x + η * (1 - ζ) .* cnodes[3].x + (1 - ξ - η) * (1 + ζ) .* cnodes[4].x + ξ * (1 + ζ) .* cnodes[5].x + η * (1 + ζ) .* cnodes[6].x ) ./ 2.0 end function mapping_jacobian(::Penta6_t, cnodes, ξηζ) ξ = ξηζ[1] η = ξηζ[2] ζ = ξηζ[3] M1 = cnodes[1].x M2 = cnodes[2].x M3 = cnodes[3].x M4 = cnodes[4].x M5 = cnodes[5].x M6 = cnodes[6].x return hcat( (1 - ζ) * (M2 - M1) + (1 + ζ) * (M5 - M4), (1 - ζ) * (M3 - M1) + (1 + ζ) * (M6 - M4), (1 - ξ - η) * (M4 - M1) + ξ * (M5 - M2) + η * (M6 - M3), ) ./ 2.0 end #---------------- Pyra5 mapping(::Pyramid, cnodes, ξ) = mapping(Pyra5_t(), cnodes, ξ) function mapping(::Pyra5_t, cnodes, ξηζ) ξ = ξηζ[1] η = ξηζ[2] ζ = ξηζ[3] # to avoid a singularity in z = 1, we replace (1-ζ) (which is always a # positive quantity), by (1 + ε - ζ). ε = eps() return ( (1 - ξ - ζ) * (1 - η - ζ) / (4 * (1 + ε - ζ)) * cnodes[1].x + (1 + ξ - ζ) * (1 - η - ζ) / (4 * (1 + ε - ζ)) * cnodes[2].x + (1 + ξ - ζ) * (1 + η - ζ) / (4 * (1 + ε - ζ)) * cnodes[3].x + (1 - ξ - ζ) * (1 + η - ζ) / (4 * (1 + ε - ζ)) * cnodes[4].x + ζ * cnodes[5].x ) end """ normal(ctype::AbstractEntityType, cnodes, iside, ξ) normal(::TopologyStyle, ctype::AbstractEntityType, cnodes, iside, ξ) Normal vector of the `iside`th face of a cell, evaluated at position `ξ` in the face reference element. So for the normal vector of the face of triangle living in a 3D space, `ξ` will be 1D (because the face is a line, which 1D). Beware this function needs the nodes `cnodes` and the type `ctype` of the cell (and not of the face). TODO: If `iside` is positive, then the outward normal (with respect to the cell) is returned, otherwise the inward normal is returned. # `::isCurvilinear` Note that the "face" normal vector of a curve is the "direction" vector at the given extremity. # `::isVolumic` ``n^{loc} = J^{-\\intercal} n^{ref}`` """ function normal(ctype::AbstractEntityType, cnodes, iside, ξ) normal(topology_style(ctype, cnodes), ctype, cnodes, iside, ξ) end function normal(::isCurvilinear, ctype::AbstractEntityType, cnodes, iside, ξ) # mapping face-reference-element (here, a node) to cell-reference-element (here, a Line) # Since a Line has always only two nodes, the node is necessary the `iside`-th ξ_cell = get_coords(Line())[iside] return normalize(mapping_jacobian(ctype, cnodes, ξ_cell) .* normal(shape(ctype), iside)) end function normal(::isSurfacic, ctype::AbstractEntityType, cnodes, iside, ξ) # Get cell shape and face type and shape cshape = shape(ctype) ftype = facetypes(ctype)[iside] # Get face nodes fnodes = map(i -> cnodes[i], faces2nodes(ctype)[iside]) # Get face direction vector (face Jacobian) u = mapping_jacobian(ftype, fnodes, ξ) # Get face parametrization function fp = mapping_face(cshape, iside) # mapping face-ref -> cell-ref # Compute surface jacobian J = mapping_jacobian(ctype, cnodes, fp(ξ)) # Compute vector that will help orient outward normal orient = mapping(ctype, cnodes, fp(ξ)) - center(ctype, cnodes) # Normal direction n = J[:, 1] × J[:, 2] × u # Orient normal outward and normalize return normalize(orient ⋅ n .* n) end function normal(::isVolumic, ctype::AbstractEntityType, cnodes, iside, ξ) # Cell shape cshape = shape(ctype) # Face parametrization to send ξ from ref-face-element to the ref-cell-element fp = mapping_face(cshape, iside) # mapping face-ref -> cell-ref # Inverse of the Jacobian matrix (but here `y` is in the cell-reference element) # Warning : do not use `mapping_inv_jacobian` which requires the knowledge of `mapping_inv` (useless here) Jinv(y) = mapping_jacobian_inv(ctype, cnodes, y) return normalize(transpose(Jinv(fp(ξ))) * normal(cshape, iside)) end """ cell_normal(ctype::AbstractEntityType, cnodes, ξ) where {T, N} Compute the cell normal vector of an entity of topology dimension equals to (n-1) in a n-D space, for instance a curve in a 2D space. This vector is expressed in the cell-reference coordinate system. Do not confuse the cell normal vector with the cell-side (i.e face) normal vector. # Topology dimension 1 the curve direction vector, u, is J/||J||. Then n = [-u.y, u.x]. """ function cell_normal( ctype::AbstractEntityType{1}, cnodes::AbstractArray{Node{2, T}, N}, ξ, ) where {T, N} Jref = mapping_jacobian(ctype, cnodes, ξ) return normalize(SA[-Jref[2], Jref[1]]) end function cell_normal( ctype::AbstractEntityType{2}, cnodes::AbstractArray{Node{3, T}, N}, ξ, ) where {T, N} J = mapping_jacobian(ctype, cnodes, ξ) return normalize(J[:, 1] × J[:, 2]) end """ center(ctype::AbstractEntityType, cnodes) Return the center of the `AbstractEntityType` by mapping the center of the corresponding `Shape`. # Warning Do not use this function on a face of a cell : since the face is of dimension "n-1", the mapping won't be appropriate. """ center(ctype::AbstractEntityType, cnodes) = mapping(ctype, cnodes, center(shape(ctype))) """ get_cell_centers(mesh::Mesh) Get mesh cell centers coordinates (assuming perfectly flat cells) """ function get_cell_centers(mesh::Mesh) c2n = connectivities_indices(mesh, :c2n) celltypes = cells(mesh) centers = map(1:ncells(mesh)) do icell ctype = celltypes[icell] cnodes = get_nodes(mesh, c2n[icell]) center(ctype, cnodes) end return centers end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
8326
""" ∂λξ_∂x(::AbstractFunctionSpace, ::Val{N}, ctype::AbstractEntityType, cnodes, ξ) where N Gradient, with respect to the physical coordinate system, of the shape functions associated to the `FunctionSpace`. Depending on the value of `N`, the shape functions are interpreted as associated to a scalar FESpace (N = 1) or a vector FESpace. For a vector FESpace, the result gradient is an array of size `(n*Nc, n, d)` where `Nc` is the number of dofs of one component (i.e scalar case), `n` is the size of the FESpace, and `d` the number of spatial dimensions. Default version : the gradient shape functions are "replicated". Specialize with a given FESpace for a custom behaviour. # Implementation We cannot use the `topology_style` to dispatch because this style is too specific to integration methods. For instance for the integration it is important the consider any line as `isCurvilinear`. However for the gradient computation we must distinguish a line in 1D, a line in 2D and a line in 3D... # """ function ∂λξ_∂x end function ∂λξ_∂x(fs::AbstractFunctionSpace, n::Val{1}, ctype::AbstractEntityType, cnodes, ξ) # Gradient of reference shape functions ∇λ = ∂λξ_∂ξ(fs, n, shape(ctype), ξ) return ∇λ * mapping_jacobian_inv(ctype, cnodes, ξ) end function ∂λξ_∂x( fs::AbstractFunctionSpace, n::Val{N}, ctype::AbstractEntityType, cnodes, ξ, ) where {N} ∇λ_sca = ∂λξ_∂x(fs, Val(1), ctype, cnodes, ξ) # Matrix of size (ndofs_sca, nspa) ndofs_sca, nspa = size(∇λ_sca) a = SArray{Tuple{ndofs_sca, 1, nspa}, eltype(∇λ_sca)}( ∇λ_sca[i, k] for i in 1:ndofs_sca, j in 1:1, k in 1:nspa ) ∇λ_vec = _block_diag_cat(a, n) return ∇λ_vec end @generated function _block_diag_cat( a::SArray{Tuple{N1, N2, N3}}, ::Val{N}, ) where {N1, N2, N3, N} T = eltype(a) z = zero(T) exprs = [:(a[$i, $j, $k]) for i in 1:N1, j in 1:N2, k in 1:N3] exprs0 = [:($z) for i in 1:N1, j in 1:N2, k in 1:N3] row_exprs = [] mat_exprs = [] for j in 1:N for i in 1:N i == j ? _exprs = exprs : _exprs = exprs0 i == 1 ? row_exprs = _exprs : row_exprs = [row_exprs; _exprs] end j == 1 ? mat_exprs = row_exprs : mat_exprs = [mat_exprs row_exprs] end N1_glo = N1 * N N2_glo = N2 * N T = eltype(a) return quote SArray{Tuple{$N1_glo, $N2_glo, N3}, $T}(tuple($(mat_exprs...))) end end @generated function _build_grad_impl(a::SMatrix{N1, N2}, ::Val{N}) where {N1, N2, N} T = eltype(a) z = zero(T) exprs = [:(a[$i, $j]) for i in 1:N1, j in 1:N2] exprs0 = Any[:($z) for i in 1:N, j in 1:N2] mat_exprs = [] for n in 1:N for k in 1:N1 _exprs = deepcopy(exprs0) _exprs[n, :] = exprs[k, :] push!(mat_exprs, _exprs) end end mat_exprs2 = Any[] for x in mat_exprs if N == 1 push!(mat_exprs2, :(SVector{$N2}(tuple($(x...))))) else push!(mat_exprs2, :(SMatrix{$N, $N2}(tuple($(x...))))) end end return quote tuple($(mat_exprs2...)) end end function ∂λξ_∂x_hypersurface( fs::AbstractFunctionSpace, ::Val{1}, ctype::AbstractEntityType{2}, cnodes::AbstractArray{<:Node{3}}, ξ, ) return _∂λξ_∂x_hypersurface(fs, ctype, cnodes, ξ) end function ∂λξ_∂x_hypersurface( fs::AbstractFunctionSpace, ::Val{1}, ctype::AbstractEntityType{1}, cnodes::AbstractArray{<:Node{2}}, ξ, ) return _∂λξ_∂x_hypersurface(fs, ctype, cnodes, ξ) end function _∂λξ_∂x_hypersurface(fs, ctype, cnodes, ξ) # First, we compute the "augmented" jacobian. J = mapping_jacobian_hypersurface(ctype, cnodes, ξ) # Compute shape functions gradient : we "add a dimension" to the ref gradient, # and then right-multiply by the inverse of the jacobian s = shape(ctype) z = @SVector zeros(get_ndofs(fs, s)) ∇λ = hcat(∂λξ_∂ξ(fs, s, ξ), z) * inv(J) return ∇λ end function ∂λξ_∂x_hypersurface( ::AbstractFunctionSpace, ::AbstractEntityType{1}, ::AbstractArray{Node{3}}, ξ, ) error("Line gradient in 3D not implemented yet") end """ ∂fξ_∂x(f, n::Val{N}, ctype::AbstractEntityType, cnodes, ξ) where N Compute the gradient, with respect to the physical coordinates, of a function `f` on a point in the reference domain. `N` is the size of the codomain of `f`. """ function ∂fξ_∂x(f::F, ::Val{1}, ctype::AbstractEntityType, cnodes, ξ) where {F} return transpose(mapping_jacobian_inv(ctype, cnodes, ξ)) * ForwardDiff.gradient(f, ξ) end function ∂fξ_∂x(f::F, ::Val{N}, ctype::AbstractEntityType, cnodes, ξ) where {F, N} return ForwardDiff.jacobian(f, ξ) * mapping_jacobian_inv(ctype, cnodes, ξ) end function ∂fξ_∂x_hypersurface(f::F, ::Val{1}, ctype::AbstractEntityType, cnodes, ξ) where {F} # Gradient in the reference domain. Add missing dimensions. Warning : we always # consider a hypersurface (topodim = spacedim - 1) and not a line in R^3 for instance. # Hence we always add only one 0. ∇f = ForwardDiff.gradient(f, ξ) ∇f = vcat(∇f, 0) # Then, we compute the "augmented" jacobian. J = mapping_jacobian_hypersurface(ctype, cnodes, ξ) return transpose(inv(J)) * ∇f end function ∂fξ_∂x_hypersurface( f::F, ::Val{N}, ctype::AbstractEntityType, cnodes, ξ, ) where {F, N} # Gradient in the reference domain. Add missing dimensions. Warning : we always # consider a hypersurface (topodim = spacedim - 1) and not a line in R^3 for instance. # Hence we always add only one 0. ∇f = ForwardDiff.jacobian(f, ξ) z = @SVector zeros(N) ∇f = hcat(∇f, z) # Then, we compute the "augmented" jacobian. J = mapping_jacobian_hypersurface(ctype, cnodes, ξ) return ∇f * inv(J) end """ interpolate(λ, q) interpolate(λ, q, ncomps) Create the interpolation function from a set of value on dofs and the shape functions, given by: ```math f(x) = \\sum_{i=1}^N q_i \\lambda_i(x) ``` So `q` is a vector whose size equals the number of dofs in the cell. If `ncomps` is present, create the interpolation function for a vector field given by a set of value on dofs and the shape functions. The interpolation formulae is the same than `interpolate(λ, q)` but the result is a vector function. Here `q` is a vector whose size equals the total number of dofs in the cell (all components mixed). Note that the result function is expressed in the same coordinate system as the input shape functions (i.e reference or local). """ function interpolate(λ, q) #@assert length(λ) === length(q) "Error : length of `q` must equal length of `lambda`" return ξ -> interpolate(λ, q, ξ) end interpolate(λ, q, ξ) = sum(λᵢ * qᵢ for (λᵢ, qᵢ) in zip(λ(ξ), q)) function interpolate(λ, q::SVector{N}, ::Val{ncomps}) where {N, ncomps} return x -> transpose(reshape(q, Size(Int(N / ncomps), ncomps))) * λ(x) end function interpolate(λ, q, ::Val{ncomps}) where {ncomps} return x -> transpose(reshape(q, :, ncomps)) * λ(x) end function interpolate(λ, q, ncomps::Integer) return ξ -> interpolate(λ, q, ncomps, ξ) end function interpolate(λ, q, ncomps::Integer, ξ) return transpose(reshape(q, :, ncomps)) * λ(ξ) end function interpolate(λ, q::SVector) return x -> transpose(q) * λ(x) end # """ # WARNING : INTERPOLATION IN LOCAL ELEMENT FOR THE MOMENT # """ # @inline function interpolate(q, dhl::DeprecatedDofHandler, icell, ctype::AbstractEntityType, cnodes, varname::Val{N}) where {N} # fs = function_space(dhl,varname) # λ = x -> shape_functions(fs, shape(ctype), mapping_inv(cnodes, ctype, x)) # ncomp = ncomps(dhl,varname) # return interpolate(λ, q[get_dof(dhl, icell, shape(ctype), varname)], Val(ncomp)) # end # """ # WARNING : INTERPOLATION IN LOCAL ELEMENT FOR THE MOMENT # """ # function interpolate(q, dhl::DeprecatedDofHandler, icell, ctype::AbstractEntityType, cnodes) # _varnames = name.(getvars(dhl)) # _nvars = nvars(dhl) # _ncomps = ncomps.(getvars(dhl)) # # Gather all Variable interpolation functions in a Tuple # w = ntuple(i->interpolate(q, dhl, icell, ctype, cnodes, Val(_varnames[i])), _nvars) # # Build a 'vector-valued' function, one row per variable and component # return x -> vcat(map(f->f(x), w)...) # end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1052
abstract type AbstractBCType end struct DirichletBCType <: AbstractBCType end struct NeumannBCType <: AbstractBCType end struct PeriodicBCType{T <: AbstractAffineTransformation, T2, T3} <: AbstractBCType transformation::T labels_master::T2 labels_slave::T3 end @inline transformation(perio::PeriodicBCType) = perio.transformation @inline labels_master(perio::PeriodicBCType) = perio.labels_master @inline labels_slave(perio::PeriodicBCType) = perio.labels_slave abstract type AbstractBoundaryCondition end """ Structure representing a boundary condition. Its purpose is to be attached to geometric entities (nodes, faces, ...). """ struct BoundaryCondition{T, F} <: AbstractBoundaryCondition type::T # Dirichlet, Neumann, other? For the moment, this property is entirely free func::F # This is a function depending on space and time : func(x,t) end @inline apply(bnd::BoundaryCondition, x, t) = bnd.func(x, t) @inline apply(bnd::BoundaryCondition, x) = bnd.func(x, 0.0) @inline type(bnd::BoundaryCondition) = bnd.type
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
4034
""" AbstractConnectivity{T} Supertype for connectivity with indices of type `T`. """ abstract type AbstractConnectivity{T} end Base.length(::AbstractConnectivity) = error("Undefined") Base.size(::AbstractConnectivity) = error("Undefined") """ Connectivity{T} Type for connectivity with elements of type `T`. """ struct Connectivity{T <: Integer} <: AbstractConnectivity{T} minsize::T maxsize::T offsets::Vector{T} indices::Vector{T} function Connectivity( minsize::T, maxsize::T, offsets::Vector{T}, indices::Vector{T}, ) where {T <: Integer} if offsets[end] - 1 ≠ length(indices) @show offsets[end] - 1, length(indices) error("Invalid offset range") end for i in firstindex(offsets):(lastindex(offsets) - 1) offsets[i + 1] < offsets[i] ? error("Invalid offset ", i) : nothing end new{T}(minsize, maxsize, offsets, indices) end end function Connectivity( numIndices::AbstractVector{T}, indices::AbstractVector{T}, ) where {T <: Integer} ne = length(numIndices) minsize = minimum(numIndices) maxsize = maximum(numIndices) offsets = zeros(T, ne + 1) offsets[1] = 1 for (i, size) in enumerate(numIndices) offsets[i + 1] = offsets[i] + size end return Connectivity(minsize, maxsize, offsets, indices) end Base.length(c::Connectivity) = length(c.offsets) - 1 Base.size(c::Connectivity) = (length(c),) Base.axes(c::Connectivity) = 1:length(c) @propagate_inbounds Base.firstindex(c::Connectivity, i) = c.offsets[i] @propagate_inbounds Base.lastindex(c::Connectivity, i) = c.offsets[i + 1] - 1 @propagate_inbounds Base.length(c::Connectivity, i) = lastindex(c, i) - firstindex(c, i) + 1 Base.size(c::Connectivity, i) = (length(c, i),) @propagate_inbounds function Base.axes(c::Connectivity, i) if i > 0 return firstindex(c, i):1:lastindex(c, i) else return lastindex(c, -i):-1:firstindex(c, -i) end end @inline Base.getindex(c::Connectivity) = c.indices @propagate_inbounds Base.getindex(c::Connectivity, i) = view(c.indices, axes(c, i)) @propagate_inbounds function Base.getindex(c::Connectivity, i, ::Val{N}) where {N} length(c, i) == N || error("invalid length $N (length(c,i)=$(length(c,i)))") SVector{N}(c[i]) end @inline minsize(c::Connectivity) = c.minsize @inline maxsize(c::Connectivity) = c.maxsize #@inline minconnectivity(c::Connectivity) = c.minConnectivity #@inline maxconnectivity(c::Connectivity) = c.maxConnectivity #@inline extrema(c::Connectivity) = (c.minElementInSet,c.maxElementInSet) Base.eltype(::Connectivity{T}) where {T <: Integer} = T function Base.iterate(c::Connectivity{T}, i = 1) where {T <: Integer} if i > length(c) return nothing else return c[i], i + 1 end end function Base.show(io::IO, c::Connectivity) println(typeof(c)) for (i, _c) in enumerate(c) println(io, i, "=>", _c) end end #Base.keys(c::Connectivity) = LinearIndices(1:length(c)) """ inverse_connectivity(c::Connectivity{T}) where {T} Returns the "inverse" of the connectivity 'c' and the corresponding 'keys'. 'keys' are provided because indices in 'c' could be sparse in the general case. # Example ```julia mesh = basic_mesh() c2n = connectivities_indices(mesh,:c2n) n2c, keys = inverse_connectivity(c2n) ``` Here, 'n2c' is the node->cell graph of connectivity and, 'n2c[i]' contains the indices of the cells connected to the node of index 'keys[i]'. If 'c2n' is dense, 'keys' is not necessary (because keys[i]==i, ∀i) """ function inverse_connectivity(c::Connectivity{T}) where {T} dict = Dict{T, Vector{T}}() for (i, cᵢ) in enumerate(c) for k in cᵢ get(dict, k, nothing) === nothing ? dict[k] = [i] : push!(dict[k], i) end end _keys = collect(keys(dict)) _vals = collect(values(dict)) numindices = length.(_vals) indices = rawcat(_vals) Connectivity(numindices, indices), _keys end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
17675
""" An `AbstractDomain` designates any set of entities from a mesh. For instance a set of cells, a set of faces etc. """ abstract type AbstractDomain{M <: AbstractMesh} end @inline get_mesh(domain::AbstractDomain) = domain.mesh @inline indices(domain::AbstractDomain) = domain.indices # with ghislainb's help, `AbstractDomain` could be parametered by `I` @inline topodim(::AbstractDomain) = error("undefined") @inline codimension(d::AbstractDomain) = topodim(get_mesh(d)) - topodim(d) LazyOperators.pretty_name(domain::AbstractDomain) = "AbstractDomain" abstract type AbstractCellDomain{M, I} <: AbstractDomain{M} end """ A `CellDomain` is a representation of the cells of a mesh. It's primary purpose is to represent a domain to integrate over. # Examples ```julia-repl julia> mesh = rectangle_mesh(10, 10) julia> Ω_all = CellDomain(mesh) julia> selectedCells = [1,3,5,6] julia> Ω_selected = CellDomain(mesh, selectedCells) ``` """ struct CellDomain{M, I} <: AbstractCellDomain{M, I} mesh::M indices::I CellDomain(mesh, indices) = new{typeof(mesh), typeof(indices)}(mesh, indices) end @inline topodim(d::CellDomain) = topodim(get_mesh(d)) CellDomain(mesh::AbstractMesh) = CellDomain(parent(mesh)) CellDomain(mesh::Mesh) = CellDomain(mesh, 1:ncells(mesh)) LazyOperators.pretty_name(domain::CellDomain) = "CellDomain" abstract type AbstractFaceDomain{M} <: AbstractDomain{M} end struct InteriorFaceDomain{M, I} <: AbstractFaceDomain{M} mesh::M indices::I InteriorFaceDomain(mesh, indices) = new{typeof(mesh), typeof(indices)}(mesh, indices) end @inline topodim(d::InteriorFaceDomain) = topodim(get_mesh(d)) - 1 InteriorFaceDomain(mesh::AbstractMesh) = InteriorFaceDomain(parent(mesh)) InteriorFaceDomain(mesh::Mesh) = InteriorFaceDomain(mesh, inner_faces(mesh)) LazyOperators.pretty_name(domain::InteriorFaceDomain) = "InteriorFaceDomain" struct AllFaceDomain{M, I} <: AbstractFaceDomain{M} mesh::M indices::I AllFaceDomain(mesh, indices) = new{typeof(mesh), typeof(indices)}(mesh, indices) end @inline topodim(d::AllFaceDomain) = topodim(get_mesh(d)) - 1 AllFaceDomain(mesh::AbstractMesh) = AllFaceDomain(mesh, 1:nfaces(mesh)) LazyOperators.pretty_name(domain::AllFaceDomain) = "AllFaceDomain" struct BoundaryFaceDomain{M, BC, L, C} <: AbstractFaceDomain{M} mesh::M bc::BC labels::L cache::C end @inline get_mesh(d::BoundaryFaceDomain) = d.mesh @inline topodim(d::BoundaryFaceDomain) = topodim(get_mesh(d)) - 1 @inline bctype(::BoundaryFaceDomain{M, BC}) where {M, BC} = BC @inline get_bc(d::BoundaryFaceDomain) = d.bc @inline get_cache(d::BoundaryFaceDomain) = d.cache LazyOperators.pretty_name(domain::BoundaryFaceDomain) = "BoundaryFaceDomain" indices(d::BoundaryFaceDomain) = get_cache(d) function BoundaryFaceDomain(mesh::Mesh, bc::PeriodicBCType) cache = _compute_periodicity(mesh, labels_master(bc), labels_slave(bc), transformation(bc)) labels = unique(vcat(labels_master(bc)..., labels_slave(bc)...)) BoundaryFaceDomain{typeof(mesh), typeof(bc), typeof(labels), typeof(cache)}( mesh, bc, labels, cache, ) end function indices(d::BoundaryFaceDomain{M, <:PeriodicBCType}) where {M} _, _, _, _, bnd_ftypes, = get_cache(d) return 1:length(bnd_ftypes) end """ Find periodic face connectivities sush as : (faces of `labels2`) = A(faces of `labels1`) """ function _compute_periodicity(mesh, labels1, labels2, A, tol = 1e-9) # Get cell -> node connectivity c2n = connectivities_indices(mesh, :c2n) # Get face -> node connectivity f2n = connectivities_indices(mesh, :f2n) # Get face -> cell connectivity f2c = connectivities_indices(mesh, :f2c) # Cell and face types #celltypes = cells(mesh) tags1 = map(label -> boundary_tag(mesh, label), labels1) tags2 = map(label -> boundary_tag(mesh, label), labels2) # Boundary faces bndfaces1 = vcat(map(tag -> boundary_faces(mesh, tag), tags1)...) bndfaces2 = vcat(map(tag -> boundary_faces(mesh, tag), tags2)...) #nbnd1 = length(bndfaces1) nbnd2 = length(bndfaces2) # Allocate result bnd_f2n1 = [zero(f2n[iface]) for iface in bndfaces1] bnd_f2n2 = [zero(f2n[iface]) for iface in bndfaces2] bnd_f2c = zeros(Int, nbnd2, 2) # Adjacent cells for each bnd face bnd_ftypes = Array{AbstractEntityType}(undef, nbnd2) # Loop over bnd faces for (i, iface) in enumerate(bndfaces2) icell = f2c[iface][1] fnodesᵢ = get_nodes(mesh, f2n[iface]) #sideᵢ = cell_side(celltypes[icell], c2n[icell], f2n[iface]) Mᵢ = center(fnodesᵢ) # compute a characteristic length : Δxᵢ = distance(center(get_nodes(mesh, c2n[icell])), Mᵢ) isfind = false for (j, jface) in enumerate(bndfaces1) jcell = f2c[jface][1] fnodesⱼ = get_nodes(mesh, f2n[jface]) #sideⱼ = cell_side(celltypes[jcell], c2n[jcell], f2n[jface]) Mⱼ = center(fnodesⱼ) # compute image point Mⱼ_bis = Node(A(get_coords(Mⱼ))) # Centers must be identical if isapprox(Mᵢ, Mⱼ_bis; atol = tol * Δxᵢ) bnd_f2n1[i] = f2n[iface] bnd_f2n2[i] = f2n[jface] bnd_ftypes[i] = faces(mesh)[iface] bnd_f2c[i, 1] = icell bnd_f2c[i, 2] = jcell # Stop looking for face in relation isfind = true break end end if isfind === false error("Face i=", i, " ", iface, " not found") end end bnd_f2f = Dict{Int, Int}() for (i, iface) in enumerate(bndfaces2) bnd_f2f[iface] = i end # node to node relation bnd_n2n = Dict{Int, Int}() for (_f2c, _f2n1, _f2n2) in zip(bnd_f2c, bnd_f2n1, bnd_f2n2) # distance between face center and adjacent cell center Δx = distance(center(get_nodes(mesh, c2n[_f2c[1]])), center(get_nodes(mesh, _f2n1))) isfind = false for i in _f2n1 Mᵢ = get_nodes(mesh, i) for j in _f2n2 Mⱼ = get_nodes(mesh, j) # compute image point Mⱼ_bis = Node(A(get_coords(Mⱼ))) if isapprox(Mᵢ, Mⱼ_bis; atol = tol * Δx) bnd_n2n[i] = j bnd_n2n[j] = i # Stop looking for face in relation isfind = true break end end if isfind === false error("Node i=", i, " not found (2)") end end end # Retain only relevant faces return bnd_f2f, bnd_f2n1, bnd_f2n2, bnd_f2c, bnd_ftypes, bnd_n2n end """ BoundaryFaceDomain(mesh) BoundaryFaceDomain(mesh, label::String) BoundaryFaceDomain(mesh, labels::Tuple{String, Vararg{String}}) Build a `BoundaryFaceDomain` corresponding to the boundaries designated by one or several labels (=names). If no label is provided, all the `BoundaryFaceDomain` corresponds to all the boundary faces. """ function BoundaryFaceDomain(mesh::Mesh, labels::Tuple{String, Vararg{String}}) tags = map(label -> boundary_tag(mesh, label), labels) # Check all tags have been found for tag in tags (tag isa Nothing) && error( "Failed to build a `BoundaryFaceDomain` with labels '$(labels...)' -> double-check that your mesh contains these labels", ) end bndfaces = vcat(map(tag -> boundary_faces(mesh, tag), tags)...) cache = bndfaces bc = nothing BoundaryFaceDomain{typeof(mesh), typeof(bc), typeof(labels), typeof(cache)}( mesh, bc, labels, cache, ) end BoundaryFaceDomain(mesh::AbstractMesh, label::String) = BoundaryFaceDomain(mesh, (label,)) function BoundaryFaceDomain(mesh::AbstractMesh) BoundaryFaceDomain(mesh, Tuple(values(boundary_names(mesh)))) end function BoundaryFaceDomain(mesh::AbstractMesh, args...; kwargs...) BoundaryFaceDomain(parent(mesh), args...; kwargs...) end """ abstract type AbstractDomainIndex # Devs notes All subtypes should implement the following functions: - get_element_type(::AbstractDomainIndex) """ abstract type AbstractDomainIndex end abstract type AbstractCellInfo <: AbstractDomainIndex end struct CellInfo{C, N, CN} <: AbstractCellInfo icell::Int ctype::C nodes::N # List/array of the cell `Node`s c2n::CN # Global indices of the nodes composing the cell end function CellInfo(icell, ctype, nodes, c2n) CellInfo{typeof(ctype), typeof(nodes), typeof(c2n)}(icell, ctype, nodes, c2n) end @inline cellindex(c::CellInfo) = c.icell @inline celltype(c::CellInfo) = c.ctype @inline nodes(c::CellInfo) = c.nodes @inline get_nodes_index(c::CellInfo) = c.c2n get_element_type(c::CellInfo) = celltype(c) """ Legacy constructor for CellInfo : no information about node indices """ CellInfo(icell, ctype, nodes) = CellInfo(icell, ctype, nodes, nothing) """ CellInfo(mesh, icell) DEBUG constructor for `icell`-th cell of `mesh`. For performance issues, don't use this version in production. """ function CellInfo(mesh, icell) c2n = connectivities_indices(mesh, :c2n) _c2n = c2n[icell] celltypes = cells(mesh) return CellInfo(icell, celltypes[icell], get_nodes(mesh, _c2n), _c2n) end abstract type AbstractCellSide <: AbstractDomainIndex end struct CellSide{C, N, CN} <: AbstractCellSide icell::Int iside::Int ctype::C nodes::N c2n::CN end function CellSide(icell, iside, ctype, nodes, c2n) CellSide{typeof(ctype), typeof(nodes), typeof(c2n)}(icell, iside, ctype, nodes, c2n) end @inline cellindex(c::CellSide) = c.icell @inline cellside(c::CellSide) = c.iside @inline celltype(c::CellSide) = c.ctype @inline nodes(c::CellSide) = c.nodes @inline cell2nodes(c::CellSide) = c.c2n get_element_type(c::CellSide) = celltype(c) abstract type AbstractFaceInfo <: AbstractDomainIndex end """ FaceInfo{CN<:CellInfo,CP<:CellInfo,FT,FN,F2N,I} Type describing a face as the common side of two adjacent cells. `CellInfo` of cells from both sides is stored with the local side index of the face relative to each adjacent cell. `iface` is the mesh-face-index (and not the domain-face-index). # Remark: - For boundary face with no periodic condition, positive cell side info are duplicate from the negative ones. - For performance reason (type stability), nodes and type of the face is stored explicitely in `FaceInfo` even if it could have been computed by collecting info from the side of the negative or positive cells. """ struct FaceInfo{CN <: CellInfo, CP <: CellInfo, FT, FN, F2N, I} <: AbstractFaceInfo cellinfo_n::CN cellinfo_p::CP cellside_n::Int cellside_p::Int faceType::FT faceNodes::FN f2n::F2N iface::I end """ FaceInfo constructor Cell sides are computed automatically. """ function FaceInfo( cellinfo_n::CellInfo, cellinfo_p::CellInfo, faceType, faceNodes, f2n::AbstractVector, iface, ) cellside_n = cell_side(celltype(cellinfo_n), get_nodes_index(cellinfo_n), f2n) cellside_p = cell_side(celltype(cellinfo_p), get_nodes_index(cellinfo_p), f2n) if cellside_n === nothing || cellside_p === nothing printstyled("\n=== ERROR in FaceInfo ===\n"; color = :red) @show cellside_n @show cellside_p @show celltype(cellinfo_n) @show get_nodes_index(cellinfo_n) @show celltype(cellinfo_p) @show get_nodes_index(cellinfo_p) @show faceType @show faceNodes @show f2n error("Invalid cellside in `FaceInfo`") end FaceInfo( cellinfo_n, cellinfo_p, cellside_n, cellside_p, faceType, faceNodes, f2n, iface, ) end """ DEBUG `FaceInfo` constructor for `kface`-th cell of `mesh`. For performance issues, don't use this version in production. """ function FaceInfo(mesh::Mesh, kface::Int) f2n = connectivities_indices(mesh, :f2n) f2c = connectivities_indices(mesh, :f2c) _f2n = f2n[kface] fnodes = get_nodes(mesh, _f2n) ftype = faces(mesh)[kface] cellinfo_n = CellInfo(mesh, f2c[kface][1]) cellinfo_p = length(f2c[kface]) > 1 ? CellInfo(mesh, f2c[kface][2]) : cellinfo_n return FaceInfo(cellinfo_n, cellinfo_p, ftype, fnodes, _f2n, kface) end nodes(faceInfo::FaceInfo) = faceInfo.faceNodes facetype(faceInfo::FaceInfo) = faceInfo.faceType faceindex(faceInfo::FaceInfo) = faceInfo.iface get_cellinfo_n(faceInfo::FaceInfo) = faceInfo.cellinfo_n get_cellinfo_p(faceInfo::FaceInfo) = faceInfo.cellinfo_p @inline get_nodes_index(faceInfo::FaceInfo) = faceInfo.f2n get_cell_side_n(faceInfo::FaceInfo) = faceInfo.cellside_n get_cell_side_p(faceInfo::FaceInfo) = faceInfo.cellside_p get_element_type(c::FaceInfo) = facetype(c) """ Return the opposite side of the `FaceInfo` : cellside "n" because cellside "p" """ function opposite_side(fInfo::FaceInfo) return FaceInfo( get_cellinfo_p(fInfo), get_cellinfo_n(fInfo), get_cell_side_p(fInfo), get_cell_side_n(fInfo), facetype(fInfo), nodes(fInfo), get_nodes_index(fInfo), faceindex(fInfo), ) end """ Return a LazyOperator representing a face normal """ get_face_normals(::AbstractFaceDomain) = FaceNormal() abstract type AbstractDomainIterator{D <: AbstractDomain} end get_domain(iter::AbstractDomainIterator) = iter.domain Base.iterate(::AbstractDomainIterator) = error("to be defined") Base.iterate(::AbstractDomainIterator, state) = error("to be defined") Base.eltype(::AbstractDomainIterator) = error("to be defined") Base.length(iter::AbstractDomainIterator) = length(indices(get_domain(iter))) Base.firstindex(::AbstractDomainIterator) = 1 Base.getindex(::AbstractDomainIterator, i) = error("to be defined") struct DomainIterator{D <: AbstractDomain} <: AbstractDomainIterator{D} domain::D end Base.eltype(::DomainIterator{<:AbstractCellDomain}) = CellInfo Base.eltype(::DomainIterator{<:AbstractFaceDomain}) = FaceInfo function Base.iterate(iter::DomainIterator, i::Integer = 1) if i > length(indices(get_domain(iter))) return nothing else return _get_index(get_domain(iter), i), i + 1 end end Base.getindex(iter::DomainIterator, i) = _get_index(get_domain(iter), i) function _get_index(domain::AbstractCellDomain, i::Integer) icell = indices(domain)[i] mesh = get_mesh(domain) _get_cellinfo(mesh, icell) end function _get_cellinfo(mesh, icell) c2n = connectivities_indices(mesh, :c2n) celltypes = cells(mesh) ctype = celltypes[icell] n_nodes = Val(nnodes(ctype)) _c2n = c2n[icell, n_nodes] cnodes = get_nodes(mesh, _c2n) CellInfo(icell, ctype, cnodes, _c2n) end function _get_index(domain::AbstractFaceDomain, i::Integer) iface = indices(domain)[i] mesh = get_mesh(domain) f2n = connectivities_indices(mesh, :f2n) cellinfo1, cellinfo2 = _get_face_cellinfo(domain, i) ftype = faces(mesh)[iface] n_fnodes = Val(nnodes(ftype)) _f2n = f2n[iface, n_fnodes] fnodes = get_nodes(mesh, _f2n) FaceInfo(cellinfo1, cellinfo2, ftype, fnodes, _f2n, iface) end function _get_face_cellinfo(domain::InteriorFaceDomain, i) mesh = get_mesh(domain) f2c = connectivities_indices(mesh, :f2c) iface = indices(domain)[i] icell1, icell2 = f2c[iface] cellinfo1 = _get_cellinfo(mesh, icell1) cellinfo2 = _get_cellinfo(mesh, icell2) return cellinfo1, cellinfo2 end function _get_face_cellinfo(domain::AllFaceDomain, i) mesh = get_mesh(domain) f2c = connectivities_indices(mesh, :f2c) iface = indices(domain)[i] if length(f2c[iface]) > 1 icell1, icell2 = f2c[iface] cellinfo1 = _get_cellinfo(mesh, icell1) cellinfo2 = _get_cellinfo(mesh, icell2) return cellinfo1, cellinfo2 else icell1, = f2c[iface] cellinfo1 = _get_cellinfo(mesh, icell1) return cellinfo1, cellinfo1 end end function _get_face_cellinfo(domain::BoundaryFaceDomain, i) mesh = get_mesh(domain) f2c = connectivities_indices(mesh, :f2c) iface = indices(domain)[i] icell1, = f2c[iface] cellinfo1 = _get_cellinfo(mesh, icell1) return cellinfo1, cellinfo1 end function _get_index(domain::BoundaryFaceDomain{M, <:PeriodicBCType}, i::Integer) where {M} mesh = get_mesh(domain) c2n = connectivities_indices(mesh, :c2n) iface = indices(domain)[i] # TODO : add a specific API for the domain cache: perio_cache = get_cache(domain) perio_trans = transformation(get_bc(domain)) _, bnd_f2n1, bnd_f2n2, bnd_f2c, bnd_ftypes, bnd_n2n = perio_cache icell1, icell2 = bnd_f2c[i, :] cellinfo1 = _get_cellinfo(mesh, icell1) ctype_j = cells(mesh)[icell2] nnodes_j = Val(nnodes(ctype_j)) _c2n_j = c2n[icell2, nnodes_j] cnodes_j = get_nodes(mesh, _c2n_j) # to be removed when function barrier is used cnodes_j_perio = map(node -> Node(perio_trans(get_coords(node))), cnodes_j) # Build c2n for cell j with nodes indices taken from cell i # for those that are shared on the periodic BC: _c2n_j_perio = map(k -> get(bnd_n2n, k, k), _c2n_j) cellinfo2 = CellInfo(icell2, ctype_j, cnodes_j_perio, _c2n_j_perio) # Face info ftype = bnd_ftypes[i] fnodes = get_nodes(mesh, bnd_f2n1[i]) cside_i = cell_side(celltype(cellinfo1), get_nodes_index(cellinfo1), bnd_f2n1[i]) cside_j = cell_side(celltype(cellinfo2), _c2n_j, bnd_f2n2[i]) _f2n = bnd_f2n1[i] return FaceInfo(cellinfo1, cellinfo2, cside_i, cside_j, ftype, fnodes, _f2n, iface) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
20342
# # NOTE : entity are defined according CGNS conventions. Beware that # for some elements, this is different from the GMSH convention (see Hexa27 # for instance). # (see https://cgns.github.io/CGNS_docs_current/sids/conv.html) abstract type AbstractEntity{dim} end abstract type AbstractNode <: AbstractEntity{0} end abstract type AbstractFace{dim} <: AbstractEntity{dim} end abstract type AbstractCell{dim} <: AbstractEntity{dim} end abstract type AbstractCellType end abstract type AbstractFaceType end abstract type AbstractEntityType{dim} end struct Node_t <: AbstractEntityType{0} end struct Bar2_t <: AbstractEntityType{1} end struct Bar3_t <: AbstractEntityType{1} end struct Bar4_t <: AbstractEntityType{1} end struct Bar5_t <: AbstractEntityType{1} end struct Tri3_t <: AbstractEntityType{2} end struct Tri6_t <: AbstractEntityType{2} end struct Tri9_t <: AbstractEntityType{2} end struct Tri10_t <: AbstractEntityType{2} end struct Tri12_t <: AbstractEntityType{2} end struct Quad4_t <: AbstractEntityType{2} end struct Quad8_t <: AbstractEntityType{2} end struct Quad9_t <: AbstractEntityType{2} end struct Quad16_t <: AbstractEntityType{2} end struct Tetra4_t <: AbstractEntityType{3} end struct Tetra10_t <: AbstractEntityType{3} end struct Hexa8_t <: AbstractEntityType{3} end struct Hexa27_t <: AbstractEntityType{3} end struct Penta6_t <: AbstractEntityType{3} end struct Pyra5_t <: AbstractEntityType{3} end struct Poly2_t{N, M} <: AbstractEntityType{2} end struct Poly3_t{N, M} <: AbstractEntityType{3} end abstract type AbstractEntityList end const EntityVector{T} = Vector{T} where {T <: AbstractEntityType} #---- Generic functions which MUST BE implemented for each concrete type ---- @inline function nnodes(::Type{<:T}) where {T <: AbstractEntityType} error("Function ‘nnodes‘ is not defined") end @inline nnodes(a::T) where {T <: AbstractEntityType} = nnodes(typeof(a)) @inline function nodes(::Type{<:T}) where {T <: AbstractEntityType} error("Function ‘nodes‘ is not defined") end @inline nodes(a::T) where {T <: AbstractEntityType} = nodes(typeof(a)) @inline function nedges(::Type{<:T}) where {T <: AbstractEntityType} error("Function nedges is not defined") end @inline nedges(a::T) where {T <: AbstractEntityType} = nedges(typeof(a)) @inline function edges2nodes(::Type{<:T}) where {T <: AbstractEntityType} error("Function edges2nodes is not defined") end @inline edges2nodes(a::T) where {T <: AbstractEntityType} = edges2nodes(typeof(a)) @inline function edgetypes(::Type{<:T}) where {T <: AbstractEntityType} error("Function edgetypes is not defined") end @inline edgetypes(a::T) where {T <: AbstractEntityType} = edgetypes(typeof(a)) @inline edgetypes(a::T, i) where {T <: AbstractEntityType} = edgetypes(a)[i] @inline function nfaces(::Type{<:T}) where {T <: AbstractEntityType} error("Function nfaces is not defined") end @inline nfaces(a::T) where {T <: AbstractEntityType} = nfaces(typeof(a)) @inline function faces2nodes(::Type{<:T}) where {T <: AbstractEntityType} error("Function faces2nodes is not defined") end @inline faces2nodes(a::T) where {T <: AbstractEntityType} = faces2nodes(typeof(a)) @inline topodim(::Type{<:AbstractEntityType{N}}) where {N} = N @inline topodim(a::T) where {T <: AbstractEntityType} = topodim(typeof(a)) @inline function facetypes(::Type{<:T}) where {T <: AbstractEntityType} error("Function facetypes is not defined") end @inline facetypes(a::T) where {T <: AbstractEntityType} = facetypes(typeof(a)) @inline facetypes(a::T, i) where {T <: AbstractEntityType} = facetypes(a)[i] #---- Valid generic functions for each type ---- @inline function edges2nodes(a::T, i) where {T <: AbstractEntityType} nedges(a) === 0 ? nothing : edges2nodes(a)[i] end @inline function edges2nodes(a::T, i...) where {T <: AbstractEntityType} nedges(a) === 0 ? nothing : edges2nodes(a)[i...] end @inline function faces2nodes(a::T, i) where {T <: AbstractEntityType} nfaces(a) === 0 ? nothing : faces2nodes(a)[i] end @inline function faces2nodes(a::T, i...) where {T <: AbstractEntityType} nfaces(a) === 0 ? nothing : faces2nodes(a)[i] end #---- Type specific functions ---- #- Node @inline nnodes(::Type{Node_t}) = 1 @inline nodes(::Type{Node_t}) = (1,) @inline nedges(::Type{Node_t}) = 0 @inline edges2nodes(::Type{Node_t}) = nothing @inline edgetypes(::Type{Node_t}) = nothing @inline nfaces(::Type{Node_t}) = 0 @inline faces2nodes(::Type{Node_t}) = nothing @inline facetypes(::Type{Node_t}) = nothing #- Bar2 @inline nnodes(::Type{Bar2_t}) = 2 @inline nodes(::Type{Bar2_t}) = (1, 2) @inline nedges(::Type{Bar2_t}) = 2 @inline edges2nodes(::Type{Bar2_t}) = ((1,), (2,)) @inline edgetypes(::Type{Bar2_t}) = (Node_t(), Node_t()) @inline nfaces(t::Type{Bar2_t}) = nedges(t) @inline faces2nodes(t::Type{Bar2_t}) = edges2nodes(t) @inline facetypes(t::Type{Bar2_t}) = edgetypes(t) #- Bar3 # N1 N3 N2 # x---------x---------x @inline nnodes(::Type{Bar3_t}) = 3 @inline nodes(::Type{Bar3_t}) = (1, 2, 3) @inline nedges(::Type{Bar3_t}) = 2 @inline edges2nodes(::Type{Bar3_t}) = ((1,), (2,)) @inline edgetypes(::Type{Bar3_t}) = (Node_t(), Node_t()) @inline nfaces(t::Type{Bar3_t}) = nedges(t) @inline faces2nodes(t::Type{Bar3_t}) = edges2nodes(t) @inline facetypes(t::Type{Bar3_t}) = edgetypes(t) #- Bar4 # N1 N3 N4 N2 # x------x------x------x @inline nnodes(::Type{Bar4_t}) = 4 @inline nodes(::Type{Bar4_t}) = (1, 2, 3, 4) @inline nedges(::Type{Bar4_t}) = 2 @inline edges2nodes(::Type{Bar4_t}) = ((1,), (2,)) @inline edgetypes(::Type{Bar4_t}) = (Node_t(), Node_t()) @inline nfaces(t::Type{Bar4_t}) = nedges(t) @inline faces2nodes(t::Type{Bar4_t}) = edges2nodes(t) @inline facetypes(t::Type{Bar4_t}) = edgetypes(t) #- Bar5 # N1 N3 N4 N5 N2 # x----x----x----x----x @inline nnodes(::Type{Bar5_t}) = 5 @inline nodes(::Type{Bar5_t}) = (1, 2, 3, 4, 5) @inline nedges(::Type{Bar5_t}) = 2 @inline edges2nodes(::Type{Bar5_t}) = ((1,), (2,)) @inline edgetypes(::Type{Bar5_t}) = (Node_t(), Node_t()) @inline nfaces(t::Type{Bar5_t}) = nedges(t) @inline faces2nodes(t::Type{Bar5_t}) = edges2nodes(t) @inline facetypes(t::Type{Bar5_t}) = edgetypes(t) #-Tri3 ---- @inline nnodes(::Type{Tri3_t}) = 3 @inline nodes(::Type{Tri3_t}) = (1, 2, 3) @inline nedges(::Type{Tri3_t}) = 3 @inline edges2nodes(::Type{Tri3_t}) = ((1, 2), (2, 3), (3, 1)) @inline edgetypes(::Type{Tri3_t}) = (Bar2_t(), Bar2_t(), Bar2_t()) @inline nfaces(t::Type{Tri3_t}) = nedges(t) @inline faces2nodes(t::Type{Tri3_t}) = edges2nodes(t) @inline facetypes(t::Type{Tri3_t}) = edgetypes(t) #-Tri6 ---- @inline nnodes(::Type{Tri6_t}) = 6 @inline nodes(::Type{Tri6_t}) = (1, 2, 3, 4, 5, 6) @inline nedges(::Type{Tri6_t}) = 3 @inline edges2nodes(::Type{Tri6_t}) = ((1, 2, 4), (2, 3, 5), (3, 1, 6)) @inline edgetypes(::Type{Tri6_t}) = (Bar3_t(), Bar3_t(), Bar3_t()) @inline nfaces(t::Type{Tri6_t}) = nedges(t) @inline faces2nodes(t::Type{Tri6_t}) = edges2nodes(t) @inline facetypes(t::Type{Tri6_t}) = edgetypes(t) #-Tri9 ---- @inline nnodes(::Type{Tri9_t}) = 9 @inline nodes(::Type{Tri9_t}) = (1, 2, 3, 4, 5, 6, 7, 8, 9) @inline nedges(::Type{Tri9_t}) = 3 @inline edges2nodes(::Type{Tri9_t}) = ((1, 2, 4, 5), (2, 3, 6, 7), (3, 1, 8, 9)) @inline edgetypes(::Type{Tri9_t}) = (Bar4_t(), Bar4_t(), Bar4_t()) @inline nfaces(t::Type{Tri9_t}) = nedges(t) @inline faces2nodes(t::Type{Tri9_t}) = edges2nodes(t) @inline facetypes(t::Type{Tri9_t}) = edgetypes(t) #-Tri10 ---- @inline nnodes(::Type{Tri10_t}) = 10 @inline nodes(::Type{Tri10_t}) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) @inline nedges(::Type{Tri10_t}) = 3 @inline edges2nodes(::Type{Tri10_t}) = ((1, 2, 4, 5), (2, 3, 6, 7), (3, 1, 8, 9)) @inline edgetypes(::Type{Tri10_t}) = (Bar4_t(), Bar4_t(), Bar4_t()) @inline nfaces(t::Type{Tri10_t}) = nedges(t) @inline faces2nodes(t::Type{Tri10_t}) = edges2nodes(t) @inline facetypes(t::Type{Tri10_t}) = edgetypes(t) #-Tri12---- @inline nnodes(::Type{Tri12_t}) = 12 @inline nodes(::Type{Tri12_t}) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) @inline nedges(::Type{Tri12_t}) = 3 @inline function edges2nodes(::Type{Tri12_t}) ((1, 2, 4, 5, 6), (2, 3, 7, 8, 9), (3, 1, 10, 11, 12)) end @inline edgetypes(::Type{Tri12_t}) = (Bar5_t(), Bar5_t(), Bar5_t()) @inline nfaces(t::Type{Tri12_t}) = nedges(t) @inline faces2nodes(t::Type{Tri12_t}) = edges2nodes(t) @inline facetypes(t::Type{Tri12_t}) = edgetypes(t) #---- Quad4 ---- @inline nnodes(::Type{Quad4_t}) = 4 @inline nodes(::Type{Quad4_t}) = (1, 2, 3, 4) @inline nedges(::Type{Quad4_t}) = 4 @inline edges2nodes(::Type{Quad4_t}) = ((1, 2), (2, 3), (3, 4), (4, 1)) @inline edgetypes(::Type{Quad4_t}) = (Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t()) @inline nfaces(t::Type{Quad4_t}) = nedges(t) @inline faces2nodes(t::Type{Quad4_t}) = edges2nodes(t) @inline facetypes(t::Type{Quad4_t}) = edgetypes(t) #---- Quad8 ---- @inline nnodes(::Type{Quad8_t}) = 8 @inline nodes(::Type{Quad8_t}) = (1, 2, 3, 4, 5, 6, 7, 8) @inline nedges(::Type{Quad8_t}) = 4 @inline edges2nodes(::Type{Quad8_t}) = ((1, 2, 5), (2, 3, 6), (3, 4, 7), (4, 1, 8)) @inline edgetypes(::Type{Quad8_t}) = (Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t()) @inline nfaces(t::Type{Quad8_t}) = nedges(t) @inline faces2nodes(t::Type{Quad8_t}) = edges2nodes(t) @inline facetypes(t::Type{Quad8_t}) = edgetypes(t) #---- Quad9 ---- @inline nnodes(::Type{Quad9_t}) = 9 @inline nodes(::Type{Quad9_t}) = (1, 2, 3, 4, 5, 6, 7, 8, 9) @inline nedges(::Type{Quad9_t}) = 4 @inline edges2nodes(::Type{Quad9_t}) = ((1, 2, 5), (2, 3, 6), (3, 4, 7), (4, 1, 8)) @inline edgetypes(::Type{Quad9_t}) = (Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t()) @inline nfaces(t::Type{Quad9_t}) = nedges(t) @inline faces2nodes(t::Type{Quad9_t}) = edges2nodes(t) @inline facetypes(t::Type{Quad9_t}) = edgetypes(t) #---- Quad16 ---- @inline nnodes(::Type{Quad16_t}) = 16 @inline nodes(::Type{Quad16_t}) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) @inline nedges(::Type{Quad16_t}) = 4 @inline function edges2nodes(::Type{Quad16_t}) ((1, 2, 5, 6), (2, 3, 7, 8), (3, 4, 9, 10), (4, 1, 11, 12)) end @inline edgetypes(::Type{Quad16_t}) = (Bar4_t(), Bar4_t(), Bar4_t(), Bar4_t()) @inline nfaces(t::Type{Quad16_t}) = nedges(t) @inline faces2nodes(t::Type{Quad16_t}) = edges2nodes(t) @inline facetypes(t::Type{Quad16_t}) = edgetypes(t) #---- Tetra4 ---- @inline nnodes(::Type{Tetra4_t}) = 4 @inline nodes(::Type{Tetra4_t}) = (1, 2, 3, 4) @inline nedges(::Type{Tetra4_t}) = 6 @inline edges2nodes(::Type{Tetra4_t}) = ((1, 2), (2, 3), (3, 1), (1, 4), (2, 4), (3, 4)) @inline function edgetypes(::Type{Tetra4_t}) (Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t()) end @inline nfaces(t::Type{Tetra4_t}) = 4 @inline faces2nodes(::Type{Tetra4_t}) = ((1, 3, 2), (1, 2, 4), (2, 3, 4), (3, 1, 4)) @inline facetypes(::Type{Tetra4_t}) = (Tri3_t(), Tri3_t(), Tri3_t(), Tri3_t()) #---- Tetra10 ---- @inline nnodes(::Type{Tetra10_t}) = 10 @inline nodes(::Type{Tetra10_t}) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) @inline nedges(::Type{Tetra10_t}) = 6 @inline function edges2nodes(::Type{Tetra10_t}) ((1, 2, 5), (2, 3, 6), (3, 1, 7), (1, 4, 8), (2, 4, 9), (3, 4, 10)) end @inline function edgetypes(::Type{Tetra10_t}) (Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t()) end @inline nfaces(t::Type{Tetra10_t}) = 4 @inline function faces2nodes(::Type{Tetra10_t}) ((1, 3, 2, 7, 6, 5), (1, 2, 4, 5, 9, 8), (2, 3, 4, 6, 10, 9), (3, 1, 4, 7, 8, 10)) end @inline facetypes(::Type{Tetra10_t}) = (Tri6_t(), Tri6_t(), Tri6_t()) #---- Hexa8 ---- @inline nnodes(::Type{Hexa8_t}) = 8 @inline nodes(::Type{Hexa8_t}) = (1, 2, 3, 4, 5, 6, 7, 8) @inline nedges(::Type{Hexa8_t}) = 12 @inline function edges2nodes(::Type{Hexa8_t}) ( (1, 2), (2, 3), (3, 4), (4, 1), (1, 5), (2, 6), (3, 7), (4, 8), (5, 6), (6, 7), (7, 8), (8, 5), ) end @inline function edgetypes(::Type{Hexa8_t}) ( Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), ) end @inline nfaces(::Type{Hexa8_t}) = 6 @inline function faces2nodes(::Type{Hexa8_t}) ((1, 4, 3, 2), (1, 2, 6, 5), (2, 3, 7, 6), (3, 4, 8, 7), (1, 5, 8, 4), (5, 6, 7, 8)) end @inline facetypes(t::Type{Hexa8_t}) = Tuple([Quad4_t() for _ in 1:nfaces(t)]) #---- Hexa27 ---- # Warning : follow CGNS convention -> different from GMSH convention @inline nnodes(::Type{Hexa27_t}) = 27 @inline function nodes(::Type{Hexa27_t}) ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, ) end @inline nedges(::Type{Hexa27_t}) = 12 @inline function edges2nodes(::Type{Hexa27_t}) ( (1, 2, 9), (2, 3, 10), (3, 4, 11), (4, 1, 12), (1, 5, 13), (2, 6, 14), (3, 7, 15), (4, 8, 16), (5, 6, 17), (6, 7, 18), (7, 8, 19), (8, 5, 20), ) end @inline function edgetypes(::Type{Hexa27_t}) ( Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), Bar3_t(), ) end @inline nfaces(::Type{Hexa27_t}) = 6 @inline function faces2nodes(::Type{Hexa27_t}) ( (1, 4, 3, 2, 12, 11, 10, 9, 21), (1, 2, 6, 5, 9, 14, 17, 13, 22), (2, 3, 7, 6, 10, 15, 18, 14, 23), (3, 4, 8, 7, 11, 16, 19, 15, 24), (1, 5, 8, 4, 13, 20, 16, 12, 25), (5, 6, 7, 8, 17, 18, 19, 20, 26), ) end @inline function facetypes(::Type{Hexa27_t}) (Quad9_t(), Quad9_t(), Quad9_t(), Quad9_t(), Quad9_t(), Quad9_t()) end #---- Penta6_t (=Prism) ---- @inline nnodes(::Type{Penta6_t}) = 6 @inline nodes(::Type{Penta6_t}) = (1, 2, 3, 4, 5, 6) @inline nedges(::Type{Penta6_t}) = 9 @inline function edges2nodes(::Type{Penta6_t}) ((1, 2), (2, 3), (3, 1), (1, 4), (2, 5), (3, 6), (4, 5), (5, 6), (6, 4)) end @inline function edgetypes(::Type{Penta6_t}) ( Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), Bar2_t(), ) end @inline nfaces(::Type{Penta6_t}) = 5 @inline function faces2nodes(::Type{Penta6_t}) ((1, 2, 5, 4), (2, 3, 6, 5), (3, 1, 4, 6), (1, 3, 2), (4, 5, 6)) end @inline facetypes(::Type{Penta6_t}) = (Quad4_t(), Quad4_t(), Quad4_t(), Tri3_t(), Tri3_t()) #---- Pyra5_t ---- @inline nnodes(::Type{Pyra5_t}) = 5 @inline nodes(::Type{Pyra5_t}) = (1, 2, 3, 4, 5) @inline nedges(::Type{Pyra5_t}) = 8 @inline function edges2nodes(::Type{Pyra5_t}) ((1, 2), (2, 3), (3, 4), (4, 1), (1, 5), (2, 5), (3, 5), (4, 5)) end @inline edgetypes(::Type{Pyra5_t}) = ntuple(Bar2_t(), nedges(Pyra5_t())) @inline nfaces(::Type{Pyra5_t}) = 5 @inline function faces2nodes(::Type{Pyra5_t}) ((1, 4, 3, 2), (1, 2, 5), (2, 3, 5), (3, 4, 5), (4, 1, 5)) end @inline facetypes(::Type{Pyra5_t}) = (Quad4_t(), Tri3_t(), Tri3_t(), Tri3_t(), Tri3_t()) #---- Poly2_t ---- @inline nnodes(::Type{Poly2_t}) = error("Function ‘nnodes‘ is not defined for ‘Poly2_t‘") @inline nodes(::Type{Poly2_t}) = error("Function ‘nodes‘ is not defined for ‘Poly2_t‘") @inline nedges(::Type{Poly2_t}) = error("Function ‘nedges‘ is not defined for ‘Poly2_t‘") @inline function edges2nodes(::Type{Poly2_t}) error("Function edges2nodes is not defined for ‘Poly2_t‘") end @inline nfaces(::Type{Poly2_t}) = error("Function nfaces is not defined for ‘Poly2_t‘") @inline function faces2nodes(::Type{Poly2_t}) error("Function ‘faces2nodes‘ is not defined for ‘Poly2_t‘") end #---- Poly3_t ---- @inline nnodes(::Type{Poly3_t}) = error("Function ‘nnodes‘ is not defined for ‘Poly3_t‘") @inline nodes(::Type{Poly3_t}) = error("Function ‘nodes‘ is not defined for ‘Poly3_t‘") @inline nedges(::Type{Poly3_t}) = error("Function ‘nedges‘ is not defined for Poly3_t") @inline function edges2nodes(::Type{Poly3_t}) error("Function edges2nodes is not defined for Poly3_t") end @inline nfaces(::Type{Poly3_t}) = error("Function nfaces is not defined for Poly3_t") @inline function faces2nodes(::Type{Poly3_t}) error("Function ‘faces2nodes‘ is not defined for Poly3_t") end function f2n_from_c2n(t, c2n::NTuple{N, T}) where {N, T} map_ref = faces2nodes(t) @assert N === nnodes(t) "Error : invalid number of nodes" ntuple(i -> ntuple(j -> c2n[map_ref[i][j]], length(map_ref[i])), length(map_ref)) end function f2n_from_c2n(t, c2n::AbstractVector) @assert length(c2n) === nnodes(t) "Error : invalid number of nodes ($(length(c2n)) ≠ $(nnodes(t)))" map_ref = faces2nodes(t) #SVector{length(map_ref)}(ntuple(i -> SVector{length(map_ref[i])}(ntuple(j -> c2n[map_ref[i][j]] , length(map_ref[i]))) ,length(map_ref))) ntuple( i -> SVector{length(map_ref[i])}( ntuple(j -> c2n[map_ref[i][j]], length(map_ref[i])), ), length(map_ref), ) end function cell_side(t::AbstractEntityType, c2n::AbstractVector, f2n::AbstractVector) all_f2n = f2n_from_c2n(t, c2n) side = myfindfirst(x -> x ⊆ f2n, all_f2n) end function oriented_cell_side(t::AbstractEntityType, c2n::AbstractVector, f2n::AbstractVector) all_f2n = f2n_from_c2n(t, c2n) side = findfirst(x -> x ⊆ f2n, all_f2n) if side ≠ nothing n = findfirst(isequal(f2n[1]), all_f2n[side]) n === nothing ? n1 = 0 : n1 = n if length(f2n) === 2 n1 == 2 ? (return -side) : (return side) else n1 + 1 > length(all_f2n[side]) ? n2 = 1 : n2 = n1 + 1 f2n[2] == all_f2n[side][n2] ? nothing : side = -side return side end end return 0 end """ A `Node` is a point in space of dimension `dim`. """ struct Node{spaceDim, T} x::SVector{spaceDim, T} end Node(x::Vector{T}) where {T} = Node{length(x), T}(SVector{length(x), T}(x)) @inline get_coords(n::Node) = n.x get_coords(n::Node, i) = get_coords(n)[i] get_coords(n::Node, i::Tuple{T, Vararg{T}}) where {T} = map(j -> get_coords(n, j), i) @inline spacedim(::Node{spaceDim, T}) where {spaceDim, T} = spaceDim function center(nodes::AbstractVector{T}) where {T <: Node} Node(sum(n -> get_coords(n), nodes) / length(nodes)) end function Base.isapprox(a::Node, b::Node, c...; d...) isapprox(get_coords(a), get_coords(b), c...; d...) end distance(a::Node, b::Node) = norm(get_coords(a) - get_coords(b)) # TopologyStyle helps dealing of curve in 2D/3D space (isCurvilinear), # surfaces in 3D space (isSurfacic) or R^n entity in a R^n space (isVolumic) abstract type TopologyStyle end struct isNodal <: TopologyStyle end struct isCurvilinear <: TopologyStyle end struct isSurfacic <: TopologyStyle end struct isVolumic <: TopologyStyle end """ topology_style(::AbstractEntityType{topoDim}, ::Node{spaceDim, T}) where {topoDim, spaceDim, T} topology_style(::AbstractEntityType{topoDim}, ::AbstractArray{Node{spaceDim, T}, N}) where {spaceDim, T, N, topoDim} Indicate the `TopologyStyle` of an entity of topology `topoDim` living in space of dimension `spaceDim`. """ @inline topology_style( ::AbstractEntityType{topoDim}, ::Node{spaceDim, T}, ) where {topoDim, spaceDim, T} = isVolumic() # everything is volumic by default # Any "Node" is... nodal @inline topology_style(::AbstractEntityType{0}, ::Node{spaceDim, T}) where {spaceDim, T} = isNodal() # Any "line" in R^2 or R^3 is curvilinear @inline topology_style(::AbstractEntityType{1}, ::Node{2, T}) where {T} = isCurvilinear() @inline topology_style(::AbstractEntityType{1}, ::Node{3, T}) where {T} = isCurvilinear() # A surface in R^2 is "volumic" @inline topology_style(::AbstractEntityType{2}, ::Node{2, T}) where {T} = isVolumic() # Any other surface is "surfacic" @inline topology_style(::AbstractEntityType{2}, ::Node{spaceDim, T}) where {spaceDim, T} = isSurfacic() @inline topology_style( etype::AbstractEntityType{topoDim}, nodes::AbstractArray{Node{spaceDim, T}, N}, ) where {spaceDim, T, N, topoDim} = topology_style(etype, nodes[1])
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
43170
import gmsh_jll include(gmsh_jll.gmsh_api) import .gmsh # Constants const GMSHTYPE = Dict( 1 => Bar2_t(), 2 => Tri3_t(), 3 => Quad4_t(), 4 => Tetra4_t(), 5 => Hexa8_t(), 6 => Penta6_t(), 7 => Pyra5_t(), 9 => Tri6_t(), 10 => Quad9_t(), 21 => Tri9_t(), 21 => Tri10_t(), 36 => Quad16_t(), ) """ read_msh(path::String, spaceDim::Int = 0; verbose::Bool = false) Read a .msh file designated by its `path`. See `read_msh()` for more details. """ function read_msh(path::String, spaceDim::Int = 0; verbose::Bool = false) isfile(path) ? nothing : error("File does not exist ", path) # Read file using gmsh lib gmsh.initialize() gmsh.option.setNumber("General.Terminal", Int(verbose)) gmsh.open(path) # build mesh mesh = _read_msh(spaceDim, verbose) # free gmsh gmsh.finalize() return mesh end """ _read_msh(spaceDim::Int, verbose::Bool) To use this function, the `gmsh` file must have been opened already (see `read_msh(path::String)` for instance). The number of topological dimensions is given by the highest dimension found in the file. The number of space dimensions is deduced from the axis dimensions if `spaceDim = 0`. If `spaceDim` is set to a positive number, this number is used as the number of space dimensions. # Implementation Global use of `gmsh` module. Do not try to improve this function by passing an argument such as `gmsh` or `gmsh.model` : it leads to problems. """ function _read_msh(spaceDim::Int, verbose::Bool) # Spatial dimension of the mesh dim = gmsh.model.getDimension() # Read nodes ids, xyz = gmsh.model.mesh.getNodes() # Create a node number remapping to ensure a dense numbering absolute_node_indices = [convert(Int, i) for i in ids] _, glo2loc_node_indices = densify(absolute_node_indices; permute_back = true) # Build nodes coordinates xyz = reshape(xyz, 3, :) _spaceDim = spaceDim > 0 ? spaceDim : _compute_space_dim(verbose) nodes = [Node(xyz[1:_spaceDim, i]) for i in axes(xyz, 2)] # Read cells elementTypes, elementTags, nodeTags = gmsh.model.mesh.getElements(dim) # Create a cell number remapping to ensure a dense numbering absolute_cell_indices = Int.(reduce(vcat, elementTags)) _, glo2loc_cell_indices = densify(absolute_cell_indices; permute_back = true) # Read boundary conditions bc_tags = gmsh.model.getPhysicalGroups(-1) bc_names = [gmsh.model.getPhysicalName(_dim, _tag) for (_dim, _tag) in bc_tags] # keep only physical groups of dimension "dim-1" with none-empty names. # bc is a vector of (tag,name) for all valid boundary conditions bc = [ (_tag, _name) for ((_dim, _tag), _name) in zip(bc_tags, bc_names) if _dim == dim - 1 && _name ≠ "" ] bc_names = Dict(convert(Int, _tag) => _name for (_tag, _name) in bc) bc_nodes = Dict( convert(Int, _tag) => Int[ glo2loc_node_indices[i] for i in gmsh.model.mesh.getNodesForPhysicalGroup(dim - 1, _tag)[1] ] for (_tag, _name) in bc ) # Fill type of each cell celltypes = [ GMSHTYPE[k] for (i, k) in enumerate(elementTypes) for t in 1:length(elementTags[i]) ] # Build cell->node connectivity (with Gmsh internal numbering convention) c2n_gmsh = Connectivity( Int[nnodes(k) for k in reduce(vcat, celltypes)], Int[glo2loc_node_indices[k] for k in reduce(vcat, nodeTags)], ) # Convert to CGNS numbering c2n = _c2n_gmsh2cgns(celltypes, c2n_gmsh) mesh = Mesh(nodes, celltypes, c2n; bc_names = bc_names, bc_nodes = bc_nodes) add_absolute_indices!(mesh, :node, absolute_node_indices) add_absolute_indices!(mesh, :cell, absolute_cell_indices) return mesh end """ read_msh_with_cell_names(path::String, spaceDim = 0; verbose = false) Read a .msh file designated by its `path` and also return names and tags """ function read_msh_with_cell_names(path::String, spaceDim = 0; verbose = false) isfile(path) ? nothing : error("File does not exist ", path) # Read file using gmsh lib gmsh.initialize() gmsh.option.setNumber("General.Terminal", Int(verbose)) gmsh.open(path) mesh, el_names, el_names_inv, el_cells, glo2loc_cell_indices = _read_msh_with_cell_names(spaceDim, verbose) # free gmsh gmsh.finalize() return mesh, el_names, el_names_inv, el_cells, glo2loc_cell_indices end """ To use this function, the `gmsh` file must have been opened already (see `read_msh_with_cell_names(path::String)` for instance). """ function _read_msh_with_cell_names(spaceDim::Int, verbose::Bool) # build mesh _spaceDim = spaceDim > 0 ? spaceDim : _compute_space_dim(verbose) mesh = _read_msh(_spaceDim, verbose) # Read volumic physical groups (build a dict tag -> name) el_tags = gmsh.model.getPhysicalGroups(_spaceDim) _el_names = [gmsh.model.getPhysicalName(_dim, _tag) for (_dim, _tag) in el_tags] el = [ (_tag, _name) for ((_dim, _tag), _name) in zip(el_tags, _el_names) if _dim == _spaceDim && _name ≠ "" ] el_names = Dict(convert(Int, _tag) => _name for (_tag, _name) in el) el_names_inv = Dict(_name => convert(Int, _tag) for (_tag, _name) in el) # Read cell indices associated to each volumic physical group el_cells = Dict{Int, Array{Int}}() for (_dim, _tag) in el_tags v = Int[] for iEntity in gmsh.model.getEntitiesForPhysicalGroup(_dim, _tag) tmpTypes, tmpTags, tmpNodeTags = gmsh.model.mesh.getElements(_dim, iEntity) # Notes : a PhysicalGroup "entity" can contain different types of elements. # So `tmpTags` is an array of the cell indices of each type in the Physical group. for _tmpTags in tmpTags v = vcat(v, Int.(_tmpTags)) end end el_cells[_tag] = v end absolute_cell_indices = absolute_indices(mesh, :cell) _, glo2loc_cell_indices = densify(absolute_cell_indices; permute_back = true) return mesh, el_names, el_names_inv, el_cells, glo2loc_cell_indices end """ Deduce the number of space dimensions from the mesh : if one (or more) dimension of the bounding box is way lower than the other dimensions, the number of space dimension is decreased. Currently, having for instance (x,z) is not supported. Only (x), or (x,y), or (x,y,z). """ function _compute_space_dim(verbose::Bool) tol = 1e-15 topodim = gmsh.model.getDimension() # Bounding box box = gmsh.model.getBoundingBox(-1, -1) lx = box[4] - box[1] ly = box[5] - box[2] lz = box[6] - box[3] return _compute_space_dim(topodim, lx, ly, lz, tol, verbose) end function _apply_gmsh_options(; split_files = false, create_ghosts = false, msh_format = 0, verbose = false, ) gmsh.option.setNumber("General.Terminal", Int(verbose)) gmsh.option.setNumber("Mesh.PartitionSplitMeshFiles", Int(split_files)) gmsh.option.setNumber("Mesh.PartitionCreateGhostCells", Int(create_ghosts)) (msh_format > 0) && gmsh.option.setNumber("Mesh.MshFileVersion", msh_format) end """ gen_line_mesh( output; nx = 2, lx = 1.0, xc = 0.0, order = 1, bnd_names = ("LEFT", "RIGHT"), n_partitions = 0, kwargs... ) Generate a 1D mesh of a segment and write to "output". Available kwargs are * `verbose` : `true` or `false` to enable gmsh verbose * `msh_format` : floating number indicating the output msh format (for instance : `2.2`) * `split_files` : if `true`, create one file by partition * `create_ghosts` : if `true`, add a layer of ghost cells at every partition boundary """ function gen_line_mesh( output; nx = 2, lx = 1.0, xc = 0.0, order = 1, bnd_names = ("LEFT", "RIGHT"), n_partitions = 0, kwargs..., ) gmsh.initialize() _apply_gmsh_options(; kwargs...) lc = 1e-1 # Points A = gmsh.model.geo.addPoint(xc - lx / 2, 0, 0, lc) B = gmsh.model.geo.addPoint(xc + lx / 2, 0, 0, lc) # Line AB = gmsh.model.geo.addLine(A, B) # Mesh settings gmsh.model.geo.mesh.setTransfiniteCurve(AB, nx) # Define boundaries (`0` stands for 0D, i.e nodes) # ("-1" to create a new tag) gmsh.model.addPhysicalGroup(0, [A], -1, bnd_names[1]) gmsh.model.addPhysicalGroup(0, [B], -1, bnd_names[2]) gmsh.model.addPhysicalGroup(1, [AB], -1, "Domain") # Gen mesh gmsh.model.geo.synchronize() gmsh.model.mesh.generate(1) gmsh.model.mesh.setOrder(order) # Mesh order gmsh.model.mesh.partition(n_partitions) # Write result gmsh.write(output) # End gmsh.finalize() end """ gen_rectangle_mesh( output, type; transfinite = false, nx = 2, ny = 2, lx = 1.0, ly = 1.0, xc = -1.0, yc = -1.0, order = 1, bnd_names = ("North", "South", "East", "West"), n_partitions = 0, write_geo = false, transfinite_lines = true, lc = 1e-1, kwargs... ) Generate a 2D mesh of a rectangle domain and write the mesh to `output`. Use `type` to specify the element types: `:tri` or `:quad`. For kwargs, see [`gen_line_mesh`](@ref). """ function gen_rectangle_mesh( output, type; transfinite = false, nx = 2, ny = 2, lx = 1.0, ly = 1.0, xc = -1.0, yc = -1.0, order = 1, bnd_names = ("North", "South", "East", "West"), n_partitions = 0, write_geo = false, transfinite_lines = true, lc = 1e-1, kwargs..., ) # North # D ------- C # | | # West | | East # | | # A ------- B # South gmsh.initialize() _apply_gmsh_options(; kwargs...) # Points A = gmsh.model.geo.addPoint(xc - lx / 2, yc - ly / 2, 0, lc) B = gmsh.model.geo.addPoint(xc + lx / 2, yc - ly / 2, 0, lc) C = gmsh.model.geo.addPoint(xc + lx / 2, yc + ly / 2, 0, lc) D = gmsh.model.geo.addPoint(xc - lx / 2, yc + ly / 2, 0, lc) # Lines AB = gmsh.model.geo.addLine(A, B) BC = gmsh.model.geo.addLine(B, C) CD = gmsh.model.geo.addLine(C, D) DA = gmsh.model.geo.addLine(D, A) # Contour ABCD = gmsh.model.geo.addCurveLoop([AB, BC, CD, DA]) # Surface surf = gmsh.model.geo.addPlaneSurface([ABCD]) # Mesh settings if transfinite_lines gmsh.model.geo.mesh.setTransfiniteCurve(AB, nx) gmsh.model.geo.mesh.setTransfiniteCurve(BC, ny) gmsh.model.geo.mesh.setTransfiniteCurve(CD, nx) gmsh.model.geo.mesh.setTransfiniteCurve(DA, ny) end (transfinite || type == :quad) && gmsh.model.geo.mesh.setTransfiniteSurface(surf) (type == :quad) && gmsh.model.geo.mesh.setRecombine(2, surf) # Synchronize gmsh.model.geo.synchronize() # Define boundaries (`1` stands for 1D, i.e lines) south = gmsh.model.addPhysicalGroup(1, [AB]) east = gmsh.model.addPhysicalGroup(1, [BC]) north = gmsh.model.addPhysicalGroup(1, [CD]) west = gmsh.model.addPhysicalGroup(1, [DA]) domain = gmsh.model.addPhysicalGroup(2, [ABCD]) gmsh.model.setPhysicalName(1, south, bnd_names[2]) gmsh.model.setPhysicalName(1, east, bnd_names[3]) gmsh.model.setPhysicalName(1, north, bnd_names[1]) gmsh.model.setPhysicalName(1, west, bnd_names[4]) gmsh.model.setPhysicalName(2, domain, "Domain") # Gen mesh gmsh.model.mesh.generate(2) gmsh.model.mesh.setOrder(order) gmsh.model.mesh.partition(n_partitions) # Write result rm(output; force = true) gmsh.write(output) if write_geo output_geo = first(splitext(output)) * ".geo_unrolled" rm(output_geo; force = true) gmsh.write(output_geo) end # End gmsh.finalize() end """ gen_mesh_around_disk( output, type; r_in = 1.0, r_ext = 10.0, nθ = 360, nr = 100, nr_prog = 1.05, order = 1, recombine = true, bnd_names = ("Farfield", "Wall"), n_partitions = 0, kwargs... ) Mesh the 2D domain around a disk. `type` can be `:quad` or `:tri`. For kwargs, see [`gen_line_mesh`](@ref). """ function gen_mesh_around_disk( output, type; r_int = 1.0, r_ext = 10.0, nθ = 360, nr = 100, nr_prog = 1.05, order = 1, recombine = true, bnd_names = ("Farfield", "Wall"), n_partitions = 0, write_geo = false, kwargs..., ) @assert type ∈ (:tri, :quad) gmsh.initialize() _apply_gmsh_options(; kwargs...) lc_ext = 2π * r_ext / (nθ - 1) lc_int = 2π * r_int / (nθ - 1) # Points O = gmsh.model.geo.addPoint(0.0, 0.0, 0.0) Ae = gmsh.model.geo.addPoint(r_ext * cos(-3π / 4), r_ext * sin(-3π / 4), 0.0, lc_ext) Be = gmsh.model.geo.addPoint(r_ext * cos(-π / 4), r_ext * sin(-π / 4), 0.0, lc_ext) Ce = gmsh.model.geo.addPoint(r_ext * cos(π / 4), r_ext * sin(π / 4), 0.0, lc_ext) De = gmsh.model.geo.addPoint(r_ext * cos(3π / 4), r_ext * sin(3π / 4), 0.0, lc_ext) Ai = gmsh.model.geo.addPoint(r_int * cos(-3π / 4), r_int * sin(-3π / 4), 0.0, lc_int) Bi = gmsh.model.geo.addPoint(r_int * cos(-π / 4), r_int * sin(-π / 4), 0.0, lc_int) Ci = gmsh.model.geo.addPoint(r_int * cos(π / 4), r_int * sin(π / 4), 0.0, lc_int) Di = gmsh.model.geo.addPoint(r_int * cos(3π / 4), r_int * sin(3π / 4), 0.0, lc_int) # Curves AOBe = gmsh.model.geo.addCircleArc(Ae, O, Be) BOCe = gmsh.model.geo.addCircleArc(Be, O, Ce) CODe = gmsh.model.geo.addCircleArc(Ce, O, De) DOAe = gmsh.model.geo.addCircleArc(De, O, Ae) AOBi = gmsh.model.geo.addCircleArc(Ai, O, Bi) BOCi = gmsh.model.geo.addCircleArc(Bi, O, Ci) CODi = gmsh.model.geo.addCircleArc(Ci, O, Di) DOAi = gmsh.model.geo.addCircleArc(Di, O, Ai) # Surfaces if type == :quad # Curves AiAe = gmsh.model.geo.addLine(Ai, Ae) BiBe = gmsh.model.geo.addLine(Bi, Be) CiCe = gmsh.model.geo.addLine(Ci, Ce) DiDe = gmsh.model.geo.addLine(Di, De) # Contours _AB = gmsh.model.geo.addCurveLoop([AiAe, AOBe, -BiBe, -AOBi]) _BC = gmsh.model.geo.addCurveLoop([BiBe, BOCe, -CiCe, -BOCi]) _CD = gmsh.model.geo.addCurveLoop([CiCe, CODe, -DiDe, -CODi]) _DA = gmsh.model.geo.addCurveLoop([DiDe, DOAe, -AiAe, -DOAi]) # Surfaces AB = gmsh.model.geo.addPlaneSurface([_AB]) BC = gmsh.model.geo.addPlaneSurface([_BC]) CD = gmsh.model.geo.addPlaneSurface([_CD]) DA = gmsh.model.geo.addPlaneSurface([_DA]) # Mesh settings for arc in [AOBe, BOCe, CODe, DOAe, AOBi, BOCi, CODi, DOAi] gmsh.model.geo.mesh.setTransfiniteCurve(arc, round(Int, nθ / 4)) end for rad in [AiAe, BiBe, CiCe, DiDe] gmsh.model.geo.mesh.setTransfiniteCurve(rad, nr, "Progression", nr_prog) end for surf in [AB, BC, CD, DA] gmsh.model.geo.mesh.setTransfiniteSurface(surf) recombine && gmsh.model.geo.mesh.setRecombine(2, surf) end surfaces = [AB, BC, CD, DA] elseif type == :tri # Contours loop_ext = gmsh.model.geo.addCurveLoop([AOBe, BOCe, CODe, DOAe]) loop_int = gmsh.model.geo.addCurveLoop([AOBi, BOCi, CODi, DOAi]) # Surface surfaces = [gmsh.model.geo.addPlaneSurface([loop_ext, loop_int])] end # Synchronize gmsh.model.geo.synchronize() # Define boundaries (`1` stands for 1D, i.e lines) farfield = gmsh.model.addPhysicalGroup(1, [AOBe, BOCe, CODe, DOAe]) wall = gmsh.model.addPhysicalGroup(1, [AOBi, BOCi, CODi, DOAi]) domain = gmsh.model.addPhysicalGroup(2, surfaces) gmsh.model.setPhysicalName(1, farfield, bnd_names[1]) gmsh.model.setPhysicalName(1, wall, bnd_names[2]) gmsh.model.setPhysicalName(2, domain, "Domain") # Gen mesh gmsh.model.mesh.generate(2) gmsh.model.mesh.setOrder(order) gmsh.model.mesh.partition(n_partitions) # Write result gmsh.write(output) if write_geo output_geo = first(splitext(output)) * ".geo_unrolled" rm(output_geo; force = true) gmsh.write(output_geo) end # End gmsh.finalize() end """ gen_rectangle_mesh_with_tri_and_quad( output; nx = 2, ny = 2, lx = 1.0, ly = 1.0, xc = -1.0, yc = -1.0, order = 1, n_partitions = 0, kwargs... ) Generate a 2D mesh of a rectangle domain and write the mesh to `output`. The domain is split vertically in two parts: the upper part is composed of 'quad' cells and the lower part with 'tri'. North D ------- C | :quad | West M₁|---------|M₂ East | :tri | A ------- B South For kwargs, see [`gen_line_mesh`](@ref). """ function gen_rectangle_mesh_with_tri_and_quad( output; nx = 2, ny = 2, lx = 1.0, ly = 1.0, xc = -1.0, yc = -1.0, order = 1, n_partitions = 0, kwargs..., ) # South gmsh.initialize() _apply_gmsh_options(; kwargs...) lc = 1e-1 # Points A = gmsh.model.geo.addPoint(xc - lx / 2, yc - ly / 2, 0, lc) B = gmsh.model.geo.addPoint(xc + lx / 2, yc - ly / 2, 0, lc) C = gmsh.model.geo.addPoint(xc + lx / 2, yc + ly / 2, 0, lc) D = gmsh.model.geo.addPoint(xc - lx / 2, yc + ly / 2, 0, lc) M₁ = gmsh.model.geo.addPoint(xc - lx / 2, yc, 0, lc) M₂ = gmsh.model.geo.addPoint(xc + lx / 2, yc, 0, lc) # Lines AB = gmsh.model.geo.addLine(A, B) BM₂ = gmsh.model.geo.addLine(B, M₂) M₂C = gmsh.model.geo.addLine(M₂, C) CD = gmsh.model.geo.addLine(C, D) DM₁ = gmsh.model.geo.addLine(D, M₁) M₁A = gmsh.model.geo.addLine(M₁, A) M₁M₂ = gmsh.model.geo.addLine(M₁, M₂) # Contour ABM₂M₁ = gmsh.model.geo.addCurveLoop([AB, BM₂, -M₁M₂, M₁A]) M₁M₂CD = gmsh.model.geo.addCurveLoop([M₁M₂, M₂C, CD, DM₁]) # Surface lower_surf = gmsh.model.geo.addPlaneSurface([ABM₂M₁]) upper_surf = gmsh.model.geo.addPlaneSurface([M₁M₂CD]) # Mesh settings gmsh.model.geo.mesh.setTransfiniteCurve(AB, nx) gmsh.model.geo.mesh.setTransfiniteCurve(CD, nx) gmsh.model.geo.mesh.setTransfiniteCurve(M₁M₂, nx) gmsh.model.geo.mesh.setTransfiniteCurve(BM₂, floor(Int, ny / 2) + 1) gmsh.model.geo.mesh.setTransfiniteCurve(M₂C, floor(Int, ny / 2) + 1) gmsh.model.geo.mesh.setTransfiniteCurve(DM₁, floor(Int, ny / 2) + 1) gmsh.model.geo.mesh.setTransfiniteCurve(M₁A, floor(Int, ny / 2) + 1) gmsh.model.geo.mesh.setTransfiniteSurface(upper_surf) gmsh.model.geo.mesh.setRecombine(2, upper_surf) # Synchronize gmsh.model.geo.synchronize() # Define boundaries (`1` stands for 1D, i.e lines) south = gmsh.model.addPhysicalGroup(1, [AB]) east = gmsh.model.addPhysicalGroup(1, [BM₂, M₂C]) north = gmsh.model.addPhysicalGroup(1, [CD]) west = gmsh.model.addPhysicalGroup(1, [DM₁, M₁A]) domain = gmsh.model.addPhysicalGroup(2, [ABM₂M₁, M₁M₂CD]) gmsh.model.setPhysicalName(1, south, "South") gmsh.model.setPhysicalName(1, east, "East") gmsh.model.setPhysicalName(1, north, "North") gmsh.model.setPhysicalName(1, west, "West") gmsh.model.setPhysicalName(2, domain, "Domain") # Gen mesh gmsh.model.mesh.generate(2) gmsh.model.mesh.setOrder(order) gmsh.model.mesh.partition(n_partitions) # Write result gmsh.write(output) # End gmsh.finalize() end """ gen_hexa_mesh( output, type; transfinite = false, nx = 2, ny = 2, nz = 2, lx = 1.0, ly = 1.0, lz = 1.0, xc = -1.0, yc = -1.0, zc = -1.0, order = 1, bnd_names = ("xmin", "xmax", "ymin", "ymax", "zmin", "zmax"), n_partitions = 0, write_geo = false, transfinite_lines = true, lc = 1e-1, kwargs..., ) Generate a 3D mesh of a hexahedral domain and write the mesh to `output`. Use `type` to specify the element types: `:tetra` or `:hexa`. For kwargs, see [`gen_line_mesh`](@ref). """ function gen_hexa_mesh( output, type; nx = 2, ny = 2, nz = 2, lx = 1.0, ly = 1.0, lz = 1.0, xc = -1.0, yc = -1.0, zc = -1.0, order = 1, bnd_names = ("xmin", "xmax", "ymin", "ymax", "zmin", "zmax"), n_partitions = 0, write_geo = false, transfinite = (type == :hexa), transfinite_lines = (type == :hexa), lc = 1e-1, kwargs..., ) @assert type ∈ (:tetra, :hexa) "`type` can only be :tetra or :hexa" @assert !((type == :hexa) && !transfinite_lines) "Cannot mix :hexa option with transfinite_lines=false" isHexa = type == :hexa gmsh.initialize() gmsh.model.add("model") # helps debugging _apply_gmsh_options(; kwargs...) # Points A = gmsh.model.geo.addPoint(xc - lx / 2, yc - ly / 2, zc - lz / 2, lc) B = gmsh.model.geo.addPoint(xc + lx / 2, yc - ly / 2, zc - lz / 2, lc) C = gmsh.model.geo.addPoint(xc + lx / 2, yc + ly / 2, zc - lz / 2, lc) D = gmsh.model.geo.addPoint(xc - lx / 2, yc + ly / 2, zc - lz / 2, lc) # Lines AB = gmsh.model.geo.addLine(A, B) BC = gmsh.model.geo.addLine(B, C) CD = gmsh.model.geo.addLine(C, D) DA = gmsh.model.geo.addLine(D, A) # Contour loop = gmsh.model.geo.addCurveLoop([AB, BC, CD, DA]) # Surface ABCD = gmsh.model.geo.addPlaneSurface([loop]) # Extrusion nlayers = (transfinite || isHexa || transfinite_lines) ? [nz - 1] : [] recombine = (transfinite || isHexa) out = gmsh.model.geo.extrude([(2, ABCD)], 0, 0, lz, nlayers, [], recombine) # Identification zmin = ABCD zmax = out[1][2] vol = out[2][2] ymin = out[3][2] xmax = out[4][2] ymax = out[5][2] xmin = out[6][2] # Mesh settings if transfinite_lines gmsh.model.geo.mesh.setTransfiniteCurve(AB, nx) gmsh.model.geo.mesh.setTransfiniteCurve(BC, ny) gmsh.model.geo.mesh.setTransfiniteCurve(CD, nx) gmsh.model.geo.mesh.setTransfiniteCurve(DA, ny) end (transfinite || isHexa) && gmsh.model.geo.mesh.setTransfiniteSurface(ABCD) isHexa && gmsh.model.geo.mesh.setRecombine(2, ABCD) # Synchronize gmsh.model.geo.synchronize() # Define boundaries (`1` stands for 1D, i.e lines) gmsh.model.addPhysicalGroup(2, [xmin], -1, bnd_names[1]) gmsh.model.addPhysicalGroup(2, [xmax], -1, bnd_names[2]) gmsh.model.addPhysicalGroup(2, [ymin], -1, bnd_names[3]) gmsh.model.addPhysicalGroup(2, [ymax], -1, bnd_names[4]) gmsh.model.addPhysicalGroup(2, [zmin], -1, bnd_names[5]) gmsh.model.addPhysicalGroup(2, [zmax], -1, bnd_names[6]) gmsh.model.addPhysicalGroup(3, [vol], -1, "Domain") # Gen mesh gmsh.model.mesh.generate(3) gmsh.model.mesh.setOrder(order) gmsh.model.mesh.partition(n_partitions) # Write result rm(output; force = true) gmsh.write(output) if write_geo output_geo = first(splitext(output)) * ".geo_unrolled" rm(output_geo; force = true) gmsh.write(output_geo) end # End gmsh.finalize() end """ gen_disk_mesh( output; radius = 1.0, lc = 1e-1, order = 1, n_partitions = 0, kwargs... ) Generate a 2D mesh of a disk domain and write the mesh to `output`. For kwargs, see [`gen_line_mesh`](@ref). """ function gen_disk_mesh( output; radius = 1.0, lc = 1e-1, order = 1, n_partitions = 0, kwargs..., ) gmsh.initialize() _apply_gmsh_options(; kwargs...) # Points O = gmsh.model.geo.addPoint(0, 0, 0, lc) A = gmsh.model.geo.addPoint(radius, 0, 0, lc) B = gmsh.model.geo.addPoint(-radius, 0, 0, lc) # Lines AOB = gmsh.model.geo.addCircleArc(A, O, B) BOA = gmsh.model.geo.addCircleArc(B, O, A) # Contour circle = gmsh.model.geo.addCurveLoop([AOB, BOA]) # Surface disk = gmsh.model.geo.addPlaneSurface([circle]) # Synchronize gmsh.model.geo.synchronize() # Define boundaries (`1` stands for 1D, i.e lines) border = gmsh.model.addPhysicalGroup(1, [AOB, BOA]) domain = gmsh.model.addPhysicalGroup(2, [disk]) gmsh.model.setPhysicalName(1, border, "BORDER") gmsh.model.setPhysicalName(2, domain, "Domain") # Gen mesh gmsh.model.mesh.generate(2) gmsh.model.mesh.setOrder(order) gmsh.model.mesh.partition(n_partitions) # Write result gmsh.write(output) # End gmsh.finalize() end """ gen_star_disk_mesh( output, ε, m; nθ = 360, radius = 1.0, lc = 1e-1, order = 1, n_partitions = 0, kwargs..., ) Generate a 2D mesh of a star domain and write the mesh to `output`. The "star" wall is defined by ``r_{wall} = R \\left( 1 + \\varepsilon \\cos(m \\theta) \\right)``. For kwargs, see [`gen_line_mesh`](@ref). """ function gen_star_disk_mesh( output, ε, m; nθ = 360, radius = 1.0, lc = 1e-1, order = 1, n_partitions = 0, kwargs..., ) gmsh.initialize() _apply_gmsh_options(; kwargs...) # Alias R = radius # Points pts = [] sizehint!(pts, nθ) for θ in range(0, 2π; length = nθ + 1) # 0 and 2π are identical so 2π will be removed rw = R * (1 + ε * cos(m * θ)) push!(pts, gmsh.model.geo.addPoint(rw * cos(θ), rw * sin(θ), 0, lc)) end pop!(pts) # remove duplicated point created by '2π' push!(pts, pts[1]) # repeat first point index -> needed for closed lines # Lines #spline = gmsh.model.geo.addSpline(pts) # Polyline seems not available in gmsh 4.0.5 #polyline = gmsh.model.geo.addPolyline(pts) # Polyline seems not available in gmsh 4.0.5 lines = [] sizehint!(lines, nθ) for (p1, p2) in zip(pts, pts[2:end]) push!(lines, gmsh.model.geo.addLine(p1, p2)) # the line [pn, p1] is taken into account end # # Contour #loop = gmsh.model.geo.addCurveLoop([spline]) #loop = gmsh.model.geo.addCurveLoop([polyline]) loop = gmsh.model.geo.addCurveLoop(lines) # # Surface disk = gmsh.model.geo.addPlaneSurface([loop]) # Synchronize gmsh.model.geo.synchronize() # Define boundaries (`1` stands for 1D, i.e lines) wall = gmsh.model.addPhysicalGroup(1, lines) domain = gmsh.model.addPhysicalGroup(2, [disk]) gmsh.model.setPhysicalName(1, wall, "WALL") gmsh.model.setPhysicalName(2, domain, "Domain") # Gen mesh gmsh.model.mesh.generate(2) gmsh.model.mesh.setOrder(order) gmsh.model.mesh.partition(n_partitions) # Write result gmsh.write(output) # End gmsh.finalize() end """ gen_cylinder_mesh( output, Lz, nz; radius = 1.0, lc = 1e-1, order = 1, n_partitions = 0, kwargs... ) Generate a 3D mesh of a cylindrical domain and length `L` and write the mesh to `output`. For kwargs, see [`gen_line_mesh`](@ref). """ function gen_cylinder_mesh( output, Lz, nz; radius = 1.0, lc = 1e-1, order = 1, n_partitions = 0, kwargs..., ) gmsh.initialize() _apply_gmsh_options(; kwargs...) # Points -> need for 4 arcs for extrusion otherwise crash O = gmsh.model.geo.addPoint(0, 0, 0, lc) A = gmsh.model.geo.addPoint(radius, 0, 0, lc) B = gmsh.model.geo.addPoint(0, radius, 0, lc) C = gmsh.model.geo.addPoint(-radius, 0, 0, lc) D = gmsh.model.geo.addPoint(0, -radius, 0, lc) # Lines AOB = gmsh.model.geo.addCircleArc(A, O, B) BOC = gmsh.model.geo.addCircleArc(B, O, C) COD = gmsh.model.geo.addCircleArc(C, O, D) DOA = gmsh.model.geo.addCircleArc(D, O, A) # Contour circle = gmsh.model.geo.addCurveLoop([AOB, BOC, COD, DOA]) # Surface disk = gmsh.model.geo.addPlaneSurface([circle]) gmsh.model.geo.synchronize() # Extrude : 1 layer divided in `nz` heights out = gmsh.model.geo.extrude([(2, disk)], 0.0, 0.0, Lz, [nz], [], true) # out[1] = (dim, tag) is the top of disk extruded # out[2] = (dim, tag) is the volume created by the extrusion # out[3] = (dim, tag) is the side created by the extrusion of AOB, (1st first element of contour `circle`) # out[4] = (dim, tag) is the side created by the extrusion of BOC, (2nd first element of contour `circle`) # out[5] = (dim, tag) is the side created by the extrusion of COD, (3rd first element of contour `circle`) # out[6] = (dim, tag) is the side created by the extrusion of DOA, (4fh first element of contour `circle`) # Synchronize gmsh.model.geo.synchronize() # Define boundaries (`1` stands for 1D, i.e lines) border = gmsh.model.addPhysicalGroup(2, [out[3][2], out[4][2], out[5][2], out[6][2]]) inlet = gmsh.model.addPhysicalGroup(2, [disk]) outlet = gmsh.model.addPhysicalGroup(2, [out[1][2]]) domain = gmsh.model.addPhysicalGroup(3, [out[2][2]]) gmsh.model.setPhysicalName(2, border, "BORDER") gmsh.model.setPhysicalName(2, inlet, "INLET") gmsh.model.setPhysicalName(2, outlet, "OUTLET") gmsh.model.setPhysicalName(3, domain, "Domain") # Gen mesh gmsh.model.mesh.generate(3) gmsh.model.mesh.setOrder(order) gmsh.model.mesh.partition(n_partitions) # Write result gmsh.write(output) # End gmsh.finalize() end """ gen_sphere_mesh( output; radius = 1.0, lc = 1e-1, order = 1, n_partitions = 0, kwargs..., ) Generate the mesh of a sphere (surface of topological dimension 2, spatial dimension 3). """ function gen_sphere_mesh( output; radius = 1.0, lc = 1e-1, order = 1, n_partitions = 0, kwargs..., ) gmsh.initialize() _apply_gmsh_options(; kwargs...) # Points P1 = gmsh.model.geo.addPoint(0, 0, 0, lc) P2 = gmsh.model.geo.addPoint(radius, 0, 0, lc) P3 = gmsh.model.geo.addPoint(0, radius, 0, lc) P4 = gmsh.model.geo.addPoint(0, 0, radius, lc) P5 = gmsh.model.geo.addPoint(-radius, 0, 0, lc) P6 = gmsh.model.geo.addPoint(0, -radius, 0, lc) P7 = gmsh.model.geo.addPoint(0, 0, -radius, lc) # Line C1 = gmsh.model.geo.addCircleArc(P2, P1, P3) C2 = gmsh.model.geo.addCircleArc(P3, P1, P5) C3 = gmsh.model.geo.addCircleArc(P5, P1, P6) C4 = gmsh.model.geo.addCircleArc(P6, P1, P2) C5 = gmsh.model.geo.addCircleArc(P2, P1, P7) C6 = gmsh.model.geo.addCircleArc(P7, P1, P5) C7 = gmsh.model.geo.addCircleArc(P5, P1, P4) C8 = gmsh.model.geo.addCircleArc(P4, P1, P2) C9 = gmsh.model.geo.addCircleArc(P6, P1, P7) C10 = gmsh.model.geo.addCircleArc(P7, P1, P3) C11 = gmsh.model.geo.addCircleArc(P3, P1, P4) C12 = gmsh.model.geo.addCircleArc(P4, P1, P6) # Loops LL1 = gmsh.model.geo.addCurveLoop([C1, C11, C8]) LL2 = gmsh.model.geo.addCurveLoop([C2, C7, -C11]) LL3 = gmsh.model.geo.addCurveLoop([C3, -C12, -C7]) LL4 = gmsh.model.geo.addCurveLoop([C4, -C8, C12]) LL5 = gmsh.model.geo.addCurveLoop([C5, C10, -C1]) LL6 = gmsh.model.geo.addCurveLoop([-C2, -C10, C6]) LL7 = gmsh.model.geo.addCurveLoop([-C3, -C6, -C9]) LL8 = gmsh.model.geo.addCurveLoop([-C4, C9, -C5]) # Surfaces RS = map([LL1, LL2, LL3, LL4, LL5, LL6, LL7, LL8]) do LL gmsh.model.geo.addSurfaceFilling([LL]) end # Domains sphere = gmsh.model.addPhysicalGroup(2, RS) gmsh.model.setPhysicalName(2, sphere, "Sphere") # Gen mesh gmsh.model.geo.synchronize() gmsh.model.mesh.generate(2) gmsh.model.mesh.setOrder(order) gmsh.model.mesh.partition(n_partitions) # Write result gmsh.write(output) # End gmsh.finalize() end """ _gen_2cubes_mesh(output) Only for testing purpose. D------E------F | | | | | | A------B------C """ function _gen_2cubes_mesh(output) lc = 1.0 gmsh.initialize() gmsh.option.setNumber("General.Terminal", 0) # Points A = gmsh.model.geo.addPoint(0, 0, 0, lc) B = gmsh.model.geo.addPoint(1, 0, 0, lc) C = gmsh.model.geo.addPoint(2, 0, 0, lc) D = gmsh.model.geo.addPoint(0, 1, 0, lc) E = gmsh.model.geo.addPoint(1, 1, 0, lc) F = gmsh.model.geo.addPoint(2, 1, 0, lc) # Line AB = gmsh.model.geo.addLine(A, B) BC = gmsh.model.geo.addLine(B, C) DE = gmsh.model.geo.addLine(D, E) EF = gmsh.model.geo.addLine(E, F) AD = gmsh.model.geo.addLine(A, D) BE = gmsh.model.geo.addLine(B, E) CF = gmsh.model.geo.addLine(C, F) # Surfaces ABED = gmsh.model.geo.addPlaneSurface([gmsh.model.geo.addCurveLoop([AB, BE, -DE, -AD])]) BCFE = gmsh.model.geo.addPlaneSurface([gmsh.model.geo.addCurveLoop([BC, CF, -EF, -BE])]) # Extrusion gmsh.model.geo.extrude([(2, ABED), (2, BCFE)], 0, 0, 1, [1], [], true) for l in (AB, BC, DE, EF, AD, BE, CF) gmsh.model.geo.mesh.setTransfiniteCurve(l, 2) end for s in (ABED, BCFE) gmsh.model.geo.mesh.setTransfiniteSurface(s) gmsh.model.geo.mesh.setRecombine(2, s) end # Gen mesh gmsh.model.geo.synchronize() gmsh.model.mesh.generate(3) # Write result gmsh.write(output) # End gmsh.finalize() end """ gen_cylinder_shell_mesh( output, nθ, nz; radius = 1.0, lz = 1.0, lc = 1e-1, order = 1, n_partitions = 0, recombine = false, transfinite = false, kwargs..., ) # Implementation Extrusion is not used to enable "random" tri filling (whereas with extrusion we can at worse obtain regular rectangle triangle) """ function gen_cylinder_shell_mesh( output, nθ, nz; radius = 1.0, lz = 1.0, lc = 1e-1, order = 1, n_partitions = 0, recombine = false, transfinite = false, kwargs..., ) gmsh.initialize() gmsh.model.add("model") # helps debugging _apply_gmsh_options(; kwargs...) # Points O1 = gmsh.model.geo.addPoint(0, 0, 0, lc) O2 = gmsh.model.geo.addPoint(0, 0, lz, lc) A1 = gmsh.model.geo.addPoint(radius, 0, 0, lc) B1 = gmsh.model.geo.addPoint(radius * cos(2π / 3), radius * sin(2π / 3), 0, lc) C1 = gmsh.model.geo.addPoint(radius * cos(4π / 3), radius * sin(4π / 3), 0, lc) A2 = gmsh.model.geo.addPoint(radius, 0, lz, lc) B2 = gmsh.model.geo.addPoint(radius * cos(2π / 3), radius * sin(2π / 3), lz, lc) C2 = gmsh.model.geo.addPoint(radius * cos(4π / 3), radius * sin(4π / 3), lz, lc) # Lines AOB1 = gmsh.model.geo.addCircleArc(A1, O1, B1) BOC1 = gmsh.model.geo.addCircleArc(B1, O1, C1) COA1 = gmsh.model.geo.addCircleArc(C1, O1, A1) AOB2 = gmsh.model.geo.addCircleArc(A2, O2, B2) BOC2 = gmsh.model.geo.addCircleArc(B2, O2, C2) COA2 = gmsh.model.geo.addCircleArc(C2, O2, A2) A1A2 = gmsh.model.geo.addLine(A1, A2) B1B2 = gmsh.model.geo.addLine(B1, B2) C1C2 = gmsh.model.geo.addLine(C1, C2) # Surfaces loops = [ gmsh.model.geo.addCurveLoop([AOB1, B1B2, -AOB2, -A1A2]), gmsh.model.geo.addCurveLoop([BOC1, C1C2, -BOC2, -B1B2]), gmsh.model.geo.addCurveLoop([COA1, A1A2, -COA2, -C1C2]), ] surfs = map(loop -> gmsh.model.geo.addSurfaceFilling([loop]), loops) # Mesh settings if transfinite _nθ = round(Int, nθ / 3) foreach( line -> gmsh.model.geo.mesh.setTransfiniteCurve(line, _nθ), (AOB1, BOC1, COA1, AOB2, BOC2, COA2), ) foreach( line -> gmsh.model.geo.mesh.setTransfiniteCurve(line, nz), (A1A2, B1B2, C1C2), ) foreach(gmsh.model.geo.mesh.setTransfiniteSurface, surfs) end recombine && map(surf -> gmsh.model.geo.mesh.setRecombine(2, surf), surfs) gmsh.model.geo.synchronize() # Define boundaries (`1` stands for 1D, i.e lines) domain = gmsh.model.addPhysicalGroup(2, surfs) bottom = gmsh.model.addPhysicalGroup(1, [AOB1, BOC1, COA1]) top = gmsh.model.addPhysicalGroup(1, [AOB2, BOC2, COA2]) gmsh.model.setPhysicalName(1, bottom, "zmin") gmsh.model.setPhysicalName(1, top, "zmax") gmsh.model.setPhysicalName(2, domain, "domain") # Gen mesh gmsh.model.mesh.generate(2) gmsh.model.mesh.setOrder(order) gmsh.model.mesh.partition(n_partitions) # Write result gmsh.write(output) # End gmsh.finalize() end """ _gen_cube_pile(output) Only for testing purpose. G------H | | | | D------E------F | | | | | | A------B------C """ function _gen_cube_pile(output) lc = 1.0 gmsh.initialize() gmsh.option.setNumber("General.Terminal", 0) # Points A = gmsh.model.geo.addPoint(0, 0, 0, lc) B = gmsh.model.geo.addPoint(1, 0, 0, lc) C = gmsh.model.geo.addPoint(2, 0, 0, lc) D = gmsh.model.geo.addPoint(0, 1, 0, lc) E = gmsh.model.geo.addPoint(1, 1, 0, lc) F = gmsh.model.geo.addPoint(2, 1, 0, lc) G = gmsh.model.geo.addPoint(1, 2, 0, lc) H = gmsh.model.geo.addPoint(2, 2, 0, lc) # Line AB = gmsh.model.geo.addLine(A, B) BC = gmsh.model.geo.addLine(B, C) DE = gmsh.model.geo.addLine(D, E) EF = gmsh.model.geo.addLine(E, F) GH = gmsh.model.geo.addLine(G, H) AD = gmsh.model.geo.addLine(A, D) BE = gmsh.model.geo.addLine(B, E) CF = gmsh.model.geo.addLine(C, F) EG = gmsh.model.geo.addLine(E, G) FH = gmsh.model.geo.addLine(F, H) # Surfaces ABED = gmsh.model.geo.addPlaneSurface([gmsh.model.geo.addCurveLoop([AB, BE, -DE, -AD])]) BCFE = gmsh.model.geo.addPlaneSurface([gmsh.model.geo.addCurveLoop([BC, CF, -EF, -BE])]) EFHG = gmsh.model.geo.addPlaneSurface([gmsh.model.geo.addCurveLoop([EF, FH, -GH, -EG])]) # Extrusion out = gmsh.model.geo.extrude([(2, ABED), (2, BCFE), (2, EFHG)], 0, 0, 1, [1], [], true) gmsh.model.geo.extrude([out[7]], 0, 0, 1, [1], [], true) for l in (AB, BC, DE, EF, GH, AD, BE, CF, EG, FH) gmsh.model.geo.mesh.setTransfiniteCurve(l, 2) end for s in (ABED, BCFE, EFHG) gmsh.model.geo.mesh.setTransfiniteSurface(s) gmsh.model.geo.mesh.setRecombine(2, s) end # Gen mesh gmsh.model.geo.synchronize() gmsh.model.mesh.generate(3) # Write result gmsh.write(output) # End gmsh.finalize() end """ gen_torus_shell_mesh(output, rint, rext; order = 1, lc = 0.1, write_geo = false, kwargs...) Generate the mesh of the shell of a torus, defined by its inner radius `rint` and exterior radius `rext`. The torus revolution axis is the z-axis. """ function gen_torus_shell_mesh( output, rint, rext; order = 1, lc = 0.1, write_geo = false, n_partitions = 0, kwargs..., ) gmsh.initialize() gmsh.model.add("model") # helps debugging _apply_gmsh_options(; kwargs...) # Points xc = (rint + rext) / 2 r = (rext - rint) / 2 O = gmsh.model.geo.addPoint(xc, 0, 0, lc) A = gmsh.model.geo.addPoint(xc + r, 0, 0, lc) B = gmsh.model.geo.addPoint(xc + r * cos(2π / 3), 0, r * sin(2π / 3), lc) C = gmsh.model.geo.addPoint(xc + r * cos(4π / 3), 0, r * sin(4π / 3), lc) # Lines AOB = gmsh.model.geo.addCircleArc(A, O, B) BOC = gmsh.model.geo.addCircleArc(B, O, C) COA = gmsh.model.geo.addCircleArc(C, O, A) # Surfaces opts = (0, 0, 0, 0, 0, 1, 2π / 3) out = gmsh.model.geo.revolve([(1, AOB), (1, BOC), (1, COA)], opts...) rev1_AOB = out[1:4] rev1_BOC = out[5:8] rev1_COA = out[9:12] out = gmsh.model.geo.revolve([rev1_AOB[1], rev1_BOC[1], rev1_COA[1]], opts...) rev2_AOB = out[1:4] rev2_BOC = out[5:8] rev2_COA = out[9:12] out = gmsh.model.geo.revolve([rev2_AOB[1], rev2_BOC[1], rev2_COA[1]], opts...) rev3_AOB = out[1:4] rev3_BOC = out[5:8] rev3_COA = out[9:12] # Gen mesh gmsh.model.geo.synchronize() gmsh.model.mesh.generate(2) gmsh.model.mesh.setOrder(order) gmsh.model.mesh.partition(n_partitions) # Write result gmsh.write(output) if write_geo output_geo = first(splitext(output)) * ".geo_unrolled" gmsh.write(output_geo) end # End gmsh.finalize() end """ nodes_gmsh2cgns(entity::AbstractEntityType, nodes::AbstractArray) Reorder `nodes` of a given `entity` from the Gmsh format to CGNS format. See https://gmsh.info/doc/texinfo/gmsh.html#Node-ordering """ function nodes_gmsh2cgns(entity::AbstractEntityType, nodes::AbstractArray) map(i -> nodes[i], nodes_gmsh2cgns(entity)) end nodes_gmsh2cgns(e) = nodes_gmsh2cgns(typeof(e)) function nodes_gmsh2cgns(::Type{<:T}) where {T <: AbstractEntityType} error("Function nodes_gmsh2cgns is not defined for type $T") end nodes_gmsh2cgns(e::Type{Node_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Bar2_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Bar3_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Bar4_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Bar5_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Tri3_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Tri6_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Tri9_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Tri10_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Tri12_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Quad4_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Quad8_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Quad9_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Quad16_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Tetra4_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Tetra10_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Hexa8_t}) = nodes(e) #same numbering between CGNS and Gmsh function nodes_gmsh2cgns(::Type{Hexa27_t}) SA[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 17, 18, 19, 20, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26, 27, ] end nodes_gmsh2cgns(e::Type{Penta6_t}) = nodes(e) #same numbering between CGNS and Gmsh nodes_gmsh2cgns(e::Type{Pyra5_t}) = nodes(e) #same numbering between CGNS and Gmsh """ Convert a cell->node connectivity with gmsh numbering convention to a cell->node connectivity with CGNs numbering convention. """ function _c2n_gmsh2cgns(celltypes, c2n_gmsh) n = Int[] indices = Int[] for (ct, c2nᵢ) in zip(celltypes, c2n_gmsh) append!(n, length(c2nᵢ)) append!(indices, nodes_gmsh2cgns(ct, c2nᵢ)) end return Connectivity(n, indices) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
15668
""" # Implementation All subtypes should implement the following functions: * `Base.parent(AbstractMesh)` (default should be `Base.parent(m::MyMesh) = m`) """ abstract type AbstractMesh{topoDim, spaceDim} end topodim(::AbstractMesh{topoDim, spaceDim}) where {topoDim, spaceDim} = topoDim spacedim(::AbstractMesh{topoDim, spaceDim}) where {topoDim, spaceDim} = spaceDim function topodim(::AbstractMesh{topoDim}, label::Symbol) where {topoDim} if label == :node || label == :vertex return 0 elseif label == :edge return 1 elseif label == :face return topoDim - 1 elseif label == :cell return topoDim else throw(ArgumentError("Expected label :node,:vertex,:edge,:face or :cell")) end end @inline boundary_tag(mesh::AbstractMesh, name::String) = boundary_tag(parent(mesh), name) abstract type AbstractMeshConnectivity end struct MeshConnectivity{C} <: AbstractMeshConnectivity from::Symbol to::Symbol by::Union{Symbol, Nothing} nLayers::Union{Int, Nothing} indices::C end function MeshConnectivity( from::Symbol, to::Symbol, by::Symbol, nLayers::Union{Int, Nothing}, connectivity::AbstractConnectivity, ) MeshConnectivity{typeof(connectivity)}(from, to, by, nLayers, connectivity) end function MeshConnectivity(from::Symbol, to::Symbol, by::Symbol, c::AbstractConnectivity) MeshConnectivity(from, to, by, nothing, c) end function MeshConnectivity(from::Symbol, to::Symbol, c::AbstractConnectivity) MeshConnectivity(from, to, nothing, nothing, c) end @inline from(c::MeshConnectivity) = c.from @inline to(c::MeshConnectivity) = c.to @inline by(c::MeshConnectivity) = c.by @inline nlayers(c::MeshConnectivity) = c.nLayers @inline indices(c::MeshConnectivity) = c.indices Base.eltype(::MeshConnectivity{C}) where {C <: AbstractConnectivity} = eltype{C} function Base.iterate(c::MeshConnectivity{C}, i = 1) where {C <: AbstractConnectivity} return iterate(indices(c); i = 1) end function Base.show(io::IO, c::MeshConnectivity) println("--------------------") println("MeshConnectivity ") println("type: ", typeof(c)) println("from,to,by,nlayers = (", from(c), " ", to(c), " ", by(c), " ", nlayers(c), ")") println("indices :") show(indices(c)) println("--------------------") end """ `bc_names` : <boundary tag> => <boundary names> `bc_nodes` : <boundary tag> => <boundary nodes tags> `bc_faces` : <boundary tag> => <boundary faces tags> """ mutable struct Mesh{topoDim, spaceDim, C, E, T} <: AbstractMesh{topoDim, spaceDim} nodes::Vector{Node{spaceDim, T}} entities::E connectivities::C bc_names::Dict{Int, String} bc_nodes::Dict{Int, Vector{Int}} bc_faces::Dict{Int, Vector{Int}} absolute_indices::Dict{Symbol, Vector{Int}} local_indices::Dict{Symbol, Dict{Int, Int}} end function Mesh( topoDim::Int, nodes::Vector{Node{spaceDim, T}}, celltypes::Vector{E}, cell2node::C, buildfaces::Bool, buildboundaryfaces::Bool, bc_names::Dict{Int, String}, bc_nodes::Dict{Int, Vector{Int}}, bc_faces::Dict{Int, Vector{Int}}, ) where {T <: Real, spaceDim, E <: AbstractEntityType, C <: AbstractConnectivity} @assert topoDim ≤ spaceDim # to improve type-stability (through union-splitting if needed) celltypes = convert_to_vector_of_union(celltypes) nodetypes = Node_t[Node_t() for i in 1:length(nodes)] entities = (cell = celltypes, node = nodetypes) connectivities = Dict{Symbol, MeshConnectivity}() c2n = MeshConnectivity(:cell, :node, cell2node) connectivities = (c2n = c2n,) if buildfaces facetypes, c2f, f2c, f2n = _build_faces!(c2n, celltypes) facetypes = convert_to_vector_of_union(facetypes) # to improve type-stability (through union-splitting if needed) connectivities = (connectivities..., c2f = c2f, f2c = f2c, f2n = f2n) entities = (entities..., face = facetypes) _bc_faces = bc_faces end if buildboundaryfaces @assert buildfaces "Faces must be built before boundary faces" f2bc, _bc_faces = _build_boundary_faces!(f2n, f2c, bc_names, bc_nodes) connectivities = (connectivities..., f2bc = f2bc) end absolute_indices = Dict{Symbol, Vector{Int}}() local_indices = Dict{Symbol, Dict{Int, Int}}() Mesh{topoDim, spaceDim, typeof(connectivities), typeof(entities), T}( nodes, entities, connectivities, bc_names, bc_nodes, _bc_faces, absolute_indices, local_indices, ) end function Mesh( nodes, celltypes::Vector{E}, cell2nodes::C; buildfaces::Bool = true, buildboundaryfaces::Bool = false, bc_names::Dict{Int, String} = Dict{Int, String}(), bc_nodes::Dict{Int, Vector{Int}} = Dict{Int, Vector{Int}}(), bc_faces::Dict{Int, Vector{Int}} = Dict{Int, Vector{Int}}(), ) where {E <: AbstractEntityType, C <: AbstractConnectivity} topoDim = topodim(valtype(celltypes)) if buildboundaryfaces @assert (!isempty(bc_names) && !isempty(bc_nodes)) "bc_names and bc_nodes must be provided to build boundary faces" @assert isempty(bc_faces) "`bc_faces` is not supported yet" else (!isempty(bc_names) && !isempty(bc_nodes)) ? buildboundaryfaces = true : nothing end Mesh( topoDim, nodes, celltypes, cell2nodes, buildfaces, buildboundaryfaces, bc_names, bc_nodes, bc_faces, ) end Base.parent(mesh::Mesh) = mesh @inline get_nodes(mesh::Mesh) = mesh.nodes @inline get_nodes(mesh::Mesh, i::SVector) = mesh.nodes[i] @inline get_nodes(mesh::Mesh, i) = view(mesh.nodes, i) @inline get_nodes(mesh::Mesh, i::Int) = mesh.nodes[i] @inline set_nodes(mesh::Mesh, nodes) = mesh.nodes = nodes @inline entities(mesh::Mesh) = mesh.entities @inline entities(mesh::Mesh, e::Symbol) = entities(mesh)[e] @inline has_entities(mesh::Mesh, e::Symbol) = haskey(entities(mesh), e) @inline has_vertices(mesh::Mesh) = has_entities(mesh, :vertex) @inline has_nodes(mesh::Mesh) = has_entities(mesh, :node) @inline has_edges(mesh::Mesh) = has_entities(mesh, :edge) @inline has_faces(mesh::Mesh) = has_entities(mesh, :face) @inline has_cells(mesh::Mesh) = has_entities(mesh, :cell) @inline function n_entities(mesh::Mesh, e::Symbol) has_entities(mesh, e) ? length(entities(mesh, e)) : 0 end @inline nvertices(mesh::Mesh) = n_entities(mesh, :vertex) @inline nnodes(mesh::Mesh) = n_entities(mesh, :node) @inline nedges(mesh::Mesh) = n_entities(mesh, :edge) @inline nfaces(mesh::Mesh) = n_entities(mesh, :face) @inline ncells(mesh::Mesh) = n_entities(mesh, :cell) @inline nodes(mesh::Mesh) = entities(mesh, :node) @inline vertex(mesh::Mesh) = entities(mesh, :vertex) @inline edges(mesh::Mesh) = entities(mesh, :edges) @inline faces(mesh::Mesh) = entities(mesh, :face) @inline cells(mesh::Mesh) = entities(mesh, :cell) @inline connectivities(mesh::Mesh) = mesh.connectivities @inline has_connectivities(mesh::Mesh, c::Symbol) = haskey(connectivities(mesh), c) @inline connectivities(mesh::Mesh, c::Symbol) = connectivities(mesh)[c] @inline connectivities_indices(mesh::Mesh, c::Symbol) = indices(connectivities(mesh, c)) @inline boundary_names(mesh::Mesh) = mesh.bc_names @inline boundary_names(mesh::Mesh, tag) = mesh.bc_names[tag] @inline boundary_nodes(mesh::Mesh) = mesh.bc_nodes @inline boundary_nodes(mesh::Mesh, tag) = mesh.bc_nodes[tag] @inline boundary_faces(mesh::Mesh) = mesh.bc_faces @inline boundary_faces(mesh::Mesh, tag) = mesh.bc_faces[tag] @inline nboundaries(mesh::Mesh) = length(keys(boundary_names(mesh))) @inline function boundary_tag(mesh::Mesh, name::String) findfirst(i -> i == name, boundary_names(mesh)) end @inline boundary_faces(mesh::Mesh, name::String) = mesh.bc_faces[boundary_tag(mesh, name)] @inline absolute_indices(mesh::Mesh) = mesh.absolute_indices @inline absolute_indices(mesh::Mesh, e::Symbol) = mesh.absolute_indices[e] @inline local_indices(mesh::Mesh) = mesh.local_indices @inline local_indices(mesh::Mesh, e::Symbol) = mesh.local_indices[e] function add_absolute_indices!(mesh::Mesh, e::Symbol, indices::Vector{Int}) @assert n_entities(mesh, e) === length(indices) "invalid number of indices" mesh.absolute_indices[e] = indices mesh.local_indices[e] = Dict{Int, Int}(indices[i] => i for i in 1:length(indices)) return nothing end function _build_faces!(c2n::MeshConnectivity, celltypes) c2n_indices = indices(c2n) T = eltype(c2n_indices) #build face->cell connectivity dict_faces = Dict{Set{T}, T}() c2f_indices = [T[] for i in 1:length(celltypes)] f2c_indices = Vector{SVector{2, T}}() f2n_indices = Vector{Vector{T}}() face_types = Vector{AbstractEntityType}() sizehint!(f2c_indices, sum(nfaces, celltypes)) nface = zero(T) for (i, (_c, _c2n)) in enumerate(zip(celltypes, c2n_indices)) for (j, _f2n) in enumerate(f2n_from_c2n(_c, _c2n)) if !haskey(dict_faces, Set(_f2n)) #create a new face push!(f2c_indices, SVector{2, T}(i::T, zero(T))) push!(face_types, facetypes(_c)[j]) push!(f2n_indices, _f2n) nface += 1 dict_faces[Set(_f2n)] = nface push!(c2f_indices[i], nface) else iface = get(dict_faces, Set(_f2n), 0) f2c_indices[iface] = [f2c_indices[iface][1], i] push!(c2f_indices[i], iface) end end end c2f = MeshConnectivity( :cell, :face, Connectivity([length(a) for a in c2f_indices], reduce(vcat, c2f_indices)), ) numIndices = [sum(i -> i > zero(eltype(a)) ? 1 : 0, a) for a in f2c_indices] _indices = [f2c_indices[i][j] for i in eachindex(f2c_indices) for j in 1:numIndices[i]] f2c = MeshConnectivity(:face, :cell, Connectivity(numIndices, _indices)) f2n = MeshConnectivity( :face, :node, Connectivity([length(a) for a in f2n_indices], reduce(vcat, f2n_indices)), ) # try to convert `face_types` to a vector of concrete type when it is possible _face_types = identity.(face_types) return _face_types, c2f, f2c, f2n end function _build_boundary_faces!( f2n::MeshConnectivity, f2c::MeshConnectivity, bc_names, bc_nodes, ) @assert (bc_names ≠ nothing && bc_nodes ≠ nothing) "bc_names and bc_nodes must be defined" @assert (bc_names ≠ nothing && bc_nodes ≠ nothing) "bc_names and bc_nodes must be defined" @assert length(indices(f2n)) == length(indices(f2c)) "invalid f2n and/or f2c" @assert length(indices(f2n)) ≠ 0 "invalid f2n and/or f2c" # find boundary faces (all faces with only 1 adjacent cell) f2bc_numindices = zeros(Int, length(indices(f2n))) f2bc_indices = Vector{Int}() sizehint!(f2bc_indices, length(f2bc_numindices)) f2c = indices(f2c) for (iface, f2n) in enumerate(indices(f2n)) if length(f2c[iface]) == 1 # Search for associated BC (if any) # Rq: there might not be any BC, for instance if the face if a ghost-cell face for (tag, nodes) in bc_nodes if f2n ⊆ nodes push!(f2bc_indices, tag) f2bc_numindices[iface] = 1 break end end end end # add face->bc connectivities in mesh struct f2bc = MeshConnectivity(:face, :face, Connectivity(f2bc_numindices, f2bc_indices)) # create bc_faces if length(bc_names) > 0 f2bc_indices = indices(f2bc) #bc2f_indices = [[i for (i,bc) in enumerate(indices(f2bc)) if length(bc)>0 && bc[1]==bctag] for bctag in keys(bc_names)] #bc_faces = (;zip(Symbol.(keys(bc_names)), bc2f_indices)...) bc_faces = Dict{Int, Vector{Int}}() for bctag in keys(bc_names) bc_faces[bctag] = [ i for (i, bc) in enumerate(indices(f2bc)) if length(bc) > 0 && bc[1] == bctag ] end end return f2bc, bc_faces end function build_boundary_faces!(mesh::Mesh) @assert (mesh.bc_names ≠ nothing && mesh.bc_nodes ≠ nothing) "bc_names and bc_nodes must be defined" @assert (mesh.bc_names ≠ nothing && mesh.bc_nodes ≠ nothing) "bc_names and bc_nodes must be defined" @assert has_faces(mesh) "face entities must be created first" @assert has_connectivities(mesh, :f2n) "face->node connectivity must be defined" # find boundary faces (all faces with only 1 adjacent cell) f2bc_numindices = zeros(Int, nfaces(mesh)) f2bc_indices = Vector{Int}() sizehint!(f2bc_indices, length(f2bc_numindices)) f2c = connectivities_indices(mesh, :f2c) for (iface, f2n) in enumerate(connectivities_indices(mesh, :f2n)) if length(f2c[iface]) == 1 f2bc_numindices[iface] = 1 for (tag, nodes) in mesh.bc_nodes f2n ⊆ nodes ? (push!(f2bc_indices, tag); break) : nothing end end end # add face->bc connectivities in mesh struct mesh.connectivities[:f2bc] = MeshConnectivity(:face, :face, Connectivity(f2bc_numindices, f2bc_indices)) # create bc_faces if nboundaries(mesh) > 0 f2bc = connectivities_indices(mesh, :f2bc) for bctag in keys(mesh.bc_names) mesh.bc_faces[bctag] = [i for (i, bc) in enumerate(f2bc) if length(bc) > 0 && bc[1] == bctag] end end return nothing end """ connectivity_cell2cell_by_faces(mesh) Build the cell -> cell connectivity by looking at neighbors by faces. """ function connectivity_cell2cell_by_faces(mesh) f2c = connectivities_indices(mesh, :f2c) T = eltype(f2c) c2c = [T[] for _ in 1:ncells(mesh)] for k in 1:nfaces(mesh) _f2c = f2c[k] if length(_f2c) > 1 i = _f2c[1] j = _f2c[2] push!(c2c[i], j) push!(c2c[j], i) end end return Connectivity(length.(c2c), rawcat(c2c)) end """ connectivity_cell2cell_by_nodes(mesh) Build the cell -> cell connectivity by looking at neighbors by nodes. """ function connectivity_cell2cell_by_nodes(mesh) c2n = connectivities_indices(mesh, :c2n) n2c, _ = inverse_connectivity(c2n) T = eltype(n2c) c2c = [T[] for _ in 1:ncells(mesh)] # Loop over node->cells arrays for _n2c in n2c # For each cell, append the others as neighbors for ci in _n2c, cj in _n2c (cj ≠ ci) && push!(c2c[ci], cj) end end # Eliminate duplicates c2c = unique.(c2c) return Connectivity(length.(c2c), rawcat(c2c)) end """ oriented_cell_side(mesh::Mesh,icell::Int,iface::Int) Return the side number to which the face 'iface' belongs in the cell 'icell' of the mesh. A negative side number is returned if the face is inverted. Returns '0' if the face does not belongs the cell. """ function oriented_cell_side(mesh::Mesh, icell::Int, iface::Int) c = cells(mesh)[icell] c2n = indices(connectivities(mesh, :c2n))[icell] f2n = indices(connectivities(mesh, :f2n))[iface] oriented_cell_side(c, c2n, f2n) end """ inner_faces(mesh) Return the indices of the inner faces. """ function inner_faces(mesh) f2c = indices(connectivities(mesh, :f2c)) return findall([length(f2c[i]) > 1 for i in 1:nfaces(mesh)]) end """ outer_faces(mesh) Return the indices of the outer (=boundary) faces. """ function outer_faces(mesh) f2c = indices(connectivities(mesh, :f2c)) return findall([length(f2c[i]) == 1 for i in 1:nfaces(mesh)]) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
26835
""" basic_mesh() Generate a toy mesh of two quads and one triangle. v1 v2 v3 v4 +---e1-->+---e5-->+---e8-->+ ^ | | c3 / e4 c1 e2 c2 e6 e9 | | | / +<--e3---+<--e7---+/ v5 v6 v7 """ function basic_mesh(; coef_x = 1.0, coef_y = 1.0) x = coef_x .* [0.0, 1.0, 2.0, 3.0, 0.0, 1.0, 2.0] y = coef_y .* [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0] nodes = [Node([_x, _y]) for (_x, _y) in zip(x, y)] celltypes = Union{Quad4_t, Tri3_t}[Quad4_t(), Quad4_t(), Tri3_t()] # cell->node connectivity indices : cell2node = Connectivity([4, 4, 3], [1, 2, 6, 5, 2, 3, 7, 6, 3, 4, 7]) # Prepare boundary nodes bnd_name = "BORDER" tag2name = Dict(1 => bnd_name) tag2nodes = Dict(1 => collect(1:7)) return Mesh(nodes, celltypes, cell2node; bc_names = tag2name, bc_nodes = tag2nodes) end """ one_cell_mesh(type::Symbol, order = 1) Generate a mesh of one cell. `type` can be `:line`, `:quad`, `:tri`, `:hexa`, `:penta`, `:pyra`. The argument `order` refers to the geometry order. It has the same effect as the `-order` parameter in gmsh. """ function one_cell_mesh( type::Symbol; xmin = -1.0, xmax = 1.0, ymin = -1, ymax = 1, zmin = -1, zmax = 1.0, order = 1, ) if (type == :line || type == :bar) return one_line_mesh(Val(order), xmin, xmax) elseif (type == :quad || type == :square) return one_quad_mesh(Val(order), xmin, xmax, ymin, ymax) elseif (type == :tri || type == :triangle) return one_tri_mesh(Val(order), xmin, xmax, ymin, ymax) elseif (type == :tetra) return one_tetra_mesh(Val(order), xmin, xmax, ymin, ymax, zmin, zmax) elseif (type == :hexa || type == :cube) return one_hexa_mesh(Val(order), xmin, xmax, ymin, ymax, zmin, zmax) elseif (type == :prism || type == :penta) return one_prism_mesh(Val(order), xmin, xmax, ymin, ymax, zmin, zmax) elseif (type == :pyra) return one_pyra_mesh(Val(order), xmin, xmax, ymin, ymax, zmin, zmax) else throw(ArgumentError("Expected type :line, :quad, :tri, :hexa")) end end """ ncube_mesh(n::Vector{Int}; order = 1) Generate either a line mesh, a rectangle mesh, a cubic mesh... depending on the dimension of `n`. # Argument - `n` number of vertices in each spatial directions # Example ```julia-repl mesh_of_a_line = ncube_mesh([10]) mesh_of_a_square = ncube_mesh([4, 5]) mesh_of_a_hexa = ncube_mesh([4, 5, 6]) ``` """ function ncube_mesh(n::Vector{Int}; order = 1) if (length(n) == 1) return line_mesh(n[1]; order = order) elseif (length(n) == 2) return rectangle_mesh(n...; order = order) elseif (length(n) == 3) return hexa_mesh(n...; order = order) else throw(ArgumentError("mesh not available for R^" * string(length(n)))) end end """ line_mesh(n; xmin = 0., xmax = 1., order = 1, names = ("xmin", "xmax")) Generate a mesh of a line of `n` vertices. # Example ```julia-repl julia> mesh = line_mesh(5) ``` """ function line_mesh(n; xmin = 0.0, xmax = 1.0, order = 1, names = ("xmin", "xmax")) l = xmax - xmin # line length nelts = n - 1 # Number of cells # Linear elements if (order == 1) Δx = l / (n - 1) # Nodes nodes = [Node([xmin + (i - 1) * Δx]) for i in 1:n] # Cell type is constant celltypes = [Bar2_t() for ielt in 1:nelts] # Cell -> nodes connectivity cell2node = zeros(Int, 2 * nelts) for ielt in 1:nelts cell2node[2 * ielt - 1] = ielt cell2node[2 * ielt] = ielt + 1 end # Number of nodes of each cell : always 2 cell2nnodes = 2 * ones(Int, nelts) # Boundaries bc_names, bc_nodes = one_line_bnd(1, n, names) # Mesh return Mesh( nodes, celltypes, Connectivity(cell2nnodes, cell2node); bc_names, bc_nodes, ) # Quadratic elements elseif (order == 2) Δx = l / 2 / (n - 1) # Cell type is constant celltypes = [Bar3_t() for ielt in 1:nelts] # Nodes + Cell -> nodes connectivity nodes = Array{Node{1, Float64}}(undef, 2 * n - 1) cell2node = zeros(Int, 3 * nelts) nodes[1] = Node([xmin]) # First node i = 1 # init counter for ielt in 1:nelts # two new nodes : middle one and then right boundary nodes[i + 1] = xmin + i * Δx nodes[i + 2] = xmin + (i + 1) * Δx # cell -> node cell2node[3 * ielt - 2] = i cell2node[3 * ielt - 1] = i + 2 cell2node[3 * ielt - 0] = i + 1 # middle node # Update counter i += 2 end # Number of nodes of each cell : always 3 cell2nnodes = 3 * ones(Int, nelts) # Boundaries bc_names, bc_nodes = one_line_bnd(1, n, names) # Mesh return Mesh( nodes, celltypes, Connectivity(cell2nnodes, cell2node); bc_names, bc_nodes, ) else throw( ArgumentError( "`order` must be <= 2 (but feel free to implement higher orders)", ), ) end end """ rectangle_mesh( nx, ny; type = :quad, xmin = 0.0, xmax = 1.0, ymin = 0.0, ymax = 1.0, order = 1, bnd_names = ("xmin", "xmax", "ymin", "ymax"), ) Generate a 2D mesh of a rectangle with `nx` and `ny` vertices in the x and y directions respectively. # Example ```julia-repl julia> mesh = rectangle_mesh(5, 4) ``` """ function rectangle_mesh( nx, ny; type = :quad, xmin = 0.0, xmax = 1.0, ymin = 0.0, ymax = 1.0, order = 1, bnd_names = ("xmin", "xmax", "ymin", "ymax"), ) @assert (nx > 1 && ny > 1) "`nx` and `ny`, the number of nodes, must be greater than 1 (nx=$nx, ny=$ny)" if (type == :quad) return _rectangle_quad_mesh(nx, ny, xmin, xmax, ymin, ymax, Val(order), bnd_names) else throw( ArgumentError("`type` must be :quad (but feel free to implement other types)"), ) end end function _rectangle_quad_mesh(nx, ny, xmin, xmax, ymin, ymax, ::Val{1}, bnd_names) # Notes # 6-----8-----9 # | | | # | 3 | 4 | # | | | # 4-----5-----6 # | | | # | 1 | 2 | # | | | # 1-----2-----3 lx = xmax - xmin ly = ymax - ymin nelts = (nx - 1) * (ny - 1) Δx = lx / (nx - 1) Δy = ly / (ny - 1) # Prepare boundary nodes tag2name = Dict(tag => name for (tag, name) in enumerate(bnd_names)) tag2nodes = Dict(tag => Int[] for tag in 1:length(bnd_names)) # Nodes iglob = 1 nodes = Array{Node{2, Float64}}(undef, nx * ny) for iy in 1:ny for ix in 1:nx nodes[(iy - 1) * nx + ix] = Node([xmin + (ix - 1) * Δx, ymin + (iy - 1) * Δy]) # Boundary conditions (ix == 1) && push!(tag2nodes[1], iglob) (ix == nx) && push!(tag2nodes[2], iglob) (iy == 1) && push!(tag2nodes[3], iglob) (iy == ny) && push!(tag2nodes[4], iglob) iglob += 1 end end # Cell -> node connectivity cell2node = zeros(Int, 4 * nelts) for iy in 1:(ny - 1) for ix in 1:(nx - 1) ielt = (iy - 1) * (nx - 1) + ix cell2node[4 * ielt - 3] = (iy + 0 - 1) * nx + ix + 0 cell2node[4 * ielt - 2] = (iy + 0 - 1) * nx + ix + 1 cell2node[4 * ielt - 1] = (iy + 1 - 1) * nx + ix + 1 cell2node[4 * ielt - 0] = (iy + 1 - 1) * nx + ix + 0 end end # Cell type is constant celltypes = fill(Quad4_t(), nelts) # Number of nodes of each cell : always 4 cell2nnodes = fill(4, nelts) return Mesh( nodes, celltypes, Connectivity(cell2nnodes, cell2node); bc_names = tag2name, bc_nodes = tag2nodes, ) end # Remark : with a rectangle domain of quadratic elements, we can then apply a mapping on # this rectangle domain to obtain a curved mesh... function _rectangle_quad_mesh(nx, ny, xmin, xmax, ymin, ymax, ::Val{2}, bnd_names) # Notes # 07----08----09 # | | # | | # 04 05 06 # | | # | | # 01----02----03 # # 11----12----13----14----15 # | | | # | | | # 06 07 08 09 10 # | | | # | | | # 01----02----03----04----05 lx = xmax - xmin ly = ymax - ymin nelts = (nx - 1) * (ny - 1) nnodes = nx * ny + (nx - 1) * ny + (ny - 1) * nx + nelts Δx = lx / (nx - 1) / 2 Δy = ly / (ny - 1) / 2 # Prepare boundary nodes tag2name = Dict(tag => name for (tag, name) in enumerate(bnd_names)) tag2nodes = Dict(tag => Int[] for tag in 1:length(bnd_names)) # Nodes # we override some nodes multiple times, but it is easier this way nodes = Array{Node{2, Float64}}(undef, nnodes) iglob = 1 for iy in 1:(ny + (ny - 1)) for ix in 1:(nx + (nx - 1)) nodes[(iy - 1) * (nx + (nx - 1)) + ix] = Node([xmin + (ix - 1) * Δx, ymin + (iy - 1) * Δy]) # Boundary conditions (ix == 1) && push!(tag2nodes[1], iglob) (ix == nx + (nx - 1)) && push!(tag2nodes[2], iglob) (iy == 1) && push!(tag2nodes[3], iglob) (iy == ny + (ny - 1)) && push!(tag2nodes[4], iglob) iglob += 1 end end # Cell -> node connectivity cell2node = zeros(Int, 9 * nelts) for j in 1:(ny - 1) for i in 1:(nx - 1) ielt = (j - 1) * (nx - 1) + i ix = (i - 1) * 2 + 1 iy = (j - 1) * 2 + 1 cell2node[9 * ielt - 8] = (iy + 0 - 1) * (nx + (nx - 1)) + ix + 0 cell2node[9 * ielt - 7] = (iy + 0 - 1) * (nx + (nx - 1)) + ix + 2 cell2node[9 * ielt - 6] = (iy + 2 - 1) * (nx + (nx - 1)) + ix + 2 cell2node[9 * ielt - 5] = (iy + 2 - 1) * (nx + (nx - 1)) + ix + 0 cell2node[9 * ielt - 4] = (iy + 0 - 1) * (nx + (nx - 1)) + ix + 1 cell2node[9 * ielt - 3] = (iy + 1 - 1) * (nx + (nx - 1)) + ix + 2 cell2node[9 * ielt - 2] = (iy + 2 - 1) * (nx + (nx - 1)) + ix + 1 cell2node[9 * ielt - 1] = (iy + 1 - 1) * (nx + (nx - 1)) + ix + 0 cell2node[9 * ielt - 0] = (iy + 1 - 1) * (nx + (nx - 1)) + ix + 1 end end # Cell type is constant celltypes = fill(Quad9_t(), nelts) # Number of nodes of each cell : always 9 cell2nnodes = fill(9, nelts) return Mesh( nodes, celltypes, Connectivity(cell2nnodes, cell2node); bc_names = tag2name, bc_nodes = tag2nodes, ) end function hexa_mesh( nx, ny, nz; xmin = 0.0, xmax = 1.0, ymin = 0.0, ymax = 1.0, zmin = 0.0, zmax = 1.0, order = 1, bnd_names = ("xmin", "xmax", "ymin", "ymax", "zmin", "zmax"), ) @assert order == 1 "Not implemented for order = $order" lx = xmax - xmin ly = ymax - ymin lz = zmax - zmin nelts = (nx - 1) * (ny - 1) * (nz - 1) Δx = lx / (nx - 1) Δy = ly / (ny - 1) Δz = lz / (nz - 1) # Prepare boundary nodes tag2name = Dict(tag => name for (tag, name) in enumerate(bnd_names)) tag2nodes = Dict(tag => Int[] for tag in 1:length(bnd_names)) # Nodes iglob = 1 nodes = Array{Node{3, Float64}}(undef, nx * ny * nz) for iz in 1:nz for iy in 1:ny for ix in 1:nx nodes[(iz - 1) * nx * ny + (iy - 1) * nx + ix] = Node([xmin + (ix - 1) * Δx, ymin + (iy - 1) * Δy, zmin + (iz - 1) * Δz]) # Boundary conditions if ix == 1 push!(tag2nodes[1], iglob) elseif ix == nx push!(tag2nodes[2], iglob) elseif iy == 1 push!(tag2nodes[3], iglob) elseif iy == ny push!(tag2nodes[4], iglob) elseif iz == 1 push!(tag2nodes[5], iglob) elseif iz == ny push!(tag2nodes[6], iglob) end iglob += 1 end end end # Cell -> node connectivity cell2node = zeros(Int, 8 * nelts) for iz in 1:(nz - 1) for iy in 1:(ny - 1) for ix in 1:(nx - 1) ielt = (iz - 1) * (nx - 1) * (ny - 1) + (iy - 1) * (nx - 1) + ix cell2node[8 * ielt - 7] = (iz - 1 + 0) * nx * ny + (iy - 1 + 0) * nx + ix + 0 cell2node[8 * ielt - 6] = (iz - 1 + 0) * nx * ny + (iy - 1 + 0) * nx + ix + 1 cell2node[8 * ielt - 5] = (iz - 1 + 0) * nx * ny + (iy - 1 + 1) * nx + ix + 1 cell2node[8 * ielt - 4] = (iz - 1 + 0) * nx * ny + (iy - 1 + 1) * nx + ix + 0 cell2node[8 * ielt - 3] = (iz - 1 + 1) * nx * ny + (iy - 1 + 0) * nx + ix + 0 cell2node[8 * ielt - 2] = (iz - 1 + 1) * nx * ny + (iy - 1 + 0) * nx + ix + 1 cell2node[8 * ielt - 1] = (iz - 1 + 1) * nx * ny + (iy - 1 + 1) * nx + ix + 1 cell2node[8 * ielt - 0] = (iz - 1 + 1) * nx * ny + (iy - 1 + 1) * nx + ix + 0 end end end # Cell type is constant celltypes = fill(Hexa8_t(), nelts) # Number of nodes of each cell : always 8 cell2nnodes = fill(8, nelts) return Mesh( nodes, celltypes, Connectivity(cell2nnodes, cell2node); bc_names = tag2name, bc_nodes = tag2nodes, ) end function one_line_mesh(::Val{1}, xmin, xmax) nodes = [Node([xmin]), Node([xmax])] celltypes = [Bar2_t()] cell2node = Connectivity([2], [1, 2]) bc_names, bc_nodes = one_line_bnd() return Mesh(nodes, celltypes, cell2node; bc_names = bc_names, bc_nodes = bc_nodes) end function one_line_mesh(::Val{2}, xmin, xmax) nodes = [Node([xmin]), Node([xmax]), Node([(xmin + xmax) / 2])] celltypes = [Bar3_t()] cell2node = Connectivity([3], [1, 2, 3]) bc_names, bc_nodes = one_line_bnd() return Mesh(nodes, celltypes, cell2node; bc_names, bc_nodes) end function one_line_bnd(ileft = 1, iright = 2, names = ("xmin", "xmax")) bc_names = Dict(1 => names[1], 2 => names[2]) bc_nodes = Dict(1 => [ileft], 2 => [iright]) return bc_names, bc_nodes end function one_tri_mesh(::Val{1}, xmin, xmax, ymin, ymax) nodes = [Node([xmin, ymin]), Node([xmax, ymin]), Node([xmin, ymax])] celltypes = [Tri3_t()] cell2node = Connectivity([3], [1, 2, 3]) return Mesh(nodes, celltypes, cell2node) end function one_tri_mesh(::Val{2}, xmin, xmax, ymin, ymax) x1 = [xmin, ymin] x2 = [xmax, ymin] x3 = [xmin, ymax] nodes = [ Node(x1), Node(x2), Node(x3), Node((x1 + x2) / 2), Node((x2 + x3) / 2), Node((x3 + x1) / 2), ] celltypes = [Tri6_t()] cell2node = Connectivity([6], [1, 2, 3, 4, 5, 6]) return Mesh(nodes, celltypes, cell2node) end function one_quad_mesh(::Val{1}, xmin, xmax, ymin, ymax) nodes = [Node([xmin, ymin]), Node([xmax, ymin]), Node([xmax, ymax]), Node([xmin, ymax])] celltypes = [Quad4_t()] cell2node = Connectivity([4], [1, 2, 3, 4]) bc_names = Dict(tag => name for (tag, name) in enumerate(("xmin", "xmax", "ymin", "ymax"))) bc_nodes = Dict(1 => [1, 4], 2 => [2, 3], 3 => [1, 2], 4 => [3, 4]) return Mesh(nodes, celltypes, cell2node; bc_names, bc_nodes) end function one_quad_mesh(::Val{2}, xmin, xmax, ymin, ymax) x1 = [xmin, ymin] x2 = [xmax, ymin] x3 = [xmax, ymax] x4 = [xmin, ymax] nodes = [ Node([xmin, ymin]), Node([xmax, ymin]), Node([xmax, ymax]), Node([xmin, ymax]), Node((x1 + x2) / 2), Node((x2 + x3) / 2), Node((x3 + x4) / 2), Node((x4 + x1) / 2), Node([(xmin + xmax) / 2, (ymin + ymax) / 2]), ] celltypes = [Quad9_t()] cell2node = Connectivity([9], collect(1:9)) return Mesh(nodes, celltypes, cell2node) end function one_quad_mesh(::Val{3}, xmin, xmax, ymin, ymax) nodes = [ Node([xmin, ymin]), # 1 Node([xmax, ymin]), # 2 Node([xmax, ymax]), # 3 Node([xmin, ymax]), # 4 Node([xmin + 1 * (xmax - xmin) / 3, ymin]), # 5 Node([xmin + 2 * (xmax - xmin) / 3, ymin]), # 6 Node([xmax, ymin + 1 * (ymax - ymin) / 3]), # 7 Node([xmax, ymin + 2 * (ymax - ymin) / 3]), # 8 Node([xmin + 2 * (xmax - xmin) / 3, ymax]), # 9 Node([xmin + 1 * (xmax - xmin) / 3, ymax]), # 10 Node([xmin, ymin + 2 * (ymax - ymin) / 3]), # 11 Node([xmin, ymin + 1 * (ymax - ymin) / 3]), # 12 Node([xmin + 1 * (xmax - xmin) / 3, ymin + 1 * (ymax - ymin) / 3]), # 13 Node([xmin + 2 * (xmax - xmin) / 3, ymin + 1 * (ymax - ymin) / 3]), # 14 Node([xmin + 2 * (xmax - xmin) / 3, ymin + 2 * (ymax - ymin) / 3]), # 15 Node([xmin + 1 * (xmax - xmin) / 3, ymin + 2 * (ymax - ymin) / 3]), # 16 ] celltypes = [Quad16_t()] cell2node = Connectivity([16], collect(1:16)) return Mesh(nodes, celltypes, cell2node) end function one_tetra_mesh(::Val{1}, xmin, xmax, ymin, ymax, zmin, zmax) nodes = [ Node([xmin, ymin, zmin]), Node([xmax, ymin, zmin]), Node([xmin, ymax, zmin]), Node([xmin, ymin, zmax]), ] celltypes = [Tetra4_t()] cell2node = Connectivity([4], collect(1:4)) # Prepare boundary nodes bnd_names = ("F1", "F2", "F3", "F4") tag2name = Dict(tag => name for (tag, name) in enumerate(bnd_names)) tag2nodes = Dict(tag => [faces2nodes(Tetra4_t)[tag]...] for tag in 1:length(bnd_names)) tag2bfaces = Dict(tag => [tag] for tag in 1:length(bnd_names)) return Mesh( nodes, celltypes, cell2node; bc_names = tag2name, bc_nodes = tag2nodes, bc_faces = tag2bfaces, ) end function one_hexa_mesh(::Val{1}, xmin, xmax, ymin, ymax, zmin, zmax) nodes = [ Node([xmin, ymin, zmin]), Node([xmax, ymin, zmin]), Node([xmax, ymax, zmin]), Node([xmin, ymax, zmin]), Node([xmin, ymin, zmax]), Node([xmax, ymin, zmax]), Node([xmax, ymax, zmax]), Node([xmin, ymax, zmax]), ] celltypes = [Hexa8_t()] cell2node = Connectivity([8], collect(1:8)) return Mesh(nodes, celltypes, cell2node) end function one_hexa_mesh(::Val{2}, xmin, xmax, ymin, ymax, zmin, zmax) P1 = [xmin, ymin, zmin] P2 = [xmax, ymin, zmin] P3 = [xmax, ymax, zmin] P4 = [xmin, ymax, zmin] P5 = [xmin, ymin, zmax] P6 = [xmax, ymin, zmax] P7 = [xmax, ymax, zmax] P8 = [xmin, ymax, zmax] nodes = [ Node(P1), Node(P2), Node(P3), Node(P4), Node(P5), Node(P6), Node(P7), Node(P8), Node(0.5 .* (P1 .+ P2)), # 9 Node(0.5 .* (P2 .+ P3)), # 10 Node(0.5 .* (P3 .+ P4)), # 11 Node(0.5 .* (P4 .+ P1)), # 12 Node(0.5 .* (P1 .+ P5)), # 13 Node(0.5 .* (P2 .+ P6)), # 14 Node(0.5 .* (P3 .+ P7)), # 15 Node(0.5 .* (P4 .+ P8)), # 16 Node(0.5 .* (P5 .+ P6)), # 17 Node(0.5 .* (P6 .+ P7)), # 18 Node(0.5 .* (P7 .+ P8)), # 19 Node(0.5 .* (P8 .+ P5)), # 20 Node(0.25 .* (P1 .+ P2 .+ P3 .+ P4)), # 21 Node(0.25 .* (P1 .+ P2 .+ P6 .+ P5)), # 22 Node(0.25 .* (P2 .+ P3 .+ P7 .+ P6)), # 23 Node(0.25 .* (P3 .+ P4 .+ P8 .+ P7)), # 24 Node(0.25 .* (P4 .+ P1 .+ P5 .+ P8)), # 25 Node(0.25 .* (P5 .+ P6 .+ P7 .+ P8)), # 26 Node(0.5 .* [xmin + xmax, ymin + ymax, zmin + zmax]), # 27 ] celltypes = [Hexa27_t()] cell2node = Connectivity([27], collect(1:27)) return Mesh(nodes, celltypes, cell2node) end function one_prism_mesh(::Val{1}, xmin, xmax, ymin, ymax, zmin, zmax) nodes = [ Node([xmin, ymin, zmin]), Node([xmax, ymin, zmin]), Node([xmin, ymax, zmin]), Node([xmin, ymin, zmax]), Node([xmax, ymin, zmax]), Node([xmin, ymax, zmax]), ] celltypes = [Penta6_t()] cell2node = Connectivity([6], [1, 2, 3, 4, 5, 6]) return Mesh(nodes, celltypes, cell2node) end function one_pyra_mesh(::Val{1}, xmin, xmax, ymin, ymax, zmin, zmax) nodes = [ Node([xmin, ymin, zmin]), Node([xmax, ymin, zmin]), Node([xmax, ymax, zmin]), Node([xmin, ymax, zmin]), Node([(xmax + xmin) / 2, (ymin + ymax) / 2, zmax]), ] celltypes = [Pyra5_t()] cell2node = Connectivity([5], [1, 2, 3, 4, 5]) return Mesh(nodes, celltypes, cell2node) end """ circle_mesh(n; r = 1, order = 1) Mesh a circle (in 2D) with `n` nodes on the circumference. """ function circle_mesh(n; radius = 1.0, order = 1) if (order == 1) # Nodes nodes = [ Node(radius * [cos(θ), sin(θ)]) for θ in range(0, 2π; length = n + 1)[1:(end - 1)] ] # Cell type is constant celltypes = [Bar2_t() for ielt in 1:n] # Cell -> nodes connectivity cell2node = zeros(Int, 2 * n) for ielt in 1:(n - 1) cell2node[2 * ielt - 1] = ielt cell2node[2 * ielt] = ielt + 1 end cell2node[2 * n - 1] = n cell2node[2 * n] = 1 # Number of nodes of each cell : always 2 cell2nnodes = 2 * ones(Int, n) # Mesh return Mesh(nodes, celltypes, Connectivity(cell2nnodes, cell2node)) elseif (order == 2) # Nodes nodes = [ Node(radius * [cos(θ), sin(θ)]) for θ in range(0, 2π; length = 2 * n + 1)[1:(end - 1)] ] # Cell type is constant celltypes = [Bar3_t() for ielt in 1:n] # Cell -> nodes connectivity cell2node = zeros(Int, 3 * n) i = 1 # init counter for ielt in 1:(n - 1) cell2node[3 * ielt - 2] = i cell2node[3 * ielt - 1] = i + 2 cell2node[3 * ielt] = i + 1 i += 2 end cell2node[3 * n - 2] = i cell2node[3 * n - 1] = 1 cell2node[3 * n] = i + 1 # Number of nodes of each cell : always 2 cell2nnodes = 3 * ones(Int, n) # Mesh return Mesh(nodes, celltypes, Connectivity(cell2nnodes, cell2node)) else error("circle_mesh not implemented for order = ", order) end end """ scale(mesh, factor) Scale the input mesh nodes coordinates by a given factor and return the resulted mesh. The `factor` can be a number or a vector. Usefull for debugging. """ scale(mesh::AbstractMesh, factor) = transform(mesh, x -> factor .* x) scale!(mesh::AbstractMesh, factor) = transform!(mesh, x -> factor .* x) """ transform(mesh::AbstractMesh, fun) Transform the input mesh nodes coordinates by applying the given `fun` function and return the resulted mesh. Usefull for debugging. """ function transform(mesh::AbstractMesh, fun) new_mesh = _duplicate_mesh(mesh) transform!(new_mesh, fun) return new_mesh end function transform!(mesh::AbstractMesh, fun) new_nodes = [Node(fun(n.x)) for n in get_nodes(mesh)] #mesh.nodes .= new_nodes # bmxam : I don't understand why this is not working set_nodes(mesh, new_nodes) end """ translate(mesh::AbstractMesh, t::AbstractVector) Translate the input mesh with vector `t`. Usefull for debugging. """ translate(mesh::AbstractMesh, t::AbstractVector) = transform(mesh, x -> x + t) translate!(mesh::AbstractMesh, t::AbstractVector) = transform!(mesh, x -> x + t) """ _duplicate_mesh(mesh::AbstractMesh) Make an exact copy of the input mesh. """ function _duplicate_mesh(mesh::AbstractMesh) Mesh( get_nodes(mesh), cells(mesh), connectivities(mesh, :c2n).indices; bc_names = boundary_names(mesh), bc_nodes = boundary_nodes(mesh), bc_faces = boundary_faces(mesh), ) end """ _compute_space_dim(topodim, lx, ly, lz, tol, verbose::Bool) Deduce the number of space dimensions from the mesh boundaries : if one (or more) dimension of the bounding box is way lower than the other dimensions, the number of space dimension is decreased. Currently, having for instance (x,z) is not supported. Only (x), or (x,y), or (x,y,z). """ function _compute_space_dim(topodim, lx, ly, lz, tol, verbose::Bool) # Maximum dimension and default value for number of space dimensions lmax = maximum([lx, ly, lz]) # Now checking several case (complex `if` cascade for comprehensive warning messages) # If the topology is 3D, useless to continue, the space dim must be 3 topodim == 3 && (return 3) if topodim == 2 if (lz / lmax < tol) msg = "Warning : the mesh is flat on the z-axis. It is now considered 2D." msg *= " (use `spacedim` argument of `read_msh` if you want to keep 3D coordinates.)" msg *= " Disable this warning with `verbose = false`" verbose && println(msg) return 2 else # otherwise, it is a surface in a 3D space, we keep 3 coordinates return 3 end end if topodim == 1 if (ly / lmax < tol && lz / lmax < tol) msg = "Warning : the mesh is flat on the y and z axis. It is now considered 1D." msg *= " (use `spacedim` argument of `read_msh` if you want to keep 2D or 3D coordinates.)" msg *= " Disable this warning with `verbose = false`" verbose && println(msg) return 1 elseif (ly / lmax < tol && lz / lmax > tol) error( "You have a flat y-axis but a non flat z-axis, this is not supported. Consider rotating your mesh.", ) elseif (ly / lmax > tol && lz / lmax < tol) msg = "Warning : the mesh is flat on the z-axis. It is now considered as a 1D mesh in a 2D space." msg *= " (use `spacedim` argument of `read_msh` if you want to keep 3D coordinates.)" msg *= " Disable this warning with `verbose = false`" verbose && println(msg) return 2 else # otherwise, it is a line in a 3D space, we keep 3 coordinates return 3 end end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
9665
abstract type AbstractShape{dim} end struct Point <: AbstractShape{0} end struct Line <: AbstractShape{1} end struct Triangle <: AbstractShape{2} end struct Square <: AbstractShape{2} end struct Tetra <: AbstractShape{3} end struct Prism <: AbstractShape{3} end struct Cube <: AbstractShape{3} end struct Pyramid <: AbstractShape{3} end """ shape(::AbstractEntityType) Return the reference `Shape` corresponding to the given `AbstractEntityType`. """ function shape(s::AbstractEntityType) error("Function 'shape' not implemented for the given AbstractEntityType : ", s) end shape(::Node_t) = Point() shape(::Bar2_t) = Line() shape(::Bar3_t) = Line() shape(::Bar4_t) = Line() shape(::Tri3_t) = Triangle() shape(::Tri6_t) = Triangle() shape(::Tri9_t) = Triangle() shape(::Tri10_t) = Triangle() shape(::Quad4_t) = Square() shape(::Quad9_t) = Square() shape(::Quad16_t) = Square() shape(::Hexa8_t) = Cube() shape(::Penta6_t) = Prism() shape(::Pyra5_t) = Pyramid() shape(::Tetra4_t) = Tetra() shape(::Tetra10_t) = Tetra() """ entity(s::AbstractShape, ::Val{D}) where D Return the geometrical `Entity` corresponding to the `AbstractShape` of a given degree `D`. Remark : Returned `entity` must be consistent with the corresponding `Lagrange` function space. """ function entity(s::AbstractShape, ::Val{D}) where {D} error( "Function 'entity' is not implemented for the given AbstractShape : ", s, " with degree=", D, ) end entity(::Point, ::Val{D}) where {D} = Node_t() entity(::Line, ::Val{0}) = Bar2_t() entity(::Line, ::Val{1}) = Bar2_t() entity(::Line, ::Val{2}) = Bar3_t() entity(::Line, ::Val{3}) = Bar4_t() entity(::Triangle, ::Val{0}) = Tri3_t() entity(::Triangle, ::Val{1}) = Tri3_t() entity(::Triangle, ::Val{2}) = Tri6_t() entity(::Triangle, ::Val{3}) = Tri10_t() entity(::Square, ::Val{0}) = Quad4_t() entity(::Square, ::Val{1}) = Quad4_t() entity(::Square, ::Val{2}) = Quad9_t() entity(::Square, ::Val{3}) = Quad16_t() """ nvertices(::AbstractShape) Indicate how many vertices a shape has. """ nvertices(::AbstractShape) = error("Function 'nvertices' is not defined") """ nedges(::AbstractShape) Generic function. Indicate how many edges a shape has. """ nedges(::AbstractShape) = error("Function 'nedges' is not defined") """ nfaces(::AbstractShape) Indicate how many faces a shape has. """ nfaces(::AbstractShape) = error("Function 'nfaces' is not defined") """ get_coords(::AbstractShape) Return node coordinates of the shape in the reference space. """ get_coords(s::AbstractShape) = error("`get_coordinates` is not defined for shape $s") """ get_coords(shape::AbstractShape,i) Return the coordinates of the `i`th shape vertices. `i` can be a tuple of indices, then the multiples vertices's coordinates are returned. """ @inline get_coords(shape::AbstractShape, i) = get_coords(shape)[i] function get_coords(shape::AbstractShape, i::Tuple{T, Vararg{T}}) where {T} map(j -> get_coords(shape, j), i) end get_coords(shape::AbstractShape, i::AbstractVector) = map(j -> get_coords(shape, j), i) """ normals(::AbstractShape) Return the outward normals of all the faces of the shape. """ normals(::AbstractShape) = error("Function 'normals' is not defined") """ normal(shape::AbstractShape, i) Return the outward normal of the `i`th face of the shape. """ normal(shape::AbstractShape, i) = normals(shape)[i] """ face_area(::AbstractShape) Return the length/area of the faces of a shape. """ function face_area(::AbstractShape) error("Function 'face_area' not implemented for the given Shape.") end """ faces2nodes(::AbstractShape) Return the index of the vertices on the faces of a shape. """ function faces2nodes(::AbstractShape) error("Function 'faces2nodes' not implemented for the given Shape.") end """ faces2nodes(shape::AbstractShape, side) Return the index of the vertices on the `iside`-th face of a shape. If `side` is positive, the face is oriented preserving the cell normal. If `side` is negative, the face is returned with the opposite direction (i.e reverse node order). """ function faces2nodes(shape::AbstractShape, side) side > 0 ? faces2nodes(shape)[side] : reverse(faces2nodes(shape)[-side]) end """ face_shapes(::AbstractShape) Return a tuple of the Shape of each face of the given (cell) Shape. For instance, a `Triangle` has three faces, all of them are `Line`. """ function face_shapes(::AbstractShape) error("Function 'face_shapes' not implemented for the given Shape.") end """ face_shapes(shape::AbstractShape, i) Shape of `i`-th shape of the input shape. """ face_shapes(shape::AbstractShape, i) = face_shapes(shape)[i] """ center(::AbstractShape) Center of the `AbstractShape`. # Implementation Specialize for better performances """ function center(s::AbstractShape) return sum(get_coords(s)) / nvertices(s) end nvertices(::Point) = 1 nvertices(::Line) = nnodes(Bar2_t()) nvertices(::Triangle) = nnodes(Tri3_t()) nvertices(::Square) = nnodes(Quad4_t()) nvertices(::Tetra) = nnodes(Tetra4_t()) nvertices(::Cube) = nnodes(Hexa8_t()) nvertices(::Prism) = nnodes(Penta6_t()) nvertices(::Pyramid) = nnodes(Pyra5_t()) nedges(::Line) = nedges(Bar2_t()) nedges(::Triangle) = nedges(Tri3_t()) nedges(::Square) = nedges(Quad4_t()) nedges(::Tetra) = nedges(Tetra4_t()) nedges(::Cube) = nedges(Hexa8_t()) nedges(::Prism) = nedges(Penta6_t()) nedges(::Pyramid) = nedges(Pyra5_t()) nfaces(::Line) = nfaces(Bar2_t()) nfaces(::Triangle) = nfaces(Tri3_t()) nfaces(::Square) = nfaces(Quad4_t()) nfaces(::Tetra) = nfaces(Tetra4_t()) nfaces(::Cube) = nfaces(Hexa8_t()) nfaces(::Prism) = nfaces(Penta6_t()) nfaces(::Pyramid) = nfaces(Pyra5_t()) get_coords(::Point) = (SA[0.0],) get_coords(::Line) = (SA[-1.0], SA[1.0]) get_coords(::Triangle) = (SA[0.0, 0.0], SA[1.0, 0.0], SA[0.0, 1.0]) get_coords(::Square) = (SA[-1.0, -1.0], SA[1.0, -1.0], SA[1.0, 1.0], SA[-1.0, 1.0]) function get_coords(::Tetra) (SA[0.0, 0.0, 0.0], SA[1.0, 0.0, 0.0], SA[0.0, 1.0, 0.0], SA[0.0, 0.0, 1.0]) end function get_coords(::Cube) ( SA[-1.0, -1.0, -1.0], SA[1.0, -1.0, -1.0], SA[1.0, 1.0, -1.0], SA[-1.0, 1.0, -1.0], SA[-1.0, -1.0, 1.0], SA[1.0, -1.0, 1.0], SA[1.0, 1.0, 1.0], SA[-1.0, 1.0, 1.0], ) end function get_coords(::Prism) ( SA[0.0, 0.0, -1.0], SA[1.0, 0.0, -1.0], SA[0.0, 1.0, -1.0], SA[0.0, 0.0, 1.0], SA[1.0, 0.0, 1.0], SA[0.0, 1.0, 1.0], ) end function get_coords(::Pyramid) ( SA[-1.0, -1.0, 0.0], SA[1.0, -1.0, 0.0], SA[1.0, 1.0, 0.0], SA[-1.0, 1.0, 0.0], SA[0.0, 0.0, 1.0], ) end face_area(::Line) = SA[1.0, 1.0] face_area(::Triangle) = SA[1.0, √(2.0), 1.0] face_area(::Square) = SA[2.0, 2.0, 2.0, 2.0] face_area(::Cube) = SA[4.0, 4.0, 4.0, 4.0, 4.0, 4.0] face_area(::Tetra) = SA[0.5, 0.5, 0.5 * √(3.0), 0.5] face_area(::Prism) = SA[2.0, 2 * √(2.0), 2.0, 0.5, 0.5] face_area(::Pyramid) = SA[4.0, √(2.0), √(2.0), √(2.0), √(2.0)] faces2nodes(::Line) = (SA[1], SA[2]) faces2nodes(::Triangle) = (SA[1, 2], SA[2, 3], SA[3, 1]) faces2nodes(::Square) = (SA[1, 2], SA[2, 3], SA[3, 4], SA[4, 1]) function faces2nodes(::Cube) ( SA[1, 4, 3, 2], SA[1, 2, 6, 5], SA[2, 3, 7, 6], SA[3, 4, 8, 7], SA[1, 5, 8, 4], SA[5, 6, 7, 8], ) end function faces2nodes(::Tetra) (SA[1, 3, 2], SA[1, 2, 4], SA[2, 3, 4], SA[3, 1, 4]) end function faces2nodes(::Prism) (SA[1, 2, 5, 4], SA[2, 3, 6, 5], SA[3, 1, 4, 6], SA[1, 3, 2], SA[4, 5, 6]) end function faces2nodes(::Pyramid) (SA[1, 4, 3, 2], SA[1, 2, 5], SA[2, 3, 5], SA[3, 4, 5], SA[4, 1, 5]) end # Normals normals(::Line) = (SA[-1.0], SA[1.0]) normals(::Triangle) = (SA[0.0, -1.0], SA[1.0, 1.0] ./ √(2), SA[-1.0, 0.0]) normals(::Square) = (SA[0.0, -1.0], SA[1.0, 0.0], SA[0.0, 1.0], SA[-1.0, 0.0]) function normals(::Cube) ( SA[0.0, 0.0, -1.0], SA[0.0, -1.0, 0.0], SA[1.0, 0.0, 0.0], SA[0.0, 1.0, 0.0], SA[-1.0, 0.0, 0.0], SA[0.0, 0.0, 1.0], ) end function normals(::Tetra) (SA[0.0, 0.0, -1.0], SA[0.0, -1.0, 0.0], SA[1.0, 1.0, 1.0] / √3, SA[-1.0, 0.0, 0.0]) end function normals(::Prism) ( SA[0.0, -1.0, 0.0], SA[√(2.0) / 2.0, √(2.0) / 2.0, 0.0], SA[-1.0, 0.0, 0.0], SA[0.0, 0.0, -1.0], SA[0.0, 0.0, 1.0], ) end function normals(::Pyramid) ( SA[0.0, 0.0, -1.0], SA[0.0, -√(2.0) / 2.0, √(2.0) / 2.0], SA[√(2.0) / 2.0, 0.0, √(2.0) / 2.0], SA[0.0, √(2.0) / 2.0, √(2.0) / 2.0], SA[-√(2.0) / 2.0, 0.0, √(2.0) / 2.0], ) end # Centers center(::Line) = SA[0.0] center(::Triangle) = SA[1.0 / 3.0, 1.0 / 3.0] center(::Square) = SA[0.0, 0.0] center(::Cube) = SA[0.0, 0.0, 0.0] center(::Tetra) = SA[0.25, 0.25, 0.25] center(::Prism) = SA[1.0 / 3.0, 1.0 / 3.0, 0.0] center(::Pyramid) = SA[0.0, 0.0, 1.0 / 5.0] # Face shapes : see notes in generic function documentation face_shapes(::Line) = (Point(), Point()) face_shapes(shape::Union{Triangle, Square}) = ntuple(i -> Line(), nfaces(shape)) face_shapes(shape::Cube) = ntuple(i -> Square(), nfaces(shape)) face_shapes(shape::Tetra) = ntuple(i -> Triangle(), nfaces(shape)) face_shapes(::Prism) = (Square(), Square(), Square(), Triangle(), Triangle()) face_shapes(::Pyramid) = (Square(), Triangle(), Triangle(), Triangle(), Triangle()) # Measure measure(::Line) = 2.0 measure(::Triangle) = 0.5 measure(::Square) = 4.0 measure(::Cube) = 8.0 measure(::Tetra) = 1.0 / 6 measure(::Prism) = 1.0 measure(::Pyramid) = 4.0 / 3.0
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
948
abstract type AbstractAffineTransformation end (::AbstractAffineTransformation)(x) = error("not implemented") Base.inv(::AbstractAffineTransformation) = error("not implemented") struct Translation{T} <: AbstractAffineTransformation vec::T end (t::Translation)(x) = x .+ t.vec Base.inv(t::Translation) = Translation(-t.vec) struct Rotation{T} <: AbstractAffineTransformation A::T end """ Rotation(u::AbstractVector, θ::Number) Return a `Rotation` operator build from a given rotation axis `u` and an angle of rotation `θ`. # Example : ```julia julia> rot = Rotation([0,0,1], π/4); julia> x = [3.0,0,0]; julia> x_rot_ref = 3√(2)/2 .*[1,1,0] # expected result julia> all(rot(x) .≈ x_rot_ref) true ``` """ function Rotation(u::AbstractVector, θ::Number) Rotation((normalize(u), sincos(θ))) end function (r::Rotation)(x) u, (sinθ, cosθ) = r.A rx = cosθ * x + (1 - cosθ) * (u ⋅ x) * u + sinθ * cross(u, x) return rx end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
32401
abstract type AbstractQuadratureType end struct QuadratureLegendre <: AbstractQuadratureType end struct QuadratureLobatto <: AbstractQuadratureType end struct QuadratureUniform <: AbstractQuadratureType end """ AbstractQuadrature{T,D} Abstract type representing quadrature of type `T` and degree `D` """ abstract type AbstractQuadrature{T, D} end get_quadtype(::AbstractQuadrature{T}) where {T} = T() get_degree(::AbstractQuadrature{T, D}) where {T, D} = D """ Quadrature{T,D} Quadrature of type `T` and degree `D` """ struct Quadrature{T, D} <: AbstractQuadrature{T, D} end function Quadrature(qt::AbstractQuadratureType, ::Val{D}) where {D} @assert D isa Integer && D ≥ 0 "'D' must be a positive Integer" Quadrature{typeof(qt), D}() end Quadrature(d::Val{D}) where {D} = Quadrature(QuadratureLegendre(), d) Quadrature(qt::AbstractQuadratureType, d::Integer) = Quadrature(qt, Val(d)) Quadrature(d::Integer) = Quadrature(Val(d)) """ AbstractQuadratureRule{S,Q} Abstract type representing a quadrature rule for a shape `S` and quadrature `Q`. Derived types must implement the following method: - [`get_weights(qr::AbstractQuadratureRule)`] - [`get_nodes(qr::AbstractQuadratureRule)`] - [`Base.length(qr::AbstractQuadratureRule)`] """ abstract type AbstractQuadratureRule{S, Q} end get_shape(::AbstractQuadratureRule{S, Q}) where {S, Q} = S get_quadrature(::AbstractQuadratureRule{S, Q}) where {S, Q} = Q """ get_weights(qr::AbstractQuadratureRule) Returns an array containing the weights of all quadrature nodes of `qr`. """ function get_weights(qr::AbstractQuadratureRule) error("`get_weights` is not implemented for $(typeof(qr))") end """ get_nodes(qr::AbstractQuadratureRule) Returns an array containing the coordinates of all quadrature nodes of `qr`. """ function get_nodes(qr::AbstractQuadratureRule) error("`get_nodes` is not implemented for $(typeof(qr))") end """ length(qr::AbstractQuadratureRule) Returns the number of quadrature nodes of `qr`. """ function Base.length(qr::AbstractQuadratureRule) error("`length` is not implemented for $(typeof(qr))") end """ QuadratureRule{S,Q} Abstract type representing a quadrature rule for a shape `S` and quadrature `Q` """ struct QuadratureRule{S, Q, N, W <: AbstractArray, X <: AbstractArray} <: AbstractQuadratureRule{S, Q} weights::W nodes::X end get_weights(qr::QuadratureRule) = qr.weights get_nodes(qr::QuadratureRule) = qr.nodes Base.length(::QuadratureRule{S, Q, N}) where {S, Q, N} = N """ QuadratureRule(shape::AbstractShape, q::AbstractQuadrature) Return the quadrature rule corresponding to the given `Shape` according to the selected quadrature 'q'. """ function QuadratureRule(shape::AbstractShape, q::AbstractQuadrature) w, x = quadrature_rule(shape, Val(get_degree(q)), get_quadtype(q)) QuadratureRule(shape, q, w, x) end function QuadratureRule(shape::AbstractShape, degree::Val{D}) where {D} QuadratureRule(shape, Quadrature(degree)) end function QuadratureRule( shape::AbstractShape, q::AbstractQuadrature, w::AbstractVector, x::AbstractVector, ) @assert length(w) == length(x) "Dimension mismatch for 'w' and 'x'" QuadratureRule{typeof(shape), typeof(q), length(x), typeof(w), typeof(x)}(w, x) end function QuadratureRule( shape::AbstractShape, q::AbstractQuadrature, w::NTuple{N, T1}, x::NTuple{N, T2}, ) where {N, T1, T2} _w = SVector{N, T1}(w) _x = SVector{N, T2}(x) QuadratureRule(shape, q, _w, _x) end function QuadratureRule(shape::AbstractShape, degree::Integer) QuadratureRule(shape, Quadrature(degree)) end # To integrate a constant, we use the first order quadrature function QuadratureRule( shape::AbstractShape, ::Q, ) where {Q <: AbstractQuadrature{T, 0}} where {T} QuadratureRule(shape, Q(T, 1)) end """ quadrature_rule_bary(::Int, ::AbstractShape, degree::Val{N}) where N Return the quadrature rule, computed with barycentric coefficients, corresponding to the given boundary of a shape and the given degree. This function returns the quadrature weights and the barycentric weights to apply to each vertex of the reference shape. Hence, to apply the quadrature using this function, one needs to do : ` for (weight, l) in quadrature_rule_bary(iside, shape(etype), degree) xp = zeros(SVector{td}) for i=1:nvertices xp += l[i]*vertices[i] end # weight, xp is the quadrature couple (weight, node) end ` """ function quadrature_rule_bary(::Int, shape::AbstractShape, degree::Val{N}) where {N} error( "Function 'quadrature_rule_bary' is not implemented for shape $shape and degree $N", ) end """ quadrature_rule(iside::Int, shape::AbstractShape, degree::Val{N}) where N Return the quadrature rule, computed with barycentric coefficients, corresponding to the given boundary of a shape and the given `degree`. """ function quadrature_rule(iside::Int, shape::AbstractShape, degree::Val{N}) where {N} # Get coordinates of the face's nodes of the shape fvertices = get_coords(shape, faces2nodes(shape)[iside]) # Get barycentric quadrature quadBary = quadrature_rule_bary(iside, shape, degree) nq = length(quadBary) weights = SVector{nq, eltype(first(quadBary)[1])}(w for (w, l) in quadBary) xq = SVector{nq, eltype(fvertices)}(sum(l .* fvertices) for (w, l) in quadBary) return weights, xq end """ quadrature_rule(::AbstractShape, ::Val{D}, ::AbstractQuadratureType) where {D} Return the weights and points associated to the quadrature rule of degree `D` for the desired shape and quadrature type. """ quadrature_rule(::AbstractShape, ::Val{D}, ::AbstractQuadratureType) where {D} # Point quadratures function quadrature_rule(::Point, ::Val{D}, ::AbstractQuadratureType) where {D} return SA[1.0], SA[0.0] end # Line quadratures """ _gausslegendre1D(::Val{N}) where N _gausslobatto1D(::Val{N}) where N Return `N`-point Gauss quadrature weights and nodes on the domain [-1:1]. """ @generated function _gausslegendre1D(::Val{N}) where {N} x, w = FastGaussQuadrature.gausslegendre(N) w0 = SVector{length(w), eltype(w)}(w) x0 = SVector{length(x), eltype(x)}(x) return :($w0, $x0) end @generated function _gausslobatto1D(::Val{N}) where {N} x, w = FastGaussQuadrature.gausslobatto(N) w0 = SVector{length(w), eltype(w)}(w) x0 = SVector{length(x), eltype(x)}(x) return :($w0, $x0) end @generated function _uniformpoints(::Val{N}) where {N} xmin = -1.0 xmax = 1.0 if N == 1 x0 = SA[(xmin + xmax) / 2] else x0 = SVector{N}(collect(LinRange(xmin, xmax, N))) end w0 = @. one(x0) / N return :($w0, $x0) end _quadrature_rule(n::Val{N}, ::QuadratureLegendre) where {N} = _gausslegendre1D(n) _quadrature_rule(n::Val{N}, ::QuadratureLobatto) where {N} = _gausslobatto1D(n) _quadrature_rule(n::Val{N}, ::QuadratureUniform) where {N} = _uniformpoints(n) """ Gauss-Legendre formula with ``n`` nodes has degree of exactness ``2n-1``. Then, to obtain a given degree ``D``, the number of nodes must satisfy: `` 2n-1 ≥ D`` or equivalently ``n ≥ (D+1)/2`` """ function _get_num_nodes(::Line, ::Val{degree}, ::QuadratureLegendre) where {degree} ceil(Int, (degree + 1) / 2) end """ Gauss-Lobatto formula with ``n+1`` nodes has degree of exactness ``2n-1``, which equivalent to a degree of ``2n-3`` with ``n`` nodes. Then, to obtain a given degree ``D``, the number of nodes must satisfy: `` 2n-3 ≥ D`` or equivalently ``n ≥ (D+3)/2`` """ function _get_num_nodes(::Line, ::Val{degree}, ::QuadratureLobatto) where {degree} ceil(Int, (degree + 3) / 2) end _get_num_nodes(::Line, ::Val{degree}, ::QuadratureUniform) where {degree} = degree + 1 """ get_num_nodes_per_dim(quadrule::AbstractQuadratureRule{S}) where S<:Shape Returns the number of nodes per dimension. This function is defined for shapes for which quadratures are based on a cartesian product : `Line`, `Square`, `Cube` Remark : Here we assume that the same `degree` is used along each dimension (no anisotropy for now!) """ function _get_num_nodes_per_dim(::AbstractQuadratureRule{<:S}) where {S} error("Not implemented for shape $S") end _get_num_nodes_per_dim(quadrule::AbstractQuadratureRule{<:Line}) = length(quadrule) function _get_num_nodes_per_dim(::AbstractQuadratureRule{<:Square, Q}) where {Q} ntuple(i -> _get_num_nodes_per_dim(QuadratureRule(Line(), Q())), Val(2)) end function _get_num_nodes_per_dim(::AbstractQuadratureRule{<:Cube, Q}) where {Q} ntuple(i -> _get_num_nodes_per_dim(QuadratureRule(Line(), Q())), Val(3)) end function quadrature_rule(line::Line, degree::Val{D}, quad::AbstractQuadratureType) where {D} @assert D isa Integer && D ≥ 0 "'D' must be a positive Integer" n = _get_num_nodes(line, degree, quad) return _quadrature_rule(Val(n), quad) end # Triangle quadratures function quadrature_rule(::Triangle, ::Val{1}, ::QuadratureLegendre) raw_unzip(get_quadrature_points(Val{:GLTRI1})) end function quadrature_rule(::Triangle, ::Val{2}, ::QuadratureLegendre) raw_unzip(get_quadrature_points(Val{:GLTRI3})) end function quadrature_rule(::Triangle, ::Val{3}, ::QuadratureLegendre) raw_unzip(get_quadrature_points(Val{:GLTRI4})) end function quadrature_rule(::Triangle, ::Val{4}, ::QuadratureLegendre) get_quadrature_points_gausslegendre(Val{:GLTRI6}) end #quadrature_points(Triangle(), Val(4), Val(:Lobatto)) function quadrature_rule(::Triangle, ::Val{5}, ::QuadratureLegendre) get_quadrature_points_gausslegendre(Val{:GLTRI7}) end function quadrature_rule(::Triangle, ::Val{6}, ::QuadratureLegendre) get_quadrature_points_gausslegendre(Val{:GLTRI12}) end function quadrature_rule(::Triangle, ::Val{7}, ::QuadratureLegendre) get_quadrature_points_gausslegendre(Val{:GLTRI16}) end function quadrature_rule(::Triangle, ::Val{8}, ::QuadratureLegendre) get_quadrature_points_gausslegendre(Val{:GLTRI16}) end function get_quadrature_points_gausslegendre(::Type{Val{:GLTRI6}}) P1 = 0.22338158967801146569500700843312 / 2 P2 = 0.10995174365532186763832632490021 / 2 A = 0.44594849091596488631832925388305 B = 0.09157621350977074345957146340220 weights = SA[P2, P2, P2, P1, P1, P1] points = SA[(B, B), (1.0 - 2.0 * B, B), (B, 1.0 - 2.0 * B), (A, 1.0 - 2 * A), (A, A), (1.0 - 2.0 * A, A)] return weights, points end """ Gauss-Legendre quadrature, 7 point rule on triangle. """ function get_quadrature_points_gausslegendre(::Type{Val{:GLTRI7}}) A = 0.47014206410511508977044120951345 B = 0.10128650732345633880098736191512 P1 = 0.13239415278850618073764938783315 / 2 P2 = 0.12593918054482715259568394550018 / 2 weights = SA[9 / 80, P1, P1, P1, P2, P2, P2] points = SA[(1 / 3, 1 / 3), (A, A), (1.0 - 2.0 * A, A), (A, 1.0 - 2.0 * A), (B, B), (1.0 - 2.0 * B, B), (B, 1.0 - 2.0 * B)] return weights, points end """ Gauss-Legendre quadrature, 12 point rule on triangle. Ref: Witherden, F. D.; Vincent, P. E. On the identification of symmetric quadrature rules for finite element methods. Comput. Math. Appl. 69 (2015), no. 10, 1232–1241 """ function get_quadrature_points_gausslegendre(::Type{Val{:GLTRI12}}) A = (-0.87382197101699554331933679425836168532 + 1) / 2 B = (-0.50142650965817915741672289378596184782 + 1) / 2 C = (-0.37929509793243118916678453208689569359 + 1) / 2 D = (-0.89370990031036610529350065673720370601 + 1) / 2 P1 = 0.10168981274041363384187361821373796809 / 4 P2 = 0.23357255145275873205057922277115888265 / 4 P3 = 0.16570215123674715038710691284088490796 / 4 weights = SA[P1, P1, P1, P2, P2, P2, P3, P3, P3, P3, P3, P3] points = SA[(A, A), (1.0 - 2.0 * A, A), (A, 1.0 - 2.0 * A), (B, B), (1.0 - 2.0 * B, B), (B, 1.0 - 2.0 * B), (C, D), (D, C), (1.0 - C - D, C), (1.0 - C - D, D), (C, 1.0 - C - D), (D, 1.0 - C - D)] return weights, points end """ Gauss-Legendre quadrature, 16 point rule on triangle, degree 8. Ref: Witherden, F. D.; Vincent, P. E. On the identification of symmetric quadrature rules for finite element methods. Comput. Math. Appl. 69 (2015), no. 10, 1232–1241 Note : quadrature is rescale to match our reference triangular shape which is defined in [0:1]² instead of [-1:1]² """ function get_quadrature_points_gausslegendre(::Type{Val{:GLTRI16}}) x = SA[ -0.33333333333333333333333333333333333333 -0.33333333333333333333333333333333333333 0.2886312153555743365021822209781292496 -0.081414823414553687942368971011661355879 -0.83717035317089262411526205797667728824 0.1901832685345692495877922087771686332 -0.83717035317089262411526205797667728824 -0.081414823414553687942368971011661355879 0.1901832685345692495877922087771686332 -0.081414823414553687942368971011661355879 -0.081414823414553687942368971011661355879 0.1901832685345692495877922087771686332 -0.65886138449647958675541299701707099796 0.31772276899295917351082599403414199593 0.20643474106943650056358310058425806003 0.31772276899295917351082599403414199593 -0.65886138449647958675541299701707099796 0.20643474106943650056358310058425806003 -0.65886138449647958675541299701707099796 -0.65886138449647958675541299701707099796 0.20643474106943650056358310058425806003 -0.89890554336593804908315289880680210631 0.79781108673187609816630579761360421262 0.064916995246396160621851856683561193593 0.79781108673187609816630579761360421262 -0.89890554336593804908315289880680210631 0.064916995246396160621851856683561193593 -0.89890554336593804908315289880680210631 -0.89890554336593804908315289880680210631 0.064916995246396160621851856683561193593 -0.98321044518008478932557233092141110162 0.45698478591080856248200075835212392604 0.05446062834886998852968938014781784832 0.45698478591080856248200075835212392604 -0.98321044518008478932557233092141110162 0.05446062834886998852968938014781784832 -0.47377434073072377315642842743071282442 0.45698478591080856248200075835212392604 0.05446062834886998852968938014781784832 0.45698478591080856248200075835212392604 -0.47377434073072377315642842743071282442 0.05446062834886998852968938014781784832 -0.47377434073072377315642842743071282442 -0.98321044518008478932557233092141110162 0.05446062834886998852968938014781784832 -0.98321044518008478932557233092141110162 -0.47377434073072377315642842743071282442 0.05446062834886998852968938014781784832 ] points = _rescale_tri.(x[:, 1], x[:, 2]) weights = x[:, 3] ./ 4 return weights, points end _rescale_tri(x, y) = (0.5 * (x + 1), 0.5 * (y + 1)) """ ref : https://www.math.umd.edu/~tadmor/references/files/Chen%20&%20Shu%20entropy%20stable%20DG%20JCP2017.pdf """ function quadrature_points(tri::Triangle, ::Val{4}, ::QuadratureLobatto) p1, p2, p3 = get_coords(tri) s12_1 = 1.0 / 2 s12_2 = 0.4384239524408185 s12_3 = 0.1394337314154536 s111_1 = (0.0, 0.230765344947159) s111_2 = (0.0, 0.046910077030668) points = SA[ _triangle_orbit_3(p1, p2, p3), _triangle_orbit_12(p1, p2, p3, s12_1), _triangle_orbit_12(p2, p3, p1, s12_1), _triangle_orbit_12(p3, p1, p2, s12_1), _triangle_orbit_12(p1, p2, p3, s12_2), _triangle_orbit_12(p2, p3, p1, s12_2), _triangle_orbit_12(p3, p1, p2, s12_2), _triangle_orbit_12(p1, p2, p3, s12_3), _triangle_orbit_12(p2, p3, p1, s12_3), _triangle_orbit_12(p3, p1, p2, s12_3), _triangle_orbit_111(p1, p2, p3, s111_1...), _triangle_orbit_111(p2, p3, p1, s111_1...), _triangle_orbit_111(p3, p1, p2, s111_1...), _triangle_orbit_111(p1, p3, p2, s111_1...), _triangle_orbit_111(p2, p1, p3, s111_1...), _triangle_orbit_111(p3, p2, p1, s111_1...), _triangle_orbit_111(p1, p2, p3, s111_2...), _triangle_orbit_111(p2, p3, p1, s111_2...), _triangle_orbit_111(p3, p1, p2, s111_2...), _triangle_orbit_111(p1, p3, p2, s111_2...), _triangle_orbit_111(p2, p1, p3, s111_2...), _triangle_orbit_111(p3, p2, p1, s111_2...), ] w3, w12_1, w12_2, w12_3, w111_1, w111_2 = ( 0.0455499555988567, 0.00926854241697489, 0.0623683661448868, 0.0527146648104222, 0.0102652298402145, 0.00330065754050081, ) weights = SA[ w3, w12_1, w12_1, w12_1, w12_2, w12_2, w12_2, w12_3, w12_3, w12_3, w111_1, w111_1, w111_1, w111_1, w111_1, w111_1, w111_2, w111_2, w111_2, w111_2, w111_2, w111_2, ] return weights, points end _triangle_orbit_3(p1, p2, p3) = 1.0 / 3 * (p1 + p2 + p3) _triangle_orbit_12(p1, p2, p3, α) = α * p1 + α * p2 + (1.0 - 2 * α) * p3 _triangle_orbit_111(p1, p2, p3, α, β) = α * p1 + β * p2 + (1.0 - α - β) * p3 # Square quadratures : generete quadrature rules for square # from the cartesian product of line quadratures (i.e. Q-element) function quadrature_rule(::Square, deg::Val{D}, quadtype::AbstractQuadratureType) where {D} quadline = QuadratureRule(Line(), Quadrature(quadtype, deg)) N = length(quadline) w1 = get_weights(quadline) x1 = get_nodes(quadline) NQ = N^2 if NQ < MAX_LENGTH_STATICARRAY w = SVector{NQ}(w1[i] * w1[j] for i in 1:N, j in 1:N) x = SVector{NQ}(SA[x1[i], x1[j]] for i in 1:N, j in 1:N) else w = vec([w1[i] * w1[j] for i in 1:N, j in 1:N]) x = vec([SA[x1[i], x1[j]] for i in 1:N, j in 1:N]) end return w, x end # Cube quadratures : generete quadrature rules for cube # from the cartesian product of line quadratures (i.e. Q-element) function quadrature_rule(::Cube, deg::Val{D}, quadtype::AbstractQuadratureType) where {D} quadline = QuadratureRule(Line(), Quadrature(quadtype, deg)) N = length(quadline) w1 = get_weights(quadline) x1 = get_nodes(quadline) NQ = N^3 if NQ < MAX_LENGTH_STATICARRAY w = SVector{NQ}(w1[i] * w1[j] * w1[k] for i in 1:N, j in 1:N, k in 1:N) x = SVector{NQ}(SA[x1[i], x1[j], x1[k]] for i in 1:N, j in 1:N, k in 1:N) else w = vec([w1[i] * w1[j] * w1[k] for i in 1:N, j in 1:N, k in 1:N]) x = vec([SA[x1[i], x1[j], x1[k]] for i in 1:N, j in 1:N, k in 1:N]) end return w, x end # Prism quadratures function quadrature_rule(::Prism, ::Val{1}, ::QuadratureLegendre) w, x = raw_unzip(get_quadrature_points(Val{:GLWED6})) _w = SVector{length(w), eltype(w)}(w) _x = SVector{length(x), eltype(x)}(x) return _w, _x end function quadrature_rule(::Prism, ::Val{2}, ::QuadratureLegendre) w, x = raw_unzip(get_quadrature_points(Val{:GLWED21})) _w = SVector{length(w), eltype(w)}(w) _x = SVector{length(x), eltype(x)}(x) return _w, _x end # Pyramid quadratures # Obtained from Ref: # Witherden, F. D.; Vincent, P. E. # On the identification of symmetric quadrature rules for finite element methods. # Comput. Math. Appl. 69 (2015), no. 10, 1232–1241 # # Note that in Witherden, the reference pyramid is between z=-1 and z=1 whereas # in Bcube the ref pyramid is between z=0 and z=1. So we shift the quadrature nodes # and fix the volume (the weigths) # # bmxam note 1 : I don't think these are strictly "QuadratureLegendre", but it is # easier for dispatch for now # function quadrature_rule(::Pyramid, ::Val{1}, ::QuadratureLegendre) points = SA[(0.0, 0.0, (-0.5 + 1) / 2)] weights = SA[2.6666666666666666666666666666666666667 / 2] return weights, points end function quadrature_rule(::Pyramid, ::Val{2}, ::QuadratureLegendre) a = 0.71892105581179616210276971993495767914 b = 0.70932703285428855378369530000365161136 points = SA[ (0.0, 0.0, (0.21658207711955775339238838942231815011 + 1) / 2), (a, 0.0, (-b + 1) / 2), (0.0, a, (-b + 1) / 2), (-a, 0.0, (-b + 1) / 2), (0.0, -a, (-b + 1) / 2), ] weights = SA[ 0.60287280353093925911579186632475611728 / 2, 0.51594846578393185188771870008547763735 / 2, 0.51594846578393185188771870008547763735 / 2, 0.51594846578393185188771870008547763735 / 2, 0.51594846578393185188771870008547763735 / 2, ] return weights, points end function quadrature_rule(::Pyramid, ::Val{3}, ::QuadratureLegendre) a = 0.56108361105873963414196154191891982155 b = 2.0 / 3.0 points = SA[ (0.0, 0.0, (0.14285714077213670617734974746312582074 + 1) / 2), (0.0, 0.0, (-0.99999998864829993678698817507850804299 + 1) / 2), (a, a, (-b + 1) / 2), (a, -a, (-b + 1) / 2), (-a, a, (-b + 1) / 2), (-a, -a, (-b + 1) / 2), ] weights = SA[ 0.67254902379402809443607078852738472107 / 2.0, 0.30000001617617323518941867705084375434 / 2.0, 0.42352940667411633426029430027210954782 / 2.0, 0.42352940667411633426029430027210954782 / 2.0, 0.42352940667411633426029430027210954782 / 2.0, 0.42352940667411633426029430027210954782 / 2.0, ] return weights, points end function quadrature_rule(::Pyramid, ::Val{4}, ::QuadratureLegendre) a = 0.6505815563982325146829577797417295398 b = 0.65796699712169008954533549931479427127 c = 0.35523170084357268589593075201816127231 d = 0.92150343220236930457646242598412224897 points = SA[ (0.0, 0.0, (0.35446557777227471722730849524904581806 + 1) / 2), (0.0, 0.0, (-0.74972609378250711033655604388057044149 + 1) / 2), (a, 0.0, (-c + 1) / 2), (0.0, a, (-c + 1) / 2), (-a, 0.0, (-c + 1) / 2), (0.0, -a, (-c + 1) / 2), (b, b, (-d + 1) / 2), (b, -b, (-d + 1) / 2), (-b, b, (-d + 1) / 2), (-b, -b, (-d + 1) / 2), ] weights = SA[ 0.30331168845504517111391728481208001144 / 2.0, 0.55168907357213937275730716433358729608 / 2.0, 0.28353223437153468006819777082540613962 / 2.0, 0.28353223437153468006819777082540613962 / 2.0, 0.28353223437153468006819777082540613962 / 2.0, 0.28353223437153468006819777082540613962 / 2.0, 0.16938424178833585063066278355484370017 / 2.0, 0.16938424178833585063066278355484370017 / 2.0, 0.16938424178833585063066278355484370017 / 2.0, 0.16938424178833585063066278355484370017 / 2.0, ] return weights, points end function quadrature_rule(::Pyramid, ::Val{5}, ::QuadratureLegendre) a = 0.70511712277882760181079385797948261057 b = 0.87777618587595407108464357252416911085 c = 0.43288286410354097685000790909815143591 d = 0.15279732576055038842025517341026975071 e = 0.70652603154632457420722562974792066862 points = SA[ (0.0, 0.0, (0.45971576156501338586164265377920811314 + 1) / 2), (0.0, 0.0, (-0.39919795837246198593385139590712322914 + 1) / 2), (0.0, 0.0, (-0.99999998701645569241460017355590234925 + 1) / 2), (e, 0.0, (-0.75 + 1) / 2), (0.0, e, (-0.75 + 1) / 2), (-e, 0.0, (-0.75 + 1) / 2), (0.0, -e, (-0.75 + 1) / 2), (a, a, (-b + 1) / 2), (a, -a, (-b + 1) / 2), (-a, a, (-b + 1) / 2), (-a, -a, (-b + 1) / 2), (c, c, (-d + 1) / 2), (c, -c, (-d + 1) / 2), (-c, c, (-d + 1) / 2), (-c, -c, (-d + 1) / 2), ] weights = SA[ 0.18249431975770692138374895897213800931 / 2.0, 0.45172563864726406056400285032640105704 / 2.0, 0.15654542887619877154120304977336547704 / 2.0, 0.20384344839498724639142514342645843799 / 2.0, 0.20384344839498724639142514342645843799 / 2.0, 0.20384344839498724639142514342645843799 / 2.0, 0.20384344839498724639142514342645843799 / 2.0, 0.10578907087905457654220386143818487109 / 2.0, 0.10578907087905457654220386143818487109 / 2.0, 0.10578907087905457654220386143818487109 / 2.0, 0.10578907087905457654220386143818487109 / 2.0, 0.15934280057233240536079894703404722173 / 2.0, 0.15934280057233240536079894703404722173 / 2.0, 0.15934280057233240536079894703404722173 / 2.0, 0.15934280057233240536079894703404722173 / 2.0, ] return weights, points end # To be completed (available in FEMQuad): tetra, hexa, prism # Conversion to barycentric rules for 'face' integration function quadrature_rule_bary(iside::Int, shape::Triangle, ::Val{1}) area = face_area(shape)[iside] weights = area .* (1.0,) baryCoords = ((0.5, 0.5),) return weights, baryCoords end function quadrature_rule_bary(iside::Int, shape::Triangle, ::Val{2}) area = face_area(shape)[iside] weights = area .* (0.5, 0.5) baryCoords = ( (0.7886751345948129, 0.21132486540518708), (0.21132486540518713, 0.7886751345948129), ) return weights, baryCoords end function quadrature_rule_bary(iside::Int, shape::Triangle, ::Val{3}) area = face_area(shape)[iside] weights = area .* (5.0 / 18.0, 8.0 / 18.0, 5.0 / 18.0) baryCoords = ( (0.8872983346207417, 0.1127016653792583), (0.5, 0.5), (0.1127016653792583, 0.8872983346207417), ) return weights, baryCoords end function quadrature_rule_bary(iside::Int, shape::Square, ::Val{1}) area = face_area(shape)[iside] weights = area .* (1.0,) baryCoords = ((0.5, 0.5),) return weights, baryCoords end function quadrature_rule_bary(iside::Int, shape::Square, ::Val{2}) area = face_area(shape)[iside] weights = area .* (0.5, 0.5) baryCoords = ( (0.7886751345948129, 0.21132486540518708), (0.21132486540518713, 0.7886751345948129), ) return weights, baryCoords end function quadrature_rule_bary(iside::Int, shape::Square, ::Val{3}) area = face_area(shape)[iside] weights = area .* (5.0 / 18.0, 8.0 / 18.0, 5.0 / 18.0) baryCoords = ( (0.8872983346207417, 0.1127016653792583), (0.5, 0.5), (0.1127016653792583, 0.8872983346207417), ) return weights, baryCoords end function quadrature_rule_bary(iside::Int, shape::Tetra, ::Val{1}) area = face_area(shape)[iside] weights = area .* (1.0,) baryCoords = ((1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0),) return weights, baryCoords end function quadrature_rule_bary(iside::Int, shape::Tetra, ::Val{2}) area = face_area(shape)[iside] weights = area .* (1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0) baryCoords = ( (1.0 / 6.0, 1.0 / 6.0, 2.0 / 3.0), (1.0 / 6.0, 2.0 / 3.0, 1.0 / 6.0), (2.0 / 3.0, 1.0 / 6.0, 1.0 / 6.0), ) return weights, baryCoords end function quadrature_rule(::Tetra, ::Val{1}, ::QuadratureLegendre) raw_unzip(get_quadrature_points(Val{:GLTET1})) end function quadrature_rule(::Tetra, ::Val{2}, ::QuadratureLegendre) raw_unzip(get_quadrature_points(Val{:GLTET4})) end function quadrature_rule(::Tetra, ::Val{3}, ::QuadratureLegendre) raw_unzip(get_quadrature_points(Val{:GLTET5})) end function quadrature_rule(::Tetra, ::Val{4}, ::QuadratureLegendre) raw_unzip(get_quadrature_points(Val{:GLTET15})) end # To be adapted to implement integration on square faces #function quadrature_rule(::Square, ::Val{1}, ::Barycentric) # weights = (1.0,) # baryCoords = ((0.25, 0.25, 0.25, 0.25),) # return zip(weights, baryCoords) #end # #function quadrature_rule(::Square, ::Val{2}, ::Barycentric) # weights = (0.25, 0.25, 0.25, 0.25) # w1 = sqrt(3.0)/3.0 # w2 = 0.5*(1.0-w1) # baryCoords = ( # (w1, w2, 0.0, w2), # (w2, w1, w2, 0.0), # (0.0, w2, w1, w2), # (w2, 0.0, w2, w1), # ) # return zip(weights, baryCoords) #end """ AbstractQuadratureNode{S,Q} Abstract type representing a quadrature node for a shape `S` and a quadrature `Q`. This type is used to represent and identify easily a quadrature node in a quadrature rules. Derived types must implement the following method: - get_index(quadnode::AbstractQuadratureNode{S,Q}) - get_coords(quadnode::AbstractQuadratureNode) """ abstract type AbstractQuadratureNode{S, Q} end get_shape(::AbstractQuadratureNode{S, Q}) where {S, Q} = S get_quadrature(::AbstractQuadratureNode{S, Q}) where {S, Q} = Q """ get_index(quadnode::AbstractQuadratureNode{S,Q}) Returns the index of `quadnode` in the parent quadrature rule `AbstractQuadRules{S,Q}` """ function get_index(quadnode::AbstractQuadratureNode) error("'get_index' is not defined for type $(typeof(quadnode))") end """ get_coords(quadnode::AbstractQuadratureNode) Returns the coordinates of `quadnode`. """ function get_coords(quadnode::AbstractQuadratureNode) error("'get_coords' is not defined for type $(typeof(quadnode))") end """ evalquadnode(f, quadnode::AbstractQuadratureNode) Evaluate the function `f` at the coordinates of `quadnode`. Basically, it computes: ```jl f(get_coords(quadnode)) ``` # Remark: Optimization could be applied if `f` is a function based on a nodal basis such as one of the DoF and `quadnode` are collocated. """ evalquadnode(f, quadnode::AbstractQuadratureNode) = f(get_coords(quadnode)) get_quadrature_rule(::AbstractQuadratureNode{S, Q}) where {S, Q} = QuadratureRule(S(), Q()) # default rules for retro-compatibility get_coords(x::Number) = x get_coords(x::AbstractArray{T}) where {T <: Number} = x Base.getindex(quadnode::AbstractQuadratureNode, i) = get_coords(quadnode)[i] Base.IteratorEltype(x::Bcube.AbstractQuadratureNode) = Base.IteratorEltype(get_coords(x)) Base.IteratorSize(x::Bcube.AbstractQuadratureNode) = Base.IteratorSize(get_coords(x)) Base.size(x::Bcube.AbstractQuadratureNode) = Base.size(get_coords(x)) Base.iterate(x::Bcube.AbstractQuadratureNode) = Base.iterate(get_coords(x)) function Base.iterate(x::Bcube.AbstractQuadratureNode, i::Integer) Base.iterate(get_coords(x), i::Integer) end function Base.Broadcast.broadcastable(x::AbstractQuadratureNode) Base.Broadcast.broadcastable(get_coords(x)) end """ QuadratureNode{S,Q} Type representing a quadrature node for a shape `S` and a quadrature `Q`. This type can be used to represent and identify easily a quadrature node in the corresponding parent quadrature rule. """ struct QuadratureNode{S, Q, Ti, Tx} <: AbstractQuadratureNode{S, Q} i::Ti x::Tx end function QuadratureNode(shape, quad, i::Integer, x) S, Q, Ti, Tx = typeof(shape), typeof(quad), typeof(i), typeof(x) QuadratureNode{S, Q, Ti, Tx}(i, x) end get_index(quadnode::QuadratureNode) = quadnode.i get_coords(quadnode::QuadratureNode) = quadnode.x function get_quadnodes_impl(::Type{<:QuadratureRule{S, Q, N}}) where {S, Q, N} quad = Q() _, x = quadrature_rule(S(), Val(get_degree(quad)), get_quadtype(quad)) x = map(a -> SVector{length(a), typeof(a[1])}(a), x) quadnodes = [QuadratureNode{S, Q, typeof(i), typeof(_x)}(i, _x) for (i, _x) in enumerate(x)] return :(SA[$(quadnodes...)]) end """ get_quadnodes(qr::QuadratureRule{S,Q,N}) where {S,Q,N} Returns an vector containing each `QuadratureNode` of `qr` """ @generated function get_quadnodes(qr::QuadratureRule{S, Q, N}) where {S, Q, N} expr = get_quadnodes_impl(qr) return expr end # ismapover(::Tuple{Vararg{AbstractQuadratureNode}}) = MapOverStyle() function _map_quadrature_node_impl( t::Type{<:Tuple{Vararg{AbstractQuadratureNode, N}}}, ) where {N} expr = ntuple(i -> :(f(t[$i])), N) return :(SA[$(expr...)]) end @generated function Base.map(f, t::Tuple{Vararg{AbstractQuadratureNode, N}}) where {N} return _map_quadrature_node_impl(t) end abstract type AbtractCollocatedStyle end struct IsCollocatedStyle <: AbtractCollocatedStyle end struct IsNotCollocatedStyle <: AbtractCollocatedStyle end is_collocated(::AbstractQuadrature, ::AbstractQuadrature) = IsNotCollocatedStyle() #default is_collocated(::Q, ::Q) where {Q <: AbstractQuadrature} = IsCollocatedStyle() is_collocated(::AbstractQuadratureRule, ::AbstractQuadratureRule) = IsNotCollocatedStyle() #default # for two AbstractQuadratureRule defined on the same shape: function is_collocated( q1::AbstractQuadratureRule{S}, q2::AbstractQuadratureRule{S}, ) where {S} return is_collocated(get_quadrature(q1), get_quadrature(q2)) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
19156
""" write_vtk(basename::String, it::Int,time::Real, mesh::AbstractMesh{topoDim,spaceDim}, vars::Dict{String,Tuple{V,L}}; append=false) where{topoDim,spaceDim,V,L<:WriteVTK.AbstractFieldData} Write a set of variables on the mesh nodes or cell centers to a VTK file. # Example ```julia mesh = basic_mesh() u = rand(ncells(mesh)) v = rand(nnodes(mesh)) dict_vars = Dict( "u" => (u, VTKCellData()), "v" => (v, VTKPointData()) ) write_vtk("output", 0, 0.0, mesh, dict_vars) ``` """ function write_vtk( basename::String, it::Int, time::Real, mesh::AbstractMesh{topoDim, spaceDim}, vars::Dict{String, Tuple{V, L}}; append = false, ) where {topoDim, spaceDim, V, L <: WriteVTK.AbstractFieldData} pvd = paraview_collection(basename; append = append) # Create coordinates arrays vtknodes = reshape( [get_coords(n)[idim] for n in get_nodes(mesh) for idim in 1:spaceDim], spaceDim, nnodes(mesh), ) # Connectivity c2n = connectivities_indices(mesh, :c2n) # Create cell array vtkcells = [MeshCell(vtk_entity(cells(mesh)[icell]), c2n[icell]) for icell in 1:ncells(mesh)] # Define mesh for vtk new_name = _build_fname_with_iterations(basename, it) vtkfile = vtk_grid(new_name, vtknodes, vtkcells) for (varname, (value, loc)) in vars vtkfile[varname, loc] = value end pvd[float(time)] = vtkfile vtk_save(pvd) # also triggers `vtk_save(vtkfile)` end """ VTK writer for a set of discontinuous functions. `vars` is a dictionnary of variable name => (values, values_location) where values is an array of numbers. """ function write_vtk_discontinuous( basename::String, it::Int, time::Real, mesh::AbstractMesh{topoDim, spaceDim}, vars::Dict{String, Tuple{V, L}}, degree::Int; append = false, ) where {topoDim, spaceDim, V, L <: WriteVTK.AbstractFieldData} pvd = paraview_collection(basename; append = append) # Connectivity c2n = connectivities_indices(mesh, :c2n) celltypes = cells(mesh) _degree = max(1, degree) fs = FunctionSpace(:Lagrange, max(1, degree)) # here, we implicitly impose that the mesh is composed of Lagrange elements only # Create coordinates arrays # vtknodes = reshape([get_coords(n)[idim] for i in 1:ncells(mesh) for n in get_nodes(mesh,c2n[i]) for idim in 1:spaceDim],spaceDim,:) _coords = [ mapping(celltypes[i], get_nodes(mesh, c2n[i]), ξ)[idim] for i in 1:ncells(mesh) for ξ in _vtk_coords_from_lagrange(shape(celltypes[i]), _degree) for idim in 1:spaceDim ] vtknodes = reshape(_coords, spaceDim, :) # Create cell array vtkcells = MeshCell[] count = 0 for icell in 1:ncells(mesh) _nnode = get_ndofs(fs, shape(celltypes[icell])) push!( vtkcells, MeshCell( vtk_entity(shape(cells(mesh)[icell]), Val(_degree)), collect((count + 1):(count + _nnode)), ), ) count += _nnode end _index_val = [ _vtk_lagrange_node_index_vtk_to_bcube(shape(celltypes[i]), _degree) for i in 1:ncells(mesh) ] index_val = similar(rawcat(_index_val)) offset = 0 for ind in _index_val index_val[(offset + 1):(offset + length(ind))] .= (offset .+ ind) offset += length(ind) end # Define mesh for vtk #vtk_save(paraview_collection(basename)) new_name = _build_fname_with_iterations(basename, it) vtkfile = vtk_grid(new_name, vtknodes, vtkcells) for (varname, (value, loc)) in vars if isa(loc, VTKPointData) vtkfile[varname, loc] = value[index_val] else vtkfile[varname, loc] = value end end pvd[float(time)] = vtkfile vtk_save(pvd) end function write_vtk_bnd_discontinuous( basename::String, it::Int, time::Real, domain::BoundaryFaceDomain, vars::Dict{String, Tuple{V, L}}, degree::Int; append = false, ) where {V, L <: WriteVTK.AbstractFieldData} pvd = paraview_collection(basename; append = append) mesh = get_mesh(domain) sdim = spacedim(mesh) # Connectivities c2n = connectivities_indices(mesh, :c2n) f2n = connectivities_indices(mesh, :f2n) f2c = connectivities_indices(mesh, :f2c) # Cell and face types celltypes = cells(mesh) bndfaces = get_cache(domain) fs = FunctionSpace(:Lagrange, max(1, degree)) # here, we implicitly impose that the mesh is composed of Lagrange elements only a = map(bndfaces) do iface icell = f2c[iface][1] sideᵢ = cell_side(celltypes[icell], c2n[icell], f2n[iface]) localfacedofs = idof_by_face_with_bounds(fs, shape(celltypes[icell]))[sideᵢ] ξ = get_coords(fs, shape(celltypes[icell]))[localfacedofs] xdofs = map(_ξ -> mapping(celltypes[icell], get_nodes(mesh, c2n[icell]), _ξ), ξ) ftype = entity(face_shapes(shape(celltypes[icell]), sideᵢ), Val(degree)) ftype, rawcat(xdofs) end ftypes = getindex.(a, 1) vtknodes = reshape(rawcat(getindex.(a, 2)), sdim, :) # Create elements array vtkcells = MeshCell[] count = 0 for ftype in ftypes _nnode = get_ndofs(fs, shape(ftype)) push!(vtkcells, MeshCell(vtk_entity(ftype), collect((count + 1):(count + _nnode)))) count += _nnode end # Define mesh for vtk new_name = _build_fname_with_iterations(basename, it) vtkfile = vtk_grid(new_name, vtknodes, vtkcells) for (varname, (value, loc)) in vars vtkfile[varname, loc] = value end pvd[float(time)] = vtkfile vtk_save(pvd) end """ write_vtk(basename::String, mesh::AbstractMesh{topoDim,spaceDim}) where{topoDim,spaceDim} Write the mesh to a VTK file. # Example ```julia write_vtk("output", basic_mesh()) ``` """ function write_vtk( basename::String, mesh::AbstractMesh{topoDim, spaceDim}, ) where {topoDim, spaceDim} dict_vars = Dict{String, Tuple{Any, WriteVTK.AbstractFieldData}}() write_vtk(basename, 1, 0.0, mesh, dict_vars) end """ vtk_entity(t::AbstractEntityType) Convert an `AbstractEntityType` into a `VTKCellType`. To find the correspondance, browse the `WriteVTK` package AND check the Doxygen (for numbering) : https://vtk.org/doc/nightly/html/classvtkTriQuadraticHexahedron.html """ function vtk_entity(t::AbstractEntityType) error("Entity type $t doesn't have a VTK correspondance") end vtk_entity(::Node_t) = VTKCellTypes.VTK_VERTEX vtk_entity(::Bar2_t) = VTKCellTypes.VTK_LINE vtk_entity(::Bar3_t) = VTKCellTypes.VTK_LAGRANGE_CURVE vtk_entity(::Bar4_t) = VTKCellTypes.VTK_LAGRANGE_CURVE #vtk_entity(::Bar5_t) = error("undefined") vtk_entity(::Tri3_t) = VTKCellTypes.VTK_TRIANGLE vtk_entity(::Tri6_t) = VTKCellTypes.VTK_LAGRANGE_TRIANGLE #VTK_QUADRATIC_TRIANGLE vtk_entity(::Tri9_t) = error("undefined") vtk_entity(::Tri10_t) = VTKCellTypes.VTK_LAGRANGE_TRIANGLE #vtk_entity(::Tri12_t) = error("undefined") vtk_entity(::Quad4_t) = VTKCellTypes.VTK_QUAD vtk_entity(::Quad8_t) = VTKCellTypes.VTK_QUADRATIC_QUAD vtk_entity(::Quad9_t) = VTKCellTypes.VTK_BIQUADRATIC_QUAD vtk_entity(::Quad16_t) = VTKCellTypes.VTK_LAGRANGE_QUADRILATERAL vtk_entity(::Tetra4_t) = VTKCellTypes.VTK_TETRA vtk_entity(::Tetra10_t) = VTKCellTypes.VTK_QUADRATIC_TETRA vtk_entity(::Penta6_t) = VTKCellTypes.VTK_WEDGE vtk_entity(::Hexa8_t) = VTKCellTypes.VTK_HEXAHEDRON vtk_entity(::Pyra5_t) = VTKCellTypes.VTK_PYRAMID #vtk_entity(::Hexa27_t) = VTK_TRIQUADRATIC_HEXAHEDRON # NEED TO CHECK NODE NUMBERING : https://vtk.org/doc/nightly/html/classvtkTriQuadraticHexahedron.html vtk_entity(::Line, ::Val{Degree}) where {Degree} = VTKCellTypes.VTK_LAGRANGE_CURVE vtk_entity(::Square, ::Val{Degree}) where {Degree} = VTKCellTypes.VTK_LAGRANGE_QUADRILATERAL vtk_entity(::Triangle, ::Val{Degree}) where {Degree} = VTKCellTypes.VTK_LAGRANGE_TRIANGLE get_vtk_name(c::VTKCellType) = Val(Symbol(c.vtk_name)) const VTK_LAGRANGE_QUADRILATERAL = get_vtk_name(VTKCellTypes.VTK_LAGRANGE_QUADRILATERAL) const VTK_LAGRANGE_TRIANGLE = get_vtk_name(VTKCellTypes.VTK_LAGRANGE_TRIANGLE) """ Return the node numbering of the node designated by its position in the x and y direction. See https://www.kitware.com/modeling-arbitrary-order-lagrange-finite-elements-in-the-visualization-toolkit/. """ function _point_index_from_IJK(t::Val{:VTK_LAGRANGE_QUADRILATERAL}, degree, i, j) 1 + _point_index_from_IJK_0based(t, degree, i - 1, j - 1) end # see : https://github.com/Kitware/VTK/blob/675adbc0feeb3f62730ecacb2af87917af124543/Filters/Sources/vtkCellTypeSource.cxx # https://github.com/Kitware/VTK/blob/265ca48a79a36538c95622c237da11133608bbe5/Common/DataModel/vtkLagrangeQuadrilateral.cxx#L558 function _point_index_from_IJK_0based(::Val{:VTK_LAGRANGE_QUADRILATERAL}, degree, i, j) # 0-based algo ni = degree nj = degree ibnd = ((i == 0) || (i == ni)) jbnd = ((j == 0) || (j == nj)) # How many boundaries do we lie on at once? nbnd = (ibnd > 0 ? 1 : 0) + (jbnd > 0 ? 1 : 0) if nbnd == 2 # Vertex DOF return (i > 0 ? (j > 0 ? 2 : 1) : (j > 0 ? 3 : 0)) end offset = 4 if nbnd == 1 # Edge DOF ibnd == 0 && (return (i - 1) + (j > 0 ? degree - 1 + degree - 1 : 0) + offset) jbnd == 0 && (return (j - 1) + (i > 0 ? degree - 1 : 2 * (degree - 1) + degree - 1) + offset) end offset = offset + 2 * (degree - 1 + degree - 1) # Face DOF return (offset + (i - 1) + (degree - 1) * (j - 1)) end function _vtk_lagrange_node_index_vtk_to_bcube(shape::AbstractShape, degree) return 1:length(get_coords(FunctionSpace(Lagrange(), degree), shape)) end """ Bcube node numbering -> VTK node numbering (in a cell) """ function _vtk_lagrange_node_index_bcube_to_vtk(shape::Union{Square, Cube}, degree) n = _get_num_nodes_per_dim( QuadratureRule(shape, Quadrature(QuadratureUniform(), Val(degree))), ) IJK = CartesianIndices(ntuple(i -> 1:n[i], length(n))) vtk_cell_name = get_vtk_name(vtk_entity(shape, Val(degree))) # We loop over all the nodes designated by (i,j,k) and find the corresponding # VTK index for each node. index = map(vec(IJK)) do ijk _point_index_from_IJK(vtk_cell_name, degree, Tuple(ijk)...) end return index end """ VTK node numbering (in a cell) -> Bcube node numbering """ function _vtk_lagrange_node_index_vtk_to_bcube(shape::Union{Square, Cube}, degree) return invperm(_vtk_lagrange_node_index_bcube_to_vtk(shape, degree)) end function _vtk_coords_from_lagrange(shape::AbstractShape, degree) return get_coords(FunctionSpace(Lagrange(), degree), shape) end """ Coordinates of the nodes in the VTK cell, ordered as expected by VTK. """ function _vtk_coords_from_lagrange(shape::Union{Square, Cube}, degree) fs = FunctionSpace(Lagrange(), degree) c = get_coords(fs, shape) index = _vtk_lagrange_node_index_vtk_to_bcube(shape, degree) return c[index] end """ write_vtk_lagrange( basename::String, vars::Dict{String, F}, mesh::AbstractMesh, it::Integer = -1, time::Real = 0.0; mesh_degree::Integer = 1, discontinuous::Bool = true, functionSpaceType::AbstractFunctionSpaceType = Lagrange(), collection_append::Bool = false, vtk_kwargs..., ) where {F <: AbstractLazy} write_vtk_lagrange( basename::String, vars::Dict{String, F}, mesh::AbstractMesh, U_export::AbstractFESpace, it::Integer = -1, time::Real = 0.0; collection_append::Bool = false, vtk_kwargs..., ) where {F <: AbstractLazy} Write the provided FEFunction/MeshCellData/CellFunction on a mesh of order `mesh_degree` with the nodes defined by the `functionSpaceType` (only `Lagrange{:Uniform}` supported for now). The boolean `discontinuous` indicate if the node values should be discontinuous or not. `vars` is a dictionnary of variable name => Union{FEFunction,MeshCellData,CellFunction} to write. Cell-centered data should be wrapped as `MeshCellData` in the `vars` dict. To convert an `AbstractLazy` to a `MeshCellData`, simply use `Bcube.cell_mean` or `MeshCellData ∘ Bcube.var_on_centers`. # Remarks: * If `mesh` is of degree `d`, the solution will be written on a mesh of degree `mesh_degree`, even if this number is different from `d`. * The degree of the input FEFunction (P1, P2, P3, ...) is not used to define the nodes where the solution is written, only `mesh` and `mesh_degree` matter. The FEFunction is simply evaluated on the aforementionned nodes. # Example ```julia mesh = rectangle_mesh(6, 7; xmin = -1, xmax = 1.0, ymin = -1, ymax = 1.0) f_u = PhysicalFunction(x -> x[1]^2 + x[2]^2) u = FEFunction(TrialFESpace(FunctionSpace(:Lagrange, 4), mesh)) projection_l2!(u, f_u, mesh) vars = Dict("f_u" => f_u, "u" => u, "grad_u" => ∇(u)) for mesh_degree in 1:5 Bcube.write_vtk_lagrange( joinpath(@__DIR__, "output"), vars, mesh; mesh_degree, discontinuous = false ) end ``` # Dev notes - in order to write an ASCII file, you must pass both `ascii = true` and `append = false` - `collection_append` is not named `append` to enable passing correct `kwargs` to `vtk_grid` - remove (once fully validated) : `write_vtk_discontinuous` """ function write_vtk_lagrange( basename::String, vars::Dict{String, F}, mesh::AbstractMesh, it::Integer = -1, time::Real = 0.0; mesh_degree::Integer = 1, discontinuous::Bool = true, functionSpaceType::AbstractFunctionSpaceType = Lagrange(), collection_append::Bool = false, vtk_kwargs..., ) where {F <: AbstractLazy} U_export = TrialFESpace( FunctionSpace(functionSpaceType, mesh_degree), mesh; isContinuous = !discontinuous, ) write_vtk_lagrange( basename, vars, mesh, U_export, it, time; collection_append, vtk_kwargs..., ) end function write_vtk_lagrange( basename::String, vars::Dict{String, F}, mesh::AbstractMesh, U_export::AbstractFESpace, it::Integer = -1, time::Real = 0.0; collection_append = false, vtk_kwargs..., ) where {F <: AbstractLazy} # FE space stuff fs_export = get_function_space(U_export) @assert get_type(fs_export) <: Lagrange "Only FunctionSpace of type Lagrange are supported for now" degree_export = get_degree(fs_export) dhl_export = Bcube._get_dhl(U_export) nd = get_ndofs(dhl_export) # extract all `MeshCellData` in `vars` as this type of variable # will not be interpolated to nodes and will be written with # the `VTKCellData` attribute. vars_cell = filter(((k, v),) -> v isa MeshData{<:CellData}, vars) vars_point = filter(((k, v),) -> k ∉ keys(vars_cell), vars) # Get ncomps and type of each `point` variable type_dim = map(var -> get_return_type_and_codim(var, mesh), values(vars_point)) # VTK stuff coords_vtk = zeros(spacedim(mesh), nd) values_vtk = map(((_t, _d),) -> zeros(_t, _d..., nd), type_dim) cells_vtk = MeshCell[] sizehint!(cells_vtk, ncells(mesh)) nodeweigth_vtk = zeros(nd) # Loop over mesh cells for cinfo in DomainIterator(CellDomain(mesh)) # Cell infos icell = cellindex(cinfo) ctype = celltype(cinfo) _shape = shape(ctype) # Get Lagrange dofs/nodes coordinates in ref space (Bcube order) coords_bcube = get_coords(fs_export, _shape) # Get VTK <-> BCUBE dofs/nodes mapping v2b = Bcube._vtk_lagrange_node_index_vtk_to_bcube(_shape, degree_export) # Add nodes coordinates to coords_vtk for (iloc, ξ) in enumerate(coords_bcube) # Global number of the node iglob = get_dof(dhl_export, icell, 1, iloc) # Create CellPoint (in reference domain) cpoint = CellPoint(ξ, cinfo, ReferenceDomain()) # Map it to the physical domain and assign to VTK coords_vtk[:, iglob] .= get_coords(change_domain(cpoint, PhysicalDomain())) nodeweigth_vtk[iglob] += 1.0 # Evaluate all vars on this node for (ivar, var) in enumerate(values(vars_point)) _var = materialize(var, cinfo) values_vtk[ivar][:, iglob] .+= materialize(_var, cpoint) end end # Create the VTK cells with the correct ordering iglobs = get_dof(dhl_export, icell) push!( cells_vtk, MeshCell(vtk_entity(_shape, Val(degree_export)), view(iglobs, v2b)), ) end # Averaging contribution at nodes : # For discontinuous variables written as a continuous # field, node averaging is necessary because each adjacent # cells gives different interpolated values at nodes, then # a averaging step is used to define a unique node value. # This step has no effect on node values for : # - discontinuous variables written as a discontinous # fields as nodes are duplicated in this case and # there is one cell contribution for each duplicated # node (nodeweigth_vtk[i] is equal to 1, ∀i). # - continous variables written as a continous fields # because interpolated values are all equals and # averaging gives the same value. for val in values_vtk for i in eachindex(nodeweigth_vtk) val[:, i] .= val[:, i] ./ nodeweigth_vtk[i] end end # Write VTK file pvd = paraview_collection(basename; append = collection_append) new_name = _build_fname_with_iterations(basename, it) vtkfile = vtk_grid(new_name, coords_vtk, cells_vtk; vtk_kwargs...) for (varname, value) in zip(keys(vars_point), values_vtk) vtkfile[varname, VTKPointData()] = value end for (varname, value) in zip(keys(vars_cell), values(vars_cell)) vtkfile[varname, VTKCellData()] = get_values(value) end pvd[float(time)] = vtkfile vtk_save(pvd) end """ Append the number of iteration (if positive) to the basename """ function _build_fname_with_iterations(basename::String, it::Integer) it >= 0 ? @sprintf("%s_%08i", basename, it) : basename end function write_file( ::Bcube.VTKIoHandler, basename::String, mesh::AbstractMesh, U_export::AbstractFESpace, data = nothing, it::Integer = -1, time::Real = 0.0; collection_append = false, kwargs..., ) # Remove extension from filename _basename = first(splitext(basename)) # Just write the mesh if `data` is `nothing` if isnothing(data) write_vtk(_basename, mesh) return end # We don't use FlowSolution names in VTK, so we flatten everything _data = data if valtype(data) <: Dict _keys = map(d -> collect(keys(d)), values(data)) _keys = vcat(_keys...) _values = map(d -> collect(values(d)), values(data)) _values = vcat(_values...) _data = Dict(_keys .=> _values) end # Write ! write_vtk_lagrange(_basename, _data, mesh, U_export, it, time; collection_append) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
4214
using Bcube using Test using StaticArrays using LinearAlgebra using DelimitedFiles using ForwardDiff using SHA: sha1 using SparseArrays using WriteVTK # from : # https://discourse.julialang.org/t/what-general-purpose-commands-do-you-usually-end-up-adding-to-your-projects/4889 @generated function compare_struct(x, y) if !isempty(fieldnames(x)) && x == y mapreduce(n -> :(x.$n == y.$n), (a, b) -> :($a && $b), fieldnames(x)) else :(x == y) end end """ Custom way to "include" a file to print infos. """ function custom_include(path) filename = split(path, "/")[end] print("Running test file " * filename * "...") include(path) println("done.") end function Base.isapprox(A::Tuple{SVector{N, R}}, B::Tuple{SVector{N, R}}) where {N, R} all(map(isapprox, A, B)) end function isapprox_arrays(a::AbstractArray, b::AbstractArray; rtol::Real = eps()) function g(x, y) if abs(y) < 10rtol isapprox(x, y; rtol = 0, atol = eps()) else isapprox(x, y; rtol = rtol) end end success = all(map(g, a, b)) (success == false) && (@show a, b) return success end import Bcube: absolute_indices, boundary_faces, boundary_nodes, by, cells, cellindex, CellInfo, CellPoint, celltype, cell_side, center, change_domain, compute, connectivities, connectivities_indices, Connectivity, connectivity_cell2cell_by_faces, connectivity_cell2cell_by_nodes, Cube, get_dof, DofHandler, DomainIterator, edges2nodes, FaceInfo, FacePoint, faces, faces2nodes, face_area, face_shapes, from, f2n_from_c2n, get_coords, get_dofs, get_fespace, get_mapping, get_nodes, has_cells, has_edges, has_entities, has_faces, has_nodes, has_vertices, indices, inner_faces, integrate_on_ref_element, interpolate, inverse_connectivity, Line, mapping, mapping_det_jacobian, mapping_face, mapping_inv, mapping_jacobian, mapping_jacobian_inv, materialize, maxsize, max_ndofs, Mesh, minsize, myrand, nedges, nfaces, nlayers, nodes, normal, normals, nvertices, n_entities, oriented_cell_side, outer_faces, Prism, PhysicalDomain, ReferenceDomain, shape, shape_functions, spacedim, Square, Tetra, to, topodim, Triangle, ∂λξ_∂ξ, ∂λξ_∂x # This dir will be removed at the end of the tests tempdir = mktempdir() # Reading sha1 checksums f = readdlm(joinpath(@__DIR__, "checksums.sha1"), String) fname2sum = Dict(r[2] => r[1] for r in eachrow(f)) @testset "Bcube.jl" begin custom_include("./test_utils.jl") custom_include("./mesh/test_entity.jl") custom_include("./mesh/test_connectivity.jl") custom_include("./mesh/test_transformation.jl") custom_include("./mesh/test_mesh.jl") custom_include("./mesh/test_mesh_generator.jl") custom_include("./mesh/test_gmsh.jl") custom_include("./mesh/test_domain.jl") custom_include("./mapping/test_mapping.jl") custom_include("./mapping/test_ref2phys.jl") custom_include("./interpolation/test_shape.jl") custom_include("./interpolation/test_lagrange.jl") custom_include("./interpolation/test_taylor.jl") custom_include("./fespace/test_dofhandler.jl") custom_include("./fespace/test_fespace.jl") custom_include("./fespace/test_fefunction.jl") custom_include("./interpolation/test_projection.jl") custom_include("./integration/test_integration.jl") # custom_include("./dof/test_variable.jl") #TODO : update with new API custom_include("./interpolation/test_shapefunctions.jl") # custom_include("./interpolation/test_limiter.jl") custom_include("./interpolation/test_cellfunction.jl") custom_include("./dof/test_assembler.jl") custom_include("./operator/test_algebra.jl") custom_include("./dof/test_meshdata.jl") custom_include("./writers/test_vtk.jl") @testset "Issues" begin custom_include("./issues/issue_112.jl") custom_include("./issues/issue_130.jl") end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1736
import Bcube: densify, densify!, rawcat @testset "utils" begin @testset "densify" begin a = [i for i in 1:5] densify!(a) @test a == [i for i in 1:5] a = [1, 3, 4, 5, 2, 3] densify!(a) @test a == [1, 2, 3, 4, 5, 2] a = [1, 2, 4, 10, 6, 10, 2] densify!(a) @test a == [1, 2, 3, 4, 5, 4, 2] a = [1, 2, 4, 10, 6, 10, 2] remap = [1, 2, 0, 3, 4, 5, 0, 0, 0, 4] _a, _remap = densify(a; permute_back = true) @test all(_remap[i] == remap[i] for i in keys(_remap)) end @testset "otimes" begin a = [1, 2] @test otimes(a, a) == [1 2; 2 4] end @testset "dcontract" begin A = zeros(2, 2, 2) A[1, :, :] .= [1 2; 3 4] A[2, :, :] .= [-1 -1; 0 0] B = zeros(2, 2) B .= [1 2; 3 4] @test A ⊡ B == [30.0; -3.0] end @testset "rawcat" begin a = [[1, 2], [3, 4, 5], [6, 7]] @test rawcat(a) == [1, 2, 3, 4, 5, 6, 7] b = [SA[1, 2], SA[3, 4, 5], SA[6, 7]] @test rawcat(b) == [1, 2, 3, 4, 5, 6, 7] c = [[1 2; 10 20], [3 4 5; 30 40 50], [6 7; 60 70]] @test rawcat(c) == [1, 10, 2, 20, 3, 30, 4, 40, 5, 50, 6, 60, 7, 70] d = [SA[1 2; 10 20], SA[3 4 5; 30 40 50], SA[6 7; 60 70]] @test rawcat(d) == [1, 10, 2, 20, 3, 30, 4, 40, 5, 50, 6, 60, 7, 70] @test isa(rawcat(d), Vector) x = [1, 2, 3] @test rawcat(x) == x end @testset "matrix_2_vector_of_SA" begin a = [ 1 2 3 4 5 6 ] b = Bcube.matrix_2_vector_of_SA(a) @test b[1] == SA[1, 4] @test b[2] == SA[2, 5] @test b[3] == SA[3, 6] end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
15235
@testset "Assembler" begin @testset "linear-single-scalar-fe" begin #---- Mesh 1 nx = 5 mesh = line_mesh(nx) Δx = 1.0 / (nx - 1) # Function space fs = FunctionSpace(:Lagrange, 1) # Finite element space V = TestFESpace(fs, mesh) # Measure dΩ = Measure(CellDomain(mesh), 3) # Linear forms f = PhysicalFunction(x -> x[1]) l1(v) = ∫(v)dΩ l2(v) = ∫(f * v)dΩ l3(v) = ∫((c * u) ⋅ ∇(v))dΩ # Compute integrals b1 = assemble_linear(l1, V) b2 = assemble_linear(l2, V) # Check results @test b1 == SA[Δx / 2, Δx, Δx, Δx, Δx / 2] res2 = [Δx^2 * (i - 1) for i in 1:nx] res2[1] = Δx^2 / 6.0 res2[nx] = Δx^2 / 2.0 * (nx - 4.0 / 3.0) @test all(isapprox.(b2, res2)) #---- Mesh 2 degree = 1 α = 10.0 c = SA[0.5, 1.0] # [cx, cy] sx = 2 sy = 3 mesh = one_cell_mesh(:quad) transform!(mesh, x -> x .* SA[sx, sy]) Δx = 2 * sx Δy = 2 * sy fs = FunctionSpace(:Lagrange, degree) U = TrialFESpace(fs, mesh; isContinuous = false) V = TestFESpace(U) dΩ = Measure(CellDomain(mesh), 2 * degree + 1) u = FEFunction(U, α .* ones(get_ndofs(V))) # Rq: # Mesh is defined by (Δx, Δy) # λ[1] <=> λ associated to node [-1, -1] (i.e node 1 of reference square) # λ[2] <=> λ associated to node [ 1, -1] (i.e node 2 of reference square) # λ[3] <=> λ associated to node [-1, 1] (i.e node 4 of reference square) # λ[4] <=> λ associated to node [ 1, 1] (i.e node 3 of reference square) l(v) = ∫((c * u) ⋅ ∇(v))dΩ b = assemble_linear(l, V) b_ref = [ -α / 2 * (c[1] * Δy + c[2] * Δx), α / 2 * (c[1] * Δy - c[2] * Δx), α / 2 * (-c[1] * Δy + c[2] * Δx), α / 2 * (c[1] * Δy + c[2] * Δx), ] @test all(b .≈ b_ref) # test with operator composition _f(u, ∇v) = (c * u) ⋅ ∇v l_compo(v) = ∫(_f ∘ (u, ∇(v)))dΩ b_compo = assemble_linear(l_compo, V) @test all(b_compo .≈ b_ref) end @testset "linear-single-vector-fe" begin # Mesh nx = 5 mesh = line_mesh(nx) Δx = 1.0 / (nx - 1) # Function space fs = FunctionSpace(:Lagrange, 1) # Finite element space V = TestFESpace(fs, mesh; size = 2) # Measure dΩ = Measure(CellDomain(mesh), 3) # Linear forms f = PhysicalFunction(x -> SA[x[1], x[1] / 2.0]) l1(v) = ∫(f ⋅ v)dΩ # Compute integrals b1 = assemble_linear(l1, V) # Check results # (obtained from single-scalar test, and knowing the dof numbering) res1 = [Δx^2 * (i - 1) for i in 1:nx] res1[1] = Δx^2 / 6.0 res1[nx] = Δx^2 / 2.0 * (nx - 4.0 / 3.0) @test b1[1] ≈ res1[1] @test b1[2] ≈ res1[2] @test b1[3] ≈ res1[1] / 2.0 @test b1[4] ≈ res1[2] / 2.0 @test all(isapprox.(b1[5:2:end], res1[3:end])) @test all(isapprox.(b1[6:2:end], res1[3:end] ./ 2.0)) end @testset "linear-multi-scalar-fe" begin # Mesh nx = 5 mesh = line_mesh(nx) Δx = 1.0 / (nx - 1) # Function space fs = FunctionSpace(:Lagrange, 1) # Finite element space V1 = TestFESpace(fs, mesh) V2 = TestFESpace(fs, mesh) V = MultiFESpace(V1, V2; arrayOfStruct = false) # Measure dΩ = Measure(CellDomain(mesh), 3) # Linear forms f1 = PhysicalFunction(x -> x[1]) f2 = PhysicalFunction(x -> x[1] / 2.0) l1((v1, v2)) = ∫(f1 * v1 + f2 * v2)dΩ # Compute integrals b1 = assemble_linear(l1, V) # Check results # (obtained from single-scalar test, and knowing the dof numbering) res1 = [Δx^2 * (i - 1) for i in 1:nx] res1[1] = Δx^2 / 6.0 res1[nx] = Δx^2 / 2.0 * (nx - 4.0 / 3.0) @test all(isapprox.(b1[1:nx], res1)) @test all(isapprox.(b1[(nx + 1):end], res1 ./ 2.0)) # test with operator composition f_l1_compo(v1, v2, f1, f2) = f1 * v1 + f2 * v2 l1_compo((v1, v2)) = ∫(f_l1_compo ∘ (v1, v2, f1, f2))dΩ b1_compo = assemble_linear(l1_compo, V) @test all(b1_compo .≈ b1) # test `MultiIntegration` l_multi(v) = 3 * l1(v) - 4 * l1(v) + 7 * l1(v) b_multi = assemble_linear(l_multi, V) @test all(b_multi .≈ 6 * b1) end @testset "linear-multi-vector-fe" begin # Mesh mesh = one_cell_mesh(:tri) # Function space fs_u = FunctionSpace(:Lagrange, 1) fs_p = FunctionSpace(:Lagrange, 1) # Finite element spaces U_xy = TrialFESpace(fs_u, mesh; size = 2) U_z = TrialFESpace(fs_u, mesh) U_p = TrialFESpace(fs_p, mesh) V_xy = TestFESpace(U_xy) V_z = TestFESpace(U_z) V_p = TestFESpace(U_p) U = MultiFESpace(U_p, U_xy, U_z) V = MultiFESpace(V_p, V_xy, V_z) # Measure dΩ = Measure(CellDomain(mesh), 3) # bi-linear form a((u_p, u_xy, u_z), (v_p, v_xy, v_z)) = ∫(u_xy ⋅ v_xy + u_p ⋅ v_z + ∇(u_p) ⋅ v_xy)dΩ # Compute integrals A = assemble_bilinear(a, U, V) # Test a few values... @test A[12, 1] ≈ 1.0 / 6.0 @test A[12, 2] ≈ 1.0 / 6.0 @test A[12, 3] ≈ 1.0 / 3.0 end @testset "Bilinear rectangular system" begin mesh = one_cell_mesh(:line) U = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh) V = TestFESpace(FunctionSpace(:Lagrange, 2), mesh) dΩ = Measure(CellDomain(mesh), 2) a(u, v) = ∫(∇(u) ⋅ v)dΩ l(v) = ∫(v)dΩ A = assemble_bilinear(a, U, V) b = assemble_linear(l, V) @test all((A[1, 1], A[1, 2]) .≈ (-1.0 / 6.0, 1.0 / 6.0)) @test all((A[2, 1], A[2, 2]) .≈ (-2.0 / 3.0, 2.0 / 3.0)) @test all((A[3, 1], A[3, 2]) .≈ (-1.0 / 6.0, 1.0 / 6.0)) end @testset "Poisson DG" begin degree = 3 degree_quad = 2 * degree + 1 γ = degree * (degree + 1) n = 4 Lx = 1.0 h = Lx / n uref = PhysicalFunction(x -> 3 * x[1] + x[2]^2 + 2 * x[1]^3) f = PhysicalFunction(x -> -2 - 12 * x[1]) g = uref # boundary condition avg(u) = 0.5 * (side⁺(u) + side⁻(u)) # Build mesh meshParam = (nx = n + 1, ny = n + 1, lx = Lx, ly = Lx, xc = 0.0, yc = 0.0) path = joinpath(tempdir, "mesh.msh") gen_rectangle_mesh(path, :quad; meshParam...) mesh = read_msh(path) # Choose degree and define function space, trial space and test space fs = FunctionSpace(:Lagrange, degree) U = TrialFESpace(fs, mesh, :discontinuous) V = TestFESpace(U) # Define volume and boundary measures dΩ = Measure(CellDomain(mesh), degree_quad) dΓ = Measure(InteriorFaceDomain(mesh), degree_quad) dΓb = Measure(BoundaryFaceDomain(mesh), degree_quad) nΓ = get_face_normals(dΓ) nΓb = get_face_normals(dΓb) a_Ω(u, v) = ∫(∇(v) ⋅ ∇(u))dΩ l_Ω(v) = ∫(v * f)dΩ function a_Γ(u, v) ∫( -jump(v, nΓ) ⋅ avg(∇(u)) - avg(∇(v)) ⋅ jump(u, nΓ) + γ / h * jump(v, nΓ) ⋅ jump(u, nΓ), )dΓ end fa_Γb(u, ∇u, v, ∇v, n) = -v * (∇u ⋅ n) - (∇v ⋅ n) * u + (γ / h) * v * u a_Γb(u, v) = ∫(fa_Γb ∘ map(side⁻, (u, ∇(u), v, ∇(v), nΓb)))dΓb fl_Γb(v, ∇v, n, g) = -(∇v ⋅ n) * g + (γ / h) * v * g l_Γb(v) = ∫(fl_Γb ∘ map(side⁻, (v, ∇(v), nΓb, g)))dΓb a(u, v) = a_Ω(u, v) + a_Γ(u, v) + a_Γb(u, v) l(v) = l_Ω(v) + l_Γb(v) sys = Bcube.AffineFESystem(a, l, U, V) uh = Bcube.solve(sys) l2(u) = sqrt(sum(compute(∫(u ⋅ u)dΩ))) h1(u) = sqrt(sum(compute(∫(u ⋅ u + ∇(u) ⋅ ∇(u))dΩ))) e = uref - uh el2 = l2(e) eh1 = h1(e) tol = 1.e-12 @test el2 < tol @test eh1 < tol end @testset "Constrained Poisson" begin n = 2 Lx = 2.0 # Build mesh meshParam = (nx = n + 1, ny = n + 1, lx = Lx, ly = Lx, xc = 0.0, yc = 0.0) tmp_path = "tmp.msh" gen_rectangle_mesh(tmp_path, :quad; meshParam...) mesh = read_msh(tmp_path) rm(tmp_path) # Choose degree and define function space, trial space and test space degree = 2 fs = FunctionSpace(:Lagrange, degree) U = TrialFESpace(fs, mesh) V = TestFESpace(U) Λᵤ = MultiplierFESpace(mesh, 1) Λᵥ = TestFESpace(Λᵤ) # The usual trial FE space and multiplier space are combined into a MultiFESpace P = MultiFESpace(U, Λᵤ) Q = MultiFESpace(V, Λᵥ) # Define volume and boundary measures dΩ = Measure(CellDomain(mesh), 2 * degree + 1) Γ₁ = BoundaryFaceDomain(mesh, ("West",)) dΓ₁ = Measure(Γ₁, 2 * degree + 1) Γ = BoundaryFaceDomain(mesh, ("East", "South", "West", "North")) dΓ = Measure(Γ, 2 * degree + 1) # Define solution FE Function ϕ = FEFunction(U) f = PhysicalFunction(x -> 1.0) int_val = 4.0 / 3.0 volume = sum(compute(∫(PhysicalFunction(x -> 1.0))dΩ)) # Define bilinear and linear forms function a((u, λᵤ), (v, λᵥ)) ∫(∇(u) ⋅ ∇(v))dΩ + ∫(side⁻(λᵤ) * side⁻(v))dΓ + ∫(side⁻(λᵥ) * side⁻(u))dΓ end function l((v, λᵥ)) ∫(f * v + int_val * λᵥ / volume)dΩ + ∫(-2.0 * side⁻(v) + 0.0 * side⁻(λᵥ))dΓ₁ end # Assemble to get matrices and vectors A = assemble_bilinear(a, P, Q) L = assemble_linear(l, Q) # Solve problem sol = A \ L ϕ = FEFunction(Q) # Compare to analytical solution set_dof_values!(ϕ, sol) u, λ = ϕ u_ref = PhysicalFunction(x -> -0.5 * (x[1] - 1.0)^2 + 1.0) error = u_ref - u l2(u) = sqrt(sum(compute(∫(u ⋅ u)dΩ))) el2 = l2(error) tol = 1.e-15 @test el2 < tol end @testset "Heat solver 3d" begin function heat_solver(mesh, degree, dirichlet_dict, q, η, T_analytical) fs = FunctionSpace(:Lagrange, degree) U = TrialFESpace(fs, mesh, dirichlet_dict) V = TestFESpace(U) dΩ = Measure(CellDomain(mesh), 2 * degree + 1) a(u, v) = ∫(η * ∇(u) ⋅ ∇(v))dΩ l(v) = ∫(q * v)dΩ sys = AffineFESystem(a, l, U, V) ϕ = Bcube.solve(sys) Tcn = var_on_centers(ϕ, mesh) Tca = map(T_analytical, get_cell_centers(mesh)) return norm(Tcn .- Tca, Inf) / norm(Tca, Inf) end function driver_heat_solver() mesh_path = joinpath(tempdir, "tmp1.msh") gen_hexa_mesh(mesh_path, :tetra; xc = 0.0, yc = 0.0, zc = 0.0) mesh = read_msh(mesh_path) λ = 100.0 η = λ degree = 1 dirichlet_dict = Dict("xmin" => 260.0, "xmax" => 285.0) q = 0.0 T_analytical(x) = 260.0 * (0.5 - x[1]) + 285 * (x[1] + 0.5) err = heat_solver(mesh, degree, dirichlet_dict, q, η, T_analytical) @test err < 1.0e-14 mesh_path = joinpath(tempdir, "tmp2.msh") gen_hexa_mesh( mesh_path, :hexa; nx = 5, ny = 5, nz = 5, xc = 0.0, yc = 0.0, zc = 0.0, ) mesh = read_msh(mesh_path) degree = 2 dirichlet_dict = Dict("xmin" => 260.0) q = 1500.0 T2_analytical(x) = 260.0 + (q / λ) * x[1] * (1.0 - 0.5 * x[1]) scale(x) = (x[1] + 0.5) err = heat_solver(mesh, degree, dirichlet_dict, q, η, T2_analytical ∘ scale) @test err < 1.0e-14 # end driver_heat_solver() end @testset "Subdomain" begin n = 5 mesh = line_mesh(2 * n + 1; xmin = 0, xmax = 1) sub1 = 1:2:(2 * n) sub2 = 2:2:(2 * n) dΩ = Measure(CellDomain(mesh), 1) dΩ1 = Measure(CellDomain(mesh, sub1), 1) dΩ2 = Measure(CellDomain(mesh, sub2), 1) f = PhysicalFunction(x -> 1.0) @test sum(Bcube.compute(∫(f)dΩ1)) == 0.5 @test sum(Bcube.compute(∫(f)dΩ2)) == 0.5 end # @testset "Symbolic (to be completed)" begin # using MultivariatePolynomials # using TypedPolynomials # @polyvar x y # λ1 = (x - 1) * (y - 1) / 4 # λ2 = -(x + 1) * (y - 1) / 4 # λ4 = (x + 1) * (y + 1) / 4 # to match Bcube ordering # λ3 = -(x - 1) * (y + 1) / 4 # λall = (λ1, λ2, λ3, λ4) # ∇λ1 = differentiate(λ1, (x, y)) # ∇λ2 = differentiate(λ2, (x, y)) # ∇λ3 = differentiate(λ3, (x, y)) # ∇λ4 = differentiate(λ4, (x, y)) # ∇λall = (∇λ1, ∇λ2, ∇λ3, ∇λ4) # function integrate_poly_on_quad(p) # a = antidifferentiate(p, x) # b = subs(a, x => 1) - subs(a, x => -1) # c = antidifferentiate(b, y) # d = subs(c, y => 1) - subs(c, y => -1) # return d # end # interp_sca(base, values) = [base...] ⋅ values # function interp_vec(base, values) # n = floor(Int, length(values) / 2) # return [interp_sca(base, values[1:n]), interp_sca(base, values[n+1:end])] # end # # One cell mesh (for volumic integration) # mesh = one_cell_mesh(:quad) # factor = 1 # scale!(mesh, factor) # degree = 1 # dΩ = Measure(CellDomain(mesh), 2 * degree + 1) # fs = FunctionSpace(:Lagrange, degree) # U_sca = TrialFESpace(fs, mesh, :discontinuous) # U_vec = TrialFESpace(fs, mesh, :discontinuous; size=2) # V_sca = TestFESpace(U_sca) # V_vec = TestFESpace(U_vec) # ρ = FEFunction(U_sca) # ρu = FEFunction(U_vec) # ρE = FEFunction(U_sca) # U = MultiFESpace(U_sca, U_vec, U_sca) # V = MultiFESpace(V_sca, V_vec, V_sca) # # bilinear tests # a(u, v) = ∫(u ⋅ v)dΩ # M1 = assemble_bilinear(a, U_sca, V_sca) # M2 = factor^2 * [integrate_poly_on_quad(λj * λi) for λj in λall, λi in λall] # @show all(isapprox.(M1, M2)) # a(u, v) = ∫(∇(u) ⋅ ∇(v))dΩ # M1 = assemble_bilinear(a, U_sca, V_sca) # M2 = [integrate_poly_on_quad(∇λj ⋅ ∇λi) for ∇λj in ∇λall, ∇λi in ∇λall] # @show all(isapprox.(M1, M2)) # # linear tests # values_ρ = [1.0, 2.0, 3.0, 4.0] # values_ρu = [5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0] # ρ.dofValues .= values_ρ # ρu.dofValues .= values_ρu # ρu_sym = interp_vec(λall, values_ρu) # l(v) = ∫(ρu ⋅ ∇(v))dΩ # b1 = assemble_linear(l, V_sca) # b2 = [integrate_poly_on_quad(ρu_sym ⋅ ∇λi) for ∇λi in ∇λall] # @show all(isapprox.(b1, b2)) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
2523
@testset "MeshData" begin @testset "CellData" begin #--- Test 1 n = 3 mesh = line_mesh(n) dΩ = Measure(CellDomain(mesh), 2) # Scalar data data = collect(1:ncells(mesh)) d = Bcube.MeshCellData(data) integ = ∫(d)dΩ @test compute(integ) == [0.5, 1.0] # tensor data # data = [[1,2,3,4], [5,6,7,8], ...] data = collect(reinterpret(SVector{4, Int}, collect(1:(4 * ncells(mesh))))) d = Bcube.MeshCellData(data) @test compute(∫(d ⋅ [0, 1, 0, 0])dΩ) == [1.0, 3.0] #--- Test 2 mesh = line_mesh(3) array = [1.0, 2.0] funcs = [PhysicalFunction(x -> x), PhysicalFunction(x -> 2x)] cellArray = MeshCellData(array) cellFuncs = MeshCellData(funcs) for cInfo in DomainIterator(CellDomain(mesh)) i = cellindex(cInfo) cPointRef = CellPoint([0.0], cInfo, ReferenceDomain()) cPointPhy = change_domain(cPointRef, PhysicalDomain()) _cellArray = Bcube.materialize(cellArray, cInfo) @test Bcube.materialize(_cellArray, cPointRef) == array[i] _cellFuncs = Bcube.materialize(cellFuncs, cInfo) @test Bcube.materialize(_cellFuncs, cPointRef) == funcs[i](cPointPhy) end #--- Test 3, MeshCellData in face integration mesh = rectangle_mesh(2, 2; xmin = 0, xmax = 3, ymin = -1, ymax = 1) data = MeshCellData(ones(ncells(mesh))) dΓ = Measure(BoundaryFaceDomain(mesh), 1) values = nonzeros(Bcube.compute(∫(side_n(data))dΓ)) @test isapprox_arrays(values, [3.0, 2.0, 3.0, 2.0]) end @testset "FaceData" begin nodes = [Node([0.0, 0.0]), Node([2.0, 0.0]), Node([3.0, 1.0]), Node([1.0, 2.0])] celltypes = [Quad4_t()] cell2node = Connectivity([4], [1, 2, 3, 4]) bnd_name = "BORDER" tag2name = Dict(1 => bnd_name) tag2nodes = Dict(1 => collect(1:4)) mesh = Mesh(nodes, celltypes, cell2node; bc_names = tag2name, bc_nodes = tag2nodes) f(fnodes) = PhysicalFunction(x -> begin norm(x - get_coords(get_nodes(mesh, fnodes[1]))) end) f2n = connectivities_indices(mesh, :f2n) D = MeshFaceData([f(fnodes) for fnodes in f2n]) ∂Ω = Measure(BoundaryFaceDomain(mesh), 3) a = compute(∫(side⁻(D))∂Ω) l = compute(∫(side⁻(PhysicalFunction(x -> 1.0)))∂Ω) @test isapprox_arrays(a, l .^ 2 ./ 2; rtol = 1e-15) end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
12268
""" This function compares the values of the input function `f` on the cell nodes with the values obtained by a `CellVariable` intialized by `f` on the corresponding cell nodes. """ function test_setvalues!_with_function( mesh, meshOrder, fesType, fesDegree, fesContinuity, f, ) fs = FunctionSpace(fesType, fesDegree) isa(f, Tuple) ? size = length(f) : size = 1 fes = FESpace(fs, fesContinuity; size = size) u = CellVariable(:u, mesh, fes) set_values!(u, f) uc = var_on_centers(u) cellTypes = cells(mesh) c2n = connectivities_indices(mesh, :c2n) for i in 1:ncells(mesh) ctype = cellTypes[i] cnodes = get_nodes(mesh, c2n[i]) uᵢ = u[i, Val(:unstable)] a = [f(Bcube.mapping(ctype, cnodes, x)) for x in get_coords(shape(ctype))] b = [uᵢ(ξ) for ξ in get_coords(shape(ctype))] @test all(isapprox.(a, b, rtol = 1000eps())) end end function test_getindex_with_collocated_quad( mesh, meshOrder, fesType, fesDegree, fesContinuity, f, ) fs = FunctionSpace(fesType, fesDegree) isa(f, Tuple) ? size = length(f) : size = 2 fes = FESpace(fs, fesContinuity; size = size) u = CellVariable(:u, mesh, fes) set_values!(u, f) cellTypes = cells(mesh) c2n = connectivities_indices(mesh, :c2n) for i in 1:ncells(mesh) ct = cellTypes[i] cn = get_nodes(mesh, c2n[i]) uᵢ = u[i, Val(:unstable)] quadrule = QuadratureRule(shape(ct), get_quadrature(fs)) a = uᵢ(quadrule) b = uᵢ.(get_nodes(quadrule)) @test all(a .≈ b) end end @testset "CellVariable" begin @testset "Mean and cell center values" begin @testset "Discontinuous" begin @testset "Taylor - linear quad" begin for Ly in (1.0, 2.0, 3.0), Lx in (1.0, 2.0, 3.0) # different cell size mesh = one_cell_mesh( :quad; xmin = 0.0, xmax = Lx, ymin = 0.0, ymax = Ly, order = 1, ) degree = 1 fs1 = FunctionSpace(:Taylor, degree) fes1 = FESpace(fs1, :discontinuous; size = 1) # DG, scalar u = CellVariable(:u, mesh, fes1) for f in (x -> 10, x -> 12x[1] + 2x[2] + 4) # test for constant and linear functions set_values!(u, f) u̅ = mean_values(u, Val(degree)) uc = var_on_centers(u) @test length(u̅) === length(uc) === 1 @test u̅[1] ≈ uc[1] ≈ f([Lx / 2, Ly / 2]) end fes2 = FESpace(fs1, :discontinuous; size = 2) v = CellVariable(:v, mesh, fes2) # DG, 2-vector variable f = (x -> 3x[1] + 4x[2] + 7 * x[1] * x[2], x -> 12x[1] + 2x[2] + 4) # here, one function per variable component gradf = x -> [ 3+7 * x[2] 4+7 * x[1] 12 2 ] set_values!(v, f) v̅ = mean_values(v, Val(degree)) vc = var_on_centers(v) @test length(v̅) === 1 @test size(vc) === (1, 2) @test v̅[1] ≈ vc[1, :] ≈ [f[1]([Lx / 2, Ly / 2]), f[2]([Lx / 2, Ly / 2])] end end @testset "Lagrange - linear and quadratic quad" begin for Ly in (1.0, 2.0, 3.0), Lx in (1.0, 2.0, 3.0) # different cell size for continuity in (:discontinuous, :continuous) for meshOrder in (1, 2) mesh = one_cell_mesh( :quad; xmin = 0.0, xmax = Lx, ymin = 0.0, ymax = Ly, order = meshOrder, ) degree = meshOrder fs1 = FunctionSpace(:Lagrange, degree) fes1 = FESpace(fs1, continuity; size = 1) # DG, scalar u = CellVariable(:u, mesh, fes1) for (f, ∇f) in zip( ( x -> 10x[1] * x[2] + 4x[1] + 7x[2], x -> 12x[1] + 2x[2] + 4, ), (x -> [10 * x[2] + 4 10 * x[1] + 7], x -> [12 2]), ) # test for constant and linear functions set_values!(u, f) u̅ = mean_values(u, Val(degree)) uc = var_on_centers(u) @test length(u̅) === length(uc) === 1 @test u̅[1] ≈ uc[1] ≈ f([Lx / 2, Ly / 2]) @test u[1, Val(:unstable)]([0.0, 0.0]) ≈ f([Lx / 2, Ly / 2]) @test all( isapprox.( ∇(u)[1, Val(:unstable)]([0.0, 0.0]), ∇f([Lx / 2, Ly / 2]), ), ) end fes2 = FESpace(fs1, continuity; size = 2) v = CellVariable(:v, mesh, fes2) # DG, 2-vector variable f = ( x -> 3x[1] + 4x[2] + 7 * x[1] * x[2], x -> 12x[1] + 2x[2] + 4, ) # here, one function per variable component ∇f = x -> [ 3+7 * x[2] 4+7 * x[1] 12 2 ] set_values!(v, f) v̅ = mean_values(v, Val(degree)) vc = var_on_centers(v) @test length(v̅) === 1 @test size(vc) === (1, 2) @test v̅[1] ≈ vc[1, :] ≈ [f[1]([Lx / 2, Ly / 2]), f[2]([Lx / 2, Ly / 2])] @test all( isapprox.( ∇(v)[1, Val(:unstable)]([0.0, 0.0]), ∇f([Lx / 2, Ly / 2]), ), ) @test all( isapprox.( ∇(v)[1, Val(:unstable)]([1.0, 0.0]), ∇f([Lx, Ly / 2]), ), ) end end end end end end dict_f = Dict( 0 => x -> 6.0, #deg 0 1 => x -> 2x[1] + 4x[2] + 5, #deg 1 2 => x -> 3x[1] * x[2] + x[1]^2 + 2.5x[2] - 1.5, #deg 2 3 => x -> 3x[1]^2 * x[2] + 10x[2] + 4, ) #deg 3 dict_fesDegree = Dict( (:quad, :Lagrange) => 0:3, (:tri, :Lagrange) => 0:2, (:quad, :Taylor) => 0:1, (:tri, :Taylor) => 0:0, ) Lx = 3.0 Ly = 2.0 nx = 3 ny = 4 @testset "setvalues! with function" begin @testset "mesh type=$meshElement and order=$meshOrder" for meshElement in (:quad, :tri), meshOrder in 1:2 if meshElement == :tri # tri mesh generator with several cells is not available mesh = one_cell_mesh( meshElement; xmin = 0.0, xmax = Lx, ymin = 0.0, ymax = Ly, order = meshOrder, ) else mesh = rectangle_mesh( nx, ny; type = meshElement, xmin = 0.0, xmax = Lx, ymin = 0.0, ymax = Ly, order = meshOrder, ) end @testset "fespace: type=$fesType degree=$fesDegree $fesContinuity" for fesType in ( :Lagrange, :Taylor, ), fesDegree in dict_fesDegree[(meshElement, fesType)], fesContinuity in (:discontinuous, :continuous) (fesType == :Taylor && fesContinuity == :continuous) && continue @testset "function deg=$d" for (d, f) in dict_f d <= fesDegree && test_setvalues!_with_function( mesh, meshOrder, fesType, fesDegree, fesContinuity, f, ) end end end end @testset "Boundary dofs" begin # Note bmxam : to build this check, I sketched the rectangle # and built the dof numbering by hand. path = joinpath(tempdir, "mesh.msh") gen_rectangle_mesh(tmp_path, :quad; nx = 2, ny = 3) mesh = read_msh(path, 2) fs = FunctionSpace(:Lagrange, 1) fes = FESpace(fs, :continuous; size = 1) u = CellVariable(:u, mesh, fes) bnd_dofs = boundary_dofs(u, "East") @test bnd_dofs == [2, 4, 6] fes = FESpace(fs, :discontinuous; size = 1) u = CellVariable(:u, mesh, fes) bnd_dofs = boundary_dofs(u, "East") @test bnd_dofs == [2, 4, 6, 8] fes = FESpace(fs, :continuous; size = 2) u = CellVariable(:u, mesh, fes) bnd_dofs = boundary_dofs(u, "East") @test bnd_dofs == [2, 6, 4, 8, 10, 12] end @testset "Dof numbering checker" begin mesh = rectangle_mesh( 4, 4; type = :quad, xmin = 0.0, xmax = 6.0, ymin = 0.0, ymax = 6.0, order = 1, ) degree = 1 fs = FunctionSpace(:Lagrange, degree) fes_sca = FESpace(fs, :discontinuous; size = 1) # DG, scalar fes_vec = FESpace(fs, :discontinuous; size = 2) # DG, vectoriel u = CellVariable(:u, mesh, fes_sca) v = CellVariable(:v, mesh, fes_vec) @test Bcube.check_numbering(u; verbose = false, exit_on_error = false) == 0 @test Bcube.check_numbering(v; verbose = false, exit_on_error = false) == 0 # insert random errors u.dhl.iglob[32] = u.dhl.iglob[29] @test Bcube.check_numbering(u; verbose = false, exit_on_error = false) == 1 u.dhl.iglob[32] = u.dhl.iglob[1] @test Bcube.check_numbering(u; verbose = false, exit_on_error = false) == 1 u.dhl.iglob[14] = u.dhl.iglob[27] @test Bcube.check_numbering(u; verbose = false, exit_on_error = false) == 1 # CONTINUOUS fes_sca = FESpace(fs, :continuous; size = 1) # DG, scalar fes_vec = FESpace(fs, :continuous; size = 2) # DG, vectoriel u = CellVariable(:u, mesh, fes_sca) v = CellVariable(:v, mesh, fes_vec) @test Bcube.check_numbering(u) == 0 @test Bcube.check_numbering(v) == 0 # insert random errors u.dhl.iglob[24] = u.dhl.iglob[31] @test Bcube.check_numbering(u; verbose = false, exit_on_error = false) == 4 u.dhl.iglob[2] = u.dhl.iglob[22] @test Bcube.check_numbering(u; verbose = false, exit_on_error = false) == 6 u.dhl.iglob[20] = u.dhl.iglob[5] @test Bcube.check_numbering(u; verbose = false, exit_on_error = false) == 14 end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
13921
@testset "DofHandler" begin @testset "2D" begin @testset "Discontinuous" begin #---- Mesh with one cell mesh = one_cell_mesh(:quad) # scalar - discontinuous dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 1), 1, false) @test get_dof(dhl, 1) == collect(1:4) @test get_dof(dhl, 1, 1, 3) == 3 @test get_ndofs(dhl, 1) == 4 # two scalar variables sharing same space U_sca = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) U = MultiFESpace(U_sca, U_sca) m = get_mapping(U, 2) dhl = Bcube._get_dhl(get_fespace(U)[2]) @test m[get_dofs(U_sca, 1)] == collect(5:8) @test m[get_dof(dhl, 1, 1, 3)] == 7 @test get_ndofs(dhl, 1) == 4 # Two scalar variables, different orders U1 = TrialFESpace(FunctionSpace(:Lagrange, 2), mesh, :discontinuous) U2 = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) U = MultiFESpace(U1, U2) m1 = get_mapping(U, 1) m2 = get_mapping(U, 2) dhl1 = Bcube._get_dhl(get_fespace(U)[1]) dhl2 = Bcube._get_dhl(get_fespace(U)[2]) @test m1[get_dofs(U1, 1)] == collect(1:9) @test m2[get_dofs(U2, 1)] == collect(10:13) @test m1[get_dof(dhl1, 1, 1, 3)] == 3 @test m2[get_dof(dhl2, 1, 1, 3)] == 12 @test get_ndofs(dhl1, 1) == 9 @test get_ndofs(dhl2, 1) == 4 # One vector variable dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 1), 2, false) @test get_ndofs(dhl, 1) == 8 @test get_dof(dhl, 1, 1) == collect(1:4) @test get_dof(dhl, 1, 2) == collect(5:8) @test get_dof(dhl, 1, 1, 3) == 3 @test get_dof(dhl, 1, 2, 3) == 7 # Three variables : one scalar, one vector, one scalar U_ρ = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) U_ρu = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous; size = 3) U_ρE = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) U = MultiFESpace(U_ρ, U_ρu, U_ρE) m_ρ = get_mapping(U, 1) m_ρu = get_mapping(U, 2) m_ρE = get_mapping(U, 3) @test m_ρ[get_dofs(U_ρ, 1)] == collect(1:4) @test m_ρu[get_dofs(U_ρu, 1)] == collect(5:16) @test m_ρE[get_dofs(U_ρE, 1)] == collect(17:20) #---- Basic mesh mesh = basic_mesh() # One scalar FESpace dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 1), 1, false) @test get_dof(dhl, 1) == collect(1:4) @test get_dof(dhl, 2) == collect(5:8) @test get_dof(dhl, 3) == collect(9:11) @test max_ndofs(dhl) == 4 # Two scalar variables sharing same FESpace U_sca = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) U = MultiFESpace(U_sca, U_sca) m1 = get_mapping(U, 1) m2 = get_mapping(U, 2) @test m1[get_dofs(U_sca, 1)] == collect(1:4) @test m2[get_dofs(U_sca, 1)] == collect(5:8) @test m1[get_dofs(U_sca, 3)] == collect(17:19) @test m2[get_dofs(U_sca, 3)] == collect(20:22) # Two vars, different orders U1 = TrialFESpace(FunctionSpace(:Lagrange, 2), mesh, :discontinuous) U2 = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) U = MultiFESpace(U1, U2) m1 = get_mapping(U, 1) m2 = get_mapping(U, 2) dhl1 = Bcube._get_dhl(get_fespace(U)[1]) dhl2 = Bcube._get_dhl(get_fespace(U)[2]) @test m1[get_dofs(U1, 1)] == collect(1:9) @test m2[get_dofs(U2, 1)] == collect(10:13) @test m1[get_dofs(U1, 3)] == collect(27:32) @test m2[get_dofs(U2, 3)] == collect(33:35) @test max_ndofs(dhl1) == 9 end @testset "Continuous" begin #---- Mesh with one cell mesh = one_cell_mesh(:quad) # One scalar dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 1), 1, true) @test get_dof(dhl, 1) == collect(1:4) # Two scalar variables sharing the same space U_sca = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) U = MultiFESpace(U_sca, U_sca) m1 = get_mapping(U, 1) m2 = get_mapping(U, 2) @test m1[get_dofs(U_sca, 1)] == collect(1:4) @test m2[get_dofs(U_sca, 1)] == collect(5:8) # Two vars, different orders U1 = TrialFESpace(FunctionSpace(:Lagrange, 2), mesh, :discontinuous) U2 = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) U = MultiFESpace(U1, U2) m1 = get_mapping(U, 1) m2 = get_mapping(U, 2) dhl1 = Bcube._get_dhl(get_fespace(U)[1]) dhl2 = Bcube._get_dhl(get_fespace(U)[2]) @test m1[get_dofs(U1, 1)] == collect(1:9) @test m2[get_dofs(U2, 1)] == collect(10:13) # Lagrange multiplier space U = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh) Λᵤ = MultiplierFESpace(mesh, 1) P = MultiFESpace(U, Λᵤ) m1 = get_mapping(P, 1) m2 = get_mapping(P, 2) @test m1[get_dofs(U, 1)] == collect(1:4) @test m2[get_dofs(Λᵤ, 1)] == [5] #---- Rectangle mesh # (from corrected bug -> checked graphically, by hand!) mesh = rectangle_mesh(3, 2; type = :quad) dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 3), 1, true) @test get_dof(dhl, 1) == collect(1:16) @test get_dof(dhl, 2) == [4, 17, 18, 19, 8, 20, 21, 22, 12, 23, 24, 25, 16, 26, 27, 28] #---- Basic mesh mesh = basic_mesh() # One scalar dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 1), 1, true) @test get_dof(dhl, 1) == [1, 2, 3, 4] @test get_dof(dhl, 2) == [2, 5, 4, 6] @test get_dof(dhl, 3) == [5, 7, 6] # Two scalar variables sharing the same space U_sca = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) # this one should be elsewhere U = MultiFESpace(U_sca, U_sca) m1 = get_mapping(U, 1) m2 = get_mapping(U, 2) @test m1[get_dofs(U_sca, 1)] == [1, 2, 3, 4] @test m2[get_dofs(U_sca, 1)] == [5, 6, 7, 8] @test m1[get_dofs(U_sca, 2)] == [9, 10, 11, 12] @test m2[get_dofs(U_sca, 2)] == [13, 14, 15, 16] @test m1[get_dofs(U_sca, 3)] == [17, 18, 19] @test m2[get_dofs(U_sca, 3)] == [20, 21, 22] # Lagrange multiplier space U = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh) Λᵤ = MultiplierFESpace(mesh, 1) P = MultiFESpace(U, Λᵤ) m1 = get_mapping(P, 1) m2 = get_mapping(P, 2) @test m1[get_dofs(U, 1)] == [1, 2, 3, 4] @test m1[get_dofs(U, 2)] == [2, 6, 4, 7] @test m1[get_dofs(U, 3)] == [6, 8, 7] @test m2[get_dofs(Λᵤ, 1)] == [5] P = MultiFESpace(U, Λᵤ; arrayOfStruct = false) m1 = get_mapping(P, 1) m2 = get_mapping(P, 2) @test m1[get_dofs(U, 1)] == [1, 2, 3, 4] @test m1[get_dofs(U, 2)] == [2, 5, 4, 6] @test m1[get_dofs(U, 3)] == [5, 7, 6] @test m2[get_dofs(Λᵤ, 1)] == [8] # One scalar variable of order 2 on second order quads mesh = rectangle_mesh(3, 2; order = 2) dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 2), 1, true) @test get_dof(dhl, 1) == collect(1:9) @test get_dof(dhl, 2) == [3, 10, 11, 6, 12, 13, 9, 14, 15] # A square domain composed of four (2x2) Quad9 mesh = rectangle_mesh(3, 3; order = 2) dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 2), 1, true) @test get_dof(dhl, 1) == [1, 2, 3, 4, 5, 6, 7, 8, 9] @test get_dof(dhl, 2) == [3, 10, 11, 6, 12, 13, 9, 14, 15] @test get_dof(dhl, 3) == [7, 8, 9, 16, 17, 18, 19, 20, 21] @test get_dof(dhl, 4) == [9, 14, 15, 18, 22, 23, 21, 24, 25] # Two quads of order 1 with variable of order > 1 mesh = rectangle_mesh(3, 2) dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 2), 1, true) @test get_dof(dhl, 1) == collect(1:9) @test get_dof(dhl, 2) == [3, 10, 11, 6, 12, 13, 9, 14, 15] end end @testset "3D" begin @testset "Discontinuous" begin #---- Mesh with one cell mesh = one_cell_mesh(:cube) # One scalar space dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 1), 1, false) @test get_dof(dhl, 1) == collect(1:8) @test get_dof(dhl, 1, 1, 3) == 3 @test get_ndofs(dhl, 1) == 8 # Two scalar variables sharing same space U_sca = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) # this one should be elsewhere U = MultiFESpace(U_sca, U_sca) m = get_mapping(U, 2) dhl = Bcube._get_dhl(get_fespace(U)[2]) @test m[get_dofs(U_sca, 1)] == collect(9:16) @test m[get_dof(dhl, 1, 1, 3)] == 11 @test get_ndofs(dhl, 1) == 8 # Two scalar variables, different orders # fes_u = FESpace(FunctionSpace(:Lagrange, 2), :discontinuous) # fes_v = FESpace(FunctionSpace(:Lagrange, 1), :discontinuous) # u = CellVariable(:u, mesh, fes_u) # v = CellVariable(:v, mesh, fes_v) # sys = System((u, v)) # @test get_dof(sys, u, 1) == collect(1:9) # @test get_dof(sys, v, 1) == collect(10:13) # @test get_dof(sys, u, 1, 1, 3) == 3 # @test get_dof(sys, v, 1, 1, 3) == 12 # @test get_ndofs(get_DofHandler(u), 1) == 9 # @test get_ndofs(get_DofHandler(v), 1) == 4 # One vector variable dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 1), 2, false) @test get_ndofs(dhl, 1) == 16 @test get_dof(dhl, 1, 1) == collect(1:8) @test get_dof(dhl, 1, 2) == collect(9:16) @test get_dof(dhl, 1, 1, 3) == 3 @test get_dof(dhl, 1, 2, 3) == 11 # Three variables : one scalar, one vector, one scalar U_ρ = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) U_ρu = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous; size = 3) U_ρE = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, :discontinuous) U = MultiFESpace(U_ρ, U_ρu, U_ρE) m_ρ = get_mapping(U, 1) m_ρu = get_mapping(U, 2) m_ρE = get_mapping(U, 3) @test m_ρ[get_dofs(U_ρ, 1)] == collect(1:8) @test m_ρu[get_dofs(U_ρu, 1)] == collect(9:32) @test m_ρE[get_dofs(U_ρE, 1)] == collect(33:40) #---- Mesh with 2 cubes side by side path = joinpath(tempdir, "mesh.msh") Bcube._gen_2cubes_mesh(path) mesh = read_msh(path) dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 2), 1, false) @test get_dof(dhl, 1) == collect(1:27) @test get_dof(dhl, 2) == collect(28:54) #---- Mesh with 4 cubes (pile) path = joinpath(tempdir, "mesh.msh") Bcube._gen_cube_pile(path) mesh = read_msh(path) # One scalar FESpace dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 1), 1, false) for icell in 1:ncells(mesh) @test get_dof(dhl, icell) == collect((1 + (icell - 1) * 8):(icell * 8)) @test get_ndofs(dhl, icell) == 8 end end @testset "Continuous" begin path = joinpath(tempdir, "mesh.msh") Bcube._gen_cube_pile(path) mesh = read_msh(path) # One scalar FESpace dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 1), 1, true) c2n = connectivities_indices(mesh, :c2n) # dof index 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 # corresponding node 01 02 05 04 09 10 11 12 03 06 13 14 08 07 15 16 17 18 19 20 @test get_dof(dhl, 1) == [1, 2, 3, 4, 5, 6, 7, 8] @test get_dof(dhl, 2) == [2, 9, 4, 10, 6, 11, 8, 12] @test get_dof(dhl, 3) == [4, 10, 13, 14, 8, 12, 15, 16] @test get_dof(dhl, 4) == [6, 11, 8, 12, 17, 18, 19, 20] #---- Mesh with 2 cubes side by side path = joinpath(tempdir, "mesh.msh") Bcube._gen_2cubes_mesh(path) mesh = read_msh(path) dhl = DofHandler(mesh, FunctionSpace(:Lagrange, 2), 1, true) @test get_dof(dhl, 1) == collect(1:27) @test get_dof(dhl, 2) == [ 3, 28, 29, 6, 30, 31, 9, 32, 33, 12, 34, 35, 15, 36, 37, 18, 38, 39, 21, 40, 41, 24, 42, 43, 27, 44, 45, ] end end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
674
@testset "FEFunction" begin @testset "SingleFEFunction" begin mesh = line_mesh(3) U = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh) u = FEFunction(U, 3.0) @test all(get_dof_values(u, 2) .== [3.0, 3.0]) end @testset "MultiFEFunction" begin mesh = one_cell_mesh(:line) U1 = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh) U2 = TrialFESpace(FunctionSpace(:Lagrange, 0), mesh) U = MultiFESpace(U1, U2) vals = [1.0, 2.0, 3.0 * im] u = FEFunction(U, vals) @test all(Bcube.get_dof_type(u) .== (ComplexF64, ComplexF64)) @test all(get_dof_values(u) .== vals) end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
318
@testset "FESpace" begin mesh = one_cell_mesh(:line) U = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh, Dict("xmin" => 3.0); size = 2) @test Bcube.is_continuous(U) @test !Bcube.is_discontinuous(U) @test Bcube.get_ncomponents(U) == 2 @test Bcube.get_dirichlet_values(U)[1](0.0, 0.0) == 3.0 end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
19847
@testset "Integration" begin @testset "Line - volumic" begin # Mesh with only one line of degree 1 : [0, 1] mesh = line_mesh(2; xmin = 0.0, xmax = 1.0) # Test length of line @test all( integrate_on_ref_element(x -> 1.0, CellInfo(mesh, 1), Quadrature(Val(degree))) ≈ 1.0 for degree in 1:5 ) end @testset "Triangle - volumic" begin # Mesh with only one triangle of degree 1 : [-1, -1], [1, -1], [-1, 1] mesh = Mesh( [Node([-1.0, -1.0]), Node([1.0, -1.0]), Node([-1.0, 1.0])], [Tri3_t()], Connectivity([3], [1, 2, 3]), ) icell = 1 ctype = cells(mesh)[icell] cInfo = CellInfo(mesh, icell) # Test area of tri @test all( integrate_on_ref_element(x -> 1.0, cInfo, Quadrature(Val(degree))) ≈ 2.0 for degree in 1:5 ) # Test for P1 shape functions and products of P1 shape functions fs = FunctionSpace(:Lagrange, 1) λ = shape_functions(fs, shape(ctype)) degree = Val(2) quad = Quadrature(degree) @test integrate_on_ref_element(ReferenceFunction(ξ -> λ(ξ)[1]), cInfo, quad) ≈ 2.0 / 3.0 @test integrate_on_ref_element(ReferenceFunction(ξ -> λ(ξ)[2]), cInfo, quad) ≈ 2.0 / 3.0 @test integrate_on_ref_element(ReferenceFunction(ξ -> λ(ξ)[3]), cInfo, quad) ≈ 2.0 / 3.0 @test integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[1] * λ(ξ)[1]), cInfo, quad, ) ≈ 1.0 / 3.0 @test integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[2] * λ(ξ)[2]), cInfo, quad, ) ≈ 1.0 / 3.0 @test integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[3] * λ(ξ)[3]), cInfo, quad, ) ≈ 1.0 / 3.0 @test integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[1] * λ(ξ)[2]), cInfo, quad, ) ≈ 1.0 / 6.0 @test integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[1] * λ(ξ)[3]), cInfo, quad, ) ≈ 1.0 / 6.0 @test integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[2] * λ(ξ)[3]), cInfo, quad, ) ≈ 1.0 / 6.0 # Test for P2 shape functions and some products of P2 shape functions fs = FunctionSpace(:Lagrange, 2) λ = shape_functions(fs, shape(ctype)) _atol = 2 * eps() _rtol = 4 * eps() for degree in 2:8 # atol fixed to 1e-10 to get a pass for degree 4 quad = Quadrature(degree) @test isapprox( integrate_on_ref_element(ReferenceFunction(ξ -> λ(ξ)[1]), cInfo, quad), 0.0, atol = _atol, ) @test isapprox( integrate_on_ref_element(ReferenceFunction(ξ -> λ(ξ)[2]), cInfo, quad), 0.0, atol = _atol, ) @test isapprox( integrate_on_ref_element(ReferenceFunction(ξ -> λ(ξ)[3]), cInfo, quad), 0.0, atol = _atol, ) @test isapprox( integrate_on_ref_element(ReferenceFunction(ξ -> λ(ξ)[4]), cInfo, quad), 2.0 / 3.0, rtol = _rtol, ) @test isapprox( integrate_on_ref_element(ReferenceFunction(ξ -> λ(ξ)[5]), cInfo, quad), 2.0 / 3.0, rtol = _rtol, ) @test isapprox( integrate_on_ref_element(ReferenceFunction(ξ -> λ(ξ)[6]), cInfo, quad), 2.0 / 3.0, rtol = _rtol, ) end for degree in 4:8 quad = Quadrature(degree) @test isapprox( integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[1] * λ(ξ)[1]), cInfo, quad, ), 1.0 / 15.0, rtol = _rtol, ) @test isapprox( integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[2] * λ(ξ)[2]), cInfo, quad, ), 1.0 / 15.0, rtol = _rtol, ) @test isapprox( integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[3] * λ(ξ)[3]), cInfo, quad, ), 1.0 / 15.0, rtol = _rtol, ) @test isapprox( integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[4] * λ(ξ)[4]), cInfo, quad, ), 16.0 / 45.0, rtol = _rtol, ) @test isapprox( integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[5] * λ(ξ)[5]), cInfo, quad, ), 16.0 / 45.0, rtol = _rtol, ) @test isapprox( integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[6] * λ(ξ)[6]), cInfo, quad, ), 16.0 / 45.0, rtol = _rtol, ) @test isapprox( integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[1] * λ(ξ)[4]), cInfo, quad, ), 0.0, atol = _atol, ) @test isapprox( integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[1] * λ(ξ)[5]), cInfo, quad, ), -2.0 / 45.0, rtol = _rtol, ) @test isapprox( integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[1] * λ(ξ)[6]), cInfo, quad, ), 0.0, atol = _atol, ) end end @testset "Square - volumic" begin # Quad on basic mesh mesh = basic_mesh() cInfo = CellInfo(mesh, 2) # Test integration on quad '2' @test all( isapprox(integrate_on_ref_element(x -> 2.0, cInfo, Quadrature(degree)), 2.0) for degree in 1:13 ) @test all( isapprox( integrate_on_ref_element( PhysicalFunction(x -> 2x[1] + 3x[2]), cInfo, Quadrature(degree), ), 4.5, ) for degree in 1:13 ) # An other quad xmin, ymin = [0.0, 0.0] xmax, ymax = [1.0, 1.0] Δx = xmax - xmin Δy = ymax - ymin mesh = one_cell_mesh(:quad; xmin, xmax, ymin, ymax) cInfo = CellInfo(mesh, 1) ctype = celltype(cInfo) cnodes = nodes(cInfo) fs = FunctionSpace(:Lagrange, 1) λ = shape_functions(fs, shape(ctype)) ∇λ = ξ -> ∂λξ_∂x(fs, Val(1), ctype, cnodes, ξ) degree = Val(2) quad = Quadrature(degree) @test integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[1] * λ(ξ)[1]), cInfo, quad, ) ≈ Δx * Δy / 9 @test integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[1] * λ(ξ)[2]), cInfo, quad, ) ≈ Δx * Δy / 18 @test integrate_on_ref_element( ReferenceFunction(ξ -> λ(ξ)[2] * λ(ξ)[2]), cInfo, quad, ) ≈ Δx * Δy / 9 @test integrate_on_ref_element( ReferenceFunction(ξ -> ∇λ(ξ)[1, :] ⋅ ∇λ(ξ)[1, :]), cInfo, quad, ) ≈ (Δx^2 + Δy^2) / (3 * Δx * Δy) end @testset "Line (not curved) - surfacic" begin Δx = 666.0 Δy = 314.0 mesh = basic_mesh(; coef_x = Δx, coef_y = Δy) c2f = connectivities_indices(mesh, :c2f) f2n = connectivities_indices(mesh, :f2n) g(x) = 1.0 for idegree in 1:3 degree = Val(idegree) quad = Quadrature(degree) for icell in (1, 2) finfo_1, finfo_2, finfo_3, finfo_4 = map(Base.Fix1(FaceInfo, mesh), c2f[icell]) @test integrate_on_ref_element(g, finfo_1, quad) ≈ Δx @test integrate_on_ref_element(g, finfo_2, quad) ≈ Δy @test integrate_on_ref_element(g, finfo_3, quad) ≈ Δx @test integrate_on_ref_element(g, finfo_4, quad) ≈ Δy end icell = 3 finfo_1, finfo_2, finfo_3 = map(Base.Fix1(FaceInfo, mesh), c2f[icell]) @test integrate_on_ref_element(g, finfo_1, quad) ≈ Δx @test integrate_on_ref_element(g, finfo_2, quad) ≈ norm([Δx, Δy]) @test integrate_on_ref_element(g, finfo_3, quad) ≈ Δy end end @testset "Line P2 - surfacic" begin # Build P2-Quad with edges defined by y = alpha (1-x)(1+x) xmin = -1.0 xmax = 1.0 ymin = -1.0 ymax = 1.0 alpha = 1.0 cnodes = [ Node([xmin, ymin]), Node([xmax, ymin]), Node([xmax, ymax]), Node([xmin, ymax]), Node([(xmax + xmin) / 2, ymin - alpha]), Node([xmax + alpha, (ymin + ymax) / 2]), Node([(xmin + xmax) / 2, ymax + alpha]), Node([xmin - alpha, (ymin + ymax) / 2]), Node([(xmin + xmax) / 2, (ymin + ymax) / 2]), ] ctype = Quad9_t() quad_mesh = Mesh(cnodes, [ctype], Connectivity([9], collect(1:9))) # Build P2 line (equivalent to one of the edge above) lnodes = [Node([0.0, 0.0]), Node([0.0, xmax - xmin]), Node([alpha, (xmax - xmin) / 2])] line_mesh = Mesh(lnodes, [Bar3_t()], Connectivity([3], collect(1:3))) # Compute analytic arc length b = xmax - xmin a = alpha L = sqrt(b^2 + 16 * a^2) / 2 + b^2 / (8a) * log((4a + sqrt(b^2 + 16 * a^2)) / b) # Test integration accuracy degquad = Val(200) quad = Quadrature(degquad) @test integrate_on_ref_element(x -> 1, CellInfo(line_mesh, 1), quad) ≈ L @test integrate_on_ref_element(x -> 1, FaceInfo(quad_mesh, 1), quad) ≈ L end @testset "Sphere" begin path = joinpath(tempdir, "mesh.msh") Bcube.gen_sphere_mesh(path; radius = 1.0) mesh = read_msh(path) # Radius = 1 => area = 4\pi c2n = connectivities_indices(mesh, :c2n) S = sum(1:ncells(mesh)) do icell cInfo = CellInfo(mesh, icell) integrate_on_ref_element(ξ -> 1.0, cInfo, Quadrature(1)) end @test isapprox(S, 4π; atol = 1e-1) end @testset "Line_boundary" begin mesh = one_cell_mesh(:line) finfo_1 = FaceInfo(mesh, 1) finfo_2 = FaceInfo(mesh, 2) g = PhysicalFunction(x -> 2.5) @test integrate_on_ref_element(g, finfo_1, Quadrature(1)) ≈ 2.5 @test integrate_on_ref_element(g, finfo_2, Quadrature(1)) ≈ 2.5 g = PhysicalFunction(x -> x[1]) # this is x -> x but since all nodes are in R^n, we need to select the component (as for triangles below) @test integrate_on_ref_element(g, finfo_1, Quadrature(2)) ≈ -1.0 @test integrate_on_ref_element(g, finfo_2, Quadrature(2)) ≈ 1.0 end @testset "Triangle_boundary" begin mesh = one_cell_mesh(:tri; xmin = 0.0, ymin = 0.0) finfo_1 = FaceInfo(mesh, 1) finfo_2 = FaceInfo(mesh, 2) finfo_3 = FaceInfo(mesh, 3) # Test for constant g = PhysicalFunction(x -> 2.5) @test integrate_on_ref_element(g, finfo_1, Quadrature(2)) ≈ 2.5 @test integrate_on_ref_element(g, finfo_2, Quadrature(2)) ≈ 2.5 * √(2.0) @test integrate_on_ref_element(g, finfo_3, Quadrature(2)) ≈ 2.5 # Test for linear function g = PhysicalFunction(x -> x[1] + x[2]) @test integrate_on_ref_element(g, finfo_1, Quadrature(2)) ≈ 0.5 @test integrate_on_ref_element(g, finfo_2, Quadrature(2)) ≈ √(2.0) @test integrate_on_ref_element(g, finfo_3, Quadrature(2)) ≈ 0.5 end @testset "TriangleP1_boundary_divergence_free" begin # Mesh with only one triangle of degree 1 : [1.0, 0.5], [3.5, 1.0], [2.0, 2.0] mesh = Mesh( [Node([1.0, 0.5]), Node([3.5, 1.0]), Node([2.0, 2.0])], [Tri3_t()], Connectivity([3], [1, 2, 3]); buildboundaryfaces = true, bc_names = Dict(1 => "boundary"), bc_nodes = Dict(1 => [1, 2, 3]), ) # Test for divergence free vector field u = x -> [x[1], -x[2]] u = PhysicalFunction(u) Γ = BoundaryFaceDomain(mesh, "boundary") dΓ = Measure(Γ, 2) nΓ = get_face_normals(dΓ) val = sum(compute(∫(side_n(u) ⋅ side_n(nΓ))dΓ)) @test isapprox(val, 0.0, atol = 1e-15) end @testset "QuadP2_boundary_divergence_free" begin # TODO : use `one_cell_mesh` from `mesh_generator.jl` # Mesh with only one quad of degree 2 mesh = Mesh( [ Node([1.0, 1.0]), Node([4.0, 1.0]), Node([4.0, 3.0]), Node([1.0, 3.0]), Node([2.5, 0.5]), Node([4.5, 2.0]), Node([2.5, 3.5]), Node([0.5, 2.0]), Node([2.5, 2.0]), ], [Quad9_t()], Connectivity([9], [1, 2, 3, 4, 5, 6, 7, 8, 9]); buildboundaryfaces = true, bc_names = Dict(1 => "boundary"), bc_nodes = Dict(1 => [1, 2, 3, 4, 5, 6, 7, 8, 9]), ) # Test for divergence free vector field u = x -> [x[1], -x[2]] u = PhysicalFunction(u) Γ = BoundaryFaceDomain(mesh, "boundary") dΓ = Measure(Γ, 2) nΓ = get_face_normals(dΓ) val = sum(compute(∫(side_n(u) ⋅ side_n(nΓ))dΓ)) @test isapprox(val, 0.0, atol = 1e-14) end @testset "QuadP2_boundary_divergence_free_sincos" begin # TODO : use `one_cell_mesh` from `mesh_generator.jl` # Mesh with only one quad of degree 2 mesh = Mesh( [ Node([0.0, 0.0]), Node([1.5, 0.0]), Node([1.5, 1.5]), Node([0.0, 1.5]), Node([0.75, -0.25]), Node([1.75, 0.75]), Node([0.75, 1.75]), Node([-0.25, 0.75]), Node([0.75, 0.75]), ], [Quad9_t()], Connectivity([9], [1, 2, 3, 4, 5, 6, 7, 8, 9]); buildboundaryfaces = true, bc_names = Dict(1 => "boundary"), bc_nodes = Dict(1 => [1, 2, 3, 4, 5, 6, 7, 8, 9]), ) # Test for divergence free vector field u = x -> [ -2.0 * sin(π * x[1]) * sin(π * x[1]) * sin(π * x[2]) * cos(π * x[2]), 2.0 * sin(π * x[2]) * sin(π * x[2]) * sin(π * x[1]) * cos(π * x[1]), ] u = PhysicalFunction(u) Γ = BoundaryFaceDomain(mesh, "boundary") dΓ = Measure(Γ, 2) nΓ = get_face_normals(dΓ) val = sum(compute(∫(side_n(u) ⋅ side_n(nΓ))dΓ)) @test isapprox(val, 0.0, atol = 1e-15) end @testset "PhysicalFunction" begin mesh = translate(one_cell_mesh(:line), [1.0]) dΩ = Measure(CellDomain(mesh), 2) g = PhysicalFunction(x -> 2 * x[1]) b = compute(∫(g)dΩ) @test b[1] == 4.0 end @testset "Lagrange cube" begin mesh = scale(translate(one_cell_mesh(:cube), [1.0, 1.0, 2.0]), 2.0) cInfo = CellInfo(mesh, 1) @test integrate_on_ref_element(x -> 1, cInfo, Quadrature(1)) == 64 mesh = one_cell_mesh(:cube) q = Quadrature(1) f(x) = 1 ξηζ = SA[0.0, 0.0, 0.0] I3 = SA[1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0] for _ in 1:10 s = 10 * rand() m = translate(mesh, rand(3)) m = scale(m, s) cInfo = CellInfo(m, 1) ctype = celltype(cInfo) cnodes = nodes(cInfo) @test isapprox_arrays( Bcube.mapping_jacobian(ctype, cnodes, ξηζ), s .* I3; rtol = 1e-14, ) @test isapprox(integrate_on_ref_element(f, cInfo, q), 8 * s^3) end end @testset "Lagrange tetra" begin # One mesh cell mesh = one_cell_mesh( :tetra; xmin = 1.0, xmax = 3.0, ymin = 1.0, ymax = 4.0, zmin = 1.0, zmax = 5.0, ) c2n = connectivities_indices(mesh, :c2n) cInfo = CellInfo(mesh, 1) @test integrate_on_ref_element(x -> 1, cInfo, Quadrature(1)) ≈ 4 dΩ = Measure(CellDomain(mesh), 2) g = PhysicalFunction(x -> 1) b = compute(∫(g)dΩ) @test b[1] ≈ 4 gref = ReferenceFunction(x -> 1) b = compute(∫(gref)dΩ) @test b[1] ≈ 4 lx = 2.0 ly = 3.0 lz = 4.0 mesh = one_cell_mesh( :tetra; xmin = 0.0, xmax = lx, ymin = 0.0, ymax = ly, zmin = 0.0, zmax = lz, ) e14 = SA[0, 0, lz] e13 = SA[0, ly, 0] e12 = SA[lx, 0, 0] e24 = SA[-lx, 0, lz] e23 = SA[-lx, ly, 0] s(a, b) = 0.5 * norm(cross(a, b)) surface_ref = (s(-e12, e23), s(-e12, e24), s(e24, e23), s(e13, e14)) for i in 1:4 dΓ = Measure(BoundaryFaceDomain(mesh, "F$i"), 1) b = compute(∫(side⁻(g))dΓ) I, = findnz(b) @test b[I[1]] ≈ surface_ref[i] end end @testset "Lagrange prism" begin # One mesh cell mesh = one_cell_mesh( :penta; xmin = 1.0, xmax = 2.0, ymin = 1.0, ymax = 2.0, zmin = 1.0, zmax = 2.5, ) c2n = connectivities_indices(mesh, :c2n) cInfo = CellInfo(mesh, 1) @test integrate_on_ref_element(x -> 1, cInfo, Quadrature(1)) == 0.75 dΩ = Measure(CellDomain(mesh), 2) g = PhysicalFunction(x -> 1) b = compute(∫(g)dΩ) @test b[1] ≈ 0.75 # Whole cylinder : build a cylinder of radius 1 and length 1, and compute its volume path = joinpath(tempdir, "mesh.msh") gen_cylinder_mesh(path, 1.0, 10) mesh = read_msh(path) dΩ = Measure(CellDomain(mesh), 2) g = PhysicalFunction(x -> 1) b = compute(∫(g)dΩ) @test sum(b) ≈ 3.1365484905459 end @testset "Lagrange pyramid" begin # One mesh cell. Volume is base_area * height / 3 mesh = one_cell_mesh( :pyra; xmin = 1.0, xmax = 2.0, ymin = 1.0, ymax = 2.0, zmin = 1.0, zmax = 2.5, ) c2n = connectivities_indices(mesh, :c2n) cInfo = CellInfo(mesh, 1) for d in 1:5 @test integrate_on_ref_element(x -> 1, cInfo, Quadrature(d)) ≈ 0.5 end dΩ = Measure(CellDomain(mesh), 2) g = PhysicalFunction(x -> 1) b = compute(∫(g)dΩ) @test b[1] ≈ 0.5 end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
9920
function test_CellPoint(cellinfo, x_ref, x_phys) p_ref = CellPoint(x_ref, cellinfo, ReferenceDomain()) @test change_domain(p_ref, ReferenceDomain()) == p_ref p_phys = change_domain(p_ref, Bcube.PhysicalDomain()) @test p_phys == CellPoint(x_phys, cellinfo, Bcube.PhysicalDomain()) @test change_domain(p_phys, Bcube.PhysicalDomain()) == p_phys p_ref_bis = change_domain(p_phys, ReferenceDomain()) @test p_ref_bis == p_ref nothing end @testset "CellFunction" begin lx, ly = 20.0, 10.0 mesh = one_cell_mesh(:quad; xmin = 0.0, xmax = lx, ymin = 0.0, ymax = ly) x = [lx / 2, ly / 2] cellinfo = CellInfo(mesh, 1) x1_ref = SA[0.0, 0.0] x1_phys = SA[lx / 2, ly / 2] x2_ref = SA[-3 / 4, 1.0] x2_phys = SA[lx / 8, ly] @testset "CellPoint" begin @testset "One point" begin test_CellPoint(cellinfo, x1_ref, x1_phys) test_CellPoint(cellinfo, x2_ref, x2_phys) end @testset "Tuple of points" begin test_CellPoint(cellinfo, (x1_ref, x2_ref), (x1_phys, x2_phys)) end @testset "Vector of points" begin test_CellPoint(cellinfo, SA[x1_ref, x2_ref], SA[x1_phys, x2_phys]) end end @testset "PhysicalFunction" begin a = CellPoint(SA[x1_ref, x2_ref], cellinfo, ReferenceDomain()) b = CellPoint(SA[x1_phys, x2_phys], cellinfo, Bcube.PhysicalDomain()) _f = x -> x[1] + x[2] f = PhysicalFunction(_f) @test f(a) == _f.(SA[x1_phys, x2_phys]) @test f(b) == _f.(SA[x1_phys, x2_phys]) a = CellPoint((x1_ref, x2_ref), cellinfo, ReferenceDomain()) b = CellPoint((x1_phys, x2_phys), cellinfo, Bcube.PhysicalDomain()) @test f(a) == _f.((x1_phys, x2_phys)) @test f(b) == _f.((x1_phys, x2_phys)) end @testset "CellFunction" begin a = CellPoint((x1_ref, x2_ref), cellinfo, ReferenceDomain()) b = CellPoint((x1_phys, x2_phys), cellinfo, Bcube.PhysicalDomain()) _f = x -> x[1] + x[2] λref = Bcube.CellFunction(_f, ReferenceDomain(), Val(1)) @test λref(a) == _f.((x1_ref, x2_ref)) λphys = Bcube.CellFunction(_f, Bcube.PhysicalDomain(), Val(1)) @test λphys(a) == _f.((x1_phys, x2_phys)) end end @testset "CoplanarRotation" begin @testset "Topodim = 1" begin cross_2D(a, b) = a[1] * b[2] - a[2] * b[1] #--- 1 A = Node([0, 0]) B = Node([1, 1]) C = Node([2, 0]) _nodes = [A, B, C] ctypes = [Bar2_t(), Bar2_t()] cell2nodes = [1, 2, 2, 3] cell2nnodes = [2, 2] mesh = Mesh(_nodes, ctypes, Connectivity(cell2nnodes, cell2nodes)) fInfo = FaceInfo(mesh, 2) fPoint = Bcube.FacePoint([0.0], fInfo, ReferenceDomain()) R = Bcube.CoplanarRotation() _R = Bcube.materialize(side_n(R), fPoint) u1 = normalize(get_coords(B) - get_coords(A)) v2 = normalize(get_coords(C) - get_coords(B)) * 2 v2_in_1 = _R * v2 @test abs(cross_2D(u1, v2_in_1)) < 1e-15 @test norm(v2_in_1) ≈ norm(v2) _R = Bcube.materialize(side_p(R), fPoint) u2 = normalize(get_coords(C) - get_coords(B)) v1 = normalize(get_coords(B) - get_coords(A)) * 2 v1_in_2 = _R * v1 @test abs(cross_2D(u2, v1_in_2)) < 1e-15 @test norm(v1_in_2) ≈ norm(v1) #--- 2 A = Node([0, 0]) B = Node([1, 1]) C = Node([2, 1]) _nodes = [A, B, C] ctypes = [Bar2_t(), Bar2_t()] cell2nodes = [1, 2, 2, 3] cell2nnodes = [2, 2] mesh = Mesh(_nodes, ctypes, Connectivity(cell2nnodes, cell2nodes)) fInfo = FaceInfo(mesh, 2) fPoint = Bcube.FacePoint([0.0], fInfo, ReferenceDomain()) R = Bcube.CoplanarRotation() _R = Bcube.materialize(side_n(R), fPoint) u1 = normalize(get_coords(B) - get_coords(A)) v2 = normalize(get_coords(C) - get_coords(B)) * 2 v2_in_1 = _R * v2 @test abs(cross_2D(u1, v2_in_1)) < 1e-15 @test norm(v2_in_1) ≈ norm(v2) _R = Bcube.materialize(side_p(R), fPoint) u2 = normalize(get_coords(C) - get_coords(B)) v1 = normalize(get_coords(B) - get_coords(A)) * 2 v1_in_2 = _R * v1 @test abs(cross_2D(u2, v1_in_2)) < 1e-15 @test norm(v1_in_2) ≈ norm(v1) #--- 3 A = Node([0, 0]) B = Node([1, 1]) C = Node([1, 2]) _nodes = [A, B, C] ctypes = [Bar2_t(), Bar2_t()] cell2nodes = [1, 2, 2, 3] cell2nnodes = [2, 2] mesh = Mesh(_nodes, ctypes, Connectivity(cell2nnodes, cell2nodes)) fInfo = FaceInfo(mesh, 2) fPoint = Bcube.FacePoint([0.0], fInfo, ReferenceDomain()) R = Bcube.CoplanarRotation() _R = Bcube.materialize(side_n(R), fPoint) u1 = normalize(get_coords(B) - get_coords(A)) v2 = -normalize(get_coords(C) - get_coords(B)) * 2 v2_in_1 = _R * v2 @test abs(cross_2D(u1, v2_in_1)) < 1e-15 @test norm(v2_in_1) ≈ norm(v2) _R = Bcube.materialize(side_p(R), fPoint) u2 = normalize(get_coords(C) - get_coords(B)) v1 = -normalize(get_coords(B) - get_coords(A)) * 2 v1_in_2 = _R * v1 @test abs(cross_2D(u2, v1_in_2)) < 1e-15 @test norm(v1_in_2) ≈ norm(v1) #--- 4 (full planar) A = Node([0, 1]) B = Node([1, 1]) C = Node([2, 1]) _nodes = [A, B, C] ctypes = [Bar2_t(), Bar2_t()] cell2nodes = [1, 2, 2, 3] cell2nnodes = [2, 2] mesh = Mesh(_nodes, ctypes, Connectivity(cell2nnodes, cell2nodes)) fInfo = FaceInfo(mesh, 2) fPoint = Bcube.FacePoint([0.0], fInfo, ReferenceDomain()) R = Bcube.CoplanarRotation() _R = Bcube.materialize(side_n(R), fPoint) u1 = normalize(get_coords(B) - get_coords(A)) v2 = -normalize(get_coords(C) - get_coords(B)) * 2 v2_in_1 = _R * v2 @test abs(cross_2D(u1, v2_in_1)) < 1e-15 @test norm(v2_in_1) ≈ norm(v2) _R = Bcube.materialize(side_p(R), fPoint) u2 = normalize(get_coords(C) - get_coords(B)) v1 = -normalize(get_coords(B) - get_coords(A)) * 2 v1_in_2 = _R * v1 @test abs(cross_2D(u2, v1_in_2)) < 1e-15 @test norm(v1_in_2) ≈ norm(v1) end @testset "Topodim = 2" begin #--- 1 A = Node([0, 0, 0]) B = Node([1, 0, 0]) C = Node([1, 1, 0]) D = Node([0, 1, 0]) E = Node([3, 0, 2]) F = Node([3, 1, 2]) _nodes = [A, B, C, D, E, F] ctypes = [Quad4_t(), Quad4_t()] cell2nodes = [1, 2, 3, 4, 2, 5, 6, 3] cell2nnodes = [4, 4] mesh = Mesh(_nodes, ctypes, Connectivity(cell2nnodes, cell2nodes)) fInfo = FaceInfo(mesh, 2) # 2 is the good one, cf `Bcube.get_nodes_index(fInfo)` fPoint = Bcube.FacePoint([0.0, 0.0], fInfo, ReferenceDomain()) cInfo_n = Bcube.get_cellinfo_n(fInfo) cnodes_n = Bcube.nodes(cInfo_n) ctype_n = Bcube.celltype(cInfo_n) ξ_n = get_coords(side_n(fPoint)) cInfo_p = Bcube.get_cellinfo_p(fInfo) cnodes_p = Bcube.nodes(cInfo_p) ctype_p = Bcube.celltype(cInfo_p) ξ_p = get_coords(side_p(fPoint)) R = Bcube.CoplanarRotation() _R = Bcube.materialize(side_n(R), fPoint) v2 = normalize(get_coords(F) - get_coords(E)) * 2 u = normalize(get_coords(C) - get_coords(B)) v2_in_1 = _R * v2 ν1 = Bcube.cell_normal(ctype_n, cnodes_n, ξ_n) @test v2 ⋅ u ≈ v2_in_1 ⋅ u @test abs(ν1 ⋅ v2_in_1) < 1e-16 _R = Bcube.materialize(side_p(R), fPoint) v1 = normalize(get_coords(D) - get_coords(B)) * 2 u = normalize(get_coords(C) - get_coords(B)) v1_in_2 = _R * v1 ν2 = Bcube.cell_normal(ctype_p, cnodes_p, ξ_p) @test v1 ⋅ u ≈ v1_in_2 ⋅ u @test abs(ν2 ⋅ v1_in_2) < 1e-16 #--- 2 A = Node([0.0, 0.0, 0.0]) B = Node([1.0, 0.0, 0.0]) C = Node([1.0, 1.0, 0.0]) D = Node([0.0, 1.0, 0.0]) E = Node([3.0, 0.0, 2.0]) F = Node([3.0, 1.0, 2.0]) _nodes = [A, B, C, D, E, F] ctypes = [Quad4_t(), Quad4_t()] cell2nodes = [1, 2, 3, 4, 2, 5, 6, 3] cell2nnodes = [4, 4] mesh = Mesh(_nodes, ctypes, Connectivity(cell2nnodes, cell2nodes)) axis = [1, 2, 3] θ = π / 3 rot = ( cos(θ) * I + sin(θ) * [0 (-axis[3]) axis[2]; axis[3] 0 (-axis[1]); -axis[2] axis[1] 0] + (1 - cos(θ)) * (axis ⊗ axis) ) transform!(mesh, x -> rot * x) fInfo = FaceInfo(mesh, 2) # 2 is the good one, cf `Bcube.get_nodes_index(fInfo)` fPoint = Bcube.FacePoint([0.0, 0.0], fInfo, ReferenceDomain()) cInfo_n = Bcube.get_cellinfo_n(fInfo) cnodes_n = Bcube.nodes(cInfo_n) ctype_n = Bcube.celltype(cInfo_n) ξ_n = get_coords(side_n(fPoint)) cInfo_p = Bcube.get_cellinfo_p(fInfo) cnodes_p = Bcube.nodes(cInfo_p) ctype_p = Bcube.celltype(cInfo_p) ξ_p = get_coords(side_p(fPoint)) R = Bcube.CoplanarRotation() _R = Bcube.materialize(side_n(R), fPoint) v2 = rot * normalize(get_coords(F) - get_coords(E)) * 2 u = rot * normalize(get_coords(C) - get_coords(B)) v2_in_1 = _R * v2 ν1 = Bcube.cell_normal(ctype_n, cnodes_n, ξ_n) @test v2 ⋅ u ≈ v2_in_1 ⋅ u @test abs(ν1 ⋅ v2_in_1) < 2e-15 _R = Bcube.materialize(side_p(R), fPoint) v1 = rot * normalize(get_coords(D) - get_coords(B)) * 2 u = rot * normalize(get_coords(C) - get_coords(B)) v1_in_2 = _R * v1 ν2 = Bcube.cell_normal(ctype_p, cnodes_p, ξ_p) @test v1 ⋅ u ≈ v1_in_2 ⋅ u @test abs(ν2 ⋅ v1_in_2) < 1e-16 end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
11928
Σ = sum """ test_lagrange_shape_function(shape, degree) Test if the lagrange shape functions are zeros on all nodes except on "their" corresponding node. """ function test_lagrange_shape_function(shape, degree) @testset "Degree=$degree" begin fs = FunctionSpace(:Lagrange, degree) expected = zeros(get_ndofs(fs, shape)) for (i, ξ) in enumerate(get_coords(fs, shape)) expected .= 0.0 expected[i] = 1.0 result = shape_functions(fs, shape, ξ) !all(isapprox.(result, expected, atol = 5eps())) && (@show degree, result, expected) @test all(isapprox.(result, expected, atol = 5eps())) end if typeof(shape) ∈ (Line, Square, Cube) # `QuadratureLobatto` is only available for `Line`, `Square`, `Cube` for now quad = QuadratureRule(shape, Quadrature(QuadratureLobatto(), Val(2))) ξquad = get_nodes(quad) λref = [shape_functions(fs, shape, ξ) for ξ in ξquad] λtest = shape_functions(fs, quad) @test all(map(≈, λtest, λref)) ∇λref = [∂λξ_∂ξ(fs, shape, ξ) for ξ in ξquad] ∇λtest = ∂λξ_∂ξ(fs, quad) @test all(map(≈, ∇λtest, ∇λref)) @test isa(Bcube.is_collocated(fs, quad), Bcube.IsNotCollocatedStyle) if degree > 0 @test isa( Bcube.is_collocated( fs, QuadratureRule(shape, Quadrature(QuadratureUniform(), Val(degree))), ), Bcube.IsCollocatedStyle, ) end end end end @testset "Lagrange" begin @testset "Line" begin shape = Line() @test get_coords(FunctionSpace(:Lagrange, 0), shape) == (SA[0.0],) @test get_coords(FunctionSpace(:Lagrange, 1), shape) == (SA[-1.0], SA[1.0]) @test get_coords(FunctionSpace(:Lagrange, 2), shape) == (SA[-1.0], SA[0.0], SA[1.0]) for deg in 0:2 test_lagrange_shape_function(shape, deg) end fs = FunctionSpace(:Lagrange, 0) λ = shape_functions(fs, shape) ∇λ = ∂λξ_∂ξ(fs, shape) @test λ(π)[1] ≈ 1.0 @test ∇λ(π)[1] ≈ 0.0 λ = Bcube.shape_functions_vec(fs, Val(1), shape, [0.0]) @test λ == [1.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape) @test λ[1]([0.0]) == 1.0 λ = Bcube.shape_functions_vec(fs, Val(2), shape) @test λ[1]([0.0]) == [1.0, 0.0] @test λ[2]([0.0]) == [0.0, 1.0] fs = FunctionSpace(:Lagrange, 1) λ = shape_functions(fs, shape) ∇λ = ∂λξ_∂ξ(fs, shape) @test λ(-1) ≈ [1.0, 0.0] @test λ(1) ≈ [0.0, 1.0] @test Σ(λ(π)) ≈ 1.0 @test ∇λ(π) ≈ [-1.0 / 2.0, 1.0 / 2.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape, [0.0]) @test λ == [0.5, 0.5] λ = Bcube.shape_functions_vec(fs, Val(1), shape) @test λ[1]([0.0]) == 0.5 @test λ[2]([0.0]) == 0.5 fs = FunctionSpace(:Lagrange, 2) λ = shape_functions(fs, shape) ∇λ = ∂λξ_∂ξ(fs, shape) @test λ(-1) ≈ [1.0, 0.0, 0.0] @test λ(0) ≈ [0.0, 1.0, 0.0] @test λ(1) ≈ [0.0, 0.0, 1.0] @test Σ(λ(π)) ≈ 1.0 @test ∇λ(0.0) ≈ [-1.0 / 2.0, 0.0, 1.0 / 2.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape, [0.0]) @test λ == [0.0, 1.0, 0.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape) @test λ[1]([0.0]) == 0.0 @test λ[2]([0.0]) == 1.0 @test λ[3]([0.0]) == 0.0 # Tests for gradients of shape functions expressed on local element # TODO: the part below should be moved to test_ref2loc mesh = Mesh([Node([0.0]), Node([1.0])], [Bar2_t()], Connectivity([2], [1, 2])) cellTypes = cells(mesh) ctype = cellTypes[1] c2n = connectivities_indices(mesh, :c2n) cnodes = get_nodes(mesh, c2n[1]) Finv = Bcube.mapping_inv(ctype, cnodes) fs = FunctionSpace(:Lagrange, 1) ∇λ = x -> ∂λξ_∂x(fs, Val(1), ctype, cnodes, Finv(x)) @test ∇λ(0.5) ≈ reshape([-1.0, 1.0], (2, 1)) end @testset "Triangle" begin shape = Triangle() @test get_coords(FunctionSpace(:Lagrange, 0), shape) ≈ (SA[1.0 / 3, 1.0 / 3],) @test get_coords(FunctionSpace(:Lagrange, 1), shape) == (SA[0.0, 0.0], SA[1.0, 0.0], SA[0.0, 1.0]) @test get_coords(FunctionSpace(:Lagrange, 2), shape) == ( SA[0.0, 0.0], SA[1.0, 0.0], SA[0.0, 1.0], SA[0.5, 0.0], SA[0.5, 0.5], SA[0.0, 0.5], ) @test get_coords(FunctionSpace(:Lagrange, 3), shape) == ( SA[0.0, 0.0], SA[1.0, 0.0], SA[0.0, 1.0], SA[1 / 3, 0.0], SA[2 / 3, 0.0], SA[2 / 3, 1 / 3], SA[1 / 3, 2 / 3], SA[0.0, 2 / 3], SA[0.0, 1 / 3], SA[1 / 3, 1 / 3], ) fs = FunctionSpace(:Lagrange, 0) λ = x -> shape_functions(fs, shape, x) ∇λ = x -> ∂λξ_∂ξ(fs, shape, x) @test λ([π, ℯ])[1] ≈ 1.0 @test ∇λ([π, ℯ]) ≈ [0.0 0.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape, [1.0 / 3.0, 1.0 / 3.0]) @test λ == [1.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape) @test λ[1]([1.0 / 3.0, 1.0 / 3.0]) == 1.0 fs = FunctionSpace(:Lagrange, 1) λ = x -> shape_functions(fs, shape, x) ∇λ = x -> ∂λξ_∂ξ(fs, shape, x) @test λ([0, 0]) ≈ [1.0, 0.0, 0.0] @test λ([1, 0]) ≈ [0.0, 1.0, 0.0] @test λ([0, 1]) ≈ [0.0, 0.0, 1.0] @test Σ(λ([π, ℯ])) ≈ 1.0 @test ∇λ([π, ℯ]) ≈ [ -1.0 -1.0 1.0 0.0 0.0 1.0 ] λ = Bcube.shape_functions_vec(fs, Val(1), shape, [1.0 / 3.0, 1.0 / 3.0]) @test λ ≈ [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape) @test λ[1]([1.0 / 3.0, 1.0 / 3.0]) ≈ 1.0 / 3.0 @test λ[2]([1.0 / 3.0, 1.0 / 3.0]) ≈ 1.0 / 3.0 @test λ[3]([1.0 / 3.0, 1.0 / 3.0]) ≈ 1.0 / 3.0 fs = FunctionSpace(:Lagrange, 2) λ = x -> shape_functions(fs, shape, x) ∇λ = x -> ∂λξ_∂ξ(fs, shape, x) @test λ([0, 0])[1:3] ≈ [1.0, 0.0, 0.0] @test λ([1, 0])[1:3] ≈ [0.0, 1.0, 0.0] @test λ([0, 1])[1:3] ≈ [0.0, 0.0, 1.0] @test Σ(λ([π, ℯ])) ≈ 1.0 @test ∇λ([0, 0]) ≈ [ -3.0 -3.0 -1.0 0.0 0.0 -1.0 4.0 0.0 0.0 0.0 0.0 4.0 ] λ = Bcube.shape_functions_vec(fs, Val(1), shape, [1.0 / 3.0, 1.0 / 3]) @test λ ≈ [ -0.11111111111111112, -0.11111111111111112, -0.11111111111111112, 0.44444444444444453, 0.4444444444444444, 0.44444444444444453, ] λ = Bcube.shape_functions_vec(fs, Val(1), shape) @test λ[1]([1.0 / 3.0, 1.0 / 3.0]) ≈ -0.111111111111111 @test λ[2]([1.0 / 3.0, 1.0 / 3.0]) ≈ -0.111111111111111 @test λ[3]([1.0 / 3.0, 1.0 / 3.0]) ≈ -0.111111111111111 @test λ[4]([1.0 / 3.0, 1.0 / 3.0]) ≈ 0.444444444444444 @test λ[5]([1.0 / 3.0, 1.0 / 3.0]) ≈ 0.444444444444444 @test λ[6]([1.0 / 3.0, 1.0 / 3.0]) ≈ 0.444444444444444 for deg in 0:3 test_lagrange_shape_function(shape, deg) end # Tests for gradients of shape functions expressed on local element # Mesh with only one triangle of order 1 : S1,S2,S3 S1 = [-1.0, -1.0] S2 = [1.0, -2.0] S3 = [-1.0, 1.0] mesh = Mesh([Node(S1), Node(S2), Node(S3)], [Tri3_t()], Connectivity([3], [1, 2, 3])) cellTypes = cells(mesh) ctype = cellTypes[1] c2n = connectivities_indices(mesh, :c2n) n = get_nodes(mesh, c2n[1]) vol = 0.5 * abs((S2[1] - S1[1]) * (S3[2] - S1[2]) - (S3[1] - S1[1]) * (S2[2] - S1[1])) fs = FunctionSpace(:Lagrange, 1) ∇λ = x -> ∂λξ_∂x(fs, Val(1), ctype, n, x) @test ∇λ([0, 0])[1, :] ≈ (0.5 / vol) * ([S2[2] - S3[2], S3[1] - S2[1]]) @test ∇λ([0, 0])[2, :] ≈ (0.5 / vol) * ([S3[2] - S1[2], S1[1] - S3[1]]) @test ∇λ([0, 0])[3, :] ≈ (0.5 / vol) * ([S1[2] - S2[2], S2[1] - S1[1]]) end @testset "Square" begin shape = Square() @test get_coords(FunctionSpace(:Lagrange, 0), shape) == (SA[0.0, 0.0],) @test get_coords(FunctionSpace(:Lagrange, 1), shape) == (SA[-1.0, -1.0], SA[1.0, -1.0], SA[-1.0, 1.0], SA[1.0, 1.0]) @test get_coords(FunctionSpace(:Lagrange, 2), shape) == ( SA[-1.0, -1.0], SA[0.0, -1.0], SA[1.0, -1.0], SA[-1.0, 0.0], SA[0.0, 0.0], SA[1.0, 0.0], SA[-1.0, 1.0], SA[0.0, 1.0], SA[1.0, 1.0], ) for deg in 0:3 test_lagrange_shape_function(shape, deg) end fs = FunctionSpace(:Lagrange, 0) λ = x -> shape_functions(fs, shape, x) ∇λ = x -> ∂λξ_∂ξ(fs, shape, x) @test λ([π, ℯ])[1] ≈ 1.0 @test ∇λ([π, ℯ])[1, :] ≈ [0.0, 0.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape, [0.0, 0.0]) @test λ == [1.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape) @test λ[1]([0.0, 0.0]) == 1.0 fs = FunctionSpace(:Lagrange, 1) λ = ξ -> shape_functions(fs, shape, ξ) ∇λ = ξ -> ∂λξ_∂ξ(fs, shape, ξ) @test λ([-1, -1])[1] ≈ 1.0 @test λ([1, -1])[2] ≈ 1.0 @test λ([1, 1])[4] ≈ 1.0 @test λ([-1, 1])[3] ≈ 1.0 @test Σ(λ([π, ℯ])) ≈ 1.0 @test ∇λ([0, 0])[1, :] ≈ [-1.0, -1.0] ./ 4.0 @test ∇λ([0, 0])[2, :] ≈ [1.0, -1.0] ./ 4.0 @test ∇λ([0, 0])[4, :] ≈ [1.0, 1.0] ./ 4.0 @test ∇λ([0, 0])[3, :] ≈ [-1.0, 1.0] ./ 4.0 λ = Bcube.shape_functions_vec(fs, Val(1), shape, [0.0, 0.0]) @test λ == [0.25, 0.25, 0.25, 0.25] λ = Bcube.shape_functions_vec(fs, Val(1), shape) @test λ[1]([0.0, 0.0]) == 0.25 @test λ[2]([0.0, 0.0]) == 0.25 @test λ[3]([0.0, 0.0]) == 0.25 @test λ[4]([0.0, 0.0]) == 0.25 λ = Bcube.shape_functions_vec(fs, Val(2), shape) @test λ[1]([0.0, 0.0]) == [0.25, 0.0] @test λ[2]([0.0, 0.0]) == [0.25, 0.0] @test λ[3]([0.0, 0.0]) == [0.25, 0.0] @test λ[4]([0.0, 0.0]) == [0.25, 0.0] @test λ[5]([0.0, 0.0]) == [0.0, 0.25] @test λ[6]([0.0, 0.0]) == [0.0, 0.25] @test λ[7]([0.0, 0.0]) == [0.0, 0.25] @test λ[8]([0.0, 0.0]) == [0.0, 0.25] fs = FunctionSpace(:Lagrange, 2) λ = ξ -> shape_functions(fs, shape, ξ) @test λ([-1, -1])[1] ≈ 1.0 @test λ([1, -1])[3] ≈ 1.0 @test λ([1, 1])[9] ≈ 1.0 @test λ([-1, 1])[7] ≈ 1.0 @test Σ(λ([π, ℯ])) ≈ 1.0 λ = Bcube.shape_functions_vec(fs, Val(1), shape, [0.0, 0.0]) @test λ == [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape) @test λ[1]([0.0, 0.0]) == 0.0 @test λ[2]([0.0, 0.0]) == 0.0 @test λ[3]([0.0, 0.0]) == 0.0 @test λ[4]([0.0, 0.0]) == 0.0 @test λ[5]([0.0, 0.0]) == 1.0 @test λ[6]([0.0, 0.0]) == 0.0 @test λ[7]([0.0, 0.0]) == 0.0 @test λ[8]([0.0, 0.0]) == 0.0 @test λ[9]([0.0, 0.0]) == 0.0 end @testset "Cube" begin for deg in 0:2 test_lagrange_shape_function(Cube(), deg) end end @testset "Tetra" begin for deg in 0:1 test_lagrange_shape_function(Tetra(), deg) end end @testset "Prism" begin for deg in 0:1 test_lagrange_shape_function(Prism(), deg) end end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1168
@testset "Limiter" begin @testset "LinearScalingLimiter" begin path = joinpath(tempdir, "mesh.msh") Lx = 3.0 Ly = 1.0 gen_rectangle_mesh( path, :quad; nx = 4, ny = 2, lx = Lx, ly = Ly, xc = Lx / 2, yc = Ly / 2, ) mesh = read_msh(path, 2) # '2' indicates the space dimension (3 by default) c2n = connectivities_indices(mesh, :c2n) f = (k, x) -> begin if x[1] < 1.0 return 0.0 elseif x[1] > 2.0 return 1.0 else return k * (x[1] - 1.5) + 0.5 end end degree = 1 fs = FunctionSpace(:Taylor, degree) fes = FESpace(fs, :discontinuous; size = 1) # DG, scalar u = CellVariable(:u, mesh, fes) for k in [1, 2] set_values!(u, x -> f(k, x)) @test mean_values(u, Val(2 * degree + 1)) ≈ [0.0, 0.5, 1.0] limᵤ, ũ = linear_scaling_limiter(u, 2 * degree + 1) @test get_values(limᵤ) ≈ [0.0, 1.0 / k, 0.0] end end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
4031
@testset "projection" begin @testset "1D_Line" begin mesh = line_mesh(11; xmin = -1.0, xmax = 1.0) Ω = CellDomain(mesh) dΩ = Measure(CellDomain(mesh), 2) U = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh) u = FEFunction(U) f = PhysicalFunction(x -> 2 * x[1] + 3) projection_l2!(u, f, dΩ) for cInfo in DomainIterator(Ω) _u = materialize(u, cInfo) _f = materialize(f, cInfo) s = shape(celltype(cInfo)) # Loop over line vertices for ξ in get_coords(s) cPoint = CellPoint(ξ, cInfo, ReferenceDomain()) @test materialize(_u, cPoint) ≈ materialize(_f, cPoint) end end # f(x) = c*x #- build mesh and variable xmin = 2.0 xmax = 7.0 mesh = one_cell_mesh(:line; xmin, xmax) Ω = CellDomain(mesh) dΩ = Measure(CellDomain(mesh), 2) cInfo = CellInfo(mesh, 1) ctype = celltype(cInfo) cnodes = nodes(cInfo) xc = center(ctype, cnodes).x # coordinates in PhysicalDomain fs = FunctionSpace(:Taylor, 1) U = TrialFESpace(fs, mesh, :discontinuous) u = FEFunction(U) #- create test function and project on solution space f = PhysicalFunction(x -> 2 * x[1] + 4.0) projection_l2!(u, f, dΩ) f_cInfo = materialize(f, cInfo) _f = x -> materialize(f_cInfo, CellPoint(x, cInfo, PhysicalDomain())) #- compare the result vector + the resulting interpolation function @test all( get_dof_values(u) .≈ [_f(xc), ForwardDiff.derivative(_f, xc)[1] * (xmax - xmin)], ) # u = [f(x0), f'(x0) dx] end @testset "2D_Triangle" begin path = joinpath(tempdir, "mesh.msh") gen_rectangle_mesh(path, :tri; nx = 3, ny = 4) mesh = read_msh(path) Ω = CellDomain(mesh) dΩ = Measure(Ω, 2) fSpace = FunctionSpace(:Lagrange, 1) U = TrialFESpace(fSpace, mesh, :continuous) u = FEFunction(U) f = PhysicalFunction(x -> x[1] + x[2]) projection_l2!(u, f, dΩ) for cInfo in DomainIterator(Ω) _u = materialize(u, cInfo) _f = materialize(f, cInfo) # Corresponding shape s = shape(celltype(cInfo)) # Loop over triangle vertices for ξ in get_coords(s) cPoint = CellPoint(ξ, cInfo, ReferenceDomain()) @test materialize(_u, cPoint) ≈ materialize(_f, cPoint) end end end @testset "misc" begin mesh = one_cell_mesh(:quad) T, N = Bcube.get_return_type_and_codim(PhysicalFunction(x -> x[1]), mesh) @test N == (1,) @test T == Float64 T, N = Bcube.get_return_type_and_codim(PhysicalFunction(x -> 1), mesh) @test N == (1,) @test T == Int T, N = Bcube.get_return_type_and_codim(PhysicalFunction(x -> x), mesh) @test N == (2,) @test T == Float64 end @testset "var_on_vertices" begin mesh = line_mesh(3) # Test 1 fs = FunctionSpace(:Lagrange, 0) U = TrialFESpace(fs, mesh) x = [1.0, 1.0] u = FEFunction(U, x) values = var_on_vertices(u, mesh) @test values == [1.0, 1.0, 1.0] # Test 2 fs = FunctionSpace(:Lagrange, 1) U = TrialFESpace(fs, mesh) x = [1.0, 2.0, 3.0] u = FEFunction(U, x) values = var_on_vertices(u, mesh) @test values == x # Test 3 fs = FunctionSpace(:Lagrange, 1) U = TrialFESpace(fs, mesh; size = 2) f = PhysicalFunction(x -> [x[1], -1.0 - 2 * x[1]]) u = FEFunction(U) projection_l2!(u, f, mesh) values = var_on_vertices(u, mesh) @test isapprox_arrays(values[:, 1], [0.0, 0.5, 1.0]; rtol = 1e-15) @test isapprox_arrays(values[:, 2], [-1.0, -2.0, -3.0]; rtol = 1e-15) end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1459
@testset "Shape" begin @testset "Line" begin line = Line() @test nvertices(line) == 2 @test nedges(line) == 2 @test nfaces(line) == 2 @test face_area(line) == SA[1.0, 1.0] @test faces2nodes(line) == (SA[1], SA[2]) @test get_coords(line) == (SA[-1.0], SA[1.0]) @test normals(line) == (SA[-1.0], SA[1.0]) end @testset "Triangle" begin tri = Triangle() @test nvertices(tri) == 3 @test nedges(tri) == 3 @test nfaces(tri) == 3 @test face_area(tri) == SA[1.0, sqrt(2.0), 1.0] @test faces2nodes(tri) == (SA[1, 2], SA[2, 3], SA[3, 1]) @test face_shapes(tri) == (Line(), Line(), Line()) @test get_coords(tri) == (SA[0.0, 0.0], SA[1.0, 0.0], SA[0.0, 1.0]) @test normals(tri) == (SA[0.0, -1.0], SA[1.0, 1.0] ./ √(2), SA[-1.0, 0.0]) end @testset "Square" begin square = Square() @test nvertices(square) == 4 @test nedges(square) == 4 @test nfaces(square) == 4 @test face_area(square) == SA[2.0, 2.0, 2.0, 2.0] @test faces2nodes(square) == (SA[1, 2], SA[2, 3], SA[3, 4], SA[4, 1]) @test face_shapes(square) == (Line(), Line(), Line(), Line()) @test get_coords(square) == (SA[-1.0, -1.0], SA[1.0, -1.0], SA[1.0, 1.0], SA[-1.0, 1.0]) @test normals(square) == (SA[0.0, -1.0], SA[1.0, 0.0], SA[0.0, 1.0], SA[-1.0, 0.0]) end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1876
@testset "Shape functions" begin # Mesh nspa = 2 mesh = one_cell_mesh(:quad) icell = 1 s = shape(cells(mesh)[icell]) cInfo = CellInfo(mesh, icell) cPoint = CellPoint(SA[0.0, 0.0], cInfo, ReferenceDomain()) # Function and fe spaces fs = FunctionSpace(:Lagrange, 1) V_vec = TestFESpace(fs, mesh; size = 3) V_sca = TestFESpace(fs, mesh; size = 1) ndofs_sca = Bcube.get_ndofs(V_sca, s) # Shape functions λ_vec = Bcube.get_shape_functions(V_vec, s) λ_sca = Bcube.get_shape_functions(V_sca, s) # LazyMapOver them ! λ_sca = Bcube.LazyMapOver(λ_sca) λ_vec = Bcube.LazyMapOver(λ_vec) # Scalar tests f = Bcube.materialize(λ_sca, cInfo) @test Bcube.unwrap(f(cPoint)) == (0.25, 0.25, 0.25, 0.25) f = Bcube.materialize(∇(λ_sca), cInfo) @test Bcube.unwrap(f(cPoint)) == ([-0.25, -0.25], [0.25, -0.25], [-0.25, 0.25], [0.25, 0.25]) # Vector tests f = Bcube.materialize(λ_vec, cInfo) @test Bcube.unwrap(f(cPoint)) == ( [0.25, 0.0, 0.0], # λ1, 0, 0 [0.25, 0.0, 0.0], # λ2, 0, 0 [0.25, 0.0, 0.0], # λ3, 0, 0 [0.25, 0.0, 0.0], # λ4, 0, 0 [0.0, 0.25, 0.0], # 0, λ1, 0 [0.0, 0.25, 0.0], # 0, λ2, 0 [0.0, 0.25, 0.0], # 0, λ3, 0 [0.0, 0.25, 0.0], # 0, λ4, 0 [0.0, 0.0, 0.25], # 0, 0, λ1 [0.0, 0.0, 0.25], # 0, 0, λ2 [0.0, 0.0, 0.25], # 0, 0, λ3 [0.0, 0.0, 0.25], # 0, 0, λ4 ) f_sca = Bcube.materialize(∇(λ_sca), cInfo) _f_sca = Bcube.unwrap(f_sca(cPoint)) f_vec = Bcube.materialize(∇(λ_vec), cInfo) _f_vec = Bcube.unwrap(f_vec(cPoint)) for i in 1:ndofs_sca for j in 1:Bcube.get_size(V_vec) I = i + (j - 1) * ndofs_sca for k in 1:nspa @test _f_vec[I][j, k] == _f_sca[i][k] end end end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1909
@testset "Taylor" begin # TODO : add more test for gradients, waiting for Ghislain's commit @testset "Line" begin shape = Line() fs = FunctionSpace(:Taylor, 0) λ = ξ -> shape_functions(fs, shape, ξ) ∇λ = ξ -> ∂λξ_∂ξ(fs, shape, ξ) @test λ(rand())[1] ≈ 1.0 @test ∇λ(rand())[1] ≈ 0.0 λ = Bcube.shape_functions_vec(fs, Val(1), shape, [0.0]) @test λ == [1.0] fs = FunctionSpace(:Taylor, 1) λ = ξ -> shape_functions(fs, shape, ξ) ∇λ = ξ -> ∂λξ_∂ξ(fs, shape, ξ) @test λ(-1) ≈ [1.0, -0.5] @test λ(1) ≈ [1.0, 0.5] λ = Bcube.shape_functions_vec(fs, Val(1), shape, [0.0]) @test λ == [1.0, 0.0] end @testset "Square" begin shape = Square() fs = FunctionSpace(:Taylor, 0) λ = ξ -> shape_functions(fs, shape, ξ) ∇λ = ξ -> ∂λξ_∂ξ(fs, shape, ξ) @test λ(rand(2))[1] ≈ 1.0 λ = Bcube.shape_functions_vec(fs, Val(1), shape, [0.0, 0.0]) @test λ == [1.0] fs = FunctionSpace(:Taylor, 1) λ = ξ -> shape_functions(fs, shape, ξ) ∇λ = ξ -> ∂λξ_∂ξ(fs, shape, ξ) @test λ([0.0, 0.0]) ≈ [1.0, 0.0, 0.0] @test λ([1.0, 0.0]) ≈ [1.0, 0.5, 0.0] @test λ([0.0, 1.0]) ≈ [1.0, 0.0, 0.5] λ = Bcube.shape_functions_vec(fs, Val(1), shape, [0.0, 0.0]) @test λ == [1.0, 0.0, 0.0] λ = Bcube.shape_functions_vec(fs, Val(1), shape) @test λ[1]([0.0, 0.0]) == 1.0 @test λ[2]([0.0, 0.0]) == 0.0 @test λ[3]([0.0, 0.0]) == 0.0 λ = Bcube.shape_functions_vec(fs, Val(2), shape) @test λ[1]([0.0, 0.0]) == [1.0, 0.0] @test λ[2]([0.0, 0.0]) == [0.0, 0.0] @test λ[3]([0.0, 0.0]) == [0.0, 0.0] @test λ[4]([0.0, 0.0]) == [0.0, 1.0] @test λ[5]([0.0, 0.0]) == [0.0, 0.0] @test λ[6]([0.0, 0.0]) == [0.0, 0.0] end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1391
@testset "TestFunction" begin # Mesh mesh = one_cell_mesh(:quad) x = [0, 0.0] cell = CellInfo(mesh, 1) # Function space fs = FunctionSpace(:Lagrange, 1) # Finite element spaces fes_vec = FESpace(fs, :continuous; size = 3) fes_sca = FESpace(fs, :continuous; size = 1) # Test functions λ_vec = TestFunction(mesh, fes_vec) λ_sca = TestFunction(mesh, fes_sca) # Scalar tests f = λ_sca @test f[cell](x) == SA[0.25, 0.25, 0.25, 0.25] f = ∇(λ_sca) ∇λ_sca_ref = SA[-0.25 -0.25; 0.25 -0.25; -0.25 0.25; 0.25 0.25] @test f[cell](x) == ∇λ_sca_ref ndofs_sca, nspa = size(∇λ_sca_ref) # Vector tests f = λ_vec @test f[cell](x) == SA[ 0.25 0.0 0.0 0.25 0.0 0.0 0.25 0.0 0.0 0.25 0.0 0.0 0.0 0.25 0.0 0.0 0.25 0.0 0.0 0.25 0.0 0.0 0.25 0.0 0.0 0.0 0.25 0.0 0.0 0.25 0.0 0.0 0.25 0.0 0.0 0.25 ] f = ∇(λ_vec) n = size(fes_vec) for i in 1:ndofs_sca for j in 1:n I = i + (j - 1) * ndofs_sca for k in 1:nspa if (1 + (j - 1) * ndofs_sca <= I <= j * ndofs_sca) @test f[cell](x)[I, j, k] == ∇λ_sca_ref[i, k] else @test f[cell](x)[I, j, k] == 0.0 end end end end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1073
@testset "issue #130" begin struct Parameters x::Int end function _run() mesh = one_cell_mesh(:line) dΩ = Measure(CellDomain(mesh), 1) U = TrialFESpace(FunctionSpace(:Lagrange, 0), mesh) V = TestFESpace(U) params = Parameters(1) f1(v) = _f1 ∘ (v,) _f1(v) = v l1(v) = ∫(f1(v))dΩ a1 = assemble_linear(l1, V) # Two tests of composition with not-only-`AbstractLazy` args : # As the first tuple arg `v` is an `AbstractLazy`, # operator `∘` automatically builds a `LazyOp` f2(v, params) = _f2 ∘ (v, params) _f2(v, params) = v l2(v) = ∫(f2(v, params))dΩ a2 = assemble_linear(l2, V) # As the first tuple arg `params` is not an `AbstractLazy`, # one must explicitly use `lazy_compose` to build a `LazyOp` f3(params, v) = lazy_compose(_f3, (params, v)) _f3(params, v) = v l3(v) = ∫(f3(params, v))dΩ a3 = assemble_linear(l3, V) @test a1 == a2 == a3 end _run() end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1303
@testset "issue #130" begin function run() # Settings Zin = 4 Zout = 8 nr = 3 nz = 3 degree = 1 qdeg = 2 * degree + 1 # quad degree # Mesh and measures mesh = rectangle_mesh( nr, nz; ymin = Zin, ymax = Zout, bnd_names = ("AXIS", "WALL", "INLET", "OUTLET"), ) Ω = CellDomain(mesh) dΩ = Measure(Ω, qdeg) # FESpace fs = FunctionSpace(:Lagrange, degree) U_up = TrialFESpace(fs, mesh) U_ur = TrialFESpace(fs, mesh) U_uz = TrialFESpace(fs, mesh) V_up = TestFESpace(U_up) V_ur = TestFESpace(U_ur) V_uz = TestFESpace(U_uz) U = MultiFESpace(U_up, U_ur, U_uz) V = MultiFESpace(V_up, V_ur, V_uz) # Bilinear forms function test(u, ∇u, v, ∇v) up, ur, uz = u vp, vr, vz = v ∇up, ∇ur, ∇uz = ∇u ∂u∂r = ∇ur ⋅ SA[1, 0] return ∂u∂r * vp end a((up, ur, uz), (vp, vr, vz)) = ∫(∇(ur) ⋅ SA[1, 0] * vp)dΩ A = assemble_bilinear(a, U, V) b(u, v) = ∫(test ∘ (u, map(∇, u), v, map(∇, v)))dΩ B = assemble_bilinear(b, U, V) @test A == B end run() end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
20446
@testset "mapping" begin # bmxam: For Jacobians we should have two type of tests : one using 'rand' checking analytical formulae, # and another one using "known" cells (for instance Square of side 2) and checking "expected" value: # "I known the area of a Square of side 2 is 4". I don't feel like writing the second type of tests right now @testset "one cell mesh" begin icell = 1 tol = 1e-15 # Line order 1 xmin = -(1.0 + rand()) xmax = 1.0 + rand() mesh = one_cell_mesh(:line; xmin, xmax, order = 1) c2n = connectivities_indices(mesh, :c2n) ctype = cells(mesh)[icell] cnodes = get_nodes(mesh, c2n[icell]) @test isapprox_arrays(mapping(ctype, cnodes, [-1.0]), [xmin]; rtol = tol) @test isapprox_arrays(mapping(ctype, cnodes, [1.0]), [xmax]; rtol = tol) @test isapprox_arrays( mapping_jacobian(ctype, cnodes, rand(1)), @SVector[(xmax - xmin) / 2.0]; rtol = tol, ) @test isapprox( mapping_det_jacobian(ctype, cnodes, rand(1)), (xmax - xmin) / 2.0, rtol = tol, ) @test isapprox_arrays(mapping_inv(ctype, cnodes, xmin), SA[-1.0], rtol = tol) @test isapprox_arrays(mapping_inv(ctype, cnodes, xmax), SA[1.0], rtol = tol) # Line order 2 -> no mapping yet, uncomment when mapping is available #mesh = scale(one_cell_mesh(:line; order = 2), rand()) #c2n = connectivities_indices(mesh,:c2n) #ct = cells(mesh)[icell] #n = get_nodes(mesh, c2n[icell]) #@test mapping(n, ct, [-1.]) == get_coords(n[1]) #@test mapping(n, ct, [ 1.]) == get_coords(n[2]) #@test mapping(n, ct, [ 0.]) == get_coords(n[3]) # Triangle order 1 xmin, ymin = -rand(2) xmax, ymax = rand(2) mesh = one_cell_mesh(:triangle; xmin, xmax, ymin, ymax, order = 1) c2n = connectivities_indices(mesh, :c2n) ctype = cells(mesh)[icell] cnodes = get_nodes(mesh, c2n[icell]) x1 = [xmin, ymin] x2 = [xmax, ymin] x3 = [xmin, ymax] @test isapprox(mapping(ctype, cnodes, [0.0, 0.0]), x1, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [1.0, 0.0]), x2, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [0.0, 1.0]), x3, rtol = eps()) @test isapprox_arrays( mapping_jacobian(ctype, cnodes, rand(2)), SA[ (xmax-xmin) 0.0 0.0 (ymax-ymin) ], ) @test isapprox( mapping_det_jacobian(ctype, cnodes, rand(2)), (xmax - xmin) * (ymax - ymin), rtol = eps(), ) @test isapprox_arrays(mapping_inv(ctype, cnodes, x1), SA[0.0, 0.0]; rtol = tol) @test isapprox_arrays(mapping_inv(ctype, cnodes, x2), SA[1.0, 0.0]; rtol = tol) @test isapprox_arrays(mapping_inv(ctype, cnodes, x3), SA[0.0, 1.0]; rtol = tol) # Triangle order 2 xmin, ymin = -rand(2) xmax, ymax = rand(2) mesh = one_cell_mesh(:triangle; xmin, xmax, ymin, ymax, order = 2) c2n = connectivities_indices(mesh, :c2n) ctype = cells(mesh)[icell] cnodes = get_nodes(mesh, c2n[icell]) x1 = [xmin, ymin] x2 = [xmax, ymin] x3 = [xmin, ymax] x4 = (x1 + x2) / 2 x5 = (x2 + x3) / 2 x6 = (x3 + x1) / 2 @test isapprox(mapping(ctype, cnodes, [0.0, 0.0]), x1, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [1.0, 0.0]), x2, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [0.0, 1.0]), x3, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [0.5, 0.0]), x4, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [0.5, 0.5]), x5, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [0.0, 0.5]), x6, rtol = eps()) @test isapprox( mapping_det_jacobian(ctype, cnodes, rand(2)), (xmax - xmin) * (ymax - ymin), ) # Quad order 1 xmin, ymin = -rand(2) xmax, ymax = rand(2) mesh = one_cell_mesh(:quad; xmin, xmax, ymin, ymax, order = 1) c2n = connectivities_indices(mesh, :c2n) ctype = cells(mesh)[icell] cnodes = get_nodes(mesh, c2n[icell]) x1 = [xmin, ymin] x2 = [xmax, ymin] x3 = [xmax, ymax] x4 = [xmin, ymax] @test isapprox(mapping(ctype, cnodes, [-1.0, -1.0]), x1, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [1.0, -1.0]), x2, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [1.0, 1.0]), x3, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [-1.0, 1.0]), x4, rtol = eps()) @test isapprox( mapping_jacobian(ctype, cnodes, rand(2)), SA[ (xmax-xmin) 0.0 0.0 (ymax-ymin) ] / 2.0, ) @test isapprox( mapping_det_jacobian(ctype, cnodes, rand(2)), (xmax - xmin) * (ymax - ymin) / 4.0, rtol = tol, ) @test isapprox_arrays(mapping_inv(ctype, cnodes, x1), SA[-1.0, -1.0]; rtol = tol) @test isapprox_arrays(mapping_inv(ctype, cnodes, x2), SA[1.0, -1.0]; rtol = tol) @test isapprox_arrays(mapping_inv(ctype, cnodes, x3), SA[1.0, 1.0]; rtol = tol) @test isapprox_arrays(mapping_inv(ctype, cnodes, x4), SA[-1.0, 1.0]; rtol = tol) θ = π / 5 s = 3 t = SA[-1, 2] R(θ) = SA[cos(θ) -sin(θ); sin(θ) cos(θ)] mesh = one_cell_mesh(:quad) mesh = transform(mesh, x -> R(θ) * (s .* x .+ t)) # scale, translate and rotate c = CellInfo(mesh, 1) cnodes = nodes(c) ctype = celltype(c) @test all(mapping_jacobian_inv(ctype, cnodes, SA[0.0, 0.0]) .≈ R(-θ) ./ s) # Quad order 2 xmin, ymin = -rand(2) xmax, ymax = rand(2) mesh = one_cell_mesh(:quad; xmin, xmax, ymin, ymax, order = 2) c2n = connectivities_indices(mesh, :c2n) ctype = cells(mesh)[icell] cnodes = get_nodes(mesh, c2n[icell]) x1 = [xmin, ymin] x2 = [xmax, ymin] x3 = [xmax, ymax] x4 = [xmin, ymax] x5 = (x1 + x2) / 2 x6 = (x2 + x3) / 2 x7 = (x3 + x4) / 2 x8 = (x4 + x1) / 2 x9 = [(xmin + xmax) / 2, (ymin + ymax) / 2] @test isapprox(mapping(ctype, cnodes, [-1.0, -1.0]), x1, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [1.0, -1.0]), x2, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [1.0, 1.0]), x3, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [-1.0, 1.0]), x4, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [0.0, -1.0]), x5, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [1.0, 0.0]), x6, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [0.0, 1.0]), x7, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [-1.0, 0.0]), x8, rtol = eps()) @test isapprox(mapping(ctype, cnodes, [0.0, 0.0]), x9, rtol = eps()) @test isapprox( mapping_det_jacobian(ctype, cnodes, rand(2)), (xmax - xmin) * (ymax - ymin) / 4.0, rtol = 1000eps(), ) # Quad order 3 xmin, ymin = -rand(2) xmax, ymax = rand(2) mesh = one_cell_mesh(:quad; xmin, xmax, ymin, ymax, order = 3) c2n = connectivities_indices(mesh, :c2n) ctype = cells(mesh)[icell] cnodes = get_nodes(mesh, c2n[icell]) tol = 1e-15 @test isapprox(mapping(ctype, cnodes, [-1.0, -1.0]), cnodes[1].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [1.0, -1.0]), cnodes[2].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [1.0, 1.0]), cnodes[3].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [-1.0, 1.0]), cnodes[4].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [-1.0 / 3.0, -1.0]), cnodes[5].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [1.0 / 3.0, -1.0]), cnodes[6].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [1.0, -1.0 / 3.0]), cnodes[7].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [1.0, 1.0 / 3.0]), cnodes[8].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [1.0 / 3, 1.0]), cnodes[9].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [-1.0 / 3, 1.0]), cnodes[10].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [-1.0, 1.0 / 3.0]), cnodes[11].x, rtol = tol) @test isapprox(mapping(ctype, cnodes, [-1.0, -1.0 / 3.0]), cnodes[12].x, rtol = tol) @test isapprox( mapping(ctype, cnodes, [-1.0 / 3.0, -1.0 / 3.0]), cnodes[13].x, rtol = tol, ) @test isapprox( mapping(ctype, cnodes, [1.0 / 3.0, -1.0 / 3.0]), cnodes[14].x, rtol = tol, ) @test isapprox( mapping(ctype, cnodes, [1.0 / 3.0, 1.0 / 3.0]), cnodes[15].x, rtol = tol, ) @test isapprox( mapping(ctype, cnodes, [-1.0 / 3.0, 1.0 / 3.0]), cnodes[16].x, rtol = tol, ) @test isapprox( mapping_det_jacobian(ctype, cnodes, rand(2)), (xmax - xmin) * (ymax - ymin) / 4.0, rtol = 1000eps(), ) # Hexa order 1 mesh = one_cell_mesh( :hexa; xmin = 1.0, xmax = 2.0, ymin = 1.0, ymax = 2.0, zmin = 1.0, zmax = 2.0, ) c2n = connectivities_indices(mesh, :c2n) icell = 1 ctype = cells(mesh)[icell] cnodes = get_nodes(mesh, c2n[icell]) F = mapping(ctype, cnodes) @test isapprox_arrays(F([-1.0, -1.0, -1.0]), [1.0, 1.0, 1.0]) @test isapprox_arrays(F([1.0, -1.0, -1.0]), [2.0, 1.0, 1.0]) @test isapprox_arrays(F([1.0, 1.0, -1.0]), [2.0, 2.0, 1.0]) @test isapprox_arrays(F([-1.0, 1.0, -1.0]), [1.0, 2.0, 1.0]) @test isapprox_arrays(F([-1.0, -1.0, 1.0]), [1.0, 1.0, 2.0]) @test isapprox_arrays(F([1.0, -1.0, 1.0]), [2.0, 1.0, 2.0]) @test isapprox_arrays(F([1.0, 1.0, 1.0]), [2.0, 2.0, 2.0]) @test isapprox_arrays(F([-1.0, 1.0, 1.0]), [1.0, 2.0, 2.0]) # Hexa order 2 # Very trivial test for now. To be improved. mesh = one_cell_mesh( :hexa; xmin = 1.0, xmax = 2.0, ymin = 1.0, ymax = 2.0, zmin = 1.0, zmax = 2.0, order = 2, ) c2n = connectivities_indices(mesh, :c2n) icell = 1 ctype = cells(mesh)[icell] cnodes = get_nodes(mesh, c2n[icell]) F = mapping(ctype, cnodes) @test isapprox_arrays(F([-1.0, -1.0, -1.0]), [1.0, 1.0, 1.0]) @test isapprox_arrays(F([1.0, -1.0, -1.0]), [2.0, 1.0, 1.0]) @test isapprox_arrays(F([1.0, 1.0, -1.0]), [2.0, 2.0, 1.0]) @test isapprox_arrays(F([-1.0, 1.0, -1.0]), [1.0, 2.0, 1.0]) @test isapprox_arrays(F([-1.0, -1.0, 1.0]), [1.0, 1.0, 2.0]) @test isapprox_arrays(F([1.0, -1.0, 1.0]), [2.0, 1.0, 2.0]) @test isapprox_arrays(F([1.0, 1.0, 1.0]), [2.0, 2.0, 2.0]) @test isapprox_arrays(F([-1.0, 1.0, 1.0]), [1.0, 2.0, 2.0]) # Penta6 mesh = one_cell_mesh( :penta; xmin = 1.0, xmax = 2.0, ymin = 1.0, ymax = 2.0, zmin = 1.0, zmax = 2.0, ) c2n = connectivities_indices(mesh, :c2n) icell = 1 ctype = cells(mesh)[icell] cnodes = get_nodes(mesh, c2n[icell]) F = mapping(ctype, cnodes) @test isapprox_arrays(F([0.0, 0.0, -1.0]), [1.0, 1.0, 1.0]) @test isapprox_arrays(F([1.0, 0.0, -1.0]), [2.0, 1.0, 1.0]) @test isapprox_arrays(F([0.0, 1.0, -1.0]), [1.0, 2.0, 1.0]) @test isapprox_arrays(F([0.0, 0.0, 1.0]), [1.0, 1.0, 2.0]) @test isapprox_arrays(F([1.0, 0.0, 1.0]), [2.0, 1.0, 2.0]) @test isapprox_arrays(F([0.0, 1.0, 1.0]), [1.0, 2.0, 2.0]) # Pyra5 mesh = one_cell_mesh( :pyra; xmin = 1.0, xmax = 2.0, ymin = 1.0, ymax = 2.0, zmin = 1.0, zmax = 3.0, ) c2n = connectivities_indices(mesh, :c2n) icell = 1 ctype = cells(mesh)[icell] cnodes = get_nodes(mesh, c2n[icell]) F = mapping(ctype, cnodes) @test isapprox_arrays(F([-1.0, -1.0, 0.0]), [1.0, 1.0, 1.0]) @test isapprox_arrays(F([1.0, -1.0, 0.0]), [2.0, 1.0, 1.0]) @test isapprox_arrays(F([1.0, 1.0, 0.0]), [2.0, 2.0, 1.0]) @test isapprox_arrays(F([-1.0, 1.0, 0.0]), [1.0, 2.0, 1.0]) @test isapprox_arrays(F([0.0, 0.0, 1.0]), [1.5, 1.5, 3.0]) end @testset "basic mesh" begin # Create mesh mesh = basic_mesh() # Get cell -> node connectivity from mesh c2n = connectivities_indices(mesh, :c2n) # Test mapping on quad '2' icell = 2 cnodes = get_nodes(mesh, c2n[icell]) ctype = cells(mesh)[icell] center = sum(y -> get_coords(y), cnodes) / length(cnodes) @test isapprox_arrays(mapping(ctype, cnodes, [-1.0, -1.0]), get_coords(cnodes[1])) @test isapprox_arrays(mapping(ctype, cnodes, [1.0, -1.0]), get_coords(cnodes[2])) @test isapprox_arrays(mapping(ctype, cnodes, [1.0, 1.0]), get_coords(cnodes[3])) @test isapprox_arrays(mapping(ctype, cnodes, [-1.0, 1.0]), get_coords(cnodes[4])) @test isapprox_arrays(mapping(ctype, cnodes, [0.0, 0.0]), center) @test isapprox(mapping_det_jacobian(ctype, cnodes, rand(2)), 0.25, rtol = eps()) @test isapprox_arrays( mapping_inv(ctype, cnodes, get_coords(cnodes[1])), [-1.0, -1.0], ) @test isapprox_arrays( mapping_inv(ctype, cnodes, get_coords(cnodes[2])), [1.0, -1.0], ) @test isapprox_arrays(mapping_inv(ctype, cnodes, get_coords(cnodes[3])), [1.0, 1.0]) @test isapprox_arrays( mapping_inv(ctype, cnodes, get_coords(cnodes[4])), [-1.0, 1.0], ) @test isapprox_arrays(mapping_inv(ctype, cnodes, center), [0.0, 0.0]) x = get_coords(cnodes[1]) @test isapprox( mapping(ctype, cnodes, mapping_inv(ctype, cnodes, x)), x, rtol = eps(eltype(x)), ) # Test mapping on triangle '3' icell = 3 cnodes = get_nodes(mesh, c2n[icell]) ctype = cells(mesh)[icell] center = sum(y -> get_coords(y), cnodes) / length(cnodes) @test isapprox_arrays(mapping(ctype, cnodes, [0.0, 0.0]), get_coords(cnodes[1])) @test isapprox_arrays(mapping(ctype, cnodes, [1.0, 0.0]), get_coords(cnodes[2])) @test isapprox_arrays(mapping(ctype, cnodes, [0.0, 1.0]), get_coords(cnodes[3])) @test isapprox( mapping(ctype, cnodes, [1 / 3, 1 / 3]), center, rtol = eps(eltype(center)), ) @test isapprox(mapping_det_jacobian(ctype, cnodes, 0.0), 1.0, rtol = eps()) @test isapprox_arrays(mapping_inv(ctype, cnodes, get_coords(cnodes[1])), [0.0, 0.0]) @test isapprox_arrays(mapping_inv(ctype, cnodes, get_coords(cnodes[2])), [1.0, 0.0]) @test isapprox_arrays(mapping_inv(ctype, cnodes, get_coords(cnodes[3])), [0.0, 1.0]) @test isapprox( mapping_inv(ctype, cnodes, center), [1 / 3, 1 / 3], rtol = 10 * eps(eltype(x)), ) x = get_coords(cnodes[1]) @test isapprox( mapping(ctype, cnodes, mapping_inv(ctype, cnodes, x)), x, rtol = eps(eltype(x)), ) end function _check_face_parametrization(mesh) c2n = connectivities_indices(mesh, :c2n) f2n = connectivities_indices(mesh, :f2n) f2c = connectivities_indices(mesh, :f2c) cellTypes = cells(mesh) faceTypes = faces(mesh) for kface in inner_faces(mesh) # Face nodes, type and shape ftype = faceTypes[kface] fshape = shape(ftype) fnodes = get_nodes(mesh, f2n[kface]) Fface = mapping(ftype, fnodes) # Neighbor cell i i = f2c[kface][1] xᵢ = get_nodes(mesh, c2n[i]) ctᵢ = cellTypes[i] shapeᵢ = shape(ctᵢ) Fᵢ = mapping(ctᵢ, xᵢ) sideᵢ = cell_side(ctᵢ, c2n[i], f2n[kface]) fpᵢ = mapping_face(shapeᵢ, sideᵢ) # mapping face-ref -> cell_i-ref # Neighbor cell j j = f2c[kface][2] xⱼ = get_nodes(mesh, c2n[j]) ctⱼ = cellTypes[j] shapeⱼ = shape(ctⱼ) Fⱼ = mapping(ctⱼ, xⱼ) sideⱼ = cell_side(ctⱼ, c2n[j], f2n[kface]) # This part is a bit tricky : we want the face parametrization (face-ref -> cell-ref) on # side `j`. For this, we need to know the permutation between the vertices of `kface` and the # vertices of the `sideⱼ`-th face of cell `j`. However all the information we have for entities, # namely `fnodes` and `faces2nodes(ctⱼ, sideⱼ)` refer to the nodes, not the vertices. So we need # to retrieve the number of vertices of the face and then restrict the arrays to these vertices. # (by the way, we use that the vertices appears necessarily in first) # We could simplify the expressions below by introducing the notion of "vertex" in Entity, for # instance with `nvertices` and `faces2vertices`. # # Some additional explanations: # c2n[j] = global index of the nodes of cell j # faces2nodes(ctⱼ, sideⱼ) = local index of the nodes of face sideⱼ of cell j # c2n[j][faces2nodes(ctⱼ, sideⱼ)] = global index of the nodes of face sideⱼ of cell j # f2n[kface] = global index of the nodes of face `kface` # indexin(a, b) = location of elements of `a` in `b` nv = length(faces2nodes(shapeⱼ, sideⱼ)) # number of vertices of the face iglob_vertices_of_face_of_cell_j = [c2n[j][faces2nodes(ctⱼ, sideⱼ)[l]] for l in 1:nv] g2l = indexin(f2n[kface][1:nv], iglob_vertices_of_face_of_cell_j) fpⱼ = mapping_face(shapeⱼ, sideⱼ, g2l) # High-level API faceInfo = FaceInfo(mesh, kface) # Note that in the following for-loop : # `length(fnodes) > length(get_coords(fshape))` # for high-order (>1) entities. Then, high-order # nodes are not tested. # TODO : test high-order nodes (mid-face node, ...) for (ξface, fnode) in zip(get_coords(fshape), fnodes) @test isapprox(Fface(ξface), fnode.x) @test isapprox(Fᵢ(fpᵢ(ξface)), fnode.x) @test isapprox(Fⱼ(fpⱼ(ξface)), fnode.x) # High-level API tests fpt_ref = FacePoint(ξface, faceInfo, ReferenceDomain()) fpt_phy = change_domain(fpt_ref, PhysicalDomain()) cpt_ref_i = side_n(fpt_ref) cpt_ref_j = side_p(fpt_ref) cpt_phy_i = change_domain(cpt_ref_i, PhysicalDomain()) cpt_phy_j = change_domain(cpt_ref_j, PhysicalDomain()) @test isapprox(get_coords(fpt_phy), fnode.x) @test isapprox(get_coords(cpt_ref_i), fpᵢ(ξface)) @test isapprox(get_coords(cpt_ref_j), fpⱼ(ξface)) @test isapprox(get_coords(cpt_phy_i), Fᵢ(fpᵢ(ξface))) @test isapprox(get_coords(cpt_phy_j), Fⱼ(fpⱼ(ξface))) end end end @testset "face parametrization" begin # Here we test the face parametrization # Two Quad9 side-by-side path = joinpath(tempdir, "mesh.msh") gen_rectangle_mesh(path, :quad; nx = 3, ny = 2, order = 2) mesh = read_msh(path) _check_face_parametrization(mesh) # For two Hexa8 side-by-side path = joinpath(tempdir, "mesh.msh") gen_hexa_mesh(path, :hexa; nx = 3, ny = 2, nz = 2) mesh = read_msh(path) _check_face_parametrization(mesh) end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
8790
@testset "ref2phys" begin # TODO : add more test for gradients, waiting for Ghislain's commit @testset "Line" begin # Line xmin = -rand() xmax = rand() mesh = one_cell_mesh(:line; xmin, xmax) xtest = range(xmin, xmax; length = 5) c2n = connectivities_indices(mesh, :c2n) cnodes = get_nodes(mesh, c2n[1]) ctype = cells(mesh)[1] Finv = Bcube.mapping_inv(ctype, cnodes) xc = center(ctype, cnodes) @test isapprox_arrays(xc, [(xmin + xmax) / 2]) #- Taylor degree 0 fs = FunctionSpace(:Taylor, 0) dhl = DofHandler(mesh, fs, 1, false) λ = x -> shape_functions(fs, shape(ctype), Finv(x)) r = rand() q = [r] u = interpolate(λ, q[get_dof(dhl, 1)]) @test isapprox_arrays(λ(rand(1)), [1.0]) @test all(isapprox(u([x]), r; rtol = eps()) for x in xtest) #-- new api U = TrialFESpace(fs, mesh, :discontinuous) u = FEFunction(U, q) cInfo = CellInfo(mesh, 1) _u = Bcube.materialize(u, cInfo) @test all( isapprox(_u(CellPoint(x, cInfo, Bcube.PhysicalDomain())), r; atol = eps()) for x in xtest ) #- Taylor degree 1 fs = FunctionSpace(:Taylor, 1) dhl = DofHandler(mesh, fs, 1, false) λ = x -> shape_functions(fs, shape(ctype), Finv(x)) coef = rand() q = [coef * (xmin + xmax) / 2, (xmax - xmin) * coef] # f(x) = coef*x u = interpolate(λ, q[get_dof(dhl, 1)]) @test isapprox(λ([xmin]), [1.0, -0.5]) @test isapprox_arrays(λ(xc), [1.0, 0.0]) @test isapprox_arrays(λ([xmax]), [1.0, 0.5]) @test all(isapprox(u([x]), coef * x) for x in xtest) #-- new api U = TrialFESpace(fs, mesh, :discontinuous) u = FEFunction(U, q) cInfo = CellInfo(mesh, 1) _u = Bcube.materialize(u, cInfo) @test all( isapprox( _u(CellPoint(x, cInfo, Bcube.PhysicalDomain())), coef * x; atol = eps(), ) for x in xtest ) # Normals # Bar2_t in 1D xmin = -2.0 xmax = 3.0 cnodes = [Node([xmin]), Node([xmax])] ctype = Bar2_t() @test isapprox_arrays(normal(ctype, cnodes, 1, rand(1)), [-1.0]) @test isapprox_arrays(normal(ctype, cnodes, 2, rand(1)), [1.0]) # Bar2_t in 2D xmin = [-2.0, -1.0] xmax = [3.0, 4.0] cnodes = [Node(xmin), Node(xmax)] ctype = Bar2_t() @test normal(ctype, cnodes, 1, rand(1)) ≈ √(2) / 2 .* [-1, -1] @test normal(ctype, cnodes, 2, rand(1)) ≈ √(2) / 2 .* [1, 1] # Bar2_t in 3D xmin = [-2.0, -1.0, 5.0] xmax = [3.0, 4.0, 0.0] cnodes = [Node(xmin), Node(xmax)] ctype = Bar2_t() @test normal(ctype, cnodes, 1, rand(1)) ≈ √(3) / 3 * [-1, -1, 1] @test normal(ctype, cnodes, 2, rand(1)) ≈ √(3) / 3 * [1, 1, -1] # Bar3_t in 3D (checked graphically, see notebook) cnodes = [Node([0.0, 0.0, 1.0]), Node([1.0, 0.0, 3.0]), Node([0.5, 0.5, 2.0])] ctype = Bar3_t() @test normal(ctype, cnodes, 1, rand(1)) ≈ 1.0 / 3.0 .* [-1, -2, -2] @test normal(ctype, cnodes, 2, rand(1)) ≈ 1.0 / 3.0 .* [1, -2, 2] end @testset "Triangle" begin # Normals # Triangle3_t in 2D cnodes = [Node([0.0, 0.0]), Node([1.0, 1.0]), Node([0.0, 2.0])] ctype = Tri3_t() @test normal(ctype, cnodes, 1, myrand(1, -1.0, 1.0)) ≈ √(2) / 2 .* [1, -1] @test normal(ctype, cnodes, 2, myrand(1, -1.0, 1.0)) ≈ √(2) / 2 .* [1, 1] @test normal(ctype, cnodes, 3, myrand(1, -1.0, 1.0)) ≈ [-1.0, 0.0] # Triangle3_t in 3D (checked graphically, see notebook) cnodes = [Node([-0.5, -1.0, -0.3]), Node([0.5, 0.0, 0.0]), Node([-0.5, 1.0, 0.5])] ctype = Tri3_t() @test normal(ctype, cnodes, 1, myrand(1, -1.0, 1.0)) ≈ [0.7162290778315695, -0.6203055406219843, -0.3197451240319506] @test normal(ctype, cnodes, 2, myrand(1, -1.0, 1.0)) ≈ [0.7396002616336388, 0.647150228929434, 0.1849000654084097] @test normal(ctype, cnodes, 3, myrand(1, -1.0, 1.0)) ≈ [-0.9957173250742359, -0.034335080174973664, 0.08583770043743415] end @testset "Quad" begin # Quad4 xmin, ymin = -rand(2) xmax, ymax = 3.0 .+ rand(2) Δx = xmax - xmin Δy = ymax - ymin mesh = one_cell_mesh(:quad; xmin, xmax, ymin, ymax) xtest = [ [x, y] for (x, y) in Base.Iterators.product( range(xmin, xmax; length = 3), range(ymin, ymax; length = 3), ) ] c2n = connectivities_indices(mesh, :c2n) cnodes = get_nodes(mesh, c2n[1]) ctype = cells(mesh)[1] Finv = Bcube.mapping_inv(ctype, cnodes) xc = center(ctype, cnodes) @test all( map( (x, y) -> isapprox(x, y; rtol = eps()), xc, [(xmin + xmax) / 2, (ymin + ymax) / 2], ), ) #- Taylor degree 0 fs = FunctionSpace(:Taylor, 0) dhl = DofHandler(mesh, fs, 1, false) λ = shape_functions(fs, shape(ctype)) r = rand() q = [r] u = interpolate(λ, q[get_dof(dhl, 1)]) @test isapprox_arrays(λ(rand(2)), [1.0]) @test all(isapprox(u(x), r; rtol = eps()) for x in xtest) #-- new api U = TrialFESpace(fs, mesh, :discontinuous) u = FEFunction(U, q) cInfo = CellInfo(mesh, 1) _u = Bcube.materialize(u, cInfo) @test all( isapprox(_u(CellPoint(x, cInfo, Bcube.PhysicalDomain())), r; atol = eps()) for x in xtest ) #- Taylor degree 1 fs = FunctionSpace(:Taylor, 1) dhl = DofHandler(mesh, fs, 1, false) λ = x -> shape_functions(fs, shape(ctype), Finv(x)) coefx, coefy = rand(2) q = [[coefx, coefy] ⋅ xc, Δx * coefx, Δy * coefy] # f(x,y) = coefx*x + coefy*y u = interpolate(λ, q[get_dof(dhl, 1)]) xr = rand(2) @test isapprox(λ(xr), [1.0, (xr[1] - xc[1]) / Δx, (xr[2] - xc[2]) / Δy]) @test all(isapprox(u(x), [coefx, coefy] ⋅ x) for x in xtest) #-- new api U = TrialFESpace(fs, mesh, :discontinuous) u = FEFunction(U, q) cInfo = CellInfo(mesh, 1) _u = Bcube.materialize(u, cInfo) @test all( isapprox( _u(CellPoint(x, cInfo, Bcube.PhysicalDomain())), [coefx, coefy] ⋅ x; atol = 10 * eps(), ) for x in xtest ) # Normals A = [0.0, 0.0] B = [1.0, 1.0] C = [0.0, 2.0] D = [-1.0, 1.0] mesh = Mesh( [Node(A), Node(B), Node(C), Node(D)], [Quad4_t()], Connectivity([4], [1, 2, 3, 4]), ) c2n = connectivities_indices(mesh, :c2n) cnodes = get_nodes(mesh, c2n[1]) ctype = cells(mesh)[1] AB = B - A BC = C - B CD = D - C DA = A - D nAB = normalize(-[-AB[2], AB[1]]) nBC = normalize(-[-BC[2], BC[1]]) nCD = normalize(-[-CD[2], CD[1]]) nDA = normalize(-[-DA[2], DA[1]]) @test isapprox_arrays(normal(ctype, cnodes, 1, rand(2)), nAB) @test isapprox_arrays(normal(ctype, cnodes, 2, rand(2)), nBC) @test isapprox_arrays(normal(ctype, cnodes, 3, rand(2)), nCD) @test isapprox_arrays(normal(ctype, cnodes, 4, rand(2)), nDA) # Quad9 # Normals (checked graphically, see notebook) cnodes = [ Node([1.0, 1.0]), Node([4.0, 1.0]), Node([4.0, 3.0]), Node([1.0, 3.0]), Node([2.5, 0.5]), Node([4.5, 2.0]), Node([2.5, 3.5]), Node([0.5, 2.0]), Node([2.5, 2.0]), ] ctype = Quad9_t() xq = [0.5773502691896258] @test normal(ctype, cnodes, 1, -xq) ≈ [-0.35921060405354993, -0.9332565252573828] @test normal(ctype, cnodes, 1, xq) ≈ [0.3592106040535497, -0.9332565252573829] @test normal(ctype, cnodes, 2, -xq) ≈ [0.8660254037844385, -0.5000000000000004] @test normal(ctype, cnodes, 2, xq) ≈ [0.8660254037844386, 0.5000000000000003] @test normal(ctype, cnodes, 3, -xq) ≈ [0.3592106040535492, 0.9332565252573829] @test normal(ctype, cnodes, 3, xq) ≈ [-0.3592106040535494, 0.9332565252573829] @test normal(ctype, cnodes, 4, -xq) ≈ [-0.8660254037844388, 0.5] @test normal(ctype, cnodes, 4, xq) ≈ [-0.8660254037844385, -0.5000000000000001] end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
868
@testset "connectivity" begin ne = 4 numIndices = [2, 4, 3, 1] indices = [10, 9, 7, 4, 6, 9, 1, 3, 5, 12] c = Connectivity(numIndices, indices) @test length(c) === 4 @test size(c) === (4,) @test length(c, 2) === 4 @test size(c, 4) === (1,) @test axes(c) === 1:4 @test axes(c, 1) === 1:1:2 @test axes(c, 2) === 3:1:6 @test c[1] == [10, 9] @test c[2] == [7, 4, 6, 9] @test c[3] == [1, 3, 5] @test c[4] == [12] @test c[-2] == reverse(c[2]) @test c[2][3] === 6 @test minsize(c) === 1 @test maxsize(c) === 4 for (i, a) in enumerate(c) @test a == c[i] end invc, _keys = inverse_connectivity(c) _test = Bool[] for (i, a) in enumerate(invc) for b in a push!(_test, _keys[i] ∈ c[b]) end end @assert length(_test) > 0 && all(_test) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
857
@testset "domain" begin nx = 10 ny = 10 l = 1.0 path = joinpath(tempdir, "mesh.msh") gen_rectangle_mesh(path, :quad; nx = nx, ny = ny, lx = l, ly = l, xc = 0.0, yc = 0.0) mesh = read_msh(path) @test topodim(mesh) === 2 periodicBCType_x = PeriodicBCType(Translation(SA[-l, 0.0]), ("East",), ("West",)) periodicBCType_y = PeriodicBCType(Translation(SA[0.0, l]), ("South",), ("North",)) Γ_perio_x = BoundaryFaceDomain(mesh, periodicBCType_x) Γ_perio_y = BoundaryFaceDomain(mesh, periodicBCType_y) # Testing subdomain mesh = line_mesh(3; xmin = 0.0, xmax = 2) # mesh with 2 cells dΩ = Measure(CellDomain(mesh, 1:1), 2) # only first cell #- new api cInfo = CellInfo(mesh, 1) res = integrate_on_ref_element(PhysicalFunction(x -> 2 * x), cInfo, Quadrature(Val(2))) @test res[1] == 1.0 end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
1764
@testset "entity types" begin # Bar2 bar = Bar2_t() @test nnodes(bar) === 2 @test nodes(bar) === (1, 2) @test nedges(bar) === 2 @test edges2nodes(bar) === ((1,), (2,)) @test edges2nodes(bar) === faces2nodes(bar) @test nfaces(bar) === nedges(bar) a = @SVector [10, 20] @test f2n_from_c2n(bar, a) == ([10], [20]) @test f2n_from_c2n(bar, a) == f2n_from_c2n(Bar2_t, a) @test cell_side(bar, [10, 20], [20]) === 2 @test cell_side(bar, [10, 20], [20]) === cell_side(bar, [10, 20], [20]) # Tri3 tri = Tri3_t() @test nnodes(tri) === 3 @test nodes(tri) === (1, 2, 3) @test nedges(tri) === 3 @test edges2nodes(tri) === ((1, 2), (2, 3), (3, 1)) @test edges2nodes(tri) === faces2nodes(tri) @test nfaces(tri) === nedges(tri) a = @SVector [10, 20, 30] @test f2n_from_c2n(tri, a) == ([10, 20], [20, 30], [30, 10]) @test f2n_from_c2n(tri, a) == f2n_from_c2n(Tri3_t, a) @test cell_side(tri, [10, 20, 30], [20, 30]) === 2 @test cell_side(tri, [10, 20, 30], [20, 30]) === cell_side(tri, [10, 20, 30], [30, 20]) @test oriented_cell_side(tri, [10, 20, 30], [30, 10]) === 3 @test oriented_cell_side(tri, [10, 20, 30], [10, 30]) === -3 @test oriented_cell_side(tri, [10, 20, 30], [20, 30]) === 2 @test oriented_cell_side(tri, [10, 20, 30], [30, 20]) === -2 # Quad4 quad = Quad4_t() @test nnodes(quad) === 4 @test nodes(quad) === (1, 2, 3, 4) @test nedges(quad) === 4 @test edges2nodes(quad) === ((1, 2), (2, 3), (3, 4), (4, 1)) @test oriented_cell_side(quad, [10, 20, 30, 40], [40, 10]) === 4 @test oriented_cell_side(quad, [10, 20, 30, 40], [10, 40]) === -4 @test oriented_cell_side(quad, [20, 10, 30, 40], [30, 10]) === -2 end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
6476
const mesh_dir = string(@__DIR__, "/../../input/mesh/") @testset "gmsh - line order1" begin path = joinpath(tempdir, "mesh.msh") Bcube.gen_line_mesh(path; nx = 11, lx = 2.0) mesh = read_msh(path) @test topodim(mesh) === 1 @test spacedim(mesh) === 1 @test nnodes(mesh) === 11 @test ncells(mesh) === 10 @test nodes(mesh) == [Node_t() for i in 1:nnodes(mesh)] @test cells(mesh) == [Bar2_t() for i in 1:ncells(mesh)] end @testset "gmsh - square with triangles" begin path = joinpath(tempdir, "mesh.msh") Bcube.gen_rectangle_mesh( path, :tri; nx = 4, ny = 4, lx = 1.0, ly = 1.0, xc = 0.5, yc = 0.5, ) mesh = read_msh(path) @test topodim(mesh) === 2 @test spacedim(mesh) === 2 @test has_cells(mesh) === true @test has_nodes(mesh) === true @test has_nodes(mesh) === has_entities(mesh, :node) @test has_vertices(mesh) === has_entities(mesh, :vertex) @test has_edges(mesh) === has_entities(mesh, :edge) @test has_faces(mesh) === has_entities(mesh, :face) @test has_cells(mesh) === has_entities(mesh, :cell) @test has_cells(mesh) === true @test has_nodes(mesh) === true @test nnodes(mesh) === 20 @test ncells(mesh) === 26 @test nnodes(mesh) === n_entities(mesh, :node) @test nvertices(mesh) === n_entities(mesh, :vertex) @test nedges(mesh) === n_entities(mesh, :edge) @test nfaces(mesh) === n_entities(mesh, :face) @test ncells(mesh) === n_entities(mesh, :cell) @test nodes(mesh) == [Node_t() for i in 1:nnodes(mesh)] @test cells(mesh) == [Tri3_t() for i in 1:ncells(mesh)] @test boundary_tag(mesh, "South") == 1 && boundary_tag(mesh, "East") == 2 && boundary_tag(mesh, "North") == 3 && boundary_tag(mesh, "West") == 4 @test boundary_names(mesh)[1] == "South" && boundary_names(mesh)[2] == "East" && boundary_names(mesh)[3] == "North" && boundary_names(mesh)[4] == "West" ref_nodes_south = Set([1, 5, 6, 2]) ref_nodes_east = Set([3, 8, 7, 2]) ref_nodes_north = Set([4, 10, 9, 3]) ref_nodes_west = Set([4, 12, 11, 1]) @test Set(absolute_indices(mesh, :node)[boundary_nodes(mesh, 1)]) == ref_nodes_south @test Set(absolute_indices(mesh, :node)[boundary_nodes(mesh, 2)]) == ref_nodes_east @test Set(absolute_indices(mesh, :node)[boundary_nodes(mesh, 3)]) == ref_nodes_north @test Set(absolute_indices(mesh, :node)[boundary_nodes(mesh, 4)]) == ref_nodes_west for tag in 1:4 _nodes = [ i for face in boundary_faces(mesh, tag) for i in connectivities_indices(mesh, :f2n)[face] ] if tag == 1 (@test Set(absolute_indices(mesh, :node)[_nodes]) == ref_nodes_south) else nothing end if tag == 2 (@test Set(absolute_indices(mesh, :node)[_nodes]) == ref_nodes_east) else nothing end if tag == 3 (@test Set(absolute_indices(mesh, :node)[_nodes]) == ref_nodes_north) else nothing end if tag == 4 (@test Set(absolute_indices(mesh, :node)[_nodes]) == ref_nodes_west) else nothing end end # for (tag,name) in boundary_names(mesh) # @show tag,name # for face in boundary_faces(mesh)[tag] # #@show connectivities_indices(mesh,:f2n)[face] # @show [coordinates(mesh,i) for i in connectivities_indices(mesh,:f2n)[face]] # end # @show [coordinates(mesh,i) for i in boundary_nodes(mesh,tag)] # end @testset "gmsh - autocompute space dim" begin # Line order 1 path = joinpath(tempdir, "mesh.msh") Bcube.gen_line_mesh(path; nx = 11, lx = 2.0) mesh = read_msh(path) @test spacedim(mesh) === 1 mesh = read_msh(path, 3) # without autocompute @test spacedim(mesh) === 3 # Square tri path = joinpath(tempdir, "mesh.msh") Bcube.gen_rectangle_mesh( path, :tri; nx = 4, ny = 4, lx = 1.0, ly = 1.0, xc = 0.5, yc = 0.5, ) mesh = read_msh(path) @test spacedim(mesh) === 2 mesh = read_msh(path, 3) # without autocompute @test spacedim(mesh) === 3 # Sphere path = joinpath(tempdir, "mesh.msh") Bcube.gen_sphere_mesh(path) mesh = read_msh(path) @test spacedim(mesh) === 3 end end @testset "gmsh - generators" begin basename = "gmsh_line_mesh" path = joinpath(tempdir, basename * ".msh") n_partitions = 2 # with `3`, the result is not deterministic... gen_line_mesh( path; nx = 12, n_partitions = n_partitions, split_files = true, create_ghosts = true, ) for i in 1:n_partitions fname = basename * "_$i.msh" @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) end # gen_mesh_around_disk fname = "gmsh_mesh_around_disk_tri.msh" Bcube.gen_mesh_around_disk(joinpath(tempdir, fname), :tri; nθ = 30, nr = 10) @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) fname = "gmsh_mesh_around_disk_quad.msh" Bcube.gen_mesh_around_disk(joinpath(tempdir, fname), :quad; nθ = 30, nr = 10) @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) # gen_mesh_around_disk fname = "gmsh_rectangle_mesh_with_tri_and_quad.msh" Bcube.gen_rectangle_mesh_with_tri_and_quad( joinpath(tempdir, fname); nx = 5, ny = 6, lx = 2, ly = 3, ) @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) # gen_disk_mesh fname = "gmsh_disk_mesh.msh" Bcube.gen_disk_mesh(joinpath(tempdir, fname)) @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) # gen_star_disk_mesh fname = "gmsh_star_disk_mesh.msh" Bcube.gen_star_disk_mesh(joinpath(tempdir, fname), 0.1, 7; nθ = 100) @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) # gen_cylinder_shell_mesh fname = "gmsh_cylinder_shell_mesh.msh" Bcube.gen_cylinder_shell_mesh(joinpath(tempdir, fname), 30, 10) @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
3604
@testset "mesh" begin m = basic_mesh() @test topodim(m) === 2 @test spacedim(m) === 2 @test topodim(m, :cell) === 2 @test topodim(m, :face) === 1 @test topodim(m, :edge) === 1 @test topodim(m, :node) === 0 @test topodim(m, :vertex) === 0 @test get_nodes(m)[6] == get_nodes(m, 6) @test get_nodes(m, 7) == Node([2.0, 0.0]) @test connectivities_indices(m, :c2n) == indices(connectivities(m, :c2n)) #test iterator c2n = indices(connectivities(m, :c2n)) c = cells(m) for (i, (_c, _c2n)) in enumerate(zip(c, c2n)) i == 1 ? (@test (i, _c, _c2n) == (1, Quad4_t(), [1, 2, 6, 5])) : nothing i == 2 ? (@test (i, _c, _c2n) == (2, Quad4_t(), [2, 3, 7, 6])) : nothing i == 3 ? (@test (i, _c, _c2n) == (3, Tri3_t(), [3, 4, 7])) : nothing end #test get_coords @test get_coords.(get_nodes(m, c2n[2])) == [[1.0, 1.0], [2.0, 1.0], [2.0, 0.0], [1.0, 0.0]] # test cell->face connectivities c2f = indices(connectivities(m, :c2f)) @test from(connectivities(m, :c2f)) === :cell @test to(connectivities(m, :c2f)) === :face @test by(connectivities(m, :c2f)) === nothing @test nlayers(connectivities(m, :c2f)) === nothing @test c2f[1] == [1, 2, 3, 4] && c2f[2] == [5, 6, 7, 2] && c2f[3] == [8, 9, 6] # test face->cell connectivities f2c = indices(connectivities(m, :f2c)) @test from(connectivities(m, :f2c)) === :face @test to(connectivities(m, :f2c)) === :cell @test by(connectivities(m, :f2c)) === nothing @test nlayers(connectivities(m, :f2c)) === nothing @test f2c[1] == [1] && f2c[2] == [1, 2] && f2c[3] == [1] && f2c[4] == [1] && f2c[5] == [2] && f2c[6] == [2, 3] && f2c[7] == [2] && f2c[8] == [3] && f2c[9] == [3] # test face->node connectivities f2n = indices(connectivities(m, :f2n)) @test from(connectivities(m, :f2n)) === :face @test to(connectivities(m, :f2n)) === :node @test by(connectivities(m, :f2n)) === nothing @test nlayers(connectivities(m, :f2n)) === nothing @test f2n[1] == [1, 2] && f2n[2] == [2, 6] && f2n[3] == [6, 5] && f2n[4] == [5, 1] && f2n[5] == [2, 3] && f2n[6] == [3, 7] && f2n[7] == [7, 6] && f2n[8] == [3, 4] && f2n[9] == [4, 7] f = faces(m) @test all([typeof(x) === Bar2_t for x in f]) # test face orientation @test oriented_cell_side(c[1], c2n[1], f2n[2]) === 2 # low-level interface @test oriented_cell_side(c[2], c2n[2], f2n[2]) === -4 @test oriented_cell_side(m, 1, 2) === 2 # high-level interface @test oriented_cell_side(m, 1, 2) === 2 @test oriented_cell_side(m, 1, 9) === 0 # Inner and outer faces @test inner_faces(m) == [2, 6] @test outer_faces(m) == [1, 3, 4, 5, 7, 8, 9] c2c = connectivity_cell2cell_by_faces(m) @test c2c[1] == [2] && c2c[2] == [1, 3] && c2c[3] == [2] # Test connectivity cell2cell by nodes # Checked using `Set` because order is not relevant mesh = rectangle_mesh(4, 4) c2c = connectivity_cell2cell_by_nodes(mesh) @test Set(c2c[1]) == Set([4, 2, 5]) @test Set(c2c[2]) == Set([1, 4, 5, 3, 6]) @test Set(c2c[3]) == Set([6, 2, 5]) @test Set(c2c[4]) == Set([1, 2, 5, 7, 8]) @test Set(c2c[5]) == Set([1, 2, 4, 6, 8, 9, 3, 7]) @test Set(c2c[6]) == Set([9, 3, 5, 8, 2]) @test Set(c2c[7]) == Set([4, 8, 5]) @test Set(c2c[8]) == Set([5, 6, 9, 7, 4]) @test Set(c2c[9]) == Set([6, 5, 8]) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
994
@testset "mesh generator" begin # These are more "functionnal tests" than "unit test" : we check that no error is committed m = basic_mesh() @test nnodes(m) == 7 @test ncells(m) == 3 m = one_cell_mesh(:line) @test nnodes(m) == 2 @test ncells(m) == 1 m = one_cell_mesh(:line; order = 2) @test nnodes(m) == 3 @test ncells(m) == 1 n = 10 m = line_mesh(n) @test nnodes(m) == n @test ncells(m) == n - 1 nx = 10 ny = 10 m = rectangle_mesh(nx, ny) @test nnodes(m) == nx * ny @test ncells(m) == (nx - 1) * (ny - 1) nx = 3 ny = 4 nz = 5 mesh = hexa_mesh(3, 4, 5) @test nnodes(mesh) == nx * ny * nz @test ncells(mesh) == (nx - 1) * (ny - 1) * (nz - 1) # Not working (maybe the structure comparison is too hard, # or maybe it does not compare object properties but objects themselves) #@test ncube_mesh([n]) == line_mesh(n) #@test ncube_mesh([nx, ny]) == rectangle_mesh(nx, ny) end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
363
@testset "Transformation" begin @testset "Translation" begin u = [2, 0] T = Translation(u) x = [3, 1] @test all(T(x) .== [5, 1]) end @testset "Rotation" begin rot = Rotation([0, 0, 1], π / 4) x = [3.0, 0, 0] x_rot_ref = 3√(2) / 2 .* [1, 1, 0] @test all(rot(x) .≈ x_rot_ref) end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
12192
@testset "Algebra" begin @testset "Gradient" begin # We test the mapping of a gradient. The idea is to compute the integral of a function `f` whose # gradient is constant. Then the result must be this constant multiplied by the cell area. # But since we need to input a `ReferenceFunction`, we need to build `f ∘ F` where `F` is the mapping. # We also need a geometric function to compute the area of a convex quad. function convex_quad_area(cnodes) n1, n2, n3, n4 = cnodes return ( abs((n1.x[1] - n3.x[1]) * (n2.x[2] - n4.x[2])) + abs((n2.x[1] - n4.x[1]) * (n1.x[2] - n3.x[2])) ) / 2 end cnodes = [Node([0.0, 0.0]), Node([1.0, 0.0]), Node([2.0, 1.5]), Node([1.0, 1.5])] celltypes = [Quad4_t()] cell2node = Connectivity([4], [1, 2, 3, 4]) mesh = Mesh(cnodes, celltypes, cell2node) # mesh = one_cell_mesh(:quad) c2n = connectivities_indices(mesh, :c2n) icell = 1 cnodes = get_nodes(mesh, c2n[icell]) ctype = cells(mesh)[icell] cInfo = CellInfo(mesh, icell) qDegree = Val(2) # Scalar test : gradient of scalar `f` in physical coordinates is [1, 2] function f1(ξ) x, y = Bcube.mapping(ctype, cnodes, ξ) return x + 2y end g = ReferenceFunction(f1) _g = Bcube.materialize(∇(g), cInfo) res = integrate_on_ref_element(_g, cInfo, Quadrature(qDegree)) @test all(isapprox.(res ./ convex_quad_area(cnodes), [1.0, 2.0])) # Vector test : gradient of vector `f` in physical coordinates is [[1,2],[3,4]] function f2(ξ) x, y = Bcube.mapping(ctype, cnodes, ξ) return [x + 2y, 3x + 4y] end g = ReferenceFunction(f2) _g = Bcube.materialize(∇(g), cInfo) res = integrate_on_ref_element(_g, cInfo, Quadrature(qDegree)) @test all(isapprox.(res ./ convex_quad_area(cnodes), [1.0 2.0; 3.0 4.0])) # Gradient of scalar PhysicalFunction # Physical function is [x,y] -> x so its gradient is [x,y] -> [1, 0] # so the integral is simply the volume of Ω mesh = one_cell_mesh(:quad) translate!(mesh, SA[-0.5, 1.0]) # the translation vector can be anything scale!(mesh, 2.0) dΩ = Measure(CellDomain(mesh), 1) @test compute(∫(∇(PhysicalFunction(x -> x[1])) ⋅ [1, 1])dΩ)[1] == 16.0 # Gradient of a vector PhysicalFunction mesh = one_cell_mesh(:quad) translate!(mesh, SA[π, -3.14]) # the translation vector can be anything scale!(mesh, 2.0) sizeU = spacedim(mesh) U = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh; sizeU) V = TestFESpace(U) _f = x -> SA[2 * x[1]^2, x[1] * x[2]] f = PhysicalFunction(_f, sizeU) ∇f = PhysicalFunction(x -> ForwardDiff.jacobian(_f, x), (sizeU, spacedim(mesh))) dΩ = Measure(CellDomain(mesh), 3) l(v) = ∫(tr(∇(f) - ∇f) ⋅ v)dΩ _a = assemble_linear(l, V) @test all(isapprox.(_a, [0.0, 0.0, 0.0, 0.0]; atol = 100 * eps())) # Shape functions gradient mesh = one_cell_mesh(:line) ctype = first(Bcube.cells(mesh)) cnodes = get_nodes(mesh) fs = FunctionSpace(:Lagrange, 2) n1 = Val(1) n2 = Val(2) ∇sca = Bcube.∂λξ_∂x(fs, n1, ctype, cnodes, [0.0]) ∇vec = Bcube.∂λξ_∂x(fs, n2, ctype, cnodes, [0.0]) @test all(isapprox.(∇sca, ∇vec[1:3, 1, 1])) @test all(isapprox.(∇sca, ∇vec[4:6, 2, 1])) @testset "TangentialGradient" begin # Topodim = 1 ctype = Bar2_t() nodes = [Node([-1.0]), Node([1.0])] celltypes = [ctype] cell2node = Bcube.Connectivity([2], [1, 2]) mesh = Bcube.Mesh(nodes, celltypes, cell2node) nodes_hypersurface = [Node([0.0, -1.0]), Node([0.0, 1.0])] celltypes = [ctype] cell2node = Bcube.Connectivity([2], [1, 2]) mesh_hypersurface = Bcube.Mesh(nodes_hypersurface, celltypes, cell2node) fs = FunctionSpace(:Lagrange, 1) n = Val(1) ∇_volumic = Bcube.∂λξ_∂x(fs, n, ctype, nodes, [0.0]) ∇_hyper = Bcube.∂λξ_∂x_hypersurface(fs, n, ctype, nodes_hypersurface, [0.0]) @test all(isapprox.(∇_volumic, ∇_hyper[:, 2])) h(x) = x[1] ∇_volumic = Bcube.∂fξ_∂x(h, n, ctype, nodes, [0.0]) ∇_hyper = Bcube.∂fξ_∂x_hypersurface(h, n, ctype, nodes_hypersurface, [0.0]) @test ∇_volumic[1] == ∇_hyper[2] # Topodim = 2 function rotMat(θx, θy, θz) Rx = [ 1.0 0.0 0.0 0.0 cos(θx) sin(θx) 0.0 (-sin(θx)) cos(θx) ] Ry = [ cos(θy) 0.0 (-sin(θy)) 0.0 1.0 0.0 sin(θy) 0.0 cos(θy) ] Rz = [ cos(θz) sin(θz) 0.0 -sin(θz) cos(θz) 0.0 0.0 0.0 1.0 ] return Rx * Ry * Rz end R = rotMat(π / 2, π / 3, π / 4) ctype = Quad4_t() nodes = [Node([-1.0, -1.0]), Node([1.0, -1.0]), Node([1.0, 1.0]), Node([-1.0, 1.0])] celltypes = [ctype] cell2node = Bcube.Connectivity([4], [1, 2, 3, 4]) mesh = Bcube.Mesh(nodes, celltypes, cell2node) nodes_hypersurface = [Node(R * [get_coords(n)..., 0.0]) for n in get_nodes(mesh)] mesh_hypersurface = Bcube.Mesh(nodes_hypersurface, celltypes, cell2node) fs = FunctionSpace(:Lagrange, 1) n = Val(1) ∇_volumic = Bcube.∂λξ_∂x(fs, n, ctype, nodes, [0.0, 0.0]) ∇_hyper = Bcube.∂λξ_∂x_hypersurface(fs, n, ctype, nodes_hypersurface, [0.0, 0.0]) ∇_volumic = transpose(hcat([R * [row..., 0] for row in eachrow(∇_volumic)]...)) @test all(isapprox.(vec(∇_volumic), vec(∇_hyper), atol = 1e-16)) n = Val(2) h2(x) = x ∇_volumic = Bcube.∂fξ_∂x(h2, n, ctype, nodes, [0.0, 0.0]) ∇_hyper = Bcube.∂fξ_∂x_hypersurface(h2, n, ctype, nodes_hypersurface, [0.0, 0.0]) ∇_volumic = transpose(hcat([R * [row..., 0] for row in eachrow(∇_volumic)]...)) @test all(isapprox.(vec(∇_volumic), vec(∇_hyper), atol = 1e-15)) end @testset "AbstractLazy" begin mesh = one_cell_mesh(:quad) scale!(mesh, 3.0) translate!(mesh, [4.0, 0.0]) U_sca = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh) U_vec = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh; size = 2) V_sca = TestFESpace(U_sca) V_vec = TestFESpace(U_vec) u_sca = FEFunction(U_sca) u_vec = FEFunction(U_vec) dΩ = Measure(CellDomain(mesh), 2) projection_l2!(u_sca, PhysicalFunction(x -> 3 * x[1] - 4x[2]), dΩ) projection_l2!( u_vec, PhysicalFunction(x -> SA[2x[1] + 5x[2], 4x[1] - 3x[2]]), dΩ, ) l1(v) = ∫((∇(π * u_sca) ⋅ ∇(2 * u_sca)) ⋅ v)dΩ l2(v) = ∫((∇(u_sca) ⋅ ∇(u_sca)) ⋅ v)dΩ a1_sca = assemble_linear(l1, V_sca) a2_sca = assemble_linear(l2, V_sca) @test all(a1_sca .≈ (2π .* a2_sca)) V_vec = TestFESpace(U_vec) l1_vec(v) = ∫((∇(π * u_vec) * u_vec) ⋅ v)dΩ l2_vec(v) = ∫((∇(u_vec) * u_vec) ⋅ v)dΩ a1_vec = assemble_linear(l1_vec, V_vec) a2_vec = assemble_linear(l2_vec, V_vec) @test all(a1_vec .≈ (π .* a2_vec)) # Testing without assemble_*linear θ = π / 5 s = 3 t = SA[-1, 2] R = SA[cos(θ) -sin(θ); sin(θ) cos(θ)] mesh = one_cell_mesh(:quad) transform!(mesh, x -> R * (s .* x .+ t)) # scale, translate and rotate # Select a cell and get its info c = CellInfo(mesh, 1) cnodes = nodes(c) ctype = Bcube.celltype(c) F = Bcube.mapping(ctype, cnodes) # tJinv = transpose(R ./ s) # if we want the analytic one... tJinv(ξ) = transpose(Bcube.mapping_jacobian_inv(ctype, cnodes, ξ)) # Test 1 u1 = PhysicalFunction(x -> x[1]) u2 = PhysicalFunction(x -> x[2]) u_a = u1 * u1 + 2 * u1 * u2 + u2 * u2 * u2 u_b = PhysicalFunction(x -> x[1]^2 + 2 * x[1] * x[2] + x[2]^3) ∇u_ana = x -> SA[2 * (x[1] + x[2]); 2 * x[1] + 3 * x[2]^2] ξ = CellPoint(SA[0.5, -0.1], c, ReferenceDomain()) x = change_domain(ξ, Bcube.PhysicalDomain()) ∇u = ∇u_ana(get_coords(x)) ∇u_a_ref = Bcube.materialize(∇(u_a), ξ) ∇u_b_ref = Bcube.materialize(∇(u_b), ξ) ∇u_a_phy = Bcube.materialize(∇(u_a), x) ∇u_b_phy = Bcube.materialize(∇(u_b), x) @test all(∇u_a_ref .≈ ∇u) @test all(∇u_b_ref .≈ ∇u) @test all(∇u_a_phy .≈ ∇u) @test all(∇u_b_phy .≈ ∇u) # Test 2 u1 = ReferenceFunction(ξ -> ξ[1]) u2 = ReferenceFunction(ξ -> ξ[2]) u_a = u1 * u1 + 2 * u1 * u2 + u2 * u2 * u2 u_b = ReferenceFunction(ξ -> ξ[1]^2 + 2 * ξ[1] * ξ[2] + ξ[2]^3) ∇u_ana = ξ -> SA[2 * (ξ[1] + ξ[2]); 2 * ξ[1] + 3 * ξ[2]^2] x = CellPoint(SA[0.5, -0.1], c, Bcube.PhysicalDomain()) ξ = change_domain(x, ReferenceDomain()) # not always possible, but ok of for quad ∇u = ∇u_ana(get_coords(ξ)) _tJinv = tJinv(get_coords(ξ)) ∇u_a_ref = Bcube.materialize(∇(u_a), ξ) ∇u_b_ref = Bcube.materialize(∇(u_b), ξ) ∇u_a_phy = Bcube.materialize(∇(u_a), x) ∇u_b_phy = Bcube.materialize(∇(u_b), x) @test all(∇u_a_ref .≈ _tJinv * ∇u) @test all(∇u_b_ref .≈ _tJinv * ∇u) @test all(∇u_a_phy .≈ _tJinv * ∇u) @test all(∇u_b_phy .≈ _tJinv * ∇u) # Test 3 u_phy = PhysicalFunction(x -> x[1]^2 + 2 * x[1] * x[2] + x[2]^3) u_ref = ReferenceFunction(ξ -> ξ[1]^2 + 2 * ξ[1] * ξ[2] + ξ[2]^3) ∇u_ana = t -> SA[2 * (t[1] + t[2]); 2 * t[1] + 3 * t[2]^2] ξ = CellPoint(SA[0.5, -0.1], c, ReferenceDomain()) x = change_domain(ξ, Bcube.PhysicalDomain()) ∇u_ref = ∇u_ana(get_coords(ξ)) ∇u_phy = ∇u_ana(get_coords(x)) _tJinv = tJinv(get_coords(ξ)) @test all(Bcube.materialize(∇(u_phy + u_ref), ξ) .≈ ∇u_phy + _tJinv * ∇u_ref) @test all(Bcube.materialize(∇(u_phy + u_ref), x) .≈ ∇u_phy + _tJinv * ∇u_ref) end end @testset "algebra" begin f = PhysicalFunction(x -> 0) a = Bcube.NullOperator() @test dcontract(a, a) == a @test dcontract(rand(), a) == a @test dcontract(a, rand()) == a @test dcontract(f, a) == a @test dcontract(a, f) == a end @testset "UniformScaling" begin mesh = one_cell_mesh(:quad) U = TrialFESpace(FunctionSpace(:Lagrange, 1), mesh; size = 2) V = TestFESpace(U) p = PhysicalFunction(x -> 3) dΩ = Measure(CellDomain(mesh), 1) l(v) = ∫((p * I) ⊡ ∇(v))dΩ a = assemble_linear(l, V) @test all(a .≈ [-3.0, 3.0, -3.0, 3.0, -3.0, -3.0, 3.0, 3.0]) end @testset "Pow" begin mesh = one_cell_mesh(:quad) u = PhysicalFunction(x -> 3.0) v = PhysicalFunction(x -> 2.0) cinfo = CellInfo(mesh, 1) cpoint = CellPoint(SA[0.1, 0.3], cinfo, ReferenceDomain()) @test Bcube.materialize(u * u, cinfo)(cpoint) ≈ 9 @test Bcube.materialize(u^2, cinfo)(cpoint) ≈ 9 @test Bcube.materialize(u^v, cinfo)(cpoint) ≈ 9 a = Bcube.NullOperator() @test a^u == a end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
code
2967
@testset "vtk" begin @testset "write_vtk" begin mesh = rectangle_mesh(10, 10; xmax = 2π, ymax = 2π) val_sca = var_on_vertices(PhysicalFunction(x -> cos(x[1]) * sin(x[2])), mesh) val_vec = var_on_vertices(PhysicalFunction(x -> SA[cos(x[1]), sin(x[2])]), mesh) basename = "write_vtk_rectangle" write_vtk( joinpath(tempdir, basename), 1, 0.0, mesh, Dict( "u" => (val_sca, WriteVTK.VTKPointData()), "v" => (transpose(val_vec), WriteVTK.VTKPointData()), ), ) fname = Bcube._build_fname_with_iterations(basename, 1) * ".vtu" @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) basename = "write_vtk_mesh" write_vtk(joinpath(tempdir, basename), basic_mesh()) fname = Bcube._build_fname_with_iterations(basename, 1) * ".vtu" @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) end @testset "write_vtk_lagrange" begin mesh = rectangle_mesh(6, 7; xmin = -1, xmax = 1.0, ymin = -1, ymax = 1.0) u = FEFunction(TrialFESpace(FunctionSpace(:Lagrange, 4), mesh)) projection_l2!(u, PhysicalFunction(x -> x[1]^2 + x[2]^2), mesh) vars = Dict("u" => u, "grad_u" => ∇(u)) # bmxam: for some obscur reason, order 3 and 5 lead to different sha1sum # when running in standard mode or in test mode... for mesh_degree in (1, 2, 4) basename = "write_vtk_lagrange_deg$(mesh_degree)" Bcube.write_vtk_lagrange( joinpath(tempdir, basename), vars, mesh; mesh_degree, discontinuous = false, vtkversion = v"1.0", ) # Check fname = basename * ".vtu" @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) end # add var MeshCellData : quad = Quadrature(4) dΩ = Measure(CellDomain(mesh), quad) vars["umean"] = Bcube.cell_mean(u, dΩ) basename = "write_vtk_lagrange_deg4_with_mean" Bcube.write_vtk_lagrange( joinpath(tempdir, basename), vars, mesh; mesh_degree = 4, discontinuous = false, vtkversion = v"1.0", ) # Check fname = basename * ".vtu" @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) basename = "write_vtk_lagrange_deg4_dg_with_mean" Bcube.write_vtk_lagrange( joinpath(tempdir, basename), vars, mesh; mesh_degree = 4, discontinuous = true, vtkversion = v"1.0", ) # Check fname = basename * ".vtu" @test fname2sum[fname] == bytes2hex(open(sha1, joinpath(tempdir, fname))) end end
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
3571
# Bcube.jl [![](https://img.shields.io/badge/docs-release-blue.svg)](https://bcube-project.github.io/Bcube.jl) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://bcube-project.github.io/Bcube.jl/dev) [![codecov](https://codecov.io/gh/bcube-project/Bcube.jl/branch/main/graph/badge.svg)](https://app.codecov.io/gh/bcube-project/Bcube.jl) [![Build Status](https://github.com/bcube-project/Bcube.jl/workflows/CI/badge.svg)](https://github.com/bcube-project/Bcube.jl/actions) Bcube is a Julia library providing tools for the spatial discretization of partial differential equation(s) (PDE). It offers a high-level API to discretize linear or non-linear problems on unstructured mesh using continuous or discontinuous finite elements (FEM - DG). The main features are: - high-level api : `a(u, v) = ∫(η * ∇(u) ⋅ ∇(v))dΩ` - 1D, 2D, 3D unstructured mesh with high-order geometrical elements (gmsh or cgns format) - Lagrange (continuous & discontinuous) and Taylor (discontinuous) finite elements (line, quad, tri, hexa, tetra, penta, pyra) - arbitrary order for hypercube Lagrange elements Browse the [documentation](https://bcube-project.github.io/Bcube.jl) for more information about the code architecture and API. Commented tutorials as well as various examples can be found in the dedicated project [BcubeTutorials.jl](https://github.com/bcube-project/BcubeTutorials.jl). ## Installation Bcube can be added to your Julia environment with this simple line : ```julia-repl pkg> add Bcube ``` ## Alternatives Numerous FEM-DG Julia packages are available, here is a non-exhaustive list; - [Gridap.jl](https://github.com/gridap/Gridap.jl) (which has greatly influenced the development of Bcube) - [Ferrite.jl](https://github.com/Ferrite-FEM/Ferrite.jl) - [Trixi.jl](https://github.com/trixi-framework/Trixi.jl) ## Contribution Any contribution(s) and/or remark(s) are welcome! Don't hesitate to open an issue to ask a question or signal a bug. PRs improving the code (new features, new elements, fixing bugs, ...) will be greatly appreciated. ## Gallery | [Helmholtz equation](https://bcube-project.github.io/BcubeTutorials.jl/dev/tutorial/helmholtz) | [Phase field solidification](https://bcube-project.github.io/BcubeTutorials.jl/dev/tutorial/phase_field_supercooled) | [Linear transport equation](https://bcube-project.github.io/BcubeTutorials.jl/dev/tutorial/linear_transport) | |-|-|-| | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/helmholtz_x21_y21_vp6.png?raw=true) | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/phase-field-supercooled-rectangle.gif?raw=true) | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/linear_transport.gif?raw=true) | | [Heat equation on a sphere](https://bcube-project.github.io/BcubeTutorials.jl/stable/example/heat_equation_sphere) | [Transport equation on hypersurfaces](https://bcube-project.github.io/BcubeTutorials.jl/stable/example/transport_hypersurface) | [Linear thermo-elasticity](https://bcube-project.github.io/BcubeTutorials.jl/stable/example/linear_thermoelasticity) | | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/heat_equation_sphere.gif?raw=true) | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/transport-torus-mesh2-degree1.gif?raw=true) | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/thermo_elasticity.gif?raw=true) | ## Authors Ghislain Blanchard, Lokman Bennani and Maxime Bouyges
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
3102
```@meta CurrentModule = Bcube ``` # Bcube.jl Bcube is a Julia library providing tools for the spatial discretization of partial differential equation(s) (PDE). It offers a high-level API to discretize linear or non-linear problems on unstructured mesh using continuous or discontinuous finite elements (FEM - DG). The main features are: - high-level api : `a(u, v) = ∫(η * ∇(u) ⋅ ∇(v))dΩ` - 1D, 2D, 3D unstructured mesh with high-order geometrical elements (gmsh format) - Lagrange (continuous & discontinuous) and Taylor (discontinuous) finite elements (line, quad, tri, hexa, penta) - arbitrary order for hypercube Lagrange elements Commented tutorials as well as various examples can be found in the dedicated project [BcubeTutorials.jl](https://github.com/bcube-project/BcubeTutorials.jl). ## Installation Bcube can be added to your Julia environment with this simple line : ```julia-repl pkg> add https://github.com/bcube-project/Bcube.jl ``` ## Alternatives Numerous FEM-DG Julia packages are available, here is a non-exhaustive list; - [Gridap.jl](https://github.com/gridap/Gridap.jl) (which has greatly influenced the development of Bcube) - [Ferrite.jl](https://github.com/Ferrite-FEM/Ferrite.jl) - [Trixi.jl](https://github.com/trixi-framework/Trixi.jl) ## Contribution Any contribution(s) and/or remark(s) are welcome! Don't hesitate to open an issue to ask a question or signal a bug. PRs improving the code (new features, new elements, fixing bugs, ...) will be greatly appreciated. ## Gallery | [Helmholtz equation](https://bcube-project.github.io/BcubeTutorials.jl/stable/tutorial/helmholtz) | [Phase field solidification](https://bcube-project.github.io/BcubeTutorials.jl/stable/tutorial/phase_field_supercooled) | [Linear transport equation](https://bcube-project.github.io/BcubeTutorials.jl/stable/tutorial/linear_transport) | | :----------------: | :------------------------: | :-----------------------: | | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/helmholtz_x21_y21_vp6.png?raw=true) | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/phase-field-supercooled-rectangle.gif?raw=true) | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/linear_transport.gif?raw=true) | | [Heat equation on a sphere](https://bcube-project.github.io/BcubeTutorials.jl/stable/example/heat_equation_sphere) | [Transport equation on hypersurfaces](https://bcube-project.github.io/BcubeTutorials.jl/stable/example/transport_hypersurface) | [Linear thermo-elasticity](https://bcube-project.github.io/BcubeTutorials.jl/stable/example/linear_thermoelasticity) | | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/heat_equation_sphere.gif?raw=true) | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/transport-torus-mesh2-degree1.gif?raw=true) | ![](https://github.com/bcube-project/BcubeTutorials.jl/blob/main/docs/src/assets/thermo_elasticity.gif?raw=true) | ## Authors Ghislain Blanchard, Lokman Bennani and Maxime Bouyges
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
176
# Degree of freedom ## Assembler ```@autodocs Modules = [Bcube] Pages = ["assembler.jl"] ``` ## DofHandler ```@autodocs Modules = [Bcube] Pages = ["dofhandler.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
261
# Integration ## Measure ```@autodocs Modules = [Bcube] Pages = ["measure.jl"] ``` ## Integration methods ```@autodocs Modules = [Bcube] Pages = ["integration.jl"] ``` ## Quadrature rules ```@autodocs Modules = [Bcube] Pages = ["quadrature.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
85
# Finite element spaces ```@autodocs Modules = [Bcube] Pages = ["fespace.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
2171
# Function spaces # Generic ```@autodocs Modules = [Bcube] Pages = ["function_space.jl"] ``` ## Lagrange ```@autodocs Modules = [Bcube] Pages = ["lagrange.jl"] ``` ## Taylor The `Taylor` function space corresponds to a function space where functions are approximated by a Taylor series expansion of order ``n`` in each cell: ```math \forall x \in \Omega_i,~g(x) = g(x_0) + (x - x_0) g'(x_0) + o(x) ``` where ``x_0`` is the cell center. Note that a Taylor-P0 is strictly equivalent to a 1st-order Finite Volume discretization (beware that "order" can have different meaning depending on whether one refers to the order of the function space basis or the order of the discretization method). Recall that any function space implies that any function ``g`` is interpolated by ``g(x) = \sum g_i \lambda_i(x)`` where ``\lambda_i`` are the shape functions. For a Taylor expansion, the definition of ``\lambda_i`` is not unique. For instance for the Taylor expansion of order ``1`` on a 1D line above, we may be tempted to set ``\lambda_1(x) = 1`` and ``\lambda_2(x) = (x - x_0)``. If you do so, what are the corresponding shape functions in the reference element, the ``\hat{\lambda_i}``? We immediately recover ``\hat{\lambda_1}(\hat{x}) = 1``. For ``\hat{\lambda_2}``: ```math \hat{\lambda_2}(\hat{x}) = (\lambda \circ F)(\hat{x}) = (x \rightarrow x - x_0) \circ (\hat{x} \rightarrow \frac{x_r - x_l}{2} \hat{x} + \frac{x_r + x_l}{2}) = \frac{x_r - x_l}{2} \hat{x} ``` So if you set ``\lambda_2(x) = (x - x_0)`` then ``\hat{\lambda_2}`` depends on the element length (``\Delta x = x_r-x_l``), which is pointless. So ``\lambda_2`` must be proportional to the element length to obtain a universal definition for ``\hat{\lambda_2}``. For instance, we may choose ``\lambda_2(x) = (x - x_0) / \Delta x``, leading to ``\hat{\lambda_2}(\hat{x}) = \hat{x} / 2``. But we could have chosen an other element length multiple. Don't forget that choosing ``\lambda_2(x) = (x - x_0) / \Delta x`` leads to ``g(x) = g(x_0) + \frac{x - x_0}{\Delta x} g'(x_0) Δx `` hence ``g_2 = g'(x_0) Δx`` in the interpolation. ```@autodocs Modules = [Bcube] Pages = ["taylor.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
76
# Reference shape ```@autodocs Modules = [Bcube] Pages = ["shape.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
167
# Mapping # Mappings ```@autodocs Modules = [Bcube] Pages = ["mapping.jl"] ``` # Reference to physical ```@autodocs Modules = [Bcube] Pages = ["ref2phys.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
70
# GMSH ```@autodocs Modules = [Bcube] Pages = ["gmsh_utils.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
299
# Mesh ## Entity ```@autodocs Modules = [Bcube] Pages = ["entity.jl"] ``` ## Connectivity ```@autodocs Modules = [Bcube] Pages = ["connectivity.jl"] ``` ## Mesh ```@autodocs Modules = [Bcube] Pages = ["mesh.jl"] ``` ## Domain ```@autodocs Modules = [Bcube] Pages = ["domain.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
84
# Mesh generator ```@autodocs Modules = [Bcube] Pages = ["mesh_generator.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
73
# Operators ```@autodocs Modules = [Bcube] Pages = ["operator.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git
[ "MIT" ]
0.1.14
20a56bc6d7fc2ffbea278d1f47fdfda594a01b46
docs
62
# VTK ```@autodocs Modules = [Bcube] Pages = ["vtk.jl"] ```
Bcube
https://github.com/bcube-project/Bcube.jl.git