Algorithm Search⌘K

Data structureresearch

Locally refined B-spline

Also called LR B-spline, LR-spline.

Dokken, Lyche and Pettersen's splines refined by inserting mesh lines that split the supports of B-splines one at a time, keeping a tensor-product flavour.

Time
O((b + s) m p) worst · averageO(b m p) best
Space
O(b + s) extra
Where
b = the number of LR B-splines before the insertion; m = the number of mesh segments; p = the larger of the two degrees; s = the number of splits
Properties
deterministiciterative
Origin
Tor Dokken, Tom Lyche, Kjell Fredrik Pettersen, 2013

LR B-splines are a way to refine a tensor product B-spline surface locally. You insert one axis-parallel mesh segment at a time. Every B-spline whose support the segment crosses from one side to the other is split in two by the insertion of one knot into its local knot vector, and the split repeats until no mesh line crosses a support without being one of its knots. Each B-spline carries a positive weight, so that the weighted B-splines still sum to 1, and the surface does not change. Dokken, Lyche and Pettersen introduced them in 2013. Each function stays a tensor product B-spline with its own local knots.

In plain words

Think of a surface made of smooth tiles, one per bump function, laid out on a grid. To add detail in one place, draw a new line on the grid, but only as long as you need.

Each bump that the new line cuts fully from one edge to the other is replaced by two narrower bumps. A bump that the line only touches or reaches into stays as it is. The two new bumps may be cut by lines that were already there, so you keep cutting until no line cuts any bump fully.

Each bump has a weight, and when it is cut, the weight is shared between the two pieces. Two pieces of different bumps can turn out to be the same bump; then you add their weights. The shape of the surface never changes, and the weighted bumps always add up to 1.

The abstract type

An LR spline of bidegree (p,q)(p, q) is a set of triples (B,γ,c)(B, \gamma, c). BB is a tensor product B-spline given by its local knot vectors x0≤⋯≤xp+1x_0 \le \cdots \le x_{p+1} and y0≤⋯≤yq+1y_0 \le \cdots \le y_{q+1}, γ>0\gamma > 0 is its weight, and cc is its coefficient, a number or a control point. The spline is

s(x,y)=∑γ c B(x,y),∑γ B(x,y)=1.s(x, y) = \sum \gamma\, c\, B(x, y), \qquad \sum \gamma\, B(x, y) = 1.

The mesh is a set of axis-parallel segments. A segment at x=ax = a traverses BB if x0<a<xp+1x_0 < a < x_{p+1}, aa is not one of the xix_i, and the segment covers [y0,yq+1][y_0, y_{q+1}]; the same with the roles of xx and yy swapped for a horizontal segment. The operations are:

  • INSERT(σ)(\sigma): add a segment σ\sigma to the mesh and split the B-splines until no B-spline is traversed. The segment must traverse at least one B-spline.
  • EVALUATE(x,y)(x, y): the value s(x,y)s(x, y), or ∑γB(x,y)\sum \gamma B(x, y).

Representation

The B-splines are a hash map from the pair of local knot vectors to the pair (γ,c)(\gamma, c). The mesh is a hash map from a direction and a value to a sorted list of disjoint intervals; a new segment is merged with the collinear segments that it overlaps or touches. All mesh lines in this implementation have multiplicity one. The start is a tensor product spline on open knot vectors: every tensor B-spline with weight 1, and every knot line over the whole domain.

The split uses the one-knot rule for a single B-spline. Insert aa with x0<a<xp+1x_0 < a < x_{p+1} into the local knots x0,…,xp+1x_0, \ldots, x_{p+1}. Let τ\tau be the p+3p + 3 sorted knots, B1B_1 the B-spline on τ0,…,τp+1\tau_0, \ldots, \tau_{p+1} and B2B_2 the one on τ1,…,τp+2\tau_1, \ldots, \tau_{p+2}. Then

B=α1B1+α2B2,α1=min⁡(1,a−x0xp−x0),α2=min⁡(1,xp+1−axp+1−x1),B = \alpha_1 B_1 + \alpha_2 B_2, \qquad \alpha_1 = \min\Bigl(1, \frac{a - x_0}{x_p - x_0}\Bigr), \quad \alpha_2 = \min\Bigl(1, \frac{x_{p+1} - a}{x_{p+1} - x_1}\Bigr),

