Algorithm Search⌘K

Data structureresearch

Truncated hierarchical B-spline

Also called THB-spline.

Giannelli, Juttler and Speleers's hierarchical spline whose coarse functions are truncated by finer ones, restoring partition of unity and reducing overlap.

Time
O(N p^2 + k L m p^2) worst · average · best
Space
O(k m) extra
Where
L = the number of levels; N = the number of tensor B-splines of all levels together; k = the number of selected basis functions; m = the number of tensor B-splines of the finest level; p = the degree
Properties
deterministiciterative
Origin
Carlotta Giannelli, Bert Jüttler, Hendrik Speleers, 2012

A truncated hierarchical B-spline basis takes the functions of the hierarchical B-spline basis and cuts each coarse function down. A function of level ℓ\ell is written in the B-splines of level ℓ+1\ell + 1, and the terms whose support lies in the next domain Ωℓ+1\Omega^{\ell+1} are dropped. This is repeated for each finer level. The truncated functions span the same space as the hierarchical basis and are linearly independent, but they are also nonnegative, they sum to 1, and their supports are smaller. Giannelli, Jüttler and Speleers introduced the basis in 2012, and it is the usual choice for adaptive isogeometric analysis with hierarchical splines.

In plain words

A hierarchical spline has a coarse grid of bumps, and finer grids of bumps in the regions that need detail. A coarse bump that reaches into a fine region overlaps the fine bumps there. Its shape in that region adds nothing new, because the fine bumps can already make it.

So cut it. Write the coarse bump as a sum of fine bumps, and throw away the fine bumps that sit inside the fine region. What remains is the coarse bump with a hole where the fine region is. Do this for each finer level in turn.

After the cuts, at each point only a few bumps are active, every bump is still nonnegative, and all the bumps add up to exactly 1. The set of shapes you can make does not change.

The abstract type

A truncated hierarchical B-spline space of degree pp with LL levels stores the same data as a hierarchical one: a tensor product knot vector per level and nested domains Ω0⊇Ω1⊇⋯⊇ΩL−1\Omega^0 \supseteq \Omega^1 \supseteq \cdots \supseteq \Omega^{L-1}, with ΩL=∅\Omega^L = \emptyset. The operations are:

  • BASIS: for each function β\beta of Kraft's hierarchical selection, its truncated form τ(β)\tau(\beta), as coefficients on the tensor B-splines of the finest level.
  • EVALUATE(c,x,y)(c, x, y): the value of a function given by coefficients on the finest level.
  • REFINE(ℓ,R)(\ell, R): add a region RR, a union of cells of level ℓ−1\ell - 1 inside Ωℓ−1\Omega^{\ell-1}, to Ωℓ\Omega^\ell.

The truncation of level kk acts on a spline ss of level k−1k - 1. Write s=∑γcγγs = \sum_\gamma c_\gamma \gamma in the B-splines γ\gamma of level kk. Then

trunc⁡ks=∑supp⁡γ⊈Ωkcγγ,\operatorname{trunc}^{k} s = \sum_{\operatorname{supp} \gamma \not\subseteq \Omega^{k}} c_\gamma \gamma,

and for β\beta of level ℓ\ell in the hierarchical basis HH,

τ(β)=trunc⁡L−1⋯trunc⁡ℓ+2trunc⁡ℓ+1β.\tau(\beta) = \operatorname{trunc}^{L-1} \cdots \operatorname{trunc}^{\ell+2} \operatorname{trunc}^{\ell+1} \beta.

Representation

The levels, cells and domains are those of the hierarchical B-spline page. Level ℓ\ell has, in each direction, the open uniform knot vector of degree pp on [0,n0][0, n_0] with spacing 2−ℓ2^{-\ell}, and a domain is a set of cells. The two-scale relation between levels ℓ\ell and ℓ+1\ell + 1 is stored as one sparse matrix per direction, computed by Boehm insertion of all the midpoints. A spline of level ℓ\ell is a sparse map from index pairs (i,j)(i, j) to coefficients; the lift to level ℓ+1\ell + 1 multiplies by the two matrices. Each truncated function is stored as a sparse map on the tensor B-splines of the finest level.

Operations

  1. BASIS(levels, Ω) ▷ Giannelli, Jüttler, Speleers
  2. 1for each (ℓ, β) in Kraft's selection H do
  3. 2c ← {β: 1} ▷ coefficients on level ℓ
  4. 3for k ← ℓ + 1 to L − 1 do
  5. 4c ← lift of c to level k ▷ two-scale relation
  6. 5c ← c without the γ with supp γ ⊆ Ω^k ▷ trunc^k
  7. 6τ(β) ← c written in the finest level
  1. EVALUATE(c, x, y)
  2. 1s ← 0
  3. 2for each finest index (i, j) with coefficient c_ij do
  4. 3s ← s + c_ij · N_i(x) · N_j(y) ▷ Cox-de Boor, finest knots
  5. 4return s

