1+ import math
12from abc import ABC
23import numpy as np
34import scipy .special as sp_special
@@ -71,6 +72,27 @@ def singularity_free_jacobi_polynomial_and_derivatives(n, a, b, x, y):
7172
7273
7374class BasisFunctionGenerator (ABC ):
75+ """
76+ The basis functions of the polynomials of degree order - 1 on the reference
77+ element: the unit interval, the triangle (0, 0), (1, 0), (0, 1), or the
78+ tetrahedron (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1).
79+
80+ A point x is given by its coordinates x[0], ..., x[dim - 1], each a number or
81+ an array of points; on the interval, by its coordinate itself.
82+
83+ family: the name a generator of this basis is asked for (see generator)
84+ hierarchical: whether the functions of degree at most m come first, in the
85+ same order for every order; then a polynomial of degree m has nonzero
86+ coefficients in the leading entries alone
87+ orthogonal: whether the functions are orthogonal in L2 on the reference element
88+ orthonormal: whether they are, in addition, of unit norm there
89+ """
90+
91+ family = None
92+ hierarchical = False
93+ orthogonal = False
94+ orthonormal = False
95+
7496 def __init__ (self , order ):
7597 self .order = order
7698
@@ -88,14 +110,72 @@ def number_of_basis_functions(self, o):
88110 def dim (self ):
89111 pass
90112
113+ def degree (self ):
114+ return self .order - 1
115+
116+ def eval_all (self , x ):
117+ """All basis functions at the points x (dim x points), shape (points, functions)."""
118+ x = _as_points (x , self .dim ())
119+ n = self .number_of_basis_functions ()
120+ return np .stack (
121+ [
122+ np .broadcast_to (self .eval_basis (_coordinates (x ), i ), x .shape [1 :])
123+ for i in range (n )
124+ ],
125+ axis = - 1 ,
126+ )
127+
128+ def eval_diff_all (self , x , k ):
129+ """The derivatives d / d_x_k of all basis functions at the points x, shape
130+ (points, functions)."""
131+ x = _as_points (x , self .dim ())
132+ n = self .number_of_basis_functions ()
133+ return np .stack (
134+ [
135+ np .broadcast_to (
136+ self .eval_diff_basis (_coordinates (x ), i , k ), x .shape [1 :]
137+ )
138+ for i in range (n )
139+ ],
140+ axis = - 1 ,
141+ )
142+
143+
144+ def _as_points (x , dim ):
145+ """Points as an array of shape (dim, points), from that shape, from the dim
146+ coordinates of one point, or on the interval from the coordinates of the
147+ points."""
148+ x = np .asarray (x , dtype = float )
149+ if x .ndim <= 1 :
150+ return x .reshape (1 , - 1 ) if dim == 1 else x .reshape (dim , 1 )
151+ if x .ndim != 2 or x .shape [0 ] != dim :
152+ raise ValueError (f"points of shape { x .shape } , not ({ dim } , points)" )
153+ return x
154+
155+
156+ def _coordinates (x ):
157+ """What eval_basis takes for points of shape (dim, points): the coordinate
158+ itself on the interval, the rows otherwise."""
159+ return x [0 ] if x .shape [0 ] == 1 else x
160+
91161
92162################################################################################
93163
94164
95165class BasisFunctionGenerator1D (BasisFunctionGenerator ):
166+ """The shifted Legendre polynomials P_i(2 x - 1) on the unit interval."""
167+
168+ family = "dubiner"
169+ hierarchical = True
170+ orthogonal = True
171+
96172 def dim (self ):
97173 return 1
98174
175+ def norm_squared (self , i ):
176+ """The L2 norm of the i-th function squared."""
177+ return 1.0 / (2 * i + 1 )
178+
99179 def eval_basis (self , x , i ):
100180 r_num = 2 * x - 1.0
101181 r_den = 1.0
@@ -119,9 +199,20 @@ def number_of_basis_functions(self):
119199
120200
121201class BasisFunctionGenerator2D (BasisFunctionGenerator ):
202+ """The Dubiner basis on the triangle, ordered by degree."""
203+
204+ family = "dubiner"
205+ hierarchical = True
206+ orthogonal = True
207+
122208 def dim (self ):
123209 return 2
124210
211+ def norm_squared (self , i ):
212+ """The L2 norm of the i-th function squared."""
213+ p , q = self .roll_index (i )
214+ return 1.0 / (2 * (2 * p + 1 ) * (p + q + 1 ))
215+
125216 def unroll_index (self , i ):
126217 n = i [0 ] + i [1 ]
127218 tri = 0.5 * n * (n + 1 )
@@ -180,9 +271,20 @@ def number_of_basis_functions(self):
180271
181272
182273class BasisFunctionGenerator3D (BasisFunctionGenerator ):
274+ """The Dubiner basis on the tetrahedron, ordered by degree."""
275+
276+ family = "dubiner"
277+ hierarchical = True
278+ orthogonal = True
279+
183280 def dim (self ):
184281 return 3
185282
283+ def norm_squared (self , i ):
284+ """The L2 norm of the i-th function squared."""
285+ p , q , r = self .roll_index (i )
286+ return 1.0 / (2 * (2 * p + 1 ) * (p + q + 1 ) * (2 * p + 2 * q + 2 * r + 3 ))
287+
186288 def unroll_index (self , i ):
187289 n = i [0 ] + i [1 ] + i [2 ]
188290 tet = (n * (n + 1 ) * (n + 2 )) / 6.0
@@ -263,3 +365,213 @@ def eval_diff_basis(self, x, i, k):
263365
264366 def number_of_basis_functions (self ):
265367 return self .order * (self .order + 1 ) * (self .order + 2 ) // 6
368+
369+
370+ ################################################################################
371+
372+
373+ class _Normalized :
374+ """The Dubiner functions divided by their L2 norm on the reference element,
375+ so that they are orthonormal there."""
376+
377+ family = "dubiner-normalized"
378+ orthonormal = True
379+
380+ def _scale (self , i ):
381+ return 1.0 / np .sqrt (super ().norm_squared (i ))
382+
383+ def norm_squared (self , i ):
384+ return 1.0
385+
386+ def eval_basis (self , x , i ):
387+ return super ().eval_basis (x , i ) * self ._scale (i )
388+
389+ def eval_diff_basis (self , x , i , k ):
390+ return super ().eval_diff_basis (x , i , k ) * self ._scale (i )
391+
392+
393+ class NormalizedDubinerGenerator1D (_Normalized , BasisFunctionGenerator1D ):
394+ pass
395+
396+
397+ class NormalizedDubinerGenerator2D (_Normalized , BasisFunctionGenerator2D ):
398+ pass
399+
400+
401+ class NormalizedDubinerGenerator3D (_Normalized , BasisFunctionGenerator3D ):
402+ pass
403+
404+
405+ ################################################################################
406+
407+
408+ def bernstein_indices (degree , dim ):
409+ """
410+ The multi-indices (a_1, ..., a_dim) of the Bernstein polynomials of a degree,
411+ in the order of the basis: a_dim varies slowest and a_1 fastest. The index of
412+ the vertex at the origin, a_0 = degree - a_1 - ... - a_dim, is implied.
413+
414+ With this order, raising one a_k by one (or lowering a_0) shifts a run of
415+ consecutive indices by a fixed offset.
416+ """
417+
418+ def at_most (total , count ):
419+ if count == 0 :
420+ return [()]
421+ return [
422+ rest + (last ,)
423+ for last in range (total + 1 )
424+ for rest in at_most (total - last , count - 1 )
425+ ]
426+
427+ return at_most (degree , dim )
428+
429+
430+ def barycentric (x , dim ):
431+ """The barycentric coordinates (l_0, ..., l_dim) of the points x on the
432+ reference element, l_k = x[k - 1] for k > 0."""
433+ if dim == 1 :
434+ coordinates = [np .asarray (x , dtype = float )]
435+ else :
436+ coordinates = [np .asarray (x [k ], dtype = float ) for k in range (dim )]
437+ return [1.0 - sum (coordinates )] + coordinates
438+
439+
440+ class BernsteinGenerator (BasisFunctionGenerator ):
441+ """
442+ The Bernstein-Bezier basis of degree order - 1 on the reference element,
443+
444+ B_a(x) = m! / (a_0! ... a_dim!) l_0^a_0 ... l_dim^a_dim,
445+
446+ with the barycentric coordinates l of x (see barycentric) and the multi-indices
447+ a of degree m in the order of bernstein_indices.
448+ """
449+
450+ family = "bernstein"
451+
452+ def __init__ (self , order , dim ):
453+ super ().__init__ (order )
454+ self ._dim = dim
455+ self ._indices = bernstein_indices (order - 1 , dim )
456+ self ._positions = {a : i for i , a in enumerate (self ._indices )}
457+ self ._lower = None
458+
459+ def dim (self ):
460+ return self ._dim
461+
462+ def number_of_basis_functions (self ):
463+ return len (self ._indices )
464+
465+ def multi_index (self , i ):
466+ """The full multi-index (a_0, ..., a_dim) of the i-th function."""
467+ a = self ._indices [i ]
468+ return (self .degree () - sum (a ),) + a
469+
470+ def index (self , a ):
471+ """The position of the function with the full multi-index a in the basis."""
472+ assert sum (a ) == self .degree ()
473+ return self ._positions [tuple (a [1 :])]
474+
475+ def eval_basis (self , x , i ):
476+ a = self .multi_index (i )
477+ coefficient = math .factorial (self .degree ())
478+ for ak in a :
479+ coefficient //= math .factorial (ak )
480+ value = coefficient
481+ for lk , ak in zip (barycentric (x , self ._dim ), a ):
482+ value = value * lk ** ak
483+ return value
484+
485+ def eval_diff_basis (self , x , i , k ):
486+ """d / d_x_k B_a = m (B_(a - e_(k+1)) - B_(a - e_0)), with the functions of
487+ degree m - 1 and a negative index standing for zero."""
488+ m = self .degree ()
489+ shape = np .shape (barycentric (x , self ._dim )[0 ])
490+ if m == 0 :
491+ return np .zeros (shape )
492+ a = self .multi_index (i )
493+ if self ._lower is None :
494+ self ._lower = BernsteinGenerator (self .order - 1 , self ._dim )
495+ lower = self ._lower
496+ value = np .zeros (shape )
497+ for component , sign in ((k + 1 , 1.0 ), (0 , - 1.0 )):
498+ if a [component ] > 0 :
499+ b = list (a )
500+ b [component ] -= 1
501+ value = value + sign * m * lower .eval_basis (x , lower .index (b ))
502+ return value
503+
504+
505+ class BernsteinGenerator1D (BernsteinGenerator ):
506+ def __init__ (self , order ):
507+ super ().__init__ (order , 1 )
508+
509+
510+ class BernsteinGenerator2D (BernsteinGenerator ):
511+ def __init__ (self , order ):
512+ super ().__init__ (order , 2 )
513+
514+
515+ class BernsteinGenerator3D (BernsteinGenerator ):
516+ def __init__ (self , order ):
517+ super ().__init__ (order , 3 )
518+
519+
520+ ################################################################################
521+
522+ #: The bases a generator can be asked for.
523+ FAMILIES = ("dubiner" , "dubiner-normalized" , "bernstein" )
524+
525+ _GENERATORS = {
526+ ("dubiner" , 1 ): BasisFunctionGenerator1D ,
527+ ("dubiner" , 2 ): BasisFunctionGenerator2D ,
528+ ("dubiner" , 3 ): BasisFunctionGenerator3D ,
529+ ("dubiner-normalized" , 1 ): NormalizedDubinerGenerator1D ,
530+ ("dubiner-normalized" , 2 ): NormalizedDubinerGenerator2D ,
531+ ("dubiner-normalized" , 3 ): NormalizedDubinerGenerator3D ,
532+ ("bernstein" , 1 ): BernsteinGenerator1D ,
533+ ("bernstein" , 2 ): BernsteinGenerator2D ,
534+ ("bernstein" , 3 ): BernsteinGenerator3D ,
535+ }
536+
537+
538+ def generator (family , dim , order ):
539+ """The generator of a basis family on the reference element of a dimension,
540+ for polynomials of degree order - 1."""
541+ if family not in FAMILIES :
542+ raise ValueError (f"unknown basis { family } ; known are { ', ' .join (FAMILIES )} " )
543+ if (family , dim ) not in _GENERATORS :
544+ raise ValueError (f"no basis on a reference element of dimension { dim } " )
545+ return _GENERATORS [(family , dim )](order )
546+
547+
548+ def describe (family ):
549+ """
550+ What a consumer of the matrices of a basis may rely on, as plain data: whether
551+ it is hierarchical, orthogonal and orthonormal, the structure of its mass
552+ matrices (identity, diagonal or dense), and the order of its functions.
553+ """
554+ basis = generator (family , 3 , 2 )
555+ if basis .orthonormal :
556+ mass = "identity"
557+ elif basis .orthogonal :
558+ mass = "diagonal"
559+ else :
560+ mass = "dense"
561+ if family == "bernstein" :
562+ ordering = (
563+ "multi-indices (a_1, ..., a_dim) of the degree, a_dim slowest and a_1 "
564+ "fastest, a_0 = degree - a_1 - ... - a_dim at the vertex at the origin"
565+ )
566+ else :
567+ ordering = (
568+ "by degree; within a degree as BasisFunctionGenerator2D/3D.unroll_index"
569+ )
570+ return {
571+ "family" : family ,
572+ "hierarchical" : basis .hierarchical ,
573+ "orthogonal" : basis .orthogonal ,
574+ "orthonormal" : basis .orthonormal ,
575+ "mass" : mass ,
576+ "ordering" : ordering ,
577+ }
0 commit comments