binius_math/
matrix.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// Copyright 2024 Irreducible Inc.

use super::error::Error;
use binius_field::{ExtensionField, Field};
use binius_utils::bail;
use bytemuck::zeroed_slice_box;
use getset::CopyGetters;
use rand::RngCore;
use std::{
	iter::repeat_with,
	ops::{Add, AddAssign, Index, IndexMut, Sub, SubAssign},
};

/// A matrix over a field.
#[derive(Debug, Clone, PartialEq, Eq, CopyGetters)]
pub struct Matrix<F: Field> {
	#[getset(get_copy = "pub")]
	m: usize,
	#[getset(get_copy = "pub")]
	n: usize,
	elements: Box<[F]>,
}

impl<F: Field> Matrix<F> {
	pub fn new(m: usize, n: usize, elements: &[F]) -> Result<Self, Error> {
		if elements.len() != m * n {
			bail!(Error::IncorrectArgumentLength {
				arg: "elements".into(),
				expected: m * n,
			});
		}
		Ok(Self {
			m,
			n,
			elements: elements.into(),
		})
	}

	pub fn zeros(m: usize, n: usize) -> Self {
		Self {
			m,
			n,
			elements: zeroed_slice_box(m * n),
		}
	}

	pub fn identity(n: usize) -> Self {
		let mut out = Self::zeros(n, n);
		for i in 0..n {
			out[(i, i)] = F::ONE;
		}
		out
	}

	fn fill_identity(&mut self) {
		assert_eq!(self.m, self.n);
		self.elements.fill(F::ZERO);
		for i in 0..self.n {
			self[(i, i)] = F::ONE;
		}
	}

	pub fn elements(&self) -> &[F] {
		&self.elements
	}

	pub fn random(m: usize, n: usize, mut rng: impl RngCore) -> Self {
		Self {
			m,
			n,
			elements: repeat_with(|| F::random(&mut rng)).take(m * n).collect(),
		}
	}

	pub fn dim(&self) -> (usize, usize) {
		(self.m, self.n)
	}

	pub fn copy_from(&mut self, other: &Self) {
		assert_eq!(self.dim(), other.dim());
		self.elements.copy_from_slice(&other.elements);
	}

	pub fn mul_into(a: &Self, b: &Self, c: &mut Self) {
		assert_eq!(a.n(), b.m());
		assert_eq!(a.m(), c.m());
		assert_eq!(b.n(), c.n());

		for i in 0..c.m() {
			for j in 0..c.n() {
				c[(i, j)] = (0..a.n()).map(|k| a[(i, k)] * b[(k, j)]).sum();
			}
		}
	}

	pub fn mul_vec_into<FE: ExtensionField<F>>(&self, x: &[FE], y: &mut [FE]) {
		assert_eq!(self.n(), x.len());
		assert_eq!(self.m(), y.len());

		for i in 0..y.len() {
			y[i] = (0..self.n()).map(|j| x[j] * self[(i, j)]).sum();
		}
	}

	/// Invert a square matrix
	///
	/// ## Throws
	///
	/// * [`Error::MatrixNotSquare`]
	/// * [`Error::MatrixIsSingular`]
	///
	/// ## Preconditions
	///
	/// * `out` - must have the same dimensions as `self`
	pub fn inverse_into(&self, out: &mut Self) -> Result<(), Error> {
		assert_eq!(self.dim(), out.dim());

		if self.m != self.n {
			bail!(Error::MatrixNotSquare);
		}

		let n = self.n;

		let mut tmp = self.clone();
		out.fill_identity();

		let mut row_buffer = vec![F::ZERO; n];

		for i in 0..n {
			// Find the pivot row
			let pivot = (i..n)
				.find(|&pivot| tmp[(pivot, i)] != F::ZERO)
				.ok_or(Error::MatrixIsSingular)?;
			if pivot != i {
				tmp.swap_rows(i, pivot, &mut row_buffer);
				out.swap_rows(i, pivot, &mut row_buffer);
			}

			// Normalize the pivot
			let scalar = tmp[(i, i)]
				.invert()
				.expect("pivot is checked to be non-zero above");
			tmp.scale_row(i, scalar);
			out.scale_row(i, scalar);

			// Clear the pivot column
			for j in (0..i).chain(i + 1..n) {
				let scalar = tmp[(j, i)];
				tmp.sub_pivot_row(j, i, scalar);
				out.sub_pivot_row(j, i, scalar);
			}
		}

		debug_assert_eq!(tmp, Self::identity(n));

		Ok(())
	}

	fn row_ref(&self, i: usize) -> &[F] {
		assert!(i < self.m);
		&self.elements[i * self.n..(i + 1) * self.n]
	}

	fn row_mut(&mut self, i: usize) -> &mut [F] {
		assert!(i < self.m);
		&mut self.elements[i * self.n..(i + 1) * self.n]
	}

	fn swap_rows(&mut self, i0: usize, i1: usize, buffer: &mut [F]) {
		assert!(i0 < self.m);
		assert!(i1 < self.m);
		assert_eq!(buffer.len(), self.n);

		if i0 == i1 {
			return;
		}

		buffer.copy_from_slice(self.row_ref(i1));
		self.elements
			.copy_within(i0 * self.n..(i0 + 1) * self.n, i1 * self.n);
		self.row_mut(i0).copy_from_slice(buffer);
	}

	fn scale_row(&mut self, i: usize, scalar: F) {
		assert!(i < self.m);

		for x in self.row_mut(i) {
			*x *= scalar;
		}
	}

