~mht/cra

ref: a3f4797faa2ae9132d5c562127285d8c56e01149 cra/cra/src/main.rs -rw-r--r-- 35.0 KiB
a3f4797f — Martin Hafskjold Thoresen Output all the pdfs 2 years ago
                                                                                
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
#![allow(dead_code)]

use std::cmp::Ordering::*;
use std::collections::HashSet;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use std::iter;
use std::process::{Command, Stdio};

const R_CUTOFF: f32 = 300.0;

fn f32_eq(a: f32, b: f32) -> bool {
    // limit is ~0.00119
    (a - b).abs() < 10_000.0 * std::f32::EPSILON
}

/// All the statistics we want to measure for performance reasoning.
#[derive(Debug)]
pub struct Statistics {
    col_adds: usize,
    add_size: Vec<(usize, usize)>,
    add_size_sum: Vec<usize>,
    add_iters: Vec<usize>,
    num_iters: Vec<usize>,
    ex_reductions: Vec<usize>,
    ex_searches: Vec<usize>,
    zeroed: usize,
    placed_single: usize,
    placed_full: usize,
    pops: usize,
}

impl Statistics {
    pub fn new() -> Self {
        Self {
            col_adds: 0,
            add_size: Vec::new(),
            add_size_sum: Vec::new(),
            add_iters: Vec::new(),
            num_iters: Vec::new(),
            ex_reductions: Vec::new(),
            ex_searches: Vec::new(),
            zeroed: 0,
            placed_single: 0,
            placed_full: 0,
            pops: 0,
        }
    }

    /// Record the number of iterations we needed to find a index containing a low in another
    /// column, while in the exhaustive variant.
    pub fn ex_search(&mut self, c: usize) {
        self.ex_searches.push(c);
    }

    /// Record the number of iterations we needed to exhaustively reduce a column after its `low`
    /// was found.
    pub fn ex_reductions(&mut self, c: usize) {
        self.ex_reductions.push(c);
    }

    /// Record the number of times we've removed the last element in an IndexList.
    pub fn pop(&mut self) {
        self.pops += 1;
    }

    /// Record the number of times a reduction ended up removing the simplex.
    pub fn zeroed(&mut self) {
        self.zeroed += 1;
    }

    /// Record the number of times a reduction ended up storing a single index.
    pub fn placed_single(&mut self) {
        self.placed_single += 1;
    }

    /// Record the number of times a reduction ended up with storing a list of indices.
    pub fn placed_full(&mut self) {
        self.placed_full += 1;
    }

    /// Record the number of iterations we used before finishing reducing a column
    pub fn reductions(&mut self, c: usize) {
        self.num_iters.push(c);
    }
    /// Record the sizes of the columns that are summed together
    pub fn add_sizes(&mut self, a: usize, b: usize) {
        self.add_size.push((a, b));
        self.add_size_sum.push(a + b);
    }

    /// Record the nubmer of iterations in the loop in `IndexList::xor`.
    pub fn add_iters(&mut self, c: usize) {
        self.add_iters.push(c);
    }

    /// Print out stats to stderr.
    pub fn eprint_avg(&self) {
        eprint!("Column additions: ");
        eprint_thousand_split(self.col_adds);
        eprintln!();

        let add_size0 =
            self.add_size.iter().map(|(a, _)| a).sum::<usize>() as f32 / self.add_size.len() as f32;
        eprintln!("  Average size of first operand:  {}", add_size0);

        let add_size1 =
            self.add_size.iter().map(|(_, b)| b).sum::<usize>() as f32 / self.add_size.len() as f32;
        eprintln!("  Average size of second operand: {}", add_size1);

        let num_iters = self.num_iters.iter().sum::<usize>() as f32 / self.num_iters.len() as f32;
        eprintln!(
            "Average #iterations before reducing a column: {}",
            num_iters
        );

        let xor_cost =
            self.add_size_sum.iter().sum::<usize>() as f32 / self.add_size_sum.len() as f32;
        eprintln!("Average cost of one column addition: {}", xor_cost);

        let adds = xor_cost * self.col_adds as f32 + self.pops as f32;
        eprint!("Estimate of number of adds: ");
        eprint_thousand_split(adds as usize);
        eprintln!();

        if self.ex_reductions.len() > 0 {
            let ex_reductions =
                self.ex_reductions.iter().sum::<usize>() as f32 / self.ex_reductions.len() as f32;
            eprintln!("Average iterations to exh. reduce a col: {}", ex_reductions);
        }

        if self.ex_searches.len() > 0 {
            let ex_searches =
                self.ex_searches.iter().sum::<usize>() as f32 / self.ex_searches.len() as f32;
            eprintln!("Average searches to find `j=low(k)`: {}", ex_searches);
        }

        eprintln!("Number of zeroed columns:    {}", self.zeroed);
        eprintln!("Number of single columns:    {}", self.placed_single);
        eprintln!("Number of remaining columns: {}", self.placed_full);
    }
}

