Want to import already defined physical groups of Microstructure in Gmsh to FEnics

Did you read the entire tutorial at Defining subdomains for different materials — FEniCSx tutorial that @dokken suggested?

At the very beginning, Subdomains on built-in meshes, he is using a built-in mesh. Afterwards, Subdomains defined from external mesh data, he also shows how to use gmsh to generate the mesh of a custom domain, which in the tutorial turns out to be the same square, but in principle you can use it to define any other domain you want (once you know how to use gmsh: if you don’t, look at their website, there are several python demos)

I understood your message, however i am asking when everything is pre-defined in Gmsh and it is also converted to xdmf file which fenics is reading and also showing region(1,2,3,4) for 4 sides and Region(5,6) for grain and grain boundaries, why needed to go for again defining subdomains? Cant we directly use the particular regions in my code?If not, why? If yes, How? As i have several Experience in other Fem based module, i used group ids gernerated by small coding which convert Gmsh(.msh file ) to vtk format which read directly by FEM module. So, what is the way of using Generated regions (xdmf file by fenics) with different material propereties.

As Francesco said, the latter bit of the tutorial uses the data from gmsh directly.
The tags are read in with

with XDMFFile(MPI.COMM_WORLD, "mesh.xdmf", "r") as xdmf:
    mesh = xdmf.read_mesh(name="Grid")
    ct = xdmf.read_meshtags(mesh, name="Grid")
mesh.topology.create_connectivity(mesh.topology.dim, mesh.topology.dim - 1)
with XDMFFile(MPI.COMM_WORLD, "mt.xdmf", "r") as xdmf:
    ft = xdmf.read_meshtags(mesh, name="Grid")

and then converted to a dolfinx.fem.Function with:

Q = FunctionSpace(mesh, ("DG", 0))
kappa = Function(Q)
bottom_cells = ct.find(bottom_marker)
kappa.x.array[bottom_cells] = np.full_like(bottom_cells, bottom_marker, dtype=default_scalar_type)
top_cells = ct.find(top_marker)
kappa.x.array[top_cells] = np.full_like(top_cells, top_marker, dtype=default_scalar_type)

In summary, you just need to transfer the data from a MeshTags (in legacy dolfin MeshFunction) to a Function if you want to use the values of the markers in your variational form as parameters.

There are other ways of defining these sub domains (although I rarely use it), see for instance: https://fenicsproject.org/olddocs/dolfin/latest/python/demos/subdomains-poisson/documentation.html?highlight=subdomain_data

Hi, still i am not able to figure out regions to implement material properties? Actually, solvers is not working? Any way how to get rid of this problem? I am getting problem with solvers after i implemented regions tags to equations? Here i took all grains as region5 and all grain boundaries as region6.
I used these equations:
F1 = uC * vC * dx(5) + ts * D * inner(grad(uC), grad(vC)) * dx(5) + uC * vC * dx(6) + ts * D * inner(grad(uC), grad(vC)) * dx(6) - ts * fC * vC * dx(5) - ts * fC * vC * dx(6) - C_old * vC * dx(5) - C_old * vC * dx(6)
a, L = lhs(F1), rhs(F1)
and,
F2 = inner(sigma(uU, c, material_properties[5]), grad(vU))*dx(5) + inner(sigma(uU, c, material_properties[6]), grad(vU))*dx(6)
aU = lhs(F2)
LU = rhs(F2) + inner(fU, vU)*dx

solver:

Time-stepping loop

for n in range(num_steps):
# Update time
t += ts
# Solve concentration problem (F1)
solver_parameters = {“linear_solver”: “gmres”, “preconditioner”: “ilu”}
solve(a == L, c, bcsc, solver_parameters=solver_parameters)

A = assemble(a, bcs=bcsc)
A.ident_zeros()

solver_parameters = {"ksp_type": "gmres", "pc_type": "ilu"}
solve(a == L, c, bcsc, solver_parameters=solver_parameters)

A = assemble(a)
b = assemble(L)
[bc.apply(A, b) for bc in bcsc]
solve(A, c.vector(), b)


#solve(a == L, c, bcsc)

# Solve displacement problem (F2)
solve(aU == LU, u, bcsu)

# Save concentration solution to VTK file
vtkfile1 << (c, t)

# Update old concentration for the next time step
C_old.assign(c)

