fitts 0.2.1

Spaced repetition scheduler using Fitts' Law for difficulty prediction and SM-2 for interval scheduling.
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
//! SM-2 spaced repetition with Fitts' Law adaptive calibration.
//!
//! # Architecture
//!
//! This module combines two complementary systems:
//!
//! - **SM-2**: Uses subjective rating → calculates next interval
//! - **Fitts' Law**: Uses objective response time → calibrates predictions
//!
//! # Key Insight
//!
//! Rating and response time are **different signals**:
//!
//! | Signal | Type | Source | Meaning |
//! |--------|------|--------|---------|
//! | Rating | Subjective | User input | "How well did I recall?" |
//! | Response Time | Objective | Measured | "How fast did I recall?" |
//!
//! A user might:
//! - Respond **fast** but rate **Hard** (implicit memory worked, but felt unsure)
//! - Respond **slow** but rate **Easy** (was distracted, but knew the answer)
//!
//! By capturing both, we get richer data for personalization.
//!
//! # Example
//!
//! ```rust
//! use fitts::{FittsScheduler, CardState, Rating, ReviewInput};
//!
//! let mut scheduler = FittsScheduler::new();
//! let card = CardState::default();
//!
//! // Predict before showing answer
//! let (predicted_rt, _) = scheduler.predict(&card);
//!
//! // User responds... app measures time
//! let input = ReviewInput {
//!     rating: Rating::Good,
//!     response_time_ms: 2500,  // 2.5 seconds
//! };
//!
//! // Process review with both signals
//! let result = scheduler.review(card, input);
//! assert_eq!(result.card.interval_days, 1.0);
//! ```

use crate::fitts::{CalibrationResult, FittsModel};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Card state for SM-2 scheduling.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CardState {
    /// Days until next review (SM-2 interval).
    pub interval_days: f64,
    /// Ease factor (SM-2 EF), range [1.3, ∞).
    pub ease_factor: f64,
    /// Number of successful reviews in a row.
    pub repetitions: u32,
    /// Number of times card was forgotten (rated Again).
    pub lapses: u32,
    /// Timestamp of last review.
    pub last_review: Option<DateTime<Utc>>,
}

impl Default for CardState {
    fn default() -> Self {
        Self {
            interval_days: 0.0,
            ease_factor: 2.5,
            repetitions: 0,
            lapses: 0,
            last_review: None,
        }
    }
}

impl CardState {
    /// Calculate next review date.
    pub fn next_review_date(&self) -> DateTime<Utc> {
        let base = self.last_review.unwrap_or_else(Utc::now);
        base + chrono::Duration::days(self.interval_days.ceil() as i64)
    }

    /// Check if card is due for review.
    pub fn is_due(&self) -> bool {
        Utc::now() >= self.next_review_date()
    }
}

/// User rating for a review (subjective input from user).
///
/// Maps to SM-2 quality scale:
/// - Again = 0 (complete failure)
/// - Hard = 1 (correct but very difficult)
/// - Good = 2 (correct with some effort)
/// - Easy = 3 (perfect recall)
///
/// In SM-2 logic: quality >= 1 is success (Hard/Good/Easy all pass).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Rating {
    /// Complete failure - didn't remember at all.
    Again = 0,
    /// Correct recall but very difficult - barely remembered.
    Hard = 1,
    /// Correct recall with some effort - normal difficulty.
    Good = 2,
    /// Perfect recall - instant and effortless.
    Easy = 3,
}

impl Rating {
    /// Convert to quality value (0-3 scale).
    /// Note: This is mapped to SM-2's 1-5 scale internally for ease factor calculation.
    pub fn to_quality(self) -> u8 {
        match self {
            Rating::Again => 0,
            Rating::Hard => 1,
            Rating::Good => 2,
            Rating::Easy => 3,
        }
    }

    /// Check if this rating represents successful recall.
    /// In SM-2: Hard, Good, and Easy are all successes (quality >= 1).
    pub fn is_success(self) -> bool {
        self.to_quality() >= 1
    }

    /// Get all ratings.
    pub fn all() -> [Self; 4] {
        [Self::Again, Self::Hard, Self::Good, Self::Easy]
    }
}

