The source file eigenproblems_ex1.C with comments:

        #include "libmesh/libmesh.h"
        #include "libmesh/mesh.h"
        #include "libmesh/mesh_generation.h"
        #include "libmesh/exodusII_io.h"
        #include "libmesh/eigen_system.h"
        #include "libmesh/equation_systems.h"
        #include "libmesh/fe.h"
        #include "libmesh/quadrature_gauss.h"
        #include "libmesh/dense_matrix.h"
        #include "libmesh/sparse_matrix.h"
        #include "libmesh/numeric_vector.h"
        #include "libmesh/dof_map.h"
        
Bring in everything from the libMesh namespace
        using namespace libMesh;
        
Function prototype. This is the function that will assemble the eigen system. Here, we will simply assemble a mass matrix.
        void assemble_mass(EquationSystems& es,
                           const std::string& system_name);
        
        
        
        int main (int argc, char** argv)
        {
Initialize libMesh and the dependent libraries.
          LibMeshInit init (argc, argv);
        
Skip SLEPc examples on a non-SLEPc libMesh build
        #ifndef LIBMESH_HAVE_SLEPC
          libmesh_example_assert(false, "--enable-slepc");
        }
        
        #else
        
        #ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
SLEPc currently gives us a nasty crash with Real==float
          libmesh_example_assert(false, "--disable-singleprecision");
        #endif
        
Check for proper usage.
          if (argc < 3)
            {
              if (libMesh::processor_id() == 0)
                std::cerr << "\nUsage: " << argv[0]
                          << " -n <number of eigen values>"
                          << std::endl;
              libmesh_error();
            }
        
Tell the user what we are doing.
          else
            {
              std::cout << "Running " << argv[0];
        
              for (int i=1; i<argc; i++)
                std::cout << " " << argv[i];
        
              std::cout << std::endl << std::endl;
            }
        
Get the number of eigen values to be computed from argv[2]
          const unsigned int nev = std::atoi(argv[2]);
        
Skip this 2D example if libMesh was compiled as 1D-only.
          libmesh_example_assert(2 <= LIBMESH_DIM, "2D support");
        
Create a mesh, with dimension to be overridden later, on the default MPI communicator.
          Mesh mesh(init.comm());
        
Use the internal mesh generator to create a uniform 2D grid on a square.
          MeshTools::Generation::build_square (mesh,
                                               20, 20,
                                               -1., 1.,
                                               -1., 1.,
                                               QUAD4);
        
Print information about the mesh to the screen.
          mesh.print_info();
        
Create an equation systems object.
          EquationSystems equation_systems (mesh);
        
Create a EigenSystem named "Eigensystem" and (for convenience) use a reference to the system we create.
          EigenSystem & eigen_system =
            equation_systems.add_system<EigenSystem> ("Eigensystem");
        
Declare the system variables. Adds the variable "p" to "Eigensystem". "p" will be approximated using second-order approximation.
          eigen_system.add_variable("p", FIRST);
        
Give the system a pointer to the matrix assembly function defined below.
          eigen_system.attach_assemble_function (assemble_mass);
        
Set necessary parametrs used in EigenSystem::solve(), i.e. the number of requested eigenpairs \p nev and the number of basis vectors \p ncv used in the solution algorithm. Note that ncv >= nev must hold and ncv >= 2*nev is recommended.
          equation_systems.parameters.set<unsigned int>("eigenpairs")    = nev;
          equation_systems.parameters.set<unsigned int>("basis vectors") = nev*3;
        
You may optionally change the default eigensolver used by SLEPc. The Krylov-Schur method is mathematically equivalent to implicitly restarted Arnoldi, the method of Arpack, so there is currently no point in using SLEPc with Arpack. ARNOLDI = default in SLEPc 2.3.1 and earlier KRYLOVSCHUR default in SLEPc 2.3.2 and later eigen_system.eigen_solver->set_eigensolver_type(KRYLOVSCHUR);

Set the solver tolerance and the maximum number of iterations.
          equation_systems.parameters.set<Real>
            ("linear solver tolerance") = pow(TOLERANCE, 5./3.);
          equation_systems.parameters.set<unsigned int>
            ("linear solver maximum iterations") = 1000;
        
Initialize the data structures for the equation system.
          equation_systems.init();
        