with α1=1\alpha_1 = 1 if xp=x0x_p = x_0 and α2=1\alpha_2 = 1 if xp+1=x1x_{p+1} = x_1. This is Boehm's rule applied to the unit coefficient vector of one B-spline.

Operations

  1. INSERT(σ)
  2. 1add σ to the mesh, merged with the collinear segments it touches
  3. 2Q ← all LR B-splines
  4. 3while Q is not empty do take B from Q
  5. 4μ ← a mesh line that traverses B; if there is none, go to L3
  6. 5remove (B, γ, c) from the set
  7. 6(B₁, α₁), (B₂, α₂) ← insert the value of μ into the local knots of B
  8. 7for i ← 1, 2 do
  9. 8merge (Bᵢ, γ αᵢ, c) into the set
  10. 9add Bᵢ to Q

Line L8 adds (Bi,γαi,c)(B_i, \gamma\alpha_i, c) if BiB_i is new. If BiB_i is already present as (Bi,γ′,c′)(B_i, \gamma', c'), it becomes (Bi,γ′+γαi,(γ′c′+γαic)/(γ′+γαi))(B_i, \gamma' + \gamma\alpha_i, (\gamma' c' + \gamma\alpha_i c) / (\gamma' + \gamma\alpha_i)). INSERT refuses a segment that splits no B-spline, and then leaves the mesh and the set unchanged. EVALUATE sums γcB(x,y)\gamma c B(x, y) with each factor of BB computed by the Cox-de Boor recursion on its local knots.

Example

Take biquadratic B-splines on the open knot vector 0,0,0,1,2,3,4,4,40, 0, 0, 1, 2, 3, 4, 4, 4 in both directions, 36 tensor B-splines with weight 1. Insert the vertical segment x=32x = \tfrac32 for 0≤y≤30 \le y \le 3. It traverses the 9 B-splines with xx knots (0,0,1,2)(0, 0, 1, 2), (0,1,2,3)(0, 1, 2, 3) or (1,2,3,4)(1, 2, 3, 4) and support in yy inside [0,3][0, 3]. Each splits into two; for example (0,1,2,3)(0, 1, 2, 3) gives 34(0,1,32,2)+34(1,32,2,3)\tfrac34 (0, 1, \tfrac32, 2) + \tfrac34 (1, \tfrac32, 2, 3). The pieces of neighbours meet: (0,1,32,2)(0, 1, \tfrac32, 2) also gets 14\tfrac14 from (0,0,1,2)(0, 0, 1, 2), and its weight is 1. The result has 39 B-splines, all with weight 1, as in a tensor product refinement of that region.

Now insert the horizontal segment y=32y = \tfrac32 for 0≤x≤30 \le x \le 3. It splits 13 B-splines and leaves 43. One of them, with knots (1,32,2,3)(1, \tfrac32, 2, 3) in both directions, has weight 1516\tfrac{15}{16}. It gets 34\tfrac34 from the split of a B-spline that the first segment had already split. It also gets 14⋅34=316\tfrac14 \cdot \tfrac34 = \tfrac{3}{16} through a cascade: the horizontal segment splits (0,1,2,3)×(1,2,3,4)(0, 1, 2, 3) \times (1, 2, 3, 4), and the old vertical segment then traverses the piece (0,1,2,3)×(1,32,2,3)(0, 1, 2, 3) \times (1, \tfrac32, 2, 3). The missing 116\tfrac{1}{16} would come from (1,2,3,4)×(1,2,3,4)(1, 2, 3, 4) \times (1, 2, 3, 4), which neither segment traverses. The weighted sum is still 1 at every point.

Correctness

Each split replaces γcB\gamma c B by γα1cB1+γα2cB2\gamma\alpha_1 c B_1 + \gamma\alpha_2 c B_2, which is the same function by the one-knot rule, and γB\gamma B by γα1B1+γα2B2\gamma\alpha_1 B_1 + \gamma\alpha_2 B_2. A merge replaces γ′c′Bi+γαicBi\gamma' c' B_i + \gamma\alpha_i c B_i by one term with the summed weight and the weighted mean coefficient, again the same function. So the spline and the weighted sum do not change; the sum starts at 1 by the partition of unity of tensor B-splines. The weights stay positive because each αi\alpha_i is in (0,1](0, 1]. The loop terminates, because each child has fewer mesh values strictly inside its support that are not among its knots than its parent. When it stops, no B-spline is traversed. The proofs are in the correctness proof.

