physics_in_parallel 4.0.0-alpha.2

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
//! Backend-agnostic rank-two matrix API.

use core::cmp::Ordering;
use core::fmt;

use num_traits::Zero;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::math::scalar::{Scalar, ScalarCastError};

use super::rank_n::errors::TensorError;
use super::universal::{Backend, Tensor, TensorBuilder, Values};

/// Failure while constructing or operating on a matrix.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum MatrixError {
    Tensor(TensorError),
    InputLength { expected: usize, actual: usize },
    BatchInputLength { columns: usize, actual: usize },
    OutputLength { expected: usize, actual: usize },
}

impl From<TensorError> for MatrixError {
    fn from(error: TensorError) -> Self {
        Self::Tensor(error)
    }
}

impl fmt::Display for MatrixError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Tensor(error) => write!(formatter, "invalid matrix: {error}"),
            Self::InputLength { expected, actual } => write!(
                formatter,
                "matrix input length mismatch: expected {expected}, got {actual}"
            ),
            Self::BatchInputLength { columns, actual } => write!(
                formatter,
                "batched matrix input length {actual} is not divisible by {columns} columns"
            ),
            Self::OutputLength { expected, actual } => write!(
                formatter,
                "matrix output length mismatch: expected {expected}, got {actual}"
            ),
        }
    }
}

impl std::error::Error for MatrixError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Tensor(error) => Some(error),
            _ => None,
        }
    }
}

/// A rank-two matrix with either the dense or sparse backend.
#[derive(Clone, Debug, PartialEq)]
pub struct Matrix<T: Scalar> {
    tensor: Tensor<T>,
}

/// Safe construction buffer returned by [`Matrix::empty`].
pub struct MatrixBuilder<T: Scalar> {
    builder: TensorBuilder<T>,
}

impl<T: Scalar> MatrixBuilder<T> {
    /// Returns the selected backend.
    pub const fn backend(&self) -> Backend {
        self.builder.backend()
    }

    /// Returns `[rows, columns]`.
    pub fn shape(&self) -> [usize; 2] {
        [self.builder.shape()[0], self.builder.shape()[1]]
    }

    /// Writes one matrix element into the construction buffer.
    pub fn set(&mut self, row: usize, column: usize, value: T) -> Result<(), MatrixError> {
        Ok(self.builder.set(&[row, column], value)?)
    }

    /// Finalizes the matrix after validating backend-specific initialization.
    pub fn finish(self) -> Result<Matrix<T>, MatrixError> {
        Matrix::from_tensor(self.builder.finish()?)
    }
}

impl<T> Eq for Matrix<T> where T: Scalar + Eq {}

impl<T: Scalar> Matrix<T> {
    /// Allocates an empty construction buffer for the selected backend.
    pub fn empty(
        rows: usize,
        columns: usize,
        backend: Backend,
    ) -> Result<MatrixBuilder<T>, MatrixError> {
        Ok(MatrixBuilder {
            builder: Tensor::empty(&[rows, columns], backend)?,
        })
    }

    /// Constructs a matrix from row-major logical values.
    pub fn from_values(
        rows: usize,
        columns: usize,
        backend: Backend,
        values: Vec<T>,
    ) -> Result<Self, MatrixError> {
        Self::from_tensor(Tensor::from_values(&[rows, columns], backend, values)?)
    }

    /// Constructs a matrix from strict `(row, column, value)` entries.
    pub fn from_entries(
        rows: usize,
        columns: usize,
        backend: Backend,
        entries: impl IntoIterator<Item = (usize, usize, T)>,
    ) -> Result<Self, MatrixError> {
        let entries = entries
            .into_iter()
            .map(|(row, column, value)| (vec![row, column], value));
        Self::from_tensor(Tensor::from_entries(&[rows, columns], backend, entries)?)
    }

    /// Constructs an all-zero matrix using the selected backend.
    pub fn zeros(rows: usize, columns: usize, backend: Backend) -> Result<Self, MatrixError> {
        Self::from_tensor(Tensor::zeros(&[rows, columns], backend)?)
    }

