# How to solve eigenvalues in FEniCSx?

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) 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.

``````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)
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]])
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}")
``````
1 Like

Thanks! I will try this.

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.

``````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'
``````

The error comes from this line:

``````from analytical_modes import verify_mode
``````

You need to download the file analytical modes from dolfinx/python/demo/demo_waveguide at v0.6.0 · FEniCS/dolfinx · GitHub

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

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

I am using pyvista 0.37.0

Could you try upgrading to `0.38.1`?

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.

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

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?

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

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.

``````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
grpcio                       1.51.1
h5py                         3.8.0
idna                         3.4
imageio                      2.25.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
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
``````conda 23.1.0