Algorithm Search⌘K

Data structureadvanced

T-spline

Also called T-spline surface.

Sederberg's generalisation of NURBS whose control grid may have T-junctions, so control points can be added locally and patches joined watertight.

Time
O(a (m + n)) worst · average · best
Space
O(a) extra
Where
a = the number of control points (anchors); m = the number of vertical index lines; n = the number of horizontal index lines
Properties
deterministiciterative
Origin
Thomas W. Sederberg, Jianmin Zheng, Almaz Bakenov, Ahmad Nasri, 2003

A T-spline is a spline surface whose control grid, the T-mesh, may have T-junctions: a line of the grid may stop in the middle of another line. Each control point gets its own blending function, a product of two cubic B-splines whose knots are read from the T-mesh near the point. When the T-mesh is a full grid, the T-spline is a tensor product NURBS surface. Sederberg, Zheng, Bakenov and Nasri introduced T-splines in 2003 to remove the superfluous control points of NURBS: a row of control points no longer has to run across the whole surface. This page treats the bicubic case on a single T-mesh, without extraordinary points.

In plain words

A NURBS surface has its control points on a full grid. If a designer wants more detail in one corner, a whole row and a whole column of points must be added across the surface, and most of them do nothing useful.

A T-spline allows a row to stop where it is no longer needed. The grid then has places shaped like the letter T. Each control point still pulls on the surface with a smooth bump. The size and shape of the bump depend on the grid lines that are close to the point in the four directions, so a point near a short line gets a narrower bump than a point far from it.

Two NURBS surfaces can be joined into one T-spline without a gap, and the result can be refined in one place only.

The abstract type

A T-spline surface stores a T-mesh, one control point PA∈R3P_A \in \mathbb R^3 and one weight wA>0w_A > 0 for each anchor AA. The operations are:

  • ANCHORS: list the control points of the T-mesh.
  • LOCAL-KNOTS(A)(A): the local knot vectors sA=(sA,0,…,sA,4)s_A = (s_{A,0}, \ldots, s_{A,4}) and tA=(tA,0,…,tA,4)t_A = (t_{A,0}, \ldots, t_{A,4}) of anchor AA.
  • BLEND(A,s,t)(A, s, t): the blending function TA(s,t)=N[sA](s) N[tA](t)T_A(s, t) = N[s_A](s)\, N[t_A](t), where N[⋅]N[\cdot] is the cubic B-spline on five knots, computed by the Cox-de Boor recursion.
  • EVALUATE(s,t)(s, t): the point of the surface
S(s,t)=∑AwAPA TA(s,t)∑AwA TA(s,t).S(s, t) = \frac{\sum_A w_A P_A\, T_A(s, t)}{\sum_A w_A\, T_A(s, t)}.
  • TO-NURBS: the matrix MM that writes each TAT_A in the tensor B-splines of the global knot vectors, so that the T-spline is a NURBS surface with control points MM times the homogeneous T-spline points.

Representation

The T-mesh lives in index space. The vertical lines have the indices 0,…,m0, \ldots, m and carry the knot values sv0≤⋯≤svmsv_0 \le \cdots \le sv_m; the horizontal lines have the indices 0,…,n0, \ldots, n and carry tv0≤⋯≤tvntv_0 \le \cdots \le tv_n. A repeated value is a zero knot interval: an open knot vector at the boundary is four lines with the same value. The mesh is a set of unit edges: (i,j)(i, j) in the horizontal set means the edge from (i,j)(i, j) to (i+1,j)(i + 1, j), and in the vertical set the edge from (i,j)(i, j) to (i,j+1)(i, j + 1). A line can be present on some unit edges and absent on others, and that is how a T-junction appears.

A vertex is a point that lies on a horizontal edge and on a vertical edge. For a bicubic T-spline the anchors are the vertices (i,j)(i, j) with 2≤i≤m−22 \le i \le m - 2 and 2≤j≤n−22 \le j \le n - 2. The two outer lines on each side are complete, so every ray of the knot rule finds two lines. Working in index space avoids two problems with knot values alone: zero knot intervals do not collapse the mesh, and the topology is kept apart from the values.

Operations

  1. LOCAL-KNOTS(mesh, A = (i, j)) ▷ bicubic, in index space
  2. 1s₂ ← i
  3. 2walk right along row j from i; s₃, s₄ ← the first two columns k such that (k, j) lies on a vertical edge
  4. 3walk left along row j from i; s₁, s₀ ← the first two such columns
  5. 4walk up and down column i, with horizontal edges, to get t₀, t₁, t₂ = j, t₃, t₄
  6. 5return the values sv[s₀], …, sv[s₄] and tv[t₀], …, tv[t₄]