Proof: LR insertion keeps the spline and the weighted partition of unity, keeps weights positive, and terminates with no traversed B-splinefull

We use the notation of the page. A B-spline BB of bidegree (p,q)(p, q) is given by local knot vectors x0≤⋯≤xp+1x_0 \le \cdots \le x_{p+1} and y0≤⋯≤yq+1y_0 \le \cdots \le y_{q+1}, and B(x,y)=N[x0,…,xp+1](x) N[y0,…,yq+1](y)B(x, y) = N[x_0, \ldots, x_{p+1}](x)\, N[y_0, \ldots, y_{q+1}](y), where N[t]N[t] is the univariate B-spline on the knots tt. The state is a set L\mathcal{L} of triples (B,γ,c)(B, \gamma, c) with distinct BB. Write s=∑LγcBs = \sum_{\mathcal{L}} \gamma c B and w=∑LγBw = \sum_{\mathcal{L}} \gamma B.

Lemma 1 (one-knot split). Let t0≤⋯≤tp+1t_0 \le \cdots \le t_{p+1} with t0<tp+1t_0 < t_{p+1}, and t0<a<tp+1t_0 < a < t_{p+1}. Let τ\tau be the sorted knots t0,…,tp+1,at_0, \ldots, t_{p+1}, a. Then

N[t]=α1N[τ0,…,τp+1]+α2N[τ1,…,τp+2]N[t] = \alpha_1 N[\tau_0, \ldots, \tau_{p+1}] + \alpha_2 N[\tau_1, \ldots, \tau_{p+2}]

with α1=min⁡(1,(a−t0)/(tp−t0))\alpha_1 = \min(1, (a - t_0)/(t_p - t_0)) (and α1=1\alpha_1 = 1 if tp=t0t_p = t_0) and α2=min⁡(1,(tp+1−a)/(tp+1−t1))\alpha_2 = \min(1, (t_{p+1} - a)/(t_{p+1} - t_1)) (and α2=1\alpha_2 = 1 if tp+1=t1t_{p+1} = t_1). Both αi\alpha_i lie in (0,1](0, 1].

Proof. Embed tt in an open knot vector TT of degree pp that contains tt as consecutive knots Tr,…,Tr+p+1T_r, \ldots, T_{r+p+1}, with p+1p + 1 extra copies of a knot below t0t_0 at the start and above tp+1t_{p+1} at the end. Then N[t]N[t] is the B-spline NrN_r of TT, with coefficient vector ere_r. Insert aa by Boehm's rule: if Tk≤a<Tk+1T_k \le a < T_{k+1}, the new coefficients are di=er(i)d_i = e_r(i) for i≤k−pi \le k - p, di=er(i−1)d_i = e_r(i-1) for i>ki > k, and di=λier(i)+(1−λi)er(i−1)d_i = \lambda_i e_r(i) + (1 - \lambda_i) e_r(i-1) with λi=(a−Ti)/(Ti+p−Ti)\lambda_i = (a - T_i)/(T_{i+p} - T_i) for k−p<i≤kk - p < i \le k. Only drd_r and dr+1d_{r+1} can be nonzero, and the new B-splines of index rr and r+1r + 1 have the knots τ0,…,τp+1\tau_0, \ldots, \tau_{p+1} and τ1,…,τp+2\tau_1, \ldots, \tau_{p+2}.

For drd_r: if r≤k−pr \le k - p, then Tr+p≤Tk≤aT_{r+p} \le T_k \le a, so tp≤at_p \le a, α1=1\alpha_1 = 1 and dr=1d_r = 1. Otherwise r>k−pr > k - p and also r≤kr \le k, since t0=Tr≤at_0 = T_r \le a and a<tp+1a < t_{p+1}; then a<Tr+p=tpa < T_{r+p} = t_p because k<r+pk < r + p, so dr=λr=(a−t0)/(tp−t0)=α1d_r = \lambda_r = (a - t_0)/(t_p - t_0) = \alpha_1, which is less than 1. For dr+1d_{r+1}: if r+1>kr + 1 > k, then a<Tr+1=t1a < T_{r+1} = t_1, dr+1=er(r)=1d_{r+1} = e_r(r) = 1, and (tp+1−a)/(tp+1−t1)>1(t_{p+1} - a)/(t_{p+1} - t_1) > 1, so α2=1\alpha_2 = 1. Otherwise r+1≤kr + 1 \le k, so t1≤at_1 \le a, and r+1>k−pr + 1 > k - p because Tr+p+1=tp+1>a≥TkT_{r+p+1} = t_{p+1} > a \ge T_k gives k<r+p+1k < r + p + 1; then dr+1=1−λr+1=(Tr+p+1−a)/(Tr+p+1−Tr+1)=α2≤1d_{r+1} = 1 - \lambda_{r+1} = (T_{r+p+1} - a)/(T_{r+p+1} - T_{r+1}) = \alpha_2 \le 1. The denominators are positive in each case, and α1>0\alpha_1 > 0 because a>t0a > t_0 and α2>0\alpha_2 > 0 because a<tp+1a < t_{p+1}. □\square

