API reference#
Problems#
The interface of a problem, discretised with the symmetric interior penalty (SIPG) method and
Nitsche’s method for the Dirichlet conditions (see dolfinx_padapt.dg).
A problem has one or more fields (e.g. a velocity and a pressure), each with a value shape and a
degree relative to the degree of the cell. It provides the residual \(F(u; v)\) on the cells
and the boundary of one degree region, the coupling terms on the interfaces between two regions,
the error indicator and the error measures. The model problems are in
dolfinx_padapt.models.
- dolfinx_padapt.problems.Fields#
The fields of a problem by name, e.g.
{"u": u, "p": p}
- class dolfinx_padapt.problems.Field(name, shape=(), degree_offset=0, boundary=None)#
A field of a problem.
- Parameters:
name (str) – Name of the field.
shape (tuple[int, ...]) – Value shape, e.g.
(gdim,)for a vector.degree_offset (int) – The degree of the field is the degree of the cell plus this offset, e.g.
-1for the pressure of the Stokes equations.boundary (int | None) – If given, the field lives on the exterior facets with this marker (see
facet_tags), with the degree of the cell of each facet, and the continuity of the fields on the cells (such that it matches their trace). Fields of different degrees are not coupled, so the forms cannot have derivatives along the boundary. Only supported by the submesh approach.
- class dolfinx_padapt.problems.Problem(mesh)#
A problem discretised with SIPG and Nitsche’s method.
In the methods below,
uandvare the trial (or solution) and test functions of each field,nthe facet normal,hthe cell size,sigmathe penalty parameter (scaled with the degree),gammathe penalty parameter (not scaled) andpthe degree of the cells.A problem with
boundary_markersalso gets the keyword argumentds_markerinresidual()andestimator(), a function returning the measure of the facets with a given marker (of the cells of the current degree). A nonlinear problem gets the keyword argumentu_prevwith the fields of a previous iterate, seesolve_nonlinear().- Parameters:
mesh (Mesh)
- is_eigenvalue_problem: bool = False#
Whether the right hand side is a (mass) matrix rather than a vector
- nullspace_fields: tuple[str, ...] = ()#
Fields that are only determined up to a constant, e.g. the pressure of the Stokes equations with Dirichlet conditions on the whole boundary
- is_nonlinear: bool = False#
Whether the residual is nonlinear in the fields. Then
uinresidual()is the current iterate, the Jacobian is computed withufl.derivative(), and the problem is solved withsolve_nonlinear()
- property petsc_options: dict#
The PETSc options of the solver. By default a direct solver (MUMPS), and for a nonlinear problem Newton’s method with a backtracking line search (PETSc SNES).
- property facet_tags: MeshTags | None#
Markers of the exterior facets, for
boundary_markersand boundary fields.
- property boundary_markers: tuple[int, ...]#
Markers of the exterior facets with their own integrals (
ds_marker).
- abstract residual(u, v, n, h, sigma, dx, ds)#
The residual on the cells (
dx) and the boundary facets (ds) of one degree.
- abstract interface(u_p, u_m, v_p, v_m, n, h, sigma, dS)#
The coupling terms on interior facets, between the fields
u_p,v_pon the “+” side andu_m,v_mon the “-” side.Called for the facets between cells of every pair of degrees
i <= j(the lower degree on the “+” side), seedolfinx_padapt.degrees.degree_pairs(). This includes the facets inside a region of degreei(i == j, where both sides are the fields of the same space) for discontinuous spaces, but not for continuous spaces, where the jumps vanish inside a region.
- mass(u, v, dx)#
The mass matrix of an eigenvalue problem.
- abstract estimator(u, h, p, gamma, w, dx, ds)#
The cell and boundary terms of the squared error indicator, tested with the DG-0 function
w.
- abstract estimator_interface(u_p, u_m, n, h, p_p, p_m, gamma, w, dS)#
The interior facet terms of the squared error indicator, on the facets between cells of every pair of degrees
i <= j, also inside a region (i == j) for continuous spaces, where the flux jumps do not vanish.
- error_integrands(u)#
Integrands of the error measures of a solution
u.
- solve(A, B, nullspace=None)#
Solve the discrete problem with the stiffness matrix
Aand the right hand sideB(mass matrix or load vector), for approaches that assemble the system themselves. By default, a linear system is solved withpetsc_options.
- solve_nonlinear(approach)#
Solve a nonlinear problem, leaving the solution in the approach. Called by
dolfinx_padapt.approaches.BlockApproach.solve(). By default, a single solve with Newton’s method (dolfinx_padapt.approaches.BlockApproach.newton(), withdolfinx.fem.petsc.NonlinearProblem). Override for an outer iteration.- Return type:
None
- abstract errors(integrals)#
The error used to stop the adaptive loop, and the values to report. Without an error measure (e.g. without an exact solution), the error is
None, and the adaptive loop uses the error indicator.
Models#
Model problems (see dolfinx_padapt.problems.Problem):
EigenvalueProblem: find \((u, \lambda)\) with \(-\Delta u = \lambda u\) in \(\Omega\) and \(u = 0\) on \(\partial\Omega\).PoissonProblem: \(-\Delta u = f\) in \(\Omega\), \(u = g\) on \(\partial\Omega\).ElasticityProblem: \(-\nabla\cdot\sigma(u) = f\) in \(\Omega\), \(u = g\) on \(\partial\Omega\).StokesProblem: \(-\nu\Delta u + \nabla p = f\), \(\nabla\cdot u = 0\) in \(\Omega\), \(u = g\) on \(\partial\Omega\).SignoriniProblem: linear elasticity with frictionless contact (a nonlinear problem).
The source problems use a manufactured solution, such that the error can be measured.
- class dolfinx_padapt.models.EigenvalueProblem(mesh, exact=11.39474727857865)#
The first eigenpair of \(-\Delta u = \lambda u\) in \(\Omega\), \(u = 0\) on \(\partial\Omega\).
- is_eigenvalue_problem: bool = True#
Whether the right hand side is a (mass) matrix rather than a vector
- property constants#
Constants in the forms of the problem.
- source(u)#
The source term \(s(u)\).
- solve(A, B, nullspace=None)#
Solve the discrete problem with the stiffness matrix
Aand the right hand sideB(mass matrix or load vector), for approaches that assemble the system themselves. By default, a linear system is solved withpetsc_options.
- errors(integrals)#
The error used to stop the adaptive loop, and the values to report. Without an error measure (e.g. without an exact solution), the error is
None, and the adaptive loop uses the error indicator.- Parameters:
integrals – The global integral of each of
error_integrands().
- class dolfinx_padapt.models.ElasticityProblem(mesh, exact_solution, mu=1.0, lmbda=1.0)#
Linear elasticity,
\[-\nabla \cdot \sigma(u) = f \text{ in } \Omega, \quad u = g \text{ on } \partial\Omega,\]with \(\sigma(u) = 2\mu\varepsilon(u) + \lambda \operatorname{tr}(\varepsilon(u)) I\), and \(f\) and \(g\) from a manufactured displacement.
The penalty parameter is scaled with \(2\mu + \lambda\).
- Parameters:
- residual(u, v, n, h, sigma, dx, ds)#
The residual on the cells (
dx) and the boundary facets (ds) of one degree.
- interface(u_p, u_m, v_p, v_m, n, h, sigma, dS)#
The coupling terms on interior facets, between the fields
u_p,v_pon the “+” side andu_m,v_mon the “-” side.Called for the facets between cells of every pair of degrees
i <= j(the lower degree on the “+” side), seedolfinx_padapt.degrees.degree_pairs(). This includes the facets inside a region of degreei(i == j, where both sides are the fields of the same space) for discontinuous spaces, but not for continuous spaces, where the jumps vanish inside a region.
- estimator(u, h, p, gamma, w, dx, ds)#
The cell and boundary terms of the squared error indicator, tested with the DG-0 function
w.
- estimator_interface(u_p, u_m, n, h, p_p, p_m, gamma, w, dS)#
The interior facet terms of the squared error indicator, on the facets between cells of every pair of degrees
i <= j, also inside a region (i == j) for continuous spaces, where the flux jumps do not vanish.
- error_integrands(u)#
Integrands of the error measures of a solution
u.
- errors(integrals)#
The error used to stop the adaptive loop, and the values to report. Without an error measure (e.g. without an exact solution), the error is
None, and the adaptive loop uses the error indicator.- Parameters:
integrals – The global integral of each of
error_integrands().
- class dolfinx_padapt.models.LaplaceProblem(mesh)#
The Laplace operator, \(-\Delta u = s(u)\) in \(\Omega\), \(u = g\) on \(\partial\Omega\), for a scalar \(u\).
- Parameters:
mesh (Mesh)
- residual(u, v, n, h, sigma, dx, ds)#
The residual on the cells (
dx) and the boundary facets (ds) of one degree.
- interface(u_p, u_m, v_p, v_m, n, h, sigma, dS)#
The coupling terms on interior facets, between the fields
u_p,v_pon the “+” side andu_m,v_mon the “-” side.Called for the facets between cells of every pair of degrees
i <= j(the lower degree on the “+” side), seedolfinx_padapt.degrees.degree_pairs(). This includes the facets inside a region of degreei(i == j, where both sides are the fields of the same space) for discontinuous spaces, but not for continuous spaces, where the jumps vanish inside a region.
- mass(u, v, dx)#
The mass matrix of an eigenvalue problem.
- estimator(u, h, p, gamma, w, dx, ds)#
The cell and boundary terms of the squared error indicator, tested with the DG-0 function
w.
- estimator_interface(u_p, u_m, n, h, p_p, p_m, gamma, w, dS)#
The interior facet terms of the squared error indicator, on the facets between cells of every pair of degrees
i <= j, also inside a region (i == j) for continuous spaces, where the flux jumps do not vanish.
- class dolfinx_padapt.models.PoissonProblem(mesh, exact_solution)#
The Poisson equation, \(-\Delta u = f\) in \(\Omega\), \(u = g\) on \(\partial\Omega\), with \(f\) and \(g\) from a manufactured solution.
- Parameters:
mesh (Mesh) – The mesh.
exact_solution (Callable[[SpatialCoordinate], Expr]) – The manufactured solution as a function of the spatial coordinate, e.g.
lambda x: ufl.sin(ufl.pi * x[0]).
- source(u)#
The source term \(s(u)\).
- boundary_value()#
The Dirichlet data \(g\).
- error_integrands(u)#
Integrands of the error measures of a solution
u.
- errors(integrals)#
The error used to stop the adaptive loop, and the values to report. Without an error measure (e.g. without an exact solution), the error is
None, and the adaptive loop uses the error indicator.- Parameters:
integrals – The global integral of each of
error_integrands().
- class dolfinx_padapt.models.SignoriniProblem(mesh, facet_tags, dirichlet_marker, contact_marker, displacement, gap, direction, E=20000.0, nu=0.4, alpha=0.1, scheme=ProximalScheme.doubling, tol=1e-08, max_iterations=100)#
Linear elasticity with frictionless contact against a rigid obstacle (the Signorini problem), solved with the latent variable proximal point (LVPP) method of Keith and Surowiec (2024), applied to contact by Dokken, Farrell, Keith, Papadopoulos and Surowiec (2025), as in the FEniCS workshop.
The displacement \(u\) satisfies \(u \cdot \hat{n} \leq g\) on the contact boundary \(\Gamma\), where \(\hat{n}\) is the direction of the obstacle and \(g\) the gap. A latent variable \(\psi\) on \(\Gamma\) (a field on the boundary, of the degree of the cell of each facet) gives \(e^\psi = g - u \cdot \hat{n} > 0\). Every proximal iteration \(k\) solves (with Newton’s method)
\[\begin{split}\alpha_k (\sigma(u), \varepsilon(v))_\Omega - (\psi - \psi_{k-1}, v \cdot \hat{n})_\Gamma &= \alpha_k (f, v)_\Omega,\\ (u \cdot \hat{n} + e^\psi - g, w)_\Gamma &= 0,\end{split}\]for all \((v, w)\), with the Dirichlet condition imposed with Nitsche’s method. The contact pressure is \(\lambda = (\psi - \psi_{k-1}) / \alpha_k\). Facets with neither marker are traction free.
- Parameters:
mesh (Mesh) – The mesh.
facet_tags (MeshTags) – Markers of the exterior facets.
dirichlet_marker (int) – Marker of the facets with the prescribed displacement.
contact_marker (int) – Marker of the (potential) contact boundary \(\Gamma\).
displacement (Callable[[SpatialCoordinate], Expr]) – The prescribed displacement as a function of the spatial coordinate.
gap (Callable[[SpatialCoordinate], Expr]) – The gap \(g\) between \(\Gamma\) and the obstacle as a function of the spatial coordinate.
direction (Sequence[float]) – The direction \(\hat{n}\) of the obstacle.
E (float) – Young’s modulus.
nu (float) – Poisson’s ratio.
alpha (float) – Initial proximal parameter \(\alpha_0\).
scheme (ProximalScheme | str) – Update of \(\alpha_k\) between the proximal iterations.
tol (float) – Stop the proximal iterations when the l2-norm of the change of the displacement (coefficients) is below this tolerance.
max_iterations (int) – Maximal number of proximal iterations.
- is_nonlinear: bool = True#
Whether the residual is nonlinear in the fields. Then
uinresidual()is the current iterate, the Jacobian is computed withufl.derivative(), and the problem is solved withsolve_nonlinear()
- property constants#
Constants in the forms of the problem.
- property facet_tags#
Markers of the exterior facets, for
boundary_markersand boundary fields.
- property boundary_markers#
Markers of the exterior facets with their own integrals (
ds_marker).
- residual(u, v, n, h, sigma, dx, ds, ds_marker=None, u_prev=None)#
The residual on the cells (
dx) and the boundary facets (ds) of one degree.
- interface(u_p, u_m, v_p, v_m, n, h, sigma, dS)#
The coupling terms on interior facets, between the fields
u_p,v_pon the “+” side andu_m,v_mon the “-” side.Called for the facets between cells of every pair of degrees
i <= j(the lower degree on the “+” side), seedolfinx_padapt.degrees.degree_pairs(). This includes the facets inside a region of degreei(i == j, where both sides are the fields of the same space) for discontinuous spaces, but not for continuous spaces, where the jumps vanish inside a region.
- contact_pressure(u, u_prev)#
The contact pressure \(\lambda = (\psi - \psi_{k-1}) / \alpha_k\) on \(\Gamma\).
- estimator(u, h, p, gamma, w, dx, ds, ds_marker=None, u_prev=None)#
The cell and boundary terms of the squared error indicator, tested with the DG-0 function
w.
- estimator_interface(u_p, u_m, n, h, p_p, p_m, gamma, w, dS)#
The interior facet terms of the squared error indicator, on the facets between cells of every pair of degrees
i <= j, also inside a region (i == j) for continuous spaces, where the flux jumps do not vanish.
- solve_nonlinear(approach)#
The proximal point iterations (
dolfinx_padapt.proximal.proximal_point()).
- errors(integrals)#
The error used to stop the adaptive loop, and the values to report. Without an error measure (e.g. without an exact solution), the error is
None, and the adaptive loop uses the error indicator.- Parameters:
integrals – The global integral of each of
error_integrands().
- class dolfinx_padapt.models.StokesProblem(mesh, exact_velocity, exact_pressure, viscosity=1.0, pressure_stabilisation=1.0)#
The Stokes equations,
\[-\nu \Delta u + \nabla p = f, \quad \nabla \cdot u = 0 \text{ in } \Omega, \quad u = g \text{ on } \partial\Omega,\]with \(f\) and \(g\) from a manufactured solution.
The velocity has the degree of the cell, and the pressure one degree less. The pressure is only determined up to a constant, which is removed from the solution and the error. The jumps of the pressure are penalised on interior facets by \(-\gamma_p \frac{h}{\nu} [\![p]\!] [\![q]\!]\), with \(\gamma_p\) the
pressure_stabilisation(Cockburn, Kanschat, Schötzau and Schwab, 2002), which removes spurious pressure oscillations when the velocity is under-resolved. As the exact pressure has no jumps, the method stays consistent.- Parameters:
mesh (Mesh) – The mesh.
exact_velocity (Callable[[SpatialCoordinate], Expr]) – The manufactured velocity (divergence free) as a function of the spatial coordinate.
exact_pressure (Callable[[SpatialCoordinate], Expr]) – The manufactured pressure as a function of the spatial coordinate.
viscosity (float) – The viscosity \(\nu\).
pressure_stabilisation (float) – Parameter of the pressure jump penalty (0 to disable it).
- nullspace_fields: tuple[str, ...] = ('p',)#
Fields that are only determined up to a constant, e.g. the pressure of the Stokes equations with Dirichlet conditions on the whole boundary
- residual(u, v, n, h, sigma, dx, ds)#
The residual on the cells (
dx) and the boundary facets (ds) of one degree.
- interface(u_p, u_m, v_p, v_m, n, h, sigma, dS)#
The coupling terms on interior facets, between the fields
u_p,v_pon the “+” side andu_m,v_mon the “-” side.Called for the facets between cells of every pair of degrees
i <= j(the lower degree on the “+” side), seedolfinx_padapt.degrees.degree_pairs(). This includes the facets inside a region of degreei(i == j, where both sides are the fields of the same space) for discontinuous spaces, but not for continuous spaces, where the jumps vanish inside a region.
- estimator(u, h, p, gamma, w, dx, ds)#
The cell and boundary terms of the squared error indicator, tested with the DG-0 function
w.
- estimator_interface(u_p, u_m, n, h, p_p, p_m, gamma, w, dS)#
The interior facet terms of the squared error indicator, on the facets between cells of every pair of degrees
i <= j, also inside a region (i == j) for continuous spaces, where the flux jumps do not vanish.
- error_integrands(u)#
Integrands of the error measures of a solution
u.
- errors(integrals)#
The error used to stop the adaptive loop, and the values to report. Without an error measure (e.g. without an exact solution), the error is
None, and the adaptive loop uses the error indicator.- Parameters:
integrals – The global integral of each of
error_integrands().
Approaches#
- class dolfinx_padapt.approaches.Approach(problem, params)#
A representation of a space with a cell-wise varying polynomial degree.
The approach owns the degree of each cell (
degrees), which starts atparams.pminand stays within[params.pmin, params.pmax], the degrees the forms are compiled for. It also owns the mesh, which starts as the mesh of the problem, and can be refined (refine()). The forms are compiled once, and are also used on the refined meshes.- Parameters:
problem (Problem) – The problem to solve, which defines the mesh.
params (Parameters) – Discretisation parameters.
- refine(cells, boundary_projection=None)#
Refine the mesh (see
dolfinx_padapt.refinement.refine_curved()). The new cells get the degree of their parent cell. Callupdate()before solving.Note
Collective.
- Parameters:
cells (ndarray[tuple[Any, ...], dtype[int32]]) – The (local) owned cells to refine. Further cells are refined to keep the mesh conforming.
boundary_projection (Callable[[ndarray[tuple[Any, ...], dtype[floating]]], ndarray[tuple[Any, ...], dtype[floating]]] | None) – If given, the new nodes on the boundary are moved to the exact boundary with this map (see
dolfinx_padapt.refinement.refine_curved()).
- Returns:
The refined mesh and its relation to the previous mesh.
- Return type:
- property params: Parameters#
The discretisation parameters.
- property degrees: DegreeField#
The degree of each cell.
- abstract update()#
Rebuild the discrete space for the current degree distribution.
- abstract assemble()#
Assemble the left and right hand sides of the problem for the current degrees: the stiffness and mass matrices of an eigenvalue problem, the stiffness matrix and load vector of a linear problem, or the Jacobian and residual of a nonlinear problem at the current iterate.
- abstract set_solution(x)#
Store the solution vector (in the layout of
assemble()).- Parameters:
x (Vec)
- abstract interpolate_solution(u, field=None)#
Interpolate a field of the solution (by default the first) into
u(a broken space on the parent mesh).
- solve()#
Solve the problem for the current degrees, and store the solution. This base implementation assembles the system and solves it with
solve()(linear and eigenvalue problems).Note
Collective.
- nullspace()#
The nullspace of the stiffness matrix (constants of the
nullspace_fields), if any.- Return type:
NullSpace | None
- estimate()#
Error indicator \(\eta_K\) for every owned cell (indexed by local cell index).
- class dolfinx_padapt.approaches.BlockApproach(problem, params)#
One space per polynomial degree, coupled through interface integrals.
All forms are compiled once (
compile_block_forms()). Every update only creates spaces for every degree and callscreate_formwith the new spaces and integration entities.- Parameters:
problem (Problem)
params (Parameters)
- property spaces: dict[tuple[int, str], FunctionSpace]#
The function space of each
(degree, field), seeupdate().
- property solution: dict[tuple[int, str], Function]#
The solution of each
(degree, field), seeupdate().
- property previous_solution: dict[tuple[int, str], Function]#
The previous iterate of each
(degree, field)of a nonlinear problem (empty for a linear problem), seestore_previous().
- update()#
Rebuild the discrete space for the current degree distribution.
- assemble()#
Assemble the left and right hand sides of the problem for the current degrees: the stiffness and mass matrices of an eigenvalue problem, the stiffness matrix and load vector of a linear problem, or the Jacobian and residual of a nonlinear problem at the current iterate.
- set_solution(x)#
Store the solution vector (in the layout of
assemble()).
- solve()#
Solve the problem for the current degrees:
an eigenvalue problem with
solve(),a linear problem with
dolfinx.fem.petsc.LinearProblem,a nonlinear problem with
solve_nonlinear()(by default Newton’s method, seenewton()),
with the
petsc_optionsof the problem.Note
Collective.
- newton()#
Solve a nonlinear problem from the current solution with
dolfinx.fem.petsc.NonlinearProblem(Newton’s method of PETSc SNES, with thepetsc_optionsof the problem). The nonlinear problem is created at the first call after everyupdate().Note
Collective.
- Returns:
The number of Newton iterations.
- Return type:
- store_previous()#
Store the current solution as the previous iterate of a nonlinear problem.
- change(field)#
The l2-norm of the change of a field from the previous iterate (of the coefficients).
Note
Collective.
- nullspace()#
The nullspace of the stiffness matrix (constants of the
nullspace_fields), if any.
- property num_dofs#
Global number of degrees of freedom.
- interpolate_solution(u, field=None)#
Interpolate a field of the solution (by default the first) into
u(a broken space on the parent mesh).
- class dolfinx_padapt.approaches.HierarchicalApproach(problem, params)#
- Parameters:
problem (Problem)
params (Parameters)
- property function_space: FunctionSpace#
The (hierarchical) space of the maximal degree.
- property dims: ndarray[tuple[Any, ...], dtype[int32]]#
The number of local degrees of freedom of a cell of each degree.
- update()#
Rebuild the discrete space for the current degree distribution.
- assemble()#
Assemble the left and right hand sides of the problem for the current degrees: the stiffness and mass matrices of an eigenvalue problem, the stiffness matrix and load vector of a linear problem, or the Jacobian and residual of a nonlinear problem at the current iterate.
- set_solution(x)#
Store the solution vector (in the layout of
assemble()).
- interpolate_solution(u, field=None)#
Interpolate a field of the solution (by default the first) into
u(a broken space on the parent mesh).
- property num_dofs#
Global number of degrees of freedom.
- class dolfinx_padapt.approaches.RestrictedApproach(problem, params)#
Spaces
V_iof degreeion the whole mesh, restricted to the cells of degreei.- Parameters:
problem (Problem)
params (Parameters)
- class dolfinx_padapt.approaches.SubmeshApproach(problem, params)#
Spaces
V_iof degreeion the submesh of cells with degreei.The forms are compiled once with the spaces on template domains (one per degree, with the coordinate element of the parent mesh). At every update the submeshes are extracted and the forms are created over the parent mesh with the cell entity maps.
A field on the boundary (see
Field) of degreeilives on a submesh of the facets with its marker whose cell has degreei.- Parameters:
problem (Problem)
params (Parameters)
- dolfinx_padapt.approaches.hierarchical_element(cell, degree)#
An orthonormal discontinuous element whose basis functions are ordered by degree.
The basis functions are the orthonormal polynomials of Basix (Dubiner polynomials on simplices and tensor products of Legendre polynomials on quadrilaterals and hexahedra), sorted by degree, such that the first
dims[k]basis functions span the space of degreek(P_kon simplices,Q_kon quadrilaterals and hexahedra). The degrees of freedom are the moments against the basis functions.
- dolfinx_padapt.approaches.restrict_function_space(V, cells)#
Restrict a function space to the degrees of freedom in the closure of
cells.The returned space lives on the same mesh, but only has degrees of freedom associated with
cells, so it must only be used with integration entities (and interpolation) overcells.An interior facet kernel always tabulates both cells of the facet, also on an interface where the space only lives on one side. The dofmap of a cell outside
cellsthat shares a facet withcellstherefore points to the dofs of a neighbour insidecells(valid local indices of the restricted space). The contributions to these dofs are identically zero (the restriction to the outside cell never appears in the form). An outside cell with several neighbours insidecellspoints to one of them, which can add zero entries (coupling the neighbours) to the sparsity pattern. Rows of all other cells are-1.- Parameters:
V (FunctionSpace) – The parent space.
cells (ndarray[tuple[Any, ...], dtype[int32]]) – Local (owned and ghosted) cells to restrict to.
- Returns:
The restricted space and the map from its (local) dofs to the dofs of
V.- Return type:
Adaptivity#
The adaptive loop: solve, estimate, mark, and enrich (p) or refine (h) the marked cells.
- class dolfinx_padapt.adaptivity.MarkingStrategy(*values)#
Strategy for marking the cells to enrich.
- maximum = 'maximum'#
\(\eta_K > \theta \max_{K'} \eta_{K'}\), see
dolfinx.mesh.mark_maximum()
- equidistribution = 'equidistribution'#
\(\eta_K^2 > \theta^2 \Vert\eta\Vert^2 / N\), see
dolfinx.mesh.mark_equidistribution()
- class dolfinx_padapt.adaptivity.Refinement(*values)#
What happens to a marked cell in the adaptive loop.
- p = 'p'#
Increase the degree (the mesh is fixed)
- h = 'h'#
Split the cell (the new cells keep the degree of their parent)
- hp = 'hp'#
Increase the degree where the solution is smooth, and split the cell otherwise (or at the maximal degree), see
dolfinx_padapt.smoothness
- class dolfinx_padapt.adaptivity.IterationResult(iteration, num_dofs, error, eta, degrees, values=<factory>, timings=<factory>)#
Result of one iteration of the adaptive loop.
- Parameters:
- dolfinx_padapt.adaptivity.mark_cells(eta, theta, degrees, strategy=MarkingStrategy.maximum, include_max_degree=False)#
Mark the cells to enrich (or refine).
See
MarkingStrategy. Unlessinclude_max_degree, the indicator of cells at the maximal degree is set to zero, as the error at a singularity would otherwise keep selecting the same (saturated) cells.- Parameters:
eta (ndarray[tuple[Any, ...], dtype[floating]]) – Error indicator of each owned cell.
theta (float) – Marking parameter in (0, 1].
degrees (DegreeField) – The degree of each cell.
strategy (MarkingStrategy | str) – Marking strategy.
include_max_degree (bool) – Also mark cells at the maximal degree (that can be split).
- Returns:
The (local) indices of the marked owned cells.
- Return type:
- dolfinx_padapt.adaptivity.mark_cells_for_coarsening(eta, theta, degrees)#
Mark the cells to coarsen: the owned cells with \(p_K > p_{min}\) and \(\eta_K < \theta \max_{K'} \eta_{K'}\).
Note
Collective. Use a
thetamuch smaller than the one used for enrichment, such that the cells do not alternate between being enriched and coarsened.
- dolfinx_padapt.adaptivity.degree_histogram(degrees)#
Global number of cells of each degree.
- Parameters:
degrees (DegreeField)
- Return type:
- dolfinx_padapt.adaptivity.solve_adaptive(approach, theta=0.5, strategy=MarkingStrategy.maximum, max_iterations=15, tol=1e-08, coarsen_theta=None, callback=None, refinement=Refinement.p, smoothness_threshold=0.2, boundary_projection=None)#
Run the p-, h- or hp-adaptive loop.
Every iteration rebuilds the space for the current degrees (and mesh), assembles and solves the problem of the approach, estimates the error and increases the degree of the marked cells (and, optionally, decreases the degree of the cells with a small error). With h-refinement, the marked cells are split instead. With hp-refinement, a marked cell is split instead of enriched if the solution is not smooth on it (
dolfinx_padapt.smoothness.decay_factor()abovesmoothness_threshold) or if it is at the maximal degree. The new cells get the degree of their parent cell (dolfinx_padapt.approaches.Approach.refine()).Note
Collective.
- Parameters:
approach (Approach) – The representation of the variable degree space (holding the problem).
theta (float) – Marking parameter, see
mark_cells().strategy (MarkingStrategy | str) – Marking strategy, see
mark_cells().max_iterations (int) – Maximal number of iterations.
tol (float) – Stop when the error measure of the problem is below this tolerance.
coarsen_theta (float | None) – If given, also decrease the degree of the cells marked by
mark_cells_for_coarsening()with this parameter (except the cells marked for enrichment).callback (Callable[[Approach, IterationResult], None] | None) – Called with the approach (holding the solution) and the result of every iteration, before the degrees are increased.
refinement (Refinement | str) – p-, h- or hp-refinement.
smoothness_threshold (float) – With hp-refinement, a marked cell is enriched if the decay factor of the Legendre coefficients of the (first field of the) solution is below this threshold, and split otherwise.
boundary_projection (Callable[[ndarray[tuple[Any, ...], dtype[floating]]], ndarray[tuple[Any, ...], dtype[floating]]] | None) – With h- and hp-refinement, move the new nodes on the boundary to the exact boundary with this map (see
dolfinx_padapt.refinement.refine_curved()).
- Returns:
The result of each iteration.
- Return type:
Refinement#
h-refinement of meshes with curved (higher order) geometry, and transfer of functions from a mesh to its refinement.
The refinement of DOLFINx (dolfinx.mesh.refine(), with the algorithm of Plaza and Carey,
“Local refinement of simplicial grids based on the skeleton”, Applied Numerical Mathematics 32(2),
2000, doi:10.1016/S0168-9274(99)00022-7) only supports meshes with straight (affine) cells. A mesh
of geometry order \(k\) is refined by
creating the straight mesh with the same topology (
dolfinx.fem.interpolate_geometry()),refining the straight mesh, which gives the parent cell of each new cell,
creating the new mesh of order \(k\) with straight cells, and
moving its nodes to the curved geometry: the coordinates of the original mesh are a vector Lagrange function of degree \(k\) (in the coordinate space of the mesh) on the straight mesh, which is interpolated into the coordinate space of the new mesh with
interpolate_from_parent().
The new cells are nested in the curved cells of the original mesh, and the boundary of the refined mesh is the (curved) boundary of the original mesh.
- dolfinx_padapt.refinement.BoundaryProjection#
Maps the coordinates of points on the boundary, with shape
(3, num_points), to the closest points on the exact boundary, with shape(3, num_points)(or(gdim, num_points))alias of
Callable[[ndarray[tuple[Any, …],dtype[floating]]],ndarray[tuple[Any, …],dtype[floating]]]
- class dolfinx_padapt.refinement.RefinedMesh(mesh, parent_cells, facet_tags)#
A refined mesh, and its relation to the original mesh.
- Parameters:
- dolfinx_padapt.refinement.interpolate_from_parent(u, u_fine, parent_cells)#
Interpolate a function into a function on a refined mesh, where each cell of the refined mesh lies in a known parent cell.
The interpolation points of each owned cell of the refined mesh are evaluated in its parent cell, which is on the same process (the refinement is not redistributed). The points are not searched for, and there is no communication but a scatter of the ghost values. As each point is evaluated in the parent cell of the cell it belongs to, this also works for discontinuous functions, where a point on the boundary of a parent cell is ambiguous.
Note
Collective.
- dolfinx_padapt.refinement.refine_curved(mesh, cells=None, facet_tags=None, boundary_projection=None)#
Refine a mesh of any geometry order with the algorithm of Plaza and Carey (see the module documentation).
Note
Collective. Only simplex meshes can be refined.
- Parameters:
mesh (Mesh) – The mesh to refine.
cells (ndarray[tuple[Any, ...], dtype[int32]] | None) – The (local) cells to refine. Further cells are refined to keep the mesh conforming. If
None, every cell is refined.facet_tags (MeshTags | None) – Facet tags to transfer to the refined mesh.
boundary_projection (Callable[[ndarray[tuple[Any, ...], dtype[floating]]], ndarray[tuple[Any, ...], dtype[floating]]] | None) – If given, the nodes of the refined mesh on the boundary are moved to the exact boundary with this map. Otherwise, the boundary of the refined mesh is the boundary of
mesh. The map must leave nodes that are on the exact boundary in place, such as all nodes ofmeshif it was created with the same map.
- Returns:
The refined mesh, ghosted over shared facets, the parent cells and the facet tags.
- Return type:
Smoothness indicator#
The local smoothness of a discrete solution, from the decay of its Legendre coefficients (Mavriplis, 1994; Houston and Süli, 2005), to choose between h- and p-refinement.
On a cell \(K\) of degree \(p_K\), the solution is expanded in the orthonormal polynomials \(P_j\) of the reference cell (Dubiner polynomials on simplices, tensor products of Legendre polynomials on quadrilaterals and hexahedra), \(u_h|_K = \sum_j a_j P_j\), and the energy of the modes of degree \(k\) is
For a smooth (analytic) function, the energies decay exponentially, \(E_k \approx C e^{-\sigma_K k}\), while they decay slowly near a singularity. The decay rate \(\sigma_K\) is the least squares fit of \(\log E_k\) for \(k = 1, \dots, p_K\), and the cell is smooth if the decay factor \(e^{-\sigma_K}\) is below a threshold. The mean (\(k = 0\)) is left out, as its size is not related to the smoothness. A cell of degree one has a single mode, which does not give a decay rate, and is considered smooth (it is enriched before it is split).
- dolfinx_padapt.smoothness.legendre_energies(approach, field=None)#
The energy \(E_k\) of the modes of degree \(k = 0, \dots, p_{max}\) of a field of the solution on each owned cell.
The solution is interpolated into the hierarchical space of degree \(p_{max}\), whose degrees of freedom are the moments against the orthonormal polynomials, i.e. the coefficients \(a_j\) (see
dolfinx_padapt.approaches.hierarchical_element()).Note
Collective.
- dolfinx_padapt.smoothness.decay_factor(approach, field=None)#
The decay factor \(e^{-\sigma_K}\) of the Legendre coefficients of a field of the solution on each owned cell (see the module documentation). Small values mean a smooth solution. Cells of degree one have the decay factor zero.
Note
Collective.
Degrees#
Cell-wise polynomial degree field and the integration entities derived from it.
- dolfinx_padapt.degrees.pair_tag(i, j, pmax)#
Interior facet tag for the interface between cells of degree
iandj.
- dolfinx_padapt.degrees.boundary_tag(marker, degree, pmax)#
Exterior facet tag for the facets with a given (non-negative) marker of the cells with a given degree. Distinct from the tags
0, ..., pmaxof all exterior facets of each degree.
- dolfinx_padapt.degrees.degree_pairs(pmin, pmax, continuous=False)#
All
(i, j),i <= j, interior facet combinations of the coupling terms.For continuous spaces, the facets interior to a single degree region carry no coupling terms (the jumps vanish), so
(i, i)is left out. The error indicator integrates over all combinations, as the flux jumps do not vanish.
- class dolfinx_padapt.degrees.DegreeField(mesh, pmin, pmax)#
Polynomial degree per cell, stored both as a DG-0 function and as cell tags.
The value of a cell tag is the polynomial degree of that cell.
- property cell_degrees: ndarray[tuple[Any, ...], dtype[int32]]#
Degree of every cell (owned and ghost) on the process.
- set_degrees(degrees)#
Set the degree of all owned cells.
- refine(cells)#
Increase the degree of the given owned cells by one (capped at
pmax).Note
Collective.
- coarsen(cells)#
Decrease the degree of the given owned cells by one (bounded below by
pmin).Note
Collective.
- change(refine, coarsen)#
Increase the degree of the owned cells
refineand decrease the degree of the owned cellscoarsenby one, within[pmin, pmax].Note
Collective.
- cells(degree, include_ghosts=False)#
Local indices of cells with the given degree.
- integration_entities(facet_tags=None, markers=())#
Integration entities (in parent mesh numbering) for every compiled subdomain id.
dx(i): cells of degreeids(i): exterior facets of cells of degreeids(boundary_tag(m, i)): exterior facets with markerm(infacet_tags) of cells of degreei, for each of themarkersdS(pair_tag(i, j)): facets between cells of degreeiandj, where the"+"restriction is the cell with the lowest degree (alsoi == j, which the coupling terms of continuous spaces do not use, but the error indicator does).
The interior facets are computed once with
dolfinx.fem.compute_integration_domains(), and grouped by the degrees of their two cells.- Parameters:
- Raises:
ValueError – If the mesh is not ghosted with
GhostMode.shared_facet.- Return type:
dict[IntegralType, list[tuple[int, ndarray[tuple[Any, …], dtype[int32]]]]]
Note
Collective. All tags are present on every process (possibly with no entities).
DG building blocks#
Building blocks of the symmetric interior penalty (SIPG) and Nitsche terms.
On an interior facet, a_p lives on the “+” side and a_m on the “-” side, such that
functions from two different spaces (e.g. of two different degrees) can be coupled. The
expressions are restricted inside these functions. The flux is the operator of the problem,
e.g. ufl.grad() for the Laplacian, or the stress for linear elasticity.
- dolfinx_padapt.dg.jump(a_p, a_m, n)#
The jump \([\![a]\!] = a^+ \otimes n^+ + a^- \otimes n^-\) (\(a^+ n^+ + a^- n^-\) for a scalar).
- dolfinx_padapt.dg.normal_jump(a_p, a_m, n)#
The normal jump \([\![a \cdot n]\!] = a^+ \cdot n^+ + a^- \cdot n^-\) of a vector.
- dolfinx_padapt.dg.average(a_p, a_m)#
The average \(\{\!\{a\}\!\} = (a^+ + a^-) / 2\).
- dolfinx_padapt.dg.sipg_interior(u_p, u_m, v_p, v_m, n, h, sigma, flux=<function grad>)#
SIPG terms on an interior facet, with the penalty \(\sigma / \{\!\{h\}\!\}\).
- dolfinx_padapt.dg.nitsche_boundary(u, v, n, h, sigma, g=0.0, flux=<function grad>)#
Nitsche terms for \(u = g\) on the boundary, with the penalty \(\sigma / h\).
- dolfinx_padapt.dg.estimator_jumps(flux_jump, value_jump, h, p_p, p_m, jump_weight, w)#
The facet terms of the error indicator on an interior facet,
\[\frac{h_K}{p_K} \left\| \tfrac{1}{2} [\![\text{flux}]\!] \right\|^2 + c \frac{p_K^3}{h_K} \left\| \tfrac{1}{2} [\![u]\!] \right\|^2,\]with \(c\) the
jump_weight, added to both cells \(K\) of the facet (each with its own \(h_K\) and \(p_K\)).
Forms#
Compilation of the forms of a problem (see dolfinx_padapt.problems) for a space with a
cell-wise polynomial degree.
Two flavours are provided:
Block forms (submeshes and restricted dofmaps), where every polynomial degree
ihas its own space for each field. Volume integralsdx(i)and boundary integralsds(i)only see the spaces of degreei, while the interface integraldS(pair_tag(i, j))couples the spaces of degreei("+", lowest degree) andj("-"). The penalty on each integral is a compile time constant.Single forms (hierarchical basis), where one space of degree
pmaxis used on all cells, and the degree enters through a DG-0 coefficient.
- class dolfinx_padapt.forms.Penalty(*values)#
Polynomial degree \(p\) in the penalty parameter \(\sigma = \alpha p^2 / h\).
- local = 'local'#
\(p = \max(p^+, p^-)\) on an interior facet, and the degree of the cell on the boundary
- global_ = 'global'#
\(p = p_{max}\) everywhere
- class dolfinx_padapt.forms.Parameters(pmin: int = 1, pmax: int = 6, alpha: float = 10.0, penalty: dolfinx_padapt.forms.Penalty | str = <Penalty.local: 'local'>, continuous: bool = False, quadrature_degree: int | None = None, form_compiler_options: dict = <factory>)#
- class dolfinx_padapt.forms.BlockForms(keys, a, rhs, eta, errors, u, u_prev, h, constants)#
Compiled block forms. The blocks are ordered by degree, and within a degree by the fields of the problem, see
keys.- Parameters:
- a: list[list[CompiledForm | None]]#
The bilinear form of each pair of blocks (
Nonefor a zero block)
- rhs: list[CompiledForm]#
The right hand side of each block, i.e. the diagonal blocks of the mass matrix (eigenvalue problem) or the linear forms (source problem)
- eta: dict[tuple[int, ...], CompiledForm]#
The error indicator, split into
(i,)fordx(i) + ds(i), and(i, j)fordS(pair_tag(i, j))
- dolfinx_padapt.forms.compile_block_forms(mesh, spaces, h, params, problem)#
Compile all forms that can appear for any distribution of degrees.
- Parameters:
mesh (Mesh) – The parent (integration) mesh.
spaces (dict[tuple[int, str], FunctionSpace]) – UFL function space of each field for each degree, with keys
(degree, field). These can live on another domain thanmesh(submeshes), as long as an entity map is supplied when creating the forms.h (Function) – Cell size (DG-0 on
mesh).params (Parameters) – Discretisation parameters.
problem (Problem) – The problem to solve.
- Return type:
- class dolfinx_padapt.forms.SingleForms(a, rhs, eta, errors, u)#
Compiled forms for a single (hierarchical) space on the whole mesh.
- Parameters:
a (CompiledForm)
rhs (CompiledForm)
eta (CompiledForm)
u (Coefficient)
- dolfinx_padapt.forms.compile_single_forms(V, h, p, params, problem)#
Compile forms on a single space where the cell-wise degree is given by
p.The problem must have a single field.
- Parameters:
V (FunctionSpace)
h (Function)
p (Function)
params (Parameters)
problem (Problem)
- Return type:
Mesh#
Second order meshes generated with GMSH: the PacMan domain and a half disk.
- dolfinx_padapt.mesh.EXACT_EIGENVALUE = 11.39474727857865#
First Dirichlet eigenvalue of the Laplacian on the PacMan domain (j_{2/3,1}^2)
- dolfinx_padapt.mesh.create_pacman(comm, h=0.25, h_corner=None, order=2, rank=0)#
Create the unit disk with the quadrant \(x > 0, y < 0\) removed.
This is the domain of the amr.py NetGen demo in the DOLFINx tutorial, with a re-entrant corner of angle \(3\pi/2\) at the origin.
- Parameters:
- Returns:
The mesh, ghosted over shared facets (required for interior facet integrals).
- Return type:
- dolfinx_padapt.mesh.pacman_boundary_projection(x)#
Project points on the boundary of the PacMan domain (
create_pacman()) to the exact boundary: the points on the arc are moved to the unit circle, and the points on the straight edges are left in place.
- dolfinx_padapt.mesh.HALF_DISK_FLAT = 1#
Marker of the flat (top) boundary of
create_half_disk()
- dolfinx_padapt.mesh.HALF_DISK_CURVED = 2#
Marker of the curved (bottom) boundary of
create_half_disk()
- dolfinx_padapt.mesh.create_half_disk(comm, radius=0.5, centre=1.0, h=0.06, order=2, rank=0)#
Create the lower half of the disk with the given radius and centre \((0, c)\), the domain of the Signorini problem in the FEniCS workshop.
- Parameters:
- Returns:
The mesh, ghosted over shared facets (required for interior facet integrals), and the facet tags, with
HALF_DISK_FLATon the flat boundary andHALF_DISK_CURVEDon the curved boundary.- Return type:
- dolfinx_padapt.mesh.half_disk_boundary_projection(radius=0.5, centre=1.0)#
The projection of points on the boundary of the half disk (
create_half_disk()) to the exact boundary: the points on the curved boundary are moved to the circle, and the points on the flat boundary are left in place.- Parameters:
- Returns:
The projection, see
dolfinx_padapt.refinement.BoundaryProjection.
Solvers#
Solvers of assembled systems: linear systems (PETSc KSP) and generalised eigenvalue problems
(SLEPc). The block approaches solve linear and nonlinear problems with
dolfinx.fem.petsc.LinearProblem and dolfinx.fem.petsc.NonlinearProblem.
- dolfinx_padapt.solvers.solve_linear(A, b, nullspace=None, petsc_options=None)#
Solve \(Ax = b\) with a PETSc KSP, where \(A\) may have a (constant) nullspace.
Proximal point method#
The latent variable proximal point (LVPP) method of Keith and Surowiec (2024): a sequence of
nonlinear problems with a proximal parameter \(\alpha_k\), each solved with Newton’s
method, see dolfinx_padapt.models.SignoriniProblem.
- class dolfinx_padapt.proximal.ProximalScheme(*values)#
Update of the proximal parameter \(\alpha_k\) between the iterations of
proximal_point().- constant = 'constant'#
\(\alpha_k = \alpha_0\)
- doubling = 'doubling'#
\(\alpha_k = 2^k \alpha_0\)
- dolfinx_padapt.proximal.proximal_point(approach, alpha, alpha_0, scheme=ProximalScheme.doubling, field='u', tol=1e-08, max_iterations=100)#
The proximal point iterations, each solved with Newton’s method from the previous iterate (
dolfinx_padapt.approaches.BlockApproach.newton()).After convergence, the previous iterate is kept (not overwritten by the last iterate), such that quantities depending on both (e.g. the contact pressure) can be evaluated.
Note
Collective.
- Parameters:
approach – The approach holding the problem and its solution.
alpha (Constant) – The proximal parameter in the forms.
alpha_0 (float) – The initial proximal parameter.
scheme (ProximalScheme | str) – The update of the proximal parameter between the iterations.
field (str) – Stop when the change of this field is small.
tol (float) – Stop when the l2-norm of the change of the coefficients of
fieldis below this tolerance.max_iterations (int) – Maximal number of proximal iterations.
- Returns:
The number of proximal and Newton iterations.
- Raises:
RuntimeError – If the iterations do not converge.
- Return type:
Post-processing#
Reporting and output of the adaptive loop.
- dolfinx_padapt.postprocessing.PHASES = ('update', 'solve', 'estimate')#
The phases of an iteration (the solve includes the assembly)
- dolfinx_padapt.postprocessing.print_header()#
Print the header of the table written by
print_iteration().
- dolfinx_padapt.postprocessing.print_iteration(approach, result)#
Print one row of the convergence table (can be used as a callback of
dolfinx_padapt.adaptivity.solve_adaptive()).- Parameters:
approach (Approach)
result (IterationResult)
- dolfinx_padapt.postprocessing.total_timings(history)#
Time spent in each phase, summed over all iterations.
- Parameters:
history (list[IterationResult])
- Return type:
- dolfinx_padapt.postprocessing.max_relative_difference(history, reference, key=None)#
Largest relative difference of a reported value of two runs, over their common iterations.
- Parameters:
history (list[IterationResult]) – The iterations of a run.
reference (list[IterationResult]) – The iterations of the reference run.
key (str | None) – The value to compare (e.g.
"lambda"). Defaults to the first reported value.
- Return type:
- dolfinx_padapt.postprocessing.print_summary(histories, key=None, timings=False)#
Compare several runs: the number of iterations, the final number of dofs and error, and the largest relative difference of a reported value (by default the first) to the first run.
- class dolfinx_padapt.postprocessing.SolutionWriter(approach, folder, name=None, field=None)#
Write a field of the solution (as a broken function of the maximal degree) and the degree of each cell to VTX files, one time step per iteration.
The mesh does not change in P-adaptivity, so a single file holds all iterations.
Plotting#
Visualise a P-adaptive solution with PyVista, and the convergence with Matplotlib.
For every degree i, the solution is interpolated onto a DG-i Lagrange space on a
submesh of the cells with degree i, and converted to a PyVista grid. The grids of every
process are gathered on one process (as in the amr.py demo of the DOLFINx tutorial) and drawn
in a single plot: the solution with iso-lines, the cell edges, and the nodes of each space (as
spheres coloured by degree), showing where the space has been enriched.
- dolfinx_padapt.plotting.CATEGORICAL_COLORS = ['#2a78d6', '#eb6834', '#1baf7a', '#eda100', '#e87ba4', '#008300', '#6250d6', '#e34948']#
Categorical colours, assigned in fixed order (to the degrees from
pmin, or to the runs)
- dolfinx_padapt.plotting.create_grids(approach)#
Create the PyVista grids of the owned cells on this process.
Note
Collective.
- dolfinx_padapt.plotting.plot_solution(approach, plotter=None, root=0, *, show_nodes=True, node_size=8.0, num_isolines=10, title=None)#
Plot the solution, the cell edges and (optionally) the nodes coloured by degree.
Note
Collective. The grids are gathered and drawn on
root, all other processes returnNone.- Parameters:
approach (Approach) – Approach holding the current solution.
plotter (Plotter | None) – Plotter to draw in (on
root), which is cleared first, e.g. to write a frame of an animation. IfNone, a new plotter is created.root (int) – Process gathering the grids and plotting.
show_nodes (bool) – Draw the nodes of each degree as spheres.
node_size (float) – Sphere size (in pixels).
num_isolines (int) – Number of iso-lines of the solution (0 for none).
title (str | None) – Text in the upper left corner.
- Returns:
The plotter on
root,Noneon the other processes.- Return type:
Plotter | None
- dolfinx_padapt.plotting.plot_degrees(degrees, plotter=None, root=0, *, clip=True, title=None)#
Plot the cells coloured by their polynomial degree.
Note
Collective. The grids are gathered and drawn on
root, all other processes returnNone.- Parameters:
degrees (DegreeField) – The degree of each cell.
plotter (Plotter | None) – Plotter to draw in (on
root), which is cleared first. IfNone, a new plotter is created.root (int) – Process gathering the grids and plotting.
clip (bool) – In 3D, remove the cells of one octant to show the interior.
title (str | None) – Text in the upper left corner.
- Return type:
Plotter | None
- dolfinx_padapt.plotting.plot_function(u, plotter=None, root=0, *, origin=None, title=None)#
Plot a (scalar, Lagrange) function on the parent mesh, e.g. the solution interpolated with
dolfinx_padapt.approaches.Approach.interpolate_solution().In 3D, the function is shown on three orthogonal slices through
origin, together with the outline of the domain.Note
Collective. The grids are gathered and drawn on
root, all other processes returnNone.- Parameters:
u (Function) – The function.
plotter (Plotter | None) – Plotter to draw in (on
root), which is cleared first. IfNone, a new plotter is created.root (int) – Process gathering the grids and plotting.
origin (tuple[float, float, float] | None) – The point the slices pass through in 3D (default: the centre of the domain).
title (str | None) – Text in the upper left corner.
- Return type:
Plotter | None
- dolfinx_padapt.plotting.plot_iteration(approach, plotter=None, root=0, *, origin=None, histogram=None, field=None, title=None)#
Plot the solution (left) and the degrees (right) side by side, e.g. to write a frame of an animation of the adaptive loop.
The solution is interpolated into a discontinuous space of the maximal degree, and shown on three orthogonal slices through
originin 3D. The degrees are shown as the mesh coloured by the degree of each cell, or as a bar chart of the number of cells of each degree.Note
Collective. The grids are gathered and drawn on
root, all other processes returnNone.- Parameters:
approach (Approach) – Approach holding the current solution.
plotter (Plotter | None) – Plotter with
shape=(1, 2)to draw in (onroot), which is cleared first. IfNone, a new plotter is created.root (int) – Process gathering the grids and plotting.
origin (tuple[float, float, float] | None) – The point the slices pass through in 3D (default: the centre of the domain).
histogram (bool | None) – Show the number of cells of each degree as a bar chart instead of the mesh. Defaults to a bar chart in 3D, where the cells inside the domain are hidden.
field (str | None) – The field of the solution to plot (by default the first). A vector is shown by its magnitude.
title (str | None) – Text in the upper left corner.
- Return type:
Plotter | None
- class dolfinx_padapt.plotting.Animation(comm, filename, root=0, *, fps=1, window_size=(1400, 600), verbose=True, **kwargs)#
A GIF of the adaptive loop, with the solution and the degrees at each iteration (see
plot_iteration()). It is a callback ofdolfinx_padapt.adaptivity.solve_adaptive(), which also prints the progress:with Animation(mesh.comm, "solution.gif") as animation: solve_adaptive(approach, callback=animation)
Note
Collective. The plotter only exists on
root.- Parameters:
comm (Comm) – The communicator of the mesh.
filename (str) – The GIF file.
root (int) – Process gathering the grids and plotting.
fps (int) – Frames (iterations) per second.
window_size (tuple[int, int]) – Size of each frame in pixels.
verbose (bool) – Print the result of each iteration (
dolfinx_padapt.postprocessing.print_iteration()).kwargs – Keyword arguments to
plot_iteration().
- dolfinx_padapt.plotting.plot_convergence(histories, filename=None, ylabel='Error', annotate=())#
The error measure of the problem against the number of degrees of freedom.
- Parameters:
histories (dict[str, list[IterationResult]]) – The iterations of each run, labelled by name.
filename (str | None) – If given, save the figure to this file.
ylabel (str) – Label of the error axis.
annotate (Sequence[str]) – Names of the runs whose points are labelled with the iteration number, e.g. a run with coarsening, where the number of degrees of freedom can decrease.
- Returns:
The Matplotlib figure.
- dolfinx_padapt.plotting.plot_history(histories, filename=None, ylabel='Error')#
The error measure (top) and the number of degrees of freedom (bottom) at each iteration.