Algorithm Search⌘K

Algorithmresearch

Local refinement of analysis-suitable T-splines

Also called Scott T-spline refinement.

Scott and coauthors' refinement that inserts the requested control points and any extra ones needed so the T-mesh stays analysis-suitable and refinement stays local.

Time
O(k c (m n (m + n) + x^2) + a^2) worst
Space
O(m n + a^2) extra
Where
a = the number of anchors; c = the number of candidate edges in one round; k = the number of insertion edges that the loop adds; m = the number of vertical index lines; n = the number of horizontal index lines; x = the number of T-junction extensions
Properties
deterministiciterative
Origin
Michael A. Scott, Xin Li, Thomas W. Sederberg, Thomas J. R. Hughes, 2012

Local refinement of analysis-suitable T-splines takes a T-spline on an analysis-suitable T-mesh T1T_1 and a set of edges that the user wants to add. It adds those edges, then adds a few more edges, one at a time, until the new T-mesh T2T_2 is analysis-suitable again and its T-junction extensions do not run into the extensions of T1T_1 in a way that breaks nesting. Then every old blending function is a combination of new ones, and the algorithm computes that combination, the refinement matrix MM. The new control points are M⊤M^\top times the old homogeneous control points, so the surface does not change. Scott, Li, Sederberg and Hughes gave the algorithm in 2012. This page treats the bicubic case in index space, with the representation of the T-spline page.

In plain words

A T-spline lets a row of control points stop in the middle of the surface. To get more detail in one place, you draw a few new short lines there. For analysis, this is not always safe. The short lines can make the smooth bumps of the control points depend on each other, and the old bumps may no longer be sums of the new ones.

The algorithm draws your lines first. Then it looks for places where the ends of short lines come too close to each other. At each such place it can make one short line a little longer. It tries every such step and keeps the one that removes the most problems. It repeats until no problem is left.

At the end, each old bump is an exact sum of new bumps, so the shape does not change.

The problem

The input is an analysis-suitable bicubic T-mesh T1T_1 in index space, with the two outer lines on each side complete, and a request RR: a list of horizontal and vertical segments on index lines. The output is a T-mesh T2⊇T1∪RT_2 \supseteq T_1 \cup R and a matrix MM such that

  1. T2T_2 is analysis-suitable,
  2. every blending function NAN_A of T1T_1 satisfies NA=∑BMABNBN_A = \sum_B M_{AB} N_B over the blending functions NBN_B of T2T_2,
  3. T2T_2 adds as few edges beyond RR as the greedy rule finds.

With homogeneous control points QA=(wAPA,wA)Q_A = (w_A P_A, w_A), condition 2 gives ∑AQANA=∑B(∑AMABQA)NB\sum_A Q_A N_A = \sum_B \big(\sum_A M_{AB} Q_A\big) N_B, so the rational surface is the same.

Analysis-suitable alone is not enough for condition 2. A T-mesh T2⊇T1T_2 \supseteq T_1 can be analysis-suitable while some old function is not in the new space; the tests give one. Scott and coauthors use a stronger condition, which they write T1ext⊆∧T2extT_1^{ext} \subseteq^{\wedge} T_2^{ext}: T1⊆T2T_1 \subseteq T_2, and no face extension of T2T_2 ends strictly inside a face extension of T1T_1 that goes in the same direction. Li and Scott (2014) prove that two analysis-suitable T-meshes with this property give nested spline spaces.

The algorithm

The T-junction extension of a T-junction JJ that is missing the edge in direction dd has two parts: the face extension goes from JJ in direction dd to the second perpendicular line that it meets, and the edge extension goes from JJ the other way to the first perpendicular line. A T-mesh is analysis-suitable when no horizontal extension meets a vertical one, the segments being closed.

The coupled extension graph E(T1→T2)E(T_1 \to T_2) has one edge for each pair of a horizontal and a vertical extension of T2T_2 that meet, and one loop edge for each face extension of T2T_2 that ends strictly inside a same-direction face extension of T1T_1. Its weight WW is the number of edges. W=0W = 0 means that T2T_2 is analysis-suitable and that T1ext⊆∧T2extT_1^{ext} \subseteq^{\wedge} T_2^{ext}.

  1. REFINE(T₁, R)
  2. 1T₂ ← T₁ ∪ R
  3. 2W ← the weight of the coupled extension graph E(T₁ → T₂)
  4. 3while W > 0 do
  5. 4for each insertion edge e: from a T-junction J of T₂ whose extension is in an edge of E, along J's missing direction, to the next perpendicular line
  6. 5keep the e for which the weight of E(T₁ → T₂ ∪ {e}) is smallest (the first one on a tie)
  7. 6T₂ ← T₂ ∪ {e}; W ← that weight
  1. REFINEMENT-MATRIX(T₁, T₂, Q)
  2. 1for each old function N_A, and each new N_B whose index box lies in that of N_A do
  3. 2insert into s_A the index lines of s_B that s_A lacks, and the same for t_A ▷ Boehm, one B-spline
  4. 3c ← (coefficient of N[s_B] in N[s_A]) · (coefficient of N[t_B] in N[t_A]), or 0 if a factor is not a piece
  5. 4M_AB ← c
  6. 5return the new control points Q_B ← Σ_A M_AB Q_A