This is the knot rule of Sederberg and coauthors: cast a ray from the anchor in each of the four directions and record the first two lines that it crosses. A ray at row jj meets column kk only if the vertical line kk is present at the height jj; a line that stops below the ray is skipped.

  1. EVALUATE(mesh, P, w, s, t)
  2. 1num ← 0; den ← 0
  3. 2for each anchor A of the mesh do
  4. 3T_A ← N[s_A](s) · N[t_A](t) ▷ cubic B-splines on the local knots
  5. 4num ← num + w_A P_A T_A; den ← den + w_A T_A
  6. 5return num / den
  1. TO-NURBS(mesh)
  2. 1for each anchor A (a column of M) do
  3. 2insert into s_A, one line at a time, every column between s_{A,0} and s_{A,4} that s_A lacks, and the same for t_A ▷ Boehm
  4. 3M[(a, b), A] ← d_a e_b, where N[s_A] = Σ_a d_a B_a and N[t_A] = Σ_b e_b B_b
  5. 4return M

Line L12 uses Boehm's rule for one B-spline: inserting a knot uu into N[t0,…,t4]N[t_0, \ldots, t_4] gives

N[t0,…,t4]=c0 N[τ0,…,τ4]+c1 N[τ1,…,τ5],c0=min⁡(1,u−t0t3−t0),c1=min⁡(1,t4−ut4−t1),N[t_0, \ldots, t_4] = c_0\, N[\tau_0, \ldots, \tau_4] + c_1\, N[\tau_1, \ldots, \tau_5], \quad c_0 = \min\Big(1, \frac{u - t_0}{t_3 - t_0}\Big), \quad c_1 = \min\Big(1, \frac{t_4 - u}{t_4 - t_1}\Big),

where τ\tau is the sorted list of the six knots. After all insertions every piece has five consecutive global lines, so it is a global B-spline BaB_a. The matrix MM is the T-spline-to-NURBS matrix of Li, Zheng, Sederberg, Hughes and Scott.

Example

Take sv=(0,0,0,0,1,2,3,4,4,4,4)sv = (0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4) and tv=(0,0,0,0,1,2,3,3,3,3)tv = (0, 0, 0, 0, 1, 2, 3, 3, 3, 3), so the lines have the indices 0..100..10 and 0..90..9. The full grid on these lines has 7×6=427 \times 6 = 42 anchors, the control points of a bicubic NURBS surface. Now remove the vertical line s=2s = 2 (index 5) inside the surface, except for the edge from t=1t = 1 to t=2t = 2 (rows 4 to 5). The anchors (5,3)(5, 3) and (5,6)(5, 6), at (s,t)=(2,0)(s, t) = (2, 0) and (2,3)(2, 3), are no longer vertices, so 40 anchors remain. The short line ends in two T-junctions, at (2,1)(2, 1) and (2,2)(2, 2).

anchor (index) at (s,t)(s, t) sAs_A tAt_A the same as the tensor product?
(4,4)(4, 4) (1,1)(1, 1) 0,0,1,2,30, 0, 1, 2, 3 0,0,1,2,30, 0, 1, 2, 3 yes, the ray at t=1t = 1 meets s=2s = 2
(4,3)(4, 3) (1,0)(1, 0) 0,0,1,3,40, 0, 1, 3, 4 0,0,0,1,20, 0, 0, 1, 2 no, the ray at t=0t = 0 skips s=2s = 2
(6,6)(6, 6) (3,3)(3, 3) 0,1,3,4,40, 1, 3, 4, 4 1,2,3,3,31, 2, 3, 3, 3 no, the ray at t=3t = 3 skips s=2s = 2
(5,4)(5, 4) (2,1)(2, 1) 0,1,2,3,40, 1, 2, 3, 4 0,0,1,2,30, 0, 1, 2, 3 yes

For the anchor (4,3)(4, 3) line L12 inserts u=2u = 2 into sA=(0,0,1,3,4)s_A = (0, 0, 1, 3, 4). Then c0=(2−0)/(3−0)=23c_0 = (2 - 0)/(3 - 0) = \tfrac23 and c1=(4−2)/(4−0)=12c_1 = (4 - 2)/(4 - 0) = \tfrac12, so

N[0,0,1,3,4]=23 N[0,0,1,2,3]+12 N[0,1,2,3,4],N[0, 0, 1, 3, 4] = \tfrac23\, N[0, 0, 1, 2, 3] + \tfrac12\, N[0, 1, 2, 3, 4],

and its column of MM has the two entries 23\tfrac23 and 12\tfrac12 in the rows of the tensor B-splines with ss indices 2 and 3 and tt index 1. MM is 42×4042 \times 40 with rank 40, so the 40 blending functions are linearly independent. At every point that the tests try, including (2,32)(2, \tfrac32) on the short line, the blending functions are nonnegative, they sum to 1, and with the coefficients 13(sA,1+sA,2+sA,3)\tfrac13(s_{A,1} + s_{A,2} + s_{A,3}) they reproduce the function ss.

Correctness

