physics_in_parallel 3.0.3

High-performance infrastructure for numerical simulations in physics
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
/*!
Generic user-facing matrix wrapper.

`Matrix<T, B>` is a rank-2 mathematical facade over a backend `B`. The backend
may be ordinary rank-N dense/sparse tensor storage or a structured matrix
backend that stores only canonical entries and derives the rest from symmetry.
*/

use core::marker::PhantomData;

use crate::math::scalar::{Scalar, ScalarCastError};
use crate::math::tensor::rank_n::{Dense, Sparse, Tensor};
use rayon::prelude::*;

use super::matrix_backend_trait::MatrixBackend;

/// Rank-N dense tensor storage used as a matrix backend.
#[derive(Debug, Clone)]
pub struct RankNDense<T: Scalar> {
    tensor: Tensor<T, Dense>,
}

/// Rank-N sparse tensor storage used as a matrix backend.
#[derive(Debug, Clone)]
pub struct RankNSparse<T: Scalar> {
    tensor: Tensor<T, Sparse>,
}

/// Generic matrix facade.
#[derive(Debug, Clone)]
pub struct Matrix<T: Scalar, B: MatrixBackend<T> = RankNDense<T>> {
    backend: B,
    _scalar: PhantomData<T>,
}

/// Dense rank-N-backed matrix.
pub type DenseMatrix<T> = Matrix<T, RankNDense<T>>;

/// Sparse rank-N-backed matrix.
pub type SparseMatrix<T> = Matrix<T, RankNSparse<T>>;

impl<T: Scalar, B: MatrixBackend<T>> Matrix<T, B> {
    /// Wrap an already-constructed backend in the public matrix facade.
    #[inline]
    pub(crate) fn from_backend(backend: B) -> Self {
        Self {
            backend,
            _scalar: PhantomData,
        }
    }

    /// Construct a zero matrix with backend-specific storage.
    #[inline]
    pub fn empty(rows: usize, cols: usize) -> Self {
        Self::from_backend(B::empty(rows, cols))
    }

    /// Alias for `empty`.
    #[inline]
    pub fn zeros(rows: usize, cols: usize) -> Self {
        Self::empty(rows, cols)
    }

    /// Number of logical rows.
    #[inline]
    pub fn rows(&self) -> usize {
        self.backend.rows()
    }

    /// Number of logical columns.
    #[inline]
    pub fn cols(&self) -> usize {
        self.backend.cols()
    }

    /// Logical matrix shape as `[rows, cols]`.
    #[inline]
    pub fn shape(&self) -> [usize; 2] {
        self.backend.shape()
    }

    /// Number of logical entries.
    #[inline]
    pub fn size(&self) -> usize {
        self.backend.size()
    }

    /// Read the scalar at `(row, col)`.
    #[inline]
    pub fn get(&self, row: isize, col: isize) -> T {
        self.backend.get(row, col)
    }

    /// Write the scalar at `(row, col)`.
    #[inline]
    pub fn set(&mut self, row: isize, col: isize, value: T) {
        self.backend.set(row, col, value);
    }

    /// Fill every logical entry according to backend semantics.
    #[inline]
    pub fn fill(&mut self, value: T)
    where
        T: Copy + Send + Sync,
    {
        self.backend.fill(value);
    }

    /// Print a compact matrix table.
    pub fn print(&self)
    where
        T: Copy,
    {
        for row in 0..self.rows() {
            for col in 0..self.cols() {
                print!("{}\t", self.get(row as isize, col as isize));
            }
            println!();
        }
    }

    fn to_dense_rank_n_tensor(&self) -> Tensor<T, Dense>
    where
        T: Copy,
    {
        Tensor::<T, Dense>::from_fn(&[self.rows(), self.cols()], |idx| self.get(idx[0], idx[1]))
    }

    fn dense_matrix_from_rank_n(tensor: Tensor<T, Dense>) -> DenseMatrix<T>
    where
        T: Copy,
    {
        let rows = tensor.shape()[0];
        let cols = tensor.shape()[1];
        DenseMatrix::from_fn(rows, cols, |row, col| {
            tensor.get(&[row as isize, col as isize])
        })
    }

    fn matrix_from_dense_rank_n_preserving(tensor: &Tensor<T, Dense>) -> Self
    where
        T: Copy,
    {
        let rows = tensor.shape()[0];
        let cols = tensor.shape()[1];
        let entries: Vec<(usize, usize, T)> = (0..rows * cols)
            .into_par_iter()
            .map(|k| {
                let row = k / cols;
                let col = k % cols;
                (row, col, tensor.get(&[row as isize, col as isize]))
            })
            .collect();

        let mut out = Self::empty(rows, cols);
        for (row, col, value) in entries {
            out.set(row as isize, col as isize, value);
        }
        out
    }

