PETSc error code is: 73, Object is in wrong state (2D Nonlinear Reaction-Diffusion Equation)

Hi all,

First time posting and related to a similar question posted a few days ago (i.e., PETSc error code is: 73, Object is in wrong state for simple hyperelastic problem).

After following through the tutorials provided for FEniCSx, I tried to solve a 2D nonlinear Reaction-Diffusion PDE (Lagrangian Formulation) over a circular domain containing two reaction species with No flux Neumann Boundary Conditions. Attempting to formulate the problem and solve the nonlinear time-discretised system results in the following Error code 73 in PETSc:

line 158, in <module>
    num_its, converged = solver.solve(c)
                         ^^^^^^^^^^^^^^^
  File "/Users/vozcoban/micromamba/envs/fenicsx/lib/python3.12/site-packages/dolfinx/nls/petsc.py", line 47, in solve
    n, converged = super().solve(u.x.petsc_vec)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Failed to successfully call PETSc function 'KSPSolve'. PETSc error code is: 73, Object is in wrong state

As a side note, for the various terms when formulating the problem there is an additional quirk in the solver (which may or may not be related but results in the same error code). I have left in all of term1-4 for both Func_A and Func_I as there is an additional issue related to the solver.convergence_criterion setting. If solver.convergence_criterion = “incremental”, then all of the individual terms result in Error 73. However, if solver.convergence_criterion = “residual”, only term3_A and term3_I result in Error 73. Not sure if this is related or not hence why it was kept in the MWE.

Moreover, I’m not sure if I’ve set up my initial conditions properly. These should be the constants 0 and 1. Is this how you would set up constant initial conditions? Not sure if this is what’s causing the problem.

Additional Information:
OS: macOS Sonoma 14.5
FEniCSx Version: 0.8.0
Installation Procedure (FEniCSx/dolfinx): micromamba (conda-forge)
Installation Procedure (gmsh): micromamba (pip)

The MWE code is as follows:

#-------------
# IMPORTS
#-------------

import ufl
import numpy as np
import gmsh
from mpi4py import MPI

from dolfinx import fem, mesh
from dolfinx.io import gmshio
from dolfinx.fem.petsc import NonlinearProblem
from dolfinx.nls.petsc import NewtonSolver
import basix



#-------------
# CREATE MESH
#-------------

# Initialise the GMSH module
gmsh.initialize()

# Create the membrane and start the computations by the GMSH CAD kernel, to generate the relevant underlying data structures
membrane = gmsh.model.occ.addDisk(0, 0, 0, 1, 1) # x, y, z, x-radius, y-radius
gmsh.model.occ.synchronize()

# Make membrane a physical surface for GMSH to recognise when generating the mesh
gdim = 2 # 2D Geometric Dimension of the Mesh
gmsh.model.addPhysicalGroup(gdim, [membrane], 0) # Dimension, Entity tag, Physical tag

# Generate 2D Mesh with uniform mesh size
gmsh.option.setNumber("Mesh.CharacteristicLengthMin", 0.25)
gmsh.option.setNumber("Mesh.CharacteristicLengthMax", 0.25)
gmsh.model.mesh.generate(gdim)

# Create a mesh from the GMSH model
gmsh_model_rank = 0
mesh_comm = MPI.COMM_WORLD
domain, cell_markers, facet_markers = gmshio.model_to_mesh(gmsh.model, mesh_comm, gmsh_model_rank, gdim=gdim)
# Finalize GMSH
gmsh.finalize()


#---------------------
# CREATE FEM FUNCTIONS
#---------------------

# Time Discretisation
t = 0 # Initial Time
T = 200 # Final Time
Nsteps = 2000 # Number of Time Steps
dt = T/Nsteps # Time Step Size


# Global Spatial Coordinates as a Vector-Valued Expression i.e. x[0] = x, x[1] = y
x = ufl.SpatialCoordinate(domain) # This may not be needed

P1 = basix.ufl.element(family="Lagrange", cell=domain.topology.cell_name(), degree=1)
element = basix.ufl.mixed_element([P1, P1])
C = fem.functionspace(mesh=domain, element=element)

# Create function space for concentrations
c = fem.Function(C)
c.name = "c"

c_n = fem.Function(C)
c_n.name = "c_n"

c_A, c_I = c.split()
c_A_n, c_I_n = c_n.split()
w_A, w_I = ufl.TestFunction(C)


#-------------------------------------------------------
# CONSTANT INITIAL CONDITIONS AND NO BOUNDARY CONDITIONS
#-------------------------------------------------------

# Initial Conditions of Species I=1 and Species A=0
c_A_0 = fem.Constant(domain, 0.0)
c_I_0 = fem.Constant(domain, 1.0)

c_A.interpolate(lambda x: np.full((x.shape[1],), c_A_0))
c_I.interpolate(lambda x: np.full((x.shape[1],), c_I_0))
c_A_n.interpolate(lambda x: np.full((x.shape[1],), c_A_0))
c_I_n.interpolate(lambda x: np.full((x.shape[1],), c_I_0))


