Spool

Open in marimo

A Spool manages patches from memory, files, directories, or remote resources. File-backed spools scan metadata first and load arrays only when patches are accessed.

import dascore as dc

spool = dc.get_example_spool()

Data sources

Use dc.spool(...) for any supported input:

memory_spool = dc.spool([dc.get_example_patch()])
file_spool = dc.spool("examples://terra15_das_1_trimmed.hdf5")

Directory spools maintain an index for fast metadata queries. Call update() after files change.

# Write example patches to a directory to get a usable path.
directory = dc.examples.spool_to_directory(dc.get_example_spool())
directory_spool = dc.spool(directory).update()

Remote UPath resources use the same constructor; see Working with remote patches. To keep the index elsewhere or open a spool from an index alone, see Index location; for key=value directory names, see Path attributes.

Accessing patches

Indexing and iteration load patches. Slicing, integer arrays, and boolean masks return a new spool.

first_patch = spool[0]
subset = spool[1:]

for patch in spool:
    ...

Integer arrays reorder patches and may repeat them; boolean arrays keep positions marked True:

import numpy as np

reordered = spool[np.array([2, 0])]
mask = np.ones(len(spool), dtype=bool)
mask[1] = False
without_second = spool[mask]

Lists and pandas Series follow the same positional rules. Slicing remains lazy: it narrows the spool plan without loading selected arrays.

Rows from get_contents() align with spool positions, so a dataframe condition can select the same patches. Do not reuse a mask from a differently ordered spool.

diverse = dc.get_example_spool("diverse_das")
rows = diverse.get_contents()
tagged = diverse[rows["tag"] == "some_tag"]

Inspecting and selecting

Displaying a spool shows its patch count, coordinate extents, and tracks for distinct patch kinds. Large spools omit the expensive summary according to display_max_patches.

A track groups patches with the same configured kind attributes and measures their span along time, or another available dimension. Single-kind spools omit redundant tracks because their overall extent already carries the same information. Tracks describe extents, not coverage; use get_coverage for missing-data statistics.

dc.get_example_spool("diverse_das")
DASCore Spool 🧵 (18 Patches)
Dimensions (time, distance)
    time:     1989-05-04T00:00:00 to 2030-01-01T00:00:07.996  <40.7 y>
    distance: 0.000 to 299.000 m  <299.000 m>
Tracks (7 along time)
    big_gaps                 3 patches  2020-01-03 <26 s>
    overlaps                 3 patches  2020-01-03 <24 s>
    random                   3 patches  2020-01-03 <24 s>
    smallg                   3 patches  2020-01-03 <24 s>
    some_tag                   1 patch  2020-01-03 <8 s>
    wayout                   2 patches  1989-05-04 <40.7 y>
    DAS2.R2D1..RAW · random  3 patches  2020-01-03 <24 s>
    (coverage: spool.viz.coverage())

Spool.get_contents returns one metadata row per patch without loading its data array. File-backed rows include source_path, source_format, and source_patch_key. A source holding one patch is recorded with an empty source_patch_key unless its key is an HDF5 dataset path; dc.scan still reports the reader’s key.

contents = diverse.get_contents()
contents[["time_min", "time_max", "source_format"]].head()
time_min time_max source_format
0 2020-01-03 00:00:00 2020-01-03 00:00:07.996 memory
1 2020-01-03 00:00:08 2020-01-03 00:00:15.996 memory
2 2020-01-03 00:00:16 2020-01-03 00:00:23.996 memory
3 2020-01-03 00:00:00 2020-01-03 00:00:07.996 memory
4 2020-01-03 00:00:08 2020-01-03 00:00:15.996 memory

The dataframe is a realized relation, so requesting every row can be expensive for a very large remote archive. Apply select first whenever the index backend can push down the predicate.

Spool.select filters metadata and trims matching patches along coordinates.

recent = diverse.select(time=("2020-01-03", ...))
sources = diverse.select(acquisition_key={"DAS2.R2D1..RAW", "DAS3.R2D1..RAW"})
glob_tags = diverse.select(tag="some*")

