algebraeon-geometry 0.0.17

Algorithms for working with geometric shapes
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
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
use super::*;
use crate::{
    affine_subspace::EmbeddedAffineSubspace,
    ambient_space::AffineSpace,
    oriented_simplex::{OrientationSide, OrientedSimplex},
    partial_simplicial_complex::{LabelledPartialSimplicialComplex, PartialSimplicialComplex},
    simplex::Simplex,
    simplex_collection::{
        InteriorOrBoundary, InteriorOrBoundarySimplexCollection, LabelledSimplexCollection,
    },
    simplicial_disjoint_union::LabelledSimplicialDisjointUnion,
    vector::Vector,
};
use std::collections::{HashMap, HashSet};

#[derive(Clone)]
pub struct SCSpxInfo<'f, FS: OrderedRingSignature + FieldSignature, T: Eq + Clone + Send + Sync> {
    inv_bdry: HashSet<Simplex<'f, FS>>,
    label: T,
}

impl<'f, FS: OrderedRingSignature + FieldSignature, T: Eq + Clone + Send + Sync> std::fmt::Debug
    for SCSpxInfo<'f, FS, T>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SCSpxInfo")
            .field("inv_bdry", &self.inv_bdry)
            .finish()
    }
}

#[derive(Clone)]
pub struct LabelledSimplicialComplex<
    'f,
    FS: OrderedRingSignature + FieldSignature,
    T: Eq + Clone + Send + Sync,
> {
    ambient_space: AffineSpace<'f, FS>,
    simplexes: HashMap<Simplex<'f, FS>, SCSpxInfo<'f, FS, T>>,
}

pub type SimplicialComplex<'f, FS> = LabelledSimplicialComplex<'f, FS, ()>;

impl<'f, FS: OrderedRingSignature + FieldSignature, T: Eq + Clone + Send + Sync> std::fmt::Debug
    for LabelledSimplicialComplex<'f, FS, T>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SimplicialComplex")
            .field("simplexes", &self.simplexes)
            .finish()
    }
}

impl<'f, FS: OrderedRingSignature + FieldSignature, T: Eq + Clone + Send + Sync>
    LabelledSimplexCollection<'f, FS, T> for LabelledSimplicialComplex<'f, FS, T>
where
    FS::Set: Hash,
{
    type WithLabel<S: Eq + Clone + Send + Sync> = LabelledSimplicialComplex<'f, FS, S>;
    type SubsetType = LabelledPartialSimplicialComplex<'f, FS, T>;

    fn try_new_labelled(
        ambient_space: AffineSpace<'f, FS>,
        simplexes: HashMap<Simplex<'f, FS>, T>,
    ) -> Result<Self, &'static str> {
        for simplex in simplexes.keys() {
            assert_eq!(simplex.ambient_space(), ambient_space);
            if simplex.points().is_empty() {
                return Err("Simplicial complex musn't contain the null simplex");
            }
        }

        let mut simplexes = simplexes
            .into_iter()
            .map(|(spx, label)| {
                (
                    spx,
                    SCSpxInfo {
                        inv_bdry: HashSet::new(),
                        label,
                    },
                )
            })
            .collect::<HashMap<_, _>>();

        for simplex in simplexes.keys().cloned().collect::<Vec<_>>() {
            for bdry_spx in simplex.proper_sub_simplices_not_null() {
                match simplexes.get_mut(&bdry_spx) {
                    Some(entry) => {
                        entry.inv_bdry.insert(simplex.clone());
                    }
                    None => {
                        return Err("Simplicial complex must be closed under taking boundaries");
                    }
                }
            }
        }

        Ok(Self {
            ambient_space,
            simplexes,
        })
    }

    fn new_labelled_unchecked(
        ambient_space: AffineSpace<'f, FS>,
        simplexes: HashMap<Simplex<'f, FS>, T>,
    ) -> Self {
        Self::try_new_labelled(ambient_space, simplexes).unwrap()
    }

    fn ambient_space(&self) -> AffineSpace<'f, FS> {
        self.ambient_space
    }

    fn labelled_simplexes(&self) -> HashMap<&Simplex<'f, FS>, &T> {
        self.simplexes
            .iter()
            .map(|(spx, info)| (spx, &info.label))
            .collect()
    }

    fn into_labelled_simplexes(self) -> HashMap<Simplex<'f, FS>, T> {
        self.simplexes
            .into_iter()
            .map(|(spx, info)| (spx, info.label))
            .collect()
    }

    fn into_partial_simplicial_complex(self) -> LabelledPartialSimplicialComplex<'f, FS, T> {
        LabelledPartialSimplicialComplex::new_labelled_unchecked(
            self.ambient_space,
            self.simplexes
                .into_iter()
                .map(|(spx, info)| (spx, info.label))
                .collect(),
        )
    }

    fn to_partial_simplicial_complex(&self) -> LabelledPartialSimplicialComplex<'f, FS, T> {
        self.clone().into_partial_simplicial_complex()
    }

    fn into_simplicial_disjoint_union(self) -> LabelledSimplicialDisjointUnion<'f, FS, T> {
        LabelledSimplicialDisjointUnion::new_labelled_unchecked(
            self.ambient_space,
            self.simplexes
                .into_iter()
                .map(|(spx, info)| (spx, info.label))
                .collect(),
        )
    }

    fn to_simplicial_disjoint_union(&self) -> LabelledSimplicialDisjointUnion<'f, FS, T> {
        self.clone().into_simplicial_disjoint_union()
    }
}