/// Input for a card review.
///
/// Captures both subjective and objective signals:
/// - **rating**: User's subjective assessment
/// - **response_time_ms**: Objectively measured time
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReviewInput {
    /// User's subjective rating.
    pub rating: Rating,
    /// Response time in milliseconds (measured by app).
    /// Set to 0 if not measured.
    pub response_time_ms: u64,
}

impl ReviewInput {
    /// Create input with only rating (no response time).
    pub fn from_rating(rating: Rating) -> Self {
        Self {
            rating,
            response_time_ms: 0,
        }
    }

    /// Create input with rating and response time.
    pub fn new(rating: Rating, response_time_ms: u64) -> Self {
        Self {
            rating,
            response_time_ms,
        }
    }

    /// Get response time in seconds.
    pub fn response_time_seconds(&self) -> f64 {
        self.response_time_ms as f64 / 1000.0
    }
}

impl From<Rating> for ReviewInput {
    fn from(rating: Rating) -> Self {
        Self::from_rating(rating)
    }
}

/// Result of a card review.
#[derive(Debug, Clone)]
pub struct ReviewResult {
    /// Updated card state after review.
    pub card: CardState,
    /// Predicted response time (from Fitts model).
    pub predicted_rt: f64,
    /// Actual response time (if provided).
    pub actual_rt: Option<f64>,
    /// Prediction error (actual - predicted), if RT was provided.
    pub prediction_error: Option<f64>,
    /// Predicted retrievability (0-1).
    pub retrievability: f64,
    /// Calibration result (if RT was provided).
    pub calibration: Option<CalibrationResult>,
}

/// SM-2 scheduler with adaptive Fitts' Law predictions.
///
/// - SM-2 handles interval scheduling (uses rating)
/// - Fitts' Law predicts difficulty (calibrates with response time)
#[derive(Debug, Clone)]
pub struct FittsScheduler {
    pub fitts: FittsModel,
}

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

impl FittsScheduler {
    /// Create scheduler with default Fitts parameters.
    pub fn new() -> Self {
        Self {
            fitts: FittsModel::new(0.5, 0.3),
        }
    }

    /// Create scheduler with custom Fitts model.
    pub fn with_fitts(fitts: FittsModel) -> Self {
        Self { fitts }
    }

    /// Create scheduler with specific learning rate.
    pub fn with_learning_rate(learning_rate: f64) -> Self {
        Self {
            fitts: FittsModel::with_learning_rate(0.5, 0.3, learning_rate),
        }
    }

    /// Process a card review.
    ///
    /// # Flow
    ///
    /// 1. **SM-2** uses rating → calculates next interval and updates EF
    /// 2. **Fitts** uses response_time (if provided) → calibrates model
    ///
    /// # SM-2 Interval Calculation
    ///
    /// - If failed (quality < 3): Reset to repetition 0, interval = 1
    /// - If success:
    ///   - rep 0 → interval = 1
    ///   - rep 1 → interval = 6
    ///   - rep n → interval = prev × EF
    pub fn review(&mut self, mut card: CardState, input: impl Into<ReviewInput>) -> ReviewResult {
        let input = input.into();
        let quality = input.rating.to_quality();

        // Fitts prediction (before update) - capture OLD state for calibration
        let (predicted_rt, retrievability) = self.predict(&card);
        let old_interval = card.interval_days.max(1.0);
        let old_ease = card.ease_factor;

        // SM-2 interval calculation
        // quality >= 1 is success (Hard, Good, Easy)
        // quality < 1 is failure (Again only)
        if quality < 1 {
            // Failed: reset repetitions, short interval
            card.repetitions = 0;
            card.interval_days = 1.0;
            card.lapses += 1;
        } else {
            // Success: increase interval
            card.interval_days = match card.repetitions {
                0 => 1.0,
                1 => 6.0,
                _ => (card.interval_days * card.ease_factor).round(),
            };
            card.repetitions += 1;
        }

        // SM-2 ease factor update
        // Our quality is 0-3, but SM-2 formula expects 0-5 scale
        // Map quality [0,3] to SM-2 equivalent [1,5]: mapped_q = 1 + quality * (4/3)
        let q = quality as f64;
        // Linear scaling: 0→1.0, 1→2.33, 2→3.67, 3→5.0
        let q_scaled = 1.0 + (q * 4.0 / 3.0);
        // Apply SM-2 ease factor formula with scaled quality
        let ease_delta = 0.1 - (5.0 - q_scaled) * (0.08 + (5.0 - q_scaled) * 0.02);
        card.ease_factor = (card.ease_factor + ease_delta).max(1.3);

        card.last_review = Some(Utc::now());

        // Fitts calibration (if response time provided)
        // IMPORTANT: Use OLD state (before SM-2 update) for calibration
        // because the user's response time was for the OLD difficulty
        let (actual_rt, prediction_error, calibration) = if input.response_time_ms > 0 {
            let actual = input.response_time_seconds();
            let stability = old_interval; // Use OLD values
            let cal = self
                .fitts
                .calibrate(old_interval, old_ease, stability, actual);
            (Some(actual), Some(cal.error), Some(cal))
        } else {
            (None, None, None)
        };

        ReviewResult {
            card,
            predicted_rt,
            actual_rt,
            prediction_error,
            retrievability,
            calibration,
        }
    }

