Skip to content
Basic

Summaries

A plot of a long track has a few hundred pixels across, and the track may hold millions of items. Reading them all for one picture costs far too much. A writer therefore keeps summaries beside the data, a coarse view built while the run is recorded. A viewer draws the whole track from them and zooms in to the items where it needs them.

A viewer, for example, opens on the whole hour of phase_a, 90 million samples, in a plot 600 pixels wide. The track's chunks hold about 100 MB, and the viewer draws the hour from the summaries instead.

A tree over item numbers

A summary node covers a run of a track's items and holds what a viewer needs to draw them. A node at level 0 covers a power of two of items, 1 024 samples for the drive's current. Each level up, a node covers 16 nodes of the level below: at level 1, 16 384 samples. The nodes run over item numbers, not time. A sparse track therefore has no empty nodes, and the nodes of two pieces of one track line up.

A track has one of two kinds of tree:

Tree Level 0 A node holds
events 2 048 items the first and last item's start, the OR of the items' flags, and for spans the latest end
series a power of two of samples, which the track picks per channel, the statistics the track declares

A series declares its statistics in its definition, a SeriesSummarySpec. The drive's phase_a keeps the minimum, the maximum, the sum and the sum of squares. From them a viewer draws the envelope and the root mean square:

SeriesSummarySpec {
    base_shift: 10,
    stats: SeriesStats {
        min: true,
        max: true,
        sum: true,
        sum_sq: true,
        clipped: false,
        flags: false,
        power_mean: false,
        power_max: false,
    },
    clip: None,
}
What the example uses here: phase_def, phase_shape
/// 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)
}

A node holds no ticks, since the chunks' grids give every sample's tick. A summary block holds the nodes of one level over a stretch of the track. The index lists it like any block, with its level.

phase_a's summary nodes over its 90000 samples, minimum to maximum level 1 level 0 one node of level 1 merges 16 of level 0 columns 91 level-0 nodes of 1024 samples, 9 of level 1; 24 pixel columns, each the merge of the level-0 nodes that start in it the bars run from each node's minimum to its maximum current, on one scale for all three rows
Summary nodes of phase_a over its item numbers: each node at level 1 merges 16 nodes of level 0, and each bar spans its node's minimum and maximum. The viewer's pixel columns take the nodes of the coarsest level that still has a node per column. Drawn by ww_tape_figures from the summary blocks of the drive's recording at 1/1000 of its data.

Drawing the hour

The viewer picks the coarsest level whose nodes still outnumber its 600 columns. Every column then gets several nodes, and no column falls between two:

// the coarsest level whose nodes still outnumber the columns: a level up, a node covers 16 times as many samples
let mut level = 0u8;
while total >> (spec.base_shift + 4 * (level + 1)) >= COLUMNS as u64 {
    level += 1;
}
What the example uses here: the fault's constants, series_def, column_of, nodes
/// 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))
}

/// The column of sample `i` of `total`.
fn column_of(i: u64, total: u64) -> usize {
    let c = u128::from(i) * COLUMNS as u128 / u128::from(total.max(1));
    usize::try_from(c).map_or(COLUMNS - 1, |c| c.min(COLUMNS - 1))
}

/// The nodes of the summary blocks of `phase_a` at `level` in every piece that cover any sample of `items`, each with
/// its first sample and the samples it covers.
fn nodes<S: ByteSource>(
    reader: &TapeReader<S>,
    entries: &[Vec<IndexEntry>],
    level: u8,
    items: core::ops::Range<u64>,
    mut take: impl FnMut(u64, u64, ChannelStats),
) -> Result<(u64, u64), FaultError<S::Error>> {
    let (mut blocks, mut count) = (0, 0);
    let mut buf = Vec::new();
    for (i, entries) in entries.iter().enumerate() {
        for e in entries {
            // entries: phase_a's index entries in piece i
            let wanted =
                e.first_item < ItemNum::new(items.end) && e.end_item() > ItemNum::new(items.start);
            if e.kind != BlockKind::Summary || e.level != level || !wanted {
                continue; // another block, another level, or outside the range drawn
            }
            let block = reader.read_block(i, e, &mut buf)?;
            let summary = Summary::of_block(&block).ok_or(FaultError::Missing("summary"))?;
            let span = 1u64 << summary.head().node_shift; // samples a node covers
            for n in 0..summary.node_count() {
                let stats = summary
                    .channel_stats(0, n)
                    .ok_or(FaultError::Missing("node"))?;
                let first = summary.head().first_item.saturating_add(n as u64 * span);
                let samples = span.min(first.saturating_offset_to(e.end_item())); // the last node may be partial
                take(first.get(), samples, stats);
            }
            blocks += 1;
            count += summary.node_count() as u64;
        }
    }
    Ok((blocks, count))
}

For the hour of phase_a that is level 1, nodes of 16 384 samples. The viewer reads the summary blocks of that level in each piece, and merges each node into the column its first sample falls in:

for e in entries {
    // entries: phase_a's index entries in piece i
    let wanted =
        e.first_item < ItemNum::new(items.end) && e.end_item() > ItemNum::new(items.start);
    if e.kind != BlockKind::Summary || e.level != level || !wanted {
        continue; // another block, another level, or outside the range drawn
    }
    let block = reader.read_block(i, e, &mut buf)?;
    let summary = Summary::of_block(&block).ok_or(FaultError::Missing("summary"))?;
    let span = 1u64 << summary.head().node_shift; // samples a node covers
    for n in 0..summary.node_count() {
        let stats = summary
            .channel_stats(0, n)
            .ok_or(FaultError::Missing("node"))?;
        let first = summary.head().first_item.saturating_add(n as u64 * span);
        let samples = span.min(first.saturating_offset_to(e.end_item())); // the last node may be partial
        take(first.get(), samples, stats);
    }
What the example uses here: column_of
/// The column of sample `i` of `total`.
fn column_of(i: u64, total: u64) -> usize {
    let c = u128::from(i) * COLUMNS as u128 / u128::from(total.max(1));
    usize::try_from(c).map_or(COLUMNS - 1, |c| c.min(COLUMNS - 1))
}

The overview reads 175 summary blocks with 5 497 nodes: about 194 KB in 175 reads, and no sample. Finding those blocks costs more than reading them. phase_a's index entries in the four pieces take about 843 KB in 19 reads, since the track has a chunk a second. A viewer that opens the recording once keeps the entries in memory.

All 600 columns get nodes. The column with the highest peak is column 519, from 51:54.000, at 31 873 mA. It holds the seconds just before the current stops at 52:00.

Zooming in

Next the viewer zooms into that column. It reads the level-0 nodes of the column alone, from the summary blocks whose items overlap it, with the same loop. The node with the highest peak covers the 1 024 samples from item 77 999 104, at 51:59.964. The zoom reads about 6.8 KB in 6 reads.

That node lies in the chunk from 51:59.000, which Series reads, sample by sample. The way from the hour to the 500 samples before the trip thus runs through summaries and one chunk. Events reads the frames after the trip, and Reading a tape the mode on either side.

The phase current in eventfull at three zooms. The phase current in eventfull at three zooms.

The same zoom in a viewer. Over the hour, each column is the range of the summary nodes in it. The second before the trip shows the 50 Hz current and its rise at the end. At 4 ms the viewer reads the chunk and draws each sample as a dot, at the 32 A peak. A screenshot rendered by eventfull_book_shots from the recording at full rate.

How nodes merge

Every statistic merges: a parent is its 16 children merged in item order, with ChannelStats::merge for a series and EventNode::merge for events. A reader that builds coarser bins of its own, such as the viewer's columns, gets exactly what the writer would have stored. A minimum of minimums is the minimum, and sums add.

Nodes of two scales merge at their common scale, as Changing scale mid-run shows. A summary block states its scale, so it reads without the chunks.

Writing summaries

The crate ww_tape_summary builds the trees as the items arrive: an EventTree for an event track, a SeriesSummaries for a series. A recorder that writes the file itself starts one for phase_a with the track's first grid and period:

let start = SeriesStart {
    track_id: key("phase_a").id(),
    track_number: numbers.phase_a,
    shape: crate::defs::phase_shape(&def),
    first_item: ItemNum::new(0),
    grid: def.first_grid(0),
    period: def.period,
    tile: ww_tape::TileCoords::NONE,
    tile_cells: 1,
};
Some(SeriesSummaries::new(start, crate::defs::phase_summaries())?)
What the example uses here: DriveNumbers, key, phase_def, phase_shape
/// 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)
}

Each second, the recorder pushes the second's samples. A level that fills a block gives that block, and the recorder hands it to the writer with TapeWriter::defer_block. The writer places a deferred block where it fits, in an aligned file into the gap before a chunk's payload:

if let Some(s) = &mut self.summaries {
    s.push(&values, 0)?; // a second of samples, flags 0
    // the blocks of the levels that filled, for the writer's defer_block
    self.queue
        .extend(s.take_blocks().into_iter().map(Act::Summary));
}
What the example uses here: Act
/// 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>),
}

At the end of the run, SeriesSummaries::finish gives the blocks of the partial nodes. The first piece of the drive's recording holds 735 summary blocks of about 825 KB, beside about 25 MB of samples. A lost summary block costs nothing that a reader cannot rebuild from the chunks.

A recorder that writes through a TapeMux builds no tree of its own. Its GridHandle computes the leaves of the samples it takes, as its summaries option says (Samples into columns shows it). The writing thread builds the levels above them, one tree per piece, ended before each cut and at the close. A mux resumed after a crash rebuilds the tree of the torn piece from the chunks the piece kept. The resumed file then holds the bytes of the run without the crash.

The crate ww_tape itself reads only a summary block's head, with Block::summary_head, which is enough to list the block in the index. Summary::of_block in ww_tape_summary reads the nodes. Checks and range hashes shows how a copy proves that it holds the same frames as the recording.