Spool Chunking

Spool.chunk works in two stages. A planner decides everything from metadata alone. Assembly then loads, trims, and joins patch data, but only when a patch is requested. The code cells in this note run against the real implementation, so the doc build fails if the note drifts.

Plans

The planner reads the spool’s flat metadata table (see Spool Index) and produces a ChunkPlan with two tables:

  • outputs: one row per patch the chunked spool will hold;
  • members: which slice of which source patch feeds each output.

Spool.chunk_plan takes the same arguments as chunk and returns the plan it would run. The chunked spool is a new in-memory catalog whose rows are the plan’s outputs. Asking for a patch loads its members through the parent spool and runs the assembly engine (dascore.utils.patch_assembly) on them.

Each call chunks one dimension; chain calls for more.

  • Chunking the same dimension again re-plans from the current view’s members (the collapse rule).
  • Chunking a different dimension plans over the current outputs, keeping the earlier boundaries. chunk(time=2).chunk(distance=100) splits both dimensions.

concatenate uses the same machinery but groups by order instead of continuity. build_concat_plan splits patches into groups exactly as a chunk plan does (kind, dimensions, every other dimension’s coordinate, the dimension’s units) and checks other attributes with conflict the same way.

It then takes each group’s rows in order along the dimension and bundles them by the requested count, with no sampling or gap test. Coordinates are checked when the output loads, not by the plan, and assembled patches follow the plan rather than re-deciding it.

import dascore as dc

spool = dc.get_example_spool("random_das")
plan = spool.chunk_plan(time=3)
assert len(plan.outputs) == len(spool.chunk(time=3))
assert {"output_id", "_patch_row", "_modified"}.issubset(plan.members.columns)
# Resolved parameters are recorded on the plan, never left in config.
assert isinstance(plan.params["group"], tuple)
assert plan.params["sampling_group_tolerance"] == dc.get_config().sampling_group_tolerance

# Chaining splits both dimensions: the second chunk plans over the
# first one's outputs, not the original members.
chained = dc.get_example_spool("random_das").chunk(time=None).chunk(distance=100)
assert all(p.shape[p.get_axis("distance")] <= 100 for p in chained)

Plans are deterministic: the same spool gives the same plan whatever its row order. Members marked _modified=False load whole, skipping per-patch selection.

Which patches can merge

Patches merge only when they agree on all four of these.

1. Kind. By default, the attributes in the patch_kind_attrs config option: acquisition key, data category, and tag (see Patch Compatibility). Override it per call with group=. Patches of different kinds go to separate outputs; that is never an error. A missing value counts as a value, so patches that never recorded an attribute group together, apart from those that did. Names passed to group= must exist somewhere in the spool; names from config are used where present.

2. Structure. The dimensions, the coordinate of every dimension not being chunked, and the chunked dimension’s units. A metre patch never merges with a seconds patch, nor a patch with units with one without. Compatible units such as metres and feet are normalized to one unit per dimensionality before planning, so they merge, and assembly converts each member to the first member’s units.

3. Sampling. Step sizes must be within config.sampling_group_tolerance (default 5%) of the group’s smallest absolute step, and in the same direction. Ascending never merges with descending, though contiguous descending patches merge with each other.

4. Continuity. Within each group, so unrelated patches can’t bridge a gap, rows are taken in coordinate order and each seam is judged against the furthest label reached so far, the earlier patch’s end, on that patch’s step (_cell_seams). The later patch joins when its first label lies one step past that end, give or take max_shift (a fraction of a step, dascore.config.max_shift by default) and the precision labels are stored in: a tick for integers and times on a step of 100 ticks or more, float exactness for floats. A wider seam is a gap and starts a new stretch. A patch with holes is one row, which the planner cuts at its holes (the pieces Patch.split_gaps returns) using the runs the index stores. A hole inside a patch is therefore judged like a gap between patches, and pieces landing in one output are read from their patch once.

