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
//! Fitts' Law memory model with adaptive calibration.
//!
//! # Fitts' Law
//!
//! Original Fitts' Law (1954) for motor tasks:
//!
//! ```text
//! MT = a + b × log₂(D/W + 1)
//! ```
//!
//! Where:
//! - MT = movement time
//! - D = distance to target
//! - W = width of target
//! - a, b = empirically determined constants
//!
//! # Memory Adaptation
//!
//! We adapt Fitts' Law to model memory retrieval:
//!
//! ```text
//! RT = a + b × log₂(distance / accessibility + 1)
//! ```
//!
//! Where:
//! - RT = predicted response time (cognitive effort)
//! - distance = memory decay factor (increases with time since last review)
//! - accessibility = memory strength (increases with stability and ease)
//!
//! # Adaptive Calibration
//!
//! Based on ACT-R (Anderson, 1993) and Pavlik & Anderson (2008):
//!
//! After each review, we update parameters using gradient descent:
//! ```text
//! error = RT_actual - RT_predicted
//! a_new = a + α × error
//! b_new = b + α × error × ID
//! ```
//!
//! Where ID = log₂(distance/accessibility + 1) is already computed.
//!
//! This allows the model to personalize to each user's response patterns.
//!
//! # Example
//!
//! ```rust
//! use fitts::FittsModel;
//!
//! let mut model = FittsModel::new(0.5, 0.3);
//!
//! // Predict response time
//! let predicted = model.response_time(7.0, 2.5, 5.0);
//!
//! // After measuring actual response time, calibrate
//! model.calibrate(7.0, 2.5, 5.0, 3.2); // actual RT was 3.2s
//! ```

use serde::{Deserialize, Serialize};
use std::fmt;

/// Fitts model parameters.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct FittsParameters {
    /// Base response time (intercept).
    pub a: f64,
    /// Scaling factor for difficulty (slope).
    pub b: f64,
    /// Multiplier for memory distance calculation.
    pub distance_factor: f64,
    /// Multiplier for memory accessibility calculation.
    pub accessibility_factor: f64,
    /// Response time threshold for retrievability calculation.
    pub threshold: f64,
    /// Learning rate for adaptive calibration (0.0 to disable).
    pub learning_rate: f64,
}

impl FittsParameters {
    /// Create new parameters with validation.
    pub fn new(
        a: f64,
        b: f64,
        distance_factor: f64,
        accessibility_factor: f64,
        threshold: f64,
        learning_rate: f64,
    ) -> Result<Self, FittsError> {
        let params = Self {
            a,
            b,
            distance_factor,
            accessibility_factor,
            threshold,
            learning_rate,
        };
        params.validate()?;
        Ok(params)
    }

    /// Validate parameter bounds.
    pub fn validate(&self) -> Result<(), FittsError> {
        if !self.a.is_finite()
            || !self.b.is_finite()
            || !self.distance_factor.is_finite()
            || !self.accessibility_factor.is_finite()
            || !self.threshold.is_finite()
            || !self.learning_rate.is_finite()
        {
            return Err(FittsError::InvalidParameters(
                "Parameters must be finite".into(),
            ));
        }

        if self.a <= 0.0
            || self.b <= 0.0
            || self.distance_factor <= 0.0
            || self.accessibility_factor <= 0.0
            || self.threshold <= 0.0
        {
            return Err(FittsError::InvalidParameters(
                "Core parameters must be positive".into(),
            ));
        }

        if self.learning_rate < 0.0 || self.learning_rate > 1.0 {
            return Err(FittsError::InvalidParameters(
                "Learning rate must be in [0, 1]".into(),
            ));
        }

        Ok(())
    }
}

impl Default for FittsParameters {
    fn default() -> Self {
        Self {
            a: 0.5, // Base response time (500ms)
            b: 0.3, // Difficulty scaling
            distance_factor: 1.0,
            accessibility_factor: 1.0,
            threshold: 2.0,      // RT threshold for retrievability sigmoid
            learning_rate: 0.05, // Adaptive learning rate
        }
    }
}

