-
Notifications
You must be signed in to change notification settings - Fork 89
/
ConstraintHandler.jl
1859 lines (1636 loc) · 73.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, ∂Ω::Set, 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.
For example, here we create a
Dirichlet condition for the `:u` field, on the faceset called
`∂Ω` and the value given by the `sin` function:
*Examples*
```jldoctest
# Obtain the faceset from the grid
∂Ω = getfaceset(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)
faces::Union{Set{Int},Set{FaceIndex},Set{EdgeIndex},Set{VertexIndex}}
field_name::Symbol
components::Vector{Int} # components of the field
local_face_dofs::Vector{Int}
local_face_dofs_offset::Vector{Int}
end
function Dirichlet(field_name::Symbol, faces::Set, f::Function, components=nothing)
return Dirichlet(f, copy(faces), 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, entires::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
Collection of constraints.
"""
struct ConstraintHandler{DH<:AbstractDofHandler,T}
dbcs::Vector{Dirichlet}
prescribed_dofs::Vector{Int}
free_dofs::Vector{Int}
inhomogeneities::Vector{T}
# Store the original constant inhomogeneities for affine constraints used to compute
# "effective" inhomogeneities in `update!` and then stored in .inhomogeneities.
affine_inhomogeneities::Vector{Union{Nothing,T}}
# `nothing` for pure DBC constraint, otherwise affine constraint
dofcoefficients::Vector{Union{Nothing, DofCoefficients{T}}}
# global dof -> index into dofs and inhomogeneities and dofcoefficients
dofmapping::Dict{Int,Int}
bcvalues::Vector{BCValues{T}}
dh::DH
closed::ScalarWrapper{Bool}
end
function ConstraintHandler(dh::AbstractDofHandler)
@assert isclosed(dh)
ConstraintHandler(
Dirichlet[], Int[], Int[], Float64[], Union{Nothing,Float64}[], Union{Nothing,DofCoefficients{Float64}}[],
Dict{Int,Int}(), BCValues{Float64}[], dh, ScalarWrapper(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
"""
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]
copy!(ch.free_dofs, setdiff(1: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, dbc::Dirichlet)
Add a `Dirichlet` boundary condition to the `ConstraintHandler`.
"""
function add!(ch::ConstraintHandler, dbc::Dirichlet)
if length(dbc.faces) == 0
@warn("adding Dirichlet Boundary Condition to set containing 0 entities")
end
celltype = getcelltype(ch.dh.grid)
@assert isconcretetype(celltype)
# Extract stuff for the field
field_idx = find_field(ch.dh, dbc.field_name) # throws if name not found
interpolation = getfieldinterpolation(ch.dh, field_idx)
field_dim = getfielddim(ch.dh, field_idx)
if !all(c -> 0 < c <= field_dim, dbc.components)
error("components $(dbc.components) not within range of field :$(dbc.field_name) ($(field_dim) dimension(s))")
end
# Empty components means constrain them all
isempty(dbc.components) && append!(dbc.components, 1:field_dim)
if eltype(dbc.faces)==Int #Special case when dbc.faces is a nodeset
bcvalue = BCValues(interpolation, default_interpolation(celltype), FaceIndex) #Not used by node bcs, but still have to pass it as an argument
else
bcvalue = BCValues(interpolation, default_interpolation(celltype), eltype(dbc.faces))
end
_add!(ch, dbc, dbc.faces, interpolation, field_dim, field_offset(ch.dh, dbc.field_name), bcvalue)
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
function _add!(ch::ConstraintHandler, dbc::Dirichlet, bcfaces::Set{Index}, interpolation::Interpolation, field_dim::Int, offset::Int, bcvalue::BCValues, cellset::Set{Int}=Set{Int}(1:getncells(ch.dh.grid))) where {Index<:BoundaryIndex}
local_face_dofs, local_face_dofs_offset =
_local_face_dofs_for_bc(interpolation, field_dim, dbc.components, offset, boundaryfunction(eltype(bcfaces)))
copy!(dbc.local_face_dofs, local_face_dofs)
copy!(dbc.local_face_dofs_offset, local_face_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, faceidx) in bcfaces
if cellidx ∉ cellset
delete!(dbc.faces, Index(cellidx, faceidx))
continue # skip faces that are not part of the cellset
end
reinit!(cc, cellidx)
r = local_face_dofs_offset[faceidx]:(local_face_dofs_offset[faceidx+1]-1)
append!(constrained_dofs, cc.dofs[local_face_dofs[r]]) # TODO: for-loop over r and simply push! to ch.prescribed_dofs
@debug println("adding dofs $(cc.dofs[local_face_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 face:
# face `i` have dofs `local_face_dofs[local_face_dofs_offset[i]:local_face_dofs_offset[i+1]-1]
function _local_face_dofs_for_bc(interpolation, field_dim, components, offset, boundaryfunc::F=faces) where F
@assert issorted(components)
local_face_dofs = Int[]
local_face_dofs_offset = Int[1]
for (_, face) in enumerate(boundaryfunc(interpolation))
for fdof in face, d in 1:field_dim
if d in components
push!(local_face_dofs, (fdof-1)*field_dim + d + offset)
end
end
push!(local_face_dofs_offset, length(local_face_dofs) + 1)
end
return local_face_dofs, local_face_dofs_offset
end
function _add!(ch::ConstraintHandler, dbc::Dirichlet, bcnodes::Set{Int}, interpolation::Interpolation, field_dim::Int, offset::Int, bcvalue::BCValues, cellset::Set{Int}=Set{Int}(1:getncells(ch.dh.grid)))
if interpolation !== default_interpolation(typeof(ch.dh.grid.cells[first(cellset)]))
@warn("adding constraint to nodeset is not recommended for sub/super-parametric approximations.")
end
ncomps = length(dbc.components)
nnodes = getnnodes(ch.dh.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 FieldHandler
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_face_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_face_dofs, node) # use this field to store the node idx for each node
end
# save it to the ConstraintHandler
copy!(dbc.local_face_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{Any,Any}) ? dbc.f : (x, _) -> dbc.f(x)
# Function barrier
_update!(ch.inhomogeneities, wrapper_f, dbc.faces, dbc.field_name, dbc.local_face_dofs, dbc.local_face_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 faces
function _update!(inhomogeneities::Vector{Float64}, f::Function, faces::Set{<:BoundaryIndex}, field::Symbol, local_face_dofs::Vector{Int}, local_face_dofs_offset::Vector{Int},
components::Vector{Int}, dh::AbstractDofHandler, facevalues::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, faceidx) in faces
reinit!(cc, cellidx)
# no need to reinit!, enough to update current_face since we only need geometric shape functions M
facevalues.current_face[] = faceidx
# local dof-range for this face
r = local_face_dofs_offset[faceidx]:(local_face_dofs_offset[faceidx+1]-1)
counter = 1
for location in 1:getnquadpoints(facevalues)
x = spatial_coordinate(facevalues, 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_face_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{Float64}, f::Function, nodes::Set{Int}, field::Symbol, nodeidxs::Vector{Int}, globaldofs::Vector{Int},
components::Vector{Int}, dh::AbstractDofHandler, facevalues::BCValues,
dofmapping::Dict{Int,Int}, dofcoefficients::Vector{Union{Nothing,DofCoefficients{T}}}, time::Real) where T
counter = 1
for (idx, nodenumber) in enumerate(nodeidxs)
x = dh.grid.nodes[nodenumber].x
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
# Saves the dirichlet boundary conditions to a vtkfile.
# Values will have a 1 where bcs are active and 0 otherwise
function WriteVTK.vtk_point_data(vtkfile, ch::ConstraintHandler)
unique_fields = []
for dbc in ch.dbcs
push!(unique_fields, dbc.field_name)
end
unique!(unique_fields)
for field in unique_fields
nd = ndim(ch.dh, field)
data = zeros(Float64, nd, getnnodes(ch.dh.grid))
for dbc in ch.dbcs
dbc.field_name != field && continue
if eltype(dbc.faces) <: BoundaryIndex
functype = boundaryfunction(eltype(dbc.faces))
for (cellidx, faceidx) in dbc.faces
for facenode in functype(ch.dh.grid.cells[cellidx])[faceidx]
for component in dbc.components
data[component, facenode] = 1
end
end
end
else
for nodeidx in dbc.faces
for component in dbc.components
data[component, nodeidx] = 1
end
end
end
end
vtk_point_data(vtkfile, data, string(field, "_bc"))
end
return vtkfile
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
`rhs[free_dofs] = rhs[free_dofs] - K[free_dofs, constrained_dofs] * a[constrained]`
where `a[constrained]` are the inhomogeneities.
Consequently, the sign of `rhs` matters (in contrast to for `apply_zero!`).
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` fullfills 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 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
# For backwards compatibility, not used anymore
@enumx ApplyStrategy Transpose Inplace
const APPLY_TRANSPOSE = ApplyStrategy.Transpose
const APPLY_INPLACE = ApplyStrategy.Inplace
function apply!(KK::Union{SparseMatrixCSC,Symmetric}, f::AbstractVector, ch::ConstraintHandler, applyzero::Bool=false;
strategy::ApplyStrategy.T=ApplyStrategy.Transpose)
K = isa(KK, Symmetric) ? 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)
f[K.rowval[j]] -= v * K.nzval[j]
end
end
end
end
# Condense K (C' * K * C) and f (C' * f)
_condense!(K, f, ch.dofcoefficients, ch.dofmapping)
# 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
# Similar to Ferrite._condense!(K, ch), but only add the non-zero entries to K (that arises from the condensation process)
function _condense_sparsity_pattern!(K::SparseMatrixCSC{T}, dofcoefficients::Vector{Union{Nothing,DofCoefficients{T}}}, dofmapping::Dict{Int,Int}, keep_constrained::Bool) where T
ndofs = size(K, 1)
# Return early if there are no non-trivial affine constraints
any(i -> !(i === nothing || isempty(i)), dofcoefficients) || return
# Adding new entries to K is extremely slow, so create a new sparsity triplet for the
# condensed sparsity pattern
N = 2 * length(dofcoefficients) # TODO: Better size estimate for additional condensed sparsity pattern.
I = Int[]; resize!(I, N)
J = Int[]; resize!(J, N)
cnt = 0
for col in 1:ndofs
col_coeffs = coefficients_for_dof(dofmapping, dofcoefficients, col)
if col_coeffs === nothing
!keep_constrained && haskey(dofmapping, col) && continue
for ri in nzrange(K, col)
row = K.rowval[ri]
row_coeffs = coefficients_for_dof(dofmapping, dofcoefficients, row)
row_coeffs === nothing && continue
for (d, _) in row_coeffs
cnt += 1
_add_or_grow(cnt, I, J, d, col)
end
end
else
for ri in nzrange(K, col)
row = K.rowval[ri]
row_coeffs = coefficients_for_dof(dofmapping, dofcoefficients, row)
if row_coeffs === nothing
!keep_constrained && haskey(dofmapping, row) && continue
for (d, _) in col_coeffs
cnt += 1
_add_or_grow(cnt, I, J, row, d)
end
else
for (d1, _) in col_coeffs
!keep_constrained && haskey(dofmapping, d1) && continue
for (d2, _) in row_coeffs
!keep_constrained && haskey(dofmapping, d2) && continue
cnt += 1
_add_or_grow(cnt, I, J, d1, d2)
end
end
end
end
end
end
resize!(I, cnt)
resize!(J, cnt)
# Fill the sparse matrix with a non-zero value so that :+ operation does not remove entries with value zero.
K2 = spzeros!!(Float64, I, J, ndofs, ndofs)
fill!(K2.nzval, 1)
K .+= K2
return nothing
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}) 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
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
#Function for adding constraint when using multiple celltypes
function add!(ch::ConstraintHandler{<:MixedDofHandler}, dbc::Dirichlet)
dbc_added = false
for fh in ch.dh.fieldhandlers
if overlaps(fh, dbc)
# Recreating the `dbc` will create a copy of `dbc.faces`.
# If `dbc` have dofs not in `fh`, these will be removed from `dbc`,
# thus the need to copy `dbc.faces`.
# In this case, add! will warn, unless warn_check_cellset=false
dbc_ = Dirichlet(dbc.field_name, dbc.faces, dbc.f,
isempty(dbc.components) ? nothing : dbc.components)
# Check for empty already done when user created `dbc`
add!(ch, fh, dbc_, warn_check_cellset=false)
dbc_added = true
end
end
dbc_added || @warn("No overlap between dbc::Dirichlet and fields in the ConstraintHandler's MixedDofHandler")
return ch
end
function overlaps(fh::FieldHandler, dbc::Dirichlet)
dbc.field_name in getfieldnames(fh) || return false # Must contain the correct field
for (cellid, _) in dbc.faces
cellid in fh.cellset && return true
end
return false
end
function add!(ch::ConstraintHandler, fh::FieldHandler, dbc::Dirichlet; warn_check_cellset=true)
warn_check_cellset && _check_cellset_dirichlet(ch.dh.grid, fh.cellset, dbc.faces)
celltype = getcelltype(ch.dh.grid, first(fh.cellset)) #Assume same celltype of all cells in fh.cellset
# Extract stuff for the field
field_idx = find_field(fh, dbc.field_name)
interpolation = getfieldinterpolations(fh)[field_idx]
field_dim = getfielddims(fh)[field_idx]
if !all(c -> 0 < c <= field_dim, dbc.components)
error("components $(dbc.components) not within range of field :$(dbc.field_name) ($(field_dim) dimension(s))")
end
# Empty components means constrain them all
isempty(dbc.components) && append!(dbc.components, 1:field_dim)
if eltype(dbc.faces)==Int #Special case when dbc.faces is a nodeset
bcvalue = BCValues(interpolation, default_interpolation(celltype), FaceIndex) #Not used by node bcs, but still have to pass it as an argument
else
bcvalue = BCValues(interpolation, default_interpolation(celltype), eltype(dbc.faces))
end
Ferrite._add!(ch, dbc, dbc.faces, interpolation, field_dim, field_offset(fh, dbc.field_name), bcvalue, fh.cellset)
return ch
end
function _check_cellset_dirichlet(::AbstractGrid, cellset::Set{Int}, faceset::Set{<:BoundaryIndex})
for (cellid,faceid) in faceset
if !(cellid in cellset)
@warn("You are trying to add a constraint to a face that is not in the cellset of the fieldhandler. The face will be skipped.")
end
end
end
function _check_cellset_dirichlet(grid::AbstractGrid, cellset::Set{Int}, nodeset::Set{Int})
nodes = Set{Int}()
for cellid in cellset
for nodeid in grid.cells[cellid].nodes
nodeid ∈ nodes || push!(nodes, nodeid)
end
end
for nodeid in nodeset
if !(nodeid ∈ nodes)
@warn("You are trying to add a constraint to a node that is not in the cellset of the fieldhandler. The node will be skipped.")
end
end
end
"""
create_symmetric_sparsity_pattern(dh::AbstractDofHandler, ch::ConstraintHandler, coupling)
Create a symmetric sparsity pattern accounting for affine constraints in `ch`. See
the Affine Constraints section of the manual for further details.
"""
function create_symmetric_sparsity_pattern(dh::AbstractDofHandler, ch::ConstraintHandler;
keep_constrained::Bool=true, coupling=nothing)
return Symmetric(_create_sparsity_pattern(dh, ch, true, keep_constrained, coupling), :U)
end
"""
create_sparsity_pattern(dh::AbstractDofHandler, ch::ConstraintHandler; coupling)
Create a sparsity pattern accounting for affine constraints in `ch`. See
the Affine Constraints section of the manual for further details.
"""
function create_sparsity_pattern(dh::AbstractDofHandler, ch::ConstraintHandler;
keep_constrained::Bool=true, coupling=nothing)
return _create_sparsity_pattern(dh, ch, false, keep_constrained, coupling)
end
struct PeriodicFacePair
mirror::FaceIndex
image::FaceIndex
rotation::UInt8 # relative rotation of the mirror face counter-clockwise the *image* normal (only relevant in 3D)
mirrored::Bool # mirrored => opposite normal vectors
end
"""
PeriodicDirichlet(u::Symbol, face_mapping, components=nothing)
PeriodicDirichlet(u::Symbol, face_mapping, R::AbstractMatrix, components=nothing)
PeriodicDirichlet(u::Symbol, face_mapping, f::Function, components=nothing)
Create a periodic Dirichlet boundary condition for the field `u` on the face-pairs given in