Line L5 is greedy: it does not search for the set of insertion edges with the fewest edges that makes WW zero. Lines L7 to L10 use the fact that the coefficient of a fine B-spline in a coarse one depends only on the coarse knots and on the knots of the fine B-spline: it is a discrete B-spline of the Oslo algorithm. So each pair (A,B)(A, B) can be treated alone, by Boehm's rule on two short knot vectors.

Example

Take the index lines 0..140..14 in both directions with the values 0,0,0,0,12,1,32,…,72,4,4,4,40, 0, 0, 0, \tfrac12, 1, \tfrac32, \ldots, \tfrac72, 4, 4, 4, 4, and let T1T_1 be the tensor mesh on the lines with integer values, the lines 0,1,2,3,5,7,9,11,12,13,140, 1, 2, 3, 5, 7, 9, 11, 12, 13, 14. It is a bicubic B-spline surface with 7×7=497 \times 7 = 49 control points. The request splits the face [1,2]×[1,2][1, 2] \times [1, 2] into four: the vertical segment on column 6 (s=32s = \tfrac32) from row 5 to row 7, and the horizontal segment on row 6 (t=32t = \tfrac32) from column 5 to column 7.

After line L1 the mesh has four new T-junctions, at index (6,5)(6, 5), (6,7)(6, 7), (5,6)(5, 6) and (7,6)(7, 6). The vertical extension of (6,5)(6, 5) runs on column 6 from row 2 to row 6, and the horizontal extension of (5,6)(5, 6) runs on row 6 from column 2 to column 6. They meet at the centre (6,6)(6, 6), so T1∪RT_1 \cup R is not analysis-suitable and W>0W > 0. The loop adds two insertion edges, from (5,6)(5, 6) left to column 3 and from (7,6)(7, 6) right to column 9: row 6 now runs from s=0s = 0 to s=3s = 3. The vertical extensions stay on column 6, and the two horizontal ones now run on row 6 from column 1 to column 5 and from column 7 to column 12, so they do not meet, W=0W = 0, and T2T_2 has 5656 anchors.

For the old anchor at (s,t)=(1,1)(s, t) = (1, 1) the local knot vectors are (0,0,1,2,3)(0, 0, 1, 2, 3) in both directions. Inserting 32\tfrac32 gives c0=3/22=34c_0 = \tfrac{3/2}{2} = \tfrac34 and c1=3−3/23=12c_1 = \tfrac{3 - 3/2}{3} = \tfrac12, so

N[0,0,1,2,3]=34 N[0,0,1,32,2]+12 N[0,1,32,2,3],N[0, 0, 1, 2, 3] = \tfrac34\, N[0, 0, 1, \tfrac32, 2] + \tfrac12\, N[0, 1, \tfrac32, 2, 3],

and the row of MM has the four products 916\tfrac{9}{16}, 38\tfrac38, 38\tfrac38 and 14\tfrac14 on the new anchors at (1,1)(1, 1), (32,1)(\tfrac32, 1), (1,32)(1, \tfrac32) and (32,32)(\tfrac32, \tfrac32). Sixteen of the 49 rows change; the other 33 old functions are new functions too.

Correctness

The loop stops, because each round adds a unit edge that T2T_2 did not have, the edges of the index grid are finite, and while W>0W > 0 there is always a candidate: an extension in an edge of EE has a face part, so its junction has a next perpendicular line. At the end W=0W = 0, so T2T_2 has no crossing extensions, which is the definition of analysis-suitable, and no loop edges, which is T1ext⊆∧T2extT_1^{ext} \subseteq^{\wedge} T_2^{ext}. Then the spaces are nested by the theorem of Li and Scott (2014), and the new functions are linearly independent by Theorem 18 of Li, Zheng, Sederberg, Hughes and Scott, so the coefficients of each NAN_A are unique. Scott and coauthors (Section 4.3) show that lines L7 to L10 compute them. Given condition 2, the new control points give the same surface. The proof has the details and marks the cited steps. The tests check condition 2 exactly, as an identity between the expansions of both sides in the tensor B-splines on all index lines.

Proof: The refinement stops with an analysis-suitable, nested T-mesh, and the new control points give the same surfacefull

We use the notation of the page. T1T_1 is an analysis-suitable bicubic T-mesh in index space with the outer lines complete, RR is the request, and T2T_2 is the T-mesh during and after lines L1 to L6. For a T-mesh TT, an extension is the closed segment from the end of the edge extension to the end of the face extension of a T-junction. E(T1→T2)E(T_1 \to T_2) is the coupled extension graph and WW its number of edges. Two steps of the argument are theorems that we cite and do not prove here; they are marked (cited).

