Note

Click here to download the full example code

# Basics of Finite Element Analysis¶

This tutorial covers the first steps into Finite Element computation
referring the *M* (Modeling) in *pyGIMLi*.

We will not dig into deep details about the theory of the Finite Elements Analysis (FEA) here, as this can be found in several books, e.g., [Zie77].

Anyhow, there is a little need for theory to understand what it means to use FEA for the solution of a boundary value problem. So we start with some basics.

Assuming Poisson’s equation as a simple partial differential problem to be solved for the sought scalar field \(u(\mathbf{r})\) within a modeling domain \(\mathbf{r}\in\Omega\) with a non zero right hand side function \(f\).

The Laplace operator \(\Delta = \nabla\cdot\nabla\) given by the divergence of the gradient, is the sum of the second partial derivatives of the field \(u(\mathbf{r})\) with respect to the Cartesian coordinates in 1D space \(\mathbf{r} = (x)\), in 2D \(\mathbf{r} = (x, y)\), or 3D space \(\mathbf{r} = (x, y, z)\). On the boundary \(\partial\Omega\) of the domain, we want known values of \(u=g\) as so called Dirichlet boundary conditions.

A common approach to solve this problem is the method of weighted residuals. The base assumption states that an approximated solution \(u_h\approx u\) will only satisfy the differential equation with a rest \(R\): \(\Delta u_h + f = R\). If we choose some weighting functions \(w\), we can try to minimize the resulting residuum over our modeling domain as:

which leads to:

It is preferable to eliminate the second derivative in the Laplace operator, either due to integration by parts or by applying the product rule and Gauss’s law. This leads to the so called weak formulation:

We can solve these integrals after choosing an appropriate basis for an approximate solution \(u_h\) as:

The latter fundamental FEA relation discretizes the continuous solution \(u_h\) into a discrete values \(\mathrm{u} = \{\mathrm{u}_i\}\) for a number of \(i = 0\ldots\mathcal{N}\) discrete points, usually called nodes.

The basis functions \(N_i\) can be understood as interpolation rules for the discrete solution between adjacent nodes and will be chosen later.

Now we can set the unknown weighting functions to be the same as the basis functions \(w=N_j\) with \(j=0\ldots\mathcal{N}\) (Galerkin method)

this can be rewritten with \(h=0\) as:

The solution of this linear system of equations leads to the discrete solution \(\mathrm{u} = \{\mathrm{u}_i\}\) for all \(i=1\ldots\mathcal{N}\) nodes inside the modeling domain.

For the practical part, the choice of the nodes is crucial. If we choose too little, the accuracy of the sought solution might be too small. If we choose too many, the dimension of the system matrix will be too large, which leads to higher memory consumption and calculation times.

To define the nodes, we discretize our modeling domain into cells, or the eponymous elements. Cells are basic geometric shapes like triangles or hexahedrons and are constructed from the nodes and collected in a mesh. See the tutorials about the mesh basics (Basics). In summary, the discrete solutions of the differential equation using FEA on a specific mesh are defined on the node positions of the mesh.

The chosen mesh cells also define the base functions and the integration rules that are necessary to assemble the stiffness matrix and the load vector and will be discussed in a different tutorial (TOWRITE link here).

To finally solve our little example we still need to handle the application of the boundary condition \(u=g\) which is called Dirichlet condition. Setting explicit values for our solution is not covered by the general Galerkin weighted residuum method but we can solve it algebraically. We reduce the linear system of equations by the known solutions \(g={g_k}\) for all \(k\) nodes on the affected boundary elements: (maybe move this to the BC tutorial)

Now we have all parts together to assemble \(\mathrm{A_D}\) and \(\mathrm{b_D}\) and finally solve the given boundary value problem.

It is usually a good idea to test a numerical approach with known solutions. To keep things simple we create a modeling problem from the reverse direction. We choose a solution, calculate the right hand side function and select the domain geometry suitable for nice Dirichlet values.

We now can solve the Poison equation applying the FEA capabilities of pygimli and compare the resulting approximate solution \(\mathrm{u}\) with our known exact solution \(u(x,y)\).

```
import numpy as np
import pygimli as pg
```

We start to define the modeling domain and functions for the exact solution and the values for the load vector. The desired mesh of our domain will be a grid with equidistant spacing in x and y directions.