#---------------------------
# REACTION-DIFFUSION PROBLEM
#---------------------------

# Reaction Function
def reaction_function(cA, cI):
    delta = fem.Constant(domain, 3.0) # Deactivation Rate
    b_0 = fem.Constant(domain, 2.0) # Basal Activation Rate
    c_hill = fem.Constant(domain, 1.0) # Hill Function Magnitude
    cA_0 = fem.Constant(domain, 0.5)
    
    return (b_0 + c_hill * (cA**6/(cA_0**6 + cA**6))) * cI - delta * cA


# Setting up tensors
spa_dim = len(x) # Spatial Dimension
I = ufl.Identity(spa_dim) # Identity Tensor
F = ufl.variable(ufl.Identity(spa_dim)) # Deformation Gradient Tensor (e.g. Identity Tensor)
F_inv = ufl.inv(F)
F_inv_tra = ufl.transpose(F_inv)
J = fem.Constant(domain, 1.0) # Jacobian Function (e.g. Constant or Pre-Defined Function)
J_n = J

# Examine Isotropic Diffusion where D_A=D*I (Diffusivity Constant multiplied by the Identity Tensor)
D_A = 2 * I
D_A_eq = J * F_inv * D_A * F_inv_tra
D_I = 4 * I
D_I_eq = J * F_inv * D_I * F_inv_tra


# Measure Set Up
metadata = {"quadrature_degree": 3}
dx = ufl.Measure('dx', domain=domain, metadata=metadata)


# Weak Form Set Up
term1_A = J * (c_A - c_A_n)/dt * w_A * dx 
term2_A = ufl.inner(D_A_eq * ufl.grad(c_A), ufl.grad(w_A)) * dx
term3_A = -J * reaction_function(c_A, c_I) * w_A * dx
term4_A = c_A * (J - J_n)/dt * w_A * dx

Func_A = term1_A + term2_A + term3_A + term4_A

term1_I = J * (c_I - c_I_n)/dt * w_I * dx
term2_I = ufl.inner(D_I_eq * ufl.grad(c_I), ufl.grad(w_I)) * dx
term3_I = J * reaction_function(c_A, c_I) * w_I * dx
term4_I = c_I * (J - J_n)/dt * w_I * dx

Func_I = term1_I + term2_I + term3_I + term4_I

Func = Func_A + Func_I

# Create Nonlinear Problem and Solver
problem = NonlinearProblem(Func, c, bcs=[])
solver = NewtonSolver(MPI.COMM_WORLD, problem)
solver.atol = 1e-8
solver.rtol = 1e-8
solver.convergence_criterion = "incremental" # Incremental causes State issues but Residual only causes for term3_A and term3_I
solver.report = True


# Update Function for each time step of the reaction-diffusion problem
for i in range(Nsteps):
    t += dt

    # Solve PDE for the current time step
    num_its, converged = solver.solve(c)
    assert converged
    
    c.x.scatter_forward

    # Update solution (c) at previous time step (c_n)
    c_A_n.x.array[:] = c_A.x.array
    c_I_n.x.array[:] = c_I.x.array

Cheers,
Volkan

Hi Volkan,

How did you install dolfinx? When running your code I get the following error, instead of the PETSc error code 73:

  File "/Users/hherlyng/Python/debug/nonlin_prob_petsc_73code.py", line 154, in <module>
    num_its, converged = solver.solve(c)
                         ^^^^^^^^^^^^^^^
  File "/opt/anaconda3/envs/fenicsx/lib/python3.11/site-packages/dolfinx/nls/petsc.py", line 46, in solve
    n, converged = super().solve(u.vector)
                   ^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Newton solver did not converge because maximum number of iterations reache

With the way you’ve set the initial conditions, only a set of the dofs are assigned values because dolfinx attempts to interpolate the constant into the function space of the concentrations. I slightly changed your initial conditions by changing that part of the code to

c_A.x.array[:] = np.full((c_A.x.array.__len__(),), c_A_0.value)
c_I.x.array[:] = np.full((c_I.x.array.__len__(),), c_I_0.value)
c_A_n.x.array[:] = np.full((c_A.x.array.__len__(),), c_A_0.value)
c_I_n.x.array[:] = np.full((c_I.x.array.__len__(),), c_I_0.value)

such that all of the dofs of the concentration functions are initialized with the initial conditions (in case this is what you want).

Regardless, I still get that the Newton solver does not converge. I don’t have much experience with the specific problem you’re trying to solve, but the most probable causes of failed convergence are

  1. the formulation of the problem is not well-posed
  2. there is a typo the code in your formulation

Cheers, Halvor

1 Like

Hey Halvor,

Really appreciate you taking the time to respond to my question with such a detailed response :smiley:

In regards to my dolfinx installation, I have followed the instructions given on https://fenicsproject.org/download/ with micromamba replacing conda (haven’t had issues with micromamba before). I am also running this on a MacBook Pro M3 (ARM64 architecture). I have tried purging my micromamba cache and reinstalling the environment, however, the error still remains when conducting the following:

micromamba create -n fenicsx-env
micromamba activate fenicsx-env
micromamba install -c conda-forge fenics-dolfinx mpich pyvista

The packages installed in the environment are as follows:

List of packages in environment: "/Users/vozcoban/micromamba/envs/fenicsx-env"

  Name                                  Version       Build                  Channel    
─────────────────────────────────────────────────────────────
  aiohttp                               3.9.5         py312he37b823_0        conda-forge
  aiosignal                             1.3.1         pyhd8ed1ab_0           conda-forge
  aom                                   3.9.1         h7bae524_0             conda-forge
  attrs                                 23.2.0        pyh71513ae_0           conda-forge
  blosc                                 1.21.5        h9c252e8_1             conda-forge
  brotli                                1.1.0         hb547adb_1             conda-forge
  brotli-bin                            1.1.0         hb547adb_1             conda-forge
  brotli-python                         1.1.0         py312h9f69965_1        conda-forge
  bzip2                                 1.0.8         h93a5062_5             conda-forge
  c-ares                                1.28.1        h93a5062_0             conda-forge
  c-blosc2                              2.14.4        ha57e6be_1             conda-forge
  ca-certificates                       2024.6.2      hf0a4a13_0             conda-forge
  cairo                                 1.18.0        hd1e100b_0             conda-forge
  cctools_osx-arm64                     986           h62378fb_0             conda-forge
  certifi                               2024.6.2      pyhd8ed1ab_0           conda-forge
  cffi                                  1.16.0        py312h8e38eb3_0        conda-forge
  charset-normalizer                    3.3.2         pyhd8ed1ab_0           conda-forge
  clang                                 16.0.6        default_h095aff0_8     conda-forge
  clang-16                              16.0.6        default_hb63da90_8     conda-forge
  clang_impl_osx-arm64                  16.0.6        hc421ffc_16            conda-forge
  clang_osx-arm64                       16.0.6        h54d7cd3_16            conda-forge
  clangxx                               16.0.6        default_h095aff0_8     conda-forge
  clangxx_impl_osx-arm64                16.0.6        hcd7bac0_16            conda-forge
  clangxx_osx-arm64                     16.0.6        h54d7cd3_16            conda-forge
  compiler-rt                           16.0.6        h3808999_2             conda-forge
  compiler-rt_osx-arm64                 16.0.6        h3808999_2             conda-forge
  contourpy                             1.2.1         py312h0fef576_0        conda-forge
  cycler                                0.12.1        pyhd8ed1ab_0           conda-forge
  dav1d                                 1.2.1         hb547adb_0             conda-forge
  double-conversion                     3.3.0         h13dd4ca_0             conda-forge
  eigen                                 3.4.0         h1995070_0             conda-forge
  expat                                 2.6.2         hebf3989_0             conda-forge
  fenics-basix                          0.8.0         py312h157fec4_1        conda-forge
  fenics-dolfinx                        0.8.0         py312h5d54870_103      conda-forge
  fenics-ffcx                           0.8.0         pyh4af843d_0           conda-forge
  fenics-libbasix                       0.8.0         h6063bf6_1             conda-forge
  fenics-libdolfinx                     0.8.0         h235d05a_103           conda-forge
  fenics-ufcx                           0.8.0         h22f594c_0             conda-forge
  fenics-ufl                            2024.1.0      pyhd8ed1ab_0           conda-forge
  ffmpeg                                6.1.1         gpl_hc16618e_112       conda-forge
  fftw                                  3.3.10        mpi_mpich_hd148bab_10  conda-forge
  font-ttf-dejavu-sans-mono             2.37          hab24e00_0             conda-forge
  font-ttf-inconsolata                  3.000         h77eed37_0             conda-forge
  font-ttf-source-code-pro              2.038         h77eed37_0             conda-forge
  font-ttf-ubuntu                       0.83          h77eed37_2             conda-forge
  fontconfig                            2.14.2        h82840c6_0             conda-forge
  fonts-conda-ecosystem                 1             0                      conda-forge
  fonts-conda-forge                     1             0                      conda-forge
  fonttools                             4.53.0        py312h7e5086c_0        conda-forge
  freetype                              2.12.1        hadb7bae_2             conda-forge
  fribidi                               1.0.10        h27ca646_0             conda-forge
  frozenlist                            1.4.1         py312he37b823_0        conda-forge
  gettext                               0.22.5        h8fbad5d_2             conda-forge
  gettext-tools                         0.22.5        h8fbad5d_2             conda-forge
  gl2ps                                 1.4.2         h17b34a0_0             conda-forge
  glew                                  2.1.0         h9f76cd9_2             conda-forge
  glib                                  2.80.2        h535f939_0             conda-forge
  glib-tools                            2.80.2        h4c882b9_0             conda-forge
  gmp                                   6.3.0         hebf3989_1             conda-forge
  gnutls                                3.7.9         hd26332c_0             conda-forge
  graphite2                             1.3.13        hebf3989_1003          conda-forge
  gst-plugins-base                      1.24.4        h8a8f8c8_0             conda-forge
  gstreamer                             1.24.4        h430e707_0             conda-forge
  harfbuzz                              8.5.0         h1836168_0             conda-forge
  hdf4                                  4.2.15        h2ee6834_7             conda-forge
  hdf5                                  1.14.3        mpi_mpich_hb65fe4a_5   conda-forge
  hypre                                 2.31.0        mpi_mpich_hbb1104e_1   conda-forge
  icu                                   73.2          hc8870d7_0             conda-forge
  idna                                  3.7           pyhd8ed1ab_0           conda-forge
  jsoncpp                               1.9.5         hc021e02_1             conda-forge
  kahip                                 3.16          py312h3df46a2_3        conda-forge
  kahip-python                          3.16          py312h7775b25_3        conda-forge
  kiwisolver                            1.4.5         py312h389731b_1        conda-forge
  krb5                                  1.21.2        h92f50d5_0             conda-forge
  lame                                  3.100         h1a8c8d9_1003          conda-forge
  lcms2                                 2.16          ha0e7c42_0             conda-forge
  ld64_osx-arm64                        711           ha4bd21c_0             conda-forge
  lerc                                  4.0.0         h9a09cb3_0             conda-forge
  libabseil                             20240116.2    cxx17_hebf3989_0       conda-forge
  libadios2                             2.10.0        mpi_mpich_h0badead_3   conda-forge
  libaec                                1.1.3         hebf3989_0             conda-forge
  libasprintf                           0.22.5        h8fbad5d_2             conda-forge
  libasprintf-devel                     0.22.5        h8fbad5d_2             conda-forge
  libass                                0.17.1        hf7da4fe_1             conda-forge
  libblas                               3.9.0         22_osxarm64_openblas   conda-forge
  libboost                              1.84.0        h17eb2be_3             conda-forge
  libboost-devel                        1.84.0        hf450f58_3             conda-forge
  libboost-headers                      1.84.0        hce30654_3             conda-forge
  libbrotlicommon                       1.1.0         hb547adb_1             conda-forge
  libbrotlidec                          1.1.0         hb547adb_1             conda-forge
  libbrotlienc                          1.1.0         hb547adb_1             conda-forge
  libcblas                              3.9.0         22_osxarm64_openblas   conda-forge
  libclang-cpp16                        16.0.6        default_hb63da90_8     conda-forge
  libclang13                            18.1.7        default_hb9c8b4a_0     conda-forge
  libcurl                               8.8.0         h7b6f9a7_0             conda-forge
  libcxx                                17.0.6        h5f092b4_0             conda-forge
  libdeflate                            1.20          h93a5062_0             conda-forge
  libedit                               3.1.20191231  hc8eb9b7_2             conda-forge
  libev                                 4.33          h93a5062_2             conda-forge
  libexpat                              2.6.2         hebf3989_0             conda-forge
  libffi                                3.4.2         h3422bc3_5             conda-forge
  libgettextpo                          0.22.5        h8fbad5d_2             conda-forge
  libgettextpo-devel                    0.22.5        h8fbad5d_2             conda-forge
  libgfortran                           5.0.0         13_2_0_hd922786_3      conda-forge
  libgfortran5                          13.2.0        hf226fd6_3             conda-forge
  libglib                               2.80.2        h535f939_0             conda-forge
  libhwloc                              2.10.0        default_h7685b71_1001  conda-forge
  libiconv                              1.17          h0d3ecfb_2             conda-forge
  libidn2                               2.3.7         h93a5062_0             conda-forge
  libintl                               0.22.5        h8fbad5d_2             conda-forge
  libintl-devel                         0.22.5        h8fbad5d_2             conda-forge
  libjpeg-turbo                         3.0.0         hb547adb_1             conda-forge
  liblapack                             3.9.0         22_osxarm64_openblas   conda-forge
  libllvm16                             16.0.6        haab561b_3             conda-forge
  libllvm18                             18.1.7        hdac5640_0             conda-forge
  libnetcdf                             4.9.2         nompi_he469be0_114     conda-forge
  libnghttp2                            1.58.0        ha4dd798_1             conda-forge
  libogg                                1.3.4         h27ca646_1             conda-forge
  libopenblas                           0.3.27        openmp_h6c19121_0      conda-forge
  libopenvino                           2024.1.0      h5c9529b_7             conda-forge
  libopenvino-arm-cpu-plugin            2024.1.0      h5c9529b_7             conda-forge
  libopenvino-auto-batch-plugin         2024.1.0      hcd65546_7             conda-forge
  libopenvino-auto-plugin               2024.1.0      hcd65546_7             conda-forge
  libopenvino-hetero-plugin             2024.1.0      h88cb26a_7             conda-forge
  libopenvino-ir-frontend               2024.1.0      h88cb26a_7             conda-forge
  libopenvino-onnx-frontend             2024.1.0      h32b5460_7             conda-forge
  libopenvino-paddle-frontend           2024.1.0      h32b5460_7             conda-forge
  libopenvino-pytorch-frontend          2024.1.0      h00cdb27_7             conda-forge
  libopenvino-tensorflow-frontend       2024.1.0      h2741c3b_7             conda-forge
  libopenvino-tensorflow-lite-frontend  2024.1.0      h00cdb27_7             conda-forge
  libopus                               1.3.1         h27ca646_1             conda-forge
  libpng                                1.6.43        h091b4b1_0             conda-forge
  libpq                                 16.3          h7afe498_0             conda-forge
  libprotobuf                           4.25.3        hbfab5d5_0             conda-forge
  libptscotch                           7.0.4         h44b462d_5             conda-forge
  libscotch                             7.0.4         h75850e6_5             conda-forge
  libsodium                             1.0.18        h27ca646_1             conda-forge
  libsqlite                             3.46.0        hfb93653_0             conda-forge
  libssh2                               1.11.0        h7a5bd25_0             conda-forge
  libtasn1                              4.19.0        h1a8c8d9_0             conda-forge
  libtheora                             1.1.1         h3422bc3_1005          conda-forge
  libtiff                               4.6.0         h07db509_3             conda-forge
  libunistring                          0.9.10        h3422bc3_0             conda-forge
  libvorbis                             1.3.7         h9f76cd9_0             conda-forge
  libvpx                                1.14.1        h7bae524_0             conda-forge
  libwebp-base                          1.4.0         h93a5062_0             conda-forge
  libxcb                                1.15          hf346824_0             conda-forge
  libxml2                               2.12.7        ha661575_1             conda-forge
  libzip                                1.10.1        ha0bc3c6_3             conda-forge
  libzlib                               1.2.13        hfb2fe0b_6             conda-forge
  llvm-openmp                           18.1.7        hde57baf_0             conda-forge
  llvm-tools                            16.0.6        haab561b_3             conda-forge
  loguru                                0.7.2         py312h81bd7bf_1        conda-forge
  lz4-c                                 1.9.4         hb7217d7_0             conda-forge
  matplotlib-base                       3.8.4         py312h4479663_2        conda-forge
  metis                                 5.1.0         h13dd4ca_1007          conda-forge
  mpfr                                  4.2.1         h41d338b_1             conda-forge
  mpi                                   1.0           mpich                  conda-forge
  mpi4py                                3.1.6         py312h66645bf_1        conda-forge
  mpich                                 4.2.1         h9ee2227_101           conda-forge
  msgpack-python                        1.0.8         py312h157fec4_0        conda-forge
  multidict                             6.0.5         py312h670c8ac_0        conda-forge
  mumps-include                         5.7.1         hce30654_1             conda-forge
  mumps-mpi                             5.7.1         hd0c33d2_1             conda-forge
  munkres                               1.1.4         pyh9f0ad1d_0           conda-forge
  mysql-common                          8.3.0         hd1853d3_4             conda-forge
  mysql-libs                            8.3.0         hf036fc4_4             conda-forge
  ncurses                               6.5           hb89a1cb_0             conda-forge
  nettle                                3.9.1         h40ed0f5_0             conda-forge
  nlohmann_json                         3.11.3        hebf3989_0             conda-forge
  numpy                                 1.26.4        py312h8442bc7_0        conda-forge
  openh264                              2.4.1         hebf3989_0             conda-forge
  openjpeg                              2.5.2         h9f1df11_0             conda-forge
  openssl                               3.3.1         hfb2fe0b_0             conda-forge
  p11-kit                               0.24.1        h29577a5_0             conda-forge
  packaging                             24.1          pyhd8ed1ab_0           conda-forge
  parmetis                              4.0.3         hb315350_1006          conda-forge
  pcre2                                 10.43         h26f9a81_0             conda-forge
  petsc                                 3.21.2        real_h7a8f866_101      conda-forge
  petsc4py                              3.21.2        py312h293dd43_1        conda-forge
  pillow                                10.3.0        py312h8a801b1_0        conda-forge
  pip                                   24.0          pyhd8ed1ab_0           conda-forge
  pixman                                0.43.4        hebf3989_0             conda-forge
  pkg-config                            0.29.2        hab62308_1008          conda-forge
  platformdirs                          4.2.2         pyhd8ed1ab_0           conda-forge
  pooch                                 1.8.2         pyhd8ed1ab_0           conda-forge
  proj                                  9.3.1         h93d94ba_0             conda-forge
  pthread-stubs                         0.4           h27ca646_1001          conda-forge
  ptscotch                              7.0.4         heaa5b5c_5             conda-forge
  pugixml                               1.14          h13dd4ca_0             conda-forge
  pycparser                             2.22          pyhd8ed1ab_0           conda-forge
  pyparsing                             3.1.2         pyhd8ed1ab_0           conda-forge
  pysocks                               1.7.1         pyha2e5f31_6           conda-forge
  python                                3.12.3        h4a7b5fc_0_cpython     conda-forge
  python-dateutil                       2.9.0         pyhd8ed1ab_0           conda-forge
  python_abi                            3.12          4_cp312                conda-forge
  pyvista                               0.43.10       pyhd8ed1ab_0           conda-forge
  qt6-main                              6.7.1         h845717a_2             conda-forge
  readline                              8.2           h92ec313_1             conda-forge
  requests                              2.32.3        pyhd8ed1ab_0           conda-forge
  scalapack                             2.2.0         h908211e_2             conda-forge
  scooby                                0.10.0        pyhd8ed1ab_0           conda-forge
  scotch                                7.0.4         heaa5b5c_5             conda-forge
  setuptools                            70.0.0        pyhd8ed1ab_0           conda-forge
  sigtool                               0.1.3         h44b9a77_0             conda-forge
  six                                   1.16.0        pyh6c4a22f_0           conda-forge
  slepc                                 3.21.1        real_h3c05993_302      conda-forge
  slepc4py                              3.21.1        py312h5464fc9_101      conda-forge
  snappy                                1.2.0         hd04f947_1             conda-forge
  sqlite                                3.46.0        h5838104_0             conda-forge
  suitesparse                           7.7.0         hf6fcff2_1             conda-forge
  superlu                               5.2.2         hc615359_0             conda-forge
  superlu_dist                          9.0.0         h2cb61f8_1             conda-forge
  svt-av1                               2.1.0         h7bae524_0             conda-forge
  tapi                                  1100.0.11     he4954df_0             conda-forge
  tbb                                   2021.12.0     h420ef59_1             conda-forge
  tbb-devel                             2021.12.0     h94f16c5_1             conda-forge
  tk                                    8.6.13        h5083fa2_1             conda-forge
  tzdata                                2024a         h0c530f3_0             conda-forge
  urllib3                               2.2.2         pyhd8ed1ab_0           conda-forge
  utfcpp                                4.0.5         hce30654_0             conda-forge
  vtk                                   9.3.0         qt_py312h1234567_200   conda-forge
  vtk-base                              9.3.0         qt_py312h1234567_200   conda-forge
  vtk-io-ffmpeg                         9.3.0         qt_py312h1234567_200   conda-forge
  wheel                                 0.43.0        pyhd8ed1ab_1           conda-forge
  wslink                                2.0.5         pyhd8ed1ab_0           conda-forge
  x264                                  1!164.3095    h57fd34a_2             conda-forge
  x265                                  3.5           hbc6ce65_3             conda-forge
  xorg-libxau                           1.0.11        hb547adb_0             conda-forge
  xorg-libxdmcp                         1.1.3         h27ca646_0             conda-forge
  xz                                    5.2.6         h57fd34a_0             conda-forge
  yaml                                  0.2.5         h3422bc3_2             conda-forge
  yarl                                  1.9.4         py312he37b823_0        conda-forge
  zeromq                                4.3.5         hcc0f68c_4             conda-forge
  zfp                                   0.5.5         hcfdfaf5_8             conda-forge
  zlib                                  1.2.13        hfb2fe0b_6             conda-forge
  zlib-ng                               2.0.7         h1a8c8d9_0             conda-forge
  zstd                                  1.5.6         hb46c0d2_0             conda-forge

