libMesh
Loading...
Searching...
No Matches
periodic_bc_test.C
Go to the documentation of this file.
1#include <libmesh/default_coupling.h>
2#include <libmesh/dirichlet_boundaries.h>
3#include <libmesh/distributed_mesh.h>
4#include <libmesh/dof_map.h>
5#include <libmesh/elem.h>
6#include <libmesh/equation_systems.h>
7#include <libmesh/exodusII_io.h>
8#include <libmesh/function_base.h>
9#include <libmesh/linear_implicit_system.h>
10#include <libmesh/partitioner.h>
11#include <libmesh/mesh.h>
12#include <libmesh/mesh_generation.h>
13#include <libmesh/numeric_vector.h>
14#include <libmesh/periodic_boundary.h>
15#include <libmesh/quadrature_gauss.h>
16#include <libmesh/sparse_matrix.h>
17#include <libmesh/wrapped_function.h>
18
19#include "test_comm.h"
20#include "libmesh_cppunit.h"
21
22
23using namespace libMesh;
24
25
26
28 const Parameters&,
29 const std::string&,
30 const std::string&)
31{
32 const Real & y = LIBMESH_DIM > 1 ? p(1) : 0;
33
34 // Discontinuity at y=1 from the forcing function there.
35 // Periodic on -3 < y < 2
36 return (y > 1) ? (y-3)*(y-3) : (y+1)*(y+1);
37}
38
39
40
41struct PeriodicQuadFunction : public FunctionBase<Number>
42{
44
45 virtual std::unique_ptr<FunctionBase<Number>> clone () const
46 { return std::make_unique<PeriodicQuadFunction>(); }
47
48 // We only really need the vector-valued output for projections
49 virtual Number operator() (const Point &,
50 const Real /*time*/ = 0.) override
51 { libmesh_error(); }
52
53 virtual void operator() (const Point & p,
54 const Real,
55 DenseVector<Number> & output) override
56 {
57 libmesh_assert_equal_to(output.size(), 1);
58 Parameters params;
59 output(0) = quadratic_solution(p, params, "", "");
60 }
61
62 Number component (unsigned int i,
63 const Point & p,
64 Real /* time */) override
65 {
66 Parameters params;
67 switch (i) {
68 case 0:
69 return quadratic_solution(p, params, "", "");
70 default:
71 libmesh_error();
72 }
73 return 0;
74 }
75};
76
77
79 const std::string&)
80{
81 const MeshBase& mesh = es.get_mesh();
83 const DofMap& dof_map = system.get_dof_map();
84
85 // Interior FE to integrate smooth part of poisson problem
86 FEType fe_type = dof_map.variable_type(0);
87 std::unique_ptr<FEBase> fe (FEBase::build(2, fe_type));
88 QGauss qrule (2, fe_type.default_quadrature_order());
89 fe->attach_quadrature_rule(&qrule);
90
91 const std::vector<Real> & JxW = fe->get_JxW();
92 const std::vector<std::vector<Real>> & phi = fe->get_phi();
93 const std::vector<std::vector<RealGradient>> & dphi = fe->get_dphi();
94
95 // Face FE to integrate delta function part of forcing
96 std::unique_ptr<FEBase> fe_face (FEBase::build(2, fe_type));
97 QGauss qface (1, fe_type.default_quadrature_order());
98 fe_face->attach_quadrature_rule(&qface);
99
100 const std::vector<Real> & JxW_face = fe_face->get_JxW();
101 const std::vector<std::vector<Real>> & phi_face = fe_face->get_phi();
102 std::unique_ptr<const Elem> elem_side;
103
106
107 std::vector<dof_id_type> dof_indices;
108
109 for (const Elem * elem : mesh.active_local_element_ptr_range())
110 {
111 dof_map.dof_indices (elem, dof_indices);
112 const unsigned int n_dofs = dof_indices.size();
113
114 Ke.resize (n_dofs, n_dofs);
115 Fe.resize (n_dofs);
116
117 fe->reinit (elem);
118
119 // Integrate the poisson problem over the element interior, where we have
120 // a nice f=2 forcing function aside from the discontinuity
121 for (unsigned int qp=0; qp<qrule.n_points(); qp++)
122 {
123 for (unsigned int i=0; i != n_dofs; i++)
124 {
125 for (unsigned int j=0; j != n_dofs; j++)
126 Ke(i,j) += -JxW[qp]*(dphi[i][qp]*dphi[j][qp]);
127
128 Fe(i) += JxW[qp]*phi[i][qp]*2;
129 }
130 }
131
132 for(unsigned int s=0; s != elem->n_sides(); ++s)
133 {
134 elem->build_side_ptr(elem_side, s);
135 Point centroid = elem_side->vertex_average();
136 if (std::abs(centroid(1) - 1) < TOLERANCE)
137 {
138 fe_face->reinit(elem, s);
139
140 for (unsigned int qp=0; qp<qface.n_points(); qp++)
141 {
142 // delta function divided by 2 since we hit it from
143 // both sides
144 for (unsigned int i=0; i != n_dofs; i++)
145 Fe(i) += JxW_face[qp]*phi_face[i][qp]*(-4);
146 }
147 }
148 }
149
150 dof_map.heterogenously_constrain_element_matrix_and_vector(Ke, Fe, dof_indices);
151 system.matrix->add_matrix (Ke, dof_indices);
152 system.rhs->add_vector (Fe, dof_indices);
153 }
154
155 system.rhs->close();
156 system.matrix->close();
157}
158
159
160// Assigns the element rows of an 8-row unit square to processors 0
161// and 1. At first processor 1 owns only row 2. With two layers of
162// ghosting it then holds the bottom row 0 but not the top row 7, which
163// is the periodic image of row 0. The repartitioned assignment also
164// gives row 0 to processor 1.
166{
167public:
168 RowPartitioner (bool repartitioned) : _repartitioned(repartitioned) {}
169
170 std::unique_ptr<Partitioner> clone () const override
171 { return std::make_unique<RowPartitioner>(*this); }
172
173protected:
174 void _do_partition (MeshBase & mesh, const unsigned int) override
175 {
176 for (auto & elem : mesh.active_element_ptr_range())
177 {
178 const auto row = static_cast<unsigned int>(elem->vertex_average()(1) * 8);
179 const bool on_proc_1 = _repartitioned ? (row == 0 || row == 2) : (row == 2);
180 elem->processor_id() = on_proc_1;
181 }
182 }
183
184private:
186};
187
188
192
193
194class PeriodicBCTest : public CppUnit::TestCase {
195public:
197
198#if LIBMESH_DIM > 1
199#if defined(LIBMESH_HAVE_SOLVER) && defined(LIBMESH_HAVE_EXODUS_API) && defined(LIBMESH_HAVE_GZSTREAM)
201#endif
205#endif // LIBMESH_DIM > 1
206
208
209private:
210
211 void testPeriodicBC (FEType fe_type)
212 {
214 BoundaryInfo & boundary = mesh.get_boundary_info();
215
218 es.add_system<LinearImplicitSystem> ("PBCSys");
219
220 // We need to change around BCIDs and set up the periodic BC first
222
223 mesh.read("meshes/shark_tooth_tri6.xda.gz");
224
225 // Add some BCIDs on top and bottom for our periodic boundary
226 for (const Elem * elem : mesh.active_element_ptr_range())
227 {
228 for (unsigned int s=0; s != 3; ++s)
229 if (!elem->neighbor_ptr(s))
230 {
231 unsigned v2 = (s+1)%3;
232 // Left-running edges are on bottom, because this xda
233 // has a flipped mesh
234 if (elem->point(s)(0) - elem->point(v2)(0) < -.1)
235 boundary.add_side(elem, s, top_id);
236
237 // Right-running edges are on top
238 else if (elem->point(s)(0) - elem->point(v2)(0) > .1)
239 boundary.add_side(elem, s, bottom_id);
240
241 // Vertical edges are Dirichlet
242 else
243 boundary.add_side(elem, s, side_id);
244 }
245 }
246
247 PeriodicBoundary vert(RealVectorValue(0., 4.0));
248 vert.myboundary = bottom_id;
249 vert.pairedboundary = top_id;
251
252 // Okay, *now* the mesh knows to save periodic neighbors
255
256 const unsigned int u_var = sys.add_variable("u", fe_type);
258
259 std::set<boundary_id_type> side_bdy { side_id };
260 std::vector<unsigned int> all_vars (1, u_var);
262 DirichletBoundary exact_bc(side_bdy, all_vars, exact_val);
263 sys.get_dof_map().add_dirichlet_boundary(exact_bc);
264
265 es.init();
266
267 sys.solve();
268
269 ExodusII_IO(mesh).write_equation_systems("periodic.e", es);
270
271 Parameters params;
272
273 for (Real x = 0.1; x < 10; x += 0.2)
274 for (Real ya = -2.9; ya < 1; ya += 0.2)
275 {
276 // Integrate the sharktooth shape
277 const Real offset = 1-std::abs(std::fmod(x,2)-1);
278 const Real y = ya + offset;
279 Point p{x,y};
280 const Number exact = quadratic_solution(p,params,"","");
281 const Number approx = sys.point_value(0,p);
282 LIBMESH_ASSERT_NUMBERS_EQUAL(exact, approx,
284 }
285 }
286
287
288 // Repartition a distributed periodic mesh so that a processor takes
289 // ownership of an element it only ghosted, before that element's
290 // periodic neighbor arrives.
292 {
293 LOG_UNIT_TEST;
294
295 // Repartitioning moves elements only between processors 0 and 1
296 if (TestCommWorld->size() < 2)
297 return;
298
300 mesh.partitioner() = std::make_unique<RowPartitioner>(false);
301
303 System & sys = es.add_system<System>("PBCSys");
304 sys.add_variable("u", FEType(FIRST, LAGRANGE));
305
306 // build_square() numbers the bottom and top sides 0 and 2
307 PeriodicBoundary vert(RealVectorValue(0., 1.));
308 vert.myboundary = 0;
309 vert.pairedboundary = 2;
311
312 // When processor 1 finds what processor 0 needs, the first layer
313 // reaches from row 1 into row 0. The second layer then asks for
314 // the periodic neighbor of row 0, which processor 1 does not have.
315 auto two_layers = std::make_shared<DefaultCoupling>();
316 two_layers->set_mesh(&mesh);
317 two_layers->set_n_levels(2);
318 two_layers->set_periodic_boundaries(sys.get_dof_map().get_periodic_boundaries());
319 mesh.add_ghosting_functor(two_layers);
320
321 MeshTools::Generation::build_square(mesh, 4, 8, 0., 1., 0., 1., QUAD4);
322 es.init();
323
324 mesh.partitioner() = std::make_unique<RowPartitioner>(true);
325 mesh.partition();
326
327 CPPUNIT_ASSERT(!mesh.is_redistributing());
328 for (const auto & elem : mesh.active_local_element_ptr_range())
329 {
330 const auto row = static_cast<unsigned int>(elem->vertex_average()(1) * 8);
331 CPPUNIT_ASSERT_EQUAL(processor_id_type(row == 0 || row == 2), elem->processor_id());
332 }
333 }
334
335 // Project a function that is not periodic in x onto a side-only
336 // space with x-periodic constraints. The constrained traces on the
337 // left side must equal the traces on the right side, and each must
338 // reproduce one side's data exactly.
339 void testPeriodicSideHierarchic(const ElemType elem_type, const Order order)
340 {
343 System & sys = es.add_system<System>("PBCSys");
344 sys.add_variable("u", FEType(order, SIDE_HIERARCHIC));
345
346 // build_square() numbers the right and left sides 1 and 3
347 PeriodicBoundary horz(RealVectorValue(1., 0.));
348 horz.myboundary = 3;
349 horz.pairedboundary = 1;
351
352 MeshTools::Generation::build_square(mesh, 3, 3, 0., 1., 0., 1., elem_type);
353 es.init();
354
355 // The trace space holds y^2 exactly at order >= 2
356 auto f = +[](const Point & p, const Parameters &, const std::string &, const std::string &)
357 -> Number { return p(0) + p(1) * p(1); };
358 sys.project_solution(f, nullptr, es.parameters);
359
360 for (Real y = 0.05; y < 1; y += 0.1)
361 {
362 const Number left = sys.point_value(0, Point(0., y));
363 const Number right = sys.point_value(0, Point(1., y));
364 LIBMESH_ASSERT_NUMBERS_EQUAL(left, right, TOLERANCE*TOLERANCE);
365 const Real err = std::min(std::abs(left - y * y), std::abs(left - Real(1) - y * y));
366 LIBMESH_ASSERT_FP_EQUAL(0, err, TOLERANCE*TOLERANCE);
367 }
368 }
369
372
374};
375
void testPeriodicSideHierarchicQuad9()
void testPeriodicBC(FEType fe_type)
CPPUNIT_TEST(testPeriodicLagrange2)
void testRedistributeToGhosts()
void testPeriodicSideHierarchic(const ElemType elem_type, const Order order)
void testPeriodicSideHierarchicTri6()
LIBMESH_CPPUNIT_TEST_SUITE(PeriodicBCTest)
CPPUNIT_TEST(testPeriodicSideHierarchicQuad9)
CPPUNIT_TEST(testPeriodicSideHierarchicTri6)
CPPUNIT_TEST(testRedistributeToGhosts)
void _do_partition(MeshBase &mesh, const unsigned int) override
This is the actual partitioning method which must be overridden in derived classes.
std::unique_ptr< Partitioner > clone() const override
RowPartitioner(bool repartitioned)
The BoundaryInfo class contains information relevant to boundary conditions including storing faces,...
void add_side(const dof_id_type elem, const unsigned short int side, const boundary_id_type id)
Add side side of element number elem with boundary id id to the boundary information data structure.
Defines a dense matrix for use in Finite Element-type computations.
void resize(const unsigned int new_m, const unsigned int new_n)
Resizes the matrix to the specified size and calls zero().
Defines a dense vector for use in Finite Element-type computations.
void resize(const unsigned int n)
Resize the vector.
virtual unsigned int size() const override final
This class allows one to associate Dirichlet boundary values with a given set of mesh boundary ids an...
The DistributedMesh class is derived from the MeshBase class, and is intended to provide identical fu...
This class handles the numbering of degrees of freedom on a mesh.
Definition dof_map.h:181
void add_dirichlet_boundary(const DirichletBoundary &dirichlet_boundary)
Adds a copy of the specified Dirichlet boundary to the system.
PeriodicBoundaries * get_periodic_boundaries()
Definition dof_map.h:1618
void add_periodic_boundary(const PeriodicBoundaryBase &periodic_boundary)
Adds a copy of the specified periodic boundary to the system.
This is the base class from which all geometric element types are derived.
Definition elem.h:96
This is the EquationSystems class.
const MeshBase & get_mesh() const
Parameters parameters
Data structure holding arbitrary parameters.
virtual void init()
Initialize all the systems.
virtual System & add_system(std::string_view system_type, std::string_view name)
Add the system of type system_type named name to the systems array.
const T_sys & get_system(std::string_view name) const
The ExodusII_IO class implements reading meshes in the ExodusII file format from Sandia National Labs...
Definition exodusII_io.h:53
virtual void write_equation_systems(const std::string &fname, const EquationSystems &es, const std::set< std::string > *system_names=nullptr) override
Writes out the solution for no specific time or timestep.
NumericVector< Number > * rhs
The system matrix.
static std::unique_ptr< FEGenericBase > build(const unsigned int dim, const FEType &type)
Builds a specific finite element type.
class FEType hides (possibly multiple) FEFamily and approximation orders, thereby enabling specialize...
Definition fe_type.h:197
Order default_quadrature_order() const
Definition fe_type.h:415
Base class for functors that can be evaluated at a point and (optionally) time.
SparseMatrix< Number > * matrix
The system matrix.
Manages consistently variables, degrees of freedom, coefficient vectors, matrices and linear solvers ...
virtual void solve() override
Assembles & solves the linear system A*x=b.
This is the MeshBase class.
Definition mesh_base.h:81
void allow_remote_element_removal(bool allow)
If false is passed in then this mesh will no longer have remote elements deleted when being prepared ...
Definition mesh_base.h:1390
const BoundaryInfo & get_boundary_info() const
The information about boundary ids on the mesh.
Definition mesh_base.h:178
virtual std::unique_ptr< Partitioner > & partitioner()
A partitioner to use at each partitioning.
Definition mesh_base.h:173
bool is_redistributing() const
Definition mesh_base.h:1407
void prepare_for_use(const bool skip_renumber_nodes_and_elements, const bool skip_find_neighbors)
Prepare a newly created (or read) mesh for use.
Definition mesh_base.C:901
virtual void read(const std::string &name, void *mesh_data=nullptr, bool skip_renumber_nodes_and_elements=false, bool skip_find_neighbors=false, bool skip_detect_interior_parents=false)=0
Interfaces for reading/writing a mesh to/from a file.
void add_ghosting_functor(GhostingFunctor &ghosting_functor)
Adds a functor which can specify ghosting requirements for use on distributed meshes.
Definition mesh_base.C:1166
virtual void partition(const unsigned int n_parts)
Call the default partitioner (currently metis_partition()).
Definition mesh_base.C:1888
The Mesh class is a thin wrapper, around the ReplicatedMesh class by default.
Definition mesh.h:51
virtual void close()=0
Calls the NumericVector's internal assembly routines, ensuring that the values are consistent across ...
virtual void add_vector(const T *v, const std::vector< numeric_index_type > &dof_indices)
Computes , where v is a pointer and each dof_indices[i] specifies where to add value v[i].
This class provides the ability to map between arbitrary, user-defined strings and several data types...
Definition parameters.h:75
The Partitioner class provides a uniform interface for partitioning algorithms.
Definition partitioner.h:52
boundary_id_type myboundary
The boundary ID of this boundary and its counterpart.
The definition of a periodic boundary.
A Point defines a location in LIBMESH_DIM dimensional Real space.
Definition point.h:41
unsigned int n_points() const
Definition quadrature.h:131
This class implements specific orders of Gauss quadrature.
virtual void close()=0
Calls the SparseMatrix's internal assembly routines, ensuring that the values are consistent across p...
virtual void add_matrix(const DenseMatrix< T > &dm, const std::vector< numeric_index_type > &rows, const std::vector< numeric_index_type > &cols)=0
Add the full matrix dm to the SparseMatrix.
Manages consistently variables, degrees of freedom, and coefficient vectors.
Definition system.h:100
void project_solution(FunctionBase< Number > *f, FunctionBase< Gradient > *g=nullptr, std::optional< ConstElemRange > active_local_range=std::nullopt, std::optional< std::vector< unsigned int > > variable_numbers=std::nullopt) const
Projects arbitrary functions onto the current solution.
Number point_value(unsigned int var, const Point &p, const bool insist_on_success=true, const NumericVector< Number > *sol=nullptr) const
Definition system.C:2274
void attach_assemble_function(void fptr(EquationSystems &es, const std::string &name))
Register a user function to use in assembling the system matrix and RHS.
Definition system.C:2014
unsigned int add_variable(std::string_view var, const FEType &type, const std::set< subdomain_id_type > *const active_subdomains=nullptr)
Adds the variable var to the list of variables for this system.
Definition system.C:1400
const DofMap & get_dof_map() const
Definition system.h:2448
Wrap a libMesh-style function pointer into a FunctionBase object.
Communicator * TestCommWorld
MeshBase & mesh
void build_square(UnstructuredMesh &mesh, const unsigned int nx, const unsigned int ny, const Real xmin=0., const Real xmax=1., const Real ymin=0., const Real ymax=1., const ElemType type=INVALID_ELEM, const bool gauss_lobatto_grid=false)
A specialized build_cube() for 2D meshes.
The libMesh namespace provides an interface to certain functionality in the library.
OStreamProxy err
ElemType
Defines an enum for geometric element types.
int8_t boundary_id_type
Definition id_types.h:51
VectorValue< Real > RealVectorValue
Useful typedefs to allow transparent switching between Real and Complex data types.
static constexpr Real TOLERANCE
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
uint8_t processor_id_type
Definition id_types.h:104
Number quadratic_solution(const Point &p, const Parameters &, const std::string &, const std::string &)
CPPUNIT_TEST_SUITE_REGISTRATION(PeriodicBCTest)
void periodic_bc_test_poisson(EquationSystems &es, const std::string &)
const boundary_id_type side_id
const boundary_id_type top_id
const boundary_id_type bottom_id
virtual Number operator()(const Point &, const Real=0.) override
Number component(unsigned int i, const Point &p, Real) override
virtual std::unique_ptr< FunctionBase< Number > > clone() const
PeriodicQuadFunction()=default