Three facts make the data structure correct. First, on a full grid every point of every line lies on an edge, so each ray of lines L2 to L4 meets the next two lines, and the local knot vectors are the windows svi−2,…,svi+2sv_{i-2}, \ldots, sv_{i+2} of the global knot vectors: the T-spline is the tensor product NURBS surface. Second, Boehm's rule is an identity between functions, so each TAT_A equals the sum in column AA of MM, and the T-spline surface is the NURBS surface on the global knot vectors with the homogeneous control points M (wAPA,wA)M\,(w_A P_A, w_A). Third, each TAT_A is nonnegative, is zero outside the box [sA,0,sA,4]×[tA,0,tA,4][s_{A,0}, s_{A,4}] \times [t_{A,0}, t_{A,4}], and is C2C^2 across a simple knot, because it is a product of two cubic B-splines. Partition of unity and linear independence are not part of the definition: they hold for analysis-suitable T-splines and can fail for others. The proofs are in the correctness proof.

Proof: T-spline blending functions are tensor B-splines on a full grid and combinations of them on any T-meshfull

We use the representation and the pseudocode of the page: a T-mesh in index space with lines 0..m0..m and 0..n0..n, knot values svsv and tvtv, the two outer lines on each side complete, and the anchors (i,j)(i, j) with 2≤i≤m−22 \le i \le m - 2 and 2≤j≤n−22 \le j \le n - 2. N[x0,…,x4]N[x_0, \ldots, x_4] is the cubic B-spline on the knots x0≤⋯≤x4x_0 \le \cdots \le x_4, and Ba=N[sva,…,sva+4]B_a = N[sv_a, \ldots, sv_{a+4}] and Bb=N[tvb,…,tvb+4]B_b = N[tv_b, \ldots, tv_{b+4}] are the global B-splines.

Lemma 1 (the rays are defined). For each anchor, lines L2 to L4 find two lines in each direction.

Proof. For i≤m−2i \le m - 2 the ray to the right passes the columns m−1m - 1 and mm, which are complete, so each of them contains (k,j)(k, j) on a vertical edge. The same holds to the left with the columns 1 and 0, since i≥2i \ge 2, and for the rows. □\square

Lemma 2 (full grid). If the T-mesh is the full grid, the anchors are all (i,j)(i, j) with 2≤i≤m−22 \le i \le m - 2 and 2≤j≤n−22 \le j \le n - 2, the local index vectors of (i,j)(i, j) are (i−2,…,i+2)(i - 2, \ldots, i + 2) and (j−2,…,j+2)(j - 2, \ldots, j + 2), and T(i,j)=Bi−2(s) Bj−2(t)T_{(i, j)} = B_{i-2}(s)\, B_{j-2}(t). So EVALUATE returns the tensor product NURBS surface with control points P(i,j)P_{(i,j)} and weights w(i,j)w_{(i,j)}.

Proof. In the full grid every point (k,j)(k, j) lies on a vertical edge and on a horizontal edge, so every point is a vertex, and the first two columns to the right of ii that meet the ray are i+1i + 1 and i+2i + 2. The same holds in the other directions. Line L5 then returns the windows of five consecutive knots, which are the knots of Bi−2B_{i-2} and Bj−2B_{j-2}. The number of anchors is (m−3)(n−3)(m - 3)(n - 3), the number of tensor B-splines. Lines L6 to L10 compute the quotient of the two sums, which is the NURBS formula. □\square

Lemma 3 (one insertion). Let t0≤⋯≤t4t_0 \le \cdots \le t_4 with t0<t4t_0 < t_4, let uu satisfy t0≤u≤t4t_0 \le u \le t_4, and let τ0≤⋯≤τ5\tau_0 \le \cdots \le \tau_5 be the sorted list of t0,…,t4,ut_0, \ldots, t_4, u. Then

N[t0,…,t4]=c0 N[τ0,…,τ4]+c1 N[τ1,…,τ5]N[t_0, \ldots, t_4] = c_0\, N[\tau_0, \ldots, \tau_4] + c_1\, N[\tau_1, \ldots, \tau_5]

with c0=1c_0 = 1 if u≥t3u \ge t_3 and c0=(u−t0)/(t3−t0)c_0 = (u - t_0)/(t_3 - t_0) otherwise, and c1=1c_1 = 1 if u≤t1u \le t_1 and c1=(t4−u)/(t4−t1)c_1 = (t_4 - u)/(t_4 - t_1) otherwise.

Proof. Extend tt to a knot vector of any spline space that contains N[t0,…,t4]N[t_0, \ldots, t_4] as one of its B-splines, with the coefficient 1 on it and 0 on the others. Boehm's rule for inserting uu gives the new coefficients αkck+(1−αk)ck−1\alpha_k c_k + (1 - \alpha_k) c_{k-1}, with αk=(u−tk)/(tk+3−tk)\alpha_k = (u - t_k)/(t_{k+3} - t_k) clamped to [0,1][0, 1]. Only two new coefficients involve the old coefficient 1: the one of the new B-spline that starts at τ0=t0\tau_0 = t_0, which is α=min⁡(1,(u−t0)/(t3−t0))\alpha = \min(1, (u - t_0)/(t_3 - t_0)), and the one of the new B-spline that ends at τ5=t4\tau_5 = t_4, which is 1−α′1 - \alpha' with α′=max⁡(0,(u−t1)/(t4−t1))\alpha' = \max(0, (u - t_1)/(t_4 - t_1)), that is min⁡(1,(t4−u)/(t4−t1))\min(1, (t_4 - u)/(t_4 - t_1)). All the other new coefficients are 0. Boehm's rule keeps the spline as a function, so the identity holds. □\square

