Skip to content

Write a filter

A filter is a Python function that takes a dataset and returns a new dataset or a field, running kernels to do the work. Tack's built-in filters are written that way, with the same public names you have, so a filter of your own can do anything theirs do. This tutorial rewrites six built-ins, building on the kernels of Write a mesh algorithm. Each rewrite gives the built-in's result in every part: topology, geometry, fields and their units, sets, ghost marks, global ids, origin, spatial unit and time. Keeping all of them is what lets a filter's output mean what its input meant, on one piece or on many.

A first filter

This filter keeps the cells whose corners all lie in a range of a point field, as td.threshold does:

import numpy as np

import tack
import tack.dataset as td

tack.set_default_device("cpu")


@tack.kernel
def all_corners_inside(cells, u, lower, upper, keep):
    for c in cells:
        inside = 0
        for j in range(cells.NUM_POINTS):
            v = u.corner_value(c, j)
            if lower <= v and v <= upper:
                inside += 1
        keep[cells.entity_id(c)] = 1 if inside == cells.NUM_POINTS else 0


def threshold(data, name, lower, upper):
    """The cells whose corners all lie in [lower, upper]."""
    field = data.fields[name]
    keep = tack.empty((data.num_cells,), tack.i32, device=data.device)
    td.for_each(all_corners_inside, data, "cells", field, float(lower), float(upper), keep)
    return td.extract_cells(data, td.Set.from_flags(data, "cells", keep))


data = td.wavelet(6)                              # 13^3 points, the field "RTData"
mine = threshold(data, "RTData", 150.0, 250.0)
theirs = td.threshold(data, "RTData", 150.0, 250.0)
assert mine.num_cells == theirs.num_cells > 0
assert np.array_equal(mine.fields["RTData"].values.numpy(),
                      theirs.fields["RTData"].values.numpy())

The kernel decides, one flag per cell, written at the cell's global id. td.Set.from_flags turns the flags into a cell set, and td.extract_cells keeps those cells. It brings along every field, set, ghost mark and global id, and the dataset's origin, unit and time, so the filter itself handles none of them.

The array of flags is made with device=data.device. Every public algorithm runs on its input's device, and a filter that allocated on the default device would fail on a dataset that lives elsewhere: a kernel refuses arrays from two devices.

What a filter has to keep

A filter has to compute the right values. It also has to keep what the dataset means:

  • Positions are relative to an origin. A dataset stores its positions relative to an origin of three double-precision numbers, so that coordinates far from zero stay accurate in single precision. Kernels see only the relative values. See Units, coordinates and time.
  • Fields have units. A parameter may come with a unit, and a computed field has the unit of what it is.
  • Pieces have ghost marks. A dataset in pieces marks the cells and points that are copies another piece owns. A reduction must count each value once.
  • Hidden cells hold no valid data. A filter never processes them.
  • Arrays live on a device, and some arrays are implicit: computed when read, never stored.

The sections below rewrite one built-in each and show where a filter of that kind deals with each of these.

The data

w = td.wavelet(6)
data = td.DataSet(w.topology, w.geometry, fields=dict(w.fields),
                  origin=(1.0e6, 2.0e6, 0.0), unit="m", time=3.0, time_unit="s")
data.fields["cell_value"] = td.values_at_centers(data, "RTData")
data.sets["some"] = td.Set(data, "cells", [0, 5, 9, 100])
pieces = td.generate_global_ids(td.split(data, 4, ghost_layers=1))

td.wavelet is VTK's wavelet source, an image with the point field RTData. Its origin is far from the cells, so a filter that mixes world and relative positions gives visibly wrong answers. It has a unit and a time, a cell set, and pieces with a layer of ghost cells and global ids. The example runs every filter on the image, on its tetrahedra and on a ghosted piece.

A field from positions: point_elevation

@tack.kernel
def _elevations(positions, lx, ly, lz, dx, dy, dz, length2, low, span, out):
    for i in range(out.shape[0]):
        p = positions[i]
        s = ((p[0] - lx) * dx + (p[1] - ly) * dy + (p[2] - lz) * dz) / length2
        out[i] = low + min(max(s, 0.0), 1.0) * span


