primal-barracuda 0.4.0

barraCuda — BARrier-free Rust Abstracted Cross-platform Unified Dimensional Algebra. Vendor-agnostic GPU compute via WGSL.
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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Evaluation recording for optimization and surrogate training
//!
//! Captures every function evaluation during optimization, not just the best.
//! This is critical for surrogate learning: RBF models are trained on ALL
//! accumulated evaluations, providing both good regions (from optimizer
//! convergence) and exploratory regions (from initial sampling).
//!
//! # Key Insight
//!
//! The `SparsitySampler` algorithm from Diaw et al. (2024) trains surrogates
//! on ALL evaluations, not just the best. This provides the surrogate with
//! both exploitation data (near optima) and exploration data (away from
//! optima), leading to dramatically better surrogate accuracy.
//!
//! # Cross-Domain Applications
//!
//! - **Surrogate learning**: Train RBF on all evaluations
//! - **Bayesian optimization**: Build GP model from evaluation history
//! - **Sensitivity analysis**: Analyze function behavior across parameter space
//! - **Debugging**: Inspect optimization trajectories
//!
//! # Persistence
//!
//! The cache can be saved and loaded for warm-starting:
//!
//! ```ignore
//! // Save after optimization
//! cache.save("results/cache.json")?;
//!
//! // Load for warm-start in next run
//! let cache = EvaluationCache::load("results/cache.json")?;
//! ```

use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;

use crate::error::{BarracudaError, Result};

/// A single function evaluation record: input point and output value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvaluationRecord {
    /// Input point (parameter vector)
    pub x: Vec<f64>,
    /// Function value at this point
    pub f: f64,
}

/// Accumulates all function evaluations during optimization.
///
/// Wraps an objective function to transparently capture every evaluation.
/// The cache provides training data for surrogate models.
///
/// # Examples
///
/// ```
/// use barracuda::optimize::EvaluationCache;
///
/// let mut cache = EvaluationCache::new();
///
/// // Evaluate and record
/// let f = |x: &[f64]| x[0].powi(2) + x[1].powi(2);
/// let x = vec![1.0, 2.0];
/// let val = f(&x);
/// cache.record(x, val);
///
/// assert_eq!(cache.len(), 1);
/// assert_eq!(cache.best_f(), Some(5.0));
/// ```
///
/// # Persistence
///
/// ```ignore
/// // Save to JSON
/// cache.save("results/optimization_cache.json")?;
///
/// // Load from previous run
/// let cache = EvaluationCache::load("results/optimization_cache.json")?;
///
/// // Or load with fallback to empty cache
/// let cache = EvaluationCache::load_or_new("results/cache.json");
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct EvaluationCache {
    /// All recorded evaluations in chronological order
    records: Vec<EvaluationRecord>,
    /// Best function value seen so far (recomputed on load)
    #[serde(skip)]
    best_idx: Option<usize>,
}

impl EvaluationCache {
    /// Create a new empty evaluation cache.
    #[must_use]
    pub fn new() -> Self {
        Self {
            records: Vec::new(),
            best_idx: None,
        }
    }

