Post-Processing: Fix Left/Right Label Switches & Gaps#

Open In Colab

In symmetric chambers (for example three-chamber social preference assays with LeftZone / RightZone or LeftTeaball / RightTeaball), detectors occasionally swap symmetric left/right labels or drop a static landmark on a few frames.

This runnable notebook migrates docs/tutorials/Annolid_post_processing_fix_left_right_switch.ipynb with modern pandas 2.x operations and Annolid’s evaluate_track_qc audit.

What you will learn:

  1. Detect and repair left/right label swaps using the arena midline (cx < width / 2 vs cx >= width / 2).

  2. Fill missing detections for static arena landmarks using their modal coordinates.

  3. Repair missing moving-object frames by matching nearest centroids across neighboring frames.

  4. Verify track integrity before and after cleanup with evaluate_track_qc.

1. Load Tracking CSV (or Build a Synthetic Symmetric-Chamber Demo)#

from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from annolid.postprocessing.track_qc import evaluate_track_qc

WORK_DIR = Path("./annolid_left_right_demo")
WORK_DIR.mkdir(parents=True, exist_ok=True)

TRACKING_CSV_PATH = None  # Set to your own *_tracking.csv path, or keep None for synthetic demo
FRAME_WIDTH = 800
FRAME_HEIGHT = 480


def build_demo_symmetric_csv(out_path: Path, *, num_frames: int = 120) -> Path:
    """Simulate a symmetric arena with deliberate Left/Right swaps and missing frames."""
    rng = np.random.default_rng(13)
    rows = []
    for f in range(num_frames):
        # Static landmarks on left (x ~ 170) and right (x ~ 630)
        objects = [
            ("LeftZone", 170.0, 240.0, 200.0, 320.0),
            ("RightZone", 630.0, 240.0, 200.0, 320.0),
            ("LeftTeaball", 180.0 + rng.normal(0, 1.0), 240.0 + rng.normal(0, 1.0), 50.0, 50.0),
            ("RightTeaball", 620.0 + rng.normal(0, 1.0), 240.0 + rng.normal(0, 1.0), 50.0, 50.0),
            ("Mouse", 400.0 + 170.0 * np.sin(f * 0.08), 240.0 + 60.0 * np.cos(f * 0.06), 46.0, 28.0),
        ]
        for name, cx, cy, w, h in objects:
            # Drop LeftZone on frames 25..28 and RightTeaball on frames 70..72
            if name == "LeftZone" and 25 <= f <= 28:
                continue
            if name == "RightTeaball" and 70 <= f <= 72:
                continue
            # Deliberately swap Left/Right teaball labels on frames 45..52
            label = name
            if 45 <= f <= 52 and name == "LeftTeaball":
                label = "RightTeaball"
            elif 45 <= f <= 52 and name == "RightTeaball":
                label = "LeftTeaball"
            rows.append(
                {
                    "frame_number": f,
                    "x1": round(cx - w / 2, 2),
                    "y1": round(cy - h / 2, 2),
                    "x2": round(cx + w / 2, 2),
                    "y2": round(cy + h / 2, 2),
                    "instance_name": label,
                    "class_score": 0.94,
                }
            )
    pd.DataFrame(rows).to_csv(out_path, index=False)
    return out_path


raw_csv = Path(TRACKING_CSV_PATH) if TRACKING_CSV_PATH else build_demo_symmetric_csv(WORK_DIR / "raw_tracking.csv")
df_raw = pd.read_csv(raw_csv)
df_raw["cx"] = (df_raw["x1"] + df_raw["x2"]) / 2.0
df_raw["cy"] = (df_raw["y1"] + df_raw["y2"]) / 2.0

swapped_mask = (
    (df_raw["instance_name"].str.contains("Left") & (df_raw["cx"] >= FRAME_WIDTH / 2))
    | (df_raw["instance_name"].str.contains("Right") & (df_raw["cx"] < FRAME_WIDTH / 2))
)
print(f"Loaded {len(df_raw)} rows across {df_raw['frame_number'].nunique()} frames.")
print(f"Detected {int(swapped_mask.sum())} left/right midline label swap(s) before cleanup.")
Loaded 593 rows across 120 frames.
Detected 16 left/right midline label swap(s) before cleanup.

2. Fix Midline Left/Right Swaps & Fill Static Landmarks#

def switch_left_right(row: pd.Series, width: float = 800.0) -> str:
    """Flip Left/Right prefix when a symmetric object crosses the arena midline."""
    instance_name = str(row["instance_name"])
    x_val = float(row["cx"]) if "cx" in row else float(row["x1"])
    if "Left" in instance_name and x_val >= width / 2.0:
        return instance_name.replace("Left", "Right")
    if "Right" in instance_name and x_val < width / 2.0:
        return instance_name.replace("Right", "Left")
    return instance_name


