Skip to content

Vertex codes

Naming isomers by what each vertex sees of the groups on its linkers: cage_isomer_builder.utils.vertex_codes.

Vertex codes: name an isomer by what each vertex (node) sees of the groups on its linkers.

Every linker joins two vertices. Seen from the pore centre with one vertex at the bottom, each site of the linker is next to one of its two vertices, on the left or on the right of the linker, at some depth: 1 for the sites closest to that vertex, 2 for the next ones, and so on. A para-phenylene has four sites, numbered 1 (bottom left), 2 (top left), 3 (top right), 4 (bottom right): sites 1 and 4 are next to the bottom vertex at depth 1, and 2 and 3 next to the top one. A biphenyl has two depths at each end.

Seen from one vertex, a linker reads one character per depth for the sites next to this vertex (groups next to the other vertex are that vertex's business):

  • one kind of group: 1 if the left site has a group, 4 if the right one has, 5 (1 + 4) if both have, 0 if neither;
  • several kinds (A, B, ...): two characters per depth, the group on the left site and the group on the right one, 0 for none (A0, 0B, AB).

One group per linker on four-site linkers gives the codes of one digit per linker (0, 1, 4) used throughout. Where a linker reads more than one character, the linkers of a code are separated by . (10.00.04).

A vertex code lists its linkers clockwise as seen from the pore centre. Two forms are used:

  • the anchored code starts at the vertex's lowest-numbered linker. The vertex name of an isomer, its anchored codes in vertex order joined by - (e.g. 000-100-141-401), is unique and converts back to the site indices exactly;
  • the environment label is the rotation of the code that sorts first with 5 < 1 < 4 < 0 (several kinds: A < B < ... < 0), e.g. 114, 140, 104. It names the vertex environment whatever linker it starts at, so different isomers can share the same labels.

The mirror image of a vertex swaps left and right (1 and 4, or the two characters of each pair) and reads its linkers the other way round.

VertexScheme dataclass

VertexScheme(vertex_linkers: tuple, linker_sites: tuple, site_codes: dict)

How the sites of a cage map onto vertex codes.

Attributes:

Name Type Description
vertex_linkers tuple of tuple of int

For each vertex, its linkers clockwise as seen from the pore centre, starting at the lowest-numbered one.

linker_sites tuple of tuple of int

The site numbers of each linker.

site_codes dict

site -> (vertex, digit) or (vertex, digit, depth): the vertex the site is next to, its side there (1 left, 4 right) and its depth (1, the closest, when left out).

An isomer is given as its occupied sites (one kind of group), or as
``{group sites}`` (several kinds; the first is A, the second B, ...),
or as an class:`~cage_isomer_builder.utils.rgroup.RGroupIsomer`.

Examples:

Two vertices joined by two linkers, sites 0-3 and 4-7:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> scheme = VertexScheme(
...     vertex_linkers=((0, 1), (0, 1)),
...     linker_sites=((0, 1, 2, 3), (4, 5, 6, 7)),
...     site_codes={0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
...                 4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
>>> scheme.name([1, 6])
'40-01'
>>> scheme.isomer("40-01")
[1, 6]
>>> scheme.resolve("1-6"), scheme.resolve("40-01")   # either name gives the isomer
([1, 6], [1, 6])

Two groups on a linker, and two kinds of group:

>>> scheme.name([0, 1, 6])
'50-01'
>>> scheme.name({"NH2": [0], "OH": [1, 6]})
'AB.00-00.B0'
>>> scheme.isomer("AB.00-00.B0")
{'A': [0], 'B': [1, 6]}

n_vertices property

n_vertices: int

Number of vertices.

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)), {}).n_vertices
2

view

view(site: int) -> tuple