Lemma 4 (column AA of MM). After line L12, N[sA]=∑adaBaN[s_A] = \sum_a d_a B_a and N[tA]=∑bebBbN[t_A] = \sum_b e_b B_b, where each sum runs over the global B-splines whose index knots lie between the first and the last index of sAs_A (and tAt_A). Hence, with the entries of line L13,

TA(s,t)=∑a,bM[(a,b),A] Ba(s) Bb(t).T_A(s, t) = \sum_{a, b} M[(a, b), A]\, B_a(s)\, B_b(t).

Proof. Line L12 inserts the missing index lines one at a time. Each insertion replaces one B-spline by two by Lemma 3, so the sum of the current pieces is always equal to N[sA]N[s_A]. A piece is split by a line xx only if xx lies strictly between its first and last index lines and is not one of them, so after all lines xx in the range have been tried, each piece has five consecutive index lines: it is some BaB_a. The pieces with the same index lines are added. The same holds for tt. The product of the two sums is TAT_A. □\square

Theorem (correctness). EVALUATE returns S(s,t)=∑AwAPATA/∑AwATAS(s, t) = \sum_A w_A P_A T_A / \sum_A w_A T_A, where TAT_A is the product of the cubic B-splines on the local knot vectors inferred by the ray rule. On a full grid this is the NURBS surface. On every T-mesh, SS is the NURBS surface on the global knot vectors with the homogeneous control points Q(a,b)=∑AM[(a,b),A] (wAPA,wA)Q_{(a, b)} = \sum_A M[(a, b), A]\, (w_A P_A, w_A). Each TAT_A is nonnegative and is zero outside [sA,0,sA,4]×[tA,0,tA,4][s_{A,0}, s_{A,4}] \times [t_{A,0}, t_{A,4}].

Proof. The rays are defined by Lemma 1. Line L8 computes TAT_A from the knots of line L5, and lines L9 and L10 form the quotient, so EVALUATE returns SS. The full grid case is Lemma 2. By Lemma 4,

∑A(wAPA,wA) TA=∑a,b(∑AM[(a,b),A] (wAPA,wA))BaBb=∑a,bQ(a,b) BaBb,\sum_A (w_A P_A, w_A)\, T_A = \sum_{a, b} \Big( \sum_A M[(a, b), A]\, (w_A P_A, w_A) \Big) B_a B_b = \sum_{a, b} Q_{(a, b)}\, B_a B_b,

and dividing the first three coordinates by the last gives the NURBS surface with those homogeneous points. A cubic B-spline is nonnegative and is zero outside its first and last knot, so the product TAT_A has the stated sign and support. □\square

Remark (what is not claimed). The theorem does not say that the TAT_A are linearly independent or that they sum to 1. Linear independence holds if and only if MM has full column rank, by Theorem 1 of Li, Zheng, Sederberg, Hughes and Scott (2012), and it can fail. Partition of unity holds for analysis-suitable T-meshes with suitable boundary lines, a cited result. The tests check both for the example of the page, exactly, at sample points and by the rank of MM. ■\blacksquare

Complexity

operation time extra space
LOCAL-KNOTS O(m+n)O(m + n) for the walks O(1)O(1)
BLEND O(1)O(1) for two cubic B-splines O(1)O(1)
EVALUATE, as written O(a)O(a) blends, after the local knots are stored O(a)O(a)
TO-NURBS O(a mn)O(a\, m n) in the worst case, since a column can have O(mn)O(m n) nonzero entries O(a mn)O(a\, m n) for a dense MM

Here aa is the number of anchors, and mm and nn are the numbers of index lines. Inferring all the local knot vectors takes O(a(m+n))O(a (m + n)) time.

A surface code stores the local knot vectors once and finds the anchors whose box contains (s,t)(s, t) with a spatial index, so that EVALUATE touches only the nonzero blending functions. The walks of lines L2 to L4 take O(log⁡)O(\log) time per step with a sorted list of the lines present at each row, but the simple walk is enough for small meshes.