On top of this, I have installed the following three packages (should gmsh install with the dofinx installation automatically?):

pip install tqdm
pip install --upgrade gmsh
pip install jupyterlab

Something I do remember about a past FEniCSx installation is that prior to installing the current version 0.8.0 the reaction-diffusion problem did not converge and I believe the code was (partially) working (at least the solver was). On a whim I decided to delete my old environment, install the latest version, update my code, and not keep the old code. In hindsight, this was probably not the best idea :smiling_face_with_tear:…

Furthermore, regarding the convergence issue, the problem is likely ill-posed or ill-conditioned and I may need to apply Strang Splitting or some other method to fix this (once these errors are fixed :sweat_smile:).

Thanks again,
Volkan

Hi again Volkan,

Could you try with another way of installation (e.g. docker or spack, see this link for several options), and see if you still get the same error? It might be that gmsh must be installed separately, yes, but off the top of my head I can’t remember. I have no experience with micromamba, so I can’t really comment on problems related to that. Maybe @dokken has some knowledge of previous issues using micromamba to install dolfinx.

All right, thanks for the information about the problem and its well-posedness. Let’s assume the error I am getting (the Newton solver not converging) is the “correct/desired” output then, and let’s see if another type of installation can fix your issue with the PETSc error.

Best, Halvor

