Custom unit cells#

The catalog is a good place to start, but a unit cell can also be a small piece of Python that describes your own repeating geometry. This guide builds two custom beam cells and one custom implicit cell, then reuses them on rectangular and curved cell maps. It ends with two builders that generate larger graph cells for you: foams grown from seed points, and cells made by applying a rule to a pattern of shapes that fills space.

This tutorial assumes you have already read the earlier metamaterials guides, especially Concepts and representation, TPMS and lattice catalog, and Functionally graded geometry. The focus here is geometry; no material attributes are added.

The custom-cell workflow#

Every example follows the same three steps:

  1. describe one cell in normalized U/V/W coordinates,

  2. create a CellMap for the finished shape, and

  3. combine them with mm.graph_lattice(...) or mm.tpms(...).

The cell uses coordinates from 0 to 1. It has no size in millimetres until you give it a cell map. This is what lets one definition work in a 12 mm cube, a larger tiled block, or a curved conformal map.

For a cell to connect across repetitions, its opposite boundaries must agree. For example, a graph vertex at (0, 0.5, 0.5) should have a matching vertex at (1, 0.5, 0.5). An implicit function must return matching values at U=0 and U=1, and likewise for V and W.

Build a graph cell from vertices and edges#

A GraphUnitCell contains:

  • normalized vertices, and

  • edges that refer to those vertices by list index.

This first cell has one vertex at its center and one at the center of each boundary face. Six indexed edges join the center to those boundary points.

import pyvcad as pv

vertices = [
    pv.Vec3(0.5, 0.5, 0.5),  # center
    pv.Vec3(0.0, 0.5, 0.5),  # U-min
    pv.Vec3(1.0, 0.5, 0.5),  # U-max
    pv.Vec3(0.5, 0.0, 0.5),  # V-min
    pv.Vec3(0.5, 1.0, 0.5),  # V-max
    pv.Vec3(0.5, 0.5, 0.0),  # W-min
    pv.Vec3(0.5, 0.5, 1.0),  # W-max
]
edges = [(0, index) for index in range(1, len(vertices))]
unit_cell = pv.GraphUnitCell(vertices, edges)

Start by placing it on a one-cell map. The map below is a 12 mm cube, so every normalized axis spans 12 mm in the preview.

import pyvcad_metamaterials as mm

preview_map = mm.rectangular_cell_map(
    (pv.Vec3(-6.0, -6.0, -6.0), pv.Vec3(6.0, 6.0, 6.0)),
    cells=(1, 1, 1),
)
preview = mm.graph_lattice(
    preview_map,
    unit_cell,
    beam_radius=0.65,
    node_radius=0.8,
)

The translucent box in the first render marks the one-cell preview. Each strut ends on a boundary and meets the matching strut from the next cell. Changing only the map to cells=(3, 3, 3) produces the connected block on the right. Beam and node radii are in millimetres.

One custom axis-star graph cell inside its one-cell map
One cell: inspect vertices, beams, and boundary crossings
Three by three by three tiling of the custom axis-star graph cell
3 × 3 × 3 cells: matching boundaries form continuous beams

Run the complete example: 01_explicit_graph_cell.py.

Generate a graph cell with Python#

Direct lists work well for small cells. For a larger or adjustable topology, use loops and functions so the code describes the pattern instead of repeating coordinates by hand.

This hourglass cell builds four bottom corners and four top corners with itertools.product. Two hub vertices connect the corner groups, and hub_offset controls their separation.

import itertools

import pyvcad as pv


def hourglass_cell(hub_offset=0.22):
    bottom_corners = [
        pv.Vec3(x, y, 0.0)
        for x, y in itertools.product((0.0, 1.0), repeat=2)
    ]
    top_corners = [
        pv.Vec3(x, y, 1.0)
        for x, y in itertools.product((0.0, 1.0), repeat=2)
    ]
    vertices = bottom_corners + [
        pv.Vec3(0.5, 0.5, 0.5 - hub_offset),
        pv.Vec3(0.5, 0.5, 0.5 + hub_offset),
    ] + top_corners

    lower_hub = 4
    upper_hub = 5
    edges = [(index, lower_hub) for index in range(4)]
    edges += [(lower_hub, upper_hub)]
    edges += [(upper_hub, index) for index in range(6, 10)]
    return pv.GraphUnitCell(vertices, edges)

Preview the result with one cell before making a large lattice. This catches swapped indices and misplaced boundary vertices quickly.

The tiled example also reuses the geometric grading from the previous guide. The topology does not change; only beam_radius grows from 0.4 mm at U-min to 0.85 mm at U-max.