Variants

  • Even degree. For degree 2 the anchors are the centres of the faces, not the vertices, and the rays start from the face centre. Bazilevs and coauthors (2010) give both cases in index space.
  • Arbitrary degree. For degree pp odd the local knot vectors have p+2p + 2 entries, p+12\frac{p+1}{2} on each side of the anchor.
  • T-NURCCs. Sederberg and coauthors (2003) allow extraordinary points and use Catmull-Clark rules near them, for surfaces of any topology.
  • Analysis-suitable T-splines. The T-meshes whose T-junction extensions do not cross; see analysis-suitable T-spline, linear independence and local refinement.
  • Related local spline spaces. Hierarchical B-splines, LR B-splines and PHT-splines also refine locally, with different rules.

When to use it

Use T-splines to model a surface that needs detail in some places only, to join NURBS patches without gaps, and to remove superfluous control points from a NURBS model. For analysis, keep the T-mesh analysis-suitable, so that the blending functions are a basis and refinement stays local. For an element-wise implementation, extract the blending functions to Bernstein form on each element, as in Bezier extraction.

Pitfalls

  • Knot values instead of index space. With zero knot intervals two lines have the same value. A ray that compares values instead of indices stops at the wrong line.
  • Rays that run out. If the outer lines are not complete, a ray near the boundary finds fewer than two lines. The code raises an error instead of guessing a knot.
  • Assuming a basis. For a general T-mesh the blending functions can be linearly dependent. Buffa, Cho and Sangalli give a T-mesh whose 40 blending functions have rank 39; see linear independence.
  • Assuming partition of unity. The weights in the denominator hide this in modelling, but a finite element code that relies on ∑ATA=1\sum_A T_A = 1 needs an analysis-suitable T-mesh with suitable boundary lines.
  • Moving a T-junction without its knot. In index space a T-junction belongs to one index line. Changing the value of that line changes every blending function whose ray meets it.

Implementations

The Python module stores the T-mesh as two sets of unit edges in index space, with the knot values of the lines. It implements the anchors, LOCAL-KNOTS by ray casting, BLEND with an exact Cox-de Boor recursion on five knots, EVALUATE of the rational surface, TO-NURBS by Boehm insertion one knot at a time, and an exact rank. The tests check that on a full grid every blending function is the tensor B-spline of a separate global Cox-de Boor evaluation and that the surface is the NURBS surface, that the local knot vectors of the example match the table, that each blending function equals its expansion in column AA of MM at random rational points, that the example has partition of unity, nonnegativity and linear precision, and that each blending function vanishes outside its local box.

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.

t_spline.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t-spline/. The authors are listed in prov/80ZTCE.jsonl.

"""Bicubic T-splines in index space (Sederberg and coauthors, 2003).

A T-mesh lives on the integer grid of index space. Vertical index lines
0..m carry the s knot values sv[0..m], horizontal index lines 0..n carry the
t knot values tv[0..n]; both lists are nondecreasing, and a repeated value
gives a zero knot interval. The mesh is a set of unit edges:

- (i, j) in h means the horizontal edge from (i, j) to (i + 1, j);
- (i, j) in v means the vertical edge from (i, j) to (i, j + 1).

The two outer lines on each side (0, 1, m - 1, m and 0, 1, n - 1, n) must be
complete, so that every ray finds two knots. The anchors (control points) of
a bicubic T-spline are the vertices (i, j) with 2 <= i <= m - 2 and
2 <= j <= n - 2. Use Fraction for exact results.
"""

from fractions import Fraction


class TMesh:
    def __init__(self, sv, tv):
        self.sv = list(sv)
        self.tv = list(tv)
        self.m = len(sv) - 1
        self.n = len(tv) - 1
        self.h = set()
        self.v = set()

    @classmethod
    def full_grid(cls, sv, tv):
        mesh = cls(sv, tv)
        for j in range(mesh.n + 1):
            mesh.add_h(0, mesh.m, j)
        for i in range(mesh.m + 1):
            mesh.add_v(i, 0, mesh.n)
        return mesh

    @classmethod
    def frame(cls, sv, tv):
        """The two outer lines on each side, complete, and nothing inside."""
        mesh = cls(sv, tv)
        m, n = mesh.m, mesh.n
        for j in (0, 1, n - 1, n):
            mesh.add_h(0, m, j)
        for i in (0, 1, m - 1, m):
            mesh.add_v(i, 0, n)
        for j in range(n + 1):
            mesh.add_h(0, 1, j)
            mesh.add_h(m - 1, m, j)
        for i in range(m + 1):
            mesh.add_v(i, 0, 1)
            mesh.add_v(i, n - 1, n)
        return mesh

    def copy(self):
        other = TMesh(self.sv, self.tv)
        other.h = set(self.h)
        other.v = set(self.v)
        return other

    def add_h(self, i0, i1, j):
        """Add the horizontal segment from (i0, j) to (i1, j)."""
        for i in range(i0, i1):
            self.h.add((i, j))

    def add_v(self, i, j0, j1):
        """Add the vertical segment from (i, j0) to (i, j1)."""
        for j in range(j0, j1):
            self.v.add((i, j))

    def on_v(self, i, j):
        return (i, j) in self.v or (i, j - 1) in self.v

    def on_h(self, i, j):
        return (i, j) in self.h or (i - 1, j) in self.h

    def is_vertex(self, i, j):
        return self.on_v(i, j) and self.on_h(i, j)

    def anchors(self):
        return [
            (i, j)
            for j in range(2, self.n - 1)
            for i in range(2, self.m - 1)
            if self.is_vertex(i, j)
        ]

    def local_index_vectors(self, i, j):
        """Index lines of the local knot vectors of the anchor (i, j)."""
        s = [i]  # @line L1
        right = [k for k in range(i + 1, self.m + 1) if self.on_v(k, j)][:2]  # @line L2
        left = [k for k in range(i - 1, -1, -1) if self.on_v(k, j)][:2]  # @line L3
        s = left[::-1] + s + right
        up = [k for k in range(j + 1, self.n + 1) if self.on_h(i, k)][:2]  # @line L4
        down = [k for k in range(j - 1, -1, -1) if self.on_h(i, k)][:2]
        t = down[::-1] + [j] + up
        if len(s) != 5 or len(t) != 5:
            raise ValueError("a ray left the mesh; complete the outer lines")
        return s, t

    def local_knots(self, i, j):
        si, ti = self.local_index_vectors(i, j)
        return [self.sv[k] for k in si], [self.tv[k] for k in ti]  # @line L5