    fn zip_preserving<RhsBackend, F>(&self, rhs: &Matrix<T, RhsBackend>, f: F) -> Self
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
        F: Fn(T, T) -> T + Sync + Send,
    {
        assert_eq!(
            self.shape(),
            rhs.shape(),
            "matrix elementwise operation shape mismatch"
        );

        let rows = self.rows();
        let cols = self.cols();
        let entries: Vec<(usize, usize, T)> = (0..rows * cols)
            .into_par_iter()
            .map(|k| {
                let row = k / cols;
                let col = k % cols;
                let value = f(
                    self.get(row as isize, col as isize),
                    rhs.get(row as isize, col as isize),
                );
                (row, col, value)
            })
            .collect();

        let mut out = Self::empty(rows, cols);
        for (row, col, value) in entries {
            out.set(row as isize, col as isize, value);
        }
        out
    }

    /// Materialize this matrix as an ordinary dense rank-N-backed matrix.
    pub fn to_dense_matrix(&self) -> DenseMatrix<T>
    where
        T: Copy,
    {
        Self::dense_matrix_from_rank_n(self.to_dense_rank_n_tensor())
    }

    /// Type-preserving elementwise matrix addition.
    ///
    /// The returned matrix has the same scalar type and same backend as
    /// `self`. Structured backends keep enforcing their mathematical
    /// invariants, so this method panics if the computed result cannot be
    /// represented by the left-hand backend.
    pub fn add<RhsBackend>(&self, rhs: &Matrix<T, RhsBackend>) -> Self
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
    {
        self.zip_preserving(rhs, |a, b| a + b)
    }

    /// Type-preserving elementwise matrix subtraction.
    pub fn sub<RhsBackend>(&self, rhs: &Matrix<T, RhsBackend>) -> Self
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
    {
        self.zip_preserving(rhs, |a, b| a - b)
    }

    /// Type-preserving elementwise matrix multiplication.
    pub fn elem_mul<RhsBackend>(&self, rhs: &Matrix<T, RhsBackend>) -> Self
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
    {
        self.zip_preserving(rhs, |a, b| a * b)
    }

    /// Type-preserving elementwise matrix division.
    pub fn elem_div<RhsBackend>(&self, rhs: &Matrix<T, RhsBackend>) -> Self
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
    {
        self.zip_preserving(rhs, |a, b| a / b)
    }

    /// Type-preserving scalar multiplication.
    pub fn scalar_mul(&self, scalar: T) -> Self
    where
        T: Copy + Send + Sync,
    {
        let rows = self.rows();
        let cols = self.cols();
        let entries: Vec<(usize, usize, T)> = (0..rows * cols)
            .into_par_iter()
            .map(|k| {
                let row = k / cols;
                let col = k % cols;
                (row, col, self.get(row as isize, col as isize) * scalar)
            })
            .collect();

        let mut out = Self::empty(rows, cols);
        for (row, col, value) in entries {
            out.set(row as isize, col as isize, value);
        }
        out
    }

    /// Type-preserving transpose.
    ///
    /// This method keeps the same backend type as `self`; structured backends
    /// therefore reject transposes that no longer fit their declared support.
    /// Use `transpose_to_dense` when changing backend is acceptable.
    pub fn transpose(&self) -> Self
    where
        T: Copy + Send + Sync,
    {
        let transposed = self.to_dense_rank_n_tensor().transpose();
        Self::matrix_from_dense_rank_n_preserving(&transposed)
    }

    /// Type-preserving Hermitian transpose.
    ///
    /// The result keeps the same backend type as `self`. Use
    /// `hermitian_transpose_to_dense` for the explicit backend-converting form.
    pub fn hermitian_transpose(&self) -> Self
    where
        T: Copy + Send + Sync,
    {
        let transposed = self.to_dense_rank_n_tensor().hermitian_transpose();
        Self::matrix_from_dense_rank_n_preserving(&transposed)
    }

