Coordinates

Open in marimo
Warning

This page covers advanced features. Most users should work through the Patch coordinate interface.

BaseCoord represents one coordinate and returns new objects rather than modifying itself. A patch groups its coordinates in a CoordManager; see Coordinate internals to use one directly. The rules coordinates follow are in the coordinate guidelines.

Coordinates

Creation

get_coord chooses the appropriate coordinate type from a range or array.

import re

import numpy as np

from dascore.core import get_coord

regular = get_coord(start=0, stop=10, step=1, units="m")
same = get_coord(data=np.arange(10), units="m")
irregular = get_coord(data=np.array([0.0, 1.0, 2.2, 4.0]))

assert regular == same
Attribute Meaning
sorted Whether the coordinate reports ascending ordering
reverse_sorted Whether the coordinate reports descending ordering
step The spacing of the one grid the values follow; only a coordinate of one grid has a step, so labels and several segments give None
segments The coordinate’s segments, each one grid or one list of labels
evenly_sampled Whether the coordinate is one grid
dtype NumPy data type
data Array of coordinate values
units Physical units, if present
degenerate Whether the coordinate is empty or zero-dimensional
min(), max() Coordinate limits
step_exact The spacing as an exact Fraction (seconds for time), or None for float coordinates

Exact sampling rates

Time and integer coordinates keep their spacing exactly. Give a step as a Fraction or a (numerator, denominator) tuple in the coordinate’s units: a 1024 Hz recording is (1, 1024) seconds, not a step rounded to 976562 ns, which would drift by 1.8 ms an hour. Each label is the nearest tick to its exact position, and slicing, striding, reversing, and selecting stay on the exact grid. step still reports the nearest whole-tick spacing.

from fractions import Fraction

t0 = np.datetime64("2020-01-01T00:00:00")
hour = get_coord(start=t0, step=(1, 1024), shape=(3_686_400,))

assert hour.step_exact == Fraction(1, 1024)
assert hour[::2].step_exact == Fraction(1, 512)
assert hour.step == np.timedelta64(976562, "ns")
# the rounded step would have drifted 1.8 ms by the end of the hour
assert hour.max() - (t0 + hour.step * (len(hour) - 1)) == np.timedelta64(1843199, "ns")

Float coordinates have no tick to be exact against: a fraction step raises, and step_exact is None.

Cells and their centres

By convention a label is the centre of a cell one step wide, closed below and open above: a label of 10 with step 2 represents [9, 11). This is a recommendation for data producers, not enforced or stored. Selection always uses labels.

To state cells that are not centred, attach the pair {dim}_start and {dim}_stop: two one-dimensional coordinates associated with dim, as CF’s cell bounds. Like {dim}_min, {dim}_max, and {dim}_step, these names are reserved. Together the pair must match the dimension’s length, units, and direction and satisfy start <= label < stop; a lone coordinate with either name is ordinary. Patch.stft and Patch.window(...).apply with mode="stack" attach the pair, in the dimension’s units, for their windows.

Selection and raw decimation keep the selected bounds, and translation and unit conversion transform them. Operations that build a new grid drop them: interpolation, resampling, filtered decimation, padding, rolling windows, and correlation lag grids. The pair must keep monotonic row order, so drop it before permuting tiles arbitrarily; inverse STFT and reassembly still work. Waterfall image extents use the pair when attached, otherwise half a step beyond the first and last labels. Coordinate internals covers spectrograms, reconstruction, and files from earlier development versions.

Coordinates with holes

A coordinate is one evenly sampled grid, one list of labels, or several of those in order, called segments. Each segment is a Grid or stored Labels, and nothing is moved across the boundary between two. Use concat_coords(...) when the blocks are known:

from dascore.core.coords import concat_coords

first = get_coord(start=0.0, stop=5.0, step=1.0, units="m")
second = get_coord(start=8.0, stop=13.0, step=1.0, units="m")
segmented = concat_coords(first, second)

print(segmented.get_discontinuities("gaps"))
   index  before  after  delta  excess
0      5     4.0    8.0    4.0     3.0

A coordinate of several segments has no step, though each segment keeps its own. get_coord keeps an array’s values: labels a grid reproduces become that grid (float labels within two millionths of a step of it included, moving that little), and anything else is one list of labels with no step. Coordinate internals describes how segments are built and merged.