fn eprint_thousand_split(mut num: usize) {
    let mut nums = vec![];
    while num > 0 {
        nums.push(num % 1_000);
        num /= 1_000;
    }
    for i in (1..nums.len()).rev() {
        if i == nums.len() - 1 {
            eprint!("{},", nums[i]);
        } else {
            eprint!("{:03},", nums[i]);
        }
    }
    if nums.len() == 1 {
        eprint!("{}", nums[0]);
    } else {
        eprint!("{:03}", nums[0]);
    }
}

/// One simplex
#[derive(Debug, Clone)]
pub struct Simplex {
    /// Original index. We need this for bookkeeping.
    j: usize,
    /// Indices of the faces of this simplex
    faces: Vec<usize>,
    /// The ball radius when this simplex is born.
    r_when_born: f32,
}

impl Simplex {
    /// Get the dimension of this simplex.
    pub fn dim(&self) -> isize {
        self.faces.len() as isize - 1
    }
}

/// Data we use for stuff.
pub struct Persistence {
    /// All simplices in the data set
    simplices: Vec<Simplex>,
    /// Point location data, for rendering.
    points: Vec<[f32; 2]>,
}

type Error = Box<std::error::Error>;
pub fn read_input_stdin2() -> Result<Persistence, Error> {
    let stdin = std::io::stdin();
    let mut lines = BufReader::new(stdin.lock()).lines();

    // File format:
    //     number-of-verts
    //     point data of the vertices
    //     empty line
    //     triangle point indices

    let first_line = lines.next().ok_or("empty stdin")??;
    let number_of_vertices: usize = first_line.parse::<usize>()?;

    let points = (&mut lines)
        .take(number_of_vertices)
        .map(|line| {
            let line = line.unwrap();
            let mut buf = [0f32; 2];
            for (i, string) in line.split(' ').enumerate() {
                buf[i] = string.parse::<f32>().unwrap();
            }
            buf
        })
        .collect::<Vec<[f32; 2]>>();

    assert_eq!(lines.next().unwrap().unwrap(), ""); // the empty line

    // Map the triangle index to the indices of the points it has. This goes directly into the
    // `points` array.
    let mut faces_to_points = Vec::new();
    for line in lines {
        let mut buf = [0usize; 3];
        for (i, string) in line.unwrap().split(' ').enumerate() {
            buf[i] = string.parse::<usize>().unwrap();
        }
        faces_to_points.push(buf);
    }

    // Now we have a vec of euclidian point data, and a vec of indices to the point data which
    // forms triangles. Next up we construct the simplices.

    let simplices: Vec<Vec<usize>> = {
        let mut simplices: Vec<Vec<usize>> =
            Vec::with_capacity(points.len() + faces_to_points.len() + 1);

        simplices.push(vec![]); // empty simplex of dim `-1`.

        for _ in &points {
            simplices.push(vec![0]);
        }

        // Now we want to make the edges, which are implicit in the face data.
        // However, we must also avoid double counting. We make a hashmap to find all
        // unique edges, and vecs for edges and faces.
        let mut edge_to_index = std::collections::HashMap::new();
        // To avoid double counting we store the edges sorted in the hashmap.
        fn sorted_a2([x, y]: [usize; 2]) -> [usize; 2] {
            if x < y {
                [x, y]
            } else {
                [y, x]
            }
        }

        let mut faces: Vec<Vec<usize>> = Vec::new();
        for &face in &faces_to_points {
            // Winding order seems to be CW, but not sure if this is guaranteed by CGAL.
            // Faces are zero-indexed, but we have the empty simlex, so we must shift the indices
            // by one.
            let current_edges = [
                [face[0] + 1, face[1] + 1],
                [face[1] + 1, face[2] + 1],
                [face[2] + 1, face[0] + 1],
            ];
            let mut buf = [0usize; 3];
            for (i, &edge) in current_edges.into_iter().enumerate() {
                let edge_i = *edge_to_index.entry(sorted_a2(edge)).or_insert_with(|| {
                    let index = simplices.len();
                    simplices.push(edge.to_vec());
                    index
                });
                buf[i] = edge_i;
            }
            faces.push(buf.to_vec());
        }
        simplices.extend_from_slice(&faces);
        simplices
    };

    let mut simplices = simplices
        .into_iter()
        .enumerate()
        .map(|(j, v)| Simplex {
            j,
            faces: v,
            r_when_born: 0.0,
        })
        .collect::<Vec<_>>();

    let simplices_ptr = simplices.as_ptr();
    for (current_simplex_i, simplex) in simplices.iter_mut().enumerate() {
        let simpl = |i: usize| unsafe {
            // We really only require `current_simplex_i != i` to avoid aliasing,
            // but this is a logic error if not.
            assert!(current_simplex_i > i);
            let target: *mut Simplex = simplices_ptr.offset(i as isize) as *mut _;
            &mut *target
        };
        match simplex.dim() {
            -1 | 0 => simplex.r_when_born = 0.0,
            1 => {
                let p0 = Point(points[simplex.faces[0] - 1]);
                let p1 = Point(points[simplex.faces[1] - 1]);
                let diff = p1 - p0;
                let r = 0.5 * diff.len();
                simplex.r_when_born = r;
            }
            2 => {
                let xy_i = simplex.faces[0];
                let xy = simpl(xy_i);
                let yz_i = simplex.faces[1];
                let _yz = simpl(yz_i);
                let zx_i = simplex.faces[2];
                let zx = simpl(zx_i);
                // The labels here may be messed up due to the sorting when making the edges.
                // Get it right.
                let (x_i, y_i, z_i) = if xy.faces[0] == zx.faces[0] {
                    // xy, xz
                    (xy.faces[0], xy.faces[1], zx.faces[1])
                } else if xy.faces[0] == zx.faces[1] {
                    // xy, zx
                    (xy.faces[0], xy.faces[1], zx.faces[0])
                } else if xy.faces[1] == zx.faces[0] {
                    // yx, xz
                    (xy.faces[1], xy.faces[0], zx.faces[1])
                } else {
                    // yx, zx
                    (xy.faces[1], xy.faces[0], zx.faces[0])
                };

                let x = Point(points[x_i - 1]);
                let y = Point(points[y_i - 1]);
                let z = Point(points[z_i - 1]);

                let xy = (y - x).len();
                let xz = (z - x).len();
                let yz = (z - y).len();

                let ax = (y - x).angle(z - x);
                let ay = (z - y).angle(x - y);
                let az = (x - z).angle(y - z);
                let am = ax.max(ay).max(az);

                // The circumcenter is the point in which the balls from each vertex meets, so
                // at `r=circumradius` the face is filled in.
                let circumradius = (xy * yz * xz)
                    / ((xy + yz + xz) * (xy + yz - xz) * (xy - yz + xz) * (-xy + yz + xz)).sqrt();

                if am * 180.0 / std::f32::consts::PI >= 90.0 {
                    // When one angle is > 90.0, the circumcenter of the triangle is outside.  Then
                    // the balls from the edges that's closest to the circumcenter doesn't meet
                    // before they are at the circumcenter. Thus we must ajust the `r_when_born` on
                    // this edge.
                    if am == ax {
                        // debug_assert_eq!(yz / 2.0, simpl(yz_i).r_when_born);
                        simpl(yz_i).r_when_born = circumradius;
                    } else if am == ay {
                        // debug_assert_eq!(xz / 2.0, simpl(zx_i).r_when_born);
                        simpl(zx_i).r_when_born = circumradius;
                    } else {
                        // debug_assert_eq!(xy / 2.0, simpl(xy_i).r_when_born);
                        simpl(xy_i).r_when_born = circumradius;
                    }
                }
                simplex.r_when_born = circumradius;
            }
            more => panic!("Only support 2d simplices! ({} > 2)", more),
        }
    }
    // The times in which a simplex dies is determined by the pairing: it will die when a simplex
    // of dimension d+1 is born.

    Ok(Persistence { simplices, points })
}