Kraft's selection in line L1 keeps the B-splines of level ℓ\ell whose support lies in Ωℓ\Omega^\ell but not in Ωℓ+1\Omega^{\ell+1}. REFINE adds the four children of each given cell to Ωℓ\Omega^\ell, checks that the cell is in Ωℓ−1\Omega^{\ell-1}, and runs BASIS again.

Example

Take p=2p = 2, n0=4n_0 = 4 and three levels, with Ω1=[0,2]2\Omega^1 = [0, 2]^2 and Ω2=[0,1]2\Omega^2 = [0, 1]^2, the example of the hierarchical B-spline page. Kraft's selection keeps 32+12+16=6032 + 12 + 16 = 60 functions, and the truncated basis has one function for each of them.

Look at the level 0 B-spline N20(x)N20(y)N^0_2(x) N^0_2(y), whose support is [0,3]2[0, 3]^2. The truncation of level 1 drops the terms of its level 1 expansion whose support lies in [0,2]2[0, 2]^2, so the function is zero near the corner and smaller in the rest of [0,2]2[0, 2]^2. At (12,12)(\tfrac12, \tfrac12) the plain function has the value 164\tfrac{1}{64} and the truncated function has the value 0. At (32,32)(\tfrac32, \tfrac32) the values are 916\tfrac{9}{16} and 2764\tfrac{27}{64}, and at (52,52)(\tfrac52, \tfrac52), outside Ω1\Omega^1, they are equal. In the finest level the plain function has 100 nonzero coefficients and the truncated one has 84.

The sum of all 60 truncated functions has every finest coefficient equal to 1, so it is the constant 1. The plain hierarchical functions sum to 12764\tfrac{127}{64} at (12,12)(\tfrac12, \tfrac12). At (34,34)(\tfrac34, \tfrac34), 14 of the hierarchical functions are nonzero, but only 9 of the truncated ones.

Correctness

The truncation of level kk is linear, and it only drops terms of an expansion whose coefficients are nonnegative, so every τ(β)\tau(\beta) has nonnegative coefficients in the finest level and is nonnegative. Partition of unity comes from an induction over the levels. At level kk, the constant 1 is the sum of the truncated functions of the levels below kk plus the B-splines of level kk that lie in Ωk\Omega^k. Lifting to level k+1k + 1 and truncating replaces the B-splines that lie in Ωk+1\Omega^{k+1} by their own children, and the coefficients of 1 in every level are all 1. The same induction shows more: a spline of level 0 has the same coefficients on the truncated basis as on the B-splines of each level, which is the preservation of coefficients. Each τ(β)\tau(\beta) differs from β\beta by functions of finer levels that lie in the finer domains, so the span equals the hierarchical span, and the triangular form of this relation gives linear independence. The proofs are in the correctness proof.

Proof: The truncated basis is nonnegative, a partition of unity, preserves coefficients, spans the hierarchical space and is linearly independentfull

We use the notation of the page. Bk\mathcal{B}^k is the set of tensor B-splines of level kk, and "γ⊆Ω\gamma \subseteq \Omega" means that every support cell of γ\gamma lies in Ω\Omega. The domains satisfy Ω0=[0,n0]2\Omega^0 = [0, n_0]^2, Ωk+1⊆Ωk\Omega^{k+1} \subseteq \Omega^k, each Ωk\Omega^k is a union of cells of level k−1k - 1, and ΩL=∅\Omega^L = \emptyset. HℓH^\ell is Kraft's selection of level ℓ\ell: the β∈Bℓ\beta \in \mathcal{B}^\ell with β⊆Ωℓ\beta \subseteq \Omega^\ell and β⊈Ωℓ+1\beta \not\subseteq \Omega^{\ell+1}. SkS^k is the span of Bk\mathcal{B}^k, and S0⊆S1⊆⋯S^0 \subseteq S^1 \subseteq \cdots. For s∈Sks \in S^k, cγk(s)c^k_\gamma(s) is its coefficient on γ∈Bk\gamma \in \mathcal{B}^k; these coefficients are unique because Bk\mathcal{B}^k is a basis of SkS^k.

