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
//! High-level fiber iterators for tensor traversal
//!
//! This module contains iterators that build on the core iterators to provide
//! high-level fiber iteration capabilities for various tensor types.

use gat_lending_iterator::LendingIterator;
use linnet::permutation::Permutation;
use std::fmt::Debug;

use crate::{
    structure::{representation::LibraryRep, slot::IsAbstractSlot, TensorStructure},
    tensors::data::{DenseTensor, GetTensorData, SparseTensor},
};

use super::{
    core_iterators::CoreFlatFiberIterator,
    fiber::{Fiber, FiberClass, FiberMut},
    traits::ResetableIterator,
    FiberIteratorItem, IteratesAlongFibers, IteratesAlongPermutedFibers,
};

/// Iterator for traversing tensor fibers
///
/// This high-level iterator uses a core iterator to traverse fibers in tensors,
/// returning references to tensor elements at each position.
#[derive(Debug)]
pub struct FiberIterator<
    'a,
    S: TensorStructure,
    I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R>,
> {
    /// The fiber being iterated
    pub fiber: Fiber<'a, S>,
    /// The underlying core iterator
    pub iter: I,
    /// Number of indices skipped
    pub skipped: usize,
}

impl<S: TensorStructure, I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R> + Clone> Clone
    for FiberIterator<'_, S, I>
{
    fn clone(&self) -> Self {
        FiberIterator {
            fiber: self.fiber.clone(),
            iter: self.iter.clone(),
            skipped: self.skipped,
        }
    }
}

impl<'a, S: TensorStructure, I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R>>
    FiberIterator<'a, S, I>
{
    /// Creates a new fiber iterator
    ///
    /// # Arguments
    ///
    /// * `fiber` - The fiber to iterate over
    /// * `conj` - Whether to use conjugate iteration
    pub fn new(fiber: Fiber<'a, S>, conj: bool) -> Self {
        FiberIterator {
            iter: I::new(&fiber, conj),
            fiber,
            skipped: 0,
        }
    }

    /// Resets the iterator to its initial state
    pub fn reset(&mut self) {
        self.iter.reset();
        self.skipped = 0;
    }

    /// Shifts the iterator by the given amount
    ///
    /// # Arguments
    ///
    /// * `shift` - The amount to shift by
    pub fn shift(&mut self, shift: usize) {
        self.reset();
        self.iter.shift(shift);
    }
}

impl<'a, S: TensorStructure, I: IteratesAlongPermutedFibers<<S::Slot as IsAbstractSlot>::R>>
    FiberIterator<'a, S, I>
{
    /// Creates a new fiber iterator with a permutation
    ///
    /// # Arguments
    ///
    /// * `fiber` - The fiber to iterate over
    /// * `permutation` - The permutation to apply
    /// * `conj` - Whether to use conjugate iteration
    pub fn new_permuted(fiber: Fiber<'a, S>, permutation: Permutation, conj: bool) -> Self {
        FiberIterator {
            iter: I::new_permuted(&fiber, conj, permutation),
            fiber,
            skipped: 0,
        }
    }
}

impl<I: IteratesAlongFibers<LibraryRep>> Iterator
    for FiberIterator<'_, crate::structure::OrderedStructure, I>
{
    type Item = I::Item;
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

impl<
        'a,
        I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R, Item = It>,
        S: TensorStructure,
        T,
        It,
    > Iterator for FiberIterator<'a, DenseTensor<T, S>, I>
where
    It: FiberIteratorItem,
{
    type Item = (&'a T, It::OtherData);
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|x| {
            // println!(
            //     "DenseTensor: flat_idx: {}, size: {:?}",
            //     x.flat_idx(),
            //     self.fiber.structure.size()
            // );
            if let Some(t) = self.fiber.structure.get_ref_linear(x.flat_idx()) {
                (t, x.other_data())
            } else {
                panic!(
                    "DenseTensor: Out of bounds {} {}",
                    x.flat_idx(),
                    self.fiber.structure.size().unwrap()
                )
            }
        })
    }
}

impl<
        'a,
        I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R, Item = It>,
        S: TensorStructure,
        T,
        It,
    > Iterator for FiberIterator<'a, SparseTensor<T, S>, I>