A later patch which starts sooner than that overlaps: each sample is kept once and the earlier patch wins. It continues from the first of its own samples at least one step less max_shift past the earlier end, if that sample passes the test, and its earlier samples are dropped; otherwise its samples past the earlier end start a new stretch, and a patch with none is dropped. An overlap on the earlier patch’s grid therefore joins, and one half a step off it splits.

tolerance, off by default, widens the test: a number t also joins seams up to t steps wide, and a quantity (1 * s, 2 * m) or a timedelta joins seams up to that width in the coordinate’s units. Patches with no step have none to judge a seam against, so they join where they overlap or touch, and otherwise only under that form. A seam wider than 1.5 steps joined because of tolerance warns, as chunk‘s default did in DASCore 0.1.24. A GapTolerance passed as tolerance keeps its own meaning, an absolute value being the excess over one step, as coordinates’ get_discontinuities and the waterfall’s gap_factor read it.

Gap and coverage reports

Spool.get_gaps and Spool.get_coverage use the same grouping. A get_coverage row is one group under rules 1–3. A get_gaps row is a seam rule 4 starts a new stretch at, under the same tolerance and max_shift, with the samples it is missing; a seam 1.3 steps wide is listed, missing none, unless tolerance spans it. On a spool of unplanned patches, merging gives one patch per coverage row plus one per gap. The reports describe the rows a spool currently shows, not a plan’s members, so a chunked spool reports on its chunked patches, and re-chunking it need not reproduce those counts.

import numpy as np

t0 = np.datetime64("2020-01-01", "ns")
p1 = dc.get_example_patch(time_min=t0, acquisition_key="XX1.R2D1..RAW")
time = p1.get_coord("time")
p2 = dc.get_example_patch(time_min=time.max() + time.step, acquisition_key="XX1.R2D1..RAW")
source = "XX2.R2D1..RAW"
p3, p4 = p1.update_attrs(acquisition_key=source), p2.update_attrs(acquisition_key=source)

# Two data sources, each with two contiguous patches: two outputs, no error.
spool = dc.spool([p1, p2, p3, p4])
merged = spool.chunk(time=None)
assert len(merged) == 2

# The reports group the same way, so the counts tie.
assert len(merged) == len(spool.get_gaps()) + len(spool.get_coverage())

Conflicting attributes

All other attributes (not grouping attributes, not dimensions) must be equal within a group. conflict decides what happens when they aren’t:

  • "raise" (default) raises an error;
  • "drop" leaves the attribute out;
  • "keep_first" uses the first member’s value, set or not.

A missing value (null or "") counts as a value, so an attribute one member set and another didn’t is a conflict; the output can only state one thing. History, the SEG-Y text header (segy_text_header) and ids are never checked: the output carries the first member’s history and text header, and derives its ids from all its members. Merging members whose histories differ, such as processed with unprocessed data, warns.

conflict also settles a non-dimensional coordinate on another dimension which the members hold differently or not at all: "keep_first" keeps the first member’s (unless it lacks one, or the coordinate rides the chunked dimension), "drop" leaves it out, and both warn naming it. The output’s index describes the coordinate the merge keeps.

import pytest
from dascore.exceptions import CoordMergeError

typed = p1.update_attrs(data_type="velocity")
with pytest.raises(CoordMergeError, match="data_type"):
    dc.spool([typed, p2]).chunk(time=None)

merged = dc.spool([typed, p2]).chunk(time=None, conflict="keep_first")
assert len(merged) == 1
assert merged.get_contents()["data_type"].iloc[0] == "velocity"
assert merged[0].attrs.data_type == "velocity"

Patches missing the dimension

Chunking works along dimensions. A patch without the chunked dimension raises by default, including one that has the name only as a non-dimensional coordinate, which can’t be trimmed or merged along. Pass on_missing_dim="drop" to skip such patches; silently dropping data needs an explicit opt-in.

import pytest
from dascore.exceptions import ChunkError

no_time = [dc.get_example_patch().mean("time") for _ in range(2)]
with pytest.raises(ChunkError, match="on_missing_dim"):
    dc.spool(no_time).chunk(time=None)
assert len(dc.spool(no_time).chunk(time=None, on_missing_dim="drop")) == 0

