Algorithm Search⌘K

Algorithmadvanced

Generic naming of topological entities

Also called Capoyleas-Chen-Hoffmann naming.

Capoyleas, Chen and Hoffmann's scheme that names each face, edge and vertex by the features and operations that made it plus local context, so names survive edits.

Time
O(n L^2) worst
Space
O(n L) extra
Where
L = the length of the longest boundary cycle; n = the number of boundary edges of the model
Properties
deterministicexactiterative
Origin
Vasilis Capoyleas, Xiangping Chen, Christoph M. Hoffmann, 1996

Generic naming gives each face, edge and vertex of a history-based model a name that does not depend on how the kernel happened to store it. The name records the operation that made the entity and the generator inside that operation. For example, "the side face that extrusion 2 swept from line 3 of its sketch". When this generative part does not single out one entity, the name is extended with the names of neighbouring entities until it does. After the designer edits a parameter and the history is replayed, every reference resolves its name in the new model by finding the entities with the same name. Capoyleas, Chen and Hoffmann gave the scheme in 1996 as an answer to the persistent naming problem. This page gives a planar version. The model is a rectangle cut by rectangles and patterns of rectangles. Each edge is labelled by the rectangle side it lies on and named by the labels of the edges around it on its boundary cycle. The page proves exactly when names survive. If the old and new boundaries are isomorphic as labelled cycles, every name resolves to its images under all such isomorphisms: one entity when the name was unique, and the full set of symmetric candidates when it was not.

In plain words

A designer cuts a slot into the top of a block, so the top edge breaks into two pieces. Later a rounding is attached to the left piece. How does the program remember which piece?

It cannot say "piece number 2", because numbers change when the model is rebuilt. It can say "a piece of the block's top". But there are two such pieces. So it adds what is next to it: "the piece of the block's top that has the slot's left wall on one side and the block's left side on the other". After the designer widens the block or moves the slot, the program rebuilds the model and looks for an edge with this description. There is still exactly one.

If the pieces are true twins, like the pieces between identical slots, no description tells them apart. The program should then report all of them.

The problem

Input. A model MM built by a history, and a model M′M' built by the same history after an edit of its parameters. In the planar toy, the history is a base rectangle followed by cut operations. Each operation is one rectangle or a pattern of copies, and the part is the base minus the cuts. The boundary of the part is a set of cycles of edges, with the material on the left.

Labels. Each edge lies on one side of one rectangle. Its label is the pair (operation, side), such as (cut 1, left). Distinct coordinates for distinct sides make this well defined. Labels are generative: they depend only on the history, not on the coordinates. A cut can split one side into several edges with the same label, and the copies of a pattern share their labels.

Output. A name for each edge and vertex of MM, and a resolution rule that maps a name and M′M' to a set of entities of M′M'. The goal is that a name resolves to the entity "with the same role" in M′M'. Here that is made precise. An isomorphism from MM to M′M' is a bijection between their boundary cycles, with a rotation of each cycle, that keeps every label. The correct answer for an edge ee is the set of its images σ(e)\sigma(e) over all isomorphisms σ\sigma. This set is a single edge when ee has no symmetric twin, and a set of twins otherwise. If no isomorphism exists, the topology has changed, and no answer is claimed.

The algorithm

