use std::fs::File;
use std::io::{self, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use clap::{ArgGroup, Args, Parser, Subcommand, ValueEnum};
use noodles_util::alignment;
use noodles::sam::alignment::Record as _;
use pmdshodh::damage::{DamageCounts, PatternCounts};
use pmdshodh::mode_check::ModeCheck;
use pmdshodh::model::Params;
use pmdshodh::reads::{Outcome, ReadFilters, SkipReason, process, process_bam};
use pmdshodh::reference::Reference;
use pmdshodh::sites::ReadScore;
use pmdshodh::sites::{Library, Settings, Treatment};
use pmdshodh::summary::{RunInfo, Summary};
mod display;
#[derive(Parser)]
#[command(name = "pmdshodh", bin_name = "pmdshodh", version, after_help = TOP_EXAMPLES)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
#[command(after_help = FILTER_EXAMPLES)]
Filter(FilterArgs),
#[command(after_help = SCORE_EXAMPLES)]
Score(ScoreArgs),
#[command(after_help = DAMAGE_EXAMPLES)]
Damage(DamageArgs),
#[command(after_help = REPORT_EXAMPLES)]
Report(ReportArgs),
}
const TOP_EXAMPLES: &str = "\
Examples:
# Keep reads with PMD score >= 3 (reference bases from MD tags, or from -r)
pmdshodh filter -t 3 -@ 8 in.bam -o out.bam
pmdshodh filter -t 3 -@ 8 -r ref.fa in.cram -o out.bam
# Damage tables and a JSON summary, then an HTML report
pmdshodh damage -@ 8 in.bam -o run.json
pmdshodh report run.json -o report.html
Run 'pmdshodh <command> --help' for each command's options and examples.";
const FILTER_EXAMPLES: &str = "\
Examples:
# Keep reads with PMD score >= 3, as
# samtools view -h in.bam | pmdtools --threshold 3 --header | samtools view -b -o out.bam -
pmdshodh filter -t 3 -@ 8 in.bam -o out.bam
# Single-stranded, UDG-half library; add the score as a pm tag and write a JSON summary
pmdshodh filter -t 3 --library ss --treatment half --tag --summary run.json in.bam -o out.bam
# In a pipe: SAM or BAM in on stdin, BAM out on stdout
samtools view -h -q 30 in.bam | pmdshodh filter -t 3 - -o - | samtools sort -o out.bam";
const SCORE_EXAMPLES: &str = "\
Examples:
# One line per read: read_name, flag, pmds, n_sites
pmdshodh score -@ 8 in.bam -o scores.tsv
# Scores as PMDtools 0.60 computes them, including its known bugs (for comparisons)
pmdshodh score --pmdtools-compat in.bam -o scores.tsv";
const DAMAGE_EXAMPLES: &str = "\
Examples:
# Substitution rates by position, score histogram and read counts as JSON
pmdshodh damage -@ 8 in.bam -o damage.json
# Only the first 100,000 reads (PMDtools -n)
pmdshodh damage -n 100000 in.bam -o damage.json";
const REPORT_EXAMPLES: &str = "Examples:
# One sample, from a summary written by damage -o, filter --summary or score --summary
pmdshodh report run.json -o report.html
# Several samples in one report, with their damage curves and score histograms overlaid
pmdshodh report run.json damage.json -o report.html";
#[derive(Args)]
struct ReportArgs {
#[arg(required = true)]
summaries: Vec<PathBuf>,
#[arg(help_heading = "Output", short, long)]
output: PathBuf,
#[arg(long)]
quiet: bool,
}
#[derive(Args)]
struct DamageArgs {
input: PathBuf,
#[arg(help_heading = "Output", short, long)]
output: Option<PathBuf>,
#[arg(
help_heading = "Summary",
long,
default_value_t = 30,
allow_negative_numbers = true
)]
range: usize,
#[arg(
help_heading = "Input",
short = 'n',
long,
visible_alias = "number",
allow_negative_numbers = true
)]
max_reads: Option<u64>,
#[command(flatten)]
model: ModelArgs,
#[arg(long)]
quiet: bool,
}
#[derive(Args)]
#[command(group(ArgGroup::new("bounds").args(["threshold", "upper_threshold"]).required(true).multiple(true)))]
struct FilterArgs {
input: PathBuf,
#[arg(help_heading = "Output", short, long)]
output: PathBuf,
#[arg(help_heading = "Output", long, value_enum)]
output_format: Option<OutputFormat>,
#[arg(
help_heading = "Filtering",
short = 't',
long,
allow_negative_numbers = true
)]
threshold: Option<f64>,
#[arg(
help_heading = "Filtering",
long,
visible_alias = "upperthreshold",
allow_negative_numbers = true
)]
upper_threshold: Option<f64>,
#[arg(help_heading = "Output", long)]
tag: bool,
#[arg(
help_heading = "Output",
long,
value_enum,
default_value = "pm",
requires = "tag"
)]
tag_name: TagName,
#[arg(long, hide = true)]
header: bool,
#[command(flatten)]
summary: SummaryArgs,
#[command(flatten)]
model: ModelArgs,
#[arg(long)]
quiet: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
enum OutputFormat {
Bam,
Sam,
}
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
enum TagName {
#[value(name = "pm")]
Pm,
#[value(name = "DS")]
Ds,
}
#[derive(Args)]
struct ScoreArgs {
input: PathBuf,
#[arg(help_heading = "Output", short, long)]
output: Option<PathBuf>,
#[command(flatten)]
summary: SummaryArgs,
#[command(flatten)]
model: ModelArgs,
#[arg(long)]
quiet: bool,
}
#[derive(Clone, Copy, ValueEnum)]
enum LibraryArg {
Ds,
Ss,
}
#[derive(Clone, Copy, ValueEnum)]
enum TreatmentArg {
None,
Half,
Full,
}
#[derive(Clone, Copy, ValueEnum)]
enum SkipFlag {
Secondary,
Supplementary,
Duplicate,
#[value(name = "qcfail")]
QcFail,
}
#[derive(Args)]
#[command(group(ArgGroup::new("library_choice").args(["library", "ss"])))]
#[command(group(ArgGroup::new("treatment_choice").args(["treatment", "udg_minus", "udg_half", "udg_plus"])))]
struct ModelArgs {
#[arg(help_heading = "Scoring model", long, value_enum, default_value = "ds")]
library: LibraryArg,
#[arg(help_heading = "Scoring model", long)]
ss: bool,
#[arg(
help_heading = "Scoring model",
long,
value_enum,
default_value = "none"
)]
treatment: TreatmentArg,
#[arg(help_heading = "Scoring model", long = "UDGminus")]
udg_minus: bool,
#[arg(help_heading = "Scoring model", long = "UDGhalf")]
udg_half: bool,
#[arg(
help_heading = "Scoring model",
long = "UDGplus",
visible_alias = "CpG"
)]
udg_plus: bool,
#[arg(
help_heading = "Scoring model",
long,
visible_alias = "PMDpparam",
default_value_t = 0.3,
allow_negative_numbers = true
)]
pmd_p: f64,
#[arg(
help_heading = "Scoring model",
long,
visible_alias = "PMDconstant",
default_value_t = 0.01,
allow_negative_numbers = true
)]
pmd_c: f64,
#[arg(
help_heading = "Scoring model",
long,
visible_alias = "polymorphism_ancient",
default_value_t = 0.001,
allow_negative_numbers = true
)]
pi_ancient: f64,
#[arg(
help_heading = "Scoring model",
long,
visible_alias = "polymorphism_contamination",
default_value_t = 0.001,
allow_negative_numbers = true
)]
pi_contamination: f64,
#[arg(
help_heading = "Read filters",
short = 'm',
long,
visible_alias = "requiremapq",
default_value_t = 0,
allow_negative_numbers = true
)]
min_mapq: u8,
#[arg(
help_heading = "Read filters",
short = 'q',
long,
visible_alias = "requirebaseq",
default_value_t = 0,
allow_negative_numbers = true
)]
min_baseq: u8,
#[arg(help_heading = "Read filters", long, visible_alias = "noclips")]
no_clips: bool,
#[arg(help_heading = "Read filters", long, visible_alias = "noindels")]
no_indels: bool,
#[arg(
help_heading = "Read filters",
long,
value_enum,
value_delimiter = ',',
value_name = "LIST"
)]
skip_flags: Vec<SkipFlag>,
#[arg(help_heading = "Scoring model", long)]
pmdtools_compat: bool,
#[arg(
help_heading = "Performance",
short = '@',
long,
default_value_t = 1,
allow_negative_numbers = true
)]
threads: usize,
#[arg(help_heading = "Input", short = 'r', long)]
reference: Option<PathBuf>,
}
impl ModelArgs {
fn settings(&self) -> Result<(Settings, ReadFilters), String> {
for (name, v) in [
("--pmd-p", self.pmd_p),
("--pmd-c", self.pmd_c),
("--pi-ancient", self.pi_ancient),
("--pi-contamination", self.pi_contamination),
] {
if !(0.0..=1.0).contains(&v) {
return Err(format!("{name} must be between 0 and 1, got {v}"));
}
}
if pmdshodh::model::damage(1, self.pmd_p, self.pmd_c) > 1.0 {
return Err(format!(
"--pmd-p + --pmd-c is the damage rate at the read end and must be at most 1, got {} + {}",
self.pmd_p, self.pmd_c
));
}
let library = if self.ss {
Library::SingleStranded
} else {
match self.library {
LibraryArg::Ds => Library::DoubleStranded,
LibraryArg::Ss => Library::SingleStranded,
}
};
let treatment = if self.udg_half {
Treatment::Half
} else if self.udg_plus {
Treatment::Full
} else if self.udg_minus {
Treatment::None
} else {
match self.treatment {
TreatmentArg::None => Treatment::None,
TreatmentArg::Half => Treatment::Half,
TreatmentArg::Full => Treatment::Full,
}
};
let settings = Settings {
library,
treatment,
params: Params {
p: self.pmd_p,
c: self.pmd_c,
pi_ancient: self.pi_ancient,
pi_contamination: self.pi_contamination,
},
min_baseq: self.min_baseq,
pmdtools_compat: self.pmdtools_compat,
};
let filters = ReadFilters {
min_mapq: self.min_mapq,
no_clips: self.no_clips,
no_indels: self.no_indels,
skip_flags: self.skip_flags.iter().fold(0, |bits, flag| {
bits | match flag {
SkipFlag::Secondary => 0x100,
SkipFlag::Supplementary => 0x800,
SkipFlag::Duplicate => 0x400,
SkipFlag::QcFail => 0x200,
}
}),
};
Ok((settings, filters))
}
}
enum Failure {
Input(String),
Runtime(String),
BrokenPipe,
}
fn main() -> ExitCode {
let cli = Cli::parse();
clean_up_on_signals();
let result = match cli.command {
Command::Filter(args) => run_filter(&args),
Command::Score(args) => run_score(&args),
Command::Damage(args) => run_damage(&args),
Command::Report(args) => run_report(&args),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(Failure::BrokenPipe) => ExitCode::from(141),
Err(Failure::Input(msg)) => {
eprintln!("pmdshodh: error: {msg}");
ExitCode::from(2)
}
Err(Failure::Runtime(msg)) => {
eprintln!("pmdshodh: error: {msg}");
ExitCode::from(1)
}
}
}
fn open_input(path: &PathBuf) -> Result<Box<dyn Read + Send>, Failure> {
if path.as_os_str() == "-" {
Ok(Box::new(io::stdin()))
} else {
let file = File::open(path)
.map_err(|e| Failure::Input(format!("cannot open {}: {e}", path.display())))?;
if let Ok(m) = file.metadata()
&& m.is_file()
{
display::set_input_size(m.len());
}
Ok(Box::new(display::Counting(file)))
}
}
#[derive(Args)]
struct SummaryArgs {
#[arg(help_heading = "Summary", long)]
summary: Option<PathBuf>,
#[arg(
help_heading = "Summary",
long,
default_value_t = 30,
allow_negative_numbers = true
)]
range: usize,
}
enum InputReader {
Alignment(alignment::io::Reader<Box<dyn Read + Send>>),
Cram(pmdshodh::cram::Reader),
}
type AlignmentRecord = alignment::Record;
#[derive(Clone, Copy)]
enum InputFormat {
Sam,
Bam,
Cram,
}
impl InputFormat {
fn name(self) -> &'static str {
match self {
InputFormat::Sam => "sam",
InputFormat::Bam => "bam",
InputFormat::Cram => "cram",
}
}
}
fn open_alignments(
path: &Path,
model: &ModelArgs,
) -> Result<
(
InputReader,
noodles::sam::Header,
Option<Reference>,
InputFormat,
usize,
),
Failure,
> {
use std::io::BufRead;
let reference_path = model.reference.as_deref();
let mut reference = open_reference(reference_path)?;
let cannot_read = |e: io::Error| Failure::Input(format!("cannot read {}: {e}", path.display()));
let mut input = io::BufReader::new(open_input(&path.to_path_buf())?);
let head = input.fill_buf().map_err(cannot_read)?;
if head.is_empty() {
return Err(Failure::Input(empty_input(path)));
}
let bgzf = head.starts_with(&[0x1f, 0x8b]);
if bgzf && head.get(3).is_some_and(|flags| flags & 0x04 == 0) {
return Err(Failure::Input(format!(
"{} is gzip-compressed but not BGZF: recompress it with bgzip",
path.display()
)));
}
let mut source: Box<dyn BufRead + Send> = if bgzf {
Box::new(io::BufReader::new(pmdshodh::bgzf::Reader::new(
input,
model.threads > 1,
)))
} else {
Box::new(input)
};
let magic = source.fill_buf().map_err(cannot_read)?;
if magic.is_empty() {
return Err(Failure::Input(empty_input(path)));
}
let format = if magic.starts_with(b"CRAM") {
InputFormat::Cram
} else if magic.starts_with(b"BAM\x01") {
InputFormat::Bam
} else {
if let Some(what) = not_sam(magic) {
return Err(Failure::Input(format!(
"{} is not SAM, BAM or CRAM: {what}",
shown(path)
)));
}
InputFormat::Sam
};
let mut source: Box<dyn Read + Send> = Box::new(source);
let invalid_header = |e: io::Error| Failure::Input(format!("invalid header: {e}"));
let (reader, header) = if let InputFormat::Cram = format {
let (Some(r), Some(p)) = (reference.as_mut(), reference_path) else {
return Err(Failure::Input(format!(
"{} is CRAM, which needs its reference: pass it with -r FILE",
path.display()
)));
};
let mut reader = pmdshodh::cram::Reader::new(source);
let header = reader.read_header().map_err(invalid_header)?;
r.enable_cram(p, &header)
.map_err(|e| reference_error(p, e))?;
(InputReader::Cram(reader), header)
} else {
use noodles_util::alignment::io::Format;
let bam_header = match format {
InputFormat::Bam => {
Some(pmdshodh::bam_header::read_header(&mut source).map_err(invalid_header)?)
}
_ => None,
};
let mut reader = alignment::io::reader::Builder::default()
.set_compression_method(None)
.set_format(match format {
InputFormat::Bam => Format::Bam,
_ => Format::Sam,
})
.build_from_reader(source)
.map_err(cannot_read)?;
let header = match bam_header {
Some(header) => header,
None => reader.read_header().map_err(invalid_header)?,
};
(InputReader::Alignment(reader), header)
};
let missing = match (reference.as_ref(), reference_path) {
(Some(r), Some(p)) => check_reference(r, p, &header)?,
_ => 0,
};
Ok((reader, header, reference, format, missing))
}
fn shown(path: &Path) -> String {
if path.as_os_str() == "-" {
"standard input".into()
} else {
path.display().to_string()
}
}
fn empty_input(path: &Path) -> String {
format!(
"{} is empty (no data): expected SAM, BAM or CRAM",
shown(path)
)
}
fn not_sam(start: &[u8]) -> Option<&'static str> {
let start = &start[..start.len().min(512)];
if start
.iter()
.any(|&b| (b < 0x20 && !matches!(b, b'\t' | b'\n' | b'\r')) || b == 0x7f)
{
return Some("it is binary data");
}
match start.first() {
Some(b'>') => Some("it looks like FASTA (sequences, not alignments)"),
Some(b'@')
if start.len() >= 4
&& !(matches!(&start[1..3], b"HD" | b"SQ" | b"RG" | b"PG" | b"CO")
&& start[3] == b'\t') =>
{
Some("it looks like FASTQ (reads that are not aligned yet)")
}
_ => None,
}
}
fn check_reference_ids(
record: &AlignmentRecord,
header: &noodles::sam::Header,
) -> Result<(), String> {
let n = header.reference_sequences().len();
for (what, id) in [
("reference", record.reference_sequence_id(header)),
(
"mate's reference",
record.mate_reference_sequence_id(header),
),
] {
match id {
Some(Ok(i)) if i < n => {}
None => {}
_ => {
return Err(format!(
"its {what} is not in the header (no @SQ line for it)"
));
}
}
}
Ok(())
}
const BATCH: usize = 10_000;
#[allow(clippy::too_many_arguments)]
fn scan(
reader: &mut InputReader,
header: &noodles::sam::Header,
reference: &mut Option<Reference>,
settings: &Settings,
filters: &ReadFilters,
summary: &mut Summary,
count_damage: bool,
max_reads: Option<u64>,
threads: usize,
progress: &mut display::Progress,
full_record: &(dyn Fn(&ReadScore) -> bool + Sync),
mut on_scored: impl FnMut(&AlignmentRecord, &ReadScore) -> Result<Option<bool>, Failure> + Send,
) -> Result<(), Failure> {
let range = count_damage.then_some(summary.damage.range);
if threads == 1 {
let mut n_read = 0u64;
loop {
let mut batch = read_batch(reader, header, reference, max_reads, &mut n_read)?;
if batch.is_empty() {
return Ok(());
}
progress.tick(n_read);
let parts = batch.score(header, settings, filters, range, full_record)?;
let first = n_read - batch.len() as u64;
consume_batch(&batch.records, &parts, first, summary, &mut on_scored)?;
}
}
rayon::scope(|s| {
let spawn = |mut batch: Batch| {
let (tx, rx) = std::sync::mpsc::sync_channel(1);
s.spawn(move |_| {
let parts = batch.score(header, settings, filters, range, full_record);
let _ = tx.send((batch, parts));
});
rx
};
let join = |rx: std::sync::mpsc::Receiver<(Batch, Result<Scored, Failure>)>| {
pmdshodh::bgzf::wait_for(&rx).expect("scoring task panicked")
};
let mut n_read = 0u64;
let mut first = 0u64;
let mut in_flight = std::collections::VecDeque::new();
let mut consume_oldest = |in_flight: &mut std::collections::VecDeque<_>| {
let (batch, parts) = join(in_flight.pop_front().unwrap());
consume_batch(&batch.records, &parts?, first, summary, &mut on_scored)?;
first += batch.len() as u64;
Ok::<(), Failure>(())
};
loop {
match read_batch(reader, header, reference, max_reads, &mut n_read) {
Ok(batch) if !batch.is_empty() => {
progress.tick(n_read);
in_flight.push_back(spawn(batch));
}
Ok(_) => {
while !in_flight.is_empty() {
consume_oldest(&mut in_flight)?;
}
return Ok(());
}
Err(e) => {
while !in_flight.is_empty() {
consume_oldest(&mut in_flight)?;
}
return Err(e);
}
}
if in_flight.len() > SCORED_AHEAD {
consume_oldest(&mut in_flight)?;
}
}
})
}
const SCORED_AHEAD: usize = 2;
type Scored = Vec<(
Vec<Result<Outcome, String>>,
Option<DamageCounts>,
PatternCounts,
)>;
struct Batch {
records: Vec<AlignmentRecord>,
bases: Vec<u8>,
windows: Vec<Option<std::ops::Range<usize>>>,
cram: Option<CramBatch>,
}
struct CramPart {
records: Vec<AlignmentRecord>,
outcomes: Vec<Result<Outcome, String>>,
damage: Option<DamageCounts>,
pattern: PatternCounts,
}
struct CramBatch {
containers: Vec<noodles::cram::io::reader::Container>,
repository: noodles::fasta::Repository,
checks: std::sync::Mutex<Vec<pmdshodh::reference::Md5Check>>,
keep: usize,
first: u64,
}
impl Batch {
fn len(&self) -> usize {
self.records.len() + self.cram.as_ref().map_or(0, |c| c.keep)
}
fn is_empty(&self) -> bool {
self.len() == 0
}
fn score(
&mut self,
header: &noodles::sam::Header,
settings: &Settings,
filters: &ReadFilters,
range: Option<usize>,
full_record: &(dyn Fn(&ReadScore) -> bool + Sync),
) -> Result<Scored, Failure> {
use noodles::sam::alignment::RecordBuf;
let Some(c) = self.cram.take() else {
return Ok(score_batch(self, settings, filters, range));
};
let error = |e: io::Error| {
Failure::Input(format!(
"CRAM records {} to {}: {e}",
c.first + 1,
c.first + c.keep as u64
))
};
for check in c.checks.into_inner().unwrap() {
pmdshodh::bgzf::wait_for(&check)
.unwrap_or_else(|| Err(io::Error::other("M5 check stopped")))
.map_err(error)?;
}
let new = || CramPart {
records: Vec::new(),
outcomes: Vec::new(),
damage: range.map(DamageCounts::new),
pattern: PatternCounts::default(),
};
let each = |part: &mut CramPart,
record: &dyn noodles::sam::alignment::Record,
window: Option<&[u8]>| {
let (damage, pattern) = (part.damage.as_mut(), Some(&mut part.pattern));
let outcome = process(record, settings, filters, window, damage, pattern);
let whole = matches!(&outcome, Ok(Outcome::Scored { score, .. }) if full_record(score));
let record = if whole {
RecordBuf::try_from_alignment_record(header, record)?
} else {
let mut kept = RecordBuf::default();
*kept.name_mut() = record.name().map(ToOwned::to_owned);
*kept.flags_mut() = record.flags()?;
kept
};
part.records.push(AlignmentRecord::Cram(record));
part.outcomes.push(outcome);
Ok(())
};
let parts = pmdshodh::cram::decode(&c.containers, c.keep, &c.repository, header, new, each)
.map_err(error)?;
let mut scored = Vec::with_capacity(parts.len());
for part in parts {
self.records.extend(part.records);
scored.push((part.outcomes, part.damage, part.pattern));
}
Ok(scored)
}
fn window(&self, i: usize) -> Option<&[u8]> {
self.windows.get(i)?.clone().map(|r| &self.bases[r])
}
}
fn read_batch(
reader: &mut InputReader,
header: &noodles::sam::Header,
reference: &mut Option<Reference>,
max_reads: Option<u64>,
n_read: &mut u64,
) -> Result<Batch, Failure> {
let reader = match reader {
InputReader::Alignment(reader) => reader,
InputReader::Cram(reader) => {
return read_cram_batch(reader, header, reference, max_reads, n_read);
}
};
let mut batch = Batch {
records: Vec::with_capacity(BATCH),
bases: Vec::new(),
windows: Vec::new(),
cram: None,
};
while batch.len() < BATCH && max_reads.is_none_or(|m| *n_read < m) {
let mut record = AlignmentRecord::default();
let n = reader
.read_record(header, &mut record)
.map_err(|e| Failure::Input(format!("record {}: {e}", *n_read + 1)))?;
if n == 0 {
break;
}
*n_read += 1;
if let Some(reference) = reference.as_mut() {
let window =
fetch_window(reference, header, &record, &mut batch.bases).map_err(|e| {
let name = record.name().map_or_else(|| "*".into(), |n| n.to_string());
Failure::Input(format!("record {} (read {name}): {e}", *n_read))
})?;
batch.windows.push(window);
}
batch.records.push(record);
}
Ok(batch)
}
fn read_cram_batch(
reader: &mut pmdshodh::cram::Reader,
header: &noodles::sam::Header,
reference: &mut Option<Reference>,
max_reads: Option<u64>,
n_read: &mut u64,
) -> Result<Batch, Failure> {
let error = |e: io::Error| Failure::Input(format!("CRAM records after record {n_read}: {e}"));
let mut batch = Batch {
records: Vec::new(),
bases: Vec::new(),
windows: Vec::new(),
cram: None,
};
if max_reads.is_some_and(|m| *n_read >= m) {
return Ok(batch);
}
let containers = reader
.read_containers(rayon::current_num_threads())
.map_err(error)?;
let ids: Vec<usize> = containers
.iter()
.filter_map(pmdshodh::cram::reference_sequence_id)
.collect();
let (repository, checks) = reference
.as_mut()
.expect("CRAM input is opened with -r")
.cram_batch(header, &ids)
.map_err(error)?;
let records: u64 = containers
.iter()
.map(|c| c.header().record_count() as u64)
.sum();
let keep = max_reads.map_or(records, |m| records.min(m - *n_read));
if keep > 0 {
batch.cram = Some(CramBatch {
containers,
repository,
checks: checks.into(),
keep: keep as usize,
first: *n_read,
});
*n_read += keep;
}
Ok(batch)
}
fn fetch_window(
reference: &mut Reference,
header: &noodles::sam::Header,
record: &AlignmentRecord,
bases: &mut Vec<u8>,
) -> io::Result<Option<std::ops::Range<usize>>> {
if record.flags()?.is_unmapped() {
return Ok(None);
}
let invalid = |msg: &str| io::Error::new(io::ErrorKind::InvalidData, msg.to_string());
let id = record
.reference_sequence_id(header)
.transpose()?
.ok_or_else(|| invalid("mapped read has no reference sequence"))?;
let start = record
.alignment_start()
.transpose()?
.ok_or_else(|| invalid("mapped read has no position"))?;
let span = record.alignment_span().transpose()?.unwrap_or(0);
let (name, _) = header
.reference_sequences()
.get_index(id)
.ok_or_else(|| invalid("reference sequence ID is not in the header"))?;
let name = std::str::from_utf8(name).map_err(|_| invalid("reference name is not UTF-8"))?;
let from = bases.len();
reference.fetch(name, usize::from(start) - 1, span, bases)?;
Ok(Some(from..bases.len()))
}
fn open_reference(path: Option<&Path>) -> Result<Option<Reference>, Failure> {
let Some(path) = path else {
return Ok(None);
};
if !path.exists() {
return Err(Failure::Input(format!(
"cannot open reference {}: no such file",
path.display()
)));
}
Reference::open(path)
.map(Some)
.map_err(|e| reference_error(path, e))
}
fn reference_error(path: &Path, e: io::Error) -> Failure {
Failure::Input(format!(
"cannot read reference {} or its index: {e} (index it with samtools faidx {})",
path.display(),
path.display()
))
}
fn check_reference(
reference: &Reference,
path: &Path,
header: &noodles::sam::Header,
) -> Result<usize, Failure> {
let mismatch = |what: String| {
Failure::Input(format!(
"reference {} does not match the input header ({what})",
path.display()
))
};
let (mut differ, mut missing) = (0, 0);
let (mut first_differ, mut first_missing) = (None, None);
for (name, seq) in header.reference_sequences() {
let len = usize::from(seq.length());
let found = match std::str::from_utf8(name) {
Ok(name) => reference.length(name),
Err(_) => reference.length(&name.to_string()),
};
match found {
Some(l) if l == len => {}
Some(l) => {
differ += 1;
first_differ.get_or_insert_with(|| {
format!("{name} has {len} bases in the header, {l} in the reference")
});
}
None => {
missing += 1;
first_missing.get_or_insert_with(|| name.to_string());
}
}
}
let n = header.reference_sequences().len();
if let Some(first) = first_differ {
return Err(mismatch(format!(
"{differ} of {n} sequences have a different length; {first}"
)));
}
if n > 0 && missing == n {
return Err(mismatch(if n == 1 {
format!(
"{} is not in the reference",
first_missing.unwrap_or_default()
)
} else {
format!("none of the {n} header sequences is in the reference")
}));
}
Ok(missing)
}
fn score_batch(
batch: &Batch,
settings: &Settings,
filters: &ReadFilters,
range: Option<usize>,
) -> Scored {
use rayon::prelude::*;
let chunk = batch.len().div_ceil(rayon::current_num_threads()).max(1);
batch
.records
.par_chunks(chunk)
.enumerate()
.map(|(c, records)| {
let mut damage = range.map(DamageCounts::new);
let mut pattern = PatternCounts::default();
let outcomes = records
.iter()
.enumerate()
.map(|(k, r)| {
let window = batch.window(c * chunk + k);
let (d, p) = (damage.as_mut(), Some(&mut pattern));
match r {
AlignmentRecord::Bam(b) => process_bam(b, settings, filters, window, d, p),
_ => process(r, settings, filters, window, d, p),
}
})
.collect();
(outcomes, damage, pattern)
})
.collect()
}
fn consume_batch(
batch: &[AlignmentRecord],
parts: &Scored,
first: u64,
summary: &mut Summary,
on_scored: &mut impl FnMut(&AlignmentRecord, &ReadScore) -> Result<Option<bool>, Failure>,
) -> Result<(), Failure> {
let outcomes = parts.iter().flat_map(|(o, _, _)| o.iter());
for (k, (record, outcome)) in batch.iter().zip(outcomes).enumerate() {
let flags = record.flags().map_err(|e| {
Failure::Input(format!(
"record {}: invalid FLAG: {e}",
first + k as u64 + 1
))
})?;
summary.add_input(flags);
match outcome {
Ok(Outcome::Scored { score, length, md }) => {
let kept = on_scored(record, score)?;
summary.add_scored(score, *length, kept);
summary.add_md_check(*md);
}
Ok(Outcome::Skipped(reason)) => summary.add_skipped(*reason),
Err(msg) => {
let name = record.name().map_or_else(|| "*".into(), |n| n.to_string());
return Err(Failure::Input(format!("read {name}: {msg}")));
}
}
}
for (_, damage, pattern) in parts {
if let Some(damage) = damage {
summary.damage.merge(damage);
}
summary.pattern.merge(pattern);
}
Ok(())
}
const MAX_RANGE: usize = 1000;
const MAX_THREADS: usize = 1024;
fn check_range(range: usize) -> Result<(), Failure> {
if range == 0 {
return Err(Failure::Input("--range must be at least 1".into()));
}
if range > MAX_RANGE {
return Err(Failure::Input(format!(
"--range must be at most {MAX_RANGE}, got {range}"
)));
}
Ok(())
}
fn init_threads(threads: usize) -> Result<(), Failure> {
if threads == 0 {
return Err(Failure::Input("--threads must be at least 1".into()));
}
if threads > MAX_THREADS {
return Err(Failure::Input(format!(
"--threads must be at most {MAX_THREADS}, got {threads}"
)));
}
rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build_global()
.map_err(|e| Failure::Runtime(format!("cannot start threads: {e}")))
}
fn command_line() -> String {
std::env::args().collect::<Vec<_>>().join(" ")
}
fn write_json(
(output, mut w): (Output, Box<dyn Write + Send>),
value: &serde_json::Value,
) -> Result<(), Failure> {
let text = serde_json::to_string_pretty(value)
.map_err(|e| Failure::Runtime(format!("cannot format summary: {e}")))?
+ "\n";
let write_err = output.write_err();
w.write_all(text.as_bytes()).map_err(&write_err)?;
w.flush().map_err(&write_err)?;
drop(w);
output.commit()
}
struct Finish<'a> {
subcommand: &'a str,
input: &'a Path,
input_format: InputFormat,
settings: Settings,
filters: ReadFilters,
threshold: Option<f64>,
upper_threshold: Option<f64>,
reference: Option<&'a Path>,
missing_sequences: usize,
outputs: Vec<String>,
}
fn output_name(path: Option<&Path>) -> String {
match path.filter(|p| p.as_os_str() != "-") {
Some(p) => p.display().to_string(),
None => "standard output".to_string(),
}
}
impl Finish<'_> {
fn json(&self, summary: &Summary) -> serde_json::Value {
summary.to_json(&RunInfo {
subcommand: self.subcommand,
command: command_line(),
input: self.input.display().to_string(),
input_format: self.input_format.name(),
settings: self.settings,
filters: self.filters,
threshold: self.threshold,
upper_threshold: self.upper_threshold,
reference: self.reference.map(|p| p.display().to_string()),
})
}
fn report(
&self,
json: &serde_json::Value,
summary: &Summary,
quiet: bool,
elapsed: std::time::Duration,
) {
if quiet {
return;
}
let r = &json["reads"];
let count = |v: &serde_json::Value| v.as_u64().unwrap_or(0);
let first = &json["damage"]["first_position"];
let report = display::RunReport {
subcommand: self.subcommand.to_string(),
input: shown(self.input),
format: self.input_format.name(),
reference: self.reference.map(|p| p.display().to_string()),
library: match self.settings.library {
Library::DoubleStranded => "ds",
Library::SingleStranded => "ss",
},
treatment: match self.settings.treatment {
Treatment::None => "none",
Treatment::Half => "half",
Treatment::Full => "full",
},
compat: self.settings.pmdtools_compat,
threshold: self.threshold,
upper_threshold: self.upper_threshold,
reads: count(&r["input"]),
scored: count(&r["scored"]),
no_sites: count(&r["no_informative_sites"]),
kept: r["kept"].as_u64(),
skipped: SkipReason::ALL
.iter()
.zip(summary.skipped())
.filter(|(_, n)| **n > 0)
.map(|(reason, n)| (reason.name(), *n))
.collect(),
at_threshold: summary.kept_at_threshold(),
first_base: (count(&first["n"]) > 0).then(|| {
(
first["c_to_t"].as_f64().unwrap_or(0.0),
first["se"].as_f64().unwrap_or(0.0),
count(&first["n"]),
)
}),
mode_notes: ModeCheck::new(
&summary.pattern,
self.settings.library,
self.settings.treatment,
)
.notes(),
md_disagreeing: summary.md_disagreeing(),
paired: count(&r["flags"]["paired"]),
missing_sequences: self.missing_sequences,
outputs: self.outputs.clone(),
elapsed,
};
eprintln!("{}", report.render(display::Style::detect()));
}
}
fn run_score(args: &ScoreArgs) -> Result<(), Failure> {
let (settings, filters) = args.model.settings().map_err(Failure::Input)?;
check_range(args.summary.range)?;
init_threads(args.model.threads)?;
check_outputs(
&args.input,
args.model.reference.as_deref(),
&[args.output.as_deref(), args.summary.summary.as_deref()],
)?;
let mut progress = display::Progress::new("score", args.quiet);
let (mut reader, header, mut reference, input_format, missing_sequences) =
open_alignments(&args.input, &args.model)?;
let (output, out) = Output::open(args.output.as_deref())?;
let summary_out = args
.summary
.summary
.as_deref()
.map(|p| Output::open(Some(p)))
.transpose()?;
let mut out = BufWriter::new(out);
let write_err = output.write_err();
writeln!(out, "read_name\tflag\tpmds\tn_sites").map_err(&write_err)?;
let mut summary = Summary::new(args.summary.range);
let scanned = scan(
&mut reader,
&header,
&mut reference,
&settings,
&filters,
&mut summary,
args.summary.summary.is_some(),
None,
args.model.threads,
&mut progress,
&|_| false,
|record, s| {
let name = record
.name()
.map_or_else(|| "*".to_string(), |n| n.to_string());
let flag = record.flags().map(u16::from).unwrap_or_default();
writeln!(out, "{name}\t{flag}\t{}\t{}", s.pmds, s.n_sites).map_err(&write_err)?;
Ok(None)
},
);
if let Err(e) = scanned {
let _ = out.into_parts();
return Err(e);
}
out.flush().map_err(&write_err)?;
drop(out);
output.commit()?;
let fin = Finish {
subcommand: "score",
input: &args.input,
input_format,
settings,
filters,
threshold: None,
upper_threshold: None,
reference: args.model.reference.as_deref(),
missing_sequences,
outputs: [Some(output_name(args.output.as_deref()))]
.into_iter()
.chain([args
.summary
.summary
.as_deref()
.map(|p| output_name(Some(p)))])
.flatten()
.collect(),
};
let json = fin.json(&summary);
if let Some(s) = summary_out {
write_json(s, &json)?;
}
progress.clear();
fin.report(&json, &summary, args.quiet, progress.elapsed());
Ok(())
}
fn run_damage(args: &DamageArgs) -> Result<(), Failure> {
let (settings, filters) = args.model.settings().map_err(Failure::Input)?;
check_range(args.range)?;
init_threads(args.model.threads)?;
check_outputs(
&args.input,
args.model.reference.as_deref(),
&[args.output.as_deref()],
)?;
let mut progress = display::Progress::new("damage", args.quiet);
let (mut reader, header, mut reference, input_format, missing_sequences) =
open_alignments(&args.input, &args.model)?;
let json_out = Output::open(args.output.as_deref())?;
let mut summary = Summary::new(args.range);
scan(
&mut reader,
&header,
&mut reference,
&settings,
&filters,
&mut summary,
true,
args.max_reads,
args.model.threads,
&mut progress,
&|_| false,
|_, _| Ok(None),
)?;
let fin = Finish {
subcommand: "damage",
input: &args.input,
input_format,
settings,
filters,
threshold: None,
upper_threshold: None,
reference: args.model.reference.as_deref(),
missing_sequences,
outputs: vec![output_name(args.output.as_deref())],
};
let json = fin.json(&summary);
write_json(json_out, &json)?;
progress.clear();
fin.report(&json, &summary, args.quiet, progress.elapsed());
Ok(())
}
fn run_report(args: &ReportArgs) -> Result<(), Failure> {
for (i, path) in args.summaries.iter().enumerate() {
if args.summaries[..i]
.iter()
.any(|earlier| earlier == path || same_file(earlier, path))
{
return Err(Failure::Input(format!("{} is given twice", path.display())));
}
check_outputs(path, None, &[Some(&args.output)])?;
}
let (output, mut w) = Output::open(Some(&args.output))?;
let mut samples = Vec::new();
for path in &args.summaries {
let shown = path.display().to_string();
let text =
std::fs::read(path).map_err(|e| Failure::Input(format!("cannot read {shown}: {e}")))?;
let json: serde_json::Value = serde_json::from_slice(&text)
.map_err(|e| Failure::Input(format!("{shown} is not valid JSON: {e}")))?;
samples.push(pmdshodh::report::parse(&shown, &json).map_err(Failure::Input)?);
}
let names: Vec<(&str, &str)> = samples
.iter()
.map(|s| (s.source.as_str(), s.input.as_str()))
.collect();
let labels = pmdshodh::report::labels(&names);
for (s, label) in samples.iter_mut().zip(labels) {
s.label = label;
}
let html = pmdshodh::report::render(&samples);
let shown = output.shown.clone();
let write_err = output.write_err();
w.write_all(html.as_bytes()).map_err(&write_err)?;
w.flush().map_err(&write_err)?;
drop(w);
output.commit()?;
if !args.quiet {
eprintln!(
"pmdshodh report: {} sample{} written to {shown}",
samples.len(),
if samples.len() == 1 { "" } else { "s" }
);
}
Ok(())
}
fn encode_tagged<'e>(
encoder: &'e mut noodles::bam::io::Writer<Vec<u8>>,
header: &noodles::sam::Header,
record: &AlignmentRecord,
tag: noodles::sam::alignment::record::data::field::Tag,
tag_name: TagName,
pmds: f64,
) -> io::Result<Option<&'e [u8]>> {
use noodles::sam::alignment::io::Write as _;
let AlignmentRecord::Bam(bam) = record else {
return Ok(None);
};
if bam.data().get(&tag).is_some() {
return Ok(None);
}
encoder.get_mut().clear();
encoder.write_alignment_record(header, record)?;
let out = encoder.get_mut();
out.extend_from_slice(tag.as_ref());
match tag_name {
TagName::Pm => {
out.push(b'f');
out.extend_from_slice(&(pmds as f32).to_le_bytes());
}
TagName::Ds => {
out.push(b'Z');
out.extend_from_slice(pmdtools_ds_text(pmds).as_bytes());
out.push(0);
}
}
let block_size =
u32::try_from(out.len() - 4).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
out[..4].copy_from_slice(&block_size.to_le_bytes());
Ok(Some(out))
}
fn pmdtools_ds_text(x: f64) -> String {
let mut s = format!("{x:.3}");
while s.ends_with('0') && !s.ends_with(".0") {
s.pop();
}
s
}
struct Output {
shown: String,
rename: Option<(PathBuf, PathBuf)>,
to_stdout: bool,
}
impl Output {
fn open(path: Option<&Path>) -> Result<(Self, Box<dyn Write + Send>), Failure> {
let Some(path) = path.filter(|p| p.as_os_str() != "-") else {
let out = Output {
shown: "standard output".into(),
rename: None,
to_stdout: true,
};
return Ok((out, Box::new(io::stdout())));
};
let shown = path.display().to_string();
let cannot = |e: io::Error| Failure::Runtime(format!("cannot create {shown}: {e}"));
let dest = match std::fs::metadata(path) {
_ if is_windows_device(path) => None,
Ok(m) if m.is_dir() => {
return Err(Failure::Input(format!("output {shown} is a directory")));
}
Ok(m) if m.is_file() => Some(std::fs::canonicalize(path).map_err(cannot)?),
Ok(_) => None,
Err(_) if path.symlink_metadata().is_ok() => None,
Err(_) => Some(path.to_path_buf()),
};
let (file, rename) = match dest {
Some(dest) => {
let mut name = dest.file_name().unwrap_or_default().to_os_string();
name.push(".pmdshodh-tmp");
let tmp = dest.with_file_name(name);
temporary().push(tmp.clone());
let file = File::create(&tmp).map_err(|e| {
forget_temporary(&tmp);
cannot(e)
})?;
(file, Some((tmp, dest)))
}
None => (File::create(path).map_err(cannot)?, None),
};
let out = Output {
shown,
rename,
to_stdout: false,
};
Ok((out, Box::new(file)))
}
fn write_err(&self) -> impl Fn(io::Error) -> Failure + Send + Sync + use<> {
let (shown, to_stdout) = (self.shown.clone(), self.to_stdout);
move |e| {
if to_stdout && e.kind() == io::ErrorKind::BrokenPipe {
Failure::BrokenPipe
} else {
Failure::Runtime(format!("cannot write {shown}: {e}"))
}
}
}
fn commit(mut self) -> Result<(), Failure> {
if let Some((tmp, dest)) = self.rename.take() {
let renamed = std::fs::rename(&tmp, &dest);
if renamed.is_err() {
let _ = std::fs::remove_file(&tmp);
}
forget_temporary(&tmp);
if let Err(e) = renamed {
return Err(Failure::Runtime(format!(
"cannot write {}: {e}",
self.shown
)));
}
}
Ok(())
}
}
impl Drop for Output {
fn drop(&mut self) {
if let Some((tmp, _)) = &self.rename {
let _ = std::fs::remove_file(tmp);
forget_temporary(tmp);
}
}
}
static TEMPORARY: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());
fn temporary() -> std::sync::MutexGuard<'static, Vec<PathBuf>> {
TEMPORARY.lock().unwrap_or_else(|e| e.into_inner())
}
fn forget_temporary(tmp: &Path) {
temporary().retain(|p| p != tmp);
}
fn clean_up_on_signals() {
fn remove_temporary() {
for tmp in temporary().iter() {
let _ = std::fs::remove_file(tmp);
}
}
#[cfg(unix)]
{
use signal_hook::consts::{SIGHUP, SIGINT, SIGTERM};
if let Ok(mut signals) = signal_hook::iterator::Signals::new([SIGINT, SIGTERM, SIGHUP]) {
std::thread::spawn(move || {
if let Some(signal) = signals.forever().next() {
remove_temporary();
let _ = signal_hook::low_level::emulate_default_handler(signal);
std::process::exit(128 + signal);
}
});
}
}
#[cfg(windows)]
{
let _ = ctrlc::set_handler(|| {
remove_temporary();
std::process::exit(130);
});
}
}
fn is_special(path: &Path) -> bool {
is_windows_device(path) || std::fs::metadata(path).is_ok_and(|m| !m.is_file() && !m.is_dir())
}
fn is_windows_device(path: &Path) -> bool {
if !cfg!(windows) {
return false;
}
let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
return false;
};
let name = name.to_ascii_uppercase();
matches!(name.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| (name.len() == 4
&& (name.starts_with("COM") || name.starts_with("LPT"))
&& matches!(name.as_bytes()[3], b'1'..=b'9'))
}
fn same_file(a: &Path, b: &Path) -> bool {
let (Ok(ma), Ok(mb)) = (std::fs::metadata(a), std::fs::metadata(b)) else {
return false;
};
if !ma.is_file() || !mb.is_file() {
return false;
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
ma.dev() == mb.dev() && ma.ino() == mb.ino()
}
#[cfg(not(unix))]
{
std::fs::canonicalize(a).ok() == std::fs::canonicalize(b).ok()
}
}
fn check_outputs(
input: &Path,
reference: Option<&Path>,
outputs: &[Option<&Path>],
) -> Result<(), Failure> {
let outputs: Vec<&Path> = outputs
.iter()
.flatten()
.copied()
.filter(|p| p.as_os_str() != "-")
.collect();
for (i, out) in outputs.iter().enumerate() {
for (what, other) in [("input", Some(input)), ("reference", reference)] {
if other.is_some_and(|o| same_file(out, o)) {
return Err(Failure::Input(format!(
"output {} is the {what} file: write to a different file",
out.display()
)));
}
}
if outputs[i + 1..]
.iter()
.any(|later| same_file(out, later) || (out == later && !is_special(out)))
{
return Err(Failure::Input(format!(
"{} is given for two outputs",
out.display()
)));
}
}
Ok(())
}
fn run_filter(args: &FilterArgs) -> Result<(), Failure> {
use noodles::sam;
use noodles::sam::alignment::RecordBuf;
use noodles::sam::alignment::record::data::field::Tag;
use noodles::sam::alignment::record_buf::data::field::Value;
use noodles::sam::header::record::value::{Map, map::program::tag as pg};
let (settings, filters) = args.model.settings().map_err(Failure::Input)?;
for (name, bound) in [
("--threshold", args.threshold),
("--upper-threshold", args.upper_threshold),
] {
if bound.is_some_and(|b| !b.is_finite()) {
return Err(Failure::Input(format!(
"{name} must be a finite number, got {}",
bound.unwrap()
)));
}
}
let compat_keeps_none = settings.pmdtools_compat
&& args.threshold.is_none_or(|t| t <= -10000.0)
&& args.upper_threshold.is_none_or(|u| u >= 1e6);
if compat_keeps_none && !args.quiet {
eprintln!(
"pmdshodh filter: with --pmdtools-compat, --threshold <= -10000 and \
--upper-threshold >= 1000000 count as not given, as in PMDtools 0.60, so no reads \
are kept"
);
}
check_range(args.summary.range)?;
init_threads(args.model.threads)?;
let format = output_format(&args.output, args.output_format)?;
check_outputs(
&args.input,
args.model.reference.as_deref(),
&[Some(&args.output), args.summary.summary.as_deref()],
)?;
let mut progress = display::Progress::new("filter", args.quiet);
let (mut reader, mut header, mut reference, input_format, missing_sequences) =
open_alignments(&args.input, &args.model)?;
let program = Map::<sam::header::record::value::map::Program>::builder()
.insert(pg::NAME, "pmdshodh")
.insert(pg::VERSION, env!("CARGO_PKG_VERSION"))
.insert(pg::COMMAND_LINE, command_line())
.build()
.map_err(|e| Failure::Runtime(format!("cannot build @PG line: {e}")))?;
header
.programs_mut()
.add("pmdshodh", program)
.map_err(|e| Failure::Runtime(format!("cannot add @PG line: {e}")))?;
let (output, sink) = Output::open(Some(&args.output))?;
let summary_out = args
.summary
.summary
.as_deref()
.map(|p| Output::open(Some(p)))
.transpose()?;
let mut writer = OutWriter::new(format, sink, args.model.threads)?;
let write_err = output.write_err();
writer.write_header(&header).map_err(&write_err)?;
let tag = match args.tag_name {
TagName::Pm => Tag::new(b'p', b'm'),
TagName::Ds => Tag::new(b'D', b'S'),
};
let mut encoder = noodles::bam::io::Writer::from(Vec::new());
let mut summary = Summary::new(args.summary.range);
let keep = |score: &ReadScore| {
!compat_keeps_none
&& args.threshold.is_none_or(|t| score.pmds >= t)
&& args
.upper_threshold
.is_none_or(|u| score.pmds < u && (score.n_sites > 0 || settings.pmdtools_compat))
};
scan(
&mut reader,
&header,
&mut reference,
&settings,
&filters,
&mut summary,
args.summary.summary.is_some(),
None,
args.model.threads,
&mut progress,
&keep,
|record, score| {
if !keep(score) {
return Ok(Some(false));
}
check_reference_ids(record, &header).map_err(|msg| {
let name = record.name().map_or_else(|| "*".into(), |n| n.to_string());
Failure::Input(format!("read {name}: {msg}"))
})?;
let long_cigar = record.cigar().len() > usize::from(u16::MAX);
if args.tag
&& !long_cigar
&& let OutWriter::Bam(w) = &mut writer
&& let Some(encoded) = encode_tagged(
&mut encoder,
&header,
record,
tag,
args.tag_name,
score.pmds,
)
.map_err(&write_err)?
{
w.get_mut().write_all(encoded).map_err(&write_err)?;
} else if args.tag || long_cigar {
let mut buf = RecordBuf::try_from_alignment_record(&header, record)
.map_err(|e| Failure::Input(format!("cannot copy record: {e}")))?;
if long_cigar {
buf.data_mut().remove(&Tag::new(b'C', b'G'));
}
if args.tag {
let value = match args.tag_name {
TagName::Pm => Value::Float(score.pmds as f32),
TagName::Ds => Value::String(pmdtools_ds_text(score.pmds).into()),
};
buf.data_mut().insert(tag, value);
}
writer.write_record(&header, &buf).map_err(&write_err)?;
} else {
writer.write_record(&header, record).map_err(&write_err)?;
}
Ok(Some(true))
},
)?;
writer.finish(&header).map_err(&write_err)?;
drop(writer);
output.commit()?;
let fin = Finish {
subcommand: "filter",
input: &args.input,
input_format,
settings,
filters,
threshold: args.threshold,
upper_threshold: args.upper_threshold,
reference: args.model.reference.as_deref(),
missing_sequences,
outputs: [Some(output_name(Some(&args.output)))]
.into_iter()
.chain([args
.summary
.summary
.as_deref()
.map(|p| output_name(Some(p)))])
.flatten()
.collect(),
};
let json = fin.json(&summary);
if let Some(s) = summary_out {
write_json(s, &json)?;
}
progress.clear();
fin.report(&json, &summary, args.quiet, progress.elapsed());
Ok(())
}
fn output_format(
path: &Path,
flag: Option<OutputFormat>,
) -> Result<noodles_util::alignment::io::Format, Failure> {
use noodles_util::alignment::io::Format;
let name = |f: OutputFormat| match f {
OutputFormat::Bam => "bam",
OutputFormat::Sam => "sam",
};
let to_stdout = path.as_os_str() == "-";
let ext = path
.extension()
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase);
let from_ext = match ext.as_deref() {
_ if to_stdout => None,
Some("bam") => Some(OutputFormat::Bam),
Some("sam") => Some(OutputFormat::Sam),
Some("cram") => {
return Err(Failure::Input(format!(
"cannot write {}: CRAM output is not supported; use .bam or .sam",
path.display()
)));
}
_ => None,
};
let format = match (from_ext, flag) {
(Some(e), Some(f)) if e != f => {
return Err(Failure::Input(format!(
"--output-format {} contradicts the .{} extension of {}",
name(f),
name(e),
path.display()
)));
}
(Some(e), _) => e,
(None, f) if to_stdout || is_special(path) => f.unwrap_or(OutputFormat::Bam),
(None, _) => {
return Err(Failure::Input(format!(
"cannot tell the output format of {}: use a .bam or .sam extension",
path.display()
)));
}
};
Ok(match format {
OutputFormat::Bam => Format::Bam,
OutputFormat::Sam => Format::Sam,
})
}
enum OutWriter {
Sam(alignment::io::Writer<BufWriter<Box<dyn Write + Send>>>),
Bam(noodles::bam::io::Writer<pmdshodh::bgzf::Writer<Box<dyn Write + Send>>>),
}
impl OutWriter {
fn new(
format: noodles_util::alignment::io::Format,
sink: Box<dyn Write + Send>,
threads: usize,
) -> Result<Self, Failure> {
use noodles_util::alignment::io::Format;
Ok(match format {
Format::Bam => OutWriter::Bam(noodles::bam::io::Writer::from(
pmdshodh::bgzf::Writer::new(sink, threads > 1),
)),
_ => OutWriter::Sam(
alignment::io::writer::Builder::default()
.set_format(format)
.build_from_writer(BufWriter::new(sink))
.map_err(|e| Failure::Runtime(format!("cannot open output: {e}")))?,
),
})
}
fn write_header(&mut self, header: &noodles::sam::Header) -> io::Result<()> {
match self {
OutWriter::Sam(w) => w.write_header(header),
OutWriter::Bam(w) => w.write_header(header),
}
}
fn write_record<R: noodles::sam::alignment::Record>(
&mut self,
header: &noodles::sam::Header,
record: &R,
) -> io::Result<()> {
use noodles::sam::alignment::io::Write as _;
match self {
OutWriter::Sam(w) => w.write_record(header, record),
OutWriter::Bam(w) => w.write_alignment_record(header, record),
}
}
fn finish(&mut self, header: &noodles::sam::Header) -> io::Result<()> {
match self {
OutWriter::Sam(w) => w.finish(header),
OutWriter::Bam(w) => w.get_mut().finish(),
}
}
}