Skip to main content

rsomics_call/
call_samples.rs

1use std::collections::HashSet;
2use std::fs::File;
3use std::io::{BufRead, BufReader, Read};
4use std::path::Path;
5
6use crate::{
7    CallError, CallPloidy, IndexedLikelihoodVariantReader, LikelihoodVariantReader,
8    LikelihoodVcfSchema, PloidyDefinition, PloidyResolver, Result, SamplePloidy,
9    samples::validate_sample_name,
10};
11
12#[derive(Clone, Debug, Default)]
13pub struct CallSampleSelection {
14    mode: SelectionMode,
15}
16
17#[derive(Clone, Debug, Default)]
18enum SelectionMode {
19    #[default]
20    All,
21    Include(Box<[SampleAssignment]>),
22    Exclude(Box<[Box<str>]>),
23}
24
25#[derive(Clone, Debug)]
26struct SampleAssignment {
27    name: Box<str>,
28    ploidy: Option<SamplePloidy>,
29}
30
31impl CallSampleSelection {
32    pub fn include(samples: impl IntoIterator<Item = impl Into<Box<str>>>) -> Result<Self> {
33        Self::include_with_ploidy(samples.into_iter().map(|name| (name, None)))
34    }
35
36    pub fn include_with_ploidy<N>(
37        samples: impl IntoIterator<Item = (N, Option<SamplePloidy>)>,
38    ) -> Result<Self>
39    where
40        N: Into<Box<str>>,
41    {
42        let mut seen = HashSet::new();
43        let mut assignments = Vec::new();
44        for (name, ploidy) in samples {
45            let name = name.into();
46            validate_sample_name(&name)?;
47            if !seen.insert(name.clone()) {
48                return Err(CallError::DuplicateSampleSelection(name.into()));
49            }
50            assignments.push(SampleAssignment { name, ploidy });
51        }
52        if assignments.is_empty() {
53            return Err(CallError::InvalidSampleCount);
54        }
55        Ok(Self {
56            mode: SelectionMode::Include(assignments.into_boxed_slice()),
57        })
58    }
59
60    pub fn exclude(samples: impl IntoIterator<Item = impl Into<Box<str>>>) -> Result<Self> {
61        let mut seen = HashSet::new();
62        let mut names = Vec::new();
63        for name in samples {
64            let name = name.into();
65            validate_sample_name(&name)?;
66            if !seen.insert(name.clone()) {
67                return Err(CallError::DuplicateSampleSelection(name.into()));
68            }
69            names.push(name);
70        }
71        if names.is_empty() {
72            return Err(CallError::InvalidSampleCount);
73        }
74        Ok(Self {
75            mode: SelectionMode::Exclude(names.into_boxed_slice()),
76        })
77    }
78
79    pub fn read(path: impl AsRef<Path>) -> Result<Self> {
80        Self::read_mode(path.as_ref(), false)
81    }
82
83    pub fn read_excluding(path: impl AsRef<Path>) -> Result<Self> {
84        Self::read_mode(path.as_ref(), true)
85    }
86
87    pub fn parse(data: &str) -> Result<Self> {
88        Self::from_reader(data.as_bytes(), "<samples>".to_owned(), false)
89    }
90
91    pub fn parse_excluding(data: &str) -> Result<Self> {
92        Self::from_reader(data.as_bytes(), "<samples>".to_owned(), true)
93    }
94
95    fn read_mode(path: &Path, exclude: bool) -> Result<Self> {
96        let display = path.display().to_string();
97        let file = File::open(path).map_err(|error| CallError::CallSampleInput {
98            path: display.clone(),
99            message: error.to_string(),
100        })?;
101        Self::from_reader(BufReader::new(file), display, exclude)
102    }
103
104    pub fn bind<R>(
105        self,
106        reader: LikelihoodVariantReader<R>,
107        definition: &PloidyDefinition,
108    ) -> Result<(LikelihoodVariantReader<R>, PloidyResolver)>
109    where
110        R: Read,
111    {
112        self.bind_reader(reader, definition)
113    }
114
115    pub fn bind_indexed(
116        self,
117        reader: IndexedLikelihoodVariantReader,
118        definition: &PloidyDefinition,
119    ) -> Result<(IndexedLikelihoodVariantReader, PloidyResolver)> {
120        self.bind_reader(reader, definition)
121    }
122
123    fn bind_reader<R>(self, reader: R, definition: &PloidyDefinition) -> Result<(R, PloidyResolver)>
124    where
125        R: ProjectLikelihoodSamples,
126    {
127        match self.mode {
128            SelectionMode::All => {
129                let resolver =
130                    definition.default_resolver(reader.schema().header().sample_names().len())?;
131                Ok((reader, resolver))
132            }
133            SelectionMode::Include(assignments) => {
134                let reader = reader.include(&assignments)?;
135                let mut default: Option<SamplePloidy> = None;
136                let mut ploidies = Vec::with_capacity(assignments.len());
137                for assignment in assignments {
138                    let ploidy = match assignment.ploidy {
139                        Some(ploidy) => ploidy,
140                        None => match &default {
141                            Some(ploidy) => ploidy.clone(),
142                            None => {
143                                let ploidy = definition.default_assignment()?;
144                                default = Some(ploidy.clone());
145                                ploidy
146                            }
147                        },
148                    };
149                    ploidies.push(ploidy);
150                }
151                let resolver = definition.resolver(ploidies)?;
152                Ok((reader, resolver))
153            }
154            SelectionMode::Exclude(names) => {
155                let reader = reader.exclude(&names)?;
156                let resolver =
157                    definition.default_resolver(reader.schema().header().sample_names().len())?;
158                Ok((reader, resolver))
159            }
160        }
161    }
162
163    fn from_reader(reader: impl BufRead, path: String, exclude: bool) -> Result<Self> {
164        let mut records = Vec::new();
165        for (index, line) in reader.lines().enumerate() {
166            let line_number = index as u64 + 1;
167            let line = line.map_err(|error| CallError::CallSampleRecord {
168                path: path.clone(),
169                line: line_number,
170                message: error.to_string(),
171            })?;
172            let line = line.trim();
173            if line.is_empty() || line.starts_with('#') {
174                continue;
175            }
176            let fields = line.split_whitespace().collect::<Vec<_>>();
177            if fields.len() > 2 {
178                return Err(CallError::CallSampleRecord {
179                    path,
180                    line: line_number,
181                    message: "expected SAMPLE and optional PLOIDY_OR_SEX".to_owned(),
182                });
183            }
184            records.push((
185                Box::<str>::from(fields[0]),
186                fields.get(1).map(|value| parse_assignment(value)),
187            ));
188        }
189        if exclude {
190            Self::exclude(records.into_iter().map(|(name, _)| name))
191        } else {
192            Self::include_with_ploidy(records)
193        }
194    }
195}
196
197trait ProjectLikelihoodSamples: Sized {
198    fn schema(&self) -> &LikelihoodVcfSchema;
199    fn include(self, assignments: &[SampleAssignment]) -> Result<Self>;
200    fn exclude(self, names: &[Box<str>]) -> Result<Self>;
201}
202
203impl<R> ProjectLikelihoodSamples for LikelihoodVariantReader<R>
204where
205    R: Read,
206{
207    fn schema(&self) -> &LikelihoodVcfSchema {
208        self.schema()
209    }
210
211    fn include(self, assignments: &[SampleAssignment]) -> Result<Self> {
212        self.select_samples(assignments.iter().map(|item| &item.name))
213    }
214
215    fn exclude(self, names: &[Box<str>]) -> Result<Self> {
216        self.exclude_samples(names)
217    }
218}
219
220impl ProjectLikelihoodSamples for IndexedLikelihoodVariantReader {
221    fn schema(&self) -> &LikelihoodVcfSchema {
222        self.schema()
223    }
224
225    fn include(self, assignments: &[SampleAssignment]) -> Result<Self> {
226        self.select_samples(assignments.iter().map(|item| &item.name))
227    }
228
229    fn exclude(self, names: &[Box<str>]) -> Result<Self> {
230        self.exclude_samples(names)
231    }
232}
233
234fn parse_assignment(value: &str) -> SamplePloidy {
235    match value {
236        "0" => SamplePloidy::Fixed(CallPloidy::Absent),
237        "1" => SamplePloidy::Fixed(CallPloidy::Haploid),
238        "2" => SamplePloidy::Fixed(CallPloidy::Diploid),
239        _ => SamplePloidy::sex(value),
240    }
241}
242
243#[cfg(test)]
244mod tests;