values = np.array([0.0, 1.0, 2.0, 7.0, 8.0, 9.0])
exact = get_coord(data=values, units="m", snap=False)
assert np.array_equal(exact.values, values)
assert exact.runs_count == 1 and exact.step is None

A spool keeps a patch with holes whole; Patch.split_gaps cuts it into one patch per segment. dc.write also writes it whole: DASDAE and pickle keep its segments and their steps, NetCDF and Zarr keep segments sharing one step, and formats that store only a grid refuse it, saying to fill or split first. NetCDF and Zarr record segments as labels beside their step, so a file of more than dascore.config.max_index_runs segments reads back as one list of labels with no step, with a warning, unless the limit is raised; DASDAE stores segments explicitly and reads back however many it holds.

Declaring a grid

Labels alone do not say which positions are missing: [0, 2, 4] fills a step-2 grid but misses two positions of a step-1 grid. Passing step with array data declares the grid: each run of consecutive positions becomes a segment on that step. If any value is off the grid, or the stretches outnumber max_index_runs, every value is kept, not moved, as one list of labels with no step.

coord = get_coord(data=[1, 3, 4, 10, 11, 12], step=1)
assert coord.runs_count == 3 and coord.step is None
assert [len(x) for x in coord.segments] == [1, 2, 3]
assert {x.step for x in coord.segments} == {1}

Filling holes is a patch operation. Patch.fill_gaps joins the segments onto the first one’s grid and writes a fill value (NaN by default) where no sample sits. A limit such as fill_gaps(time=10), in coordinate units, or a count of missing samples with samples=True, fills only holes up to that width (missing samples times the step) and leaves wider ones.

import dascore as dc

gapped = dc.Patch(data=np.ones(len(coord)), coords={"x": coord}, dims=("x",))
filled = gapped.fill_gaps("x", fill_value=0)
assert filled.shape == (12,) and filled.data.sum() == len(coord)

get_discontinuities reports the boundaries between runs and, for a monotonic array, every spacing other than its declared step (or median spacing). Its tolerance is the excess over one step in coordinate units; GapTolerance.samples(k) counts steps instead, as waterfall(gap_factor=) does. Spool.chunk judges seams between patches differently; see the coordinate guidelines.

Updating and units

update uses an existing coordinate as a template:

start = np.datetime64("2023-01-01")
by_minute = get_coord(start=start, stop=start + np.timedelta64(1, "h"), step=np.timedelta64(1, "m"))

shifted = by_minute.update(data=by_minute.values + np.timedelta64(10, "s"))
coarser = by_minute.update(step=np.timedelta64(30, "m"))

Updating min, max, or step keeps the length and derives the rest of the range. Updating data lets DASCore choose the simplest coordinate for the new array.

set_units changes the units without changing values; convert_units converts both.

relabeled = regular.set_units("ft")
converted = regular.convert_units("ft")

Sorting, snapping, and selecting

Methods that reorder or remove samples return a coordinate and an indexer for the associated array.

unsorted = get_coord(data=np.array([3, 1, 2]))
sorted_coord, indexer = unsorted.sort()

array = np.arange(6).reshape(3, 2)
sorted_array = array[indexer, :]

selected_coord, indexer = regular.select((3, 7))
selected_array = np.arange(len(regular))[indexer]

Selections convert compatible quantities before comparing:

from dascore.units import ft

selected_in_feet, _ = regular.select((3 * ft, 20 * ft))

sort permutes existing values. snap() replaces them with one evenly sampled grid, so it returns only a coordinate; use CoordManager.snap or Patch.snap_coords when the data must be sorted along with it.

String coordinates

String coordinates support exact matches, * and ? wildcards, compiled regular expressions, boolean masks, and sorting. They do not support units, relative selection, or numeric ranges.

labels = get_coord(data=np.array(["ch_a", "ch_b", "aux_1", "aux_2"]))

exact_match, _ = labels.select("ch_b")
channels, _ = labels.select("ch_*")
aux, _ = labels.select(re.compile(r"^aux_\d$"))
sorted_labels, sort_indexer = labels.sort()

Strings containing * or ? are wildcard patterns, so avoid those characters in labels matched literally, or select with a boolean mask.

Finding insertion positions

get_next_index returns where a value is or would be inserted in a sorted coordinate:

assert regular.get_next_index(2) == 2
assert regular.get_next_index(2.1) == 3