licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.1.1
91e7a85ba7923e80f9a6bc359abb18b0fe437314
code
1355
module MultiAgentPOMDPs using POMDPs abstract type JointMDP{S, A<:AbstractVector} <: MDP{S, A} end """ function n_agents(m::JointMDP) Return the number of agents in the (PO)MDP """ function n_agents end """ function agent_actions(m::JointMDP, idx::Int64, s::S) where S Returns the discrete actions for the given agent index. !!! note This will be called a LOT so it should not allocate each time.... """ function agent_actions end """ function agent_states(m::JointMDP, idx::Int64) Returns the discrete states for the given agent index """ function agent_states end """ function agent_actionindex(m::JointMDP, idx::Int64, a::A) where A Returns the integer index of action `a` for agent `idx`. Used for discrete models only. """ function agent_actionindex end """ function agent_actionindex(m::JointMDP, idx::Int64, s::S) where S Returns the integer index of state `s` for agent `idx`. Used for discrete models only. """ function agent_stateindex end """ function coordination_graph(m::JointMDP) function coordination_graph(m::JointMDP, s::S) where S Returns the LightGraphs.SimpleGraph (or any appropriate structure) for the coordination graph. """ function coordination_graph end export JointMDP, n_agents, agent_actions, agent_states, agent_actionindex, agent_stateindex, agent_reward, coordination_graph end
MultiAgentPOMDPs
https://github.com/JuliaPOMDP/MultiAgentPOMDPs.jl.git
[ "MIT" ]
0.1.1
91e7a85ba7923e80f9a6bc359abb18b0fe437314
code
612
using MultiAgentPOMDPs using POMDPs using Test mutable struct X <: JointMDP{Vector{Float64},Vector{Bool}} end abstract type Z <: JointMDP{Vector{Float64},Vector{Int}} end mutable struct Y <: Z end @testset "MultiAgentPOMDPs.jl" begin @testset "inference" begin @test_throws ErrorException statetype(Int) @test_throws ErrorException actiontype(Int) @test_throws ErrorException obstype(Int) @test statetype(X) == Vector{Float64} @test statetype(Y) == Vector{Float64} @test actiontype(X) == Vector{Bool} @test actiontype(Y) == Vector{Int} end end
MultiAgentPOMDPs
https://github.com/JuliaPOMDP/MultiAgentPOMDPs.jl.git
[ "MIT" ]
0.1.1
91e7a85ba7923e80f9a6bc359abb18b0fe437314
docs
930
# MultiAgentPOMDPs [![CI](https://github.com/JuliaPOMDP/MultiAgentPOMDPs.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/JuliaPOMDP/MultiAgentPOMDPs.jl/actions/workflows/ci.yml) [![codecov.io](http://codecov.io/github/JuliaPOMDP/MultiAgentPOMDPs.jl/coverage.svg?branch=master)](http://codecov.io/github/JuliaPOMDP/MultiAgentPOMDPs.jl?branch=master) [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaPOMDP.github.io/MultiAgentPOMDPs.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://JuliaPOMDP.github.io/MultiAgentPOMDPs.jl/dev) This package provides a core interface for working with **multi-agent** [Markov decision processes (MDPs)](https://en.wikipedia.org/wiki/Markov_decision_process). For examples, please see [MultiAgentSysAdmin](https://github.com/JuliaPOMDP/MultiAgentSysAdmin.jl) and [MultiUAVDelivery](https://github.com/JuliaPOMDP/MultiUAVDelivery.jl).
MultiAgentPOMDPs
https://github.com/JuliaPOMDP/MultiAgentPOMDPs.jl.git
[ "MIT" ]
0.1.1
91e7a85ba7923e80f9a6bc359abb18b0fe437314
docs
128
```@meta CurrentModule = MultiAgentPOMDPs ``` # MultiAgentPOMDPs ```@index ``` ```@autodocs Modules = [MultiAgentPOMDPs] ```
MultiAgentPOMDPs
https://github.com/JuliaPOMDP/MultiAgentPOMDPs.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
17858
# Imagenet training script based on https://github.com/pytorch/examples/blob/main/imagenet/main.py using ArgParse # Parse Arguments from Commandline using Augmentor # Image Augmentation using CUDA # GPUs <3 using DataLoaders # Pytorch like DataLoaders using Dates # Printing current time using ExplicitFluxLayers # Neural Network Framework using Flux # Only being used for OneHotArrays using FluxMPI # Distibuted Training using Formatting # Pretty Printing using Images # Image Processing using Metalhead # Image Classification Models using MLDataUtils # Shuffling and Splitting Data using NNlib # Neural Network Backend using Optimisers # Collection of Gradient Based Optimisers using ParameterSchedulers # Collection of Schedulers for Parameter Updates using Random # Make things less Random using Serialization # Serialize Models using Setfield # Easy Parameter Manipulation using Zygote # Our AD Engine import DataLoaders.LearnBase: getobs, nobs # Extending Datasets # Distributed Training FluxMPI.Init(;verbose=true) CUDA.allowscalar(false) # unsafe_free OneHotArrays CUDA.unsafe_free!(x::Flux.OneHotArray) = CUDA.unsafe_free!(x.indices) # Image Classification Models VGG11_BN(args...; kwargs...) = VGG11(args...; batchnorm=true, kwargs...) VGG13_BN(args...; kwargs...) = VGG13(args...; batchnorm=true, kwargs...) VGG16_BN(args...; kwargs...) = VGG16(args...; batchnorm=true, kwargs...) VGG19_BN(args...; kwargs...) = VGG19(args...; batchnorm=true, kwargs...) MobileNetv3_small(args...; kwargs...) = MobileNetv3(:small, args...; kwargs...) MobileNetv3_large(args...; kwargs...) = MobileNetv3(:large, args...; kwargs...) ResNeXt50(args...; kwargs...) = ResNeXt(50, args...; kwargs...) ResNeXt101(args...; kwargs...) = ResNeXt(101, args...; kwargs...) ResNeXt152(args...; kwargs...) = ResNeXt(152, args...; kwargs...) AVAILABLE_IMAGENET_MODELS = [ AlexNet, VGG11, VGG13, VGG16, VGG19, VGG11_BN, VGG13_BN, VGG16_BN, VGG19_BN, ResNet18, ResNet34, ResNet50, ResNet101, ResNet152, ResNeXt50, ResNeXt101, ResNeXt152, GoogLeNet, DenseNet121, DenseNet161, DenseNet169, DenseNet201, MobileNetv1, MobileNetv2, MobileNetv3_small, MobileNetv3_large, ConvMixer, ] IMAGENET_MODELS_DICT = Dict(string(model) => model for model in AVAILABLE_IMAGENET_MODELS) function get_model(model_name::String, models_dict::Dict, rng, args...; warmup=true, kwargs...) model = EFL.transform(models_dict[model_name](args...; kwargs...).layers) ps, st = EFL.setup(rng, model) .|> EFL.gpu if warmup # Warmup for compilation x__ = randn(rng, Float32, 224, 224, 3, 1) |> EFL.gpu y__ = Flux.onehotbatch([1], 1:1000) |> EFL.gpu should_log() && println("$(now()) ==> staring `$model_name` warmup...") model(x__, ps, st) should_log() && println("$(now()) ==> forward pass warmup completed") (l, _, _), back = Zygote.pullback(p -> logitcrossentropyloss(x__, y__, model, p, st), ps) back((one(l), nothing, nothing)) should_log() && println("$(now()) ==> backward pass warmup completed") end if is_distributed() ps = FluxMPI.synchronize!(ps; root_rank=0) st = FluxMPI.synchronize!(st; root_rank=0) should_log() && println("$(now()) ==> models synced across all ranks") end return model, ps, st end # Parse Training Arguments function parse_commandline_arguments() parse_settings = ArgParseSettings("ExplicitFluxLayers ImageNet Training") @add_arg_table! parse_settings begin "--arch" default = "ResNet18" range_tester = x -> x ∈ keys(IMAGENET_MODELS_DICT) help = "model architectures: " * join(keys(IMAGENET_MODELS_DICT), ", ", " or ") "--epochs" help = "number of total epochs to run" arg_type = Int default = 90 "--start-epoch" help = "manual epoch number (useful on restarts)" arg_type = Int default = 0 "--batch-size" help = "mini-batch size, this is the total batch size across all GPUs" arg_type = Int default = 256 "--learning-rate" help = "initial learning rate" arg_type = Float32 default = 0.1f0 "--momentum" help = "momentum" arg_type = Float32 default = 0.9f0 "--weight-decay" help = "weight decay" arg_type = Float32 default = 1.0f-4 "--print-freq" help = "print frequency" arg_type = Int default = 10 "--resume" help = "resume from checkpoint" arg_type = String default = "" "--evaluate" help = "evaluate model on validation set" action = :store_true "--pretrained" help = "use pre-trained model" action = :store_true "--seed" help = "seed for initializing training. " arg_type = Int default = 0 "data" help = "path to dataset" required = true end return parse_args(parse_settings) end # Loss Function logitcrossentropyloss(ŷ, y) = mean(-sum(y .* logsoftmax(ŷ; dims=1); dims=1)) function logitcrossentropyloss(x, y, model, ps, st) ŷ, st_ = model(x, ps, st) return logitcrossentropyloss(ŷ, y), ŷ, st_ end # Optimisers / Parameter Schedulers function update_lr(st::ST, eta) where {ST} if hasfield(ST, :eta) @set! st.eta = eta end return st end update_lr(st::Optimisers.OptimiserChain, eta) = update_lr.(st.opts, eta) function update_lr(st::Optimisers.Leaf, eta) @set! st.rule = update_lr(st.rule, eta) end update_lr(st_opt::NamedTuple, eta) = fmap(l -> update_lr(l, eta), st_opt) # Accuracy function accuracy(ŷ, y, topk=(1,)) maxk = maximum(topk) pred_labels = partialsortperm.(eachcol(ŷ), (1:maxk,), rev=true) true_labels = Flux.onecold(y) accuracies = Vector{Float32}(undef, length(topk)) for (i, k) in enumerate(topk) accuracies[i] = sum(map((a, b) -> sum(view(a, 1:k) .== b), pred_labels, true_labels)) end return accuracies .* 100 ./ size(y, ndims(y)) end # Distributed Utils is_distributed() = FluxMPI.Initialized() && total_workers() > 1 should_log() = !FluxMPI.Initialized() || local_rank() == 0 # Checkpointing function save_checkpoint(state, is_best, filename="checkpoint.pth.tar") if should_log() serialize(filename, state) if is_best cp(filename, "model_best.pth.tar") end end end # DataLoading struct ImageDataset image_files labels mapping augmentation_pipeline normalization_parameters end function ImageDataset(folder::String, augmentation_pipeline, normalization_parameters) ulabels = readdir(folder) label_dirs = joinpath.((folder,), ulabels) @assert length(label_dirs) == 1000 "There should be 1000 subdirectories in $folder" classes = readlines(joinpath(@__DIR__, "synsets.txt")) mapping = Dict(z => i for (i, z) in enumerate(ulabels)) istrain = endswith(folder, r"train|train/") if istrain image_files = vcat(map((x, y) -> joinpath.((x,), y), label_dirs, readdir.(label_dirs))...) remove_files = [ "n01739381_1309.JPEG", "n02077923_14822.JPEG", "n02447366_23489.JPEG", "n02492035_15739.JPEG", "n02747177_10752.JPEG", "n03018349_4028.JPEG", "n03062245_4620.JPEG", "n03347037_9675.JPEG", "n03467068_12171.JPEG", "n03529860_11437.JPEG", "n03544143_17228.JPEG", "n03633091_5218.JPEG", "n03710637_5125.JPEG", "n03961711_5286.JPEG", "n04033995_2932.JPEG", "n04258138_17003.JPEG", "n04264628_27969.JPEG", "n04336792_7448.JPEG", "n04371774_5854.JPEG", "n04596742_4225.JPEG", "n07583066_647.JPEG", "n13037406_4650.JPEG", "n02105855_2933.JPEG" ] remove_files = joinpath.( (folder,), joinpath.(first.(rsplit.(remove_files, "_", limit=2)), remove_files) ) image_files = [setdiff(Set(image_files), Set(remove_files))...] labels = [mapping[x] for x in map(x -> x[2], rsplit.(image_files, "/", limit=3))] else vallist = hcat(split.(readlines(joinpath(@__DIR__, "val_list.txt")))...) labels = parse.(Int, vallist[2, :]) .+ 1 filenames = [joinpath(classes[l], vallist[1, i]) for (i, l) in enumerate(labels)] image_files = joinpath.((folder,), filenames) idxs = findall(isfile, image_files) image_files = image_files[idxs] labels = labels[idxs] end return ImageDataset(image_files, labels, mapping, augmentation_pipeline, normalization_parameters) end nobs(data::ImageDataset) = length(data.image_files) function getobs(data::ImageDataset, i::Int) img = Images.load(data.image_files[i]) img = augment(img, data.augmentation_pipeline) cimg = channelview(img) if ndims(cimg) == 2 cimg = reshape(cimg, 1, size(cimg, 1), size(cimg, 2)) cimg = vcat(cimg, cimg, cimg) end img = Float32.(permutedims(cimg, (3, 2, 1))) img = (img .- data.normalization_parameters.mean) ./ data.normalization_parameters.std return img, Flux.onehot(data.labels[i], 1:1000) end # Tracking Base.@kwdef mutable struct AverageMeter fmtstr val::Float64 = 0.0 sum::Float64 = 0.0 count::Int = 0 average::Float64 = 0 end function AverageMeter(name::String, fmt::String) fmtstr = FormatExpr("$name {1:$fmt} ({2:$fmt})") return AverageMeter(; fmtstr=fmtstr) end function update!(meter::AverageMeter, val, n::Int) meter.val = val meter.sum += val * n meter.count += n meter.average = meter.sum / meter.count return meter.average end print_meter(meter::AverageMeter) = printfmt(meter.fmtstr, meter.val, meter.average) struct ProgressMeter{N} batch_fmtstr meters::NTuple{N,AverageMeter} end function ProgressMeter(num_batches::Int, meters::NTuple{N}, prefix::String="") where {N} fmt = "%" * string(length(string(num_batches))) * "d" prefix = prefix != "" ? endswith(prefix, " ") ? prefix : prefix * " " : "" batch_fmtstr = generate_formatter("$prefix[$fmt/" * sprintf1(fmt, num_batches) * "]") return ProgressMeter{N}(batch_fmtstr, meters) end function print_meter(meter::ProgressMeter, batch::Int) base_str = meter.batch_fmtstr(batch) print(base_str) foreach(x -> (print("\t"); print_meter(x)), meter.meters[1:end]) return println() end # Validation function validate(val_loader, model, ps, st, args) batch_time = AverageMeter("Batch Time", "6.3f") losses = AverageMeter("Loss", ".4f") top1 = AverageMeter("Acc@1", "6.2f") top5 = AverageMeter("Acc@5", "6.2f") progress = ProgressMeter(length(val_loader), (batch_time, losses, top1, top5), "Val:") st_ = EFL.testmode(st) t = time() for (i, (x, y)) in enumerate(CuIterator(val_loader)) # Compute Output ŷ, st_ = model(x, ps, st_) loss = logitcrossentropyloss(ŷ, y) # Metrics acc1, acc5 = accuracy(EFL.cpu(ŷ), EFL.cpu(y), (1, 5)) update!(top1, acc1, size(x, ndims(x))) update!(top5, acc5, size(x, ndims(x))) update!(losses, loss, size(x, ndims(x))) # Measure Elapsed Time bt = time() - t update!(batch_time, bt, 1) # Print Progress if i % args["print-freq"] == 0 || i == length(val_loader) print_meter(progress, i) end t = time() end return top1.average, top5.average, losses.average end # Training function train(train_loader, model, ps, st, optimiser_state, epoch, args) batch_time = AverageMeter("Batch Time", "6.3f") data_time = AverageMeter("Data Time", "6.3f") losses = AverageMeter("Loss", ".4e") top1 = AverageMeter("Acc@1", "6.2f") top5 = AverageMeter("Acc@5", "6.2f") progress = ProgressMeter(length(train_loader), (batch_time, data_time, losses, top1, top5), "Epoch: [$epoch]") st = EFL.trainmode(st) t = time() for (i, (x, y)) in enumerate(CuIterator(train_loader)) update!(data_time, time() - t, size(x, ndims(x))) # Gradients and Update (loss, ŷ, st), back = Zygote.pullback(p -> logitcrossentropyloss(x, y, model, p, st), ps) gs = back((one(loss), nothing, nothing))[1] optimiser_state, ps = Optimisers.update(optimiser_state, ps, gs) # Metrics acc1, acc5 = accuracy(EFL.cpu(ŷ), EFL.cpu(y), (1, 5)) update!(top1, acc1, size(x, ndims(x))) update!(top5, acc5, size(x, ndims(x))) update!(losses, loss, size(x, ndims(x))) # Measure Elapsed Time bt = time() - t update!(batch_time, bt, 1) # Print Progress if i % args["print-freq"] == 0 || i == length(train_loader) print_meter(progress, i) end t = time() end return ps, st, optimiser_state, (top1.average, top5.average, losses.average) end # Main Function function main(args) best_acc1 = 0 # Seeding rng = Random.default_rng() Random.seed!(rng, args["seed"]) # Model Construction if should_log() if args["pretrained"] println("$(now()) => using pre-trained model `$(args["arch"])`") else println("$(now()) => creating model `$(args["arch"])`") end end model, ps, st = get_model(args["arch"], IMAGENET_MODELS_DICT, rng; warmup=true, pretrain=args["pretrained"]) normalization_parameters = ( mean=reshape([0.485f0, 0.456f0, 0.406f0], 1, 1, 3), std=reshape([0.229f0, 0.224f0, 0.225f0], 1, 1, 3) ) train_data_augmentation = Resize(256, 256) |> FlipX(0.5) |> RCropSize(224, 224) val_data_augmentation = Resize(256, 256) |> CropSize(224, 224) train_dataset = ImageDataset( joinpath(args["data"], "train"), train_data_augmentation, normalization_parameters ) val_dataset = ImageDataset( joinpath(args["data"], "val"), val_data_augmentation, normalization_parameters ) if is_distributed() train_dataset = DistributedDataContainer(train_dataset) val_dataset = DistributedDataContainer(val_dataset) end train_loader = DataLoader(shuffleobs(train_dataset), args["batch-size"]) val_loader = DataLoader(val_dataset, args["batch-size"]) # Optimizer and Scheduler should_log() && println("$(now()) => creating optimiser") optimiser = Optimisers.OptimiserChain( Optimisers.Momentum(args["learning-rate"], args["momentum"]), Optimisers.WeightDecay(args["weight-decay"]) ) if is_distributed() optimiser = DistributedOptimiser(optimiser) end optimiser_state = Optimisers.setup(optimiser, ps) if is_distributed() optimiser_state = FluxMPI.synchronize!(optimiser_state) should_log() && println("$(now()) ==> synced optimiser state across all ranks") end scheduler = Step(λ=args["learning-rate"], γ=0.1f0, step_sizes=30) if args["resume"] != "" if isfile(args["resume"]) checkpoint = deserialize(args["resume"]) args["start-epoch"] = checkpoint["epoch"] optimiser_state = checkpoint["optimiser_state"] |> EFL.gpu ps = checkpoint["model_parameters"] |> EFL.gpu st = checkpoint["model_states"] |> EFL.gpu should_log() && println("$(now()) => loaded checkpoint `$(args["resume"])` (epoch $(args["start-epoch"]))") else should_log() && println("$(now()) => no checkpoint found at `$(args["resume"])`") end end if args["evaluate"] @assert !is_distributed() "We are not syncing statistics. For evaluation run on 1 process" validate(val_loader, model, ps, st, args) return end GC.gc(true) CUDA.reclaim() for epoch in args["start-epoch"]:args["epochs"] # Train for 1 epoch ps, st, optimiser_state, _ = train(train_loader, model, ps, st, optimiser_state, epoch, args) # Some Housekeeping GC.gc(true) CUDA.reclaim() # Evaluate on validation set acc1, _, _ = validate(val_loader, model, ps, st, args) # ParameterSchedulers eta_new = scheduler(epoch) optimiser_state = update_lr(optimiser_state, eta_new) # Some Housekeeping GC.gc(true) CUDA.reclaim() # Remember Best Accuracy and Save Checkpoint is_best = acc1 > best_acc1 best_acc1 = max(acc1, best_acc1) save_state = Dict( "epoch" => epoch, "arch" => args["arch"], "model_states" => st |> EFL.cpu, "model_parameters" => ps |> EFL.cpu, "optimiser_state" => optimiser_state |> EFL.cpu, ) save_checkpoint(save_state, is_best) end end main(parse_commandline_arguments())
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
5070
# MNIST Classification using Neural ODEs ## Package Imports using ExplicitFluxLayers, DiffEqSensitivity, OrdinaryDiffEq, Random, Flux, CUDA, MLDataUtils, Printf, MLDatasets, Optimisers, ComponentArrays using Flux.Losses: logitcrossentropy using Flux.Data: DataLoader CUDA.allowscalar(false) ## DataLoader function loadmnist(batchsize, train_split) # Use MLDataUtils LabelEnc for natural onehot conversion onehot(labels_raw) = convertlabel(LabelEnc.OneOfK, labels_raw, LabelEnc.NativeLabels(collect(0:9))) # Load MNIST imgs, labels_raw = MNIST.traindata() # Process images into (H,W,C,BS) batches x_data = Float32.(reshape(imgs, size(imgs, 1), size(imgs, 2), 1, size(imgs, 3))) y_data = onehot(labels_raw) (x_train, y_train), (x_test, y_test) = stratifiedobs((x_data, y_data); p=train_split) return ( # Use Flux's DataLoader to automatically minibatch and shuffle the data DataLoader(collect.((x_train, y_train)); batchsize=batchsize, shuffle=true), # Don't shuffle the test data DataLoader(collect.((x_test, y_test)); batchsize=batchsize, shuffle=false), ) end ## Define the Neural ODE Layer struct NeuralODE{M<:EFL.AbstractExplicitLayer,So,Se,T,K} <: EFL.AbstractExplicitContainerLayer{(:model,)} model::M solver::So sensealg::Se tspan::T kwargs::K end function NeuralODE( model::EFL.AbstractExplicitLayer; solver=Tsit5(), sensealg=InterpolatingAdjoint(; autojacvec=ZygoteVJP()), tspan=(0.0f0, 1.0f0), kwargs..., ) return NeuralODE(model, solver, sensealg, tspan, kwargs) end function (n::NeuralODE)(x, ps, st) function dudt(u, p, t) u_, st = n.model(u, p, st) return u_ end prob = ODEProblem{false}(ODEFunction{false}(dudt), x, n.tspan, ps) return solve(prob, n.solver; sensealg=n.sensealg, n.kwargs...), st end diffeqsol_to_array(x::ODESolution{T,N,<:AbstractVector{<:CuArray}}) where {T,N} = dropdims(EFL.gpu(x); dims=3) diffeqsol_to_array(x::ODESolution) = dropdims(Array(x); dims=3) function train() ## Construct the Neural ODE Model model = EFL.Chain( EFL.FlattenLayer(), EFL.Dense(784, 20, tanh), NeuralODE( EFL.Chain(EFL.Dense(20, 10, tanh), EFL.Dense(10, 10, tanh), EFL.Dense(10, 20, tanh)); save_everystep=false, reltol=1.0f-3, abstol=1.0f-3, save_start=false, ), diffeqsol_to_array, EFL.Dense(20, 10), ) ps, st = EFL.setup(MersenneTwister(0), model) ps = ComponentArray(ps) |> EFL.gpu st = st |> EFL.gpu ## Utility Functions get_class(x) = argmax.(eachcol(x)) function loss(x, y, model, ps, st) ŷ, st = model(x, ps, st) return logitcrossentropy(ŷ, y), st end function accuracy(model, ps, st, dataloader) total_correct, total = 0, 0 st = EFL.testmode(st) for (x, y) in CuIterator(dataloader) target_class = get_class(cpu(y)) predicted_class = get_class(cpu(model(x, ps, st)[1])) total_correct += sum(target_class .== predicted_class) total += length(target_class) end return total_correct / total end ## Training train_dataloader, test_dataloader = loadmnist(128, 0.9) opt = Optimisers.ADAM(0.001f0) st_opt = Optimisers.setup(opt, ps) ### Warmup the Model img, lab = EFL.gpu(train_dataloader.data[1][:, :, :, 1:1]), EFL.gpu(train_dataloader.data[2][:, 1:1]) loss(img, lab, model, ps, st) (l, _), back = Flux.pullback(p -> loss(img, lab, model, p, st), ps) back((one(l), nothing)) ### Lets train the model nepochs = 10 for epoch in 1:nepochs stime = time() for (x, y) in CuIterator(train_dataloader) (l, _), back = Flux.pullback(p -> loss(x, y, model, p, st), ps) gs = back((one(l), nothing))[1] st_opt, ps = Optimisers.update(st_opt, ps, gs) end ttime = time() - stime println( "[$epoch/$nepochs] \t Time $(round(ttime; digits=2))s \t Training Accuracy: " * "$(round(accuracy(model, ps, st, train_dataloader) * 100; digits=2))% \t " * "Test Accuracy: $(round(accuracy(model, ps, st, test_dataloader) * 100; digits=2))%" ) end end train() # [1/10] Time 23.27s Training Accuracy: 90.88% Test Accuracy: 90.45% # [2/10] Time 26.2s Training Accuracy: 92.27% Test Accuracy: 91.78% # [3/10] Time 26.49s Training Accuracy: 93.03% Test Accuracy: 92.58% # [4/10] Time 25.94s Training Accuracy: 93.57% Test Accuracy: 92.8% # [5/10] Time 26.86s Training Accuracy: 93.76% Test Accuracy: 93.18% # [6/10] Time 26.63s Training Accuracy: 94.17% Test Accuracy: 93.48% # [7/10] Time 25.39s Training Accuracy: 94.41% Test Accuracy: 93.72% # [8/10] Time 26.17s Training Accuracy: 94.68% Test Accuracy: 93.73% # [9/10] Time 27.03s Training Accuracy: 94.78% Test Accuracy: 93.65% # [10/10] Time 26.04s Training Accuracy: 94.97% Test Accuracy: 94.02%
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
1056
module ExplicitFluxLayers const EFL = ExplicitFluxLayers # Accelerator Support using CUDA # Neural Network Backend using NNlib import NNlibCUDA: batchnorm # Julia StdLibs using Random, Statistics, LinearAlgebra, SparseArrays # Parameter Manipulation using Functors, Setfield import Adapt: adapt, adapt_storage # Arrays using FillArrays, ComponentArrays # Automatic Differentiation using ChainRulesCore, Zygote # Optimization using Optimisers # Optional Dependency using Requires const use_cuda = Ref{Union{Nothing,Bool}}(nothing) # Data Transfer Utilities include("adapt.jl") # Utilities include("utils.jl") # Core include("core.jl") # Layer Implementations include("layers/basic.jl") include("layers/normalize.jl") include("layers/conv.jl") include("layers/dropout.jl") # Neural Network Backend include("nnlib.jl") # Pretty Printing include("layers/display.jl") # AutoDiff include("autodiff.jl") # Transition to Explicit Layers function __init__() @require Flux="587475ba-b771-5e3f-ad9e-33799f191a9c" include("transform.jl") end export EFL end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
1935
abstract type EFLDeviceAdaptor end struct EFLCPUAdaptor <: EFLDeviceAdaptor end struct EFLCUDAAdaptor <: EFLDeviceAdaptor end adapt_storage(::EFLCUDAAdaptor, x) = CUDA.cu(x) adapt_storage(::EFLCUDAAdaptor, x::FillArrays.AbstractFill) = CUDA.cu(colelct(x)) adapt_storage(::EFLCUDAAdaptor, x::Zygote.OneElement) = CUDA.cu(collect(x)) adapt_storage(to::EFLCUDAAdaptor, x::ComponentArray) = ComponentArray(adapt_storage(to, getdata(x)), getaxes(x)) adapt_storage(::EFLCUDAAdaptor, rng::AbstractRNG) = rng function adapt_storage( ::EFLCPUAdaptor, x::Union{AbstractRange,FillArrays.AbstractFill,Zygote.OneElement,SparseArrays.AbstractSparseArray}, ) return x end adapt_storage(::EFLCPUAdaptor, x::AbstractArray) = adapt(Array, x) adapt_storage(to::EFLCPUAdaptor, x::ComponentArray) = ComponentArray(adapt_storage(to, getdata(x)), getaxes(x)) adapt_storage(::EFLCPUAdaptor, rng::AbstractRNG) = rng # TODO: SparseArrays adapt_storage(::EFLCPUAdaptor, x::CUDA.CUSPARSE.CUDA.CUSPARSE.AbstractCuSparseMatrix) = adapt(Array, x) _isbitsarray(::AbstractArray{<:Number}) = true _isbitsarray(::AbstractArray{T}) where {T} = isbitstype(T) _isbitsarray(x) = false _isleaf(::AbstractRNG) = true _isleaf(x) = _isbitsarray(x) || Functors.isleaf(x) cpu(x) = fmap(x -> adapt(EFLCPUAdaptor(), x), x) function gpu(x) check_use_cuda() return use_cuda[] ? fmap(x -> adapt(EFLCUDAAdaptor(), x), x; exclude=_isleaf) : x end function check_use_cuda() if use_cuda[] === nothing use_cuda[] = CUDA.functional() if use_cuda[] && !CUDA.has_cudnn() @warn "CUDA.jl found cuda, but did not find libcudnn. Some functionality will not be available." end if !(use_cuda[]) @info """The GPU function is being called but the GPU is not accessible. Defaulting back to the CPU. (No action is required if you want to run on the CPU).""" maxlog = 1 end end end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
4451
# Non Differentiable Functions ChainRulesCore.@non_differentiable replicate(::Any) ChainRulesCore.@non_differentiable update_statistics(::Any, ::Any, ::Any, ::Any, ::Any, ::Any, ::Any) ChainRulesCore.@non_differentiable generate_dropout_mask(::Any, ::Any, ::Any) ChainRulesCore.@non_differentiable compute_adaptive_pooling_dims(::Any, ::Any) ChainRulesCore.@non_differentiable glorot_normal(::Any...) ChainRulesCore.@non_differentiable glorot_uniform(::Any...) ChainRulesCore.@non_differentiable check_use_cuda() ChainRulesCore.Tangent{P}(; kwargs...) where {P<:AbstractExplicitLayer} = NoTangent() ChainRulesCore.rrule(::typeof(istraining)) = true, _ -> (NoTangent(),) function ChainRulesCore.rrule(::typeof(istraining), st::NamedTuple) return st.training, _ -> (NoTangent(), NoTangent()) end no_grad(x) = zero(x) no_grad(nt::NamedTuple) = fmap(no_grad, nt) no_grad(::Union{AbstractRNG,Bool,AbstractExplicitLayer}) = NoTangent() ChainRulesCore.rrule(::typeof(Base.broadcasted), ::typeof(identity), x) = x, Δ -> (NoTangent(), NoTangent(), Δ) # Base Functions function ChainRulesCore.rrule(::typeof(merge), nt1::NamedTuple{f1}, nt2::NamedTuple{f2}) where {f1,f2} nt = merge(nt1, nt2) function merge_pullback(Δ) return ( NoTangent(), NamedTuple{f1}(map(k -> k ∈ f2 ? NoTangent() : Δ[k], keys(Δ))), NamedTuple{f2}(getfield.((Δ,), f2)), ) end return nt, merge_pullback end function ChainRulesCore.rrule(::typeof(lastindex), nt::NTuple{N,Int64}) where {N} res = lastindex(nt) function lastindex_pullback(Δ) return (NoTangent(), (ntuple(_ -> NoTangent(), N - 1)..., Δ)) end return res, lastindex_pullback end # NNlib Functions function ChainRulesCore.rrule(::typeof(applydropout), x, mask) y, broadcast_pullback = rrule_via_ad(Zygote.ZygoteRuleConfig(), broadcast, *, x, mask) function applydropout_pullback(Δ) _, _, Δx, _ = broadcast_pullback(Δ) return (NoTangent(), Δx, NoTangent()) end return y, applydropout_pullback end function ChainRulesCore.rrule(::typeof(dropout), rng, x, prob, dims, training) @assert training AssertionError("Trying to conpute dropout gradients when `training`=false") rng = replicate(rng) mask = generate_dropout_mask(rng, x, prob; dims) y, broadcast_pullback = rrule_via_ad(Zygote.ZygoteRuleConfig(), broadcast, *, x, mask) function dropout_pullback(Δ) _, _, Δx, _ = broadcast_pullback(Δ[1]) return (NoTangent(), NoTangent(), Δx, NoTangent(), NoTangent(), NoTangent()) end return (y, mask, rng), dropout_pullback end # Activation Rrules function ChainRulesCore.rrule( ::typeof(applyactivation), f::cudnnValidActivationTypes, x::CuArray{T}, inplace # Just ignore this argument ) where {T} mode = getCUDNNActivationMode(f) y = CUDA.CUDNN.cudnnActivationForward(x; mode) function applyactivation_pullback(Δ) # NOTE: Since this is an internal function, we are violating our pure function standards # and mutating the input Δx = Δ desc = CUDA.CUDNN.cudnnActivationDescriptor(mode, CUDA.CUDNN.CUDNN_NOT_PROPAGATE_NAN, Cdouble(1)) CUDA.CUDNN.cudnnActivationBackward( CUDA.CUDNN.handle(), desc, CUDA.CUDNN.scalingParameter(T, 1), CUDA.CUDNN.cudnnTensorDescriptor(y), y, CUDA.CUDNN.cudnnTensorDescriptor(Δ), Δ, CUDA.CUDNN.cudnnTensorDescriptor(x), x, CUDA.CUDNN.scalingParameter(T, 0), CUDA.CUDNN.cudnnTensorDescriptor(Δx), Δx, ) return NoTangent(), NoTangent(), Δx, NoTangent() end return y, applyactivation_pullback end # Zygote Fixes function Zygote.accum(x::ComponentArray, ys::ComponentArray...) return ComponentArray(Zygote.accum(getdata(x), getdata.(ys)...), getaxes(x)) end # Adapt Interface function ChainRulesCore.rrule(::typeof(Array), x::CUDA.CuArray) return Array(x), d -> (NoTangent(), CUDA.cu(d),) end function ChainRulesCore.rrule(::typeof(adapt_storage), to::EFLCPUAdaptor, x::CUDA.AbstractGPUArray) return adapt_storage(to, x), d -> (NoTangent(), NoTangent(), adapt_storage(EFLCUDAAdaptor(), d),) end function ChainRulesCore.rrule(::typeof(adapt_storage), to::EFLCUDAAdaptor, x::Array) return adapt_storage(to, x), d -> (NoTangent(), NoTangent(), adapt_storage(EFLCPUAdaptor(), d),) end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
3079
# Base Type ## API: ### initialparameters(rng, l) --> Must return a NamedTuple/ComponentArray ### initialstates(rng, l) --> Must return a NamedTuple ### parameterlength(l) --> Integer ### statelength(l) --> Integer ### l(x, ps, st) abstract type AbstractExplicitLayer end initialparameters(::AbstractRNG, ::Any) = NamedTuple() initialparameters(rng::AbstractRNG, l::NamedTuple) = map(Base.Fix1(initialparameters, rng), l) initialstates(::AbstractRNG, ::Any) = NamedTuple() initialstates(rng::AbstractRNG, l::NamedTuple) = map(Base.Fix1(initialstates, rng), l) parameterlength(l::AbstractExplicitLayer) = parameterlength(initialparameters(Random.default_rng(), l)) parameterlength(nt::Union{NamedTuple,Tuple}) = length(nt) == 0 ? 0 : sum(parameterlength, nt) parameterlength(a::AbstractArray) = length(a) parameterlength(x) = 0 statelength(l::AbstractExplicitLayer) = statelength(initialstates(Random.default_rng(), l)) statelength(nt::Union{NamedTuple,Tuple}) = length(nt) == 0 ? 0 : sum(statelength, nt) statelength(a::AbstractArray) = length(a) statelength(x::Union{Number,Symbol}) = 1 statelength(x) = 0 setup(rng::AbstractRNG, l::AbstractExplicitLayer) = (initialparameters(rng, l), initialstates(rng, l)) apply(model::AbstractExplicitLayer, x, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) = model(x, ps, st) function Base.show(io::IO, x::AbstractExplicitLayer) __t = rsplit(string(get_typename(x)), "."; limit=2) T = length(__t) == 2 ? __t[2] : __t[1] print(io, "$T()") end # Abstract Container Layers abstract type AbstractExplicitContainerLayer{layers} <: AbstractExplicitLayer end function initialparameters(rng::AbstractRNG, l::AbstractExplicitContainerLayer{layers}) where {layers} length(layers) == 1 && return initialparameters(rng, getfield(l, layers[1])) return NamedTuple{layers}(initialparameters.(rng, getfield.((l,), layers))) end function initialstates(rng::AbstractRNG, l::AbstractExplicitContainerLayer{layers}) where {layers} length(layers) == 1 && return initialstates(rng, getfield(l, layers[1])) return NamedTuple{layers}(initialstates.(rng, getfield.((l,), layers))) end parameterlength(l::AbstractExplicitContainerLayer{layers}) where {layers} = sum(parameterlength, getfield.((l,), layers)) statelength(l::AbstractExplicitContainerLayer{layers}) where {layers} = sum(statelength, getfield.((l,), layers)) # Test Mode testmode(st::NamedTuple, mode::Bool=true) = update_state(st, :training, !mode) trainmode(x::Any, mode::Bool=true) = testmode(x, !mode) # Utilities to modify global state function update_state(st::NamedTuple, key::Symbol, value; layer_check=_default_layer_check(key)) function _update_state(st, key::Symbol, value) return Setfield.set(st, Setfield.PropertyLens{key}(), value) end return fmap(_st -> _update_state(_st, key, value), st; exclude=layer_check) end function _default_layer_check(key) _default_layer_check_closure(x) = hasmethod(keys, (typeof(x),)) ? key ∈ keys(x) : false return _default_layer_check_closure end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
5136
## TODO: Eventually we want to move all these functions and their adjoints to NNlib.jl # Normalization Implementation @inline function update_statistics(::AbstractNormalizationLayer, xmean, xvar, batchmean, batchvar, momentum, m) batchmean = mean(batchmean; dims=ndims(batchmean)) batchvar = mean(batchvar; dims=ndims(batchvar)) _xmean = @. (1 - momentum) * xmean + momentum * batchmean _xvar = @. (1 - momentum) * xvar + momentum * batchvar * (m / (m - 1)) return (_xmean, _xvar) end @inline function update_statistics(::BatchNorm, xmean, xvar, batchmean, batchvar, momentum, m) _xmean = @. (1 - momentum) * xmean + momentum * batchmean _xvar = @. (1 - momentum) * xvar + momentum * batchvar * (m / (m - 1)) return (_xmean, _xvar) end ## FIXME: Zygote doesn't like these branching. We can compile these away pretty easily function normalization_forward( l::AbstractNormalizationLayer{affine,track_stats}, x::AbstractArray{T,N}, xmean::Union{Nothing,AbstractArray{T,N}}, xvar::Union{Nothing,AbstractArray{T,N}}, scale::Union{Nothing,AbstractArray{T,N}}, bias::Union{Nothing,AbstractArray{T,N}}, activation::AT; training::Bool, ) where {T,N,affine,track_stats,AT} reduce_dims = get_reduce_dims(l, x) if !training # Computing the mean and variance for the batch if !track_stats batchmean = mean(x; dims=reduce_dims) batchvar = var(x; mean=batchmean, dims=reduce_dims, corrected=false) else batchmean = xmean batchvar = xvar end else batchmean = mean(x; dims=reduce_dims) batchvar = var(x; mean=batchmean, dims=reduce_dims, corrected=false) if track_stats xmean, xvar = update_statistics( l, xmean, xvar, batchmean, batchvar, l.momentum, T(prod(size(x, i) for i in reduce_dims)) ) end end if affine if AT == typeof(identity) x_normalized = @. scale * (x - batchmean) / √(batchvar + l.ϵ) + bias else x_normalized = @. activation(scale * (x - batchmean) / √(batchvar + l.ϵ) + bias) end else if AT == typeof(identity) x_normalized = @. (x - batchmean) / √(batchvar + l.ϵ) else x_normalized = @. activation((x - batchmean) / √(batchvar + l.ϵ)) end end # the mean and variance should not be used in any form other than storing # for future iterations return x_normalized, xmean, xvar end # Convolution @inline conv_wrapper(x, weight, cdims) = conv(x, weight, cdims) @inline function conv_wrapper(x::SubArray{T,N,<:CuArray}, weight, cdims) where {T,N} return conv(copy(x), weight, cdims) end # Dropout _dropout_shape(s, ::Colon) = size(s) _dropout_shape(s, dims) = tuple((i ∉ dims ? 1 : si for (i, si) ∈ enumerate(size(s)))...) ## TODO: Cache `1 / q` since we never need `q` _dropout_kernel(y::T, p, q) where {T} = y > p ? T(1 / q) : T(0) function generate_dropout_mask(rng::AbstractRNG, x, p; dims=:) realfptype = float(real(eltype(x))) y = rand!(rng, similar(x, realfptype, _dropout_shape(x, dims))) y .= _dropout_kernel.(y, p, 1 - p) return y end function dropout(rng::AbstractRNG, x, prob, dims, training) if training rng = replicate(rng) mask = generate_dropout_mask(rng, x, prob; dims) return applydropout(x, mask), mask, rng else # Return `x` for type stability return x, x, rng end end applydropout(x, mask) = x .* mask # Adaptive Pooling function compute_adaptive_pooling_dims(x::AbstractArray, outsize) insize = size(x)[1:(end - 2)] stride = insize .÷ outsize k = insize .- (outsize .- 1) .* stride pad = 0 return PoolDims(x, k; padding=pad, stride=stride) end # Activation Functions ## I think this is handled by NNlibCUDA. But currently leaving here for ## benchmarking larger models const cudnnValidActivationTypes = Union{ typeof(tanh),typeof(sigmoid),typeof(relu),typeof(elu),typeof(tanh_fast),typeof(sigmoid_fast) } getCUDNNActivationMode(::Union{typeof(tanh),typeof(tanh_fast)}) = CUDA.CUDNN.CUDNN_ACTIVATION_TANH getCUDNNActivationMode(::Union{typeof(sigmoid),typeof(sigmoid_fast)}) = CUDA.CUDNN.CUDNN_ACTIVATION_SIGMOID getCUDNNActivationMode(::Union{typeof(relu)}) = CUDA.CUDNN.CUDNN_ACTIVATION_RELU getCUDNNActivationMode(::Union{typeof(elu)}) = CUDA.CUDNN.CUDNN_ACTIVATION_ELU @inline function applyactivation(f::Function, x::AbstractArray, ::Val{true}) x .= f.(x) end @inline applyactivation(f::Function, x::AbstractArray, ::Val{false}) = f.(x) @inline function applyactivation(f::cudnnValidActivationTypes, x::CuArray, ::Val{true}) return CUDA.CUDNN.cudnnActivationForward!(x, x; mode=getCUDNNActivationMode(f)) end @inline function applyactivation(f::cudnnValidActivationTypes, x::CuArray, ::Val{false}) return CUDA.CUDNN.cudnnActivationForward(x; mode=getCUDNNActivationMode(f)) end @inline applyactivation(::typeof(identity), x::AbstractArray, ::Val{true}) = x @inline applyactivation(::typeof(identity), x::AbstractArray, ::Val{false}) = x
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
2161
import .Flux """ transform(model) Convert a Flux Model to ExplicitFluxLayers Model. # Examples ```julia using ExplicitFluxLayers, Metalhead, Random m = ResNet(18) m2 = EFL.transform(m.layers) x = randn(Float32, 224, 224, 3, 1); ps, st = EFL.setup(Random.default_rng(), m2); m2(x, ps, st) ``` """ transform(::T) where {T} = error("Transformation for type $T not implemented") transform(model::Flux.Chain) = Chain(transform.(model.layers)...) function transform(model::Flux.BatchNorm) return BatchNorm( model.chs, model.λ; affine=model.affine, track_stats=model.track_stats, ϵ=model.ϵ, momentum=model.momentum ) end function transform(model::Flux.Conv) return Conv( size(model.weight)[1:(end - 2)], size(model.weight, ndims(model.weight) - 1) * model.groups => size(model.weight, ndims(model.weight)), model.σ; stride=model.stride, pad=model.pad, bias=model.bias isa Bool ? model.bias : !(model.bias isa Flux.Zeros), dilation=model.dilation, groups=model.groups, ) end function transform(model::Flux.SkipConnection) return SkipConnection(transform(model.layers), model.connection) end function transform(model::Flux.Dense) return Dense(size(model.weight, 2), size(model.weight, 1), model.σ) end function transform(model::Flux.MaxPool) return MaxPool(model.k, model.pad, model.stride) end function transform(model::Flux.MeanPool) return MeanPool(model.k, model.pad, model.stride) end function transform(::Flux.GlobalMaxPool) return GlobalMaxPool() end function transform(::Flux.GlobalMeanPool) return GlobalMeanPool() end function transform(p::Flux.AdaptiveMaxPool) return AdaptiveMaxPool(p.out) end function transform(p::Flux.AdaptiveMeanPool) return AdaptiveMeanPool(p.out) end function transform(model::Flux.Parallel) return Parallel(model.connection, transform.(model.layers)...) end function transform(d::Flux.Dropout) return Dropout(Float32(d.p); dims=d.dims) end transform(::typeof(identity)) = NoOpLayer() transform(::typeof(Flux.flatten)) = FlattenLayer() transform(f::Function) = WrappedFunction(f)
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
4467
## Quite a few of these are borrowed from Flux.jl # Misc nfan() = 1, 1 # fan_in, fan_out nfan(n) = 1, n # A vector is treated as a n×1 matrix nfan(n_out, n_in) = n_in, n_out # In case of Dense kernels: arranged as matrices nfan(dims::Tuple) = nfan(dims...) nfan(dims...) = prod(dims[1:end-2]) .* (dims[end-1], dims[end]) # In case of convolution kernels # Neural Network Initialization ## NOTE: Would be great if these could be moved into its own package and NN frameworks ## could just import it. zeros32(rng::AbstractRNG, args...; kwargs...) = zeros(rng, Float32, args...; kwargs...) ones32(rng::AbstractRNG, args...; kwargs...) = ones(rng, Float32, args...; kwargs...) Base.zeros(rng::AbstractRNG, args...; kwargs...) = zeros(args...; kwargs...) Base.ones(rng::AbstractRNG, args...; kwargs...) = ones(args...; kwargs...) function glorot_uniform(rng::AbstractRNG, dims::Integer...; gain::Real=1) scale = Float32(gain) * sqrt(24.0f0 / sum(nfan(dims...))) return (rand(rng, Float32, dims...) .- 0.5f0) .* scale end function glorot_normal(rng::AbstractRNG, dims::Integer...; gain::Real=1) std = Float32(gain) * sqrt(2.0f0 / sum(nfan(dims...))) return randn(rng, Float32, dims...) .* std end # PRNG Handling replicate(rng::AbstractRNG) = copy(rng) replicate(rng::CUDA.RNG) = deepcopy(rng) # Training Check @inline istraining() = false @inline istraining(st::NamedTuple) = st.training # Linear Algebra @inline _norm(x; dims=Colon()) = sqrt.(sum(abs2, x; dims=dims)) @inline _norm_except(x::AbstractArray{T,N}, except_dim=N) where {T,N} = _norm(x; dims=filter(i -> i != except_dim, 1:N)) # Convolution function convfilter(rng::AbstractRNG, filter::NTuple{N,Integer}, ch::Pair{<:Integer,<:Integer}; init = glorot_uniform, groups = 1) where N cin, cout = ch @assert cin % groups == 0 "Input channel dimension must be divisible by groups." @assert cout % groups == 0 "Output channel dimension must be divisible by groups." return init(rng, filter..., cin÷groups, cout) end expand(N, i::Tuple) = i expand(N, i::Integer) = ntuple(_ -> i, N) _maybetuple_string(pad) = string(pad) _maybetuple_string(pad::Tuple) = all(==(pad[1]), pad) ? string(pad[1]) : string(pad) # Padding struct SamePad end calc_padding(lt, pad, k::NTuple{N,T}, dilation, stride) where {T,N}= expand(Val(2*N), pad) function calc_padding(lt, ::SamePad, k::NTuple{N,T}, dilation, stride) where {N,T} # Ref: "A guide to convolution arithmetic for deep learning" https://arxiv.org/abs/1603.07285 # Effective kernel size, including dilation k_eff = @. k + (k - 1) * (dilation - 1) # How much total padding needs to be applied? pad_amt = @. k_eff - 1 # In case amount of padding is odd we need to apply different amounts to each side. return Tuple(mapfoldl(i -> [cld(i, 2), fld(i,2)], vcat, pad_amt)) end # Handling ComponentArrays ## NOTE: We should probably upsteam some of these Base.zero(c::ComponentArray{T,N,<:CuArray{T}}) where {T,N} = ComponentArray(zero(getdata(c)), getaxes(c)) Base.vec(c::ComponentArray{T,N,<:CuArray{T}}) where {T,N} = getdata(c) Base.:-(x::ComponentArray{T,N,<:CuArray{T}}) where {T,N} = ComponentArray(-getdata(x), getaxes(x)) function Base.similar(c::ComponentArray{T,N,<:CuArray{T}}, l::Vararg{Union{Integer,AbstractUnitRange}}) where {T,N} return similar(getdata(c), l) end function Functors.functor(::Type{<:ComponentArray}, c) return NamedTuple{propertynames(c)}(getproperty.((c,), propertynames(c))), ComponentArray end function Optimisers.update!(st, ps::ComponentArray, gs::ComponentArray) Optimisers.update!(st, NamedTuple(ps), NamedTuple(gs)) return st, ps end function ComponentArrays.make_carray_args(nt::NamedTuple) data, ax = ComponentArrays.make_carray_args(Vector, nt) data = length(data) == 0 ? Float32[] : (length(data)==1 ? [data[1]] : reduce(vcat, data)) return (data, ax) end ## For being able to print empty ComponentArrays function ComponentArrays.last_index(f::FlatAxis) nt = ComponentArrays.indexmap(f) length(nt) == 0 && return 0 return ComponentArrays.last_index(last(nt)) end ComponentArrays.recursive_length(nt::NamedTuple{(), Tuple{}}) = 0 # Return Nothing if field not present function safegetproperty(x::Union{ComponentArray,NamedTuple}, k::Symbol) k ∈ propertynames(x) && return getproperty(x, k) return nothing end # Getting typename get_typename(::T) where {T} = Base.typename(T).wrapper
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
16826
""" ReshapeLayer(dims) Reshapes the passed array to have a size of `(dims..., :)` """ struct ReshapeLayer{N} <: AbstractExplicitLayer dims::NTuple{N,Int} end @inline function (r::ReshapeLayer)(x::AbstractArray, ps, st::NamedTuple) return reshape(x, r.dims..., :), st end """ FlattenLayer() Flattens the passed array into a matrix. """ struct FlattenLayer <: AbstractExplicitLayer end @inline function (f::FlattenLayer)(x::AbstractArray{T,N}, ps, st::NamedTuple) where {T,N} return reshape(x, :, size(x, N)), st end """ SelectDim(dim, i) See the documentation for `selectdim` for more information. """ struct SelectDim{I} <: AbstractExplicitLayer dim::Int i::I end @inline (s::SelectDim)(x, ps, st::NamedTuple) = selectdim(x, s.dim, s.i), st """ NoOpLayer() As the name suggests does nothing but allows pretty printing of layers. """ struct NoOpLayer <: AbstractExplicitLayer end @inline (noop::NoOpLayer)(x, ps, st::NamedTuple) = x, st """ WrappedFunction(f) Wraps a stateless and parameter less function. Might be used when a function is added to [Chain](@doc). For example, `Chain(x -> relu.(x))` would not work and the right thing to do would be `Chain((x, ps, st) -> (relu.(x), st))`. An easier thing to do would be `Chain(WrappedFunction(Base.Fix1(broadcast, relu)))` """ struct WrappedFunction{F} <: AbstractExplicitLayer func::F end (wf::WrappedFunction)(x, ps, st::NamedTuple) = wf.func(x), st function Base.show(io::IO, w::WrappedFunction) return print(io, "WrappedFunction(", w.func, ")") end """ ActivationFunction(f) Broadcast `f` on the input but fallback to CUDNN for Backward Pass """ struct ActivationFunction{F} <: AbstractExplicitLayer func::F end initialstates(::AbstractRNG, ::ActivationFunction) = (training=true,) (af::ActivationFunction)(x, ps, st::NamedTuple) = applyactivation(af.func, x, Val(false)), st function Base.show(io::IO, af::ActivationFunction) return print(io, "ActivationFunction(", af.func, ")") end """ SkipConnection(layer, connection) Create a skip connection which consists of a layer or `Chain` of consecutive layers and a shortcut connection linking the block's input to the output through a user-supplied 2-argument callable. The first argument to the callable will be propagated through the given `layer` while the second is the unchanged, "skipped" input. The simplest "ResNet"-type connection is just `SkipConnection(layer, +)`. """ struct SkipConnection{T<:AbstractExplicitLayer,F} <: AbstractExplicitContainerLayer{(:layers,)} layers::T connection::F end @inline function (skip::SkipConnection)(input, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) mx, st = skip.layers(input, ps, st) return skip.connection(mx, input), st end """ Parallel(connection, layers...) Behaves differently on different input types: * If `x` is a Tuple then each element is passed to each layer * Otherwise, `x` is directly passed to all layers """ struct Parallel{F,T<:NamedTuple} <: AbstractExplicitContainerLayer{(:layers,)} connection::F layers::T end function Parallel(connection, layers...) names = ntuple(i -> Symbol("layer_$i"), length(layers)) return Parallel(connection, NamedTuple{names}(layers)) end function Parallel(connection; kw...) layers = NamedTuple(kw) if :layers in Base.keys(layers) || :connection in Base.keys(layers) throw(ArgumentError("a Parallel layer cannot have a named sub-layer called `connection` or `layers`")) end isempty(layers) && throw(ArgumentError("a Parallel layer must have at least one sub-layer")) return Parallel(connection, layers) end function (m::Parallel)(x, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) return applyparallel(m.layers, m.connection, x, ps, st) end @generated function applyparallel( layers::NamedTuple{names}, connection::C, x::T, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple ) where {names,C,T} N = length(names) y_symbols = [gensym() for _ in 1:(N + 1)] st_symbols = [gensym() for _ in 1:N] getinput(i) = T <: Tuple ? :(x[$i]) : :x calls = [] append!( calls, [ :(($(y_symbols[i]), $(st_symbols[i])) = layers[$i]($(getinput(i)), ps.$(names[i]), st.$(names[i]))) for i in 1:N ], ) append!(calls, [:(st = NamedTuple{$names}((($(Tuple(st_symbols)...),))))]) if C == Nothing append!(calls, [:($(y_symbols[N + 1]) = tuple($(Tuple(y_symbols[1:N])...)))]) else append!(calls, [:($(y_symbols[N + 1]) = connection($(Tuple(y_symbols[1:N])...)))]) end append!(calls, [:(return $(y_symbols[N + 1]), st)]) return Expr(:block, calls...) end Base.keys(m::Parallel) = Base.keys(getfield(m, :layers)) """ BranchLayer(layers...) Takes an input `x` and passes it through all the `layers` and returns a tuple of the outputs. This is slightly different from `Parallel(nothing, layers...)` - If the input is a tuple Parallel will pass each element individually to each layer - `BranchLayer` essentially assumes 1 input comes in and is branched out into `N` outputs An easy way to replicate an input to an NTuple is to do ```julia l = EFL.BranchLayer( EFL.NoOpLayer(), EFL.NoOpLayer(), EFL.NoOpLayer(), ) ``` """ struct BranchLayer{T<:NamedTuple} <: AbstractExplicitContainerLayer{(:layers,)} layers::T end function BranchLayer(layers...) names = ntuple(i -> Symbol("layer_$i"), length(layers)) return BranchLayer(NamedTuple{names}(layers)) end function BranchLayer(; kwargs...) layers = NamedTuple(kwargs) if :layers in Base.keys(layers) throw(ArgumentError("A BranchLayer cannot have a named sub-layer called `layers`")) end isempty(layers) && throw(ArgumentError("A BranchLayer must have at least one sub-layer")) return BranchLayer(layers) end (m::BranchLayer)(x, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) = applybranching(m.layers, x, ps, st) @generated function applybranching( layers::NamedTuple{names}, x, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple ) where {names} N = length(names) y_symbols = [gensym() for _ in 1:N] st_symbols = [gensym() for _ in 1:N] calls = [] append!( calls, [:(($(y_symbols[i]), $(st_symbols[i])) = layers[$i](x, ps.$(names[i]), st.$(names[i]))) for i in 1:N] ) append!(calls, [:(st = NamedTuple{$names}((($(Tuple(st_symbols)...),))))]) append!(calls, [:(return tuple($(Tuple(y_symbols)...)), st)]) return Expr(:block, calls...) end Base.keys(m::BranchLayer) = Base.keys(getfield(m, :layers)) """ PairwiseFusion(connection, layers...) Layer behaves differently based on input type: 1. Input `x` is a tuple of length `N` then the `layers` must be a tuple of length `N`. The computation is as follows ```julia y = x[1] for i in 1:N y = connection(x[i], layers[i](y)) end ``` 2. Any other kind of input ```julia y = x for i in 1:N y = connection(x, layers[i](y)) end ``` """ struct PairwiseFusion{F,T<:NamedTuple} <: AbstractExplicitContainerLayer{(:layers,)} connection::F layers::T end function PairwiseFusion(connection, layers...) names = ntuple(i -> Symbol("layer_$i"), length(layers)) return PairwiseFusion(connection, NamedTuple{names}(layers)) end function PairwiseFusion(connection; kw...) layers = NamedTuple(kw) if :layers in Base.keys(layers) || :connection in Base.keys(layers) throw(ArgumentError("a PairwiseFusion layer cannot have a named sub-layer called `connection` or `layers`")) end isempty(layers) && throw(ArgumentError("a PairwiseFusion layer must have at least one sub-layer")) return PairwiseFusion(connection, layers) end function (m::PairwiseFusion)(x, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) return applypairwisefusion(m.layers, m.connection, x, ps, st) end @generated function applypairwisefusion( layers::NamedTuple{names}, connection::C, x::T, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple ) where {names,C,T} N = length(names) y_symbols = [gensym() for _ in 1:(N + 1)] st_symbols = [gensym() for _ in 1:N] getinput(i) = T <: Tuple ? :(x[$i]) : :x calls = [:($(y_symbols[N + 1]) = $(getinput(1)))] for i in 1:N push!( calls, :(($(y_symbols[i]), $(st_symbols[i])) = layers[$i]($(y_symbols[N + 1]), ps.$(names[i]), st.$(names[i]))), ) push!(calls, :($(y_symbols[N + 1]) = connection($(y_symbols[i]), $(getinput(i + 1))))) end append!(calls, [:(st = NamedTuple{$names}((($(Tuple(st_symbols)...),))))]) append!(calls, [:(return $(y_symbols[N + 1]), st)]) return Expr(:block, calls...) end Base.keys(m::PairwiseFusion) = Base.keys(getfield(m, :layers)) """ Chain(layers...; disable_optimizations::Bool = false) Collects multiple layers / functions to be called in sequence on a given input. Performs a few optimizations to generate reasonable architectures. Can be disabled using keyword argument `disable_optimizations`. * All sublayers are recursively optimized. * If a function `f` is passed as a layer and it doesn't take 3 inputs, it is converted to a WrappedFunction(`f`) which takes only one input. * If the layer is a Chain, it is expanded out. * `NoOpLayer`s are removed. * If there is only 1 layer (left after optimizations), then it is returned without the `Chain` wrapper. * If there are no layers (left after optimizations), a `NoOpLayer` is returned. """ struct Chain{T} <: AbstractExplicitContainerLayer{(:layers,)} layers::T function Chain(xs...; disable_optimizations::Bool=false) xs = disable_optimizations ? xs : flatten_model(xs) length(xs) == 0 && return NoOpLayer() length(xs) == 1 && return first(xs) names = ntuple(i -> Symbol("layer_$i"), length(xs)) layers = NamedTuple{names}(xs) return new{typeof(layers)}(layers) end Chain(xs::AbstractVector; disable_optimizations::Bool=false) = Chain(xs...; disable_optimizations) end function flatten_model(layers::Union{AbstractVector,Tuple}) new_layers = [] for l in layers f = flatten_model(l) if f isa Tuple || f isa AbstractVector append!(new_layers, f) elseif f isa Function if !hasmethod(f, (Any, Union{ComponentArray,NamedTuple}, NamedTuple)) push!(new_layers, WrappedFunction(f)) else push!(new_layers, f) end elseif f isa Chain append!(new_layers, f.layers) elseif f isa NoOpLayer continue else push!(new_layers, f) end end return layers isa AbstractVector ? new_layers : Tuple(new_layers) end flatten_model(x) = x (c::Chain)(x, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) = applychain(c.layers, x, ps, st) @generated function applychain( layers::NamedTuple{fields}, x, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple{fields} ) where {fields} N = length(fields) x_symbols = [gensym() for _ in 1:N] st_symbols = [gensym() for _ in 1:N] calls = [:(($(x_symbols[1]), $(st_symbols[1])) = layers[1](x, ps.layer_1, st.layer_1))] append!( calls, [ :(($(x_symbols[i]), $(st_symbols[i])) = layers[$i]($(x_symbols[i - 1]), ps.$(fields[i]), st.$(fields[i]))) for i in 2:N ], ) append!(calls, [:(st = NamedTuple{$fields}((($(Tuple(st_symbols)...),))))]) append!(calls, [:(return $(x_symbols[N]), st)]) return Expr(:block, calls...) end Base.keys(m::Chain) = Base.keys(getfield(m, :layers)) """ Dense(in => out, σ=identity; initW=glorot_uniform, initb=zeros32, bias::Bool=true) Create a traditional fully connected layer, whose forward pass is given by: `y = σ.(weight * x .+ bias)` * The input `x` should be a vector of length `in`, or batch of vectors represented as an `in × N` matrix, or any array with `size(x,1) == in`. * The output `y` will be a vector of length `out`, or a batch with `size(y) == (out, size(x)[2:end]...)` Keyword `bias=false` will switch off trainable bias for the layer. The initialisation of the weight matrix is `W = initW(rng, out, in)`, calling the function given to keyword `initW`, with default [`glorot_uniform`](@doc Flux.glorot_uniform). """ struct Dense{bias,F1,F2,F3} <: AbstractExplicitLayer λ::F1 in_dims::Int out_dims::Int initW::F2 initb::F3 end function Base.show(io::IO, d::Dense{bias}) where {bias} print(io, "Dense($(d.in_dims) => $(d.out_dims)") (d.λ == identity) || print(io, ", $(d.λ)") bias || print(io, ", bias=false") return print(io, ")") end function Dense(mapping::Pair{<:Int,<:Int}, λ=identity; initW=glorot_uniform, initb=zeros32, bias::Bool=true) return Dense(first(mapping), last(mapping), λ; initW=initW, initb=initb, bias=bias) end function Dense(in_dims::Int, out_dims::Int, λ=identity; initW=glorot_uniform, initb=zeros32, bias::Bool=true) λ = NNlib.fast_act(λ) return Dense{bias,typeof(λ),typeof(initW),typeof(initb)}(λ, in_dims, out_dims, initW, initb) end function initialparameters(rng::AbstractRNG, d::Dense{bias}) where {bias} if bias return (weight=d.initW(rng, d.out_dims, d.in_dims), bias=d.initb(rng, d.out_dims, 1)) else return (weight=d.initW(rng, d.out_dims, d.in_dims),) end end parameterlength(d::Dense{bias}) where {bias} = bias ? d.out_dims * (d.in_dims + 1) : d.out_dims * d.in_dims statelength(d::Dense) = 0 @inline function (d::Dense{false})(x::AbstractArray, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) return applyactivation(d.λ, ps.weight * x, Val(false)), st end @inline function (d::Dense{false,typeof(identity)})( x::AbstractArray, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple ) return ps.weight * x, st end @inline function (d::Dense{true})(x::AbstractArray, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) return applyactivation(d.λ, ps.weight * x .+ ps.bias, Val(false)), st end @inline function (d::Dense{true,typeof(identity)})( x::AbstractArray, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple ) return ps.weight * x .+ ps.bias, st end @inline function (d::Dense{true})(x::AbstractVector, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) return applyactivation(d.λ, ps.weight * x .+ vec(ps.bias), Val(false)), st end @inline function (d::Dense{true,typeof(identity)})( x::AbstractVector, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple ) return ps.weight * x .+ vec(ps.bias), st end """ Scale(dims, σ=identity; initW=ones32, initb=zeros32, bias::Bool=true) Create a Sparsely Connected Layer with a very specific structure (only Diagonal Elements are non-zero). The forward pass is given by: `y = σ.(weight .* x .+ bias)` * The input `x` should be a vector of length `dims`, or batch of vectors represented as an `in × N` matrix, or any array with `size(x,1) == in`. * The output `y` will be a vector of length `dims`, or a batch with `size(y) == (dims, size(x)[2:end]...)` Keyword `bias=false` will switch off trainable bias for the layer. The initialisation of the weight matrix is `W = initW(rng, dims)`, calling the function given to keyword `initW`, with default [`glorot_uniform`](@doc Flux.glorot_uniform). """ struct Scale{bias,F1,D,F2,F3} <: AbstractExplicitLayer λ::F1 dims::D initW::F2 initb::F3 end function Base.show(io::IO, d::Scale) print(io, "Scale($(d.dims)") (d.λ == identity) || print(io, ", $(d.λ)") return print(io, ")") end function Scale(dims, λ=identity; initW=glorot_uniform, initb=zeros32, bias::Bool=true) λ = NNlib.fast_act(λ) return Scale{bias,typeof(λ),typeof(dims),typeof(initW),typeof(initb)}(λ, dims, initW, initb) end function initialparameters(rng::AbstractRNG, d::Scale{true}) return (weight=d.initW(rng, d.dims), bias=d.initb(rng, d.dims)) end initialparameters(rng::AbstractRNG, d::Scale{false}) = (weight=d.initW(rng, d.dims),) parameterlength(d::Scale{bias}) where {bias} = (1 + bias) * d.dims statelength(d::Scale) = 0 function (d::Scale{true})(x::AbstractArray, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) return applyactivation(d.λ, ps.weight .* x .+ ps.bias, Val(false)), st end function (d::Scale{true,typeof(identity)})(x::AbstractArray, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) return ps.weight .* x .+ ps.bias, st end function (d::Scale{false})(x::AbstractArray, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) return applyactivation(d.λ, ps.weight .* x, Val(false)), st end function (d::Scale{false,typeof(identity)})(x::AbstractArray, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) return ps.weight .* x, st end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
11740
""" Conv(filter, in => out, σ = identity; stride = 1, pad = 0, dilation = 1, groups = 1, [bias, initW]) Standard convolutional layer. # Arguments * `filter` is a tuple of integers specifying the size of the convolutional kernel * `in` and `out` specify the number of input and output channels. Image data should be stored in WHCN order (width, height, channels, batch). In other words, a 100×100 RGB image would be a `100×100×3×1` array, and a batch of 50 would be a `100×100×3×50` array. This has `N = 2` spatial dimensions, and needs a kernel size like `(5,5)`, a 2-tuple of integers. To take convolutions along `N` feature dimensions, this layer expects as input an array with `ndims(x) == N+2`, where `size(x, N+1) == in` is the number of input channels, and `size(x, ndims(x))` is (as always) the number of observations in a batch. * `filter` should be a tuple of `N` integers. * Keywords `stride` and `dilation` should each be either single integer, or a tuple with `N` integers. * Keyword `pad` specifies the number of elements added to the borders of the data array. It can be - a single integer for equal padding all around, - a tuple of `N` integers, to apply the same padding at begin/end of each spatial dimension, - a tuple of `2*N` integers, for asymmetric padding, or - the singleton `SamePad()`, to calculate padding such that `size(output,d) == size(x,d) / stride` (possibly rounded) for each spatial dimension. * Keyword `groups` is expected to be an `Int`. It specifies the number of groups to divide a convolution into. Keywords to control initialization of the layer: * `initW` - Function used to generate initial weights. Defaults to `glorot_uniform`. * `bias` - The initial bias vector is all zero by default. Trainable bias can be disabled entirely by setting this to `false`. """ struct Conv{N,bias,M,F1,F2} <: AbstractExplicitLayer λ::F1 in_chs::Int out_chs::Int kernel_size::NTuple{N,Int} stride::NTuple{N,Int} pad::NTuple{M,Int} dilation::NTuple{N,Int} groups::Int initW::F2 end function Conv( k::NTuple{N,Integer}, ch::Pair{<:Integer,<:Integer}, λ=identity; initW=glorot_uniform, stride=1, pad=0, dilation=1, groups=1, bias=true, ) where {N} stride = expand(Val(N), stride) dilation = expand(Val(N), dilation) pad = calc_padding(Conv, pad, k, dilation, stride) λ = NNlib.fast_act(λ) return Conv{N,bias,length(pad),typeof(λ),typeof(initW)}( λ, first(ch), last(ch), k, stride, pad, dilation, groups, initW ) end function initialparameters(rng::AbstractRNG, c::Conv{N,bias}) where {N,bias} weight = convfilter(rng, c.kernel_size, c.in_chs => c.out_chs; init=c.initW, groups=c.groups) return bias ? (weight=weight, bias=zeros(eltype(weight), ntuple(_ -> 1, N)..., c.out_chs, 1)) : (weight=weight,) end function parameterlength(c::Conv{N,bias}) where {N,bias} return prod(c.kernel_size) * c.in_chs * c.out_chs ÷ c.groups + (bias ? c.out_chs : 0) end @inline function (c::Conv{N,false})(x::AbstractArray, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) where {N} cdims = DenseConvDims(x, ps.weight; stride=c.stride, padding=c.pad, dilation=c.dilation, groups=c.groups) return applyactivation(c.λ, conv_wrapper(x, ps.weight, cdims), Val(false)), st end @inline function (c::Conv{N,true})(x::AbstractArray, ps::Union{ComponentArray,NamedTuple}, st::NamedTuple) where {N} cdims = DenseConvDims(x, ps.weight; stride=c.stride, padding=c.pad, dilation=c.dilation, groups=c.groups) return applyactivation(c.λ, conv_wrapper(x, ps.weight, cdims) .+ ps.bias, Val(false)), st end function Base.show(io::IO, l::Conv) print(io, "Conv(", l.kernel_size) print(io, ", ", l.in_chs, " => ", l.out_chs) _print_conv_opt(io, l) return print(io, ")") end function _print_conv_opt(io::IO, l::Conv{N,bias}) where {N,bias} l.λ == identity || print(io, ", ", l.λ) all(==(0), l.pad) || print(io, ", pad=", _maybetuple_string(l.pad)) all(==(1), l.stride) || print(io, ", stride=", _maybetuple_string(l.stride)) all(==(1), l.dilation) || print(io, ", dilation=", _maybetuple_string(l.dilation)) (l.groups == 1) || print(io, ", groups=", l.groups) (bias == false) && print(io, ", bias=false") return nothing end """ MaxPool(window::NTuple; pad=0, stride=window) # Arguments * Max pooling layer, which replaces all pixels in a block of size `window` with one. * Expects as input an array with `ndims(x) == N+2`, i.e. channel and batch dimensions, after the `N` feature dimensions, where `N = length(window)`. * By default the window size is also the stride in each dimension. * The keyword `pad` accepts the same options as for the [`Conv`](@ref) layer, including `SamePad()`. See also [`Conv`](@ref), [`MeanPool`](@ref), [`GlobalMaxPool`](@ref). """ struct MaxPool{N,M} <: AbstractExplicitLayer k::NTuple{N,Int} pad::NTuple{M,Int} stride::NTuple{N,Int} end function MaxPool(k::NTuple{N,Integer}; pad=0, stride=k) where {N} stride = expand(Val(N), stride) pad = calc_padding(MaxPool, pad, k, 1, stride) return MaxPool{N,length(pad)}(k, pad, stride) end function (m::MaxPool{N,M})(x, ps, st::NamedTuple) where {N,M} pdims = PoolDims(x, m.k; padding=m.pad, stride=m.stride) return maxpool(x, pdims), st end function Base.show(io::IO, m::MaxPool) print(io, "MaxPool(", m.k) all(==(0), m.pad) || print(io, ", pad=", _maybetuple_string(m.pad)) m.stride == m.k || print(io, ", stride=", _maybetuple_string(m.stride)) return print(io, ")") end """ MeanPool(window::NTuple; pad=0, stride=window) # Arguments * Mean pooling layer, which replaces all pixels in a block of size `window` with one. * Expects as input an array with `ndims(x) == N+2`, i.e. channel and batch dimensions, after the `N` feature dimensions, where `N = length(window)`. * By default the window size is also the stride in each dimension. * The keyword `pad` accepts the same options as for the [`Conv`](@ref) layer, including `SamePad()`. See also [`Conv`](@ref), [`MaxPool`](@ref), [`GlobalMeanPool`](@ref). """ struct MeanPool{N,M} <: AbstractExplicitLayer k::NTuple{N,Int} pad::NTuple{M,Int} stride::NTuple{N,Int} end function MeanPool(k::NTuple{N,Integer}; pad=0, stride=k) where {N} stride = expand(Val(N), stride) pad = calc_padding(MeanPool, pad, k, 1, stride) return MeanPool{N,length(pad)}(k, pad, stride) end function (m::MeanPool{N,M})(x, ps, st::NamedTuple) where {N,M} pdims = PoolDims(x, m.k; padding=m.pad, stride=m.stride) return meanpool(x, pdims), st end function Base.show(io::IO, m::MeanPool) print(io, "MeanPool(", m.k) all(==(0), m.pad) || print(io, ", pad=", _maybetuple_string(m.pad)) m.stride == m.k || print(io, ", stride=", _maybetuple_string(m.stride)) return print(io, ")") end """ Upsample(mode = :nearest; [scale, size]) Upsample(scale, mode = :nearest) An upsampling layer. # Arguments One of two keywords must be given: * If `scale` is a number, this applies to all but the last two dimensions (channel and batch) of the input. It may also be a tuple, to control dimensions individually. * Alternatively, keyword `size` accepts a tuple, to directly specify the leading dimensions of the output. Currently supported upsampling `mode`s and corresponding NNlib's methods are: - `:nearest` -> [`NNlib.upsample_nearest`](@ref) - `:bilinear` -> [`NNlib.upsample_bilinear`](@ref) - `:trilinear` -> [`NNlib.upsample_trilinear`](@ref) """ struct Upsample{mode,S,T} <: AbstractExplicitLayer scale::S size::T end function Upsample(mode::Symbol=:nearest; scale=nothing, size=nothing) mode in [:nearest, :bilinear, :trilinear] || throw(ArgumentError("mode=:$mode is not supported.")) if !(isnothing(scale) ⊻ isnothing(size)) throw(ArgumentError("Either scale or size should be specified (but not both).")) end return Upsample{mode,typeof(scale),typeof(size)}(scale, size) end Upsample(scale, mode::Symbol=:nearest) = Upsample(mode; scale) function (m::Upsample{:nearest})(x::AbstractArray, ps, st::NamedTuple) return NNlib.upsample_nearest(x, m.scale), st end function (m::Upsample{:nearest,Int})(x::AbstractArray{T,N}, ps, st::NamedTuple) where {T,N} return NNlib.upsample_nearest(x, ntuple(i -> m.scale, N - 2)), st end function (m::Upsample{:nearest,Nothing})(x::AbstractArray, ps, st::NamedTuple) return NNlib.upsample_nearest(x; size=m.size), st end function (m::Upsample{:bilinear})(x::AbstractArray, ps, st::NamedTuple) return NNlib.upsample_bilinear(x, m.scale), st end function (m::Upsample{:bilinear,Nothing})(x::AbstractArray, ps, st::NamedTuple) return NNlib.upsample_bilinear(x; size=m.size), st end function (m::Upsample{:trilinear})(x::AbstractArray, ps, st::NamedTuple) return NNlib.upsample_trilinear(x, m.scale), st end function (m::Upsample{:trilinear,Nothing})(x::AbstractArray, ps, st::NamedTuple) return NNlib.upsample_trilinear(x; size=m.size), st end function Base.show(io::IO, u::Upsample{mode}) where {mode} print(io, "Upsample(") print(io, ":", mode) u.scale !== nothing && print(io, ", scale = $(u.scale)") u.size !== nothing && print(io, ", size = $(u.size)") return print(io, ")") end """ GlobalMeanPool() Global Mean Pooling layer. Transforms (w,h,c,b)-shaped input into (1,1,c,b)-shaped output, by performing max pooling on the complete (w,h)-shaped feature maps. See also [`MeanPool`](@ref), [`GlobalMaxPool`](@ref). """ struct GlobalMeanPool <: AbstractExplicitLayer end function (g::GlobalMeanPool)(x, ps, st::NamedTuple) return meanpool(x, PoolDims(x, size(x)[1:(end - 2)])), st end """ GlobalMaxPool() Global Max Pooling layer. Transforms (w,h,c,b)-shaped input into (1,1,c,b)-shaped output, by performing max pooling on the complete (w,h)-shaped feature maps. See also [`MaxPool`](@ref), [`GlobalMeanPool`](@ref). """ struct GlobalMaxPool <: AbstractExplicitLayer end function (g::GlobalMaxPool)(x, ps, st::NamedTuple) return maxpool(x, PoolDims(x, size(x)[1:(end - 2)])), st end """ AdaptiveMaxPool(out::NTuple) Adaptive Max Pooling layer. Calculates the necessary window size such that its output has `size(y)[1:N] == out`. Expects as input an array with `ndims(x) == N+2`, i.e. channel and batch dimensions, after the `N` feature dimensions, where `N = length(out)`. See also [`MaxPool`](@ref), [`AdaptiveMeanPool`](@ref). """ struct AdaptiveMaxPool{S,O} <: AbstractExplicitLayer out::NTuple{O,Int} AdaptiveMaxPool(out::NTuple{O,Int}) where {O} = new{O + 2,O}(out) end function (a::AdaptiveMaxPool{S})(x::AbstractArray{T,S}, ps, st::NamedTuple) where {S,T} pdims = compute_adaptive_pooling_dims(x, a.out) return maxpool(x, pdims), st end function Base.show(io::IO, a::AdaptiveMaxPool) return print(io, "AdaptiveMaxPool(", a.out, ")") end """ AdaptiveMeanPool(out::NTuple) Adaptive Mean Pooling layer. Calculates the necessary window size such that its output has `size(y)[1:N] == out`. Expects as input an array with `ndims(x) == N+2`, i.e. channel and batch dimensions, after the `N` feature dimensions, where `N = length(out)`. See also [`MaxPool`](@ref), [`AdaptiveMaxPool`](@ref). """ struct AdaptiveMeanPool{S,O} <: AbstractExplicitLayer out::NTuple{O,Int} AdaptiveMeanPool(out::NTuple{O,Int}) where {O} = new{O + 2,O}(out) end function (a::AdaptiveMeanPool{S})(x::AbstractArray{T,S}, ps, st::NamedTuple) where {S,T} pdims = compute_adaptive_pooling_dims(x, a.out) return meanpool(x, pdims), st end function Base.show(io::IO, a::AdaptiveMeanPool) return print(io, "AdaptiveMeanPool(", a.out, ")") end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
5314
function Base.show(io::IO, ::MIME"text/plain", x::AbstractExplicitContainerLayer) if get(io, :typeinfo, nothing) === nothing # e.g. top level in REPL _big_show(io, x) elseif !get(io, :compact, false) # e.g. printed inside a Vector, but not a Matrix _layer_show(io, x) else show(io, x) end end function _big_show(io::IO, obj, indent::Int=0, name=nothing) pre, post = "(", ")" children = _get_children(obj) if obj isa Function println(io, " "^indent, isnothing(name) ? "" : "$name = ", obj) elseif all(_show_leaflike, children) _layer_show(io, obj, indent, name) else println(io, " "^indent, isnothing(name) ? "" : "$name = ", nameof(typeof(obj)), pre) if obj isa Chain{<:NamedTuple} for k in Base.keys(obj) _big_show(io, obj.layers[k], indent + 4, k) end elseif obj isa Parallel{<:Any,<:NamedTuple} if obj.connection !== nothing _big_show(io, obj.connection, indent + 4) end for k in Base.keys(obj) _big_show(io, obj.layers[k], indent + 4, k) end elseif obj isa PairwiseFusion _big_show(io, obj.connection, indent + 4) for k in Base.keys(obj) _big_show(io, obj.layers[k], indent + 4, k) end elseif obj isa BranchLayer for k in Base.keys(obj) _big_show(io, obj.layers[k], indent + 4, k) end else if children isa NamedTuple for (k, c) in pairs(children) _big_show(io, c, indent + 4, k) end else for c in children _big_show(io, c, indent + 4) end end end if indent == 0 # i.e. this is the outermost container print(io, rpad(post, 2)) _big_finale(io, obj) else println(io, " "^indent, post, ",") end end end _show_leaflike(x) = Functors.isleaf(x) # mostly follow Functors, except for: _show_leaflike(x::AbstractExplicitLayer) = false _show_leaflike(::Tuple{Vararg{<:Number}}) = true # e.g. stride of Conv _show_leaflike(::Tuple{Vararg{<:AbstractArray}}) = true # e.g. parameters of LSTMcell function _get_children(l::AbstractExplicitContainerLayer{names}) where {names} # length(names) == 1 && return getfield(l, names[1]) return NamedTuple{names}(getfield.((l,), names)) end _get_children(p::Parallel) = p.connection === nothing ? p.layers : (p.connection, p.layers...) _get_children(s::SkipConnection) = (s.layers, s.connection) _get_children(s::WeightNorm) = (s.layer,) _get_children(::Any) = () function Base.show(io::IO, ::MIME"text/plain", x::AbstractExplicitLayer) if !get(io, :compact, false) _layer_show(io, x) else show(io, x) end end function _layer_show(io::IO, layer, indent::Int=0, name=nothing) _str = isnothing(name) ? "" : "$name = " str = _str * sprint(show, layer; context=io) print(io, " "^indent, str, indent == 0 ? "" : ",") paramlength = parameterlength(layer) if paramlength > 0 print(io, " "^max(2, (indent == 0 ? 20 : 39) - indent - length(str))) printstyled(io, "# ", underscorise(paramlength), " parameters"; color=:light_black) nonparam = statelength(layer) if nonparam > 0 printstyled(io, ", plus ", underscorise(nonparam), indent == 0 ? " non-trainable" : ""; color=:light_black) end end return indent == 0 || println(io) end function _big_finale(io::IO, m) paramlength = parameterlength(m) nonparamlength = statelength(m) pars = underscorise(paramlength) bytes = Base.format_bytes(Base.summarysize(m)) nonparam = underscorise(nonparamlength) printstyled(io, " "^08, "# Total: "; color=:light_black) println(io, pars, " parameters,") printstyled(io, " "^10, "# plus "; color=:light_black) print(io, nonparam, " states, ") printstyled(io, "summarysize "; color=:light_black) print(io, bytes, ".") end _childarray_sum(f, x::AbstractArray{<:Number}) = f(x) function _childarray_sum(f, x::ComponentArray) if Flux.Functors.isleaf(x) return 0 else c = Flux.Functors.children(x) if length(c) == 0 return 0 else return sum(y -> _childarray_sum(f, y), c) end end end function _childarray_sum(f, x) if Flux.Functors.isleaf(x) return 0 else c = Flux.Functors.children(x) if length(c) == 0 return 0 else return sum(y -> _childarray_sum(f, y), c) end end end # utility functions underscorise(n::Integer) = join(reverse(join.(reverse.(Iterators.partition(digits(n), 3)))), '_') function _nan_show(io::IO, x) if !isempty(x) && _all(iszero, x) printstyled(io, " (all zero)"; color=:cyan) elseif _any(isnan, x) printstyled(io, " (some NaN)"; color=:red) elseif _any(isinf, x) printstyled(io, " (some Inf)"; color=:red) end end _any(f, xs::AbstractArray{<:Number}) = any(f, xs) _any(f, xs) = any(x -> _any(f, x), xs) _any(f, x::Number) = f(x) _all(f, xs) = !_any(!f, xs)
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
2543
""" Dropout(p; dims=:) Dropout layer. # Arguments * To apply dropout along certain dimension(s), specify the `dims` keyword. e.g. `Dropout(p; dims = 3)` will randomly zero out entire channels on WHCN input (also called 2D dropout). * Each execution of the Layer increments the `seed` and returns it wrapped in the state Call [`testmode`](@ref) to switch to test mode. """ struct Dropout{T,D} <: AbstractExplicitLayer p::T dims::D end function initialstates(rng::AbstractRNG, ::Dropout) # FIXME: Take PRNGs seriously randn(rng, 1) return (rng=replicate(rng), training=true) end function Dropout(p; dims=:) @assert 0 ≤ p ≤ 1 return Dropout(p, dims) end function (d::Dropout{T})(x::AbstractArray{T}, ps, st::NamedTuple) where {T} y, _, rng = dropout(st.rng, x, d.p, d.dims, istraining(st)) return y, merge(st, (rng=rng,)) end function Base.show(io::IO, d::Dropout) print(io, "Dropout(", d.p) d.dims != Colon() && print(io, ", dims=", d.dims) return print(io, ")") end """ VariationalHiddenDropout(p; dims=:) VariationalHiddenDropout layer. The only difference from Dropout is that the `mask` is retained until `EFL.update_state(l, :update_mask, true)` is called. # Arguments * To apply dropout along certain dimension(s), specify the `dims` keyword. e.g. `Dropout(p; dims = 3)` will randomly zero out entire channels on WHCN input (also called 2D dropout). * Each execution of the Layer increments the `seed` and returns it wrapped in the state Call [`testmode`](@ref) to switch to test mode. """ struct VariationalHiddenDropout{T,D} <: AbstractExplicitLayer p::T dims::D end function initialstates(rng::AbstractRNG, ::VariationalHiddenDropout) # FIXME: Take PRNGs seriously randn(rng, 1) return (rng=replicate(rng), training=true, update_mask=true) end function VariationalHiddenDropout(p; dims=:) @assert 0 ≤ p ≤ 1 return VariationalHiddenDropout(p, dims) end function (d::VariationalHiddenDropout{T})(x::AbstractArray{T}, ps, st::NamedTuple) where {T} if st.update_mask y, mask, rng = dropout(st.rng, x, d.p, d.dims, istraining(st)) return y, (mask=mask, rng=rng, update_mask=false, training=st.training) else if !istraining(st) return x, st end return applydropout(x, st.mask), st end end function Base.show(io::IO, d::VariationalHiddenDropout) print(io, "VariationalHiddenDropout(", d.p) d.dims != Colon() && print(io, ", dims=", d.dims) return print(io, ")") end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
11969
abstract type AbstractNormalizationLayer{affine,track_stats} <: AbstractExplicitLayer end get_reduce_dims(::AbstractNormalizationLayer, ::AbstractArray) = error("Not Implemented Yet!!") get_proper_shape(::AbstractNormalizationLayer, ::AbstractArray, y::Nothing, args...) = y get_proper_shape(::AbstractNormalizationLayer, x::AbstractArray{T,N}, y::AbstractArray{T,N}, args...) where {T,N} = y """ BatchNorm(chs::Integer, λ=identity; initβ=zeros32, initγ=ones32, affine = true, track_stats = true, ϵ=1f-5, momentum= 0.1f0) [Batch Normalization](https://arxiv.org/abs/1502.03167) layer. `BatchNorm` computes the mean and variance for each `D_1×...×D_{N-2}×1×D_N` input slice and normalises the input accordingly. # Arguments * `chs` should be the size of the channel dimension in your data (see below). Given an array with `N` dimensions, call the `N-1`th the channel dimension. For a batch of feature vectors this is just the data dimension, for `WHCN` images it's the usual channel dimension. * After normalisation, elementwise activation `λ` is applied. * If `affine=true`, it also applies a shift and a rescale to the input through to learnable per-channel bias β and scale γ parameters. * If `track_stats=true`, accumulates mean and var statistics in training phase that will be used to renormalize the input in test phase. Use [`testmode`](@ref) during inference. # Examples ```julia m = EFL.Chain( EFL.Dense(784 => 64), EFL.BatchNorm(64, relu), EFL.Dense(64 => 10), EFL.BatchNorm(10) ) ``` """ struct BatchNorm{affine,track_stats,F1,F2,F3,N} <: AbstractNormalizationLayer{affine,track_stats} λ::F1 ϵ::N momentum::N chs::Int initβ::F2 initγ::F3 end function BatchNorm( chs::Int, λ=identity; initβ=zeros32, initγ=ones32, affine::Bool=true, track_stats::Bool=true, ϵ=1.0f-5, momentum=0.1f0, ) λ = NNlib.fast_act(λ) return BatchNorm{affine,track_stats,typeof(λ),typeof(initβ),typeof(initγ),typeof(ϵ)}( λ, ϵ, momentum, chs, initβ, initγ ) end function initialparameters(rng::AbstractRNG, l::BatchNorm{affine}) where {affine} return affine ? (γ=l.initγ(rng, l.chs), β=l.initβ(rng, l.chs)) : NamedTuple() end function initialstates(rng::AbstractRNG, l::BatchNorm{affine,track_stats}) where {affine,track_stats} return track_stats ? (μ=zeros32(rng, l.chs), σ²=ones32(rng, l.chs), training=true) : (training=true,) end parameterlength(l::BatchNorm{affine}) where {affine} = affine ? (l.chs * 2) : 0 statelength(l::BatchNorm{affine,track_stats}) where {affine,track_stats} = (track_stats ? 2 * l.chs : 0) + 1 get_reduce_dims(::BatchNorm, x::AbstractArray{T,N}) where {T,N} = [1:(N - 2); N] function get_proper_shape(::BatchNorm, x::AbstractArray{T,N}, y::AbstractVector) where {T,N} return reshape(y, ntuple(i -> i == N - 1 ? length(y) : 1, N)...) end function (BN::BatchNorm{affine,track_stats})(x::AbstractArray{T,N}, ps, st::NamedTuple) where {T,N,affine,track_stats} @assert size(x, N - 1) == BN.chs @assert !istraining(st) || size(x, N) > 1 "During `training`, `BatchNorm` can't handle Batch Size == 1" x_normalized, xmean, xvar = normalization_forward( BN, x, get_proper_shape(BN, x, track_stats ? st.μ : nothing), get_proper_shape(BN, x, track_stats ? st.σ² : nothing), get_proper_shape(BN, x, affine ? ps.γ : nothing), get_proper_shape(BN, x, affine ? ps.β : nothing), BN.λ; training=istraining(st), ) st_ = track_stats ? (μ=xmean, σ²=xvar, training=st.training) : st return (x_normalized, st_) end function (BN::BatchNorm{affine,track_stats})( x::Union{CuArray{T,2},CuArray{T,4},CuArray{T,5}}, ps, st::NamedTuple ) where {T<:Union{Float32,Float64},affine,track_stats} # NNlibCUDA silently updates μ and σ² so copying them if istraining(st) μ2 = track_stats ? copy(st.μ) : nothing σ²2 = track_stats ? copy(st.σ²) : nothing else if track_stats μ2 = copy(st.μ) σ²2 = copy(st.σ²) else reduce_dims = get_reduce_dims(BN, x) μ2 = mean(x; dims=reduce_dims) σ²2 = var(x; mean=μ2, dims=reduce_dims, corrected=false) end end res = applyactivation( BN.λ, batchnorm( affine ? ps.γ : nothing, affine ? ps.β : nothing, x, μ2, σ²2, BN.momentum; eps=BN.ϵ, training=istraining(st), ), Val(!istraining(st)) ) if track_stats st = merge(st, (μ=μ2, σ²=σ²2)) end return res, st end function Base.show(io::IO, l::BatchNorm{affine,track_stats}) where {affine,track_stats} print(io, "BatchNorm($(l.chs)") (l.λ == identity) || print(io, ", $(l.λ)") affine || print(io, ", affine=false") track_stats || print(io, ", track_stats=false") return print(io, ")") end """ GroupNorm(chs::Integer, groups::Integer, λ=identity; initβ=zeros32, initγ=ones32, affine=true, track_stats=false, ϵ=1f-5, momentum=0.1f0) [Group Normalization](https://arxiv.org/abs/1803.08494) layer. # Arguments * `chs` is the number of channels, the channel dimension of your input. For an array of N dimensions, the `N-1`th index is the channel dimension. * `G` is the number of groups along which the statistics are computed. The number of channels must be an integer multiple of the number of groups. * After normalisation, elementwise activation `λ` is applied. * If `affine=true`, it also applies a shift and a rescale to the input through to learnable per-channel bias `β` and scale `γ` parameters. * If `track_stats=true`, accumulates mean and var statistics in training phase that will be used to renormalize the input in test phase. !!! warn GroupNorm doesn't have CUDNN support. The GPU fallback is not very efficient. """ struct GroupNorm{affine,track_stats,F1,F2,F3,N} <: AbstractNormalizationLayer{affine,track_stats} λ::F1 ϵ::N momentum::N chs::Int initβ::F2 initγ::F3 groups::Int end function GroupNorm( chs::Int, groups::Int, λ=identity; initβ=zeros32, initγ=ones32, affine::Bool=true, track_stats::Bool=true, ϵ=1.0f-5, momentum=0.1f0, ) @assert chs % groups == 0 "The number of groups ($(groups)) must divide the number of channels ($chs)" λ = NNlib.fast_act(λ) return GroupNorm{affine,track_stats,typeof(λ),typeof(initβ),typeof(initγ),typeof(ϵ)}( λ, ϵ, momentum, chs, initβ, initγ, groups ) end function initialparameters(rng::AbstractRNG, l::GroupNorm{affine}) where {affine} return affine ? (γ=l.initγ(rng, l.chs), β=l.initβ(rng, l.chs)) : NamedTuple() end function initialstates(rng::AbstractRNG, l::GroupNorm{affine,track_stats}) where {affine,track_stats} return track_stats ? (μ=zeros32(rng, l.groups), σ²=ones32(rng, l.groups), training=true) : (training=true,) end parameterlength(l::GroupNorm{affine}) where {affine} = affine ? (l.chs * 2) : 0 statelength(l::GroupNorm{affine,track_stats}) where {affine,track_stats} = (track_stats ? 2 * l.groups : 0) + 1 get_reduce_dims(::GroupNorm, ::AbstractArray{T,N}) where {T,N} = 1:(N - 1) function get_proper_shape(::GroupNorm, x::AbstractArray{T,N}, y::AbstractVector, mode::Symbol) where {T,N} if mode == :state return reshape(y, ntuple(i -> i == N - 1 ? size(x, i) : 1, N)...) else return reshape(y, ntuple(i -> i ∈ (N - 2, N - 1) ? size(x, i) : 1, N)...) end end function (GN::GroupNorm{affine,track_stats})(x::AbstractArray{T,N}, ps, st::NamedTuple) where {T,N,affine,track_stats} sz = size(x) @assert N > 2 @assert sz[N - 1] == GN.chs x_ = reshape(x, sz[1:(N - 2)]..., sz[N - 1] ÷ GN.groups, GN.groups, sz[N]) x_normalized, xmean, xvar = normalization_forward( GN, x_, get_proper_shape(GN, x_, track_stats ? st.μ : nothing, :state), get_proper_shape(GN, x_, track_stats ? st.σ² : nothing, :state), get_proper_shape(GN, x_, affine ? ps.γ : nothing, :param), get_proper_shape(GN, x_, affine ? ps.β : nothing, :param), GN.λ; training=istraining(st), ) st_ = if track_stats (μ=xmean, σ²=xvar, training=st.training) else st end return reshape(x_normalized, sz), st_ end function Base.show(io::IO, l::GroupNorm{affine,track_stats}) where {affine,track_stats} print(io, "GroupNorm($(l.chs), $(l.groups)") (l.λ == identity) || print(io, ", $(l.λ)") affine || print(io, ", affine=false") track_stats || print(io, ", track_stats=false") return print(io, ")") end """ WeightNorm(layer::AbstractExplicitLayer, which_params::NTuple{N,Symbol}, dims::Union{Tuple,Nothing}=nothing) Applies [weight normalization](https://arxiv.org/abs/1602.07868) to a parameter in the given layer. ``w = g\\frac{v}{\\|v\\|}`` Weight normalization is a reparameterization that decouples the magnitude of a weight tensor from its direction. This updates the parameters in `which_params` (e.g. `weight`) using two parameters: one specifying the magnitude (e.g. `weight_g`) and one specifying the direction (e.g. `weight_v`). By default, a norm over the entire array is computed. Pass `dims` to modify the dimension. """ struct WeightNorm{which_params,L<:AbstractExplicitLayer,D} <: AbstractExplicitLayer layer::L dims::D end function WeightNorm( layer::AbstractExplicitLayer, which_params::NTuple{N,Symbol}, dims::Union{Tuple,Nothing}=nothing ) where {N} return WeightNorm{Val{which_params},typeof(layer),typeof(dims)}(layer, dims) end function initialparameters(rng::AbstractRNG, wn::WeightNorm{Val{which_params}}) where {which_params} ps_layer = initialparameters(rng, wn.layer) ps_normalized = [] ps_unnormalized = [] i = 1 for k in propertynames(ps_layer) v = ps_layer[k] if k ∈ which_params dim = wn.dims === nothing ? ndims(v) : wn.dims[i] push!(ps_normalized, Symbol(string(k) * "_g") => _norm_except(v, dim)) push!(ps_normalized, Symbol(string(k) * "_v") => v) i += 1 else push!(ps_unnormalized, k => v) end end ps_unnormalized = length(ps_unnormalized) == 0 ? NamedTuple() : (; ps_unnormalized...) return (normalized=(; ps_normalized...), unnormalized=ps_unnormalized) end initialstates(rng::AbstractRNG, wn::WeightNorm) = initialstates(rng, wn.layer) function (wn::WeightNorm)(x, ps::Union{ComponentArray,NamedTuple}, s::NamedTuple) _ps = get_normalized_parameters(wn, wn.dims, ps.normalized) return wn.layer(x, merge(_ps, ps.unnormalized), s) end @inbounds @generated function get_normalized_parameters( ::WeightNorm{Val{which_params}}, dims::T, ps::Union{ComponentArray,NamedTuple} ) where {T,which_params} parameter_names = string.(which_params) v_parameter_names = Symbol.(parameter_names .* "_v") g_parameter_names = Symbol.(parameter_names .* "_g") normalized_params_symbol = [gensym(p) for p in parameter_names] function get_norm_except_invoke(i) return if T <: Tuple :(_norm_except(ps.$(v_parameter_names[i]), dims[$i])) else :(_norm_except(ps.$(v_parameter_names[i]))) end end calls = [] for i in 1:length(parameter_names) push!( calls, :( $(normalized_params_symbol[i]) = ps.$(v_parameter_names[i]) .* (ps.$(g_parameter_names[i]) ./ $(get_norm_except_invoke(i))) ), ) end push!(calls, :(return NamedTuple{$(which_params)}(tuple($(Tuple(normalized_params_symbol)...))))) return Expr(:block, calls...) end function Base.show(io::IO, w::WeightNorm{Val{which_params}}) where {which_params} return print(io, "WeightNorm{", which_params, "}(", w.layer, ")") end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
1667
using Test, Random, Statistics, Zygote, Metalhead, ExplicitFluxLayers, Functors import Flux: relu, pullback, sigmoid, gradient import ExplicitFluxLayers: apply, setup, parameterlength, statelength, initialparameters, initialstates, update_state, trainmode, testmode, transform, AbstractExplicitLayer, AbstractExplicitContainerLayer, Dense, BatchNorm, SkipConnection, Parallel, Chain, WrappedFunction, NoOpLayer, Conv, MaxPool, MeanPool, GlobalMaxPool, GlobalMeanPool, Upsample function gradtest(model, input, ps, st) y, pb = Zygote.pullback(p -> model(input, p, st)[1], ps) gs = pb(ones(Float32, size(y))) # if we make it to here with no error, success! return true end function run_model(m::AbstractExplicitLayer, x, mode=:test) if mode == :test ps, st = setup(Random.default_rng(), m) st = testmode(st) return apply(m, x, ps, st)[1] end end function Base.isapprox(nt1::NamedTuple{fields}, nt2::NamedTuple{fields}) where {fields} checkapprox(xy) = xy[1] ≈ xy[2] checkapprox(t::Tuple{Nothing,Nothing}) = true all(checkapprox, zip(values(nt1), values(nt2))) end @testset "ExplicitFluxLayers" begin @testset "Layers" begin @testset "Basic" begin include("layers/basic.jl") end @testset "Normalization" begin include("layers/normalize.jl") end end # Might not want to run always @testset "Metalhead Models" begin @testset "ConvNets -- ImageNet" begin include("models/convnets.jl") end end end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
5344
@testset "Dense" begin @testset "constructors" begin layer = Dense(10, 100) ps, st = setup(MersenneTwister(0), layer) @test size(ps.weight) == (100, 10) @test size(ps.bias) == (100, 1) @test layer.λ == identity layer = Dense(10, 100, relu; bias=false) ps, st = setup(MersenneTwister(0), layer) @test !haskey(ps, :bias) @test layer.λ == relu end @testset "dimensions" begin layer = Dense(10, 5) ps, st = setup(MersenneTwister(0), layer) # For now only support 2D/1D input # @test length(first(apply(layer, randn(10), ps, st))) == 5 # @test_throws DimensionMismatch first(apply(layer, randn(1), ps, st)) # @test_throws MethodError first(apply(layer, 1, ps, st)) @test size(first(apply(layer, randn(10), ps, st))) == (5,) @test size(first(apply(layer, randn(10, 2), ps, st))) == (5, 2) # @test size(first(apply(layer, randn(10, 2, 3), ps, st))) == (5, 2, 3) # @test size(first(apply(layer, randn(10, 2, 3, 4), ps, st))) == (5, 2, 3, 4) # @test_throws DimensionMismatch first(apply(layer, randn(11, 2, 3), ps, st)) end @testset "zeros" begin @test begin layer = Dense(10, 1, identity; initW=ones) first(apply(layer, ones(10, 1), setup(MersenneTwister(0), layer)...)) end == 10 * ones(1, 1) @test begin layer = Dense(10, 1, identity; initW=ones) first(apply(layer, ones(10, 2), setup(MersenneTwister(0), layer)...)) end == 10 * ones(1, 2) @test begin layer = Dense(10, 2, identity; initW=ones) first(apply(layer, ones(10, 1), setup(MersenneTwister(0), layer)...)) end == 10 * ones(2, 1) @test begin layer = Dense(10, 2, identity; initW=ones) first(apply(layer, [ones(10, 1) 2 * ones(10, 1)], setup(MersenneTwister(0), layer)...)) end == [10 20; 10 20] @test begin layer = Dense(10, 2, identity; initW=ones, bias=false) first(apply(layer, [ones(10, 1) 2 * ones(10, 1)], setup(MersenneTwister(0), layer)...)) end == [10 20; 10 20] end end @testset "SkipConnection" begin @testset "zero sum" begin input = randn(10, 10, 10, 10) layer = SkipConnection(WrappedFunction(zero), (a, b) -> a .+ b) @test apply(layer, input, setup(MersenneTwister(0), layer)...)[1] == input end @testset "concat size" begin input = randn(10, 2) layer = SkipConnection(Dense(10, 10), (a, b) -> hcat(a, b)) @test size(apply(layer, input, setup(MersenneTwister(0), layer)...)[1]) == (10, 4) end end @testset "Parallel" begin @testset "zero sum" begin input = randn(10, 10, 10, 10) layer = Parallel(+, WrappedFunction(zero), NoOpLayer()) @test layer(input, setup(MersenneTwister(0), layer)...)[1] == input end @testset "concat size" begin input = randn(10, 2) layer = Parallel((a, b) -> cat(a, b; dims=2), Dense(10, 10), NoOpLayer()) @test size(apply(layer, input, setup(MersenneTwister(0), layer)...)[1]) == (10, 4) layer = Parallel(hcat, Dense(10, 10), NoOpLayer()) @test size(apply(layer, input, setup(MersenneTwister(0), layer)...)[1]) == (10, 4) end @testset "vararg input" begin inputs = randn(10), randn(5), randn(4) layer = Parallel(+, Dense(10, 2), Dense(5, 2), Dense(4, 2)) @test size(apply(layer, inputs, setup(MersenneTwister(0), layer)...)[1]) == (2,) end @testset "connection is called once" begin CNT = Ref(0) f_cnt = (x...) -> (CNT[] += 1; +(x...)) layer = Parallel(f_cnt, WrappedFunction(sin), WrappedFunction(cos), WrappedFunction(tan)) apply(layer, 1, setup(MersenneTwister(0), layer)...) @test CNT[] == 1 apply(layer, (1, 2, 3), setup(MersenneTwister(0), layer)...) @test CNT[] == 2 layer = Parallel(f_cnt, WrappedFunction(sin)) apply(layer, 1, setup(MersenneTwister(0), layer)...) @test CNT[] == 3 end # Ref https://github.com/FluxML/Flux.jl/issues/1673 @testset "Input domain" begin struct Input x end struct L1 <: AbstractExplicitLayer end (::L1)(x, ps, st) = (ps.x * x, st) EFL.initialparameters(rng::AbstractRNG, ::L1) = (x=randn(rng, Float32, 3, 3),) Base.:*(a::AbstractArray, b::Input) = a * b.x par = Parallel(+, L1(), L1()) ps, st = setup(MersenneTwister(0), par) ip = Input(rand(Float32, 3, 3)) ip2 = Input(rand(Float32, 3, 3)) @test par(ip, ps, st)[1] ≈ par.layers[1](ip.x, ps.layer_1, st.layer_1)[1] + par.layers[2](ip.x, ps.layer_2, st.layer_2)[1] @test par((ip, ip2), ps, st)[1] ≈ par.layers[1](ip.x, ps.layer_1, st.layer_1)[1] + par.layers[2](ip2.x, ps.layer_2, st.layer_2)[1] gs = gradient((p, x...) -> sum(par(x, p, st)[1]), ps, ip, ip2) gs_reg = gradient(ps, ip, ip2) do p, x, y sum(par.layers[1](x.x, p.layer_1, st.layer_1)[1] + par.layers[2](y.x, p.layer_2, st.layer_2)[1]) end @test gs[1] ≈ gs_reg[1] @test gs[2].x ≈ gs_reg[2].x @test gs[3].x ≈ gs_reg[3].x end end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
2190
@testset "BatchNorm" begin let m = BatchNorm(2), x = [ 1.0f0 3.0f0 5.0f0 2.0f0 4.0f0 6.0f0 ] ps, st = setup(MersenneTwister(0), m) @test parameterlength(m) == 2 * 2 @test ps.β == [0, 0] # initβ(2) @test ps.γ == [1, 1] # initγ(2) y, st_ = pullback(m, x, ps, st)[1] @test isapprox(y, [-1.22474 0 1.22474; -1.22474 0 1.22474], atol=1.0e-5) # julia> x # 2×3 Array{Float64,2}: # 1.0 3.0 5.0 # 2.0 4.0 6.0 # # μ of batch will be # (1. + 3. + 5.) / 3 = 3 # (2. + 4. + 6.) / 3 = 4 # # ∴ update rule with momentum: # .1 * 3 + 0 = .3 # .1 * 4 + 0 = .4 @test st_.μ ≈ reshape([0.3, 0.4], 2, 1) # julia> .1 .* var(x, dims = 2, corrected=false) .* (3 / 2).+ .9 .* [1., 1.] # 2×1 Array{Float64,2}: # 1.3 # 1.3 @test st_.σ² ≈ 0.1 .* var(x; dims=2, corrected=false) .* (3 / 2) .+ 0.9 .* [1.0, 1.0] st_ = testmode(st_) x′ = m(x, ps, st_)[1] @test isapprox(x′[1], (1 .- 0.3) / sqrt(1.3), atol=1.0e-5) @inferred m(x, ps, st) end let m = BatchNorm(2; track_stats=false), x = [1.0f0 3.0f0 5.0f0; 2.0f0 4.0f0 6.0f0] ps, st = setup(MersenneTwister(0), m) @inferred m(x, ps, st) end # with activation function let m = BatchNorm(2, sigmoid), x = [ 1.0f0 3.0f0 5.0f0 2.0f0 4.0f0 6.0f0 ] ps, st = setup(MersenneTwister(0), m) st = testmode(st) y, st_ = m(x, ps, st) @test isapprox(y, sigmoid.((x .- st_.μ) ./ sqrt.(st_.σ² .+ m.ϵ)), atol=1.0e-7) @inferred m(x, ps, st) end let m = BatchNorm(2), x = reshape(Float32.(1:6), 3, 2, 1) ps, st = setup(MersenneTwister(0), m) st = trainmode(st) @test_throws AssertionError m(x, ps, st)[1] end let m = BatchNorm(32), x = randn(Float32, 416, 416, 32, 1) ps, st = setup(MersenneTwister(0), m) st = testmode(st) m(x, ps, st) @test (@allocated m(x, ps, st)) < 100_000_000 @inferred m(x, ps, st) end end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
code
3192
@testset "AlexNet" begin m = AlexNet() m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 256, 256, 3, 1))) == (1000, 1) end GC.gc(true) @testset "VGG" begin @testset "VGG($sz, batchnorm=$bn)" for sz in [11, 13, 16, 19], bn in [true, false] m = VGG(sz, batchnorm = bn) m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 224, 224, 3, 1))) == (1000, 1) GC.gc(true) end end @testset "ResNet" begin @testset "ResNet($sz)" for sz in [18, 34, 50, 101, 152] m = ResNet(sz) m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 256, 256, 3, 1))) == (1000, 1) GC.gc(true) end # @testset "Shortcut C" begin # m = Metalhead.resnet(Metalhead.basicblock, :C; channel_config = [1, 1], # block_config = [2, 2, 2, 2]) # m2 = transform(m.layers) # @test_broken size(run_model(m2, rand(Float32, 256, 256, 3, 1))) == (1000, 1) # GC.gc(true) # end end @testset "ResNeXt" begin @testset for depth in [50, 101, 152] m = ResNeXt(depth) m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 224, 224, 3, 1))) == (1000, 1) GC.gc(true) end end @testset "GoogLeNet" begin m = GoogLeNet() m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 224, 224, 3, 1))) == (1000, 1) GC.gc(true) end @testset "Inception3" begin m = Inception3() m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 224, 224, 3, 1))) == (1000, 1) GC.gc(true) end @testset "SqueezeNet" begin m = SqueezeNet() m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 224, 224, 3, 1))) == (1000, 1) GC.gc(true) end @testset "DenseNet" begin @testset for sz in [121, 161, 169, 201] m = DenseNet(sz) m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 224, 224, 3, 1))) == (1000, 1) GC.gc(true) end end @testset "MobileNet" verbose = true begin @testset "MobileNetv1" begin m = MobileNetv1() m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 224, 224, 3, 1))) == (1000, 1) GC.gc(true) end GC.gc() @testset "MobileNetv2" begin m = MobileNetv2() m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 224, 224, 3, 1))) == (1000, 1) GC.gc(true) end GC.gc() @testset "MobileNetv3" verbose = true begin @testset for mode in [:small, :large] m = MobileNetv3(mode) m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 224, 224, 3, 1))) == (1000, 1) GC.gc(true) end end end GC.gc() # TODO: ConvNeXt requires LayerNorm Implementation GC.gc() @testset "ConvMixer" verbose = true begin @testset for mode in [:base, :large, :small] m = ConvMixer(mode) m2 = transform(m.layers) @test size(run_model(m2, rand(Float32, 224, 224, 3, 1))) == (1000, 1) GC.gc(true) end end
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
docs
6972
# ExplicitFluxLayers [![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) [![CI](https://github.com/avik-pal/ExplicitFluxLayers.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/avik-pal/ExplicitFluxLayers.jl/actions/workflows/CI.yml) [![codecov](https://codecov.io/gh/avik-pal/ExplicitFluxLayers.jl/branch/main/graph/badge.svg?token=IMqBM1e3hz)](https://codecov.io/gh/avik-pal/ExplicitFluxLayers.jl) Explicit Parameterization of Flux Layers ## Installation ```julia ] add ExplicitFluxLayers ``` ## Getting Started ```julia using ExplicitFluxLayers, Random, Optimisers # Seeding rng = Random.default_rng() Random.seed!(rng, 0) # Construct the layer model = EFL.Chain( EFL.BatchNorm(128), EFL.Dense(128, 256, tanh), EFL.BatchNorm(256), EFL.Chain( EFL.Dense(256, 1, tanh), EFL.Dense(1, 10) ) ) # Parameter and State Variables ps, st = EFL.setup(rng, model) .|> EFL.gpu # Dummy Input x = rand(rng, Float32, 128, 2) |> EFL.gpu # Run the model y, st = EFL.apply(model, x, ps, st) # Gradients gs = gradient(p -> sum(EFL.apply(model, x, p, st)[1]), ps)[1] # Optimization st_opt = Optimisers.setup(Optimisers.ADAM(0.0001), ps) st_opt, ps = Optimisers.update(st_opt, ps, gs) ``` ## Design Principles * **Layers must be immutable** -- i.e. they cannot store any parameters/states but rather stores information to construct them * **Layers return a Tuple containing the result and the updated state** * **Layers are pure functions** * **Given same inputs the outputs must be same** -- stochasticity is controlled by seeds passed in the state variables * **Easily extendible for Custom Layers**: Each Custom Layer should be a subtype of either: a. `AbstractExplicitLayer`: Useful for Base Layers and needs to define the following functions 1. `initialparameters(rng::AbstractRNG, layer::CustomAbstractExplicitLayer)` -- This returns a `ComponentArray`/`NamedTuple` containing the trainable parameters for the layer. 2. `initialstates(rng::AbstractRNG, layer::CustomAbstractExplicitLayer)` -- This returns a NamedTuple containing the current state for the layer. For most layers this is typically empty. Layers that would potentially contain this include `BatchNorm`, Recurrent Neural Networks, etc. 3. `parameterlength(layer::CustomAbstractExplicitLayer)` & `statelength(layer::CustomAbstractExplicitLayer)` -- These can be automatically calculated, but it is recommended that the user defines these. b. `AbstractExplicitContainerLayer`: Used when the layer is storing other `AbstractExplicitLayer`s or `AbstractExplicitContainerLayer`s. This allows good defaults of the dispatches for functions mentioned in the previous point. ## Why use ExplicitFluxLayers over Flux? * **Large Neural Networks** * For small neural networks we recommend [SimpleChains.jl](https://github.com/PumasAI/SimpleChains.jl). * For SciML Applications (Neural ODEs, Deep Equilibrium Models) solvers typically expect a monolithic parameter vector. Flux enables this via its `destructure` mechanism, however, it often leads to [weird bugs](https://github.com/FluxML/Flux.jl/issues?q=is%3Aissue+destructure). EFL forces users to make an explicit distinction between state variables and parameter variables to avoid these issues. * Comes battery-included for distributed training using [FluxMPI.jl](https://github.com/avik-pal/FluxMPI.jl) * **Sensible display of Custom Layers** -- Ever wanted to see Pytorch like Network printouts or wondered how to extend the pretty printing of Flux's layers. ExplicitFluxLayers handles all of that by default. * **Less Bug-ridden Code** * *No arbitrary internal mutations* -- all layers are implemented as pure functions. * *All layers are deterministic* given the parameter and state -- if the layer is supposed to be stochastic (say `Dropout`), the state must contain a seed which is then updated after the function call. * **Easy Parameter Manipulation** -- Wondering why Flux doesn't have `WeightNorm`, `SpectralNorm`, etc. The implicit parameter handling makes it extremely hard to pass parameters around without mutations which AD systems don't like. With ExplicitFluxLayers implementing them is outright simple. ## Usage Examples * Differential Equations + Deep Learning * [Neural ODEs for MNIST Image Classification](examples/NeuralODE/) -- Example borrowed from [DiffEqFlux.jl](https://diffeqflux.sciml.ai/dev/examples/mnist_neural_ode/) * [Deep Equilibrium Models](https://github.com/SciML/FastDEQ.jl) * Image Classification * [ImageNet](examples/ImageNet/main.jl) * Distributed Training using [MPI.jl](https://github.com) -- [FluxMPI](https://github.com/avik-pal/FluxMPI.jl) + [FastDEQ](https://github.com/SciML/FastDEQ.jl/examples) ## Recommended Libraries for Various ML Tasks ExplicitFluxLayers is exclusively focused on designing Neural Network Architectures. All other parts of the DL training/evaluation pipeline should be offloaded to the following frameworks: * Data Manipulation/Loading -- [Augmentor.jl](https://evizero.github.io/Augmentor.jl/stable/), [DataLoaders.jl](https://lorenzoh.github.io/DataLoaders.jl/docs/dev/), [Images.jl](https://juliaimages.org/stable/) * Optimisation -- [Optimisers.jl](https://github.com/FluxML/Optimisers.jl), [ParameterSchedulers.jl](https://darsnack.github.io/ParameterSchedulers.jl/dev/README.html) * Automatic Differentiation -- [Zygote.jl](https://github.com/FluxML/Zygote.jl) * Parameter Manipulation -- [Functors.jl](https://fluxml.ai/Functors.jl/stable/) * Model Checkpointing -- [Serialization.jl](https://docs.julialang.org/en/v1/stdlib/Serialization/) * Activation Functions / Common Neural Network Primitives -- [NNlib.jl](https://fluxml.ai/Flux.jl/stable/models/nnlib/) * Distributed Training -- [FluxMPI.jl](https://github.com/avik-pal/FluxMPI.jl) * Training Visualization -- [Wandb.jl](https://github.com/avik-pal/Wandb.jl) If you found any other packages useful, please open a PR and add them to this list. ## Implemented Layers We don't have a Documentation Page as of now. But all these functions have docs which can be access in the REPL help mode. * `Chain`, `Parallel`, `SkipConnection`, `BranchLayer`, `PairwiseFusion` * `Dense`, `Diagonal` * `Conv`, `MaxPool`, `MeanPool`, `GlobalMaxPool`, `GlobalMeanPool`, `Upsample`, `AdaptiveMaxPool`, `AdaptiveMeanPool` * `BatchNorm`, `WeightNorm`, `GroupNorm` * `ReshapeLayer`, `SelectDim`, `FlattenLayer`, `NoOpLayer`, `WrappedFunction` * `Dropout`, `VariationalHiddenDropout` ## TODOs - [ ] Support Recurrent Neural Networks - [ ] Add wider support for Flux Layers - [ ] Convolution --> ConvTranspose, CrossCor - [ ] Upsampling --> PixelShuffle - [ ] General Purpose --> Maxout, Bilinear, Embedding, AlphaDropout - [ ] Normalization --> LayerNorm, InstanceNorm - [ ] Port tests over from Flux
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
0.2.0
6f46e437e15aa01da5db2bec9d2d85eb5142b9f8
docs
3637
# Imagenet Training using ExplicitFluxLayers This implements training of popular model architectures, such as ResNet, AlexNet, and VGG on the ImageNet dataset. ## Requirements * Install [julia](https://julialang.org/) * In the Julia REPL instantiate the `Project.toml` in the parent directory * Download the ImageNet dataset from http://www.image-net.org/ - Then, move and extract the training and validation images to labeled subfolders, using [the following shell script](https://github.com/pytorch/examples/blob/main/imagenet/extract_ILSVRC.sh) ## Training To train a model, run `main.jl` with the desired model architecture and the path to the ImageNet dataset: ```bash julia main.jl -t 16 -a ResNet18 [imagenet-folder with train and val folders] ``` The default learning rate schedule starts at 0.1 and decays by a factor of 10 every 30 epochs. This is appropriate for ResNet and models with batch normalization, but too high for AlexNet and VGG. Use 0.01 as the initial learning rate for AlexNet or VGG: ```bash julia main.jl -t 16 -a AlexNet --learning-rate 0.01 [imagenet-folder with train and val folders] ``` ## Distributed Data Parallel Training Ensure that you have a CUDA-Aware MPI Installed (else communication might severely bottleneck training) and [MPI.jl](https://juliaparallel.org/MPI.jl/stable/usage/#CUDA-aware-MPI-support) is aware of this build. Apart from this run the script using `mpiexecjl`. ## Usage ```bash usage: main.jl [--arch ARCH] [--epochs EPOCHS] [--start-epoch START-EPOCH] [--batch-size BATCH-SIZE] [--learning-rate LEARNING-RATE] [--momentum MOMENTUM] [--weight-decay WEIGHT-DECAY] [--print-freq PRINT-FREQ] [--resume RESUME] [--evaluate] [--pretrained] [--seed SEED] [--distributed] [-h] data ExplicitFluxLayers ImageNet Training positional arguments: data path to dataset optional arguments: --arch ARCH model architectures: VGG19, ResNet50, GoogLeNet, ResNeXt152, DenseNet201, MobileNetv3_small, ResNet34, ResNet18, DenseNet121, ResNet101, VGG13_BN, DenseNet169, MobileNetv1, VGG11_BN, DenseNet161, MobileNetv3_large, VGG11, VGG19_BN, VGG16_BN, VGG16, ResNeXt50, AlexNet, VGG13, ResNeXt101, MobileNetv2, ConvMixer or ResNet152 (default: "ResNet18") --epochs EPOCHS number of total epochs to run (type: Int64, default: 90) --start-epoch START-EPOCH manual epoch number (useful on restarts) (type: Int64, default: 0) --batch-size BATCH-SIZE mini-batch size, this is the total batch size across all GPUs (type: Int64, default: 256) --learning-rate LEARNING-RATE initial learning rate (type: Float32, default: 0.1) --momentum MOMENTUM momentum (type: Float32, default: 0.9) --weight-decay WEIGHT-DECAY weight decay (type: Float32, default: 0.0001) --print-freq PRINT-FREQ print frequency (type: Int64, default: 10) --resume RESUME resume from checkpoint (default: "") --evaluate evaluate model on validation set --pretrained use pre-trained model --seed SEED seed for initializing training. (type: Int64, default: 0) -h, --help show this help message and exit ```
ExplicitFluxLayers
https://github.com/avik-pal/Lux.jl.git
[ "MIT" ]
3.0.0
a8e18eb383b5ecf1b5e6fc237eb39255044fd92b
code
3224
module ScientificTypesBase # Type exports export Convention # re-export-able types and methods export Scientific, Found, Unknown, Known, Finite, Infinite, OrderedFactor, Multiclass, Count, Continuous, ScientificTimeType, ScientificDate, ScientificDateTime, ScientificTime, Textual, Binary, ColorImage, GrayImage, Image, Table, Density, Sampleable, ManifoldPoint, Annotated, AnnotationOf, Multiset, Iterator, Compositional export elscitype, nonmissing # ------------------------------------------------------------------- # Scientific Types abstract type Found end abstract type Known <: Found end abstract type Unknown <: Found end abstract type Annotated{S} <: Known end abstract type AnnotationOf{S} <: Known end abstract type Multiset{S} <: Known end # for iterators over objects with scitype Ω that do not have some # AbstractVector scitype: abstract type Iterator{Ω} end abstract type Infinite <: Known end abstract type Finite{N} <: Known end abstract type Image{W,H} <: Known end abstract type ScientificTimeType <: Known end abstract type Textual <: Known end abstract type Table{K} <: Known end abstract type Continuous <: Infinite end abstract type Count <: Infinite end abstract type Multiclass{N} <: Finite{N} end abstract type OrderedFactor{N} <: Finite{N} end abstract type ScientificDate <: ScientificTimeType end abstract type ScientificTime <: ScientificTimeType end abstract type ScientificDateTime <: ScientificTimeType end abstract type GrayImage{W,H} <: Image{W,H} end abstract type ColorImage{W,H} <: Image{W,H} end # when sampled, objects with these scitypes return objects of scitype Ω: abstract type Sampleable{Ω} end abstract type Density{Ω} <: Sampleable{Ω} end abstract type ManifoldPoint{M} <: Known end # compositional data with D components, see CoDa.jl abstract type Compositional{D} <: Known end # aliases: const Binary = Finite{2} const Scientific = Union{Missing,Found} # deprecated (no longer publicized) # for internal use const Arr = AbstractArray const TUPLE_SPECIALIZATION_THRESHOLD = 20 # ------------------------------------------------------------------ # Convention abstract type Convention end # ----------------------------------------------------------------- # nonmissing if VERSION < v"1.3" # see also discourse.julialang.org/t/get-non-missing-type-in-the-case-of-parametric-type/29109 """ nonmissingtype(TT) Return the type `T` if `TT = Union{Missing,T}` for some `T` and return `TT` otherwise. """ function nonmissingtype(::Type{T}) where T return T isa Union ? ifelse(T.a == Missing, T.b, T.a) : T end end nonmissing = nonmissingtype # ----------------------------------------------------------------- # Constructor for table scientific type """ Table(...) Constructor for the `Table` scientific type with: ``` Table(S1, S2, ..., Sn) <: Table ``` where `S1, ..., Sn` are the scientific type of the table's columns which are expected to be represented by abstract vectors. """ Table(Ts::Type...) = Table{<:Union{(Arr{<:T,1} for T in Ts)...}} # ----------------------------------------------------------------- # scitype include("scitype.jl") end # module
ScientificTypesBase
https://github.com/JuliaAI/ScientificTypesBase.jl.git
[ "MIT" ]
3.0.0
a8e18eb383b5ecf1b5e6fc237eb39255044fd92b
code
4546
# ----------------------------------------------------------------------------------------- # This file introduces `scitype`, `Scitype` methods and associated fallbacks methods. # It also defines some conveneince methods. # ----------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------- # scitype function (generic) with fallbacks. """ scitype(X, C::Convention) The scientific type (interpretation) of object `X` (distinct from its machine type) as specified by the convention 'C'. """ function scitype end scitype(X, C::Convention) = fallback_scitype(X, C) fallback_scitype(X, C) = Unknown fallback_scitype(::Missing, C) = Missing fallback_scitype(::Nothing, C) = Nothing # ----------------------------------------------------------------------------------------- # `Scitype` function (generic) with fallbacks. # (When implemented can considerably speed-up computation of `scitype` of abstractarrays.) """ Scitype(T::Type, C::Convention) Method for implementers of a convention `C` to enable speed-up of scitype evaluations for arrays. In general, one cannot infer the scitype of an object of type `AbstractArray{T, N}` from the machine type `T` alone. Nevertheless, for some *restricted* machine types `U`, the statement `type(X) == AbstractArray{T, N}` for some `T<:U` already allows one deduce that `scitype(X, C) = AbstractArray{S, N}`, where `S` is determined by `U`, and convention `C` alone. This is the case in the `DefaultConvention` which is used by *ScientificTypes.jl* , where for example, if `U = Integer`, then `S = Count`. Such shortcuts are specified as follows: ``` Scitype(::Type{<:U}, ::C) = S ``` which incurs a considerable speed-up in the computation of `scitype(X, C)`. There is also a speed-up for the case that `T <: Union{U, Missing}`. For example, in the `DefaultConvention`, one has ``` Scitype(::Type{<:Integer}, ::DefaultConvention) = Count ``` """ function Scitype end Scitype(T, C::Convention) = Fallback_Scitype(T, C) Fallback_Scitype(::Type, C) = Unknown # To distinguish between `Any` type and `Union{T, Missing}` for some more # specialised `T`, we define the `Any` case explicitly. Fallback_Scitype(::Type{Any}, C) = Unknown # For the case `Union{T, Missing}` we return `Union{S, Missing}` with `S` # the scientific type corresponding to `T`. function Fallback_Scitype(::Type{Union{T, Missing}}, C) where T return Union{Scitype(Missing, C), Scitype(T, C)} end # For the case `Missing` and `Nothing`, # we return `Missing` and `Nothing` respectively. Fallback_Scitype(::Type{Missing}, C) = Missing Fallback_Scitype(::Type{Nothing}, C) = Nothing # --------------------------------------------------------------------------------------- # Fallbacks for `scitype` of tuples and abstractarrays. function fallback_scitype(@nospecialize(t::Tuple), C) if length(t) <= TUPLE_SPECIALIZATION_THRESHOLD return _tuple_scitype(t, C) else return Tuple{(scitype(el, C) for el in t)...} end end @inline function _tuple_scitype(t::T, C) where {T} if @generated stypes = Tuple( :(scitype(getindex(t, $i), C)) for i in 1:fieldcount(T) ) return :(Tuple{$(stypes...)}) else stypes_ = Tuple( scitype(getindex(t, i), C) for i in 1:fieldcount(T) ) return Tuple{(stypes_)...} end end function fallback_scitype(A::Arr{T}, C) where T return arr_scitype(A, Scitype(T, C), C) end """ arr_scitype(A, S, C) Return the scitype associated with an array `A` of type `{T, N}` assuming an explicit `Scitype` correspondence exist mapping `T` to `S`. """ @inline function arr_scitype( @nospecialize(A::Arr{T, N}), S::Type, C; tight::Bool = false ) where {T, N} if S === Unknown return Arr{scitype_union(A, C), N} elseif S === Union{Scitype(Missing, C), Unknown} return Arr{Union{Scitype(Missing, C), scitype_union(A, C)}, N} else return Arr{S, N} end end # ----------------------------------------------------------------------------------------- # internal methods. """ scitype_union(A, C::convention) Return the type union, over all elements `x` generated by the iterable `A`, of `scitype(x, C)` for a given convention `C`. See also [`scitype`](@ref). """ function scitype_union(A, C::Convention) iterate(A) === nothing && return Unknown reduce((a, b)->Union{a, b}, (scitype(el, C) for el in A)) end
ScientificTypesBase
https://github.com/JuliaAI/ScientificTypesBase.jl.git
[ "MIT" ]
3.0.0
a8e18eb383b5ecf1b5e6fc237eb39255044fd92b
code
476
@testset "nonmissing" begin U = Union{Missing,Int} @test nonmissing(U) == Int end @testset "table" begin T0 = Table(Continuous) @test T0 == Table{K} where K<:AbstractVector{<:Continuous} T1 = Table(Continuous, Count) @test T1 == Table{K} where K<:Union{AbstractVector{<:Continuous}, AbstractVector{<:Count}} T2 = Table(Continuous, Union{Missing,Continuous}) @test T2 == Table{K} where K<:Union{AbstractVector{<:Union{Missing,Continuous}}} end
ScientificTypesBase
https://github.com/JuliaAI/ScientificTypesBase.jl.git
[ "MIT" ]
3.0.0
a8e18eb383b5ecf1b5e6fc237eb39255044fd92b
code
156
using Test, ScientificTypesBase, Tables import ScientificTypesBase: scitype const ST = ScientificTypesBase include("convention.jl") include("scitype.jl")
ScientificTypesBase
https://github.com/JuliaAI/ScientificTypesBase.jl.git
[ "MIT" ]
3.0.0
a8e18eb383b5ecf1b5e6fc237eb39255044fd92b
code
1985
struct MockMLJ <: Convention end @testset "void types" begin @test scitype(nothing, MockMLJ()) == Nothing @test scitype(missing, MockMLJ()) == Missing @test scitype([nothing, nothing], MockMLJ()) == AbstractVector{Nothing} end @testset "scitype" begin X = [1, 2, 3] @test scitype(X, MockMLJ()) == AbstractVector{Unknown} @test scitype(missing, MockMLJ()) == Missing @test scitype((5, 2), MockMLJ()) == Tuple{Unknown,Unknown} anyv = Any[5] @test scitype(anyv[1], MockMLJ()) == Unknown X = [missing, 1, 2, 3] @test scitype(X, MockMLJ()) == AbstractVector{Union{Missing, Unknown}} Xnm = X[2:end] @test scitype(Xnm, MockMLJ()) == AbstractVector{Union{Missing, Unknown}} Xm = Any[missing, missing] @test scitype(Xm, MockMLJ()) == AbstractVector{Missing} @test scitype([missing, missing], MockMLJ()) == AbstractVector{Missing} end @testset "scitype2" begin ScientificTypesBase.Scitype(::Type{<:Integer}, ::MockMLJ) = Count X = [1, 2, 3] @test scitype(X, MockMLJ()) == AbstractVector{Count} Xm = [missing, 1, 2, 3] @test scitype(Xm, MockMLJ()) == AbstractVector{Union{Missing,Count}} Xnm = Xm[2:end] @test scitype(Xnm, MockMLJ()) == AbstractVector{Union{Missing,Count}} end @testset "temporal types" begin @test ScientificDate <: ScientificTimeType @test ScientificDateTime <: ScientificTimeType @test ScientificTime <: ScientificTimeType end @testset "compositional" begin @test Compositional{3} <: Known end @testset "Empty array" begin ScientificTypesBase.Scitype(::Type{<:Integer}, ::MockMLJ) = Count ScientificTypesBase.Scitype(::Type{Missing}, ::MockMLJ) = Missing @test scitype(Int[], MockMLJ()) == AbstractVector{Count} @test scitype(Any[], MockMLJ()) == AbstractVector{Unknown} @test scitype(Missing[], MockMLJ()) == AbstractVector{Missing} @test scitype(Vector{Union{Int,Missing}}(), MockMLJ()) == AbstractVector{Union{Missing,Count}} end
ScientificTypesBase
https://github.com/JuliaAI/ScientificTypesBase.jl.git
[ "MIT" ]
3.0.0
a8e18eb383b5ecf1b5e6fc237eb39255044fd92b
docs
1115
MIT License Copyright (c) 2021- JuliaAI Copyright (c) until 2020 The Alan Turing Institute Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
ScientificTypesBase
https://github.com/JuliaAI/ScientificTypesBase.jl.git
[ "MIT" ]
3.0.0
a8e18eb383b5ecf1b5e6fc237eb39255044fd92b
docs
11530
# ScientificTypesBase.jl | [Linux] | Coverage | | :-----------: | :------: | | [![Build status](https://github.com/JuliaAI/ScientificTypesBase.jl/workflows/CI/badge.svg)](https://github.com/JuliaAI/ScientificTypesBase.jl/actions)| [![codecov.io](http://codecov.io/github/JuliaAI/ScientificTypesBase.jl/coverage.svg?branch=master)](http://codecov.io/github/JuliaAI/ScientificTypesBase.jl?branch=master) | A light-weight, dependency-free, Julia interface defining a collection of types (without instances) for implementing conventions about the scientific interpretation of data. This package makes a distinction between the **machine type** and **scientific type** of a Julia object: * The _machine type_ refers to the Julia type being used to represent the object (for instance, `Float64`). * The _scientific type_ is one of the types defined in this package reflecting how the object should be _interpreted_ (for instance, `Continuous` or `Multiclass{3}`). The distinction is useful because the same machine type is often used to represent data with *differing* scientific interpretations - `Int` is used for product numbers (a factor) but also for a person's weight (a continuous variable) - while the same scientific type is frequently represented by *different* machine types - both `Int` and `Float64` are used to represent weights, for example. For implementation of a concrete convention assigning specific scientific types (interpretations) to julia objects, see instead the [ScientificTypes.jl](https://github.com/JuliaAI/ScientificTypes.jl) package. Formerly "ScientificTypesBase.jl" code lived at "ScientificTypes.jl". Since version 2.0 the code at "ScientificTypes.jl" is code that formerly resided at "MLJScientificTypes.jl" (now deprecated). ``` Finite{N} ├─ Multiclass{N} └─ OrderedFactor{N} Infinite ├─ Continuous └─ Count Image{W,H} ├─ ColorImage{W,H} └─ GrayImage{W,H} ScientificTimeType ├─ ScientificDate ├─ ScientificTime └─ ScientificDateTime Sampleable{Ω} └─ Density{Ω} Annotated{S} AnnotationFor{S} Multiset{S} Table{K} Textual ManifoldPoint{MT} Compositional{D} Unknown ``` > Figure 1. The type hierarchy defined in ScientificTypesBase.jl (The Julia native `Missing` and `Nothing` type are also regarded as a scientific types). #### Contents - [Who is this repository for?](#who-is-this-repository-for) - [What's provided here?](#what-is-provided-here) - [Defining a new convention](#defining-a-new-convention) ## Who is this repository for? This package should only be used by developers who intend to define their own scientific type convention. The [ScientificTypes.jl](https://github.com/JuliaAI/ScientificTypes.jl) package (versions 2.0 and higher) implements such a convention, first adopted in the [MLJ](https://github.com/JuliaAI/MLJ.jl) universe, but which can be adopted by other statistical and scientific software. The purpose of this package is to provide a mechanism for articulating conventions around the scientific interpretation of data. With such a convention in place, a numerical algorithm declares its data requirements in terms of scientific types, the user has a convenient way to check compliance of his data with that requirement, and the developer understands precisely the constraints his data specification places on the actual machine type of the data supplied. ## What is provided here? #### 1. Scientific types ScientificTypesBase provides the new julia types appearing in Figure 1 above, signifying "scientific type" for use in method dispatch (e.g., for trait values). Instances of the types play no role. The types `Finite{N}`, `Multiclass{N}` and `OrderedFactor{N}` are all parametrised by the number of levels `N`, while `Image{W,H}`, `GrayImage{W,H}` and `ColorImage{W,H}` are all parametrised by the image width and height dimensions, `(W, H)`. The parameter `Ω` in `Sampleable{Ω}` and `Density{Ω}` is the scientific type of the sample space. The type `ManifoldPoint{MT}`, intended for points lying on a manifold, is parameterized by the type `MT` of the manifold to which the points belong. The scientific type `ScientificDate` is for representing dates (for example, the 23rd of April, 2029), `ScientificTime` represents time within a 24-hour day, while `ScientificDateTime` represents both a time of day and date. These types mirror the types `Date`, `Time` and `DateTime` from the Julia standard library Dates (and indeed, in the [MLJ convention](https://github.com/JuliaAI/ScientificTypes.jl) the difference is only a formal one). The type parameter `K` in `Table{K}` is for conveying the scientific type(s) of a table's columns. See [More on the `Table` type](#more-on-the-table-type). The julia native types `Missing` and `Nothing` are also regarded as scientific types. #### 2. The `scitype` and `Scitype` methods ScientificTypesBase provides a method `scitype` for articulating a particular convention: `scitype(X, C())` is the scientific type of object `X` under convention `C`. For example, in the `DefaultConvention` convention, implemented by [ScientificTypes](https://github.com/JuliaAI/ScientificTypes.jl), one has `scitype(3.14, Defaultconvention()) = Continuous` and `scitype(42, Defaultconvention()) = Count`. > *Aside.* `scitype` is *not* a mapping of types to types but from > *instances* to types. This is because one may want to distinguish > the scientific type of objects having the same machine type. For > example, in the `DefaultConvention` implemented in ScientificTypes.jl, some > `CategoricalArrays.CategoricalValue` objects have the scitype > `OrderedFactor` but others are `Multiclass`. In CategoricalArrays.jl > the `ordered` attribute is not a type parameter and so it can only > be extracted from instances. The developer implementing a particular scientific type convention [overloads](#defining-a-new-convention) the `scitype` method appropriately. However, this package provides certain rudimentary fallback behaviour: **Property 0.** For any convention `C`, `scitype(missing, C()) == Missing` and `scitype(nothing, C()) == Nothing` (regarding `Missing` and `Nothing` as native scientific types). **Property 1.** For any convention `C` `scitype(X, C()) == Unknown`, unless `X` is a tuple, an abstract array, `nothing`, or `missing`. **Property 2.** For any convention `C`, The scitype of a `k`-tuple is `Tuple{S1, S2, ..., Sk}` where `Sj` is the scitype of the `j`th element under convention `C`. For example, in the `Defaultconvention` convention implemented by [ScientificTypes](https://github.com/JuliaAI/ScientificTypes.jl): ```julia julia> scitype((1, 4.5), Defaultconvention()) Tuple{Count, Continuous} ``` **Property 3.** For any given convention `C`, the scitype of an `AbstractArray`, `A`, is always`AbstractArray{U}` where `U` is the union of the scitypes of the elements of `A` under convention `C`, with one exception: If `typeof(A) <:AbstractArray{Union{Missing,T}}` for some `T` different from `Any`, then the scitype of `A` is `AbstractArray{Union{Missing, U}}`, where `U` is the union over all non-missing elements under convention `C`, **even if `A` has no missing elements.** This exception is made for performance reasons. In `DefaultConvention` implemented by [ScientificTypes](https://github.com/JuliaAI/ScientificTypes.jl): ```julia julia> v = [1.3, 4.5, missing] julia> scitype(v, DefaultConvention()) AbstractArray{Union{Missing, Continuous}, 1} ``` ```julia julia> scitype(v[1:2], DefaultConvention()) AbstractArray{Union{Missing, Continuous},1} ``` > *Performance note.* Computing type unions over large arrays is > expensive and, depending on the convention's implementation and the > array eltype, computing the scitype can be slow. In the common case > that the scitype of an array can be determined from the machine type > of the object alone, the implementer of a new connvention can speed > up compututations by implementing a `Scitype` method. Do > `?ScientificTypesBase.Scitype` for details. #### More on the `Table` type An object of scitype `Table{K}` is expected to have a notion of "columns", which are `AbstractVector`s, and the intention of the type parameter `K` is to encode the scientific type(s) of its columns. Specifically, developers are requested to adhere to the following: **Tabular data convention.** If `scitype(X, C()) <: Table`, for a given convention `C` then in fact ```julia scitype(X, C()) == Table{Union{scitype(c1, C), ..., scitype(cn, C)}} ``` where `c1`, `c2`, ..., `cn` are the columns of `X`. With this definition, common type checks can be performed with tables. For instance, you could check that each column of `X` has an element scitype that is either `Continuous` or `Finite`: ```@example 5 scitype(X, C()) <: Table{<:Union{AbstractVector{<:Continuous}, AbstractVector{<:Finite}}} ``` A built-in `Table` constructor provides a shorthand for the right-hand side: ```@example 5 scitype(X, C()) <: Table(Continuous, Finite) ``` Note that `Table(Continuous, Finite)` is a *type* union and not a `Table` *instance*. ## Defining a new convention If you want to implement your own convention, you can consider the [ScientificTypes.jl](https://github.com/JuliaAI/ScientificTypes.jl) as a blueprint. The steps below summarise the possible steps in defining such a convention: * declare a new convention, * add explicit `scitype` (and `Scitype`) definitions, * optionally define `coerce` methods for your convention Each step is explained below, taking the MLJ convention as an example. ### Naming the convention In the module, define a singleton as thus ```julia struct MyConvention <: ScientificTypesBase.Convention end ``` ### Adding explicit `scitype` declarations. When overloading `scitype` one needs to dipatch over the convention, as in this example: ```julia ScientificTypesBase.scitype(::Integer, ::DefaultConvention) = Count ``` To avoid method ambiguities, avoid dispatching only on the first argument. For example, defining ```julia ScientificTypesBase.scitype(::AbstractFloat, C) = Continous ``` would lead to ambiguities in another package defining ```julia ScientificTypesBase.scitype(a, ::DefaultConvention) = Count ``` Since `ScientificTypesBase.jl` does not define a single-argument `scitype(X)` method, an implementation of a new scientific convention will typically want to explicitly implement the single argument method in their package, to save users from needing to explicitly specify a convention. That is, so the user can call `scitype(2.3)` instead of `scitype(2.3, MyConvention())`. For example, one declares: ```julia scitype(X) = scitype(X, MyConvention()) ``` ### Defining a `coerce` function It may be very useful to define a function to coerce machine types so as to correct an unintended scientific interpretation, according to a given convention. In the `DefaultConvention` convention, this is implemented by defining `coerce` methods (no stub provided by `ScientificTypesBase`) For instance consider the simplified: ```julia function coerce(y::AbstractArray{T}, T2::Type{<:Union{Missing, Continuous}} ) where T <: Union{Missing, Real} return float(y) end ``` Under this definition, `coerce([1, 2, 4], Continuous)` is mapped to `[1.0, 2.0, 4.0]`, which has scitype `AbstractVector{Continuous}`. In the case of tabular data, one might additionally define `coerce` methods to selectively coerce data in specified columns. See [ScientificTypes](https://github.com/JuliaAI/ScientificTypes.jl) for examples.
ScientificTypesBase
https://github.com/JuliaAI/ScientificTypesBase.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
324
using Literate src_dir = string(@__DIR__,"/../test/Applications/") out_dir = string(@__DIR__,"/src/Examples/") mkpath(out_dir) for file in readdir(src_dir) if !endswith(file,".jl") continue end in_file = string(src_dir,file) out_file = string(out_dir,file) Literate.markdown( in_file, out_dir ) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
1495
using GridapSolvers using Documenter include("examples.jl") DocMeta.setdocmeta!(GridapSolvers, :DocTestSetup, :(using GridapSolvers); recursive=true) makedocs(; modules=[GridapSolvers,GridapSolvers.BlockSolvers], authors="Santiago Badia <[email protected]>, Jordi Manyer <[email protected]>, Alberto F. Martin <[email protected]>", repo="https://github.com/gridap/GridapSolvers.jl/blob/{commit}{path}#{line}", sitename="GridapSolvers.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://gridap.github.io/GridapSolvers.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", "SolverInterfaces" => "SolverInterfaces.md", "MultilevelTools" => "MultilevelTools.md", "LinearSolvers" => "LinearSolvers.md", "NonlinearSolvers" => "NonlinearSolvers.md", "BlockSolvers" => "BlockSolvers.md", "PatchBasedSmoothers" => "PatchBasedSmoothers.md", "Examples" => [ "Stokes" => "Examples/Stokes.md", "Navier-Stokes" => "Examples/NavierStokes.md", "Stokes (GMG)" => "Examples/StokesGMG.md", "Navier-Stokes (GMG)" => "Examples/NavierStokesGMG.md", "Darcy (GMG)" => "Examples/DarcyGMG.md", ], ], warnonly=[:doctest,:example_block,:eval_block] ) deploydocs(; repo="github.com/gridap/GridapSolvers.jl", devbranch="main", )
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
1547
module GridapSolvers include("SolverInterfaces/SolverInterfaces.jl") include("MultilevelTools/MultilevelTools.jl") include("BlockSolvers/BlockSolvers.jl") include("PatchBasedSmoothers/PatchBasedSmoothers.jl") include("LinearSolvers/LinearSolvers.jl") include("NonlinearSolvers/NonlinearSolvers.jl") using GridapSolvers.SolverInterfaces using GridapSolvers.MultilevelTools using GridapSolvers.BlockSolvers using GridapSolvers.LinearSolvers using GridapSolvers.PatchBasedSmoothers using GridapSolvers.NonlinearSolvers # MultilevelTools export get_parts, generate_level_parts, generate_subparts export ModelHierarchy, CartesianModelHierarchy, P4estCartesianModelHierarchy export num_levels, get_level, get_level_parts export get_model, get_model_before_redist export FESpaceHierarchy export get_fe_space, get_fe_space_before_redist export compute_hierarchy_matrices export DistributedGridTransferOperator export RestrictionOperator, ProlongationOperator export setup_transfer_operators # BlockSolvers export BlockDiagonalSolver # LinearSolvers export JacobiLinearSolver export RichardsonSmoother export SymGaussSeidelSmoother export GMGLinearSolver export BlockDiagonalSmoother export ConjugateGradientSolver export IS_GMRESSolver export IS_MINRESSolver export IS_SSORSolver export CGSolver export MINRESSolver export GMRESSolver export FGMRESSolver # PatchBasedSmoothers export PatchDecomposition export PatchFESpace export PatchBasedLinearSolver end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
5570
""" struct BlockDiagonalSolver{N} <: LinearSolver Solver representing a block-diagonal solver, i.e ``` │ A11 0 0 │ │ x1 │ │ r1 │ │ 0 A22 0 │ ⋅ │ x2 │ = │ r2 │ │ 0 0 A33 │ │ x3 │ │ r3 │ ``` where `N` is the number of diagonal blocks. # Properties: - `blocks::AbstractVector{<:SolverBlock}`: Matrix of solver blocks, indicating how each diagonal block of the preconditioner is obtained. - `solvers::AbstractVector{<:LinearSolver}`: Vector of solvers, one for each diagonal block. """ struct BlockDiagonalSolver{N,A,B} <: Gridap.Algebra.LinearSolver blocks :: A solvers :: B @doc """ function BlockDiagonalSolver( blocks :: AbstractVector{<:SolverBlock}, solvers :: AbstractVector{<:LinearSolver} ) Create and instance of [`BlockDiagonalSolver`](@ref) from its underlying properties. """ function BlockDiagonalSolver( blocks :: AbstractVector{<:SolverBlock}, solvers :: AbstractVector{<:Gridap.Algebra.LinearSolver} ) N = length(solvers) @check length(blocks) == N A = typeof(blocks) B = typeof(solvers) return new{N,A,B}(blocks,solvers) end end # Constructors @doc """ function BlockDiagonalSolver( solvers::AbstractVector{<:LinearSolver}; is_nonlinear::Vector{Bool}=fill(false,length(solvers)) ) Create and instance of [`BlockDiagonalSolver`](@ref) where all blocks are extracted from the linear system. """ function BlockDiagonalSolver(solvers::AbstractVector{<:Gridap.Algebra.LinearSolver}; is_nonlinear::Vector{Bool}=fill(false,length(solvers))) blocks = map(nl -> nl ? NonlinearSystemBlock() : LinearSystemBlock(),is_nonlinear) return BlockDiagonalSolver(blocks,solvers) end @doc """ function BlockDiagonalSolver( funcs :: AbstractArray{<:Function}, trials :: AbstractArray{<:FESpace}, tests :: AbstractArray{<:FESpace}, solvers :: AbstractArray{<:LinearSolver}; is_nonlinear::Vector{Bool}=fill(false,length(solvers)) ) Create and instance of [`BlockDiagonalSolver`](@ref) where all blocks are given by integral forms. """ function BlockDiagonalSolver( funcs :: AbstractArray{<:Function}, trials :: AbstractArray{<:FESpace}, tests :: AbstractArray{<:FESpace}, solvers :: AbstractArray{<:Gridap.Algebra.LinearSolver}; is_nonlinear::Vector{Bool}=fill(false,length(solvers)) ) blocks = map(funcs,trials,tests,is_nonlinear) do f,trial,test,nl nl ? TriformBlock(f,trial,test) : BiformBlock(f,trial,test) end return BlockDiagonalSolver(blocks,solvers) end @doc """ function BlockDiagonalSolver( mats::AbstractVector{<:AbstractMatrix}, solvers::AbstractVector{<:LinearSolver} ) Create and instance of [`BlockDiagonalSolver`](@ref) where all blocks are given by external matrices. """ function BlockDiagonalSolver( mats::AbstractVector{<:AbstractMatrix}, solvers::AbstractVector{<:Gridap.Algebra.LinearSolver} ) blocks = map(MatrixBlock,mats) return BlockDiagonalSolver(blocks,solvers) end # Symbolic setup struct BlockDiagonalSolverSS{A,B} <: Gridap.Algebra.SymbolicSetup solver :: A block_ss :: B end function Gridap.Algebra.symbolic_setup(solver::BlockDiagonalSolver,mat::AbstractBlockMatrix) mat_blocks = diag(blocks(mat)) block_ss = map(block_symbolic_setup,solver.blocks,solver.solvers,mat_blocks) return BlockDiagonalSolverSS(solver,block_ss) end function Gridap.Algebra.symbolic_setup(solver::BlockDiagonalSolver,mat::AbstractBlockMatrix,x::AbstractBlockVector) mat_blocks = diag(blocks(mat)) block_ss = map((b,m) -> block_symbolic_setup(b,m,x),solver.blocks,solver.solvers,mat_blocks) return BlockDiagonalSolverSS(solver,block_ss) end # Numerical setup struct BlockDiagonalSolverNS{A,B,C} <: Gridap.Algebra.NumericalSetup solver :: A block_ns :: B work_caches :: C end function Gridap.Algebra.numerical_setup(ss::BlockDiagonalSolverSS,mat::AbstractBlockMatrix) solver = ss.solver mat_blocks = diag(blocks(mat)) block_ns = map(block_numerical_setup,ss.block_ss,mat_blocks) y = mortar(map(allocate_in_domain,block_ns)); fill!(y,0.0) work_caches = y return BlockDiagonalSolverNS(solver,block_ns,work_caches) end function Gridap.Algebra.numerical_setup(ss::BlockDiagonalSolverSS,mat::AbstractBlockMatrix,x::AbstractBlockVector) solver = ss.solver mat_blocks = diag(blocks(mat)) block_ns = map((b,m) -> block_numerical_setup(b,m,x),ss.block_ss,mat_blocks) y = mortar(map(allocate_in_domain,block_ns)); fill!(y,0.0) work_caches = y return BlockDiagonalSolverNS(solver,block_ns,work_caches) end function Gridap.Algebra.numerical_setup!(ns::BlockDiagonalSolverNS,mat::AbstractBlockMatrix) mat_blocks = diag(blocks(mat)) map(block_numerical_setup!,ns.block_ns,mat_blocks) return ns end function Gridap.Algebra.numerical_setup!(ns::BlockDiagonalSolverNS,mat::AbstractBlockMatrix,x::AbstractBlockVector) mat_blocks = diag(blocks(mat)) map((b,m) -> block_numerical_setup!(b,m,x),ns.block_ns,mat_blocks) return ns end function Gridap.Algebra.solve!(x::AbstractBlockVector,ns::BlockDiagonalSolverNS,b::AbstractBlockVector) @check blocklength(x) == blocklength(b) == length(ns.block_ns) y = ns.work_caches for (iB,bns) in enumerate(ns.block_ns) xi = blocks(x)[iB] bi = blocks(b)[iB] yi = blocks(y)[iB] solve!(yi,bns.ns,bi) copy!(xi,yi) end return x end function LinearAlgebra.ldiv!(x,ns::BlockDiagonalSolverNS,b) solve!(x,ns,b) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
5005
struct BlockFEOperator{NB,SB,P} <: FEOperator global_op :: FEOperator block_ops :: Matrix{<:Union{<:FEOperator,Missing,Nothing}} is_nonlinear :: Matrix{Bool} end const BlockFESpaceTypes{NB,SB,P} = Union{<:MultiFieldFESpace{<:BlockMultiFieldStyle{NB,SB,P}},<:GridapDistributed.DistributedMultiFieldFESpace{<:BlockMultiFieldStyle{NB,SB,P}}} function BlockFEOperator( res::Matrix{<:Union{<:Function,Missing,Nothing}}, jac::Matrix{<:Union{<:Function,Missing,Nothing}}, trial::BlockFESpaceTypes, test::BlockFESpaceTypes; kwargs... ) assem = SparseMatrixAssembler(test,trial) return BlockFEOperator(res,jac,trial,test,assem) end function BlockFEOperator( res::Matrix{<:Union{<:Function,Missing,Nothing}}, jac::Matrix{<:Union{<:Function,Missing,Nothing}}, trial::BlockFESpaceTypes{NB,SB,P}, test::BlockFESpaceTypes{NB,SB,P}, assem::MultiField.BlockSparseMatrixAssembler{NB,NV,SB,P}; is_nonlinear::Matrix{Bool}=fill(true,(NB,NB)) ) where {NB,NV,SB,P} @check size(res,1) == size(jac,1) == NB @check size(res,2) == size(jac,2) == NB global_res = residual_from_blocks(NB,SB,P,res) global_jac = jacobian_from_blocks(NB,SB,P,jac) global_op = FEOperator(global_res,global_jac,trial,test,assem) trial_blocks = blocks(trial) test_blocks = blocks(test) assem_blocks = blocks(assem) block_ops = map(CartesianIndices(res)) do I if !ismissing(res[I]) && !isnothing(res[I]) FEOperator(res[I],jac[I],test_blocks[I[1]],trial_blocks[I[2]],assem_blocks[I]) end end return BlockFEOperator{NB,SB,P}(global_op,block_ops,is_nonlinear) end # BlockArrays API BlockArrays.blocks(op::BlockFEOperator) = op.block_ops # FEOperator API FESpaces.get_test(op::BlockFEOperator) = get_test(op.global_op) FESpaces.get_trial(op::BlockFEOperator) = get_trial(op.global_op) Algebra.allocate_residual(op::BlockFEOperator,u) = allocate_residual(op.global_op,u) Algebra.residual(op::BlockFEOperator,u) = residual(op.global_op,u) Algebra.allocate_jacobian(op::BlockFEOperator,u) = allocate_jacobian(op.global_op,u) Algebra.jacobian(op::BlockFEOperator,u) = jacobian(op.global_op,u) Algebra.residual!(b::AbstractVector,op::BlockFEOperator,u) = residual!(b,op.global_op,u) function Algebra.jacobian!(A::AbstractBlockMatrix,op::BlockFEOperator{NB},u) where NB map(blocks(A),blocks(op),op.is_nonlinear) do A,op,nl if nl residual!(A,op,u) end end return A end # Private methods function residual_from_blocks(NB,SB,P,block_residuals) function res(u,v) block_ranges = MultiField.get_block_ranges(NB,SB,P) block_u = map(r -> (length(r) == 1) ? u[r[1]] : Tuple(u[r]), block_ranges) block_v = map(r -> (length(r) == 1) ? v[r[1]] : Tuple(v[r]), block_ranges) block_contrs = map(CartesianIndices(block_residuals)) do I if !ismissing(block_residuals[I]) && !isnothing(block_residuals[I]) block_residuals[I](block_u[I[2]],block_v[I[1]]) end end return add_block_contribs(block_contrs) end return res end function jacobian_from_blocks(NB,SB,P,block_jacobians) function jac(u,du,dv) block_ranges = MultiField.get_block_ranges(NB,SB,P) block_u = map(r -> (length(r) == 1) ? u[r[1]] : Tuple(u[r]) , block_ranges) block_du = map(r -> (length(r) == 1) ? du[r[1]] : Tuple(du[r]), block_ranges) block_dv = map(r -> (length(r) == 1) ? dv[r[1]] : Tuple(dv[r]), block_ranges) block_contrs = map(CartesianIndices(block_jacobians)) do I if !ismissing(block_jacobians[I]) && !isnothing(block_jacobians[I]) block_jacobians[I](block_u[I[2]],block_du[I[2]],block_dv[I[1]]) end end return add_block_contribs(block_contrs) end return jac end function add_block_contribs(contrs) c = contrs[1] for ci in contrs[2:end] if !ismissing(ci) && !isnothing(ci) c = c + ci end end return c end function BlockArrays.blocks(a::MultiField.BlockSparseMatrixAssembler) return a.block_assemblers end function BlockArrays.blocks(f::MultiFieldFESpace{<:BlockMultiFieldStyle{NB,SB,P}}) where {NB,SB,P} block_ranges = MultiField.get_block_ranges(NB,SB,P) block_spaces = map(block_ranges) do range (length(range) == 1) ? f[range[1]] : MultiFieldFESpace(f[range]) end return block_spaces end function BlockArrays.blocks(f::GridapDistributed.DistributedMultiFieldFESpace{<:BlockMultiFieldStyle{NB,SB,P}}) where {NB,SB,P} block_gids = blocks(get_free_dof_ids(f)) block_ranges = MultiField.get_block_ranges(NB,SB,P) block_spaces = map(block_ranges,block_gids) do range, gids if (length(range) == 1) space = f[range[1]] else global_sf_spaces = f[range] local_sf_spaces = GridapDistributed.to_parray_of_arrays(map(local_views,global_sf_spaces)) local_mf_spaces = map(MultiFieldFESpace,local_sf_spaces) vector_type = GridapDistributed._find_vector_type(local_mf_spaces,gids) space = MultiFieldFESpace(global_sf_spaces,local_mf_spaces,gids,vector_type) end space end return block_spaces end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
12370
""" abstract type SolverBlock end Abstract type representing a block in a block solver. More specifically, it indicates how a block is obtained from the original system matrix. """ abstract type SolverBlock end """ abstract type LinearSolverBlock <: SolverBlock end SolverBlock that will not be updated between nonlinear iterations. """ abstract type LinearSolverBlock <: SolverBlock end """ abstract type NonlinearSolverBlock <: SolverBlock end SolverBlock that will be updated between nonlinear iterations. """ abstract type NonlinearSolverBlock <: SolverBlock end is_nonlinear(::LinearSolverBlock) = false is_nonlinear(::NonlinearSolverBlock) = true struct BlockSS{A,B,C} <: Algebra.SymbolicSetup block :: A ss :: B cache :: C end mutable struct BlockNS{A,B,C,D} <: Algebra.NumericalSetup block :: A ns :: B mat :: C cache :: D end is_nonlinear(ss::BlockSS) = is_nonlinear(ss.block) is_nonlinear(ns::BlockNS) = is_nonlinear(ns.block) function Algebra.allocate_in_domain(block::BlockNS) return allocate_in_domain(block.mat) end function Algebra.allocate_in_range(block::BlockNS) return allocate_in_range(block.mat) end function restrict_blocks(x::AbstractBlockVector,ids::Vector{Int8}) if isempty(ids) return x elseif length(ids) == 1 return blocks(x)[ids[1]] else return mortar(blocks(x)[ids]) end end """ block_symbolic_setup(block::SolverBlock,solver::LinearSolver,mat::AbstractMatrix) block_symbolic_setup(block::SolverBlock,solver::LinearSolver,mat::AbstractMatrix,x::AbstractVector) Given a SolverBlock, returns the symbolic setup associated to the LinearSolver. """ function block_symbolic_setup(block::SolverBlock,solver::LinearSolver,mat::AbstractMatrix) @abstractmethod end function block_symbolic_setup(block::SolverBlock,solver::LinearSolver,mat::AbstractMatrix,x::AbstractVector) @abstractmethod end @inline function block_symbolic_setup(block::LinearSolverBlock,solver::LinearSolver,mat::AbstractMatrix,x::AbstractVector) return block_symbolic_setup(block,solver,mat) end """ block_numerical_setup(block::SolverBlock,ss::BlockSS,mat::AbstractMatrix) block_numerical_setup(block::SolverBlock,ss::BlockSS,mat::AbstractMatrix,x::AbstractVector) Given a SolverBlock, returns the numerical setup associated to it. """ function block_numerical_setup(block::SolverBlock,ss::BlockSS,mat::AbstractMatrix) @abstractmethod end function block_numerical_setup(block::SolverBlock,ss::BlockSS,mat::AbstractMatrix,x::AbstractVector) @abstractmethod end @inline function block_numerical_setup(block::LinearSolverBlock,ss::BlockSS,mat::AbstractMatrix,x::AbstractVector) return block_numerical_setup(block,ss,mat) end @inline function block_numerical_setup(ss::BlockSS,mat::AbstractMatrix) block_numerical_setup(ss.block,ss,mat) end @inline function block_numerical_setup(ss::BlockSS,mat::AbstractMatrix,x::AbstractVector) block_numerical_setup(ss.block,ss,mat,x) end """ block_numerical_setup!(block::SolverBlock,ns::BlockNS,mat::AbstractMatrix) block_numerical_setup!(block::SolverBlock,ns::BlockNS,mat::AbstractMatrix,x::AbstractVector) Given a SolverBlock, updates the numerical setup associated to it. """ function block_numerical_setup!(block::LinearSolverBlock,ns::BlockNS,mat::AbstractMatrix) ns end function block_numerical_setup!(block::LinearSolverBlock,ns::BlockNS,mat::AbstractMatrix,x::AbstractVector) ns end function block_numerical_setup!(block::NonlinearSolverBlock,ns::BlockNS,mat::AbstractMatrix,x::AbstractVector) @abstractmethod end @inline function block_numerical_setup!(ns::BlockNS,mat::AbstractMatrix) block_numerical_setup!(ns.block,ns,mat) end @inline function block_numerical_setup!(ns::BlockNS,mat::AbstractMatrix,x::AbstractVector) block_numerical_setup!(ns.block,ns,mat,x) end """ block_offdiagonal_setup(block::SolverBlock,mat::AbstractMatrix) block_offdiagonal_setup(block::SolverBlock,mat::AbstractMatrix,x::AbstractVector) Given a SolverBlock, returns the off-diagonal block of associated to it. """ function block_offdiagonal_setup(block::SolverBlock,mat::AbstractMatrix) @abstractmethod end function block_offdiagonal_setup(block::NonlinearSolverBlock,mat::AbstractMatrix,x::AbstractVector) @abstractmethod end @inline function block_offdiagonal_setup(block::LinearSolverBlock,mat::AbstractMatrix,x::AbstractVector) return block_offdiagonal_setup(block,mat) end """ block_offdiagonal_setup!(cache,block::SolverBlock,mat::AbstractMatrix) block_offdiagonal_setup!(cache,block::SolverBlock,mat::AbstractMatrix,x::AbstractVector) Given a SolverBlock, updates the off-diagonal block of associated to it. """ @inline function block_offdiagonal_setup!(cache,block::LinearSolverBlock,mat::AbstractMatrix) return cache end @inline function block_offdiagonal_setup!(cache,block::LinearSolverBlock,mat::AbstractMatrix,x::AbstractVector) return cache end function block_offdiagonal_setup!(cache,block::NonlinearSolverBlock,mat::AbstractMatrix,x::AbstractVector) @abstractmethod end # MatrixBlock """ struct MatrixBlock{A} <: LinearSolverBlock SolverBlock representing an external, independent matrix. # Parameters: - `mat::A`: The matrix. """ struct MatrixBlock{A} <: LinearSolverBlock mat :: A function MatrixBlock(mat::AbstractMatrix) A = typeof(mat) return new{A}(mat) end end function block_symbolic_setup(block::MatrixBlock,solver::LinearSolver,mat::AbstractMatrix) return BlockSS(block,symbolic_setup(solver,block.mat),nothing) end function block_numerical_setup(block::MatrixBlock,ss::BlockSS,mat::AbstractMatrix) return BlockNS(block,numerical_setup(ss.ss,block.mat),block.mat,nothing) end function block_offdiagonal_setup(block::MatrixBlock,mat::AbstractMatrix) return block.mat end # SystemBlocks """ struct LinearSystemBlock <: LinearSolverBlock SolverBlock representing a linear (i.e non-updateable) block that is directly taken from the system matrix. This block will not be updated between nonlinear iterations. """ struct LinearSystemBlock <: LinearSolverBlock end """ struct NonlinearSystemBlock <: LinearSolverBlock I :: Vector{Int} end SolverBlock representing a nonlinear (i.e updateable) block that is directly taken from the system matrix. This block will be updated between nonlinear iterations. # Parameters: - `ids::Vector{Int8}`: Block indices considered when updating the nonlinear block. By default, all indices are considered. """ struct NonlinearSystemBlock <: NonlinearSolverBlock ids :: Vector{Int8} function NonlinearSystemBlock(ids::Vector{<:Integer}) new(convert(Vector{Int8},ids)) end end NonlinearSystemBlock() = NonlinearSystemBlock(Int8[]) NonlinearSystemBlock(id::Integer) = NonlinearSystemBlock([Int8(id)]) function block_symbolic_setup(block::LinearSystemBlock,solver::LinearSolver,mat::AbstractMatrix) return BlockSS(block,symbolic_setup(solver,mat),mat) end function block_symbolic_setup(block::NonlinearSystemBlock,solver::LinearSolver,mat::AbstractMatrix,x::AbstractVector) y = restrict_blocks(x,block.ids) return BlockSS(block,symbolic_setup(solver,mat,y),mat) end function block_numerical_setup(block::LinearSystemBlock,ss::BlockSS,mat::AbstractMatrix) return BlockNS(block,numerical_setup(ss.ss,mat),mat,nothing) end function block_numerical_setup(block::NonlinearSystemBlock,ss::BlockSS,mat::AbstractMatrix,x::AbstractVector) y = restrict_blocks(x,block.ids) return BlockNS(block,numerical_setup(ss.ss,mat,y),mat,nothing) end function block_numerical_setup!(block::NonlinearSystemBlock,ns::BlockNS,mat::AbstractMatrix,x::AbstractVector) y = restrict_blocks(x,block.ids) numerical_setup!(ns.ns,mat,y) return ns end function block_offdiagonal_setup(block::LinearSystemBlock,mat::AbstractMatrix) return mat end function block_offdiagonal_setup(block::NonlinearSystemBlock,mat::AbstractMatrix,x::AbstractVector) return mat end function block_offdiagonal_setup!(cache,block::NonlinearSystemBlock,mat::AbstractMatrix,x::AbstractVector) return mat end # BiformBlock/TriformBlock """ struct BiformBlock <: LinearSolverBlock SolverBlock representing a linear block assembled from a bilinear form. This block will be not updated between nonlinear iterations. # Parameters: - `f::Function`: The bilinear form, i.e f(du,dv) = ∫(...)dΩ - `trial::FESpace`: The trial space. - `test::FESpace`: The test space. - `assem::Assembler`: The assembler to use. """ struct BiformBlock <: LinearSolverBlock f :: Function trial :: FESpace test :: FESpace assem :: Assembler function BiformBlock( f::Function, trial::FESpace, test::FESpace, assem=SparseMatrixAssembler(trial,test) ) return new(f,trial,test,assem) end end """ struct TriformBlock <: NonlinearSolverBlock SolverBlock representing a nonlinear block assembled from a trilinear form. This block will be updated between nonlinear iterations. # Parameters: - `f::Function`: The trilinear form, i.e f(u,du,dv) = ∫(...)dΩ - `param::FESpace`: The parameter space, where `u` lives. - `trial::FESpace`: The trial space, where `du` lives. - `test::FESpace`: The test space, where `dv` lives. - `assem::Assembler`: The assembler to use. - `ids::Vector{Int8}`: Block indices considered when updating the nonlinear block. By default, all indices are considered. """ struct TriformBlock <: NonlinearSolverBlock f :: Function param :: FESpace trial :: FESpace test :: FESpace ids :: Vector{Int8} assem :: Assembler function TriformBlock( f::Function, param::FESpace, trial::FESpace, test::FESpace, ids::Vector{<:Integer}=Int8[], assem=SparseMatrixAssembler(trial,test) ) return new(f,param,trial,test,convert(Vector{Int8},ids),assem) end end function TriformBlock( f::Function,trial::FESpace,test::FESpace,ids::Vector{<:Integer},assem=SparseMatrixAssembler(trial,test) ) return TriformBlock(f,trial,trial,test,ids,assem) end function TriformBlock( f::Function,trial::FESpace,test::FESpace,id::Integer,assem=SparseMatrixAssembler(trial,test) ) return TriformBlock(f,trial,trial,test,[Int8(id)],assem) end function block_symbolic_setup(block::BiformBlock,solver::LinearSolver,mat::AbstractMatrix) A = assemble_matrix(block.f,block.assem,block.trial,block.test) return BlockSS(block,symbolic_setup(solver,A),A) end function block_numerical_setup(block::BiformBlock,ss::BlockSS,mat::AbstractMatrix) A = ss.cache return BlockNS(block,numerical_setup(ss.ss,A),A,nothing) end function block_symbolic_setup(block::TriformBlock,solver::LinearSolver,mat::AbstractMatrix,x::AbstractVector) y = restrict_blocks(x,block.ids) uh = FEFunction(block.param,y) f(u,v) = block.f(uh,u,v) A = assemble_matrix(f,block.assem,block.trial,block.test) return BlockSS(block,symbolic_setup(solver,A,y),A) end function block_numerical_setup(block::TriformBlock,ss::BlockSS,mat::AbstractMatrix,x::AbstractVector) A = ss.cache y = restrict_blocks(x,block.ids) return BlockNS(block,numerical_setup(ss.ss,A,y),A,nothing) end function block_numerical_setup!(block::TriformBlock,ns::BlockNS,mat::AbstractMatrix,x::AbstractVector) y = restrict_blocks(x,block.ids) uh = FEFunction(block.param,y) f(u,v) = block.f(uh,u,v) A = assemble_matrix!(f,ns.mat,block.assem,block.trial,block.test) numerical_setup!(ns.ns,A,y) return ns end function block_offdiagonal_setup(block::BiformBlock,mat::AbstractMatrix) A = assemble_matrix(block.f,block.assem,block.trial,block.test) return A end function block_offdiagonal_setup(block::TriformBlock,mat::AbstractMatrix,x::AbstractVector) y = restrict_blocks(x,block.ids) uh = FEFunction(block.param,y) f(u,v) = block.f(uh,u,v) A = assemble_matrix(f,block.assem,block.trial,block.test) return A end function block_offdiagonal_setup!(cache,block::TriformBlock,mat::AbstractMatrix,x::AbstractVector) y = restrict_blocks(x,block.ids) uh = FEFunction(block.param,y) f(u,v) = block.f(uh,u,v) A = assemble_matrix!(f,cache,block.assem,block.trial,block.test) return A end # CompositeBlock, i.e something that takes from the system matrix and adds another contribution to it. # How do we deal with different sparsity patterns? Not trivial...
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
717
module BlockSolvers using LinearAlgebra using SparseArrays using SparseMatricesCSR using BlockArrays using IterativeSolvers using Gridap using Gridap.Helpers, Gridap.Algebra, Gridap.CellData, Gridap.Arrays, Gridap.FESpaces, Gridap.MultiField using PartitionedArrays using GridapDistributed using GridapSolvers.MultilevelTools using GridapSolvers.SolverInterfaces include("BlockFEOperators.jl") include("BlockSolverInterfaces.jl") include("BlockDiagonalSolvers.jl") include("BlockTriangularSolvers.jl") export BlockFEOperator export MatrixBlock, LinearSystemBlock, NonlinearSystemBlock, BiformBlock, TriformBlock export BlockDiagonalSolver export BlockTriangularSolver end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
7673
""" struct BlockTriangularSolver{T,N} <: LinearSolver Solver representing a block-triangular (upper/lower) solver, i.e ``` │ A11 c12⋅A12 c13⋅A13 │ │ x1 │ │ r1 │ │ 0 A22 c23⋅A23 │ ⋅ │ x2 │ = │ r2 │ │ 0 0 A33 │ │ x3 │ │ r3 │ ``` where `N` is the number of diagonal blocks and `T` is either `Val{:upper}` or `Val{:lower}`. # Properties: - `blocks::AbstractMatrix{<:SolverBlock}`: Matrix of solver blocks, indicating how each block of the preconditioner is obtained. - `solvers::AbstractVector{<:LinearSolver}`: Vector of solvers, one for each diagonal block. - `coeffs::AbstractMatrix{<:Real}`: Matrix of coefficients, indicating the contribution of the off-diagonal blocks to the right-hand side of each diagonal. In particular, blocks can be turned off by setting the corresponding coefficient to zero. """ struct BlockTriangularSolver{T,N,A,B,C} <: Gridap.Algebra.LinearSolver blocks :: A solvers :: B coeffs :: C @doc """ function BlockTriangularSolver( blocks :: AbstractMatrix{<:SolverBlock}, solvers :: AbstractVector{<:LinearSolver}, coeffs = fill(1.0,size(blocks)), half = :upper ) Create and instance of [`BlockTriangularSolver`](@ref) from its underlying properties. The kwarg `half` can have values `:upper` or `:lower`. """ function BlockTriangularSolver( blocks :: AbstractMatrix{<:SolverBlock}, solvers :: AbstractVector{<:Gridap.Algebra.LinearSolver}, coeffs = fill(1.0,size(blocks)), half = :upper ) N = length(solvers) @check size(blocks,1) == size(blocks,2) == N @check size(coeffs,1) == size(coeffs,2) == N @check half ∈ (:upper,:lower) A = typeof(blocks) B = typeof(solvers) C = typeof(coeffs) return new{Val{half},N,A,B,C}(blocks,solvers,coeffs) end end @doc """ function BlockTriangularSolver( solvers::AbstractVector{<:LinearSolver}; is_nonlinear::Matrix{Bool}=fill(false,(length(solvers),length(solvers))), coeffs=fill(1.0,size(is_nonlinear)), half=:upper ) Create and instance of [`BlockTriangularSolver`](@ref) where all blocks are extracted from the linear system. The kwarg `half` can have values `:upper` or `:lower`. """ function BlockTriangularSolver( solvers::AbstractVector{<:Gridap.Algebra.LinearSolver}; is_nonlinear::Matrix{Bool}=fill(false,(length(solvers),length(solvers))), coeffs=fill(1.0,size(is_nonlinear)), half=:upper ) blocks = map(nl -> nl ? NonlinearSystemBlock() : LinearSystemBlock(),is_nonlinear) return BlockTriangularSolver(blocks,solvers,coeffs,half) end # Symbolic setup struct BlockTriangularSolverSS{A,B,C} <: Gridap.Algebra.SymbolicSetup solver :: A block_ss :: B block_off :: C end function Gridap.Algebra.symbolic_setup(solver::BlockTriangularSolver,mat::AbstractBlockMatrix) mat_blocks = blocks(mat) block_ss = map(block_symbolic_setup,diag(solver.blocks),solver.solvers,diag(mat_blocks)) block_off = map(CartesianIndices(mat_blocks)) do I if I[1] != I[2] block_offdiagonal_setup(solver.blocks[I],mat_blocks[I]) else mat_blocks[I] end end return BlockTriangularSolverSS(solver,block_ss,block_off) end function Gridap.Algebra.symbolic_setup(solver::BlockTriangularSolver{T,N},mat::AbstractBlockMatrix,x::AbstractBlockVector) where {T,N} mat_blocks = blocks(mat) block_ss = map((b,s,m) -> block_symbolic_setup(b,s,m,x),diag(solver.blocks),solver.solvers,diag(mat_blocks)) block_off = map(CartesianIndices(mat_blocks)) do I if I[1] != I[2] block_offdiagonal_setup(solver.blocks[I],mat_blocks[I],x) else mat_blocks[I] end end return BlockTriangularSolverSS(solver,block_ss,block_off) end # Numerical setup struct BlockTriangularSolverNS{T,A,B,C,D} <: Gridap.Algebra.NumericalSetup solver :: A block_ns :: B block_off :: C work_caches :: D function BlockTriangularSolverNS( solver::BlockTriangularSolver{T}, block_ns,block_off,work_caches ) where T A = typeof(solver) B = typeof(block_ns) C = typeof(block_off) D = typeof(work_caches) return new{T,A,B,C,D}(solver,block_ns,block_off,work_caches) end end function Gridap.Algebra.numerical_setup(ss::BlockTriangularSolverSS,mat::AbstractBlockMatrix) solver = ss.solver block_ns = map(block_numerical_setup,ss.block_ss,diag(blocks(mat))) y = mortar(map(allocate_in_domain,block_ns)); fill!(y,0.0) # This should be removed with PA 0.4 w = allocate_in_range(mat); fill!(w,0.0) work_caches = w, y return BlockTriangularSolverNS(solver,block_ns,ss.block_off,work_caches) end function Gridap.Algebra.numerical_setup(ss::BlockTriangularSolverSS,mat::AbstractBlockMatrix,x::AbstractBlockVector) solver = ss.solver mat_blocks = blocks(mat) block_ns = map((b,m) -> block_numerical_setup(b,m,x),ss.block_ss,diag(mat_blocks)) y = mortar(map(allocate_in_domain,block_ns)); fill!(y,0.0) w = allocate_in_range(mat); fill!(w,0.0) work_caches = w, y return BlockTriangularSolverNS(solver,block_ns,ss.block_off,work_caches) end function Gridap.Algebra.numerical_setup!(ns::BlockTriangularSolverNS,mat::AbstractBlockMatrix) solver = ns.solver mat_blocks = blocks(mat) map(ns.block_ns,diag(mat_blocks)) do nsi, mi if is_nonlinear(nsi) block_numerical_setup!(nsi,mi) end end map(CartesianIndices(mat_blocks)) do I if (I[1] != I[2]) && is_nonlinear(solver.blocks[I]) block_offdiagonal_setup!(ns.block_off[I],solver.blocks[I],mat_blocks[I]) end end return ns end function Gridap.Algebra.numerical_setup!(ns::BlockTriangularSolverNS,mat::AbstractBlockMatrix,x::AbstractBlockVector) solver = ns.solver mat_blocks = blocks(mat) map(ns.block_ns,diag(mat_blocks)) do nsi, mi if is_nonlinear(nsi) block_numerical_setup!(nsi,mi,x) end end map(CartesianIndices(mat_blocks)) do I if (I[1] != I[2]) && is_nonlinear(solver.blocks[I]) block_offdiagonal_setup!(ns.block_off[I],solver.blocks[I],mat_blocks[I],x) end end return ns end function Gridap.Algebra.solve!(x::AbstractBlockVector,ns::BlockTriangularSolverNS{Val{:lower}},b::AbstractBlockVector) @check blocklength(x) == blocklength(b) == length(ns.block_ns) NB = length(ns.block_ns) c = ns.solver.coeffs w, y = ns.work_caches mats = ns.block_off for iB in 1:NB # Add lower off-diagonal contributions wi = blocks(w)[iB] copy!(wi,blocks(b)[iB]) for jB in 1:iB-1 cij = c[iB,jB] if abs(cij) > eps(cij) xj = blocks(x)[jB] mul!(wi,mats[iB,jB],xj,-cij,1.0) end end # Solve diagonal block nsi = ns.block_ns[iB].ns xi = blocks(x)[iB] yi = blocks(y)[iB] solve!(yi,nsi,wi) copy!(xi,yi) end return x end function Gridap.Algebra.solve!(x::AbstractBlockVector,ns::BlockTriangularSolverNS{Val{:upper}},b::AbstractBlockVector) @check blocklength(x) == blocklength(b) == length(ns.block_ns) NB = length(ns.block_ns) c = ns.solver.coeffs w, y = ns.work_caches mats = ns.block_off for iB in NB:-1:1 # Add upper off-diagonal contributions wi = blocks(w)[iB] copy!(wi,blocks(b)[iB]) for jB in iB+1:NB cij = c[iB,jB] if abs(cij) > eps(cij) xj = blocks(x)[jB] mul!(wi,mats[iB,jB],xj,-cij,1.0) end end # Solve diagonal block nsi = ns.block_ns[iB].ns xi = blocks(x)[iB] yi = blocks(y)[iB] solve!(yi,nsi,wi) copy!(xi,yi) # Remove this with PA 0.4 end return x end function LinearAlgebra.ldiv!(x,ns::BlockTriangularSolverNS,b) solve!(x,ns,b) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
15265
""" struct GMGLinearSolverFromMatrices <: LinearSolver ... end Geometric MultiGrid solver, from algebraic parts. """ struct GMGLinearSolverFromMatrices{A,B,C,D,E,F,G} <: Algebra.LinearSolver mh :: A smatrices :: B interp :: C restrict :: D pre_smoothers :: E post_smoothers :: F coarsest_solver :: G mode :: Symbol log :: ConvergenceLog{Float64} end @doc """ GMGLinearSolver( mh::ModelHierarchy, matrices::AbstractArray{<:AbstractMatrix}, prolongations, restrictions; pre_smoothers = Fill(RichardsonSmoother(JacobiLinearSolver(),10),num_levels(mh)-1), post_smoothers = pre_smoothers, coarsest_solver = LUSolver(), mode::Symbol = :preconditioner, maxiter = 100, atol = 1.0e-14, rtol = 1.0e-08, verbose = false, ) Creates an instance of [`GMGLinearSolverFromMatrices`](@ref) from the underlying model hierarchy, the system matrices at each level and the transfer operators and smoothers at each level except the coarsest. The solver has two modes of operation, defined by the kwarg `mode`: - `:solver`: The GMG solver takes a rhs `b` and returns a solution `x`. - `:preconditioner`: The GMG solver takes a residual `r` and returns a correction `dx`. """ function GMGLinearSolver( mh::ModelHierarchy, smatrices::AbstractArray{<:AbstractMatrix}, interp,restrict; pre_smoothers = Fill(RichardsonSmoother(JacobiLinearSolver(),10),num_levels(mh)-1), post_smoothers = pre_smoothers, coarsest_solver = Gridap.Algebra.LUSolver(), mode::Symbol = :preconditioner, maxiter = 100, atol = 1.0e-14, rtol = 1.0e-08, verbose = false, ) @check mode ∈ [:preconditioner,:solver] tols = SolverTolerances{Float64}(;maxiter=maxiter,atol=atol,rtol=rtol) log = ConvergenceLog("GMG",tols;verbose=verbose) return GMGLinearSolverFromMatrices( mh,smatrices,interp,restrict,pre_smoothers,post_smoothers,coarsest_solver,mode,log ) end """ struct GMGLinearSolverFromWeakForm <: LinearSolver ... end Geometric MultiGrid solver, from FE parts. """ struct GMGLinearSolverFromWeakform{A,B,C,D,E,F,G,H,I} <: Algebra.LinearSolver mh :: A trials :: B tests :: C biforms :: D interp :: E restrict :: F pre_smoothers :: G post_smoothers :: H coarsest_solver :: I mode :: Symbol log :: ConvergenceLog{Float64} is_nonlinear :: Bool primal_restrictions end @doc """ GMGLinearSolver( mh::ModelHierarchy, trials::FESpaceHierarchy, tests::FESpaceHierarchy, biforms::AbstractArray{<:Function}, interp, restrict; pre_smoothers = Fill(RichardsonSmoother(JacobiLinearSolver(),10),num_levels(mh)-1), post_smoothers = pre_smoothers, coarsest_solver = Gridap.Algebra.LUSolver(), mode::Symbol = :preconditioner, is_nonlinear = false, maxiter = 100, atol = 1.0e-14, rtol = 1.0e-08, verbose = false, ) Creates an instance of [`GMGLinearSolverFromMatrices`](@ref) from the underlying model hierarchy, the trial and test FEspace hierarchies, the weakform lhs at each level and the transfer operators and smoothers at each level except the coarsest. The solver has two modes of operation, defined by the kwarg `mode`: - `:solver`: The GMG solver takes a rhs `b` and returns a solution `x`. - `:preconditioner`: The GMG solver takes a residual `r` and returns a correction `dx`. """ function GMGLinearSolver( mh::ModelHierarchy, trials::FESpaceHierarchy, tests::FESpaceHierarchy, biforms::AbstractArray{<:Function}, interp,restrict; pre_smoothers = Fill(RichardsonSmoother(JacobiLinearSolver(),10),num_levels(mh)-1), post_smoothers = pre_smoothers, coarsest_solver = Gridap.Algebra.LUSolver(), mode::Symbol = :preconditioner, is_nonlinear = false, maxiter = 100, atol = 1.0e-14, rtol = 1.0e-08, verbose = false, ) @check mode ∈ [:preconditioner,:solver] @check matching_level_parts(mh,trials,tests,biforms) tols = SolverTolerances{Float64}(;maxiter=maxiter,atol=atol,rtol=rtol) log = ConvergenceLog("GMG",tols;verbose=verbose) primal_restrictions = is_nonlinear ? setup_restriction_operators(trials,8;mode=:solution,solver=IS_ConjugateGradientSolver(;reltol=1.e-6)) : nothing return GMGLinearSolverFromWeakform( mh,trials,tests,biforms,interp,restrict,pre_smoothers,post_smoothers,coarsest_solver,mode,log,is_nonlinear,primal_restrictions ) end struct GMGSymbolicSetup{A} <: Algebra.SymbolicSetup solver :: A end function Algebra.symbolic_setup(solver::GMGLinearSolverFromMatrices,::AbstractMatrix) return GMGSymbolicSetup(solver) end function Algebra.symbolic_setup(solver::GMGLinearSolverFromWeakform,::AbstractMatrix) return GMGSymbolicSetup(solver) end struct GMGNumericalSetup{A,B,C,D,E,F,G,H} <: Algebra.NumericalSetup solver :: A smatrices :: B finest_level_cache :: C pre_smoothers_caches :: D post_smoothers_caches :: E coarsest_solver_cache :: F work_vectors :: G system_caches :: H end function Algebra.numerical_setup(ss::GMGSymbolicSetup,mat::AbstractMatrix) s = ss.solver smatrices = gmg_compute_matrices(s,mat) finest_level_cache = gmg_finest_level_cache(smatrices) work_vectors = gmg_work_vectors(smatrices) pre_smoothers_caches = gmg_smoothers_caches(s.pre_smoothers,smatrices) if !(s.pre_smoothers === s.post_smoothers) post_smoothers_caches = gmg_smoothers_caches(s.post_smoothers,smatrices) else post_smoothers_caches = pre_smoothers_caches end coarsest_solver_cache = gmg_coarse_solver_caches(s.coarsest_solver,smatrices,work_vectors) return GMGNumericalSetup( s,smatrices,finest_level_cache,pre_smoothers_caches,post_smoothers_caches,coarsest_solver_cache,work_vectors,nothing ) end function Algebra.numerical_setup(ss::GMGSymbolicSetup,mat::AbstractMatrix,x::AbstractVector) s = ss.solver smatrices, svectors = gmg_compute_matrices(s,mat,x) system_caches = (smatrices,svectors) finest_level_cache = gmg_finest_level_cache(smatrices) work_vectors = gmg_work_vectors(smatrices) pre_smoothers_caches = gmg_smoothers_caches(s.pre_smoothers,smatrices,svectors) if !(s.pre_smoothers === s.post_smoothers) post_smoothers_caches = gmg_smoothers_caches(s.post_smoothers,smatrices,svectors) else post_smoothers_caches = pre_smoothers_caches end coarsest_solver_cache = gmg_coarse_solver_caches(s.coarsest_solver,smatrices,svectors,work_vectors) # Update transfer operators mh, interp, restrict = s.mh, s.interp, s.restrict nlevs = num_levels(mh) map(linear_indices(mh),smatrices,svectors) do lev, Ah, xh if lev != nlevs if isa(interp[lev],PatchProlongationOperator) || isa(interp[lev],MultiFieldTransferOperator) MultilevelTools.update_transfer_operator!(interp[lev],xh) end if isa(restrict[lev],PatchRestrictionOperator) || isa(restrict[lev],MultiFieldTransferOperator) MultilevelTools.update_transfer_operator!(restrict[lev],xh) end end end return GMGNumericalSetup( s,smatrices,finest_level_cache,pre_smoothers_caches,post_smoothers_caches,coarsest_solver_cache,work_vectors,system_caches ) end function Algebra.numerical_setup!( ns::GMGNumericalSetup{<:GMGLinearSolverFromMatrices}, mat::AbstractMatrix ) msg = " GMGLinearSolverFromMatrices does not support updates.\n Please use GMGLinearSolverFromWeakform instead. " @error msg end function Algebra.numerical_setup!( ns::GMGNumericalSetup{<:GMGLinearSolverFromWeakform}, mat::AbstractMatrix, x::AbstractVector ) @check ns.solver.is_nonlinear s = ns.solver mh, interp, restrict = s.mh, s.interp, s.restrict pre_smoothers_ns, post_smoothers_ns = ns.pre_smoothers_caches, ns.post_smoothers_caches coarsest_solver_ns = ns.coarsest_solver_cache nlevs = num_levels(mh) # Update smatrices and svectors smatrices, svectors = gmg_compute_matrices!(ns.system_caches, s,mat,x) # Update prolongations and smoothers map(linear_indices(mh),smatrices,svectors) do lev, Ah, xh if lev != nlevs if isa(interp[lev],PatchProlongationOperator) || isa(interp[lev],MultiFieldTransferOperator) MultilevelTools.update_transfer_operator!(interp[lev],xh) end if isa(restrict[lev],PatchRestrictionOperator) || isa(restrict[lev],MultiFieldTransferOperator) MultilevelTools.update_transfer_operator!(restrict[lev],xh) end numerical_setup!(pre_smoothers_ns[lev],Ah,xh) if !(s.pre_smoothers === s.post_smoothers) numerical_setup!(post_smoothers_ns[lev],Ah,xh) end end if lev == nlevs numerical_setup!(coarsest_solver_ns,Ah,xh) end end end function gmg_project_solutions(solver::GMGLinearSolverFromWeakform,x::AbstractVector) tests = solver.tests svectors = map(tests) do shlev Vh = MultilevelTools.get_fe_space(shlev) return zero_free_values(Vh) end return gmg_project_solutions!(svectors,solver,x) end function gmg_project_solutions!( svectors::AbstractVector{<:AbstractVector}, solver::GMGLinearSolverFromWeakform, x::AbstractVector ) restrictions = solver.primal_restrictions copy!(svectors[1],x) map(linear_indices(restrictions),restrictions) do lev, R mul!(unsafe_getindex(svectors,lev+1),R,svectors[lev]) end return svectors end function gmg_compute_matrices(s::GMGLinearSolverFromMatrices,mat::AbstractMatrix) smatrices = s.smatrices smatrices[1] = mat return smatrices end function gmg_compute_matrices(s::GMGLinearSolverFromWeakform,mat::AbstractMatrix) @check !s.is_nonlinear map(linear_indices(s.mh),s.biforms) do l, biform if l == 1 return mat end Ul = MultilevelTools.get_fe_space(s.trials,l) Vl = MultilevelTools.get_fe_space(s.tests,l) al(u,v) = biform(u,v) return assemble_matrix(al,Ul,Vl) end end function gmg_compute_matrices(s::GMGLinearSolverFromWeakform,mat::AbstractMatrix,x::AbstractVector) @check s.is_nonlinear svectors = gmg_project_solutions(s,x) smatrices = map(linear_indices(s.mh),s.biforms,svectors) do l, biform, xl if l == 1 return mat end Ul = MultilevelTools.get_fe_space(s.trials,l) Vl = MultilevelTools.get_fe_space(s.tests,l) ul = FEFunction(Ul,xl) al(u,v) = biform(ul,u,v) return assemble_matrix(al,Ul,Vl) end return smatrices, svectors end function gmg_compute_matrices!(caches,s::GMGLinearSolverFromWeakform,mat::AbstractMatrix,x::AbstractVector) @check s.is_nonlinear tests, trials = s.tests, s.trials smatrices, svectors = caches svectors = gmg_project_solutions!(svectors,s,x) map(linear_indices(s.mh),s.biforms,smatrices,svectors) do l, biform, matl, xl if l == 1 copyto!(matl,mat) else Ul = MultilevelTools.get_fe_space(trials,l) Vl = MultilevelTools.get_fe_space(tests,l) ul = FEFunction(Ul,xl) al(u,v) = biform(ul,u,v) assemble_matrix!(al,matl,Ul,Vl) end end return smatrices, svectors end function gmg_finest_level_cache(smatrices::AbstractVector{<:AbstractMatrix}) with_level(smatrices,1) do Ah rh = allocate_in_domain(Ah); fill!(rh,0.0) return rh end end function gmg_smoothers_caches( smoothers::AbstractVector{<:LinearSolver}, smatrices::AbstractVector{<:AbstractMatrix} ) nlevs = num_levels(smatrices) # Last (i.e., coarsest) level does not need pre-/post-smoothing caches = map(smoothers,view(smatrices,1:nlevs-1)) do smoother, mat numerical_setup(symbolic_setup(smoother, mat), mat) end return caches end function gmg_smoothers_caches( smoothers::AbstractVector{<:LinearSolver}, smatrices::AbstractVector{<:AbstractMatrix}, svectors ::AbstractVector{<:AbstractVector} ) nlevs = num_levels(smatrices) # Last (i.e., coarsest) level does not need pre-/post-smoothing caches = map(smoothers,view(smatrices,1:nlevs-1),view(svectors,1:nlevs-1)) do smoother, mat, x numerical_setup(symbolic_setup(smoother, mat, x), mat, x) end return caches end function gmg_coarse_solver_caches( solver::LinearSolver, smatrices::AbstractVector{<:AbstractMatrix}, work_vectors ) nlevs = num_levels(smatrices) with_level(smatrices,nlevs) do AH _, _, dxH, rH = work_vectors[nlevs-1] cache = numerical_setup(symbolic_setup(solver, AH), AH) if isa(solver,PETScLinearSolver) cache = CachedPETScNS(cache, dxH, rH) end return cache end end function gmg_coarse_solver_caches( solver::LinearSolver, smatrices::AbstractVector{<:AbstractMatrix}, svectors::AbstractVector{<:AbstractVector}, work_vectors ) nlevs = num_levels(smatrices) with_level(smatrices,nlevs) do AH _, _, dxH, rH = work_vectors[nlevs-1] xH = svectors[nlevs] cache = numerical_setup(symbolic_setup(solver, AH, xH), AH, xH) if isa(solver,PETScLinearSolver) cache = CachedPETScNS(cache, dxH, rH) end return cache end end function gmg_work_vectors(smatrices::AbstractVector{<:AbstractMatrix}) nlevs = num_levels(smatrices) mats = view(smatrices,1:nlevs-1) work_vectors = map(linear_indices(mats),mats) do lev, Ah dxh = allocate_in_domain(Ah); fill!(dxh,zero(eltype(dxh))) Adxh = allocate_in_range(Ah); fill!(Adxh,zero(eltype(Adxh))) rH, dxH = with_level(smatrices,lev+1;default=(nothing,nothing)) do AH rH = allocate_in_domain(AH); fill!(rH,zero(eltype(rH))) dxH = allocate_in_domain(AH); fill!(dxH,zero(eltype(dxH))) rH, dxH end dxh, Adxh, dxH, rH end return work_vectors end function apply_GMG_level!(lev::Integer,xh::Union{PVector,Nothing},rh::Union{PVector,Nothing},ns::GMGNumericalSetup) mh = ns.solver.mh parts = get_level_parts(mh,lev) if i_am_in(parts) if (lev == num_levels(mh)) ## Coarsest level solve!(xh, ns.coarsest_solver_cache, rh) else ## General case Ah = ns.smatrices[lev] restrict, interp = ns.solver.restrict[lev], ns.solver.interp[lev] dxh, Adxh, dxH, rH = ns.work_vectors[lev] # Pre-smooth current solution solve!(xh, ns.pre_smoothers_caches[lev], rh) # Restrict the residual mul!(rH,restrict,rh) # Apply next_level !isa(dxH,Nothing) && fill!(dxH,0.0) apply_GMG_level!(lev+1,dxH,rH,ns) # Interpolate dxH in finer space mul!(dxh,interp,dxH) # Update solution & residual xh .= xh .+ dxh mul!(Adxh, Ah, dxh) rh .= rh .- Adxh # Post-smooth current solution solve!(xh, ns.post_smoothers_caches[lev], rh) end end end function Gridap.Algebra.solve!(x::AbstractVector,ns::GMGNumericalSetup,b::AbstractVector) mode = ns.solver.mode log = ns.solver.log rh = ns.finest_level_cache if (mode == :preconditioner) fill!(x,0.0) copy!(rh,b) else Ah = ns.smatrices[1] mul!(rh,Ah,x) rh .= b .- rh end res = norm(rh) done = init!(log,res) while !done apply_GMG_level!(1,x,rh,ns) res = norm(rh) done = update!(log,res) end finalize!(log,res) return x end function LinearAlgebra.ldiv!(x::AbstractVector,ns::GMGNumericalSetup,b::AbstractVector) solve!(x,ns,b) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
627
# Identity solver, for testing purposes struct IdentitySolver <: Gridap.Algebra.LinearSolver end struct IdentitySymbolicSetup <: Gridap.Algebra.SymbolicSetup solver end function Gridap.Algebra.symbolic_setup(s::IdentitySolver,A::AbstractMatrix) IdentitySymbolicSetup(s) end struct IdentityNumericalSetup <: Gridap.Algebra.NumericalSetup solver end function Gridap.Algebra.numerical_setup(ss::IdentitySymbolicSetup,mat::AbstractMatrix) s = ss.solver return IdentityNumericalSetup(s) end function Gridap.Algebra.solve!(x::AbstractVector,ns::IdentityNumericalSetup,y::AbstractVector) copy!(x,y) return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
7123
abstract type IterativeLinearSolverType end struct CGIterativeSolverType <: IterativeLinearSolverType end struct GMRESIterativeSolverType <: IterativeLinearSolverType end struct MINRESIterativeSolverType <: IterativeLinearSolverType end struct SSORIterativeSolverType <: IterativeLinearSolverType end # Constructors """ struct IterativeLinearSolver <: LinearSolver ... end Wrappers for [IterativeSolvers.jl](https://github.com/JuliaLinearAlgebra/IterativeSolvers.jl) krylov-like iterative solvers. All wrappers take the same kwargs as the corresponding solver in IterativeSolvers.jl. The following solvers are available: - [`IS_ConjugateGradientSolver`](@ref) - [`IS_GMRESSolver`](@ref) - [`IS_MINRESSolver`](@ref) - [`IS_SSORSolver`](@ref) """ struct IterativeLinearSolver{A} <: Gridap.Algebra.LinearSolver args kwargs function IterativeLinearSolver(type::IterativeLinearSolverType,args,kwargs) A = typeof(type) return new{A}(args,kwargs) end end SolverType(::IterativeLinearSolver{T}) where T = T() """ IS_ConjugateGradientSolver(;kwargs...) Wrapper for the [Conjugate Gradient solver](https://iterativesolvers.julialinearalgebra.org/dev/linear_systems/cg/). """ function IS_ConjugateGradientSolver(;kwargs...) options = [:statevars,:initially_zero,:Pl,:abstol,:reltol,:maxiter,:verbose,:log] @check all(map(opt -> opt ∈ options,keys(kwargs))) return IterativeLinearSolver(CGIterativeSolverType(),nothing,kwargs) end """ IS_GMRESSolver(;kwargs...) Wrapper for the [GMRES solver](https://iterativesolvers.julialinearalgebra.org/dev/linear_systems/gmres/). """ function IS_GMRESSolver(;kwargs...) options = [:initially_zero,:abstol,:reltol,:restart,:maxiter,:Pl,:Pr,:log,:verbose,:orth_meth] @check all(map(opt -> opt ∈ options,keys(kwargs))) return IterativeLinearSolver(GMRESIterativeSolverType(),nothing,kwargs) end """ IS_MINRESSolver(;kwargs...) Wrapper for the [MINRES solver](https://iterativesolvers.julialinearalgebra.org/dev/linear_systems/minres/). """ function IS_MINRESSolver(;kwargs...) options = [:initially_zero,:skew_hermitian,:abstol,:reltol,:maxiter,:log,:verbose] @check all(map(opt -> opt ∈ options,keys(kwargs))) return IterativeLinearSolver(MINRESIterativeSolverType(),nothing,kwargs) end """ IS_SSORSolver(ω;kwargs...) Wrapper for the [SSOR solver](https://iterativesolvers.julialinearalgebra.org/dev/linear_systems/stationary/#SSOR). """ function IS_SSORSolver(ω::Real;kwargs...) options = [:maxiter] @check all(map(opt -> opt ∈ options,keys(kwargs))) args = Dict(:ω => ω) return IterativeLinearSolver(SSORIterativeSolverType(),args,kwargs) end # Symbolic setup struct IterativeLinearSolverSS <: Gridap.Algebra.SymbolicSetup solver end function Gridap.Algebra.symbolic_setup(solver::IterativeLinearSolver,A::AbstractMatrix) IterativeLinearSolverSS(solver) end # Numerical setup struct IterativeLinearSolverNS <: Gridap.Algebra.NumericalSetup solver A caches end function Gridap.Algebra.numerical_setup(ss::IterativeLinearSolverSS,A::AbstractMatrix) solver_type = SolverType(ss.solver) numerical_setup(solver_type,ss,A) end function Gridap.Algebra.numerical_setup(::IterativeLinearSolverType, ss::IterativeLinearSolverSS, A::AbstractMatrix) IterativeLinearSolverNS(ss.solver,A,nothing) end function Gridap.Algebra.numerical_setup(::CGIterativeSolverType, ss::IterativeLinearSolverSS, A::AbstractMatrix) x = allocate_in_domain(A); fill!(x,zero(eltype(x))) caches = IterativeSolvers.CGStateVariables(zero(x), similar(x), similar(x)) return IterativeLinearSolverNS(ss.solver,A,caches) end function Gridap.Algebra.numerical_setup(::SSORIterativeSolverType, ss::IterativeLinearSolverSS, A::AbstractMatrix) x = allocate_in_range(A); fill!(x,zero(eltype(x))) b = allocate_in_domain(A); fill!(b,zero(eltype(b))) ω = ss.solver.args[:ω] maxiter = ss.solver.kwargs[:maxiter] caches = IterativeSolvers.ssor_iterable(x,A,b,ω;maxiter=maxiter) return IterativeLinearSolverNS(ss.solver,A,caches) end function IterativeSolvers.ssor_iterable(x::PVector, A::PSparseMatrix, b::PVector, ω::Real; maxiter::Int = 10) iterables = map(own_values(x),own_values(A),own_values(b)) do _xi,_Aii,_bi xi = Vector(_xi) Aii = SparseMatrixCSC(_Aii) bi = Vector(_bi) return IterativeSolvers.ssor_iterable(xi,Aii,bi,ω;maxiter=maxiter) end return iterables end # Solve function LinearAlgebra.ldiv!(x::AbstractVector,ns::IterativeLinearSolverNS,b::AbstractVector) solve!(x,ns,b) end function Gridap.Algebra.solve!(x::AbstractVector, ns::IterativeLinearSolverNS, y::AbstractVector) solver_type = SolverType(ns.solver) solve!(solver_type,x,ns,y) end function Gridap.Algebra.solve!(::IterativeLinearSolverType, ::AbstractVector, ::IterativeLinearSolverNS, ::AbstractVector) @abstractmethod end function Gridap.Algebra.solve!(::CGIterativeSolverType, x::AbstractVector, ns::IterativeLinearSolverNS, y::AbstractVector) A, kwargs, caches = ns.A, ns.solver.kwargs, ns.caches return cg!(x,A,y;kwargs...,statevars=caches) end function Gridap.Algebra.solve!(::GMRESIterativeSolverType, x::AbstractVector, ns::IterativeLinearSolverNS, y::AbstractVector) A, kwargs = ns.A, ns.solver.kwargs return gmres!(x,A,y;kwargs...) end function Gridap.Algebra.solve!(::MINRESIterativeSolverType, x::AbstractVector, ns::IterativeLinearSolverNS, y::AbstractVector) A, kwargs = ns.A, ns.solver.kwargs return minres!(x,A,y;kwargs...) end function Gridap.Algebra.solve!(::SSORIterativeSolverType, x::AbstractVector, ns::IterativeLinearSolverNS, y::AbstractVector) iterable = ns.caches iterable.x = x iterable.b = y for item = iterable end return x end function Gridap.Algebra.solve!(::SSORIterativeSolverType, x::PVector, ns::IterativeLinearSolverNS, y::PVector) iterables = ns.caches map(iterables,own_values(x),own_values(y)) do iterable, xi, yi iterable.x .= xi iterable.b .= yi for item = iterable end xi .= iterable.x yi .= iterable.b end consistent!(x) |> fetch return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
1628
""" struct JacobiLinearSolver <: LinearSolver end Given a matrix `A`, the Jacobi or Diagonal preconditioner is defined as `P = diag(A)`. """ struct JacobiLinearSolver <: Gridap.Algebra.LinearSolver end struct JacobiSymbolicSetup <: Gridap.Algebra.SymbolicSetup end function Gridap.Algebra.symbolic_setup(s::JacobiLinearSolver,A::AbstractMatrix) JacobiSymbolicSetup() end struct JacobiNumericalSetup{A} <: Gridap.Algebra.NumericalSetup inv_diag :: A end function Gridap.Algebra.numerical_setup(ss::JacobiSymbolicSetup,A::AbstractMatrix) inv_diag = 1.0./diag(A) return JacobiNumericalSetup(inv_diag) end function Gridap.Algebra.numerical_setup!(ns::JacobiNumericalSetup, A::AbstractMatrix) ns.inv_diag .= 1.0 ./ diag(A) end function Gridap.Algebra.numerical_setup(ss::JacobiSymbolicSetup,A::PSparseMatrix) inv_diag = map(own_values(A)) do A 1.0 ./ diag(A) end return JacobiNumericalSetup(inv_diag) end function Gridap.Algebra.numerical_setup!(ns::JacobiNumericalSetup, A::PSparseMatrix) map(ns.inv_diag,own_values(A)) do inv_diag, A inv_diag .= 1.0 ./ diag(A) end return ns end function Gridap.Algebra.solve!(x::AbstractVector, ns::JacobiNumericalSetup, b::AbstractVector) inv_diag = ns.inv_diag x .= inv_diag .* b return x end function Gridap.Algebra.solve!(x::PVector, ns::JacobiNumericalSetup, b::PVector) inv_diag = ns.inv_diag map(inv_diag,own_values(x),own_values(b)) do inv_diag, x, b x .= inv_diag .* b end #consistent!(x) |> wait return x end function LinearAlgebra.ldiv!(x::AbstractVector,ns::JacobiNumericalSetup,b::AbstractVector) solve!(x,ns,b) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
1440
module LinearSolvers using Printf using AbstractTrees using LinearAlgebra using SparseArrays using SparseMatricesCSR using BlockArrays using IterativeSolvers using Gridap using Gridap.Helpers, Gridap.Algebra, Gridap.CellData, Gridap.Arrays, Gridap.FESpaces, Gridap.MultiField using PartitionedArrays using GridapPETSc using GridapDistributed using GridapSolvers.MultilevelTools using GridapSolvers.SolverInterfaces using GridapSolvers.PatchBasedSmoothers export JacobiLinearSolver export RichardsonSmoother export SymGaussSeidelSmoother export GMGLinearSolver export BlockDiagonalSmoother export SchurComplementSolver # Wrappers for IterativeSolvers.jl export IS_ConjugateGradientSolver export IS_GMRESSolver export IS_MINRESSolver export IS_SSORSolver # Krylov solvers export CGSolver export GMRESSolver export FGMRESSolver export MINRESSolver include("Krylov/KrylovUtils.jl") include("Krylov/CGSolvers.jl") include("Krylov/GMRESSolvers.jl") include("Krylov/FGMRESSolvers.jl") include("Krylov/MINRESSolvers.jl") include("PETSc/PETScUtils.jl") include("PETSc/PETScCaches.jl") include("PETSc/ElasticitySolvers.jl") include("PETSc/HipmairXuSolvers.jl") include("IdentityLinearSolvers.jl") include("JacobiLinearSolvers.jl") include("RichardsonSmoothers.jl") include("SymGaussSeidelSmoothers.jl") include("GMGLinearSolvers.jl") include("IterativeLinearSolvers.jl") include("SchurComplementSolvers.jl") include("MatrixSolvers.jl") end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
964
struct MatrixSolver <: Algebra.LinearSolver M::AbstractMatrix solver::Algebra.LinearSolver function MatrixSolver(M;solver=LUSolver()) new(M,solver) end end struct MatrixSolverSS <: Algebra.SymbolicSetup solver::MatrixSolver ss::Algebra.SymbolicSetup function MatrixSolverSS(solver::MatrixSolver) ss = Algebra.symbolic_setup(solver.solver, solver.M) new(solver, ss) end end Algebra.symbolic_setup(solver::MatrixSolver,mat::AbstractMatrix) = MatrixSolverSS(solver) struct MatrixSolverNS <: Algebra.NumericalSetup solver::MatrixSolver ns::Algebra.NumericalSetup function MatrixSolverNS(ss::MatrixSolverSS) solver = ss.solver ns = Gridap.Algebra.numerical_setup(ss.ss, solver.M) new(solver, ns) end end Algebra.numerical_setup(ss::MatrixSolverSS,mat::AbstractMatrix) = MatrixSolverNS(ss) function Algebra.solve!(x::AbstractVector, solver::MatrixSolverNS, b::AbstractVector) Algebra.solve!(x, solver.ns, b) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
2835
""" struct RichardsonSmoother{A} <: LinearSolver M :: A niter :: Int64 ω :: Float64 end Iterative Richardson smoother. Given a solution `x` and a residual `r`, performs `niter` Richardson iterations with damping parameter `ω` using the linear solver `M`. A Richardson iteration is given by: ``` dx = ω * inv(M) * r x = x + dx r = r - A * dx ``` Updates both the solution `x` and the residual `r` in place. """ struct RichardsonSmoother{A} <: Gridap.Algebra.LinearSolver M :: A niter :: Int64 ω :: Float64 @doc """ function RichardsonSmoother(M::LinearSolver,niter::Int=1,ω::Float64=1.0) Returns an instance of [`RichardsonSmoother`](@ref) from its underlying properties. """ function RichardsonSmoother( M::Gridap.Algebra.LinearSolver, niter::Integer=1, ω::Real=1.0 ) A = typeof(M) return new{A}(M,niter,ω) end end struct RichardsonSmootherSymbolicSetup{A,B} <: Gridap.Algebra.SymbolicSetup smoother :: RichardsonSmoother{A} Mss :: B end function Gridap.Algebra.symbolic_setup(smoother::RichardsonSmoother,mat::AbstractMatrix) Mss = symbolic_setup(smoother.M,mat) return RichardsonSmootherSymbolicSetup(smoother,Mss) end mutable struct RichardsonSmootherNumericalSetup{A,B,C,D,E} <: Gridap.Algebra.NumericalSetup smoother :: RichardsonSmoother{A} A :: B Adx :: C dx :: D Mns :: E end function Gridap.Algebra.numerical_setup(ss::RichardsonSmootherSymbolicSetup, A::AbstractMatrix) Adx = allocate_in_range(A) dx = allocate_in_domain(A) Mns = numerical_setup(ss.Mss,A) return RichardsonSmootherNumericalSetup(ss.smoother,A,Adx,dx,Mns) end function Gridap.Algebra.numerical_setup(ss::RichardsonSmootherSymbolicSetup, A::AbstractMatrix, x::AbstractVector) Adx = allocate_in_range(A) dx = allocate_in_domain(A) Mns = numerical_setup(ss.Mss,A,x) return RichardsonSmootherNumericalSetup(ss.smoother,A,Adx,dx,Mns) end function Gridap.Algebra.numerical_setup!(ns::RichardsonSmootherNumericalSetup, A::AbstractMatrix) numerical_setup!(ns.Mns,A) ns.A = A return ns end function Gridap.Algebra.numerical_setup!(ns::RichardsonSmootherNumericalSetup, A::AbstractMatrix, x::AbstractVector) numerical_setup!(ns.Mns,A,x) ns.A = A return ns end function Gridap.Algebra.solve!(x::AbstractVector,ns::RichardsonSmootherNumericalSetup,r::AbstractVector) Adx,dx,Mns = ns.Adx,ns.dx,ns.Mns niter, ω = ns.smoother.niter, ns.smoother.ω iter = 1 fill!(dx,0.0) while iter <= niter solve!(dx,Mns,r) dx .= ω .* dx x .= x .+ dx mul!(Adx, ns.A, dx) r .= r .- Adx iter += 1 end end function LinearAlgebra.ldiv!(x::AbstractVector,ns::RichardsonSmootherNumericalSetup,b::AbstractVector) fill!(x,0.0) aux = copy(b) solve!(x,ns,aux) return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
2040
""" Schur complement solver [A B] ^ -1 [Ip -A^-1 B] [A^-1 ] [ Ip ] [C D] = [ Iq ] ⋅ [ S^-1] ⋅ [-C A^-1 Iq] where S = D - C A^-1 B """ struct SchurComplementSolver{T1,T2,T3,T4} <: Gridap.Algebra.LinearSolver A :: T1 B :: T2 C :: T3 S :: T4 function SchurComplementSolver(A::Gridap.Algebra.NumericalSetup, B::AbstractMatrix, C::AbstractMatrix, S::Gridap.Algebra.NumericalSetup) T1 = typeof(A) T2 = typeof(B) T3 = typeof(C) T4 = typeof(S) return new{T1,T2,T3,T4}(A,B,C,S) end end struct SchurComplementSymbolicSetup <: Gridap.Algebra.SymbolicSetup solver end function Gridap.Algebra.symbolic_setup(s::SchurComplementSolver,A::AbstractMatrix) SchurComplementSymbolicSetup(s) end struct SchurComplementNumericalSetup{A,B,C} <: Gridap.Algebra.NumericalSetup solver::A mat ::B caches::C end function get_shur_complement_caches(B::AbstractMatrix,C::AbstractMatrix) du = allocate_in_domain(C) bu = allocate_in_domain(C) bp = allocate_in_domain(B) return du,bu,bp end function Gridap.Algebra.numerical_setup(ss::SchurComplementSymbolicSetup,mat::AbstractMatrix) s = ss.solver caches = get_shur_complement_caches(s.B,s.C) return SchurComplementNumericalSetup(s,mat,caches) end function Gridap.Algebra.solve!(x::AbstractBlockVector,ns::SchurComplementNumericalSetup,y::AbstractBlockVector) s = ns.solver A,B,C,S = s.A,s.B,s.C,s.S du,bu,bp = ns.caches @check blocklength(x) == blocklength(y) == 2 y_u = y[Block(1)]; y_p = y[Block(2)] x_u = x[Block(1)]; x_p = x[Block(2)] # Solve Schur complement solve!(x_u,A,y_u) # x_u = A^-1 y_u copy!(bp,y_p); mul!(bp,C,du,-1.0,1.0) # bp = C*(A^-1 y_u) - y_p solve!(x_p,S,bp) # x_p = S^-1 bp mul!(bu,B,x_p) # bu = B*x_p solve!(du,A,bu) # du = A^-1 bu x_u .-= du # x_u = x_u - du return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
4702
# Extensions of IterativeSolvers.jl to support parallel matrices struct DiagonalIndices{Tv,Ti,A,B} mat :: A diag :: B last :: B function DiagonalIndices(mat ::AbstractSparseMatrix{Tv,Ti}, diag::AbstractVector{Ti}, last::AbstractVector{Ti}) where {Tv,Ti} A = typeof(mat) B = typeof(diag) @check typeof(last) == B new{Tv,Ti,A,B}(mat,diag,last) end end function DiagonalIndices(A::SparseMatrixCSR{Tv,Ti},row_range) where {Tv,Ti} @notimplemented end function DiagonalIndices(A::SparseMatrixCSC{Tv,Ti},col_range) where {Tv,Ti} n = length(col_range) diag = Vector{Ti}(undef, n) last = Vector{Ti}(undef, n) for col in col_range # Diagonal index r1 = Int(A.colptr[col]) r2 = Int(A.colptr[col + 1] - 1) r1 = searchsortedfirst(A.rowval, col, r1, r2, Base.Order.Forward) if r1 > r2 || A.rowval[r1] != col || iszero(A.nzval[r1]) throw(LinearAlgebra.SingularException(col)) end diag[col] = r1 # Last owned index r1 = Int(A.colptr[col]) r2 = Int(A.colptr[col + 1] - 1) r1 = searchsortedfirst(A.rowval, n+1, r1, r2, Base.Order.Forward) - 1 last[col] = r1 end return DiagonalIndices(A,diag,last) end struct LowerTriangular{Tv,Ti,A,B} mat :: A diag :: DiagonalIndices{Tv,Ti,A,B} end struct UpperTriangular{Tv,Ti,A,B} mat :: A diag :: DiagonalIndices{Tv,Ti,A,B} end function forward_sub!(L::LowerTriangular{Tv,Ti,<:SparseMatrixCSC},x::AbstractVector) where {Tv,Ti} A, diag, last = L.mat, L.diag.diag, L.diag.last n = length(diag) for col = 1 : n # Solve for diagonal element idx = diag[col] x[col] /= A.nzval[idx] # Substitute next values involving x[col] for i = idx + 1 : last[col] x[A.rowval[i]] -= A.nzval[i] * x[col] end end return x end function forward_sub!(L::AbstractArray{<:LowerTriangular},x::PVector) map(L,own_values(x)) do L, x forward_sub!(L, x) end end function backward_sub!(U::UpperTriangular{Tv,Ti,<:SparseMatrixCSC}, x::AbstractVector) where {Tv,Ti} A, diag = U.mat, U.diag.diag n = length(diag) for col = n : -1 : 1 # Solve for diagonal element idx = diag[col] x[col] = x[col] / A.nzval[idx] # Substitute next values involving x[col] for i = A.colptr[col] : idx - 1 x[A.rowval[i]] -= A.nzval[i] * x[col] end end return x end function backward_sub!(U::AbstractArray{<:UpperTriangular},x::PVector) map(U,own_values(x)) do U, x backward_sub!(U, x) end end # Smoother struct SymGaussSeidelSmoother <: Gridap.Algebra.LinearSolver num_iters::Int end struct SymGaussSeidelSymbolicSetup <: Gridap.Algebra.SymbolicSetup solver :: SymGaussSeidelSmoother end function Gridap.Algebra.symbolic_setup(s::SymGaussSeidelSmoother,A::AbstractMatrix) SymGaussSeidelSymbolicSetup(s) end # Numerical setup struct SymGaussSeidelNumericalSetup{A,B,C,D} <: Gridap.Algebra.NumericalSetup solver :: SymGaussSeidelSmoother mat :: A L :: B U :: C caches :: D end function _gs_get_caches(A::AbstractMatrix) dx = allocate_in_domain(A) Adx = allocate_in_range(A) return dx, Adx end function _gs_decompose_matrix(A::AbstractMatrix) idx_range = 1:minimum(size(A)) D = DiagonalIndices(A,idx_range) L = LowerTriangular(A, D) U = UpperTriangular(A, D) return L,U end function _gs_decompose_matrix(A::PSparseMatrix{T,<:AbstractArray{MatType}}) where {T, MatType} values = partition(A) indices = isa(PartitionedArrays.getany(values),SparseMatrixCSC) ? partition(axes(A,2)) : partition(axes(A,1)) L,U = map(values,indices) do A, indices D = DiagonalIndices(A,own_to_local(indices)) L = LowerTriangular(A,D) U = UpperTriangular(A,D) return L,U end |> tuple_of_arrays return L,U end function Gridap.Algebra.numerical_setup(ss::SymGaussSeidelSymbolicSetup,A::AbstractMatrix) L, U = _gs_decompose_matrix(A) caches = _gs_get_caches(A) return SymGaussSeidelNumericalSetup(ss.solver,A,L,U,caches) end # Solve function Gridap.Algebra.solve!(x::AbstractVector, ns::SymGaussSeidelNumericalSetup, r::AbstractVector) A, L, U, caches = ns.mat, ns.L, ns.U, ns.caches dx, Adx = caches niter = ns.solver.num_iters iter = 1 while iter <= niter # Forward pass copy!(dx,r) forward_sub!(L, dx) x .= x .+ dx mul!(Adx, A, dx) r .= r .- Adx # Backward pass copy!(dx,r) backward_sub!(U, dx) x .= x .+ dx mul!(Adx, A, dx) r .= r .- Adx iter += 1 end return x end function LinearAlgebra.ldiv!(x::AbstractVector, ns::SymGaussSeidelNumericalSetup, b::AbstractVector) fill!(x,0.0) aux = copy(b) solve!(x,ns,aux) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
2680
""" struct CGSolver <: LinearSolver ... end CGSolver(Pl;maxiter=1000,atol=1e-12,rtol=1.e-6,flexible=false,verbose=0,name="CG") Left-Preconditioned Conjugate Gradient solver. """ struct CGSolver <: Gridap.Algebra.LinearSolver Pl :: Gridap.Algebra.LinearSolver log :: ConvergenceLog{Float64} flexible :: Bool end function CGSolver(Pl;maxiter=1000,atol=1e-12,rtol=1.e-6,flexible=false,verbose=0,name="CG") tols = SolverTolerances{Float64}(;maxiter=maxiter,atol=atol,rtol=rtol) log = ConvergenceLog(name,tols;verbose=verbose) return CGSolver(Pl,log,flexible) end AbstractTrees.children(s::CGSolver) = [s.Pl] struct CGSymbolicSetup <: Gridap.Algebra.SymbolicSetup solver end function Gridap.Algebra.symbolic_setup(solver::CGSolver, A::AbstractMatrix) return CGSymbolicSetup(solver) end mutable struct CGNumericalSetup <: Gridap.Algebra.NumericalSetup solver A Pl_ns caches end function get_solver_caches(solver::CGSolver,A::AbstractMatrix) w = allocate_in_domain(A); fill!(w,zero(eltype(w))) p = allocate_in_domain(A); fill!(p,zero(eltype(p))) z = allocate_in_domain(A); fill!(z,zero(eltype(z))) r = allocate_in_domain(A); fill!(r,zero(eltype(r))) return (w,p,z,r) end function Gridap.Algebra.numerical_setup(ss::CGSymbolicSetup, A::AbstractMatrix) solver = ss.solver Pl_ns = numerical_setup(symbolic_setup(solver.Pl,A),A) caches = get_solver_caches(solver,A) return CGNumericalSetup(solver,A,Pl_ns,caches) end function Gridap.Algebra.numerical_setup!(ns::CGNumericalSetup, A::AbstractMatrix) numerical_setup!(ns.Pl_ns,A) ns.A = A return ns end function Gridap.Algebra.numerical_setup!(ns::CGNumericalSetup, A::AbstractMatrix, x::AbstractVector) numerical_setup!(ns.Pl_ns,A,x) ns.A = A return ns end function Gridap.Algebra.solve!(x::AbstractVector,ns::CGNumericalSetup,b::AbstractVector) solver, A, Pl, caches = ns.solver, ns.A, ns.Pl_ns, ns.caches flexible, log = solver.flexible, solver.log w,p,z,r = caches # Initial residual mul!(w,A,x); r .= b .- w fill!(p,zero(eltype(p))) fill!(z,zero(eltype(z))) γ = one(eltype(p)) res = norm(r) done = init!(log,res) while !done if !flexible # β = (zₖ₊₁ ⋅ rₖ₊₁)/(zₖ ⋅ rₖ) solve!(z, Pl, r) β = γ; γ = dot(z, r); β = γ / β else # β = (zₖ₊₁ ⋅ (rₖ₊₁-rₖ))/(zₖ ⋅ rₖ) δ = dot(z, r) solve!(z, Pl, r) β = γ; γ = dot(z, r); β = (γ-δ) / β end p .= z .+ β .* p # w = A⋅p mul!(w,A,p) α = γ / dot(p, w) # Update solution and residual x .+= α .* p r .-= α .* w res = norm(r) done = update!(log,res) end finalize!(log,res) return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
5757
""" struct FGMRESSolver <: LinearSolver ... end FGMRESSolver(m,Pr;Pl=nothing,restart=false,m_add=1,maxiter=100,atol=1e-12,rtol=1.e-6,verbose=false,name="FGMRES") Flexible GMRES solver, with right-preconditioner `Pr` and optional left-preconditioner `Pl`. The solver starts by allocating a basis of size `m`. Then: - If `restart=true`, the basis size is fixed and restarted every `m` iterations. - If `restart=false`, the basis size is allowed to increase. When full, the solver allocates `m_add` new basis vectors at a time. """ struct FGMRESSolver <: Gridap.Algebra.LinearSolver m :: Int restart :: Bool m_add :: Int Pr :: Gridap.Algebra.LinearSolver Pl :: Union{Gridap.Algebra.LinearSolver,Nothing} log :: ConvergenceLog{Float64} end function FGMRESSolver(m,Pr;Pl=nothing,restart=false,m_add=1,maxiter=100,atol=1e-12,rtol=1.e-6,verbose=false,name="FGMRES") tols = SolverTolerances{Float64}(maxiter=maxiter,atol=atol,rtol=rtol) log = ConvergenceLog(name,tols,verbose=verbose) return FGMRESSolver(m,restart,m_add,Pr,Pl,log) end function restart(s::FGMRESSolver,k::Int) if s.restart && (k > s.m) print_message(s.log,"Restarting Krylov basis.") return true end return false end AbstractTrees.children(s::FGMRESSolver) = [s.Pr,s.Pl] struct FGMRESSymbolicSetup <: Gridap.Algebra.SymbolicSetup solver end function Gridap.Algebra.symbolic_setup(solver::FGMRESSolver, A::AbstractMatrix) return FGMRESSymbolicSetup(solver) end mutable struct FGMRESNumericalSetup <: Gridap.Algebra.NumericalSetup solver A Pr_ns Pl_ns caches end function get_solver_caches(solver::FGMRESSolver,A::AbstractMatrix) m = solver.m V = [allocate_in_domain(A) for i in 1:m+1] Z = [allocate_in_domain(A) for i in 1:m] zl = allocate_in_domain(A) H = zeros(m+1,m) # Hessenberg matrix g = zeros(m+1) # Residual vector c = zeros(m) # Gibens rotation cosines s = zeros(m) # Gibens rotation sines return (V,Z,zl,H,g,c,s) end function krylov_cache_length(ns::FGMRESNumericalSetup) V, _, _, _, _, _, _ = ns.caches return length(V) - 1 end function expand_krylov_caches!(ns::FGMRESNumericalSetup) V, Z, zl, H, g, c, s = ns.caches m = krylov_cache_length(ns) m_add = ns.solver.m_add m_new = m + m_add for _ in 1:m_add push!(V,allocate_in_domain(ns.A)) push!(Z,allocate_in_domain(ns.A)) end H_new = zeros(eltype(H),m_new+1,m_new); H_new[1:m+1,1:m] .= H g_new = zeros(eltype(g),m_new+1); g_new[1:m+1] .= g c_new = zeros(eltype(c),m_new); c_new[1:m] .= c s_new = zeros(eltype(s),m_new); s_new[1:m] .= s ns.caches = (V,Z,zl,H_new,g_new,c_new,s_new) return H_new,g_new,c_new,s_new end function Gridap.Algebra.numerical_setup(ss::FGMRESSymbolicSetup, A::AbstractMatrix) solver = ss.solver Pr_ns = numerical_setup(symbolic_setup(solver.Pr,A),A) Pl_ns = !isnothing(solver.Pl) ? numerical_setup(symbolic_setup(solver.Pl,A),A) : nothing caches = get_solver_caches(solver,A) return FGMRESNumericalSetup(solver,A,Pr_ns,Pl_ns,caches) end function Gridap.Algebra.numerical_setup(ss::FGMRESSymbolicSetup, A::AbstractMatrix, x::AbstractVector) solver = ss.solver Pr_ns = numerical_setup(symbolic_setup(solver.Pr,A,x),A,x) Pl_ns = !isnothing(solver.Pl) ? numerical_setup(symbolic_setup(solver.Pl,A,x),A,x) : nothing caches = get_solver_caches(solver,A) return FGMRESNumericalSetup(solver,A,Pr_ns,Pl_ns,caches) end function Gridap.Algebra.numerical_setup!(ns::FGMRESNumericalSetup, A::AbstractMatrix) numerical_setup!(ns.Pr_ns,A) if !isa(ns.Pl_ns,Nothing) numerical_setup!(ns.Pl_ns,A) end ns.A = A return ns end function Gridap.Algebra.numerical_setup!(ns::FGMRESNumericalSetup, A::AbstractMatrix, x::AbstractVector) numerical_setup!(ns.Pr_ns,A,x) if !isa(ns.Pl_ns,Nothing) numerical_setup!(ns.Pl_ns,A,x) end ns.A = A return ns end function Gridap.Algebra.solve!(x::AbstractVector,ns::FGMRESNumericalSetup,b::AbstractVector) solver, A, Pl, Pr, caches = ns.solver, ns.A, ns.Pl_ns, ns.Pr_ns, ns.caches V, Z, zl, H, g, c, s = caches m = krylov_cache_length(ns) log = solver.log fill!(V[1],zero(eltype(V[1]))) fill!(zl,zero(eltype(zl))) # Initial residual krylov_residual!(V[1],x,A,b,Pl,zl) β = norm(V[1]) done = init!(log,β) while !done # Arnoldi process j = 1 V[1] ./= β fill!(H,0.0) fill!(g,0.0); g[1] = β while !done && !restart(solver,j) # Expand Krylov basis if needed if j > m H, g, c, s = expand_krylov_caches!(ns) m = krylov_cache_length(ns) end # Arnoldi orthogonalization by Modified Gram-Schmidt fill!(V[j+1],zero(eltype(V[j+1]))) fill!(Z[j],zero(eltype(Z[j]))) krylov_mul!(V[j+1],A,V[j],Pr,Pl,Z[j],zl) for i in 1:j H[i,j] = dot(V[j+1],V[i]) V[j+1] .= V[j+1] .- H[i,j] .* V[i] end H[j+1,j] = norm(V[j+1]) V[j+1] ./= H[j+1,j] # Update QR for i in 1:j-1 γ = c[i]*H[i,j] + s[i]*H[i+1,j] H[i+1,j] = -s[i]*H[i,j] + c[i]*H[i+1,j] H[i,j] = γ end # New Givens rotation, update QR and residual c[j], s[j], _ = LinearAlgebra.givensAlgorithm(H[j,j],H[j+1,j]) H[j,j] = c[j]*H[j,j] + s[j]*H[j+1,j]; H[j+1,j] = 0.0 g[j+1] = -s[j]*g[j]; g[j] = c[j]*g[j] β = abs(g[j+1]) j += 1 done = update!(log,β) end j = j-1 # Solve least squares problem Hy = g by backward substitution for i in j:-1:1 g[i] = (g[i] - dot(H[i,i+1:j],g[i+1:j])) / H[i,i] end # Update solution & residual for i in 1:j x .+= g[i] .* Z[i] end krylov_residual!(V[1],x,A,b,Pl,zl) end finalize!(log,β) return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
6052
""" struct GMRESSolver <: LinearSolver ... end GMRESSolver(m;Pr=nothing,Pl=nothing,restart=false,m_add=1,maxiter=100,atol=1e-12,rtol=1.e-6,verbose=false,name="GMRES") GMRES solver, with optional right and left preconditioners `Pr` and `Pl`. The solver starts by allocating a basis of size `m`. Then: - If `restart=true`, the basis size is fixed and restarted every `m` iterations. - If `restart=false`, the basis size is allowed to increase. When full, the solver allocates `m_add` new basis vectors. """ struct GMRESSolver <: Gridap.Algebra.LinearSolver m :: Int restart :: Bool m_add :: Int Pr :: Union{Gridap.Algebra.LinearSolver,Nothing} Pl :: Union{Gridap.Algebra.LinearSolver,Nothing} log :: ConvergenceLog{Float64} end function GMRESSolver(m;Pr=nothing,Pl=nothing,restart=false,m_add=1,maxiter=100,atol=1e-12,rtol=1.e-6,verbose=false,name="GMRES") tols = SolverTolerances{Float64}(maxiter=maxiter,atol=atol,rtol=rtol) log = ConvergenceLog(name,tols,verbose=verbose) return GMRESSolver(m,restart,m_add,Pr,Pl,log) end function restart(s::GMRESSolver,k::Int) if s.restart && (k > s.m) print_message(s.log,"Restarting Krylov basis.") return true end return false end AbstractTrees.children(s::GMRESSolver) = [s.Pr,s.Pl] struct GMRESSymbolicSetup <: Gridap.Algebra.SymbolicSetup solver end function Gridap.Algebra.symbolic_setup(solver::GMRESSolver, A::AbstractMatrix) return GMRESSymbolicSetup(solver) end mutable struct GMRESNumericalSetup <: Gridap.Algebra.NumericalSetup solver A Pr_ns Pl_ns caches end function get_solver_caches(solver::GMRESSolver,A::AbstractMatrix) m, Pl, Pr = solver.m, solver.Pl, solver.Pr V = [allocate_in_domain(A) for i in 1:m+1] zr = !isnothing(Pr) ? allocate_in_domain(A) : nothing zl = allocate_in_domain(A) H = zeros(m+1,m) # Hessenberg matrix g = zeros(m+1) # Residual vector c = zeros(m) # Gibens rotation cosines s = zeros(m) # Gibens rotation sines return (V,zr,zl,H,g,c,s) end function krylov_cache_length(ns::GMRESNumericalSetup) V, _, _, _, _, _, _ = ns.caches return length(V) - 1 end function expand_krylov_caches!(ns::GMRESNumericalSetup) V, zr, zl, H, g, c, s = ns.caches m = krylov_cache_length(ns) m_add = ns.solver.m_add m_new = m + m_add for _ in 1:m_add push!(V,allocate_in_domain(ns.A)) end H_new = zeros(eltype(H),m_new+1,m_new); H_new[1:m+1,1:m] .= H g_new = zeros(eltype(g),m_new+1); g_new[1:m+1] .= g c_new = zeros(eltype(c),m_new); c_new[1:m] .= c s_new = zeros(eltype(s),m_new); s_new[1:m] .= s ns.caches = (V,zr,zl,H_new,g_new,c_new,s_new) return H_new,g_new,c_new,s_new end function Gridap.Algebra.numerical_setup(ss::GMRESSymbolicSetup, A::AbstractMatrix) solver = ss.solver Pr_ns = !isnothing(solver.Pr) ? numerical_setup(symbolic_setup(solver.Pr,A),A) : nothing Pl_ns = !isnothing(solver.Pl) ? numerical_setup(symbolic_setup(solver.Pl,A),A) : nothing caches = get_solver_caches(solver,A) return GMRESNumericalSetup(solver,A,Pr_ns,Pl_ns,caches) end function Gridap.Algebra.numerical_setup(ss::GMRESSymbolicSetup, A::AbstractMatrix, x::AbstractVector) solver = ss.solver Pr_ns = !isnothing(solver.Pr) ? numerical_setup(symbolic_setup(solver.Pr,A,x),A,x) : nothing Pl_ns = !isnothing(solver.Pl) ? numerical_setup(symbolic_setup(solver.Pl,A,x),A,x) : nothing caches = get_solver_caches(solver,A) return GMRESNumericalSetup(solver,A,Pr_ns,Pl_ns,caches) end function Gridap.Algebra.numerical_setup!(ns::GMRESNumericalSetup, A::AbstractMatrix) if !isa(ns.Pr_ns,Nothing) numerical_setup!(ns.Pr_ns,A) end if !isa(ns.Pl_ns,Nothing) numerical_setup!(ns.Pl_ns,A) end ns.A = A return ns end function Gridap.Algebra.numerical_setup!(ns::GMRESNumericalSetup, A::AbstractMatrix, x::AbstractVector) if !isa(ns.Pr_ns,Nothing) numerical_setup!(ns.Pr_ns,A,x) end if !isa(ns.Pl_ns,Nothing) numerical_setup!(ns.Pl_ns,A,x) end ns.A = A return ns end function Gridap.Algebra.solve!(x::AbstractVector,ns::GMRESNumericalSetup,b::AbstractVector) solver, A, Pl, Pr, caches = ns.solver, ns.A, ns.Pl_ns, ns.Pr_ns, ns.caches V, zr, zl, H, g, c, s = caches m = krylov_cache_length(ns) log = solver.log fill!(V[1],zero(eltype(V[1]))) !isnothing(zr) && fill!(zr,zero(eltype(zr))) fill!(zl,zero(eltype(zl))) # Initial residual krylov_residual!(V[1],x,A,b,Pl,zl) β = norm(V[1]) done = init!(log,β) while !done # Arnoldi process j = 1 V[1] ./= β fill!(H,0.0) fill!(g,0.0); g[1] = β while !done && !restart(solver,j) # Expand Krylov basis if needed if j > m H, g, c, s = expand_krylov_caches!(ns) m = krylov_cache_length(ns) end # Arnoldi orthogonalization by Modified Gram-Schmidt fill!(V[j+1],zero(eltype(V[j+1]))) krylov_mul!(V[j+1],A,V[j],Pr,Pl,zr,zl) for i in 1:j H[i,j] = dot(V[j+1],V[i]) V[j+1] .= V[j+1] .- H[i,j] .* V[i] end H[j+1,j] = norm(V[j+1]) V[j+1] ./= H[j+1,j] # Update QR for i in 1:j-1 γ = c[i]*H[i,j] + s[i]*H[i+1,j] H[i+1,j] = -s[i]*H[i,j] + c[i]*H[i+1,j] H[i,j] = γ end # New Givens rotation, update QR and residual c[j], s[j], _ = LinearAlgebra.givensAlgorithm(H[j,j],H[j+1,j]) H[j,j] = c[j]*H[j,j] + s[j]*H[j+1,j]; H[j+1,j] = 0.0 g[j+1] = -s[j]*g[j]; g[j] = c[j]*g[j] β = abs(g[j+1]) j += 1 done = update!(log,β) end j = j-1 # Solve least squares problem Hy = g by backward substitution for i in j:-1:1 g[i] = (g[i] - dot(H[i,i+1:j],g[i+1:j])) / H[i,i] end # Update solution & residual if isa(Pr,Nothing) for i in 1:j x .+= g[i] .* V[i] end else fill!(zl,0.0) for i in 1:j zl .+= g[i] .* V[i] end solve!(zr,Pr,zl) x .+= zr end krylov_residual!(V[1],x,A,b,Pl,zl) end finalize!(log,β) return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
782
""" Computes the Krylov matrix-vector product `y = Pl⁻¹⋅A⋅Pr⁻¹⋅x` by solving ``` Pr⋅wr = x wl = A⋅wr Pl⋅y = wl ``` """ function krylov_mul!(y,A,x,Pr,Pl,wr,wl) solve!(wr,Pr,x) mul!(wl,A,wr) solve!(y,Pl,wl) end function krylov_mul!(y,A,x,Pr,Pl::Nothing,wr,wl) solve!(wr,Pr,x) mul!(y,A,wr) end function krylov_mul!(y,A,x,Pr::Nothing,Pl,wr,wl) mul!(wl,A,x) solve!(y,Pl,wl) end function krylov_mul!(y,A,x,Pr::Nothing,Pl::Nothing,wr,wl) mul!(y,A,x) end """ Computes the Krylov residual `r = Pl⁻¹(A⋅x - b)` by solving ``` w = A⋅x - b Pl⋅r = w ``` """ function krylov_residual!(r,x,A,b,Pl,w) mul!(w,A,x) w .= b .- w solve!(r,Pl,w) end function krylov_residual!(r,x,A,b,Pl::Nothing,w) mul!(r,A,x) r .= b .- r end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
4005
""" struct MINRESSolver <: LinearSolver ... end MINRESSolver(m;Pl=nothing,maxiter=100,atol=1e-12,rtol=1.e-6,verbose=false,name="MINRES") MINRES solver, with optional left preconditioners `Pl`. The preconditioner must be symmetric and positive definite. """ struct MINRESSolver <: Gridap.Algebra.LinearSolver Pl :: Union{Gridap.Algebra.LinearSolver,Nothing} log :: ConvergenceLog{Float64} end function MINRESSolver(;Pl=nothing,maxiter=1000,atol=1e-12,rtol=1.e-6,verbose=false,name="MINRES") tols = SolverTolerances{Float64}(maxiter=maxiter,atol=atol,rtol=rtol) log = ConvergenceLog(name,tols,verbose=verbose) return MINRESSolver(Pl,log) end AbstractTrees.children(s::MINRESSolver) = [s.Pl] struct MINRESSymbolicSetup <: Gridap.Algebra.SymbolicSetup solver end function Gridap.Algebra.symbolic_setup(solver::MINRESSolver, A::AbstractMatrix) return MINRESSymbolicSetup(solver) end mutable struct MINRESNumericalSetup <: Gridap.Algebra.NumericalSetup solver A Pl_ns caches end function get_solver_caches(solver::MINRESSolver,A::AbstractMatrix) V = Tuple([allocate_in_domain(A) for i in 1:3]) W = Tuple([allocate_in_domain(A) for i in 1:3]) Z = Tuple([allocate_in_domain(A) for i in 1:3]) return (V,W,Z) end function Gridap.Algebra.numerical_setup(ss::MINRESSymbolicSetup, A::AbstractMatrix) solver = ss.solver Pl_ns = isa(solver.Pl,Nothing) ? nothing : numerical_setup(symbolic_setup(solver.Pl,A),A) caches = get_solver_caches(solver,A) return MINRESNumericalSetup(solver,A,Pl_ns,caches) end function Gridap.Algebra.numerical_setup(ss::MINRESSymbolicSetup, A::AbstractMatrix, x::AbstractVector) solver = ss.solver Pl_ns = isa(solver.Pl,Nothing) ? nothing : numerical_setup(symbolic_setup(solver.Pl,A,x),A,x) caches = get_solver_caches(solver,A) return MINRESNumericalSetup(solver,A,Pl_ns,caches) end function Gridap.Algebra.numerical_setup!(ns::MINRESNumericalSetup, A::AbstractMatrix) if !isa(ns.Pl_ns,Nothing) numerical_setup!(ns.Pl_ns,A) end ns.A = A end function Gridap.Algebra.numerical_setup!(ns::MINRESNumericalSetup, A::AbstractMatrix, x::AbstractVector) if !isa(ns.Pl_ns,Nothing) numerical_setup!(ns.Pl_ns,A,x) end ns.A = A return ns end function Gridap.Algebra.solve!(x::AbstractVector,ns::MINRESNumericalSetup,b::AbstractVector) solver, A, Pl, caches = ns.solver, ns.A, ns.Pl_ns, ns.caches Vs, Ws, Zs = caches log = solver.log Vnew, V, Vold = Vs Wnew, W, Wold = Ws Znew, Z, Zold = Zs T = eltype(A) fill!(W,zero(T)) fill!(Wold,zero(T)) fill!(Vold,zero(T)) fill!(Zold,zero(T)) mul!(Vnew,A,x) Vnew .= b .- Vnew fill!(Znew,zero(T)) !isnothing(Pl) ? solve!(Znew,Pl,Vnew) : copy!(Znew,Vnew) β_r = norm(Znew) β_p = dot(Znew,Vnew) @check β_p > zero(T) γnew, γ, γold = zero(T), sqrt(β_p), one(T) cnew, c, cold = zero(T), one(T), one(T) snew, s, sold = zero(T), zero(T), zero(T) V .= Vnew ./ γ Z .= Znew ./ γ η = γ done = init!(log,β_r) while !done # Lanczos process mul!(Vnew,A,Z) !isnothing(Pl) ? solve!(Znew,Pl,Vnew) : copy!(Znew,Vnew) δ = dot(Vnew,Z) Vnew .= Vnew .- δ .* V .- γ .* Vold Znew .= Znew .- δ .* Z .- γ .* Zold β_p = dot(Znew,Vnew) γnew = sqrt(β_p) Vnew .= Vnew ./ γnew Znew .= Znew ./ γnew # Update QR α0 = c*δ - cold*s*γ cnew, snew, α1 = LinearAlgebra.givensAlgorithm(α0,γnew) α2 = s*δ + cold*c*γ α3 = sold*γ # Update solution Wnew .= (Z .- α2 .* W .- α3 .* Wold) ./ α1 x .= x .+ (cnew*η) .* Wnew η = - snew * η # Update residual β_r = abs(snew) * β_r # Swap variables swap3(xnew,x,xold) = xold, xnew, x Vnew, V, Vold = swap3(Vnew, V, Vold) Wnew, W, Wold = swap3(Wnew, W, Wold) Znew, Z, Zold = swap3(Znew, Z, Zold) γnew, γ, γold = swap3(γnew, γ, γold) cnew, c, cold = swap3(cnew, c, cold) snew, s, sold = swap3(snew, s, sold) done = update!(log,β_r) end finalize!(log,β_r) return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
4695
""" struct ElasticitySolver <: LinearSolver ... end GMRES + AMG solver, specifically designed for linear elasticity problems. Follows PETSc's documentation for [PCAMG](https://petsc.org/release/manualpages/PC/PCGAMG.html) and [MatNullSpaceCreateRigidBody](https://petsc.org/release/manualpages/Mat/MatNullSpaceCreateRigidBody.html). """ struct ElasticitySolver{A} <: Algebra.LinearSolver space :: A tols :: SolverTolerances{Float64} @doc """ function ElasticitySolver(space::FESpace; maxiter=500, atol=1.e-12, rtol=1.e-8) Returns an instance of [`ElasticitySolver`](@ref) from its underlying properties. """ function ElasticitySolver(space::FESpace; maxiter=500,atol=1.e-12,rtol=1.e-8) tols = SolverTolerances{Float64}(;maxiter=maxiter,atol=atol,rtol=rtol) A = typeof(space) new{A}(space,tols) end end SolverInterfaces.get_solver_tolerances(s::ElasticitySolver) = s.tols struct ElasticitySymbolicSetup{A} <: SymbolicSetup solver::A end function Gridap.Algebra.symbolic_setup(solver::ElasticitySolver,A::AbstractMatrix) ElasticitySymbolicSetup(solver) end function elasticity_ksp_setup(ksp,tols) rtol = PetscScalar(tols.rtol) atol = PetscScalar(tols.atol) dtol = PetscScalar(tols.dtol) maxits = PetscInt(tols.maxiter) @check_error_code GridapPETSc.PETSC.KSPSetType(ksp[],GridapPETSc.PETSC.KSPCG) @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) @check_error_code GridapPETSc.PETSC.KSPView(ksp[],C_NULL) end mutable struct ElasticityNumericalSetup <: NumericalSetup A::PETScMatrix X::PETScVector B::PETScVector ksp::Ref{GridapPETSc.PETSC.KSP} null::Ref{GridapPETSc.PETSC.MatNullSpace} initialized::Bool function ElasticityNumericalSetup(A::PETScMatrix,X::PETScVector,B::PETScVector) ksp = Ref{GridapPETSc.PETSC.KSP}() null = Ref{GridapPETSc.PETSC.MatNullSpace}() new(A,X,B,ksp,null,false) end end function GridapPETSc.Init(a::ElasticityNumericalSetup) @assert Threads.threadid() == 1 GridapPETSc._NREFS[] += 2 a.initialized = true finalizer(GridapPETSc.Finalize,a) end function GridapPETSc.Finalize(ns::ElasticityNumericalSetup) if ns.initialized && GridapPETSc.Initialized() if ns.A.comm == MPI.COMM_SELF @check_error_code GridapPETSc.PETSC.KSPDestroy(ns.ksp) @check_error_code GridapPETSc.PETSC.MatNullSpaceDestroy(ns.null) else @check_error_code GridapPETSc.PETSC.PetscObjectRegisterDestroy(ns.ksp[].ptr) @check_error_code GridapPETSc.PETSC.PetscObjectRegisterDestroy(ns.null[].ptr) end ns.initialized = false @assert Threads.threadid() == 1 GridapPETSc._NREFS[] -= 2 end nothing end function Gridap.Algebra.numerical_setup(ss::ElasticitySymbolicSetup,_A::PSparseMatrix) _num_dims(space::FESpace) = num_cell_dims(get_triangulation(space)) _num_dims(space::GridapDistributed.DistributedSingleFieldFESpace) = getany(map(_num_dims,local_views(space))) s = ss.solver # Create ns A = convert(PETScMatrix,_A) X = convert(PETScVector,allocate_in_domain(_A)) B = convert(PETScVector,allocate_in_domain(_A)) ns = ElasticityNumericalSetup(A,X,B) # Compute coordinates for owned dofs dof_coords = convert(PETScVector,get_dof_coordinates(s.space)) @check_error_code GridapPETSc.PETSC.VecSetBlockSize(dof_coords.vec[],_num_dims(s.space)) # Create matrix nullspace @check_error_code GridapPETSc.PETSC.MatNullSpaceCreateRigidBody(dof_coords.vec[],ns.null) @check_error_code GridapPETSc.PETSC.MatSetNearNullSpace(ns.A.mat[],ns.null[]) # Setup solver and preconditioner @check_error_code GridapPETSc.PETSC.KSPCreate(ns.A.comm,ns.ksp) @check_error_code GridapPETSc.PETSC.KSPSetOperators(ns.ksp[],ns.A.mat[],ns.A.mat[]) elasticity_ksp_setup(ns.ksp,s.tols) @check_error_code GridapPETSc.PETSC.KSPSetUp(ns.ksp[]) GridapPETSc.Init(ns) end function Gridap.Algebra.numerical_setup!(ns::ElasticityNumericalSetup,A::AbstractMatrix) ns.A = convert(PETScMatrix,A) @check_error_code GridapPETSc.PETSC.MatSetNearNullSpace(ns.A.mat[],ns.null[]) @check_error_code GridapPETSc.PETSC.KSPSetOperators(ns.ksp[],ns.A.mat[],ns.A.mat[]) @check_error_code GridapPETSc.PETSC.KSPSetUp(ns.ksp[]) ns end function Algebra.solve!(x::AbstractVector{PetscScalar},ns::ElasticityNumericalSetup,b::AbstractVector{PetscScalar}) X, B = ns.X, ns.B copy!(B,b) @check_error_code GridapPETSc.PETSC.KSPSolve(ns.ksp[],B.vec[],X.vec[]) copy!(x,X) return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
2349
function ADS_Solver(model,tags,order;rtol=1e-8,maxits=300) @assert (num_cell_dims(model) == 3) "Not implemented for 2D" @assert (order == 1) "Only works for linear order" V_H1_sc, V_H1, V_Hdiv, V_Hcurl = get_ads_spaces(model,order,tags) G, C, Π_div, Π_curl = get_ads_operators(V_H1_sc,V_H1,V_Hcurl,V_Hdiv) D = num_cell_dims(model) ksp_setup(ksp) = ads_ksp_setup(ksp,rtol,maxits,D,G,C,Π_div,Π_curl) return PETScLinearSolver(ksp_setup) end function get_ads_spaces(model,order,tags) reffe_H1_sc = ReferenceFE(lagrangian,Float64,order) V_H1_sc = FESpace(model,reffe_H1_sc;dirichlet_tags=tags) reffe_H1 = ReferenceFE(lagrangian,VectorValue{D,Float64},order) V_H1 = FESpace(model,reffe_H1;dirichlet_tags=tags) reffe_Hdiv = ReferenceFE(raviart_thomas,Float64,order-1) V_Hdiv = FESpace(model,reffe_Hdiv;dirichlet_tags=tags) reffe_Hcurl = ReferenceFE(nedelec,Float64,order-1) V_Hcurl = FESpace(model,reffe_Hcurl;dirichlet_tags=tags) return V_H1_sc, V_H1, V_Hdiv, V_Hcurl end function get_ads_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 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
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
1690
""" struct CachedPETScNS <: NumericalSetup ... end Wrapper around a PETSc NumericalSetup, providing highly efficiend reusable caches: When converting julia vectors/PVectors to PETSc vectors, we purposely create aliasing of the vector values. This means we can avoid copying data from one to another before solving, but we need to be careful about it. This structure takes care of this, and makes sure you do not attempt to solve the system with julia vectors that are not the ones you used to create the solver cache. """ struct CachedPETScNS{TM,A} ns :: GridapPETSc.PETScLinearSolverNS{TM} X :: PETScVector B :: PETScVector owners :: A @doc """ function CachedPETScNS(ns::PETScLinearSolverNS,x::AbstractVector,b::AbstractVector) Create a new instance of [`CachedPETScNS`](@ref) from its underlying properties. Once this structure is created, you can **only** solve the system with the same vectors you used to create it. """ function CachedPETScNS(ns::GridapPETSc.PETScLinearSolverNS{TM},x::AbstractVector,b::AbstractVector) where TM X = convert(PETScVector,x) B = convert(PETScVector,b) owners = (x,b) A = typeof(owners) new{TM,A}(ns,X,B,owners) end end function Algebra.solve!(x::AbstractVector,ns::CachedPETScNS,b::AbstractVector) @assert x === ns.owners[1] @assert b === ns.owners[2] solve!(ns.X,ns.ns,ns.B) consistent!(x) return x end function Algebra.numerical_setup!(ns::CachedPETScNS,mat::AbstractMatrix) numerical_setup!(ns.ns,mat) end function Algebra.numerical_setup!(ns::CachedPETScNS,mat::AbstractMatrix,x::AbstractVector) numerical_setup!(ns.ns,mat,x) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
5230
# DoF coordinates """ get_dof_coordinates(space::FESpace) Given a lagrangian FESpace, returns the physical coordinates of the DoFs, as required by some PETSc solvers. See [PETSc documentation](https://petsc.org/release/manualpages/PC/PCSetCoordinates.html). """ function get_dof_coordinates(space::GridapDistributed.DistributedSingleFieldFESpace) coords = map(local_views(space),partition(space.gids)) do space, dof_ids local_to_own_dofs = local_to_own(dof_ids) return get_dof_coordinates(space;perm=local_to_own_dofs) 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 get_dof_coordinates(space::FESpace;perm=Base.OneTo(num_free_dofs(space))) trian = get_triangulation(space) cell_dofs = get_fe_dof_basis(space) cell_ids = get_cell_dof_ids(space) cell_ref_nodes = lazy_map(get_nodes,CellData.get_data(cell_dofs)) cell_dof_to_node = lazy_map(get_dof_to_node,CellData.get_data(cell_dofs)) cell_dof_to_comp = lazy_map(get_dof_to_comp,CellData.get_data(cell_dofs)) cmaps = get_cell_map(trian) cell_phys_nodes = lazy_map(evaluate,cmaps,cell_ref_nodes) node_coords = Vector{Float64}(undef,maximum(perm)) cache_nodes = array_cache(cell_phys_nodes) cache_ids = array_cache(cell_ids) cache_dof_to_node = array_cache(cell_dof_to_node) cache_dof_to_comp = array_cache(cell_dof_to_comp) for cell in 1:num_cells(trian) ids = getindex!(cache_ids,cell_ids,cell) nodes = getindex!(cache_nodes,cell_phys_nodes,cell) dof_to_comp = getindex!(cache_dof_to_comp,cell_dof_to_comp,cell) dof_to_node = getindex!(cache_dof_to_node,cell_dof_to_node,cell) for (dof,c,n) in zip(ids,dof_to_comp,dof_to_node) if (dof > 0) && (perm[dof] > 0) node_coords[perm[dof]] = nodes[n][c] end end end return node_coords end # Interpolation matrices 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
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
14690
""" """ struct DistributedGridTransferOperator{T,R,M,A,B} sh :: A cache :: B function DistributedGridTransferOperator( op_type::Symbol,redist::Bool,restriction_method::Symbol,sh::FESpaceHierarchy,cache ) T = typeof(Val(op_type)) R = typeof(Val(redist)) M = typeof(Val(restriction_method)) A = typeof(sh) B = typeof(cache) new{T,R,M,A,B}(sh,cache) end end ### Constructors """ """ function RestrictionOperator(lev::Int,sh::FESpaceHierarchy,qdegree::Int;kwargs...) return DistributedGridTransferOperator(lev,sh,qdegree,:restriction;kwargs...) end """ """ function ProlongationOperator(lev::Int,sh::FESpaceHierarchy,qdegree::Int;kwargs...) return DistributedGridTransferOperator(lev,sh,qdegree,:prolongation;kwargs...) end function DistributedGridTransferOperator( lev::Int,sh::FESpaceHierarchy,qdegree::Int,op_type::Symbol; mode::Symbol=:solution,restriction_method::Symbol=:projection, solver=LUSolver() ) @check lev < num_levels(sh) @check op_type ∈ [:restriction, :prolongation] @check mode ∈ [:solution, :residual] @check restriction_method ∈ [:projection, :interpolation, :dof_mask] # Refinement if (op_type == :prolongation) || (restriction_method ∈ [:interpolation,:dof_mask]) cache_refine = _get_interpolation_cache(lev,sh,qdegree,mode) elseif mode == :solution cache_refine = _get_projection_cache(lev,sh,qdegree,mode,solver) else cache_refine = _get_dual_projection_cache(lev,sh,qdegree,solver) restriction_method = :dual_projection end # Redistribution redist = has_redistribution(sh,lev) cache_redist = _get_redistribution_cache(lev,sh,mode,op_type,restriction_method,cache_refine) cache = cache_refine, cache_redist return DistributedGridTransferOperator(op_type,redist,restriction_method,sh,cache) end function _get_interpolation_cache(lev::Int,sh::FESpaceHierarchy,qdegree::Int,mode::Symbol) cparts = get_level_parts(sh,lev+1) if i_am_in(cparts) model_h = get_model_before_redist(sh,lev) Uh = get_fe_space_before_redist(sh,lev) fv_h = pfill(0.0,partition(Uh.gids)) dv_h = (mode == :solution) ? get_dirichlet_dof_values(Uh) : zero_dirichlet_values(Uh) UH = get_fe_space(sh,lev+1) fv_H = pfill(0.0,partition(UH.gids)) dv_H = (mode == :solution) ? get_dirichlet_dof_values(UH) : zero_dirichlet_values(UH) cache_refine = model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H else model_h = get_model_before_redist(sh,lev) Uh = get_fe_space_before_redist(sh,lev) cache_refine = model_h, Uh, nothing, nothing, nothing, nothing, nothing end return cache_refine end function _get_projection_cache(lev::Int,sh::FESpaceHierarchy,qdegree::Int,mode::Symbol,solver) cparts = get_level_parts(sh,lev+1) if i_am_in(cparts) model_h = get_model_before_redist(sh,lev) Uh = get_fe_space_before_redist(sh,lev) Ωh = Triangulation(model_h) fv_h = zero_free_values(Uh) dv_h = (mode == :solution) ? get_dirichlet_dof_values(Uh) : zero_dirichlet_values(Uh) model_H = get_model(sh,lev+1) UH = get_fe_space(sh,lev+1) VH = get_fe_space(sh,lev+1) ΩH = Triangulation(model_H) dΩH = Measure(ΩH,qdegree) dΩhH = Measure(ΩH,Ωh,qdegree) aH(u,v) = ∫(v⋅u)*dΩH lH(v,uh) = ∫(v⋅uh)*dΩhH assem = SparseMatrixAssembler(UH,VH) fv_H = zero_free_values(UH) dv_H = zero_dirichlet_values(UH) u0 = FEFunction(UH,fv_H,true) # Zero at free dofs u00 = FEFunction(UH,fv_H,dv_H,true) # Zero everywhere u_dir = (mode == :solution) ? u0 : u00 u,v = get_trial_fe_basis(UH), get_fe_basis(VH) data = collect_cell_matrix_and_vector(UH,VH,aH(u,v),lH(v,u00),u_dir) AH,bH0 = assemble_matrix_and_vector(assem,data) AH_ns = numerical_setup(symbolic_setup(solver,AH),AH) xH = allocate_in_domain(AH); fill!(xH,zero(eltype(xH))) bH = copy(bH0) cache_refine = model_h, Uh, fv_h, dv_h, VH, AH_ns, lH, xH, bH, bH0, assem else model_h = get_model_before_redist(sh,lev) Uh = get_fe_space_before_redist(sh,lev) cache_refine = model_h, Uh, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing end return cache_refine end function _get_dual_projection_cache(lev::Int,sh::FESpaceHierarchy,qdegree::Int,solver) cparts = get_level_parts(sh,lev+1) if i_am_in(cparts) model_h = get_model_before_redist(sh,lev) Uh = get_fe_space_before_redist(sh,lev) Ωh = Triangulation(model_h) dΩh = Measure(Ωh,qdegree) uh = FEFunction(Uh,zero_free_values(Uh),zero_dirichlet_values(Uh)) model_H = get_model(sh,lev+1) UH = get_fe_space(sh,lev+1) ΩH = Triangulation(model_H) dΩhH = Measure(ΩH,Ωh,qdegree) Mh = assemble_matrix((u,v)->∫(v⋅u)*dΩh,Uh,Uh) Mh_ns = numerical_setup(symbolic_setup(solver,Mh),Mh) assem = SparseMatrixAssembler(UH,UH) rh = allocate_in_domain(Mh); fill!(rh,zero(eltype(rh))) cache_refine = model_h, Uh, UH, Mh_ns, rh, uh, assem, dΩhH else model_h = get_model_before_redist(sh,lev) Uh = get_fe_space_before_redist(sh,lev) cache_refine = model_h, Uh, nothing, nothing, nothing, nothing, nothing, nothing end return cache_refine end function _get_redistribution_cache(lev::Int,sh::FESpaceHierarchy,mode::Symbol,op_type::Symbol,restriction_method::Symbol,cache_refine) redist = has_redistribution(sh,lev) if !redist cache_redist = nothing return cache_redist end Uh_red = get_fe_space(sh,lev) model_h_red = get_model(sh,lev) fv_h_red = pfill(0.0,partition(Uh_red.gids)) dv_h_red = (mode == :solution) ? get_dirichlet_dof_values(Uh_red) : zero_dirichlet_values(Uh_red) glue = sh[lev].mh_level.red_glue if (op_type == :prolongation) || (restriction_method ∈ [:interpolation,:dof_mask]) model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine cache_exchange = get_redistribute_free_values_cache(fv_h_red,Uh_red,fv_h,dv_h,Uh,model_h_red,glue;reverse=false) elseif restriction_method == :projection model_h, Uh, fv_h, dv_h, VH, AH, lH, xH, bH, bH0, assem = cache_refine cache_exchange = get_redistribute_free_values_cache(fv_h,Uh,fv_h_red,dv_h_red,Uh_red,model_h,glue;reverse=true) else model_h, Uh, UH, Mh, rh, uh, assem, dΩhH = cache_refine fv_h = isa(uh,Nothing) ? nothing : get_free_dof_values(uh) cache_exchange = get_redistribute_free_values_cache(fv_h,Uh,fv_h_red,dv_h_red,Uh_red,model_h,glue;reverse=true) end cache_redist = fv_h_red, dv_h_red, Uh_red, model_h_red, glue, cache_exchange return cache_redist end # TODO: Please replace this type of functions by a map functionality over hierarchies function setup_transfer_operators(sh::FESpaceHierarchy,qdegree;kwargs...) prolongations = setup_prolongation_operators(sh,qdegree;kwargs...) restrictions = setup_restriction_operators(sh,qdegree;kwargs...) return restrictions, prolongations end function setup_prolongation_operators(sh::FESpaceHierarchy,qdegree::Integer;kwargs...) qdegrees = Fill(qdegree,num_levels(sh)) return setup_prolongation_operators(sh,qdegrees;kwargs...) end function setup_prolongation_operators(sh::FESpaceHierarchy,qdegrees::AbstractArray{<:Integer};kwargs...) @check length(qdegrees) == num_levels(sh) map(view(linear_indices(sh),1:num_levels(sh)-1)) do lev qdegree = qdegrees[lev] ProlongationOperator(lev,sh,qdegree;kwargs...) end end function setup_restriction_operators(sh::FESpaceHierarchy,qdegree::Integer;kwargs...) qdegrees = Fill(qdegree,num_levels(sh)) return setup_restriction_operators(sh,qdegrees;kwargs...) end function setup_restriction_operators(sh::FESpaceHierarchy,qdegrees::AbstractArray{<:Integer};kwargs...) @check length(qdegrees) == num_levels(sh) map(view(linear_indices(sh),1:num_levels(sh)-1)) do lev qdegree = qdegrees[lev] RestrictionOperator(lev,sh,qdegree;kwargs...) end end ### Applying the operators: # A) Prolongation, without redistribution function LinearAlgebra.mul!(y::PVector,A::DistributedGridTransferOperator{Val{:prolongation},Val{false}},x::PVector) cache_refine, cache_redist = A.cache model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine copy!(fv_H,x) # Matrix layout -> FE layout uH = FEFunction(UH,fv_H,dv_H) uh = interpolate!(uH,fv_h,Uh) copy!(y,fv_h) # FE layout -> Matrix layout return y end # B.1) Restriction, without redistribution, by interpolation function LinearAlgebra.mul!(y::PVector,A::DistributedGridTransferOperator{Val{:restriction},Val{false},Val{:interpolation}},x::PVector) cache_refine, cache_redist = A.cache model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine copy!(fv_h,x) # Matrix layout -> FE layout uh = FEFunction(Uh,fv_h,dv_h) uH = interpolate!(uh,fv_H,UH) copy!(y,fv_H) # FE layout -> Matrix layout return y end # B.2) Restriction, without redistribution, by projection function LinearAlgebra.mul!(y::PVector,A::DistributedGridTransferOperator{Val{:restriction},Val{false},Val{:projection}},x::PVector) cache_refine, cache_redist = A.cache model_h, Uh, fv_h, dv_h, VH, AH_ns, lH, xH, bH, bH0, assem = cache_refine copy!(fv_h,x) # Matrix layout -> FE layout uh = FEFunction(Uh,fv_h,dv_h) v = get_fe_basis(VH) vec_data = collect_cell_vector(VH,lH(v,uh)) copy!(bH,bH0) assemble_vector_add!(bH,assem,vec_data) # Matrix layout solve!(xH,AH_ns,bH) copy!(y,xH) return y end # B.3) Restriction, without redistribution, by dof selection (only nodal dofs) function LinearAlgebra.mul!(y::PVector,A::DistributedGridTransferOperator{Val{:restriction},Val{false},Val{:dof_mask}},x::PVector) cache_refine, cache_redist = A.cache model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine copy!(fv_h,x) # Matrix layout -> FE layout consistent!(fv_h) |> fetch restrict_dofs!(fv_H,fv_h,dv_h,Uh,UH,get_adaptivity_glue(model_h)) copy!(y,fv_H) # FE layout -> Matrix layout return y end # C) Prolongation, with redistribution function LinearAlgebra.mul!(y::PVector,A::DistributedGridTransferOperator{Val{:prolongation},Val{true}},x::Union{PVector,Nothing}) cache_refine, cache_redist = A.cache model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine fv_h_red, dv_h_red, Uh_red, model_h_red, glue, cache_exchange = cache_redist # 1 - Interpolate in coarse partition if !isa(x,Nothing) copy!(fv_H,x) # Matrix layout -> FE layout uH = FEFunction(UH,fv_H,dv_H) uh = interpolate!(uH,fv_h,Uh) end # 2 - Redistribute from coarse partition to fine partition redistribute_free_values!(cache_exchange,fv_h_red,Uh_red,fv_h,dv_h,Uh,model_h_red,glue;reverse=false) copy!(y,fv_h_red) # FE layout -> Matrix layout return y end # D.1) Restriction, with redistribution, by interpolation function LinearAlgebra.mul!(y::Union{PVector,Nothing},A::DistributedGridTransferOperator{Val{:restriction},Val{true},Val{:interpolation}},x::PVector) cache_refine, cache_redist = A.cache model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine fv_h_red, dv_h_red, Uh_red, model_h_red, glue, cache_exchange = cache_redist # 1 - Redistribute from fine partition to coarse partition copy!(fv_h_red,x) consistent!(fv_h_red) |> fetch redistribute_free_values!(cache_exchange,fv_h,Uh,fv_h_red,dv_h_red,Uh_red,model_h,glue;reverse=true) # 2 - Interpolate in coarse partition if !isa(y,Nothing) uh = FEFunction(Uh,fv_h,dv_h) uH = interpolate!(uh,fv_H,UH) copy!(y,fv_H) # FE layout -> Matrix layout end return y end # D.2) Restriction, with redistribution, by projection function LinearAlgebra.mul!(y::Union{PVector,Nothing},A::DistributedGridTransferOperator{Val{:restriction},Val{true},Val{:projection}},x::PVector) cache_refine, cache_redist = A.cache model_h, Uh, fv_h, dv_h, VH, AH_ns, lH, xH, bH, bH0, assem = cache_refine fv_h_red, dv_h_red, Uh_red, model_h_red, glue, cache_exchange = cache_redist # 1 - Redistribute from fine partition to coarse partition copy!(fv_h_red,x) consistent!(fv_h_red) |> fetch redistribute_free_values!(cache_exchange,fv_h,Uh,fv_h_red,dv_h_red,Uh_red,model_h,glue;reverse=true) # 2 - Solve f2c projection coarse partition if !isa(y,Nothing) consistent!(fv_h) |> fetch uh = FEFunction(Uh,fv_h,dv_h) v = get_fe_basis(VH) vec_data = collect_cell_vector(VH,lH(v,uh)) copy!(bH,bH0) assemble_vector_add!(bH,assem,vec_data) # Matrix layout solve!(xH,AH_ns,bH) copy!(y,xH) end return y end # D.3) Restriction, with redistribution, by dof selection (only nodal dofs) function LinearAlgebra.mul!(y::Union{PVector,Nothing},A::DistributedGridTransferOperator{Val{:restriction},Val{true},Val{:dof_mask}},x::PVector) cache_refine, cache_redist = A.cache model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine fv_h_red, dv_h_red, Uh_red, model_h_red, glue, cache_exchange = cache_redist # 1 - Redistribute from fine partition to coarse partition copy!(fv_h_red,x) consistent!(fv_h_red) |> fetch redistribute_free_values!(cache_exchange,fv_h,Uh,fv_h_red,dv_h_red,Uh_red,model_h,glue;reverse=true) # 2 - Interpolate in coarse partition if !isa(y,Nothing) consistent!(fv_h) |> fetch restrict_dofs!(fv_H,fv_h,dv_h,Uh,UH,get_adaptivity_glue(model_h)) copy!(y,fv_H) # FE layout -> Matrix layout end return y end ############################################################### function LinearAlgebra.mul!(y::PVector,A::DistributedGridTransferOperator{Val{:restriction},Val{false},Val{:dual_projection}},x::PVector) cache_refine, cache_redist = A.cache model_h, Uh, VH, Mh_ns, rh, uh, assem, dΩhH = cache_refine fv_h = get_free_dof_values(uh) solve!(rh,Mh_ns,x) copy!(fv_h,rh) consistent!(fv_h) |> fetch v = get_fe_basis(VH) assemble_vector!(y,assem,collect_cell_vector(VH,∫(v⋅uh)*dΩhH)) return y end function LinearAlgebra.mul!(y::Union{PVector,Nothing},A::DistributedGridTransferOperator{Val{:restriction},Val{true},Val{:dual_projection}},x::PVector) cache_refine, cache_redist = A.cache model_h, Uh, VH, Mh_ns, rh, uh, assem, dΩhH = cache_refine fv_h_red, dv_h_red, Uh_red, model_h_red, glue, cache_exchange = cache_redist fv_h = isa(uh,Nothing) ? nothing : get_free_dof_values(uh) # 1 - Redistribute from fine partition to coarse partition copy!(fv_h_red,x) consistent!(fv_h_red) |> fetch redistribute_free_values!(cache_exchange,fv_h,Uh,fv_h_red,dv_h_red,Uh_red,model_h,glue;reverse=true) # 2 - Solve f2c projection coarse partition if !isa(y,Nothing) solve!(rh,Mh_ns,fv_h) copy!(fv_h,rh) consistent!(fv_h) |> fetch v = get_fe_basis(VH) assemble_vector!(y,assem,collect_cell_vector(VH,∫(v⋅uh)*dΩhH)) end return y end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
6393
struct FESpaceHierarchyLevel{A,B,C,D,E} level :: Int fe_space :: A fe_space_red :: B cell_conformity :: C cell_conformity_red :: D mh_level :: E end """ const FESpaceHierarchy = HierarchicalArray{<:FESpaceHierarchyLevel} A `FESpaceHierarchy` is a hierarchical array of `FESpaceHierarchyLevel` objects. It stores the adapted/redistributed fe spaces and the corresponding subcommunicators. For convenience, implements some of the API of `FESpace`. """ const FESpaceHierarchy = HierarchicalArray{<:FESpaceHierarchyLevel} FESpaces.get_fe_space(sh::FESpaceHierarchy,lev::Int) = get_fe_space(sh[lev]) FESpaces.get_fe_space(a::FESpaceHierarchyLevel{A,Nothing}) where {A} = a.fe_space FESpaces.get_fe_space(a::FESpaceHierarchyLevel{A,B}) where {A,B} = a.fe_space_red get_fe_space_before_redist(sh::FESpaceHierarchy,lev::Int) = get_fe_space_before_redist(sh[lev]) get_fe_space_before_redist(a::FESpaceHierarchyLevel) = a.fe_space get_cell_conformity(sh::FESpaceHierarchy,lev::Int) = get_cell_conformity(sh[lev]) get_cell_conformity(a::FESpaceHierarchyLevel{A,Nothing}) where A = a.cell_conformity get_cell_conformity(a::FESpaceHierarchyLevel{A,B}) where {A,B} = a.cell_conformity_red get_cell_conformity_before_redist(sh::FESpaceHierarchy,lev::Int) = get_cell_conformity_before_redist(sh[lev]) get_cell_conformity_before_redist(a::FESpaceHierarchyLevel) = a.cell_conformity get_model(sh::FESpaceHierarchy,level::Integer) = get_model(sh[level]) get_model(a::FESpaceHierarchyLevel) = get_model(a.mh_level) get_model_before_redist(a::FESpaceHierarchy,level::Integer) = get_model_before_redist(a[level]) get_model_before_redist(a::FESpaceHierarchyLevel) = get_model_before_redist(a.mh_level) has_redistribution(sh::FESpaceHierarchy,level::Integer) = has_redistribution(sh[level]) has_redistribution(a::FESpaceHierarchyLevel) = has_redistribution(a.mh_level) has_refinement(sh::FESpaceHierarchy,level::Integer) = has_refinement(sh[level]) has_refinement(a::FESpaceHierarchyLevel) = has_refinement(a.mh_level) # Test/Trial FESpaces for ModelHierarchyLevels function _cell_conformity( model::DiscreteModel, reffe::Tuple{<:Gridap.FESpaces.ReferenceFEName,Any,Any}; conformity=nothing, kwargs... ) :: CellConformity basis, reffe_args, reffe_kwargs = reffe cell_reffe = ReferenceFE(model,basis,reffe_args...;reffe_kwargs...) conformity = Conformity(Gridap.Arrays.testitem(cell_reffe),conformity) return CellConformity(cell_reffe,conformity) end function _cell_conformity( model::GridapDistributed.DistributedDiscreteModel,args...;kwargs... ) :: AbstractVector{<:CellConformity} cell_conformities = map(local_views(model)) do model _cell_conformity(model,args...;kwargs...) end return cell_conformities end function FESpaces.FESpace(mh::ModelHierarchyLevel,args...;kwargs...) if has_redistribution(mh) cparts, _ = get_old_and_new_parts(mh.red_glue,Val(false)) Vh = i_am_in(cparts) ? FESpace(get_model_before_redist(mh),args...;kwargs...) : nothing Vh_red = FESpace(get_model(mh),args...;kwargs...) cell_conformity = i_am_in(cparts) ? _cell_conformity(get_model_before_redist(mh),args...;kwargs...) : nothing cell_conformity_red = _cell_conformity(get_model(mh),args...;kwargs...) else Vh = FESpace(get_model(mh),args...;kwargs...) Vh_red = nothing cell_conformity = _cell_conformity(get_model(mh),args...;kwargs...) cell_conformity_red = nothing end return FESpaceHierarchyLevel(mh.level,Vh,Vh_red,cell_conformity,cell_conformity_red,mh) end function FESpaces.TrialFESpace(a::FESpaceHierarchyLevel,args...;kwargs...) Uh = !isa(a.fe_space,Nothing) ? TrialFESpace(a.fe_space,args...;kwargs...) : nothing Uh_red = !isa(a.fe_space_red,Nothing) ? TrialFESpace(a.fe_space_red,args...;kwargs...) : nothing return FESpaceHierarchyLevel(a.level,Uh,Uh_red,a.cell_conformity,a.cell_conformity_red,a.mh_level) end # Test/Trial FESpaces for ModelHierarchies/FESpaceHierarchy function FESpaces.FESpace(mh::ModelHierarchy,args...;kwargs...) map(mh) do mhl TestFESpace(mhl,args...;kwargs...) end end function FESpaces.FESpace( mh::ModelHierarchy, arg_vector::AbstractVector{<:Union{ReferenceFE,Tuple{<:ReferenceFEs.ReferenceFEName,Any,Any}}}; kwargs... ) map(linear_indices(mh),mh) do l, mhl args = arg_vector[l] TestFESpace(mhl,args...;kwargs...) end end function FESpaces.TrialFESpace(sh::FESpaceHierarchy,u) map(sh) do shl TrialFESpace(shl,u) end end function FESpaces.TrialFESpace(sh::FESpaceHierarchy) map(TrialFESpace,sh) end # MultiField support function Gridap.MultiField.MultiFieldFESpace(spaces::Vector{<:FESpaceHierarchyLevel};kwargs...) level = spaces[1].level Uh = all(map(s -> !isa(s.fe_space,Nothing),spaces)) ? MultiFieldFESpace(map(s -> s.fe_space, spaces); kwargs...) : nothing Uh_red = all(map(s -> !isa(s.fe_space_red,Nothing),spaces)) ? MultiFieldFESpace(map(s -> s.fe_space_red, spaces); kwargs...) : nothing cell_conformity = map(s -> s.cell_conformity, spaces) cell_conformity_red = map(s -> s.cell_conformity_red, spaces) return FESpaceHierarchyLevel(level,Uh,Uh_red,cell_conformity,cell_conformity_red,first(spaces).mh_level) end function Gridap.MultiField.MultiFieldFESpace(spaces::Vector{<:HierarchicalArray};kwargs...) @check all(s -> isa(s,FESpaceHierarchy),spaces) map(spaces...) do spaces_i... MultiFieldFESpace([spaces_i...];kwargs...) end end # Computing system matrices function compute_hierarchy_matrices( trials::FESpaceHierarchy, tests::FESpaceHierarchy, a::Function, l::Function, qdegree::Integer ) return compute_hierarchy_matrices(trials,tests,a,l,Fill(qdegree,num_levels(trials))) end function compute_hierarchy_matrices( trials::FESpaceHierarchy, tests::FESpaceHierarchy, a::Function, l::Function, qdegree::AbstractArray{<:Integer} ) mats, vecs = map(linear_indices(trials)) do lev model = get_model(trials,lev) U = get_fe_space(trials,lev) V = get_fe_space(tests,lev) Ω = Triangulation(model) dΩ = Measure(Ω,qdegree[lev]) ai(u,v) = a(u,v,dΩ) if lev == 1 li(v) = l(v,dΩ) op = AffineFEOperator(ai,li,U,V) return get_matrix(op), get_vector(op) else return assemble_matrix(ai,U,V), nothing end end |> tuple_of_arrays return mats, mats[1], vecs[1] end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
2527
""" function Base.map(::typeof(Gridap.Arrays.testitem), a::Tuple{<:AbstractVector{<:AbstractVector{<:VectorValue}},<:AbstractVector{<:Gridap.Fields.LinearCombinationFieldVector}}) a2=Gridap.Arrays.testitem(a[2]) a1=Vector{eltype(eltype(a[1]))}(undef,size(a2,1)) a1.=zero(Gridap.Arrays.testitem(a1)) (a1,a2) end """ # MultiField/DistributedMultiField missing API """ function Gridap.FESpaces.zero_dirichlet_values(f::MultiFieldFESpace) map(zero_dirichlet_values,f.spaces) end function Gridap.FESpaces.interpolate_everywhere!(objects,free_values::AbstractVector,dirichlet_values::Vector,fe::MultiFieldFESpace) blocks = SingleFieldFEFunction[] for (field, (U,object)) in enumerate(zip(fe.spaces,objects)) free_values_i = restrict_to_field(fe,free_values,field) dirichlet_values_i = dirichlet_values[field] uhi = interpolate!(object, free_values_i, dirichlet_values_i, U) push!(blocks,uhi) end Gridap.MultiField.MultiFieldFEFunction(free_values,fe,blocks) end function Gridap.FESpaces.interpolate!(objects::GridapDistributed.DistributedMultiFieldFEFunction,free_values::AbstractVector,fe::GridapDistributed.DistributedMultiFieldFESpace) part_fe_fun = map(local_views(objects),partition(free_values),local_views(fe)) do objects,x,f interpolate!(objects,x,f) end field_fe_fun = GridapDistributed.DistributedSingleFieldFEFunction[] for i in 1:num_fields(fe) free_values_i = Gridap.MultiField.restrict_to_field(fe,free_values,i) fe_space_i = fe.field_fe_space[i] fe_fun_i = FEFunction(fe_space_i,free_values_i) push!(field_fe_fun,fe_fun_i) end GridapDistributed.DistributedMultiFieldFEFunction(field_fe_fun,part_fe_fun,free_values) end function Gridap.FESpaces.FEFunction( f::GridapDistributed.DistributedMultiFieldFESpace,x::AbstractVector, dirichlet_values::AbstractArray{<:AbstractVector},isconsistent=false ) free_values = GridapDistributed.change_ghost(x,f.gids;is_consistent=isconsistent,make_consistent=true) part_fe_fun = map(FEFunction,f.part_fe_space,partition(free_values)) field_fe_fun = GridapDistributed.DistributedSingleFieldFEFunction[] for i in 1:num_fields(f) free_values_i = Gridap.MultiField.restrict_to_field(f,free_values,i) dirichlet_values_i = dirichlet_values[i] fe_space_i = f.field_fe_space[i] fe_fun_i = FEFunction(fe_space_i,free_values_i,dirichlet_values_i,true) push!(field_fe_fun,fe_fun_i) end GridapDistributed.DistributedMultiFieldFEFunction(field_fe_fun,part_fe_fun,free_values) end """
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
4353
""" HierarchicalArray{T,A,B} <: AbstractVector{T} Array of hierarchical (nested) distributed objects. Each level might live in a different subcommunicator. If a processor does not belong to subcommunicator `ranks[i]`, then `array[i]` is `nothing`. However, it assumes: - The subcommunicators are nested, so that `ranks[i]` contains `ranks[i+1]`. - The first subcommunicator does not have empty parts. """ struct HierarchicalArray{T,A,B} <: AbstractVector{T} array :: A ranks :: B function HierarchicalArray{T}(array::AbstractVector,ranks::AbstractVector) where T @assert length(array) == length(ranks) A = typeof(array) B = typeof(ranks) new{T,A,B}(array,ranks) end end function HierarchicalArray(array,ranks) T = typejoin(filter(t -> t != Nothing, map(typeof,array))...) HierarchicalArray{T}(array,ranks) end function HierarchicalArray{T}(::UndefInitializer,ranks::AbstractVector) where T array = Vector{Union{Nothing,T}}(undef,length(ranks)) HierarchicalArray{T}(array,ranks) end Base.length(a::HierarchicalArray) = length(a.array) Base.size(a::HierarchicalArray) = (length(a),) function Base.getindex(a::HierarchicalArray,i::Integer) msg = "Processor does not belong to subcommunicator $i." @assert i_am_in(a.ranks[i]) msg a.array[i] end function Base.setindex!(a::HierarchicalArray,v,i::Integer) msg = "Processor does not belong to subcommunicator $i." @assert i_am_in(a.ranks[i]) msg a.array[i] = v return v end # Unsafe getindex: Returns the value without # checking if the processor belongs to the subcommunicator. unsafe_getindex(a::HierarchicalArray,i::Integer) = getindex(a.array,i) unsafe_getindex(a::AbstractArray,i::Integer) = getindex(a,i) function Base.view(a::HierarchicalArray{T},I) where T return HierarchicalArray{T}(view(a.array,I),view(a.ranks,I)) end Base.IndexStyle(::Type{HierarchicalArray}) = IndexLinear() function PartitionedArrays.linear_indices(a::HierarchicalArray) ids = LinearIndices(a.array) return HierarchicalArray{eltype(ids)}(ids,a.ranks) end function Base.show(io::IO,k::MIME"text/plain",data::HierarchicalArray{T}) where T println(io,"HierarchicalArray{$T}") end num_levels(a::HierarchicalArray) = length(a.ranks) get_level_parts(a::HierarchicalArray) = a.ranks get_level_parts(a::HierarchicalArray,lev) = a.ranks[lev] function matching_level_parts(a::HierarchicalArray,b::HierarchicalArray) @assert num_levels(a) == num_levels(b) return all(map(===, get_level_parts(a), get_level_parts(b))) end function matching_level_parts(arrays::Vararg{HierarchicalArray,N}) where N a1 = first(arrays) return all(a -> matching_level_parts(a1,a), arrays) end """ Base.map(f::Function,args::Vararg{HierarchicalArray,N}) where N Maps a function to a set of `HierarchicalArrays`. The function is applied only in the subcommunicators where the processor belongs to. """ function Base.map(f,args::Vararg{HierarchicalArray,N}) where N @assert matching_level_parts(args...) ranks = get_level_parts(first(args)) arrays = map(a -> a.array, args) array = map(ranks, arrays...) do ranks, arrays... if i_am_in(ranks) f(arrays...) else nothing end end return HierarchicalArray(array,ranks) end function Base.map(f,a::HierarchicalArray) array = map(a.ranks, a.array) do ranks, ai if i_am_in(ranks) f(ai) else nothing end end return HierarchicalArray(array,a.ranks) end function Base.map!(f,a::HierarchicalArray,args::Vararg{HierarchicalArray,N}) where N @assert matching_level_parts(a,args...) ranks = get_level_parts(a) arrays = map(a -> a.array, args) map(ranks, a.array, arrays...) do ranks, ai, arrays... if i_am_in(ranks) ai = f(arrays...) else nothing end end return a end """ with_level(f::Function,a::HierarchicalArray,lev::Integer;default=nothing) Applies a function to the `lev`-th level of a `HierarchicalArray`. If the processor does not belong to the subcommunicator of the `lev`-th level, then `default` is returned. """ function with_level(f::Function,a::HierarchicalArray,lev::Integer;default=nothing) if i_am_in(a.ranks[lev]) return f(a.array[lev]) else return default end end function with_level(f::Function,a::AbstractArray,lev::Integer;default=nothing) f(a.array[lev]) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
7727
""" abstract type LocalProjectionMap{T} <: Map end """ abstract type LocalProjectionMap{T} <: Map end ## LocalProjectionMap API function Arrays.evaluate!( cache, k::LocalProjectionMap, u::GridapDistributed.DistributedCellField ) fields = map(local_views(u)) do u evaluate!(nothing,k,u) end return GridapDistributed.DistributedCellField(fields,u.trian) end function Arrays.evaluate!( cache,k::LocalProjectionMap,u::MultiField.MultiFieldFEBasisComponent ) nfields, fieldid = u.nfields, u.fieldid block_fields(fields,::TestBasis) = lazy_map(BlockMap(nfields,fieldid),fields) block_fields(fields,::TrialBasis) = lazy_map(BlockMap((1,nfields),fieldid),fields) sf = evaluate!(nothing,k,u.single_field) sf_data = CellData.get_data(sf) mf_data = block_fields(sf_data,BasisStyle(u.single_field)) return CellData.similar_cell_field(sf,mf_data,get_triangulation(sf),DomainStyle(sf)) end function Arrays.evaluate!( cache,k::LocalProjectionMap,v::SingleFieldFEBasis{<:TestBasis} ) cell_v = CellData.get_data(v) cell_u = lazy_map(transpose,cell_v) u = FESpaces.similar_fe_basis(v,cell_u,get_triangulation(v),TrialBasis(),DomainStyle(v)) data = _compute_local_projections(k,u) return GenericCellField(data,get_triangulation(u),ReferenceDomain()) end function Arrays.evaluate!( cache,k::LocalProjectionMap,u::SingleFieldFEBasis{<:TrialBasis} ) _data = _compute_local_projections(k,u) data = lazy_map(transpose,_data) return GenericCellField(data,get_triangulation(u),ReferenceDomain()) end function Arrays.evaluate!( cache,k::LocalProjectionMap,u::SingleFieldFEFunction ) data = _compute_local_projections(k,u) return GenericCellField(data,get_triangulation(u),ReferenceDomain()) end """ struct ReffeProjectionMap{T} <: LocalProjectionMap{T} op :: Operation{T} reffe :: Tuple{<:ReferenceFEName,Any,Any} qdegree :: Int end Map that projects a field/field-basis onto another local reference space given by a `ReferenceFE`. Example: ```julia model = CartesianDiscreteModel((0,1,0,1),(2,2)) reffe_h1 = ReferenceFE(QUAD,lagrangian,Float64,1,space=:Q) reffe_l2 = ReferenceFE(QUAD,lagrangian,Float64,1,space=:P) U = FESpace(model,reffe_h1) u_h1 = interpolate(f,U) Ω = Triangulation(model) dΩ = Measure(Ω,2) Π = LocalProjectionMap(reffe_l2) u_l2 = Π(u_h1,dΩ) ``` """ struct ReffeProjectionMap{T,A} <: LocalProjectionMap{T} op::Operation{T} reffe::A qdegree::Int function ReffeProjectionMap( op::Function, reffe::Tuple{<:ReferenceFEName,Any,Any}, qdegree::Integer ) T = typeof(op) A = typeof(reffe) return new{T,A}(Operation(op),reffe,Int(qdegree)) end end function LocalProjectionMap( op::Function, reffe::Tuple{<:ReferenceFEName,Any,Any}, qdegree::Integer=2*maximum(reffe[2][2]) ) ReffeProjectionMap(op,reffe,qdegree) end function LocalProjectionMap(op::Function,basis::ReferenceFEName,args...;kwargs...) LocalProjectionMap(op,(basis,args,kwargs)) end function LocalProjectionMap(basis::ReferenceFEName,args...;kwargs...) LocalProjectionMap(identity,basis,args...;kwargs...) end # We expect the input to be in `TrialBasis` style. function _compute_local_projections( k::ReffeProjectionMap,u::CellField ) Ω = get_triangulation(u) dΩ = Measure(Ω,k.qdegree) basis, args, kwargs = k.reffe cell_polytopes = lazy_map(get_polytope,get_cell_reffe(Ω)) cell_reffe = lazy_map(p -> ReferenceFE(p,basis,args...;kwargs...),cell_polytopes) test_shapefuns = lazy_map(get_shapefuns,cell_reffe) trial_shapefuns = lazy_map(transpose,test_shapefuns) p = SingleFieldFEBasis(trial_shapefuns,Ω,TrialBasis(),ReferenceDomain()) q = SingleFieldFEBasis(test_shapefuns,Ω,TestBasis(),ReferenceDomain()) op = k.op.op lhs_data = get_array(∫(p⋅q)dΩ) rhs_data = get_array(∫(q⋅op(u))dΩ) basis_data = CellData.get_data(q) return lazy_map(k,lhs_data,rhs_data,basis_data) end # Note on the caches: # - We CANNOT overwrite `lhs`: In the case of constant cell_maps and `u` being a `FEFunction`, # the lhs will be a Fill, but the rhs will not be optimized (regular LazyArray). # In that case, we will see multiple times the same `lhs` being used for different `rhs`. # - The converse never happens (I think), so we can overwrite `rhs` since it will always be recomputed. function Arrays.return_cache(::LocalProjectionMap,lhs::Matrix{T},rhs::A,basis) where {T,A<:Union{Matrix{T},Vector{T}}} return CachedArray(copy(lhs)), CachedArray(copy(rhs)) end function Arrays.evaluate!(cache,::LocalProjectionMap,lhs::Matrix{T},rhs::A,basis) where {T,A<:Union{Matrix{T},Vector{T}}} cmat, cvec = cache setsize!(cmat,size(lhs)) mat = cmat.array copyto!(mat,lhs) setsize!(cvec,size(rhs)) vec = cvec.array copyto!(vec,rhs) f = cholesky!(mat,NoPivot();check=false) @check issuccess(f) "Factorization failed" ldiv!(f,vec) return linear_combination(vec,basis) end """ struct SpaceProjectionMap{T} <: LocalProjectionMap{T} op :: Operation{T} space :: A qdegree :: Int end Map that projects a CellField onto another `FESpace`. Necessary when the arrival space has constraints (e.g. boundary conditions) that need to be taken into account. """ struct SpaceProjectionMap{T,A} <: LocalProjectionMap{T} op::Operation{T} space::A qdegree::Int function SpaceProjectionMap( op::Function, space::FESpace, qdegree::Integer ) T = typeof(op) A = typeof(space) return new{T,A}(Operation(op),space,Int(qdegree)) end end function LocalProjectionMap(op::Function,space::FESpace,qdegree::Integer) SpaceProjectionMap(op,space,qdegree) end function LocalProjectionMap(space::FESpace,qdegree::Integer) LocalProjectionMap(identity,space,qdegree) end function GridapDistributed.local_views(k::SpaceProjectionMap) @check isa(k.space,GridapDistributed.DistributedFESpace) map(local_views(k.space)) do space SpaceProjectionMap(k.op.op,space,k.qdegree) end end function Arrays.evaluate!( cache, k::SpaceProjectionMap, u::GridapDistributed.DistributedCellField, ) @check isa(k.space,GridapDistributed.DistributedFESpace) fields = map(local_views(k),local_views(u)) do k,u evaluate!(nothing,k,u) end return GridapDistributed.DistributedCellField(fields,u.trian) end function _compute_local_projections( k::SpaceProjectionMap,u::CellField ) space = k.space p = get_trial_fe_basis(space) q = get_fe_basis(space) Ω = get_triangulation(space) dΩ = Measure(Ω,k.qdegree) ids = lazy_map(ids -> findall(id -> id > 0, ids), get_cell_dof_ids(space)) op = k.op.op lhs_data = get_array(∫(p⋅q)dΩ) rhs_data = get_array(∫(q⋅op(u))dΩ) basis_data = CellData.get_data(q) return lazy_map(k,lhs_data,rhs_data,basis_data,ids) end function Arrays.return_cache(::LocalProjectionMap,lhs::Matrix{T},rhs::A,basis,ids) where {T,A<:Union{Matrix{T},Vector{T}}} return CachedArray(copy(lhs)), CachedArray(copy(rhs)), CachedArray(zeros(eltype(rhs),(length(ids),size(rhs,2)))) end function Arrays.evaluate!(cache,::LocalProjectionMap,lhs::Matrix{T},rhs::A,basis,ids) where {T,A<:Union{Matrix{T},Vector{T}}} cmat, cvec, cvec2 = cache n = length(ids) if iszero(n) setsize!(cvec,size(rhs)) vec = cvec.array fill!(vec,zero(eltype(rhs))) else setsize!(cmat,(n,n)) mat = cmat.array copyto!(mat,lhs[ids,ids]) setsize!(cvec2,(n,size(rhs,2))) vec2 = cvec2.array copyto!(vec2,rhs[ids,:]) setsize!(cvec,size(rhs)) vec = cvec.array fill!(vec,zero(eltype(rhs))) f = cholesky!(mat,NoPivot();check=false) @check issuccess(f) "Factorization failed" ldiv!(f,vec2) vec[ids,:] .= vec2 end return linear_combination(vec,basis) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
13860
""" Single level for a ModelHierarchy. Note that `model_red` and `red_glue` might be of type `Nothing` whenever there is no redistribution in a given level. `ref_glue` is of type `Nothing` on the coarsest level. """ struct ModelHierarchyLevel{A,B,C,D} level :: Int model :: A ref_glue :: B model_red :: C red_glue :: D end """ const ModelHierarchy = HierarchicalArray{<:ModelHierarchyLevel} A `ModelHierarchy` is a hierarchical array of `ModelHierarchyLevel` objects. It stores the adapted/redistributed models and the corresponding subcommunicators. For convenience, implements some of the API of `DiscreteModel`. """ const ModelHierarchy = HierarchicalArray{<:ModelHierarchyLevel} get_model(a::ModelHierarchy,level::Integer) = get_model(a[level]) get_model(a::ModelHierarchyLevel{A,B,Nothing}) where {A,B} = a.model get_model(a::ModelHierarchyLevel{A,B,C}) where {A,B,C} = a.model_red get_model_before_redist(a::ModelHierarchy,level::Integer) = get_model_before_redist(a[level]) get_model_before_redist(a::ModelHierarchyLevel) = a.model has_redistribution(a::ModelHierarchy,level::Integer) = has_redistribution(a[level]) has_redistribution(a::ModelHierarchyLevel{A,B,C,D}) where {A,B,C,D} = true has_redistribution(a::ModelHierarchyLevel{A,B,C,Nothing}) where {A,B,C} = false has_refinement(a::ModelHierarchy,level::Integer) = has_refinement(a[level]) has_refinement(a::ModelHierarchyLevel{A,B}) where {A,B} = true has_refinement(a::ModelHierarchyLevel{A,Nothing}) where A = false """ CartesianModelHierarchy( ranks::AbstractVector{<:Integer}, np_per_level::Vector{<:NTuple{D,<:Integer}}, domain::Tuple, nc::NTuple{D,<:Integer}; nrefs::Union{<:Integer,Vector{<:Integer},Vector{<:NTuple{D,<:Integer}},NTuple{D,<:Integer}}, map::Function = identity, isperiodic::NTuple{D,Bool} = Tuple(fill(false,D)), add_labels!::Function = (labels -> nothing), ) where D Returns a `ModelHierarchy` with a Cartesian model as coarsest level. The i-th level will be distributed among `np_per_level[i]` processors. Two consecutive levels are refined by a factor of `nrefs[i]`. ## Parameters: - `ranks`: Initial communicator. Will be used to generate subcommunicators. - `domain`: Tuple containing the domain limits. - `nc`: Tuple containing the number of cells in each direction for the coarsest model. - `np_per_level`: Vector containing the number of processors we want to distribute each level into. Requires a tuple `np = (np_1,...,np_d)` for each level, then each level will be distributed among `prod(np)` processors with `np_i` processors in the i-th direction. - `nrefs`: Vector containing the refinement factor for each level. Has `nlevs-1` entries, and each entry can either be an integer (homogeneous refinement) or a tuple with `D` integers (inhomogeneous refinement). """ function CartesianModelHierarchy( ranks::AbstractVector{<:Integer}, np_per_level::Vector{<:NTuple{D,<:Integer}}, domain::Tuple, nc::NTuple{D,<:Integer}; nrefs::Union{<:Integer,Vector{<:Integer},Vector{<:NTuple{D,<:Integer}},NTuple{D,<:Integer}}=2, map::Function = identity, isperiodic::NTuple{D,Bool} = Tuple(fill(false,D)), add_labels!::Function = (labels -> nothing), ) where D lnr(x::Integer,n) = fill(Tuple(fill(x,D)),n) lnr(x::Vector{<:Integer},n) = [Tuple(fill(xi,D)) for xi in x] lnr(x::NTuple{D,<:Integer},n) = fill(x,n) lnr(x::Vector{<:NTuple{D,<:Integer}},n) = x nlevs = length(np_per_level) level_parts = generate_level_parts(ranks,Base.map(prod,np_per_level)) level_nrefs = lnr(nrefs,length(level_parts)-1) @assert length(level_parts)-1 == length(level_nrefs) # Cartesian descriptors for each level level_descs = Vector{GridapDistributed.DistributedCartesianDescriptor}(undef,nlevs) ncells = nc for lev in nlevs:-1:1 level_descs[lev] = GridapDistributed.DistributedCartesianDescriptor( level_parts[lev],np_per_level[lev],CartesianDescriptor(domain,ncells;map,isperiodic) ) if lev != 1 ncells = ncells .* level_nrefs[lev-1] end end map_main(ranks) do r @info "$(nlevs)-level CartesianModelHierarchy:\n$(join([" > Level $(lev): "*repr("text/plain",level_descs[lev]) for lev in 1:nlevs],"\n"))" end # Coarsest level meshes = Vector{ModelHierarchyLevel}(undef,nlevs) if i_am_in(level_parts[nlevs]) coarsest_model = CartesianDiscreteModel(level_parts[nlevs],np_per_level[nlevs],domain,nc;map,isperiodic) Base.map(add_labels!,local_views(get_face_labeling(coarsest_model))) else coarsest_model = nothing end meshes[nlevs] = ModelHierarchyLevel(nlevs,coarsest_model,nothing,nothing,nothing) # Remaining levels for lev in nlevs-1:-1:1 fparts = level_parts[lev] cparts = level_parts[lev+1] # Refinement if i_am_in(cparts) cmodel = get_model(meshes[lev+1]) model_ref = Gridap.Adaptivity.refine(cmodel,level_nrefs[lev]) ref_glue = Gridap.Adaptivity.get_adaptivity_glue(model_ref) else model_ref, ref_glue = nothing, nothing, nothing end # Redistribution (if needed) if i_am_in(fparts) && (cparts !== fparts) _model_ref = i_am_in(cparts) ? Gridap.Adaptivity.get_model(model_ref) : nothing model_red, red_glue = GridapDistributed.redistribute(_model_ref,level_descs[lev];old_ranks=cparts) else model_red, red_glue = nothing, nothing end meshes[lev] = ModelHierarchyLevel(lev,model_ref,ref_glue,model_red,red_glue) end return HierarchicalArray(meshes,level_parts) end """ P4estCartesianModelHierarchy( ranks,np_per_level,domain,nc::NTuple{D,<:Integer}; num_refs_coarse::Integer = 0, add_labels!::Function = (labels -> nothing), map::Function = identity, isperiodic::NTuple{D,Bool} = Tuple(fill(false,D)) ) where D Returns a `ModelHierarchy` with a Cartesian model as coarsest level, using GridapP4est.jl. The i-th level will be distributed among `np_per_level[i]` processors. The seed model is given by `cmodel = CartesianDiscreteModel(domain,nc)`. """ function P4estCartesianModelHierarchy( ranks,np_per_level,domain,nc::NTuple{D,<:Integer}; num_refs_coarse::Integer = 0, add_labels!::Function = (labels -> nothing), map::Function = identity, isperiodic::NTuple{D,Bool} = Tuple(fill(false,D)) ) where D cparts = generate_subparts(ranks,np_per_level[end]) cmodel = CartesianDiscreteModel(domain,nc;map,isperiodic) add_labels!(get_face_labeling(cmodel)) coarse_model = OctreeDistributedDiscreteModel(cparts,cmodel,num_refs_coarse) mh = ModelHierarchy(ranks,coarse_model,np_per_level) return mh end """ ModelHierarchy(root_parts,model,num_procs_x_level) - `root_parts`: Initial communicator. Will be used to generate subcommunicators. - `model`: Initial refinable distributed model. Will be set as coarsest level. - `num_procs_x_level`: Vector containing the number of processors we want to distribute each level into. We need `num_procs_x_level[end]` to be equal to the number of parts of `model`, and `num_procs_x_level[1]` to lower than the total number of available processors in `root_parts`. """ function ModelHierarchy( root_parts ::AbstractArray, model ::GridapDistributed.DistributedDiscreteModel, num_procs_x_level ::Vector{<:Integer}; mesh_refinement = true, kwargs... ) # Request correct number of parts from MAIN model_parts = get_parts(model) my_num_parts = map(root_parts) do _p num_parts(model_parts) # == -1 if !i_am_in(my_parts) end main_num_parts = PartitionedArrays.getany(emit(my_num_parts)) if main_num_parts == num_procs_x_level[end] # Coarsest model if mesh_refinement return _model_hierarchy_by_refinement(root_parts,model,num_procs_x_level;kwargs...) else return _model_hierarchy_without_refinement_bottom_up(root_parts,model,num_procs_x_level;kwargs...) end end if main_num_parts == num_procs_x_level[1] # Finest model if mesh_refinement return _model_hierarchy_by_coarsening(root_parts,model,num_procs_x_level;kwargs...) else return _model_hierarchy_without_refinement_top_down(root_parts,model,num_procs_x_level;kwargs...) end end @error "Model parts do not correspond to coarsest or finest parts!" end function _model_hierarchy_without_refinement_bottom_up( root_parts::AbstractArray{T}, bottom_model::GridapDistributed.DistributedDiscreteModel, num_procs_x_level::Vector{<:Integer} ) where T num_levels = length(num_procs_x_level) level_parts = Vector{Union{typeof(root_parts),GridapDistributed.MPIVoidVector{T}}}(undef,num_levels) meshes = Vector{ModelHierarchyLevel}(undef,num_levels) level_parts[num_levels] = get_parts(bottom_model) meshes[num_levels] = ModelHierarchyLevel(num_levels,bottom_model,nothing,nothing,nothing) for i = num_levels-1:-1:1 model = get_model(meshes[i+1]) if (num_procs_x_level[i] != num_procs_x_level[i+1]) level_parts[i] = generate_subparts(root_parts,num_procs_x_level[i]) model_red,red_glue = GridapDistributed.redistribute(model,level_parts[i]) else level_parts[i] = level_parts[i+1] model_red,red_glue = nothing,nothing end meshes[i] = ModelHierarchyLevel(i,model,nothing,model_red,red_glue) end mh = HierarchicalArray(meshes,level_parts) return mh end function _model_hierarchy_without_refinement_top_down( root_parts::AbstractArray{T}, top_model::GridapDistributed.DistributedDiscreteModel, num_procs_x_level::Vector{<:Integer} ) where T num_levels = length(num_procs_x_level) level_parts = Vector{Union{typeof(root_parts),GridapDistributed.MPIVoidVector{T}}}(undef,num_levels) meshes = Vector{ModelHierarchyLevel}(undef,num_levels) level_parts[1] = get_parts(top_model) model = top_model for i = 1:num_levels-1 if (num_procs_x_level[i] != num_procs_x_level[i+1]) level_parts[i+1] = generate_subparts(root_parts,num_procs_x_level[i+1]) model_red = model model,red_glue = GridapDistributed.redistribute(model_red,level_parts[i+1]) else level_parts[i+1] = level_parts[i] model_red,red_glue = nothing, nothing end meshes[i] = ModelHierarchyLevel(i,model,nothing,model_red,red_glue) end meshes[num_levels] = ModelHierarchyLevel(num_levels,model,nothing,nothing,nothing) mh = HierarchicalArray(meshes,level_parts) return mh end function _model_hierarchy_by_refinement( root_parts::AbstractArray{T}, coarsest_model::GridapDistributed.DistributedDiscreteModel, num_procs_x_level::Vector{<:Integer}; num_refs_x_level=nothing ) where T # TODO: Implement support for num_refs_x_level? (future work) num_levels = length(num_procs_x_level) level_parts = Vector{Union{typeof(root_parts),GridapDistributed.MPIVoidVector{T}}}(undef,num_levels) meshes = Vector{ModelHierarchyLevel}(undef,num_levels) level_parts[num_levels] = get_parts(coarsest_model) meshes[num_levels] = ModelHierarchyLevel(num_levels,coarsest_model,nothing,nothing,nothing) for i = num_levels-1:-1:1 modelH = get_model(meshes[i+1]) if (num_procs_x_level[i] != num_procs_x_level[i+1]) # meshes[i+1].model is distributed among P processors # model_ref is distributed among Q processors, with P!=Q level_parts[i] = generate_subparts(root_parts,num_procs_x_level[i]) model_ref,ref_glue = Gridap.Adaptivity.refine(modelH) model_red,red_glue = GridapDistributed.redistribute(model_ref,level_parts[i]) else level_parts[i] = level_parts[i+1] model_ref,ref_glue = Gridap.Adaptivity.refine(modelH) model_red,red_glue = nothing,nothing end meshes[i] = ModelHierarchyLevel(i,model_ref,ref_glue,model_red,red_glue) end mh = HierarchicalArray(meshes,level_parts) return convert_to_adapted_models(mh) end function _model_hierarchy_by_coarsening( root_parts::AbstractArray{T}, finest_model::GridapDistributed.DistributedDiscreteModel, num_procs_x_level::Vector{<:Integer}; num_refs_x_level=nothing ) where T # TODO: Implement support for num_refs_x_level? (future work) num_levels = length(num_procs_x_level) level_parts = Vector{Union{typeof(root_parts),GridapDistributed.MPIVoidVector{T}}}(undef,num_levels) meshes = Vector{ModelHierarchyLevel}(undef,num_levels) level_parts[1] = get_parts(finest_model) model = finest_model for i = 1:num_levels-1 if (num_procs_x_level[i] != num_procs_x_level[i+1]) level_parts[i+1] = generate_subparts(root_parts,num_procs_x_level[i+1]) model_red = model model_ref,red_glue = GridapDistributed.redistribute(model_red,level_parts[i+1]) model_H ,ref_glue = Gridap.Adaptivity.coarsen(model_ref) else level_parts[i+1] = level_parts[i] model_red = nothing model_ref,red_glue = model, nothing model_H ,ref_glue = Gridap.Adaptivity.coarsen(model_ref) end model = model_H meshes[i] = ModelHierarchyLevel(i,model_ref,ref_glue,model_red,red_glue) end meshes[num_levels] = ModelHierarchyLevel(num_levels,model,nothing,nothing,nothing) mh = HierarchicalArray(meshes,level_parts) return convert_to_adapted_models(mh) end function convert_to_adapted_models(mh::ModelHierarchy) map(linear_indices(mh),mh) do lev, mhl if lev == num_levels(mh) return mhl end if i_am_in(get_level_parts(mh,lev+1)) model = get_model_before_redist(mh,lev) parent = get_model(mh,lev+1) ref_glue = mhl.ref_glue model_ref = GridapDistributed.DistributedAdaptedDiscreteModel(model,parent,ref_glue) else model_ref = nothing end return ModelHierarchyLevel(lev,model_ref,mhl.ref_glue,mhl.model_red,mhl.red_glue) end end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
2069
""" """ struct MultiFieldTransferOperator{T,A,B,C,D} Vh_in :: A Vh_out :: B ops :: C cache :: D function MultiFieldTransferOperator( op_type::Symbol,Vh_in::A,Vh_out::B,ops::C,cache::D ) where {A,B,C,D} T = Val{op_type} new{T,A,B,C,D}(Vh_in,Vh_out,ops,cache) end end function MultiFieldTransferOperator(lev::Integer,sh::FESpaceHierarchy,operators;op_type=:prolongation) @check op_type in (:prolongation,:restriction) cparts = get_level_parts(sh,lev+1) Vh = get_fe_space(sh,lev) VH = i_am_in(cparts) ? get_fe_space(sh,lev+1) : nothing Vh_out, Vh_in = (op_type == :prolongation) ? (Vh,VH) : (VH,Vh) xh = isnothing(Vh_out) ? nothing : zero_free_values(Vh_out) yh = isnothing(Vh_in) ? nothing : zero_free_values(Vh_in) caches = xh, yh return MultiFieldTransferOperator(op_type,Vh_in,Vh_out,operators,caches) end function MultiFieldTransferOperator(sh::FESpaceHierarchy,operators;op_type=:prolongation) nlevs = num_levels(sh) @check all(map(a -> length(a) == nlevs-1, operators)) mfops = Vector{MultiFieldTransferOperator}(undef,nlevs-1) for (lev,ops) in enumerate(zip(operators...)) parts = get_level_parts(sh,lev) if i_am_in(parts) mfops[lev] = MultiFieldTransferOperator(lev,sh,ops;op_type) end end return mfops end function update_transfer_operator!(op::MultiFieldTransferOperator,x::PVector) xh, _ = op.cache if !isnothing(xh) copy!(x,xh) end for (i,op_i) in enumerate(op.ops) xh_i = isnothing(xh) ? nothing : MultiField.restrict_to_field(op.Vh_out,xh,i) update_transfer_operator!(op_i,xh_i) end end function LinearAlgebra.mul!(x,op::MultiFieldTransferOperator,y) xh, yh = op.cache if !isnothing(yh) copy!(yh,y) end for (i,op_i) in enumerate(op.ops) xh_i = isnothing(xh) ? nothing : MultiField.restrict_to_field(op.Vh_out,xh,i) yh_i = isnothing(yh) ? nothing : MultiField.restrict_to_field(op.Vh_in,yh,i) LinearAlgebra.mul!(xh_i,op_i,yh_i) end if !isnothing(xh) copy!(x,xh) consistent!(x) |> fetch end return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
1930
module MultilevelTools using MPI using LinearAlgebra using FillArrays using BlockArrays using Gridap using Gridap.Helpers, Gridap.Algebra, Gridap.Arrays, Gridap.Fields, Gridap.CellData using Gridap.ReferenceFEs, Gridap.Geometry, Gridap.FESpaces, Gridap.Adaptivity, Gridap.MultiField using PartitionedArrays, GridapDistributed, GridapP4est using Gridap.FESpaces: BasisStyle, TestBasis, TrialBasis, SingleFieldFEBasis using Gridap.MultiField: MultiFieldFEBasisComponent using GridapDistributed: redistribute_cell_dofs, redistribute_cell_dofs!, get_redistribute_cell_dofs_cache using GridapDistributed: redistribute_free_values, redistribute_free_values!, get_redistribute_free_values_cache using GridapDistributed: redistribute_fe_function using GridapDistributed: get_old_and_new_parts using GridapDistributed: i_am_in, num_parts, change_parts, generate_subparts, local_views export change_parts, num_parts, i_am_in export generate_level_parts, generate_subparts export HierarchicalArray export num_levels, get_level_parts, with_level, matching_level_parts, unsafe_getindex export ModelHierarchy, CartesianModelHierarchy export num_levels, get_level, get_level_parts export get_model, get_model_before_redist, has_refinement, has_redistribution export FESpaceHierarchy export get_fe_space, get_fe_space_before_redist export compute_hierarchy_matrices export LocalProjectionMap export DistributedGridTransferOperator export RestrictionOperator, ProlongationOperator export setup_transfer_operators, setup_prolongation_operators, setup_restriction_operators export mul! export MultiFieldTransferOperator include("SubpartitioningTools.jl") include("HierarchicalArrays.jl") include("GridapFixes.jl") include("RefinementTools.jl") include("ModelHierarchies.jl") include("FESpaceHierarchies.jl") include("LocalProjectionMaps.jl") include("DistributedGridTransferOperators.jl") include("MultiFieldTransferOperators.jl") end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
2079
# DistributedAdaptedTriangulations const DistributedAdaptedTriangulation{Dc,Dp} = GridapDistributed.DistributedTriangulation{Dc,Dp,<:AbstractArray{<:AdaptedTriangulation{Dc,Dp}}} # Restriction of dofs function restrict_dofs!(fv_c::PVector, fv_f::PVector, dv_f::AbstractArray, U_f ::GridapDistributed.DistributedSingleFieldFESpace, U_c ::GridapDistributed.DistributedSingleFieldFESpace, glue::AbstractArray{<:AdaptivityGlue}) map(restrict_dofs!,local_views(fv_c),local_views(fv_f),dv_f,local_views(U_f),local_views(U_c),glue) consistent!(fv_c) |> fetch return fv_c end function restrict_dofs!(fv_c::AbstractVector, fv_f::AbstractVector, dv_f::AbstractVector, U_f ::FESpace, U_c ::FESpace, glue::AdaptivityGlue) fine_cell_ids = get_cell_dof_ids(U_f) fine_cell_values = Gridap.Arrays.Table(lazy_map(Gridap.Arrays.PosNegReindex(fv_f,dv_f),fine_cell_ids.data),fine_cell_ids.ptrs) coarse_rrules = Gridap.Adaptivity.get_old_cell_refinement_rules(glue) f2c_cell_values = Gridap.Adaptivity.n2o_reindex(fine_cell_values,glue) child_ids = Gridap.Adaptivity.n2o_reindex(glue.n2o_cell_to_child_id,glue) f2c_maps = lazy_map(FineToCoarseDofMap,coarse_rrules) caches = lazy_map(Gridap.Arrays.return_cache,f2c_maps,f2c_cell_values,child_ids) coarse_cell_values = lazy_map(Gridap.Arrays.evaluate!,caches,f2c_maps,f2c_cell_values,child_ids) fv_c = gather_free_values!(fv_c,U_c,coarse_cell_values) return fv_c end struct FineToCoarseDofMap{A} rr::A end function Gridap.Arrays.return_cache(m::FineToCoarseDofMap,fine_cell_vals,child_ids) return fill(0.0,Gridap.Adaptivity.num_subcells(m.rr)) end function Gridap.Arrays.evaluate!(cache,m::FineToCoarseDofMap,fine_cell_vals,child_ids) fill!(cache,0.0) for (k,i) in enumerate(child_ids) cache[i] = fine_cell_vals[k][i] end return cache end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
1210
""" generate_level_parts(root_parts::AbstractArray,num_procs_x_level::Vector{<:Integer}) From a root communicator `root_parts`, generate a sequence of nested subcommunicators with sizes given by `num_procs_x_level`. """ function generate_level_parts(root_parts::AbstractArray,num_procs_x_level::Vector{<:Integer}) num_levels = length(num_procs_x_level) T = Union{typeof(root_parts),GridapDistributed.MPIVoidVector{eltype(root_parts)}} level_parts = Vector{T}(undef,num_levels) level_parts[1] = generate_subparts(root_parts,num_procs_x_level[1]) for l = 2:num_levels level_parts[l] = generate_level_parts(root_parts,level_parts[l-1],num_procs_x_level[l]) end return level_parts end function generate_level_parts(root_parts::AbstractArray,last_level_parts::AbstractArray,level_parts_size::Integer) if level_parts_size == num_parts(last_level_parts) return last_level_parts end return generate_subparts(root_parts,level_parts_size) end my_print(x::PVector,s) = my_print(partition(x),s) function my_print(x::MPIArray,s) parts = linear_indices(x) i_am_main(parts) && println(s) map(parts,x) do p,xi sleep(p*0.2) println(" > $p: ", xi) end sleep(2) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
4796
""" NLsolveNonlinearSolver <: NonlinearSolver NLsolveNonlinearSolver(ls::LinearSolver;kwargs...) NLsolveNonlinearSolver(;kwargs...) Wrapper for `NLsolve.jl` nonlinear solvers. It is equivalent to the wrappers in Gridap, but with support for nonlinear preconditioners. Same `kwargs` as in `nlsolve`. Due to `NLSolve.jl` not using LinearAlgebra's API, these solvers are not compatible with `PartitionedArrays.jl`. For parallel computations, use [`NewtonSolver`](@ref) instead. """ struct NLsolveNonlinearSolver{A} <: NonlinearSolver ls::A kwargs::Dict function NLsolveNonlinearSolver( ls::LinearSolver;kwargs... ) @assert ! haskey(kwargs,:linsolve) "linsolve cannot be used here. It is managed internally" A = typeof(ls) new{A}(ls,kwargs) end end function NLsolveNonlinearSolver(;kwargs...) ls = LUSolver() NLsolveNonlinearSolver(ls;kwargs...) end mutable struct NLSolversCache <: GridapType f0::AbstractVector j0::AbstractMatrix df::OnceDifferentiable ns::NumericalSetup cache result end function Algebra.solve!( x::AbstractVector,nls::NLsolveNonlinearSolver,op::NonlinearOperator,cache::Nothing ) cache = _new_nlsolve_cache(x,nls,op) _nlsolve_with_updated_cache!(x,nls,op,cache) cache end function Algebra.solve!( x::AbstractVector,nls::NLsolveNonlinearSolver,op::NonlinearOperator,cache::NLSolversCache ) cache = _update_nlsolve_cache!(cache,x,op) _nlsolve_with_updated_cache!(x,nls,op,cache) cache end function _nlsolve_with_updated_cache!(x,nls::NLsolveNonlinearSolver,op,cache) df = cache.df ns = cache.ns kwargs = nls.kwargs internal_cache = cache.cache function linsolve!(p,A,b) fill!(p,zero(eltype(p))) # Needed because NLSolve gives you NaNs on the 1st iteration... numerical_setup!(ns,A,internal_cache.x) solve!(p,ns,b) end r = _nlsolve(df,x;linsolve=linsolve!,cache=internal_cache,kwargs...) cache.result = r copy_entries!(x,r.zero) end function _new_nlsolve_cache(x0,nls::NLsolveNonlinearSolver,op) f!(r,x) = residual!(r,op,x) j!(j,x) = jacobian!(j,op,x) fj!(r,j,x) = residual_and_jacobian!(r,j,op,x) f0, j0 = residual_and_jacobian(op,x0) df = OnceDifferentiable(f!,j!,fj!,x0,f0,j0) ss = symbolic_setup(nls.ls,j0,x0) ns = numerical_setup(ss,j0,x0) cache = nlsolve_internal_cache(df,nls.kwargs) NLSolversCache(f0,j0,df,ns,cache,nothing) end function _update_nlsolve_cache!(cache,x0,op) f!(r,x) = residual!(r,op,x) j!(j,x) = jacobian!(j,op,x) fj!(r,j,x) = residual_and_jacobian!(r,j,op,x) f0 = cache.f0 j0 = cache.j0 ns = cache.ns residual_and_jacobian!(f0,j0,op,x0) df = NLsolve.OnceDifferentiable(f!,j!,fj!,x0,f0,j0) numerical_setup!(ns,j0,x0) NLSolversCache(f0,j0,df,ns,cache.cache,nothing) end nlsolve_internal_cache(df,kwargs) = nlsolve_internal_cache(Val(kwargs[:method]),df,kwargs) nlsolve_internal_cache(::Val{:newton},df,kwargs) = NLsolve.NewtonCache(df) nlsolve_internal_cache(::Val{:trust_region},df,kwargs) = NLsolve.NewtonTrustRegionCache(df) nlsolve_internal_cache(::Val{:anderson},df,kwargs) = NLsolve.AndersonCache(df,kwargs[:m]) # Copied from https://github.com/JuliaNLSolvers/NLsolve.jl/blob/master/src/nlsolve/nlsolve.jl # We need to modify it so that we can access the internal caches... function _nlsolve( df::Union{NLsolve.NonDifferentiable, NLsolve.OnceDifferentiable}, initial_x::AbstractArray; method::Symbol = :trust_region, xtol::Real = zero(real(eltype(initial_x))), ftol::Real = convert(real(eltype(initial_x)), 1e-8), iterations::Integer = 1_000, store_trace::Bool = false, show_trace::Bool = false, extended_trace::Bool = false, linesearch = LineSearches.Static(), linsolve=(x, A, b) -> copyto!(x, A\b), factor::Real = one(real(eltype(initial_x))), autoscale::Bool = true, m::Integer = 10, beta::Real = 1, aa_start::Integer = 1, droptol::Real = convert(real(eltype(initial_x)), 1e10), cache = nothing ) if show_trace println("Iter f(x) inf-norm Step 2-norm") println("------ -------------- --------------") end if method == :newton NLsolve.newton_( df, initial_x, xtol, ftol, iterations, store_trace, show_trace, extended_trace, linesearch, linsolve, cache ) elseif method == :trust_region NLsolve.trust_region_( df, initial_x, xtol, ftol, iterations, store_trace, show_trace, extended_trace, factor, autoscale, cache ) elseif method == :anderson NLsolve.anderson( df, initial_x, xtol, ftol, iterations, store_trace, show_trace, extended_trace, beta, aa_start, droptol, cache ) elseif method == :broyden NLsolve.broyden( df, initial_x, xtol, ftol, iterations, store_trace, show_trace, extended_trace, linesearch ) else throw(ArgumentError("Unknown method $method")) end end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
2001
# TODO: This should be called NewtonRaphsonSolver, but it would clash with Gridap. """ struct NewtonSolver <: Algebra.NonlinearSolver Newton-Raphson solver. Same as `NewtonRaphsonSolver` in Gridap, but with a couple addons: - Better logging and verbosity control. - Better convergence criteria. - Works with geometric LinearSolvers/Preconditioners. """ struct NewtonSolver <: Algebra.NonlinearSolver ls ::Algebra.LinearSolver log::ConvergenceLog{Float64} end function NewtonSolver(ls;maxiter=100,atol=1e-12,rtol=1.e-6,verbose=0,name="Newton-Raphson") tols = SolverTolerances{Float64}(;maxiter=maxiter,atol=atol,rtol=rtol) log = ConvergenceLog(name,tols;verbose=verbose) return NewtonSolver(ls,log) end struct NewtonCache A::AbstractMatrix b::AbstractVector dx::AbstractVector ns::NumericalSetup end function Algebra.solve!(x::AbstractVector,nls::NewtonSolver,op::NonlinearOperator,cache::Nothing) b = residual(op, x) A = jacobian(op, x) dx = allocate_in_domain(A); fill!(dx,zero(eltype(dx))) ss = symbolic_setup(nls.ls,A) ns = numerical_setup(ss,A,x) _solve_nr!(x,A,b,dx,ns,nls,op) return NewtonCache(A,b,dx,ns) end function Algebra.solve!(x::AbstractVector,nls::NewtonSolver,op::NonlinearOperator,cache::NewtonCache) A,b,dx,ns = cache.A, cache.b, cache.dx, cache.ns residual!(b, op, x) jacobian!(A, op, x) numerical_setup!(ns,A,x) _solve_nr!(x,A,b,dx,ns,nls,op) return cache end function _solve_nr!(x,A,b,dx,ns,nls,op) log = nls.log # Check for convergence on the initial residual res = norm(b) done = init!(log,res) # Newton-like iterations while !done # Solve linearized problem rmul!(b,-1) solve!(dx,ns,b) x .+= dx # Check convergence for the current residual residual!(b, op, x) res = norm(b) done = update!(log,res) if !done # Update jacobian and solver jacobian!(A, op, x) numerical_setup!(ns,A,x) end end finalize!(log,res) return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
555
module NonlinearSolvers using LinearAlgebra using SparseArrays using SparseMatricesCSR using BlockArrays using NLsolve, LineSearches using Gridap using Gridap.Helpers, Gridap.Algebra, Gridap.CellData, Gridap.Arrays, Gridap.FESpaces, Gridap.MultiField using PartitionedArrays using GridapDistributed using GridapSolvers.SolverInterfaces using GridapSolvers.MultilevelTools using GridapSolvers.SolverInterfaces include("NewtonRaphsonSolver.jl") export NewtonSolver include("NLsolve.jl") export NLsolveNonlinearSolver end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
860
module PatchBasedSmoothers using FillArrays, BlockArrays using LinearAlgebra using Gridap using Gridap.Helpers, Gridap.Algebra, Gridap.Arrays, Gridap.Fields using Gridap.Geometry, Gridap.FESpaces, Gridap.ReferenceFEs using PartitionedArrays using GridapDistributed using GridapSolvers.MultilevelTools export PatchDecomposition export PatchFESpace export PatchBasedLinearSolver export PatchProlongationOperator, PatchRestrictionOperator export setup_patch_prolongation_operators, setup_patch_restriction_operators # Geometry include("seq/PatchDecompositions.jl") include("mpi/PatchDecompositions.jl") include("seq/PatchTriangulations.jl") # FESpaces include("seq/PatchFESpaces.jl") include("mpi/PatchFESpaces.jl") include("seq/PatchMultiFieldFESpaces.jl") # Solvers include("seq/PatchBasedLinearSolvers.jl") include("seq/PatchTransferOperators.jl") end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
3079
struct DistributedPatchDecomposition{Dr,Dc,Dp,A,B} <: GridapType patch_decompositions::A model::B end GridapDistributed.local_views(a::DistributedPatchDecomposition) = a.patch_decompositions function PatchDecomposition( model::GridapDistributed.DistributedDiscreteModel{Dc,Dp}; Dr=0, patch_boundary_style::PatchBoundaryStyle=PatchBoundaryExclude() ) where {Dc,Dp} mark_interface_facets!(model) patch_decompositions = map(local_views(model)) do lmodel PatchDecomposition( lmodel; Dr=Dr, patch_boundary_style=patch_boundary_style, boundary_tag_names=["boundary","interface"] ) end A = typeof(patch_decompositions) B = typeof(model) return DistributedPatchDecomposition{Dr,Dc,Dp,A,B}(patch_decompositions,model) end function PatchDecomposition(mh::ModelHierarchy;kwargs...) nlevs = num_levels(mh) decomps = map(view(mh,1:nlevs-1)) do mhl model = get_model(mhl) PatchDecomposition(model;kwargs...) end return decomps end function Geometry.Triangulation(a::DistributedPatchDecomposition) trians = map(local_views(a)) do a Triangulation(a) end return GridapDistributed.DistributedTriangulation(trians,a.model) end function Geometry.BoundaryTriangulation(a::DistributedPatchDecomposition,args...;kwargs...) trians = map(local_views(a)) do a BoundaryTriangulation(a,args...;kwargs...) end return GridapDistributed.DistributedTriangulation(trians,a.model) end function Geometry.SkeletonTriangulation(a::DistributedPatchDecomposition,args...;kwargs...) trians = map(local_views(a)) do a SkeletonTriangulation(a,args...;kwargs...) end return GridapDistributed.DistributedTriangulation(trians,a.model) end get_patch_root_dim(::DistributedPatchDecomposition{Dr}) where Dr = Dr function mark_interface_facets!(model::GridapDistributed.DistributedDiscreteModel{Dc,Dp}) where {Dc,Dp} face_labeling = get_face_labeling(model) topo = get_grid_topology(model) map(local_views(face_labeling),local_views(topo)) do face_labeling, topo tag_to_name = face_labeling.tag_to_name tag_to_entities = face_labeling.tag_to_entities d_to_dface_to_entity = face_labeling.d_to_dface_to_entity # Create new tag & entity interface_entity = maximum(map(x -> maximum(x;init=0),tag_to_entities)) + 1 push!(tag_to_entities,[interface_entity]) push!(tag_to_name,"interface") # Interface faces should also be interior interior_tag = findfirst(x->(x=="interior"),tag_to_name) push!(tag_to_entities[interior_tag],interface_entity) # Select interface entities boundary_tag = findfirst(x->(x=="boundary"),tag_to_name) boundary_entities = tag_to_entities[boundary_tag] f2c_map = Geometry.get_faces(topo,Dc-1,Dc) num_cells_around_facet = map(length,f2c_map) mx = maximum(num_cells_around_facet) for (f,nf) in enumerate(num_cells_around_facet) is_boundary = (d_to_dface_to_entity[Dc][f] ∈ boundary_entities) if !is_boundary && (nf != mx) d_to_dface_to_entity[Dc][f] = interface_entity end end end end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
4276
const DistributedPatchFESpace = GridapDistributed.DistributedSingleFieldFESpace{<:AbstractVector{<:PatchFESpace}} function PatchFESpace( space::GridapDistributed.DistributedSingleFieldFESpace, patch_decomposition::DistributedPatchDecomposition, reffe::Union{ReferenceFE,Tuple{<:ReferenceFEs.ReferenceFEName,Any,Any}}; conformity=nothing ) cell_conformity = MultilevelTools._cell_conformity(patch_decomposition.model,reffe;conformity=conformity) return PatchFESpace(space,patch_decomposition,cell_conformity) end function PatchFESpace( space::GridapDistributed.DistributedSingleFieldFESpace, patch_decomposition::DistributedPatchDecomposition, cell_conformity::AbstractArray{<:CellConformity}; patches_mask = default_patches_mask(patch_decomposition) ) spaces = map( local_views(space), local_views(patch_decomposition), cell_conformity, patches_mask ) do space, patch_decomposition, cell_conformity, patches_mask PatchFESpace(space,patch_decomposition,cell_conformity;patches_mask) end # This PRange has no ghost dofs local_ndofs = map(num_free_dofs,spaces) global_ndofs = sum(local_ndofs) patch_partition = variable_partition(local_ndofs,global_ndofs,false) trian = Triangulation(patch_decomposition) gids = PRange(patch_partition) return GridapDistributed.DistributedSingleFieldFESpace(spaces,gids,trian,get_vector_type(space)) end function default_patches_mask(patch_decomposition::DistributedPatchDecomposition) model = patch_decomposition.model root_gids = get_face_gids(model,get_patch_root_dim(patch_decomposition)) patches_mask = map(partition(root_gids)) do partition patches_mask = fill(false,local_length(partition)) patches_mask[ghost_to_local(partition)] .= true # Mask ghost patch roots return patches_mask end return patches_mask end function PatchFESpace( sh::FESpaceHierarchy, patch_decompositions::AbstractArray{<:DistributedPatchDecomposition} ) nlevs = num_levels(sh) psh = map(view(sh,1:nlevs-1),patch_decompositions) do shl,decomp space = MultilevelTools.get_fe_space(shl) cell_conformity = MultilevelTools.get_cell_conformity(shl) return PatchFESpace(space,decomp,cell_conformity) end return psh end # x \in PatchFESpace # y \in SingleFESpace # x is always consistent at the end since Ph has no ghosts function prolongate!( x::PVector, Ph::DistributedPatchFESpace, y::PVector; is_consistent::Bool=false ) if is_consistent map(prolongate!,partition(x),local_views(Ph),partition(y)) else # Transfer ghosts while copying owned dofs rows = axes(y,1) t = consistent!(y) map(partition(x),local_views(Ph),partition(y),own_to_local(rows)) do x,Ph,y,ids prolongate!(x,Ph,y;dof_ids=ids) end # Wait for transfer to end and copy ghost dofs wait(t) map(partition(x),local_views(Ph),partition(y),ghost_to_local(rows)) do x,Ph,y,ids prolongate!(x,Ph,y;dof_ids=ids) end end end # x \in SingleFESpace # y \in PatchFESpace # y is always consistent at the start since Ph has no ghosts function inject!( x::PVector, Ph::DistributedPatchFESpace, y::PVector; make_consistent::Bool=true ) map(partition(x),local_views(Ph),partition(y)) do x,Ph,y inject!(x,Ph,y) end # Exchange local contributions assemble!(x) |> fetch if make_consistent consistent!(x) |> fetch end return x end function inject!( x::PVector, Ph::DistributedPatchFESpace, y::PVector, w::PVector, w_sums::PVector; make_consistent::Bool=true ) map(partition(x),local_views(Ph),partition(y),partition(w),partition(w_sums)) do x,Ph,y,w,w_sums inject!(x,Ph,y,w,w_sums) end # Exchange local contributions assemble!(x) |> fetch if make_consistent consistent!(x) |> fetch end return x end function compute_weight_operators(Ph::DistributedPatchFESpace,Vh) # Local weights and partial sums w_values, w_sums_values = map(compute_weight_operators,local_views(Ph),local_views(Vh)) |> tuple_of_arrays w = PVector(w_values,partition(Ph.gids)) w_sums = PVector(w_sums_values,partition(Vh.gids)) # partial sums -> global sums assemble!(w_sums) |> fetch # ghost -> owners consistent!(w_sums) |> fetch # repopulate ghosts with owner info return w, w_sums end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
6749
""" struct PatchBasedLinearSolver <: LinearSolver ... end Sub-assembled linear solver for patch-based methods. Given a bilinear form `a` and a space decomposition `V = Σ_i V_i` given by a patch space, returns a global correction given by aggregated local corrections, i.e ``` dx = Σ_i w_i I_i inv(A_i) (I_i)^* x ``` where `A_i` is the patch-local system matrix defined by ``` (A_i u_i, v_i) = a(u_i,v_i) ∀ v_i ∈ V_i ``` and `I_i` is the natural injection from the patch space to the global space. The aggregation can be un-weighted (i.e. `w_i = 1`) or weighted, where `w_i = 1/#(i)`. """ struct PatchBasedLinearSolver{A,B,C} <: Gridap.Algebra.LinearSolver biform :: Function patch_space :: A space :: B local_solver :: C is_nonlinear :: Bool weighted :: Bool @doc """ function PatchBasedLinearSolver( biform::Function, patch_space::FESpace, space::FESpace; local_solver = LUSolver(), is_nonlinear = false, weighted = false ) Returns an instance of [`PatchBasedLinearSolver`](@ref) from its underlying properties. Local patch-systems are solved with `local_solver`. If `weighted`, uses weighted patch aggregation to compute the global correction. """ function PatchBasedLinearSolver( biform::Function, patch_space::FESpace, space::FESpace; local_solver = LUSolver(), is_nonlinear = false, weighted = false ) A = typeof(patch_space) B = typeof(space) C = typeof(local_solver) return new{A,B,C}(biform,patch_space,space,local_solver,is_nonlinear,weighted) end end struct PatchBasedSymbolicSetup <: Gridap.Algebra.SymbolicSetup solver :: PatchBasedLinearSolver end function Gridap.Algebra.symbolic_setup(ls::PatchBasedLinearSolver,A::AbstractMatrix) return PatchBasedSymbolicSetup(ls) end struct PatchBasedSmootherNumericalSetup{A,B,C,D} <: Gridap.Algebra.NumericalSetup solver :: PatchBasedLinearSolver local_A :: A local_ns :: B weights :: C caches :: D end function Gridap.Algebra.numerical_setup(ss::PatchBasedSymbolicSetup,A::AbstractMatrix) @check !ss.solver.is_nonlinear solver = ss.solver Ph, Vh = solver.patch_space, solver.space weights = solver.weighted ? compute_weight_operators(Ph,Vh) : nothing ap(u,v) = solver.biform(u,v) assem = SparseMatrixAssembler(Ph,Ph) Ap = assemble_matrix(ap,assem,Ph,Ph) Ap_ns = numerical_setup(symbolic_setup(solver.local_solver,Ap),Ap) # Caches rp = allocate_in_range(Ap); fill!(rp,0.0) dxp = allocate_in_domain(Ap); fill!(dxp,0.0) caches = (rp,dxp) return PatchBasedSmootherNumericalSetup(solver,nothing,Ap_ns,weights,caches) end function Gridap.Algebra.numerical_setup(ss::PatchBasedSymbolicSetup,A::AbstractMatrix,x::AbstractVector) @check ss.solver.is_nonlinear solver = ss.solver Ph, Vh = solver.patch_space, solver.space weights = solver.weighted ? compute_weight_operators(Ph,Vh) : nothing u0 = FEFunction(Vh,x) ap(u,v) = solver.biform(u0,u,v) assem = SparseMatrixAssembler(Ph,Ph) Ap = assemble_matrix(ap,assem,Ph,Ph) Ap_ns = numerical_setup(symbolic_setup(solver.local_solver,Ap),Ap) # Caches rp = allocate_in_range(Ap); fill!(rp,0.0) dxp = allocate_in_domain(Ap); fill!(dxp,0.0) caches = (rp,dxp) return PatchBasedSmootherNumericalSetup(solver,Ap,Ap_ns,weights,caches) end function Gridap.Algebra.numerical_setup(ss::PatchBasedSymbolicSetup,A::PSparseMatrix) @check !ss.solver.is_nonlinear solver = ss.solver Ph, Vh = solver.patch_space, solver.space weights = solver.weighted ? compute_weight_operators(Ph,Vh) : nothing # Patch system solver (only local systems need to be solved) u, v = get_trial_fe_basis(Vh), get_fe_basis(Vh) contr = solver.biform(u,v) matdata = collect_cell_matrix(Ph,Ph,contr) Ap, Ap_ns = map(local_views(Ph),matdata) do Ph, matdata assem = SparseMatrixAssembler(Ph,Ph) Ap = assemble_matrix(assem,matdata) Ap_ns = numerical_setup(symbolic_setup(solver.local_solver,Ap),Ap) return Ap, Ap_ns end |> PartitionedArrays.tuple_of_arrays # Caches rp = pfill(0.0,partition(Ph.gids)) dxp = pfill(0.0,partition(Ph.gids)) r = pfill(0.0,partition(Vh.gids)) x = pfill(0.0,partition(Vh.gids)) caches = (rp,dxp,r,x) return PatchBasedSmootherNumericalSetup(solver,nothing,Ap_ns,weights,caches) end function Gridap.Algebra.numerical_setup(ss::PatchBasedSymbolicSetup,A::PSparseMatrix,x::PVector) @check ss.solver.is_nonlinear solver = ss.solver Ph, Vh = solver.patch_space, solver.space weights = solver.weighted ? compute_weight_operators(Ph,Vh) : nothing # Patch system solver (only local systems need to be solved) u0, u, v = FEFunction(Vh,x), get_trial_fe_basis(Vh), get_fe_basis(Vh) contr = solver.biform(u0,u,v) matdata = collect_cell_matrix(Ph,Ph,contr) Ap, Ap_ns = map(local_views(Ph),matdata) do Ph, matdata assem = SparseMatrixAssembler(Ph,Ph) Ap = assemble_matrix(assem,matdata) Ap_ns = numerical_setup(symbolic_setup(solver.local_solver,Ap),Ap) return Ap, Ap_ns end |> PartitionedArrays.tuple_of_arrays # Caches rp = pfill(0.0,partition(Ph.gids)) dxp = pfill(0.0,partition(Ph.gids)) r = pfill(0.0,partition(Vh.gids)) x = pfill(0.0,partition(Vh.gids)) caches = (rp,dxp,r,x) return PatchBasedSmootherNumericalSetup(solver,Ap,Ap_ns,weights,caches) end function Gridap.Algebra.numerical_setup!(ns::PatchBasedSmootherNumericalSetup,A::PSparseMatrix,x::PVector) @check ns.solver.is_nonlinear solver = ns.solver Ph, Vh = solver.patch_space, solver.space Ap, Ap_ns = ns.local_A, ns.local_ns u0, u, v = FEFunction(Vh,x), get_trial_fe_basis(Vh), get_fe_basis(Vh) contr = solver.biform(u0,u,v) matdata = collect_cell_matrix(Ph,Ph,contr) map(Ap, Ap_ns, local_views(Ph), matdata) do Ap, Ap_ns, Ph, matdata assem = SparseMatrixAssembler(Ph,Ph) assemble_matrix!(Ap,assem,matdata) numerical_setup!(Ap_ns,Ap) end end function Gridap.Algebra.solve!(x::AbstractVector,ns::PatchBasedSmootherNumericalSetup,r::AbstractVector) Ap_ns, weights, caches = ns.local_ns, ns.weights, ns.caches Ph = ns.solver.patch_space #w, w_sums = weights rp, dxp = caches prolongate!(rp,Ph,r) solve!(dxp,Ap_ns,rp) inject!(x,Ph,dxp) return x end function Gridap.Algebra.solve!(x_mat::PVector,ns::PatchBasedSmootherNumericalSetup,r_mat::PVector) Ap_ns, weights, caches = ns.local_ns, ns.weights, ns.caches Ph = ns.solver.patch_space #w, w_sums = weights rp, dxp, r, x = caches copy!(r,r_mat) prolongate!(rp,Ph,r) map(solve!,partition(dxp),Ap_ns,partition(rp)) inject!(x,Ph,dxp) copy!(x_mat,x) return x_mat end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
16993
""" abstract type PatchBoundaryStyle end struct PatchBoundaryExclude <: PatchBoundaryStyle end struct PatchBoundaryInclude <: PatchBoundaryStyle end Controls the boundary consitions imposed at the patch boundaries for the sub-spaces. - `PatchBoundaryInclude`: No BCs are imposed at the patch boundaries. - `PatchBoundaryExclude`: Zero dirichlet BCs are imposed at the patch boundaries. """ abstract type PatchBoundaryStyle end struct PatchBoundaryExclude <: PatchBoundaryStyle end struct PatchBoundaryInclude <: PatchBoundaryStyle end """ struct PatchDecomposition{Dr,Dc,Dp} <: DiscreteModel{Dc,Dp} Represents a patch decomposition of a discrete model, i.e an overlapping cell covering `{Ω_i}` of `Ω` such that `Ω = Σ_i Ω_i`. ## Properties: - `Dr::Integer` : Dimension of the patch root - `model::DiscreteModel{Dc,Dp}` : Underlying discrete model - `patch_cells::Table` : [patch][local cell] -> cell - `patch_cells_overlapped::Table` : [patch][local cell] -> overlapped cell - `patch_cells_faces_on_boundary::Table` : [d][overlapped cell][local face] -> face is on patch boundary """ struct PatchDecomposition{Dr,Dc,Dp} <: GridapType model :: DiscreteModel{Dc,Dp} patch_cells :: Gridap.Arrays.Table # [patch][local cell] -> cell patch_cells_overlapped :: Gridap.Arrays.Table # [patch][local cell] -> overlapped cell patch_cells_faces_on_boundary :: Vector{Gridap.Arrays.Table} # [d][overlapped cell][local face] -> face is on patch boundary end num_patches(a::PatchDecomposition) = length(a.patch_cells) Gridap.Geometry.num_cells(a::PatchDecomposition) = length(a.patch_cells.data) @doc """ function PatchDecomposition( model::DiscreteModel{Dc,Dp}; Dr=0, patch_boundary_style::PatchBoundaryStyle=PatchBoundaryExclude(), boundary_tag_names::AbstractArray{String}=["boundary"] ) Returns an instance of [`PatchDecomposition`](@ref) from a given discrete model. """ function PatchDecomposition( model::DiscreteModel{Dc,Dp}; Dr=0, patch_boundary_style::PatchBoundaryStyle=PatchBoundaryExclude(), boundary_tag_names::AbstractArray{String}=["boundary"] ) where {Dc,Dp} Gridap.Helpers.@check 0 <= Dr <= Dc-1 topology = get_grid_topology(model) patch_cells = Gridap.Geometry.get_faces(topology,Dr,Dc) patch_facets = Gridap.Geometry.get_faces(topology,Dr,Dc-1) patch_cells_overlapped = compute_patch_overlapped_cells(patch_cells) patch_cells_faces_on_boundary = compute_patch_cells_faces_on_boundary( model, patch_cells, patch_cells_overlapped, patch_facets, patch_boundary_style, boundary_tag_names ) return PatchDecomposition{Dr,Dc,Dp}( model, patch_cells, patch_cells_overlapped, patch_cells_faces_on_boundary ) end function compute_patch_overlapped_cells(patch_cells) num_overlapped_cells = length(patch_cells.data) data = Gridap.Arrays.IdentityVector(num_overlapped_cells) return Gridap.Arrays.Table(data,patch_cells.ptrs) end # patch_cell_faces_on_boundary :: # [Df][overlapped cell][lface] -> Face is boundary of the patch function compute_patch_cells_faces_on_boundary( model::DiscreteModel, patch_cells, patch_cells_overlapped, patch_facets, patch_boundary_style, boundary_tag_names ) patch_cell_faces_on_boundary = _allocate_patch_cells_faces_on_boundary(model,patch_cells) if !isa(patch_boundary_style,PatchBoundaryInclude) _compute_patch_cells_faces_on_boundary!( patch_cell_faces_on_boundary, model, patch_cells, patch_cells_overlapped, patch_facets, patch_boundary_style, boundary_tag_names ) end return patch_cell_faces_on_boundary end function _allocate_patch_cells_faces_on_boundary(model::DiscreteModel{Dc},patch_cells) where {Dc} ctype_to_reffe = get_reffes(model) cell_to_ctype = get_cell_type(model) patch_cells_faces_on_boundary = Vector{Gridap.Arrays.Table}(undef,Dc) for d = 0:Dc-1 ctype_to_num_dfaces = map(reffe -> num_faces(reffe,d),ctype_to_reffe) patch_cells_faces_on_boundary[d+1] = _allocate_ocell_to_dface(Bool, patch_cells,cell_to_ctype, ctype_to_num_dfaces) end return patch_cells_faces_on_boundary end function _allocate_ocell_to_dface(::Type{T},patch_cells,cell_to_ctype,ctype_to_num_dfaces) where T<:Number num_overlapped_cells = length(patch_cells.data) ptrs = Vector{Int}(undef,num_overlapped_cells+1) ptrs[1] = 1 for i = 1:num_overlapped_cells cell = patch_cells.data[i] ctype = cell_to_ctype[cell] ptrs[i+1] = ptrs[i] + ctype_to_num_dfaces[ctype] end data = zeros(T,ptrs[end]-1) return Gridap.Arrays.Table(data,ptrs) end function _compute_patch_cells_faces_on_boundary!( patch_cells_faces_on_boundary, model::DiscreteModel, patch_cells, patch_cells_overlapped, patch_facets, patch_boundary_style, boundary_tag_names ) num_patches = length(patch_cells.ptrs)-1 cache_patch_cells = array_cache(patch_cells) cache_patch_facets = array_cache(patch_facets) for patch = 1:num_patches current_patch_cells = getindex!(cache_patch_cells,patch_cells,patch) current_patch_facets = getindex!(cache_patch_facets,patch_facets,patch) _compute_patch_cells_faces_on_boundary!( patch_cells_faces_on_boundary, model, patch, current_patch_cells, patch_cells_overlapped, current_patch_facets, patch_boundary_style, boundary_tag_names ) end end function _compute_patch_cells_faces_on_boundary!( patch_cells_faces_on_boundary, model::DiscreteModel{Dc}, patch, patch_cells, patch_cells_overlapped, patch_facets, patch_boundary_style, boundary_tag_names ) where Dc face_labeling = get_face_labeling(model) topology = get_grid_topology(model) boundary_tags = findall(x -> (x ∈ boundary_tag_names), face_labeling.tag_to_name) Gridap.Helpers.@check !isempty(boundary_tags) boundary_entities = vcat(face_labeling.tag_to_entities[boundary_tags]...) # Cells facets Df = Dc-1 cell_to_facets = Gridap.Geometry.get_faces(topology,Dc,Df) cache_cell_to_facets = array_cache(cell_to_facets) facet_to_cells = Gridap.Geometry.get_faces(topology,Df,Dc) cache_facet_to_cells = array_cache(facet_to_cells) d_to_facet_to_dfaces = [Gridap.Geometry.get_faces(topology,Df,d) for d = 0:Df-1] d_to_cell_to_dfaces = [Gridap.Geometry.get_faces(topology,Dc,d) for d = 0:Df-1] d_to_dface_to_cells = [Gridap.Geometry.get_faces(topology,d,Dc) for d = 0:Df-1] # Go over all cells in the current patch for (lcell,cell) in enumerate(patch_cells) overlapped_cell = patch_cells_overlapped.data[patch_cells_overlapped.ptrs[patch]+lcell-1] cell_facets = getindex!(cache_cell_to_facets,cell_to_facets,cell) # Go over the facets (i.e., faces of dim Dc-1) in the current cell for (lfacet,facet) in enumerate(cell_facets) facet_entity = face_labeling.d_to_dface_to_entity[Df+1][facet] cells_around_facet = getindex!(cache_facet_to_cells,facet_to_cells,facet) # Check if facet has a neighboring cell that does not belong to the patch has_nbor_outside_patch = false for c in cells_around_facet if c ∉ patch_cells has_nbor_outside_patch = true break end end facet_at_global_boundary = (facet_entity ∈ boundary_entities) && (facet ∉ patch_facets) facet_at_patch_boundary = facet_at_global_boundary || has_nbor_outside_patch if (facet_at_patch_boundary) # Mark the facet as boundary position = patch_cells_faces_on_boundary[Df+1].ptrs[overlapped_cell]+lfacet-1 patch_cells_faces_on_boundary[Df+1].data[position] = true # Go over the faces of lower dimension on the boundary of the current facet, # and mark them as boundary as well. for d = 0:Df-1 for facet_face in d_to_facet_to_dfaces[d+1][facet] # Locate the local position of the face within the cell (lface) for cell_around_face in d_to_dface_to_cells[d+1][facet_face] if cell_around_face ∈ patch_cells cell_dfaces = d_to_cell_to_dfaces[d+1][cell_around_face] lface = findfirst(x -> x==facet_face, cell_dfaces) lcell2 = findfirst(x -> x==cell_around_face, patch_cells) overlapped_cell2 = patch_cells_overlapped.data[patch_cells_overlapped.ptrs[patch]+lcell2-1] position = patch_cells_faces_on_boundary[d+1].ptrs[overlapped_cell2]+lface-1 patch_cells_faces_on_boundary[d+1].data[position] = true end end end end end end end end # Patch cell faces: # patch_faces[pcell] = [face1, face2, ...] # where face1, face2, ... are the faces of the overlapped cell `pcell` such that # - they are NOT on the boundary of the patch # - they are flagged `true` in faces_mask function get_patch_cell_faces(PD::PatchDecomposition,Df::Integer) model = PD.model topo = get_grid_topology(model) faces_mask = Fill(true,num_faces(topo,Df)) return get_patch_cell_faces(PD,Df,faces_mask) end function get_patch_cell_faces(PD::PatchDecomposition{Dr,Dc},Df::Integer,faces_mask) where {Dr,Dc} model = PD.model topo = get_grid_topology(model) c2e_map = Gridap.Geometry.get_faces(topo,Dc,Df) patch_cells = Gridap.Arrays.Table(PD.patch_cells) patch_cell_faces = map(Reindex(c2e_map),patch_cells.data) faces_on_boundary = PD.patch_cells_faces_on_boundary[Df+1] patch_faces = _allocate_patch_cell_faces(patch_cell_faces,faces_on_boundary,faces_mask) _generate_patch_cell_faces!(patch_faces,patch_cell_faces,faces_on_boundary,faces_mask) return patch_faces end function _allocate_patch_cell_faces(patch_cell_faces,faces_on_boundary,faces_mask) num_patch_cells = length(patch_cell_faces) num_patch_faces = 0 patch_cells_faces_cache = array_cache(patch_cell_faces) faces_on_boundary_cache = array_cache(faces_on_boundary) for iC in 1:num_patch_cells cell_faces = getindex!(patch_cells_faces_cache,patch_cell_faces,iC) on_boundary = getindex!(faces_on_boundary_cache,faces_on_boundary,iC) for (iF,face) in enumerate(cell_faces) if (!on_boundary[iF] && faces_mask[face]) num_patch_faces += 1 end end end patch_faces_data = zeros(Int64,num_patch_faces) patch_faces_ptrs = zeros(Int64,num_patch_cells+1) return Gridap.Arrays.Table(patch_faces_data,patch_faces_ptrs) end function _generate_patch_cell_faces!(patch_faces,patch_cell_faces,faces_on_boundary,faces_mask) num_patch_cells = length(patch_cell_faces) patch_faces_data, patch_faces_ptrs = patch_faces.data, patch_faces.ptrs pface = 1 patch_faces_ptrs[1] = 1 patch_cells_faces_cache = array_cache(patch_cell_faces) faces_on_boundary_cache = array_cache(faces_on_boundary) for iC in 1:num_patch_cells cell_faces = getindex!(patch_cells_faces_cache,patch_cell_faces,iC) on_boundary = getindex!(faces_on_boundary_cache,faces_on_boundary,iC) patch_faces_ptrs[iC+1] = patch_faces_ptrs[iC] for (iF,face) in enumerate(cell_faces) if (!on_boundary[iF] && faces_mask[face]) patch_faces_data[pface] = face patch_faces_ptrs[iC+1] += 1 pface += 1 end end end return patch_faces end # Patch faces: # patch_faces[patch] = [face1, face2, ...] # where face1, face2, ... are the faces of the patch such that # - they are NOT on the boundary of the patch # - they are flagged `true` in faces_mask # If `reverse` is `true`, the faces are the ones ON the boundary of the patch. function get_patch_faces( PD::PatchDecomposition{Dr,Dc},Df::Integer,faces_mask;reverse=false ) where {Dr,Dc} model = PD.model topo = get_grid_topology(model) c2e_map = Gridap.Geometry.get_faces(topo,Dc,Df) patch_cells = Gridap.Arrays.Table(PD.patch_cells) patch_cell_faces = map(Reindex(c2e_map),patch_cells.data) faces_on_boundary = PD.patch_cells_faces_on_boundary[Df+1] patch_faces = _allocate_patch_faces(patch_cells,patch_cell_faces,faces_on_boundary,faces_mask,reverse) _generate_patch_faces!(patch_faces,patch_cells,patch_cell_faces,faces_on_boundary,faces_mask,reverse) return patch_faces end function _allocate_patch_faces( patch_cells,patch_cell_faces,faces_on_boundary,faces_mask,reverse ) num_patches = length(patch_cells) touched = Dict{Int,Bool}() pcell = 1 num_patch_faces = 0 patch_cells_cache = array_cache(patch_cells) patch_cells_faces_cache = array_cache(patch_cell_faces) faces_on_boundary_cache = array_cache(faces_on_boundary) for patch in 1:num_patches current_patch_cells = getindex!(patch_cells_cache,patch_cells,patch) for _ in 1:length(current_patch_cells) cell_faces = getindex!(patch_cells_faces_cache,patch_cell_faces,pcell) on_boundary = getindex!(faces_on_boundary_cache,faces_on_boundary,pcell) for (iF,face) in enumerate(cell_faces) A = xor(on_boundary[iF],reverse) # reverse the flag if needed if (!A && faces_mask[face] && !haskey(touched,face)) num_patch_faces += 1 touched[face] = true end end pcell += 1 end empty!(touched) end patch_faces_data = zeros(Int64,num_patch_faces) patch_faces_ptrs = zeros(Int64,num_patches+1) return Gridap.Arrays.Table(patch_faces_data,patch_faces_ptrs) end function _generate_patch_faces!( patch_faces,patch_cells,patch_cell_faces,faces_on_boundary,faces_mask,reverse ) num_patches = length(patch_cells) patch_faces_data, patch_faces_ptrs = patch_faces.data, patch_faces.ptrs touched = Dict{Int,Bool}() pcell = 1 pface = 1 patch_faces_ptrs[1] = 1 patch_cells_cache = array_cache(patch_cells) patch_cells_faces_cache = array_cache(patch_cell_faces) faces_on_boundary_cache = array_cache(faces_on_boundary) for patch in 1:num_patches current_patch_cells = getindex!(patch_cells_cache,patch_cells,patch) patch_faces_ptrs[patch+1] = patch_faces_ptrs[patch] for _ in 1:length(current_patch_cells) cell_faces = getindex!(patch_cells_faces_cache,patch_cell_faces,pcell) on_boundary = getindex!(faces_on_boundary_cache,faces_on_boundary,pcell) for (iF,face) in enumerate(cell_faces) A = xor(on_boundary[iF],reverse) # reverse the flag if needed if (!A && faces_mask[face] && !haskey(touched,face)) patch_faces_data[pface] = face patch_faces_ptrs[patch+1] += 1 touched[face] = true pface += 1 end end pcell += 1 end empty!(touched) end return patch_faces end # Face connectivity for the patches # pface_to_pcell[pface] = [pcell1, pcell2, ...] # This would be the Gridap equivalent to `get_faces(patch_topology,Df,Dc)`. # On top of this, we also return the local cell index (within the face connectivity) of cell, # which is needed when a pface touches different cells depending on the patch. # The argument `patch_faces` allows to select only some pfaces (i.e boundary/skeleton/etc...). function get_pface_to_pcell(PD::PatchDecomposition{Dr,Dc},Df::Integer,patch_faces) where {Dr,Dc} model = PD.model topo = get_grid_topology(model) faces_to_cells = Gridap.Geometry.get_faces(topo,Df,Dc) pfaces_to_cells = lazy_map(Reindex(faces_to_cells),patch_faces.data) patch_cells = Gridap.Arrays.Table(PD.patch_cells) patch_cells_overlapped = PD.patch_cells_overlapped num_patches = length(patch_cells) num_pfaces = length(pfaces_to_cells) patch_cells_cache = array_cache(patch_cells) patch_cells_overlapped_cache = array_cache(patch_cells_overlapped) pfaces_to_cells_cache = array_cache(pfaces_to_cells) # Maximum length of the data array k = sum(pface -> length(getindex!(pfaces_to_cells_cache,pfaces_to_cells,pface)),1:num_pfaces) # Collect patch cells touched by each pface # Remark: Each pface does NOT necessarily touch all it's neighboring cells, since # some of them might be outside the patch. ptrs = zeros(Int64,num_pfaces+1) data = zeros(Int64,k) pface_to_lcell = zeros(Int8,k) k = 1 for patch in 1:num_patches cells = getindex!(patch_cells_cache,patch_cells,patch) cells_overlapped = getindex!(patch_cells_overlapped_cache,patch_cells_overlapped,patch) for pface in patch_faces.ptrs[patch]:patch_faces.ptrs[patch+1]-1 pface_to_cells = getindex!(pfaces_to_cells_cache,pfaces_to_cells,pface) for (lcell,cell) in enumerate(pface_to_cells) lid_patch = findfirst(c->c==cell,cells) if !isnothing(lid_patch) ptrs[pface+1] += 1 data[k] = cells_overlapped[lid_patch] pface_to_lcell[k] = Int8(lcell) k += 1 end end end end Arrays.length_to_ptrs!(ptrs) data = resize!(data,k-1) pface_to_lcell = resize!(pface_to_lcell,k-1) pface_to_pcell = Gridap.Arrays.Table(data,ptrs) return pface_to_pcell, pface_to_lcell end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
14438
# INPUT # [[1, 2]] # [[1, 2], [2, 3]] # [[2, 3], [3, 4]] # [[3, 4], [4, 5]] # [[4, 5]] # OUTPUT # [[1, 2]] # [[3, 4], [4, 5]] # [[6, 7], [7, 8]] # [[9, 10], [10, 11]] # [[12, 13]] # Negative numbers correspond to Dirichlet DoFs # in the GLOBAL space. In these examples, we # are neglecting Dirichlet DoFs in the boundary # of the patches (assuming they are needed) # INPUT # [[-1, 1]] # [[-1, 1], [1, 2]] # [[1, 2], [2, 3]] # [[2, 3], [3, -2]] # [[3, -2]] # OUTPUT # [[-1, 1]] # [[-1, 2], [2, 3]] # [[4, 5], [5, 6]] # [[6, 7], [7, -2]] # [[8, -2]] """ struct PatchFESpace <: SingleFieldFESpace ... end FESpace representing a patch-based subspace decomposition `V = Σ_i V_i` of a global space `V`. """ struct PatchFESpace <: FESpaces.SingleFieldFESpace Vh :: FESpaces.SingleFieldFESpace patch_decomposition :: PatchDecomposition num_dofs :: Int patch_cell_dofs_ids :: Arrays.Table dof_to_pdof :: Arrays.Table end @doc """ function PatchFESpace( space::FESpaces.SingleFieldFESpace, patch_decomposition::PatchDecomposition, reffe::Union{ReferenceFE,Tuple{<:ReferenceFEs.ReferenceFEName,Any,Any}}; conformity=nothing, patches_mask=Fill(false,num_patches(patch_decomposition)) ) Constructs a `PatchFESpace` from a global `SingleFieldFESpace` and a `PatchDecomposition`. The conformity of the FESpace is deduced from `reffe` and `conformity`, which need to be the same as the ones used to construct the global FESpace. If `patches_mask[p] = true`, the patch `p` is ignored. Used in parallel. """ function PatchFESpace( space::FESpaces.SingleFieldFESpace, patch_decomposition::PatchDecomposition, reffe::Union{ReferenceFE,Tuple{<:ReferenceFEs.ReferenceFEName,Any,Any}}; conformity=nothing, patches_mask=Fill(false,num_patches(patch_decomposition)) ) cell_conformity = MultilevelTools._cell_conformity(patch_decomposition.model,reffe;conformity=conformity) return PatchFESpace(space,patch_decomposition,cell_conformity;patches_mask=patches_mask) end @doc """ function PatchFESpace( space::FESpaces.SingleFieldFESpace, patch_decomposition::PatchDecomposition, cell_conformity::CellConformity; patches_mask=Fill(false,num_patches(patch_decomposition)) ) Constructs a `PatchFESpace` from a global `SingleFieldFESpace`, a `PatchDecomposition` and a `CellConformity` instance. If `patches_mask[p] = true`, the patch `p` is ignored. Used in parallel. """ function PatchFESpace( space::FESpaces.SingleFieldFESpace, patch_decomposition::PatchDecomposition, cell_conformity::CellConformity; patches_mask = Fill(false,num_patches(patch_decomposition)) ) cell_dofs_ids = get_cell_dof_ids(space) patch_cell_dofs_ids, num_dofs = generate_patch_cell_dofs_ids( get_grid_topology(patch_decomposition.model), patch_decomposition.patch_cells, patch_decomposition.patch_cells_overlapped, patch_decomposition.patch_cells_faces_on_boundary, cell_dofs_ids,cell_conformity,patches_mask ) dof_to_pdof = generate_dof_to_pdof(space,patch_decomposition,patch_cell_dofs_ids) return PatchFESpace(space,patch_decomposition,num_dofs,patch_cell_dofs_ids,dof_to_pdof) end FESpaces.get_dof_value_type(a::PatchFESpace) = Gridap.FESpaces.get_dof_value_type(a.Vh) FESpaces.get_free_dof_ids(a::PatchFESpace) = Base.OneTo(a.num_dofs) FESpaces.get_fe_basis(a::PatchFESpace) = get_fe_basis(a.Vh) FESpaces.ConstraintStyle(::PatchFESpace) = Gridap.FESpaces.UnConstrained() FESpaces.ConstraintStyle(::Type{PatchFESpace}) = Gridap.FESpaces.UnConstrained() FESpaces.get_vector_type(a::PatchFESpace) = get_vector_type(a.Vh) FESpaces.get_fe_dof_basis(a::PatchFESpace) = get_fe_dof_basis(a.Vh) function Gridap.CellData.get_triangulation(a::PatchFESpace) PD = a.patch_decomposition patch_cells = Gridap.Arrays.Table(PD.patch_cells) trian = get_triangulation(a.Vh) return PatchTriangulation(trian,PD,patch_cells,nothing) end # get_cell_dof_ids FESpaces.get_cell_dof_ids(a::PatchFESpace) = a.patch_cell_dofs_ids FESpaces.get_cell_dof_ids(a::PatchFESpace,::Triangulation) = @notimplemented function FESpaces.get_cell_dof_ids(a::PatchFESpace,trian::PatchTriangulation) return get_cell_dof_ids(trian.trian,a,trian) end function FESpaces.get_cell_dof_ids(t::Gridap.Adaptivity.AdaptedTriangulation,a::PatchFESpace,trian::PatchTriangulation) return get_cell_dof_ids(t.trian,a,trian) end function FESpaces.get_cell_dof_ids(::Triangulation,a::PatchFESpace,trian::PatchTriangulation) return a.patch_cell_dofs_ids end function FESpaces.get_cell_dof_ids(::BoundaryTriangulation,a::PatchFESpace,trian::PatchTriangulation) cell_dof_ids = get_cell_dof_ids(a) pface_to_pcell = trian.pface_to_pcell pcells = isempty(pface_to_pcell) ? Int[] : lazy_map(x->x[1],pface_to_pcell) return lazy_map(Reindex(cell_dof_ids),pcells) end function FESpaces.get_cell_dof_ids(::SkeletonTriangulation,a::PatchFESpace,trian::PatchTriangulation) cell_dof_ids = get_cell_dof_ids(a) pface_to_pcell = trian.pface_to_pcell pcells_plus = isempty(pface_to_pcell) ? Int[] : lazy_map(x->x[1],pface_to_pcell) pcells_minus = isempty(pface_to_pcell) ? Int[] : lazy_map(x->x[2],pface_to_pcell) plus = lazy_map(Reindex(cell_dof_ids),pcells_plus) minus = lazy_map(Reindex(cell_dof_ids),pcells_minus) return lazy_map(Fields.BlockMap(2,[1,2]),plus,minus) end # scatter dof values function FESpaces.scatter_free_and_dirichlet_values(f::PatchFESpace,free_values,dirichlet_values) cell_vals = Fields.PosNegReindex(free_values,dirichlet_values) return lazy_map(Broadcasting(cell_vals),f.patch_cell_dofs_ids) end # Construction of the patch cell dofs ids function generate_patch_cell_dofs_ids( topology, patch_cells, patch_cells_overlapped, patch_cells_faces_on_boundary, cell_dofs_ids, cell_conformity, patches_mask ) patch_cell_dofs_ids = allocate_patch_cell_dofs_ids(patch_cells,cell_dofs_ids) num_dofs = generate_patch_cell_dofs_ids!( patch_cell_dofs_ids,topology, patch_cells,patch_cells_overlapped, patch_cells_faces_on_boundary, cell_dofs_ids,cell_conformity,patches_mask ) return patch_cell_dofs_ids, num_dofs end function allocate_patch_cell_dofs_ids(patch_cells,cell_dofs_ids) cache_cells = array_cache(patch_cells) cache_cdofs = array_cache(cell_dofs_ids) num_overlapped_cells = length(patch_cells.data) ptrs = Vector{Int}(undef,num_overlapped_cells+1) ptrs[1] = 1; ncells = 1 for patch = 1:length(patch_cells) cells = getindex!(cache_cells,patch_cells,patch) for cell in cells current_cell_dof_ids = getindex!(cache_cdofs,cell_dofs_ids,cell) ptrs[ncells+1] = ptrs[ncells]+length(current_cell_dof_ids) ncells += 1 end end @check num_overlapped_cells+1 == ncells data = Vector{Int}(undef,ptrs[end]-1) return Gridap.Arrays.Table(data,ptrs) end function generate_patch_cell_dofs_ids!( patch_cell_dofs_ids, topology, patch_cells, patch_cells_overlapped, patch_cells_faces_on_boundary, cell_dofs_ids, cell_conformity, patches_mask ) cache = array_cache(patch_cells) num_patches = length(patch_cells) current_dof = 1 for patch = 1:num_patches current_patch_cells = getindex!(cache,patch_cells,patch) current_dof = generate_patch_cell_dofs_ids!( patch_cell_dofs_ids, topology, patch, current_patch_cells, patch_cells_overlapped, patch_cells_faces_on_boundary, cell_dofs_ids, cell_conformity; free_dofs_offset=current_dof, mask=patches_mask[patch] ) end return current_dof-1 end # TO-THINK/STRESS: # 1. MultiFieldFESpace case? # 2. FESpaces which are directly defined on physical space? We think this case is covered by # the fact that we are using a CellConformity instance to rely on ownership info. # free_dofs_offset : the ID from which we start to assign free DoF IDs upwards # Note: we do not actually need to generate a global numbering for Dirichlet DoFs. We can # tag all as them with -1, as we are always imposing homogenous Dirichlet boundary # conditions, and thus there is no need to address the result of interpolating Dirichlet # Data into the FE space. function generate_patch_cell_dofs_ids!( patch_cell_dofs_ids, topology, patch::Integer, patch_cells::AbstractVector{<:Integer}, patch_cells_overlapped::Gridap.Arrays.Table, patch_cells_faces_on_boundary, global_space_cell_dofs_ids, cell_conformity; free_dofs_offset=1, mask=false ) o = patch_cells_overlapped.ptrs[patch] if mask for lpatch_cell = 1:length(patch_cells) cell_overlapped_mesh = patch_cells_overlapped.data[o+lpatch_cell-1] s = patch_cell_dofs_ids.ptrs[cell_overlapped_mesh] e = patch_cell_dofs_ids.ptrs[cell_overlapped_mesh+1]-1 patch_cell_dofs_ids.data[s:e] .= -1 end else g2l = Dict{Int,Int}() Dc = length(patch_cells_faces_on_boundary) d_to_cell_to_dface = [Gridap.Geometry.get_faces(topology,Dc,d) for d in 0:Dc-1] # Loop over cells of the patch (local_cell_id_within_patch) for (lpatch_cell,patch_cell) in enumerate(patch_cells) cell_overlapped_mesh = patch_cells_overlapped.data[o+lpatch_cell-1] s = patch_cell_dofs_ids.ptrs[cell_overlapped_mesh] e = patch_cell_dofs_ids.ptrs[cell_overlapped_mesh+1]-1 current_patch_cell_dofs_ids = view(patch_cell_dofs_ids.data,s:e) ctype = cell_conformity.cell_ctype[patch_cell] # 1) DoFs belonging to faces (Df < Dc) face_offset = 0 for d = 0:Dc-1 num_cell_faces = length(d_to_cell_to_dface[d+1][patch_cell]) for lface in 1:num_cell_faces for ldof in cell_conformity.ctype_lface_own_ldofs[ctype][face_offset+lface] gdof = global_space_cell_dofs_ids[patch_cell][ldof] face_in_patch_boundary = patch_cells_faces_on_boundary[d+1][cell_overlapped_mesh][lface] dof_is_dirichlet = (gdof < 0) if face_in_patch_boundary || dof_is_dirichlet current_patch_cell_dofs_ids[ldof] = -1 elseif gdof in keys(g2l) current_patch_cell_dofs_ids[ldof] = g2l[gdof] else g2l[gdof] = free_dofs_offset current_patch_cell_dofs_ids[ldof] = free_dofs_offset free_dofs_offset += 1 end end end face_offset += cell_conformity.d_ctype_num_dfaces[d+1][ctype] end # 2) Interior DoFs for ldof in cell_conformity.ctype_lface_own_ldofs[ctype][face_offset+1] current_patch_cell_dofs_ids[ldof] = free_dofs_offset free_dofs_offset += 1 end end end return free_dofs_offset end function generate_dof_to_pdof(Vh,PD,patch_cell_dofs_ids) dof_to_pdof = _allocate_dof_to_pdof(Vh,PD,patch_cell_dofs_ids) _generate_dof_to_pdof!(dof_to_pdof,Vh,PD,patch_cell_dofs_ids) return dof_to_pdof end function _allocate_dof_to_pdof(Vh,PD,patch_cell_dofs_ids) touched = Dict{Int,Bool}() cell_mesh_overlapped = 1 cache_patch_cells = array_cache(PD.patch_cells) cell_dof_ids = get_cell_dof_ids(Vh) cache_cell_dof_ids = array_cache(cell_dof_ids) ptrs = fill(0,num_free_dofs(Vh)+1) for patch = 1:length(PD.patch_cells) current_patch_cells = getindex!(cache_patch_cells,PD.patch_cells,patch) for cell in current_patch_cells current_cell_dof_ids = getindex!(cache_cell_dof_ids,cell_dof_ids,cell) s = patch_cell_dofs_ids.ptrs[cell_mesh_overlapped] e = patch_cell_dofs_ids.ptrs[cell_mesh_overlapped+1]-1 current_patch_cell_dof_ids = view(patch_cell_dofs_ids.data,s:e) for (dof,pdof) in zip(current_cell_dof_ids,current_patch_cell_dof_ids) if pdof > 0 && !(dof ∈ keys(touched)) touched[dof] = true ptrs[dof+1] += 1 end end cell_mesh_overlapped += 1 end empty!(touched) end PartitionedArrays.length_to_ptrs!(ptrs) data = fill(0,ptrs[end]-1) return Gridap.Arrays.Table(data,ptrs) end function _generate_dof_to_pdof!(dof_to_pdof,Vh,PD,patch_cell_dofs_ids) touched = Dict{Int,Bool}() cell_mesh_overlapped = 1 cache_patch_cells = array_cache(PD.patch_cells) cell_dof_ids = get_cell_dof_ids(Vh) cache_cell_dof_ids = array_cache(cell_dof_ids) ptrs = dof_to_pdof.ptrs data = dof_to_pdof.data local_ptrs = fill(Int32(0),num_free_dofs(Vh)) for patch = 1:length(PD.patch_cells) current_patch_cells = getindex!(cache_patch_cells,PD.patch_cells,patch) for cell in current_patch_cells current_cell_dof_ids = getindex!(cache_cell_dof_ids,cell_dof_ids,cell) s = patch_cell_dofs_ids.ptrs[cell_mesh_overlapped] e = patch_cell_dofs_ids.ptrs[cell_mesh_overlapped+1]-1 current_patch_cell_dof_ids = view(patch_cell_dofs_ids.data,s:e) for (dof,pdof) in zip(current_cell_dof_ids,current_patch_cell_dof_ids) if pdof > 0 && !(dof ∈ keys(touched)) touched[dof] = true idx = ptrs[dof] + local_ptrs[dof] @check idx < ptrs[dof+1] data[idx] = pdof local_ptrs[dof] += 1 end end cell_mesh_overlapped += 1 end empty!(touched) end end # x \in PatchFESpace # y \in SingleFESpace function prolongate!(x,Ph::PatchFESpace,y;dof_ids=LinearIndices(y)) dof_to_pdof = Ph.dof_to_pdof ptrs = dof_to_pdof.ptrs data = dof_to_pdof.data for dof in dof_ids for k in ptrs[dof]:ptrs[dof+1]-1 pdof = data[k] x[pdof] = y[dof] end end end # x \in SingleFESpace # y \in PatchFESpace function inject!(x,Ph::PatchFESpace,y) dof_to_pdof = Ph.dof_to_pdof ptrs = dof_to_pdof.ptrs data = dof_to_pdof.data for dof in 1:length(dof_to_pdof) x[dof] = 0.0 for k in ptrs[dof]:ptrs[dof+1]-1 pdof = data[k] x[dof] += y[pdof] end end end function inject!(x,Ph::PatchFESpace,y,w,w_sums) dof_to_pdof = Ph.dof_to_pdof ptrs = dof_to_pdof.ptrs data = dof_to_pdof.data for dof in 1:length(dof_to_pdof) x[dof] = 0.0 for k in ptrs[dof]:ptrs[dof+1]-1 pdof = data[k] x[dof] += y[pdof] * w[pdof] end x[dof] /= w_sums[dof] end end function compute_weight_operators(Ph::PatchFESpace,Vh) w = Fill(1.0,num_free_dofs(Ph)) w_sums = zeros(num_free_dofs(Vh)) inject!(w_sums,Ph,w,Fill(1.0,num_free_dofs(Ph)),Fill(1.0,num_free_dofs(Vh))) return w, w_sums end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
3396
## PatchFESpace from MultiFieldFESpace @doc """ function PatchFESpace( space::Gridap.MultiField.MultiFieldFESpace, patch_decomposition::PatchDecomposition, cell_conformity::Vector{<:CellConformity}; kwargs... ) `PatchFESpace` constructor for `MultiFieldFESpace`. Returns a `MultiFieldFESpace` of `PatchFESpace`s . """ function PatchFESpace( space::Gridap.MultiField.MultiFieldFESpace, patch_decomposition::PatchDecomposition, cell_conformity::Vector{<:CellConformity}; kwargs... ) patch_spaces = map((s,c) -> PatchFESpace(s,patch_decomposition,c;kwargs...),space,cell_conformity) return MultiFieldFESpace(patch_spaces) end function PatchFESpace( space::GridapDistributed.DistributedMultiFieldFESpace, patch_decomposition::DistributedPatchDecomposition, cell_conformity::Vector; patches_mask = default_patches_mask(patch_decomposition) ) field_spaces = map((s,c) -> PatchFESpace(s,patch_decomposition,c;patches_mask),space,cell_conformity) part_spaces = map(MultiFieldFESpace,GridapDistributed.to_parray_of_arrays(map(local_views,field_spaces))) # This PRange has no ghost dofs local_ndofs = map(num_free_dofs,part_spaces) global_ndofs = sum(local_ndofs) patch_partition = variable_partition(local_ndofs,global_ndofs,false) gids = PRange(patch_partition) vector_type = get_vector_type(space) return GridapDistributed.DistributedMultiFieldFESpace(field_spaces,part_spaces,gids,vector_type) end # Inject/Prolongate for MultiField (only for ConsecutiveMultiFieldStyle) # x \in PatchFESpace # y \in SingleFESpace function prolongate!(x,Ph::MultiFieldFESpace,y) Ph_spaces = Ph.spaces Vh_spaces = map(Phi -> Phi.Vh, Ph_spaces) Ph_offsets = Gridap.MultiField._compute_field_offsets(Ph_spaces) Vh_offsets = Gridap.MultiField._compute_field_offsets(Vh_spaces) Ph_ndofs = map(num_free_dofs,Ph_spaces) Vh_ndofs = map(num_free_dofs,Vh_spaces) for (i,Ph_i) in enumerate(Ph_spaces) x_i = view(x, Ph_offsets[i]+1:Ph_offsets[i]+Ph_ndofs[i]) y_i = view(y, Vh_offsets[i]+1:Vh_offsets[i]+Vh_ndofs[i]) prolongate!(x_i,Ph_i,y_i) end end # x \in SingleFESpace # y \in PatchFESpace function inject!(x,Ph::MultiFieldFESpace,y) Ph_spaces = Ph.spaces Vh_spaces = map(Phi -> Phi.Vh, Ph_spaces) Ph_offsets = Gridap.MultiField._compute_field_offsets(Ph_spaces) Vh_offsets = Gridap.MultiField._compute_field_offsets(Vh_spaces) Ph_ndofs = map(num_free_dofs,Ph_spaces) Vh_ndofs = map(num_free_dofs,Vh_spaces) for (i,Ph_i) in enumerate(Ph_spaces) y_i = view(y, Ph_offsets[i]+1:Ph_offsets[i]+Ph_ndofs[i]) x_i = view(x, Vh_offsets[i]+1:Vh_offsets[i]+Vh_ndofs[i]) inject!(x_i,Ph_i,y_i) end end function prolongate!(x::PVector, Ph::GridapDistributed.DistributedMultiFieldFESpace, y::PVector; is_consistent::Bool=false) if !is_consistent consistent!(y) |> fetch end map(prolongate!,partition(x),local_views(Ph),partition(y)) end function inject!(x::PVector, Ph::GridapDistributed.DistributedMultiFieldFESpace, y::PVector; make_consistent::Bool=true) map(partition(x),local_views(Ph),partition(y)) do x,Ph,y inject!(x,Ph,y) end # Exchange local contributions assemble!(x) |> fetch if make_consistent consistent!(x) |> fetch end return x end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
10599
""" struct PatchProlongationOperator end A `PatchProlongationOperator` is a modified prolongation operator such that given a coarse solution `xH` returns ``` xh = Ih(xH) - yh ``` where `yh` is a subspace-based correction computed by solving local problems on coarse cells within the fine mesh. """ struct PatchProlongationOperator{R,A,B,C} sh :: A PD :: B lhs :: Union{Nothing,Function} rhs :: Union{Nothing,Function} is_nonlinear :: Bool caches :: C function PatchProlongationOperator{R}(sh,PD,lhs,rhs,is_nonlinear,caches) where R A, B, C = typeof(sh), typeof(PD), typeof(caches) new{R,A,B,C}(sh,PD,lhs,rhs,is_nonlinear,caches) end end @doc """ function PatchProlongationOperator( lev :: Integer, sh :: FESpaceHierarchy, PD :: PatchDecomposition, lhs :: Function, rhs :: Function; is_nonlinear=false ) Returns an instance of `PatchProlongationOperator` for a given level `lev` and a given FESpaceHierarchy `sh`. The subspace-based correction on a solution `uH` is computed by solving local problems given by ``` lhs(u_i,v_i) = rhs(uH,v_i) ∀ v_i ∈ V_i ``` where `V_i` is the patch-local space indiced by the PatchDecomposition `PD`. """ function PatchProlongationOperator(lev,sh,PD,lhs,rhs;is_nonlinear=false) cache_refine = MultilevelTools._get_interpolation_cache(lev,sh,0,:residual) cache_redist = MultilevelTools._get_redistribution_cache(lev,sh,:residual,:prolongation,:interpolation,cache_refine) cache_patch = _get_patch_cache(lev,sh,PD,lhs,rhs,is_nonlinear,cache_refine) caches = cache_refine, cache_patch, cache_redist redist = has_redistribution(sh,lev) R = typeof(Val(redist)) return PatchProlongationOperator{R}(sh,PD,lhs,rhs,is_nonlinear,caches) end function _get_patch_cache(lev,sh,PD,lhs,rhs,is_nonlinear,cache_refine) model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine cparts = get_level_parts(sh,lev+1) if i_am_in(cparts) # Patch-based correction fespace glue = sh[lev].mh_level.ref_glue patches_mask = get_coarse_node_mask(model_h,glue) cell_conformity = MultilevelTools.get_cell_conformity_before_redist(sh,lev) Ph = PatchFESpace(Uh,PD,cell_conformity;patches_mask) # Solver caches u, v = get_trial_fe_basis(Uh), get_fe_basis(Uh) contr = is_nonlinear ? lhs(zero(Uh),u,v) : lhs(u,v) matdata = collect_cell_matrix(Ph,Ph,contr) Ap_ns, Ap = map(local_views(Ph),matdata) do Ph, matdata assem = SparseMatrixAssembler(Ph,Ph) Ap = assemble_matrix(assem,matdata) Ap_ns = numerical_setup(symbolic_setup(LUSolver(),Ap),Ap) return Ap_ns, Ap end |> tuple_of_arrays Ap = is_nonlinear ? Ap : nothing duh = zero(Uh) dxp, rp = zero_free_values(Ph), zero_free_values(Ph) return Ph, Ap_ns, Ap, duh, dxp, rp else return nothing, nothing, nothing, nothing, nothing, nothing end end # Please make this a standard API or something function MultilevelTools.update_transfer_operator!(op::PatchProlongationOperator,x::Union{PVector,Nothing}) cache_refine, cache_patch, cache_redist = op.caches model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine Ph, Ap_ns, Ap, duh, dxp, rp = cache_patch if !isa(cache_redist,Nothing) fv_h_red, dv_h_red, Uh_red, model_h_red, glue, cache_exchange = cache_redist copy!(fv_h_red,x) consistent!(fv_h_red) |> fetch GridapDistributed.redistribute_free_values(fv_h,Uh,fv_h_red,dv_h_red,Uh_red,model_h,glue;reverse=true) else copy!(fv_h,x) end if !isa(fv_h,Nothing) u, v = get_trial_fe_basis(Uh), get_fe_basis(Uh) contr = op.is_nonlinear ? op.lhs(FEFunction(Uh,fv_h),u,v) : op.lhs(u,v) matdata = collect_cell_matrix(Ph,Ph,contr) map(Ap_ns,Ap,local_views(Ph),matdata) do Ap_ns, Ap, Ph, matdata assem = SparseMatrixAssembler(Ph,Ph) assemble_matrix!(Ap,assem,matdata) numerical_setup!(Ap_ns,Ap) end end end function LinearAlgebra.mul!(y::PVector,A::PatchProlongationOperator{Val{false}},x::PVector) cache_refine, cache_patch, cache_redist = A.caches model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine Ph, Ap_ns, Ap, duh, dxp, rp = cache_patch dxh = get_free_dof_values(duh) copy!(fv_H,x) # Matrix layout -> FE layout uH = FEFunction(UH,fv_H,dv_H) interpolate!(uH,fv_h,Uh) uh = FEFunction(Uh,fv_h,dv_h) assemble_vector!(v->A.rhs(uh,v),rp,Ph) map(solve!,partition(dxp),Ap_ns,partition(rp)) inject!(dxh,Ph,dxp) fv_h .= fv_h .- dxh copy!(y,fv_h) return y end function LinearAlgebra.mul!(y::PVector,A::PatchProlongationOperator{Val{true}},x::Union{PVector,Nothing}) cache_refine, cache_patch, cache_redist = A.caches model_h, Uh, fv_h, dv_h, UH, fv_H, dv_H = cache_refine fv_h_red, dv_h_red, Uh_red, model_h_red, glue, cache_exchange = cache_redist Ph, Ap_ns, Ap, duh, dxp, rp = cache_patch dxh = isa(duh,Nothing) ? nothing : get_free_dof_values(duh) # 1 - Interpolate in coarse partition if !isa(x,Nothing) copy!(fv_H,x) # Matrix layout -> FE layout uH = FEFunction(UH,fv_H,dv_H) interpolate!(uH,fv_h,Uh) uh = FEFunction(Uh,fv_h,dv_h) assemble_vector!(v->A.rhs(uh,v),rp,Ph) map(solve!,partition(dxp),Ap_ns,partition(rp)) inject!(dxh,Ph,dxp) fv_h .= fv_h .- dxh end # 2 - Redistribute from coarse partition to fine partition GridapDistributed.redistribute_free_values!(cache_exchange,fv_h_red,Uh_red,fv_h,dv_h,Uh,model_h_red,glue;reverse=false) copy!(y,fv_h_red) # FE layout -> Matrix layout return y end function setup_patch_prolongation_operators(sh,lhs,rhs,qdegrees;is_nonlinear=false) map(view(linear_indices(sh),1:num_levels(sh)-1)) do lev qdegree = isa(qdegrees,Number) ? qdegrees : qdegrees[lev] cparts = get_level_parts(sh,lev+1) if i_am_in(cparts) model = get_model_before_redist(sh,lev) PD = PatchDecomposition(model) Ω = Triangulation(PD) dΩ = Measure(Ω,qdegree) lhs_i = is_nonlinear ? (u,du,dv) -> lhs(u,du,dv,dΩ) : (u,v) -> lhs(u,v,dΩ) rhs_i = (u,v) -> rhs(u,v,dΩ) else PD, lhs_i, rhs_i = nothing, nothing, nothing end PatchProlongationOperator(lev,sh,PD,lhs_i,rhs_i;is_nonlinear) end end function get_coarse_node_mask(fmodel::GridapDistributed.DistributedDiscreteModel,glue) gids = get_face_gids(fmodel,0) mask = map(local_views(fmodel),glue,partition(gids)) do fmodel, glue, gids mask = get_coarse_node_mask(fmodel,glue) mask[ghost_to_local(gids)] .= true # Mask ghost nodes as well return mask end return mask end # Coarse nodes are the ones that are shared by fine cells that do not belong to the same coarse cell. # Conversely, fine nodes are the ones shared by fine cells that all have the same parent coarse cell. function get_coarse_node_mask(fmodel::DiscreteModel{Dc},glue) where Dc ftopo = get_grid_topology(fmodel) n2c_map = Gridap.Geometry.get_faces(ftopo,0,Dc) n2c_map_cache = array_cache(n2c_map) f2c_cells = glue.n2o_faces_map[Dc+1] is_boundary = get_isboundary_face(ftopo,0) is_coarse = map(1:length(n2c_map)) do n nbor_cells = getindex!(n2c_map_cache,n2c_map,n) parent = f2c_cells[first(nbor_cells)] return is_boundary[n] || any(c -> f2c_cells[c] != parent, nbor_cells) end return is_coarse end # PatchRestrictionOperator struct PatchRestrictionOperator{R,A,B} Ip :: A rhs :: Union{Function,Nothing} caches :: B function PatchRestrictionOperator{R}( Ip::PatchProlongationOperator{R}, rhs, caches ) where R A = typeof(Ip) B = typeof(caches) new{R,A,B}(Ip,rhs,caches) end end function PatchRestrictionOperator(lev,sh,Ip,rhs,qdegree;solver=LUSolver()) cache_refine = MultilevelTools._get_dual_projection_cache(lev,sh,qdegree,solver) cache_redist = MultilevelTools._get_redistribution_cache(lev,sh,:residual,:restriction,:dual_projection,cache_refine) cache_patch = Ip.caches[2] caches = cache_refine, cache_patch, cache_redist redist = has_redistribution(sh,lev) R = typeof(Val(redist)) return PatchRestrictionOperator{R}(Ip,rhs,caches) end function MultilevelTools.update_transfer_operator!(op::PatchRestrictionOperator,x::Union{PVector,Nothing}) nothing end function setup_patch_restriction_operators(sh,patch_prolongations,rhs,qdegrees;kwargs...) map(view(linear_indices(sh),1:num_levels(sh)-1)) do lev qdegree = isa(qdegrees,Number) ? qdegrees : qdegrees[lev] cparts = get_level_parts(sh,lev+1) if i_am_in(cparts) model = get_model_before_redist(sh,lev) Ω = Triangulation(model) dΩ = Measure(Ω,qdegree) rhs_i = (u,v) -> rhs(u,v,dΩ) else rhs_i = nothing end Ip = patch_prolongations[lev] PatchRestrictionOperator(lev,sh,Ip,rhs_i,qdegree;kwargs...) end end function LinearAlgebra.mul!(y::PVector,A::PatchRestrictionOperator{Val{false}},x::PVector) cache_refine, cache_patch, _ = A.caches model_h, Uh, VH, Mh_ns, rh, uh, assem, dΩhH = cache_refine Ph, Ap_ns, Ap, duh, dxp, rp = cache_patch fv_h = get_free_dof_values(uh) dxh = get_free_dof_values(duh) copy!(fv_h,x) fill!(rp,0.0) prolongate!(rp,Ph,fv_h) map(solve!,partition(dxp),Ap_ns,partition(rp)) inject!(dxh,Ph,dxp) consistent!(dxh) |> fetch assemble_vector!(v->A.rhs(duh,v),rh,Uh) fv_h .= fv_h .- rh consistent!(fv_h) |> fetch solve!(rh,Mh_ns,fv_h) copy!(fv_h,rh) consistent!(fv_h) |> fetch v = get_fe_basis(VH) assemble_vector!(y,assem,collect_cell_vector(VH,∫(v⋅uh)*dΩhH)) return y end function LinearAlgebra.mul!(y::Union{PVector,Nothing},A::PatchRestrictionOperator{Val{true}},x::PVector) cache_refine, cache_patch, cache_redist = A.caches model_h, Uh, VH, Mh_ns, rh, uh, assem, dΩhH = cache_refine Ph, Ap_ns, Ap, duh, dxp, rp = cache_patch fv_h_red, dv_h_red, Uh_red, model_h_red, glue, cache_exchange = cache_redist fv_h = isa(uh,Nothing) ? nothing : get_free_dof_values(uh) dxh = isa(duh,Nothing) ? nothing : get_free_dof_values(duh) copy!(fv_h_red,x) consistent!(fv_h_red) |> fetch GridapDistributed.redistribute_free_values!(cache_exchange,fv_h,Uh,fv_h_red,dv_h_red,Uh_red,model_h,glue;reverse=true) if !isa(y,Nothing) fill!(rp,0.0) prolongate!(rp,Ph,fv_h;is_consistent=true) map(solve!,partition(dxp),Ap_ns,partition(rp)) inject!(dxh,Ph,dxp) consistent!(dxh) |> fetch assemble_vector!(v->A.rhs(duh,v),rh,Uh) fv_h .= fv_h .- rh consistent!(fv_h) |> fetch solve!(rh,Mh_ns,fv_h) copy!(fv_h,rh) consistent!(fv_h) |> fetch v = get_fe_basis(VH) assemble_vector!(y,assem,collect_cell_vector(VH,∫(v⋅uh)*dΩhH)) end return y end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
6703
""" struct PatchTriangulation{Dc,Dp} <: Triangulation{Dc,Dp} ... end Wrapper around a Triangulation, for patch-based assembly. """ struct PatchTriangulation{Dc,Dp,A,B,C,D} <: Gridap.Geometry.Triangulation{Dc,Dp} trian :: A PD :: B patch_faces :: C pface_to_pcell :: D function PatchTriangulation( trian::Triangulation{Dc,Dp}, PD::PatchDecomposition, patch_faces, pface_to_pcell ) where {Dc,Dp} A = typeof(trian) B = typeof(PD) C = typeof(patch_faces) D = typeof(pface_to_pcell) new{Dc,Dp,A,B,C,D}(trian,PD,patch_faces,pface_to_pcell) end end # Triangulation API function Geometry.get_background_model(t::PatchTriangulation) get_background_model(t.trian) end function Geometry.get_grid(t::PatchTriangulation) get_grid(t.trian) end function Geometry.get_glue(t::PatchTriangulation,::Val{d}) where d get_glue(t.trian,Val(d)) end function Geometry.get_facet_normal(trian::PatchTriangulation) get_facet_normal(trian.trian) end # For now, I am disabling changes from PatchTriangulations to other Triangulations. # Reason: When the tface_to_mface map is not injective (i.e when we have overlapping), # the glue is not well defined. Gridap will throe an error when trying to create # the inverse map mface_to_tface. # I believe this could technically be relaxed in the future, but for now I don't see a # scenario where we would need this. function Geometry.is_change_possible(strian::PatchTriangulation,ttrian::Triangulation) return strian === ttrian end # Constructors function Geometry.Triangulation(PD::PatchDecomposition) patch_cells = Gridap.Arrays.Table(PD.patch_cells) trian = Triangulation(PD.model) return PatchTriangulation(trian,PD,patch_cells,nothing) end # By default, we return faces which are NOT patch-boundary faces. To get the patch-boundary faces, # set `reverse` to true (see docs for `get_patch_faces`). function Geometry.BoundaryTriangulation( PD::PatchDecomposition{Dr,Dc};tags="boundary",reverse=false, ) where {Dr,Dc} Df = Dc-1 model = PD.model labeling = get_face_labeling(model) is_boundary = get_face_mask(labeling,tags,Df) patch_faces = get_patch_faces(PD,Df,is_boundary;reverse) pface_to_pcell, pface_to_lcell = get_pface_to_pcell(PD,Df,patch_faces) trian = OverlappingBoundaryTriangulation(model,patch_faces.data,pface_to_lcell) return PatchTriangulation(trian,PD,patch_faces,pface_to_pcell) end function Geometry.SkeletonTriangulation(PD::PatchDecomposition{Dr,Dc}) where {Dr,Dc} Df = Dc-1 model = PD.model labeling = get_face_labeling(model) is_interior = get_face_mask(labeling,["interior"],Df) patch_faces = get_patch_faces(PD,Df,is_interior) pface_to_pcell, _ = get_pface_to_pcell(PD,Df,patch_faces) nfaces = length(patch_faces.data) plus = OverlappingBoundaryTriangulation(model,patch_faces.data,fill(Int8(1),nfaces)) minus = OverlappingBoundaryTriangulation(model,patch_faces.data,fill(Int8(2),nfaces)) trian = SkeletonTriangulation(plus,minus) return PatchTriangulation(trian,PD,patch_faces,pface_to_pcell) end # Move contributions @inline function Geometry.move_contributions(scell_to_val::AbstractArray,strian::PatchTriangulation) return move_contributions(strian.trian,scell_to_val,strian) end function Geometry.move_contributions( t::Gridap.Adaptivity.AdaptedTriangulation, scell_to_val::AbstractArray, strian::PatchTriangulation ) return move_contributions(t.trian,scell_to_val,strian) end function Geometry.move_contributions( ::BodyFittedTriangulation, scell_to_val::AbstractArray, strian::PatchTriangulation ) patch_cells = strian.patch_faces return lazy_map(Reindex(scell_to_val),patch_cells.data), strian end function Geometry.move_contributions( ::Union{<:BoundaryTriangulation,<:SkeletonTriangulation}, scell_to_val::AbstractArray, strian::PatchTriangulation ) display(ndims(eltype(scell_to_val))) return scell_to_val, strian end # Overlapping BoundaryTriangulation # # This is the situation: I do not see any show-stopper for us to have an overlapping # BoundaryTriangulation. Within the FaceToCellGlue, the array `bgface_to_lcell` is never # used for anything else than the constructor. # So in my mind nothing stops us from creating the glue from a `face_to_lcell` array instead. # # The following code does just that, and returns a regular BoundaryTriangulation. It is # mostly copied from Gridap/Geometry/BoundaryTriangulations.jl function OverlappingBoundaryTriangulation( model::DiscreteModel, face_to_bgface::AbstractVector{<:Integer}, face_to_lcell::AbstractVector{<:Integer} ) D = num_cell_dims(model) topo = get_grid_topology(model) bgface_grid = Grid(ReferenceFE{D-1},model) face_grid = view(bgface_grid,face_to_bgface) cell_grid = get_grid(model) glue = OverlappingFaceToCellGlue(topo,cell_grid,face_grid,face_to_bgface,face_to_lcell) trian = BodyFittedTriangulation(model,face_grid,face_to_bgface) return BoundaryTriangulation(trian,glue) end function OverlappingFaceToCellGlue( topo::GridTopology, cell_grid::Grid, face_grid::Grid, face_to_bgface::AbstractVector, face_to_lcell::AbstractVector ) Dc = num_cell_dims(cell_grid) Df = num_cell_dims(face_grid) bgface_to_cell = get_faces(topo,Df,Dc) bgcell_to_bgface = get_faces(topo,Dc,Df) cell_to_lface_to_pindex = Table(get_cell_permutations(topo,Df)) face_to_cell = lazy_map(Reindex(bgface_to_cell), face_to_bgface) face_to_cell = collect(Int32,lazy_map(getindex,face_to_cell,face_to_lcell)) face_to_lface = overlapped_find_local_index(face_to_bgface,face_to_cell,bgcell_to_bgface) f = (p)->fill(Int8(UNSET),num_faces(p,Df)) ctype_to_lface_to_ftype = map( f, get_reffes(cell_grid) ) face_to_ftype = get_cell_type(face_grid) cell_to_ctype = get_cell_type(cell_grid) Geometry._fill_ctype_to_lface_to_ftype!( ctype_to_lface_to_ftype, face_to_cell, face_to_lface, face_to_ftype, cell_to_ctype) Geometry.FaceToCellGlue( face_to_bgface, face_to_lcell, face_to_cell, face_to_lface, face_to_lcell, face_to_ftype, cell_to_ctype, cell_to_lface_to_pindex, ctype_to_lface_to_ftype) end function overlapped_find_local_index( c_to_a :: Vector{<:Integer}, c_to_b :: Vector{<:Integer}, b_to_lc_to_a :: Table ) c_to_lc = fill(Int8(-1),length(c_to_a)) for (c,a) in enumerate(c_to_a) b = c_to_b[c] pini = b_to_lc_to_a.ptrs[b] pend = b_to_lc_to_a.ptrs[b+1]-1 for (lc,p) in enumerate(pini:pend) if a == b_to_lc_to_a.data[p] c_to_lc[c] = Int8(lc) break end end end return c_to_lc end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
4322
""" @enum SolverVerboseLevel begin SOLVER_VERBOSE_NONE = 0 SOLVER_VERBOSE_LOW = 1 SOLVER_VERBOSE_HIGH = 2 end SolverVerboseLevel(true) = SOLVER_VERBOSE_HIGH SolverVerboseLevel(false) = SOLVER_VERBOSE_NONE """ @enum SolverVerboseLevel begin SOLVER_VERBOSE_NONE = 0 SOLVER_VERBOSE_LOW = 1 SOLVER_VERBOSE_HIGH = 2 end SolverVerboseLevel(verbose::Bool) = (verbose ? SOLVER_VERBOSE_HIGH : SOLVER_VERBOSE_NONE) """ mutable struct ConvergenceLog{T} ... end ConvergenceLog( name :: String, tols :: SolverTolerances{T}; verbose = SOLVER_VERBOSE_NONE, depth = 0 ) Standarized logging system for iterative linear solvers. # Methods: - [`reset!`](@ref) - [`init!`](@ref) - [`update!`](@ref) - [`finalize!`](@ref) - [`print_message`](@ref) """ mutable struct ConvergenceLog{T<:Real} name :: String tols :: SolverTolerances{T} num_iters :: Int residuals :: Vector{T} verbose :: SolverVerboseLevel depth :: Int end function ConvergenceLog( name :: String, tols :: SolverTolerances{T}; verbose = SOLVER_VERBOSE_NONE, depth = 0 ) where T residuals = Vector{T}(undef,tols.maxiter+1) verbose = SolverVerboseLevel(verbose) return ConvergenceLog(name,tols,0,residuals,verbose,depth) end @inline get_tabulation(log::ConvergenceLog) = get_tabulation(log,2) @inline get_tabulation(log::ConvergenceLog,n::Int) = repeat(' ', n + 2*log.depth) """ reset!(log::ConvergenceLog{T}) Resets the convergence log `log` to its initial state. """ function reset!(log::ConvergenceLog{T}) where T log.num_iters = 0 fill!(log.residuals,0.0) return log end """ init!(log::ConvergenceLog{T},r0::T) Initializes the convergence log `log` with the initial residual `r0`. """ function init!(log::ConvergenceLog{T},r0::T) where T log.num_iters = 0 log.residuals[1] = r0 if log.verbose > SOLVER_VERBOSE_LOW header = " Starting $(log.name) solver " println(get_tabulation(log,0),rpad(string(repeat('-',15),header),55,'-')) t = get_tabulation(log) msg = @sprintf("> Iteration %3i - Residuals: %.2e, %.2e ", 0, r0, 1) println(t,msg) end return finished(log.tols,log.num_iters,r0,1.0) end """ update!(log::ConvergenceLog{T},r::T) Updates the convergence log `log` with the residual `r` at the current iteration. """ function update!(log::ConvergenceLog{T},r::T) where T log.num_iters += 1 log.residuals[log.num_iters+1] = r r_rel = r / log.residuals[1] if log.verbose > SOLVER_VERBOSE_LOW t = get_tabulation(log) msg = @sprintf("> Iteration %3i - Residuals: %.2e, %.2e ", log.num_iters, r, r_rel) println(t,msg) end return finished(log.tols,log.num_iters,r,r_rel) end """ finalize!(log::ConvergenceLog{T},r::T) Finalizes the convergence log `log` with the final residual `r`. """ function finalize!(log::ConvergenceLog{T},r::T) where T r_rel = r / log.residuals[1] flag = finished_flag(log.tols,log.num_iters,r,r_rel) if log.verbose > SOLVER_VERBOSE_NONE t = get_tabulation(log,0) println(t,"Solver $(log.name) finished with reason $(flag)") msg = @sprintf("Iterations: %3i - Residuals: %.2e, %.2e ", log.num_iters, r, r_rel) println(t,msg) if log.verbose > SOLVER_VERBOSE_LOW footer = " Exiting $(log.name) solver " println(t,rpad(string(repeat('-',15),footer),55,'-')) end end return flag end """ print_message(log::ConvergenceLog{T},msg::String) Prints the message `msg` to the output stream of the convergence log `log`. """ function print_message(log::ConvergenceLog{T},msg::String) where T if log.verbose > SOLVER_VERBOSE_LOW println(get_tabulation(log),msg) end end function Base.show(io::IO,k::MIME"text/plain",log::ConvergenceLog) println(io,"ConvergenceLog[$(log.name)]") println(io," > tols: $(summary(log.tols))") println(io," > num_iter: $(log.num_iters)") println(io," > residual: $(log.residuals[log.num_iters+1])") end function Base.summary(log::ConvergenceLog) r_abs = log.residuals[log.num_iters+1] r_rel = r_abs / log.residuals[1] flag = finished_flag(log.tols,log.num_iters,r_abs,r_rel) msg = "Convergence[$(log.name)]: conv_flag=$(flag), niter=$(log.num_iters), r_abs=$(r_abs), r_rel=$(r_rel)" return msg end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
473
# LinearSolvers that depend on the non-linear solution function Gridap.Algebra.symbolic_setup(ns::Gridap.Algebra.LinearSolver,A::AbstractMatrix,x::AbstractVector) symbolic_setup(ns,A) end function Gridap.Algebra.numerical_setup(ns::Gridap.Algebra.SymbolicSetup,A::AbstractMatrix,x::AbstractVector) numerical_setup(ns,A) end function Gridap.Algebra.numerical_setup!(ns::Gridap.Algebra.NumericalSetup,A::AbstractMatrix,x::AbstractVector) numerical_setup!(ns,A) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
1421
struct SolverInfo name :: String data :: Dict{Symbol, Any} end SolverInfo(name::String) = SolverInfo(name,Dict{Symbol, Any}()) function get_solver_info(solver::Gridap.Algebra.LinearSolver) return SolverInfo(string(typeof(solver))) end function merge_info!(a::SolverInfo,b::SolverInfo;prefix=b.name) for (key,val) in b.data a.data[Symbol(prefix,key)] = val end return a end function add_info!(a::SolverInfo,key::Union{Symbol,String},val;prefix="") key = Symbol(prefix,key) a.data[key] = val end function add_convergence_info!(a::SolverInfo,log::ConvergenceLog;prefix="") prefix = string(prefix,log.name) add_info!(a,:num_iters,log.num_iters,prefix=prefix) add_info!(a,:residuals,copy(log.residuals),prefix=prefix) end function add_tolerance_info!(a::SolverInfo,tols::SolverTolerances;prefix="") add_info!(a,:maxiter,tols.maxiter,prefix=prefix) add_info!(a,:atol,tols.atol,prefix=prefix) add_info!(a,:rtol,tols.rtol,prefix=prefix) end function add_tolerance_info!(a::SolverInfo,log::ConvergenceLog;prefix="") prefix = string(prefix,log.name) add_tolerance_info!(a,log.tols,prefix=prefix) end Base.summary(info::SolverInfo) = info.name AbstractTrees.children(s::Gridap.Algebra.LinearSolver) = [] AbstractTrees.nodevalue(s::Gridap.Algebra.LinearSolver) = summary(get_solver_info(s)) function Base.show(io::IO,a::Gridap.Algebra.LinearSolver) AbstractTrees.print_tree(io,a) end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
445
module SolverInterfaces using Gridap using Gridap.Helpers using Gridap.Algebra using AbstractTrees using Printf include("GridapExtras.jl") include("SolverTolerances.jl") include("ConvergenceLogs.jl") include("SolverInfos.jl") export SolverVerboseLevel, SolverConvergenceFlag export SolverTolerances, get_solver_tolerances, set_solver_tolerances! export ConvergenceLog, init!, update!, finalize!, reset!, print_message export SolverInfo end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
3538
""" @enum SolverConvergenceFlag begin SOLVER_CONVERGED_ATOL = 0 SOLVER_CONVERGED_RTOL = 1 SOLVER_DIVERGED_MAXITER = 2 SOLVER_DIVERGED_BREAKDOWN = 3 end Convergence flags for iterative linear solvers. """ @enum SolverConvergenceFlag begin SOLVER_CONVERGED_ATOL = 0 SOLVER_CONVERGED_RTOL = 1 SOLVER_DIVERGED_MAXITER = 2 SOLVER_DIVERGED_BREAKDOWN = 3 end """ mutable struct SolverTolerances{T} ... end SolverTolerances{T}( maxiter :: Int = 1000, atol :: T = eps(T), rtol :: T = 1.e-5, dtol :: T = Inf ) Structure to check convergence conditions for iterative linear solvers. # Methods: - [`get_solver_tolerances`](@ref) - [`set_solver_tolerances!`](@ref) - [`converged`](@ref) - [`finished`](@ref) - [`finished_flag`](@ref) """ mutable struct SolverTolerances{T <: Real} maxiter :: Int atol :: T rtol :: T dtol :: T end function SolverTolerances{T}(;maxiter=1000, atol=eps(T), rtol=T(1.e-5), dtol=T(Inf)) where T return SolverTolerances{T}(maxiter, atol, rtol, dtol) end """ get_solver_tolerances(s::LinearSolver) Returns the solver tolerances of the linear solver `s`. """ get_solver_tolerances(s::Gridap.Algebra.LinearSolver) = @abstractmethod """ set_solver_tolerances!(s::LinearSolver; maxiter = 1000, atol = eps(T), rtol = T(1.e-5), dtol = T(Inf) ) Modifies tolerances of the linear solver `s`. """ function set_solver_tolerances!(s::Gridap.Algebra.LinearSolver;kwargs...) set_solver_tolerances!(get_solver_tolerances(s);kwargs...) end function set_solver_tolerances!( a::SolverTolerances{T}; maxiter = 1000, atol = eps(T), rtol = T(1.e-5), dtol = T(Inf) ) where T a.maxiter = maxiter a.atol = atol a.rtol = rtol a.dtol = dtol return a end """ finished_flag(tols::SolverTolerances,niter,e_a,e_r) :: SolverConvergenceFlag Computes the solver exit condition given - the number of iterations `niter` - the absolute error `e_a` - and the relative error `e_r`. Returns the corresponding `SolverConvergenceFlag`. """ function finished_flag(tols::SolverTolerances,niter,e_a,e_r) :: SolverConvergenceFlag if !finished(tols,niter,e_a,e_r) @warn "finished_flag() called with unfinished solver!" end if e_r < tols.rtol return SOLVER_CONVERGED_RTOL elseif e_a < tols.atol return SOLVER_CONVERGED_ATOL elseif niter >= tols.maxiter return SOLVER_DIVERGED_MAXITER else return SOLVER_DIVERGED_BREAKDOWN end end """ finished(tols::SolverTolerances,niter,e_a,e_r) :: Bool Returns `true` if the solver has finished, `false` otherwise. """ function finished(tols::SolverTolerances,niter,e_a,e_r) :: Bool return (niter >= tols.maxiter) || converged(tols,niter,e_a,e_r) end """ converged(tols::SolverTolerances,niter,e_a,e_r) :: Bool Returns `true` if the solver has converged, `false` otherwise. """ function converged(tols::SolverTolerances,niter,e_a,e_r) :: Bool return (e_r < tols.rtol) || (e_a < tols.atol) end function Base.show(io::IO,k::MIME"text/plain",t::SolverTolerances{T}) where T println(io,"SolverTolerances{$T}:") println(io," - maxiter: $(t.maxiter)") println(io," - atol: $(t.atol)") println(io," - rtol: $(t.rtol)") println(io," - dtol: $(t.dtol)") end function Base.summary(t::SolverTolerances{T}) where T return "Tolerances: maxiter=$(t.maxiter), atol=$(t.atol), rtol=$(t.rtol), dtol=$(t.dtol)" end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
492
using GridapSolvers using Test @testset "Sequential tests" begin include("MultilevelTools/seq/runtests.jl") include("LinearSolvers/seq/runtests.jl") include("NonlinearSolvers/seq/runtests.jl") include("BlockSolvers/seq/runtests.jl") include("Applications/seq/runtests.jl") end @testset "MPI tests" begin include("MultilevelTools/mpi/runtests.jl") include("LinearSolvers/mpi/runtests.jl") include("BlockSolvers/mpi/runtests.jl") include("Applications/mpi/runtests.jl") end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
3841
module DarcyGMGApplication 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.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 main(distribute,np,nc,np_per_level) parts = distribute(LinearIndices((prod(np),))) Dc = length(nc) domain = (Dc == 2) ? (0,1,0,1) : (0,1,0,1,0,1) mh = CartesianModelHierarchy(parts,np_per_level,domain,nc) model = get_model(mh,1) order = 2 qdegree = 2*(order+1) reffe_u = ReferenceFE(raviart_thomas,Float64,order-1) reffe_p = ReferenceFE(lagrangian,Float64,order-1;space=:P) u_exact(x) = (Dc==2) ? VectorValue(x[1]+x[2],-x[2]) : VectorValue(x[1]+x[2],-x[2],0.0) p_exact(x) = 2.0*x[1]-1.0 tests_u = TestFESpace(mh,reffe_u,dirichlet_tags=["boundary"]); trials_u = TrialFESpace(tests_u,[u_exact]); U, V = get_fe_space(trials_u,1), get_fe_space(tests_u,1) Q = TestFESpace(model,reffe_p;conformity=:L2) mfs = Gridap.MultiField.BlockMultiFieldStyle() X = MultiFieldFESpace([U,Q];style=mfs) Y = MultiFieldFESpace([V,Q];style=mfs) α = 1.e2 f(x) = u_exact(x) + ∇(p_exact)(x) graddiv(u,v,dΩ) = ∫(α*divergence(u)⋅divergence(v))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); 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_prolongation_operators( tests_u,qdegree;mode=:residual ) restrictions = setup_restriction_operators( tests_u,qdegree;mode=:residual,solver=IS_ConjugateGradientSolver(;reltol=1.e-6) ) gmg = GMGLinearSolver( mh,trials_u,tests_u,biforms, prolongations,restrictions, pre_smoothers=smoothers, post_smoothers=smoothers, coarsest_solver=LUSolver(), maxiter=3,mode=:preconditioner,verbose=i_am_main(parts) ) solver_u = gmg solver_p = CGSolver(JacobiLinearSolver();maxiter=20,atol=1e-14,rtol=1.e-6,verbose=i_am_main(parts)) solver_p.log.depth = 2 bblocks = [LinearSystemBlock() LinearSystemBlock(); LinearSystemBlock() BiformBlock((p,q) -> ∫(-1.0/α*p*q)dΩ,Q,Q)] 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-10,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) r = allocate_in_range(A) mul!(r,A,x) r .-= b @test norm(r) < 1.e-5 end end # module
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
4358
# # Incompressible Navier-Stokes equations in a 2D/3D cavity # # This example solves the incompressible Stokes equations, given by # # ```math # \begin{align*} # -\Delta u + \text{R}_e (u \nabla) u - \nabla p &= f \quad \text{in} \quad \Omega, \\ # \nabla \cdot u &= 0 \quad \text{in} \quad \Omega, \\ # u &= \hat{x} \quad \text{in} \quad \Gamma_\text{top} \subset \partial \Omega, \\ # u &= 0 \quad \text{in} \quad \partial \Omega \backslash \Gamma_\text{top} \\ # \end{align*} # ``` # # where $\Omega = [0,1]^d$. # # We use a mixed finite-element scheme, with $Q_k \times P_{k-1}^{-}$ elements for the velocity-pressure pair. # # To solve the linear system, we use a FGMRES solver preconditioned by a block-triangular # Shur-complement-based preconditioner. We use an Augmented Lagrangian approach to # get a better approximation of the Schur complement. Details for this preconditoner can be # found in [Benzi and Olshanskii (2006)](https://epubs.siam.org/doi/10.1137/050646421). # # The velocity block is solved directly using an exact solver. module NavierStokesApplication 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, BiformBlock, BlockTriangularSolver function add_labels_2d!(labels) add_tag_from_tags!(labels,"top",[6]) add_tag_from_tags!(labels,"walls",[1,2,3,4,5,7,8]) end function add_labels_3d!(labels) add_tag_from_tags!(labels,"top",[22]) add_tag_from_tags!(labels,"walls",[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,26]) end function main(distribute,np,nc) parts = distribute(LinearIndices((prod(np),))) 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)) 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) Re = 10.0 ν = 1/Re α = 1.e2 f = (Dc==2) ? VectorValue(0.0,0.0) : VectorValue(0.0,0.0,0.0) Π_Qh = LocalProjectionMap(divergence,Q,qdegree) graddiv(u,v,dΩ) = ∫(α*(∇⋅v)⋅Π_Qh(u))dΩ conv(u,∇u) = (∇u')⋅u dconv(du,∇du,u,∇u) = conv(u,∇du)+conv(du,∇u) c(u,v,dΩ) = ∫(v⊙(conv∘(u,∇(u))))dΩ dc(u,du,dv,dΩ) = ∫(dv⊙(dconv∘(du,∇(du),u,∇(u))))dΩ lap(u,v,dΩ) = ∫(ν*∇(v)⊙∇(u))dΩ rhs(v,dΩ) = ∫(v⋅f)dΩ jac_u(u,du,dv,dΩ) = lap(du,dv,dΩ) + dc(u,du,dv,dΩ) + graddiv(du,dv,dΩ) jac((u,p),(du,dp),(dv,dq),dΩ) = jac_u(u,du,dv,dΩ) - ∫(divergence(dv)*dp)dΩ - ∫(divergence(du)*dq)dΩ res_u(u,v,dΩ) = lap(u,v,dΩ) + c(u,v,dΩ) + graddiv(u,v,dΩ) - rhs(v,dΩ) res((u,p),(v,q),dΩ) = res_u(u,v,dΩ) - ∫(divergence(v)*p)dΩ - ∫(divergence(u)*q)dΩ Ω = Triangulation(model) dΩ = Measure(Ω,qdegree) jac_h(x,dx,dy) = jac(x,dx,dy,dΩ) res_h(x,dy) = res(x,dy,dΩ) op = FEOperator(res_h,jac_h,X,Y) solver_u = LUSolver() solver_p = CGSolver(JacobiLinearSolver();maxiter=20,atol=1e-14,rtol=1.e-6,verbose=i_am_main(parts)) solver_p.log.depth = 4 bblocks = [NonlinearSystemBlock() LinearSystemBlock(); LinearSystemBlock() BiformBlock((p,q) -> ∫(-(1.0/α)*p*q)dΩ,Q,Q)] coeffs = [1.0 1.0; 0.0 1.0] P = BlockTriangularSolver(bblocks,[solver_u,solver_p],coeffs,:upper) solver = FGMRESSolver(20,P;atol=1e-11,rtol=1.e-8,verbose=i_am_main(parts)) solver.log.depth = 2 nlsolver = NewtonSolver(solver;maxiter=20,atol=1e-10,rtol=1.e-12,verbose=i_am_main(parts)) xh = solve(nlsolver,op); @test true end end # module
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
6282
# # Incompressible Navier-Stokes equations in a 2D/3D cavity, using GMG. # # This example solves the incompressible Stokes equations, given by # # ```math # \begin{align*} # -\Delta u + \text{R}_e (u \nabla) u - \nabla p &= f \quad \text{in} \quad \Omega, \\ # \nabla \cdot u &= 0 \quad \text{in} \quad \Omega, \\ # u &= \hat{x} \quad \text{in} \quad \Gamma_\text{top} \subset \partial \Omega, \\ # u &= 0 \quad \text{in} \quad \partial \Omega \backslash \Gamma_\text{top} \\ # \end{align*} # ``` # # where $\Omega = [0,1]^d$. # # We use a mixed finite-element scheme, with $Q_k \times P_{k-1}^{-}$ elements for the velocity-pressure pair. # # To solve the linear system, we use a FGMRES solver preconditioned by a block-triangular # Shur-complement-based preconditioner. We use an Augmented Lagrangian approach to # get a better approximation of the Schur complement. Details for this preconditoner can be # found in [Benzi and Olshanskii (2006)](https://epubs.siam.org/doi/10.1137/050646421). # # The velocity block is solved using a Geometric Multigrid (GMG) solver. Due to the kernel # introduced by the Augmented-Lagrangian operator, we require special smoothers and prolongation/restriction # operators. See [Schoberl (1999)](https://link.springer.com/article/10.1007/s002110050465) for more details. module NavierStokesGMGApplication 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 using GridapSolvers.PatchBasedSmoothers, GridapSolvers.NonlinearSolvers using GridapSolvers.BlockSolvers: NonlinearSystemBlock, LinearSystemBlock, BiformBlock, BlockTriangularSolver function get_patch_smoothers(mh,tests,biform,patch_decompositions,qdegree;is_nonlinear=false) 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,du,dv) -> biform(u,du,dv,dΩ) patch_smoother = PatchBasedLinearSolver(ap,Ph,Vh;is_nonlinear) return RichardsonSmoother(patch_smoother,10,0.2) end return smoothers end function get_trilinear_form(mh_lev,triform,qdegree) model = get_model(mh_lev) Ω = Triangulation(model) dΩ = Measure(Ω,qdegree) return (u,du,dv) -> triform(u,du,dv,dΩ) end function add_labels_2d!(labels) add_tag_from_tags!(labels,"top",[6]) add_tag_from_tags!(labels,"walls",[1,2,3,4,5,7,8]) end function add_labels_3d!(labels) add_tag_from_tags!(labels,"top",[22]) add_tag_from_tags!(labels,"walls",[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,26]) end function main(distribute,np,nc,np_per_level) parts = distribute(LinearIndices((prod(np),))) Dc = length(nc) 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_per_level,domain,nc;add_labels! = add_labels!) model = get_model(mh,1) 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) tests_u = TestFESpace(mh,reffe_u,dirichlet_tags=["walls","top"]); trials_u = TrialFESpace(tests_u,[u_walls,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) Re = 10.0 ν = 1/Re α = 1.e2 f = (Dc==2) ? VectorValue(1.0,1.0) : VectorValue(1.0,1.0,1.0) Π_Qh = LocalProjectionMap(divergence,reffe_p,qdegree) graddiv(u,v,dΩ) = ∫(α*(∇⋅v)⋅Π_Qh(u))dΩ conv(u,∇u) = (∇u')⋅u dconv(du,∇du,u,∇u) = conv(u,∇du)+conv(du,∇u) c(u,v,dΩ) = ∫(v⊙(conv∘(u,∇(u))))dΩ dc(u,du,dv,dΩ) = ∫(dv⊙(dconv∘(du,∇(du),u,∇(u))))dΩ lap(u,v,dΩ) = ∫(ν*∇(v)⊙∇(u))dΩ rhs(v,dΩ) = ∫(v⋅f)dΩ jac_u(u,du,dv,dΩ) = lap(du,dv,dΩ) + dc(u,du,dv,dΩ) + graddiv(du,dv,dΩ) jac((u,p),(du,dp),(dv,dq),dΩ) = jac_u(u,du,dv,dΩ) - ∫(divergence(dv)*dp)dΩ - ∫(divergence(du)*dq)dΩ res_u(u,v,dΩ) = lap(u,v,dΩ) + c(u,v,dΩ) + graddiv(u,v,dΩ) - rhs(v,dΩ) res((u,p),(v,q),dΩ) = res_u(u,v,dΩ) - ∫(divergence(v)*p)dΩ - ∫(divergence(u)*q)dΩ Ω = Triangulation(model) dΩ = Measure(Ω,qdegree) jac_h(x,dx,dy) = jac(x,dx,dy,dΩ) res_h(x,dy) = res(x,dy,dΩ) op = FEOperator(res_h,jac_h,X,Y) biforms = map(mhl -> get_trilinear_form(mhl,jac_u,qdegree),mh) patch_decompositions = PatchDecomposition(mh) smoothers = get_patch_smoothers( mh,trials_u,jac_u,patch_decompositions,qdegree;is_nonlinear=true ) prolongations = setup_patch_prolongation_operators( tests_u,jac_u,graddiv,qdegree;is_nonlinear=true ) restrictions = setup_patch_restriction_operators( tests_u,prolongations,graddiv,qdegree;solver=IS_ConjugateGradientSolver(;reltol=1.e-6) ) gmg = GMGLinearSolver( mh,trials_u,tests_u,biforms, prolongations,restrictions, pre_smoothers=smoothers, post_smoothers=smoothers, coarsest_solver=LUSolver(), maxiter=2,mode=:preconditioner,verbose=i_am_main(parts),is_nonlinear=true ) 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 = 3 solver_p.log.depth = 3 bblocks = [NonlinearSystemBlock([1]) LinearSystemBlock(); LinearSystemBlock() BiformBlock((p,q) -> ∫(-(1.0/α)*p*q)dΩ,Q,Q)] coeffs = [1.0 1.0; 0.0 1.0] P = BlockTriangularSolver(bblocks,[solver_u,solver_p],coeffs,:upper) solver = FGMRESSolver(20,P;atol=1e-11,rtol=1.e-8,verbose=i_am_main(parts)) solver.log.depth = 2 nlsolver = NewtonSolver(solver;maxiter=20,atol=1e-10,rtol=1.e-12,verbose=i_am_main(parts)) xh = solve(nlsolver,op) @test true end end # module
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
3909
# # Incompressible Stokes equations in a 2D/3D cavity # # This example solves the incompressible Stokes equations, given by # # ```math # \begin{align*} # -\Delta u - \nabla p &= f \quad \text{in} \quad \Omega, \\ # \nabla \cdot u &= 0 \quad \text{in} \quad \Omega, \\ # u &= \hat{x} \quad \text{in} \quad \Gamma_\text{top} \subset \partial \Omega, \\ # u &= 0 \quad \text{in} \quad \partial \Omega \backslash \Gamma_\text{top} \\ # \end{align*} # ``` # # where $\Omega = [0,1]^d$. # # We use a mixed finite-element scheme, with $Q_k \times P_{k-1}^{-}$ elements for the velocity-pressure pair. # # To solve the linear system, we use a FGMRES solver preconditioned by a block-triangular # Shur-complement-based preconditioner. We use an Augmented Lagrangian approach to # get a better approximation of the Schur complement. Details for this preconditoner can be # found in [Benzi and Olshanskii (2006)](https://epubs.siam.org/doi/10.1137/050646421). # # The velocity block is solved directly using an exact solver. module StokesApplication 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 using GridapSolvers.BlockSolvers: LinearSystemBlock, BiformBlock, BlockTriangularSolver function add_labels_2d!(labels) add_tag_from_tags!(labels,"top",[6]) add_tag_from_tags!(labels,"walls",[1,2,3,4,5,7,8]) end function add_labels_3d!(labels) add_tag_from_tags!(labels,"top",[22]) add_tag_from_tags!(labels,"walls",[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,26]) end function main(distribute,np,nc) parts = distribute(LinearIndices((prod(np),))) 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)) 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) α = 1.e2 f = (Dc==2) ? VectorValue(1.0,1.0) : VectorValue(1.0,1.0,1.0) Π_Qh = LocalProjectionMap(divergence,Q,qdegree) graddiv(u,v,dΩ) = ∫(α*(∇⋅v)⋅Π_Qh(u))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=i_am_main(parts)) solver_p.log.depth = 2 bblocks = [LinearSystemBlock() LinearSystemBlock(); LinearSystemBlock() BiformBlock((p,q) -> ∫(-(1.0/α)*p*q)dΩ,Q,Q)] coeffs = [1.0 1.0; 0.0 1.0] P = BlockTriangularSolver(bblocks,[solver_u,solver_p],coeffs,:upper) solver = FGMRESSolver(20,P;atol=1e-10,rtol=1.e-12,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) r = allocate_in_range(A) mul!(r,A,x) r .-= b @test norm(r) < 1.e-7 end end # module
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
5799
# # Incompressible Stokes equations in a 2D/3D cavity, using GMG. # # This example solves the incompressible Stokes equations, given by # # ```math # \begin{align*} # -\Delta u - \nabla p &= f \quad \text{in} \quad \Omega, \\ # \nabla \cdot u &= 0 \quad \text{in} \quad \Omega, \\ # u &= \hat{x} \quad \text{in} \quad \Gamma_\text{top} \subset \partial \Omega, \\ # u &= 0 \quad \text{in} \quad \partial \Omega \backslash \Gamma_\text{top} \\ # \end{align*} # ``` # # where $\Omega = [0,1]^d$. # # We use a mixed finite-element scheme, with $Q_k \times P_{k-1}^{-}$ elements for the velocity-pressure pair. # # To solve the linear system, we use a FGMRES solver preconditioned by a block-triangular # Shur-complement-based preconditioner. We use an Augmented Lagrangian approach to # get a better approximation of the Schur complement. Details for this preconditoner can be # found in [Benzi and Olshanskii (2006)](https://epubs.siam.org/doi/10.1137/050646421). # # The velocity block is solved using a Geometric Multigrid (GMG) solver. Due to the kernel # introduced by the Augmented-Lagrangian operator, we require special smoothers and prolongation/restriction # operators. See [Schoberl (1999)](https://link.springer.com/article/10.1007/s002110050465) for more details. module StokesGMGApplication 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",[6]) add_tag_from_tags!(labels,"walls",[1,2,3,4,5,7,8]) end function add_labels_3d!(labels) add_tag_from_tags!(labels,"top",[22]) add_tag_from_tags!(labels,"walls",[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,26]) end function main(distribute,np,nc,np_per_level) parts = distribute(LinearIndices((prod(np),))) Dc = length(nc) 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_per_level,domain,nc;add_labels! = add_labels!) model = get_model(mh,1) 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) tests_u = TestFESpace(mh,reffe_u,dirichlet_tags=["walls","top"]); trials_u = TrialFESpace(tests_u,[u_walls,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) α = 1.e2 f = (Dc==2) ? VectorValue(1.0,1.0) : VectorValue(1.0,1.0,1.0) Π_Qh = LocalProjectionMap(divergence,reffe_p,qdegree) graddiv(u,v,dΩ) = ∫(α*(∇⋅v)⋅Π_Qh(u))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); 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=CGSolver(JacobiLinearSolver()) ) 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_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-10,rtol=1.e-12,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 @test norm(r) < 1.e-7 end end # module
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
437
module StokesGMGApplicationMPI using MPI, PartitionedArrays include("../DarcyGMG.jl") with_mpi() do distribute DarcyGMGApplication.main(distribute,4,(8,8),[(2,2),(1,1)]) DarcyGMGApplication.main(distribute,4,(8,8),[(2,2),(2,1)]) DarcyGMGApplication.main(distribute,4,(8,8),[(2,2),(2,2)]) DarcyGMGApplication.main(distribute,4,(4,4,4),[(2,2,1),(1,1,1)]) DarcyGMGApplication.main(distribute,4,(4,4,4),[(2,2,1),(2,2,1)]) end end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
241
module NavierStokesApplicationMPI using MPI, PartitionedArrays include("../NavierStokes.jl") with_mpi() do distribute NavierStokesApplication.main(distribute,(2,2),(8,8)) NavierStokesApplication.main(distribute,(2,2,1),(4,4,4)) end end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
417
module NavierStokesGMGApplicationMPI using MPI, PartitionedArrays include("../NavierStokesGMG.jl") with_mpi() do distribute NavierStokesGMGApplication.main(distribute,4,(8,8),[(2,2),(1,1)]) NavierStokesGMGApplication.main(distribute,4,(8,8),[(2,2),(2,2)]) NavierStokesGMGApplication.main(distribute,4,(4,4,4),[(2,2,1),(1,1,1)]) NavierStokesGMGApplication.main(distribute,4,(4,4,4),[(2,2,1),(2,2,1)]) end end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
217
module StokesApplicationMPI using MPI, PartitionedArrays include("../Stokes.jl") with_mpi() do distribute StokesApplication.main(distribute,(2,2),(8,8)) StokesApplication.main(distribute,(2,2,1),(4,4,4)) end end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
579
module StokesGMGApplicationMPI using MPI, PartitionedArrays include("../StokesGMG.jl") with_mpi() do distribute StokesGMGApplication.main(distribute,4,(8,8),[(2,2),(1,1)]) StokesGMGApplication.main(distribute,4,(8,8),[(2,2),(2,1)]) StokesGMGApplication.main(distribute,4,(8,8),[(2,2),(2,2)]) StokesGMGApplication.main(distribute,4,(4,4),[(2,2),(2,1),(1,1)]) StokesGMGApplication.main(distribute,4,(4,4,4),[(2,2,1),(1,1,1)]) StokesGMGApplication.main(distribute,4,(4,4,4),[(2,2,1),(2,1,1)]) StokesGMGApplication.main(distribute,4,(4,4,4),[(2,2,1),(2,2,1)]) end end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
456
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
300
module NavierStokesApplicationSequential using PartitionedArrays include("../NavierStokes.jl") with_debug() do distribute NavierStokesApplication.main(distribute,(1,1),(8,8)) NavierStokesApplication.main(distribute,(2,2),(8,8)) NavierStokesApplication.main(distribute,(2,2,1),(4,4,4)) end end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
270
module StokesApplicationSequential using PartitionedArrays include("../Stokes.jl") with_debug() do distribute StokesApplication.main(distribute,(1,1),(8,8)) StokesApplication.main(distribute,(2,2),(8,8)) StokesApplication.main(distribute,(2,2,1),(4,4,4)) end end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
71
using Test @testset "Stokes equation" begin include("Stokes.jl") end
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git
[ "MIT" ]
0.4.1
2b09db401471a212fb06a9c2577f4a0be77039c2
code
1763
module BlockDiagonalSolversTests using Test using BlockArrays, LinearAlgebra using Gridap, Gridap.MultiField, Gridap.Algebra using PartitionedArrays, GridapDistributed using GridapSolvers using GridapSolvers.LinearSolvers 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)*dΩ l((v1,v2)) = ∫(sol⋅v1 - sol⋅v2)*dΩ op = AffineFEOperator(a,l,Y,Y) A, b = get_matrix(op), get_vector(op); s = GMRESSolver(10;rtol=1.e-10) ss = symbolic_setup(s,A) ns = numerical_setup(ss,A) x = allocate_in_domain(A); fill!(x,0.0) solve!(x,ns,b) # 1) From system blocks s1 = BlockDiagonalSolver([LUSolver(),LUSolver()]) 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) @test norm(x1-x) < 1.e-8 # 2) From matrix blocks s2 = BlockDiagonalSolver([A[Block(1,1)],A[Block(2,2)]],[LUSolver(),LUSolver()]) 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) @test norm(x2-x) < 1.e-8 # 3) From weakform blocks aii = (u,v) -> ∫(u⋅v)*dΩ s3 = BlockDiagonalSolver([aii,aii],[V,V],[V,V],[LUSolver(),LUSolver()]) ss3 = symbolic_setup(s3,A) ns3 = numerical_setup(ss3,A) numerical_setup!(ns3,A) x3 = allocate_in_domain(A); fill!(x3,0.0) solve!(x3,ns3,b) @test norm(x3-x) < 1.e-8 end end # module
GridapSolvers
https://github.com/gridap/GridapSolvers.jl.git