odis 2026.4.0

Formal Concept Analysis algorithms and data structures
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
use std::{
    collections::HashSet,
    io::{BufRead, Error},
    num::ParseIntError,
};

use bit_set::{self, BitSet};

/// Error returned when parsing a formal context from bytes fails.
#[derive(Debug)]
pub enum FormatError {
    /// Underlying I/O error while reading the context file.
    IoError(Error),
    /// An integer field in the header could not be parsed.
    ParseError(ParseIntError),
    /// The file does not conform to the expected Burmeister (.cxt) format.
    InvalidFormat,
}

impl From<Error> for FormatError {
    fn from(err: Error) -> FormatError {
        FormatError::IoError(err)
    }
}

impl From<ParseIntError> for FormatError {
    fn from(err: ParseIntError) -> FormatError {
        FormatError::ParseError(err)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// Formal context: a set of *objects*, a set of *attributes*, and a binary incidence
/// relation. Operations (extent, intent, closure) are available in labelled form
/// (on `T` values) and index-based form (on [`bit_set::BitSet`] indices).
///
/// # Examples
///
/// ```
/// use odis::FormalContext;
///
/// // Build a small context from Burmeister bytes: objects {a, b}, attributes {x, y}
/// let ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n2\n2\n\na\nb\nx\ny\nXX\nX.\n").unwrap();
/// assert_eq!(ctx.objects.len(), 2);
/// assert_eq!(ctx.attributes.len(), 2);
/// ```
pub struct FormalContext<T> {
    /// The name of the formal context (Burmeister format line 2).
    pub name: String,
    /// The objects (rows) of the context table.
    pub objects: Vec<T>,
    /// The attributes (columns) of the context table.
    pub attributes: Vec<T>,
    /// The incidence relation: `(g, m)` is present iff object `g` has attribute `m` (index-based).
    pub incidence: HashSet<(usize, usize)>,
    // Precomputed derivations for single objects/attributes for performance
    pub(crate) atomic_object_derivations: Vec<BitSet>,
    pub(crate) atomic_attribute_derivations: Vec<BitSet>,
}

impl<T> Default for FormalContext<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> FormalContext<T> {
    fn construct(name: String, objects: Vec<T>, attributes: Vec<T>, incidence: HashSet<(usize, usize)>) -> Self {
        let mut atomic_object_derivations =
            vec![BitSet::with_capacity(attributes.len()); objects.len()];
        let mut atomic_attribute_derivations =
            vec![BitSet::with_capacity(objects.len()); attributes.len()];
        for &(g, m) in incidence.iter() {
            atomic_object_derivations[g].insert(m);
            atomic_attribute_derivations[m].insert(g);
        }

        FormalContext {
            name,
            objects,
            attributes,
            incidence,
            atomic_object_derivations,
            atomic_attribute_derivations,
        }
    }

    /// Creates an empty formal context.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    ///
    /// let ctx = FormalContext::<String>::new();
    /// assert_eq!(ctx.objects.len(), 0);
    /// assert_eq!(ctx.attributes.len(), 0);
    /// ```
    pub fn new() -> Self {
        Self::construct(String::new(), Vec::new(), Vec::new(), HashSet::new())
    }

    /// Reads a formal context in Burmeister format (.cxt).
    ///
    /// Returns `Err(FormatError)` if the byte slice is not valid Burmeister format.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    ///
    /// let cxt = b"B\n\n2\n2\n\ncat\ndog\nlegs\nfur\nXX\nX.\n";
    /// let ctx: FormalContext<String> = FormalContext::<String>::from(cxt).unwrap();
    /// assert!(ctx.objects.contains(&"cat".to_string()));
    /// assert!(ctx.attributes.contains(&"legs".to_string()));
    /// ```
    pub fn from(contents: &[u8]) -> Result<FormalContext<String>, FormatError> {
        let mut lines = contents.lines();

        if lines.next().ok_or(FormatError::InvalidFormat)?? != "B" {
            return Err(FormatError::InvalidFormat);
        }

        let name = lines.next().ok_or(FormatError::InvalidFormat)??;

        let object_count: usize = lines.next().ok_or(FormatError::InvalidFormat)??.parse()?;
        let attribute_count: usize = lines.next().ok_or(FormatError::InvalidFormat)??.parse()?;

        lines.next().ok_or(FormatError::InvalidFormat)??;

        let mut objects: Vec<String> = Vec::with_capacity(object_count);
        for _ in 0..object_count {
            objects.push(lines.next().ok_or(FormatError::InvalidFormat)??);
        }

        let mut attributes: Vec<String> = Vec::with_capacity(attribute_count);
        for _ in 0..attribute_count {
            attributes.push(lines.next().ok_or(FormatError::InvalidFormat)??);
        }

        let mut incidence: HashSet<(usize, usize)> = HashSet::new();
        for g in 0..object_count {
            let line = lines.next().ok_or(FormatError::InvalidFormat)??;
            for (m, x) in line.chars().enumerate() {
                if x == 'X' || x == 'x' {
                    incidence.insert((g, m));
                }
            }
        }

        Ok(FormalContext::construct(name, objects, attributes, incidence))
    }

    // --- Index Methods ---

    /// Computes the extent (set of objects) for a given set of attribute indices.
    ///
    /// Index-based variant of [`FormalContext::extent`]. Operates on
    /// [`bit_set::BitSet`] indices directly, bypassing label translation.
    /// Prefer [`FormalContext::extent`] unless working in a performance-critical
    /// inner loop.
    ///
    /// See also: [`FormalContext::extent`]
    pub fn index_extent(&self, attributes: &BitSet) -> BitSet {
        match attributes.len() {
            0 => (0..self.objects.len()).collect(),
            1 => self.atomic_attribute_derivations[attributes.iter().next().unwrap()].clone(),
            _ => {
                let mut iter = attributes.iter();
                let mut result = self.atomic_attribute_derivations[iter.next().unwrap()].clone();
                for n in iter {
                    result.intersect_with(&self.atomic_attribute_derivations[n]);
                }
                result
            }
        }
    }

    /// Computes the intent (set of attributes) for a given set of object indices.
    ///
    /// Index-based variant of [`FormalContext::intent`]. Prefer
    /// [`FormalContext::intent`] unless working in a performance-critical inner loop.
    ///
    /// See also: [`FormalContext::intent`]
    pub fn index_intent(&self, objects: &BitSet) -> BitSet {
        match objects.len() {
            0 => (0..self.attributes.len()).collect(),
            1 => self.atomic_object_derivations[objects.iter().next().unwrap()].clone(),
            _ => {
                let mut iter = objects.iter();
                let mut result = self.atomic_object_derivations[iter.next().unwrap()].clone();
                for n in iter {
                    result.intersect_with(&self.atomic_object_derivations[n]);
                }
                result
            }
        }
    }

    /// Computes the attribute hull (closure) for a given set of attribute indices.
    ///
    /// Index-based variant of [`FormalContext::attribute_hull`].
    ///
    /// See also: [`FormalContext::attribute_hull`]
    pub fn index_attribute_hull(&self, attributes: &BitSet) -> BitSet {
        let extent = self.index_extent(attributes);
        self.index_intent(&extent)
    }

    /// Computes the object hull (closure) for a given set of object indices.
    ///
    /// Index-based variant of [`FormalContext::object_hull`].
    ///
    /// See also: [`FormalContext::object_hull`]
    pub fn index_object_hull(&self, objects: &BitSet) -> BitSet {
        let intent = self.index_intent(objects);
        self.index_extent(&intent)
    }

    // --- High-Level Methods (Sets of T) ---

    /// Computes the extent for a given set of attributes.
    ///
    /// Returns the set of all objects that possess every attribute in `attributes`.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    /// use std::collections::HashSet;
    ///
    /// let ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n2\n2\n\ncat\ndog\nx\ny\nXX\nX.\n").unwrap();
    /// let extent = ctx.extent(&HashSet::from(["x".to_string()]));
    /// assert!(extent.contains("cat"));
    /// assert!(extent.contains("dog"));
    /// ```
    pub fn extent(&self, attributes: &HashSet<T>) -> HashSet<T>
    where
        T: Eq + std::hash::Hash + Clone,
    {
        let mut bits = BitSet::new();
        for attr in attributes {
            if let Some(idx) = self.attributes.iter().position(|a| a == attr) {
                bits.insert(idx);
            }
        }
        let result_bits = self.index_extent(&bits);
        result_bits
            .iter()
            .map(|idx| self.objects[idx].clone())
            .collect()
    }

    /// Computes the intent for a given set of objects.
    ///
    /// Returns the set of all attributes that every object in `objects` possesses.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    /// use std::collections::HashSet;
    ///
    /// let ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n2\n2\n\ncat\ndog\nx\ny\nXX\nX.\n").unwrap();
    /// let intent = ctx.intent(&HashSet::from(["cat".to_string(), "dog".to_string()]));
    /// // Both cat and dog have attribute x; only cat has y
    /// assert!(intent.contains("x"));
    /// assert!(!intent.contains("y"));
    /// ```
    pub fn intent(&self, objects: &HashSet<T>) -> HashSet<T>
    where
        T: Eq + std::hash::Hash + Clone,
    {
        let mut bits = BitSet::new();
        for obj in objects {
            if let Some(idx) = self.objects.iter().position(|o| o == obj) {
                bits.insert(idx);
            }
        }
        let result_bits = self.index_intent(&bits);
        result_bits
            .iter()
            .map(|idx| self.attributes[idx].clone())
            .collect()
    }

    /// Computes the closure (hull) of a set of attributes under the Galois connection.
    ///
    /// Returns the smallest concept intent that contains all given attributes.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    /// use std::collections::HashSet;
    ///
    /// let ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n2\n2\n\ncat\ndog\nx\ny\nXX\nX.\n").unwrap();
    /// // Hull of {x} is {x, y} because every object with x also has y (only cat does)
    /// let hull = ctx.attribute_hull(&HashSet::from(["x".to_string()]));
    /// // hull contains at least x
    /// assert!(hull.contains("x"));
    /// ```
    pub fn attribute_hull(&self, attributes: &HashSet<T>) -> HashSet<T>
    where
        T: Eq + std::hash::Hash + Clone,
    {
        let mut bits = BitSet::new();
        for attr in attributes {
            if let Some(idx) = self.attributes.iter().position(|a| a == attr) {
                bits.insert(idx);
            }
        }
        let result_bits = self.index_attribute_hull(&bits);
        result_bits
            .iter()
            .map(|idx| self.attributes[idx].clone())
            .collect()
    }

    /// Computes the closure (hull) of a set of objects under the Galois connection.
    ///
    /// Returns the smallest concept extent that contains all given objects.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    /// use std::collections::HashSet;
    ///
    /// let ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n2\n2\n\ncat\ndog\nx\ny\nXX\nX.\n").unwrap();
    /// let hull = ctx.object_hull(&HashSet::from(["cat".to_string()]));
    /// assert!(hull.contains("cat"));
    /// ```
    pub fn object_hull(&self, objects: &HashSet<T>) -> HashSet<T>
    where
        T: Eq + std::hash::Hash + Clone,
    {
        let mut bits = BitSet::new();
        for obj in objects {
            if let Some(idx) = self.objects.iter().position(|o| o == obj) {
                bits.insert(idx);
            }
        }
        let result_bits = self.index_object_hull(&bits);
        result_bits
            .iter()
            .map(|idx| self.objects[idx].clone())
            .collect()
    }

    /// Adds a new object with its corresponding attributes to the existing FormalContext.
    ///
    /// The `attributes` BitSet uses attribute indices (positions in `self.attributes`).
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    /// use bit_set::BitSet;
    ///
    /// let mut ctx = FormalContext::<String>::new();
    /// ctx.add_object("cat".to_string(), &BitSet::new()); // no attributes yet
    /// assert_eq!(ctx.objects.len(), 1);
    /// ```
    pub fn add_object(&mut self, new_object: T, attributes: &BitSet) {
        self.objects.push(new_object);
        let object_index = self.objects.len() - 1;
        self.atomic_object_derivations.push(BitSet::new());

        for attribute in attributes.iter() {
            self.incidence.insert((object_index, attribute));
            self.atomic_object_derivations[object_index].insert(attribute);
            self.atomic_attribute_derivations[attribute].insert(object_index);
        }
    }

    /// Adds a new attribute with its corresponding objects to the existing FormalContext.
    ///
    /// The `objects` BitSet uses object indices (positions in `self.objects`).
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    /// use bit_set::BitSet;
    ///
    /// let mut ctx = FormalContext::<String>::new();
    /// ctx.add_attribute("legs".to_string(), &BitSet::new());
    /// assert_eq!(ctx.attributes.len(), 1);
    /// ```
    pub fn add_attribute(&mut self, new_attribute: T, objects: &BitSet) {
        self.attributes.push(new_attribute);
        let attribute_index = self.attributes.len() - 1;
        self.atomic_attribute_derivations.push(BitSet::new());

        for object in objects.iter() {
            self.incidence.insert((object, attribute_index));
            self.atomic_object_derivations[object].insert(attribute_index);
            self.atomic_attribute_derivations[attribute_index].insert(object);
        }
    }

    /// Sets or clears the incidence cross at object index `g` and attribute index `m`,
    /// keeping the precomputed derivation caches in sync.
    pub fn set_cross(&mut self, g: usize, m: usize, value: bool) {
        if value {
            self.incidence.insert((g, m));
            self.atomic_object_derivations[g].insert(m);
            self.atomic_attribute_derivations[m].insert(g);
        } else {
            self.incidence.remove(&(g, m));
            self.atomic_object_derivations[g].remove(m);
            self.atomic_attribute_derivations[m].remove(g);
        }
    }

    /// Removes the object at the specified index from the existing FormalContext.
    ///
    /// All incidence entries involving the removed object are deleted.
    /// Indices of subsequent objects are decremented to remain contiguous.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    ///
    /// let mut ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n2\n1\n\ncat\ndog\nlegs\nX\nX\n").unwrap();
    /// assert_eq!(ctx.objects.len(), 2);
    /// ctx.remove_object(0); // remove "cat" (index 0)
    /// assert_eq!(ctx.objects.len(), 1);
    /// assert_eq!(ctx.objects[0], "dog");
    /// ```
    pub fn remove_object(&mut self, index: usize) {
        for n in 0..self.attributes.len() {
            self.incidence.remove(&(index, n));
        }

        self.incidence = self
            .incidence
            .iter()
            .map(|x| if x.0 > index { (x.0 - 1, x.1) } else { *x })
            .collect();

        for n in 0..self.attributes.len() {
            self.atomic_attribute_derivations[n].remove(index);
        }

        for n in 0..self.attributes.len() {
            self.atomic_attribute_derivations[n] = self.atomic_attribute_derivations[n]
                .iter()
                .map(|x| if x > index { x - 1 } else { x })
                .collect();
        }

        self.atomic_object_derivations.remove(index);
        self.objects.remove(index);
    }

    /// Removes the attribute at the specified index from the existing FormalContext.
    ///
    /// All incidence entries involving the removed attribute are deleted.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    ///
    /// let mut ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n1\n2\n\ncat\nlegs\nfur\nXX\n").unwrap();
    /// assert_eq!(ctx.attributes.len(), 2);
    /// ctx.remove_attribute(1); // remove "fur" (index 1)
    /// assert_eq!(ctx.attributes.len(), 1);
    /// assert_eq!(ctx.attributes[0], "legs");
    /// ```
    pub fn remove_attribute(&mut self, index: usize) {
        for n in 0..self.objects.len() {
            self.incidence.remove(&(n, index));
        }

        self.incidence = self
            .incidence
            .iter()
            .map(|x| if x.1 > index { (x.0, x.1 - 1) } else { *x })
            .collect();

        for n in 0..self.objects.len() {
            self.atomic_object_derivations[n].remove(index);
        }

        for n in 0..self.objects.len() {
            self.atomic_object_derivations[n] = self.atomic_object_derivations[n]
                .iter()
                .map(|x| if x > index { x - 1 } else { x })
                .collect();
        }

        self.atomic_attribute_derivations.remove(index);
        self.attributes.remove(index);
    }

    /// Changes the name of the object at the specified index.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    ///
    /// let mut ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n1\n1\n\ncat\nlegs\nX\n").unwrap();
    /// ctx.change_object_name("feline".to_string(), 0);
    /// assert_eq!(ctx.objects[0], "feline");
    /// ```
    pub fn change_object_name(&mut self, name: T, index: usize) {
        self.objects[index] = name;
    }

    /// Changes the name of the attribute at the specified index.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    ///
    /// let mut ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n1\n1\n\ncat\nlegs\nX\n").unwrap();
    /// ctx.change_attribute_name("limbs".to_string(), 0);
    /// assert_eq!(ctx.attributes[0], "limbs");
    /// ```
    pub fn change_attribute_name(&mut self, name: T, index: usize) {
        self.attributes[index] = name;
    }

    /// In place sorts the concepts in lectic order using indices.
    ///
    /// Index-based variant of [`FormalContext::sort_lectic_order`].
    ///
    /// See also: [`FormalContext::sort_lectic_order`]
    pub fn index_sort_lectic_order(&self, concepts: &mut [(BitSet, BitSet)]) {
        let length = self.attributes.len();
        let weight: Vec<usize> = (1..=length).map(|x| 2_usize.pow(x as u32)).collect();

        let mut order: Vec<(usize, usize)> = Vec::new();

        for (index, (_, set)) in concepts.iter().enumerate() {
            let mut sum = 0;
            for n in set {
                if length > n {
                    sum += weight[length - 1 - n];
                }
            }
            order.push((index, sum));
        }

        order.sort_by(|x, y| x.1.cmp(&y.1));

        for index in 0..(order.len() - 1) {
            let swap = order[index].0;
            if index != swap {
                concepts.swap(index, swap);
                let correction = order.iter().position(|x| x.0 == index).unwrap();
                order[index] = (0, 0);
                order[correction] = (swap, 0);
            }
        }
    }

    /// In place sorts named concept pairs in lectic order.
    ///
    /// Attribute names in a concept intent that are not found in `context.attributes` are
    /// treated as weight 0 (silently ignored in the sort-key computation).
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    /// use std::collections::HashSet;
    ///
    /// let ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n2\n2\n\ncat\ndog\nx\ny\nXX\nX.\n").unwrap();
    /// let mut concepts: Vec<(HashSet<String>, HashSet<String>)> = vec![
    ///     (HashSet::from(["cat".to_string()]), HashSet::from(["x".to_string(), "y".to_string()])),
    ///     (HashSet::from(["cat".to_string(), "dog".to_string()]), HashSet::from(["x".to_string()])),
    /// ];
    /// ctx.sort_lectic_order(&mut concepts);
    /// // After sorting, intents appear in lectic (canonical) order
    /// assert_eq!(concepts.len(), 2);
    /// ```
    pub fn sort_lectic_order(&self, concepts: &mut [(HashSet<T>, HashSet<T>)])
    where
        T: Eq + std::hash::Hash + Clone,
    {
        let mut indexed: Vec<(BitSet, BitSet)> = concepts
            .iter()
            .map(|(g_set, m_set)| {
                let g_bits = g_set
                    .iter()
                    .filter_map(|name| self.objects.iter().position(|o| o == name))
                    .collect();
                let m_bits = m_set
                    .iter()
                    .filter_map(|name| self.attributes.iter().position(|a| a == name))
                    .collect();
                (g_bits, m_bits)
            })
            .collect();
        self.index_sort_lectic_order(&mut indexed);
        for (i, (g_bits, m_bits)) in indexed.into_iter().enumerate() {
            concepts[i] = (
                g_bits.iter().map(|idx| self.objects[idx].clone()).collect(),
                m_bits.iter().map(|idx| self.attributes[idx].clone()).collect(),
            );
        }
    }

    /// Filter a concept iterator to only keep concepts whose extent is at least `min_extent` objects.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    /// use odis::ConceptEnumerator;
    /// use bit_set::BitSet;
    ///
    /// let ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n3\n2\n\na\nb\nc\nx\ny\nXX\nX.\n.X\n").unwrap();
    /// let all: Vec<_> = ctx.index_concepts().collect();
    /// let filtered = FormalContext::<String>::filter_concepts_by_min_extent(all.into_iter(), 2);
    /// assert!(filtered.iter().all(|(ext, _)| ext.len() >= 2));
    /// ```
    pub fn filter_concepts_by_min_extent(
        concepts: impl Iterator<Item = (BitSet, BitSet)>,
        min_extent: usize,
    ) -> Vec<(BitSet, BitSet)> {
        concepts
            .filter(|(extent, _)| extent.len() >= min_extent)
            .collect()
    }

    /// Filter a concept iterator to keep concepts whose extent is at least `min_extent_percent` of all objects.
    ///
    /// The threshold is rounded up: `(total_objects × min_extent_percent / 100).ceil()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    /// use odis::ConceptEnumerator;
    ///
    /// let ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n4\n2\n\na\nb\nc\nd\nx\ny\nXX\nXX\nX.\n..\n").unwrap();
    /// let all: Vec<_> = ctx.index_concepts().collect();
    /// // Keep only concepts covering at least 50% of objects (i.e., ≥ 2 out of 4)
    /// let filtered = FormalContext::<String>::filter_concepts_by_min_extent_percent(
    ///     all.into_iter(), 50.0, 4
    /// );
    /// assert!(filtered.iter().all(|(ext, _)| ext.len() >= 2));
    /// ```
    pub fn filter_concepts_by_min_extent_percent(
        concepts: impl Iterator<Item = (BitSet, BitSet)>,
        min_extent_percent: f64,
        total_objects: usize,
    ) -> Vec<(BitSet, BitSet)> {
        let min_extent = ((total_objects as f64) * min_extent_percent / 100.0).ceil() as usize;
        Self::filter_concepts_by_min_extent(concepts, min_extent)
    }
}

impl FormalContext<String> {
    /// Serializes this context to Burmeister (.cxt) format bytes.
    ///
    /// The returned bytes can be written to a file or passed to
    /// [`FormalContext::from`] to round-trip a context.
    ///
    /// # Examples
    ///
    /// ```
    /// use odis::FormalContext;
    ///
    /// let ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n1\n1\n\ncat\nlegs\nX\n").unwrap();
    /// let bytes = ctx.to_cxt_bytes();
    /// let ctx2: FormalContext<String> = FormalContext::<String>::from(&bytes).unwrap();
    /// assert_eq!(ctx2.objects, ctx.objects);
    /// ```
    pub fn to_cxt_bytes(&self) -> Vec<u8> {
        let mut out = String::new();
        out.push_str("B\n");
        out.push_str(&self.name);
        out.push('\n');
        out.push_str(&self.objects.len().to_string());
        out.push('\n');
        out.push_str(&self.attributes.len().to_string());
        out.push_str("\n\n");
        for obj in &self.objects {
            out.push_str(obj.as_str());
            out.push('\n');
        }
        for attr in &self.attributes {
            out.push_str(attr.as_str());
            out.push('\n');
        }
        for (g, _) in self.objects.iter().enumerate() {
            for m in 0..self.attributes.len() {
                if self.incidence.contains(&(g, m)) {
                    out.push('X');
                } else {
                    out.push('.');
                }
            }
            out.push('\n');
        }
        out.into_bytes()
    }

    /// Writes this context to a `.cxt` file at the given path.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use odis::FormalContext;
    ///
    /// let ctx: FormalContext<String> = FormalContext::<String>::from(b"B\n\n1\n1\n\ncat\nlegs\nX\n").unwrap();
    /// ctx.to_file("/tmp/output.cxt").unwrap();
    /// ```
    pub fn to_file(&self, path: &str) -> std::io::Result<()> {
        std::fs::write(path, self.to_cxt_bytes())
    }
}

#[cfg(test)]
mod tests {
    use super::FormalContext;
    use bit_set::BitSet;
    use itertools::Itertools;
    use std::{collections::HashSet, fs};

    #[test]
    fn test_read_context() {
        let context =
            FormalContext::<String>::from(&fs::read("test_data/eu.cxt").unwrap()).unwrap();
        assert_eq!(context.objects.len(), 48);
        assert_eq!(context.objects[0], "Albanien");
        assert_eq!(context.objects[47], "Zypern");
        assert_eq!(context.attributes.len(), 7);
        assert_eq!(context.attributes[0], "EU");
        assert_eq!(context.attributes[6], "Europarat");
        assert_eq!(context.incidence.len(), 201);
        assert!(!context.incidence.contains(&(1, 0)));
        assert!(context.incidence.contains(&(1, 1)));
        assert!(!context.incidence.contains(&(1, 2)));
        assert!(!context.incidence.contains(&(1, 3)));
        assert!(!context.incidence.contains(&(1, 4)));
        assert!(context.incidence.contains(&(1, 5)));
        assert!(context.incidence.contains(&(1, 6)));
    }

    #[test]
    fn text_index_derivations() {
        let context =
            FormalContext::<String>::from(&fs::read("test_data/eu.cxt").unwrap()).unwrap();

        assert_eq!(context.index_extent(&BitSet::new()).len(), 48);
        assert_eq!(context.index_intent(&BitSet::new()).len(), 7);
        let context = FormalContext::<String>::from(
            &fs::read("test_data/living_beings_and_water.cxt").unwrap(),
        )
        .unwrap();
        assert_eq!(
            context.index_extent(&BitSet::from_bytes(&[0b10000000])),
            BitSet::from_bytes(&[0b11111111])
        );
    }

    #[test]
    fn test_high_level_methods() {
        let context = FormalContext::<String>::from(
            &fs::read("test_data/living_beings_and_water.cxt").unwrap(),
        )
        .unwrap();

        let mut attrs = HashSet::new();
        attrs.insert("needs water to live".to_string());

        let objects = context.extent(&attrs);
        assert_eq!(objects.len(), 8);
        assert!(objects.contains("fish leech"));

        let mut objects_set = HashSet::new();
        objects_set.insert("frog".to_string());
        let intent = context.intent(&objects_set);
        assert!(intent.contains("lives in water"));
        assert!(intent.contains("lives on land"));
    }

    #[test]
    fn text_index_hulls() {
        let context = FormalContext::<String>::from(
            &fs::read("test_data/living_beings_and_water.cxt").unwrap(),
        )
        .unwrap();
        assert_eq!(
            context.index_attribute_hull(&BitSet::from_bytes(&[0b00000000])),
            BitSet::from_bytes(&[0b10000000])
        );
        for gs in (0..context.objects.len()).powerset() {
            let sub: BitSet = gs.into_iter().collect();
            let hull = context.index_object_hull(&sub);
            assert!(sub.is_subset(&hull));
        }
        for ms in (0..context.attributes.len()).powerset() {
            let sub: BitSet = ms.into_iter().collect();
            let hull = context.index_attribute_hull(&sub);
            assert!(sub.is_subset(&hull));
        }
    }

    #[test]
    fn lectic_sort() {
        let context =
            FormalContext::<String>::from(&fs::read("test_data/living_beings_and_water.cxt").unwrap()).unwrap();

        let mut concepts_unsorted: Vec<(BitSet, BitSet)> = context.index_fcbo_concepts().collect();
        let concepts_sorted: Vec<(BitSet, BitSet)> = context.index_next_closure_concepts().collect();

        assert!(concepts_sorted != concepts_unsorted);

        context.index_sort_lectic_order(&mut concepts_unsorted);

        assert!(concepts_sorted == concepts_unsorted);
    }

    #[test]
    fn test_to_file_round_trip() {
        let ctx = FormalContext::<String>::from(
            &fs::read("test_data/living_beings_and_water.cxt").unwrap(),
        )
        .unwrap();

        let tmp = std::env::temp_dir().join("odis_round_trip_test.cxt");
        ctx.to_file(tmp.to_str().unwrap()).expect("to_file should succeed");

        let reloaded = FormalContext::<String>::from(&fs::read(&tmp).unwrap()).unwrap();
        assert_eq!(ctx.name, reloaded.name);
        assert_eq!(ctx.objects, reloaded.objects);
        assert_eq!(ctx.attributes, reloaded.attributes);
        assert_eq!(ctx.incidence, reloaded.incidence);

        let _ = fs::remove_file(tmp);
    }
}