Spool Selection

Spool.select works the same way on in-memory and directory spools. Both build up selections in a PatchCatalog. Arguments are validated immediately, but ordinary metadata filters run in SQLite and stay lazy until you ask for contents, length, an item, or iterate.

Names

A bare name like select(station=...) is looked up as an attribute first, then as a coordinate. Unknown names raise immediately rather than being ignored.

To be explicit, use _attrs or _coords, in either of two forms:

  • a name -> selector mapping, the fully general form, needed when a name is not a valid Python keyword;
  • a name, or collection of names, saying which bare keywords belong to that namespace, e.g. select(sensor=(1, 10), _coords="sensor").

Attribute selectors

The index evaluates equality, membership, ranges, and glob patterns. Regular expressions use a rough SQL filter followed by an exact check in Python; several regular expressions combine with AND.

source_path takes the same string selectors, matched against the source_path column of get_contents() (relative to the directory for a directory spool, normalised for other spools); check that column for the exact spelling.

Quantities are converted to the unit the index recorded for that attribute. A dimensionally incompatible query raises rather than quietly matching the wrong rows. Values stored without units can’t be proven incompatible, so they stay candidates for quantity selectors.

Coordinate selectors

Coordinates are selected by range: a (start, stop) tuple or slice, with None or ... for an open end. A range open at both ends means no filter, like None, so it keeps patches that lack the coordinate.

Scalars, value lists, and boolean sample masks have no exact meaning across a whole spool, so they raise. Apply them per patch with spool.map(lambda p: p.select(...)). A boolean array over patches, spool[mask], still picks patches.

Units. The index stores each coordinate in the units its file used, so bare numbers mean the coordinate’s own units, just as in Patch.select. Quantities convert to whatever units each patch uses. In an archive where files state different units for one coordinate, a bare range therefore picks a different physical interval per file; pass a quantity to mean one interval. Archives mixing patches with and without units work in one selection, because the exact trim is worked out per patch.

Two stages. The index first keeps patches whose stored ranges could overlap the request. Each patch is then trimmed exactly when it loads. samples=True never excludes a patch at the index stage.

Relative selection. With relative=True, bounds are resolved per patch: positive offsets count from the coordinate’s minimum, negative ones from its maximum. The first bound is always the lower limit and the second the upper. Crossed bounds select nothing. Equal bounds keep a sample at that value if there is one. Attribute filters in the same call are unaffected.

A relative selection drops patches that lack the coordinate, and patches whose stored ranges show the window is empty. For a three-second patch, both select(time=(5, -1), relative=True) and select(time=(5, ...), relative=True) return an empty spool, while Patch.select returns a zero-sample patch for either. Length, contents, indexing, and iteration all use the remaining rows. A window that overlaps a stored range can still land between samples or inside a gap, so its exact result is only known at load time. Sample-index selection keeps empty patches.

Sample counts and ids before loading

Some selections leave a row’s sample count and data_id unknown until the patch loads:

  • every sample-index selection, even one spanning the whole patch;
  • relative selections on coordinates stored as float16 or float32, where index arithmetic can’t tell whether rounding removes a sample.

The loaded patch still applies the exact selection and reports its real identity.

Identity of a selected patch

When a selection is pushed into the file reader, the loaded patch gets the data_id of the window it read. That is the same id the selection would give on the loaded patch, so replaying select finds nothing to do. select adds no history entry.

A window is named by the samples it holds, not by how you asked for it. For a file-backed patch, ..., None, and a quantity in any unit all give the same id. A selection the reader can’t do itself — stepped, fancy indexing, or along an axis the file’s array can’t be sliced on — gets an id derived from the whole array plus the select call, so those spellings still differ.

A single range in native units can be pushed into the reader on even or uneven coordinates. These instead replay on the loaded patch:

  • several ranges composed on an uneven or float16/float32 coordinate, since stored ranges can’t reliably tell which samples earlier selections left;
  • selections involving associated coordinates, so a trim on one coordinate can make a later trim on another coordinate along the same axis a no-op.

The spool’s contents follow such a trim before anything loads: selecting on one coordinate narrows the advertised range of every evenly sampled coordinate on its dimension, so get_contents, get_coverage and chunk see what the patch will hold. An advertised range is never narrower than what loads. Times and integers are advertised exactly; a float range may pass the loaded one by the float exactness of the coordinate contract, since a stored label can sit that far from its grid position. A coordinate with no step, or on several dimensions, keeps its whole range.

Attribute filters, including on data_id, always query the indexed file metadata, not ids generated when a selected patch loads.

Views

Operations that make new patches (chunking, concatenation) produce a new in-memory catalog whose rows are the planned outputs, so selecting on a chunked spool uses the same engine. Sorting, slicing, and array selection never restructure; they stack lazy order and membership onto the current catalog. Selections attached to a parent view still apply when its source patches load.

Views share their source catalog. Adding, removing, or rescanning sources clears cached metadata, so existing views see the updated catalog through their own filters.

Examples

Names resolve attributes first, unknown names raise, and coordinate ranges are exact on loaded patches:

import pytest

import dascore as dc
from dascore.exceptions import InvalidSpoolQueryError

spool = dc.get_example_spool("diverse_das")
with pytest.raises(InvalidSpoolQueryError):
    spool.select(not_a_name="anything")

selected = spool.select(acquisition_key="DAS2.*")
assert all(p.attrs.acquisition_key.startswith("DAS2.") for p in selected)

df = spool.get_contents()
t0 = df["time_min"].min()
window = (t0, t0 + dc.to_timedelta64(1))
for patch in spool.select(time=window):
    coord = patch.get_coord("time")
    assert coord.min() >= window[0] and coord.max() <= window[1]

Bare numbers mean the coordinate’s own units, and scalar coordinate selectors raise:

ft_patch = dc.get_example_patch().convert_units(distance="ft")
coord = dc.spool([ft_patch]).select(distance=(20, 60))[0].get_coord("distance")
assert float(coord.min()) >= 20 and float(coord.max()) <= 60  # 20-60 ft

with pytest.raises(InvalidSpoolQueryError):
    dc.spool([ft_patch]).select(distance=100)  # a scalar is not a range

Relative selection never swaps crossed bounds to pull data from the other end of a short patch:

short_patch = dc.get_example_patch().select(time=(0, 3), relative=True)
for bounds in [(5, -1), (5, ...)]:
    assert short_patch.select(time=bounds, relative=True).size == 0
    assert len(dc.spool([short_patch]).select(time=bounds, relative=True)) == 0

Several windows at once

Pass an (n, 2) array to select several absolute ranges along a coordinate. Several coordinates can take arrays with the same number of rows; row i of each forms one box. Spool Chunking lists the forms a window takes.

  • Each row is applied to each matching patch, in input order.
  • Overlapping, repeated, and touching ranges stay separate pieces, so two rows across a file boundary can return more than two patches.
  • Endpoints are inclusive. An empty (0, 2) array selects nothing.
  • Ordinary selectors on other attributes or coordinates can be combined with it.
  • Arrays require samples=False and relative=False.

The result is lazy and follows updates to the source catalog. Its contents show each piece’s exact sample range when the index holds the full coordinate values, including uneven coordinates; file scans can read coordinates without loading data. A single (start, stop) selector behaves as before.

import numpy as np

patch = dc.get_example_patch()
source = dc.spool(patch)
windows = np.array([[2, 4], [4, 6], [2, 4]])
pieces = source.select(distance=windows)
assert len(pieces) == 3
assert [(p.get_coord("distance").min(), p.get_coord("distance").max()) for p in pieces] == [(2, 4), (4, 6), (2, 4)]