    /// Constructs a matrix filled with one value using the selected backend.
    pub fn filled(
        rows: usize,
        columns: usize,
        backend: Backend,
        value: T,
    ) -> Result<Self, MatrixError> {
        Self::from_tensor(Tensor::filled(&[rows, columns], backend, value)?)
    }

    /// Constructs a matrix from a coordinate function using the selected backend.
    pub fn from_fn<F>(
        rows: usize,
        columns: usize,
        backend: Backend,
        mut function: F,
    ) -> Result<Self, MatrixError>
    where
        F: FnMut(usize, usize) -> T,
    {
        Self::from_tensor(Tensor::from_fn(&[rows, columns], backend, |coordinates| {
            function(coordinates[0], coordinates[1])
        })?)
    }

    /// Constructs an identity matrix using the selected backend.
    pub fn identity(size: usize, backend: Backend) -> Result<Self, MatrixError> {
        Self::from_tensor(Tensor::identity(size, backend)?)
    }

    /// Returns the selected numerical backend.
    pub const fn backend(&self) -> Backend {
        self.tensor.backend()
    }

    /// Converts this matrix to the selected backend when necessary.
    pub fn set_backend(&mut self, backend: Backend) {
        self.tensor.set_backend(backend);
    }

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

    pub fn columns(&self) -> usize {
        self.tensor.shape()[1]
    }

    pub fn shape(&self) -> [usize; 2] {
        [self.rows(), self.columns()]
    }

    pub fn size(&self) -> usize {
        self.tensor.size()
    }

    pub fn get(&self, row: usize, column: usize) -> Result<T, MatrixError> {
        Ok(self.tensor.get(&[row, column])?)
    }

    pub fn set(&mut self, row: usize, column: usize, value: T) -> Result<(), MatrixError> {
        Ok(self.tensor.set(&[row, column], value)?)
    }

