libMesh
Loading...
Searching...
No Matches
eigenproblems_ex3.C
Go to the documentation of this file.
1// The libMesh Finite Element Library.
2// Copyright (C) 2002-2026 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
3
4// This library is free software; you can redistribute it and/or
5// modify it under the terms of the GNU Lesser General Public
6// License as published by the Free Software Foundation; either
7// version 2.1 of the License, or (at your option) any later version.
8
9// This library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12// Lesser General Public License for more details.
13
14// You should have received a copy of the GNU Lesser General Public
15// License along with this library; if not, write to the Free Software
16// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
18
19
20// <h1>Eigenproblems Example 3 - Can you "hear the shape" of a drum?</h1>
21// \author David Knezevic
22// \date 2012
23//
24// The sound that a drum makes is determined by it's resonant frequencies,
25// which are given by the eigenvalues of the Laplacian. "Can One Hear the
26// Shape of a Drum?" was the title of an article by Mark Kac
27// in the American Mathematical Monthly in 1966, where he raised the question:
28// If we know all the eigenvalues of a drum, can we uniquely determine it's shape?
29// This question was resolved in 1992, when Gordon, Webb, and Wolpert constructed
30// a pair of regions in 2D that have different shapes but identical eigenvalues.
31// So the answer to Kac's question is no: the spectrum of the Laplacian does
32// not uniquely determine the shape of the domain.
33
34// In this example, we compute the first few eigenvalues of the two domains proposed
35// by Gordon, Webb and Wolpert. This amounts to solving a generalized eigenvalue
36// problem in each case. The computed eigenvalues are stored in drum1_evals.txt and
37// drum2_evals.txt. We can compare these to the (highly accurate) values reported in:
38// T.A. Driscoll, "Eigenmodes of Isospectral Drums", SIAM Review, Vol. 39, No. 1, pp. 1-17, 1997.
39//
40// The first five eigenvalues from Driscoll are listed below (the author states that
41// "all digits shown are believed to be correct"):
42// 2.53794399980
43// 3.65550971352
44// 5.17555935622
45// 6.53755744376
46// 7.24807786256
47
48
49// C++ include files
50#include <fstream>
51
52// libMesh include files.
53#include "libmesh/libmesh.h"
54#include "libmesh/mesh.h"
55#include "libmesh/mesh_generation.h"
56#include "libmesh/exodusII_io.h"
57#include "libmesh/condensed_eigen_system.h"
58#include "libmesh/equation_systems.h"
59#include "libmesh/fe.h"
60#include "libmesh/quadrature_gauss.h"
61#include "libmesh/dense_matrix.h"
62#include "libmesh/sparse_matrix.h"
63#include "libmesh/numeric_vector.h"
64#include "libmesh/dof_map.h"
65#include "libmesh/fe_interface.h"
66#include "libmesh/getpot.h"
67#include "libmesh/elem.h"
68#include "libmesh/zero_function.h"
69#include "libmesh/dirichlet_boundaries.h"
70#include "libmesh/slepc_macro.h"
71#include "libmesh/enum_eigen_solver_type.h"
72
73#define BOUNDARY_ID 100
74
75// Bring in everything from the libMesh namespace
76using namespace libMesh;
77
78
79// Function prototype. This is the function that will assemble
80// the eigen system. Here, we will simply assemble a mass matrix.
82 const std::string & system_name);
83
84// We store the Dirichlet dofs in a set in order to impose the boundary conditions
86 const std::string & system_name,
87 std::set<unsigned int> & global_dirichlet_dofs_set);
88
89
90int main (int argc, char ** argv)
91{
92 // Initialize libMesh and the dependent libraries.
93 LibMeshInit init (argc, argv);
94
95 // This example uses an ExodusII input file
96#ifndef LIBMESH_HAVE_EXODUS_API
97 libmesh_example_requires(false, "--enable-exodus");
98#endif
99
100 // This example is designed for the SLEPc eigen solver interface.
101#ifndef LIBMESH_HAVE_SLEPC
102 if (init.comm().rank() == 0)
103 libMesh::err << "ERROR: This example requires libMesh to be\n"
104 << "compiled with SLEPc eigen solvers support!"
105 << std::endl;
106
107 return 0;
108#else
109
110#ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
111 // SLEPc currently gives us a nasty crash with Real==float
112 libmesh_example_requires(false, "--disable-singleprecision");
113#endif
114
115#if defined(LIBMESH_USE_COMPLEX_NUMBERS) && SLEPC_VERSION_LESS_THAN(3,6,2)
116 // SLEPc used to give us an "inner product not well defined" with
117 // Number==complex; but this problem seems to be solved in newer versions.
118 libmesh_example_requires(false, "--disable-complex or use SLEPc>=3.6.2");
119#endif
120
121 // We use Dirichlet boundary conditions here
122#ifndef LIBMESH_ENABLE_DIRICHLET
123 libmesh_example_requires(false, "--enable-dirichlet");
124#endif
125
126 // Tell the user what we are doing.
127 {
128 libMesh::out << "Running " << argv[0];
129
130 for (int i=1; i<argc; i++)
131 libMesh::out << " " << argv[i];
132
133 libMesh::out << std::endl << std::endl;
134 }
135
136 // Skip this 2D example if libMesh was compiled as 1D-only.
137 libmesh_example_requires(2 <= LIBMESH_DIM, "2D support");
138
139 // Use GetPot to parse the command line arguments
140 GetPot command_line (argc, argv);
141
142 // Read the mesh name from the command line
143 const std::string mesh_name =
144 libMesh::command_line_next("-mesh_name", std::string());
145
146 // Also, read in the index of the eigenvector that we should plot
147 // (zero-based indexing, as usual!)
148 const unsigned int plotting_index =
149 libMesh::command_line_next("-plotting_index", 0u);
150
151 // Finally, read in the number of eigenpairs we want to compute!
152 const unsigned int n_evals =
153 libMesh::command_line_next("-n_evals", 0u);
154
155 // Append the .e to mesh_name
156 std::ostringstream mesh_name_exodus;
157 mesh_name_exodus << mesh_name << "_mesh.e";
158
159 // Create a mesh, with dimension to be overridden by the file, on
160 // the default MPI communicator.
161 Mesh mesh(init.comm());
162
163 mesh.read(mesh_name_exodus.str());
164
165 // Add boundary IDs to this mesh so that we can use DirichletBoundary
166 // Each processor should know about each boundary condition it can
167 // see, so we loop over all elements, not just local elements.
168 for (const auto & elem : mesh.element_ptr_range())
169 for (auto side : elem->side_index_range())
170 if (elem->neighbor_ptr (side) == nullptr)
171 mesh.get_boundary_info().add_side(elem, side, BOUNDARY_ID);
172
174
175 // Print information about the mesh to the screen.
177
178 // Create an equation systems object.
179 EquationSystems equation_systems (mesh);
180
181 // Create a CondensedEigenSystem named "Eigensystem" and (for convenience)
182 // use a reference to the system we create.
183 CondensedEigenSystem & eigen_system =
184 equation_systems.add_system<CondensedEigenSystem> ("Eigensystem");
185
186 // Declare the system variables.
187 // Adds the variable "p" to "Eigensystem". "p"
188 // will be approximated using second-order approximation.
189 eigen_system.add_variable("p", SECOND);
190
191 // Give the system a pointer to the matrix assembly
192 // function defined below.
194
195 // Set the number of requested eigenpairs n_evals and the number
196 // of basis vectors used in the solution algorithm.
197 equation_systems.parameters.set<unsigned int>("eigenpairs") = n_evals;
198 equation_systems.parameters.set<unsigned int>("basis vectors") = n_evals*3;
199
200 // Set the solver tolerance and the maximum number of iterations.
201 equation_systems.parameters.set<Real>("linear solver tolerance") = pow(TOLERANCE, 5./3.);
202 equation_systems.parameters.set<unsigned int>
203 ("linear solver maximum iterations") = 1000;
204
205 // Set the type of the problem, here we deal with
206 // a generalized Hermitian problem.
207 eigen_system.set_eigenproblem_type(GHEP);
208
209 // Set the target eigenvalue
210 eigen_system.get_eigen_solver().set_position_of_spectrum(0., TARGET_REAL);
211
212 {
214
215#ifdef LIBMESH_ENABLE_DIRICHLET
216 // Most DirichletBoundary users will want to supply a "locally
217 // indexed" functor
218 DirichletBoundary dirichlet_bc({BOUNDARY_ID}, {0}, zf,
220
221 eigen_system.get_dof_map().add_dirichlet_boundary(dirichlet_bc);
222#endif
223 }
224
225 // Initialize the data structures for the equation system.
226 equation_systems.init();
227
228 // Prints information about the system to the screen.
229 equation_systems.print_info();
230
231 eigen_system.initialize_condensed_dofs();
232
233 // Solve the system "Eigensystem".
234 eigen_system.solve();
235
236 // Get the number of converged eigen pairs.
237 unsigned int nconv = eigen_system.get_n_converged();
238
239 libMesh::out << "Number of converged eigenpairs: "
240 << nconv
241 << "\n"
242 << std::endl;
243
244 if (plotting_index > n_evals)
245 {
246 libMesh::out << "WARNING: Solver did not converge for the requested eigenvector!" << std::endl;
247 }
248
249 // write out all of the computed eigenvalues and plot the specified eigenvector
250 std::ostringstream eigenvalue_output_name;
251 eigenvalue_output_name << mesh_name << "_evals.txt";
252 std::ofstream evals_file(eigenvalue_output_name.str().c_str());
253
254 for (unsigned int i=0; i<nconv; i++)
255 {
256 std::pair<Real,Real> eval = eigen_system.get_eigenpair(i);
257
258 // The eigenvalues should be real!
259 libmesh_assert_less (eval.second, TOLERANCE);
260 evals_file << eval.first << std::endl;
261
262 // plot the specified eigenvector
263 if (i == plotting_index)
264 {
265#ifdef LIBMESH_HAVE_EXODUS_API
266 // Write the eigen vector to file.
267 std::ostringstream eigenvector_output_name;
268 eigenvector_output_name << mesh_name << "_evec.e";
269 ExodusII_IO (mesh).write_equation_systems (eigenvector_output_name.str(), equation_systems);
270#endif // #ifdef LIBMESH_HAVE_EXODUS_API
271 }
272 }
273
274 evals_file.close();
275
276#endif // LIBMESH_HAVE_SLEPC
277
278 // All done.
279 return 0;
280}
281
282
283
285 const std::string & libmesh_dbg_var(system_name))
286{
287
288 // It is a good idea to make sure we are assembling
289 // the proper system.
290 libmesh_assert_equal_to (system_name, "Eigensystem");
291
292#ifdef LIBMESH_HAVE_SLEPC
293
294 // Get a constant reference to the mesh object.
295 const MeshBase & mesh = es.get_mesh();
296
297 // The dimension that we are running.
298 const unsigned int dim = mesh.mesh_dimension();
299
300 // Get a reference to our system.
301 EigenSystem & eigen_system = es.get_system<EigenSystem> ("Eigensystem");
302
303 // Get a constant reference to the Finite Element type
304 // for the first (and only) variable in the system.
305 FEType fe_type = eigen_system.get_dof_map().variable_type(0);
306
307 // A reference to the two system matrices
308 SparseMatrix<Number> & matrix_A = eigen_system.get_matrix_A();
309 SparseMatrix<Number> & matrix_B = eigen_system.get_matrix_B();
310
311 // Build a Finite Element object of the specified type. Since the
312 // FEBase::build() member dynamically creates memory we will
313 // store the object as a std::unique_ptr<FEBase>. This can be thought
314 // of as a pointer that will clean up after itself.
315 std::unique_ptr<FEBase> fe (FEBase::build(dim, fe_type));
316
317 // A Gauss quadrature rule for numerical integration.
318 // Use the default quadrature order.
319 QGauss qrule (dim, fe_type.default_quadrature_order());
320
321 // Tell the finite element object to use our quadrature rule.
322 fe->attach_quadrature_rule (&qrule);
323
324 // The element Jacobian * quadrature weight at each integration point.
325 const std::vector<Real> & JxW = fe->get_JxW();
326
327 // The element shape functions evaluated at the quadrature points.
328 const std::vector<std::vector<Real>> & phi = fe->get_phi();
329
330 // The element shape function gradients evaluated at the quadrature
331 // points.
332 const std::vector<std::vector<RealGradient>> & dphi = fe->get_dphi();
333
334 // A reference to the DofMap object for this system. The DofMap
335 // object handles the index translation from node and element numbers
336 // to degree of freedom numbers.
337 const DofMap & dof_map = eigen_system.get_dof_map();
338
339 // The element mass and stiffness matrices.
342
343 // This vector will hold the degree of freedom indices for
344 // the element. These define where in the global system
345 // the element degrees of freedom get mapped.
346 std::vector<dof_id_type> dof_indices;
347
348
349 // Now we will loop over all the elements in the mesh that
350 // live on the local processor. We will compute the element
351 // matrix and right-hand-side contribution. In case users
352 // later modify this program to include refinement, we will
353 // be safe and will only consider the active elements;
354 // hence we use a variant of the active_elem_iterator.
355 for (const auto & elem : mesh.active_local_element_ptr_range())
356 {
357 // Get the degree of freedom indices for the
358 // current element. These define where in the global
359 // matrix and right-hand-side this element will
360 // contribute to.
361 dof_map.dof_indices (elem, dof_indices);
362
363 // Compute the element-specific data for the current
364 // element. This involves computing the location of the
365 // quadrature points (q_point) and the shape functions
366 // (phi, dphi) for the current element.
367 fe->reinit (elem);
368
369 // Zero the element matrices before
370 // summing them. We use the resize member here because
371 // the number of degrees of freedom might have changed from
372 // the last element. Note that this will be the case if the
373 // element type is different (i.e. the last element was a
374 // triangle, now we are on a quadrilateral).
375 const unsigned int n_dofs =
376 cast_int<unsigned int>(dof_indices.size());
377 Ke.resize (n_dofs, n_dofs);
378 Me.resize (n_dofs, n_dofs);
379
380 // Now loop over the quadrature points. This handles
381 // the numeric integration.
382 //
383 // We will build the element matrix. This involves
384 // a double loop to integrate the test functions (i) against
385 // the trial functions (j).
386 for (unsigned int qp=0; qp<qrule.n_points(); qp++)
387 for (unsigned int i=0; i<n_dofs; i++)
388 for (unsigned int j=0; j<n_dofs; j++)
389 {
390 Me(i,j) += JxW[qp]*phi[i][qp]*phi[j][qp];
391 Ke(i,j) += JxW[qp]*(dphi[i][qp]*dphi[j][qp]);
392 }
393
394 // The calls to constrain_element_matrix below have no effect in
395 // the current example. However, if users modify this example to
396 // include hanging nodes due to mesh refinement, for example,
397 // then it is essential to call constrain_element_matrix.
398 // As a result we include constrain_element_matrix here to
399 // ensure this example is ready to be used with hanging nodes.
400 // (Note that constrained rows/cols will be eliminated from
401 // the eigenproblem by the CondensedEigenSystem.)
402 dof_map.constrain_element_matrix(Ke, dof_indices, false);
403 dof_map.constrain_element_matrix(Me, dof_indices, false);
404
405 // Finally, simply add the element contribution to the
406 // overall matrices A and B.
407 matrix_A.add_matrix (Ke, dof_indices);
408 matrix_B.add_matrix (Me, dof_indices);
409 } // end of element loop
410
411
412#else
413 // Avoid compiler warnings
414 libmesh_ignore(es);
415#endif // LIBMESH_HAVE_SLEPC
416}
unsigned int dim
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.
void regenerate_id_sets()
Clears and regenerates the cached sets of ids.
This class extends EigenSystem to allow a simple way of solving (standard or generalized) eigenvalue ...
virtual void solve() override
Override to solve the condensed eigenproblem with the dofs in local_non_condensed_dofs_vector strippe...
void initialize_condensed_dofs(const std::set< dof_id_type > &global_condensed_dofs_set=std::set< dof_id_type >())
Loop over the dofs on each processor to initialize the list of non-condensed dofs.
virtual std::pair< Real, Real > get_eigenpair(dof_id_type i) override
Override get_eigenpair() to retrieve the eigenpair for the condensed eigensolve.
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().
This class allows one to associate Dirichlet boundary values with a given set of mesh boundary ids an...
This class handles the numbering of degrees of freedom on a mesh.
Definition dof_map.h:181
void dof_indices(const Elem *const elem, std::vector< dof_id_type > &di) const
Definition dof_map.C:2201
void add_dirichlet_boundary(const DirichletBoundary &dirichlet_boundary)
Adds a copy of the specified Dirichlet boundary to the system.
void constrain_element_matrix(DenseMatrix< Number > &matrix, std::vector< dof_id_type > &elem_dofs, bool asymmetric_constraint_rows=true) const
Constrains the element matrix.
Definition dof_map.h:2485
const FEType & variable_type(const unsigned int i) const
Definition dof_map.h:2388
Manages consistently variables, degrees of freedom, and coefficient vectors for eigenvalue problems.
void set_eigenproblem_type(EigenProblemType ept)
Sets the type of the current eigen problem.
const SparseMatrix< Number > & get_matrix_B() const
unsigned int get_n_converged() const
const SparseMatrix< Number > & get_matrix_A() const
const EigenSolver< Number > & get_eigen_solver() const
This is the EquationSystems class.
void print_info(std::ostream &os=libMesh::out) const
Prints information about the equation systems, by default to libMesh::out.
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.
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
The LibMeshInit class, when constructed, initializes the dependent libraries (e.g.
Definition libmesh.h:92
This is the MeshBase class.
Definition mesh_base.h:81
const BoundaryInfo & get_boundary_info() const
The information about boundary ids on the mesh.
Definition mesh_base.h:170
unsigned int mesh_dimension() const
Definition mesh_base.C:430
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 print_info(std::ostream &os=libMesh::out, const unsigned int verbosity=0, const bool global=true) const
Prints relevant information about the mesh.
Definition mesh_base.C:1755
The Mesh class is a thin wrapper, around the ReplicatedMesh class by default.
Definition mesh.h:51
T & set(const std::string &)
Definition parameters.h:494
unsigned int n_points() const
Definition quadrature.h:131
This class implements specific orders of Gauss quadrature.
Generic sparse matrix.
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.
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:1959
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:1344
const DofMap & get_dof_map() const
Definition system.h:2417
ConstFunction that simply returns 0.
void assemble_matrices(EquationSystems &es, const std::string &system_name)
void get_dirichlet_dofs(EquationSystems &es, const std::string &system_name, std::set< unsigned int > &global_dirichlet_dofs_set)
MeshBase & mesh
The libMesh namespace provides an interface to certain functionality in the library.
OStreamProxy err
void libmesh_ignore(const Args &...)
OStreamProxy out
T command_line_next(std::string name, T default_value)
Use GetPot's search()/next() functions to get following arguments from the command line.
Definition libmesh.C:1025
static constexpr Real TOLERANCE
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
int main()