A patch whose data are not read yet holds a LazyArray, which Patch.set_backend and Spool.set_backend give it under the name "lazy": a Recipe, which says which stored samples fill which box of the array, and a chain of the operations run on it since. An operation on such a patch computes nothing. Its kernel appends the processor and its plan to the chain, and Patch.load runs the chain: on the whole array when that is small, and a chunk at a time when it is not. The rules below are what let the work be split without changing any result. The code cells execute against the real machinery, so this note fails the doc build if it drifts from the implementation.
Chunk size is an implementation detail. The result is the same, within floating-point precision, whether it was computed whole or a chunk at a time, and it has the same data_id. An operation states what a chunk of its output needs of its input by returning a chunk contract from chunk_contract, given the input’s dtype and its plan. The contracts are listed below. A contract is decided from the dtype and the plan, never from the values: an operation whose no-op depends on the values, such as fillna, cannot state one.
Metadata is never lazy. A lazy patch always has concrete coords, attrs, shape and dtype. They come from get_metadata, which runs when the operation is called and knows nothing of chunks, so it must state the dtype the kernel returns as well as the shape. load checks each step’s result against what its metadata stated, and refuses a mismatch naming the processor. An operation whose metadata depends on the data cannot be lazy.
loaded = out.load()assert loaded.dtype == out.dtype and loaded.shape == out.shape
The lazy backend never falls back unasked. An operation with no contract raises LazyOperationError before anything is read, where another backend would convert to NumPy, unless the numpy_fallback setting allows the read; see Backends. Arithmetic and NumPy functions on the patch, whichever operand is lazy, rolling, stacking a spool, and the waterfall and specplot figures raise it whatever the setting. A patch’s repr describes lazy data without reading them. Unless the setting allows more, the data are read in these places only:
Patch.load (and Spool.load, which calls it), Patch.set_backend naming an array library, np.asarray(patch), and writing the patch to a file, where the caller asks for the values;
Patch.equals (and ==), which compares them.
Everything else refuses. A spool with no lazy backend reads its files as it always has: those data were never lazy.
from dascore.exceptions import LazyOperationErrortry: lazy.detrend("time")except LazyOperationError as error:print(error)
detrend cannot run on a lazy patch: it would have to read the data, which the lazy backend never does behind your back. Call patch.load() to read them into memory first.
Each step has its own identity. A step’s data_id is the one PatchProcessor records for an eager patch: derived from the operation’s id and the previous patch’s data_id. The node records the id the patch was given at that step, so every lazy step has the eager step’s id, and an eager no-op (an Unchanged contract) hands back the patch itself, id and all. A metadata-only operation changes the patch’s id and leaves the lazy array as it was; the patch’s attrs.data_id is what names the patch.
eager = lazy.load().abs().update_attrs(station="here").angle()assert loaded.attrs.data_id == eager.attrs.data_id == out.attrs.data_idassert lazy.real() is lazy # real data: nothing to do, as eagerly
The contracts
A chunk is a box of the array: one slice for each axis. A contract says which box of its input a box of its output is computed from, and nothing else about chunks; no operation chooses a chunk size or loops over chunks.
Contract
A box of the output needs
Stated by
Pointwise
the same box of the input
abs, real, imag, angle, conj
Halo
the same box and a fixed number of samples around it, stopping at the ends of the array
median_filter, gaussian_filter, and savgol_filter with an edge mode other than its default; pass_filter and notch_filter called on a Patch.impulse_window, by the reach their response to an impulse measures
WholeAxis
the whole of some axes, and the same place along the others
pass_filter; the three above when their edge mode wraps; savgol_filter in its default mode, which fits a polynomial to each end of what it is given
Window
the same box moved by where a selection starts
select with ranges
Tiles
the tiles which overlap the box, each whole; along the other axes, what the operation in the window states
real and conj of real data, a select which keeps everything
The filters state a contract for float32 and float64 data only, the dtypes their kernels return as given, and gaussian_filter states none when its edge mode is given axis by axis. A query which does not resolve to one range for each dimension is no window and is refused: a select by an array of values or a mask, and what unselect and order build.
A patch operation called on a window is computed a tile at a time and blended, so it states Tiles whatever the operation is. The tiles are placed by the array and not by the box: a box is grown out to the edges of the tiles which overlap it, each of those is computed whole, and the box is cut from the blend. A windowed axis can therefore be cut even where the operation alone needs it whole, and window(time=10).detrend("time") runs on a lazy patch where detrend("time") is refused. Along an axis which is not windowed the box needs what the operation’s own contract says, and the whole axis where it states none. Where the operation keeps every n-th sample of a windowed axis, as fbe with a step does, the result is shorter than what it is computed from: a box counts samples of the result, the tiles which overlap it are found in those samples, and those tiles are read from the input. The lazy patch states its dtype by running the operation’s kernel once on a window of zeros, since an operation with no contract has never had to state what its kernel returns. A reduction in a window and a function given to apply state no contract yet, so both are refused on a lazy patch.
A Halo kernel sees the true ends of the array in the chunks which hold them, so it treats them as it does eagerly, and what it makes of a cut end is trimmed off. A halo never reaches past an earlier selection: to a filter after a select, the window’s ends are the array’s.
Cut the result into boxes. If no array the result needs is larger than the lazy_block_size setting, there is one box. There is also one box when no step computes anything, since reading in pieces would only open each file again. Otherwise the box is halved along the first axis worth cutting until they fit. An axis an operation needs whole is not worth cutting, and nor is one already short beside its halo, so the block size is aimed for rather than promised.
Work out what each box reads. Each step’s contract is asked, last to first, which box of its input it needs. Nothing is read to answer, so every read is known before the first one happens.
Read and compute each box. The recipe reads only the box needed, and each step’s kernel for the array’s library runs on it, first to last.
A selection therefore narrows what is read wherever it sits in the chain.
The whole result is still put together in memory; writing each box out as it is made is a later change, and Windowed and Lazy Processing is the plan for it and for what else is to come. Until then:
Nothing is kept between loads. Each piece a spool cuts from a lazy patch runs the chain for itself, so a piece cut along an axis a step needs whole reads and computes that whole axis again.
A kernel is not run until the chain is, so an argument its kernel refuses, such as an edge mode scipy does not know, is refused at load rather than at the call.
A step which recorded no contract, as a kernel registered for the lazy backend may leave, is given all of its input.
Backends
A patch or a spool is moved to a backend by name. An array library, such as "numpy", "jax" or "cupy", holds the data in memory on it. "LazyArray", or its alias "lazy", reads nothing until the data are asked for, and in brackets names the library each box is computed on: "LazyArray[jax]". NumPy is the default.
from dascore.utils.downloader import fetchspool = dc.spool(fetch("example_dasdae_event_1.h5")).set_backend("lazy")waiting = spool[0].abs()print(waiting.backend, waiting.set_backend("numpy").backend)
lazy numpy
A patch becomes lazy only if its data are what a stored array holds, since a lazy patch is a promise to read. One made or changed in memory is refused.
A spool hands out each patch on its backend: read lazily where a read can be, which is a selection of neighbouring samples from a format which names its stored arrays. A spool made from it, as by select or sort, keeps the backend. Lazy reading is in force only while the spool reads a patch: a dc.read the caller makes while iterating it fills memory as usual. Spools added together must be on one backend.
A merge stays lazy. Under a lazy backend spool.chunk(time=None)[0] is one lazy patch whose recipe names a window of each file, built from the index with no file opened. A selection made before load reads only the files it touches. The files are checked against the index when the patch is made; one rewritten between then and load is refused only if it no longer holds an array of the shape and dtype its row states.
Merging and concatenating join data where they are. Lazy patches with nothing pending and one dtype, which are windows of what is stored, are joined by their recipes and stay lazy, whether a spool merges files the index describes or members it reads as patches, or concatenates them along a dimension they have. Patches in memory on one array library are joined by that library’s own concat, so dask, CuPy or JAX data are never taken through NumPy for it.
Each box is computed on the library named, by the kernel each step has for that library. A step with none has each box converted through NumPy.
One setting, numpy_fallback, decides a conversion through NumPy and a read of lazy data which was not asked for: "raise" refuses it, "warn" converts with a NumpyFallbackWarning, and "ignore" converts silently. Left unset it is "raise" for lazy data and "warn" for any other. It decides an operation with no kernel for an array library, an operation with no contract on a lazy patch (which reads the data into memory), a read which cannot be lazy (a selection of samples which are not next to each other, or a format which names no stored array or reads by a method of its own), a fill of a gap between files, and a merge or concatenation which cannot stay lazy: lazy patches with operations pending or of different dtypes, a mix of lazy patches and patches in memory, members in different data units, a new dimension for lazy patches, or members whose dtypes promote differently a member at a time than all at once. Patches on different array libraries are joined through NumPy, which the setting decides too. A patch a spool already holds in memory is not read, so it is not made lazy. Nothing is converted or read unasked without the setting having allowed it, and a step already pending is asked again when its patch is moved to another library. Arithmetic and NumPy functions on a lazy patch, rolling, the waterfall and specplot figures, and stacking a spool of lazy patches are refused whatever it says. Spool.load was asked to read everything, so it reads what could not have been lazy without asking the setting, onto the library a lazy backend computes on.
Where it happens
kernel_for answers the lazy backend with a class’s own registered lazy kernel, or else with lazy_kernel, for the first class in the MRO which computes, whether by a kernel it writes or one registered on it; a class with none stays metadata-only. The generic kernel asks for the contract only when it describes the kernel which runs – the class stating it is the class owning that kernel, or a subclass of it – and refuses an operation which overrides reconcile, which would be handed the lazy array. For any contract but Unchanged it then appends a pending node, recording the contract on it. PatchProcessor settles that node with the output shape, dtype and data_id once the result’s attrs are final and before the patch is built.
Why not dask
Dask plans its work as a graph holding a task for every chunk of every operation. For very large arrays, building and scheduling that graph costs more than the work it describes. A chain holds one node for each operation, whatever the size of the array, and how the work is split into boxes is decided only when it runs.
A dask array is still accepted as a patch’s data, as any other array backend is, and its dispatch is unchanged: an operation runs on dask where its kernel can, and otherwise falls back to NumPy with a warning; a patch operation run in the windows of a Patch.window is the exception, computed a piece at a time from the windows which overlap each piece, and so is one run in a Patch.impulse_window, computed a chunk at a time with its measured reach around it; a reduction there still falls back, and apply gives back NumPy data. None of the rules above hold for it. Patch.load reads a dask-backed patch into memory as well, and Spool.io.to_xarray builds dask arrays because that is how xarray defers a read. For data larger than memory within DASCore, the lazy backend is the one to use.