poseidon_parameters/
matrix_ops.rs

1use core::slice::Chunks;
2
3use crate::error::PoseidonParameterError;
4use decaf377::Fq;
5
6pub trait MatrixOperations {
7    /// Create a new matrix
8    fn new(elements: &[Fq]) -> Self;
9    /// Access elements as an array of arrays
10    fn elements(&self) -> &[Fq];
11    /// Get element[i,j]
12    fn get_element(&self, i: usize, j: usize) -> Fq;
13    /// Set element[i,j]
14    fn set_element(&mut self, i: usize, j: usize, val: Fq);
15    /// Get rows
16    fn iter_rows(&self) -> Chunks<Fq> {
17        self.elements().chunks(self.n_cols())
18    }
19    /// Number of rows
20    fn n_rows(&self) -> usize;
21    /// Number of columns
22    fn n_cols(&self) -> usize;
23    /// Compute Hadamard (element-wise) product
24    fn hadamard_product(&self, rhs: &Self) -> Result<Self, PoseidonParameterError>
25    where
26        Self: Sized;
27}
28
29/// Compute vector dot product
30pub fn dot_product(a: &[Fq], b: &[Fq]) -> Fq {
31    if a.len() != b.len() {
32        panic!("vecs not same len")
33    }
34
35    a.iter().zip(b.iter()).map(|(x, y)| *x * *y).sum()
36}
37
38/// Matrix operations that are defined on square matrices.
39pub trait SquareMatrixOperations {
40    /// Compute the matrix inverse, if it exists
41    fn inverse(&self) -> Result<Self, PoseidonParameterError>
42    where
43        Self: Sized;
44    /// Construct an identity matrix
45    fn identity() -> Self;
46    /// Compute the matrix of minors
47    fn minors(&self) -> Self;
48    /// Compute the matrix of cofactors
49    fn cofactors(&self) -> Self;
50    /// Compute the matrix determinant
51    fn determinant(&self) -> Fq;
52}