/// Given a `Vec<Vec<usize>>` in which the first `Vec` is a list of simplices and the second `Vec`
/// is the indices of its faces, run the "matrix reduction" algorithm.
///
/// We assume the slice is sorted, such that all faces precede their simplices, and that
/// the indices are sorted.
pub fn reduce(p: &Persistence, exhaustive: bool, stats: &mut Statistics) -> Vec<(usize, usize)> {
    let n = p.simplices.len();
    let mut simplex_with_low: Vec<Ptr> = vec![Ptr { addr: 0 }; n];

    let mut pairings = Vec::new();

    let mut killed = HashSet::new();
    let mut zeroed = HashSet::new();

    let mut gives_death = vec![false; n];
    let mut got_zeroed = Vec::new();

    for simplex in p.simplices.iter() {
        let j = simplex.j;
        // eprintln!("== {:?}", simplex);
        if simplex.r_when_born >= R_CUTOFF {
            // Already sorted on `r_when_born`, but might be some floating point trickery going on,
            // so just iterate to the end.
            // eprintln!("Skipping simplex with `r_when_born == {}`", simplex.r_when_born);
            continue;
        }
        // We probably want to copy the face data anyways, since we're chaning the columns and we
        // want to still have the original data in the `Persistence` struct.
        let mut current_simplex = IndexList::from_slice(&simplex.faces);
        if j > 0 && current_simplex.max() >= j {
            eprintln!("OH NO!! {:?}", simplex);
            for &face in &simplex.faces {
                eprintln!("        {:?}", p.simplices[face]);
            }
            eprintln!("    {:?}", current_simplex);
            panic!(
                "This list is not well formed! j={} {:?}",
                j, current_simplex.0
            );
        }

        if current_simplex.last().is_none() {
            continue;
        }

        let mut iter = 0;
        loop {
            let low = current_simplex.last().unwrap();

            if simplex_with_low[low].is_null() {
                // We have found a simplex that no other dimen=d simplex have yet.
                assert!(low <= j);
                pairings.push((low, j));
                gives_death[j] = true;
                killed.insert(low);

                if current_simplex.len() == 1 {
                    stats.placed_single();
                    // We're only storing `low`. Store as implicit.
                    simplex_with_low[low].addr = 1;
                } else {
                    stats.placed_full();
                    current_simplex.pop(stats);
                    simplex_with_low[low].addr = Box::into_raw(Box::new(current_simplex)) as usize;

                    if exhaustive {
                        // We have stored a Vec of the remaining set indices for this simplex (`j`
                        // itself is already removed). Try to remove the others by looping through
                        // from the back and check if there is a simplex with that low.
                        let mut iter = 0;
                        'search: loop {
                            let list_len = simplex_with_low[low].get().len();
                            for (iter_i, face_i) in
                                (0..list_len).rev().enumerate()
                            {
                                let this_index = simplex_with_low[low].get().0[face_i];
                                let other = &simplex_with_low[this_index];
                                if other.is_null() {
                                    // nothing to see here
                                    continue;
                                }
                                let ours = simplex_with_low[low].get_mut();
                                stats.pop();
                                ours.0.remove(face_i); // Sort of a `pop`
                                if other.is_vec() {
                                    ours.xor(other.get(), stats);
                                }
                                iter += 1;
                                stats.ex_search(iter_i + 1);
                                // if ours.is_empty() { break; }
                                continue 'search;
                            }
                            stats.ex_search(list_len);
                            stats.ex_reductions(iter);
                            break;
                        }
                        let curr = &mut simplex_with_low[low];
                        if curr.get().len() == 0 {
                            curr.implicit();
                        }
                    }
                }
                break;
            } else if simplex_with_low[low].is_implicit() {
                // Handle special case where the vector is not stored, but is really [low].
                // (we don't need to store [low], since it's index is already low.)
                current_simplex.pop(stats);
            } else {
                // Add `low` to `j`.
                let other: &IndexList = simplex_with_low[low].get();
                assert!(other.max() <= low);
                current_simplex.xor(other, stats);
                current_simplex.pop(stats); // xor out the implicit value as well.
            }

            if current_simplex.is_empty() {
                // We're reduced away the entire simplex! Now we look at row j, and check if there
                // is another simplex `k` with `low(k) = j`: if not present, then `j` is an
                // essential cycle. Since we're storing a simplex with its `low` (low) implicit in
                // that index, this is `simplex_with_low[j]`.
                stats.zeroed();
                got_zeroed.push(j);
                zeroed.insert(j);
                break;
            }
            iter += 1;
        }
        stats.reductions(iter);
        // Exhaustive goes down here! Go through remaining simplex numbers, and find entries with
        // simplex_with_low[i] != 0.
    }

    // Find the essential cycles: these are entries that did not give death, and are `null` in the
    // `simplex_with_low` (in matrix terms, this means that row `i` has no `low`s in it).

    for &cyc in zeroed.difference(&killed) {
        let s = p.simplices.iter().find(|&s| s.j == cyc).unwrap();
        eprintln!("[reduce] Essential cycle: {:?}", s);
    }

    // for (i, ptr) in simplex_with_low.iter().enumerate() {
    //     eprint!("{:2}: ", i);
    //     if ptr.is_null() {
    //         eprintln!("null");
    //     } else if ptr.is_implicit() {
    //         eprintln!("{}", i);
    //     } else {
    //         for i in ptr.get().0.iter() {
    //             eprint!("{} ", i);
    //         }
    //         eprintln!("");
    //     }
    // }

    pairings
}

