Skip to content

Vertex-label tables

Every symmetry-unique isomer with its vertex name and environment labels, for a built cage or an ideal polyhedron: cage_isomer_builder.utils.vertex_table.

Vertex-label tables: every symmetry-unique isomer, with the vertex name and environment labels of each (see :mod:cage_isomer_builder.utils.vertex_codes), for statistics over vertex environments. One group per linker by default; groups and linker_patterns place several groups, or several kinds, per linker, as in :meth:~cage_isomer_builder.cage.base.CageBuilder.enumerate_rgroup_isomers.

Works for any cage whose vertex scheme is known:

  • an ideal polyhedron (:func:ideal_cage): a named one (:data:POLYHEDRA) or any vertex coordinates, with a linker on every edge lying flat on the cage (perpendicular to the radial direction): a four-site ring, or any sites (:data:LINKERS);
  • a built cage: :meth:~cage_isomer_builder.cage.base.CageBuilder.vertex_table.

Symmetry-equivalent placements are one isomer, mirror images included; each is represented by the placement with the smallest index (linker 0 the most significant base-4 digit), as in :meth:~cage_isomer_builder.cage.base.CageBuilder.enumerate_isomers. A chiral isomer therefore appears once, in one hand: its mirror_labels give the other hand's labels, and an operation is improper exactly when it swaps left and right (1 and 4) at the sites.

The enumeration checks all placements (4 ** n_linkers for one group on four-site linkers), vectorised, so it is practical up to about 16 linkers (octahedron, cube, trigonal prism, square antiprism), not for the icosahedron or dodecahedron (30 linkers). For any size, without enumerating:

  • :func:count_isomers counts the isomers and :func:count_environments the vertex environments over all isomers, exactly (Burnside's lemma);
  • :func:sample_labels estimates the distribution of label multisets from random placements, weighted by their stabiliser sizes so that the sample is uniform over isomers, with standard errors.

SiteSymmetry dataclass

SiteSymmetry(scheme: VertexScheme, perms: ndarray, improper: ndarray, group: str = '', layout: Optional[SlotLayout] = None)

A vertex scheme with the symmetry operations of its cage.

Attributes:

Name Type Description
scheme VertexScheme
perms np.ndarray, shape (|G|, n_sites)

perms[g, s] is the site that operation g sends site s to. Row 0 is the identity.

improper np.ndarray of bool, shape (|G|,)

True for the operations that swap left and right (reflections, inversion, improper rotations).

group str

Schoenflies symbol, when known ("" otherwise).

layout (SlotLayout, optional)

Linker types (:class:~cage_isomer_builder.utils.rgroup.SlotLayout), for groups or linker_patterns given per type. Default: one type per number of sites.

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage
>>> cage = ideal_cage("tetrahedron")
>>> cage.group, cage.order, cage.n_linkers, int(cage.improper.sum())
('Td', 24, 6, 12)

order property

order: int

Number of operations, including the identity.

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage
>>> ideal_cage("octahedron").order
48

n_linkers property

n_linkers: int

Number of linkers (edges).

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage
>>> ideal_cage("cube").n_linkers
12

from_permutations classmethod

from_permutations(scheme: VertexScheme, perms, group: str = '', layout: Optional[SlotLayout] = None) -> SiteSymmetry

Build from site permutations (identity included or not); which ones are improper is read from the scheme: they send every left site to a right one.

Raises:

Type Description
ValueError

If an operation keeps some sites' sides and swaps others', or the permutations do not move whole linkers.

Examples:

Two vertices joined by two linkers; swapping the linkers keeps left and right, the swap of the two ends of each linker does not:

>>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
>>> from cage_isomer_builder.utils.vertex_table import SiteSymmetry
>>> 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)})
>>> sym = SiteSymmetry.from_permutations(
...     scheme, [[4, 5, 6, 7, 0, 1, 2, 3], [3, 2, 1, 0, 7, 6, 5, 4]])
>>> sym.order, sym.improper.tolist()
(3, [False, False, True])
Source code in cage_isomer_builder/utils/vertex_table.py
@classmethod
def from_permutations(cls, scheme: VertexScheme, perms, group: str = "",
                      layout: Optional[SlotLayout] = None) -> "SiteSymmetry":
    """
    Build from site permutations (identity included or not); which ones
    are improper is read from the scheme: they send every left site to
    a right one.

    Raises
    ------
    ValueError
        If an operation keeps some sites' sides and swaps others', or the
        permutations do not move whole linkers.

    Examples
    --------
    Two vertices joined by two linkers; swapping the linkers keeps left
    and right, the swap of the two ends of each linker does not:

    >>> from cage_isomer_builder.utils.vertex_codes import VertexScheme
    >>> from cage_isomer_builder.utils.vertex_table import SiteSymmetry
    >>> 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)})
    >>> sym = SiteSymmetry.from_permutations(
    ...     scheme, [[4, 5, 6, 7, 0, 1, 2, 3], [3, 2, 1, 0, 7, 6, 5, 4]])
    >>> sym.order, sym.improper.tolist()
    (3, [False, False, True])
    """
    n = len(scheme.site_codes)
    rows = [tuple(range(n))]
    for p in perms:
        p = tuple(int(s) for s in p)
        if p not in rows:
            rows.append(p)
    perms = np.array(rows, dtype=np.int64)
    linker_of = {s: L for L, ss in enumerate(scheme.linker_sites) for s in ss}
    improper = []
    for p in perms:
        swaps = {scheme.site_codes[s][1] != scheme.site_codes[int(p[s])][1] for s in range(n)}
        if len(swaps) != 1:
            raise ValueError("an operation swaps left and right at some sites only: "
                             "the permutations are not symmetry operations of this scheme.")
        for ss in scheme.linker_sites:
            if len({linker_of[int(p[s])] for s in ss}) != 1:
                raise ValueError("an operation splits the sites of a linker.")
        improper.append(swaps.pop())
    return cls(scheme, perms, np.array(improper), group, layout)

VertexTable dataclass

VertexTable(sym: SiteSymmetry, indices: ndarray, achiral: ndarray, groups: Union[str, list, dict] = 'A', linker_patterns: Optional[dict] = None)

The symmetry-unique isomers of a cage, kept as placement indices: names and labels are worked out on request, and the counts in vectorised chunks, so tables of hundreds of millions of isomers fit in memory.

Attributes:

Name Type Description
sym SiteSymmetry
indices np.ndarray of int64