The window of radius rr of an edge ee on a cycle of length LL is the tuple of the labels of the 2r+12r + 1 edges centred on ee, going around the cycle. When 2r+1>L2r + 1 > L the window wraps around, and then it also records LL. The level of ee is the least rr at which its window is unique among all edges of MM. If no window is unique up to the length of the longest cycle, the level is that length. The name of ee is its level and its window at that level. A vertex is named by the names of the edge before it and the edge after it.

  1. NAME-EDGES(M)
  2. 1for r ← 0, 1, ... while some edge has no level and r ≤ the longest cycle length do
  3. 2count the windows of radius r over all edges of M
  4. 3for each edge e with no level yet do
  5. 4if window_r(e) occurs once, or r is the longest cycle length, then level(e) ← r
  6. 5return name(e) = (level(e), window_level(e)(e)) for every edge e
  7. RESOLVE-EDGE((r, w), M')
  8. 6return the edges e' of M' with window_r(e') = w
  9. NAME-VERTEX(v) and RESOLVE-VERTEX
  10. 7name(v) ← (name of the edge before v, name of the edge after v)
  11. 8return the vertices of M' whose edge before resolves from the first name
  12. and whose edge after resolves from the second

The level-0 window is the generative label alone, which is the name of most edges. The level-1 window adds the two neighbours, which is enough to tell apart the pieces of a side split by one cut. Higher levels are needed only when a pattern or several cuts repeat the same local picture.

Example

The base is [0,10]×[0,6][0, 10] \times [0, 6] and cut 1 is [4,6]×[3,8][4, 6] \times [3, 8], a slot through the top. The part has one boundary cycle of 8 edges, listed counterclockwise from the bottom:

edge label level name
(0,0)(0,0) to (10,0)(10,0) base bottom 0 base bottom
(10,0)(10,0) to (10,6)(10,6) base right 0 base right
(10,6)(10,6) to (6,6)(6,6) base top 1 (base right, base top, cut 1 right)
(6,6)(6,6) to (6,3)(6,3) cut 1 right 0 cut 1 right
(6,3)(6,3) to (4,3)(4,3) cut 1 bottom 0 cut 1 bottom
(4,3)(4,3) to (4,6)(4,6) cut 1 left 0 cut 1 left
(4,6)(4,6) to (0,6)(0,6) base top 1 (cut 1 left, base top, base left)
(0,6)(0,6) to (0,0)(0,0) base left 0 base left

The edit changes the base to [0,20]×[0,9][0, 20] \times [0, 9] and the cut to [5,12]×[4,15][5, 12] \times [4, 15]. The new model has the same cycle of labels, so each name resolves to exactly one edge, at the same place in the cycle. The left piece of the top is now the edge from (5,9)(5, 9) to (0,9)(0, 9).

If instead the cut becomes [4,6]×[3,5][4, 6] \times [3, 5], a pocket that no longer reaches the top, then the top is one edge again. Both names of level 1 resolve to nothing. That is the right answer, since the piece no longer exists. The level-0 label "base top" would find the whole top edge, which a modeler can offer as a repair.

With a pattern of three through slots [4,5][4, 5], [9,10][9, 10] and [14,15][14, 15] across [0,20]×[0,10][0, 20] \times [0, 10], the part falls into four pieces. The two middle pieces both have the cycle (base bottom, cut 1 left, base top, cut 1 right). Their 8 edges have no unique window at any level. Each gets the top level 4 and resolves to 2 edges, which are its images under the two isomorphisms that swap or keep the middle pieces. The other 8 edges are unique at level 0 or 1.

Correctness

The proof file proves:

  1. Windows are invariant. An isomorphism σ\sigma keeps labels, cycle lengths and the cyclic order, so windowr(σ(e))=windowr(e)\mathrm{window}_r(\sigma(e)) = \mathrm{window}_r(e) for every rr.
  2. Names resolve to the images. Suppose MM and M′M' are isomorphic by some σ0\sigma_0. The edges of M′M' with window ww at radius rr are exactly σ0\sigma_0 applied to the edges of MM with window ww. If the name of ee is unique in MM, it resolves to {σ0(e)}\{\sigma_0(e)\}, and every isomorphism agrees there. If it is not unique, the level is the top level. Then the window holds the cycle length and the whole cycle read from ee, and the edges of MM with that window are exactly the images of ee under the automorphisms of MM. So in both cases line L6 returns {σ(e):σ an isomorphism}\{\sigma(e) : \sigma \text{ an isomorphism}\}.
  3. Vertices follow. An isomorphism maps the vertex between aa and its successor to the vertex between σ(a)\sigma(a) and σ(a)\sigma(a)'s successor, so line L8 returns the images of the vertex.
  4. Order-preserving edits keep every name. If an edit keeps the order of all xx coordinates and of all yy coordinates, the code builds the same grid, cells, cycles and labels from the ranks. So the identity is an isomorphism, and each name resolves to a set that contains the edge at the same grid position, which is that edge alone when the name is unique.

The tests check these claims against a brute-force oracle. The oracle tries every bijection between the cycles of the two models and every rotation of each cycle, keeps those that preserve all labels, and collects the images of every edge. Random histories have up to 3 operations, each a single rectangle or a pattern of 2 or 3 copies, and some cut through the whole part. For 150 histories with an order-preserving change of all coordinates, every edge and vertex name must resolve to exactly the oracle's images, which must include the same grid edge. For 250 histories whose coordinates all move by up to 3, the same must hold whenever the oracle finds an isomorphism. That was 61 of them, and the other 189 changed the topology. The tests also check that the boundary cycles enclose the same area as the inside grid cells.

Proof: Generic names resolve to the images of an entity under every label-preserving isomorphism, and naming terminatesfull

We use the notation and the pseudocode of the page. A model MM is a finite set of cycles. Cycle CC has a length LC≥1L_C \ge 1 and a sequence of labels C[0],…,C[LC−1]C[0], \dots, C[L_C - 1], with indices taken modulo LCL_C. An edge is a pair (C,i)(C, i), and its successor is next(C,i)=(C,i+1)\mathrm{next}(C, i) = (C, i + 1). A vertex is a pair (a,next(a))(a, \mathrm{next}(a)) of an edge and its successor.

The window of radius rr of e=(C,i)e = (C, i) is

windowr(e)=(λr(LC), (C[i−r],C[i−r+1],…,C[i+r])),\mathrm{window}_r(e) = \bigl(\lambda_r(L_C),\ (C[i - r], C[i - r + 1], \dots, C[i + r])\bigr),

where λr(L)=L\lambda_r(L) = L if 2r+1>L2r + 1 > L and λr(L)=0\lambda_r(L) = 0 otherwise. Let T(M)T(M) be the largest cycle length of MM.

An isomorphism σ:M→M′\sigma : M \to M' is a bijection π\pi from the cycles of MM onto those of M′M', together with a shift sCs_C for each cycle CC of MM, such that Lπ(C)=LCL_{\pi(C)} = L_C and π(C)[i+sC]=C[i]\pi(C)[i + s_C] = C[i] for all ii. It acts on edges by σ(C,i)=(π(C),i+sC)\sigma(C, i) = (\pi(C), i + s_C) and on vertices by σ(a,b)=(σ(a),σ(b))\sigma(a, b) = (\sigma(a), \sigma(b)). An isomorphism from MM to itself is an automorphism. Isomorphisms compose, and their inverses are isomorphisms.

Lemma 1 (windows are invariant). For every isomorphism σ\sigma, every edge ee and every r≥0r \ge 0, windowr(σ(e))=windowr(e)\mathrm{window}_r(\sigma(e)) = \mathrm{window}_r(e). Also σ(next(e))=next(σ(e))\sigma(\mathrm{next}(e)) = \mathrm{next}(\sigma(e)).

Proof. Let e=(C,i)e = (C, i). Then σ(e)=(π(C),i+sC)\sigma(e) = (\pi(C), i + s_C), and Lπ(C)=LCL_{\pi(C)} = L_C, so the first components agree. For −r≤d≤r-r \le d \le r, the label at offset dd is π(C)[i+sC+d]=C[i+d]\pi(C)[i + s_C + d] = C[i + d]. The second claim is (π(C),i+1+sC)=next(π(C),i+sC)(\pi(C), i + 1 + s_C) = \mathrm{next}(\pi(C), i + s_C). □\square

Lemma 2 (the top window determines the orbit). Let R≥T(M)R \ge T(M), and let ee and ff be edges of MM. Then windowR(e)=windowR(f)\mathrm{window}_R(e) = \mathrm{window}_R(f) if and only if α(e)=f\alpha(e) = f for some automorphism α\alpha of MM.

Proof. If α(e)=f\alpha(e) = f, the windows are equal by Lemma 1. Conversely, let e=(C,i)e = (C, i) and f=(D,j)f = (D, j) have equal windows. Since 2R+1>R≥LC2R + 1 > R \ge L_C, the first component of windowR(e)\mathrm{window}_R(e) is LCL_C, and likewise for ff, so LC=LD=LL_C = L_D = L. The offsets 0,1,…,L−10, 1, \dots, L - 1 all lie in [−R,R][-R, R], so C[i+d]=D[j+d]C[i + d] = D[j + d] for 0≤d<L0 \le d < L, and so for all dd by periodicity. Define α\alpha as follows. If C=DC = D, it shifts CC by j−ij - i and fixes the other cycles. If C≠DC \ne D, it maps CC to DD with shift j−ij - i, maps DD to CC with shift i−ji - j, and fixes the other cycles. In both cases each shifted cycle keeps its labels, by the identity C[i+d]=D[j+d]C[i + d] = D[j + d]. So α\alpha is an automorphism with α(e)=f\alpha(e) = f. □\square

Lemma 3 (levels). Line L4 gives each edge ee of MM a level ℓ(e)≤T(M)\ell(e) \le T(M). Either windowℓ(e)(e)\mathrm{window}_{\ell(e)}(e) occurs exactly once among the edges of MM, or ℓ(e)=T(M)\ell(e) = T(M).

Proof. The loop of lines L1 to L4 runs r=0,1,…r = 0, 1, \dots while some edge is pending and r≤T(M)r \le T(M). At r=T(M)r = T(M), line L4 assigns a level to every pending edge. So every edge gets a level, the loop stops after at most T(M)+1T(M) + 1 rounds, and the level is the first rr at which the window was unique or the top was reached. □\square

Theorem 1 (edge names resolve to the images). Let σ0:M→M′\sigma_0 : M \to M' be an isomorphism, and let ee be an edge of MM with name (r,w)(r, w), where r=ℓ(e)r = \ell(e) and w=windowr(e)w = \mathrm{window}_r(e). Then line L6 returns

RESOLVE((r,w),M′)={σ(e):σ an isomorphism from M to M′}.\mathrm{RESOLVE}((r, w), M') = \{\sigma(e) : \sigma \text{ an isomorphism from } M \text{ to } M'\}.

If ww occurs once in MM, this set is the single edge σ0(e)\sigma_0(e).

Proof. Let Ew={f∈M:windowr(f)=w}E_w = \{f \in M : \mathrm{window}_r(f) = w\}. By Lemma 1, applied to σ0\sigma_0 and to σ0−1\sigma_0^{-1}, the edges of M′M' with window ww at radius rr are exactly σ0(Ew)\sigma_0(E_w). So line L6 returns σ0(Ew)\sigma_0(E_w).

Every isomorphism σ:M→M′\sigma : M \to M' has the form σ0∘α\sigma_0 \circ \alpha with α=σ0−1∘σ\alpha = \sigma_0^{-1} \circ \sigma an automorphism of MM, and every such composition is an isomorphism. So the right side is σ0(Oe)\sigma_0(O_e), where Oe={α(e):α an automorphism of M}O_e = \{\alpha(e) : \alpha \text{ an automorphism of } M\}. It remains to show Ew=OeE_w = O_e. By Lemma 3 there are two cases.

The window is unique. Then Ew={e}E_w = \{e\}. By Lemma 1 every automorphism keeps the window of ee, so it maps ee into EwE_w, and Oe={e}O_e = \{e\}.

The level is the top. Then r=T(M)r = T(M), and Lemma 2 gives Ew=OeE_w = O_e directly.

In both cases line L6 returns σ0(Oe)\sigma_0(O_e), which is the set of images. In the unique case it is {σ0(e)}\{\sigma_0(e)\}. □\square

Corollary 1 (vertices). Under the same hypothesis, let v=(a,b)v = (a, b) be a vertex of MM, so b=next(a)b = \mathrm{next}(a). Then line L8 returns {σ(v):σ an isomorphism from M to M′}\{\sigma(v) : \sigma \text{ an isomorphism from } M \text{ to } M'\}.

Proof. By Theorem 1, the two resolved sets are A={σ(a)}A = \{\sigma(a)\} and B={σ(b)}B = \{\sigma(b)\}, each over all isomorphisms σ\sigma. Line L8 returns the vertices (x,next(x))(x, \mathrm{next}(x)) of M′M' with x∈Ax \in A and next(x)∈B\mathrm{next}(x) \in B. For any σ\sigma, the vertex σ(v)=(σ(a),σ(b))\sigma(v) = (\sigma(a), \sigma(b)) equals (σ(a),next(σ(a)))(\sigma(a), \mathrm{next}(\sigma(a))) by Lemma 1, and its two edges lie in AA and BB. Conversely, if x=σ(a)∈Ax = \sigma(a) \in A, then next(x)=σ(b)\mathrm{next}(x) = \sigma(b) by Lemma 1, so the returned vertex is σ(v)\sigma(v). □\square

Corollary 2 (order-preserving edits). Let M′M' be built from the same history as MM by a change of coordinates that keeps the strict order of all xx values and of all yy values. Then the identity on grid positions is an isomorphism. So each edge name resolves to a set that contains the edge at the same grid position, and to that edge alone when the name was unique in MM.

Proof. The construction depends on the coordinates only through comparisons. The owner of each value is fixed by the history, and the sorted lists xsxs and ysys list the same owners in the same order. A grid cell (i,j)(i, j) is inside when its doubled centre xs[i]+xs[i+1]xs[i] + xs[i + 1] lies strictly between 2a2a and 2c2c for the base, and not for any cut (a,b,c,d)(a, b, c, d), and likewise in yy. For a grid value aa, the test 2a<xs[i]+xs[i+1]2a < xs[i] + xs[i + 1] holds exactly when a≤xs[i]a \le xs[i], since aa is not strictly between consecutive grid values. So it is a comparison of ranks, and the same holds for the other three tests. The set of inside cells is therefore the same in index space. The directed unit segments, their labels and the tracing by turn rank use only indices, so they produce the same cycles in the same order. The identity on (C,i)(C, i) is then an isomorphism, and Theorem 1 applies with σ0\sigma_0 the identity. □\square

Termination. Lemma 3 bounds the naming loop by T(M)+1T(M) + 1 rounds of O(n)O(n) windows each. Tracing a cycle marks each directed unit segment as used once, and the walk stops when it returns to a used segment. Each walk starts at an unused segment, so the number of steps is the number of segments. The merge loop advances kk while consecutive keys agree. That loop stops, because a boundary cycle of an axis-parallel region turns at least four times, so not all keys are equal. Resolution scans the edges or vertices once. □\square

What is not claimed. If no isomorphism from MM to M′M' exists, the topology has changed, and the theorems say nothing. A name may then resolve to nothing, to one edge or to several, and whether that edge is "the same" is a question of the designer's intent. The proof is also about labelled cycles only. Two models with isomorphic labelled boundaries but different shapes are treated as the same, which is the generative view the scheme takes.

Complexity

Let nn be the number of edges and LL the length of the longest cycle. Level rr computes nn windows of length 2r+12r + 1, so it costs O(nr)O(n r) time with hashing, and the levels up to LL cost O(nL2)O(n L^2) in the worst case. Most edges stop at level 0 or 1, so the typical cost is O(n)O(n). Resolving one name costs O(nL)O(n L). The names take O(nL)O(n L) space. Building the toy model from cc rectangles takes O(c3)O(c^3) time on its O(c2)O(c^2) grid cells.

These bounds are for the planar toy. In a solid modeler, names are built over the face adjacency graph, and extending a name by neighbours is a bounded-radius neighbourhood in a graph. The cost depends on how the kernel records the generators of each face during the replay, and the papers give no general bound.

Properties

  • Deterministic and exact. Names are tuples of labels, with integer coordinates only in the geometry of the toy.
  • Generative. A name depends on the history and the topology, not on coordinates or storage order. Geometry enters only through the topology it produces.
  • Honest about symmetry. A name that cannot be made unique resolves to all candidates, rather than to an arbitrary one.
  • Local. An edge whose label is unique keeps its name under any edit that keeps its label in the model, even if the topology elsewhere changes.

Variants and improvements

  • Names in three dimensions. Capoyleas, Chen and Hoffmann name a face by its feature and generator, such as the sketch entity that an extrusion sweeps, or the start and end caps. They name an edge by the faces that meet at it, and a vertex by its faces or edges. When two faces meet along several edges, an edge name is extended by the faces at its ends. When a face is split, the pieces are told apart by their neighbours.
  • Topological ID. Kripac's mechanism is close in spirit. It also names faces by feature and generator and edges and vertices by their faces, and it records the history of splits and merges.
  • Geometric tie-breaking. When the topology leaves a tie, as with the twins of a pattern, many systems break it by geometry: the piece nearest to the old position, or on a given side of a reference plane. This picks one entity, which is right more often than not, but the choice is a heuristic and is not proved.
  • Graph matching. Without generative labels, the resolution is a matching of attributed adjacency graphs, a form of graph isomorphism or maximum common subgraph. The labels make that matching easy here. The windows play the role of the colours of Weisfeiler-Leman refinement on a cycle.
  • Faster windows. On a cycle, the windows of all edges at all radii come from one pass of string matching on the doubled cycle, and canonical rotations come from Booth's algorithm. This removes the factor LL from the time per level.

When to use it

Use generic naming in a history-based modeler, whenever later features refer to entities made by earlier ones: fillets on edges, sketches on faces, holes on faces, constraints between faces. It works best when most entities have a unique generator. A face swept from one sketch line usually does. Splits and patterns are the cases where the extension by neighbours matters. In direct modeling, where there is no history to replay, entities can keep their identity through the edit, and naming is less critical.

Pitfalls

  • A unique name is not a correct name. After a topological change, a name can resolve to one entity that is not the one the designer meant. For example, a level-0 label resolves to the merged top edge, which is longer than the old piece. The scheme proves correctness only when the boundaries are isomorphic.
  • Picking one of several. A resolution that returns several candidates must be shown to the user or handled by a stated rule. Picking the first one silently moves a feature to a twin.
  • Labels from storage order. If the generator is recorded as "the third curve the kernel created" rather than "line 3 of the sketch", the names change on replay, and the scheme fails from the start.
  • Too small a neighbourhood. Stopping at level 1 when two pieces still share their window leaves a tie that a larger radius would break.
  • Too large a neighbourhood. A name that includes far-away entities breaks when something far away changes. Extend only as far as uniqueness needs, as line L4 does.

Implementations

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.

generic_naming_scheme.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generic-naming-scheme/. The authors are listed in prov/5S5Z62.jsonl.

"""Generic names for the edges and vertices of a toy planar modeler.

The modeler builds a part from a history: a base rectangle, then a list of
cut operations, each one rectangle or a pattern of several rectangles. The
part is the base minus the open cuts, and its
boundary is a set of cycles of axis-parallel edges, with the material on the
left. Every edge lies on one side of one rectangle of the history, and that
(operation, side) pair is its generative label. A cut can split a side into
several edges with the same label, and the copies of a pattern share their
labels, so the label alone is not a name.

The naming step follows Capoyleas, Chen and Hoffmann: the name of an entity
is the operation and the generator that made it, extended by the names of
its neighbours until it is unique. Here the neighbours are the edges before
and after it on its boundary cycle. The window of radius r of an edge is the
tuple of the labels of the 2r + 1 edges centred on it; once the window wraps
around the cycle, the cycle length is added. The level of an edge is the
least r at which its window is unique in the model, or the largest cycle
length if no window is unique. A vertex is named by the names of its two
edges.

Resolution computes the windows of the new model at the stored level and
returns every entity with an equal window. If the new model has the same
labelled boundary as the old one, up to the choice of the start of each
cycle and the order of the cycles, the result is exactly the set of images
of the entity under all label-preserving isomorphisms: one entity when the
name was unique, and all the symmetric candidates otherwise.

Precondition: the coordinates of all rectangles are integers, two x-sides
or two y-sides share a coordinate only if they are the same side of copies
in one pattern, and the copies of a pattern do not overlap.
Cost: for c cut rectangles the part has O(c^2) grid cells, built in O(c^3)
time, and the boundary has n = O(c^2) edges. Naming takes O(n L^2) time for
the largest cycle length L <= n, since level r costs O(n r), and resolving
one name takes O(n L).
"""

from __future__ import annotations

from typing import Sequence

Label = tuple[str, str]
Rect = tuple[int, int, int, int]          # x0, y0, x1, y1


class Part:
    """The boundary of base minus cuts, as cycles of labelled edges."""

    def __init__(self, base: Rect, ops: Sequence):
        """ops[k] is one rectangle, or a list of rectangles cut by one
        pattern operation, which all get the label of operation k + 1."""
        rects = [("base", base)]
        for k, op in enumerate(ops):
            for r in ([op] if isinstance(op[0], int) else op):
                rects.append(("cut%d" % (k + 1), tuple(r)))
        cuts = [r for name, r in rects[1:]]
        owner_x: dict[int, Label] = {}
        owner_y: dict[int, Label] = {}
        for name, (x0, y0, x1, y1) in rects:
            assert x0 < x1 and y0 < y1
            for v, side, own in ((x0, "left", owner_x), (x1, "right", owner_x),
                                 (y0, "bottom", owner_y), (y1, "top", owner_y)):
                assert own.get(v, (name, side)) == (name, side), "coordinates must be distinct"
                own[v] = (name, side)
        xs, ys = sorted(owner_x), sorted(owner_y)
        self.xs, self.ys = xs, ys

        def inside(i, j):
            if not (0 <= i < len(xs) - 1 and 0 <= j < len(ys) - 1):
                return False
            cx, cy = xs[i] + xs[i + 1], ys[j] + ys[j + 1]   # twice the centre
            x0, y0, x1, y1 = base
            if not (2 * x0 < cx < 2 * x1 and 2 * y0 < cy < 2 * y1):
                return False
            return not any(2 * a < cx < 2 * c and 2 * b < cy < 2 * d for a, b, c, d in cuts)

        self.cells = {(i, j) for i in range(len(xs) - 1) for j in range(len(ys) - 1) if inside(i, j)}
        # unit boundary segments between grid nodes, directed with material on the left
        succ: dict[tuple[int, int], list[tuple[int, int]]] = {}
        seg_label: dict[tuple, Label] = {}

        def add(a, b, lab):
            succ.setdefault(a, []).append(b)
            seg_label[(a, b)] = lab

        for i in range(len(xs)):
            for j in range(len(ys) - 1):
                left, right = inside(i - 1, j), inside(i, j)
                if left and not right:
                    add((i, j), (i, j + 1), owner_x[xs[i]])
                elif right and not left:
                    add((i, j + 1), (i, j), owner_x[xs[i]])
        for i in range(len(xs) - 1):
            for j in range(len(ys)):
                below, above = inside(i, j - 1), inside(i, j)
                if above and not below:
                    add((i, j), (i + 1, j), owner_y[ys[j]])
                elif below and not above:
                    add((i + 1, j), (i, j), owner_y[ys[j]])

        def turn_rank(d_in, d_out):
            # prefer the left turn, then straight, then right: it keeps the
            # boundary of each cell at a pinch vertex in its own cycle
            cr = d_in[0] * d_out[1] - d_in[1] * d_out[0]
            return -cr if cr else 0

        used: set[tuple] = set()
        self.cycles: list[list[Label]] = []        # labels of the edges, in order
        self.edge_geom: list[list[tuple]] = []      # (start node, end node) of each edge
        for a0 in sorted(succ):
            for b0 in sorted(succ[a0]):
                if (a0, b0) in used:
                    continue
                segs = []
                a, b = a0, b0
                while (a, b) not in used:
                    used.add((a, b))
                    segs.append((a, b))
                    d_in = (b[0] - a[0], b[1] - a[1])
                    c = min(succ[b], key=lambda c: turn_rank(d_in, (c[0] - b[0], c[1] - b[1])))
                    a, b = b, c
                # merge runs of segments with one direction and one label into edges
                def key(s):
                    return (s[1][0] - s[0][0], s[1][1] - s[0][1], seg_label[s])
                k = 0
                while key(segs[k - 1]) == key(segs[k]):
                    k += 1
                segs = segs[k:] + segs[:k]
                labels, geom = [], []
                for s in segs:
                    if labels and key(s) == key(prev):
                        geom[-1] = (geom[-1][0], s[1])
                    else:
                        labels.append(seg_label[s])
                        geom.append(s)
                    prev = s
                self.cycles.append(labels)
                self.edge_geom.append(geom)
        self.edges = [(c, i) for c in range(len(self.cycles)) for i in range(len(self.cycles[c]))]

    def area(self) -> int:
        """The area enclosed by the cycles, by the shoelace formula."""
        tot = 0
        for geom in self.edge_geom:
            for (a, b) in geom:
                ax, ay, bx, by = self.xs[a[0]], self.ys[a[1]], self.xs[b[0]], self.ys[b[1]]
                tot += ax * by - bx * ay
        return tot // 2

    def label(self, e) -> Label:
        return self.cycles[e[0]][e[1]]

    def vertices(self):
        """A vertex is the pair (edge before it, edge after it) on a cycle."""
        return [((c, i - 1 if i else len(cyc) - 1), (c, i))
                for c, cyc in enumerate(self.cycles) for i in range(len(cyc))]

    def window(self, e, r: int):
        c, i = e
        cyc = self.cycles[c]
        L = len(cyc)
        return (L if 2 * r + 1 > L else 0, tuple(cyc[(i + d) % L] for d in range(-r, r + 1)))


def name_edges(part: Part) -> dict:
    """The generic name (level, window) of every edge."""
    top = max((len(c) for c in part.cycles), default=0)
    level = {}
    pending = set(part.edges)
    r = 0
    while pending and r <= top:  # @line L1
        count: dict = {}
        for e in part.edges:  # @line L2
            w = part.window(e, r)
            count[w] = count.get(w, 0) + 1
        for e in list(pending):  # @line L3
            if count[part.window(e, r)] == 1 or r == top:  # @line L4
                level[e] = r
                pending.discard(e)
        r += 1
    return {e: (level[e], part.window(e, level[e])) for e in part.edges}  # @line L5


def resolve_edge(name, part: Part) -> set:
    """All edges of part with the given name."""
    r, w = name
    return {e for e in part.edges if part.window(e, r) == w}  # @line L6


def name_vertices(part: Part, edge_names: dict) -> dict:
    return {v: (edge_names[v[0]], edge_names[v[1]]) for v in part.vertices()}  # @line L7


def resolve_vertex(name, part: Part) -> set:
    a, b = resolve_edge(name[0], part), resolve_edge(name[1], part)
    return {v for v in part.vertices() if v[0] in a and v[1] in b}  # @line L8
test_generic_naming_scheme.py 217 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generic-naming-scheme/. The authors are listed in prov/5S5Z62.jsonl.

import random
import unittest
from itertools import permutations

from generic_naming_scheme import Part, name_edges, name_vertices, resolve_edge, resolve_vertex


def isomorphism_images(p1: Part, p2: Part):
    """Brute force: every map of the cycles of p1 onto the cycles of p2, with
    a rotation of each cycle, that preserves all labels. Returns, for each
    edge of p1, the set of its images, or None if there is no such map."""
    if len(p1.cycles) != len(p2.cycles):
        return None
    images = {e: set() for e in p1.edges}
    found = False
    for perm in permutations(range(len(p2.cycles))):
        rots = []
        for c1, c2 in enumerate(perm):
            a, b = p1.cycles[c1], p2.cycles[c2]
            if len(a) != len(b):
                break
            ok = [s for s in range(len(b)) if all(b[(i + s) % len(b)] == a[i] for i in range(len(a)))]
            if not ok:
                break
            rots.append(ok)
        else:
            found = True
            for c1, c2 in enumerate(perm):
                L = len(p1.cycles[c1])
                for i in range(L):
                    for s in rots[c1]:
                        images[(c1, i)].add((c2, (i + s) % L))
    return images if found else None


def distinct(base, ops):
    """Only the same side of copies in one pattern may share a coordinate."""
    owners = {}
    for k, op in enumerate([[base]] + list(ops)):
        for r in op:
            for axis, v, side in (("x", r[0], 0), ("x", r[2], 1), ("y", r[1], 0), ("y", r[3], 1)):
                if owners.setdefault((axis, v), (k, side)) != (k, side):
                    return False
    return True


def perturb(rng, base, ops):
    """A parameter change: every coordinate value moves by at most 3, so
    the topology may or may not change."""
    rects = [base] + [r for op in ops for r in op]
    vals = {v for r in rects for v in r}
    while True:
        m = {v: v + rng.randint(-3, 3) for v in vals}
        nb = (m[base[0]], m[base[1]], m[base[2]], m[base[3]])
        nops = [[(m[a], m[b], m[c], m[d]) for a, b, c, d in op] for op in ops]
        if all(r[0] < r[2] and r[1] < r[3] for r in [nb] + [r for op in nops for r in op]) \
                and distinct(nb, nops):
            return nb, nops


def random_history(rng, nops, shape=None):
    """A base rectangle and nops cut operations; each is one rectangle or a
    pattern of 2 or 3 copies shifted along x or y. With shape given, the
    same number of copies per operation is kept."""
    while True:
        W, H = rng.randint(12, 30), rng.randint(8, 20)
        base = (0, 0, W, H)
        ops = []
        for k in range(nops):
            copies = shape[k] if shape else rng.choice([1, 1, 2, 3])
            w, h = rng.randint(1, 8), rng.randint(1, 8)
            if rng.random() < 0.3:      # a through cut, across the whole part
                if rng.random() < 0.5:
                    h = H + 2 * rng.randint(1, 3) + 1
                else:
                    w = W + 2 * rng.randint(1, 3) + 1
            x0, y0 = rng.randint(-4, W - 1), rng.randint(-4, H - 1)
            if h > H:
                y0 = -rng.randint(1, h - H - 1)
            if w > W:
                x0 = -rng.randint(1, w - W - 1)
            dx, dy = (rng.randint(w + 1, w + 6), 0) if rng.random() < 0.5 else (0, rng.randint(h + 1, h + 6))
            if w > W:
                dx, dy = 0, rng.randint(h + 1, h + 6)
            if h > H:
                dx, dy = rng.randint(w + 1, w + 6), 0
            ops.append([(x0 + i * dx, y0 + i * dy, x0 + i * dx + w, y0 + i * dy + h) for i in range(copies)])
        if distinct(base, ops):
            return base, ops


def remap(rng, base, ops):
    """A parameter change that keeps the order of all x and all y values."""
    rects = [base] + [r for op in ops for r in op]
    xv = sorted({r[0] for r in rects} | {r[2] for r in rects})
    yv = sorted({r[1] for r in rects} | {r[3] for r in rects})
    nx = dict(zip(xv, sorted(rng.sample(range(-60, 160), len(xv)))))
    ny = dict(zip(yv, sorted(rng.sample(range(-60, 160), len(yv)))))
    new = [[(nx[a], ny[b], nx[c], ny[d]) for a, b, c, d in op] for op in [[base]] + list(ops)]
    return new[0][0], new[1:]


def cell_area(p: Part) -> int:
    return sum((p.xs[i + 1] - p.xs[i]) * (p.ys[j + 1] - p.ys[j]) for i, j in p.cells)


class TestHandCases(unittest.TestCase):
    def test_slot_splits_the_top(self):
        p = Part((0, 0, 10, 6), [(4, 3, 6, 8)])
        self.assertEqual(len(p.cycles), 1)
        self.assertEqual(len(p.cycles[0]), 8)
        tops = [e for e in p.edges if p.label(e) == ("base", "top")]
        self.assertEqual(len(tops), 2)
        names = name_edges(p)
        self.assertEqual(sorted(names[e][0] for e in tops), [1, 1])
        self.assertEqual(max(n[0] for n in names.values()), 1)
        # resize everything: the names still find the same pieces
        q = Part((0, 0, 20, 9), [(5, 4, 12, 15)])
        for e in tops:
            (f,) = resolve_edge(names[e], q)
            self.assertEqual(p.edge_geom[e[0]][e[1]], q.edge_geom[f[0]][f[1]])  # same grid position
        # make the cut a pocket: the top is whole again, and the split names fail
        r = Part((0, 0, 10, 6), [(4, 3, 6, 5)])
        self.assertEqual(len(r.cycles), 2)
        for e in tops:
            self.assertEqual(resolve_edge(names[e], r), set())
        self.assertEqual(len(resolve_edge((0, r.window(tops[0], 0)), r)), 1)

    def test_cut_through_splits_the_part(self):
        p = Part((0, 0, 10, 6), [(4, -1, 6, 8)])
        self.assertEqual(sorted(len(c) for c in p.cycles), [4, 4])
        names = name_edges(p)
        self.assertTrue(all(len(resolve_edge(n, p)) == 1 for n in names.values()))

    def test_pattern_gives_symmetric_pieces(self):
        # three through slots of one pattern: the two middle pieces have the
        # same labels all round, so their edges cannot be told apart
        ops = [[(4, -1, 5, 11), (9, -1, 10, 11), (14, -1, 15, 11)]]
        p = Part((0, 0, 20, 10), ops)
        self.assertEqual(sorted(len(c) for c in p.cycles), [4, 4, 4, 4])
        names = name_edges(p)
        counts = sorted(len(resolve_edge(n, p)) for n in names.values())
        self.assertEqual(counts, [1] * 8 + [2] * 8)
        self.assertTrue(all(n[0] == 4 for n in names.values() if len(resolve_edge(n, p)) == 2))
        q = Part((0, 0, 30, 12), [[(3, -2, 9, 13), (11, -2, 12, 13), (20, -2, 26, 13)]])
        images = isomorphism_images(p, q)
        for e, n in names.items():
            self.assertEqual(resolve_edge(n, q), images[e])


class TestAgainstBruteForce(unittest.TestCase):
    def test_model_is_consistent(self):
        rng = random.Random(1)
        for _ in range(150):
            base, cuts = random_history(rng, rng.randint(0, 3))
            p = Part(base, cuts)
            self.assertEqual(p.area(), cell_area(p))
            for c in p.cycles:
                for i in range(len(c)):
                    self.assertNotEqual(c[i], c[i - 1])  # each edge is maximal

    def test_names_survive_order_preserving_changes(self):
        rng = random.Random(2)
        checked = 0
        for _ in range(150):
            base, cuts = random_history(rng, rng.randint(0, 3))
            p = Part(base, cuts)
            q = Part(*remap(rng, base, cuts))
            images = isomorphism_images(p, q)
            self.assertIsNotNone(images)
            en = name_edges(p)
            for e, n in en.items():
                got = resolve_edge(n, q)
                self.assertEqual(got, images[e])
                self.assertIn(e, got)                 # the same grid edge
                if len(resolve_edge(n, p)) == 1:
                    self.assertEqual(got, {e})
                checked += 1
            for v, n in name_vertices(p, en).items():
                # an isomorphism maps the vertex after edge a to the vertex after its image
                want = {(x, (x[0], (x[1] + 1) % len(q.cycles[x[0]]))) for x in images[v[0]]}
                self.assertEqual(resolve_vertex(n, q), want)
                checked += 1
        self.assertGreater(checked, 500)

    def test_names_against_isomorphisms_after_any_change(self):
        """Every coordinate moves by up to 3, which may change the order of
        the coordinates and the topology. When the labelled boundaries are
        isomorphic, resolution returns exactly the images under all
        isomorphisms. Otherwise nothing is claimed; the test only counts
        these cases, to show that the edits do change the topology."""
        rng = random.Random(3)
        checked = iso = changed = 0
        for _ in range(250):
            ncuts = rng.randint(1, 3)
            base, cuts = random_history(rng, ncuts)
            p = Part(base, cuts)
            q = Part(*perturb(rng, base, cuts))
            images = isomorphism_images(p, q)
            if images is None:
                changed += 1
                continue
            iso += 1
            en = name_edges(p)
            for e, n in en.items():
                self.assertEqual(resolve_edge(n, q), images[e])
                checked += 1
        self.assertGreater(iso, 50)
        self.assertGreater(changed, 10)
        self.assertGreater(checked, 500)


if __name__ == "__main__":
    unittest.main()

History

The parametric, history-based modelers of the late 1980s and early 1990s exposed the problem. References to faces and edges broke when an early feature was edited and the history replayed. Chen and Hoffmann described in 1995 how features attach to entities of the model before them. Capoyleas, Chen and Hoffmann published generic naming in 1996, with names built from the operations and generators of a generative design and extended by neighbouring entities to remove ambiguity. Kripac's topological ID system of 1997 took a related approach in a commercial setting. Marcheix and Pierra surveyed the methods in 2002, and they showed that every known scheme fails on some edits, because the problem refers to the designer's intent.

References

  1. Vasilis Capoyleas, Xiangping Chen and Christoph M. Hoffmann, Generic naming in generative, constraint-based design, Computer-Aided Design 28(1), 17 to 26, 1996, the whole paper (names built from the creating operation and the entities it is made from, extended by neighbouring entities when ambiguous, and the matching of names after a regeneration)
  2. Xiangping Chen and Christoph M. Hoffmann, Towards feature attachment, Computer-Aided Design 27(9), 695 to 702, 1995, how a feature refers to entities of the model built before it, and what happens to the references on regeneration
  3. Jiri Kripac, A mechanism for persistently naming topological entities in history-based parametric solid models, Computer-Aided Design 29(2), 113 to 122, 1997, the topological ID system, a related scheme that names faces by their feature and edges and vertices by their faces
  4. David Marcheix and Guy Pierra, A survey of the persistent naming problem, Proceedings of the Seventh ACM Symposium on Solid Modeling and Applications, 13 to 22, 2002, the classes of naming methods, including generic naming, and the cases where each one fails

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