1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use anyhow::Context as _;
use clap::ValueEnum;
use compact_genome::implementation::alphabets::dna_alphabet_or_n::DnaAlphabetOrN;
use lib_tsalign::a_star_aligner::configurable_a_star_align::MinLengthStrategySelector;
use lib_tsalign::a_star_aligner::template_switch_distance::TSMUncertaintyRangeExtensionMode;
use lib_tsalign::config::TemplateSwitchConfig;
use lib_tsalign::costs::U64Cost;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::str::FromStr;
use std::{fs::File, io::BufReader, time::Duration};
use tokio::sync::Semaphore;
use tracing::warn;
use bytesize::ByteSize;
use crate::common::aligner::db::CliDatabaseArgs;
use crate::common::aligner::{AlignerSelector, chain, fpa::FourPointAligner};
#[derive(clap::Args, Debug)]
#[command(next_help_heading = "Alignment")]
#[expect(
clippy::struct_excessive_bools,
reason = "independent command line flags"
)]
pub struct CliAlignmentArgs {
/// Number of threads to use for the alignments. Defaults to the number of available cores.
#[arg(long = "threads", value_name = "NUM")]
pub num_threads: Option<usize>,
/// Set an overall memory limit, for example 4gb or 500mb. It is split evenly across the threads.
/// Defaults to the memory currently available on the machine, so results may differ between machines and runs unless it is set explicitly.
#[arg(short, long, global = true, value_name = "EXPR", value_parser = ByteSize::from_str)]
pub memory_limit: Option<ByteSize>,
/// Set a timeout for each individual run of the aligner, as a number with a unit: `ms`, `s`, `m` or `h` (e.g. `30s`).
/// If an alignment takes longer than that, it will fail and no template switch is found. Unlimited by default.
#[arg(long = "aligner-timeout", value_name = "EXPR", value_parser = parse_duration)]
pub aligner_timeout: Option<Duration>,
/// How much context to add on each side of a mutation cluster. This bounds where a template
/// switch may "jump" to (e.g. 100 for +-100 bases around the cluster), but not where it may
/// start and end -- that is what --range-extension bounds.
#[arg(short, long, default_value_t = 200, value_name = "BASES")]
pub padding: usize,
/// How many extra bases on each side of the cluster the alignment range covers. A template
/// switch must start and end inside that range, so this bounds where one may be placed, while
/// --padding bounds where it may jump to. Raising --padding alone does not help an event whose
/// entrance or exit falls outside the range.
#[arg(long = "range-extension", default_value_t = 5, value_name = "BASES")]
pub range_extension: usize,
/// A config file for the costs (in custom .tsa format), this is used by the aligner.
#[arg(short, long, value_name = "FILE")]
pub costs: Option<String>,
/// Force the aligner to NOT align with template switches, so no template switch is ever reported. Useful for performance benchmarks, useless otherwise.
#[arg(long)]
pub no_ts: bool,
/// Use the Four-Point-Aligner, based on dynamic programming. While it has limited capabilities, it is generally faster.
/// It cannot, however, find alignments that have indels in the inner part of the template switch or that have more than one template switch.
/// A best effort is made to keep the costs consistent with the `--costs` argument, with some exceptions. The most notable one is that since
/// this aligner is not gap-affine, there is no gap open cost. Only the cost for extending a gap is taken into account.
#[arg(long = "fpa")]
pub use_fpa: bool,
/// Use the chaining-based aligner from tsalign, which anchors the alignment on exact k-mer matches.
/// It needs a cost model with a single substitution, gap open and gap extend cost over A, C, G and T, and it only finds reverse template switches.
/// Graded `Length` penalties become a hard range: lengths with a zero cost are allowed, all others are forbidden.
/// Sequences containing other bases than A, C, G and T are skipped. The aligner needs preprocessed tables, which are cached for the run in a private directory under `$TMPDIR` and removed at its end.
#[arg(long = "chain", conflicts_with = "use_fpa")]
pub use_chain: bool,
/// With --chain: the k-mer size of the anchors. By default, it is inferred from the sequence lengths of each alignment, like tsalign does.
#[arg(long = "chain-k", value_name = "K", requires = "use_chain", value_parser = clap::value_parser!(u32).range(1..=64))]
pub chain_k: Option<u32>,
/// With --chain: the longest sequence the preprocessed tables support; longer sequences are skipped.
/// By default, the longer sequence of each alignment rounded up to a power of two, so a table is built per power of two.
/// A fixed value builds fewer tables, but larger ones, and building them takes much longer the larger they are.
#[arg(long = "chain-max-n", value_name = "BASES", requires = "use_chain")]
pub chain_max_n: Option<usize>,
/// Ignored with --fpa, --chain and --no-ts: Select a strategy to determine lower bounds on the length of a template switch. This is an implementation detail and not part of the cost function.
/// To enforce a minimum (or maximum) length of the inner part of a template switch, use the cost file.
#[arg(long, value_name = "ML_STRATEGY", default_value_t)]
pub min_length_strategy: MLSSelector,
/// Ignored with --fpa, --chain and --no-ts: Select how to compute the uncertainty ranges around template switches. See the aligner repo for details.
#[arg(long, value_name = "UR_MODE", default_value_t)]
pub uncertainty_range_mode: URMSelector,
/// Ignored with --fpa, --chain and --no-ts: Allow multiple template switches in the same solution to have different descendants. By default, all template switches in the solution must have the same descendant, but it can be either of the sequences (ref / alt).
#[arg(long)]
pub allow_mixed_descendants: bool,
/// If specified, write the region of every failed alignment to this file, one per line,
/// in samtools region format (chr:start-end, 1-based inclusive). The file can be passed
/// directly to samtools/bcftools via -R or -T to retry or inspect failed regions.
#[arg(long = "output-failed-alignments", value_name = "FILE")]
pub failed_alignments_output: Option<String>,
/// If specified, write one CSV row per alignment to this file, covering runtime, peak memory,
/// where the result came from (a fresh computation, the in-memory cache or the database) and
/// the statistics reported by the aligner. Clusters that map to the same alignment yield one
/// row each; filter on `source == computed` to see only the alignments that were actually run.
#[arg(long = "output-alignment-stats", value_name = "FILE")]
pub alignment_stats_output: Option<String>,
#[clap(flatten)]
pub database: CliDatabaseArgs,
}
fn parse_duration(s: &str) -> anyhow::Result<Duration> {
if s.is_empty() {
anyhow::bail!("empty duration string");
}
let ix = s
.find(|c: char| !c.is_ascii_digit() && c != '.')
.ok_or_else(|| anyhow::anyhow!("no unit detected"))?;
let (number, unit) = s.split_at_checked(ix).context("non-utf8 duration string")?;
let value: u64 = number.trim().parse()?;
let dur = match unit.trim() {
"ms" => Duration::from_millis(value),
"s" => Duration::from_secs(value),
"m" => Duration::from_mins(value),
"h" => Duration::from_hours(value),
_ => anyhow::bail!("unknown duration unit: {unit}"),
};
Ok(dur)
}
impl Default for CliAlignmentArgs {
fn default() -> Self {
Self {
num_threads: None,
memory_limit: None,
aligner_timeout: None,
padding: 200,
range_extension: 5,
costs: None,
no_ts: false,
use_fpa: false,
use_chain: false,
chain_k: None,
chain_max_n: None,
min_length_strategy: MLSSelector::default(),
uncertainty_range_mode: URMSelector::default(),
allow_mixed_descendants: false,
failed_alignments_output: None,
alignment_stats_output: None,
database: CliDatabaseArgs::default(),
}
}
}
fn default_costs() -> anyhow::Result<TemplateSwitchConfig<DnaAlphabetOrN, U64Cost>> {
let costs = include_bytes!("../../../default_costs.tsa");
TemplateSwitchConfig::read_plain(&costs[..]).context("unable to parse the default cost file")
}
impl CliAlignmentArgs {
pub(super) fn init_aligner(
&self,
) -> anyhow::Result<(
AlignerSelector,
TemplateSwitchConfig<DnaAlphabetOrN, U64Cost>,
)> {
let costs = if let Some(cost_path) = &self.costs {
tracing::info!("Loading costs from {cost_path}");
let file = BufReader::new(File::open(cost_path)?);
TemplateSwitchConfig::read_plain(file)?
} else {
tracing::info!("Using default costs");
default_costs()?
};
let aligner = if self.use_fpa {
AlignerSelector::Fpa(FourPointAligner::new(costs.clone(), self.no_ts))
} else if self.use_chain {
AlignerSelector::Chain {
costs: chain::costs_from_config(&costs, self.no_ts)?,
k: self.chain_k,
max_n: self.chain_max_n,
}
} else {
AlignerSelector::AStar {
costs: costs.clone(),
min_length_strategy: self.min_length_strategy,
uncertainty_range_mode: self.uncertainty_range_mode,
allow_mixed_descendants: self.allow_mixed_descendants,
no_ts: self.no_ts,
}
};
// Only after the aligner accepted the costs: the warnings assume a usable setup.
crate::common::settings_warnings::warn_about_alignment_settings(self, &costs);
Ok((aligner, costs))
}
pub fn init_semaphore(&self) -> anyhow::Result<(Semaphore, usize)> {
let n = if let Some(num) = self.num_threads {
num.try_into()?
} else {
std::thread::available_parallelism()?
};
let sem = Semaphore::new(n.into());
let total_memory = usize::try_from(
self.memory_limit
.map_or_else(default_memory_limit, Ok)?
.as_u64(),
)
.context("The memory limit is too high")?;
let memory_per_thread = total_memory / n;
Ok((sem, memory_per_thread))
}
}
#[derive(Default, ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MLSSelector {
/// Do not compute lower bounds. Turns A* into Dijkstra.
None,
/// Compute a lower bound by looking ahead from each candidate jump.
Lookahead,
/// Check for perfect matches of minimum length and filter out imperfect matches. Note that
/// this is only implemented for reverse template switches; with forward ones enabled, prefer `lookahead`.
#[default]
PreprocessFilter,
/// Check for perfect matches of minimum length and compute a lower bound for imperfect matches.
PreprocessPrice,
/// Check for perfect matches of minimum length and cache the costs of imperfect matches.
PreprocessLookahead,
}
impl From<MLSSelector> for MinLengthStrategySelector {
fn from(value: MLSSelector) -> Self {
match value {
MLSSelector::None => Self::None,
MLSSelector::Lookahead => Self::Lookahead,
MLSSelector::PreprocessFilter => Self::PreprocessFilter,
MLSSelector::PreprocessPrice => Self::PreprocessPrice,
MLSSelector::PreprocessLookahead => Self::PreprocessLookahead,
}
}
}
impl Display for MLSSelector {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let pv = self.to_possible_value().ok_or(std::fmt::Error)?;
f.write_str(pv.get_name())
}
}
#[derive(Default, ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum URMSelector {
/// Do not compute uncertainty ranges; they are reported as invalid (`[-]`).
None,
/// Extend TS entrance and exit as far as possible without increasing the alignment cost.
#[default]
EqualCost,
/// Like `equal-cost`, but ignore cost increases that are caused by changing the template switch geometry.
/// For example, with this it is possible to report the minimum and maximum length of a perfect match,
/// even if the minimum (maximum) length is smaller than what is specified via `--costs`.
EqualCostIgnoreGeometry,
}
impl From<URMSelector> for TSMUncertaintyRangeExtensionMode {
fn from(value: URMSelector) -> Self {
match value {
URMSelector::None => Self::None,
URMSelector::EqualCost => Self::EqualCost,
URMSelector::EqualCostIgnoreGeometry => Self::EqualCostIgnoreGeometry,
}
}
}
impl Display for URMSelector {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let pv = self.to_possible_value().ok_or(std::fmt::Error)?;
f.write_str(pv.get_name())
}
}
fn default_memory_limit() -> anyhow::Result<ByteSize> {
let mut system = sysinfo::System::new_all()?;
system.refresh_memory();
let mem = ByteSize::b(system.total_memory() / 2);
warn!(
"No memory limit specified. Using {mem}, half of this machine's RAM, as the default. For reproducible runs, set the limit yourself with -m."
);
Ok(mem)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_duration_milliseconds() {
assert_eq!(parse_duration("100ms").unwrap(), Duration::from_millis(100));
}
#[test]
fn parse_duration_seconds() {
assert_eq!(parse_duration("5s").unwrap(), Duration::from_secs(5));
}
#[test]
fn parse_duration_minutes() {
assert_eq!(parse_duration("2m").unwrap(), Duration::from_mins(2));
}
#[test]
fn parse_duration_hours() {
assert_eq!(parse_duration("1h").unwrap(), Duration::from_hours(1));
}
#[test]
fn parse_duration_empty_is_error() {
assert!(parse_duration("").is_err());
}
#[test]
fn parse_duration_no_unit_is_error() {
assert!(parse_duration("100").is_err());
}
#[test]
fn parse_duration_unknown_unit_is_error() {
assert!(parse_duration("10d").is_err());
}
#[test]
fn parse_default_costs() {
let _ = default_costs();
}
}