/// Cheat pointer type: we want to represent `null`, a sentinel pointer, or a real pointer to a
/// `IndexList`, since we're implicitly representing one of the numbers in the IndexList, namely
/// the highest one, since it is in this position in the `L` list we're stored.
///
/// We cannot do this with an `Option`, since we need both "no list" and "just the implicit entry".
#[derive(Debug, Clone)]
struct Ptr {
    addr: usize,
}

impl Ptr {
    fn is_null(&self) -> bool {
        self.addr == 0
    }

    fn is_implicit(&self) -> bool {
        self.addr == 1
    }

    fn is_vec(&self) -> bool {
        self.addr > 1
    }

    fn get(&self) -> &IndexList {
        unsafe { &*(self.addr as *const IndexList) }
    }

    fn null(&mut self) {
        if self.is_vec() {
            let _il: Box<IndexList> = unsafe { Box::from_raw(self.addr as *mut _) };
        }
        self.addr = 0;
    }

    fn implicit(&mut self) {
        if self.is_vec() {
            let _il: Box<IndexList> = unsafe { Box::from_raw(self.addr as *mut _) };
        }
        self.addr = 1;
    }

    /// WARNING: This should be `&mut self`, but is not, since this would require `unsafe` other
    /// places. Not a great thing, but okay.
    fn get_mut(&self) -> &mut IndexList {
        unsafe { &mut *(self.addr as *const IndexList as *mut IndexList) }
    }

