From ef0fbeca38af3bf63717e52f5caed4d477849cba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rayan=20Hassa=C3=AFne?= Date: Thu, 26 Nov 2026 16:59:12 +0100 Subject: [PATCH] fix(dupradar): write the MultiQC files as the nf-core dupradar module does The nf-core module writes _dup_intercept_mqc.txt and _duprateExpDensCurve_mqc.txt from its R template: its own YAML headers, space-separated values with 15 significant digits, and the curve as the fitted duplication rate (%) at every 10th expressed gene sorted by RPK. RustQC wrote different headers, tab-separated values and 101 evenly spaced points. Write both files in the template's layout. The fit itself is unchanged, so the numbers can differ from R's in the last digits. Co-Authored-By: Claude Opus 5.5 --- docs/src/content/docs/rna/dupradar.mdx | 6 +- docs/src/content/docs/usage/configuration.md | 2 +- src/rna/dupradar/dupmatrix.rs | 2 +- src/rna/dupradar/plots.rs | 206 ++++++++++++++----- tests/integration_test.rs | 82 ++++---- 5 files changed, 198 insertions(+), 100 deletions(-) diff --git a/docs/src/content/docs/rna/dupradar.mdx b/docs/src/content/docs/rna/dupradar.mdx index 3cc2ada8..28a9a712 100644 --- a/docs/src/content/docs/rna/dupradar.mdx +++ b/docs/src/content/docs/rna/dupradar.mdx @@ -171,10 +171,10 @@ See the [Interpreting plots](#interpreting-plots) section below for how to read ### MultiQC files -- `_dup_intercept_mqc.txt` -- Intercept and slope values in MultiQC general statistics format. -- `_duprateExpDensCurve_mqc.txt` -- Fitted duplication rate curve data points for MultiQC line plot visualization. +- `_dup_intercept_mqc.txt` -- The intercept in MultiQC general statistics format (`dupInt` column). +- `_duprateExpDensCurve_mqc.txt` -- The fitted duplication rate (%) at every 10th expressed gene, sorted by RPK, for the MultiQC line plot. -These files integrate with [MultiQC](https://multiqc.info/) for inclusion in multi-sample QC reports. +Both files use the same layout as the ones the nf-core dupradar module (as used by nf-core/rnaseq) writes: the same YAML header, so MultiQC reports them in the same sections, space-separated values with up to 15 significant digits, and the same rows. The numbers can differ from R's in the last digits, because they come from RustQC's own fit. These files integrate with [MultiQC](https://multiqc.info/) for inclusion in multi-sample QC reports. ## Interpreting plots diff --git a/docs/src/content/docs/usage/configuration.md b/docs/src/content/docs/usage/configuration.md index 9ca66389..85dd9ed3 100644 --- a/docs/src/content/docs/usage/configuration.md +++ b/docs/src/content/docs/usage/configuration.md @@ -365,7 +365,7 @@ rna: density_scatter_plot: true # Density scatter plot (PNG + SVG) boxplot: true # Duplication rate boxplot (PNG + SVG) expression_histogram: true # Expression histogram (PNG + SVG) - multiqc_intercept: true # MultiQC intercept/slope file + multiqc_intercept: true # MultiQC intercept file multiqc_curve: true # MultiQC fitted curve file ``` diff --git a/src/rna/dupradar/dupmatrix.rs b/src/rna/dupradar/dupmatrix.rs index 7b34aed7..47c41b96 100644 --- a/src/rna/dupradar/dupmatrix.rs +++ b/src/rna/dupradar/dupmatrix.rs @@ -240,7 +240,7 @@ pub struct DupMatStats { /// Format a float for TSV output, handling NaN as "NA" to match R's output. /// Uses R-compatible formatting with up to 15 significant digits. -fn format_float(v: f64) -> String { +pub(crate) fn format_float(v: f64) -> String { if v.is_nan() { "NA".to_string() } else if v.is_infinite() { diff --git a/src/rna/dupradar/plots.rs b/src/rna/dupradar/plots.rs index 802fc37d..e08c251b 100644 --- a/src/rna/dupradar/plots.rs +++ b/src/rna/dupradar/plots.rs @@ -8,7 +8,7 @@ //! All plots are output as both high-resolution PNG and SVG files, //! styled to visually match the original R dupRadar package output. -use crate::rna::dupradar::dupmatrix::DupMatrix; +use crate::rna::dupradar::dupmatrix::{format_float, DupMatrix}; use crate::rna::dupradar::fitting::FitResult; use anyhow::Result; use plotters::prelude::*; @@ -1298,71 +1298,108 @@ pub fn write_intercept_slope( Ok(()) } -/// Write a MultiQC-compatible general-stats intercept file. +/// MultiQC header of `_dup_intercept_mqc.txt`, as in the nf-core dupradar +/// module's template (`templates/dupradar.r`). +const MQC_INTERCEPT_HEADER: &str = "#id: DupInt +#plot_type: 'generalstats' +#pconfig: +# dupRadar_intercept: +# title: 'dupInt' +# namespace: 'DupRadar' +# description: 'Intercept value from DupRadar' +# max: 100 +# min: 0 +# scale: 'RdYlGn-rev' +Sample dupRadar_intercept +"; + +/// MultiQC header of `_duprateExpDensCurve_mqc.txt`, as in the nf-core +/// dupradar module's template. +const MQC_CURVE_HEADER: &str = "#id: dupradar +#plot_type: 'linegraph' +#section_name: 'DupRadar' +#section_href: 'bioconductor.org/packages/release/bioc/html/dupRadar.html' +#description: \"provides duplication rate quality control for RNA-Seq datasets. Highly expressed genes can be expected to have a lot of duplicate reads, but high numbers of duplicates at low read counts can indicate low library complexity with technical duplication. +# This plot shows the general linear models - a summary of the gene duplication distributions. \" +#pconfig: +# title: 'DupRadar General Linear Model' +# xlog: True +# xlab: 'expression (reads/kbp)' +# ylab: '% duplicate reads' +# ymax: 100 +# ymin: 0 +# tt_label: '{point.x:.1f} reads/kbp: {point.y:,.2f}% duplicates' +# x_lines: +# - color: 'green' +# dash: 'LongDash' +# label: +# text: '0.5 RPKM' +# value: 0.5 +# width: 1 +# - color: 'red' +# dash: 'LongDash' +# label: +# text: '1 read/bp' +# value: 1000 +# width: 1 +"; + +/// Write the MultiQC general-stats intercept file in the layout of the +/// nf-core dupradar module: its header, then ` `. pub fn write_mqc_intercept( fit: &FitResult, sample_name: &str, path: &std::path::Path, ) -> Result<()> { - use std::io::Write; - let mut f = std::fs::File::create(path)?; - writeln!(f, "# id: dupRadar")?; - writeln!(f, "# plot_type: 'generalstats'")?; - writeln!(f, "# pconfig:")?; - writeln!(f, "# dupRadar_intercept:")?; - writeln!(f, "# title: 'dupRadar int'")?; - writeln!(f, "# namespace: 'dupRadar'")?; - writeln!( - f, - "# description: 'dupRadar duplication rate at low read counts'" - )?; - writeln!(f, "# max: 100")?; - writeln!(f, "# min: 0")?; - writeln!(f, "# format: '{{:.2f}}'")?; - writeln!(f, "Sample\tdupRadar_intercept")?; - writeln!(f, "{}\t{}", sample_name, fit.intercept)?; + std::fs::write(path, mqc_intercept_text(fit, sample_name))?; Ok(()) } -/// Write a MultiQC-compatible line-graph curve file. +/// The intercept file contents. +fn mqc_intercept_text(fit: &FitResult, sample_name: &str) -> String { + format!( + "{MQC_INTERCEPT_HEADER}{} {}\n", + mqc_sample_name(sample_name), + format_float(fit.intercept) + ) +} + +/// The template strips the `Aligned.sortedByCoord.out.markDups` suffix that +/// STAR-based pipelines leave on the sample name. +fn mqc_sample_name(sample_name: &str) -> String { + sample_name.replace("Aligned.sortedByCoord.out.markDups", "") +} + +/// Write the MultiQC line-graph curve file in the layout of the nf-core +/// dupradar module. pub fn write_mqc_curve(fit: &FitResult, dm: &DupMatrix, path: &std::path::Path) -> Result<()> { - use std::io::Write; - let mut f = std::fs::File::create(path)?; - writeln!(f, "# id: 'dupradar'")?; - writeln!(f, "# section_name: 'dupRadar'")?; - writeln!(f, "# description: 'Duplication rate vs expression'")?; - writeln!(f, "# plot_type: 'linegraph'")?; - writeln!(f, "# pconfig:")?; - writeln!(f, "# title: 'dupRadar General Linear Model'")?; - writeln!(f, "# xlab: 'Expression (reads/kbp)'")?; - writeln!(f, "# ylab: 'Duplication rate (%)'")?; - writeln!(f, "# ymin: 0")?; - writeln!(f, "# ymax: 100")?; - writeln!(f, "# xlog: True")?; - - let rpks: Vec = dm - .rows - .iter() - .filter(|r| r.rpk > 0.0) - .map(|r| r.rpk) - .collect(); - if rpks.is_empty() { - return Ok(()); - } + let rpk: Vec = dm.rows.iter().map(|r| r.rpk).collect(); + std::fs::write(path, mqc_curve_text(fit, &rpk))?; + Ok(()) +} - let mn = rpks.iter().copied().fold(f64::INFINITY, f64::min); - let mx = rpks.iter().copied().fold(f64::NEG_INFINITY, f64::max); - let lmin = mn.log10(); - let lmax = mx.log10(); - let n = 100; - - for i in 0..=n { - let lr = lmin + (lmax - lmin) * (i as f64) / (n as f64); - let rpk = 10.0_f64.powf(lr); - let pct = fit.predict_rpk(rpk) * 100.0; - writeln!(f, "{}\t{}", rpk, pct)?; +/// The curve file contents: the header, then one ` ` row +/// per 10 expressed genes (RPK > 0) sorted by RPK, starting with the least +/// expressed, with the fitted duplication rate in percent. Numbers are +/// written with 15 significant digits, separated by a space. +/// +/// The template stops with an error when every gene has reads; this writes +/// the header without data rows in that case. +fn mqc_curve_text(fit: &FitResult, rpk: &[f64]) -> String { + let mut out = String::from(MQC_CURVE_HEADER); + let mut log_rpk: Vec = rpk.iter().map(|&r| r.log10()).collect(); + log_rpk.sort_by(f64::total_cmp); + let expressed: Vec = log_rpk.into_iter().filter(|x| x.is_finite()).collect(); + if expressed.len() == rpk.len() { + return out; } - Ok(()) + for &x in expressed.iter().step_by(10) { + out.push_str(&format_float(10f64.powf(x))); + out.push(' '); + out.push_str(&format_float(100.0 * fit.predict(x))); + out.push('\n'); + } + out } // ============================================================================ @@ -1384,6 +1421,65 @@ mod tests { assert_eq!((c_mid.0, c_mid.1, c_mid.2), (0, 255, 0)); // green } + #[test] + fn test_mqc_intercept_text_matches_nfcore_template() { + let fit = FitResult { + beta0: 0.0, + beta1: 0.0, + intercept: 0.0331294701668489, + slope: 1.55223856783934, + }; + let text = mqc_intercept_text(&fit, "test"); + assert!(text.starts_with("#id: DupInt\n#plot_type: 'generalstats'\n")); + assert!(text.ends_with( + "# scale: 'RdYlGn-rev'\nSample dupRadar_intercept\ntest 0.0331294701668489\n" + )); + assert_eq!(text.lines().count(), 12); + } + + #[test] + fn test_mqc_sample_name_strips_star_suffix() { + assert_eq!(mqc_sample_name("test"), "test"); + assert_eq!( + mqc_sample_name("WT_REP1Aligned.sortedByCoord.out.markDups"), + "WT_REP1" + ); + } + + #[test] + fn test_mqc_curve_text_every_tenth_expressed_gene() { + let fit = FitResult { + beta0: -3.0, + beta1: 1.0, + intercept: (-3.0f64).exp(), + slope: 1.0f64.exp(), + }; + // 3 genes without reads, 25 expressed genes in reverse order. + let mut rpk = vec![0.0; 3]; + rpk.extend((1..=25).rev().map(|i| i as f64 * 10.0)); + let text = mqc_curve_text(&fit, &rpk); + let rows: Vec<&str> = text.lines().filter(|l| !l.starts_with('#')).collect(); + // Sorted expressed genes 10, 20, ..., 250: rows for the 1st, 11th and 21st. + assert_eq!(rows.len(), 3); + assert!(rows[0].starts_with("10 "), "{}", rows[0]); + assert!(rows[1].starts_with("110 "), "{}", rows[1]); + assert!(rows[2].starts_with("210 "), "{}", rows[2]); + let y: f64 = rows[0].split(' ').nth(1).unwrap().parse().unwrap(); + assert!((y - 100.0 / (1.0 + (2.0f64).exp())).abs() < 1e-12, "{y}"); + assert!(text.starts_with(MQC_CURVE_HEADER)); + } + + #[test] + fn test_mqc_curve_text_without_unexpressed_genes_has_no_rows() { + let fit = FitResult { + beta0: -3.0, + beta1: 1.0, + intercept: (-3.0f64).exp(), + slope: 1.0f64.exp(), + }; + assert_eq!(mqc_curve_text(&fit, &[1.0, 2.0, 3.0]), MQC_CURVE_HEADER); + } + #[test] fn test_quantile() { let d = vec![1.0, 2.0, 3.0, 4.0, 5.0]; diff --git a/tests/integration_test.rs b/tests/integration_test.rs index 8f124569..d7743028 100644 --- a/tests/integration_test.rs +++ b/tests/integration_test.rs @@ -521,31 +521,26 @@ fn test_mqc_intercept_format() { let output = run_rustqc(outdir); assert!(output.status.success()); - // Check MultiQC intercept file format + // Same layout as the nf-core dupradar module's file: a YAML header in `#` + // lines, then space-separated "Sample dupRadar_intercept" and value lines. let content = fs::read_to_string(format!("{}/dupradar/test_dup_intercept_mqc.txt", outdir)).unwrap(); - // Skip YAML comment lines (starting with #) + assert!(content.starts_with("#id: DupInt\n#plot_type: 'generalstats'\n")); let data_lines: Vec<&str> = content.lines().filter(|l| !l.starts_with('#')).collect(); - assert!(data_lines.len() >= 2, "MultiQC intercept file too short"); + assert_eq!(data_lines.len(), 2, "MultiQC intercept file: {content}"); + assert_eq!(data_lines[0], "Sample dupRadar_intercept"); + let parts: Vec<&str> = data_lines[1].split(' ').collect(); + assert_eq!(parts.len(), 2, "MQC data line should have 2 columns"); + assert_eq!(parts[0], "test"); + let intercept: f64 = parts[1].parse().expect("MQC intercept should be numeric"); - // First data line should be a header with "Sample" and "dupRadar_intercept" - assert!( - data_lines[0].contains("Sample"), - "Missing 'Sample' in MQC header" - ); + // The same intercept as in the R fixture. + let (r_intercept, _) = parse_intercept_slope("tests/expected/intercept_slope.txt"); assert!( - data_lines[0].contains("dupRadar_intercept"), - "Missing 'dupRadar_intercept' in MQC header" + approx_eq(r_intercept, intercept, 1e-6), + "MQC intercept {intercept} vs R {r_intercept}" ); - // Second data line should have sample name and numeric value - let parts: Vec<&str> = data_lines[1].split('\t').collect(); - assert_eq!(parts.len(), 2, "MQC data line should have 2 columns"); - let _intercept: f64 = parts[1] - .trim() - .parse() - .expect("MQC intercept should be numeric"); - // Cleanup let _ = fs::remove_dir_all(outdir); } @@ -559,34 +554,41 @@ fn test_mqc_curve_format() { let output = run_rustqc(outdir); assert!(output.status.success()); - // Check MultiQC curve file format + // Same layout as the nf-core dupradar module's file: a YAML header in `#` + // lines, then "RPK duplication-percent" rows (space-separated, no header). let content = fs::read_to_string(format!( "{}/dupradar/test_duprateExpDensCurve_mqc.txt", outdir )) .unwrap(); - // Skip YAML comment lines (starting with #) + assert!(content.starts_with("#id: dupradar\n#plot_type: 'linegraph'\n")); let data_lines: Vec<&str> = content.lines().filter(|l| !l.starts_with('#')).collect(); - // Header + at least some data points (101 evenly spaced + header = 102) - assert!( - data_lines.len() >= 3, - "MultiQC curve file too short: {} lines", - data_lines.len() - ); - - // Should have a header line with 2 columns - let header_parts: Vec<&str> = data_lines[0].split('\t').collect(); - assert_eq!(header_parts.len(), 2, "Curve header should have 2 columns"); - - // Data lines should have numeric values - for line in &data_lines[1..] { - if line.trim().is_empty() { - continue; - } - let parts: Vec<&str> = line.split('\t').collect(); - assert_eq!(parts.len(), 2, "Curve data should have 2 columns"); - let _x: f64 = parts[0].parse().expect("X should be numeric"); - let _y: f64 = parts[1].parse().expect("Y should be numeric"); + // One row per 10 expressed genes (RPK > 0), starting with the least expressed. + let matrix = fs::read_to_string(format!("{}/dupradar/test_dupMatrix.txt", outdir)).unwrap(); + let rpk_col = matrix + .lines() + .next() + .unwrap() + .split('\t') + .position(|h| h == "RPK") + .unwrap(); + let expressed = matrix + .lines() + .skip(1) + .filter(|l| l.split('\t').nth(rpk_col).unwrap() != "0") + .count(); + assert!(expressed > 0); + assert_eq!(data_lines.len(), expressed.div_ceil(10), "{content}"); + let mut prev_x = 0.0; + for line in &data_lines { + let parts: Vec<&str> = line.split(' ').collect(); + assert_eq!(parts.len(), 2, "Curve data should have 2 columns: {line}"); + let x: f64 = parts[0].parse().expect("X should be numeric"); + let y: f64 = parts[1].parse().expect("Y should be numeric"); + // Rows are genes sorted by expression; y is a percentage. + assert!(x > 0.0 && x >= prev_x, "{line}"); + assert!((0.0..=100.0).contains(&y), "{line}"); + prev_x = x; } // Cleanup