Prints information about the system to the screen.
          equation_systems.print_info();
        
Solve the system "Eigensystem".
          eigen_system.solve();
        
Get the number of converged eigen pairs.
          unsigned int nconv = eigen_system.get_n_converged();
        
          std::cout << "Number of converged eigenpairs: " << nconv
                    << "\n" << std::endl;
        
Get the last converged eigenpair
          if (nconv != 0)
            {
              eigen_system.get_eigenpair(nconv-1);
        
        #ifdef LIBMESH_HAVE_EXODUS_API
Write the eigen vector to file.
              ExodusII_IO (mesh).write_equation_systems ("out.e", equation_systems);
        #endif // #ifdef LIBMESH_HAVE_EXODUS_API
            }
          else
            {
              std::cout << "WARNING: Solver did not converge!\n" << nconv << std::endl;
            }
        
All done.
          return 0;
        }
        
        #endif // LIBMESH_HAVE_SLEPC
        
        
        
        
        void assemble_mass(EquationSystems& es,
                           const std::string& system_name)
        {
        
It is a good idea to make sure we are assembling the proper system.
          libmesh_assert_equal_to (system_name, "Eigensystem");
        
        #ifdef LIBMESH_HAVE_SLEPC
        
Get a constant reference to the mesh object.
          const MeshBase& mesh = es.get_mesh();
        
The dimension that we are running.
          const unsigned int dim = mesh.mesh_dimension();
        
Get a reference to our system.
          EigenSystem & eigen_system = es.get_system<EigenSystem> (system_name);
        
Get a constant reference to the Finite Element type for the first (and only) variable in the system.
          FEType fe_type = eigen_system.get_dof_map().variable_type(0);
        
A reference to the system matrix
          SparseMatrix<Number>&  matrix_A = *eigen_system.matrix_A;
        
Build a Finite Element object of the specified type. Since the \p FEBase::build() member dynamically creates memory we will store the object as an \p AutoPtr. This can be thought of as a pointer that will clean up after itself.
          AutoPtr<FEBase> fe (FEBase::build(dim, fe_type));
        
A Gauss quadrature rule for numerical integration. Use the default quadrature order.
          QGauss qrule (dim, fe_type.default_quadrature_order());
        
Tell the finite element object to use our quadrature rule.
          fe->attach_quadrature_rule (&qrule);
        
The element Jacobian * quadrature weight at each integration point.
          const std::vector<Real>& JxW = fe->get_JxW();
        
The element shape functions evaluated at the quadrature points.
          const std::vector<std::vector<Real> >& phi = fe->get_phi();
        
The element shape function gradients evaluated at the quadrature points. const std::vector >& dphi = fe->get_dphi();

A reference to the \p DofMap object for this system. The \p DofMap object handles the index translation from node and element numbers to degree of freedom numbers.
          const DofMap& dof_map = eigen_system.get_dof_map();
        
The element mass matrix.
          DenseMatrix<Number>   Me;
        
This vector will hold the degree of freedom indices for the element. These define where in the global system the element degrees of freedom get mapped.
          std::vector<dof_id_type> dof_indices;
        
        
Now we will loop over all the elements in the mesh that live on the local processor. We will compute the element matrix and right-hand-side contribution. In case users later modify this program to include refinement, we will be safe and will only consider the active elements; hence we use a variant of the \p active_elem_iterator.
          MeshBase::const_element_iterator       el     = mesh.active_local_elements_begin();
          const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end();
        
          for ( ; el != end_el; ++el)
            {
Store a pointer to the element we are currently working on. This allows for nicer syntax later.
              const Elem* elem = *el;
        
Get the degree of freedom indices for the current element. These define where in the global matrix and right-hand-side this element will contribute to.
              dof_map.dof_indices (elem, dof_indices);
        
Compute the element-specific data for the current element. This involves computing the location of the quadrature points (q_point) and the shape functions (phi, dphi) for the current element.
              fe->reinit (elem);
        
Zero the element matrices and rhs before summing them. We use the resize member here because the number of degrees of freedom might have changed from the last element. Note that this will be the case if the element type is different (i.e. the last element was a triangle, now we are on a quadrilateral).
              Me.resize (dof_indices.size(), dof_indices.size());
        
Now loop over the quadrature points. This handles the numeric integration.

We will build the element matrix. This involves a double loop to integrate the test funcions (i) against the trial functions (j).
              for (unsigned int qp=0; qp<qrule.n_points(); qp++)
                for (unsigned int i=0; i<phi.size(); i++)
                  for (unsigned int j=0; j<phi.size(); j++)
                      Me(i,j) += JxW[qp]*phi[i][qp]*phi[j][qp];
        
On an unrefined mesh, constrain_element_matrix does nothing. If this assembly function is ever repurposed to run on a refined mesh, getting the hanging node constraints right will be important. Note that, even with asymmetric_constraint_rows = false, the constrained dof diagonals still exist in the matrix, with diagonal entries that are there to ensure non-singular matrices for linear solves but which would generate positive non-physical eigenvalues for eigensolves.
              dof_map.constrain_element_matrix(Me, dof_indices, false);
        
Finally, simply add the element contribution to the overall matrix.
              matrix_A.add_matrix (Me, dof_indices);
        
        
            } // end of element loop
        
        #endif // LIBMESH_HAVE_SLEPC
        
          /**
           * All done!
           */
          return;
        
        }