    fn vec(&self) -> Option<&IndexList> {
        if self.is_vec() {
            Some(self.get())
        } else {
            None
        }
    }
}

/// A list of the face indices of a simplex.
#[derive(Debug)]
struct IndexList(Vec<usize>);

impl IndexList {
    fn from_slice(slice: &[usize]) -> Self {
        let mut v = Vec::new();
        v.extend(slice);
        v.sort();
        IndexList(v)
    }

    fn pop(&mut self, stats: &mut Statistics) {
        stats.pop();
        self.0.pop();
    }

    /// XOR together the two indices list. This means joining all indices, and removing the indices
    /// that were present in both lists.
    fn xor(&mut self, other: &Self, stats: &mut Statistics) {
        stats.col_adds += 1;
        stats.add_sizes(self.len(), other.len());
        // For now, let's just walk through both vecs trying to find matches, add new ones into
        // self, and sort at the end.
        // PERF: Allocation in here! Can we do without?
        let mut new = Vec::new();
        let mut our_i = 0;
        let mut their_i = 0;
        let our_last = self.0.len();
        let their_last = other.0.len();

        let mut i = 0;
        while our_i < our_last && their_i < their_last {
            i += 1;
            if self.0[our_i] < other.0[their_i] {
                new.push(self.0[our_i]);
                our_i += 1;
            } else if self.0[our_i] == other.0[their_i] {
                our_i += 1;
                their_i += 1;
            } else {
                new.push(other.0[their_i]);
                their_i += 1;
            }
        }
        stats.add_iters(i);
        new.extend(&other.0[their_i..]);
        new.extend(&self.0[our_i..]);
        self.0 = new;
    }

    fn len(&self) -> usize {
        self.0.len()
    }

    fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    fn last(&self) -> Option<usize> {
        self.0.last().cloned()
    }

    fn max(&self) -> usize {
        *self.0.iter().max().unwrap()
    }
}

use std::ops::Index;
impl Index<usize> for IndexList {
    type Output = usize;
    fn index(&self, i: usize) -> &usize {
        &self.0[i]
    }
}

#[derive(Copy, Clone, Debug)]
pub struct Point(pub [f32; 2]);