    /// Type-preserving matrix multiplication.
    ///
    /// The calculation uses the rank-N matrix multiplication algorithm, then
    /// writes the result back into the left-hand backend. Structured backends
    /// panic if the product cannot be represented by that backend.
    pub fn matmul<RhsBackend>(&self, rhs: &Matrix<T, RhsBackend>) -> Self
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
    {
        assert_eq!(
            self.cols(),
            rhs.rows(),
            "matrix multiplication dimension mismatch"
        );
        let lhs = self.to_dense_rank_n_tensor();
        let rhs = rhs.to_dense_rank_n_tensor();
        let product = lhs.matmul(&rhs);
        Self::matrix_from_dense_rank_n_preserving(&product)
    }

    /// Backend-converting elementwise matrix addition.
    pub fn add_to_dense<RhsBackend>(&self, rhs: &Matrix<T, RhsBackend>) -> DenseMatrix<T>
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
    {
        let lhs = self.to_dense_rank_n_tensor();
        let rhs = rhs.to_dense_rank_n_tensor();
        Self::dense_matrix_from_rank_n(lhs.zip_with(&rhs, |a, b| a + b))
    }

    /// Backend-converting elementwise matrix subtraction.
    pub fn sub_to_dense<RhsBackend>(&self, rhs: &Matrix<T, RhsBackend>) -> DenseMatrix<T>
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
    {
        let lhs = self.to_dense_rank_n_tensor();
        let rhs = rhs.to_dense_rank_n_tensor();
        Self::dense_matrix_from_rank_n(lhs.zip_with(&rhs, |a, b| a - b))
    }

    /// Backend-converting elementwise matrix multiplication.
    pub fn elem_mul_to_dense<RhsBackend>(&self, rhs: &Matrix<T, RhsBackend>) -> DenseMatrix<T>
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
    {
        let lhs = self.to_dense_rank_n_tensor();
        let rhs = rhs.to_dense_rank_n_tensor();
        Self::dense_matrix_from_rank_n(lhs.elem_mul(&rhs))
    }

    /// Backend-converting elementwise matrix division.
    pub fn elem_div_to_dense<RhsBackend>(&self, rhs: &Matrix<T, RhsBackend>) -> DenseMatrix<T>
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
    {
        let lhs = self.to_dense_rank_n_tensor();
        let rhs = rhs.to_dense_rank_n_tensor();
        Self::dense_matrix_from_rank_n(lhs.elem_div(&rhs))
    }

    /// Backend-converting scalar multiplication.
    pub fn scalar_mul_to_dense(&self, scalar: T) -> DenseMatrix<T>
    where
        T: Copy + Send + Sync,
    {
        Self::dense_matrix_from_rank_n(self.to_dense_rank_n_tensor().scalar_mul(scalar))
    }

    /// Backend-converting transpose.
    pub fn transpose_to_dense(&self) -> DenseMatrix<T>
    where
        T: Copy + Send + Sync,
    {
        Self::dense_matrix_from_rank_n(self.to_dense_rank_n_tensor().transpose())
    }

    /// Backend-converting Hermitian transpose.
    pub fn hermitian_transpose_to_dense(&self) -> DenseMatrix<T>
    where
        T: Copy + Send + Sync,
    {
        Self::dense_matrix_from_rank_n(self.to_dense_rank_n_tensor().hermitian_transpose())
    }

    /// Backend-converting matrix multiplication.
    pub fn matmul_to_dense<RhsBackend>(&self, rhs: &Matrix<T, RhsBackend>) -> DenseMatrix<T>
    where
        RhsBackend: MatrixBackend<T>,
        T: Copy + Send + Sync,
    {
        assert_eq!(
            self.cols(),
            rhs.rows(),
            "matrix multiplication dimension mismatch"
        );
        let lhs = self.to_dense_rank_n_tensor();
        let rhs = rhs.to_dense_rank_n_tensor();
        Self::dense_matrix_from_rank_n(lhs.matmul(&rhs))
    }

    /// Sum of diagonal entries.
    pub fn trace(&self) -> T
    where
        T: Copy,
    {
        let n = self.rows().min(self.cols());
        (0..n).fold(T::zero(), |acc, i| acc + self.get(i as isize, i as isize))
    }
}

impl<T: Scalar> Matrix<T, RankNDense<T>> {
    /// Build a dense matrix from row-major values.
    #[inline]
    pub fn from_vec(rows: usize, cols: usize, data: Vec<T>) -> Self {
        assert_eq!(
            data.len(),
            rows.checked_mul(cols)
                .expect("matrix shape product overflow"),
            "dense matrix data length mismatch"
        );
        Self::from_backend(RankNDense {
            tensor: Tensor::<T, Dense>::from_vec(&[rows, cols], data),
        })
    }

