eulumdat-quiz 0.6.0

Photometric knowledge quiz engine for lighting professionals
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
//! Photometric knowledge quiz engine for lighting professionals.
//!
//! Pure Rust library with no UI dependencies. Designed to be FFI-safe
//! (uniffi/PyO3) for use across TUI, Web, Desktop, iOS, Android, and Python.

pub mod i18n;
mod questions;
mod session;

pub use session::QuizSession;

/// Knowledge domain categories.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum Category {
    /// LDT file structure, line numbers, field meanings
    EulumdatFormat,
    /// LM-63 versions, keywords, photometric types A/B/C
    IesFormat,
    /// 5 symmetry types, data expansion, compression ratios
    Symmetry,
    /// C-plane angles, gamma angles, nadir/zenith, Type B↔C
    CoordinateSystems,
    /// LOR, DFF, beam/field angles, CIE flux codes, efficacy
    PhotometricCalc,
    /// TM-15-11 zones, thresholds, B/U/G 0-5 scale
    BugRating,
    /// UGR formula, standard rooms, CIE 117
    UgrGlare,
    /// CCT, CRI groups, TM-30 Rf/Rg, Duv, SPD
    ColorScience,
    /// PAR, PPF, PPFD, DLI, R:FR ratio, spectral zones
    Horticultural,
    /// TM-32-24 parameters, NEMA GUIDs, housing shapes
    BimIntegration,
    /// TM-33-23/ATLA S001, XML vs JSON, spectral support
    ModernFormats,
    /// Warning codes W001-W046, error codes E001-E006
    Validation,
    /// lux/fc, m/ft, mm/in, cd/klm, lm/W
    Units,
    /// Polar, cartesian, heatmap, cone, butterfly, isolux
    DiagramTypes,
    /// Reading and interpreting polar light distribution diagrams
    DiagramReading,
    /// CIE, IES, NEMA, EN 13201, IDA, LEED, Title 24
    Standards,
}

impl Category {
    /// Stable string key for i18n lookup (matches JSON locale keys).
    pub fn key(&self) -> &'static str {
        match self {
            Self::EulumdatFormat => "eulumdat_format",
            Self::IesFormat => "ies_format",
            Self::Symmetry => "symmetry",
            Self::CoordinateSystems => "coordinate_systems",
            Self::PhotometricCalc => "photometric_calc",
            Self::BugRating => "bug_rating",
            Self::UgrGlare => "ugr_glare",
            Self::ColorScience => "color_science",
            Self::Horticultural => "horticultural",
            Self::BimIntegration => "bim_integration",
            Self::ModernFormats => "modern_formats",
            Self::Validation => "validation",
            Self::Units => "units",
            Self::DiagramTypes => "diagram_types",
            Self::DiagramReading => "diagram_reading",
            Self::Standards => "standards",
        }
    }

    /// Human-readable label for display.
    pub fn label(&self) -> &'static str {
        match self {
            Self::EulumdatFormat => "EULUMDAT Format",
            Self::IesFormat => "IES Format",
            Self::Symmetry => "Symmetry",
            Self::CoordinateSystems => "Coordinate Systems",
            Self::PhotometricCalc => "Photometric Calculations",
            Self::BugRating => "BUG Rating",
            Self::UgrGlare => "UGR & Glare",
            Self::ColorScience => "Color Science",
            Self::Horticultural => "Horticultural Lighting",
            Self::BimIntegration => "BIM Integration",
            Self::ModernFormats => "Modern Formats",
            Self::Validation => "Validation",
            Self::Units => "Units & Conversions",
            Self::DiagramTypes => "Diagram Types",
            Self::DiagramReading => "Diagram Reading",
            Self::Standards => "Standards & Compliance",
        }
    }

    /// All category variants.
    pub fn all() -> Vec<Category> {
        vec![
            Self::EulumdatFormat,
            Self::IesFormat,
            Self::Symmetry,
            Self::CoordinateSystems,
            Self::PhotometricCalc,
            Self::BugRating,
            Self::UgrGlare,
            Self::ColorScience,
            Self::Horticultural,
            Self::BimIntegration,
            Self::ModernFormats,
            Self::Validation,
            Self::Units,
            Self::DiagramTypes,
            Self::DiagramReading,
            Self::Standards,
        ]
    }
}

/// Difficulty level for questions.
#[derive(
    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
pub enum Difficulty {
    /// Format basics, unit definitions, simple facts
    Beginner,
    /// Calculations, thresholds, standard comparisons
    Intermediate,
    /// Cross-standard nuances, edge cases, formulas
    Expert,
}

impl Difficulty {
    /// Stable string key for i18n lookup.
    pub fn key(&self) -> &'static str {
        match self {
            Self::Beginner => "beginner",
            Self::Intermediate => "intermediate",
            Self::Expert => "expert",
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            Self::Beginner => "Beginner",
            Self::Intermediate => "Intermediate",
            Self::Expert => "Expert",
        }
    }
}

/// A single quiz question with 4 multiple-choice options.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Question {
    pub id: u32,
    pub category: Category,
    pub difficulty: Difficulty,
    pub text: String,
    /// 4 choices (A-D)
    pub options: Vec<String>,
    /// Index of the correct option (0-3)
    pub correct_index: u8,
    /// Explanation shown after answering
    pub explanation: String,
    /// Reference standard or specification
    pub reference: Option<String>,
}

/// Configuration for creating a quiz session.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct QuizConfig {
    /// Filter by categories (empty = all)
    pub categories: Vec<Category>,
    /// Filter by difficulty (None = mixed)
    pub difficulty: Option<Difficulty>,
    /// Number of questions (0 = all matching)
    pub num_questions: u32,
    /// Shuffle question order
    pub shuffle: bool,
    /// Seed for reproducible shuffle
    pub seed: Option<u64>,
}

