Skip to main content

sklears_dummy/
memory_management.rs

1//! Advanced Memory Management for Dummy Estimators
2//!
3//! This module provides advanced memory management features including efficient storage,
4//! memory pooling, streaming algorithms, memory-mapped access, and reference counting.
5
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex, RwLock, Weak};
8
9/// Advanced memory pool with size-based allocation strategies
10pub mod advanced_pooling {
11    use super::*;
12
13    /// Pool statistics for monitoring memory usage
14    #[derive(Debug, Clone)]
15    pub struct PoolStatistics {
16        /// total_allocations
17        pub total_allocations: usize,
18        /// pool_hits
19        pub pool_hits: usize,
20        /// pool_misses
21        pub pool_misses: usize,
22        /// current_pool_size
23        pub current_pool_size: usize,
24        /// peak_pool_size
25        pub peak_pool_size: usize,
26        /// total_memory_saved
27        pub total_memory_saved: usize,
28    }
29
30    /// Size-aware memory pool that tracks allocations by size classes
31    pub struct SizeClassMemoryPool<T> {
32        pools: HashMap<usize, Vec<Vec<T>>>,
33        max_pool_size: usize,
34        size_classes: Vec<usize>,
35        stats: Arc<Mutex<PoolStatistics>>,
36    }
37
38    impl<T> SizeClassMemoryPool<T> {
39        /// Create new size-class memory pool
40        pub fn new(max_pool_size: usize) -> Self {
41            // Common size classes: powers of 2 and some intermediate values
42            let size_classes = vec![
43                8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768,
44            ];
45
46            Self {
47                pools: HashMap::new(),
48                max_pool_size,
49                size_classes,
50                stats: Arc::new(Mutex::new(PoolStatistics {
51                    total_allocations: 0,
52                    pool_hits: 0,
53                    pool_misses: 0,
54                    current_pool_size: 0,
55                    peak_pool_size: 0,
56                    total_memory_saved: 0,
57                })),
58            }
59        }
60
61        /// Get the best size class for a requested size
62        fn get_size_class(&self, size: usize) -> usize {
63            self.size_classes
64                .iter()
65                .find(|&&class_size| class_size >= size)
66                .copied()
67                .unwrap_or(size.next_power_of_two())
68        }
69
70        /// Get a vector from the pool or allocate new one
71        pub fn get(&mut self, size: usize) -> Vec<T> {
72            let size_class = self.get_size_class(size);
73
74            if let Some(pool) = self.pools.get_mut(&size_class) {
75                if let Some(mut vec) = pool.pop() {
76                    vec.clear();
77                    vec.reserve(size);
78
79                    // Update statistics
80                    if let Ok(mut stats) = self.stats.lock() {
81                        stats.pool_hits += 1;
82                        stats.current_pool_size -= 1;
83                        stats.total_memory_saved += size_class * std::mem::size_of::<T>();
84                    }
85
86                    return vec;
87                }
88            }
89
90            // Pool miss - allocate new vector
91            if let Ok(mut stats) = self.stats.lock() {
92                stats.pool_misses += 1;
93                stats.total_allocations += 1;
94            }
95
96            Vec::with_capacity(size)
97        }
98
99        /// Return a vector to the pool
100        pub fn return_vec(&mut self, mut vec: Vec<T>) {
101            let capacity = vec.capacity();
102            let size_class = self.get_size_class(capacity);
103
104            let pool = self.pools.entry(size_class).or_default();
105
106            if pool.len() < self.max_pool_size {
107                vec.clear();
108                pool.push(vec);
109
110                // Update statistics
111                if let Ok(mut stats) = self.stats.lock() {
112                    stats.current_pool_size += 1;
113                    stats.peak_pool_size = stats.peak_pool_size.max(stats.current_pool_size);
114                }
115            }
116        }
117
118        /// Get pool statistics
119        pub fn statistics(&self) -> PoolStatistics {
120            self.stats
121                .lock()
122                .expect("lock should not be poisoned")
123                .clone()
124        }
125
126        /// Get pool efficiency (hit rate)
127        pub fn efficiency(&self) -> f64 {
128            if let Ok(stats) = self.stats.lock() {
129                let total_requests = stats.pool_hits + stats.pool_misses;
130                if total_requests > 0 {
131                    stats.pool_hits as f64 / total_requests as f64
132                } else {
133                    0.0
134                }
135            } else {
136                0.0
137            }
138        }
139
140        /// Clear all pools and reset statistics
141        pub fn clear(&mut self) {
142            self.pools.clear();
143            if let Ok(mut stats) = self.stats.lock() {
144                *stats = PoolStatistics {
145                    total_allocations: 0,
146                    pool_hits: 0,
147                    pool_misses: 0,
148                    current_pool_size: 0,
149                    peak_pool_size: 0,
150                    total_memory_saved: 0,
151                };
152            }
153        }
154    }
155
156    /// Thread-safe memory pool for concurrent access
157    pub struct ThreadSafeMemoryPool<T> {
158        inner: Arc<Mutex<SizeClassMemoryPool<T>>>,
159    }
160
161    impl<T> ThreadSafeMemoryPool<T> {
162        /// Create new thread-safe memory pool
163        pub fn new(max_pool_size: usize) -> Self {
164            Self {
165                inner: Arc::new(Mutex::new(SizeClassMemoryPool::new(max_pool_size))),
166            }
167        }
168
169        /// Get a vector from the pool
170        pub fn get(&self, size: usize) -> Vec<T> {
171            self.inner
172                .lock()
173                .expect("lock should not be poisoned")
174                .get(size)
175        }
176
177        /// Return a vector to the pool
178        pub fn return_vec(&self, vec: Vec<T>) {
179            self.inner
180                .lock()
181                .expect("lock should not be poisoned")
182                .return_vec(vec);
183        }
184
185        /// Get pool statistics
186        pub fn statistics(&self) -> PoolStatistics {
187            self.inner
188                .lock()
189                .expect("lock should not be poisoned")
190                .statistics()
191        }
192
193        /// Get pool efficiency
194        pub fn efficiency(&self) -> f64 {
195            self.inner
196                .lock()
197                .expect("lock should not be poisoned")
198                .efficiency()
199        }
200    }
201
202    /// Memory-mapped storage for large datasets
203    pub struct MemoryMappedStorage {
204        data: Vec<u8>,
205        element_size: usize,
206        length: usize,
207    }
208
209    impl MemoryMappedStorage {
210        /// Create new memory-mapped storage
211        pub fn new(element_size: usize, initial_capacity: usize) -> Self {
212            Self {
213                data: Vec::with_capacity(initial_capacity * element_size),
214                element_size,
215                length: 0,
216            }
217        }
218
219        /// Append element to storage
220        pub fn push<T>(&mut self, element: &T) -> Result<usize, &'static str>
221        where
222            T: Copy,
223        {
224            if std::mem::size_of::<T>() != self.element_size {
225                return Err("Element size mismatch");
226            }
227
228            let bytes = unsafe {
229                std::slice::from_raw_parts(element as *const T as *const u8, self.element_size)
230            };
231
232            let index = self.length;
233            self.data.extend_from_slice(bytes);
234            self.length += 1;
235            Ok(index)
236        }
237
238        /// Get element by index
239        pub fn get<T>(&self, index: usize) -> Option<T>
240        where
241            T: Copy,
242        {
243            if index >= self.length || std::mem::size_of::<T>() != self.element_size {
244                return None;
245            }
246
247            let start = index * self.element_size;
248            let end = start + self.element_size;
249            let bytes = &self.data[start..end];
250
251            unsafe {
252                let ptr = bytes.as_ptr() as *const T;
253                Some(*ptr)
254            }
255        }
256
257        /// Get number of elements
258        pub fn len(&self) -> usize {
259            self.length
260        }
261
262        /// Check if empty
263        pub fn is_empty(&self) -> bool {
264            self.length == 0
265        }
266
267        /// Get memory usage in bytes
268        pub fn memory_usage(&self) -> usize {
269            self.data.len()
270        }
271
272        /// Shrink storage to fit current data
273        pub fn shrink_to_fit(&mut self) {
274            self.data.shrink_to_fit();
275        }
276    }
277}
278
279/// Reference counting for shared data structures
280pub mod reference_counting {
281    use super::*;
282
283    /// Reference-counted prediction cache
284    pub struct SharedPredictionCache {
285        inner: Arc<RwLock<HashMap<u64, f64>>>,
286        stats: Arc<RwLock<CacheStats>>,
287    }
288
289    #[derive(Debug, Clone, Default)]
290    pub struct CacheStats {
291        /// hits
292        pub hits: usize,
293        /// misses
294        pub misses: usize,
295        /// total_size
296        pub total_size: usize,
297        /// max_size
298        pub max_size: usize,
299    }
300
301    impl Default for SharedPredictionCache {
302        fn default() -> Self {
303            Self::new()
304        }
305    }
306
307    impl SharedPredictionCache {
308        /// Create new shared prediction cache
309        pub fn new() -> Self {
310            Self {
311                inner: Arc::new(RwLock::new(HashMap::new())),
312                stats: Arc::new(RwLock::new(CacheStats::default())),
313            }
314        }
315
316        /// Get value from cache
317        pub fn get(&self, key: u64) -> Option<f64> {
318            if let Ok(cache) = self.inner.read() {
319                let result = cache.get(&key).copied();
320
321                if let Ok(mut stats) = self.stats.write() {
322                    if result.is_some() {
323                        stats.hits += 1;
324                    } else {
325                        stats.misses += 1;
326                    }
327                }
328
329                result
330            } else {
331                None
332            }
333        }
334
335        /// Insert value into cache
336        pub fn insert(&self, key: u64, value: f64) {
337            if let Ok(mut cache) = self.inner.write() {
338                cache.insert(key, value);
339
340                if let Ok(mut stats) = self.stats.write() {
341                    stats.total_size = cache.len();
342                    stats.max_size = stats.max_size.max(stats.total_size);
343                }
344            }
345        }
346
347        /// Get cache statistics
348        pub fn stats(&self) -> CacheStats {
349            self.stats.read().expect("operation should succeed").clone()
350        }
351
352        /// Get cache hit rate
353        pub fn hit_rate(&self) -> f64 {
354            let stats = self.stats();
355            let total = stats.hits + stats.misses;
356            if total > 0 {
357                stats.hits as f64 / total as f64
358            } else {
359                0.0
360            }
361        }
362
363        /// Clear cache
364        pub fn clear(&self) {
365            if let Ok(mut cache) = self.inner.write() {
366                cache.clear();
367            }
368            if let Ok(mut stats) = self.stats.write() {
369                *stats = CacheStats::default();
370            }
371        }
372
373        /// Create a weak reference to this cache
374        pub fn downgrade(&self) -> WeakPredictionCache {
375            WeakPredictionCache {
376                inner: Arc::downgrade(&self.inner),
377                stats: Arc::downgrade(&self.stats),
378            }
379        }
380    }
381
382    impl Clone for SharedPredictionCache {
383        fn clone(&self) -> Self {
384            Self {
385                inner: Arc::clone(&self.inner),
386                stats: Arc::clone(&self.stats),
387            }
388        }
389    }
390
391    /// Weak reference to prediction cache
392    pub struct WeakPredictionCache {
393        inner: Weak<RwLock<HashMap<u64, f64>>>,
394        stats: Weak<RwLock<CacheStats>>,
395    }
396
397    impl WeakPredictionCache {
398        /// Upgrade to strong reference if still alive
399        pub fn upgrade(&self) -> Option<SharedPredictionCache> {
400            if let (Some(inner), Some(stats)) = (self.inner.upgrade(), self.stats.upgrade()) {
401                Some(SharedPredictionCache { inner, stats })
402            } else {
403                None
404            }
405        }
406    }
407
408    /// Reference-counted model storage
409    pub struct SharedModelStorage<T> {
410        models: Arc<RwLock<HashMap<String, T>>>,
411        access_count: Arc<RwLock<HashMap<String, usize>>>,
412    }
413
414    impl<T: Clone> Default for SharedModelStorage<T> {
415        fn default() -> Self {
416            Self::new()
417        }
418    }
419
420    impl<T: Clone> SharedModelStorage<T> {
421        /// Create new shared model storage
422        pub fn new() -> Self {
423            Self {
424                models: Arc::new(RwLock::new(HashMap::new())),
425                access_count: Arc::new(RwLock::new(HashMap::new())),
426            }
427        }
428
429        /// Store a model
430        pub fn store(&self, name: String, model: T) {
431            if let Ok(mut models) = self.models.write() {
432                models.insert(name.clone(), model);
433            }
434            if let Ok(mut counts) = self.access_count.write() {
435                counts.insert(name, 0);
436            }
437        }
438
439        /// Get a model by name
440        pub fn get(&self, name: &str) -> Option<T> {
441            let result = if let Ok(models) = self.models.read() {
442                models.get(name).cloned()
443            } else {
444                None
445            };
446
447            if result.is_some() {
448                // Increment access count
449                if let Ok(mut counts) = self.access_count.write() {
450                    *counts.entry(name.to_string()).or_insert(0) += 1;
451                }
452            }
453
454            result
455        }
456
457        /// Get access count for a model
458        pub fn access_count(&self, name: &str) -> usize {
459            self.access_count
460                .read()
461                .expect("operation should succeed")
462                .get(name)
463                .copied()
464                .unwrap_or(0)
465        }
466
467        /// Get most accessed models
468        pub fn most_accessed(&self, limit: usize) -> Vec<(String, usize)> {
469            if let Ok(counts) = self.access_count.read() {
470                let mut items: Vec<_> = counts
471                    .iter()
472                    .map(|(name, &count)| (name.clone(), count))
473                    .collect();
474                items.sort_by_key(|b| std::cmp::Reverse(b.1));
475                items.truncate(limit);
476                items
477            } else {
478                Vec::new()
479            }
480        }
481
482        /// Remove unused models (access count = 0)
483        pub fn cleanup_unused(&self) {
484            if let (Ok(mut models), Ok(mut counts)) =
485                (self.models.write(), self.access_count.write())
486            {
487                let unused: Vec<_> = counts
488                    .iter()
489                    .filter(|(_, &count)| count == 0)
490                    .map(|(name, _)| name.clone())
491                    .collect();
492
493                for name in unused {
494                    models.remove(&name);
495                    counts.remove(&name);
496                }
497            }
498        }
499    }
500
501    impl<T: Clone> Clone for SharedModelStorage<T> {
502        fn clone(&self) -> Self {
503            Self {
504                models: Arc::clone(&self.models),
505                access_count: Arc::clone(&self.access_count),
506            }
507        }
508    }
509}
510
511/// Streaming algorithms for constant memory usage
512pub mod streaming_algorithms {
513
514    /// Streaming quantile estimation using P² algorithm
515    pub struct StreamingQuantileEstimator {
516        quantile: f64,
517        marker_positions: [f64; 5],
518        marker_heights: [f64; 5],
519        positions: [i32; 5],
520        increments: [f64; 5],
521        count: usize,
522    }
523
524    impl StreamingQuantileEstimator {
525        /// Create new streaming quantile estimator
526        pub fn new(quantile: f64) -> Self {
527            let p = quantile;
528            Self {
529                quantile,
530                marker_positions: [0.0, 0.0, 0.0, 0.0, 0.0],
531                marker_heights: [0.0, 0.0, 0.0, 0.0, 0.0],
532                positions: [1, 2, 3, 4, 5],
533                increments: [0.0, p / 2.0, p, (1.0 + p) / 2.0, 1.0],
534                count: 0,
535            }
536        }
537
538        /// Update with new value
539        pub fn update(&mut self, value: f64) {
540            self.count += 1;
541
542            if self.count <= 5 {
543                // Initialize first 5 values
544                self.marker_heights[self.count - 1] = value;
545                if self.count == 5 {
546                    self.marker_heights
547                        .sort_by(|a, b| a.partial_cmp(b).expect("operation should succeed"));
548                    for i in 0..5 {
549                        self.marker_positions[i] = i as f64 + 1.0;
550                    }
551                }
552                return;
553            }
554
555            // Find cell k; initial value is always overwritten by one of the branches below
556            #[allow(unused_assignments)]
557            let mut k = 0_usize;
558            if value < self.marker_heights[0] {
559                self.marker_heights[0] = value;
560                k = 1;
561            } else if value >= self.marker_heights[4] {
562                self.marker_heights[4] = value;
563                k = 4;
564            } else {
565                k = 4; // default if no element satisfies value < marker_heights[i]
566                for i in 1..4 {
567                    if value < self.marker_heights[i] {
568                        k = i;
569                        break;
570                    }
571                }
572            }
573
574            // Increment positions
575            for i in k..5 {
576                self.positions[i] += 1;
577            }
578
579            // Update desired positions
580            for i in 0..5 {
581                self.marker_positions[i] += self.increments[i];
582            }
583
584            // Adjust heights
585            for i in 1..4 {
586                let d = self.marker_positions[i] - self.positions[i] as f64;
587                if (d >= 1.0 && self.positions[i + 1] - self.positions[i] > 1)
588                    || (d <= -1.0 && self.positions[i - 1] - self.positions[i] < -1)
589                {
590                    let d_sign = d.signum() as i32;
591                    let new_height = self.parabolic_prediction(i, d_sign);
592
593                    if self.marker_heights[i - 1] < new_height
594                        && new_height < self.marker_heights[i + 1]
595                    {
596                        self.marker_heights[i] = new_height;
597                    } else {
598                        self.marker_heights[i] = self.linear_prediction(i, d_sign);
599                    }
600                    self.positions[i] += d_sign;
601                }
602            }
603        }
604
605        /// Get current quantile estimate
606        pub fn quantile(&self) -> f64 {
607            if self.count < 5 {
608                let mut sorted = self.marker_heights[..self.count].to_vec();
609                sorted.sort_by(|a, b| a.partial_cmp(b).expect("operation should succeed"));
610                let index = (self.quantile * (self.count - 1) as f64) as usize;
611                sorted[index]
612            } else {
613                self.marker_heights[2]
614            }
615        }
616
617        fn parabolic_prediction(&self, i: usize, d: i32) -> f64 {
618            let qi = self.marker_heights[i];
619            let qi_1 = self.marker_heights[i - 1];
620            let qi1 = self.marker_heights[i + 1];
621            let ni = self.positions[i] as f64;
622            let ni_1 = self.positions[i - 1] as f64;
623            let ni1 = self.positions[i + 1] as f64;
624
625            qi + (d as f64 / (ni1 - ni_1))
626                * ((ni - ni_1 + d as f64) * (qi1 - qi) / (ni1 - ni)
627                    + (ni1 - ni - d as f64) * (qi - qi_1) / (ni - ni_1))
628        }
629
630        fn linear_prediction(&self, i: usize, d: i32) -> f64 {
631            let qi = self.marker_heights[i];
632            let ni = self.positions[i] as f64;
633
634            if d == 1 {
635                let qi1 = self.marker_heights[i + 1];
636                let ni1 = self.positions[i + 1] as f64;
637                qi + (qi1 - qi) / (ni1 - ni)
638            } else {
639                let qi_1 = self.marker_heights[i - 1];
640                let ni_1 = self.positions[i - 1] as f64;
641                qi - (qi_1 - qi) / (ni - ni_1)
642            }
643        }
644    }
645
646    /// Streaming histogram with adaptive binning
647    pub struct StreamingHistogram {
648        bins: Vec<(f64, f64, usize)>, // (min, max, count)
649        max_bins: usize,
650        total_count: usize,
651    }
652
653    impl StreamingHistogram {
654        /// Create new streaming histogram
655        pub fn new(max_bins: usize) -> Self {
656            Self {
657                bins: Vec::new(),
658                max_bins,
659                total_count: 0,
660            }
661        }
662
663        /// Update histogram with new value
664        pub fn update(&mut self, value: f64) {
665            self.total_count += 1;
666
667            // Find appropriate bin
668            let mut bin_index = None;
669            for (i, (min, max, _)) in self.bins.iter().enumerate() {
670                if value >= *min && value <= *max {
671                    bin_index = Some(i);
672                    break;
673                }
674            }
675
676            if let Some(i) = bin_index {
677                // Update existing bin
678                self.bins[i].2 += 1;
679            } else {
680                // Create new bin
681                self.bins.push((value, value, 1));
682
683                // Merge bins if we exceed maximum
684                if self.bins.len() > self.max_bins {
685                    self.merge_closest_bins();
686                }
687            }
688        }
689
690        /// Get histogram bins
691        pub fn bins(&self) -> &[(f64, f64, usize)] {
692            &self.bins
693        }
694
695        /// Get total count
696        pub fn total_count(&self) -> usize {
697            self.total_count
698        }
699
700        /// Estimate quantile from histogram
701        pub fn quantile(&self, q: f64) -> f64 {
702            let target_count = (q * self.total_count as f64) as usize;
703            let mut cumulative = 0;
704
705            for (min, max, count) in &self.bins {
706                cumulative += count;
707                if cumulative >= target_count {
708                    // Linear interpolation within bin
709                    let bin_progress = (target_count - (cumulative - count)) as f64 / *count as f64;
710                    return min + bin_progress * (max - min);
711                }
712            }
713
714            // Return maximum value if not found
715            self.bins.last().map(|(_, max, _)| *max).unwrap_or(0.0)
716        }
717
718        fn merge_closest_bins(&mut self) {
719            if self.bins.len() < 2 {
720                return;
721            }
722
723            // Find two closest bins to merge
724            let mut min_distance = f64::INFINITY;
725            let mut merge_index = 0;
726
727            for i in 0..self.bins.len() - 1 {
728                let distance = self.bins[i + 1].0 - self.bins[i].1; // Gap between bins
729                if distance < min_distance {
730                    min_distance = distance;
731                    merge_index = i;
732                }
733            }
734
735            // Merge bins
736            let bin1 = self.bins[merge_index];
737            let bin2 = self.bins[merge_index + 1];
738            let merged_bin = (
739                bin1.0.min(bin2.0), // min
740                bin1.1.max(bin2.1), // max
741                bin1.2 + bin2.2,    // count
742            );
743
744            self.bins[merge_index] = merged_bin;
745            self.bins.remove(merge_index + 1);
746        }
747    }
748
749    /// Streaming correlation coefficient estimation
750    pub struct StreamingCorrelation {
751        count: usize,
752        sum_x: f64,
753        sum_y: f64,
754        sum_xx: f64,
755        sum_yy: f64,
756        sum_xy: f64,
757    }
758
759    impl Default for StreamingCorrelation {
760        fn default() -> Self {
761            Self::new()
762        }
763    }
764
765    impl StreamingCorrelation {
766        /// Create new streaming correlation estimator
767        pub fn new() -> Self {
768            Self {
769                count: 0,
770                sum_x: 0.0,
771                sum_y: 0.0,
772                sum_xx: 0.0,
773                sum_yy: 0.0,
774                sum_xy: 0.0,
775            }
776        }
777
778        /// Update with new (x, y) pair
779        pub fn update(&mut self, x: f64, y: f64) {
780            self.count += 1;
781            self.sum_x += x;
782            self.sum_y += y;
783            self.sum_xx += x * x;
784            self.sum_yy += y * y;
785            self.sum_xy += x * y;
786        }
787
788        /// Get current correlation coefficient
789        pub fn correlation(&self) -> f64 {
790            if self.count < 2 {
791                return 0.0;
792            }
793
794            let n = self.count as f64;
795            let numerator = n * self.sum_xy - self.sum_x * self.sum_y;
796            let denominator = ((n * self.sum_xx - self.sum_x * self.sum_x)
797                * (n * self.sum_yy - self.sum_y * self.sum_y))
798                .sqrt();
799
800            if denominator == 0.0 {
801                0.0
802            } else {
803                numerator / denominator
804            }
805        }
806
807        /// Get sample count
808        pub fn count(&self) -> usize {
809            self.count
810        }
811    }
812}
813
814#[allow(non_snake_case)]
815#[cfg(test)]
816mod tests {
817    use super::*;
818
819    #[test]
820    fn test_size_class_memory_pool() {
821        let mut pool = advanced_pooling::SizeClassMemoryPool::<i32>::new(10);
822
823        // Test getting and returning vectors
824        let vec1 = pool.get(100);
825        assert!(vec1.capacity() >= 100);
826
827        let vec2 = pool.get(50);
828        assert!(vec2.capacity() >= 50);
829
830        pool.return_vec(vec1);
831        pool.return_vec(vec2);
832
833        // Test pool reuse
834        let _vec3 = pool.get(100);
835        let stats = pool.statistics();
836        assert!(stats.pool_hits > 0);
837
838        // Test efficiency
839        let efficiency = pool.efficiency();
840        assert!(efficiency > 0.0);
841    }
842
843    #[test]
844    fn test_thread_safe_memory_pool() {
845        let pool = advanced_pooling::ThreadSafeMemoryPool::<f64>::new(5);
846
847        let vec1 = pool.get(50);
848        assert!(vec1.capacity() >= 50);
849
850        pool.return_vec(vec1);
851
852        let vec2 = pool.get(40);
853        assert!(vec2.capacity() >= 40);
854
855        let efficiency = pool.efficiency();
856        assert!(efficiency >= 0.0);
857    }
858
859    #[test]
860    fn test_memory_mapped_storage() {
861        let mut storage =
862            advanced_pooling::MemoryMappedStorage::new(std::mem::size_of::<f64>(), 10);
863
864        // Store some values
865        let idx1 = storage.push(&1.23f64).expect("operation should succeed");
866        let idx2 = storage.push(&4.56f64).expect("operation should succeed");
867
868        assert_eq!(storage.len(), 2);
869        assert_eq!(storage.get::<f64>(idx1), Some(1.23));
870        assert_eq!(storage.get::<f64>(idx2), Some(4.56));
871
872        let memory_usage = storage.memory_usage();
873        assert!(memory_usage > 0);
874    }
875
876    #[test]
877    fn test_shared_prediction_cache() {
878        let cache = reference_counting::SharedPredictionCache::new();
879
880        // Test cache operations
881        cache.insert(42, 1.23);
882        assert_eq!(cache.get(42), Some(1.23));
883        assert_eq!(cache.get(99), None);
884
885        let stats = cache.stats();
886        assert_eq!(stats.hits, 1);
887        assert_eq!(stats.misses, 1);
888
889        let hit_rate = cache.hit_rate();
890        assert_eq!(hit_rate, 0.5);
891
892        // Test cloning
893        let cache2 = cache.clone();
894        assert_eq!(cache2.get(42), Some(1.23));
895    }
896
897    #[test]
898    fn test_shared_model_storage() {
899        let storage = reference_counting::SharedModelStorage::<String>::new();
900
901        storage.store("model1".to_string(), "data1".to_string());
902        storage.store("model2".to_string(), "data2".to_string());
903
904        assert_eq!(storage.get("model1"), Some("data1".to_string()));
905        assert_eq!(storage.get("model1"), Some("data1".to_string())); // Second access
906        assert_eq!(storage.get("model2"), Some("data2".to_string()));
907
908        assert_eq!(storage.access_count("model1"), 2);
909        assert_eq!(storage.access_count("model2"), 1);
910
911        let most_accessed = storage.most_accessed(1);
912        assert_eq!(most_accessed[0].0, "model1");
913        assert_eq!(most_accessed[0].1, 2);
914    }
915
916    #[test]
917    fn test_streaming_quantile_estimator() {
918        let mut estimator = streaming_algorithms::StreamingQuantileEstimator::new(0.5); // Median
919
920        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
921        for value in data {
922            estimator.update(value);
923        }
924
925        let median = estimator.quantile();
926        assert!((median - 5.5).abs() < 1.0); // Should be approximately 5.5
927    }
928
929    #[test]
930    fn test_streaming_histogram() {
931        let mut histogram = streaming_algorithms::StreamingHistogram::new(5);
932
933        for i in 1..=100 {
934            histogram.update(i as f64);
935        }
936
937        assert_eq!(histogram.total_count(), 100);
938
939        let median = histogram.quantile(0.5);
940        assert!((median - 50.0).abs() < 10.0); // Should be approximately 50
941
942        let bins = histogram.bins();
943        assert!(bins.len() <= 5);
944    }
945
946    #[test]
947    fn test_streaming_correlation() {
948        let mut corr = streaming_algorithms::StreamingCorrelation::new();
949
950        // Perfect positive correlation
951        for i in 1..=10 {
952            corr.update(i as f64, (i * 2) as f64);
953        }
954
955        let correlation = corr.correlation();
956        assert!((correlation - 1.0).abs() < 1e-10);
957        assert_eq!(corr.count(), 10);
958    }
959}