(vertex, side, depth) of a site: the vertex it is next to, 1 (left) or 4 (right) seen from there, and its depth (1 = closest).

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> VertexScheme(((0,), (0,)), ((0, 1, 2),), {0: (0, 1), 1: (0, 1, 2), 2: (1, 4)}).view(1)
(0, 1, 2)
Source code in cage_isomer_builder/utils/vertex_codes.py
def view(self, site: int) -> tuple:
    """
    ``(vertex, side, depth)`` of a site: the vertex it is next to, 1
    (left) or 4 (right) seen from there, and its depth (1 = closest).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> VertexScheme(((0,), (0,)), ((0, 1, 2),), {0: (0, 1), 1: (0, 1, 2), 2: (1, 4)}).view(1)
    (0, 1, 2)
    """
    code = self.site_codes[int(site)]
    return int(code[0]), int(code[1]), int(code[2]) if len(code) > 2 else 1

depths

depths(vertex: int, linker: int) -> int

Number of depths vertex reads on linker (characters per linker with one kind of group, twice that with several).

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> scheme = VertexScheme(((0,), (0,)), ((0, 1, 2),), {0: (0, 1), 1: (0, 1, 2), 2: (1, 4)})
>>> scheme.depths(0, 0), scheme.depths(1, 0)
(2, 1)
Source code in cage_isomer_builder/utils/vertex_codes.py
def depths(self, vertex: int, linker: int) -> int:
    """
    Number of depths ``vertex`` reads on ``linker`` (characters per
    linker with one kind of group, twice that with several).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> scheme = VertexScheme(((0,), (0,)), ((0, 1, 2),), {0: (0, 1), 1: (0, 1, 2), 2: (1, 4)})
    >>> scheme.depths(0, 0), scheme.depths(1, 0)
    (2, 1)
    """
    return self._depths.get((int(vertex), int(linker)), 1)

codes

codes(isomer) -> list

Anchored code of every vertex, in vertex order.

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
>>> scheme.codes([1, 6])
['40', '01']
Source code in cage_isomer_builder/utils/vertex_codes.py
def codes(self, isomer) -> list:
    """
    Anchored code of every vertex, in vertex order.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
    ...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
    ...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
    >>> scheme.codes([1, 6])
    ['40', '01']
    """
    occupied, n_kinds = self._occupancy(isomer)
    return [_join([self._token(v, L, occupied, n_kinds > 1) for L in linkers])
            for v, linkers in enumerate(self.vertex_linkers)]

name

name(isomer) -> str

Vertex name: the anchored codes joined by -. Unique for every placement, and :meth:isomer converts it back.

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
>>> scheme.name([0, 4])
'11-00'
Source code in cage_isomer_builder/utils/vertex_codes.py
def name(self, isomer) -> str:
    """
    Vertex name: the anchored codes joined by ``-``. Unique for every
    placement, and :meth:`isomer` converts it back.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
    ...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
    ...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
    >>> scheme.name([0, 4])
    '11-00'
    """
    return "-".join(self.codes(isomer))

labels

labels(isomer) -> list

Environment label of every vertex, in vertex order (see :func:environment_label).

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
>>> scheme.labels([1, 6])
['40', '10']
Source code in cage_isomer_builder/utils/vertex_codes.py
def labels(self, isomer) -> list:
    """
    Environment label of every vertex, in vertex order (see
    :func:`environment_label`).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
    ...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
    ...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
    >>> scheme.labels([1, 6])
    ['40', '10']
    """
    return [environment_label(c) for c in self.codes(isomer)]

is_vertex_name

is_vertex_name(name: str) -> bool

True if name has the form of a vertex name of this cage (one code per vertex, one token per linker of the right width).

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
>>> scheme.is_vertex_name("40-01"), scheme.is_vertex_name("1-6")
(True, False)
Source code in cage_isomer_builder/utils/vertex_codes.py
def is_vertex_name(self, name: str) -> bool:
    """
    True if ``name`` has the form of a vertex name of this cage (one code
    per vertex, one token per linker of the right width).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
    ...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
    ...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
    >>> scheme.is_vertex_name("40-01"), scheme.is_vertex_name("1-6")
    (True, False)
    """
    return self._split(name) is not None

isomer

isomer(name: str)

The isomer with this vertex name: its sites (sorted) with one kind of group, or {"A": sites, "B": sites, ...} with several.

