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
41# ifndef MODULAR_LINALG_H
42# define MODULAR_LINALG_H
43
44# include <cstdint>
45# include <algorithm>
46# include <optional>
47# include <type_traits>
48# include <ah-errors.H>
49# include <tpl_array.H>
50# include <tpl_dynMat.H>
51# include <modular_arithmetic.H>
52# include <primality.H>
53# include <concepts>
54# include <utility>
55
56namespace Aleph
57{
61 template <typename T>
62 concept SparseMatrix = requires(const T & m, T & mut_m, size_t r, size_t c, uint64_t v)
63 {
64 { m.rows() } -> std::convertible_to<size_t>;
65 { m.cols() } -> std::convertible_to<size_t>;
66 { m.read_ne(r, c) } -> std::convertible_to<uint64_t>;
67 { mut_m.write(r, c, v) };
68 { mut_m.traverse_allocated([](uint64_t &) { return true; }) } -> std::convertible_to<bool>;
69 { mut_m.set_dimension(r, c) };
70 };
71
75 template <typename T>
76 concept DenseMatrix = std::is_same_v<T, Array<Array<uint64_t>>>;
77
81 template <typename T>
83
92 template <DenseMatrix MatrixT>
93 [[nodiscard]] constexpr std::pair<size_t, size_t>
94 matrix_dims(const MatrixT & m) noexcept
95 {
96 const size_t rows = m.size();
97 return {rows, rows > 0 ? m[0].size() : 0};
98 }
99
101 template <SparseMatrix MatrixT>
102 [[nodiscard]] constexpr std::pair<size_t, size_t>
103 matrix_dims(const MatrixT & m) noexcept
104 {
105 return {m.rows(), m.cols()};
106 }
107
121 template <ModularMatrixBackend MatrixT>
123 {
124 MatrixT mat;
126
127 // Private helpers for matrix element access using constrained overloads
128 static uint64_t get_val(const MatrixT & m, size_t r, size_t c)
129 {
130 if constexpr (DenseMatrix<MatrixT>)
131 return m[r][c];
132 else
133 return m.read_ne(r, c);
134 }
135
136 static void set_val(MatrixT & m, size_t r, size_t c, uint64_t v)
137 {
138 if constexpr (DenseMatrix<MatrixT>)
139 m(r)(c) = v;
140 else
141 {
142 // Avoid materializing zero entries in sparse matrices.
143 // Only write if value is non-zero or if entry already exists.
144 if (v != 0 or m.read_ne(r, c) != 0)
145 m.write(r, c, v);
146 }
147 }
148
149 static void swap_rows(MatrixT & m, size_t r1, size_t r2)
150 {
151 if constexpr (DenseMatrix<MatrixT>)
152 std::swap(m(r1), m(r2));
153 else
154 {
155 const size_t cols = m.cols();
156 for (size_t j = 0; j < cols; ++j)
157 {
158 const uint64_t v1 = m.read_ne(r1, j);
159 const uint64_t v2 = m.read_ne(r2, j);
160
161 // Avoid redundant writes that can densify sparse backends
162 if (v1 == v2)
163 continue;
164
165 set_val(m, r1, j, v2);
166 set_val(m, r2, j, v1);
167 }
168 }
169 }
170
171 public:
181 Modular_Matrix(const MatrixT & m, const uint64_t p)
182 : mat(m), mod(p)
183 {
185 << "Modular_Matrix: modulus " << mod << " must be prime";
186
187 // Normalize initial values
188 if constexpr (DenseMatrix<MatrixT>)
189 {
190 const auto [n_rows, n_cols] = matrix_dims(mat);
191 if (n_rows > 0)
192 for (size_t i = 0; i < n_rows; ++i)
193 {
195 << "Modular_Matrix: ragged matrix input is not supported";
196 for (size_t j = 0; j < n_cols; ++j)
197 mat(i)(j) %= mod;
198 }
199 }
200 else // SparseMatrix
201 {
202 // Use traverse_allocated to efficiently normalize only stored entries
203 mat.traverse_allocated([this](uint64_t & val)
204 {
205 val %= mod;
206 return true;
207 });
208 }
209 }
210
211 private:
212 // Internal constructor to skip validation when data is already normalized
214 {};
215
217 : mat(std::move(m)), mod(p) {}
218
219 public:
226 const MatrixT &get() const noexcept { return mat; }
227
238 {
239 const auto [n_rows, n_cols] = matrix_dims(mat);
240
242 << "Determinant requires a square matrix";
243
244 MatrixT a = mat;
245 uint64_t det = 1;
246
247 for (size_t i = 0; i < n_rows; ++i)
248 {
249 size_t pivot = i;
250 if (get_val(a, i, i) == 0)
251 {
252 for (size_t j = i + 1; j < n_rows; ++j)
253 if (get_val(a, j, i) != 0)
254 {
255 pivot = j;
256 break;
257 }
258 }
259
260 if (get_val(a, pivot, i) == 0)
261 return 0; // Singular matrix
262
263 if (i != pivot)
264 {
265 swap_rows(a, i, pivot);
266 det = (mod - det) % mod;
267 }
268
269 const uint64_t diag = get_val(a, i, i);
270 det = mod_mul(det, diag, mod);
271 const uint64_t inv = mod_inv(diag, mod);
272
273 for (size_t j = i + 1; j < n_rows; ++j)
274 if (const uint64_t val_ji = get_val(a, j, i); val_ji != 0)
275 {
276 const uint64_t factor = mod_mul(val_ji, inv, mod);
277 for (size_t k = i; k < n_cols; ++k)
278 if (const uint64_t val_ik = get_val(a, i, k); val_ik != 0)
279 {
280 const uint64_t term = mod_mul(factor, val_ik, mod);
281 const uint64_t current = get_val(a, j, k);
282 const uint64_t res = (current >= term) ? (current - term) : (mod - (term - current));
283 set_val(a, j, k, res);
284 }
285 }
286 }
287 return det;
288 }
289
301 [[nodiscard]] std::optional<Modular_Matrix<MatrixT>> inverse() const
302 {
303 const auto [n_rows, n_cols] = matrix_dims(mat);
304
306 << "Inverse requires a square matrix";
307
308 MatrixT a = mat;
309 MatrixT inv;
310
311 if constexpr (DenseMatrix<MatrixT>)
312 {
313 inv.reserve(n_rows);
314 for (size_t i = 0; i < n_rows; ++i)
315 {
316 Array<uint64_t> row;
317 row.reserve(n_rows);
318 for (size_t j = 0; j < n_rows; ++j)
319 row.append(i == j ? 1 : 0);
320 inv.append(std::move(row));
321 }
322 }
323 else
324 {
325 inv.set_dimension(n_rows, n_rows);
326 for (size_t i = 0; i < n_rows; ++i)
327 inv.write(i, i, 1);
328 }
329
330 for (size_t i = 0; i < n_rows; ++i)
331 {
332 size_t pivot = i;
333 if (get_val(a, i, i) == 0)
334 for (size_t j = i + 1; j < n_rows; ++j)
335 if (get_val(a, j, i) != 0)
336 {
337 pivot = j;
338 break;
339 }
340
341 if (get_val(a, pivot, i) == 0)
342 return std::nullopt; // Singular matrix
343
344 if (i != pivot)
345 {
346 swap_rows(a, i, pivot);
347 swap_rows(inv, i, pivot);
348 }
349
350 const uint64_t pivot_val = get_val(a, i, i);
352 for (size_t j = 0; j < n_rows; ++j)
353 {
354 if (const uint64_t val = get_val(a, i, j); val != 0)
355 set_val(a, i, j, mod_mul(val, pivot_inv, mod));
356 if (const uint64_t val = get_val(inv, i, j); val != 0)
357 set_val(inv, i, j, mod_mul(val, pivot_inv, mod));
358 }
359
360 for (size_t j = 0; j < n_rows; ++j)
361 if (i != j)
362 if (const uint64_t factor = get_val(a, j, i); factor != 0)
363 for (size_t k = 0; k < n_rows; ++k)
364 {
365 if (const uint64_t val_ik = get_val(a, i, k); val_ik != 0)
366 {
367 const uint64_t term_a = mod_mul(factor, val_ik, mod);
368 const uint64_t curr_a = get_val(a, j, k);
369 set_val(a, j, k, (curr_a >= term_a) ? (curr_a - term_a) : (mod - (term_a - curr_a)));
370 }
371
372 if (const uint64_t val_inv_ik = get_val(inv, i, k); val_inv_ik != 0)
373 {
374 const uint64_t term_inv = mod_mul(factor, val_inv_ik, mod);
375 const uint64_t curr_inv = get_val(inv, j, k);
376 set_val(inv, j, k, (curr_inv >= term_inv) ?
377 (curr_inv - term_inv) :
378 (mod - (term_inv - curr_inv)));
379 }
380 }
381 }
382
383 return Modular_Matrix<MatrixT>(std::move(inv), mod, skip_validation_t{});
384 }
385 };
386
393
400} // namespace Aleph
401
402# 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:522
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:639
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:139
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:245
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:315
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.
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).
Divide_Conquer_DP_Result< Cost > divide_and_conquer_partition_dp(const size_t groups, const size_t n, Transition_Cost_Fn transition_cost, const Cost inf=dp_optimization_detail::default_inf< Cost >())
Optimize partition DP using divide-and-conquer optimization.
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:87
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.