    /// Traverses every logical value in row-major coordinate order.
    ///
    /// # Complexity
    ///
    /// This is `O(rows * columns)` for both backends.
    pub fn values(&self) -> Values<'_, T> {
        self.tensor.values()
    }

    pub fn fill(&mut self, value: T) {
        self.tensor.fill(value);
    }

    /// Adds two matrices and preserves the receiver's backend.
    ///
    /// # Result backend
    ///
    /// The result has the same backend as `self`.
    pub fn add(&self, rhs: &Self) -> Result<Self, MatrixError> {
        Self::from_tensor(self.tensor.add(&rhs.tensor)?)
    }

    pub fn subtract(&self, rhs: &Self) -> Result<Self, MatrixError> {
        Self::from_tensor(self.tensor.subtract(&rhs.tensor)?)
    }

    pub fn multiply(&self, rhs: &Self) -> Result<Self, MatrixError> {
        Self::from_tensor(self.tensor.multiply(&rhs.tensor)?)
    }

    pub fn divide(&self, rhs: &Self) -> Result<Self, MatrixError> {
        Self::from_tensor(self.tensor.divide(&rhs.tensor)?)
    }

    pub fn add_into(&self, rhs: &Self, output: &mut Self) -> Result<(), MatrixError> {
        Ok(self.tensor.add_into(&rhs.tensor, &mut output.tensor)?)
    }

    pub fn subtract_into(&self, rhs: &Self, output: &mut Self) -> Result<(), MatrixError> {
        Ok(self.tensor.subtract_into(&rhs.tensor, &mut output.tensor)?)
    }

    pub fn multiply_into(&self, rhs: &Self, output: &mut Self) -> Result<(), MatrixError> {
        Ok(self.tensor.multiply_into(&rhs.tensor, &mut output.tensor)?)
    }

    pub fn divide_into(&self, rhs: &Self, output: &mut Self) -> Result<(), MatrixError> {
        Ok(self.tensor.divide_into(&rhs.tensor, &mut output.tensor)?)
    }

    pub fn scale(&self, scalar: T) -> Self {
        Self {
            tensor: self.tensor.scale(scalar),
        }
    }

    pub fn abs(&self) -> Self {
        Self {
            tensor: self.tensor.abs(),
        }
    }

    pub fn transpose(&self) -> Result<Self, MatrixError> {
        Self::from_tensor(self.tensor.transpose()?)
    }

    pub fn hermitian_transpose(&self) -> Result<Self, MatrixError> {
        Self::from_tensor(self.tensor.hermitian_transpose()?)
    }

    /// Multiplies two matrices and preserves the receiver's backend.
    ///
    /// # Result backend
    ///
    /// The result has the same backend as `self`.
    ///
    /// # Complexity
    ///
    /// The general kernel is `O(mkn)`. A sparse receiver can produce
    /// dense occupancy and dense-scale memory use.
    pub fn matmul(&self, rhs: &Self) -> Result<Self, MatrixError> {
        Self::from_tensor(self.tensor.matmul(&rhs.tensor)?)
    }

    pub fn trace(&self) -> T {
        (0..self.rows().min(self.columns())).fold(T::zero(), |sum, coordinate| {
            sum + self
                .tensor
                .get_flat_unchecked(coordinate * self.columns() + coordinate)
        })
    }

    pub fn max_abs_real(&self) -> T::Real
    where
        T::Real: PartialOrd,
    {
        self.values()
            .map(Scalar::abs_real)
            .fold(T::Real::zero(), |left, right| {
                match left.partial_cmp(&right) {
                    Some(Ordering::Less) => right,
                    Some(_) => left,
                    None => left + right,
                }
            })
    }

    pub fn mul_vector_into(&self, input: &[T], output: &mut [T]) -> Result<(), MatrixError> {
        if input.len() != self.columns() {
            return Err(MatrixError::InputLength {
                expected: self.columns(),
                actual: input.len(),
            });
        }
        if output.len() != self.rows() {
            return Err(MatrixError::OutputLength {
                expected: self.rows(),
                actual: output.len(),
            });
        }
        for (row, output_value) in output.iter_mut().enumerate() {
            *output_value =
                input
                    .iter()
                    .copied()
                    .enumerate()
                    .fold(T::zero(), |sum, (column, value)| {
                        sum + self
                            .tensor
                            .get_flat_unchecked(row * self.columns() + column)
                            * value
                    });
        }
        Ok(())
    }

    pub fn mul_vectors_into(&self, input: &[T], output: &mut [T]) -> Result<(), MatrixError> {
        if !input.len().is_multiple_of(self.columns()) {
            return Err(MatrixError::BatchInputLength {
                columns: self.columns(),
                actual: input.len(),
            });
        }
        let batch = input.len() / self.columns();
        let expected = batch
            .checked_mul(self.rows())
            .ok_or(TensorError::ShapeProductOverflow {
                shape: vec![batch, self.rows()],
            })?;
        if output.len() != expected {
            return Err(MatrixError::OutputLength {
                expected,
                actual: output.len(),
            });
        }
        for (input, output) in input
            .chunks_exact(self.columns())
            .zip(output.chunks_exact_mut(self.rows()))
        {
            self.mul_vector_into(input, output)?;
        }
        Ok(())
    }

    pub fn cast<U: Scalar>(&self) -> Result<Matrix<U>, ScalarCastError> {
        Ok(Matrix {
            tensor: self.tensor.cast()?,
        })
    }

    pub(crate) fn tensor(&self) -> &Tensor<T> {
        &self.tensor
    }

    pub(crate) fn tensor_mut(&mut self) -> &mut Tensor<T> {
        &mut self.tensor
    }

    fn from_tensor(tensor: Tensor<T>) -> Result<Self, MatrixError> {
        if tensor.rank() != 2 {
            return Err(TensorError::ExpectedRank {
                operation: "matrix construction",
                expected: 2,
                actual: tensor.rank(),
            }
            .into());
        }
        Ok(Self { tensor })
    }
}

impl<T> Serialize for Matrix<T>
where
    T: Scalar + Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.tensor.serialize(serializer)
    }
}

impl<'de, T> Deserialize<'de> for Matrix<T>
where
    T: Scalar + DeserializeOwned,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let tensor = Tensor::<T>::deserialize(deserializer)?;
        Self::from_tensor(tensor).map_err(serde::de::Error::custom)
    }
}