//Error:
RuntimeError Traceback (most recent call last)
Cell In[858], line 7
5 # Solve concentration problem (F1)
6 solver_parameters = {“linear_solver”: “gmres”, “preconditioner”: “ilu”}
----> 7 solve(a == L, c, bcsc, solver_parameters=solver_parameters)
9 A = assemble(a, bcs=bcsc)
10 A.ident_zeros()

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/fem/solving.py:233, in solve(*args, **kwargs)
230 # Call variational problem solver if we get an equation (but not a
231 # tolerance)
232 elif isinstance(args[0], ufl.classes.Equation):
→ 233 _solve_varproblem(*args, **kwargs)
235 # Default case, just call the wrapped C++ solve function
236 else:
237 if kwargs:

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/fem/solving.py:273, in _solve_varproblem(*args, **kwargs)
271 solver = LinearVariationalSolver(problem)
272 solver.parameters.update(solver_parameters)
→ 273 solver.solve()
275 # Solve nonlinear variational problem
276 else:
278 if u._functions is not None:
279 # Extract blocks from the variational formulation

RuntimeError:

*** -------------------------------------------------------------------------
*** DOLFIN encountered an error. If you are not able to resolve this issue
*** using the information listed below, you can ask for help at


*** fenics-support@googlegroups.com


*** Remember to include the error message listed below and, if possible,
*** include a minimal running example to reproduce the error.


*** -------------------------------------------------------------------------
*** Error: Unable to set given (local) rows to identity matrix.
*** Reason: some diagonal elements not preallocated (try assembler option keep_diagonal).
*** Where: This error was encountered inside PETScMatrix.cpp.
*** Process: 0


*** DOLFIN version: 2019.2.0.dev0
*** Git changeset: ubuntu
*** -------------------------------------------------------------------------

Your code is not a minimal reproducible example, so I am not able to further help you without you putting the effort into creating the smallest subset of code that:

  1. Reproduces the error and can be copy-pasted by me or anyone else to produce the error message
  2. Code formatted as
    ```python
    # Add code here
    ```
    
  3. Clarify if your goal is to solve a problem on a subset of the geometry, or the complete geometry with different material parameters in different regions.

Here i used same geometry as previously i sent you .geo file, small change i did as i defined all grains as region5 and grain boundary as region6, you can use same geometry.
My goal is to solve the complete geometry with different material parameters in different regions(grain and grain boundaries).

Please just reduce your problem to defining the material parameters. No need to show the whole problem.

Remove everything after defining the material parameter you want, and then show what you get as output, and explain how it differs from what you expect.

The code i posted was for your reference to check if i was doing mistake on defining regions or defining solver as i got error message to check equations. I think you misunderstood my question that lead you to other direction. I am simply asking have you run the code i sent to you. I just wanted feedback so i can correct mistakes on code.

Asking people to work through your whole code is quite demanding, as people post on this forum on a volunteer basis, and sending over 100 lines of code and asking people to review them, is alot of work.

The first step to checking if you have set up material properties correctly is to post code that creates the markers, and saves them to file, so that you can visually inspect them in for instance Paraview.
Once you are happy with these, one can move on to defining the variational problem and in turn how to setup a solver for the set of equations.

Now, i removed microstructre and used simple geometry(square divided into 2 parts 0.5 and 0.5) having region1 and region2 exported from Gmsh(simplified one). Look, the same error i am encountering. where is the problem?

# Define the variational problem for Concentration
F1 = uC * vC * dx(1) + ts * D * inner(grad(uC), grad(vC)) * dx(1) + uC * vC * dx(2) + ts * D * inner(grad(uC), grad(vC)) * dx(2) - ts * fC * vC * dx(1) - ts * fC * vC * dx(2) - C_old * vC * dx(1) - C_old * vC * dx(2)
a, L = lhs(F1), rhs(F1)

#For displacement
F2 = inner(sigma(uU, c, material_properties[1]), grad(vU))*dx(1) + inner(sigma(uU, c, material_properties[2]), grad(vU))*dx(2)
aU = lhs(F2)
LU = rhs(F2) + inner(fU, vU)*dx(1) + inner(fU, vU)*dx(2)


# Set the initial guess for the solution
c.assign(interpolate(ic, UC))
u.assign(Constant((0.0, 0.0)))

# Newton-Raphson parameters
max_iter = 10
tolerance = 1e-6

# Newton-Raphson iteration
for k in range(max_iter):
    # Assemble the Jacobian matrix and residual
    A, b = assemble_system(lhs(F1), rhs(F1), bcsc, keep_diagonal=True)

    # Solve for the increments
    solve(A, dc.vector(), b)

    # Update the solution
    c.vector()[:] -= dc.vector()

    # Assemble the residual for displacement
    bU = assemble(rhs(F1))

    # Solve for the displacement increments
    solve(aU == LU, du, bcsu)

    # Update the displacement solution
    u.vector()[:] -= du.vector()

    # Check the convergence
    if norm(dc) < tolerance and norm(du) < tolerance:
        break