Lemma 2 (invariants of one step). Lines L5 to L8 do not change ss or ww, and they keep all weights positive.

Proof. Say μ\mu is vertical with value aa; the horizontal case is the same with the roles swapped. Line L5 removes (B,γ,c)(B, \gamma, c), and line L6 applies Lemma 1 to the xx knots: B=α1B1+α2B2B = \alpha_1 B_1 + \alpha_2 B_2, where BiB_i has the new xx knots and the same yy knots. Line L8 adds γαicBi\gamma\alpha_i c B_i to ss and γαiBi\gamma\alpha_i B_i to ww. If BiB_i is new, it is stored with weight γαi\gamma\alpha_i and coefficient cc. If BiB_i is stored as (Bi,γ′,c′)(B_i, \gamma', c'), it becomes (Bi,γ′′,c′′)(B_i, \gamma'', c'') with γ′′=γ′+γαi\gamma'' = \gamma' + \gamma\alpha_i and c′′=(γ′c′+γαic)/γ′′c'' = (\gamma' c' + \gamma\alpha_i c)/\gamma'', and γ′′c′′Bi=γ′c′Bi+γαicBi\gamma'' c'' B_i = \gamma' c' B_i + \gamma\alpha_i c B_i and γ′′Bi=γ′Bi+γαiBi\gamma'' B_i = \gamma' B_i + \gamma\alpha_i B_i. In both cases the two additions sum to γcB\gamma c B and γB\gamma B, which line L5 removed. Weights are sums of products of positive numbers, by Lemma 1. □\square

Lemma 3 (termination). Let VxV_x and VyV_y be the finite sets of values of the vertical and horizontal mesh lines after line L1. For a B-spline BB let Φ(B)\Phi(B) be the number of v∈Vxv \in V_x with x0<v<xp+1x_0 < v < x_{p+1} and v∉{xi}v \notin \{x_i\}, plus the same count in yy. If BB is split in line L6, each child BiB_i has Φ(Bi)≤Φ(B)−1\Phi(B_i) \le \Phi(B) - 1. Hence the loop of lines L3 to L9 ends.

Proof. Take a vertical split at aa. The yy knots do not change, so the yy count does not change. The support of B1B_1 in xx is [τ0,τp+1]⊆[x0,xp+1][\tau_0, \tau_{p+1}] \subseteq [x_0, x_{p+1}], and its knots are all the τj\tau_j with j≤p+1j \le p + 1. Every old knot xix_i with τ0<xi<τp+1\tau_0 < x_i < \tau_{p+1} is among τ1,…,τp\tau_1, \ldots, \tau_p, so it is a knot of B1B_1, and so is aa when it lies inside. So a value v∈Vxv \in V_x counted for B1B_1 lies strictly inside the support of BB and is not an old knot, so it is counted for BB; and aa is counted for BB but not for B1B_1. The same holds for B2B_2. Now let P=∑3Φ(B)P = \sum 3^{\Phi(B)} over the keys in the set, an integer at least 0. A split removes one key with Φ=φ≥1\Phi = \varphi \ge 1 and adds at most two new keys with Φ≤φ−1\Phi \le \varphi - 1; a merge adds no key. So PP falls by at least 3φ−2⋅3φ−1≥13^\varphi - 2 \cdot 3^{\varphi-1} \ge 1, and there are finitely many splits. Each iteration either splits or removes one entry from QQ without adding any, and the entries added to QQ are those of line L2 and two per split. So the number of iterations is finite. □\square

Lemma 4 (no traversed B-spline at the end). When INSERT returns, no stored B-spline is traversed by a mesh line.