def elevation(data, low_point, high_point, range):
    """Each point's position along the line from low_point to high_point,
    scaled to range: td.point_elevation."""
    # The two points are world positions; the kernel sees positions relative
    # to the dataset's origin. Convert on the host, in f64.
    low = np.asarray(low_point, float) - np.asarray(data.origin)
    direction = np.asarray(high_point, float) - np.asarray(data.origin) - low
    n = size_of(data.geometry.values)               # an implicit array has no .shape
    out = tack.empty((n,), data.dtype, device=data.device)
    # An implicit array goes to the kernel as it is: an image's positions are
    # computed as the kernel reads them, never stored.
    _elevations(data.geometry.values, *map(float, low), *map(float, direction),
                float(direction @ direction), float(range[0]), float(range[1] - range[0]),
                out)
    return td.Field(data.geometry.space, out)

The result is a Field on the geometry's space, one value per point. Three things in it matter for every filter:

  • World parameters convert on the host. The two end points are world positions. The filter subtracts the origin from them in double precision, on the host, before any kernel sees them. The kernel then works in relative positions throughout.
  • Allocate on the dataset's device and in its precision. data.device is the device, and data.dtype is the geometry's floating-point type.
  • Arrays may be implicit. An image's geometry is a UniformCoordinates array, which computes positions instead of storing them. It has no .shape, so the filter takes its length with size_of. Pass an implicit array to a kernel as it is: kernels index implicit arrays as they index stored ones. tack.arrays.materialize stores every value, which an image of a billion points cannot afford. Keep it for code that needs stored memory, such as a pointer handed to another library.

A subset of cells: threshold

@tack.kernel
def _all_corners_inside(cells, u, lower, upper, keep):
    for c in cells:
        inside = 0
        for j in range(cells.NUM_POINTS):
            v = u.corner_value(c, j)
            if lower <= v and v <= upper:
                inside += 1
        keep[cells.entity_id(c)] = 1 if inside == cells.NUM_POINTS else 0


def threshold(data, name, lower, upper):
    """The cells whose corners all lie in [lower, upper]: td.threshold."""
    field = data.fields[name]
    lower = units.magnitude(lower, field.unit, "threshold's bounds")   # "300 K" or 300.0
    upper = units.magnitude(upper, field.unit, "threshold's bounds")
    keep = tack.empty((data.num_cells,), tack.i32, device=data.device)
    td.for_each(_all_corners_inside, data, "cells", field, lower, upper, keep)
    return td.extract_cells(data, td.Set.from_flags(data, "cells", keep))

This is the first filter again, with one addition: its bounds take quantities. units.magnitude turns "300 K", (26.85, "degC") or a plain 300.0 into a number in the field's unit. So threshold(data, "T", "-123.15 degC", (250, "K")) works as the built-in's does. A plain number passes through untouched. For a length, convert to the spatial unit with units.magnitude(value, data.unit, ...).

New geometry on the same cells: shrink

@tack.kernel
def _shrink_corners(positions, offsets, factor, n_cells):
    for c in range(n_cells):
        first = offsets[c]
        end = offsets[c + 1]
        center = positions[first]
        for k in range(first + 1, end):
            center += positions[k]
        center = center / (end - first)
        for k in range(first, end):
            positions[k] = center + factor * (positions[k] - center)


def shrink(data, factor):
    """Each cell shrunk toward its corners' mean: td.shrink."""
    l2 = td.L2(data)                                # each cell its own copy of its corners
    corners = td.project(data, data.geometry, l2)
    if data.num_cells:
        _shrink_corners(corners.values, corners.space.offsets, float(factor), data.num_cells)
    fields = {}
    for name, f in data.fields.items():
        if isinstance(f.space, td.Values) and f.space.on == "points":
            f = td.Field(td.H1(data), f.values, f.unit)
        fields[name] = td.project(data, f, l2) if isinstance(f.space, td.H1) else f
    # The same cells and points as the input: keep its marks, ids, origin,
    # unit and time.
    return td.keep_marks(data, td.DataSet(data.topology, corners, fields=fields,
                                          sets=dict(data.sets)))

