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
use std::collections::{BTreeSet, BTreeMap};
use l_group_formulas::short_free_group_term::*;
use l_group_formulas::literal::Literal;
use l_group_formulas::Term;

/// Represents the closed ball of radius 3 around e in the Cayley
/// graph of a free group with respect to the standard free generating set.
/// 
/// # Examples
/// Basic usage:
/// ```
/// use truncated_free_groups::truncated_subgroup::TruncatedSubgroup;
/// use l_group_formulas::short_free_group_term::ShortFreeGroupTerm;
/// use l_group_formulas::literal::Literal;
/// use std::collections::BTreeSet;
/// let s = ShortFreeGroupTerm::from("xY");
/// let t = ShortFreeGroupTerm::from("yz");
/// let mut set = BTreeSet::new();
/// set.insert(s);
/// set.insert(t);
/// let mut gens = BTreeSet::new();
/// gens.insert(Literal::from('x'));
/// gens.insert(Literal::from('y'));
/// gens.insert(Literal::from('z'));
/// let truncated = TruncatedSubgroup::new(Box::new(set), gens, false, false, false);
/// let mut expected = Box::new(BTreeSet::new());
/// expected.insert(s);
/// expected.insert(t);
/// expected.insert(ShortFreeGroupTerm::from("xz"));
/// assert_eq!(expected, truncated.elements.clone());
/// ```
#[derive(Debug)]
pub struct TruncatedSubgroup {
    pub elements:            Box<BTreeSet<ShortFreeGroupTerm>>,
    // pub gens_of_ambient_group:   BTreeSet<Literal>,
    starts_with_single:      Box<BTreeMap<Literal, BTreeSet<ShortFreeGroupTerm>>>,
    previously_new:          BTreeSet<ShortFreeGroupTerm>,
    ends_with_single:        Box<BTreeMap<Literal, BTreeSet<ShortFreeGroupTerm>>>,
    starts_with_pair:        Box<BTreeMap<(Literal, Literal), BTreeSet<ShortFreeGroupTerm>>>,
    ends_with_pair:          Box<BTreeMap<(Literal, Literal), BTreeSet<ShortFreeGroupTerm>>>,
    length_one:              Box<BTreeSet<ShortFreeGroupTerm>>,
    length_two:              Box<BTreeSet<ShortFreeGroupTerm>>,
    length_three:            Box<BTreeSet<ShortFreeGroupTerm>>,
    verbose:                 bool,
    break_at_identity:       bool
}

impl TruncatedSubgroup {
    pub fn new(
        elements:          Box<BTreeSet<ShortFreeGroupTerm>>, 
        gens:              BTreeSet<Literal>,
        closed:            bool,
        break_at_identity: bool,
        verbose:           bool
    ) -> TruncatedSubgroup {
        // close gens under inversion
        let mut gens_of_ambient_group = BTreeSet::new();
        for g in gens {
            gens_of_ambient_group.insert(g);
            gens_of_ambient_group.insert(g.inverse());
        }

        // initialize categories
        let mut length_one   = Box::new(BTreeSet::new());
        let mut length_two   = Box::new(BTreeSet::new());
        let mut length_three = Box::new(BTreeSet::new());

        let mut starts_with_single = Box::new(BTreeMap::new());
        let mut starts_with_pair   = Box::new(BTreeMap::new());
        let mut ends_with_single   = Box::new(BTreeMap::new());
        let mut ends_with_pair     = Box::new(BTreeMap::new());

        for g in &gens_of_ambient_group {
            starts_with_single.insert(*g, BTreeSet::new());
            ends_with_single.insert(*g, BTreeSet::new());
            for h in &gens_of_ambient_group {
                starts_with_pair.insert((*g, *h), BTreeSet::new());
                ends_with_pair.insert((*g, *h), BTreeSet::new());
            }
        }

        for y in &*elements {
            match (y.left, y.mid, y.right) {
                (Some(a), None, None) => {
                    length_one.insert(*y);
                    starts_with_single.get_mut(&a).unwrap().insert(*y);
                    ends_with_single.get_mut(&a).unwrap().insert(*y);
                },
                (Some(a), Some(b), None) => {
                    length_two.insert(*y);
                    starts_with_single.get_mut(&a).unwrap().insert(*y);
                    ends_with_single.get_mut(&b).unwrap().insert(*y);
                    starts_with_pair.get_mut(&(a, b)).unwrap().insert(*y);
                    ends_with_pair.get_mut(&(a, b)).unwrap().insert(*y);
                },
                (Some(a), Some(b), Some(c)) => {
                    length_three.insert(*y);
                    starts_with_single.get_mut(&a).unwrap().insert(*y);
                    ends_with_single.get_mut(&c).unwrap().insert(*y);
                    starts_with_pair.get_mut(&(a, b)).unwrap().insert(*y);
                    ends_with_pair.get_mut(&(b, c)).unwrap().insert(*y);
                }
                _ => {} // is identity
            };
        }

        let previously_new: BTreeSet<ShortFreeGroupTerm>;
        if !closed {
            previously_new = *elements.clone()
        } else {
            previously_new = BTreeSet::new();
        }

        let mut sub = TruncatedSubgroup {
            elements:              elements.clone(),
            // gens_of_ambient_group: gens_of_ambient_group,
            previously_new:        previously_new,
            starts_with_single:    starts_with_single,
            starts_with_pair:      starts_with_pair,
            ends_with_single:      ends_with_single,
            ends_with_pair:        ends_with_pair,
            length_one:            length_one,
            length_two:            length_two,
            length_three:          length_three,
            break_at_identity:     break_at_identity,
            verbose:               verbose
        };
        if !closed { sub.close(); }
        return sub;
    }
}