def fill_static_zones_with_mode(frame_df: pd.DataFrame, static_names: list[str]) -> pd.DataFrame:
    """Insert modal bounding box rows for static landmarks missing on any frame."""
    all_frames = sorted(frame_df["frame_number"].unique().tolist())
    additions = []
    for name in static_names:
        sub = frame_df[frame_df["instance_name"] == name]
        if sub.empty:
            continue
        template = sub.mode().iloc[0].to_dict()
        present = set(sub["frame_number"].tolist())
        for f in all_frames:
            if f not in present:
                row = dict(template)
                row["frame_number"] = f
                additions.append(row)
    if not additions:
        return frame_df.copy()
    return (
        pd.concat([frame_df, pd.DataFrame(additions)], ignore_index=True)
        .sort_values(["frame_number", "instance_name"])
        .reset_index(drop=True)
    )


def repair_missing_in_window(
    frame_df: pd.DataFrame,
    expected_names: list[str],
    *,
    window_size: int = 5,
) -> pd.DataFrame:
    """Fill remaining single/short-gap missing instances from the nearest prior frame."""
    all_frames = sorted(frame_df["frame_number"].unique().tolist())
    additions = []
    for f in all_frames:
        present = set(frame_df.loc[frame_df["frame_number"] == f, "instance_name"])
        missing = [n for n in expected_names if n not in present]
        for name in missing:
            prev = frame_df[
                (frame_df["instance_name"] == name)
                & (frame_df["frame_number"] < f)
                & (frame_df["frame_number"] >= f - window_size)
            ].sort_values("frame_number")
            if prev.empty:
                continue
            row = prev.iloc[-1].to_dict()
            row["frame_number"] = f
            additions.append(row)
    if not additions:
        return frame_df.copy()
    return (
        pd.concat([frame_df, pd.DataFrame(additions)], ignore_index=True)
        .sort_values(["frame_number", "instance_name"])
        .reset_index(drop=True)
    )


df_fixed = df_raw.copy()
df_fixed["instance_name"] = df_fixed.apply(lambda r: switch_left_right(r, FRAME_WIDTH), axis=1)
df_fixed = fill_static_zones_with_mode(df_fixed, ["LeftZone", "RightZone"])
expected_all = ["LeftZone", "RightZone", "LeftTeaball", "RightTeaball", "Mouse"]
df_fixed = repair_missing_in_window(df_fixed, expected_all, window_size=5)

remaining_swaps = (
    (df_fixed["instance_name"].str.contains("Left") & (df_fixed["cx"] >= FRAME_WIDTH / 2))
    | (df_fixed["instance_name"].str.contains("Right") & (df_fixed["cx"] < FRAME_WIDTH / 2))
)
fixed_csv = WORK_DIR / "fixed_tracking.csv"
df_fixed.to_csv(fixed_csv, index=False)

print(f"Remaining midline swaps: {int(remaining_swaps.sum())}")
print(f"Rows before: {len(df_raw)} -> after gap repair: {len(df_fixed)} (expected {len(expected_all) * df_fixed['frame_number'].nunique()})")
print(f"Saved cleaned CSV -> {fixed_csv.name}")
Remaining midline swaps: 0
Rows before: 593 -> after gap repair: 600 (expected 600)
Saved cleaned CSV -> fixed_tracking.csv

3. Audit With Annolid Track QC & Plot Before vs. After#

qc_before = evaluate_track_qc(raw_csv, expected_instances=5, fps=30.0)
qc_after = evaluate_track_qc(fixed_csv, expected_instances=5, fps=30.0)
print(
    f"Track QC issues: before={len(qc_before.issues)} (review bouts={len(qc_before.review_queue)}) "
    f"-> after={len(qc_after.issues)} (review bouts={len(qc_after.review_queue)})"
)

fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8), sharey=True)
for ax, data, title in [
    (axes[0], df_raw, "Before Cleanup (Swaps + Gaps)"),
    (axes[1], df_fixed, "After Midline Fix & Gap Repair"),
]:
    for name, color in [("LeftTeaball", "#2563eb"), ("RightTeaball", "#ea580c")]:
        sub = data[data["instance_name"] == name].sort_values("frame_number")
        ax.scatter(sub["frame_number"], sub["cx"], s=14, label=name, color=color, alpha=0.85)
    ax.axhline(FRAME_WIDTH / 2.0, color="#64748b", linestyle="--", linewidth=1.1, label="Midline (x = width/2)")
    ax.set_title(title)
    ax.set_xlabel("Frame number")
    ax.legend(fontsize=8, loc="center right")
    ax.grid(alpha=0.25)

axes[0].set_ylabel("Centroid x (px)")
plt.tight_layout()
plt.show()
Track QC issues: before=8 (review bouts=4) -> after=0 (review bouts=0)
../_images/dd3dbea5f5a67edda47ee5a31a93ae716b2757e1ded7937c9fa87b914c1f7249.png