Skip to content

Adding a type#

A type declares its on-disk form, and everything built on that form — hashing, caching, new — follows from the declaration. Subclass one of the three leaf kinds, or one of the file bases that refine FileScalar for a format, with its wire name, and the subclass is registered, hashable, cacheable, and returnable from a recipe; nothing else in the system is touched:

import capturegraph as cg


class Manifest(cg.FileScalar, name="edu.example.manifest", extensions=("txt",)): ...


class ColmapModel(cg.DirScalar, name="edu.example.colmap_model"): ...


class Calibration(cg.JSONScalar, name="edu.example.calibration"):
    focal_mm: float
    sensor_mm: float


class Rows(cg.NumpyScalar, name="edu.example.rows"):
    layout = {"ab": ("int32", (-1, 2)), "weight": ("float32", (-1,))}


class Normals(cg.EXRScalar, name="edu.example.normals"): ...


class Cloud(cg.PLYScalar, name="edu.example.cloud"): ...
  • cg.FileScalar — the value is a file; extensions lists what it accepts (Manifest).
  • cg.DirScalar — the value is a directory, held whole (ColmapModel).
  • cg.JSONScalar — a frozen dataclass stored as one JSON file; the annotations are the fields (Calibration).
  • cg.NumpyScalar — a FileScalar for named arrays in one compressed .npz, declared by layout (Rows).
  • cg.EXRScalar — a FileScalar for named float planes in one OpenEXR file (Normals).
  • cg.PLYScalar — a FileScalar for named vertex columns in one binary PLY (Cloud).
  • cg.StillImageFile — a FileScalar for a picture, carrying the decode helpers cg.Image, cg.Panorama and cg.Thumbnail share (pil, exif, linear, to_jpeg); the ui viewers accept any subclass, so a still-image scalar of your own shows in a Gallery like a captured photo.

Two refinements of JSONScalar cover the common special cases. A cg.Enum is a JSONScalar with one string field whose values are a closed set declared with cg.case — how a capture option or any other closed choice is normally added. A scalar becomes a cg.Map key by mixing in cg.Keyable beside its base and implementing key_encode / key_decode, the folder-name codec that sits beside the JSON value codec. key_encode takes a key, raw or a value of the scalar, and returns its folder name; key_decode takes a folder name and returns a value of the scalar. A map holds its keys as values of the scalar, and keys order by their folder names:

class Tier(cg.Enum, name="edu.example.tier"):
    LOW = cg.case("low")
    HIGH = cg.case("high")


class Tag(cg.JSONScalar, cg.Keyable, name="edu.example.tag"):
    value: str

    @classmethod
    def key_encode(cls, key: object) -> str:
        return cls.coerce(key).value

    @classmethod
    def key_decode(cls, name: str) -> "Tag":
        return cls(name)

Leaves compose into cg.Struct (subclass it; the annotations are the fields), cg.Array[T] (a homogeneous sequence) and cg.Map[K, V] (entries keyed by a Keyable scalar), as Containers describes; a composition needs no wire name of its own.

A shape none of those fit subclasses cg.CGType directly and implements load(base) and store(base, value). Two caveats: CGType.schema() raises, so such a type has no wire form — it stays inside recipes, and no schema document can name it for cg.from_schema to rebuild — and the scratch keeps every value it hands back alive by setting _cg_pin on it, so a value class that declares __slots__ must include "_cg_pin" (the leaf kinds and containers already do).

Reading and writing a value#

What a loaded value is, and how a recipe makes one, per kind:

FileScalar. The value is a pathlib.Path subclass pointing at the file: Splat.load(base) returns the .ply path, to open like any file, and a method on the class is its reader. Splat.new("ply") — Splat.new() when the type declares exactly one extension — hands a recipe a fresh, not-yet-written path; the recipe writes it and returns it.

DirScalar. The value is the directory's Path. ColmapModel.new() creates an empty one; stage(source, rel) copies a file or tree to a relative path inside it (the copy is the directory's own, so a tool may overwrite it in place); exec(argv) runs a tool with the directory as its working directory, output logged. This is the vocabulary cg.ManagedDir has — DirScalar under the managed_dir wire name, analysis-only.