//and error
encountring:---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Cell In[358], line 16
13 bU = assemble(rhs(F1))
15 # Solve for the displacement increments
—> 16 solve(aU == LU, du, bcsu)
18 # Update the displacement solution
19 u.vector()[:] -= du.vector()

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/fem/solving.py:233, in solve(*args, **kwargs)
230 # Call variational problem solver if we get an equation (but not a
231 # tolerance)
232 elif isinstance(args[0], ufl.classes.Equation):
→ 233 _solve_varproblem(*args, **kwargs)
235 # Default case, just call the wrapped C++ solve function
236 else:
237 if kwargs:

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/fem/solving.py:273, in _solve_varproblem(*args, **kwargs)
271 solver = LinearVariationalSolver(problem)
272 solver.parameters.update(solver_parameters)
→ 273 solver.solve()
275 # Solve nonlinear variational problem
276 else:
278 if u._functions is not None:
279 # Extract blocks from the variational formulation

RuntimeError:

*** -------------------------------------------------------------------------
*** DOLFIN encountered an error. If you are not able to resolve this issue
*** using the information listed below, you can ask for help at


*** fenics-support@googlegroups.com


*** Remember to include the error message listed below and, if possible,
*** include a minimal running example to reproduce the error.


*** -------------------------------------------------------------------------
*** Error: Unable to set given (local) rows to identity matrix.
*** Reason: some diagonal elements not preallocated (try assembler option keep_diagonal).
*** Where: This error was encountered inside PETScMatrix.cpp.
*** Process: 0


*** DOLFIN version: 2019.2.0.dev0
*** Git changeset: ubuntu
*** -------------------------------------------------------------------------

Good job for the clean up, but now you have exaggerated :wink: The code you post should:

  1. contain the minimal set of instructions to replicate your bug, but
  2. should also contain the minimal set of imports and the minimal set of variable definitions to be able to copy-and-paste it in a file and run it.

