spenso 0.5.5

A tensor (n-dim array) network, iterating, and contraction (using automatic abstract index matching) library.
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! Iterators for specific tensor types
//!
//! This module provides iterators specific to different tensor implementations,
//! including dense, sparse, and data tensors.

use std::collections::hash_map;

use crate::{
    algebra::algebraic_traits::RefZero,
    algebra::upgrading_arithmetic::{FallibleAddAssign, FallibleSubAssign},
    contraction::ContractableWith,
    structure::{
        concrete_index::{ConcreteIndex, ExpandedIndex, FlatIndex},
        TensorStructure,
    },
    tensors::data::{DataTensor, DenseTensor, GetTensorData, SparseTensor},
};

use super::traits::IteratableTensor;

/// Iterator over all the elements of a sparse tensor
///
/// Returns the expanded indices and the element at that index
pub struct SparseTensorIterator<'a, T, N> {
    iter: hash_map::Iter<'a, FlatIndex, T>,
    structure: &'a N,
}

impl<'a, T, N> SparseTensorIterator<'a, T, N> {
    /// Creates a new sparse tensor iterator
    ///
    /// # Arguments
    ///
    /// * `tensor` - The tensor to iterate over
    pub fn new(tensor: &'a SparseTensor<T, N>) -> Self {
        SparseTensorIterator {
            iter: tensor.elements.iter(),
            structure: &tensor.structure,
        }
    }
}

impl<'a, T, N> Iterator for SparseTensorIterator<'a, T, N>
where
    N: TensorStructure,
{
    type Item = (ExpandedIndex, &'a T);

    fn next(&mut self) -> Option<Self::Item> {
        if let Some((k, v)) = self.iter.next() {
            let indices = self.structure.expanded_index(*k).unwrap();
            Some((indices, v))
        } else {
            None
        }
    }
}

/// Iterator over all the elements of a sparse tensor
///
/// Returns the flat index and the element at that index
pub struct SparseTensorLinearIterator<'a, T> {
    iter: hash_map::Iter<'a, FlatIndex, T>,
}

impl<'a, T> SparseTensorLinearIterator<'a, T> {
    /// Creates a new sparse tensor linear iterator
    ///
    /// # Arguments
    ///
    /// * `tensor` - The tensor to iterate over
    pub fn new<N>(tensor: &'a SparseTensor<T, N>) -> Self {
        SparseTensorLinearIterator {
            iter: tensor.elements.iter(),
        }
    }
}

impl<'a, T> Iterator for SparseTensorLinearIterator<'a, T> {
    type Item = (FlatIndex, &'a T);

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|(k, v)| (*k, v))
    }
}

/// Iterator over all but two indices of a sparse tensor, where the two indices are traced
///
/// The iterator next returns the value of the trace at the current indices, and the current indices
pub struct SparseTensorTraceIterator<'a, T, I> {
    tensor: &'a SparseTensor<T, I>,
    trace_indices: [usize; 2],
    current_indices: Vec<ConcreteIndex>,
    done: bool,
}

impl<'a, T, I> SparseTensorTraceIterator<'a, T, I>
where
    I: TensorStructure,
{
    /// Create a new trace iterator
    ///
    /// # Arguments
    ///
    /// * `tensor` - A reference to the tensor
    /// * `trace_indices` - The indices to be traced
    ///
    /// # Panics
    ///
    /// Panics if the trace indices do not point to the same dimension
    pub fn new(tensor: &'a SparseTensor<T, I>, trace_indices: [usize; 2]) -> Self {
        //trace positions must point to the same dimension
        assert!(
            trace_indices
                .iter()
                .map(|&pos| tensor.get_rep(pos).unwrap())
                .collect::<Vec<_>>()
                .iter()
                .all(|&sig| sig == tensor.get_rep(trace_indices[0]).unwrap()),
            "Trace indices must point to the same dimension"
        );
        SparseTensorTraceIterator {
            tensor,
            trace_indices,
            current_indices: vec![0; tensor.order()],
            done: false,
        }
    }

    /// Increments the current indices, skipping trace indices
    ///
    /// Returns true if incrementation succeeded, false if we've reached the end
    fn increment_indices(&mut self) -> bool {
        for (i, index) in self
            .current_indices
            .iter_mut()
            .enumerate()
            .rev()
            .filter(|(pos, _)| !self.trace_indices.contains(pos))
        // Filter out the trace indices
        {
            *index += 1;
            // If the index goes beyond the shape boundary, wrap around to 0
            if index >= &mut usize::try_from(self.tensor.shape()[i]).unwrap() {
                *index = 0;
                continue; // carry over to the next dimension
            }
            return true; // We've successfully found the next combination
        }
        false // No more combinations left
    }
}