```
domain = pg.createGrid(x=np.linspace(0.0, 2*np.pi, 25),
y=np.linspace(0.0, 2*np.pi, 25))
uExact = lambda pos: np.sin(pos[0]) * np.sin(pos[1])
f = lambda cell: 2.0 * np.sin(cell.center()[0]) * np.sin(cell.center()[1])
```

We use the existing shortcut functions for the assembling of the basic FEA system matrices and vectors. The implemented parts of the solving process are supposed to be dimension independent. You only need to find a valid mesh with the supported element types.

```
A = pg.solver.createStiffnessMatrix(domain)
b = pg.solver.createLoadVector(domain, f)
```

To apply the boundary condition we first need to identify all boundary elements. The default grid applies the following boundary marker on the outermost boundaries: 1 (left), 2(right), 3(top), and 4(bottom).

```
boundaries = pg.solver.parseArgToBoundaries({'1,2,3,4': 0.0}, domain)
```

parseArgToBoundaries is a helper function to collect a list of tupels (Boundary element, value), which can be used to apply the Dirichlet conditions.

The approximate solution \(\mathrm{u}\) can then be found as the solution of the linear system of equations.

```
u = pg.solver.linSolve(A, b)
```

The resulting scalar field can displayed with the pg.show shortcut.

```
pg.show(domain, u, label='Approximated solution $\mathrm{u}$', nLevs=7)
```

Out:

```
(<matplotlib.axes._subplots.AxesSubplot object at 0x7f28eb193b70>, <matplotlib.colorbar.Colorbar object at 0x7f28ebbc4c50>)
```

For analyzing the accuracy for the approximation we apply the
L2 norm for the finite element space `pygimli.solver.normL2`

for a
set of different solutions with decreasing cell size. Instead of using the
the single assembling steps again, we apply our Finite Element shortcut function
`pygimli.solver.solve`

.

```
domain = pg.createGrid(x=np.linspace(0.0, 2*np.pi, 3),
y=np.linspace(0.0, 2*np.pi, 3))
h = []
l2 = []
for i in range(5):
domain = domain.createH2()
u_h = pg.solve(domain, f=f, bc={'Dirichlet':{'1:5': 0}})
u = np.array([uExact(_) for _ in domain.positions()])
l2.append(pg.solver.normL2(u - u_h, domain))
h.append(min(domain.boundarySizes()))
print("NodeCount: {0}, h:{1}m, L2:{2}%".format(domain.nodeCount(),
h[-1], l2[-1]))
ax,_ = pg.show()
ax.loglog(h, l2, 'o-')
ax.set_ylabel('Approximation error: $L_2$ norm')
ax.set_xlabel('Cell size $h$ (m)')
ax.grid()
```

Out:

```
NodeCount: 25, h:1.5707963267949996m, L2:0.15650280987419554%
NodeCount: 81, h:0.7853981633969997m, L2:0.011159591448331284%
NodeCount: 289, h:0.39269908169799983m, L2:0.0007191303721150352%
NodeCount: 1089, h:0.19634954084899991m, L2:4.528472440659257e-05%
NodeCount: 4225, h:0.09817477042399947m, L2:2.835596460837906e-06%
```

We calculated the examples before for a homogeneous material parameter a=1, but we can apply any heterogeneous values to0. One way is to create a list of parameter values, one for each cell of the domain. Currently the values for each cell can be of type float, complex, or real valued anisotropy or constitutive matrix. For illustration we show a calculation with an anisotropic material. We simply use the same setting as above and assume a -45 degree dipping angle in the left and 45 degree dipping in the right part of the domain. Maybe we will find someday a more meaningful example. If you have an idea please don’t hesitate to share.

```
a = [None]*domain.cellCount()
for c in domain.cells():
if c.center()[0] < np.pi:
a[c.id()] = pg.solver.anisotropyMatrix(lon=1.0, trans=10.0,
theta=-45/180 * np.pi)
else:
a[c.id()] = pg.solver.anisotropyMatrix(lon=1.0, trans=10.0,
theta=45/180 * np.pi)
u = pg.solve(domain, a=a, f=f, bc={'Dirichlet':{'*': 0}})
pg.show(domain, u, label='Solution $\mathrm{u}$ for anisotrop material parameter $a$', nLevs=7)
```

Out:

```
(<matplotlib.axes._subplots.AxesSubplot object at 0x7f28e584b6d8>, <matplotlib.colorbar.Colorbar object at 0x7f28fa971978>)
```