Please add imports and variables according to 2. Make sure to use “```” correctly, for instance to enclose the error message.

This is simple 2D heat transfer formulation. U can easily understand as its general code available in your FEniCS site.I attached code with .geo and code file.

from dolfin import *
import numpy as np
import matplotlib.pyplot as plt

import numpy as np
import meshio

def process_mesh(mesh, cell_type, target_regions=None, prune_z=False):
    cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
    unique_regions = np.unique(cell_data)

    def extract_ids(region_id):
        return list(np.where(cell_data == region_id)[0])

    def create_and_write(out_file, mesh_type, indices):
        out_mesh = meshio.Mesh(points=mesh.points[:, :2] if prune_z else mesh.points,
                               cells={mesh_type: mesh.get_cells_type(mesh_type)},
                               cell_data={"name_to_read": [cell_data]})
        meshio.write(out_file, out_mesh)

    # Create and write triangle mesh
    create_and_write("mesh.xdmf", "triangle", extract_ids(1) + extract_ids(2))

    # Material properties
    material_properties = {
        1: {"E": 200e9, "nu": 0.30},  # Material1 = Steel
        2: {"E": 90e9, "nu": 0.25}    # Material2 = Brass
    }

    # Assign material properties and print
    for region_id in [1, 2]:
        properties = material_properties.get(region_id, {})
        print(f"Material properties for Region {region_id}:", properties)

    # Create and write line mesh
    create_and_write("mf.xdmf", "triangle", extract_ids(1) + extract_ids(2))

mesh_from_file = meshio.read("Hima.msh")
process_mesh(mesh_from_file, "triangle", target_regions=[1, 2], prune_z=True)


from fenics import *
# Assuming you have loaded a mesh using meshio
mesh_from_file = meshio.read("Hima.msh")
mesh = Mesh()
with XDMFFile("mesh.xdmf") as infile:
    infile.read(mesh)
# Define subdomains for the mesh
subdomains = MeshFunction('size_t', mesh, 2)  # 2-dimensional subdomains
subdomains.set_all(0)  # Initialize all subdomains to 0


U = FunctionSpace(mesh,"CG",1)


#Defining boundary conditions
#right
u_D1 = Constant(1000.0)
right = CompiledSubDomain("near (x[0], 1.0) && on_boundary")
bc1 = DirichletBC(U, u_D1, right)
#left
u_D2 = Constant(25.0)
left = CompiledSubDomain("near (x[0], 0.0) && on_boundary")
bc2 = DirichletBC(U, u_D2, left)


bcs = [bc1, bc2]

#since we are solving 2-D time dependent with heat generation problem, the initial condition is u = 25
ic = Constant(25)
#discretising the initial condition over the function space
u_old = interpolate(ic, U)


u = TrialFunction(U)
v = TestFunction(U)
f = Constant(0.0)
u_sol = Function(U)
#alpha is the diffusivity
alpha = 5e-6

# Create VTK file for saving solution
vtkfile = File('2-D transient heat transfer/solution.pvd')

#ts is the time step
#Implicit Euler discretisation
t = 0.0
T = 300.0
ts = 1
num_steps = int(T/ts)

#u_o is the previous value of u
F = (u*v*dx(1)) + (ts*alpha*inner(grad(u), grad(v))*dx(1)) - (ts*f*v*dx(1)) - (u_old*v*dx(1)) + (u*v*dx(2)) + (ts*alpha*inner(grad(u), grad(v))*dx(2)) - (ts*f*v*dx(2)) - (u_old*v*dx(2))
a = lhs(F)
L = rhs(F)

for n in range(num_steps+1):
      solve(a == L, u_sol, bcs)
      # Save to file and plot solution
      vtkfile << (u_sol, t)
      print(t)
      u_old.assign(u_sol)
      t +=ts
"---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[116], line 2
      1 for n in range(num_steps+1):
----> 2       solve(a == L, u_sol, bcs)
      3       # Save to file and plot solution
      4       vtkfile << (u_sol, t)

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/fem/solving.py:233, in solve(*args, **kwargs)
    230 # Call variational problem solver if we get an equation (but not a
    231 # tolerance)
    232 elif isinstance(args[0], ufl.classes.Equation):
--> 233     _solve_varproblem(*args, **kwargs)
    235 # Default case, just call the wrapped C++ solve function
    236 else:
    237     if kwargs:

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/fem/solving.py:273, in _solve_varproblem(*args, **kwargs)
    271         solver = LinearVariationalSolver(problem)
    272         solver.parameters.update(solver_parameters)
--> 273         solver.solve()
    275 # Solve nonlinear variational problem
    276 else:
    278     if u._functions is not None:
    279         # Extract blocks from the variational formulation

RuntimeError: 

*** -------------------------------------------------------------------------
*** DOLFIN encountered an error. If you are not able to resolve this issue
*** using the information listed below, you can ask for help at
***
***     fenics-support@googlegroups.com
***
*** Remember to include the error message listed below and, if possible,
*** include a *minimal* running example to reproduce the error.
***
*** -------------------------------------------------------------------------
*** Error:   Unable to set given (local) rows to identity matrix.
*** Reason:  some diagonal elements not preallocated (try assembler option keep_diagonal).
*** Where:   This error was encountered inside PETScMatrix.cpp.
*** Process: 0
*** 
*** DOLFIN version: 2019.2.0.dev0
*** Git changeset:  ubuntu
*** -------------------------------------------------------------------------"

Please edit your post and use “```” to enclose the mesh and the error too.

This is simple 2D heat transfer formulation. U can easily understand as its general code available in your FEniCS site.I attached code with .geo and code file.

from dolfin import *
import numpy as np
import matplotlib.pyplot as plt

import numpy as np
import meshio

def process_mesh(mesh, cell_type, target_regions=None, prune_z=False):
    cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
    unique_regions = np.unique(cell_data)

    def extract_ids(region_id):
        return list(np.where(cell_data == region_id)[0])

    def create_and_write(out_file, mesh_type, indices):
        out_mesh = meshio.Mesh(points=mesh.points[:, :2] if prune_z else mesh.points,
                               cells={mesh_type: mesh.get_cells_type(mesh_type)},
                               cell_data={"name_to_read": [cell_data]})
        meshio.write(out_file, out_mesh)

    # Create and write triangle mesh
    create_and_write("mesh.xdmf", "triangle", extract_ids(1) + extract_ids(2))

    # Material properties
    material_properties = {
        1: {"E": 200e9, "nu": 0.30},  # Material1 = Steel
        2: {"E": 90e9, "nu": 0.25}    # Material2 = Brass
    }

    # Assign material properties and print
    for region_id in [1, 2]:
        properties = material_properties.get(region_id, {})
        print(f"Material properties for Region {region_id}:", properties)

    # Create and write line mesh
    create_and_write("mf.xdmf", "triangle", extract_ids(1) + extract_ids(2))

mesh_from_file = meshio.read("Hima.msh")
process_mesh(mesh_from_file, "triangle", target_regions=[1, 2], prune_z=True)


from fenics import *
# Assuming you have loaded a mesh using meshio
mesh_from_file = meshio.read("Hima.msh")
mesh = Mesh()
with XDMFFile("mesh.xdmf") as infile:
    infile.read(mesh)