1 Like

Mixing pip and conda is never adviced if it can be avoided. I would suggest that you create a new environment, and install tqdm gmsh and jupyterlab through conda-forge instead of with pip.

GMSH is not a strong dependency of DOLFINx.

1 Like

Hey @dokken,

Thanks for letting me know. Yep, forget about mixing these… However, after creating a new env and using micromamba instead of pip the issue persists and does not seem to be the cause.

Thanks!

Hey Halvor,

I tried docker as follows:

docker pull dolfinx/lab:stable

and a script launch with:

#!/usr/bin/env bash

docker run --init -ti --rm -v "$(pwd)":/mountedFolder -p 8888:8888 -w /mountedFolder dolfinx/lab:stable --NotebookApp.token=''

with the usual error (in jupyter):

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[18], line 12
      7 t += dt
      8 #print(t)
      9 #log.set_log_level(log.LogLevel.INFO)
     10 # Solve PDE for the current time step
     11 #try:
---> 12 num_its, converged = solver.solve(c)
     13 assert converged
     14 #except RuntimeError as e:
     15     #print(f"Solver failed with error: {e}")
     16 #c.x.scatter_forward
     17 # Update solution (c) at previous time step (c_n)

File /usr/local/dolfinx-real/lib/python3.10/dist-packages/dolfinx/nls/petsc.py:47, in NewtonSolver.solve(self, u)
     44 def solve(self, u: fem.Function):
     45     """Solve non-linear problem into function u. Returns the number
     46     of iterations and if the solver converged."""
