from mpi4py import MPI from petsc4py import PETSc from petsc4py.PETSc import ScalarType…
- User
from mpi4py import MPI from petsc4py import PETSc from petsc4py.PETSc import ScalarType
import ufl import dolfinx import numpy as np import pyvista
comm = MPI.COMM_WORLD pyvista.OFF_SCREEN = False plot_sol = True
Create the domain (mesh) and its connectivity
nx, ny = 8, 8 cell_type = dolfinx.mesh.CellType.quadrilateral domain = dolfinx.mesh.create_unit_square(comm, nx, ny, cell_type) tdim = domain.topology.dim fdim = tdim - 1 domain.topology.create_connectivity(fdim, tdim)
FunctionSpace, Trial, and Test Functions
V = dolfinx.fem.FunctionSpace(domain, ("Lagrange", 1)) u = ufl.TrialFunction(V) v = ufl.TestFunction(V)
Dirichlet Boundary Conditions
uh = dolfinx.fem.Function(V)
Create a Function object for the constant value
imposed_disp = dolfinx.fem.Function(V) dolfinx.fem.interpolate_constant(imposed_disp, value=ScalarType(10.0)) uh.interpolate(imposed_disp)
Create Boundary conditions
boundary_facets = dolfinx.mesh.exterior_facet_indices(domain.topology) boundary_dofs = dolfinx.fem.locate_dofs_topological(V, fdim, boundary_facets) bc = dolfinx.fem.dirichletbc(uh, boundary_dofs)
Source term
f = dolfinx.fem.Constant(domain, dolfinx.default_scalar_type(-6))
Bilinear and Linear forms
a = ufl.dot(ufl.grad(u), ufl.grad(v)) * ufl.dx L = f * v * ufl.dx
problem = dolfinx.fem.petsc.LinearProblem( a, L, bcs=[bc], petsc_options={"ksp_type": "preonly", "pc_type": "lu"} ) uh = problem.solve()
print(pyvista.global_theme.jupyter_backend)
if plot_sol is True: u_topology, u_cell_types, u_geometry = dolfinx.plot.vtk_mesh(V)
u_grid = pyvista.UnstructuredGrid(u_topology, u_cell_types, u_geometry) u_grid.point_data["u"] = uh.x.array.real u_grid.set_active_scalars("u") u_plotter = pyvista.Plotter() u_plotter.add_mesh(u_grid, show_edges=True) u_plotter.view_xy() if not pyvista.OFF_SCREEN: u_plotter.show() - Assistant
It seems like you are trying to solve a partial differential equation (PDE) on a square domain using the FEniCSx library, which is the next generation of the FEniCS project. The code snippet you provided contains the setup of a finite element problem, including mesh creation, definition of function spaces, imposition of Dirichlet boundary conditions, formulation of linear and bilinear forms, and solving of the linear system using PETSc through
dolfinx.fem.petsc.LinearProblem.Additionally, your code is set up to plot the solution using PyVista, if the
plot_solflag is set toTrue.Here's a simplified breakdown of the code:
- Initialize MPI communicator.
- Set PyVista parameters for on-screen or off-screen rendering.
- Create a square mesh.
- Define the function space, trial function, and test function.
- Set up Dirichlet boundary conditions with a constant value (imposed displacement of 10.0).
- Define the source term for the right-hand side of the equation.
- Formulate the bilinear and linear forms representing the PDE.
- Solve the PDE using PETSc's linear problem solver with specific solver options.
- Print the PyVista global theme's Jupyter backend.
- If
plot_solisTrue, extract mesh information for plotting, create a PyVista unstructured grid, set the solution fielduas the active scalars, and launch a PyVista plotter to visualize the solution.
The
print(pyvista.global_theme.jupyter_backend)line prints the configuration of the PyVista theme for the Jupyter notebook backend. This can be useful information if you're running the script in an IPython or Jupyter environment to understand how plots will be rendered.Before you run the script, make sure that the required libraries (
mpi4py,petsc4py,ufl,dolfinx,numpy, andpyvista) are installed in your Python environment. If you're running the script in a Jupyter notebook environment, thepyvista.global_theme.jupyter_backendsetting should correspond to the backend used for interactive 3D visualization within the notebook (e.g.,'ipygany'or'panel').Remember, your script is configured not to use
pyvista.OFF_SCREENrendering, so it will attempt to open a plotting window on your computer's display.Lastly, be aware that FEniCSx and PyVista are under active development and their APIs may evolve. If you encounter any issues, check the respective documentation or user forums for troubleshooting and updates.
- User
User My code from mpi4py import MPI from petsc4py import PETSc from petsc4py.PETSc import ScalarType
import ufl import dolfinx import numpy as np import pyvista
comm = MPI.COMM_WORLD pyvista.OFF_SCREEN = False plot_sol = True
Create the domain (mesh) and its connectivity
nx, ny = 8, 8 cell_type = dolfinx.mesh.CellType.quadrilateral domain = dolfinx.mesh.create_unit_square(comm, nx, ny, cell_type) tdim = domain.topology.dim fdim = tdim - 1 domain.topology.create_connectivity(fdim, tdim)
FunctionSpace, Trial, and Test Functions
V = dolfinx.fem.FunctionSpace(domain, ("Lagrange", 1)) u = ufl.TrialFunction(V) v = ufl.TestFunction(V)
Dirichlet Boundary Conditions
uh = dolfinx.fem.Function(V)
uh.interpolate(lambda x: 1 + x[0]**2 + 2 * x[1]**2)
imposed_disp = dolfinx.fem.Constant(domain, ScalarType(10.0)) uh.interpolate(imposed_disp)
Create Boundary conditions
boundary_facets = dolfinx.mesh.exterior_facet_indices(domain.topology) boundary_dofs = dolfinx.fem.locate_dofs_topological(V, fdim, boundary_facets) bc = dolfinx.fem.dirichletbc(uh, boundary_dofs)
Source term
f = dolfinx.fem.Constant(domain, dolfinx.default_scalar_type(-6))
Bilinear and Linear forms
a = ufl.dot(ufl.grad(u), ufl.grad(v)) * ufl.dx L = f * v * ufl.dx
problem = dolfinx.fem.petsc.LinearProblem( a, L, bcs=[bc], petsc_options={"ksp_type": "preonly", "pc_type": "lu"} ) uh = problem.solve()
print(pyvista.global_theme.jupyter_backend)
if plot_sol is True: u_topology, u_cell_types, u_geometry = dolfinx.plot.vtk_mesh(V)
u_grid = pyvista.UnstructuredGrid(u_topology, u_cell_types, u_geometry) u_grid.point_data["u"] = uh.x.array.real u_grid.set_active_scalars("u") u_plotter = pyvista.Plotter() u_plotter.add_mesh(u_grid, show_edges=True) u_plotter.view_xy() if not pyvista.OFF_SCREEN: u_plotter.show()The error: michelangelo@hp:~/Ongoing.Projects/NGVU2/mytests/expression$ python3 expression.py Traceback (most recent call last): File "/usr/lib/petsc/lib/python3/dist-packages/dolfinx/fem/function.py", line 397, in interpolate _interpolate(u, cells) File "/usr/lib/python3.10/functools.py", line 889, in wrapper return dispatch(args[0].class)(*args, **kw) File "/usr/lib/petsc/lib/python3/dist-packages/dolfinx/fem/function.py", line 373, in _interpolate self._cpp_object.interpolate(u, cells, nmm_interpolation_data) TypeError: interpolate(): incompatible function arguments. The following argument types are supported: 1. (self: dolfinx.cpp.fem.Function_float64, f: numpy.ndarray[numpy.float64], cells: numpy.ndarray[numpy.int32]) -> None 2. (self: dolfinx.cpp.fem.Function_float64, u: dolfinx.cpp.fem.Function_float64, cells: numpy.ndarray[numpy.int32], nmm_interpolation_data: Tuple[List[int], List[int], List[float], List[int]]) -> None 3. (self: dolfinx.cpp.fem.Function_float64, expr: dolfinx::fem::Expression<double, double>, cells: numpy.ndarray[numpy.int32]) -> None
Invoked with: <dolfinx.cpp.fem.Function_float64 object at 0x7efc2c5e1d70>, Constant(Mesh(blocked element (Basix element (P, quadrilateral, 1, gll_warped, unset, False), (2,)), 0), (), 0), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63], dtype=int32), ((), (), (), ())
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "/home/michelangelo/Ongoing.Projects/NGVU2/mytests/expression/expression.py", line 31, in uh.interpolate(imposed_disp) File "/usr/lib/petsc/lib/python3/dist-packages/dolfinx/fem/function.py", line 402, in interpolate self._cpp_object.interpolate(np.asarray(u(x), dtype=self.dtype), cells) IndexError: invalid axis: 0 (ndim = 0)
Suggestion from the community administrator to a similar issue: imposed_disp = dolfinx.fem.Constant(my_domain, ScalarType((0.0, 0.0))) u_right.interpolate(imposed_disp) You can either wrap it as
u_right = dolfinx.fem.Function(V) imposed_disp = dolfinx.fem.Expression(dolfinx.fem.Constant(my_domain, ScalarType((0.0, 0.0))), V.element.interpolation_points()) u_right.interpolate(imposed_disp) or do something along the lines of:
class TimeDepBC(): def init(self, t=0): self.t = t self.values = None def call(self, x): if self.values is None: self.values = np.zeros((2, x.shape[1]), dtype=ScalarType) # Update values[0] and values[1] (the x and y component depending on the self.t parameter) # ... # For instance: self.values[0] = self.t return self.values
bc_expr = TimeDepBC()
u_right = dolfinx.fem.Function(V) u_right.interpolate(bc_expr.call) print(u_right.x.array) bc_expr.t = 5 u_right.interpolate(bc_expr.call) print(u_right.x.array)
- Assistant
The issue here is that
uh.interpolate(imposed_disp)is not working as you might expect becauseimposed_dispis adolfinx.fem.Constant, which theinterpolatemethod does not know how to handle directly. The intention appears to be to assign a constant value to every point in the function space, but the API expects either anumpy.ndarray, an expression (dolfinx.fem.Expression), or a callable Python object defining the values at the interpolation points.Let's address the specific error by using the correct method to assign a constant value to your function
uh. We will use a Python callable to define the constant value which, when interpolated, assigns a value of 10 to every degree of freedom in the function spaceV.Here's the corrected part of the code:
# Define a Python function that returns the constant value def constant_value_function(x): values = np.full(x.shape[1], 10.0) # Assuming `x` is a 2D array where x.shape[1] gives the number of points return values # Dirichlet Boundary Conditions uh = dolfinx.fem.Function(V) uh.interpolate(constant_value_function) # Interpolate using the Python functionAnd now you can proceed with creating boundary conditions and solving the problem in the same way as before.
This should resolve the error and allow you to set the constant Dirichlet boundary condition and solve the PDE without any issues. If you want to ensure that the interpolation worked correctly, you can check the values of
uhbefore proceeding with the rest of the code. - User
from mpi4py import MPI from petsc4py import PETSc from petsc4py.PETSc import ScalarType
import ufl import dolfinx import numpy as np import pyvista
comm = MPI.COMM_WORLD pyvista.OFF_SCREEN = False plot_sol = True
Define a Python function that returns the constant value
def constant_value_function(x): values = np.full(x.shape[1], 10.0) # Assuming x is a 2D array where x.shape[1] gives the number of points return values
Create the domain (mesh) and its connectivity
nx, ny = 8, 8 cell_type = dolfinx.mesh.CellType.quadrilateral domain = dolfinx.mesh.create_unit_square(comm, nx, ny, cell_type) tdim = domain.topology.dim fdim = tdim - 1 domain.topology.create_connectivity(fdim, tdim)
FunctionSpace, Trial, and Test Functions
V = dolfinx.fem.FunctionSpace(domain, ("Lagrange", 1)) u = ufl.TrialFunction(V) v = ufl.TestFunction(V)
Dirichlet Boundary Conditions
uh = dolfinx.fem.Function(V)
uh.interpolate(lambda x: 1 + x[0]**2 + 2 * x[1]**2)
uh.interpolate(constant_value_function) # Interpolate using the Python function
Create Boundary conditions
boundary_facets = dolfinx.mesh.exterior_facet_indices(domain.topology) boundary_dofs = dolfinx.fem.locate_dofs_topological(V, fdim, boundary_facets) bc = dolfinx.fem.dirichletbc(uh, boundary_dofs)
Source term
f = dolfinx.fem.Constant(domain, dolfinx.default_scalar_type(-6))
Bilinear and Linear forms
a = ufl.dot(ufl.grad(u), ufl.grad(v)) * ufl.dx L = f * v * ufl.dx
problem = dolfinx.fem.petsc.LinearProblem( a, L, bcs=[bc], petsc_options={"ksp_type": "preonly", "pc_type": "lu"} ) uh = problem.solve()
print(pyvista.global_theme.jupyter_backend)
if plot_sol is True: u_topology, u_cell_types, u_geometry = dolfinx.plot.vtk_mesh(V)
u_grid = pyvista.UnstructuredGrid(u_topology, u_cell_types, u_geometry) u_grid.point_data["u"] = uh.x.array.real u_grid.set_active_scalars("u") u_plotter = pyvista.Plotter() u_plotter.add_mesh(u_grid, show_edges=True) u_plotter.view_xy() if not pyvista.OFF_SCREEN: u_plotter.show()michelangelo@hp:~/Ongoing.Projects/NGVU2/mytests/expression$ python3 expression.py Traceback (most recent call last): File "/home/michelangelo/Ongoing.Projects/NGVU2/mytests/expression/expression.py", line 49, in problem = dolfinx.fem.petsc.LinearProblem( AttributeError: module 'dolfinx.fem' has no attribute 'petsc'
- Assistant
It appears from the error you encountered that there's a misunderstanding about the import paths or a change in the
dolfinxmodule's structure. TheLinearProblemclass is not found underdolfinx.fem.petscbut rather directly underdolfinx.fem. This could be either due to an update in the library or an incorrect import.You should be able to fix this by modifying your import as follows:
Replace this line:
problem = dolfinx.fem.petsc.LinearProblem( a, L, bcs=[bc], petsc_options={"ksp_type": "preonly", "pc_type": "lu"} )With:
problem = dolfinx.fem.LinearProblem( a, L, bcs=[bc], petsc_options={"ksp_type": "preonly", "pc_type": "lu"} )So the
LinearProblemshould be directly called fromdolfinx.fem.Please ensure that you are using a version of
dolfinxthat matches the code you are writing. Given that the error indicates a missing attribute, it is also worth checking the official documentation to ensure you are using the correct import paths according to the version ofdolfinxyou have installed. - User
i want to implement in dolfinx a boundary condition given by a constant value function, give me different examples
- Assistant
In DOLFINx, you can implement boundary conditions with constant values in several ways. Below are a few examples to demonstrate different use cases.
Example 1: Constant on the entire boundary
In this example, you will set a constant value on all the boundaries of your domain (e.g.,
value = 10).from dolfinx import mesh, fem import ufl import numpy as np # Assume you have a mesh 'domain', function space 'V', trial and test functions 'u' and 'v' # ... # Constant value to impose value = 10.0 # Define boundary condition with the constant value for all boundary facets bc_value = fem.Constant(domain, np.float64(value)) boundary_dofs = fem.locate_dofs_geometrical(V, lambda x: np.full(x.shape[1], True)) bc = fem.dirichletbc(bc_value, boundary_dofs)Example 2: Constant on a part of the boundary
Here you set a constant value on a defined part of the domain boundary, such as
y=0for the bottom edge of a 2D domain.def bottom_boundary(x): return np.isclose(x[1], 0) boundary_dofs = fem.locate_dofs_geometrical(V, bottom_boundary) bc = fem.dirichletbc(bc_value, boundary_dofs)Example 3: Constant with the Python function
You can also use a Python function if you want to utilize the same constant value function syntax for more complex scenarios in the future.
def constant_value_function(x): values = np.full(x.shape[1], 10.0) return values # Create a Function and set it with the constant value using 'interpolate' uh = fem.Function(V) uh.interpolate(constant_value_function) boundary_dofs = fem.locate_dofs_geometrical(V, lambda x: np.full(x.shape[1], True)) bc = fem.dirichletbc(uh, boundary_dofs)Remember, these are just templates and need to be adjusted based on the specifics of your problem, such as the mesh and function space definitions.
In each example, the
boundary_dofsare determined by the geometric location of the degrees of freedom on the mesh (facades or vertices, depending on the mesh topology and finite element definition). Thelambdafunction is used to create a logical array representing the facets where the boundary condition applies.For more advanced situations you might want to control the boundary condition in a more refined way or during the simulation, then you would use a Python function or a class to update the values interactively.
Please ensure you are using a version of DOLFINx that matches the examples or check the documentation or source code for the correct class and function names.
- User
consider class BoundaryCondition(): def init(self, type, marker, values): self._type = type if type == "Dirichlet": u_D = Function(V) u_D.interpolate(values) facets = facet_tag.find(marker) dofs = locate_dofs_topological(V, fdim, facets) self._bc = dirichletbc(u_D, dofs) elif type == "Neumann": self._bc = inner(values, v) * ds(marker) elif type == "Robin": self._bc = values[0] * inner(u-values[1], v)* ds(marker) else: raise TypeError("Unknown boundary condition: {0:s}".format(type)) @property def bc(self): return self._bc
@property def type(self): return self._typeDefine the Dirichlet condition
boundary_conditions = [BoundaryCondition("Dirichlet", 1, u_ex), BoundaryCondition("Dirichlet", 2, u_ex), BoundaryCondition("Robin", 3, (r, s)), BoundaryCondition("Neumann", 4, g)]
I want to introduce u_ex as constant, how ca i do that? In this example u_ex is defined as u_ex = lambda x: 1 + x[0]**2 + 2*x[1]**2
- Assistant
To define
u_exas a constant in this context, you can use thedolfinx.fem.Constantclass instead of a lambda function. Here's an example of how you might do it:from dolfinx.fem import Function, Constant, locate_dofs_topological from dolfinx import mesh from ufl import TrialFunction, TestFunction, inner, ds # Assume you have a mesh 'domain', function space 'V', trial and test functions 'u' and 'v' # ... class BoundaryCondition(): def __init__(self, type, V, marker, values): self._type = type if type == "Dirichlet": u_D = Function(V) # If 'values' is a Constant, interpolate is not needed, you can directly use it if isinstance(values, Constant): u_D.interpolate(values) elif callable(values): # If 'values' is a function u_D.interpolate(values) # ... extra cases for other types of 'values' facets = mesh.locate_entities_boundary(V.mesh, V.mesh.topology.dim - 1, marker) dofs = locate_dofs_topological(V, V.mesh.topology.dim - 1, facets) self._bc = dirichletbc(u_D, dofs) # ... additional boundary condition types: Neumann, Robin @property def bc(self): return self._bc @property def type(self): return self._type # In your example, you have a function defined by a lambda # u_ex = lambda x: 1 + x[0]**2 + 2*x[1]**2 # Instead, if you want to use a constant value: u_ex_const = Constant(domain, PETSc.ScalarType(1.0)) # Replace 1.0 with your desired constant value # Define the Dirichlet condition using the constant boundary_conditions = [BoundaryCondition("Dirichlet", V, 1, u_ex_const), # ... additional boundary conditions ]In this code,
Constantis used to create a constant value that can be interpolated directly into aFunctionrepresenting the Dirichlet boundary condition. In your original classBoundaryCondition, you need to pass the appropriateFunctionSpace(here noted asV) and the domain for theConstantcreation.Do note, however, that the way marker functions are used has undergone some changes in recent versions of DOLFINx. If the above code doesn't work, please consult the documentation for the version of DOLFINx you're using to make sure that marker functions and boundary entities are being located correctly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.