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
/*!
Generic front API for tensor storage backends.

`Tensor<T, B>` provides one user-facing type parameterized by backend marker `B`:
- `Dense`  -> contiguous dense storage
- `Sparse` -> hash-backed sparse storage

This facade delegates to existing backend implementations in `rank_n::dense` and
`rank_n::sparse` while exposing a consistent construction/access surface. The
element type is always constrained by `T: Scalar`, so tensor algorithms operate
on PiP scalar values rather than backend-specific primitive assumptions.
*/

use core::marker::PhantomData;

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

use super::{
    dense::Tensor as DenseStorage, sparse::Tensor as SparseStorage, tensor_trait::TensorTrait,
};

/// Dense backend marker for `Tensor<T, B>`.
#[derive(Debug, Clone, Copy, Default)]
pub struct Dense;

/// Sparse backend marker for `Tensor<T, B>`.
#[derive(Debug, Clone, Copy, Default)]
pub struct Sparse;

/// Backend type mapping for generic `Tensor`.
pub trait Backend<T: Scalar> {
    type Storage: TensorTrait<T>;
}

impl<T: Scalar> Backend<T> for Dense {
    type Storage = DenseStorage<T>;
}

impl<T: Scalar> Backend<T> for Sparse {
    type Storage = SparseStorage<T>;
}

/// Generic tensor facade.
#[derive(Debug, Clone)]
pub struct Tensor<T: Scalar, B: Backend<T> = Dense> {
    inner: B::Storage,
    _backend: PhantomData<B>,
}

impl<T: Scalar, B: Backend<T>> Tensor<T, B> {
    #[inline]
    /// Details:
    /// - Purpose: Wraps a backend-specific dense or sparse storage object in
    ///   the public `Tensor<T, B>` facade while preserving the backend marker.
    /// - Parameters:
    ///   - `inner` (`B::Storage`): Already-validated backend storage to expose
    ///     through the generic tensor API.
    pub(crate) fn from_storage(inner: B::Storage) -> Self {
        Self {
            inner,
            _backend: PhantomData,
        }
    }

    #[inline]
    /// Details:
    /// - Purpose: Gives internal IO and conversion code read-only access to
    ///   the backend storage without making storage details part of the public
    ///   end-user API.
    /// - Parameters:
    ///   - (none): Borrows the facade's backend storage.
    pub(crate) fn storage(&self) -> &B::Storage {
        &self.inner
    }

    #[inline]
    pub(crate) fn storage_mut(&mut self) -> &mut B::Storage {
        &mut self.inner
    }
}