impl std::ops::Add<Point> for Point {
    type Output = Point;
    fn add(self, other: Point) -> Point {
        Point([self.0[0] + other.0[0], self.0[1] + other.0[1]])
    }
}

impl std::ops::Sub<Point> for Point {
    type Output = Point;
    fn sub(self, other: Point) -> Point {
        Point([self.0[0] - other.0[0], self.0[1] - other.0[1]])
    }
}

impl std::ops::Div<f32> for Point {
    type Output = Point;
    fn div(self, f: f32) -> Point {
        Point([self.0[0] / f, self.0[1] / f])
    }
}

impl Point {
    fn len(self) -> f32 {
        (self.0[0].powi(2) + self.0[1].powi(2)).sqrt()
    }

    fn dot(self, other: Self) -> f32 {
        self.0[0] * other.0[0] + self.0[1] * other.0[1]
    }

    fn angle(self, other: Point) -> f32 {
        let n = self.dot(other) / (self.len() * other.len());
        n.acos()
    }
}

fn main() {
    let mut persistence = read_input_stdin2().unwrap();

    for (i, s) in persistence.simplices.iter().enumerate() {
        assert_eq!(i, s.j);
    }

    persistence.simplices.sort_by(|a, b| {
        if b.faces.contains(&a.j) {
            Less
        } else if a.faces.contains(&b.j) {
            Greater
        } else if f32_eq(a.r_when_born, b.r_when_born) {
            a.dim().cmp(&b.dim())
        } else {
            a.r_when_born.partial_cmp(&b.r_when_born).unwrap()
        }
    });

    // Map j to sorted index.
    let sorted_index_of_j = {
        let mut v = (0..persistence.simplices.len()).collect::<Vec<_>>();
        for (i, s) in persistence.simplices.iter().enumerate() {
            v[s.j] = i;
        }
        v
    };

    // Change all `r-values` to be in the sorted format, such that `simplex[a].j == a`.
    for (j, s) in persistence.simplices.iter_mut().enumerate() {
        for face in s.faces.iter_mut() {
            *face = sorted_index_of_j[*face];
        }
        s.j = j;
    }

    for (j, s) in persistence.simplices.iter().enumerate() {
        if let Some(&max) = s.faces.iter().max() {
            if max >= j {
                panic!();
            }
        }
    }

    let mut r_stats = Statistics::new();
    let _pairings = reduce(&persistence, false, &mut r_stats);

    eprintln!("## Statistics for the =Regular= variant ##");
    r_stats.eprint_avg();
    eprintln!("\n");

    let mut e_stats = Statistics::new();
    let pairings = reduce(&persistence, true, &mut e_stats);

    eprintln!("## Statistics for the =Exhaustive= variant ##");
    e_stats.eprint_avg();
    eprintln!("\n");

    output_histogram(&e_stats.ex_searches,
                     "Iters for finding k=low(i) for any i",
                     "ex_searches.pdf");
    output_histogram(&e_stats.ex_reductions,
                     "Iters for exhaustively reducing a column",
                     "ex_reductions.pdf");

    output_2histogram(&r_stats.add_iters, &e_stats.add_iters, 
                      "Loop iterations in 'xor'",
                      "add_iters.pdf");
    output_2histogram(&r_stats.add_size_sum, &e_stats.add_size_sum,
                      "Cost estimate for column addition",
                      "add_size_sum.pdf");
    output_2histogram(&r_stats.num_iters, &e_stats.num_iters,
                      "Number of iterations for reducing a column",
                      "num_iters.pdf");

    // eprintln!("{:#?}", persistence.simplices);
    // eprintln!("{:?}", pairings);

    for (a, b) in pairings {
        let birth = persistence.simplices[a].r_when_born;
        let death = persistence.simplices[b].r_when_born;
        // eprintln!("{}", birth);
        if birth > death && !f32_eq(death, birth) {
            panic!(
                "Birth cannot be _after_ death! {} {} diff={} {:?} {:?}",
                death,
                birth,
                (death - birth),
                persistence.simplices[a],
                persistence.simplices[b],
            );
        }
        println!("pair({}, {})", birth, death);
    }

    output_svg(&persistence);
}