impl Default for QuizConfig {
    fn default() -> Self {
        Self {
            categories: vec![],
            difficulty: None,
            num_questions: 10,
            shuffle: true,
            seed: None,
        }
    }
}

/// Score for a specific category.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct CategoryScore {
    pub category: Category,
    pub correct: u32,
    pub total: u32,
}

/// Score for a specific difficulty level.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DifficultyScore {
    pub difficulty: Difficulty,
    pub correct: u32,
    pub total: u32,
}

/// Overall quiz score with breakdowns.
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct QuizScore {
    pub correct: u32,
    pub wrong: u32,
    pub skipped: u32,
    pub total: u32,
    pub by_category: Vec<CategoryScore>,
    pub by_difficulty: Vec<DifficultyScore>,
}

impl QuizScore {
    /// Percentage score (0.0-100.0).
    pub fn percentage(&self) -> f64 {
        if self.total == 0 {
            0.0
        } else {
            self.correct as f64 / self.total as f64 * 100.0
        }
    }
}

/// Result of answering a question.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AnswerResult {
    pub is_correct: bool,
    pub correct_index: u8,
    pub explanation: String,
    pub reference: Option<String>,
}

/// Static quiz bank with all available questions.
pub struct QuizBank;

impl QuizBank {
    /// All questions in the bank.
    pub fn all_questions() -> Vec<Question> {
        questions::all_questions()
    }

    /// Available categories with question counts.
    pub fn categories() -> Vec<(Category, u32)> {
        let questions = Self::all_questions();
        Category::all()
            .into_iter()
            .map(|cat| {
                let count = questions.iter().filter(|q| q.category == cat).count() as u32;
                (cat, count)
            })
            .filter(|(_, count)| *count > 0)
            .collect()
    }

    /// Total number of questions.
    pub fn total_count() -> u32 {
        Self::all_questions().len() as u32
    }
}

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

    #[test]
    fn test_all_questions_valid() {
        let questions = QuizBank::all_questions();
        assert!(
            questions.len() >= 100,
            "Expected at least 100 questions, got {}",
            questions.len()
        );

        for q in &questions {
            assert_eq!(q.options.len(), 4, "Question {} must have 4 options", q.id);
            assert!(
                q.correct_index < 4,
                "Question {} has invalid correct_index {}",
                q.id,
                q.correct_index
            );
            assert!(!q.text.is_empty(), "Question {} has empty text", q.id);
            assert!(
                !q.explanation.is_empty(),
                "Question {} has empty explanation",
                q.id
            );
        }
    }

    #[test]
    fn test_no_duplicate_ids() {
        let questions = QuizBank::all_questions();
        let mut ids: Vec<u32> = questions.iter().map(|q| q.id).collect();
        ids.sort();
        ids.dedup();
        assert_eq!(ids.len(), questions.len(), "Duplicate question IDs found");
    }

    #[test]
    fn test_all_categories_have_questions() {
        let questions = QuizBank::all_questions();
        for cat in Category::all() {
            let count = questions.iter().filter(|q| q.category == cat).count();
            assert!(
                count >= 5,
                "Category {:?} has only {} questions (need >= 5)",
                cat,
                count
            );
        }
    }

    #[test]
    fn test_all_difficulties_have_questions() {
        let questions = QuizBank::all_questions();
        for diff in [
            Difficulty::Beginner,
            Difficulty::Intermediate,
            Difficulty::Expert,
        ] {
            let count = questions.iter().filter(|q| q.difficulty == diff).count();
            assert!(
                count >= 20,
                "Difficulty {:?} has only {} questions (need >= 20)",
                diff,
                count
            );
        }
    }

    #[test]
    fn test_quiz_session_basic() {
        let config = QuizConfig {
            num_questions: 5,
            shuffle: false,
            ..Default::default()
        };
        let mut session = QuizSession::new(config);
        assert!(!session.is_finished());

        let (idx, total) = session.progress();
        assert_eq!(idx, 0);
        assert_eq!(total, 5);

        let q = session.current_question().unwrap();
        let result = session.answer(q.correct_index);
        assert!(result.is_correct);

        let score = session.score();
        assert_eq!(score.correct, 1);
        assert_eq!(score.wrong, 0);
    }

    #[test]
    fn test_quiz_session_skip() {
        let config = QuizConfig {
            num_questions: 3,
            shuffle: false,
            ..Default::default()
        };
        let mut session = QuizSession::new(config);
        session.skip();
        let score = session.score();
        assert_eq!(score.skipped, 1);
    }

    #[test]
    fn test_quiz_config_filter_category() {
        let config = QuizConfig {
            categories: vec![Category::BugRating],
            num_questions: 0,
            shuffle: false,
            ..Default::default()
        };
        let session = QuizSession::new(config);
        let (_, total) = session.progress();
        assert!(total > 0);
        // All questions should be BugRating
        for i in 0..total {
            let q = &session.questions[i];
            assert_eq!(q.category, Category::BugRating);
        }
    }

    #[test]
    fn test_quiz_config_filter_difficulty() {
        let config = QuizConfig {
            difficulty: Some(Difficulty::Expert),
            num_questions: 0,
            shuffle: false,
            ..Default::default()
        };
        let session = QuizSession::new(config);
        for q in &session.questions {
            assert_eq!(q.difficulty, Difficulty::Expert);
        }
    }

    #[test]
    fn test_score_percentage() {
        let score = QuizScore {
            correct: 7,
            wrong: 3,
            skipped: 0,
            total: 10,
            ..Default::default()
        };
        assert!((score.percentage() - 70.0).abs() < f64::EPSILON);
    }
}