use std::{
collections::{BTreeSet, HashMap},
fmt::Debug,
sync::Arc,
};
use bstr::ByteSlice;
use rust_htslib::bcf::{self, record::GenotypeAllele};
use tracing::trace;
use super::cluster::ClusteringSettings;
use crate::vcf::pipeline::record::InputRecord;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Allele(pub Option<u32>);
impl Allele {
pub const fn is_missing(self) -> bool {
self.0.is_none()
}
pub const fn is_ref(self) -> bool {
matches!(self.0, Some(0))
}
pub const fn is_alt(self) -> bool {
matches!(self.0, Some(a) if a > 0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Phase {
Unphased,
Phased(i32),
}
impl Phase {
pub const fn phaseset(self) -> Option<i32> {
match self {
Self::Unphased => None,
Self::Phased(ps) => Some(ps),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Genotype {
Haploid(Allele),
Diploid { alleles: [Allele; 2], phase: Phase },
}
const UNKNOWN: Genotype = Genotype::Diploid {
alleles: [Allele(None), Allele(None)],
phase: Phase::Unphased,
};
impl Genotype {
pub const fn slots(&self) -> &[Allele] {
match self {
Self::Haploid(a) => std::slice::from_ref(a),
Self::Diploid { alleles, .. } => alleles,
}
}
pub const fn phase(&self) -> Phase {
match self {
Self::Haploid(_) => Phase::Unphased,
Self::Diploid { phase, .. } => *phase,
}
}
pub fn has_missing(&self) -> bool {
self.slots().iter().any(|a| a.is_missing())
}
pub fn has_alt(&self) -> bool {
self.slots().iter().any(|a| a.is_alt())
}
pub fn is_hom_ref(&self) -> bool {
self.slots().iter().all(|a| a.is_ref())
}
pub fn is_hom(&self) -> bool {
matches!(self, Self::Diploid { alleles: [a0, a1], .. } if a0 == a1)
}
pub const fn is_phased(&self) -> bool {
matches!(self.phase(), Phase::Phased(_))
}
pub const fn is_haploid(&self) -> bool {
matches!(self, Self::Haploid(_))
}
pub fn is_unphased_het(&self) -> bool {
matches!(
self,
Self::Diploid {
phase: Phase::Unphased,
..
}
) && !self.is_hom()
}
}
impl Genotype {
pub(crate) fn from_record(record: &bcf::Record, sample_ix: usize) -> Self {
let Ok(genotypes) = record.genotypes() else {
return UNKNOWN;
};
let gt = genotypes.get(sample_ix);
match gt.as_slice() {
[a] => Self::Haploid(Allele(a.index())),
[a0, a1] => {
let phase = if let GenotypeAllele::Phased(..) | GenotypeAllele::PhasedMissing = a1 {
Phase::Phased(read_phaseset(record, sample_ix))
} else {
Phase::Unphased
};
Self::Diploid {
alleles: [Allele(a0.index()), Allele(a1.index())],
phase,
}
}
_ => UNKNOWN,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Haplotype {
H0,
H1,
Both,
Haploid,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutputPhasing {
pub alleles: &'static [u32],
pub phaseset: Option<i32>,
}
impl OutputPhasing {
pub const fn from_subcluster(haplo: Haplotype, phaseset: Option<i32>) -> Self {
let alleles: &[u32] = match haplo {
Haplotype::H0 => &[1, 0], Haplotype::H1 => &[0, 1], Haplotype::Both => &[1, 1], Haplotype::Haploid => &[1], };
Self { alleles, phaseset }
}
pub const fn is_phased(&self) -> bool {
self.phaseset.is_some()
}
pub const fn is_hom(&self) -> bool {
!matches!(self.alleles, [a0, a1] if *a0 != *a1)
}
pub const fn written_phaseset(&self) -> Option<i32> {
if self.is_phased() && !self.is_hom() {
Some(match self.phaseset {
Some(ps) => ps,
None => 0,
})
} else {
None
}
}
pub fn changes(&self, old: &InputRecord, alt_idx: u32) -> bool {
let gtp = old.input_gt();
let old_alleles = gtp.slots().iter().map(|a| match a.0 {
Some(0) => Some(0),
Some(i) if i == alt_idx => Some(1),
_ => None,
});
!old_alleles.eq(self.alleles.iter().copied().map(Some))
|| gtp.is_phased() != self.is_phased()
|| ps_tag(old.record(), old.sample_ix()) != self.written_phaseset()
}
}
type RecordAllele = (Arc<InputRecord>, u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlankAllele {
Apply(u32),
Ref,
Unknown,
}
pub fn input_phasesets(proximity_cluster: &[Arc<InputRecord>]) -> Vec<i32> {
proximity_cluster
.iter()
.map(|r| r.input_gt())
.filter(|gt| !gt.is_hom())
.filter_map(|gt| gt.phase().phaseset())
.collect()
}
pub fn flank_allele(flank: Genotype, haplo: Haplotype, phaseset: Option<i32>) -> FlankAllele {
let allele = match (haplo, flank) {
(Haplotype::Haploid, Genotype::Haploid(a)) => a,
(
_,
Genotype::Diploid {
alleles: [a0, a1], ..
},
) if a0 == a1 => a0,
(
Haplotype::H0 | Haplotype::H1,
Genotype::Diploid {
alleles,
phase: Phase::Phased(ps),
},
) if Some(ps) == phaseset => {
let [a0, a1] = alleles;
if haplo == Haplotype::H1 { a1 } else { a0 }
}
_ => Allele(None),
};
match allele.0 {
None => FlankAllele::Unknown,
Some(0) => FlankAllele::Ref,
Some(a) => FlankAllele::Apply(a),
}
}
pub struct HaplotypeSubCluster {
pub records: Vec<RecordAllele>,
pub phaseset: Option<i32>,
pub haplo: Haplotype,
}
impl Debug for HaplotypeSubCluster {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HaplotypeSubCluster")
.field(
"records",
&self
.records
.iter()
.filter_map(|(r, a)| {
let alleles = r.alleles();
let ra = alleles.first()?.as_bstr().to_owned();
let aa = alleles.get(*a as usize)?.as_bstr().to_owned();
Some(format!("{}: {ra} -> {aa}", r.pos() + 1))
})
.collect::<Vec<_>>(),
)
.field("phaseset", &self.phaseset)
.field("haplo", &self.haplo)
.finish()
}
}
fn ps_tag(record: &bcf::Record, sample_ix: usize) -> Option<i32> {
record
.format(b"PS")
.integer()
.ok()
.and_then(|data| data.get(sample_ix).and_then(|s| s.first().copied()))
}
fn read_phaseset(record: &bcf::Record, sample_ix: usize) -> i32 {
ps_tag(record, sample_ix).unwrap_or(i32::MIN)
}
pub fn is_trivially_resolvable(records: &[Arc<InputRecord>]) -> bool {
(records.len() <= 1
|| records.iter().all(|r| !r.gt().is_unphased_het())
|| records.iter().fold((0, 0), |(unphased_het, het), r| {
let gtp = r.gt();
(
unphased_het + u32::from(gtp.is_unphased_het()),
het + u32::from(!gtp.is_hom()),
)
}) == (1, 1))
&& records.iter().all(|r| !r.gt().has_missing())
}
#[derive(Debug)]
pub enum SplitIntoHaplotypesError {
MoreThanOneUnphasedHet,
MissingAllele,
MixedPloidy,
HomAcrossPhaseSets,
#[expect(dead_code)]
Other(anyhow::Error),
}
pub fn split_into_haplotype_clusters(
proximity_cluster: &[Arc<InputRecord>],
settings: &ClusteringSettings,
) -> Result<Vec<HaplotypeSubCluster>, SplitIntoHaplotypesError> {
match proximity_cluster
.iter()
.filter(|r| r.gt().is_haploid())
.count()
{
0 => {}
n if n == proximity_cluster.len() => {
let records: Vec<RecordAllele> = proximity_cluster
.iter()
.filter_map(|r| match r.gt() {
Genotype::Haploid(Allele(Some(a))) if a > 0 => Some((Arc::clone(r), a)),
_ => None,
})
.collect();
return Ok(into_proximity_sub_clusters(&records, settings)
.into_iter()
.map(|records| HaplotypeSubCluster {
records,
phaseset: None,
haplo: Haplotype::Haploid,
})
.collect());
}
_ => return Err(SplitIntoHaplotypesError::MixedPloidy),
}
if let Some((c, &[])) = proximity_cluster.split_first() {
return handle_single_record(c, settings).map_err(SplitIntoHaplotypesError::Other);
}
if proximity_cluster.iter().any(|r| r.gt().has_missing()) {
return Err(SplitIntoHaplotypesError::MissingAllele);
}
if proximity_cluster
.iter()
.fold((0, 0), |(unphased_het, het), r| {
let gtp = r.gt();
(
unphased_het + u32::from(gtp.is_unphased_het()),
het + u32::from(!gtp.is_hom()),
)
})
== (1, 1)
{
return handle_cluster_with_single_unphased_het(proximity_cluster, settings)
.map_err(SplitIntoHaplotypesError::Other);
}
if proximity_cluster.iter().any(|r| r.gt().is_unphased_het()) {
return Err(SplitIntoHaplotypesError::MoreThanOneUnphasedHet);
}
let iter = proximity_cluster.iter().map(|r| r.gt());
debug_assert!(iter.clone().all(|gtp| !gtp.has_missing()));
debug_assert!(iter.clone().filter(Genotype::is_unphased_het).count() <= 1);
debug_assert!(
iter.clone()
.all(|gtp| gtp.is_hom() || gtp.is_phased() || gtp.is_unphased_het())
);
create_subclusters(proximity_cluster, settings)
}
fn handle_single_record(
rec: &Arc<InputRecord>,
settings: &ClusteringSettings,
) -> anyhow::Result<Vec<HaplotypeSubCluster>> {
let gtp = rec.gt();
if gtp.is_hom_ref() {
return Ok(vec![]);
}
if let Genotype::Diploid {
alleles: [Allele(Some(a0)), Allele(Some(a1))],
phase,
} = gtp
&& a0 == a1
{
return Ok(vec![HaplotypeSubCluster {
records: vec![(rec.clone(), a0)],
phaseset: phase.phaseset(),
haplo: Haplotype::Both,
}]);
}
let Genotype::Diploid {
alleles: [a0, a1],
phase,
} = gtp
else {
return Ok(vec![]);
};
let mut phase = phase.phaseset();
let mut result = Vec::new();
phase.get_or_insert(i32::try_from(rec.pos() + 1)?);
if let Allele(Some(a0)) = a0
&& a0 > 0
{
for records in into_proximity_sub_clusters(&[(rec.clone(), a0)], settings) {
result.push(HaplotypeSubCluster {
records,
phaseset: phase,
haplo: Haplotype::H0,
});
}
}
if let Allele(Some(a1)) = a1
&& a1 > 0
{
for records in into_proximity_sub_clusters(&[(rec.clone(), a1)], settings) {
result.push(HaplotypeSubCluster {
records,
phaseset: phase,
haplo: Haplotype::H1,
});
}
}
Ok(result)
}
fn handle_cluster_with_single_unphased_het(
proximity_cluster: &[Arc<InputRecord>],
settings: &ClusteringSettings,
) -> anyhow::Result<Vec<HaplotypeSubCluster>> {
let mut h0 = Vec::new();
let mut h1 = Vec::new();
let mut phaseset = None;
for r in proximity_cluster {
let gtp @ Genotype::Diploid {
alleles: [Allele(Some(a0)), Allele(Some(a1))],
..
} = r.gt()
else {
continue;
};
if gtp.is_unphased_het() {
phaseset = Some(i32::try_from(r.pos() + 1)?);
}
if a0 != 0 {
h0.push((r.clone(), a0));
}
if a1 != 0 {
h1.push((r.clone(), a1));
}
}
Ok([(h0, Haplotype::H0), (h1, Haplotype::H1)]
.into_iter()
.flat_map(|(records, haplo)| {
into_proximity_sub_clusters(&records, settings)
.into_iter()
.map(move |records| HaplotypeSubCluster {
records,
phaseset,
haplo,
})
})
.collect())
}
fn create_subclusters(
proximity_cluster: &[Arc<InputRecord>],
settings: &ClusteringSettings,
) -> Result<Vec<HaplotypeSubCluster>, SplitIntoHaplotypesError> {
let mut phased_groups: HashMap<(i32, Haplotype), Vec<RecordAllele>> = HashMap::new();
let mut hom_alt: Vec<RecordAllele> = Vec::new();
for record in proximity_cluster {
let gtp = record.gt();
match gtp {
Genotype::Diploid {
alleles: [Allele(Some(a0)), Allele(Some(a1))],
phase: Phase::Phased(phase),
} if a0 != a1 => {
if a0 > 0 {
phased_groups
.entry((phase, Haplotype::H0))
.or_default()
.push((Arc::clone(record), a0));
}
if a1 > 0 {
phased_groups
.entry((phase, Haplotype::H1))
.or_default()
.push((Arc::clone(record), a1));
}
}
gtp @ Genotype::Diploid {
alleles: [Allele(Some(a)), ..],
..
} if a > 0 && gtp.is_hom() => {
hom_alt.push((Arc::clone(record), a));
}
_ => {}
}
}
let mut result = Vec::new();
if phased_groups.is_empty() {
for sc in into_proximity_sub_clusters(&hom_alt, settings) {
result.push(HaplotypeSubCluster {
records: sc,
phaseset: None,
haplo: Haplotype::Both,
});
}
} else {
let phasesets: BTreeSet<i32> = phased_groups.keys().map(|(ps, _)| *ps).collect();
if !hom_alt.is_empty() && phasesets.len() > 1 {
return Err(SplitIntoHaplotypesError::HomAcrossPhaseSets);
}
for ps in phasesets {
for hap in [Haplotype::H0, Haplotype::H1] {
let mut combined = phased_groups.remove(&(ps, hap)).unwrap_or_default();
combined.extend(hom_alt.iter().cloned());
combined.sort_by_key(|(r, _)| r.pos());
for sc in into_proximity_sub_clusters(&combined, settings) {
result.push(HaplotypeSubCluster {
records: sc,
phaseset: Some(ps),
haplo: hap,
});
}
}
}
}
trace!("Phasing result: {result:#?}");
Ok(result)
}
fn into_proximity_sub_clusters(
candidates: &[RecordAllele],
settings: &ClusteringSettings,
) -> Vec<Vec<RecordAllele>> {
let mut result = Vec::new();
let mut current: Vec<RecordAllele> = Vec::new();
for record in candidates {
if !settings
.belongs(current.last().map(|(r, _)| r.clone()), record.0.clone())
.unwrap_or(false)
{
result.push(std::mem::take(&mut current));
}
current.push(record.clone());
}
if !current.is_empty() {
result.push(current);
}
result
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use rust_htslib::bcf::record::GenotypeAllele;
use rust_htslib::bcf::{self, Header, Writer};
use super::*;
fn make_header() -> Header {
let mut h = Header::new();
h.push_record(b"##contig=<ID=chr1,length=1000000>");
h.push_record(b"##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
h.push_record(b"##FORMAT=<ID=PS,Number=1,Type=Integer,Description=\"Phase set\">");
h.push_sample(b"S1");
h
}
fn make_writer(header: &Header) -> Writer {
Writer::from_stdout(header, true, bcf::Format::Vcf).unwrap()
}
fn make_record(
writer: &Writer,
pos: i64,
alleles: &[&[u8]],
gt: &[GenotypeAllele],
ps: Option<i32>,
) -> InputRecord {
let mut rec = writer.empty_record();
let rid = rec.header().name2rid(b"chr1").unwrap();
rec.set_rid(Some(rid));
rec.set_pos(pos);
rec.set_alleles(alleles).unwrap();
rec.push_genotypes(gt).unwrap();
if let Some(p) = ps {
rec.push_format_integer(b"PS", &[p]).unwrap();
}
InputRecord::new(rec, 0)
}
#[test]
fn changes_false_for_identical_phasing() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)],
Some(42),
);
let op = OutputPhasing::from_subcluster(Haplotype::H1, Some(42));
assert!(!op.changes(&rec, 1));
}
#[test]
fn changes_false_for_identical_phasing_on_second_alt() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T", b"G"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(2)],
Some(42),
);
let op = OutputPhasing::from_subcluster(Haplotype::H1, Some(42));
assert!(!op.changes(&rec, 2));
}
#[test]
fn changes_compares_against_the_input_genotype_not_the_local_one() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)],
None,
);
let locally_phased = rec.with_local_gt(Genotype::Diploid {
alleles: [Allele(Some(0)), Allele(Some(1))],
phase: Phase::Phased(77),
});
assert_eq!(
locally_phased.gt().phase(),
Phase::Phased(77),
"the resolved genotype must be the effective one"
);
assert_eq!(
locally_phased.input_gt().phase(),
Phase::Unphased,
"the input genotype must stay untouched"
);
let op = OutputPhasing::from_subcluster(Haplotype::H1, Some(77));
assert!(
op.changes(&locally_phased, 1),
"phasing this program assigned itself must count as a change"
);
}
#[test]
fn changes_true_for_swapped_haplotype() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)],
Some(42),
);
let op = OutputPhasing::from_subcluster(Haplotype::H0, Some(42));
assert!(op.changes(&rec, 1));
}
#[test]
fn changes_true_when_phasing_added() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)],
None,
);
let op = OutputPhasing::from_subcluster(Haplotype::H1, Some(101));
assert!(op.changes(&rec, 1));
}
#[test]
fn changes_true_for_different_phaseset() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)],
Some(42),
);
let op = OutputPhasing::from_subcluster(Haplotype::H1, Some(7));
assert!(op.changes(&rec, 1));
}
#[test]
fn changes_true_when_phaseset_dropped() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(1), GenotypeAllele::Phased(1)],
Some(42),
);
let op = OutputPhasing::from_subcluster(Haplotype::Both, Some(42));
assert!(op.changes(&rec, 1));
}
#[test]
fn changes_true_for_missing_slot() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::UnphasedMissing, GenotypeAllele::Phased(1)],
Some(42),
);
let op = OutputPhasing::from_subcluster(Haplotype::H1, Some(42));
assert!(op.changes(&rec, 1));
}
#[test]
fn classify_hom_ref_unphased() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(0)],
None,
);
assert!(rec.gt().is_hom_ref());
}
#[test]
fn classify_hom_ref_phased() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(0)],
None,
);
assert!(rec.gt().is_hom_ref());
}
#[test]
fn classify_hom_alt_unphased() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)],
None,
);
let gtp = rec.gt();
assert!(gtp.is_hom() && !gtp.is_hom_ref());
}
#[test]
fn classify_hom_alt_phased() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(1), GenotypeAllele::Phased(1)],
Some(100),
);
let gtp = rec.gt();
assert!(gtp.is_hom() && !gtp.is_hom_ref());
}
#[test]
fn classify_phased_het_0_1() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)],
Some(100),
);
let mut settings = default_settings();
settings.min_records = Some(1);
let sub = split_into_haplotype_clusters(&[Arc::new(rec)], &settings).unwrap();
assert_eq!(sub.len(), 1);
assert_eq!(sub[0].haplo, Haplotype::H1);
assert_eq!(sub[0].phaseset, Some(100));
}
#[test]
fn classify_phased_het_1_0() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(1), GenotypeAllele::Phased(0)],
Some(100),
);
let mut settings = default_settings();
settings.min_records = Some(1);
let sub = split_into_haplotype_clusters(&[Arc::new(rec)], &settings).unwrap();
assert_eq!(sub.len(), 1);
assert_eq!(sub[0].haplo, Haplotype::H0);
assert_eq!(sub[0].phaseset, Some(100));
}
#[test]
fn classify_unphased_het() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)],
None,
);
assert!(rec.gt().is_unphased_het());
}
fn default_settings() -> ClusteringSettings {
ClusteringSettings::default()
}
#[test]
fn split_all_same_haplotype() {
let h = make_header();
let w = make_writer(&h);
let alleles: &[&[u8]] = &[b"A", b"T"];
let gt = &[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)];
let records: Vec<Arc<InputRecord>> = vec![
Arc::new(make_record(&w, 100, alleles, gt, Some(100))),
Arc::new(make_record(&w, 105, alleles, gt, Some(100))),
Arc::new(make_record(&w, 110, alleles, gt, Some(100))),
];
let sub = split_into_haplotype_clusters(&records, &default_settings()).unwrap();
assert_eq!(sub.len(), 1);
let h1 = sub.iter().find(|sc| sc.haplo == Haplotype::H1).unwrap();
assert_eq!(h1.phaseset, Some(100));
assert_eq!(h1.records.len(), 3);
}
#[test]
fn split_mixed_haplotypes_with_hom_alt() {
let h = make_header();
let w = make_writer(&h);
let r01 = Arc::new(make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)],
Some(100),
));
let r10 = Arc::new(make_record(
&w,
105,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(1), GenotypeAllele::Phased(0)],
Some(100),
));
let r11 = Arc::new(make_record(
&w,
108,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)],
None,
));
let mut settings = default_settings();
settings.min_records = Some(1);
let records = vec![r01, r10, r11];
let sub = split_into_haplotype_clusters(&records, &settings).unwrap();
let haps: Vec<Haplotype> = sub.iter().map(|sc| sc.haplo).collect();
assert!(haps.contains(&Haplotype::H0));
assert!(haps.contains(&Haplotype::H1));
assert!(
!haps.contains(&Haplotype::Both),
"split mode emits no `Both`"
);
let containing: Vec<&HaplotypeSubCluster> = sub
.iter()
.filter(|sc| sc.records.iter().any(|(r, _)| r.pos() == 108))
.collect();
assert_eq!(containing.len(), 2, "hom-alt folds onto both haplotypes");
let containing_haps: Vec<Haplotype> = containing.iter().map(|sc| sc.haplo).collect();
assert!(containing_haps.contains(&Haplotype::H0));
assert!(containing_haps.contains(&Haplotype::H1));
let h0 = sub.iter().find(|sc| sc.haplo == Haplotype::H0).unwrap();
assert!(h0.records.iter().any(|(r, _)| r.pos() == 105));
let h1 = sub.iter().find(|sc| sc.haplo == Haplotype::H1).unwrap();
assert!(h1.records.iter().any(|(r, _)| r.pos() == 100));
}
#[test]
fn hom_alt_context_rescues_gap_split() {
let h = make_header();
let w = make_writer(&h);
let gt10 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Phased(0)];
let gt11 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
let r1 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt10, Some(100)));
let rhom = Arc::new(make_record(&w, 118, &[b"A", b"T"], gt11, None));
let r2 = Arc::new(make_record(&w, 136, &[b"A", b"T"], gt10, Some(100)));
let mut settings = default_settings();
settings.min_records = Some(1);
settings.min_density = 0.0; let sub = split_into_haplotype_clusters(&[r1, rhom, r2], &settings).unwrap();
let h0: Vec<_> = sub.iter().filter(|sc| sc.haplo == Haplotype::H0).collect();
assert_eq!(
h0.len(),
1,
"hom-alt context keeps H0 hets in one sub-cluster"
);
assert_eq!(h0[0].records.len(), 3);
assert!(!sub.iter().any(|sc| sc.haplo == Haplotype::Both));
}
#[test]
fn pure_hom_alt_emits_both_once() {
let h = make_header();
let w = make_writer(&h);
let gt11 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
let r1 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt11, None));
let r2 = Arc::new(make_record(&w, 108, &[b"A", b"T"], gt11, None));
let mut settings = default_settings();
settings.min_records = Some(1);
let sub = split_into_haplotype_clusters(&[r1, r2], &settings).unwrap();
assert!(sub.iter().all(|sc| sc.haplo == Haplotype::Both));
for pos in [100, 108] {
let n = sub
.iter()
.filter(|sc| sc.records.iter().any(|(r, _)| r.pos() == pos))
.count();
assert_eq!(n, 1, "pure hom-alt must emit exactly once");
}
}
#[test]
fn hom_alt_split_lone_on_other_hap() {
let h = make_header();
let w = make_writer(&h);
let gt10 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Phased(0)];
let gt01 = &[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)];
let gt11 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
let r_h0 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt10, Some(100)));
let r_hom = Arc::new(make_record(&w, 110, &[b"A", b"T"], gt11, None));
let r_h1 = Arc::new(make_record(&w, 500, &[b"A", b"T"], gt01, Some(100)));
let mut settings = default_settings();
settings.min_records = Some(1);
settings.min_density = 0.0; let sub = split_into_haplotype_clusters(&[r_h0, r_hom, r_h1], &settings).unwrap();
assert!(!sub.iter().any(|sc| sc.haplo == Haplotype::Both));
let h0 = sub.iter().find(|sc| sc.haplo == Haplotype::H0).unwrap();
assert!(h0.records.iter().any(|(r, _)| r.pos() == 100));
assert!(h0.records.iter().any(|(r, _)| r.pos() == 110));
assert!(
sub.iter()
.any(|sc| sc.haplo == Haplotype::H1
&& sc.records.iter().any(|(r, _)| r.pos() == 110))
);
assert!(
sub.iter()
.any(|sc| sc.haplo == Haplotype::H1
&& sc.records.iter().any(|(r, _)| r.pos() == 500))
);
}
#[test]
fn multi_phaseset_hom_alt_blocks_cluster() {
let h = make_header();
let w = make_writer(&h);
let gt01 = &[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)];
let gt11 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
let ps_a = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt01, Some(100)));
let hom = Arc::new(make_record(&w, 110, &[b"A", b"T"], gt11, None));
let ps_b = Arc::new(make_record(&w, 120, &[b"A", b"T"], gt01, Some(999)));
let mut settings = default_settings();
settings.min_records = Some(1);
settings.min_density = 0.0; let sub = split_into_haplotype_clusters(&[ps_a, hom, ps_b], &settings);
assert!(
matches!(sub, Err(SplitIntoHaplotypesError::HomAcrossPhaseSets)),
"{sub:#?}"
);
}
#[test]
fn singleton_unphased_het_with_hom_alt_resolved() {
let h = make_header();
let w = make_writer(&h);
let gt01 = &[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)];
let gt11 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
let r01 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt01, None));
let r11 = Arc::new(make_record(&w, 105, &[b"A", b"T"], gt11, None));
let mut settings = default_settings();
settings.min_records = Some(1);
let sub = split_into_haplotype_clusters(&[r01, r11], &settings).unwrap();
assert!(!sub.iter().any(|sc| sc.haplo == Haplotype::Both));
assert!(sub.iter().all(|sc| sc.phaseset.is_some()), "{sub:#?}");
let h0 = sub.iter().find(|sc| sc.haplo == Haplotype::H0).unwrap();
assert_eq!(h0.records.len(), 1);
assert!(h0.records.iter().any(|(r, _)| r.pos() == 105));
let h1 = sub.iter().find(|sc| sc.haplo == Haplotype::H1).unwrap();
assert_eq!(h1.records.len(), 2);
assert!(h1.records.iter().any(|(r, _)| r.pos() == 100));
assert!(h1.records.iter().any(|(r, _)| r.pos() == 105));
}
#[test]
fn singleton_unphased_het_with_hom_ref_only_no_resolution() {
let h = make_header();
let w = make_writer(&h);
let gt01 = &[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)];
let gt00 = &[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(0)];
let r01 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt01, None));
let r00 = Arc::new(make_record(&w, 105, &[b"A", b"T"], gt00, None));
let mut settings = default_settings();
settings.min_records = Some(1);
let sub = split_into_haplotype_clusters(&[r01, r00], &settings).unwrap();
dbg!(&sub);
assert_eq!(sub.len(), 1);
assert_eq!(sub[0].haplo, Haplotype::H1);
assert!(sub[0].phaseset.is_some());
assert!(sub[0].records.iter().any(|(r, _)| r.pos() == 100));
}
#[test]
fn is_trivially_resolvable_single_record() {
let h = make_header();
let w = make_writer(&h);
let gt01 = &[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)];
let r = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt01, None));
assert!(is_trivially_resolvable(&[r]));
}
#[test]
fn is_trivially_resolvable_singleton_with_hom_alt() {
let h = make_header();
let w = make_writer(&h);
let gt01 = &[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)];
let gt11 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
let r01 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt01, None));
let r11 = Arc::new(make_record(&w, 105, &[b"A", b"T"], gt11, None));
assert!(is_trivially_resolvable(&[r01, r11]));
}
#[test]
fn is_trivially_resolvable_false_for_two_unphased_hets() {
let h = make_header();
let w = make_writer(&h);
let gt01 = &[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)];
let r1 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt01, None));
let r2 = Arc::new(make_record(&w, 105, &[b"A", b"T"], gt01, None));
assert!(!is_trivially_resolvable(&[r1, r2]));
}
#[test]
fn is_trivially_resolvable_false_for_unphased_het_with_phased_anchor() {
let h = make_header();
let w = make_writer(&h);
let r01 = Arc::new(make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)],
Some(100),
));
let r_unphased = Arc::new(make_record(
&w,
105,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)],
None,
));
assert!(!is_trivially_resolvable(&[r01, r_unphased]));
}
#[test]
fn is_trivially_resolvable_false_for_missing_allele() {
let h = make_header();
let w = make_writer(&h);
let gt11 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
let r11 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt11, None));
let r_missing = Arc::new(make_record(
&w,
105,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(1), GenotypeAllele::UnphasedMissing],
None,
));
assert!(!is_trivially_resolvable(&[r11, r_missing]));
}
#[test]
fn split_hom_alt_with_half_called_het_blocks_cluster() {
let h = make_header();
let w = make_writer(&h);
let gt11 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
let r11 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt11, None));
let r_missing = Arc::new(make_record(
&w,
105,
&[b"A", b"T"],
&[GenotypeAllele::UnphasedMissing, GenotypeAllele::Unphased(1)],
None,
));
let sub = split_into_haplotype_clusters(&[r11, r_missing], &default_settings());
assert!(
matches!(sub, Err(SplitIntoHaplotypesError::MissingAllele)),
"{sub:#?}"
);
}
#[test]
fn split_unphased_het_with_phased_blocks_cluster() {
let h = make_header();
let w = make_writer(&h);
let r01 = Arc::new(make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)],
Some(100),
));
let r_unphased = Arc::new(make_record(
&w,
105,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)],
None,
));
let records = vec![r01, r_unphased];
let sub = split_into_haplotype_clusters(&records, &default_settings());
assert!(
matches!(sub, Err(SplitIntoHaplotypesError::MoreThanOneUnphasedHet)),
"UnphasedHet + Phased should block"
);
}
#[test]
fn split_two_unphased_hets_blocks_cluster() {
let h = make_header();
let w = make_writer(&h);
let gt_unphased = &[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)];
let r1 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt_unphased, None));
let r2 = Arc::new(make_record(&w, 105, &[b"A", b"T"], gt_unphased, None));
let records = vec![r1, r2];
let sub = split_into_haplotype_clusters(&records, &default_settings());
assert!(
matches!(sub, Err(SplitIntoHaplotypesError::MoreThanOneUnphasedHet)),
"two UnphasedHet records should block"
);
}
#[test]
fn split_single_unphased_het_is_realigned() {
let h = make_header();
let w = make_writer(&h);
let mut settings = default_settings();
settings.min_records = Some(1);
let r = make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)],
None,
);
let sub = split_into_haplotype_clusters(&[Arc::new(r)], &settings).unwrap();
assert_eq!(sub.len(), 1);
assert_eq!(sub[0].haplo, Haplotype::H1);
assert_eq!(sub[0].phaseset, Some(101));
}
#[test]
fn sub_clusters_of_several_phasesets_come_in_ascending_phaseset_order() {
let h = make_header();
let w = make_writer(&h);
let gt = &[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)];
let phasesets = [100, 900, 300, 700, 200, 800, 400, 600];
let records: Vec<_> = phasesets
.iter()
.zip((100..).step_by(5))
.map(|(&ps, pos)| Arc::new(make_record(&w, pos, &[b"A", b"T"], gt, Some(ps))))
.collect();
let mut settings = default_settings();
settings.min_records = Some(1);
settings.min_density = 0.0;
let sub = split_into_haplotype_clusters(&records, &settings).unwrap();
let mut order: Vec<i32> = sub.iter().filter_map(|sc| sc.phaseset).collect();
order.dedup();
let mut expected = phasesets.to_vec();
expected.sort_unstable();
assert_eq!(order, expected);
}
#[test]
fn split_different_phasesets() {
let h = make_header();
let w = make_writer(&h);
let gt = &[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)];
let r1 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt, Some(100)));
let r2 = Arc::new(make_record(&w, 105, &[b"A", b"T"], gt, Some(999)));
let mut settings = default_settings();
settings.min_records = Some(1); let records = vec![r1, r2];
let sub = split_into_haplotype_clusters(&records, &settings).unwrap();
let psets: Vec<i32> = sub.iter().filter_map(|sc| sc.phaseset).collect();
assert!(psets.contains(&100));
assert!(psets.contains(&999));
}
#[test]
fn split_gap_introduced_by_removing_other_haplotype() {
let h = make_header();
let w = make_writer(&h);
let gt01 = &[GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1)];
let gt10 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Phased(0)];
let r1 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt01, Some(100)));
let r2 = Arc::new(make_record(&w, 110, &[b"A", b"T"], gt10, Some(100)));
let r3 = Arc::new(make_record(&w, 200, &[b"A", b"T"], gt01, Some(100)));
let mut settings = default_settings();
settings.min_records = Some(1);
let records = vec![r1, r2, r3];
let sub = split_into_haplotype_clusters(&records, &settings).unwrap();
let hap1_clusters = sub.iter().filter(|sc| sc.haplo == Haplotype::H1).count();
assert_eq!(
hap1_clusters, 2,
"gap should split hap=1 into two sub-clusters"
);
}
#[test]
fn test_single_unphased_outputs_valid_clusters() {
let h = make_header();
let w = make_writer(&h);
let gt01 = &[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)];
let gt11 = &[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
let r1 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt01, None));
let r2 = Arc::new(make_record(&w, 103, &[b"A", b"T"], gt11, None));
let records = vec![r1, r2];
let sub = split_into_haplotype_clusters(&records, &default_settings()).unwrap();
let mut sizes: Vec<_> = sub.iter().map(|s| s.records.len()).collect();
sizes.sort_unstable();
assert_eq!(sizes, [1, 2], "{sub:#?}");
let lone = sub.iter().find(|s| s.records.len() == 1).unwrap();
assert_eq!(lone.records[0].0.pos(), 103, "the lone record is the hom");
}
#[test]
fn haploid_gt_is_parsed() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(&w, 100, &[b"A", b"T"], &[GenotypeAllele::Unphased(1)], None);
assert_eq!(rec.gt(), Genotype::Haploid(Allele(Some(1))));
assert!(rec.gt().has_alt());
assert!(!rec.gt().is_unphased_het());
}
#[test]
fn haploid_cluster_is_one_haploid_subcluster() {
let h = make_header();
let w = make_writer(&h);
let gt1 = &[GenotypeAllele::Unphased(1)];
let r1 = Arc::new(make_record(&w, 100, &[b"A", b"T"], gt1, None));
let r2 = Arc::new(make_record(&w, 105, &[b"A", b"T"], gt1, None));
assert!(is_trivially_resolvable(&[r1.clone(), r2.clone()]));
let sub = split_into_haplotype_clusters(&[r1, r2], &default_settings()).unwrap();
assert_eq!(sub.len(), 1, "{sub:#?}");
assert_eq!(sub[0].haplo, Haplotype::Haploid);
assert_eq!(sub[0].phaseset, None);
assert_eq!(sub[0].records.len(), 2);
}
#[test]
fn mixed_ploidy_is_rejected() {
let h = make_header();
let w = make_writer(&h);
let r1 = Arc::new(make_record(
&w,
100,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(1)],
None,
));
let r2 = Arc::new(make_record(
&w,
105,
&[b"A", b"T"],
&[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)],
None,
));
assert!(matches!(
split_into_haplotype_clusters(&[r1, r2], &default_settings()),
Err(SplitIntoHaplotypesError::MixedPloidy)
));
}
#[test]
fn changes_false_for_identical_haploid() {
let h = make_header();
let w = make_writer(&h);
let rec = make_record(&w, 100, &[b"A", b"T"], &[GenotypeAllele::Unphased(1)], None);
let op = OutputPhasing::from_subcluster(Haplotype::Haploid, None);
assert!(!op.changes(&rec, 1));
assert_eq!(op.written_phaseset(), None);
}
#[test]
fn flank_allele_follows_the_sub_clusters_haplotype() {
use super::{FlankAllele, flank_allele};
use FlankAllele::{Apply, Ref, Unknown};
use Haplotype::{Both, H0, H1, Haploid};
let diploid = |a0, a1, phase| Genotype::Diploid {
alleles: [Allele(a0), Allele(a1)],
phase,
};
let hom = diploid(Some(1), Some(1), Phase::Unphased);
let phased_hom = diploid(Some(2), Some(2), Phase::Phased(9));
let het = diploid(Some(0), Some(1), Phase::Unphased);
let ps7 = diploid(Some(1), Some(0), Phase::Phased(7));
let ps7_multi = diploid(Some(1), Some(2), Phase::Phased(7));
let ps7_missing = diploid(None, Some(1), Phase::Phased(7));
let no_ps = diploid(Some(0), Some(1), Phase::Phased(i32::MIN));
let haploid = Genotype::Haploid(Allele(Some(1)));
let cases = [
(hom, H0, None, Apply(1)),
(hom, Both, None, Apply(1)),
(phased_hom, H1, Some(7), Apply(2)),
(hom, Haploid, None, Apply(1)),
(ps7, H0, Some(7), Apply(1)),
(ps7, H1, Some(7), Ref),
(ps7_multi, H1, Some(7), Apply(2)),
(ps7_missing, H0, Some(7), Unknown),
(ps7_missing, H1, Some(7), Apply(1)),
(ps7, H0, Some(8), Unknown),
(ps7, H0, None, Unknown),
(het, H0, None, Unknown),
(no_ps, H1, Some(i32::MIN), Apply(1)),
(ps7, Both, Some(7), Unknown),
(haploid, Haploid, None, Apply(1)),
(ps7, Haploid, None, Unknown),
(haploid, H0, None, Unknown),
];
for (flank, haplo, phaseset, expected) in cases {
assert_eq!(
flank_allele(flank, haplo, phaseset),
expected,
"{flank:?} on {haplo:?} with phase set {phaseset:?}"
);
}
}
#[test]
fn input_phasesets_ignores_synthetic_phase_sets() {
use GenotypeAllele::{Phased, Unphased};
let h = make_header();
let w = make_writer(&h);
let anchor = make_record(&w, 100, &[b"A", b"T"], &[Phased(0), Phased(1)], Some(5));
let hom = make_record(&w, 105, &[b"A", b"T"], &[Phased(1), Phased(1)], Some(9));
let resolved = make_record(&w, 110, &[b"A", b"T"], &[Unphased(0), Unphased(1)], None)
.with_local_gt(Genotype::Diploid {
alleles: [Allele(Some(1)), Allele(Some(0))],
phase: Phase::Phased(111),
});
let cluster: Vec<_> = [anchor, hom, resolved].into_iter().map(Arc::new).collect();
assert_eq!(input_phasesets(&cluster), [5]);
}
}