impl<T, I> Iterator for SparseTensorTraceIterator<'_, T, I>
where
    T: ContractableWith<T> + FallibleAddAssign<T> + FallibleSubAssign<T> + Clone + RefZero,
    I: TensorStructure + Clone,
{
    type Item = (Vec<ConcreteIndex>, T);
    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        let trace_dimension = self.tensor.get_rep(self.trace_indices[0]).unwrap();
        let trace_sign = trace_dimension.negative().unwrap();
        let mut iter = trace_sign.iter().enumerate();
        let mut indices = self.current_indices.clone();
        let (i, mut sign) = iter.next().unwrap(); //First element (to eliminate the need for default)

        indices[self.trace_indices[0]] = i;
        indices[self.trace_indices[1]] = i;

        // Data might not exist at that concrete index usize, we advance it till it does, and if not we skip
        while self.tensor.is_empty_at_expanded(&indices) {
            let Some((i, signint)) = iter.next() else {
                self.done = !self.increment_indices();
                return self.next(); // skip
            };
            indices[self.trace_indices[0]] = i;
            indices[self.trace_indices[1]] = i;
            sign = signint;
        }

        let value = self.tensor.get_ref(&indices).unwrap(); //Should now be safe to unwrap
        let zero = value.ref_zero();

        let mut trace = if *sign {
            let mut zero = zero.clone();
            zero.sub_assign_fallible(value);
            zero
        } else {
            value.clone()
        };

        for (i, sign) in iter {
            indices[self.trace_indices[0]] = i;
            indices[self.trace_indices[1]] = i;
            if let Ok(value) = self.tensor.get_ref(&indices) {
                if *sign {
                    trace.sub_assign_fallible(value);
                } else {
                    trace.add_assign_fallible(value);
                }
            }
        }

        //make a vector without the trace indices
        let trace_indices: Vec<ConcreteIndex> = self
            .current_indices
            .clone()
            .into_iter()
            .enumerate()
            .filter(|&(i, _)| !self.trace_indices.contains(&i))
            .map(|(_, x)| x)
            .collect();

        self.done = !self.increment_indices();

        Some((trace_indices, trace))
    }
}

impl<T, S: TensorStructure> SparseTensor<T, S> {
    /// Creates an iterator that traces over two indices
    ///
    /// # Arguments
    ///
    /// * `trace_indices` - The indices to trace over
    pub fn iter_trace(&self, trace_indices: [usize; 2]) -> SparseTensorTraceIterator<'_, T, S> {
        SparseTensorTraceIterator::new(self, trace_indices)
    }
}

/// Iterator over all the elements of a dense tensor
///
/// Returns the expanded indices and the element at that index
pub struct DenseTensorIterator<'a, T, I> {
    tensor: &'a DenseTensor<T, I>,
    current_flat_index: FlatIndex,
}

impl<'a, T, I> DenseTensorIterator<'a, T, I> {
    /// Create a new dense tensor iterator
    ///
    /// # Arguments
    ///
    /// * `tensor` - A reference to the tensor
    pub fn new(tensor: &'a DenseTensor<T, I>) -> Self {
        DenseTensorIterator {
            tensor,
            current_flat_index: 0.into(),
        }
    }
}

impl<'a, T, I> Iterator for DenseTensorIterator<'a, T, I>
where
    I: TensorStructure,
{
    type Item = (ExpandedIndex, &'a T);

    fn next(&mut self) -> Option<Self::Item> {
        if let Ok(indices) = self.tensor.expanded_index(self.current_flat_index) {
            let value = self.tensor.get_ref_linear(self.current_flat_index).unwrap();

            self.current_flat_index += 1.into();

            Some((indices, value))
        } else {
            None
        }
    }
}

/// Iterator over all the elements of a dense tensor
///
/// Returns the flat index and the element at that index
pub struct DenseTensorLinearIterator<'a, T, I> {
    tensor: &'a DenseTensor<T, I>,
    current_flat_index: FlatIndex,
}