We use two facts from the hierarchical B-spline proof: (two-scale) each β∈Bk\beta \in \mathcal{B}^k is ∑γrβγγ\sum_\gamma r_{\beta\gamma} \gamma over γ∈Bk+1\gamma \in \mathcal{B}^{k+1} with rβγ≥0r_{\beta\gamma} \ge 0, and rβγ≠0r_{\beta\gamma} \ne 0 only if the support of γ\gamma lies in that of β\beta; and (span) every β∈Bℓ\beta \in \mathcal{B}^\ell with β⊆Ωℓ\beta \subseteq \Omega^\ell lies in the span of H=⋃ℓHℓH = \bigcup_\ell H^\ell, which is linearly independent.

For s∈Sk−1s \in S^{k-1}, trunc⁡ks=∑γ∈Bk,γ⊈Ωkcγk(s)γ\operatorname{trunc}^k s = \sum_{\gamma \in \mathcal{B}^k, \gamma \not\subseteq \Omega^k} c^k_\gamma(s) \gamma. This map is linear. Lines L2 to L5 compute τ(β)=trunc⁡L−1⋯trunc⁡ℓ+1β\tau(\beta) = \operatorname{trunc}^{L-1} \cdots \operatorname{trunc}^{\ell+1} \beta for β∈Hℓ\beta \in H^\ell, and line L6 writes it in the finest level by the two-scale relation; an empty product means τ(β)=β\tau(\beta) = \beta.

Lemma 1 (nonnegativity). For β∈Hℓ\beta \in H^\ell and each k≥ℓk \ge \ell, the coefficients of the partial truncation trunc⁡k⋯trunc⁡ℓ+1β\operatorname{trunc}^{k} \cdots \operatorname{trunc}^{\ell+1} \beta on Bk\mathcal{B}^k are nonnegative, and so are the coefficients of τ(β)\tau(\beta) on the finest level. Hence τ(β)≥0\tau(\beta) \ge 0.

Proof. At k=ℓk = \ell the coefficients are a unit vector. A lift multiplies nonnegative coefficients by the nonnegative two-scale coefficients and adds, and the truncation sets some coefficients to zero. So every step keeps the coefficients nonnegative, and so does the final lift in line L6. B-splines are nonnegative, so τ(β)≥0\tau(\beta) \ge 0. □\square

Theorem 1 (preservation of coefficients). For every s∈S0s \in S^0,

s=∑ℓ=0L−1∑β∈Hℓcβℓ(s) τ(β).s = \sum_{\ell = 0}^{L-1} \sum_{\beta \in H^\ell} c^\ell_\beta(s)\, \tau(\beta).

Proof. For 0≤k≤L−10 \le k \le L - 1 let

gk=∑ℓ<k∑β∈Hℓcβℓ(s) trunc⁡k⋯trunc⁡ℓ+1β.g_k = \sum_{\ell < k} \sum_{\beta \in H^\ell} c^\ell_\beta(s)\, \operatorname{trunc}^{k} \cdots \operatorname{trunc}^{\ell+1} \beta.

We prove by induction on kk the two claims (a) gk=∑γ∈Bk,γ⊈Ωkcγk(s)γg_k = \sum_{\gamma \in \mathcal{B}^k, \gamma \not\subseteq \Omega^k} c^k_\gamma(s) \gamma and (b) s=gk+∑γ∈Bk,γ⊆Ωkcγk(s)γs = g_k + \sum_{\gamma \in \mathcal{B}^k, \gamma \subseteq \Omega^k} c^k_\gamma(s) \gamma. Claim (b) follows from (a) because s=∑γ∈Bkcγk(s)γs = \sum_{\gamma \in \mathcal{B}^k} c^k_\gamma(s) \gamma.

For k=0k = 0, g0=0g_0 = 0 and every γ∈B0\gamma \in \mathcal{B}^0 lies in Ω0\Omega^0, so (a) holds.

Assume (a) and (b) for some k<L−1k < L - 1. Split the B-splines of level kk in Ωk\Omega^k into HkH^k and Dk={γ∈Bk:γ⊆Ωk+1}D^k = \{\gamma \in \mathcal{B}^k : \gamma \subseteq \Omega^{k+1}\}. Then (b) reads s=u+vs = u + v with

u=gk+∑β∈Hkcβk(s)β,v=∑γ∈Dkcγk(s)γ.u = g_k + \sum_{\beta \in H^k} c^k_\beta(s) \beta, \qquad v = \sum_{\gamma \in D^k} c^k_\gamma(s) \gamma.

