binius_math/
matrix.rs

1// Copyright 2024-2025 Irreducible Inc.
2
3use std::{
4	iter::repeat_with,
5	ops::{Add, AddAssign, Index, IndexMut, Sub, SubAssign},
6};
7
8use binius_field::{ExtensionField, Field};
9use binius_utils::bail;
10use bytemuck::zeroed_slice_box;
11use getset::CopyGetters;
12use rand::RngCore;
13
14use super::error::Error;
15
16/// A matrix over a field.
17#[derive(Debug, Clone, PartialEq, Eq, CopyGetters)]
18pub struct Matrix<F: Field> {
19	/// The number of rows.
20	#[getset(get_copy = "pub")]
21	m: usize,
22	/// The number of columns.
23	#[getset(get_copy = "pub")]
24	n: usize,
25	elements: Box<[F]>,
26}
27
28impl<F: Field> Matrix<F> {
29	pub fn new(m: usize, n: usize, elements: &[F]) -> Result<Self, Error> {
30		if elements.len() != m * n {
31			bail!(Error::IncorrectArgumentLength {
32				arg: "elements".into(),
33				expected: m * n,
34			});
35		}
36		Ok(Self {
37			m,
38			n,
39			elements: elements.into(),
40		})
41	}
42
43	pub fn zeros(m: usize, n: usize) -> Self {
44		Self {
45			m,
46			n,
47			elements: zeroed_slice_box(m * n),
48		}
49	}
50
51	pub fn identity(n: usize) -> Self {
52		let mut out = Self::zeros(n, n);
53		for i in 0..n {
54			out[(i, i)] = F::ONE;
55		}
56		out
57	}
58
59	fn fill_identity(&mut self) {
60		assert_eq!(self.m, self.n);
61		self.elements.fill(F::ZERO);
62		for i in 0..self.n {
63			self[(i, i)] = F::ONE;
64		}
65	}
66
67	pub const fn elements(&self) -> &[F] {
68		&self.elements
69	}
70
71	pub fn random(m: usize, n: usize, mut rng: impl RngCore) -> Self {
72		Self {
73			m,
74			n,
75			elements: repeat_with(|| F::random(&mut rng)).take(m * n).collect(),
76		}
77	}
78
79	pub const fn dim(&self) -> (usize, usize) {
80		(self.m, self.n)
81	}
82
83	pub fn copy_from(&mut self, other: &Self) {
84		assert_eq!(self.dim(), other.dim());
85		self.elements.copy_from_slice(&other.elements);
86	}
87
88	pub fn mul_into(a: &Self, b: &Self, c: &mut Self) {
89		assert_eq!(a.n(), b.m());
90		assert_eq!(a.m(), c.m());
91		assert_eq!(b.n(), c.n());
92
93		for i in 0..c.m() {
94			for j in 0..c.n() {
95				c[(i, j)] = (0..a.n()).map(|k| a[(i, k)] * b[(k, j)]).sum();
96			}
97		}
98	}
99
100	pub fn mul_vec_into<FE: ExtensionField<F>>(&self, x: &[FE], y: &mut [FE]) {
101		assert_eq!(self.n(), x.len());
102		assert_eq!(self.m(), y.len());
103
104		for i in 0..y.len() {
105			y[i] = (0..self.n()).map(|j| x[j] * self[(i, j)]).sum();
106		}
107	}
108
109	/// Invert a square matrix
110	///
111	/// ## Throws
112	///
113	/// * [`Error::MatrixNotSquare`]
114	/// * [`Error::MatrixIsSingular`]
115	///
116	/// ## Preconditions
117	///
118	/// * `out` - must have the same dimensions as `self`
119	pub fn inverse_into(&self, out: &mut Self) -> Result<(), Error> {
120		assert_eq!(self.dim(), out.dim());
121
122		if self.m != self.n {
123			bail!(Error::MatrixNotSquare);
124		}
125
126		let n = self.n;
127
128		let mut tmp = self.clone();
129		out.fill_identity();
130
131		let mut row_buffer = vec![F::ZERO; n];
132
133		for i in 0..n {
134			// Find the pivot row
135			let pivot = (i..n)
136				.find(|&pivot| tmp[(pivot, i)] != F::ZERO)
137				.ok_or(Error::MatrixIsSingular)?;
138			if pivot != i {
139				tmp.swap_rows(i, pivot, &mut row_buffer);
140				out.swap_rows(i, pivot, &mut row_buffer);
141			}
142
143			// Normalize the pivot
144			let scalar = tmp[(i, i)]
145				.invert()
146				.expect("pivot is checked to be non-zero above");
147			tmp.scale_row(i, scalar);
148			out.scale_row(i, scalar);
149
150			// Clear the pivot column
151			for j in (0..i).chain(i + 1..n) {
152				let scalar = tmp[(j, i)];
153				tmp.sub_pivot_row(j, i, scalar);
154				out.sub_pivot_row(j, i, scalar);
155			}
156		}
157
158		debug_assert_eq!(tmp, Self::identity(n));
159
160		Ok(())
161	}
162
163	fn row_ref(&self, i: usize) -> &[F] {
164		assert!(i < self.m);
165		&self.elements[i * self.n..(i + 1) * self.n]
166	}
167
168	fn row_mut(&mut self, i: usize) -> &mut [F] {
169		assert!(i < self.m);
170		&mut self.elements[i * self.n..(i + 1) * self.n]
171	}
172
173	fn swap_rows(&mut self, i0: usize, i1: usize, buffer: &mut [F]) {
174		assert!(i0 < self.m);
175		assert!(i1 < self.m);
176		assert_eq!(buffer.len(), self.n);
177
178		if i0 == i1 {
179			return;
180		}
181
182		buffer.copy_from_slice(self.row_ref(i1));
183		self.elements
184			.copy_within(i0 * self.n..(i0 + 1) * self.n, i1 * self.n);
185		self.row_mut(i0).copy_from_slice(buffer);
186	}
187
188	fn scale_row(&mut self, i: usize, scalar: F) {
189		for x in self.row_mut(i) {
190			*x *= scalar;
191		}
192	}
193
194	fn sub_pivot_row(&mut self, i0: usize, i1: usize, scalar: F) {
195		assert!(i0 < self.m);
196		assert!(i1 < self.m);
197
198		for j in 0..self.n {
199			let x = self[(i1, j)];
200			self[(i0, j)] -= x * scalar;
201		}
202	}
203}
204
205impl<F: Field> Index<(usize, usize)> for Matrix<F> {
206	type Output = F;
207
208	fn index(&self, (i, j): (usize, usize)) -> &Self::Output {
209		assert!(i < self.m);
210		assert!(j < self.n);
211		&self.elements[i * self.n + j]
212	}
213}
214
215impl<F: Field> IndexMut<(usize, usize)> for Matrix<F> {
216	fn index_mut(&mut self, (i, j): (usize, usize)) -> &mut Self::Output {
217		assert!(i < self.m);
218		assert!(j < self.n);
219		&mut self.elements[i * self.n + j]
220	}
221}
222
223impl<F: Field> Add<Self> for &Matrix<F> {
224	type Output = Matrix<F>;
225
226	fn add(self, rhs: Self) -> Matrix<F> {
227		let mut out = self.clone();
228		out += rhs;
229		out
230	}
231}
232
233impl<F: Field> Sub<Self> for &Matrix<F> {
234	type Output = Matrix<F>;
235
236	fn sub(self, rhs: Self) -> Matrix<F> {
237		let mut out = self.clone();
238		out -= rhs;
239		out
240	}
241}
242
243impl<F: Field> AddAssign<&Self> for Matrix<F> {
244	fn add_assign(&mut self, rhs: &Self) {
245		assert_eq!(self.dim(), rhs.dim());
246		for (a_ij, &b_ij) in self.elements.iter_mut().zip(rhs.elements.iter()) {
247			*a_ij += b_ij;
248		}
249	}
250}
251
252impl<F: Field> SubAssign<&Self> for Matrix<F> {
253	fn sub_assign(&mut self, rhs: &Self) {
254		assert_eq!(self.dim(), rhs.dim());
255		for (a_ij, &b_ij) in self.elements.iter_mut().zip(rhs.elements.iter()) {
256			*a_ij -= b_ij;
257		}
258	}
259}
260
261#[cfg(test)]
262mod tests {
263	use binius_field::BinaryField32b;
264	use proptest::prelude::*;
265	use rand::{rngs::StdRng, SeedableRng};
266
267	use super::*;
268
269	proptest! {
270		#[test]
271		fn test_left_linearity(c_m in 0..8usize, c_n in 0..8usize, a_n in 0..8usize) {
272			type F = BinaryField32b;
273
274			let mut rng = StdRng::seed_from_u64(0);
275			let a0 = Matrix::<F>::random(c_m, a_n, &mut rng);
276			let a1 = Matrix::<F>::random(c_m, a_n, &mut rng);
277			let b = Matrix::<F>::random(a_n, c_n, &mut rng);
278			let mut c0 = Matrix::<F>::zeros(c_m, c_n);
279			let mut c1 = Matrix::<F>::zeros(c_m, c_n);
280
281			let a0p1 = &a0 + &a1;
282			let mut c0p1 = Matrix::<F>::zeros(c_m, c_n);
283
284			Matrix::mul_into(&a0, &b, &mut c0);
285			Matrix::mul_into(&a1, &b, &mut c1);
286			Matrix::mul_into(&a0p1, &b, &mut c0p1);
287
288			assert_eq!(c0p1, &c0 + &c1);
289		}
290
291		#[test]
292		fn test_right_linearity(c_m in 0..8usize, c_n in 0..8usize, a_n in 0..8usize) {
293			type F = BinaryField32b;
294
295			let mut rng = StdRng::seed_from_u64(0);
296			let a = Matrix::<F>::random(c_m, a_n, &mut rng);
297			let b0 = Matrix::<F>::random(a_n, c_n, &mut rng);
298			let b1 = Matrix::<F>::random(a_n, c_n, &mut rng);
299			let mut c0 = Matrix::<F>::zeros(c_m, c_n);
300			let mut c1 = Matrix::<F>::zeros(c_m, c_n);
301
302			let b0p1 = &b0 + &b1;
303			let mut c0p1 = Matrix::<F>::zeros(c_m, c_n);
304
305			Matrix::mul_into(&a, &b0, &mut c0);
306			Matrix::mul_into(&a, &b1, &mut c1);
307			Matrix::mul_into(&a, &b0p1, &mut c0p1);
308
309			assert_eq!(c0p1, &c0 + &c1);
310		}
311
312		#[test]
313		fn test_double_inverse(n in 0..8usize) {
314			type F = BinaryField32b;
315
316			let mut rng = StdRng::seed_from_u64(0);
317			let a = Matrix::<F>::random(n, n, &mut rng);
318			let mut a_inv = Matrix::<F>::zeros(n, n);
319			let mut a_inv_inv = Matrix::<F>::zeros(n, n);
320
321			a.inverse_into(&mut a_inv).unwrap();
322			a_inv.inverse_into(&mut a_inv_inv).unwrap();
323			assert_eq!(a_inv_inv, a);
324		}
325
326		#[test]
327		fn test_inverse(n in 0..8usize) {
328			type F = BinaryField32b;
329
330			let mut rng = StdRng::seed_from_u64(0);
331			let a = Matrix::<F>::random(n, n, &mut rng);
332			let mut a_inv = Matrix::<F>::zeros(n, n);
333			let mut prod = Matrix::<F>::zeros(n, n);
334
335			a.inverse_into(&mut a_inv).unwrap();
336
337			Matrix::mul_into(&a, &a_inv, &mut prod);
338			assert_eq!(prod, Matrix::<F>::identity(n));
339
340			Matrix::mul_into(&a_inv, &a, &mut prod);
341			assert_eq!(prod, Matrix::<F>::identity(n));
342		}
343	}
344}