# Define subdomains for the mesh
subdomains = MeshFunction('size_t', mesh, 2)  # 2-dimensional subdomains
subdomains.set_all(0)  # Initialize all subdomains to 0


U = FunctionSpace(mesh,"CG",1)


#Defining boundary conditions
#right
u_D1 = Constant(1000.0)
right = CompiledSubDomain("near (x[0], 1.0) && on_boundary")
bc1 = DirichletBC(U, u_D1, right)
#left
u_D2 = Constant(25.0)
left = CompiledSubDomain("near (x[0], 0.0) && on_boundary")
bc2 = DirichletBC(U, u_D2, left)


bcs = [bc1, bc2]

#since we are solving 2-D time dependent with heat generation problem, the initial condition is u = 25
ic = Constant(25)
#discretising the initial condition over the function space
u_old = interpolate(ic, U)


u = TrialFunction(U)
v = TestFunction(U)
f = Constant(0.0)
u_sol = Function(U)
#alpha is the diffusivity
alpha = 5e-6

# Create VTK file for saving solution
vtkfile = File('2-D transient heat transfer/solution.pvd')

#ts is the time step
#Implicit Euler discretisation
t = 0.0
T = 300.0
ts = 1
num_steps = int(T/ts)

#u_o is the previous value of u
F = (u*v*dx(1)) + (ts*alpha*inner(grad(u), grad(v))*dx(1)) - (ts*f*v*dx(1)) - (u_old*v*dx(1)) + (u*v*dx(2)) + (ts*alpha*inner(grad(u), grad(v))*dx(2)) - (ts*f*v*dx(2)) - (u_old*v*dx(2))
a = lhs(F)
L = rhs(F)

for n in range(num_steps+1):
      solve(a == L, u_sol, bcs)
      # Save to file and plot solution
      vtkfile << (u_sol, t)
      print(t)
      u_old.assign(u_sol)
      t +=ts
"---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[116], line 2
      1 for n in range(num_steps+1):
----> 2       solve(a == L, u_sol, bcs)
      3       # Save to file and plot solution
      4       vtkfile << (u_sol, t)

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/fem/solving.py:233, in solve(*args, **kwargs)
    230 # Call variational problem solver if we get an equation (but not a
    231 # tolerance)
    232 elif isinstance(args[0], ufl.classes.Equation):
--> 233     _solve_varproblem(*args, **kwargs)
    235 # Default case, just call the wrapped C++ solve function
    236 else:
    237     if kwargs:

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/fem/solving.py:273, in _solve_varproblem(*args, **kwargs)
    271         solver = LinearVariationalSolver(problem)
    272         solver.parameters.update(solver_parameters)
--> 273         solver.solve()
    275 # Solve nonlinear variational problem
    276 else:
    278     if u._functions is not None:
    279         # Extract blocks from the variational formulation

RuntimeError: 

*** -------------------------------------------------------------------------
*** DOLFIN encountered an error. If you are not able to resolve this issue
*** using the information listed below, you can ask for help at
***
***     fenics-support@googlegroups.com
***
*** Remember to include the error message listed below and, if possible,
*** include a *minimal* running example to reproduce the error.
***
*** -------------------------------------------------------------------------
*** Error:   Unable to set given (local) rows to identity matrix.
*** Reason:  some diagonal elements not preallocated (try assembler option keep_diagonal).
*** Where:   This error was encountered inside PETScMatrix.cpp.
*** Process: 0
*** 
*** DOLFIN version: 2019.2.0.dev0
*** Git changeset:  ubuntu
*** -------------------------------------------------------------------------"

Mesh:

Point(1) = {0, 0, 0, 1.0};
//+
Point(2) = {0, 1, 0, 1.0};
//+
Point(3) = {1, 1, 0, 1.0};
//+
Point(4) = {1, 0, 0, 1.0};
//+
Point(5) = {0.5, 1, 0, 1.0};
//+
Point(6) = {0.5, 0, 0, 1.0};
//+
Line(1) = {2, 1};
//+
Line(2) = {1, 6};
//+
Line(3) = {6, 5};
//+
Line(4) = {2, 5};
//+
Line(5) = {5, 3};
//+
Line(6) = {3, 4};
//+
Line(7) = {4, 6};
//+
Curve Loop(1) = {4, -3, -2, -1};
//+
Plane Surface(1) = {1};
//+
Curve Loop(2) = {5, 6, 7, 3};
//+
Plane Surface(2) = {2};
//+
Physical Surface("Region1") = {1};
//+
Physical Surface("Region2") = {2};