---> 47     n, converged = super().solve(u.x.petsc_vec)
     48     u.x.scatter_forward()
     49     return n, converged

RuntimeError: Failed to successfully call PETSc function 'KSPSolve'. PETSc error code is: 73, Object is in wrong state

Additionally, I decided to try v0.7.2 of the dolfinx docker as follows:

docker pull dolfinx/lab:v0.7.2

and something interesting happened. I also ended up getting the non-convergence related error which you also had:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[21], line 12
      7 t += dt
      8 #print(t)
      9 #log.set_log_level(log.LogLevel.INFO)
     10 # Solve PDE for the current time step
     11 #try:
---> 12 num_its, converged = solver.solve(c)
     13 assert converged
     14 #except RuntimeError as e:
     15     #print(f"Solver failed with error: {e}")
     16 #c.x.scatter_forward
     17 # Update solution (c) at previous time step (c_n)

File /usr/local/dolfinx-real/lib/python3.10/dist-packages/dolfinx/nls/petsc.py:46, in NewtonSolver.solve(self, u)
     43 def solve(self, u: fem.Function):
     44     """Solve non-linear problem into function u. Returns the number
     45     of iterations and if the solver converged."""
---> 46     n, converged = super().solve(u.vector)
     47     u.x.scatter_forward()
     48     return n, converged