where
    It: FiberIteratorItem,
{
    type Item = (&'a T, usize, It::OtherData);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(i) = self.iter.next() {
            if let Some(t) = self.fiber.structure.get_ref_linear(i.flat_idx()) {
                let skipped = self.skipped;
                self.skipped = 0;
                return Some((t, skipped, i.other_data()));
            } else {
                self.skipped += 1;
                return self.next();
            }
        }
        None
    }
}

/// Mutable iterator for traversing tensor fibers
///
/// Similar to `FiberIterator` but returns mutable references to tensor elements.
pub struct MutFiberIterator<
    'a,
    S: TensorStructure,
    I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R>,
> {
    /// The underlying core iterator
    iter: I,
    /// The fiber being iterated
    fiber: FiberMut<'a, S>,
    /// Number of indices skipped
    skipped: usize,
}

impl<
        I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R, Item = It>,
        S: TensorStructure,
        T,
        It,
    > LendingIterator for MutFiberIterator<'_, SparseTensor<T, S>, I>
where
    It: FiberIteratorItem,
{
    type Item<'r>
        = (&'r mut T, usize, It::OtherData)
    where
        Self: 'r;
    fn next(&mut self) -> Option<Self::Item<'_>> {
        let flat = self.iter.next()?;
        if self.fiber.structure.is_empty_at_flat(flat.flat_idx()) {
            let skipped = self.skipped;
            self.skipped = 0;
            Some((
                self.fiber
                    .structure
                    .get_mut_linear(flat.flat_idx())
                    .unwrap(),
                skipped,
                flat.other_data(),
            ))
        } else {
            self.skipped += 1;
            self.next()
        }
    }
}

impl<
        I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R, Item = It>,
        S: TensorStructure,
        T,
        It,
    > LendingIterator for MutFiberIterator<'_, DenseTensor<T, S>, I>
where
    It: FiberIteratorItem,
{
    type Item<'r>
        = (&'r mut T, It::OtherData)
    where
        Self: 'r;
    fn next(&mut self) -> Option<Self::Item<'_>> {
        self.iter.next().map(|x| {
            (
                self.fiber.structure.get_mut_linear(x.flat_idx()).unwrap(),
                x.other_data(),
            )
        })
    }
}

impl<'a, S: TensorStructure, I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R>>
    MutFiberIterator<'a, S, I>
{
    /// Creates a new mutable fiber iterator
    ///
    /// # Arguments
    ///
    /// * `fiber` - The fiber to iterate over
    /// * `conj` - Whether to use conjugate iteration
    pub fn new(fiber: FiberMut<'a, S>, conj: bool) -> Self {
        MutFiberIterator {
            iter: I::new(&fiber, conj),
            fiber,
            skipped: 0,
        }
    }

    /// Resets the iterator to its initial state
    pub fn reset(&mut self) {
        self.iter.reset();
        self.skipped = 0;
    }

    /// Shifts the iterator by the given amount
    ///
    /// # Arguments
    ///
    /// * `shift` - The amount to shift by
    pub fn shift(&mut self, shift: usize) {
        self.iter.shift(shift);
    }
}

impl<'a, S: TensorStructure, I: IteratesAlongPermutedFibers<<S::Slot as IsAbstractSlot>::R>>
    MutFiberIterator<'a, S, I>
{
    /// Creates a new mutable fiber iterator with a permutation
    ///
    /// # Arguments
    ///
    /// * `fiber` - The fiber to iterate over
    /// * `permutation` - The permutation to apply
    /// * `conj` - Whether to use conjugate iteration
    pub fn new_permuted(fiber: FiberMut<'a, S>, permutation: Permutation, conj: bool) -> Self {
        MutFiberIterator {
            iter: I::new_permuted(&fiber, conj, permutation),
            fiber,
            skipped: 0,
        }
    }
}

/// Iterator for traversing fiber classes
///
/// Iterates over all fibers in a fiber class, returning an iterator for each fiber.
pub struct FiberClassIterator<
    'b,
    S: TensorStructure,
    I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R> = CoreFlatFiberIterator,