    /// Build a dense matrix from a coordinate function.
    pub fn from_fn<F>(rows: usize, cols: usize, mut f: F) -> Self
    where
        F: FnMut(usize, usize) -> T,
    {
        let data = (0..rows)
            .flat_map(|row| (0..cols).map(move |col| (row, col)))
            .map(|(row, col)| f(row, col))
            .collect();
        Self::from_vec(rows, cols, data)
    }

    /// Fallibly cast all entries to a new scalar type.
    #[inline]
    pub fn try_cast_to<U: Scalar>(&self) -> Result<Matrix<U, RankNDense<U>>, ScalarCastError> {
        self.backend
            .tensor
            .try_cast_to::<U>()
            .map(|tensor| Matrix::from_backend(RankNDense { tensor }))
    }

    /// Cast all entries to a new scalar type, panicking on conversion failure.
    #[inline]
    pub fn cast_to<U: Scalar + Send + Sync>(&self) -> Matrix<U, RankNDense<U>> {
        Matrix::from_backend(RankNDense {
            tensor: self.backend.tensor.cast_to::<U>(),
        })
    }

    /// Convert this dense matrix into a sparse rank-N-backed matrix.
    #[inline]
    pub fn to_sparse(&self) -> Matrix<T, RankNSparse<T>> {
        Matrix::from_backend(RankNSparse {
            tensor: self.backend.tensor.to_sparse(),
        })
    }
}

impl<T: Scalar> Matrix<T, RankNSparse<T>> {
    /// Build a sparse matrix from `(row, col, value)` entries.
    pub fn from_triplets(
        rows: usize,
        cols: usize,
        triplets: impl IntoIterator<Item = (usize, usize, T)>,
    ) -> Self {
        let tensor_triplets = triplets
            .into_iter()
            .map(|(row, col, value)| (vec![row, col], value));
        Self::from_backend(RankNSparse {
            tensor: Tensor::<T, Sparse>::from_triplets(vec![rows, cols], tensor_triplets),
        })
    }

    /// Fallibly cast all explicitly stored entries to a new scalar type.
    #[inline]
    pub fn try_cast_to<U: Scalar>(&self) -> Result<Matrix<U, RankNSparse<U>>, ScalarCastError> {
        self.backend
            .tensor
            .try_cast_to::<U>()
            .map(|tensor| Matrix::from_backend(RankNSparse { tensor }))
    }

    /// Cast all explicitly stored entries to a new scalar type, panicking on failure.
    #[inline]
    pub fn cast_to<U: Scalar + Send + Sync>(&self) -> Matrix<U, RankNSparse<U>> {
        Matrix::from_backend(RankNSparse {
            tensor: self.backend.tensor.cast_to::<U>(),
        })
    }

    /// Convert this sparse matrix into a dense rank-N-backed matrix.
    #[inline]
    pub fn to_dense(&self) -> Matrix<T, RankNDense<T>> {
        Matrix::from_backend(RankNDense {
            tensor: self.backend.tensor.to_dense(),
        })
    }

    /// Number of explicitly stored sparse entries.
    #[inline]
    pub fn nnz(&self) -> usize {
        self.backend.tensor.nnz()
    }
}

impl<T: Scalar> MatrixBackend<T> for RankNDense<T> {
    #[inline]
    fn empty(rows: usize, cols: usize) -> Self {
        Self {
            tensor: Tensor::<T, Dense>::empty(&[rows, cols]),
        }
    }

    #[inline]
    fn rows(&self) -> usize {
        self.tensor.shape()[0]
    }

    #[inline]
    fn cols(&self) -> usize {
        self.tensor.shape()[1]
    }

    #[inline]
    fn get(&self, row: isize, col: isize) -> T {
        self.tensor.get(&[row, col])
    }

    #[inline]
    fn set(&mut self, row: isize, col: isize, value: T) {
        self.tensor.set(&[row, col], value);
    }
}

impl<T: Scalar> MatrixBackend<T> for RankNSparse<T> {
    #[inline]
    fn empty(rows: usize, cols: usize) -> Self {
        Self {
            tensor: Tensor::<T, Sparse>::empty(&[rows, cols]),
        }
    }

    #[inline]
    fn rows(&self) -> usize {
        self.tensor.shape()[0]
    }

    #[inline]
    fn cols(&self) -> usize {
        self.tensor.shape()[1]
    }

    #[inline]
    fn get(&self, row: isize, col: isize) -> T {
        self.tensor.get(&[row, col])
    }

    #[inline]
    fn set(&mut self, row: isize, col: isize, value: T) {
        self.tensor.set(&[row, col], value);
    }
}