libMesh
Loading...
Searching...
No Matches
transient_ex1.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>Transient Example 1 - Solving a Transient Linear System in Parallel</h1>
21// \author Benjamin S. Kirk
22// \date 2003
23//
24// This example shows how a simple, linear transient
25// system can be solved in parallel. The system is simple
26// scalar convection-diffusion with a specified external
27// velocity. The initial condition is given, and the
28// solution is advanced in time with a standard Crank-Nicolson
29// time-stepping strategy.
30
31// C++ include files that we need
32#include <iostream>
33#include <algorithm>
34#include <sstream>
35#include <math.h>
36
37// Basic include file needed for the mesh functionality.
38#include "libmesh/libmesh.h"
39#include "libmesh/mesh.h"
40#include "libmesh/mesh_refinement.h"
41#include "libmesh/gmv_io.h"
42#include "libmesh/equation_systems.h"
43#include "libmesh/fe.h"
44#include "libmesh/quadrature_gauss.h"
45#include "libmesh/dof_map.h"
46#include "libmesh/sparse_matrix.h"
47#include "libmesh/numeric_vector.h"
48#include "libmesh/dense_matrix.h"
49#include "libmesh/dense_vector.h"
50#include "libmesh/exodusII_io.h"
51#include "libmesh/enum_solver_package.h"
52#include "libmesh/getpot.h"
53
54// This example will solve a linear transient system,
55// so we need to include the TransientLinearImplicitSystem definition.
56#include "libmesh/linear_implicit_system.h"
57#include "libmesh/transient_system.h"
58#include "libmesh/vector_value.h"
59
60// The definition of a geometric element
61#include "libmesh/elem.h"
62
63// Bring in everything from the libMesh namespace
64using namespace libMesh;
65
66// Function prototype. This function will assemble the system
67// matrix and right-hand-side at each time step. Note that
68// since the system is linear we technically do not need to
69// assemble the matrix at each time step, but we will anyway.
70// In subsequent examples we will employ adaptive mesh refinement,
71// and with a changing mesh it will be necessary to rebuild the
72// system matrix.
74 const std::string & system_name);
75
76// Function prototype. This function will initialize the system.
77// Initialization functions are optional for systems. They allow
78// you to specify the initial values of the solution. If an
79// initialization function is not provided then the default (0)
80// solution is provided.
82 const std::string & system_name);
83
84// Exact solution function prototype. This gives the exact
85// solution as a function of space and time. In this case the
86// initial condition will be taken as the exact solution at time 0,
87// as will the Dirichlet boundary conditions at time t.
88Real exact_solution (const Real x,
89 const Real y,
90 const Real t);
91
93 const Parameters & parameters,
94 const std::string &,
95 const std::string &)
96{
97 return exact_solution(p(0), p(1), parameters.get<Real> ("time"));
98}
99
100
101
102// We can now begin the main program. Note that this
103// example will fail if you are using complex numbers
104// since it was designed to be run only with real numbers.
105int main (int argc, char ** argv)
106{
107 // Initialize libMesh.
108 LibMeshInit init (argc, argv);
109
110 // This example requires a linear solver package.
111 libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE,
112 "--enable-petsc, --enable-trilinos, or --enable-eigen");
113
114 // This example requires Adaptive Mesh Refinement support - although
115 // it only refines uniformly, the refinement code used is the same
116 // underneath
117#ifndef LIBMESH_ENABLE_AMR
118 libmesh_example_requires(false, "--enable-amr");
119#else
120
121 // Skip this 2D example if libMesh was compiled as 1D-only.
122 libmesh_example_requires(2 <= LIBMESH_DIM, "2D support");
123
124 // Read the mesh from file. This is the coarse mesh that will be used
125 // in example 10 to demonstrate adaptive mesh refinement. Here we will
126 // simply read it in and uniformly refine it before we compute with
127 // it.
128 //
129 // Create a mesh object, with dimension to be overridden later,
130 // distributed across the default MPI communicator.
131 Mesh mesh(init.comm());
132
133 mesh.read ("mesh.xda");
134
135 // Query the command line for the number of mesh refinements to use
136 GetPot input(argc, argv);
137 const unsigned int n_refinements = input("n_refinements", 5);
138
139 // Create a MeshRefinement object to handle refinement of our mesh.
140 // This class handles all the details of mesh refinement and coarsening.
141 MeshRefinement mesh_refinement (mesh);
142
143 // Uniformly refine the mesh as requested.
144 mesh_refinement.uniformly_refine (n_refinements);
145
146 // Print information about the mesh to the screen.
148
149 // Create an equation systems object.
150 EquationSystems equation_systems (mesh);
151
152 // Add a transient system to the EquationSystems
153 // object named "Convection-Diffusion".
155 equation_systems.add_system<TransientLinearImplicitSystem> ("Convection-Diffusion");
156
157 // Adds the variable "u" to "Convection-Diffusion". "u"
158 // will be approximated using first-order approximation.
159 system.add_variable ("u", FIRST);
160
161 // Give the system a pointer to the matrix assembly
162 // and initialization functions.
163 system.attach_assemble_function (assemble_cd);
164 system.attach_init_function (init_cd);
165
166 // Initialize the data structures for the equation system.
167 equation_systems.init ();
168
169 // Prints information about the system to the screen.
170 equation_systems.print_info();
171
172 // Write out the initial conditions.
173#ifdef LIBMESH_HAVE_EXODUS_API
174 // If Exodus is available, we'll write all timesteps to the same file
175 // rather than one file per timestep.
176 std::string exodus_filename = "transient_ex1.e";
178#else
179 GMVIO(mesh).write_equation_systems ("out_000.gmv", equation_systems);
180#endif
181
182 // The Convection-Diffusion system requires that we specify
183 // the flow velocity. We will specify it as a RealVectorValue
184 // data type and then use the Parameters object to pass it to
185 // the assemble function.
186 equation_systems.parameters.set<RealVectorValue>("velocity") =
187 RealVectorValue (0.8, 0.8);
188
189 // Solve the system "Convection-Diffusion". This will be done by
190 // looping over the specified time interval and calling the
191 // solve() member at each time step. This will assemble the
192 // system and call the linear solver.
193 const Real dt = 0.025;
194 system.time = 0.;
195
196 for (unsigned int t_step = 0; t_step < 50; t_step++)
197 {
198 // Increment the time counter, set the time and the
199 // time step size as parameters in the EquationSystem.
200 system.time += dt;
201
202 equation_systems.parameters.set<Real> ("time") = system.time;
203 equation_systems.parameters.set<Real> ("dt") = dt;
204
205 // A pretty update message
206 libMesh::out << " Solving time step ";
207
208 // Do fancy zero-padded formatting of the current time.
209 {
210 std::ostringstream out;
211
212 out << std::setw(2)
213 << std::right
214 << t_step
215 << ", time="
216 << std::fixed
217 << std::setw(6)
218 << std::setprecision(3)
219 << std::setfill('0')
220 << std::left
221 << system.time
222 << "...";
223
224 libMesh::out << out.str() << std::endl;
225 }
226
227 // At this point we need to update the old
228 // solution vector. The old solution vector
229 // will be the current solution vector from the
230 // previous time step. We will do this by extracting the
231 // system from the EquationSystems object and using
232 // vector assignment. Since only TransientSystems
233 // (and systems derived from them) contain old solutions
234 // we need to specify the system type when we ask for it.
235 *system.old_local_solution = *system.current_local_solution;
236
237 // Assemble & solve the linear system
238 equation_systems.get_system("Convection-Diffusion").solve();
239
240 // Output every 10 timesteps to file.
241 if ((t_step+1)%10 == 0)
242 {
243
244#ifdef LIBMESH_HAVE_EXODUS_API
245 ExodusII_IO exo(mesh);
246 exo.append(true);
247 exo.write_timestep (exodus_filename, equation_systems, t_step+1, system.time);
248#else
249 std::ostringstream file_name;
250
251 file_name << "out_"
252 << std::setw(3)
253 << std::setfill('0')
254 << std::right
255 << t_step+1
256 << ".gmv";
257
258
259 GMVIO(mesh).write_equation_systems (file_name.str(),
260 equation_systems);
261#endif
262 }
263 }
264#endif // #ifdef LIBMESH_ENABLE_AMR
265
266 // All done.
267 return 0;
268}
269
270// We now define the function which provides the
271// initialization routines for the "Convection-Diffusion"
272// system. This handles things like setting initial
273// conditions and boundary conditions.
275 const std::string & libmesh_dbg_var(system_name))
276{
277 // It is a good idea to make sure we are initializing
278 // the proper system.
279 libmesh_assert_equal_to (system_name, "Convection-Diffusion");
280
281 // Get a reference to the Convection-Diffusion system object.
283 es.get_system<TransientLinearImplicitSystem>("Convection-Diffusion");
284
285 // Project initial conditions at time 0
286 es.parameters.set<Real> ("time") = system.time = 0;
287
288 system.project_solution(exact_value, nullptr, es.parameters);
289}
290
291
292
293// Now we define the assemble function which will be used
294// by the EquationSystems object at each timestep to assemble
295// the linear system for solution.
297 const std::string & system_name)
298{
299 // Ignore unused parameter warnings when !LIBMESH_ENABLE_AMR.
300 libmesh_ignore(es, system_name);
301
302#ifdef LIBMESH_ENABLE_AMR
303 // It is a good idea to make sure we are assembling
304 // the proper system.
305 libmesh_assert_equal_to (system_name, "Convection-Diffusion");
306
307 // Get a constant reference to the mesh object.
308 const MeshBase & mesh = es.get_mesh();
309
310 // The dimension that we are running
311 const unsigned int dim = mesh.mesh_dimension();
312
313 // Get a reference to the Convection-Diffusion system object.
315 es.get_system<TransientLinearImplicitSystem> ("Convection-Diffusion");
316
317 // Get a constant reference to the Finite Element type
318 // for the first (and only) variable in the system.
319 FEType fe_type = system.variable_type(0);
320
321 // Build a Finite Element object of the specified type. Since the
322 // FEBase::build() member dynamically creates memory we will
323 // store the object as a std::unique_ptr<FEBase>. This can be thought
324 // of as a pointer that will clean up after itself.
325 std::unique_ptr<FEBase> fe (FEBase::build(dim, fe_type));
326 std::unique_ptr<FEBase> fe_face (FEBase::build(dim, fe_type));
327
328 // A Gauss quadrature rule for numerical integration.
329 // Let the FEType object decide what order rule is appropriate.
330 QGauss qrule (dim, fe_type.default_quadrature_order());
331 QGauss qface (dim-1, fe_type.default_quadrature_order());
332
333 // Tell the finite element object to use our quadrature rule.
334 fe->attach_quadrature_rule (&qrule);
335 fe_face->attach_quadrature_rule (&qface);
336
337 // Here we define some references to cell-specific data that
338 // will be used to assemble the linear system. We will start
339 // with the element Jacobian * quadrature weight at each integration point.
340 const std::vector<Real> & JxW = fe->get_JxW();
341 const std::vector<Real> & JxW_face = fe_face->get_JxW();
342
343 // The element shape functions evaluated at the quadrature points.
344 const std::vector<std::vector<Real>> & phi = fe->get_phi();
345 const std::vector<std::vector<Real>> & psi = fe_face->get_phi();
346
347 // The element shape function gradients evaluated at the quadrature
348 // points.
349 const std::vector<std::vector<RealGradient>> & dphi = fe->get_dphi();
350
351 // The XY locations of the quadrature points used for face integration
352 const std::vector<Point> & qface_points = fe_face->get_xyz();
353
354 // A reference to the DofMap object for this system. The DofMap
355 // object handles the index translation from node and element numbers
356 // to degree of freedom numbers. We will talk more about the DofMap
357 // in future examples.
358 const DofMap & dof_map = system.get_dof_map();
359
360 // Define data structures to contain the element matrix
361 // and right-hand-side vector contribution. Following
362 // basic finite element terminology we will denote these
363 // "Ke" and "Fe".
366
367 // This vector will hold the degree of freedom indices for
368 // the element. These define where in the global system
369 // the element degrees of freedom get mapped.
370 std::vector<dof_id_type> dof_indices;
371
372 // Here we extract the velocity & parameters that we put in the
373 // EquationSystems object.
374 const RealVectorValue velocity =
375 es.parameters.get<RealVectorValue> ("velocity");
376
377 const Real dt = es.parameters.get<Real> ("dt");
378
379 SparseMatrix<Number> & matrix = system.get_system_matrix();
380
381 // Now we will loop over all the elements in the mesh that
382 // live on the local processor. We will compute the element
383 // matrix and right-hand-side contribution. Since the mesh
384 // will be refined we want to only consider the ACTIVE elements,
385 // hence we use a variant of the active_elem_iterator.
386 for (const auto & elem : mesh.active_local_element_ptr_range())
387 {
388 // Get the degree of freedom indices for the
389 // current element. These define where in the global
390 // matrix and right-hand-side this element will
391 // contribute to.
392 dof_map.dof_indices (elem, dof_indices);
393
394 // Compute the element-specific data for the current
395 // element. This involves computing the location of the
396 // quadrature points (q_point) and the shape functions
397 // (phi, dphi) for the current element.
398 fe->reinit (elem);
399
400 // Zero the element matrix and right-hand side before
401 // summing them. We use the resize member here because
402 // the number of degrees of freedom might have changed from
403 // the last element. Note that this will be the case if the
404 // element type is different (i.e. the last element was a
405 // triangle, now we are on a quadrilateral).
406 Ke.resize (dof_indices.size(),
407 dof_indices.size());
408
409 Fe.resize (dof_indices.size());
410
411 // Now we will build the element matrix and right-hand-side.
412 // Constructing the RHS requires the solution and its
413 // gradient from the previous timestep. This myst be
414 // calculated at each quadrature point by summing the
415 // solution degree-of-freedom values by the appropriate
416 // weight functions.
417 for (unsigned int qp=0; qp<qrule.n_points(); qp++)
418 {
419 // Values to hold the old solution & its gradient.
420 Number u_old = 0.;
421 Gradient grad_u_old;
422
423 // Compute the old solution & its gradient.
424 for (std::size_t l=0; l<phi.size(); l++)
425 {
426 u_old += phi[l][qp]*system.old_solution (dof_indices[l]);
427
428 // This will work,
429 // grad_u_old += dphi[l][qp]*system.old_solution (dof_indices[l]);
430 // but we can do it without creating a temporary like this:
431 grad_u_old.add_scaled (dphi[l][qp], system.old_solution (dof_indices[l]));
432 }
433
434 // Now compute the element matrix and RHS contributions.
435 for (std::size_t i=0; i<phi.size(); i++)
436 {
437 // The RHS contribution
438 Fe(i) += JxW[qp]*(
439 // Mass matrix term
440 u_old*phi[i][qp] +
441 -.5*dt*(
442 // Convection term
443 // (grad_u_old may be complex, so the
444 // order here is important!)
445 (grad_u_old*velocity)*phi[i][qp] +
446
447 // Diffusion term
448 0.01*(grad_u_old*dphi[i][qp]))
449 );
450
451 for (std::size_t j=0; j<phi.size(); j++)
452 {
453 // The matrix contribution
454 Ke(i,j) += JxW[qp]*(
455 // Mass-matrix
456 phi[i][qp]*phi[j][qp] +
457
458 .5*dt*(
459 // Convection term
460 (velocity*dphi[j][qp])*phi[i][qp] +
461
462 // Diffusion term
463 0.01*(dphi[i][qp]*dphi[j][qp]))
464 );
465 }
466 }
467 }
468
469 // At this point the interior element integration has
470 // been completed. However, we have not yet addressed
471 // boundary conditions. For this example we will only
472 // consider simple Dirichlet boundary conditions imposed
473 // via the penalty method.
474 //
475 // The following loops over the sides of the element.
476 // If the element has no neighbor on a side then that
477 // side MUST live on a boundary of the domain.
478 {
479 // The penalty value.
480 const Real penalty = 1.e10;
481
482 // The following loops over the sides of the element.
483 // If the element has no neighbor on a side then that
484 // side MUST live on a boundary of the domain.
485 for (auto s : elem->side_index_range())
486 if (elem->neighbor_ptr(s) == nullptr)
487 {
488 fe_face->reinit(elem, s);
489
490 for (unsigned int qp=0; qp<qface.n_points(); qp++)
491 {
492 const Number value = exact_solution (qface_points[qp](0),
493 qface_points[qp](1),
494 system.time);
495
496 // RHS contribution
497 for (std::size_t i=0; i<psi.size(); i++)
498 Fe(i) += penalty*JxW_face[qp]*value*psi[i][qp];
499
500 // Matrix contribution
501 for (std::size_t i=0; i<psi.size(); i++)
502 for (std::size_t j=0; j<psi.size(); j++)
503 Ke(i,j) += penalty*JxW_face[qp]*psi[i][qp]*psi[j][qp];
504 }
505 }
506 }
507
508 // If this assembly program were to be used on an adaptive mesh,
509 // we would have to apply any hanging node constraint equations
510 dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
511
512 // The element matrix and right-hand-side are now built
513 // for this element. Add them to the global matrix and
514 // right-hand-side vector. The SparseMatrix::add_matrix()
515 // and NumericVector::add_vector() members do this for us.
516 matrix.add_matrix (Ke, dof_indices);
517 system.rhs->add_vector (Fe, dof_indices);
518 }
519
520 // That concludes the system matrix assembly routine.
521#endif // #ifdef LIBMESH_ENABLE_AMR
522}
unsigned int dim
Number(* exact_solution)(const Point &p, const Parameters &, const std::string &, const std::string &)
std::string exodus_filename(unsigned number)
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.
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 constrain_element_matrix_and_vector(DenseMatrix< Number > &matrix, DenseVector< Number > &rhs, std::vector< dof_id_type > &elem_dofs, bool asymmetric_constraint_rows=true) const
Constrains the element matrix and vector.
Definition dof_map.h:2498
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
void append(bool val)
If true, this flag will cause the ExodusII_IO object to attempt to open an existing file for writing,...
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.
void write_timestep(const std::string &fname, const EquationSystems &es, const int timestep, const Real time, const std::set< std::string > *system_names=nullptr)
Writes out the solution at a specific 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
This class implements writing meshes in the GMV format.
Definition gmv_io.h:48
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
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
virtual void write_equation_systems(const std::string &, const EquationSystems &, const std::set< std::string > *system_names=nullptr)
This method implements writing a mesh with data to a specified file where the data is taken from the ...
Definition mesh_output.C:31
Implements (adaptive) mesh refinement algorithms for a MeshBase.
void uniformly_refine(unsigned int n=1)
Uniformly refines the mesh n times.
The Mesh class is a thin wrapper, around the ReplicatedMesh class by default.
Definition mesh.h:51
This class provides the ability to map between arbitrary, user-defined strings and several data types...
Definition parameters.h:75
T & set(const std::string &)
Definition parameters.h:494
const T & get(std::string_view) const
Definition parameters.h:451
A Point defines a location in LIBMESH_DIM dimensional Real space.
Definition point.h:40
unsigned int n_points() const
Definition quadrature.h:131
This class implements specific orders of Gauss quadrature.
Generic sparse matrix.
Manages storage and variables for transient systems.
NumericVector< Number > * old_local_solution
All the values I need to compute my contribution to the simulation at hand.
Number old_solution(const dof_id_type global_dof_number) const
void add_scaled(const TypeVector< T2 > &, const T &)
Add a scaled value to this vector without creating a temporary.
MeshBase & mesh
The libMesh namespace provides an interface to certain functionality in the library.
void libmesh_ignore(const Args &...)
SolverPackage default_solver_package()
Definition libmesh.C:1064
OStreamProxy out
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
Number exact_value(const Point &p, const Parameters &parameters, const std::string &, const std::string &)
void assemble_cd(EquationSystems &es, const std::string &system_name)
void init_cd(EquationSystems &es, const std::string &system_name)
int main()
static const bool value
Definition xdr_io.C:55