oat_rust 0.2.0

User-friendly tools for applied topology
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
use std::collections::HashSet;
use std::time::Instant;


use itertools::Itertools;
use num::Integer;


use crate::algebra::matrices::operations::MatrixOracleOperations;
use crate::algebra::matrices::types::packet::MatrixAlgebraPacket;
use crate::algebra::zigzag::hypergraph_pipeline::chain_dimension;
use crate::algebra::rings::traits::DivisionRingOperations; 
use crate::algebra::rings::types::field_prime_order::BooleanField;
use crate::algebra::matrices::types::vec_of_vec::sorted::VecOfVec;
use crate::utilities::order::OrderOperatorByKey;



use super::cospans::Cospan;
use super::decompose::Diagonalization;
use super::hypergraph_pipeline::IntervalSubmoduleBasis;
use super::{cospans::{factor_dowker_complex, induced_cospan}, decompose::{QuiverReprsentation, SingleBarBasisVectorIndexLedger}};


use derive_getters::{Getters, Dissolve};
use derive_new::new;

// THIS JUST MAKES THE CODE EASIER TO READ
type Simplex        =   Vec<usize>;
type Chain<RingElement>          =   Vec< (Simplex, RingElement) >;








/// Returns an interval decomposition of the zigzag module of a sequence of cospans, where each cospan has an associated basis of simplicial chains
/// 
/// **This method consumes the cospans**, because we place them in a quiver representation.
/// 
/// The coefficient field is determined by the choice of `ring_operator`.
/// 
/// # Examples
/// 
/// ```
/// use oat_rust::algebra::rings::types::field_prime_order::BooleanField;
/// use oat_rust::topology::simplicial::from::relation::sideways_ladder_edges;
/// use oat_rust::algebra::zigzag::hypergraph_pipeline::interval_decomposition_for_zigzag_of_hypgeraph_unions;
/// 
/// 
/// // Construct length-2 sequence of hypergraphs of the following form. (in this
/// // case there are actually just simple undirected graphs)
/// //
/// // hypergraph 0:
/// //
/// // 1 ---- 3 ---- 5
/// // |      |      |
/// // |      |      |
/// // 0 ---- 2 ---- 4
/// //
/// // hypergraph 1:
/// //
/// //        3 ---- 5 ---- 7
/// //        |      |      |
/// //        |      |      |
/// //        2 ---- 4 ---- 6
/// //
/// // --------------------------------------------------------------------
/// 
/// let number_of_ladders                           =   2;
/// let holes_per_ladder                            =   2;
/// 
/// let mut hypergraphs                             =   Vec::new();
/// for offset_from_left in 0 .. number_of_ladders {
///     hypergraphs.push( 
///         sideways_ladder_edges(offset_from_left, holes_per_ladder)  
///     );   
/// }
/// 
/// // Compute the barcode for the corresponding zigzag:
/// //
/// // hypergraph_0 ----> ( hypergraph_0  U  hypergraph_1 ) <---- hypergraph_1
/// //
/// // --------------------------------------------------------------------
/// 
/// let ring_operator                               =   BooleanField::new();
/// let max_homology_dimension                      =   2;
/// let interval_decomposition                      =   interval_decomposition_for_zigzag_of_hypgeraph_unions(hypergraphs, ring_operator, max_homology_dimension);
/// let barcode                                     =   interval_decomposition.iter()
///                                                         .map(| (dim, submodule)| ( dim.clone(), submodule.interval_endpoints() ) )
///                                                         .collect::<Vec<_>>();
/// 
/// // Verify that the barcode is correct
/// // Note that each pair (a,b) represents a half-open interval of form [a,b)
/// // The actual barcode is
/// //
/// //             
/// // dimension 0:
/// //       
/// //      0 ---- 1 ---- 2             
/// //
/// // dimension 1  
/// //      
/// //      0 ---- 1
/// //      0 ---- 1 ---- 2
/// //             1 ---- 2
/// //
/// // --------------------------------------------------------------------
///         
/// let barcode_ground_truth: Vec< (usize,(usize,usize)) >                        =   vec![
///                                                         ( 0, (0,3) ),
///                                                         ( 1, (0,2) ),
///                                                         ( 1, (0,3) ),
///                                                         ( 1, (1,3) ),                                                                                                                                                                                               
///                                                     ];
/// 
/// assert_eq!( barcode, barcode_ground_truth );
/// ```
pub fn interval_decomposition_for_zigzag_of_cospans< RingOperator >( 
        cospans:                    Vec< Cospan< RingOperator::Element > >, 
        ring_operator:              RingOperator,
    )
    -> 
    Vec< ( usize, IntervalSubmoduleBasis< RingOperator::Element > ) >

    where
        RingOperator:       Clone +  DivisionRingOperations + std::fmt::Debug,
        RingOperator::Element:        Clone + std::fmt::Debug + Eq + Ord,
{
    // compute number of vertices and arrows    
    if cospans.len() == 0 { // if there are no hypergraphs then short circuit
        return Vec::with_capacity(0);
    }    
    let n_cospans                                       =   cospans.len();
    let n_arrows                                        =   2 * n_cospans;
    let n_vertices                                      =   2 * n_cospans + 1.min( cospans.len() ); // the term 1.min( cospans.len() adds 1 if there is at least one cospan in the list; technically we don't need to worry about this because we can't get to this poitn in the code unless there is at least one cospan ... but it makes me feel better to have formulae that work everywhere

    // build quiver representation
    // ---------------------------

    let start = Instant::now();

    // define arrow directions
    let arrow_directions                                =   ( 0 .. n_arrows ).map(|i| i.is_even() ).collect::<Vec<_>>();    



    // initialize matrices and cycle bases
    let mut matrices                                    =   Vec::with_capacity(n_arrows);  
    let mut homology_cycle_bases                        =   Vec::with_capacity(n_vertices);

    // insert the basis for the leftmost vertex
    homology_cycle_bases.push( cospans[0].left_basis.clone() );
    
    
    // fill in matrices, vector space grades, and gradings
    for cospan in cospans {      
        matrices.push( cospan.left_morphism );
        matrices.push( cospan.right_morphism );
        homology_cycle_bases.push( cospan.center_basis );
        homology_cycle_bases.push( cospan.right_basis );            
    }

    let vector_space_dimensions                         =   homology_cycle_bases.iter().map(|basis| basis.number_of_rows() ).collect::<Vec<_>>();
    let quiver_representation                           =   QuiverReprsentation::new(
                                                                arrow_directions, 
                                                                matrices, 
                                                                vector_space_dimensions,
                                                                ring_operator.clone(),
                                                            );

                
    
    let duration = start.elapsed();                     // Stop the timer
    println!("Time to build quiver: {:?}", duration);     // Print the elapsed time

    // diagonalize the representation
    // ----------------------------------
    let diagonalization                                 =   quiver_representation.diagonalize().unwrap();



    // compute submodules

    let mut submodules                                  =   Vec::new();
    for single_bar_ledger in diagonalization.list_of_single_bar_basis_vector_index_ledgers() {

        let mut chains                                  =   Vec::with_capacity(single_bar_ledger.bar_length());
        for (vertex, basis_vector_index) in single_bar_ledger.iter() {
            let row       =   diagonalization.bases()[ vertex ].row_ref( basis_vector_index );

            let homology_cycle_basis_matrix   =     MatrixAlgebraPacket::with_default_order(
                                                                & homology_cycle_bases[ vertex ], 
                                                                ring_operator.clone()
                                                            );

            let chain   =   homology_cycle_basis_matrix.multiply_with_row_vector(row).collect();
            
            chains.push(chain);
        }

        let dimension                               =   chain_dimension( & chains[0] );        
        let submodule                               =   IntervalSubmoduleBasis{ 
                                                            leftmost_vertex:    single_bar_ledger.leftmost_vertex(),
                                                            basis_vectors:      chains,
                                                        };

        submodules.push( ( dimension, submodule ) );        
    }

    submodules.sort_by_key( |(dim,submodule)|  ( dim.clone(), submodule.interval_endpoints() )  );
    submodules
}







