Raises:

Type Description
ValueError

If name is not a vertex name of this cage, or puts a group on a site the cage does not have.

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
>>> scheme.isomer("11-00"), scheme.isomer("50-00")
([0, 4], [0, 1])
Source code in cage_isomer_builder/utils/vertex_codes.py
def isomer(self, name: str):
    """
    The isomer with this vertex name: its sites (sorted) with one kind of
    group, or ``{"A": sites, "B": sites, ...}`` with several.

    Raises
    ------
    ValueError
        If ``name`` is not a vertex name of this cage, or puts a group on
        a site the cage does not have.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
    ...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
    ...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
    >>> scheme.isomer("11-00"), scheme.isomer("50-00")
    ([0, 4], [0, 1])
    """
    split = self._split(name)
    if split is None:
        raise ValueError(
            f"{name!r} is not a vertex name of this cage: expected {self.n_vertices} "
            "codes, one token per linker (digits 0, 1, 4, 5, or pairs of group "
            "letters and 0).")
    letters, tokens = split
    groups = {}
    for v, (toks, linkers) in enumerate(zip(tokens, self.vertex_linkers)):
        for tok, L in zip(toks, linkers):
            if letters:
                pairs = [(tok[i], tok[i + 1]) for i in range(0, len(tok), 2)]
                marks = [(c, side, k) for k, pair in enumerate(pairs, 1)
                         for c, side in zip(pair, (1, 4)) if c != "0"]
            else:
                marks = [("A", side, k) for k, d in enumerate(tok, 1)
                         for side in (1, 4) if int(d) & {1: 1, 4: 4}[side]]
            for c, side, k in marks:
                s = self._position.get((L, v, side, k))
                if s is None:
                    raise ValueError(f"{name!r} puts a group on a site that linker {L} "
                                     f"does not have (vertex {v}, depth {k}).")
                groups.setdefault(c, []).append(s)
    if not letters:
        return sorted(groups.get("A", []))
    top = max((LETTERS.index(c) for c in groups), default=-1)
    return {LETTERS[i]: sorted(groups.get(LETTERS[i], [])) for i in range(top + 1)}

resolve

resolve(name)

The isomer given by its vertex name ("000-100-141-401"), its site name ("0-4-9-13-16-22"), an R-group isomer name ("NH2-0-5_OH-1-6"), its list of sites or {group: sites}: sorted sites, or {group: sorted sites} for several kinds.

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
>>> scheme.resolve([6, 1]), scheme.resolve("1-6"), scheme.resolve("40-01")
([1, 6], [1, 6], [1, 6])
>>> scheme.resolve("NH2-0_OH-1-6")
{'NH2': [0], 'OH': [1, 6]}
Source code in cage_isomer_builder/utils/vertex_codes.py
def resolve(self, name):
    """
    The isomer given by its vertex name (``"000-100-141-401"``), its
    site name (``"0-4-9-13-16-22"``), an R-group isomer name
    (``"NH2-0-5_OH-1-6"``), its list of sites or ``{group: sites}``:
    sorted sites, or ``{group: sorted sites}`` for several kinds.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
    ...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
    ...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
    >>> scheme.resolve([6, 1]), scheme.resolve("1-6"), scheme.resolve("40-01")
    ([1, 6], [1, 6], [1, 6])
    >>> scheme.resolve("NH2-0_OH-1-6")
    {'NH2': [0], 'OH': [1, 6]}
    """
    if hasattr(name, "to_dict"):
        name = name.to_dict()
    if isinstance(name, dict):
        out = {k: sorted(int(s) for s in v) for k, v in name.items()}
    elif not isinstance(name, str):
        out = sorted(int(s) for s in name)
    elif self.is_vertex_name(name):
        return self.isomer(name)
    else:
        try:
            out = sorted(int(s) for s in name.split("-")) if name else []
        except ValueError:
            try:
                out = _parse_rgroup_name(name)
            except ValueError:
                raise ValueError(f"{name!r} is neither a vertex name nor a site "
                                 "name.") from None
    self._occupancy(out)
    return out