Proof. Every key in the set at the end was put in QQ in line L2 or line L9, after the last time its triple changed. When it was taken from QQ, line L4 found no traversing line, because it is still in the set and line L5 removes every key that has one. The mesh does not change after line L1, and the traversal test depends only on the key and the mesh, so the answer is the same at the end. □\square

Theorem. Start from the tensor product spline on open knot vectors, with all weights 1. After any sequence of INSERT calls, (1) ss is the original spline, (2) w=1w = 1 on the domain, (3) all weights are positive, and (4) no B-spline is traversed by a mesh line.

Proof. At the start every γ=1\gamma = 1, so ww is the sum of the tensor B-splines, which is 1 on the domain by the partition of unity of B-splines on open knot vectors in each direction. Line L1 changes only the mesh. By Lemma 2 every step of the loop keeps ss, ww and the positivity of the weights, by Lemma 3 the loop ends, and by Lemma 4 the end state has no traversed B-spline. A refused segment restores the state, so it changes nothing. Induction over the calls gives the claims. ■\blacksquare

Complexity

Let bb be the number of LR B-splines before the insertion, ss the number of splits, mm the number of mesh segments and pp the larger degree. The queue processes the bb old B-splines and at most 2s2s children. Each one is tested against every mesh line, and each test looks up the value among p+2p + 2 knots, so INSERT takes O((b+s)mp)O((b + s) m p) time. A spatial index of the B-splines by cell reduces the work to the B-splines near the segment. The queue and the new B-splines take O(b+s)O(b + s) extra space. EVALUATE takes O(p2)O(p^2) time per B-spline, or per B-spline that is nonzero at the point with a cell index.

Variants

  • Refinement strategies. Johannessen, Kvamsdal and Dokken compare ways to choose the segments in adaptive analysis: segments that split only the marked elements, segments over the full support of the B-splines on them, and the split of chosen B-splines through the middle of their longest knot interval. The tests use the last one.
  • Higher multiplicity. A mesh line may have multiplicity up to the degree plus one, to lower the smoothness across it. The traversal rule then counts the multiplicity of the value among the local knots.
  • Trivariate LR B-splines. The same splitting works with box partitions in three dimensions, with planes instead of lines.
  • Related local refinement. T-splines use one global T-mesh and infer the local knots from it, and hierarchical and truncated hierarchical B-splines use dyadic levels. LR B-splines refine by single knot insertions, so all tensor B-splines of the refined parts stay ordinary B-splines.

When to use it

Use LR B-splines when you want local refinement that keeps every basis function an ordinary tensor B-spline with its own knots, as in adaptive isogeometric analysis or local surface fitting, and when the refinement is not tied to dyadic levels. If you need guaranteed linear independence without checks, prefer truncated hierarchical B-splines or analysis-suitable T-splines, or restrict the meshes as the literature describes.

Pitfalls

  • Linear dependence. LR B-splines can be linearly dependent on some meshes. Dokken, Lyche and Pettersen discuss linear independence and how to check it, and Bressan relates local linear independence to how many B-splines cover each element. Test the result if the method needs a basis.
  • Forgetting the cascade. Splitting only the B-splines that the new segment traverses is not enough. The children can be traversed by old mesh lines, as in the example, and must be split too.
  • Dropping the weights. Without the weights γ\gamma, the B-splines of a refined LR mesh do not sum to 1, and merged B-splines double count.
  • Segments that split nothing. A segment that traverses no B-spline adds a line to the mesh that no basis function sees. The definition forbids it.
  • Exact arithmetic for the knot test. The traversal test compares knot values. With floating point values from repeated midpoints, use exact numbers or a tolerance.

Implementations

The Python module stores the B-splines and the mesh in hash maps, implements the one-knot split, INSERT of lines L1 to L9 with merging, and EVALUATE by Cox-de Boor on local knots, all with fractions. The tests check the one-knot split against direct evaluation for degrees 1 to 3 and repeated knots, that full-length lines give the tensor product refinement of Boehm's rule on the coefficient net, the counts and the weight 1516\tfrac{15}{16} of the example, that the weighted sum is 1 at random points after random refinements with positive weights, that the surface is unchanged after each insertion, that no B-spline is left traversed, and that a segment that splits nothing is refused.

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.

lr_b_spline.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lr-b-spline/. The authors are listed in prov/G8C6QC.jsonl.

