diff --git a/tools/cli/rust/src/bin/rust_face_cluster.rs b/tools/cli/rust/src/bin/rust_face_cluster.rs index e251fd48..74568503 100644 --- a/tools/cli/rust/src/bin/rust_face_cluster.rs +++ b/tools/cli/rust/src/bin/rust_face_cluster.rs @@ -578,94 +578,73 @@ fn apply_cooccurrence_constraints( fn merge_small_clusters( trace_to_person: std::collections::BTreeMap, trace_embeddings: &std::collections::BTreeMap>, - trace_similarities: &std::collections::BTreeMap, - min_large_cluster_size: usize, + _trace_similarities: &std::collections::BTreeMap, + _min_large_cluster_size: usize, merge_similarity_threshold: f64, + cooccurrence: &std::collections::HashSet<(i64, i64)>, ) -> std::collections::BTreeMap { let mut trace_to_person = trace_to_person; - - // Count traces per person - let mut person_trace_count: std::collections::HashMap = std::collections::HashMap::new(); - for (_, pid) in &trace_to_person { - *person_trace_count.entry(*pid).or_insert(0) += 1; - } - - // Identify large clusters (seeds) and small clusters - let mut large_clusters: std::collections::HashSet = std::collections::HashSet::new(); - let mut small_clusters: std::collections::HashSet = std::collections::HashSet::new(); - - for (pid, count) in &person_trace_count { - if *count >= min_large_cluster_size { - large_clusters.insert(*pid); - } else { - small_clusters.insert(*pid); + let merge_sim = merge_similarity_threshold; + + // Iteratively merge the most-similar compatible pair until no merge is + // possible. Recompute centroids each round so chained merges use fresh data. + // Co-occurrence constraint prevents merging traces that appeared together + // in a frame (different physical people). + loop { + let mut cur_traces: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (tid, pid) in &trace_to_person { + cur_traces.entry(*pid).or_default().push(*tid); } - } - - if small_clusters.is_empty() || large_clusters.is_empty() { - return trace_to_person; - } - - eprintln!("[MERGE] Large clusters: {:?}, Small clusters: {:?}", large_clusters, small_clusters); - - // Compute mean embedding for each person - let mut person_embeddings: std::collections::HashMap> = std::collections::HashMap::new(); - for (tid, pid) in &trace_to_person { - if let Some(emb) = trace_embeddings.get(tid) { - person_embeddings.entry(*pid).or_insert_with(|| vec![0.0; emb.len()]); - let pe = person_embeddings.get_mut(pid).unwrap(); - for (i, &v) in emb.iter().enumerate() { - pe[i] += v; - } - } - } - // Normalize - for (pid, traces) in &person_trace_count { - if let Some(pe) = person_embeddings.get_mut(pid) { - let count = *traces as f64; - for v in pe.iter_mut() { - *v /= count; - } - } - } - - // Merge each small cluster into most similar large cluster - for small_pid in small_clusters { - let mut best_sim = -1.0; - let mut best_large_pid: Option = None; - - for large_pid in &large_clusters { - if let (Some(emb_small), Some(emb_large)) = (person_embeddings.get(&small_pid), person_embeddings.get(large_pid)) { - let sim = cosine_similarity(emb_small, emb_large); - if sim > best_sim { - best_sim = sim; - best_large_pid = Some(*large_pid); - } - } - } - - if let Some(target_pid) = best_large_pid { - if best_sim >= merge_similarity_threshold { - eprintln!(" [MERGE] Person_{} ({} traces) -> Person_{} (sim={:.3})", - small_pid, person_trace_count.get(&small_pid).unwrap_or(&0), target_pid, best_sim); - - // Reassign all traces from small to large - for (tid, pid) in trace_to_person.iter_mut() { - if *pid == small_pid { - *pid = target_pid; + let mut centroids: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (pid, tids) in &cur_traces { + let mut mean: Option> = None; + for tid in tids { + if let Some(e) = trace_embeddings.get(tid) { + if let Some(m) = mean.as_mut() { + for (i, &v) in e.iter().enumerate() { m[i] += v; } + } else { + mean = Some(vec![0.0; e.len()]); + for (i, &v) in e.iter().enumerate() { mean.as_mut().unwrap()[i] += v; } } } - } else { - eprintln!(" [SKIP] Person_{} not similar enough to any large cluster (best sim={:.3})", small_pid, best_sim); + } + if let Some(mut m) = mean { + let n = tids.len() as f64; + for v in m.iter_mut() { *v /= n; } + centroids.insert(*pid, m); } } + let pids: Vec = cur_traces.keys().copied().collect(); + let mut best: Option<(f64, i64, i64)> = None; + for (i, &pa) in pids.iter().enumerate() { + for &pb in pids.iter().skip(i + 1) { + let (ea, eb) = match (centroids.get(&pa), centroids.get(&pb)) { + (Some(a), Some(b)) => (a, b), + _ => continue, + }; + let sim = cosine_similarity(ea, eb); + if sim < merge_sim { continue; } + let conflict = cur_traces[&pa].iter().any(|a| { + cur_traces[&pb].iter().any(|b| { + cooccurrence.contains(&((*a).min(*b), (*a).max(*b))) + }) + }); + if !conflict && best.map_or(true, |(bs, _, _)| sim > bs) { + best = Some((sim, pa, pb)); + } + } + } + match best { + Some((sim, from, to)) => { + eprintln!(" [MERGE] Person_{} ({} traces) -> Person_{} (sim={:.3})", + from, cur_traces[&from].len(), to, sim); + for (tid, pid) in trace_to_person.iter_mut() { + if *pid == from { *pid = to; } + } + } + None => break, + } } - - // Re-index person IDs - let unique_pids: std::collections::BTreeSet = trace_to_person.values().copied().collect(); - let pid_map: std::collections::HashMap = unique_pids.into_iter().enumerate().map(|(new, old)| (old, new as i64)).collect(); - trace_to_person = trace_to_person.into_iter().map(|(tid, pid)| (tid, *pid_map.get(&pid).unwrap())).collect(); - trace_to_person } @@ -844,7 +823,8 @@ fn main() { &trace_embeddings, &trace_similarities, 5, // min traces to be considered a "large" cluster - 0.7 // similarity threshold for merging + 0.7, // similarity threshold for merging + &cooccurrence_constraints, // never merge same-frame (different-person) traces ); let n_persons: usize = trace_to_person.values().collect::>().len();