to_info

to_info() -> dict

The scheme as text entries for a structure's info, so an isomer file carries what it takes to convert between its names (:meth:from_info reads them back).

  • vertex_order: each vertex's linkers in reading order ("0:0,1,2 1:0,4,3": vertex 1 reads linker 0, then 4, then 3),
  • linker_sites: the sites of each linker ("0:0-3 1:4-7"),
  • site_codes: site:vertex/digit for every site ("9:2/1": site 9 is next to vertex 2, on the left), with /depth added beyond the first depth ("9:2/1/2").

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
>>> info = scheme.to_info()
>>> info["vertex_order"], info["linker_sites"]
('0:0,1 1:0,1', '0:0-3 1:4-7')
>>> info["site_codes"]
'0:0/1 1:0/4 2:1/1 3:1/4 4:0/1 5:0/4 6:1/1 7:1/4'
>>> VertexScheme.from_info(info) == scheme
True
Source code in cage_isomer_builder/utils/vertex_codes.py
def to_info(self) -> dict:
    """
    The scheme as text entries for a structure's ``info``, so an isomer
    file carries what it takes to convert between its names
    (:meth:`from_info` reads them back).

    * ``vertex_order``: each vertex's linkers in reading order
      (``"0:0,1,2 1:0,4,3"``: vertex 1 reads linker 0, then 4, then 3),
    * ``linker_sites``: the sites of each linker (``"0:0-3 1:4-7"``),
    * ``site_codes``: ``site:vertex/digit`` for every site
      (``"9:2/1"``: site 9 is next to vertex 2, on the left), with
      ``/depth`` added beyond the first depth (``"9:2/1/2"``).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> scheme = VertexScheme(((0, 1), (0, 1)), ((0, 1, 2, 3), (4, 5, 6, 7)),
    ...                       {0: (0, 1), 1: (0, 4), 2: (1, 1), 3: (1, 4),
    ...                        4: (0, 1), 5: (0, 4), 6: (1, 1), 7: (1, 4)})
    >>> info = scheme.to_info()
    >>> info["vertex_order"], info["linker_sites"]
    ('0:0,1 1:0,1', '0:0-3 1:4-7')
    >>> info["site_codes"]
    '0:0/1 1:0/4 2:1/1 3:1/4 4:0/1 5:0/4 6:1/1 7:1/4'
    >>> VertexScheme.from_info(info) == scheme
    True
    """
    return {
        "vertex_order": " ".join(f"{v}:{','.join(map(str, ls))}"
                                 for v, ls in enumerate(self.vertex_linkers)),
        "linker_sites": " ".join(f"{L}:{_format_ranges(ss)}"
                                 for L, ss in enumerate(self.linker_sites)),
        "site_codes": " ".join(
            f"{s}:{v}/{d}" + (f"/{k}" if k > 1 else "")
            for s, (v, d, k) in sorted((s, self.view(s)) for s in self.site_codes)),
    }

from_info classmethod

from_info(info: dict) -> VertexScheme

Read the scheme back from a structure's info (see :meth:to_info), e.g. from an isomer file written by :meth:~cage_isomer_builder.cage.base.CageBuilder.enumerate_isomers.

Raises:

Type Description
ValueError

