Coordinate Internals

This note explains the current internal coordinate model in DASCore, with particular attention to exact values, runs, summaries, and scan payloads.

Coordinate classes

get_coord(...) returns the simplest coordinate that fits the supplied inputs:

Class Purpose
NumericCoord Every numeric, datetime, and timedelta coordinate, of any shape, including one whose labels are unknown (a single blank run).
CoordString String or categorical labels.

A NumericCoord holds its labels as an ordered tuple of runs, each either a Grid or a Labels:

Run Purpose
Grid An evenly sampled stretch described by numbers rather than stored. Nanosecond time and integer grids are exact: the labels are origin + (phase + k * step_num) // step_den ticks, so a fractional step such as 1/1024 s never drifts and step_exact reports it, while step stays the nearest whole-tick spacing. A float grid (step_den of zero) keeps a scalar step and linear spacing; slices also retain parent_count, k0, and stride to evaluate the original labels, which is also what time in coarser or finer units and an integer span that does not divide by its count (get_coord(start=0, stop=10, shape=3) is float) fall back to.
Labels A window – offset, count and (possibly negative) stride – into one array of labels held as it is, read-only, of any shape. The array itself lives in the coordinate’s sources mapping under the id it was hashed with on the way in, so a slice, a stride, a reversal or a move to another coordinate only moves the window and the labels are copied and hashed once however far they travel. Converting units scales a window’s labels into a new entry, which is a genuinely new array.

One grid is the evenly sampled coordinate; one stored run is an arbitrary or N-dimensional array; several runs are segments, each its own grid or labels, where each boundary records a break in sampling without changing any label. runs_count says how many there are and segments hands each back as a coordinate of its own.

How a coordinate is sampled is said by its form, as the coordinate guidelines define it: only a coordinate of one grid has a step and is evenly_sampled; one list of labels is irregular, and several segments mean gaps. get_coord(dim, require_evenly_sampled=True) on a patch is the one requirement check.

get_coord(data=...), under the default snap=None or snap=False, reads labels exactly (rule 2 of the guidelines). Labels a fitted grid restates at consecutive positions are that grid: integer and time labels are judged exactly in their own tick unit, so 1024 Hz labels stored in microseconds find their 15625/16 µs grid, and a fractional step must span at least 100 ticks. Float labels within twice the float allowance of the grid spanning them (the allowance is the larger of _GRID_RTOL, a millionth, of the step and 4 ulp of the largest label, in the dtype they were stored in; float64 holding float32 values counts as float32) are held as that grid under every snap, so each label may move by up to twice the allowance, two millionths of a step for most data. Looking up a value within that distance of one of the grid’s labels (select by value or by array, order, get_next_index) finds that label, so the labels a grid was built from find their samples. Anything else is one list of labels with no step, so no label moves. Inference never makes segments. A stated step places the labels on its grid instead: each stretch of consecutive positions is a grid segment of that step where grids restate every stretch, judged so; otherwise, as for integer labels on a non-integer step or past max_index_runs stretches (with a warning), the labels are one list with no step, never moved and never refused.