impl<'f, FS: OrderedRingSignature + FieldSignature, T: Eq + Clone + Send + Sync>
    LabelledSimplicialComplex<'f, FS, T>
where
    FS::Set: Hash,
{
    #[allow(unused)]
    pub(crate) fn check(&self) {
        let mut inv_bdry_map = HashMap::new();
        for spx in self.simplexes.keys() {
            inv_bdry_map.insert(spx.clone(), HashSet::new());
        }

        for spx in self.simplexes.keys() {
            for bdry_spx in spx.proper_sub_simplices_not_null() {
                assert!(self.simplexes.contains_key(&bdry_spx));
                inv_bdry_map.get_mut(&bdry_spx).unwrap().insert(spx.clone());
            }
        }

        for (spx, info) in &self.simplexes {
            assert_eq!(&info.inv_bdry, inv_bdry_map.get(spx).unwrap());
        }

        //check that every pair of distinct simplexes intersect in the empty set
        LabelledSimplicialDisjointUnion::new_labelled_unchecked(
            self.ambient_space(),
            self.simplexes
                .iter()
                .map(|(spx, info)| (spx.clone(), info.label.clone()))
                .collect(),
        )
        .check();
    }
}

impl<'f, FS: OrderedRingSignature + FieldSignature> SimplicialComplex<'f, FS>
where
    FS::Set: Hash,
{
    pub fn interior_and_boundary(&self) -> LabelledSimplicialComplex<'f, FS, InteriorOrBoundary> {
        /*
        let n be the dimension of the space self is living in
         - every simplex of rank n is part of the interior
         - a simplex of rank n-1 is the facet of at most 2 simplices of rank n, and is part of the interior if and only if it is the facet of exactly 2 simplices of rank n
         - a simplex of rank less or equal to n-2 is part of the interior iff it is in the boundary of some strictly higher rank simplex AND every strictly higher rank simplex containing it as part of the boundary is part of the interior
        */

        let n = self.ambient_space().affine_dimension();

        let mut simplexes = HashMap::new();

        let mut all = self.simplexes.keys().cloned().collect::<Vec<_>>();
        all.sort_unstable_by_key(|s| std::cmp::Reverse(s.n())); //so that we process largest rank first
        for simplex in all {
            let r = simplex.n();
            if r == n {
                //rank n simplex is always part of the interior
                simplexes.insert(simplex, InteriorOrBoundary::Interior);
            } else {
                let inv_bdry = &self.simplexes.get(&simplex).unwrap().inv_bdry;
                if r == n - 1 {
                    //rank n-1 simplex is part of the boundary of at most 2 rank n simplices
                    //it is part of the boundary of the simplicial complex iff it is the boundary of exactly 2
                    match inv_bdry.len() {
                        0 | 1 => {
                            simplexes.insert(simplex, InteriorOrBoundary::Boundary);
                        }
                        2 => {
                            simplexes.insert(simplex, InteriorOrBoundary::Interior);
                        }
                        _ => panic!(
                            "rank n-1 simplex should be in the boundary of at most 2 rank n simplices"
                        ),
                    }
                } else {
                    //rank < n-1 simplex is part of the interior iff it is part of the boundary of at least one simplex and every such simplex is part of the interior
                    debug_assert!(r < n - 1);
                    if inv_bdry.is_empty() {
                        simplexes.insert(simplex, InteriorOrBoundary::Boundary);
                    } else if inv_bdry
                        .iter()
                        .all(|b| simplexes.get(b).unwrap() == &InteriorOrBoundary::Interior)
                    {
                        simplexes.insert(simplex, InteriorOrBoundary::Interior);
                    } else {
                        simplexes.insert(simplex, InteriorOrBoundary::Boundary);
                    }
                }
            }
        }

        LabelledSimplicialComplex::try_new_labelled(self.ambient_space(), simplexes).unwrap()
    }

    pub(crate) fn interior_raw(&self) -> PartialSimplicialComplex<'f, FS> {
        self.interior_and_boundary().interior()
    }

    pub fn interior(&self) -> PartialSimplicialComplex<'f, FS> {
        self.interior_raw().simplify()
    }

    pub(crate) fn boundary_raw(&self) -> SimplicialComplex<'f, FS> {
        self.interior_and_boundary()
            .boundary()
            .try_into_simplicial_complex()
            .unwrap()
    }

    pub fn boundary(&self) -> SimplicialComplex<'f, FS> {
        self.boundary_raw().simplify()
    }
}