def bspline(knots, x, last=None):
    """The B-spline with the given knots (degree len - 2) at x, by Cox-de Boor.

    The pieces are half open, [a, b). If last is given, the interval that ends
    at last is closed, so the basis is right continuous at the domain end.
    """
    p = len(knots) - 2
    x = Fraction(x)
    vals = []
    for a, b in zip(knots, knots[1:]):
        inside = a <= x < b or (last is not None and a < b == last == x)
        vals.append(Fraction(1) if inside else Fraction(0))
    for d in range(1, p + 1):
        nxt = []
        for k in range(len(vals) - 1):
            val = Fraction(0)
            if knots[k + d] != knots[k]:
                val += (x - knots[k]) / (knots[k + d] - knots[k]) * vals[k]
            if knots[k + d + 1] != knots[k + 1]:
                val += (knots[k + d + 1] - x) / (knots[k + d + 1] - knots[k + 1]) * vals[k + 1]
            nxt.append(val)
        vals = nxt
    return vals[0]


def blend(mesh, anchor, s, t):
    """The blending function T_A(s, t) = N[s_A](s) N[t_A](t)."""
    sk, tk = mesh.local_knots(*anchor)
    return bspline(sk, s, mesh.sv[-1]) * bspline(tk, t, mesh.tv[-1])


def evaluate(mesh, P, w, s, t):
    """The rational T-spline surface at (s, t); P and w are dicts on the anchors."""
    dim = len(next(iter(P.values())))
    num = [Fraction(0)] * dim  # @line L6
    den = Fraction(0)
    for A in mesh.anchors():  # @line L7
        T = blend(mesh, A, s, t)  # @line L8
        if T:
            den += w[A] * T  # @line L9
            for c in range(dim):
                num[c] += w[A] * P[A][c] * T
    return tuple(x / den for x in num)  # @line L10


def insert_one(knots, x, values):
    """Boehm's rule for one B-spline: insert index line x into the index knots.

    Returns [(c0, k0), (c1, k1)] with B[knots] = c0 B[k0] + c1 B[k1].
    """
    p = len(knots) - 2
    tau = sorted(knots + [x])
    t = [values[k] for k in knots]
    u = values[x]
    c0 = Fraction(1) if u >= t[p] else (u - t[0]) / (t[p] - t[0])
    c1 = Fraction(1) if u <= t[1] else (t[p + 1] - u) / (t[p + 1] - t[1])
    return [(c0, tau[: p + 2]), (c1, tau[1:])]


def refine_to_global(index_knots, values):
    """Write B[index_knots] in the global B-splines of its range, by insertion.

    Returns {start: coefficient}, where start is the first index line of a
    global B-spline with consecutive index knots start .. start + p + 1.
    """
    funcs = {tuple(index_knots): Fraction(1)}
    lo, hi = index_knots[0], index_knots[-1]
    for x in range(lo, hi + 1):  # @line L12
        nxt = {}
        for kn, c in funcs.items():
            if kn[0] < x < kn[-1] and x not in kn:
                for c2, k2 in insert_one(list(kn), x, values):
                    if c2:
                        nxt[tuple(k2)] = nxt.get(tuple(k2), Fraction(0)) + c * c2
            else:
                nxt[kn] = nxt.get(kn, Fraction(0)) + c
        funcs = nxt
    out = {}
    for kn, c in funcs.items():
        assert list(kn) == list(range(kn[0], kn[0] + len(kn)))
        out[kn[0]] = c
    return out