shrink keeps the input's cells and points, but builds a new DataSet around them. Each cell gets its own copy of its corners, an L2 field of the positions, moved toward the cell's centre. A dataset built by hand starts with nothing, so the filter hands it the input's ghost marks, global ids, origin, unit and time with td.keep_marks.

Forgetting them is a silent error. Some outputs cannot place their ghost marks: a contour of pieces without ghost cells cannot tell which piece owns a point it makes on a shared edge. Such an output records that its marks were lost, and reductions over it refuse to run rather than count shared points twice. A filter that builds a dataset without keep_marks drops that record, which turns the refusal into a wrong answer. When a filter's output cells and points do not correspond to the input's at all, call td.drop_marks(data, out, reason) instead. It records the loss, and reason is the sentence the refusal will show.

Fields on faces, and units of results: jump

@tack.kernel
def _cell_jump(faces, values, out):
    for f in faces:
        inside = values[faces.side_cell(f, 0)]
        out[faces.entity_id(f)] = (values[faces.side_cell(f, 1)] - inside
                                   if faces.num_sides(f) == 2 else inside * 0.0)


def jump(data, name):
    """A cell field's difference across each face: td.jump."""
    field = data.fields[name]
    values = field.values                           # stored or implicit: kernels index both
    out = tack.empty((data.topology.faces().num_faces,), dtype_of(values), device=data.device)
    td.for_each(_cell_jump, data, "faces", values, out)
    # A difference of degrees Celsius is in kelvin; unknown stays unknown.
    return td.Field(td.Values(data, "faces"), out, units.delta(field.unit))

The kernel runs over faces: side_cell(f, 0) is the cell on the face's inner side, and a boundary face has one side. The result is a field of values on faces.

A field a filter computes gets the unit of what it is. A difference gets units.delta of the field's unit: a difference of degrees Celsius is in kelvin. For other results:

  • units.derived((unit, power), ...) gives the unit of a product of powers. A gradient, for example, is the field's unit over the spatial unit.
  • units.named folds a unit to its SI name, where a filter names its result.

An unknown unit (None) gives None, never a guess. A filter that passes no unit at all also gives None, so forgetting a unit loses it rather than making it wrong.

New cells: triangulate

_TRIANGLES = {int(td.shapes.TRIANGLE): [0, 1, 2], int(td.shapes.QUAD): [0, 1, 2, 0, 2, 3],
              int(td.shapes.PIXEL): [0, 1, 3, 0, 3, 2]}


@tack.kernel
def _piece_counts(cells, pieces, counts):
    for c in cells:
        counts[cells.entity_id(c)] = pieces


@tack.kernel
def _split(cells, table, pieces, starts, connectivity, sources):
    for c in cells:
        e = cells.entity_id(c)
        at = starts[e]
        for t in range(pieces):
            for v in range(3):
                connectivity[(at + t) * 3 + v] = cells.point_id(c, table[t * 3 + v])
            sources[at + t] = e