snap=True snaps labels within a relative 0.1% of one spacing onto a grid, as DASCore 0.1.24 did by default; where that median step would move a label half a step or more (#1419), the labels are spread evenly from their end labels instead, if that moves none half a step, and otherwise keep no step. A zero-dimensional array stays a scalar coordinate under snap=None and snap=True; only snap=False makes it one label, snap=None’s one difference from snap=False. Readers do not use it: each builds its snapped grids with stored_coord and reads every other label exactly.

Cell convention

The Coordinates tutorial states the cell convention, the {dim}_start / {dim}_stop pair, and how operations treat it. Internally:

  • The coordinate manager validates the pair when both are attached, and grid-building operations discard it through the manager’s shared grid update. It adds no coordinate method and leaves selection and coordinate summaries unchanged.
  • STFT and stacked tiles keep their reconstruction indices in a private _tile_index_{dim} coordinate, which follows reordered rows, so inverse STFT and reassembly work after the public pair is dropped.
  • The public pair replaced a unitless sample-index pair. Development-version stacks that stored sample indices there fail validation and must be regenerated from their source patches.
  • Spectrogram rendering omits source-window bounds and draws one cell per hop at the window-centre label.

Segmented coordinates

Holding labels as runs keeps sampling breaks rather than flattening them into a single array or idealizing them as one grid. Segments are independent: no grid runs across a gap between them, so nothing numbers the samples a gap lacks. A grid which is exactly the next samples of its predecessor joins it automatically, and so do two windows which read on through one stored array; windows into different arrays never join, since concatenating their labels would cost a copy and lose both ids. Concatenation unions the stores, and an entry no window reads is dropped. A coordinate of several runs reports no step, since segments share no grid, and equals the same labels held any other way; a summary carries a step only for an evenly sampled coordinate, since a summary with a step rebuilds one.

There are two primary construction paths:

  • concat_coords(...) combines already-known coordinate blocks, normalizes their ordering, and records non-contiguous boundaries.
  • get_coord(data=..., snap=False) keeps an array as one grid when it reproduces every label, float ones within float exactness, otherwise as one stored-label run with no step, so it makes no segments. Declaring step (get_coord(data=..., step=...)) places the labels on that grid, making each stretch of consecutive positions a grid segment of that step where grids restate them (else, or past max_index_runs stretches, one stored run with no step), and split_gaps and the spool’s gap methods then see the gaps between those segments. Selecting samples by mask, array or position leaves each stretch kept its own segment on the original step (past max_index_runs, one list of labels with no step); only a stride gives a coarser step.

get_discontinuities(...) reports segment boundaries without materializing the full coordinate; the tutorial describes what it reports and its tolerance, a GapTolerance (dascore.utils.gaps). kind="all" returns every boundary and kind="gaps" only those the tolerance calls gaps. Spool.chunk, get_gaps and get_coverage judge the seams between patches by max_shift instead (rule 5 of the guidelines), and their tolerance is the widest seam joined, in steps for a number or as a width for a quantity, not an excess.

snap(...) forces one uniform grid and has no bound on interior movement; max_shift makes it raise past a bound. Nothing else refits labels: Patch.fill_gaps places later segments onto an earlier one’s grid within half a step, and chunk labels each stretch with the grid it fitted (rule 6 of the guidelines).

A spool holds a patch whose dimensional coordinates have several segments as one row; its index stores the coordinate’s segments as runs (see the spool index), so reports and plans see the gaps. patch.split_gaps() cuts such a patch into its segments, and write(...) keeps its segments or refuses it, as the tutorial describes.

String coordinates

CoordString is the dedicated coordinate type for string or categorical values. String coordinates do not support units, numeric range operations, relative selection, or slice-style range selection. They do support exact matching, wildcard matching, compiled regular expressions, boolean-mask selection, ordering, and lossy lexicographic min/max summaries.

Plain string selectors reserve * and ? for wildcard behavior. Compiled re.Pattern instances provide explicit regular-expression matching. Any construction path for string coordinates should reject unit-bearing inputs explicitly rather than silently dropping units.

Selection and indexing

Patch.select, Patch.sel, Patch.isel, and Patch.order share the coordinate manager’s _select execution path. The wrappers normalize their queries; existing coordinate select/order methods resolve DASCore queries, while sel resolves labels with pandas’ xarray-compatible rules. All resulting positional indexers go through the same validation, dependent-coordinate updates, dimension reduction, and backend-aware array indexing.

select and order retain dimensions; scalar sel/isel indexers reduce them. Label queries on compact ranges verify the existing coordinate lookup estimates, with batched binary searches as a fallback and a pandas index containing only candidate labels when needed for compatibility. Exact numeric label arrays resolve positions directly without constructing that index. Neither small nor bulk queries expand the input range: lookup memory is proportional to the number of requested labels, and search rounds grow logarithmically with axis length. Grids below floating-point resolution may contain repeated labels; array or nearest lookup rejects ambiguous long grids instead of scanning or materializing them to establish global uniqueness. Positional indexing remains available.

Slice results remain compact for integer, temporal, and floating coordinates, following existing select behavior. Floating slices retain the original grid expression and its length, plus an integer offset and stride. Slicing, striding, and reversal therefore preserve the selected labels bit-for-bit without expanding the coordinate, including through lazy xarray indexing and DASDAE version 2 storage. Scalar and array indexers in sel/isel evaluate only the requested output labels. These bounds apply to the new indexing methods; legacy array-based select/order paths can still materialize ranges. String label slices and exact matching in sel follow pandas’ rules, while coordinate-level select retains DASCore’s wildcard and range behavior.

Summaries are envelopes, not full coordinates

CoordSummary contains min, max, step, dtype, units, associated dims, length, and the coordinate’s exact data_id. The canonical construction path is coord.to_summary(), which starts from a live coordinate; build one with get_coord(...) first when starting from a raw value array.

The summary itself is intentionally lossy. An evenly sampled coordinate has a non-null step and can be reconstructed with summary.to_coord(); an exact grid also carries step_numerator, step_denominator, and origin_offset, so a fractional step rebuilds exactly, and the spool index stores these fields with the summary. Irregular, string, and multi-run coordinates use step=None; their envelopes and ids can support indexing and change detection, but neither field reconstructs their full values.

PatchSummary keeps non-coordinate PatchAttrs, a mapping of coordinate summaries, patch dimensions/shape/dtype, and reload provenance. PatchSummary.flat_dump(...) produces fields such as time_min, time_max, time_step, and time_data_id for dataframes and indexes. Those flattened fields are output records, not supported input for synthesizing a new structured PatchSummary or live coordinate.

Metadata and summary boundaries

Every FiberIO.get_metadata(...) result is a PatchMeta containing attrs, a full CoordManager, dtype, and optionally a logical source key. Dimensions and shape derive from the coordinate manager. The inherited FiberIO.scan uses the same metadata hook.

dc.scan_payloads(...) exposes that metadata and attaches source provenance separately from attrs. snap names the dimensions whose stored labels come back on a grid (rule 3 of the guidelines): by default the format’s own names, shown in its get_metadata signature; True every dimension; False none, every coordinate exactly as stored. Header-defined start/step/count grids are already exact, so the option changes nothing for them. Every mode describes the same written sample extent.

dc.scan(...) consumes the same metadata patches but collapses their coordinates to CoordSummary envelopes, under the same snap. dc.scan_to_df(...) flattens the same summaries for tabular/index use.

This separation keeps directory indexing compact while allowing targeted callers to probe a file’s true coordinate values without loading its data array. Data-less patches can still retain large coordinate arrays, so they should be requested for specific resources and discarded promptly.

DASDAE coordinate storage and scanning

DASDAE stores coordinates separately from patch data. Format version 2, the default when writing, stores each coordinate as it is described: one grid as its start, extent, and step (the exact grid where the coordinate holds one, so a fractional sampling rate rebuilds the same labels) at the cost of a few numbers however long it is, and any other coordinate as an array of values, with each segment’s length where it has several, and a step beside them where its segments share one. The node tag "CoordRange" is the format’s own name for a grid. A patch with gaps is written whole, as its segments. Version 1 files, and file_version="1" writes, store every coordinate as an array beside a whole-tick step, so version 1 refuses a fractional step rather than rounding it, and segments or labels its step does not restate rather than dropping them. Releases before version 2 existed cannot read a version 2 file; write with file_version="1" for them.

Full reads rebuild those descriptions into a CoordManager as written. Under the default snap (None), a coordinate stored as one list of labels comes back as the grid fitted from its first and last labels where every label is within max_shift of it, judged in the labels’ own ticks, and otherwise as the labels stored, with no step and no warning; an evenly sampled coordinate returns before its labels are read. Under snap=True, or a tuple naming the dimension, every label is judged the same way, so the coordinate decodes as under the default, but labels kept as stored warn as in every reader (rule 3). A step stored beside an array is read only to place its segments. Files written by development versions before 1.0, which can store labels beside a step they sit off, read the same way: the step places the segments of labels skipping its positions, up to max_index_runs of them. Scans also construct a real CoordManager, but avoid loading the data array itself; explicit stored start/step metadata remains a range fast path.

String-array serialization is separate from coordinate semantics. HDF5 backends cannot all store NumPy unicode arrays directly, so DASDAE encodes only arrays that are actually string-like and restores them before coordinate construction.

Coordinate managers

A CoordManager groups a patch’s coordinates and keeps their associated arrays aligned. Most code uses it through Patch methods; this section shows it directly.

import numpy as np

import dascore as dc
from dascore.core import get_coord, get_coord_manager

Creation and association

get_coord_manager creates a manager from coordinates and ordered dimensions. Tuple values specify (associated_dimensions, coordinate); use None for an independent coordinate.

distance = get_coord(start=0, stop=10, step=1)
time = get_coord(start=0, stop=1, step=0.1)
latitude = get_coord(data=np.linspace(41.5, 41.6, len(distance)))

manager = get_coord_manager(
    coords={
        "distance": distance,
        "time": time,
        "latitude": ("distance", latitude),
        "deployment": (None, get_coord(data=np.array(["A"]))),
    },
    dims=("distance", "time"),
)

manager.dims stores dimension order, coord_map maps names to coordinates, and dim_map records dimensional associations.

print(manager.dims)
print(dict(manager.dim_map))
('distance', 'time')
{'distance': ('distance',), 'time': ('time',), 'latitude': ('distance',), 'deployment': ()}

Updating

CoordManager.update replaces, adds, disassociates, or drops coordinates:

new_distance = distance.update(data=distance.values + 10)
updated = manager.update(distance=new_distance)
detached = updated.update(latitude=(None, latitude))
without_latitude = detached.update(latitude=None)

New coordinates use the same update form:

quality = get_coord(data=np.linspace(0, 1, len(distance)))
with_quality = manager.update(quality=("distance", quality))
independent = manager.update(run=(None, get_coord(data=np.array([1]))))

Setting a dimension coordinate to None drops that dimension and every coordinate depending on it. Dropping a missing non-dimensional coordinate is a no-op.

Methods with data

Operations that change array alignment accept the array and return an updated manager and array. Coordinate names are keyword arguments, as on Patch.

patch = dc.get_example_patch()
patch_manager, data = patch.coords, patch.data

selected_manager, selected_data = patch_manager.select(array=data, distance=(..., 100))
sorted_manager, sorted_data = patch_manager.sort("time", "distance", array=data, reverse=True)
renamed = patch_manager.rename_coord(time="elapsed_time")

When several dimensions are sorted together, the returned data reflects each permutation in dimension order. Renaming a dimension also updates every coordinate association that refers to it.

select, order, sort, and snap accept an associated array and return (manager, array). Methods that do not change alignment, such as unit conversion, return only a manager.

Prefer the corresponding Patch methods when operating on a patch; they keep data, coordinates, metadata, and provenance together.

Practical guidance

When changing coordinate or scan internals:

  • choose tolerant get_coord(data=...) only when idealizing small jitter is acceptable
  • use truth-preserving construction for any snap=False or exact-value contract
  • keep run boundaries in live coordinates; a summary states only the envelope, never a coordinate’s runs
  • treat flat coordinate-summary fields as persisted output, not coordinate reconstruction input
  • keep string-coordinate rules explicit instead of routing them through generic numeric logic
  • put shared exact-construction behavior in coordinate or IO helpers instead of duplicating it across formats