cell_map = mm.rectangular_cell_map(
    (pv.Vec3(-24.0, -18.0, -18.0), pv.Vec3(24.0, 18.0, 18.0)),
    cells=(4, 3, 3),
)
beam_radius = cell_map.logical_position.x.map_range(
    0.0, 4.0, 0.4, 0.85
)
root = mm.graph_lattice(
    cell_map,
    hourglass_cell(),
    beam_radius=beam_radius,
)
One parameterized hourglass graph cell inside its one-cell map
One generated cell: two hubs join the top and bottom corner groups
Tiled custom hourglass graph cell with beams growing from left to right
4 × 3 × 3 cells: the same topology with radius graded along U

Run 02_programmed_graph_cell.py and try changing hub_offset.

Build a custom implicit cell#

An implicit unit cell replaces vertices and edges with a periodic scalar function. OpenVCAD builds the sheet around the function’s zero surface.

The example below starts with three cosine waves and adds a fourth coupled wave:

\[f(u,v,w) = \cos(2\pi u) + \cos(2\pi v) + \cos(2\pi w) + 0.35\cos(2\pi(u+v+w)).\]

Every term repeats after one unit along U, V, or W, so the cell matches at all six boundaries.

import math

import pyvcad as pv


def rippled_p(u, v, w):
    a = 2.0 * math.pi * u
    b = 2.0 * math.pi * v
    c = 2.0 * math.pi * w
    return (
        math.cos(a)
        + math.cos(b)
        + math.cos(c)
        + 0.35 * math.cos(a + b + c)
    )


unit_cell = pv.ImplicitUnitCell(rippled_p, name="rippled_p")
assert unit_cell.validate_periodicity()

validate_periodicity() samples opposite boundaries and checks that the function values agree. Use it before rendering a new equation.

The cell becomes geometry when passed to mm.tpms(...). Here mode="sheet" keeps a 0.9 mm wall around the zero surface.

cell_map = mm.rectangular_cell_map(
    (pv.Vec3(-18.0, -18.0, -18.0), pv.Vec3(18.0, 18.0, 18.0)),
    cells=(3, 3, 3),
)
root = mm.tpms(
    cell_map,
    unit_cell,
    mode="sheet",
    wall_thickness=0.9,
)
One custom rippled implicit cell inside its one-cell map
One cell: the zero surface meets each opposite boundary in the same pattern
Three by three by three tiling of the custom rippled implicit cell
3 × 3 × 3 cells: the sheet joins without seams

Run 03_custom_implicit_cell.py. The standalone example also defines the analytic gradient of the equation. A gradient is optional, but supplying one avoids numerical gradient estimation when the mapped surface is evaluated.

Reuse the cells on curved maps#

Nothing in either custom-cell definition refers to a box. To make the structure conformal, replace the rectangular map with a surface map and keep the same unit cell.

This abbreviated example creates a cylindrical CAD face and places the hourglass graph on it:

import cadquery as cq

import pyvcad as pv
import pyvcad_metamaterials as mm

cad = cq.Workplane("XY").circle(12.0).extrude(24.0)
surface = pv.CADModel.from_cadquery(
    cad.faces("%CYLINDER")
).faces[0]

cell_map = mm.cell_map_from_cad_face(
    surface,
    cells=(16, 8, 1),
    height=3.0,
    linear=False,
)
root = mm.graph_lattice(
    cell_map,
    hourglass_cell(),
    beam_radius=0.28,
    node_radius=0.34,
)

cells=(16, 8, 1) places sixteen cells around the cylinder, eight along its height, and one through the 3 mm map thickness. linear=False lets graph beams subdivide and follow the curved map.

The companion example applies this map to both custom representations. The graph beams curve around the first cylinder; the implicit sheet follows the second cylinder without changing its periodic equation.

Custom hourglass graph cell tiled around a cylindrical CAD face
Custom graph cell on a cylindrical cell map
Custom rippled implicit cell tiled around a cylindrical CAD face
Custom implicit cell on a cylindrical cell map

Run 04_conformal_custom_cells.py. It requires the optional CadQuery installation described in Conformal mapping CAD surfaces.

Build cells from seeds and tessellations#

Typing vertices by hand works well for small cells. A foam can have dozens of struts, though, and typing those is slow and easy to get wrong. Instead, you can describe how the cell divides up space and let OpenVCAD find the struts.

This section shows two builders that do that. Both give you a graph cell that you pass to mm.graph_lattice(...) in the same place as a catalog name.

Voronoi cells from periodic seeds#