If info has no vertex scheme or it cannot be read.

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> scheme = VertexScheme.from_info({
...     "vertex_order": "0:0,1 1:0,1", "linker_sites": "0:0-3 1:4-7",
...     "site_codes": "0:0/1 1:0/4 2:1/1 3:1/4 4:0/1 5:0/4 6:1/1 7:1/4"})
>>> scheme.name([1, 6])
'40-01'
>>> VertexScheme.from_info({"isomer": "1-6"})
Traceback (most recent call last):
...
ValueError: no vertex scheme (vertex_order, linker_sites, site_codes) in this structure: ...
Source code in cage_isomer_builder/utils/vertex_codes.py
@classmethod
def from_info(cls, info: dict) -> "VertexScheme":
    """
    Read the scheme back from a structure's ``info`` (see
    :meth:`to_info`), e.g. from an isomer file written by
    :meth:`~cage_isomer_builder.cage.base.CageBuilder.enumerate_isomers`.

    Raises
    ------
    ValueError
        If ``info`` has no vertex scheme or it cannot be read.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> scheme = VertexScheme.from_info({
    ...     "vertex_order": "0:0,1 1:0,1", "linker_sites": "0:0-3 1:4-7",
    ...     "site_codes": "0:0/1 1:0/4 2:1/1 3:1/4 4:0/1 5:0/4 6:1/1 7:1/4"})
    >>> scheme.name([1, 6])
    '40-01'
    >>> VertexScheme.from_info({"isomer": "1-6"})
    Traceback (most recent call last):
    ...
    ValueError: no vertex scheme (vertex_order, linker_sites, site_codes) in this structure: ...
    """
    missing = [k for k in ("vertex_order", "linker_sites", "site_codes") if k not in info]
    if missing:
        raise ValueError(
            f"no vertex scheme ({', '.join(missing)}) in this structure: write it with "
            "enumerate_isomers() from a cage that has vertex codes.")
    try:
        vertex_linkers = {}
        for item in str(info["vertex_order"]).split():
            v, ls = item.split(":")
            vertex_linkers[int(v)] = tuple(int(L) for L in ls.split(",") if L)
        linker_sites = {}
        for item in str(info["linker_sites"]).split():
            L, ss = item.split(":")
            linker_sites[int(L)] = _parse_ranges(ss)
        site_codes = {}
        for item in str(info["site_codes"]).split():
            s, code = item.split(":")
            parts = [int(x) for x in code.split("/")]
            if len(parts) not in (2, 3) or (len(parts) == 3 and parts[2] == 1):
                raise ValueError(f"bad site code {item!r}")
            site_codes[int(s)] = tuple(parts)
        return cls(vertex_linkers=tuple(vertex_linkers[v] for v in range(len(vertex_linkers))),
                   linker_sites=tuple(linker_sites[L] for L in range(len(linker_sites))),
                   site_codes=site_codes)
    except (ValueError, KeyError) as exc:
        raise ValueError(f"cannot read the vertex scheme of this structure: {exc}") from None

environment_label

environment_label(code: str) -> str

The environment label of a vertex code: its rotation (by whole linkers) that sorts first with 5 < 1 < 4 < 0, or A < B < ... < 0.

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import environment_label
>>> environment_label("141"), environment_label("401"), environment_label("041")
('114', '140', '104')
>>> environment_label("00.10.05"), environment_label("0B.A0.00")
('10.05.00', 'A0.00.0B')
Source code in cage_isomer_builder/utils/vertex_codes.py
def environment_label(code: str) -> str:
    """
    The environment label of a vertex code: its rotation (by whole
    linkers) that sorts first with 5 < 1 < 4 < 0, or A < B < ... < 0.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import environment_label
    >>> environment_label("141"), environment_label("401"), environment_label("041")
    ('114', '140', '104')
    >>> environment_label("00.10.05"), environment_label("0B.A0.00")
    ('10.05.00', 'A0.00.0B')
    """
    _check_code(code)
    tokens = _tokens(code)
    rotations = [_join(tokens[i:] + tokens[:i]) for i in range(len(tokens))]
    return min(rotations, key=lambda r: (_key(r), r))

mirror_code

mirror_code(code: str) -> str

The code of the mirror image of a vertex, read from the same linker: left and right swap (1 <-> 4, or the two characters of each pair) and the linkers are read the other way round.

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import mirror_code
>>> mirror_code("140"), mirror_code("10.00.05"), mirror_code("A0.0B.00")
('014', '05.00.40', '00.B0.0A')
Source code in cage_isomer_builder/utils/vertex_codes.py
def mirror_code(code: str) -> str:
    """
    The code of the mirror image of a vertex, read from the same linker:
    left and right swap (1 <-> 4, or the two characters of each pair) and
    the linkers are read the other way round.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import mirror_code
    >>> mirror_code("140"), mirror_code("10.00.05"), mirror_code("A0.0B.00")
    ('014', '05.00.40', '00.B0.0A')
    """
    _check_code(code)
    letters = any(c in LETTERS for c in code)
    return _join([_mirror_token(t, letters) for t in reversed(_tokens(code))])

