Skip to main content

fontoxide_misc/
classify_tools.rs

1//! Port of `fontTools.misc.classifyTools`: classifying things into similar
2//! sets.
3
4use std::collections::{BTreeMap, BTreeSet};
5
6/// Classifies things into similar sets (`Classifier`): every class is either a
7/// subset of, or disjoint from, each of the sets added.
8#[derive(Debug, Clone)]
9pub struct Classifier<T> {
10	/// All things known so far (`_things`).
11	things: BTreeSet<T>,
12	/// The class sets produced so far (`_sets`); emptied classes stay until
13	/// they are processed.
14	sets: Vec<BTreeSet<T>>,
15	/// The index in `sets` of the class of each thing (`_mapping`).
16	mapping: BTreeMap<T, usize>,
17	dirty: bool,
18	sort: bool,
19}
20
21impl<T: Ord + Clone> Default for Classifier<T> {
22	fn default() -> Self {
23		Self::new(true)
24	}
25}
26
27impl<T: Ord + Clone> Classifier<T> {
28	/// `Classifier(sort=sort)`: with `sort`, the classes are sorted by
29	/// decreasing size, then by their sorted things.
30	pub fn new(sort: bool) -> Self {
31		Classifier {
32			things: BTreeSet::new(),
33			sets: Vec::new(),
34			mapping: BTreeMap::new(),
35			dirty: false,
36			sort,
37		}
38	}
39
40	/// Adds a set (`add`).
41	///
42	/// The classes split by the set are processed in the order of their
43	/// smallest thing in it, which is the order of Python's set iteration for
44	/// small integers; it only matters to the order of unsorted classes.
45	pub fn add(&mut self, set_of_things: impl IntoIterator<Item = T>) {
46		let s: BTreeSet<T> = set_of_things.into_iter().collect();
47		if s.is_empty() {
48			return;
49		}
50		self.dirty = true;
51		let (mut intersection, difference): (BTreeSet<T>, BTreeSet<T>) =
52			s.into_iter().partition(|t| self.things.contains(t));
53		// Add new class for new things
54		if !difference.is_empty() {
55			let index = self.sets.len();
56			for thing in &difference {
57				self.things.insert(thing.clone());
58				self.mapping.insert(thing.clone(), index);
59			}
60			self.sets.push(difference);
61		}
62		while let Some(first) = intersection.first() {
63			// Take one item and process the old class it belongs to
64			let Some(&old) = self.mapping.get(first) else {
65				break;
66			};
67			let old_class_intersection: BTreeSet<T> = self.sets[old]
68				.intersection(&intersection)
69				.cloned()
70				.collect();
71			// Update old class to remove items from new set, and remove processed
72			// items from todo list
73			for thing in &old_class_intersection {
74				self.sets[old].remove(thing);
75				intersection.remove(thing);
76			}
77			// Add new class for the intersection with old class
78			let index = self.sets.len();
79			for thing in &old_class_intersection {
80				self.mapping.insert(thing.clone(), index);
81			}
82			self.sets.push(old_class_intersection);
83		}
84	}
85
86	/// Adds sets (`update`).
87	pub fn update<I: IntoIterator<Item = T>>(&mut self, list_of_sets: impl IntoIterator<Item = I>) {
88		for s in list_of_sets {
89			self.add(s);
90		}
91	}
92
93	/// Drops the emptied classes and sorts them (`_process`).
94	fn process(&mut self) {
95		if !self.dirty {
96			return;
97		}
98		let mut sets: Vec<BTreeSet<T>> = std::mem::take(&mut self.sets)
99			.into_iter()
100			.filter(|s| !s.is_empty())
101			.collect();
102		if self.sort {
103			// `key=lambda s: (-len(s), sorted(s))`
104			sets.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.iter().cmp(b.iter())));
105		}
106		self.mapping.clear();
107		for (i, set) in sets.iter().enumerate() {
108			for thing in set {
109				self.mapping.insert(thing.clone(), i);
110			}
111		}
112		self.sets = sets;
113		self.dirty = false;
114	}
115
116	/// All things known so far (`getThings`).
117	pub fn get_things(&mut self) -> &BTreeSet<T> {
118		self.process();
119		&self.things
120	}
121
122	/// The class sets (`getClasses`).
123	pub fn get_classes(&mut self) -> &[BTreeSet<T>] {
124		self.process();
125		&self.sets
126	}
127
128	/// The index in [`Classifier::get_classes`] of the class of each thing
129	/// (`getMapping`, which maps to the class sets themselves).
130	pub fn get_mapping(&mut self) -> &BTreeMap<T, usize> {
131		self.process();
132		&self.mapping
133	}
134}
135
136/// Classifies the things present in any of the sets into the smallest list of
137/// sets such that each one is either a subset of, or disjoint from, each of the
138/// input sets (`classify`). Returns the classes and the class of each thing.
139///
140/// With `sort`, the classes are sorted by decreasing size and their sorted
141/// things; otherwise they are in the order they were identified.
142///
143/// ```
144/// use std::collections::BTreeSet;
145/// use fontoxide_misc::classify_tools::classify;
146/// let (classes, mapping) = classify([vec![1, 2], vec![2, 4, 5]], true);
147/// assert_eq!(classes, [BTreeSet::from([4, 5]), BTreeSet::from([1]), BTreeSet::from([2])]);
148/// assert_eq!(mapping[&5], BTreeSet::from([4, 5]));
149/// ```
150pub fn classify<T: Ord + Clone, I: IntoIterator<Item = T>>(
151	list_of_sets: impl IntoIterator<Item = I>,
152	sort: bool,
153) -> (Vec<BTreeSet<T>>, BTreeMap<T, BTreeSet<T>>) {
154	let mut classifier = Classifier::new(sort);
155	classifier.update(list_of_sets);
156	let classes = classifier.get_classes().to_vec();
157	let mapping = classifier
158		.get_mapping()
159		.iter()
160		.map(|(thing, &i)| (thing.clone(), classes[i].clone()))
161		.collect();
162	(classes, mapping)
163}