Start with a few points inside one cell, given in cell coordinates from 0 to 1. These points are called seeds. Now hand every location in space to the seed closest to it. Each seed ends up owning a region called its Voronoi cell. Neighbouring regions meet along flat walls, and the walls meet along edges. Those edges make a foam-like network of struts.

mm.periodic_voronoi(seeds) repeats your seeds in every cell along U, V and W and works out their Voronoi cells. Its .edges() method returns the cell edges as a graph cell. Because the seeds repeat, every strut that leaves one face of the cell lines up exactly with a strut entering the opposite face. The foam therefore tiles without seams.

The example builds two foams. The block on the left uses eight seeds at the positions of the A15 crystal structure, which gives the Weaire-Phelan foam. The ring on the right uses ten random seeds per cell.

import numpy as np

# Eight A15 sites: the Weaire-Phelan foam.
a15 = [(0, 0, 0), (0.5, 0.5, 0.5), (0.25, 0.5, 0), (0.75, 0.5, 0),
       (0, 0.25, 0.5), (0, 0.75, 0.5), (0.5, 0, 0.25), (0.5, 0, 0.75)]
weaire_phelan = mm.periodic_voronoi(a15).edges()

# Random seeds: a random foam that still tiles, so it can follow a curved map.
random_foam = mm.periodic_voronoi(np.random.default_rng(4).random((10, 3))).edges()

block = mm.rectangular_cell_map((pv.Vec3(-46, -12, -12), pv.Vec3(-22, 12, 12)), cells=(2, 2, 2))
ring = mm.cylindrical_cell_map(pv.Vec3(20, 0, -12), 14.0, 26.0, 24.0, cells=(10, 2, 1))
root = pv.Union(
    mm.graph_lattice(block, weaire_phelan, beam_radius=0.45),
    mm.graph_lattice(ring, random_foam, beam_radius=0.45),
)
Weaire-Phelan foam built from A15 seeds
A15 seeds: the Weaire-Phelan foam, 2 × 2 × 2 cells
Random periodic Voronoi foam tiled around a cylindrical map
Ten random seeds per cell, tiled around a cylinder

The random foam still tiles, so it can wrap all the way around the cylindrical map without a visible seam.

Regular seed patterns give familiar catalog cells. One seed at the centre gives "cubic". Seeds at the corner and the centre of the cell (BCC sites) give the Kelvin cell. Seeds at the corner and the face centres (FCC sites) give rhombic dodecahedra. mm.voronoi_unit_cell(kind) is a shortcut for these three patterns, with kind set to "sc", "bcc" or "fcc".

By default, the builder assumes the map’s cells are cubes. If they are not, pass their proportions as cell_size, for example cell_size=(1.0, 1.0, 1.6) for cells that are 1.6 times as long along W as along U and V. The builder then measures “closest” in those proportions, so the foam keeps the right shape once it is placed on the map.

Seed points can also stand for the atoms of a crystal. There you usually want struts between neighbouring atoms rather than the Voronoi edges around them. mm.periodic_bonds(sites, max_length) adds a strut between every two sites that are closer together than max_length, including sites in the neighbouring copies of the cell. max_length is measured in the same units as cell_size, so for cube-shaped cells it is a fraction of the cell width. For diamond, the atoms sit on the FCC sites plus a copy of them shifted a quarter of the way along each axis:

fcc = [(0, 0, 0), (0.5, 0.5, 0), (0.5, 0, 0.5), (0, 0.5, 0.5)]
diamond_sites = fcc + [(x + 0.25, y + 0.25, z + 0.25) for x, y, z in fcc]
diamond = mm.periodic_bonds(diamond_sites, max_length=0.44)  # the "diamond" cell

Tessellations and rules#

A tessellation is a set of solid shapes that fill space with no gaps or overlaps, like stacked cubes or a honeycomb of hexagonal prisms. Each shape is one cell of the tessellation. A rule says where to put struts in those cells. Because you can apply any rule to any tessellation, one tessellation gives you a whole family of lattice cells:

Rule

Struts

"edges"

every edge of every cell

"cell_vertex_centroid"

each cell’s centre joined to each of its corners

"facet_vertex_centroid"

each face’s centre joined to each corner of that face

"dual"

the centres of every two cells that share a face

"central_axes"

each cell’s centre joined to the centre of each of its faces

mm.tessellation(name) gives you a built-in tessellation, and mm.TESSELLATION_NAMES lists them: stacked cubes; hexagonal, re-entrant, triangular and rotated prisms; the tetrahedral-octahedral honeycomb, which packs tetrahedra and octahedra together; and the truncated-cube honeycomb.