	fn sub_pivot_row(&mut self, i0: usize, i1: usize, scalar: F) {
		assert!(i0 < self.m);
		assert!(i1 < self.m);

		for j in 0..self.n {
			let x = self[(i1, j)];
			self[(i0, j)] -= x * scalar;
		}
	}
}

impl<F: Field> Index<(usize, usize)> for Matrix<F> {
	type Output = F;

	fn index(&self, index: (usize, usize)) -> &Self::Output {
		let (i, j) = index;
		assert!(i < self.m);
		assert!(j < self.n);
		&self.elements[i * self.n + j]
	}
}

impl<F: Field> IndexMut<(usize, usize)> for Matrix<F> {
	fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output {
		let (i, j) = index;
		assert!(i < self.m);
		assert!(j < self.n);
		&mut self.elements[i * self.n + j]
	}
}

impl<F: Field> Add<Self> for &Matrix<F> {
	type Output = Matrix<F>;

	fn add(self, rhs: Self) -> Matrix<F> {
		let mut out = self.clone();
		out += rhs;
		out
	}
}

impl<F: Field> Sub<Self> for &Matrix<F> {
	type Output = Matrix<F>;

	fn sub(self, rhs: Self) -> Matrix<F> {
		let mut out = self.clone();
		out -= rhs;
		out
	}
}

impl<F: Field> AddAssign<&Self> for Matrix<F> {
	fn add_assign(&mut self, rhs: &Self) {
		assert_eq!(self.dim(), rhs.dim());
		for (a_ij, &b_ij) in self.elements.iter_mut().zip(rhs.elements.iter()) {
			*a_ij += b_ij;
		}
	}
}

impl<F: Field> SubAssign<&Self> for Matrix<F> {
	fn sub_assign(&mut self, rhs: &Self) {
		assert_eq!(self.dim(), rhs.dim());
		for (a_ij, &b_ij) in self.elements.iter_mut().zip(rhs.elements.iter()) {
			*a_ij -= b_ij;
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use binius_field::BinaryField32b;
	use proptest::prelude::*;
	use rand::{rngs::StdRng, SeedableRng};

	proptest! {
		#[test]
		fn test_left_linearity(c_m in 0..8usize, c_n in 0..8usize, a_n in 0..8usize) {
			type F = BinaryField32b;

			let mut rng = StdRng::seed_from_u64(0);
			let a0 = Matrix::<F>::random(c_m, a_n, &mut rng);
			let a1 = Matrix::<F>::random(c_m, a_n, &mut rng);
			let b = Matrix::<F>::random(a_n, c_n, &mut rng);
			let mut c0 = Matrix::<F>::zeros(c_m, c_n);
			let mut c1 = Matrix::<F>::zeros(c_m, c_n);

			let a0p1 = &a0 + &a1;
			let mut c0p1 = Matrix::<F>::zeros(c_m, c_n);

			Matrix::mul_into(&a0, &b, &mut c0);
			Matrix::mul_into(&a1, &b, &mut c1);
			Matrix::mul_into(&a0p1, &b, &mut c0p1);

			assert_eq!(c0p1, &c0 + &c1);
		}

		#[test]
		fn test_right_linearity(c_m in 0..8usize, c_n in 0..8usize, a_n in 0..8usize) {
			type F = BinaryField32b;

			let mut rng = StdRng::seed_from_u64(0);
			let a = Matrix::<F>::random(c_m, a_n, &mut rng);
			let b0 = Matrix::<F>::random(a_n, c_n, &mut rng);
			let b1 = Matrix::<F>::random(a_n, c_n, &mut rng);
			let mut c0 = Matrix::<F>::zeros(c_m, c_n);
			let mut c1 = Matrix::<F>::zeros(c_m, c_n);

			let b0p1 = &b0 + &b1;
			let mut c0p1 = Matrix::<F>::zeros(c_m, c_n);

			Matrix::mul_into(&a, &b0, &mut c0);
			Matrix::mul_into(&a, &b1, &mut c1);
			Matrix::mul_into(&a, &b0p1, &mut c0p1);

			assert_eq!(c0p1, &c0 + &c1);
		}

		#[test]
		fn test_double_inverse(n in 0..8usize) {
			type F = BinaryField32b;

			let mut rng = StdRng::seed_from_u64(0);
			let a = Matrix::<F>::random(n, n, &mut rng);
			let mut a_inv = Matrix::<F>::zeros(n, n);
			let mut a_inv_inv = Matrix::<F>::zeros(n, n);

			a.inverse_into(&mut a_inv).unwrap();
			a_inv.inverse_into(&mut a_inv_inv).unwrap();
			assert_eq!(a_inv_inv, a);
		}

		#[test]
		fn test_inverse(n in 0..8usize) {
			type F = BinaryField32b;

			let mut rng = StdRng::seed_from_u64(0);
			let a = Matrix::<F>::random(n, n, &mut rng);
			let mut a_inv = Matrix::<F>::zeros(n, n);
			let mut prod = Matrix::<F>::zeros(n, n);

			a.inverse_into(&mut a_inv).unwrap();

			Matrix::mul_into(&a, &a_inv, &mut prod);
			assert_eq!(prod, Matrix::<F>::identity(n));

			Matrix::mul_into(&a_inv, &a, &mut prod);
			assert_eq!(prod, Matrix::<F>::identity(n));
		}
	}
}