eunoia 0.5.0

A library for creating area-proportional Euler and Venn diagrams
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
//! Builder for constructing diagram specifications.

use super::{Combination, DiagramSpec, InputType};
use crate::error::DiagramError;
use std::collections::{HashMap, HashSet};

/// Builder for creating diagram specifications with a fluent API.
///
/// The specification is shape-agnostic - the shape type is determined when
/// fitting the diagram using a `Fitter`, not when building the spec.
///
/// # Examples
///
/// ```
/// use eunoia::{DiagramSpecBuilder, InputType, Fitter};
/// use eunoia::geometry::shapes::Circle;
///
/// let spec = DiagramSpecBuilder::new()
///     .set("A", 5.0)
///     .set("B", 2.0)
///     .intersection(&["A", "B"], 1.0)
///     .input_type(InputType::Exclusive)
///     .build()
///     .expect("Failed to build diagram specification");
///
/// // Shape type is chosen when fitting
/// let layout = Fitter::<Circle>::new(&spec).fit().unwrap();
/// ```
#[derive(Debug)]
pub struct DiagramSpecBuilder {
    combinations: HashMap<Combination, f64>,
    input_type: Option<InputType>,
    set_order: Vec<String>,
}

impl Default for DiagramSpecBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl DiagramSpecBuilder {
    /// Creates a new diagram builder.
    pub fn new() -> Self {
        DiagramSpecBuilder {
            combinations: HashMap::new(),
            input_type: None,
            set_order: Vec::new(),
        }
    }

    /// Adds a single set with the given value.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the set
    /// * `value` - The size/value for this set
    ///
    /// # Examples
    ///
    /// ```
    /// use eunoia::DiagramSpecBuilder;
    ///
    ///
    /// let builder = DiagramSpecBuilder::new()
    ///     .set("A", 10.0);
    /// ```
    pub fn set(mut self, name: impl Into<String>, value: f64) -> Self {
        let name_string = name.into();
        let combination = Combination::new(&[&name_string]);
        // Track order of first occurrence
        if !self.set_order.contains(&name_string) {
            self.set_order.push(name_string.clone());
        }
        self.combinations.insert(combination, value);
        self
    }

    /// Adds an intersection of multiple sets with the given value.
    ///
    /// # Arguments
    ///
    /// * `sets` - A slice of set names to intersect
    /// * `value` - The size/value for this intersection
    ///
    /// # Examples
    ///
    /// ```
    /// use eunoia::DiagramSpecBuilder;
    ///
    ///
    /// let builder = DiagramSpecBuilder::new()
    ///     .set("A", 10.0)
    ///     .set("B", 8.0)
    ///     .intersection(&["A", "B"], 2.0);
    /// ```
    pub fn intersection(mut self, sets: &[&str], value: f64) -> Self {
        let combination = Combination::new(sets);
        self.combinations.insert(combination, value);
        self
    }

    /// Sets how the input values should be interpreted.
    ///
    /// # Arguments
    ///
    /// * `input_type` - Whether values are exclusive or inclusive
    ///
    /// # Examples
    ///
    /// ```
    /// use eunoia::{DiagramSpecBuilder, InputType};
    ///
    ///
    /// let builder = DiagramSpecBuilder::new()
    ///     .input_type(InputType::Exclusive);
    /// ```
    pub fn input_type(mut self, input_type: InputType) -> Self {
        self.input_type = Some(input_type);
        self
    }