By the two-scale fact, vv is a combination of B-splines η∈Bk+1\eta \in \mathcal{B}^{k+1} whose supports lie in the supports of members of DkD^k, so in Ωk+1\Omega^{k+1}. Hence for every η∈Bk+1\eta \in \mathcal{B}^{k+1} with η⊈Ωk+1\eta \not\subseteq \Omega^{k+1}, cηk+1(v)=0c^{k+1}_\eta(v) = 0 and cηk+1(u)=cηk+1(s)c^{k+1}_\eta(u) = c^{k+1}_\eta(s) by linearity and uniqueness of coefficients. So

trunc⁡k+1u=∑η⊈Ωk+1cηk+1(s) η.\operatorname{trunc}^{k+1} u = \sum_{\eta \not\subseteq \Omega^{k+1}} c^{k+1}_\eta(s)\, \eta.

By linearity of trunc⁡k+1\operatorname{trunc}^{k+1}, trunc⁡k+1u=gk+1\operatorname{trunc}^{k+1} u = g_{k+1}, since trunc⁡k+1\operatorname{trunc}^{k+1} applied to the terms of gkg_k adds one more truncation and trunc⁡k+1β\operatorname{trunc}^{k+1} \beta is the partial truncation of β∈Hk\beta \in H^k. This is (a) for k+1k + 1.

At k=L−1k = L - 1, ΩL=∅\Omega^L = \emptyset, so no γ∈BL−1\gamma \in \mathcal{B}^{L-1} lies in ΩL\Omega^L and the γ⊆ΩL−1\gamma \subseteq \Omega^{L-1} are exactly HL−1H^{L-1}. For these, τ(γ)=γ\tau(\gamma) = \gamma. Claim (b) is then

s=gL−1+∑β∈HL−1cβL−1(s)β=∑ℓ∑β∈Hℓcβℓ(s) τ(β).□s = g_{L-1} + \sum_{\beta \in H^{L-1}} c^{L-1}_\beta(s) \beta = \sum_{\ell} \sum_{\beta \in H^\ell} c^\ell_\beta(s)\, \tau(\beta). \qquad \square

Corollary 1 (partition of unity). ∑(ℓ,β)∈Hτ(β)=1\sum_{(\ell, \beta) \in H} \tau(\beta) = 1.

Proof. The constant 1 lies in S0S^0, and by the partition of unity of B-splines on an open knot vector, 1=∑γ∈Bkγ1 = \sum_{\gamma \in \mathcal{B}^k} \gamma in every level, so cβℓ(1)=1c^\ell_\beta(1) = 1 for all β\beta. Apply Theorem 1. □\square

Lemma 2 (triangular form). For β∈Hℓ\beta \in H^\ell, τ(β)−β\tau(\beta) - \beta is a combination of B-splines γ\gamma of levels k>ℓk > \ell with γ⊆Ωk\gamma \subseteq \Omega^k.

Proof. Write tℓ=βt_\ell = \beta and tk=trunc⁡ktk−1t_k = \operatorname{trunc}^k t_{k-1}. Then tk−1−tk=∑γ∈Bk,γ⊆Ωkcγk(tk−1)γt_{k-1} - t_k = \sum_{\gamma \in \mathcal{B}^k, \gamma \subseteq \Omega^k} c^k_\gamma(t_{k-1}) \gamma, and τ(β)−β=−∑k=ℓ+1L−1(tk−1−tk)\tau(\beta) - \beta = -\sum_{k = \ell+1}^{L-1} (t_{k-1} - t_k). □\square

Theorem 2 (same span, linear independence). The functions τ(β)\tau(\beta), (ℓ,β)∈H(\ell, \beta) \in H, are linearly independent and span the same space as HH.

Proof. By Lemma 2 and the span fact, each γ\gamma of level kk with γ⊆Ωk\gamma \subseteq \Omega^k lies in the span of Hk∪Hk+1∪⋯H^k \cup H^{k+1} \cup \cdots, so τ(β)−β\tau(\beta) - \beta lies in the span of ⋃k>ℓHk\bigcup_{k > \ell} H^k for β∈Hℓ\beta \in H^\ell. Order HH by level from the finest down. In the basis HH of span⁡H\operatorname{span} H, the matrix that maps HH to {τ(β)}\{\tau(\beta)\} has ones on the diagonal and nonzero entries off the diagonal only from a level to finer levels, so it is unit triangular and invertible. Hence {τ(β)}\{\tau(\beta)\} is a basis of span⁡H\operatorname{span} H. □\square

Corollary 2 (nested spaces). If Ω^ℓ⊇Ωℓ\hat\Omega^\ell \supseteq \Omega^\ell for every level, the truncated basis for Ω^\hat\Omega spans a space that contains the span of the truncated basis for Ω\Omega.

Proof. By Theorem 2 both spans equal the hierarchical spans, which are nested by the nesting theorem of the hierarchical B-spline proof. □\square

