# Solution becomes NaN when parameters are too high

**URL:** <https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331>\
**Category:** Uncategorized\
**Created:** [March 17, 2021, 1:22pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331 "2021-03-17T13:22:28Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![marcbzzz](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/marcbzzz/32/2069_2.png) [@marcbzzz](https://fenicsproject.discourse.group/u/marcbzzz)\
**Post date:** [March 17, 2021, 1:22pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/1 "2021-03-17T13:22:28Z")

</div>

Hello, I’m quite new to FEniCS and I’m encoutering a problem with my program. I’m calculating the displacement of an elastic membrane under internal pressure.

I can vary different parameters such as the pressure of the number of iterations. When the values are not too big, the program works fine and I get very nice plots.  
However if I increase the pressure or the meshSize or the number of iterations too much. The displacement vector becomes NaN everywhere.  
And I don’t know exactly why.

**Do you have any idea of how I could solve this - as a beginner ?**

Here’s my code and the plots I get when the values are too high and when they are the working range

 ![Capture d’écran 2021-03-17 à 14.18.19](https://global.discourse-cdn.com/free1/uploads/fenicsproject1/original/2X/6/694786e63d0e0444d9d23d8e750de9eabdca6780.png)

 ![Capture d’écran 2021-03-17 à 14.13.23](https://global.discourse-cdn.com/free1/uploads/fenicsproject1/original/2X/f/f8dffc4e9b01d8d01d132f3373367a15a11d7c77.png)

> from **future** import print\_function  
> from fenics import \*  
> import numpy as np  
> from dolfin import \*  
> from mshr import \*  
> import matplotlib.pyplot as plt  
> %matplotlib notebook
> 
> # Constants
> 
> Re = 12  
> Ri = 9  
> p = 220  
> dP = 5000  
> H = 9  
> Hinv = Re - H
> 
> iterations = 89  
> meshSize = 2  
> E\_tip = 1e5  
> ratio = 10  
> E\_side = E\_tip\*ratio  
> tol = 0.1
> 
> # Create Domain & Mesh
> 
> domain = Circle(Point(0., 0.), Re, 100) - Circle(Point(0., 0.), Ri, 100)  
> domain = domain - Rectangle(Point(Re, 0.), Point(-Re, -Re))   
> + Rectangle(Point(Ri, -10), Point(Re, 0))   
> + Rectangle(Point(-Ri,-10),Point(-Re,0))  
> #domain = domain + Circle(Point(0., 0.), Ri, 100) + R
> 
> # Create Mesh
> 
> mesh = generate\_mesh(domain, meshSize)  
> meshBeforeContraction = generate\_mesh(domain, meshSize)  
> originalMesh = generate\_mesh(domain, meshSize)
> 
> # Set Subdomains and Mark Subdomains
> 
> tipDomain = CompiledSubDomain(‘x[0]\*x[0] + x[1]_x[1] + tol \>= Ri_Ri   
> && x[0]\*x[0] + x[1]_x[1] - tol \<= Re_Re && x[1]\>=0- tol &&x[1]\>=Hinv-tol   
> ||(x[1] \<= 0 + tol &&x[1]\>=Hinv && abs(x[0])\<=Re+tol && abs(x[0])\>=Ri -tol)’,  
> tol=tol, Hinv=Hinv, Re=Re, Ri=Ri)  
> sideDomain = CompiledSubDomain('x[1] \<= Hinv + tol && x[0]\<=Re && x[0]\>=Ri -tol ',  
> tol=tol, Hinv=Hinv, Re=Re, Ri=Ri)
> 
> subdomains = MeshFunction(‘size\_t’, mesh, mesh.topology().dim(), 0)  
> subdomains.set\_all(4)  
> tipDomain.mark(subdomains, 5)
> 
> # Create Boundaries
> 
> class Bottom(SubDomain):  
> def inside(self, x, on\_boundary):  
> return near(x[1], -10) and on\_boundary
> 
> class Inner(SubDomain):  
> def inside(self, x, on\_boundary):  
> return (near(sqrt(x[0]\*\*2+x[1]\*\*2), Ri, 1e-1) and x[1] \> Hinv and on\_boundary)  
> or (near(x[0], Ri) and x[1] \> -10 and x[1] \< 0 and on\_boundary)
> 
> class InnerHard(SubDomain):  
> def inside(self, x, on\_boundary):  
> return (near(sqrt(x[0]\*\*2+x[1]\*\*2), Ri, 0.5) and x[1]-tol \<= Hinv and x[1] + tol \>= 0 and on\_boundary)  
> or (near(abs(x[0]), Ri) and x[1]+tol \>= -10 and x[1]-tol \<= 0 and x[1]+tol \<= Hinv and on\_boundary)
> 
> class InnerSoft(SubDomain):  
> def inside(self, x, on\_boundary):  
> return (near(sqrt(x[0]\*\*2+x[1]\*\*2), Ri, 0.5) and x[1] \>= Hinv and x[1] \>= 0 and on\_boundary)  
> or (near(abs(x[0]), Ri) and x[1] \>= -10 and x[1] \<= 0 and x[1] \>= Hinv and on\_boundary)
> 
> # Mark facets
> 
> facets = MeshFunction(“size\_t”, mesh, 1)  
> facets.set\_all(0)  
> Bottom().mark(facets, 1)  
> Inner().mark(facets, 3)  
> InnerHard().mark(facets, 31)  
> InnerSoft().mark(facets, 32)
> 
> ds = Measure(“ds”, subdomain\_data=facets)
> 
> # Young Modulus
> 
> class Young(UserExpression):  
> def **init** (self, subdomains, tip, side, \*\*kwargs):  
> super(). **init** (\*\*kwargs)  
> self.subdomains = subdomains  
> self.side = side  
> self.tip = tip
> 
> ```
> def eval_cell(self, values, x, cell):
> if self.subdomains[cell.index] == 4:
> values[0] = self.side
> else:
> values[0] = self.tip
> 
> ```
> 
> x = SpatialCoordinate(mesh)
> 
> # Define constants stress/stain :
> 
> E = Young(subdomains=subdomains, side=E\_side, tip=E\_tip, degree=0)  
> nu = Constant(0.3)  
> mu = E/2/(1+nu)  
> lmbda = E_nu/(1+nu)/(1-2_nu)
> 
> # Define Strain Tenosr
> 
> def eps(v):  
> return sym(as\_tensor([[v[0].dx(0), 0, v[0].dx(1)],  
> [0, v[0]/x[0], 0],  
> [v[1].dx(0), 0, v[1].dx(1)]]))
> 
> # Define Stress
> 
> ‘’‘3D hookes law formula of stress’‘’
> 
> def sigma(v):  
> return lmbda_tr(eps(v))Identity(3) + 2.0mu_eps(v)
> 
> n = FacetNormal(mesh)
> 
> V = VectorFunctionSpace(mesh, ‘CG’, degree=2)  
> V\_original = VectorFunctionSpace(originalMesh, ‘CG’, degree=2)  
> du = TrialFunction(V)  
> u\_ = TestFunction(V)  
> a = inner(sigma(du), eps(u\_))\*x[0]_dx  
> l = inner(-p_n, u\_)\*x[0]_ds(31) + inner(-p_n, u\_)\*x[0]\*ds(32)
> 
> u = Function(V, name=“Displacement”)  
> u\_original = Function(V\_original, name=“original position”)
> 
> ‘’‘THIS IS THE INTERESTING BOUNDARY CASE’‘’
> 
> bcs2 = [DirichletBC(V, Constant((0., 0.)), facets, 1)]
> 
> #fid = File(“viz/solution.pvd”)  
> for i in range(0, iterations):  
> solve(a == l, u, bcs2)  
> # u.rename(“u”, “u”) #see the QA reported below.  
> #fid \<\< u, i
> 
> ```
> ALE.move(mesh, u)
> meshBeforeContraction = Mesh(mesh)
> 
> ```
> 
> plt.figure()  
> #plot(mesh, linewidth=0.2)  
> plot(originalMesh, linewidth=0.2)  
> p2 = plot(u, mode=“displacement”)  
> plt.colorbar(p2)  
> plt.axhline(y=Hinv, color=‘b’, linestyle=‘–’)
> 
> plt.show()  
> plt.title(‘Model before contraction ;’ + 'H = ’ + str(H))

Thank you so much in advance

---

<div class="post-metadata">

**Author:** ![marcbzzz](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/marcbzzz/32/2069_2.png) [@marcbzzz](https://fenicsproject.discourse.group/u/marcbzzz)\
**Post date:** [March 18, 2021, 4:29pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/2 "2021-03-18T16:29:51Z")

</div>

Hi, anyone has an idea ? I heard the words “singularity” and preconditioned . However I have no idea of how to implement those here.

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [March 19, 2021, 12:17pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/3 "2021-03-19T12:17:20Z")

</div>

Please format your code appropriately.  
You should use 3x` encapsulation around your code, such that quotation, comments and indentation is preserved.

Example:

```python
from dolfin import *
def test():
    mesh = UnitSquareMesh(10, 10)
    V = FunctionSpace(mesh, "CG", 1)
    return V
test()

```

---

<div class="post-metadata">

**Author:** ![dparsons](https://avatars.discourse-cdn.com/v4/letter/d/5e9695/32.png) [@dparsons](https://fenicsproject.discourse.group/u/dparsons)\
**Post date:** [March 19, 2021, 2:19pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/4 "2021-03-19T14:19:31Z")

</div>

Since you have a working solution in hand, one general approach is to use that solution iteratively. Apply the previous solution as an initial guess for the next iteration, increasing your control parameter incrementally at each iteration until it reaches the value you want.

---

<div class="post-metadata">

**Author:** ![marcbzzz](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/marcbzzz/32/2069_2.png) [@marcbzzz](https://fenicsproject.discourse.group/u/marcbzzz)\
**Post date:** [March 19, 2021, 4:13pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/5 "2021-03-19T16:13:44Z")

</div>

```auto

from __future__ import print_function
from fenics import *
import numpy as np
from dolfin import *
from mshr import *
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'notebook')

# Constants
H = 11
p = Constant(100.)
Hinv = 11 - H
Re = 11.
Ri = 9
iterations = 20

¨
# Create Domain & Mesh
domain = Circle(Point(0., 0.), Re, 100) - Circle(Point(0., 0.), Ri, 100)
domain = domain - Rectangle(Point(Re, 0.), Point(-Re, -Re)) + Rectangle(Point(Ri, -10), Point(Re, 0)) + Rectangle(Point(-Ri,-10),Point(-Re,0))
# Create Mesh
mesh = generate_mesh(domain, 5)
originalMesh = generate_mesh(domain, 100)

# Set Subdomains and Mark Subdomains

tol = 0.1
tipDomain = CompiledSubDomain('x[0]*x[0] + x[1]*x[1] + tol >= Ri*Ri && x[0]*x[0] + x[1]*x[1] - tol <= Re*Re && x[1]>=0- tol &&x[1]>=Hinv-tol ||(x[1] <= 0 + tol &&x[1]>=Hinv && abs(x[0])<=Re+tol && abs(x[0])>=Ri -tol)',
                              tol=tol, Hinv=Hinv, Re=Re, Ri=Ri)
sideDomain = CompiledSubDomain('x[1] <= Hinv + tol && abs(x[0])<=Re+tol && abs(x[0])>=Ri -tol ',
                               tol=tol, Hinv=Hinv, Re=Re, Ri=Ri)

subdomains = MeshFunction('size_t', mesh, mesh.topology().dim(), 0)
subdomains.set_all(4)
tipDomain.mark(subdomains, 5)

# Create Boundaries
class Bottom(SubDomain):
    def inside(self, x, on_boundary):
        return near(x[1], -10) and abs(x[0])>=3 and on_boundary

class Outer(SubDomain):
    def inside(self, x, on_boundary):
        return (near(sqrt(x[0]**2+x[1]**2), Ri, 1e-1) and x[1] > Hinv and on_boundary) or (near(x[0], abs(Ri)) and x[1] > -10 and x[1] < 0 and on_boundary)
    
class TopMiddle(SubDomain):
    def inside(self, x, on_boundary):
        return near(x[0],0)

# Mark facets
facets = MeshFunction("size_t", mesh, 1)
facets.set_all(0)
Bottom().mark(facets, 1)
Outer().mark(facets, 3)
TopMiddle().mark(facets,2)
ds = Measure("ds", subdomain_data=facets)

# In[3]:

# Plot the mesh and horizontal line
plt.figure()
plot(mesh)

plt.axhline(y=Hinv, color='b', linestyle='--')

plot(subdomains)

class Young(UserExpression):
    def __init__ (self, subdomains, tip, side, **kwargs):
        super(). __init__ (**kwargs)
        self.subdomains = subdomains
        self.side = side
        self.tip = tip

    def eval_cell(self, values, x, cell):
        if self.subdomains[cell.index] == 4:
            values[0] = self.side
        else:
            values[0] = self.tip

x = SpatialCoordinate(mesh)
# Define constants stress/stain :
E_tip = 1e4
E_side = 1e6
E = Young(subdomains=subdomains, side=E_side, tip=E_tip, degree=0)
nu = Constant(0.3)
mu = E/2/(1+nu)
lmbda = E*nu/(1+nu)/(1-2*nu)
tol = 1e-1

# Define Strain Tenosr
def eps(v):
    return sym(as_tensor([[v[0].dx(0), 0, v[0].dx(1)],
                          [0, v[0]/x[0], 0],
                          [v[1].dx(0), 0, v[1].dx(1)]]))

# Define Stress

def sigma(v):
    return lmbda*tr(eps(v))*Identity(3) + 2.0*mu*eps(v)

¨
n = FacetNormal(mesh)

V = VectorFunctionSpace(mesh, 'CG', degree=2)
V_original = VectorFunctionSpace(originalMesh, 'CG', degree=2)
du = TrialFunction(V)
u_ = TestFunction(V)
a = inner(sigma(du), eps(u_))*x[0]*dx    
l = inner(-p*n, u_)*x[0]*ds(3)

u = Function(V, name="Displacement")
u_original = Function(V_original, name="original position")

# Boundaries and solving
bcs2 = [DirichletBC(V, Constant((0., 0.)), facets, 1)]

fid = File("../Desktop/Viz/solution.pvd")
for i in range(0, iterations):
    solve(a == l, u, bcs2)

    #u.rename("u", "u") #see the QA reported below.
    #fid << u, i
    ALE.move(mesh, u)

plt.figure()
#plot(mesh, linewidth=0.2)
plot(originalMesh, linewidth=0.2)
p2 = plot(u, mode="displacement")
plt.colorbar(p2)
plt.axhline(y=Hinv, color='b', linestyle='--')

plt.show()

```

---

<div class="post-metadata">

**Author:** ![marcbzzz](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/marcbzzz/32/2069_2.png) [@marcbzzz](https://fenicsproject.discourse.group/u/marcbzzz)\
**Post date:** [March 19, 2021, 4:13pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/6 "2021-03-19T16:13:58Z")

</div>

sorry I just fixed it

---

<div class="post-metadata">

**Author:** ![marcbzzz](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/marcbzzz/32/2069_2.png) [@marcbzzz](https://fenicsproject.discourse.group/u/marcbzzz)\
**Post date:** [March 19, 2021, 4:28pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/7 "2021-03-19T16:28:27Z")

</div>

What do you mean exactly ?

---

<div class="post-metadata">

**Author:** ![dparsons](https://avatars.discourse-cdn.com/v4/letter/d/5e9695/32.png) [@dparsons](https://fenicsproject.discourse.group/u/dparsons)\
**Post date:** [March 19, 2021, 5:02pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/8 "2021-03-19T17:02:00Z")

</div>

Depending on the specific algorithm, the algorithm can converge more efficiently by commencing from some initial function (a known approximate solution). This is the case in FEniCS, at least with the nonlinear solver, which internally uses Newton iterations to converge to the solution.

The default initial function used in the FEniCS nonlinear solver is the trivial function, zero everywhere. You can override that by assigning a known function to `u` (the variable `u` that is provided to the `solve(...)` function) before running the `solve` function.

Note that in your example you’re invoking the high level `solve` function, which is a wrapper around a LinearSolver, not a NonlinearSolver. You can’t assign an initial guess in the case of the LinearSolver. You’d have to rework your code to use the NonlinearSolver.

---

<div class="post-metadata">

**Author:** ![marcbzzz](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/marcbzzz/32/2069_2.png) [@marcbzzz](https://fenicsproject.discourse.group/u/marcbzzz)\
**Post date:** [March 22, 2021, 1:56pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/9 "2021-03-22T13:56:14Z")

</div>

I realized that there was a problem with values of x =0, since my plot seems to have diverge giving crazy displacements when x is near 0.

**I think there is a division by 0 somewhere. The thing is , I don’t know how to solve it.**

**Do you have an idea ?**

---

<div class="post-metadata">

**Author:** ![dparsons](https://avatars.discourse-cdn.com/v4/letter/d/5e9695/32.png) [@dparsons](https://fenicsproject.discourse.group/u/dparsons)\
**Post date:** [March 22, 2021, 6:44pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/10 "2021-03-22T18:44:59Z")

</div>

You have` v[0]/x[0]` . Looks like it’s mathematically divergent. Do you expect v/x to be finite at x=0 ?

---

<div class="post-metadata">

**Author:** ![marcbzzz](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/marcbzzz/32/2069_2.png) [@marcbzzz](https://fenicsproject.discourse.group/u/marcbzzz)\
**Post date:** [March 23, 2021, 9:06pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/11 "2021-03-23T21:06:59Z")

</div>

Yes I do. However, even replacing x[0] by a number in v[0]/x[0] doesn’t solve the problem. There still is a division by 0 somewhere that I can’t get rid of 😕

---

<div class="post-metadata">

**Author:** ![dparsons](https://avatars.discourse-cdn.com/v4/letter/d/5e9695/32.png) [@dparsons](https://fenicsproject.discourse.group/u/dparsons)\
**Post date:** [March 23, 2021, 9:14pm UTC](https://fenicsproject.discourse.group/t/solution-becomes-nan-when-parameters-are-too-high/5331/12 "2021-03-23T21:14:06Z")

</div>

Your code does not run. Can you make sure it runs cleanly by copy&paste using the python command? Provide a minimal code example. You’ve got references to ipython which are not relevant to the problem and prevent the code from running.
