-
Notifications
You must be signed in to change notification settings - Fork 707
/
grid_tools.cc
7172 lines (6274 loc) · 275 KB
/
grid_tools.cc
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
// ---------------------------------------------------------------------
//
// Copyright (C) 2001 - 2021 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.md at
// the top level directory of deal.II.
//
// ---------------------------------------------------------------------
#include <deal.II/base/mpi.h>
#include <deal.II/base/mpi.templates.h>
#include <deal.II/base/mpi_consensus_algorithms.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/thread_management.h>
#include <deal.II/distributed/fully_distributed_tria.h>
#include <deal.II/distributed/p4est_wrappers.h>
#include <deal.II/distributed/shared_tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_nothing.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/fe/mapping_q1.h>
#include <deal.II/grid/filtered_iterator.h>
#include <deal.II/grid/grid_reordering.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/grid/grid_tools_cache.h>
#include <deal.II/grid/manifold.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/lac/constrained_linear_operator.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/sparsity_pattern.h>
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/lac/vector.h>
#include <deal.II/lac/vector_memory.h>
#include <deal.II/numerics/matrix_tools.h>
#include <deal.II/numerics/vector_tools_integrate_difference.h>
DEAL_II_DISABLE_EXTRA_DIAGNOSTICS
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>
DEAL_II_ENABLE_EXTRA_DIAGNOSTICS
#include <array>
#include <cmath>
#include <iostream>
#include <list>
#include <numeric>
#include <set>
#include <tuple>
#include <unordered_map>
DEAL_II_NAMESPACE_OPEN
namespace GridTools
{
template <int dim, int spacedim>
double
diameter(const Triangulation<dim, spacedim> &tria)
{
// we can't deal with distributed meshes since we don't have all
// vertices locally. there is one exception, however: if the mesh has
// never been refined. the way to test this is not to ask
// tria.n_levels()==1, since this is something that can happen on one
// processor without being true on all. however, we can ask for the
// global number of active cells and use that
#if defined(DEAL_II_WITH_P4EST) && defined(DEBUG)
if (const parallel::distributed::Triangulation<dim, spacedim> *p_tria =
dynamic_cast<
const parallel::distributed::Triangulation<dim, spacedim> *>(&tria))
Assert(p_tria->n_global_active_cells() == tria.n_cells(0),
ExcNotImplemented());
#endif
// the algorithm used simply traverses all cells and picks out the
// boundary vertices. it may or may not be faster to simply get all
// vectors, don't mark boundary vertices, and compute the distances
// thereof, but at least as the mesh is refined, it seems better to
// first mark boundary nodes, as marking is O(N) in the number of
// cells/vertices, while computing the maximal distance is O(N*N)
const std::vector<Point<spacedim>> &vertices = tria.get_vertices();
std::vector<bool> boundary_vertices(vertices.size(), false);
typename Triangulation<dim, spacedim>::active_cell_iterator cell =
tria.begin_active();
const typename Triangulation<dim, spacedim>::active_cell_iterator endc =
tria.end();
for (; cell != endc; ++cell)
for (const unsigned int face : cell->face_indices())
if (cell->face(face)->at_boundary())
for (unsigned int i = 0; i < cell->face(face)->n_vertices(); ++i)
boundary_vertices[cell->face(face)->vertex_index(i)] = true;
// now traverse the list of boundary vertices and check distances.
// since distances are symmetric, we only have to check one half
double max_distance_sqr = 0;
std::vector<bool>::const_iterator pi = boundary_vertices.begin();
const unsigned int N = boundary_vertices.size();
for (unsigned int i = 0; i < N; ++i, ++pi)
{
std::vector<bool>::const_iterator pj = pi + 1;
for (unsigned int j = i + 1; j < N; ++j, ++pj)
if ((*pi == true) && (*pj == true) &&
((vertices[i] - vertices[j]).norm_square() > max_distance_sqr))
max_distance_sqr = (vertices[i] - vertices[j]).norm_square();
}
return std::sqrt(max_distance_sqr);
}
template <int dim, int spacedim>
double
volume(const Triangulation<dim, spacedim> &triangulation,
const Mapping<dim, spacedim> & mapping)
{
// get the degree of the mapping if possible. if not, just assume 1
unsigned int mapping_degree = 1;
if (const auto *p = dynamic_cast<const MappingQ<dim, spacedim> *>(&mapping))
mapping_degree = p->get_degree();
else if (const auto *p =
dynamic_cast<const MappingQ<dim, spacedim> *>(&mapping))
mapping_degree = p->get_degree();
// then initialize an appropriate quadrature formula
const QGauss<dim> quadrature_formula(mapping_degree + 1);
const unsigned int n_q_points = quadrature_formula.size();
// we really want the JxW values from the FEValues object, but it
// wants a finite element. create a cheap element as a dummy
// element
FE_Nothing<dim, spacedim> dummy_fe;
FEValues<dim, spacedim> fe_values(mapping,
dummy_fe,
quadrature_formula,
update_JxW_values);
typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active(),
endc = triangulation.end();
double local_volume = 0;
// compute the integral quantities by quadrature
for (; cell != endc; ++cell)
if (cell->is_locally_owned())
{
fe_values.reinit(cell);
for (unsigned int q = 0; q < n_q_points; ++q)
local_volume += fe_values.JxW(q);
}
double global_volume = 0;
#ifdef DEAL_II_WITH_MPI
if (const parallel::TriangulationBase<dim, spacedim> *p_tria =
dynamic_cast<const parallel::TriangulationBase<dim, spacedim> *>(
&triangulation))
global_volume =
Utilities::MPI::sum(local_volume, p_tria->get_communicator());
else
#endif
global_volume = local_volume;
return global_volume;
}
namespace
{
/**
* The algorithm to compute the affine approximation to a cell finds an
* affine map A x_hat + b from the reference cell to the real space.
*
* Some details about how we compute the least square plane. We look
* for a spacedim x (dim + 1) matrix X such that X * M = Y where M is
* a (dim+1) x n_vertices matrix and Y a spacedim x n_vertices. And:
* The i-th column of M is unit_vertex[i] and the last row all
* 1's. The i-th column of Y is real_vertex[i]. If we split X=[A|b],
* the least square approx is A x_hat+b Classically X = Y * (M^t (M
* M^t)^{-1}) Let K = M^t * (M M^t)^{-1} = [KA Kb] this can be
* precomputed, and that is exactly what we do. Finally A = Y*KA and
* b = Y*Kb.
*/
template <int dim>
struct TransformR2UAffine
{
static const double KA[GeometryInfo<dim>::vertices_per_cell][dim];
static const double Kb[GeometryInfo<dim>::vertices_per_cell];
};
/*
Octave code:
M=[0 1; 1 1];
K1 = transpose(M) * inverse (M*transpose(M));
printf ("{%f, %f},\n", K1' );
*/
template <>
const double TransformR2UAffine<1>::KA[GeometryInfo<1>::vertices_per_cell]
[1] = {{-1.000000}, {1.000000}};
template <>
const double TransformR2UAffine<1>::Kb[GeometryInfo<1>::vertices_per_cell] =
{1.000000, 0.000000};
/*
Octave code:
M=[0 1 0 1;0 0 1 1;1 1 1 1];
K2 = transpose(M) * inverse (M*transpose(M));
printf ("{%f, %f, %f},\n", K2' );
*/
template <>
const double TransformR2UAffine<2>::KA[GeometryInfo<2>::vertices_per_cell]
[2] = {{-0.500000, -0.500000},
{0.500000, -0.500000},
{-0.500000, 0.500000},
{0.500000, 0.500000}};
/*
Octave code:
M=[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1; 0 0 0 0 1 1 1 1; 1 1 1 1 1 1 1 1];
K3 = transpose(M) * inverse (M*transpose(M))
printf ("{%f, %f, %f, %f},\n", K3' );
*/
template <>
const double TransformR2UAffine<2>::Kb[GeometryInfo<2>::vertices_per_cell] =
{0.750000, 0.250000, 0.250000, -0.250000};
template <>
const double TransformR2UAffine<3>::KA[GeometryInfo<3>::vertices_per_cell]
[3] = {
{-0.250000, -0.250000, -0.250000},
{0.250000, -0.250000, -0.250000},
{-0.250000, 0.250000, -0.250000},
{0.250000, 0.250000, -0.250000},
{-0.250000, -0.250000, 0.250000},
{0.250000, -0.250000, 0.250000},
{-0.250000, 0.250000, 0.250000},
{0.250000, 0.250000, 0.250000}
};
template <>
const double TransformR2UAffine<3>::Kb[GeometryInfo<3>::vertices_per_cell] =
{0.500000,
0.250000,
0.250000,
0.000000,
0.250000,
0.000000,
0.000000,
-0.250000};
} // namespace
template <int dim, int spacedim>
std::pair<DerivativeForm<1, dim, spacedim>, Tensor<1, spacedim>>
affine_cell_approximation(const ArrayView<const Point<spacedim>> &vertices)
{
AssertDimension(vertices.size(), GeometryInfo<dim>::vertices_per_cell);
// A = vertex * KA
DerivativeForm<1, dim, spacedim> A;
for (unsigned int d = 0; d < spacedim; ++d)
for (unsigned int v = 0; v < GeometryInfo<dim>::vertices_per_cell; ++v)
for (unsigned int e = 0; e < dim; ++e)
A[d][e] += vertices[v][d] * TransformR2UAffine<dim>::KA[v][e];
// b = vertex * Kb
Tensor<1, spacedim> b;
for (unsigned int v = 0; v < GeometryInfo<dim>::vertices_per_cell; ++v)
b += vertices[v] * TransformR2UAffine<dim>::Kb[v];
return std::make_pair(A, b);
}
template <int dim>
Vector<double>
compute_aspect_ratio_of_cells(const Mapping<dim> & mapping,
const Triangulation<dim> &triangulation,
const Quadrature<dim> & quadrature)
{
FE_Nothing<dim> fe;
FEValues<dim> fe_values(mapping, fe, quadrature, update_jacobians);
Vector<double> aspect_ratio_vector(triangulation.n_active_cells());
// loop over cells of processor
for (const auto &cell : triangulation.active_cell_iterators())
{
if (cell->is_locally_owned())
{
double aspect_ratio_cell = 0.0;
fe_values.reinit(cell);
// loop over quadrature points
for (unsigned int q = 0; q < quadrature.size(); ++q)
{
const Tensor<2, dim, double> jacobian =
Tensor<2, dim, double>(fe_values.jacobian(q));
// We intentionally do not want to throw an exception in case of
// inverted elements since this is not the task of this
// function. Instead, inf is written into the vector in case of
// inverted elements.
if (determinant(jacobian) <= 0)
{
aspect_ratio_cell = std::numeric_limits<double>::infinity();
}
else
{
LAPACKFullMatrix<double> J = LAPACKFullMatrix<double>(dim);
for (unsigned int i = 0; i < dim; ++i)
for (unsigned int j = 0; j < dim; ++j)
J(i, j) = jacobian[i][j];
J.compute_svd();
double const max_sv = J.singular_value(0);
double const min_sv = J.singular_value(dim - 1);
double const ar = max_sv / min_sv;
// Take the max between the previous and the current
// aspect ratio value; if we had previously encountered
// an inverted cell, we will have placed an infinity
// in the aspect_ratio_cell variable, and that value
// will survive this max operation.
aspect_ratio_cell = std::max(aspect_ratio_cell, ar);
}
}
// fill vector
aspect_ratio_vector(cell->active_cell_index()) = aspect_ratio_cell;
}
}
return aspect_ratio_vector;
}
template <int dim>
double
compute_maximum_aspect_ratio(const Mapping<dim> & mapping,
const Triangulation<dim> &triangulation,
const Quadrature<dim> & quadrature)
{
Vector<double> aspect_ratio_vector =
compute_aspect_ratio_of_cells(mapping, triangulation, quadrature);
return VectorTools::compute_global_error(triangulation,
aspect_ratio_vector,
VectorTools::Linfty_norm);
}
template <int dim, int spacedim>
BoundingBox<spacedim>
compute_bounding_box(const Triangulation<dim, spacedim> &tria)
{
using iterator =
typename Triangulation<dim, spacedim>::active_cell_iterator;
const auto predicate = [](const iterator &) { return true; };
return compute_bounding_box(
tria, std::function<bool(const iterator &)>(predicate));
}
// Generic functions for appending face data in 2D or 3D. TODO: we can
// remove these once we have 'if constexpr'.
namespace internal
{
inline void
append_face_data(const CellData<1> &face_data, SubCellData &subcell_data)
{
subcell_data.boundary_lines.push_back(face_data);
}
inline void
append_face_data(const CellData<2> &face_data, SubCellData &subcell_data)
{
subcell_data.boundary_quads.push_back(face_data);
}
// Lexical comparison for sorting CellData objects.
template <int structdim>
struct CellDataComparator
{
bool
operator()(const CellData<structdim> &a,
const CellData<structdim> &b) const
{
// Check vertices:
if (std::lexicographical_compare(std::begin(a.vertices),
std::end(a.vertices),
std::begin(b.vertices),
std::end(b.vertices)))
return true;
// it should never be necessary to check the material or manifold
// ids as a 'tiebreaker' (since they must be equal if the vertex
// indices are equal). Assert it anyway:
#ifdef DEBUG
if (std::equal(std::begin(a.vertices),
std::end(a.vertices),
std::begin(b.vertices)))
{
Assert(a.material_id == b.material_id &&
a.manifold_id == b.manifold_id,
ExcMessage(
"Two CellData objects with equal vertices must "
"have the same material/boundary ids and manifold "
"ids."));
}
#endif
return false;
}
};
/**
* get_coarse_mesh_description() needs to store face data for dim>1, but
* we can not have this code in the function, as this requires either an
* instantiation of CellData<dim-1>, or constexpr if. We use a class with
* specialization instead for now.
*
* Data on faces is added with insert_face_data() and then retrieved with
* get().
*/
template <int dim>
class FaceDataHelper
{
public:
/**
* Store the data about the given face @p face.
*/
template <class FaceIteratorType>
void
insert_face_data(const FaceIteratorType &face)
{
CellData<dim - 1> face_cell_data;
for (unsigned int vertex_n = 0; vertex_n < face->n_vertices();
++vertex_n)
face_cell_data.vertices[vertex_n] = face->vertex_index(vertex_n);
face_cell_data.boundary_id = face->boundary_id();
face_cell_data.manifold_id = face->manifold_id();
face_data.insert(face_cell_data);
}
/**
* Return the @p subcell_data with the stored information.
*/
SubCellData
get()
{
SubCellData subcell_data;
for (const CellData<dim - 1> &face_cell_data : face_data)
internal::append_face_data(face_cell_data, subcell_data);
return subcell_data;
}
private:
std::set<CellData<dim - 1>, internal::CellDataComparator<dim - 1>>
face_data;
};
// Do nothing for dim=1:
template <>
class FaceDataHelper<1>
{
public:
template <class FaceIteratorType>
void
insert_face_data(const FaceIteratorType &)
{}
SubCellData
get()
{
return SubCellData();
}
};
} // namespace internal
template <int dim, int spacedim>
std::
tuple<std::vector<Point<spacedim>>, std::vector<CellData<dim>>, SubCellData>
get_coarse_mesh_description(const Triangulation<dim, spacedim> &tria)
{
Assert(1 <= tria.n_levels(),
ExcMessage("The input triangulation must be non-empty."));
std::vector<Point<spacedim>> vertices;
std::vector<CellData<dim>> cells;
unsigned int max_level_0_vertex_n = 0;
for (const auto &cell : tria.cell_iterators_on_level(0))
for (const unsigned int cell_vertex_n : cell->vertex_indices())
max_level_0_vertex_n =
std::max(cell->vertex_index(cell_vertex_n), max_level_0_vertex_n);
vertices.resize(max_level_0_vertex_n + 1);
internal::FaceDataHelper<dim> face_data;
std::set<CellData<1>, internal::CellDataComparator<1>>
line_data; // only used in 3D
for (const auto &cell : tria.cell_iterators_on_level(0))
{
// Save cell data
CellData<dim> cell_data(cell->n_vertices());
for (const unsigned int cell_vertex_n : cell->vertex_indices())
{
Assert(cell->vertex_index(cell_vertex_n) < vertices.size(),
ExcInternalError());
vertices[cell->vertex_index(cell_vertex_n)] =
cell->vertex(cell_vertex_n);
cell_data.vertices[cell_vertex_n] =
cell->vertex_index(cell_vertex_n);
}
cell_data.material_id = cell->material_id();
cell_data.manifold_id = cell->manifold_id();
cells.push_back(cell_data);
// Save face data
if (dim > 1)
{
for (const unsigned int face_n : cell->face_indices())
face_data.insert_face_data(cell->face(face_n));
}
// Save line data
if (dim == 3)
{
for (unsigned int line_n = 0; line_n < cell->n_lines(); ++line_n)
{
const auto line = cell->line(line_n);
CellData<1> line_cell_data;
for (unsigned int vertex_n = 0; vertex_n < line->n_vertices();
++vertex_n)
line_cell_data.vertices[vertex_n] =
line->vertex_index(vertex_n);
line_cell_data.boundary_id = line->boundary_id();
line_cell_data.manifold_id = line->manifold_id();
line_data.insert(line_cell_data);
}
}
}
// Double-check that there are no unused vertices:
#ifdef DEBUG
{
std::vector<bool> used_vertices(vertices.size());
for (const CellData<dim> &cell_data : cells)
for (const auto v : cell_data.vertices)
used_vertices[v] = true;
Assert(std::find(used_vertices.begin(), used_vertices.end(), false) ==
used_vertices.end(),
ExcMessage("The level zero vertices should form a contiguous "
"range."));
}
#endif
SubCellData subcell_data = face_data.get();
if (dim == 3)
for (const CellData<1> &face_line_data : line_data)
subcell_data.boundary_lines.push_back(face_line_data);
return std::tuple<std::vector<Point<spacedim>>,
std::vector<CellData<dim>>,
SubCellData>(std::move(vertices),
std::move(cells),
std::move(subcell_data));
}
template <int dim, int spacedim>
void
delete_unused_vertices(std::vector<Point<spacedim>> &vertices,
std::vector<CellData<dim>> & cells,
SubCellData & subcelldata)
{
Assert(
subcelldata.check_consistency(dim),
ExcMessage(
"Invalid SubCellData supplied according to ::check_consistency(). "
"This is caused by data containing objects for the wrong dimension."));
// first check which vertices are actually used
std::vector<bool> vertex_used(vertices.size(), false);
for (unsigned int c = 0; c < cells.size(); ++c)
for (unsigned int v = 0; v < cells[c].vertices.size(); ++v)
{
Assert(cells[c].vertices[v] < vertices.size(),
ExcMessage("Invalid vertex index encountered! cells[" +
Utilities::int_to_string(c) + "].vertices[" +
Utilities::int_to_string(v) + "]=" +
Utilities::int_to_string(cells[c].vertices[v]) +
" is invalid, because only " +
Utilities::int_to_string(vertices.size()) +
" vertices were supplied."));
vertex_used[cells[c].vertices[v]] = true;
}
// then renumber the vertices that are actually used in the same order as
// they were beforehand
const unsigned int invalid_vertex = numbers::invalid_unsigned_int;
std::vector<unsigned int> new_vertex_numbers(vertices.size(),
invalid_vertex);
unsigned int next_free_number = 0;
for (unsigned int i = 0; i < vertices.size(); ++i)
if (vertex_used[i] == true)
{
new_vertex_numbers[i] = next_free_number;
++next_free_number;
}
// next replace old vertex numbers by the new ones
for (unsigned int c = 0; c < cells.size(); ++c)
for (auto &v : cells[c].vertices)
v = new_vertex_numbers[v];
// same for boundary data
for (unsigned int c = 0; c < subcelldata.boundary_lines.size(); // NOLINT
++c)
for (unsigned int v = 0;
v < subcelldata.boundary_lines[c].vertices.size();
++v)
{
Assert(subcelldata.boundary_lines[c].vertices[v] <
new_vertex_numbers.size(),
ExcMessage(
"Invalid vertex index in subcelldata.boundary_lines. "
"subcelldata.boundary_lines[" +
Utilities::int_to_string(c) + "].vertices[" +
Utilities::int_to_string(v) + "]=" +
Utilities::int_to_string(
subcelldata.boundary_lines[c].vertices[v]) +
" is invalid, because only " +
Utilities::int_to_string(vertices.size()) +
" vertices were supplied."));
subcelldata.boundary_lines[c].vertices[v] =
new_vertex_numbers[subcelldata.boundary_lines[c].vertices[v]];
}
for (unsigned int c = 0; c < subcelldata.boundary_quads.size(); // NOLINT
++c)
for (unsigned int v = 0;
v < subcelldata.boundary_quads[c].vertices.size();
++v)
{
Assert(subcelldata.boundary_quads[c].vertices[v] <
new_vertex_numbers.size(),
ExcMessage(
"Invalid vertex index in subcelldata.boundary_quads. "
"subcelldata.boundary_quads[" +
Utilities::int_to_string(c) + "].vertices[" +
Utilities::int_to_string(v) + "]=" +
Utilities::int_to_string(
subcelldata.boundary_quads[c].vertices[v]) +
" is invalid, because only " +
Utilities::int_to_string(vertices.size()) +
" vertices were supplied."));
subcelldata.boundary_quads[c].vertices[v] =
new_vertex_numbers[subcelldata.boundary_quads[c].vertices[v]];
}
// finally copy over the vertices which we really need to a new array and
// replace the old one by the new one
std::vector<Point<spacedim>> tmp;
tmp.reserve(std::count(vertex_used.begin(), vertex_used.end(), true));
for (unsigned int v = 0; v < vertices.size(); ++v)
if (vertex_used[v] == true)
tmp.push_back(vertices[v]);
swap(vertices, tmp);
}
template <int dim, int spacedim>
void
delete_duplicated_vertices(std::vector<Point<spacedim>> &vertices,
std::vector<CellData<dim>> & cells,
SubCellData & subcelldata,
std::vector<unsigned int> & considered_vertices,
const double tol)
{
AssertIndexRange(2, vertices.size());
// create a vector of vertex indices. initialize it to the identity, later
// on change that if necessary.
std::vector<unsigned int> new_vertex_numbers(vertices.size());
std::iota(new_vertex_numbers.begin(), new_vertex_numbers.end(), 0);
// if the considered_vertices vector is empty, consider all vertices
if (considered_vertices.size() == 0)
considered_vertices = new_vertex_numbers;
Assert(considered_vertices.size() <= vertices.size(), ExcInternalError());
// The algorithm below improves upon the naive O(n^2) algorithm by first
// sorting vertices by their value in one component and then only
// comparing vertices for equality which are nearly equal in that
// component. For example, if @p vertices form a cube, then we will only
// compare points that have the same x coordinate when we try to find
// duplicated vertices.
// Start by finding the longest coordinate direction. This minimizes the
// number of points that need to be compared against each-other in a
// single set for typical geometries.
const BoundingBox<spacedim> bbox(vertices);
const auto & min = bbox.get_boundary_points().first;
const auto & max = bbox.get_boundary_points().second;
unsigned int longest_coordinate_direction = 0;
double longest_coordinate_length = max[0] - min[0];
for (unsigned int d = 1; d < spacedim; ++d)
{
const double coordinate_length = max[d] - min[d];
if (longest_coordinate_length < coordinate_length)
{
longest_coordinate_length = coordinate_length;
longest_coordinate_direction = d;
}
}
// Sort vertices (while preserving their vertex numbers) along that
// coordinate direction:
std::vector<std::pair<unsigned int, Point<spacedim>>> sorted_vertices;
sorted_vertices.reserve(vertices.size());
for (const unsigned int vertex_n : considered_vertices)
{
AssertIndexRange(vertex_n, vertices.size());
sorted_vertices.emplace_back(vertex_n, vertices[vertex_n]);
}
std::sort(sorted_vertices.begin(),
sorted_vertices.end(),
[&](const std::pair<unsigned int, Point<spacedim>> &a,
const std::pair<unsigned int, Point<spacedim>> &b) {
return a.second[longest_coordinate_direction] <
b.second[longest_coordinate_direction];
});
auto within_tolerance = [=](const Point<spacedim> &a,
const Point<spacedim> &b) {
for (unsigned int d = 0; d < spacedim; ++d)
if (std::abs(a[d] - b[d]) > tol)
return false;
return true;
};
// Find a range of numbers that have the same component in the longest
// coordinate direction:
auto range_start = sorted_vertices.begin();
while (range_start != sorted_vertices.end())
{
auto range_end = range_start + 1;
while (range_end != sorted_vertices.end() &&
std::abs(range_end->second[longest_coordinate_direction] -
range_start->second[longest_coordinate_direction]) <
tol)
++range_end;
// preserve behavior with older versions of this function by replacing
// higher vertex numbers by lower vertex numbers
std::sort(range_start,
range_end,
[](const std::pair<unsigned int, Point<spacedim>> &a,
const std::pair<unsigned int, Point<spacedim>> &b) {
return a.first < b.first;
});
// Now de-duplicate [range_start, range_end)
//
// We have identified all points that are within a strip of width 'tol'
// in one coordinate direction. Now we need to figure out which of these
// are also close in other coordinate directions. If two are close, we
// can mark the second one for deletion.
for (auto reference = range_start; reference != range_end; ++reference)
{
if (reference->first != numbers::invalid_unsigned_int)
for (auto it = reference + 1; it != range_end; ++it)
{
if (within_tolerance(reference->second, it->second))
{
new_vertex_numbers[it->first] = reference->first;
// skip the replaced vertex in the future
it->first = numbers::invalid_unsigned_int;
}
}
}
range_start = range_end;
}
// now we got a renumbering list. simply renumber all vertices
// (non-duplicate vertices get renumbered to themselves, so nothing bad
// happens). after that, the duplicate vertices will be unused, so call
// delete_unused_vertices() to do that part of the job.
for (auto &cell : cells)
for (auto &vertex_index : cell.vertices)
vertex_index = new_vertex_numbers[vertex_index];
for (auto &quad : subcelldata.boundary_quads)
for (auto &vertex_index : quad.vertices)
vertex_index = new_vertex_numbers[vertex_index];
for (auto &line : subcelldata.boundary_lines)
for (auto &vertex_index : line.vertices)
vertex_index = new_vertex_numbers[vertex_index];
delete_unused_vertices(vertices, cells, subcelldata);
}
template <int dim, int spacedim>
void
invert_all_negative_measure_cells(
const std::vector<Point<spacedim>> &all_vertices,
std::vector<CellData<dim>> & cells)
{
if (dim == 1)
return;
if (dim == 2 && spacedim == 3)
Assert(false, ExcNotImplemented());
std::size_t n_negative_cells = 0;
for (auto &cell : cells)
{
Assert(cell.vertices.size() ==
ReferenceCells::get_hypercube<dim>().n_vertices(),
ExcNotImplemented());
const ArrayView<const unsigned int> vertices(cell.vertices);
if (GridTools::cell_measure(all_vertices, vertices) < 0)
{
++n_negative_cells;
// TODO: this only works for quads and hexes
if (dim == 2)
{
// flip the cell across the y = x line in 2D
std::swap(cell.vertices[1], cell.vertices[2]);
}
else if (dim == 3)
{
// swap the front and back faces in 3D
std::swap(cell.vertices[0], cell.vertices[2]);
std::swap(cell.vertices[1], cell.vertices[3]);
std::swap(cell.vertices[4], cell.vertices[6]);
std::swap(cell.vertices[5], cell.vertices[7]);
}
// Check whether the resulting cell is now ok.
// If not, then the grid is seriously broken and
// we just give up.
AssertThrow(GridTools::cell_measure(all_vertices, vertices) > 0,
ExcInternalError());
}
}
// We assume that all cells of a grid have
// either positive or negative volumes but
// not both mixed. Although above reordering
// might work also on single cells, grids
// with both kind of cells are very likely to
// be broken. Check for this here.
AssertThrow(n_negative_cells == 0 || n_negative_cells == cells.size(),
ExcMessage(
std::string(
"This function assumes that either all cells have positive "
"volume, or that all cells have been specified in an "
"inverted vertex order so that their volume is negative. "
"(In the latter case, this class automatically inverts "
"every cell.) However, the mesh you have specified "
"appears to have both cells with positive and cells with "
"negative volume. You need to check your mesh which "
"cells these are and how they got there.\n"
"As a hint, of the total ") +
std::to_string(cells.size()) + " cells in the mesh, " +
std::to_string(n_negative_cells) +
" appear to have a negative volume."));
}
// Functions and classes for consistently_order_cells
namespace
{
/**
* A simple data structure denoting an edge, i.e., the ordered pair
* of its vertex indices. This is only used in the is_consistent()
* function.
*/
struct CheapEdge
{
/**
* Construct an edge from the global indices of its two vertices.
*/
CheapEdge(const unsigned int v0, const unsigned int v1)
: v0(v0)
, v1(v1)
{}
/**
* Comparison operator for edges. It compares based on the
* lexicographic ordering of the two vertex indices.
*/
bool
operator<(const CheapEdge &e) const
{
return ((v0 < e.v0) || ((v0 == e.v0) && (v1 < e.v1)));
}
private:
/**
* The global indices of the vertices that define the edge.
*/
const unsigned int v0, v1;
};
/**
* A function that determines whether the edges in a mesh are
* already consistently oriented. It does so by adding all edges
* of all cells into a set (which automatically eliminates
* duplicates) but before that checks whether the reverse edge is
* already in the set -- which would imply that a neighboring cell
* is inconsistently oriented.
*/
template <int dim>
bool
is_consistent(const std::vector<CellData<dim>> &cells)
{
std::set<CheapEdge> edges;
for (typename std::vector<CellData<dim>>::const_iterator c =
cells.begin();
c != cells.end();
++c)
{
// construct the edges in reverse order. for each of them,
// ensure that the reverse edge is not yet in the list of
// edges (return false if the reverse edge already *is* in
// the list) and then add the actual edge to it; std::set
// eliminates duplicates automatically
for (unsigned int l = 0; l < GeometryInfo<dim>::lines_per_cell; ++l)
{
const CheapEdge reverse_edge(
c->vertices[GeometryInfo<dim>::line_to_cell_vertices(l, 1)],
c->vertices[GeometryInfo<dim>::line_to_cell_vertices(l, 0)]);
if (edges.find(reverse_edge) != edges.end())
return false;
// ok, not. insert edge in correct order
const CheapEdge correct_edge(
c->vertices[GeometryInfo<dim>::line_to_cell_vertices(l, 0)],