Following objects through a video: tracking by detection
Link a detector's boxes into identities that persist across frames with a Kalman filter and the Hungarian method, then judge the tracks with MOTA, IDF1 and identity switches.
What runs in CodeSplash
You will be able to
- Describe tracking by detection as predict, associate and update
- Choose between SORT, ByteTrack and DeepSORT-style association
- Set how many detections confirm a track and how long a lost track is kept
- Read MOTA, IDF1, identity switches and fragmentations against reference tracks
From boxes to identities
ReadObject detection answers "what is in this frame?". Counting people who walked past a door, measuring how long a car waited, or following a cell across a microscope video needs more: the boxes of one object in consecutive frames must share an id. That is tracking by detectionMulti-object tracking (tracking by detection)Linking detections in consecutive frames into tracks, so each object keeps one id while it moves through the video., and it needs only the table of boxes — no video.
Every frame, three steps:
- Predict. A Kalman filterKalman filterExact filtering for linear-Gaussian state-space models: the hidden state's mean and variance, updated step by step. moves each track's box forward with its estimated velocity.
- Associate. The Hungarian methodHungarian method (linear assignment)Pairs two lists (tracks and detections) one-to-one so the total cost is smallest; ties go to the lowest index in CodeSplash. pairs predicted boxes with this frame's detections, one-to-one, at the lowest total cost.
- Update. Paired tracks correct their state with the detection; unpaired detections may start new tracks; tracks unpaired for too long end.
Three ways to pair
ReadSORT, ByteTrack and DeepSORTSORT, ByteTrack and DeepSORTWays to join detections to tracks: by box overlap (SORT), also rescuing low-confidence boxes (ByteTrack), or by appearance (DeepSORT). share the motion model and differ in what they pair on:
| Association | Pairs by | Good when |
|---|---|---|
| SORT | box overlap (IoU) with the predicted box | detections are reliable and objects move smoothly |
| ByteTrack | confident boxes first, then low-confidence boxes for tracks seen in the last frame | occlusions lower the detector's confidence |
| DeepSORT-style | distance between appearance embeddings, inside a motion gate | objects cross paths or disappear briefly |
7 tracks from 184 detections in 2 sequences (SORT association); 178 detections joined a track. Against 7 reference tracks: MOTA 0.886, IDF1 0.939, 0 identity switches.
- Tracks
- 7
- MOTA
- 0.8856
- IDF1
- 0.9393
- Identity switches
- 0
Plots
Bars break where a track missed more than one frame.
View data
| media_id | Last frame | Track | frame |
|---|---|---|---|
| cam1 | 5 | 1 · person | 0 |
| cam1 | 11 | 1 · person | 7 |
| cam1 | 15 | 1 · person | 14 |
| cam1 | 22 | 1 · person | 17 |
| cam1 | 34 | 1 · person | 24 |
| cam1 | 39 | 1 · person | 36 |
| cam1 | 3 | 2 · person | 0 |
| cam1 | 6 | 2 · person | 5 |
| cam1 | 22 | 2 · person | 8 |
| cam1 | 26 | 2 · person | 24 |
| cam1 | 36 | 2 · person | 28 |
| cam1 | 39 | 2 · person | 38 |
| cam1 | 29 | 3 · car | 5 |
| cam1 | 21 | 4 · person | 18 |
| cam1 | 25 | 4 · person | 23 |
| cam1 | 30 | 4 · person | 27 |
| cam1 | 39 | 4 · person | 32 |
| cam2 | 10 | 5 · car | 0 |
| cam2 | 13 | 5 · car | 12 |
| cam2 | 17 | 5 · car | 15 |
| cam2 | 23 | 5 · car | 20 |
| cam2 | 25 | 5 · car | 25 |
| cam2 | 29 | 5 · car | 27 |
| cam2 | 23 | 6 · person | 3 |
| cam2 | 25 | 6 · person | 25 |
| cam2 | 29 | 6 · person | 27 |
| cam2 | 25 | 7 · person | 10 |
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections | Mean score |
|---|---|---|---|---|---|---|---|
| 1 | cam1 | person | 0 | 39 | 40 | 34 | 0.7038 |
| 2 | cam1 | person | 0 | 39 | 40 | 35 | 0.7367 |
| 3 | cam1 | car | 5 | 29 | 25 | 25 | 0.7794 |
| 4 | cam1 | person | 18 | 39 | 22 | 19 | 0.8095 |
| 5 | cam2 | car | 0 | 29 | 30 | 24 | 0.7069 |
| 6 | cam2 | person | 3 | 29 | 27 | 25 | 0.7759 |
| 7 | cam2 | person | 10 | 25 | 16 | 16 | 0.8254 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 0.8856 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 0.9393 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 0.8794 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 20 | A tracked object was lost and found again |
| Misses | 23 | Reference boxes with no track |
| False positives | 0 | Tracked boxes with no reference object |
| Mostly tracked | 7 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Boxes pair only within the same class. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact R script · R R version 4.5.1 (2025-06-13)
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 6e6158204937fdf6
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_track_objects (tracker), cs_eval_mot (tracking metrics), cs_eval_stacked
# %% Data
SEQ <- "media_id"; FRAME <- "frame"
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
SCORE <- "score"
LABEL <- "label"
FEATURES <- c()
SOURCE <- "source"
TRUTH <- "track_id"
MODE <- "sort" # sort | bytetrack | deepsort
OPTS <- list(iou = 0.3, min_hits = as.integer(3), max_age = as.numeric(30),
min_score = 0, high = 0.6, low = 0.1,
low_iou = 0.5, max_cosine = 0.3, motion_weight = 0,
per_class = TRUE)
MOT_IOU <- 0.5
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction") # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
FEATURES <- if (length(FEATURES)) as.character(FEATURES) else character(0)
columns <- unique(c(SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH, FEATURES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_tracks.parquet", col_select = columns))
df$`__row` <- seq_len(nrow(df)) - 1L # position in the analysis input
n_input <- nrow(df)
if (MODE == "bytetrack" && is.null(SCORE)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or DeepSORT-style unless a confidence score column is set", value = "ByteTrack")
if (MODE == "deepsort" && !length(FEATURES)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or ByteTrack unless embedding columns are set", value = "DeepSORT-style")
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
# The reference table's rows go above the detections under an added source column (twin: with_reference).
w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/track.objects/sort-with-reference/out-r", "reference_table"),
list(sequence = SEQ, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, score = SCORE, label = LABEL, truth = TRUTH),
REF_ROLES, list(label = "Class"), SOURCE, REF_LEVEL, c("sequence", "frame", "x0", "y0", "x1", "y1", if (!is.null(LABEL)) "label"))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
SEQ <- wc$sequence; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
LABEL <- wc$label; TRUTH <- wc$truth
SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
}
needed <- c(SEQ, FRAME, X0, Y0, X1, Y1, LABEL)
numeric_cols <- c(FRAME, X0, Y0, X1, Y1, SCORE, FEATURES)
if (!is.null(SOURCE)) {
st <- cs_eval_stacked(df, c(needed, SOURCE), numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
} else {
if (n_input == 0L) cs_error("CS_E_NO_ROWS")
for (c in needed) if (all(is.na(df[[c]]))) cs_error("CS_E_ALL_MISSING", column = c)
keep <- rep(TRUE, n_input)
for (c in needed) keep <- keep & !is.na(df[[c]])
df <- df[keep, , drop = FALSE]
warnings <- if (nrow(df) < n_input) list(cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input)) else list()
if (nrow(df) == 0L) cs_error("CS_E_NO_ROWS")
for (c in numeric_cols) {
k <- sum(is.infinite(as.numeric(df[[c]])))
if (k > 0) cs_error("CS_E_NOT_FINITE", column = c, count = k)
}
is_ref <- logical(nrow(df))
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
det <- !is_ref
if (!is.null(SCORE)) {
no_score <- det & is.na(as.numeric(df[[SCORE]]))
if (any(no_score)) {
warnings <- c(warnings, sprintf("%d detections have no %s and were left out.", sum(no_score), SCORE))
det <- det & !no_score
}
}
if (length(FEATURES)) {
no_feat <- det & !stats::complete.cases(df[FEATURES])
if (any(no_feat)) {
warnings <- c(warnings, sprintf("%d detections miss an embedding value and were left out.", sum(no_feat)))
det <- det & !no_feat
}
}
if (sum(det) < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Tracking", min = 2, n = sum(det))
# %% Tracks
di <- which(det)
seq_all <- as.character(df[[SEQ]])
frame_all <- as.numeric(df[[FRAME]])
lab_all <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
feats <- if (length(FEATURES)) as.matrix(df[di, FEATURES, drop = FALSE]) else NULL
if (!is.null(feats)) storage.mode(feats) <- "double"
res <- cs_track_objects(seq_all[di], frame_all[di], box[di, , drop = FALSE], if (!is.null(SCORE)) as.numeric(df[[SCORE]])[di] else NULL,
if (!is.null(LABEL)) lab_all[di] else NULL, feats, MODE, OPTS)
tid_det <- res$track
track_id <- rep(NA_integer_, n_input) # per input row; rows that weren't tracked stay empty
track_id[df$`__row`[di][tid_det > 0L] + 1L] <- tid_det[tid_det > 0L]
tracks <- res$tracks
n_tracks <- length(tracks)
n_assigned <- sum(tid_det > 0L)
# %% Against the reference tracks
metrics <- NULL
switch_events <- list()
if (!is.null(SOURCE) && !is.null(TRUTH) && sum(is_ref) > 0) {
truth_ok <- is_ref & !is.na(df[[TRUTH]])
if (sum(is_ref & !truth_ok) > 0) warnings <- c(warnings, sprintf("%d reference boxes have no %s and were left out of the tracking metrics.", sum(is_ref & !truth_ok), TRUTH))
truth_all <- as.character(df[[TRUTH]])
gi <- which(truth_ok)
hi <- di[tid_det > 0L]
hyp_of <- integer(nrow(df))
hyp_of[di] <- tid_det
seqs <- list()
for (sq in sort(unique(c(seq_all[gi], seq_all[hi])), method = "radix")) {
g_s <- gi[seq_all[gi] == sq]
h_s <- hi[seq_all[hi] == sq]
frames <- list()
for (f in sort(unique(c(frame_all[g_s], frame_all[h_s])))) {
g_f <- g_s[frame_all[g_s] == f]
h_f <- h_s[frame_all[h_s] == f]
# paste() would recycle an empty id vector into one id: frames with predictions but no reference boxes get none.
gt_ids <- if (length(g_f)) paste(sq, truth_all[g_f], sep = "\u001f") else character(0)
frames[[length(frames) + 1L]] <- list(frame = f, gt_ids = gt_ids, gt_boxes = box[g_f, , drop = FALSE],
hyp_ids = as.character(hyp_of[h_f]), hyp_boxes = box[h_f, , drop = FALSE])
}
seqs[[length(seqs) + 1L]] <- frames
}
metrics <- cs_eval_mot(seqs, MOT_IOU)
switch_events <- metrics$switch_events
}
# %% Assumptions
assumptions <- list(
list(key = "frames", label = "Frames are in order", status = "info",
detail = "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."),
list(key = "motion", label = "Objects move smoothly", status = "info",
detail = "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.")
)
if (length(FEATURES)) assumptions[[3]] <- list(key = "appearance", label = "Embeddings describe appearance", status = "info",
detail = "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close.")
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tl <- vapply(tracks, function(t) if (is.na(t$label)) NA_character_ else t$label, character(1))
labels_seen <- sort(unique(tl[!is.na(tl)]), method = "radix")
seq_list <- sort(unique(seq_all[di]), method = "radix")
n_frames <- sum(!duplicated(paste(seq_all[di], sprintf("%.17g", frame_all[di]), sep = "\u001f")))
nz <- function(v) if (is.null(v)) NA_real_ else v
values <- list(association = MODE, n_sequences = length(seq_list), n_frames = n_frames, n_detections = length(di), n_tracks = n_tracks,
n_assigned = n_assigned, n_unassigned = length(di) - n_assigned,
mean_track_length = if (n_tracks) mean(vapply(tracks, function(t) t$n_detections, numeric(1))) else NA_real_,
mota = NA_real_, motp = NA_real_, idf1 = NA_real_, idp = NA_real_, idr = NA_real_, id_switches = NA_real_, fragmentations = NA_real_,
false_positives = NA_real_, misses = NA_real_, mostly_tracked = NA_real_, partially_tracked = NA_real_, mostly_lost = NA_real_,
precision = NA_real_, recall = NA_real_, n_gt_tracks = NA_real_, n_gt_boxes = NA_real_, track_id = I(track_id))
for (lab in labels_seen) values[[sprintf("tracks[%s]", lab)]] <- sum(tl == lab, na.rm = TRUE)
if (!is.null(metrics)) {
values$mota <- metrics$mota; values$motp <- metrics$motp; values$idf1 <- metrics$idf1; values$idp <- metrics$idp; values$idr <- metrics$idr
values$id_switches <- metrics$switches; values$fragmentations <- metrics$fragmentations; values$false_positives <- metrics$false_positives
values$misses <- metrics$misses; values$mostly_tracked <- metrics$mostly_tracked; values$partially_tracked <- metrics$partially_tracked
values$mostly_lost <- metrics$mostly_lost; values$precision <- metrics$precision; values$recall <- metrics$recall
values$n_gt_tracks <- metrics$n_gt_tracks; values$n_gt_boxes <- metrics$objects
}
trk_rows <- lapply(tracks, function(t) list(track_id = t$track_id, sequence = t$sequence, label = t$label, first_frame = t$first_frame,
last_frame = t$last_frame, span = t$last_frame - t$first_frame + 1, n_detections = t$n_detections,
mean_score = t$mean_score))
tcols <- c(list(list(key = "track_id", label = "Track", type = "integer"), list(key = "sequence", label = SEQ, type = "string")),
if (!is.null(LABEL)) list(list(key = "label", label = LABEL, type = "string")),
list(list(key = "first_frame", label = "First frame", type = "number"), list(key = "last_frame", label = "Last frame", type = "number"),
list(key = "span", label = "Frames spanned", type = "number"), list(key = "n_detections", label = "Detections", type = "integer")),
if (!is.null(SCORE)) list(list(key = "mean_score", label = "Mean score", type = "number")))
tables <- list(list(key = "tracks", title = "Tracks", columns = tcols, rows = utils::head(trk_rows, 500),
note = if (length(trk_rows) > 500) "First 500 tracks." else NULL))
if (!is.null(metrics)) {
mrows <- list(list("MOTA", metrics$mota, "1 − (misses + false positives + identity switches) / reference boxes"),
list("IDF1", metrics$idf1, "Share of boxes on the right identity (global track matching)"),
list("MOTP (mean IoU)", metrics$motp, "Mean overlap of the paired boxes"),
list("Identity switches", metrics$switches, "A reference object took a different track"),
list("Fragmentations", metrics$fragmentations, "A tracked object was lost and found again"),
list("Misses", metrics$misses, "Reference boxes with no track"), list("False positives", metrics$false_positives, "Tracked boxes with no reference object"),
list("Mostly tracked", metrics$mostly_tracked, "Reference tracks paired in at least 80% of their frames"),
list("Mostly lost", metrics$mostly_lost, "Reference tracks paired in under 20% of their frames"))
tables[[length(tables) + 1L]] <- list(key = "mot", title = sprintf("Against the reference tracks (IoU ≥ %g)", MOT_IOU),
columns = list(list(key = "metric", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "meaning", label = "Meaning", type = "string")),
rows = lapply(mrows, function(r) list(metric = r[[1]], value = r[[2]], meaning = r[[3]])))
if (length(switch_events)) {
tables[[length(tables) + 1L]] <- list(key = "switches", title = "Identity switches",
columns = list(list(key = "sequence", label = SEQ, type = "string"), list(key = "frame", label = "Frame", type = "number"),
list(key = "object", label = "Reference object", type = "string"), list(key = "from", label = "From track", type = "string"),
list(key = "to", label = "To track", type = "string")),
rows = lapply(utils::head(switch_events, 200), function(e) { p <- strsplit(e$object, "\u001f", fixed = TRUE)[[1]]
list(sequence = p[1], frame = e$frame, object = p[2], from = e$from, to = e$to) }),
note = if (length(switch_events) > 200) "First 200 switches." else NULL)
}
}
charts <- list()
if (n_tracks) {
lane_of <- function(t) paste0(t$track_id, if (!is.na(t$label)) paste0(" · ", t$label) else "")
shown <- utils::head(tracks, 60)
color_of <- function(t) if (length(seq_list) > 1L) t$sequence else if (!is.na(t$label)) t$label else t$sequence
ln <- character(0); s0 <- numeric(0); s1 <- numeric(0); col <- character(0); ev <- character(0)
fr_det <- frame_all[di]
for (t in shown) {
fr <- sort(fr_det[tid_det == t$track_id])
brk <- which(diff(fr) > 1)
starts <- c(fr[1], fr[brk + 1L])
ends <- c(fr[brk], fr[length(fr)])
ln <- c(ln, rep(lane_of(t), length(starts))); s0 <- c(s0, starts); s1 <- c(s1, ends)
col <- c(col, rep(color_of(t), length(starts))); ev <- c(ev, rep(NA_character_, length(starts)))
}
shown_ids <- vapply(shown, function(t) t$track_id, numeric(1))
for (e in switch_events) {
to <- as.integer(e$to)
if (to %in% shown_ids) {
t <- shown[[which(shown_ids == to)[1]]]
ln <- c(ln, lane_of(t)); s0 <- c(s0, e$frame); s1 <- c(s1, e$frame); col <- c(col, color_of(t)); ev <- c(ev, "Identity switch")
}
}
roles <- list(lane = cs_col("Track", ln, "categorical", levels = vapply(shown, lane_of, character(1))),
start = cs_col(FRAME, s0, "numeric"), end = cs_col("Last frame", s1, "numeric"),
color = cs_col(if (length(seq_list) > 1L) SEQ else if (!is.null(LABEL)) LABEL else SEQ, col, "categorical"))
if (any(!is.na(ev))) roles$event <- cs_col("Event", ev, "categorical")
charts[[1]] <- cs_chart("timeline", "track-timeline", "When each track was seen", roles,
note = paste0(if (n_tracks > 60) "The first 60 tracks. " else "", "Bars break where a track missed more than one frame."))
}
out <- cs_ml_out_dir("target/academy-parity/run-8142/track.objects/sort-with-reference/out-r")
labels_path <- file.path(out, "labels.parquet")
nanoparquet::write_parquet(data.frame(row = as.numeric(seq_len(n_input) - 1L), cluster = as.numeric(ifelse(is.na(track_id), -1L, track_id))), labels_path)
names_mode <- c(sort = "SORT", bytetrack = "ByteTrack", deepsort = "DeepSORT-style")
summary <- sprintf("%d track%s from %d detections in %d sequence%s (%s association); %d detections joined a track.", n_tracks, if (n_tracks != 1) "s" else "",
length(di), length(seq_list), if (length(seq_list) != 1) "s" else "", names_mode[[MODE]], n_assigned)
if (!is.null(metrics)) summary <- paste0(summary, sprintf(" Against %d reference tracks: MOTA %s, IDF1 %s, %d identity switches.", as.integer(metrics$n_gt_tracks),
f3(metrics$mota), f3(metrics$idf1), as.integer(metrics$switches)))
cs_publish(list(
method = "track.objects",
methodVersion = "1.1.1",
title = "Object tracks",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = c(list(list(key = "n_tracks", label = "Tracks", value = n_tracks)),
if (!is.null(metrics)) list(list(key = "mota", label = "MOTA", value = metrics$mota), list(key = "idf1", label = "IDF1", value = metrics$idf1),
list(key = "id_switches", label = "Identity switches", value = metrics$switches))),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Tracks start from detections and are confirmed after %d detections; a confirmed track ends after %g frames without one. ", OPTS$min_hits, OPTS$max_age),
if (!is.null(LABEL) && OPTS$per_class) "Boxes pair only within the same class. " else "",
"Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).")),
charts = charts,
artifacts = list(list(key = "labels", path = labels_path, format = "parquet")),
values = values
))
7 tracks from 184 detections in 2 sequences (SORT association); 178 detections joined a track. Against 7 reference tracks: MOTA 0.886, IDF1 0.939, 0 identity switches.
- Tracks
- 7
- MOTA
- 0.8856
- IDF1
- 0.9393
- Identity switches
- 0
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections | Mean score |
|---|---|---|---|---|---|---|---|
| 1 | cam1 | person | 0 | 39 | 40 | 34 | 0.7038 |
| 2 | cam1 | person | 0 | 39 | 40 | 35 | 0.7367 |
| 3 | cam1 | car | 5 | 29 | 25 | 25 | 0.7794 |
| 4 | cam1 | person | 18 | 39 | 22 | 19 | 0.8095 |
| 5 | cam2 | car | 0 | 29 | 30 | 24 | 0.7069 |
| 6 | cam2 | person | 3 | 29 | 27 | 25 | 0.7759 |
| 7 | cam2 | person | 10 | 25 | 16 | 16 | 0.8254 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 0.8856 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 0.9393 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 0.8794 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 20 | A tracked object was lost and found again |
| Misses | 23 | Reference boxes with no track |
| False positives | 0 | Tracked boxes with no reference object |
| Mostly tracked | 7 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Boxes pair only within the same class. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 6e6158204937fdf6
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.evaluate import mot # twin: codesplashr cs_eval_mot
from codesplash.evaluate.stacked import stacked # twin: cs_eval_stacked
from codesplash import ml as csml
from codesplash.track import objects as tr # twin: codesplashr cs_track_objects
# %% Data
SEQ, FRAME = "media_id", "frame"
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
SCORE = "score"
LABEL = "label"
FEATURES = []
SOURCE = "source"
TRUTH = "track_id"
MODE = "sort" # sort | bytetrack | deepsort
OPTS = {"iou": 0.3, "min_hits": int(3), "max_age": float(30),
"min_score": 0, "high": 0.6, "low": 0.1,
"low_iou": 0.5, "max_cosine": 0.3, "motion_weight": 0,
"per_class": True}
MOT_IOU = 0.5
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"] # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH] + FEATURES if c))
df = pd.read_parquet("tests/parity/fixtures/img4_tracks.parquet", columns=columns)
df["__row"] = np.arange(len(df)) # position in the analysis input
n_input = len(df)
if MODE == "bytetrack" and not SCORE:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or DeepSORT-style unless a confidence score column is set", value="ByteTrack")
if MODE == "deepsort" and not FEATURES:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or ByteTrack unless embedding columns are set", value="DeepSORT-style")
pre_warnings = []
if REF_ROLES is not None:
# The reference table's rows go above the detections under an added source column (twin: cs_eval_with_reference).
from codesplash.graph import dataset_option # the table the host wrote for the option
from codesplash.evaluate.stacked import with_reference
w = with_reference(df, dataset_option("target/academy-parity/run-8142/track.objects/sort-with-reference/out-python", "reference_table"),
{"sequence": SEQ, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "score": SCORE, "label": LABEL, "truth": TRUTH},
REF_ROLES, {"label": "Class"}, SOURCE, REF_LEVEL, ["sequence", "frame", "x0", "y0", "x1", "y1"] + (["label"] if LABEL else []))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
SEQ, FRAME, X0, Y0, X1, Y1 = wc["sequence"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
LABEL, TRUTH = wc["label"], wc["truth"]
SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
needed = [SEQ, FRAME, X0, Y0, X1, Y1] + ([LABEL] if LABEL else [])
numeric = [c for c in [FRAME, X0, Y0, X1, Y1, SCORE] if c] + FEATURES
if SOURCE:
st = stacked(df, needed + [SOURCE], numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
else:
if n_input == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in needed:
if df[c].isna().all():
cs.cs_error("CS_E_ALL_MISSING", column=c)
keep = np.ones(n_input, dtype=bool)
for c in needed:
keep &= df[c].notna().to_numpy()
df = df.loc[keep].reset_index(drop=True)
warnings = [cs.cs_warning("CS_W_ROWS_DROPPED", dropped=int(n_input - len(df)), total=n_input)] if len(df) < n_input else []
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in numeric:
k = int(np.isinf(df[c].to_numpy(dtype=float, na_value=np.nan)).sum())
if k:
cs.cs_error("CS_E_NOT_FINITE", column=c, count=k)
is_ref = np.zeros(len(df), dtype=bool)
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
det = ~is_ref
if SCORE:
no_score = det & np.isnan(df[SCORE].to_numpy(dtype=float, na_value=np.nan))
if no_score.any():
warnings.append(f"{int(no_score.sum())} detections have no {SCORE} and were left out.")
det &= ~no_score
if FEATURES:
no_feat = det & df[FEATURES].isna().any(axis=1).to_numpy()
if no_feat.any():
warnings.append(f"{int(no_feat.sum())} detections miss an embedding value and were left out.")
det &= ~no_feat
if int(det.sum()) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Tracking", min=2, n=int(det.sum()))
# %% Tracks
di = np.flatnonzero(det)
seq_all = np.asarray([str(x) for x in df[SEQ].tolist()], dtype=object)
frame_all = df[FRAME].to_numpy(dtype=float)
lab_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object) if LABEL else None
res = tr.track(seq_all[di], frame_all[di], box[di], df[SCORE].to_numpy(dtype=float)[di] if SCORE else None,
lab_all[di] if LABEL else None, df[FEATURES].to_numpy(dtype=float)[di] if FEATURES else None, MODE, **OPTS)
tid_det = res["track"]
track_id = [None] * n_input # per input row; rows that weren't tracked stay empty
for k, i in enumerate(di):
if tid_det[k] > 0:
track_id[int(df["__row"].iloc[i])] = int(tid_det[k])
tracks = res["tracks"]
n_tracks = len(tracks)
n_assigned = int(np.sum(tid_det > 0))
# %% Against the reference tracks
metrics = None
switch_events = []
if SOURCE and TRUTH and int(is_ref.sum()):
truth_ok = is_ref & df[TRUTH].notna().to_numpy()
if int((is_ref & ~truth_ok).sum()):
warnings.append(f"{int((is_ref & ~truth_ok).sum())} reference boxes have no {TRUTH} and were left out of the tracking metrics.")
truth_all = np.asarray([str(x) for x in df[TRUTH].tolist()], dtype=object)
gi = np.flatnonzero(truth_ok)
hi = di[tid_det > 0]
hyp_id = {int(i): str(int(t)) for i, t in zip(di, tid_det) if t > 0}
seqs = []
for sq in sorted(set(seq_all[gi].tolist()) | set(seq_all[hi].tolist())):
g_s = gi[seq_all[gi] == sq]
h_s = hi[seq_all[hi] == sq]
frames = []
for f in sorted(set(frame_all[g_s].tolist()) | set(frame_all[h_s].tolist())):
g_f = g_s[frame_all[g_s] == f]
h_f = h_s[frame_all[h_s] == f]
frames.append({"frame": f, "gt_ids": [f"{sq}\x1f{truth_all[i]}" for i in g_f], "gt_boxes": box[g_f],
"hyp_ids": [hyp_id[int(i)] for i in h_f], "hyp_boxes": box[h_f]})
seqs.append(frames)
metrics = mot.clear_mot(seqs, MOT_IOU)
switch_events = metrics["switch_events"]
# %% Assumptions
assumptions = [
{"key": "frames", "label": "Frames are in order", "status": "info",
"detail": "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."},
{"key": "motion", "label": "Objects move smoothly", "status": "info",
"detail": "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks."},
]
if FEATURES:
assumptions.append({"key": "appearance", "label": "Embeddings describe appearance", "status": "info",
"detail": "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close."})
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
labels_seen = sorted(set(t["label"] for t in tracks if t["label"] is not None))
seq_list = sorted(set(seq_all[di].tolist()))
n_frames = len(set(zip(seq_all[di].tolist(), frame_all[di].tolist())))
values = {"association": MODE, "n_sequences": len(seq_list), "n_frames": n_frames, "n_detections": int(di.size), "n_tracks": n_tracks,
"n_assigned": n_assigned, "n_unassigned": int(di.size - n_assigned),
"mean_track_length": float(np.mean([t["n_detections"] for t in tracks])) if tracks else None,
"mota": None, "motp": None, "idf1": None, "idp": None, "idr": None, "id_switches": None, "fragmentations": None,
"false_positives": None, "misses": None, "mostly_tracked": None, "partially_tracked": None, "mostly_lost": None,
"precision": None, "recall": None, "n_gt_tracks": None, "n_gt_boxes": None, "track_id": track_id}
for lab in labels_seen:
values[f"tracks[{lab}]"] = sum(1 for t in tracks if t["label"] == lab)
if metrics is not None:
values.update({"mota": metrics["mota"], "motp": metrics["motp"], "idf1": metrics["idf1"], "idp": metrics["idp"], "idr": metrics["idr"],
"id_switches": metrics["switches"], "fragmentations": metrics["fragmentations"], "false_positives": metrics["false_positives"],
"misses": metrics["misses"], "mostly_tracked": metrics["mostly_tracked"], "partially_tracked": metrics["partially_tracked"],
"mostly_lost": metrics["mostly_lost"], "precision": metrics["precision"], "recall": metrics["recall"],
"n_gt_tracks": metrics["n_gt_tracks"], "n_gt_boxes": metrics["objects"]})
trk_rows = [{"track_id": t["track_id"], "sequence": t["sequence"], "label": t["label"], "first_frame": t["first_frame"], "last_frame": t["last_frame"],
"span": t["last_frame"] - t["first_frame"] + 1.0, "n_detections": t["n_detections"], "mean_score": t["mean_score"]} for t in tracks]
tables = [{"key": "tracks", "title": "Tracks",
"columns": [{"key": "track_id", "label": "Track", "type": "integer"}, {"key": "sequence", "label": SEQ, "type": "string"}]
+ ([{"key": "label", "label": LABEL, "type": "string"}] if LABEL else [])
+ [{"key": "first_frame", "label": "First frame", "type": "number"}, {"key": "last_frame", "label": "Last frame", "type": "number"},
{"key": "span", "label": "Frames spanned", "type": "number"}, {"key": "n_detections", "label": "Detections", "type": "integer"}]
+ ([{"key": "mean_score", "label": "Mean score", "type": "number"}] if SCORE else []),
"rows": trk_rows[:500], "note": "First 500 tracks." if len(trk_rows) > 500 else None}]
if metrics is not None:
mrows = [("MOTA", metrics["mota"], "1 − (misses + false positives + identity switches) / reference boxes"),
("IDF1", metrics["idf1"], "Share of boxes on the right identity (global track matching)"),
("MOTP (mean IoU)", metrics["motp"], "Mean overlap of the paired boxes"),
("Identity switches", metrics["switches"], "A reference object took a different track"),
("Fragmentations", metrics["fragmentations"], "A tracked object was lost and found again"),
("Misses", metrics["misses"], "Reference boxes with no track"), ("False positives", metrics["false_positives"], "Tracked boxes with no reference object"),
("Mostly tracked", metrics["mostly_tracked"], "Reference tracks paired in at least 80% of their frames"),
("Mostly lost", metrics["mostly_lost"], "Reference tracks paired in under 20% of their frames")]
tables.append({"key": "mot", "title": f"Against the reference tracks (IoU ≥ {MOT_IOU:g})",
"columns": [{"key": "metric", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "meaning", "label": "Meaning", "type": "string"}],
"rows": [{"metric": a, "value": b, "meaning": c} for a, b, c in mrows]})
if switch_events:
tables.append({"key": "switches", "title": "Identity switches",
"columns": [{"key": "sequence", "label": SEQ, "type": "string"}, {"key": "frame", "label": "Frame", "type": "number"},
{"key": "object", "label": "Reference object", "type": "string"}, {"key": "from", "label": "From track", "type": "string"},
{"key": "to", "label": "To track", "type": "string"}],
"rows": [{"sequence": e["object"].split("\x1f")[0], "frame": e["frame"], "object": e["object"].split("\x1f")[1],
"from": e["from"], "to": e["to"]} for e in switch_events[:200]],
"note": "First 200 switches." if len(switch_events) > 200 else None})
charts = []
if tracks:
lane_of = {t["track_id"]: f"{t['track_id']}" + (f" · {t['label']}" if t["label"] is not None else "") for t in tracks}
shown = tracks[:60]
ln, s0, s1, col, ev = [], [], [], [], []
for t in shown:
fr = np.sort(frame_all[di][tid_det == t["track_id"]])
brk = np.flatnonzero(np.diff(fr) > 1.0)
starts = np.concatenate([[fr[0]], fr[brk + 1]])
ends = np.concatenate([fr[brk], [fr[-1]]])
for a, b in zip(starts, ends):
ln.append(lane_of[t["track_id"]])
s0.append(float(a))
s1.append(float(b))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append(None)
shown_ids = {t["track_id"] for t in shown}
for e in switch_events:
if int(e["to"]) in shown_ids:
t = next(x for x in shown if x["track_id"] == int(e["to"]))
ln.append(lane_of[t["track_id"]])
s0.append(float(e["frame"]))
s1.append(float(e["frame"]))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append("Identity switch")
roles = {"lane": cs.col("Track", ln, "categorical", levels=[lane_of[t["track_id"]] for t in shown]),
"start": cs.col(FRAME, s0, "numeric"), "end": cs.col("Last frame", s1, "numeric"),
"color": cs.col(SEQ if len(seq_list) > 1 else (LABEL or SEQ), col, "categorical")}
if any(v is not None for v in ev):
roles["event"] = cs.col("Event", ev, "categorical")
charts.append(cs.chart("timeline", "track-timeline", "When each track was seen", roles,
note=("The first 60 tracks. " if len(tracks) > 60 else "") + "Bars break where a track missed more than one frame."))
out = csml.out_dir("target/academy-parity/run-8142/track.objects/sort-with-reference/out-python")
labels_path = os.path.join(out, "labels.parquet")
pd.DataFrame({"row": np.arange(n_input, dtype=np.int64), "cluster": np.asarray([-1 if v is None else v for v in track_id], dtype=np.int64)}).to_parquet(labels_path, index=False)
summary = (f"{n_tracks} track{'s' if n_tracks != 1 else ''} from {int(di.size)} detections in {len(seq_list)} sequence{'s' if len(seq_list) != 1 else ''} "
f"({ {'sort': 'SORT', 'bytetrack': 'ByteTrack', 'deepsort': 'DeepSORT-style'}[MODE] } association); {n_assigned} detections joined a track.")
if metrics is not None:
summary += (f" Against {metrics['n_gt_tracks']} reference tracks: MOTA {f3(metrics['mota'])}, IDF1 {f3(metrics['idf1'])}, "
f"{metrics['switches']} identity switches.")
cs.publish({
"method": "track.objects",
"methodVersion": "1.1.1",
"title": "Object tracks",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "n_tracks", "label": "Tracks", "value": n_tracks}]
+ ([{"key": "mota", "label": "MOTA", "value": metrics["mota"]}, {"key": "idf1", "label": "IDF1", "value": metrics["idf1"]},
{"key": "id_switches", "label": "Identity switches", "value": metrics["switches"]}] if metrics is not None else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Tracks start from detections and are confirmed after {OPTS['min_hits']} detections; a confirmed track ends after {OPTS['max_age']:g} frames without one. "
+ ("Boxes pair only within the same class. " if (LABEL and OPTS["per_class"]) else "")
+ "Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers)."],
"charts": charts,
"artifacts": [{"key": "labels", "path": labels_path, "format": "parquet"}],
"values": values,
})
SORT on two cameras
ReadSORT formed 7 tracks from 184 detections. The timeline shows each track's lane; gaps are frames where the detector missed the object and the track coasted on its prediction.
Predict first
Raising "Detections to confirm a track" from 3 to 10, what happens to the number of tracks?
Reveal
Fewer tracks. Short-lived tracks — usually false detections — never reach 10 detections and get no id. Set it too high and real objects seen briefly disappear too.
Scoring against reference tracks
ReadWith labeled tracks (each reference box carries its true object id, in the same table or in one chosen under Reference table), tracked boxes are paired with reference boxes frame by frame at IoU ≥ 0.5:
- MOTAMOTA (multiple object tracking accuracy)1 − (missed boxes + false boxes + identity switches) / reference boxes; 1 is perfect and it can fall below 0. = 1 − (missed + false + identity switches) / reference boxes. Here MOTA = 0.886.
- IDF1IDF1 (identity F1)Share of boxes on the right identity after matching whole tracks to whole objects; F1 of identity precision and recall. matches whole tracks to whole objects and asks how many boxes kept the right identity: 0.939.
- An identity switchIdentity switch and fragmentationA switch: an object moves onto another track. A fragmentation: a track loses its object for a while and finds it again. is an object moving onto another track; a fragmentation is a track losing its object and finding it again (20 here).
- Mostly trackedMostly tracked, partially tracked, mostly lostReference objects followed in at least 80%, 20–80% or under 20% of the frames they appear in. objects are followed in at least 80% of their frames.
Label every scored frame: on a frame without reference boxes, each tracked box counts as a false positive.
ByteTrack on the same detections
Read7 tracks from 184 detections in 2 sequences (ByteTrack association); 164 detections joined a track. Against 7 reference tracks: MOTA 0.816, IDF1 0.899, 0 identity switches.
- Tracks
- 7
- MOTA
- 0.8159
- IDF1
- 0.8986
- Identity switches
- 0
Plots
Bars break where a track missed more than one frame.
View data
| media_id | Last frame | Track | frame |
|---|---|---|---|
| cam1 | 5 | 1 · person | 0 |
| cam1 | 11 | 1 · person | 7 |
| cam1 | 15 | 1 · person | 14 |
| cam1 | 22 | 1 · person | 17 |
| cam1 | 34 | 1 · person | 29 |
| cam1 | 39 | 1 · person | 36 |
| cam1 | 3 | 2 · person | 0 |
| cam1 | 6 | 2 · person | 5 |
| cam1 | 22 | 2 · person | 8 |
| cam1 | 36 | 2 · person | 29 |
| cam1 | 39 | 2 · person | 38 |
| cam1 | 29 | 3 · car | 7 |
| cam1 | 21 | 4 · person | 18 |
| cam1 | 25 | 4 · person | 23 |
| cam1 | 30 | 4 · person | 27 |
| cam1 | 39 | 4 · person | 32 |
| cam2 | 10 | 5 · car | 3 |
| cam2 | 13 | 5 · car | 12 |
| cam2 | 17 | 5 · car | 15 |
| cam2 | 23 | 5 · car | 20 |
| cam2 | 25 | 5 · car | 25 |
| cam2 | 29 | 5 · car | 27 |
| cam2 | 23 | 6 · person | 3 |
| cam2 | 25 | 6 · person | 25 |
| cam2 | 29 | 6 · person | 27 |
| cam2 | 25 | 7 · person | 10 |
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections | Mean score |
|---|---|---|---|---|---|---|---|
| 1 | cam1 | person | 0 | 39 | 40 | 29 | 0.7782 |
| 2 | cam1 | person | 0 | 39 | 40 | 31 | 0.7869 |
| 3 | cam1 | car | 7 | 29 | 23 | 23 | 0.7908 |
| 4 | cam1 | person | 18 | 39 | 22 | 19 | 0.8095 |
| 5 | cam2 | car | 3 | 29 | 27 | 21 | 0.7143 |
| 6 | cam2 | person | 3 | 29 | 27 | 25 | 0.7759 |
| 7 | cam2 | person | 10 | 25 | 16 | 16 | 0.8254 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 0.8159 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 0.8986 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 0.8805 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 19 | A tracked object was lost and found again |
| Misses | 37 | Reference boxes with no track |
| False positives | 0 | Tracked boxes with no reference object |
| Mostly tracked | 4 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Boxes pair only within the same class. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact R script · R R version 4.5.1 (2025-06-13)
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec c7e4ef13684aef6c
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_track_objects (tracker), cs_eval_mot (tracking metrics), cs_eval_stacked
# %% Data
SEQ <- "media_id"; FRAME <- "frame"
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
SCORE <- "score"
LABEL <- "label"
FEATURES <- c()
SOURCE <- "source"
TRUTH <- "track_id"
MODE <- "bytetrack" # sort | bytetrack | deepsort
OPTS <- list(iou = 0.3, min_hits = as.integer(3), max_age = as.numeric(30),
min_score = 0, high = 0.6, low = 0.1,
low_iou = 0.5, max_cosine = 0.3, motion_weight = 0,
per_class = TRUE)
MOT_IOU <- 0.5
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction") # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
FEATURES <- if (length(FEATURES)) as.character(FEATURES) else character(0)
columns <- unique(c(SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH, FEATURES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_tracks.parquet", col_select = columns))
df$`__row` <- seq_len(nrow(df)) - 1L # position in the analysis input
n_input <- nrow(df)
if (MODE == "bytetrack" && is.null(SCORE)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or DeepSORT-style unless a confidence score column is set", value = "ByteTrack")
if (MODE == "deepsort" && !length(FEATURES)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or ByteTrack unless embedding columns are set", value = "DeepSORT-style")
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
# The reference table's rows go above the detections under an added source column (twin: with_reference).
w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/track.objects/bytetrack-with-reference/out-r", "reference_table"),
list(sequence = SEQ, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, score = SCORE, label = LABEL, truth = TRUTH),
REF_ROLES, list(label = "Class"), SOURCE, REF_LEVEL, c("sequence", "frame", "x0", "y0", "x1", "y1", if (!is.null(LABEL)) "label"))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
SEQ <- wc$sequence; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
LABEL <- wc$label; TRUTH <- wc$truth
SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
}
needed <- c(SEQ, FRAME, X0, Y0, X1, Y1, LABEL)
numeric_cols <- c(FRAME, X0, Y0, X1, Y1, SCORE, FEATURES)
if (!is.null(SOURCE)) {
st <- cs_eval_stacked(df, c(needed, SOURCE), numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
} else {
if (n_input == 0L) cs_error("CS_E_NO_ROWS")
for (c in needed) if (all(is.na(df[[c]]))) cs_error("CS_E_ALL_MISSING", column = c)
keep <- rep(TRUE, n_input)
for (c in needed) keep <- keep & !is.na(df[[c]])
df <- df[keep, , drop = FALSE]
warnings <- if (nrow(df) < n_input) list(cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input)) else list()
if (nrow(df) == 0L) cs_error("CS_E_NO_ROWS")
for (c in numeric_cols) {
k <- sum(is.infinite(as.numeric(df[[c]])))
if (k > 0) cs_error("CS_E_NOT_FINITE", column = c, count = k)
}
is_ref <- logical(nrow(df))
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
det <- !is_ref
if (!is.null(SCORE)) {
no_score <- det & is.na(as.numeric(df[[SCORE]]))
if (any(no_score)) {
warnings <- c(warnings, sprintf("%d detections have no %s and were left out.", sum(no_score), SCORE))
det <- det & !no_score
}
}
if (length(FEATURES)) {
no_feat <- det & !stats::complete.cases(df[FEATURES])
if (any(no_feat)) {
warnings <- c(warnings, sprintf("%d detections miss an embedding value and were left out.", sum(no_feat)))
det <- det & !no_feat
}
}
if (sum(det) < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Tracking", min = 2, n = sum(det))
# %% Tracks
di <- which(det)
seq_all <- as.character(df[[SEQ]])
frame_all <- as.numeric(df[[FRAME]])
lab_all <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
feats <- if (length(FEATURES)) as.matrix(df[di, FEATURES, drop = FALSE]) else NULL
if (!is.null(feats)) storage.mode(feats) <- "double"
res <- cs_track_objects(seq_all[di], frame_all[di], box[di, , drop = FALSE], if (!is.null(SCORE)) as.numeric(df[[SCORE]])[di] else NULL,
if (!is.null(LABEL)) lab_all[di] else NULL, feats, MODE, OPTS)
tid_det <- res$track
track_id <- rep(NA_integer_, n_input) # per input row; rows that weren't tracked stay empty
track_id[df$`__row`[di][tid_det > 0L] + 1L] <- tid_det[tid_det > 0L]
tracks <- res$tracks
n_tracks <- length(tracks)
n_assigned <- sum(tid_det > 0L)
# %% Against the reference tracks
metrics <- NULL
switch_events <- list()
if (!is.null(SOURCE) && !is.null(TRUTH) && sum(is_ref) > 0) {
truth_ok <- is_ref & !is.na(df[[TRUTH]])
if (sum(is_ref & !truth_ok) > 0) warnings <- c(warnings, sprintf("%d reference boxes have no %s and were left out of the tracking metrics.", sum(is_ref & !truth_ok), TRUTH))
truth_all <- as.character(df[[TRUTH]])
gi <- which(truth_ok)
hi <- di[tid_det > 0L]
hyp_of <- integer(nrow(df))
hyp_of[di] <- tid_det
seqs <- list()
for (sq in sort(unique(c(seq_all[gi], seq_all[hi])), method = "radix")) {
g_s <- gi[seq_all[gi] == sq]
h_s <- hi[seq_all[hi] == sq]
frames <- list()
for (f in sort(unique(c(frame_all[g_s], frame_all[h_s])))) {
g_f <- g_s[frame_all[g_s] == f]
h_f <- h_s[frame_all[h_s] == f]
# paste() would recycle an empty id vector into one id: frames with predictions but no reference boxes get none.
gt_ids <- if (length(g_f)) paste(sq, truth_all[g_f], sep = "\u001f") else character(0)
frames[[length(frames) + 1L]] <- list(frame = f, gt_ids = gt_ids, gt_boxes = box[g_f, , drop = FALSE],
hyp_ids = as.character(hyp_of[h_f]), hyp_boxes = box[h_f, , drop = FALSE])
}
seqs[[length(seqs) + 1L]] <- frames
}
metrics <- cs_eval_mot(seqs, MOT_IOU)
switch_events <- metrics$switch_events
}
# %% Assumptions
assumptions <- list(
list(key = "frames", label = "Frames are in order", status = "info",
detail = "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."),
list(key = "motion", label = "Objects move smoothly", status = "info",
detail = "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.")
)
if (length(FEATURES)) assumptions[[3]] <- list(key = "appearance", label = "Embeddings describe appearance", status = "info",
detail = "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close.")
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tl <- vapply(tracks, function(t) if (is.na(t$label)) NA_character_ else t$label, character(1))
labels_seen <- sort(unique(tl[!is.na(tl)]), method = "radix")
seq_list <- sort(unique(seq_all[di]), method = "radix")
n_frames <- sum(!duplicated(paste(seq_all[di], sprintf("%.17g", frame_all[di]), sep = "\u001f")))
nz <- function(v) if (is.null(v)) NA_real_ else v
values <- list(association = MODE, n_sequences = length(seq_list), n_frames = n_frames, n_detections = length(di), n_tracks = n_tracks,
n_assigned = n_assigned, n_unassigned = length(di) - n_assigned,
mean_track_length = if (n_tracks) mean(vapply(tracks, function(t) t$n_detections, numeric(1))) else NA_real_,
mota = NA_real_, motp = NA_real_, idf1 = NA_real_, idp = NA_real_, idr = NA_real_, id_switches = NA_real_, fragmentations = NA_real_,
false_positives = NA_real_, misses = NA_real_, mostly_tracked = NA_real_, partially_tracked = NA_real_, mostly_lost = NA_real_,
precision = NA_real_, recall = NA_real_, n_gt_tracks = NA_real_, n_gt_boxes = NA_real_, track_id = I(track_id))
for (lab in labels_seen) values[[sprintf("tracks[%s]", lab)]] <- sum(tl == lab, na.rm = TRUE)
if (!is.null(metrics)) {
values$mota <- metrics$mota; values$motp <- metrics$motp; values$idf1 <- metrics$idf1; values$idp <- metrics$idp; values$idr <- metrics$idr
values$id_switches <- metrics$switches; values$fragmentations <- metrics$fragmentations; values$false_positives <- metrics$false_positives
values$misses <- metrics$misses; values$mostly_tracked <- metrics$mostly_tracked; values$partially_tracked <- metrics$partially_tracked
values$mostly_lost <- metrics$mostly_lost; values$precision <- metrics$precision; values$recall <- metrics$recall
values$n_gt_tracks <- metrics$n_gt_tracks; values$n_gt_boxes <- metrics$objects
}
trk_rows <- lapply(tracks, function(t) list(track_id = t$track_id, sequence = t$sequence, label = t$label, first_frame = t$first_frame,
last_frame = t$last_frame, span = t$last_frame - t$first_frame + 1, n_detections = t$n_detections,
mean_score = t$mean_score))
tcols <- c(list(list(key = "track_id", label = "Track", type = "integer"), list(key = "sequence", label = SEQ, type = "string")),
if (!is.null(LABEL)) list(list(key = "label", label = LABEL, type = "string")),
list(list(key = "first_frame", label = "First frame", type = "number"), list(key = "last_frame", label = "Last frame", type = "number"),
list(key = "span", label = "Frames spanned", type = "number"), list(key = "n_detections", label = "Detections", type = "integer")),
if (!is.null(SCORE)) list(list(key = "mean_score", label = "Mean score", type = "number")))
tables <- list(list(key = "tracks", title = "Tracks", columns = tcols, rows = utils::head(trk_rows, 500),
note = if (length(trk_rows) > 500) "First 500 tracks." else NULL))
if (!is.null(metrics)) {
mrows <- list(list("MOTA", metrics$mota, "1 − (misses + false positives + identity switches) / reference boxes"),
list("IDF1", metrics$idf1, "Share of boxes on the right identity (global track matching)"),
list("MOTP (mean IoU)", metrics$motp, "Mean overlap of the paired boxes"),
list("Identity switches", metrics$switches, "A reference object took a different track"),
list("Fragmentations", metrics$fragmentations, "A tracked object was lost and found again"),
list("Misses", metrics$misses, "Reference boxes with no track"), list("False positives", metrics$false_positives, "Tracked boxes with no reference object"),
list("Mostly tracked", metrics$mostly_tracked, "Reference tracks paired in at least 80% of their frames"),
list("Mostly lost", metrics$mostly_lost, "Reference tracks paired in under 20% of their frames"))
tables[[length(tables) + 1L]] <- list(key = "mot", title = sprintf("Against the reference tracks (IoU ≥ %g)", MOT_IOU),
columns = list(list(key = "metric", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "meaning", label = "Meaning", type = "string")),
rows = lapply(mrows, function(r) list(metric = r[[1]], value = r[[2]], meaning = r[[3]])))
if (length(switch_events)) {
tables[[length(tables) + 1L]] <- list(key = "switches", title = "Identity switches",
columns = list(list(key = "sequence", label = SEQ, type = "string"), list(key = "frame", label = "Frame", type = "number"),
list(key = "object", label = "Reference object", type = "string"), list(key = "from", label = "From track", type = "string"),
list(key = "to", label = "To track", type = "string")),
rows = lapply(utils::head(switch_events, 200), function(e) { p <- strsplit(e$object, "\u001f", fixed = TRUE)[[1]]
list(sequence = p[1], frame = e$frame, object = p[2], from = e$from, to = e$to) }),
note = if (length(switch_events) > 200) "First 200 switches." else NULL)
}
}
charts <- list()
if (n_tracks) {
lane_of <- function(t) paste0(t$track_id, if (!is.na(t$label)) paste0(" · ", t$label) else "")
shown <- utils::head(tracks, 60)
color_of <- function(t) if (length(seq_list) > 1L) t$sequence else if (!is.na(t$label)) t$label else t$sequence
ln <- character(0); s0 <- numeric(0); s1 <- numeric(0); col <- character(0); ev <- character(0)
fr_det <- frame_all[di]
for (t in shown) {
fr <- sort(fr_det[tid_det == t$track_id])
brk <- which(diff(fr) > 1)
starts <- c(fr[1], fr[brk + 1L])
ends <- c(fr[brk], fr[length(fr)])
ln <- c(ln, rep(lane_of(t), length(starts))); s0 <- c(s0, starts); s1 <- c(s1, ends)
col <- c(col, rep(color_of(t), length(starts))); ev <- c(ev, rep(NA_character_, length(starts)))
}
shown_ids <- vapply(shown, function(t) t$track_id, numeric(1))
for (e in switch_events) {
to <- as.integer(e$to)
if (to %in% shown_ids) {
t <- shown[[which(shown_ids == to)[1]]]
ln <- c(ln, lane_of(t)); s0 <- c(s0, e$frame); s1 <- c(s1, e$frame); col <- c(col, color_of(t)); ev <- c(ev, "Identity switch")
}
}
roles <- list(lane = cs_col("Track", ln, "categorical", levels = vapply(shown, lane_of, character(1))),
start = cs_col(FRAME, s0, "numeric"), end = cs_col("Last frame", s1, "numeric"),
color = cs_col(if (length(seq_list) > 1L) SEQ else if (!is.null(LABEL)) LABEL else SEQ, col, "categorical"))
if (any(!is.na(ev))) roles$event <- cs_col("Event", ev, "categorical")
charts[[1]] <- cs_chart("timeline", "track-timeline", "When each track was seen", roles,
note = paste0(if (n_tracks > 60) "The first 60 tracks. " else "", "Bars break where a track missed more than one frame."))
}
out <- cs_ml_out_dir("target/academy-parity/run-8142/track.objects/bytetrack-with-reference/out-r")
labels_path <- file.path(out, "labels.parquet")
nanoparquet::write_parquet(data.frame(row = as.numeric(seq_len(n_input) - 1L), cluster = as.numeric(ifelse(is.na(track_id), -1L, track_id))), labels_path)
names_mode <- c(sort = "SORT", bytetrack = "ByteTrack", deepsort = "DeepSORT-style")
summary <- sprintf("%d track%s from %d detections in %d sequence%s (%s association); %d detections joined a track.", n_tracks, if (n_tracks != 1) "s" else "",
length(di), length(seq_list), if (length(seq_list) != 1) "s" else "", names_mode[[MODE]], n_assigned)
if (!is.null(metrics)) summary <- paste0(summary, sprintf(" Against %d reference tracks: MOTA %s, IDF1 %s, %d identity switches.", as.integer(metrics$n_gt_tracks),
f3(metrics$mota), f3(metrics$idf1), as.integer(metrics$switches)))
cs_publish(list(
method = "track.objects",
methodVersion = "1.1.1",
title = "Object tracks",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = c(list(list(key = "n_tracks", label = "Tracks", value = n_tracks)),
if (!is.null(metrics)) list(list(key = "mota", label = "MOTA", value = metrics$mota), list(key = "idf1", label = "IDF1", value = metrics$idf1),
list(key = "id_switches", label = "Identity switches", value = metrics$switches))),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Tracks start from detections and are confirmed after %d detections; a confirmed track ends after %g frames without one. ", OPTS$min_hits, OPTS$max_age),
if (!is.null(LABEL) && OPTS$per_class) "Boxes pair only within the same class. " else "",
"Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).")),
charts = charts,
artifacts = list(list(key = "labels", path = labels_path, format = "parquet")),
values = values
))
7 tracks from 184 detections in 2 sequences (ByteTrack association); 164 detections joined a track. Against 7 reference tracks: MOTA 0.816, IDF1 0.899, 0 identity switches.
- Tracks
- 7
- MOTA
- 0.8159
- IDF1
- 0.8986
- Identity switches
- 0
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections | Mean score |
|---|---|---|---|---|---|---|---|
| 1 | cam1 | person | 0 | 39 | 40 | 29 | 0.7782 |
| 2 | cam1 | person | 0 | 39 | 40 | 31 | 0.7869 |
| 3 | cam1 | car | 7 | 29 | 23 | 23 | 0.7908 |
| 4 | cam1 | person | 18 | 39 | 22 | 19 | 0.8095 |
| 5 | cam2 | car | 3 | 29 | 27 | 21 | 0.7143 |
| 6 | cam2 | person | 3 | 29 | 27 | 25 | 0.7759 |
| 7 | cam2 | person | 10 | 25 | 16 | 16 | 0.8254 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 0.8159 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 0.8986 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 0.8805 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 19 | A tracked object was lost and found again |
| Misses | 37 | Reference boxes with no track |
| False positives | 0 | Tracked boxes with no reference object |
| Mostly tracked | 4 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Boxes pair only within the same class. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec c7e4ef13684aef6c
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.evaluate import mot # twin: codesplashr cs_eval_mot
from codesplash.evaluate.stacked import stacked # twin: cs_eval_stacked
from codesplash import ml as csml
from codesplash.track import objects as tr # twin: codesplashr cs_track_objects
# %% Data
SEQ, FRAME = "media_id", "frame"
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
SCORE = "score"
LABEL = "label"
FEATURES = []
SOURCE = "source"
TRUTH = "track_id"
MODE = "bytetrack" # sort | bytetrack | deepsort
OPTS = {"iou": 0.3, "min_hits": int(3), "max_age": float(30),
"min_score": 0, "high": 0.6, "low": 0.1,
"low_iou": 0.5, "max_cosine": 0.3, "motion_weight": 0,
"per_class": True}
MOT_IOU = 0.5
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"] # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH] + FEATURES if c))
df = pd.read_parquet("tests/parity/fixtures/img4_tracks.parquet", columns=columns)
df["__row"] = np.arange(len(df)) # position in the analysis input
n_input = len(df)
if MODE == "bytetrack" and not SCORE:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or DeepSORT-style unless a confidence score column is set", value="ByteTrack")
if MODE == "deepsort" and not FEATURES:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or ByteTrack unless embedding columns are set", value="DeepSORT-style")
pre_warnings = []
if REF_ROLES is not None:
# The reference table's rows go above the detections under an added source column (twin: cs_eval_with_reference).
from codesplash.graph import dataset_option # the table the host wrote for the option
from codesplash.evaluate.stacked import with_reference
w = with_reference(df, dataset_option("target/academy-parity/run-8142/track.objects/bytetrack-with-reference/out-python", "reference_table"),
{"sequence": SEQ, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "score": SCORE, "label": LABEL, "truth": TRUTH},
REF_ROLES, {"label": "Class"}, SOURCE, REF_LEVEL, ["sequence", "frame", "x0", "y0", "x1", "y1"] + (["label"] if LABEL else []))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
SEQ, FRAME, X0, Y0, X1, Y1 = wc["sequence"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
LABEL, TRUTH = wc["label"], wc["truth"]
SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
needed = [SEQ, FRAME, X0, Y0, X1, Y1] + ([LABEL] if LABEL else [])
numeric = [c for c in [FRAME, X0, Y0, X1, Y1, SCORE] if c] + FEATURES
if SOURCE:
st = stacked(df, needed + [SOURCE], numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
else:
if n_input == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in needed:
if df[c].isna().all():
cs.cs_error("CS_E_ALL_MISSING", column=c)
keep = np.ones(n_input, dtype=bool)
for c in needed:
keep &= df[c].notna().to_numpy()
df = df.loc[keep].reset_index(drop=True)
warnings = [cs.cs_warning("CS_W_ROWS_DROPPED", dropped=int(n_input - len(df)), total=n_input)] if len(df) < n_input else []
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in numeric:
k = int(np.isinf(df[c].to_numpy(dtype=float, na_value=np.nan)).sum())
if k:
cs.cs_error("CS_E_NOT_FINITE", column=c, count=k)
is_ref = np.zeros(len(df), dtype=bool)
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
det = ~is_ref
if SCORE:
no_score = det & np.isnan(df[SCORE].to_numpy(dtype=float, na_value=np.nan))
if no_score.any():
warnings.append(f"{int(no_score.sum())} detections have no {SCORE} and were left out.")
det &= ~no_score
if FEATURES:
no_feat = det & df[FEATURES].isna().any(axis=1).to_numpy()
if no_feat.any():
warnings.append(f"{int(no_feat.sum())} detections miss an embedding value and were left out.")
det &= ~no_feat
if int(det.sum()) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Tracking", min=2, n=int(det.sum()))
# %% Tracks
di = np.flatnonzero(det)
seq_all = np.asarray([str(x) for x in df[SEQ].tolist()], dtype=object)
frame_all = df[FRAME].to_numpy(dtype=float)
lab_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object) if LABEL else None
res = tr.track(seq_all[di], frame_all[di], box[di], df[SCORE].to_numpy(dtype=float)[di] if SCORE else None,
lab_all[di] if LABEL else None, df[FEATURES].to_numpy(dtype=float)[di] if FEATURES else None, MODE, **OPTS)
tid_det = res["track"]
track_id = [None] * n_input # per input row; rows that weren't tracked stay empty
for k, i in enumerate(di):
if tid_det[k] > 0:
track_id[int(df["__row"].iloc[i])] = int(tid_det[k])
tracks = res["tracks"]
n_tracks = len(tracks)
n_assigned = int(np.sum(tid_det > 0))
# %% Against the reference tracks
metrics = None
switch_events = []
if SOURCE and TRUTH and int(is_ref.sum()):
truth_ok = is_ref & df[TRUTH].notna().to_numpy()
if int((is_ref & ~truth_ok).sum()):
warnings.append(f"{int((is_ref & ~truth_ok).sum())} reference boxes have no {TRUTH} and were left out of the tracking metrics.")
truth_all = np.asarray([str(x) for x in df[TRUTH].tolist()], dtype=object)
gi = np.flatnonzero(truth_ok)
hi = di[tid_det > 0]
hyp_id = {int(i): str(int(t)) for i, t in zip(di, tid_det) if t > 0}
seqs = []
for sq in sorted(set(seq_all[gi].tolist()) | set(seq_all[hi].tolist())):
g_s = gi[seq_all[gi] == sq]
h_s = hi[seq_all[hi] == sq]
frames = []
for f in sorted(set(frame_all[g_s].tolist()) | set(frame_all[h_s].tolist())):
g_f = g_s[frame_all[g_s] == f]
h_f = h_s[frame_all[h_s] == f]
frames.append({"frame": f, "gt_ids": [f"{sq}\x1f{truth_all[i]}" for i in g_f], "gt_boxes": box[g_f],
"hyp_ids": [hyp_id[int(i)] for i in h_f], "hyp_boxes": box[h_f]})
seqs.append(frames)
metrics = mot.clear_mot(seqs, MOT_IOU)
switch_events = metrics["switch_events"]
# %% Assumptions
assumptions = [
{"key": "frames", "label": "Frames are in order", "status": "info",
"detail": "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."},
{"key": "motion", "label": "Objects move smoothly", "status": "info",
"detail": "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks."},
]
if FEATURES:
assumptions.append({"key": "appearance", "label": "Embeddings describe appearance", "status": "info",
"detail": "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close."})
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
labels_seen = sorted(set(t["label"] for t in tracks if t["label"] is not None))
seq_list = sorted(set(seq_all[di].tolist()))
n_frames = len(set(zip(seq_all[di].tolist(), frame_all[di].tolist())))
values = {"association": MODE, "n_sequences": len(seq_list), "n_frames": n_frames, "n_detections": int(di.size), "n_tracks": n_tracks,
"n_assigned": n_assigned, "n_unassigned": int(di.size - n_assigned),
"mean_track_length": float(np.mean([t["n_detections"] for t in tracks])) if tracks else None,
"mota": None, "motp": None, "idf1": None, "idp": None, "idr": None, "id_switches": None, "fragmentations": None,
"false_positives": None, "misses": None, "mostly_tracked": None, "partially_tracked": None, "mostly_lost": None,
"precision": None, "recall": None, "n_gt_tracks": None, "n_gt_boxes": None, "track_id": track_id}
for lab in labels_seen:
values[f"tracks[{lab}]"] = sum(1 for t in tracks if t["label"] == lab)
if metrics is not None:
values.update({"mota": metrics["mota"], "motp": metrics["motp"], "idf1": metrics["idf1"], "idp": metrics["idp"], "idr": metrics["idr"],
"id_switches": metrics["switches"], "fragmentations": metrics["fragmentations"], "false_positives": metrics["false_positives"],
"misses": metrics["misses"], "mostly_tracked": metrics["mostly_tracked"], "partially_tracked": metrics["partially_tracked"],
"mostly_lost": metrics["mostly_lost"], "precision": metrics["precision"], "recall": metrics["recall"],
"n_gt_tracks": metrics["n_gt_tracks"], "n_gt_boxes": metrics["objects"]})
trk_rows = [{"track_id": t["track_id"], "sequence": t["sequence"], "label": t["label"], "first_frame": t["first_frame"], "last_frame": t["last_frame"],
"span": t["last_frame"] - t["first_frame"] + 1.0, "n_detections": t["n_detections"], "mean_score": t["mean_score"]} for t in tracks]
tables = [{"key": "tracks", "title": "Tracks",
"columns": [{"key": "track_id", "label": "Track", "type": "integer"}, {"key": "sequence", "label": SEQ, "type": "string"}]
+ ([{"key": "label", "label": LABEL, "type": "string"}] if LABEL else [])
+ [{"key": "first_frame", "label": "First frame", "type": "number"}, {"key": "last_frame", "label": "Last frame", "type": "number"},
{"key": "span", "label": "Frames spanned", "type": "number"}, {"key": "n_detections", "label": "Detections", "type": "integer"}]
+ ([{"key": "mean_score", "label": "Mean score", "type": "number"}] if SCORE else []),
"rows": trk_rows[:500], "note": "First 500 tracks." if len(trk_rows) > 500 else None}]
if metrics is not None:
mrows = [("MOTA", metrics["mota"], "1 − (misses + false positives + identity switches) / reference boxes"),
("IDF1", metrics["idf1"], "Share of boxes on the right identity (global track matching)"),
("MOTP (mean IoU)", metrics["motp"], "Mean overlap of the paired boxes"),
("Identity switches", metrics["switches"], "A reference object took a different track"),
("Fragmentations", metrics["fragmentations"], "A tracked object was lost and found again"),
("Misses", metrics["misses"], "Reference boxes with no track"), ("False positives", metrics["false_positives"], "Tracked boxes with no reference object"),
("Mostly tracked", metrics["mostly_tracked"], "Reference tracks paired in at least 80% of their frames"),
("Mostly lost", metrics["mostly_lost"], "Reference tracks paired in under 20% of their frames")]
tables.append({"key": "mot", "title": f"Against the reference tracks (IoU ≥ {MOT_IOU:g})",
"columns": [{"key": "metric", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "meaning", "label": "Meaning", "type": "string"}],
"rows": [{"metric": a, "value": b, "meaning": c} for a, b, c in mrows]})
if switch_events:
tables.append({"key": "switches", "title": "Identity switches",
"columns": [{"key": "sequence", "label": SEQ, "type": "string"}, {"key": "frame", "label": "Frame", "type": "number"},
{"key": "object", "label": "Reference object", "type": "string"}, {"key": "from", "label": "From track", "type": "string"},
{"key": "to", "label": "To track", "type": "string"}],
"rows": [{"sequence": e["object"].split("\x1f")[0], "frame": e["frame"], "object": e["object"].split("\x1f")[1],
"from": e["from"], "to": e["to"]} for e in switch_events[:200]],
"note": "First 200 switches." if len(switch_events) > 200 else None})
charts = []
if tracks:
lane_of = {t["track_id"]: f"{t['track_id']}" + (f" · {t['label']}" if t["label"] is not None else "") for t in tracks}
shown = tracks[:60]
ln, s0, s1, col, ev = [], [], [], [], []
for t in shown:
fr = np.sort(frame_all[di][tid_det == t["track_id"]])
brk = np.flatnonzero(np.diff(fr) > 1.0)
starts = np.concatenate([[fr[0]], fr[brk + 1]])
ends = np.concatenate([fr[brk], [fr[-1]]])
for a, b in zip(starts, ends):
ln.append(lane_of[t["track_id"]])
s0.append(float(a))
s1.append(float(b))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append(None)
shown_ids = {t["track_id"] for t in shown}
for e in switch_events:
if int(e["to"]) in shown_ids:
t = next(x for x in shown if x["track_id"] == int(e["to"]))
ln.append(lane_of[t["track_id"]])
s0.append(float(e["frame"]))
s1.append(float(e["frame"]))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append("Identity switch")
roles = {"lane": cs.col("Track", ln, "categorical", levels=[lane_of[t["track_id"]] for t in shown]),
"start": cs.col(FRAME, s0, "numeric"), "end": cs.col("Last frame", s1, "numeric"),
"color": cs.col(SEQ if len(seq_list) > 1 else (LABEL or SEQ), col, "categorical")}
if any(v is not None for v in ev):
roles["event"] = cs.col("Event", ev, "categorical")
charts.append(cs.chart("timeline", "track-timeline", "When each track was seen", roles,
note=("The first 60 tracks. " if len(tracks) > 60 else "") + "Bars break where a track missed more than one frame."))
out = csml.out_dir("target/academy-parity/run-8142/track.objects/bytetrack-with-reference/out-python")
labels_path = os.path.join(out, "labels.parquet")
pd.DataFrame({"row": np.arange(n_input, dtype=np.int64), "cluster": np.asarray([-1 if v is None else v for v in track_id], dtype=np.int64)}).to_parquet(labels_path, index=False)
summary = (f"{n_tracks} track{'s' if n_tracks != 1 else ''} from {int(di.size)} detections in {len(seq_list)} sequence{'s' if len(seq_list) != 1 else ''} "
f"({ {'sort': 'SORT', 'bytetrack': 'ByteTrack', 'deepsort': 'DeepSORT-style'}[MODE] } association); {n_assigned} detections joined a track.")
if metrics is not None:
summary += (f" Against {metrics['n_gt_tracks']} reference tracks: MOTA {f3(metrics['mota'])}, IDF1 {f3(metrics['idf1'])}, "
f"{metrics['switches']} identity switches.")
cs.publish({
"method": "track.objects",
"methodVersion": "1.1.1",
"title": "Object tracks",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "n_tracks", "label": "Tracks", "value": n_tracks}]
+ ([{"key": "mota", "label": "MOTA", "value": metrics["mota"]}, {"key": "idf1", "label": "IDF1", "value": metrics["idf1"]},
{"key": "id_switches", "label": "Identity switches", "value": metrics["switches"]}] if metrics is not None else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Tracks start from detections and are confirmed after {OPTS['min_hits']} detections; a confirmed track ends after {OPTS['max_age']:g} frames without one. "
+ ("Boxes pair only within the same class. " if (LABEL and OPTS["per_class"]) else "")
+ "Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers)."],
"charts": charts,
"artifacts": [{"key": "labels", "path": labels_path, "format": "parquet"}],
"values": values,
})
ByteTrack ignores boxes below its low score and only lets low-confidence boxes extend tracks; on these detections it reaches MOTA = 0.816. MOTA is mostly about detection errors; IDF1 is about identities. A tracker can improve one and hurt the other.
The best case
Read3 tracks from 60 detections in 1 sequence (SORT association); 60 detections joined a track. Against 3 reference tracks: MOTA 1.000, IDF1 1.000, 0 identity switches.
- Tracks
- 3
- MOTA
- 1
- IDF1
- 1
- Identity switches
- 0
Plots
Bars break where a track missed more than one frame.
View data
| label | Last frame | Track | frame |
|---|---|---|---|
| person | 19 | 1 · person | 0 |
| car | 19 | 2 · car | 0 |
| person | 19 | 3 · person | 0 |
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections |
|---|---|---|---|---|---|---|
| 1 | cam9 | person | 0 | 19 | 20 | 20 |
| 2 | cam9 | car | 0 | 19 | 20 | 20 |
| 3 | cam9 | person | 0 | 19 | 20 | 20 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 1 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 1 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 1 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 0 | A tracked object was lost and found again |
| Misses | 0 | Reference boxes with no track |
| False positives | 0 | Tracked boxes with no reference object |
| Mostly tracked | 3 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Boxes pair only within the same class. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact R script · R R version 4.5.1 (2025-06-13)
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 5ca79c9e535e861b
# Dataset: img4_tracks_perfect (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_track_objects (tracker), cs_eval_mot (tracking metrics), cs_eval_stacked
# %% Data
SEQ <- "media_id"; FRAME <- "frame"
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
SCORE <- NULL
LABEL <- "label"
FEATURES <- c()
SOURCE <- "source"
TRUTH <- "track_id"
MODE <- "sort" # sort | bytetrack | deepsort
OPTS <- list(iou = 0.3, min_hits = as.integer(3), max_age = as.numeric(30),
min_score = 0, high = 0.6, low = 0.1,
low_iou = 0.5, max_cosine = 0.3, motion_weight = 0,
per_class = TRUE)
MOT_IOU <- 0.5
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction") # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
FEATURES <- if (length(FEATURES)) as.character(FEATURES) else character(0)
columns <- unique(c(SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH, FEATURES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_tracks_perfect.parquet", col_select = columns))
df$`__row` <- seq_len(nrow(df)) - 1L # position in the analysis input
n_input <- nrow(df)
if (MODE == "bytetrack" && is.null(SCORE)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or DeepSORT-style unless a confidence score column is set", value = "ByteTrack")
if (MODE == "deepsort" && !length(FEATURES)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or ByteTrack unless embedding columns are set", value = "DeepSORT-style")
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
# The reference table's rows go above the detections under an added source column (twin: with_reference).
w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/track.objects/perfect-detections/out-r", "reference_table"),
list(sequence = SEQ, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, score = SCORE, label = LABEL, truth = TRUTH),
REF_ROLES, list(label = "Class"), SOURCE, REF_LEVEL, c("sequence", "frame", "x0", "y0", "x1", "y1", if (!is.null(LABEL)) "label"))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
SEQ <- wc$sequence; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
LABEL <- wc$label; TRUTH <- wc$truth
SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
}
needed <- c(SEQ, FRAME, X0, Y0, X1, Y1, LABEL)
numeric_cols <- c(FRAME, X0, Y0, X1, Y1, SCORE, FEATURES)
if (!is.null(SOURCE)) {
st <- cs_eval_stacked(df, c(needed, SOURCE), numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
} else {
if (n_input == 0L) cs_error("CS_E_NO_ROWS")
for (c in needed) if (all(is.na(df[[c]]))) cs_error("CS_E_ALL_MISSING", column = c)
keep <- rep(TRUE, n_input)
for (c in needed) keep <- keep & !is.na(df[[c]])
df <- df[keep, , drop = FALSE]
warnings <- if (nrow(df) < n_input) list(cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input)) else list()
if (nrow(df) == 0L) cs_error("CS_E_NO_ROWS")
for (c in numeric_cols) {
k <- sum(is.infinite(as.numeric(df[[c]])))
if (k > 0) cs_error("CS_E_NOT_FINITE", column = c, count = k)
}
is_ref <- logical(nrow(df))
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
det <- !is_ref
if (!is.null(SCORE)) {
no_score <- det & is.na(as.numeric(df[[SCORE]]))
if (any(no_score)) {
warnings <- c(warnings, sprintf("%d detections have no %s and were left out.", sum(no_score), SCORE))
det <- det & !no_score
}
}
if (length(FEATURES)) {
no_feat <- det & !stats::complete.cases(df[FEATURES])
if (any(no_feat)) {
warnings <- c(warnings, sprintf("%d detections miss an embedding value and were left out.", sum(no_feat)))
det <- det & !no_feat
}
}
if (sum(det) < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Tracking", min = 2, n = sum(det))
# %% Tracks
di <- which(det)
seq_all <- as.character(df[[SEQ]])
frame_all <- as.numeric(df[[FRAME]])
lab_all <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
feats <- if (length(FEATURES)) as.matrix(df[di, FEATURES, drop = FALSE]) else NULL
if (!is.null(feats)) storage.mode(feats) <- "double"
res <- cs_track_objects(seq_all[di], frame_all[di], box[di, , drop = FALSE], if (!is.null(SCORE)) as.numeric(df[[SCORE]])[di] else NULL,
if (!is.null(LABEL)) lab_all[di] else NULL, feats, MODE, OPTS)
tid_det <- res$track
track_id <- rep(NA_integer_, n_input) # per input row; rows that weren't tracked stay empty
track_id[df$`__row`[di][tid_det > 0L] + 1L] <- tid_det[tid_det > 0L]
tracks <- res$tracks
n_tracks <- length(tracks)
n_assigned <- sum(tid_det > 0L)
# %% Against the reference tracks
metrics <- NULL
switch_events <- list()
if (!is.null(SOURCE) && !is.null(TRUTH) && sum(is_ref) > 0) {
truth_ok <- is_ref & !is.na(df[[TRUTH]])
if (sum(is_ref & !truth_ok) > 0) warnings <- c(warnings, sprintf("%d reference boxes have no %s and were left out of the tracking metrics.", sum(is_ref & !truth_ok), TRUTH))
truth_all <- as.character(df[[TRUTH]])
gi <- which(truth_ok)
hi <- di[tid_det > 0L]
hyp_of <- integer(nrow(df))
hyp_of[di] <- tid_det
seqs <- list()
for (sq in sort(unique(c(seq_all[gi], seq_all[hi])), method = "radix")) {
g_s <- gi[seq_all[gi] == sq]
h_s <- hi[seq_all[hi] == sq]
frames <- list()
for (f in sort(unique(c(frame_all[g_s], frame_all[h_s])))) {
g_f <- g_s[frame_all[g_s] == f]
h_f <- h_s[frame_all[h_s] == f]
# paste() would recycle an empty id vector into one id: frames with predictions but no reference boxes get none.
gt_ids <- if (length(g_f)) paste(sq, truth_all[g_f], sep = "\u001f") else character(0)
frames[[length(frames) + 1L]] <- list(frame = f, gt_ids = gt_ids, gt_boxes = box[g_f, , drop = FALSE],
hyp_ids = as.character(hyp_of[h_f]), hyp_boxes = box[h_f, , drop = FALSE])
}
seqs[[length(seqs) + 1L]] <- frames
}
metrics <- cs_eval_mot(seqs, MOT_IOU)
switch_events <- metrics$switch_events
}
# %% Assumptions
assumptions <- list(
list(key = "frames", label = "Frames are in order", status = "info",
detail = "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."),
list(key = "motion", label = "Objects move smoothly", status = "info",
detail = "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.")
)
if (length(FEATURES)) assumptions[[3]] <- list(key = "appearance", label = "Embeddings describe appearance", status = "info",
detail = "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close.")
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tl <- vapply(tracks, function(t) if (is.na(t$label)) NA_character_ else t$label, character(1))
labels_seen <- sort(unique(tl[!is.na(tl)]), method = "radix")
seq_list <- sort(unique(seq_all[di]), method = "radix")
n_frames <- sum(!duplicated(paste(seq_all[di], sprintf("%.17g", frame_all[di]), sep = "\u001f")))
nz <- function(v) if (is.null(v)) NA_real_ else v
values <- list(association = MODE, n_sequences = length(seq_list), n_frames = n_frames, n_detections = length(di), n_tracks = n_tracks,
n_assigned = n_assigned, n_unassigned = length(di) - n_assigned,
mean_track_length = if (n_tracks) mean(vapply(tracks, function(t) t$n_detections, numeric(1))) else NA_real_,
mota = NA_real_, motp = NA_real_, idf1 = NA_real_, idp = NA_real_, idr = NA_real_, id_switches = NA_real_, fragmentations = NA_real_,
false_positives = NA_real_, misses = NA_real_, mostly_tracked = NA_real_, partially_tracked = NA_real_, mostly_lost = NA_real_,
precision = NA_real_, recall = NA_real_, n_gt_tracks = NA_real_, n_gt_boxes = NA_real_, track_id = I(track_id))
for (lab in labels_seen) values[[sprintf("tracks[%s]", lab)]] <- sum(tl == lab, na.rm = TRUE)
if (!is.null(metrics)) {
values$mota <- metrics$mota; values$motp <- metrics$motp; values$idf1 <- metrics$idf1; values$idp <- metrics$idp; values$idr <- metrics$idr
values$id_switches <- metrics$switches; values$fragmentations <- metrics$fragmentations; values$false_positives <- metrics$false_positives
values$misses <- metrics$misses; values$mostly_tracked <- metrics$mostly_tracked; values$partially_tracked <- metrics$partially_tracked
values$mostly_lost <- metrics$mostly_lost; values$precision <- metrics$precision; values$recall <- metrics$recall
values$n_gt_tracks <- metrics$n_gt_tracks; values$n_gt_boxes <- metrics$objects
}
trk_rows <- lapply(tracks, function(t) list(track_id = t$track_id, sequence = t$sequence, label = t$label, first_frame = t$first_frame,
last_frame = t$last_frame, span = t$last_frame - t$first_frame + 1, n_detections = t$n_detections,
mean_score = t$mean_score))
tcols <- c(list(list(key = "track_id", label = "Track", type = "integer"), list(key = "sequence", label = SEQ, type = "string")),
if (!is.null(LABEL)) list(list(key = "label", label = LABEL, type = "string")),
list(list(key = "first_frame", label = "First frame", type = "number"), list(key = "last_frame", label = "Last frame", type = "number"),
list(key = "span", label = "Frames spanned", type = "number"), list(key = "n_detections", label = "Detections", type = "integer")),
if (!is.null(SCORE)) list(list(key = "mean_score", label = "Mean score", type = "number")))
tables <- list(list(key = "tracks", title = "Tracks", columns = tcols, rows = utils::head(trk_rows, 500),
note = if (length(trk_rows) > 500) "First 500 tracks." else NULL))
if (!is.null(metrics)) {
mrows <- list(list("MOTA", metrics$mota, "1 − (misses + false positives + identity switches) / reference boxes"),
list("IDF1", metrics$idf1, "Share of boxes on the right identity (global track matching)"),
list("MOTP (mean IoU)", metrics$motp, "Mean overlap of the paired boxes"),
list("Identity switches", metrics$switches, "A reference object took a different track"),
list("Fragmentations", metrics$fragmentations, "A tracked object was lost and found again"),
list("Misses", metrics$misses, "Reference boxes with no track"), list("False positives", metrics$false_positives, "Tracked boxes with no reference object"),
list("Mostly tracked", metrics$mostly_tracked, "Reference tracks paired in at least 80% of their frames"),
list("Mostly lost", metrics$mostly_lost, "Reference tracks paired in under 20% of their frames"))
tables[[length(tables) + 1L]] <- list(key = "mot", title = sprintf("Against the reference tracks (IoU ≥ %g)", MOT_IOU),
columns = list(list(key = "metric", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "meaning", label = "Meaning", type = "string")),
rows = lapply(mrows, function(r) list(metric = r[[1]], value = r[[2]], meaning = r[[3]])))
if (length(switch_events)) {
tables[[length(tables) + 1L]] <- list(key = "switches", title = "Identity switches",
columns = list(list(key = "sequence", label = SEQ, type = "string"), list(key = "frame", label = "Frame", type = "number"),
list(key = "object", label = "Reference object", type = "string"), list(key = "from", label = "From track", type = "string"),
list(key = "to", label = "To track", type = "string")),
rows = lapply(utils::head(switch_events, 200), function(e) { p <- strsplit(e$object, "\u001f", fixed = TRUE)[[1]]
list(sequence = p[1], frame = e$frame, object = p[2], from = e$from, to = e$to) }),
note = if (length(switch_events) > 200) "First 200 switches." else NULL)
}
}
charts <- list()
if (n_tracks) {
lane_of <- function(t) paste0(t$track_id, if (!is.na(t$label)) paste0(" · ", t$label) else "")
shown <- utils::head(tracks, 60)
color_of <- function(t) if (length(seq_list) > 1L) t$sequence else if (!is.na(t$label)) t$label else t$sequence
ln <- character(0); s0 <- numeric(0); s1 <- numeric(0); col <- character(0); ev <- character(0)
fr_det <- frame_all[di]
for (t in shown) {
fr <- sort(fr_det[tid_det == t$track_id])
brk <- which(diff(fr) > 1)
starts <- c(fr[1], fr[brk + 1L])
ends <- c(fr[brk], fr[length(fr)])
ln <- c(ln, rep(lane_of(t), length(starts))); s0 <- c(s0, starts); s1 <- c(s1, ends)
col <- c(col, rep(color_of(t), length(starts))); ev <- c(ev, rep(NA_character_, length(starts)))
}
shown_ids <- vapply(shown, function(t) t$track_id, numeric(1))
for (e in switch_events) {
to <- as.integer(e$to)
if (to %in% shown_ids) {
t <- shown[[which(shown_ids == to)[1]]]
ln <- c(ln, lane_of(t)); s0 <- c(s0, e$frame); s1 <- c(s1, e$frame); col <- c(col, color_of(t)); ev <- c(ev, "Identity switch")
}
}
roles <- list(lane = cs_col("Track", ln, "categorical", levels = vapply(shown, lane_of, character(1))),
start = cs_col(FRAME, s0, "numeric"), end = cs_col("Last frame", s1, "numeric"),
color = cs_col(if (length(seq_list) > 1L) SEQ else if (!is.null(LABEL)) LABEL else SEQ, col, "categorical"))
if (any(!is.na(ev))) roles$event <- cs_col("Event", ev, "categorical")
charts[[1]] <- cs_chart("timeline", "track-timeline", "When each track was seen", roles,
note = paste0(if (n_tracks > 60) "The first 60 tracks. " else "", "Bars break where a track missed more than one frame."))
}
out <- cs_ml_out_dir("target/academy-parity/run-8142/track.objects/perfect-detections/out-r")
labels_path <- file.path(out, "labels.parquet")
nanoparquet::write_parquet(data.frame(row = as.numeric(seq_len(n_input) - 1L), cluster = as.numeric(ifelse(is.na(track_id), -1L, track_id))), labels_path)
names_mode <- c(sort = "SORT", bytetrack = "ByteTrack", deepsort = "DeepSORT-style")
summary <- sprintf("%d track%s from %d detections in %d sequence%s (%s association); %d detections joined a track.", n_tracks, if (n_tracks != 1) "s" else "",
length(di), length(seq_list), if (length(seq_list) != 1) "s" else "", names_mode[[MODE]], n_assigned)
if (!is.null(metrics)) summary <- paste0(summary, sprintf(" Against %d reference tracks: MOTA %s, IDF1 %s, %d identity switches.", as.integer(metrics$n_gt_tracks),
f3(metrics$mota), f3(metrics$idf1), as.integer(metrics$switches)))
cs_publish(list(
method = "track.objects",
methodVersion = "1.1.1",
title = "Object tracks",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = c(list(list(key = "n_tracks", label = "Tracks", value = n_tracks)),
if (!is.null(metrics)) list(list(key = "mota", label = "MOTA", value = metrics$mota), list(key = "idf1", label = "IDF1", value = metrics$idf1),
list(key = "id_switches", label = "Identity switches", value = metrics$switches))),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Tracks start from detections and are confirmed after %d detections; a confirmed track ends after %g frames without one. ", OPTS$min_hits, OPTS$max_age),
if (!is.null(LABEL) && OPTS$per_class) "Boxes pair only within the same class. " else "",
"Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).")),
charts = charts,
artifacts = list(list(key = "labels", path = labels_path, format = "parquet")),
values = values
))
3 tracks from 60 detections in 1 sequence (SORT association); 60 detections joined a track. Against 3 reference tracks: MOTA 1.000, IDF1 1.000, 0 identity switches.
- Tracks
- 3
- MOTA
- 1
- IDF1
- 1
- Identity switches
- 0
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections |
|---|---|---|---|---|---|---|
| 1 | cam9 | person | 0 | 19 | 20 | 20 |
| 2 | cam9 | car | 0 | 19 | 20 | 20 |
| 3 | cam9 | person | 0 | 19 | 20 | 20 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 1 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 1 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 1 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 0 | A tracked object was lost and found again |
| Misses | 0 | Reference boxes with no track |
| False positives | 0 | Tracked boxes with no reference object |
| Mostly tracked | 3 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Boxes pair only within the same class. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 5ca79c9e535e861b
# Dataset: img4_tracks_perfect (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.evaluate import mot # twin: codesplashr cs_eval_mot
from codesplash.evaluate.stacked import stacked # twin: cs_eval_stacked
from codesplash import ml as csml
from codesplash.track import objects as tr # twin: codesplashr cs_track_objects
# %% Data
SEQ, FRAME = "media_id", "frame"
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
SCORE = None
LABEL = "label"
FEATURES = []
SOURCE = "source"
TRUTH = "track_id"
MODE = "sort" # sort | bytetrack | deepsort
OPTS = {"iou": 0.3, "min_hits": int(3), "max_age": float(30),
"min_score": 0, "high": 0.6, "low": 0.1,
"low_iou": 0.5, "max_cosine": 0.3, "motion_weight": 0,
"per_class": True}
MOT_IOU = 0.5
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"] # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH] + FEATURES if c))
df = pd.read_parquet("tests/parity/fixtures/img4_tracks_perfect.parquet", columns=columns)
df["__row"] = np.arange(len(df)) # position in the analysis input
n_input = len(df)
if MODE == "bytetrack" and not SCORE:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or DeepSORT-style unless a confidence score column is set", value="ByteTrack")
if MODE == "deepsort" and not FEATURES:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or ByteTrack unless embedding columns are set", value="DeepSORT-style")
pre_warnings = []
if REF_ROLES is not None:
# The reference table's rows go above the detections under an added source column (twin: cs_eval_with_reference).
from codesplash.graph import dataset_option # the table the host wrote for the option
from codesplash.evaluate.stacked import with_reference
w = with_reference(df, dataset_option("target/academy-parity/run-8142/track.objects/perfect-detections/out-python", "reference_table"),
{"sequence": SEQ, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "score": SCORE, "label": LABEL, "truth": TRUTH},
REF_ROLES, {"label": "Class"}, SOURCE, REF_LEVEL, ["sequence", "frame", "x0", "y0", "x1", "y1"] + (["label"] if LABEL else []))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
SEQ, FRAME, X0, Y0, X1, Y1 = wc["sequence"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
LABEL, TRUTH = wc["label"], wc["truth"]
SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
needed = [SEQ, FRAME, X0, Y0, X1, Y1] + ([LABEL] if LABEL else [])
numeric = [c for c in [FRAME, X0, Y0, X1, Y1, SCORE] if c] + FEATURES
if SOURCE:
st = stacked(df, needed + [SOURCE], numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
else:
if n_input == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in needed:
if df[c].isna().all():
cs.cs_error("CS_E_ALL_MISSING", column=c)
keep = np.ones(n_input, dtype=bool)
for c in needed:
keep &= df[c].notna().to_numpy()
df = df.loc[keep].reset_index(drop=True)
warnings = [cs.cs_warning("CS_W_ROWS_DROPPED", dropped=int(n_input - len(df)), total=n_input)] if len(df) < n_input else []
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in numeric:
k = int(np.isinf(df[c].to_numpy(dtype=float, na_value=np.nan)).sum())
if k:
cs.cs_error("CS_E_NOT_FINITE", column=c, count=k)
is_ref = np.zeros(len(df), dtype=bool)
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
det = ~is_ref
if SCORE:
no_score = det & np.isnan(df[SCORE].to_numpy(dtype=float, na_value=np.nan))
if no_score.any():
warnings.append(f"{int(no_score.sum())} detections have no {SCORE} and were left out.")
det &= ~no_score
if FEATURES:
no_feat = det & df[FEATURES].isna().any(axis=1).to_numpy()
if no_feat.any():
warnings.append(f"{int(no_feat.sum())} detections miss an embedding value and were left out.")
det &= ~no_feat
if int(det.sum()) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Tracking", min=2, n=int(det.sum()))
# %% Tracks
di = np.flatnonzero(det)
seq_all = np.asarray([str(x) for x in df[SEQ].tolist()], dtype=object)
frame_all = df[FRAME].to_numpy(dtype=float)
lab_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object) if LABEL else None
res = tr.track(seq_all[di], frame_all[di], box[di], df[SCORE].to_numpy(dtype=float)[di] if SCORE else None,
lab_all[di] if LABEL else None, df[FEATURES].to_numpy(dtype=float)[di] if FEATURES else None, MODE, **OPTS)
tid_det = res["track"]
track_id = [None] * n_input # per input row; rows that weren't tracked stay empty
for k, i in enumerate(di):
if tid_det[k] > 0:
track_id[int(df["__row"].iloc[i])] = int(tid_det[k])
tracks = res["tracks"]
n_tracks = len(tracks)
n_assigned = int(np.sum(tid_det > 0))
# %% Against the reference tracks
metrics = None
switch_events = []
if SOURCE and TRUTH and int(is_ref.sum()):
truth_ok = is_ref & df[TRUTH].notna().to_numpy()
if int((is_ref & ~truth_ok).sum()):
warnings.append(f"{int((is_ref & ~truth_ok).sum())} reference boxes have no {TRUTH} and were left out of the tracking metrics.")
truth_all = np.asarray([str(x) for x in df[TRUTH].tolist()], dtype=object)
gi = np.flatnonzero(truth_ok)
hi = di[tid_det > 0]
hyp_id = {int(i): str(int(t)) for i, t in zip(di, tid_det) if t > 0}
seqs = []
for sq in sorted(set(seq_all[gi].tolist()) | set(seq_all[hi].tolist())):
g_s = gi[seq_all[gi] == sq]
h_s = hi[seq_all[hi] == sq]
frames = []
for f in sorted(set(frame_all[g_s].tolist()) | set(frame_all[h_s].tolist())):
g_f = g_s[frame_all[g_s] == f]
h_f = h_s[frame_all[h_s] == f]
frames.append({"frame": f, "gt_ids": [f"{sq}\x1f{truth_all[i]}" for i in g_f], "gt_boxes": box[g_f],
"hyp_ids": [hyp_id[int(i)] for i in h_f], "hyp_boxes": box[h_f]})
seqs.append(frames)
metrics = mot.clear_mot(seqs, MOT_IOU)
switch_events = metrics["switch_events"]
# %% Assumptions
assumptions = [
{"key": "frames", "label": "Frames are in order", "status": "info",
"detail": "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."},
{"key": "motion", "label": "Objects move smoothly", "status": "info",
"detail": "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks."},
]
if FEATURES:
assumptions.append({"key": "appearance", "label": "Embeddings describe appearance", "status": "info",
"detail": "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close."})
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
labels_seen = sorted(set(t["label"] for t in tracks if t["label"] is not None))
seq_list = sorted(set(seq_all[di].tolist()))
n_frames = len(set(zip(seq_all[di].tolist(), frame_all[di].tolist())))
values = {"association": MODE, "n_sequences": len(seq_list), "n_frames": n_frames, "n_detections": int(di.size), "n_tracks": n_tracks,
"n_assigned": n_assigned, "n_unassigned": int(di.size - n_assigned),
"mean_track_length": float(np.mean([t["n_detections"] for t in tracks])) if tracks else None,
"mota": None, "motp": None, "idf1": None, "idp": None, "idr": None, "id_switches": None, "fragmentations": None,
"false_positives": None, "misses": None, "mostly_tracked": None, "partially_tracked": None, "mostly_lost": None,
"precision": None, "recall": None, "n_gt_tracks": None, "n_gt_boxes": None, "track_id": track_id}
for lab in labels_seen:
values[f"tracks[{lab}]"] = sum(1 for t in tracks if t["label"] == lab)
if metrics is not None:
values.update({"mota": metrics["mota"], "motp": metrics["motp"], "idf1": metrics["idf1"], "idp": metrics["idp"], "idr": metrics["idr"],
"id_switches": metrics["switches"], "fragmentations": metrics["fragmentations"], "false_positives": metrics["false_positives"],
"misses": metrics["misses"], "mostly_tracked": metrics["mostly_tracked"], "partially_tracked": metrics["partially_tracked"],
"mostly_lost": metrics["mostly_lost"], "precision": metrics["precision"], "recall": metrics["recall"],
"n_gt_tracks": metrics["n_gt_tracks"], "n_gt_boxes": metrics["objects"]})
trk_rows = [{"track_id": t["track_id"], "sequence": t["sequence"], "label": t["label"], "first_frame": t["first_frame"], "last_frame": t["last_frame"],
"span": t["last_frame"] - t["first_frame"] + 1.0, "n_detections": t["n_detections"], "mean_score": t["mean_score"]} for t in tracks]
tables = [{"key": "tracks", "title": "Tracks",
"columns": [{"key": "track_id", "label": "Track", "type": "integer"}, {"key": "sequence", "label": SEQ, "type": "string"}]
+ ([{"key": "label", "label": LABEL, "type": "string"}] if LABEL else [])
+ [{"key": "first_frame", "label": "First frame", "type": "number"}, {"key": "last_frame", "label": "Last frame", "type": "number"},
{"key": "span", "label": "Frames spanned", "type": "number"}, {"key": "n_detections", "label": "Detections", "type": "integer"}]
+ ([{"key": "mean_score", "label": "Mean score", "type": "number"}] if SCORE else []),
"rows": trk_rows[:500], "note": "First 500 tracks." if len(trk_rows) > 500 else None}]
if metrics is not None:
mrows = [("MOTA", metrics["mota"], "1 − (misses + false positives + identity switches) / reference boxes"),
("IDF1", metrics["idf1"], "Share of boxes on the right identity (global track matching)"),
("MOTP (mean IoU)", metrics["motp"], "Mean overlap of the paired boxes"),
("Identity switches", metrics["switches"], "A reference object took a different track"),
("Fragmentations", metrics["fragmentations"], "A tracked object was lost and found again"),
("Misses", metrics["misses"], "Reference boxes with no track"), ("False positives", metrics["false_positives"], "Tracked boxes with no reference object"),
("Mostly tracked", metrics["mostly_tracked"], "Reference tracks paired in at least 80% of their frames"),
("Mostly lost", metrics["mostly_lost"], "Reference tracks paired in under 20% of their frames")]
tables.append({"key": "mot", "title": f"Against the reference tracks (IoU ≥ {MOT_IOU:g})",
"columns": [{"key": "metric", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "meaning", "label": "Meaning", "type": "string"}],
"rows": [{"metric": a, "value": b, "meaning": c} for a, b, c in mrows]})
if switch_events:
tables.append({"key": "switches", "title": "Identity switches",
"columns": [{"key": "sequence", "label": SEQ, "type": "string"}, {"key": "frame", "label": "Frame", "type": "number"},
{"key": "object", "label": "Reference object", "type": "string"}, {"key": "from", "label": "From track", "type": "string"},
{"key": "to", "label": "To track", "type": "string"}],
"rows": [{"sequence": e["object"].split("\x1f")[0], "frame": e["frame"], "object": e["object"].split("\x1f")[1],
"from": e["from"], "to": e["to"]} for e in switch_events[:200]],
"note": "First 200 switches." if len(switch_events) > 200 else None})
charts = []
if tracks:
lane_of = {t["track_id"]: f"{t['track_id']}" + (f" · {t['label']}" if t["label"] is not None else "") for t in tracks}
shown = tracks[:60]
ln, s0, s1, col, ev = [], [], [], [], []
for t in shown:
fr = np.sort(frame_all[di][tid_det == t["track_id"]])
brk = np.flatnonzero(np.diff(fr) > 1.0)
starts = np.concatenate([[fr[0]], fr[brk + 1]])
ends = np.concatenate([fr[brk], [fr[-1]]])
for a, b in zip(starts, ends):
ln.append(lane_of[t["track_id"]])
s0.append(float(a))
s1.append(float(b))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append(None)
shown_ids = {t["track_id"] for t in shown}
for e in switch_events:
if int(e["to"]) in shown_ids:
t = next(x for x in shown if x["track_id"] == int(e["to"]))
ln.append(lane_of[t["track_id"]])
s0.append(float(e["frame"]))
s1.append(float(e["frame"]))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append("Identity switch")
roles = {"lane": cs.col("Track", ln, "categorical", levels=[lane_of[t["track_id"]] for t in shown]),
"start": cs.col(FRAME, s0, "numeric"), "end": cs.col("Last frame", s1, "numeric"),
"color": cs.col(SEQ if len(seq_list) > 1 else (LABEL or SEQ), col, "categorical")}
if any(v is not None for v in ev):
roles["event"] = cs.col("Event", ev, "categorical")
charts.append(cs.chart("timeline", "track-timeline", "When each track was seen", roles,
note=("The first 60 tracks. " if len(tracks) > 60 else "") + "Bars break where a track missed more than one frame."))
out = csml.out_dir("target/academy-parity/run-8142/track.objects/perfect-detections/out-python")
labels_path = os.path.join(out, "labels.parquet")
pd.DataFrame({"row": np.arange(n_input, dtype=np.int64), "cluster": np.asarray([-1 if v is None else v for v in track_id], dtype=np.int64)}).to_parquet(labels_path, index=False)
summary = (f"{n_tracks} track{'s' if n_tracks != 1 else ''} from {int(di.size)} detections in {len(seq_list)} sequence{'s' if len(seq_list) != 1 else ''} "
f"({ {'sort': 'SORT', 'bytetrack': 'ByteTrack', 'deepsort': 'DeepSORT-style'}[MODE] } association); {n_assigned} detections joined a track.")
if metrics is not None:
summary += (f" Against {metrics['n_gt_tracks']} reference tracks: MOTA {f3(metrics['mota'])}, IDF1 {f3(metrics['idf1'])}, "
f"{metrics['switches']} identity switches.")
cs.publish({
"method": "track.objects",
"methodVersion": "1.1.1",
"title": "Object tracks",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "n_tracks", "label": "Tracks", "value": n_tracks}]
+ ([{"key": "mota", "label": "MOTA", "value": metrics["mota"]}, {"key": "idf1", "label": "IDF1", "value": metrics["idf1"]},
{"key": "id_switches", "label": "Identity switches", "value": metrics["switches"]}] if metrics is not None else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Tracks start from detections and are confirmed after {OPTS['min_hits']} detections; a confirmed track ends after {OPTS['max_age']:g} frames without one. "
+ ("Boxes pair only within the same class. " if (LABEL and OPTS["per_class"]) else "")
+ "Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers)."],
"charts": charts,
"artifacts": [{"key": "labels", "path": labels_path, "format": "parquet"}],
"values": values,
})
Three objects in separate lanes, each detected exactly: every object gets one track, MOTA and IDF1 are 1 and nothing switches. Real data falls short of this through missed detections, false boxes and crossings.
Check yourself
ReadCheck yourself
People often walk behind a pillar for 2 seconds (50 frames). "Frames a lost track is kept" is 30. What happens when someone reappears?
Show the answer
Answer: b
A confirmed track ends once more than 30 frames pass without a detection. Raise the value above the longest expected occlusion, at the cost of more wrong re-pairings.
Check yourself
Tracker A: MOTA 0.75, IDF1 0.50. Tracker B: MOTA 0.72, IDF1 0.70. You need to count unique visitors. Which do you prefer?
Show the answer
Answer: b
MOTA mostly reflects detection errors; IDF1 measures whether each person keeps one id. Unique counts break when identities split, so IDF1 matters more here.
Check yourself
During occlusions the detector still sees partly hidden people, but with scores around 0.3. Which association uses those boxes?
Show the answer
Answer: b
ByteTrack's second round lets tracks seen in the last frame take low-confidence boxes, so a track survives the occlusion instead of breaking.
Concepts in this lesson