# How to solve eigenvalues in FEniCSx?

**URL:** <https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738>\
**Category:** dolfinx\
**Created:** [March 22, 2023, 8:57am UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738 "2023-03-22T08:57:10Z")\
**Posts on this page:** 18\
**Page:** 1

<div class="post-metadata">

**Author:** ![VICTORIA\_CHAN](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/victoria_chan/32/4602_2.png) [@VICTORIA\_CHAN](https://fenicsproject.discourse.group/u/VICTORIA_CHAN)\
**Post date:** [March 22, 2023, 8:57am UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/1 "2023-03-22T08:57:10Z")

</div>

I am going to find a way to solve the eigenvalues by FEniCSx, and I want to show all the eigenvalues and the parameters. I got some code from this link ([A known analytical solution — FEniCSx tutorial](https://jsdokken.com/dolfinx-tutorial/chapter2/heat_code.html?highlight=assemible)) which seems to solve the eigenvector and find the error. Can anyone teach me how to revise it to solve the eigenvalue, and show the parameters? I really appreciate any help you can provide.

```auto
t = 0 # Start time
T = 2 # End time
num_steps = 20 # Number of time steps
dt = (T-t)/num_steps # Time step size
alpha = 3
beta = 1.2

import numpy
from dolfinx import mesh, fem
import ufl
from mpi4py import MPI
from petsc4py import PETSc

nx, ny = 5, 5
domain = mesh.create_unit_square(MPI.COMM_WORLD, nx, ny, mesh.CellType.triangle)
V = fem.FunctionSpace(domain, ("CG", 1))

class exact_solution():
    def __init__ (self, alpha, beta, t):
        self.alpha = alpha
        self.beta = beta
        self.t = t
    def __call__ (self, x):
        return 1 + x[0]**2 + self.alpha * x[1]**2 + self.beta * self.t
u_exact = exact_solution(alpha, beta, t)

u_D = fem.Function(V)
u_D.interpolate(u_exact)
tdim = domain.topology.dim
fdim = tdim - 1
domain.topology.create_connectivity(fdim, tdim)
boundary_facets = mesh.exterior_facet_indices(domain.topology)
bc = fem.dirichletbc(u_D, fem.locate_dofs_topological(V, fdim, boundary_facets))

u_n = fem.Function(V)
u_n.interpolate(u_exact)

f = fem.Constant(domain, beta - 2 - 2 * alpha)

u, v = ufl.TrialFunction(V), ufl.TestFunction(V)
F = u*v*ufl.dx + dt*ufl.dot(ufl.grad(u), ufl.grad(v))*ufl.dx - (u_n + dt*f)*v*ufl.dx
a = fem.form(ufl.lhs(F))
L = fem.form(ufl.rhs(F))

A = fem.petsc.assemble_matrix(a, bcs=[bc])
A.assemble()
b = fem.petsc.create_vector(L)
uh = fem.Function(V)

solver = PETSc.KSP().create(domain.comm)
solver.setOperators(A)
solver.setType(PETSc.KSP.Type.PREONLY)
solver.getPC().setType(PETSc.PC.Type.LU)

for n in range(num_steps):
    # Update Diriclet boundary condition 
    u_exact.t+=dt
    u_D.interpolate(u_exact)
    
    # Update the right hand side reusing the initial vector
    with b.localForm() as loc_b:
        loc_b.set(0)
    fem.petsc.assemble_vector(b, L)
    
    # Apply Dirichlet boundary condition to the vector
    fem.petsc.apply_lifting(b, [a], [[bc]])
    b.ghostUpdate(addv=PETSc.InsertMode.ADD_VALUES, mode=PETSc.ScatterMode.REVERSE)
    fem.petsc.set_bc(b, [bc])

    # Solve linear problem
    solver.solve(b, uh.vector)
    uh.x.scatter_forward()

    # Update solution at previous time step (u_n)
    u_n.x.array[:] = uh.x.array

    # Compute L2 error and error at nodes
V_ex = fem.FunctionSpace(domain, ("CG", 2))
u_ex = fem.Function(V_ex)
u_ex.interpolate(u_exact)
error_L2 = numpy.sqrt(domain.comm.allreduce(fem.assemble_scalar(fem.form((uh - u_ex)**2 * ufl.dx)), op=MPI.SUM))
if domain.comm.rank == 0:
    print(f"L2-error: {error_L2:.2e}")

# Compute values at mesh vertices
error_max = domain.comm.allreduce(numpy.max(numpy.abs(uh.x.array-u_D.x.array)), op=MPI.MAX)
if domain.comm.rank == 0:
    print(f"Error_max: {error_max:.2e}")

```

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [March 22, 2023, 9:10am UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/2 "2023-03-22T09:10:43Z")

</div>

See for instance: [Mode analysis for a half-loaded rectangular waveguide — DOLFINx 0.6.0 documentation](https://docs.fenicsproject.org/dolfinx/v0.6.0/python/demos/demo_half_loaded_waveguide.html)

---

<div class="post-metadata">

**Author:** ![VICTORIA\_CHAN](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/victoria_chan/32/4602_2.png) [@VICTORIA\_CHAN](https://fenicsproject.discourse.group/u/VICTORIA_CHAN)\
**Post date:** [March 22, 2023, 9:17am UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/3 "2023-03-22T09:17:56Z")

</div>

Thanks! I will try this.

---

<div class="post-metadata">

**Author:** ![VICTORIA\_CHAN](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/victoria_chan/32/4602_2.png) [@VICTORIA\_CHAN](https://fenicsproject.discourse.group/u/VICTORIA_CHAN)\
**Post date:** [March 22, 2023, 12:02pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/4 "2023-03-22T12:02:28Z")

</div>

When I copy the code from the link you provided and test whether the code works in my computer, I found that the following error appear. How can I solve it? Thanks.

```auto
Traceback (most recent call last):
  File "/Users/victoriachan/Documents/CityU Doc/FYP/python_files/eigen_3.21.6.py", line 4, in <module>
    from analytical_modes import verify_mode
ModuleNotFoundError: No module named 'analytical_modes'

```

---

<div class="post-metadata">

**Author:** ![VICTORIA\_CHAN](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/victoria_chan/32/4602_2.png) [@VICTORIA\_CHAN](https://fenicsproject.discourse.group/u/VICTORIA_CHAN)\
**Post date:** [March 22, 2023, 12:03pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/5 "2023-03-22T12:03:13Z")

</div>

The error comes from this line:

```auto
from analytical_modes import verify_mode

```

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [March 22, 2023, 12:51pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/6 "2023-03-22T12:51:10Z")

</div>

You need to download the file analytical modes from [dolfinx/python/demo/demo\_waveguide at v0.6.0 · FEniCS/dolfinx · GitHub](https://github.com/FEniCS/dolfinx/tree/v0.6.0/python/demo/demo_waveguide)

---

<div class="post-metadata">

**Author:** ![VICTORIA\_CHAN](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/victoria_chan/32/4602_2.png) [@VICTORIA\_CHAN](https://fenicsproject.discourse.group/u/VICTORIA_CHAN)\
**Post date:** [March 22, 2023, 1:11pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/7 "2023-03-22T13:11:52Z")

</div>

Thank you so much! I can successfully run the code, but it is normal to have the following results after the images appear?

 ![Screenshot 2023-03-22 at 9.10.06 PM](https://global.discourse-cdn.com/free1/uploads/fenicsproject1/original/2X/f/fe09d330ef90b9821c618d5c7773119352e40c22.jpeg)

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [March 22, 2023, 1:13pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/8 "2023-03-22T13:13:42Z")

</div>

No, I haven’t seen that before. It seems to be related to exiting the plotting (pyvista). What version of pyvista are you using?

---

<div class="post-metadata">

**Author:** ![VICTORIA\_CHAN](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/victoria_chan/32/4602_2.png) [@VICTORIA\_CHAN](https://fenicsproject.discourse.group/u/VICTORIA_CHAN)\
**Post date:** [March 22, 2023, 1:26pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/9 "2023-03-22T13:26:50Z")

</div>

I am using pyvista 0.37.0

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [March 22, 2023, 3:11pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/10 "2023-03-22T15:11:36Z")

</div>

> [@VICTORIA\_CHAN](#):
>
> pyvista 0.37.0

Could you try upgrading to `0.38.1`?

---

<div class="post-metadata">

**Author:** ![VICTORIA\_CHAN](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/victoria_chan/32/4602_2.png) [@VICTORIA\_CHAN](https://fenicsproject.discourse.group/u/VICTORIA_CHAN)\
**Post date:** [March 22, 2023, 3:46pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/11 "2023-03-22T15:46:06Z")

</div>

I upgraded and the error happens again. I am using VScode. This error only appeared after I closed the images generated from the program. Not sure if it matters.

 ![Screenshot 2023-03-22 at 11.42.55 PM](https://global.discourse-cdn.com/free1/uploads/fenicsproject1/original/2X/a/a54b8e0452626669c6b09609c9344fedd38624af.jpeg)

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [March 22, 2023, 4:06pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/12 "2023-03-22T16:06:35Z")

</div>

I don’t think it matters.  
It is not something realted to DOLFINx, as it happens inside the `pyvista`-plotting.

---

<div class="post-metadata">

**Author:** ![VICTORIA\_CHAN](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/victoria_chan/32/4602_2.png) [@VICTORIA\_CHAN](https://fenicsproject.discourse.group/u/VICTORIA_CHAN)\
**Post date:** [March 22, 2023, 4:13pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/13 "2023-03-22T16:13:58Z")

</div>

Thank you for your explanation, I understand what you mean. However, I’m afraid that the problem still persists and cannot be solved at the moment. Do you have any other suggestions that we can try?

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [March 22, 2023, 4:35pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/14 "2023-03-22T16:35:51Z")

</div>

If you write down how you installed all your dependencies I can try to re-create your error message locally.

---

<div class="post-metadata">

**Author:** ![VICTORIA\_CHAN](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/victoria_chan/32/4602_2.png) [@VICTORIA\_CHAN](https://fenicsproject.discourse.group/u/VICTORIA_CHAN)\
**Post date:** [March 22, 2023, 4:54pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/15 "2023-03-22T16:54:46Z")

</div>

I am not entirely certain if the list of dependencies I am providing is what you need, but I have included the versions of the installed packages that I am using along with the Conda version, since I am using Conda. I hope this information is helpful to you.

```auto
Package Version
---------------------------- ---------
absl-py 1.4.0
aiohttp 3.8.3
aiosignal 1.3.1
appdirs 1.4.4
appnope 0.1.2
asttokens 2.0.5
astunparse 1.6.3
async-timeout 4.0.2
attrs 22.2.0
backcall 0.2.0
brotlipy 0.7.0
cachetools 5.3.0
certifi 2022.12.7
cffi 1.15.1
charset-normalizer 2.1.1
contourpy 1.0.7
cryptography 39.0.0
cycler 0.11.0
debugpy 1.6.6
decorator 5.1.1
entrypoints 0.4
executing 0.8.3
fastjsonschema 2.16.2
fenics-basix 0.6.0
fenics-dolfinx 0.6.0
fenics-ffcx 0.6.0
fenics-ufl 2023.1.0
flatbuffers 23.1.21
fonttools 4.38.0
frozenlist 1.3.3
gast 0.4.0
google-auth 2.16.0
google-auth-oauthlib 0.4.6
google-pasta 0.2.0
grpcio 1.51.1
h5py 3.8.0
idna 3.4
imageio 2.25.0
importlib-metadata 6.0.0
importlib-resources 5.10.2
ipydatawidgets 4.3.2
ipygany 0.5.0
ipykernel 6.15.0
ipython 8.3.0
ipywidgets 8.0.4
jedi 0.18.1
jsonschema 4.17.3
jupyter_client 7.4.9
jupyter_core 4.12.0
jupyterlab-widgets 3.0.5
keras 2.11.0
kiwisolver 1.4.4
libclang 15.0.6.1
loguru 0.6.0
Markdown 3.4.1
MarkupSafe 2.1.2
matplotlib 3.6.3
matplotlib-inline 0.1.2
mpi4py 3.1.4
multidict 6.0.4
nbformat 5.7.3
nest-asyncio 1.5.6
numpy 1.24.1
oauthlib 3.2.2
opt-einsum 3.3.0
packaging 23.0
parso 0.8.3
petsc4py 3.17.4
pexpect 4.8.0
pickleshare 0.7.5
Pillow 9.4.0
pip 23.0
pkgutil_resolve_name 1.3.10
pooch 1.6.0
prompt-toolkit 3.0.20
protobuf 3.19.6
psutil 5.9.4
ptyprocess 0.7.0
pure-eval 0.2.2
pyasn1 0.4.8
pyasn1-modules 0.2.8
pycparser 2.21
Pygments 2.11.2
pyOpenSSL 23.0.0
pyparsing 3.0.9
pyrsistent 0.19.3
PySocks 1.7.1
python-dateutil 2.8.2
pythreejs 2.4.1
pyvista 0.38.1
pyzmq 25.0.0
requests 2.28.2
requests-oauthlib 1.3.1
rsa 4.9
scipy 1.10.1
scooby 0.7.1
setuptools 66.1.1
six 1.16.0
slepc4py 3.17.2
stack-data 0.2.0
tensorboard 2.11.2
tensorboard-data-server 0.6.1
tensorboard-plugin-wit 1.8.1
tensorflow 2.11.0
tensorflow-estimator 2.11.0
tensorflow-io-gcs-filesystem 0.30.0
termcolor 2.2.0
tornado 6.2
traitlets 5.1.1
traittypes 0.2.1
typing_extensions 4.4.0
urllib3 1.26.14
vtk 9.2.5
wcwidth 0.2.5
Werkzeug 2.2.2
wheel 0.38.4
widgetsnbextension 4.0.5
wrapt 1.14.1
wslink 1.10.0
yarl 1.8.2
zipp 3.12.1

```

Conda version:

```auto
conda 23.1.0

```

Thanks for your help.

---

<div class="post-metadata">

**Author:** ![Syed\_Muhammad\_Zubair](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/syed_muhammad_zubair/32/8483_2.png) [@Syed\_Muhammad\_Zubair](https://fenicsproject.discourse.group/u/Syed_Muhammad_Zubair)\
**Post date:** [May 26, 2025, 10:36am UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/16 "2025-05-26T10:36:23Z")

</div>

Hi @dokken. I am new in fenicsx… Is there any direct function available in fenicsx by which we can compute eigenvalues and eigenvectors.  
I want to compute eigenvalue and eigenvector for **right Cauchy green tenso** r (C) in 3D domain. Thankyou for your help.

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [May 26, 2025, 11:44am UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/17 "2025-05-26T11:44:48Z")

</div>

There is functionality for using `UFL` to get the eigenvalue and eigenvectors of a problem, ref:

> <https://github.com/fenics-dolfiny/dolfiny/blob/main/src/dolfiny/invariants.py#L72-L309>

One could use these expressions inside either a projection or interpolation (using `dolfinx.fem.Expression`) to evaluate the eigenvalues and eigenvectors for specific degrees of freedom for each node/dof in the domain.

An alternative workflow would be to get the numerical tensor C by inserting it into a dolfinx.fem.Expression, evaluate it and then use

> **[numpy.linalg.eig — NumPy v2.1 Manual](https://numpy.org/doc/2.1/reference/generated/numpy.linalg.eig.html)**

---

<div class="post-metadata">

**Author:** ![Syed\_Muhammad\_Zubair](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/syed_muhammad_zubair/32/8483_2.png) [@Syed\_Muhammad\_Zubair](https://fenicsproject.discourse.group/u/Syed_Muhammad_Zubair)\
**Post date:** [May 28, 2025, 8:15pm UTC](https://fenicsproject.discourse.group/t/how-to-solve-eigenvalues-in-fenicsx/10738/18 "2025-05-28T20:15:21Z")

</div>

Dear @dokken Thankyou.  
I need to compute the maximum and minimum principal stretches (λ\_max and λ\_min) from the eigenvalues of the right Cauchy-Green tensor (C) as I want to use this in equation. Is the following UFL code correct for calculating these stretches?

```auto
######### Eigenvalues and Eigenvectors ##############

eigvalue_c , eigvector_c = eigenstate3(C)

### eigenvalues
eigvalue_c1 = eigvalue_c[0]
eigvalue_c2 = eigvalue_c[1]
eigvalue_c3 = eigvalue_c[2]

## stretches
stretch_1 = ufl.sqrt(eigvalue_c1)
stretch_2 = ufl.sqrt(eigvalue_c2)
stretch_3 = ufl.sqrt(eigvalue_c3)

### maximum stretch
max_lam = ufl.conditional(ufl.gt(stretch_1, stretch_2), stretch_1, stretch_2)
max_lam1 = ufl.conditional(ufl.gt(max_lam, stretch_3), max_lam, stretch_3)

### minimum stretch
min_lam = ufl.conditional(ufl.gt(stretch_1, stretch_2), stretch_2, stretch_1)
min_lam1 = ufl.conditional(ufl.gt(min_lam, stretch_3),stretch_3, max_lam)

## functionspace for interpolation
V_eig = fem.functionspace(domain, P3)
lam_max = fem.Expression(max_lam1, V_eig.element.interpolation_points())

lam_maxf = Function(V_eig)
lam_maxf.interpolate(lam_max)

```
