Struct CSVBinaryMatrix

Source
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

Source

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.

Source

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

Source

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.

Source

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.

Source

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

Source

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);
Source

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

Source

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());
Source

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()
);
Source

pub fn to_submatrix<R, C>( &self, row_filter: &R, column_filter: &C, ) -> Result<CSVBinaryMatrix, DegeneratedMatrixError>

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
§Panics

Unreachable: if there are no distances in the distance list.

Source

pub fn into_submatrices<R, C>( self, row_col_filters: Vec<(&R, &C)>, ) -> Vec<Result<CSVBinaryMatrix, DegeneratedMatrixError>>

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
§Panics

Unreachable: if there are no distances in the distance list.

Source§

impl CSVBinaryMatrix

Source

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

Source

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

Source

pub fn number_of_cells(&self) -> usize

Returns the number of cells.

Source

pub fn number_of_ones(&self) -> usize

Returns the number of ones.

Source

pub fn number_of_zeros(&self) -> usize

Returns the number of zeros.

Source

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.

Source

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.

Source

pub fn is_complete(&self) -> bool

Returns true if the matrix is complete or all-ones.

Source

pub fn is_empty(&self) -> bool

Returns true if the matrix is empty or all-zeros.

Source§

impl CSVBinaryMatrix

Source

pub fn number_of_rows(&self) -> usize

Returns the number of rows.

Source

pub fn number_of_columns(&self) -> usize

Returns the number of columns.

Trait Implementations§

Source§

impl Clone for CSVBinaryMatrix

Source§

fn clone(&self) -> CSVBinaryMatrix

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CSVBinaryMatrix

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for CSVBinaryMatrix

Source§

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

Source§

fn eq(self: &CSVBinaryMatrix, other: &CSVBinaryMatrix) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

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>

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

The type returned in the event of a conversion error.
Source§

impl TryFrom<&Vec<Vec<bool>>> for CSVBinaryMatrix

Source§

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

The type returned in the event of a conversion error.
Source§

impl TryFrom<&Vec<Vec<u8>>> for CSVBinaryMatrix

Source§

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.

Source§

type Error = TryFromIntRowsError

The type returned in the event of a conversion error.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.