1use std::io::{Read, Write};
2use std::path::Path;
3
4use noodles::core::Region;
5
6use crate::{
7 CallError, CallPloidy, CalledSite, CalledVariantWriter, CalledVcfSchema, ConsensusCaller,
8 ConsensusCallerConfig, GvcfBlocker, IndexedLikelihoodVariantReader, LikelihoodSite,
9 LikelihoodVariantReader, LikelihoodVcfSchema, MultiallelicCaller, MultiallelicCallerConfig,
10 PloidyResolver, Result, VariantOutputFormat, caller::validate_sample_groups,
11};
12
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub enum CallModel {
15 Multiallelic(MultiallelicCallerConfig),
16 Consensus(ConsensusCallerConfig),
17}
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20pub struct CallOutputOptions {
21 variants_only: bool,
22 keep_masked_reference: bool,
23 skip_snps: bool,
24 skip_indels: bool,
25}
26
27impl CallOutputOptions {
28 pub fn with_variants_only(mut self, enabled: bool) -> Self {
29 self.variants_only = enabled;
30 self
31 }
32
33 pub fn with_keep_masked_reference(mut self, enabled: bool) -> Self {
34 self.keep_masked_reference = enabled;
35 self
36 }
37
38 pub fn with_skip_snps(mut self, enabled: bool) -> Self {
39 self.skip_snps = enabled;
40 self
41 }
42
43 pub fn with_skip_indels(mut self, enabled: bool) -> Self {
44 self.skip_indels = enabled;
45 self
46 }
47
48 fn accepts(self, source: &LikelihoodSite, called: &CalledSite) -> bool {
49 if !self.keep_masked_reference && source.reference().as_bytes().contains(&b'N') {
50 return false;
51 }
52 if source.indel_summary().is_some() {
53 if self.skip_indels {
54 return false;
55 }
56 } else if self.skip_snps {
57 return false;
58 }
59 !self.variants_only || called.is_variant()
60 }
61}
62
63pub struct LikelihoodCallRun {
64 caller: SiteCaller,
65 ploidy: PloidyResolver,
66 gvcf: Option<GvcfBlocker>,
67 output: CallOutputOptions,
68 sample_groups: Option<Box<[usize]>>,
69}
70
71enum SiteCaller {
72 Multiallelic(MultiallelicCaller),
73 Consensus(ConsensusCaller),
74}
75
76impl LikelihoodCallRun {
77 pub fn new(model: CallModel, ploidy: PloidyResolver) -> Self {
78 let caller = match model {
79 CallModel::Multiallelic(config) => {
80 SiteCaller::Multiallelic(MultiallelicCaller::new(config))
81 }
82 CallModel::Consensus(config) => SiteCaller::Consensus(ConsensusCaller::new(config)),
83 };
84 Self {
85 caller,
86 ploidy,
87 gvcf: None,
88 output: CallOutputOptions::default(),
89 sample_groups: None,
90 }
91 }
92
93 pub fn with_gvcf(mut self, thresholds: impl Into<Box<[u32]>>) -> Result<Self> {
94 if matches!(&self.caller, SiteCaller::Consensus(_)) {
95 return Err(CallError::UnsupportedGvcfModel);
96 }
97 self.gvcf = Some(GvcfBlocker::new(thresholds)?);
98 Ok(self)
99 }
100
101 pub fn with_output_options(mut self, options: CallOutputOptions) -> Self {
102 self.output = options;
103 self
104 }
105
106 pub fn with_sample_groups(mut self, groups: impl IntoIterator<Item = usize>) -> Result<Self> {
107 if matches!(&self.caller, SiteCaller::Consensus(_)) {
108 return Err(CallError::UnsupportedCallerGroups);
109 }
110 let groups = groups.into_iter().collect::<Box<[_]>>();
111 if groups.len() != self.ploidy.sample_count() {
112 return Err(CallError::CallerGroupCountMismatch);
113 }
114 validate_sample_groups(&groups)?;
115 self.sample_groups = Some(groups);
116 Ok(self)
117 }
118
119 pub fn run<R, W>(
120 self,
121 mut reader: LikelihoodVariantReader<R>,
122 output: W,
123 format: VariantOutputFormat,
124 ) -> Result<W>
125 where
126 R: Read,
127 W: Write,
128 {
129 let mut run = self.start(reader.schema(), output, format)?;
130 while let Some(site) = reader.read_site()? {
131 run.push(reader.record_number(), &site)?;
132 }
133 run.finish()
134 }
135
136 pub fn run_indexed<W>(
137 self,
138 reader: IndexedLikelihoodVariantReader,
139 regions: impl IntoIterator<Item = Region>,
140 output: W,
141 format: VariantOutputFormat,
142 ) -> Result<W>
143 where
144 W: Write,
145 {
146 let regions = reader.normalize_regions(regions)?;
147 let mut run = self.start(reader.schema(), output, format)?;
148 reader.visit_normalized_regions(regions, |record, site| run.push(record, &site))?;
149 run.finish()
150 }
151
152 pub fn run_indexed_regions_file<W>(
153 self,
154 reader: IndexedLikelihoodVariantReader,
155 regions: impl AsRef<Path>,
156 output: W,
157 format: VariantOutputFormat,
158 ) -> Result<W>
159 where
160 W: Write,
161 {
162 let regions = crate::region_file::read_regions(regions.as_ref())?;
163 let regions = reader.normalize_region_file(regions)?;
164 let mut run = self.start(reader.schema(), output, format)?;
165 reader.visit_normalized_regions(regions, |record, site| run.push(record, &site))?;
166 run.finish()
167 }
168
169 pub(crate) fn run_generated<W>(
170 self,
171 input_schema: &LikelihoodVcfSchema,
172 output: W,
173 format: VariantOutputFormat,
174 generate: impl FnOnce(&mut dyn FnMut(&LikelihoodSite) -> Result<()>) -> Result<()>,
175 ) -> Result<W>
176 where
177 W: Write,
178 {
179 let mut run = self.start(input_schema, output, format)?;
180 let mut record = 0;
181 generate(&mut |site| {
182 record += 1;
183 run.push(record, site)
184 })?;
185 run.finish()
186 }
187
188 fn start<W>(
189 self,
190 input_schema: &LikelihoodVcfSchema,
191 output: W,
192 format: VariantOutputFormat,
193 ) -> Result<ActiveCallRun<W>>
194 where
195 W: Write,
196 {
197 let sample_count = self.ploidy.sample_count();
198 if sample_count != input_schema.header().sample_names().len() {
199 return Err(CallError::PloidySampleCountMismatch);
200 }
201 if self.gvcf.is_some() && !input_schema.header().formats().contains_key("DP") {
202 return Err(CallError::MissingGvcfDepth);
203 }
204 let schema = match &self.caller {
205 SiteCaller::Multiallelic(_) => CalledVcfSchema::from_likelihood(input_schema),
206 SiteCaller::Consensus(_) => CalledVcfSchema::from_consensus_likelihood(input_schema),
207 };
208 let schema = if self.gvcf.is_some() {
209 schema.with_gvcf()
210 } else {
211 schema
212 };
213 Ok(ActiveCallRun {
214 caller: self.caller,
215 ploidy: self.ploidy,
216 gvcf: self.gvcf,
217 output: self.output,
218 sample_groups: self.sample_groups,
219 writer: CalledVariantWriter::new(output, schema, format)?,
220 reference_names: input_schema
221 .header()
222 .contigs()
223 .keys()
224 .map(|name| Box::<str>::from(name.as_str()))
225 .collect(),
226 ploidies: Vec::with_capacity(sample_count),
227 })
228 }
229}
230
231struct ActiveCallRun<W>
232where
233 W: Write,
234{
235 caller: SiteCaller,
236 ploidy: PloidyResolver,
237 gvcf: Option<GvcfBlocker>,
238 output: CallOutputOptions,
239 sample_groups: Option<Box<[usize]>>,
240 writer: CalledVariantWriter<W>,
241 reference_names: Box<[Box<str>]>,
242 ploidies: Vec<CallPloidy>,
243}
244
245impl<W> ActiveCallRun<W>
246where
247 W: Write,
248{
249 fn push(&mut self, record: u64, site: &LikelihoodSite) -> Result<()> {
250 let reference = self
251 .reference_names
252 .get(site.reference_sequence_id())
253 .expect("decoded contig ID belongs to the reader schema");
254 self.ploidy
255 .resolve_site_into(reference, site, &mut self.ploidies)
256 .map_err(|error| call_record_error(record, error))?;
257 let called = self
258 .caller
259 .call(
260 site,
261 &self.ploidies,
262 self.ploidy.prior_chromosome_count(),
263 self.sample_groups.as_deref(),
264 )
265 .map_err(|error| call_record_error(record, error))?;
266 if !self.output.accepts(site, &called) {
267 return Ok(());
268 }
269 if let Some(blocker) = &mut self.gvcf {
270 blocker.push(called, |called| self.writer.write_site(&called))
271 } else {
272 self.writer.write_site(&called)
273 }
274 }
275
276 fn finish(mut self) -> Result<W> {
277 if let Some(blocker) = self.gvcf {
278 blocker.finish(|called| self.writer.write_site(&called))?;
279 }
280 self.writer.finish()
281 }
282}
283
284impl SiteCaller {
285 fn call(
286 &self,
287 site: &LikelihoodSite,
288 ploidies: &[CallPloidy],
289 prior_chromosome_count: usize,
290 sample_groups: Option<&[usize]>,
291 ) -> Result<CalledSite> {
292 match self {
293 Self::Multiallelic(caller) => match sample_groups {
294 Some(groups) => {
295 caller.call_with_groups(site, ploidies, prior_chromosome_count, groups)
296 }
297 None => caller.call_with_ploidies(site, ploidies, prior_chromosome_count),
298 },
299 Self::Consensus(caller) => caller.call_with_ploidies(site, ploidies),
300 }
301 }
302}
303
304pub fn run_likelihood_calls<R, W>(
305 mut reader: LikelihoodVariantReader<R>,
306 writer: W,
307 output_schema: CalledVcfSchema,
308 output_format: VariantOutputFormat,
309 mut call: impl FnMut(&LikelihoodSite) -> Result<CalledSite>,
310) -> Result<W>
311where
312 R: Read,
313 W: Write,
314{
315 let mut writer = CalledVariantWriter::new(writer, output_schema, output_format)?;
316 while let Some(site) = reader.read_site()? {
317 let record = reader.record_number();
318 let called = call(&site).map_err(|error| call_record_error(record, error))?;
319 writer.write_site(&called)?;
320 }
321 writer.finish()
322}
323
324fn call_record_error(record: u64, error: CallError) -> CallError {
325 CallError::LikelihoodCallRecord {
326 record,
327 source: Box::new(error),
328 }
329}
330
331#[cfg(test)]
332mod tests;