Correctness of the operations. Line L1 is Kraft's selection. Lines L2 to L5 compute trunc⁡k⋯trunc⁡ℓ+1β\operatorname{trunc}^{k} \cdots \operatorname{trunc}^{\ell+1} \beta for k=ℓ+1,…,L−1k = \ell + 1, \ldots, L - 1: line L4 lifts by the two-scale matrices, which give the unique coefficients on Bk\mathcal{B}^k, and line L5 drops exactly the terms with γ⊆Ωk\gamma \subseteq \Omega^k. Line L6 lifts the result to the finest level without change of the function. Lines L7 to L10 sum the coefficients times the finest tensor B-splines, computed by the Cox-de Boor recursion. So BASIS returns τ(β)\tau(\beta) for each β∈H\beta \in H, and Lemma 1, Theorem 1, Corollary 1, Theorem 2 and Corollary 2 hold for its output. The tests check each of them exactly with fractions. ■\blacksquare

Complexity

Let NN be the number of tensor B-splines of all levels together, kk the number of selected functions, LL the number of levels and mm the number of tensor B-splines of the finest level. Kraft's selection takes O(Np2)O(N p^2) time. Each lift of a sparse map with at most mm entries spreads each entry to at most (p+2)2(p + 2)^2 children, and the truncation test checks (p+1)2(p + 1)^2 cells per term, so one function costs O(Lmp2)O(L m p^2) and BASIS costs O(Np2+kLmp2)O(N p^2 + k L m p^2) in the worst case. In practice the maps stay local, of size O(4L−ℓp2)O(4^{L - \ell} p^2) for a function of level ℓ\ell. Storing all truncated functions on the finest level takes O(km)O(k m) space. EVALUATE costs O(p2)O(p^2) per stored coefficient, or O(p2)O(p^2) per point with an index of the coefficients by cell.

Variants

  • Hierarchical basis without truncation. The hierarchical B-spline basis spans the same space but is not a partition of unity and its supports overlap more.
  • Truncation of each level only. Storing τ(β)\tau(\beta) level by level, as β\beta minus the dropped parts, avoids the finest level and keeps the maps small. The test against a level by level reference evaluates this form.
  • Admissible meshes. For error estimates and the condition number in analysis, the domains are often restricted so that only a bounded number of levels have truncated functions that are nonzero on a cell.
  • Other nested spaces. The construction needs only nested spline spaces whose bases have nonnegative two-scale coefficients and partition of unity, so it extends to nonuniform knots, to different refinements per direction, and to some other spline families.

When to use it

Use truncated hierarchical B-splines for adaptive isogeometric analysis, for local fitting, and for any method that needs a partition of unity with local refinement on a tensor product structure, for example a rational form or the convex hull property of a control net. The fewer overlaps give sparser stiffness matrices than the plain hierarchical basis. For local refinement that is not dyadic or not aligned to levels, compare T-splines, LR B-splines and PHT-splines.

Pitfalls

  • Truncating against the wrong domain. The truncation of level kk drops the B-splines whose support lies in Ωk\Omega^k, not those that merely meet it. Dropping more breaks partition of unity and the span.
  • Skipping intermediate levels. τ(β)\tau(\beta) must be truncated at each level from ℓ+1\ell + 1 to L−1L - 1 in order. Lifting straight to the finest level and truncating once against ΩL−1\Omega^{L-1} gives a different function.
  • Nonnegative two-scale coefficients. Nonnegativity of the truncated functions needs nonnegative two-scale coefficients, which hold for B-splines but not for every refinable basis.
  • Updating after refinement. A REFINE of level ℓ\ell changes the truncated form of functions of all coarser levels, not only those of level ℓ−1\ell - 1.

Implementations

The Python module builds the open uniform knot vectors of the levels, the two-scale matrices by Boehm insertion of all midpoints, the domains as sets of cells, Kraft's selection, the truncation of lines L1 to L6, EVALUATE by Cox-de Boor on the finest knots, and an exact sparse rank. The tests check that one level gives the tensor B-splines, the counts of the example, that the truncated functions sum to 1 exactly in coefficients and at points, that a random spline of level 0 keeps its coefficients, that the coefficients are positive and lie inside those of the plain functions, that the span equals the hierarchical span and the functions are independent, that refinement gives nested spaces, the values against a level by level reference, and the truncated function of the example.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

truncated_hierarchical_b_spline.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/truncated-hierarchical-b-spline/. The authors are listed in prov/EY36RH.jsonl.