#[cfg(test)]
mod tests {



    

    #[test]
    fn doc_test_sideways_ladder() {
        use crate::algebra::rings::types::field_prime_order::BooleanField;
        use crate::topology::simplicial::from::relation::sideways_ladder_edges;
        use crate::algebra::zigzag::hypergraph_pipeline::interval_decomposition_for_zigzag_of_hypgeraph_unions;


        // Construct length-2 sequence of hypergraphs of the following form. (in this
        // case there are actually just simple undirected graphs)
        //
        // hypergraph 0:
        //
        // 1 ---- 3 ---- 5
        // |      |      |
        // |      |      |
        // 0 ---- 2 ---- 4
        //
        // hypergraph 1:
        //
        //        3 ---- 5 ---- 7
        //        |      |      |
        //        |      |      |
        //        2 ---- 4 ---- 6
        //
        // --------------------------------------------------------------------

        let number_of_ladders                           =   2;
        let holes_per_ladder                            =   2;

        let mut hypergraphs                             =   Vec::new();
        for offset_from_left in 0 .. number_of_ladders {
            hypergraphs.push( 
                sideways_ladder_edges(offset_from_left, holes_per_ladder)  
            );   
        }

        // Compute the barcode for the corresponding zigzag:
        //
        // hypergraph_0 ----> ( hypergraph_0  U  hypergraph_1 ) <---- hypergraph_1
        //
        // --------------------------------------------------------------------

        let ring_operator                               =   BooleanField::new();
        let max_homology_dimension                      =   2;
        let interval_decomposition                      =   interval_decomposition_for_zigzag_of_hypgeraph_unions(hypergraphs, ring_operator, max_homology_dimension);
        let barcode                                     =   interval_decomposition.iter()
                                                                .map(| (dim, submodule)| ( dim.clone(), submodule.interval_endpoints() ) )
                                                                .collect::<Vec<_>>();
        
        // Verify that the barcode is correct
        // Note that each pair (a,b) represents a half-open interval of form [a,b)
        // The actual barcode is
        //
        //             
        // dimension 0:
        //       
        //      0 ---- 1 ---- 2             
        //
        // dimension 1  
        //      
        //      0 ---- 1
        //      0 ---- 1 ---- 2
        //             1 ---- 2
        //
        // --------------------------------------------------------------------
                
        let barcode_ground_truth: Vec< (usize,(usize,usize)) >                        =   vec![
                                                                ( 0, (0,3) ),
                                                                ( 1, (0,2) ),
                                                                ( 1, (0,3) ),
                                                                ( 1, (1,3) ),                                                                                                                                                                                               
                                                            ];

        assert_eq!( barcode, barcode_ground_truth );

    }