/// Fitts' Law memory model with adaptive calibration.
///
/// Predicts cognitive difficulty (response time) and retrievability
/// for memory items. Calibrates itself using actual response times.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
pub struct FittsModel {
    pub params: FittsParameters,
}

impl FittsModel {
    /// Create model with specified a and b parameters.
    pub fn new(a: f64, b: f64) -> Self {
        Self {
            params: FittsParameters {
                a: a.clamp(0.01, 10.0),
                b: b.clamp(0.01, 5.0),
                ..Default::default()
            },
        }
    }

    /// Create model with adaptive calibration enabled.
    pub fn with_learning_rate(a: f64, b: f64, learning_rate: f64) -> Self {
        Self {
            params: FittsParameters {
                a: a.clamp(0.01, 10.0),
                b: b.clamp(0.01, 5.0),
                learning_rate: learning_rate.clamp(0.0, 1.0),
                ..Default::default()
            },
        }
    }

    /// Create model with full parameter validation.
    pub fn with_validated_params(params: FittsParameters) -> Result<Self, FittsError> {
        params.validate()?;
        Ok(Self { params })
    }

    /// Create model with custom parameters (no validation).
    pub fn with_params(params: FittsParameters) -> Self {
        Self { params }
    }

    /// Calculate memory distance (decay factor).
    ///
    /// Distance increases with:
    /// - Longer intervals (more time since review)
    /// - Lower ease factors (harder items)
    ///
    /// Formula: `distance_factor × ln(1 + interval) × (1 / ease)`
    pub fn memory_distance(&self, interval_days: f64, ease: f64) -> f64 {
        let interval = interval_days.clamp(0.0, 1e6);
        let safe_ease = ease.clamp(1.0, 5.0);

        let time_factor = (1.0 + interval).ln();
        let ease_penalty = 1.0 / safe_ease;
        let distance = self.params.distance_factor * time_factor * ease_penalty;

        distance.clamp(0.0, 100.0)
    }

    /// Calculate memory accessibility (strength factor).
    ///
    /// Accessibility increases with:
    /// - Higher stability (more reinforced memories)
    /// - Higher ease factors (easier items)
    ///
    /// Formula: `accessibility_factor × stability × ease`
    pub fn memory_accessibility(&self, stability: f64, ease: f64) -> f64 {
        let safe_stability = stability.clamp(0.01, 1000.0);
        let safe_ease = ease.clamp(1.0, 5.0);
        let accessibility = self.params.accessibility_factor * safe_stability * safe_ease;
        accessibility.max(0.01)
    }

    /// Calculate index of difficulty (ID).
    ///
    /// ID = log₂(distance / accessibility + 1)
    pub fn index_of_difficulty(&self, interval_days: f64, ease: f64, stability: f64) -> f64 {
        let distance = self.memory_distance(interval_days, ease);
        let accessibility = self.memory_accessibility(stability, ease);
        let ratio = distance / accessibility;
        (ratio + 1.0).log2().max(0.0)
    }

    /// Predict response time using Fitts' Law.
    ///
    /// Higher RT indicates more cognitive effort required.
    ///
    /// Formula: `RT = a + b × log₂(distance / accessibility + 1)`
    pub fn response_time(&self, interval_days: f64, ease: f64, stability: f64) -> f64 {
        if interval_days < 0.0 || ease <= 0.0 || stability <= 0.0 {
            return self.params.a;
        }

        let id = self.index_of_difficulty(interval_days, ease, stability);

        if !id.is_finite() {
            return self.params.a;
        }

        let rt = self.params.a + self.params.b * id;
        rt.max(0.0)
    }