fn output_svg(persistence: &Persistence) {
    let mut f = std::fs::File::create("lol.svg").unwrap();

    const PADDING: f32 = 40f32;

    let min_x = persistence
        .points
        .iter()
        .map(|a| a[0])
        .min_by(|a, b| a.partial_cmp(b).unwrap())
        .unwrap();
    let max_x = persistence
        .points
        .iter()
        .map(|a| a[0])
        .max_by(|a, b| a.partial_cmp(b).unwrap())
        .unwrap();
    let min_y = persistence
        .points
        .iter()
        .map(|a| a[1])
        .min_by(|a, b| a.partial_cmp(b).unwrap())
        .unwrap();
    let max_y = persistence
        .points
        .iter()
        .map(|a| a[1])
        .max_by(|a, b| a.partial_cmp(b).unwrap())
        .unwrap();
    let xr = max_x - min_x;
    let yr = max_y - min_y;

    f.write_fmt(format_args!(
        r#"<svg xmlns="http://www.w3.org/2000/svg"
                xmlns:xlink="http://www.w3.org/1999/xlink"
                height="{}" width="{}">"#,
        yr + PADDING * 2.0,
        xr + PADDING * 2.0
    ))
    .unwrap();
    f.write(&[b'\n']).unwrap();

    let xo = PADDING - min_x;
    let yo = PADDING - min_y;

    for simplex in persistence.simplices.iter() {
        if simplex.dim() == 2 {
            let xy_i = simplex.faces[0];
            let xy = &persistence.simplices[xy_i];
            let yz_i = simplex.faces[1];
            let yz = &persistence.simplices[yz_i];
            let zx_i = simplex.faces[2];
            let zx = &persistence.simplices[zx_i];
            // The labels here may be messed up due to the sorting when making the edges. Get it
            // right.
            let (x_i, y_i, z_i) = if xy.faces[0] == zx.faces[0] {
                // xy, xz
                (xy.faces[0], xy.faces[1], zx.faces[1])
            } else if xy.faces[0] == zx.faces[1] {
                // xy, zx
                (xy.faces[0], xy.faces[1], zx.faces[0])
            } else if xy.faces[1] == zx.faces[0] {
                // yx, xz
                (xy.faces[1], xy.faces[0], zx.faces[1])
            } else {
                // yx, zx
                (xy.faces[1], xy.faces[0], zx.faces[0])
            };

            let p0 = Point(persistence.points[x_i - 1]);
            let p1 = Point(persistence.points[y_i - 1]);
            let p2 = Point(persistence.points[z_i - 1]);

            if simplex.r_when_born >= R_CUTOFF {
                if xy.r_when_born < R_CUTOFF {
                    f.write_fmt(format_args!(
                        r#"<line x1="{}" y1="{}" x2="{}" y2="{}"
                                 style="stroke:black;stroke-width:1;" />"#,
                        p0.0[0] + xo,
                        p0.0[1] + yo,
                        p1.0[0] + xo,
                        p1.0[1] + yo
                    ))
                    .unwrap();
                    f.write(&[b'\n']).unwrap();
                }
                if zx.r_when_born < R_CUTOFF {
                    f.write_fmt(format_args!(
                        r#"<line x1="{}" y1="{}" x2="{}" y2="{}"
                                 style="stroke:black;stroke-width:1;" />"#,
                        p0.0[0] + xo,
                        p0.0[1] + yo,
                        p2.0[0] + xo,
                        p2.0[1] + yo
                    ))
                    .unwrap();
                    f.write(&[b'\n']).unwrap();
                }
                if yz.r_when_born < R_CUTOFF {
                    f.write_fmt(format_args!(
                        r#"<line x1="{}" y1="{}" x2="{}" y2="{}"
                                 style="stroke:black;stroke-width:1;" />"#,
                        p1.0[0] + xo,
                        p1.0[1] + yo,
                        p2.0[0] + xo,
                        p2.0[1] + yo
                    ))
                    .unwrap();
                    f.write(&[b'\n']).unwrap();
                }
            } else {
                f.write_fmt(format_args!(
                    r#"<polygon points="{},{} {},{} {},{}" style="fill:#e0a0f0;stroke:black;stroke-width:1;" />"#,
                    p0.0[0] + xo,
                    p0.0[1] + yo,
                    p1.0[0] + xo,
                    p1.0[1] + yo,
                    p2.0[0] + xo,
                    p2.0[1] + yo
                )).unwrap();
                f.write(&[b'\n']).unwrap();
            }
        }
    }
    println!("{:?}", persistence.points);
    for (_i, v) in persistence.points.iter().enumerate() {
        f.write_fmt(format_args!(
            r#"<circle cx="{}" cy="{}" r="2" fill="red"/>"#,
            v[0] + PADDING - min_x,
            v[1] + PADDING - min_y
        ))
        .unwrap();
        f.write_fmt(format_args!(
            r#"<text x="{}" y="{}" >{}</text>"#,
            v[0] + PADDING - min_x,
            v[1] + PADDING - min_y,
            _i + 1
        ))
        .unwrap();
        f.write(&[b'\n']).unwrap();
    }
    f.write_all(b"</svg>").unwrap();
}