pub trait Insert {
    /// Inserts `element` and returns what was newly added.
    fn insert(&mut self, element: ShortFreeGroupTerm) -> BTreeSet<ShortFreeGroupTerm>;
}

impl Insert for TruncatedSubgroup {
    fn insert(&mut self, element: ShortFreeGroupTerm) -> BTreeSet<ShortFreeGroupTerm> {
        self.elements.insert(element);
        self.previously_new.insert(element);
        return self.close();
    }
}

trait Closable {
    fn close(&mut self) -> BTreeSet<ShortFreeGroupTerm>;
}

impl Closable for TruncatedSubgroup {
    fn close(&mut self) -> BTreeSet<ShortFreeGroupTerm> {
        let mut output = BTreeSet::new();
        let mut found_new_element = true;
        let mut new_elements_buffer: BTreeSet<ShortFreeGroupTerm> = self.previously_new.clone();
        /*if self.verbose { 
            println!("\nClosing under multiplication."); 
        }*/
        while found_new_element {
            /*if self.verbose {
                println!("Currently {} elements, {} of which are not checked.", 
                         self.elements.len(), 
                         new_elements_buffer.len());
            }*/

            if self.break_at_identity {
                if self.elements.contains(&ShortFreeGroupTerm::new(None, None, None)) {
                    return output;
                }
            }

            found_new_element = false;
            for y in &new_elements_buffer {
                self.elements.insert(y.clone());
                output.insert(y.clone());
                match (y.left, y.mid, y.right) {
                    (Some(a), None, None) => {
                        self.length_one.insert(*y);
                        self.starts_with_single.get_mut(&a).unwrap().insert(*y);
                        self.ends_with_single.get_mut(&a).unwrap().insert(*y);
                    },
                    (Some(a), Some(b), None) => {
                        self.length_two.insert(*y);
                        self.starts_with_single.get_mut(&a).unwrap().insert(*y);
                        self.ends_with_single.get_mut(&b).unwrap().insert(*y);
                        self.starts_with_pair.get_mut(&(a, b)).unwrap().insert(*y);
                        self.ends_with_pair.get_mut(&(a, b)).unwrap().insert(*y);
                    },
                    (Some(a), Some(b), Some(c)) => {
                        self.length_three.insert(*y);
                        self.starts_with_single.get_mut(&a).unwrap().insert(*y);
                        self.ends_with_single.get_mut(&c).unwrap().insert(*y);
                        self.starts_with_pair.get_mut(&(a, b)).unwrap().insert(*y);
                        self.ends_with_pair.get_mut(&(b, c)).unwrap().insert(*y);
                    }
                    _ => {} // is identity
                };
            }
            self.previously_new = new_elements_buffer.clone();
            new_elements_buffer = BTreeSet::new();
            for x in &self.previously_new {
                match x.len() {
                    0 => {},
                    1 => {
                        // x * y is shorter than 3 if either y is shorter 
                        // than 2 or there is cancellation, i.e., y begins
                        // with x^-1. Same for y * x, except then y ends
                        // with x^-1.
                        for y in &*self.length_one {
                            let maybe_new = *x * *y;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                            let maybe_new = *y * *x;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                        }
                        for y in &*self.length_two {
                            let maybe_new = *x * *y;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                            let maybe_new = *y * *x;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                        }
                        let lit = x.left.unwrap();
                        let cancelling_candidates_start = self.starts_with_single.get(&lit.inverse()).unwrap();
                        for y in cancelling_candidates_start {
                            let maybe_new = *x * *y;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                        }
                        let cancelling_candidates_end = self.ends_with_single.get(&lit.inverse()).unwrap();
                        for y in cancelling_candidates_end {
                            let maybe_new = *y * *x;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                        }
                    },
                    2 => {
                        // if y has length 1, then x * y and y * x are of length <= 3
                        // if y has length 2 or 3, then 
                        //      x * y has length <= 3 if y starts with x.mid.inverse()
                        //      y * x has length <= 3 if y ends with x.left.inverse()
                        for y in &*self.length_one {
                            let maybe_new = *x * *y;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                            let maybe_new = *y * *x;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                        }
                        let cancelling_candidates_start = self.starts_with_single.get(&x.mid.unwrap().inverse()).unwrap();
                        for y in cancelling_candidates_start {
                            let maybe_new = *x * *y;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                        }
                        let cancelling_candidates_end = self.ends_with_single.get(&x.left.unwrap().inverse()).unwrap();
                        for y in cancelling_candidates_end {
                            let maybe_new = *y * *x;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                        }
                    },
                    3 => {
                        // if y has length 1 or 2, then x * y is of length <= 3 if y.left == x.right.inverse(),
                        // and                     y * x is of length <= 3 if y.(left/mid) == x.left.inverse().
                        // if y has length 3, then x * y is of length <= 3 if y.left == x.right.inverse() && y.mid == x.mid.inverse(),
                        //                                  i.e., y starts with (x.right.inverse(), x.mid.inverse())
                        // and                     y * x is of length <= 3 if y.right == x.left.inverse() && y.mid == x.mid.inverse(),
                        //                                  i.e., y ends with (x.mid.inverse(), x.left.inverse())
                        for y in &*self.length_one {
                            if y.left.unwrap() == x.right.unwrap().inverse() {
                                let maybe_new = *x * *y;
                                if !self.elements.contains(&maybe_new) {
                                    found_new_element = true;
                                    new_elements_buffer.insert(maybe_new);
                                }
                            }
                            if y.left.unwrap() == x.left.unwrap().inverse() {
                                let maybe_new = *y * *x;
                                if !self.elements.contains(&maybe_new) {
                                    found_new_element = true;
                                    new_elements_buffer.insert(maybe_new);
                                }
                            }
                        }
                        for y in &*self.length_two {
                            if y.left.unwrap() == x.right.unwrap().inverse() {
                                let maybe_new = *x * *y;
                                if !self.elements.contains(&maybe_new) {
                                    found_new_element = true;
                                    new_elements_buffer.insert(maybe_new);
                                }
                            }
                            if y.mid.unwrap() == x.left.unwrap().inverse() {
                                let maybe_new = *y * *x;
                                if !self.elements.contains(&maybe_new) {
                                    found_new_element = true;
                                    new_elements_buffer.insert(maybe_new);
                                }
                            }
                        }
                        let cancelling_candidates_start = self.starts_with_pair.get(&(x.right.unwrap().inverse(), x.mid.unwrap().inverse())).unwrap();
                        for y in cancelling_candidates_start {
                            let maybe_new = *x * *y;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                        }
                        let cancelling_candidates_end = self.ends_with_pair.get(&(x.mid.unwrap().inverse(), x.left.unwrap().inverse())).unwrap();
                        for y in cancelling_candidates_end {
                            let maybe_new = *y * *x;
                            if !self.elements.contains(&maybe_new) {
                                found_new_element = true;
                                new_elements_buffer.insert(maybe_new);
                            }
                        }
                    },
                    _ => { panic!("Invalid short free group term!") }
                };
            }
        }
        return output;
    }
}