ofempy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ofempy/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """Python port of oFEM (ofem_v2).
2
+
3
+ Conventions that differ from the MATLAB version:
4
+
5
+ * all indices are 0-based (``el``, ``ed``, ``el2ed``, ``refTet``, DOFs, ...),
6
+ * per-element arrays have the element index first, e.g. ``DinvT`` has
7
+ shape ``(Ne, d, d)`` instead of ``d x d x Ne``,
8
+ * coordinates are stored as ``co`` with shape ``(Nco, dim)``, and
9
+ functions of space take points as ``(N, dim)`` arrays.
10
+ """
11
+
12
+ from .boundary import (AbsorbingBoundaryCondition, Dirichlet, DirichletEdge, Neumann, NormalTrace, Robin,
13
+ WaveguideInput)
14
+ from .dofs import DOFHandler
15
+ from .elements import H1Element, HCurlElement, HDivElement
16
+ from .geometry import Boundary, Geometry, Part
17
+ from .materials import Material
18
+ from .problem import InitialCondition, PhysicalProblem
19
+ from .quadrature import gauss_simplex
20
+ from .volume_force import VolumeForce
21
+
22
+ __all__ = ["AbsorbingBoundaryCondition", "Boundary", "DOFHandler", "Dirichlet", "DirichletEdge", "Geometry", "H1Element", "HCurlElement",
23
+ "HDivElement", "InitialCondition", "Material", "Neumann", "NormalTrace", "Part", "PhysicalProblem",
24
+ "Robin", "VolumeForce", "WaveguideInput", "gauss_simplex"]
ofempy/assembly.py ADDED
@@ -0,0 +1,118 @@
1
+ """Element matrix helpers shared by the element classes.
2
+
3
+ Ports of tools/refTensorMatrices.m and tools/geometryFactor.m, plus the
4
+ triplet-to-sparse step of the assembly routines.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+ import scipy.sparse as sps
11
+
12
+ __all__ = ["as_values", "geometry_factor", "is_per_element", "material_times", "points", "ref_tensor_matrices",
13
+ "to_sparse", "to_vector"]
14
+
15
+
16
+ def as_values(v):
17
+ """``v`` as an array of floats, or of complex numbers if it is complex."""
18
+ v = np.asarray(v)
19
+ return v if np.iscomplexobj(v) else v.astype(float, copy=False)
20
+
21
+
22
+ def is_per_element(mat, n):
23
+ """True if ``mat`` holds one value (or tensor) per element of n elements."""
24
+ return isinstance(mat, np.ndarray) and mat.ndim in (1, 3) and mat.shape[0] == n
25
+
26
+
27
+ def _as_element_tensor(mat, ne):
28
+ """Material as broadcastable (1|Ne, nc, nc) array."""
29
+ m = np.asarray(mat, dtype=float)
30
+ if m.ndim == 0:
31
+ return m.reshape(1, 1, 1)
32
+ if m.ndim == 1:
33
+ if m.shape[0] != ne:
34
+ raise ValueError(f"per element material has {m.shape[0]} values for {ne} elements")
35
+ return m.reshape(-1, 1, 1)
36
+ if m.ndim == 2:
37
+ return m[None]
38
+ return m
39
+
40
+
41
+ def geometry_factor(T, mat, fac):
42
+ """Per element factor ``G = T^T mat T * fac`` (Ne, nc, nc).
43
+
44
+ ``T`` (Ne, d, nc) transformation of the reference basis or ``None``;
45
+ ``mat`` scalar, (nc, nc), (Ne,) or (Ne, nc, nc); ``fac`` (Ne,).
46
+ """
47
+ fac = np.asarray(fac).reshape(-1, 1, 1)
48
+ m = _as_element_tensor(mat, fac.shape[0])
49
+ if T is None:
50
+ return np.broadcast_to(m, (fac.shape[0],) + m.shape[1:]) * fac
51
+ if m.shape[1:] == (1, 1):
52
+ return m * np.matmul(T.swapaxes(1, 2), T) * fac
53
+ return np.matmul(np.matmul(T.swapaxes(1, 2), m), T) * fac
54
+
55
+
56
+ def ref_tensor_matrices(B, w, refTet, G):
57
+ """Element matrices on affine elements via reference tensors.
58
+
59
+ ``B`` (nv, Nq, nc, Ns): reference basis (or derivatives) of each
60
+ variant at the quadrature points, ``w`` (Nq,), ``refTet`` (Ne,),
61
+ ``G`` (Ne, nc, nc) everything constant per element. Returns
62
+
63
+ Me[e] = sum_q w_q B_q^T G[e] B_q (Ne, Ns, Ns)
64
+
65
+ computed as ``G[e] : R`` with ``R_ab = sum_q w_q B_q[a]^T B_q[b]``,
66
+ i.e. one matrix product per element instead of a quadrature loop.
67
+ """
68
+ nv, _, nc, ns = B.shape
69
+ ne = G.shape[0]
70
+ R = np.einsum("q,vqai,vqbj->vijab", w, B, B).reshape(nv, ns * ns, nc * nc)
71
+ Gf = G.reshape(ne, nc * nc)
72
+ Me = np.empty((ne, ns * ns), dtype=np.result_type(Gf, R))
73
+ for v in range(nv):
74
+ e = refTet == v
75
+ if e.any():
76
+ Me[e] = Gf[e] @ R[v].T
77
+ return Me.reshape(ne, ns, ns)
78
+
79
+
80
+ def to_sparse(Me, dofs, nd):
81
+ """Sparse matrix from element matrices ``Me`` (Ne, Ns, Ns) and ``dofs`` (Ne, Ns).
82
+
83
+ Entry ``Me[e, i, j]`` goes to row ``dofs[e, i]`` and column
84
+ ``dofs[e, j]``; duplicates are summed. Indices are int32 when they fit.
85
+ """
86
+ ne, ns, _ = Me.shape
87
+ idx = np.int32 if nd < 2**31 else np.int64
88
+ d = dofs.astype(idx, copy=False)
89
+ I = np.broadcast_to(d[:, :, None], (ne, ns, ns)).ravel()
90
+ J = np.broadcast_to(d[:, None, :], (ne, ns, ns)).ravel()
91
+ A = sps.coo_array((Me.ravel(), (I, J)), shape=(nd, nd))
92
+ return A.tocsr()
93
+
94
+
95
+ def to_vector(Fe, dofs, nd):
96
+ """Vector from element vectors ``Fe`` (Ne, Ns) and ``dofs`` (Ne, Ns); real or complex."""
97
+ d = dofs.ravel()
98
+ Fe = np.asarray(Fe)
99
+ if np.iscomplexobj(Fe): # bincount takes real weights only
100
+ return (np.bincount(d, weights=Fe.real.ravel(), minlength=nd)
101
+ + 1j * np.bincount(d, weights=Fe.imag.ravel(), minlength=nd))
102
+ return np.bincount(d, weights=Fe.ravel(), minlength=nd)
103
+
104
+
105
+ def points(elco, lq):
106
+ """Physical points (Ne, dim) of the reference point ``lq`` (dim,)."""
107
+ bary = np.concatenate([[1 - lq.sum()], lq])
108
+ return np.einsum("k,ekd->ed", bary, elco)
109
+
110
+
111
+ def material_times(A, P):
112
+ """Material values ``A`` (scalar, (Ne,), (d,d) or (Ne,d,d)) times basis values ``P`` (Ne, d, Ns)."""
113
+ A = np.asarray(A)
114
+ if A.ndim == 0:
115
+ return A * P
116
+ if A.ndim == 1 or A.shape[1:] == (1, 1):
117
+ return A.reshape(-1, 1, 1) * P
118
+ return np.matmul(A, P)
@@ -0,0 +1,8 @@
1
+ from .absorbing import AbsorbingBoundaryCondition, WaveguideInput
2
+ from .base import BoundaryCondition, FixedBoundary, MixedBoundary, NaturalBoundary
3
+ from .dirichlet import Dirichlet
4
+ from .natural import Neumann, Robin
5
+ from .traces import DirichletEdge, NormalTrace
6
+
7
+ __all__ = ["AbsorbingBoundaryCondition", "BoundaryCondition", "Dirichlet", "DirichletEdge", "FixedBoundary",
8
+ "MixedBoundary", "NaturalBoundary", "Neumann", "NormalTrace", "Robin", "WaveguideInput"]
@@ -0,0 +1,104 @@
1
+ """Absorbing boundary and waveguide port for H(curl) problems.
2
+
3
+ Ports of boundary/AbsorbingBoundaryCondition.m and boundary/WaveguideInput.m.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import numpy as np
9
+
10
+ from ..assembly import to_sparse
11
+ from .base import MixedBoundary
12
+ from .integration import BoundaryQuadrature, function_data_order
13
+ from .traces import DirichletEdge, tangential_trace
14
+
15
+
16
+ class AbsorbingBoundaryCondition(MixedBoundary):
17
+ """First order absorbing boundary: ``factor * int (n x u) . (n x v) ds``.
18
+
19
+ Adds the tangential boundary mass matrix, scaled by ``factor`` (e.g.
20
+ ``1j * k`` for the Silver-Mueller condition of ``curl curl E - k^2 E``),
21
+ to ``M_robin``; there is no right hand side. Any degree, 2D and 3D,
22
+ real or complex ``factor`` (constant or ``f(X)`` / ``f(X, n)``).
23
+
24
+ AbsorbingBoundaryCondition.m only handled lowest order elements on
25
+ faces in the xy plane (it dropped the z coordinate and used a 2D
26
+ Whitney element on each face); its arguments ``feBd``, ``phys`` and the
27
+ normal ``n`` are not needed here: ``(name, mesh, factor)``.
28
+ """
29
+
30
+ def __init__(self, boundary_name, mesh, factor=1.0, order=None):
31
+ super().__init__(0.0, boundary_name, mesh)
32
+ self.factor = factor
33
+ self.order = order
34
+ self.nodes = np.zeros(0, dtype=np.int64)
35
+ self.quad = BoundaryQuadrature(mesh, self.cells)
36
+
37
+ @property
38
+ def normalVector(self):
39
+ return self.quad.normal
40
+
41
+ def load_vector(self, phys):
42
+ return np.zeros(phys.DOFs.Nd)
43
+
44
+ def assemble_mass(self, phys):
45
+ fe, q = phys.element, self.quad
46
+ order = self.order
47
+ if order is None:
48
+ order = 2 * max(fe.degree, 1)
49
+ if callable(self.factor):
50
+ order = function_data_order(fe.dim, order + 2)
51
+ w, X = q.rule(order)
52
+ T = tangential_trace(phys, q, X)
53
+ jw = w[None, :] * q.jac[:, None]
54
+ if callable(self.factor):
55
+ jw = jw * q.evaluate(self.factor, X)
56
+ Me = np.einsum("fq,fqcs,fqct->fst", jw, T, T)
57
+ if not callable(self.factor):
58
+ Me = self.factor * Me
59
+ self.M = to_sparse(Me, phys.DOFs.el2DOF[q.elem], phys.DOFs.Nd)
60
+ return self.M
61
+
62
+
63
+ class WaveguideInput(DirichletEdge):
64
+ """Tangential field of a waveguide mode prescribed on a port (3D).
65
+
66
+ ``u_in`` (Np, 2) are the transverse field samples at the points
67
+ ``x`` (Np, 2) of the port plane (MATLAB: 2 x Np arrays, transposed
68
+ here). As in WaveguideInput.m the field at a point is the average of
69
+ the ``k`` nearest samples (KD tree instead of knnsearch), using the
70
+ coordinates ``axes`` of the mesh points (default x, y: a port in a
71
+ plane z = const); the third component is zero.
72
+
73
+ The field is then set like :class:`DirichletEdge`, by the L2 projection
74
+ of its tangential trace. WaveguideInput.m assigned ``value . t`` (edge
75
+ vector t) to every edge DOF, which for the Whitney DOFs has the wrong
76
+ sign and leaves the higher order DOFs wrong.
77
+ """
78
+
79
+ def __init__(self, u_in, x, boundary_name, mesh, k=10, axes=(0, 1), order=None):
80
+ if mesh.dim != 3:
81
+ raise ValueError("WaveguideInput is only defined in 3D")
82
+ from scipy.spatial import cKDTree
83
+
84
+ u_in = np.asarray(u_in)
85
+ u_in = u_in if np.iscomplexobj(u_in) else u_in.astype(float) # a complex mode carries a phase
86
+ x = np.asarray(x, dtype=float)
87
+ if u_in.shape[0] == 2 and u_in.shape[1] != 2:
88
+ u_in = u_in.T
89
+ if x.shape[0] == 2 and x.shape[1] != 2:
90
+ x = x.T
91
+ self.u_in, self.x, self.k, self.axes = u_in, x, min(k, len(x)), tuple(axes)
92
+ tree = cKDTree(x)
93
+ free_axis = [a for a in range(3) if a not in self.axes][0]
94
+
95
+ def mode(X):
96
+ _, idx = tree.query(X[:, self.axes], k=self.k)
97
+ idx = idx.reshape(len(X), -1)
98
+ uv = self.u_in[idx].mean(axis=1)
99
+ out = np.zeros((len(X), 3), dtype=self.u_in.dtype)
100
+ out[:, self.axes[0]], out[:, self.axes[1]] = uv[:, 0], uv[:, 1]
101
+ out[:, free_axis] = 0
102
+ return out
103
+
104
+ super().__init__(mode, boundary_name, mesh, order)
@@ -0,0 +1,61 @@
1
+ """Boundary condition base classes (Boundary_Condition, Fixed/Natural/MixedBoundary)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+
8
+ class BoundaryCondition:
9
+ """A condition on the boundary ``name`` of a mesh.
10
+
11
+ Collects the boundary's entities like the MATLAB constructors:
12
+ ``cells`` (unique, sorted node tuples), ``nodes``, ``edges`` and, in 3D,
13
+ ``faces`` (indices into the mesh's node, edge and face lists).
14
+ ``index`` is the position of the boundary in ``mesh.bd``.
15
+ """
16
+
17
+ def __init__(self, value, boundary_name, mesh):
18
+ self.value = value
19
+ self.name = boundary_name
20
+ self.index = next((i for i, b in enumerate(mesh.bd) if b.name == boundary_name), None)
21
+ if self.index is None:
22
+ raise KeyError(f"no boundary named {boundary_name!r}; have {[b.name for b in mesh.bd]}")
23
+ self.cells = np.unique(np.sort(mesh.bd[self.index].cells, axis=1), axis=0)
24
+ self.nodes = np.unique(self.cells)
25
+ self.faces = np.zeros(0, dtype=np.int64)
26
+ self.interiors = None
27
+ if mesh.dim == 2:
28
+ self.edges = np.unique(mesh.edge_index(self.cells))
29
+ else:
30
+ self.faces = np.unique(mesh.face_index(self.cells))
31
+ self.edges = np.unique(mesh.fa2ed[self.faces])
32
+ if (self.edges < 0).any() or (self.faces < 0).any():
33
+ raise ValueError(f"boundary {boundary_name!r} has cells that are not mesh entities")
34
+
35
+ def remove_entities(self, other):
36
+ """Drop the nodes, edges and faces that ``other`` contains as well."""
37
+ self.nodes = np.setdiff1d(self.nodes, other.nodes)
38
+ self.edges = np.setdiff1d(self.edges, other.edges)
39
+ self.faces = np.setdiff1d(self.faces, other.faces)
40
+
41
+ def shares_entities(self, other):
42
+ """True if both conditions act on a common node, edge or face.
43
+
44
+ Edges and faces matter for the trace conditions of H(curl) / H(div),
45
+ which have no node DOFs: two of them meeting along a curve would
46
+ otherwise both set (and add up) the DOFs of the common edges.
47
+ """
48
+ return any(np.intersect1d(a, b).size for a, b in ((self.nodes, other.nodes), (self.edges, other.edges),
49
+ (self.faces, other.faces)))
50
+
51
+
52
+ class FixedBoundary(BoundaryCondition):
53
+ """Essential condition: ``load_vector`` returns DOF values and fixes them."""
54
+
55
+
56
+ class NaturalBoundary(BoundaryCondition):
57
+ """Natural condition: ``load_vector`` returns a right hand side contribution."""
58
+
59
+
60
+ class MixedBoundary(BoundaryCondition):
61
+ """Robin type condition: right hand side plus a boundary mass matrix."""
@@ -0,0 +1,30 @@
1
+ """Dirichlet boundary condition, port of boundary/Dirichlet.m."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from .base import FixedBoundary
8
+
9
+
10
+ class Dirichlet(FixedBoundary):
11
+ """Prescribed values on a boundary.
12
+
13
+ ``value`` is a constant or a function ``f(X)`` of the vertex
14
+ coordinates ``X`` (N, dim) returning (N,). As in MATLAB, only the
15
+ vertex DOFs get the value; all other DOFs on the boundary (edges,
16
+ faces) are fixed to zero. This is exact for data that is linear on
17
+ each boundary cell, e.g. constants.
18
+ """
19
+
20
+ def load_vector(self, phys):
21
+ dofs = phys.DOFs
22
+ values = self.value
23
+ if callable(values) and dofs.n2DOF is not None and self.nodes.size:
24
+ values = np.asarray(values(phys.geometry.co[self.nodes])).reshape(-1)
25
+ u = np.zeros(dofs.Nd, dtype=complex if np.iscomplexobj(values) else float)
26
+ if dofs.n2DOF is not None and self.nodes.size:
27
+ u[dofs.n2DOF[self.nodes, 0]] = values
28
+ dofs.reduce_dofs(self)
29
+ self.u = u
30
+ return u
@@ -0,0 +1,120 @@
1
+ """Integration over boundary cells with the trace of the volume basis.
2
+
3
+ Instead of a separate boundary element (``feBd`` in MATLAB), the volume
4
+ basis of the element adjacent to each boundary cell is evaluated at the
5
+ cell's quadrature points. Basis functions that do not live on the cell
6
+ vanish there, so the result is the trace space with the correct global
7
+ DOFs and orientation for any polynomial degree, in 2D and 3D.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import inspect
13
+ from math import factorial
14
+
15
+ import numpy as np
16
+
17
+ from ..quadrature import MAX_ORDER, gauss_simplex
18
+
19
+
20
+ class BoundaryQuadrature:
21
+ """Geometry of the boundary cells ``cells`` (Nf, dim) of ``mesh``.
22
+
23
+ ``elem`` (Nf,) adjacent element, ``normal`` (Nf, dim) unit normal
24
+ pointing out of that element, ``meas`` (Nf,) length / area.
25
+ """
26
+
27
+ def __init__(self, mesh, cells, edges=None, faces=None, elem=None):
28
+ self.mesh = mesh
29
+ self.cells = np.asarray(cells)
30
+ dim = mesh.dim
31
+ x = mesh.co[self.cells] # (Nf, dim, dim) vertex coordinates
32
+ self.x0 = x[:, 0]
33
+ self.T = (x[:, 1:] - x[:, :1]).swapaxes(1, 2) # (Nf, dim, dim-1) tangents
34
+ if dim == 2:
35
+ t = self.T[:, :, 0]
36
+ n = np.column_stack([t[:, 1], -t[:, 0]])
37
+ if elem is None:
38
+ ent = mesh.edge_index(self.cells) if edges is None else edges
39
+ elem = owners(mesh.el2ed, ent)
40
+ else:
41
+ n = np.cross(self.T[:, :, 0], self.T[:, :, 1])
42
+ if elem is None:
43
+ ent = mesh.face_index(self.cells) if faces is None else faces
44
+ elem = owners(mesh.el2fa, ent)
45
+ self.elem = np.asarray(elem)
46
+ norm = np.linalg.norm(n, axis=1)
47
+ self.meas = norm / factorial(dim - 1)
48
+ n = n / norm[:, None]
49
+ centroid = mesh.co[mesh.el[self.elem]].mean(axis=1)
50
+ s = np.sign(np.einsum("fd,fd->f", n, self.x0 - centroid))
51
+ s[s == 0] = 1
52
+ self.normal = n * s[:, None]
53
+ # |J| of the map from the reference boundary simplex
54
+ self.jac = norm
55
+
56
+ def rule(self, order):
57
+ """Quadrature: weights (Nq,), physical points (Nf, Nq, dim)."""
58
+ w, s = gauss_simplex(self.mesh.dim - 1, order)
59
+ X = self.x0[:, None, :] + np.einsum("fdk,qk->fqd", self.T, s)
60
+ return w, X
61
+
62
+ def basis(self, fe, X):
63
+ """Volume basis of the adjacent elements at ``X`` (Nf, Nq, dim).
64
+
65
+ Returns the values (Nf, Nq, Ns); the matching global DOFs are
66
+ ``el2DOF[self.elem]``.
67
+ """
68
+ return self.reference_basis(fe.phi, X)[:, :, 0, :]
69
+
70
+ def reference_points(self, X):
71
+ """Reference coordinates (Nf, Nq, dim) of ``X`` in the adjacent elements."""
72
+ g, e = self.mesh, self.elem
73
+ return np.einsum("fji,fqj->fqi", g.DinvT[e], X - g.co[g.el[e, 0]][:, None, :])
74
+
75
+ def reference_basis(self, fun, X):
76
+ """``fun(l)`` (2, Nq, nc, Ns) of the adjacent elements at ``X``: (Nf, Nq, nc, Ns)."""
77
+ nf, nq, dim = X.shape
78
+ P = fun(self.reference_points(X).reshape(-1, dim))
79
+ P = P.reshape((2, nf, nq) + P.shape[2:])
80
+ variant = self.mesh.refTet[self.elem].astype(np.intp)
81
+ return np.take_along_axis(P, variant[None, :, None, None, None], axis=0)[0]
82
+
83
+ def evaluate(self, value, X):
84
+ """Values of ``value`` at ``X`` (Nf, Nq, dim): constant, f(X) or f(X, n)."""
85
+ if not callable(value):
86
+ v = np.asarray(value)
87
+ return np.broadcast_to(v if np.iscomplexobj(v) else v.astype(float), X.shape[:2])
88
+ nf, nq, dim = X.shape
89
+ pts = X.reshape(-1, dim)
90
+ try:
91
+ nargs = len(inspect.signature(value).parameters)
92
+ except (TypeError, ValueError):
93
+ nargs = 1
94
+ if nargs >= 2:
95
+ n = np.repeat(self.normal, nq, axis=0)
96
+ v = value(pts, n)
97
+ else:
98
+ v = value(pts)
99
+ v = np.asarray(v)
100
+ return (v if np.iscomplexobj(v) else v.astype(float)).reshape(nf, nq)
101
+
102
+
103
+ def function_data_order(dim, order):
104
+ """Automatic quadrature order for function data, at most the highest rule on the boundary cells.
105
+
106
+ Function data are not integrated exactly anyway; without the bound,
107
+ high degrees in 3D asked for triangle rules beyond order 12.
108
+ """
109
+ return min(order, MAX_ORDER[dim - 1])
110
+
111
+
112
+ def owners(el2x, idx):
113
+ """One element containing each of the entities ``idx`` (adjacentElements in MATLAB)."""
114
+ ne = el2x.shape[0]
115
+ owner = np.full(el2x.max() + 1, -1, dtype=np.int64)
116
+ owner[el2x.ravel()] = np.repeat(np.arange(ne), el2x.shape[1])
117
+ res = owner[np.asarray(idx)]
118
+ if (res < 0).any():
119
+ raise ValueError("boundary entity without an adjacent element")
120
+ return res
@@ -0,0 +1,116 @@
1
+ """Neumann and Robin boundary conditions (boundary/Neumann.m, boundary/Robin.m)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import scipy.sparse as sps
7
+
8
+ from ..assembly import to_sparse, to_vector
9
+ from .base import MixedBoundary, NaturalBoundary
10
+ from .integration import BoundaryQuadrature, function_data_order
11
+
12
+
13
+ def _order(fe, *values, base, order=None):
14
+ """Quadrature order for a boundary integral.
15
+
16
+ ``base`` if all values are constants (the integrand is then a
17
+ polynomial of that degree), ``2p + 2`` if any value is a function: exact
18
+ for data up to degree p + 2 (MATLAB's Neumann used p + 2 throughout;
19
+ bounded by the highest available rule). ``order`` overrides the choice.
20
+ """
21
+ if order is not None:
22
+ return order
23
+ if any(callable(v) for v in values):
24
+ return function_data_order(fe.dim, 2 * fe.degree + 2)
25
+ return base
26
+
27
+
28
+ class Neumann(NaturalBoundary):
29
+ """Natural condition ``k du/dn = g``: adds ``int g v ds`` to the right hand side.
30
+
31
+ ``value`` is a constant ``g``, a function ``g(X)`` of the points
32
+ ``X`` (N, dim), or ``g(X, n)`` with the outer unit normals ``n``
33
+ (N, dim). Works for any degree in 2D and 3D (MATLAB: order 1 in 3D)
34
+ and needs no boundary element. ``order`` sets the quadrature order
35
+ (default: exact for constants, and for function data up to degree p+2).
36
+ """
37
+
38
+ def __init__(self, value, boundary_name, mesh, order=None):
39
+ super().__init__(value, boundary_name, mesh)
40
+ self.order = order
41
+ self.quad = BoundaryQuadrature(mesh, self.cells)
42
+
43
+ @property
44
+ def normalVector(self):
45
+ return self.quad.normal
46
+
47
+ @property
48
+ def meas(self):
49
+ return self.quad.meas
50
+
51
+ def load_vector(self, phys):
52
+ fe, q = phys.element, self.quad
53
+ w, X = q.rule(_order(fe, self.value, base=fe.degree, order=self.order))
54
+ P = q.basis(fe, X)
55
+ g = q.evaluate(self.value, X)
56
+ Fe = np.einsum("q,fq,fqi->fi", w, g, P) * q.jac[:, None]
57
+ self.b = to_vector(Fe, phys.DOFs.el2DOF[q.elem], phys.DOFs.Nd)
58
+ return self.b
59
+
60
+
61
+ class Robin(MixedBoundary):
62
+ """Robin condition ``k du/dn + alpha u = beta g``.
63
+
64
+ Adds ``int alpha u v ds`` to ``M_robin`` and ``int beta g v ds`` to the
65
+ right hand side. ``value`` (g), ``alpha`` and ``beta`` are constants or
66
+ functions ``f(X)`` / ``f(X, n)`` like for :class:`Neumann`. The argument
67
+ order is MATLAB's ``Robin(value, alpha, beta, feBd, name, mesh)``
68
+ without ``feBd``; ``order`` sets the quadrature order of both terms.
69
+
70
+ Differences to Robin.m:
71
+
72
+ * The boundary mass matrix is the consistent one. Robin.m built it
73
+ with equal row and column indices (``I = J``), which adds every entry
74
+ to the diagonal, i.e. it is the row-sum lumped matrix; pass
75
+ ``lumped=True`` to get that (meaningful for P1).
76
+ * DOFs and areas are matched per cell for any degree (Robin.m mixed
77
+ the order of faces and areas in 3D and mapped face edges wrongly).
78
+ * Function values are evaluated at the quadrature points.
79
+ """
80
+
81
+ def __init__(self, value, alpha, beta, boundary_name, mesh, order=None, lumped=False):
82
+ super().__init__(value, boundary_name, mesh)
83
+ self.order = order
84
+ self.lumped = lumped
85
+ self.alpha = alpha
86
+ self.beta = beta
87
+ self.quad = BoundaryQuadrature(mesh, self.cells)
88
+
89
+ @property
90
+ def normalVector(self):
91
+ return self.quad.normal
92
+
93
+ @property
94
+ def meas(self):
95
+ return self.quad.meas
96
+
97
+ def load_vector(self, phys):
98
+ fe, q = phys.element, self.quad
99
+ w, X = q.rule(_order(fe, self.value, self.beta, base=fe.degree, order=self.order))
100
+ P = q.basis(fe, X)
101
+ g = q.evaluate(self.value, X) * q.evaluate(self.beta, X)
102
+ Fe = np.einsum("q,fq,fqi->fi", w, g, P) * q.jac[:, None]
103
+ self.b = to_vector(Fe, phys.DOFs.el2DOF[q.elem], phys.DOFs.Nd)
104
+ return self.b
105
+
106
+ def assemble_mass(self, phys):
107
+ fe, q = phys.element, self.quad
108
+ w, X = q.rule(_order(fe, self.alpha, base=2 * fe.degree, order=self.order))
109
+ P = q.basis(fe, X)
110
+ a = q.evaluate(self.alpha, X)
111
+ Me = np.einsum("q,fq,fqi,fqj->fij", w, a, P, P) * q.jac[:, None, None]
112
+ M = to_sparse(Me, phys.DOFs.el2DOF[q.elem], phys.DOFs.Nd)
113
+ if self.lumped:
114
+ M = sps.diags_array(np.asarray(M.sum(axis=1)).ravel(), format="csr")
115
+ self.M = M
116
+ return self.M