Placement index of each isomer (see :func:unique_placements).

achiral np.ndarray of bool
groups, linker_patterns

What goes on the linkers (see :func:count_isomers).

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
>>> table = vertex_table(ideal_cage("tetrahedron"))
>>> len(table), table.site_name(0), table.name(0), table.labels(0)
(176, '0-4-8-12-16-20', '111-011-001-000', '111-110-100-000')
>>> table.mirror_labels(0), bool(table.achiral[0])
('444-440-400-000', False)

Two groups on every linker, and one A and one B:

>>> vertex_table(ideal_cage("tetrahedron"), groups="AA").name(0)
'000-500-550-555'
>>> ab = vertex_table(ideal_cage("tetrahedron"), groups="AB")
>>> ab.site_name(0)
'A-2-6-10-14-18-22_B-3-7-11-15-19-23'
>>> ab.name(0)
'00.00.00-AB.00.00-AB.AB.00-AB.AB.AB'

isomer

isomer(i: int)

Sites of isomer i, sorted (one kind of group), or {group: sites} (several kinds).

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
>>> vertex_table(ideal_cage("tetrahedron")).isomer(1)
[0, 4, 8, 12, 16, 21]
Source code in cage_isomer_builder/utils/vertex_table.py
def isomer(self, i: int):
    """
    Sites of isomer ``i``, sorted (one kind of group), or
    ``{group: sites}`` (several kinds).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
    >>> vertex_table(ideal_cage("tetrahedron")).isomer(1)
    [0, 4, 8, 12, 16, 21]
    """
    return self._space.isomer(self._states(slice(i, i + 1))[0])

site_name

site_name(i: int) -> str

Site name of isomer i, as in the isomer file names (0-4-8-12-16-21, or A-0-4_B-1-5 for several kinds).

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
>>> vertex_table(ideal_cage("tetrahedron")).site_name(1)
'0-4-8-12-16-21'
Source code in cage_isomer_builder/utils/vertex_table.py
def site_name(self, i: int) -> str:
    """
    Site name of isomer ``i``, as in the isomer file names
    (``0-4-8-12-16-21``, or ``A-0-4_B-1-5`` for several kinds).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
    >>> vertex_table(ideal_cage("tetrahedron")).site_name(1)
    '0-4-8-12-16-21'
    """
    return site_name(self.isomer(i))

name

name(i: int) -> str

Vertex name of isomer i (anchored codes in vertex order).

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
>>> table = vertex_table(ideal_cage("tetrahedron"))
>>> table.name(1) == table.sym.scheme.name(table.isomer(1))
True
Source code in cage_isomer_builder/utils/vertex_table.py
def name(self, i: int) -> str:
    """
    Vertex name of isomer ``i`` (anchored codes in vertex order).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
    >>> table = vertex_table(ideal_cage("tetrahedron"))
    >>> table.name(1) == table.sym.scheme.name(table.isomer(1))
    True
    """
    return self.sym.scheme.name(self.isomer(i))

labels

labels(i: int) -> str

Environment labels of isomer i, sorted with 5 < 1 < 4 < 0 (A < B < ... < 0): its multiset of vertex environments.

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
>>> vertex_table(ideal_cage("octahedron")).labels(0)
'1111-1110-1100-1100-1000-0000'
Source code in cage_isomer_builder/utils/vertex_table.py
def labels(self, i: int) -> str:
    """
    Environment labels of isomer ``i``, sorted with 5 < 1 < 4 < 0 (A < B
    < ... < 0): its multiset of vertex environments.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
    >>> vertex_table(ideal_cage("octahedron")).labels(0)
    '1111-1110-1100-1100-1000-0000'
    """
    return self._codes.display(self._codes.label_ids(self._states(slice(i, i + 1)))[0][0])

mirror_labels

mirror_labels(i: int) -> str

The labels of the mirror image of isomer i (left and right swapped, linkers read the other way round).

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
>>> vertex_table(ideal_cage("octahedron")).mirror_labels(0)
'4444-4440-4400-4400-4000-0000'
Source code in cage_isomer_builder/utils/vertex_table.py
def mirror_labels(self, i: int) -> str:
    """
    The labels of the mirror image of isomer ``i`` (left and right
    swapped, linkers read the other way round).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
    >>> vertex_table(ideal_cage("octahedron")).mirror_labels(0)
    '4444-4440-4400-4400-4000-0000'
    """
    return self._codes.display(self._codes.label_ids(self._states(slice(i, i + 1)))[1][0])

label_counts

label_counts(merge_mirrors: bool = False) -> Counter

Number of isomers with each label multiset, most common first. With merge_mirrors, a multiset and its mirror image count together (under the one of the two that sorts first), so the result does not depend on which hand represents each chiral isomer.

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
>>> table = vertex_table(ideal_cage("tetrahedron"))
>>> len(table.label_counts()), len(table.label_counts(merge_mirrors=True))
(55, 54)
>>> table.label_counts().most_common(1)
[('110-140-100-400', 8)]
Source code in cage_isomer_builder/utils/vertex_table.py
def label_counts(self, merge_mirrors: bool = False) -> Counter:
    """
    Number of isomers with each label multiset, most common first.
    With ``merge_mirrors``, a multiset and its mirror image count
    together (under the one of the two that sorts first), so the result
    does not depend on which hand represents each chiral isomer.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
    >>> table = vertex_table(ideal_cage("tetrahedron"))
    >>> len(table.label_counts()), len(table.label_counts(merge_mirrors=True))
    (55, 54)
    >>> table.label_counts().most_common(1)
    [('110-140-100-400', 8)]
    """
    counts = Counter()
    for sl in self._chunks():
        states = self._states(sl)
        if merge_mirrors:
            rows = _merged_rows(self._codes, states)
        else:
            rows = np.sort(self._codes.label_ids(states)[0], axis=1)
        uniq, n = np.unique(rows, axis=0, return_counts=True)
        counts.update({tuple(u): int(c) for u, c in zip(uniq.tolist(), n)})
    shown = {self._codes.display(row, merge_mirrors): n for row, n in counts.items()}
    order = sorted(shown, key=lambda s: (-shown[s], [_lab_key(x) for x in s.split("-")]))
    return Counter({s: shown[s] for s in order})

environment_counts

environment_counts(both_hands: bool = False) -> Counter