Lemma 1 (a candidate exists). If W>0W > 0, line L4 has at least one insertion edge, and it is not an edge of T2T_2.

Proof. W>0W > 0 means that EE has a crossing edge or a loop edge. Each of them involves an extension of a T-junction JJ of T2T_2 that is missing the edge in some direction dd. The face part of that extension is the walk from JJ in direction dd to the second perpendicular line, so the walk meets at least one perpendicular line, and the segment from JJ to the first one is an insertion edge. Its first unit edge, at JJ in direction dd, is not in T2T_2, because JJ is missing that edge. □\square

Lemma 2 (termination). The loop of lines L3 to L6 stops after at most uu rounds, where uu is the number of unit edges of the index grid.

Proof. By Lemma 1 every round adds at least one unit edge that T2T_2 did not have, and no round removes an edge. T2T_2 is a subset of the uu unit edges, so there are at most uu rounds. When the loop stops, W=0W = 0. □\square

Lemma 3 (what W=0W = 0 means). When the loop stops, T1∪R⊆T2T_1 \cup R \subseteq T_2, T2T_2 is analysis-suitable, and no face extension of T2T_2 ends strictly inside a face extension of T1T_1 in the same direction.

Proof. Line L1 puts T1T_1 and RR into T2T_2, and later lines only add edges. W=0W = 0 means that there is no crossing edge, so no horizontal extension of T2T_2 meets a vertical one, which is the definition of analysis-suitable (Li, Zheng, Sederberg, Hughes and Scott, Definition 7). It also means that there is no loop edge, which is the second statement. □\square

Step 4 (nesting, cited). By Lemma 3, T1T_1 and T2T_2 are analysis-suitable and T1ext⊆∧T2extT_1^{ext} \subseteq^{\wedge} T_2^{ext} in the sense of Scott, Li, Sederberg and Hughes (Section 4.1). Li and Scott (2014) prove that then every blending function NAN_A of T1T_1 lies in the span of the blending functions NBN_B of T2T_2. By Theorem 18 of Li and coauthors (2012) the NBN_B are linearly independent, so the coefficients cABc_{AB} in NA=∑BcABNBN_A = \sum_B c_{AB} N_B are unique.

Step 5 (the pair formula, cited). For a cubic B-spline N[x0,…,x4]N[x_0, \ldots, x_4] and a finer knot vector that contains xx, the coefficient of a fine B-spline N[y0,…,y4]N[y_0, \ldots, y_4] depends only on xx and yy: it is a discrete B-spline of Cohen, Lyche and Riesenfeld, the number that the Oslo algorithm computes, and Boehm's rule one knot at a time gives the same number. Scott and coauthors (Section 4.3) use this to show that cABc_{AB} is the product of the univariate coefficient of N[sB]N[s_B] in N[sA]N[s_A] and that of N[tB]N[t_B] in N[tA]N[t_A], and is 0 when the index box of BB is not inside that of AA or when sBs_B or tBt_B is not a piece of the insertion. Lines L7 to L10 compute exactly these products, by the one-knot form of Boehm's rule proved on the T-spline page (Lemma 3 of its proof). So MAB=cABM_{AB} = c_{AB}.

Lemma 6 (the surface does not change). If NA=∑BMABNBN_A = \sum_B M_{AB} N_B for every old anchor AA, then with QB=∑AMABQAQ_B = \sum_A M_{AB} Q_A from line L11,

∑AQANA=∑BQBNB,\sum_A Q_A N_A = \sum_B Q_B N_B,

