Interpolate Gaussian distrbution in mixed element space

I’m interpolating a Gaussian distribution as the IC for my system of time-dependent equations, but I keep getting the error: Couldn’t map ‘c_4’ to a float, returning ufl object without evaluation.

Past examples of this error include not using the in-built ufl functions for exp, which I have fixed.

I’ve tested and the issue isn’t with using multiple function spaces to account for only two of the five variables being time-dependent (would appreciate advice on whether this is a wise option too!)

Dolfinx installed via conda on Mac M1 Monterey.

Thank you so much!

Below is the minimal code:

import ufl
from dolfinx import mesh, fem, io, nls, log
from mpi4py import MPI
from petsc4py import PETSc
import numpy as np

xmin = -5
xmax = 5
ymax = 5
domain = mesh.create_rectangle(MPI.COMM_WORLD, [(xmin,0),(xmax,ymax)], n=[200, 50])

x = ufl.SpatialCoordinate(domain)
degree = 3
P1 = ufl.FiniteElement("Lagrange", domain.ufl_cell(), degree) 
element = ufl.MixedElement([P1, P1, P1, P1, P1]) #create a mixed function space 
V = fem.FunctionSpace(domain, element)  

#we create another function space for the t dependent h1 and h2 only
element2 = ufl.MixedElement([P1, P1])
W = fem.FunctionSpace(domain, element2) 

v1, v2, v3, v4, v5 = ufl.TestFunctions(V)

u = fem.Function(V) 
u_n = fem.Function(W) #update previous solution 
h1, h2, p1, p2, ul = ufl.split(u) 
h1_n, h2_n = ufl.split(u_n) 

#Define constants
Hbath = 2.0
shape = fem.Constant(domain, PETSc.ScalarType(5.0)) 
Aconst = fem.Constant(domain, PETSc.ScalarType(100.0))
hinf = fem.Constant(domain, PETSc.ScalarType(0.01))

#ERROR
u.sub(1).interpolate(Hbath + hinf + ufl.sqrt(shape*pi) * ufl.exp(-shape*pow(x[0],2)) * 4./3)
u.x.scatter_forward()

You could use a simple lambda function for this:

import ufl
from dolfinx import mesh, fem, io, nls, log
from mpi4py import MPI
from petsc4py import PETSc
import numpy as np

xmin = -5
xmax = 5
ymax = 5
domain = mesh.create_rectangle(MPI.COMM_WORLD, [(xmin,0),(xmax,ymax)], n=[200, 50])

x = ufl.SpatialCoordinate(domain)
degree = 3
P1 = ufl.FiniteElement("Lagrange", domain.ufl_cell(), degree) 
element = ufl.MixedElement([P1, P1, P1, P1, P1]) #create a mixed function space 
V = fem.FunctionSpace(domain, element)  

#we create another function space for the t dependent h1 and h2 only
element2 = ufl.MixedElement([P1, P1])
W = fem.FunctionSpace(domain, element2) 

v1, v2, v3, v4, v5 = ufl.TestFunctions(V)

u = fem.Function(V) 
u_n = fem.Function(W) #update previous solution 
h1, h2, p1, p2, ul = ufl.split(u) 
h1_n, h2_n = ufl.split(u_n) 

#Define constants
Hbath = 2.0
shape = 5.0
Aconst = 100.0
hinf = 0.01
gaussian = lambda x: Hbath + hinf + np.sqrt(shape*np.pi) * np.exp(-shape*x[0]**2) * 4./3

#ERROR
u.sub(1).interpolate(gaussian)
u.x.scatter_forward()

1 Like