Is it possible to import a .csv data file to FEniCS

432 views
Skip to first unread message

Dmitry Golovaty

unread,
Oct 16, 2016, 1:19:22 AM10/16/16
to fenics-support

I need to import an initial condition for a vector-valued solution of a PDE in 2 dimensions that is defined as a table in a .csv text file. The file has four columns representing x- and y- coordinates of a point and the components of a vector function at that point, respectively. Is it possible to import this data into a FEniCS code and interpolate it over an already defined mesh? Thanks in advance,

Dmitry


Jan Blechta

unread,
Oct 16, 2016, 3:31:23 AM10/16/16
to Dmitry Golovaty, fenics-support
Example which runs with FEniCS 2016.1.0 or current master:

File dato.xyz
============================
0.0 0.0 666.0
1.0 0.0 1000.0
0.0 1.0 2000.0
1.0 1.0 -300.0
============================

Python code
============================
from dolfin import *
import numpy as np
from scipy.interpolate import interp2d

data = np.loadtxt('dato.xyz')
x, y, values = data[:,0], data[:,1], data[:,2]
interpolant = interp2d(x, y, values, kind='linear', copy=False, bounds_error=True)

class ExpressionFromScipyFunction(Expression):
def __init__(self, f, *args, **kwargs):
self._f = f
def eval(self, values, x):
values[:] = self._f(*x)

mesh = UnitSquareMesh(3, 3)
expression = ExpressionFromScipyFunction(interpolant, degree=2, domain=mesh)
plot(expression, mesh=mesh)
interactive()
============================

Jan

Jan Blechta

unread,
Oct 16, 2016, 3:33:39 AM10/16/16
to Dmitry Golovaty, fenics-support
Note that evaluating provided expression is very very slow. So for
its further usage it might be advantageous to interpolate it to a
suitable DOLFIN Function first.

Jan

Dmitry Golovaty

unread,
Oct 16, 2016, 1:57:11 PM10/16/16
to fenics-support
Many thanks, Jan - not sure if I fully understand how one would implement what you are suggesting in your second comment.

Best,

Dmitry

Jan Blechta

unread,
Oct 17, 2016, 7:13:45 AM10/17/16
to Dmitry Golovaty, fenics-support
On Sun, 16 Oct 2016 10:57:11 -0700 (PDT)
Dmitry Golovaty <dgol...@gmail.com> wrote:

> Many thanks, Jan - not sure if I fully understand how one would
> implement what you are suggesting in your second comment.

V = FunctionSpace(mesh, expression.ufl_element())
expression = interpolate(expression, V)

Jan

Dmitry Golovaty

unread,
Oct 17, 2016, 12:10:04 PM10/17/16
to fenics-support
Thank you!
Message has been deleted

ricardob...@gmail.com

unread,
Mar 21, 2019, 10:51:27 AM3/21/19
to fenics-support
Hi Jan,
when I run this code with UseExpression instead of Expression I get "AttributeError: 'ExpressionFromScipyFunction' object has no attribute '_ufl_function_space'
" what am I doing wrong?
thanks,
Reply all
Reply to author
Forward
0 new messages