    #[test]
    fn test_sideways_ladder() {
        use crate::algebra::rings::types::field_prime_order::BooleanField;
        use crate::topology::simplicial::from::relation::sideways_ladder_edges;
        use crate::algebra::zigzag::hypergraph_pipeline::interval_decomposition_for_zigzag_of_hypgeraph_unions;


        let number_of_ladders                           =   3;
        let holes_per_ladder                            =   2;

        let mut hypergraphs                             =   Vec::new();
        for offset_from_left in 0 .. number_of_ladders {
            hypergraphs.push( 
                sideways_ladder_edges(offset_from_left, holes_per_ladder)  
            );   
        }

        // Compute the barcode for the corresponding zigzag:
        // hypergraph_0 ----> ( hypergraph_0  U  hypergraph_1 ) <---- hypergraph_1
        let ring_operator                               =   BooleanField::new();
        let max_homology_dimension                      =   2;        
        let interval_decomposition                      =   interval_decomposition_for_zigzag_of_hypgeraph_unions(hypergraphs, ring_operator, max_homology_dimension);
        let barcode                                     =   interval_decomposition.iter()
                                                                .map(| (dim, submodule)| ( dim.clone(), submodule.interval_endpoints() ) )
                                                                .collect::<Vec<_>>();

        // println!("max grade with bars: {:?}", diagonalization.max_nontrivial_grade() );
        // println!("diagonalization: {:#?}", & diagonalization );
        // println!("barcode: {:?}", barcode);

        // Verify that the barcode is correct
        // Note that each pair (a,b) represents a half-open interval of form [a,b)
        //
        // Here's a "diagram" of the ladders, where each * represents a hole
        //
        //  laddder 0        : * *
        //  laddder 1 (union): * * *
        //  laddder 2        :   * *
        //  laddder 3 (union):   * * *
        //  laddder 4        :     * *
        //
        // By in specting this we can see that the barcode should be
        //
        // Dimension 0:
        //      0 ---- 1 ---- 2 ---- 3 ---- 4
        //
        // Dimension 2:
        //      0 ---- 1 
        //      0 ---- 1 ---- 2 ---- 3
        //             1 ---- 2 ---- 3 ---- 4
        //                           3 ---- 4
                                     
        let barcode_ground_truth                        =   vec![
                                                                ( 0, (0,5) ),
                                                                ( 1, (0,2) ),
                                                                ( 1, (0,4) ),
                                                                ( 1, (1,5) ),
                                                                ( 1, (3,5) ),
                                                            ];

        assert_eq!( barcode, barcode_ground_truth );

    }    


