scikit-fem is a lightweight Python 3.7+ library for performing finite element
assembly. Its main purpose
is the transformation of bilinear forms into sparse matrices and linear forms
into vectors. The library supports triangular, quadrilateral, tetrahedral and
hexahedral meshes as well as one-dimensional problems.
The library fills a gap in the spectrum of finite element codes. The library is lightweight and has minimal dependencies. It contains no compiled code meaning that it's easy to install and use on all platforms that support NumPy. Despite being fully interpreted, the code has a reasonable performance.
The most recent release can be installed simply by
pip install scikit-fem
Solve the Poisson problem (see also
ex01.py):
from skfem import *
from skfem.helpers import dot, grad
# create the mesh
m = MeshTri().refined(4)
# or, with your own points and cells:
# m = MeshTri(points, cells)
e = ElementTriP1()
basis = Basis(m, e) # shorthand for CellBasis
# this method could also be imported from skfem.models.laplace
@BilinearForm
def laplace(u, v, _):
return dot(grad(u), grad(v))
# this method could also be imported from skfem.models.unit_load
@LinearForm
def rhs(v, _):
return 1.0 * v
A = asm(laplace, basis)
b = asm(rhs, basis)
# or:
# A = laplace.assemble(basis)
# b = rhs.assemble(basis)
# enforce Dirichlet boundary conditions
A, b = enforce(A, b, D=m.boundary_nodes())
# solve -- can be anything that takes a sparse matrix and a right-hand side
x = solve(A, b)
# plot the solution
from skfem.visuals.matplotlib import plot, savefig
plot(m, x, shading='gouraud', colorbar=True)
savefig('solution.png')Meshes can be initialized manually, loaded from external files using meshio, or created with the help of special constructors:
import numpy as np
from skfem import MeshLine, MeshTri, MeshTet
mesh = MeshLine(np.array([0., .5, 1.]))
mesh = MeshTri(
np.array([[0., 0.],
[1., 0.],
[0., 1.]]).T,
np.array([[0, 1, 2]]).T,
)
mesh = MeshTri.load("docs/examples/meshes/square.msh")
mesh = MeshTet.init_tensor(*((np.linspace(0, 1, 60),) * 3))We support many common finite elements. Below the stiffness matrix is assembled using second-order tetrahedra:
from skfem import Basis, ElementTetP2
basis = Basis(mesh, ElementTetP2()) # quadratic tetrahedron
A = laplace.assemble(basis) # type: scipy.sparse.csr_matrixMore examples can be found in the gallery.
The following benchmark (docs/examples/performance.py) demonstrates the time
spent on finite element assembly in comparison to the time spent on linear
solve. The given numbers were calculated using a ThinkPad X1 Carbon laptop (7th
gen). Note that the timings are only illustrative as they depend on, e.g., the
type of element used, the number of quadrature points used, the type of linear
solver, and the complexity of the forms. This benchmark solves the Laplace
equation using linear tetrahedral elements and the default direct sparse solver
of scipy.sparse.linalg.spsolve.
| Degrees-of-freedom | Assembly (s) | Linear solve (s) |
|---|---|---|
| 4096 | 0.04805 | 0.04241 |
| 8000 | 0.09804 | 0.16269 |
| 15625 | 0.20347 | 0.87741 |
| 32768 | 0.46399 | 5.98163 |
| 64000 | 1.00143 | 36.47855 |
| 125000 | 2.05274 | nan |
| 262144 | 4.48825 | nan |
| 512000 | 8.82814 | nan |
| 1030301 | 18.25461 | nan |
The project is documented using Sphinx under docs/.
Built version can be found from Read the Docs.
Here are direct links to additional resources:
If you encounter an issue and cannot find help from the documentation, you can use the Github Discussions to ask questions. Try to provide a snippet of code which fails and include also the version of the library you are using. The version can be found as follows:
python -c "import pkg_resources; print(pkg_resources.get_distribution('scikit-fem').version)"
The minimal dependencies for installing scikit-fem are
numpy, scipy and
meshio. In addition, many
examples use
matplotlib for visualization. Some examples
demonstrate the use of other external packages; see requirements.txt for a
list of test dependencies.
The tests are run by Github Actions. The Makefile in the repository root has
targets for running the testing container locally using docker. For example,
make test_py38 runs the tests using py38 branch from
kinnala/scikit-fem-docker-action.
The releases are tested in
kinnala/scikit-fem-release-tests.
The contents of skfem/ and the PyPI package scikit-fem are licensed under
the 3-clause BSD license. Some examples under docs/examples/ or snippets
in the documentation may have a different license.
This project was started while working under a grant from the Finnish Cultural Foundation. Versions 2.0.0+ were prepared while working in a project funded by the Academy of Finland. The approach used in the finite element assembly has been inspired by the work of A. Hannukainen and M. Juntunen.
We are happy to welcome any contributions to the library. Reasonable projects for first timers include:
By contributing code to scikit-fem, you are agreeing to release it under BSD-3-Clause, see LICENSE.md.
You may use the following BibTeX entry:
@article{skfem2020,
doi = {10.21105/joss.02369},
year = {2020},
volume = {5},
number = {52},
pages = {2369},
author = {Tom Gustafsson and G. D. McBain},
title = {scikit-fem: A {P}ython package for finite element assembly},
journal = {Journal of Open Source Software}
}
Use the Zenodo DOIs if you want to cite a specific version, e.g., to ensure reproducibility.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning with respect to documented and/or tested features.
- Added:
Mesh.save/Mesh.loadnow exports/importsMesh.subdomainsandMesh.boundaries - Added:
Mesh.loadnow optionally writes any mesh data to a list passed via the keyword argumentout - Added:
Mesh.save(andskfem.io.meshio.from_file) now supports the additional keyword argumentforce_meshio_typefor loading mesh files that have multiple element types written in the same file, one element type at a time - Added:
asmwill now accept a list of bases, assemble the same form using all of the bases and sum the result (useful for jump terms and mixed meshes, see Example 41) - Added:
Mesh.with_boundariesnow allows the definition of internal boundaries/interfaces via the flagboundaries_only=False - Added:
MeshTri1DG,MeshQuad1DG,MeshHex1DG,MeshLine1DG; new mesh types for describing meshes with a discontinuous topology, e.g., periodic meshes (see Example 42) - Added:
ElementHexDGfor transforming hexahedral H1 elements to DG/L2 elements. - Added:
ElementTriP1DG,ElementQuad1DG,ElementHex1DG,ElementLineP1DG; shorthands forElementTriDG(ElementTriP1())etc. - Added:
ElementTriSkeletonP0andElementTriSkeletonP1for defining Lagrange multipliers on the skeleton mesh (see Example 40) - Added:
TrilinearFormfor assembling a sparse 3-tensor, e.g., when dealing with unknown material data - Added:
MeshTri.orientedfor CCW oriented triangular meshes which can be useful for debugging or interfacing to external tools - Added: partial support for
MeshWedge1andElementWedge1, the lowest order wedge mesh and element - Added:
ElementTriP3, cubic triangular Lagrange element - Added:
ElementTriP4, quartic triangular Lagrange element - Added:
ElementTri15ParamPlate, 15-parameter nonconforming triangular element for plates - Added:
ElementTriBDM1, the lowest order Brezzi-Douglas-Marini element - Added:
Mesh.draw().show()will now visualize any mesh interactively (requires vedo) - Added: Adaptive refinement for
MeshTet1 - Fixed:
MappingIsoparametricis now about 2x faster for large meshes thanks to additional caching - Fixed:
MeshHex2.savedid not work properly - Fixed:
Mesh.loadignores unparseablecell_setsinserted bymeshioin MSH 4.1 - Changed:
Meshstring representation is now more informative - Changed:
Form.assembleno more allows keyword arguments withlistordicttype: from now on onlyDiscreteFieldor 1d/2dndarrayobjects are allowed and 1dndarrayis passed automatically toBasis.interpolatefor convenience - Changed:
MeshLineis now a function which initializesMeshLine1and not an alias toMeshLine1 - Changed:
FacetBasisis now a shorthand forBoundaryFacetBasisand no longer initializesInteriorFacetBasisorMortarFacetBasisif the keyword argumentsideis passed to the constructor - Removed: the deprecated
Mesh.define_boundarymethod - Removed: the unused
Mesh.validateattribute
- Added:
ElementTriCCRandElementTetCCR, conforming Crouzeix-Raviart finite elements - Fixed:
Mesh.mirroredreturned a wrong mesh when a point other than the origin was used - Fixed:
MeshLineconstructor accepted only NumPy arrays and not plain Python lists - Fixed:
Mesh.element_finder(andCellBasis.probes,CellBasis.interpolator) was not working properly for a small number of elements (<5) or a large number of input points (>1000) - Fixed:
MeshTetandMeshTri.element_finderare now more robust against degenerate elements - Fixed:
Mesh.element_finder(andCellBasis.probes,CellBasis.interpolator) raises exception if the query point is outside of the domain
- Added:
Basis, a shorthand forCellBasis - Added:
CellBasis, a new preferred name forInteriorBasis - Added:
BoundaryFacetBasis, a new preferred name forExteriorFacetBasis - Added:
utils.penalize, an alternative tocondenseandenforcefor essential boundary conditions - Added:
InteriorBasis.point_source, withex38 - Added:
ElementTetDG, similar toElementTriDGfor tetrahedral meshes - Fixed:
MeshLine1.element_finder
- Added: Completely rewritten
Meshbase class which is "immutable" and usesElementclasses to define the ordering of nodes; better support for high-order and other more general mesh types in the future - Added: New quadratic mesh types:
MeshTri2,MeshQuad2,MeshTet2andMeshHex2 - Added:
InteriorBasis.probes; likeInteriorBasis.interpolatorbut returns a matrix that operates on solution vectors to interpolate them at the given points - Added: More overloads for
DiscreteField, e.g., multiplication, summation and subtraction are now explicitly supported inside the form definitions - Added:
MeshHex.to_meshtetfor splitting hexahedra into tetrahedra - Added:
MeshHex.element_finderfor interpolating finite element solutions on hexahedral meshes viaInteriorBasis.interpolator - Added:
Mesh.with_boundaries, a functional replacement toMesh.define_boundary, i.e. defining boundaries via Boolean lambda function - Added:
Mesh.with_subdomainsfor defining subdomains via Boolean lambda function - Added:
skfem.utils.projection, a replacement ofskfem.utils.projectwith a different, more intuitive order of arguments - Added:
skfem.utils.enforcefor setting essential boundary conditions by changing matrix rows to zero and diagonals to one. - Deprecated:
skfem.utils.projectin favor ofskfem.utils.projection - Deprecated:
Mesh.define_boundaryin favor ofMesh.with_boundaries - Removed:
Mesh.{refine,scale,translate}; the replacements areMesh.{refined,scaled,translated} - Removed:
skfem.models.helpers; available asskfem.helpers - Removed:
DiscreteField.{f,df,ddf,hod}; available asDiscreteField.{value,grad,hess,grad3,...} - Removed: Python 3.6 support
- Changed:
Mesh.refinedno more attempts to fix the indexing ofMesh.boundariesafter refine - Changed:
skfem.utils.solvenow usesscipy.sparse.eigsinstead ofscipy.sparse.eigshby default; the old behavior can be retained by explicitly passingsolver=solver_scipy_eigs_sym() - Fixed: High memory usage and other small fixes in
skfem.visuals.matplotlibrelated to 1D plotting
- Deprecated:
sidekeyword argument toFacetBasisin favor of the more explicitInteriorFacetBasisandMortarFacetBasis. - Added:
InteriorFacetBasisfor integrating over the interior facets, e.g., evaluating error estimators with jumps and implementing DG methods. - Added:
MortarFacetBasisfor integrating over the mortar mesh. - Added:
InteriorBasis.with_elementfor reinitializing an equivalent basis that uses a different element. - Added:
Form.partialfor applyingfunctools.partialto the form function wrapped byForm. - Fixed: Include explicit Python 3.9 support.
- Deprecated: List and tuple keyword argument types to
asm. - Deprecated:
Mesh2D.mirrorin favor of the more generalMesh.mirrored. - Deprecated:
Mesh.refine,Mesh.scaleandMesh.translatein favor ofMesh.refined,Mesh.scaledandMesh.translated. - Added:
Mesh.refined,Mesh.scaled, andMesh.translated. The new methods return a copy instead of modifyingself. - Added:
Mesh.mirroredfor mirroring a mesh using a normal and a point. - Added:
Functionalnow supports forms that evaluate to vectors or other tensors. - Added:
ElementHex0, piecewise constant element for hexahedral meshes. - Added:
FacetBasis.tracefor restricting existing solutions to lower dimensional meshes on boundaries or interfaces. - Fixed:
MeshLine.refinednow correctly performs adaptive refinement of one-dimensional meshes.
- Added:
ElementLineP0, one-dimensional piecewise constant element. - Added:
skfem.helpers.curlnow calculates the rotated gradient for two-dimensional elements. - Added:
MeshTet.init_ballfor meshing a ball. - Fixed:
ElementQuad0was not compatible withFacetBasis.
- Fixed: Remove an unnecessary dependency.
- Fixed: Make the preconditioner in
TestEx32more robust.
- Fixed: Remove
testsfrom the PyPI distribution.
- Deprecated:
L2_projectionwill be replaced byproject. - Deprecated:
derivativewill be replaced byproject. - Added:
MeshTet.element_finderandMeshLine.element_finderfor usingInteriorBasis.interpolator. - Added:
ElementTriCR, the nonconforming Crouzeix-Raviart element for Stokes flow. - Added:
ElementTetCR, tetrahedral nonconforming Crouzeix-Raviart element. - Added:
ElementTriHermite, an extension ofElementLineHermiteto triangular meshes. - Fixed: Fix
Mesh.validatefor unsignedMesh.t.
- Fixed: Further optimizations to
Mesh3D.boundary_edges: tested to run on a laptop with over 10 million elements.
- Added:
ElementHex2, a triquadratic hexahedral element. - Added:
MeshTri.init_circle, constructor for a circle mesh. - Fixed:
Mesh3D.boundary_edges(and, consequently,Basis.find_dofs) was slow and used lots of memory due to an exhaustive search of all edges.
- Deprecated:
projectwill only support functions likelambda x: x[0]instead oflambda x, y, z: xin the future. - Added: Support for complex-valued forms:
BilinearFormandLinearFormnow take an optional argumentdtypewhich defaults tonp.float64but can be alsonp.complex64. - Added:
Dofs.__or__andDofs.__add__, for merging degree-of-freedom sets (i.e.Dofsobjects) using|and+operators. - Added:
Dofs.dropandDofs.keep, for further filtering the degree-of-freedom sets - Removed: Support for old-style decorators
bilinear_form,linear_form, andfunctional(deprecated since 1.0.0). - Fixed:
FacetBasisdid not initialize withElementQuadP.
- Added:
MeshQuad._splitquadsaliased asMeshQuad.to_meshtri. - Added:
Mesh.__add__, for merging meshes using+operator: duplicated nodes are joined. - Added:
ElementHexS2, a 20-node quadratic hexahedral serendipity element. - Added:
ElementLineMini, MINI-element for one-dimensional mesh. - Fixed:
Mesh3D.boundary_edgeswas broken in case of hexahedral meshes. - Fixed:
skfem.utils.projectdid not work forElementGlobal.
- Added:
ElementTetMini, MINI-element for tetrahedral mesh. - Fixed:
Mesh3D.boundary_edgesincorrectly returned all edges where both nodes are on the boundary.
- Deprecated: Old-style form constructors
bilinear_form,linear_form, andfunctional. - Changed:
Basis.interpolatereturnsDiscreteFieldobjects instead of ndarray tuples. - Changed:
Basis.interpolateworks now properly for vectorial and high-order elements by interpolating all components and higher order derivatives. - Changed:
Form.assembleaccepts now any keyword arguments (with typeDiscreteField) that are passed over to the forms. - Changed: Renamed
skfem.importerstoskfem.io. - Changed: Renamed
skfem.models.helperstoskfem.helpers. - Changed:
skfem.utils.solvewill now expand also the solutions of eigenvalue problems. - Added: New-style form constructors
BilinearForm,LinearForm, andFunctional. - Added:
skfem.io.jsonfor serialization of meshes to/from json-files. - Added:
ElementLinePp, p-th order one-dimensional elements. - Added:
ElementQuadP, p-th order quadrilateral elements. - Added:
ElementQuadDGfor transforming quadrilateral H1 elements to DG elements. - Added:
ElementQuadBFS, Bogner-Fox-Schmit element for biharmonic problems. - Added:
ElementTriMini, MINI-element for Stokes problems. - Added:
ElementCompositefor using multiple elements in one bilinear form. - Added:
ElementQuadS2, quadratic Serendipity element. - Added:
ElementLineHermite, cubic Hermite element for Euler-Bernoulli beams. - Added:
Mesh.define_boundaryfor defining named boundaries. - Added:
Basis.find_dofsfor finding degree-of-freedom indices. - Added:
Mesh.from_basisfor defining high-order meshes. - Added:
Basis.splitfor splitting multicomponent solutions. - Added:
MortarMappingwith basic support for mortar methods in 2D. - Added:
Basisconstructors now acceptquadraturekeyword argument for specifying a custom quadrature rule.
