Below is code that solves an eigenvalue problem. Unfortunately, the first couple of solutions do not satisfy the boundary conditions. Is there a way to prevent those from occurring? Maybe I'm not imposing the boundary conditions correctly?
from dolfin import *
import numpy as np
# Create mesh and define function space
nx = 20
L = 4.0
mesh = IntervalMesh(nx,0.0,L)
# Order of method
p = 0
# Function Spaces
V0 = FunctionSpace(mesh, 'CG', p+2)
zeroVelocity = Constant(0.0)
def left(x, on_boundary): return x[0] < DOLFIN_EPS
def right(x, on_boundary): return x[0] > L - DOLFIN_EPS
bc0 = DirichletBC(V0, zeroVelocity, left)
bc1 = DirichletBC(V0, zeroVelocity, right)
bcs = [bc0, bc1]
# Parameters
beta = Constant(1e0)
k2 = Constant((2.*np.pi/L)**2)
# Define variational problem
p = TrialFunction(V0)
r = TestFunction(V0)
a = -beta*(r*p)*dx
b = (r.dx(0)*p.dx(0) + k2*r*p)*dx
# Assemble Matrices
A = PETScMatrix()
assemble(a, tensor=A)
[bc.apply(A) for bc in bcs]
B = PETScMatrix()
assemble(b, tensor=B)
[bc.apply(B) for bc in bcs]
# Create eigensolver
eigensolver = SLEPcEigenSolver(A, B)
eigensolver.parameters["spectrum"] = "largest magnitude"
# Compute all eigenvalues of A x = \lambda B x
print("Computing eigenvalues. This can take a minute.")
num = 6
eigensolver.solve(num)
print -1e0/((2.*np.pi/L)**2 + (np.arange(1,5)*np.pi/4.0)**2)
psi = Function(V0)
psi_vec = psi.vector()
# Extract largest (first) eigenpair
print("Before get_eigenpair")
for i in range(num):
r, c, rx, cx = eigensolver.get_eigenpair(i)
print("Eigenvalue:", i, r, c)
plot(Function(V0, rx), title='%d real' % i)
interactive()