-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathConstraintHandler.jl
1733 lines (1542 loc) · 70.1 KB
/
ConstraintHandler.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# abstract type Constraint end
"""
Dirichlet(u::Symbol, ∂Ω::AbstractVecOrSet, f::Function, components=nothing)
Create a Dirichlet boundary condition on `u` on the `∂Ω` part of
the boundary. `f` is a function of the form `f(x)` or `f(x, t)`
where `x` is the spatial coordinate and `t` is the current time,
and returns the prescribed value. `components` specify the components
of `u` that are prescribed by this condition. By default all components
of `u` are prescribed.
The set, `∂Ω`, can be an `AbstractSet` or `AbstractVector` with elements of
type [`FacetIndex`](@ref), [`FaceIndex`](@ref), [`EdgeIndex`](@ref), [`VertexIndex`](@ref),
or `Int`. For most cases, the element type is `FacetIndex`, as shown below.
To constrain a single point, using `VertexIndex` is recommended, but it is also possible
to constrain a specific nodes by giving the node numbers via `Int` elements.
To constrain e.g. an edge in 3d `EdgeIndex` elements can be given.
For example, here we create a
Dirichlet condition for the `:u` field, on the facetset called
`∂Ω` and the value given by the `sin` function:
*Examples*
```jldoctest
# Obtain the facetset from the grid
∂Ω = getfacetset(grid, "boundary-1")
# Prescribe scalar field :s on ∂Ω to sin(t)
dbc = Dirichlet(:s, ∂Ω, (x, t) -> sin(t))
# Prescribe all components of vector field :v on ∂Ω to 0
dbc = Dirichlet(:v, ∂Ω, x -> 0 * x)
# Prescribe component 2 and 3 of vector field :v on ∂Ω to [sin(t), cos(t)]
dbc = Dirichlet(:v, ∂Ω, (x, t) -> [sin(t), cos(t)], [2, 3])
```
`Dirichlet` boundary conditions are added to a [`ConstraintHandler`](@ref)
which applies the condition via [`apply!`](@ref) and/or [`apply_zero!`](@ref).
"""
struct Dirichlet # <: Constraint
f::Function # f(x) or f(x,t) -> value(s)
facets::OrderedSet{T} where T <: Union{Int, FacetIndex, FaceIndex, EdgeIndex, VertexIndex}
field_name::Symbol
components::Vector{Int} # components of the field
local_facet_dofs::Vector{Int}
local_facet_dofs_offset::Vector{Int}
end
function Dirichlet(field_name::Symbol, facets::AbstractVecOrSet, f::Function, components=nothing)
return Dirichlet(f, convert_to_orderedset(facets), field_name, __to_components(components), Int[], Int[])
end
# components=nothing is default and means that all components should be constrained
# but since number of components isn't known here it will be populated in add!
__to_components(::Nothing) = Int[]
function __to_components(c)
components = convert(Vector{Int}, vec(collect(Int, c)))
isempty(components) && error("components are empty: $c")
issorted(components) || error("components not sorted: $c")
allunique(components) || error("components not unique: $c")
return components
end
const DofCoefficients{T} = Vector{Pair{Int,T}}
"""
AffineConstraint(constrained_dof::Int, entries::Vector{Pair{Int,T}}, b::T) where T
Define an affine/linear constraint to constrain one degree of freedom, `u[i]`,
such that `u[i] = ∑(u[j] * a[j]) + b`,
where `i=constrained_dof` and each element in `entries` are `j => a[j]`
"""
struct AffineConstraint{T}
constrained_dof::Int
entries::DofCoefficients{T} # masterdofs and factors
b::T # inhomogeneity
end
"""
ConstraintHandler([T=Float64], dh::AbstractDofHandler)
A collection of constraints associated with the dof handler `dh`.
`T` is the numeric type for stored values.
"""
mutable struct ConstraintHandler{DH<:AbstractDofHandler,T}
const dbcs::Vector{Dirichlet}
const prescribed_dofs::Vector{Int}
const free_dofs::Vector{Int}
const inhomogeneities::Vector{T}
# Store the original constant inhomogeneities for affine constraints used to compute
# "effective" inhomogeneities in `update!` and then stored in .inhomogeneities.
const affine_inhomogeneities::Vector{Union{Nothing,T}}
# `nothing` for pure DBC constraint, otherwise affine constraint
const dofcoefficients::Vector{Union{Nothing, DofCoefficients{T}}}
# global dof -> index into dofs and inhomogeneities and dofcoefficients
const dofmapping::Dict{Int,Int}
const bcvalues::Vector{BCValues{T}}
const dh::DH
closed::Bool
end
ConstraintHandler(dh::AbstractDofHandler) = ConstraintHandler(Float64, dh)
function ConstraintHandler(::Type{T}, dh::AbstractDofHandler) where T <: Number
@assert isclosed(dh)
ConstraintHandler(
Dirichlet[], Int[], Int[], T[], Union{Nothing,T}[], Union{Nothing,DofCoefficients{T}}[],
Dict{Int,Int}(), BCValues{T}[], dh, false,
)
end
"""
RHSData
Stores the constrained columns and mean of the diagonal of stiffness matrix `A`.
"""
struct RHSData{T}
m::T
constrained_columns::SparseMatrixCSC{T, Int}
end
"""
get_rhs_data(ch::ConstraintHandler, A::SparseMatrixCSC) -> RHSData
Returns the needed [`RHSData`](@ref) for [`apply_rhs!`](@ref).
This must be used when the same stiffness matrix is reused for multiple steps,
for example when timestepping, with different non-homogeneouos Dirichlet boundary
conditions.
"""
function get_rhs_data(ch::ConstraintHandler, A::SparseMatrixCSC)
m = meandiag(A)
constrained_columns = A[:, ch.prescribed_dofs]
return RHSData(m, constrained_columns)
end
"""
apply_rhs!(data::RHSData, f::AbstractVector, ch::ConstraintHandler, applyzero::Bool=false)
Applies the boundary condition to the right-hand-side vector without modifying the stiffness matrix.
See also: [`get_rhs_data`](@ref).
"""
function apply_rhs!(data::RHSData, f::AbstractVector, ch::ConstraintHandler, applyzero::Bool=false)
K = data.constrained_columns
@assert length(f) == size(K, 1)
@boundscheck checkbounds(f, ch.prescribed_dofs)
m = data.m
# TODO: Can the loops be combined or does the order matter?
@inbounds for i in 1:length(ch.inhomogeneities)
v = ch.inhomogeneities[i]
if !applyzero && v != 0
for j in nzrange(K, i)
f[K.rowval[j]] -= v * K.nzval[j]
end
end
end
@inbounds for (i, pdof) in pairs(ch.prescribed_dofs)
dofcoef = ch.dofcoefficients[i]
b = ch.inhomogeneities[i]
if dofcoef !== nothing # if affine constraint
for (d, v) in dofcoef
f[d] += f[pdof] * v
end
end
bz = applyzero ? zero(eltype(f)) : b
f[pdof] = bz * m
end
end
function Base.show(io::IO, ::MIME"text/plain", ch::ConstraintHandler)
println(io, "ConstraintHandler:")
if !isclosed(ch)
print(io, " Not closed!")
else
print(io, " BCs:")
for dbc in ch.dbcs
print(io, "\n ", "Field: ", dbc.field_name, ", ", "Components: ", dbc.components)
end
end
end
isclosed(ch::ConstraintHandler) = ch.closed
free_dofs(ch::ConstraintHandler) = ch.free_dofs
prescribed_dofs(ch::ConstraintHandler) = ch.prescribed_dofs
# Equivalent to `copy!(out, setdiff(1:n_entries, diff))`, but requires that
# `issorted(diff)` and that `1 ≤ diff[1] ≤ diff[end] ≤ n_entries`
function _sorted_setdiff!(out::Vector{Int}, n_entries::Int, diff::Vector{Int})
n_diff = length(diff)
resize!(out, n_entries - n_diff)
diff_ind = out_ind = 1
for i in 1:n_entries
if diff_ind ≤ n_diff && i == diff[diff_ind]
diff_ind += 1
else
out[out_ind] = i
out_ind += 1
end
end
return out
end
"""
close!(ch::ConstraintHandler)
Close and finalize the `ConstraintHandler`.
"""
function close!(ch::ConstraintHandler)
@assert(!isclosed(ch))
@assert( allunique(ch.prescribed_dofs) )
I = sortperm(ch.prescribed_dofs)
ch.prescribed_dofs .= ch.prescribed_dofs[I]
ch.inhomogeneities .= ch.inhomogeneities[I]
ch.affine_inhomogeneities .= ch.affine_inhomogeneities[I]
ch.dofcoefficients .= ch.dofcoefficients[I]
_sorted_setdiff!(ch.free_dofs, ndofs(ch.dh), ch.prescribed_dofs)
for i in 1:length(ch.prescribed_dofs)
ch.dofmapping[ch.prescribed_dofs[i]] = i
end
# TODO: Store index for each affine constraint?
# affine_mapping = Dict{Int,Int}(pdof => i for (i, pdof) in pairs(cd.prescribed_dofs) if ch.dofcoefficients[i] !== nothing )
# TODO:
# Do a bunch of checks to see if the affine constraints are linearly indepented etc.
# If they are not, it is possible to automatically reformulate the constraints
# such that they become independent. However, at this point, it is left to
# the user to assure this.
# Basic verification of constraints:
# - `add_prescribed_dof` make sure all prescribed dofs are unique by overwriting the old
# constraint when adding a new (TODO: Might change in the future, see comment in
# `add_prescribed_dof`.)
# - We allow affine constraints to have prescribed dofs as master dofs iff those master
# dofs are constrained with just an inhomogeneity (i.e. DBC). The effective
# inhomogeneity is computed in `update!`.
for coeffs in ch.dofcoefficients
coeffs === nothing && continue
for (d, _) in coeffs
i = get(ch.dofmapping, d, 0)
i == 0 && continue
icoeffs = ch.dofcoefficients[i]
if !(icoeffs === nothing || isempty(icoeffs))
error("nested affine constraints currently not supported")
end
end
end
ch.closed = true
# Compute the prescribed values by calling update!: This should be cheap, and for the
# common case where constraints does not depend on time it is annoying and easy to
# forget to call this on the outside.
update!(ch)
return ch
end
"""
add!(ch::ConstraintHandler, ac::AffineConstraint)
Add the `AffineConstraint` to the `ConstraintHandler`.
"""
function add!(ch::ConstraintHandler, ac::AffineConstraint)
# TODO: Would be nice to pass nothing if ac.entries is empty, but then we lose the fact
# that this constraint is an AffineConstraint which is currently needed in update!
# in order to not update inhomogeneities for affine constraints
add_prescribed_dof!(ch, ac.constrained_dof, ac.b, #=isempty(ac.entries) ? nothing : =# ac.entries)
end
"""
add_prescribed_dof!(ch, constrained_dof::Int, inhomogeneity, dofcoefficients=nothing)
Add a constrained dof directly to the `ConstraintHandler`.
This function checks if the `constrained_dof` is already constrained, and overrides the old
constraint if true.
"""
function add_prescribed_dof!(ch::ConstraintHandler, constrained_dof::Int, inhomogeneity, dofcoefficients=nothing)
@assert(!isclosed(ch))
i = get(ch.dofmapping, constrained_dof, 0)
if i != 0
@debug @warn "dof $i already prescribed, overriding the old constraint"
ch.prescribed_dofs[i] = constrained_dof
ch.inhomogeneities[i] = inhomogeneity
ch.affine_inhomogeneities[i] = dofcoefficients === nothing ? nothing : inhomogeneity
ch.dofcoefficients[i] = dofcoefficients
else
N = length(ch.dofmapping)
push!(ch.prescribed_dofs, constrained_dof)
push!(ch.inhomogeneities, inhomogeneity)
push!(ch.affine_inhomogeneities, dofcoefficients === nothing ? nothing : inhomogeneity)
push!(ch.dofcoefficients, dofcoefficients)
ch.dofmapping[constrained_dof] = N + 1
end
return ch
end
# Dirichlet on (facet|face|edge|vertex)set
function _add!(ch::ConstraintHandler, dbc::Dirichlet, bcfacets::AbstractVecOrSet{Index}, interpolation::Interpolation, field_dim::Int, offset::Int, bcvalue::BCValues, _) where {Index<:BoundaryIndex}
local_facet_dofs, local_facet_dofs_offset =
_local_facet_dofs_for_bc(interpolation, field_dim, dbc.components, offset, dirichlet_boundarydof_indices(eltype(bcfacets)))
copy!(dbc.local_facet_dofs, local_facet_dofs)
copy!(dbc.local_facet_dofs_offset, local_facet_dofs_offset)
# loop over all the faces in the set and add the global dofs to `constrained_dofs`
constrained_dofs = Int[]
cc = CellCache(ch.dh, UpdateFlags(; nodes=false, coords=false, dofs=true))
for (cellidx, facetidx) in bcfacets
reinit!(cc, cellidx)
r = local_facet_dofs_offset[facetidx]:(local_facet_dofs_offset[facetidx+1]-1)
append!(constrained_dofs, cc.dofs[local_facet_dofs[r]]) # TODO: for-loop over r and simply push! to ch.prescribed_dofs
@debug println("adding dofs $(cc.dofs[local_facet_dofs[r]]) to dbc")
end
# save it to the ConstraintHandler
push!(ch.dbcs, dbc)
push!(ch.bcvalues, bcvalue)
for d in constrained_dofs
add_prescribed_dof!(ch, d, NaN, nothing)
end
return ch
end
# Calculate which local dof index live on each facet:
# facet `i` have dofs `local_facet_dofs[local_facet_dofs_offset[i]:local_facet_dofs_offset[i+1]-1]
function _local_facet_dofs_for_bc(interpolation, field_dim, components, offset, boundaryfunc::F=dirichlet_facetdof_indices) where F
@assert issorted(components)
local_facet_dofs = Int[]
local_facet_dofs_offset = Int[1]
for (_, facet) in enumerate(boundaryfunc(interpolation))
for fdof in facet, d in 1:field_dim
if d in components
push!(local_facet_dofs, (fdof-1)*field_dim + d + offset)
end
end
push!(local_facet_dofs_offset, length(local_facet_dofs) + 1)
end
return local_facet_dofs, local_facet_dofs_offset
end
function _add!(ch::ConstraintHandler, dbc::Dirichlet, bcnodes::AbstractVecOrSet{Int}, interpolation::Interpolation, field_dim::Int, offset::Int, bcvalue::BCValues, cellset::AbstractVecOrSet{Int}=OrderedSet{Int}(1:getncells(get_grid(ch.dh))))
grid = get_grid(ch.dh)
if interpolation !== geometric_interpolation(getcelltype(grid, first(cellset)))
@warn("adding constraint to nodeset is not recommended for sub/super-parametric approximations.")
end
ncomps = length(dbc.components)
nnodes = getnnodes(grid)
interpol_points = getnbasefunctions(interpolation)
node_dofs = zeros(Int, ncomps, nnodes)
visited = falses(nnodes)
for cell in CellIterator(ch.dh, cellset) # only go over cells that belong to current SubDofHandler
for idx in 1:min(interpol_points, length(cell.nodes))
node = cell.nodes[idx]
if !visited[node]
noderange = (offset + (idx-1)*field_dim + 1):(offset + idx*field_dim) # the dofs in this node
for (i,c) in enumerate(dbc.components)
node_dofs[i,node] = cell.dofs[noderange[c]]
@debug println("adding dof $(cell.dofs[noderange[c]]) to node_dofs")
end
visited[node] = true
end
end
end
constrained_dofs = Int[]
sizehint!(constrained_dofs, ncomps*length(bcnodes))
sizehint!(dbc.local_facet_dofs, length(bcnodes))
for node in bcnodes
if !visited[node]
# either the node belongs to another field handler or it does not have dofs in the constrained field
continue
end
for i in 1:ncomps
push!(constrained_dofs, node_dofs[i,node])
end
push!(dbc.local_facet_dofs, node) # use this field to store the node idx for each node
end
# save it to the ConstraintHandler
copy!(dbc.local_facet_dofs_offset, constrained_dofs) # use this field to store the global dofs
push!(ch.dbcs, dbc)
push!(ch.bcvalues, bcvalue)
for d in constrained_dofs
add_prescribed_dof!(ch, d, NaN, nothing)
end
return ch
end
"""
update!(ch::ConstraintHandler, time::Real=0.0)
Update time-dependent inhomogeneities for the new time. This calls `f(x)` or `f(x, t)` when
applicable, where `f` is the function(s) corresponding to the constraints in the handler, to
compute the inhomogeneities.
Note that this is called implicitly in `close!(::ConstraintHandler)`.
"""
function update!(ch::ConstraintHandler, time::Real=0.0)
@assert ch.closed
for (i, dbc) in pairs(ch.dbcs)
# If the BC function only accept one argument, i.e. f(x), we create a wrapper
# g(x, t) = f(x) that discards the second parameter so that _update! can always call
# the function with two arguments internally.
wrapper_f = hasmethod(dbc.f, Tuple{get_coordinate_type(get_grid(ch.dh)), typeof(time)}) ? dbc.f : (x, _) -> dbc.f(x)
# Function barrier
_update!(ch.inhomogeneities, wrapper_f, dbc.facets, dbc.field_name, dbc.local_facet_dofs, dbc.local_facet_dofs_offset,
dbc.components, ch.dh, ch.bcvalues[i], ch.dofmapping, ch.dofcoefficients, time)
end
# Compute effective inhomogeneity for affine constraints with prescribed dofs in the
# RHS. For example, in u2 = w3 * u3 + w4 * u4 + b2 we allow e.g. u3 to be prescribed by
# a trivial constraint with just an inhomogeneity (e.g. DBC), for example u3 = f(t).
# This value have now been computed in _update! and we can compute the effective
# inhomogeneity h2 for u2 which becomes h2 = w3 * u3 + b2 = w3 * f3(t) + b2.
for i in eachindex(ch.prescribed_dofs, ch.dofcoefficients, ch.inhomogeneities)
coeffs = ch.dofcoefficients[i]
coeffs === nothing && continue
h = ch.affine_inhomogeneities[i]
@assert h !== nothing
for (d, w) in coeffs
j = get(ch.dofmapping, d, 0)
j == 0 && continue
# If this dof is prescribed it must only have an inhomogeneity (verified in close!)
@assert (jcoeffs = ch.dofcoefficients[j]; jcoeffs === nothing || isempty(jcoeffs))
h += ch.inhomogeneities[j] * w
end
ch.inhomogeneities[i] = h
end
return nothing
end
# for facets, vertices, faces and edges
function _update!(inhomogeneities::Vector{T}, f::Function, boundary_entities::AbstractVecOrSet{<:BoundaryIndex}, field::Symbol, local_facet_dofs::Vector{Int}, local_facet_dofs_offset::Vector{Int},
components::Vector{Int}, dh::AbstractDofHandler, boundaryvalues::BCValues,
dofmapping::Dict{Int,Int}, dofcoefficients::Vector{Union{Nothing,DofCoefficients{T}}}, time::Real) where {T}
cc = CellCache(dh, UpdateFlags(; nodes=false, coords=true, dofs=true))
for (cellidx, entityidx) in boundary_entities
reinit!(cc, cellidx)
# no need to reinit!, enough to update current_entity since we only need geometric shape functions M
boundaryvalues.current_entity = entityidx
# local dof-range for this facet
r = local_facet_dofs_offset[entityidx]:(local_facet_dofs_offset[entityidx+1]-1)
counter = 1
for location in 1:getnquadpoints(boundaryvalues)
x = spatial_coordinate(boundaryvalues, location, cc.coords)
bc_value = f(x, time)
@assert length(bc_value) == length(components)
for i in 1:length(components)
# find the global dof
globaldof = cc.dofs[local_facet_dofs[r[counter]]]
counter += 1
dbc_index = dofmapping[globaldof]
# Only DBC dofs are currently update!-able so don't modify inhomogeneities
# for affine constraints
if dofcoefficients[dbc_index] === nothing
inhomogeneities[dbc_index] = bc_value[i]
@debug println("prescribing value $(bc_value[i]) on global dof $(globaldof)")
end
end
end
end
end
# for nodes
function _update!(inhomogeneities::Vector{T}, f::Function, ::AbstractVecOrSet{Int}, field::Symbol, nodeidxs::Vector{Int}, globaldofs::Vector{Int},
components::Vector{Int}, dh::AbstractDofHandler, facetvalues::BCValues,
dofmapping::Dict{Int,Int}, dofcoefficients::Vector{Union{Nothing,DofCoefficients{T}}}, time::Real) where T
counter = 1
for nodenumber in nodeidxs
x = get_node_coordinate(get_grid(dh), nodenumber)
bc_value = f(x, time)
@assert length(bc_value) == length(components)
for v in bc_value
globaldof = globaldofs[counter]
counter += 1
dbc_index = dofmapping[globaldof]
# Only DBC dofs are currently update!-able so don't modify inhomogeneities
# for affine constraints
if dofcoefficients[dbc_index] === nothing
inhomogeneities[dbc_index] = v
@debug println("prescribing value $(v) on global dof $(globaldof)")
end
end
end
end
"""
apply!(K::SparseMatrixCSC, rhs::AbstractVector, ch::ConstraintHandler)
Adjust the matrix `K` and right hand side `rhs` to account for the Dirichlet boundary
conditions specified in `ch` such that `K \\ rhs` gives the expected solution.
!!! note
`apply!(K, rhs, ch)` essentially calculates
```julia
rhs[free] = rhs[free] - K[constrained, constrained] * a[constrained]
```
where `a[constrained]` are the inhomogeneities. Consequently, the sign of `rhs` matters
(in contrast with `apply_zero!`).
```julia
apply!(v::AbstractVector, ch::ConstraintHandler)
```
Apply Dirichlet boundary conditions and affine constraints, specified in `ch`, to the solution vector `v`.
# Examples
```julia
K, f = assemble_system(...) # Assemble system
apply!(K, f, ch) # Adjust K and f to account for boundary conditions
u = K \\ f # Solve the system, u should be "approximately correct"
apply!(u, ch) # Explicitly make sure bcs are correct
```
!!! note
The last operation is not strictly necessary since the boundary conditions should
already be fulfilled after `apply!(K, f, ch)`. However, solvers of linear systems are
not exact, and thus `apply!(u, ch)` can be used to make sure the boundary conditions
are fulfilled exactly.
"""
apply!
"""
apply_zero!(K::SparseMatrixCSC, rhs::AbstractVector, ch::ConstraintHandler)
Adjust the matrix `K` and the right hand side `rhs` to account for prescribed Dirichlet
boundary conditions and affine constraints such that `du = K \\ rhs` gives the expected
result (e.g. `du` zero for all prescribed degrees of freedom).
apply_zero!(v::AbstractVector, ch::ConstraintHandler)
Zero-out values in `v` corresponding to prescribed degrees of freedom and update values
prescribed by affine constraints, such that if `a` fulfills the constraints,
`a ± v` also will.
These methods are typically used in e.g. a Newton solver where the increment, `du`, should
be prescribed to zero even for non-homogeneouos boundary conditions.
See also: [`apply!`](@ref).
# Examples
```julia
u = un + Δu # Current guess
K, g = assemble_system(...) # Assemble residual and tangent for current guess
apply_zero!(K, g, ch) # Adjust tangent and residual to take prescribed values into account
ΔΔu = K \\ g # Compute the (negative) increment, prescribed values are "approximately" zero
apply_zero!(ΔΔu, ch) # Make sure values are exactly zero
Δu .-= ΔΔu # Update current guess
```
!!! note
The last call to `apply_zero!` is only strictly necessary for affine constraints.
However, even if the Dirichlet boundary conditions should be fulfilled after
`apply!(K, g, ch)`, solvers of linear systems are not exact.
`apply!(ΔΔu, ch)` can be used to make sure the values
for the prescribed degrees of freedom are fulfilled exactly.
"""
apply_zero!
apply_zero!(v::AbstractVector, ch::ConstraintHandler) = _apply_v(v, ch, true)
apply!( v::AbstractVector, ch::ConstraintHandler) = _apply_v(v, ch, false)
function _apply_v(v::AbstractVector, ch::ConstraintHandler, apply_zero::Bool)
@assert isclosed(ch)
@assert length(v) >= ndofs(ch.dh)
v[ch.prescribed_dofs] .= apply_zero ? 0.0 : ch.inhomogeneities
# Apply affine constraints, e.g u2 = s6*u6 + s3*u3 + h2
for (dof, dofcoef, h) in zip(ch.prescribed_dofs, ch.dofcoefficients, ch.affine_inhomogeneities)
dofcoef === nothing && continue
@assert h !== nothing
v[dof] = apply_zero ? 0.0 : h
for (d, s) in dofcoef
v[dof] += s * v[d]
end
end
return v
end
function apply!(K::Union{SparseMatrixCSC,Symmetric}, ch::ConstraintHandler)
apply!(K, eltype(K)[], ch, true)
end
function apply_zero!(K::Union{SparseMatrixCSC,Symmetric}, f::AbstractVector, ch::ConstraintHandler)
apply!(K, f, ch, true)
end
function apply!(KK::Union{SparseMatrixCSC,Symmetric}, f::AbstractVector, ch::ConstraintHandler, applyzero::Bool=false)
@assert isclosed(ch)
sym = isa(KK, Symmetric)
K = sym ? KK.data : KK
@assert length(f) == 0 || length(f) == size(K, 1)
@boundscheck checkbounds(K, ch.prescribed_dofs, ch.prescribed_dofs)
@boundscheck length(f) == 0 || checkbounds(f, ch.prescribed_dofs)
m = meandiag(K) # Use the mean of the diagonal here to not ruin things for iterative solver
# Add inhomogeneities to f: (f - K * ch.inhomogeneities)
if !applyzero
@inbounds for i in 1:length(ch.inhomogeneities)
d = ch.prescribed_dofs[i]
v = ch.inhomogeneities[i]
if v != 0
for j in nzrange(K, d)
r = K.rowval[j]
sym && r > d && break # don't look below diagonal
f[r] -= v * K.nzval[j]
end
end
end
if sym
# In the symmetric case, for a constrained dof `d`, we handle the contribution
# from `K[1:d, d]` in the loop above, but we are still missing the contribution
# from `K[(d+1):size(K,1), d]`. These values are not stored, but since the
# matrix is symmetric we can instead use `K[d, (d+1):size(K,1)]`. Looping over
# rows is slow, so loop over all columns again, and check if the row is a
# constrained row.
@inbounds for col in 1:size(K, 2)
for ri in nzrange(K, col)
row = K.rowval[ri]
row >= col && break
if (i = get(ch.dofmapping, row, 0); i != 0)
f[col] -= ch.inhomogeneities[i] * K.nzval[ri]
end
end
end
end
end
# Condense K (C' * K * C) and f (C' * f)
_condense!(K, f, ch.dofcoefficients, ch.dofmapping, sym)
# Remove constrained dofs from the matrix
zero_out_columns!(K, ch.prescribed_dofs)
zero_out_rows!(K, ch.dofmapping)
# Add meandiag to constraint dofs
@inbounds for i in 1:length(ch.inhomogeneities)
d = ch.prescribed_dofs[i]
K[d, d] = m
if length(f) != 0
vz = applyzero ? zero(eltype(f)) : ch.inhomogeneities[i]
f[d] = vz * m
end
end
end
# Fetch dof coefficients for a dof prescribed by an affine constraint. Return nothing if the
# dof is not prescribed, or prescribed by DBC.
@inline function coefficients_for_dof(dofmapping, dofcoeffs, dof)
idx = get(dofmapping, dof, 0)
idx == 0 && return nothing
return dofcoeffs[idx]
end
# Condenses K and f: C'*K*C, C'*f, in-place assuming the sparsity pattern is correct
function _condense!(K::SparseMatrixCSC, f::AbstractVector, dofcoefficients::Vector{Union{Nothing, DofCoefficients{T}}}, dofmapping::Dict{Int,Int}, sym::Bool=false) where T
ndofs = size(K, 1)
condense_f = !(length(f) == 0)
condense_f && @assert( length(f) == ndofs )
# Return early if there are no non-trivial affine constraints
any(i -> !(i === nothing || isempty(i)), dofcoefficients) || return
# TODO: The rest of this method can't handle K::Symmetric
if sym
error("condensation of ::Symmetric matrix not supported")
end
for col in 1:ndofs
col_coeffs = coefficients_for_dof(dofmapping, dofcoefficients, col)
if col_coeffs === nothing
for a in nzrange(K, col)
Kval = K.nzval[a]
iszero(Kval) && continue
row = K.rowval[a]
row_coeffs = coefficients_for_dof(dofmapping, dofcoefficients, row)
row_coeffs === nothing && continue
for (d, v) in row_coeffs
addindex!(K, v * Kval, d, col)
end
# Perform f - K*g. However, this has already been done in outside this functions so we skip this.
# if condense_f
# f[col] -= K.nzval[a] * ac.b;
# end
end
else
for a in nzrange(K, col)
Kval = K.nzval[a]
iszero(Kval) && continue
row = K.rowval[a]
row_coeffs = coefficients_for_dof(dofmapping, dofcoefficients, row)
if row_coeffs === nothing
for (d, v) in col_coeffs
addindex!(K, v * Kval, row, d)
end
else
for (d1, v1) in col_coeffs, (d2, v2) in row_coeffs
addindex!(K, v1 * v2 * Kval, d1, d2)
end
end
end
if condense_f
for (d, v) in col_coeffs
f[d] += f[col] * v
end
f[col] = 0.0
end
end
end
end
function _add_or_grow(cnt::Int, I::Vector{Int}, J::Vector{Int}, dofi::Int, dofj::Int)
if cnt > length(J)
resize!(I, trunc(Int, length(I) * 1.5))
resize!(J, trunc(Int, length(J) * 1.5))
end
I[cnt] = dofi
J[cnt] = dofj
end
"""
create_constraint_matrix(ch::ConstraintHandler)
Create and return the constraint matrix, `C`, and the inhomogeneities, `g`, from the affine
(linear) and Dirichlet constraints in `ch`.
The constraint matrix relates constrained, `a_c`, and free, `a_f`, degrees of freedom via
`a_c = C * a_f + g`. The condensed system of linear equations is obtained as
`C' * K * C = C' * (f - K * g)`.
"""
function create_constraint_matrix(ch::ConstraintHandler{dh,T}) where {dh,T}
@assert(isclosed(ch))
I = Int[]; J = Int[]; V = T[];
g = zeros(T, ndofs(ch.dh)) # inhomogeneities
for (j, d) in enumerate(ch.free_dofs)
push!(I, d)
push!(J, j)
push!(V, 1.0)
end
for (i,pdof) in enumerate(ch.prescribed_dofs)
dofcoef = ch.dofcoefficients[i]
if dofcoef !== nothing #if affine constraint
for (d, v) in dofcoef
push!(I, pdof)
j = searchsortedfirst(ch.free_dofs, d)
push!(J, j)
push!(V, v)
end
end
end
g[ch.prescribed_dofs] .= ch.inhomogeneities
C = sparse(I, J, V, ndofs(ch.dh), length(ch.free_dofs))
return C, g
end
# columns need to be stored entries, this is not checked
function zero_out_columns!(K, dofs::Vector{Int}) # can be removed in 0.7 with #24711 merged
@debug @assert issorted(dofs)
for col in dofs
r = nzrange(K, col)
K.nzval[r] .= 0.0
end
end
function zero_out_rows!(K, dofmapping)
rowval = K.rowval
nzval = K.nzval
@inbounds for i in eachindex(rowval, nzval)
if haskey(dofmapping, rowval[i])
nzval[i] = 0
end
end
end
function meandiag(K::AbstractMatrix)
z = zero(eltype(K))
for i in 1:size(K, 1)
z += abs(K[i, i])
end
return z / size(K, 1)
end
"""
add!(ch::ConstraintHandler, dbc::Dirichlet)
Add a `Dirichlet` boundary condition to the `ConstraintHandler`.
"""
function add!(ch::ConstraintHandler, dbc::Dirichlet)
# Duplicate the Dirichlet constraint for every SubDofHandler
dbc_added = false
for sdh in ch.dh.subdofhandlers
# Skip if the constrained field does not live on this sub domain
dbc.field_name in sdh.field_names || continue
# Compute the intersection between dbc.set and the cellset of this
# SubDofHandler and skip if the set is empty
filtered_set = filter_dbc_set(get_grid(ch.dh), sdh.cellset, dbc.facets)
isempty(filtered_set) && continue
# Fetch information about the field on this SubDofHandler
field_idx = find_field(sdh, dbc.field_name)
interpolation = getfieldinterpolation(sdh, field_idx)
# Internally we use the devectorized version
n_comp = n_dbc_components(interpolation)
if interpolation isa VectorizedInterpolation
interpolation = interpolation.ip
end
getorder(interpolation) == 0 && error("No dof prescribed for order 0 interpolations")
# Set up components to prescribe (empty input means prescribe all components)
components = isempty(dbc.components) ? collect(Int, 1:n_comp) : dbc.components
if !all(c -> 0 < c <= n_comp, components)
error("components $(components) not within range of field :$(dbc.field_name) ($(n_comp) dimension(s))")
end
# Create BCValues for coordinate evaluation at dof-locations
EntityType = eltype(dbc.facets) # (Facet|Face|Edge|Vertex)Index
if EntityType <: Integer
# BCValues are just dummy for nodesets so set to FacetIndex
EntityType = FacetIndex
end
CT = getcelltype(sdh) # Same celltype enforced in SubDofHandler constructor
bcvalues = BCValues(interpolation, geometric_interpolation(CT), EntityType)
# Recreate the Dirichlet(...) struct with the filtered set and call internal add!
filtered_dbc = Dirichlet(dbc.field_name, filtered_set, dbc.f, components)
_add!(
ch, filtered_dbc, filtered_dbc.facets, interpolation, n_comp,
field_offset(sdh, field_idx), bcvalues, sdh.cellset,
)
dbc_added = true
end
dbc_added || error("No overlap between dbc::Dirichlet and fields in the ConstraintHandler's DofHandler")
return ch
end
# Return the intersection of the SubDofHandler set and the Dirichlet BC set
function filter_dbc_set(::AbstractGrid, fhset::AbstractSet{Int}, dbcset::AbstractSet{<:BoundaryIndex})
ret = empty(dbcset)::typeof(dbcset)
for x in dbcset
cellid, _ = x
cellid in fhset && push!(ret, x)
end
return ret
end
function filter_dbc_set(grid::AbstractGrid, fhset::AbstractSet{Int}, dbcset::AbstractSet{Int})
ret = empty(dbcset)
nodes_in_fhset = OrderedSet{Int}()
for cc in CellIterator(grid, fhset, UpdateFlags(; nodes=true, coords=false))
union!(nodes_in_fhset, cc.nodes)
end
for nodeid in dbcset
nodeid in nodes_in_fhset && push!(ret, nodeid)
end
return ret
end
struct PeriodicFacetPair
mirror::FacetIndex
image::FacetIndex
rotation::UInt8 # relative rotation of the mirror facet counter-clockwise the *image* normal (only relevant in 3D)
mirrored::Bool # mirrored => opposite normal vectors
end
"""
PeriodicDirichlet(u::Symbol, facet_mapping, components=nothing)
PeriodicDirichlet(u::Symbol, facet_mapping, R::AbstractMatrix, components=nothing)
PeriodicDirichlet(u::Symbol, facet_mapping, f::Function, components=nothing)
Create a periodic Dirichlet boundary condition for the field `u` on the facet-pairs given in
`facet_mapping`. The mapping can be computed with [`collect_periodic_facets`](@ref). The
constraint ensures that degrees-of-freedom on the mirror facet are constrained to the
corresponding degrees-of-freedom on the image facet. `components` specify the components of
`u` that are prescribed by this condition. By default all components of `u` are prescribed.
If the mapping is not aligned with the coordinate axis (e.g. rotated) a rotation matrix `R`
should be passed to the constructor. This matrix rotates dofs on the mirror facet to the
image facet. Note that this is only applicable for vector-valued problems.
To construct an inhomogeneous periodic constraint it is possible to pass a function `f`.
Note that this is currently only supported when the periodicity is aligned with the
coordinate axes.
See the manual section on [Periodic boundary conditions](@ref) for more information.
"""
struct PeriodicDirichlet
field_name::Symbol
components::Vector{Int} # components of the field
facet_pairs::Vector{Pair{String,String}} # legacy that will populate facet_map on add!
facet_map::Vector{PeriodicFacetPair}
func::Union{Function,Nothing}
rotation_matrix::Union{Matrix{Float64},Nothing}
end
# Default to no inhomogeneity function/rotation
PeriodicDirichlet(fn::Symbol, fp::Union{Vector{<:Pair},Vector{PeriodicFacetPair}}, c=nothing) =
PeriodicDirichlet(fn, fp, nothing, c)
# Basic constructor for the simple case where face_map will be populated in
# add!(::ConstraintHandler, ...) instead
function PeriodicDirichlet(fn::Symbol, fp::Vector{<:Pair}, f::Union{Function,Nothing}, c=nothing)
facet_map = PeriodicFacetPair[] # This will be populated in add!(::ConstraintHandler, ...) instead
return PeriodicDirichlet(fn, __to_components(c), fp, facet_map, f, nothing)
end
function PeriodicDirichlet(fn::Symbol, fm::Vector{PeriodicFacetPair}, f_or_r::Union{AbstractMatrix,Function,Nothing}, c=nothing)
f = f_or_r isa Function ? f_or_r : nothing
rotation_matrix = f_or_r isa AbstractMatrix ? f_or_r : nothing
components = __to_components(c)
return PeriodicDirichlet(fn, components, Pair{String,String}[], fm, f, rotation_matrix)
end
function add!(ch::ConstraintHandler, pdbc::PeriodicDirichlet)
# Legacy code: Might need to build the facet_map
is_legacy = !isempty(pdbc.facet_pairs) && isempty(pdbc.facet_map)
if is_legacy
for (mset, iset) in pdbc.facet_pairs
collect_periodic_facets!(pdbc.facet_map, get_grid(ch.dh), mset, iset, identity) # TODO: Better transform
end
end
field_idx = find_field(ch.dh, pdbc.field_name)
interpolation = getfieldinterpolation(ch.dh, field_idx)
n_comp = n_dbc_components(interpolation)
if interpolation isa VectorizedInterpolation
interpolation = interpolation.ip
end
if !all(c -> 0 < c <= n_comp, pdbc.components)
error("components $(pdbc.components) not within range of field :$(pdbc.field_name) ($(n_comp) dimension(s))")
end
# Empty components means constrain them all
isempty(pdbc.components) && append!(pdbc.components, 1:n_comp)
if pdbc.rotation_matrix === nothing
dof_map_t = Int
iterator_f = identity
else
@assert pdbc.func === nothing # Verified in constructor
if is_legacy
error("legacy mode not supported with rotations")
end
nc = length(pdbc.components)
if !(nc == size(pdbc.rotation_matrix, 1) == size(pdbc.rotation_matrix, 2))
error("size of rotation matrix does not match the number of components")
end
if nc !== n_comp
error("rotations currently only supported when all components are periodic")
end
dof_map_t = Vector{Int}
iterator_f = x -> Iterators.partition(x, nc)
end
_add!(ch, pdbc, interpolation, n_comp, field_offset(ch.dh.subdofhandlers[field_idx[1]], field_idx[2]), is_legacy, pdbc.rotation_matrix, dof_map_t, iterator_f)
return ch
end
function _add!(ch::ConstraintHandler, pdbc::PeriodicDirichlet, interpolation::Interpolation,
field_dim::Int, offset::Int, is_legacy::Bool, rotation_matrix::Union{Matrix{T},Nothing}, ::Type{dof_map_t}, iterator_f::F) where {T, dof_map_t, F <: Function}
grid = get_grid(ch.dh)
facet_map = pdbc.facet_map
# Indices of the local dofs for the facets
local_facet_dofs, local_facet_dofs_offset =
_local_facet_dofs_for_bc(interpolation, field_dim, pdbc.components, offset)
mirrored_indices =
mirror_local_dofs(local_facet_dofs, local_facet_dofs_offset, interpolation, length(pdbc.components))
rotated_indices = rotate_local_dofs(local_facet_dofs, local_facet_dofs_offset, interpolation, length(pdbc.components))
# Dof map for mirror dof => image dof
dof_map = Dict{dof_map_t,dof_map_t}()
n = ndofs_per_cell(ch.dh, first(facet_map).mirror[1])
mirror_dofs = zeros(Int, n)
image_dofs = zeros(Int, n)
for facet_pair in facet_map
m = facet_pair.mirror
i = facet_pair.image
celldofs!(mirror_dofs, ch.dh, m[1])
celldofs!( image_dofs, ch.dh, i[1])
mdof_range = local_facet_dofs_offset[m[2]] : (local_facet_dofs_offset[m[2] + 1] - 1)
idof_range = local_facet_dofs_offset[i[2]] : (local_facet_dofs_offset[i[2] + 1] - 1)
for (md, id) in zip(iterator_f(mdof_range), iterator_f(idof_range))
mdof = image_dofs[local_facet_dofs[id]]