impl<'a, T, I> DenseTensorLinearIterator<'a, T, I> {
    /// Creates a new dense tensor linear iterator
    ///
    /// # Arguments
    ///
    /// * `tensor` - The tensor to iterate over
    pub fn new(tensor: &'a DenseTensor<T, I>) -> Self {
        DenseTensorLinearIterator {
            tensor,
            current_flat_index: 0.into(),
        }
    }
}

impl<'a, T, I> Iterator for DenseTensorLinearIterator<'a, T, I>
where
    I: TensorStructure,
{
    type Item = (FlatIndex, &'a T);

    fn next(&mut self) -> Option<Self::Item> {
        let value = self.tensor.get_ref_linear(self.current_flat_index)?;
        let index = self.current_flat_index;
        self.current_flat_index += 1.into();
        Some((index, value))
    }
}

impl<'a, T, I> IntoIterator for &'a DenseTensor<T, I>
where
    I: TensorStructure,
{
    type Item = (ExpandedIndex, &'a T);
    type IntoIter = DenseTensorIterator<'a, T, I>;

    fn into_iter(self) -> Self::IntoIter {
        DenseTensorIterator::new(self)
    }
}

/// An consuming iterator over the elements of a dense tensor
///
/// Returns the expanded indices and the element at that index
pub struct DenseTensorIntoIterator<T, I> {
    tensor: DenseTensor<T, I>,
    current_flat_index: FlatIndex,
}

impl<T, I> DenseTensorIntoIterator<T, I> {
    /// Creates a new consuming iterator over a dense tensor
    ///
    /// # Arguments
    ///
    /// * `tensor` - The tensor to consume
    pub fn new(tensor: DenseTensor<T, I>) -> Self {
        DenseTensorIntoIterator {
            tensor,
            current_flat_index: 0.into(),
        }
    }
}

impl<T, I> Iterator for DenseTensorIntoIterator<T, I>
where
    I: TensorStructure,
{
    type Item = (ExpandedIndex, T);

    fn next(&mut self) -> Option<Self::Item> {
        if let Ok(indices) = self.tensor.expanded_index(self.current_flat_index) {
            let indices = indices.clone();
            let value = self.tensor.data.remove(self.current_flat_index.into());

            self.current_flat_index += 1.into();

            Some((indices, value))
        } else {
            None
        }
    }
}

impl<T, I> IntoIterator for DenseTensor<T, I>
where
    I: TensorStructure,
{
    type Item = (ExpandedIndex, T);
    type IntoIter = DenseTensorIntoIterator<T, I>;

    fn into_iter(self) -> Self::IntoIter {
        DenseTensorIntoIterator::new(self)
    }
}

/// Iterator over all indices of a dense tensor, keeping two indices fixed and tracing over them
///
/// The next method returns the value of the trace at the current indices, and the current indices
pub struct DenseTensorTraceIterator<'a, T, I> {
    tensor: &'a DenseTensor<T, I>,
    trace_indices: [usize; 2],
    current_indices: Vec<ConcreteIndex>,
    done: bool,
}

impl<'a, T, I> DenseTensorTraceIterator<'a, T, I>
where
    I: TensorStructure,
{
    /// Create a new trace iterator
    ///
    /// # Arguments
    ///
    /// * `tensor` - A reference to the tensor
    /// * `trace_indices` - The indices to be traced
    ///
    pub fn new(tensor: &'a DenseTensor<T, I>, trace_indices: [usize; 2]) -> Self {
        assert!(trace_indices.len() >= 2, "Invalid trace indices");
        //trace positions must point to the same dimension
        assert!(
            trace_indices
                .iter()
                .map(|&pos| tensor.get_rep(pos))
                .collect::<Vec<_>>()
                .iter()
                .all(|&sig| sig == tensor.get_rep(trace_indices[0])),
            "Trace indices must point to the same dimension"
        );
        DenseTensorTraceIterator {
            tensor,
            trace_indices,
            current_indices: vec![0; tensor.order()],
            done: false,
        }
    }

    /// Increments the current indices, skipping trace indices
    ///
    /// Returns true if incrementation succeeded, false if we've reached the end
    fn increment_indices(&mut self) -> bool {
        for (i, index) in self
            .current_indices
            .iter_mut()
            .enumerate()
            .rev()
            .filter(|(pos, _)| !self.trace_indices.contains(pos))
        {
            *index += 1;
            // If the index goes beyond the shape boundary, wrap around to 0
            if index >= &mut usize::try_from(self.tensor.shape()[i]).unwrap() {
                *index = 0;
                continue; // carry over to the next dimension
            }
            return true; // We've successfully found the next combination
        }
        false // No more combinations left
    }
}

impl<T, I> Iterator for DenseTensorTraceIterator<'_, T, I>
where
    T: ContractableWith<T, Out = T> + FallibleAddAssign<T> + FallibleSubAssign<T> + Clone + RefZero,
    I: TensorStructure,
{
    type Item = (Vec<ConcreteIndex>, T);
    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        let trace_dimension = self.tensor.get_rep(self.trace_indices[0]).unwrap();
        let trace_sign = trace_dimension.negative().unwrap();

        let mut iter = trace_sign.iter().enumerate();
        let mut indices = self.current_indices.clone();
        let (_, sign) = iter.next().unwrap(); //First sign

        for pos in self.trace_indices {
            indices[pos] = 0;
        }

        let value = self.tensor.get_ref(&indices).unwrap();
        let zero = value.ref_zero();

        let mut trace = if *sign {
            let mut zero = zero.clone();
            zero.sub_assign_fallible(value);
            zero
        } else {
            value.clone()
        };

        for (i, sign) in iter {
            for pos in self.trace_indices {
                indices[pos] = i;
            }

            if let Ok(value) = self.tensor.get_ref(&indices) {
                if *sign {
                    trace.sub_assign_fallible(value);
                } else {
                    trace.add_assign_fallible(value);
                }
            }
        }

        //make a vector without the trace indices
        let trace_indices: Vec<ConcreteIndex> = self
            .current_indices
            .clone()
            .into_iter()
            .enumerate()
            .filter(|&(i, _)| !self.trace_indices.contains(&i))
            .map(|(_, x)| x)
            .collect();

        self.done = !self.increment_indices();

        Some((trace_indices, trace))
    }
}