One issue is surely the fact that dx is not aware of the subdomains. Try having a look at Transitioning from mesh.xml to mesh.xdmf, from dolfin-convert to meshio - #186 by gangadhara or similar messages in that same post and trying some of the solutions posted there. Note how the code in that post ends with

ds = Measure("ds", domain=mesh, subdomain_data=mf)
dx=Measure("dx", domain=mesh, subdomain_data=cf)

which is the way to define measures which are aware of markers. That might also simplify the part about Defining boundary conditions, and allow you to use markers defined in the geo file rather than defining them again in the python file.

Here is some code for reading in the MeshFunction

mesh_from_file = meshio.read("Hima.msh")
mesh = Mesh()
mvc = MeshValueCollection("size_t", mesh, 1)
with XDMFFile("mesh.xdmf") as infile:
    infile.read(mesh)
    infile.read(mvc, "name_to_read")
subdomains = cpp.mesh.MeshFunctionSizet(mesh, mvc)

and setting the integration measure

dx = Measure("dx", domain=mesh, subdomain_data=subdomains)

further work has to be done by the original poster after adding these to his/her code.

import numpy as np
import meshio
from dolfin import *

def create_mesh(mesh, cell_type, prune_z=False):
    cells = mesh.get_cells_type(cell_type)
    cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
    points = mesh.points[:, :2] if prune_z else mesh.points
    out_mesh = meshio.Mesh(points=points, cells={cell_type: cells}, cell_data={"name_to_read": [cell_data]})
    if prune_z:
        out_mesh.prune_z_0()
    return out_mesh

def extract_group_ids(mesh, cell_type, target_regions=None):
    cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
    unique_regions = np.unique(cell_data)
    group_ids = {region_id: list(np.where(cell_data == region_id)[0]) for region_id in unique_regions if target_regions is None or region_id in target_regions}
    return group_ids

def assign_material_properties(mesh, cell_type, group_ids, material_properties):
    properties = {region_id: material_properties[region_id] for region_id in group_ids if region_id in material_properties}
    return properties

def extract_region_ids(mesh, cell_type, target_regions=None, prune_z=False):
    cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
    points = mesh.points[:, :2] if prune_z else mesh.points
    out_mesh = meshio.Mesh(points=points, cells={cell_type: mesh.get_cells_type(cell_type)}, cell_data={"name_to_read": [cell_data]})
    region_ids = {region_id: list(np.where(cell_data == region_id)[0]) for region_id in np.unique(cell_data) if target_regions is None or region_id in target_regions}
    return out_mesh, region_ids

# Example usage:
mesh_from_file = meshio.read("Hima.msh")

triangle_mesh = create_mesh(mesh_from_file, "triangle", prune_z=False)
meshio.write("mesh.xdmf", triangle_mesh)

# Extract and assign material properties
triangle_group_ids_region1 = extract_group_ids(mesh_from_file, "triangle", target_regions=[1])
triangle_group_ids_region2 = extract_group_ids(mesh_from_file, "triangle", target_regions=[2])

material_properties = {
    1: {"E": 200e9, "nu": 0.30},  # Material1 = Steel
    2: {"E": 90e9, "nu": 0.25}    # Material2 = Brass
}

material_properties_region1 = assign_material_properties(mesh_from_file, "triangle", triangle_group_ids_region1, material_properties)
material_properties_region2 = assign_material_properties(mesh_from_file, "triangle", triangle_group_ids_region2, material_properties)

print("Material properties for Region 1:", material_properties_region1)
print("Material properties for Region 2:", material_properties_region2)

# Extract region ids
target_regions_triangle = [1, 2]
triangle_mesh, region_ids_triangle = extract_region_ids(mesh_from_file, "triangle", target_regions_triangle, prune_z=True)
meshio.write("mf.xdmf", triangle_mesh)

# Dolfin specific code
parameters["allow_extrapolation"] = True 
parameters["form_compiler"]["optimize"] = True 

mesh = Mesh()
mvc = MeshValueCollection("size_t", mesh, mesh.topology().dim())

with XDMFFile("mesh.xdmf") as infile:
    infile.read(mesh)
    infile.read(mvc, "name_to_read")

cf = cpp.mesh.MeshFunctionSizet(mesh, mvc)

mvc = MeshValueCollection("size_t", mesh, mesh.topology().dim()-1)
with XDMFFile("mf.xdmf") as infile:
    infile.read(mvc, "name_to_read")   
mf = cpp.mesh.MeshFunctionSizet(mesh, mvc) 

ds = Measure("ds", domain=mesh, subdomain_data=mf)
dx = Measure("dx", domain=mesh, subdomain_data=cf)