RuntimeError: Newton solver did not converge because maximum number of iterations reached

So I guess this is now the desired output :sweat_smile: Just have to use the previous version I guess, although now I don’t know whether there is an issue with the way I’ve set up my function spaces and mixed elements on this version as the code was updated for v0.8.0.

Could the error message be an issue with v0.8.0 spitting out the wrong error message (Error 73) instead of non-convergence? Or it picking that up first?

Also, which version of dolfinx and OS are you using?

Cheers,
Volkan

The usage of c.split() and c_n.split() causes the issues.
Here is a modified version of the code that runs nicely:

#-------------
# IMPORTS
#-------------

import ufl
import numpy as np
import gmsh
from mpi4py import MPI

from dolfinx import fem, mesh
from dolfinx.io import gmshio
from dolfinx.fem.petsc import NonlinearProblem
from dolfinx.nls.petsc import NewtonSolver
import basix



#-------------
# CREATE MESH
#-------------

# Initialise the GMSH module
gmsh.initialize()

# Create the membrane and start the computations by the GMSH CAD kernel, to generate the relevant underlying data structures
membrane = gmsh.model.occ.addDisk(0, 0, 0, 1, 1) # x, y, z, x-radius, y-radius
gmsh.model.occ.synchronize()

# Make membrane a physical surface for GMSH to recognise when generating the mesh
gdim = 2 # 2D Geometric Dimension of the Mesh
gmsh.model.addPhysicalGroup(gdim, [membrane], 0) # Dimension, Entity tag, Physical tag

# Generate 2D Mesh with uniform mesh size
gmsh.option.setNumber("Mesh.CharacteristicLengthMin", 0.25)
gmsh.option.setNumber("Mesh.CharacteristicLengthMax", 0.25)
gmsh.model.mesh.generate(gdim)

# Create a mesh from the GMSH model
gmsh_model_rank = 0
mesh_comm = MPI.COMM_WORLD
domain, cell_markers, facet_markers = gmshio.model_to_mesh(gmsh.model, mesh_comm, gmsh_model_rank, gdim=gdim)
# Finalize GMSH
gmsh.finalize()


#---------------------
# CREATE FEM FUNCTIONS
#---------------------

# Time Discretisation
t = 0 # Initial Time
T = 200 # Final Time
Nsteps = 2000 # Number of Time Steps
dt = T/Nsteps # Time Step Size