    /// Builds the diagram specification, validating all inputs.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No sets are defined
    /// - Any value is negative
    /// - An intersection references undefined sets
    ///
    /// # Examples
    ///
    /// ```
    /// use eunoia::{DiagramSpecBuilder, InputType};
    ///
    ///
    /// let spec = DiagramSpecBuilder::new()
    ///     .set("A", 5.0)
    ///     .set("B", 2.0)
    ///     .intersection(&["A", "B"], 1.0)
    ///     .build()
    ///     .expect("Failed to build diagram specification");
    /// ```
    pub fn build(self) -> Result<DiagramSpec, DiagramError> {
        // Check that we have at least one set
        if self.combinations.is_empty() {
            return Err(DiagramError::EmptySets);
        }

        // Collect all unique set names from all combinations
        let mut all_set_names = HashSet::new();
        let mut single_sets = HashSet::new();

        for combination in self.combinations.keys() {
            for set_name in combination.sets() {
                all_set_names.insert(set_name.clone());
            }
            if combination.len() == 1 {
                single_sets.insert(combination.sets()[0].clone());
            }
        }

        // For sets that appear in intersections but not as single sets,
        // implicitly add them with value 0.0 (they exist entirely within intersections)
        let mut combinations = self.combinations;
        for set_name in &all_set_names {
            if !single_sets.contains(set_name) {
                let combination = Combination::new(&[set_name.as_str()]);
                combinations.insert(combination, 0.0);
                single_sets.insert(set_name.clone());
            }
        }

        // Use set_order to create an ordered vector of set names, then add any
        // implicitly defined sets that weren't in the original order
        let mut ordered_set_names: Vec<String> = self
            .set_order
            .iter()
            .filter(|name| all_set_names.contains(*name))
            .cloned()
            .collect();

        // Add any sets that were implicitly discovered but not in set_order
        for set_name in &all_set_names {
            if !ordered_set_names.contains(set_name) {
                ordered_set_names.push(set_name.clone());
            }
        }

        // Validate that all values are non-negative
        for (combination, &value) in &combinations {
            if value < 0.0 {
                return Err(DiagramError::InvalidValue {
                    combination: combination.to_string(),
                    value,
                });
            }
        }

        // Convert to both exclusive and inclusive representations
        let input_type = self.input_type.unwrap_or_default();
        let (exclusive_areas, inclusive_areas) = match input_type {
            InputType::Exclusive => {
                let exclusive = combinations;
                let inclusive = DiagramSpec::exclusive_to_inclusive_static(&exclusive)?;
                (exclusive, inclusive)
            }
            InputType::Inclusive => {
                let inclusive = combinations;
                let exclusive = DiagramSpec::inclusive_to_exclusive_static(&inclusive)?;
                (exclusive, inclusive)
            }
        };

        Ok(DiagramSpec {
            exclusive_areas,
            inclusive_areas,
            input_type,
            set_names: ordered_set_names,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_simple() {
        let spec = DiagramSpecBuilder::new()
            .set("A", 5.0)
            .set("B", 2.0)
            .build()
            .unwrap();

        assert_eq!(spec.set_names().len(), 2);
        assert!(spec.set_names().contains(&"A".to_string()));
        assert!(spec.set_names().contains(&"B".to_string()));

        // Both representations should be available
        assert!(spec.get_inclusive(&Combination::new(&["A"])).is_some());
        assert!(spec.get_exclusive(&Combination::new(&["A"])).is_some());
    }

    #[test]
    fn test_builder_with_intersection() {
        let spec = DiagramSpecBuilder::new()
            .set("A", 5.0)
            .set("B", 2.0)
            .intersection(&["A", "B"], 1.0)
            .input_type(InputType::Exclusive)
            .build()
            .unwrap();

        assert_eq!(spec.input_type(), InputType::Exclusive);
        assert_eq!(spec.exclusive_areas().len(), 3);
        assert_eq!(spec.inclusive_areas().len(), 3);
    }

    #[test]
    fn test_builder_implicit_zero_set() {
        // When a set is referenced in an intersection but not defined as a single set,
        // it should be implicitly added with value 0.0
        let spec = DiagramSpecBuilder::new()
            .set("B", 5.0)
            .intersection(&["A", "B"], 1.0)
            .input_type(InputType::Exclusive)
            .build()
            .unwrap();

        // Set A should be implicitly added with exclusive value 0.0
        let combo_a = Combination::new(&["A"]);
        assert_eq!(spec.get_exclusive(&combo_a), Some(0.0));

        // In inclusive representation, A should have total size = 1.0 (just the intersection)
        assert_eq!(spec.get_inclusive(&combo_a), Some(1.0));
    }

    #[test]
    fn test_contained_set_exclusive() {
        // Test case: A=0, B=5, A&B=1 (exclusive)
        // This means A is entirely contained within B
        let spec = DiagramSpecBuilder::new()
            .set("A", 0.0)
            .set("B", 5.0)
            .intersection(&["A", "B"], 1.0)
            .input_type(InputType::Exclusive)
            .build()
            .unwrap();

        // Exclusive areas
        assert_eq!(spec.get_exclusive(&Combination::new(&["A"])), Some(0.0));
        assert_eq!(spec.get_exclusive(&Combination::new(&["B"])), Some(5.0));
        assert_eq!(
            spec.get_exclusive(&Combination::new(&["A", "B"])),
            Some(1.0)
        );

        // Inclusive areas (total sizes)
        assert_eq!(spec.get_inclusive(&Combination::new(&["A"])), Some(1.0)); // A total = 0 + 1
        assert_eq!(spec.get_inclusive(&Combination::new(&["B"])), Some(6.0)); // B total = 5 + 1
        assert_eq!(
            spec.get_inclusive(&Combination::new(&["A", "B"])),
            Some(1.0)
        );
    }

    #[test]
    fn test_implicit_set_from_three_way() {
        // Test case: A=0, B=5, A&B=1, A&B&C=0.1 (disjoint)
        // Set C is only referenced in the 3-way intersection
        let spec = DiagramSpecBuilder::new()
            .set("A", 0.0)
            .set("B", 5.0)
            .intersection(&["A", "B"], 1.0)
            .intersection(&["A", "B", "C"], 0.1)
            .input_type(InputType::Exclusive)
            .build()
            .unwrap();

        // All three sets should exist
        assert_eq!(spec.set_names().len(), 3);
        assert!(spec.set_names().contains(&"A".to_string()));
        assert!(spec.set_names().contains(&"B".to_string()));
        assert!(spec.set_names().contains(&"C".to_string()));

        // Check that C was implicitly added with value 0.0
        assert_eq!(spec.get_exclusive(&Combination::new(&["C"])), Some(0.0));

        // C's inclusive area should be 0.1 (just the 3-way intersection)
        assert_eq!(spec.get_inclusive(&Combination::new(&["C"])), Some(0.1));
    }

    #[test]
    fn test_nested_containment() {
        // Test case: B=5, A&B=2, A&B&C=1 (disjoint)
        // A is contained in B, and C is contained in A&B
        let spec = DiagramSpecBuilder::new()
            .set("B", 5.0)
            .intersection(&["A", "B"], 2.0)
            .intersection(&["A", "B", "C"], 1.0)
            .input_type(InputType::Exclusive)
            .build()
            .unwrap();

        // All three sets should exist
        assert_eq!(spec.set_names().len(), 3);

        // Expected exclusive areas
        assert_eq!(spec.get_exclusive(&Combination::new(&["A"])), Some(0.0));
        assert_eq!(spec.get_exclusive(&Combination::new(&["B"])), Some(5.0));
        assert_eq!(spec.get_exclusive(&Combination::new(&["C"])), Some(0.0));
        assert_eq!(
            spec.get_exclusive(&Combination::new(&["A", "B"])),
            Some(2.0)
        );
        assert_eq!(
            spec.get_exclusive(&Combination::new(&["A", "B", "C"])),
            Some(1.0)
        );

        // Expected inclusive areas (total sizes)
        assert_eq!(spec.get_inclusive(&Combination::new(&["A"])), Some(3.0)); // 0 + 2 + 1
        assert_eq!(spec.get_inclusive(&Combination::new(&["B"])), Some(8.0)); // 5 + 2 + 1
        assert_eq!(spec.get_inclusive(&Combination::new(&["C"])), Some(1.0)); // 0 + 1
    }

    #[test]
    fn test_builder_negative_value_error() {
        let result = DiagramSpecBuilder::new().set("A", -5.0).build();

        assert!(matches!(result, Err(DiagramError::InvalidValue { .. })));
    }

    #[test]
    fn test_builder_empty_error() {
        let result = DiagramSpecBuilder::new().build();
        assert!(matches!(result, Err(DiagramError::EmptySets)));
    }

    #[test]
    fn test_three_way_intersection() {
        let spec = DiagramSpecBuilder::new()
            .set("A", 10.0)
            .set("B", 8.0)
            .set("C", 12.0)
            .intersection(&["A", "B"], 2.0)
            .intersection(&["A", "C"], 3.0)
            .intersection(&["B", "C"], 1.0)
            .intersection(&["A", "B", "C"], 0.5)
            .build()
            .unwrap();

        assert_eq!(spec.set_names().len(), 3);
        assert_eq!(spec.exclusive_areas().len(), 7);
        assert_eq!(spec.inclusive_areas().len(), 7);
    }

    #[test]
    fn test_get_combination() {
        let spec = DiagramSpecBuilder::new()
            .set("A", 5.0)
            .set("B", 2.0)
            .intersection(&["A", "B"], 1.0)
            .build()
            .unwrap();

        let combo_ab = Combination::new(&["A", "B"]);
        assert_eq!(spec.get_inclusive(&combo_ab), Some(1.0));

        let combo_ac = Combination::new(&["A", "C"]);
        assert_eq!(spec.get_inclusive(&combo_ac), None);
    }
}