// Run `gnuplot` with the given script and out file for output.
fn run_gnuplot(script: &str, out_file: &str) {
    let mut gnuplot = Command::new("gnuplot")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("Failed to run `gnuplot`");
    {
        let stdin = gnuplot
            .stdin
            .as_mut()
            .expect("Failed to open stdin for `gnuplot`");
        stdin
            .write_all(script.as_bytes())
            .expect("Failed to write to stdin");
    }
    let output = gnuplot
        .wait_with_output()
        .expect("`wait_for_output` failed!");
    match output.status.code() {
        Some(0) => {}
        other => panic!("`gnuplot` process returned error: {:?}", other),
    }

    let mut f = File::create(out_file).unwrap();
    f.write_all(&output.stdout).unwrap();
}

fn histogram(data: &[usize]) -> Vec<usize> {
    if data.len() == 0 {
        panic!("Trying to create histogram of empty data set");
    }
    let max = data.iter().max().unwrap();
    let mut freq = iter::repeat(0).take(max + 1).collect::<Vec<_>>();
    for &d in data.iter() {
        freq[d] += 1;
    }
    freq
}

fn output_histogram(data: &[usize], label: &str, out_file: &str) {
    if data.len() == 0 {
        panic!("output_histogram: `data` cannot be empty!");
    }

    let frequency = histogram(data);

    let mut file = File::create("kek.freq").unwrap();
    for (ind, freq) in frequency.iter().enumerate() {
        file.write_fmt(format_args!("{} {}\n", ind, freq)).unwrap();
    }

    let plot_script = format!(
        r#"
stats 'kek.freq' 
set grid
set terminal pdf size 12cm,10cm
set logscale y
set xtics out
set ytics out
set xrange [-0.5:STATS_max_x + 0.5]
set xlabel "{}"
set ylabel "Frequency"
set style fill solid 1.0 noborder
set boxwidth 1.1
plot 'kek.freq' using ($1):($2 + 1) with boxes lc rgb"gray40" notitle
"#,
        label
    );

    run_gnuplot(&plot_script, out_file);
}

fn output_2histogram(data_a: &[usize], data_b: &[usize], label: &str, out_file: &str) {
    if data_a.len() == 0 || data_b.len() == 0 {
        panic!("output_histogram: `data` cannot be empty!");
    }

    let a_hist = histogram(data_a);
    let b_hist = histogram(data_b);

    let mut file = File::create("kek.freq").unwrap();

    for (a, b) in a_hist.iter().zip(b_hist.iter()) {
        file.write_fmt(format_args!("{} {}\n", a, b)).unwrap();
    }

    let plot_script = format!(
        r#"
set terminal pdf size 18cm,14cm
set logscale y
set xtics out
set ytics out
set xrange [-1:]
set xlabel "{}"
set ylabel "Frequency"
set boxwidth 0.5
set style fill solid 1.0 noborder
plot 'kek.freq' using ($0 - 0.25):($1+1) with boxes lc rgb"gray20" title "Regular",\
     'kek.freq' using ($0 + 0.25):($2+1) with boxes lc rgb"0x88bb88" title "Exhaustive"
"#,
        label
    );

    run_gnuplot(&plot_script, out_file);
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn indexlist_xor() {
        let s = &mut Statistics::new();

        let mut il = IndexList(vec![0, 1, 2, 3]);

        il.xor(&IndexList(vec![2, 3, 4, 5]), s);
        assert_eq!(il.0, vec![0, 1, 4, 5]);

        il.xor(&IndexList(vec![4, 5, 6]), s);
        assert_eq!(il.0, vec![0, 1, 6]);

        il.xor(&IndexList(vec![2]), s);
        assert_eq!(il.0, vec![0, 1, 2, 6]);

        il.xor(&IndexList(vec![0, 2, 6]), s);
        assert_eq!(il.0, vec![1]);

        il.xor(&IndexList(vec![1]), s);
        assert_eq!(il.0, vec![]);
    }
}