impl<T: Scalar, B: Backend<T>> Tensor<T, B>
where
    B::Storage: TensorTrait<T>,
{
    #[inline]
    /// Details:
    /// - Purpose: Creates a tensor of the selected backend with the requested
    ///   shape and that backend's zero/default empty representation.
    /// - Parameters:
    ///   - `shape` (`&[usize]`): Non-empty list of positive axis lengths.
    pub fn empty(shape: &[usize]) -> Self {
        Self::from_storage(<B::Storage as TensorTrait<T>>::empty(shape))
    }

    #[inline]
    pub fn zeros(shape: &[usize]) -> Self {
        Self::empty(shape)
    }

    #[inline]
    /// Details:
    /// - Purpose: Returns the logical axis lengths shared by every backend
    ///   representation of this tensor.
    /// - Parameters:
    ///   - (none): Delegates to the backend storage shape.
    pub fn shape(&self) -> &[usize] {
        self.inner.shape()
    }

    #[inline]
    /// Tensor rank.
    pub fn rank(&self) -> usize {
        self.inner.rank()
    }

    #[inline]
    /// Logical dense size.
    pub fn size(&self) -> usize {
        self.inner.size()
    }

    #[inline]
    /// Details:
    /// - Purpose: Computes the scalar sum of all logical tensor entries using
    ///   the backend's native reduction semantics.
    /// - Parameters:
    ///   - (none): Reads all logical entries represented by this tensor.
    pub fn get_sum(&self) -> T {
        self.inner.get_sum()
    }

    #[inline]
    /// Sum of tensor values.
    pub fn sum(&self) -> T {
        self.inner.sum()
    }

    #[inline]
    /// Details:
    /// - Purpose: Reads a scalar at a multidimensional coordinate through the
    ///   backend's indexing rules; dense returns stored values and sparse
    ///   returns zero for implicit entries.
    /// - Parameters:
    ///   - `idx` (`&[isize]`): One signed coordinate per tensor axis.
    pub fn get(&self, idx: &[isize]) -> T
    where
        T: Copy,
    {
        self.inner.get(idx)
    }

    #[inline]
    pub fn get_mut(&mut self, idx: &[isize]) -> &mut T {
        self.inner.get_mut(idx)
    }

    #[inline]
    /// Details:
    /// - Purpose: Writes a scalar at a multidimensional coordinate through the
    ///   backend's update rules; sparse zero writes remove explicit storage.
    /// - Parameters:
    ///   - `idx` (`&[isize]`): One signed coordinate per tensor axis.
    ///   - `val` (`T`): Scalar value to store at that logical coordinate.
    pub fn set(&mut self, idx: &[isize], val: T) {
        self.inner.set(idx, val);
    }

    #[inline]
    pub fn fill(&mut self, value: T)
    where
        T: Copy + Send + Sync,
    {
        self.inner.fill(value);
    }

    #[inline]
    pub fn map<F>(&self, f: F) -> Self
    where
        T: Copy + Send + Sync,
        F: Fn(T) -> T + Sync + Send,
    {
        Self::from_storage(self.inner.map(f))
    }

    #[inline]
    pub fn map_in_place<F>(&mut self, f: F)
    where
        T: Copy + Send + Sync,
        F: Fn(T) -> T + Sync + Send,
    {
        self.inner.map_in_place(f);
    }

    #[inline]
    pub fn zip_with<RhsBackend, F>(&self, other: &Tensor<T, RhsBackend>, f: F) -> Self
    where
        RhsBackend: Backend<T>,
        RhsBackend::Storage: TensorTrait<T>,
        T: Copy + Send + Sync,
        F: Fn(T, T) -> T + Sync + Send,
    {
        Self::from_storage(self.inner.zip_with(&other.inner, f))
    }

    #[inline]
    pub fn conj(&self) -> Self
    where
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.conj())
    }

    #[inline]
    pub fn abs(&self) -> Self
    where
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.abs())
    }

    #[inline]
    pub fn norm_sqr(&self) -> Self
    where
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.norm_sqr())
    }

    #[inline]
    pub fn sqrt(&self) -> Self
    where
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.sqrt())
    }

    #[inline]
    pub fn scalar_mul(&self, scalar: T) -> Self
    where
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.scalar_mul(scalar))
    }

    #[inline]
    pub fn elem_mul<RhsBackend>(&self, other: &Tensor<T, RhsBackend>) -> Self
    where
        RhsBackend: Backend<T>,
        RhsBackend::Storage: TensorTrait<T>,
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.elem_mul(&other.inner))
    }

    #[inline]
    pub fn elem_div<RhsBackend>(&self, other: &Tensor<T, RhsBackend>) -> Self
    where
        RhsBackend: Backend<T>,
        RhsBackend::Storage: TensorTrait<T>,
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.elem_div(&other.inner))
    }

    #[inline]
    pub fn transpose(&self) -> Self
    where
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.transpose())
    }

    #[inline]
    pub fn hermitian_transpose(&self) -> Self
    where
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.hermitian_transpose())
    }

    #[inline]
    pub fn dot<RhsBackend>(&self, other: &Tensor<T, RhsBackend>) -> T
    where
        RhsBackend: Backend<T>,
        RhsBackend::Storage: TensorTrait<T>,
        T: Copy + Send + Sync,
    {
        self.inner.dot(&other.inner)
    }

    #[inline]
    pub fn hermitian_dot<RhsBackend>(&self, other: &Tensor<T, RhsBackend>) -> T
    where
        RhsBackend: Backend<T>,
        RhsBackend::Storage: TensorTrait<T>,
        T: Copy + Send + Sync,
    {
        self.inner.hermitian_dot(&other.inner)
    }

    #[inline]
    pub fn norm_sqr_real(&self) -> T::Real
    where
        T: Copy + Send + Sync,
        T::Real: Send + Sync,
    {
        self.inner.norm_sqr_real()
    }

    #[inline]
    pub fn norm(&self) -> T
    where
        T: Copy + Send + Sync,
        T::Real: Send + Sync,
    {
        self.inner.norm()
    }

    #[inline]
    pub fn cross<RhsBackend>(&self, other: &Tensor<T, RhsBackend>) -> Self
    where
        RhsBackend: Backend<T>,
        RhsBackend::Storage: TensorTrait<T>,
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.cross(&other.inner))
    }

    #[inline]
    pub fn wedge<RhsBackend>(&self, other: &Tensor<T, RhsBackend>) -> Self
    where
        RhsBackend: Backend<T>,
        RhsBackend::Storage: TensorTrait<T>,
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.wedge(&other.inner))
    }

    #[inline]
    pub fn matmul<RhsBackend>(&self, other: &Tensor<T, RhsBackend>) -> Self
    where
        RhsBackend: Backend<T>,
        RhsBackend::Storage: TensorTrait<T>,
        T: Copy + Send + Sync,
    {
        Self::from_storage(self.inner.matmul(&other.inner))
    }

    #[inline]
    /// Details:
    /// - Purpose: Delegates to the backend's terminal printer so users can
    ///   quickly inspect tensor shape and representative values.
    /// - Parameters:
    ///   - (none): Reads this tensor without modifying it.
    pub fn print(&self) {
        self.inner.print();
    }
}

