The code snippets below plots a simple sin
function first on an IntervalMesh
and then on a refined version of that mesh. The first plot is correct, but the second one is wrong. It looks like there is a mismatch between the mesh coordinates (which are sorted in ascending order) and the function values (where the values at the nodes which were added during refinement appear after the original ones).
Using dolfin
's own plot
command produces the correct output in both cases, so I'm clearly missing something regarding the ordering of the mesh coordinates vs. function dofs. I tried to replace the line
coords = mesh.coordinates()
with
coords = V.dofmap().tabulate_all_coordinates(mesh)
but this didn't help (it produced a different wrong result). Thanks in advance for any hints!
Code snippet:
from dolfin import *
import matplotlib.pyplot as plt
import numpy as np
def plot_sin_on_mesh(mesh, outfilename):
expr = Expression('sin(x[0])')
V = FunctionSpace(mesh, 'CG', 1)
f = interpolate(expr, V)
fig = plt.figure()
ax = fig.gca()
# Plot the values of the dolfin.Function
coords = mesh.coordinates()
f_vals = f.vector()[vertex_to_dof_map(V)].array()
ax.plot(coords, f_vals, 'b.-', label='f')
# Plot the sin function for comparison
xs = np.linspace(0, 2*pi, 100)
ax.plot(xs, np.sin(xs), 'b--', label='sin(x)')
ax.legend(loc='best')
fig.savefig(outfilename)
# Plot on the coarse mesh (correct result)
mesh = IntervalMesh(6, 0, 2*pi)
plot_sin_on_mesh(mesh, 'plot_coarse.png')
# Plot on the refined mesh (wrong result)
mesh2 = refine(mesh)
plot_sin_on_mesh(mesh2, 'plot_refined.png')