"""Bivariate LR B-splines (Dokken, Lyche and Pettersen), in exact arithmetic.

An LR B-spline is a tensor product B-spline of bidegree (p, q) given by its
local knot vectors x0 <= ... <= x(p+1) and y0 <= ... <= y(q+1), with a
positive weight g and a coefficient c. The spline is sum g * c * B, and the
weights make sum g * B = 1.

The mesh is a set of axis-parallel segments of multiplicity one. A vertical
segment ("v", a, lo, hi) is the line x = a for lo <= y <= hi; a horizontal
segment ("h", b, lo, hi) is y = b for lo <= x <= hi. Collinear segments that
overlap or touch are merged.

A segment traverses a B-spline when its value lies strictly inside the
support in one direction, is not one of the local knots in that direction,
and the segment covers the whole support in the other direction. Inserting
the value into the local knot vector then splits the B-spline into two.
"""

from fractions import Fraction


def split_knots(t, a):
    """One-knot insertion in a single B-spline: B[t] = a1 B[t1] + a2 B[t2]."""
    p = len(t) - 2
    tau = sorted(t + (a,))
    a1 = min(Fraction(1), (a - t[0]) / (t[p] - t[0])) if t[p] > t[0] else Fraction(1)
    a2 = min(Fraction(1), (t[p + 1] - a) / (t[p + 1] - t[1])) if t[p + 1] > t[1] else Fraction(1)
    return (tuple(tau[: p + 2]), a1), (tuple(tau[1:]), a2)


def local_bspline(t, x, end):
    """B-spline on the local knots t at x, by Cox-de Boor; closed at the domain end."""
    p = len(t) - 2
    vals = [Fraction(int(t[k] <= x < t[k + 1] or (x == end and t[k] < t[k + 1] == end))) for k in range(p + 1)]
    for d in range(1, p + 1):
        vals = [
            ((x - t[k]) / (t[k + d] - t[k]) * vals[k] if t[k + d] != t[k] else 0)
            + ((t[k + d + 1] - x) / (t[k + d + 1] - t[k + 1]) * vals[k + 1] if t[k + d + 1] != t[k + 1] else 0)
            for k in range(len(vals) - 1)
        ]
    return vals[0]


class LRSpline:
    def __init__(self, xknots, yknots, p, q, coeffs=None):
        """Start from a tensor product spline on open knot vectors.

        coeffs[i][j] is the coefficient of the tensor B-spline (i, j); the
        default is 0.
        """
        self.p, self.q = p, q
        self.xend, self.yend = xknots[-1], yknots[-1]
        self.box = (xknots[0], xknots[-1], yknots[0], yknots[-1])
        self.funcs = {}
        for i in range(len(xknots) - p - 1):
            for j in range(len(yknots) - q - 1):
                c = Fraction(coeffs[i][j]) if coeffs else Fraction(0)
                self.funcs[(tuple(xknots[i : i + p + 2]), tuple(yknots[j : j + q + 2]))] = [Fraction(1), c]
        self.lines = {}
        for a in sorted(set(xknots)):
            self._add(("v", a, yknots[0], yknots[-1]))
        for b in sorted(set(yknots)):
            self._add(("h", b, xknots[0], xknots[-1]))

    def _add(self, seg):
        d, v, lo, hi = seg
        spans = self.lines.setdefault((d, v), [])
        spans.append((lo, hi))
        spans.sort()
        merged = [spans[0]]
        for s, e in spans[1:]:
            if s <= merged[-1][1]:
                merged[-1] = (merged[-1][0], max(merged[-1][1], e))
            else:
                merged.append((s, e))
        self.lines[(d, v)] = merged

    def _covers(self, d, v, lo, hi):
        return any(s <= lo and hi <= e for s, e in self.lines.get((d, v), []))

    def traversing(self, key):
        """A mesh line that traverses the B-spline: ("v" or "h", value), or None."""
        xk, yk = key
        for (d, v), spans in self.lines.items():
            if d == "v" and xk[0] < v < xk[-1] and v not in xk and self._covers(d, v, yk[0], yk[-1]):
                return d, v
            if d == "h" and yk[0] < v < yk[-1] and v not in yk and self._covers(d, v, xk[0], xk[-1]):
                return d, v
        return None

    def _merge_in(self, key, g, c):
        if key in self.funcs:
            g0, c0 = self.funcs[key]
            self.funcs[key] = [g0 + g, (g0 * c0 + g * c) / (g0 + g)]
            return False
        self.funcs[key] = [g, c]
        return True

    def insert(self, seg):
        """Insert a mesh segment and split until no B-spline is traversed."""
        d, v, lo, hi = seg
        x0, x1, y0, y1 = self.box
        if not (lo < hi and ((d == "v" and x0 < v < x1 and y0 <= lo and hi <= y1) or (d == "h" and y0 < v < y1 and x0 <= lo and hi <= x1))):
            raise ValueError("the segment must lie inside the domain")
        before = dict(self.funcs)
        lines = {k: list(s) for k, s in self.lines.items()}
        self._add(seg)  # @line L1
        queue = list(self.funcs)  # @line L2
        split = 0
        while queue:  # @line L3
            key = queue.pop()
            if key not in self.funcs:
                continue
            hit = self.traversing(key)  # @line L4
            if hit is None:
                continue
            g, c = self.funcs.pop(key)  # @line L5
            split += 1
            xk, yk = key
            if hit[0] == "v":
                parts = [((t, yk), a) for t, a in split_knots(xk, hit[1])]  # @line L6
            else:
                parts = [((xk, t), a) for t, a in split_knots(yk, hit[1])]
            for child, a in parts:  # @line L7
                self._merge_in(child, g * a, c)  # @line L8
                queue.append(child)  # @line L9
        if split == 0:
            self.funcs, self.lines = before, lines
            raise ValueError("an LR refinement must split at least one B-spline")
        return split

    def evaluate(self, x, y, weights_only=False):
        """sum g * c * B(x, y), or sum g * B(x, y) when weights_only is set."""
        s = Fraction(0)
        for (xk, yk), (g, c) in self.funcs.items():
            b = local_bspline(xk, x, self.xend)
            if b:
                b *= local_bspline(yk, y, self.yend)
                s += g * b * (1 if weights_only else c)
        return s