impl<T: Scalar> Tensor<T, Dense> {
    #[inline]
    pub fn from_vec(shape: &[usize], data: Vec<T>) -> Self {
        Self::from_storage(DenseStorage::<T>::from_vec(shape, data))
    }

    pub fn from_fn<F>(shape: &[usize], mut f: F) -> Self
    where
        F: FnMut(&[isize]) -> T,
    {
        let mut out = Self::empty(shape);
        let rank = shape.len();
        for k in 0..out.size() {
            let mut rem = k;
            let mut idx = vec![0isize; rank];
            for axis in (0..rank).rev() {
                idx[axis] = (rem % shape[axis]) as isize;
                rem /= shape[axis];
            }
            out.set(&idx, f(&idx));
        }
        out
    }

    #[inline]
    pub fn cast_to<U: Scalar + Send + Sync>(&self) -> Tensor<U, Dense> {
        Tensor::<U, Dense>::from_storage(self.inner.cast_to::<U>())
    }

    #[inline]
    pub fn try_cast_to<U: Scalar>(&self) -> Result<Tensor<U, Dense>, ScalarCastError> {
        self.inner
            .try_cast_to::<U>()
            .map(Tensor::<U, Dense>::from_storage)
    }

    #[inline]
    /// Details:
    /// - Purpose: Converts a dense facade tensor into a sparse facade tensor by
    ///   preserving shape and explicitly storing only nonzero entries.
    /// - Parameters:
    ///   - (none): Reads this dense tensor.
    pub fn to_sparse(&self) -> Tensor<T, Sparse> {
        Tensor::<T, Sparse>::from_storage(self.inner.to_sparse())
    }

    #[inline]
    /// Details:
    /// - Purpose: Builds a dense facade tensor by materializing every implicit
    ///   sparse zero into a full dense buffer.
    /// - Parameters:
    ///   - `s` (`&Tensor<T, Sparse>`): Sparse facade tensor to densify.
    pub fn from_sparse(s: &Tensor<T, Sparse>) -> Self {
        Self::from_storage(DenseStorage::<T>::from_sparse(&s.inner))
    }
}

impl<T: Scalar> Tensor<T, Sparse> {
    #[inline]
    pub fn from_triplets(
        shape: Vec<usize>,
        triplets: impl IntoIterator<Item = (Vec<usize>, T)>,
    ) -> Self {
        Self::from_storage(SparseStorage::<T>::from_triplets(shape, triplets))
    }

    #[inline]
    pub fn cast_to<U: Scalar + Send + Sync>(&self) -> Tensor<U, Sparse> {
        Tensor::<U, Sparse>::from_storage(self.inner.cast_to::<U>())
    }

    #[inline]
    pub fn try_cast_to<U: Scalar>(&self) -> Result<Tensor<U, Sparse>, ScalarCastError> {
        self.inner
            .try_cast_to::<U>()
            .map(Tensor::<U, Sparse>::from_storage)
    }

    #[inline]
    /// Details:
    /// - Purpose: Returns how many entries are explicitly stored by the sparse
    ///   backend; implicit zeros are excluded.
    /// - Parameters:
    ///   - (none): Reads the sparse backend's storage map length.
    pub fn nnz(&self) -> usize {
        self.inner.nnz()
    }

    #[inline]
    /// Details:
    /// - Purpose: Returns the number of logical positions in the sparse tensor's
    ///   dense domain, equal to the product of shape axes.
    /// - Parameters:
    ///   - (none): Uses the sparse tensor's shape metadata.
    pub fn len_dense(&self) -> usize {
        self.inner.len_dense()
    }

    #[inline]
    /// Details:
    /// - Purpose: Converts a sparse facade tensor into a dense facade tensor by
    ///   allocating the full dense buffer and filling implicit zeros.
    /// - Parameters:
    ///   - (none): Reads this sparse tensor.
    pub fn to_dense(&self) -> Tensor<T, Dense> {
        Tensor::<T, Dense>::from_storage(self.inner.to_dense())
    }

    #[inline]
    /// Details:
    /// - Purpose: Builds a sparse facade tensor by scanning a dense tensor and
    ///   keeping only entries that are not `T::zero()`.
    /// - Parameters:
    ///   - `d` (`&Tensor<T, Dense>`): Dense facade tensor to compress.
    pub fn from_dense(d: &Tensor<T, Dense>) -> Self {
        Self::from_storage(SparseStorage::<T>::from_dense(&d.inner))
    }
}