mirror_label

mirror_label(code: str) -> str

Environment label of the mirror image of a vertex (see :func:mirror_code).

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import mirror_label
>>> mirror_label("114"), mirror_label("110"), mirror_label("140")
('144', '440', '140')
>>> mirror_label("A0.0B.00")
'B0.0A.00'
Source code in cage_isomer_builder/utils/vertex_codes.py
def mirror_label(code: str) -> str:
    """
    Environment label of the mirror image of a vertex (see
    :func:`mirror_code`).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import mirror_label
    >>> mirror_label("114"), mirror_label("110"), mirror_label("140")
    ('144', '440', '140')
    >>> mirror_label("A0.0B.00")
    'B0.0A.00'
    """
    return environment_label(mirror_code(code))

environments

environments(n_linkers: int = 3) -> list

Every environment label of a vertex with n_linkers linkers, one group per linker on four-site linkers, sorted with 1 < 4 < 0.

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import environments
>>> labels = environments(3)
>>> len(labels), labels
(11, ['111', '114', '110', '144', '140', '104', '100', '444', '440', '400', '000'])
Source code in cage_isomer_builder/utils/vertex_codes.py
def environments(n_linkers: int = 3) -> list:
    """
    Every environment label of a vertex with ``n_linkers`` linkers, one
    group per linker on four-site linkers, sorted with 1 < 4 < 0.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import environments
    >>> labels = environments(3)
    >>> len(labels), labels
    (11, ['111', '114', '110', '144', '140', '104', '100', '444', '440', '400', '000'])
    """
    labels = {environment_label("".join(w)) for w in product(DIGITS, repeat=n_linkers)}
    return sorted(labels, key=_key)

site_name

site_name(isomer) -> str

Site name of an isomer, as isomer files are named: its sites joined by -, or {group: sites} as NH2-0-5_OH-1 (bare if empty).

Examples:

>>> from cage_isomer_builder.utils.vertex_codes import site_name
>>> site_name([0, 4, 9]), site_name({"NH2": [0, 5], "OH": [1]})
('0-4-9', 'NH2-0-5_OH-1')
Source code in cage_isomer_builder/utils/vertex_codes.py
def site_name(isomer) -> str:
    """
    Site name of an isomer, as isomer files are named: its sites joined by
    ``-``, or ``{group: sites}`` as ``NH2-0-5_OH-1`` (``bare`` if empty).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_codes import site_name
    >>> site_name([0, 4, 9]), site_name({"NH2": [0, 5], "OH": [1]})
    ('0-4-9', 'NH2-0-5_OH-1')
    """
    if not isinstance(isomer, dict):
        return "-".join(map(str, isomer))
    parts = ["-".join([name] + [str(s) for s in sites]) for name, sites in isomer.items()]
    return "_".join(parts) if parts else "bare"

scheme_from_geometry

scheme_from_geometry(site_positions, linker_sites, linker_vertices, linker_centres, vertex_centres, centre, tol: float = 0.2, midway: float = 0.02) -> VertexScheme

Work out the vertex scheme of a cage from its geometry.

Every site is next to the closer of the linker's two vertices; the sites on one side next to one vertex get depths 1, 2, ... from the closest. Linkers may have any number of sites.

Parameters:

Name Type Description Default
site_positions (array, shape(n_sites, 3))
required
linker_sites sequence of sequence of int

The sites of each linker.

required
linker_vertices sequence of (int, int)

The two vertices each linker joins.

required
linker_centres (array, shape(n, 3))
required
vertex_centres (array, shape(n, 3))
required
centre (array, shape(3))

Pore centre: left, right and clockwise are as seen from here.

required
tol float

Smallest sine of the angle that still tells left from right, or one linker from the next around a vertex.