Coordinate selections both discard patches outside the range and trim intersecting patches. Attribute selections only filter rows. Collections, globs, and compiled regular expressions are accepted for string metadata. A glob means what SQLite’s GLOB means, since that is what the index applies: * and ? are wildcards, [abc] is a character class, and [^abc] negates one.

import re

regex_tags = diverse.select(tag=re.compile(r"^some"))

Unselect

Spool.unselect returns patches rejected by the same attribute selection.

not_tagged = diverse.unselect(tag="some_tag")

Patch coordinates are excluded because complementing an interior range would split every patch; use Patch.unselect for that. Inventory coordinates are allowed; see Inventory.

Chunking

Spool.chunk lazily changes patch boundaries. It can merge contiguous patches, create fixed windows with overlap, or limit array size.

from dascore.units import megabytes, s

windowed = spool.chunk(time=3 * s, overlap=1 * s, keep_partial=True)
merged = spool.chunk(time=None)
bounded = spool.chunk(time=1 * megabytes)

overlap accepts the same coordinate-unit, quantity, or data-size forms as the chunk length. keep_partial=True retains a shorter final window. Passing time=None asks DASCore to merge every contiguous compatible segment.

chunk takes lengths only. To request particular absolute windows, pass an (n, 2) array to select or cut. select returns each matching source piece separately; cut joins the pieces of each window as chunk joins patches, so a window crossing files gives one patch, and a gap leaves fragments labelled by the window’s row. Rows stay in input order, including overlaps and duplicates, and a window running past the data keeps the samples it holds. Neither loads measurement arrays until a patch is asked for.

small = dc.spool(dc.get_example_patch().select(distance=(0, 9)))
windows = np.array([[2, 4], [6, 8]])
source_pieces = small.select(distance=windows)
cut = small.cut(distance=windows)
assert len(source_pieces) == len(cut) == 2
assert cut.get_contents()["window"].tolist() == [0, 1]

chunk_plan shows what a chunk call would produce without loading data. See Spool chunking for how the planner works.

Data-size limits cover the array only, not coordinates, metadata, or later processing copies. MB is decimal and MiB is binary.

Joining across seams

chunk joins two patches when the later starts one step after the earlier ends, give or take a fraction of a step set by max_shift, and then fits one evenly sampled grid to each stretch of joined patches. A wider seam is a gap, and starts a new output. tolerance, off by default, also joins seams up to that many steps wide (or that width, given as a quantity or timedelta) and closes them by spreading the stretch’s labels evenly, as DASCore 0.1.24 did by default with tolerance=1.5; it warns when a joined seam is wider than 1.5 steps.

from dascore.examples import random_spool

late = random_spool(time_gap=np.timedelta64(1_200_000, "ns"), length=2)
assert len(late.chunk(time=None)) == 2  # a seam 1.3 steps wide is a gap
assert len(late.chunk(time=None, tolerance=1.5)) == 1

To fill the holes tolerance bridges, or to report gaps and coverage, see Large archives.

Concatenate

Spool.concatenate joins each compatible group even across gaps or overlaps. Unlike chunk, it does not require continuity.

earlier = dc.get_example_patch()
one_hour = dc.to_timedelta64(3600)
later = earlier.update_coords(time_min=earlier.get_coord("time").max() + one_hour)

joined = dc.spool([earlier, later]).concatenate(time=None)

concatenate can also create a new dimension when given a name not already present. Use this to stack compatible patches whose samples should remain distinct rather than merging along an existing axis.

Patches that cannot concatenate remain in separate output groups. Values are ordered along the concatenated dimension when it has a step; otherwise spool order is retained. Other coordinates must agree, while coordinates along the concatenated dimension are joined. For conflicting non-coordinate attributes, conflict= can raise (the default), drop them, or keep the first value.

Loading into memory

Spool.load reads every patch and returns a spool of in-memory patches, the way xarray’s load does. The bytes the arrays take are estimated from the spool contents first and compared with the memory available, so a spool which will not fit raises InsufficientMemoryError before anything is read rather than failing part way. A patch whose size cannot be told from its metadata counts nothing. The check needs psutil; without it the read goes ahead unchecked.

loaded = spool.select(distance=(0, 100)).load()

To load upcoming patches in the background, or apply a function to every patch, see Large archives.

Inventory

A spool can attach an inventory, then select and enrich patches by what it states.