"""Bivariate truncated hierarchical B-splines (THB-splines), in exact arithmetic.

The levels and domains are those of the hierarchical-b-spline page. Level l
has the open uniform knot vector of degree p on [0, n0] with spacing 2^-l in
each direction. Omega^0 = [0, n0]^2, Omega^l is a union of cells of level
l - 1 inside Omega^(l-1), and Omega^L is empty. Kraft's rule selects the
B-splines of level l that lie in Omega^l but not in Omega^(l+1).

The truncated function of a selected B-spline of level l is found level by
level: write it in the B-splines of level k = l + 1, ..., L - 1 and drop the
terms whose support lies in Omega^k. The result is kept as coefficients on
the tensor B-splines of the finest level.
"""

from fractions import Fraction


def open_knots(n0, p, level):
    k = 2**level
    return [Fraction(0)] * p + [Fraction(a, k) for a in range(n0 * k + 1)] + [Fraction(n0)] * p


def insert_knot(knots, coeffs, u, p):
    """Boehm's rule on a whole coefficient vector: the same spline with u added."""
    k = max(i for i in range(len(knots) - 1) if knots[i] <= u < knots[i + 1])
    new = []
    for i in range(len(coeffs) + 1):
        if i <= k - p:
            new.append(coeffs[i])
        elif i > k:
            new.append(coeffs[i - 1])
        else:
            a = (u - knots[i]) / (knots[i + p] - knots[i])
            new.append(a * coeffs[i] + (1 - a) * coeffs[i - 1])
    return sorted(knots + [u]), new


def two_scale(n0, p, level):
    """R[i] = {j: c}: B-spline i of the level is sum_j c N_j of the next level."""
    coarse = open_knots(n0, p, level)
    new = sorted(set(open_knots(n0, p, level + 1)) - set(coarse))
    R = []
    for i in range(len(coarse) - p - 1):
        knots, c = list(coarse), [Fraction(int(r == i)) for r in range(len(coarse) - p - 1)]
        for u in new:
            knots, c = insert_knot(knots, c, u, p)
        R.append({j: x for j, x in enumerate(c) if x})
    return R


def bspline(knots, i, p, x):
    """N_i of degree p on the knots at x, by Cox-de Boor; closed at the right end."""
    last = knots[-1]
    vals = [Fraction(int(knots[k] <= x < knots[k + 1] or (x == last and knots[k] < knots[k + 1] == last))) for k in range(i, i + p + 1)]
    for d in range(1, p + 1):
        vals = [
            ((x - knots[i + k]) / (knots[i + k + d] - knots[i + k]) * vals[k] if knots[i + k + d] != knots[i + k] else 0)
            + ((knots[i + k + d + 1] - x) / (knots[i + k + d + 1] - knots[i + k + 1]) * vals[k + 1] if knots[i + k + d + 1] != knots[i + k + 1] else 0)
            for k in range(len(vals) - 1)
        ]
    return vals[0]


class THB:
    def __init__(self, n0, p, levels):
        self.n0, self.p, self.L = n0, p, levels
        self.knots = [open_knots(n0, p, l) for l in range(levels)]
        self.R = [two_scale(n0, p, l) for l in range(levels - 1)]
        self.omega = [{(a, b) for a in range(n0) for b in range(n0)}] + [set() for _ in range(levels - 1)]

    def size(self, level):
        return self.n0 * 2**level + self.p

    def cells(self, level, i):
        return range(max(i - self.p, 0), min(i, self.n0 * 2**level - 1) + 1)

    def inside(self, level, B, m):
        """Does the support of the level-`level` B-spline B lie in Omega^m (m >= level)?"""
        if m >= self.L:
            return False
        r = 2 ** (m - level)
        return all(
            (r * a + x, r * b + y) in self.omega[m]
            for a in self.cells(level, B[0])
            for b in self.cells(level, B[1])
            for x in range(r)
            for y in range(r)
        )

    def refine(self, level, coarse_cells):
        """Add to Omega^level the given cells of level - 1, which must lie in Omega^(level-1)."""
        for a, b in coarse_cells:
            if (a, b) not in self.omega[level - 1]:
                raise ValueError("Omega^l must lie inside Omega^(l-1)")
            self.omega[level] |= {(2 * a + x, 2 * b + y) for x in (0, 1) for y in (0, 1)}

    def kraft(self):
        return [
            (l, (i, j))
            for l in range(self.L)
            for i in range(self.size(l))
            for j in range(self.size(l))
            if self.inside(l, (i, j), l) and not self.inside(l, (i, j), l + 1)
        ]

    def lift(self, c, level):
        """Coefficients on level `level` B-splines to coefficients on level `level` + 1."""
        out = {}
        R = self.R[level]
        for (i, j), x in c.items():
            for a, u in R[i].items():
                for b, v in R[j].items():
                    out[(a, b)] = out.get((a, b), Fraction(0)) + x * u * v
        return out

    def to_finest(self, c, level):
        for k in range(level, self.L - 1):
            c = self.lift(c, k)
        return c

    def basis(self):
        """{(level, (i, j)): truncated function as finest-level coefficients}."""
        out = {}
        for l, B in self.kraft():  # @line L1
            c = {B: Fraction(1)}  # @line L2
            for k in range(l + 1, self.L):  # @line L3
                c = self.lift(c, k - 1)  # @line L4
                c = {g: x for g, x in c.items() if not self.inside(k, g, k)}  # @line L5
            out[(l, B)] = self.to_finest(c, self.L - 1) if c else {}  # @line L6
        return out

    def evaluate(self, coeffs, x, y):
        """sum over {(i, j): c} of c times the finest-level tensor B-spline at (x, y)."""
        kn, p = self.knots[-1], self.p
        total = Fraction(0)  # @line L7
        for (i, j), c in coeffs.items():  # @line L8
            total += c * bspline(kn, i, p, x) * bspline(kn, j, p, y)  # @line L9
        return total  # @line L10

    def plain(self, level, B):
        """The untruncated B-spline in the finest level, for comparison."""
        return self.to_finest({B: Fraction(1)}, level)


