use serde_json::{Value, json};
use crate::damage::{PatternCounts, SiteCount};
use crate::sites::{Library, Treatment};
pub const MIN_SITES: u64 = 500;
const MIN_Z: f64 = 5.0;
const LIBRARY_MIN_DIFFERENCE: f64 = 0.005;
const LIBRARY_MIN_RATIO: f64 = 2.0;
const DAMAGED_MIN_EXCESS: f64 = 0.04;
const HALF_MAX_RATIO: f64 = 0.15;
const NONE_MIN_RATIO: f64 = 0.35;
const FULL_MAX_EXCESS: f64 = 0.02;
const FULL_MIN_CPG_DIFFERENCE: f64 = 0.02;
const FULL_MIN_CPG_RATIO: f64 = 3.0;
fn z(a: SiteCount, b: SiteCount) -> f64 {
let (x, y) = (a.rate().unwrap_or(f64::NAN), b.rate().unwrap_or(f64::NAN));
let se = (x * (1.0 - x) / a.sites as f64 + y * (1.0 - y) / b.sites as f64).sqrt();
(x - y) / se
}
fn library_test(c_to_t: SiteCount, g_to_a: SiteCount) -> Option<Library> {
let (Some(x), Some(y)) = (c_to_t.rate(), g_to_a.rate()) else {
return None;
};
if c_to_t.sites < MIN_SITES || g_to_a.sites < MIN_SITES {
return None;
}
let z = z(c_to_t, g_to_a);
if x - y >= LIBRARY_MIN_DIFFERENCE && x >= LIBRARY_MIN_RATIO * y && z >= MIN_Z {
Some(Library::SingleStranded)
} else if y - x >= LIBRARY_MIN_DIFFERENCE && y >= LIBRARY_MIN_RATIO * x && -z >= MIN_Z {
Some(Library::DoubleStranded)
} else {
None
}
}
pub fn library_pattern(
terminal: (SiteCount, SiteCount),
cpg: (SiteCount, SiteCount),
) -> (Option<Library>, bool) {
match (
library_test(terminal.0, terminal.1),
library_test(cpg.0, cpg.1),
) {
(Some(a), Some(b)) if a != b => (None, false),
(Some(a), _) => (Some(a), false),
(None, b) => (b, b.is_some()),
}
}
pub fn treatment_pattern(
first: SiteCount,
second: SiteCount,
background: SiteCount,
first_cpg: SiteCount,
) -> Option<Treatment> {
if [first, second, background]
.iter()
.any(|c| c.sites < MIN_SITES)
{
return None;
}
let (p0, p1, b) = (first.rate()?, second.rate()?, background.rate()?);
let (e0, e1) = (p0 - b, p1 - b);
if e0 >= DAMAGED_MIN_EXCESS {
let r = e1 / e0;
return if r < HALF_MAX_RATIO {
Some(Treatment::Half)
} else if r > NONE_MIN_RATIO {
Some(Treatment::None)
} else {
None
};
}
let c0 = first_cpg.rate()?;
(e0 < FULL_MAX_EXCESS
&& first_cpg.sites >= MIN_SITES
&& c0 - p0 >= FULL_MIN_CPG_DIFFERENCE
&& c0 >= FULL_MIN_CPG_RATIO * p0
&& z(first_cpg, first) >= MIN_Z)
.then_some(Treatment::Full)
}
fn library_name(l: Library) -> &'static str {
match l {
Library::DoubleStranded => "ds",
Library::SingleStranded => "ss",
}
}
fn treatment_name(t: Treatment) -> &'static str {
match t {
Treatment::None => "none",
Treatment::Half => "half",
Treatment::Full => "full",
}
}
fn percent(c: SiteCount) -> String {
format!("{:.1}%", 100.0 * c.rate().unwrap_or(0.0))
}
pub struct ModeCheck {
counts: PatternCounts,
library: Library,
treatment: Treatment,
pub library_pattern: Option<Library>,
pub library_by_cpg: bool,
pub treatment_pattern: Option<Treatment>,
}
impl ModeCheck {
pub fn new(counts: &PatternCounts, library: Library, treatment: Treatment) -> ModeCheck {
let (library_pattern, library_by_cpg) = library_pattern(
(counts.three_prime_c, counts.three_prime_g),
(counts.three_prime_cpg_c, counts.three_prime_cpg_g),
);
let treatment_pattern = treatment_pattern(
counts.five_prime_first,
counts.five_prime_second,
counts.five_prime_background,
counts.five_prime_cpg,
);
ModeCheck {
counts: *counts,
library,
treatment,
library_pattern,
library_by_cpg,
treatment_pattern,
}
}
pub fn library_agrees(&self) -> Option<bool> {
self.library_pattern.map(|p| p == self.library)
}
pub fn treatment_agrees(&self) -> Option<bool> {
self.treatment_pattern.map(|p| p == self.treatment)
}
pub fn to_json(&self) -> Value {
let c = &self.counts;
json!({
"library": {
"pattern": self.library_pattern.map(library_name),
"agrees": self.library_agrees(),
"three_prime_c_to_t": c.three_prime_c.rate(),
"three_prime_g_to_a": c.three_prime_g.rate(),
"c_sites": c.three_prime_c.sites,
"g_sites": c.three_prime_g.sites,
"cpg_c_to_t": c.three_prime_cpg_c.rate(),
"cpg_g_to_a": c.three_prime_cpg_g.rate(),
"cpg_sites": c.three_prime_cpg_c.sites.min(c.three_prime_cpg_g.sites),
},
"treatment": {
"pattern": self.treatment_pattern.map(treatment_name),
"agrees": self.treatment_agrees(),
"first_base": c.five_prime_first.rate(),
"second_base": c.five_prime_second.rate(),
"background": c.five_prime_background.rate(),
"sites": c.five_prime_first.sites,
"first_base_cpg": c.five_prime_cpg.rate(),
"cpg_sites": c.five_prime_cpg.sites,
},
})
}
pub fn notes(&self) -> Vec<String> {
let c = &self.counts;
let mut notes = Vec::new();
if let (Some(pattern), Some(false)) = (self.library_pattern, self.library_agrees()) {
let (ct, ga, place) = if self.library_by_cpg {
(
c.three_prime_cpg_c,
c.three_prime_cpg_g,
"at CpG sites the 3′ ends show",
)
} else {
(c.three_prime_c, c.three_prime_g, "the 3′ ends show")
};
let (more, less, kind) = match pattern {
Library::SingleStranded => (
format!("C→T ({})", percent(ct)),
format!("G→A ({})", percent(ga)),
"single",
),
Library::DoubleStranded => (
format!("G→A ({})", percent(ga)),
format!("C→T ({})", percent(ct)),
"double",
),
};
notes.push(format!(
"{place} {more} more than {less}, as {kind}-stranded libraries do; the reads were \
scored as --library {}",
library_name(self.library)
));
}
if let (Some(pattern), Some(false)) = (self.treatment_pattern, self.treatment_agrees()) {
let (p0, p1) = (percent(c.five_prime_first), percent(c.five_prime_second));
let seen = match pattern {
Treatment::Full => format!(
"5′ C→T at the first base is {} at CpG sites but {p0} elsewhere, as after full \
UDG treatment",
percent(c.five_prime_cpg)
),
Treatment::Half => format!(
"5′ C→T outside CpG sites is {p0} at the first base but {p1} at the second, as \
after UDG-half treatment"
),
Treatment::None => format!(
"5′ C→T outside CpG sites is {p0} at the first base and {p1} at the second, as \
in untreated libraries"
),
};
notes.push(format!(
"{seen}; the reads were scored as --treatment {}",
treatment_name(self.treatment)
));
}
notes
}
}
#[cfg(test)]
mod tests {
use super::*;
fn count(rate: f64, n: u64) -> SiteCount {
SiteCount {
sites: n,
changed: (rate * n as f64).round() as u64,
}
}
const N: u64 = 20_000;
fn treatment(p0: f64, p1: f64, b: f64, c0: f64) -> Option<Treatment> {
treatment_pattern(count(p0, N), count(p1, N), count(b, N), count(c0, N))
}
fn library(ct: f64, ga: f64, cpg_ct: f64, cpg_ga: f64) -> Option<Library> {
library_pattern(
(count(ct, N), count(ga, N)),
(count(cpg_ct, N), count(cpg_ga, N)),
)
.0
}
#[test]
fn treatment_of_real_libraries() {
use Treatment as T;
for (name, [p0, p1, b, c0], want) in [
(
"untreated ds BER11_NOuser",
[0.181, 0.120, 0.033, 0.197],
Some(T::None),
),
(
"untreated ss UKY001",
[0.258, 0.149, 0.048, 0.194],
Some(T::None),
),
(
"untreated ss wolf",
[0.177, 0.107, 0.037, 0.206],
Some(T::None),
),
(
"half ss I19359",
[0.225, 0.0036, 0.0021, 0.297],
Some(T::Half),
),
(
"full ds BER11_USER",
[0.0019, 0.0018, 0.0015, 0.062],
Some(T::Full),
),
(
"full ds Motala3",
[0.0037, 0.0019, 0.0010, 0.197],
Some(T::Full),
),
("JK2067", [0.0096, 0.0030, 0.0010, 0.0165], None),
("modern NA12878", [0.0012, 0.0013, 0.0016, 0.003], None),
] {
assert_eq!(treatment(p0, p1, b, c0), want, "{name}");
}
let zku = |n: u64, cpg: u64| {
treatment_pattern(
count(0.18, n),
count(0.11, n),
count(0.035, 5 * n),
count(0.2, cpg),
)
};
assert_eq!(zku(6_600, 535), Some(T::None));
}
#[test]
fn library_of_real_libraries() {
use Library::*;
let no_b = (0.0, 0.0);
for (name, a, b, want) in [
("ss UKY001", (0.178, 0.013), no_b, Some(SingleStranded)),
("ss I19359", (0.20, 0.004), no_b, Some(SingleStranded)),
(
"ds BER11_NOuser",
(0.011, 0.126),
no_b,
Some(DoubleStranded),
),
("ds JK2067", (0.0037, 0.0129), no_b, Some(DoubleStranded)),
("ds Motala3", (0.0021, 0.0138), no_b, Some(DoubleStranded)),
(
"BER11_USER",
(0.0023, 0.0047),
(0.0097, 0.0426),
Some(DoubleStranded),
),
("NA12878", (0.0015, 0.0009), (0.0026, 0.0034), None),
] {
assert_eq!(library(a.0, a.1, b.0, b.1), want, "{name}");
}
assert_eq!(library_test(count(0.0023, N), count(0.0047, N)), None);
let (pattern, by_cpg) = library_pattern(
(count(0.0023, N), count(0.0047, N)),
(count(0.0097, N), count(0.0426, N)),
);
assert_eq!((pattern, by_cpg), (Some(DoubleStranded), true));
}
#[test]
fn library_boundaries() {
use Library::*;
let n = 1_000_000; let test = |x: f64, y: f64| library_test(count(x, n), count(y, n));
assert_eq!(test(0.0051, 0.0), Some(SingleStranded));
assert_eq!(test(0.0049, 0.0), None);
assert_eq!(test(0.0, 0.0051), Some(DoubleStranded));
assert_eq!(test(0.202, 0.1), Some(SingleStranded));
assert_eq!(test(0.198, 0.1), None);
assert_eq!(test(0.1, 0.202), Some(DoubleStranded));
let few = |n: u64| library_test(count(0.03, n), count(0.01, n));
assert_eq!(few(20_000), Some(SingleStranded));
assert_eq!(few(1_000), None); assert_eq!(library_test(count(0.5, 499), count(0.0, n)), None);
assert_eq!(library_test(count(0.5, n), count(0.0, 499)), None);
assert_eq!(
library_test(count(0.5, 500), count(0.0, 500)),
Some(SingleStranded)
);
assert_eq!(
library_test(SiteCount::default(), SiteCount::default()),
None
);
}
#[test]
fn library_tests_combine() {
use Library::*;
let ss = (count(0.2, N), count(0.01, N));
let ds = (count(0.01, N), count(0.2, N));
let none = (count(0.002, N), count(0.002, N));
assert_eq!(library_pattern(ss, none), (Some(SingleStranded), false));
assert_eq!(library_pattern(ss, ss), (Some(SingleStranded), false));
assert_eq!(library_pattern(none, ds), (Some(DoubleStranded), true));
assert_eq!(library_pattern(none, none), (None, false));
assert_eq!(library_pattern(ss, ds), (None, false));
assert_eq!(library_pattern(ds, ss), (None, false));
}
#[test]
fn treatment_boundaries() {
use Treatment as T;
let t = |p0: f64, p1: f64, b: f64, c0: f64| {
let n = 1_000_000;
treatment_pattern(count(p0, n), count(p1, n), count(b, n), count(c0, n))
};
assert_eq!(t(0.051, 0.03, 0.01, 0.05), Some(T::None));
assert_eq!(t(0.049, 0.03, 0.01, 0.05), None);
assert_eq!(t(0.11, 0.024, 0.01, 0.1), Some(T::Half));
assert_eq!(t(0.11, 0.026, 0.01, 0.1), None);
assert_eq!(t(0.11, 0.044, 0.01, 0.1), None);
assert_eq!(t(0.11, 0.046, 0.01, 0.1), Some(T::None));
assert_eq!(t(0.02, 0.0, 0.001, 0.1), Some(T::Full));
assert_eq!(t(0.022, 0.0, 0.001, 0.1), None);
assert_eq!(t(0.005, 0.005, 0.005, 0.026), Some(T::Full));
assert_eq!(t(0.005, 0.005, 0.005, 0.024), None);
assert_eq!(t(0.015, 0.015, 0.015, 0.046), Some(T::Full));
assert_eq!(t(0.015, 0.015, 0.015, 0.044), None);
assert_eq!(t(0.001, 0.001, 0.001, 0.001), None);
}
#[test]
fn treatment_needs_min_sites() {
use Treatment as T;
let c = |rate: f64, n: u64| count(rate, n);
let half = |n0: u64, n1: u64, nb: u64| {
treatment_pattern(c(0.225, n0), c(0.0036, n1), c(0.0021, nb), c(0.297, 0))
};
assert_eq!(
half(N, N, N),
Some(T::Half),
"CpG sites are not needed for half"
);
assert_eq!(half(499, N, N), None);
assert_eq!(half(N, 499, N), None);
assert_eq!(half(N, N, 499), None);
let full =
|ncpg: u64| treatment_pattern(c(0.0037, N), c(0.0019, N), c(0.001, N), c(0.197, ncpg));
assert_eq!(full(500), Some(T::Full));
assert_eq!(full(499), None);
let weak = treatment_pattern(c(0.01, 600), c(0.01, N), c(0.01, N), c(0.04, 600));
assert_eq!(weak, None);
}
fn counts(ct: f64, ga: f64, p0: f64, p1: f64, b: f64, c0: f64) -> PatternCounts {
PatternCounts {
three_prime_c: count(ct, N),
three_prime_g: count(ga, N),
five_prime_first: count(p0, N),
five_prime_second: count(p1, N),
five_prime_background: count(b, 5 * N),
five_prime_cpg: count(c0, N),
..PatternCounts::default()
}
}
#[test]
fn pattern_names_are_frozen() {
let libraries = [Library::DoubleStranded, Library::SingleStranded].map(library_name);
assert_eq!(libraries, ["ds", "ss"]);
let treatments = [Treatment::None, Treatment::Half, Treatment::Full].map(treatment_name);
assert_eq!(treatments, ["none", "half", "full"]);
}
#[test]
fn notes_and_json_for_disagreements() {
let uky = counts(0.178, 0.013, 0.258, 0.149, 0.048, 0.194);
let m = ModeCheck::new(&uky, Library::DoubleStranded, Treatment::None);
assert_eq!(
m.notes(),
[
"the 3′ ends show C→T (17.8%) more than G→A (1.3%), as single-stranded libraries \
do; the reads were scored as --library ds"
]
);
let j = m.to_json();
assert_eq!(j["library"]["pattern"], "ss");
assert_eq!(j["library"]["agrees"], false);
assert_eq!(j["library"]["c_sites"], N);
assert_eq!(j["library"]["cpg_c_to_t"], Value::Null);
assert_eq!(j["library"]["cpg_sites"], 0);
assert_eq!(j["treatment"]["pattern"], "none");
assert_eq!(j["treatment"]["agrees"], true);
assert_eq!(j["treatment"]["sites"], N);
assert_eq!(j["treatment"]["background"], 0.048);
assert!(
ModeCheck::new(&uky, Library::SingleStranded, Treatment::None)
.notes()
.is_empty()
);
let mut user = counts(0.0023, 0.0047, 0.0019, 0.0018, 0.0015, 0.062);
user.three_prime_cpg_c = count(0.0097, N);
user.three_prime_cpg_g = count(0.0426, N);
let m = ModeCheck::new(&user, Library::SingleStranded, Treatment::None);
assert_eq!(
m.notes(),
[
"at CpG sites the 3′ ends show G→A (4.3%) more than C→T (1.0%), as \
double-stranded libraries do; the reads were scored as --library ss",
"5′ C→T at the first base is 6.2% at CpG sites but 0.2% elsewhere, as after full \
UDG treatment; the reads were scored as --treatment none",
]
);
assert_eq!(m.to_json()["library"]["cpg_sites"], N);
let half = counts(0.20, 0.004, 0.225, 0.0036, 0.0021, 0.297);
let m = ModeCheck::new(&half, Library::SingleStranded, Treatment::None);
assert_eq!(
m.notes(),
[
"5′ C→T outside CpG sites is 22.5% at the first base but 0.4% at the second, as \
after UDG-half treatment; the reads were scored as --treatment none"
]
);
let none = counts(0.011, 0.126, 0.181, 0.120, 0.033, 0.197);
let m = ModeCheck::new(&none, Library::DoubleStranded, Treatment::Half);
assert_eq!(
m.notes(),
[
"5′ C→T outside CpG sites is 18.1% at the first base and 12.0% at the second, as in \
untreated libraries; the reads were scored as --treatment half"
]
);
let m = ModeCheck::new(
&PatternCounts::default(),
Library::DoubleStranded,
Treatment::None,
);
assert!(m.notes().is_empty());
let j = m.to_json();
for side in ["library", "treatment"] {
assert_eq!(j[side]["pattern"], Value::Null);
assert_eq!(j[side]["agrees"], Value::Null);
}
assert_eq!(j["library"]["three_prime_c_to_t"], Value::Null);
assert_eq!(j["treatment"]["first_base"], Value::Null);
assert_eq!(j["treatment"]["background"], Value::Null);
assert_eq!(j["treatment"]["sites"], 0);
}
}