Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
modular_linalg.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
42# ifndef MODULAR_LINALG_H
43# define MODULAR_LINALG_H
44
45# include <cstdint>
46# include <algorithm>
47# include <optional>
48# include <type_traits>
49# include <ah-errors.H>
50# include <tpl_array.H>
51# include <tpl_dynMat.H>
52# include <modular_arithmetic.H>
53# include <primality.H>
54# include <concepts>
55# include <utility>
56
57namespace Aleph
58{
62 template <typename T>
63 concept SparseMatrix = requires(const T & m, T & mut_m, size_t r, size_t c, uint64_t v)
64 {
65 { m.rows() } -> std::convertible_to<size_t>;
66 { m.cols() } -> std::convertible_to<size_t>;
67 { m.read_ne(r, c) } -> std::convertible_to<uint64_t>;
68 { mut_m.write(r, c, v) };
69 { mut_m.traverse_allocated([](uint64_t &) { return true; }) } -> std::convertible_to<bool>;
70 { mut_m.set_dimension(r, c) };
71 };
72
76 template <typename T>
77 concept DenseMatrix = std::is_same_v<T, Array<Array<uint64_t>>>;
78
82 template <typename T>
84
93 template <DenseMatrix MatrixT>
94 [[nodiscard]] constexpr std::pair<size_t, size_t>
95 matrix_dims(const MatrixT & m) noexcept
96 {
97 const size_t rows = m.size();
98 return {rows, rows > 0 ? m[0].size() : 0};
99 }
100
102 template <SparseMatrix MatrixT>
103 [[nodiscard]] constexpr std::pair<size_t, size_t>
104 matrix_dims(const MatrixT & m) noexcept
105 {
106 return {m.rows(), m.cols()};
107 }
108
122 template <ModularMatrixBackend MatrixT>
124 {
125 MatrixT mat;
127
128 // Private helpers for matrix element access using constrained overloads
129 static uint64_t get_val(const MatrixT & m, size_t r, size_t c)
130 {
131 if constexpr (DenseMatrix<MatrixT>)
132 return m[r][c];
133 else
134 return m.read_ne(r, c);
135 }
136
137 static void set_val(MatrixT & m, size_t r, size_t c, uint64_t v)
138 {
139 if constexpr (DenseMatrix<MatrixT>)
140 m(r)(c) = v;
141 else
142 {
143 // Avoid materializing zero entries in sparse matrices.
144 // Only write if value is non-zero or if entry already exists.
145 if (v != 0 or m.read_ne(r, c) != 0)
146 m.write(r, c, v);
147 }
148 }
149
150 static void swap_rows(MatrixT & m, size_t r1, size_t r2)
151 {
152 if constexpr (DenseMatrix<MatrixT>)
153 std::swap(m(r1), m(r2));
154 else
155 {
156 const size_t cols = m.cols();
157 for (size_t j = 0; j < cols; ++j)
158 {
159 const uint64_t v1 = m.read_ne(r1, j);
160 const uint64_t v2 = m.read_ne(r2, j);
161
162 // Avoid redundant writes that can densify sparse backends
163 if (v1 == v2)
164 continue;
165
166 set_val(m, r1, j, v2);
167 set_val(m, r2, j, v1);
168 }
169 }
170 }
171
172 public:
182 Modular_Matrix(const MatrixT & m, const uint64_t p)
183 : mat(m), mod(p)
184 {
186 << "Modular_Matrix: modulus " << mod << " must be prime";
187
188 // Normalize initial values
189 if constexpr (DenseMatrix<MatrixT>)
190 {
191 const auto [n_rows, n_cols] = matrix_dims(mat);
192 if (n_rows > 0)
193 for (size_t i = 0; i < n_rows; ++i)
194 {
196 << "Modular_Matrix: ragged matrix input is not supported";
197 for (size_t j = 0; j < n_cols; ++j)
198 mat(i)(j) %= mod;
199 }
200 }
201 else // SparseMatrix
202 {
203 // Use traverse_allocated to efficiently normalize only stored entries
204 mat.traverse_allocated([this](uint64_t & val)
205 {
206 val %= mod;
207 return true;
208 });
209 }
210 }
211
212 private:
213 // Internal constructor to skip validation when data is already normalized
215 {};
216
218 : mat(std::move(m)), mod(p) {}
219
220 public:
227 const MatrixT &get() const noexcept { return mat; }
228
239 {
240 const auto [n_rows, n_cols] = matrix_dims(mat);
241
243 << "Determinant requires a square matrix";
244
245 MatrixT a = mat;
246 uint64_t det = 1;
247
248 for (size_t i = 0; i < n_rows; ++i)
249 {
250 size_t pivot = i;
251 if (get_val(a, i, i) == 0)
252 {
253 for (size_t j = i + 1; j < n_rows; ++j)
254 if (get_val(a, j, i) != 0)
255 {
256 pivot = j;
257 break;
258 }
259 }
260
261 if (get_val(a, pivot, i) == 0)
262 return 0; // Singular matrix
263
264 if (i != pivot)
265 {
266 swap_rows(a, i, pivot);
267 det = (mod - det) % mod;
268 }
269
270 const uint64_t diag = get_val(a, i, i);
271 det = mod_mul(det, diag, mod);
272 const uint64_t inv = mod_inv(diag, mod);
273
274 for (size_t j = i + 1; j < n_rows; ++j)
275 if (const uint64_t val_ji = get_val(a, j, i); val_ji != 0)
276 {
277 const uint64_t factor = mod_mul(val_ji, inv, mod);
278 for (size_t k = i; k < n_cols; ++k)
279 if (const uint64_t val_ik = get_val(a, i, k); val_ik != 0)
280 {
281 const uint64_t term = mod_mul(factor, val_ik, mod);
282 const uint64_t current = get_val(a, j, k);
283 const uint64_t res = (current >= term) ? (current - term) : (mod - (term - current));
284 set_val(a, j, k, res);
285 }
286 }
287 }
288 return det;
289 }
290
302 [[nodiscard]] std::optional<Modular_Matrix<MatrixT>> inverse() const
303 {
304 const auto [n_rows, n_cols] = matrix_dims(mat);
305
307 << "Inverse requires a square matrix";
308
309 MatrixT a = mat;
310 MatrixT inv;
311
312 if constexpr (DenseMatrix<MatrixT>)
313 {
314 inv.reserve(n_rows);
315 for (size_t i = 0; i < n_rows; ++i)
316 {
319 for (size_t j = 0; j < n_rows; ++j)
320 row.append(i == j ? 1 : 0);
321 inv.append(std::move(row));
322 }
323 }
324 else
325 {
326 inv.set_dimension(n_rows, n_rows);
327 for (size_t i = 0; i < n_rows; ++i)
328 inv.write(i, i, 1);
329 }
330
331 for (size_t i = 0; i < n_rows; ++i)
332 {
333 size_t pivot = i;
334 if (get_val(a, i, i) == 0)
335 for (size_t j = i + 1; j < n_rows; ++j)
336 if (get_val(a, j, i) != 0)
337 {
338 pivot = j;
339 break;
340 }
341
342 if (get_val(a, pivot, i) == 0)
343 return std::nullopt; // Singular matrix
344
345 if (i != pivot)
346 {
347 swap_rows(a, i, pivot);
348 swap_rows(inv, i, pivot);
349 }
350
351 const uint64_t pivot_val = get_val(a, i, i);
353 for (size_t j = 0; j < n_rows; ++j)
354 {
355 if (const uint64_t val = get_val(a, i, j); val != 0)
356 set_val(a, i, j, mod_mul(val, pivot_inv, mod));
357 if (const uint64_t val = get_val(inv, i, j); val != 0)
358 set_val(inv, i, j, mod_mul(val, pivot_inv, mod));
359 }
360
361 for (size_t j = 0; j < n_rows; ++j)
362 if (i != j)
363 if (const uint64_t factor = get_val(a, j, i); factor != 0)
364 for (size_t k = 0; k < n_rows; ++k)
365 {
366 if (const uint64_t val_ik = get_val(a, i, k); val_ik != 0)
367 {
368 const uint64_t term_a = mod_mul(factor, val_ik, mod);
369 const uint64_t curr_a = get_val(a, j, k);
370 set_val(a, j, k, (curr_a >= term_a) ? (curr_a - term_a) : (mod - (term_a - curr_a)));
371 }
372
373 if (const uint64_t val_inv_ik = get_val(inv, i, k); val_inv_ik != 0)
374 {
375 const uint64_t term_inv = mod_mul(factor, val_inv_ik, mod);
376 const uint64_t curr_inv = get_val(inv, j, k);
377 set_val(inv, j, k, (curr_inv >= term_inv) ?
378 (curr_inv - term_inv) :
379 (mod - (term_inv - curr_inv)));
380 }
381 }
382 }
383
384 return Modular_Matrix<MatrixT>(std::move(inv), mod, skip_validation_t{});
385 }
386 };
387
394
401} // namespace Aleph
402
403# endif // MODULAR_LINALG_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:527
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:644
size_t row
Definition ca-c-api.h:115
size_t * rows
Definition ca-c-api.h:112
size_t cols
Definition ca-c-api.h:105
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:138
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:320
Matrix operations modulo a prime.
MatrixT mat
The underlying matrix data.
static void swap_rows(MatrixT &m, size_t r1, size_t r2)
uint64_t mod
The prime modulus defining the finite field.
const MatrixT & get() const noexcept
Get a constant reference to the underlying matrix.
Modular_Matrix(MatrixT &&m, uint64_t p, skip_validation_t)
static void set_val(MatrixT &m, size_t r, size_t c, uint64_t v)
uint64_t determinant() const
Computes the determinant of the matrix modulo p.
Modular_Matrix(const MatrixT &m, const uint64_t p)
Construct a modular matrix from an existing matrix and a prime modulus.
static uint64_t get_val(const MatrixT &m, size_t r, size_t c)
std::optional< Modular_Matrix< MatrixT > > inverse() const
Computes the inverse of the matrix modulo p.
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:619
Expresses requirements for dense matrix backends like Array<Array<uint64_t>>.
Union of supported matrix backends for modular operations.
Expresses requirements for sparse matrix backends like DynMatrix.
size_t blossom_maximum_cardinality_matching(const GT &g, DynDlist< typename GT::Arc * > &matching, SA sa=SA())
Alias of compute_maximum_cardinality_general_matching().
Definition Blossom.H:466
Safe modular arithmetic, extended Euclidean algorithm, and Chinese Remainder Theorem.
Main namespace for Aleph-w library functions.
Definition ah-arena.H:89
uint64_t mod_inv(const uint64_t a, const uint64_t m)
Modular Inverse.
size_t size(Node *root) noexcept
constexpr std::pair< size_t, size_t > matrix_dims(const MatrixT &m) noexcept
Get dimensions of a matrix (dense or sparse).
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:105
bool miller_rabin(uint64_t n) noexcept
Miller-Rabin primality test for 64-bit integers.
Definition primality.H:88
uint64_t mod_mul(uint64_t a, uint64_t b, uint64_t m)
Safe 64-bit modular multiplication.
STL namespace.
Advanced primality testing algorithms.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
gsl_rng * r
Dynamic array container with automatic resizing.
Dynamic matrix with lazy allocation.