def rank(vectors):
    """Exact rank of sparse vectors given as dicts, by incremental elimination."""
    pivots = {}
    for v in vectors:
        v = {k: x for k, x in v.items() if x}
        while v:
            k = min(v)
            if k not in pivots:
                pivots[k] = v
                break
            p = pivots[k]
            f = v[k] / p[k]
            for kk, x in p.items():
                v[kk] = v.get(kk, Fraction(0)) - f * x
            v = {kk: x for kk, x in v.items() if x}
    return len(pivots)
test_truncated_hierarchical_b_spline.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/truncated-hierarchical-b-spline/. The authors are listed in prov/EY36RH.jsonl.

import random
from fractions import Fraction as F

from truncated_hierarchical_b_spline import THB, bspline, rank


def example(p=2):
    """Three levels on [0, 4]^2: Omega^1 = [0, 2]^2 and Omega^2 = [0, 1]^2."""
    T = THB(4, p, 3)
    T.refine(1, [(a, b) for a in range(2) for b in range(2)])
    T.refine(2, [(a, b) for a in range(2) for b in range(2)])
    return T


def random_thb(rng, p):
    T = THB(4, p, 3)
    T.refine(1, rng.sample(sorted(T.omega[0]), 7))
    T.refine(2, rng.sample(sorted(T.omega[1]), 9))
    return T


def pts(rng, k):
    return [(F(rng.randint(0, 400), 100), F(rng.randint(0, 400), 100)) for _ in range(k)]


def cases():
    rng = random.Random(5)
    yield example(2)
    yield example(3)
    for p in (2, 3):
        for _ in range(2):
            yield random_thb(rng, p)


def reference_value(T, l, B, x, y):
    """Truncate by the definition and evaluate each level with its own knots.

    The function is B minus, for each finer level k, the dropped terms of its
    expansion in level k, each evaluated by Cox-de Boor on the knots of level k.
    """
    def ev(level, c):
        kn = T.knots[level]
        return sum(v * bspline(kn, i, T.p, x) * bspline(kn, j, T.p, y) for (i, j), v in c.items())

    value = ev(l, {B: F(1)})
    c = {B: F(1)}
    for k in range(l + 1, T.L):
        c = T.lift(c, k - 1)
        dropped = {g: v for g, v in c.items() if T.inside(k, g, k)}
        value -= ev(k, dropped)
        c = {g: v for g, v in c.items() if g not in dropped}
    return value


def test_one_level_gives_the_tensor_b_splines():
    T = THB(3, 2, 1)
    basis = T.basis()
    assert len(basis) == 25
    for (l, B), c in basis.items():
        assert c == {B: 1}


def test_example_counts_match_kraft():
    T = example()
    levels = [sum(1 for l, _ in T.basis() if l == k) for k in range(3)]
    assert levels == [32, 12, 16]


def test_partition_of_unity_exactly():
    rng = random.Random(6)
    for T in cases():
        total = {}
        for c in T.basis().values():
            for g, v in c.items():
                total[g] = total.get(g, F(0)) + v
        n = T.size(T.L - 1)
        assert total == {(a, b): F(1) for a in range(n) for b in range(n)}
        for x, y in pts(rng, 3):
            assert T.evaluate(total, x, y) == 1