Many catalog cells are just one rule on one of these. The cube’s "edges" give "cubic", and its "cell_vertex_centroid" gives BCC. The "edges" of the tetrahedral-octahedral honeycomb give the octet truss. The code below applies four rules to that honeycomb, and the figures show the result of each:

tet_oct = mm.tessellation("tet_oct")
cell_map = mm.rectangular_cell_map((pv.Vec3(-10, -10, -10), pv.Vec3(10, 10, 10)), cells=(2, 2, 2))
for rule in ["edges", "cell_vertex_centroid", "facet_vertex_centroid", "dual"]:
    lattice = mm.graph_lattice(cell_map, tet_oct.edges(rule), beam_radius=0.45)
Edges of the tetrahedral-octahedral honeycomb
"edges": the octet truss
Cell centres joined to their corners
"cell_vertex_centroid"
Face centres joined to their corners
"facet_vertex_centroid"
Dual of the tetrahedral-octahedral honeycomb
"dual": neighbouring cell centres joined

You can narrow down or combine rules in three ways:

  • kinds uses only some types of cell. For example, tet_oct.edges("cell_vertex_centroid", kinds="tet") uses only the tetrahedra, which gives the fluorite cell.

  • face_tags uses only some faces. Prisms label their top and bottom faces "cap" and their side faces "side".

  • A list of rules gives the struts of all of them together.

OpenVCAD tidies up every result for you. Where one strut ends partway along another, that other strut is split there so the two meet at a joint, and duplicate struts are removed. Combined rules therefore still give clean joints.

You can also describe your own tessellation. List the cells that make up one repeat of the pattern, each as an mm.Polyhedron. For a convex cell, one with no dents, give its corner points and OpenVCAD finds the faces. For a honeycomb, give a 2D outline to mm.Polyhedron.prism(...), which extends it along W. A cell may stick out past the 0 to 1 range; the copy from the neighbouring repeat fills in the part that is missing.

This example fills space with squares turned 45°, two per cell:

# Squares turned 45 degrees: two per cell.
squares = [
    mm.Polyhedron.prism([(0, 0), (0.5, -0.5), (1, 0), (0.5, 0.5)]),
    mm.Polyhedron.prism([(0, 0), (0.5, 0.5), (0, 1), (-0.5, 0.5)]),
]
turned = mm.PeriodicTessellation(squares)
struts = turned.edges()                       # a graph cell
walls = turned.face_cell(face_tags="side")    # a pv.FaceUnitCell of the walls
root = mm.face_lattice(cell_map, walls, wall_thickness=0.6)

edges() gives you struts, as before. face_cell(...) gives you walls instead: it turns the chosen faces into a face cell for mm.face_lattice(...). Here face_tags="side" keeps only the side walls, which gives a square honeycomb turned 45°.

A Voronoi tessellation has a face cell too. It makes a closed-cell foam, where walls seal every cell, so check that resin or powder can drain out before you print it.

Run 05_periodic_voronoi_cells.py and 06_tessellation_rules.py for the complete scripts. Each one opens its result in the interactive preview.

A practical first-pass checklist#

Before using a new cell in a large part:

  1. Keep graph vertices inside [0, 1] on U, V, and W.

  2. Check that every indexed edge refers to an existing vertex.

  3. Match graph vertices across opposite boundaries when the structure should continue into the next cell.

  4. Call validate_periodicity() for a custom implicit function.

  5. Render one cell before rendering many cells.

  6. Remember that beam radius, node radius, wall thickness, and map dimensions are in millimetres.

  7. Test the intended conformal map; strong deformation can change beam angles and local cell shape even when connectivity is preserved.

Run all companion examples#

From the repository root:

./.venv/bin/python examples/metamaterials/custom_unit_cells/01_explicit_graph_cell.py
./.venv/bin/python examples/metamaterials/custom_unit_cells/02_programmed_graph_cell.py
./.venv/bin/python examples/metamaterials/custom_unit_cells/03_custom_implicit_cell.py
./.venv/bin/python examples/metamaterials/custom_unit_cells/04_conformal_custom_cells.py
./.venv/bin/python examples/metamaterials/custom_unit_cells/05_periodic_voronoi_cells.py
./.venv/bin/python examples/metamaterials/custom_unit_cells/06_tessellation_rules.py

Each numbered script contains the complete unit-cell definitions it needs, so you can read, copy, and run it without any local helper imports.

Once your cell is working, continue with Functionally graded geometry to vary its dimensions, or the CAD surface and triangle-mesh guides to place it on a part.