"---------------------------------------------------------------------------
/home/himalaya/.local/lib/python3.10/site-packages/h5py/__init__.py:36: UserWarning: h5py is running against HDF5 1.10.7 when it was built against 1.14.2, this may cause problems
  _warn(("h5py is running against HDF5 {0} when it was built against {1}, 

ValueError                                Traceback (most recent call last)
Cell In[79], line 35
     32 mesh_from_file = meshio.read("Hima.msh")
     34 triangle_mesh = create_mesh(mesh_from_file, "triangle", prune_z=False)
---> 35 meshio.write("mesh.xdmf", triangle_mesh)
     37 # Extract and assign material properties
     38 triangle_group_ids_region1 = extract_group_ids(mesh_from_file, "triangle", target_regions=[1])

File ~/.local/lib/python3.10/site-packages/meshio/_helpers.py:188, in write(filename, mesh, file_format, **kwargs)
    185         pass
    187 # Write
--> 188 return writer(filename, mesh, **kwargs)

File ~/.local/lib/python3.10/site-packages/meshio/xdmf/main.py:546, in write(*args, **kwargs)
    545 def write(*args, **kwargs):
--> 546     XdmfWriter(*args, **kwargs)

File ~/.local/lib/python3.10/site-packages/meshio/xdmf/main.py:338, in XdmfWriter.__init__(self, filename, mesh, data_format, compression, compression_opts)
    335 def __init__(
    336     self, filename, mesh, data_format="HDF", compression="gzip", compression_opts=4
    337 ):
--> 338     import h5py
    340     if data_format not in ["XML", "Binary", "HDF"]:
    341         raise WriteError(
    342             "Unknown XDMF data format "
    343             f"'{data_format}' (use 'XML', 'Binary', or 'HDF'.)"
    344         )

File ~/.local/lib/python3.10/site-packages/h5py/__init__.py:56
     51 _register_lzf()
     54 # --- Public API --------------------------------------------------------------
---> 56 from . import h5a, h5d, h5ds, h5f, h5fd, h5g, h5r, h5s, h5t, h5p, h5z, h5pl
     58 from ._hl import filters
     59 from ._hl.base import is_hdf5, HLObject, Empty

File h5py/h5fd.pyx:222, in init h5py.h5fd()
    220 
    221     # local imports
--> 222     from . import h5f, h5fd
    223 
    224     # Utilities

ValueError: 'open' and/or 'close' methods are not defined ('open' and/or 'close' methods are not defined)"
---------------------------------------------------------------------------"

You still have

/home/himalaya/.local/lib/python3.10/site-packages/h5py/__init__.py:36: UserWarning: h5py is running against HDF5 1.10.7 when it was built against 1.14.2, this may cause problems
  _warn(("h5py is running against HDF5 {0} when it was built against {1}, 

Didn’t you fix that a month ago?

Actually, before its working, later started showing issues, now i corrected however i defined function its not working.

from dolfin import *
import numpy as np
import matplotlib.pyplot as plt
import meshio

def process_mesh(mesh, cell_type, target_regions=None, prune_z=False):
    cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
    unique_regions = np.unique(cell_data)

    def extract_ids(region_id):
        return list(np.where(cell_data == region_id)[0])

    def create_and_write(out_file, mesh_type, indices):
        out_mesh = meshio.Mesh(points=mesh.points[:, :2] if prune_z else mesh.points,
                               cells={mesh_type: mesh.get_cells_type(mesh_type)},
                               cell_data={"name_to_read": [cell_data]})
        meshio.write(out_file, out_mesh)

    # Create and write triangle mesh
    create_and_write("mesh.xdmf", "triangle", extract_ids(1) + extract_ids(2))

    # Material properties
    material_properties = {
        1: {"E": 200e9, "nu": 0.30},  # Material1 = Steel
        2: {"E": 90e9, "nu": 0.25}    # Material2 = Brass
    }

    # Assign material properties and print
    for region_id in [1, 2]:
        properties = material_properties.get(region_id, {})
        print(f"Material properties for Region {region_id}:", properties)

mesh_from_file = meshio.read("Hima.msh")
process_mesh(mesh_from_file, "triangle", target_regions=[1, 2], prune_z=True)

def create_mesh(mesh, cell_type, prune_z=False):
    cells = mesh.get_cells_type(cell_type)
    cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
    out_mesh = meshio.Mesh(points=mesh.points, cells={cell_type: cells}, cell_data={"name_to_read":[cell_data]})
    if prune_z:
        out_mesh.prune_z_0()
    return out_mesh

msh=meshio.read("Hima.msh")

triangle_mesh = create_mesh(msh, "triangle", False)
meshio.write("mf.xdmf", triangle_mesh) 
from dolfin import *
parameters["allow_extrapolation"] = True 
parameters["form_compiler"]["optimize"] = True 

mesh=Mesh()
mvc = MeshValueCollection("size_t", mesh, mesh.topology().dim())
with XDMFFile("mesh.xdmf") as infile:
   infile.read(mesh)
   infile.read(mvc, "name_to_read")
cf = cpp.mesh.MeshFunctionSizet(mesh, mvc)
mvc = MeshValueCollection("size_t", mesh, mesh.topology().dim()-1)
with XDMFFile("mf.xdmf") as infile:
    infile.read(mvc, "name_to_read")   
mf = cpp.mesh.MeshFunctionSizet(mesh, mvc) 
  
ds = Measure("ds", domain=mesh, subdomain_data=mf)
dx = Measure("dx", domain=mesh, subdomain_data=cf)

#Creating function space for concentration
UC = FunctionSpace(mesh,"CG",1)

#Creating function space for displacement
UU = VectorFunctionSpace(mesh, "CG", 1)
Unknown ufl object type FiniteElement

---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
Cell In[17], line 2
      1 # Corrected function spaces for concentration and displacement
----> 2 UC = FunctionSpace(mesh, "CG", 1)  # Concentration
      3 UU = VectorFunctionSpace(mesh, "CG", 1)  # Displacement

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/function/functionspace.py:33, in FunctionSpace.__init__(self, *args, **kwargs)
     31     self._init_from_ufl(*args, **kwargs)
     32 else:
---> 33     self._init_convenience(*args, **kwargs)

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/function/functionspace.py:100, in FunctionSpace._init_convenience(self, mesh, family, degree, form_degree, constrained_domain, restriction)
     93 def _init_convenience(self, mesh, family, degree, form_degree=None,
     94                       constrained_domain=None, restriction=None):
     95 
     96     # Create UFL element
     97     element = ufl.FiniteElement(family, mesh.ufl_cell(), degree,
     98                                 form_degree=form_degree)
--> 100     self._init_from_ufl(mesh, element, constrained_domain=constrained_domain)

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/function/functionspace.py:42, in FunctionSpace._init_from_ufl(self, mesh, element, constrained_domain)
     39 ufl.FunctionSpace.__init__(self, mesh.ufl_domain(), element)
     41 # Compile dofmap and element
---> 42 ufc_element, ufc_dofmap = ffc_jit(element, form_compiler_parameters=None,
     43                                   mpi_comm=mesh.mpi_comm())
     44 ufc_element = cpp.fem.make_ufc_finite_element(ufc_element)
     46 # Create DOLFIN element and dofmap

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/jit/jit.py:50, in mpi_jit_decorator.<locals>.mpi_jit(*args, **kwargs)
     48 # Just call JIT compiler when running in serial
     49 if MPI.size(mpi_comm) == 1:
---> 50     return local_jit(*args, **kwargs)
     52 # Default status (0 == ok, 1 == fail)
     53 status = 0

File /usr/lib/petsc/lib/python3/dist-packages/dolfin/jit/jit.py:100, in ffc_jit(ufl_form, form_compiler_parameters)
     98 p.update(dict(parameters["form_compiler"]))
     99 p.update(form_compiler_parameters or {})
--> 100 return ffc.jit(ufl_form, parameters=p)

File ~/.local/lib/python3.10/site-packages/ffc/jitcompiler.py:214, in jit(ufl_object, parameters, indirect)
    211 set_prefix(parameters["log_prefix"])
    213 # Make unique module name for generated code
--> 214 kind, module_name = compute_jit_prefix(ufl_object, parameters)
    216 # Inspect cache and generate+build if necessary
    217 module = jit_build(ufl_object, module_name, parameters)

File ~/.local/lib/python3.10/site-packages/ffc/jitcompiler.py:156, in compute_jit_prefix(ufl_object, parameters, kind)
    154     object_signature = repr(ufl_object)
    155 else:
--> 156     error("Unknown ufl object type %s" % (ufl_object.__class__.__name__,))
    158 # Compute deterministic string of relevant parameters
    159 parameters_signature = compute_jit_parameters_signature(parameters)

File <string>:1, in <lambda>(*message)

File ~/.local/lib/python3.10/site-packages/ufl/log.py:172, in Logger.error(self, *message)
    170 "Write error message and raise an exception."
    171 self._log.error(*message)
--> 172 raise self._exception_type(self._format_raw(*message))

Exception: Unknown ufl object type FiniteElement