impl<T, I> DenseTensor<T, I>
where
    I: TensorStructure,
{
    /// Creates an iterator that traces over two indices
    ///
    /// # Arguments
    ///
    /// * `trace_indices` - The indices to trace over
    pub fn iter_trace(&self, trace_indices: [usize; 2]) -> DenseTensorTraceIterator<'_, T, I> {
        DenseTensorTraceIterator::new(self, trace_indices)
    }
}

/// Linear iterator that works with both dense and sparse tensors
///
/// Returns flat indices and elements.
pub enum DataTensorLinearIterator<'a, T, S> {
    /// Iterator for dense tensors
    Dense(DenseTensorLinearIterator<'a, T, S>),
    /// Iterator for sparse tensors
    Sparse(SparseTensorLinearIterator<'a, T>),
}

impl<'a, T, S> From<DenseTensorLinearIterator<'a, T, S>> for DataTensorLinearIterator<'a, T, S> {
    fn from(value: DenseTensorLinearIterator<'a, T, S>) -> Self {
        DataTensorLinearIterator::Dense(value)
    }
}

impl<'a, T, S> From<SparseTensorLinearIterator<'a, T>> for DataTensorLinearIterator<'a, T, S> {
    fn from(value: SparseTensorLinearIterator<'a, T>) -> Self {
        DataTensorLinearIterator::Sparse(value)
    }
}

impl<'a, T, S: TensorStructure> Iterator for DataTensorLinearIterator<'a, T, S> {
    type Item = (FlatIndex, &'a T);

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            DataTensorLinearIterator::Dense(iter) => iter.next(),
            DataTensorLinearIterator::Sparse(iter) => iter.next(),
        }
    }
}

