Body Decomposition Algorithm#

How the stock stage takes a body apart, one primitive at a time, until a stock reader reads what is left.

Note

This document is for developers working on shape_editing.defeaturing.body_decomposition and the stock stage of BRepDefeaturerProcessor. The user-facing side, with one part followed through every output, is Body Decomposition. Read Shape Editing Architecture first for the pipeline the decomposition is a stage of.

The problem#

Note

The figures on this page follow the user guide’s part, a plate with a pad on its corner and a lug through its end. Its faces are numbered on Body Decomposition.

The feature-driven pipeline removes a part’s subtractive features and reads what remains, the remainder, as one stock: an extrusion or a revolution. Many remainders are not one primitive. A plate with a pad running off its edge, a shaft with a bar across it, a flange with a boss on it: the stock readers either read nothing on them, or the extrusion reader reads a profile pair with laterals and leaves the rest of the faces unexplained.

Boussuge, Léon, Hahmann and Fine (Extraction of generative processes from B-Rep shapes and application to idealization transformations, CAD 2014) decompose such a body by repeatedly identifying a primitive visible on it, removing it, and continuing on the simpler body. This module applies that idea in the narrowest form that fits the existing readers:

  • a candidate is whatever the prism and revolution readers already read on the body, with the solid that reading describes; nothing new is recognised;

  • a removal is a boolean cut, accepted only when it leaves one sound solid with fewer faces and takes off the candidate’s own volume;

  • the loop stops when a stock reader reads the body whole. That reading is the root; what was cut off on the way are the additions.

The loop lives in one module, body_decomposition.py: the reading of candidates, the containment check, one removal, the loop and its record. The solid a candidate describes is built by primitive_solids.py, next to the readers, from their records.

The module’s interface is decompose_body, the RootReader it is given, and the records it returns. Every step below is private to it, and the tests go through decompose_body except for the few behaviours a small fixture cannot reach through the loop.

The loop#

decompose_body(remainder, read_root, *, lineage=None, deadline=None, max_steps=MAX_STEPS) is the entry point. In pseudocode:

trail  = Defeaturer(remainder)          # follows faces across every cut
body   = remainder
repeat up to MAX_STEPS times:
    if the deadline passed:               end "ran_out"
    reading = PartReading(body)           # ShapeTypeError -> end "unread"
    candidates = _read_candidates(reading) # an error -> end "failed"
    for each of the first _MAX_CANDIDATES_PER_STEP in _in_removal_order:
        if the deadline passed:           end "ran_out"
        if not _lies_inside(candidate):   refuse "outside the body", next
        cut = _remove(body, candidate)
        if cut is a refusal:              refuse with its reason, next
        take it: body = cut, record the step, break
    if nothing was taken:                 end "no_candidate"
    if the deadline passed:               end "ran_out"
    root = read_root(body)                # an error -> end "failed"
    if root:                              end "root"
end "step_bound"

Only reading a body and asking the stock reader of it are guarded; an error in the bookkeeping of a cut is a bug and propagates. Every ending returns a DecompositionResult whose record is a DecompositionRecord: the ending, the steps taken, every refusal with its reason, the time spent. Only the "root" ending also carries the root, its type, the lineage of its faces over the input and the additions.

Step 1: reading the candidates#

_read_candidates(reading, tolerance) asks the two existing readers:

  • recognise_prisms along each of the body’s dominant axes. Only additive prisms are kept, and only those whose solid prism_solid can build (an open loop or a self-crossing profile gives no solid, so no candidate).

  • recognise_revolution about the first five turns of the body, the lines its technique fits say it may have been turned about. It always reads a whole turn, so no revolution is held back for being partial; one is kept only when revolution_solid builds the solid. A revolution of more than one chain builds none: it is a body with a bore, and turning its outer chain alone would fill the bore.

