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.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 1373 | using Test
using BlockArrays, LinearAlgebra
using Gridap, Gridap.MultiField, Gridap.Algebra
using PartitionedArrays, GridapDistributed
using GridapSolvers, GridapSolvers.BlockSolvers
function same_block_array(A,B)
map(blocks(A),blocks(B)) do A, B
t = map(partition(A),partition(B)) do A, B
A ≈ B
end
reduce(&,t)
end |> all
end
np = (2,2)
ranks = with_debug() do distribute
distribute(LinearIndices((prod(np),)))
end
model = CartesianDiscreteModel(ranks,np,(0,1,0,1),(8,8))
reffe = ReferenceFE(lagrangian,Float64,1)
V = FESpace(model,reffe)
mfs = BlockMultiFieldStyle()
Y = MultiFieldFESpace([V,V];style=mfs)
Ω = Triangulation(model)
dΩ = Measure(Ω,4)
u0 = zero(Y)
sol(x) = sum(x)
# Reference operator
a_ref((u1,u2),(v1,v2)) = ∫(u1⋅v1 + u2⋅v2)*dΩ
l_ref((v1,v2)) = ∫(sol⋅v1 + sol⋅v2)*dΩ
res_ref(u,v) = a_ref(u,v) - l_ref(v)
jac_ref(u,du,dv) = a_ref(du,dv)
op_ref = FEOperator(res_ref,jac_ref,Y,Y)
A_ref = jacobian(op_ref,u0)
b_ref = residual(op_ref,u0)
# Block operator
a(u,v) = ∫(u⋅v)*dΩ
l(v) = ∫(sol⋅v)*dΩ
res(u,v) = a(u,v) - l(v)
jac(u,du,dv) = a(du,dv)
res_blocks = collect(reshape([res,missing,missing,res],(2,2)))
jac_blocks = collect(reshape([jac,missing,missing,jac],(2,2)))
op = BlockFEOperator(res_blocks,jac_blocks,Y,Y)
A = jacobian(op,u0)
b = residual(op,u0)
@test same_block_array(A,A_ref)
@test same_block_array(b,b_ref)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 1212 | module BlockTriangularSolversTests
using BlockArrays, LinearAlgebra
using Gridap, Gridap.MultiField, Gridap.Algebra
using PartitionedArrays, GridapDistributed
using GridapSolvers, GridapSolvers.BlockSolvers
function main(distribute,parts)
ranks = distribute(LinearIndices((prod(parts),)))
model = CartesianDiscreteModel(ranks,parts,(0,1,0,1),(8,8))
reffe = ReferenceFE(lagrangian,Float64,1)
V = FESpace(model,reffe)
mfs = BlockMultiFieldStyle()
Y = MultiFieldFESpace([V,V];style=mfs)
Ω = Triangulation(model)
dΩ = Measure(Ω,4)
sol(x) = sum(x)
a((u1,u2),(v1,v2)) = ∫(u1⋅v1 + u2⋅v2 + u1⋅v2 - u2⋅v1)*dΩ
l((v1,v2)) = ∫(sol⋅v1 - sol⋅v2)*dΩ
op = AffineFEOperator(a,l,Y,Y)
A, b = get_matrix(op), get_vector(op);
# Upper
s1 = BlockTriangularSolver([LUSolver(),LUSolver()];half=:upper)
ss1 = symbolic_setup(s1,A)
ns1 = numerical_setup(ss1,A)
numerical_setup!(ns1,A)
x1 = allocate_in_domain(A); fill!(x1,0.0)
solve!(x1,ns1,b)
# Lower
s2 = BlockTriangularSolver([LUSolver(),LUSolver()];half=:lower)
ss2 = symbolic_setup(s2,A)
ns2 = numerical_setup(ss2,A)
numerical_setup!(ns2,A)
x2 = allocate_in_domain(A); fill!(x2,0.0)
solve!(x2,ns2,b)
end
end # module | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 193 | module BlockDiagonalSolversMPITests
using MPI, PartitionedArrays
include("../BlockDiagonalSolversTests.jl")
with_mpi() do distribute
BlockDiagonalSolversTests.main(distribute,(2,2))
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 199 | module BlockTriangularSolversMPITests
using MPI, PartitionedArrays
include("../BlockTriangularSolversTests.jl")
with_mpi() do distribute
BlockTriangularSolversTests.main(distribute,(2,2))
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 457 | using Test
using MPI
using GridapSolvers
function run_tests(testdir)
istest(f) = endswith(f, ".jl") && !(f=="runtests.jl")
testfiles = sort(filter(istest, readdir(testdir)))
@time @testset "$f" for f in testfiles
MPI.mpiexec() do cmd
np = 4
cmd = `$cmd -n $(np) --oversubscribe $(Base.julia_cmd()) --project=. $(joinpath(testdir, f))`
@show cmd
run(cmd)
@test true
end
end
end
# MPI tests
run_tests(@__DIR__)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 250 | module BlockDiagonalSolversSequentialTests
using PartitionedArrays
include("../BlockDiagonalSolversTests.jl")
with_debug() do distribute
BlockDiagonalSolversTests.main(distribute, (1,1))
BlockDiagonalSolversTests.main(distribute, (2,2))
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 259 | module BlockTriangularSolversSequentialTests
using PartitionedArrays
include("../BlockTriangularSolversTests.jl")
with_debug() do distribute
BlockTriangularSolversTests.main(distribute, (1,1))
BlockTriangularSolversTests.main(distribute, (2,2))
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 180 | using Test
@testset "BlockDiagonalSolvers" begin include("BlockDiagonalSolversTests.jl") end
@testset "BlockTriangularSolvers" begin include("BlockTriangularSolversTests.jl") end
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 9672 | module GMGTests
using MPI
using Test
using LinearAlgebra
using IterativeSolvers
using FillArrays
using Gridap
using Gridap.ReferenceFEs, Gridap.Algebra
using PartitionedArrays
using GridapDistributed
using GridapP4est
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers
function get_patch_smoothers(mh,tests,biform,qdegree)
patch_decompositions = PatchDecomposition(mh)
patch_spaces = PatchFESpace(tests,patch_decompositions)
nlevs = num_levels(mh)
smoothers = map(view(tests,1:nlevs-1),patch_decompositions,patch_spaces) do tests, PD, Ph
Vh = get_fe_space(tests)
Ω = Triangulation(PD)
dΩ = Measure(Ω,qdegree)
ap = (u,v) -> biform(u,v,dΩ)
patch_smoother = PatchBasedLinearSolver(ap,Ph,Vh)
return RichardsonSmoother(patch_smoother,10,0.2)
end
return smoothers
end
function get_jacobi_smoothers(mh)
nlevs = num_levels(mh)
smoothers = Fill(RichardsonSmoother(JacobiLinearSolver(),10,2.0/3.0),nlevs-1)
level_parts = view(get_level_parts(mh),1:nlevs-1)
return HierarchicalArray(smoothers,level_parts)
end
function get_bilinear_form(mh_lev,biform,qdegree)
model = get_model(mh_lev)
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
return (u,v) -> biform(u,v,dΩ)
end
function gmg_driver_from_mats(t,parts,mh,spaces,qdegree,smoothers,biform,liform,u)
tests, trials = spaces
restrictions, prolongations = setup_transfer_operators(
trials, qdegree; mode=:residual, solver=IS_ConjugateGradientSolver(;reltol=1.e-6)
)
smatrices, A, b = compute_hierarchy_matrices(trials,tests,biform,liform,qdegree)
gmg = GMGLinearSolver(
mh,smatrices,
prolongations,restrictions,
pre_smoothers=smoothers,
post_smoothers=smoothers,
coarsest_solver=LUSolver(),
maxiter=1,mode=:preconditioner
)
solver = CGSolver(gmg;maxiter=20,atol=1e-14,rtol=1.e-6,verbose=i_am_main(parts))
#solver = FGMRESSolver(5,gmg;maxiter=20,atol=1e-14,rtol=1.e-6,verbose=i_am_main(parts))
ns = numerical_setup(symbolic_setup(solver,A),A)
# Solve
tic!(t;barrier=true)
x = pfill(0.0,partition(axes(A,2)))
solve!(x,ns,b)
# Error
if !isa(u,Nothing)
model = get_model(mh,1)
Uh = get_fe_space(trials,1)
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
uh = FEFunction(Uh,x)
eh = u-uh
e_l2 = sum(∫(eh⋅eh)dΩ)
if i_am_main(parts)
println("L2 error = ", e_l2)
end
end
end
function gmg_driver_from_weakform(t,parts,mh,spaces,qdegree,smoothers,biform,liform,u)
tests, trials = spaces
restrictions, prolongations = setup_transfer_operators(
trials, qdegree; mode=:residual, solver=IS_ConjugateGradientSolver(;reltol=1.e-6)
)
A, b = with_level(mh,1) do _
model = get_model(mh,1)
U = get_fe_space(trials,1)
V = get_fe_space(tests,1)
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
al(du,dv) = biform(du,dv,dΩ)
ll(dv) = liform(dv,dΩ)
op = AffineFEOperator(al,ll,U,V)
return get_matrix(op), get_vector(op)
end
biforms = map(mhl -> get_bilinear_form(mhl,biform,qdegree),mh)
gmg = GMGLinearSolver(
mh,trials,tests,biforms,
prolongations,restrictions,
pre_smoothers=smoothers,
post_smoothers=smoothers,
coarsest_solver=LUSolver(),
maxiter=1,mode=:preconditioner
)
solver = CGSolver(gmg;maxiter=20,atol=1e-14,rtol=1.e-6,verbose=i_am_main(parts))
#solver = FGMRESSolver(5,gmg;maxiter=20,atol=1e-14,rtol=1.e-6,verbose=i_am_main(parts))
ns = numerical_setup(symbolic_setup(solver,A),A)
# Solve
x = pfill(0.0,partition(axes(A,2)))
solve!(x,ns,b)
# Error
if !isa(u,Nothing)
model = get_model(mh,1)
Uh = get_fe_space(trials,1)
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
uh = FEFunction(Uh,x)
eh = u-uh
e_l2 = sum(∫(eh⋅eh)dΩ)
if i_am_main(parts)
println("L2 error = ", e_l2)
end
end
end
function gmg_poisson_driver(t,parts,mh,order)
tic!(t;barrier=true)
u(x) = x[1] + x[2]
f(x) = -Δ(u)(x)
biform(u,v,dΩ) = ∫(∇(v)⋅∇(u))dΩ
liform(v,dΩ) = ∫(v*f)dΩ
qdegree = 2*order+1
reffe = ReferenceFE(lagrangian,Float64,order)
smoothers = get_jacobi_smoothers(mh)
tests = TestFESpace(mh,reffe,dirichlet_tags="boundary")
trials = TrialFESpace(tests,u)
spaces = tests, trials
toc!(t,"FESpaces")
tic!(t;barrier=true)
gmg_driver_from_mats(t,parts,mh,spaces,qdegree,smoothers,biform,liform,u)
toc!(t,"Solve with matrices")
tic!(t;barrier=true)
gmg_driver_from_weakform(t,parts,mh,spaces,qdegree,smoothers,biform,liform,u)
toc!(t,"Solve with weakforms")
end
function gmg_laplace_driver(t,parts,mh,order)
tic!(t;barrier=true)
α = 1.0
u(x) = x[1] + x[2]
f(x) = u(x) - α * Δ(u)(x)
biform(u,v,dΩ) = ∫(v*u)dΩ + ∫(α*∇(v)⋅∇(u))dΩ
liform(v,dΩ) = ∫(v*f)dΩ
qdegree = 2*order+1
reffe = ReferenceFE(lagrangian,Float64,order)
smoothers = get_jacobi_smoothers(mh)
tests = TestFESpace(mh,reffe,dirichlet_tags="boundary")
trials = TrialFESpace(tests,u)
spaces = tests, trials
toc!(t,"FESpaces")
tic!(t;barrier=true)
gmg_driver_from_mats(t,parts,mh,spaces,qdegree,smoothers,biform,liform,u)
toc!(t,"Solve with matrices")
tic!(t;barrier=true)
gmg_driver_from_weakform(t,parts,mh,spaces,qdegree,smoothers,biform,liform,u)
toc!(t,"Solve with weakforms")
end
function gmg_vector_laplace_driver(t,parts,mh,order)
tic!(t;barrier=true)
Dc = num_cell_dims(get_model(mh,1))
α = 1.0
u(x) = (Dc==2) ? VectorValue(x[1],x[2]) : VectorValue(x[1],x[2],x[3])
f(x) = (Dc==2) ? VectorValue(x[1],x[2]) : VectorValue(x[1],x[2],x[3])
biform(u,v,dΩ) = ∫(v⋅u)dΩ + ∫(α*∇(v)⊙∇(u))dΩ
liform(v,dΩ) = ∫(v⋅f)dΩ
qdegree = 2*order+1
reffe = ReferenceFE(lagrangian,VectorValue{Dc,Float64},order)
smoothers = get_jacobi_smoothers(mh)
tests = TestFESpace(mh,reffe,dirichlet_tags="boundary")
trials = TrialFESpace(tests,u)
spaces = tests, trials
toc!(t,"FESpaces")
tic!(t;barrier=true)
gmg_driver_from_mats(t,parts,mh,spaces,qdegree,smoothers,biform,liform,u)
toc!(t,"Solve with matrices")
tic!(t;barrier=true)
gmg_driver_from_weakform(t,parts,mh,spaces,qdegree,smoothers,biform,liform,u)
toc!(t,"Solve with weakforms")
end
function gmg_hdiv_driver(t,parts,mh,order)
tic!(t;barrier=true)
Dc = num_cell_dims(get_model(mh,1))
α = 1.0
u(x) = (Dc==2) ? VectorValue(x[1],x[2]) : VectorValue(x[1],x[2],x[3])
f(x) = (Dc==2) ? VectorValue(x[1],x[2]) : VectorValue(x[1],x[2],x[3])
biform(u,v,dΩ) = ∫(v⋅u)dΩ + ∫(α*divergence(v)⋅divergence(u))dΩ
liform(v,dΩ) = ∫(v⋅f)dΩ
qdegree = 2*(order+1)
reffe = ReferenceFE(raviart_thomas,Float64,order-1)
tests = TestFESpace(mh,reffe,dirichlet_tags="boundary")
trials = TrialFESpace(tests,u)
spaces = tests, trials
toc!(t,"FESpaces")
tic!(t;barrier=true)
smoothers = get_patch_smoothers(mh,tests,biform,qdegree)
toc!(t,"Patch Decomposition")
tic!(t;barrier=true)
gmg_driver_from_mats(t,parts,mh,spaces,qdegree,smoothers,biform,liform,u)
toc!(t,"Solve with matrices")
tic!(t;barrier=true)
gmg_driver_from_weakform(t,parts,mh,spaces,qdegree,smoothers,biform,liform,u)
toc!(t,"Solve with weakforms")
end
function gmg_multifield_driver(t,parts,mh,order)
tic!(t;barrier=true)
Dc = num_cell_dims(get_model(mh,1))
@assert Dc == 3
β = 1.0
γ = 1.0
B = VectorValue(0.0,0.0,1.0)
f = VectorValue(fill(1.0,Dc)...)
biform((u,j),(v_u,v_j),dΩ) = ∫(β*∇(u)⊙∇(v_u) -γ*(j×B)⋅v_u + j⋅v_j - (u×B)⋅v_j)dΩ
liform((v_u,v_j),dΩ) = ∫(v_u⋅f)dΩ
reffe_u = ReferenceFE(lagrangian,VectorValue{Dc,Float64},order)
tests_u = FESpace(mh,reffe_u;dirichlet_tags="boundary");
trials_u = TrialFESpace(tests_u);
reffe_j = ReferenceFE(raviart_thomas,Float64,order-1)
tests_j = FESpace(mh,reffe_j;dirichlet_tags="boundary");
trials_j = TrialFESpace(tests_j);
trials = MultiFieldFESpace([trials_u,trials_j]);
tests = MultiFieldFESpace([tests_u,tests_j]);
spaces = tests, trials
toc!(t,"FESpaces")
tic!(t;barrier=true)
qdegree = 2*(order+1)
smoothers = get_patch_smoothers(mh,tests,biform,qdegree)
toc!(t,"Patch Decomposition")
tic!(t;barrier=true)
gmg_driver_from_mats(t,parts,mh,spaces,qdegree,smoothers,biform,liform,nothing)
toc!(t,"Solve with matrices")
tic!(t;barrier=true)
gmg_driver_from_weakform(t,parts,mh,spaces,qdegree,smoothers,biform,liform,nothing)
toc!(t,"Solve with weakforms")
end
function main_gmg_driver(parts,mh,order,pde)
t = PTimer(parts,verbose=true)
if pde == :poisson
gmg_poisson_driver(t,parts,mh,order)
elseif pde == :laplace
gmg_laplace_driver(t,parts,mh,order)
elseif pde == :vector_laplace
gmg_vector_laplace_driver(t,parts,mh,order)
elseif pde == :hdiv
gmg_hdiv_driver(t,parts,mh,order)
elseif pde == :multifield
gmg_multifield_driver(t,parts,mh,order)
else
error("Unknown PDE")
end
end
function get_mesh_hierarchy(parts,nc,np_per_level)
Dc = length(nc)
domain = (Dc == 2) ? (0,1,0,1) : (0,1,0,1,0,1)
mh = CartesianModelHierarchy(parts,np_per_level,domain,nc)
return mh
end
function main(distribute,np::Integer,nc::Tuple,np_per_level::Vector)
parts = distribute(LinearIndices((np,)))
mh = get_mesh_hierarchy(parts,nc,np_per_level)
Dc = length(nc)
for pde in [:poisson,:laplace,:vector_laplace,:hdiv,:multifield]
if (pde != :multifield) || (Dc == 3)
if i_am_main(parts)
println(repeat("=",80))
println("Testing GMG with Dc=$(length(nc)), PDE=$pde")
end
order = 1
main_gmg_driver(parts,mh,order,pde)
end
end
end
end # module GMGTests | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 2084 | module IterativeSolversWrappersTests
using Test
using Gridap, Gridap.Algebra
using IterativeSolvers
using LinearAlgebra
using SparseArrays
using PartitionedArrays
using GridapDistributed
using GridapSolvers
using GridapSolvers.LinearSolvers
sol(x) = x[1] + x[2]
f(x) = -Δ(sol)(x)
function test_solver(solver,op,Uh,dΩ)
A, b = get_matrix(op), get_vector(op);
ns = numerical_setup(symbolic_setup(solver,A),A)
x = allocate_in_domain(A); fill!(x,zero(eltype(x)))
solve!(x,ns,b)
u = interpolate(sol,Uh)
uh = FEFunction(Uh,x)
eh = uh - u
E = sum(∫(eh*eh)*dΩ)
@test E < 1.e-6
end
function get_mesh(parts,np)
Dc = length(np)
if Dc == 2
domain = (0,1,0,1)
nc = (8,8)
else
@assert Dc == 3
domain = (0,1,0,1,0,1)
nc = (8,8,8)
end
if prod(np) == 1
model = CartesianDiscreteModel(domain,nc)
else
model = CartesianDiscreteModel(parts,np,domain,nc)
end
return model
end
function main(distribute,np)
parts = distribute(LinearIndices((prod(np),)))
model = get_mesh(parts,np)
verbose = i_am_main(parts)
order = 1
qorder = order*2 + 1
reffe = ReferenceFE(lagrangian,Float64,order)
Vh = TestFESpace(model,reffe;conformity=:H1,dirichlet_tags="boundary")
Uh = TrialFESpace(Vh,sol)
u = interpolate(sol,Uh)
Ω = Triangulation(model)
dΩ = Measure(Ω,qorder)
a(u,v) = ∫(∇(v)⋅∇(u))*dΩ
l(v) = ∫(v⋅f)*dΩ
op = AffineFEOperator(a,l,Uh,Vh)
verbose && println("> Testing CG")
cg_solver = IS_ConjugateGradientSolver(;maxiter=100,reltol=1.e-12,verbose=verbose)
test_solver(cg_solver,op,Uh,dΩ)
if prod(np) == 1
verbose && println("> Testing SSOR")
ssor_solver = IS_SSORSolver(2.0/3.0;maxiter=1000)
test_solver(ssor_solver,op,Uh,dΩ)
verbose && println("> Testing GMRES")
gmres_solver = IS_GMRESSolver(;maxiter=100,reltol=1.e-12,verbose=verbose)
test_solver(gmres_solver,op,Uh,dΩ)
verbose && println("> Testing MINRES")
minres_solver = IS_MINRESSolver(;maxiter=100,reltol=1.e-12,verbose=verbose)
test_solver(minres_solver,op,Uh,dΩ)
end
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 2320 | module KrylovTests
using Test
using Gridap, Gridap.Algebra
using GridapDistributed
using PartitionedArrays
using IterativeSolvers
using GridapSolvers
using GridapSolvers.LinearSolvers
sol(x) = x[1] + x[2]
f(x) = -Δ(sol)(x)
function test_solver(solver,op,Uh,dΩ)
A, b = get_matrix(op), get_vector(op);
ns = numerical_setup(symbolic_setup(solver,A),A)
x = allocate_in_domain(A); fill!(x,0.0)
solve!(x,ns,b)
u = interpolate(sol,Uh)
uh = FEFunction(Uh,x)
eh = uh - u
E = sum(∫(eh*eh)*dΩ)
@test E < 1.e-6
end
function get_mesh(parts,np)
Dc = length(np)
if Dc == 2
domain = (0,1,0,1)
nc = (8,8)
else
@assert Dc == 3
domain = (0,1,0,1,0,1)
nc = (8,8,8)
end
if prod(np) == 1
model = CartesianDiscreteModel(domain,nc)
else
model = CartesianDiscreteModel(parts,np,domain,nc)
end
return model
end
function main(distribute,np)
parts = distribute(LinearIndices((prod(np),)))
model = get_mesh(parts,np)
order = 1
qorder = order*2 + 1
reffe = ReferenceFE(lagrangian,Float64,order)
Vh = TestFESpace(model,reffe;conformity=:H1,dirichlet_tags="boundary")
Uh = TrialFESpace(Vh,sol)
u = interpolate(sol,Uh)
Ω = Triangulation(model)
dΩ = Measure(Ω,qorder)
a(u,v) = ∫(∇(v)⋅∇(u))*dΩ
l(v) = ∫(v⋅f)*dΩ
op = AffineFEOperator(a,l,Uh,Vh)
P = JacobiLinearSolver()
verbose = i_am_main(parts)
# GMRES with left and right preconditioner
gmres = LinearSolvers.GMRESSolver(40;Pr=P,Pl=P,rtol=1.e-8,verbose=verbose)
test_solver(gmres,op,Uh,dΩ)
# GMRES without preconditioner
gmres = LinearSolvers.GMRESSolver(10;rtol=1.e-8,verbose=verbose)
test_solver(gmres,op,Uh,dΩ)
gmres = LinearSolvers.GMRESSolver(10;restart=true,rtol=1.e-8,verbose=verbose)
test_solver(gmres,op,Uh,dΩ)
fgmres = LinearSolvers.FGMRESSolver(10,P;rtol=1.e-8,verbose=verbose)
test_solver(fgmres,op,Uh,dΩ)
fgmres = LinearSolvers.FGMRESSolver(10,P;restart=true,rtol=1.e-8,verbose=verbose)
test_solver(fgmres,op,Uh,dΩ)
pcg = LinearSolvers.CGSolver(P;rtol=1.e-8,verbose=verbose)
test_solver(pcg,op,Uh,dΩ)
fpcg = LinearSolvers.CGSolver(P;flexible=true,rtol=1.e-8,verbose=verbose)
test_solver(fpcg,op,Uh,dΩ)
minres = LinearSolvers.MINRESSolver(;Pl=P,rtol=1.e-8,verbose=verbose)
test_solver(minres,op,Uh,dΩ)
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 2984 | module SchurComplementSolversTests
using Test
using BlockArrays
using Gridap
using Gridap.MultiField, Gridap.Algebra
using Gridap.Algebra
using Gridap.Geometry
using Gridap.FESpaces
using Gridap.ReferenceFEs
using PartitionedArrays
using GridapDistributed
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
function l2_error(xh,sol,dΩ)
eh = xh - sol
e = sum(∫(eh⋅eh)dΩ)
return e
end
function l2_error(x,sol,X,dΩ)
xh = FEFunction(X,x)
return l2_error(xh,sol,dΩ)
end
function get_mesh(parts,np)
Dc = length(np)
if Dc == 2
domain = (0,1,0,1)
nc = (8,8)
else
@assert Dc == 3
domain = (0,1,0,1,0,1)
nc = (8,8,8)
end
if prod(np) == 1
model = CartesianDiscreteModel(domain,nc)
else
model = CartesianDiscreteModel(parts,np,domain,nc)
end
return model
end
# Darcy solution
const β_U = 50.0
const γ = 100.0
u_ref(x) = VectorValue(x[1]+x[2],-x[2])
p_ref(x) = 2.0*x[1]-1.0
f_ref(x) = u_ref(x) + ∇(p_ref)(x)
function main(distribute,np)
parts = distribute(LinearIndices((prod(np),)))
model = get_mesh(parts,np)
labels = get_face_labeling(model)
add_tag_from_tags!(labels,"dirichlet",[1,2,3,4,5,6,7])
add_tag_from_tags!(labels,"newmann",[8,])
order = 0
reffeᵤ = ReferenceFE(raviart_thomas,Float64,order)
V = TestFESpace(model,reffeᵤ,conformity=:HDiv,dirichlet_tags="dirichlet")
U = TrialFESpace(V,u_ref)
reffeₚ = ReferenceFE(lagrangian,Float64,order;space=:P)
Q = TestFESpace(model,reffeₚ,conformity=:L2)
P = TrialFESpace(Q,p_ref)
mfs = BlockMultiFieldStyle()
Y = MultiFieldFESpace([V, Q];style=mfs)
X = MultiFieldFESpace([U, P];style=mfs)
qdegree = 4
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
Γ_N = BoundaryTriangulation(model;tags="newmann")
dΓ_N = Measure(Γ_N,qdegree)
n_Γ_N = get_normal_vector(Γ_N)
a(u,v) = ∫(v⊙u)dΩ + ∫(γ*(∇⋅v)*(∇⋅u))dΩ
b(p,v) = ∫(-(∇⋅v)*p)dΩ
c(u,q) = ∫(- q*(∇⋅u))dΩ
biform((u,p),(v,q)) = a(u,v) + b(p,v) + c(u,q)
liform((v,q)) = ∫(f_ref⋅v)dΩ - ∫((v⋅n_Γ_N)⋅p_ref)dΓ_N
op = AffineFEOperator(biform,liform,X,Y)
sysmat, sysvec = get_matrix(op), get_vector(op);
############################################################################################
# Solve by GMRES preconditioned with inexact Schur complement
s(p,q) = ∫(γ*p*q)dΩ
PS = assemble_matrix(s,P,Q)
PS_solver = LUSolver()
PS_ns = numerical_setup(symbolic_setup(PS_solver,PS),PS)
A = sysmat[Block(1,1)]
A_solver = LUSolver()
A_ns = numerical_setup(symbolic_setup(A_solver,A),A)
B = sysmat[Block(1,2)]; C = sysmat[Block(2,1)]
psc_solver = SchurComplementSolver(A_ns,B,C,PS_ns);
gmres = GMRESSolver(20;Pr=psc_solver,rtol=1.e-10,verbose=i_am_main(parts))
gmres_ns = numerical_setup(symbolic_setup(gmres,sysmat),sysmat)
x = allocate_in_domain(sysmat)
solve!(x,gmres_ns,sysvec)
xh = FEFunction(X,x)
uh, ph = xh
#@test l2_error(uh,u_ref,dΩ) < 1.e-4
#@test l2_error(ph,p_ref,dΩ) < 1.e-4
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 2225 | module SmoothersTests
using Test
using MPI
using Gridap, Gridap.Algebra
using GridapDistributed
using PartitionedArrays
using IterativeSolvers
using GridapSolvers
using GridapSolvers.LinearSolvers
function smoothers_driver(parts,model,P)
sol(x) = x[1] + x[2]
f(x) = -Δ(sol)(x)
order = 1
qorder = order*2 + 1
reffe = ReferenceFE(lagrangian,Float64,order)
Vh = TestFESpace(model,reffe;conformity=:H1,dirichlet_tags="boundary")
Uh = TrialFESpace(Vh,sol)
u = interpolate(sol,Uh)
Ω = Triangulation(model)
dΩ = Measure(Ω,qorder)
a(u,v) = ∫(∇(v)⋅∇(u))*dΩ
l(v) = ∫(v⋅f)*dΩ
op = AffineFEOperator(a,l,Uh,Vh)
A, b = get_matrix(op), get_vector(op)
ss = symbolic_setup(P,A)
ns = numerical_setup(ss,A)
x = allocate_in_domain(A); ; fill!(x,zero(eltype(x)))
x, history = IterativeSolvers.cg!(x,A,b;
verbose=i_am_main(parts),
reltol=1.0e-8,
Pl=ns,
log=true)
u = interpolate(sol,Uh)
uh = FEFunction(Uh,x)
eh = uh - u
E = sum(∫(eh*eh)*dΩ)
if i_am_main(parts)
println("L2 Error: ", E)
end
@test E < 1.e-8
end
function main_smoother_driver(parts,model,smoother)
if smoother === :richardson
P = RichardsonSmoother(JacobiLinearSolver(),5,2.0/3.0)
elseif smoother === :sym_gauss_seidel
P = SymGaussSeidelSmoother(5)
else
error("Unknown smoother")
end
smoothers_driver(parts,model,P)
end
function get_mesh(parts,np)
Dc = length(np)
if Dc == 2
domain = (0,1,0,1)
nc = (8,8)
else
@assert Dc == 3
domain = (0,1,0,1,0,1)
nc = (8,8,8)
end
if prod(np) == 1
model = CartesianDiscreteModel(domain,nc)
else
model = CartesianDiscreteModel(parts,np,domain,nc)
end
return model
end
function main(distribute,np)
parts = distribute(LinearIndices((prod(np),)))
model = get_mesh(parts,np)
for smoother in [:richardson,:sym_gauss_seidel]
if i_am_main(parts)
println(repeat("=",80))
println("Testing smoother $smoother with Dc=$(length(np))")
end
main_smoother_driver(parts,model,smoother)
end
end
end # module SmoothersTests | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 238 | module GMGTestsMPI
using MPI, PartitionedArrays
include("../GMGTests.jl")
with_mpi() do distribute
GMGTests.main(distribute,4,(4,4),[(2,2),(2,1),(1,1)]) # 2D
GMGTests.main(distribute,4,(2,2,2),[(2,2,1),(2,1,1),(1,1,1)]) # 3D
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 203 | module KrylovTestsMPI
using MPI, PartitionedArrays
include("../KrylovTests.jl")
with_mpi() do distribute
KrylovTests.main(distribute,(2,2)) # 2D
KrylovTests.main(distribute,(2,2,1)) # 3D
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 199 | module SchurComplementSolversTestsMPI
using PartitionedArrays, MPI
include("../SchurComplementSolversTests.jl")
with_mpi() do distribute
SchurComplementSolversTests.main(distribute,(2,2))
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 214 | module SmoothersTestsMPI
using MPI, PartitionedArrays
include("../SmoothersTests.jl")
with_mpi() do distribute
SmoothersTests.main(distribute,(2,2)) # 2D
SmoothersTests.main(distribute,(2,2,1)) # 3D
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 457 | using Test
using MPI
using GridapSolvers
function run_tests(testdir)
istest(f) = endswith(f, ".jl") && !(f=="runtests.jl")
testfiles = sort(filter(istest, readdir(testdir)))
@time @testset "$f" for f in testfiles
MPI.mpiexec() do cmd
np = 4
cmd = `$cmd -n $(np) --oversubscribe $(Base.julia_cmd()) --project=. $(joinpath(testdir, f))`
@show cmd
run(cmd)
@test true
end
end
end
# MPI tests
run_tests(@__DIR__)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 221 | module GMGTestsSeq
using PartitionedArrays
include("../GMGTests.jl")
with_debug() do distribute
GMGTests.main(distribute,4,(4,4),[(2,2),(1,1)]) # 2D
GMGTests.main(distribute,4,(2,2,2),[(2,2,1),(1,1,1)]) # 3D
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 420 | module IterativeSolversWrappersTestsSequential
using PartitionedArrays
include("../IterativeSolversWrappersTests.jl")
with_debug() do distribute
IterativeSolversWrappersTests.main(distribute,(1,1)) # 2D - serial
IterativeSolversWrappersTests.main(distribute,(2,2)) # 2D
IterativeSolversWrappersTests.main(distribute,(1,1,1)) # 3D - serial
IterativeSolversWrappersTests.main(distribute,(2,2,1)) # 3D
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 312 | module KrylovTestsSequential
using PartitionedArrays
include("../KrylovTests.jl")
with_debug() do distribute
KrylovTests.main(distribute,(1,1)) # 2D - serial
KrylovTests.main(distribute,(2,2)) # 2D
KrylovTests.main(distribute,(1,1,1)) # 3D - serial
KrylovTests.main(distribute,(2,2,1)) # 3D
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 256 | module SchurComplementSolversTestsSequential
using PartitionedArrays
include("../SchurComplementSolversTests.jl")
with_debug() do distribute
SchurComplementSolversTests.main(distribute,(1,1))
SchurComplementSolversTests.main(distribute,(2,2))
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 330 | module SmoothersTestsSequential
using PartitionedArrays
include("../SmoothersTests.jl")
with_debug() do distribute
SmoothersTests.main(distribute,(1,1)) # 2D - serial
SmoothersTests.main(distribute,(2,2)) # 2D
SmoothersTests.main(distribute,(1,1,1)) # 3D - serial
SmoothersTests.main(distribute,(2,2,1)) # 3D
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 134 | using Test
include("KrylovTests.jl")
include("IterativeSolversWrappersTests.jl")
include("SmoothersTests.jl")
include("GMGTests.jl")
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 5190 | module DistributedGridTransferOperatorsTests
using MPI
using PartitionedArrays
using Gridap, Gridap.Algebra
using GridapDistributed
using GridapP4est
using Test
using GridapSolvers
using GridapSolvers.MultilevelTools
using GridapDistributed: change_ghost
function get_model_hierarchy(parts,Dc,num_parts_x_level)
mh = GridapP4est.with(parts) do
if Dc == 2
domain = (0,1,0,1)
nc = (2,2)
else
@assert Dc == 3
domain = (0,1,0,1,0,1)
nc = (2,2,2)
end
num_refs_coarse = 2
num_levels = length(num_parts_x_level)
cparts = generate_subparts(parts,num_parts_x_level[num_levels])
cmodel = CartesianDiscreteModel(domain,nc)
coarse_model = OctreeDistributedDiscreteModel(cparts,cmodel,num_refs_coarse)
return ModelHierarchy(parts,coarse_model,num_parts_x_level)
end
return mh
end
function get_hierarchy_matrices(trials,tests,a,l,qdegree)
mats, vecs = map(trials,tests) do trials,tests
U = get_fe_space(trials)
V = get_fe_space(tests)
Ω = get_triangulation(U)
dΩ = Measure(Ω,qdegree)
ai(u,v) = a(u,v,dΩ)
li(v) = l(v,dΩ)
op = AffineFEOperator(ai,li,U,V)
return get_matrix(op), get_vector(op)
end |> tuple_of_arrays
return mats, vecs
end
function main_driver(parts,mh,sol,trials,tests,mats,vecs,qdegree,rm,mode)
# Create Operators:
ops = setup_transfer_operators(trials, qdegree; restriction_method=rm, mode=mode)
restrictions, prolongations = ops
nlevs = num_levels(mh)
for lev in 1:nlevs-1
parts_h = get_level_parts(mh,lev)
parts_H = get_level_parts(mh,lev+1)
if i_am_in(parts_h)
i_am_main(parts) && println(" >> Level: ", lev)
Ah = mats[lev]
bh = vecs[lev]
Uh = get_fe_space(trials,lev)
Vh = get_fe_space(tests,lev)
uh_ref = interpolate(sol,Uh)
xh_ref = change_ghost(get_free_dof_values(uh_ref),axes(Ah,2);make_consistent=true)
rh_ref = similar(xh_ref); mul!(rh_ref,Ah,xh_ref); rh_ref .= bh .- rh_ref;
yh = similar(xh_ref)
if mode == :solution
xh = copy(xh_ref)
yh_ref = xh_ref
else
xh = copy(rh_ref)
yh_ref = rh_ref
end
if i_am_in(parts_H)
AH = mats[lev+1]
bH = vecs[lev+1]
UH = get_fe_space(trials,lev+1)
VH = get_fe_space(tests,lev+1)
uH_ref = interpolate(sol,UH)
xH_ref = change_ghost(get_free_dof_values(uH_ref),axes(AH,2);make_consistent=true)
rH_ref = similar(xH_ref); mul!(rH_ref,AH,xH_ref); rH_ref .= bH .- rH_ref;
yH = similar(xH_ref)
if mode == :solution
xH = copy(xH_ref)
yH_ref = xH_ref
else
xH = copy(rH_ref)
yH_ref = rH_ref
end
else
xH_ref = nothing
xH = nothing
yH_ref = nothing
yH = nothing
end
# ---- Restriction ----
i_am_main(parts) && println(" >>> Restriction")
R = restrictions[lev]
mul!(yH,R,xh)
if i_am_in(parts_H)
errors = map(own_values(yH_ref),own_values(yH)) do y_ref,y
e = norm(y-y_ref)
i_am_main(parts) && println(" - Error = ", e)
return e < 1.e-3
end
@test PartitionedArrays.getany(errors)
end
# ---- Prolongation ----
i_am_main(parts) && println(" >>> Prolongation")
P = prolongations[lev]
mul!(yh,P,xH)
errors = map(own_values(yh_ref),own_values(yh)) do y_ref,y
e = norm(y-y_ref)
i_am_main(parts) && println(" - Error = ", e)
return e < 1.e-3
end
@test PartitionedArrays.getany(errors)
end
end
end
u_hdiv(x) = VectorValue([x[2]-x[1],x[1]-x[2]])
u_h1(x) = x[1]+x[2]
#u_h1(x) = x[1]*(1-x[1])*x[2]*(1-x[2])
#u_hdiv(x) = VectorValue([x[1]*(1.0-x[1]),-x[2]*(1.0-x[2])])
function main(distribute,np,Dc,np_x_level)
parts = distribute(LinearIndices((np,)))
mh = get_model_hierarchy(parts,Dc,np_x_level)
conformities = [:h1,:hdiv]
solutions = [u_h1,u_hdiv]
for order in [1,2]
reffes = [ReferenceFE(lagrangian,Float64,order),ReferenceFE(raviart_thomas,Float64,order)]
for (conf,u,reffe) in zip(conformities,solutions,reffes)
tests = TestFESpace(mh,reffe;dirichlet_tags="boundary")
trials = TrialFESpace(tests,u)
for mode in [:solution]#,:residual]
for rm in [:projection]#,:interpolation]
qdegree = 2*order + 1
fx = zero(u(VectorValue(0.0,0.0)))
a(u,v,dΩ) = ∫(v⋅u)*dΩ
l(v,dΩ) = ∫(v⋅fx)*dΩ
mats, vecs = get_hierarchy_matrices(trials,tests,a,l,qdegree)
if i_am_main(parts)
println(repeat("=",80))
println("> Testing transfers for")
println(" - order = ", order)
println(" - conformity = ", conf)
println(" - transfer_mode = ", mode)
println(" - restriction_method = ", rm)
end
main_driver(parts,mh,u,trials,tests,mats,vecs,qdegree,rm,mode)
end
end
end
end
end
with_mpi() do distribute
main(distribute,4,2,[4,2,2])
end
end # module DistributedGridTransferOperatorsTests | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 1354 | module ModelHierarchiesTests
using MPI
using Gridap
using Gridap.FESpaces, Gridap.Algebra
using GridapDistributed
using PartitionedArrays
using GridapP4est
using GridapSolvers
using GridapSolvers.MultilevelTools
function main(distribute,np,num_parts_x_level)
parts = distribute(LinearIndices((prod(np),)))
GridapP4est.with(parts) do
# Start from coarse, refine models
domain = (0,1,0,1)
num_levels = length(num_parts_x_level)
cparts = generate_subparts(parts,num_parts_x_level[num_levels])
cmodel = CartesianDiscreteModel(domain,(2,2))
coarse_model = OctreeDistributedDiscreteModel(cparts,cmodel,2)
mh = ModelHierarchy(parts,coarse_model,num_parts_x_level)
sol(x) = x[1] + x[2]
reffe = ReferenceFE(lagrangian,Float64,1)
tests = TestFESpace(mh,reffe,conformity=:H1)
trials = TrialFESpace(tests,sol)
# Start from fine, coarsen models
domain = (0,1,0,1)
fparts = generate_subparts(parts,num_parts_x_level[1])
fmodel = CartesianDiscreteModel(domain,(2,2))
fine_model = OctreeDistributedDiscreteModel(fparts,fmodel,8)
mh = ModelHierarchy(parts,fine_model,num_parts_x_level)
sol(x) = x[1] + x[2]
reffe = ReferenceFE(lagrangian,Float64,1)
tests = TestFESpace(mh,reffe,conformity=:H1)
trials = TrialFESpace(tests,sol)
end
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 2481 | module RedistributeToolsTests
using MPI
using PartitionedArrays
using Gridap, Gridap.Algebra
using GridapDistributed
using GridapP4est
using Test
using GridapSolvers
using GridapSolvers.MultilevelTools
using GridapDistributed: redistribute_cell_dofs, redistribute_fe_function, redistribute_free_values
function get_model_hierarchy(parts,Dc,num_parts_x_level)
mh = GridapP4est.with(parts) do
if Dc == 2
domain = (0,1,0,1)
nc = (2,2)
else
@assert Dc == 3
domain = (0,1,0,1,0,1)
nc = (2,2,2)
end
num_refs_coarse = 2
num_levels = length(num_parts_x_level)
cparts = generate_subparts(parts,num_parts_x_level[num_levels])
cmodel = CartesianDiscreteModel(domain,nc)
coarse_model = OctreeDistributedDiscreteModel(cparts,cmodel,num_refs_coarse)
return ModelHierarchy(parts,coarse_model,num_parts_x_level)
end
return mh
end
function main_driver(parts,mh)
level_parts = get_level_parts(mh)
old_parts = level_parts[2]
new_parts = level_parts[1]
# FE Spaces
order = 2
u(x) = x[1]^2 + x[2]^2 - 3.0*x[1]*x[2]
reffe = ReferenceFE(lagrangian,Float64,order)
glue = mh[1].red_glue
model_old = get_model_before_redist(mh[1])
if i_am_in(old_parts)
VOLD = TestFESpace(model_old,reffe,dirichlet_tags="boundary")
UOLD = TrialFESpace(VOLD,u)
else
VOLD = nothing
UOLD = nothing
end
model_new = get_model(mh[1])
VNEW = TestFESpace(model_new,reffe,dirichlet_tags="boundary")
UNEW = TrialFESpace(VNEW,u)
# Triangulations
qdegree = 2*order+1
Ω_new = Triangulation(model_new)
dΩ_new = Measure(Ω_new,qdegree)
uh_new = interpolate(u,UNEW)
if i_am_in(old_parts)
Ω_old = Triangulation(model_old)
dΩ_old = Measure(Ω_old,qdegree)
uh_old = interpolate(u,UOLD)
else
Ω_old = nothing
dΩ_old = nothing
uh_old = nothing
end
# Old -> New
uh_old_red = redistribute_fe_function(uh_old,UNEW,model_new,glue)
n = sum(∫(uh_old_red)*dΩ_new)
if i_am_in(old_parts)
o = sum(∫(uh_old)*dΩ_old)
@test o ≈ n
end
# New -> Old
uh_new_red = redistribute_fe_function(uh_new,UOLD,model_old,glue;reverse=true)
n = sum(∫(uh_new)*dΩ_new)
if i_am_in(old_parts)
o = sum(∫(uh_new_red)*dΩ_old)
@test o ≈ n
end
end
function main(distribute,np,Dc,np_x_level)
parts = distribute(LinearIndices((np,)))
mh = get_model_hierarchy(parts,Dc,np_x_level)
main_driver(parts,mh)
end
end # module RedistributeToolsTests | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 3222 | module RefinementToolsTests
using MPI
using PartitionedArrays
using Gridap, Gridap.Algebra
using GridapDistributed
using GridapP4est
using Test
using IterativeSolvers
using GridapSolvers
using GridapSolvers.MultilevelTools
function get_model_hierarchy(parts,Dc,num_parts_x_level)
mh = GridapP4est.with(parts) do
if Dc == 2
domain = (0,1,0,1)
nc = (2,2)
else
@assert Dc == 3
domain = (0,1,0,1,0,1)
nc = (2,2,2)
end
num_refs_coarse = 2
num_levels = length(num_parts_x_level)
cparts = generate_subparts(parts,num_parts_x_level[num_levels])
cmodel = CartesianDiscreteModel(domain,nc)
coarse_model = OctreeDistributedDiscreteModel(cparts,cmodel,num_refs_coarse)
return ModelHierarchy(parts,coarse_model,num_parts_x_level)
end
return mh
end
function main_driver(parts,mh)
# FE Spaces
order = 2
sol(x) = x[1]^2 + x[2]^2 - 3.0*x[1]*x[2]
reffe = ReferenceFE(lagrangian,Float64,order)
tests = TestFESpace(mh,reffe;conformity=:H1,dirichlet_tags="boundary")
trials = TrialFESpace(tests,sol)
nlevs = num_levels(mh)
quad_order = 2*order+1
for lev in 1:nlevs-1
fparts = get_level_parts(mh,lev)
cparts = get_level_parts(mh,lev+1)
if i_am_in(cparts)
model_h = get_model_before_redist(mh,lev)
Vh = get_fe_space_before_redist(tests,lev)
Uh = get_fe_space_before_redist(trials,lev)
Ωh = get_triangulation(model_h)
dΩh = Measure(Ωh,quad_order)
uh = interpolate(sol,Uh)
model_H = get_model(mh,lev+1)
VH = get_fe_space(tests,lev+1)
UH = get_fe_space(trials,lev+1)
ΩH = get_triangulation(model_H)
dΩH = Measure(ΩH,quad_order)
uH = interpolate(sol,UH)
dΩhH = Measure(ΩH,Ωh,quad_order)
# Coarse FEFunction -> Fine FEFunction, by projection
ah(u,v) = ∫(v⋅u)*dΩh
lh(v) = ∫(v⋅uH)*dΩh
oph = AffineFEOperator(ah,lh,Uh,Vh)
Ah = get_matrix(oph)
bh = get_vector(oph)
xh = pfill(0.0,partition(axes(Ah,2)))
IterativeSolvers.cg!(xh,Ah,bh;verbose=i_am_main(parts),reltol=1.0e-08)
uH_projected = FEFunction(Uh,xh)
_eh = uh-uH_projected
eh = sum(∫(_eh⋅_eh)*dΩh)
i_am_main(parts) && println("Error H2h: ", eh)
@test eh < 1.0e-10
# Fine FEFunction -> Coarse FEFunction, by projection
aH(u,v) = ∫(v⋅u)*dΩH
lH(v) = ∫(v⋅uH_projected)*dΩhH
opH = AffineFEOperator(aH,lH,UH,VH)
AH = get_matrix(opH)
bH = get_vector(opH)
xH = pfill(0.0,partition(axes(AH,2)))
IterativeSolvers.cg!(xH,AH,bH;verbose=i_am_main(parts),reltol=1.0e-08)
uh_projected = FEFunction(UH,xH)
_eH = uH-uh_projected
eH = sum(∫(_eH⋅_eH)*dΩH)
i_am_main(parts) && println("Error h2H: ", eH)
@test eh < 1.0e-10
# Coarse FEFunction -> Fine FEFunction, by interpolation
uH_i = interpolate(uH,Uh)
_eh = uH_i-uh
eh = sum(∫(_eh⋅_eh)*dΩh)
i_am_main(parts) && println("Error h2H: ", eh)
@test eh < 1.0e-10
end
end
end
function main(distribute,np,Dc,np_x_level)
parts = distribute(LinearIndices((np,)))
mh = get_model_hierarchy(parts,Dc,np_x_level)
main_driver(parts,mh)
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 315 | module DistributedGridTransferOperatorsTestsMPI
using MPI, PartitionedArrays
include("../DistributedGridTransferOperatorsTests.jl")
with_mpi() do distribute
DistributedGridTransferOperatorsTests.main(distribute,4,2,[4,2,2]) # 2D
#DistributedGridTransferOperatorsTests.main(distribute,4,3,[4,2,2]) # 3D
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 187 | module ModelHierarchiesTestsMPI
using MPI, PartitionedArrays
include("../ModelHierarchiesTests.jl")
with_mpi() do distribute
ModelHierarchiesTests.main(distribute,4,[4,4,2,2])
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 251 | module RedistributeToolsTestsMPI
using MPI, PartitionedArrays
include("../RedistributeToolsTests.jl")
with_mpi() do distribute
RedistributeToolsTests.main(distribute,4,2,[4,2]) # 2D
#RedistributeToolsTests.main(distribute,4,3,[4,2]) # 3D
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 247 | module RefinementToolsTestsMPI
using MPI, PartitionedArrays
include("../RefinementToolsTests.jl")
with_mpi() do distribute
RefinementToolsTests.main(distribute,4,2,[4,2,2]) # 2D
#RefinementToolsTests.main(distribute,4,3,[4,2,2]) # 3D
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 457 | using Test
using MPI
using GridapSolvers
function run_tests(testdir)
istest(f) = endswith(f, ".jl") && !(f=="runtests.jl")
testfiles = sort(filter(istest, readdir(testdir)))
@time @testset "$f" for f in testfiles
MPI.mpiexec() do cmd
np = 4
cmd = `$cmd -n $(np) --oversubscribe $(Base.julia_cmd()) --project=. $(joinpath(testdir, f))`
@show cmd
run(cmd)
@test true
end
end
end
# MPI tests
run_tests(@__DIR__)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 1785 | module NonlinearSolversTests
using Test
using LinearAlgebra
using FillArrays, BlockArrays
using LineSearches: BackTracking
using GridapDistributed, PartitionedArrays
using Gridap
using Gridap.Algebra
using GridapSolvers
using GridapSolvers.NonlinearSolvers, GridapSolvers.LinearSolvers
function main(ranks,model,solver)
u_sol(x) = sum(x)
order = 1
reffe = ReferenceFE(lagrangian,Float64,order)
Vh = TestFESpace(model,reffe,dirichlet_tags=["boundary"])
Uh = TrialFESpace(Vh,u_sol)
degree = 4*order
Ω = Triangulation(model)
dΩ = Measure(Ω,degree)
α(u) = (1 + u + u^2)
f(x) = α(u_sol(x))
res(u,v) = ∫((α∘u)⋅v - f*v)dΩ
op = FEOperator(res,Uh,Vh)
ls = GMRESSolver(10,Pr=JacobiLinearSolver(),maxiter=50,verbose=false)
if solver == :nlsolvers_newton
nls = NLsolveNonlinearSolver(ls; show_trace=true, method=:newton, linesearch=BackTracking(), iterations=20)
elseif solver == :nlsolvers_trust_region
nls = NLsolveNonlinearSolver(ls; show_trace=true, method=:trust_region, linesearch=BackTracking(), iterations=20)
elseif solver == :nlsolvers_anderson
nls = NLsolveNonlinearSolver(ls; show_trace=true, method=:anderson, linesearch=BackTracking(), iterations=40, m=10)
elseif solver == :newton
nls = NewtonSolver(ls,maxiter=20,verbose=true)
else
@error "Unknown solver"
end
solver = FESolver(nls)
uh0 = interpolate(0.01,Uh)
uh, = solve!(uh0,solver,op)
@test norm(residual(op,uh)) < 1e-6
end
# Serial
function main(solver)
model = CartesianDiscreteModel((0,1,0,1),(8,8))
ranks = DebugArray([1])
main(ranks,model,solver)
end
# Distributed
function main(distribute,solver)
ranks = distribute(LinearIndices((4,)))
model = CartesianDiscreteModel((0,1,0,1),(8,8))
main(ranks,model,solver)
end
end #module | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 356 |
using Test
include("../NonlinearSolversTests.jl")
@testset "NonlinearSolvers" begin
@testset "NLSolvers" begin
NonlinearSolversTests.main(:nlsolvers_newton)
NonlinearSolversTests.main(:nlsolvers_trust_region)
NonlinearSolversTests.main(:nlsolvers_anderson)
end
@testset "Newton" begin
NonlinearSolversTests.main(:newton)
end
end
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 267 | using PartitionedArrays
using GridapDistributed
macro pdebug(parts,msg)
return quote
if i_am_main($parts)
@debug $msg
end
end
end
np = 4
parts = with_mpi() do distribute
distribute(LinearIndices((prod(np),)))
end
@pdebug(parts,"Hello, world!")
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 3053 | using Test
using LinearAlgebra
using FillArrays, BlockArrays
using Gridap
using Gridap.ReferenceFEs, Gridap.Algebra, Gridap.Geometry, Gridap.FESpaces
using Gridap.CellData, Gridap.MultiField, Gridap.Algebra
using PartitionedArrays
using GridapDistributed
using GridapSolvers
using GridapSolvers.LinearSolvers, GridapSolvers.MultilevelTools, GridapSolvers.NonlinearSolvers
using GridapSolvers.BlockSolvers: LinearSystemBlock, NonlinearSystemBlock, TriformBlock, BlockTriangularSolver
function add_labels_2d!(labels)
add_tag_from_tags!(labels,"top",[3,4,6])
add_tag_from_tags!(labels,"bottom",[1,2,5])
add_tag_from_tags!(labels,"walls",[7,8])
end
function add_labels_3d!(labels)
add_tag_from_tags!(labels,"top",[5,6,7,8,11,12,15,16,22])
add_tag_from_tags!(labels,"bottom",[1,2,3,4,9,10,13,14,21])
add_tag_from_tags!(labels,"walls",[17,18,23,25,26])
end
np = (1,1)
nc = (4,4)
parts = with_mpi() do distribute
distribute(LinearIndices((prod(np),)))
end
# Geometry
Dc = length(nc)
domain = (Dc == 2) ? (0,1,0,1) : (0,1,0,1,0,1)
model = CartesianDiscreteModel(parts,np,domain,nc)
add_labels! = (Dc == 2) ? add_labels_2d! : add_labels_3d!
add_labels!(get_face_labeling(model))
# FE spaces
order = 2
qdegree = 2*(order+1)
reffe_u = ReferenceFE(lagrangian,VectorValue{Dc,Float64},order)
reffe_p = ReferenceFE(lagrangian,Float64,order-1;space=:P)
u_bottom = (Dc==2) ? VectorValue(0.0,0.0) : VectorValue(0.0,0.0,0.0)
u_top = (Dc==2) ? VectorValue(1.0,0.0) : VectorValue(1.0,0.0,0.0)
V = TestFESpace(model,reffe_u,dirichlet_tags=["bottom","top"]);
U = TrialFESpace(V,[u_bottom,u_top]);
Q = TestFESpace(model,reffe_p;conformity=:L2,constraint=:zeromean)
mfs = Gridap.MultiField.BlockMultiFieldStyle()
X = MultiFieldFESpace([U,Q];style=mfs)
Y = MultiFieldFESpace([V,Q];style=mfs)
# Weak formulation
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
p = 3
_ν(∇u) = norm(∇u)^(p-2)
_dν(∇u) = (p-2)*norm(∇u)^(p-4)
_flux(∇u) = _ν(∇u)*∇u
_dflux(∇du,∇u) = _dν(∇u)*(∇u⊙∇du)*∇u + _ν(∇u)*∇du
ν(u) = _ν∘(∇(u))
flux(u) = _flux∘(∇(u))
dflux(du,u) = _dflux∘(∇(du),∇(u))
f = (Dc==2) ? VectorValue(1.0,1.0) : VectorValue(1.0,1.0,1.0)
res_u(u,v) = ∫(∇(v)⊙flux(u))dΩ - ∫(v⋅f)dΩ
res((u,p),(v,q)) = res_u(u,v) - ∫(divergence(v)*p)dΩ - ∫(divergence(u)*q)dΩ
jac_u(u,du,v) = ∫(∇(v)⊙dflux(du,u))dΩ
jac((u,p),(du,dq),(v,q)) = jac_u(u,du,v) - ∫(divergence(v)*dq)dΩ - ∫(divergence(du)*q)dΩ
op = FEOperator(res,jac,X,Y)
# Solver
solver_u = LUSolver()
solver_p = CGSolver(JacobiLinearSolver();maxiter=30,atol=1e-14,rtol=1.e-6,verbose=false)
solver_p.log.depth = 2
bblocks = [NonlinearSystemBlock() LinearSystemBlock();
LinearSystemBlock() TriformBlock(((u,p),dp,q) -> ∫(-ν(u)*dp*q)dΩ,X,Q,Q)]
coeffs = [1.0 1.0;
0.0 1.0]
P = BlockTriangularSolver(bblocks,[solver_u,solver_p],coeffs,:upper)
ls_solver = FGMRESSolver(20,P;atol=1e-14,rtol=1.e-8,verbose=i_am_main(parts))
nls_solver = NewtonSolver(ls_solver;maxiter=5,atol=1e-14,rtol=1.e-6,verbose=i_am_main(parts))
xh = interpolate([VectorValue(1.0,1.0),0.0],X);
solve!(xh,nls_solver,op)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 4475 | using PartitionedArrays
using Gridap, GridapPETSc, GridapSolvers, GridapDistributed, GridapP4est
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
import GridapSolvers.PatchBasedSmoothers as PBS
using Gridap.ReferenceFEs, Gridap.Geometry
function get_mesh_hierarchy(parts,Dc,np_per_level,nrefs_coarse)
if Dc == 2
domain = (0,1,0,1)
nc = (2,2)
else
@assert Dc == 3
domain = (0,1,0,1,0,1)
nc = (2,2,2)
end
num_levels = length(np_per_level)
cparts = generate_subparts(parts,np_per_level[num_levels])
cmodel = CartesianDiscreteModel(domain,nc)
coarse_model = OctreeDistributedDiscreteModel(cparts,cmodel,nrefs_coarse)
mh = ModelHierarchy(parts,coarse_model,np_per_level)
return mh
end
function test_solver(s,D_j)
ns = numerical_setup(symbolic_setup(s,D_j),D_j)
b = allocate_in_domain(D_j)
x = allocate_in_domain(D_j)
fill!(b,1.0)
solve!(x,ns,b)
err = norm(b - D_j*x)
return err
end
function test_smoother(s,D_j)
ns = numerical_setup(symbolic_setup(s,D_j),D_j)
b = allocate_in_domain(D_j)
x = allocate_in_domain(D_j)
r = allocate_in_range(D_j)
fill!(b,1.0)
fill!(x,1.0)
mul!(r,D_j,x)
r .= b .- r
solve!(x,ns,r)
err = norm(b - D_j*x)
return err
end
function get_hierarchy_matrices(mh,tests,trials,biform)
mats = Vector{AbstractMatrix}(undef,num_levels(mh))
A = nothing
b = nothing
for lev in 1:num_levels(mh)
model = get_model(mh,lev)
U_j = get_fe_space(trials,lev)
V_j = get_fe_space(tests,lev)
Ω = Triangulation(model)
dΩ = Measure(Ω,2*k)
ai(j,v_j) = biform(j,v_j,dΩ)
if lev == 1
Dc = num_cell_dims(model)
f = (Dc==2) ? VectorValue(1.0,1.0) : VectorValue(1.0,1.0,1.0)
li(v) = ∫(v⋅f)*dΩ
op = AffineFEOperator(ai,li,U_j,V_j)
A, b = get_matrix(op), get_vector(op)
mats[lev] = A
else
mats[lev] = assemble_matrix(ai,U_j,V_j)
end
end
return mats, A, b
end
function get_patch_smoothers(tests,patch_spaces,patch_decompositions,biform,qdegree)
mh = tests.mh
nlevs = num_levels(mh)
smoothers = Vector{RichardsonSmoother}(undef,nlevs-1)
for lev in 1:nlevs-1
parts = get_level_parts(mh,lev)
if i_am_in(parts)
PD = patch_decompositions[lev]
Ph = get_fe_space(patch_spaces,lev)
Vh = get_fe_space(tests,lev)
Ω = Triangulation(PD)
dΩ = Measure(Ω,qdegree)
a_j(j,v_j) = biform(j,v_j,dΩ)
local_solver = LUSolver() # IS_ConjugateGradientSolver(;reltol=1.e-6)
patch_smoother = PatchBasedLinearSolver(a_j,Ph,Vh,local_solver)
smoothers[lev] = RichardsonSmoother(patch_smoother,1000,1.0)
end
end
return smoothers
end
############################################################################################
np = 1
ranks = with_mpi() do distribute
distribute(LinearIndices((np,)))
end
# Geometry
Dc = 2
mh = get_mesh_hierarchy(ranks,Dc,[1,1],3);
model = get_model(mh,1)
println("Number of cells: ",num_cells(model))
# FESpaces
k = 1
qdegree = 2*k+2
j_bc = (Dc==2) ? VectorValue(0.0,0.0) : VectorValue(0.0,0.0,0.0)
reffe_j = ReferenceFE(raviart_thomas,Float64,k)
tests = TestFESpace(mh,reffe_j;dirichlet_tags="boundary");
trials = TrialFESpace(tests,j_bc);
biform(j,v_j,dΩ) = ∫(j⋅v_j + (∇⋅j)⋅(∇⋅v_j))*dΩ
# Patch solver
patch_decompositions = PBS.PatchDecomposition(mh)
patch_spaces = PBS.PatchFESpace(mh,reffe_j,DivConformity(),patch_decompositions,tests);
smoothers = get_patch_smoothers(tests,patch_spaces,patch_decompositions,biform,qdegree)
restrictions, prolongations = setup_transfer_operators(trials,qdegree;mode=:residual);
smatrices, A, b = get_hierarchy_matrices(mh,tests,trials,biform);
println("System size: ",size(A))
gmg = GMGLinearSolver(mh,
smatrices,
prolongations,
restrictions,
pre_smoothers=smoothers,
post_smoothers=smoothers,
maxiter=4,
rtol=1.0e-8,
verbose=true,
mode=:preconditioner)
solver = FGMRESSolver(100,gmg;rtol=1e-6,verbose=true)
ns = numerical_setup(symbolic_setup(solver,A),A)
x = allocate_in_domain(A)
solve!(x,ns,b)
test_smoother(smoothers[1],A)
Pl = LinearSolvers.IdentitySolver()
solver2 = GMRESSolver(1000;Pl=Pl,rtol=1e-6,verbose=true)
ns2 = numerical_setup(symbolic_setup(solver2,A),A)
x2 = allocate_in_domain(A)
solve!(x2,ns2,b)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 4639 | using LinearAlgebra
using Gridap
using PartitionedArrays
using GridapDistributed
using GridapP4est
using Gridap.FESpaces
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers
u_exact_2d(x) = VectorValue(x[1]^2,-2.0*x[1]*x[2])
u_exact_3d(x) = VectorValue(x[1]^2,-2.0*x[1]*x[2],1.0)
function Gridap.cross(a::VectorValue{2},b::VectorValue{3})
@assert iszero(b[1]) && iszero(b[2])
VectorValue(a[2]*b[3],-a[1]*b[3])
end
function get_patch_smoothers(
mh,tests,biform,qdegree;
w=0.2,
is_nonlinear=false,
patch_decompositions = PatchDecomposition(mh)
)
patch_spaces = PatchFESpace(tests,patch_decompositions)
nlevs = num_levels(mh)
smoothers = map(view(tests,1:nlevs-1),patch_decompositions,patch_spaces) do tests, PD, Ph
Vh = get_fe_space(tests)
Ω = Triangulation(PD)
dΩ = Measure(Ω,qdegree)
ap = is_nonlinear ? (u,du,dv) -> biform(u,du,dv,dΩ) : (u,v) -> biform(u,v,dΩ)
patch_smoother = PatchBasedLinearSolver(ap,Ph,Vh;is_nonlinear=is_nonlinear)
return RichardsonSmoother(patch_smoother,5,w)
end
return smoothers
end
function get_patch_smoothers_bis(
mh,tests,biform,qdegree;
niter = 10,
is_nonlinear=false,
patch_decompositions = PatchDecomposition(mh)
)
patch_spaces = PatchFESpace(tests,patch_decompositions)
nlevs = num_levels(mh)
smoothers = map(view(tests,1:nlevs-1),patch_decompositions,patch_spaces) do tests, PD, Ph
Vh = get_fe_space(tests)
Ω = Triangulation(PD)
dΩ = Measure(Ω,qdegree)
ap = is_nonlinear ? (u,du,dv) -> biform(u,du,dv,dΩ) : (u,v) -> biform(u,v,dΩ)
patch_smoother = PatchBasedLinearSolver(ap,Ph,Vh;is_nonlinear=is_nonlinear)
gmres = GMRESSolver(niter;Pr=patch_smoother,maxiter=niter,atol=1e-14,rtol=1.e-10,verbose=false);
return RichardsonSmoother(gmres,1,1.0)
end
return smoothers
end
function get_bilinear_form(mh_lev,biform,qdegree)
model = get_model(mh_lev)
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
return (u,v) -> biform(u,v,dΩ)
end
############################################################################################
Dc = 3
np = 1
nc = Tuple(fill(4,Dc))
np_per_level = [np,np]
parts = with_mpi() do distribute
distribute(LinearIndices((np,)))
end
domain = (Dc == 2) ? (0,1,0,1) : (0,1,0,1,0,1)
mh = CartesianModelHierarchy(parts,np_per_level,domain,nc)
B = VectorValue(0.0,0.0,1.0)
u_exact(x) = (Dc == 2) ? u_exact_2d(x) : u_exact_3d(x)
j_exact(x) = cross(u_exact(x),B)
f(x) = -Δ(u_exact)(x) - cross(j_exact(x),B)
order = 2
qdegree = 2*(order+1)
reffe_h1 = ReferenceFE(lagrangian,VectorValue{Dc,Float64},order)
reffe_hdiv = ReferenceFE(raviart_thomas,Float64,order-1)
tests_u = TestFESpace(mh,reffe_h1,dirichlet_tags="boundary");
tests_j = TestFESpace(mh,reffe_hdiv,dirichlet_tags="boundary");
trials_u = TrialFESpace(tests_u,u_exact);
trials_j = TrialFESpace(tests_j,j_exact);
tests = MultiFieldFESpace([tests_u,tests_j]);
trials = MultiFieldFESpace([trials_u,trials_j]);
Ha = 1.0e3
β = 1/Ha^2 # Laplacian coefficient
η = 1000
poly = (Dc == 2) ? QUAD : HEX
Π = LocalProjectionMap(divergence,lagrangian,Float64,order-1;space=:P)
mass(x,v_x,dΩ) = ∫(v_x⋅x)dΩ
lap(x,v_x,dΩ) = ∫(β*∇(v_x)⊙∇(x))dΩ
graddiv(x,v_x,dΩ) = ∫(η*divergence(v_x)⋅divergence(x))dΩ
Qgraddiv(x,v_x,dΩ) = ∫(η*Π(v_x,dΩ)⋅Π(x,dΩ))dΩ
crossB(x,v_x,dΩ) = ∫(v_x⋅cross(x,B))dΩ
biform_u(u,v_u,dΩ) = lap(u,v_u,dΩ) + Qgraddiv(u,v_u,dΩ)
biform_j(j,v_j,dΩ) = mass(j,v_j,dΩ) + graddiv(j,v_j,dΩ)
biform((u,j),(v_u,v_j),dΩ) = biform_u(u,v_u,dΩ) + biform_j(j,v_j,dΩ) - crossB(u,v_j,dΩ) - crossB(j,v_u,dΩ)
liform((v_u,v_j),dΩ) = ∫(v_u⋅f)dΩ
rhs((u,j),(v_u,v_j),dΩ) = Qgraddiv(u,v_u,dΩ) + graddiv(j,v_j,dΩ)
rhs_u(u,v_u,dΩ) = Qgraddiv(u,v_u,dΩ)
smatrices, A, b = compute_hierarchy_matrices(trials,tests,biform,liform,qdegree);
smoothers = get_patch_smoothers_bis(mh,tests,biform,qdegree);
prolongations = setup_patch_prolongation_operators(tests,biform,biform,qdegree);
restrictions = setup_patch_restriction_operators(tests,prolongations,biform,qdegree);
gmg = GMGLinearSolver(
mh,smatrices,prolongations,restrictions,
pre_smoothers=smoothers,post_smoothers=smoothers,
coarsest_solver=LUSolver(),
maxiter=4,rtol=1.0e-8,
verbose=i_am_main(parts),mode=:preconditioner
);
gmg.log.depth += 1
# Standalone GMG
gmg_ns = numerical_setup(symbolic_setup(gmg,A),A)
x = pfill(0.0,partition(axes(A,2)))
r = b - A*x
solve!(x,gmg_ns,r)
# FGMRES + GMG
#solver = FGMRESSolver(10,gmg;m_add=5,maxiter=30,atol=1e-14,rtol=1.e-8,verbose=i_am_main(parts));
#ns = numerical_setup(symbolic_setup(solver,A),A);
#x = pfill(0.0,partition(axes(A,2)));
#solve!(x,ns,b)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 4532 | using Test
using LinearAlgebra
using FillArrays, BlockArrays
using Gridap
using Gridap.ReferenceFEs, Gridap.Algebra, Gridap.Geometry, Gridap.FESpaces
using Gridap.CellData, Gridap.MultiField, Gridap.Algebra
using PartitionedArrays
using GridapDistributed
using GridapP4est
using GridapSolvers
using GridapSolvers.LinearSolvers, GridapSolvers.MultilevelTools, GridapSolvers.PatchBasedSmoothers
using GridapSolvers.BlockSolvers: LinearSystemBlock, BiformBlock, BlockTriangularSolver
function get_patch_smoothers(mh,tests,biform,patch_decompositions,qdegree)
patch_spaces = PatchFESpace(tests,patch_decompositions)
nlevs = num_levels(mh)
smoothers = map(view(tests,1:nlevs-1),patch_decompositions,patch_spaces) do tests, PD, Ph
Vh = get_fe_space(tests)
Ω = Triangulation(PD)
dΩ = Measure(Ω,qdegree)
ap = (u,v) -> biform(u,v,dΩ)
patch_smoother = PatchBasedLinearSolver(ap,Ph,Vh)
return RichardsonSmoother(patch_smoother,10,0.2)
end
return smoothers
end
function get_bilinear_form(mh_lev,biform,qdegree)
model = get_model(mh_lev)
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
return (u,v) -> biform(u,v,dΩ)
end
function add_labels_2d!(labels)
add_tag_from_tags!(labels,"top",[3,4,6])
add_tag_from_tags!(labels,"walls",[1,5,7,2,8])
add_tag_from_tags!(labels,"right",[2,8])
end
function add_labels_3d!(labels)
add_tag_from_tags!(labels,"top",[5,6,7,8,11,12,15,16,22])
add_tag_from_tags!(labels,"walls",[1,2,9,13,14,17,18,21,23,25,26,3,4,10,19,20,24])
add_tag_from_tags!(labels,"right",[3,4,10,19,20,24])
end
np = (1,1)
parts = with_mpi() do distribute
distribute(LinearIndices((prod(np),)))
end
# Geometry
Dc = 2
nc = Tuple(fill(8,Dc))
domain = (Dc == 2) ? (0,1,0,1) : (0,1,0,1,0,1)
add_labels! = (Dc == 2) ? add_labels_2d! : add_labels_3d!
mh = CartesianModelHierarchy(parts,[np,np],domain,nc;add_labels! = add_labels!)
model = get_model(mh,1)
# FE spaces
order = 2
qdegree = 2*(order+1)
reffe_u = ReferenceFE(lagrangian,VectorValue{Dc,Float64},order)
reffe_p = ReferenceFE(lagrangian,Float64,order-1;space=:P)
u_wall = (Dc==2) ? VectorValue(0.0,0.0) : VectorValue(0.0,0.0,0.0)
u_top = (Dc==2) ? VectorValue(1.0,0.0) : VectorValue(1.0,0.0,0.0)
tests_u = TestFESpace(mh,reffe_u,dirichlet_tags=["walls","top"]);
trials_u = TrialFESpace(tests_u,[u_wall,u_top]);
U, V = get_fe_space(trials_u,1), get_fe_space(tests_u,1)
Q = TestFESpace(model,reffe_p;conformity=:L2,constraint=:zeromean)
mfs = Gridap.MultiField.BlockMultiFieldStyle()
X = MultiFieldFESpace([U,Q];style=mfs)
Y = MultiFieldFESpace([V,Q];style=mfs)
# Weak formulation
α = 1.e2
f = (Dc==2) ? VectorValue(1.0,1.0) : VectorValue(1.0,1.0,1.0)
poly = (Dc==2) ? QUAD : HEX
Π_Qh = LocalProjectionMap(divergence,lagrangian,Float64,order-1;space=:P)
graddiv(u,v,dΩ) = ∫(α*Π_Qh(u,dΩ)⋅Π_Qh(v,dΩ))dΩ
biform_u(u,v,dΩ) = ∫(∇(v)⊙∇(u))dΩ + graddiv(u,v,dΩ)
biform((u,p),(v,q),dΩ) = biform_u(u,v,dΩ) - ∫(divergence(v)*p)dΩ - ∫(divergence(u)*q)dΩ
liform((v,q),dΩ) = ∫(v⋅f)dΩ
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
a(u,v) = biform(u,v,dΩ)
l(v) = liform(v,dΩ)
op = AffineFEOperator(a,l,X,Y)
A, b = get_matrix(op), get_vector(op);
# GMG Solver for u
biforms = map(mhl -> get_bilinear_form(mhl,biform_u,qdegree),mh)
patch_decompositions = PatchDecomposition(mh)
smoothers = get_patch_smoothers(
mh,tests_u,biform_u,patch_decompositions,qdegree
);
prolongations = setup_patch_prolongation_operators(
tests_u,biform_u,graddiv,qdegree
);
restrictions = setup_patch_restriction_operators(
tests_u,prolongations,graddiv,qdegree;solver=LUSolver()
);
gmg = GMGLinearSolver(
mh,trials_u,tests_u,biforms,
prolongations,restrictions,
pre_smoothers=smoothers,
post_smoothers=smoothers,
coarsest_solver=LUSolver(),
maxiter=4,mode=:preconditioner,verbose=i_am_main(parts)
);
# Solver
solver_u = gmg;
solver_p = CGSolver(JacobiLinearSolver();maxiter=20,atol=1e-14,rtol=1.e-6,verbose=i_am_main(parts));
solver_u.log.depth = 2
solver_p.log.depth = 2
diag_blocks = [LinearSystemBlock(),BiformBlock((p,q) -> ∫(-1.0/α*p*q)dΩ,Q,Q)]
bblocks = map(CartesianIndices((2,2))) do I
(I[1] == I[2]) ? diag_blocks[I[1]] : LinearSystemBlock()
end
coeffs = [1.0 1.0;
0.0 1.0]
P = BlockTriangularSolver(bblocks,[solver_u,solver_p],coeffs,:upper)
solver = FGMRESSolver(20,P;atol=1e-14,rtol=1.e-8,verbose=i_am_main(parts))
ns = numerical_setup(symbolic_setup(solver,A),A)
x = allocate_in_domain(A); fill!(x,0.0)
solve!(x,ns,b)
xh = FEFunction(X,x);
r = allocate_in_range(A)
mul!(r,A,x)
r .-= b
norm(r) < 1.e-6
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 5218 | using Gridap
using Gridap.Geometry, Gridap.FESpaces, Gridap.Adaptivity, Gridap.ReferenceFEs, Gridap.Arrays
using Gridap.CellData
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers
using LinearAlgebra
order = 2
poly = QUAD
# Geometry
n = 6
cmodel = CartesianDiscreteModel((0,1,0,1),(n,n))
if poly == TRI
cmodel = simplexify(cmodel)
end
labels = get_face_labeling(cmodel)
for D in 1:2
for i in LinearIndices(labels.d_to_dface_to_entity[D])
if labels.d_to_dface_to_entity[D][i] == 9 # Interior faces (not cells)
labels.d_to_dface_to_entity[D][i] = 10 # new entity
end
end
end
push!(labels.tag_to_entities[9],10)
push!(labels.tag_to_entities,[1:8...,10])
push!(labels.tag_to_name,"coarse")
add_tag_from_tags!(labels,"top",[3,4,6])
add_tag_from_tags!(labels,"bottom",[1,2,5])
add_tag_from_tags!(labels,"walls",[7,8])
fmodel = refine(cmodel)
Ωh = Triangulation(fmodel)
ΩH = Triangulation(cmodel)
qdegree = 2*(order+1)
dΩh = Measure(Ωh,qdegree)
dΩH = Measure(ΩH,qdegree)
dΩHh = Measure(ΩH,Ωh,qdegree)
# Spaces
conformity = H1Conformity()
u_exact(x) = VectorValue(x[1]^2,-2.0*x[2]*x[1])
u_bottom = VectorValue(0.0,0.0)
u_top = VectorValue(1.0,0.0)
reffe = ReferenceFE(lagrangian,VectorValue{2,Float64},order)
#VH = TestFESpace(cmodel,reffe,dirichlet_tags="boundary")
#UH = TrialFESpace(VH,u_exact)
#Vh = TestFESpace(fmodel,reffe,dirichlet_tags="boundary")
#Uh = TrialFESpace(Vh,u_exact)
VH = TestFESpace(cmodel,reffe,dirichlet_tags=["bottom","top"])
UH = TrialFESpace(VH,[u_bottom,u_top])
Vh = TestFESpace(fmodel,reffe,dirichlet_tags=["bottom","top"])
Uh = TrialFESpace(Vh,[u_bottom,u_top])
# Weakform
α = 1.e10
f(x) = -Δ(u_exact)(x)
Π_Qh = LocalProjectionMap(divergence,lagrangian,Float64,order-1;space=:P)
lap(u,v,dΩ) = ∫(∇(v)⊙∇(u))dΩ
graddiv(u,v,dΩ) = ∫(α*Π_Qh(v,dΩ)⋅Π_Qh(u,dΩ))dΩ
biform(u,v,dΩ) = lap(u,v,dΩ) + graddiv(u,v,dΩ)
ah(u,v) = biform(u,v,dΩh)
aH(u,v) = biform(u,v,dΩH)
lh(v) = ∫(v⋅f)*dΩh
lH(v) = ∫(v⋅f)*dΩH
oph = AffineFEOperator(ah,lh,Uh,Vh)
opH = AffineFEOperator(aH,lH,UH,VH)
xh_star = get_free_dof_values(solve(oph))
xH_star = get_free_dof_values(solve(opH))
Ah, bh = get_matrix(oph), get_vector(oph);
AH, bH = get_matrix(opH), get_vector(opH);
Mhh = assemble_matrix((u,v)->∫(u⋅v)*dΩh,Vh,Vh)
function project_c2f(xH)
uH = FEFunction(VH,xH)
op = AffineFEOperator((u,v)->∫(u⋅v)*dΩh,v->∫(v⋅uH)*dΩh,Vh,Vh)
return get_matrix(op)\get_vector(op)
end
function project_f2c(rh)
Qrh = Mhh\rh
uh = FEFunction(Vh,Qrh)
assemble_vector(v->∫(v⋅uh)*dΩHh,VH)
end
function interp_c2f(xH)
get_free_dof_values(interpolate(FEFunction(VH,xH),Vh))
end
# Smoother
PD = PatchDecomposition(fmodel)
Ph = PatchFESpace(Vh,PD,reffe;conformity)
Ωp = Triangulation(PD)
dΩp = Measure(Ωp,qdegree)
ap(u,v) = biform(u,v,dΩp)
smoother = RichardsonSmoother(PatchBasedLinearSolver(ap,Ph,Vh),10,0.2)
smoother_ns = numerical_setup(symbolic_setup(smoother,Ah),Ah)
# Prolongation Operator 1
Ṽh = FESpace(fmodel,reffe;dirichlet_tags="coarse")
Ãh = assemble_matrix(ah,Ṽh,Ṽh)
function P1(dxH)
dxh = interp_c2f(dxH)
uh = FEFunction(Vh,dxh)
bh = assemble_vector(v -> graddiv(uh,v,dΩh),Ṽh)
dx̃ = Ãh\bh
ũh = interpolate(FEFunction(Ṽh,dx̃),Vh)
y = dxh - get_free_dof_values(ũh)
return y
end
function R1(rh)
r̃h = get_free_dof_values(interpolate(FEFunction(Vh,rh),Ṽh))
dr̃h = Ãh\r̃h
dxh = interpolate(FEFunction(Ṽh,dr̃h),Vh)
drh = assemble_vector(v -> graddiv(dxh,v,dΩh),Vh)
rH = project_f2c(rh - drh)
return rH
end
# Prolongation Operator 2
patches_mask = PatchBasedSmoothers.get_coarse_node_mask(fmodel,fmodel.glue)
Ih = PatchFESpace(Vh,PD,reffe;conformity=conformity,patches_mask=patches_mask)
I_solver = PatchBasedLinearSolver(ap,Ih,Vh)
I_ns = numerical_setup(symbolic_setup(I_solver,Ah),Ah)
Ai = assemble_matrix(ap,Ih,Ih)
function P2(dxH)
dxh = interp_c2f(dxH)
uh = FEFunction(Vh,dxh)
r̃h = assemble_vector(v -> graddiv(uh,v,dΩp),Ih)
dx̃ = Ai\r̃h
Pdxh = fill(0.0,length(dxh))
PatchBasedSmoothers.inject!(Pdxh,Ih,dx̃)
y = dxh - Pdxh
return y
end
function R2(rh)
r̃h = zero_free_values(Ih)
PatchBasedSmoothers.prolongate!(r̃h,Ih,rh)
dr̃h = Ai\r̃h
dxh = zero_free_values(Vh)
PatchBasedSmoothers.inject!(dxh,Ih,dr̃h)
drh = assemble_vector(v -> graddiv(FEFunction(Vh,dxh),v,dΩh),Vh)
rH = project_f2c(rh - drh)
return rH
end
# Solve
#xh = fill(1.0,size(Ah,2));
xh = randn(size(Ah,2))
rh = bh - Ah*xh
niters = 100
iter = 0
error0 = norm(rh)
error = error0
e_rel = error/error0
while iter < niters && e_rel > 1.0e-10
println("Iter $iter:")
println(" > Initial: ", norm(rh))
solve!(xh,smoother_ns,rh)
println(" > Pre-smoother: ", norm(rh))
rH = R1(rh)
qH = AH\rH
qh = P1(qH)
rh = rh - Ah*qh
xh = xh + qh
println(" > Post-correction: ", norm(rh))
solve!(xh,smoother_ns,rh)
iter += 1
error = norm(rh)
e_rel = error/error0
println(" > Final: ",error, " - ", e_rel)
end
uh = FEFunction(Uh,xh)
eh = uh - u_exact
uh_star = FEFunction(Uh,xh_star)
writevtk(Ωh,"data/solution",cellfields=["u_star"=>uh_star])
writevtk(cmodel,"data/cmodel")
#writevtk(Ωh,"data/solution",cellfields=["u"=>uh,"u_star"=>uh_star,"error"=>eh])
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 6326 | using Gridap
using Gridap.Geometry, Gridap.FESpaces, Gridap.Adaptivity, Gridap.ReferenceFEs, Gridap.Arrays
using Gridap.CellData
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers
using PartitionedArrays, GridapDistributed
using LinearAlgebra
function DModel(parts,model)
models = map(p -> model, parts)
n = num_cells(model)
indices = map(p -> LocalIndices(n,1,collect(1:n),fill(1,n)), parts)
gids = PRange(indices)
return GridapDistributed.DistributedDiscreteModel(models,gids)
end
order = 2
poly = QUAD
# Geometry
n = 6
cmodel = CartesianDiscreteModel((0,1,0,1),(n,n))
if poly == TRI
cmodel = simplexify(cmodel)
end
labels = get_face_labeling(cmodel)
for D in 1:2
for i in LinearIndices(labels.d_to_dface_to_entity[D])
if labels.d_to_dface_to_entity[D][i] == 9 # Interior faces (not cells)
labels.d_to_dface_to_entity[D][i] = 10 # new entity
end
end
end
push!(labels.tag_to_entities[9],10)
push!(labels.tag_to_entities,[1:8...,10])
push!(labels.tag_to_name,"coarse")
fmodel = refine(cmodel)
np = 1
parts = with_mpi() do distribute
distribute(LinearIndices((np,)))
end
dcmodel = DModel(parts,cmodel)
dfmodel = DModel(parts,fmodel)
dglue = map(p -> get_adaptivity_glue(fmodel), parts)
mh_clevel = MultilevelTools.ModelHierarchyLevel(2,dcmodel,nothing,nothing,nothing)
mh_flevel = MultilevelTools.ModelHierarchyLevel(1,dfmodel,dglue,nothing,nothing)
mh = HierarchicalArray([mh_flevel,mh_clevel],[parts,parts])
Ωh = Triangulation(dfmodel)
ΩH = Triangulation(dcmodel)
qdegree = 2*(order+1)
dΩh = Measure(Ωh,qdegree)
dΩH = Measure(ΩH,qdegree)
dΩHh = Measure(ΩH,Ωh,qdegree)
# Spaces
conformity = H1Conformity()
u_exact(x) = VectorValue(x[1]^2,-2.0*x[2]*x[1])
#u_exact(x) = VectorValue(x[1]*(x[1]-1.0)*x[2]*(x[2]-1.0),(1.0-2.0*x[1])*(1.0/3.0*x[2]^3 - 1.0/2.0*x[2]^2))
reffe = ReferenceFE(lagrangian,VectorValue{2,Float64},order)
VH = TestFESpace(dcmodel,reffe,dirichlet_tags="boundary")
UH = TrialFESpace(VH,u_exact)
Vh = TestFESpace(dfmodel,reffe,dirichlet_tags="boundary")
Uh = TrialFESpace(Vh,u_exact)
# Weakform
α = 1.e10
f(x) = -Δ(u_exact)(x)
Π_Qh = LocalProjectionMap(divergence,lagrangian,Float64,order-1;space=:P)
lap(u,v,dΩ) = ∫(∇(v)⊙∇(u))dΩ
graddiv(u,v,dΩ) = ∫(α*Π_Qh(v,dΩ)⋅Π_Qh(u,dΩ))dΩ
biform(u,v,dΩ) = lap(u,v,dΩ) + graddiv(u,v,dΩ)
ah(u,v) = biform(u,v,dΩh)
aH(u,v) = biform(u,v,dΩH)
lh(v) = ∫(v⋅f)*dΩh
lH(v) = ∫(v⋅f)*dΩH
oph = AffineFEOperator(ah,lh,Uh,Vh)
opH = AffineFEOperator(aH,lH,UH,VH)
xh_star = get_free_dof_values(solve(oph))
xH_star = get_free_dof_values(solve(opH))
Ah, bh = get_matrix(oph), get_vector(oph);
AH, bH = get_matrix(opH), get_vector(opH);
Mhh = assemble_matrix((u,v)->∫(u⋅v)*dΩh,Vh,Vh)
function project_f2c(rh)
Qrh = Mhh\rh
uh = FEFunction(Vh,Qrh)
assemble_vector(v->∫(v⋅uh)*dΩHh,VH)
end
# Smoother
PD = PatchDecomposition(dfmodel)
Ph = PatchFESpace(Vh,PD,reffe;conformity)
Ωp = Triangulation(PD)
dΩp = Measure(Ωp,qdegree)
ap(u,v) = biform(u,v,dΩp)
smoother = RichardsonSmoother(PatchBasedLinearSolver(ap,Ph,Vh),10,0.2)
smoother_ns = numerical_setup(symbolic_setup(smoother,Ah),Ah)
# Prolongation Operator 1
Ṽh = FESpace(dfmodel,reffe;dirichlet_tags="coarse")
Ãh = assemble_matrix(ah,Ṽh,Ṽh)
function P1(dxH)
uh = interpolate(FEFunction(VH,dxH),Vh)
dxh = get_free_dof_values(uh)
bh = assemble_vector(v -> graddiv(uh,v,dΩh),Ṽh)
dx̃ = Ãh\bh
ũh = interpolate(FEFunction(Ṽh,dx̃),Vh)
y = dxh - get_free_dof_values(ũh)
return y
end
function R1_bis(rh)
r̃h = get_free_dof_values(interpolate(FEFunction(Vh,rh),Ṽh))
dr̃h = Ãh\r̃h
drh = get_free_dof_values(interpolate(FEFunction(Ṽh,dr̃h),Vh))
rH = project_f2c(rh - drh)
return rH
end
function R1(rh)
r̃h = get_free_dof_values(interpolate(FEFunction(Vh,rh),Ṽh))
dr̃h = Ãh\r̃h
dxh = interpolate(FEFunction(Ṽh,dr̃h),Vh)
drh = assemble_vector(v -> graddiv(dxh,v,dΩh),Vh)
rH = project_f2c(rh - drh)
return rH
end
# Prolongation Operator 2
mh_Vh = FESpace(mh,reffe;dirichlet_tags="boundary")
cell_conformity = mh_Vh[1].cell_conformity
patches_mask = PatchBasedSmoothers.get_coarse_node_mask(dfmodel,dglue)
Ih = PatchFESpace(Vh,PD,cell_conformity;patches_mask=patches_mask)
I_solver = PatchBasedLinearSolver(ap,Ih,Vh)
I_ns = numerical_setup(symbolic_setup(I_solver,Ah),Ah)
Ai = assemble_matrix(ap,Ih,Ih)
function P2(dxH)
uh = interpolate(FEFunction(VH,dxH),Vh)
dxh = get_free_dof_values(uh)
r̃h = assemble_vector(v -> graddiv(uh,v,dΩp),Ih)
dx̃ = Ai\r̃h
Pdxh = zero_free_values(Vh)
PatchBasedSmoothers.inject!(Pdxh,Ih,dx̃)
y = dxh - Pdxh
return y
end
function R2_bis(rh)
r̃h = zero_free_values(Ih)
PatchBasedSmoothers.prolongate!(r̃h,Ih,rh)
dr̃h = Ai\r̃h
drh = zero_free_values(Vh)
PatchBasedSmoothers.inject!(drh,Ih,dr̃h)
rH = project_f2c(rh - drh)
return rH
end
function R2(rh)
r̃h = zero_free_values(Ih)
PatchBasedSmoothers.prolongate!(r̃h,Ih,rh)
dr̃h = Ai\r̃h
dxh = zero_free_values(Vh)
PatchBasedSmoothers.inject!(dxh,Ih,dr̃h)
drh = assemble_vector(v -> graddiv(FEFunction(Vh,dxh),v,dΩh),Vh)
rH = project_f2c(rh - drh)
return rH
end
# Prolongation Operator 3
prolongations = setup_patch_prolongation_operators(
mh_Vh,biform,graddiv,qdegree
);
restrictions = setup_patch_restriction_operators(
mh_Vh,prolongations,graddiv,qdegree
);
function P3(dxH)
dxh = zero_free_values(Vh)
mul!(dxh,prolongations[1],dxH)
return dxh
end
function R3(rh)
rH = zero_free_values(UH)
mul!(rH,restrictions[1],rh)
return rH
end
# Solve
begin
xh = pfill(1.0,partition(axes(Ah,2)));
#xh = prandn(partition(axes(Ah,2)))
rh = bh - Ah*xh
niters = 100
iter = 0
error0 = norm(rh)
error = error0
e_rel = error/error0
while iter < niters && e_rel > 1.0e-10
println("Iter $iter:")
println(" > Initial: ", norm(rh))
solve!(xh,smoother_ns,rh)
println(" > Pre-smoother: ", norm(rh))
rH = R3(rh)
println(" > rH: ", norm(rH))
qH = AH\rH
println(" > qH: ", norm(qH))
qh = P3(qH)
println(" > qh: ", norm(qh))
rh = rh - Ah*qh
xh = xh + qh
println(" > Post-correction: ", norm(rh))
solve!(xh,smoother_ns,rh)
iter += 1
error = norm(rh)
e_rel = error/error0
println(" > Final: ",error, " - ", e_rel)
end
end
uh = FEFunction(Uh,xh)
eh = FEFunction(Vh,rh)
uh_star = FEFunction(Uh,xh_star)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 5636 | using Gridap
using Gridap.Geometry, Gridap.FESpaces, Gridap.Adaptivity, Gridap.ReferenceFEs, Gridap.Arrays
using Gridap.CellData, Gridap.Fields
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers
using LinearAlgebra
order = 3
poly = QUAD
# Geometry
n = 6
cmodel = CartesianDiscreteModel((0,1,0,1),(n,n))
if poly == TRI
cmodel = simplexify(cmodel)
end
fmodel = refine(cmodel)
Ωh = Triangulation(fmodel)
ΩH = Triangulation(cmodel)
qdegree = 2*(order+1)
dΩh = Measure(Ωh,qdegree)
dΩH = Measure(ΩH,qdegree)
dΩHh = Measure(ΩH,Ωh,qdegree)
# Spaces
conformity = H1Conformity()
u_exact(x) = VectorValue(x[1]^2,-2.0*x[2]*x[1])
#u_exact(x) = VectorValue(x[1]*(x[1]-1.0)*x[2]*(x[2]-1.0),(1.0-2.0*x[1])*(1.0/3.0*x[2]^3 - 1.0/2.0*x[2]^2))
reffe = ReferenceFE(lagrangian,VectorValue{2,Float64},order)
VH = TestFESpace(cmodel,reffe,dirichlet_tags="boundary")
UH = TrialFESpace(VH,u_exact)
Vh = TestFESpace(fmodel,reffe,dirichlet_tags="boundary")
Uh = TrialFESpace(Vh,u_exact)
# Weakform
α = 1.e8
f(x) = -Δ(u_exact)(x)
Π_Qh = LocalProjectionMap(divergence,lagrangian,Float64,order-1;space=:P)
lap(u,v,dΩ) = ∫(∇(v)⊙∇(u))dΩ
graddiv(u,v,dΩ) = ∫(α*Π_Qh(v,dΩ)⋅Π_Qh(u,dΩ))dΩ
biform(u,v,dΩ) = lap(u,v,dΩ) + graddiv(u,v,dΩ)
ah(u,v) = biform(u,v,dΩh)
aH(u,v) = biform(u,v,dΩH)
lh(v) = ∫(v⋅f)*dΩh
lH(v) = ∫(v⋅f)*dΩH
oph = AffineFEOperator(ah,lh,Uh,Vh)
opH = AffineFEOperator(aH,lH,UH,VH)
xh_star = get_free_dof_values(solve(oph))
xH_star = get_free_dof_values(solve(opH))
Ah, bh = get_matrix(oph), get_vector(oph);
AH, bH = get_matrix(opH), get_vector(opH);
Mhh = assemble_matrix((u,v)->∫(u⋅v)*dΩh,Vh,Vh)
function project_c2f(xH)
uH = FEFunction(VH,xH)
op = AffineFEOperator((u,v)->∫(u⋅v)*dΩh,v->∫(v⋅uH)*dΩh,Vh,Vh)
return get_matrix(op)\get_vector(op)
end
function project_f2c(rh)
Qrh = Mhh\rh
uh = FEFunction(Vh,Qrh)
assemble_vector(v->∫(v⋅uh)*dΩHh,VH)
end
function interp_c2f(xH)
get_free_dof_values(interpolate(FEFunction(VH,xH),Vh))
end
# Smoother
PD = PatchDecomposition(fmodel)
Ph = PatchFESpace(Vh,PD,reffe;conformity)
Ωp = Triangulation(PD)
dΩp = Measure(Ωp,qdegree)
ap(u,v) = biform(u,v,dΩp)
smoother = RichardsonSmoother(PatchBasedLinearSolver(ap,Ph,Vh),20,0.2)
smoother_ns = numerical_setup(symbolic_setup(smoother,Ah),Ah)
# New prolongation operator
ftopo = get_grid_topology(fmodel)
n2e_map = Gridap.Geometry.get_faces(ftopo,0,1)
e2n_map = Gridap.Geometry.get_faces(ftopo,1,0)
ccoords = get_node_coordinates(cmodel)
fcoords = get_node_coordinates(fmodel)
function is_fine(n)
A = fcoords[n] ∉ ccoords
edges = n2e_map[n]
for e in edges
nbor_nodes = e2n_map[e]
A = A && all(m -> fcoords[m] ∉ ccoords,nbor_nodes)
end
return !A
end
_patches_mask = map(is_fine,LinearIndices(fcoords))
patches_mask = reshape(_patches_mask,length(fcoords))
Ih = PatchFESpace(Vh,PD,reffe;conformity=conformity,patches_mask=patches_mask)
I_solver = PatchBasedLinearSolver(ap,Ih,Vh)
I_ns = numerical_setup(symbolic_setup(I_solver,Ah),Ah)
Ai = assemble_matrix(ap,Ih,Ih)
patches_mask_2 = GridapSolvers.PatchBasedSmoothers.get_coarse_node_mask(fmodel,fmodel.glue)
patches_mask_2 == patches_mask
_patches_mask_2 = reshape(patches_mask_2,size(fcoords))
function prolongate(dxH)
dxh = interp_c2f(dxH)
uh = FEFunction(Vh,dxh)
bh = assemble_vector(v -> graddiv(uh,v,dΩp),Ih)
dx̃ = Ai\bh
Pdxh = fill(0.0,length(dxh))
GridapSolvers.PatchBasedSmoothers.inject!(Pdxh,Ih,dx̃)
y = dxh - Pdxh
return y
end
# Solve
xh = fill(1.0,size(Ah,2));
rh = bh - Ah*xh
niters = 20
iter = 0
error = norm(bh - Ah*xh)
while iter < niters && error > 1.0e-8
println("Iter $iter:")
println(" > Initial: ", norm(rh))
solve!(xh,smoother_ns,rh)
println(" > Pre-smoother: ", norm(rh))
rH = project_f2c(rh)
qH = AH\rH
qh = prolongate(qH)
rh = rh - Ah*qh
xh = xh + qh
println(" > Post-correction: ", norm(rh))
solve!(xh,smoother_ns,rh)
iter += 1
error = norm(bh - Ah*xh)
println(" > Final: ",error)
end
uh = FEFunction(Uh,xh)
eh = FEFunction(Vh,rh)
uh_star = FEFunction(Uh,xh_star)
#writevtk(Ωh,"data/h1div_error";cellfields=["eh"=>eh,"u"=>uh,"u_star"=>uh_star,"u_exact"=>u_exact])
"""
reffe_p = ReferenceFE(lagrangian,Float64,0;space=:P)
QH = FESpace(cmodel,reffe_p;conformity=:L2)
checks = fill(false,(num_free_dofs(QH),num_free_dofs(VH)))
for i in 1:num_free_dofs(QH)
qH = zeros(num_free_dofs(QH)); qH[i] = 1.0
for j in 1:num_free_dofs(VH)
vH = zeros(num_free_dofs(VH)); vH[j] = 1.0
vh = interp_c2f(vH)
ϕH = FEFunction(QH,qH)
φh = FEFunction(Vh,vh)
φH = FEFunction(VH,vH)
lhs = sum(∫(divergence(φh)*ϕH)*dΩh)
rhs = sum(∫(divergence(φH)*ϕH)*dΩh)
checks[i,j] = abs(lhs-rhs) < 1.0e-10
end
end
all(checks)
reffe = LagrangianRefFE(VectorValue{2,Float64},QUAD,2)
dof_ids = get_cell_dof_ids(Vh)
local_dof_nodes = lazy_map(Reindex(reffe.reffe.dofs.nodes),reffe.reffe.dofs.dof_to_node)
cell_maps = get_cell_map(fmodel)
dof_nodes = Vector{VectorValue{2,Float64}}(undef,num_free_dofs(Vh))
for (ids,cmap) in zip(dof_ids,cell_maps)
for (i,id) in enumerate(ids)
if id > 0
dof_nodes[id] = cmap(local_dof_nodes[i])
end
end
end
V̂h_dofs = findall(x -> !isempty(x),Ih.dof_to_pdof)
checks = fill(false,(num_free_dofs(QH),length(V̂h_dofs)))
for i in 1:num_free_dofs(QH)
qH = zeros(num_free_dofs(QH)); qH[i] = 1.0
for (j,j_dof) in enumerate(V̂h_dofs)
vh = zeros(num_free_dofs(Vh)); vh[j_dof] = 1.0
ϕH = FEFunction(QH,qH)
φh = FEFunction(Vh,vh)
lhs = sum(∫(divergence(φh)*ϕH)*dΩHh)
checks[i,j] = abs(lhs) < 1.0e-10
end
end
all(checks)
""" | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 6264 | using Gridap
using Gridap.Geometry, Gridap.FESpaces, Gridap.Adaptivity, Gridap.ReferenceFEs, Gridap.Arrays
using Gridap.CellData
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers
using PartitionedArrays, GridapDistributed, GridapP4est
using LinearAlgebra
order = 2
poly = QUAD
# Geometry
n = 6
cmodel = CartesianDiscreteModel((0,1,0,1),(n,n))
if poly == TRI
cmodel = simplexify(cmodel)
end
labels = get_face_labeling(cmodel)
for D in 1:2
for i in LinearIndices(labels.d_to_dface_to_entity[D])
if labels.d_to_dface_to_entity[D][i] == 9 # Interior faces (not cells)
labels.d_to_dface_to_entity[D][i] = 10 # new entity
end
end
end
push!(labels.tag_to_entities[9],10)
push!(labels.tag_to_entities,[1:8...,10])
push!(labels.tag_to_name,"coarse")
add_tag_from_tags!(labels,"top",[3,4,6])
add_tag_from_tags!(labels,"bottom",[1,2,5])
add_tag_from_tags!(labels,"walls",[7,8])
np = 1
parts = with_mpi() do distribute
distribute(LinearIndices((np,)))
end
dcmodel = OctreeDistributedDiscreteModel(parts,cmodel,0)
mh = ModelHierarchy(parts,dcmodel,[np,np])
dcmodel = MultilevelTools.get_model(mh,2)
dfmodel = MultilevelTools.get_model(mh,1)
Ωh = Triangulation(dfmodel)
ΩH = Triangulation(dcmodel)
qdegree = 2*(order+1)
dΩh = Measure(Ωh,qdegree)
dΩH = Measure(ΩH,qdegree)
dΩHh = Measure(ΩH,Ωh,qdegree)
# Spaces
conformity = H1Conformity()
u_exact(x) = VectorValue(x[1]^2,-2.0*x[2]*x[1])
u_bottom = VectorValue(0.0,0.0)
u_top = VectorValue(1.0,0.0)
reffe = ReferenceFE(lagrangian,VectorValue{2,Float64},order)
#VH = TestFESpace(dcmodel,reffe,dirichlet_tags="boundary")
#UH = TrialFESpace(VH,u_exact)
#Vh = TestFESpace(dfmodel,reffe,dirichlet_tags="boundary")
#Uh = TrialFESpace(Vh,u_exact)
VH = TestFESpace(dcmodel,reffe,dirichlet_tags=["bottom","top"])
UH = TrialFESpace(VH,[u_bottom,u_top])
Vh = TestFESpace(dfmodel,reffe,dirichlet_tags=["bottom","top"])
Uh = TrialFESpace(Vh,[u_bottom,u_top])
# Weakform
α = 1.e10
f(x) = -Δ(u_exact)(x)
Π_Qh = LocalProjectionMap(divergence,lagrangian,Float64,order-1;space=:P)
lap(u,v,dΩ) = ∫(∇(v)⊙∇(u))dΩ
graddiv(u,v,dΩ) = ∫(α*Π_Qh(v,dΩ)⋅Π_Qh(u,dΩ))dΩ
biform(u,v,dΩ) = lap(u,v,dΩ) + graddiv(u,v,dΩ)
ah(u,v) = biform(u,v,dΩh)
aH(u,v) = biform(u,v,dΩH)
lh(v) = ∫(v⋅f)*dΩh
lH(v) = ∫(v⋅f)*dΩH
oph = AffineFEOperator(ah,lh,Uh,Vh)
opH = AffineFEOperator(aH,lH,UH,VH)
xh_star = get_free_dof_values(solve(oph))
xH_star = get_free_dof_values(solve(opH))
Ah, bh = get_matrix(oph), get_vector(oph);
AH, bH = get_matrix(opH), get_vector(opH);
Mhh = assemble_matrix((u,v)->∫(u⋅v)*dΩh,Vh,Vh)
function project_f2c(rh)
Qrh = Mhh\rh
uh = FEFunction(Vh,Qrh)
assemble_vector(v->∫(v⋅uh)*dΩHh,VH)
end
# Smoother
PD = PatchDecomposition(dfmodel)
Ph = PatchFESpace(Vh,PD,reffe;conformity)
Ωp = Triangulation(PD)
dΩp = Measure(Ωp,qdegree)
ap(u,v) = biform(u,v,dΩp)
smoother = RichardsonSmoother(PatchBasedLinearSolver(ap,Ph,Vh),10,0.2)
smoother_ns = numerical_setup(symbolic_setup(smoother,Ah),Ah)
# Prolongation Operator 1
Ṽh = FESpace(dfmodel,reffe;dirichlet_tags="coarse")
Ãh = assemble_matrix(ah,Ṽh,Ṽh)
function P1(dxH)
uh = interpolate(FEFunction(VH,dxH),Vh)
dxh = get_free_dof_values(uh)
bh = assemble_vector(v -> graddiv(uh,v,dΩh),Ṽh)
dx̃ = Ãh\bh
ũh = interpolate(FEFunction(Ṽh,dx̃),Vh)
y = dxh - get_free_dof_values(ũh)
return y
end
function R1_bis(rh)
r̃h = get_free_dof_values(interpolate(FEFunction(Vh,rh),Ṽh))
dr̃h = Ãh\r̃h
drh = get_free_dof_values(interpolate(FEFunction(Ṽh,dr̃h),Vh))
rH = project_f2c(rh - drh)
return rH
end
function R1(rh)
r̃h = get_free_dof_values(interpolate(FEFunction(Vh,rh),Ṽh))
dr̃h = Ãh\r̃h
dxh = interpolate(FEFunction(Ṽh,dr̃h),Vh)
drh = assemble_vector(v -> graddiv(dxh,v,dΩh),Vh)
rH = project_f2c(rh - drh)
return rH
end
# Prolongation Operator 2
#mh_Vh = FESpace(mh,reffe;dirichlet_tags="boundary")
mh_Vh = FESpace(mh,reffe;dirichlet_tags=["bottom","top"])
cell_conformity = mh_Vh[1].cell_conformity
dglue = mh_Vh[1].mh_level.ref_glue
patches_mask = PatchBasedSmoothers.get_coarse_node_mask(dfmodel,dglue)
Ih = PatchFESpace(Vh,PD,cell_conformity;patches_mask=patches_mask)
I_solver = PatchBasedLinearSolver(ap,Ih,Vh)
I_ns = numerical_setup(symbolic_setup(I_solver,Ah),Ah)
Ai = assemble_matrix(ap,Ih,Ih)
function P2(dxH)
uh = interpolate(FEFunction(VH,dxH),Vh)
dxh = get_free_dof_values(uh)
r̃h = assemble_vector(v -> graddiv(uh,v,dΩp),Ih)
dx̃ = Ai\r̃h
Pdxh = zero_free_values(Vh)
PatchBasedSmoothers.inject!(Pdxh,Ih,dx̃)
y = dxh - Pdxh
return y
end
function R2_bis(rh)
r̃h = zero_free_values(Ih)
PatchBasedSmoothers.prolongate!(r̃h,Ih,rh)
dr̃h = Ai\r̃h
drh = zero_free_values(Vh)
PatchBasedSmoothers.inject!(drh,Ih,dr̃h)
rH = project_f2c(rh - drh)
return rH
end
function R2(rh)
r̃h = zero_free_values(Ih)
PatchBasedSmoothers.prolongate!(r̃h,Ih,rh)
dr̃h = Ai\r̃h
dxh = zero_free_values(Vh)
PatchBasedSmoothers.inject!(dxh,Ih,dr̃h)
drh = assemble_vector(v -> graddiv(FEFunction(Vh,dxh),v,dΩh),Vh)
rH = project_f2c(rh - drh)
return rH
end
# Prolongation Operator 3
prolongations = setup_patch_prolongation_operators(
mh_Vh,biform,graddiv,qdegree
);
restrictions = setup_patch_restriction_operators(
mh_Vh,prolongations,graddiv,qdegree
);
function P3(dxH)
dxh = zero_free_values(Vh)
mul!(dxh,prolongations[1],dxH)
return dxh
end
function R3(rh)
rH = zero_free_values(UH)
mul!(rH,restrictions[1],rh)
return rH
end
# Solve
xh = pfill(1.0,partition(axes(Ah,2)));
#xh = prandn(partition(axes(Ah,2)))
rh = bh - Ah*xh
niters = 10
iter = 0
err0 = norm(rh)
err = err0
e_rel = err/err0
while iter < niters && e_rel > 1.0e-10
println("Iter $iter:")
println(" > Initial: ", norm(rh))
solve!(xh,smoother_ns,rh)
println(" > Pre-smoother: ", norm(rh))
rH = R3(rh)
println(" > rH: ", norm(rH))
qH = AH\rH
println(" > qH: ", norm(qH))
qh = P3(qH)
println(" > qh: ", norm(qh))
rh = rh - Ah*qh
xh = xh + qh
println(" > Post-correction: ", norm(rh))
solve!(xh,smoother_ns,rh)
iter += 1
err = norm(rh)
e_rel = err/err0
println(" > Final: ",err, " - ", e_rel)
end
uh = FEFunction(Uh,xh)
eh = FEFunction(Vh,rh)
uh_star = FEFunction(Uh,xh_star)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 6464 | using Gridap
using Gridap.Geometry, Gridap.FESpaces, Gridap.Adaptivity, Gridap.ReferenceFEs, Gridap.Arrays
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers
u_h1(x) = x[1] + x[2]
# u_h1(x) = x[1]*(1-x[1])*x[2]*(1-x[2])
#u_hdiv(x) = VectorValue(x[1],x[2])
u_hdiv(x) = VectorValue([x[1]*(1.0-x[1]),-x[2]*(1.0-x[2])])
a_h1(u,v,dΩ) = ∫(u⋅v)*dΩ
a_hdiv(u,v,dΩ) = ∫(u⋅v + divergence(u)⋅divergence(v))*dΩ
conf = :hdiv
order = 1
poly = QUAD
cmodel = CartesianDiscreteModel((0,1,0,1),(16,16))
if poly == TRI
cmodel = simplexify(cmodel)
end
fmodel = refine(cmodel)
Ωh = Triangulation(fmodel)
ΩH = Triangulation(cmodel)
qdegree = 2*(order+1)
dΩh = Measure(Ωh,qdegree)
dΩH = Measure(ΩH,qdegree)
dΩHh = Measure(ΩH,Ωh,qdegree)
if conf == :h1
u_bc = u_h1
conformity = H1Conformity()
reffe = ReferenceFE(lagrangian,Float64,order)
ah(u,v) = a_h1(u,v,dΩh)
aH(u,v) = a_h1(u,v,dΩH)
f = zero(Float64)
else
u_bc = u_hdiv
conformity = DivConformity()
reffe = ReferenceFE(raviart_thomas,Float64,order)
ah(u,v) = a_hdiv(u,v,dΩh)
aH(u,v) = a_hdiv(u,v,dΩH)
f = zero(VectorValue{2,Float64})
end
lh(v) = ∫(v⋅f)*dΩh
lH(v) = ∫(v⋅f)*dΩH
VH = TestFESpace(cmodel,reffe,dirichlet_tags="boundary")
UH = TrialFESpace(VH,u_bc)
Vh = TestFESpace(fmodel,reffe,dirichlet_tags="boundary")
Uh = TrialFESpace(Vh,u_bc)
oph = AffineFEOperator(ah,lh,Uh,Vh)
opH = AffineFEOperator(aH,lH,UH,VH)
xh_star = get_free_dof_values(solve(oph))
xH_star = get_free_dof_values(solve(opH))
Ah, bh = get_matrix(oph), get_vector(oph);
AH, bH = get_matrix(opH), get_vector(opH);
Mhh = assemble_matrix((u,v)->∫(u⋅v)*dΩh,Vh,Vh)
function compute_MhH()
MhH = zeros(num_free_dofs(Vh),num_free_dofs(VH))
xHi = fill(0.0,num_free_dofs(VH))
for iH in 1:num_free_dofs(VH)
fill!(xHi,0.0); xHi[iH] = 1.0
vHi = FEFunction(VH,xHi)
vH = assemble_vector((v)->∫(v⋅vHi)*dΩh,Vh)
MhH[:,iH] .= vH
end
return MhH
end
MhH = compute_MhH()
# Projection operators
function Λ_project(xh)
uh = FEFunction(Vh,xh)
op = AffineFEOperator((u,v)->∫(u⋅v)*dΩh,v->∫(v⋅uh + divergence(v)⋅divergence(uh))*dΩh,Vh,Vh)
return get_matrix(op)\get_vector(op)
end
function project_c2f(xH)
uH = FEFunction(VH,xH)
op = AffineFEOperator((u,v)->∫(u⋅v)*dΩh,v->∫(v⋅uH)*dΩh,Vh,Vh)
return get_matrix(op)\get_vector(op)
end
function Λ_project_c2f(xH)
uH = FEFunction(VH,xH)
op = AffineFEOperator((u,v)->∫(u⋅v)*dΩh,v->∫(v⋅uH + divergence(v)⋅divergence(uH))*dΩh,Vh,Vh)
return get_matrix(op)\get_vector(op)
end
function Λ_project_f2c(xh)
uh = FEFunction(Vh,xh)
op = AffineFEOperator((u,v)->∫(u⋅v)*dΩH,v->∫(v⋅uh + divergence(v)⋅divergence(uh))*dΩHh,VH,VH)
return get_matrix(op)\get_vector(op)
end
function project_f2c(xh)
uh = FEFunction(Vh,xh)
op = AffineFEOperator((u,v)->∫(u⋅v)*dΩH,v->∫(v⋅uh)*dΩHh,VH,VH)
return get_matrix(op)\get_vector(op)
end
function interp_f2c(xh)
get_free_dof_values(interpolate(FEFunction(Vh,xh),VH))
end
function dotH(a::AbstractVector,b::AbstractVector)
_a = FEFunction(VH,a)
_b = FEFunction(VH,b)
dotH(_a,_b)
end
function dotH(a,b)
sum(∫(a⋅b)*dΩH)
end
function doth(a::AbstractVector,b::AbstractVector)
_a = FEFunction(Vh,a)
_b = FEFunction(Vh,b)
doth(_a,_b)
end
function doth(a,b)
sum(∫(a⋅b)*dΩh)
end
# Patch Decomposition
PD = PatchDecomposition(fmodel)
Ph = PatchFESpace(Vh,PD,reffe;conformity)
Ωp = Triangulation(PD)
dΩp = Measure(Ωp,qdegree)
if conf == :h1
smoother = RichardsonSmoother(JacobiLinearSolver(),5,0.6)
else
ap(u,v) = a_hdiv(u,v,dΩp)
smoother = RichardsonSmoother(PatchBasedLinearSolver(ap,Ph,Vh),10,0.2)
Ap = assemble_matrix(ap,Ph,Ph)
end
smoother_ns = numerical_setup(symbolic_setup(smoother,Ah),Ah)
function smooth!(x,r)
A = smoother_ns.A
Ap = smoother_ns.Mns.Ap_ns.A
dx = smoother_ns.dx
rp = smoother_ns.Mns.caches[1]
dxp = smoother_ns.Mns.caches[2]
w, w_sums = smoother_ns.Mns.weights
w_sums = fill(1.0,length(w_sums))
β = 0.4
niter = 10
for i in 1:niter
_r = bh - Λ_project(x)
PatchBasedSmoothers.prolongate!(rp,Ph,r,w,w_sums)
dxp = Ap\rp
PatchBasedSmoothers.inject!(dx,Ph,dxp,w,w_sums)
x .+= β*dx
r .-= β*A*dx
end
end
xh = fill(1.0,size(Ah,2))
rh = bh - Ah*xh
niters = 10
wH = randn(size(AH,2))
wh = project_c2f(wH)
function project_f2c_bis(rh)
Qrh = Mhh\rh
uh = FEFunction(Vh,Qrh)
assemble_vector(v->∫(v⋅uh)*dΩHh,VH)
end
iter = 0
error = norm(bh - Ah*xh)
while iter < niters && error > 1.0e-8
println("Iter $iter:")
println(" > Pre-smoother: ")
println(" > norm(xh) = ",norm(xh))
println(" > norm(rh) = ",norm(rh))
solve!(xh,smoother_ns,rh)
println(" > Post-smoother: ")
println(" > norm(xh) = ",norm(xh))
println(" > norm(rh) = ",norm(rh))
rH = project_f2c_bis(rh)
qH = AH\rH
qh = project_c2f(qH)
println(" > GMG approximation properties:")
println(" > (AH*qH,wH) = ",dotH(AH*qH,wH))
println(" > (rH,wH) = ",dotH(rH,wH))
println(" > (rh,wh) = ",doth(rh,wh))
println(" > (Ah*(x-xh),wh) = ",doth(Ah*(xh_star-xh),wh))
rh = rh - Ah*qh
xh = xh + qh
solve!(xh,smoother_ns,rh)
iter += 1
error = norm(bh - Ah*xh)
println(" > error = ",error)
end
######################################################################################
using GridapSolvers.PatchBasedSmoothers: prolongate!, inject!, compute_weight_operators
xh = fill(1.0,size(Ah,2))
rh = bh - Ah*xh
w, w_sums = compute_weight_operators(Ph,Ph.Vh)
rp = fill(0.0,size(Ap,2))
prolongate!(rp,Ph,rh)
xp = Ap\rp
dxh = fill(0.0,size(Ah,2))
inject!(dxh,Ph,xp,w,w_sums)
_rh = fill(0.0,size(Ah,2))
inject!(_rh,Ph,rp,w,w_sums)
patch_cells = PD.patch_cells
ids_Ph = get_cell_dof_ids(Ph)
ids_Vh = get_cell_dof_ids(Vh)
patch_ids_Ph = Table(ids_Ph,patch_cells.ptrs)
patch_ids_Vh = Table(lazy_map(Reindex(ids_Vh),patch_cells.data),patch_cells.ptrs)
######################################################################################
using LinearAlgebra
function LinearAlgebra.ldiv!(x,ns,b)
solve!(x,ns,b)
end
using IterativeSolvers
x = zeros(size(Ah,2))
cg!(x,Ah,bh;Pl=smoother_ns.Mns,verbose=true)
######################################################################################
_s = IS_ConjugateGradientSolver(maxiter=50,reltol=1.e-16,verbose=true)
_ns = numerical_setup(symbolic_setup(_s,Mhh),Mhh)
x = zeros(size(Mhh,2))
_rh = copy(rh)
solve!(x,_ns,_rh)
norm(rh - Mhh*x)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 3657 | using LinearAlgebra
using FillArrays, BlockArrays
using Gridap
using Gridap.ReferenceFEs, Gridap.Algebra, Gridap.Geometry, Gridap.FESpaces, Gridap.Polynomials
using Gridap.CellData, Gridap.MultiField, Gridap.Arrays, Gridap.Fields, Gridap.Helpers
using PartitionedArrays
using GridapDistributed
using GridapPETSc
using GridapSolvers
using GridapSolvers.LinearSolvers, GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers, GridapSolvers.NonlinearSolvers
using GridapSolvers.BlockSolvers: NonlinearSystemBlock, LinearSystemBlock, BiformBlock, TriformBlock
using GridapSolvers.BlockSolvers: BlockTriangularSolver, BlockDiagonalSolver
using GridapSolvers.MultilevelTools: get_level_parts
function HuntModelHierarchy(
parts,np_per_level,nc
)
return CartesianModelHierarchy(
parts,np_per_level,(-1,1,-1,1,0,0.2),nc;
add_labels! = add_labels_hunt!,
isperiodic = (false,false,true),
#map = hunt_stretch_map(1.0,sol.Ha,1.0,1.0,adapt),
nrefs = (2,2,2)
)
end
function add_labels_hunt!(labels)
add_tag_from_tags!(labels,"noslip",[1:20...,23,24,25,26])
add_tag_from_tags!(labels,"insulating",[1:20...,25,26])
add_tag_from_tags!(labels,"topbottom",[21,22])
end
function get_patch_smoothers(
mh,tests,biform,qdegree;
w=0.2,
niter=20,
is_nonlinear=false,
patch_decompositions = PatchDecomposition(mh)
)
patch_spaces = PatchFESpace(tests,patch_decompositions)
nlevs = num_levels(mh)
smoothers = map(view(tests,1:nlevs-1),patch_decompositions,patch_spaces) do tests, PD, Ph
Vh = get_fe_space(tests)
Ω = Triangulation(PD)
dΩ = Measure(Ω,qdegree)
ap = is_nonlinear ? (u,du,dv) -> biform(u,du,dv,dΩ) : (u,v) -> biform(u,v,dΩ)
patch_solver = PatchBasedLinearSolver(ap,Ph,Vh;is_nonlinear=is_nonlinear)
if w < 0
solver = GMRESSolver(niter;Pr=patch_solver,maxiter=niter)
patch_smoother = RichardsonSmoother(solver,1,1.0)
else
patch_smoother = RichardsonSmoother(patch_solver,niter,w)
end
return patch_smoother
end
return smoothers
end
function get_bilinear_form(mh_lev,biform,qdegree)
model = get_model(mh_lev)
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
return (u,v) -> biform(u,v,dΩ)
end
np = (2,2,1)
parts = with_debug() do distribute
distribute(LinearIndices((prod(np),)))
end
mh = HuntModelHierarchy(parts,[np,np],(4,4,3))
order = 2
qdegree = 2*(order+1)
reffe = ReferenceFE(raviart_thomas,Float64,order-1)
tests = TestFESpace(mh,reffe,dirichlet_tags=["insulating"]);
trials = TrialFESpace(tests,VectorValue(0.0,0.0,0.0));
J, D = get_fe_space(trials,1), get_fe_space(tests,1)
η = 100.0
mass(x,v_x,dΩ) = ∫(v_x⋅x)dΩ
graddiv(x,v_x,dΩ) = ∫(η*divergence(v_x)⋅divergence(x))dΩ
biform(j,v_j,dΩ) = mass(j,v_j,dΩ) + graddiv(j,v_j,dΩ)
biforms = map(mhl -> get_bilinear_form(mhl,biform,qdegree),mh)
smoothers = get_patch_smoothers(
mh,trials,biform,qdegree; w=0.2
)
prolongations = setup_prolongation_operators(
trials,qdegree;mode=:residual,solver=LUSolver()
)
restrictions = setup_restriction_operators(
trials,qdegree;mode=:residual,solver=LUSolver()
)
gmg = GMGLinearSolver(
mh,trials,tests,biforms,
prolongations,restrictions,
pre_smoothers=smoothers,
post_smoothers=smoothers,
coarsest_solver=LUSolver(),
maxiter = 3, mode = :preconditioner,
verbose = i_am_main(parts)
)
solver = FGMRESSolver(5,gmg;maxiter=10,rtol=1.e-8,verbose=i_am_main(parts))
Ω = Triangulation(get_model(mh,1))
dΩ = Measure(Ω,qdegree)
ah(j,d) = biform(j,d,dΩ)
Ah = assemble_matrix(ah,D,J)
b = allocate_in_range(Ah)
fill!(b,1.0)
ns = numerical_setup(symbolic_setup(solver,Ah),Ah)
x = allocate_in_domain(Ah)
fill!(x,0.0)
solve!(x,ns,b)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 3169 | module PRefinementGMGLinearSolverPoissonTests
using MPI
using Test
using LinearAlgebra
using IterativeSolvers
using FillArrays
using Gridap
using Gridap.Helpers
using Gridap.ReferenceFEs
using PartitionedArrays
using GridapDistributed
using GridapP4est
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
u(x) = x[1] + x[2]
f(x) = -Δ(u)(x)
function main(parts, coarse_grid_partition, num_parts_x_level, num_refs_coarse, max_order)
GridapP4est.with(parts) do
domain = (0,1,0,1)
num_levels = length(num_parts_x_level)
cparts = generate_subparts(parts,num_parts_x_level[num_levels])
cmodel = CartesianDiscreteModel(domain,coarse_grid_partition)
coarse_model = OctreeDistributedDiscreteModel(cparts,cmodel,num_refs_coarse)
mh = ModelHierarchy(parts,coarse_model,num_parts_x_level;mesh_refinement=false)
orders = collect(max_order:-1:1)
qdegrees = map(o->2*(o+1),orders)
reffes = map(o->ReferenceFE(lagrangian,Float64,o),orders)
tests = TestFESpace(mh,reffes;conformity=:H1,dirichlet_tags="boundary")
trials = TrialFESpace(tests,u)
biform(u,v,dΩ) = ∫(∇(v)⋅∇(u))dΩ
liform(v,dΩ) = ∫(v*f)dΩ
smatrices, A, b = compute_hierarchy_matrices(trials,biform,liform,qdegrees)
# Preconditioner
smoothers = Fill(RichardsonSmoother(JacobiLinearSolver(),10,2.0/3.0),num_levels-1)
restrictions, prolongations = setup_transfer_operators(trials,qdegrees;
mode=:residual,
restriction_method=:interpolation)
gmg = GMGLinearSolver(mh,
smatrices,
prolongations,
restrictions,
pre_smoothers=smoothers,
post_smoothers=smoothers,
maxiter=1,
rtol=1.0e-10,
verbose=false,
mode=:preconditioner)
ss = symbolic_setup(gmg,A)
ns = numerical_setup(ss,A)
# Solve
x = pfill(0.0,partition(axes(A,2)))
x, history = IterativeSolvers.cg!(x,A,b;
verbose=i_am_main(parts),
reltol=1.0e-12,
Pl=ns,
log=true)
# Error norms and print solution
model = get_model(mh,1)
Uh = get_fe_space(trials,1)
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegrees[1])
uh = FEFunction(Uh,x)
e = u-uh
e_l2 = sum(∫(e⋅e)dΩ)
tol = 1.0e-9
@test e_l2 < tol
if i_am_main(parts)
println("L2 error = ", e_l2)
end
end
end
##############################################
if !MPI.Initialized()
MPI.Init()
end
# Parameters
max_order = 3
coarse_grid_partition = (2,2)
num_refs_coarse = 2
num_parts_x_level = [4,4,1]
num_ranks = num_parts_x_level[1]
parts = with_mpi() do distribute
distribute(LinearIndices((prod(num_ranks),)))
end
main(parts,coarse_grid_partition,num_parts_x_level,num_refs_coarse,max_order)
MPI.Finalize()
end
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 3264 |
using MPI
using Test
using LinearAlgebra
using IterativeSolvers
using FillArrays
using Gridap
using Gridap.ReferenceFEs, Gridap.Algebra
using PartitionedArrays
using GridapDistributed
using GridapP4est
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers
function get_patch_smoothers(tests,patch_decompositions,biform,qdegree)
mh = tests.mh
patch_spaces = PatchFESpace(tests,patch_decompositions)
nlevs = num_levels(mh)
smoothers = Vector{RichardsonSmoother}(undef,nlevs-1)
for lev in 1:nlevs-1
parts = get_level_parts(mh,lev)
if i_am_in(parts)
PD = patch_decompositions[lev]
Ph = get_fe_space(patch_spaces,lev)
Vh = get_fe_space(tests,lev)
Ω = Triangulation(PD)
dΩ = Measure(Ω,qdegree)
ap(u,v) = biform(u,v,dΩ)
patch_smoother = PatchBasedLinearSolver(ap,Ph,Vh)
smoothers[lev] = RichardsonSmoother(patch_smoother,10,0.1)
end
end
return smoothers
end
function get_mesh_hierarchy(parts,nc,np_per_level)
Dc = length(nc)
domain = (Dc == 2) ? (0,1,0,1) : (0,1,0,1,0,1)
num_refs_coarse = (Dc == 2) ? 1 : 0
num_levels = length(np_per_level)
cparts = generate_subparts(parts,np_per_level[num_levels])
cmodel = CartesianDiscreteModel(domain,nc)
coarse_model = OctreeDistributedDiscreteModel(cparts,cmodel,num_refs_coarse)
mh = ModelHierarchy(parts,coarse_model,np_per_level)
return mh
end
u(x) = VectorValue(x[1]^2,-2*x[1]*x[2])
f(x) = VectorValue(x[1],x[2])
np = 1
nc = (6,6)
np_per_level = [np,np]
parts = with_mpi() do distribute
distribute(LinearIndices((np,)))
end
mh = get_mesh_hierarchy(parts,nc,np_per_level)
α = 1000.0
#biform(u,v,dΩ) = ∫(v⋅u)dΩ + ∫(α*divergence(v)⋅divergence(u))dΩ
biform(u,v,dΩ) = ∫(∇(v)⊙∇(u))dΩ + ∫(α*divergence(v)⋅divergence(u))dΩ
liform(v,dΩ) = ∫(v⋅f)dΩ
order = 2
qdegree = 2*(order+1)
#reffe = ReferenceFE(raviart_thomas,Float64,order-1)
reffe = ReferenceFE(lagrangian,VectorValue{2,Float64},order)
tests = TestFESpace(mh,reffe,dirichlet_tags="boundary");
trials = TrialFESpace(tests,u);
patch_decompositions = PatchDecomposition(mh)
smoothers = get_patch_smoothers(tests,patch_decompositions,biform,qdegree)
smatrices, A, b = compute_hierarchy_matrices(trials,tests,biform,liform,qdegree);
coarse_solver = LUSolver()
restrictions, prolongations = setup_transfer_operators(trials,
qdegree;
mode=:residual,
solver=LUSolver());
gmg = GMGLinearSolver(mh,
smatrices,
prolongations,
restrictions,
pre_smoothers=smoothers,
post_smoothers=smoothers,
coarsest_solver=coarse_solver,
maxiter=2,
rtol=1.0e-8,
verbose=true,
mode=:preconditioner)
gmg.log.depth += 1
solver = CGSolver(gmg;maxiter=20,atol=1e-14,rtol=1.e-6,verbose=i_am_main(parts))
ns = numerical_setup(symbolic_setup(solver,A),A)
# Solve
x = pfill(0.0,partition(axes(A,2)))
solve!(x,ns,b)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 3111 | using LinearAlgebra
using FillArrays, BlockArrays
using Gridap
using Gridap.ReferenceFEs, Gridap.Algebra, Gridap.Geometry, Gridap.FESpaces
using Gridap.CellData, Gridap.MultiField, Gridap.Algebra
using PartitionedArrays
using GridapDistributed
using GridapSolvers
using GridapSolvers.LinearSolvers, GridapSolvers.MultilevelTools
using GridapSolvers.BlockSolvers: LinearSystemBlock, BiformBlock, BlockTriangularSolver
function add_labels_2d!(labels)
add_tag_from_tags!(labels,"top",[3,4,6])
add_tag_from_tags!(labels,"walls",[1,2,5,7,8])
end
function add_labels_3d!(labels)
add_tag_from_tags!(labels,"top",[5,6,7,8,11,12,15,16,22])
add_tag_from_tags!(labels,"walls",[1,2,3,4,9,10,13,14,17,18,19,20,21,23,24,25,26])
end
nc = (10,10)
Dc = length(nc)
domain = (Dc == 2) ? (0,1,0,1) : (0,1,0,1,0,1)
model = CartesianDiscreteModel(domain,nc)
add_labels! = (Dc == 2) ? add_labels_2d! : add_labels_3d!
add_labels!(get_face_labeling(model))
order = 2
qdegree = 2*(order+1)
reffe_u = ReferenceFE(lagrangian,VectorValue{Dc,Float64},order)
reffe_p = ReferenceFE(lagrangian,Float64,order-1;space=:P)
u_walls = (Dc==2) ? VectorValue(0.0,0.0) : VectorValue(0.0,0.0,0.0)
u_top = (Dc==2) ? VectorValue(1.0,0.0) : VectorValue(1.0,0.0,0.0)
V = TestFESpace(model,reffe_u,dirichlet_tags=["walls","top"]);
U = TrialFESpace(V,[u_walls,u_top]);
Q = TestFESpace(model,reffe_p;conformity=:L2,constraint=:zeromean)
mfs = Gridap.MultiField.BlockMultiFieldStyle()
X = MultiFieldFESpace([U,Q];style=mfs)
Y = MultiFieldFESpace([V,Q];style=mfs)
α = 10.0
f = (Dc==2) ? VectorValue(1.0,1.0) : VectorValue(1.0,1.0,1.0)
poly = (Dc==2) ? QUAD : HEX
Π_Qh = LocalProjectionMap(divergence,lagrangian,Float64,order-1;space=:P)
graddiv(u,v,dΩ) = ∫(α*Π_Qh(u,dΩ)⋅Π_Qh(v,dΩ))dΩ
biform_u(u,v,dΩ) = ∫(∇(v)⊙∇(u))dΩ + graddiv(u,v,dΩ)
biform((u,p),(v,q),dΩ) = biform_u(u,v,dΩ) - ∫(divergence(v)*p)dΩ - ∫(divergence(u)*q)dΩ
liform((v,q),dΩ) = ∫(v⋅f)dΩ
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
a(u,v) = biform(u,v,dΩ)
l(v) = liform(v,dΩ)
op = AffineFEOperator(a,l,X,Y)
A, b = get_matrix(op), get_vector(op);
solver_u = LUSolver()
solver_p = CGSolver(JacobiLinearSolver();maxiter=20,atol=1e-14,rtol=1.e-6,verbose=true)
solver_p.log.depth = 2
β = max(1.0,α)
bblocks = [LinearSystemBlock(),BiformBlock((p,q) -> ∫((1.0/β)*p*q)dΩ,Q,Q)]
P = BlockDiagonalSolver(bblocks,[solver_u,solver_p])
solver = MINRESSolver(;Pl=P,atol=1e-14,rtol=1.e-8,verbose=true)
ns = numerical_setup(symbolic_setup(solver,A),A)
x = allocate_in_domain(A); fill!(x,0.0)
solve!(x,ns,b);
###############################################
X2 = MultiFieldFESpace([U,Q])
Y2 = MultiFieldFESpace([V,Q])
op2 = AffineFEOperator(a,l,X2,Y2)
A2, b2 = get_matrix(op2), get_vector(op2);
x_ref = A2\b2
p((u,p),(v,q)) = biform_u(u,v,dΩ) + ∫((1.0/β)*p*q)dΩ
P2_mat = assemble_matrix(p,X2,Y2)
P2 = LinearSolvers.MatrixSolver(P2_mat)
solver2 = MINRESSolver(;Pl=P2,atol=1e-14,rtol=1.e-8,verbose=true)
ns2 = numerical_setup(symbolic_setup(solver2,A2),A2)
x2 = allocate_in_domain(A2); fill!(x2,0.0)
solve!(x2,ns2,b2);
norm(A*x-b), norm(A2*x_ref-b2)
norm(x-x_ref), norm(x2-x_ref)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 1595 |
using Gridap
using Gridap.Adaptivity, Gridap.Geometry, Gridap.ReferenceFEs, Gridap.FESpaces, Gridap.Arrays
using FillArrays
u_sol(x) = VectorValue(x[1]^2*x[2], -x[1]*x[2]^2)
p_sol(x) = (x[1] - 1.0/2.0)
model = simplexify(CartesianDiscreteModel((0,1,0,1),(20,20)))
labels = get_face_labeling(model)
add_tag_from_tags!(labels,"top",[6])
add_tag_from_tags!(labels,"walls",[1,2,3,4,5,7,8])
order = 2
rrule = Adaptivity.BarycentricRefinementRule(TRI)
reffes = Fill(LagrangianRefFE(VectorValue{2,Float64},TRI,order),Adaptivity.num_subcells(rrule))
reffe_u = Adaptivity.MacroReferenceFE(rrule,reffes)
reffe_p = LagrangianRefFE(Float64,TRI,order-1)
#reffe_p = Adaptivity.MacroReferenceFE(rrule,reffes;conformity=L2Conformity())
qdegree = 2*order
quad = Quadrature(TRI,Adaptivity.CompositeQuadrature(),rrule,qdegree)
V = FESpace(model,reffe_u,dirichlet_tags=["boundary"])
Q = FESpace(model,reffe_p,conformity=:L2,constraint=:zeromean)
U = TrialFESpace(V,u_sol)
Ω = Triangulation(model)
dΩ = Measure(Ω,quad)
@assert abs(sum(∫(p_sol)dΩ)) < 1.e-15
@assert abs(sum(∫(divergence(u_sol))dΩ)) < 1.e-15
X = MultiFieldFESpace([U,Q])
Y = MultiFieldFESpace([V,Q])
f(x) = -Δ(u_sol)(x) + ∇(p_sol)(x)
lap(u,v) = ∫(∇(u)⊙∇(v))dΩ
a((u,p),(v,q)) = lap(u,v) + ∫(divergence(u)*q - divergence(v)*p)dΩ
l((v,q)) = ∫(f⋅v)dΩ
op = AffineFEOperator(a,l,X,Y)
xh = solve(op)
uh, ph = xh
sum(∫(uh⋅uh)dΩ)
sum(∫(ph)dΩ)
eh_u = uh - u_sol
eh_p = ph - p_sol
sum(∫(eh_u⋅eh_u)dΩ)
sum(∫(eh_p*eh_p)dΩ)
writevtk(
Ω,"stokes",
cellfields=["u"=>uh,"p"=>ph,"eu"=>eh_u,"ep"=>eh_p,"u_sol"=>u_sol,"p_sol"=>p_sol],
append=false,
)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 591 |
using Gridap
using GridapDistributed, PartitionedArrays
using GridapSolvers
using Gridap.MultiField
ranks = with_debug() do distribute
distribute(LinearIndices((4,)))
end
np_per_level = [(2,2),(2,2),(2,1)]
nrefs = [(2,1),(2,2)]
isperiodic = (true,false)
mh = CartesianModelHierarchy(
ranks,
np_per_level,
(0,1,0,1),
(10,10);
nrefs,
isperiodic
)
ncells_per_level = map(num_cells∘get_model,mh).array
reffe = ReferenceFE(lagrangian,Float64,1)
V = FESpace(mh,reffe,dirichlet_tags="boundary")
X = MultiFieldFESpace([V,V])
PD = PatchDecomposition(mh)
Ph = PatchFESpace(V,PD)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 685 | using PartitionedArrays
using GridapDistributed
using GridapSolvers, GridapSolvers.MultilevelTools
using Gridap, Gridap.Geometry
struct HierarchyLevel{A,B,C}
object :: A
object_red :: B
red_glue :: C
end
############################################################################################
np = (2,1)
ranks = DebugArray(LinearIndices((prod(np),)))
dmodel = CartesianDiscreteModel(ranks,np,(0,1,0,1),(4,4))
model1 = CartesianDiscreteModel((0,1,0,1),(4,4))
model2 = UnstructuredDiscreteModel(model1)
a = HierarchicalArray(fill(dmodel,2),fill(ranks,2))
b = HierarchicalArray([dmodel,nothing],fill(ranks,2))
c = HierarchicalArray([model1,model2],fill(ranks,2))
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 1241 |
using Gridap
using GridapDistributed, PartitionedArrays
using GridapSolvers
using GridapSolvers.MultilevelTools
using Gridap.Arrays
np = (2,2)
ranks = with_debug() do distribute
distribute(LinearIndices((prod(np),)))
end
layer(x) = sign(x)*abs(x)^(1/3)
cmap(x) = VectorValue(layer(x[1]),layer(x[2]))
model = CartesianDiscreteModel((0,-1,0,-1),(10,10),map=cmap)
Ω = Triangulation(model)
dΩ = Measure(Ω,2)
order = 2
qdegree = 2*(order+1)
reffe_u = ReferenceFE(lagrangian,VectorValue{2,Float64},order)
reffe_p = ReferenceFE(lagrangian,Float64,order-1;space=:P)
V = TestFESpace(model,reffe_u,dirichlet_tags="boundary");
Q = TestFESpace(model,reffe_p;conformity=:L2,constraint=:zeromean)
mfs = Gridap.MultiField.BlockMultiFieldStyle()
X = MultiFieldFESpace([V,Q];style=mfs)
#Π_Qh = LocalProjectionMap(divergence,reffe_p,qdegree)
Π_Qh = LocalProjectionMap(divergence,Q,qdegree)
A = assemble_matrix((u,v) -> ∫(∇(v)⊙∇(u))dΩ, V, V)
D = assemble_matrix((u,v) -> ∫(Π_Qh(u)⋅(∇⋅v))dΩ, V, V)
B = assemble_matrix((u,q) -> ∫(divergence(u)*q)dΩ, V, Q)
Bt = assemble_matrix((p,v) -> ∫(divergence(v)*p)dΩ, Q, V)
Mp = assemble_matrix((p,q) -> ∫(p⋅q)dΩ, Q, Q)
@assert Bt ≈ B'
F = Bt*inv(Matrix(Mp))*B
G = Matrix(D)
F-G
norm(F-G)
maximum(abs.(F-G))
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 1984 |
using Gridap
using GridapDistributed, PartitionedArrays
using GridapSolvers
using Gridap.MultiField, Gridap.Arrays, Gridap.Geometry
using GridapSolvers.PatchBasedSmoothers
function add_labels!(labels)
add_tag_from_tags!(labels,"noslip",[1:20...,23,24,25,26])
add_tag_from_tags!(labels,"insulating",[1:20...,25,26])
add_tag_from_tags!(labels,"topbottom",[21,22])
end
ranks = with_debug() do distribute
distribute(LinearIndices((4,)))
end
nrefs = (2,2,2)
isperiodic = (false,false,true)
np_per_level = [(2,2,1),(2,2,1)]
mh = CartesianModelHierarchy(
ranks,
np_per_level,
(-1.,1.,-1.,1.,0.,0.1),
(4,4,4);
nrefs,
isperiodic,
add_labels!,
)
order = 2
qdegree = 2*order
reffe_u = ReferenceFE(lagrangian,VectorValue{3,Float64},order)
reffe_j = ReferenceFE(raviart_thomas,Float64,order-1)
tests_u = TestFESpace(mh,reffe_u,dirichlet_tags=["noslip"]);
tests_j = TestFESpace(mh,reffe_j,dirichlet_tags=["insulating"]);
tests = MultiFieldFESpace([tests_u,tests_j])
PD = PatchDecomposition(mh)
Ph = PatchFESpace(tests,PD)
biform((u,j),(v,s),dΩ) = ∫(u⋅v + j⋅s)dΩ
nlevs = num_levels(mh)
smoothers = map(view(tests,1:nlevs-1),PD,Ph) do tests, PD, Ph
Vh = get_fe_space(tests)
Ω = Triangulation(PD)
dΩ = Measure(Ω,qdegree)
ap(u,v) = biform(u,v,dΩ)
patch_solver = PatchBasedLinearSolver(ap,Ph,Vh)
RichardsonSmoother(patch_solver,10,0.2)
end
smatrices = map(view(mh,1:nlevs-1),view(tests,1:nlevs-1)) do mhlev,tests
Vh = get_fe_space(tests)
model = get_model(mhlev)
Ω = Triangulation(model)
dΩ = Measure(Ω,qdegree)
a(u,v) = biform(u,v,dΩ)
assemble_matrix(a,Vh,Vh)
end
smoother_ns = map(smoothers,smatrices) do s, m
numerical_setup(symbolic_setup(s,m),m)
end
prolongations = map(view(linear_indices(mh),1:nlevs-1),view(mh,1:nlevs-1),PD) do lev,mhlev,PD
model = get_model(mhlev)
Ω = Triangulation(PD)
dΩ = Measure(Ω,qdegree)
lhs(u,v) = biform(u,v,dΩ)
rhs(u,v) = biform(u,v,dΩ)
PatchProlongationOperator(lev,tests,PD,lhs,rhs)
end
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 3039 |
using Gridap
using Gridap.Geometry, Gridap.FESpaces, Gridap.Adaptivity
u_h1(x) = x[1]*(1-x[1])*x[2]*(1-x[2]) #x[1] + x[2]
u_hdiv(x) = VectorValue(x[1],x[2])
a_h1(u,v,dΩ) = ∫(u⋅v)*dΩ
a_hdiv(u,v,dΩ) = ∫(u⋅v + divergence(u)⋅divergence(v))*dΩ
conf = :hdiv
order = 1
cmodel = CartesianDiscreteModel((0,1,0,1),(8,8))
fmodel = refine(cmodel)
Ωh = Triangulation(fmodel)
ΩH = Triangulation(cmodel)
qdegree = 2*(order+1)
dΩh = Measure(Ωh,qdegree)
dΩH = Measure(ΩH,qdegree)
dΩHh = Measure(ΩH,Ωh,qdegree)
if conf == :h1
u_bc = u_h1
reffe = ReferenceFE(lagrangian,Float64,order)
ah(u,v) = a_h1(u,v,dΩh)
aH(u,v) = a_h1(u,v,dΩH)
f = zero(Float64)
else
u_bc = u_hdiv
reffe = ReferenceFE(raviart_thomas,Float64,order)
ah(u,v) = a_hdiv(u,v,dΩh)
aH(u,v) = a_hdiv(u,v,dΩH)
f = zero(VectorValue{2,Float64})
end
lh(v) = ∫(v⋅f)*dΩh
lH(v) = ∫(v⋅f)*dΩH
VH = TestFESpace(cmodel,reffe,dirichlet_tags="boundary")
UH = TrialFESpace(VH,u_bc)
Vh = TestFESpace(fmodel,reffe,dirichlet_tags="boundary")
Uh = TrialFESpace(Vh,u_bc)
oph = AffineFEOperator(ah,lh,Uh,Vh)
opH = AffineFEOperator(aH,lH,UH,VH)
xh_star = get_free_dof_values(solve(oph))
xH_star = get_free_dof_values(solve(opH))
Ah, bh = get_matrix(oph), get_vector(oph);
AH, bH = get_matrix(opH), get_vector(opH);
uh = interpolate(u_bc,Uh)
uH = interpolate(u_bc,UH)
xh = get_free_dof_values(uh)
xH = get_free_dof_values(uH)
eh = xh_star - xh
eH = xH_star - xH
rh = bh - Ah*xh
rH = bH - AH*xH
norm(Ah*eh - rh)
norm(AH*eH - rH)
uh0 = FEFunction(Vh,xh)
yh = bh - assemble_vector(v -> ah(uh0,v),Vh)
norm(rh-yh)
function project_sol_c2f(xH)
uH = FEFunction(UH,xH)
op = AffineFEOperator((u,v)->∫(u⋅v)*dΩh,v->∫(v⋅uH)*dΩh,Uh,Vh)
return get_matrix(op)\get_vector(op)
end
function project_err_c2f(xH)
uH = FEFunction(VH,xH)
op = AffineFEOperator((u,v)->∫(u⋅v)*dΩh,v->∫(v⋅uH)*dΩh,Vh,Vh)
return get_matrix(op)\get_vector(op)
end
#function project_err_f2c(xh)
# uh = FEFunction(Vh,xh)
# uH = interpolate(uh,VH)
# return get_free_dof_values(uH)
#end
function project_err_f2c(xh)
uh = FEFunction(Vh,xh)
op = AffineFEOperator((u,v)->∫(u⋅v)*dΩH,v->∫(v⋅uh)*dΩHh,VH,VH)
return get_matrix(op)\get_vector(op)
end
yh = project_sol_c2f(xH)
norm(xh-yh)
yh = project_err_c2f(eH)
norm(eh-yh)
norm(rh-Ah*yh)
########################################
hH = get_cell_measure(ΩH)
hh = get_cell_measure(Ωh)
function dotH(a::AbstractVector,b::AbstractVector)
_a = FEFunction(VH,a)
_b = FEFunction(VH,b)
dotH(_a,_b)
end
function dotH(a,b)
sum(∫(a⋅b)*dΩH)
end
function doth(a::AbstractVector,b::AbstractVector)
_a = FEFunction(Vh,a)
_b = FEFunction(Vh,b)
doth(_a,_b)
end
function doth(a,b)
sum(∫(a⋅b)*dΩh)
end
g = rh
z = Ah\g
zm1 = fill(0.1,size(Ah,2))
gH = project_err_f2c(g-Ah*zm1)
qH = AH\gH
wH = randn(size(AH,2))
wh = get_free_dof_values(interpolate(FEFunction(VH,wH),Vh))
#wh = project_err_c2f(wH)
dotH(AH*qH,wH)
dotH(gH,wH)
doth(g-Ah*zm1,wh)
doth(Ah*(z-zm1),wh)
gH = project_err_f2c(g)
dotH(gH,wH)
doth(g,wh)
gh = project_err_c2f(gH)
doth(gh-g,wh)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 5854 | using Gridap, Gridap.TensorValues, Gridap.Geometry, Gridap.ReferenceFEs
using GridapDistributed
using GridapPETSc
using GridapPETSc: PetscScalar, PetscInt, PETSC, @check_error_code
using PartitionedArrays
using SparseMatricesCSR
using MPI
import GridapDistributed.DistributedCellField
import GridapDistributed.DistributedFESpace
import GridapDistributed.DistributedDiscreteModel
import GridapDistributed.DistributedMeasure
import GridapDistributed.DistributedTriangulation
function isotropic_3d(E::M,nu::M) where M<:AbstractFloat
λ = E*nu/((1+nu)*(1-2nu)); μ = E/(2*(1+nu))
C =[λ+2μ λ λ 0 0 0
λ λ+2μ λ 0 0 0
λ λ λ+2μ 0 0 0
0 0 0 μ 0 0
0 0 0 0 μ 0
0 0 0 0 0 μ];
return SymFourthOrderTensorValue(
C[1,1], C[6,1], C[5,1], C[2,1], C[4,1], C[3,1],
C[1,6], C[6,6], C[5,6], C[2,6], C[4,6], C[3,6],
C[1,5], C[6,5], C[5,5], C[2,5], C[4,5], C[3,5],
C[1,2], C[6,2], C[5,2], C[2,2], C[4,2], C[3,2],
C[1,4], C[6,4], C[5,4], C[2,4], C[4,4], C[3,4],
C[1,3], C[6,3], C[5,3], C[2,3], C[4,3], C[3,3])
end
struct ElasticitySolver{A,B} <: Gridap.Algebra.LinearSolver
trian ::A
space ::B
rtol ::PetscScalar
maxits::PetscInt
function ElasticitySolver(trian::DistributedTriangulation,
space::DistributedFESpace;
rtol=1.e-12,
maxits=100)
A = typeof(trian)
B = typeof(space)
new{A,B}(trian,space,rtol,maxits)
end
end
struct ElasticitySymbolicSetup{A} <: Gridap.Algebra.SymbolicSetup
solver::A
end
function Gridap.Algebra.symbolic_setup(solver::ElasticitySolver,A::AbstractMatrix)
ElasticitySymbolicSetup(solver)
end
function get_dof_coords(trian,space)
coords = map(local_views(trian),local_views(space),partition(space.gids)) do trian, space, dof_indices
node_coords = Gridap.Geometry.get_node_coordinates(trian)
dof_to_node = space.metadata.free_dof_to_node
dof_to_comp = space.metadata.free_dof_to_comp
o2l_dofs = own_to_local(dof_indices)
coords = Vector{PetscScalar}(undef,length(o2l_dofs))
for (i,dof) in enumerate(o2l_dofs)
node = dof_to_node[dof]
comp = dof_to_comp[dof]
coords[i] = node_coords[node][comp]
end
return coords
end
ngdofs = length(space.gids)
indices = map(local_views(space.gids)) do dof_indices
owner = part_id(dof_indices)
own_indices = OwnIndices(ngdofs,owner,own_to_global(dof_indices))
ghost_indices = GhostIndices(ngdofs,Int64[],Int32[]) # We only consider owned dofs
OwnAndGhostIndices(own_indices,ghost_indices)
end
return PVector(coords,indices)
end
function elasticity_ksp_setup(ksp,rtol,maxits)
rtol = PetscScalar(rtol)
atol = GridapPETSc.PETSC.PETSC_DEFAULT
dtol = GridapPETSc.PETSC.PETSC_DEFAULT
maxits = PetscInt(maxits)
@check_error_code GridapPETSc.PETSC.KSPView(ksp[],C_NULL)
@check_error_code GridapPETSc.PETSC.KSPSetType(ksp[],GridapPETSc.PETSC.KSPGMRES)
@check_error_code GridapPETSc.PETSC.KSPSetTolerances(ksp[], rtol, atol, dtol, maxits)
pc = Ref{GridapPETSc.PETSC.PC}()
@check_error_code GridapPETSc.PETSC.KSPGetPC(ksp[],pc)
@check_error_code GridapPETSc.PETSC.PCSetType(pc[],GridapPETSc.PETSC.PCGAMG)
end
function Gridap.Algebra.numerical_setup(ss::ElasticitySymbolicSetup,A::PSparseMatrix)
s = ss.solver; Dc = num_cell_dims(s.trian)
# Compute coordinates for owned dofs
dof_coords = convert(PETScVector,get_dof_coords(s.trian,s.space))
@check_error_code GridapPETSc.PETSC.VecSetBlockSize(dof_coords.vec[],Dc)
# Create matrix nullspace
B = convert(PETScMatrix,A)
null = Ref{GridapPETSc.PETSC.MatNullSpace}()
@check_error_code GridapPETSc.PETSC.MatNullSpaceCreateRigidBody(dof_coords.vec[],null)
@check_error_code GridapPETSc.PETSC.MatSetNearNullSpace(B.mat[],null[])
# Setup solver and preconditioner
ns = GridapPETSc.PETScLinearSolverNS(A,B)
@check_error_code GridapPETSc.PETSC.KSPCreate(B.comm,ns.ksp)
@check_error_code GridapPETSc.PETSC.KSPSetOperators(ns.ksp[],ns.B.mat[],ns.B.mat[])
elasticity_ksp_setup(ns.ksp,s.rtol,s.maxits)
@check_error_code GridapPETSc.PETSC.KSPSetUp(ns.ksp[])
GridapPETSc.Init(ns)
end
############
D = 3
order = 1
n = 20
np_x_dim = 1
np = Tuple(fill(np_x_dim,D)) #Tuple([fill(np_x_dim,D-1)...,1])
ranks = with_debug() do distribute
distribute(LinearIndices((prod(np),)))
end
n_tags = (D==2) ? "tag_6" : "tag_22"
d_tags = (D==2) ? ["tag_5"] : ["tag_21"]
nc = (D==2) ? (n,n) : (n,n,n)
domain = (D==2) ? (0,1,0,1) : (0,1,0,1,0,1)
model = CartesianDiscreteModel(domain,nc)
Ω = Triangulation(model)
Γ = Boundary(model,tags=n_tags)
ΓD = Boundary(model,tags=d_tags)
poly = (D==2) ? QUAD : HEX
reffe = LagrangianRefFE(VectorValue{D,Float64},poly,order)
V = TestFESpace(model,reffe;dirichlet_tags=d_tags)
U = TrialFESpace(V)
assem = SparseMatrixAssembler(SparseMatrixCSR{0,PetscScalar,PetscInt},Vector{PetscScalar},U,V)#,FullyAssembledRows())
dΩ = Measure(Ω,2*order)
dΓ = Measure(Γ,2*order)
C = (D == 2) ? isotropic_2d(1.,0.3) : isotropic_3d(1.,0.3)
g = (D == 2) ? VectorValue(0.0,1.0) : VectorValue(0.0,0.0,1.0)
a(u,v) = ∫((C ⊙ ε(u) ⊙ ε(v)))dΩ
l(v) = ∫(v ⋅ g)dΓ
op = AffineFEOperator(a,l,U,V,assem)
A, b = get_matrix(op), get_vector(op);
dim, coords = get_coords(Ω,V);
pcoords = PVector(coords,partition(axes(A,1)))
options = "
-ksp_type cg -ksp_rtol 1.0e-12
-pc_type gamg -mat_block_size $D
-ksp_converged_reason -ksp_error_if_not_converged true
"
GridapPETSc.with(args=split(options)) do
solver = PETScLinearSolver(ksp_setup)
ss = symbolic_setup(solver,A)
ns = my_numerical_setup(ss,A,pcoords,dim)
x = pfill(PetscScalar(1.0),partition(axes(A,2)))
solve!(x,ns,b)
end
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 7271 |
using Gridap
using GridapDistributed
using PartitionedArrays
using GridapPETSc
using SparseMatricesCSR
using LinearAlgebra
using Gridap.Geometry, Gridap.FESpaces, Gridap.CellData, Gridap.Arrays
function get_operators(V_H1_sc,V_H1_vec,V_Hcurl,V_Hdiv)
G = interpolation_operator(u->∇(u),V_H1_sc,V_Hcurl)
C = interpolation_operator(u->cross(∇,u),V_Hcurl,V_Hdiv)
Π_div = interpolation_operator(u->u,V_H1_vec,V_Hdiv)
Π_curl = interpolation_operator(u->u,V_H1_vec,V_Hcurl)
return G, C, Π_div, Π_curl
end
function interpolation_operator(op,U_in,V_out;
strat=SubAssembledRows(),
Tm=SparseMatrixCSR{0,PetscScalar,PetscInt},
Tv=Vector{PetscScalar})
out_dofs = get_fe_dof_basis(V_out)
in_basis = get_fe_basis(U_in)
cell_interp_mats = out_dofs(op(in_basis))
local_contr = map(local_views(out_dofs),cell_interp_mats) do dofs, arr
contr = DomainContribution()
add_contribution!(contr,get_triangulation(dofs),arr)
return contr
end
contr = GridapDistributed.DistributedDomainContribution(local_contr)
matdata = collect_cell_matrix(U_in,V_out,contr)
assem = SparseMatrixAssembler(Tm,Tv,U_in,V_out,strat)
I = allocate_matrix(assem,matdata)
takelast_matrix!(I,assem,matdata)
return I
end
function takelast_matrix(a::SparseMatrixAssembler,matdata)
m1 = Gridap.Algebra.nz_counter(get_matrix_builder(a),(get_rows(a),get_cols(a)))
symbolic_loop_matrix!(m1,a,matdata)
m2 = Gridap.Algebra.nz_allocation(m1)
takelast_loop_matrix!(m2,a,matdata)
m3 = Gridap.Algebra.create_from_nz(m2)
return m3
end
function takelast_matrix!(mat,a::SparseMatrixAssembler,matdata)
LinearAlgebra.fillstored!(mat,zero(eltype(mat)))
takelast_matrix_add!(mat,a,matdata)
end
function takelast_matrix_add!(mat,a::SparseMatrixAssembler,matdata)
takelast_loop_matrix!(mat,a,matdata)
Gridap.Algebra.create_from_nz(mat)
end
function takelast_loop_matrix!(A,a::GridapDistributed.DistributedSparseMatrixAssembler,matdata)
rows = get_rows(a)
cols = get_cols(a)
map(takelast_loop_matrix!,local_views(A,rows,cols),local_views(a),matdata)
end
function takelast_loop_matrix!(A,a::SparseMatrixAssembler,matdata)
strategy = Gridap.FESpaces.get_assembly_strategy(a)
for (cellmat,_cellidsrows,_cellidscols) in zip(matdata...)
cellidsrows = Gridap.FESpaces.map_cell_rows(strategy,_cellidsrows)
cellidscols = Gridap.FESpaces.map_cell_cols(strategy,_cellidscols)
@assert length(cellidscols) == length(cellidsrows)
@assert length(cellmat) == length(cellidsrows)
if length(cellmat) > 0
rows_cache = array_cache(cellidsrows)
cols_cache = array_cache(cellidscols)
vals_cache = array_cache(cellmat)
mat1 = getindex!(vals_cache,cellmat,1)
rows1 = getindex!(rows_cache,cellidsrows,1)
cols1 = getindex!(cols_cache,cellidscols,1)
add! = Gridap.Arrays.AddEntriesMap((a,b) -> b)
add_cache = return_cache(add!,A,mat1,rows1,cols1)
caches = add_cache, vals_cache, rows_cache, cols_cache
_takelast_loop_matrix!(A,caches,cellmat,cellidsrows,cellidscols)
end
end
A
end
@noinline function _takelast_loop_matrix!(mat,caches,cell_vals,cell_rows,cell_cols)
add_cache, vals_cache, rows_cache, cols_cache = caches
add! = Gridap.Arrays.AddEntriesMap((a,b) -> b)
for cell in 1:length(cell_cols)
rows = getindex!(rows_cache,cell_rows,cell)
cols = getindex!(cols_cache,cell_cols,cell)
vals = getindex!(vals_cache,cell_vals,cell)
evaluate!(add_cache,add!,mat,vals,rows,cols)
end
end
function ads_ksp_setup(ksp,rtol,maxits,dim,G,C,Π_div,Π_curl)
rtol = PetscScalar(rtol)
atol = GridapPETSc.PETSC.PETSC_DEFAULT
dtol = GridapPETSc.PETSC.PETSC_DEFAULT
maxits = PetscInt(maxits)
@check_error_code GridapPETSc.PETSC.KSPSetType(ksp[],GridapPETSc.PETSC.KSPGMRES)
@check_error_code GridapPETSc.PETSC.KSPSetTolerances(ksp[], rtol, atol, dtol, maxits)
pc = Ref{GridapPETSc.PETSC.PC}()
@check_error_code GridapPETSc.PETSC.KSPGetPC(ksp[],pc)
@check_error_code GridapPETSc.PETSC.PCSetType(pc[],GridapPETSc.PETSC.PCHYPRE)
_G = convert(PETScMatrix,G)
_C = convert(PETScMatrix,C)
_Π_div = convert(PETScMatrix,Π_div)
_Π_curl = convert(PETScMatrix,Π_curl)
@check_error_code GridapPETSc.PETSC.PCHYPRESetDiscreteGradient(pc[],_G.mat[])
@check_error_code GridapPETSc.PETSC.PCHYPRESetDiscreteCurl(pc[],_C.mat[])
@check_error_code GridapPETSc.PETSC.PCHYPRESetInterpolations(pc[],dim,_Π_div.mat[],C_NULL,_Π_curl.mat[],C_NULL)
@check_error_code GridapPETSc.PETSC.KSPView(ksp[],C_NULL)
end
###############################################################################
n = 10
D = 3
order = 1
np = (1,1,1)#Tuple(fill(1,D))
ranks = with_mpi() do distribute
distribute(LinearIndices((prod(np),)))
end
domain = (D==2) ? (0,1,0,1) : (0,1,0,1,0,1)
ncells = (D==2) ? (n,n) : (n,n,n)
model = CartesianDiscreteModel(ranks,np,domain,ncells)
trian = Triangulation(model)
reffe_H1_sc = ReferenceFE(lagrangian,Float64,order)
V_H1_sc = FESpace(model,reffe_H1_sc)#;dirichlet_tags="boundary")
U_H1_sc = TrialFESpace(V_H1_sc)
reffe_H1 = ReferenceFE(lagrangian,VectorValue{D,Float64},order)
V_H1 = FESpace(model,reffe_H1)#;dirichlet_tags="boundary")
U_H1 = TrialFESpace(V_H1)
reffe_Hdiv = ReferenceFE(raviart_thomas,Float64,order-1)
V_Hdiv = FESpace(model,reffe_Hdiv)#;dirichlet_tags="boundary")
U_Hdiv = TrialFESpace(V_Hdiv)
reffe_Hcurl = ReferenceFE(nedelec,Float64,order-1)
V_Hcurl = FESpace(model,reffe_Hcurl)#;dirichlet_tags="boundary")
U_Hcurl = TrialFESpace(V_Hcurl)
##############################################################################
dΩ = Measure(trian,(order+1)*2)
G, C, Π_div, Π_curl = get_operators(V_H1_sc,V_H1,V_Hcurl,V_Hdiv);
u(x) = x[1]^3 + x[2]^3
u_h1 = interpolate(u,U_H1_sc)
x_h1 = get_free_dof_values(u_h1)
#u_hcurl = interpolate(∇(u_h1),U_Hcurl)
#x_hcurl = G * x_h1
#@assert norm(x_hcurl - get_free_dof_values(u_hcurl)) < 1.e-8
#
#u_hdiv = interpolate(∇×(u_hcurl),U_Hdiv)
#x_hdiv = C * x_hcurl
#@assert norm(x_hdiv - get_free_dof_values(u_hdiv)) < 1.e-8
#
#u_vec(x) = VectorValue(x[1]^3,x[2]^3,x[3]^3)
#u_h1_vec = interpolate(u_vec,V_H1)
#x_h1_vec = get_free_dof_values(u_h1_vec)
#
#u_hcurl_bis = interpolate(u_h1_vec,U_Hcurl)
#x_hcurl_bis = Π_curl * x_h1_vec
#@assert norm(x_hcurl_bis - get_free_dof_values(u_hcurl_bis)) < 1.e-8
#u_hdiv_bis = interpolate(u_h1_vec,U_Hcurl)
#x_hdiv_bis = Π_curl * x_h1_vec
#@assert norm(x_hdiv_bis - get_free_dof_values(u_hdiv_bis)) < 1.e-8
############################################################################################
sol(x) = (D==2) ? VectorValue(x[1],x[2]) : VectorValue(x[1],x[2],x[3])
f(x) = (D==2) ? VectorValue(x[1],x[2]) : VectorValue(x[1],x[2],x[3])
α = 1.0
a(u,v) = ∫(u⋅v + α⋅(∇⋅u)⋅(∇⋅v)) * dΩ
l(v) = ∫(f⋅v) * dΩ
V = FESpace(model,reffe_Hdiv)#;dirichlet_tags="boundary")
U = TrialFESpace(V,sol)
op = AffineFEOperator(a,l,V,U)
A = get_matrix(op)
b = get_vector(op)
options = "-ksp_converged_reason"
GridapPETSc.with(args=split(options)) do
ksp_setup(ksp) = ads_ksp_setup(ksp,1e-8,300,D,G,C,Π_div,Π_curl)
solver = PETScLinearSolver(ksp_setup)
ns = numerical_setup(symbolic_setup(solver,A),A)
x = pfill(0.0,partition(axes(A,2)))
solve!(x,ns,b)
end
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 1460 |
using Test
using LinearAlgebra
using FillArrays
using Gridap
using Gridap.ReferenceFEs, Gridap.Algebra, Gridap.FESpaces, Gridap.Geometry
using PartitionedArrays
using GridapDistributed
using GridapP4est
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers
function weakforms(model)
Ω = Triangulation(model)
Γ = BoundaryTriangulation(model)
Λ = SkeletonTriangulation(model)
dΩ = Measure(Ω, qorder)
dΓ = Measure(Γ, qorder)
dΛ = Measure(Λ, qorder)
n_Γ = get_normal_vector(Γ)
n_Λ = get_normal_vector(Λ)
a1(u,v) = ∫(∇(u)⊙∇(v))dΩ
a2(u,v) = ∫((∇(v)⋅n_Γ)⋅u)dΓ
a3(u,v) = ∫(jump(u⋅n_Λ)⋅jump(v⋅n_Λ))dΛ
return a1, a2, a3
end
model = CartesianDiscreteModel((0,1,0,1),(2,2))
order = 1
qorder = 2*order+1
reffe = ReferenceFE(raviart_thomas,Float64,order-1)
Vh = FESpace(model,reffe)
Ω = Triangulation(model)
Γ = BoundaryTriangulation(model)
Λ = SkeletonTriangulation(model)
PD = PatchDecomposition(model)
Ph = PatchFESpace(Vh,PD,reffe)
Ωp = Triangulation(PD)
Γp = BoundaryTriangulation(PD)
Λp = SkeletonTriangulation(PD)
Γp_virtual = BoundaryTriangulation(PD,tags=["boundary","interior"],reverse=true)
a1, a2, a3 = weakforms(model)
ap1, ap2, ap3 = weakforms(PD)
A1 = assemble_matrix(a1,Vh,Vh)
Ap1 = assemble_matrix(ap1,Ph,Ph)
A2 = assemble_matrix(a2,Vh,Vh)
Ap2 = assemble_matrix(ap2,Ph,Ph)
A3 = assemble_matrix(a3,Vh,Vh)
Ap3 = assemble_matrix(ap3,Ph,Ph)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 4976 | module DistributedPatchFESpacesHDivTests
using LinearAlgebra
using Test
using PartitionedArrays
using Gridap
using Gridap.Helpers
using Gridap.Arrays
using Gridap.Geometry
using Gridap.ReferenceFEs
using GridapDistributed
using FillArrays
using GridapSolvers
import GridapSolvers.PatchBasedSmoothers as PBS
function run(ranks)
parts = with_debug() do distribute
distribute(LinearIndices((prod(ranks),)))
end
domain = (0.0,1.0,0.0,1.0)
partition = (2,4)
model = CartesianDiscreteModel(parts,ranks,domain,partition)
order = 0
reffe = ReferenceFE(raviart_thomas,Float64,order)
Vh = TestFESpace(model,reffe)
PD = PBS.PatchDecomposition(model)
Ph = PBS.PatchFESpace(model,reffe,DivConformity(),PD,Vh)
# ---- Testing Prolongation and Injection ---- #
w, w_sums = PBS.compute_weight_operators(Ph,Vh);
xP = pfill(1.0,partition(Ph.gids))
yP = pfill(0.0,partition(Ph.gids))
x = pfill(1.0,partition(Vh.gids))
y = pfill(0.0,partition(Vh.gids))
PBS.prolongate!(yP,Ph,x)
PBS.inject!(y,Ph,yP,w,w_sums)
@test x ≈ y
PBS.inject!(x,Ph,xP,w,w_sums)
PBS.prolongate!(yP,Ph,x)
@test xP ≈ yP
# ---- Assemble systems ---- #
sol(x) = VectorValue(x[1],x[2])
f(x) = VectorValue(2.0*x[2]*(1.0-x[1]*x[1]),2.0*x[1]*(1-x[2]*x[2]))
α = 1.0
biform(u,v,dΩ) = ∫(v⋅u)dΩ + ∫(α*divergence(v)⋅divergence(u))dΩ
liform(v,dΩ) = ∫(v⋅f)dΩ
Ω = Triangulation(model)
dΩ = Measure(Ω,2*order+1)
a(u,v) = biform(u,v,dΩ)
l(v) = liform(v,dΩ)
assembler = SparseMatrixAssembler(Vh,Vh)
Ah = assemble_matrix(a,assembler,Vh,Vh)
fh = assemble_vector(l,assembler,Vh)
sol_h = solve(LUSolver(),Ah,fh)
Ωₚ = Triangulation(PD)
dΩₚ = Measure(Ωₚ,2*order+1)
ap(u,v) = biform(u,v,dΩₚ)
lp(v) = liform(v,dΩₚ)
assembler_P = SparseMatrixAssembler(Ph,Ph,FullyAssembledRows())
Ahp = assemble_matrix(ap,assembler_P,Ph,Ph)
fhp = assemble_vector(lp,assembler_P,Ph)
sol_hp = solve(LUSolver(),Ahp,fhp)
# ---- Define solvers ---- #
LU = LUSolver()
LUss = symbolic_setup(LU,Ahp)
LUns = numerical_setup(LUss,Ahp)
M = PBS.PatchBasedLinearSolver(ap,Ph,Vh,LU)
Mss = symbolic_setup(M,Ah)
Mns = numerical_setup(Mss,Ah)
R = RichardsonSmoother(M,10,1.0/3.0)
Rss = symbolic_setup(R,Ah)
Rns = numerical_setup(Rss,Ah)
# ---- Manual solve using LU ---- #
x1_mat = pfill(0.5,partition(axes(Ah,2)))
r1_mat = fh-Ah*x1_mat
consistent!(r1_mat) |> fetch
r1 = pfill(0.0,partition(Vh.gids))
x1 = pfill(0.0,partition(Vh.gids))
rp = pfill(0.0,partition(Ph.gids))
xp = pfill(0.0,partition(Ph.gids))
rp_mat = pfill(0.0,partition(axes(Ahp,2)))
xp_mat = pfill(0.0,partition(axes(Ahp,2)))
copy!(r1,r1_mat)
consistent!(r1) |> fetch
PBS.prolongate!(rp,Ph,r1) # OK
copy!(rp_mat,rp)
consistent!(rp_mat) |> fetch
solve!(xp_mat,LUns,rp_mat)
copy!(xp,xp_mat) # Some big numbers appear here....
w, w_sums = PBS.compute_weight_operators(Ph,Vh);
PBS.inject!(x1,Ph,xp,w,w_sums) # Problem here!!
copy!(x1_mat,x1)
# ---- Same using the PatchBasedSmoother ---- #
x2_mat = pfill(0.5,partition(axes(Ah,2)))
r2_mat = fh-Ah*x2_mat
consistent!(r2_mat) |> fetch
solve!(x2_mat,Mns,r2_mat)
# ---- Smoother inside Richardson
x3_mat = pfill(0.5,partition(axes(Ah,2)))
r3_mat = fh-Ah*x3_mat
consistent!(r3_mat)
solve!(x3_mat,Rns,r3_mat)
consistent!(x3_mat) |> fetch
# Outputs
res = Dict{String,Any}()
res["sol_h"] = sol_h
res["sol_hp"] = sol_hp
res["r1"] = r1
res["x1"] = x1
res["r1_mat"] = r1_mat
res["x1_mat"] = x1_mat
res["rp"] = rp
res["xp"] = xp
res["rp_mat"] = rp_mat
res["xp_mat"] = xp_mat
res["w"] = w
res["w_sums"] = w_sums
return model,PD,Ph,Vh,res
end
ranks = (1,1)
Ms,PDs,Phs,Vhs,res_single = run(ranks);
ranks = (1,2)
Mm,PDm,Phm,Vhm,res_multi = run(ranks);
println(repeat('#',80))
map(local_views(Ms)) do model
cell_ids = get_cell_node_ids(model)
cell_coords = get_cell_coordinates(model)
display(reshape(cell_ids,length(cell_ids)))
display(reshape(cell_coords,length(cell_coords)))
end;
println(repeat('-',80))
cell_gids = get_cell_gids(Mm)
vertex_gids = get_face_gids(Mm,0)
edge_gids = get_face_gids(Mm,1)
println(">>> Cell gids")
map(cell_gids.partition) do p
println(transpose(p.lid_to_ohid))
end;
println(repeat('-',80))
println(">>> Vertex gids")
map(vertex_gids.partition) do p
println(transpose(p.lid_to_ohid))
end;
println(repeat('-',80))
println(">>> Edge gids")
map(edge_gids.partition) do p
println(transpose(p.lid_to_ohid))
end;
println(repeat('#',80))
map(local_views(Phs)) do Ph
display(Ph.patch_cell_dofs_ids)
end;
map(local_views(Phm)) do Ph
display(Ph.patch_cell_dofs_ids)
end;
println(repeat('#',80))
for key in keys(res_single)
val_s = res_single[key]
val_m = res_multi[key]
println(">>> ", key)
map(partition(val_s)) do v
println(transpose(v))
end;
map(own_values(val_m)) do v
println(transpose(v))
end;
println(repeat('-',80))
end
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 3997 | module DistributedPatchFESpacesTests
using LinearAlgebra
using Test
using PartitionedArrays
using Gridap
using Gridap.Helpers
using Gridap.Geometry
using Gridap.FESpaces
using Gridap.ReferenceFEs
using GridapDistributed
using FillArrays
using GridapSolvers
import GridapSolvers.PatchBasedSmoothers as PBS
np = (2,1)
parts = with_debug() do distribute
distribute(LinearIndices((prod(np),)))
end
domain = (0,1,0,1)
domain_partition = (4,3)
isperiodic = (false,true)
if prod(np) == 1
model = CartesianDiscreteModel(domain,domain_partition;isperiodic)
add_tag_from_tags!(get_face_labeling(model), "dirichlet", [1,2,5])
else
model = CartesianDiscreteModel(parts,np,domain,domain_partition;isperiodic)
map(local_views(get_face_labeling(model))) do labels
add_tag_from_tags!(labels, "dirichlet", [1,2,5])
end
end
pbs = PBS.PatchBoundaryExclude()
PD = PBS.PatchDecomposition(model;patch_boundary_style=pbs)
conf = :hdiv
order = 1
if conf === :h1
_reffe = ReferenceFE(lagrangian,Float64,order)
reffe = LagrangeRefFE(Float64,QUAD,order)
conformity = H1Conformity()
f = 1.0
u_bc = 0.0
biform(u,v,dΩ) = ∫(v⋅u)*dΩ
liform(v,dΩ) = ∫(f⋅v)*dΩ
else
_reffe = ReferenceFE(raviart_thomas,Float64,order)
reffe = RaviartThomasRefFE(Float64,QUAD,order)
conformity = DivConformity()
f = VectorValue(1.0,1.0)
u_bc = VectorValue(1.0,0.0)
biform(u,v,dΩ) = ∫(u⋅v + divergence(v)⋅divergence(u))*dΩ
liform(v,dΩ) = ∫(f⋅v)*dΩ
end
Vh = TestFESpace(model,_reffe,dirichlet_tags="dirichlet")
Uh = TrialFESpace(Vh,u_bc)
Ph = PBS.PatchFESpace(Vh,PD,_reffe;conformity)
Ωₚ = Triangulation(PD)
dΩₚ = Measure(Ωₚ,2*(order+2))
ap(u,v) = biform(u,v,dΩₚ)
Ahp = assemble_matrix(ap,Ph,Ph)
cond(Matrix(Ahp))
det(Ahp)
n1 = 4 # 8
A_corner = Matrix(Ahp)[1:n1,1:n1]
det(A_corner)
# ---- Testing Prolongation and Injection ---- #
w, w_sums = PBS.compute_weight_operators(Ph,Vh);
xP = zero_free_values(Ph) .+ 1.0
yP = zero_free_values(Ph)
x = zero_free_values(Vh) .+ 1.0
y = zero_free_values(Vh)
PBS.prolongate!(yP,Ph,x)
PBS.inject!(y,Ph,yP,w,w_sums)
@test x ≈ y
PBS.inject!(x,Ph,xP,w,w_sums)
PBS.prolongate!(yP,Ph,x)
@test xP ≈ yP
@benchmark PBS.inject!($y,$Ph,$yP,$w,$w_sums)
@benchmark PBS.inject!($y,$Ph,$yP)
# ---- Assemble systems ---- #
Ω = Triangulation(model)
dΩ = Measure(Ω,2*order+1)
a(u,v) = biform(u,v,dΩ)
l(v) = liform(v,dΩ)
assembler = SparseMatrixAssembler(Vh,Vh)
Ah = assemble_matrix(a,assembler,Vh,Vh)
fh = assemble_vector(l,assembler,Vh)
sol_h = solve(LUSolver(),Ah,fh)
Ωₚ = Triangulation(PD)
dΩₚ = Measure(Ωₚ,2*order+1)
ap(u,v) = biform(u,v,dΩₚ)
lp(v) = liform(v,dΩₚ)
assembler_P = SparseMatrixAssembler(Ph,Ph)
Ahp = assemble_matrix(ap,assembler_P,Ph,Ph)
fhp = assemble_vector(lp,assembler_P,Ph)
# ---- Define solvers ---- #
LU = LUSolver()
LUss = symbolic_setup(LU,Ahp)
LUns = numerical_setup(LUss,Ahp)
M = PBS.PatchBasedLinearSolver(ap,Ph,Vh,LU)
Mss = symbolic_setup(M,Ah)
Mns = numerical_setup(Mss,Ah)
R = RichardsonSmoother(M,10,1.0/3.0)
Rss = symbolic_setup(R,Ah)
Rns = numerical_setup(Rss,Ah)
# ---- Manual solve using LU ---- #
x1_mat = pfill(0.5,partition(axes(Ah,2)))
r1_mat = fh-Ah*x1_mat
consistent!(r1_mat) |> fetch
r1 = pfill(0.0,partition(Vh.gids))
x1 = pfill(0.0,partition(Vh.gids))
rp = pfill(0.0,partition(Ph.gids))
xp = pfill(0.0,partition(Ph.gids))
rp_mat = pfill(0.0,partition(axes(Ahp,2)))
xp_mat = pfill(0.0,partition(axes(Ahp,2)))
copy!(r1,r1_mat)
consistent!(r1) |> fetch
PBS.prolongate!(rp,Ph,r1)
copy!(rp_mat,rp)
solve!(xp_mat,LUns,rp_mat)
copy!(xp,xp_mat)
w, w_sums = PBS.compute_weight_operators(Ph,Vh);
PBS.inject!(x1,Ph,xp,w,w_sums)
copy!(x1_mat,x1)
# ---- Same using the PatchBasedSmoother ---- #
x2_mat = pfill(0.5,partition(axes(Ah,2)))
r2_mat = fh-Ah*x2_mat
consistent!(r2_mat) |> fetch
solve!(x2_mat,Mns,r2_mat)
# ---- Smoother inside Richardson
x3_mat = pfill(0.5,partition(axes(Ah,2)))
r3_mat = fh-Ah*x3_mat
consistent!(r3_mat) |> fetch
solve!(x3_mat,Rns,r3_mat)
consistent!(x3_mat) |> fetch
end | GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 1780 |
using LinearAlgebra
using Test
using PartitionedArrays
using Gridap
using Gridap.Arrays
using Gridap.Helpers
using Gridap.Geometry
using Gridap.ReferenceFEs
using Gridap.FESpaces
using GridapDistributed
using FillArrays
using GridapSolvers
import GridapSolvers.PatchBasedSmoothers as PBS
num_ranks = (1,2)
parts = with_debug() do distribute
distribute(LinearIndices((prod(num_ranks),)))
end
domain = (0,1,0,1)
mesh_partition = (2,4)
model = CartesianDiscreteModel(domain,mesh_partition)
#order = 1; reffe = ReferenceFE(lagrangian,Float64,order;space=:P); conformity = L2Conformity();
order = 1; reffe = ReferenceFE(lagrangian,Float64,order); conformity = H1Conformity();
#order = 0; reffe = ReferenceFE(raviart_thomas,Float64,order); conformity = HDivConformity();
Vh = TestFESpace(model,reffe,conformity=conformity)
PD = PBS.PatchDecomposition(model)
Ph = PBS.PatchFESpace(Vh,PD,reffe;conformity)
# ---- Assemble systems ---- #
Ω = Triangulation(model)
dΩ = Measure(Ω,2*order+1)
Λ = Skeleton(model)
dΛ = Measure(Λ,3)
Γ = Boundary(model)
dΓ = Measure(Γ,3)
aΩ(u,v) = ∫(v⋅u)*dΩ
aΛ(u,v) = ∫(jump(v)⋅jump(u))*dΛ
aΓ(u,v) = ∫(v⋅u)*dΓ
a(u,v) = aΩ(u,v) + aΛ(u,v) + aΓ(u,v)
l(v) = ∫(1*v)*dΩ
assembler = SparseMatrixAssembler(Vh,Vh)
Ah = assemble_matrix(a,assembler,Vh,Vh)
fh = assemble_vector(l,assembler,Vh)
sol_h = solve(LUSolver(),Ah,fh)
Ωₚ = Triangulation(PD)
dΩₚ = Measure(Ωₚ,2*order+1)
Λₚ = SkeletonTriangulation(PD)
dΛₚ = Measure(Λₚ,3)
Γₚ = BoundaryTriangulation(PD)
dΓₚ = Measure(Γₚ,3)
aΩp(u,v) = ∫(v⋅u)*dΩₚ
aΛp(u,v) = ∫(jump(v)⋅jump(u))*dΛₚ
aΓp(u,v) = ∫(v⋅u)*dΓₚ
ap(u,v) = aΩp(u,v) + aΛp(u,v) + aΓp(u,v)
lp(v) = ∫(1*v)*dΩₚ
assembler_P = SparseMatrixAssembler(Ph,Ph)
Ahp = assemble_matrix(ap,assembler_P,Ph,Ph)
fhp = assemble_vector(lp,assembler_P,Ph)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 795 |
using Gridap
using GridapDistributed
using PartitionedArrays
using GridapSolvers
using GridapSolvers.MultilevelTools, GridapSolvers.PatchBasedSmoothers
np = 2
parts = with_mpi() do distribute
distribute(LinearIndices((prod(np),)))
end
mh1 = CartesianModelHierarchy(parts,[np,np],(0,1,0,1),(2,2))
model1 = get_model(mh1,1)
glue1 = mh1[1].ref_glue
mh2 = CartesianModelHierarchy(parts,[np,1],(0,1,0,1),(2,2))
model2 = get_model_before_redist(mh2,1)
glue2 = mh2[1].ref_glue
gids1 = get_face_gids(model1,0)
mask1 = PatchBasedSmoothers.get_coarse_node_mask(model1,glue1)
display(local_to_global(gids1))
display(mask1)
if i_am_main(parts)
gids2 = get_face_gids(model2,0)
mask2 = PatchBasedSmoothers.get_coarse_node_mask(model2,glue2)
display(local_to_global(gids2))
display(mask2)
end
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | code | 4561 | using Gridap
using Gridap.CellData, Gridap.Geometry, Gridap.FESpaces, Gridap.Arrays, Gridap.Algebra
using GridapSolvers
using GridapSolvers.LinearSolvers
using GridapSolvers.MultilevelTools
using GridapSolvers.PatchBasedSmoothers
using LinearAlgebra
get_edge_measures(Ω::Triangulation,dΩ) = sqrt∘CellField(get_array(∫(1)dΩ),Ω)
function weakform_dg(u,v,Ω,Γ,Λ,qorder)
dΩ = Measure(Ω, qorder)
dΓ = Measure(Γ, qorder)
dΛ = Measure(Λ, qorder)
n_Γ = get_normal_vector(Γ)
n_Λ = get_normal_vector(Λ)
h_e_Λ = get_edge_measures(Λ,dΛ)
h_e_Γ = get_edge_measures(Γ,dΓ)
ω = 1000.0
c = ∫(∇(u)⋅∇(v))*dΩ +
∫(-jump(u⋅n_Λ)⋅mean(∇(v)) - mean(∇(u))⋅jump(v⋅n_Λ) + ω/h_e_Λ*jump(u⋅n_Λ)⋅jump(v⋅n_Λ))*dΛ +
∫(-(∇(u)⋅n_Γ)⋅v - u⋅(∇(v)⋅n_Γ) + ω/h_e_Γ*(u⋅n_Γ)⋅(v⋅n_Γ))*dΓ
return c
end
function weakform_dg_patch(u,v,Ω,Γ_phys,Γ_patch,Λ,qorder)
dΩ = Measure(Ω, qorder)
dΓ_phys = Measure(Γ_phys, qorder)
dΓ_patch = Measure(Γ_patch, qorder)
dΛ = Measure(Λ, qorder)
n_Γ_phys = get_normal_vector(Γ_phys)
n_Γ_patch = get_normal_vector(Γ_patch)
n_Λ = get_normal_vector(Λ)
h_e_Λ = get_edge_measures(Λ,dΛ)
h_e_Γ_phys = get_edge_measures(Γ_phys,dΓ_phys)
h_e_Γ_patch = get_edge_measures(Γ_patch,dΓ_patch)
ω = 1000.0
c = ∫(∇(u)⋅∇(v))*dΩ +
∫(-jump(u⋅n_Λ)⋅mean(∇(v)) - mean(∇(u))⋅jump(v⋅n_Λ) + ω/h_e_Λ*jump(u⋅n_Λ)⋅jump(v⋅n_Λ))*dΛ +
∫(-(∇(u)⋅n_Γ_phys)⋅v - u⋅(∇(v)⋅n_Γ_phys) + ω/h_e_Γ_phys*(u⋅n_Γ_phys)⋅(v⋅n_Γ_phys))*dΓ_phys +
∫(-(∇(u)⋅n_Γ_patch)⋅v - u⋅(∇(v)⋅n_Γ_patch) + ω/h_e_Γ_patch*(u⋅n_Γ_patch)⋅(v⋅n_Γ_patch))*dΓ_patch
return c
end
function weakform(u,v,Ω,qorder)
dΩ = Measure(Ω, qorder)
c = ∫(∇(u)⋅∇(v))*dΩ
return c
end
btags = ["boundary"]
model = CartesianDiscreteModel((0,1,0,1),(8,8))
PD = PatchDecomposition(model;boundary_tag_names=btags)
Ω = Triangulation(model)
Γ = BoundaryTriangulation(model)
Λ = SkeletonTriangulation(model)
Ωp = Triangulation(PD)
Γp = BoundaryTriangulation(PD)
Λp = SkeletonTriangulation(PD)
Γp_patch = BoundaryTriangulation(PD;reverse=true)
order = 2
qdegree = 2*(order+1)
dΩ = Measure(Ω, qdegree)
dΓ = Measure(Γ, qdegree)
dΛ = Measure(Λ, qdegree)
u_sol(x) = x[1]*(1-x[1])*x[2]*(1-x[2])
f(x) = Δ(u_sol)(x)
g = VectorValue(1.0,1.0)
# Continuous problem
reffe_h1 = ReferenceFE(lagrangian,Float64,order)
V_h1 = FESpace(model,reffe_h1;dirichlet_tags=btags)
P_h1 = PatchFESpace(V_h1,PD,reffe_h1)
a_h1(u,v) = weakform(u,v,Ω,qdegree)
l_h1(v) = ∫(f⋅v)*dΩ
op_h1 = AffineFEOperator(a_h1,l_h1,V_h1,V_h1)
A_h1, b_h1 = get_matrix(op_h1), get_vector(op_h1)
S_h1 = RichardsonSmoother(PatchBasedLinearSolver((u,v)->weakform(u,v,Ωp,qdegree),P_h1,V_h1),10,0.2)
solver_h1 = CGSolver(S_h1,verbose=true)
ns_h1 = numerical_setup(symbolic_setup(solver_h1,A_h1),A_h1)
x_h1 = allocate_in_domain(A_h1); fill!(x_h1,0.0)
solve!(x_h1,ns_h1,b_h1)
uh_h1 = FEFunction(V_h1,x_h1)
# Discontinuous problem
reffe_l2 = ReferenceFE(lagrangian,Float64,order)
V_l2 = FESpace(model,reffe_l2;conformity=:L2,dirichlet_tags="boundary")
P_l2 = PatchFESpace(V_l2,PD,reffe_l2;conformity=:L2)
ω = 1000.0
h_e_Γ = get_edge_measures(Γ,dΓ)
n_Γ = get_normal_vector(Γ)
a_l2(u,v) = weakform_dg(u,v,Ω,Γ,Λ,qdegree)
l_l2(v) = ∫(f⋅v)*dΩ + ∫(-(∇(v)⋅n_Γ)*u_sol + (ω/h_e_Γ)*v*u_sol)*dΓ
op_l2 = AffineFEOperator(a_l2,l_l2,V_l2,V_l2)
A_l2, b_l2 = get_matrix(op_l2), get_vector(op_l2)
S_l2 = RichardsonSmoother(PatchBasedLinearSolver((u,v)->weakform_dg_patch(u,v,Ωp,Γp,Γp_patch,Λp,qdegree),P_l2,V_l2),10,0.2)
solver_l2 = CGSolver(S_l2,verbose=true)
ns_l2 = numerical_setup(symbolic_setup(solver_l2,A_l2),A_l2)
x_l2 = allocate_in_domain(A_l2); fill!(x_l2,0.0)
solve!(x_l2,ns_l2,b_l2)
S_l2_ns = numerical_setup(symbolic_setup(S_l2,A_l2),A_l2)
solve!(x_l2,S_l2_ns,b_l2)
x_l2
x_l2 = A_l2\b_l2
uh_l2 = FEFunction(V_l2,x_l2)
eh = uh_h1 - uh_l2
sum(∫(eh⋅eh)*dΩ)
############################################################################################
### VECTOR POISSON PROBLEM
reffe_hdiv = ReferenceFE(raviart_thomas,Float64,order-1)
V_hdiv = FESpace(model,reffe_hdiv;dirichlet_tags="boundary")
P_hdiv = PatchFESpace(V_hdiv,PD,reffe_hdiv)
a_hdiv(u,v) = weakform_dg(u,v,Ω,Γ,Λ,qdegree)
l_hdiv(v) = ∫(f⋅v)*dΩ
op = AffineFEOperator(a_hdiv,l_hdiv,V_hdiv,V_hdiv)
A_hdiv, b_hdiv = get_matrix(op), get_vector(op)
S_hdiv = RichardsonSmoother(PatchBasedLinearSolver((u,v)->weakform_dg(u,v,Ωp,Γp,Λp,qdegree),P_hdiv,V_hdiv),10,0.2)
solver_hdiv = CGSolver(S_hdiv,verbose=true)
ns_hdiv = numerical_setup(symbolic_setup(solver_hdiv,A_hdiv),A_hdiv)
x_hdiv = allocate_in_domain(A_hdiv); fill!(x,0.0)
solve!(x_hdiv,ns_hdiv,b_hdiv)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | docs | 2973 | # GridapSolvers
[](https://gridap.github.io/GridapSolvers.jl/stable/)
[](https://gridap.github.io/GridapSolvers.jl/dev/)
[](https://github.com/gridap/GridapSolvers.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/gridap/GridapSolvers.jl)
[](https://zenodo.org/records/13327414)
GridapSolvers provides algebraic and non-algebraic solvers for the Gridap ecosystem, designed with High Performance Computing (HPC) in mind.
Solvers follow a modular design, where most blocks can be combined to produce PDE-taylored solvers for a wide range of problems.
## (Non-exhaustive) list of features
- **Krylov solvers**: We provide a (short) list of Krylov solvers, with full preconditioner support and HPC-first implementation.
- **Block preconditioners**: We provide full support for block assembly of multiphysics problems, and a generic API for building block-based preconditioners for block-assembled systems.
- **Multilevel support**: We provide a generic API for building multilevel preconditioners.
- **Geometric Multigrid**: We provide a full-fledged geometric multigrid solver. Highly scalable adaptivity and redistribution of meshes, provided by `p4est` through `GridapP4est.jl`.
- **PETSc interface**: Full access to PETSc algebraic solvers, through `GridapPETSc.jl`, with full interoperability with the rest of the aforementioned solvers.
## Installation
GridapSolvers is a registered package in the official [Julia package registry](https://github.com/JuliaRegistries/General). Thus, the installation of GridapSolvers is straight forward using the [Julia's package manager](https://julialang.github.io/Pkg.jl/v1/). Open the Julia REPL, type `]` to enter package mode, and install as follows
```julia
pkg> add GridapSolvers
pkg> build
```
Building is required to link the external artifacts (e.g., PETSc, p4est) to the Julia environment. Restarting Julia is required after building in order to make the changes take effect.
### Using custom binaries
The previous installations steps will setup GridapSolvers to work using Julia's pre-compiled artifacts for MPI, PETSc and p4est. However, you can also link local copies of these libraries. This might be very desirable in clusters, where hardware-specific libraries might be faster/more stable than the ones provided by Julia. To do so, follow the next steps:
- [MPI.jl](https://juliaparallel.org/MPI.jl/stable/configuration/)
- [GridapPETSc.jl](https://github.com/gridap/GridapPETSc.jl)
- [GridapP4est.jl](https://github.com/gridap/GridapP4est.jl), and [P4est_wrapper.jl](https://github.com/gridap/p4est_wrapper.jl)
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | docs | 2076 |
```@meta
CurrentModule = GridapSolvers.BlockSolvers
```
# GridapSolvers.BlockSolvers
Many scalable preconditioners for multiphysics problems are based on (possibly partial) block factorizations. This module provides a simple interface to define and use block solvers for block-assembled systems.
## Block types
In a same preconditioner, blocks can come from different sources. For example, in a Schur-complement-based preconditioner you might want to solve the eliminated block (which comes from the original matrix), while having an approximation for your Schur complement (which can come from a matrix assembled in your driver, or from a weakform).
For this reason, we define the following abstract interface:
```@docs
SolverBlock
LinearSolverBlock
NonlinearSolverBlock
```
On top of this interface, we provide some useful block implementations:
```@docs
LinearSystemBlock
NonlinearSystemBlock
MatrixBlock
BiformBlock
TriformBlock
```
To create a new type of block, one needs to implement the following implementation (similar to the one for `LinearSolver`):
```@docs
block_symbolic_setup
block_numerical_setup
block_numerical_setup!
block_offdiagonal_setup
block_offdiagonal_setup!
```
## Block solvers
We can combine blocks to define a block solver. All block solvers take an array of blocks and a vector of solvers for the diagonal blocks (which need to be solved for). We provide two common types of block solvers:
### BlockDiagonalSolvers
```@docs
BlockDiagonalSolver
BlockDiagonalSolver(blocks::AbstractVector{<:SolverBlock},solvers::AbstractVector{<:LinearSolver})
BlockDiagonalSolver(solvers::AbstractVector{<:LinearSolver})
BlockDiagonalSolver(funcs::AbstractArray{<:Function},trials::AbstractArray{<:FESpace},tests::AbstractArray{<:FESpace},solvers::AbstractArray{<:LinearSolver})
```
### BlockTriangularSolvers
```@docs
BlockTriangularSolver
BlockTriangularSolver(blocks::AbstractMatrix{<:SolverBlock},solvers ::AbstractVector{<:LinearSolver},)
BlockTriangularSolver(solvers::AbstractVector{<:LinearSolver})
```
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | docs | 1512 |
```@meta
CurrentModule = GridapSolvers.LinearSolvers
```
# GridapSolvers.LinearSolvers
## Krylov solvers
```@docs
CGSolver
MINRESSolver
GMRESSolver
FGMRESSolver
krylov_mul!
krylov_residual!
```
## Smoothers
Given a linear system ``Ax = b``, a **smoother** is an operator `S` that takes an iterative solution ``x_k`` and its residual ``r_k = b - A x_k``, and modifies them **in place**
```math
S : (x_k,r_k) \rightarrow (x_{k+1},r_{k+1})
```
such that ``|r_{k+1}| < |r_k|``.
```@docs
RichardsonSmoother
RichardsonSmoother(M::LinearSolver)
```
## Preconditioners
Given a linear system ``Ax = b``, a **preconditioner** is an operator that takes an iterative residual ``r_k`` and returns a correction ``dx_k``.
```@docs
JacobiLinearSolver
GMGLinearSolverFromMatrices
GMGLinearSolverFromWeakform
GMGLinearSolver
```
## Wrappers
### PETSc
Building on top of [GridapPETSc.jl](https://github.com/gridap/GridapPETSc.jl), GridapSolvers provides specific solvers for some particularly complex PDEs:
```@docs
ElasticitySolver
ElasticitySolver(::FESpace)
CachedPETScNS
CachedPETScNS(::GridapPETSc.PETScLinearSolverNS,::AbstractVector,::AbstractVector)
get_dof_coordinates
```
### IterativeSolvers.jl
GridapSolvers provides wrappers for some iterative solvers from the package [IterativeSolvers.jl](https://iterativesolvers.julialinearalgebra.org/dev/):
```@docs
IterativeLinearSolver
IS_ConjugateGradientSolver
IS_GMRESSolver
IS_MINRESSolver
IS_SSORSolver
```
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | docs | 1053 |
```@meta
CurrentModule = GridapSolvers.MultilevelTools
```
# GridapSolvers.MultilevelTools
## Nested subpartitions
One of the main difficulties of multilevel algorithms is dealing with the complexity of having multiple subcommunicators. We provide some tools to deal with it. In particular we introduce `HierarchicalArray`s.
```@docs
generate_level_parts
HierarchicalArray
Base.map
with_level
```
## ModelHierarchies and FESpaceHierarchies
This objects are the multilevel counterparts of Gridap's `DiscreteModel` and `FESpace`.
```@docs
ModelHierarchy
ModelHierarchyLevel
CartesianModelHierarchy
P4estCartesianModelHierarchy
FESpaceHierarchy
```
## Grid transfer operators
To move information between different levels, we will require grid transfer operators. Although any custom-made operator can be used, we provide some options.
```@docs
DistributedGridTransferOperator
RestrictionOperator
ProlongationOperator
MultiFieldTransferOperator
```
## Local projection maps
```@docs
LocalProjectionMap
ReffeProjectionMap
SpaceProjectionMap
```
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | docs | 143 |
```@meta
CurrentModule = GridapSolvers.NonlinearSolvers
```
# GridapSolvers.NonlinearSolvers
```@autodocs
Modules = [NonlinearSolvers,]
```
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | docs | 152 |
```@meta
CurrentModule = GridapSolvers.PatchBasedSmoothers
```
# GridapSolvers.PatchBasedSmoothers
```@autodocs
Modules = [PatchBasedSmoothers,]
```
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | docs | 388 |
```@meta
CurrentModule = GridapSolvers.SolverInterfaces
```
# GridapSolvers.SolverInterfaces
## SolverTolerances
```@docs
SolverTolerances
SolverConvergenceFlag
get_solver_tolerances
set_solver_tolerances!
finished
converged
finished_flag
```
## ConvergenceLogs
```@docs
ConvergenceLog
SolverVerboseLevel
reset!
init!
update!
finalize!
print_message
```
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.4.1 | 2b09db401471a212fb06a9c2577f4a0be77039c2 | docs | 588 | ```@meta
CurrentModule = GridapSolvers
```
# GridapSolvers
Documentation for [GridapSolvers](https://github.com/gridap/GridapSolvers.jl).
GridapSolvers provides algebraic and non-algebraic solvers for the Gridap ecosystem, designed with High Performance Computing (HPC) in mind.
Solvers follow a modular design, where most blocks can be combined to produce PDE-taylored solvers for a wide range of problems.
```@contents
Pages = [
"SolverInterfaces.md",
"MultilevelTools.md",
"LinearSolvers.md",
"NonlinearSolvers.md",
"BlockSolvers.md",
"PatchBasedSmoothers.md"
]
```
| GridapSolvers | https://github.com/gridap/GridapSolvers.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | code | 70 | @static if Sys.isapple()
using Homebrew
Homebrew.update()
end
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | code | 22194 | # This file contains the API that users interact with. Everything in here should
# depend only on `brew()` calls.
"""
`brew(cmd::Cmd; no_stderr=false, no_stdout=false, verbose=false, force=false, quiet=false)`
Run command `cmd` using the configured brew binary, optionally suppressing
stdout and stderr, and providing flags such as `--verbose` to the brew binary.
"""
function brew(cmd::Cmd; no_stderr=false, no_stdout=false, verbose::Bool=false, force::Bool=false, quiet::Bool=false)
cmd = add_flags(`$brew_exe $cmd`, Dict(`--verbose` => verbose, `--force` => force, `--quiet` => quiet))
if no_stderr
cmd = pipeline(cmd, stderr=devnull)
end
if no_stdout
cmd = pipeline(cmd, stdout=devnull)
end
return run(cmd)
end
"""
`brewchomp(cmd::Cmd; no_stderr=false, no_stdout=false, verbose=false, force=false, quiet=false))`
Run command `cmd` using the configured brew binary, optionally suppressing
stdout and stderr, and providing flags such as `--verbose` to the brew binary.
This function uses `readchomp()`, as opposed to `brew()` which uses `run()`
"""
function brewchomp(cmd::Cmd; no_stderr=false, no_stdout=false, verbose::Bool=false, force::Bool=false, quiet::Bool=false)
cmd = add_flags(`$brew_exe $cmd`, Dict(`--verbose` => verbose, `--force` => force, `--quiet` => quiet))
if no_stderr
cmd = pipeline(cmd, stderr=devnull)
end
if no_stdout
cmd = pipeline(cmd, stdout=devnull)
end
return readchomp(cmd)
end
"""
`update(;verbose::Bool=false)`
Runs `brew update` to update Homebrew itself and all taps. Then runs `upgrade()`
to upgrade all formulae that have fallen out of date.
"""
function update(;verbose::Bool=false)
# Just run `brew update`
brew(`update`; force=true, verbose=verbose)
# Ensure we're on the right tag
update_tag(;verbose=verbose)
# Finally, upgrade outdated packages.
upgrade(;verbose=verbose)
end
"""
`prefix()`
Returns `brew_prefix`, the location where all Homebrew files are stored.
"""
function prefix()
return brew_prefix
end
"""
`prefix(pkg::Union{AbstractString,BrewPkg})`
Returns the prefix for a particular package's latest installed version.
"""
function prefix(pkg::StringOrPkg) end
function prefix(name::AbstractString)
path, tap_path = formula_tap(name)
return joinpath(brew_prefix, "Cellar", path, info(name).version)
end
function prefix(pkg::BrewPkg)
prefix(pkg.name)
end
"""
`list()`
Returns a list of all installed packages as a `Vector{BrewPkg}`
"""
function list()
# Get list of fully-qualified installed packages
names = brewchomp(`list --full-name`)
# If we've got something, then return info on all those names
if !isempty(names)
return info(split(names,"\n"))
end
return BrewPkg[]
end
"""
`outdated()`
Returns a list of all installed packages that are out of date as a `Vector{BrewPkg}`
"""
function outdated()
json_str = brewchomp(`outdated --json=v1`)
if isempty(json_str)
return BrewPkg[]
end
brew_outdated = JSON.parse(json_str)
outdated_pkgs = BrewPkg[info(pkg["name"]) for pkg in brew_outdated]
return outdated_pkgs
end
"""
`refresh!(;verbose=false)`
Forcibly remove all packages and add them again. This should only be used to
fix a broken installation, normal operation should never need to use this.
"""
function refresh!(;verbose=false)
pkg_list = list()
for pkg in pkg_list
rm(pkg,verbose=verbose)
end
for pkg in pkg_list
add(pkg,verbose=verbose)
end
end
"""
`upgrade(;verbose::Bool=false)`
Iterate over all packages returned from `outdated()`, removing the old version
and adding a new one. Note that we do not simply call `brew upgrade` here, as
we have special logic inside of `add()` to install from our tap before trying to
install from mainline Homebrew.
"""
function upgrade(;verbose::Bool=false)
# We have to manually upgrade each package, as `brew upgrade` will pull from mxcl/master
for pkg in outdated()
rm(pkg; verbose=verbose)
add(pkg; verbose=verbose)
end
end
const json_cache = Dict{String,Dict{AbstractString,Any}}()
"""
`json(names::Vector{AbstractString})`
For each package name in `names`, return the full JSON object for `name`, the
result of `brew info --json=v1 \$name`, stored in a dictionary keyed by the names
passed into this function. If `brew info` fails, throws an error. If `brew info`
returns an empty object "[]", that object is represented by an empty dictionary.
Note that running `brew info --json=v1` is somewhat expensive, so we cache the
results in a global dictionary, and batching larger requests with this function
similarly increases performance.
"""
function json(names::Vector{T}) where {T <: AbstractString}
# This is the dictionary of responses we'll return
objs = Dict{String,Dict{AbstractString,Any}}()
# Build list of names we have to ask for, eschewing asking for caching when we can
ask_names = String[]
for name in names
if haskey(json_cache, name)
objs[name] = json_cache[name]
else
push!(ask_names, name)
end
end
# Now ask for all these names if we have any
if !isempty(ask_names)
# Tap the necessary tap for each name we're asking about, if there is one
for name in ask_names
path, tap_path = formula_tap(name)
if !isempty(tap_path)
tap(tap_path)
end
end
try
jdata = JSON.parse(brewchomp(Cmd(String["info", "--json=v1", ask_names...])))
for idx in 1:length(jdata)
json_cache[ask_names[idx]] = jdata[idx]
objs[ask_names[idx]] = jdata[idx]
end
catch
throw(ArgumentError("`brew info` failed for $(ask_names)!"))
end
end
# Return these hard-won objects
return objs
end
"""
`json(pkg::Union{AbstractString,BrewPkg})`
Return the full JSON object for `pkg`, the result of `brew info --json=v1 \$pkg`.
If `brew info` fails, throws an error. If `brew info` returns an empty object,
(e.g. "[]"), this returns an empty Dict.
Note that running `brew info --json=v1` is somewhat expensive, so we cache the
results in a global dictionary, and batching larger requests with the vectorized
`json()` function similarly increases performance.
"""
function json(pkg::StringOrPkg) end
function json(name::AbstractString)
return json([name])[name]
end
function json(pkg::BrewPkg)
return json([fullname(pkg)])[fullname(pkg)]
end
"""
`info(names::Vector{String})`
For each name in `names`, returns information about that particular package name
as a BrewPkg. This is our batched `String` -> `BrewPkg` converter.
"""
function info(names::Vector{T}) where {T <: AbstractString}
# Get the JSON representations of all of these packages
objs = json(names)
infos = BrewPkg[]
for name in names
obj = objs[name]
# First, get name and version
obj_name = obj["name"]
version = obj["versions"]["stable"]
# Manually append the revision to the end of the version, as brew is wont to do
if obj["revision"] > 0
version *= "_$(obj["revision"])"
end
tap = dirname(obj["full_name"])
if isempty(tap)
tap = "Homebrew/core"
end
# Push that BrewPkg onto our infos object
push!(infos, BrewPkg(obj_name, tap, version))
end
# Return the list of infos
return infos
end
"""
`info(name::AbstractString)`
Returns information about a particular package name as a BrewPkg. This is our
basic `String` -> `BrewPkg` converter.
"""
function info(name::AbstractString)
return info([name])[1]
end
"""
`direct_deps(pkg::Union{AbstractString,BrewPkg}; build_deps::Bool=false)`
Return a list of all direct dependencies of `pkg` as a `Vector{BrewPkg}`
If `build_deps` is `true` include formula depependencies marked as `:build`.
"""
function direct_deps(pkg::StringOrPkg; build_deps::Bool=false) end
function direct_deps(name::AbstractString; build_deps::Bool=false)
obj = json(name)
# Iterate over all dependencies, removing optional and build dependencies
dependencies = String[dep for dep in obj["dependencies"]]
dependencies = filter(x -> !(x in obj["optional_dependencies"]), dependencies)
if !build_deps
dependencies = filter(x -> !(x in obj["build_dependencies"]), dependencies)
end
return info(dependencies)
end
function direct_deps(pkg::BrewPkg; build_deps::Bool=false)
return direct_deps(fullname(pkg); build_deps=build_deps)
end
"""
`deps_tree(pkg::Union{AbstractString,BrewPkg}; build_deps::Bool=false)`
Return a dictionary mapping every dependency (both direct and indirect) of `pkg`
to a `Vector{BrewPkg}` of all of its dependencies. Used in `deps_sorted()`.
If `build_deps` is `true` include formula depependencies marked as `:build`.
"""
function deps_tree(pkg::StringOrPkg; build_deps::Bool=false) end
function deps_tree(name::AbstractString; build_deps::Bool=false)
# First, get all the knowledge we need about dependencies
deptree = Dict{String,Vector{BrewPkg}}()
pending_deps = direct_deps(name; build_deps=build_deps)
completed_deps = Set(String[])
while !isempty(pending_deps)
# Temporarily move pending_deps over to curr_pending_deps
curr_pending_deps = pending_deps
pending_deps = BrewPkg[]
# Iterate over these currently pending deps, adding new ones to pending_deps
for pkg in curr_pending_deps
deptree[fullname(pkg)] = direct_deps(pkg; build_deps=build_deps)
push!(completed_deps, fullname(pkg))
for dpkg in deptree[fullname(pkg)]
if !(fullname(dpkg) in completed_deps)
push!(pending_deps, dpkg)
end
end
end
end
return deptree
end
function deps_tree(pkg::BrewPkg; build_deps::Bool=false)
return deps_tree(fullname(pkg); build_deps=build_deps)
end
"""
`insert_after_dependencies(tree::Dict, sorted_deps::Vector{BrewPkg}, name::AbstractString)`
Given a mapping from names to dependencies in `tree`, and a list of sorted
dependencies in `sorted_deps`, insert a new dependency `name` into `sorted_deps`
after all dependencies of `name`. If a dependency of `name` is not already in
`sorted_deps`, then recursively add that dependency as well.
"""
function insert_after_dependencies(tree::Dict, sorted_deps::Vector{BrewPkg}, name::AbstractString)
# First off, are we already in sorted_deps? If so, back out!
self_idx = findfirst(x -> (fullname(x) == name), sorted_deps)
if self_idx != nothing
return self_idx
end
# This is the index at which we will insert ourselves
insert_idx = 1
# Iterate over all dependencies
for dpkg in tree[name]
# Is this dependency already in the sorted_deps?
idx = findfirst(x -> (fullname(x) == fullname(dpkg)), sorted_deps)
# If the dependency is not already in this list, then recurse into it!
if self_idx == nothing
idx = insert_after_dependencies(tree, sorted_deps, fullname(dpkg))
end
# Otherwise, update insert_idx
insert_idx = max(insert_idx, idx + 1)
end
# Finally, insert ourselves
insert!(sorted_deps, insert_idx, info(name))
return insert_idx
end
"""
`deps_sorted(pkg::Union{AbstractString,BrewPkg}; build_deps::Bool)`
Return a sorted `Vector{BrewPkg}` of all dependencies (direct and indirect) such
that each entry in the list appears after all of its own dependencies.
If `build_deps` is `true` include formula depependencies marked as `:build`.
"""
function deps_sorted(pkg::StringOrPkg; build_deps::Bool=false) end
function deps_sorted(name::AbstractString; build_deps::Bool=false)
tree = deps_tree(name; build_deps=build_deps)
sorted_deps = BrewPkg[]
# For each package in the tree, insert it only after all of its dependencies
# Just for aesthetic purposes, sort the keys by the number of dependencies
# they have first, so that packages with few deps end up on top
for name in sort(collect(keys(tree)), by=k-> length(tree[k]))
insert_after_dependencies(tree, sorted_deps, name)
end
return sorted_deps
end
function deps_sorted(pkg::BrewPkg; build_deps::Bool=false)
return deps_sorted(fullname(pkg); build_deps=build_deps)
end
"""
`add(pkg::Union{AbstractString,BrewPkg}; verbose::Bool=false, keep_translations::Bool=false)`
Install package `pkg` and all dependencies, using bottles only, unlinking any
previous versions if necessary, and linking the new ones in place. Will attempt
to install non-relocatable bottles from `Homebrew/core` by translating formulae
and forcing `cellar :any` into the formulae.
Automatically deletes all translated formulae before adding formulae and after,
unless `keep_translations` is set to `true`.
"""
function add(pkg::StringOrPkg; verbose::Bool=false, keep_translations::Bool=false) end
function add(name::AbstractString; verbose::Bool=false, keep_translations::Bool=false)
# We do this so that things are as unambiguous and fresh as possible.
# It's not a bad situation because translation is very fast.
if !keep_translations
delete_all_translated_formulae()
end
# Begin by translating all dependencies of `name`, including :build deps.
# We need to translate :build deps so that we don't run into the diamond of death
sorted_deps = AbstractString[]
build_deps_only = AbstractString[]
runtime_deps = [x.name for x in deps_sorted(name)]
if verbose
println("runtime_deps: $runtime_deps")
end
for dep in deps_sorted(name; build_deps=true)
translated_dep = translate_formula(dep; verbose=verbose)
# Collect the translated runtime_deps into sorted_deps
if dep.name in runtime_deps
push!(sorted_deps, translated_dep)
else
push!(build_deps_only, translated_dep)
end
end
if verbose
println("sorted_deps: $sorted_deps")
println("build_deps only: $build_deps_only")
end
# Translate the actual formula we're interested in
name = translate_formula(name; verbose=verbose)
# Push `name` onto the end of `sorted_deps` so we have one list of things to install
push!(sorted_deps, name)
# Ensure that we are able to install relocatable bottles for every package
non_relocatable = filter(x -> !has_relocatable_bottle(x), sorted_deps)
if !isempty(non_relocatable)
@warn("""
The following packages do not have relocatable bottles, installation may fail!
Please report these packages to https://github.com/JuliaLang/Homebrew.jl:
$(join(non_relocatable, "\n "))""")
end
# Get list of outdated packages and remove them all
for dep in filter(pkg -> pkg.name in sorted_deps, Homebrew.outdated())
unlink(dep; verbose=verbose)
end
# Install this package and all dependencies, in dependency order
for dep in sorted_deps
install_and_link(dep; verbose=verbose)
end
# Cleanup translated formula once we're done, unless asked not to
if !keep_translations
delete_all_translated_formulae()
end
end
function add(pkg::BrewPkg; verbose::Bool=false, keep_translations::Bool=false)
add(fullname(pkg); verbose=verbose, keep_translations=keep_translations)
end
"""
`install_and_link(pkg::Union{AbstractString,BrewPkg}; verbose=false)`
Installs, and links package `pkg`. Used by `add()`. Don't call manually
unless you really know what you're doing, as this doesn't deal with
dependencies, and so can trigger compilation when you don't want it to.
"""
function install_and_link(pkg::StringOrPkg; verbose::Bool=false) end
function install_and_link(name::AbstractString; verbose::Bool=false)
# If we're already linked, don't sweat it.
if linked(name)
return
end
# Install dependency and link it
brew(`install --ignore-dependencies $name`; verbose=verbose)
link(name; verbose=verbose)
end
function install_and_link(pkg::BrewPkg; verbose::Bool=false)
return install_and_link(fullname(pkg); verbose=verbose)
end
"""
`postinstall(pkg::Union{AbstractString,BrewPkg}; verbose=false)`
Runs `brew postinstall` against package `pkg`, useful for debugging complicated
formulae when a bottle doesn't install right and you want to re-run postinstall.
"""
function postinstall(pkg::StringOrPkg; verbose::Bool=false) end
function postinstall(name::AbstractString; verbose::Bool=false)
brew(`postinstall $name`, verbose=verbose)
end
function postinstall(pkg::BrewPkg; verbose::Bool=false)
postinstall(fullname(pkg), verbose=verbose)
end
"""
`link(pkg::Union{AbstractString,BrewPkg}; verbose=false, force=true)`
Link package `name` into the global namespace, uses `--force` if `force == true`
"""
function link(name::StringOrPkg; verbose::Bool=false, force::Bool=true) end
function link(name::AbstractString; verbose::Bool=false, force::Bool=true)
brew(`link $name`, no_stdout=true, verbose=verbose, force=force)
end
function link(pkg::BrewPkg; verbose::Bool=false, force::Bool=true)
return link(fullname(pkg); force=force, verbose=verbose)
end
"""
`unlink(pkg::Union{AbstractString,BrewPkg}; verbose::Bool=false, quiet::Bool=true)`
Unlink package `pkg` from the global namespace, uses `--quiet` if `quiet == true`
"""
function unlink(name::StringOrPkg; verbose::Bool=false, quiet::Bool=true) end
function unlink(name::AbstractString; verbose::Bool=false, quiet::Bool=true)
brew(`unlink $name`; verbose=verbose, quiet=quiet)
end
function unlink(pkg::BrewPkg; verbose::Bool=false, quiet::Bool=true)
return unlink(fullname(pkg); verbose=verbose, quiet=quiet)
end
"""
`rm(pkg::Union{AbstractString,BrewPkg}; verbose::Bool=false, force::Bool=true)`
Remove package `pkg`, use `--force` if `force` == `true`
"""
function rm(pkg::StringOrPkg; verbose::Bool=false, force::Bool=false) end
function rm(pkg::AbstractString; verbose::Bool=false, force::Bool=true)
brew(`rm --ignore-dependencies $pkg`; verbose=verbose, force=force)
end
function rm(pkg::BrewPkg; verbose::Bool=false, force::Bool=true)
return rm(fullname(pkg); verbose=verbose, force=force)
end
"""
`rm(pkgs::Vector{String or BrewPkg}; verbose::Bool=false, force::Bool=true)`
Remove packages `pkgs`, use `--force` if `force` == `true`
"""
function rm(pkgs::Vector{T}; verbose::Bool=false, force::Bool=false) where {T <: StringOrPkg}
for pkg in pkgs
try
rm(pkg; verbose=verbose, force=force)
catch
end
end
end
"""
`cleanup()`
Cleans up old installed versions of formulae, as well as purging all downloaded bottles
"""
function cleanup()
brew(`cleanup -s`)
end
"""
`tap(tap_name::AbstractString; full::Bool=true, verbose::Bool=false)`
Runs `brew tap \$tap_name` if the tap does not already exist. If `full` is `true`
adds the flag `--full` to clone a full tap instead of Homebrew's default shallow.
If `git` is not available, manually tap it with curl and tar. This tap will be
unshallowed at the next `brew update` when `git` is available.
"""
function tap(tap_name::AbstractString; full::Bool=true, verbose::Bool=false)
if !tap_exists(tap_name)
# If we have no git available, then do it oldschool style
if !git_installed()
user = dirname(tap_name)
repo = "homebrew-$(basename(tap_name))"
tarball_url = "https://github.com/$user/$repo/tarball/master"
tap_path = joinpath(brew_prefix,"Library","Taps", user, repo)
if verbose
@info("Manually tapping $tap_name...")
end
try
mkpath(tap_path)
run(pipeline(`curl -\# -L $tarball_url`, `tar xz -m --strip 1 -C $tap_path`))
catch
@warn("Could not download/extract $tarball_url into $(tap_path)!")
rethrow()
end
else
if full
brew(`tap --full $tap_name`; verbose=verbose)
else
brew(`tap $tap_name`; verbose=verbose)
end
end
end
end
const OSX_VERSION = [""]
function osx_version_string()
global OSX_VERSION
if isempty(OSX_VERSION[1])
OSX_VERSION[1] = join(split(readchomp(`sw_vers -productVersion`), ".")[1:2],".")
end
return Dict(
"10.4" => "tiger",
"10.5" => "leopard",
"10.6" => "snow_leopard",
"10.7" => "lion",
"10.8" => "mountain_lion",
"10.9" => "mavericks",
"10.10" => "yosemite",
"10.11" => "el_capitan",
"10.12" => "sierra",
"10.13" => "high_sierra",
"10.14" => "mojave"
)[OSX_VERSION[1]]
end
"""
`has_bottle(name::AbstractString)`
Checks if a given formula has a bottle at all
"""
function has_bottle(name::AbstractString)
return haskey(json(name)["bottle"], "stable") &&
haskey(json(name)["bottle"]["stable"]["files"], osx_version_string())
end
"""
`has_relocatable_bottle(name::AbstractString)`
Checks to see if a given formula has a bottle that can be installed anywhere
"""
function has_relocatable_bottle(name::AbstractString)
if !has_bottle(name)
return false
end
return json(name)["bottle"]["stable"]["cellar"] in [":any", ":any_skip_relocation"]
end
function versioninfo(;verbose=false)
InteractiveUtils.versioninfo(stdout; verbose=verbose)
run(Cmd(`git log -1 '--pretty=format:Homebrew git revision %h; last commit %cr'`; dir=joinpath(prefix())))
run(Cmd(`git log -1 '--pretty=format:homebrew/core git revision %h; last commit %cr'`; dir=joinpath(prefix(), "Library", "Taps", "homebrew", "homebrew-core")))
run(Cmd(`git log -1 '--pretty=format:staticfloat/juliadeps revision %h; last commit %cr'`; dir=joinpath(prefix(), "Library", "Taps", "staticfloat", "homebrew-juliadeps")))
installed_pkgs = list()
println("\n$(length(installed_pkgs)) total packages installed:")
println(join([x.name for x in installed_pkgs], ", "))
end
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | code | 1443 | module Homebrew
import Base: show
using Unicode, JSON, Libdl, InteractiveUtils
# Find homebrew installation prefix
const brew_prefix = abspath(joinpath(dirname(@__FILE__),"..","deps", "usr"))
const brew_exe = joinpath(brew_prefix,"bin","brew")
# Types and show() overrides, etc..
include("types.jl")
# Utilities
include("util.jl")
# The public API that uses Homebrew like a blackbox, only through the `brew` script
include("API.jl")
# The private API that peeks into the internals of Homebrew a bit
include("private_API.jl")
include("translation.jl")
# Include our own, personal bindeps integration stuff
include("bindeps_integration.jl")
"""
`__init__()`
Initialization function. Calls `install_brew()` to ensure that everything we
need is downloaded/installed, then calls `update_env()` to set the environment
properly so that packages being installed can find their binaries.
"""
function __init__()
if Sys.isapple()
# Let's see if Homebrew is installed. If not, let's do that first!
(isdir(brew_prefix) && isdir(tappath)) || install_brew()
# Update environment variables such as PATH, DL_LOAD_PATH, etc...
update_env()
else
# change this to an error in future
@warn("""
Homebrew.jl can only be used on Apple macOS. Suggested usage is
@static if Sys.isapple()
using Homebrew
# Homebrew specific code goes here
end
""")
end
end
end # module
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | code | 1258 | # This file contains the necessary ingredients to create a PackageManager for BinDeps
using BinDeps
import BinDeps: PackageManager, can_use, package_available, libdir, generate_steps, LibraryDependency, provider
import Base: show
mutable struct HB <: PackageManager
packages
end
show(io::IO, hb::HB) = write(io, "Homebrew Bottles ",
join(isa(hb.packages, AbstractString) ? [hb.packages] : hb.packages,", "))
# Only return true on Darwin platforms
can_use(::Type{HB}) = Sys.KERNEL == :Darwin
function package_available(p::HB)
!can_use(HB) && return false
pkgs = p.packages
if isa(pkgs, AbstractString)
pkgs = [pkgs]
end
# For each package, see if we can get info about it. If not, fail out
for pkg in pkgs
try
info(pkg)
catch
return false
end
end
return true
end
libdir(p::HB, dep) = joinpath(brew_prefix, "lib")
provider(::Type{HB}, packages::Vector{T}; opts...) where {T <: AbstractString} = HB(packages)
function generate_steps(dep::LibraryDependency, p::HB, opts)
pkgs = p.packages
if isa(pkgs, AbstractString)
pkgs = [pkgs]
end
()->install(pkgs)
end
function install(pkgs)
for pkg in pkgs
add(pkg)
end
end
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | code | 5426 | # This file contains all functions that either do not directly interface with `brew`
# or peek into the internals of Homebrew a bit, such as `install_brew()` which
# installs Homebrew using Git, `tap_exists()` which presupposes knowledge of the
# internal layout of Taps, and `installed()` which presupposed knowledge of the
# location of files within the Cellar
# This is the tap that contains our manually-curated overrides
const tapname = "staticfloat/juliadeps"
const tappath = joinpath(brew_prefix,"Library","Taps","staticfloat","homebrew-juliadeps")
# This is the tap that will contain our automatically-translated overrides
const auto_tapname = "staticfloat/juliatranslated"
const auto_tappath = joinpath(brew_prefix,"Library","Taps","staticfloat","homebrew-juliatranslated")
# Where we download brew from
const BREW_URL = "https://github.com/Homebrew/brew"
const BREW_BRANCH = "master"
const BREW_STABLE_SHA = "38287e6309c02272cec18fb1655145d3519f1b2f"
"""
`install_brew()`
Ensures that Homebrew is installed as desired, that our basic Taps are available
and that we have whatever binary tools we need, such as `install_name_tool`
"""
function install_brew()
# Ensure brew_prefix exists
if !isdir(brew_prefix) || !isfile(joinpath(brew_prefix,"bin","brew"))
try
mkdir(brew_prefix)
catch
end
try
@info("Downloading brew...")
run(pipeline(`curl -\# -L $BREW_URL/tarball/$BREW_BRANCH`,
`tar xz -m --strip 1 -C $brew_prefix`))
catch
@warn("Could not download/extract $BREW_URL/tarball/$BREW_BRANCH into $(brew_prefix)!")
rethrow()
end
cd(brew_prefix) do
try
git(`fetch --unshallow`)
catch
end
end
end
# Tap homebrew/core, always and forever
tap("homebrew/core")
# Tap our own "overrides" taps
tap("staticfloat/juliadeps")
tap("staticfloat/juliatranslated")
if !clt_installed() && !installed("cctools")
# If we don't have the command-line tools installed, then let's grab
# cctools, as we need that to install bottles that need relocation
add("cctools")
end
if !git_installed() && !installed("git")
# If we don't have a git available, install it now
add("git")
end
# Update the environment before running update()
update_env()
# Update immediately so that we get onto our "stable" tag
update(verbose=true)
return nothing
end
"""
`tap_exists(tap_name::AbstractString)`
Check to see if a tap called `tap_name` (ex: `"staticfloat/juliadeps"`) exists
"""
function tap_exists(tap_name::AbstractString)
path = joinpath(brew_prefix,"Library","Taps", dirname(tap_name), "homebrew-$(basename(tap_name))")
return isdir(path)
end
"""
`installed(pkg::Union{AbstractString,BrewPkg})`
Return true if the given package `pkg` is a directory in the Cellar, showing
that it has been installed (but possibly not linked, see `linked()`)
"""
function installed(pkg::StringOrPkg) end
function installed(name::AbstractString)
isdir(joinpath(brew_prefix,"Cellar",basename(name)))
end
function installed(pkg::BrewPkg)
installed(pkg.name)
end
"""
`linked(pkg::Union{AbstractString,BrewPkg})`
Returns true if the given package `pkg` is linked to LinkedKegs, signifying
all files installed by this package have been linked into the global prefix.
"""
function linked(pkg::StringOrPkg) end
function linked(name::AbstractString)
return islink(joinpath(brew_prefix,"var","homebrew","linked",basename(name)))
end
function linked(pkg::BrewPkg)
return linked(pkg.name)
end
"""
`formula_path(pkg::Union{AbstractString,BrewPkg})`
Returns the absolute path on-disk of the given package `pkg`.
"""
function formula_path(pkg::StringOrPkg) end
function formula_path(name::AbstractString)
path, tap_path = formula_tap(name)
if isempty(tap_path)
return joinpath(brew_prefix, "Library", "Taps", "homebrew", "homebrew-core", "Formula", "$path.rb")
else
# Insert the "homebrew-" that exists in all taps
tap_path = "$(dirname(tap_path))/homebrew-$(basename(tap_path))"
return joinpath(brew_prefix, "Library", "Taps", tap_path, "$path.rb")
end
end
function formula_path(pkg::BrewPkg)
return formula_path(fullname(pkg))
end
"""
`update_tag(;verbose::Bool = false)`
We maintain our own "stable" tag that overrides Homebrew so that we can
update at our own pace along with them. Make sure to call `update_env()`
before calling this, as calling our `git` doesn't work properly otherwise.
"""
function update_tag(;verbose::Bool=false)
global BREW_STABLE_SHA, brew_prefix
# If a recent enough version of git is not installed, then install our own
# This is necessary because some people do not have git installed but already
# have Homebrew installed, and the check up above during install_brew()
# doesn't run every time
if !git_installed()
add("git")
end
if verbose
git = cmd -> run(`git $cmd`)
else
git = cmd -> run(pipeline(`git $cmd`, stdout=devnull, stderr=devnull))
end
cd(brew_prefix) do
try
git(`tag -d 9.9.9`)
catch
end
git(`tag 9.9.9 $BREW_STABLE_SHA`)
git(`checkout 9.9.9`)
end
return nothing
end
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | code | 9283 | """
`read_formula(pkg::Union{AbstractString,BrewPkg})`
Returns the string contents of a package's formula.
"""
function read_formula(pkg::StringOrPkg) end
function read_formula(name::AbstractString)
return read(formula_path(name), String)
end
function read_formula(pkg::BrewPkg)
return read(formula_path(pkg), String)
end
"""
`write_formula(name::AbstractString, formula::AbstractString)`
Write out fully-qualified formula `name` with contents `formula` to disk. Note
that writing out without a tap name is not allowed; we won't write new formulae
out to `Homebrew/core`, only to taps.
"""
function write_formula(name::AbstractString, formula::AbstractString)
path, tap_path = formula_tap(name)
if isempty(tap_path)
error("Cannot write a formula out to Homebrew/core!")
end
# Insert the "homebrew-" that exists in all taps
tap_path = "$(dirname(tap_path))/homebrew-$(basename(tap_path))"
# Open this file, and write it out!
path = joinpath(brew_prefix, "Library", "Taps", tap_path, "$path.rb")
open(path, "w") do f
write(f, formula)
end
# We done!
return
end
"""
`delete_translated_formula(name::AbstractString; verbose::Bool=false)`
Delete a translated formula from the `staticfloat/juliatranslated` tap.
"""
function delete_translated_formula(name::AbstractString; verbose::Bool=false)
# Throw out the tap_path part of any formula that someone passed into here.
path, tap_path = formula_tap(name)
# Override tap_path with our auto_tapname
tap_path = "$(dirname(auto_tapname))/homebrew-$(basename(auto_tapname))"
try
del_path = joinpath(brew_prefix, "Library", "Taps", tap_path, "$path.rb")
Base.rm(del_path)
if verbose
println("Deleting $(basename(del_path))...")
end
catch
end
end
"""
`delete_all_translated_formulae(;verbose::Bool=false)`
Delete all translated formulae from the `staticfloat/juliatranslated` tap. This
is useful for debugging misbehaving formulae during translation.
"""
function delete_all_translated_formulae(;verbose::Bool=false)
for f in readdir(auto_tappath)
if endswith(f,".rb")
if verbose
println("Deleting $f...")
end
Base.rm(joinpath(auto_tappath,f))
end
end
end
"""
`translate_formula(pkg::Union{AbstractString,BrewPkg}; verbose::Bool=false)`
Given a formula `name`, return the fully-qualified name of a translated formula
if it is translatable. Translation copies a `Homebrew/core` formula to
`$auto_tapname`, adding appropriate `cellar :any` and `root_url` lines to
any bottle stanzas. This allows us to transparently install non-cellar-any
formulae from `Homebrew/core`.
This function is fairly strict, bailing out at every possible opportunity, and
returning the original name. If a formula is non-translatable, it's possible
it needs manual intervention, check out the $tapname tap for examples.
"""
function translate_formula(pkg::StringOrPkg; verbose::Bool=false) end
function translate_formula(name::AbstractString; verbose::Bool=false)
if verbose
println("translation: beginning for $name")
end
path, tap_path = formula_tap(name)
# We maintain a list of formulae that we WILL NOT translate. As an example,
# 'xz' is automatically added as a dependency by Homebrew when a formula
# has a `.tar.xz` source tarball. This cannot be redirected to the
# `staticfloat/juliatranslated` tap, causing diamonds of death where we have
# the potential for both `xz` and `staticfloat/juliatranslated/xz` to
# be in the dependency tree for a formula.
translation_blacklist = ["xz"]
if basename(name) in translation_blacklist
if verbose
println("translation: bailing because $name is in the translation blacklist")
end
return name
end
# Did we ask for any old name, or did we explicitly request a tap?
if isempty(tap_path)
# Bail if there is an overriding formula in our manually-curated tap
if isfile(joinpath(tappath, "$(name).rb"))
if verbose
println("translation: using $tapname/$name for the source of our translation")
end
tap_path = tapname
name = "$(tap_path)/$(path)"
end
else
# If we explicitly asked for a tap, then make sure it's here!
tap(tap_path)
end
# Bail if we have no bottles
if !has_bottle(name)
if verbose
println("translation: bailing because $name has no bottles")
end
return name
end
# Delete any older translated formula if they exist
auto_path = joinpath(auto_tappath, "$(path).rb")
override_name = joinpath(auto_tapname, path)
if isfile(auto_path)
src_path = formula_path(name)
if stat(auto_path).mtime < stat(src_path).mtime
if verbose
println("translation: deleting stale translation for $name")
end
delete_translated_formula(override_name; verbose=verbose)
else
if verbose
println("translation: bailing becuase $name is already available in tap $auto_tapname")
end
return joinpath(auto_tapname, path)
end
end
# Read formula source in, and also get a JSON representation of it
obj = json(name)
formula = read_formula(name)
# Find bottle section. We allow 1 to 8 lines of code in a bottle stanza:
# a root_url, a prefix, a cellar, a revision, and four OSX version bottles.
ex = r"(?:\r\n|\r|\n)\s*bottle\s+do(?:\r\n|\r|\n)(?:[^\n]*(?:\r\n|\r|\n)){1,8}\s*end\s*(?:\r\n|\r|\n)"
m = match(ex, formula)
if m === nothing
# This shouldn't happen, because we passed `has_bottle()` above
@warn("Couldn't find bottle stanza in $name")
return name
end
# We know there is no `cellar :any` or `cellar :any_skip_relocation` since
# we made it past the `has_relocatable_bottle()` check. Eliminate any
# `cellar` lines still within the match, then replace that section with a
# section that contains the `cellar :any` we rely so heavily upon.
bottle_lines = split(m.match, "\n")
# Eliminate any lines that start with "cellar" or "root_url"
bottle_lines = filter(line -> !startswith(lstrip(line), "cellar"), bottle_lines)
bottle_lines = filter(line -> !startswith(lstrip(line), "root_url"), bottle_lines)
# Find at which line the "bottle do" actually starts
bottle_idx = findfirst(line -> match(r"bottle\s+do", line) !== nothing, bottle_lines)
# Add a "cellar :any" and "root_url" line to this formula just after the
# `bottle do`. Note that since `match()` returns SubString's, we need to
# explicitly convert our string to SubString; this should be fixed in 0.6
# We should, however, preserve :any_skip_relocation if that is what this
# bottle is marked as, which includes important bottles such as `cctools`.
if occursin(":any_skip_relocation", m.match)
insert!(bottle_lines, bottle_idx+1, SubString(" cellar :any_skip_relocation",1))
else
insert!(bottle_lines, bottle_idx+1, SubString(" cellar :any",1))
end
insert!(bottle_lines, bottle_idx+1, SubString(" root_url \"$(obj["bottle"]["stable"]["root_url"])\"",1))
# Resynthesize the bottle stanza and embed it into `formula` once more
bottle_stanza = join(bottle_lines, "\n")
formula = formula[1:m.offset-1] * bottle_stanza * formula[m.offset+length(m.match):end]
# Find any depends_on lines, substitute in any translated formulae
adjustment = 0
for m in eachmatch(r"depends_on\s+\"([^ ]+)\"", formula)
# This is the path that this dependency would have if it has been translated
dep_name = m.captures[1]
auto_dep_path = joinpath(auto_tappath, "$(dep_name).rb")
# If this dependency has been translated, then prepend "staticfloat/juliatranslated"
# to it in the formula, so there is no confusion inside of Homebrew
if isfile(auto_dep_path)
if verbose
println("translation: replacing dependency $dep_name because it's been translated before")
end
new_name = "$(auto_tapname)/$(dep_name)"
offset = m.offsets[1]
start_idx = offset-1+adjustment
stop_idx = offset+length(dep_name)+adjustment
formula = formula[1:start_idx] * new_name * formula[stop_idx:end]
adjustment += length(auto_tapname) + 1
end
end
# Write our patched formula out to our override tap
write_formula(override_name, formula)
# Read that formula in again as a JSON object, compare with the original
new_obj = json(override_name)
if !has_relocatable_bottle(override_name)
@warn("New formula $override_name doesn't have a relocatable bottle despite our meddling")
return name
end
# Wow. We actually did it.
if verbose
println("translation: successfully finished for $name")
end
return override_name
end
function translate_formula(pkg::BrewPkg; verbose::Bool=false)
return translate_formula(fullname(pkg); verbose=verbose)
end
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | code | 1204 | import Base: ==
"""
`BrewPkg`
A simple type to give us some nice ways of representing our packages to the user
It contains important information such as the `name` of the package, the `tap` it
came from, the `version` of the package and whether it was `translated` or not
"""
struct BrewPkg
# The name of this particular Brew package
name::String
# The tap this brew package comes from ("Homebrew/core" in general)
tap::String
# The version of this brew package
version::String
end
function ==(x::BrewPkg, y::BrewPkg)
return x.name == y.name && x.tap == y.tap && x.version == y.version
end
"""
`fullname(pkg::BrewPkg)`
Return the fully-qualified name for a package, dropping "Homebrew/core"
"""
function fullname(pkg::BrewPkg)
if pkg.tap == "Homebrew/core"
return pkg.name
end
return joinpath(pkg.tap,pkg.name)
end
"""
`show(io::IO, b::BrewPkg)`
Writes a `BrewPkg` to `io`, showing tap, name and version number
"""
function show(io::IO, b::BrewPkg)
write(io, "$(fullname(b)): $(b.version)")
end
"""
`StringOrPkg`
A convenience type accepting either an `AbstractString` or a `BrewPkg`
"""
const StringOrPkg = Union{AbstractString, BrewPkg}
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | code | 4517 | # This file contains various utility functions that don't belong anywhere else
"""
`update_env()`
Updates environment variables PATH and HOMEBREW_CACHE, and modifies DL_LOAD_PATH
to point to our Homebrew installation, allowing us to use things inside of
Homebrew transparently. This causes BinDeps to find the binaries during
Pkg.build() time, writing the absolute path into `deps/deps.jl`. Because the
paths are written into `deps/deps.jl`, packages do not need to load in the entire
Homebrew package just to find their dependencies.
HOMEBREW_CACHE stores our bottle download cache in a separate place, separating
ourselves from other Homebrew installations so we don't conflict with anyone
"""
function update_env()
if findfirst(joinpath(brew_prefix, "bin"), ENV["PATH"]) == nothing
ENV["PATH"] = "$(abspath(joinpath(brew_prefix, "bin"))):$(abspath(joinpath(brew_prefix, "sbin"))):$(ENV["PATH"])"
end
if !(joinpath(brew_prefix,"lib") in Libdl.DL_LOAD_PATH)
push!(Libdl.DL_LOAD_PATH, joinpath(brew_prefix, "lib") )
end
# We need to set our own, private, cache directory so that we don't conflict with
# user-maintained Homebrew installations, and multiple users can use it at once
ENV["HOMEBREW_CACHE"] = joinpath(ENV["HOME"],"Library/Caches/Homebrew.jl/")
# We invoke `brew` a lot, let's disable automatic updates since we do those explicitly
ENV["HOMEBREW_NO_AUTO_UPDATE"] = "1"
# We opt out of analytics by default
if !("HOMEBREW_NO_ANALYTICS" in keys(ENV))
ENV["HOMEBREW_NO_ANALYTICS"] = "1"
end
# If we have `git` installed from Homebrew, add its environment variables
if isfile(joinpath(brew_prefix,"bin","git"))
git_core = joinpath(brew_prefix,"opt","git","libexec","git-core")
ENV["PATH"] = ENV["PATH"] * ":" * git_core
ENV["HOMEBREW_NO_ENV_FILTERING"] = "1"
ENV["GIT_EXEC_PATH"] = git_core
ENV["GIT_TEMPLATE_DIR"] = joinpath(brew_prefix,"opt","git","share","git-core")
end
return
end
"""
`add_flags(cmd::AbstractString, flags::Dict{String,Bool})`
Given a mapping of flags to Bools, return [cmd, flag1, flag2...] if the
respective Bools are true. Useful for adding `--verbose` and `--force` flags
onto the end of commands
"""
function add_flags(cmd::Cmd, flags::Dict{Cmd,Bool})
for flag in keys(flags)
if flags[flag]
cmd = `$cmd $flag`
end
end
return cmd
end
"""
`download_and_unpack(url::AbstractString, target_dir::AbstractString)`
Download a tarball from `url` and unpack it into `target_dir`.
"""
function download_and_unpack(url::AbstractString, target_dir::AbstractString; strip=0)
run(pipeline(`curl -\# -L $url`,
`tar xz -m --strip 1 -C $target_dir`))
end
"""
`clt_installed()`
Checks whether the command-line tools are installed, as reported by xcode-select
"""
function clt_installed()
try
!isempty(readchomp(pipeline(`/usr/bin/xcode-select -print-path`, stderr=devnull)))
catch
return false
end
end
"""
`git_installed()`
Checks whether `git` is truly installed or not, dealing with stubs in /usr/bin
Also ensure that the version is new enough (e.g. >= 2.0.0.0) that it will work
with `git fetch --unshallow` on Homebrew.
"""
function git_installed()
gitpath = readchomp(`which git`)
# If there is no `git` executable at all, fail
if isempty(gitpath)
return false
end
# If we have a git from the CLT location, but the CLT isn't installed, fail
if gitpath == "/usr/bin/git" && !clt_installed()
return false
end
# check that the git version is at least 2.0.0.0. We may end up
# tightening these bounds a little bit in the future, so parse
# out the full git version
m = match(r"^git version ([\d\.]+) ", readchomp(`git --version`))
if m === nothing
return false
end
gitver = [parse(Int64, x) for x in split(m.captures[1], ".")]
if gitver[1] < 2
return false
end
# If we made it through the gauntlet, succeed!
return true
end
"""
`formula_tap(name::AbstractString)`
Given a formula `name`, return the formula name and the tap it is from, replacing
"" for "Homebrew/core", as we don't care about that particular prefix.
"""
function formula_tap(name::AbstractString)
tap_path = dirname(name)
if isempty(tap_path) || lowercase(tap_path) == "homebrew/core"
return basename(name), ""
end
return basename(name), tap_path
end
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | code | 5512 | using Homebrew
using Test
# Print some debugging info
@info("Using Homebrew.jl installed to $(Homebrew.prefix())")
# Restore pkg-config to its installed (or non-installed) state at the end of all of this
pkg_was_installed = Homebrew.installed("pkg-config")
libgfortran_was_installed = Homebrew.installed("staticfloat/juliadeps/libgfortran")
if pkg_was_installed
@info("Removing pkg-config for our testing...")
Homebrew.rm("pkg-config")
end
# Add pkg-config
Homebrew.add("pkg-config")
@test Homebrew.installed("pkg-config") == true
# Print versioninfo() to boost coverage
Homebrew.versioninfo()
# Now show that we have it and that it's the right version
function strip_underscores(str)
range = something(findlast("_", str), 0:0)
if range.start > 1
return str[1:range.start-1]
else
return str
end
end
pkgconfig = Homebrew.info("pkg-config")
version = readchomp(`pkg-config --version`)
@test version == strip_underscores(pkgconfig.version)
@test Homebrew.installed(pkgconfig) == true
@info("$(pkgconfig) installed to: $(Homebrew.prefix(pkgconfig))")
@test isdir(Homebrew.prefix("pkg-config"))
@test isdir(Homebrew.prefix(pkgconfig))
# Run through some of the Homebrew API, both with strings and with BrewPkg objects
@test length(filter(x -> x.name == "pkg-config", Homebrew.list())) > 0
@test Homebrew.linked("pkg-config") == true
@test Homebrew.linked(pkgconfig) == true
# Test dependency inspection
@test Homebrew.direct_deps("pkg-config") == []
@test Homebrew.direct_deps(pkgconfig) == []
@test Homebrew.direct_deps("nettle") == [Homebrew.info("gmp")]
@test Homebrew.direct_deps(Homebrew.info("nettle")) == [Homebrew.info("gmp")]
# Run through our sorted deps routines, ensuring that everything is sorted
sortdeps = Homebrew.deps_sorted("pango")
for idx in 1:length(sortdeps)
for dep in Homebrew.direct_deps(sortdeps[idx])
depidx = findfirst(x -> (x.name == dep.name), sortdeps)
@test depidx != 0
@test depidx < idx
end
end
# Test that we can probe for bottles properly
@test Homebrew.has_bottle("ack") == false
@test Homebrew.has_bottle("cairo") == true
# I will be a very happy man the day this test starts to fail
@test Homebrew.has_relocatable_bottle("cairo") == false
if Homebrew.has_bottle("staticfloat/juliadeps/libgfortran")
@test Homebrew.has_relocatable_bottle("staticfloat/juliadeps/libgfortran") == true
end
@test Homebrew.json(pkgconfig)["name"] == "pkg-config"
# Test that has_bottle knows which OSX version we're running on.
@test Homebrew.has_bottle("ld64") == false
# Test that we can translate properly
@info("Translation should pass:")
@test Homebrew.translate_formula("gettext"; verbose=true) == "staticfloat/juliatranslated/gettext"
@info("Translation should fail because it has no bottles:")
@test Homebrew.translate_formula("ack"; verbose=true) == "ack"
if libgfortran_was_installed
# Remove libgfortran before we start messing around with it
Homebrew.rm("staticfloat/juliadeps/libgfortran"; force=true)
end
# Make sure translation works properly with other taps
Homebrew.delete_translated_formula("staticfloat/juliadeps/libgfortran"; verbose=true)
@info("Translation should pass because we just deleted libgfortran from translation cache:")
@test Homebrew.translate_formula("staticfloat/juliadeps/libgfortran"; verbose=true) == "staticfloat/juliatranslated/libgfortran"
@info("Translation should fail because libgfortran has already been translated:")
# Do it a second time so we can get coverage of practicing that particular method of bailing out
Homebrew.translate_formula(Homebrew.info("staticfloat/juliadeps/libgfortran"); verbose=true)
# Test that installation of a formula from a tap when it's already been translated works
Homebrew.add("staticfloat/juliadeps/libgfortran"; verbose=true)
if !libgfortran_was_installed
Homebrew.rm("staticfloat/juliadeps/libgfortran")
end
# Now that we have staticfloat/juliadeps tapped, test to make sure that prefix() works
# with taps properly:
@test Homebrew.prefix("libgfortran") == Homebrew.prefix("staticfloat/juliadeps/libgfortran")
# Test more miscellaneous things
fontconfig = Homebrew.info("staticfloat/juliadeps/fontconfig")
@test Homebrew.formula_path(fontconfig) == joinpath(Homebrew.tappath, "fontconfig.rb")
@test !isempty(Homebrew.read_formula("xz"))
@test !isempty(Homebrew.read_formula(fontconfig))
@info("add() should fail because this actually isn't a package name:")
@test_throws ArgumentError Homebrew.add("thisisntapackagename")
Homebrew.unlink(pkgconfig)
@test Homebrew.installed(pkgconfig) == true
@test Homebrew.linked(pkgconfig) == false
Homebrew.link(pkgconfig)
@test Homebrew.installed(pkgconfig) == true
@test Homebrew.linked(pkgconfig) == true
# Can't really do anything useful with these, but can at least run them to ensure they work
Homebrew.outdated()
Homebrew.update()
Homebrew.postinstall("pkg-config")
Homebrew.postinstall(pkgconfig)
Homebrew.delete_translated_formula("gettext"; verbose=true)
Homebrew.delete_all_translated_formulae(verbose=true)
# Test deletion as well, showing that the array-argument form continues on after errors
Homebrew.rm(pkgconfig)
Homebrew.add(pkgconfig)
@info("rm() should fail because this isn't actually a package name:")
Homebrew.rm(["thisisntapackagename", "pkg-config"])
@test Homebrew.installed("pkg-config") == false
@test Homebrew.linked("pkg-config") == false
if pkg_was_installed
@info("Adding pkg-config back again...")
Homebrew.add("pkg-config")
end
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | docs | 7478 | # Homebrew.jl (OSX only)
[](https://travis-ci.org/JuliaPackaging/Homebrew.jl)
Homebrew.jl sets up a [homebrew](http://brew.sh) installation inside your [Julia](http://julialang.org/) package directory. It uses Homebrew to provide specialized binary packages to satisfy dependencies for other Julia packages, without the need for a compiler or other development tools; it is completely self-sufficient.
Package authors with dependencies that want binaries distributed in this manner should open an issue here for inclusion into the package database.
NOTE: If you have MacPorts installed, and are seeing issues with `git` or `curl` complaining about certificates, try to update the the ```curl``` and ```curl-ca-bundle``` packages before using Homebrew.jl. From the terminal, run:
```
port selfupdate
port upgrade curl curl-ca-bundle
```
# Usage (Users)
As a user, you ideally shouldn't ever have to use Homebrew directly, short of installing it via `Pkg.add("Homebrew")`. However, there is a simple to use interface for interacting with the Homebrew package manager:
* `Homebrew.add("pkg")` will install `pkg`, note that if you want to install a package from a non-default tap, you can do so via `Homebrew.add("user/tap/formula")`. An example of this is installing the `metis4` formula from the [`Homebrew/science` tap](https://github.com/Homebrew/homebrew-science) via `Homebrew.add("homebrew/science/metis4")`.
* `Homebrew.rm("pkg")` will uninstall `pkg`
* `Homebrew.update()` will update the available formulae for installation and upgrade installed packages if a newer version is available
* `Homebrew.list()` will list all installed packages and versions
* `Homebrew.installed("pkg")` will return a `Bool` denoting whether or not `pkg` is installed
* `Homebrew.prefix()` will return the prefix that all packages are installed to
# Usage (Package Authors)
As a package author, the first thing to do is to [write](https://github.com/Homebrew/brew/blob/master/share/doc/homebrew/Formula-Cookbook.md)/[find](http://braumeister.org/) a Homebrew formula for whatever package you wish to create. The easiest way to tell if the binary will work out-of-the-box is `Homebrew.add()` it. Formulae from the default `homebrew/core` tap need no prefix, but if you are installing something from another tap, you need to prefix it with the appropriate tap name. For example, to install `metis4` from the `homebrew/science` tap, you would run `Homebrew.add("homebrew/science/metis4")`. Programs installed to `<prefix>/bin` and libraries installed to `<prefix>/lib` will automatically be availble for `run()`'ing and `dlopen()`'ing.
If that doesn't "just work", there may be some special considerations necessary for your piece of software. Open an issue here with a link to your formula and we will discuss what the best approach for your software is. To see examples of formulae we have already included for special usage, peruse the [homebrew-juliadeps](https://github.com/staticfloat/homebrew-juliadeps) repository.
To have your Julia package automatically install these precompiled binaries, `Homebrew.jl` offers a BinDeps provider which can be accessed as `Homebrew.HB`. Simply declare your dependency on `Homebrew.jl` via a `@osx Homebrew` in your REQUIRE files, create a BinDeps `library_dependency` and state that `Homebrew` provides that dependency:
```julia
using BinDeps
@BinDeps.setup
nettle = library_dependency("nettle", aliases = ["libnettle","libnettle-4-6"])
...
# Wrap in @osx_only to avoid non-OSX users from erroring out
@osx_only begin
using Homebrew
provides( Homebrew.HB, "nettle", nettle, os = :Darwin )
end
@BinDeps.install Dict(:nettle => :nettle)
```
Then, the `Homebrew` package will automatically download the requisite bottles for any dependencies you state it can provide. This example garnered from the `build.jl` file from [`Nettle.jl` package](https://github.com/staticfloat/Nettle.jl/blob/master/deps/build.jl).
## Why Package Authors should use Homebrew.jl
A common question is why bother with Homebrew formulae and such when a package author could simply compile the `.dylib`'s needed by their package, upload them somewhere and download them to a user's installation somewhere. There are multiple reasons, and although they are individually surmountable Homebrew offers a simpler (and standardized) method of solving many of these problems automatically:
* On OSX shared libraries link via full paths. This means that unless you manually alter the path inside of a `.dylib` or binary to have an `@rpath` or `@executable_path` in it, the path will be attempting to point to the exact location on your harddrive that the shared library was found at compile-time. This is not an issue if all libraries linked to are standard system libraries, however as soon as you wish to link to a library in a non-standard location you must alter the paths. Homebrew does this for you automatically, rewriting the paths during installation via `install_name_tool`. To see the paths embedded in your libraries and executable files, run `otool -L <file>`.
* Dependencies on other libraries are handled gracefully by Homebrew. If your package requires some heavy-weight library such as `cairo`, `glib`, etc... Homebrew already has those libraries ready to be installed for you.
* Releasing new versions of binaries can be difficult. Homebrew.jl has builtin mechanisms for upgrading all old packages, and even detecting when a binary of the same version number has a new revision (e.g. if an old binary had an error embedded inside it).
## Why doesn't this package use my system-wide Homebrew installation?
Some of the formulae in the [staticfloat/juliadeps tap](https://github.com/staticfloat/homebrew-juliadeps) are specifically patched to work with Julia. Some of these patches have not (or will not) be merged back into Homebrew mainline, so we don't want to conflict with any packages the user may or may not have installed.
Users can modify Homebrew's internal workings, so it's better to have a known good Homebrew installation than to risk bug reports from users that have unknowingly merged patches into Homebrew that break functionality we require.
If you already have something installed, and it is usable, (e.g. `BinDeps` can load it and it passes any quick internal tests the Package authors have defined) then `Homebrew.jl` won't try to install it. `BinDeps` always checks to see if there is a library in the current load path that satisfies the requirements setup by package authors, and if there is, it doesn't build anything.
## Advanced usage
`Homebrew.jl` provides a convenient wrapper around most of the functionality of Homebrew, however there are rare cases where access to the full suite of `brew` commands is necessary. To facilitate this, users that are familiar with the `brew` command set can use `Homebrew.brew()` to directly feed commands to the `brew` binary within `Homebrew.jl`. Example usage:
```
julia> using Homebrew
julia> Homebrew.brew(`info staticfloat/juliadeps/libgfortran`)
staticfloat/juliadeps/libgfortran: stable 6.2 (bottled)
http://gcc.gnu.org/wiki/GFortran
/Users/sabae/.julia/v0.5/Homebrew/deps/usr/Cellar/libgfortran/6.2 (9 files, 2M) *
Poured from bottle on 2016-11-21 at 13:14:33
From: https://github.com/staticfloat/homebrew-juliadeps/blob/master/libgfortran.rb
==> Dependencies
Build: gcc ✘
```
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | docs | 248 | When opening an issue, please ping `@staticfloat`.
He does not receive emails automatically when new issues are created.
Without this ping, your issue may slip through the cracks!
If no response is garnered within a week, feel free to ping again.
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.7.1 | f01fb2f34675f9839d55ba7238bab63ebd2e531e | docs | 248 | When opening an issue, please ping `@staticfloat`.
He does not receive emails automatically when new issues are created.
Without this ping, your issue may slip through the cracks!
If no response is garnered within a week, feel free to ping again.
| Homebrew | https://github.com/JuliaPackaging/Homebrew.jl.git |
|
[
"MIT"
] | 0.3.2 | add78dc1de6ffcf80f4fc350cf38794ad257690c | code | 2696 | module NaturallyUnitful
using Reexport
@reexport using Unitful
export natural, unnatural
const c = 1u"c"
const ħ = Unitful.ħ
const ħc = ħ*c
const kB = Unitful.k
const ϵ0 = Unitful.ϵ0
setDimPow(D::Dict, x::Unitful.Dimension{T}) where {T} = D[T] = x.power
function dimDict(x::Unitful.Dimensions{T}) where {T}
D = Dict{Symbol, Rational}(:Length => 0,
:Mass => 0,
:Temperature => 0,
:Time => 0,
:Current => 0)
for t in T
setDimPow(D,t)
end
return D
end
dimDict(x::Unitful.Quantity{T}) where {T} = dimDict(dimension(x))
dimDict(x) = Dict{Symbol, Rational}(:Length => 0, :Mass => 0, :Temperature => 0, :Time => 0, :Current => 0)
gettypeparams(::Unitful.FreeUnits{T, U, V}) where {T, U, V} = T, U, V
const energydimension = gettypeparams(u"GeV")[2]
"""
natural(q; base=u"eV")
Convert `q` to natural units based on the units specified by `base`. If `base` is
unspecified, `natural` will default to `eV`. Currently, `natural` only supports
`base`s with dimensions of energy. For all other `base` you will need to use `unnatrual` '
to convert.
Examples:
julia> natural(1u"kg")
5.609588650020686e35 eV
julia> natural(1u"kg", base=u"GeV")
5.609588650020685e26 GeV
julia> natural(1u"m")
5.067730759202785e6 eV^-1
julia> natural(1u"m", base=u"GeV")
5.067730759202785e15 GeV^-1
"""
natural(q; base=u"eV") = _natural(base, q)
function _natural(base::Unitful.FreeUnits{T, energydimension, U}, q) where {T, U}
D = dimDict(q)
(α,β,γ,δ,ϕ) = (D[:Length], D[:Mass], D[:Temperature], D[:Time], D[:Current])
uconvert(base^(-α-δ+β+γ+ϕ),
q*ħc^(-α+ϕ/2)*ħ^(-δ)*c^(2(β-ϕ/2))*kB^(γ)*(4π*ϵ0)^(-ϕ/2))
end
function _natural(base::Unitful.FreeUnits{T, U, V}, q) where {T, U, V}
throw("""natural(q; base)` where `base` has dimensions `$U` has not yet been implemented. Please use a base with dimensions of `energy` and then use `unnatural` to convert to your desired units.""")
end
"""
unnatural(targetUnit, q)
Convert a quantity `q` to units specified by `targetUnits` automatically inserting whatever
factors of `ħ`, `c`, `ϵ₀` and `kb` are required to make the conversion work.
Examples:
julia> unnatural(u"m", 5.067730759202785e6u"eV^-1")
1.0 m
julia> unnatural(u"m/s", 1)
2.99792458e8 m s^-1
julia> unnatural(u"K", 1u"eV")
11604.522060401006 K
"""
function unnatural(targetUnit, q)
natTarget = natural(1targetUnit)
natQ = natural(q)
ratio = natQ/natTarget
if typeof(ratio |> dimension) == Unitful.Dimensions{()}
(ratio)targetUnit
else
throw(Unitful.DimensionError)
end
end
end # module
| NaturallyUnitful | https://github.com/MasonProtter/NaturallyUnitful.jl.git |
|
[
"MIT"
] | 0.3.2 | add78dc1de6ffcf80f4fc350cf38794ad257690c | code | 635 | using Test, NaturallyUnitful
using NaturallyUnitful: c, ħ, ħc, kB, ϵ0
@testset "tests" begin
@test natural(1u"m") ≈ uconvert(u"eV^-1", 1u"m"/(ħc))
@test unnatural(u"m", uconvert(u"eV^-1", 1u"m"/(ħc))) ≈ 1.0u"m"
@test natural(1e8u"m/s") ≈ convert(Float64, 1e8u"m/s"/c)
@test unnatural(u"m/s", convert(Float64, 1e8u"m/s"/c)) ≈ 1e8u"m/s"
@test natural(1u"kg") ≈ uconvert(u"GeV", 1u"kg"*c^2)
@test natural(1u"m", base=u"GeV") ≈ uconvert(u"GeV^-1", 1u"m"/(ħc))
@test unnatural(u"K", 1u"eV") ≈ uconvert(u"K", 1u"eV"/kB)
@test unnatural(u"(m/s)^(3/2)", 1) ≈ uconvert(u"(m/s)^(3/2)", c^(3/2))
end
| NaturallyUnitful | https://github.com/MasonProtter/NaturallyUnitful.jl.git |
|
[
"MIT"
] | 0.3.2 | add78dc1de6ffcf80f4fc350cf38794ad257690c | docs | 1358 | [](https://github.com/MasonProtter/NaturallyUnitful.jl/actions/workflows/ci.yml)
# NaturallyUnitful.jl
This package reexports [Unitful.jl](https://github.com/ajkeller34/Unitful.jl) alongside two extra functions:
1. `natural`, a function for converting a given quantity to the Physicist's so-called
"[natural units](https://en.wikipedia.org/wiki/Natural_units)", in which
`ħ = c = ϵ₀ = kb = 1`
```julia
julia> using NaturallyUnitful
julia> natural(1u"m")
5.067730759202785e6 eV^-1
julia> natural(3e8u"m/s")
1.000692285594456
```
`natural` also accepts a keyword argument `base` (defaults to electron volts) which determines what unit
your natural quantity is constructed from. Currently, the `base` unit must have dimensions of energy.
```julia
julia> natural(1u"m", base=u"GeV")
5.067730759202785e15 GeV^-1
```
2. `unnatural`, a function for converting from natural units to a given `unnatural` unit such as meters
```julia
julia> unnatural(u"m", 5.067730759202785e6u"eV^-1")
1.0 m
julia> unnatural(u"m/s", 1)
2.99792458e8 m s^-1
```
## Installation Instructions
To install, simply open the `pkg` prompt from the julia REPL by pressing `]`, and type:
```
pkg> add NaturallyUnitful
```
| NaturallyUnitful | https://github.com/MasonProtter/NaturallyUnitful.jl.git |
|
[
"MIT"
] | 0.5.4 | 62176f36b39144429a567d71ab98c72ee4617579 | code | 772 | using TuringBenchmarking
using Documenter
DocMeta.setdocmeta!(TuringBenchmarking, :DocTestSetup, :(using TuringBenchmarking); recursive=true)
makedocs(;
modules=[TuringBenchmarking],
authors="Tor Erlend Fjelde <[email protected]> and contributors",
repo="https://github.com/TuringLang/TuringBenchmarking.jl/blob/{commit}{path}#{line}",
sitename="TuringBenchmarking.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://turinglang.org/TuringBenchmarking.jl",
edit_link="main",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/TuringLang/TuringBenchmarking.jl",
devbranch="main",
push_preview=true,
)
| TuringBenchmarking | https://github.com/TuringLang/TuringBenchmarking.jl.git |
|
[
"MIT"
] | 0.5.4 | 62176f36b39144429a567d71ab98c72ee4617579 | code | 2582 | using TuringBenchmarking,
BridgeStan,
BenchmarkTools,
Turing,
Zygote,
ReverseDiff,
ForwardDiff,
JSON
### Setup ###
function sim(I, P)
yvec = Vector{Int}(undef, I * P)
ivec = similar(yvec)
pvec = similar(yvec)
beta = rand(Normal(), I)
theta = rand(Normal(), P)
n = 0
for i in 1:I, p in 1:P
n += 1
ivec[n] = i
pvec[n] = p
yvec[n] = rand(BernoulliLogit(theta[p] - beta[i]))
end
return yvec, ivec, pvec, theta, beta
end
P = 1000
y, i, p, _, _ = sim(20, P);
### Turing ###
# naive implementation
@model function irt_naive(y, i, p; I = maximum(i), P = maximum(p))
theta ~ filldist(Normal(), P)
beta ~ filldist(Normal(), I)
for n in eachindex(y)
y[n] ~ Bernoulli(logistic(theta[p[n]] - beta[i[n]]))
end
end
# performant model
function bernoulli_logit_logpdf(y, theta, beta)
return logpdf(BernoulliLogit(theta - beta), y)
end
@model function irt(y, i, p; I = maximum(i), P = maximum(p))
theta ~ filldist(Normal(), P)
beta ~ filldist(Normal(), I)
Turing.@addlogprob! sum(bernoulli_logit_logpdf.(y, theta[p], beta[i]))
return (; theta, beta)
end
# Instantiate
model = irt(y, i, p);
# Make the benchmark suite.
suite = TuringBenchmarking.make_turing_suite(
model,
adbackends = [
TuringBenchmarking.ForwardDiffAD{40}(),
TuringBenchmarking.ReverseDiffAD{true}(),
TuringBenchmarking.ReverseDiffAD{false}()
]
);
# Run suite!
@info "Turing.jl" run(suite)
### Stan ###
@info "Compiling Stan model..."
# Tell `TuringBenchmarking` how to convert `model` into data consumable by Stan.
function TuringBenchmarking.extract_stan_data(model::DynamicPPL.Model{typeof(irt)})
args = Dict(zip(string.(keys(model.args)), values(model.args)))
kwargs = Dict(zip(string.(keys(model.defaults)), values(model.defaults)))
kwargs["N"] = kwargs["I"] * kwargs["P"]
return JSON.json(merge(args, kwargs))
end
# Tell `TuringBenchmarking` about the corresponding Stan model.
TuringBenchmarking.stan_model_string(model::DynamicPPL.Model{typeof(irt)}) = """
data {
int<lower=1> I;
int<lower=1> P;
int<lower=1> N;
int<lower=1, upper=I> i[N];
int<lower=1, upper=P> p[N];
int<lower=0, upper=1> y[N];
}
parameters {
vector[I] beta;
vector[P] theta;
}
model {
theta ~ std_normal();
beta ~ std_normal();
y ~ bernoulli_logit(theta[p] - beta[i]);
}
"""
# Construct benchmark suite.
stan_suite = TuringBenchmarking.make_stan_suite(model)
# Run suite!
@info "Stan" run(stan_suite)
| TuringBenchmarking | https://github.com/TuringLang/TuringBenchmarking.jl.git |
|
[
"MIT"
] | 0.5.4 | 62176f36b39144429a567d71ab98c72ee4617579 | code | 2229 | module TuringBenchmarkingBridgeStanExt
if isdefined(Base, :get_extension)
using TuringBenchmarking: TuringBenchmarking, BenchmarkTools
using BridgeStan: BridgeStan
else
using ..TuringBenchmarking: TuringBenchmarking, BenchmarkTools
using ..BridgeStan: BridgeStan
end
function stan_model_to_file_maybe(x::AbstractString)
endswith(x, ".stan") && return x
# Write to a temporary file.
tmpfile = tempname() * ".stan"
open(tmpfile, "w") do io
write(io, x)
end
return tmpfile
end
"""
make_stan_suite(model::Turing.Model; kwargs...)
Create default benchmark suite for the Stan model corresponding to `model`.
# Arguments
- `model`: The model to benchmark.
# Keyword arguments
- `θ`: The parameters to evaluate the model at. If `nothing`, then the parameters are
randomly initialized.
- `model_string`: The Stan model string. If `nothing`, the model is obtained
by calling `stan_model_string(model)`. This can either be a string representing
the model or a path to a file ending in `.stan`.
- `kwargs...`: Additional keyword arguments to pass to `BridgeStan.StanModel`.
"""
function TuringBenchmarking.make_stan_suite(
model::TuringBenchmarking.DynamicPPL.Model;
θ = nothing,
model_string = nothing,
kwargs...
)
if isnothing(model_string)
model_string = TuringBenchmarking.stan_model_string(model)
end
# Convert the data/observations into something consumable by the Stan model.
data = TuringBenchmarking.extract_stan_data(model)
stan_model = BridgeStan.StanModel(
stan_file = stan_model_to_file_maybe(model_string),
data = data,
kwargs...
)
# Initialize from chain if parameters have not been provided.
ϕ = if isnothing(θ)
rand(BridgeStan.param_num(stan_model))
else
BridgeStan.param_unconstrain(stan_model, θ)
end
# Create suite.
stan_suite = BenchmarkTools.BenchmarkGroup()
stan_suite["evaluation"] = BenchmarkTools.@benchmarkable $(BridgeStan.log_density)(
$stan_model, $ϕ
)
stan_suite["gradient"] = BenchmarkTools.@benchmarkable $(BridgeStan.log_density_gradient)(
$stan_model, $ϕ
)
return stan_suite
end
end
| TuringBenchmarking | https://github.com/TuringLang/TuringBenchmarking.jl.git |
|
[
"MIT"
] | 0.5.4 | 62176f36b39144429a567d71ab98c72ee4617579 | code | 12328 | module TuringBenchmarking
using LinearAlgebra
using BenchmarkTools
using LogDensityProblems
using LogDensityProblemsAD
using DynamicPPL
using ADTypes
using PrettyTables: PrettyTables
using AbstractMCMC: AbstractMCMC
using DynamicPPL: DynamicPPL
# Load some the default backends to trigger conditional loading.
using ForwardDiff: ForwardDiff
using ReverseDiff: ReverseDiff
using Zygote: Zygote
if !isdefined(Base, :get_extension)
using Requires
end
export benchmark_model, make_turing_suite, BenchmarkTools, @tagged
# Don't include `TrackerAD` because it's never going to win.
const DEFAULT_ADBACKENDS = [
AutoForwardDiff(chunksize=0),
AutoReverseDiff(compile=false),
AutoReverseDiff(compile=true),
AutoZygote(),
]
backend_label(x) = "$x"
backend_label(::AutoForwardDiff) = "ForwardDiff"
function backend_label(ad::AutoReverseDiff)
"ReverseDiff" * (ad.compile ? " [compiled]" : "")
end
backend_label(::AutoZygote) = "Zygote"
backend_label(::AutoTracker) = "Tracker"
backend_label(::AutoEnzyme) = "Enzyme"
const SYMBOL_TO_BACKEND = Dict(
:forwarddiff => AutoForwardDiff(chunksize=0),
:reversediff => AutoReverseDiff(compile=false),
:reversediff_compiled => AutoReverseDiff(compile=true),
:zygote => AutoZygote(),
:tracker => AutoTracker(),
)
to_backend(x) = error("Unknown backend: $x")
to_backend(x::ADTypes.AbstractADType) = x
function to_backend(x::Union{AbstractString,Symbol})
k = Symbol(lowercase(string(x)))
haskey(SYMBOL_TO_BACKEND, k) || error("Unknown backend: $x")
return SYMBOL_TO_BACKEND[k]
end
_default_params(model, varinfo) = rand(Vector, model)
_default_params_linked(model, varinfo) = randn(length(DynamicPPL.link(varinfo, model)[:]))
"""
benchmark_model(model::Turing.Model; suite_kwargs..., kwargs...)
Create and run a benchmark suite for `model`.
The benchmarking suite will be created using [`make_turing_suite`](@ref).
See [`make_turing_suite`](@ref) for the available keyword arguments and more information.
# Keyword arguments
- `suite_kwargs`: Keyword arguments passed to [`make_turing_suite`](@ref).
- `kwargs`: Keyword arguments passed to `BenchmarkTools.run`.
"""
function benchmark_model(
model::DynamicPPL.Model;
adbackends = DEFAULT_ADBACKENDS,
run_once::Bool = true,
check::Bool = false,
check_grads::Bool = check,
error_on_failed_check::Bool = false,
error_on_failed_backend::Bool = false,
varinfo::DynamicPPL.AbstractVarInfo = DynamicPPL.VarInfo(model),
sampler::Union{AbstractMCMC.AbstractSampler,Nothing} = nothing,
context::DynamicPPL.AbstractContext = DynamicPPL.DefaultContext(),
θ::AbstractVector = _default_params(model, varinfo),
θ_linked::AbstractVector = _default_params_linked(model, varinfo),
atol::Real = 1e-6,
rtol::Real = 0,
kwargs...
)
suite = make_turing_suite(
model;
adbackends,
run_once,
check,
check_grads,
error_on_failed_check,
error_on_failed_backend,
varinfo,
sampler,
context,
atol,
rtol,
)
return run(suite; kwargs...)
end
"""
make_turing_suite(model::Turing.Model; kwargs...)
Create default benchmark suite for `model`.
# Keyword arguments
- `adbackends`: a collection of adbackends to use, specified either as a type from
ADTypes.jl or using a `Symbol`. Defaults to `$(DEFAULT_ADBACKENDS)`.
- `run_once=true`: if `true`, the body of each benchmark will be run once to avoid
compilation to be included in the timings (this may occur if compilation runs
longer than the allowed time limit).
- `check=false`: if `true`, the log-density evaluations and the gradients
will be compared against each other to ensure that they are consistent.
Note that this will force `run_once=true`.
- `error_on_failed_check=false`: if `true`, an error will be thrown if the
check fails rather than just printing a warning, as is done by default.
- `error_on_failed_backend=false`: if `true`, an error will be thrown if the
evaluation of the log-density or the gradient fails for any of the backends
rather than just printing a warning, as is done by default.
- `varinfo`: the `VarInfo` to use. Defaults to `DynamicPPL.VarInfo(model)`.
- `sampler`: the `Sampler` to use. Defaults to `nothing` (i.e. no sampler).
- `context`: the `Context` to use. Defaults to `DynamicPPL.DefaultContext()`.
- `θ`: the parameters to use. Defaults to `rand(Vector, model)`.
- `θ_linked`: the linked parameters to use. Defaults to `randn(d)` where `d`
is the length of the linked parameters..
- `atol`: the absolute tolerance to use for comparisons.
- `rtol`: the relative tolerance to use for comparisons.
# Notes
- A separate "parameter" instance (`DynamicPPL.VarInfo`) will be created for _each test_.
Hence if you have a particularly large model, you might want to only pass one `adbackend`
at the time.
"""
function make_turing_suite(
model::DynamicPPL.Model;
adbackends = DEFAULT_ADBACKENDS,
run_once::Bool = true,
check::Bool = false,
check_grads::Bool = check,
error_on_failed_check::Bool = false,
error_on_failed_backend::Bool = false,
varinfo::DynamicPPL.AbstractVarInfo = DynamicPPL.VarInfo(model),
sampler::Union{AbstractMCMC.AbstractSampler,Nothing} = nothing,
context::DynamicPPL.AbstractContext = DynamicPPL.DefaultContext(),
θ::AbstractVector = _default_params(model, varinfo),
θ_linked::AbstractVector = _default_params_linked(model, varinfo),
atol::Real = 1e-6,
rtol::Real = 0,
)
if check != check_grads
Base.depwarn(
"The `check_grads` keyword argument is deprecated. Use `check` instead.",
:make_turing_suite
)
check = check_grads
end
grads_and_vals = Dict(:standard => Dict(), :linked => Dict())
adbackends = map(to_backend, adbackends)
suite = BenchmarkGroup()
suite_evaluation = BenchmarkGroup()
suite_gradient = BenchmarkGroup()
suite["evaluation"] = suite_evaluation
suite["gradient"] = suite_gradient
indexer = sampler === nothing ? Colon() : sampler
if sampler !== nothing
context = DynamicPPL.SamplingContext(sampler, context)
end
for adbackend in adbackends
suite_backend = BenchmarkGroup([backend_label(adbackend)])
suite_gradient["$(adbackend)"] = suite_backend
suite_backend["standard"] = BenchmarkGroup()
suite_backend["linked"] = BenchmarkGroup()
# We construct `LogDensityFunction` using different values
# than the ones we're going to use for the test. Some of the AD backends
# compiles the tape upon `ADgradient` construction, and so we want to
# check that the compiled tape is also correct on inputs which it wasn't
# compiled for.
varinfo_current = DynamicPPL.unflatten(varinfo, context, varinfo[indexer])
f = LogDensityProblemsAD.ADgradient(
adbackend,
DynamicPPL.LogDensityFunction(varinfo_current, model, context)
)
try
if run_once || check_grads
ℓ, ∇ℓ = LogDensityProblems.logdensity_and_gradient(f, θ)
@debug "$(backend_label(adbackend))" θ ℓ ∇ℓ
if check_grads
grads_and_vals[:standard][adbackend] = (ℓ, ∇ℓ)
end
end
suite_backend["standard"] = @benchmarkable $(LogDensityProblems.logdensity_and_gradient)($f, $θ)
catch e
if error_on_failed_backend
rethrow(e)
else
@warn "Gradient computation (without linking) failed for $(adbackend): $(e)"
end
end
# Need a separate `VarInfo` for the linked version since otherwise we risk the
# `varinfo` from above being mutated.
varinfo_linked = if sampler === nothing
DynamicPPL.link(varinfo_current, model)
else
DynamicPPL.link(varinfo_current, sampler, model)
end
f_linked = LogDensityProblemsAD.ADgradient(
adbackend,
DynamicPPL.LogDensityFunction(varinfo_linked, model, context)
)
try
if run_once || check_grads
ℓ_linked, ∇ℓ_linked = LogDensityProblems.logdensity_and_gradient(f_linked, θ_linked)
@debug "$(backend_label(adbackend)) [linked]" θ_linked ℓ_linked ∇ℓ_linked
if check_grads
grads_and_vals[:linked][adbackend] = (ℓ_linked, ∇ℓ_linked)
end
end
suite_backend["linked"] = @benchmarkable $(LogDensityProblems.logdensity_and_gradient)($f_linked, $θ_linked)
catch e
if error_on_failed_backend
rethrow(e)
else
@warn "Gradient computation (with linking) failed for $(adbackend): $(e)"
end
end
end
# Also benchmark just standard model evaluation because why not.
suite_evaluation["standard"] = @benchmarkable $(DynamicPPL.evaluate!!)(
$model, $varinfo, $context
)
varinfo_linked = if sampler === nothing
DynamicPPL.link(varinfo, model)
else
DynamicPPL.link(varinfo, sampler, model)
end
suite_evaluation["linked"] = @benchmarkable $(DynamicPPL.evaluate!!)(
$model, $varinfo_linked, $context
)
if check_grads
success = true
for type in [:standard, :linked]
backends = collect(keys(grads_and_vals[type]))
vals = map(first, values(grads_and_vals[type]))
vals_dists = compute_distances(backends, vals)
if !all(isapprox.(values(vals_dists), 0, atol=atol, rtol=rtol))
@warn "There is disagreement in the log-density values!"
show_distances(vals_dists; header=([titlecase(string(type)), "Log-density"], ["backend", "distance"]), atol=atol, rtol=rtol)
success = false
end
grads = map(last, values(grads_and_vals[type]))
grads_dists = compute_distances(backends, grads)
if !all(isapprox.(values(grads_dists), 0, atol=atol, rtol=rtol))
@warn "There is disagreement in the gradients!"
show_distances(grads_dists, header=([titlecase(string(type)), "Gradient"], ["backend", "distance"]), atol=atol, rtol=rtol)
success = false
end
end
if !success && error_on_failed_check
error("Consistency checks failed!")
end
end
return suite
end
function compute_distances(backends, vals)
T = eltype(first(vals))
n = length(vals)
dists = DynamicPPL.OrderedDict{String,T}()
for (i, backend_i) in zip(1:n, backends)
for (j, backend_j) in zip(i + 1:n, backends[i + 1:end])
dists["$(backend_label(backend_i)) vs $(backend_label(backend_j))"] = norm(vals[i] - vals[j])
end
end
return dists
end
function show_distances(dists::AbstractDict; header=["Backend", "Distance"], atol=1e-6, rtol=0)
hl = PrettyTables.Highlighter(
(data, i, j) -> !isapprox(data[i, 2], 0; atol=atol, rtol=rtol),
PrettyTables.crayon"red bold"
)
PrettyTables.pretty_table(
dists;
header=header,
highlighters=(hl,),
formatters=PrettyTables.ft_printf("%.2f", [2])
)
end
"""
extract_stan_data(model::DynamicPPL.Model)
Return the data in `model` in a format consumable by the corresponding Stan model.
The Stan model requires the return data to be either
1. A JSON string representing a dictionary with the data.
2. A path to a data file ending in `.json`.
"""
function extract_stan_data end
"""
stan_model_string(model::DynamicPPL.Model)
Return a string defining the Stan model corresponding to `model`.
"""
function stan_model_string end
"""
make_stan_suite(model::Turing.Model; kwargs...)
Create default benchmark suite for the Stan model corresponding to `model`.
"""
function make_stan_suite end
# This symbol is only defined on Julia versions that support extensions
@static if !isdefined(Base, :get_extension)
function __init__()
@require BridgeStan = "c88b6f0a-829e-4b0b-94b7-f06ab5908f5a" include("../ext/TuringBenchmarkingBridgeStanExt.jl")
end
end
end # module TuringBenchmarking
| TuringBenchmarking | https://github.com/TuringLang/TuringBenchmarking.jl.git |
|
[
"MIT"
] | 0.5.4 | 62176f36b39144429a567d71ab98c72ee4617579 | code | 5921 | using TuringBenchmarking
using BenchmarkTools
using DynamicPPL, Distributions, DistributionsAD
using Test
using ADTypes
using Zygote: Zygote
using ReverseDiff: ReverseDiff
# Just make things run a bit faster.
BenchmarkTools.DEFAULT_PARAMETERS.seconds = 1
BenchmarkTools.DEFAULT_PARAMETERS.evals = 1
BenchmarkTools.DEFAULT_PARAMETERS.samples = 2
# These should be ordered (ascendingly) by runtime.
ADBACKENDS = TuringBenchmarking.DEFAULT_ADBACKENDS
@testset "TuringBenchmarking.jl" begin
@testset "Item-Response model" begin
# Simulate data.
function sim(I, P)
yvec = Vector{Int}(undef, I * P)
ivec = similar(yvec)
pvec = similar(yvec)
beta = rand(Normal(), I)
theta = rand(Normal(), P)
n = 0
for i in 1:I, p in 1:P
n += 1
ivec[n] = i
pvec[n] = p
yvec[n] = rand(BernoulliLogit(theta[p] - beta[i]))
end
return yvec, ivec, pvec, theta, beta
end
y, i, p, _, _ = sim(5, 3)
# Performant model.
@model function irt(y, i, p; I=maximum(i), P=maximum(p))
theta ~ filldist(Normal(), P)
beta ~ filldist(Normal(), I)
DynamicPPL.@addlogprob! sum(logpdf.(BernoulliLogit.(theta[p] - beta[i]), y))
return (; theta, beta)
end
# Instantiate
model = irt(y, i, p)
# Make the benchmark suite.
@testset "$(nameof(typeof(varinfo)))" for varinfo in [
DynamicPPL.VarInfo(model),
DynamicPPL.SimpleVarInfo(model),
]
suite = TuringBenchmarking.make_turing_suite(
model;
adbackends=ADBACKENDS,
varinfo=varinfo,
check_grads=true,
)
results = run(suite, verbose=true)
@testset "$adbackend" for (i, adbackend) in enumerate(ADBACKENDS)
adbackend_string = "$(adbackend)"
results_backend = results[@tagged adbackend_string]
# Each AD backend should have two results.
@test length(BenchmarkTools.leaves(results_backend)) == 2
# It should be under the "gradient" section.
@test haskey(results_backend, "gradient")
# It should have one tagged "linked" and one "standard"
@test length(BenchmarkTools.leaves(results_backend[@tagged "linked"])) == 1
@test length(BenchmarkTools.leaves(results_backend[@tagged "standard"])) == 1
end
end
@testset "Specify AD backends using symbols" begin
varinfo = DynamicPPL.VarInfo(model)
suite = TuringBenchmarking.make_turing_suite(
model;
adbackends=[:forwarddiff, :reversediff, :reversediff_compiled, :zygote],
varinfo=varinfo,
)
results = run(suite, verbose=true)
@testset "$adbackend" for (i, adbackend) in enumerate(ADBACKENDS)
adbackend_string = "$(adbackend)"
results_backend = results[@tagged adbackend_string]
# Each AD backend should have two results.
@test length(BenchmarkTools.leaves(results_backend)) == 2
# It should be under the "gradient" section.
@test haskey(results_backend, "gradient")
# It should have one tagged "linked" and one "standard"
@test length(BenchmarkTools.leaves(results_backend[@tagged "linked"])) == 1
@test length(BenchmarkTools.leaves(results_backend[@tagged "standard"])) == 1
end
end
end
@testset "Model with mutation" begin
@model function demo_with_mutation(::Type{TV}=Vector{Float64}) where {TV}
x = TV(undef, 2)
x[1] ~ Normal()
x[2] ~ Normal()
return x
end
model = demo_with_mutation()
# Make the benchmark suite.
@testset "$(nameof(typeof(varinfo)))" for varinfo in [
DynamicPPL.VarInfo(model),
DynamicPPL.SimpleVarInfo(x=randn(2)),
DynamicPPL.SimpleVarInfo(DynamicPPL.OrderedDict(@varname(x) => randn(2))),
]
# Zygote will fail.
@test_throws Union{MethodError,ErrorException,Zygote.CompileError} TuringBenchmarking.make_turing_suite(
model;
adbackends=ADBACKENDS,
varinfo=varinfo,
error_on_failed_backend=true,
)
# Skip the failing ones.
suite = TuringBenchmarking.make_turing_suite(
model;
adbackends=ADBACKENDS,
varinfo=varinfo,
error_on_failed_backend=false,
)
results = run(suite, verbose=true)
@testset "$adbackend" for (i, adbackend) in enumerate(ADBACKENDS)
adbackend_string = "$(adbackend)"
results_backend = results[@tagged adbackend_string]
if adbackend isa AutoZygote
# Zygote.jl should fail, i.e. return an empty suite.
@test length(BenchmarkTools.leaves(results_backend)) == 0
else
# Each AD backend should have two results.
@test length(BenchmarkTools.leaves(results_backend)) == 2
# It should be under the "gradient" section.
@test haskey(results_backend, "gradient")
# It should have one tagged "linked" and one "standard"
@test length(BenchmarkTools.leaves(results_backend[@tagged "linked"])) == 1
@test length(BenchmarkTools.leaves(results_backend[@tagged "standard"])) == 1
end
end
end
end
end
| TuringBenchmarking | https://github.com/TuringLang/TuringBenchmarking.jl.git |
|
[
"MIT"
] | 0.5.4 | 62176f36b39144429a567d71ab98c72ee4617579 | docs | 2601 | # TuringBenchmarking.jl
[](https://turinglang.github.io/TuringBenchmarking.jl/stable/)
[](https://turinglang.github.io/TuringBenchmarking.jl/dev/)
[](https://github.com/turinglang/TuringBenchmarking.jl/actions/workflows/CI.yml?query=branch%3Amain)
A quick and dirty way to compare different automatic-differentiation backends in Turing.jl.
A typical workflow will look something like
``` julia
using BenchmarkTools
using Turing
using TuringBenchmarking
# Define your model.
@model function your_model(...)
# ...
end
# Create and run the benchmarking suite for Turing.jl.
turing_suite = make_turing_suite(model; kwargs...)
run(turing_suite)
```
Example output:
``` julia
# Running `examples/item-response-model.jl` on my laptop.
2-element BenchmarkTools.BenchmarkGroup:
tags: []
"linked" => 2-element BenchmarkTools.BenchmarkGroup:
tags: []
"evaluation" => Trial(1.132 ms)
"Turing.Essential.ReverseDiffAD{true}()" => Trial(1.598 ms)
"Turing.Essential.ForwardDiffAD{40, true}()" => Trial(184.703 ms)
"not_linked" => 2-element BenchmarkTools.BenchmarkGroup:
tags: []
"evaluation" => Trial(1.131 ms)
"Turing.Essential.ReverseDiffAD{true}()" => Trial(1.596 ms)
"Turing.Essential.ForwardDiffAD{40, true}()" => Trial(182.864 ms)
```
`"linked"`/`"not_linked"` here refers to whether or not we're working in unconstrained space.
And if you want to compare the result to Stan:
``` julia
using BridgeStan, JSON
# Tell `TuringBenchmarking` how to convert `model` into Stan data & model.
function TuringBenchmaring.extract_stan_data(model::Turing.Model{typeof(your_model)})
# In the case where the Turing.jl and Stan models are identical in what they expect we can just do:
return JSON.json(Dict(zip(string.(keys(model.args)), values(model.args))))
end
TuringBenchmarking.stan_model_string(model::Turing.Model{typeof(your_model)}) = """
[HERE GOES YOUR STAN MODEL DEFINITION]
"""
# Create and run the benchmarking suite for Stan.
stan_suite = make_stan_suite(model; kwargs...)
run(stan_suite)
```
Example output:
``` julia
# Running `examples/item-response-model.jl` on my laptop.
2-element BenchmarkTools.BenchmarkGroup:
tags: []
"evaluation" => Trial(1.102 ms)
"gradient" => Trial(1.256 ms)
```
Note that the benchmarks for Stan are only in unconstrained space.
| TuringBenchmarking | https://github.com/TuringLang/TuringBenchmarking.jl.git |
|
[
"MIT"
] | 0.5.4 | 62176f36b39144429a567d71ab98c72ee4617579 | docs | 717 | ```@meta
CurrentModule = TuringBenchmarking
```
# TuringBenchmarking.jl
A useful package for benchmarking and checking [Turing.jl](https://github.com/TuringLang/Turing.jl) models.
## Example
```@repl
using TuringBenchmarking, Turing
@model function demo(x)
s ~ InverseGamma(2, 3)
m ~ Normal(0, sqrt(s))
for i in 1:length(x)
x[i] ~ Normal(m, sqrt(s))
end
end
model = demo([1.5, 2.0]);
benchmark_model(
model;
# Check correctness of computations
check=true,
# Automatic differentiation backends to check and benchmark
adbackends=[:forwarddiff, :reversediff, :reversediff_compiled, :zygote]
)
```
## API
```@index
```
```@autodocs
Modules = [TuringBenchmarking]
```
| TuringBenchmarking | https://github.com/TuringLang/TuringBenchmarking.jl.git |
|
[
"MIT"
] | 1.0.1 | 137fe5b646de73455486043ba766490722f0546c | code | 12377 | __precompile__(true)
"""
API Tools package
Copyright 2018-2019 Gandalf Software, Inc., Scott P. Jones
Licensed under MIT License, see LICENSE.md
(@def macro "stolen" from DiffEqBase.jl/src/util.jl :-) )
"""
module ModuleInterfaceTools
const debug = Ref(false)
const showeval = Ref(false)
const V6_COMPAT = VERSION < v"0.7-"
const BIG_ENDIAN = (ENDIAN_BOM == 0x01020304)
_stdout() = stdout
_stderr() = stderr
Base.parse(::Type{Expr}, args...; kwargs...) =
Meta.parse(args...; kwargs...)
export @api, V6_COMPAT, BIG_ENDIAN
_api_def(name, definition) =
quote
macro $(esc(name))()
esc($(Expr(:quote, definition)))
end
end
const SymSet = Set{Symbol}
abstract type AbstractAPI end
struct TMP_API <: AbstractAPI
mod::Module
base::SymSet
public::SymSet
develop::SymSet
public!::SymSet
develop!::SymSet
modules::SymSet
TMP_API(mod::Module) = new(mod, SymSet(), SymSet(), SymSet(), SymSet(), SymSet(), SymSet())
end
const SymList = Tuple{Vararg{Symbol}}
struct API <: AbstractAPI
mod::Module
base::SymList
public::SymList
develop::SymList
public!::SymList
develop!::SymList
modules::SymList
end
API(api::TMP_API) =
API(api.mod, SymList(api.base), SymList(api.public), SymList(api.develop),
SymList(api.public!), SymList(api.develop!), SymList(api.modules))
function Base.show(io::IO, api::AbstractAPI)
println(io, "ModuleInterfaceTools.API: ", api.mod)
for fld in (:base, :public, :develop, :public!, :develop!, :modules)
syms = getfield(api, fld)
isempty(syms) && continue
print(fld, ":")
for s in syms
print(" ", s)
end
println()
println()
end
end
function m_eval(mod, expr)
try
showeval[] && println("m_eval($mod, $expr)")
Core.eval(mod, expr)
catch ex
println("m_eval($mod, $expr)");
println(sprint(showerror, ex, catch_backtrace()))
#rethrow(ex)
end
end
"""
@api <cmd> [<symbols>...]
* freeze # use at end of module to freeze API
* list <modules>... # list API(s) of given modules (or current if none given)
* use <modules>... # use, without importing (i.e. can't extend)
* use! <modules>... # use, without importing (i.e. can't extend), "export"
* test <modules>... # using public and develop APIs, for testing purposes
* extend <modules>... # for development, imports api & dev, use api & dev definitions
* extend! <modules>... # for development, imports api & dev, use api & dev definitions, "export"
* reexport <modules>... # export public definitions from those modules
* base <names...> # Add functions from Base that are part of the API (extendible)
* base! <names...> # Add functions from Base or define them if not in Base
* public <names...> # Add other symbols that are part of the public API (structs, consts)
* public! <names...> # Add functions that are part of the public API (extendible)
* develop <names...> # Add other symbols that are part of the development API
* develop! <names...> # Add functions that are part of the development API (extendible)
* define! <names...> # Define functions to be extended, public API
* defdev! <names...> # Define functions to be extended, develop API
* modules <names...> # Add submodule names that are part of the API
* path <paths...> # Add paths to LOAD_PATH
* def <name> <expr> # Same as the @def macro, creates a macro with the given name
"""
macro api(cmd::Symbol)
mod = __module__
cmd == :list ? _api_list(mod) :
cmd == :freeze ? _api_freeze(mod) :
cmd == :test ? _api_test(mod) :
error("@api unrecognized command: $cmd")
end
function _api_display(mod, nam)
if isdefined(mod, nam) && (api = m_eval(mod, nam)) !== nothing
show(api);
else
println("Exported from $mod:")
syms = names(mod)
if !isempty(syms)
print(fld, ":")
for s in syms
print(" ", s)
end
end
end
println()
end
_api_list(mod::Module) = (_api_display(mod, :__api__) ; _api_display(mod, :__tmp_api__))
function _api_freeze(mod::Module)
ex = :( const __api__ = ModuleInterfaceTools.API(__tmp_api__) ; __tmp_api__ = nothing )
isdefined(mod, :__tmp_api__) && m_eval(mod, :( __tmp_api__ !== nothing ) ) && m_eval(mod, ex)
nothing
end
function _api_path(curmod, exprs)
for exp in exprs
if isa(exp, Expr) || isa(exp, Symbol)
str = m_eval(curmod, exp)
elseif isa(exp, String)
str = exp
else
error("@api path: syntax error $exp")
end
m_eval(curmod, :( push!(LOAD_PATH, $str) ))
end
nothing
end
const _cmduse = (:use, :use!, :test, :extend, :extend!, :reexport, :list)
const _cmdadd =
(:modules, :public, :develop, :public!, :develop!, :base, :base!, :define!, :defdev!)
_ff(lst, val) = (ret = findfirst(isequal(val), lst); ret === nothing ? 0 : ret)
function _add_def!(curmod, grp, exp)
debug[] && print("_add_def!($curmod, $grp, $exp::$(typeof(exp))")
if isa(exp, Symbol)
sym = exp
elseif isa(exp, AbstractString)
sym = Symbol(exp)
else
error("@api $grp: syntax error $exp")
end
if grp == :base! && isdefined(Base, sym)
m_eval(curmod, :(import Base.$sym ))
m_eval(curmod, :(push!(__tmp_api__.base, $(QuoteNode(sym)))))
return
end
m_eval(curmod, :(function $sym end))
m_eval(curmod, (grp == :defdev!
? :(push!(__tmp_api__.develop!, $(QuoteNode(sym))))
: :(push!(__tmp_api__.public!, $(QuoteNode(sym))))))
end
function push_args!(symbols, lst, grp)
for ex in lst
if isa(ex, Expr) && ex.head == :tuple
push_args!(symbols, ex.args)
elseif isa(ex, Symbol)
push!(symbols, ex)
elseif isa(ex, AbstractString)
push!(symbols, Symbol(ex))
else
error("@api $grp: syntax error $ex")
end
end
end
"""Initialize the temp api variable for this module"""
_init_api(curmod) =
isdefined(curmod, :__tmp_api__) ||
m_eval(curmod, :( global __tmp_api__ = ModuleInterfaceTools.TMP_API($curmod)))
"""Add symbols"""
function _add_symbols(curmod, grp, exprs)
if debug[]
print("_add_symbols($curmod, $grp, $exprs)")
isdefined(curmod, :__tmp_api__) && print(" => ", m_eval(curmod, :__tmp_api__))
println()
end
_init_api(curmod)
if grp == :base! || grp == :define! || grp == :defdev!
for ex in exprs
if isa(ex, Expr) && ex.head == :tuple
for sym in ex.args
_add_def!(curmod, grp, sym)
end
else
_add_def!(curmod, grp, ex)
end
end
else
symbols = SymSet()
for ex in exprs
if isa(ex, Expr) && ex.head == :tuple
push_args!(symbols, ex.args, grp)
elseif isa(ex, Symbol)
push!(symbols, ex)
elseif isa(ex, AbstractString)
push!(symbols, Symbol(ex))
else
error("@api $grp: syntax error $ex")
end
end
if grp == :base
for sym in symbols
m_eval(curmod, :( import Base.$sym ))
end
end
for sym in symbols
m_eval(curmod, :( push!(__tmp_api__.$grp, $(QuoteNode(sym)) )))
end
end
debug[] && println("after add symbols: ", m_eval(curmod, :__tmp_api__))
nothing
end
has_api(mod) = isdefined(mod, :__api__)
get_api(curmod, mod) = m_eval(curmod, :( $mod.__api__ ))
function _api_extend(curmod, modules, cpy::Bool)
for nam in modules
mod = m_eval(curmod, nam)
if has_api(mod)
api = get_api(curmod, mod)
_do_list(curmod, cpy, :import, Base, :Base, :base, api)
_do_list(curmod, cpy, :import, mod, nam, :public!, api)
_do_list(curmod, cpy, :import, mod, nam, :develop!, api)
_do_list(curmod, cpy, :using, mod, nam, :public, api)
_do_list(curmod, cpy, :using, mod, nam, :develop, api)
else
_do_list(curmod, cpy, :import, mod, nam, :public!, names(mod))
end
end
nothing
end
function _api_use(curmod, modules, cpy::Bool)
for nam in modules
mod = m_eval(curmod, nam)
if has_api(mod)
api = get_api(curmod, mod)
_do_list(curmod, cpy, :using, mod, nam, :public, api)
_do_list(curmod, cpy, :using, mod, nam, :public!, api)
else
_do_list(curmod, cpy, :using, mod, nam, :public!, names(mod))
end
end
nothing
end
function _api_reexport(curmod, modules)
for nam in modules
mod = m_eval(curmod, nam)
if has_api(mod)
api = get_api(curmod, mod)
l1, l2, l3 = getfield(api, :modules), getfield(api, :public), getfield(api, :public!)
if !(isempty(l1) && isempty(l2) && isempty(l3))
debug[] && println("Reexport: api = $api:$l1,$l2,$l3")
m_eval(curmod, Expr( :export, l1..., l2..., l3... ))
end
end
end
nothing
end
function _api_list(curmod, modules)
for nam in modules
_api_list(m_eval(curmod, nam))
end
nothing
end
_api_test(mod) = m_eval(mod, :(using Test))
function _api(curmod::Module, cmd::Symbol, exprs)
cmd == :def && return _api_def(exprs...)
cmd == :path && return _api_path(curmod, exprs)
ind = _ff(_cmdadd, cmd)
ind == 0 || return _add_symbols(curmod, cmd, exprs)
_ff(_cmduse, cmd) == 0 && error("Syntax error: @api $cmd $exprs")
debug[] && print("_api($curmod, $cmd, $exprs)")
# Be nice and set up standard Test
cmd == :test && _api_test(curmod)
modules = SymSet()
for ex in exprs
if isa(ex, Expr) && ex.head == :tuple
# Some of these might not just be modules
# might have module(symbols, !syms, sym => other), need to add support for that
for sym in ex.args
if isa(sym, Symbol)
push!(modules, sym)
m_eval(curmod, :(import $sym))
else
println("Not a symbol: $sym");
dump(sym);
end
end
elseif isa(ex, Symbol)
push!(modules, ex)
m_eval(curmod, :(import $ex))
else
error("@api $cmd: syntax error $ex")
end
end
debug[] && println(" => $modules")
cmd == :reexport && return _api_reexport(curmod, modules)
cmd == :list && return _api_list(curmod, modules)
cpy = (cmd == :use!) || (cmd == :extend!)
cpy && _init_api(curmod)
for nam in modules
mod = m_eval(curmod, nam)
if has_api(mod)
api = get_api(curmod, mod)
for sym in getfield(api, :modules)
if isdefined(mod, sym)
m_eval(curmod, :(using $nam.$sym))
cpy && m_eval(curmod, :( push!(__tmp_api__.modules, $(QuoteNode(sym)) )))
else
println(_stderr(), "Warning: Exported symbol $sym is not defined in $nam")
end
end
end
end
((cmd == :use || cmd == :use!)
? _api_use(curmod, modules, cpy)
: _api_extend(curmod, modules, cpy))
end
function makecmd(cmd, nam, sym)
(cmd == :using
? Expr(cmd, Expr(:(:), Expr(:., nam), Expr(:., sym)))
: Expr(cmd, Expr(:., nam, sym)))
end
_do_list(curmod, cpy, cmd, mod, nam, grp, api::API) =
_do_list(curmod, cpy, cmd, mod, nam, grp, getfield(api, grp))
function _do_list(curmod, cpy, cmd, mod, nam, grp, lst)
debug[] && println("_do_list($curmod, $cpy, $cmd, $mod, $nam, $grp, $lst)")
for sym in lst
if isdefined(mod, sym)
m_eval(curmod, makecmd(cmd, nam, sym))
cpy && m_eval(curmod, :( push!(__tmp_api__.$grp, $(QuoteNode(sym)) )))
else
println(_stderr(), "Warning: Exported symbol $sym is not defined in $nam")
end
end
end
macro api(cmd::Symbol, exprs...)
_api(__module__, cmd, exprs)
end
end # module ModuleInterfaceTools
| ModuleInterfaceTools | https://github.com/JuliaString/ModuleInterfaceTools.jl.git |
|
[
"MIT"
] | 1.0.1 | 137fe5b646de73455486043ba766490722f0546c | code | 568 | # Copyright 2018 Gandalf Software, Inc., Scott P. Jones
# Licensed under MIT License, see LICENSE.md
using ModuleInterfaceTools
@api test
@api extend InternedStrings
@api list InternedStrings
@api def testcase begin
myname = "Scott Paul Jones"
end
@testset "@api def <name> <expr>" begin
@testcase
@test myname == "Scott Paul Jones"
end
intern(x::Integer) = 1
intern(x::Float64) = 2
@testset "Function extension" begin
@test typeof(intern("foo")) == String
@test intern(1) == 1
@test intern(2.0) == 2
@test intern("th") == "th"
end
| ModuleInterfaceTools | https://github.com/JuliaString/ModuleInterfaceTools.jl.git |
|
[
"MIT"
] | 1.0.1 | 137fe5b646de73455486043ba766490722f0546c | docs | 4988 | # ModuleInterfaceTools
| **Info** | **Windows** | **Linux & MacOS** | **Package Evaluator** | **CodeCov** | **Coveralls** |
|:------------------:|:------------------:|:---------------------:|:-----------------:|:---------------------:|:-----------------:|
| [![][license-img]][license-url] | [![][app-s-img]][app-s-url] | [![][travis-s-img]][travis-url] | [![][pkg-s-img]][pkg-s-url] | [![][codecov-img]][codecov-url] | [![][coverall-s-img]][coverall-s-url]
| [![][gitter-img]][gitter-url] | [![][app-m-img]][app-m-url] | [![][travis-m-img]][travis-url] | [![][pkg-m-img]][pkg-m-url] | [![][codecov-img]][codecov-url] | [![][coverall-m-img]][coverall-m-url]
[license-img]: http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat
[license-url]: LICENSE.md
[gitter-img]: https://badges.gitter.im/Join%20Chat.svg
[gitter-url]: https://gitter.im/JuliaString/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge
[travis-url]: https://travis-ci.org/JuliaString/ModuleInterfaceTools.jl
[travis-s-img]: https://travis-ci.org/JuliaString/ModuleInterfaceTools.jl.svg
[travis-m-img]: https://travis-ci.org/JuliaString/ModuleInterfaceTools.jl.svg?branch=master
[app-s-url]: https://ci.appveyor.com/project/ScottPJones/moduleinterfacetools-jl
[app-m-url]: https://ci.appveyor.com/project/ScottPJones/moduleinterfacetools-jl/branch/master
[app-s-img]: https://ci.appveyor.com/api/projects/status/x13gh7y6id3fbmke?svg=true
[app-m-img]: https://ci.appveyor.com/api/projects/status/x13gh7y6id3fbmke/branch/master?svg=true
[pkg-s-url]: http://pkg.julialang.org/detail/ModuleInterfaceTools
[pkg-m-url]: http://pkg.julialang.org/detail/ModuleInterfaceTools
[pkg-s-img]: http://pkg.julialang.org/badges/ModuleInterfaceTools_0.6.svg
[pkg-m-img]: http://pkg.julialang.org/badges/ModuleInterfaceTools_0.7.svg
[codecov-url]: https://codecov.io/gh/JuliaString/ModuleInterfaceTools.jl
[codecov-img]: https://codecov.io/gh/JuliaString/ModuleInterfaceTools.jl/branch/master/graph/badge.svg
[coverall-s-url]: https://coveralls.io/github/JuliaString/ModuleInterfaceTools.jl
[coverall-m-url]: https://coveralls.io/github/JuliaString/ModuleInterfaceTools.jl?branch=master
[coverall-s-img]: https://coveralls.io/repos/github/JuliaString/ModuleInterfaceTools.jl/badge.svg
[coverall-m-img]: https://coveralls.io/repos/github/JuliaString/ModuleInterfaceTools.jl/badge.svg?branch=master
This provides a way of having different lists of names that you want to be part of a public API,
as well as being part of a development API (i.e. functions that are not normally needed by users of a package, but *are* needed by a developer writing a package that depends on it).
It also separates lists of names of functions, that can be extended, from names of types, modules, constants that cannot be extended, and functions that are not intended to be extended.
This is a bit of a work-in-progress, I heartily welcome any suggestions for better syntax, better implementation, and extra functionality.
```julia
@api <cmd> [<symbols>...]
* @api list # display information about this module's API
* @api freeze # use at end of module, to "freeze" API
* @api list <modules>... # display information about one or more modules' API
* @api use <modules>... # for normal use, i.e. `using`
* @api test <modules>... # using public and develop symbols, for testing purposes
* @api extend <modules>... # for development, imports `base`, `public`, and `develop` lists,
* # uses `define_public`and `define_develop` lists
* @api export <modules>... # export api symbols
* @api base <names...> # Add functions from Base that are part of the API
* @api public! <names...> # Add functions that are part of the public API
* @api develop! <names...> # Add functions that are part of the development API
* @api public <names...> # Add other symbols that are part of the public API (structs, consts)
* @api develop <names...> # Add other symbols that are part of the development API
* @api modules <names...> # Add submodule names that are part of the API
* @api base! <names...> # Conditionally import functions from Base, or define them
```
This also includes the `@def` macro, renamed as `@api def` which I've found very useful!
I would also like to add commands that add the functionality of `@reexport`,
but instead of exporting the symbols found in the module(s), add them to either the public
or develop list. (I had a thought that it could automatically add names that do not start with `_`,
have a docstring, and are not exported, to the develop list, and all exported names would be added to the public list).
Another thing I'd like to add is a way of using/importing a module, but having pairs of names, for renaming purposes, i.e. something like `@api use Foobar: icantreadthisname => i_cant_read_this_name`
which would import the variable from Foobar, but with the name after the `=>`.
| ModuleInterfaceTools | https://github.com/JuliaString/ModuleInterfaceTools.jl.git |
|
[
"MIT"
] | 0.1.1 | 5aa07104cc57e5aeaaa14891afcac7d0c95f28b7 | code | 248 | using PyCall: pyimport_conda
using Conda
function installpypackage()
try
pyimport_conda("sklearn", "scikit-learn")
catch
try
Conda.add("scikit-learn")
catch
println("scikit-learn failed to install")
end
end
end
installpypackage() | SyntheticDatasets | https://github.com/ATISLabs/SyntheticDatasets.jl.git |
|
[
"MIT"
] | 0.1.1 | 5aa07104cc57e5aeaaa14891afcac7d0c95f28b7 | code | 2471 | ### A Pluto.jl notebook ###
# v0.11.9
using Markdown
using InteractiveUtils
# ╔═╡ 9cd14420-fd07-11ea-2bba-8965aca56d2d
begin
using StatsPlots, SyntheticDatasets
end
# ╔═╡ a3c9a100-fd07-11ea-078c-21cb7dc31f79
blobs = SyntheticDatasets.make_blobs(n_samples = 1000,
n_features = 2,
centers = [-1 1; -0.5 0.5],
cluster_std = 0.25,
center_box = (-2.0, 2.0),
shuffle = true,
random_state = nothing);
# ╔═╡ 44690e10-fd09-11ea-36b8-f16615c1f284
gauss = SyntheticDatasets.make_gaussian_quantiles(mean =[10,1],
cov = 2.0,
n_samples = 1000,
n_features = 2,
n_classes = 3,
shuffle = true,
random_state = 2);
# ╔═╡ e6227ef0-fdc0-11ea-1cde-e904cfe08d34
spirals = SyntheticDatasets.make_twospirals(n_samples=2000,
start_degrees = 90,
total_degrees = 570,
noise =0.1);
# ╔═╡ 514edde0-fdc1-11ea-2790-c59af5f94ae4
kernel = SyntheticDatasets.make_halfkernel(n_samples = 1000,
minx = -20,
r1 = 20,
r2 = 35,
noise = 3.0,
ratio = 0.6);
# ╔═╡ 776a58e0-fd0a-11ea-3a6a-4fac23cba2d9
blob = @df blobs scatter(
:feature_1,
:feature_2,
group = :label,
title = "Blobs"
)
# ╔═╡ dcc15f70-fdc0-11ea-0ba7-5b09883ed63a
gaussian_quantiles = @df gauss scatter(
:feature_1,
:feature_2,
group = :label,
title = "Gaussian Quantiles"
)
# ╔═╡ e4b3acb0-fdc0-11ea-1e86-535f2541fc20
half_kernel = @df kernel scatter(
:feature_1,
:feature_2,
group = :label,
title = "Half Kernel"
)
# ╔═╡ 96652d30-fdc1-11ea-30d6-790213f94220
two_spirals = @df spirals scatter(
:feature_1,
:feature_2,
group = :label,
title = "Two Spirals"
)
# ╔═╡ aea9f1f0-fdc1-11ea-31db-2d8f810726b0
plot(two_spirals,half_kernel,gaussian_quantiles,blob)
# ╔═╡ Cell order:
# ╠═9cd14420-fd07-11ea-2bba-8965aca56d2d
# ╠═a3c9a100-fd07-11ea-078c-21cb7dc31f79
# ╠═44690e10-fd09-11ea-36b8-f16615c1f284
# ╠═e6227ef0-fdc0-11ea-1cde-e904cfe08d34
# ╠═514edde0-fdc1-11ea-2790-c59af5f94ae4
# ╠═776a58e0-fd0a-11ea-3a6a-4fac23cba2d9
# ╠═dcc15f70-fdc0-11ea-0ba7-5b09883ed63a
# ╠═e4b3acb0-fdc0-11ea-1e86-535f2541fc20
# ╠═96652d30-fdc1-11ea-30d6-790213f94220
# ╠═aea9f1f0-fdc1-11ea-31db-2d8f810726b0
| SyntheticDatasets | https://github.com/ATISLabs/SyntheticDatasets.jl.git |
|
[
"MIT"
] | 0.1.1 | 5aa07104cc57e5aeaaa14891afcac7d0c95f28b7 | code | 1872 | using StatsPlots, SyntheticDatasets
blobs = SyntheticDatasets.make_blobs( n_samples = 1000,
n_features = 2,
centers = [-1 1; -0.5 0.5],
cluster_std = 0.25,
center_box = (-2.0, 2.0),
shuffle = true,
random_state = nothing);
@df blobs scatter(:feature_1, :feature_2, group = :label, title = "Blobs")
gauss = SyntheticDatasets.make_gaussian_quantiles( mean = [10,1],
cov = 2.0,
n_samples = 1000,
n_features = 2,
n_classes = 3,
shuffle = true,
random_state = 2);
@df gauss scatter(:feature_1, :feature_2, group = :label, title = "Gaussian Quantiles")
spirals = SyntheticDatasets.make_twospirals(n_samples = 2000,
start_degrees = 90,
total_degrees = 570,
noise =0.1);
@df spirals scatter(:feature_1, :feature_2, group = :label, title = "Two Spirals")
kernel = SyntheticDatasets.make_halfkernel( n_samples = 1000,
minx = -20,
r1 = 20,
r2 = 35,
noise = 3.0,
ratio = 0.6);
@df kernel scatter(:feature_1, :feature_2, group = :label, title = "Half Kernel") | SyntheticDatasets | https://github.com/ATISLabs/SyntheticDatasets.jl.git |
|
[
"MIT"
] | 0.1.1 | 5aa07104cc57e5aeaaa14891afcac7d0c95f28b7 | code | 1126 | module SyntheticDatasets
using PyCall
using DataFrames
using Random
const datasets = PyNULL()
function __init__()
copy!(datasets, pyimport("sklearn.datasets"))
end
include("sklearn.jl")
include("matlab.jl")
function convert(features::Array{T, 2}, labels::Array{D, 1})::DataFrame where {T <: Number, D <: Number}
df = DataFrame()
for i = 1:size(features)[2]
df[!, Symbol("feature_$(i)")] = eltype(features)[]
end
df[!, :label] = eltype(labels)[]
for label in unique(labels)
for i in findall(r->r == label, labels)
push!(df, (features[i, :]... , label))
end
end
return df
end
function convert(features::Array{T, 2}, labels::Array{D, 2})::DataFrame where {T <: Number, D <: Number}
df = DataFrame()
for i = 1:size(features)[2]
df[!, Symbol("feature_$(i)")] = eltype(features)[]
end
for i = 1:size(labels)[2]
df[!, Symbol("label_$(i)")] = eltype(labels)[]
end
for row in 1:size(features)[1]
push!(df, (features[row, :]... , labels[row, :]...))
end
return df
end
end # module
| SyntheticDatasets | https://github.com/ATISLabs/SyntheticDatasets.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.