Series¶
A sampled signal, such as a current or an audio stream, produces values at a fixed rate for as long as it runs. Its samples need no times of their own. The question is how to keep them compact and still find the time and value of each. A series stores them in fixed point on a grid, with a scale that may change mid-run. A reader reads any range of them.
The drive's phase current, for example, is a series: 25 000 samples a second, one every 40 µs, for the whole hour. The last 20 ms before the fault at 52:00 are 500 samples. They show how fast the current rose past the 31 A limit.
Samples without times¶
A series is a track of samples at an exact period. An ADC channel, an audio stream
and the drive's phase current are series. A sample needs no time of its own, since the period gives it. A series
therefore stores only values, in series chunks, and the drive's phase_a costs about 1.1 bytes per
sample (Sizes and speeds).
The track's items and its definition, a GridDef, say what a sample is:
| Field | What it says | phase_a |
iq, an RF capture |
|---|---|---|---|
items: Numbers |
the stored element and the type of one value, as the producer's API declares it | i16, a current in mA |
a complex i16 of the radio's converter |
channels |
the elements of one sample | one | one |
period |
ticks per sample, as an exact fraction | 40/1 on the board's µs clock | 50/1 on a 1 ns clock |
scale |
what one step of a stored number is worth | 10⁻³ A | one step of the converter |
summaries |
the coarse view the writer builds | minimum, maximum, sum, sum of squares | minimum, maximum, mean and largest power |
The period is a fraction, so no sample time drifts by rounding. Audio at 48 kHz on a 1 ns clock has the period 62500/3: three samples take exactly 62 500 ns.
Fixed point first¶
For data a device controls, store fixed-point integers. The drive's current is an i16 in steps of 1 mA: an i16 on
the wire and an i16 in the column. The scale, 10⁻³ A per step, lives in the track and in each chunk's head, never in a
sample. The numbers stay integers from the device to the file, and nothing passes through a float.
Integers also compress best. The writer stores the differences between neighbouring samples, bit-packed per group of
128 samples, and a smooth signal needs few bits per difference. Fixed point is smaller than the best float codec on
every data set that Sizes and speeds measures. Floats that a device did not
choose, such as a sensor that reports only f32, have codecs of their own. Samples and their
codecs explains the codecs and when to pick each.
A device that sends its own packing, such as two 12-bit values in three bytes, can have its bytes stored as sent. A reader converts only the samples it reads.
A fast series: radio samples¶
A series at a high rate is stored the same way as a slow one, and only the numbers grow. The second case of this
chapter is an RF capture. A software-defined radio's front end turns a band of spectrum into 20 million complex samples
a second. Each sample is a pair of values, the in-phase I and the quadrature Q, and the capture is one track,
iq.
The track's items are numbers of two parts, a 16-bit signed integer each:
/// The element of `iq`'s items: I and Q side by side, a 16-bit signed integer each.
pub const IQ_ELEMENT: ElementDesc = ElementDesc::of_scalar(Scalar::I16, 2);
A sample's I and Q lie side by side in the column. Every codec codes them as two lanes, so neither needs a track of
its own. The converter gives 12 bits in each 16-bit word. The summaries keep the power of each node, I² + Q², which
shows where a signal is on the air:
let def = GridDef {
channels: UNib32(1), // one sample of IQ_ELEMENT at a time
period: Ratio64::new(1_000_000_000, u64::from(self.rate_hz))?, // 50 ns at 20 MS/s
scale: Magnitude::ONE, // one step of the converter
summaries: self.summaries.then(summaries), // extremes and power per 1024 samples
media: None,
axes: RefVec::new(), // no fixed axes: a series
};
What the example uses here: Rf
/// An RF capture: its rate, its length and how it is stored.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Rf {
/// Complex samples per second; it divides 10^9, so a sample period is a whole number of ns.
pub rate_hz: u32,
/// Length of the capture, seconds.
pub seconds: u32,
/// Samples per series chunk.
pub chunk_samples: u32,
/// The codec of the samples.
pub codec: Codec,
/// `iq` carries summaries.
pub summaries: bool,
}
The track stores the samples in the converter's packed form, PACKED12_LSB: 12 bits per value, as the front end
sends them. A sample then takes 3 bytes instead of 4, and a minute of the capture is a piece of 3.7 GB. Sizes and
speeds gives the measured sizes and how fast the writer and the reader go.