A prism read along several directions comes back several times with the same kind, volume and faces, and is kept once. The candidates are returned largest first. What the readers leave out, and the solids that cannot be built, are logged at debug level.

A candidate keeps two sets of faces. read_face_ids are the faces the reader read it off, which the ordering of step 2 looks at. face_ids are the ones it owns, those lying within its solid. For a prism they are the same, its walls; a revolution is read off every face on its profile, including a plane the body runs on past it, and owns only the faces within its solid.

Nothing here invents a primitive. A body the readers cannot read has no candidate, and the loop ends on "no_candidate". That is deliberate: the decomposition inherits the readers’ coverage and their gaps, and a reader gap is fixed in the reader, never patched around here.

Step 2: ordering, own faces first, the presumed root last#

_in_removal_order sorts the candidates on three keys:

  1. a candidate bigger than _ROOT_SHARE (half) of the body’s volume goes last;

  2. among the rest, a candidate standing on faces of its own goes before one that is not;

  3. among equals, the larger first.

The first key is the stock’s definition: the largest primitive the rest stands on. Taking the biggest primitive off a body is taking the stock off, which leaves the additions as the thing to read, upside down. A candidate bigger than half the body is therefore presumed to be the root and is only removed when nothing smaller can be. The paper’s criterion does not forbid removing the largest primitive; our stock stage defines the root as the largest, so the order follows.

The second key tells a thing standing on the body from a slice through it. _stands_on_its_own_faces compares the geometric extent of the candidate’s solid with the extent of each face it was read off: when every face lies within the solid, to the containment tolerance, the candidate is walled by its own faces. A candidate read off a face the body runs on past it, the way the plate’s side runs on past the pad’s outer wall, extends the face’s primitive through the body, and comes after. On the user guide’s part this is what puts the pad before the column through the plate under it, which is read off the plate’s own side and back, passes every check and would slice the corner off the plate if tried first.

The extents are the bounding boxes of the exact geometry (ocp_helpers.solids.shape_bounds), not of a triangulation: a triangulated box grows by the mesh deflection, and whether a face is meshed when the step runs depends on what ran before, so the triangulated test flipped between a fresh shape and one a reader had meshed.

Only the first _MAX_CANDIDATES_PER_STEP (8) candidates of a step are tried. Each try costs a containment check and, usually, a boolean cut, so the cap bounds a step’s time on a body with many readable prisms.

The five candidates of the first step in the order they are tried, each drawn in orange on the see-through part

The first step’s candidates in the order they are tried, each drawn in orange on the see-through body: the lug and the pad, standing on faces of their own, then three readings of the column through the plate. Four readings bigger than half the body come after these and are never reached.#

Step 3: containment#

_lies_inside(candidate, containment) samples the candidate’s outline and classifies every sample against the body with one SolidContainment built per step:

  • a prism: 120 points of its first closure, lifted to five levels of its height (10 %, 30 %, 50 %, 70 %, 90 %);

  • a revolution: each primitive of its first chain sampled 40 times, turned to 12 azimuths.

The tolerance is _containment_tolerance(reading), ten of the body’s quanta, the smallest length that tells two places of it apart, taken from the size of its surfaces, so it scales with the part. A sample on the boundary counts as inside.

This is a sampling check, not an exact one. A candidate that overhangs the body between two levels passes it; the cut and the checks after it are what catch that case, the volume check of step 4 among them.

Step 4: one removal#

_remove(body, candidate, tolerance, faces_before) is a boolean cut of the candidate’s solid off the body, two surfaces closer than the tolerance counting as one, followed by unified_same_domain to merge the faces the cut leaves on one surface. The result is accepted only when:

  1. the cut ran ("cut failed") and raised no kernel error ("kernel: <ExceptionName>");

  2. it left exactly one solid ("empty", "split into N solids");

  3. that solid is sound ("not sound"), before and after the merge;

  4. the merged face count is lower than the body’s ("no face merged away (M before, N after)");

  5. the cut took off the candidate’s own volume, to _VOLUME_SHARE_TOLERANCE (1 %) of it ("covers a void (removed X, candidate Y)"). A reader reads a pad with a hole down through it as a solid block; cutting the block off takes the hole with it, and adding the block back would fill it.