> {
    /// Iterator over fibers within the class
    pub fiber_iter: FiberIterator<'b, S, I>,
    /// Iterator over indices of fibers in the class
    pub class_iter: CoreFlatFiberIterator,
}

impl<'b, N: TensorStructure> FiberClassIterator<'b, N, CoreFlatFiberIterator> {
    /// Creates a new fiber class iterator
    ///
    /// # Arguments
    ///
    /// * `class` - The fiber class to iterate over
    pub fn new(class: FiberClass<'b, N>) -> Self {
        let (iter, iter_conj) = CoreFlatFiberIterator::new_paired_conjugates(&class);

        let fiber = FiberIterator {
            fiber: class.into(),
            iter,
            skipped: 0,
        };

        FiberClassIterator {
            fiber_iter: fiber,
            class_iter: iter_conj,
        }
    }
}

impl<N: TensorStructure, I: IteratesAlongFibers<<N::Slot as IsAbstractSlot>::R>>
    FiberClassIterator<'_, N, I>
{
    /// Resets the iterator to its initial state
    pub fn reset(&mut self) {
        self.class_iter.reset();
        self.fiber_iter.reset();
        self.fiber_iter.shift(0);
    }
}

impl<'b, N: TensorStructure, I: IteratesAlongPermutedFibers<<N::Slot as IsAbstractSlot>::R>>
    FiberClassIterator<'b, N, I>
{
    /// Creates a new fiber class iterator with a permutation
    ///
    /// # Arguments
    ///
    /// * `class` - The fiber class to iterate over
    /// * `permutation` - The permutation to apply
    pub fn new_permuted(class: FiberClass<'b, N>, permutation: Permutation) -> Self {
        let iter = CoreFlatFiberIterator::new(&class, false);

        let fiber = FiberIterator::new_permuted(class.into(), permutation, false);

        FiberClassIterator {
            fiber_iter: fiber,
            class_iter: iter,
        }
    }
}

impl<
        'a,
        S: TensorStructure + 'a,
        I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R> + Clone + Debug,
    > Iterator for FiberClassIterator<'a, S, I>
{
    type Item = FiberIterator<'a, S, I>;

    fn next(&mut self) -> Option<Self::Item> {
        let shift = self.class_iter.next()?;
        self.fiber_iter.reset();
        self.fiber_iter.shift(shift.into());
        Some(self.fiber_iter.clone())
    }
}

impl<'a, S: TensorStructure + 'a, I: IteratesAlongFibers<<S::Slot as IsAbstractSlot>::R>>
    LendingIterator for FiberClassIterator<'a, S, I>
{
    type Item<'r>
        = &'r mut FiberIterator<'a, S, I>
    where
        Self: 'r;

    fn next(&mut self) -> Option<Self::Item<'_>> {
        let shift = self.class_iter.next()?;
        self.fiber_iter.reset();
        self.fiber_iter.shift(shift.into());
        Some(&mut self.fiber_iter)
    }
}

#[cfg(test)]
mod tests {

    use crate::structure::{
        representation::{Euclidean, RepName},
        OrderedStructure, PermutedStructure,
    };

    use super::*;

    #[test]
    fn weaved_iterator() {
        let strct: DenseTensor<u32, OrderedStructure<Euclidean>> = DenseTensor::zero(
            PermutedStructure::from_iter([
                Euclidean {}.new_slot(4, 1),
                Euclidean {}.new_slot(4, 2),
                Euclidean {}.new_slot(4, 3),
                Euclidean {}.new_slot(4, 4),
            ])
            .structure,
        );

        let fiber_spec = [true, false, true, false];
        let self_fiber_class = Fiber::from(fiber_spec.as_slice(), &strct.structure); //We use the partition as a filter here, for indices that belong to self, vs those that belong to other
        let (self_fiber_class_iter, mut _other_fiber_class_iter) =
            CoreFlatFiberIterator::new_paired_conjugates(&self_fiber_class); // these are iterators over the open indices of self and other, except expressed in the flat indices of the resulting structure

        for i in self_fiber_class_iter {
            println!("{}-> {:?}", i, strct.expanded_index(i))
        }
    }
}