"""Patient centroid separation loss (PCSL) — lightweight auxiliary loss."""

import torch


def compute_pcsl_loss(features, patient_ids, eps=1e-6):
    """
  PCSL: mean within-patient feature variance (minimize for patient-invariant reps).
  features: [B, D] pooled frame features
  patient_ids: [B] integer patient ids
  """
    unique_ids = torch.unique(patient_ids)
    if unique_ids.numel() <= 1:
        return features.new_zeros(())

    within = features.new_zeros(())
    count = 0
    for pid in unique_ids:
        mask = patient_ids == pid
        if mask.sum() <= 1:
            continue
        f = features[mask]
        within = within + ((f - f.mean(dim=0, keepdim=True)) ** 2).mean()
        count += 1
    if count == 0:
        return features.new_zeros(())
    return within / (count + eps)
