diff --git a/src/gtf.rs b/src/gtf.rs index 7d04f930..a69e5e7f 100644 --- a/src/gtf.rs +++ b/src/gtf.rs @@ -8,7 +8,7 @@ use anyhow::{Context, Result}; use indexmap::IndexMap; -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::io::BufRead; /// Represents a single exon interval. @@ -294,6 +294,80 @@ struct TranscriptBuilder { stop_codons: Vec<(u64, u64)>, } +/// Counters collected while scanning a GTF, used to explain an empty parse. +#[derive(Debug, Default)] +struct GtfParseDiagnostics { + /// Non-comment, non-empty lines seen. + data_lines: u64, + /// Lines with fewer than the 9 mandatory tab-separated columns. + short_lines: u64, + /// Well-formed `exon` lines seen (before the gene_id check). + exon_lines: u64, + /// Feature lines of a type we consume that carried no `gene_id` attribute. + missing_gene_id: u64, + /// Distinct values seen in column 3 (the feature-type column). + feature_types: BTreeSet, +} + +/// Build the fatal error raised when a GTF yields no genes. +/// +/// The message names the most likely root cause based on what the scan saw, +/// so the failure is actionable instead of surfacing later as an unrelated +/// "chromosome name mismatch". +fn empty_gtf_error(path: &str, diag: &GtfParseDiagnostics) -> anyhow::Error { + let cause = if diag.data_lines == 0 { + "the file contains no annotation lines (it is empty, or every line is a comment)" + .to_string() + } else if diag.short_lines == diag.data_lines { + format!( + "all {} annotation lines have fewer than the 9 mandatory tab-separated GTF columns \ + (truncated file, or space- instead of tab-separated)", + diag.data_lines + ) + } else if diag.exon_lines == 0 { + let types: Vec<&str> = diag + .feature_types + .iter() + .take(8) + .map(|s| s.as_str()) + .collect(); + format!( + "no 'exon' features were found; feature types present: {}{}. \ + GFF3 files (which use 'ID='/'Parent=' attributes) are not supported — convert to GTF", + if types.is_empty() { + "none".to_string() + } else { + types.join(", ") + }, + if diag.feature_types.len() > 8 { + ", ..." + } else { + "" + } + ) + } else if diag.missing_gene_id > 0 { + format!( + "{} feature lines were found but none carried a 'gene_id' attribute \ + (GFF3 files use 'ID='/'Parent=' instead — convert to GTF)", + diag.missing_gene_id + ) + } else { + "the file has exon features with gene_id attributes, but none could be assembled into a \ + gene" + .to_string() + }; + + anyhow::anyhow!( + "No genes could be extracted from GTF file '{}': {}.\n\ + \n\ + Every RustQC analysis needs a usable gene annotation, so processing cannot continue.\n\ + Check that the file is uncorrupted, tab-separated GTF (not GFF3) with 'exon' features \ + carrying 'gene_id' attributes.", + path, + cause + ) +} + /// Parse a GTF file and return a map of gene_id -> Gene. /// /// Extracts all exon and CDS features, groups them by gene_id, and builds @@ -320,6 +394,10 @@ pub fn parse_gtf(path: &str, extra_attributes: &[String]) -> Result> = IndexMap::new(); + // Diagnostics, used to explain *why* nothing was extracted if the file + // turns out to yield no genes (see `empty_gtf_error`). + let mut diag = GtfParseDiagnostics::default(); + for line in reader.lines() { let line = line.context("Failed to read line from GTF file")?; @@ -327,13 +405,19 @@ pub fn parse_gtf(path: &str, extra_attributes: &[String]) -> Result = line.split('\t').collect(); if fields.len() < 9 { + diag.short_lines += 1; continue; } let feature_type = fields[2]; + if feature_type == "exon" { + diag.exon_lines += 1; + } + diag.feature_types.insert(feature_type.to_string()); // We care about exon, CDS, start_codon, and stop_codon features if feature_type != "exon" @@ -364,7 +448,11 @@ pub fn parse_gtf(path: &str, extra_attributes: &[String]) -> Result id, - None => continue, // Skip features without gene_id + None => { + // Skip features without gene_id (GFF3 uses ID=/Parent= instead) + diag.missing_gene_id += 1; + continue; + } }; // For exon features, update the gene-level data (unchanged from original) @@ -445,13 +533,11 @@ pub fn parse_gtf(path: &str, extra_attributes: &[String]) -> Result 0) .count(); if merged.total_mapped > 0 && genes_with_reads == 0 { + // Only a naming mismatch if no alignment name, after prefix/mapping, + // is a GTF chromosome. + let shared_chroms: Vec<&str> = tid_to_name + .iter() + .filter(|bam_name| { + let gtf_name = match chrom_mapping.get(bam_name.as_str()) { + Some(mapped) => mapped.clone(), + None => format!("{}{}", chrom_prefix.unwrap_or(""), bam_name), + }; + index.contains_key(>f_name) + }) + .take(5) + .map(|s| s.as_str()) + .collect(); + if !shared_chroms.is_empty() { + anyhow::bail!( + "No reads could be assigned to any gene under the configured gene-assignment rules \ + ({} mapped reads).\n\ + \n\ + Chromosomes in both the alignment and the GTF (first 5): {}\n\ + \n\ + The chromosome names match. Check the annotation, genome assembly, and \ + strandedness setting for this library.", + merged.total_mapped, + shared_chroms.join(", ") + ); + } let bam_chroms: Vec<&str> = tid_to_name.iter().take(5).map(|s| s.as_str()).collect(); // First 5 annotated chromosomes in GTF order (not the index's hash order). let mut gtf_chroms: Vec<&str> = Vec::with_capacity(5); @@ -1663,6 +1690,18 @@ pub fn count_reads( gtf_chroms.push(exon.chrom.as_str()); } } + // An empty annotation index is not a naming mismatch — there is nothing + // on the GTF side to match against. Say so instead of suggesting a + // chromosome_mapping that cannot possibly help. + anyhow::ensure!( + !gtf_chroms.is_empty(), + "No reads could be assigned to any gene because the annotation is empty: \ + the parsed GTF contains no genes on any chromosome.\n\ + \n\ + This is an annotation problem, not a chromosome naming mismatch. Check that the \ + GTF file is uncorrupted, tab-separated GTF (not GFF3) with 'exon' features carrying \ + 'gene_id' attributes." + ); anyhow::bail!( "Chromosome name mismatch: no reads could be assigned to any gene.\n\ \n\ diff --git a/tests/integration_test.rs b/tests/integration_test.rs index 1819e018..88e806ae 100644 --- a/tests/integration_test.rs +++ b/tests/integration_test.rs @@ -1688,3 +1688,166 @@ fn test_parallel_cram_with_no_unplaced_reads() { fs::remove_dir_all(root).unwrap(); } } + +// =================================================================== +// No-genic-reads diagnostic +// =================================================================== + +/// Run `rustqc rna` on one mapped read at `bam_chrom:11`, outside the only +/// gene (`gtf_chrom:900-3000`), with optional YAML config. Returns the output. +fn run_no_genic_reads( + label: &str, + bam_chrom: &str, + gtf_chrom: &str, + config: Option<&str>, +) -> std::process::Output { + let root = unique_test_dir(label); + let bam_path = root.join("s.bam"); + let gtf_path = root.join("a.gtf"); + let outdir = root.join("out"); + fs::create_dir_all(&outdir).unwrap(); + fs::write( + >f_path, + format!( + "{gtf_chrom}\tt\tgene\t900\t3000\t.\t+\t.\tgene_id \"g1\"; gene_name \"g1\";\n\ + {gtf_chrom}\tt\texon\t900\t3000\t.\t+\t.\tgene_id \"g1\"; transcript_id \"t1\"; exon_number \"1\";\n" + ), + ) + .unwrap(); + let read = format!( + "r0\t0\t{bam_chrom}\t11\t60\t50M\t*\t0\t0\tACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTAC\t??????????????????????????????????????????????????" + ); + write_bam_fixture(&bam_path, &[(bam_chrom, 100_000)], &[&read]); + + let mut cmd = Command::new(rustqc_binary()); + cmd.args(["rna", "--skip-dup-check", "--gtf"]) + .arg(>f_path) + .arg("--outdir") + .arg(&outdir) + .arg(&bam_path); + if let Some(yaml) = config { + let config_path = root.join("config.yaml"); + fs::write(&config_path, yaml).unwrap(); + cmd.arg("--config").arg(&config_path); + } + let output = cmd.output().expect("Failed to execute rustqc"); + let _ = fs::remove_dir_all(root); + output +} + +/// When BAM and GTF share chromosome names but no read lands in a gene, +/// the error must not claim a naming mismatch. It still fails. +#[test] +fn test_no_genic_reads_with_shared_names_is_not_a_name_mismatch() { + let output = run_no_genic_reads("no-genic-shared", "chr1", "chr1", None); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + !output.status.success(), + "rustqc should still fail:\n{stderr}" + ); + assert!( + !stderr.contains("Chromosome name mismatch"), + "BAM and GTF both name chr1, so this is not a name mismatch:\n{stderr}" + ); + assert!( + stderr.contains("No reads could be assigned to any gene"), + "missing no-assigned-reads diagnostic:\n{stderr}" + ); +} + +/// Names that only match after `chromosome_prefix` are not a mismatch either. +#[test] +fn test_no_genic_reads_with_prefix_mapped_names_is_not_a_name_mismatch() { + let output = run_no_genic_reads( + "no-genic-prefix", + "1", + "chr1", + Some("rna:\n chromosome_prefix: \"chr\"\n"), + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + !output.status.success(), + "rustqc should still fail:\n{stderr}" + ); + assert!( + !stderr.contains("Chromosome name mismatch"), + "chromosome_prefix maps 1 to chr1, so this is not a name mismatch:\n{stderr}" + ); + assert!( + stderr.contains("No reads could be assigned to any gene"), + "missing no-assigned-reads diagnostic:\n{stderr}" + ); +} + +/// A real naming mismatch (BAM `1`, GTF `chr1`) keeps the mismatch diagnostic. +#[test] +fn test_no_genic_reads_with_disjoint_names_is_a_name_mismatch() { + let output = run_no_genic_reads("no-genic-disjoint", "1", "chr1", None); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!output.status.success(), "rustqc should fail:\n{stderr}"); + assert!( + stderr.contains("Chromosome name mismatch"), + "missing chromosome-name diagnostic:\n{stderr}" + ); +} + +/// A physical gene overlap rejected by strandedness is an assignment failure. +#[test] +fn test_no_genic_reads_with_wrong_strand_is_assignment_failure() { + let root = unique_test_dir("no-genic-wrong-strand"); + let bam_path = root.join("s.bam"); + let gtf_path = root.join("a.gtf"); + fs::write( + >f_path, + "chr1\tt\tgene\t900\t3000\t.\t+\t.\tgene_id \"g1\"; gene_name \"g1\";\n\ + chr1\tt\texon\t900\t3000\t.\t+\t.\tgene_id \"g1\"; transcript_id \"t1\"; exon_number \"1\";\n", + ) + .unwrap(); + let read = format!( + "r0\t16\tchr1\t1001\t60\t50M\t*\t0\t0\t{}\t{}", + "A".repeat(50), + "I".repeat(50) + ); + write_bam_fixture(&bam_path, &[("chr1", 100_000)], &[&read]); + let run = |stranded: &str| { + Command::new(env!("CARGO_BIN_EXE_rustqc")) + .args(["rna", "--skip-dup-check", "--skip-preseq", "--gtf"]) + .arg(>f_path) + .args(["--stranded", stranded, "--outdir"]) + .arg(root.join(stranded)) + .arg(&bam_path) + .output() + .expect("Failed to execute rustqc") + }; + let control = run("unstranded"); + assert!( + control.status.success(), + "the overlapping read must be assigned in the unstranded control:\n{}", + String::from_utf8_lossy(&control.stderr) + ); + let output = run("forward"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + !output.status.success(), + "assignment failure must remain fatal:\n{stderr}" + ); + assert!( + !stderr.contains("Chromosome name mismatch"), + "chromosome names match:\n{stderr}" + ); + assert!( + !stderr.contains("overlaps a gene"), + "the read overlaps chr1:1001-1050 within g1 at chr1:900-3000; the unstranded control passed:\n{stderr}" + ); + assert!( + stderr.contains("configured gene-assignment rules"), + "missing assignment-rule diagnostic:\n{stderr}" + ); + assert!( + stderr.contains("annotation") + && stderr.contains("genome assembly") + && stderr.contains("strandedness"), + "missing diagnostic guidance:\n{stderr}" + ); + fs::remove_dir_all(root).unwrap(); +}