When I tried to explore the coupling between the cahnhilliard equation and the ns equation, I found that I did not know how to perform nonsmooth operations on variables in the finite element space, such as when the relationship between density and concentration is a piecewise linear function.
The following is my code:
import random
from numpy.ma import tanh
import numpy as np
from fenics import *
from matplotlib import pyplot as plt
# piecewise function
def den(c_):
rho = np.piecewise(
c_, [0 <= c_ < c_ox, c_ox <= c_ < c_met, c_met <= c_ <= 1],
(lambda c_: (rho_eq_ox - rho_int_ox) / c_ox * c_ + rho_int_ox,
lambda c_: (rho_eq_met - rho_eq_ox) / (c_met - c_ox) * (c_ - c_ox) + rho_eq_ox,
lambda c_: (rho_eq_met - rho_int_met) / (c_met - 1) * (c_ - c_met) + rho_eq_met
)
)
return rho
class InitialConditions(UserExpression):
def eval(self, values, x):
x_ = x[0]
y_ = x[1]
random.seed(x_)
rx = 2 * random.random() - 1
values[0] = 0.5 * (1 + tanh(2 / wint * (y_ - L - 0.5e-4 * L * rx)))
values[1] = 0.0
def value_shape(self):
return 2,
# Sub domain for Periodic boundary condition
class PeriodicBoundaryX(SubDomain):
def inside(self, x, on_boundary):
return DOLFIN_EPS > x[0] > (- DOLFIN_EPS) and on_boundary
def map(self, x, y):
y[0] = x[0] - L
y[1] = x[1]
#
L = 0.176
wint = L / 16
rho_int_ox = 8.24783e3
rho_int_met = 6.96642e3
rho_eq_ox = 7.97994e3
rho_eq_met = 9.01478e3
c_ox = 1.87512e-3
c_met = 6.16085e-1
nx = 192
ny = 384
mesh = RectangleMesh(Point(0, 0), Point(L, 2 * L), nx, ny)
P1 = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
ME = FunctionSpace(mesh, P1 * P1)
du = TrialFunction(ME)
q, v = TestFunctions(ME)
u = Function(ME) # current solution
u0 = Function(ME) # solution from previous converged step
dc, dmu = split(du)
c, mu = split(u)
c0, mu0 = split(u0)
u_init = InitialConditions(degree=1)
u.interpolate(u_init)
u0.interpolate(u_init)
#
u_0 = u.split(deepcopy=True)[0]
rho_0 = den(u_0.vector().get_local()) #How will I modify the line code?
The following error message is:
Traceback (most recent call last):
File "/home/wangyao/PycharmProjects/hello_word/main.py", line 88, in <module>
rho_0 = den(u_0.vector().get_local())
File "/home/wangyao/PycharmProjects/hello_word/main.py", line 11, in den
c_, [0 <= c_ < c_ox, c_ox <= c_ < c_met, c_met <= c_ <= 1],
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I hope to calculate the density distribution based on the c distribution.
Here is the relationship between density and concentration:
Thank you for your help!