test_lr_b_spline.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lr-b-spline/. The authors are listed in prov/G8C6QC.jsonl.

import random
from fractions import Fraction as F

from lr_b_spline import LRSpline, local_bspline, split_knots


def open_knots(n, p):
    return [F(0)] * (p + 1) + [F(a) for a in range(1, n)] + [F(n)] * (p + 1)


def boehm(knots, coeffs, u, p):
    """Reference: whole-vector knot insertion in one direction."""
    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 pts(rng, k, n=4):
    return [(F(rng.randint(0, 100 * n), 100), F(rng.randint(0, 100 * n), 100)) for _ in range(k)]


def refine_random(S, rng):
    """Split a random B-spline at the middle of its longest knot interval, with a segment over its support."""
    xk, yk = rng.choice(sorted(S.funcs))
    if rng.random() < 0.5:
        a, b = max(zip(xk, xk[1:]), key=lambda ab: ab[1] - ab[0])
        return S.insert(("v", (a + b) / 2, yk[0], yk[-1]))
    a, b = max(zip(yk, yk[1:]), key=lambda ab: ab[1] - ab[0])
    return S.insert(("h", (a + b) / 2, xk[0], xk[-1]))


def test_one_knot_split_is_an_identity():
    rng = random.Random(1)
    for p in (1, 2, 3):
        for _ in range(20):
            t = tuple(sorted(F(rng.randint(0, 6)) for _ in range(p + 2)))
            if t[0] == t[-1]:
                continue
            a = F(rng.randint(1, 59), 10)
            if not t[0] < a < t[-1] or a in t:
                continue
            (t1, a1), (t2, a2) = split_knots(t, a)
            assert 0 < a1 <= 1 and 0 < a2 <= 1
            for _ in range(5):
                x = F(rng.randint(0, 600), 100)
                assert local_bspline(t, x, F(6)) == a1 * local_bspline(t1, x, F(6)) + a2 * local_bspline(t2, x, F(6))