    /// Predict retrievability (probability of successful recall).
    ///
    /// Uses logistic function that decreases with response time:
    /// `R = 1 / (1 + exp((RT - threshold) / scale))`
    ///
    /// - When RT < threshold: R > 0.5 (likely to recall)
    /// - When RT = threshold: R = 0.5 (50/50 chance)
    /// - When RT > threshold: R < 0.5 (unlikely to recall)
    ///
    /// This models the relationship: harder cards (higher RT) = lower recall probability.
    pub fn retrievability(&self, interval_days: f64, ease: f64, stability: f64) -> f64 {
        let rt = self.response_time(interval_days, ease, stability);
        let threshold = self.params.threshold.max(0.1);
        let scale = threshold / 2.0; // Controls steepness of sigmoid
        let exponent = ((rt - threshold) / scale).clamp(-700.0, 700.0);
        let r = 1.0 / (1.0 + exponent.exp());
        r.clamp(0.0, 1.0)
    }

    /// Predict both response time and retrievability.
    pub fn predict(&self, interval_days: f64, ease: f64, stability: f64) -> (f64, f64) {
        let rt = self.response_time(interval_days, ease, stability);
        let r = self.retrievability(interval_days, ease, stability);
        (rt, r)
    }

    /// Calibrate model using actual response time.
    ///
    /// Updates parameters using gradient descent:
    /// ```text
    /// error = actual_rt - predicted_rt
    /// a += learning_rate × error
    /// b += learning_rate × error × ID
    /// ```
    ///
    /// Based on ACT-R (Anderson, 1993) and Pavlik & Anderson (2008).
    pub fn calibrate(
        &mut self,
        interval_days: f64,
        ease: f64,
        stability: f64,
        actual_rt_seconds: f64,
    ) -> CalibrationResult {
        let predicted_rt = self.response_time(interval_days, ease, stability);
        let error = actual_rt_seconds - predicted_rt;
        let id = self.index_of_difficulty(interval_days, ease, stability);

        let lr = self.params.learning_rate;
        if lr > 0.0 {
            // Gradient descent update
            let a_update = lr * error;
            let b_update = lr * error * id;

            self.params.a = (self.params.a + a_update).clamp(0.01, 10.0);
            self.params.b = (self.params.b + b_update).clamp(0.01, 5.0);
        }

        CalibrationResult {
            predicted_rt,
            actual_rt: actual_rt_seconds,
            error,
            new_a: self.params.a,
            new_b: self.params.b,
        }
    }
}

/// Result of a calibration step.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CalibrationResult {
    /// What the model predicted.
    pub predicted_rt: f64,
    /// What actually happened.
    pub actual_rt: f64,
    /// Error (actual - predicted).
    pub error: f64,
    /// Updated 'a' parameter.
    pub new_a: f64,
    /// Updated 'b' parameter.
    pub new_b: f64,
}

impl fmt::Display for FittsModel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "FittsModel(a={:.3}, b={:.3}, lr={:.3})",
            self.params.a, self.params.b, self.params.learning_rate
        )
    }
}

/// Errors in Fitts model operations.
#[derive(Debug, Clone, PartialEq)]
pub enum FittsError {
    /// Invalid parameter values.
    InvalidParameters(String),
    /// Numerical computation error.
    ComputationError(String),
}

impl fmt::Display for FittsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FittsError::InvalidParameters(msg) => write!(f, "Invalid parameters: {msg}"),
            FittsError::ComputationError(msg) => write!(f, "Computation error: {msg}"),
        }
    }
}