/*
Input:
    A list of oriented simplicies which join to form a closed region of space
    with negative side inside and positive side outside which join

    A list of simplicies filling the interior of the region, each labelled

Output:
    Figure out whether the region can be filled in by fanning out from some point such that the labelling of space is preserved
    If it can't: return None
    If it can: return the simplicies to use to fill in the interior region

*/

fn simplify_in_region<'f, FS: OrderedRingSignature + FieldSignature, T: Eq + Clone + Send + Sync>(
    space: AffineSpace<'f, FS>,
    boundary_facets: Vec<OrientedSimplex<'f, FS>>,
    labelled_interior: HashMap<Simplex<'f, FS>, T>,
) -> Option<HashMap<Simplex<'f, FS>, T>>
where
    FS::Set: Hash,
{
    let labelled_interior =
        LabelledSimplicialDisjointUnion::new_labelled_unchecked(space, labelled_interior);

    let interior_uniform_label = {
        let labels = labelled_interior
            .labelled_simplexes()
            .into_values()
            .collect::<Vec<_>>();
        let first = *labels.first()?;
        if labels.iter().all(|label| *label == first) {
            Some(first)
        } else {
            None
        }
    };

    for spx in &boundary_facets {
        debug_assert_eq!(spx.ambient_space(), space);
    }

    let mut boundary_points: HashMap<Vector<'f, FS>, Vec<usize>> = HashMap::new();
    for (idx, spx) in boundary_facets.iter().enumerate() {
        for pt in spx.simplex().points() {
            if boundary_points.contains_key(pt) {
                boundary_points.get_mut(pt).unwrap().push(idx);
            } else {
                boundary_points.insert(pt.clone(), vec![idx]);
            }
        }
    }

    'BOUNDARY_LOOP: for (boundary_point, adjacent_facets) in boundary_points {
        let mut nonadjacent_facets = (0..boundary_facets.len()).collect::<HashSet<_>>();
        for idx in &adjacent_facets {
            nonadjacent_facets.remove(idx);
        }

        if nonadjacent_facets.iter().all(|idx| {
            match boundary_facets[*idx].classify_point(&boundary_point) {
                OrientationSide::Positive | OrientationSide::Neutral => false,
                OrientationSide::Negative => true,
            }
        }) {
            let mut nonadjacent_simplexes = HashSet::new();
            for idx in nonadjacent_facets {
                for spx in boundary_facets[idx].simplex().sub_simplices_not_null() {
                    nonadjacent_simplexes.insert(spx);
                }
            }
            for idx in adjacent_facets {
                for spx in boundary_facets[idx].simplex().sub_simplices_not_null() {
                    nonadjacent_simplexes.remove(&spx);
                }
            }

            let labelled_new_interior = LabelledSimplicialDisjointUnion::new_labelled_unchecked(
                space,
                nonadjacent_simplexes
                    .into_iter()
                    .enumerate()
                    .map(|(i, spx)| {
                        (
                            {
                                let mut points = spx.points().clone();
                                points.push(boundary_point.clone());
                                spx.ambient_space().simplex(points).unwrap()
                            },
                            i,
                        )
                    })
                    .collect(),
            );

            let filler = if let Some(interior_label) = interior_uniform_label {
                labelled_new_interior.apply_label_function(|_| interior_label.clone())
            } else {
                let interior_intersection = LabelledSimplicialDisjointUnion::intersect_raw(
                    &labelled_interior,
                    &labelled_new_interior,
                );

                debug_assert!(
                    LabelledSimplicialDisjointUnion::subtract_raw(
                        &labelled_interior,
                        &labelled_new_interior,
                    )
                    .labelled_simplexes()
                    .is_empty()
                );

                debug_assert!(
                    LabelledSimplicialDisjointUnion::subtract_raw(
                        &labelled_new_interior,
                        &labelled_interior,
                    )
                    .labelled_simplexes()
                    .is_empty()
                );

                let mut i_to_label_map = HashMap::new();
                for (_, (label, i)) in interior_intersection.labelled_simplexes() {
                    match i_to_label_map.entry(i) {
                        std::collections::hash_map::Entry::Occupied(occupied_entry) => {
                            if *occupied_entry.get() != label {
                                continue 'BOUNDARY_LOOP;
                            }
                        }
                        std::collections::hash_map::Entry::Vacant(vacant_entry) => {
                            vacant_entry.insert(label);
                        }
                    }
                }

                labelled_new_interior
                    .apply_label_function(|label| (*i_to_label_map.get(label).unwrap()).clone())
            };

            return Some(filler.into_labelled_simplexes());
        }
    }
    None
}