eventfull_book_shots from the capture at 1/100 of its rate. The signal is the
same, at 200 thousand samples a second.Samples and what they mean, in two chains¶
A radio's samples and what a decoder finds in them grow at very different rates. The example's decoder finds bursts by the mean power of 16 samples, and it measures the band's mean power each second. A minute at 1/100 of the rate then holds 38 MB of samples and five bursts.
Each kind goes into a chain of its own, iq and decoded. A reader of the bursts never walks the samples, and
each chain is cut at its own size. One process writes both, each through a TapeMux of its own:
let iq_mux = ww_tape_fs::mux::create(
&Self::iq_dir(dir),
OWNER,
IQ_CHAIN,
&[],
chain_options(self.iq_piece_chunks),
MuxOptions::default(),
)?;
let decoded_mux = ww_tape_fs::mux::create(
&Self::decoded_dir(dir),
OWNER,
DECODED_CHAIN,
&[],
chain_options(0), // a minute's finds fit one piece
MuxOptions::default(),
)?;
let iq = iq_mux.define_track(rf.iq_track::<FsError>(iq_mux.define_clock(clock())?)?)?;
let c = decoded_mux.define_clock(clock())?;
let bursts =
decoded_mux.define_track(decoded_track(bursts_key(), "bursts", Ends::Spans, c))?;
let power =
decoded_mux.define_track(decoded_track(power_key(), "power", Ends::Instants, c))?;
A radio thread pushes each chunk's samples into the grid handle of iq and hands them to a decoder thread through
a bounded queue. The decoder pushes a span per burst into the track bursts and a power reading per second into the
track power. It completes each second's finds, so they reach the tape a second at a time and in time order:
let mut samples = iq_mux.grid::<i16>(
iq,
GridOptions {
chunk_steps: rf.chunk_samples,
latency: None, // the radio fills every chunk
codec: rf.codec,
..GridOptions::default()
},
)?;
let finds = |track| {
decoded_mux.events(
track,
EventsOptions {
latency: None, // the decoder completes each second's finds
..EventsOptions::default()
},
)
};
let (mut bursts, mut power) = (finds(bursts)?, finds(power)?);
let mut detector = Detector::new(&rf).ok_or(ChainsError::Rf(RfError::Settings(
"the period is a whole number of ns",
)))?;
let (to_decoder, from_radio) = mpsc::sync_channel::<Vec<i16>>(DECODER_QUEUE_MAX);
let decoded = std::thread::scope(|s| {
let radio = s.spawn(move || -> Result<(), ChainsError> {
let signal = rf.signal();
for k in 0..rf.chunks() {
let (first, count) = rf.chunk_range(k);
let mut values = vec![0; usize::try_from(count).unwrap_or(0) * 2];
signal.fill(first, &mut values);
samples.push(&values)?;
to_decoder
.send(values)
.map_err(|_e| ChainsError::Thread("the decoder"))?;
}
Ok(samples.finish()?)
});
let decoder = s.spawn(move || -> Result<Vec<Decoded>, ChainsError> {
let (mut all, mut found) = (Vec::new(), Vec::new());
for values in from_radio {
detector.push(&values, &mut found);
for d in found.drain(..) {
put(&mut bursts, &mut power, d)?;
all.push(d);
}
}
bursts.finish()?;
power.finish()?;
Ok(all)
});
let radio = radio.join().map_err(|_e| ChainsError::Thread("the radio"));
let decoded = decoder
.join()
.map_err(|_e| ChainsError::Thread("the decoder"));
radio??;
decoded?
})?;
let (iq_pieces, decoded_pieces) = (iq_mux.close()?, decoded_mux.close()?);
Each mux places the units of its own handles on its own writing thread, so neither chain waits for the other's
writes. A crash leaves each chain unclosed at its own byte, and each resumes alone. The test mux_multi.rs of
ww_tape_tests cuts two such chains at 201 pairs of bytes and resumes both at once.
A reader follows both chains while they are written. A ChainFollower on each hands out the blocks that check, and
a TimeMerge gives their items in time order. A chunk of samples counts at the tick of its first sample, and a find
at its start. The two tracks of decoded form one source, since the decoder sends them in time order. The merge
holds the chunks of samples back until the decoder's next second shows that no burst comes before them:
let mut iq = ChainFollower::new(iq_dir, FollowOptions::default())?.track(iq_key().id());
let mut decoded = ChainFollower::new(decoded_dir, FollowOptions::default())?;
let (mut bursts, mut power) = (
TrackItems::new(bursts_key().id()),
TrackItems::new(power_key().id()),
);
let now = Instant::now();
let mut merge = TimeMerge::new(None); // exact order: wait for both chains
let (from_iq, from_decoded) = (merge.add_source(now), merge.add_source(now));
let mut out = Followed::default();
let mut last_chunk = None;
// a block or item a wait brought, taken first in the next round
let (mut held_iq, mut held_decoded) = (None, None);
loop {
let mut got = false;
// the samples' chunks, each at the tick of its first sample
while let Some(item) = held_iq
.take()
.map_or_else(|| iq.try_next(), |i| Ok(Some(i)))?
{
let TrackItem::Samples(s) = item else {
return Err(ChainsError::Read("iq holds samples, none lost"));
};
let tick = s
.grid
.tick(period, s.first)
.ok_or(ChainsError::Read("a chunk's tick"))?;
let chunk = Item::Chunk {
first: s.first,
count: s.count,
};
merge.push(from_iq, i128::from(tick), chunk, now);
got = true;
}
// the decoder's finds: two tracks sent a second at a time, in time order, so one source
while let Some(f) = held_decoded
.take()
.map_or_else(|| decoded.try_next(), |f| Ok(Some(f)))?
{
let mut items = VecDeque::new();
bursts.take(&f.block, decoded.definitions(), &mut items)?;
power.take(&f.block, decoded.definitions(), &mut items)?;
for d in items.into_iter().map(decoded_item) {
let d = d?;
merge.push(from_decoded, i128::from(d.start()), Item::Decoded(d), now);
}
got = true;
}
// a closed chain holds nothing more: past every time
for (source, closed) in [
(from_iq, iq.chain().is_closed()),
(from_decoded, decoded.is_closed()),
] {
if closed {
merge.mark(source, i128::MAX, now);
}
}
while let Some(m) = merge.pop(now) {
out.late += u64::from(m.late);
match m.item {
Item::Chunk { first, count } => {
out.chunks += 1;
out.samples += u64::from(count);
last_chunk = Some(first.get());
}
Item::Decoded(d) => {
if let (Decoded::Burst { .. }, Some(first)) = (d, last_chunk) {
out.bursts.push((d, first));
}
out.decoded.push(d);
}
}
}
if iq.chain().is_closed() && decoded.is_closed() && merge.waiting() == 0 {
break;
}
if !got {
// nothing new in either chain: wait for the decoder's next second, which holds the merge back, or for
// the samples once the decoder is done
if decoded.is_closed() {
held_iq = iq.wait_next_for(FOLLOW_WAIT)?;
} else {
held_decoded = decoded.wait_next_for(FOLLOW_WAIT)?;
}
}
}
cargo run --release -p example_rf DIR writes the minute at 1/100 of the rate. The chain iq
holds 60 pieces of 38 MB together, a piece per second, and decoded one piece of 25 KB. The reader merges 6000 chunks
and 65 finds, none of them late. Each burst comes right after the chunk that holds its first sample. The burst at
7.3 s comes after the chunk from sample 1 460 000.
At 50 times the rate, a billion samples a second, the same signal needs its band split into channels. Keeping the bursts of a fast band spreads them over several muxes and measures where that stops.
Grids: where samples are in time¶
A series has no records. Each series chunk's head carries the grid its samples are on instead, a SeriesGrid:
grid_index, a sample number at or before the chunk's first sample;grid_tick, that sample's tick;scale, what a stored number of the chunk is worth.
Sample i lies at grid_tick + (i - grid_index) · period, rounded down. A chunk thus times and scales its samples
alone: nothing else has to be found, linked or kept near it. Consecutive chunks of one stretch of recording carry the
same grid, so no sample time moves, however the samples are cut into chunks.
The program reads the chunk that holds 51:59.980 and the 500 samples from there. It turns the time into a sample number with the grid, then decodes from that sample on:
let mut buf = Vec::new();
let block = reader.read_block(piece, entry, &mut buf)?;
let chunk = block
.chunk()
.ok_or(FaultError::Missing("chunk of samples"))?;
let head = chunk.head();
let grid = head.grid.ok_or(FaultError::Missing("grid"))?;
// sample `i` is at grid_tick + (i - grid_index) · period: the first at or after `from`
let steps = period
.recip()
.apply_rounded(from - grid.grid_tick, Rounding::Ceil);
let first = grid.grid_index
+ steps
.and_then(|s| u64::try_from(s).ok())
.ok_or(FaultError::Missing("sample"))?;
let at = head
.first_item
.offset_to(ItemNum::new(first))
.and_then(|n| usize::try_from(n).ok())
.ok_or(FaultError::Missing("sample"))?; // in the chunk
let n = period
.recip()
.apply(BEFORE_US)
.and_then(|n| usize::try_from(n).ok())
.ok_or(FaultError::Missing("sample"))?;
let column = chunk
.find(ColumnKind::Samples, 0)
.ok_or(FaultError::Missing("samples"))?;
let samples = Samples::of(
&column,
SampleShape::scalar(ElementDesc::of(Element::I16)),
head.count as usize,
)
.map_err(FaultError::Samples)?;
let mut ma = vec![0i16; n]; // stored numbers: steps of grid.scale, 10⁻³ A
samples
.decode(at, &mut ma) // from the group that holds sample `at`
.map_err(FaultError::Samples)?;
What the example uses here: fault_us, the fault's constants, series_def, Current
/// The ticks of the fault on the board's clock, µs since boot.
pub const fn fault_us() -> i64 {
FAULT_MINUTE as i64 * US_PER_MINUTE
}
/// Microseconds of the board's clock in a minute.
const US_PER_MINUTE: i64 = 60_000_000;
/// Pixel columns of the viewer's plot of the hour.
pub const COLUMNS: usize = 600;
/// [COLUMNS] as a number of µs to divide.
const COLUMNS_I64: i64 = 600;
/// Microseconds of the current before the fault that [current] reads.
pub const BEFORE_US: i64 = 20_000;
/// Microseconds of frames after the fault that [frames] lists.
pub const AFTER_US: i64 = 5_000;
/// The period and the summaries of `phase_a`, found by its key among the definitions in force at `offset` of piece
/// `piece`.
fn series_def<S: ByteSource>(
reader: &TapeReader<S>,
piece: usize,
offset: u64,
) -> Result<(Ratio64, Option<SeriesSummarySpec>), FaultError<S::Error>> {
let defs = reader.definitions_at(piece, offset)?;
let number = defs
.track_number(key("phase_a").id(), [0; 32])
.ok_or(FaultError::Missing("phase_a"))?;
let state = defs
.items
.get(&Slot::Track { number })
.ok_or(FaultError::Missing("definition of phase_a"))?;
let Ok(Describe::Track(def)) = Describe::from_ww_bytes(&state.item) else {
return Err(FaultError::Missing("track definition that decodes"));
};
let TrackKind::Series(series) = def.kind else {
return Err(FaultError::Missing("series definition"));
};
Ok((series.period, series.summaries))
}
/// What [current] read: the samples of `phase_a` for [BEFORE_US] up to the fault.
#[derive(Clone, Debug, PartialEq)]
pub struct Current {
/// The track's ticks per sample.
pub period: (u64, u64),
/// The scale of the chunk's numbers.
pub scale: Magnitude,
/// The first sample read, its item number.
pub first: u64,
/// The samples, stored numbers.
pub samples: Vec<i16>,
/// The largest magnitude among them, its item number and its stored number.
pub peak: (u64, i16),
/// Samples in the chunk, and the bytes of its block.
pub in_chunk: u32,
pub block_len: u32,
}
The chunk holds 25 000 samples in a block of about 28 KB, at period 40/1 µs and scale 10⁻³. The first sample read is
item 77 999 500 of phase_a. The largest in magnitude is -31 873 mA at 51:59.995, past the 31 A limit, 5 ms before
the drive tripped. The step reads about 29 KB in 6 reads: the definitions in force, to learn the period, and the
block.
ww_tape::Samples::decode starts at the group of 128 samples that holds the first sample asked for. A reader of any
range therefore decodes at most 127 samples it does not need.
Gaps and lost samples¶
A grid ends where the samples stop following it. A restart of the device on the same clock, or a stretch the device did not sample, starts a new grid. The new grid starts more than a period after the last tick of the chunk before, and a viewer draws no line across that gap.
Sample numbers that are missing between two chunks of one grid are lost samples. A chunk of them was damaged, or lies in a piece the reader does not have. Their ticks are known, since the grid gives them; their values are not.
ww_tape_figures; the ticks are SeriesTimeline's.TapeReader::series_timeline builds a track's timeline, a SeriesTimeline, from its chunk heads alone. It
reads each chunk's head with TapeReader::read_chunk_head, up to the payload and none of the samples. Some chunks are
left out as lost: one whose head is damaged, or one that does not line up with its neighbours. Each one's error comes
back beside the timeline.
Changing scale mid-run¶
Some instruments change range while they record. A current meter that measures a capacitor's charging current reports milliamperes at first, as integers at scale 10⁻³. As the current dies away, the meter switches to its micro range at sample 10 000 and reports microamperes at scale 10⁻⁶.
The writer ends the open chunk with sample 9 999. The next chunk carries the same grid at scale 10⁻⁶: its integers mean microamperes. Sample 10 000 keeps the tick that the grid gives it. A chunk has one scale, and the change costs one chunk boundary.
ww_tape_figures from the chunks and summaries that ww_tape writes and reads back.A summary node that covers samples of both scales keeps them at their common scale. That is the largest scale that both are whole multiples of, 10⁻⁶ here. The third node in the drawing covers the switch, and its maximum reads 6000 at 10⁻⁶, though its chunk stores that sample in milliamperes. The node's minimum and maximum thus stay exact integers. Two scales without a common scale are refused, never mixed.
Wire batches and file columns¶
A device sends samples to the host in Series<T> batches of the WireWeaver wire
format. The file stores them in sample columns. The two layers code the same
numbers for different readers:
Series<T> on the wire |
Sample columns in a tape | |
|---|---|---|
| Size | a batch of about 32 items | a chunk of up to megabytes |
| Read | from the start, item by item | any range of samples, by group, in place |
| Encoder | sized for a microcontroller | sized for a host, with vector kernels |
| Scale | a prefix per item or in the type | one per chunk |
The host decodes a batch once and codes its numbers again for the file. The integers pass through unchanged. A prefix change ends the chunk where the batch restarts its column. The file keeps no time column of the batch, since the grid gives every sample's tick.
A whole hour of 90 million samples is too much to draw by reading them. The next chapter draws it from the summaries that the writer kept beside the chunks.
TapeReader.pub struct GridDef<'i>
A fixed-rate series: scalar or vector samples of the track's element, see the module docs.
pub struct TapeMux<T: PieceStore> {
shared: Arc<Shared<T>>,
thread: Option<JoinHandle<()>>,
}
Writes one chain from a thread of its own, for producers on any thread; see the crate docs.
pub struct ChainFollower
Follows a chain in a directory (or one file) while a writer in any process writes it; see the module docs.
pub struct TimeMerge<T> {
sources: Vec<Source<T>>,
quiet_max: Option<Duration>,
/// The time of the last item given.
given: Option<i128>,
}
Merges sources of timed items into one stream in time order, as far as the slowest source allows.
pub struct SeriesGrid {
/// The sample the grid counts from, at most the chunk's first sample.
pub grid_index: u64,
/// Tick of sample [Self::grid_index].
pub grid_tick: i64,
/// What a stored number of the chunk is worth in the sample type's unit.
pub scale: Magnitude,
}
The time grid and scale of a series chunk's samples, carried in its head; see the module docs.
pub fn decode<T: Sample>(&self, first: usize, out: &mut [T]) -> Result<(), SampleError> {
self.column
.decode(first, out)
.map_err(column_err(self.shape))
}
Decode samples from first on into out, whole samples of interleaved lanes: out.len() / lanes samples.
pub fn series_timeline(
&self,
i: usize,
track_id: TrackId,
period: Ratio64,
) -> R<Timeline<S>, S>
The timeline of the series track track_id in piece i, of period ticks per sample, from the heads of its
chunks alone (Self::read_chunk_head).
pub struct SeriesTimeline {
period: Ratio64,
stretches: Vec<SeriesStretch>,
}
The grids of one series track, from its chunk heads in any order, checked as they come.
pub fn read_chunk_head(
&self,
i: usize,
entry: &IndexEntry,
buf: &mut Vec<u8>,
) -> R<ChunkHead, S>
Read the head of the chunk block of entry in piece i, using buf: its header, then its bytes up to the
payload, head CRC and ranges checked (ChunkHead::read_head).