JSONScalar. The value is the frozen dataclass instance: construct it with keyword arguments and read fields as attributes. There is no new(), because there is nothing to allocate; storing the value writes one .json file with one key per field (a single-field scalar stores the bare value). Fields may be JSON-native values (numbers, strings, booleans, lists, dicts), optionals of them, and other JSONScalars; a layout the automatic codec cannot express overrides the encode / decode classmethods.

calibration = Calibration(focal_mm=4.2, sensor_mm=6.1)
calibration.focal_mm  # 4.2

A numeric field can say what it measures with cg.Quantity in its Annotated metadata: a unit, a name for a person, and a fixed span. Storage ignores it; charts read it, so cgui.Scatter.of(readings) labels the field "Temperature (°C)" without being told.

class Reading(cg.JSONScalar, name="example.reading"):
    temperature_celsius: Annotated[float, cg.Quantity("°C", name="Temperature")]
    heading_degrees: Annotated[float, cg.Quantity("°", name="Heading", span=(0.0, 360.0))]

NumpyScalar. The value is the .npz path. Rows.of(**arrays) writes a fresh value, coercing each array to the layout's dtype and shape; empty() writes one of no rows; array(name) reads one member, arrays() every member, and count() the number of rows. In a layout shape, -1 is the row dimension: at most one per array (numpy's reshape rule, which of applies), zero in empty(), and count() reads the leading axis of the first layout entry — so declare a row-shaped array first, and any per-value scalar such as ("int32", ()) after it.

rows = Rows.of(ab=[[1, 2], [3, 4]], weight=[0.5, 0.25])
rows.count()          # 2
rows.array("weight")  # array([0.5 , 0.25], dtype=float32)

EXRScalar. The value is the .exr path. Normals.of(planes) writes a fresh value from a dict of H×W arrays keyed by channel name, each stored as a 32-bit float plane; planes() reads every channel back by name. A subclass's named accessors pick from that dict.

import numpy as np

normals = Normals.of({"X": np.zeros((4, 4)), "Y": np.zeros((4, 4)), "Z": np.ones((4, 4))})
sorted(normals.planes())         # ['X', 'Y', 'Z']
normals.planes()["Z"].shape      # (4, 4)

PLYScalar. The value is the .ply path. Cloud.of(vertices) writes a fresh binary little-endian PLY from a dict of equal-length columns keyed by vertex property, each column's dtype naming the PLY property type (float32 → float, uint8 → uchar); vertices() reads every column back by name, and count() reads the vertex count from the header alone.

cloud = Cloud.of({"x": np.arange(3, dtype=np.float32), "red": np.array([0, 128, 255], dtype=np.uint8)})
cloud.count()                    # 3
cloud.vertices()["red"]          # array([  0, 128, 255], dtype=uint8)

of, like new, needs a scratch to allocate in — inside a recipe it has one; in a script or test, see Where new() gets its path.

The worked examples#

capturegraph-recipes adds ten types without touching the core package: seven leaf scalars declared exactly this way — Keypoints, Pairs, Matches, Tracks and Observations as NumpyScalars, Splat as a PLYScalar and RelativeDepth as an EXRScalar — and three Struct compositions of them, PosedImage, Reconstruction and Multiview, one per file in the recipes package's types module. Two more scalars, Driver (a FileScalar of .py files) and Weights (a JSONScalar), sit under cgr.depth. cgr.Splat is a PLYScalar with one reader over the columns vertices() returns:

import capturegraph as cg
import numpy as np


class Splat(cg.PLYScalar, name="edu.cornell.splat.3dgs"):
    """A 3D Gaussian splat model as a PLY file; a loaded value is its file ``Path``."""

    __slots__ = ()

    analysis_only = True

    def centers(self) -> tuple[np.ndarray, np.ndarray]:
        """Every gaussian's centre and colour as ``(positions, colors)``."""
        columns = self.vertices()
        ...

cgr.Keypoints is a NumpyScalar whose layout is the on-disk contract and whose docstring says what each array means:

import capturegraph as cg