/// Expanded iterator that works with both dense and sparse tensors
///
/// Returns expanded indices and elements.
pub enum DataTensorExpandedIterator<'a, T, S> {
    /// Iterator for dense tensors
    Dense(DenseTensorIterator<'a, T, S>),
    /// Iterator for sparse tensors
    Sparse(SparseTensorIterator<'a, T, S>),
}

impl<'a, T, S> From<DenseTensorIterator<'a, T, S>> for DataTensorExpandedIterator<'a, T, S> {
    fn from(value: DenseTensorIterator<'a, T, S>) -> Self {
        DataTensorExpandedIterator::Dense(value)
    }
}

impl<'a, T, S> From<SparseTensorIterator<'a, T, S>> for DataTensorExpandedIterator<'a, T, S> {
    fn from(value: SparseTensorIterator<'a, T, S>) -> Self {
        DataTensorExpandedIterator::Sparse(value)
    }
}

impl<'a, T, S: TensorStructure> Iterator for DataTensorExpandedIterator<'a, T, S> {
    type Item = (ExpandedIndex, &'a T);

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            DataTensorExpandedIterator::Dense(iter) => iter.next(),
            DataTensorExpandedIterator::Sparse(iter) => iter.next(),
        }
    }
}

impl<T: Clone, S: TensorStructure> IteratableTensor for DataTensor<T, S> {
    type Data<'a>
        = &'a T
    where
        Self: 'a;

    fn iter_expanded(&self) -> impl Iterator<Item = (ExpandedIndex, Self::Data<'_>)> {
        match self {
            DataTensor::Dense(tensor) => {
                DataTensorExpandedIterator::Dense(DenseTensorIterator::new(tensor))
            }
            DataTensor::Sparse(tensor) => {
                DataTensorExpandedIterator::Sparse(SparseTensorIterator::new(tensor))
            }
        }
    }

    fn iter_flat(&self) -> impl Iterator<Item = (FlatIndex, Self::Data<'_>)> {
        match self {
            DataTensor::Dense(tensor) => {
                DataTensorLinearIterator::Dense(DenseTensorLinearIterator::new(tensor))
            }
            DataTensor::Sparse(tensor) => {
                DataTensorLinearIterator::Sparse(SparseTensorLinearIterator::new(tensor))
            }
        }
    }
}

impl<T, S: TensorStructure> IteratableTensor for SparseTensor<T, S> {
    type Data<'a>
        = &'a T
    where
        Self: 'a;

    fn iter_expanded(&self) -> impl Iterator<Item = (ExpandedIndex, Self::Data<'_>)> {
        SparseTensorIterator::new(self)
    }

    fn iter_flat(&self) -> impl Iterator<Item = (FlatIndex, Self::Data<'_>)> {
        SparseTensorLinearIterator::new(self)
    }
}

impl<T, S> IteratableTensor for DenseTensor<T, S>
where
    S: TensorStructure,
{
    type Data<'a>
        = &'a T
    where
        Self: 'a;

    fn iter_expanded(&self) -> impl Iterator<Item = (ExpandedIndex, &T)> {
        DenseTensorIterator::new(self)
    }

    fn iter_flat(&self) -> impl Iterator<Item = (FlatIndex, &T)> {
        DenseTensorLinearIterator::new(self)
    }
}

/// An iterator over all indices of a tensor structure
///
/// Returns expanded indices
pub struct TensorStructureIndexIterator<'a, I: TensorStructure> {
    structure: &'a I,
    current_flat_index: FlatIndex,
}

impl<I: TensorStructure> Iterator for TensorStructureIndexIterator<'_, I> {
    type Item = ExpandedIndex;
    fn next(&mut self) -> Option<Self::Item> {
        if let Ok(indices) = self.structure.expanded_index(self.current_flat_index) {
            self.current_flat_index += 1.into();

            Some(indices)
        } else {
            None
        }
    }
}

impl<'a, I: TensorStructure> TensorStructureIndexIterator<'a, I> {
    /// Creates a new tensor structure index iterator
    ///
    /// # Arguments
    ///
    /// * `structure` - The tensor structure to iterate over
    #[must_use]
    pub fn new(structure: &'a I) -> Self {
        TensorStructureIndexIterator {
            structure,
            current_flat_index: 0.into(),
        }
    }
}