def to_nurbs_matrix(mesh):
    """The T-spline-to-NURBS matrix M of Li and coauthors.

    Rows are the tensor B-splines B_a(s) B_b(t) on the global knot vectors,
    numbered a * (n - 3) + b; columns are the anchors in the order of
    mesh.anchors(). Column A holds the coefficients of T_A.
    """
    anchors = mesh.anchors()
    ns, nt = mesh.m - 3, mesh.n - 3
    M = [[Fraction(0)] * len(anchors) for _ in range(ns * nt)]
    for col, A in enumerate(anchors):  # @line L11
        si, ti = mesh.local_index_vectors(*A)
        ds = refine_to_global(si, mesh.sv)
        dt = refine_to_global(ti, mesh.tv)
        for a, ca in ds.items():  # @line L13
            for b, cb in dt.items():
                M[a * nt + b][col] = ca * cb
    return anchors, M  # @line L14


def tensor_basis(mesh, a, b, s, t):
    """The global tensor B-spline with s index knots a..a+4 and t index knots b..b+4."""
    return bspline(mesh.sv[a : a + 5], s, mesh.sv[-1]) * bspline(mesh.tv[b : b + 5], t, mesh.tv[-1])


def rank(M):
    """Rank of a matrix of Fractions by exact Gaussian elimination."""
    A = [list(r) for r in M]
    rows, cols = len(A), len(A[0]) if A else 0
    r = 0
    for c in range(cols):
        piv = next((i for i in range(r, rows) if A[i][c] != 0), None)
        if piv is None:
            continue
        A[r], A[piv] = A[piv], A[r]
        for i in range(r + 1, rows):
            if A[i][c] != 0:
                f = A[i][c] / A[r][c]
                A[i] = [x - f * y for x, y in zip(A[i], A[r])]
        r += 1
    return r
test_t_spline.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t-spline/. The authors are listed in prov/80ZTCE.jsonl.

import random
from fractions import Fraction as F

from t_spline import TMesh, blend, evaluate, rank, tensor_basis, to_nurbs_matrix

SV = [F(x) for x in (0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4)]
TV = [F(x) for x in (0, 0, 0, 0, 1, 2, 3, 3, 3, 3)]


def example_mesh():
    """The full grid without the line s = 2, except for the edge t in [1, 2]."""
    mesh = TMesh.full_grid(SV, TV)
    mesh.v -= {(5, j) for j in range(2, 7)}
    mesh.add_v(5, 4, 5)
    return mesh


def all_basis(knots, p, x):
    """Reference: all B-splines of degree p on a clamped knot vector at x."""
    n = len(knots) - p - 1
    if x == knots[-1]:
        return [F(int(i == n - 1)) for i in range(n)]
    N = [F(int(knots[i] <= x < knots[i + 1])) for i in range(len(knots) - 1)]
    for d in range(1, p + 1):
        M = []
        for i in range(len(N) - 1):
            v = F(0)
            if knots[i + d] > knots[i]:
                v += (x - knots[i]) / (knots[i + d] - knots[i]) * N[i]
            if knots[i + d + 1] > knots[i + 1]:
                v += (knots[i + d + 1] - x) / (knots[i + d + 1] - knots[i + 1]) * N[i + 1]
            M.append(v)
        N = M
    return N


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


def test_full_grid_blending_functions_are_the_tensor_b_splines():
    mesh = TMesh.full_grid(SV, TV)
    anchors = mesh.anchors()
    assert len(anchors) == (mesh.m - 3) * (mesh.n - 3) == 42
    for i, j in anchors:
        assert mesh.local_index_vectors(i, j) == (list(range(i - 2, i + 3)), list(range(j - 2, j + 3)))
    rng = random.Random(1)
    for s, t in points(rng, 25):
        Bs, Bt = all_basis(SV, 3, s), all_basis(TV, 3, t)
        for i, j in anchors:
            assert blend(mesh, (i, j), s, t) == Bs[i - 2] * Bt[j - 2]


def test_full_grid_surface_is_the_nurbs_surface():
    mesh = TMesh.full_grid(SV, TV)
    rng = random.Random(2)
    P = {A: (F(rng.randint(-9, 9)), F(rng.randint(-9, 9)), F(rng.randint(-9, 9))) for A in mesh.anchors()}
    w = {A: F(rng.randint(1, 5), rng.randint(1, 3)) for A in mesh.anchors()}
    for s, t in points(rng, 15):
        Bs, Bt = all_basis(SV, 3, s), all_basis(TV, 3, t)
        num = [F(0)] * 3
        den = F(0)
        for i, j in mesh.anchors():
            b = w[i, j] * Bs[i - 2] * Bt[j - 2]
            den += b
            num = [x + b * y for x, y in zip(num, P[i, j])]
        assert evaluate(mesh, P, w, s, t) == tuple(x / den for x in num)
    anchors, M = to_nurbs_matrix(mesh)
    nt = mesh.n - 3
    for c, (i, j) in enumerate(anchors):
        assert [M[r][c] for r in range(42)] == [F(r == (i - 2) * nt + (j - 2)) for r in range(42)]