The source file eigenproblems_ex1.C without comments:

 
  #include "libmesh/libmesh.h"
  #include "libmesh/mesh.h"
  #include "libmesh/mesh_generation.h"
  #include "libmesh/exodusII_io.h"
  #include "libmesh/eigen_system.h"
  #include "libmesh/equation_systems.h"
  #include "libmesh/fe.h"
  #include "libmesh/quadrature_gauss.h"
  #include "libmesh/dense_matrix.h"
  #include "libmesh/sparse_matrix.h"
  #include "libmesh/numeric_vector.h"
  #include "libmesh/dof_map.h"
  
  using namespace libMesh;
  
  void assemble_mass(EquationSystems& es,
                     const std::string& system_name);
  
  
  
  int main (int argc, char** argv)
  {
    LibMeshInit init (argc, argv);
  
  #ifndef LIBMESH_HAVE_SLEPC
    libmesh_example_assert(false, "--enable-slepc");
  }
  
  #else
  
  #ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
    libmesh_example_assert(false, "--disable-singleprecision");
  #endif
  
    if (argc < 3)
      {
        if (libMesh::processor_id() == 0)
          std::cerr << "\nUsage: " << argv[0]
                    << " -n <number of eigen values>"
                    << std::endl;
        libmesh_error();
      }
  
    else
      {
        std::cout << "Running " << argv[0];
  
        for (int i=1; i<argc; i++)
          std::cout << " " << argv[i];
  
        std::cout << std::endl << std::endl;
      }
  
    const unsigned int nev = std::atoi(argv[2]);
  
    libmesh_example_assert(2 <= LIBMESH_DIM, "2D support");
  
    Mesh mesh(init.comm());
  
    MeshTools::Generation::build_square (mesh,
                                         20, 20,
                                         -1., 1.,
                                         -1., 1.,
                                         QUAD4);
  
    mesh.print_info();
  
    EquationSystems equation_systems (mesh);
  
    EigenSystem & eigen_system =
      equation_systems.add_system<EigenSystem> ("Eigensystem");
  
    eigen_system.add_variable("p", FIRST);
  
    eigen_system.attach_assemble_function (assemble_mass);
  
    equation_systems.parameters.set<unsigned int>("eigenpairs")    = nev;
    equation_systems.parameters.set<unsigned int>("basis vectors") = nev*3;
  
  
    equation_systems.parameters.set<Real>
      ("linear solver tolerance") = pow(TOLERANCE, 5./3.);
    equation_systems.parameters.set<unsigned int>
      ("linear solver maximum iterations") = 1000;
  
    equation_systems.init();
  
    equation_systems.print_info();
  
    eigen_system.solve();
  
    unsigned int nconv = eigen_system.get_n_converged();
  
    std::cout << "Number of converged eigenpairs: " << nconv
              << "\n" << std::endl;
  
    if (nconv != 0)
      {
        eigen_system.get_eigenpair(nconv-1);
  
  #ifdef LIBMESH_HAVE_EXODUS_API
        ExodusII_IO (mesh).write_equation_systems ("out.e", equation_systems);
  #endif // #ifdef LIBMESH_HAVE_EXODUS_API
      }
    else
      {
        std::cout << "WARNING: Solver did not converge!\n" << nconv << std::endl;
      }
  
    return 0;
  }
  
  #endif // LIBMESH_HAVE_SLEPC
  
  
  
  
  void assemble_mass(EquationSystems& es,
                     const std::string& system_name)
  {
  
    libmesh_assert_equal_to (system_name, "Eigensystem");
  
  #ifdef LIBMESH_HAVE_SLEPC
  
    const MeshBase& mesh = es.get_mesh();
  
    const unsigned int dim = mesh.mesh_dimension();
  
    EigenSystem & eigen_system = es.get_system<EigenSystem> (system_name);
  
    FEType fe_type = eigen_system.get_dof_map().variable_type(0);
  
    SparseMatrix<Number>&  matrix_A = *eigen_system.matrix_A;
  
    AutoPtr<FEBase> fe (FEBase::build(dim, fe_type));
  
    QGauss qrule (dim, fe_type.default_quadrature_order());
  
    fe->attach_quadrature_rule (&qrule);
  
    const std::vector<Real>& JxW = fe->get_JxW();
  
    const std::vector<std::vector<Real> >& phi = fe->get_phi();
  
  
    const DofMap& dof_map = eigen_system.get_dof_map();
  
    DenseMatrix<Number>   Me;
  
    std::vector<dof_id_type> dof_indices;
  
  
    MeshBase::const_element_iterator       el     = mesh.active_local_elements_begin();
    const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end();
  
    for ( ; el != end_el; ++el)
      {
        const Elem* elem = *el;
  
        dof_map.dof_indices (elem, dof_indices);
  
        fe->reinit (elem);
  
        Me.resize (dof_indices.size(), dof_indices.size());
  
        for (unsigned int qp=0; qp<qrule.n_points(); qp++)
          for (unsigned int i=0; i<phi.size(); i++)
            for (unsigned int j=0; j<phi.size(); j++)
                Me(i,j) += JxW[qp]*phi[i][qp]*phi[j][qp];
  
        dof_map.constrain_element_matrix(Me, dof_indices, false);
  
        matrix_A.add_matrix (Me, dof_indices);
  
  
      } // end of element loop
  
  #endif // LIBMESH_HAVE_SLEPC
  
    /**
     * All done!
     */
    return;
  
  }