How often each vertex environment occurs, over all vertices of all isomers, in label order. With both_hands every isomer counts in both hands, which makes mirror-image environments (114 and 144, ...) equally common.

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
>>> counts = vertex_table(ideal_cage("tetrahedron")).environment_counts(both_hands=True)
>>> counts["114"] == counts["144"], sum(counts.values())
(True, 1408)
Source code in cage_isomer_builder/utils/vertex_table.py
def environment_counts(self, both_hands: bool = False) -> Counter:
    """
    How often each vertex environment occurs, over all vertices of all
    isomers, in label order. With ``both_hands`` every isomer counts in
    both hands, which makes mirror-image environments (114 and 144, ...)
    equally common.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
    >>> counts = vertex_table(ideal_cage("tetrahedron")).environment_counts(both_hands=True)
    >>> counts["114"] == counts["144"], sum(counts.values())
    (True, 1408)
    """
    total = Counter()
    for sl in self._chunks():
        lab, mir = self._codes.label_ids(self._states(sl))
        total.update(Counter(lab.ravel().tolist()))
        if both_hands:
            total.update(Counter(mir.ravel().tolist()))
    names = {self._codes.label_names[i]: n for i, n in total.items() if n}
    return Counter({k: names[k] for k in sorted(names, key=_lab_key)})

write

write(path: str) -> str

Write the table as tab-separated text (gzip-compressed if path ends in .gz): site name, vertex name, labels, mirror labels, chiral (Y/N). Returns path.

Examples:

>>> import os, tempfile
>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
>>> path = vertex_table(ideal_cage("tetrahedron")).write(
...     os.path.join(tempfile.mkdtemp(), "tet.tsv"))
>>> print(open(path).read().splitlines()[1])
0-4-8-12-16-20  111-011-001-000 111-110-100-000 444-440-400-000 Y
Source code in cage_isomer_builder/utils/vertex_table.py
def write(self, path: str) -> str:
    """
    Write the table as tab-separated text (gzip-compressed if ``path``
    ends in ``.gz``): site name, vertex name, labels, mirror labels,
    chiral (Y/N). Returns ``path``.

    Examples
    --------
    >>> import os, tempfile
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
    >>> path = vertex_table(ideal_cage("tetrahedron")).write(
    ...     os.path.join(tempfile.mkdtemp(), "tet.tsv"))
    >>> print(open(path).read().splitlines()[1])
    0-4-8-12-16-20	111-011-001-000	111-110-100-000	444-440-400-000	Y
    """
    c, space = self._codes, self._space
    nv = len(c.vertices)
    shown = {}
    opener = gzip.open if str(path).endswith(".gz") else open
    with opener(path, "wt") as fh:
        fh.write("# site_name\tvertex_name\tlabels\tmirror_labels\tchiral\n")
        for sl in self._chunks():
            states = self._states(sl)
            combos = [c.combo_ids(v, states).tolist() for v in range(nv)]
            lab, mir = c.label_ids(states)
            lab, mir = np.sort(lab, axis=1).tolist(), np.sort(mir, axis=1).tolist()
            achiral = self.achiral[sl]
            lines = []
            for r in range(len(states)):
                name = "-".join(c.code(v, combos[v][r]) for v in range(nv))
                labels = [shown.get(tuple(x)) or shown.setdefault(tuple(x), c.display(x))
                          for x in (lab[r], mir[r])]
                lines.append(f"{site_name(space.isomer(states[r]))}\t{name}\t"
                             f"{labels[0]}\t{labels[1]}\t{'N' if achiral[r] else 'Y'}\n")
            fh.writelines(lines)
    return path

LabelSample dataclass

LabelSample(sym: SiteSymmetry, n_samples: int, n_isomers: int, labels: list, fractions: ndarray, stderr: ndarray, hits: ndarray, environments: dict)

Distribution of label multisets, and environment counts, over the symmetry-unique isomers, estimated from random placements (see :func:sample_labels). Each multiset is merged with its mirror image (under the one that sorts first), so every isomer has one, whichever hand represents it.

Attributes:

Name Type Description
sym SiteSymmetry
n_samples int
n_isomers int

Exact number of isomers (:func:count_isomers).

labels list of str

The multisets seen, most common first.

fractions ndarray

Estimated fraction of isomers with each multiset (sums to 1).

stderr ndarray

Standard error of each fraction.

hits np.ndarray of int

Number of samples that gave each multiset.

environments dict

label -> (estimate, standard error) of how often each vertex environment occurs over all isomers, both hands: the estimate of :func:count_environments.

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, sample_labels
>>> sample = sample_labels(ideal_cage("icosahedron"), 20000, seed=1)
>>> sample.n_samples, sample.n_isomers, round(float(sample.fractions.sum()), 6)
(20000, 9607679214180672, 1.0)

fraction

fraction(labels: str) -> tuple

(fraction, standard error) of the isomers with a label multiset (either hand), (0.0, 0.0) if no sample gave it.

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, sample_labels
>>> sample = sample_labels(ideal_cage("tetrahedron"), 50000, seed=0)
>>> f, se = sample.fraction("110-140-100-400")
>>> abs(f - 8 / 176) < 3 * se           # exact: 8 of the 176 isomers
True
Source code in cage_isomer_builder/utils/vertex_table.py
def fraction(self, labels: str) -> tuple:
    """
    ``(fraction, standard error)`` of the isomers with a label multiset
    (either hand), ``(0.0, 0.0)`` if no sample gave it.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, sample_labels
    >>> sample = sample_labels(ideal_cage("tetrahedron"), 50000, seed=0)
    >>> f, se = sample.fraction("110-140-100-400")
    >>> abs(f - 8 / 176) < 3 * se           # exact: 8 of the 176 isomers
    True
    """
    names = sorted((environment_label(p) for p in labels.split("-")), key=_lab_key)
    mirror = sorted((mirror_label(p) for p in names), key=_lab_key)
    merged = "-".join(min(names, mirror, key=lambda ns: [_lab_key(x) for x in ns]))
    if merged in self.labels:
        i = self.labels.index(merged)
        return float(self.fractions[i]), float(self.stderr[i])
    return 0.0, 0.0

write

write(path: str) -> str

Write the distribution as tab-separated text (gzip-compressed if path ends in .gz): labels, fraction, standard error, estimated number of isomers, samples. Returns path.

Examples:

>>> import os, tempfile
>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, sample_labels
>>> path = sample_labels(ideal_cage("cube"), 1000, seed=0).write(
...     os.path.join(tempfile.mkdtemp(), "cube.tsv"))
>>> open(path).readline().split()
['#', 'labels', 'fraction', 'stderr', 'est_isomers', 'samples']
Source code in cage_isomer_builder/utils/vertex_table.py
def write(self, path: str) -> str:
    """
    Write the distribution as tab-separated text (gzip-compressed if
    ``path`` ends in ``.gz``): labels, fraction, standard error,
    estimated number of isomers, samples. Returns ``path``.

    Examples
    --------
    >>> import os, tempfile
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, sample_labels
    >>> path = sample_labels(ideal_cage("cube"), 1000, seed=0).write(
    ...     os.path.join(tempfile.mkdtemp(), "cube.tsv"))
    >>> open(path).readline().split()
    ['#', 'labels', 'fraction', 'stderr', 'est_isomers', 'samples']
    """
    opener = gzip.open if str(path).endswith(".gz") else open
    with opener(path, "wt") as fh:
        fh.write("# labels\tfraction\tstderr\test_isomers\tsamples\n")
        for lab, f, se, h in zip(self.labels, self.fractions, self.stderr, self.hits):
            fh.write(f"{lab}\t{f:.6e}\t{se:.2e}\t{f * self.n_isomers:.4g}\t{h}\n")
    return path

hull_edges

hull_edges(vertices, tol: float = 0.001) -> list

Edges of a convex polyhedron: the sides of the faces of the convex hull of vertices (coplanar hull triangles are merged into one face, so square and pentagonal faces get no diagonals).

Parameters:

Name Type Description Default
vertices (array, shape(n, 3))
required
tol float

Faces whose planes differ by less than this (relative to the size of the polyhedron) are one face.

1e-3

Raises:

Type Description
ValueError

If a vertex is not a corner of the hull.

Examples:

A triangular prism taller than it is wide: 9 edges, no square diagonals.

>>> from cage_isomer_builder.utils.vertex_table import hull_edges
>>> hull_edges([[1, 0, 1], [-0.5, 0.866, 1], [-0.5, -0.866, 1],
...             [1, 0, -1], [-0.5, 0.866, -1], [-0.5, -0.866, -1]])
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
Source code in cage_isomer_builder/utils/vertex_table.py
def hull_edges(vertices, tol: float = 1e-3) -> list:
    """
    Edges of a convex polyhedron: the sides of the faces of the convex hull
    of ``vertices`` (coplanar hull triangles are merged into one face, so
    square and pentagonal faces get no diagonals).

    Parameters
    ----------
    vertices : array, shape (n, 3)
    tol : float, default 1e-3
        Faces whose planes differ by less than this (relative to the size of
        the polyhedron) are one face.

    Raises
    ------
    ValueError
        If a vertex is not a corner of the hull.

    Examples
    --------
    A triangular prism taller than it is wide: 9 edges, no square diagonals.

    >>> from cage_isomer_builder.utils.vertex_table import hull_edges
    >>> hull_edges([[1, 0, 1], [-0.5, 0.866, 1], [-0.5, -0.866, 1],
    ...             [1, 0, -1], [-0.5, 0.866, -1], [-0.5, -0.866, -1]])
    [(0, 1), (0, 2), (0, 3), (1, 2), (1, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
    """
    from scipy.spatial import ConvexHull

    V = np.asarray(vertices, float)
    hull = ConvexHull(V)
    size = np.linalg.norm(V - V.mean(axis=0), axis=1).max()
    if len(set(hull.vertices)) != len(V):
        raise ValueError("some vertices lie inside the convex hull of the others: the cage "
                         "must be a convex polyhedron (or give the edges).")
    faces = []                      # (normal, offset, triangles)
    for tri, eq in zip(hull.simplices, hull.equations):
        for normal, offset, tris in faces:
            if np.allclose(normal, eq[:3], atol=tol) and abs(offset - eq[3]) < tol * size:
                tris.append(tri)
                break
        else:
            faces.append((eq[:3], eq[3], [tri]))
    edges = set()
    for _, _, tris in faces:
        sides = Counter(tuple(sorted((int(t[i]), int(t[(i + 1) % 3])))) for t in tris
                        for i in range(3))
        edges.update(e for e, n in sides.items() if n == 1)    # interior diagonals occur twice
    return sorted(edges)

ideal_cage

ideal_cage(polyhedron: Union[str, Sequence], edges: Optional[Sequence] = None, radius: float = 10.0, ring: float = 1.2, tol: float = 0.05, linker: Union[str, Sequence] = 'phenylene') -> SiteSymmetry

An ideal cage: a vertex at every corner of a polyhedron and a linker along every edge, its sites lying flat on the cage (perpendicular to the radial direction). For a symmetric linker the polyhedron's whole point group acts on the sites; otherwise the group the decorated cage keeps.

Parameters:

Name Type Description Default
polyhedron (str or array, shape(n_vertices, 3))

A name from :data:POLYHEDRA, or vertex coordinates (centred anywhere; the pore centre is their mean).

required
edges sequence of (int, int)

Default: the edges of the convex hull (:func:hull_edges).

None
radius float

The vertices are scaled to this mean distance from the centre.

10.0
ring float

Length unit (Angstrom) of the site offsets: a phenylene's sites are ring from the linker centre along and across the edge.

1.2
tol float

Matching tolerance (Angstrom) of the point-group detection.

0.05
linker str or sequence of (along, across)

A name from :data:LINKERS, or the site offsets.

"phenylene"

Raises:

Type Description
ValueError