# A name carried only as a non-dimensional coordinate counts as missing.
base = dc.get_example_patch()
aux = base.update_coords(
    sensor=("distance", np.arange(base.shape[base.get_axis("distance")], dtype=float))
)
with pytest.raises(ChunkError, match="non-dimensional coordinate"):
    dc.spool([aux]).chunk(sensor=100)

One grid per stretch

Before any window is cut, each stretch gets one grid (_fit_grids). It starts at the stretch’s first label, and its samples are numbered consecutively across its patches, overlaps already trimmed. Its step is the roundest one any patch states (fewest significant digits in the rate or the step; ties go to the earliest patch) for which every patch’s first and last label lies within max_shift of its numbered position; this is found for all stated steps at once, as the interval of steps every patch’s ends allow. If none fits, the step spreads the stretch evenly from its first label to its last, as DASCore 0.1.24 did; that is also how a seam joined only by tolerance is closed. Integer and time steps are exact fractions of a tick, so a stretch of 1024 Hz files keeps its exact step. A stretch holding a patch with no step has no grid and keeps its labels as recorded.

Each output’s members carry its slice of that grid (_{dim}_stretch), which assembly labels the output with, so every output is one evenly sampled run and chunk outputs rejoin exactly; a float slice reproduces the stretch’s linspace labels bit for bit. A stretch of one whole patch on its own grid is left with its own labels. chunk_plan’s members record why each starts where it does (reason), how far the grid moved its labels (shift, in steps) and how many samples an overlap dropped (dropped).

from dascore.core.coords import get_coord

def late(steps):
    """A patch starting `steps` samples after the first one's start."""
    step = np.timedelta64(1, "ms")
    start = np.datetime64("2020-01-01", "ns") + int(steps * 1_000_000) * np.timedelta64(1, "ns")
    return dc.Patch(
        data=np.zeros(1000), coords={"time": get_coord(start=start, step=step, shape=(1000,))}, dims=("time",)
    )

# each file 0.15 step later than the last: they join, and the grid spreads them
drifting = dc.spool([late(i * 1000.15) for i in range(5)])
(joined,) = drifting.chunk(time=None)
assert joined.get_coord("time").evenly_sampled
assert drifting.chunk_plan(time=None).members["shift"].max() > 0  # in steps
# and windows cut from that grid rejoin to it exactly
rejoined = dc.spool(list(drifting.chunk(time=0.25))).chunk(time=None)
assert rejoined[0].get_coord("time") == joined.get_coord("time")

Regular windows

A chunk length splits each stretch into half-open windows [start, start + length), the first starting at the stretch’s first label and each length - overlap after the previous one. A window holds exactly the samples whose labels on the stretch’s grid fall inside it.

  • No overlap: windows split the samples with no repeats. A length that isn’t a whole number of samples gives windows whose sample counts differ by one.
  • With overlap: windows stop at the first one holding the group’s last sample, so the last window always holds a sample the previous one doesn’t.
  • Partial windows: a window is complete when it ends no more than one sample past the group’s last sample. Only complete windows are kept unless keep_partial=True.

An output’s coordinate range runs from its first sample to its last when its sources are evenly sampled with known positions. Otherwise (uneven coordinates, or a view trimmed by a relative selection) it states the window’s own bounds.

Chunking by size

A chunk length can be a quantity instead of a bare number:

  • a unit compatible with the coordinate (time=10 * s, distance=100 * m), converted to the group’s coordinate units; a spool with no units for that coordinate raises, since there’s nothing to convert to;
  • an amount of data (time=25 * megabytes), which sizes each output by its data array.

A bare number means the coordinate’s own units, like everywhere else. overlap accepts the same forms.

A data size is resolved per group, since it depends on the group’s step, its size along the other dimensions, and its dtype:

