Add documentation and fix logic for counting nth bases
//! GC counter over an `IntoTextIterator` object.
-//! Complexity: o(n)
+//! Complexity: O(n), where n is the length of the sequence.
use std::borrow::Borrow;
/// Base gc content counter
fn gcn_content<C: Borrow<u8>, T: IntoIterator<Item = C>>(sequence: T, step: usize) -> f32 {
- let mut l = 0f32;
- let mut count = 0.0;
- for (i, n) in sequence.into_iter().enumerate() {
- if i % step == 0 {
- count += match *n.borrow() {
- b'c' | b'g' | b'G' | b'C' => 1f32, // G or C
- _ => 0f32,
- };
- }
- l = i as f32;
- }
- count / (l + 1f32)
+ let (l, count) = sequence
+ .into_iter()
+ .step_by(step)
+ .fold((0.0, 0.0), |(l, count), n| match *n.borrow() {
+ b'c' | b'g' | b'G' | b'C' => (l + 1.0, count + 1.0),
+ _ => (l + 1.0, count),
+ });
+ count / l
}
-/// gc content counter for every nucleotide
+/// Returns the ratio of bases which are guanine or cytososine
+///
+/// # Arguments
+///
+/// * `sequence` - A sequence of bases
+///
+/// # Example
+///
+/// ```
+/// use bio::seq_analysis::gc::gc_content;
+///
+/// const seq: &'static [u8] = b"GATATACA";
+/// assert_eq!(gc_content(seq), 2. / 8.);
+/// ```
pub fn gc_content<C: Borrow<u8>, T: IntoIterator<Item = C>>(sequence: T) -> f32 {
gcn_content(sequence, 1usize)
}
-/// gc content counter for the nucleotide in 3rd position
+/// Returns the ratio of bases in the 3rd position which are guanine
+/// or cytososine.
+///
+/// # Arguments
+///
+/// * `sequence` - A sequence of bases
+///
+/// # Example
+///
+/// ```
+/// use bio::seq_analysis::gc::gc3_content;
+/// const seq: &'static [u8] = b"GATATACA";
+/// // ^ ^ ^
+/// assert_eq!(gc3_content(seq), 2. / 3.);
+/// ```
pub fn gc3_content<C: Borrow<u8>, T: IntoIterator<Item = C>>(sequence: T) -> f32 {
gcn_content(sequence, 3usize)
}
