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
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 built by a history, and a model 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 , and a resolution rule that maps a name and to a set of entities of . The goal is that a name resolves to the entity "with the same role" in . Here that is made precise. An isomorphism from to is a bijection between their boundary cycles, with a rotation of each cycle, that keeps every label. The correct answer for an edge is the set of its images over all isomorphisms . This set is a single edge when 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 of an edge on a cycle of length is the tuple of the labels of the edges centred on , going around the cycle. When the window wraps around, and then it also records . The level of is the least at which its window is unique among all edges of . If no window is unique up to the length of the longest cycle, the level is that length. The name of 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.
NAME-EDGES(M)- 1
for r ← 0, 1, ... while some edge has no level and r ≤ the longest cycle length do - 2
count the windows of radius r over all edges of M - 3
for each edge e with no level yet do - 4
if window_r(e) occurs once, or r is the longest cycle length, then level(e) ← r - 5
return name(e) = (level(e), window_level(e)(e)) for every edge e RESOLVE-EDGE((r, w), M')- 6
return the edges e' of M' with window_r(e') = w NAME-VERTEX(v) and RESOLVE-VERTEX- 7
name(v) ← (name of the edge before v, name of the edge after v) - 8
return the vertices of M' whose edge before resolves from the first name 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 and cut 1 is , a slot through the top. The part has one boundary cycle of 8 edges, listed counterclockwise from the bottom:
| edge | label | level | name |
|---|---|---|---|
| to | base bottom | 0 | base bottom |
| to | base right | 0 | base right |
| to | base top | 1 | (base right, base top, cut 1 right) |
| to | cut 1 right | 0 | cut 1 right |
| to | cut 1 bottom | 0 | cut 1 bottom |
| to | cut 1 left | 0 | cut 1 left |
| to | base top | 1 | (cut 1 left, base top, base left) |
| to | base left | 0 | base left |
The edit changes the base to and the cut to . 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 to .
If instead the cut becomes , 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 , and across , 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:
- Windows are invariant. An isomorphism keeps labels, cycle lengths and the cyclic order, so for every .
- Names resolve to the images. Suppose and are isomorphic by some . The edges of with window at radius are exactly applied to the edges of with window . If the name of is unique in , it resolves to , 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 , and the edges of with that window are exactly the images of under the automorphisms of . So in both cases line L6 returns .
- Vertices follow. An isomorphism maps the vertex between and its successor to the vertex between and 's successor, so line L8 returns the images of the vertex.
- Order-preserving edits keep every name. If an edit keeps the order of all coordinates and of all 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 is a finite set of cycles. Cycle has a length and a sequence of labels , with indices taken modulo . An edge is a pair , and its successor is . A vertex is a pair of an edge and its successor.
The window of radius of is
where if and otherwise. Let be the largest cycle length of .
An isomorphism is a bijection from the cycles of onto those of , together with a shift for each cycle of , such that and for all . It acts on edges by and on vertices by . An isomorphism from to itself is an automorphism. Isomorphisms compose, and their inverses are isomorphisms.
Lemma 1 (windows are invariant). For every isomorphism , every edge and every , . Also .
Proof. Let . Then , and , so the first components agree. For , the label at offset is . The second claim is .
Lemma 2 (the top window determines the orbit). Let , and let and be edges of . Then if and only if for some automorphism of .
Proof. If , the windows are equal by Lemma 1. Conversely, let and have equal windows. Since , the first component of is , and likewise for , so . The offsets all lie in , so for , and so for all by periodicity. Define as follows. If , it shifts by and fixes the other cycles. If , it maps to with shift , maps to with shift , and fixes the other cycles. In both cases each shifted cycle keeps its labels, by the identity . So is an automorphism with .
Lemma 3 (levels). Line L4 gives each edge of a level . Either occurs exactly once among the edges of , or .
Proof. The loop of lines L1 to L4 runs while some edge is pending and . At , line L4 assigns a level to every pending edge. So every edge gets a level, the loop stops after at most rounds, and the level is the first at which the window was unique or the top was reached.
Theorem 1 (edge names resolve to the images). Let be an isomorphism, and let be an edge of with name , where and . Then line L6 returns
If occurs once in , this set is the single edge .
Proof. Let . By Lemma 1, applied to and to , the edges of with window at radius are exactly . So line L6 returns .
Every isomorphism has the form with an automorphism of , and every such composition is an isomorphism. So the right side is , where . It remains to show . By Lemma 3 there are two cases.
The window is unique. Then . By Lemma 1 every automorphism keeps the window of , so it maps into , and .
The level is the top. Then , and Lemma 2 gives directly.
In both cases line L6 returns , which is the set of images. In the unique case it is .
Corollary 1 (vertices). Under the same hypothesis, let be a vertex of , so . Then line L8 returns .
Proof. By Theorem 1, the two resolved sets are and , each over all isomorphisms . Line L8 returns the vertices of with and . For any , the vertex equals by Lemma 1, and its two edges lie in and . Conversely, if , then by Lemma 1, so the returned vertex is .
Corollary 2 (order-preserving edits). Let be built from the same history as by a change of coordinates that keeps the strict order of all values and of all 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 .
Proof. The construction depends on the coordinates only through comparisons. The owner of each value is fixed by the history, and the sorted lists and list the same owners in the same order. A grid cell is inside when its doubled centre lies strictly between and for the base, and not for any cut , and likewise in . For a grid value , the test holds exactly when , since 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 is then an isomorphism, and Theorem 1 applies with the identity.
Termination. Lemma 3 bounds the naming loop by rounds of 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 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.
What is not claimed. If no isomorphism from to 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 be the number of edges and the length of the longest cycle. Level computes windows of length , so it costs time with hashing, and the levels up to cost in the worst case. Most edges stop at level 0 or 1, so the typical cost is . Resolving one name costs . The names take space. Building the toy model from rectangles takes time on its 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 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.
# 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
- 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)
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5S5Z62 Edit this page History Report an error Markdown