def test_coefficients_of_a_level_0_spline_are_preserved():
    rng = random.Random(9)
    for T in cases():
        n = T.size(0)
        s0 = {(i, j): F(rng.randint(-9, 9)) for i in range(n) for j in range(n)}
        level = [s0]
        for k in range(T.L - 1):
            level.append(T.lift(level[-1], k))
        total = {}
        for (l, B), c in T.basis().items():
            w = level[l].get(B, F(0))
            for g, v in c.items():
                total[g] = total.get(g, F(0)) + w * v
        total = {g: v for g, v in total.items() if v}
        assert total == {g: v for g, v in level[-1].items() if v}


def test_coefficients_are_nonnegative_and_supports_shrink():
    smaller = 0
    for T in cases():
        for (l, B), c in T.basis().items():
            plain = T.plain(l, B)
            assert all(v > 0 for v in c.values())
            assert set(c) <= set(plain)
            assert all(c[g] <= plain[g] for g in c)
            smaller += set(c) != set(plain)
    assert smaller > 0


def test_same_span_as_the_hierarchical_basis_and_independent():
    for T in cases():
        basis = T.basis()
        thb = [c for c in basis.values()]
        hb = [T.plain(l, B) for l, B in basis]
        r = rank(thb)
        assert r == len(basis)
        assert rank(thb + hb) == r


def test_refinement_gives_nested_spaces():
    rng = random.Random(7)
    T = random_thb(rng, 2)
    old = list(T.basis().values())
    for _ in range(3):
        level = rng.choice([1, 2])
        T.refine(level, rng.sample(sorted(T.omega[level - 1]), 2))
        new = list(T.basis().values())
        assert rank(new) == len(new)
        assert rank(new + old) == len(new)
        old = new


def test_values_against_level_by_level_reference():
    rng = random.Random(8)
    T = example()
    basis = T.basis()
    keys = sorted(basis)
    for l, B in rng.sample(keys, 12) + [(0, (2, 2)), (1, (3, 3))]:
        for x, y in pts(rng, 3) + [(F(1, 2), F(1, 2)), (F(3, 2), F(5, 4))]:
            assert T.evaluate(basis[(l, B)], x, y) == reference_value(T, l, B, x, y)


def test_truncated_function_in_the_example():
    T = example()
    basis = T.basis()
    c = basis[(0, (2, 2))]
    # the level 0 B-spline with support [0, 3]^2 loses its part inside [0, 2]^2
    assert T.evaluate(c, F(1, 2), F(1, 2)) == 0
    assert T.evaluate(c, F(5, 2), F(5, 2)) == T.evaluate(T.plain(0, (2, 2)), F(5, 2), F(5, 2))
    assert T.evaluate(c, F(3, 2), F(3, 2)) < T.evaluate(T.plain(0, (2, 2)), F(3, 2), F(3, 2))

History

Forsey and Bartels introduced hierarchical B-spline refinement in 1988, Kraft gave the selection rule for linear independence in 1997, and Vuong, Giannelli, Jüttler and Simeon used the hierarchical basis for adaptive isogeometric analysis in 2011. Giannelli, Jüttler and Speleers defined the truncation in 2012 to restore partition of unity and reduce overlap. In 2014 they proved that the truncated basis is strongly stable, with constants that do not depend on the number of levels.

References

  1. Carlotta Giannelli, Bert Jüttler and Hendrik Speleers, THB-splines, the truncated basis for hierarchical splines, Computer Aided Geometric Design 29(7) (2012), 485 to 498, the truncation operator, the definition of the truncated basis, and the proofs of nonnegativity, partition of unity, linear independence, equal span and nested spaces (general locator)
  2. Carlotta Giannelli, Bert Jüttler and Hendrik Speleers, Strongly stable bases for adaptively refined multilevel spline spaces, Advances in Computational Mathematics 40(2) (2014), 459 to 490, the strong stability of the truncated basis and the preservation of coefficients (general locator)
  3. A.-V. Vuong, C. Giannelli, B. Jüttler and B. Simeon, A hierarchical approach to adaptive local refinement in isogeometric analysis, Computer Methods in Applied Mechanics and Engineering 200(49-52) (2011), 3554 to 3567, the hierarchical basis by Kraft's rule that the truncation starts from, and its use in adaptive isogeometric analysis (general locator)
  4. Rainer Kraft, Adaptive and linearly independent multilevel B-splines, in A. Le Méhauté, C. Rabut and L. L. Schumaker (editors), Surface Fitting and Multiresolution Methods, Vanderbilt University Press, 1997, the selection of B-splines of each level by the nested domains (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/EY36RH/text.yaml