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
pub mod bamlift;
pub mod basemods;
pub mod center;
pub mod cli;
pub mod extract;
pub mod predict_m6a;
use anyhow::Result;
use itertools::Itertools;
use lazy_static::lazy_static;
use regex::Regex;
use rust_htslib::{bam, bam::Read};
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{self, stdout, BufWriter, Write};
use std::path::PathBuf;
use std::process::exit;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const GIT_HASH: &str = env!("CARGO_GIT_HASH");
pub const LONG_VERSION: &str = env!("CARGO_LONG_VERSION");
const BUFFER_SIZE: usize = 32 * 1024;
const PROGRESS_STYLE: &str =
"[{elapsed_precise:.yellow}] {bar:50.cyan/blue} {human_pos:>5.cyan}/{human_len:.blue} {percent:>3.green}% {per_sec:<10.cyan}";
fn get_output(path: Option<PathBuf>) -> Result<Box<dyn Write + Send + 'static>> {
let writer: Box<dyn Write + Send + 'static> = match path {
Some(path) => {
if path.as_os_str() == "-" {
Box::new(BufWriter::with_capacity(BUFFER_SIZE, stdout()))
} else {
Box::new(BufWriter::with_capacity(BUFFER_SIZE, File::create(path)?))
}
}
None => Box::new(BufWriter::with_capacity(BUFFER_SIZE, stdout())),
};
Ok(writer)
}
pub fn unzip_to_vectors<T, U>(vec: Vec<(T, U)>) -> (Vec<T>, Vec<U>) {
vec.into_iter().unzip()
}
pub fn join_by_str<'a, I, Z>(vals: I, sep: &str) -> String
where
I: IntoIterator<Item = Z>,
Z: ToString + 'a,
{
vals.into_iter().map(|v| v.to_string() + sep).collect()
}
pub fn writer(filename: &str) -> Result<Box<dyn Write>> {
let path = PathBuf::from(filename);
let buffer = get_output(Some(path))?; Ok(buffer)
}
pub fn bam_reader(bam: &str, threads: usize) -> bam::Reader {
let mut bam = if bam == "-" {
bam::Reader::from_stdin().unwrap_or_else(|_| panic!("Failed to open bam from stdin"))
} else {
bam::Reader::from_path(bam).unwrap_or_else(|_| panic!("Failed to open {}", bam))
};
bam.set_threads(threads).unwrap();
bam
}
pub fn bam_writer(out: &str, template_bam: &bam::Reader, threads: usize) -> bam::Writer {
let mut header = bam::Header::from_template(template_bam.header());
let header_string = String::from_utf8_lossy(&header.to_bytes()).to_string();
let mut header_rec = bam::header::HeaderRecord::new(b"PG");
let ft_count = header_string.matches("PN:fibertools-rs").count();
header_rec.push_tag(b"ID", &format!("ft.{}", ft_count + 1));
header_rec.push_tag(b"PN", &"fibertools-rs");
let re_pp = Regex::new(r"@PG\tID:([^\t]+)").unwrap();
let last_program = re_pp.captures_iter(&header_string).last();
if let Some(last_program) = last_program {
let last_program = last_program[1].to_string();
log::trace!("last program {}", last_program);
header_rec.push_tag(b"PP", &last_program);
};
header_rec.push_tag(b"VN", &VERSION);
let cli = env::args().join(" ");
header_rec.push_tag(b"CL", &cli);
header.push_record(&header_rec);
log::trace!("{:?}", String::from_utf8_lossy(&header.to_bytes()));
let mut out = if out == "-" {
bam::Writer::from_stdout(&header, bam::Format::Bam).unwrap()
} else {
bam::Writer::from_path(out, &header, bam::Format::Bam).unwrap()
};
out.set_threads(threads).unwrap();
out
}
pub struct FiberOut {
pub m6a: Option<Box<dyn Write>>,
pub cpg: Option<Box<dyn Write>>,
pub msp: Option<Box<dyn Write>>,
pub nuc: Option<Box<dyn Write>>,
pub all: Option<Box<dyn Write>>,
pub reference: bool,
pub simplify: bool,
pub quality: bool,
pub min_ml_score: u8,
pub full_float: bool,
}
impl FiberOut {
#[allow(clippy::too_many_arguments)]
pub fn new(
m6a: &Option<String>,
cpg: &Option<String>,
msp: &Option<String>,
nuc: &Option<String>,
all: &Option<String>,
reference: bool,
simplify: bool,
quality: bool,
min_ml_score: u8,
full_float: bool,
) -> Result<Self> {
let m6a = match m6a {
Some(m6a) => Some(writer(m6a)?),
None => None,
};
let cpg = match cpg {
Some(cpg) => Some(writer(cpg)?),
None => None,
};
let msp = match msp {
Some(msp) => Some(writer(msp)?),
None => None,
};
let nuc = match nuc {
Some(nuc) => Some(writer(nuc)?),
None => None,
};
let all = match all {
Some(all) => Some(writer(all)?),
None => None,
};
let mut min_ml_score = min_ml_score;
if full_float {
min_ml_score = 0;
}
Ok(FiberOut {
m6a,
cpg,
msp,
nuc,
all,
reference,
simplify,
quality,
min_ml_score,
full_float,
})
}
}
pub fn write_to_file(out: &str, file: &mut Box<dyn Write>) {
let out = write!(file, "{}", out);
if let Err(err) = out {
if err.kind() == io::ErrorKind::BrokenPipe {
exit(0);
} else {
panic!("Error: {}", err);
}
}
}
pub fn write_to_stdout(out: &str) {
let mut out_f = Box::new(std::io::stdout()) as Box<dyn Write>;
write_to_file(out, &mut out_f);
}
use colored::Colorize;
use std::time::Instant;
struct BamChunk<'a> {
bam: bam::Records<'a, bam::Reader>,
chunk_size: usize,
}
impl<'a> Iterator for BamChunk<'a> {
type Item = Vec<bam::Record>;
fn next(&mut self) -> Option<Self::Item> {
let start = Instant::now();
let mut cur_vec = vec![];
for r in self.bam.by_ref().take(self.chunk_size) {
cur_vec.push(r.unwrap())
}
if cur_vec.is_empty() {
None
} else {
let duration = start.elapsed().as_secs_f64();
log::info!(
"Read {} bam records at {}.",
format!("{:}", cur_vec.len()).bright_magenta().bold(),
format!("{:.2?} reads/s", cur_vec.len() as f64 / duration)
.bright_cyan()
.bold(),
);
Some(cur_vec)
}
}
}
#[derive(Clone, Debug)]
pub enum PbChem {
Two,
TwoPointTwo,
Revio,
}
pub fn find_pb_polymerase(header: &bam::Header) -> PbChem {
lazy_static! {
static ref CHEMISTRY_MAP: HashMap<String, PbChem> = HashMap::from([
("101-789-500".to_string(), PbChem::Two),
("101-820-500".to_string(), PbChem::Two),
("101-894-200".to_string(), PbChem::TwoPointTwo),
("102-194-200".to_string(), PbChem::Two),
("102-194-100".to_string(), PbChem::TwoPointTwo),
("102-739-100".to_string(), PbChem::Revio)
]);
}
lazy_static! {
static ref MM_DS: regex::Regex =
regex::Regex::new(r".*READTYPE=([^;]+);.*BINDINGKIT=([^;]+);").unwrap();
}
let z = header.to_hashmap();
let rg = z.get("RG").expect("RG tag missing from bam file");
let mut read_type = "";
let mut binding_kit = "";
for tag in rg {
for (tag, val) in tag {
if tag == "DS" {
for cap in MM_DS.captures_iter(val) {
read_type = cap.get(1).map_or("", |m| m.as_str());
binding_kit = cap.get(2).map_or("", |m| m.as_str());
}
}
}
}
if env::var("FT_REVIO").is_ok() {
binding_kit = "102-739-100";
}
assert_eq!(read_type, "CCS");
let chemistry = CHEMISTRY_MAP.get(binding_kit).unwrap_or_else(|| {
log::warn!(
"Polymerase for BINDINGKIT={} not found. Defaulting to ML model made with 2.2",
binding_kit
);
&PbChem::TwoPointTwo
});
chemistry.clone()
}