The console output of the program:

make[4]: Entering directory `/net/spark/workspace/roystgnr/libmesh/git/devel/examples/eigenproblems/eigenproblems_ex1'
***************************************************************
* Running Example eigenproblems_ex1:
*  mpirun -np 4 example-devel -n 5 -pc_type bjacobi -sub_pc_type ilu -sub_pc_factor_levels 4 -sub_pc_factor_zeropivot 0 -ksp_right_pc
***************************************************************
 
Running /net/spark/workspace/roystgnr/libmesh/git/devel/examples/eigenproblems/eigenproblems_ex1/.libs/lt-example-devel -n 5 -pc_type bjacobi -sub_pc_type ilu -sub_pc_factor_levels 4 -sub_pc_factor_zeropivot 0 -ksp_right_pc

 Mesh Information:
  mesh_dimension()=2
  spatial_dimension()=3
  n_nodes()=441
    n_local_nodes()=123
  n_elem()=400
    n_local_elem()=100
    n_active_elem()=400
  n_subdomains()=1
  n_partitions()=4
  n_processors()=4
  n_threads()=1
  processor_id()=0

 EquationSystems
  n_systems()=1
   System #0, "Eigensystem"
    Type "Eigen"
    Variables="p" 
    Finite Element Types="LAGRANGE", "JACOBI_20_00" 
    Infinite Element Mapping="CARTESIAN" 
    Approximation Orders="FIRST", "THIRD" 
    n_dofs()=441
    n_local_dofs()=123
    n_constrained_dofs()=0
    n_local_constrained_dofs()=0
    n_vectors()=0
    n_matrices()=1
    DofMap Sparsity
      Average  On-Processor Bandwidth <= 8.17914
      Average Off-Processor Bandwidth <= 0.571429
      Maximum  On-Processor Bandwidth <= 11
      Maximum Off-Processor Bandwidth <= 6
    DofMap Constraints
      Number of DoF Constraints = 0
      Number of Node Constraints = 0

Number of converged eigenpairs: 5


 -------------------------------------------------------------------------------------------------------------------
| Processor id:   0                                                                                                 |
| Num Processors: 4                                                                                                 |
| Time:           Fri Apr 19 11:49:14 2013                                                                          |
| OS:             Linux                                                                                             |
| HostName:       spark.ices.utexas.edu                                                                             |
| OS Release:     2.6.32-279.22.1.el6.x86_64                                                                        |
| OS Version:     #1 SMP Tue Feb 5 14:33:39 CST 2013                                                                |
| Machine:        x86_64                                                                                            |
| Username:       roystgnr                                                                                          |
| Configuration:  ../configure  '--enable-everything'                                                               |
|  'METHODS=devel'                                                                                                  |
|  '--prefix=/h2/roystgnr/libmesh-test'                                                                             |
|  'CXX=distcc /usr/bin/g++'                                                                                        |
|  'CC=distcc /usr/bin/gcc'                                                                                         |
|  'FC=distcc /usr/bin/gfortran'                                                                                    |
|  'F77=distcc /usr/bin/gfortran'                                                                                   |
|  'PETSC_DIR=/opt/apps/ossw/libraries/petsc/petsc-3.3-p2'                                                          |
|  'PETSC_ARCH=gcc-system-mkl-gf-10.3.12.361-mpich2-1.4.1p1-cxx-opt'                                                |
|  'SLEPC_DIR=/opt/apps/ossw/libraries/slepc/slepc-3.3-p2-petsc-3.3-p2-cxx-opt'                                     |
|  'TRILINOS_DIR=/opt/apps/ossw/libraries/trilinos/trilinos-10.12.2/sl6/gcc-system/mpich2-1.4.1p1/mkl-gf-10.3.12.361'|
|  'VTK_DIR=/opt/apps/ossw/libraries/vtk/vtk-5.10.0/sl6/gcc-system'                                                 |
|  'HDF5_DIR=/opt/apps/ossw/libraries/hdf5/hdf5-1.8.9/sl6/gcc-system'                                               |
 -------------------------------------------------------------------------------------------------------------------
 ----------------------------------------------------------------------------------------------------------------
| libMesh Performance: Alive time=0.201832, Active time=0.087214                                                 |
 ----------------------------------------------------------------------------------------------------------------
| Event                              nCalls    Total Time  Avg Time    Total Time  Avg Time    % of Active Time  |
|                                              w/o Sub     w/o Sub     With Sub    With Sub    w/o S    With S   |
|----------------------------------------------------------------------------------------------------------------|
|                                                                                                                |
|                                                                                                                |
| DofMap                                                                                                         |
|   add_neighbors_to_send_list()     1         0.0006      0.000582    0.0009      0.000852    0.67     0.98     |
|   build_sparsity()                 1         0.0005      0.000480    0.0013      0.001276    0.55     1.46     |
|   create_dof_constraints()         1         0.0002      0.000181    0.0002      0.000181    0.21     0.21     |
|   distribute_dofs()                1         0.0012      0.001188    0.0033      0.003330    1.36     3.82     |
|   dof_indices()                    351       0.0019      0.000005    0.0019      0.000005    2.14     2.14     |
|   prepare_send_list()              1         0.0000      0.000006    0.0000      0.000006    0.01     0.01     |
|   reinit()                         1         0.0018      0.001831    0.0018      0.001831    2.10     2.10     |
|                                                                                                                |
| EquationSystems                                                                                                |
|   build_solution_vector()          1         0.0004      0.000363    0.0012      0.001160    0.42     1.33     |
|                                                                                                                |
| ExodusII_IO                                                                                                    |
|   write_nodal_data()               1         0.0370      0.036967    0.0370      0.036967    42.39    42.39    |
|                                                                                                                |
| FE                                                                                                             |
|   compute_shape_functions()        100       0.0002      0.000002    0.0002      0.000002    0.28     0.28     |
|   init_shape_functions()           1         0.0000      0.000007    0.0000      0.000007    0.01     0.01     |
|                                                                                                                |
| FEMap                                                                                                          |
|   compute_affine_map()             100       0.0003      0.000003    0.0003      0.000003    0.29     0.29     |
|   init_reference_to_physical_map() 1         0.0000      0.000045    0.0000      0.000045    0.05     0.05     |
|                                                                                                                |
| Mesh                                                                                                           |
|   find_neighbors()                 1         0.0014      0.001356    0.0014      0.001429    1.55     1.64     |
|   renumber_nodes_and_elem()        2         0.0001      0.000044    0.0001      0.000044    0.10     0.10     |
|                                                                                                                |
| MeshCommunication                                                                                              |
|   compute_hilbert_indices()        2         0.0035      0.001765    0.0035      0.001765    4.05     4.05     |
|   find_global_indices()            2         0.0005      0.000273    0.0049      0.002442    0.63     5.60     |
|   parallel_sort()                  2         0.0003      0.000173    0.0005      0.000253    0.40     0.58     |
|                                                                                                                |
| MeshOutput                                                                                                     |
|   write_equation_systems()         1         0.0001      0.000060    0.0383      0.038264    0.07     43.87    |
|                                                                                                                |
| MeshTools::Generation                                                                                          |
|   build_cube()                     1         0.0004      0.000400    0.0004      0.000400    0.46     0.46     |
|                                                                                                                |
| MetisPartitioner                                                                                               |
|   partition()                      1         0.0045      0.004516    0.0068      0.006818    5.18     7.82     |
|                                                                                                                |
| Parallel                                                                                                       |
|   allgather()                      9         0.0001      0.000015    0.0002      0.000018    0.15     0.19     |
|   max(bool)                        1         0.0000      0.000004    0.0000      0.000004    0.00     0.00     |
|   max(scalar)                      105       0.0004      0.000004    0.0004      0.000004    0.51     0.51     |
|   max(vector)                      24        0.0002      0.000007    0.0004      0.000018    0.18     0.49     |
|   min(bool)                        121       0.0005      0.000004    0.0005      0.000004    0.53     0.53     |
|   min(scalar)                      99        0.0007      0.000007    0.0007      0.000007    0.78     0.78     |
|   min(vector)                      24        0.0002      0.000009    0.0005      0.000021    0.25     0.58     |
|   probe()                          36        0.0001      0.000003    0.0001      0.000003    0.14     0.14     |
|   receive()                        36        0.0001      0.000003    0.0002      0.000007    0.12     0.27     |
|   send()                           36        0.0001      0.000002    0.0001      0.000002    0.08     0.08     |
|   send_receive()                   40        0.0002      0.000005    0.0006      0.000015    0.25     0.67     |
|   sum()                            20        0.0002      0.000012    0.0003      0.000016    0.28     0.37     |
|                                                                                                                |
| Parallel::Request                                                                                              |
|   wait()                           36        0.0001      0.000001    0.0001      0.000001    0.06     0.06     |
|                                                                                                                |
| Partitioner                                                                                                    |
|   set_node_processor_ids()         1         0.0004      0.000391    0.0006      0.000577    0.45     0.66     |
|   set_parent_processor_ids()       1         0.0001      0.000127    0.0001      0.000127    0.15     0.15     |
|                                                                                                                |
| SlepcEigenSolver                                                                                               |
|   solve_standard()                 1         0.0282      0.028246    0.0282      0.028246    32.39    32.39    |
|                                                                                                                |
| System                                                                                                         |
|   assemble()                       1         0.0007      0.000678    0.0018      0.001802    0.78     2.07     |
 ----------------------------------------------------------------------------------------------------------------
| Totals:                            1164      0.0872                                          100.00            |
 ----------------------------------------------------------------------------------------------------------------

 
***************************************************************
* Done Running Example eigenproblems_ex1:
*  mpirun -np 4 example-devel -n 5 -pc_type bjacobi -sub_pc_type ilu -sub_pc_factor_levels 4 -sub_pc_factor_zeropivot 0 -ksp_right_pc
***************************************************************
make[4]: Leaving directory `/net/spark/workspace/roystgnr/libmesh/git/devel/examples/eigenproblems/eigenproblems_ex1'

Site Created By: libMesh Developers
Last modified: April 23 2013 04:19:30 UTC

Hosted By:
SourceForge.net Logo