    /// Create a cache with pre-allocated capacity.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            records: Vec::with_capacity(capacity),
            best_idx: None,
        }
    }

    /// Record a function evaluation.
    pub fn record(&mut self, x: Vec<f64>, f: f64) {
        let idx = self.records.len();
        self.records.push(EvaluationRecord { x, f });

        // Update best
        match self.best_idx {
            None => self.best_idx = Some(idx),
            Some(best) => {
                if f < self.records[best].f {
                    self.best_idx = Some(idx);
                }
            }
        }
    }

    /// Number of recorded evaluations.
    #[must_use]
    pub fn len(&self) -> usize {
        self.records.len()
    }

    /// Whether the cache is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.records.is_empty()
    }

    /// Best function value seen, if any.
    #[must_use]
    pub fn best_f(&self) -> Option<f64> {
        self.best_idx.map(|idx| self.records[idx].f)
    }

    /// Best point found so far, if any.
    #[must_use]
    pub fn best_x(&self) -> Option<&[f64]> {
        self.best_idx.map(|idx| self.records[idx].x.as_slice())
    }

    /// Best evaluation record, if any.
    #[must_use]
    pub fn best(&self) -> Option<&EvaluationRecord> {
        self.best_idx.map(|idx| &self.records[idx])
    }

    /// Get all recorded evaluations as a slice.
    #[must_use]
    pub fn records(&self) -> &[EvaluationRecord] {
        &self.records
    }

    /// Extract training data: (X, y) where X is matrix of inputs, y is vector of outputs.
    ///
    /// Returns `(x_data, y_data)` suitable for feeding into `RBFSurrogate::train()`.
    #[must_use]
    pub fn training_data(&self) -> (Vec<Vec<f64>>, Vec<f64>) {
        let x_data: Vec<Vec<f64>> = self.records.iter().map(|r| r.x.clone()).collect();
        let y_data: Vec<f64> = self.records.iter().map(|r| r.f).collect();
        (x_data, y_data)
    }

    /// Merge another cache into this one.
    ///
    /// Useful for combining results from multiple parallel solvers.
    pub fn merge(&mut self, other: &Self) {
        for record in &other.records {
            self.record(record.x.clone(), record.f);
        }
    }

    // === Persistence Methods ===

    /// Save cache to a JSON file.
    ///
    /// The file can be loaded later with [`EvaluationCache::load`] for
    /// warm-starting optimization or surrogate training.
    ///
    /// # Example
    ///
    /// ```ignore
    /// cache.save("results/optimization_cache.json")?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Err`] if file creation fails (e.g. permission denied, invalid
    /// path) or JSON serialization fails.
    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let file = File::create(path.as_ref())
            .map_err(|e| BarracudaError::Internal(format!("Failed to create cache file: {e}")))?;
        let writer = BufWriter::new(file);
        serde_json::to_writer_pretty(writer, self)
            .map_err(|e| BarracudaError::Internal(format!("Failed to serialize cache: {e}")))?;
        Ok(())
    }

    /// Load cache from a JSON file.
    ///
    /// Recomputes the `best_idx` after loading (not serialized).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let cache = EvaluationCache::load("results/optimization_cache.json")?;
    /// tracing::info!("Loaded {} evaluations, best: {:?}", cache.len(), cache.best_f());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Err`] if the file cannot be opened (e.g. not found,
    /// permission denied) or JSON deserialization fails.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
        let file = File::open(path.as_ref())
            .map_err(|e| BarracudaError::Internal(format!("Failed to open cache file: {e}")))?;
        let reader = BufReader::new(file);
        let mut cache: Self = serde_json::from_reader(reader)
            .map_err(|e| BarracudaError::Internal(format!("Failed to deserialize cache: {e}")))?;

        // Recompute best_idx
        cache.recompute_best();
        Ok(cache)
    }

    /// Load cache from file, or create a new empty cache if file doesn't exist.
    ///
    /// This is useful for warm-starting: on first run, creates empty cache;
    /// on subsequent runs, loads previous results.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // First run: creates empty cache
    /// // Subsequent runs: loads from file
    /// let mut cache = EvaluationCache::load_or_new("results/cache.json");
    /// ```
    pub fn load_or_new<P: AsRef<Path>>(path: P) -> Self {
        match Self::load(&path) {
            Ok(cache) => cache,
            Err(e) => {
                tracing::debug!("EvaluationCache: starting fresh (load failed: {e})");
                Self::default()
            }
        }
    }

    /// Create a cache from existing training data.
    ///
    /// Useful for initializing from external data sources.
    ///
    /// # Arguments
    ///
    /// * `x_data` - Vector of input points
    /// * `y_data` - Vector of function values
    ///
    /// # Example
    ///
    /// ```
    /// use barracuda::optimize::EvaluationCache;
    ///
    /// let x_data = vec![vec![0.0, 0.0], vec![1.0, 1.0]];
    /// let y_data = vec![0.0, 2.0];
    /// let cache = EvaluationCache::from_training_data(x_data, y_data);
    /// assert_eq!(cache.len(), 2);
    /// ```
    #[must_use]
    pub fn from_training_data(x_data: Vec<Vec<f64>>, y_data: Vec<f64>) -> Self {
        let mut cache = Self::with_capacity(x_data.len());
        for (x, f) in x_data.into_iter().zip(y_data) {
            cache.record(x, f);
        }
        cache
    }

    /// Recompute the `best_idx` from records.
    ///
    /// Called after deserialization (`best_idx` is not serialized).
    fn recompute_best(&mut self) {
        self.best_idx = None;
        if self.records.is_empty() {
            return;
        }

        let mut best = 0;
        for (i, record) in self.records.iter().enumerate() {
            if record.f < self.records[best].f {
                best = i;
            }
        }
        self.best_idx = Some(best);
    }
}

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

    #[test]
    fn test_cache_basic() {
        let mut cache = EvaluationCache::new();
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
        assert!(cache.best_f().is_none());

        cache.record(vec![1.0, 2.0], 5.0);
        assert_eq!(cache.len(), 1);
        assert!(!cache.is_empty());
        assert_eq!(cache.best_f(), Some(5.0));
    }

    #[test]
    fn test_cache_tracks_best() {
        let mut cache = EvaluationCache::new();

        cache.record(vec![0.0], 10.0);
        cache.record(vec![1.0], 3.0); // best
        cache.record(vec![2.0], 7.0);
        cache.record(vec![3.0], 15.0);

        assert_eq!(cache.best_f(), Some(3.0));
        assert_eq!(cache.best_x(), Some(vec![1.0].as_slice()));
    }

    #[test]
    fn test_cache_training_data() {
        let mut cache = EvaluationCache::new();
        cache.record(vec![1.0, 2.0], 5.0);
        cache.record(vec![3.0, 4.0], 7.0);

        let (x_data, y_data) = cache.training_data();
        assert_eq!(x_data.len(), 2);
        assert_eq!(y_data.len(), 2);
        assert_eq!(x_data[0], vec![1.0, 2.0]);
        assert_eq!(y_data[1], 7.0);
    }

    #[test]
    fn test_cache_merge() {
        let mut a = EvaluationCache::new();
        a.record(vec![0.0], 10.0);
        a.record(vec![1.0], 5.0);

        let mut b = EvaluationCache::new();
        b.record(vec![2.0], 3.0); // best overall
        b.record(vec![3.0], 8.0);

        a.merge(&b);
        assert_eq!(a.len(), 4);
        assert_eq!(a.best_f(), Some(3.0));
    }

    #[test]
    fn test_cache_with_capacity() {
        let cache = EvaluationCache::with_capacity(1000);
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_eval_record_clone() {
        let record = EvaluationRecord {
            x: vec![1.0, 2.0, 3.0],
            f: 42.0,
        };
        let cloned = record;
        assert_eq!(cloned.x, vec![1.0, 2.0, 3.0]);
        assert_eq!(cloned.f, 42.0);
    }

    #[test]
    fn test_from_training_data() {
        let x_data = vec![vec![1.0, 2.0], vec![3.0, 4.0], vec![0.0, 0.0]];
        let y_data = vec![5.0, 7.0, 0.0];

        let cache = EvaluationCache::from_training_data(x_data, y_data);

        assert_eq!(cache.len(), 3);
        assert_eq!(cache.best_f(), Some(0.0)); // 0.0 is the minimum
        assert_eq!(cache.best_x(), Some(vec![0.0, 0.0].as_slice()));
    }

    #[test]
    fn test_save_load_roundtrip() {
        let mut cache = EvaluationCache::new();
        cache.record(vec![1.0, 2.0], 5.0);
        cache.record(vec![3.0, 4.0], 2.0); // best
        cache.record(vec![5.0, 6.0], 8.0);

        let tmp = tempfile::NamedTempFile::new().expect("Failed to create temp file");
        let temp_path = tmp.path().to_str().expect("non-UTF-8 path");

        cache.save(temp_path).expect("Failed to save");
        let loaded = EvaluationCache::load(temp_path).expect("Failed to load");

        assert_eq!(loaded.len(), 3);
        assert_eq!(loaded.best_f(), Some(2.0));
        assert_eq!(loaded.best_x(), Some(vec![3.0, 4.0].as_slice()));
    }

    #[test]
    fn test_load_or_new_nonexistent() {
        let cache = EvaluationCache::load_or_new("/nonexistent/path/cache.json");
        assert!(cache.is_empty());
    }

    #[test]
    fn test_load_or_new_existing() {
        let mut original = EvaluationCache::new();
        original.record(vec![1.0], 42.0);

        let tmp = tempfile::NamedTempFile::new().expect("Failed to create temp file");
        let temp_path = tmp.path().to_str().expect("non-UTF-8 path");
        original.save(temp_path).expect("Failed to save");

        let loaded = EvaluationCache::load_or_new(temp_path);
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded.best_f(), Some(42.0));
    }

    #[test]
    fn test_serialization_format() {
        let mut cache = EvaluationCache::new();
        cache.record(vec![1.0, 2.0], 5.0);

        let json = serde_json::to_string(&cache).expect("Failed to serialize");

        // Verify it's valid JSON containing our data
        assert!(json.contains("1.0"));
        assert!(json.contains("2.0"));
        assert!(json.contains("5.0"));
    }

    #[test]
    fn test_recompute_best_on_load() {
        let mut cache = EvaluationCache::new();
        cache.record(vec![0.0], 100.0);
        cache.record(vec![1.0], 1.0); // best
        cache.record(vec![2.0], 50.0);

        let tmp = tempfile::NamedTempFile::new().expect("Failed to create temp file");
        let temp_path = tmp.path().to_str().expect("non-UTF-8 path");
        cache.save(temp_path).expect("Failed to save");

        let loaded = EvaluationCache::load(temp_path).expect("Failed to load");
        assert_eq!(loaded.best_f(), Some(1.0));
        assert_eq!(loaded.best_x(), Some(vec![1.0].as_slice()));
    }
}