pub struct CSVBinaryMatrix { /* private fields */ }
Expand description
Binary matrix Compressed Sparse Vector.
For all the example sections, we use matrix
is the following matrix:
0 0 0
0 0 1
0 1 1
1 1 1
You can obtain this matrix with the following code:
use csvbinmatrix::prelude::CSVBinaryMatrix;
let matrix = CSVBinaryMatrix::try_from(&[
[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
]).unwrap();
See csvbinmatrix::matrix::create
module for more details.
Implementations§
Source§impl CSVBinaryMatrix
impl CSVBinaryMatrix
Sourcepub fn new<I: IntoIterator<Item = usize>>(
number_of_rows: usize,
number_of_columns: usize,
distances: I,
) -> Result<Self, DistancesExceedRowsError>
pub fn new<I: IntoIterator<Item = usize>>( number_of_rows: usize, number_of_columns: usize, distances: I, ) -> Result<Self, DistancesExceedRowsError>
Create a CSVBinaryMatrix
from distances.
The first distance is the one that separates the first cell from the first one. The last distance is the one that separates the penulti-last one from the last one.
§Example
match CSVBinaryMatrix::new(4, 3, vec![5, 2, 1, 1, 1, 1]) {
Ok(m) => assert_eq!(m, matrix),
Err(e) => panic!("[ERROR] {e}"),
}
§Errors
Raises DistancesExceedRowsError
.
Sourcepub fn try_from_coordinates<T: IntoIterator<Item = C>, C: Into<Coordinates>>(
number_of_rows: usize,
number_of_columns: usize,
coordinates: T,
) -> Result<Self, TryFromCoordinatesError>
pub fn try_from_coordinates<T: IntoIterator<Item = C>, C: Into<Coordinates>>( number_of_rows: usize, number_of_columns: usize, coordinates: T, ) -> Result<Self, TryFromCoordinatesError>
Create a CSVBinaryMatrix
from the row-column coordinates.
The coordinates must be sorted according to the row and then to the column.
§Examples
match CSVBinaryMatrix::try_from_coordinates(
4,
3,
vec![(1, 2), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2)]
) {
Ok(matrix_from_coo) => assert_eq!(matrix, matrix_from_coo),
Err(e) => panic!("[ERROR] {e}"),
}
§Errors
Raise a TryFromCoordinatesError
.
Source§impl CSVBinaryMatrix
impl CSVBinaryMatrix
Sourcepub fn to_file<P: AsRef<Path>>(&self, filepath: P) -> Result<(), Error>
pub fn to_file<P: AsRef<Path>>(&self, filepath: P) -> Result<(), Error>
Write a binary matrix with the CSVBM format to disk.
§Example
use csvbinmatrix::prelude::CSVBinaryMatrix;
let matrix = CSVBinaryMatrix::try_from(&[
[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
]).unwrap();
match matrix.to_file("mymatrix.csvbm") {
Ok(_) => println!("[INFO] File created"),
Err(e) => println!("[ERROR] creating file fails: {e}"),
}
// You can still use `matrix`
assert_eq!(matrix.number_of_ones(), 6);
In our example matrix, the file is:
4 3 6 0
5
2
1
1
1
1
For more details about the CSVBM file format, please refer to the csvbinmatrix::matrix::io
module documentation.
§Errors
Returns an error if the file cannot be created.
Sourcepub fn into_file<P: AsRef<Path>>(self, filepath: P) -> Result<(), Error>
pub fn into_file<P: AsRef<Path>>(self, filepath: P) -> Result<(), Error>
Write a binary matrix with the CSVBM format to disk.
The matrix is consumed while its components are written on disk.
§Example
use csvbinmatrix::prelude::CSVBinaryMatrix;
let matrix = CSVBinaryMatrix::try_from(&[
[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
]).unwrap();
match matrix.into_file("mymatrix.csvbm") {
Ok(_) => println!("[INFO] File created"),
Err(e) => println!("[ERROR] creating file fails: {e}"),
}
// `matrix` is consumed so you cannot use it anymore.
// This will fail at compilation time:
// assert_eq!(matrix.number_of_ones(), 6);
In our example matrix, the file is:
4 3 6 1
0
1
1
1
1
2
Note:
The file contains the list of distances from the end of the matrix (see CSVBinaryMatrix::reverse
and CSVBinaryMatrix::into_reversed
).
For more details about the CSVBM file format, please refer to the csvbinmatrix::matrix::io
module documentation.
§Errors
Returns an error if the file cannot be created.
§Panics
Unreachable: the matrix has not been correctly built.
Sourcepub fn try_from_file<P: AsRef<Path>>(
filename: P,
) -> Result<Self, ParseCSVBMFileError>
pub fn try_from_file<P: AsRef<Path>>( filename: P, ) -> Result<Self, ParseCSVBMFileError>
Read a binary matrix from a CSVBM file.
For more details about the CSVBM file format, please refer to the csvbinmatrix::matrix::io
module documentation.
§Example
use csvbinmatrix::prelude::CSVBinaryMatrix;
let matrix = CSVBinaryMatrix::try_from(&[
[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
]).unwrap();
let matrix_from_file = match CSVBinaryMatrix::try_from_file("mymatrix.csvbm") {
Ok(m) => m,
Err(e) => panic!("[ERROR] reading file fails: {e}"),
};
assert_eq!(matrix_from_file, matrix);
§Errors
Returns a ParseCSVBMFileError
error if the file cannot be read or if the format is invalid.
Source§impl<'distvec> CSVBinaryMatrix
impl<'distvec> CSVBinaryMatrix
Sourcepub fn iter_ones_coordinates(&self) -> IterOnesCoordinates<'_> ⓘ
pub fn iter_ones_coordinates(&self) -> IterOnesCoordinates<'_> ⓘ
Returns an iterator over the ones coordinates in the matrix.
§Example
use csvbinmatrix::prelude::Coordinates;
let mut ones_coordinates = matrix.iter_ones_coordinates();
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(1, 2)));
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(2, 1)));
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(2, 2)));
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(3, 0)));
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(3, 1)));
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(3, 2)));
assert_eq!(ones_coordinates.next(), None);
Sourcepub fn iter_ones_coordinates_from_end(
&'distvec self,
) -> IterOnesCoordinatesFromEnd<'_> ⓘ
pub fn iter_ones_coordinates_from_end( &'distvec self, ) -> IterOnesCoordinatesFromEnd<'_> ⓘ
Returns an iterator over the ones coordinates in the matrix by going from the end.
§Example
use csvbinmatrix::prelude::Coordinates;
let mut ones_coordinates = matrix.iter_ones_coordinates_from_end();
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(3, 2)));
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(3, 1)));
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(3, 0)));
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(2, 2)));
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(2, 1)));
assert_eq!(ones_coordinates.next(), Some(Coordinates::new(1, 2)));
assert_eq!(ones_coordinates.next(), None);
Source§impl CSVBinaryMatrix
impl CSVBinaryMatrix
Sourcepub fn reverse(&mut self)
pub fn reverse(&mut self)
Reverse the rows and the columns of the CSVBinaryMatrix
in place.
Memory and time complexities is O(1).
Do not confuse reversing the matrix with reading the ones coordinates from the end of the matrix.
For this purpose, use CSVBinaryMatrix::iter_ones_coordinates_from_end
.
§Example
matrix.reverse();
assert_eq!(matrix, CSVBinaryMatrix::try_from(&[
[1, 1, 1],
[1, 1, 0],
[1, 0, 0],
[0, 0, 0],
]).unwrap());
Sourcepub fn into_reversed(self) -> Self
pub fn into_reversed(self) -> Self
Returns the matrix where the rows and the columns of self are reversed.
Memory and time complexities is O(1).
Do not confuse reversing the matrix with reading the ones coordinates from the end of the matrix.
For this purpose, use CSVBinaryMatrix::iter_ones_coordinates_from_end
.
§Example
assert_eq!(
CSVBinaryMatrix::try_from(&[
[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
]).unwrap().into_reversed(),
CSVBinaryMatrix::try_from(&[
[1, 1, 1],
[1, 1, 0],
[1, 0, 0],
[0, 0, 0],
]).unwrap()
);
Sourcepub fn to_submatrix<R, C>(
&self,
row_filter: &R,
column_filter: &C,
) -> Result<CSVBinaryMatrix, DegeneratedMatrixError>where
R: DimensionFilter,
C: DimensionFilter,
pub fn to_submatrix<R, C>(
&self,
row_filter: &R,
column_filter: &C,
) -> Result<CSVBinaryMatrix, DegeneratedMatrixError>where
R: DimensionFilter,
C: DimensionFilter,
Return a submatrix from the given matrix.
§Example
use csvbinmatrix::prelude::{CSVBinaryMatrix, ClosureDimensionFilter};
let matrix = CSVBinaryMatrix::try_from(&[
[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
]).unwrap();
let expected_sub_matrix = CSVBinaryMatrix::try_from(&[[0, 0], [1, 1], [1, 1]]).unwrap();
let row_filter = ClosureDimensionFilter::new(|i| i != 1);
let column_filter = ClosureDimensionFilter::new(|j| j != 0);
// Generate submatrices according to the couples of row and column filters.
// `matrix` is not consumed.
match matrix.to_submatrix(&row_filter, &column_filter) {
Ok(sub_matrix) => assert_eq!(sub_matrix, expected_sub_matrix),
Err(err) => panic!("[ERROR] {err}"),
}
§Errors
DegeneratedMatrixError
if the submatrix is degenerated.
§Panics
Unreachable: if there are no distances in the distance list.
Sourcepub fn into_submatrices<R, C>(
self,
row_col_filters: Vec<(&R, &C)>,
) -> Vec<Result<CSVBinaryMatrix, DegeneratedMatrixError>>where
R: DimensionFilter,
C: DimensionFilter,
pub fn into_submatrices<R, C>(
self,
row_col_filters: Vec<(&R, &C)>,
) -> Vec<Result<CSVBinaryMatrix, DegeneratedMatrixError>>where
R: DimensionFilter,
C: DimensionFilter,
Return several submatrices from the given binary matrix.
This function is efficient as it creates new submatrices while consuming the given super matrix. The memory and the time complexities are linear according to the number ones of the super binary matrix.
For example, let the initial matrix to be
0 0 0
0 0 1
0 1 1
1 1 1
Then the submatrix (with row/column filters set to true for all the elements) will be
1 1 1
1 1 0
1 0 0
0 0 0
§Example
use csvbinmatrix::prelude::{CSVBinaryMatrix, BoolVecDimensionFilter, ClosureDimensionFilter};
let matrix = CSVBinaryMatrix::try_from(&[
[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
]).unwrap();
let expected_sub_matrix = CSVBinaryMatrix::try_from(&[[0, 0], [1, 1], [1, 1]]).unwrap();
// Filter with a boolean vector:
// * to represent complex truth states
// * costly
let row_filter =
match BoolVecDimensionFilter::new(vec![true, false, true, true], matrix.number_of_rows()) {
Ok(filter) => filter,
Err(err) => panic!("[ERROR] {err}"),
};
// Filter with a closure
// * to represent simple truth states
// * efficient
let column_filter = ClosureDimensionFilter::new(|j| j != 0);
// Generate submatrices according to the couples of row and column filters.
// `matrix` is consumed.
let mut sub_matrices = matrix.into_submatrices(vec![(&row_filter, &column_filter)]);
// Iterate over the submatrices and check them
match sub_matrices.pop() {
Some(Ok(reversed_sub_matrix)) => {
assert_eq!(reversed_sub_matrix, expected_sub_matrix)
}
Some(Err(err)) => panic!("[ERROR] {err}"),
_ => unreachable!("There must be one resulting sub matrix."),
}
// We give only one filter couple, so there is only one resulting submatrix.
assert!(sub_matrices.pop().is_none());
§Errors
DegeneratedMatrixError
if the submatrix is degenerated.
§Panics
Unreachable: if there are no distances in the distance list.
Source§impl CSVBinaryMatrix
impl CSVBinaryMatrix
Sourcepub fn extend_with_rows(
&mut self,
extension: Self,
) -> Result<(), UpdateMatrixError>
pub fn extend_with_rows( &mut self, extension: Self, ) -> Result<(), UpdateMatrixError>
Extends the rows of the current matrix with the given matrix.
Move the values of extension into self.
Time complexity is O(1).
§Example
let extension = CSVBinaryMatrix::try_from(&[[0, 1, 0]]).unwrap();
match matrix.extend_with_rows(extension) {
Ok(()) => (),
Err(err) => panic!("[ERROR] {err}"),
}
assert_eq!(
matrix,
CSVBinaryMatrix::try_from(&[
[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[0, 1, 0]
]).unwrap()
);
§Errors
UpdateMatrixError
- The extension’s number of columns must match the self’s number of columns.
§Panics
Panics if the extension has not been built correctly
Sourcepub fn extend_with_columns(
&mut self,
extension: Self,
) -> Result<(), UpdateMatrixError>
pub fn extend_with_columns( &mut self, extension: Self, ) -> Result<(), UpdateMatrixError>
Extends the columns of the current matrix with the given matrix.
The memory and the time complexities are linear according to the number ones of the two matrices.
§Example
Let A be the following matrix:
0 0 0
0 0 1
0 1 1
1 1 1
Let B be the extension matrix:
1
1
1
1
The resulting extended matrix will be
0 0 0 1
0 0 1 1
0 1 1 1
1 1 1 1
let extension = CSVBinaryMatrix::try_from(&[[1], [1], [1], [1]]).unwrap();
match matrix.extend_with_columns(extension) {
Ok(()) => { },
Err(err) => panic!("[ERROR] {err}"),
}
assert_eq!(matrix, CSVBinaryMatrix::try_from(&[
[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
]).unwrap());
§Errors
UpdateMatrixError
- The extension’s number of rows must match the self’s number of rows.
§Panics
Unreachable: if self or the extension have not been built correctly
Source§impl CSVBinaryMatrix
impl CSVBinaryMatrix
Sourcepub fn number_of_cells(&self) -> usize
pub fn number_of_cells(&self) -> usize
Returns the number of cells.
Sourcepub fn number_of_ones(&self) -> usize
pub fn number_of_ones(&self) -> usize
Returns the number of ones.
Sourcepub fn number_of_zeros(&self) -> usize
pub fn number_of_zeros(&self) -> usize
Returns the number of zeros.
Sourcepub fn sparsity(&self) -> f64
pub fn sparsity(&self) -> f64
Returns the sparsity of the matrix.
The sparsity is the ratio of the number of zeros to the number of cells.
Sourcepub fn density(&self) -> f64
pub fn density(&self) -> f64
Returns the density of the matrix.
The density is the ratio of the number of ones to the number of cells.
Sourcepub fn is_complete(&self) -> bool
pub fn is_complete(&self) -> bool
Returns true
if the matrix is complete or all-ones.
Source§impl CSVBinaryMatrix
impl CSVBinaryMatrix
Sourcepub fn number_of_rows(&self) -> usize
pub fn number_of_rows(&self) -> usize
Returns the number of rows.
Sourcepub fn number_of_columns(&self) -> usize
pub fn number_of_columns(&self) -> usize
Returns the number of columns.
Trait Implementations§
Source§impl Clone for CSVBinaryMatrix
impl Clone for CSVBinaryMatrix
Source§fn clone(&self) -> CSVBinaryMatrix
fn clone(&self) -> CSVBinaryMatrix
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moreSource§impl Debug for CSVBinaryMatrix
impl Debug for CSVBinaryMatrix
Source§impl Default for CSVBinaryMatrix
impl Default for CSVBinaryMatrix
Source§fn default() -> Self
fn default() -> Self
Creates a new empty or all-zeros CSVBinaryMatrix
.
§Example
use csvbinmatrix::prelude::CSVBinaryMatrix;
assert_eq!(
CSVBinaryMatrix::default(),
CSVBinaryMatrix::try_from(&[[0]]).unwrap()
);
Source§impl PartialEq for CSVBinaryMatrix
impl PartialEq for CSVBinaryMatrix
Source§fn eq(self: &CSVBinaryMatrix, other: &CSVBinaryMatrix) -> bool
fn eq(self: &CSVBinaryMatrix, other: &CSVBinaryMatrix) -> bool
self
and other
values to be equal, and is used by ==
.Source§impl<const N: usize, const M: usize> TryFrom<&[[u8; M]; N]> for CSVBinaryMatrix
impl<const N: usize, const M: usize> TryFrom<&[[u8; M]; N]> for CSVBinaryMatrix
Source§fn try_from(rows: &[[u8; M]; N]) -> Result<Self, Self::Error>
fn try_from(rows: &[[u8; M]; N]) -> Result<Self, Self::Error>
Create a CSVBinaryMatrix
from 0-1 rows.
§Example
let matrix = match CSVBinaryMatrix::try_from(&[
[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
]) {
Ok(matrix) => matrix,
Err(e) => panic!("[ERROR] {e}"),
};
§Errors
Raise a TryFromIntRowsError
.
Source§type Error = TryFromIntRowsError
type Error = TryFromIntRowsError
Source§impl TryFrom<&Vec<Vec<bool>>> for CSVBinaryMatrix
impl TryFrom<&Vec<Vec<bool>>> for CSVBinaryMatrix
Source§fn try_from(rows: &Vec<Vec<bool>>) -> Result<Self, Self::Error>
fn try_from(rows: &Vec<Vec<bool>>) -> Result<Self, Self::Error>
Create a CSVBinaryMatrix
from boolean rows.
§Example
let matrix = match CSVBinaryMatrix::try_from(&vec![
vec![false, false, false],
vec![false, false, true],
vec![false, true, true],
vec![true, true, true],
]) {
Ok(matrix) => matrix,
Err(e) => panic!("[ERROR] {e}"),
};
§Errors
Raise a TryFromBoolRowsError
.
Source§type Error = TryFromBoolRowsError
type Error = TryFromBoolRowsError
Source§impl TryFrom<&Vec<Vec<u8>>> for CSVBinaryMatrix
impl TryFrom<&Vec<Vec<u8>>> for CSVBinaryMatrix
Source§fn try_from(rows: &Vec<Vec<u8>>) -> Result<Self, Self::Error>
fn try_from(rows: &Vec<Vec<u8>>) -> Result<Self, Self::Error>
Create a CSVBinaryMatrix
from 0-1 rows.
§Example
let matrix = match CSVBinaryMatrix::try_from(&vec![
vec![0, 0, 0],
vec![0, 0, 1],
vec![0, 1, 1],
vec![1, 1, 1],
]) {
Ok(matrix) => matrix,
Err(e) => panic!("[ERROR] {e}"),
};
§Errors
Raise a TryFromIntRowsError
.