bytes_per_sample = itemsize * (product of the other dimensions' sample counts)
n_samples        = floor(requested_bytes / bytes_per_sample)

Rounding down means an output’s data array never exceeds the request.

Packing factor

The length is also divided by a packing factor, which is what actually guarantees that bound. An output holds the sum of its members’ sample counts, which equals span / step + 1 only when the group sits on one grid. Members separated by less than one sample each add their own trailing sample, so near-contiguous files whose boundaries miss the grid pack more samples into a span than the grid predicts.

The factor is the group’s highest local sample density, in units of its step: exactly 1.0 when members tile the grid. It is reported in params["size"]. Measuring in step units also makes the choice of step irrelevant; the smallest is used only to make rounding as fine as possible. Overlapping members are left out of the measurement because they are deduplicated and add no samples.

Dtype

Dtype is resolved per output, not per group. It is deliberately not a grouping rule, since that would change which patches merge, so a group can mix dtypes. An output drawn only from float32 members really is float32; using the whole group’s np.result_type would over-size later chunks and make the plan row disagree with the patch it builds, which spool equality compares. An output that spans members of different dtypes gets the upcast type, matching what assembly produces. A metadata table without dtype (a hand-built dataframe, or an index from before the column existed) raises ChunkError rather than guessing.

from dascore.units import megabytes

target = 1 * megabytes
sized = dc.get_example_spool("random_das").chunk(time=target)
assert max(p.data.nbytes for p in sized) <= 1e6

# The plan explains what the request resolved to.
plan = dc.get_example_spool("random_das").chunk_plan(time=target)
(part,) = plan.params["size"]["partitions"]
assert part["bytes_per_sample"] == part["itemsize"] * part["slab_samples"]
assert part["n_samples"] == int(1e6) // part["bytes_per_sample"]
assert part["packing"] == 1.0  # this spool tiles its grid exactly

# The dtype carries through a chained chunk, so sizes still work.
chained = dc.get_example_spool("random_das").chunk(distance=100).chunk(time=target)
assert max(p.data.nbytes for p in chained) <= 1e6

A size counts only the data array; coordinates, attributes, and copies made by later processing are extra. If one sample along the chunked dimension is already bigger than the request, each output holds one sample and a warning says so.

Merged coordinates

Assembly joins the members’ data and coordinates, then labels the chunked dimension with the output’s slice of its stretch’s grid (see above). chunk’s snap_coords argument is deprecated and ignored: use Spool.concatenate to keep recorded labels, and Patch.snap_coords to regularize them.

A gap tolerance joins is closed by that grid, spreading the stretch’s labels evenly over it. chunk never fills. Spool.fill_gaps fills instead: it joins patches as chunk(time=None) would, across gaps up to its size, each output keeps its first patch’s grid, the patches after each gap move onto it by under half a step, and the missing samples are written. A later chunk along the filled dimension is planned once, straight over the source files (unless it states its own tolerance or max_shift, or the fill’s conflict is not "raise", when it plans over the fill’s outputs); a cut builds the fill’s outputs and plans over them. Either way, loading a window reads only the files it reaches, padding with the fill where it runs past them; under a conflict of "keep_first" or "drop" it reads every file of its stretch, since the attrs that policy settles depend on all of them.

import warnings

# Contiguous members: one evenly sampled run.
patch = dc.spool([p1, p2]).chunk(time=None)[0]
assert patch.get_coord("time").evenly_sampled

# A seam three steps wide is a gap unless a tolerance spans it ...
gap_start = time.max() + 3 * time.step
p_gap = dc.get_example_patch(time_min=gap_start, acquisition_key="XX1.R2D1..RAW")
assert len(dc.spool([p1, p_gap]).chunk(time=None)) == 2
with warnings.catch_warnings():
    warnings.simplefilter("ignore")  # joining across a gap warns, as released
    # ... which spreads the labels over it,
    spread = dc.spool([p1, p_gap]).chunk(time=None, tolerance=5)[0]
# fill_gaps writes the missing samples on the sources' step instead;
filled = dc.spool([p1, p_gap]).fill_gaps(time=2, samples=True)[0]
# a size in the coordinate's units is the missing span.
absolute = dc.spool([p1, p_gap]).fill_gaps(time=2 * time.step)[0]
assert spread.get_coord("time").evenly_sampled
assert len(spread.get_coord("time")) == 2 * len(time)
assert filled.get_coord("time").step == time.step
assert np.isnan(filled.data).any()
assert absolute.get_coord("time") == filled.get_coord("time")

Combined spools

spool + spool makes a lazy spool over both spools’ metadata. Chunking works across the join, so contiguous patches from different spools, even a mix of file-backed and in-memory, merge into one. The sum is on the backend its operands were set to; under a lazy backend a merge which has to read patches held in memory beside files is the numpy_fallback setting’s to allow.

combined = dc.spool([p1]) + dc.spool([p2])
assert len(combined.chunk(time=None)) == 1

# Spools are sets of patch instances: the same patch (or a copy) appears
# once; operations make new instances.
assert len(dc.spool([p1, p1])) == 1
assert len(dc.spool([p1, p1.new()])) == 2
assert len(dc.spool([p1]) + dc.spool([p1])) == 1

Explicit output windows

chunk and chunk_plan take lengths only, and refuse an (n, 2) array of windows. Spool.select returns each source’s part of each window, unjoined, and Spool.cut joins each window’s parts as chunk joins them.

Both take windows in these forms, though cut bounds dimensions only and select also takes non-dimensional coordinates:

  • An (n, 2) numpy array, nested lists, or a quantity wrapping an (n, 2) array (np.array([[10, 20]]) * m). Each row is one window, inclusive at both ends.
  • Reversed bounds are swapped (rule 8 of the coordinate guidelines). None, ..., NaN, or NaT leaves a bound open at the edge of the data; a signed infinity opens its own side, whichever column holds it.
  • Several dimensions can take arrays with the same number of rows; row i of every array forms one box. A row open at both ends spans its dimension, and keeps patches lacking it.
  • Bare numbers are in each patch’s own units; quantities convert to them as absolute points. On a datetime coordinate, bounds are instants: datetimes, datetime strings, or numbers of seconds since 1970, as Patch.select reads them. A timedelta or time quantity there is refused, since it is an offset; add it to a start time.
  • Outputs come in window order, overlapping and duplicate rows included, each window’s parts in the spool’s order from select and in coordinate order from cut. An empty (0, 2) array gives an empty spool.
  • No window has to be complete (rule 9 of the coordinate guidelines): a window running past the data, or into a gap, keeps the samples it holds, and one holding none gives nothing.

Planning pairs every window with every source in array operations, so thousands of windows plan in seconds. It reads coordinates, never data arrays: a window’s samples come from each source’s coordinate, which the index states for regular grids and the file states otherwise, and a source whose coordinate is unknown raises MissingPatchError.

Among the sources one window reaches, an earlier source keeps the samples it holds (rule 6 of the coordinate guidelines), judged after each source’s samples were chosen in its own units. cut then joins the parts of each window which agree under rules 1–3 above, across the seams rule 4 passes, along every dimension, taking tolerance, max_shift and conflict as chunk does, the first two along the dimensions each window bounds; joining repeats along every dimension until no join reduces the parts; a tolerance with units applies along dimensions of its kind. Parts are cut at their sources’ holes, so a window split by a gap gives fragments, each stating the window’s row as its window attribute. A window held in one part is not rejoined and keeps its recorded labels and units. A cut replaces any window, feature_id or annotation label its sources carry.

import numpy as np

patch = dc.get_example_patch().select(distance=(0, 9))
source = dc.spool(patch)
windows = np.array([[2, 4], [8, 10]])
cut = source.cut(distance=windows)
ends = [(p.get_coord("distance").min(), p.get_coord("distance").max()) for p in cut]
assert ends == [(2, 4), (8, 9)]
assert cut.get_contents()["window"].tolist() == [0, 1]
boxes = source.cut(time=np.array([[None, None]] * 2), distance=windows)
assert [p.get_coord("distance").max() for p in boxes] == [4, 9]
# a gap splits a window into fragments, labelled by the window
gapped = dc.spool([patch.select(distance=(0, 4)), patch.select(distance=(7, 9))])
assert gapped.cut(distance=np.array([[2, 8]])).get_contents()["window"].tolist() == [0, 0]