Skip to content

Commit

Permalink
Add symmetric -> square conversion for non-Copy+Default
Browse files Browse the repository at this point in the history
  • Loading branch information
arcresu committed Jan 11, 2023
1 parent 48598bc commit e0b26bd
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/symmetric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::formats::{
parse_phylip_lt, parse_tabular_lt, PhylipDialect, PhylipError, Separator, TabularError,
};
pub use crate::square::Labels;
use crate::{open_file, AbsDiff};
use crate::{open_file, AbsDiff, SquareMatrix};

/// Stores the lower triangle of a matrix.
///
Expand Down Expand Up @@ -417,6 +417,17 @@ impl<D> DistMatrix<D> {
pub fn size(&self) -> usize {
self.size
}

/// Convert into a square matrix by mirroring the lower triangle and filling the diagonal.
///
/// Note that if `D: Copy + Default` then you can instead use
/// `let square: SquareMatrix<D> = dist_matrix.into()`.
pub fn as_square<'a>(&'a self, diagonal: &'a D) -> SquareMatrix<&'a D> {
self.iter_rows()
.flatten()
.map(|entry| entry.unwrap_or(diagonal))
.collect()
}
}

impl DistMatrix<f32> {
Expand Down Expand Up @@ -902,6 +913,17 @@ mod tests {
assert_eq!(m.size(), 4);
}

#[test]
fn as_square() {
let sym = DistMatrix::<i32>::from_pw_distances(&[1, 6, 8, 9, 3]);
let m1: SquareMatrix<i32> = sym.as_square(&0).copied();
let m2 = SquareMatrix::<i32>::from_pw_distances(&[1, 6, 8, 9, 3]);
assert_eq!(m1, m2);

let m1: SquareMatrix<i32> = sym.into();
assert_eq!(m1, m2);
}

#[test]
fn readme() {
// A symmetric matrix stored as the lower triangle:
Expand Down

0 comments on commit e0b26bd

Please sign in to comment.