def test_local_knot_vectors_by_ray_casting():
    mesh = example_mesh()
    assert len(mesh.anchors()) == 40 and (5, 3) not in mesh.anchors() and (5, 6) not in mesh.anchors()
    expect = {
        (4, 4): ([0, 0, 1, 2, 3], [0, 0, 1, 2, 3]),  # the ray at t = 1 meets s = 2
        (4, 3): ([0, 0, 1, 3, 4], [0, 0, 0, 1, 2]),  # the ray at t = 0 does not
        (6, 6): ([0, 1, 3, 4, 4], [1, 2, 3, 3, 3]),
        (5, 4): ([0, 1, 2, 3, 4], [0, 0, 1, 2, 3]),
    }
    for A, (s, t) in expect.items():
        assert mesh.local_knots(*A) == ([F(x) for x in s], [F(x) for x in t])


def test_blending_functions_equal_their_tensor_expansion():
    mesh = example_mesh()
    anchors, M = to_nurbs_matrix(mesh)
    nt = mesh.n - 3
    rng = random.Random(3)
    for s, t in points(rng, 12):
        N = [tensor_basis(mesh, r // nt, r % nt, s, t) for r in range(len(M))]
        for c, A in enumerate(anchors):
            assert blend(mesh, A, s, t) == sum(M[r][c] * N[r] for r in range(len(M)))
    assert rank(M) == len(anchors)  # linearly independent


def test_partition_of_unity_and_linear_precision_on_the_example():
    mesh = example_mesh()
    anchors = mesh.anchors()
    centre = {A: [sum(k[1:4]) / 3 for k in mesh.local_knots(*A)] for A in anchors}
    rng = random.Random(4)
    for s, t in points(rng, 20) + [(F(2), F(3, 2)), (F(4), F(3))]:
        T = {A: blend(mesh, A, s, t) for A in anchors}
        assert sum(T.values()) == 1
        assert sum(centre[A][0] * T[A] for A in anchors) == s
        assert sum(centre[A][1] * T[A] for A in anchors) == t
        assert all(x >= 0 for x in T.values())


def test_each_blending_function_is_nonzero_only_inside_its_local_box():
    mesh = example_mesh()
    rng = random.Random(5)
    for A in mesh.anchors():
        sk, tk = mesh.local_knots(*A)
        for s, t in points(rng, 6):
            if not (sk[0] <= s <= sk[-1] and tk[0] <= t <= tk[-1]):
                assert blend(mesh, A, s, t) == 0

History

Sederberg, Zheng, Bakenov and Nasri introduced T-splines and T-NURCCs at SIGGRAPH 2003. In 2004 Sederberg, Cardon, Finnigan, North, Zheng and Lyche gave local refinement and the simplification of NURBS models into T-splines. Bazilevs, Calo, Cottrell, Evans, Hughes, Lipton, Scott and Sederberg used T-splines for isogeometric analysis in 2010. In the same year Buffa, Cho and Sangalli found a T-mesh with linearly dependent blending functions, and Li, Zheng, Sederberg, Hughes and Scott answered with analysis-suitable T-splines, published in 2012.

References

  1. Thomas W. Sederberg, Jianmin Zheng, Almaz Bakenov and Ahmad Nasri, T-splines and T-NURCCs, ACM Transactions on Graphics 22(3) (SIGGRAPH 2003), 477 to 484, the definition of the T-mesh, the rule that infers the local knot vectors of a control point from the T-mesh, and the point-based form of the surface (general locator)
  2. Thomas W. Sederberg, David L. Cardon, G. Thomas Finnigan, Nicholas S. North, Jianmin Zheng and Tom Lyche, T-spline simplification and local refinement, ACM Transactions on Graphics 23(3) (SIGGRAPH 2004), 276 to 283, the local refinement of blending functions and the merging of NURBS patches (general locator)
  3. Y. Bazilevs, V. M. Calo, J. A. Cottrell, J. A. Evans, T. J. R. Hughes, S. Lipton, M. A. Scott and T. W. Sederberg, Isogeometric analysis using T-splines, Computer Methods in Applied Mechanics and Engineering 199(5-8), 2010, 229 to 263, T-splines of odd and even degree in index space, and their use as a basis for analysis
  4. Xin Li, Jianmin Zheng, Thomas W. Sederberg, Thomas J. R. Hughes and Michael A. Scott, On linear independence of T-spline blending functions, Computer Aided Geometric Design 29(1), 2012, 63 to 76, Section 2 (review of T-splines, the local knot vectors of Figure 2) and Section 3 (the T-spline-to-NURBS matrix M and its computation by knot insertion)
  5. A. Buffa, D. Cho and G. Sangalli, Linear independence of the T-spline blending functions associated with some particular T-meshes, Computer Methods in Applied Mechanics and Engineering 199(23-24), 2010, 1437 to 1445, the example of a T-mesh whose blending functions are linearly dependent

Where this leads

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/80ZTCE/text.yaml