    /// Similar to preceding test, but for every hypergraph we add a hyperdge that contains all the odd vertices.
    #[test]
    fn test_sideways_ladder_with_top_blob() {
        use num::Integer;
        use std::collections::HashSet;
        use crate::algebra::rings::types::field_prime_order::BooleanField;
        use crate::topology::simplicial::from::relation::sideways_ladder_edges;
        use crate::algebra::zigzag::hypergraph_pipeline::interval_decomposition_for_zigzag_of_hypgeraph_unions;


        let number_of_ladders                           =   3;
        let holes_per_ladder                            =   2;

        let mut hypergraphs                             =   Vec::new();


        // build the ladder hypergraphs
        for offset_from_left in 0 .. number_of_ladders {
            hypergraphs.push( 
                sideways_ladder_edges(offset_from_left, holes_per_ladder)  
            );   
        }

        // add the blob
        let mut blob                                    =   HashSet::new();
        blob.extend( 
            hypergraphs.iter()
                .map(|x| x.iter().map(|y| y.iter().cloned() ).flatten() )
                .flatten()
                .filter(|x| x.is_odd() )
            );
        let mut blob: Vec<_>                                    =   blob.into_iter().collect();
        blob.sort();

        for hypergraph in hypergraphs.iter_mut() {
            hypergraph.push( blob.clone() );
        }            

        // Compute the barcode for the corresponding zigzag:
        // hypergraph_0 ----> ( hypergraph_0  U  hypergraph_1 ) <---- hypergraph_1
        let ring_operator                               =   BooleanField::new();
        let max_homology_dimension                      =   2;        
        let interval_decomposition                      =   interval_decomposition_for_zigzag_of_hypgeraph_unions(hypergraphs, ring_operator, max_homology_dimension);
        let barcode                                     =   interval_decomposition.iter()
                                                                .map(| (dim, submodule)| ( dim.clone(), submodule.interval_endpoints() ) )
                                                                .collect::<Vec<_>>();

        // println!("max grade with bars: {:?}", diagonalization.max_nontrivial_grade() );
        // println!("diagonalization: {:#?}", & diagonalization );
        // println!("barcode: {:?}", barcode);

        // Verify that the barcode is correct
        // Note that each pair (a,b) represents a half-open interval of form [a,b)
        //
        // Here's a "diagram" of the ladders, where each * represents a hole
        //
        //  laddder 0        : * *
        //  laddder 1 (union): * * *
        //  laddder 2        :   * *
        //  laddder 3 (union):   * * *
        //  laddder 4        :     * *
        //
        // By in specting this we can see that the barcode should be
        //
        // Dimension 0:
        //      0 ---- 1 ---- 2 ---- 3 ---- 4
        //
        // Dimension 2:
        //      0 ---- 1 
        //      0 ---- 1 ---- 2 ---- 3
        //             1 ---- 2 ---- 3 ---- 4
        //                           3 ---- 4
                                     

        let barcode_ground_truth                        =   vec![
                                                                ( 0, (0,5) ),
                                                                ( 1, (0,2) ),
                                                                ( 1, (0,4) ),
                                                                ( 1, (1,5) ),
                                                                ( 1, (3,5) ),
                                                            ];                                     

        assert_eq!( barcode, barcode_ground_truth );

    }        

}