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
#![crate_name = "genomics"]
use ndarray;
use ndarray::ShapeBuilder;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::error::Error;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};

pub mod prelude;

//mod fileio;
mod observable;

pub type Groups = HashMap<String, Arc<Group>>;
pub type Meta = HashMap<String, String>;
pub type AlleleCount = u32;
pub type Variations = Arc<Mutex<BTreeMap<String, Arc<Variation>>>>;
pub type Loci = BTreeMap<String, Arc<Locus>>;
pub type Allele = (Arc<Locus>, Arc<Variation>);
pub type Individuals = BTreeMap<String, Individual>;
pub type Genome = HashMap<Allele, AlleleCount>;

pub trait LociExt {
    fn n_alleles(&self) -> usize;
}

impl LociExt for Loci {
    fn n_alleles(&self) -> usize {
        self.iter().fold(0, |count, (_, locus)| {
            count + locus.variations.lock().unwrap().len()
        })
    }
}

#[derive(Hash, Eq, PartialEq)]
pub struct Variation {
    name: String,
}

impl Variation {
    pub fn new(name: &str) -> Self {
        Self { name: name.into() }
    }
}

pub enum LocusHint {
    Classical,
    Microsatellite,
}

pub struct Locus {
    name: String,
    variations: Variations,
    hint: LocusHint,
}

impl Hash for Locus {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
    }
}

impl PartialEq for Locus {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}

impl Eq for Locus {}

impl Locus {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.into(),
            variations: Variations::new(Mutex::new(BTreeMap::new())),
            hint: LocusHint::Microsatellite,
        }
    }
}

#[derive(Hash, PartialEq, Eq)]
pub struct Group {
    name: String,
}

impl Group {
    pub fn new(name: &str) -> Self {
        Self { name: name.into() }
    }
}

pub struct Individual {
    name: String,
    genome: Genome,
    groups: HashSet<Arc<Group>>,
    meta: Meta,
}

impl Individual {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.into(),
            genome: Genome::new(),
            groups: HashSet::new(),
            meta: Meta::new(),
        }
    }
}

pub struct AlleleMatrix {
    data: ndarray::Array2<AlleleCount>,
    dirty: bool,
}

impl AlleleMatrix {
    pub fn new() -> Self {
        Self {
            data: ndarray::Array2::<AlleleCount>::zeros((0, 0)),
            dirty: false,
        }
    }
}

/// An observation of an Individual
pub enum Observation {
    /// An Observation that an individual has an Allele
    /// Individual's name, Locus's name, Variation's name
    Allele(String, String, String),

    /// An Observation that an Individual belongs to a Group
    /// Individual's name, Group's name
    Group(String, String),

    /// An `Observation` that an `Individual` has associated metadata
    /// Individual's name, Meta data description, Meta data content. 
    Meta(String, String, String),
}

pub struct Sample {
    loci: Loci,
    groups: Groups,
    individuals: Individuals,
    matrix: AlleleMatrix,
}

impl Sample {
    /// Constructs a new empty `Sample`
    ///
    /// The `Sample` can be filled up iteratively by calling
    /// `observation()`.
    pub fn new() -> Self {
        Self {
            loci: Loci::new(),
            groups: Groups::new(),
            individuals: Individuals::new(),
            matrix: AlleleMatrix::new(),
        }
    }

    /// Recreates the `Sample`'s `matrix`.
    ///
    /// This function is called before a matrix calculation
    /// so there is no need to explicitly call it after observing data.
    pub fn flush(&mut self) -> Result<(), Box<dyn Error>> {
        self.matrix = AlleleMatrix {
            dirty: false,
            data: ndarray::Array::from_shape_vec(
                (self.individuals.len(), self.loci.n_alleles()).strides((self.loci.n_alleles(), 1)),
                Vec::<AlleleCount>::from(&*self),
            )?,
        };
        Ok(())
    }

    /// Returns the allele in this locus
    ///
    /// This will create the locus and allele if needed and mark
    /// the Sample as dirty. Dirty samples will updated before
    /// the next call that requires a matrix calculation or when
    /// `flush()` is called.
    pub fn allele(&mut self, locus: &str, variation: &str) -> Allele {
        (
            self.loci
                .entry(locus.into())
                .or_insert({
                    self.matrix.dirty = true;
                    Arc::new(Locus::new(locus))
                })
                .clone(),
            self.loci
                .get(locus)
                .unwrap() // Guaranteed to exist since we just inserted it.
                .variations
                .lock()
                .unwrap()
                .entry(variation.into())
                .or_insert({
                    self.matrix.dirty = true;
                    Arc::new(Variation::new(variation))
                })
                .clone(),
        )
    }

    /// Returns a reference to a `Group`
    ///
    /// This will create the `Group` if needed and mark the `Sample`
    /// as dirty.
    pub fn group(&mut self, group: &str) -> Arc<Group> {
        self.groups
            .entry(group.into())
            .or_insert({
                self.matrix.dirty = true;
                Arc::new(Group::new(group.into()))
            })
            .clone()
    }

    /// Observes a single `Observation`
    ///
    /// This function is normally called by a `Sample`'s observe
    /// function to read in data. To read in data from an arbitrary
    /// data source. Implement an Iterator with type Item = Observation.
    pub fn _observe(&mut self, observation: Observation) {
        match &observation {
            Observation::Allele(individual, locus, variation) => {
                let allele = self.allele(&locus, &variation);
                *self
                    .individuals
                    .entry(individual.into())
                    .or_insert(Individual::new(individual))
                    .genome
                    .entry(allele)
                    .or_insert(0) += 1;
            }
            Observation::Group(individual, group) => {
                let arc_group = self.group(group);
                self.individuals
                    .entry(individual.into())
                    .or_insert(Individual::new(individual))
                    .groups
                    .insert(arc_group);
            },
            Observation::Meta(individual, meta, content) => {
                self.individuals
                    .entry(individual.into())
                    .or_insert(Individual::new(individual))
                    .meta
                    .insert(meta.into(), content.into());
            }
        }
    }

    /// Observe all the data in the argument.
    pub fn observe<I>(&mut self, observable: I) -> Result<(), Box<dyn Error>>
    where 
        I: Iterator<Item = Result<Observation, Box<dyn Error>>> 
    {
        for observation in observable {
            self._observe(observation?);
        }
        Ok(())
    }

    /// A list of the names of all loci in a sample
    pub fn loci_names(&self) -> Vec<&String> {
        self.loci.keys().collect()
    }
}

impl From<&Sample> for Vec<AlleleCount> {
    fn from(sample: &Sample) -> Vec<AlleleCount> {
        let mut v = vec![];
        for (_, individual) in sample.individuals.iter() {
            for (_, locus) in sample.loci.iter() {
                for (_, variation) in locus.variations.lock().unwrap().iter() {
                    v.push(
                        match individual.genome.get(&(locus.clone(), variation.clone())) {
                            None => 0,
                            Some(c) => *c,
                        },
                    )
                }
            }
        }
        v
    }
}