0.2
midway float

Smallest difference (relative to the linker length) between a site's distances to the two vertices, or between two sites on one side: closer is ambiguous.

0.02

Raises:

Type Description
ValueError

If a site is neither left nor right, or midway between the vertices, two sites on one side cannot be ordered, or the linkers of a vertex cannot be put in order around it.

Examples:

One linker along z from vertex 0 (bottom) to vertex 1, its ring facing a pore centre at -x. Looking from there with vertex 0 at the bottom, -y is on the right; turned round for vertex 1, +y is:

>>> import numpy as np
>>> from cage_isomer_builder.utils.vertex_codes import scheme_from_geometry
>>> sites = np.array([[0, -1, -1], [0, -1, 1], [0, 1, 1], [0, 1, -1]], float)
>>> scheme = scheme_from_geometry(sites, [[0, 1, 2, 3]], [(0, 1)], [[0, 0, 0]],
...                               [[0, 0, -3], [0, 0, 3]], [-5, 0, 0])
>>> scheme.site_codes
{0: (0, 4), 1: (1, 1), 2: (1, 4), 3: (0, 1)}

A biphenyl: two sites on each side at each end, the outer ones at depth 2:

>>> sites = np.array([[0, y, z] for z in (-3, -1, 1, 3) for y in (-1, 1)], float)
>>> scheme = scheme_from_geometry(sites, [range(8)], [(0, 1)], [[0, 0, 0]],
...                               [[0, 0, -5], [0, 0, 5]], [-5, 0, 0])
>>> [scheme.view(s) for s in range(4)]
[(0, 4, 1), (0, 1, 1), (0, 4, 2), (0, 1, 2)]
Source code in cage_isomer_builder/utils/vertex_codes.py
def scheme_from_geometry(site_positions, linker_sites, linker_vertices, linker_centres,
                         vertex_centres, centre, tol: float = 0.2,
                         midway: float = 0.02) -> VertexScheme:
    """
    Work out the vertex scheme of a cage from its geometry.

    Every site is next to the closer of the linker's two vertices; the
    sites on one side next to one vertex get depths 1, 2, ... from the
    closest. Linkers may have any number of sites.

    Parameters
    ----------
    site_positions : array, shape (n_sites, 3)
    linker_sites : sequence of sequence of int
        The sites of each linker.
    linker_vertices : sequence of (int, int)
        The two vertices each linker joins.
    linker_centres, vertex_centres : array, shape (n, 3)
    centre : array, shape (3,)
        Pore centre: left, right and clockwise are as seen from here.
    tol : float, default 0.2
        Smallest sine of the angle that still tells left from right, or one
        linker from the next around a vertex.
    midway : float, default 0.02
        Smallest difference (relative to the linker length) between a
        site's distances to the two vertices, or between two sites on one
        side: closer is ambiguous.

    Raises
    ------
    ValueError
        If a site is neither left nor right, or midway between the
        vertices, two sites on one side cannot be ordered, or the linkers of
        a vertex cannot be put in order around it.

    Examples
    --------
    One linker along z from vertex 0 (bottom) to vertex 1, its ring facing a
    pore centre at -x. Looking from there with vertex 0 at the bottom, -y
    is on the right; turned round for vertex 1, +y is:

    >>> import numpy as np
    >>> from cage_isomer_builder.utils.vertex_codes import scheme_from_geometry
    >>> sites = np.array([[0, -1, -1], [0, -1, 1], [0, 1, 1], [0, 1, -1]], float)
    >>> scheme = scheme_from_geometry(sites, [[0, 1, 2, 3]], [(0, 1)], [[0, 0, 0]],
    ...                               [[0, 0, -3], [0, 0, 3]], [-5, 0, 0])
    >>> scheme.site_codes
    {0: (0, 4), 1: (1, 1), 2: (1, 4), 3: (0, 1)}

    A biphenyl: two sites on each side at each end, the outer ones at depth 2:

    >>> sites = np.array([[0, y, z] for z in (-3, -1, 1, 3) for y in (-1, 1)], float)
    >>> scheme = scheme_from_geometry(sites, [range(8)], [(0, 1)], [[0, 0, 0]],
    ...                               [[0, 0, -5], [0, 0, 5]], [-5, 0, 0])
    >>> [scheme.view(s) for s in range(4)]
    [(0, 4, 1), (0, 1, 1), (0, 4, 2), (0, 1, 2)]
    """
    site_positions = np.asarray(site_positions, float)
    linker_centres = np.asarray(linker_centres, float)
    vertex_centres = np.asarray(vertex_centres, float)
    centre = np.asarray(centre, float)
    n_vertices = len(vertex_centres)

    site_codes = {}
    for L, (sites, (va, vb)) in enumerate(zip(linker_sites, linker_vertices)):
        lc = linker_centres[L]
        out = lc - centre
        length = np.linalg.norm(vertex_centres[vb] - vertex_centres[va])
        by_side = {}                     # (vertex, digit) -> [(distance, site)]
        for s in sites:
            p = site_positions[s]
            da = np.linalg.norm(p - vertex_centres[va])
            db = np.linalg.norm(p - vertex_centres[vb])
            if abs(da - db) < midway * length:
                raise ValueError(
                    f"site {s} of linker {L} lies midway between its two vertices, so it "
                    "is next to neither.")
            near, far, dist = (va, vb, da) if da < db else (vb, va, db)
            up = vertex_centres[far] - vertex_centres[near]
            r = p - lc
            side = np.dot(np.cross(up, r), out) / (
                np.linalg.norm(up) * np.linalg.norm(r) * np.linalg.norm(out))
            if abs(side) < tol:
                raise ValueError(
                    f"site {s} of linker {L} lies in the plane through the linker and the "
                    "pore centre, so it is neither left nor right.")
            by_side.setdefault((near, 4 if side > 0 else 1), []).append((dist, int(s)))
        for (near, digit), entries in by_side.items():
            entries.sort()
            for (d1, s1), (d2, s2) in zip(entries, entries[1:]):
                if d2 - d1 < midway * length:
                    raise ValueError(
                        f"sites {s1} and {s2} of linker {L} are on the same side at the "
                        "same distance from their vertex, so they have no order.")
            for depth, (_, s) in enumerate(entries, 1):
                site_codes[s] = (int(near), digit) if depth == 1 else (int(near), digit, depth)
    site_codes = dict(sorted(site_codes.items()))

    vertex_linkers = []
    for v in range(n_vertices):
        linkers = sorted(L for L, pair in enumerate(linker_vertices) if v in pair)
        if not linkers:
            vertex_linkers.append(())
            continue
        axis = vertex_centres[v] - centre
        axis /= np.linalg.norm(axis)
        flat = {}
        for L in linkers:
            w = linker_centres[L] - vertex_centres[v]
            w = w - np.dot(w, axis) * axis
            flat[L] = w / np.linalg.norm(w)
        e1 = flat[linkers[0]]
        e2 = np.cross(axis, e1)
        # Counter-clockwise seen from outside is clockwise seen from the pore centre.
        angle = {L: np.arctan2(flat[L] @ e2, flat[L] @ e1) % (2 * np.pi) for L in linkers}
        ordered = sorted(linkers, key=angle.get)
        # The anchor's angle is 0, or just under 2 pi after rounding: start there.
        start = ordered.index(linkers[0])
        ordered = ordered[start:] + ordered[:start]
        gaps = [np.cross(flat[a], flat[b]) @ axis
                for a, b in zip(ordered, ordered[1:] + ordered[:1])]
        if len(linkers) > 2 and min(abs(g) for g in gaps) < tol:
            raise ValueError(f"the linkers of vertex {v} cannot be put in order around it.")
        vertex_linkers.append(tuple(int(L) for L in ordered))

    return VertexScheme(vertex_linkers=tuple(vertex_linkers),
                        linker_sites=tuple(tuple(int(s) for s in ss) for ss in linker_sites),
                        site_codes=site_codes)