The fourth rule is the one that does the most work. A primitive sitting on the body shares its interface with it, so cutting it off makes the interface face disappear into the face it stood on and the body ends simpler. A candidate that is a slice through the body, or whose cut leaves a notch with as many new faces as it took away, explains nothing, and is refused even though it lay inside. The user-guide example shows one such refusal, the lug: cutting the whole cylinder off leaves a round groove through the plate with as many faces as the lug had.

The merge is counted the same way on both sides: _merged_face_count runs unified_same_domain on the first body, the count of each accepted cut is kept for the next step, and the removal compares against it, so a body whose faces are already merged is not penalised.

What three of the cuts leave behind: the plate with a round groove, with nine faces, the plate with its lug, with six, and the plate with its corner sliced off, with eight

What a cut leaves behind decides the removal. The lug, the pad and the column all lie inside the body. Cutting the lug off leaves nine faces where there were nine, and is refused. The pad’s cut merges three faces away. The column’s cut would pass too, with eight faces left, by slicing the corner off the plate: it is the ordering of step 2, not this check, that keeps it from being tried before the pad.#

A removal returns the new solid, its merged face count and a HistoryGraph of the cut followed by the merge. The history is what lets the next step follow faces.

Step 5: following the faces#

The remainder itself is never changed. _Run holds a Defeaturer of its own, the trail, that starts from the remainder and has each accepted removal applied to it with its history, so at any point trail.get_origins(face) says which faces of the remainder lie behind a face of the current body.

When a candidate is taken, _Run.take records what it claims, in remainder face ids:

  • its own faces: the origins of the faces it owns (face_ids);

  • the faces its removal deleted: the origins standing before the cut minus those standing after it. This is how an end cap, which no reader lists as a face of the prism, is claimed by the pad it caps;

  • its interface: the origins of the body faces touching its own faces, minus what it claimed;

  • its ends: the deleted faces that are not among its own, the caps where it stops.

When the run ends on a root, _Run.end_with_root turns all of it into faces of the input, through the lineage the caller gave (the identity when there is none). The root claims first; then the additions, in build order, each claim the input faces behind theirs that nothing before them claimed. One input face belongs to one step. Without this rule a pad wall coplanar with the plate’s side is claimed twice, and a consumer ordering the claims sees them contradict. Build order is the reverse of removal: the primitive removed last is the one standing directly on the root, and goes back on first.

Step 6: the root#

After each removal the loop builds an adjacency graph of the body and calls read_root. Its contract is to return a stock only when the stock accounts for every face of the body. In the pipeline it is defeaturer_processor.read_whole_stock: the extrusion reader, then the revolved one, each reading kept only when its all_face_indices cover every face. The extrusion reader accepts a profile pair and laterals without checking that nothing is left over; the revolved reader accepts a revolution that covers half of the faces and files every other face it reaches as one joining its features. So an extrusion counts its profiles and laterals, and a revolution its revolved faces, its end caps and its shoulders, the joining planes square to its axis. A partial reading does not end the loop: the body is not the root yet, and the next step removes more.

The part from two sides with the three faces standing across each extrusion direction in red

Before the loop starts: no reader reads the part. Along each of its three directions a face stands in the way of the extrusion reader, in red: the pad’s inner wall across the plate’s length, its front wall across the width, the lug across the pad’s height. A reading that leaves faces over, or none at all, is not the root, so the loop runs.#

When a reader reads the body whole the run ends on "root" and _Run.end_with_root resolves the lineage: for each face of the root body, the input faces behind it, through the trail and the caller’s lineage.

The six-face root with its profile pair and laterals, and the input part with the stock's faces in grey and the addition's in green