For an unknown name, a site beyond the end of its edge, or a polyhedron whose linkers cannot be read left/right (see :func:~cage_isomer_builder.utils.vertex_codes.scheme_from_geometry).

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage
>>> oct_ = ideal_cage("octahedron")
>>> oct_.group, oct_.n_linkers, oct_.scheme.vertex_linkers[0]
('Oh', 12, (0, 1, 2, 3))
>>> ideal_cage("trigonal_prism").group
'D3h'
>>> bpdc = ideal_cage("tetrahedron", linker="biphenyl")
>>> bpdc.group, len(bpdc.scheme.linker_sites[0]), bpdc.scheme.depths(0, 0)
('Td', 8, 2)
>>> ideal_cage("tetrahedron", linker="fumarate").group      # trans: no mirror planes
'T'
Source code in cage_isomer_builder/utils/vertex_table.py
def ideal_cage(polyhedron: Union[str, Sequence], edges: Optional[Sequence] = None,
               radius: float = 10.0, ring: float = 1.2, tol: float = 0.05,
               linker: Union[str, Sequence] = "phenylene") -> SiteSymmetry:
    """
    An ideal cage: a vertex at every corner of a polyhedron and a linker
    along every edge, its sites lying flat on the cage (perpendicular to
    the radial direction). For a symmetric linker the polyhedron's whole
    point group acts on the sites; otherwise the group the decorated cage
    keeps.

    Parameters
    ----------
    polyhedron : str or array, shape (n_vertices, 3)
        A name from :data:`POLYHEDRA`, or vertex coordinates (centred
        anywhere; the pore centre is their mean).
    edges : sequence of (int, int), optional
        Default: the edges of the convex hull (:func:`hull_edges`).
    radius : float, default 10.0
        The vertices are scaled to this mean distance from the centre.
    ring : float, default 1.2
        Length unit (Angstrom) of the site offsets: a phenylene's sites are
        ``ring`` from the linker centre along and across the edge.
    tol : float, default 0.05
        Matching tolerance (Angstrom) of the point-group detection.
    linker : str or sequence of (along, across), default "phenylene"
        A name from :data:`LINKERS`, or the site offsets.

    Raises
    ------
    ValueError
        For an unknown name, a site beyond the end of its edge, or a
        polyhedron whose linkers cannot be read left/right (see
        :func:`~cage_isomer_builder.utils.vertex_codes.scheme_from_geometry`).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage
    >>> oct_ = ideal_cage("octahedron")
    >>> oct_.group, oct_.n_linkers, oct_.scheme.vertex_linkers[0]
    ('Oh', 12, (0, 1, 2, 3))
    >>> ideal_cage("trigonal_prism").group
    'D3h'
    >>> bpdc = ideal_cage("tetrahedron", linker="biphenyl")
    >>> bpdc.group, len(bpdc.scheme.linker_sites[0]), bpdc.scheme.depths(0, 0)
    ('Td', 8, 2)
    >>> ideal_cage("tetrahedron", linker="fumarate").group      # trans: no mirror planes
    'T'
    """
    from ase import Atoms

    from cage_isomer_builder.utils.pointgroup import detect_point_group

    if isinstance(polyhedron, str):
        if polyhedron not in POLYHEDRA:
            raise ValueError(f"polyhedron={polyhedron!r}; choose from {sorted(POLYHEDRA)} "
                             "or give vertex coordinates.")
        polyhedron = POLYHEDRA[polyhedron]
    V = np.asarray(polyhedron, float)
    V = V - V.mean(axis=0)
    V *= radius / np.linalg.norm(V, axis=1).mean()
    if edges is None:
        edges = hull_edges(V)
    edges = [tuple(sorted(map(int, e))) for e in edges]

    if isinstance(linker, str):
        if linker not in LINKERS:
            raise ValueError(f"linker={linker!r}; choose from {sorted(LINKERS)} or give "
                             "(along, across) offsets.")
        linker = LINKERS[linker]
    offsets = np.asarray(linker, float).reshape(-1, 2) * ring

    sites, centres = [], []
    for a, b in edges:
        c = (V[a] + V[b]) / 2
        half = np.linalg.norm(V[b] - V[a]) / 2
        if len(offsets) and np.abs(offsets[:, 0]).max() >= 0.9 * half:
            raise ValueError(f"a linker site lies beyond the end of edge {(a, b)}; "
                             "use a larger radius or a smaller ring.")
        u = (V[b] - V[a]) / np.linalg.norm(V[b] - V[a])
        n = c / np.linalg.norm(c)
        w = np.cross(n, u)
        for along, across in offsets:
            sites.append(c + along * u + across * w)
        centres.append(c)
    sites = np.array(sites).reshape(-1, 3)
    k = len(offsets)
    linker_sites = [range(k * L, k * L + k) for L in range(len(edges))]
    scheme = scheme_from_geometry(sites, linker_sites, edges, np.array(centres), V,
                                  np.zeros(3))

    atoms = Atoms(numbers=[40] * len(V) + [1] * len(sites), positions=np.vstack([V, sites]))
    pg = detect_point_group(atoms, tol=tol)
    perms = pg.atom_perms[:, len(V):] - len(V)
    return SiteSymmetry.from_permutations(scheme, perms, group=pg.name)

count_isomers

count_isomers(sym: SiteSymmetry, chiral: bool = False, groups='A', linker_patterns: Optional[dict] = None) -> int

Number of symmetry-unique isomers, from Burnside's lemma (no enumeration, so fine for any size).

Parameters:

Name Type Description Default
sym SiteSymmetry
required
chiral bool

Count mirror images as different isomers (proper rotations only).

False
groups

What goes on the linkers, as for :meth:~cage_isomer_builder.cage.base.CageBuilder.enumerate_rgroup_isomers: "A" (the default) one group on every linker, "AA" two, "AB" one A and one B, linker_patterns={"A": 3, "": 3} one group on three linkers, and so on.

'A'
linker_patterns

What goes on the linkers, as for :meth:~cage_isomer_builder.cage.base.CageBuilder.enumerate_rgroup_isomers: "A" (the default) one group on every linker, "AA" two, "AB" one A and one B, linker_patterns={"A": 3, "": 3} one group on three linkers, and so on.

'A'

Examples:

>>> from cage_isomer_builder.utils.vertex_table import count_isomers, ideal_cage
>>> count_isomers(ideal_cage("tetrahedron")), count_isomers(ideal_cage("octahedron"))
(176, 349928)
>>> count_isomers(ideal_cage("icosahedron"))
9607679214180672
>>> tet = ideal_cage("tetrahedron")
>>> count_isomers(tet, groups="AA"), count_isomers(tet, groups="AB")
(2013, 124464)
>>> count_isomers(tet, linker_patterns={"A": 3, "": 3})
56
Source code in cage_isomer_builder/utils/vertex_table.py
def count_isomers(sym: SiteSymmetry, chiral: bool = False, groups="A",
                  linker_patterns: Optional[dict] = None) -> int:
    """
    Number of symmetry-unique isomers, from Burnside's lemma (no
    enumeration, so fine for any size).

    Parameters
    ----------
    sym : SiteSymmetry
    chiral : bool, default False
        Count mirror images as different isomers (proper rotations only).
    groups, linker_patterns
        What goes on the linkers, as for
        :meth:`~cage_isomer_builder.cage.base.CageBuilder.enumerate_rgroup_isomers`:
        ``"A"`` (the default) one group on every linker, ``"AA"`` two,
        ``"AB"`` one A and one B, ``linker_patterns={"A": 3, "": 3}`` one
        group on three linkers, and so on.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import count_isomers, ideal_cage
    >>> count_isomers(ideal_cage("tetrahedron")), count_isomers(ideal_cage("octahedron"))
    (176, 349928)
    >>> count_isomers(ideal_cage("icosahedron"))
    9607679214180672
    >>> tet = ideal_cage("tetrahedron")
    >>> count_isomers(tet, groups="AA"), count_isomers(tet, groups="AB")
    (2013, 124464)
    >>> count_isomers(tet, linker_patterns={"A": 3, "": 3})
    56
    """
    space = _Space(sym, groups, linker_patterns)
    total = used = 0
    for op, improper in zip(space.ops, sym.improper):
        if chiral and improper:
            continue
        used += 1
        total += space.count_fixed(space.fixed_cycles(op))
    if total % used:
        raise ValueError("the operations do not form a group (Burnside sum not divisible).")
    return total // used