class Keypoints(cg.NumpyScalar, name="edu.cornell.keypoints"):
    """The local features found in one image."""

    __slots__ = ()

    analysis_only = True

    layout = {
        "xy": ("float32", (-1, 2)),
        "scale": ("float32", (-1,)),
        "angle": ("float32", (-1,)),
        "descriptors": ("uint8", (-1, 128)),
        "color": ("uint8", (-1, 3)),
        "width": ("int32", ()),
        "height": ("int32", ()),
    }

A recipe writes one with Keypoints.of(xy=..., scale=..., ...) and reads it back with keypoints.arrays() or keypoints.count(); the value in between is a path the scratch hashes, seals and evicts like any other.

The name#

A scalar's byte layout is specified by its reverse-DNS identifier, never by prose. edu.cornell.* names a format this library defines, and its codec is the definition; any other owner — com.apple.arkit.world_map, or your own edu.example.* — names a format defined elsewhere, which is how a foreign tool's output becomes a first-class value. One identifier never names two byte layouts, so a change to the layout is a new name.

Declaring a class registers its name in the process-wide registry, and nothing checks for a collision: a second class declared under a name already taken silently replaces the first as what cg.from_schema resolves the name to. Two packages that both need a format agree on one owner for its name.

Analysis-only types#

analysis_only = True marks a type a recipe produces and a procedure never stores. One mechanism enforces it: a schema walk in @cg.procedure. positions visits every type the schema declares, labelling each by its position from the schema's class name — .field for a struct field, [*] for a container element — and the decorator rejects the schema naming every offending position:

AuthoringError: @cg.procedure schema holds analysis-only types with no
cross-platform mirror: Reconstruction.observations (Observations).
Analysis-only types stay inside recipes; export a typed value into the
schema instead.

So no procedure stores an analysis-only type, and it needs no Swift mirror and no place in The Captured-Data File Format. Every scalar the recipes package adds is analysis-only, as are the core's cg.ManagedDir and cg.Blob; a Struct composition inherits the ban only through the analysis-only members it holds — cgr.Reconstruction is rejected for its Observations field, while a schema of cgr.PosedImage (an Image, a Pose, a Depth) is legal. A type a phone captures is a change to the standard and is implemented on every platform (The Procedure JSON Format).

Where new() gets its path#

A value allocated with T.new() inside the body of a memoized call — a call to a function decorated with cg.pure_function, whose result the scratch caches — lands in that call's live directory and is sealed with its result. One allocated outside any call, in a script or a test, gets a live directory of its own and holds it for as long as the value lives.

The type system does not know the scratch exists. T.new() is defined in the core package and asks the ambient workspace (reference) for a value of T at a fresh path: Workspace.allocate(cls, suffix) answers new(), and Workspace.run(owner, argv, ...) answers DirScalar.exec — owner is the directory value running the tool, argv its command line, and the tool's output is logged wherever the owner's files live. Nothing in the type system installs a workspace: provide(workspace) sets the process's, and current() returns it or raises NoWorkspace. Importing capturegraph.scratch — which import capturegraph does — provides ScratchWorkspace, so NoWorkspace is not the error a reader meets: with the scratch imported, T.new() lands in the active scratch, the machine's shared one unless cg.scratch.configure(path) or a cg.scratch.temporary() block names another. That is why new() works for a type defined anywhere: the type declares its suffix, and the scratch decides the path.

Registration is import#

Declaring the class registers its wire name, and nothing else does. A schema document naming edu.cornell.splat.3dgs resolves to cgr.Splat through cg.from_schema only once capturegraph_recipes has been imported; before that it resolves to an opaque scalar carrying the document's kind and extensions, enough to lay the position out on disk and move its data untouched — a "json" kind loads as parsed JSON data, a "binary" kind as the file's path — and nothing more: none of the real type's methods, and no cases, fields or layout to validate against. A package that adds types is imported, not discovered.

Testing#

Under the cg_scratch pytest fixture — shipped by the core package as a plugin, so any package's tests can name it — T.new() allocates, and a cg.pure_function returning the type seals its result: renames it from the call's live directory into the scratch's immutable object store, named by its content hash, and serves it from there on the next call (Caching and the scratch). A test round-trips a value through a recipe and asserts on what the loaded value reads back, never on where the file went.