and the rational surfaces of (T1,Q)(T_1, Q) and (T2,Q′)(T_2, Q') are equal.

Proof. ∑AQANA=∑AQA∑BMABNB=∑B(∑AMABQA)NB=∑BQBNB\sum_A Q_A N_A = \sum_A Q_A \sum_B M_{AB} N_B = \sum_B \big(\sum_A M_{AB} Q_A\big) N_B = \sum_B Q_B N_B, by exchanging two finite sums. Both sides are vectors (x,y,z,w)(x, y, z, w) of functions. The surface is (x/w,y/w,z/w)(x/w, y/w, z/w), so it is the same on both meshes. □\square

Theorem. REFINE stops. Its output T2T_2 contains T1T_1 and the request, is analysis-suitable, and every old blending function is the combination of new ones given by its row of MM. The control points of line L11 give the same rational surface.

Proof. Termination is Lemma 2, and the properties of T2T_2 are Lemma 3. The identity NA=∑BMABNBN_A = \sum_B M_{AB} N_B is Step 4 with Step 5. The surface is Lemma 6. □\square

Remark (what the tests check). The two cited steps are checked exactly on every mesh of the tests: for each old function, the tests expand NAN_A and ∑BMABNB\sum_B M_{AB} N_B in the tensor B-splines on all index lines of the box, with a Boehm insertion that is independent of lines L7 to L10, and compare the two coefficient lists in exact rational arithmetic. The tests also give a T-mesh that is analysis-suitable but not nested, which shows that the loop edges of Lemma 3 are needed. ■\blacksquare

Complexity

Let kk be the number of rounds, cc the number of candidates in a round, xx the number of extensions and aa the number of anchors. One weight takes O(mn(m+n))O(m n (m + n)) time to find the extensions by walks on the index grid and O(x2)O(x^2) to test pairs, so the loop takes O(kc(mn(m+n)+x2))O(k c (m n (m + n) + x^2)). Lines L7 to L10 test O(a2)O(a^2) pairs, and each pair inserts at most eight knots into two knot vectors of length 5, which is O(1)O(1). The extra space is O(mn)O(m n) for the edge sets and O(a2)O(a^2) for a dense MM; MM has O(a)O(a) nonzero entries in practice, because a new function lies in the box of only a few old ones.

These bounds are for the simple implementation. A production code keeps the extensions in a spatial index and updates the weight after each edge instead of starting again, so one round costs time proportional to the size of the change.

Properties

  • Local. An insertion edge starts at a T-junction whose extension is in conflict, so new edges appear only near the request and near the edges added before them.
  • Not unique. The result depends on the order of the candidates when two of them give the same weight, and the greedy choice need not be the smallest set of edges.
  • Convex rows. Each entry of MM is a product of Boehm coefficients, so it is nonnegative. Each new control point is a nonnegative combination of old homogeneous points.
  • A request is never undone. The algorithm only adds edges, so the requested segments are in T2T_2.

Variants and improvements

  • Sederberg and coauthors (2004). The first local refinement of T-splines inserts control points and then fixes the blending functions one at a time. It can add superfluous control points and can produce a T-mesh that is not analysis-suitable.
  • Arbitrary degree. Beirão da Veiga, Buffa, Sangalli and Vázquez (2013) define analysis-suitable T-splines of any degree and show that they are dual-compatible. The extensions are longer for higher degree, and the same test of crossing extensions applies.
  • Other local spline spaces. Hierarchical B-splines, truncated hierarchical B-splines, LR B-splines and PHT-splines refine locally with simpler rules, at the cost of other properties.

When to use it

Use this algorithm in adaptive isogeometric analysis with T-splines: an error estimator marks elements, each marked face is split into four, and the algorithm makes the result analysis-suitable and nested, so the old solution is in the new space. For modelling alone, where only the shape matters, the 2004 refinement is enough.

Pitfalls

  • Analysis-suitable is not nested. A T-mesh T2⊇T1T_2 \supseteq T_1 can be analysis-suitable while an old function is not a combination of the new ones. The loop edges of the coupled graph catch this case.
  • Closed segments. Two extensions that touch at one point count as meeting. With open segments the example above would look analysis-suitable, and it is not.
  • Superfluous edges. The greedy rule can add more edges than the minimum, because it does not search for the smallest set.
  • The pair formula needs nesting. Lines L7 to L10 give the right MM only when NAN_A is in the new space. Called on a pair of meshes that is not nested, they return numbers whose sum is not NAN_A.
  • Knot values instead of indices. As for every T-spline code, repeated knot values need index space, or the extensions end at the wrong lines.

Implementations

The Python module stores the T-mesh in index space as two sets of unit edges, finds the face and edge extensions of every T-junction by walks on the grid, and implements the analysis-suitable test with closed segments, the weight of the coupled extension graph, the greedy loop of lines L1 to L6, the pair-by-pair matrix of lines L7 to L10 with exact Boehm insertion, and the new control points of line L11. The tests check the face cross example and its two insertion edges, that an L-junction is not analysis-suitable, that an analysis-suitable T-mesh can fail to be nested and that the algorithm repairs it, that four random face splits stay analysis-suitable with every old function equal to its row of MM, compared exactly with the expansion of both sides in the tensor B-splines on all index lines, and that the rational surface and the partition of unity do not change at sample points.

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_local_refinement.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t-spline-local-refinement/. The authors are listed in prov/WVHYV3.jsonl.

"""Local refinement of analysis-suitable bicubic T-splines (Scott, Li, Sederberg, Hughes).

The T-mesh lives on a fixed integer grid of index space (see the t-spline
page): vertical lines 0..m with knot values sv, horizontal lines 0..n with
values tv, and sets of unit edges. A grid line that has no edge is not part of
the T-mesh; refinement may add edges on it. Lines 0, 1, m - 1, m and
0, 1, n - 1, n must be complete. Use Fraction for exact results.

refine(T1, R) adds the requested edges R to T1, then adds insertion edges, one
at a time and greedily, until the coupled extension graph has no edges. It
returns the refined mesh and the refinement operator, so that the surface is
the same.
"""

from fractions import Fraction

DIRS = {"R": (1, 0), "L": (-1, 0), "U": (0, 1), "D": (0, -1)}
OPP = {"R": "L", "L": "R", "U": "D", "D": "U"}


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

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

    def add_h(self, i0, i1, j):
        for i in range(min(i0, i1), max(i0, i1)):
            self.h.add((i, j))

    def add_v(self, i, j0, j1):
        for j in range(min(j0, j1), max(j0, j1)):
            self.v.add((i, j))

    def add_lines(self, cols, rows):
        """Add the complete vertical lines cols and horizontal lines rows."""
        for i in cols:
            self.add_v(i, 0, self.n)
        for j in rows:
            self.add_h(0, self.m, 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 has_edge(self, i, j, d):
        if d == "R":
            return (i, j) in self.h
        if d == "L":
            return (i - 1, j) in self.h
        if d == "U":
            return (i, j) in self.v
        return (i, j - 1) in self.v

    def crosses(self, i, j, d):
        """Does the point (i, j) lie on an edge perpendicular to direction d?"""
        return self.on_v(i, j) if d in "RL" else self.on_h(i, j)

    def inside(self, i, j):
        return 0 <= i <= self.m and 0 <= j <= self.n

    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 march(self, i, j, d, count):
        """Points met when walking from (i, j) in direction d that lie on perpendicular edges."""
        di, dj = DIRS[d]
        out = []
        while len(out) < count:
            i, j = i + di, j + dj
            if not self.inside(i, j):
                break
            if self.crosses(i, j, d):
                out.append((i, j))
        return out

    def local_index_vectors(self, i, j):
        r = [p[0] for p in self.march(i, j, "R", 2)]
        l = [p[0] for p in self.march(i, j, "L", 2)]
        u = [p[1] for p in self.march(i, j, "U", 2)]
        d = [p[1] for p in self.march(i, j, "D", 2)]
        if min(len(r), len(l), len(u), len(d)) < 2:
            raise ValueError("a ray left the mesh; complete the outer lines")
        return (tuple(l[::-1] + [i] + r), tuple(d[::-1] + [j] + u))

    def functions(self):
        """The blending functions as {anchor: (s index vector, t index vector)}."""
        return {A: self.local_index_vectors(*A) for A in self.anchors()}


def face_extensions_and_junctions(mesh):
    """The T-junction extensions of the mesh in index space.

    For each vertex and each missing direction d whose opposite edge exists,
    the face extension marches in direction d to the second point on a
    perpendicular edge; the edge extension marches the other way to the first
    such point. Returns a list of (junction, d, face_end, edge_end).
    """
    out = []
    for i in range(mesh.m + 1):
        for j in range(mesh.n + 1):
            if not mesh.is_vertex(i, j):
                continue
            for d in "RLUD":
                di, dj = DIRS[d]
                if not mesh.inside(i + di, j + dj):
                    continue  # the outer boundary of the index domain
                if not mesh.has_edge(i, j, d) and mesh.has_edge(i, j, OPP[d]):
                    face = mesh.march(i, j, d, 2)
                    edge = mesh.march(i, j, OPP[d], 1)
                    out.append(((i, j), d, face[-1], edge[0]))
    return out


def segment(ext):
    """The closed segment of a T-junction extension, as (horizontal?, line, lo, hi)."""
    (i, j), d, f, e = ext
    if d in "RL":
        return True, j, min(f[0], e[0]), max(f[0], e[0])
    return False, i, min(f[1], e[1]), max(f[1], e[1])


def crossing_pairs(exts):
    segs = [segment(x) for x in exts]
    pairs = []
    for a, (ha, la, loa, hia) in enumerate(segs):
        for b, (hb, lb, lob, hib) in enumerate(segs):
            if ha and not hb and loa <= lb <= hia and lob <= la <= hib:
                pairs.append((a, b))
    return pairs


def is_analysis_suitable(mesh):
    """No horizontal T-junction extension meets a vertical one (closed segments)."""
    return not crossing_pairs(face_extensions_and_junctions(mesh))


def _strictly_inside(p, a, b, d):
    if d in "RL":
        return p[1] == a[1] and min(a[0], b[0]) < p[0] < max(a[0], b[0])
    return p[0] == a[0] and min(a[1], b[1]) < p[1] < max(a[1], b[1])


def coupled_weight(ext1, mesh2):
    """Weight of the coupled extension graph E(T1->2): crossings in T2 plus loop edges.

    A loop edge is a face extension of T2 that ends strictly inside a face
    extension of T1 with the same direction, on the same line.
    """
    ext2 = face_extensions_and_junctions(mesh2)
    w = len(crossing_pairs(ext2))
    for _, d, f2, _ in ext2:
        if any(d1 == d and _strictly_inside(f2, J1, f1, d) for J1, d1, f1, _ in ext1):
            w += 1
    return w, ext2


def insertion_edges(ext1, mesh2):
    """Candidate edges: from a T-junction of nonzero weight to the next perpendicular line."""
    ext2 = face_extensions_and_junctions(mesh2)
    pairs = crossing_pairs(ext2)
    busy = {a for a, _ in pairs} | {b for _, b in pairs}
    for k, (J, d, f2, _) in enumerate(ext2):
        for J1, d1, f1, _ in ext1:
            if d1 == d and _strictly_inside(f2, J1, f1, d):
                busy.add(k)
    cands = []
    for k in sorted(busy):
        J, d, _, _ = ext2[k]
        nxt = mesh2.march(J[0], J[1], d, 1)
        if nxt:
            cands.append((J, nxt[0], d))
    return sorted(set(cands))


def add_edge(mesh, cand):
    (i0, j0), (i1, j1), d = cand
    if d in "RL":
        mesh.add_h(i0, i1, j0)
    else:
        mesh.add_v(i0, j0, j1)


def refine(mesh1, request):
    """Scott, Li, Sederberg and Hughes's local refinement.

    mesh1 must be analysis-suitable. request is a list of ("h", i0, i1, j) and
    ("v", i, j0, j1) segments. Returns (mesh2, M, added) where M[A][B] is the
    coefficient of the new function B in the old function A, and added lists
    the insertion edges in the order they were added.
    """
    ext1 = face_extensions_and_junctions(mesh1)
    mesh2 = mesh1.copy()  # @line L1
    for seg in request:
        if seg[0] == "h":
            mesh2.add_h(seg[1], seg[2], seg[3])
        else:
            mesh2.add_v(seg[1], seg[2], seg[3])
    W, _ = coupled_weight(ext1, mesh2)  # @line L2
    added = []
    while W > 0:  # @line L3
        best = None
        for cand in insertion_edges(ext1, mesh2):  # @line L4
            trial = mesh2.copy()
            add_edge(trial, cand)
            w, _ = coupled_weight(ext1, trial)
            if best is None or w < best[0]:  # @line L5
                best = (w, cand)
        add_edge(mesh2, best[1])  # @line L6
        W = best[0]
        added.append(best[1])
    return mesh2, refinement_operator(mesh1, mesh2), added


def insert_one(knots, x, values):
    """Boehm's rule for one cubic B-spline with index knots; see the t-spline page."""
    tau = sorted(list(knots) + [x])
    t = [values[k] for k in knots]
    u = values[x]
    c0 = Fraction(1) if u >= t[3] else (u - t[0]) / (t[3] - t[0])
    c1 = Fraction(1) if u <= t[1] else (t[4] - u) / (t[4] - t[1])
    return [(c0, tuple(tau[:5])), (c1, tuple(tau[1:]))]


def refine_vector(knots, lines, values):
    """Write B[knots] in the B-splines on knots plus lines: {5 index knots: coefficient}."""
    funcs = {tuple(knots): Fraction(1)}
    for x in sorted(lines):
        nxt = {}
        for kn, c in funcs.items():
            parts = insert_one(kn, x, values) if kn[0] < x < kn[-1] and x not in kn else [(1, kn)]
            for c2, k2 in parts:
                if c2:
                    nxt[k2] = nxt.get(k2, Fraction(0)) + c * c2
        funcs = nxt
    return funcs


def refinement_operator(mesh1, mesh2):
    """M[A][B] with N_A (old) = sum_B M[A][B] N_B (new), by basis function refinement.

    For each pair with the index domain of B inside that of A, the knots of B
    are inserted into the local knot vectors of A, and the coefficient of the
    piece that equals N_B is taken. The coefficient of a fine B-spline depends
    only on the coarse knots and its own knots (the discrete B-splines of the
    Oslo algorithm), so one pair at a time gives the right value. Whether the
    sum reproduces N_A is the nesting property, which the tests check.
    """
    old, new = mesh1.functions(), mesh2.functions()
    M = {}
    for A, (sA, tA) in old.items():  # @line L7
        row = {}
        for B, (sB, tB) in new.items():
            if sA[0] <= sB[0] and sB[-1] <= sA[-1] and tA[0] <= tB[0] and tB[-1] <= tA[-1]:
                ds = refine_vector(sA, set(sB) - set(sA), mesh2.sv)  # @line L8
                dt = refine_vector(tA, set(tB) - set(tA), mesh2.tv)
                c = ds.get(sB, 0) * dt.get(tB, 0)  # @line L9
                if c:
                    row[B] = c  # @line L10
        M[A] = row
    return M


def new_control_points(M, Q):
    """Homogeneous control points of the new mesh: Q_B = sum_A M[A][B] Q_A."""
    out = {}
    for A, row in M.items():
        for B, c in row.items():
            acc = out.setdefault(B, [Fraction(0)] * len(Q[A]))
            for k, q in enumerate(Q[A]):
                acc[k] += c * q
    return {B: tuple(v) for B, v in out.items()}  # @line L11


def bspline(knots, x, last=None):
    """Cubic B-spline (degree len - 2) on the knot values at x, by Cox-de Boor."""
    p = len(knots) - 2
    x = Fraction(x)
    vals = [Fraction(int(a <= x < b or (last is not None and a < b == last == x))) for a, b in zip(knots, knots[1:])]
    for d in range(1, p + 1):
        vals = [
            (((x - knots[k]) / (knots[k + d] - knots[k]) * vals[k]) if knots[k + d] != knots[k] else 0)
            + (((knots[k + d + 1] - x) / (knots[k + d + 1] - knots[k + 1]) * vals[k + 1]) if knots[k + d + 1] != knots[k + 1] else 0)
            for k in range(len(vals) - 1)
        ]
    return vals[0]


def blend(mesh, idx, s, t):
    si, ti = idx
    return bspline([mesh.sv[k] for k in si], s, mesh.sv[-1]) * bspline([mesh.tv[k] for k in ti], t, mesh.tv[-1])


def evaluate(mesh, Q, s, t):
    """The surface from homogeneous control points Q (dict on anchors), projected."""
    acc = None
    for A, idx in mesh.functions().items():
        b = blend(mesh, idx, s, t)
        if b:
            term = [b * q for q in Q[A]]
            acc = term if acc is None else [x + y for x, y in zip(acc, term)]
    return tuple(x / acc[-1] for x in acc[:-1])
test_t_spline_local_refinement.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t-spline-local-refinement/. The authors are listed in prov/WVHYV3.jsonl.

import random
from fractions import Fraction as F

from t_spline_local_refinement import (
    TMesh,
    blend,
    coupled_weight,
    evaluate,
    face_extensions_and_junctions,
    is_analysis_suitable,
    new_control_points,
    refine,
    refine_vector,
)

HALF = [F(0)] * 4 + [F(k, 2) for k in range(1, 8)] + [F(4)] * 4  # lines 0..14
QUARTER = [F(0)] * 4 + [F(k, 4) for k in range(1, 16)] + [F(4)] * 4  # lines 0..22


def coarse(vals, step):
    """The tensor mesh on the integer knot values; the other lines are not in the mesh."""
    mesh = TMesh(vals, vals)
    m = len(vals) - 1
    lines = [0, 1, 2] + list(range(3, m - 2, step)) + [m - 2, m - 1, m]
    mesh.add_lines(lines, lines)
    return mesh


def global_coefficients(mesh, idx):
    """Reference: the coefficients of a blending function in the tensor B-splines on all lines."""
    s, t = idx
    ds = refine_vector(s, set(range(s[0], s[-1] + 1)) - set(s), mesh.sv)
    dt = refine_vector(t, set(range(t[0], t[-1] + 1)) - set(t), mesh.tv)
    return {(a, b): ca * cb for a, ca in ds.items() for b, cb in dt.items()}


def rank(cols):
    keys = sorted({k for c in cols for k in c})
    A = [[c.get(k, F(0)) for c in cols] for k in keys]
    r = 0
    for c in range(len(cols)):
        piv = next((i for i in range(r, len(A)) 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, len(A)):
            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


def face_cross(mesh, i, j):
    """Request to split the face that contains the unit cell (i, j) into four, or None."""
    left = max(k for k in range(0, i + 1) if (k, j) in mesh.v)
    right = min(k for k in range(i + 1, mesh.m + 1) if (k, j) in mesh.v)
    bottom = max(k for k in range(0, j + 1) if (i, k) in mesh.h)
    top = min(k for k in range(j + 1, mesh.n + 1) if (i, k) in mesh.h)
    if right - left < 2 or top - bottom < 2:
        return None
    mi, mj = (left + right) // 2, (bottom + top) // 2
    return [("v", mi, bottom, top), ("h", left, right, mj)]


def check_nested(T1, T2, M):
    old, new = T1.functions(), T2.functions()
    for A, idx in old.items():
        lhs = global_coefficients(T1, idx)
        rhs = {}
        for B, c in M[A].items():
            for k, v in global_coefficients(T2, new[B]).items():
                rhs[k] = rhs.get(k, F(0)) + c * v
        assert {k: v for k, v in rhs.items() if v} == lhs


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


def test_one_split_face_needs_two_insertion_edges():
    T1 = coarse(HALF, 2)
    assert is_analysis_suitable(T1) and len(T1.anchors()) == 49
    request = [("v", 6, 5, 7), ("h", 5, 7, 6)]
    T = T1.copy()
    T.add_v(6, 5, 7)
    T.add_h(5, 7, 6)
    assert not is_analysis_suitable(T)  # the extensions meet at the centre (6, 6)
    T2, M, added = refine(T1, request)
    assert added == [((5, 6), (3, 6), "L"), ((7, 6), (9, 6), "R")]
    assert is_analysis_suitable(T2) and len(T2.anchors()) == 56
    assert T1.h <= T2.h and T1.v <= T2.v and T.h <= T2.h and T.v <= T2.v
    check_nested(T1, T2, M)
    row = {B: c for B, c in M[(5, 5)].items()}
    assert row == {(5, 5): F(9, 16), (6, 5): F(3, 8), (5, 6): F(3, 8), (6, 6): F(1, 4)}
    assert sum(1 for A in M if M[A] != {A: 1}) == 16


def test_an_l_junction_is_not_analysis_suitable():
    T = coarse(HALF, 2)
    T.add_v(6, 5, 6)  # from the bottom of the face to its centre
    T.add_h(6, 7, 6)  # from the centre to the right side of the face
    ext = face_extensions_and_junctions(T)
    assert any(J == (6, 6) and d == "U" for J, d, _, _ in ext)
    assert any(J == (6, 6) and d == "L" for J, d, _, _ in ext)
    assert not is_analysis_suitable(T)


def test_analysis_suitable_is_not_enough_for_nesting():
    T1, _, _ = refine(coarse(HALF, 2), [("v", 6, 5, 7), ("h", 5, 7, 6)])
    T2 = T1.copy()
    T2.add_h(0, T2.m, 4)  # a full line through the face extension of (6, 5)
    assert is_analysis_suitable(T2)
    w, _ = coupled_weight(face_extensions_and_junctions(T1), T2)
    assert w > 0  # a loop edge
    new = [global_coefficients(T2, idx) for idx in T2.functions().values()]
    old = global_coefficients(T1, T1.functions()[(6, 5)])
    assert rank(new + [old]) == rank(new) + 1  # the old function is not in the new space
    T3, M, _ = refine(T1, [("h", 0, T1.m, 4)])
    assert is_analysis_suitable(T3)
    check_nested(T1, T3, M)


def test_random_refinements_stay_analysis_suitable_and_nested():
    rng = random.Random(5)
    T = coarse(QUARTER, 4)
    for _ in range(4):
        req = None
        while req is None:
            req = face_cross(T, rng.randint(3, 18), rng.randint(3, 18))
        T2, M, _ = refine(T, req)
        assert is_analysis_suitable(T2)
        assert T.h <= T2.h and T.v <= T2.v
        check_nested(T, T2, M)
        T = T2


def test_refined_surface_is_unchanged_and_basis_sums_to_one():
    rng = random.Random(6)
    T = coarse(QUARTER, 4)
    Q = {A: (F(rng.randint(-20, 20)), F(rng.randint(-20, 20)), F(rng.randint(-20, 20)), F(rng.randint(1, 4))) for A in T.anchors()}
    Q = {A: (x * w, y * w, z * w, w) for A, (x, y, z, w) in Q.items()}  # homogeneous
    pts = random_points(rng, 6) + [(F(1), F(1)), (F(3, 2), F(5, 4)), (F(4), F(4))]
    before = [evaluate(T, Q, s, t) for s, t in pts]
    for _ in range(3):
        req = None
        while req is None:
            req = face_cross(T, rng.randint(3, 18), rng.randint(3, 18))
        T2, M, _ = refine(T, req)
        Q = new_control_points(M, Q)
        assert set(Q) == set(T2.anchors())
        assert [evaluate(T2, Q, s, t) for s, t in pts] == before
        funcs = T2.functions()
        for s, t in pts:
            assert sum(blend(T2, idx, s, t) for idx in funcs.values()) == 1
        T = T2

History

Sederberg, Cardon, Finnigan, North, Zheng and Lyche gave the first local refinement of T-splines in 2004. Buffa, Cho and Sangalli showed in 2010 that T-spline blending functions can be linearly dependent, and Li, Zheng, Sederberg, Hughes and Scott answered with analysis-suitable T-splines. Scott, Li, Sederberg and Hughes then gave this refinement, which keeps the class of analysis-suitable T-splines and the nesting of the spaces, in a 2011 ICES report and in Computer Methods in Applied Mechanics and Engineering in 2012. Li and Scott proved the nesting theorem and the approximation properties in 2014.

References

  1. Michael A. Scott, Xin Li, Thomas W. Sederberg and Thomas J. R. Hughes, Local refinement of analysis-suitable T-splines, Computer Methods in Applied Mechanics and Engineering 213-216 (2012), 206 to 222, Section 3.1 (face and edge extensions), Section 3.3 (analysis-suitable T-meshes by the extended T-mesh), Section 4.1 (nested T-spline spaces and the coupled extension graph), Section 4.2 (the refinement algorithm, steps 1 to 5, and the greedy choice of insertion edges), Section 4.3 (the refinement matrix computed one pair of functions at a time)
  2. Xin Li and Michael A. Scott, Analysis-suitable T-splines, characterization, refineability, and approximation, Mathematical Models and Methods in Applied Sciences 24(6) (2014), 1141 to 1164, the proof that analysis-suitable T-spline spaces are nested when the extended T-meshes are nested (general locator)
  3. 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, Definition 7 (analysis-suitable T-meshes) and Theorem 18 (their blending functions are linearly independent)
  4. 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 earlier local refinement by blending function refinement (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.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)
WritingW2 basic
  • a scene preset for the example