Skip to content

Command line

The cage-vertex-name command converts isomers between site names and vertex names, and cage-vertex-table tabulates the vertex labels of every isomer of an ideal cage: cage_isomer_builder.cli. Run either with --help for every option.

Command-line tools.

cage-vertex-name converts between the site name of an isomer (0-4-9-13-16-22) and its vertex name (000-100-141-401, see :mod:cage_isomer_builder.utils.vertex_codes), for names or for isomer files written by :meth:~cage_isomer_builder.cage.base.CageBuilder.enumerate_isomers::

cage-vertex-name 0-4-9-13-16-22.xyz            # writes 000-100-141-401.xyz
cage-vertex-name 000-100-141-401.xyz           # writes 0-4-9-13-16-22.xyz
cage-vertex-name isomers/*.xyz -o by_vertex    # a whole folder
cage-vertex-name --ref isomers/0-4-8-12-16-20.xyz 0-4-9-13-16-22 000-100-141-401

With --ref, any isomer file of the cage supplies the vertex scheme and the names are converted and printed; nothing is written.

cage-vertex-table writes every symmetry-unique isomer of an ideal cage with its vertex name and labels (see :mod:cage_isomer_builder.utils.vertex_table)::

cage-vertex-table octahedron -o octahedron.tsv.gz
cage-vertex-table --xyz my_polyhedron.xyz -o table.tsv   # vertices from any xyz file
cage-vertex-table icosahedron --count                    # too many to list: count them
cage-vertex-table icosahedron --environments             # exact environment counts, any size
cage-vertex-table icosahedron --sample 1000000 -o ico.tsv  # sampled label distribution
cage-vertex-table tetrahedron --groups AB -o tet_ab.tsv    # one A and one B per linker
cage-vertex-table octahedron --linker biphenyl --count     # eight-site linkers
cage-vertex-table tetrahedron --linker-patterns A:3,:3     # three linkers bare
cage-vertex-table --list

vertex_name_main

vertex_name_main(argv: Optional[Sequence[str]] = None) -> int

The cage-vertex-name command: convert isomer files, or with --ref isomer names, between site names and vertex names. Returns the exit status: 0, or 1 if any file or name failed.

Examples:

An isomer file of a toy cage (two vertices joined by two linkers, sites 0-3 and 4-7) with the vertex scheme in its info:

>>> import os, tempfile
>>> from ase import Atoms
>>> from cage_isomer_builder.cli import vertex_name_main
>>> from cage_isomer_builder.utils.sites import write_isomer
>>> 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)})
>>> atoms = Atoms("H2", positions=[[0, 0, 0], [0, 0, 1]])
>>> atoms.info.update(isomer="1-6", **scheme.to_info())
>>> os.chdir(tempfile.mkdtemp())
>>> _ = write_isomer("1-6.xyz", atoms)

A file named by its sites gets a copy named by its vertex name, and back:

>>> vertex_name_main(["1-6.xyz"])
1-6.xyz -> 40-01.xyz
0
>>> vertex_name_main(["40-01.xyz", "-o", "back"])
40-01.xyz -> back/1-6.xyz
0

With --ref, names are converted either way:

>>> vertex_name_main(["--ref", "1-6.xyz", "0-4", "40-01"])
0-4 -> 11-00   labels 11-00
40-01 -> 1-6   labels 40-10
0
Source code in cage_isomer_builder/cli.py
def vertex_name_main(argv: Optional[Sequence[str]] = None) -> int:
    """
    The ``cage-vertex-name`` command: convert isomer files, or with
    ``--ref`` isomer names, between site names and vertex names. Returns
    the exit status: 0, or 1 if any file or name failed.

    Examples
    --------
    An isomer file of a toy cage (two vertices joined by two linkers, sites
    0-3 and 4-7) with the vertex scheme in its ``info``:

    >>> import os, tempfile
    >>> from ase import Atoms
    >>> from cage_isomer_builder.cli import vertex_name_main
    >>> from cage_isomer_builder.utils.sites import write_isomer
    >>> 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)})
    >>> atoms = Atoms("H2", positions=[[0, 0, 0], [0, 0, 1]])
    >>> atoms.info.update(isomer="1-6", **scheme.to_info())
    >>> os.chdir(tempfile.mkdtemp())
    >>> _ = write_isomer("1-6.xyz", atoms)

    A file named by its sites gets a copy named by its vertex name, and back:

    >>> vertex_name_main(["1-6.xyz"])
    1-6.xyz -> 40-01.xyz
    0
    >>> vertex_name_main(["40-01.xyz", "-o", "back"])
    40-01.xyz -> back/1-6.xyz
    0

    With ``--ref``, names are converted either way:

    >>> vertex_name_main(["--ref", "1-6.xyz", "0-4", "40-01"])
    0-4 -> 11-00   labels 11-00
    40-01 -> 1-6   labels 40-10
    0
    """
    parser = argparse.ArgumentParser(
        prog="cage-vertex-name",
        description="Convert isomers between site names (0-4-9-13-16-22, or "
                    "NH2-0-4_OH-1-5 for several groups) and vertex names (000-100-141-401, "
                    "or AB.00.00-...). Give isomer files to write copies under the other "
                    "name, or --ref FILE and names to print the conversion.")
    parser.add_argument("items", nargs="+", metavar="FILE_OR_NAME",
                        help="isomer files, or names when --ref is given")
    parser.add_argument("--ref", metavar="FILE",
                        help="an isomer file of the cage: convert the names given instead of files")
    parser.add_argument("--to", choices=("auto", "vertex", "sites"), default="auto",
                        help="name to give files (default: the other one)")
    parser.add_argument("-o", "--outdir", help="write the files here (default: next to each file)")
    parser.add_argument("--move", action="store_true", help="rename instead of copying")
    parser.add_argument("--force", action="store_true", help="overwrite existing files")
    args = parser.parse_args(argv)

    status = 0
    if args.ref:
        try:
            from cage_isomer_builder.utils.sites import read_isomer
            ref_info = read_isomer(args.ref).info
            scheme = VertexScheme.from_info(ref_info)
        except (ValueError, OSError) as exc:
            print(f"error: {args.ref}: {exc}", file=sys.stderr)
            return 1
        names = str(ref_info.get("rgroup_labels", "")).split()
        jobs = [(name, lambda n: _convert_name(scheme, n, names)) for name in args.items]
    else:
        jobs = [(path, lambda p: _convert_file(p, args.to, args.outdir, args.move, args.force))
                for path in args.items]
    for item, job in jobs:
        try:
            print(job(item))
        except (ValueError, OSError) as exc:
            print(f"error: {exc}", file=sys.stderr)
            status = 1
    return status

vertex_table_main

vertex_table_main(argv: Optional[Sequence[str]] = None) -> int

The cage-vertex-table command: the symmetry-unique isomers of an ideal cage (a named polyhedron, or the vertices in an xyz file) with their vertex names and labels, written as a table; a summary goes to standard output. Returns the exit status.

Examples:

>>> import os, tempfile
>>> from cage_isomer_builder.cli import vertex_table_main
>>> os.chdir(tempfile.mkdtemp())
>>> vertex_table_main(["tetrahedron", "-o", "tet.tsv"])
tetrahedron: Td, 4 vertices, 6 linkers, 176 isomers (0 achiral) -> tet.tsv
0
>>> print(open("tet.tsv").read().splitlines()[1])
0-4-8-12-16-20      111-011-001-000 111-110-100-000 444-440-400-000 Y
>>> vertex_table_main(["icosahedron", "--count"])
icosahedron: Ih, 12 vertices, 30 linkers, 9607679214180672 isomers (19215358410465280 counting mirror images apart)
0

Any polyhedron, from the vertex coordinates of an xyz file:

>>> from ase.io import write
>>> from ase import Atoms
>>> write("prism.xyz", Atoms("X6", positions=[[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]]))
>>> vertex_table_main(["--xyz", "prism.xyz", "--count"])
prism.xyz: D3h, 6 vertices, 9 linkers, 21856 isomers (43712 counting mirror images apart)
0

Cages too big to list: exact environment counts (both hands), and the distribution of label multisets estimated from random placements:

>>> vertex_table_main(["icosahedron", "--environments"])
icosahedron: Ih, 12 vertices, 30 linkers, 9607679214180672 isomers (...)
  11111  225179981581120
...
0
>>> vertex_table_main(["octahedron", "--sample", "20000", "-o", "oct_sample.tsv"])
octahedron: Oh, 6 vertices, 12 linkers, 349928 isomers; 20000 samples, 7018 label multisets -> oct_sample.tsv
0

Several groups per linker, several kinds, longer linkers, fixed numbers of linkers per pattern:

>>> vertex_table_main(["tetrahedron", "--groups", "AB", "-o", "tet_ab.tsv"])
tetrahedron: Td, 4 vertices, 6 linkers, 124464 isomers (0 achiral) -> tet_ab.tsv
0
>>> print(open("tet_ab.tsv").read().splitlines()[1])
A-2-6-10-14-18-22_B-3-7-11-15-19-23 00.00.00-AB.00.00-AB.AB.00-AB.AB.AB     AB.AB.AB-AB.AB.00-AB.00.00-00.00.00     BA.BA.BA-BA.BA.00-BA.00.00-00.00.00     Y
>>> vertex_table_main(["octahedron", "--linker", "biphenyl", "--count"])
octahedron: Oh, 6 vertices, 12 linkers, 1431678432 isomers (2863345792 counting mirror images apart)
0
>>> vertex_table_main(["tetrahedron", "--linker-patterns", "A:3,:3", "--count"])
tetrahedron: Td, 4 vertices, 6 linkers, 56 isomers (112 counting mirror images apart)
0
Source code in cage_isomer_builder/cli.py
def vertex_table_main(argv: Optional[Sequence[str]] = None) -> int:
    """
    The ``cage-vertex-table`` command: the symmetry-unique isomers of an
    ideal cage (a named polyhedron, or the vertices in an xyz file) with
    their vertex names and labels, written as a table; a summary goes to
    standard output. Returns the exit status.

    Examples
    --------
    >>> import os, tempfile
    >>> from cage_isomer_builder.cli import vertex_table_main
    >>> os.chdir(tempfile.mkdtemp())
    >>> vertex_table_main(["tetrahedron", "-o", "tet.tsv"])
    tetrahedron: Td, 4 vertices, 6 linkers, 176 isomers (0 achiral) -> tet.tsv
    0
    >>> print(open("tet.tsv").read().splitlines()[1])
    0-4-8-12-16-20	111-011-001-000	111-110-100-000	444-440-400-000	Y
    >>> vertex_table_main(["icosahedron", "--count"])
    icosahedron: Ih, 12 vertices, 30 linkers, 9607679214180672 isomers (19215358410465280 counting mirror images apart)
    0

    Any polyhedron, from the vertex coordinates of an xyz file:

    >>> from ase.io import write
    >>> from ase import Atoms
    >>> write("prism.xyz", Atoms("X6", positions=[[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]]))
    >>> vertex_table_main(["--xyz", "prism.xyz", "--count"])
    prism.xyz: D3h, 6 vertices, 9 linkers, 21856 isomers (43712 counting mirror images apart)
    0

    Cages too big to list: exact environment counts (both hands), and the
    distribution of label multisets estimated from random placements:

    >>> vertex_table_main(["icosahedron", "--environments"])  # doctest: +ELLIPSIS
    icosahedron: Ih, 12 vertices, 30 linkers, 9607679214180672 isomers (...)
      11111  225179981581120
    ...
    0
    >>> vertex_table_main(["octahedron", "--sample", "20000", "-o", "oct_sample.tsv"])
    octahedron: Oh, 6 vertices, 12 linkers, 349928 isomers; 20000 samples, 7018 label multisets -> oct_sample.tsv
    0

    Several groups per linker, several kinds, longer linkers, fixed
    numbers of linkers per pattern:

    >>> vertex_table_main(["tetrahedron", "--groups", "AB", "-o", "tet_ab.tsv"])
    tetrahedron: Td, 4 vertices, 6 linkers, 124464 isomers (0 achiral) -> tet_ab.tsv
    0
    >>> print(open("tet_ab.tsv").read().splitlines()[1])
    A-2-6-10-14-18-22_B-3-7-11-15-19-23	00.00.00-AB.00.00-AB.AB.00-AB.AB.AB	AB.AB.AB-AB.AB.00-AB.00.00-00.00.00	BA.BA.BA-BA.BA.00-BA.00.00-00.00.00	Y
    >>> vertex_table_main(["octahedron", "--linker", "biphenyl", "--count"])
    octahedron: Oh, 6 vertices, 12 linkers, 1431678432 isomers (2863345792 counting mirror images apart)
    0
    >>> vertex_table_main(["tetrahedron", "--linker-patterns", "A:3,:3", "--count"])
    tetrahedron: Td, 4 vertices, 6 linkers, 56 isomers (112 counting mirror images apart)
    0
    """
    from cage_isomer_builder.utils import vertex_table as vt

    parser = argparse.ArgumentParser(
        prog="cage-vertex-table",
        description="Every symmetry-unique isomer of an ideal cage, with its vertex name "
                    "and environment labels: a polyhedron with a linker lying flat on "
                    "every edge. One group per linker unless --groups or "
                    "--linker-patterns say otherwise.")
    parser.add_argument("polyhedron", nargs="?", help=f"one of {', '.join(vt.POLYHEDRA)}")
    parser.add_argument("--xyz", help="take the vertices from this file (all its atoms); "
                                      "the edges are those of their convex hull")
    parser.add_argument("-o", "--output", help="table to write (.tsv, or .tsv.gz)")
    parser.add_argument("--count", action="store_true",
                        help="only count the isomers (Burnside), for any size")
    parser.add_argument("--environments", action="store_true",
                        help="print how often each vertex environment occurs over all isomers, "
                             "both hands (exact, any size)")
    parser.add_argument("--sample", type=int, metavar="N",
                        help="estimate the distribution of label multisets (mirror images "
                             "merged) from N random placements, for any size; -o writes it")
    parser.add_argument("--seed", type=int, default=0, help="random seed of --sample (default 0)")
    parser.add_argument("--max-placements", type=float, default=4.0 ** 16,
                        help="refuse more than this many raw placements (default 4**16)")
    parser.add_argument("--linker", default="phenylene",
                        help=f"sites on every edge: one of {', '.join(vt.LINKERS)} "
                             "(default phenylene)")
    parser.add_argument("--groups", default="A",
                        help="groups on every linker: A (one, the default), AA (two), AB (one "
                             "A and one B), ...; names with commas: NH2,OH")
    parser.add_argument("--linker-patterns", metavar="P:N,...",
                        help="fixed numbers of linkers per pattern instead, e.g. A:3,B:3 or "
                             "AB:2,:4 (four bare linkers)")
    parser.add_argument("--list", action="store_true", help="list the named polyhedra")
    args = parser.parse_args(argv)
    groups = args.groups.split(",") if "," in args.groups else args.groups
    patterns = None
    if args.linker_patterns:
        try:
            patterns = {p: int(n) for p, n in (item.rsplit(":", 1)
                                               for item in args.linker_patterns.split(","))}
        except ValueError:
            print("error: --linker-patterns takes PATTERN:NUMBER,... (e.g. A:3,B:3)",
                  file=sys.stderr)
            return 1
    spec = {"groups": groups, "linker_patterns": patterns}

    if args.list:
        for name in vt.POLYHEDRA:
            sym = vt.ideal_cage(name)
            print(f"{name:18s} {sym.group:4s} {len(sym.scheme.vertex_linkers):3d} vertices "
                  f"{sym.n_linkers:3d} linkers")
        return 0
    if bool(args.polyhedron) == bool(args.xyz):
        print("error: give a polyhedron name or --xyz FILE", file=sys.stderr)
        return 1
    try:
        if args.xyz:
            from ase.io import read
            label, vertices = os.path.basename(args.xyz), read(args.xyz).positions
        else:
            label, vertices = args.polyhedron, args.polyhedron
        sym = vt.ideal_cage(vertices, linker=args.linker)
        head = (f"{label}: {sym.group}, {len(sym.scheme.vertex_linkers)} vertices, "
                f"{sym.n_linkers} linkers")
        if args.sample is not None:
            sample = vt.sample_labels(sym, args.sample, seed=args.seed, **spec)
            line = (f"{head}, {sample.n_isomers} isomers; {sample.n_samples} samples, "
                    f"{len(sample)} label multisets")
            if args.output:
                sample.write(args.output)
                line += f" -> {args.output}"
            print(line)
        elif args.count or (args.environments and not args.output):
            # no table needed: counting works for any size
            print(f"{head}, {vt.count_isomers(sym, **spec)} isomers "
                  f"({vt.count_isomers(sym, chiral=True, **spec)} counting mirror images apart)")
        else:
            table = vt.vertex_table(sym, int(args.max_placements), **spec)
            line = f"{head}, {len(table)} isomers ({int(table.achiral.sum())} achiral)"
            if args.output:
                table.write(args.output)
                line += f" -> {args.output}"
            print(line)
        if args.environments:
            for env, n in vt.count_environments(sym, **spec).items():
                print(f"  {env}  {n}")
    except (ValueError, OSError) as exc:
        hint = " Use --count to count them." if "max_placements" in str(exc) else ""
        print(f"error: {exc}{hint}", file=sys.stderr)
        return 1
    return 0