def test_full_lines_give_the_tensor_product_refinement():
    rng = random.Random(2)
    p, q = 2, 3
    xk, yk = open_knots(4, p), open_knots(3, q)
    C = [[F(rng.randint(-9, 9)) for _ in range(len(yk) - q - 1)] for _ in range(len(xk) - p - 1)]
    S = LRSpline(xk, yk, p, q, C)
    S.insert(("v", F(5, 2), F(0), F(3)))
    S.insert(("h", F(1, 2), F(0), F(4)))
    # reference: Boehm on the rows, then on the columns
    xr, rows = xk, C
    cols = [list(c) for c in zip(*rows)]
    new_cols = []
    for col in cols:
        xr, c = boehm(xk, col, F(5, 2), p)
        new_cols.append(c)
    rows = [list(r) for r in zip(*new_cols)]
    yr = yk
    new_rows = []
    for row in rows:
        yr, r = boehm(yk, row, F(1, 2), q)
        new_rows.append(r)
    assert len(S.funcs) == len(new_rows) * len(new_rows[0])
    for i, row in enumerate(new_rows):
        for j, c in enumerate(row):
            key = (tuple(xr[i : i + p + 2]), tuple(yr[j : j + q + 2]))
            assert S.funcs[key] == [1, c]


def test_example_counts_and_weight():
    kn = open_knots(4, 2)
    S = LRSpline(kn, kn, 2, 2)
    assert S.insert(("v", F(3, 2), F(0), F(3))) == 9
    assert len(S.funcs) == 39
    assert all(g == 1 for g, _ in S.funcs.values())
    assert S.insert(("h", F(3, 2), F(0), F(3))) == 13
    assert len(S.funcs) == 43
    t = (F(1), F(3, 2), F(2), F(3))
    assert {k: g for k, (g, _) in S.funcs.items() if g != 1} == {(t, t): F(15, 16)}


def test_weighted_partition_of_unity():
    rng = random.Random(3)
    for p, q in ((2, 2), (3, 2), (1, 3)):
        S = LRSpline(open_knots(4, p), open_knots(4, q), p, q)
        for _ in range(12):
            refine_random(S, rng)
        assert all(g > 0 for g, _ in S.funcs.values())
        for x, y in pts(rng, 8) + [(F(4), F(4)), (F(0), F(4))]:
            assert S.evaluate(x, y, weights_only=True) == 1


def test_refinement_leaves_the_surface_unchanged():
    rng = random.Random(4)
    for p, q in ((2, 2), (3, 3)):
        xk, yk = open_knots(4, p), open_knots(4, q)
        C = [[F(rng.randint(-9, 9)) for _ in range(len(yk) - q - 1)] for _ in range(len(xk) - p - 1)]
        S = LRSpline(xk, yk, p, q, C)
        probe = pts(rng, 10)
        before = [S.evaluate(x, y) for x, y in probe]
        for _ in range(10):
            refine_random(S, rng)
            assert [S.evaluate(x, y) for x, y in probe] == before


def test_no_b_spline_is_left_traversed():
    rng = random.Random(5)
    S = LRSpline(open_knots(4, 2), open_knots(4, 2), 2, 2)
    for _ in range(15):
        refine_random(S, rng)
        assert all(S.traversing(k) is None for k in S.funcs)


def test_a_segment_that_splits_nothing_is_refused():
    kn = open_knots(4, 2)
    S = LRSpline(kn, kn, 2, 2)
    funcs, lines = dict(S.funcs), dict(S.lines)
    try:
        S.insert(("v", F(3, 2), F(0), F(1, 2)))
        refused = False
    except ValueError:
        refused = True
    assert refused
    assert S.funcs == funcs and S.lines == lines

History

Dokken, Lyche and Pettersen defined LR B-splines over locally refined box partitions in 2013, as a local refinement that keeps the tensor structure of each basis function. In the same year Bressan studied their linear independence. Johannessen, Kvamsdal and Dokken used LR B-splines for adaptive isogeometric analysis in 2014 and compared refinement strategies.

References

  1. Tor Dokken, Tom Lyche and Kjell Fredrik Pettersen, Polynomial splines over locally refined box-partitions, Computer Aided Geometric Design 30(3) (2013), 331 to 356, the LR mesh, the definition of LR B-splines with weights, the splitting by one-knot insertion, and the refinement by mesh lines (general locator)
  2. Andrea Bressan, Some properties of LR-splines, Computer Aided Geometric Design 30(8) (2013), 778 to 794, linear independence and local linear independence of LR B-splines (general locator)
  3. Kjetil André Johannessen, Trond Kvamsdal and Tor Dokken, Isogeometric analysis using LR B-splines, Computer Methods in Applied Mechanics and Engineering 269 (2014), 471 to 514, refinement strategies for analysis and numerical tests of adaptive isogeometric analysis with LR B-splines (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/G8C6QC/text.yaml