# Global Spatial Coordinates as a Vector-Valued Expression i.e. x[0] = x, x[1] = y
x = ufl.SpatialCoordinate(domain) # This may not be needed

P1 = basix.ufl.element(family="Lagrange", cell=domain.topology.cell_name(), degree=1)
element = basix.ufl.mixed_element([P1, P1])
C = fem.functionspace(mesh=domain, element=element)

# Create function space for concentrations
c = fem.Function(C)
c.name = "c"

c_n = fem.Function(C)
c_n.name = "c_n"

c_A, c_I = ufl.split(c)
c_A_n, c_I_n = ufl.split(c_n)
w_A, w_I = ufl.TestFunction(C)


#-------------------------------------------------------
# CONSTANT INITIAL CONDITIONS AND NO BOUNDARY CONDITIONS
#-------------------------------------------------------

# Initial Conditions of Species I=1 and Species A=0
c_A_0 = fem.Constant(domain, 0.0)
c_I_0 = fem.Constant(domain, 1.0)

c.sub(0).interpolate(lambda x: np.full((x.shape[1],), c_A_0))
c.sub(1).interpolate(lambda x: np.full((x.shape[1],), c_I_0))
c_n.sub(0).interpolate(lambda x: np.full((x.shape[1],), c_A_0))
c_n.sub(1).interpolate(lambda x: np.full((x.shape[1],), c_I_0))


#---------------------------
# REACTION-DIFFUSION PROBLEM
#---------------------------

# Reaction Function
def reaction_function(cA, cI):
    delta = fem.Constant(domain, 3.0) # Deactivation Rate
    b_0 = fem.Constant(domain, 2.0) # Basal Activation Rate
    c_hill = fem.Constant(domain, 1.0) # Hill Function Magnitude
    cA_0 = fem.Constant(domain, 0.5)
    
    return (b_0 + c_hill * (cA**6/(cA_0**6 + cA**6))) * cI - delta * cA


# Setting up tensors
spa_dim = len(x) # Spatial Dimension
I = ufl.Identity(spa_dim) # Identity Tensor
F = ufl.variable(ufl.Identity(spa_dim)) # Deformation Gradient Tensor (e.g. Identity Tensor)
F_inv = ufl.inv(F)
F_inv_tra = ufl.transpose(F_inv)
J = fem.Constant(domain, 1.0) # Jacobian Function (e.g. Constant or Pre-Defined Function)
J_n = J

# Examine Isotropic Diffusion where D_A=D*I (Diffusivity Constant multiplied by the Identity Tensor)
D_A = 2 * I
D_A_eq = J * F_inv * D_A * F_inv_tra
D_I = 4 * I
D_I_eq = J * F_inv * D_I * F_inv_tra


# Measure Set Up
metadata = {"quadrature_degree": 3}
dx = ufl.Measure('dx', domain=domain, metadata=metadata)


# Weak Form Set Up
term1_A = J * (c_A - c_A_n)/dt * w_A * dx 
term2_A = ufl.inner(D_A_eq * ufl.grad(c_A), ufl.grad(w_A)) * dx
term3_A = -J * reaction_function(c_A, c_I) * w_A * dx
term4_A = c_A * (J - J_n)/dt * w_A * dx

Func_A = term1_A + term2_A + term3_A + term4_A

term1_I = J * (c_I - c_I_n)/dt * w_I * dx
term2_I = ufl.inner(D_I_eq * ufl.grad(c_I), ufl.grad(w_I)) * dx
term3_I = J * reaction_function(c_A, c_I) * w_I * dx
term4_I = c_I * (J - J_n)/dt * w_I * dx

Func_I = term1_I + term2_I + term3_I + term4_I

Func = Func_A + Func_I

# Create Nonlinear Problem and Solver
problem = NonlinearProblem(Func, c, bcs=[])
solver = NewtonSolver(MPI.COMM_WORLD, problem)
solver.atol = 1e-8
solver.rtol = 1e-8
solver.convergence_criterion = "incremental" # Incremental causes State issues but Residual only causes for term3_A and term3_I
solver.report = True


# Update Function for each time step of the reaction-diffusion problem
for i in range(Nsteps):
    t += dt

    # Solve PDE for the current time step
    num_its, converged = solver.solve(c)
    assert converged
    
    c.x.scatter_forward()

    # Update solution (c) at previous time step (c_n)
    c_n.x.array[:] = c.x.array

The big changes are at

and

2 Likes

Thanks a lot for spotting that Jørgen! I found this previous forum answer that you answered last year with an explanation of why ufl.split() must be used here and I attach it here, in case Volkan is interested in the difference in the two ways of using split.

Hope this solved your problem Volkan.

Cheers

2 Likes

This worked!!! Thanks so much for finding the specific issue.

Thanks for all the help @dokken and @hherlyng. Really appreciate you guys taking the time to fix this problem :smiley:

Cheers,
Volkan

1 Like