def triangulate(data):
    """Each polygon of a surface as triangles: td.triangulate."""
    data = td.visible(data)                         # hidden cells are never processed
    n, idt, device = data.num_cells, data.id_dtype, data.device
    groups = [g for g in data.topology.groups() if g.count and int(g.shape.ID) in _TRIANGLES]
    # Count each cell's triangles, scan the counts into starts, fill.
    counts = tack.zeros((n,), tack.i32, device=device)
    for g in groups:
        _piece_counts(g.view(), len(_TRIANGLES[int(g.shape.ID)]) // 3, counts)
    starts = tack.empty((n,), idt, device=device)
    count = exclusive_scan(counts, starts, n) if n else 0
    connectivity = tack.empty((3 * count,), idt, device=device)
    sources = tack.empty((count,), idt, device=device)
    for g in groups:
        table = _TRIANGLES[int(g.shape.ID)]
        _split(g.view(), tack.array(np.array(table, np.int32), device=device),
               len(table) // 3, starts, connectivity, sources)
    out = td.UnstructuredTopology(ConstantArray(int(td.shapes.TRIANGLE), count, dtype=tack.u8,
                                                device=device),
                                  CountingArray(count + 1, start=0, step=3, dtype=idt),
                                  connectivity, num_points=data.num_points)
    # The input's points; each triangle a piece of the cell `sources` names.
    return td.carry(data, out, points=td.Same(), cells=td.Pieces(sources))
  • Start from visible(data). td.visible leaves out hidden cells, whose data is not valid, and AMR cells a finer level covers. Every filter that makes cells starts there.
  • Count, scan, fill. One kernel counts each cell's output, an exclusive_scan turns the counts into each cell's first slot and the total, and a second kernel fills the slots. No atomics are needed, and the output is in input order on every device. The scan is Core's; see Reductions, scans and sorts.
  • A topology's arrays may be implicit. Every output cell is a triangle, so the cell types are a ConstantArray and the offsets a CountingArray. The ConstantArray is made with device=device, like every array the filter makes: an implicit array lives on the device it is made for.
  • carry brings everything else. td.carry takes the input dataset, the new topology, and a map for each kind of entity. A map says where the output's entities came from. Here the points are the input's (Same()), and each triangle is a piece of the cell sources names (Pieces(sources)). The next section, whose filter also makes new points, takes carry apart.

New points and lines: contour of triangles

@tack.kernel
def _crossed_edges(faces, u, level, crossed):
    # A 2D mesh's faces are its edges: 1 where the level lies between the two ends.
    for f in faces:
        above_a = u[faces.point_id(f, 0)] >= level
        above_b = u[faces.point_id(f, 1)] >= level
        crossed[faces.entity_id(f)] = 1 if above_a != above_b else 0


@tack.kernel
def _edge_points(faces, u, level, crossed, slots, ends, weights):
    # Each crossed edge's point: its two ends, and how far it lies from the first,
    # as td.edge_crossing places it -- from the end first by position, so pieces
    # sharing the edge compute it to the same bits.
    for f in faces:
        e = faces.entity_id(f)
        if crossed[e] == 1:
            a = faces.point_id(f, 0)
            b = faces.point_id(f, 1)
            first, second, w = td.edge_crossing(level, a, b, u[a], u[b],
                                                faces.corner_position(f, 0),
                                                faces.corner_position(f, 1))
            ends[slots[e]] = [first, second]
            weights[slots[e]] = w


@tack.kernel
def _crossed_triangles(cells, u, level, counts):
    # A triangle with one or two corners above the level holds one line.
    for c in cells:
        above = 0
        for j in range(3):
            if u[cells.point_id(c, j)] >= level:
                above += 1
        counts[cells.entity_id(c)] = 1 if above == 1 or above == 2 else 0


@tack.kernel
def _segments(cells, u, level, counts, starts, slots, connectivity, sources):
    # Going round the triangle, its line runs from the edge where the values rise
    # past the level to the edge where they fall back, so higher values lie on its
    # right. Its points are those edges' points, numbered by `slots`.
    for c in cells:
        e = cells.entity_id(c)
        if counts[e] == 1:
            rising = slots[0] - slots[0]
            falling = rising
            for k in range(3):
                above_a = u[cells.side_point_id(c, k, 0)] >= level
                above_b = u[cells.side_point_id(c, k, 1)] >= level
                if above_b and not above_a:
                    rising = slots[cells.face_id(c, k)]
                if above_a and not above_b:
                    falling = slots[cells.face_id(c, k)]
            connectivity[2 * starts[e]] = rising
            connectivity[2 * starts[e] + 1] = falling
            sources[starts[e]] = e


def contour(data, name, level):
    """Lines where a point field of a triangle mesh crosses a level: td.contour of a
    surface."""
    data = td.visible(data)
    u = data.fields[name].values
    n, idt, device = data.num_cells, data.id_dtype, data.device
    # The points: one per edge the level crosses, numbered by a scan over the edges.
    nf = data.topology.faces().num_faces
    crossed = tack.empty((nf,), tack.i32, device=device)
    td.for_each(_crossed_edges, data, "faces", u, level, crossed)
    slots = tack.empty((nf,), idt, device=device)
    count = exclusive_scan(crossed, slots, nf) if nf else 0
    ends = tack.empty((count,), tack.vec(2, idt), device=device)
    weights = tack.empty((count,), u.dtype, device=device)
    td.for_each(_edge_points, data, "faces", u, level, crossed, slots, ends, weights)
    # The lines: one per triangle the level crosses, numbered by a scan over the cells.
    counts = tack.empty((n,), tack.i32, device=device)
    td.for_each(_crossed_triangles, data, "cells", u, level, counts)
    starts = tack.empty((n,), idt, device=device)
    lines = exclusive_scan(counts, starts, n) if n else 0
    connectivity = tack.empty((2 * lines,), idt, device=device)
    sources = tack.empty((lines,), idt, device=device)
    td.for_each(_segments, data, "cells", u, level, counts, starts, slots, connectivity,
                sources, incidence="faces")
    out = td.UnstructuredTopology(ConstantArray(int(td.shapes.LINE), lines, dtype=tack.u8,
                                                device=device),
                                  CountingArray(lines + 1, start=0, step=2, dtype=idt),
                                  connectivity, num_points=count)
    # Point i lies between points ends[i] at weights[i]; line i lies in cell sources[i].
    return td.carry(data, out, points=td.Interpolate(ends, weights), cells=td.Pieces(sources))

This filter makes the lines where a point field crosses a level on a mesh of triangles, which is what td.contour gives for a surface. It makes new points, one on each edge the level crosses, and new cells, each a line inside a triangle. So carry gets a map for each.

  • Number the new points by the edges. A 2D mesh's faces are its edges (data.topology.faces()), each stored once and shared by the triangles on either side. One kernel over the faces flags the edges the level crosses. A scan numbers them. A second kernel records each new point's two ends and its weight, how far it lies from the first end. The two triangles on an edge then name its point by the same number, slots[face_id], so their lines join. That kernel over the triangles reads their faces, so its for_each asks for them: incidence="faces".
  • Place each crossing as the built-ins do. td.edge_crossing is the rule every built-in cut uses. It interpolates from the end that comes first by position (x, then y, then z), so every piece holding the edge computes the point to the same bits.
  • Orient the lines. Going round each triangle, its line runs from the edge where the values rise past the level to the edge where they fall back. The higher values then lie on its right, as with the built-in.

The built-in does three things this rewrite leaves out. It contours several levels at once. It skips cells with a NaN. And when a point's value is the level, or a crossing lies within half an ulp of a point, it makes the crossings of every edge there into that one point. edge_crossing reports that case by returning the point as both ends. The example picks a level no crossing lands on a point at.

carry, map by map

td.carry(data, out, points=..., cells=...) builds a dataset on the new topology out, and brings everything of data that its maps say how to bring:

Map Output entity i is Used for
Same() input entity i points or cells kept as they are
Take(ids) input entity ids[i] a subset, a reordering
Pieces(ids) a part of input cell ids[i] cells cut from cells: triangles, tetrahedra, contour lines
Interpolate(ends, weights) the point weights[i] of the way from input point ends[i][0] to ends[i][1] points made on edges: contours, clips

Each kind of entity has its own keyword. points= and cells= are the usual two. faces= and edges= carry values stored on a mesh's faces or edges. faces_to_cells= and edges_to_cells= say that the output's cells are the input's faces or edges, as in an extracted surface or extracted edges.

What goes with each map:

  • Point fields (H1 fields and values on points) go by the points map. Interpolate blends them as va + w * (vb - va), so the contour's points get RTData (the level, to rounding) and every other point field. A field of integers cannot be blended, and is left behind.
  • The geometry is a point field like any other, so Interpolate places the new points. The filter never computes a position. A filter that computes positions some other way passes them as geometry=.
  • Cell fields (Constant fields and values on cells) go by the cells map: each line takes its triangle's value. L2 fields go only with Same and Take, since a piece of a cell is not the whole cell their basis describes. H1 fields above order 1 keep their order under Same and Take too, and bring their corner values under other maps.
  • Sets go by the same maps, so a line is in a cell set when its triangle is. A point set cannot go through Interpolate, and is left behind.
  • Ghost marks. A line takes its triangle's mark. A new point takes the mark of its edge's first end by position, so the piece that owns that end owns the point, and each line or point of the whole's contour is owned once over the pieces. Pieces without ghost cells cannot tell who owns what they make on the edges they share. Their output records that its marks were lost, as shrink above describes. td.generate_global_ids of the outputs then decides the owners by matching positions, which works because every piece computes a shared point to the same bits.
  • Global ids go with entities that are input entities (Same, Take). Made points and pieces of cells have none.
  • The frame, the origin, spatial unit and time, always comes along.

A kind of entity with no map carries nothing: no fields, sets, marks or ids of that kind. fields= (a list of names) limits which fields are carried.

A reduction over pieces: entropy

def entropy(pieces, name, bins=10):
    """The entropy of a point field's histogram over every piece: td.entropy."""
    blocks = tc.Blocks([p.device for p in pieces], pieces.world)
    # Owned values only: a point a ghost layer copies is counted once.
    values = {g: td.owned_values(p, name).numpy() for g, p in zip(blocks.local, pieces)}
    lo = blocks.all_reduce({g: v.min() for g, v in values.items()}, op="min")
    hi = blocks.all_reduce({g: v.max() for g, v in values.items()}, op="max")
    counts = {}
    for (g, v), piece in zip(values.items(), pieces):
        c, _ = histogram(tack.array(v, device=piece.device), bins=bins, range=(lo, hi))
        counts[g] = np.asarray(c.numpy() if hasattr(c, "numpy") else c, float)
    p = blocks.all_reduce(counts)                    # summed in piece order, on every rank
    p = p[p > 0] / p.sum()
    return 0.0 - float((p * np.log2(p)).sum())

This filter takes a PartitionedDataSet, the pieces of a dataset, and returns one number for the whole.

  • Count each value once. td.owned_values gives the values of the cells and points a piece owns. It leaves out ghost copies and hidden cells, so a value shared by two pieces is counted once. It refuses a piece whose marks were lost.
  • Reduce over the blocks. tack.communication.Blocks holds this rank's pieces, one block each. all_reduce combines one value per block in global block order, so a floating-point sum has the same bits however the pieces are spread over ranks. The same function runs unchanged under MPI: give the PartitionedDataSet a World(comm). See Communication.

Algorithms that need their neighbours' data rather than a reduction use the rest of the Communication layer: exchanges and ghost plans (Exchange and plans) and sending points to the pieces that hold them (Routing).

What to keep, and what forgetting it gives

Concern Do Forgetting it gives
Origin Convert world parameters with data.origin on the host; build datasets through carry, keep_marks, or with origin= Wrong positions, visible only far from zero
Device Allocate with device=data.device An error on a dataset on another device
Implicit arrays size_of, materialize, or index them in a kernel AttributeError on .shape
Hidden cells Start from visible(data) Cells with invalid data processed
Ghost marks carry maps, keep_marks, or drop_marks Shared cells and points counted once per piece
Units units.magnitude for parameters; units.delta or units.derived for results A number in the wrong unit, or a wrong unit on the result
Pieces owned_values, Blocks.all_reduce Ghost copies counted, or results that depend on the rank count

Run it

uv run python docs/examples/data_filters.py --arch cpu --check

The check holds each rewrite to its built-in on the image, its tetrahedra and a ghosted piece, and a threshold with bounds in degrees Celsius and kelvin to the built-in's. The test suite holds the same rewrites, and a seventh (net_flux, cells summing their faces), to the built-ins with a check that they import nothing private. Download the complete program.

Details

  • The public pieces. Everything this page uses is public: td.carry and its maps (Same, Take, Pieces, Interpolate), edge_crossing, keep_marks, drop_marks, visible, owned_values, Set.from_flags, td.units and tack.communication. A built-in filter that comes to need anything else is a gap to report. The Data Model reference documents each name.
  • Higher-order data. A filter that reads corner values, as these do, sees an H1 field above order 1 through its corners. The built-in cuts instead cut such cells on linear sub-cells, with each crossing placed on the field itself; see Extract.
  • Several fields of one name. A point field and a cell field may share a name. data.fields[name, td.Constant] picks the cell one; see Fields.

Where to go next

  • VTK puts a filter of your own into a VTK pipeline, beside VTK's filters.
  • Filters over pieces shows what changes when the data comes in pieces: ghost cells, global ids, merging, MPI.