    /// Predict difficulty using Fitts' Law.
    ///
    /// Returns (predicted_response_time, retrievability).
    pub fn predict(&self, card: &CardState) -> (f64, f64) {
        let interval = card.interval_days.max(1.0);
        let ease = card.ease_factor;
        let stability = interval;

        self.fitts.predict(interval, ease, stability)
    }

    /// Order cards by predicted difficulty (hardest first).
    pub fn order_by_difficulty(&self, cards: &mut [CardState]) {
        cards.sort_by(|a, b| {
            let (rt_a, _) = self.predict(a);
            let (rt_b, _) = self.predict(b);
            rt_b.partial_cmp(&rt_a).unwrap_or(std::cmp::Ordering::Equal)
        });
    }

    /// Get current Fitts model parameters.
    pub fn model_params(&self) -> (f64, f64) {
        (self.fitts.params.a, self.fitts.params.b)
    }
}

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

    #[test]
    fn test_rating_quality_mapping() {
        assert_eq!(Rating::Again.to_quality(), 0);
        assert_eq!(Rating::Hard.to_quality(), 1);
        assert_eq!(Rating::Good.to_quality(), 2);
        assert_eq!(Rating::Easy.to_quality(), 3);
    }

    #[test]
    fn test_rating_is_success() {
        // Only Again is failure (quality 0)
        assert!(!Rating::Again.is_success());
        // Hard, Good, Easy are all successes (quality >= 1)
        assert!(Rating::Hard.is_success());
        assert!(Rating::Good.is_success());
        assert!(Rating::Easy.is_success());
    }

    #[test]
    fn test_review_input_creation() {
        let input = ReviewInput::new(Rating::Good, 2500);
        assert_eq!(input.rating, Rating::Good);
        assert_eq!(input.response_time_ms, 2500);
        assert!((input.response_time_seconds() - 2.5).abs() < 0.001);
    }

    #[test]
    fn test_review_with_rating_only() {
        let mut scheduler = FittsScheduler::new();
        let card = CardState::default();

        let result = scheduler.review(card, Rating::Good);
        assert_eq!(result.card.interval_days, 1.0);
        assert!(result.actual_rt.is_none());
        assert!(result.calibration.is_none());
    }

    #[test]
    fn test_review_with_response_time() {
        let mut scheduler = FittsScheduler::with_learning_rate(0.1);
        let card = CardState::default();

        let input = ReviewInput::new(Rating::Good, 3000);
        let result = scheduler.review(card, input);

        assert_eq!(result.card.interval_days, 1.0);
        assert!(result.actual_rt.is_some());
        assert!((result.actual_rt.unwrap() - 3.0).abs() < 0.001);
        assert!(result.calibration.is_some());
    }

    #[test]
    fn test_calibration_improves_predictions() {
        let mut scheduler = FittsScheduler::with_learning_rate(0.1);

        // Simulate a user who consistently responds in ~2 seconds
        let actual_rt_ms = 2000;

        for _ in 0..20 {
            let card = CardState {
                interval_days: 7.0,
                ease_factor: 2.5,
                ..Default::default()
            };
            let input = ReviewInput::new(Rating::Good, actual_rt_ms);
            scheduler.review(card, input);
        }

        // After calibration, predictions should be closer to 2 seconds
        let card = CardState {
            interval_days: 7.0,
            ease_factor: 2.5,
            ..Default::default()
        };
        let (predicted, _) = scheduler.predict(&card);

        // Should be closer to 2.0 than original prediction
        assert!(
            predicted > 1.0 && predicted < 4.0,
            "Prediction should be calibrated towards actual RT"
        );
    }

    #[test]
    fn test_sm2_new_card() {
        let mut scheduler = FittsScheduler::new();
        let card = CardState::default();

        let result = scheduler.review(card, Rating::Good);
        assert_eq!(result.card.interval_days, 1.0);
        assert_eq!(result.card.repetitions, 1);
    }

    #[test]
    fn test_sm2_progression() {
        let mut scheduler = FittsScheduler::new();
        let mut card = CardState::default();

        card = scheduler.review(card, Rating::Good).card;
        assert_eq!(card.interval_days, 1.0);

        card = scheduler.review(card, Rating::Good).card;
        assert_eq!(card.interval_days, 6.0);

        card = scheduler.review(card, Rating::Good).card;
        assert!(card.interval_days > 6.0);
    }

    #[test]
    fn test_sm2_hard_is_success() {
        let mut scheduler = FittsScheduler::new();
        let card = CardState::default();

        let result = scheduler.review(card, Rating::Hard);
        // Hard (quality 1) is success (>= 1)
        assert_eq!(result.card.repetitions, 1);
        assert_eq!(result.card.lapses, 0);
        assert_eq!(result.card.interval_days, 1.0);
    }

    #[test]
    fn test_sm2_lapse() {
        let mut scheduler = FittsScheduler::new();
        let card = CardState {
            interval_days: 30.0,
            ease_factor: 2.5,
            repetitions: 5,
            lapses: 0,
            last_review: None,
        };

        let result = scheduler.review(card, Rating::Again);
        assert_eq!(result.card.interval_days, 1.0);
        assert_eq!(result.card.repetitions, 0);
        assert_eq!(result.card.lapses, 1);
    }

    #[test]
    fn test_ease_factor_bounds() {
        let mut scheduler = FittsScheduler::new();
        let mut card = CardState::default();

        for _ in 0..10 {
            card = scheduler.review(card, Rating::Again).card;
        }
        assert!(card.ease_factor >= 1.3);
    }

    #[test]
    fn test_quality_scaling_to_sm2() {
        // Verify quality mapping to SM-2 scale
        // Our scale: 0, 1, 2, 3
        // SM-2 scale: 1, 2.33, 3.67, 5
        let test_cases: [(f64, f64); 4] = [
            (0.0, 1.0),   // Again
            (1.0, 2.333), // Hard
            (2.0, 3.667), // Good
            (3.0, 5.0),   // Easy
        ];

        for (q, expected) in test_cases.iter() {
            let q_scaled = 1.0 + (q * 4.0 / 3.0);
            assert!(
                (q_scaled - expected).abs() < 0.01,
                "Quality {} should map to ~{}, got {}",
                q,
                expected,
                q_scaled
            );
        }
    }

    #[test]
    fn test_order_by_difficulty() {
        let scheduler = FittsScheduler::new();
        let mut cards = vec![
            CardState {
                interval_days: 1.0,
                ease_factor: 2.5,
                ..Default::default()
            },
            CardState {
                interval_days: 30.0,
                ease_factor: 1.5,
                ..Default::default()
            },
            CardState {
                interval_days: 7.0,
                ease_factor: 2.0,
                ..Default::default()
            },
        ];

        scheduler.order_by_difficulty(&mut cards);

        let (rt_first, _) = scheduler.predict(&cards[0]);
        let (rt_last, _) = scheduler.predict(&cards[cards.len() - 1]);
        assert!(rt_first >= rt_last);
    }
}