impl std::error::Error for FittsError {}

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

    #[test]
    fn test_model_creation() {
        let model = FittsModel::new(0.5, 0.3);
        assert_eq!(model.params.a, 0.5);
        assert_eq!(model.params.b, 0.3);
    }

    #[test]
    fn test_memory_distance() {
        let model = FittsModel::default();

        // Distance increases with interval
        let dist1 = model.memory_distance(1.0, 2.0);
        let dist2 = model.memory_distance(10.0, 2.0);
        assert!(dist2 > dist1, "Distance should increase with interval");

        // Distance decreases with ease
        let dist_low = model.memory_distance(7.0, 1.5);
        let dist_high = model.memory_distance(7.0, 2.5);
        assert!(dist_low > dist_high, "Distance should decrease with ease");
    }

    #[test]
    fn test_memory_accessibility() {
        let model = FittsModel::default();

        // Accessibility increases with stability
        let acc1 = model.memory_accessibility(1.0, 2.0);
        let acc2 = model.memory_accessibility(10.0, 2.0);
        assert!(acc2 > acc1);

        // Accessibility increases with ease
        let acc_low = model.memory_accessibility(5.0, 1.5);
        let acc_high = model.memory_accessibility(5.0, 2.5);
        assert!(acc_high > acc_low);
    }

    #[test]
    fn test_response_time_properties() {
        let model = FittsModel::new(0.5, 0.3);

        // RT is always positive
        let rt = model.response_time(7.0, 2.0, 5.0);
        assert!(rt > 0.0);

        // RT >= a (base response time)
        assert!(rt >= model.params.a);
    }

    #[test]
    fn test_retrievability_bounds() {
        let model = FittsModel::default();

        for interval in [0.0, 1.0, 7.0, 30.0, 365.0] {
            let r = model.retrievability(interval, 2.0, 5.0);
            assert!((0.0..=1.0).contains(&r), "Retrievability must be in [0,1]");
        }
    }

    #[test]
    fn test_retrievability_decreases_with_rt() {
        let model = FittsModel::default();

        // Easy card (short interval, high ease) should have higher retrievability
        let r_easy = model.retrievability(1.0, 2.5, 10.0);
        // Hard card (long interval, low ease) should have lower retrievability
        let r_hard = model.retrievability(30.0, 1.5, 1.0);

        assert!(
            r_easy > r_hard,
            "Easy cards should have higher retrievability: {} vs {}",
            r_easy,
            r_hard
        );
    }

    #[test]
    fn test_calibration_reduces_error() {
        let mut model = FittsModel::with_learning_rate(0.5, 0.3, 0.1);

        let interval = 7.0;
        let ease = 2.0;
        let stability = 5.0;
        let actual_rt = 2.0; // Actual was 2 seconds

        let initial_prediction = model.response_time(interval, ease, stability);
        let initial_error = (actual_rt - initial_prediction).abs();

        // Calibrate multiple times
        for _ in 0..10 {
            model.calibrate(interval, ease, stability, actual_rt);
        }

        let final_prediction = model.response_time(interval, ease, stability);
        let final_error = (actual_rt - final_prediction).abs();

        assert!(
            final_error < initial_error,
            "Calibration should reduce error"
        );
    }

    #[test]
    fn test_calibration_disabled_when_lr_zero() {
        let mut model = FittsModel::with_learning_rate(0.5, 0.3, 0.0);
        let original_a = model.params.a;
        let original_b = model.params.b;

        model.calibrate(7.0, 2.0, 5.0, 10.0);

        assert_eq!(model.params.a, original_a);
        assert_eq!(model.params.b, original_b);
    }

    #[test]
    fn test_parameter_validation() {
        assert!(FittsParameters::new(0.5, 0.3, 1.0, 1.0, 2.0, 0.05).is_ok());
        assert!(FittsParameters::new(-0.5, 0.3, 1.0, 1.0, 2.0, 0.05).is_err());
        assert!(FittsParameters::new(0.5, 0.3, 1.0, 1.0, 2.0, 1.5).is_err());
    }

    #[test]
    fn test_numerical_stability() {
        let model = FittsModel::default();

        // Edge cases shouldn't panic
        let _ = model.response_time(0.0, 1.3, 0.01);
        let _ = model.response_time(1000000.0, 5.0, 1000.0);
        let _ = model.response_time(f64::MAX, 2.5, 1.0);
    }
}