Samples and their codecs¶
A series stores only values, and nearly all of its bytes are samples. How the samples are coded therefore
decides the size of a recording and how fast a reader decodes it. Which numbers should a device send, and which
codec suits them? The drive's phase_a shows the usual case: 25 000 samples a second of a current in steps of
1 mA.
Samples into columns¶
A series chunk of the drive holds a second of phase_a: 25 000 samples as i16. The recorder encodes them with
ww_tape::samples::encode into one samples column, and builds the head from the track's grid:
let shape = crate::defs::phase_shape(&def);
let mut bytes = vec![0u8; max_encoded_len(PHASE_CODEC, shape, values.len())?];
let len = encode(PHASE_CODEC, shape, &values, &mut bytes)?;
bytes.truncate(len);
let grid: SeriesGrid = def.first_grid(0);
let count = u32::try_from(samples.end - samples.start)
.map_err(|_e| Error::Settings("a block of phase_a holds at most 2^32 samples"))?;
let (first_tick, last_tick) =
grid.chunk_ticks(def.period, ItemNum::new(samples.start), count)?;
let head = ChunkHead {
kind: BlockKind::Series,
track_id: key("phase_a").id(),
track_number: self.numbers.phase_a,
first_item: ItemNum::new(samples.start),
count,
first_tick,
last_tick,
latest_end: last_tick,
time_mode: 0,
end_mode: EndMode::Absent,
grid: Some(grid),
tile: ww_tape::TileCoords::NONE,
level: 0,
};
let spec = ColumnSpec {
kind: ColumnKind::Samples,
codec: PHASE_CODEC,
param: 0,
len: bytes.len(),
};
What the example uses here: DriveNumbers, key, phase_def, phase_shape, Act
/// The numbers the drive's definitions were given ([Definitions::define_clock], [Definitions::define_track]): what its
/// records, chunks and maps name each clock and track by.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DriveNumbers {
/// The board's microsecond timer since boot: the clock of every track.
pub board_clock: ClockNum,
/// The host's wall clock in ns since the Unix epoch, which the board's clock maps to.
pub host_clock: ClockNum,
/// The firmware's log lines.
pub log: TrackNum,
/// The controller's mode, a state track.
pub mode: TrackNum,
/// CAN frames on the vehicle bus.
pub can0: TrackNum,
/// Phase current, 16-bit fixed point in mA.
pub phase_a: TrackNum,
/// Board temperature.
pub temp: TrackNum,
}
/// The key of a track at `name` in the drive's API.
pub fn key(name: &str) -> TrackKey {
track_key(API_ROOT, &[Segment::Name(name)])
}
/// The `phase_a` series definition at `hz` samples a second.
pub fn phase_def(hz: u32, summaries: bool) -> Option<GridDef<'static>> {
let mut def = GridDef::of::<i16>(1, Ratio64::new(1_000_000, u64::from(hz))?);
def.scale = Magnitude::pow10(-3);
def.summaries = summaries.then(phase_summaries);
Some(def)
}
/// The shape of `phase_a`'s samples: its track's items are i16 numbers, one channel.
pub fn phase_shape(def: &GridDef<'_>) -> SampleShape {
def.shape(<i16 as SeriesValue>::ELEMENT)
}
/// One thing the recorder hands the chain.
#[derive(Clone, Debug, PartialEq)]
pub enum Act {
/// A put of the mode in force from `ticks` on.
Put { ticks: i64, mode: Mode },
/// A records block: log lines and temperatures, (track, ticks, item) in time order.
Records(Vec<(TrackNum, i64, Vec<u8>)>),
/// A chunk of `can0` or `phase_a`: its head and columns.
Chunk {
head: Box<ChunkHead>,
columns: Vec<(ColumnSpec, Vec<u8>)>,
},
/// A summary block of `phase_a`.
Summary(Vec<u8>),
}
A recorder that writes through a TapeMux leaves the encoding to the handle of the track. The drive's recorder gives
the GridHandle the codec of the column, and then only the samples of each second:
let options = GridOptions {
chunk_steps: u32::MAX,
chunk_bytes: exact_units::Bytes::new(u32::MAX),
latency: None, // a chunk is completed after each block of the run, not by time
codec: PHASE_CODEC,
summaries: self.drive.summaries,
first_item: head.first_item,
first_tick: head.first_tick,
};
let mut phase_a = self.mux.grid::<i16>(self.numbers.phase_a, options)?;
if head.first_item.get() > 0 {
// a resumed track goes on on the grid the run started with, from sample 0
let def = crate::defs::phase_def(self.drive.phase_hz, self.drive.summaries)
.ok_or(Error::Settings("phase_hz is not 0"))?;
phase_a.regrid(def.first_grid(0))?;
}
self.phase_a = Some(phase_a);
The head's first and last tick come from the grid, by SeriesGrid::chunk_ticks, and every sample's tick follows from
them. The chunk stores no time per sample. The column's codec is the recorder's choice, here Codec::DELTA.
A codec works on groups of 128 samples. Every group restarts its prediction, so a reader decodes any range from the start of its group, and damage costs only the groups it touches. A chunk of several channels, such as I and Q, codes each channel as a lane of its own. Sample codecs lists every codec by number.
Fixed point¶
A fixed-point number is an integer count of a step that the type states. The drive's current is an i16 in steps
of 1 mA, and the device sends the count. The step lives in the track and in each chunk's head, never in a sample. An
exact_units Fixed<Ampere, Milli, i16> is such a type, an i16 on the wire and in the column.
Fixed point keeps the numbers exact from the device to the file, and nothing passes through a float on the way. It is also the smallest form of the data and the fastest to decode. A converter's counts are integers already, so a device that controls its data sends them as they are.
Delta codecs¶
A smooth signal changes little from one sample to the next. The delta codecs store those differences instead of the values, in groups of 128. Each group stores its first value and its smallest difference. The differences less that minimum are bit-packed at the group's width, so a constant or a ramp costs no bits per sample.
ww_tape_figures from the first group of the chunk of phase_a at second 60, full
rate.Codec::DELTA2 stores the differences of the differences, which suits a signal that changes by steady steps. The
drive's hour shows what each codec costs phase_a:
phase_a codec |
Bytes | Bytes per sample |
|---|---|---|
Codec::RAW |
180000000 | 2.000 |
Codec::DELTA |
99131283 | 1.101 |
Codec::DELTA2 |
96350188 | 1.071 |
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 stores a radio's samples that way.
Floats and ALP¶
Some floats come from sources nobody controls, such as a sensor that reports only f32 or a value that another
program computed. For them the format has one float codec, Codec::ALP, after the paper by Afroozeh, Kuffó and Boncz
at the SIGMOD conference of 2024.
ALP looks for floats that began as decimals and stores the integers they came from. A converter's count times 0.1, for
example, becomes the count again, and ALP bit-packs those integers in groups. Floats with full mantissas take ALP's
second scheme, which codes their front bits through a small dictionary. Values that do not come back bit for bit stay
whole, such as NaN payloads, infinities and -0.0. A group never grows by more than 7 bytes over its raw size.
ALP can only recover integers that a short decimal scale hid. The test below codes 4096 counts of a 12-bit converter in
three ways. They are i16 counts with DELTA, volts in tenths with ALP, and volts of a 3.3 V range with ALP:
/// The bytes `values` take in `codec`.
fn coded<T: Sample + SeriesValue>(codec: Codec, values: &[T]) -> usize {
let shape = SampleShape::scalar(T::ELEMENT);
let mut out = vec![0; max_encoded_len(codec, shape, values.len()).expect("a valid shape")];
encode(codec, shape, values, &mut out).expect("the values code")
}
// A slow triangle wave with a little noise, as a 12-bit converter counts it.
let mut noise = 1u32;
let counts: Vec<i16> = (0..4096)
.map(|i: i16| {
noise = noise.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
500 + (i % 1024 - 512).abs() * 3 + (noise >> 29) as i16
})
.collect();
let tenths: Vec<f64> = counts.iter().map(|&c| f64::from(c) * 0.1).collect();
let volts: Vec<f64> = counts
.iter()
.map(|&c| f64::from(c) * 3.3 / 4096.0)
.collect();
assert_eq!(coded(Codec::DELTA, &counts), 2336); // fixed point
assert_eq!(coded(Codec::ALP, &tenths), 5152); // a short decimal scale
assert_eq!(coded(Codec::ALP, &volts), 26848); // a scale ALP cannot undo
assert_eq!(coded(Codec::RAW, &volts), 32768); // 8 bytes a sample
The counts take about 2.3 KB. ALP undoes the scale of 0.1 and stores the same signal in about 5.2 KB, still more than twice the size. The scale 3.3/4096 is no short decimal, so ALP stores about 27 KB of the 33 KB raw.
Fixed point against floats¶
just bench-sample-codecs compares the same choices on real and simulated data. It stores each set as fixed-point
integers with DELTA and as floats with ALP. For comparison, it also tries the XOR codecs after Gorilla and Chimp, and
DELTA on the float bits. The bench keeps those other float codecs for comparison only; they are not part of the
format. Every value comes back bit for bit.
The bench runs in chunks of 4096 samples. Sizes and speeds draws its ratio and decode time per data set. Fixed point is smaller than the best float codec on every set, and it decodes fastest. Float codecs measured describes the data sets.
Which sample codec¶
The choice follows from who controls the numbers:
| The samples are | Store them as | Codec |
|---|---|---|
| counts or steps a device controls | fixed-point integers, the step in the type | Codec::DELTA, or Codec::DELTA2 for steady slopes |
| a device's own packing, such as 12-bit pairs | the device's bytes as sent | the packed element, decoded on read |
| floats nobody controls | the floats | Codec::ALP |
Series shows how a reader finds and decodes a range of samples.
What a chunk costs the writer¶
The writer adds little to the encoding. just bench-chunks measures what it spends on a series chunk of 1 MiB, which
holds 524 288 i16 samples. Sizes and speeds draws each part.
| What | ns per chunk | GB/s |
|---|---|---|
chunk::write_chunk: copy and CRCs |
57 629 | 18.20 |
Block::read: the CRCs checked |
36 665 | 28.60 |
ItemHash::of: BLAKE3 |
235 403 | 4.46 |
TrackHash::chunk_unit: the unit hash |
159 | 6598.18 |
TapeWriter::write_chunk (columns) |
306 780 | 3.42 |
TapeWriter::write_chunk into a MemSink |
957 762 | 1.10 |
chunk::write_chunk + TapeWriter::write_block |
327 055 | 3.21 |
just bench-chunks on build-1, load average 5.68 before, 5.68 after.
The content hash is most of the cost.
TapeReader.pub fn encode<T: Sample>(
codec: Codec,
shape: SampleShape,
values: &[T],
out: &mut [u8],
) -> Result<usize, SampleError> {
let (lane, lanes) = lanes_of(shape)?;
codecs::encode(codec, lane, lanes, values, out).map_err(column_err(shape))
}
Code values (whole samples of shape, lanes interleaved) in codec into out, which holds at least
max_encoded_len bytes; returns the bytes written.
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 GridHandle<T: PieceStore, S: Scalar + Sample + Send + 'static> {
s: Sender<T>,
open: Arc<Open<T, GridChunks<S>>>,
backlog: Backlog<T>,
track: TrackNum,
}
Writes the time steps of one grid track from one producer: the whole grid, or one box of its tiles.
pub fn chunk_ticks(
&self,
period: Ratio64,
first_item: ItemNum,
count: u32,
) -> Result<(i64, i64), SeriesError>
First and last tick of count samples from first_item on the grid: what a series chunk head of them holds.
pub const DELTA: Self = Self(32);
Integers, differences bit-packed per group.
pub const DELTA2: Self = Self(33);
Integers, differences of differences bit-packed per group.
pub const ALP: Self = Self(26);
Floats, ALP: decimals as integers bit-packed per group, other floats' front bits through a dictionary.
pub const RAW: Self = Self(0);
Plain little-endian values (starts and ends as i64, flags as u32, lengths as u32, samples in their element type) or plain bytes (payload).