impl<'f, FS: OrderedRingSignature + FieldSignature, T: Eq + Clone + Send + Sync>
    LabelledSimplicialComplex<'f, FS, T>
where
    FS::Set: Hash,
{
    pub fn simplify(mut self) -> Self {
        //go through each point
        //compute its star
        //enter the affine subspace spanned by its star
        //compute its link as oriented simplices
        //if point is part of the link then no simplification can be made, so move on
        //check whether any point of the link is in the interior with respect to every boundary of the link
        //if such a point exists, it can be used to fill in the star in a simpler way by fanning out

        let mut pts_todo = HashSet::new();
        for simplex in self.simplexes.keys() {
            for pt in simplex.points() {
                pts_todo.insert(pt.clone());
            }
        }

        while !pts_todo.is_empty() {
            let pt = {
                let mut pts_todo_iter = pts_todo.into_iter();
                let pt = pts_todo_iter.next().unwrap();
                pts_todo = pts_todo_iter.collect();
                pt
            };

            let pt_spx = self.ambient_space().simplex(vec![pt.clone()]).unwrap();
            let (star, link) = {
                let mut star = self.simplexes.get(&pt_spx).unwrap().inv_bdry.clone();
                star.insert(pt_spx.clone());

                let mut nbd = HashSet::new();
                for spx in &star {
                    for bdry in spx.sub_simplices_not_null() {
                        nbd.insert(bdry);
                    }
                }

                let mut link = nbd.clone();
                for spx in &star {
                    link.remove(spx);
                }

                debug_assert_eq!(star.len() + link.len(), nbd.len());
                for link_spx in &link {
                    debug_assert!(self.simplexes.contains_key(link_spx));
                }

                (star, link)
            };

            let link_points = {
                let mut link_points: Vec<Vector<'f, FS>> = vec![];
                for spx in &link {
                    for p in spx.points() {
                        link_points.push(p.clone());
                    }
                }
                link_points
            };

            let nbd_points = {
                let mut nbd_points = link_points.clone();
                nbd_points.push(pt.clone());
                nbd_points
            };

            let nbd_affine_subspace = EmbeddedAffineSubspace::new_affine_span(
                self.ambient_space(),
                nbd_points.iter().collect(),
            );

            let nbd_points_img = nbd_points
                .iter()
                .map(|pt| nbd_affine_subspace.unembed_point(pt).unwrap())
                .collect::<Vec<_>>();

            let pt_img = nbd_affine_subspace.unembed_point(&pt).unwrap();
            let pt_img_spx = nbd_affine_subspace
                .embedded_space()
                .simplex(vec![pt_img.clone()])
                .unwrap();

            let star_img = star
                .iter()
                .map(|s| {
                    (
                        nbd_affine_subspace.unembed_simplex(s).unwrap(),
                        self.simplexes.get(s).unwrap().label.clone(),
                    )
                })
                .collect::<HashMap<_, _>>();

            let link_img = link
                .iter()
                .map(|s| nbd_affine_subspace.unembed_simplex(s).unwrap())
                .collect::<HashSet<_>>();

            let nbd = LabelledSimplicialComplex::<'f, FS, T>::try_new(
                nbd_affine_subspace.embedded_space(),
                {
                    let mut simplexes = HashSet::new();
                    simplexes.extend(star_img.keys().cloned());
                    simplexes.extend(link_img.clone());
                    simplexes
                },
            )
            .unwrap();
            let nbd_interior = nbd.interior_raw().into_simplexes();

            if !nbd_interior.contains(&pt_img_spx) {
                /*
                pt is on the boundary of nbd and nbd looks something like this

                    l     l      l
                     +----------+
                    / \\__       \
                l  /   \  \__ s   \ l
                  /   s \    \__   \
                 /       \      \__ \
                +---------+---------+
                r    b    p    b    r

                where
                    p = point
                    b = boundary = intersection of star and ndb.boundary
                    r = rim = closure of boundary minus boundary
                    l = semilink = link minus rim
                    s = semistar = star minus boundary

                so the idea here is
                    simplify the boundary by filling in the rim to replace the boundary
                    then simplify the rest by filling in the new boundary and the link to replace the star
                */

                let boundary_img = star_img
                    .iter()
                    .filter(|(spx, _)| !nbd_interior.contains(spx))
                    .collect::<HashMap<_, _>>();
                let semistar_img = star_img
                    .iter()
                    .filter(|(spx, _)| nbd_interior.contains(spx))
                    .collect::<HashMap<_, _>>();

                let boundary = boundary_img
                    .keys()
                    .map(|spx| nbd_affine_subspace.embed_simplex(spx))
                    .collect::<Vec<_>>();
                let semistar = semistar_img
                    .keys()
                    .map(|spx| nbd_affine_subspace.embed_simplex(spx))
                    .collect::<Vec<_>>();

                debug_assert_eq!(boundary.len() + semistar.len(), star.len());

                let mut boundary_img_points = HashSet::new();
                for spx in boundary_img.keys() {
                    for p in spx.points() {
                        boundary_img_points.insert(p);
                    }
                }
                let nbd_boundary_affine_subspace = EmbeddedAffineSubspace::new_affine_span(
                    nbd_affine_subspace.embedded_space(),
                    boundary_img_points.into_iter().collect(),
                );
                debug_assert!(
                    nbd_boundary_affine_subspace
                        .embedded_space()
                        .affine_dimension()
                        <= nbd_affine_subspace.embedded_space().affine_dimension()
                );
                if nbd_boundary_affine_subspace
                    .embedded_space()
                    .affine_dimension()
                    + 1
                    == nbd_affine_subspace.embedded_space().affine_dimension()
                {
                    let ref_point_img = {
                        let mut ref_point_img = None;
                        for pt in &nbd_points_img {
                            if nbd_boundary_affine_subspace.unembed_point(pt).is_none() {
                                ref_point_img = Some(pt.clone());
                                break;
                            }
                        }
                        ref_point_img.unwrap()
                    };
                    let oriented_hyperplane = OrientedSimplex::new_with_negative_point(
                        nbd_boundary_affine_subspace.ambient_space(),
                        nbd_boundary_affine_subspace.get_embedding_points().clone(),
                        &ref_point_img,
                    )
                    .unwrap();
                    for pt in &nbd_points_img {
                        debug_assert!(
                            oriented_hyperplane.classify_point(pt) != OrientationSide::Positive
                        );
                    }

                    let rim_img = {
                        let mut rim_img = HashSet::new();
                        for spx in boundary_img.keys() {
                            for bspx in spx.sub_simplices_not_null() {
                                rim_img.insert(bspx);
                            }
                        }
                        for spx in boundary_img.keys() {
                            rim_img.remove(spx);
                        }
                        rim_img
                    };

                    let pt_img_img = nbd_boundary_affine_subspace.unembed_point(&pt_img).unwrap();

                    let rim_img_img = rim_img
                        .iter()
                        .map(|spx| {
                            OrientedSimplex::new_with_negative_point(
                                nbd_boundary_affine_subspace.embedded_space(),
                                nbd_boundary_affine_subspace
                                    .unembed_simplex(spx)
                                    .unwrap()
                                    .points()
                                    .clone(),
                                &pt_img_img,
                            )
                            .unwrap()
                        })
                        .collect::<Vec<_>>();

                    let boundary_img_img = boundary_img
                        .iter()
                        .map(|(spx, label)| {
                            (
                                nbd_boundary_affine_subspace.unembed_simplex(spx).unwrap(),
                                *label,
                            )
                        })
                        .collect::<Vec<_>>();

                    if let Some(new_boundary_img_img) = simplify_in_region(
                        nbd_boundary_affine_subspace.embedded_space(),
                        rim_img_img,
                        boundary_img_img
                            .iter()
                            .map(|(spx, label)| (spx.clone(), (*label).clone()))
                            .collect(),
                    ) {
                        let new_boundary_img = new_boundary_img_img
                            .iter()
                            .map(|(spx, label)| {
                                (nbd_boundary_affine_subspace.embed_simplex(spx), label)
                            })
                            .collect::<Vec<_>>();

                        let sphere_img = {
                            let mut sphere_img = vec![];
                            for (spx, _) in &new_boundary_img {
                                if spx.n() + 1
                                    == nbd_affine_subspace.embedded_space().affine_dimension()
                                {
                                    sphere_img.push(
                                        OrientedSimplex::new_with_negative_point(
                                            nbd_affine_subspace.embedded_space(),
                                            spx.points().clone(),
                                            &ref_point_img,
                                        )
                                        .unwrap(),
                                    );
                                }
                            }
                            for spx in &link_img {
                                if spx.n() + 1
                                    == nbd_affine_subspace.embedded_space().affine_dimension()
                                {
                                    sphere_img.push(
                                        OrientedSimplex::new_with_negative_point(
                                            nbd_affine_subspace.embedded_space(),
                                            spx.points().clone(),
                                            &pt_img,
                                        )
                                        .unwrap(),
                                    );
                                }
                            }
                            sphere_img
                        };

                        if let Some(new_star_img) = simplify_in_region(
                            nbd_affine_subspace.embedded_space(),
                            sphere_img,
                            semistar_img
                                .into_iter()
                                .map(|(spx, label)| (spx.clone(), label.clone()))
                                .collect(),
                        ) {
                            self.remove_simplexes_unchecked(star.into_iter().collect());
                            self.add_simplexes_unchecked(
                                new_boundary_img
                                    .into_iter()
                                    .map(|(spx_img, label)| {
                                        (nbd_affine_subspace.embed_simplex(&spx_img), label.clone())
                                    })
                                    .collect(),
                            );
                            self.add_simplexes_unchecked(
                                new_star_img
                                    .into_iter()
                                    .map(|(spx_img, label)| {
                                        (nbd_affine_subspace.embed_simplex(&spx_img), label.clone())
                                    })
                                    .collect(),
                            );
                            pts_todo.extend(link_points);
                        }
                    }
                }
            } else {
                /*
                pt is in the interior and nbd looks something like

                          l
                     +---------+
                    / \       / \
                l  /   \  s  /   \ l
                  /  s  \   /  s  \
                 /       \ /       \
                +---------p---------+
                 \       / \       /
                  \  s  /   \  s  /
                l  \   /  s  \   / l
                    \ /       \ /
                     +---------+
                          l

                where
                    p = point
                    s = star
                    l = link
                */

                let boundary_img = link_img
                    .iter()
                    .filter(|spx| {
                        let n = spx.n();
                        let a = nbd_affine_subspace.embedded_space().affine_dimension();
                        if n >= a {
                            unreachable!()
                        } else if n + 1 == a {
                            true
                        } else {
                            debug_assert!(n + 1 < a);
                            false
                        }
                    })
                    .map(|spx| {
                        OrientedSimplex::new_with_negative_point(
                            nbd_affine_subspace.embedded_space(),
                            spx.points().clone(),
                            &pt_img,
                        )
                        .unwrap()
                    })
                    .collect();

                if let Some(new_star_img) = simplify_in_region(
                    nbd_affine_subspace.embedded_space(),
                    boundary_img,
                    star_img
                        .iter()
                        .map(|(spx, label)| (spx.clone(), label.clone()))
                        .collect(),
                ) {
                    self.remove_simplexes_unchecked(star.into_iter().collect());
                    self.add_simplexes_unchecked(
                        new_star_img
                            .into_iter()
                            .map(|(spx_img, label)| {
                                (nbd_affine_subspace.embed_simplex(&spx_img), label)
                            })
                            .collect(),
                    );
                    pts_todo.extend(link_points);
                }
            }
        }

        #[cfg(debug_assertions)]
        self.check();

        self
    }

    //remove simplexes and remove them from the inverse boundary of any others
    //self may not be in a valid state after this operation
    fn remove_simplexes_unchecked(&mut self, simplexes: Vec<Simplex<'f, FS>>) {
        for spx in &simplexes {
            for bdry_spx in spx.proper_sub_simplices_not_null() {
                if let Some(info) = self.simplexes.get_mut(&bdry_spx) {
                    info.inv_bdry.remove(spx);
                }
            }
        }
        for spx in &simplexes {
            self.simplexes.remove(spx);
        }
    }

    pub fn remove_simplexes(&mut self, simplexes: Vec<Simplex<'f, FS>>) {
        self.remove_simplexes_unchecked(simplexes);
        #[cfg(debug_assertions)]
        self.check();
    }

    //add the given simplexes and add them to the inverse boundary map on anything on their boundaries
    //must be added together to cover the case where there are mutual boundary relations
    //self may not be in a valid state after this operation
    fn add_simplexes_unchecked(&mut self, simplexes: Vec<(Simplex<'f, FS>, T)>) {
        for (spx, label) in &simplexes {
            self.simplexes.insert(
                spx.clone(),
                SCSpxInfo {
                    inv_bdry: HashSet::new(),
                    label: label.clone(),
                },
            );
        }
        for (spx, _) in simplexes {
            for bdry_spx in spx.proper_sub_simplices_not_null() {
                self.simplexes
                    .get_mut(&bdry_spx)
                    .unwrap()
                    .inv_bdry
                    .insert(spx.clone());
            }
        }
    }

    pub fn add_simplexes(&mut self, simplexes: Vec<(Simplex<'f, FS>, T)>) {
        self.add_simplexes_unchecked(simplexes);
        #[cfg(debug_assertions)]
        self.check();
    }
}