Left, the body after the pad’s removal: the extrusion reader reads it off its front and back faces and every lateral is accounted for. Right, the outcome carried back to the input: each face belongs to the stock or to the one addition, never to both.#

Bounds and endings#

Ending

When

"root"

A reader read the body whole. The only ending with a root and additions.

"no_candidate"

A step tried every candidate it had and refused each. Includes the body with no candidate at all.

"step_bound"

MAX_STEPS (12) removals were made without a reader reading the body.

"ran_out"

The deadline passed: before a step, between two candidates, or before the stock reader is asked.

"unread"

PartReading refused the body (ShapeTypeError); the error is in reason.

"failed"

Reading a body or asking the stock reader of it raised (GEOM_ERRORS or ValueError); the error is in reason, the steps so far in steps, and a warning with the trace is logged.

A kernel error inside one cut is a refusal of that candidate ("kernel: <ExceptionName>"), and an error reading a body or asking the stock reader of it is a "failed" ending, so the benchmark can count them. An error anywhere else, in following the faces across a cut, is a bug and propagates.

Where the pipeline runs it#

BRepDefeaturerProcessor._read_stock runs after the features are removed and the remainder’s faces are already mapped back to the input (face_lineage):

  1. The stock readers read the remainder. If one reading explains every face, that is the stock and nothing else happens.

  2. Otherwise decompose_body runs with read_whole_stock as read_root, face_lineage as its lineage and _decomposition_deadline() as its deadline. The record is published as DefeaturingResult.decomposition whatever the ending.

  3. On a "root" ending the root replaces the stock, stock_lineage is the root’s lineage over the input, and body_additions are the additions, already in input faces and disjoint from the stock.

  4. The stock is claimed as an Extrusion ("base_extrusion"), then each extrusion added back as one ("body_addition"), in build order, so the registry’s first claim keeps a shared face with the stock. A revolved addition, like a revolved stock, has no feature to claim with; the face segmentation reads it from body_additions.

stock_lineage always pairs with stock_shape: it is face_lineage when the stock was read on the remainder itself, the root’s when it was decomposed. A consumer reads the stock’s faces through it and never has to choose.

On any other ending the stock reading stays what the readers gave, possibly partial, possibly none: the decomposition never makes a part worse than it was, by construction, since root plus additions equal the remainder exactly or the remainder is left alone.

The deadline#

The processor takes an optional deadline (a time.perf_counter() instant). The decomposition gets _DECOMPOSITION_TIME_SHARE (half) of whatever is left of it when the stock stage starts, so a slow decomposition cannot consume the time the stages after it need. The share is the processor’s policy and lives there; the module only ever sees an absolute instant. With no deadline the loop is bounded by its step count and its candidate cap only.

Design decisions, in one place#

  • Candidates come from the readers, not from here. Coverage is the readers’; a gap (a revolved reader that accepts a cylinder about another axis as a revolution face, work item volmdlr_tools#42) shows up as a wrong root here but is fixed there.

  • Own faces first, largest among equals, presumed root last. A candidate walled by its own faces is a thing on the body; one read off a face the body runs past is a slice through it. Fewest steps to a readable stock; the stock is never removed while something smaller can be.

  • A removal must simplify. Fewer merged faces, one sound solid, its own volume taken off, or it is refused with a reason the record keeps.

  • Root must explain every face. Part of the RootReader contract; the readers’ partial readings do not end the loop.

  • One input face, one step. Root first, then additions in build order, resolved in the module, not by each caller.

  • Reading fails as an ending, bookkeeping fails loudly. A body the readers cannot read ends the run with a reason; an error following faces raises.

  • Time is a share, not a cap of its own. The decomposition spends at most half of what the processor has left.

Parked follow-ups: containment by exact volume; a drafted-extrusion root is accepted here although the reconstruction refuses a drafted stock.

See Also#