API reference

Every public module of braidpy, by what it is for.

Start here

A few questions answered in plain data, and the same offered to AI assistants.

braidpy: braids in Python — represented, worked with and analysed, and drawn and made, by hand or on a machine.

braidpy’s front door: a few questions about braids, answered in plain data — for a person at a prompt, a script, or an AI assistant (braidpy.mcp_server offers each as a tool).

Each function takes and gives only text, numbers, lists and dicts, so what goes in and comes out can be read, printed or sent as JSON as it is. None does anything of its own: each asks the module that knows, and says which.

>>> from braidpy import tools
>>> tools.describe_braid("1 -2")["permutation"]
[2, 3, 1]
>>> tools.compare_braids("1 -2", "-2 1", n_strands=3)["same_braid"]
True

A braid is given as a braid word: signed generators, 1 for σ₁, -2 for σ₂⁻¹, written as braidpy reads them (parse_word()): "1 -2", "1,-2", "s1 s2^-1" or "aB".

braidpy.tools.STUDIO = 'https://baptistelabat.github.io/braidpy/studio/'

Braid Studio, where a braid described here can be seen made.

braidpy.tools.compare_braids(a: str, b: str, n_strands: int | None = None) → dict[str, Any]

Whether two braid words make the same braid pattern, however written: alike, as braidpy’s ways of making a braid check it — by their fingerprints (braidpy.braid_pattern.BraidPattern.alike()) — and, if so, proven or not (proven()); and how unlike they are (braidpy.similarity.distance(): 0 the same, up to 6).

Parameters:
  • a – A braid word.

  • b – Another.

  • n_strands – The strands of both; as many as they need if None.

Returns:

same_braid, whether they are alike; proven, whether they are proven the same pattern — None if the proof would take too long, or they are not alike, which proves them different; and distance.

braidpy.tools.describe_braid(word: str, n_strands: int | None = None) → dict[str, Any]

What is known of a braid from its word: strands, crossings, the permutation it makes, whether it is pure and after how many repeats, what it closes up into, its Garside normal form, which of periodic, reducible or pseudo-Anosov it is, its band word where that is shorter (braidpy.braid.Braid.band_word()) — as Braid Studio’s card shows it (braidpy.web) — and a link to see it.

Parameters:
  • word – The braid word, for example "1 -2".

  • n_strands – The strands; as many as the word needs if None.

Returns:

What is known, by name.

braidpy.tools.list_braids(source: str | None = None) → dict[str, Any]

The braids braidpy knows by name, by what makes them: braid words, kumihimo disks, Ashley’s sinnets, braiding machines, lace machines (braidpy.web.catalog()).

Parameters:

source – Only this one, for example "sinnet"; all if None.

Returns:

Per source, its title and its braids — each a name and a title — and the settings it takes, with their defaults.

braidpy.tools.make_braid(spec: dict[str, Any]) → dict[str, Any]

A braid made as Braid Studio makes it (braidpy.web.build()), told in words: what is known of it and what was noted on the way — not the thousands of points of its yarns, for which build itself, or the link, is the place.

Parameters:

spec – What it is made from, for example {"source": "sinnet", "name": "abok_3042"}; see list_braids() for each source’s settings.

Returns:

title, info, notes and a studio link.

braidpy.tools.similar_braids(word: str, n_strands: int | None = None, count: int = 5) → list[dict[str, Any]]

The braids of braidpy’s catalogues most like this one, nearest first, each with every way braidpy knows of making it (braidpy.topology_catalog.related()).

Parameters:
  • word – The braid word.

  • n_strands – The strands; as many as the word needs if None.

  • count – How many to give.

Returns:

its title, distance (0 is this very braid), and made_as, each way of making it with a studio link.

Return type:

Per braid

Where Braid Studio makes a braid, from what describes it — a link to open, to see it in 3D, turn it, grow it.

Parameters:

spec – What braidpy.web.build() makes it from, for example {"source": "word", "word": "1 -2", "n_strands": 3}.

Returns:

The link.

braidpy.tools.ways_to_make(word: str, n_strands: int | None = None) → dict[str, Any]

How to make a braid by hand or on a machine (braidpy.making): a kumihimo disk’s moves, a Jacquard lace machine’s punchcard, and Ashley’s stand — a sinnet of the book’s kind if one makes it, or the braid itself one strand a space; each from the word shortened first (shortened()), fewer crossings to make.

Parameters:
  • word – The braid word, one repeat of it.

  • n_strands – The strands; as many as the word needs if None.

Returns:

its moves, from slot > to slot, and a studio link; lace: the punchcard, as punched, and where the bobbins go; ashley: its spaces, moves, whether it is a_sinnet of the book’s kind, and a studio link.

Return type:

disk

braidpy as an MCP server: braidpy.tools, each function a tool an AI assistant can call — Claude, or any client of the Model Context Protocol (https://modelcontextprotocol.io).

Installed with the mcp extra, it runs over stdio:

pip install "braidpy[mcp]"
braidpy-mcp

and is added to a client as a command, for example to Claude Code:

claude mcp add braidpy -- braidpy-mcp

The tools are braidpy.tools’s functions as they are, their docstrings what the assistant reads of them: nothing here but the wiring, so what a person reads in the library and what an assistant is told are the same words.

braidpy.mcp_server.TOOLS: list[Callable[[...], Any]] = [<function list_braids>, <function describe_braid>, <function compare_braids>, <function similar_braids>, <function ways_to_make>, <function make_braid>, <function studio_link>]

What the server offers, in the order it lists them.

braidpy.mcp_server.main() → None

Run the server over stdio: braidpy-mcp.

braidpy.mcp_server.server() → Any

The MCP server, its tools registered. The catalogue of braids by topology, a minute or so to make, is made at once in the background, so that the first question needing it is not kept waiting long.

Returns:

An mcp.server.mcpserver.MCPServer.

Raises:

ImportError – Without the mcp extra.

Braids and their words

Braid words, their notations, operations and properties.

The braid itself (Braid): a word in Artin’s generators on so many strands, and what can be done with it.

braidpy.braid.reduced_burau_generator(generator: int, n_strands: int, t, one, zero) → list[list]

The reduced Burau matrix of one generator, σ_i or its inverse, as rows: the identity, but for row i (from 0),

σ_i: ( …, t, −t, 1, … ) at columns i − 1, i, i + 1, σ_i⁻¹: ( …, 1, −1/t, 1/t, … ),

the columns that fall off the matrix left out. t, one and zero are of whatever ring the matrix is wanted in: a sympy symbol, an element of a polynomial field, a complex number.

Parameters:
  • generator – i for σ_i, -i for its inverse.

  • n_strands – Number of strands; the matrix is n_strands − 1 square.

  • t – The Burau variable.

  • one – The ring’s one.

  • zero – The ring’s zero.

Returns:

The rows.

class braidpy.braid.BraidWordNotation(*values)

Bases: str, Enum

How Braid.format_to_notation() writes a braid word: in Artin’s generators (s_{1}^{1.0}), in letters (aB), or as math-braid and braidlab write it (<1 : -2>).

ARTIN = 'ARTIN'
ALPHA = 'ALPHA'
DEFAULT = 'DEFAULT'
braidpy.braid.single_crossing_braiding_process(process: tuple[int | tuple[int, ...], ...]) → list[int]

Flattens a tuple of braiding steps into a list of signed crossings.

Each step may be a single crossing or multiple simultaneous crossings. To get Artin generators we need only consecutive single crossing, which is topologically equivalent

class braidpy.braid.Braid(process: int | Sequence[int | Sequence[BraidProcess]], n_strands: int = None)

Bases: object

Sometimes referred to as algebraic braids :param process: list of Artin’s generator, which may group or not by parenthesis (tuples) :type process: BraidProcess :param n_strands: number of strands. Default to the minimum number needed for process :type n_strands: Optional[int]

process: int | Sequence[int | Sequence[BraidProcess]]
n_strands: int = None
property generators: list[int]

List of Artin’s generators in the braid word.

property main_generator: int | None

A main generator of a braid word w is the generator with the lowest index.

https://pure.tue.nl/ws/portalfiles/portal/67742824/630595-1.pdf page 33

format_to_notation(target: str = '') → str

Inspired from https://github.com/abhikpal/dehornoy/blob/master/braid.py

Allow to format the braidword using several classical notations.:

The Artin representation can also be used in a latex file.

The neutral element is ‘e’ for the Artin representation and ‘#’ for alpha.

Parameters:

target (str) – Among ‘alpha’: for example ‘aBa’ ‘artin’ for example ‘s_{1}^{1.0} s_{2}^{1.0} s_{1}^{-1.0} s_{2}^{-1.0}’ ‘default’ syntax used by other tools such as math-braid and braidlab

Returns:

the formatted braid word

Return type:

str

format(generator_symbols: list[str] | None = None, inverse_generator_symbols: list[str] | None = None, zero_symbol: str = 'e', separator: str = '') → str

Allow to format the braid word following different formats.

Note that the power are limited to -1/1 due to the actual braid word definition (not possible to display σ₁² for example)

See also format_to_notation for simpler predefined format

Parameters:
  • generator_symbols (Optional(list[str])) – Default to [“σ₁”, “σ₂”, …]

  • inverse_generator_symbols (Optional(list[str])) – Default to [“σ₁⁻¹”, …]

  • zero_symbol (Optional(str)) – Default to “e

  • separator (Optional(str)) – Default to “”

Returns:

the formatted braid word

Return type:

str

no_zero() → Braid

Suppress all the zero steps (multiplication by neutral element).

Returns:

A new braid with zero generators removed.

Return type:

Braid

word_length() → int

Length of the word including neutral element.

Returns:

The length of the braid word.

Return type:

int

word_eq(other: Braid) → bool

Check if two braids have identical word representations.

Parameters:

other – The braid to compare with.

Returns:

True if the braid words are identical.

Return type:

bool

word() → BraidWord

The braid’s word, compared as a word (braidpy.braid_word).

pattern() → BraidPattern

The braid made over and over, compared as a pattern (braidpy.braid_pattern).

closed() → ClosedBraid

The braid closed, each strand’s end tied to its start: a knot or a link, compared as one (braidpy.closed_braid).

inverse() → Braid

Return the inverse of the braid.

This corresponds to the image of the braid in a mirror. Both order and signs are reversed.

Returns:

The inverse braid.

Return type:

Braid

n(n_strands: int) → Braid

Compact notation to allow changing the number of strands.

Parameters:

n_strands – The new number of strands.

Returns:

A new braid with updated number of strands.

Return type:

Braid

flip() → Braid

Flip the braid This corresponds to the image of the braid in a mirror on the side of the braid reordered from left to right The strands are reversed, not the order of operations Sign is also changed. This step is often used when braiding

Example

>>> b = Braid([1], 3)
>>> basic_3_braid = (b * (b.flip())) ** 3
Returns:

The reversed braid.

Return type:

Braid

half_twist(sign: int = 1) → Braid

Twist the braid with half a turn.

https://en.wikipedia.org/wiki/Twist_(differential_geometry)

Parameters:

sign – Sign of the twist. If positive the first strand is going over. Defaults to +1.

Returns:

The twisted braid.

Return type:

Braid

full_twist(sign: int = 1) → Braid

Twist the braid with a complete turn.

https://en.wikipedia.org/wiki/Twist_(differential_geometry)

Parameters:

sign – Sign of the twist. If positive the first strand is going over. Defaults to +1.

Returns:

The twisted braid.

Return type:

Braid

full_twists() → int

How many whole turns of every strand together the braid contains.

The full twist Δ² commutes with every braid, so it can always be moved to the front: β = Δ^{2m} · β′. Which m is a choice, made here so that what is left sits evenly about no twist at all: the canonical factors give the least and the most twist the braid lies between (its infimum and supremum, in half twists), and m is their middle in whole turns, rounded to the nearest. Adding k full twists to any braid adds exactly k to it.

A real braid hanging free, as from a kumihimo disk, does not keep these: turning every strand together only turns the cord, which turns back. See without_full_twists().

Returns:

m, negative for turns the other way.

Return type:

int

without_full_twists() → Braid

The braid with its whole turns taken out: β · Δ^{-2m}.

What is left is the braid’s real crossings, and at most a fraction of a turn. Two braids that differ only by full twists — a word read off a kumihimo disk that was turned round, and the cord it makes — are then equal.

Returns:

the same crossings, without the full twists.

Return type:

Braid

up_side_down() → Braid

Invert up and down crossing operations.

For hair braiding this is called “inversé”.

Returns:

The mirrored braid.

Return type:

Braid

shortened() → Braid

The same braid in as few crossings as are found: crossings that cancel, brought together by the braid relations, and Dehornoy’s handle reduction where it is shorter (braidpy.shortening.shortened()).

Returns:

The braid, its word no longer than this one’s.

is_reduced() → bool

Check if a braid word is reduced.

A braid word w is reduced either if it is the null string, or the empty braid, or if the main generator of w occurs only positively or only negatively.

https://pure.tue.nl/ws/portalfiles/portal/67742824/630595-1.pdf page 33

Returns:

True if the braid word is reduced.

Return type:

bool

writhe() → int

Calculate the writhe of the braid (sum of generator powers).

Returns:

The writhe value.

Return type:

int

get_canonical_factors() → GarsideCanonicalFactors

Get decomposition in Artin’s left normal form, Δ^k · A_1 ⋯ A_r

n_half_twist is k, the number of half twists Δ in front, and each A_i is a permutation braid — a positive braid in which any two strands cross at most once — given as the permutation it makes. See artin_left_normal_form().

Returns:

the unique decomposition of the braid according to left convention

Return type:

GarsideCanonicalFactors

get_band_canonical_factors() → GarsideCanonicalFactors

Get decomposition in Birman, Ko and Lee’s left normal form, in band generators, δ^p · A_1 ⋯ A_r (band_left_normal_form()).

Not Artin’s form: n_half_twist here counts δ, every strand a place round, a 1/n_strands turn — a full twist is n_strands of them — and each factor is strands in blocks round the circle (factor_blocks()).

Returns:

the band generator decomposition.

Return type:

GarsideCanonicalFactors

band_word() → list[tuple[int, int]]

The braid in band generators, as its band normal form spells it (band_word()): (t, s) for a_ts, strands t > s crossing in front of those between, (s, t) for its inverse. A disk braid’s is far shorter than its word.

Returns:

The band letters.

to_matrix() → Matrix

Convert braid to its (unreduced) Burau matrix representation.

Burau matrix representation is faithful for n_strands=3 or n_strands=4, but not faithful for n_strand>=5. https://arxiv.org/abs/2607.05283

Returns:

The Burau matrix representation of the braid.

Return type:

Matrix

to_reduced_matrix() → Matrix

Return the reduced Burau representation.

https://en.wikipedia.org/wiki/Burau_representation

Returns:

The reduced Burau matrix representation.

Return type:

Matrix

is_trivial() → bool

Check if the braid is trivial (identity braid): no crossing at all, however its word is written (σ₁σ₁⁻¹ is trivial).

By Dehornoy’s handle reduction (braidpy.handles_reduction): a braid is trivial exactly when its Dehornoy sign is 0. It is the faster on most braids; but it can blow up on long words of many strands (ABOK #3082’s, 61 strands and 1800 crossings: minutes). So it is given HANDLE_REDUCTION_S seconds, and then the braid’s left normal form decides (artin_left_normal_form()): trivial exactly when it is no half twist and no factor (three seconds there).

Returns:

True if the braid is trivial.

Return type:

bool

permutations(plot: bool = False) → list[list[int]]

Return the permutations induced by the braid

perm() → list[int]

Compute the permutation corresponding to the braid.

This is a braid invariant.

Returns:

The final permutation due to the braid.

Return type:

list[int]

is_pure() → bool

Check if a braid is pure (permutation is identity).

Returns:

True if the braid is pure.

Return type:

bool

is_palindromic() → bool

Check if the braid word is palindromic.

Returns:

True if the braid word reads the same forwards and backwards.

Return type:

bool

is_involutive() → bool

Check if braid word is involutive.

Returns true if inverse of braid word is the same as braid word. This probably works only for the neutral element.

Returns:

True if braid word is involutive.

Return type:

bool

is_periodic() → bool

Check if braid is periodic: some power of it is a power of the half-twist ∆ — a rotation of the disk holding the strands, the strands riding it round.

A braid x is periodic if and only if its nth power or its (n − 1)st power is a power of the half-twist ∆ (González-Meneses, Periodic braids): that power is read in the Garside canonical form (braidpy.garside_canonical_form.artin_left_normal_form()), where a power of ∆ is the form with no permutation braid left in it. Being pure is not enough: σ₁² keeps every strand’s place and is not periodic, while σ₁σ₂ turns the three strands round and is.

https://hal.science/hal-00647035v2/file/B_nNTHClassificationv5.pdf https://homepages.math.uic.edu/~jaca2009/notes/Meneses.pdf

Returns:

True if the braid is periodic.

Return type:

bool

without_strand(strand: int) → Braid

The braid with one strand taken out, as if it had never been there.

The crossings that strand takes part in go with it; every other crossing stays, between the same two strands and the same way over, renumbered for the slot the strand no longer takes up.

Parameters:

strand – The strand to take out, numbered from 1 by where it starts, as perm() numbers them.

Returns:

The braid on one strand fewer.

Raises:

ValueError – If there is no such strand, or none would be left.

is_brunnian() → bool

Whether the braid is Brunnian: pure, and trivial once any one of its strands is taken out (without_strand()), though perhaps not before — as three strands make the Borromean rings, any two of them apart.

Brunnian braids form a subgroup of the pure braid group. On three strands or more a braid trivial with any one strand out is pure anyway; on two, purity is what rules out a single crossing. The trivial braid is Brunnian.

https://en.wikipedia.org/wiki/Brunnian_link#Brunnian_braids

Returns:

True if Brunnian.

Return type:

bool

is_reducible(limit: int | None = 10000) → bool

Check if the braid is reducible.

If a braid is reducible, it means that the strands can be separated into groups of strands (less groups than number of strands), such that each group is running inside one tube. The tubes themselves can form a braid. Said of curves: some round curve round consecutive strands — two of them at least, all but two at most — is brought back to itself, up to stretching. The trivial braid is reducible, every curve coming back; a periodic braid (is_periodic()) may be too, the full twist turning every curve round and back; a braid neither periodic nor reducible is pseudo-Anosov.

Reducibility goes with a braid’s conjugates, so it is asked of the super summit set (braidpy.conjugacy.super_summit_set()): a reducible braid has a conjugate there that keeps a round curve (Benardete, Gutiérrez and Nitecki 1993; Calvez, Fast Nielsen–Thurston classification of braids, theorem 10), and of that set’s braids ∆^p · A_1 ⋯ A_r the one keeps the round curve round strands i…j when every A_k carries strands i…j back to them, and ∆^p, for an odd p, when i + j is one more than the number of strands — the middle curve, which the half twist turns round and back.

Parameters:

limit – The most braids of the super summit set to find; None for no limit.

Returns:

True if reducible.

Return type:

bool

Raises:

braidpy.conjugacy.SuperSummitSetTooLarge – If it cannot tell within limit braids.

slot_history() → list[list[int]]

Which slot every strand occupies, before and after each generator.

Slots are the positions across the braid, numbered from zero. A generator names two neighbouring slots and exchanges whoever is standing in them, whichever strands those happen to be, so this is the braid word’s permutation unrolled step by step.

It says nothing about which strand passed over which: that is the sign of the generator, and it is read separately — see strand_paths().

Returns:

A list of len(generators) + 1 rows; row m holds the slot of each strand after m generators, indexed by strand.

to_parametric_strands(amplitude: float = 0.2) → list[ParametricStrand]

Convert a braid into a list of 3D parametric strand paths.

Parameters:

amplitude – Height of the sine wave for over/under crossings. Defaults to 0.2.

Returns:

List of ParametricStrand objects representing the strands.

Return type:

list[ParametricStrand]

draw() → Braid

Draw the braid in the terminal with arrows.

Allows to better check the different operations (with colors!).

Returns:

Returns self to allow chaining the different steps.

Return type:

Braid

plot(n_samples: int = 400, line_width: float = 3.0, gap: float = 0.45, amplitude: float = 0.28, profile=None, color: str | None = None, title: str | None = None, save: str | None = None, ax=None) → Braid

Draw the braid as a 2D diagram, running down the page.

The braid hangs downward, the way it is worked, with its word written above it. Each strand is drawn in the colour draw() gives it, and the one passing behind is interrupted where they meet. The over-and-under is not re-derived: it is read from the curve strand_paths() computes.

This used to be drawn by braid-visualiser, which used its own colours, so a strand was one colour in the console and another in the plot. The arguments changed with it: “style” is gone, “gap_size” became “gap” as a fraction of the strand spacing, and “save” takes a path rather than a flag.

Parameters:
  • n_samples – Points along each strand.

  • line_width – Thickness of a strand.

  • gap – Width of the break where a strand passes behind, as a fraction of the distance between neighbouring strands.

  • amplitude – How far a strand swings out of line as it crosses.

  • profile – How a strand travels sideways; smoothstep by default, LINEAR for straight segments.

  • color – One colour for every strand; each takes its own by default.

  • title – Heading; the braid’s word by default, and “” for none.

  • save – Path to write the figure to, if wanted.

  • ax – Axes to draw on; a new figure otherwise.

Returns:

self, so the call can be chained.

Return type:

Braid

braidpy.braid.slide_strand(n_slide: int, start_index: int = 1, sign: int = 1) → Braid

Combine Artin Generator to move one braid over or under several braids.

This is noted as (ai…as) by Garside where i=start_index and s= i+n_slide. Πs corresponds to start_index=1 (default) and n_slide=s-1.

Parameters:
  • n_slide – Number of crossings.

  • start_index – Index of the strand to move. Defaults to 1.

  • sign – Positive if the start strand is going over. Defaults to +1.

Returns:

The corresponding braid.

Return type:

Braid

braidpy.braid.weave_strand(n_slide: int, start_index: int = 1, sign: int = 1) → Braid

Combine Artin Generator to move one braid over/under/over… or under/over/under… several braids.

Parameters:
  • n_slide – Number of crossings.

  • start_index – Index of the strand to move. Defaults to 1.

  • sign – Positive if the start strand is first going over. Defaults to +1.

Returns:

The corresponding braid.

Return type:

Braid

Artin’s generators: a braid described crossing by crossing.

class braidpy.artin_generators.a(process: int | Sequence[int | Sequence[BraidProcess]], n_strands: int = None)

Bases: Braid

This class is a shortcut to be able to use a compact notation with Artin’s generators

Braid words read from text, written in letters (aB), as signed numbers (1 -2) or as named generators (s1 s2^-1): braidpy’s one reader of them (parse_word()).

braidpy.braidword.braidword_alpha_to_numeric(braidword: str) → list[int]

Convert an alphabetical braid word to its numerical representation.

Each lowercase letter represents a braid generator σ_i, where:
  • ‘a’ → σ₁ → 1

  • ‘b’ → σ₂ → 2

  • …

Each uppercase letter represents the inverse generator σ_i⁻¹:
  • ‘A’ → σ₁⁻¹ → -1

  • ‘B’ → σ₂⁻¹ → -2

  • …

Special character # can be used for neutral element

Parameters:

braidword (str) – A string of alphabetical characters representing the braid word. Must contain only letters a–z and A–Z or character #

Returns:

The numerical representation of the braid word.

Return type:

List[int]

Raises:

ValueError – If the input contains non-alphabetical characters.

Example

>>> braidword_alpha_to_numeric("abAB")
[1, 2, -1, -2]
braidpy.braidword.parse_word(text: str) → list[int]

A braid word, as signed generator indices.

Reads 1 -2 1 (or with commas), s1 s2^-1 s1 (σ too), and letters, aBa: a is σ₁, b σ₂ and so on, a capital the inverse (braidword_alpha_to_numeric()).

Parameters:

text – The word.

Returns:

The generators; empty for an empty word.

Raises:

ValueError – If the text is none of these.

braidpy.braidword.parse_band_word(text: str) → list[tuple[int, int]]

A braid word in band generators (braidpy.band_canonical_form), as band letters.

Reads 4:1 2:1 1:3 (or with commas): t:s for a_ts, strands t > s crossing in front of those between, and s:t for its inverse.

Parameters:

text – The word.

Returns:

The letters, (t, s) or (s, t); empty for an empty word.

Raises:

ValueError – If a letter is not two strands apart from 1 on.

Properties and invariants of braids.

braidpy.properties.alexander_polynomial(braid: Braid) → Poly

The Alexander polynomial of the braid’s closure, in t.

From the reduced Burau matrix B of an n-strand braid (Burau, 1935):

Δ(t) ≐ det(I − B) (1 − t) / (1 − tⁿ),

up to a unit ±tᵏ, which is fixed here as most tables fix it: no negative powers, a nonzero constant term, a positive leading coefficient. A split link — loops that could be pulled apart — has Δ = 0, as can some links that are not.

It is a link invariant: it is the same for a braid read from any starting point (conjugation), and for braids on different numbers of strands that close up the same way (Markov’s theorem). It does not tell a braid from its mirror image, nor every link from every other.

Computed exactly, over the field of rational functions of t: a few hundred crossings on eight strands take a fraction of a second. For longer braids, alexander_on_circle() samples it.

Parameters:

braid – The braid.

Returns:

Δ(t), as a polynomial with integer coefficients.

References

W. Burau, “Über Zopfgruppen und gleichsinnig verdrillte Verkettungen”, Abh. Math. Sem. Hamburg 11, 179 (1935). D. Rolfsen, Knots and Links (1976), chapter 8.

braidpy.properties.alexander_on_circle(braid: Braid, angles: Sequence[float], repeats: int = 1) → tuple[float | None, ...]

log₁₀ |Δ(e^{iθ})|: the Alexander polynomial of the closure of the braid repeated repeats times, sampled on the unit circle.

On the unit circle |±tᵏ| = 1, so the modulus is exactly an invariant of the closure, with nothing to normalise; it is computed numerically, from the eigenvalues of the braid’s Burau matrix at t = e^{iθ} (_log_det_minus_power()) — milliseconds where the polynomial of a long braid takes minutes. The angles should not be rational multiples of π: at an n-th root of unity the formula divides by zero.

Parameters:
  • braid – The braid.

  • angles – The angles θ, in radians.

  • repeats – How many times the braid is repeated before it is closed.

Returns:

Per angle, log₁₀ |Δ|; None where Δ vanishes there.

braidpy.properties.burau_polynomial_on_circle(braid: Braid, angles: Sequence[float], repeats: int = 1, at: float = 2.0) → tuple[float, ...]

log₁₀ |det(x − B(e^{iθ}))| at x = at: the characteristic polynomial of the braid’s reduced Burau matrix B, the braid repeated repeats times, sampled on the unit circle.

The characteristic polynomial does not change when the braid is conjugated — read from another starting point, as a braid round a disk is wherever its circle is cut — so two braids it tells apart are not the same braid however written. It is a finer test than the Alexander polynomial of the closure (alexander_on_circle()), which is that polynomial at x = 1: where the Burau matrix has the eigenvalue 1, as for many braids with a closure of several loops, the Alexander polynomial vanishes and tells nothing apart, but this does not.

Parameters:
  • braid – The braid.

  • angles – The angles θ, in radians.

  • repeats – How many times the braid is repeated.

  • at – Where the characteristic polynomial is taken, off the unit circle so that it does not vanish there.

Returns:

Per angle, log₁₀ |det(x − B)|.

braidpy.properties.burau_polynomial_mod(braid: Braid, t: int, repeats: int = 1) → tuple[int, ...]

The characteristic polynomial det(x − Bᵏ) of the braid’s reduced Burau matrix B, the braid repeated k = repeats times, at an integer t, exactly, modulo PRIME.

burau_polynomial_on_circle() takes the same polynomial in floating point, which for a long braid loses digits: two words for the same braid can then disagree in its third. Modulo a prime nothing is rounded, so the same braid gives the same coefficients however written, and a braid read from another starting point (conjugated) too. Two different polynomials, in t and x, agree at a given t modulo the prime only by rare chance. The Alexander polynomial of the closure is in it as well: det(1 − Bᵏ) is its value at x = 1.

Parameters:
  • braid – The braid.

  • t – The Burau variable’s value; not a multiple of PRIME.

  • repeats – How many times the braid is repeated; a power taken by squaring, so millions of repeats cost a few dozen products.

Returns:

The coefficients, from xⁿ⁻¹’s (1) down, each in [0, PRIME).

braidpy.properties.conjugacy_class(braid: Braid, conjugators: list[Braid] | None = None) → list[Braid]

Generate conjugates of a braid by a list of other braids.

Parameters:
  • braid – The Braid object to conjugate.

  • conjugators – A list of Braid objects to use as conjugators. Defaults to generators and their inverses.

Returns:

List of unique conjugates a * braid * a⁻¹.

Return type:

List[Braid]

Pure braids: the ones that leave every strand where it started.

A braid is pure when its word returns every strand to the slot it set out from — when the permutation it performs is the identity. The pure braids form a subgroup, the kernel of the map from the braid group to the symmetric group, and are sometimes called the coloured braid group, since each strand can then be given a colour that survives composition.

Purity is also what decides whether a braid has a shape that repeats. A strand of a pure braid comes back to where it began, so its path closes and can be described periodically; a strand of an impure one ends somewhere else and has no period of its own until the word is repeated enough times to bring it home. closing_repeats() says how many, from the strands’ cycles().

braidpy.pure_braid.permutation(braid: Braid) → list[int]

Where each strand ends up, as a slot per strand.

Parameters:

braid – The braid.

Returns:

slot[s] — the slot strand s finishes in, having started in slot s.

braidpy.pure_braid.is_pure(braid: Braid) → bool

Whether the braid returns every strand to the slot it started in.

Parameters:

braid – The braid.

Returns:

True if its permutation is the identity.

braidpy.pure_braid.cycles(braid: Braid) → list[list[int]]

The strands’ cycles: the slots a strand passes through, braid after braid, until it is back where it started.

Parameters:

braid – The braid.

Returns:

Each cycle, as the slots in the order the strand visits them. The braid’s closure makes one separate piece per cycle.

braidpy.pure_braid.components(braid: Braid) → int

How many separate pieces the braid’s closure makes: its cycles.

Parameters:

braid – The braid.

Returns:

1 if every strand passes through every slot before coming home.

braidpy.pure_braid.closing_repeats(braid: Braid, limit: int | None = 1000) → int | None

How many times a braid must be repeated before it is pure.

Repeating a braid repeats its permutation, so a strand is home after a whole number of turns of its cycle: every strand, after the least common multiple of the cycles’ lengths. That is the permutation’s order, so a closing repeat always exists; the limit is there for a caller who would not repeat the braid that often.

Parameters:
  • braid – The braid.

  • limit – The most repeats worth having, or None for no limit.

Returns:

The smallest number of repeats that closes it — 1 if it is already pure — or None if that is over the limit.

braidpy.pure_braid.repeating_unit(word: Sequence[T]) → list[T]

The shortest word that, repeated, makes word.

Parameters:

word – Signed Artin generators, or any sequence: the gears a carrier track runs round, say.

Returns:

word itself if it repeats nothing shorter.

Return type:

The unit

Braids in band generators (Birman, Ko and Lee, 1998): the strands round a circle, any two crossing along the chord between them.

A band generator a_ts (t > s) crosses strands t and s directly, passing in front of every strand between them, as a band stretched across: a_ts = σ_{t-1} ⋯ σ_{s+1} σ_s σ_{s+1}⁻¹ ⋯ σ_{t-1}⁻¹, and a_{s+1,s} is σ_s. Where Artin’s generators cross neighbours on a line, these treat every place round a circle alike, as a kumihimo disk or a marudai does: a strand carried across the disk is one letter, a ring word’s crossing across the seam is a_{n,1}, and δ = a_{n,n-1} ⋯ a_{2,1}, every strand a place round, is the ring’s turn.

Every braid is δ^p A_1 ⋯ A_r in one way (Birman, Ko and Lee’s left normal form, band_left_normal_form()): each factor A_i strands in blocks round the circle, no two blocks crossing, each block’s strands a place round within it (a descending cycle), each pair of factors left-weighted. Worked out as Artin’s form is (artin_left_normal_form()): the turns kept at the word’s end, each factor made left-weighted with those before it in one pass back, a pair’s meet the blocks the two share.

Disk braids spell far shorter so: Kongo gumi on 8 strands, 81 crossings shortened, is 43 band letters (band_word()); machine braids of neighbours crossing, longer.

braidpy.band_canonical_form.artin_from_band(letters: Sequence[tuple[int, int]]) → list[int]

Band letters as Artin generators: a_ts = σ_{t-1} ⋯ σ_{s+1} σ_s σ_{s+1}⁻¹ ⋯ σ_{t-1}⁻¹.

Parameters:

letters – (t, s) for a_ts, (s, t) for its inverse, strands from 1.

Returns:

The signed Artin generators.

braidpy.band_canonical_form.band_left_normal_form(generators: Sequence[int], n_strands: int) → tuple[int, tuple[tuple[int, ...], ...]]

A braid word, of Artin generators, in Birman, Ko and Lee’s left normal form, δ^p · A_1 ⋯ A_r.

Parameters:
  • generators – Signed Artin generators, +i for σᵢ and -i for its inverse; 0 is ignored.

  • n_strands – Number of strands.

Returns:

p, the turns in front (negative the other way), and the factors as permutations, strands from 0: A[j] is where strand j ends, each block’s strands a place up it (factor_blocks()).

braidpy.band_canonical_form.band_letters(generators: Sequence[int]) → list[tuple[int, int]]

A braid word read as band letters as it stands: each run σ_{t-1} ⋯ σ_{s+1} σ_s^±1 σ_{s+1}⁻¹ ⋯ σ_{t-1}⁻¹ one letter, the longest first, and every other crossing σ_i^±1 the letter a_{i+1,i}^±1. Never longer than the word, where band_word() may be; the same braid, crossing for crossing.

Parameters:

generators – Signed Artin generators.

Returns:

The letters, as band_word() gives them.

braidpy.band_canonical_form.band_text(letters: Sequence[tuple[int, int]]) → str

Band letters as they are typed, and read back by parse_band_word(): 4:1 for a_41, 1:4 for its inverse.

Parameters:

letters – The letters.

Returns:

The word.

braidpy.band_canonical_form.band_word(generators: Sequence[int], n_strands: int) → list[tuple[int, int]]

A braid word written in band generators, as its band normal form spells it: δ^p, each δ a_{n,n-1} ⋯ a_{2,1}, then the factors’ letters.

Parameters:
  • generators – Signed Artin generators.

  • n_strands – Number of strands.

Returns:

(t, s), t > s, for a_ts, and (s, t) for its inverse.

Return type:

The letters

braidpy.band_canonical_form.factor_blocks(a: tuple[int, ...]) → list[tuple[int, ...]]

A factor’s blocks of more than one strand, strands from 1: each is its strands carried a place round within it, a_{b_k b_{k-1}} ⋯ a_{b_2 b_1}.

Parameters:

a – A factor of band_left_normal_form().

Returns:

The blocks, each its strands in increasing order.

The Garside canonical form: a braid as a power of the half twist and permutation braids, the same however the braid was written.

class braidpy.garside_canonical_form.GarsideCanonicalFactors(n_half_twist: int, n_strands: StrictlyPositiveInt, Ai: tuple[tuple[int, ...], ...])

Bases: object

Represents the Garside asymmetric canonical form of a braid. Also called greedy normal form.

Also known as Garside canonical form: https://webhomes.maths.ed.ac.uk/~v1ranick/papers/garside.pdf

Variables:
  • n_half_twist (int) – The exponent of the Garside element Δ (number of half-twists). From get_band_canonical_factors() it is instead the band generators’ δ, a 1/n_strands turn.

  • n_strands (int) – The number of strands in the braid.

  • Ai (Tuple[int]) – The sequence of simple elements (as indices or identifiers). Also known as Garside generators. From artin_left_normal_form(), each is a permutation: A[j] is where strand j ends.

n_half_twist: int
n_strands: StrictlyPositiveInt
Ai: tuple[tuple[int, ...], ...]
property dehornoy_floor: int

Computes the Dehornoy floor of the braid.

It is the unique integer m such that:

Δ^{2m} < β < Δ^{2m+2}

An estimate is floor(n_half_twist / 2) or floor(n_half_twist / 2) + 1 depending on the position of the braid in Dehornoy order.

For now, we return the conservative lower bound:

floor(n_half_twist / 2)

Returns:

the Dehornoy floor

Return type:

int

property garside_length: PositiveInt

Returns the Garside (canonical) length of the braid, defined as the number of simple elements A_i in the positive part.

Returns:

the Garside length

Return type:

int

braidpy.garside_canonical_form.artin_left_normal_form(generators, n_strands: int) → tuple[int, tuple[tuple[int, ...], ...]]

A braid word in Artin’s left normal form, Δ^k · A_1 ⋯ A_r.

The half twists are kept at the word’s end as it is read: there a crossing passes them by turning over (Δ σᵢ = σₙ₋ᵢ Δ), and an inverse crossing is a half twist less and a permutation braid more (σᵢ⁻¹ = (σᵢ⁻¹Δ) Δ⁻¹), so no factor read before is touched. Each factor is then made left-weighted with those before it (left_weighted()), and the half twists brought to the front, turning the factors over once.

Parameters:
  • generators – Signed Artin generators, +i for σ_i and -i for its inverse; 0 is ignored.

  • n_strands – Number of strands.

Returns:

k, the number of half twists in front — negative for half twists the other way — and the factors A_i as permutations.

braidpy.garside_canonical_form.left_weighted(k: int, factors: Sequence[tuple[int, ...]]) → tuple[int, tuple[tuple[int, ...], ...]]

Δ^k · F_1 ⋯ F_m, for any permutation braids F_i, in left normal form.

The factors are taken one at a time, each made left-weighted with the one before it, and that one with the one before it, back until a pair is left as it was: one pass back is enough for a left normal form followed by one permutation braid (Thurston; Epstein et al., Word Processing in Groups, chapter 9). Half twists the form begins with go into k, and factors left empty go.

Parameters:
  • k – Half twists in front.

  • factors – Permutation braids, Δ and the identity among them if need be.

Returns:

k and the factors, as artin_left_normal_form() gives them.

braidpy.garside_canonical_form.permutation_word(a: tuple[int, ...]) → list

A positive word for a permutation braid: each pair crosses once at most.

Dehornoy’s handle reduction: a braid word simplified, its handles removed, towards a form that tells braids apart.

exception braidpy.handles_reduction.HandleReducedButUnexpectedResult

Bases: FunctionalException

Exception to be raised if handle reduction is not finishing as expected

class braidpy.handles_reduction.HandleReductionMode(*values)

Bases: str, Enum

How far handle reduction goes.

  • FULL: every handle is reduced.

  • COMPARE: a partial reduction, stopped as soon as the braid is known to be positive, negative or trivial.

FULL = 'FULL'
COMPARE = 'COMPARE'
class braidpy.handles_reduction.HandleReductionResults(generators: list[int], sign: int, handle_reduction_mode: HandleReductionMode)

Bases: object

What handle reduction ends with: the braid word reduced, its sign in Dehornoy’s order (+1 positive, -1 negative, 0 trivial), and how far it went.

generators: list[int]
sign: int
handle_reduction_mode: HandleReductionMode
braidpy.handles_reduction.dehornoy_handle_indices(gens: list[int]) → tuple[PositiveInt, PositiveInt] | None

Detect the first Dehornoy handle in gens. A handle is of the form g … g^-1, with all intermediates having strictly larger absolute values.

Parameters:

gens (list[SignedCrossingIndex]) – list of Artin’s generator

Returns:

(i, j) — the indices of g and g^-1 — for the first such valid handle or None if no more handles

Return type:

Tuple[int, int] | None

braidpy.handles_reduction.reduce_handle(segment: list[int]) → list[int]

Reduces a Dehornoy handle of the form [sigma_m, u…, sigma_m^{-1}] by keeping u and replacing each sigma_{m+1} with sigma_{m+1}^{-1} * sigma_m * sigma_{m+1}.

Parameters:

segment (list[SignedCrossingIndex]) – segment corresponding to handle

Returns:

the segment with handle reduced (and no more complete handle, but it may create the start of new one)

Return type:

list[SignedCrossingIndex]

Raises:

ValueError – if segment is not a handle

braidpy.handles_reduction.dehornoy_sign(gens: list[int]) → int | None

Check if braid is Dehornoy positive, negative, neutral or if this can not be directly said from braid word

Parameters:

gens(SignedCrossingIndex – list of Artin’s generator

Returns:

1 if Dehornoy positive, -1 if Dehornoy negative, 0 if neutral element and None if it can not be said

Return type:

int|None

braidpy.handles_reduction.dehornoy_reduce_core(gens: list[int], mode: HandleReductionMode | str = HandleReductionMode.FULL, time_out_s: float = 1) → HandleReductionResults

Unified Dehornoy reduction engine.

Parameters:
  • -gens (List[SignedCrossingIndex]) – list of Artin’s generators

  • -mode (HandleReductionMode | str) – “FULL”: returns the fully reduced word. “COMPARE`: returns early if positive/neutral/negative.

  • -time_out_s (Optional(float)) – safety timeout. Default to 1

Returns:

generators, the reduced word, sign and the handle_reduction_mode used, where sign is:

Return type:

HandleReductionResults

  • 1 if Dehornoy positive

  • -1 if Dehornoy negative

  • 0 if neutral element

  • None in case it can not be said without reducing handles further

Raises:

HandleReducedButUnexpectedResult –

A braid word made shorter: the same braid, in fewer crossings.

Fewer crossings are fewer moves to make, by hand or on a machine. Three ways are tried, and the shortest word kept:

  • free cancellation: a crossing followed at once by its inverse, σᵢ σᵢ⁻¹, is no crossing at all (free_reduced());

  • braid relations: a crossing and its inverse kept apart by crossings that can be moved out of the way. Crossings of strands far apart commute, σᵢ σⱼ = σⱼ σᵢ when |i - j| ≥ 2, and three crossings of three strands can be made the other way round, σᵢ σᵢ₊₁ σᵢ = σᵢ₊₁ σᵢ σᵢ₊₁, signs mixed too (σᵢ σⱼ σᵢ⁻¹ = σⱼ⁻¹ σᵢ σⱼ). None of these changes the word’s length; each piece of the word, WINDOW crossings long, is rewritten every way they allow, up to SEARCH_BUDGET words, for one where two crossings cancel (shortened());

  • handle reduction (braidpy.handles_reduction): Dehornoy’s, which leaves no handle, σᵢ … σᵢ⁻¹ with only higher crossings between. Its word is often longer (the book’s #3072 goes from 114 crossings to 150), so it is kept only when it is shorter, after the search above.

A shortest word is not promised: finding one is hard in general. The word found is the same braid exactly (braidpy.braid.Braid.__eq__()), not merely one alike when repeated.

A word of moves round a ring (braidpy.annulus_braid) is shortened the same way, its relations read round the ring (shortened_ring()): crossing n, of the pair whose slots wrap, is a crossing like any other, neighbour of crossings n - 1 and 1, and a turn passes a crossing by renumbering it (turns_last()). The braid kept is the braid round the core (cored_word()), so a tube stays a tube.

braidpy.shortening.free_reduced(word: Sequence[int]) → tuple[int, ...]

A word with every crossing followed at once by its inverse taken out, and again, until none is.

Parameters:

word – The crossings, i for σᵢ and -i for σᵢ⁻¹.

Returns:

The word, freely reduced.

braidpy.shortening.rewrites(word: tuple[int, ...], ring: int | None = None) → Iterator[tuple[int, ...]]

The words one braid relation away, as long as this one: two neighbouring crossings of strands far apart swapped, or three crossings of three strands made the other way round, signs mixed too. Each is the same braid; read round a word, as a card runs it, they are what braidpy.making.lace.card_conjugate() searches.

Parameters:
  • word – The crossings, i for σᵢ and -i for σᵢ⁻¹.

  • ring – If given, the word is moves round a ring of so many slots (braidpy.annulus_braid): crossings are neighbours round the ring, crossing ring beside crossing 1, and a turn, ±(ring + 1), passes a crossing by renumbering it. On two slots the two crossings are not related at all.

Yields:

Each word one relation away.

braidpy.shortening.shortened(braid: Braid, window: int = 10, budget: int = 500) → Braid

The braid in as few crossings as are found; see the module.

Parameters:
  • braid – The braid.

  • window – How many crossings are rewritten at once.

  • budget – How many rewritings of each piece are tried.

Returns:

The same braid, exactly, its word no longer than the braid’s, on as many strands.

braidpy.shortening.shortened_ring(moves: Sequence[int], n_strands: int, window: int = 10, budget: int = 500) → list[int]

Moves round a ring in as few as are found: the turns moved to the end (turns_last()), where those one way and the other cancel, then the crossings searched as shortened() searches a word, their relations read round the ring.

Parameters:
  • moves – Crossings ±1 to ±n_strands, turns ±(n_strands + 1) (braidpy.annulus_braid).

  • n_strands – How many slots the ring has.

  • window – How many moves are rewritten at once.

  • budget – How many rewritings of each piece are tried.

Returns:

the same braid round the core, exactly (cored_word()), no more of them.

Return type:

The moves

Linking numbers: how many times the loops of a braid’s closure wind round each other.

Close a braid — join the top of each slot to the bottom of the same slot, round the outside — and its strands become loops, one per cycle of its permutation (braidpy.pure_braid.cycles()). Two loops have a linking number: how many times one winds round the other, counted with a sign. It does not change however the loops are bent, stretched or pulled tight, as long as neither passes through the other, so it is what is checked to know that a braid settled by physics is still the braid that was laid.

It is found two ways here, which agree:

  • from the braid word (linking_matrix()): half the signed number of crossings between the two loops’ strands, the usual combinatorial formula (Rolfsen, Knots and Links, 1976, §5.D);

  • from the yarns themselves, as curves in space (yarn_linking()): the Gauss linking integral, summed exactly over pairs of straight segments as the solid angle each pair subtends (Klenin and Langowski, Computation of writhe in modeling of supercoiled DNA, Biopolymers 54, 307, 2000), after closing the yarns up round the outside (close_yarns()).

From the word, a positive generator is a positive crossing, the usual convention: σ₁² closes into a Hopf link of linking number +1. braidpy’s own drawing of a word in space (braidpy.parametric_strand.strand_paths(), a positive generator’s lower strand passing over towards +y, the braid rising along z) is its mirror image: yarns laid that way measure the opposite sign. Either way, what is compared — a braid laid, then settled — is measured the same way.

braidpy.linking.close_yarns(yarns: Sequence[ndarray], turn: float = 0.0, pairing: Sequence[int] | None = None, bottom_turn: float = 0.0, reach: float = 40.0) → list[ndarray]

A braid’s yarns closed up into its loops, round the outside.

Each yarn’s top end is turned back by turn — the turn of the plate holding the top ends, so the top ends are where they were laid again — then taken up above the braid, out to reach from the axis, down the outside and in, under the braid, to the bottom end it joins, turned back by bottom_turn. Each yarn rises and falls at heights of its own, so no two closing paths meet.

Parameters:
  • yarns – Each yarn’s centreline, (n, 3), bottom end first, the braid rising along z round the z axis.

  • turn – How far the top ends have turned since they were laid, in radians.

  • pairing – For each yarn, the yarn whose bottom end its top end joins; by default the one whose bottom end is nearest it in angle, the top end turned back.

  • bottom_turn – How far the bottom ends have turned.

  • reach – How far out the closing paths go: well clear of the braid.

Returns:

the yarns of each, in order, with their closing paths.

Return type:

One polygon per loop

Raises:

ValueError – If the top ends do not each find a bottom end of their own.

braidpy.linking.gauss_linking_number(first: ndarray, second: ndarray) → float

The linking number of two closed polygons, from their geometry.

The Gauss linking integral, summed exactly over every pair of edges as the solid angle the pair subtends (Klenin and Langowski, 2000, eq. 15 and 16). For two closed curves that do not meet it is a whole number; any difference from one measures how near they come to touching.

Parameters:
  • first – The first polygon’s corners, (n, 3); its last corner joins its first.

  • second – The second’s, (m, 3).

Returns:

The linking number.

braidpy.linking.linking_matrix(braid, repeats: int = 1) → ndarray

The linking numbers of a braid’s closure, from its word.

Each crossing between strands of two different loops adds half its sign to their linking number; crossings of a loop with itself add nothing.

The braid may be taken repeated: each repeat makes the same crossings at the same slots, between whichever strands the repeats before have brought there, so the word is read once however many times it is repeated. A home braid of a few hundred repeats of a long unit (braidpy.similarity.home()) is millions of crossings, and reading them one by one took a minute.

Parameters:
  • braid – A Braid.

  • repeats – How many times it is repeated before it is closed.

Returns:

A symmetric matrix of whole numbers, one row and column per loop, the loops in the order of braidpy.pure_braid.cycles() (by their first strand) of the braid repeated; zero on the diagonal.

braidpy.linking.yarn_linking(yarns: Sequence[ndarray], turn: float = 0.0, pairing: Sequence[int] | None = None, bottom_turn: float = 0.0) → dict[str, object]

The linking numbers of yarns’ closure, from their geometry.

Parameters:
  • yarns – Each yarn’s centreline, bottom end first; see close_yarns(), which takes the other arguments too.

  • turn – How far the top ends have turned.

  • pairing – Which bottom end each top end joins.

  • bottom_turn – How far the bottom ends have turned.

Returns:

components, how many loops; and links, the linking number of every pair of loops, (0, 1), (0, 2), … (1, 2), …, not rounded.

Comparing and cataloguing braids

Whether braids are alike, and the braids braidpy knows.

A braid word: its crossings in order, compared as such.

One braid has many words: σ₁σ₂σ₁ and σ₂σ₁σ₂ are two words and one braid. A word is the same word only crossing for crossing; for the same braid, compare braids (BraidWord.braid()).

Braids are the same in four ways, each its own type with its own == and hash — a word (BraidWord), a braid (Braid), a pattern (BraidPattern) and a closed braid (ClosedBraid): see docs/source/comparing_braids.md, Four kinds of “the same”.

class braidpy.braid_word.BraidWord(generators: tuple[int, ...], n_strands: int)

Bases: object

A braid word: its crossings in order, i for σᵢ and -i for σᵢ⁻¹, on so many strands. Two words are equal when their crossings are, as tuples are.

Parameters:
  • generators – The crossings.

  • n_strands – How many strands.

generators: tuple[int, ...]
n_strands: int
braid() → Braid

The braid the word writes.

A braid made over and over, compared as such: the same pattern however often it is repeated and wherever it is read from.

σ₁σ₂ and σ₂σ₁ are two braids and one pattern, the one read from the other’s second crossing; so are w and w w. A pattern and a closed braid (braidpy.closed_braid) are both coarser than a braid, but neither than the other: w and w w close into two links.

Braids are the same in four ways, each its own type with its own == and hash — a word (BraidWord), a braid (Braid), a pattern (BraidPattern) and a closed braid (ClosedBraid): see docs/source/comparing_braids.md, Four kinds of “the same”.

class braidpy.braid_pattern.BraidPattern(braid: Braid)

Bases: object

A braid made over and over: what is the same however often it is repeated and wherever it is read from.

Two patterns are equal when their braids, brought home (home()), are conjugate (same_pattern()): proven so, or proven not. Where the search would be too long (SuperSummitSetTooLarge), as for long braids of many strands, they are equal when their fingerprints are (same_fingerprint()), which proves only that they differ; proven() says which. A pattern hashes by its fingerprint, which two equal patterns share.

Parameters:

braid – One braid of the pattern: one repeat, or several.

braid: Braid
fingerprint: Fingerprint
key() → tuple[Any, ...]

What two equal patterns share, exactly: the fingerprint’s exact parts (exact_part()).

alike(other: BraidPattern) → bool

Whether nothing measured tells two patterns apart: their fingerprints agree (key()). Fast, and what the ways of making a braid check what they made by; not a proof, which == and proven() give, and which can take seconds on many strands.

proven(other: BraidPattern) → bool | None

Whether two patterns are the same, proven; None if the search for it would be too long.

braidpy.braid_pattern.alike(a: Braid, b: Braid) → bool

Whether two braids make patterns nothing measured tells apart (BraidPattern.alike()): how the ways of making a braid check that they made it, whatever the words.

Parameters:
  • a – A braid.

  • b – Another.

Returns:

True if their fingerprints agree.

A braid closed, each strand’s end tied back to its own start: a knot or a link, compared as such.

It does not matter where the braid is read from, nor how many strands it is on (Markov’s theorem): σ₁ on two strands and a single strand close into one loop, two patterns (braidpy.braid_pattern) but one closed braid. Grommets and Turk’s heads are closed braids.

Braids are the same in four ways, each its own type with its own == and hash — a word (BraidWord), a braid (Braid), a pattern (BraidPattern) and a closed braid (ClosedBraid): see docs/source/comparing_braids.md, Four kinds of “the same”.

class braidpy.closed_braid.ClosedBraid(braid: Braid)

Bases: object

A braid closed: each strand’s end tied back to its own start, a knot or a link of several loops — a grommet, a Turk’s head.

It does not matter where the braid is read from, nor how many strands it is on (Markov’s theorem): σ₁ on two strands closes into one loop, as one strand does. Telling two knots apart is hard in general, and here two closed braids are equal when nothing measured tells them apart: the number of loops, the linking numbers of every two (linking_matrix()), sorted, and the Alexander polynomial (alexander_polynomial()). Equal so is not proven the same — a knot and its mirror image are equal so — but different is proven different.

Parameters:

braid – The braid closed.

braid: Braid
property loops: int

one for a knot.

Type:

How many loops it closes into

key() → tuple[Any, ...]

What it is measured by: its loops, their linking numbers sorted, and the coefficients of its Alexander polynomial.

Braids compared by what does not depend on how they are written down.

The same braid can be written many ways: from another starting point, with far crossings swapped, made of more or fewer repeats. What does not change is its topology, and a few numbers measure it. A braid’s fingerprint() holds them; similar() ranks other braids by how far their fingerprints are from it — to suggest, for a braid of your own, the braids it is most like.

The fingerprint is of the braid’s pattern, not of its length: the word’s repeating_unit(), and that unit repeated until every strand is back where it started (home()), which closes each strand into a loop of its own. It holds:

  • n_strands;

  • loops: how the unit takes the strands round — the sizes of the loops its closure makes, largest first (braidpy.pure_braid.cycles());

  • writhe: the unit’s crossings counted with their signs. It tells a braid from its mirror image, which the others do not;

  • linking: how many times each two strands wind round each other in a repeat, as linking numbers of the home braid’s loops (braidpy.linking.linking_matrix()), sorted, so that it does not matter which strand is which;

  • alexander: the Alexander polynomial of the home braid’s closure, sampled on the unit circle (braidpy.properties.alexander_on_circle()). It tells apart braids the linking numbers cannot: a plait from strands hanging straight, both with all their linking numbers 0.

  • burau: the characteristic polynomial of the home braid’s Burau matrix, sampled on the unit circle (braidpy.properties.burau_polynomial_on_circle()). It tells apart braids whose Alexander polynomial vanishes, as it does for many braids closing into several loops: a kumihimo disk’s edo yatsu from Ashley’s 8-strand square sinnet, ABOK #3070, which agree on all the rest.

  • burau_mod: that characteristic polynomial again, exactly, modulo a prime at a few values of t (braidpy.properties.burau_polynomial_mod()). The samples above are in floating point, which a long braid rounds differently for each way it is written; they say how near two braids are (distance()), this says whether they are the same (same_fingerprint()). It holds the Alexander polynomial too, as its value at 1.

None of these changes when a braid is read from another starting point (conjugation), and the loops, linking numbers and Alexander and Burau polynomials do not change either when the strands are numbered otherwise. Equal fingerprints do not prove two braids the same — no handful of invariants can — but different ones prove them different. braidpy.conjugacy.same_pattern() proves either way, more slowly; braidpy.braid_pattern.BraidPattern is a braid compared so.

class braidpy.similarity.Fingerprint(n_strands: int, loops: tuple[int, ...], writhe: int, linking: tuple[int, ...], alexander: tuple[float | None, ...], burau: tuple[float, ...] = (), burau_mod: tuple[tuple[int, ...], ...] = ())

Bases: object

What a braid’s topology is, in a few numbers; see the module.

n_strands: int
loops: tuple[int, ...]
writhe: int
linking: tuple[int, ...]
alexander: tuple[float | None, ...]
burau: tuple[float, ...] = ()
burau_mod: tuple[tuple[int, ...], ...] = ()
braidpy.similarity.distance(a: Fingerprint, b: Fingerprint) → float

How unlike two braids are, from their fingerprints: 0 for the same fingerprint, up to 6 for braids alike in nothing.

Each of the six parts adds a share from 0 to 1: the numbers of strands, the loops, the writhe, the linking numbers, and the Alexander and Burau polynomials on the circle (log₁₀ of them, so that a braid twice as long is not twice as far away).

Parameters:
  • a – A fingerprint.

  • b – Another.

Returns:

The distance.

braidpy.similarity.exact_part(mark: Fingerprint) → tuple

What same_fingerprint() compares: the parts of a fingerprint taken exactly, not sampled in floating point. Hashable: a key for braids by their pattern (braidpy.braid_pattern.BraidPattern).

Parameters:

mark – A fingerprint.

Returns:

Its strands, loops, writhe, linking numbers and Burau polynomials modulo a prime.

braidpy.similarity.fingerprint(braid: Braid) → Fingerprint

A braid’s fingerprint; see the module.

Parameters:

braid – The braid.

Returns:

Its fingerprint.

braidpy.similarity.home(braid: Braid) → tuple[Braid, Braid]

A braid’s pattern: its repeating unit, and the unit repeated until every strand is back where it started.

Parameters:

braid – The braid.

Returns:

The unit, and the home braid.

braidpy.similarity.same_fingerprint(a: Fingerprint, b: Fingerprint) → bool

Whether two fingerprints are the same: nothing measured tells the braids apart.

The polynomials are compared by burau_mod, exactly, not by their samples in floating point: those differ in the third digit for two long words of one braid, and burau_mod holds what they measure.

Parameters:
  • a – A fingerprint.

  • b – Another.

Returns:

True if they are the same.

braidpy.similarity.similar(braid: Braid, candidates: Mapping[str, Braid] | None = None, count: int = 5) → list[Match]

The braids most like this one, nearest first.

Parameters:
  • braid – The braid — your own, say.

  • candidates – The braids to look among, by name; by default those of braidpy.braid_catalog.

  • count – How many to give.

Returns:

Up to count matches, by distance(); same_fingerprint where nothing measured tells the two apart.

Whether two braids are the same braid however written: a proof, not a fingerprint.

Two words make the same braid, read from any starting point, when one is a conjugate of the other: b = c⁻¹ a c for some braid c. Fingerprints (braidpy.similarity) prove braids different but never the same. This decides it, by Garside’s method as Elrifai–Morton and Franco–González- Meneses made it practical:

  • every braid is written once in left normal form, Δ^p · A_1 ⋯ A_r (braidpy.garside_canonical_form.artin_left_normal_form());

  • cycling and decycling — taking A_1 round to the end, or A_r round to the front — are conjugations, and repeated they raise p and lower p + r as far as any conjugate allows: to the braid’s super summit set, the conjugates with p greatest and p + r least;

  • that set is finite, and each of its braids leads to the others by conjugating with the least permutation braids that keep it there, one for each crossing σ_i (minimal simple elements); so it is found whole by following them;

  • two braids are conjugate exactly when their super summit sets are the same, and so when one holds a braid of the other’s.

same_pattern() asks this of two braids’ patterns, their home() braids. Strands numbered from the other side, σ_i read as σ_{n-i}, need no asking: that is conjugation by Δ. The set can be large — exponential in the number of strands at worst — so the search stops at limit braids and says it could not tell.

A permutation braid is kept as in braidpy.garside_canonical_form: a tuple p, p[j] the place strand j ends at; a product is read left to right.

exception braidpy.conjugacy.SuperSummitSetTooLarge

Bases: Exception

The super summit set has more braids than the search was let find.

braidpy.conjugacy.are_conjugate(a: Braid, b: Braid, limit: int | None = 10000) → bool

Whether b = c⁻¹ a c for some braid c: the same braid read from another starting point.

Parameters:
  • a – A braid.

  • b – Another, on as many strands.

  • limit – The most braids of a super summit set to find.

Returns:

True if they are conjugate, False if not.

Raises:

SuperSummitSetTooLarge – if it cannot tell within limit braids.

braidpy.conjugacy.same_braid(a: Braid, b: Braid, limit: int | None = 10000) → bool

Whether two braids are the same pattern, made over and over, however written: their patterns (home()) conjugate. Not whether they are the same braid, which Braid.__eq__ tells: σ₁σ₂ and σ₂σ₁ are one pattern and two braids (braidpy.braid_pattern).

Home braids repeated as often are conjugate exactly when their units are, a braid’s roots being unique up to conjugacy (González-Meneses): so then the units are compared, far shorter. And braids whose fingerprints differ (same_fingerprint()) are different already: no search is made.

Parameters:
  • a – A braid.

  • b – Another.

  • limit – The most braids of a super summit set to find.

Returns:

True if they are proven the same, False if proven not.

Raises:

SuperSummitSetTooLarge – if it cannot tell within limit braids.

braidpy.conjugacy.same_pattern(a: Braid, b: Braid, limit: int | None = 10000) → bool

Whether two braids are the same pattern, made over and over, however written: their patterns (home()) conjugate. Not whether they are the same braid, which Braid.__eq__ tells: σ₁σ₂ and σ₂σ₁ are one pattern and two braids (braidpy.braid_pattern).

Home braids repeated as often are conjugate exactly when their units are, a braid’s roots being unique up to conjugacy (González-Meneses): so then the units are compared, far shorter. And braids whose fingerprints differ (same_fingerprint()) are different already: no search is made.

Parameters:
  • a – A braid.

  • b – Another.

  • limit – The most braids of a super summit set to find.

Returns:

True if they are proven the same, False if proven not.

Raises:

SuperSummitSetTooLarge – if it cannot tell within limit braids.

braidpy.conjugacy.super_summit_set(braid: Braid, limit: int | None = 10000) → set[tuple[int, tuple[tuple[int, ...], ...]]]

Every conjugate of a braid in its super summit set; see the module.

Parameters:
  • braid – The braid.

  • limit – The most braids to find; None for no limit.

Returns:

The super summit set, each braid in left normal form.

Raises:

SuperSummitSetTooLarge – if it has more than limit braids.

Braids by their topology, and the ways each is made.

Every other catalogue lists braids by how they are made: as a braid word (braidpy.braid_catalog), on a kumihimo disk (braidpy.mobidai_catalog), as one of Ashley’s solid sinnets (braidpy.solid_sinnets_catalog), on a braiding machine (braidpy.machine_catalog). Different ways can make the same braid: the plait is a braid word, Ashley’s #2965 on his stand, and what a three-carrier flat braiding machine makes. This catalogue lists braids by what they are — their fingerprint() — each pointing to every way of making it, and each way pointing back (topology_of()). For a braid of your own, related() gives the topologies nearest it.

A way of making a braid is a Method: a source and an entry of its catalogue, with the description Braid Studio makes it from (braidpy.web.build()). Its braid word is the one braidpy reads off it, over a whole period: for a disk braid that creeps round the disk from cycle to cycle, as kongo gumi does, as many cycles as bring every strand home. A machine braiding round cores has its cores in its word, each a strand standing still (braidpy.horn_gear.word).

Building the catalogue makes every braid of every catalogue — some ten seconds — so it is built once, when first asked for (catalog()). Braid Studio has it built with the site: export() writes it as JSON, load() reads it back, and for_page() says, for the braid on the page, every other way of making it and the braids nearest it.

class braidpy.topology_catalog.Method(source: str, name: str, title: str, spec: tuple[tuple[str, Any], ...], links: tuple[Link, ...] = ())

Bases: object

One way of making a braid.

Parameters:
  • source – Which catalogue: word, kumihimo, mobidai, sinnet or machine, as braidpy.web.build() has them.

  • name – The braid’s name in that catalogue.

  • title – What it is called, to show.

  • spec – What braidpy.web.build() makes it from.

  • links – Where it comes from and is shown: its catalogue entry’s (braidpy.catalog.Link).

source: str
name: str
title: str
spec: tuple[tuple[str, Any], ...]
property key: str

source:name, unique across the catalogues.

description() → dict[str, Any]

The description braidpy.web.build() makes it from.

describes(spec: Mapping[str, Any]) → bool

Whether a description is of this method’s braid, however much of it is made: as a page’s address has it, every value a string. Of a source whose every setting makes the braid what it is, as a shape’s (_DEFINING), every setting must agree, given or not.

class braidpy.topology_catalog.Topology(name: str, title: str, fingerprint: Fingerprint, methods: tuple[Method, ...])

Bases: object

A braid, as what it is: its fingerprint, and every way of making it.

Parameters:
  • name – The name it is listed by: its first method’s.

  • title – What it is called: its first method’s title.

  • fingerprint – Its fingerprint.

  • methods – The ways of making it, in the order the catalogues list them.

name: str
title: str
fingerprint: Fingerprint
methods: tuple[Method, ...]
braidpy.topology_catalog.braid_of(info: Mapping[str, Any]) → Braid | None

The braid braidpy.web.build() made, from what it says of it: its braid word, or, for a tubular machine, its word round the ring with the middle filled in.

Parameters:

info – The result’s info.

Returns:

The braid; None if it has no braid word.

braidpy.topology_catalog.catalog() → dict[str, Entry[Topology]]

The catalogue, as every catalogue lists its braids (braidpy.catalog): an entry per topology, by its first method’s name. Built the first time it is asked for.

Returns:

The entries.

braidpy.topology_catalog.export() → list[dict[str, Any]]

The catalogue as JSON-ready data, for load() to read back without making every braid again.

Returns:

Per topology, its name, title, fingerprint and methods.

braidpy.topology_catalog.for_page(spec: Mapping[str, Any], info: Mapping[str, Any], topologies: Sequence[Topology], count: int = 5) → dict[str, list[dict[str, Any]]]

What Braid Studio shows of the braid it made, beside it: the other ways of making it, and the braids nearest it.

A braid of the catalogues is known by its description, and has the fingerprint of its whole period; any other — your own — by the fingerprint of the braid made.

Parameters:
  • spec – The description the braid was made from.

  • info – What braidpy.web.build() said of it.

  • topologies – The catalogue (load()).

  • count – How many nearest braids to give.

Returns:

the methods making a braid with the same fingerprint, but the one shown; near: the nearest other topologies, each with its distance. Each has a title and source to show and the spec to make it from, as much of it as the page makes by default. Both are empty for a braid with no braid word.

Return type:

same

A catalogued braid’s links, by the source that makes it and its name there; none for one no catalogue lists.

braidpy.topology_catalog.load(data: Sequence[Mapping[str, Any]]) → tuple[Topology, ...]

The catalogue, from what export() wrote.

Parameters:

data – The exported data.

Returns:

The topologies.

braidpy.topology_catalog.methods() → list[Method]

Every way of making a braid the catalogues list, in their order: braid words, kumihimo, kumihimo disks, sinnets, machines.

Returns:

The methods.

braidpy.topology_catalog.related(braid: Braid, count: int = 5, topologies: Sequence[Topology] | None = None) → list[tuple[Topology, float]]

The topologies nearest a braid — one of your own, say — nearest first; distance 0 for its own, if the catalogue has it.

Parameters:
  • braid – The braid.

  • count – How many to give.

  • topologies – Where to look; by default this catalogue.

Returns:

Up to count topologies, each with its distance().

braidpy.topology_catalog.topology_of(source: str, name: str, topologies: Sequence[Topology] | None = None) → Topology | None

The topology a catalogue’s braid has: the way back from a method.

Parameters:
  • source – Its catalogue, as in Method.

  • name – Its name there.

  • topologies – Where to look; by default this catalogue.

Returns:

Its topology; None if it has no braid word.

What every catalogue of braids in braidpy has in common.

Each catalogue — braidpy.braid_catalog (braid words), braidpy.mobidai_catalog (kumihimo disk braids), braidpy.solid_sinnets_catalog (Ashley’s solid sinnets) and braidpy.machine_catalog (braiding machines) — keeps its braids as it likes best, and lists them in a CATALOG: an Entry per braid, by the name it is known by, in the order to offer them.

A site built from braidpy can add braids of its own to a catalogue without braidpy knowing them (extended()): a package of the site’s names, in the entry point group GROUP, a CATALOG to add to one of braidpy’s, by that catalogue’s module name (docs: A site of your own).

class braidpy.catalog.Entry(title: str, make: Callable[[], T], links: tuple[Link, ...] = ())

Bases: Generic[T]

One braid of a catalogue.

Parameters:
  • title – What it is called, to show.

  • make – Makes it, as its catalogue keeps it: a braid, a disk braid’s moves, a sinnet, a machine. Nothing is drawn.

  • links – Where it comes from, and where it is shown: a book and its number, a video, a page.

title: str
make: Callable[[], T]
property reference: str

the first link’s title.

Type:

Where it comes from, as one line

Bases: object

Where a braid comes from, or is shown being made.

Parameters:
  • title – What it is, to show: a book and its number, a video’s title.

  • kind – One of KINDS.

  • url – Where it is on the web; none for a book on paper, or a post known only by where it was.

title: str
kind: str = 'book'
url: str = ''
braidpy.catalog.ashley(number: int | str) → Link

The Ashley Book of Knots, at a knot’s number.

braidpy.catalog.extended(name: str, own: dict[str, Entry[T]]) → dict[str, Entry[T]]

A catalogue of braidpy’s, with the braids installed packages add to it: each entry point of GROUP named name (the catalogue’s module, as machine_catalog, or lace_machines for its lace machines) loads a dict of Entry by name, listed after braidpy’s own. A package’s catalogue imports from braidpy what its braids need, but not the catalogue it adds to.

Parameters:
  • name – The catalogue’s module name, without braidpy.; or lace_machines, braidpy.machine_catalog.LACE.

  • own – braidpy’s own entries.

Returns:

braidpy’s entries, then every package’s.

Raises:

ValueError – If a package names a braid the catalogue has already.

A catalogue of remarkable braids, as words.

braidpy.braid_catalog.garside_half_twist_braid(n_strands: StrictlyPositiveInt) → Braid

Compute the Garside half twist braid also known as Garside element ∆n or (simply ∆ if n=n_strands-1) ∆² is known to generate the “center” of the braid group Bn+1. This is the biggest simple element.

It is sometimes called fundamental braid. It can be obtained by recursion ∆n = σ1σ2…σn−1∆n−1

Demi-vrille

Composition of half_twist is giving a “torsade”

Parameters:

n_strands (StrictlyPositiveInt) – number of strands

Returns:

Braid

braidpy.braid_catalog.full_twist_braid(n_strands: StrictlyPositiveInt) → Braid

Compute the full twist braid ∆n² which is the square of Garside half twist braid ∆n It is known to generate the “center” of the braid group Bn.

Vrille

Composition of twist is giving a “torsade”

Parameters:

n_strands (StrictlyPositiveInt) – number of strands

Returns:

Braid

braidpy.braid_catalog.flat3(draw: bool = True) → tuple[Braid, int]

Basic braid with 3 strands going above central braid

ABOK 2965: “FLAT, ENGLISH, ORDINARY or COMMON SINNET is the plat or braid seen in schoolgirl pigtails. It is made of three strands and is the simplest possible plat. To make: Secure three strands together and make the end fast to a hook or nail. Hold two strands in the right hand and one in the left. Bring the outer right strand down across its sister strand and lay it parallel to and below the single left strand. Now bring the upper Ie ft strand down across its sister strand and lay it parallel to and below the single right strand. Repeat alternately”

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.inverted_flat3(draw: bool = True) → tuple[Braid, int]

Basic braid with 3 strands going below central braid. Also known as dutch braid

ABOK 2966: “Possibly a quicker but less usual way to make this plat is - to pass the strands at the back, employing only the first and second fingers and the thumbs”

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.square4(draw: bool = True) → tuple[Braid, int]

Basic round braid with 4 strands

ABOK 2999. “SQUARE SINNET of four strands. Used for lanyards, whips, whiplashes, quirts and leashes. With strands of two colors, arranged as pictured, the two colors helix around the sinnet, giving a barber-pole or candy-twist effect. The sinnet is made in two movements. First, take the top left strand, bring it around to the back of the other strands and then from back to front between the opposing strands. Finally lay it beside its sister strand into the lower position at the left. Second, take the right upper strand, bring it around to the back of the other strands and then from back to front between the opposing strands. Finally lay it beside its sister strand into the lower position at the right. In this size, this sinnet, although made by the SQUARE SINNET method, is identical with ROUND SINNET of four strands.”

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.asymmetric_flat4(draw: bool = True) → tuple[Braid, int]

Basic flat braid with 4 strands

ABOK 2969: “Unless for some special purpose, this method is usually limited to an odd number of strands, as with an even number of strands the sinnet is unsymmetrical. But I have seen the braid, made as if with three strands in the left hand and one in the right hand, as here pictured, used as edging on theater-seat upholstery. Of course it was machine-made.”

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.flat6(draw: bool = True) → tuple[Braid, int]

This one is probably not unique !

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.regular_flat6(draw: bool = True) → tuple[Braid, int]

Regular flat braid with 6 strands.

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.double_flat3(parallel: bool = False, draw: bool = True) → tuple[Braid, int]

ABOK 2971: “If the same method of turning edges is applied where units of two or three parallel round cords are used, instead of single strands, a distinctive sinnet results”

ABOK 2972, its parallel twin, is not made yet: “In this sinnet the strands are double and parallel. The effect is very different from the last, in which the edges were turned.”

Parameters:
  • parallel – ABOK 2972 rather than 2971: not made yet.

  • draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.weave3(draw: bool = True) → tuple[Braid, int]

A braid of 3 strands where 2 strands run parallel while the third one weaves through them.

ABOK 2973: “The number of sinnets that are possible with three strands only seem very limited. Three are given on these two facing pages.”

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.abok_2974(draw: bool = True) → tuple[Braid, int]
  1. With four strands the horizon is somewhat widened.

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.flat5(draw: bool = True) → tuple[Braid, int]

Flat braid with 5 strands.

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.flat_sinnet5(draw: bool = True) → tuple[Braid, int]

ABOK 2967: “With more than three strands it is well to secure the strands in a straight line. Two pencils and two elastic bands are sufficient apparatus. FLAT SINNET may be made with any odd number of strands in the way already described. The outer strands are moved alternately, and the tension is correctly and evenly arranged as each strand is passed”.

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.flat_sinnet7(draw: bool = True) → tuple[Braid, int]

ABOK 2968: “Seven strands is about the practical limit of the method. Beyond that there is difficulty in keeping it even. Even if a degree of success is achieved, a very little rough treatment will cause it to distort.”

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

class braidpy.braid_catalog.AshleyPlat(shape: str, n_strands: int, n_left: int, leads: tuple[str, ...], method: Literal['plat', 'square'] = 'plat', first: Literal['left', 'right'] = 'left')

Bases: object

A sinnet plaited in the hands as The Ashley Book of Knots says, its strands held in two groups, the top strand of each led in turn.

Two ways of leading a strand, as the book’s plat sinnets have them:

  • "plat" (#2976–#2998, and Smith’s square sinnets #3017–#3019): the top strand is led to the centre, over and under its sisters as its path says, and joins the other group, lowest in it;

  • "square" (the square sinnet’s method, #2999–#3014): the top strand goes round behind its sisters and behind the opposing strands, comes forward between two of them — its path as long as the opposing strands it passed, counted from the bottom — and comes back along its path, over and under them, to lie lowest in its own group.

The strands are numbered from the left, the left group first; a strand led over its neighbour to the right is σᵢ, as everywhere in braidpy.

Parameters:
  • shape – What the book calls it: “flat”, “French”, “square”…

  • n_strands – Strands.

  • n_left – Strands held in the left hand at the start.

  • leads – Each lead’s path, the left group’s top strand first unless first says otherwise, then the right’s, in turn.

  • method – How a strand is led.

  • first – The group whose strand is led first.

shape: str
n_strands: int
n_left: int
leads: tuple[str, ...]
method: Literal['plat', 'square'] = 'plat'
first: Literal['left', 'right'] = 'left'
braid() → Braid

The braid of one round of the leads.

Returns:

The braid.

Raises:

ValueError – If a lead passes more strands than it can, or the groups are not as they started after the round.

braidpy.braid_catalog.ASHLEY_PLATS: dict[int, AshleyPlat] = {2976: AshleyPlat(shape='French', n_strands=7, n_left=4, leads=('u1 o1 u1', 'u1 o1 u1'), method='plat', first='left'), 2977: AshleyPlat(shape='French', n_strands=6, n_left=3, leads=('o1 u1', 'u1 o1 u1'), method='plat', first='left'), 2980: AshleyPlat(shape='flat', n_strands=8, n_left=5, leads=('u3 o1', 'o3'), method='plat', first='left'), 2981: AshleyPlat(shape='flat', n_strands=6, n_left=3, leads=('o1 u1', 'u1 o2'), method='plat', first='left'), 2982: AshleyPlat(shape='flat', n_strands=7, n_left=5, leads=('u3 o1', 'u1 o1'), method='plat', first='left'), 2983: AshleyPlat(shape='flat', n_strands=7, n_left=4, leads=('u2 o1', 'u2 o1'), method='plat', first='left'), 2984: AshleyPlat(shape='flat', n_strands=7, n_left=5, leads=('u2 o2', 'o2'), method='plat', first='left'), 2985: AshleyPlat(shape='flat', n_strands=9, n_left=5, leads=('u2 o2', 'u2 o2'), method='plat', first='left'), 2986: AshleyPlat(shape='flat', n_strands=11, n_left=6, leads=('u2 o3', 'u2 o3'), method='plat', first='left'), 2987: AshleyPlat(shape='flat', n_strands=11, n_left=6, leads=('u2 o2 u1', 'u2 o2 u1'), method='plat', first='left'), 2988: AshleyPlat(shape='French', n_strands=5, n_left=3, leads=('o2', 'o2', 'u2', 'u2'), method='plat', first='left'), 2989: AshleyPlat(shape='duplex', n_strands=6, n_left=4, leads=('o3', 'o2', 'u3', 'u2'), method='plat', first='left'), 2990: AshleyPlat(shape='twill', n_strands=9, n_left=5, leads=('u1 o3', 'u1 o3', 'u2 o2', 'u2 o2'), method='plat', first='left'), 2991: AshleyPlat(shape='twill', n_strands=10, n_left=5, leads=('o2 u2', 'o2 u2 o1', 'o2 u2', 'o2 u3'), method='plat', first='left'), 2992: AshleyPlat(shape='twill', n_strands=10, n_left=5, leads=('o1 u3', 'o1 u3 o1', 'o1 u3', 'o1 u4'), method='plat', first='left'), 2994: AshleyPlat(shape='doubled-edge flat', n_strands=6, n_left=4, leads=('o1 u2', 'o2', 'u1 o2', 'u2'), method='plat', first='left'), 2995: AshleyPlat(shape='doubled-edge flat', n_strands=7, n_left=4, leads=('o2 u1', 'u1 o2', 'u2 o1', 'o1 u2'), method='plat', first='left'), 2996: AshleyPlat(shape='doubled-edge flat', n_strands=8, n_left=5, leads=('u1 o2 u1', 'u1 o2', 'o1 u2 o1', 'o1 u2'), method='plat', first='left'), 2997: AshleyPlat(shape='doubled-edge flat', n_strands=10, n_left=6, leads=('u2 o2 u1', 'u2 o2', 'o2 u2 o1', 'o2 u2'), method='plat', first='left'), 2998: AshleyPlat(shape='doubled-edge flat', n_strands=11, n_left=6, leads=('u1 o2 u1 o1', 'u2 o1 u2', 'o1 u1 o2 u1', 'o1 u2 o1 u1', 'o2 u1 o2', 'u1 o1 u2 o1'), method='plat', first='left'), 3001: AshleyPlat(shape='square', n_strands=8, n_left=4, leads=('o2', 'o2'), method='square', first='left'), 3002: AshleyPlat(shape='square', n_strands=12, n_left=6, leads=('o3', 'o3'), method='square', first='right'), 3003: AshleyPlat(shape='half round', n_strands=6, n_left=3, leads=('o1', 'o1'), method='square', first='left'), 3004: AshleyPlat(shape='half round', n_strands=8, n_left=4, leads=('o1', 'o1'), method='square', first='left'), 3005: AshleyPlat(shape='half round', n_strands=10, n_left=5, leads=('o2', 'o2'), method='square', first='left'), 3006: AshleyPlat(shape='half round', n_strands=8, n_left=4, leads=('o1 u1', 'o1 u1'), method='square', first='left'), 3007: AshleyPlat(shape='ellipse', n_strands=8, n_left=4, leads=('o1 u2', 'o1 u1'), method='square', first='left'), 3008: AshleyPlat(shape='ellipse', n_strands=6, n_left=3, leads=('o2', 'o1'), method='square', first='left'), 3009: AshleyPlat(shape='ellipse', n_strands=8, n_left=4, leads=('o3', 'o1'), method='square', first='left'), 3010: AshleyPlat(shape='ellipse', n_strands=10, n_left=5, leads=('o3', 'o2'), method='square', first='left'), 3011: AshleyPlat(shape='round', n_strands=6, n_left=3, leads=('o1 u1', 'o1'), method='square', first='left'), 3012: AshleyPlat(shape='round', n_strands=8, n_left=4, leads=('o1 u1 o1', 'o1 u1 o1'), method='square', first='left'), 3013: AshleyPlat(shape='square', n_strands=5, n_left=3, leads=('o1', 'o2'), method='square', first='left'), 3014: AshleyPlat(shape='square', n_strands=7, n_left=4, leads=('o2', 'o2'), method='square', first='left'), 3017: AshleyPlat(shape='square', n_strands=4, n_left=3, leads=('o2', 'o1', 'u2', 'u1'), method='plat', first='left'), 3018: AshleyPlat(shape='square', n_strands=8, n_left=5, leads=('o4', 'o3', 'u4', 'u3'), method='plat', first='left'), 3019: AshleyPlat(shape='square', n_strands=12, n_left=7, leads=('o6', 'o5', 'u6', 'u5'), method='plat', first='left')}

The plat sinnets of The Ashley Book of Knots (chapter 38) made as its text says, by number. Left out: those of doubled strands (#2972, #2978, coachwhipping #3015, #3016), the “trick” sinnet #2993, #2979 (#2976 made another way, the same braid), and the round sinnets worked turning in the hand (#3021 on), which are ring words.

braidpy.braid_catalog.RECTANGULAR_14 = '2 -5 -9 7 -11 -3 13 1 -6 10 -8 4 -4 -10 -7 -12 -2 4 7 10 5 9 -7 -13 -1 11 3 -10 -4 6 8 12'

The rectangular braid of fourteen strands, as the word it repeats.

The fourteen places fall into two sets of seven that never mix: the word’s permutation is two 7-cycles, so seven repeats bring every strand home. The sets interleave across the face, one place of the first, then two of the second, then two of the first: ABBAABBAABBAAB. Thirty-two crossings a repeat, as many one way as the other, so nothing twists.

braidpy.braid_catalog.rectangular14(draw: bool = True) → tuple[Braid, int]

The rectangular braid of fourteen strands (RECTANGULAR_14).

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.RECTANGULAR_20 = '2 19 -4 -16 1 -10 -9 -11 10 3 17 -5 -15 -6 -14 -4 -16 -8 -12 5 15 -3 -17 9 11 -2 6 14 -18 7 13 -6 -14 17 3 8 12 7 13 -12 -1 -8 -19 5 15 18'

The rectangular braid of twenty strands, as the word it repeats.

Forty-six crossings a repeat, as many one way as the other, and every one of the nineteen crossing places used. The twenty places fall into two sets of ten that never mix — the word’s permutation is two 10-cycles — so ten repeats bring every strand home. Wider than RECTANGULAR_14 and not a wider copy of it: the sets interleave as ABBABAABABBABAABABBA, in threes and pairs rather than evenly.

braidpy.braid_catalog.rectangular20(draw: bool = True) → tuple[Braid, int]

The rectangular braid of twenty strands (RECTANGULAR_20).

Parameters:

draw – Draw the braid as it is made (the default); False only builds it.

Returns:

the braid object describing the single step to realize the braid n: the number of iterations to get back to initial order of strands

Return type:

Braid

braidpy.braid_catalog.word_examples() → list[dict[str, Any]]

Braids to try as braid words, as plain data: each of CATALOG reduced to the word it repeats, then WORD_EXAMPLES. A braid is repeated as many times as brings every strand home, twice or more: at least _FEWEST_CROSSINGS crossings.

Returns:

Per braid, its word, n_strands, repeat and title; a ring word’s layout too.

Making braids

Kumihimo, Ashley’s sinnets, braiding and lace machines, and how to make a given braid on each.

kumihimo.py

Kumihimo simulator and visualizer.

Features: - Simulates formal S/R sequences (swap, rotate) - Tracks Artin braid word (σ generators) - Produces a vertical timeline with labeled steps - Displays step labels, strand IDs, and pattern info

class braidpy.kumihimo.Kumihimo(n_strands: int = 8)

Bases: object

Simulate and visualize Kumihimo braiding sequences with annotations.

Variables:
  • n_strands (int) – Number of strands (divisible by 4).

  • k (int) – Number of positions per quarter turn.

  • state (List[int]) – Current strand order around the disk.

  • braid_word (List[int]) – Sequence of Artin generators, signed.

  • history (List[str]) – Record of performed S/R moves.

  • frames (List[List[int]]) – Strand configurations per step.

  • angles (np.ndarray) – Angular positions of strand slots.

  • colors (np.ndarray) – Color assigned to each strand.

  • pattern (str) – Original S/R pattern executed.

swap_top_bottom() → None

Swap top and bottom strands.

Returns:

None

rotate(turns: int = 1) → None

Rotate the disk clockwise by quarter turns.

Parameters:

turns (int, optional) – Number of 90° clockwise turns. Defaults to 1.

move(pattern: str) → Kumihimo

Execute a sequence of S/R operations.

Parameters:

pattern (str) – String of moves, e.g. “SRSRSR”.

Returns:

Self (for chaining).

Return type:

Kumihimo

plot_timeline(step_width: float = 2.5, show_ids: bool = True) → None

Plot the braid evolution as horizontally arranged disks.

Parameters:
  • step_width (float, optional) – Horizontal spacing between steps. Defaults to 2.5

  • show_ids (bool, optional) – Whether to display strand indices. Defaults to True.

animate(output_html: str | None = None, **kwargs)

Animate the moves made so far on the disk, seen from above.

A Plotly animation in which each strand runs from its slot to the middle and moves continuously from step to step — see animate_kumihimo(), which kwargs are passed to.

Parameters:

output_html – If given, write the animation to this HTML file.

Returns:

The animation.

Return type:

plotly.graph_objects.Figure

mobidai.py

A simulator for the traditional Japanese braiding stand (Marudai / Mobidai). Sometimes known as friendship disk and used for kumihimo braiding.

This module provides classes to model, simulate, and visualize the braiding process, based on configurations of slots, strands, and moves. It also includes topological tracking to extract the Artin Braid Group word associated with the braiding moves.

exception braidpy.mobidai.SlotAlreadyInUseError

Bases: Exception

Exception raised when attempting to move a strand to an occupied slot.

class braidpy.mobidai.Strand(color: str, position: int, id: int = -1)

Bases: object

Represents a strand placed on a mobidai slot.

Variables:
  • color (str) – The color of the strand (format as supported by matplotlib).

  • position (int) – The slot number (1-indexed) where the strand currently sits.

  • id (int) – A unique identifier for the strand to track it topologically. Defaults to -1 (assigned during initialization).

color: str
position: int
id: int = -1
class braidpy.mobidai.Move(from_slot: int, to_slot: int, force_direction: int = 0)

Bases: object

Represents one strand move from one slot to another.

Variables:
  • from_slot (int) – The slot number where the strand starts.

  • to_slot (int) – The slot number where the strand will be placed.

  • force_direction (int) – The way round it goes: 1 clockwise, -1 anticlockwise, 0 (the default) the shorter way.

from_slot: int
to_slot: int
force_direction: int = 0
class braidpy.mobidai.MobidaiConfig(strands: list[Strand], moves: list[Move], n_shift_after_cycle: int, n_slots: int = 32, is_clockwise: bool = True)

Bases: object

Configuration of a mobidai setup.

Variables:
  • strands (List[Strand]) – Initial list of strands on slots.

  • moves (List[Move]) – Sequence of moves performed in one braiding cycle.

  • n_shift_after_cycle (int) – Number of slots to rotate between cycles to come back to strands positions similar to initial positions.

  • n_slots (int) – Total number of slots on the mobidai disk. Defaults to 32.

  • is_clockwise (bool) – Direction of rotation for numbering (True = clockwise). Defaults to True.

strands: list[Strand]
moves: list[Move]
n_shift_after_cycle: int
n_slots: int = 32
is_clockwise: bool = True
braidpy.mobidai.cycle_drift(start_slots: list[int], moves: list[Move], n_slots: int, n_shift_after_cycle: int = 0) → int

How many slots round a cycle leaves the strands from where they began.

Many braids do not bring their strands back to the slots they started in, but to the same arrangement one or more slots round — kongo gumi creeps one slot back each cycle — and the braider simply makes the same moves again from where the strands now are. That shift is a property of the cycle, so it is read off it rather than written down: one cycle is made, and the occupied slots compared with the starting ones turned round.

Parameters:
  • start_slots – The slots holding a strand at the start.

  • moves – One cycle’s moves.

  • n_slots – Slots round the disk.

  • n_shift_after_cycle – How far the disk is turned after the moves.

Returns:

The drift, the smallest turn that matches; 0 if the cycle does not bring the strands back to their arrangement at all.

braidpy.mobidai.drifted(move: Move, offset: int, n_slots: int) → Move

The same move, made offset slots round.

class braidpy.mobidai.BraidTracker(strands: list[Strand], n_slots: int, is_disk_clockwise: bool)

Bases: object

Tracks the topological state of the strands to generate Artin words.

This class maintains the ‘linear order’ of strands. When a strand moves physically on the disk, this tracker determines which strands it crosses over and generates the corresponding Artin generators (σ_i or σ_i^-1).

Variables:
  • linear_order (List[int]) – A list of Strand IDs representing their current order from ‘left’ to ‘right’ (or counter-clockwise to clockwise).

  • strand_map (Dict[int, Strand]) – Reference to the actual strand objects.

get_generators_for_move(move: Move) → str

The braid word’s generators for a move: the strand moved crossing every strand it passes, the way it goes round; empty if no strand is in the slot it is moved from.

class braidpy.mobidai.Mobidai(config: MobidaiConfig)

Bases: object

A kumihimo disk at work: its slots, the strands in them, and the braid word its moves make.

slots: dict[int, Strand | None]
braid_word: list[str]
property generators: list[int]

The braid word as signed generator indices.

braid_word keeps one readable string per move, such as "s2^-1 s1^-1". The rest of braidpy speaks signed integers — that is what Braid takes, and what braid_word() returns — so this gives the same word in that form, flattened across moves.

Returns:

+i for si, -i for si^-1.

Return type:

One signed index per crossing

Raises:

ValueError – If a generator cannot be read, which would mean the tracker had written something this cannot parse.

single_step(move: Move, slots: dict[int, Strand | None]) → dict[int, Strand | None]

Make one move: the strand in its slot moved to the slot it goes to, the generators it makes added to the braid word.

Raises:

SlotAlreadyInUseError – If that slot already holds a strand.

rotate(steps: int)

Turn the disk so many slots round, every strand with it.

all_steps()

Make one cycle of moves, then turn the disk.

Each cycle is made drift slots round from the one before, so a braid that creeps round the disk is worked as it is by hand.

visualize(ax=None, shift_back_to_initial_position: bool = False)

Visualizes the current state of the mobidai.

Parameters:
  • ax (matplotlib.axes.Axes, optional) – Axis to draw on. Creates one if None.

  • shift_back_to_initial_position (bool, optional) – If True, rotates the visualization counter to the total shift, making the strands appear stationary relative to the viewer. Defaults to False.

mobidai_catalog.py

Kumihimo braids transcribed from Bracelets Kumihimo, technique des bracelets japonais by Agnès Delage-Calvet, and braids shared by Richard Buenger in the Kumihimo group on Facebook (each entry says which).

Each entry carries everything a Mobidai needs: how many slots the disk has, which colour starts in which slot, the moves of one cycle, and how far the disk is turned before the cycle repeats. Call CatalogedMobidai.to_config() to run one. CATALOG lists them, as every catalogue does (braidpy.catalog).

braidpy.mobidai_catalog.CatalogedBraid

alias of CatalogedMobidai

class braidpy.mobidai_catalog.CatalogedMobidai(name: str, n_slots: int, initial_slots: tuple[tuple[int, str], ...], moves: tuple[tuple[int, int], ...], n_shift_after_cycle: int = 0, source: str = 'Delage-Calvet, Bracelets Kumihimo')

Bases: object

One disk braid from the book, ready to run on a mobidai.

Parameters:
  • name – How the braid is referred to here.

  • n_slots – Slots round the disk.

  • initial_slots – (slot, colour) for each strand at the start.

  • moves – (from_slot, to_slot) in the order they are made, for one cycle.

  • n_shift_after_cycle – How far the disk turns before repeating; some braids are a cycle of moves plus a rotation.

  • source – Where in the book it comes from.

name: str
n_slots: int
initial_slots: tuple[tuple[int, str], ...]
moves: tuple[tuple[int, int], ...]
n_shift_after_cycle: int = 0
source: str = 'Delage-Calvet, Bracelets Kumihimo'
property n_strands: int

How many strands are threaded.

to_config(**overrides)

A MobidaiConfig for this braid.

Parameters:

**overrides – Passed to the config, to vary a braid without editing the catalogue.

Returns:

Ready to hand to Mobidai.

Return type:

MobidaiConfig

disk_animation.py

A braiding disk, animated as the braider sees it: from above.

Each strand runs from its slot on the rim in to the middle, where the braid goes down through the hole — so it is drawn as a radial line from the centre to its carrier. The carriers move continuously, step by step, along the paths disk_trajectories() gives them, so this is the same motion the braid is laid from, and what is seen here is what lay_yarns() builds on.

A strand lifted over the others passes inside the rim — over, seen from above — and is drawn on top of them while it does, so the picture says which way every crossing goes.

animate_kumihimo() and animate_mobidai() read their sources onto a disk and animate it; animate_disk() does the drawing for any disk.

class braidpy.disk_animation.BraidGrowth(start, steps, n_slots: int, yarn_diameter: float = 0.12, clockwise: bool = True, take_off_per_row: float = 1.5, window_rows: float = 12, iterations: int = 300, samples_per_row: int = 12, shown_per_row: int = 4)

Bases: object

The braid a disk is making, as it grows below it — for a side view.

The braid is laid once, from its crossings round a ring and tightened (see disk_braid()), and shown as the disk is worked: each crossing reaches the fell, just under the disk, as the strand making it passes the one it crosses on the disk, the older rows carried down by the take-off. Rows are made in the order their crossings are, so nothing shows below the disk before it is made on it. The braid hangs from the disk and turns with it. Only the last window_rows rows are shown, as a braider sees the length of braid nearest the disk.

Parameters:
  • start – Each strand’s slot, 1-based.

  • steps – Per step, the strands that move and by how many slots.

  • n_slots – Slots round the disk.

  • yarn_diameter – Yarn diameter.

  • clockwise – Whether slot numbers go round clockwise, seen from above.

  • take_off_per_row – Braid taken off per row of crossings, in diameters.

  • window_rows – Rows of braid shown below the fell.

  • iterations – Tightening steps.

  • samples_per_row – Points along each yarn per row, as tightened: fewer and the tightening can snap a yarn across its neighbour.

  • shown_per_row – Points along each yarn per row, as drawn.

Raises:

ValueError – If the moves cross no strands: there is no braid.

rows_at(time: float) → float

How many rows the braid has, time disk steps in.

turn_at(rows: float, carriers: Mapping[Hashable, Sequence[float]]) → float

How far round the braid hangs, its strands nearest their carriers.

Parameters:
  • rows – Rows made.

  • carriers – Each strand’s carrier on the disk, from its centre.

Returns:

The angle, anticlockwise seen from above, to turn the braid by.

traces(time: float, color: Mapping[Hashable, str], carriers: Mapping[Hashable, Sequence[float]] | None = None) → list[Scatter3d]

Each yarn’s visible length, time disk steps in.

Parameters:
  • time – Disk steps made.

  • color – Each strand’s colour.

  • carriers – Each strand’s carrier on the disk, from its centre, to turn the braid as the disk is; not turned if None.

fell() → Scatter3d

A ring at the fell, where the braid forms, just under the disk.

scene() → dict

The side view’s scene: seen from the front of the disk as drawn from above — its bottom edge — the braid hanging down.

braidpy.disk_animation.animate_disk(trajectories: StrandTrajectories, step_labels: Sequence[str] | None = None, title: str = 'Braiding disk', output_html: str | None = None, colors: Sequence[str] | None = None, show_ids: bool = True, frame_duration_ms: int = 50, max_frames: int = 900, braid: BraidGrowth | None = None) → Figure

Animate strands moving round a disk, seen from above.

Parameters:
  • trajectories – Where the strands go — from disk_trajectories() or a reader built on it. One unit of time is one step.

  • step_labels – What each step is, shown on the slider as it is made.

  • title – Figure title.

  • output_html – If given, write the animation to this HTML file.

  • colors – One colour per strand; the horn gear animation’s if None.

  • show_ids – Name each strand at its carrier.

  • frame_duration_ms – How long each frame is shown.

  • braid – Show the braid the disk is making beside it, growing below the disk — see BraidGrowth.

  • max_frames – Frame budget: a long sequence is sampled more coarsely rather than written to a page too big to open.

Returns:

The figure, with one frame per sample kept.

braidpy.disk_animation.kumihimo_step_labels(kumihimo, n_strands: int | None = None) → list[str]

What each disk step of a kumihimo sequence is, for the slider.

A swap takes three steps on the disk (see kumihimo_steps()); a rotation one.

braidpy.disk_animation.animate_kumihimo(kumihimo, n_strands: int | None = None, output_html: str | None = None, title: str | None = None, samples_per_step: int = 12, side_view: bool = False, yarn_diameter: float = 0.12, **kwargs) → Figure

Animate a kumihimo sequence on its disk, seen from above.

Parameters:
  • kumihimo – A Kumihimo, or a pattern of S and R for n_strands strands.

  • n_strands – Strands, when given a pattern.

  • output_html – If given, write the animation to this HTML file.

  • title – Figure title; names the pattern if None.

  • samples_per_step – Frames per disk step.

  • side_view – Also show the braid growing below the disk, from the side.

  • yarn_diameter – The yarn’s diameter in the side view, the disk’s radius being 1.

  • **kwargs – Passed on to animate_disk().

Returns:

The figure.

braidpy.disk_animation.animate_mobidai(mobidai, n_cycles: int = 1, drift: int | None = None, output_html: str | None = None, title: str | None = None, samples_per_step: int = 12, slot_offset: float = 0.0, side_view: bool = False, yarn_diameter: float = 0.12, **kwargs) → Figure

Animate a mobidai’s cycles on its disk, seen from above.

Parameters:
  • mobidai – A Mobidai or its configuration.

  • n_cycles – Cycles to animate.

  • drift – Slots each cycle’s moves are shifted from the one before; read off the cycle if None — see mobidai_steps().

  • output_html – If given, write the animation to this HTML file.

  • title – Figure title.

  • samples_per_step – Frames per move.

  • slot_offset – Slots the numbering is turned by: 0.5 puts the top of the disk between the last slot and slot 1, as a kumihimo disk is marked.

  • side_view – Also show the braid growing below the disk, from the side.

  • yarn_diameter – The yarn’s diameter in the side view, the disk’s radius being 1.

  • **kwargs – Passed on to animate_disk().

Returns:

The figure.

braidpy.disk_animation.animate_sinnet(sinnet, n_cycles: int = 1, output_html: str | None = None, title: str | None = None, samples_per_step: int = 12, side_view: bool = False, yarn_diameter: float = 0.12, **kwargs) → Figure

Animate an Ashley solid sinnet on its disk, seen from above.

Every strand is followed from space to space, lifted over the strands it passes, and the strands of a space slide together to make room — see sinnet_disk(). Spaces are numbered as the book draws them: anticlockwise from the left.

Parameters:
  • sinnet – An AshleySolidSinnet.

  • n_cycles – Times its moves are made.

  • output_html – If given, write the animation to this HTML file.

  • title – Figure title; says how many strands and spaces if None.

  • samples_per_step – Frames per step.

  • side_view – Also show the braid growing below the disk, from the side.

  • yarn_diameter – The yarn’s diameter in the side view, the disk’s radius being 1.

  • **kwargs – Passed on to animate_disk().

Returns:

The figure.

Ashley disk braid visualizer.

Renders an annulus partitioned into sectors. Strands in each sector lie on a common circle and are ordered counterclockwise. Each frame shows the state before a move, optional arrows for the active move path, and the final state. Optionally builds an animated GIF.

According to ABOK3036 “All odd strands, when they are moved, are led to the right, counterclockwise; all even strands are led. to the left, clock- wise. The earliest strand to occupy any space is always the next one to be moved from that space. The earliest odd-numbered strand is always the right-hand strand of its group; when it is moved it is led to the right, counterclockwise, until it reaches its destination, where it is put into the near or left-hand position of an odd-numbered space. At an even-numbered space the left strand of the group is moved to the left (clockwise) until it reaches its destination, where it is put into the right-hand position. The two ways of moving strands are indicated with arrows in diagram fIi 304 I. All strands are moved “over alL” If, however, an odd strand is led to an even-numhered space, as is sometimes the case, it passes to the right as it lea … ~s the odd space but is carried to the right side of the even-numbered space when it arrives. If a strand from an even-numbered space is led to an odd-numbered space, it is moved to the left but is placed at the left side of the odd-numbered space.”

Requirements:

matplotlib imageio (optional, for GIF)

class braidpy.ashley_solid_sinnet.AshleySolidSinnet(initial_counts_per_space: list[int], moves: list[tuple[int, int]], shape: str | None = None, all_right: bool = False)

Bases: object

Ashley-style braid pattern.

Spaces are numbered anticlockwise, seen from above, from the left of the disk as the book draws it. A strand is moved over all the strands it passes: from an odd space its right-hand strand, anticlockwise; from an even space its left-hand strand, clockwise. It goes in at the left (clockwise) end of an odd space and at the right (anticlockwise) end of an even one, so the earliest strand in a space is always the next to leave it. When all_right, as the book has it for “All strands move to the right”, the strand from an even space is led anticlockwise too, still from its left and over all.

Variables:
  • initial_counts_per_space (List[int]) – Number of strands per sector. 1-based sectors.

  • moves (List[Tuple[int, int]]) – Sequence of (from_sector, to_sector) moves, each 1-based.

  • shape (Optional[str]) – The cross-section the sinnet takes when made, as the book names it: “round”, “triangle”, “hexagon”…

  • all_right (bool) – Every strand is led to the right, anticlockwise, not only those from odd spaces. The same table makes another braid so: #3057 and #3058 differ only in this.

initial_counts_per_space: list[int]
moves: list[tuple[int, int]]
shape: str | None = None
all_right: bool = False
goes_right(space: int) → bool

Whether a strand leaving space is led to the right, anticlockwise. Which end it leaves from, and which it arrives at, is the space’s parity whichever way it goes.

property n_strands: int

How many strands the sinnet has.

disk(n_cycles: int = 1) → SinnetDisk

The sinnet worked on a disk — see sinnet_disk().

annular_word(n_cycles: int = 1) → list[int]

The braid it makes, round the ring — see disk_annular_word().

braid(n_cycles: int = 1) → Braid

The braid it makes, as a flat braid word: the ring’s, with the middle solid — see solid_word().

to_mobidai() → MobidaiConfig

One cycle as a kumihimo disk (mobidai) pattern — see sinnet_to_mobidai().

animate(n_cycles: int = 1, **kwargs)

Animate it on its disk, seen from above — see animate_sinnet().

braid_3d(yarn_diameter: float = 0.12, n_cycles: int = 4, **kwargs)

The braid it makes, laid and tightened — see disk_braid().

class braidpy.ashley_solid_sinnet.SinnetDisk(n_spaces: int, slots_per_space: int, start: dict[Hashable, int], steps: list[dict[Hashable, int]], labels: list[str])

Bases: object

A sinnet set out on a disk with a slot for every place a strand stops.

Each space has slots_per_space slots side by side, its strands kept together in the middle of them. Slots are numbered anticlockwise, as the spaces are, from the clockwise end of space 1.

Variables:
n_spaces: int
slots_per_space: int
start: dict[Hashable, int]
steps: list[dict[Hashable, int]]
labels: list[str]
property n_slots: int

The disk’s slots, every space’s.

middle_slot(space: int) → int

The slot in the middle of a space, where its number is written.

property slot_offset: float

How far round the numbering is turned to draw it as the book does: space 1 starting on the left, anticlockwise from there.

braidpy.ashley_solid_sinnet.sinnet_disk(sinnet: AshleySolidSinnet, n_cycles: int = 1) → SinnetDisk

Work a sinnet on a disk, following every strand.

Each move takes the earliest strand of its space — the right-hand one of an odd space, the left-hand one of an even space — round the disk over every strand it passes, the way AshleySolidSinnet.goes_right() says, into its place at the end of the space it goes to. The strands left behind, and those it joins, then slide along together to the middle of their spaces, so each space always has room either side of its strands.

Parameters:
  • sinnet – The sinnet.

  • n_cycles – How many times its moves are made.

Returns:

The disk, and the steps that work it.

Raises:

ValueError – If a move is from or to a space that is not there, or from a space to itself.

braidpy.ashley_solid_sinnet.sinnet_to_mobidai(sinnet: AshleySolidSinnet) → MobidaiConfig

One cycle of a sinnet as a kumihimo disk (mobidai) pattern.

The disk of sinnet_disk(), numbered as a mobidai is, every move made from slot to slot the way the sinnet goes round — anticlockwise from an odd space, clockwise from an even one, unless all go to the right — and every slide made one strand at a time, the front one first. A sinnet whose cycle brings each space back to its count brings every slot back too, so the pattern is simply repeated.

Parameters:

sinnet – The sinnet.

Returns:

The pattern.

braidpy.ashley_solid_sinnet.strand_colors(n: int) → list[str]

A colour per strand, evenly round the hue circle.

braidpy.ashley_solid_sinnet.init_spaces_from_counts(counts: list[int]) → dict[int, list[int]]

Build the mapping sector -> strand IDs from counts.

Strand IDs are assigned contiguously starting at 1, scanning sectors in ascending order.

Parameters:

counts (List[int]) – Number of strands in each sector, length = n_sectors.

Returns:

Mapping from sector index (1-based) to list of strand IDs.

Return type:

Dict[int, List[int]]

braidpy.ashley_solid_sinnet.flatten_spaces(spaces: dict[int, list[int]]) → list[int]

Flatten the strands from all spaces into a single list in order of space index.

Parameters:

spaces (Dict[int, List[int]]) – Space-to-strand mapping.

Returns:

Flattened list of strand IDs.

Return type:

List[int]

braidpy.ashley_solid_sinnet.ashley_single_move_to_artin(counts: list[int], from_space: int, to_space: int) → tuple[list[int], list[int]]

Apply one Ashley move and return updated counts and the Artin braid word segment.

The direction is determined by the parity of from_space: odd moves right (anticlockwise, increasing sector index), even moves left (clockwise). Wrap-around crosses all other strands in the appropriate Artin order.

Note

This function updates only the per-sector counts. It reconstructs strand IDs from counts at each step, so IDs are not persistent across moves. The output braid word is computed according to the provided logic but the visualizer uses counts only.

Parameters:
  • counts (List[int]) – Current number of strands per sector.

  • from_space (int) – 1-based starting sector index.

  • to_space (int) – 1-based destination sector index.

Returns:

Updated counts after the move, and the list of signed Artin σ generators produced during this move.

Return type:

Tuple[List[int], List[int]]

braidpy.ashley_solid_sinnet.ashley_to_artin_exact(counts: list[int], moves: dict[int, int] | Sequence[tuple[int, int]]) → tuple[list[int], list[int]]

Convert an Ashley-style braid (sinnet) into an exact Artin braid word.

Ashley braids are described in the Ashley book of knots

The word is read anticlockwise, and counts a strand moved over, seen from above, as a positive crossing: the mirror image, read from the other side, of AshleySolidSinnet.braid(), which reads the braid as braidpy draws one. The two are the same braid.

This function simulates each strand’s movement: - Handles wrap-around moves by crossing all other strands in reverse order. - Records crossings in correct Artin σ notation. - Handles parity-based insertion into the destination space.

Parameters:
  • counts (List[int]) – List of strand counts for each space.

  • moves – (source, destination) spaces, in order. A mapping from source to destination is also read, but cannot hold two moves from one space.

Returns:

  • List of Artin σ generators as signed int.

  • Final mapping of spaces to strands.

Return type:

Tuple[List[int], List[int]]

braidpy.ashley_solid_sinnet.visualize_sinnet(initial_counts: list[int], moves: list[tuple[int, int]], out_dir: str = 'ashley_viz', prefix: str = 'step', make_gif: bool = True, gif_name: str = 'animation.gif', show_ids: bool = True, r_strand_circle: float = 0.75, arc_pad_frac: float = 0.12) → dict[str, list[str] | str]

Render an Ashley sinnet into step images and an optional GIF.

See AshleySolidSinnet.animate() for an animation that follows every strand, and the braid growing beside it.

This function draws an initial frame, then a frame per move showing the path between sectors, then a final frame after all moves. Each strand ID gets a consistent color derived from matplotlib.cm.tab20.

Note

Colors are assigned by global strand ID computed from initial_counts. Since IDs are reconstructed from counts at each step, IDs are not persistent across moves. If persistent identity is required, use a stateful mapping and explicit crossing simulation.

Parameters:
  • initial_counts (List[int]) – Initial counts per sector.

  • moves (List[Tuple[int, int]]) – List of (from_sector, to_sector) moves, 1-based.

  • out_dir (str) – Output directory for saved frames and GIF.

  • prefix (str) – Filename prefix for step images.

  • make_gif (bool) – If True and imageio is available, save an animated GIF.

  • gif_name (str) – Filename for the GIF inside out_dir.

  • show_ids (bool) – If True, draw numeric IDs over dots.

  • r_strand_circle (float) – Radius of the strand circle inside the annulus.

  • arc_pad_frac (float) – Trim near sector borders to avoid overlaps.

Returns:

Dictionary containing:
  • ”frames”: List[str]. Paths to saved PNG frames.

  • ”final”: str. Path to the final frame.

  • ”gif”: str. Path to the saved GIF, or a message if skipped.

Return type:

Dict[str, List[str] | str]

Ashley’s solid sinnets, from The Ashley Book of Knots: each its own AshleySolidSinnet, named by its number in the book, and all of them in CATALOG, as every catalogue lists its braids (braidpy.catalog).

braidpy.solid_sinnets_catalog.abok_2965 = AshleySolidSinnet(initial_counts_per_space=[2, 1], moves=[(1, 2), (2, 1)], shape='flat', all_right=False)

ABOK #2999 4-strand square

braidpy.solid_sinnets_catalog.abok_2999 = AshleySolidSinnet(initial_counts_per_space=[1, 1, 1, 1], moves=[(1, 3), (3, 1), (2, 4), (4, 2)], shape='square', all_right=False)

ABOK #3021 6-strand round

braidpy.solid_sinnets_catalog.abok_3021 = AshleySolidSinnet(initial_counts_per_space=[1, 1, 1, 1, 1, 1], moves=[(1, 3), (3, 5), (5, 1), (2, 6), (6, 4), (4, 2)], shape='round', all_right=False)

ABOK #3042 8-strand round

braidpy.solid_sinnets_catalog.abok_3042 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 1, 2, 1, 1], moves=[(1, 5), (4, 2), (5, 3), (2, 6), (3, 1), (6, 4)], shape='round', all_right=False)

ABOK #3043 11-strand triangle

braidpy.solid_sinnets_catalog.abok_3043 = AshleySolidSinnet(initial_counts_per_space=[3, 1, 2, 2, 2, 1], moves=[(1, 5), (4, 2), (5, 3), (2, 6), (3, 1), (6, 4)], shape='triangle', all_right=False)

ABOK #3044 8-strand triangle

braidpy.solid_sinnets_catalog.abok_3044 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 1, 1, 1, 2], moves=[(1, 5), (6, 4), (5, 3), (4, 2), (3, 1), (2, 6)], shape='triangle', all_right=False)

ABOK #3045 10-strand triangle

braidpy.solid_sinnets_catalog.abok_3045 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 2, 1, 2], moves=[(1, 5), (4, 2), (3, 1), (6, 4), (5, 3), (2, 6)], shape='triangle', all_right=False)

ABOK #3046 13-strand triangle “Any sinnet with Il1l uneven mnnber of edges (or sides), in order to be symmetrical, must have all the strands at the edges rotate in the same direction.”

braidpy.solid_sinnets_catalog.abok_3046 = AshleySolidSinnet(initial_counts_per_space=[3, 2, 3, 2, 2, 1], moves=[(1, 5), (2, 6), (3, 1), (4, 2), (5, 3), (6, 4)], shape='triangle', all_right=False)

ABOK #3047 19-strand triangle

braidpy.solid_sinnets_catalog.abok_3047 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2], moves=[(1, 9), (8, 2), (3, 7), (6, 4), (5, 1), (12, 6), (7, 11), (10, 8), (9, 5), (4, 10), (11, 3), (2, 12)], shape='triangle', all_right=False)

ABOK #3048 17-strand triangle

braidpy.solid_sinnets_catalog.abok_3048 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 1, 1, 2, 1, 2, 1, 1, 2, 1], moves=[(1, 9), (8, 2), (3, 7), (6, 4), (9, 5), (4, 10), (11, 3), (2, 12), (5, 1), (12, 6), (7, 11), (10, 8)], shape='triangle', all_right=False)

ABOK #3049 22-strand triangle

braidpy.solid_sinnets_catalog.abok_3049 = AshleySolidSinnet(initial_counts_per_space=[3, 1, 2, 1, 3, 2, 1, 2, 2, 2, 1, 2], moves=[(1, 9), (8, 2), (3, 7), (6, 4), (5, 1), (12, 6), (7, 11), (10, 8), (9, 5), (4, 10), (11, 3), (2, 12)], shape='triangle', all_right=False)

ABOK #3050 29-strand triangle

braidpy.solid_sinnets_catalog.abok_3050 = AshleySolidSinnet(initial_counts_per_space=[3, 2, 3, 2, 2, 3, 2, 3, 2, 2, 3, 2], moves=[(1, 9), (8, 2), (3, 7), (6, 4), (9, 5), (4, 10), (11, 3), (2, 12), (5, 1), (12, 6), (7, 11), (10, 8)], shape='triangle', all_right=False)

ABOK #3051 28-strand triangle

braidpy.solid_sinnets_catalog.abok_3051 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2], moves=[(1, 13), (12, 2), (3, 11), (10, 4), (5, 9), (8, 6), (7, 1), (18, 8), (9, 17), (16, 10), (11, 15), (14, 12), (13, 7), (6, 14), (15, 5), (4, 16), (17, 3), (2, 18)], shape='triangle', all_right=False)

ABOK #3052 20-strand hexagon

braidpy.solid_sinnets_catalog.abok_3052 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 1, 2, 2, 2, 1, 2, 1, 2, 2], moves=[(12, 8), (7, 1), (1, 7), (6, 2), (2, 10), (9, 3), (3, 9), (8, 4), (4, 12), (11, 5), (5, 11), (10, 6)], shape='hexagon', all_right=False)

In these diagrams, for the first time a strand from an odd-numbered space is led to an even-numbered space, and a strand from an even-numbered space is led to an odd-numbered space.

braidpy.solid_sinnets_catalog.abok_3053 = AshleySolidSinnet(initial_counts_per_space=[3, 1, 2, 1, 2, 2, 3, 1, 3, 1], moves=[(6, 4), (3, 7), (7, 2), (1, 8), (8, 5), (4, 9), (9, 3), (2, 10), (10, 6), (5, 1)], shape='half hexagon', all_right=False)

ABOK #3054 17-strand half round The same moves as #3053.

braidpy.solid_sinnets_catalog.abok_3054 = AshleySolidSinnet(initial_counts_per_space=[3, 1, 2, 1, 2, 2, 2, 1, 2, 1], moves=[(6, 4), (3, 7), (7, 2), (1, 8), (8, 5), (4, 9), (9, 3), (2, 10), (10, 6), (5, 1)], shape='half round', all_right=False)

ABOK #3055 26-strand fanbelt

braidpy.solid_sinnets_catalog.abok_3055 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 1, 2, 1], moves=[(12, 7), (6, 13), (13, 5), (4, 14), (15, 3), (2, 16), (1, 12), (11, 2), (3, 11), (10, 4), (5, 9), (8, 6), (7, 1), (16, 8), (9, 15), (14, 10)], shape='fanbelt', all_right=False)

ABOK #3056 26-strand diamond ABOK #3056

braidpy.solid_sinnets_catalog.abok_3056 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 1, 2, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2], moves=[(1, 12), (11, 2), (3, 10), (9, 4), (6, 1), (16, 7), (8, 15), (14, 9), (2, 16), (15, 3), (4, 14), (13, 5), (5, 13), (12, 6), (7, 11), (10, 8)], shape='diamond', all_right=False)

ABOK #3057 9-strand triangle #3058’s table, odd strands to the right and even ones to the left.

braidpy.solid_sinnets_catalog.abok_3057 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 2, 1, 1, 1], moves=[(1, 5), (2, 4), (3, 1), (4, 6), (5, 3), (6, 2)], shape='triangle', all_right=False)

ABOK #3058 9-strand triangle All strands move to the right.

braidpy.solid_sinnets_catalog.abok_3058 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 2, 1, 1, 1], moves=[(1, 5), (2, 4), (3, 1), (4, 6), (5, 3), (6, 2)], shape='triangle', all_right=True)

ABOK #3059 13-strand triangle All strands move to the right.

braidpy.solid_sinnets_catalog.abok_3059 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 2, 2, 1, 1, 1, 1, 1], moves=[(1, 7), (2, 6), (3, 5), (4, 1), (5, 9), (6, 8), (7, 4), (8, 3), (9, 2)], shape='triangle', all_right=True)

ABOK #3060 9-strand triangle Strands move right and left.

braidpy.solid_sinnets_catalog.abok_3060 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 1, 1, 2, 2], moves=[(1, 3), (6, 4), (5, 1), (4, 2), (3, 5), (2, 6)], shape='triangle', all_right=False)

ABOK #3061 12-strand square With a core.

braidpy.solid_sinnets_catalog.abok_3061 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 1, 1, 2, 1, 2, 1], moves=[(2, 8), (1, 3), (8, 6), (7, 1), (6, 4), (5, 7), (4, 2), (3, 5)], shape='square', all_right=False)

ABOK #3062 26-strand round

braidpy.solid_sinnets_catalog.abok_3062 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 3], moves=[(12, 8), (7, 1), (1, 7), (6, 2), (2, 10), (9, 3), (3, 9), (8, 4), (4, 12), (11, 5), (5, 11), (10, 6)], shape='round', all_right=False)

ABOK #3063 45-strand round

braidpy.solid_sinnets_catalog.abok_3063 = AshleySolidSinnet(initial_counts_per_space=[3, 2, 3, 3, 2, 3, 2, 3, 2, 2, 3, 2, 2, 3, 2, 3, 2, 3], moves=[(16, 12), (11, 17), (18, 10), (1, 9), (8, 2), (3, 7), (4, 18), (17, 5), (6, 16), (7, 15), (14, 8), (9, 13), (10, 6), (5, 11), (12, 4), (13, 3), (2, 14), (15, 1)], shape='round', all_right=False)

ABOK #3064 19-strand round

braidpy.solid_sinnets_catalog.abok_3064 = AshleySolidSinnet(initial_counts_per_space=[1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1], moves=[(7, 11), (6, 12), (5, 1), (4, 2), (11, 3), (10, 4), (9, 5), (8, 6), (3, 7), (2, 8), (1, 9), (12, 10)], shape='round', all_right=False)

ABOK #3065 9-strand round

braidpy.solid_sinnets_catalog.abok_3065 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 1, 2, 1], moves=[(5, 2), (1, 4), (3, 6), (2, 5), (4, 1), (6, 3)], shape='round', all_right=False)

ABOK #3066 10-strand round All strands move to the right.

braidpy.solid_sinnets_catalog.abok_3066 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 1, 1, 2, 1, 1, 1], moves=[(1, 2), (5, 6), (2, 3), (6, 7), (3, 4), (7, 8), (4, 5), (8, 1)], shape='round', all_right=True)

ABOK #3068 12-strand round All strands move to the right.

braidpy.solid_sinnets_catalog.abok_3068 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 2, 2, 2, 2], moves=[(1, 4), (4, 1), (2, 5), (5, 2), (3, 6), (6, 3)], shape='round', all_right=True)

ABOK #3069 6-strand round All strands move to the right.

braidpy.solid_sinnets_catalog.abok_3069 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 1, 1], moves=[(1, 3), (2, 4), (3, 1), (4, 2)], shape='round', all_right=True)

ABOK #3070 8-strand square Odd strands move right; even strands move left.

braidpy.solid_sinnets_catalog.abok_3070 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 2, 2], moves=[(1, 3), (3, 1), (2, 4), (4, 2)], shape='square', all_right=False)

ABOK #3071 14-strand chisel-edge Odd strands move right; even strands move left.

braidpy.solid_sinnets_catalog.abok_3071 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 1, 3, 2, 1, 2], moves=[(5, 1), (8, 2), (3, 7), (6, 4), (1, 5), (4, 6), (7, 3), (2, 8)], shape='chisel-edge', all_right=False)

ABOK #3072 20-strand chisel-edge Odd strands move right; even strands move left.

braidpy.solid_sinnets_catalog.abok_3072 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 1, 2, 1, 3, 2, 1, 2, 1, 2], moves=[(7, 1), (12, 2), (3, 11), (10, 4), (5, 9), (8, 6), (1, 7), (6, 8), (9, 5), (4, 10), (11, 3), (2, 12)], shape='chisel-edge', all_right=False)

ABOK #3073 20-strand square

braidpy.solid_sinnets_catalog.abok_3073 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1], moves=[(2, 12), (11, 3), (4, 10), (10, 4), (5, 9), (8, 6), (3, 5), (6, 2), (1, 7), (7, 1), (12, 8), (9, 11)], shape='square', all_right=False)

ABOK #3074 26-strand square

braidpy.solid_sinnets_catalog.abok_3074 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 2, 1, 2, 1], moves=[(2, 16), (15, 3), (4, 14), (13, 5), (5, 13), (12, 6), (7, 11), (10, 8), (6, 4), (3, 7), (8, 2), (1, 9), (9, 1), (16, 10), (11, 15), (14, 12)], shape='square', all_right=False)

ABOK #3075 20-strand oblong

braidpy.solid_sinnets_catalog.abok_3075 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 1, 2, 1, 2, 2, 2, 1, 2, 1, 2], moves=[(2, 12), (12, 3), (4, 11), (10, 5), (6, 9), (8, 6), (5, 7), (7, 4), (3, 8), (9, 2), (1, 10), (11, 1)], shape='oblong', all_right=False)

ABOK #3076 20-strand oblong

braidpy.solid_sinnets_catalog.abok_3076 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2], moves=[(4, 2), (1, 5), (6, 1), (12, 7), (7, 11), (10, 8), (2, 12), (11, 3), (3, 10), (9, 4), (5, 9), (8, 6)], shape='oblong', all_right=False)

ABOK #3077 32-strand oblong

braidpy.solid_sinnets_catalog.abok_3077 = AshleySolidSinnet(initial_counts_per_space=[2, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1], moves=[(2, 20), (19, 3), (4, 19), (18, 5), (6, 17), (16, 7), (8, 15), (14, 9), (9, 13), (12, 10), (10, 8), (7, 11), (11, 6), (5, 12), (13, 4), (3, 14), (15, 2), (1, 16), (17, 1), (20, 18)], shape='oblong', all_right=False)

ABOK #3078 20-strand ellipse

braidpy.solid_sinnets_catalog.abok_3078 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1], moves=[(1, 3), (4, 14), (13, 5), (12, 6), (7, 11), (10, 8), (8, 13), (14, 7), (6, 1), (5, 9), (9, 4), (3, 10), (11, 2), (2, 12)], shape='ellipse', all_right=False)

ABOK #3079 36-strand pentagon

braidpy.solid_sinnets_catalog.abok_3079 = AshleySolidSinnet(initial_counts_per_space=[3, 1, 2, 1, 3, 1, 2, 1, 3, 2, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2], moves=[(1, 13), (12, 2), (3, 11), (10, 4), (5, 17), (16, 6), (7, 15), (14, 8), (9, 1), (20, 10), (11, 19), (18, 12), (13, 5), (4, 14), (15, 3), (2, 16), (17, 9), (8, 18), (19, 7), (6, 20)], shape='pentagon', all_right=False)

ABOK #3080 16-strand pentagon

braidpy.solid_sinnets_catalog.abok_3080 = AshleySolidSinnet(initial_counts_per_space=[2, 1, 2, 1, 2, 2, 1, 2, 1, 2], moves=[(1, 7), (6, 2), (3, 9), (8, 4), (5, 1), (10, 6), (7, 3), (2, 8), (9, 5), (4, 10)], shape='pentagon', all_right=False)

ABOK #3081 31-strand pentalpha

braidpy.solid_sinnets_catalog.abok_3081 = AshleySolidSinnet(initial_counts_per_space=[3, 1, 1, 1, 3, 1, 1, 1, 3, 1, 1, 2, 2, 1, 2, 1, 2, 2, 1, 1], moves=[(18, 16), (15, 19), (1, 13), (12, 2), (2, 20), (19, 3), (5, 17), (16, 6), (6, 4), (3, 7), (9, 1), (20, 10), (10, 8), (7, 11), (13, 5), (4, 14), (14, 12), (11, 15), (17, 9), (8, 18)], shape='pentalpha', all_right=False)

ABOK #3082 61-strand pentalpha

braidpy.solid_sinnets_catalog.abok_3082 = AshleySolidSinnet(initial_counts_per_space=[3, 1, 2, 1, 1, 1, 2, 1, 3, 1, 2, 1, 1, 1, 2, 1, 3, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1], moves=[(34, 32), (31, 35), (36, 30), (29, 37), (1, 25), (24, 2), (3, 23), (22, 4), (2, 40), (39, 3), (4, 38), (37, 5), (9, 33), (32, 10), (11, 31), (30, 12), (10, 8), (7, 11), (12, 6), (5, 13), (17, 1), (40, 18), (19, 39), (38, 20), (18, 16), (15, 19), (20, 14), (13, 21), (25, 9), (8, 26), (27, 7), (6, 28), (26, 24), (23, 27), (28, 22), (21, 29), (33, 17), (16, 34), (35, 15), (14, 36)], shape='pentalpha', all_right=False)

82-strand pentagonal sinnet 3082-2 By Norbert Trupiano http://charles.hamel.free.fr/knots-and-cordages/PUBLICATIONS/Solid%20Sinnet%20variations.pdf

A disk braid made as on a marudai: move by move, each moved yarn laid over the others and drawn tight, the braid turning to balance.

web/marudai.js, which Braid Studio runs in the browser, in Python: the same algorithm, step for step, in the same order (tests/test_marudai_python.py runs both and compares them). The method is braid3dmin’s, a kumihimo simulation in three.js; docs/source/marudai.md describes it as done here. The code is this project’s own. In short:

  • Each yarn is a chain of beads a unit apart, two units thick. A link pulls its beads together only when stretched, as a rope does; two beads less than two units apart push each other away.

  • Each yarn’s end is drawn towards its carrier, out on the rim and above the braid’s tip, by a constant pull: its bobbin.

  • A move lays the yarn’s end over the top of everything on its way to its new carrier, then draws the new stretch tight as a string would go: each bead to between its neighbours, or round a yarn in the way.

  • The braid then relaxes from what moved: a bead at a time, each moved by its forces, its neighbours and the beads near it then queued, with steps shrinking until the queue dies down.

  • Hanging free, the braid turns until its yarns’ ends pull it no way round.

  • Well behind a yarn’s end, the braid is made: frozen.

  • A core, if there is one, rises up the braid’s axis, past the carriers: a yarn pulled straight up, or rigid, held where it stands. A yarn’s move passes beside it, on the side it goes round — a move of more than nine tenths of a half turn is made in two — and is drawn tight round it. The braid turns about it.

Inside, lengths are in units of half a yarn diameter, y up, as the method was given; what make() returns is in yarn diameters, z up.

It follows the JavaScript step for step: JavaScript’s rounding to whole numbers (_round()), its floating-point random numbers (Machine._shuffle), and the order beads are found and woken in (the grid of cells as linked lists, and bead numbers reused as the JavaScript reuses them). Given the same numbers from the maths library, it makes the same braid bead for bead. The libraries themselves differ in the last place — Python’s math.hypot is correctly rounded, JavaScript’s Math.hypot not always — and thousands of relaxation steps make that visible, as they would any change: the two braids are alike, not identical. It is pure Python and slow — tens of times slower than in a browser — which suits checking it, not making long braids.

class braidpy.marudai.Machine(n_threads: int, turning: bool = True, core: str | None = None)

Bases: object

The marudai and its yarns: web/marudai.js’s Machine.

Parameters:
  • n_threads – How many yarns.

  • turning – Whether the braid hangs free and turns to balance.

  • core – A core up the axis, "yarn" or "rigid", after the yarns; None for none.

hold(held: bool) → None

While the bobbins turn round the braid together: held, the yarns carried round with them rather than over each other, and not balanced; then as before again (hold in web/marudai.js).

lay(t: int, to: float, gentle: bool = False, over: bool = True) → None

Thread t’s end goes to the carrier at angle to: up over what lies on its way, then out to the rim, then drawn tight. Carried round with the others, not over them, it goes straight out to the rim, passing nobody.

relax() → None

Let the braid relax from what moved, then trim, find its tip, balance it, and forget the made braid far below.

turn(ax: float, az: float, f: float) → None

The whole braid turned by f about the vertical through (ax, az).

twist(f: float) → None

The bobbins carried round by f together, the braid held: each yarn’s free part turns with them about the axis, all of it at its carrier and none of it at the braid’s tip, twisting the yarns in.

start(angles: Sequence[float]) → None

The yarns tied together where the braid begins: round a ring, as the method has it, for as many as it was made for; more, and the ring would be so wide the yarns rose from it as a tube, never drawn in to a braid. So then rings of at most RING, one under the other, the yarns taken in turn round the disk.

positions(t: int) → list[list[float]]

Thread t’s beads as they stand, oldest first, each [x, y, z].

braidpy.marudai.begin(job: dict[str, Any]) → dict[str, Any]

A braid being made: the marudai set up, its moves made one by one with step(moves, number), the braid as it is so far with result(); and the machine itself, as machine.

braidpy.marudai.make(job: dict[str, Any]) → dict[str, Any]

A disk braid made move by move: web/marudai.js’s make.

Parameters:

job – A disk program, as braidpy.web gives it: n_slots, start (each yarn’s slot, from 1), steps (per step, [yarn, slots moved]), clockwise; and optionally split, held, twists, from, turning and core, as in the JavaScript.

Returns:

yarns (each yarn’s beads, flat [x, y, z, …] in yarn diameters, z up, oldest first, cut at the braid’s tip), whole, tails, rim, tip and updates, as the JavaScript’s.

horn_gear/__init__.py

Horn gear braiding machine simulator.

A braiding machine is described as a graph of connected horn gears. Each gear has N slots and the bobbins (carriers) travel between gears as the gears turn.

BraidingMachine covers machines whose gears are geared together, where the carriers follow closed tracks fixed by the wiring. JacquardLaceMachine covers machines whose gears are driven one by one from a punched programme, where they do not. Both are laid out, simulated and drawn by the same code.

yarn_paths() follows the carriers through a run and lays their yarns off along the machine’s axis, with no tension yet, and visualize_yarns() draws the result in 3D standing on the machine.

horn_gear/model.py

Data model for a horn gear braiding machine.

A machine is a graph of HornGear nodes connected by Connection edges.

A connection is a fixed point in space where two gears meet. As a gear turns, a different slot arrives there; Connection.slot_a0/slot_b0 record which slot of each gear sits there at t=0.

BraidingMachine describes a machine whose gears are geared together: every gear turns one slot every step, each slot belongs to one gear, and a carrier crosses to its neighbour when its slot reaches a contact. A machine built differently says so by overriding a handful of methods — turning_gears(), rotation(), next_position() and their neighbours — and the rest of the package needs no special case. See JacquardLaceMachine.

class braidpy.horn_gear.model.HornGear(name: str, n_slots: int, direction: int = 1, size: int | None = None)

Bases: object

A single horn gear with N evenly-spaced slots.

Parameters:
  • name – Unique identifier for this gear.

  • n_slots – Number of carrier slots (≥ 2).

  • direction – +1 for counter-clockwise, -1 for clockwise rotation.

  • size – How large the gear is drawn, as the slot count of a gear that size; its own slot count if None. One half of a split gear (multiband) has half the slots of the gear it is part of, and is as large.

name: str
n_slots: int
direction: int = 1
size: int | None = None
angle_at_rotation(slot: int, rotation: float) → float

Angle (radians) of a slot after the gear has turned rotation slots.

The gear knows only how far it has turned, never how that relates to simulation time — a gear that is driven individually turns at its own pace. Ask the machine for the rotation; see BraidingMachine.rotation().

Parameters:
  • slot – Slot index (0-based).

  • rotation – Signed slots turned through, fractional allowed.

Returns:

Angle in radians, measured CCW from the positive x-axis.

class braidpy.horn_gear.model.Connection(gear_a: str, gear_b: str, slot_a0: int, slot_b0: int, name: str | None = None, phase: float = 0.0)

Bases: object

A transfer point between two gears.

At each simulation step the slot of gear_a that is currently at the connection angle and the slot of gear_b that is currently at the connection angle are computed. A carrier sitting in the gear_a slot transfers to gear_b (and vice-versa).

A contact hands over at the end of each step, when every gear’s slots are back on slot angles. One between two split gears, whose horns meet there once a horn’s pitch, as often as their parts in a step, hands over at phase, a fraction of the way through each step: the parts’ first pairing at 0, their second a step’s 1/k on, and so on, all at the one contact (described). A step then holds k ticks, each a pitch of the split gears, and a hand-over at each.

Parameters:
  • gear_a – Name of the first gear.

  • gear_b – Name of the second gear.

  • slot_a0 – Slot index of gear_a at the connection point at t=phase.

  • slot_b0 – Slot index of gear_b at the connection point at t=phase.

  • name – Optional label for this connection.

  • phase – How far through each step it hands over, from 0 (at the step’s end, as every contact of whole gears) to below 1.

gear_a: str
gear_b: str
slot_a0: int
slot_b0: int
name: str | None = None
phase: float = 0.0
slots_at(machine: BraidingMachine, time: int) → tuple[int, int]

Return the (slot_of_a, slot_of_b) currently at this connection.

Parameters:
  • machine – The machine containing gear definitions.

  • time – Current step.

Returns:

Tuple (slot_in_a, slot_in_b) currently at the connection point.

class braidpy.horn_gear.model.Axial(name: str, anchor: tuple[str, ...])

Bases: object

A yarn fed straight down a fixed column, never carried by a gear.

Braiding carriers travel around an axial; the axial itself does not move, holds no slot, and has no track. It is therefore not a carrier and takes no part in stepping, tracks or collision detection — it is a fixed point that the braid forms around.

The column stands at the centroid of the gears it is anchored to, which covers both ways a machine carries one:

  • anchor=("B",) — one gear, so the column is that gear’s own centre, as an axial yarn fed up through a hollow horn gear spindle. This is the 0° reinforcement of a triaxial braid, and the cord of a soutache.

  • anchor=("A", "B", "C", "D") — the ring of gears around a hole, so the column is the centre of the tube they braid, as a rope core or a mandrel. tube_rings() finds these rings for you.

Parameters:
  • name – Unique identifier for this axial.

  • anchor – Names of the gears whose centroid the column stands at.

name: str
anchor: tuple[str, ...]
class braidpy.horn_gear.model.BraidingMachine(gears: list[HornGear], connections: list[Connection], axials: Iterable[Axial] = ())

Bases: object

A complete horn-gear braiding machine described as a connection graph.

Parameters:
  • gears – List of HornGear instances.

  • connections – List of Connection edges between gears.

  • axials – Optional Axial columns the braid forms around.

Variables:
  • gears – Dict mapping gear name → HornGear.

  • connections – List of Connection instances.

  • axials – List of Axial instances (empty for a machine without cores).

  • graph – NetworkX graph of gear connections (for layout / analysis).

gears_interpenetrate: bool = False

Whether neighbouring gear circles overlap, cutting a notch that both gears share, rather than merely touching at a point.

has_fixed_tracks: bool = True

Whether carriers follow closed tracks fixed by the machine’s wiring. False on a machine driven by a programme, where the path a carrier takes is whatever the programme dictates and need never come back.

gears: dict[str, HornGear]
connections: list[Connection]
axials: list[Axial]
graph: Graph
with_axials(axials: Iterable[Axial]) → BraidingMachine

The same machine braiding round these axials instead of its own.

with_loading(loading: Iterable[tuple[str, int]]) → BraidingMachine

The same machine, starting with these carriers when the caller does not say otherwise (default_carriers()).

Parameters:

loading – Each carrier’s (gear, slot), carrier after carrier.

Raises:

ValueError – If a slot is not the machine’s, or holds two carriers.

turning_gears(step: int) → frozenset[str]

Gears that turn during the transition from step to step + 1.

Parameters:

step – The step being taken.

Returns:

Names of the gears that move. Every gear, on an ordinary machine.

rotation(gear_name: str, time: int) → int

Signed number of slots a gear has turned through after time steps.

Parameters:
  • gear_name – Name of the gear.

  • time – Current step.

Returns:

Slots turned; negative for a clockwise gear.

contact_period() → int

Steps after which every contact shows the same slots again.

Each gear returns its slots to the contacts every n_slots steps, so the machine’s contact pattern repeats with period lcm(n_slots).

program_rows() → list[tuple[str, tuple[bool, ...]]] | None

The machine’s programme as punchcard rows, or None if it has none.

One row per phase, in the order they are driven, each a label and a flag per gear. A machine whose gears are geared together has no programme to show.

Returns:

List of (label, flags) or None.

preferred_layout(scale: float = 1.0) → dict[str, tuple[float, float]] | None

A layout the machine knows to be right for itself, or None.

Returning None lets compute_layout() work the positions out from the connection graph, which is what an ordinary machine of tangent gears wants. A machine whose geometry is pinned by its own construction overrides this.

Parameters:

scale – Overall scale factor for gear radii.

Returns:

Gear name → (x, y), or None to let the layout be computed.

preferred_gear_radii(scale: float = 1.0) → dict[str, float] | None

The radii to draw gears at, where the machine knows better.

gear_radii() draws a gear as large as the square root of its horn count, which is a convention and no more: horn gears do not roll on one another – each is driven from below – so a radius is free where a slot count is not. A machine that has solved its own geometry says so here, for the gears it has solved; the rest keep the convention.

Returns:

Gear name -> radius, at this scale, or None to leave every gear to the convention.

riding_position(pos: tuple[str, int], time: int, frac: float = 0.0) → tuple[str, int]

Which (gear, slot) sweeps a carrier through the step at time.

This is what an animation must draw it on, and it is not always where the carrier is recorded. On an ordinary machine the carrier’s own gear carries it round to the contact and hands over only at the very end of the step, so it rides its own gear throughout — which is what this returns.

A machine whose gears share their slots overrides this, because there the receiving gear does the sweeping: see riding_position().

A contact handing over during the step (Connection’s phase) has the carrier drawn on the neighbour from then on.

Parameters:
  • pos – The carrier’s (gear_name, slot_index) at time.

  • time – Step being taken.

  • frac – How far into the step.

Returns:

The (gear_name, slot_index) to draw the carrier on then.

default_carriers() → dict[int, tuple[str, int]]

How to thread this machine when the caller does not say: as it was given (with_loading()), if it was.

Otherwise a wired machine is loaded along its tracks, as far as it will go. A machine without tracks overrides this — see notch_positions().

Returns:

Dict mapping carrier_id → (gear_name, slot).

carrier_colours

An attribute under its old name, read and written as the new one.

Held by the class under the old name: color = renamed_attribute("colour").

Parameters:

new – The attribute’s new name.

carrier_colors(carriers: dict[int, tuple[str, int]] | None = None) → dict[int, str] | None

The colours a loading’s carriers are drawn in, if the machine has a way of its own to choose them.

Parameters:

carriers – Carrier number -> (gear, slot) it starts at; the machine’s own loading if None.

Returns:

Carrier number -> colour as #rrggbb; None to leave it to whoever draws them, which gives each carrier a colour of the palette (braidpy.utils.PALETTE) in turn.

next_position(pos: tuple[str, int], time: int) → tuple[str, int]

Where a carrier goes during the step from time to time + 1.

On an ordinary machine the gears are tangent and every slot belongs to one gear alone, so a carrier rides its own slot round until that slot arrives at a contact, and then crosses into the neighbour’s slot waiting there.

A machine built differently overrides this — see next_position(), whose gears interpenetrate and share their slots.

Parameters:
  • pos – Current (gear_name, slot_index).

  • time – Step being taken.

Returns:

The (gear_name, slot_index) the carrier occupies afterwards.

slot_at_connection(gear_name: str, slot0_at_t0: int, time: int) → int

Which slot sits at the contact whose slot at t=0 was slot0_at_t0.

Contacts are fixed in space, so as the gear turns a different slot arrives at each one.

Parameters:
  • gear_name – Name of the gear.

  • slot0_at_t0 – Slot that was at the contact at t=0.

  • time – Current step.

Returns:

Slot index currently at that contact.

slot_angle(gear_name: str, slot: int, time: int = 0, frac: float = 0.0) → float

Angle (radians) of a slot at continuous time time + frac.

Parameters:
  • gear_name – Name of the gear.

  • slot – Slot index.

  • time – Current step.

  • frac – Fraction of the way into the step, for smooth animation.

Returns:

Angle in radians, measured CCW from the positive x-axis.

total_slots() → int

Total number of carrier slots across all gears.

connections_of(gear_name: str) → list[Connection]

Return all connections involving a given gear.

Parameters:

gear_name – Name of the gear.

Returns:

List of Connection objects.

neighbor_at_slot(gear_name: str, slot: int, time: int) → tuple[str, int] | None

If slot slot of gear gear_name is at a connection at step time, return (neighbor_gear_name, neighbor_slot). Otherwise None.

Parameters:
  • gear_name – Name of the gear.

  • slot – Current slot index.

  • time – Current step.

Returns:

(neighbor_name, neighbor_slot) or None.

A horn gear machine written as its graph: which gears mesh with which.

A machine is gears that mesh, so it can be written as the pairs that do: A-B B-C C-D D-A is four gears in a ring, A-B two side by side. A gear’s name is any run of letters, digits and underscores (B, g2, left): no name has to come first. A gear may be given its own number of slots, A:6, anywhere it is named; the others have as many as machine_from_graph()’s n_slots, 4 unless given (Braid Studio’s Slots per gear).

A split gear — gears on one axle, turning as one, their horns taking turns round it, each meeting only its own neighbours, so that the bands they serve never exchange a carrier (multiband) — is written as its parts, each a gear in the pairs, joined on their axle: A-B1 B2-C B1+B2 is the twin plait, its middle gear of six horns split in two. A gear may be split in more parts, H1+H2+H3, its parts as many slots each; and split gears may be anywhere in the graph.

Two split gears may mesh more than once, a band to each pairing of their parts: A1-B1 A2-B2 A1+A2 B1+B2 is two bands side by side, each on its own pair of halves, and neither can reach the other. What may not happen is one part meeting one axle twice – a carrier of that band could then leave by either contact, which is the split undone – so a whole gear meshing with both parts of a split one (A-B1 A-B2 B1+B2) is refused. The two axles touch, at one contact. A horn of each comes round to it once a horn’s pitch, as often in a step as each has parts, the parts in turn: the pairing named first hands over there at the end of each step, the next a 1/k step on, and so on (a step of k ticks, a hand-over at each; Connection’s phase). The bands so share the one contact without their carriers meeting. Turning opposite ways, the two axles bring their parts round in opposite orders, which for parts in three or more the pairings named have to follow.

The rest follows from the graph:

  • Two gears that mesh turn opposite ways, so each gear’s direction is the graph’s two colours, the first gear named turning anticlockwise, a split gear’s parts all one way. A ring of an odd number of gears cannot turn at all, and is refused. Which gear is named first is all the order of the pairs says: A-B B-C and B-C A-B turn their gears opposite ways.

  • A ring is laid out clockwise, seen from above, from the gear whose name sorts first towards its neighbour whose name sorts first (compute_layout()): A-B B-C C-D D-A and A-D D-C C-B B-A are one machine, A, B, C and D clockwise round it, whichever way the pairs are written. Names that sort otherwise lay it the other way round.

  • Where the gears stand is where the layout puts them (compute_layout(), from the graph and the gears’ sizes alone, a split gear’s parts at one centre, as large as the whole); in a tree of gears, each neighbour of a split gear’s part where a horn of that part comes round.

  • Each gear’s contacts are where the layout puts them, if whole slots can say so, and otherwise as evenly spread as its slots allow, in the order the layout puts them, its first contact named at slot 0.

Where it feeds axial yarns is written as the places, B up a gear’s spindle or A-B-C-D down the hole of a ring of gears (read_axials()); the carriers it starts with, if it is not to load itself, as A:0 B:2 (read_loading()). The catalogue’s machines are written so (braidpy.horn_gear.examples).

graph_of() writes a machine back as its graph, axials_of() and loading_of() its axials and a loading. A machine written so and read again is the same machine, its slots perhaps numbered from another one round.

braidpy.horn_gear.described.axial_text(axial: Axial) → str

Where an axial is fed, as written: its gear, B, or the ring of gears round its hole, A-B-C-D.

braidpy.horn_gear.described.axials_of(machine: BraidingMachine) → str

Where a machine feeds its axials, as read_axials() reads it.

braidpy.horn_gear.described.graph_of(machine: BraidingMachine) → tuple[str, int]

A machine written as its graph, for machine_from_graph().

Gears on one axle — the parts of a split gear, drawn as large as the whole (HornGear.size) and at one centre — are written as one, B1+B2.

Parameters:

machine – The machine.

Returns:

The pairs of gears that mesh, and the number of slots most of its gears have: a gear with another number is written with its own.

braidpy.horn_gear.described.loading_of(loading: dict[int, tuple[str, int]]) → str

A loading as read_loading() reads it, carrier after carrier.

braidpy.horn_gear.described.machine_from_graph(text: str, n_slots: int = 4, axials: str = '', loading: str = '') → BraidingMachine

The machine whose gears mesh as written.

Parameters:
  • text – The pairs of gears that mesh, as A-B B-C, separated by spaces, commas or semicolons; a gear’s own number of slots as A:6; a gear split into parts on one axle as B1+B2 (or more parts), each part a gear of its own in the pairs.

  • n_slots – How many slots a gear, or a part, has when the text does not say.

  • axials – Where it feeds axial yarns (read_axials()): none if empty.

  • loading – The carriers it starts with when not told otherwise (read_loading()); if empty, as it loads itself (default_carriers()).

Returns:

The machine, its gears’ directions and contacts worked out.

Raises:

ValueError – If the text cannot be read, names a pair twice, falls into separate machines, has a ring of an odd number of gears, or a split gear whose parts mesh with one another, with the same gear, or with none; or if an axial or a carrier cannot be where it is given.

braidpy.horn_gear.described.read_axials(machine: BraidingMachine, text: str) → list[Axial]

The axials fed where written, each one of the machine’s axial_spots().

Parameters:
  • machine – The machine.

  • text – The places, separated by spaces, commas or semicolons: a gear, B, up its spindle (a split gear by any of its parts); or the ring of gears round a hole, A-B-C-D, in any order, down it.

Returns:

The axials, in the order written.

Raises:

ValueError – For a place the machine has no room for an axial at, or one given twice.

braidpy.horn_gear.described.read_loading(text: str, machine: BraidingMachine, named: dict[str, tuple[str, int]] | None = None) → list[tuple[str, int]]

Carriers as written, A:0 B:2: each its gear and slot, once.

Parameters:
  • text – The carriers, separated by spaces, commas or semicolons.

  • machine – The machine they are on.

  • named – Other names a carrier’s place may go by, with its gear and slot: a lace machine’s notches.

Returns:

Each carrier’s (gear, slot), in the order written.

Raises:

ValueError – For a carrier that cannot be read or is not on the machine, two on one slot, or none at all.

horn_gear/layout.py

Where everything sits: gear centres, the notches between them, the circles a carrier rides on, and the columns a braid forms around.

Gears are placed from the connection graph — BFS along the x-axis for a chain, Kamada-Kawai relaxed till every two gears that mesh touch for anything with a cycle (ring_geometry()) — unless the machine pins its own geometry, in which case preferred_layout() wins. Gear radius goes as sqrt(n_slots), which is a drawing convention and not a mechanical one — see _gear_radius().

Everything else here is derived from those centres: where two gears meet (contact_point()), how far out a carrier rides (carrier_radius()), how each gear must be turned for its slots to face its notches (slot_offsets()), by how much that fails where a line of gears bends (offset_residuals()), and how the slots are drawn so that carriers are handed on without jumping all the same (slot_angles()). It is all plain geometry with no drawing in it, so it can be measured and tested directly.

braidpy.horn_gear.layout.compute_layout(machine: BraidingMachine, scale: float = 1.0, seed: int | None = 42, iterations: int = 500) → dict[str, tuple[float, float]]

Compute 2-D positions for all gears with adjacent circles exactly tangential.

For tree / path graphs (flat braid): BFS-based placement along the x-axis guarantees every pair of adjacent gear circles touches exactly.

For cyclic graphs (a tubular braider’s ring, a matrix of gears): ring_geometry(), which also sizes the gears so that they touch.

Parameters:
  • machine – The BraidingMachine whose gears to position.

  • scale – Overall scale factor for gear radii.

  • seed – Random seed for reproducibility (cyclic graphs only).

  • iterations – Spring-layout iterations (cyclic fallback only).

Returns:

Dict mapping gear name → (x, y) in layout coordinates.

braidpy.horn_gear.layout.ring_geometry(machine: BraidingMachine, scale: float = 1.0, seed: int | None = 42, iterations: int = 500) → tuple[dict[str, tuple[float, float]], dict[str, float]]

Where the gears of a machine with a ring of gears stand, and how large they are drawn, so that every two that mesh touch and no two others overlap.

Kamada-Kawai lays the graph out with each mesh as long as the two radii, which it can do exactly for one ring of gears alike, as a tubular braider is. Where it cannot, as in a matrix of gears of several sizes, its compromise is relaxed (_relax()): the gears that mesh are drawn to touch, moving their centres and, within RADIUS_RANGE, their sizes; those that do not are pushed apart, past touching. Not an exact solution, but no gear runs through another, nor does a carrier through another’s path. A layout that is right already is kept as it is.

Parameters:
  • machine – The machine; its graph has a cycle.

  • scale – Overall scale for the radii.

  • seed – Random seed for the spring layout, the fallback.

  • iterations – Iterations of the spring layout.

Returns:

Gear name → centre, and gear name → radius.

class braidpy.horn_gear.layout.RingContacts(first: ndarray, second: ndarray, turns: ndarray, part_first: ndarray, part_second: ndarray, weight: ndarray, timer_first: ndarray | None = None, timer_second: ndarray | None = None, n_timers: int | None = None, apart: tuple[tuple[int, int, float], ...] = ())

Bases: object

When a ring’s contacts come round, for time_ring(): one entry a contact, between gear first and gear second (indices).

A gear of n slots a part, turning d (+1 anticlockwise) and turned psi to start with, brings its part p of k to a contact at angle alpha at the times t with d n (alpha - psi) / 2 pi - d p / k = t (mod 1). Written with the gear’s start x = d n psi / 2 pi, that is turns * alpha - x - part = t.

Each start is a timer’s: by default each gear’s, its parts a fixed share of a step apart; or, with timer_first and timer_second, one of n_timers, so that the parts of a split gear, stacked on one axle, each start where they are set, as their horn plates are when the machine is assembled (part then 0).

Variables:
  • first (numpy.ndarray) – Each contact’s first gear.

  • second (numpy.ndarray) – Its second gear.

  • turns (numpy.ndarray) – d n / 2 pi of each gear, by index.

  • part_first (numpy.ndarray) – d p / k of the first gear’s part there.

  • part_second (numpy.ndarray) – The same of the second’s.

  • weight (numpy.ndarray) – A miss of one step at the contact, as a share of the gap between two horns of the first gear.

  • timer_first (numpy.ndarray | None) – The timer of the first gear’s part, by index; the gear’s own if None.

  • timer_second (numpy.ndarray | None) – The same of the second’s.

  • n_timers (int | None) – How many timers; as many as gears if None.

  • apart (tuple[tuple[int, int, float], ...]) – Timers set so far apart once fitted, as (timer, other, share of a step): the parts of a split gear, their horns taking turns round its axle. Where no contact ties the two, as two bands joined by split gears, the first’s whole band is turned so, which changes no contact of it.

first: ndarray
second: ndarray
turns: ndarray
part_first: ndarray
part_second: ndarray
weight: ndarray
timer_first: ndarray | None = None
timer_second: ndarray | None = None
n_timers: int | None = None
apart: tuple[tuple[int, int, float], ...] = ()
braidpy.horn_gear.layout.time_ring(centers: ndarray, radii: ndarray, convention: ndarray, meshes: list[tuple[int, int]], others: list[tuple[int, int]], contacts: RingContacts) → tuple[ndarray, ndarray, ndarray, list[float]]

Move and size the gears of a ring, from ring_geometry()’s layout, so that each contact’s two horns come round to it together, and say when.

A contact between two gears asks their starts to differ by so much, mod 1 (RingContacts): one equation a contact, and one start a gear, so round each ring of gears one equation is left over, which the layout has to meet. Round a single ring of gears alike it cancels. Every two gears that mesh touch, no two others come within CLEARANCE, each radius stays within RADIUS_RANGE of its convention, and the horns arrive together: a least-squares fit of all of it, by Levenberg-Marquardt with exact derivatives.

Parameters:
  • centers – Each gear’s centre, (n, 2).

  • radii – Each gear’s radius as drawn.

  • convention – Each gear’s radius by the drawing convention (_gear_radius()), which its radius may leave by RADIUS_RANGE at most.

  • meshes – The gears that mesh, as index pairs.

  • others – Those that do not.

  • contacts – When the contacts come round.

Returns:

The centres, the radii, each gear’s start (x of RingContacts), and when each contact hands over, as a share of a step.

braidpy.horn_gear.layout.axial_position(machine: BraidingMachine, layout: dict[str, tuple[float, float]], axial: Axial) → tuple[float, float]

Where an axial’s column stands: the centroid of the gears it anchors to.

One gear gives that gear’s own centre; a ring of gears gives the centre of the hole they enclose.

Parameters:
  • machine – The machine the axial belongs to.

  • layout – Gear centre positions from compute_layout.

  • axial – The axial to place.

Returns:

(x, y) of the column in layout coordinates.

braidpy.horn_gear.layout.axial_positions(machine: BraidingMachine, layout: dict[str, tuple[float, float]]) → dict[str, tuple[float, float]]

Column position for every axial on the machine, keyed by axial name.

braidpy.horn_gear.layout.axial_clearance(machine: BraidingMachine, layout: dict[str, tuple[float, float]], position: tuple[float, float], scale: float = 1.0) → float

Free space around a column: the distance to the nearest carrier path.

Carriers on a gear ride that gear’s rim, so the distance from a point to the nearest carrier is |distance to the centre - radius|, minimised over every gear. The one expression covers both anchors: a column at a gear’s centre clears that gear’s radius, while a column in a tube clears the gap between the hole’s centre and the surrounding rims.

A value at or below zero means carriers pass through the column in this projection. That is a genuine clash for a tube core, but expected for a flat braid, whose core rises through the convergence point where the carriers meet.

Parameters:
  • machine – The machine.

  • layout – Gear centre positions from compute_layout.

  • position – The column’s (x, y).

  • scale – Scale factor (must match the one used for the layout).

Returns:

Clearance in layout units.

braidpy.horn_gear.layout.contact_point(machine: BraidingMachine, layout: dict[str, tuple[float, float]], gear: str, neighbor: str, scale: float = 1.0) → tuple[float, float]

The middle of the notch two gears share.

Where the circles cross, the notch is the chord between the two crossings and the bobbin sits at its middle — which lies on the line between the two centres. Where the circles merely touch, the two crossings coincide and that middle is the tangent point, so one construction serves both.

braidpy.horn_gear.layout.contact_angle(machine: BraidingMachine, layout: dict[str, tuple[float, float]], gear: str, neighbor: str, scale: float = 1.0) → float

Angle (rad) from a gear’s centre toward the notch it shares with a neighbour.

braidpy.horn_gear.layout.carrier_radius(machine: BraidingMachine, layout: dict[str, tuple[float, float]], gear: str, scale: float = 1.0) → float

How far from a gear’s centre its bobbins ride.

A bobbin sits in a notch, so it turns about the gear at the distance of that notch — the gear’s own radius when the gears merely touch, and less than that when they overlap and the notch is cut back inside the rim.

braidpy.horn_gear.layout.slot_offsets(machine: BraidingMachine, layout: dict[str, tuple[float, float]]) → dict[str, float]

Per-gear rotation offset phi so connection slots point toward their neighbors.

Every connection of a gear is taken into account, via the circular mean of the offsets they each ask for. When the machine’s connection slots match its layout the requests coincide and the mean reproduces them exactly; when they do not, the residual error is shared between the contacts instead of being dumped entirely onto whichever connection happened to come second.

braidpy.horn_gear.layout.offset_residuals(machine: BraidingMachine, layout: dict[str, tuple[float, float]]) → dict[str, float]

Worst angular error (radians) between each gear’s slots and its contacts.

Zero means every contact of that gear falls exactly on a slot. A non-zero value means its slots, turned rigidly, cannot meet every contact, as where a line of gears bends; GearAngles then draws them spread unevenly, so that carriers do not jump when they transfer there.

braidpy.horn_gear.layout.FITS = 1e-09

How far (radians) a gear’s slots may miss its contacts and still be drawn turned rigidly: rounding, not a bend.

class braidpy.horn_gear.layout.GearAngles(offset: float, knots: tuple[tuple[float, float], ...] = ())

Bases: object

Where a gear’s slots are drawn on the deck, from their angle on the gear.

A gear’s slots are evenly spaced round it and turn at its rate, and are drawn turned by its offset (slot_offsets()). That puts a slot on every contact at every step only when the contacts are a whole number of slots apart round the gear, as on a straight line of gears. Where a line bends at a gear they are not, so its slots are drawn spread unevenly instead: the slot at a contact is always drawn on it, and those between two contacts evenly between their angles. A carrier rounds the outside of the bend a little faster than the inside, then, and is handed on where it is, without jumping. Which slot is where is the machine’s; only the drawing changes (see offset_residuals()).

Parameters:
  • offset – The gear’s offset, from slot_offsets().

  • knots – Each contact as (angle of its slot on the gear, angle on the deck), in order round the gear; empty where turning the slots rigidly by offset puts one on every contact.

offset: float
knots: tuple[tuple[float, float], ...] = ()
braidpy.horn_gear.layout.slot_angles(machine: BraidingMachine, layout: dict[str, tuple[float, float]]) → dict[str, GearAngles]

How each gear’s slots are drawn: see GearAngles.

Parameters:
  • machine – The machine definition.

  • layout – Gear centres, from compute_layout().

Returns:

Gear name -> its GearAngles.

braidpy.horn_gear.layout.tube_rings(machine: BraidingMachine, layout: dict[str, tuple[float, float]] | None = None) → list[list[str]]

Find the rings of gears that enclose a hole — one per tube.

Gears are tangent circles in the plane, so the connection graph is planar and the holes in the machine are exactly the bounded faces of its planar embedding. Every face is walked and the outer one — the space around the machine rather than a hole inside it — is dropped, being the largest by absolute signed area.

A flat braid has no cycle and so returns no rings; a ring braid returns one; a grid of gears returns one per opening.

Parameters:
  • machine – The machine to inspect.

  • layout – Gear centre positions (computed if None).

Returns:

List of rings, each a list of gear names in the order they enclose the hole. Empty if the machine has no hole.

braidpy.horn_gear.layout.tube_axials(machine: BraidingMachine, layout: dict[str, tuple[float, float]] | None = None, min_clearance: float = 1e-06, prefix: str = 'core') → list[Axial]

One core Axial per tube the machine braids.

Rings too tight to hold a core — where the surrounding gears reach the centre of the hole — are skipped rather than returned, so the result is only cores that physically fit.

Parameters:
  • machine – The machine to inspect.

  • layout – Gear centre positions (computed if None).

  • min_clearance – Smallest acceptable gap between core and carriers.

  • prefix – Name stem; cores are named core, core_1, … in order.

Returns:

List of Axial, empty for a machine with no tube.

braidpy.horn_gear.layout.axial_spots(machine: BraidingMachine, layout: dict[str, tuple[float, float]] | None = None) → list[Axial]

Every place the machine could feed an axial yarn, loaded or not.

Up each gear’s hollow spindle, at its centre — once for the parts of a split gear, which share an axle, named by its first part — and down the hole of each ring of gears that leaves room for one (tube_axials()). Which of them a machine braids round is its axials.

Parameters:
  • machine – The machine to inspect.

  • layout – Gear centre positions (computed if None).

Returns:

The gears’ spots, in the machine’s order, then the rings’.

braidpy.horn_gear.layout.ring_core(machine: BraidingMachine, layout: dict[str, tuple[float, float]] | None = None) → Axial | None

The core a machine that is one ring of gears braids round: down the hole the ring encloses, as a tubular machine’s or a lace machine’s.

Only a ring of every gear makes a tube: a line folded round, as the multiband machine’s, encloses a hole between its gears too, but braids flat bands, not round it.

Parameters:
  • machine – The machine.

  • layout – Gear centre positions (computed if None).

Returns:

The core, named centre; None if the machine is not one ring, or its hole has no room for a core.

braidpy.horn_gear.layout.gear_radii(machine: BraidingMachine, scale: float = 1.0) → dict[str, float]

Return the visual radius for each gear.

Parameters:
  • machine – The BraidingMachine.

  • scale – Scale factor.

Returns:

Dict mapping gear name → radius.

braidpy.horn_gear.layout.carrier_xy(machine: BraidingMachine, layout: dict[str, tuple[float, float]], angles: dict[str, GearAngles], carrier_radii: dict[str, float], position: tuple[str, int], time: int, frac: float = 0.0) → tuple[float, float]

Where in the plane a carrier is, at continuous time time + frac.

A carrier rides in a horn of its gear, so its angle is simply that slot’s angle: it turns with the gear and always sits on its slot, drawn where GearAngles draws it. It is drawn on whatever is actually moving it this step — on a machine with shared slots that is the receiving gear, see riding_position().

Transfers stay continuous without any special casing: a carrier moves to the neighbour only at the step where its slot is at the contact point, and it lands on the neighbour’s slot that is at that same contact point at that same instant, so the two coincide; where a line bends at a gear, its slots are drawn so that they still do (GearAngles).

Parameters:
  • machine – The machine definition.

  • layout – Gear centres, from compute_layout().

  • angles – How each gear’s slots are drawn, from slot_angles().

  • carrier_radii – Per-gear riding radius, from carrier_radius().

  • position – The carrier’s recorded (gear, slot) at time.

  • time – The step being taken.

  • frac – How far into that step, from 0 to 1.

Returns:

The carrier’s (x, y).

horn_gear/tracks.py

Precompute the closed carrier tracks of a braiding machine.

A track is the closed path a carrier follows when started at a given (gear, slot) position at t=0. A carrier rides in a physical horn of its gear, so at each step it either:

  1. Stays where it is — keeping its slot index while the gear turns it to a new angle.

  2. Transfers to an adjacent gear, which happens on exactly the step where its slot is the one sitting at a contact point.

Contact points are fixed in space, so a different slot index reaches them every step. The dynamics are therefore time-dependent, and a track only closes once the carrier is back at its starting slot and the contact pattern is back to its t=0 phase — usually well after one gear revolution.

Tracks normally partition the slots, but not always: two carriers may cross the same slot at different times without ever meeting, in which case their tracks overlap.

exception braidpy.horn_gear.tracks.NoFixedTracks

Bases: RuntimeError

Raised when a fixed-track calculation is asked of a programmed machine.

braidpy.horn_gear.tracks.ring_order(machine: BraidingMachine) → list[str] | None

The gears in the order they circle the machine, or None if it has no ring.

A flat braid is a chain with no way round, so there is no circulation to speak of and this returns None.

braidpy.horn_gear.tracks.circulation(machine: BraidingMachine, start: tuple[str, int], period: int | None = None) → int

Which way round the machine a carrier started at start travels.

Returns the net number of gear-to-gear steps it makes around the ring over one period: positive one way, negative the other, zero for a machine with no ring or a carrier that ends up where it began.

This counts steps around the connection graph, so it needs no layout — and it is a property of the starting position, not of the track: positions alternate in sign along a track, because a carrier placed in a slot at t=0 sits at a different phase from one that arrived there.

Only one of those two parities can be occupied at a time, though. Put carriers on both and they move towards each other and collide on the first step, so a loadable machine fills half of each track and every carrier on a given track circulates the same way. Carriers going opposite ways are on different tracks — which is what a braid is made of.

Parameters:
  • machine – The machine definition.

  • start – The (gear_name, slot_index) a carrier is placed in.

  • period – Steps to follow it for; the simulation period if None.

Returns:

Signed number of places moved around the ring.

braidpy.horn_gear.tracks.walk(machine: BraidingMachine, start: tuple[str, int], period: int | None = None) → list[tuple[str, int]]

Every position a carrier passes through, in order, repeats included.

A Track lists the distinct positions on a loop, which is what you want for counting slots but not for following one: a carrier that comes back to a slot it has already used is not recorded again, so two entries that sit side by side in a track need not be a step apart in time. On a flat braid that leaves the track reading as though a carrier hopped straight from one end gear to the other, which are not even connected.

Parameters:
  • machine – The machine definition.

  • start – Where the carrier begins.

  • period – Steps to follow it for; the simulation period if None.

Returns:

The positions visited, one per step, starting at start.

braidpy.horn_gear.tracks.contact_period(machine: BraidingMachine) → int

Number of steps after which every contact point shows the same slots again.

Delegates to the machine, because how fast the contacts cycle depends on how the gears are driven — see BraidingMachine.contact_period().

braidpy.horn_gear.tracks.compute_track(machine: BraidingMachine, start: tuple[str, int], max_steps: int = 100000) → list[tuple[str, int]]

Follow a single carrier from start until it returns.

Time advances for real: the contact pattern shifts every step, exactly as in simulate(). A carrier holds its slot for several steps, then transfers when that slot reaches a contact, so the track records the distinct positions visited, in order.

The track is closed only when the carrier is back at start and the machine’s contact pattern is back to its t=0 phase — otherwise the path from there onward would not repeat.

Parameters:
  • machine – The machine definition.

  • start – Starting (gear_name, slot_index).

  • max_steps – Safety limit to prevent infinite loops in broken configs.

Returns:

The closed track as a list of positions (start not repeated at end).

Raises:

RuntimeError – If the track does not close within max_steps.

braidpy.horn_gear.tracks.simulation_period(machine: BraidingMachine, max_steps: int = 100000) → int

Number of steps after which every carrier is back where it started.

A carrier holds each slot for several steps and must go all the way round its track, so this is generally larger than len(track) and larger than contact_period().

Parameters:
  • machine – The machine definition.

  • max_steps – Safety limit passed to the track follower.

Returns:

The machine’s full simulation period in steps.

braidpy.horn_gear.tracks.compute_tracks(machine: BraidingMachine) → list[list[tuple[str, int]]]

Compute all distinct closed tracks for the machine.

A slot belongs to one gear and one track, so the tracks partition the slots. Following a track out of every slot instead would not improve on this: at a contact the carrier is in two slots at once, so entering the loop by the other one hands back the same track reversed, and on a flat braid entering at a different phase hands back an ordering that is neither a rotation nor a reversal of the first. Starting from the slots not yet accounted for is what keeps the result a partition.

Every (gear, slot) appears on at least one track. For most machines the tracks also partition the slots, but that is not guaranteed: two carriers may pass through the same slot at different times without ever meeting, in which case their tracks overlap and the lengths sum to more than machine.total_slots(). Callers placing carriers from tracks should therefore drop repeated positions.

Parameters:

machine – The machine definition.

Returns:

List of tracks. Each track is a list of (gear_name, slot_index) visited in order.

braidpy.horn_gear.tracks.tracks_summary(tracks: list[list[tuple[str, int]]]) → dict[str, int]

Return summary statistics for a list of tracks.

Parameters:

tracks – Output of compute_tracks.

Returns:

Dict with keys ‘n_tracks’, ‘min_length’, ‘max_length’, ‘total_positions’.

horn_gear/loading.py

Deciding where the carriers start.

Threading a machine is a search, not a convention. A placement has to survive being run: _is_collision_free() simulates a candidate and rejects it if two carriers ever share a slot or meet at a connection point. Among the placements that survive, _fullest_loading() takes the one that carries most, breaking ties on circulation balance (equal numbers going each way), crowding, and how evenly the carriers spread over the gears.

Separate from simulation because the two are different jobs and the dependency runs one way: loading calls simulate to try a candidate, while stepping never calls loading.

load_carriers() needs the machine to have fixed tracks, so it is not the whole story — a machine reaches its own threading through default_carriers(), which is a hook rather than a shortcut. A Jacquard lace machine overrides it to thread one bobbin into every notch, and must: its carriers go where the programme sends them, there are no fixed tracks, and load_carriers() raises NoFixedTracks on it.

braidpy.horn_gear.loading.load_carriers(machine: BraidingMachine) → dict[int, tuple[str, int]]

Fill the machine with as many carriers as it can hold without collisions.

A real machine is loaded with a spool in every other slot along each track, which is what this tries first, since it reproduces how a machine is threaded in practice. That has no meaning for a track whose path revisits slots — the interior gears of a flat braid are crossed once per traversal — so the machine is then filled as far as it will go instead.

Either way the candidate is validated by simulating a full period: checking occupancy at t=0 is not enough, because contact points move to a different slot every step and conflicts can surface later in the cycle.

Parameters:

machine – The machine definition.

Returns:

Dict mapping carrier_id → (gear_name, slot).

Raises:

RuntimeError – If not even one carrier can be placed.

horn_gear/simulation.py

Simulation state and stepping for a horn gear braiding machine.

Each carrier occupies exactly one (gear, slot) position. At each step every turning gear advances by one slot-pitch, carrying its slots round with it; a carrier keeps its own slot and rides with it, and crosses into a neighbour’s slot only when its own slot reaches a contact. So the slot index of a carrier riding its gear does not change from step to step — it changes when the carrier transfers.

“Turning” matters: an ordinary machine turns every gear every step, but turning_gears() enables only the gears of the current phase, and a gear that is not turning holds its carriers where they are.

This module is intentionally pure / functional: MachineState is a frozen dataclass and step() returns a new state rather than mutating in place, making it easy to replay or branch the simulation.

exception braidpy.horn_gear.simulation.CollisionError(step: int, collisions: dict[tuple[str, int], list[int]], history: list[MachineState])

Bases: RuntimeError

Raised when two or more carriers occupy the same (gear, slot) after a step.

Variables:
  • step – The step at which the collision was detected.

  • collisions – Mapping of {(gear, slot): [carrier_id, …]} for every position with more than one carrier.

  • history – Valid MachineState list up to (but not including) the colliding step — i.e. the last entry is the last safe state.

class braidpy.horn_gear.simulation.CarrierState(carrier_id: int, gear: str, slot: int)

Bases: object

Position and identity of a single carrier.

Parameters:
  • carrier_id – Unique identifier for this carrier.

  • gear – Gear the carrier is currently on.

  • slot – Slot index within that gear.

carrier_id: int
gear: str
slot: int
property position: tuple[str, int]

its gear and slot.

Type:

Where the carrier is

class braidpy.horn_gear.simulation.MachineState(time: int, carriers: tuple[CarrierState, ...])

Bases: object

Snapshot of the machine at a particular simulation step.

Parameters:
  • time – Current step index (0 = initial state).

  • carriers – Tuple of CarrierState, one per carrier.

time: int
carriers: tuple[CarrierState, ...]
carrier_positions() → dict[int, tuple[str, int]]

Return {carrier_id: (gear, slot)} for all carriers.

braidpy.horn_gear.simulation.initial_state(machine: BraidingMachine, carrier_positions: dict[int, tuple[str, int]] | None = None) → MachineState

Create an initial MachineState.

If carrier_positions is None, one carrier is placed in each slot across all gears in the order they were defined.

Parameters:
  • machine – The machine definition.

  • carrier_positions – Optional mapping {carrier_id: (gear, slot)}.

Returns:

MachineState at time=0.

Raises:

ValueError – If two carriers share a position, or a position is invalid.

braidpy.horn_gear.simulation.step(machine: BraidingMachine, state: MachineState) → MachineState

Advance the machine by one step.

Each carrier moves to its next position as determined by _next_position (gear rotation + optional transfer).

Parameters:
  • machine – The machine definition.

  • state – Current machine state.

Returns:

New MachineState at state.time + 1.

braidpy.horn_gear.simulation.carrier_places(machine: BraidingMachine, state: MachineState) → dict[int, tuple[str, int]]

Where each carrier actually is: its gear, and the angle it has reached.

A slot index is a label painted on a turning gear, not a place. Every step turns a gear by one slot, so its notches land back on notch angles and the gear is indistinguishable from the gear a step earlier — which means a carrier sitting in a different notch may be at exactly the point in space it started from, and one back in “its own” notch may be on the far side of the gear. What the eye sees, and what the machine does next, follow from the angle.

Angles are returned as whole millionths of a turn, so they compare exactly and 0 and a full turn are the same place.

Parameters:
  • machine – The machine definition.

  • state – The snapshot to read.

Returns:

(gear, angle in millionths of a turn)}.

Return type:

{carrier_id

braidpy.horn_gear.simulation.state_period(machine: BraidingMachine, carrier_positions: dict[int, tuple[str, int]] | None = None, max_steps: int = 10000) → int | None

Steps after which the machine is exactly as it started, or None.

“Exactly” means every carrier back at the point it set off from — see carrier_places() for why that is not the same as back in its own slot — and the drive back to its starting phase, so the step that follows is the step that followed then. Run the machine for this many steps and the last frame hands straight back to the first.

This is a property of the machine and of how it is loaded, and it varies a lot: eight steps for a square braid, eighteen for a flat braid on nine carriers. It is not how long a carrier takes to walk its whole track — that flat braid’s track is ninety steps round — because the machine is back where it started long before any one carrier has been everywhere.

A machine driven by a programme need not ever come back — a carrier goes where the programme sends it — so this returns None rather than pretend.

Parameters:
  • machine – The machine definition.

  • carrier_positions – The carriers to follow; the machine’s own if None.

  • max_steps – How far to look before giving up.

Returns:

The cycle length in steps, or None if there is none within reach.

braidpy.horn_gear.simulation.simulate(machine: BraidingMachine, n_steps: int, carrier_positions: dict[int, tuple[str, int]] | None = None) → list[MachineState]

Run the simulation for n_steps steps.

Parameters:
  • machine – The machine definition.

  • n_steps – Number of steps to simulate.

  • carrier_positions – Optional initial placement of carriers.

Returns:

List of MachineState objects, length n_steps + 1 (includes t=0).

horn_gear/word.py

The braid word a machine and its loading make.

A braid word is not a property of a machine alone. It is a property of the machine, how it is threaded, and a direction to look from — a braid is a set of curves in space, and a word records which strand passed in front of which when they are projected onto a plane. Two projections of the same braid give different words.

Two projections are offered, because braiding machines come in two shapes:

  • flat_word() looks along the deck’s y axis, so the carriers are ordered left to right and the word is an ordinary Artin word. This is the right reading for a flat braider, whose carriers stay strung out along a line.

  • ring_word() reads round an axis — a core, or a spot one could be fed at — and writes the braid as moves round a ring (RingWord), turns and all: with the core kept as a strand it is the braid the machine makes round it, and it can be shortened (RingWord.shortened()).

  • annular_word() looks outward from a point you choose, so the carriers are ordered by angle around it and the word is an annular one — the vocabulary of braidpy.annulus_braid, where index n is the pair whose numbering wraps. This is the right reading for a tubular braider, and the point to choose is normally the axis of the tube.

Both read the word from where the carriers actually are, computed exactly from the machine at each instant by carrier_xy() — not sampled off the yarn geometry. A crossing is therefore found wherever two carriers exchange order, with no dependence on how finely a shape was drawn.

braid_word() reads a word off drawn curves instead, and the two should agree for a flat machine. The tests check that they do, which is worth more than either on its own: one works from the machine’s motion, the other from the shape that motion lays down.

class braidpy.horn_gear.word.AnnularWord(generators: list[int], winding: dict[int, float], center: tuple[float, float], n_strands: int)

Bases: object

A braid read as it winds round a point.

Parameters:
  • generators – The crossings, as signed indices. i in 1..``n-1`` is the pair at cyclic positions i-1 and i; n is the pair whose numbering wraps, which a flat word has no room for — the same numbering wrap_crossing() uses. A positive index means the strand arriving from the lower position passed outside, further from the centre.

  • winding – Per carrier, how many times it went round the centre over the stretch read. Half the carriers of a tubular braider go one way and half the other, so these come in both signs.

  • center – The point the braid was read around.

  • n_strands – How many strands there are, which is the index of the wrapping pair.

generators: list[int]
winding: dict[int, float]
center: tuple[float, float]
n_strands: int
centre

An attribute under its old name, read and written as the new one.

Held by the class under the old name: color = renamed_attribute("colour").

Parameters:

new – The attribute’s new name.

property net_winding: float

the sum of the windings.

Zero for a braid that twists as much one way as the other, which is what a balanced tubular braider makes.

Type:

The whole cross-section’s rotation

class braidpy.horn_gear.word.RingWord(moves: tuple[int, ...], n_strands: int, axis: Axial, strands: tuple[Hashable, ...])

Bases: object

A machine’s braid as moves round a ring, read round an axis.

Parameters:
  • moves – Crossings ±1 to ±n_strands and turns ±(n_strands + 1), as braidpy.annulus_braid writes them: the slots are numbered clockwise from a seam, as braidpy.ring_program numbers places, and a strand passing the seam is a turn.

  • n_strands – The strands round the axis: the carriers, and the machine’s axials but the axis’s own.

  • axis – Where the braid was read round: the core.

  • strands – The carrier or axial in each slot to begin with.

moves: tuple[int, ...]
n_strands: int
axis: Axial
strands: tuple[Hashable, ...]
braid() → Braid

The braid with nothing in its middle (solid_word()): a tube and a flat braid curled up are then the same.

cored() → Braid

The braid round its core, the core strand 1 (cored_word()).

shortened() → RingWord

The same braid round the core in as few moves as are found (shortened_ring()).

braidpy.horn_gear.word.annular_word(machine: BraidingMachine, around: tuple[float, float] | None = None, carriers: dict[int, tuple[str, int]] | None = None, n_steps: int | None = None, n_substeps: int = 64, scale: float = 1.0) → AnnularWord

The braid this machine makes, read as it winds round a point.

Carriers are ordered by their angle about around, and two of them cross exactly when their angles coincide — when their unwrapped angles differ by a whole turn. The generator’s index is where the pair sits in that cyclic order, so index n is the pair straddling the point where the numbering wraps, and its sign says which passed outside.

Nothing distinguishes that wrapping pair physically: it is an artefact of having to start numbering somewhere, exactly as in braidpy.annulus_braid.

Parameters:
  • machine – The machine definition.

  • around – The point to look out from; deck_center() if None.

  • carriers – The loading; the machine’s own if None.

  • n_steps – How many steps to read; one full cycle if None.

  • n_substeps – Samples per step.

  • scale – Layout scale.

Returns:

The crossings, and how far each carrier wound round the centre.

braidpy.horn_gear.word.deck_center(machine: BraidingMachine, scale: float = 1.0) → tuple[float, float]

The centroid of the gears, as a default point to look out from.

For a machine whose gears ring a hole — a tubular braider — this is the axis of the tube, which is the point annular_word() wants. For any other shape it is just a centroid, and worth replacing with a point you chose on purpose.

Parameters:
  • machine – The machine definition.

  • scale – Layout scale.

Returns:

The (x, y) centroid of the gear centres.

braidpy.horn_gear.word.default_axis(machine: BraidingMachine) → Axial

Where to read a machine’s braid round, if not said: the core it braids round, or the nearest thing to one.

In this order: an axial the machine feeds down a ring’s hole; the hole a ring of gears encloses, which a tubular braider braids round (tube_axials()); an axial the machine feeds up a gear, as a soutache’s cord; the gear nearest the deck’s centre (deck_center()).

Parameters:

machine – The machine.

Returns:

The axis, one of the machine’s axial_spots(), or its own axials.

braidpy.horn_gear.word.flat_word(machine: BraidingMachine, carriers: dict[int, tuple[str, int]] | None = None, n_steps: int | None = None, n_substeps: int = 64, scale: float = 1.0) → list[int]

The Artin word of the braid this machine makes, seen from the front.

Carriers are ordered left to right across the deck and a crossing is recorded whenever two neighbours exchange places. Its sign says which passed in front: positive when the one arriving from the left passes on the near side, the convention braid_word() and to_parametric_strands() both use.

This suits a machine whose carriers stay strung out along a line. On a tubular braider the left-to-right order is meaningless — the carriers go round — and the word comes out as noise; use annular_word() there.

Parameters:
  • machine – The machine definition.

  • carriers – The loading; the machine’s own if None.

  • n_steps – How many steps to read; one full cycle if None.

  • n_substeps – Samples per step. Two carriers exchanging and exchanging back within one sample are missed, so this is generous by default.

  • scale – Layout scale.

Returns:

The word, as signed generator indices.

braidpy.horn_gear.word.ring_unit(machine: BraidingMachine, axis: Axial | None = None, carriers: dict[int, tuple[str, int]] | None = None) → tuple[RingWord, int]

The shortest stretch of a machine’s cycle that, repeated, makes it: as few steps as bring the carriers back to where carriers stood, each perhaps where another was, read as a ring word (ring_word()).

A tube comes round long before its carriers are home: a tubular braider of 16 does in 2 steps what its 16-step cycle does 8 times. The stretch need not bring a strand home, nor make a pure braid; made over and over, it makes the machine’s braid round its core, exactly.

Parameters:
  • machine – The machine.

  • axis – As ring_word() takes it.

  • carriers – The loading; the machine’s own if None.

Returns:

The stretch’s ring word, shortened (RingWord.shortened()), and how many times a cycle makes it.

braidpy.horn_gear.word.ring_word(machine: BraidingMachine, axis: Axial | None = None, carriers: dict[int, tuple[str, int]] | None = None, n_steps: int | None = None, n_substeps: int = 64) → RingWord

The braid a machine makes as moves round a ring, read round an axis.

Seen from the axis, the strands are in a ring: in order round it, clockwise from a seam put in the widest gap between them. Two strands neighbours round it cross when they come in line with the axis, the one further from it outside; a strand passing the seam, crossing nobody, turns the ring by a slot. Where annular_word() keeps only the order round the axis, this keeps the seam, and so the turns: the braid round the axis, its core kept (RingWord.cored()), is the braid the machine makes round a yarn fed there, exactly.

The axis matters: round another point the same machine makes another braid round its core, the same once the core is taken away (RingWord.braid()).

Parameters:
  • machine – The machine.

  • axis – What to read the braid round, an axial or a spot one could be fed at (axial_spots()); default_axis() if None. An axial the machine feeds there is the core, not a strand.

  • carriers – The loading; the machine’s own if None.

  • n_steps – How many steps to read: one cycle of the machine if None (state_period()), or for a machine driven by a programme, one pass of it.

  • n_substeps – Samples per step.

Returns:

The moves, and which strand began where.

Raises:

ValueError – If a strand passes through the axis.

horn_gear/jacquard.py

Jacquard lace machine: a braiding machine whose gears are driven one by one from a punched programme instead of being geared together.

An ordinary braiding machine turns every gear on every step, so its braid is fixed by the wiring of the machine. A Jacquard machine reads, at each step of its programme, a two-line binary mask over the gears:

  • the first line says which gears take a half turn trigonometrically (CCW),

  • the second line says which take a half turn clockwise.

A gear’s direction belongs to the gear and never changes; the mask only says whether it is allowed to turn this step.

What makes this machine different is its geometry. Its gear circles interpenetrate rather than merely touching, and a slot is the notch cut where two of them overlap — so a slot belongs to both gears at once, and a bobbin sitting in one is swept out by whichever of the pair turns. That is what lets a gear turn while its neighbour stands still, which a machine of tangent gears cannot do.

It also means two neighbouring gears must never turn together: they would both reach for the bobbin in the notch they share. Hence the two lines, driven one after the other — neighbours alternate direction round a ring, so each line on its own only ever turns gears that do not touch. A programme that breaks this is rejected when the machine is built.

Because the programme decides where every bobbin goes, a bobbin’s path need not come back on itself: there are no closed tracks here and no period, and compute_tracks() and its relatives say so rather than inventing one. Thread the machine with notch_positions() and simulate the programme instead.

Layout, drawing and collision detection are shared with any other machine and need no special case: the only things that differ are how far each gear has turned by a given step and where a bobbin goes next, both of which the base class already asks itself through rotation() and next_position().

exception braidpy.horn_gear.jacquard.JacquardProgramError

Bases: ValueError

Raised when a programme cannot be run on this machine.

braidpy.horn_gear.jacquard.notch_positions(machine: JacquardLaceMachine) → dict[int, tuple[str, int]]

One bobbin in every notch — the usual way a lace machine is threaded.

A notch is shared by the two gears whose circles cut it, so there is one bobbin position per contact, not per slot. Filling them all is safe by construction: no two bobbins can land in the same notch.

Parameters:

machine – The machine to thread.

Returns:

Dict mapping carrier_id → (gear_name, slot), one entry per contact.

class braidpy.horn_gear.jacquard.JacquardLaceMachine(gears: list[HornGear], connections: list[Connection], program: Sequence[tuple[str | Sequence[int | bool], str | Sequence[int | bool]]], axials: Iterable[Axial] = (), threaded: Sequence[int] | None = None)

Bases: BraidingMachine

A braiding machine whose gears are driven individually by a programme.

Parameters:
  • gears – The horn gears. Lace machines use 2-slot gears, but any slot count works.

  • connections – Contacts between gears, as for any machine.

  • program – One entry per programmed step, each a (trigonometric_line, clockwise_line) pair. A line is a bit per gear, in the order the gears were given — "1010", (1, 0, 1, 0) or a tuple of bools.

  • axials – Optional cords the braid forms around.

Raises:

JacquardProgramError – If the programme is empty, a line is the wrong length, a line enables a gear that turns the other way, or a line turns two neighbouring gears at once.

gears_interpenetrate: bool = True

The circles overlap, and a slot is the notch they cut between them.

has_fixed_tracks: bool = False

Carriers go where the programme sends them, so their paths need not close and the machine has no tracks or period to compute.

threaded

The notches threaded, by contact; every one if None.

turning_gears(step: int) → frozenset[str]

Gears enabled for the phase running from step to step + 1.

program_rows() → list[tuple[str, tuple[bool, ...]]]

The programme as punchcard rows, two per punched step.

preferred_layout(scale: float = 1.0) → dict[str, tuple[float, float]] | None

Place a ring so every notch lands exactly on a slot.

The generic layout sets gear circles tangent, which is right for a braiding machine but wrong here: these circles have to overlap for there to be a notch at all. For a ring of n gears of 2 slots the geometry is forced, and worth deriving rather than approximating.

A gear’s two notches are cut where its circle crosses each neighbour’s, and being 2-slot they must come out diametrically opposite — so the gear’s centre is the midpoint of the two notches. Putting the centres on a circle of radius R and working that condition through gives:

r = R * tan(pi / n)

which is larger than the R * sin(pi / n) half-spacing that would make them touch, so the circles interpenetrate exactly as they should.

Returns None — deferring to the generic layout — for anything that is not a ring of equal 2-slot gears.

Parameters:

scale – Overall scale factor for gear radii.

Returns:

Gear name → (x, y), or None.

riding_position(pos: tuple[str, int], time: int, frac: float = 0.0) → tuple[str, int]

Which gear sweeps a bobbin through this step — which may not be its own.

A bobbin in a notch is swept by whichever of the two gears turns, so the gear that moves it is the one it ends the step on. Drawing it on its own idle gear instead would leave it still for the whole step and then jump it across to the neighbour.

All three cases fall out of next_position(): the bobbin’s own gear when that turns, the receiving gear when the neighbour takes it, and where it already is when nothing moves.

default_carriers() → dict[int, tuple[str, int]]

Thread one bobbin into every notch, or into those threaded.

next_position(pos: tuple[str, int], time: int) → tuple[str, int]

Where a carrier goes during the step from time to time + 1.

The gear circles interpenetrate, so a slot is the notch cut where two of them overlap and belongs to both gears at once. A bobbin sitting in that notch is swept out by whichever of the two turns:

  • its own gear turns → it stays on that gear, carried round to the gear’s other notch;

  • its own gear is idle and the gear across the notch turns → that gear takes it, and it rides on round to that gear’s other notch;

  • neither turns → it stays where it is.

Both turning at once would have the two gears fighting over the same bobbin, which is why the mask is split into two lines and applied one after the other; the constructor rejects a line that enables neighbouring gears together.

Parameters:
  • pos – Current (gear_name, slot_index).

  • time – Step being taken.

Returns:

The (gear_name, slot_index) the carrier occupies afterwards.

rotation(gear_name: str, time: int) → int

Signed slots turned through after time simulation steps.

contact_period() → int

Steps until the programme restarts and every gear is back square.

The programme repeats every steps_per_pass steps, but a gear only looks the same again once its accumulated turns are a whole number of revolutions, so the true period is a multiple of the programme length.

property steps_per_pass: int

Simulation steps in one pass of the programme — two per punched step.

The two mask lines are driven one after the other, so a punched step takes two simulation steps.

braidpy.horn_gear.jacquard.jacquard_lace_ring(n_gears: int = 6, program: Sequence[tuple[str | Sequence[int | bool], str | Sequence[int | bool]]] | None = None, n_slots: int = 2, threaded: Sequence[int] | None = None) → JacquardLaceMachine

A tubular Jacquard lace machine: 2-slot gears in a ring.

Layout:

[A] - [B] - [C] - [D] - [E] - [F] - back to [A]

Each gear carries two slots, one at each of its two contacts, so a half turn swaps which neighbour each of its carriers faces. Gears alternate direction round the ring, which is why n_gears must be even — meshing gears have to turn opposite ways.

With no programme given, every gear is enabled on every step, which drives the machine exactly like an ordinary tubular braider and is the useful baseline to compare a real programme against.

Parameters:
  • n_gears – Number of gears in the ring; must be even and at least 4.

  • program – Punched steps; defaults to one step with everything enabled.

  • n_slots – Slots per gear. Lace machines use 2.

  • threaded – The notches a bobbin is put in, notch k between gears k and k + 1; every notch if None.

Returns:

JacquardLaceMachine for a ring of gears.

Raises:

ValueError – If n_gears is odd or smaller than 4.

A braiding machine worked by hand: carriers placed, the handle turned a step at a time, forwards or back.

load_carriers() loads a machine outright, but when the loading wanted collides it says nothing of where or why. Turning the handle and watching is often quicker.

What is turned is always the loading at step 0 — the carriers the machine braids with — so there is one thing to keep: going back a step is running one step fewer, and a carrier put on a slot at step t goes onto the slot at step 0 that brings it there (origin()), changing the loading itself. Every step is the machine’s own (simulate()), and so is every collision: two carriers in one slot, two crossing at a contact, or a carrier either side of one.

Handle keeps a loading and a step, for Python and plotly; Braid Studio keeps them in the page and asks turn() for each step.

class braidpy.horn_gear.handle.Handle(machine: BraidingMachine, loading: Sequence[tuple[str, int]] | None = None)

Bases: object

A machine, its loading, and how far its handle has been turned.

>>> from braidpy.horn_gear.examples import flat_braid_9
>>> handle = Handle(flat_braid_9())
>>> handle.turn(3).time
3
>>> handle.back().time
2
Parameters:
  • machine – The machine.

  • loading – The carriers at step 0; the machine’s own if None.

turned() → Turned

The machine as the handle has turned it.

property met: dict[tuple[str, int], list[int]]

Where carriers met, if they did, on the way to this step.

turn(steps: int = 1) → Handle

Turn the handle on, stopping where carriers meet.

Parameters:

steps – How many steps.

Returns:

The handle, at the step reached.

back(steps: int = 1) → Handle

Turn the handle back, no further than step 0.

Parameters:

steps – How many steps.

Returns:

The handle.

toggle(position: tuple[str, int]) → Handle

Put a carrier on a place, as it is at this step, or take off the one there: the loading changes, at the slot that leads there.

Parameters:

position – The place, as (gear, slot), at this step.

Returns:

The handle.

Raises:

ValueError – If no slot leads there.

figure(**options) → go.Figure

The machine turned from step 0 to this one, as a plotly animation; where carriers met, ringed.

Parameters:

**options – For animate().

Returns:

The figure.

class braidpy.horn_gear.handle.Turned(state: MachineState, met: dict[tuple[str, int], list[int]])

Bases: object

Where the handle got to: the machine at that step, and what stopped it, if anything did.

Parameters:
  • state – The carriers at the step reached.

  • met – Where carriers met, by the carriers on each place; empty if none did. The handle stops at the step they met.

property time: int

The step reached.

property positions: list[tuple[str, int]]

Where each carrier is, in the loading’s order.

braidpy.horn_gear.handle.drawing(machine: BraidingMachine) → Drawing

Where a machine’s gears are, how they are turned and the circle their carriers ride: worked out once, for sweep() to draw every step.

braidpy.horn_gear.handle.origin(machine: BraidingMachine, position: tuple[str, int], time: int) → tuple[str, int] | None

The slot at step 0 whose carrier is at position at step time.

Parameters:
  • machine – The machine.

  • position – A place at step time, as (gear, slot).

  • time – The step.

Returns:

That slot; None if no slot leads there.

braidpy.horn_gear.handle.sweep(machine: BraidingMachine, state: MachineState, frames: int, drawn: Drawing | None = None) → tuple[list[Position], list[list[list[float]]], list[list[list[float]]]]

Where every slot and carrier is through one step, from state: frames pictures, the first the step itself. The same places as the plotly animation draws (animate()).

Parameters:
  • machine – The machine.

  • state – The carriers at the step.

  • frames – How many pictures.

  • drawn – The machine’s drawing(), if already worked out.

Returns:

The slots, gear by gear; and per picture, each slot’s and each carrier’s (x, y).

braidpy.horn_gear.handle.turn(machine: BraidingMachine, loading: Sequence[tuple[str, int]], time: int) → Turned

The handle turned time steps from a loading, as the machine turns it, stopping where carriers meet.

Parameters:
  • machine – The machine.

  • loading – The carriers at step 0, as (gear, slot).

  • time – How many steps to turn.

Returns:

Where the handle got to.

A line of horn gears that braids several bands at once.

A line of gears braids one band however long it is: every interior gear has two contacts, so a carrier entering by one leaves by the other and walks the whole line. A band needs a gear at each end that turns its carriers back, and that gear needs an odd number of slots: an even one returns a carrier to the strand it came in on and breaks the band into short tracks that fill only part of it (see flat_braid_9()).

Where two bands meet, one gear turns the carriers of both back. It is a split gear: two gears on one axis, turning together, one for each band, with their horns between each other’s. A six-horn split gear gives each band three: an odd turning gear for each, and the two never share a horn. Each half meets only its own band’s neighbour, so a carrier can never cross into the other band, and the half that is not at a contact is always a third of a pitch away from it.

It is modelled as two HornGear of three slots at the same centre, drawn as large as the six-horn gear they make. Each turns one of its own slots a step, as every gear does, which is two horns of the whole gear: the bands see three-slot turning gears, which is what the machine needs.

multiband_10_15_10() is the three-band machine of the Atelier de Tressage’s circuit drawing (see the references page), sixteen gears:

5  4  4  8  6  8  4  4  4  4  8  6  8  4  4  5
            ^                    ^
         split                 split

The two six-horn gears are split, cutting the line into bands of 24, 38 and 24 slots. Each band holds at most half its slots, 12, 19 and 12 carriers, as a flat braid does; the drawing runs 10, 15 and 10 (MULTIBAND_10_15_10_LOADING).

twin_plait() is the smallest such machine: three gears, 3 6 3, and two plaits braided side by side.

braidpy.horn_gear.multiband.TWIN_PLAIT_SLOTS = (3, 6, 3)

an end gear of three slots, a six-slot gear split three and three, and another end gear. Each band is three slots of end gear and three of split gear, the smallest flat braid there is: two plaits side by side.

Type:

The smallest line that braids two bands

braidpy.horn_gear.multiband.TWIN_PLAIT_SPLIT = (1,)

Its one split gear.

braidpy.horn_gear.multiband.MULTIBAND_10_15_10_SLOTS = (5, 4, 4, 8, 6, 8, 4, 4, 4, 4, 8, 6, 8, 4, 4, 5)

Slots per gear along the line, read off the circuit drawing. The gears lie on a line folded round into nearly a circle; its ends never join.

braidpy.horn_gear.multiband.MULTIBAND_10_15_10_SPLIT = (4, 11)

The gears split between the bands on either side of them.

braidpy.horn_gear.multiband.MULTIBAND_10_15_10_LOADING = ((('G0', 0), ('G0', 2), ('G0', 4), ('G1', 2), ('G1', 3), ('G2', 1), ('G2', 2), ('G3', 2), ('G3', 5), ('G4a', 1)), (('G4b', 0), ('G4b', 2), ('G5', 2), ('G5', 5), ('G6', 1), ('G6', 2), ('G7', 2), ('G7', 3), ('G8', 1), ('G8', 2), ('G9', 2), ('G9', 3), ('G10', 1), ('G10', 4), ('G11a', 2)), (('G11b', 0), ('G11b', 1), ('G12', 1), ('G12', 4), ('G13', 2), ('G13', 3), ('G14', 1), ('G14', 2), ('G15', 2), ('G15', 4)))

10, 15 and 10, the 10-15-10 of its name. Not the most it holds (the exact loading search gives 12, 19 and 12): as the drawing loads it, gear by gear, each carrier going the way the drawing’s arrows send it. Every gear but the eight-horn ones takes its carriers on the only slots that do; an eight-horn gear carries one each way, as drawn, on one of the four pairs of slots that run (the drawing does not say which). The tests run it over the whole machine’s period, 2280 steps.

Type:

Where the reference machine’s carriers start, band by band

braidpy.horn_gear.multiband.bands_of(n_gears: int, split: Sequence[int]) → tuple[tuple[int, int], ...]

Which gears each band of a line runs over: from an end or a split gear to the next.

Parameters:
  • n_gears – Gears along the line.

  • split – The split gears.

Returns:

Per band, its first and last gear; a split gear is the last of one band and the first of the next.

braidpy.horn_gear.multiband.gear_name(index: int, split: Sequence[int], side: int = 0) → str

The name of gear index, or of one half of it if it is split.

Parameters:
  • index – Position along the line.

  • split – The split gears.

  • side – For a split gear, -1 for the half serving the band before it, +1 for the band after it.

Returns:

G<index>, with a or b for a half.

class braidpy.horn_gear.multiband.MultibandLine(slots: Sequence[int], split: Sequence[int], first: int = 0, last: int | None = None, loading: Sequence[tuple[str, int]] | None = None)

Bases: BraidingMachine

A line of gears cut into bands by split gears, or some of its bands.

Gear names and slot numbering are the whole line’s whichever bands are built, so a loading reads the same on a band as on the whole machine.

Parameters:
  • slots – Slots per gear along the whole line; a split gear’s count is that of the whole gear, both halves.

  • split – Which gears are split between two bands.

  • first – The first gear built.

  • last – The last gear built.

  • loading – The carriers to start with, if known; else searched for.

TURN = 5.410520681182422

How far the line turns, end to end, folded round on itself.

property bands: tuple[tuple[int, int], ...]

see bands_of().

Type:

Which gears each band of the whole line runs over

band_of(gear: str) → int | None

Which band a gear, or a split gear’s half, serves.

Parameters:

gear – Gear name, G<index>, with a or b for a half.

Returns:

The band, counted from 0 along the whole line; None if the line has no such gear.

carrier_colors(carriers: dict[int, tuple[str, int]] | None = None) → dict[int, str] | None

Every carrier in its band’s colour, so the bands can be told apart in the braid they make together.

Parameters:

carriers – Carrier number -> (gear, slot) it starts at; the machine’s own loading if None.

Returns:

the palette’s first for the first band, its second for the next, and so on.

Return type:

Carrier number -> colour

preferred_layout(scale: float = 1.0) → dict[str, tuple[float, float]] | None

Gear centres along the folded line, consecutive rims touching, a split gear’s two halves on one centre.

The line runs straight through a split gear, its two contacts opposite each other, so that each half’s three horns stand exactly between the other’s: the six make a regular hexagon. It folds by the same angle at every other interior gear, TURN in all, which brings its ends round near each other without touching.

The whole line’s fold, whichever bands are built, so a band sits where it does in the whole machine.

Parameters:

scale – Overall scale factor.

Returns:

Gear name -> (x, y).

braidpy.horn_gear.multiband.twin_plait() → MultibandLine

Two plaits braided at once on one line of three gears.

The smallest machine with a split gear, to see what one does: two three-slot end gears either side of a six-slot gear split between them. Each band is a plait of three carriers, turned back on its own half of the middle gear; the two plaits share that gear and never meet.

Returns:

the line, loaded with three carriers in each band.

Return type:

MultibandLine

braidpy.horn_gear.multiband.multiband_10_15_10() → MultibandLine

The three-band 10-15-10 machine, loaded as its drawing is.

Sixteen gears, the two six-horn ones split between the bands on either side; see the module.

Returns:

the whole line.

Return type:

MultibandLine

braidpy.horn_gear.multiband.multiband_band(band: int) → MultibandLine

One band of multiband_10_15_10(), on its own.

Its gears, with the half of each split gear that serves it, and its part of the reference loading. It braids exactly as it does in the whole machine: the other halves never meet it.

Parameters:

band – 0, 1 or 2, along the line.

Returns:

that band’s gears.

Return type:

MultibandLine

Raises:

ValueError – If band is not 0, 1 or 2.

horn_gear/take_off.py

The braid coming off a horn gear machine.

The machine says where each carrier is at every instant (carrier_trajectories()); from there the braid is laid, drawn in to a fell and tightened exactly as any other source of strands is — see braidpy.take_off, which holds the model. This module only adds what a machine knows: its gears to stand the braid on, the middle of them for an axis, the axial cores the braid is laid round, and a take-off rate in proportion to its gears.

class braidpy.horn_gear.take_off.CarrierTrajectories(times: ~numpy.ndarray, xy: dict[~collections.abc.Hashable, ~numpy.ndarray], outlines: tuple[~numpy.ndarray, ...] = (), axis: tuple[float, float] | None = None, label: str = 'Yarn ', outline_name: str = 'Deck', slots: tuple[tuple[float, float, str], ...] = (), layout: dict[str, tuple[float, float]] = <factory>, radii: dict[str, float] = <factory>)

Bases: StrandTrajectories

Where every carrier went, sampled through a run of the machine.

StrandTrajectories with times in steps, and the machine’s layout kept alongside.

Parameters:
  • layout – Gear centres the positions are measured against.

  • radii – Gear radii at the same scale.

layout: dict[str, tuple[float, float]]
radii: dict[str, float]
class braidpy.horn_gear.take_off.Clearance(distance: float, gap: float, met: TooCloseError | None)

Bases: object

How close a machine’s carriers come to each other, and so how large the machine has to be for its bobbins.

Scaled up, a machine keeps its carriers further apart in proportion: bobbins of diameter b pass if it is drawn b / distance times as large (scale_for()), in whatever unit b is given. Only two carriers at one point (met) can pass on no machine.

Variables:
  • distance (float) – The closest two carriers come.

  • gap (float) – The smallest gap between two neighbouring horns of a gear; round a split gear, all its parts’ horns count.

  • met (braidpy.horn_gear.take_off.TooCloseError | None) – Where two carriers first came to one point, if they did.

distance: float
gap: float
met: TooCloseError | None
property share: float

The closest two carriers come, as a share of gap.

scale_for(bobbin_diameter: float) → float

How large the machine must be drawn for bobbins of bobbin_diameter to pass each other: so many of the bobbin’s units to one unit of the drawing (mm to a unit, for a diameter in mm).

exception braidpy.horn_gear.take_off.TooCloseError(step: int, carriers: tuple[int, int], distance: float, limit: float, history: list)

Bases: CollisionError

Raised for two carriers that come to one point (MEET), in different slots: the simulation sees no collision, but they would hit on a machine of any size.

Variables:
  • step – The step during which they came that close.

  • collisions – The first carrier’s place as the step began, and the two carriers, as CollisionError gives them.

  • history – The states before that step.

  • distance – How close they came.

  • limit – How close they could have come.

braidpy.horn_gear.take_off.carrier_trajectories(machine: BraidingMachine, n_steps: int, carrier_positions: dict[int, tuple[str, int]] | None = None, n_substeps: int = 12, scale: float = 1.0) → CarrierTrajectories

Follow every carrier through n_steps steps of the machine.

Each step is split into n_substeps samples, at the same positions the animation draws (carrier_xy()), so what is laid here is exactly what is seen turning there.

Parameters:
  • machine – The machine definition.

  • n_steps – How many steps to run.

  • carrier_positions – The loading; the machine’s own if None.

  • n_substeps – Samples per step.

  • scale – Layout scale.

Returns:

The sampled trajectories, n_steps * n_substeps + 1 samples long.

Raises:

CollisionError – If the loading collides within the run — a braid that cannot be made has no shape to give.

braidpy.horn_gear.take_off.clearance(machine: BraidingMachine, n_steps: int, carrier_positions: dict[int, tuple[str, int]] | None = None, scale: float = 1.0) → Clearance | None

How close the carriers come in n_steps, following them as they are drawn (carrier_trajectories()).

The simulation stops a machine where two carriers would take one slot (CollisionError). Two carriers in different slots can come to one point all the same, as on gears laid out too close together.

Parameters:
  • machine – The machine definition.

  • n_steps – How many steps to look over.

  • carrier_positions – The loading; the machine’s own if None.

  • scale – Layout scale.

A machine driven by a card, as a lace machine is, swaps two bobbins by passing one by the other in a notch: it is not looked at.

Returns:

How close they come, and where two first came to one point if they did; None for fewer than two carriers, or a machine driven by a card.

braidpy.horn_gear.take_off.default_take_off(machine: BraidingMachine, scale: float = 1.0) → float

A take-off rate that draws a machine’s braid in sensible proportions.

Half the mean gear radius per step: a carrier then moves across the deck about as far as the braid moves up, so its yarn leaves at roughly 45°, near the angle a braid is usually made at. It sets only how stretched the picture is — nothing about which yarn crosses which depends on it.

braidpy.horn_gear.take_off.jammed_contraction(rel: ndarray, spacing: float, diameter: float) → float

How far a braid can be drawn in before two yarns touch.

Drawing the plane in by k shrinks the sideways part of every distance by k and leaves the height part alone, so a pair of samples a height dz apart and s apart sideways touches when k = sqrt(d² - dz²) / s. The braid jams at the largest of these — an exact answer over the samples, with no search.

Parameters:
  • rel – Per yarn, its samples relative to the axis; shape (yarns, n, 2), every yarn at the same heights.

  • spacing – Height between successive samples.

  • diameter – Yarn diameter.

Returns:

The contraction k; above 1 if the yarns do not fit even undrawn.

Raises:

ValueError – If two yarns pass through the same place too close in height for any drawing-in to separate them — the take-off is too slow for yarns this thick.

braidpy.horn_gear.take_off.tighten_yarns(paths: YarnPaths, yarn_diameter: float, iterations: int = 400, step: float = 20.0, core_radius: float | None = None, tolerance: float = 0.001, hold_top: bool = True, rigid: Collection[Hashable] = (), periodic: Periodic | None = None) → tuple[YarnPaths, dict[str, list[float]]]

Pull the yarns taut above the fell, without letting them overlap.

Each iteration shortens every yarn, sideways only, so every sample keeps its height; then it pushes apart any two samples of different yarns closer than a diameter, until none are. The yarn is held where it arrives at the fell from its carrier, and at its oldest end, where the take-off holds it. Between the two, far enough from the fell, the braid takes the shape its yarns pull it into, whatever shape the fell started it in.

Shortening at fixed height is the length objective of Solving a braid’s shape numerically in its small-slope form — tension pulls a yarn toward the middle of its neighbours — and the push is its non-interpenetration constraint. The tension is taken implicitly, as a backward-Euler step of step along that flow, which settles a whole yarn in a few dozen iterations where moving each sample toward its neighbours would take thousands. No sample moves more than a fifth of a diameter in one go, though, so a yarn cannot jump through another and the braid the machine made is the braid that comes out.

Parameters:
  • paths – The braid to tighten.

  • yarn_diameter – Yarn diameter.

  • iterations – Shortening steps.

  • step – How far along the tension flow each step goes, in units where 1 moves a sample half way to its neighbours’ middle.

  • core_radius – Keep the yarns outside a core of this radius round the axis, for a braid laid over one.

  • tolerance – Overlap, as a fraction of the diameter, that the contact push accepts.

  • hold_top – Hold the oldest end where it is, as the take-off does. Left free, the end can turn about the axis and untwist the braid. Ignored when periodic is given, which holds neither end.

  • rigid – Yarns held where they are all along, as stiff cores: the others are pushed off them, and they never move.

  • periodic – Join the fell end of the braid to its top, so that what is tightened is one window of an endless braid rather than a short piece of a held one. See Periodic: the window must be a whole number of periods.

Returns:

"length", the total yarn length above the fell, and "closest", the closest approach, after each iteration.

Return type:

The tightened braid, and its history

Warns:

UserWarning – If the braid is laid too coarsely for contact between samples to keep its yarns apart (warn_if_too_coarse()).

braidpy.horn_gear.take_off.too_close(machine: BraidingMachine, n_steps: int, carrier_positions: dict[int, tuple[str, int]] | None = None, scale: float = 1.0) → TooCloseError | None

The first time two carriers come to one point in n_steps, if they do (clearance()): they would hit on a machine of any size.

Parameters:
  • machine – The machine definition.

  • n_steps – How many steps to look over.

  • carrier_positions – The loading; the machine’s own if None.

  • scale – Layout scale.

Returns:

The first two carriers at one point, as an error to raise or report; None if no two are, or the machine is driven by a card.

braidpy.horn_gear.take_off.visualize_yarns(machine: BraidingMachine, paths: YarnPaths | None = None, output_html: str | None = None, title: str | None = None, tube_diameter: float | None = None, n_around: int = 12, show_deck: bool = True, **kwargs) → Figure

The yarns in 3D, standing on the machine that laid them.

visualize_yarns(), with the gears outlined on the deck and any axial core standing as a column through the braid. Each yarn is drawn in its carrier’s colour — the same colours as animate().

Parameters:
  • machine – The machine definition.

  • paths – Yarns to draw; computed by yarn_paths() if None, which kwargs are then passed to.

  • output_html – If given, write the figure to this HTML file.

  • title – Figure title; says which model the yarns follow if None.

  • tube_diameter – Draw the yarns as tubes this thick. Defaults to the yarn diameter the braid was made for, if any; 0 draws lines.

  • n_around – Points round each tube, when drawing them.

  • show_deck – Outline the gears at z = 0.

Returns:

The figure.

braidpy.horn_gear.take_off.yarn_paths(machine: BraidingMachine, n_steps: int | None = None, carrier_positions: dict[int, tuple[str, int]] | None = None, take_off: float | None = None, n_substeps: int = 12, scale: float = 1.0, n_cycles: int = 3, axials: bool = False, **lay) → YarnPaths

The braid a machine has made after n_steps steps.

Follows the carriers (carrier_trajectories()) and lays their yarns with lay_yarns(), which lay is passed to: fell_radius, yarn_diameter, fell_height, axis, n_converge and settle_length. The axis defaults to the middle of the gears.

Parameters:
  • machine – The machine definition.

  • n_steps – How long to braid for. If None, n_cycles full cycles of the machine (state_period()), so the braid shows its repeat that many times over; a programmed machine with no cycle runs its drive round that many times.

  • carrier_positions – The loading; the machine’s own if None.

  • take_off – Length of braid drawn off per step. Defaults to default_take_off().

  • n_substeps – Samples per step. With a yarn_diameter, keep take_off / n_substeps below it, or contacts go unseen.

  • scale – Layout scale.

  • n_cycles – Cycles to braid for when n_steps is None.

  • axials – Lay the axial cores too, each a yarn that stays where it enters the braid, named after the axial: drawn in to the fell and tightened with the others, it ends up inside the braid, held there by the yarns crossing round it, as a core is.

Returns:

The yarns, one per carrier, and one per axial if asked for.

horn_gear/visualization.py

Interactive Plotly visualizations for horn gear braiding machines.

Three entry points:

  • visualize_machine: Static diagram of gear layout and connections.

  • visualize_tracks: Tracks drawn as circular arcs connecting physical

    gear-contact points (no straight-line jumps).

  • animate: Smooth sub-step animation showing continuous

    gear rotation (e.g. quarter-turns for 4-slot gears), one full cycle of the machine, played round and round.

Key geometric conventions

Each gear G has a layout position (cx, cy) and radius r. Two connected gears meet at a notch: for tangent gears that is the single point where they touch, and for gears that interpenetrate it is the middle of the chord between the two places their circles cross. Either way it lies on the line between the two centres, and a carrier rides at that distance from its gear’s centre — on the rim when the gears merely touch, inside it when they overlap.

The rotation offset phi_G turns each gear so its connection slots point at its notches, fitted across all of them (slot_offsets()); where a line of gears bends, so that turned rigidly they cannot all meet them, the slots are drawn spread unevenly instead, so that carriers are handed on without jumping (slot_angles()).

Nothing here decides how far a gear has turned, where a carrier goes next, or which gear is carrying it — those belong to the machine, so that an ordinary braider and a programme-driven lace machine can both be drawn by this code without it knowing the difference.

braidpy.horn_gear.visualization.track_curves(machine: BraidingMachine, layout: dict[str, tuple[float, float]], tracks: list[list[tuple[str, int]]] | None = None, scale: float = 1.0) → list[tuple[str, ndarray]]

Each carrier track as a closed run of arcs, seen from above.

A run of positions on the same gear is drawn as a single arc from the notch the carrier came in by to the one it leaves by, following the gear’s rotation, at the radius the carriers actually ride at — so the tracks lie under the carriers rather than beside them.

Tracks belong to the wiring, so they are the same at every step. A machine driven by a programme has none.

Parameters:
  • machine – The machine.

  • layout – Where its gears are (compute_layout()).

  • tracks – Its tracks, if already worked out.

  • scale – The layout’s scale.

Returns:

Per distinct closed curve, a name — the loop of gears it runs round — and its points, shape (n, 2), the first repeated at the end.

braidpy.horn_gear.visualization.colored_tracks(machine: BraidingMachine, layout: dict[str, tuple[float, float]], tracks: list[list[tuple[str, int]]] | None = None, scale: float = 1.0) → list[tuple[str, str, ndarray]]

Each carrier track (track_curves()) in its colour: the palette’s, one after another, wherever the tracks are drawn.

Returns:

Per track, its name, its colour and its points.

braidpy.horn_gear.visualization.visualize_machine(machine: BraidingMachine, scale: float = 1.0, output_html: str | None = None, title: str = 'Horn Gear Braiding Machine') → Figure

Static diagram of the machine layout with oriented slot tick marks.

braidpy.horn_gear.visualization.visualize_tracks(machine: BraidingMachine, tracks: list[list[tuple[str, int]]] | None = None, scale: float = 1.0, output_html: str | None = None, title: str = 'Carrier Tracks') → Figure

Draw carrier tracks as circular arcs that meet at physical contact points.

For each run of consecutive positions on the same gear, the arc runs from the physical contact point with the incoming gear to the physical contact point with the outgoing gear, following the gear’s rotation direction. Gear transfers happen exactly at the tangent point between gear circumferences – no jump lines.

Parameters:
  • machine – The machine to visualise.

  • tracks – Precomputed tracks (computed if None).

  • scale – Layout scale.

  • output_html – If given, write figure to this HTML file path.

  • title – Figure title.

Returns:

Plotly Figure.

braidpy.horn_gear.visualization.animate(machine: BraidingMachine, n_steps: int | None = None, carrier_positions: dict | None = None, scale: float = 1.0, output_html: str | None = None, title: str = 'Carrier Animation', frame_duration_ms: int = 40, n_substeps: int = 9, max_frames: int = 900) → Figure

Animate carriers with smooth gear rotation between simulation steps.

By default the animation runs for exactly one cycle of the machine — the point at which every carrier is back at the place it set off from, with the drive in its starting phase (state_period()) — so the last frame hands straight back to the first and the page written by output_html plays it round and round. That is a good deal shorter than a carrier’s whole journey: the machine comes back long before any one carrier has been everywhere its track goes.

Each simulation step is split into n_substeps intermediate frames. Carrier and tick-mark positions are interpolated so a 4-slot gear shows a smooth 90° (quarter-turn) rotation per step.

Parameters:
  • machine – The machine definition.

  • n_steps – Number of simulation steps to animate. One full cycle if None, falling back to the drive’s own period for a programmed machine, whose carriers need never come back at all.

  • carrier_positions – Optional initial carrier placement.

  • scale – Layout scale.

  • output_html – If given, write figure to this HTML file path.

  • title – Figure title.

  • frame_duration_ms – Duration of each sub-frame in ms.

  • n_substeps – Intermediate frames per simulation step.

  • max_frames – Frame budget. A long cycle gets fewer sub-frames per step rather than a page too big to open.

Returns:

Plotly Figure with animation frames.

horn_gear/examples.py

Classic braiding machine configurations as factory functions.

Each function returns a ready-to-use BraidingMachine, written as its graph (machine_from_graph()): the gears that mesh and where it feeds axial yarns. Each loads itself. braidpy.machine_catalog lists the braids they make.

References

  • Brunnschweiler, D. (1953). “Horn Gear Mechanism of Braiding Machines.”

  • Kyosev, Y. (2014). “Braiding Technology for Textiles.”

braidpy.horn_gear.examples.flat_braid_3() → BraidingMachine

The simplest machine there is: 2 gears of 3 slots, 3 carriers.

Layout:

[A(3)] -- [B(3)]

This is the smallest configuration that still braids, and the easiest one to read in the animation. Six slots hold three carriers; each rides its gear for three steps, hands over at the single contact, rides the other gear for three steps and comes back, so the whole machine repeats every 6 steps. Three strands shuttling between two points is the ordinary three-strand plait.

Both gears have a single connection, so their one contact can always be placed exactly on a slot — the layout is exact.

Returns:

BraidingMachine for a 2-gear, 3-carrier flat braid.

braidpy.horn_gear.examples.flat_braid_4(n_slots: int = 4) → BraidingMachine

Flat braid: 2 gears in a row, turning in opposite directions.

Layout:

[A] -- [B]

Carriers shuttle between the two gears through the single contact. Half the slots can be loaded, so the machine carries n_slots carriers. See flat_braid_3() for the smallest useful case.

Parameters:

n_slots – Number of slots per gear (= number of carriers).

Returns:

BraidingMachine for a 2-gear flat braid.

braidpy.horn_gear.examples.soutache_braid(n_slots: int = 5) → BraidingMachine

Soutache: the narrow flat braid used for trimming and in jewellery.

Layout:

[A(5)] -- [B(5)]

Two gears carrying the same odd number of slots, loaded every other slot, which gives n_slots carriers. The odd count is what makes the braid narrow and even: a carrier returning from one gear comes back on the opposite strand, so every slot lies on its own two-position track and the whole machine repeats in 2 x n_slots steps.

Both gears have a single connection, so their slots sit exactly on their one contact whatever the count — the layout is always exact.

Soutache carries two cords, one fed up the spindle of each gear, and the carriers braid around both as they pass between them. They are Axial columns: they never ride a horn, and each stands clear of the carriers by its gear’s radius. The two cords are what make soutache soutache — the braid closes over them and is held flat, rather than rounding up as an uncored braid would.

Parameters:

n_slots – Slots per gear. Odd values give the classic soutache.

Returns:

BraidingMachine for a 2-gear soutache braid with two cords.

braidpy.horn_gear.examples.princess_braid() → BraidingMachine

Princess braid: 3 gears, 5/6/5 slots, 8 carriers over a cord.

Layout:

           cord
            ↓
[A(5)] -- [B(6)] -- [C(5)]

The classic princess arrangement: two 5-slot end gears either side of a 6-slot centre gear, sixteen slots carrying eight carriers on a single track, so every carrier eventually occupies every slot and the braid is fully interlinked.

Unlike soutache_braid(), this machine has a gear in the middle, so its cord can be fed up that gear’s spindle and stands clear of the carriers by a full gear radius. The cord is an Axial: it never rides a horn, and the carriers braid around it as they pass between the end gears.

The end gears have one connection each, so their 5 slots sit exactly on their contacts; the centre gear’s two contacts are 180° apart, which is three of its six slots. The layout is exact.

Returns:

BraidingMachine for a 3-gear princess braid with a cord core.

braidpy.horn_gear.examples.flat_braid_9(n_end: int = 5) → BraidingMachine

9-carrier flat braid: 4 gears in a row, turnaround gears at each end.

Layout:

[A(5)] -- [B(4)] -- [C(4)] -- [D(5)]

The end gears have only one connection each, so their slot count is free: that single contact can always be put exactly on a slot whatever it is. The interior gears sit between two neighbours on a straight line, 180° apart, which is a whole number of slots for a 4-slot gear. Every variant is therefore geometrically exact.

What n_end changes is how the carrier paths join up. A carrier entering an end gear rides round it and leaves by the same contact it arrived through, so an odd n_end brings it back on the opposite strand and fuses the machine into one closed track over every slot, while an even n_end returns it to its own strand and leaves separate tracks that never exchange carriers:

n_end

slots

tracks

carriers

load

period

3

14

1

7

50%

84

4

16

4

4

25%

16

5

18

1

9

50%

180

6

20

2

10

50%

60

7

22

1

11

50%

308

8

24

8

8

33%

24

9

26

1

13

50%

468

Odd values always reach 50% loading — the ceiling, since only one of the two slots meeting at a contact may be occupied — at the cost of a much longer period. Even values can fall short: 4 and 8 share a factor with the 4-slot interior gears, which fragments the machine into many short tracks and strands slots that cannot be filled. These are true maxima, not the best a search happened to find: load_carriers solves loading exactly.

Parameters:

n_end – Slot count of the two end gears. Odd gives one combined track, even gives several separate ones.

Returns:

BraidingMachine for a 4-gear flat braid.

braidpy.horn_gear.examples.tubular_braid_8() → BraidingMachine

Classic 8-carrier tubular braid: 4 gears in a ring.

Layout:

   [A]
  /   \
[D]   [B]
  \   /
   [C]

All gears have 4 slots; rotations alternate around the ring.

Four equal circles in a ring meet at contacts 90° apart on each gear, which is exactly one 4-slot pitch, so each gear’s two contact slots are side by side: carriers then sweep in step with the gear instead of drifting against it.

Returns:

BraidingMachine for a 4-gear ring braid.

braidpy.horn_gear.examples.tubular_braid_12() → BraidingMachine

12-carrier tubular braid: 6 gears in a hexagonal ring.

Each gear has 4 slots; gears alternate direction around the ring. Produces the classic 12-carrier tubular braid.

Returns:

BraidingMachine for a 6-gear hexagonal ring braid.

braidpy.horn_gear.examples.tubular_braid_16() → BraidingMachine

16-carrier tubular braid: 8 gears in a ring.

Each gear has 4 slots; gears alternate direction around the ring. This produces the classic tubular braid with 16 carriers.

Returns:

BraidingMachine for an 8-gear ring braid.

braidpy.horn_gear.examples.triaxial_braid_16() → BraidingMachine

16-carrier triaxial braid: the tubular braid of 16, round 8 axial yarns.

A triaxial braid lays a third set of yarns along the braid, at 0°, between the two sets braided at ±θ: they stiffen it along its length and hold its diameter, which is why braided composites are made so. On a maypole braider each axial yarn is fed up through a hollow horn gear spindle (van Ravenhorst’s thesis, see the references page): it stands still at that gear’s centre while the gear’s carriers go round it, those of one set passing it on the inside of the braid and those of the other on the outside, so that it lies between them.

So this is tubular_braid_16(), unchanged, with an Axial up each of its eight gears.

Returns:

BraidingMachine for an 8-gear ring braid with an axial yarn up each gear.

braidpy.horn_gear.examples.diamond_braid() → BraidingMachine

Diamond / square braid — the same machine as tubular_braid_8().

Drawing the four gears as a 2×2 grid rather than a ring suggests a different machine, but it is not one. Both are a 4-cycle of 4-slot gears with alternating rotations, and they are isomorphic with slot counts and directions respected (A→A, C→B, D→C, B→D): 16 slots, 8 carriers, four 4-position tracks, period 8. So this delegates rather than restating the same gears and connections in a different order.

The braiding terms diamond (1/1 intersection) and square or regular (2/2) name different interlacings of this one machine, not different machines. Telling them apart needs which yarn crosses over which, which the simulator does not compute yet — see the axial/interlacing note in Axial.

Returns:

BraidingMachine for a 4-gear ring braid.

braidpy.horn_gear.examples.mixed_gear_machine() → BraidingMachine

Example machine mixing 4-slot and 6-slot gears.

Layout:

[A(6)] -- [B(4)] -- [C(6)]

Demonstrates heterogeneous gear support.

Returns:

BraidingMachine with mixed slot counts.

The braids horn gear braiding machines make, and the Jacquard lace machines (braidpy.horn_gear.jacquard), as every catalogue lists its braids (braidpy.catalog).

A horn gear machine is one of braidpy.horn_gear.examples, written there as its graph, as a machine of your own is (machine_from_graph()). The machines that braid several bands at once are built by braidpy.horn_gear.multiband, as their line folds round and their bands’ colours are more than a graph says yet.

Listing them loads nothing: a machine is only made, and the simulator and networkx with it, when it is asked for.

class braidpy.machine_catalog.LaceRing(n_gears: int, steps: tuple[tuple[tuple[bool, ...], tuple[bool, ...]], ...], threaded: tuple[int, ...] | None = None)

Bases: object

A lace machine as data: its gears, its card — per step, whether each gear turns anticlockwise, then clockwise — and the notches threaded, every one if None. Listed without making the machine, which needs networkx.

n_gears: int
steps: tuple[tuple[tuple[bool, ...], tuple[bool, ...]], ...]
threaded: tuple[int, ...] | None = None
machine() → BraidingMachine

The machine, its gears driven by the card.

A braid as neighbours swapping places round a ring: the step between a braid and the ways of making it.

A braid word, a kumihimo disk, a lace machine: each makes a braid by moving strands round a ring of places, two neighbours at a time. A RingProgram says so once, for all of them: the places, which strand starts where — a place may be empty — and rows of swaps, each two neighbouring places exchanging what they hold, the swaps of a row sharing no place so that they are made at once. A braid becomes a ring program (from_braid()), and a ring program becomes each way of making it; read back as a braid (RingProgram.braid()), each must be the braid it was made from, as braidpy compares braids: by their topology, their patterns alike (braidpy.braid_pattern.alike()).

Conventions. The ring is seen from above, from the side the braider works from on a kumihimo disk, and the braid is made downwards, away from the eye, as it hangs below a disk. Places are numbered 0 to n - 1 clockwise, the seam between the last and place 0. A swap of place p exchanges what places p and p + 1 hold:

  • two strands make a crossing. At a positive swap, +1, the strand at p + 1 goes first, anticlockwise, lifted over the one at p — over as seen from above, so passing inside it, nearer the braid’s axis — and the strand at p then moves clockwise into the place it left. At a negative swap, -1, the strand at p goes first, clockwise, over the one at p + 1. With the strands at places 1 to n, counted from the seam, the positive swap of place i - 1 is σᵢ, the negative one σᵢ⁻¹: the disk’s own reading (disk_annular_word()) reads them back so;

  • a strand and an empty place make no crossing: the strand moves on by one place, to the empty one, and the swap’s sign changes nothing;

  • two empty places: nothing moves.

The ring has a seam, between its last place and its first. Strands carried across it twist the braid below them, as carriers going round a tubular braiding machine do: every strand once round the ring is a full twist. That is still a braid, and often a shorter way to make one; but a braid word has its strands in a row from the seam, so the ways made from a word keep them off it for now, and make that very word. Shorter programs, going over the seam, are for later.

class braidpy.ring_program.RingProgram(n_places: int, start: tuple[int | None, ...], rows: tuple[tuple[Swap, ...], ...])

Bases: object

A braid as neighbours swapping places round a ring; see the module.

Parameters:
  • n_places – Places round the ring.

  • start – The strand at each place to begin with, 0 to n - 1, or None where a place is empty.

  • rows – The swaps, row after row; the swaps of a row share no place.

Raises:

ValueError – If a strand is missing or placed twice, a swap is off the ring or has no sign, or two swaps of a row share a place.

n_places: int
start: tuple[int | None, ...]
rows: tuple[tuple[Swap, ...], ...]
property n_strands: int

How many strands the ring holds.

swaps() → list[Swap]

Every swap, row after row.

disk() → tuple[dict[Hashable, int], list[dict[Hashable, int]]]

The program as a disk’s moves: each strand’s slot, 1-based, and per step, the one strand that moves and by how much — as disk_annular_word() and Braid Studio take them. A swap is the lifted strand moved over its neighbour, then the neighbour moved into the place it left.

Returns:

The start and the steps.

ring_word() → tuple[list[int], int]

The braid the program makes as moves round its ring (braidpy.annulus_braid), read off its disk moves, as a disk braid is: a strand carried across the seam is a turn. Round a core (cored_word()), it says how far round each strand goes.

Returns:

The moves, and how many strands.

braid() → Braid

The braid the program makes, as a braid word: its ring word (ring_word()), the middle filled.

Returns:

The braid, on the program’s strands.

ends() → tuple[int | None, ...]

The strand at each place once the program is done.

class braidpy.ring_program.Swap(place: int, sign: int)

Bases: object

Two neighbouring places exchanging what they hold: a crossing if both hold a strand, a strand moved on by one place if one is empty. See the module for which way round.

Parameters:
  • place – The place p, 0-based; it swaps with place p + 1, clockwise from it seen from above, the last place with place 0.

  • sign – The crossing’s sign, if two strands cross: +1 when the strand at p + 1 is lifted over the one at p, -1 when the one at p is lifted over the one at p + 1. It changes nothing when a place is empty.

place: int
sign: int
braidpy.ring_program.from_braid(braid: Braid, n_places: int | None = None, offset: int = 0) → RingProgram

A braid as a ring program: its strands side by side from place offset, each crossing σᵢ^±1 the strands at places offset + i - 1 and offset + i swapping, packed into rows.

Parameters:
  • braid – The braid.

  • n_places – Places round the ring; as many as strands if None.

  • offset – The place of the first strand. The strands stay clear of the seam, so offset + n_strands is at most n_places.

Returns:

The program; RingProgram.braid() is the braid exactly, its crossings in another order only where they commute.

Raises:

ValueError – If the strands do not fit between the seam and itself.

braidpy.ring_program.same_braid(a: Braid, b: Braid) → bool

Whether two braids make alike patterns: the name braidpy.braid_pattern.alike() had, kept.

Parameters:
  • a – A braid.

  • b – Another.

Returns:

True if nothing measured tells them apart.

How to make a braid, by hand or on a machine: each through a RingProgram, and each checked by reading the braid back off what it made. See docs/source/making.md.

braidpy.making.for_page(info: Mapping[str, Any]) → dict[str, Any]

What Braid Studio shows of the other ways of making the braid it made: its repeating unit as moves on a kumihimo disk, and as a lace machine’s punchcard. Ashley’s stand is searched for only when asked (sinnet_for_page()).

Parameters:

info – What braidpy.web.build() said of the braid.

Returns:

Braid Studio’s description of the disk braid, and the moves; lace: the card, the gears, how the bobbins are threaded and Braid Studio’s description of the lace machine, and whether it makes the braid as a tube — for a braid made round a core, its strands going round across the ring’s seam, its card’s unit the shortest stretch that, repeated, makes it (_tube_card()). Empty for a braid with no braid word, or too long.

Return type:

disk

braidpy.making.sinnet_for_page(info: Mapping[str, Any], time_limit_s: float = 3.0) → dict[str, Any]

A sinnet on Ashley’s stand making the braid Braid Studio made, as the page shows it: searched for, for at most time_limit_s seconds.

Parameters:
Returns:

the sinnet, as Braid Studio makes it, or None if none was found, exact then being the braid made one strand per space (ashley_moves()), which always makes it; complete, whether every sinnet of up to as many spaces as strands was tried; tried, how many were.

Return type:

spec

A braid as moves on a kumihimo disk (a mobidai).

A mobidai’s move takes one strand from a slot to another, the short way round, lifted over every strand it passes (braidpy.mobidai). The strands are kept two slots apart — strand k from slot 2k + 3 — so that every strand has an empty slot either side of it, and each crossing is three moves:

  • one of the two strands crossing is lifted over the other, and over every strand between them, into the empty slot beyond it;

  • the other moves into the place it left;

  • the lifted strand settles into the other’s old place.

Every strand is then back two slots from the next, and the disk ready for the next crossing. The two strands need not be neighbours: a band letter a_ts (braidpy.band_canonical_form), strands t and s crossing in front of those between, is three moves however far apart they are, where in crossings of neighbours it is 2(t - s) - 1 of them. The braid is made in band letters where that takes fewer — a disk braid, its strands carried across the disk: Kongo gumi’s 81 crossings, 243 moves so, are 43 letters, 129 moves — and as its ring program’s crossings of neighbours (braidpy.ring_program) where not, as a machine’s braid. A 32-slot disk takes up to 15 strands this way. None passes the seam between the last slot and the first: that would twist the braid, which is still a braid and can be shorter to make, but from a braid word the strands are in a row, and keeping them so makes the word itself. Shorter moves, over the seam, are for later.

disk_braid() reads the braid back as braidpy reads any mobidai’s (mobidai_steps()).

class braidpy.making.disk.DiskMoves(n_slots: int, slots: tuple[int, ...], moves: tuple[tuple[int, int], ...])

Bases: object

A braid as a kumihimo disk makes it.

Parameters:
  • n_slots – Slots round the disk.

  • slots – The slot each strand starts in, 1-based.

  • moves – The moves, each from a slot to another, the short way round.

n_slots: int
slots: tuple[int, ...]
moves: tuple[tuple[int, int], ...]
config()

The disk as braidpy’s mobidai describes it.

Returns:

A MobidaiConfig, one cycle being the whole braid.

text() → str

The moves as a braider writes them: from>to, in order.

spec() → dict[str, Any]

The disk as Braid Studio makes your own disk braid (braidpy.web.build()), once through.

braidpy.making.disk.disk_braid(moves: DiskMoves) → Braid

The braid a disk’s moves make, read as braidpy reads any mobidai.

Parameters:

moves – The moves.

Returns:

The braid.

braidpy.making.disk.disk_moves(braid: Braid, n_slots: int = 32) → DiskMoves

A braid as moves on a kumihimo disk; see the module.

Parameters:
  • braid – The braid.

  • n_slots – Slots round the disk.

Returns:

The moves. disk_braid() reads back the same braid, exactly.

Raises:

ValueError – If the disk has too few slots for the strands, two apart with room either side.

A braid as a punchcard for the Jacquard lace machine.

braidpy’s lace machine (jacquard_lace_ring()) is a ring of 2-slot gears. A bobbin sits in a notch, cut where two neighbouring gears overlap — notch k between gears k and k + 1 — and a gear’s half turn swaps the bobbins of its two notches: gear g, notches g - 1 and g. The notches are a ring of places, and a half turn a swap of neighbours (RingProgram).

A gear always turns the same way, and neighbours turn opposite ways, so which bobbin passes over is fixed by where the crossing is made: a gear turning anticlockwise (an even one) makes a positive crossing, one turning clockwise a negative one. A braid word does not care: its crossings may come with any signs, anywhere. So the ring has notches to spare, and before each crossing its two strands are brought, through the empty notches between and beside them, to two notches whose gear turns the way of the crossing’s sign, crossing nobody; only those two move, and only if they must. Where both are hemmed in, the strands beside are pushed along towards the nearest empty notch. The strands keep their order and keep off the ring’s seam, as the strands of a word do (braidpy.ring_program); and they end in the notches they began in, since a punchcard is run round and round.

Spare notches cost gears but save steps: with one, every strand between a pair and the spare notch must move for each sign that does not suit; with one beside each strand, only the pair does. Where the strands begin matters as much: begun a notch along, the plait’s crossings all fall on gears of their signs. So the strands are tried packed together from every notch, spread a notch apart and spread evenly (_starts()), on as many gears as are given or on each number from the fewest to MOST_GEARS_PER_STRAND a strand; then searched, a few hundred tries seeded: the crossings in other orders where they commute (_reordered()), the strands begun anywhere, a crossing at times at the next nearest gear of its sign. The card of fewest steps is kept, of fewest gears if two tie. A word shortened first (braidpy.braid.Braid.shortened()) has fewer crossings to make, and so fewer moves: Braid Studio shortens it so.

A step of the card is two lines over the gears, as the machine reads it: the gears to turn anticlockwise, then those to turn clockwise. The swaps of a ring program’s row share no notch, so their gears never touch, and a row is a step: each swap is made in the first step after the last that used either of its notches, so that moves of strands apart are made at once.

lace_braid() reads the braid back off the machine: the punchcard is run (simulate()), after each step each bobbin is found in its notch, and each gear that turned swapped the two — the machine’s own motion, with each crossing the sign of the gear’s turn.

class braidpy.making.lace.CardSearch(tried_crossings: int = 100000, runs: int = 300, crossings: int = 30000, gears: int = 3, reordered: float = 0.7, anywhere: float = 0.3, next_nearest: float = 0.2, seed: int = 0)

Bases: object

How lace_card() searches for a card of fewer steps: first each way of beginning the strands on each number of gears, then tries of the crossings in other orders, the strands begun anywhere, a crossing at times at the next nearest gear of its sign. Seeded, so that a braid always has the same card.

Parameters:
  • tried_crossings – Crossings made at most in trying each way of beginning the strands: every so many ways, if they are more.

  • runs – Tries at most, after.

  • crossings – Crossings made at most in those tries: together, a second or two in a browser.

  • gears – How many numbers of gears are tried, those of the best cards found before.

  • reordered – How often a try takes the crossings in another order.

  • anywhere – How often a try begins the strands anywhere.

  • next_nearest – How often a crossing goes to the next nearest gear of its sign.

  • seed – The tries’ seed.

tried_crossings: int = 100000
runs: int = 300
crossings: int = 30000
gears: int = 3
reordered: float = 0.7
anywhere: float = 0.3
next_nearest: float = 0.2
seed: int = 0
class braidpy.making.lace.ConjugateSearch(tries: int = 3000, crossings: int = 300000, warm: float = 1.0, cooling: float = 0.999, cold: float = 0.05, seed: int = 0)

Bases: object

How card_conjugate() searches for a conjugate of fewer steps: rewrites tried, each kept if it lowers the floor a repeat, or now and then if it raises it, the more rarely as the search cools. Seeded.

Parameters:
  • tries – Rewrites tried at most, a hundredth of a second each on the book’s sinnets.

  • crossings – Crossings counted at most, each try counting three times the word’s: a second or two in a browser.

  • warm – The temperature it begins at, in steps of the floor.

  • cooling – What the temperature is multiplied by, each try.

  • cold – The temperature it cools to, and no further.

  • seed – The tries’ seed.

tries: int = 3000
crossings: int = 300000
warm: float = 1.0
cooling: float = 0.999
cold: float = 0.05
seed: int = 0
class braidpy.making.lace.LaceCard(n_gears: int, steps: tuple[tuple[tuple[bool, ...], tuple[bool, ...]], ...], bobbins: tuple[int | None, ...], program: RingProgram)

Bases: object

A punchcard for the lace machine, and how to thread it.

Parameters:
  • n_gears – Gears round the ring.

  • steps – Per step, the two lines of the card: per gear, whether it turns anticlockwise, then whether it turns clockwise.

  • bobbins – The strand in each notch to begin with, or None.

  • program – The same as a ring program, places being notches.

n_gears: int
steps: tuple[tuple[tuple[bool, ...], tuple[bool, ...]], ...]
bobbins: tuple[int | None, ...]
program: RingProgram
machine()

The lace machine, its gears driven by this card.

Returns:

A JacquardLaceMachine.

threaded() → list[int]

The notches threaded, strand after strand.

threading() → dict[int, tuple[str, int]]

Where each strand’s bobbin goes, as the machine numbers its slots.

Returns:

Strand → (gear, slot) of its notch.

notches() → list[str]

The notches to put a bobbin in, named by the two gears that cut each — “A-B” — as the lace ring names its contacts; worked out without building the machine, which needs networkx.

Returns:

The notches threaded, strand after strand.

text() → str

The card as it is punched: see punchcard_text().

spec(cycles: int = 1) → dict[str, Any]

The card as Braid Studio makes your own lace machine (braidpy.web.build()): its gears, the card as typed and the bobbins in their notches.

Parameters:

cycles – Passes of the card.

Returns:

The description, as the page writes it in its address.

braidpy.making.lace.card_conjugate(braid: Braid, search: ConjugateSearch = ConjugateSearch(tries=3000, crossings=300000, warm=1.0, cooling=0.999, cold=0.05, seed=0)) → Braid

A conjugate of a braid whose repeats a lace card makes in fewer steps: the same braid, once repeated, seen another way.

The word is read round, as a card runs it, and rewritten by the braid relations (braidpy.shortening), wherever the word is cut: crossings of strands apart swapped, three crossings of three strands made the other way round. Reading it from elsewhere conjugates it, and a relation keeps it, so each word met is a conjugate. A rewrite that lowers the floor a repeat (repeat_floor()) is kept, one that raises it now and then, less and less often, so as to cross what does not change it. Seeded, so a braid always has the same conjugate. The book’s sinnets, written as cascades of one strand crossing many, come out with a floor a third of theirs or less.

Parameters:
  • braid – The braid.

  • search – How the conjugate is searched for.

Returns:

the braid if none is lower.

Return type:

The conjugate of lowest floor found

braidpy.making.lace.card_names(steps: Sequence[tuple[Sequence[bool], Sequence[bool]]]) → str

A lace machine’s card by the gears each step turns, as a link writes it and Braid Studio takes it: a step after another, / between, its gears by name, - for none. A gear always turns its own way, so the names say which line of the step each is on: A, C, E… anticlockwise, first; B, D, F… clockwise, after. Far shorter than its digits (card_digits()), mostly 0.

Parameters:

steps – Per step, whether each gear turns anticlockwise, then clockwise.

Returns:

The card.

braidpy.making.lace.gear_name(gear: int) → str

A lace ring’s gear by name, as its card and its notches name it: A to Z, then AA, AB… as a spreadsheet names its columns.

Parameters:

gear – The gear, from 0.

Returns:

Its name.

braidpy.making.lace.gear_number(name: str) → int

The gear a name names (gear_name()), from 0, whatever its case.

Parameters:

name – The name.

Returns:

The gear.

Raises:

ValueError – If the name is not letters.

braidpy.making.lace.lace_braid(card: LaceCard) → Braid

The braid a punchcard makes on the lace machine, read off the machine itself (ring_braid()), threaded as the card says.

Parameters:

card – The card, and its threading.

Returns:

The braid.

braidpy.making.lace.lace_card(braid: Braid, n_gears: int | None = None, search: CardSearch = CardSearch(tried_crossings=100000, runs=300, crossings=30000, gears=3, reordered=0.7, anywhere=0.3, next_nearest=0.2, seed=0)) → LaceCard

A braid as a lace machine’s punchcard of as few steps as are found; see the module.

Parameters:
  • braid – The braid.

  • n_gears – Gears round the ring: even, at least FEWEST_GEARS, and more than the strands, a notch being spare. If None, each number from the fewest that do to MOST_GEARS_PER_STRAND a strand is tried.

  • search – How the card is searched for.

Returns:

The card. lace_braid() reads back the same braid, exactly.

Raises:

ValueError – If n_gears cannot hold the strands with a notch to spare, or is odd or below FEWEST_GEARS.

braidpy.making.lace.punchcard_text(steps: Sequence[tuple[Sequence[bool], Sequence[bool]]]) → str

A lace machine’s card as it is punched and as the machine’s animation draws it (animate()): a column per gear, ● punched and ○ not, two lines per step read downwards — the anticlockwise line ↺, then the clockwise line ↻, half a punch to its right, as it is driven half a step later.

Parameters:

steps – Per step, whether each gear turns anticlockwise, then clockwise.

Returns:

The card, the gears named along the top (gear_name()), a column as wide as the longest name: AA and on, past 26 gears.

braidpy.making.lace.read_card(text: str, n_gears: int) → list[tuple[tuple[bool, ...], tuple[bool, ...]]]

A card as it is typed: by the gears each step turns (card_names()), or as digits (card_digits()), groups of 0 and 1, a digit a gear, taken two by two — the gears turning anticlockwise, then clockwise — however the steps are laid out on lines.

Parameters:
  • text – The card.

  • n_gears – Gears round the ring.

Returns:

Per step, whether each gear turns anticlockwise, then clockwise.

Raises:

ValueError – If a group is not of 0 and 1, a digit a gear, or the groups do not make whole steps; or a gear named is not on the ring.

braidpy.making.lace.repeat_floor(word: Sequence[int], n_strands: int) → int

The fewest steps a repeat of a word can take on a card run round and round (step_floor()), once the repeats follow one another: what a third repeat adds to two. It does not depend on where the word is cut: every rotation of a word has the same.

Parameters:
  • word – The crossings of one repeat.

  • n_strands – The strands.

Returns:

The floor, in steps a repeat.

braidpy.making.lace.ring_braid(machine, threading: Mapping[int, tuple[str, int]] | None = None) → Braid

The braid one pass of a lace machine’s card makes, read off the machine itself: the card run, each bobbin found in its notch after each step, and the two bobbins of each gear that turned swapped — with the sign of that gear’s turn, + anticlockwise.

Parameters:
  • machine – A lace ring (jacquard_lace_ring()).

  • threading – Each bobbin’s place at the start, as (gear, slot); the machine’s own threading if None. Bobbins are the braid’s strands, numbered in the order they are given.

Returns:

The braid.

Raises:

RuntimeError – If a bobbin is found anywhere but where the card’s gears should have taken it.

braidpy.making.lace.ring_card(moves: Sequence[int], n_strands: int, n_gears: int | None = None, search: CardSearch = CardSearch(tried_crossings=100000, runs=300, crossings=30000, gears=3, reordered=0.7, anywhere=0.3, next_nearest=0.2, seed=0)) → LaceCard

A braid round a core, as a ring word, as a lace machine’s punchcard: a tube made as a tube.

lace_card() keeps its strands off the ring’s seam, as a braid word’s are in a row, and so makes a flat braid curled up; here they go round, across the seam as a tube’s do. A ring word’s moves (braidpy.annulus_braid) say which two neighbours round the ring cross, with which sign, and how far round each strand ends; the crossings are made as lace_card() makes them — the two strands brought through the empty notches between and beside them to a gear turning the way of the sign, the strands beside pushed along if hemmed in — but round the ring, and every strand then walks to where it ends, as many times round the ring as the word takes it. A pass of the card need not bring a strand home: the notches threaded are the same, each perhaps holding another strand, so the card runs round and round.

The same starts and the same seeded search are tried as for lace_card(), a crossing always at the nearest gear of its sign.

Parameters:
  • moves – Crossings ±1 to ±n_strands, turns ±(n_strands + 1).

  • n_strands – The strands round the ring.

  • n_gears – Gears round the ring, even and at least FEWEST_GEARS; each number from the fewest that hold the strands to MOST_GEARS_PER_STRAND a strand if None.

  • search – How the card is searched for.

Returns:

made, its braid round the ring’s core is the word’s (cored_word()).

Return type:

The card

Raises:

ValueError – If no card is found: the strands fill the ring, and its gears do not turn the ways the crossings want.

braidpy.making.lace.step_floor(word: Sequence[int], n_strands: int) → int

The fewest steps any card for a word can take, on any lace ring: no fewer than its longest chain of crossings each waiting for the last, a crossing waiting a step more when a strand of it crossed last the same way with the same sign. Neighbouring gears turn opposite ways, so its two gears are of the same way, a notch apart: it must move a notch between. On the small braids of the catalogue, the fewest steps there are, found by trying every turn of every gear, are this or a few more.

Parameters:
  • word – The crossings, i for σᵢ and -i for σᵢ⁻¹.

  • n_strands – The strands.

Returns:

The floor, in steps.

A braid as a sinnet on Ashley’s stand, found by searching.

On Ashley’s stand (braidpy.ashley_solid_sinnet) the strands lie in spaces round the rim, and a move carries a strand from one space to another, over every strand it passes. A move is not a swap of neighbours, so a braid cannot be turned into moves crossing by crossing as for a disk or a lace machine: a sinnet that makes it is searched for instead.

The sinnets searched are made as the book’s are: every space gives a strand and receives one in each cycle, so a cycle’s moves follow a derangement of the spaces — no space to itself — and every space has its strands back after a cycle. Each candidate is the strands shared out among the spaces, the derangement, and the order of its moves. A cycle read from another move is the same braid, so the first move is taken from space 1.

A sinnet is found when its braid is the braid wanted, compared as every way of making a braid compares them: by their topology (alike()) — the braid repeated, read from any strand, however written. Fewer spaces are tried first, so the simplest sinnet is found first; the search stops at a time limit, and says whether it tried everything it could. Not every braid is a sinnet: when none is found, the nearest is given, and how far it is (distance()).

Every braid can be made on the stand, though, once its moves need not be a sinnet’s (ashley_moves()): one strand per space, with an empty space after each, and each crossing made in three or four moves through the empty spaces, every space holding what it held before. It is the braid itself, exactly, but no longer a sinnet of the book’s kind: spaces give and take strands unevenly, and a space can sit empty.

A sinnet can also be made from the shape it is to take, as the book draws it (sinnet_from_shape()): straight lines across the shape, parallel to its sides, each turning at the outline in a bight into the next. The bights are the spaces, the lines the moves, made in the book’s order. And the other way: a sinnet’s moves, grouped by the direction of their lines (move_groups()), are the same at any size for shapes drawn on one principle, and make its shape (shapes_from_moves()).

class braidpy.making.ashley.AshleySearch(sinnet: AshleySolidSinnet | None, nearest: AshleySolidSinnet | None, distance: float, tried: int, complete: bool)

Bases: object

What a search for a sinnet found.

Parameters:
  • sinnet – A sinnet making the braid; None if none was found.

  • nearest – The sinnet whose braid was nearest, found or not.

  • distance – How far its braid is from the one wanted: 0 if found.

  • tried – How many sinnets were tried.

  • complete – Whether every sinnet of up to the spaces allowed was tried, rather than the time running out.

sinnet: AshleySolidSinnet | None
nearest: AshleySolidSinnet | None
distance: float
tried: int
complete: bool
class braidpy.making.ashley.FoundShape(name: str, outline: tuple[tuple[float, float], ...], sinnet: AshleySolidSinnet, same_lines: bool, grid: str | None = None, shape: str | None = None, size: int | None = None, height: int | None = None, holes: tuple[tuple[tuple[float, float], ...], ...] = ())

Bases: object

A shape found for a sinnet’s moves (shapes_from_moves()).

Parameters:
  • name – What it is: “L, 5 by 2 on the square grid”, “regular”, “parallel-sided”.

  • outline – Its corners, anticlockwise, in spacings between lines.

  • sinnet – Its own sinnet (sinnet_from_shape()).

  • same_lines – Whether its drawing joins the very spaces the moves join, not only lines grouped alike.

  • grid – On a grid, which (GRIDS), and the shape, size and height grid_shape() makes it of; None, not on a grid.

  • shape – See grid.

  • size – See grid.

  • height – See grid.

  • holes – The corners of each hole in it.

name: str
outline: tuple[tuple[float, float], ...]
sinnet: AshleySolidSinnet
same_lines: bool
grid: str | None = None
shape: str | None = None
size: int | None = None
height: int | None = None
holes: tuple[tuple[tuple[float, float], ...], ...] = ()
class braidpy.making.ashley.MoveGroups(n_spaces: int, groups: tuple[tuple[Fraction, int], ...])

Bases: object

A sinnet’s moves grouped by the direction of their lines: what stays the same, whatever the size, for shapes drawn on the same principle (move_groups()).

Parameters:
  • n_spaces – The spaces round the stand.

  • groups – For each direction, its angle from the first, as a share of a half turn, and the moves made along it.

n_spaces: int
groups: tuple[tuple[Fraction, int], ...]
property angles: list[float]

Each direction’s angle from the first.

property lines: list[int]

The moves made along each direction.

property family: tuple[tuple[Fraction, Fraction], ...]

Each direction’s angle, and its moves as a share of the spaces: the same for a shape drawn on the same principle at any size, as every triangle of triangle() is, its three directions a third of a half turn apart, each with a third of the moves.

class braidpy.making.ashley.ShapeLine(ends: tuple[tuple[float, float], tuple[float, float]], direction: int)

Bases: object

A line of Ashley’s diagram, across the shape.

Parameters:
  • ends – Where it meets the outline, its two ends.

  • direction – Which way it runs: the index of the first side of the outline parallel to it.

ends: tuple[tuple[float, float], tuple[float, float]]
direction: int
braidpy.making.ashley.ashley_moves(braid: Braid) → AshleySolidSinnet

Any braid on Ashley’s stand, crossing by crossing; see the module.

The strands lie one per odd space, from space 1, each followed by an empty even space: 2n spaces for n strands. A strand moved from an odd space goes anticlockwise, from an even one clockwise, over every strand it passes. The two strands of σᵢ are in spaces a = 2(n - i) - 1 and b = a + 2, as the stand reads its strands the other way round, and the crossing is made through the empty spaces after them:

  • σᵢ: b to b + 1, b + 1 to a + 1, over the strand in a; then a to b and a + 1 back to a;

  • σᵢ⁻¹: a to b, over the strand there; then b (its earlier strand) to b + 1, and on to a.

Parameters:

braid – The braid.

Returns:

The strands and moves, as a sinnet whose one cycle is the braid, exactly.

braidpy.making.ashley.ashley_sinnet(braid: Braid, max_spaces: int = 6, time_limit_s: float = 20.0, spaces: Sequence[int] | None = None) → AshleySearch

A sinnet on Ashley’s stand that makes a braid; see the module.

Parameters:
  • braid – The braid wanted.

  • max_spaces – The most spaces round the rim to try.

  • time_limit_s – Seconds to search for, at most.

  • spaces – The numbers of spaces to try, in order; 2 to max_spaces if None.

Returns:

the sinnet found, or the nearest.

Return type:

The search

braidpy.making.ashley.cell_outline(grid: str, cell: tuple[int, ...]) → list[tuple[float, float]]

A cell’s corners, anticlockwise, in spacings.

braidpy.making.ashley.corner_spaces(outline: Sequence[tuple[float, float]], holes: Sequence[Sequence[tuple[float, float]]] = (), across: Sequence[float] | None = None, halfway: float | None = None) → list[int]

The spaces at a shape’s corners, where the book adds strands to sharpen its edges: each bight turning a corner, its two lines ending on two sides, and each bight alone on its side, as at the ends of a flat oblong. Spaces 1, 5 and 9 of a triangle of four lines a side (#3049), 1 and 7 of an oblong of 10 by 2 (#3072).

Parameters:
  • outline – The shape’s corners, anticlockwise, in spacings.

  • holes – The corners of each hole in it, clockwise.

  • across – The lines’ directions, if not the sides’ (shape_lines()).

  • halfway – The direction of lines halfway between the others’ crossings, if any (shape_lines()).

Returns:

The spaces, numbered as sinnet_from_shape() numbers them.

braidpy.making.ashley.grid_across(grid: str) → tuple[float, ...]

The directions of Ashley’s lines on a grid, as angles: across and up, a third of a half turn apart on the triangular grid, and across and two thirds of a half turn on the skewed grid, along its rhombs’ sides (and halfway between, grid_halfway()).

braidpy.making.ashley.grid_halfway(grid: str) → float | None

The direction of the lines a grid draws halfway between the others’ crossings (shape_lines()’s halfway): along its rhombs’ short diagonals on the skewed grid, a third of a half turn; None on the others.

braidpy.making.ashley.grid_lines(grid: str) → tuple[float, ...] | None

The directions to draw a grid’s shapes’ lines in (shape_lines()’s across): None where every side of the outline is parallel to some, as on the square and triangular grids, and the lines are drawn parallel to the sides; the grid’s own on the diagonal grid, whose outline may run on a slant.

braidpy.making.ashley.grid_outline(grid: str, cells: Sequence[tuple[int, ...]]) → list[list[tuple[float, float]]]

The outline of a shape made of a grid’s cells: round them, half a spacing beyond (FIRST_LINE), each side of it parallel to one of theirs; from its bottom left corner, as the book numbers the spaces. Three rows of triangles, three, two and one points across, are the book’s triangle of three lines a side (triangle()). Round a hole in them, half a spacing in from them, the outline of the hole: a hole as wide as a point of the grid left out, at least, or it closes up.

Parameters:
  • grid – One of GRIDS.

  • cells – The cells.

Returns:

The outline’s corners, anticlockwise, in spacings; then each hole’s, clockwise.

Raises:

ValueError – If the cells are not in one piece, or meet at a point only.

braidpy.making.ashley.grid_shape(grid: str, name: str, size: int, height: int) → list[tuple[int, ...]]

A shape to start from, as its cells on a grid.

Parameters:
  • grid – One of GRIDS.

  • name – On the square grid, “oblong”, size lines across and height up; “L” and “U”, size lines across and up, their arms height thick; “frame”, a hollow square, size lines across, its sides height thick. The same on the skewed grid, skewed: #3078 is an oblong of 3 by 5, a parallelogram. On the diagonal grid, a “square” or an “oblong” standing on a corner, size lines along its sides, and an oblong’s height across: #3073 is a square of 6, #3074 of 8, #3075 an oblong of 10 by 2. On the triangular grid, “triangle” or “hexagon”, size lines along each side.

  • size – Its size, in lines.

  • height – Its height, or its arms’ or sides’, in lines.

Returns:

Its cells.

braidpy.making.ashley.least_counts(moves: Sequence[tuple[int, int]], n_spaces: int) → list[int]

The fewest strands each space can start with so that none is ever left empty: two in a space that gives its strand before it is given one in the cycle, one in any other.

Parameters:
  • moves – The moves of a cycle, every space giving and receiving once.

  • n_spaces – How many spaces.

Returns:

The strands of each space, space 1 first.

braidpy.making.ashley.move_groups(moves: Sequence[tuple[int, int]]) → MoveGroups

A sinnet’s moves grouped by the direction of their lines (see MoveGroups).

Lines of one direction never cross. Where joining every two moves whose lines do not cross leaves sets in which none do, as across an oblong, those sets are the directions, taken as evenly spread (at right angles for two). Otherwise, as across a triangle, whose lines of different directions miss each other near its corners, the directions are found from the spaces’ numbers: round a stand of n spaces evenly spaced, the line from space a to space b runs at (a + b) π / n and a half turn, so moves whose spaces add up to the same number, modulo n, are parallel. Wherever the numbering starts, or whichever way it runs, the directions only turn together, and are kept turned as little as can be.

Parameters:

moves – The moves, each space giving and receiving once.

Returns:

The groups.

braidpy.making.ashley.oblong(width: int, height: int) → list[tuple[float, float]]

An oblong (a square if width == height), in spacings between lines, from its bottom left corner: height lines across it, width up it.

braidpy.making.ashley.regular_polygon(sides: int, lines_per_side: int) → list[tuple[float, float]]

A regular polygon of an odd number of sides standing on one, with so many lines parallel to each side, the farthest a spacing from the corner opposite, from its bottom left corner.

Parameters:
  • sides – Its sides, odd: with an even number they are parallel in pairs, a shape of _parallel_sided().

  • lines_per_side – Lines parallel to each side.

Returns:

Its corners, anticlockwise, in spacings between lines.

braidpy.making.ashley.shape_diagram(outline: Sequence[tuple[float, float]], holes: Sequence[Sequence[tuple[float, float]]] = (), across: Sequence[float] | None = None, halfway: float | None = None) → tuple[list[ShapeLine], list[tuple[int, int]], list[tuple[float, float]]]

Ashley’s diagram of a shape: its lines (shape_lines()), the two spaces each joins, and where each bight is, space 1 first (sinnet_from_shape()).

Parameters:
  • outline – The shape’s corners, anticlockwise, in spacings.

  • holes – The corners of each hole in it, clockwise.

  • across – The lines’ directions, if not the sides’ (shape_lines()).

  • halfway – The direction of lines halfway between the others’ crossings, if any (shape_lines()).

Returns:

The lines, the spaces each joins, and the bights.

braidpy.making.ashley.shape_lines(outline: Sequence[tuple[float, float]], holes: Sequence[Sequence[tuple[float, float]]] = (), across: Sequence[float] | None = None, halfway: float | None = None) → list[ShapeLine]

The lines Ashley draws across a shape: parallel to each side, the first FIRST_LINE in from it, the others a spacing on, as many as fit strictly inside. Parallel sides share their lines. Where the outline turns back, as round the arms of an L or a U, or round a hole, a line is cut in pieces, each a line of its own. With halfway, a third way too, halfway between the crossings of the other two (_halfway_lines()), as in #3078.

Parameters:
  • outline – The shape’s corners, anticlockwise, in spacings: any outline that does not cross itself.

  • holes – The corners of each hole in it, clockwise.

  • across – Directions, as angles, to draw the lines in instead, a spacing apart through the origin, as on a grid whose outline may run on a slant (grid_lines()); none if None.

  • halfway – The direction, as an angle, of lines drawn halfway between the crossings of the others, which run two ways (grid_halfway()); none if None.

Returns:

The lines, by direction, then from the side inwards; those halfway last.

braidpy.making.ashley.shape_tracks(moves: Sequence[tuple[int, int]]) → list[list[int]]

The tracks of a sinnet’s moves: the curves the book draws, each line turning at a bight into the next, the way the moves run. Every space giving once and receiving once, each move leads to the one from the space it ends in, and round to where it started.

Parameters:

moves – The moves of a cycle, every space giving and receiving once.

Returns:

Each track’s moves, by index, in the order they follow each other, the track with the first move first.

braidpy.making.ashley.shapes_from_moves(moves: Sequence[tuple[int, int]]) → list[FoundShape]

The shapes drawn on the principle of a sinnet’s moves, at its size.

On a grid (grid_shape()): the shapes with as many lines as there are moves, on the grids their groups (move_groups()) say, each kept if its own sinnet joins the same spaces. Off a grid, made from the groups: each direction of lines is a side, or a pair of parallel sides, of the shape, as far across as its moves need, a regular polygon of an odd number of sides (regular_polygon()) where the directions are evenly spread with as many moves each, and the shape with sides parallel in pairs; each kept if its own sinnet’s moves group alike.

Parameters:

moves – A sinnet’s moves, each space giving and receiving once.

Returns:

The shapes, those whose drawing joins the same spaces first; none if the moves are not drawn so.

braidpy.making.ashley.sinnet_from_shape(outline: Sequence[tuple[float, float]], extra: Sequence[int] | None = None, turned: Sequence[int] = (), order: str = 'book', holes: Sequence[Sequence[tuple[float, float]]] = (), across: Sequence[float] | None = None, halfway: float | None = None) → AshleySolidSinnet

The sinnet the book’s method makes of a shape.

Lines cross the shape parallel to its sides (shape_lines()), and at the outline each turns, in a bight, into the next: two lines meeting the outline at one point into each other, others into their neighbour on the same side. The bights are the spaces, numbered anticlockwise from the one nearest the first corner, and each line is a move between the two it joins.

The moves are made in the book’s order: from space 1, along the line across the first side if one starts there; then each from the space beside where the last ended, one back, then one on, and so on, along the line parallel to the last while there is one there, across the shape and back; a space that has given its strand gives none again, and its line is taken towards it. The moves of any track (shape_tracks()) may be made the other way round: every space still gives once and receives once. Each space starts with the fewest strands the order lets it (least_counts()), and any extra: the book adds strands at the corners of a shape to sharpen its edges.

Parameters:
  • outline – The shape’s corners, anticlockwise, in spacings between lines; the first is where the numbering starts, the book’s bottom left.

  • extra – Strands to add to each space, space 1 first; none if None.

  • turned – The tracks made the other way round, numbered from 1 as shape_tracks() lists them.

  • order – “book”, the book’s order; or “spaces”, space by space, as the book makes the moves where it cannot alternate them.

  • holes – The corners of each hole in the shape, clockwise: its bights are numbered with the outline’s, by the way they lie from the middle (shape_diagram()).

  • across – The lines’ directions, if not the sides’, as on the diagonal grid (shape_lines()).

  • halfway – The direction of lines halfway between the others’ crossings, as on the skewed grid (shape_lines()).

Returns:

The sinnet.

Raises:

ValueError – If the lines cannot be made into moves in that order.

braidpy.making.ashley.sinnet_spec(sinnet: AshleySolidSinnet, cycles: int = 4)

A sinnet as Braid Studio makes your own (braidpy.web.build()).

Parameters:
  • sinnet – The sinnet.

  • cycles – How many cycles to make.

Returns:

The description.

braidpy.making.ashley.triangle(lines_per_side: int) → list[tuple[float, float]]

A triangle standing on its base, as the book draws #3045, #3047 and #3051 (2, 4 and 6 lines a side): see regular_polygon().

A braid designed in braid3d, the 3D braid designer of craftdesignonline.com (see the references page), read from its file as a mobidai braid: the disk’s slots, where each yarn starts, and the moves of a cycle (CatalogedMobidai).

The file (.b3d) is URL-encoded JSON: each yarn’s colour, and the steps the braid was designed by, each a group of moves of yarns from one angle round the disk to another, or a repeat of earlier steps. web/b3d.js writes one for a braid made on the marudai here (write_b3d() writes any design’s JSON so, read_b3d() reads it). This needs only the standard library, so that Braid Studio can read a design in the browser too.

How a file is read:

  • Where the yarns start: the first list of where the yarns are that names each yarn once. braid3d, and braidpy after it, write with each step where the yarns are before it, the first step’s list left as it was by braid3d and where they start by braidpy: either way, that list is the start.

  • A step moves the yarns standing at its moves’ first angles, as braid3d does, each to its second angle, the short way round, one after another in the order given, but for a yarn going where another of the step is leaving, which waits for it to go, as a braider makes room.

  • A repeat first moves the yarns back to where the repeated steps found them, then plays those steps again, so many times. Moving them back must pass no yarn over another, which is checked: the yarns keep their order round the disk, only spaced otherwise. Its rotate turns the whole braid, which moves nothing against anything else and changes nothing here.

  • The disk: angles become the slots of a disk of as few slots as hold them all exactly; a design whose angles fall on no such disk is given as few as keep every yarn in its order round the disk and every move going the same way round. The braid is the same; only the spacing differs. A move of exactly half a turn, which the file cannot say the way round of, goes round as a mobidai’s does. braidpy writes a move of half a turn or more as two steps, each less than half a turn, so it is read going round as it went.

  • The cycle: a design that is one cycle and a repeat of it is that cycle, made as many times; any other is all its moves, made once.

class braidpy.b3d.Design(start: dict[int, float], colors: tuple[str, ...], prelude: tuple[Group, ...], cycle: tuple[Group, ...], times: int)

Bases: object

A braid3d design: where each yarn starts, in what colour, and the groups of moves made, a repeat played out.

Variables:
  • start (dict[int, float]) – Each yarn’s angle at the start.

  • colors (tuple[str, ...]) – Each yarn’s colour, as #rrggbb.

  • prelude (tuple[braidpy.b3d.Group, ...]) – The groups made before the cycle, once.

  • cycle (tuple[braidpy.b3d.Group, ...]) – The groups of a cycle.

  • times (int) – How many times the cycle is made.

start: dict[int, float]
colors: tuple[str, ...]
prelude: tuple[Group, ...]
cycle: tuple[Group, ...]
times: int
colours

An attribute under its old name, read and written as the new one.

Held by the class under the old name: color = renamed_attribute("colour").

Parameters:

new – The attribute’s new name.

classmethod read(text: str) → Design

The design a braid3d file holds.

Raises:

ValueError – If it holds none, or does what is not read here.

braidpy.b3d.mobidai_from_b3d(text: str, name: str = 'braid3d design', most_slots: int = 128) → tuple[CatalogedMobidai, int]

A braid3d design as a mobidai braid, and how many cycles make it.

Parameters:
  • text – The file’s text.

  • name – What to call it.

  • most_slots – The most slots its disk may have.

Returns:

The mobidai braid — its disk, where each yarn starts, in its colour, and a cycle’s moves — and how many cycles.

Raises:

ValueError – If the file holds no braid3d design, or one that does what is not read here.

braidpy.b3d.read_b3d(text: str) → dict[str, Any]

A braid3d file’s JSON, URL-encoded or not.

Raises:

ValueError – If it holds no braid3d design.

braidpy.b3d.write_b3d(data: dict[str, Any]) → str

A braid3d design’s JSON as its file holds it, URL-encoded (read_b3d() reads it back).

The shape of a braid

Laying braids in 3D, drawing them, and settling their yarns.

Strands as curves in space: a braid word laid as arcs from crossing to crossing (strand_paths()), sampled into points (sample_strands(), SampledStrand), and a strand as a function of its height (ParametricStrand).

braidpy.parametric_strand.make_arc(x_start: float, x_end: float, t_start: float, t_end: float, amplitude: float) → Callable[[float], tuple[float, float, float]]

Creates a sine-arc parametric function between two x-positions.

Parameters:
  • x_start (float) – Starting x position.

  • x_end (float) – Ending x position.

  • t_start (float) – Start time.

  • t_end (float) – End time.

  • amplitude (float) – Amplitude of the sine wave in the y-direction.

Returns:

A function that maps time t to a 3D point (x, y, z).

braidpy.parametric_strand.make_idle_arc(x: float, t_start: float, t_end: float) → Callable[[float], tuple[float, float, float]]

Creates a straight-line parametric function for idle strands.

Parameters:
  • x – Fixed x position.

  • t_start – Start time.

  • t_end – End time.

Returns:

A function that maps time t to a 3D point (x, 0.0, z).

braidpy.parametric_strand.combine_arcs(arcs: list[tuple[float, float, Callable[[float], tuple[float, float, float]]]]) → Callable[[float], tuple[float, float, float]]

Combines a list of arcs into a single time-dependent function.

Parameters:

arcs – A list of arcs represented as (t_start, t_end, function).

Returns:

A function from t to (x, y, z), switching arcs over time.

class braidpy.parametric_strand.ParametricStrand(func: Callable[[float], tuple])

Bases: object

A strand as a curve in space, a function of its height.

evaluate(t: float) → tuple[float, float, float]

Compute the strand position at time t (along z axis) :param t: time or z coordinates

Returns:

position of braid [x(t), y(t), t]

Return type:

tuple[float, float, float]

sample(n: StrictlyPositiveInt = 100) → list[tuple]

Return a list of sampled points for plotting

Parameters:

n (StrictlyPositiveInt) – number of samples

Returns:

list of 3D coordinates

Return type:

List[tuple]

braidpy.parametric_strand.LINEAR: tuple[float, ...] = (0.0, 1.0)

Straight from slot to slot, which is what make_arc does.

braidpy.parametric_strand.SMOOTHSTEP: tuple[float, ...] = (0.0, 0.0, 3.0, -2.0)

The cubic 3 tau^2 - 2 tau^3. Among transitions that leave and arrive parallel to the axis it is the one that minimises bending energy, so a strand drawn with it has no corner where a crossing begins or ends.

braidpy.parametric_strand.evaluate_profile(profile: tuple[float, ...], tau: float) → float

The profile at tau, by Horner’s rule.

Parameters:
  • profile – Polynomial coefficients, lowest power first.

  • tau – Position within the segment, 0 to 1.

Returns:

P(tau), which is 0 at the start of a segment and 1 at the end.

class braidpy.parametric_strand.StrandPath(slots: tuple[int, ...], signs: tuple[int, ...], spacing: float = 1.0, amplitude: float = 0.2, profile: tuple[float, ...] = (0.0, 1.0))

Bases: object

One strand’s path through a braid, segment by segment.

Unlike ParametricStrand, which is a closure, this keeps the braid’s own description of the strand — where it is and what it passed — so that exact things can be computed from it. One unit of z per generator, and it repeats.

Parameters:
  • slots – The slot it occupies at each of len(signs) + 1 instants.

  • signs – Per segment, +1 if it crosses over, -1 if under, 0 if it holds its slot.

  • spacing – Distance between neighbouring slots.

  • amplitude – How far off the axis a crossing strand rides.

  • profile – How it travels sideways; see LINEAR and SMOOTHSTEP.

slots: tuple[int, ...]
signs: tuple[int, ...]
spacing: float = 1.0
amplitude: float = 0.2
profile: tuple[float, ...] = (0.0, 1.0)
property length: int

The braid’s period along its axis, one unit per generator.

position(z: float) → tuple[float, float, float]

Where the strand is at z along the axis.

z is taken modulo the period, so a closed braid can be followed round as many times as wanted.

Parameters:

z – Distance along the braid axis.

Returns:

(x, y, z) — sideways, off-axis, and along.

to_parametric() → ParametricStrand

The same path as a ParametricStrand, on t in [0, 1].

So that everything already built on parametric strands — sampling, ParametricBraid and its plotting — works on this without knowing what it is.

braidpy.parametric_strand.strand_paths(braid, spacing: float = 1.0, amplitude: float = 0.2, profile: tuple[float, ...] = (0.0, 1.0)) → list[StrandPath]

The path of every strand of a braid.

Which strand of a crossing goes over is read from the generator’s sign, not from the direction it moves: a positive generator sends the strand coming from the lower slot over the top, and its inverse sends the one from the upper slot over instead. Both exchange the same pair, so a model that watched only the slots would make a braid and its inverse identical.

Parameters:
  • braid – A Braid.

  • spacing – Distance between neighbouring slots.

  • amplitude – How far off the axis a crossing strand rides.

  • profile – How a strand travels sideways within a segment.

Returns:

One StrandPath per strand, in strand order.

braidpy.parametric_strand.sample_strands(strands, per_unit: int = 20, rise: float = 1.0) → list[np.ndarray]

Strands as points along them, for whatever takes yarns as points.

Parameters:
  • strands – Anything answering position(z) over a common length: strand_paths(), say.

  • per_unit – Points per unit of z, one generator of a path.

  • rise – How far each unit of z rises: the braid stretched along its axis.

Returns:

Per strand, (points, 3), rising from z = 0.

class braidpy.parametric_strand.SampledStrand(points: np.ndarray)

Bases: object

A strand known by points along it, rising: a yarn laid or settled.

It answers position(z) as the other strands do, so a word can be read off it (braidpy.symmetric_braid.braid_word()) and its length measured (arc_length()).

Parameters:

points – (n, 3), rising strictly along z from its bottom end.

Raises:

ValueError – If the points do not rise all along: a strand that turns back down has no single place at some heights.

points: np.ndarray
property length: float

How far it rises, bottom end to top end.

position(z: float) → tuple[float, float, float]

Where it is z above its bottom end, between its points.

braidpy.parametric_strand.arc_length(strand, n_samples: int = 4000) → float

How long a strand is over a period, measured along the strand.

Compare it with the strand’s length, which is the distance the same period covers along the axis: the difference is what the braid costs in yarn over running straight. Works on anything that answers position(z) — a path, a series, a helix.

Parameters:
  • strand – The strand to measure.

  • n_samples – Segments to measure along. A sum of chords always understates a curve, so this converges from below.

Returns:

The length of one period.

braidpy.parametric_strand.transported_frame(points)

A frame carried along a centreline without spinning about it.

Two vectors square to the curve and to each other at every point, got by rolling the previous pair onto the new tangent — parallel transport. The obvious alternatives both misbehave:

  • the Frenet frame flips at an inflection, where the curve straightens and the normal is undefined, which creases a tube drawn on it;

  • recomputing a frame at each point from a fixed world axis, as the Cosserat animation’s create_circle does, leaves consecutive rings unaligned, so a tube built segment by segment does not join up — and it degenerates when the curve runs along that axis, which np.allclose(direction, [0, 0, 1]) catches going up and misses coming down.

The carried frame need not close up after a loop. For a tube of circular section in one colour that is invisible; for anything painted round the tube it is not.

Parameters:

points – The centreline, as a sequence of (x, y, z).

Returns:

(centre, normal, binormal) as arrays of one row per point.

braidpy.parametric_strand.tube_rings(points, radius: float, n_around: int = 16)

A ring of points round the centreline at every sample.

The shared half of drawing a strand as yarn: tube_mesh() reshapes this for a surface plot and tube_faces() stitches it into quads, so the two renderings cannot drift apart.

Parameters:
  • points – The centreline, as a sequence of (x, y, z).

  • radius – The tube’s radius, which is half the strand’s diameter.

  • n_around – Points round the circle.

Returns:

its first point is repeated at the end.

Return type:

An (len(points), n_around + 1, 3) array. The ring is closed

braidpy.parametric_strand.tube_mesh(points, radius: float, n_around: int = 16)

A strand drawn as what it is: a tube of yarn, not a line.

Sweeps a circle of radius along a sampled centreline, so a picture of a braid shows its strands at their real thickness — and therefore shows them touching, which is the whole of what sets a braid’s size. A line drawing cannot show that and has to be believed instead.

Takes the points rather than a strand, so it serves anything that can be sampled: a ParametricStrand via sample(), a StrandPath, a helix, or a rod simulation’s output.

Parameters:
  • points – The centreline, as a sequence of (x, y, z).

  • radius – The tube’s radius, which is half the strand’s diameter.

  • n_around – Points round the circle.

Returns:

(x, y, z), each a (len(points), n_around + 1) array, ready for a surface plot.

braidpy.parametric_strand.tube_faces(points, radius: float, n_around: int = 16, stride: int = 1)

The same tube as quads, for a renderer that wants polygons.

Matplotlib’s Poly3DCollection takes faces rather than a surface, so this is what to hand it — and because it shares tube_rings() with tube_mesh(), the matplotlib and Plotly pictures are of the same tube.

Parameters:
  • points – The centreline, as a sequence of (x, y, z).

  • radius – The tube’s radius.

  • n_around – Points round the circle.

  • stride – Take every n-th sample along the centreline, for an animation that has to redraw quickly.

Returns:

A list of four-cornered faces, each a list of (x, y, z).

A braid as curves in space, its strands through a punctured disk.

class braidpy.parametric_braid.Plotter(*values)

Bases: str, Enum

What draws a braid: Plotly or Matplotlib.

PLOTLY = 'PLOTLY'
MATPLOTLIB = 'MATPLOTLIB'
class braidpy.parametric_braid.ParametricBraid(strands: list[ParametricStrand])

Bases: object

A braid as its strands’ curves in space, to sample and draw.

get_positions_at(t: PositiveFloat) → list[tuple[float, float, float]]

Get position of different strands at a given time

Parameters:

t – time or z coordinates

Returns:

list of 3D coordinates

Return type:

List[Tuple[float, float, float]]

figure(n_sample: StrictlyPositiveInt = 200, title: str = '', tube_diameter: float | None = None, n_around: int = 16, opacity: float = 0.55, colors: Sequence[str] | None = None, names: Sequence[str] | None = None, line_width: float = 10, z_title: str = 'Z (time)', flip_z: bool = True) → Figure

The braid as a Plotly figure, drawn but neither shown nor written.

Given tube_diameter, the strands are drawn at their real thickness instead of as lines. That is worth the extra cost when the point is how the strands fit: a line drawing shows where the centres go and leaves whether the yarn touches or overlaps to be taken on trust. The tubes are semi-transparent so the far side of a rope is not simply hidden behind the near one.

Parameters:
  • n_sample – Points sampled along each strand.

  • title – Figure title.

  • tube_diameter – Draw the strands this thick, rather than as lines.

  • n_around – Points round each tube, when drawing them.

  • opacity – How far through a tube the one behind shows.

  • colors – One colour per strand, cycled; the terminal colours if None.

  • names – One legend name per strand; “Strand i” if None.

  • line_width – Width of the lines, when not drawing tubes.

  • z_title – Title of the z axis.

  • flip_z – Run z downward, as time does in a braid diagram. A braid whose z is a height, such as one coming off a machine, wants it upright instead.

Returns:

The figure.

plot(n_sample: StrictlyPositiveInt = 200, plotter: Plotter = Plotter.PLOTLY, output_html: str | None = None, title: str = '', tube_diameter: float | None = None, n_around: int = 16, opacity: float = 0.55) → ParametricBraid

Plot the braid in 3D

Parameters:
  • n_sample – Points sampled along each strand.

  • plotter – Which backend to draw with.

  • output_html – If given, write the figure to this path instead of showing it. Plotly only.

  • title – Figure title, for a written page that has to say what it is.

  • tube_diameter – Draw the strands at this thickness rather than as lines — see figure(). Plotly only.

  • n_around – Points round each tube, when drawing them.

  • opacity – How far through a tube the one behind shows.

Returns:

the braid itself

Return type:

ParametricBraid

braidpy.parametric_braid.closest_approach(strands: Sequence, n_samples: int = 600, span: float = 1.0, against: Sequence[int] | None = None) → float

The nearest the centres of two different strands come to each other.

Strands of diameter d may not come closer than d. Nothing in a drawing enforces that, so it has to be measured — and a shape that fails here is not a braid however pretty. Works on anything that answers position(z) over a known length, whoever produced it.

Every pair of heights is compared, not only equal ones. Comparing strands at the same height is much cheaper and is wrong: two strands that wind round each other pass closest at different heights, and on a three-strand rope laid one turn per period the equal-height figure overstates the clearance by a third. A strand is followed over span periods either side of the other’s, which is ample — the distance between two points is at least their difference in height, so a neighbour further away than that in z cannot be the nearest.

Parameters:
  • strands – The strands to compare.

  • n_samples – Points sampled along a period. The measurement is a minimum over samples, so it converges from above.

  • span – Periods to follow one strand either side of the other’s. The distance between two points is at least their difference in height, so a fraction of a period is enough whenever the strands are thin against the period — and much cheaper.

  • against – Compare only these strands against all the others, rather than every pair. For a braid with a symmetry that carries one strand onto another, most pairs are repeats of a few, and naming the few is the difference between a search that finishes and one that does not. Comparing everything if left out.

Returns:

The smallest distance found; infinity if there are fewer than two strands.

The 2D braid diagram, drawn by braidpy rather than by a library.

braidpy used to hand this picture to braid-visualiser, which drew a perfectly good diagram in its own colours — so a strand was one colour in the console and another in the plot, and the two could not be read together. Drawing it here fixes that: the diagram uses terminal_colors, the same palette draw() uses, so strand 3 is the same colour wherever you look at it.

The braid runs down the page, the way a braid hangs and the way a braider works, with the word written above it. Strands swing across on the smoothstep profile of parametric_strand, so a crossing is a curve rather than a corner; pass profile=LINEAR for straight segments.

Nothing about the braid is re-derived here. strand_paths() gives each strand as a curve in three coordinates — across the braid, depth (positive where a strand passes in front), and along — so the diagram is that curve seen from the front, with the strand passing behind interrupted where the two meet.

braidpy.braid_diagram.diagram_segments(paths: Sequence, n_samples: int = 400, gap: float = 0.45) → list[list[ndarray]]

Each strand as the pieces of it that are visible from the front.

A strand is hidden where it passes behind another — where the two are at the same place across the braid and this one has the lesser depth. Breaking the line there is what makes a diagram readable as a braid rather than as a tangle.

Parameters:
  • paths – StrandPath objects, as strand_paths() returns.

  • n_samples – Points along each strand. A crossing narrower than the spacing between samples would be drawn unbroken.

  • gap – How wide the break is, as a fraction of the distance between neighbouring strands.

Returns:

Per strand, a list of (n, 2) arrays of (across, along) to draw as separate lines.

braidpy.braid_diagram.draw_diagram(braid, n_samples: int = 400, line_width: float = 3.0, gap: float = 0.45, amplitude: float = 0.28, profile: tuple[float, ...] = (0.0, 0.0, 3.0, -2.0), color: str | None = None, title: str | None = None, save: str | None = None, ax: Axes | None = None) → Axes

Draw a braid as a diagram, running down the page.

Parameters:
  • braid – The braid to draw.

  • n_samples – Points along each strand.

  • line_width – Thickness of a strand.

  • gap – Width of the break where a strand passes behind, as a fraction of the distance between neighbouring strands. Generous on purpose: this is a diagram, not a picture of a real braid, and the break is what says which strand went behind.

  • amplitude – How far a strand swings out of line as it crosses. Larger is rounder; the crossing is drawn, not just implied.

  • profile – How a strand travels sideways — SMOOTHSTEP for curves, LINEAR for straight segments.

  • color – One colour for every strand. By default each takes its own, the same colour draw() gives it.

  • title – Heading; the braid’s word by default, and “” for none.

  • save – Path to write the figure to, if wanted.

  • ax – Axes to draw on; a new figure otherwise.

Returns:

The axes drawn on.

braidpy.braid_diagram.sample_period(path, n_samples: int) → ndarray

One period of a strand, without the wrap at the end.

position() takes z modulo the period, so that a closed braid can be followed round and round. Asked for the very last point of one period it therefore answers with the first, and a diagram drawn from that has every strand jumping back to where it started. Sample up to the period and finish with the slot the strand genuinely ends in.

Parameters:
  • path – A StrandPath.

  • n_samples – Points to take.

Returns:

An (n_samples, 3) array of (across, depth, along).

braidpy.braid_diagram.strand_color(index: int) → str

The colour of a strand, matching the one the console draws it in.

Parameters:

index – Which strand, from 0. Wraps round when there are more strands than colours, exactly as the console does.

Returns:

A colour matplotlib understands.

Braids on a ring of slots, and the shape a laid rope takes.

References on the annular braid group:

A flat braid lays its slots out on a line, so a strand that wants to get from one end to the other has to climb over everyone in between. An annulus lays them round a circle, and that changes what a word can ask for:

A crossing puts two neighbouring strands past each other. On a line one of them goes over; on a ring the depth direction is radial, so one of them goes outside — further from the axis — and the other inside. A positive move sends the strand in the lower-numbered slot of the pair outside, which is the same rule as the flat braid’s positive generator sending the lower strand over.

Slot numbers run 0 to N-1, so the pairs run (0,1) up to (N-2,N-1) — indices 1 to N-1 — and then (N-1,0), index N, which is the pair a flat braid has no room for. Nothing distinguishes that pair on the ring: it is the pair whose slot numbers wrap, and the wrap exists only because the numbering has to start somewhere. Rotate the labels and a different pair becomes index N. The annular braid literature writes this generator as \(\sigma_0\) or \(\sigma_N\) and says the indices are read modulo N; wrap_crossing() is just a name for crossing(N) so a word reads without the reader counting slots.

A turn carries every strand round one slot together. Nobody passes anybody and nobody goes outside anybody; the cross-section simply rotates. On a line there is no such move. On a ring it is what a rope is. Index N + 1 names it.

Everything up to tubular_paths() is bookkeeping — which strand is where, and which passed outside which — and is exact combinatorics, checkable against a drawing of the braid.

rope_helices() is the one piece of geometry in braidpy that is both closed-form and physical, and it is worth being clear about why it can be. Laying up a rope asks nothing of the strands beyond winding on together, so their shape is a one-parameter family — helices of radius R — and symmetry says where they touch without anyone having to search for it. Minimising length then drives R down until they do, at lay_radius(). Take away either the symmetry or the absence of crossings and neither step survives; see docs/source/why_no_closed_form.md.

braidpy.annulus_braid.crossing(index: int) → int

The move that puts slots index - 1 and index past each other.

Used positive, the strand in slot index - 1 passes outside — at the greater radius — and ends up in slot index; the other passes inside. Negate the move to swap who goes outside.

Parameters:

index – Which neighbouring pair, from 1 to n_strands. The last value names the pair (n_strands - 1, 0), whose slot numbers wrap; wrap_crossing() names it without counting.

Returns:

The move, which is the index itself.

braidpy.annulus_braid.wrap_crossing(n_strands: int) → int

The move that crosses the pair whose slot numbers wrap round to zero.

This is crossing(n_strands): the pair made of the last slot and slot zero. It is a crossing like any other — the ring has no privileged place, and which pair wraps depends only on where the numbering starts. What makes it worth a name is that a flat braid has no such pair, so this is the one crossing that needs the ring.

Used positive, the strand in the last slot passes outside, and carries on round rather than turning back: its winding goes up by one while the other strand’s goes down.

Parameters:

n_strands – How many slots the ring has.

Returns:

The move, which is n_strands.

braidpy.annulus_braid.turn(n_strands: int) → int

The move that carries every strand round one slot, passing nobody.

Nobody is outside or inside anybody — the whole cross-section rotates. Used positive it turns towards increasing slot numbers.

Parameters:

n_strands – How many slots the ring has.

Returns:

The move, which is n_strands + 1.

braidpy.annulus_braid.rope(n_strands: int) → list[int]

The word for a rope: every strand round together, once round the tube.

Laying up a rope is not a sequence of crossings — no strand climbs over another — it is the cross-section turning.

Parameters:

n_strands – How many strands are laid up.

Returns:

The word, one turn per slot, which brings every strand home.

braidpy.annulus_braid.solid_word(moves: Sequence[int], n_strands: int) → list[int]

The flat braid word of a ring braid with nothing in the middle.

A solid braid — a kumihimo cord, a solid sinnet — has no core for its strands to go round: they meet in the middle. Filling the hole of the annulus that way sends each crossing to the flat braid’s generator of the same index, and the two moves a flat braid has no room for to what they become once the middle is solid:

  • the turn, every strand carried round one slot towards increasing numbers, is σₙ₋₁…σ₂σ₁: the last strand passes outside every other to the front, a 1/n turn of the whole braid; n of them are a full twist. A strand that goes once round inside all the others, crossing them and then the seam, so comes back unlinked;

  • the crossing whose slots wrap is what the first crossing becomes once the numbering is turned back by one: the turn, σ₁, the turn undone.

This respects every relation of the ring’s moves, so the flat word does not depend on where the ring’s numbering starts, up to conjugation.

Parameters:
  • moves – Crossings ±1 to ±n_strands, turns ±(n_strands + 1).

  • n_strands – How many slots the ring has.

Returns:

The word, as signed generator indices from 1 to n_strands - 1, with any generator next to its own inverse cancelled.

Raises:

ValueError – If a move is not one of the ring’s.

braidpy.annulus_braid.ring_moves(word: Sequence[int], n_strands: int) → tuple[list[int], bool]

A flat braid word as moves on a ring: what solid_word() undoes.

A full run of crossings round the ring — σₙ₋₁…σ₁, or its inverse σ₁⁻¹…σₙ₋₁⁻¹ — is the bobbins all turning one place round (turn()), as a braider lays up a rope; carried out as crossings, one strand would go all the way round under the others. Every other crossing stays a crossing of neighbours. The ring is numbered whichever way round finds the more turns: the other way is a half turn of the whole braid about its axis, σᵢ read as σₙ₋ᵢ.

Parameters:
  • word – Signed generator indices, from 1 to n_strands - 1.

  • n_strands – How many slots the ring has.

Returns:

The moves — crossings ±1 to ±(n_strands - 1), turns ±(n_strands + 1) — and whether the ring is numbered the other way round. solid_word() of the moves is the word, or read the other way round if so, with any generator next to its own inverse cancelled.

braidpy.annulus_braid.cored_word(moves: Sequence[int], n_strands: int) → list[int]

The flat braid word of a ring braid round a core: the core kept, as a strand of its own that the others go round.

solid_word() fills the middle, and a braid round a core and the same braid lifted off it are then one; a strand going once round the core comes back unlinked. Kept as a strand, the core tells them apart: a tube is not a flat braid curled up. The core is strand 1, standing still, and the ring’s slots are strands 2 to n_strands + 1:

  • a crossing of slots i - 1 and i is σᵢ₊₁, of the same sign;

  • the turn is σₙ₊₁…σ₃σ₂σ₁²: the last strand passes outside every other to the front, as in solid_word(), and goes round the core;

  • the crossing whose slots wrap is the turn, σ₂, the turn undone.

Forgetting the core (strand 1) gives solid_word() back.

Parameters:
  • moves – Crossings ±1 to ±n_strands, turns ±(n_strands + 1).

  • n_strands – How many slots the ring has.

Returns:

The word on n_strands + 1 strands.

Raises:

ValueError – If a move is not one of the ring’s.

braidpy.annulus_braid.turns_last(moves: Sequence[int], n_strands: int) → list[int]

The same ring braid with its turns all at the end, as few as there are.

A turn renumbers the slots by one, so a crossing made after it is the crossing of the pair one slot back before it: a turn followed by crossing i is crossing i - 1 followed by the turn, indices read round the ring. Moved to the end so, the turns one way and the other cancel, and what is left is the cross-section’s net rotation.

Parameters:
  • moves – Crossings ±1 to ±n_strands, turns ±(n_strands + 1).

  • n_strands – How many slots the ring has.

Returns:

The crossings, then the turns, all one way.

Raises:

ValueError – If a move is not one of the ring’s.

class braidpy.annulus_braid.TubularStrandPath(slots: tuple[int, ...], signs: tuple[int, ...], n_slots: int)

Bases: object

Where one strand goes round a tubular braid, and what it passed.

This records the braid’s combinatorics, not a shape: which slot the strand occupies at each step and which side of each crossing it took. Turning that into a curve is the part that has no general answer.

Parameters:
  • slots – Its unwrapped slot number at each of len(signs) + 1 instants — it counts on past the last slot rather than resetting to zero, so that going round reads as carrying on.

  • signs – Per move, +1 if it passed outside — further from the axis — -1 if inside, 0 if it passed nobody. The two strands of a crossing always get +1 and -1; a turn gives everyone 0.

  • n_slots – How many slots the ring has.

slots: tuple[int, ...]
signs: tuple[int, ...]
n_slots: int
property length: int

The braid’s period along its axis, one unit per move.

property turns: float

How many times round the tube the strand goes in one period.

braidpy.annulus_braid.tubular_paths(moves: Sequence[int], n_strands: int) → list[TubularStrandPath]

Follow every strand round a tubular braid word.

Parameters:
  • moves – The word. ±i for i in 1..``n_strands - 1`` crosses slots i-1 and i; ±n_strands crosses the wrapping pair (n_strands - 1, 0); ±(n_strands + 1) turns the whole ring; 0 does nothing. A positive crossing sends the strand in the lower-numbered slot outside, at the greater radius.

  • n_strands – How many strands, which is how many slots the ring has.

Returns:

One path per strand, in strand order.

Raises:

ValueError – If a move names something the ring does not have.

braidpy.annulus_braid.packing_radius(n_strands: int, diameter: float) → float

The radius n parallel strands sit at when they touch their neighbours.

Evenly spaced round a circle, strands touch when the chord between two neighbours is one diameter:

\[R = \frac{d}{2 \sin(\pi / n)}\]

This is the cross-section packing answer, and it is exact only for strands that run straight — a rope with no lay at all. Twist them and they come closer than this says, because a strand’s neighbour is nearer at a different height than alongside it: at the tightest lay they can be made at, three strands at this radius clear 0.76 of a diameter, and the shortfall barely eases with more strands — 0.71 at twelve. For a rope with an actual lay use lay_radius(), which solves for it.

Parameters:
  • n_strands – How many strands are laid up.

  • diameter – How thick they are.

Returns:

The radius at which parallel neighbours just touch.

Raises:

ValueError – If there are fewer than two strands to touch.

braidpy.annulus_braid.minimum_lay(n_strands: int, diameter: float) → float

The shortest lay an evenly laid rope of this thickness can have.

Strand k of an evenly laid rope is strand 0 slid along the axis by k n-ths of a lay — the strands are one helix, repeated at n phases. So take a point on one and the matching point on another: they are at the same place across the rope and differ only by lay / n of height. Widening the rope does not separate them, because they are the same point of the same curve. Hence

\[\lambda \ge n \, d\]

Below that no radius keeps the strands apart and the rope cannot be made.

What this needs is the evenness, not ropes in general: it follows from the strands being one curve repeated, which is what “evenly laid” means here. A rope whose strands differ from one another is outside it.

The bound is not attained — clearing a diameter at it would take an infinite radius — and it is rarely what bites first; crowding round the circle usually does. It is cheap to check and exact, which is its use.

Parameters:
  • n_strands – How many strands are laid up.

  • diameter – How thick they are.

Returns:

The shortest workable lay length.

braidpy.annulus_braid.helix_clearance(n_strands: int, radius: float, lay: float, n_samples: int = 2000) → float

How close two strands of a laid rope come, exactly.

Because the strands are one helix repeated — strand k slid along by k n-ths of a lay — the distance between two of them depends only on how far along one is slid relative to the other:

\[D(w)^2 = 4R^2\sin^2\!\left(\frac{\pi w}{\lambda}\right) + \left(\frac{k\lambda}{n} - w\right)^2\]

so the clearance is that minimised over w — one variable, no surface to search. At w = k\lambda/n it is the chord between neighbours, which is the packing answer; at w = 0 it is k\lambda/n, which is why minimum_lay() exists. The true minimum is generally at neither.

Parameters:
  • n_strands – How many strands are laid up.

  • radius – The radius they sit at.

  • lay – The lay length — the axial distance for one full turn.

  • n_samples – Points in the coarse scan, before it is refined.

Returns:

The smallest distance between the centres of two strands.

braidpy.annulus_braid.lay_radius(n_strands: int, diameter: float = 0.4, lay: float | None = None, tolerance: float = 1e-09) → float

The radius a rope of a given lay settles at, found by squeezing it.

Nothing holds strands out at a radius: a helix of smaller radius is shorter, so tension pulls them in and what stops them is each other. Where they stop depends on the lay, and not in a way packing_radius() can express — the tighter the lay, the further out they must sit for the same clearance, because winding brings a strand nearer to its neighbour’s other turns.

There is no closed form, only a well-posed search: helix_clearance() rises with the radius, so bisection finds where it equals a diameter. That it is a search rather than a formula is the point — see docs/source/why_no_closed_form.md.

Parameters:
  • n_strands – How many strands are laid up.

  • diameter – How thick they are.

  • lay – The lay length. Defaults to the shortest that can be made, minimum_lay(), which needs an infinite radius — so give a longer one for a rope that exists.

  • tolerance – How closely to pin the radius down, relative to the diameter.

Returns:

The radius at which the strands just touch.

Raises:

ValueError – If the lay is too short for the strands to fit past one another at any radius at all.

class braidpy.annulus_braid.Helix(radius: float, turns: float, length: int, phase: float = 0.0)

Bases: object

A strand winding uniformly at a constant radius.

Parameters:
  • radius – Distance from the axis.

  • turns – Laps round the axis per period.

  • length – The period along the axis.

  • phase – Where on the circle it starts, in radians.

radius: float
turns: float
length: int
phase: float = 0.0
position(z: float) → tuple[float, float, float]

Where the strand is at z along the axis.

braidpy.annulus_braid.rope_helices(n_strands: int, diameter: float = 0.4, length: int = 1, turns: float = 1.0, radius: float | None = None) → list[Helix]

The shape a laid rope takes: helices, touching, evenly spaced.

The only braid shape in this package that is both closed-form and physical. It is available because a rope asks nothing of its strands beyond winding on together, which leaves a one-parameter family; because symmetry says which strands touch, so the contact set needs no searching; and because minimising length within that family is then a single inequality. Where that inequality bites has no closed form once the rope has any lay to it, so lay_radius() searches for it.

Parameters:
  • n_strands – How many strands are laid up.

  • diameter – How thick they are.

  • length – The period along the axis.

  • turns – Laps per period.

  • radius – Override the radius. Left out, it is the one the lay settles at — see lay_radius() — since nothing holds the strands out at any other. Anything smaller makes them overlap, which closest_approach() reports.

Returns:

One helix per strand, evenly spaced in phase.

class braidpy.annulus_braid.TubularBraidStrand(n_strands: int, radius: float, braid_angle: float, bulge: float, direction: int, phase: float)

Bases: object

A strand of a braided tube, after Brunnschweiler’s geometric model.

The strand winds round the tube at a constant angle to the axis while its distance from the axis swings in and out — out where it passes over a strand coming the other way, in where it passes under. That swing is the whole of the braid: take it away and the strands are helices that would have to pass through one another.

From “The geometry of tubular braided structures”, page 19: https://scispace.com/pdf/the-geometry-of-tubular-braided-structures-32b4yiwio2.pdf

Parameters:
  • n_strands – How many strands the tube has, half going each way.

  • radius – The mean distance from the axis.

  • braid_angle – The angle the mean helix makes with the axis, in radians — zero is straight up the tube, a right angle is round it. The swing makes the local angle wander either side of it, and biases it upward, since swinging out and in adds path across the tube but none along it.

  • bulge – How far the strand swings out and in. Two strands crossing are 2 * bulge apart radially, so half a diameter makes them touch there.

  • direction – +1 or -1, which way round the tube it goes.

  • phase – Where on the circle it starts, in radians.

n_strands: int
radius: float
braid_angle: float
bulge: float
direction: int
phase: float
property length: float

The axial distance in which the strand goes once round the tube.

position(z: float) → tuple[float, float, float]

Where the strand is at z along the axis.

braidpy.annulus_braid.tubular_braid(n_strands: int, radius: float = 1.0, braid_angle: float = 0.7853981633974483, diameter: float = 0.4, bulge: float | None = None) → list[TubularBraidStrand]

A braided tube: half the strands each way, interlacing.

Two things the bare formula does not say, and without which it does not braid:

The strands alternate direction round the tube. Spaced evenly and alternating, two that cross meet where the radial swing is at its extreme, so one is fully out and the other fully in. Space them any other way and they meet mid-swing, or — in the worst case — where the swing is zero and they are in the same place.

The swing follows the direction. A strand going one way bulges out where one going the other way tucks in; give them a common sign and both strands of a crossing take the same radius, which is a collision rather than a braid.

Parameters:
  • n_strands – How many strands, which must be even — half go each way.

  • radius – The mean distance from the axis.

  • braid_angle – The angle the strands make with the axis, in radians.

  • diameter – How thick the strands are. Only used to pick a default bulge; the geometry itself does not depend on it.

  • bulge – How far the strands swing. Half a diameter if left out, which sets two crossing strands exactly a diameter apart at the crossing — the clearance everywhere only while the crossings are the tightest spot, which closest_approach() will tell you.

Returns:

One strand per place round the tube, alternating direction.

Raises:

ValueError – If the strand count is odd, or the braid angle leaves the strands running straight up the tube without braiding.

braidpy.annulus_braid.tubular_braid_clearance(strands: Sequence, n_samples: int = 500) → float

How close two strands of a braided tube come, using its symmetry.

Turning the tube by two places and relabelling the strands to match carries the braid onto itself, so the pair (0, j) is the same distance apart as the pair (2, j + 2). Every pair is therefore a repeat of one involving strand 0 or strand 1, and comparing those two against the rest answers the question at a fraction of the cost — which matters, because finding a tube’s radius asks it a few dozen times.

The strands are also thin against the length in which they go once round, so only a fraction of a period either side need be searched.

Parameters:
  • strands – The strands of one braided tube, as tubular_braid() returns them.

  • n_samples – Points per period.

Returns:

The smallest distance between the centres of two strands.

braidpy.annulus_braid.crossing_binds_above(n_strands: int, braid_angle: float) → bool

Which of the two conditions on the radius is the binding one.

See tubular_braid_radius(). Below the crossover angle the tube’s width is set by the strands’ own swing; above it, by how fast they climb. The crossover is at

\[\tan q^{*} = \sqrt{1 + 4/n^{2}}\]

which tends to 45 degrees as the strands are added, so any braid of more than a few strands changes character near 45.

Parameters:
  • n_strands – How many strands, half each way.

  • braid_angle – The angle they make with the axis, in radians.

Returns:

True if the climbing condition binds, False if the swing does.

braidpy.annulus_braid.tubular_braid_radius(n_strands: int, diameter: float = 0.4, braid_angle: float = 0.7853981633974483, bulge: float | None = None) → float

The narrowest tube on which these strands braid without crowding.

In closed form, from the geometry, rather than by squeezing and measuring.

Take the two strands of a crossing and let s and t measure how far each has gone past it. At the crossing itself the swing holds them 2b apart. Just beside it the swing has decayed — as \(\cos(ns/2)\), so by \(b n^{2} s^{2}/8\) to second order — while the angle between them has opened by s + t and their heights have parted by \(R\cot q\,(s - t)\). Writing p = s + t and m = s - t, the squared distance comes out as

\[D^{2} \simeq 4b^{2} + p^{2}\left[(R^{2} - b^{2}) - \tfrac{1}{4}b^{2}n^{2}\right] + m^{2}\left[R^{2}\cot^{2}q - \tfrac{1}{4}b^{2}n^{2}\right]\]

— no cross term, the two motions being independent. So the crossing is the tightest spot exactly when both brackets are non-negative, and the narrowest tube is where the first of them reaches zero:

\[R = b \max\!\left(\sqrt{1 + \tfrac{n^{2}}{4}},\; \tfrac{n}{2}\tan q\right)\]

Two conditions, and which one binds says what is holding the tube open: the strands’ own swing, or the rate at which they climb past one another. crossing_binds_above() says which.

The rope has no such formula (lay_radius() searches), and the reason is visible here: this works because a crossing is a point of symmetry for both strands, so it is automatically a critical point of the distance and only the second-order terms matter. Two helices of a rope have no such point — their nearest approach is not where the chord between them is.

Parameters:
  • n_strands – How many strands, half each way.

  • diameter – How thick they are.

  • braid_angle – The angle they make with the axis, in radians.

  • bulge – The radial swing; half a diameter if left out.

Returns:

The smallest mean radius at which the strands are no closer together than they are at their crossings.

braidpy.annulus_braid.cover_factor(n_strands: int, radius: float, braid_angle: float, diameter: float) → float

How much of the tube’s surface the strands hide, as a fraction.

The measure of a braid’s tightness, and the one a braider cares about: a sleeve at 0.4 is visibly open, one at 1 is closed. Half the strands run each way, so one direction covers the surface when its n/2 strands, each crossing a circumferential cut in a segment of d / cos(q), together span the circumference:

\[\text{cover} = \frac{n}{2}\, \frac{d / \cos q}{2 \pi R}\]

Above 1 the strands of one direction would have to overlap each other, which round ones cannot.

Parameters:
  • n_strands – How many strands, half each way.

  • radius – The mean distance from the axis.

  • braid_angle – The angle the strands make with the axis, in radians.

  • diameter – How thick they are.

Returns:

The covered fraction, counting one direction.

braidpy.annulus_braid.radius_for_cover(n_strands: int, diameter: float, braid_angle: float, cover: float = 1.0) → float

The radius at which the strands cover that fraction of the tube.

cover_factor() rearranged, which is worth having because the radius that avoids crowding and the radius that looks like a braid are not the same number, and the gap between them is the model’s main limitation — see below.

\[R = \frac{n \, d}{4 \pi \, \text{cover} \, \cos q}\]

This will not clear. At its own non-crowding radius (tubular_braid_radius()) the model covers about 0.4 whatever the strand count, the braid angle or the swing depth — measured across 4 to 16 strands and 45 to 80 degrees. Tightening past that makes the strands overlap: at a cover of 0.9 they are a third of a diameter into one another.

The reason is the sinusoidal swing. Two strands are nearest not at their crossing, where the swing holds them a full 2b apart, but just beside it, where the swing has decayed while the angle between them is still small — and at a smaller radius a given angle buys less arc to separate them with. A real braid escapes this because its strands are not round: yarn flattens where it crosses and stays proud for longer, which is a squarer swing than a sine.

So use this to draw a braid that looks like one, and tubular_braid_radius() for the tightest the round-strand model honestly allows.

Parameters:
  • n_strands – How many strands, half each way.

  • diameter – How thick they are.

  • braid_angle – The angle they make with the axis, in radians.

  • cover – The fraction of the surface to hide.

Returns:

The mean radius giving that cover.

Closed-form shapes for braids symmetric enough to have one.

No formula takes a braid word to the shape its strands settle into — see docs/source/why_no_closed_form.md. But some braids are regular enough that a family of shapes can be written down and the choosing left to a handful of numbers, and then the question becomes a small search instead of an open problem.

The classic three-strand flat braid is one. Every strand does the same thing a third of a period later, so one curve and three phases describe the whole braid:

\[x_k(z) = A \sin\!\left(\frac{2\pi z}{P} - \frac{2\pi k}{3}\right), \qquad y_k(z) = H \sin\!\left(\frac{4\pi z}{P} - \frac{4\pi k}{3}\right)\]

The over-and-under runs at exactly twice the frequency of the side-to-side, which is what makes each strand a figure eight in cross-section, and what makes the three of them braid rather than merely weave past one another. braid_word() reads the braid straight off the curves and confirms it is the flat braid, six crossings to the period.

Two amplitudes and a period are all that is left to choose, so the shape can be optimised — shortest strands that still keep a diameter apart — which is a search in two variables rather than over a space of curves. That is the honest sense in which a braid like this has an analytic geometry: the family is closed-form, the choice within it is not.

Two facts about the family worth having, both exact:

  • The period cannot be shorter than ``n`` diameters. Strand k is strand 0 slid along the axis by k thirds of a period, so a point on one and the matching point on another are at the same place across the braid and differ only by P/3 of height — which widening the braid does not change, since they are the same point of the same curve. This follows from the strands being one curve repeated and says nothing about braids that are not.

  • Across the cross-section alone, two strands pass closest at a crossing, where they sit at ±H√3/2, so they clear H√3 there — provided A >= 2H. Below that the tightest spot moves off the crossing. Neither statement is the whole clearance, which also counts the axial offset: that is figure_eight_clearance().

class braidpy.symmetric_braid.FigureEightStrand(amplitude: float, height: float, period: float, phase: float = 0.0)

Bases: object

One strand of a symmetric flat braid, as the user’s equations give it.

Parameters:
  • amplitude – A, how far it swings to either side.

  • height – H, how far it rides over and under.

  • period – P, the axial distance in which the braid repeats.

  • phase – Which strand it is, as a fraction of a period of delay.

amplitude: float
height: float
period: float
phase: float = 0.0
property length: float

The period along the axis.

position(z: float) → tuple[float, float, float]

Where the strand is at z along the axis.

braidpy.symmetric_braid.figure_eight_strands(amplitude: float, height: float, period: float, n_strands: int = 3) → list[FigureEightStrand]

The strands of a symmetric flat braid, evenly spread in phase.

Parameters:
  • amplitude – A.

  • height – H.

  • period – P.

  • n_strands – How many strands; three is the classic braid.

Returns:

One strand per phase, in order.

braidpy.symmetric_braid.minimum_period(n_strands: int, diameter: float) → float

The shortest period this family can have, n diameters.

Strand k is strand 0 slid along the axis by k n-ths of a period, so a point on one and the matching point on another sit at the same place across the braid and differ only by P/n of height. Widening the braid does not separate them — they are the same point of the same curve — so below n diameters no amplitudes will do.

The bound belongs to braids whose strands are one curve repeated, which this family is by construction; it is not a fact about braids in general.

In practice the family needs a good deal more than this — crowding across the cross-section bites first, and it runs out between six and seven diameters of period — but this bound is exact and costs nothing to check.

Parameters:
  • n_strands – How many strands.

  • diameter – How thick they are.

Returns:

The shortest conceivable period.

braidpy.symmetric_braid.crossing_clearance(amplitude: float, height: float) → float

How far apart two strands pass, counting the cross-section only.

At a crossing the two strands sit at angles of pi/6 and 5pi/6, so their heights are ±H√3/2 and they clear H√3. Writing the pair separation as (A√3 cos u, H√3 cos 2u), the squared distance 3(A²c² + H²(2c² - 1)²) is smallest at c = 0 — the crossing — exactly when A >= 2H; below that the tightest spot slides off the crossing and the clearance is smaller.

This ignores the axial offset between strands, so it is an upper bound on the real clearance, not the real clearance. Use figure_eight_clearance() for that.

Parameters:
  • amplitude – A.

  • height – H.

Returns:

The smallest separation within a cross-section.

braidpy.symmetric_braid.symmetric_contact_needs(amplitude: float, height: float) → bool

Whether the strands pass closest where they cross, as the tube’s do.

A braided tube’s tightest spot is its crossing, which is a point of symmetry for both strands and therefore a critical point of the distance whatever the parameters — which is what lets its radius be written down (tubular_braid_radius()).

This family has a candidate for the same role: w = P/4, where the two strands sit either side of the widest part of the swing and so are at the same place across the braid. There the sideways term drops out entirely and the distance depends on H alone. But it is only a minimum in w while

\[A \ge 4H\]

and below that it is a saddle: the tightest spot slides off it, picks up a dependence on A, and stops being anywhere symmetry can name. The shapes worth having sit below it — the tightest three-strand plait comes out at A/H near 1.2 to 1.7 — so the flat braid does not close the way the tube does, and tightest_figure_eight() searches.

Parameters:
  • amplitude – A.

  • height – H.

Returns:

True if the crossing is the tightest spot.

braidpy.symmetric_braid.figure_eight_clearance(amplitude: float, height: float, period: float, n_strands: int = 3, n_samples: int = 200) → float

How close two strands of the braid really come, axial offset included.

Minimises _pair_distance_squared() — two variables in closed form, rather than a grid over two sampled curves. A coarse sweep then a local descent, because the minimum is not at any point symmetry can name (see symmetric_contact_needs()) and so there is nothing to solve for.

Parameters:
  • amplitude – A.

  • height – H.

  • period – P.

  • n_strands – How many strands.

  • n_samples – Points per axis in the coarse sweep.

Returns:

The smallest distance between the centres of two strands.

braidpy.symmetric_braid.tightest_figure_eight(diameter: float, period: float, n_strands: int = 3, n_samples: int = 260, refinements: int = 4) → tuple[float, float] | None

The shortest strands of this family that still clear a diameter.

Length falls as the amplitudes shrink and clearance falls with them, so the answer sits on the boundary where the strands just touch. Finding it is a search in two variables — coarse grid, then refined about the best — which is cheap and reliable, and is the sense in which this shape is “solved”.

Parameters:
  • diameter – How thick the strands are.

  • period – The axial period to fit the braid into.

  • n_strands – How many strands.

  • n_samples – Points per period in the clearance measurement.

  • refinements – How many times to narrow the search about the best.

Returns:

(amplitude, height), or None if no shape of this family fits that period — which happens long before minimum_period().

braidpy.symmetric_braid.braid_word(strands: Sequence, n_samples: int = 200000) → list[int]

Read the braid word off a set of curves.

Which slots a crossing exchanges is read from the order of the strands across the braid, and its sign from which of the two was higher as they passed — the same convention to_parametric_strands() draws with.

This is how a shape is checked against the braid it claims to be, rather than taken on trust. It needs the strands to be ordered across the braid at every height, so it suits a flat braid and not a tubular one.

Parameters:
  • strands – Anything answering position(z) over a common length.

  • n_samples – Heights to look at. A crossing narrower than the spacing between samples is missed, so this wants to be generous.

Returns:

The word, as signed generator indices.

take_off

A braid as it comes off whatever made it: laid, drawn in, and tightened.

Everything here works from one thing only — where each strand’s carrier was, in a plane, over time (StrandTrajectories). A horn gear machine, a braid word, a kumihimo disk: each says where its strands go, and from then on the braid is made the same way.

Laying

The braid is drawn off along the axis square to that plane at a steady rate, and a yarn is taken to stay where its carrier put it. The piece laid at time t sits over the point the carrier occupied then, carried up by the braid taken off since:

yarn(t) = (x(t), y(t), take_off * (T - t))

for a braid observed at time T. That gets the topology exactly: which yarn passes which, and on which side.

The fell

Real yarns run straight from their carriers up to the fell, where the braid forms, at fell_height: a ring about the size of the braid itself, yarns being as thick as they are. Above it each level of the braid is the carriers’ footprint drawn in toward the axis by a factor k: the fell’s own size at the fell — by default the braid’s own, as tight as the yarn allows (jammed_contraction()); k = 0 is the idealised braiding point, every yarn meeting at one point — and away from it as tight as the yarn allows. Any positive k at each level keeps which yarn passes over which, so the braid made is the braid kept.

Tightening

tighten_yarns() then shortens every yarn under tension, keeping every point at its height and no two yarns closer than a diameter — the problem of Solving a braid’s shape numerically. Far from the fell the braid settles to the shape its yarns pull it into, whatever the fell started it as.

Its parts

Each name is imported from here; it is kept in one of

  • braidpy.take_off.paths: the trajectories a braid is laid from, and the yarns laid;

  • braidpy.take_off.laying: laying them, drawn in to the fell;

  • braidpy.take_off.contact: contact between yarns, and how fast and how tight they allow;

  • braidpy.take_off.tighten: tightening;

  • braidpy.take_off.drawing: drawing the yarns;

  • braidpy.take_off.sources: where strands go, from a braid word, a disk, a mobidai or a kumihimo;

  • braidpy.take_off.ring: a disk’s braid, laid round a ring.

class braidpy.take_off.Periodic(partner: tuple[int, ...])

Bases: object

How the bottom of a tightened braid continues into its top.

A braid off a machine repeats, so a length of it is a window on something endless. Holding both ends still is a boundary the real braid does not have, and it is felt for a few periods in from each end. Saying instead that the yarn leaving the bottom of the window arrives at the top of it removes the boundary altogether: what is solved is one window of an endless braid rather than a short piece of a held one.

The window must be a whole number of periods, and the pattern must come back to itself over it – same positions, possibly a different yarn in each. partner says which: the yarn that leaves the fell end of yarn a arrives at the top end of yarn partner[a]. For a braid whose period permutes its strands this is that permutation; where the window is a whole number of full cycles it is the identity.

A window over which the pattern also turns about the axis is not handled: choose a whole number of turns, where there is nothing to undo.

Parameters:

partner – Yarn index to yarn index, a permutation. Yarns are numbered in the order of YarnPaths.points.

partner: tuple[int, ...]
classmethod closing(formed: ndarray) → Periodic | None

The wrap a laid braid closes on, if it does.

A braid laid over a whole number of periods ends where it began: each yarn’s last level sits on some yarn’s first.

Parameters:

formed – Yarn samples, shape (n_yarns, n_levels, 3).

Returns:

The wrap that joins each yarn’s last level to the first it sits on, or None if the braid does not close.

check(n_yarns: int) → None

Raise if the wrap does not cover n_yarns yarns.

loops(n_yarns: int, n_levels: int, tied: bool = False) → list[ndarray]

The closed loops the wrap makes, as sample indices in order.

Following a yarn down to the fell and on into its partner comes back to where it started after one cycle of the permutation, so the samples fall into one loop per cycle.

Parameters:
  • n_yarns – Number of yarns.

  • n_levels – Samples per yarn.

  • tied – The last level repeats the first, so it is not a sample of its own and is left out of the loop.

Returns:

One array of sample indices per loop, each in the order the yarn runs.

class braidpy.take_off.StrandTrajectories(times: ndarray, xy: dict[Hashable, ndarray], outlines: tuple[ndarray, ...] = (), axis: tuple[float, float] | None = None, label: str = 'Yarn ', outline_name: str = 'Deck', slots: tuple[tuple[float, float, str], ...] = ())

Bases: object

Where every strand’s carrier went, sampled over time.

This is all the rest of the module needs: a braid is laid from it, drawn in and tightened without knowing what made it.

Parameters:
  • times – Time of each sample, evenly spaced; shape (n,). The units are whatever the source counts in — machine steps, moves, or the 0 to 1 of a parametric strand — and take_off is per unit.

  • xy – Per strand, its position in the plane at each of those times; shape (n, 2).

  • outlines – Closed curves to draw on the plane under the braid — the gears, a disk’s rim — each of shape (m, 2).

  • axis – The braid’s axis in the plane, if the source knows where it is; the middle of the samples otherwise.

  • label – Prefix naming a strand in a drawing, followed by its key.

  • outline_name – What the outlines are, in a drawing’s legend.

  • slots – Named places in the plane to mark in a drawing — a disk’s slots — as (x, y, name).

times: ndarray
xy: dict[Hashable, ndarray]
outlines: tuple[ndarray, ...] = ()
axis: tuple[float, float] | None = None
label: str = 'Yarn '
outline_name: str = 'Deck'
slots: tuple[tuple[float, float, str], ...] = ()
centre

An attribute under its old name, read and written as the new one.

Held by the class under the old name: color = renamed_attribute("colour").

Parameters:

new – The attribute’s new name.

center() → tuple[float, float]

The braid’s axis: the source’s, or the middle of every sample.

class braidpy.take_off.YarnPaths(times: ndarray, points: dict[Hashable, ndarray], take_off: float, trajectories: StrandTrajectories, fell_height: float = 0.0, fell_radius: float | None = None, axis: tuple[float, float] = (0.0, 0.0), contraction: float = 1.0, n_formed: int | None = None, yarn_diameter: float | None = None)

Bases: object

The yarns of a braid, as they stand at one instant.

Parameters:
  • times – When each point of a yarn was laid, in the trajectories’ units; shape (n,).

  • points – Per strand, its yarn’s centreline; shape (n, 3), in the same order as times, so the last point is the one at the deck, where the yarn leaves its carrier.

  • take_off – Length of braid drawn off per unit of time.

  • trajectories – The strand motion the yarns were laid from.

  • fell_height – Height of the fell over the deck; 0 if the yarns do not converge on one.

  • fell_radius – Radius of the fell, 0 for a braiding point; None if the yarns do not converge.

  • axis – The braid’s axis, in the deck plane.

  • contraction – How far the braid itself is drawn in, away from the fell.

  • n_formed – Points per yarn above the fell; all of them if None.

  • yarn_diameter – The yarn’s thickness, if the braid was made for one; it is then drawn that thick.

times: ndarray
points: dict[Hashable, ndarray]
take_off: float
trajectories: StrandTrajectories
fell_height: float = 0.0
fell_radius: float | None = None
axis: tuple[float, float] = (0.0, 0.0)
contraction: float = 1.0
n_formed: int | None = None
yarn_diameter: float | None = None
property length: float

How much braid has come off, measured above the fell.

property top: float

Height of the oldest yarn.

property formed_count: int

Points per yarn in the braid itself, above the fell.

They come first; any after them run down from the fell to the carrier.

formed() → ndarray

The braid above the fell, one row per yarn; shape (yarns, n, 3).

Every yarn is sampled at the same heights, so [:, i] is one level.

closest_approach(include_fell: bool = True) → float

The nearest two different yarns come in the braid, over its samples.

Parameters:

include_fell – Count the fell itself. At a braiding point every yarn meets there, so the answer is 0 unless it is left out.

to_parametric_braid()

The same yarns as a ParametricBraid.

Each strand is parametrised from the deck (0) to the oldest yarn (1), and interpolated linearly between samples, so the drawing and the measuring done on parametric braids apply here too.

Returns:

One strand per yarn, in order.

Return type:

ParametricBraid

braidpy.take_off.braid_word_trajectories(braid, samples_per_crossing: int = 24, spacing: float = 1.0, lift: float = 0.5) → StrandTrajectories

A braid word’s strands, as trajectories to lay.

The strands stand in a row spacing apart, and a crossing swaps two neighbours, the one going over lifted lift * spacing to one side and the one going under to the other — the drawing of to_parametric_strands(). Anything that makes a braid word can therefore be laid, tightened and drawn: a kumihimo sequence, a catalogue braid, or a word read off a machine.

Parameters:
  • braid – A Braid, or its generators as signed integers.

  • samples_per_crossing – Samples per generator.

  • spacing – Distance between neighbouring strands.

  • lift – How far a crossing strand moves off the row, as a fraction of spacing.

Returns:

The trajectories, over times 0 to 1.

braidpy.take_off.crossing_rows(order: Sequence[Hashable], crossings: Sequence[tuple[Hashable, Hashable]], in_turn: bool = False) → list[int]

The row of the ring each crossing is made in — see ring_trajectories().

Each crossing goes in the first row after both its strands’ last ones, so crossings of different strands are made side by side and each strand’s crossings stay in order.

Parameters:
  • order – The strands round the ring.

  • crossings – (over, under) in the order they are made.

  • in_turn – Never put a crossing in a row before an earlier crossing’s, so the rows are made in the order the crossings are, as a braid grows below a disk.

Returns:

One row index per crossing.

braidpy.take_off.default_take_off(trajectories: StrandTrajectories) → float

A take-off rate that draws a braid in sensible proportions.

The strands’ mean speed across the plane: a yarn then rises about as fast as it travels sideways, so it leaves at roughly 45°, near the angle a braid is usually made at. It sets only how stretched the picture is — nothing about which yarn crosses which depends on it.

braidpy.take_off.disk_annular_word(start: Mapping[Hashable, int], steps: Sequence[Mapping[Hashable, int]], n_slots: int, clockwise: bool = True) → tuple[list[int], int]

The annular braid a disk’s moves make — see braidpy.annulus_braid.

The strands are numbered in order round the disk, seen from above and read clockwise from the seam between the last slot and slot 1, so an anticlockwise disk is read from its last slot back. A strand lifted over another — over, seen from above — passes inside it, nearer the braid’s axis, and the annulus counts a crossing by who is outside: a move clockwise over a strand is a negative crossing, anticlockwise a positive one.

A strand passing between the last slot and slot 1, crossing nobody, changes nothing on the disk, but every strand’s number then moves on one: a turn (turn()), as the disk turning by one strand would be. Which strands are numbered from where depends only on where slot 1 is; another starting point gives the same braid, conjugated.

Parameters:
  • start – Each strand’s slot, 1-based.

  • steps – Per step, the strands that move and by how many slots, as disk_crossings() takes them.

  • n_slots – Slots round the disk.

  • clockwise – Whether slot numbers go round clockwise, seen from above.

Returns:

The word, crossings ±1 to ±n and turns ±(n + 1), and the number of strands n.

Raises:

ValueError – As disk_crossings().

braidpy.take_off.disk_braid(start: Mapping[Hashable, int], steps: Sequence[Mapping[Hashable, int]], n_slots: int, yarn_diameter: float, take_off_per_row: float = 1.5, iterations: int = 300, clockwise: bool = True) → YarnPaths

The braid a disk’s moves make: laid on a ring, drawn in and tightened.

The crossings are read off the moves (disk_crossings()), the strands set evenly round a ring and crossed there (ring_trajectories()), and the braid laid and tightened as any other (lay_yarns(), tighten_yarns()).

Parameters:
  • start – Each strand’s slot, 1-based.

  • steps – Per step, the strands that move and by how many slots.

  • n_slots – Slots round the disk.

  • yarn_diameter – Yarn diameter.

  • take_off_per_row – Braid taken off per row of crossings, in yarn diameters. Above one: two strands often cross back over each other a row later, along the same path, and need that much room.

  • iterations – Tightening steps.

  • clockwise – Whether slot numbers go round clockwise, seen from above.

Returns:

The tightened braid.

braidpy.take_off.disk_crossing_steps(start: Mapping[Hashable, int], steps: Sequence[Mapping[Hashable, int]], n_slots: int) → tuple[list[Hashable], list[tuple[Hashable, Hashable]], list[float]]

The crossings a disk’s moves make, and when each is made.

A strand that moves while the others stay passes over each strand between its slot and its new one, one after another, nearest first — the rule disk_trajectories() draws and the mobidai’s own word records. A step that moves every strand alike turns the disk and crosses nothing; so does one that slides a few strands along together, as long as no strand that stays is in their way.

Parameters:
  • start – Each strand’s slot, 1-based.

  • steps – Per step, the strands that move and by how many slots, as mobidai_steps() and kumihimo_steps() give them.

  • n_slots – Slots round the disk.

Returns:

The strands in slot order from slot 1 at the start, each crossing as (over, under), and when each is made, in steps: a strand moving n slots passes the slot j along at j / n of its step, as disk_trajectories() moves it.

Raises:

ValueError – If two strands move at once other than by turning the disk or sliding along together, which this cannot order into crossings.

braidpy.take_off.disk_crossings(start: Mapping[Hashable, int], steps: Sequence[Mapping[Hashable, int]], n_slots: int) → tuple[list[Hashable], list[tuple[Hashable, Hashable]]]

The crossings a disk’s moves make, in the order they are made.

See disk_crossing_steps(), which also says which step made each.

Returns:

The strands in slot order from slot 1 at the start, and each crossing as (over, under).

braidpy.take_off.disk_trajectories(start: Mapping[Hashable, int], steps: Sequence[Mapping[Hashable, int]], n_slots: int, radius: float = 1.0, lift: float = 0.15, samples_per_step: int = 12, clockwise: bool = True, label: str = 'Strand ', slot_offset: float = 0.0, slot_names: Mapping[int, str] | None = None) → StrandTrajectories

Strands moved between the slots round a disk, as trajectories to lay.

This is how a kumihimo disk or a mobidai is worked: each step moves some strands round the rim by a number of slots — positive toward higher slot numbers — and a step that moves every strand alike is the disk itself turning.

A strand that moves while others stay is lifted over the ones it passes — over as seen from above the disk, the side the braider works from, with the braid going down through the middle. Over is therefore inside: the moving strand travels round inside the rim, a lift fraction of the radius in, and comes back out to its new slot. Read in slot order with inside as over, that gives the crossings the mobidai’s own braid word records on a clockwise disk — a move toward higher slots crosses over, positively.

That is the opposite way round from braidpy.annulus_braid, which looks at a tube from outside, where over is outside.

Parameters:
  • start – Each strand’s slot, 1-based.

  • steps – Per step, the strands that move and by how many slots.

  • n_slots – Slots round the disk.

  • radius – The disk’s radius.

  • lift – How far in a moving strand travels, as a fraction of the radius.

  • samples_per_step – Samples per step.

  • clockwise – Whether slot numbers go round clockwise, seen from above.

  • label – Prefix naming a strand in a drawing.

  • slot_offset – Slots the numbering is turned by, so slot 1 sits that far round from the top. A kumihimo disk marks the top between its last slot and slot 1: half a slot.

  • slot_names – What to call each slot that is marked, by slot number; every slot by its number if None.

Returns:

The trajectories, one unit of time per step.

Raises:

ValueError – If a strand is not on a slot, or a step leaves two strands in one slot.

braidpy.take_off.jammed_contraction(rel: ndarray, spacing: float, diameter: float) → float

How far a braid can be drawn in before two yarns touch.

Drawing the plane in by k shrinks the sideways part of every distance by k and leaves the height part alone, so a pair of samples a height dz apart and s apart sideways touches when k = sqrt(d² - dz²) / s. The braid jams at the largest of these — an exact answer over the samples, with no search.

Parameters:
  • rel – Per yarn, its samples relative to the axis; shape (yarns, n, 2), every yarn at the same heights.

  • spacing – Height between successive samples.

  • diameter – Yarn diameter.

Returns:

The contraction k; above 1 if the yarns do not fit even undrawn.

Raises:

ValueError – If two yarns pass through the same place too close in height for any drawing-in to separate them — the take-off is too slow for yarns this thick.

braidpy.take_off.kumihimo_braid(kumihimo, yarn_diameter: float, n_strands: int | None = None, **kwargs) → YarnPaths

The braid a kumihimo sequence makes — see disk_braid().

Parameters:
  • kumihimo – A Kumihimo, or a pattern of S and R.

  • yarn_diameter – Yarn diameter.

  • n_strands – Strands, when given a pattern.

  • **kwargs – Passed on to disk_braid().

Returns:

The tightened braid.

braidpy.take_off.kumihimo_steps(kumihimo, n_strands: int | None = None) → tuple[int, dict[Hashable, int], list[dict[Hashable, int]]]

A kumihimo sequence, as the disk and steps disk_trajectories() takes.

Reads a Kumihimo — its strand count and the S and R moves it has recorded — or a pattern string such as "SRSR" for n_strands strands, without running anything.

The disk is given twice as many slots as there are strands, so that a swap has somewhere to pass: position p is slot 2p + 1. A swap of the top and bottom strands is then the move swap_top_bottom() writes down — the top strand goes over every strand on its way to just past the bottom one, the bottom one comes back over the others to the top, and the first settles into its place. A rotation turns the whole disk, a quarter turn clockwise per R.

Parameters:
  • kumihimo – A Kumihimo, or a pattern of S and R.

  • n_strands – Strands, when given a pattern.

Returns:

The number of slots, each strand’s starting slot, and the steps.

Raises:

ValueError – If the pattern is empty or has other moves, or the strands are not a multiple of four.

braidpy.take_off.kumihimo_trajectories(kumihimo, n_strands: int | None = None, radius: float = 1.0, lift: float = 0.15, samples_per_step: int = 12) → StrandTrajectories

A kumihimo sequence worked on its disk, as trajectories to lay.

Positions are numbered anticlockwise from the top, as plot_timeline() draws them.

Parameters:
  • kumihimo – A Kumihimo, or a pattern of S and R.

  • n_strands – Strands, when given a pattern.

  • radius – The disk’s radius.

  • lift – How far in a moving strand travels, as a fraction of the radius.

  • samples_per_step – Samples per step.

Returns:

The trajectories, one unit of time per step.

braidpy.take_off.lay_yarns(trajectories: StrandTrajectories, take_off: float | None = None, fell_radius: float | None = None, yarn_diameter: float | None = None, fell_height: float | None = None, axis: tuple[float, float] | None = None, n_converge: int = 16, settle_length: float | None = None) → YarnPaths

The braid laid from these trajectories, as it stands at their last sample.

With neither fell_radius nor yarn_diameter each yarn lies over the path its carrier traced, lifted along the axis by the braid taken off since. With either, the yarns converge on a fell and the braid above it is drawn in toward the axis. With both, the fell is only where the braid starts: it opens out — or closes in — to as tight as the yarn allows over settle_length of take-off, and tighten_yarns() takes it from there.

Parameters:
  • trajectories – Where the strands went.

  • take_off – Length of braid drawn off per unit of time. Defaults to default_take_off() — or, with yarn_diameter, faster if need be, so that two yarns passing the same point are a diameter apart in height there; see least_take_off().

  • fell_radius – Radius of the fell circle the braid is formed on; 0 for a braiding point.

  • yarn_diameter – Draw the braid in as far as yarns this thick allow — see jammed_contraction() — away from the fell, and at the fell too if fell_radius is not given. The samples should then be closer than a diameter apart along the axis, or contacts between them go unseen.

  • fell_height – Height of the fell over the plane. Defaults to as far above it as the braid is drawn in, so the yarns converge at about 45°.

  • axis – The braid’s axis, in the plane. Defaults to the trajectories’.

  • n_converge – Points along each yarn from the fell down to its carrier.

  • settle_length – Take-off over which the braid goes from the fell’s size to its own, when both fell_radius and yarn_diameter are given. Defaults to twice the difference in radius.

Returns:

The yarns, one per strand.

braidpy.take_off.least_take_off(trajectories: StrandTrajectories, yarn_diameter: float, take_off: float) → float

The slowest take-off that lifts yarns passing the same point, or nearly, far enough apart to fit, at least take_off.

Where one strand leaves a place and another comes to the very same point later — as each crossing of a braid word does, one strand arriving where the other left — no drawing-in can separate them (jammed_contraction()): only the height the take-off puts between them can. The fewer strands move at a time, the slower the default take-off, and the closer in height they come.

Nearly the same point is as bad: two yarns a sideways distance s apart touch, dz apart in height, unless the braid is drawn out by sqrt(d² − dz²) / s, a hundredfold for carriers on one split axle that pass a hundredth of a diameter apart between two samples. So the take-off is raised until every pair fits undrawn, dz at least sqrt(d² − s²); a braid whose yarns already do is left as it was.

Parameters:
  • trajectories – Where the strands went, sampled evenly in time.

  • yarn_diameter – Yarn diameter.

  • take_off – The take-off to start from.

Returns:

take_off, or a little faster than the least take-off that lets the closest such pair fit.

braidpy.take_off.longest_step(paths: YarnPaths) → float

The furthest any yarn moves sideways between two levels of the braid above the fell.

braidpy.take_off.mobidai_braid(mobidai, yarn_diameter: float, n_cycles: int = 8, **kwargs) → YarnPaths

The braid a mobidai makes in n_cycles cycles — see disk_braid().

Parameters:
  • mobidai – A Mobidai or MobidaiConfig (see braidpy.mobidai).

  • yarn_diameter – Yarn diameter.

  • n_cycles – Cycles to work.

  • **kwargs – Passed on to disk_braid().

Returns:

The tightened braid, one yarn per strand, keyed as the mobidai’s.

braidpy.take_off.mobidai_steps(mobidai, n_cycles: int = 1, drift: int | None = None) → tuple[dict[Hashable, int], list[dict[Hashable, int]]]

A mobidai’s cycles, as the start and steps disk_trajectories() takes.

Reads either a Mobidai or its MobidaiConfig (see braidpy.mobidai) without running it, and follows its rules: a move goes the short way round unless forced, a move from an empty slot does nothing, and the disk turns n_shift_after_cycle slots after each cycle.

Some braids do not come back to the slots they started in after a cycle but one or more slots round from them — kongo gumi creeps one slot back each time — and the braider simply repeats the same moves from where the strands now are: cycle c makes every move c * drift slots round from the first cycle’s. The drift is read off the cycle itself, as Mobidai does (see cycle_drift()).

Parameters:
  • mobidai – The mobidai, or its configuration.

  • n_cycles – Cycles to work.

  • drift – Slots each cycle’s moves are shifted from the one before; read off the cycle if None.

Returns:

Each strand’s starting slot, keyed by strand id, and the steps.

braidpy.take_off.mobidai_trajectories(mobidai, n_cycles: int = 3, drift: int | None = None, radius: float = 1.0, lift: float = 0.15, samples_per_step: int = 12, slot_offset: float = 0.0) → StrandTrajectories

A mobidai worked for n_cycles cycles, as trajectories to lay.

Parameters:
  • mobidai – A Mobidai or MobidaiConfig (see braidpy.mobidai).

  • n_cycles – Cycles to work.

  • drift – Slots each cycle’s moves are shifted from the one before; read off the cycle if None — see mobidai_steps().

  • radius – The disk’s radius.

  • lift – How far in a moving strand travels, as a fraction of the radius.

  • samples_per_step – Samples per move.

  • slot_offset – Slots the numbering is turned by — see disk_trajectories().

Returns:

The trajectories, one unit of time per move.

braidpy.take_off.parametric_trajectories(braid, n_samples: int = 400, label: str = 'Strand ') → StrandTrajectories

The strands of a parametric braid, as trajectories to lay.

A ParametricStrand is a curve γ(t) = (x, y, z) for t from 0 to 1. Its (x, y) is taken as where its carrier was at time t, so the strand drawn first is laid first and ends up highest, as ParametricBraid.plot draws it — over and under come from y, as they do there.

Parameters:
  • braid – A ParametricBraid, or a sequence of strands.

  • n_samples – Samples along each strand.

  • label – Prefix naming a strand in a drawing.

Returns:

The trajectories, over times 0 to 1.

braidpy.take_off.ring_trajectories(order: Sequence[Hashable], crossings: Sequence[tuple[Hashable, Hashable]], diameter: float = 1.0, samples_per_row: int = 12, clockwise: bool = True, label: str = 'Strand ', rows: Sequence[int] | None = None) → StrandTrajectories

Strands standing evenly round a ring, swapping neighbours as they cross.

Every crossing is made by two strands next to each other round the ring: they change places, the one going over passing inside, the other outside, a diameter apart where they meet. Crossings of different strands are made side by side, in rows, as long as each strand’s crossings stay in order; each row takes one unit of time.

Nothing about which strand passes which, or on which side, is lost — inside is over, as on a disk seen from above — so a braid laid from this is the braid the moves made, with the strands where a braid holds them rather than where a disk does.

Parameters:
  • order – The strands round the ring, in slot order.

  • crossings – (over, under) in the order they are made; each pair must be neighbours on the ring when its turn comes.

  • diameter – Yarn diameter, setting the ring’s size and how far apart the two strands of a crossing pass.

  • samples_per_row – Samples per row of crossings.

  • clockwise – Whether the order runs clockwise, seen from above.

  • label – Prefix naming a strand in a drawing.

  • rows – The row of each crossing; crossing_rows() if None.

Returns:

The trajectories, one unit of time per row.

Raises:

ValueError – If a crossing’s strands are not neighbours on the ring.

braidpy.take_off.tighten_yarns(paths: YarnPaths, yarn_diameter: float, iterations: int = 400, step: float = 20.0, core_radius: float | None = None, tolerance: float = 0.001, hold_top: bool = True, rigid: Collection[Hashable] = (), periodic: Periodic | None = None) → tuple[YarnPaths, dict[str, list[float]]]

Pull the yarns taut above the fell, without letting them overlap.

Each iteration shortens every yarn, sideways only, so every sample keeps its height; then it pushes apart any two samples of different yarns closer than a diameter, until none are. The yarn is held where it arrives at the fell from its carrier, and at its oldest end, where the take-off holds it. Between the two, far enough from the fell, the braid takes the shape its yarns pull it into, whatever shape the fell started it in.

Shortening at fixed height is the length objective of Solving a braid’s shape numerically in its small-slope form — tension pulls a yarn toward the middle of its neighbours — and the push is its non-interpenetration constraint. The tension is taken implicitly, as a backward-Euler step of step along that flow, which settles a whole yarn in a few dozen iterations where moving each sample toward its neighbours would take thousands. No sample moves more than a fifth of a diameter in one go, though, so a yarn cannot jump through another and the braid the machine made is the braid that comes out.

Parameters:
  • paths – The braid to tighten.

  • yarn_diameter – Yarn diameter.

  • iterations – Shortening steps.

  • step – How far along the tension flow each step goes, in units where 1 moves a sample half way to its neighbours’ middle.

  • core_radius – Keep the yarns outside a core of this radius round the axis, for a braid laid over one.

  • tolerance – Overlap, as a fraction of the diameter, that the contact push accepts.

  • hold_top – Hold the oldest end where it is, as the take-off does. Left free, the end can turn about the axis and untwist the braid. Ignored when periodic is given, which holds neither end.

  • rigid – Yarns held where they are all along, as stiff cores: the others are pushed off them, and they never move.

  • periodic – Join the fell end of the braid to its top, so that what is tightened is one window of an endless braid rather than a short piece of a held one. See Periodic: the window must be a whole number of periods.

Returns:

"length", the total yarn length above the fell, and "closest", the closest approach, after each iteration.

Return type:

The tightened braid, and its history

Warns:

UserWarning – If the braid is laid too coarsely for contact between samples to keep its yarns apart (warn_if_too_coarse()).

braidpy.take_off.visualize_yarns(paths: YarnPaths, output_html: str | None = None, title: str | None = None, tube_diameter: float | None = None, n_around: int = 12, show_deck: bool = True, colors: Sequence[str] | None = None, extra_traces: Sequence[go.BaseTraceType] = ()) → go.Figure

The yarns in 3D, standing on whatever laid them.

Each yarn ends in a marker at the plane, where its carrier is now; the source’s outlines are drawn there, and the fell or braiding point where the yarns meet.

Parameters:
  • paths – The yarns to draw.

  • output_html – If given, write the figure to this HTML file.

  • title – Figure title; says which model the yarns follow if None.

  • tube_diameter – Draw the yarns as tubes this thick. Defaults to the yarn diameter the braid was made for, if any; 0 draws lines.

  • n_around – Points round each tube, when drawing them.

  • show_deck – Draw the source’s outlines at z = 0.

  • colors – One colour per yarn, cycled; the horn gear animation’s if None, so a yarn can be matched to its bobbin there.

  • extra_traces – Anything else to draw in the same scene.

Returns:

The figure.

braidpy.take_off.warn_if_too_coarse(paths: YarnPaths, yarn_diameter: float) → None

Warn when the braid is laid too coarsely for tighten_yarns() to keep its yarns apart: see SAFE_STEP.

Parameters:
  • paths – The braid about to be tightened.

  • yarn_diameter – Its yarns’ diameter.

braidpy.take_off.tighten.SAFE_STEP = 1.0

How far, in diameters, a yarn may move sideways between two levels and tightening still keep yarns from passing through each other. It looks for contact between samples only, and two yarns can cross between two levels without a sample of either coming within a diameter of the other only if their steps there add up to two diameters or more.

Yarns as elastic rods, settled by their own physics: web/rope.js, in Python.

The same algorithm, step for step, in the same order (tests/test_rope_python.py runs both and compares them); the model is rope.js’s, and docs/source/rope_physics.md describes it. In short, each yarn is a chain of beads, and its energy is the sum of

  • stretching: k_s/2 (|x_{i+1} - x_i| - s)² per link — stiff, so yarn barely stretches;

  • bending: k_b/2 |x_{i-1} - 2 x_i + x_{i+1}|² / s² per bead — slight;

  • contact, for any two segments of different yarns (or of one yarn, far apart along it): a yarn is a firm core inside a soft surface. Closer than a diameter d, the surfaces press together, k_r/2 (d - r)²; closer than d - w, the cores too, k_c/2 (d - w - r)², much stiffer;

and the ends’ work. The yarns’ bottom ends are clamped; their top ends are fixed to an end plate, drawn up by a force, which may turn about the axis. The yarns may also be fed through the plate from bobbins pulling them back with a tension T, their links’ rest length then one more unknown. The minimum of that energy, the braid at rest, is found by FIRE (Bitzek et al., 2006). Lengths are in yarn diameters.

The mechanics (near_pairs() to move_beads(), and relay()) are shared with braidpy.form, as rope.js shares them with form.js.

It follows the JavaScript step for step: given the same numbers from the maths library, it settles the same yarns, bead for bead. The libraries differ in the last place (Python’s math.hypot is correctly rounded, JavaScript’s not always), and thousands of steps make that visible: the two settle alike, not identically. It is pure Python and slow — tens of times slower than in a browser — which suits checking it, not settling long braids.

References:

  • FIRE: E. Bitzek, P. Koskinen, F. Gähler, M. Moseler, P. Gumbsch, “Structural relaxation made simple”, Phys. Rev. Lett. 97, 170201 (2006).

  • Closest points of two segments: C. Ericson, Real-Time Collision Detection (Morgan Kaufmann, 2005), §5.1.9.

  • The grid of cells: M. Teschner, B. Heidelberger, M. Müller, D. Pomeranets, M. Gross, “Optimized spatial hashing for collision detection of deformable objects”, Vision, Modeling, and Visualization (2003). rope.js hashes the cells with three large primes; here a cell is its own key, which finds the same pairs in the same order.

braidpy.rope.relay(yarn: Sequence[float], spacing: float) → list[float]

A yarn’s beads again, evenly spaced about spacing apart, its two ends kept.

braidpy.rope.settle(yarns: Sequence[Sequence[float]], spacing: float | None = None, force: float = 1.0, turns: bool = False, feed: float | None = None, stretch: float = 400.0, bend: float = 0.5, contact: float = 400.0, soft: float = 5.0, shell: float = 0.1, steps: int = 20000, tolerance: float = 0.001, dt_max: float = 0.05, progress: Callable[[dict[str, Any]], None] | None = None) → dict[str, Any]

Yarns settled at rest: rope.js’s settle.

Parameters:
  • yarns – Each yarn’s beads, x y z after x y z, bottom end first.

  • spacing – Rest length of a link; by default each yarn’s first link’s.

  • force – Drawing the end plate up.

  • turns – Whether the end plate may turn.

  • feed – T: feed the yarns through the plate at this tension. Without it, each yarn keeps its length.

  • stretch – k_s.

  • bend – k_b.

  • contact – k_c, the cores’.

  • soft – k_r, the soft surfaces’.

  • shell – w, how thick the soft surface is, of a diameter; 0 for a yarn hard all through.

  • steps – The most steps to take.

  • tolerance – Stop once no force is larger.

  • dt_max – FIRE’s longest time step.

  • progress – Told, every 500 steps, the yarns as they are and how far along.

Returns:

yarns, at rest; the end plate’s rise and turn; steps taken; largestForce, how near rest; contacts and deepest, the cores pressing into each other now, and deepestEver, the deepest they ever did; and the links’ rest lengths, spacing.

Making a braid crossing by crossing — beaten up, row by row, with friction: web/form.js, in Python.

The same algorithm, step for step, in the same order (tests/test_rope_python.py runs both and compares them). braidpy.rope.settle() beats a whole laid braid up at once. Here the braid is made from its oldest row up, as a braid is made: its yarns as laid by braidpy, in the order their crossings are made, so the crossings are the right ones.

The yarns are in three parts:

  • made: below a working window, the braid already beaten up, frozen;

  • working: the window, a row or two, where the yarns move — the same stretching, bending and contact as braidpy.rope, plus friction;

  • to come: above it, the rest of the braid as laid, moving as one block. The yarns’ tension draws it down onto the window, a weight draws it up: while the yarns pull harder, the newest row is beaten up against the made braid, until its crossings jam.

Each yarn slides into the window from the block at its tension, as from a bobbin. Once a row is beaten up, the lower part of the window is frozen into the made braid, and the window takes in the next row from the block.

Friction: two yarns in contact hold each other along their surfaces with a spring from where they first touched, until its pull reaches mu times the push between them, when they slip (Coulomb’s law, as the discrete element method has it). It is what keeps a beaten crossing where it was beaten.

The window is settled by FIRE, with braidpy.rope’s own mechanics, as form.js uses rope.js’s. Lengths are in yarn diameters. Pure Python, and slow: for checking, not for long braids.

References:

  • Friction as a tangential spring, capped by Coulomb’s law: P. A. Cundall and O. D. L. Strack, “A discrete numerical model for granular assemblies”, Géotechnique 29, 47 (1979), https://doi.org/10.1680/geot.1979.29.1.47 (not free to read). The same tangential spring, among other contact models, free to read: “Review of contact models used in Discrete Element Method (DEM)”, https://arxiv.org/abs/2509.07461.

  • FIRE, and the contact geometry: see braidpy.rope.

braidpy.form.form(yarns: Sequence[Sequence[float]], row: float, friction: float = 0.3, feed: float = 1.0, weight: float | None = None, stretch: float = 100.0, bend: float = 0.5, contact: float = 100.0, soft: float = 5.0, shell: float = 0.1, grip: float = 20.0, keep: float = 2.0, window: float = 2.0, steps_per_row: int = 4000, tolerance: float = 0.002, progress: Callable[[dict[str, Any]], None] | None = None) → dict[str, Any]

A braid made crossing by crossing: form.js’s form.

Parameters:
  • yarns – Each yarn’s points, x y z after x y z, its oldest end first, rising: the braid as laid.

  • row – Height of a row as laid.

  • friction – mu; 0 for none.

  • feed – T, each yarn’s tension.

  • weight – W, drawing the braid off, all yarns together; by default a quarter of the yarns’ tension.

  • stretch – k_s.

  • bend – k_b.

  • contact – k_c, the cores’.

  • soft – k_r, the soft surfaces’.

  • shell – w, how thick the soft surface is, of a diameter.

  • grip – k_t, the friction springs’ stiffness.

  • keep – How much of the window, at its top, is not frozen once a row is made.

  • window – How many rows the window starts with.

  • steps_per_row – The most steps to settle a row (three times as many for the last).

  • tolerance – A row is settled once no force is larger.

  • progress – Told, after each row, the yarns and how far along.

Returns:

yarns as made; the block’s offset; the steps taken; deepestEver, the deepest the cores ever pressed into each other; and how many stages.

braidpy.form.friction_force(grips: dict[int, list[float]], key: int, v: Sequence[float], i: int, j: int, u: float, w: float, nx: float, ny: float, nz: float, push: float, dt: float, mu: float, kt: float) → tuple[float, float, float]

Friction at a contact: the tangential spring between the segments at offsets i and j of the beads’ velocities v, at u and w along them, stretched by how the contact points slid past each other this step — kept in the contact’s tangent plane, normal (nx, ny, nz) — and given way to what friction holds, mu times the push, when it pulls harder: the contact slips. The springs are kept in grips by the pair’s key.

Returns:

The friction force on the first segment.

A braid made by its carriers: each yarn drawn by its carrier going round the machine, through a forming ring, into the braid taken off above.

Nothing here is laid in advance. The carriers go round their tracks (carrier_trajectories()), and the yarns follow:

  • To scale. Lengths are in yarn diameters, the machine at its real size: a gear some 5.5 cm across is GEAR_DIAMETER of 1100 dtex yarn, about 0.4 mm thick; the forming ring stands RING_HEIGHT above the carriers’ eyes, 3 cm.

  • Pulled by the carriers. Each yarn runs straight from its carrier’s eye up to BELOW under the ring; from there to the braid it is a chain of beads. Its carrier pulls it with a steady tension, as a carrier’s spring tensioner does: the lowest bead is pulled towards the eye, and yarn is paid out — a bead added at the bottom — when the braid draws it up, or taken back when it slackens. No bead is ever renamed, so a contact remembers its friction for as long as it lasts.

  • The forming ring, a torus of wire round the braid’s axis, the yarns passing inside it: it brings them together where the braid forms.

  • Friction holds the yarns where they cross, as on a real machine: a crossing is beaten up at the fell and carried up with the braid. With none, two taut yarns slide to wherever they touch, and the braid taken off would have no crossings at all.

  • The braid taken off: ABOVE over the ring, the yarns are made — frozen — and drawn up at a steady rate, TAKE_OFF a step of the machine.

Between moves of the carriers, the beads settle by FIRE, with the mechanics of braidpy.rope — stretching, bending, contact — and the friction of braidpy.form. Pure Python, and slow: a reference, for checking, and for a few steps of a small machine.

class braidpy.carried.CarriedBraid(yarns: list[~numpy.ndarray], made: list[int], eyes: ~numpy.ndarray, frames: list[dict[str, ~typing.Any]], colors: list[str], machine: dict[str, ~typing.Any], ring: dict[str, float], deepest: float = 0.0, settings: dict[str, float] = <factory>)

Bases: object

A braid made by its carriers, and how it was made.

Variables:
  • yarns (list[numpy.ndarray]) – Each yarn, oldest first, as (n, 3): the braid made, then the free yarn down to its carrier’s eye.

  • made (list[int]) – How many of each yarn’s points are the braid made.

  • eyes (numpy.ndarray) – Each carrier’s eye, where it is at the end.

  • frames (list[dict[str, Any]]) – Moments of the making, for an animation: each {"time", "yarns", "made", "eyes"} as above.

  • colors (list[str]) – One colour per yarn.

  • machine (dict[str, Any]) – The deck: gear centres and radii, to scale.

  • ring (dict[str, float]) – The forming ring: radius, height, wire.

  • deepest (float) – The deepest any two yarns’ cores pressed into each other.

yarns: list[ndarray]
made: list[int]
eyes: ndarray
frames: list[dict[str, Any]]
colors: list[str]
machine: dict[str, Any]
ring: dict[str, float]
deepest: float = 0.0
settings: dict[str, float]
colours

An attribute under its old name, read and written as the new one.

Held by the class under the old name: color = renamed_attribute("colour").

Parameters:

new – The attribute’s new name.

braidpy.carried.braid_by_carriers(machine: BraidingMachine, n_steps: int, carriers: dict[int, tuple[str, int]] | None = None, frame_every: int = 0, progress: Callable[[dict[str, Any]], None] | None = None, **options: Any) → CarriedBraid

A braid made by a machine’s carriers going round; see the module.

Parameters:
  • machine – The machine.

  • n_steps – Steps of the machine to make.

  • carriers – The loading; the machine’s own if None.

  • frame_every – Keep a moment of the making every so many settlings; 0 for none.

  • progress – Told after each step: {"step", "of"}.

  • **options – As carriers_job() takes them.

Returns:

The braid made, and how.

braidpy.carried.carriers_job(machine: BraidingMachine, n_steps: int, carriers: dict[int, tuple[str, int]] | None = None, gear_diameter: float = 140.0, ring_height: float = 75.0, ring_radius: float | None = None, take_off: float = 1.0, tension: float = 1.0, friction: float = 0.3, substeps: int = 60) → dict[str, Any]

What make() (and web/carried.js) makes a braid from: each carrier’s eye at each moment, the yarns as they start, the ring, and every setting, as plain data.

Parameters:
  • machine – The machine.

  • n_steps – Steps of the machine to make.

  • carriers – The loading; the machine’s own if None.

  • gear_diameter – The machine’s mean gear, across, in yarn diameters.

  • ring_height – The forming ring over the carriers’ eyes.

  • ring_radius – The ring’s radius, to its wire’s middle; by default as wide as the yarns’ start, with RING_ROOM to spare.

  • take_off – Braid drawn off, a step.

  • tension – Each carrier’s pull on its yarn.

  • friction – mu, between yarns.

  • substeps – The carriers’ places between settlings, a step.

Returns:

eyes, per moment each carrier’s [x, y]; start, each yarn’s beads flat, the first made; ring; settings; substeps; colours; and the deck, to draw it.

Return type:

The job

braidpy.carried.figure(braid: CarriedBraid, view: str = 'braid', n_around: int = 12) → Figure

The braid in 3D.

Parameters:
  • braid – What braid_by_carriers() made.

  • view – "braid", the braid made and the yarns into it, as tubes, near; or "machine", everything to scale — the deck, the carriers, the yarns’ straight runs up to the ring, the ring, and the braid as small as it is beside them.

  • n_around – Points round each tube.

Returns:

The figure.

braidpy.carried.make(job: dict[str, Any], frame_every: int = 0, progress: Callable[[dict[str, Any]], None] | None = None) → dict[str, Any]

The braid made from a job (carriers_job()): web/carried.js’s make, step for step.

Parameters:
  • job – What to make it from.

  • frame_every – Keep a moment of the making every so many settlings; 0 for none.

  • progress – Told after each step of the machine: {"step", "of"}.

Returns:

the braid made, then the free beads; made, how many of each are made; deepest; and frames, each {"sample", "yarns", "made"}.

Return type:

yarns, each oldest first, flat

Braid Studio

What the web page asks of braidpy.

Package: braidpy.web Description: Braids as plain data, for a page to draw Authors: Baptiste Labat Created: 2026-10-04 Repository: https://github.com/baptistelabat/braidpy License: Mozilla Public License 2.0

The braidpy web page runs braidpy itself, in the browser, through Pyodide, and draws what it computes with three.js. This package is everything the page asks of braidpy: what can be made (catalog()), and the braid a description makes (build()), both as plain JSON-ready data — lists, numbers and strings — so the page needs nothing of Python’s to draw it.

A description says where the braid comes from — by default, the first source offered:

{"source": "word", "word": "1 -2", "n_strands": 3, "repeat": 6}

A braid word: signed generator indices (1 -2), s1 s2^-1, or letters (aB, a for σ₁ and A its inverse). With "layout": "ring", a ring word, the strands round a circle: n crosses the last strand and the first, across the seam, and n + 1 turns them all one place round. With "layout": "band", a band word (braidpy.band_canonical_form): 4:1 crosses strands 4 and 1 in front of those between, 1:4 the other way.

{"source": "kumihimo", "pattern": "SR", "n_strands": 8, "repeat": 8}

Kumihimo’s own moves: swap top and bottom, rotate a quarter.

{"source": "mobidai", "name": "KONGO_8", "cycles": 8}

A disk braid from the catalogue (braidpy.mobidai_catalog).

{"source": "sinnet", "name": "abok_3042", "cycles": 4}

An Ashley solid sinnet (braidpy.solid_sinnets_catalog).

{"source": "machine", "name": "tubular_8", "cycles": 3}

A horn gear braiding machine (braidpy.horn_gear.examples).

Every description may also give yarn_diameter and iterations, the tightening steps; 0 lays the yarns without tightening them.

class braidpy.web.MachineGeometry

Bases: TypedDict

A machine as the page draws it from above, to load it by hand.

name: str
gears: list[Gear]
contacts: list[Contact]
loading: list[list[str | int]]
axials: list[dict[str, Any]]
own_axials: list[str]
core_colour: str
graph: dict[str, Any] | None
tracks: list[Track]
class braidpy.web.MachineTurned

Bases: TypedDict

A machine’s handle turned by hand, as the page shows it.

time: int
carriers: list[list[str | int]]
met: list[list[str | int]]
slots: list[list[str | int]]
frames: list[TurnedFrame]
class braidpy.web.Result

Bases: _Result

A braid, as braidpy.web.build() gives it.

timeline: Timeline
tighten: Tightening
disk: DiskProgram
ashley_shape: ShapeDrawing
carriers: dict[str, Any]
title: str
strands: list[Strand]
times: list[float]
yarn_diameter: float
info: Info
notes: list[str]
class braidpy.web.Source

Bases: _Source

A source of braids: its title, its defaults, and what it offers.

entries: list[Entry]
examples: list[Example]
grids: dict[str, str]
shapes: dict[str, dict[str, str]]
orders: dict[str, str]
title: str
defaults: dict[str, str | int | float]
class braidpy.web.Spec

Bases: TypedDict

A description of a braid: where it comes from, and its settings.

source: str
yarn_diameter: str | float | None
iterations: str | float | None
settle: str
twist: str
word: str
layout: str
n_strands: str | float | None
repeat: str | float | None
pattern: str
name: str
cycles: str | float | None
slots: str
moves: str
n_slots: str | float | None
shift: str | float | None
counts: str
grid: str
shape: str
size: str | float | None
height: str | float | None
cells: str
order: str
turned: str
extra: str
corners: str | float | None
carriers: str
core: str
cores: str
n_gears: str | float | None
card: str
graph: str
braidpy.web.braids(topologies: Sequence[Mapping[str, Any]]) → list[dict[str, Any]]

Every braid a page offers as it comes (premade_specs()), as a row of a table to look braids up in: what it is called and made from, what it is — from its topology, where the catalogue of braids by topology has it — and where it is shown.

Parameters:

topologies – The catalogue of braids by topology, as braidpy.topology_catalog.export() writes it.

Returns:

key, a name for its files; title; source; spec, what build() makes it from; links, as braidpy.catalog.Link has them; and, if its topology is known, topology, its name, n_strands, loops, the sizes of the loops its closure makes, writhe, and same, the titles of the other braids of the catalogue it is. A braid the catalogue of braids by topology does not take, as a lace machine’s, has no topology.

Return type:

Per braid

braidpy.web.build(spec: Spec, tighten: bool = True) → Result

The braid a description makes, as data for a page to draw.

Parameters:
  • spec – The description; see the module’s documentation.

  • tighten – Tighten the yarns here. If False they are only laid, and the result carries tighten, everything a page needs to tighten them itself — as Braid Studio does, in JavaScript (web/tighten.js), many times faster than numpy in the browser: the samples’ xy, yarn after yarn, and tighten_yarns()’s settings; with chosen, which of them the strands’ points are, and centre, what was taken off them.

Returns:

title; strands, each with its name, colour and the points of its yarn’s centreline, oldest first, the braid’s axis along z; yarn_diameter; info, what is known of the braid — strands, its word and crossings, the permutation it makes; and notes worth telling whoever asked. times says when each point was laid, and timeline what laid it, seen from above — the carriers’ paths, the outlines under them and the slots — with its clock relating the source’s time to the braid’s. A machine’s axial cores are yarns among the others, named Core.

Raises:

ValueError – If the description cannot be made.

braidpy.web.catalog() → dict[str, Source]

What the page can make, with sensible defaults for each source.

Returns:

Per source, a title, its defaults, and for the catalogued ones the entries to choose from, each with a name and a title.

braidpy.web.from_b3d(text: str) → Spec

A design saved by braid3d, as your own mobidai braid’s description (mobidai_from_b3d()): its disk, where each yarn starts, in its colour, a cycle’s moves and how many cycles.

Parameters:

text – The .b3d file’s text.

Returns:

The description, for the page to fill its fields with and make.

Raises:

ValueError – If the file holds no design, or one not read here.

braidpy.web.machine_geometry(name: str) → MachineGeometry

A machine as the page draws it from above, to load it by hand: its gears — where, how big, the circle their carriers ride, their slots, the way they turn and where each slot is at step 0, drawn as braidpy draws it (GearAngles) — the contacts between them, the machine’s own loading, every place it could feed an axial yarn (axial_spots()), those it does, in the colour cores are drawn in, and, for a machine of gears geared together, the machine written as the gears that mesh (graph_of()), for your own to start from.

braidpy.web.machine_origin(name: str, place: list[Any], time: int) → list[Any] | None

The slot at step 0 whose carrier is at place at step time: where a carrier put on the machine there goes in its loading.

Parameters:
  • name – The machine.

  • place – As (gear, slot), at step time.

  • time – The step.

Returns:

(gear, slot) at step 0; None if no slot leads there.

braidpy.web.machine_turned(name: str, loading: list[list[Any]], time: int, frames: int = 8) → MachineTurned

A machine’s handle turned time steps by hand, as the page shows it (see braidpy.horn_gear.handle): stopped where carriers meet, and drawn through the next step, for the page to turn it smoothly.

Parameters:
  • name – The machine.

  • loading – The carriers at step 0, as (gear, slot).

  • time – How many steps to turn.

  • frames – Pictures of the next step.

Returns:

time, the step reached; carriers there, in the loading’s order; met, where carriers met, if they did; slots, every slot gear by gear; and frames, the slots’ and carriers’ places through the next step, the first at the step reached.

braidpy.web.parse_moves(text: str) → list[tuple[int, int]]

Moves from one place to another, as (from, to) pairs.

Reads 1>15, 17>31, 1->15; 17->31, 1 15, 17 31, (1, 15) (17, 31), one move per line, and the like: what matters is the order of the numbers, taken two by two.

Parameters:

text – The moves.

Returns:

The moves, in order.

Raises:

ValueError – If there are no moves, or an odd number of places.

braidpy.web.parse_word(text: str) → list[int]

A braid word, as signed generator indices.

Reads 1 -2 1 (or with commas), s1 s2^-1 s1 (σ too), and letters, aBa: a is σ₁, b σ₂ and so on, a capital the inverse (braidword_alpha_to_numeric()).

Parameters:

text – The word.

Returns:

The generators; empty for an empty word.

Raises:

ValueError – If the text is none of these.

braidpy.web.premade(directory: str, workers: int | None = None) → list[dict[str, Any]]

Make every braid of premade_specs(), laid as build() lays it for a page to tighten (tighten=False), and write each as JSON in directory, with index.json saying which is which. A page finding the braid asked for there shows it at once, without Python. The same braid every time: unchanged, a file is written the same.

Parameters:
  • directory – Where to write them; made if missing.

  • workers – Processes to make them with; one per processor if None.

Returns:

per braid, its spec and its file.

Return type:

The index

braidpy.web.premade_specs() → list[Spec]

The braids a page offers as they come — each catalogued braid and each braid word example, with the source’s defaults — to be made once, with the site, rather than by every visitor (premade()).

Returns:

what differs from the source’s defaults is left to them.

Return type:

Their descriptions, as short as they can be

Disk braids: kumihimo’s own S/R moves, a mobidai braid, an Ashley solid sinnet. Each is laid round a ring with its rows in the order the disk makes their crossings, so the page can show the disk and the braid in step, and comes with its moves, for the page to make it move by move as on a marudai.

braidpy.web.disks.from_b3d(text: str) → Spec

A design saved by braid3d, as your own mobidai braid’s description (mobidai_from_b3d()): its disk, where each yarn starts, in its colour, a cycle’s moves and how many cycles.

Parameters:

text – The .b3d file’s text.

Returns:

The description, for the page to fill its fields with and make.

Raises:

ValueError – If the file holds no design, or one not read here.

Horn gear braiding machines: the braid a machine makes, loaded as it loads itself or by hand, stopped where carriers meet; and the machine as the page draws it from above, to load it by hand.

braidpy.web.machines.machine_geometry(name: str) → MachineGeometry

A machine as the page draws it from above, to load it by hand: its gears — where, how big, the circle their carriers ride, their slots, the way they turn and where each slot is at step 0, drawn as braidpy draws it (GearAngles) — the contacts between them, the machine’s own loading, every place it could feed an axial yarn (axial_spots()), those it does, in the colour cores are drawn in, and, for a machine of gears geared together, the machine written as the gears that mesh (graph_of()), for your own to start from.

braidpy.web.machines.tracks(machine: Any, layout: Any = None) → list[tuple[str, Any]]

A machine’s carrier tracks, seen from above as the demo draws them (coloured_tracks()), each in its colour, with fewer points: none for a machine driven by a programme.

Parameters:
  • machine – The machine.

  • layout – Where its gears are; worked out if None.

Returns:

Per track, its colour and its points, shape (n, 2), in the layout’s plane — the carriers’ too.

braidpy.web.machines.machine_turned(name: str, loading: list[list[Any]], time: int, frames: int = 8) → MachineTurned

A machine’s handle turned time steps by hand, as the page shows it (see braidpy.horn_gear.handle): stopped where carriers meet, and drawn through the next step, for the page to turn it smoothly.

Parameters:
  • name – The machine.

  • loading – The carriers at step 0, as (gear, slot).

  • time – How many steps to turn.

  • frames – Pictures of the next step.

Returns:

time, the step reached; carriers there, in the loading’s order; met, where carriers met, if they did; slots, every slot gear by gear; and frames, the slots’ and carriers’ places through the next step, the first at the step reached.

braidpy.web.machines.machine_origin(name: str, place: list[Any], time: int) → list[Any] | None

The slot at step 0 whose carrier is at place at step time: where a carrier put on the machine there goes in its loading.

Parameters:
  • name – The machine.

  • place – As (gear, slot), at step time.

  • time – The step.

Returns:

(gear, slot) at step 0; None if no slot leads there.

Braid words, flat or round a ring: laid as braidpy draws them, and as moves on a ring of bobbins, for the page to make the braid move by move as on a marudai.

braidpy.web.words.place_program(program: RingProgram, slots: int = 12) → DiskProgram

A ring program (braidpy.ring_program.RingProgram) as a disk program for the page: each place slots slots on from the last, each swap made as _swapped() makes it, the braid hanging free. An empty place holds no bobbin: a strand beside it moves into it.

Parameters:
  • program – The ring program.

  • slots – Slots between neighbouring places.

Returns:

What the disk does, strands by index.

Utilities

Utilities braidpy shares, not about braids themselves.

braidpy.utils.colorize_by_index(text: str, index: int) → str

Colorize a string using a repeating color based on index (starting at 0).

Parameters:
  • text – The string to colorize.

  • index – The index used to determine the color.

Returns:

The colorized string.

Return type:

str

braidpy.utils.colorize(item: str | int, index: int | None = None) → str

Colorize item based on index (or its value if it’s an int).

Parameters:
  • item – The item to colorize (string or integer).

  • index – Optional index to use for color selection. If None, uses the item’s value (if int) or 0.

Returns:

The colorized string representation of the item.

Return type:

str

braidpy.utils.int_to_superscript(n: int) → str

Convert an integer to its superscript representation.

Parameters:

n – The integer to convert.

Returns:

The superscript representation of the integer.

Return type:

str

braidpy.utils.int_to_subscript(n: int) → str

Convert an integer to its subscript representation.

Parameters:

n – The integer to convert.

Returns:

The subscript representation of the integer.

Return type:

str

class braidpy.utils.PositiveFloat(value: Any)

Bases: float

A float that is zero or more: anything else raises ValueError.

class braidpy.utils.StrictlyPositiveFloat(value: Any)

Bases: float

A float that is more than zero: anything else raises ValueError.

class braidpy.utils.PositiveInt(value: Any)

Bases: int

An int that is zero or more: anything else raises ValueError.

class braidpy.utils.StrictlyPositiveInt(value: Any)

Bases: int

An int that is more than zero: anything else raises ValueError.

braidpy.utils.lazy_module(name: str) → Any

A module that is only imported when first used.

Drawing libraries — plotly, matplotlib — are heavy, and most of braidpy computes without them: in a browser, through Pyodide, not loading them is the difference between a page that opens and one that downloads tens of megabytes first. Modules that draw import them this way, and keep the real import under TYPE_CHECKING for the type checker.

Parameters:

name – The module’s dotted name.

Returns:

A stand-in that imports the module on first attribute access.

exception braidpy.utils.FunctionalException

Bases: Exception

A braid computation that ran but did not give what it must: a bug in braidpy rather than in what it was asked.

braidpy.utils.play_controls(frame_duration_ms: float, marks: Sequence[tuple[str, str]]) → dict[str, list[dict[str, Any]]]

Play and pause buttons, and a slider, for a Plotly animation.

Parameters:
  • frame_duration_ms – How long each frame is shown while playing.

  • marks – The slider’s notches, as (frame name, label).

Returns:

updatemenus and sliders, for Figure.update_layout. The slider’s read-out is hidden: Plotly’s repeats the active notch’s label, and notches between two labelled ones have none to repeat, so it would blank out while the animation ran.