unique_placements

unique_placements(sym: SiteSymmetry, max_placements: int = 4 ** 16, groups='A', linker_patterns: Optional[dict] = None)

Indices of the symmetry-unique placements and whether each is achiral (left unchanged by an improper operation). Each isomer is represented as the builder's enumerations represent it: by the smallest index of its orbit (each linker's state is a digit, linker 0 the most significant; states in ascending order of their site labels, except that with one group on every linker state j is the group on site j, as in :meth:~cage_isomer_builder.cage.base.CageBuilder.enumerate_isomers), or in mixed mode by the placement whose linker patterns, then site labels, sort first, as in :meth:~cage_isomer_builder.cage.base.CageBuilder.enumerate_rgroup_isomers.

The index is split into two halves, so every operation is two table lookups and an add per placement.

Parameters:

Name Type Description Default
sym SiteSymmetry
required
max_placements int

Refuse larger enumerations (all raw placements are checked).

``4 ** 16``
groups

See :func:count_isomers.

'A'
linker_patterns

See :func:count_isomers.

'A'

Returns:

Name Type Description
indices np.ndarray of int64
achiral np.ndarray of bool

Raises:

Type Description
ValueError

If there are more than max_placements placements.

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, unique_placements
>>> idx, achiral = unique_placements(ideal_cage("tetrahedron"))
>>> len(idx), int(idx[0]), int(achiral.sum())
(176, 0, 0)
>>> len(unique_placements(ideal_cage("tetrahedron"), groups="AB")[0])
124464
Source code in cage_isomer_builder/utils/vertex_table.py
def unique_placements(sym: SiteSymmetry, max_placements: int = 4 ** 16, groups="A",
                      linker_patterns: Optional[dict] = None):
    """
    Indices of the symmetry-unique placements and whether each is achiral
    (left unchanged by an improper operation). Each isomer is represented
    as the builder's enumerations represent it: by the smallest index of its
    orbit (each linker's state is a digit, linker 0 the most significant;
    states in ascending order of their site labels, except that with one
    group on every linker state ``j`` is the group on site ``j``, as in
    :meth:`~cage_isomer_builder.cage.base.CageBuilder.enumerate_isomers`),
    or in mixed mode by the placement whose linker patterns, then site
    labels, sort first, as in
    :meth:`~cage_isomer_builder.cage.base.CageBuilder.enumerate_rgroup_isomers`.

    The index is split into two halves, so every operation is two table
    lookups and an add per placement.

    Parameters
    ----------
    sym : SiteSymmetry
    max_placements : int, default ``4 ** 16``
        Refuse larger enumerations (all raw placements are checked).
    groups, linker_patterns
        See :func:`count_isomers`.

    Returns
    -------
    indices : np.ndarray of int64
    achiral : np.ndarray of bool

    Raises
    ------
    ValueError
        If there are more than ``max_placements`` placements.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, unique_placements
    >>> idx, achiral = unique_placements(ideal_cage("tetrahedron"))
    >>> len(idx), int(idx[0]), int(achiral.sum())
    (176, 0, 0)
    >>> len(unique_placements(ideal_cage("tetrahedron"), groups="AB")[0])
    124464
    """
    space = _Space(sym, groups, linker_patterns)
    nL = space.nL
    total = space.n_valid
    if total > max_placements:
        raise ValueError(
            f"{nL} linkers give {total:.3g} placements (max_placements="
            f"{max_placements:.3g}); count_isomers() gives the number of isomers "
            f"({count_isomers(sym, groups=groups, linker_patterns=linker_patterns):.4g}) "
            "without enumerating them.")
    h = nL // 2                      # linkers 0..h-1 make the high half
    weight = space.weights()
    contribs = [[maps[L] * weight[new_L[L]] for L in range(nL)] for new_L, maps in space.ops]

    def digits(ranges):
        return np.array(list(itertools.product(*ranges)),
                        dtype=np.int64).reshape(-1, len(ranges))

    found, flags = [], []
    for ranges in space.assignments():     # one, unless mixed mode fixes pattern counts
        hi_digits, lo_digits = digits(ranges[:h]), digits(ranges[h:])
        hi_idx, lo_idx = hi_digits @ weight[:h], lo_digits @ weight[h:]
        tables = []
        for contrib in contribs:
            A = sum((contrib[L][hi_digits[:, L]] for L in range(h)),
                    np.zeros(len(hi_digits), np.int64))
            B = sum((contrib[L][lo_digits[:, i]] for i, L in enumerate(range(h, nL))),
                    np.zeros(len(lo_digits), np.int64))
            tables.append((A, B))
        rows_per_chunk = max(1, (1 << 22) // len(lo_idx))
        for start in range(0, len(hi_idx), rows_per_chunk):
            hi = np.arange(start, min(start + rows_per_chunk, len(hi_idx)))
            idx = hi_idx[hi][:, None] + lo_idx[None, :]
            canonical = np.ones(idx.shape, bool)
            achiral = np.zeros(idx.shape, bool)
            for (A, B), bad in zip(tables[1:], sym.improper[1:]):
                image = A[hi][:, None] + B[None, :]
                canonical &= idx <= image
                if bad:
                    achiral |= image == idx
            found.append(idx[canonical])
            flags.append(achiral[canonical])
    idx, achiral = np.concatenate(found), np.concatenate(flags)
    if space.constrained:
        # mixed mode: the representative enumerate_rgroup_isomers() keeps
        # (patterns compared first, then sites)
        idx = np.concatenate([space.rgroup_representatives(idx[a:a + (1 << 18)])
                              for a in range(0, len(idx), 1 << 18)] or [idx])
    order = np.argsort(idx, kind="stable")
    return idx[order], achiral[order]

vertex_table

vertex_table(sym: SiteSymmetry, max_placements: int = 4 ** 16, groups='A', linker_patterns: Optional[dict] = None) -> VertexTable

Every symmetry-unique isomer (see :class:VertexTable).

Parameters:

Name Type Description Default
sym SiteSymmetry

From :func:ideal_cage, or :meth:~cage_isomer_builder.cage.base.CageBuilder.vertex_table for a built cage.

required
max_placements int

See :func:unique_placements.

``4 ** 16``
groups

What goes on the linkers (see :func:count_isomers); one group per linker by default.

'A'
linker_patterns

What goes on the linkers (see :func:count_isomers); one group per linker by default.

'A'

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
>>> table = vertex_table(ideal_cage("octahedron"))
>>> len(table), int(table.achiral.sum())
(349928, 192)
>>> counts = table.label_counts(merge_mirrors=True)
>>> len(counts), max(counts.values()), counts["1111-1111-1111-1111-1111-1111"]
(10440, 256, 0)
Source code in cage_isomer_builder/utils/vertex_table.py
def vertex_table(sym: SiteSymmetry, max_placements: int = 4 ** 16, groups="A",
                 linker_patterns: Optional[dict] = None) -> VertexTable:
    """
    Every symmetry-unique isomer (see :class:`VertexTable`).

    Parameters
    ----------
    sym : SiteSymmetry
        From :func:`ideal_cage`, or
        :meth:`~cage_isomer_builder.cage.base.CageBuilder.vertex_table` for
        a built cage.
    max_placements : int, default ``4 ** 16``
        See :func:`unique_placements`.
    groups, linker_patterns
        What goes on the linkers (see :func:`count_isomers`); one group per
        linker by default.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, vertex_table
    >>> table = vertex_table(ideal_cage("octahedron"))
    >>> len(table), int(table.achiral.sum())
    (349928, 192)
    >>> counts = table.label_counts(merge_mirrors=True)
    >>> len(counts), max(counts.values()), counts["1111-1111-1111-1111-1111-1111"]
    (10440, 256, 0)
    """
    idx, achiral = unique_placements(sym, max_placements, groups, linker_patterns)
    return VertexTable(sym, idx, achiral, groups, linker_patterns)

count_environments

count_environments(sym: SiteSymmetry, groups='A', linker_patterns: Optional[dict] = None, max_combinations: int = 2000000) -> Counter

How often each vertex environment occurs over all vertices of all symmetry-unique isomers, every isomer counted in both hands: exact, from Burnside's lemma, without enumerating the isomers, so fine for any number of linkers. Equal to :meth:VertexTable.environment_counts with both_hands=True where a table can be built; the counts add up to 2 * n_vertices * n_isomers.

Parameters:

Name Type Description Default
sym SiteSymmetry
required
groups

What goes on the linkers (see :func:count_isomers).

'A'
linker_patterns

What goes on the linkers (see :func:count_isomers).

'A'
max_combinations int

Refuse when a vertex sees more combinations of its linkers than this (many sites and kinds of group on high-degree vertices); :func:sample_labels estimates the counts instead.

2000000

Raises:

Type Description
ValueError

If a vertex has more than max_combinations combinations.

Examples:

>>> from cage_isomer_builder.utils.vertex_table import (
...     count_environments, count_isomers, ideal_cage, vertex_table)
>>> tet = ideal_cage("tetrahedron")
>>> count_environments(tet) == vertex_table(tet).environment_counts(both_hands=True)
True
>>> ico = ideal_cage("icosahedron")
>>> counts = count_environments(ico)
>>> sum(counts.values()) == 2 * 12 * count_isomers(ico), counts["11111"]
(True, 225179981581120)
Source code in cage_isomer_builder/utils/vertex_table.py
def count_environments(sym: SiteSymmetry, groups="A", linker_patterns: Optional[dict] = None,
                       max_combinations: int = 2_000_000) -> Counter:
    """
    How often each vertex environment occurs over all vertices of all
    symmetry-unique isomers, every isomer counted in both hands: exact, from
    Burnside's lemma, without enumerating the isomers, so fine for any
    number of linkers. Equal to :meth:`VertexTable.environment_counts`
    with ``both_hands=True`` where a table can be built; the counts add up
    to ``2 * n_vertices * n_isomers``.

    Parameters
    ----------
    sym : SiteSymmetry
    groups, linker_patterns
        What goes on the linkers (see :func:`count_isomers`).
    max_combinations : int, default 2000000
        Refuse when a vertex sees more combinations of its linkers than
        this (many sites and kinds of group on high-degree vertices);
        :func:`sample_labels` estimates the counts instead.

    Raises
    ------
    ValueError
        If a vertex has more than ``max_combinations`` combinations.

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import (
    ...     count_environments, count_isomers, ideal_cage, vertex_table)
    >>> tet = ideal_cage("tetrahedron")
    >>> count_environments(tet) == vertex_table(tet).environment_counts(both_hands=True)
    True
    >>> ico = ideal_cage("icosahedron")
    >>> counts = count_environments(ico)
    >>> sum(counts.values()) == 2 * 12 * count_isomers(ico), counts["11111"]
    (True, 225179981581120)
    """
    space = _Space(sym, groups, linker_patterns)
    codes = _Codes(space)
    total = Counter()                       # label id -> Python int (no overflow)
    for op in space.ops:
        cycles = space.fixed_cycles(op)
        if any(not options for _, options in cycles):
            continue
        cycle_of = {L: c for c, (cycle, _) in enumerate(cycles) for L in cycle}
        for v, info in enumerate(codes.vertices):
            linkers = info["linkers"]
            touched = sorted({cycle_of[L] for L in linkers})
            rest = [cycles[c] for c in range(len(cycles)) if c not in touched]
            if space.constrained:
                completions = space.completions(rest)
            else:
                completions = {(): math.prod(len(o) for _, o in rest)}
            # group each touched cycle's assignments by the tokens v reads, and pattern
            grouped = []
            for c in touched:
                cycle, options = cycles[c]
                g = Counter()
                for a in options:
                    toks = tuple((i, int(info["toks"][i][a[L]]))
                                 for i, L in enumerate(linkers) if L in a)
                    g[toks, int(space.pattern[cycle[0]][a[cycle[0]]]), len(cycle)] += 1
                grouped.append(list(g.items()))
            if math.prod(len(g) for g in grouped) > max_combinations:
                raise ValueError(
                    f"vertex {v} sees more than max_combinations={max_combinations} "
                    "combinations; sample_labels() estimates the environment counts.")
            local = Counter()
            for combo in itertools.product(*grouped):
                ways = 1
                tok = [0] * len(linkers)
                used = [0] * len(space.required)
                for (toks, p, length), n in combo:
                    ways *= n
                    for i, t in toks:
                        tok[i] = t
                    used[p] += length
                if space.constrained:
                    need = tuple(r - u for r, u in zip(space.required, used))
                    if min(need) < 0:
                        continue
                    ways *= completions.get(need, 0)
                else:
                    ways *= completions[()]
                if not ways:
                    continue
                combo_id = 0
                for t, r in zip(tok, info["radices"]):
                    combo_id = combo_id * r + t
                lab, mir = codes._ids(v, combo_id)
                local[lab] += ways
                local[mir] += ways
            total.update(local)
    if any(n % sym.order for n in total.values()):
        raise ValueError("the operations do not form a group (Burnside sum not divisible).")
    names = {codes.label_names[i]: n // sym.order for i, n in total.items() if n}
    return Counter({k: names[k] for k in sorted(names, key=_lab_key)})

sample_labels

sample_labels(sym: SiteSymmetry, n_samples: int, seed: Optional[int] = 0, chunk: int = 1 << 16, groups='A', linker_patterns: Optional[dict] = None) -> LabelSample

Estimate the distribution of label multisets over the symmetry-unique isomers, and the environment counts, from n_samples random placements, for cages too big to enumerate.

Placements are drawn uniformly; an isomer whose placements are fixed by k operations is drawn k times less often than the others, so each sample counts with weight k (its stabiliser size), which makes the estimate uniform over isomers. The fractions are the weighted shares, their standard errors from the delta method. Summed over all placements instead of a sample, the same weights give the exact counts (Burnside).

Parameters:

Name Type Description Default
sym SiteSymmetry
required
n_samples int
required
seed int or None

Random seed (None: fresh entropy).

0
chunk int

Placements processed at once.

65536
groups

What goes on the linkers (see :func:count_isomers).

'A'
linker_patterns

What goes on the linkers (see :func:count_isomers).

'A'

Examples:

>>> from cage_isomer_builder.utils.vertex_table import ideal_cage, sample_labels, vertex_table
>>> sample = sample_labels(ideal_cage("octahedron"), 100000, seed=0)
>>> exact = vertex_table(ideal_cage("octahedron")).label_counts(merge_mirrors=True)
>>> labels, n = exact.most_common(1)[0]
>>> f, se = sample.fraction(labels)
>>> n, abs(f - n / 349928) < 3 * se
(256, True)
Source code in cage_isomer_builder/utils/vertex_table.py
def sample_labels(sym: SiteSymmetry, n_samples: int, seed: Optional[int] = 0,
                  chunk: int = 1 << 16, groups="A",
                  linker_patterns: Optional[dict] = None) -> LabelSample:
    """
    Estimate the distribution of label multisets over the symmetry-unique
    isomers, and the environment counts, from ``n_samples`` random
    placements, for cages too big to enumerate.

    Placements are drawn uniformly; an isomer whose placements are fixed by
    ``k`` operations is drawn ``k`` times less often than the others, so
    each sample counts with weight ``k`` (its stabiliser size), which makes
    the estimate uniform over isomers. The fractions are the weighted
    shares, their standard errors from the delta method. Summed over all
    placements instead of a sample, the same weights give the exact counts
    (Burnside).

    Parameters
    ----------
    sym : SiteSymmetry
    n_samples : int
    seed : int or None, default 0
        Random seed (``None``: fresh entropy).
    chunk : int, default 65536
        Placements processed at once.
    groups, linker_patterns
        What goes on the linkers (see :func:`count_isomers`).

    Examples
    --------
    >>> from cage_isomer_builder.utils.vertex_table import ideal_cage, sample_labels, vertex_table
    >>> sample = sample_labels(ideal_cage("octahedron"), 100000, seed=0)
    >>> exact = vertex_table(ideal_cage("octahedron")).label_counts(merge_mirrors=True)
    >>> labels, n = exact.most_common(1)[0]
    >>> f, se = sample.fraction(labels)
    >>> n, abs(f - n / 349928) < 3 * se
    (256, True)
    """
    if n_samples < 1:
        raise ValueError(f"n_samples={n_samples}; need at least one sample.")
    space = _Space(sym, groups, linker_patterns)
    codes = _Codes(space)
    rng = np.random.default_rng(seed)
    acc: dict = {}
    for start in range(0, n_samples, chunk):
        _accumulate(space, codes, space.random_states(rng, min(chunk, n_samples - start)), acc)
    sums = acc["multisets"]
    keys = list(sums)
    s1 = np.array([sums[k][0] for k in keys], float)
    s2 = np.array([sums[k][1] for k in keys], float)
    hits = np.array([sums[k][2] for k in keys], np.int64)
    W, W2 = float(acc["W"]), float(acc["W2"])
    f = s1 / W
    # delta method for a ratio of sums: Var = sum (w (1_M - f))^2 / W^2
    stderr = np.sqrt(np.maximum(s2 * (1 - 2 * f) + f * f * W2, 0)) / W
    shown = [codes.display(k, merged=True) for k in keys]
    order = sorted(range(len(keys)),
                   key=lambda i: (-f[i], [_lab_key(x) for x in shown[i].split("-")]))
    n_isomers = count_isomers(sym, groups=groups, linker_patterns=linker_patterns)
    m = acc["E1"] / W
    var = np.maximum(acc["E3"] - 2 * m * acc["E2"] + m * m * W2, 0) / W ** 2
    environments = {codes.label_names[i]: (float(m[i] * n_isomers),
                                           float(np.sqrt(var[i]) * n_isomers))
                    for i in sorted(range(len(m)), key=lambda i: _lab_key(codes.label_names[i]))
                    if m[i] > 0}
    return LabelSample(sym, int(n_samples), n_isomers, [shown[i] for i in order], f[order],
                       stderr[order], hits[order], environments)