ppflib 0.1.0

Advanced computational library for Physics-Prime Factorization (PPF): quantum mechanics through number theory, featuring Sign Prime (-1), state space collapse, topological analysis, and IOT geometric realizations
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
//! P-prime generation and caching
//!
//! This module provides efficient generation of P-prime sequences, including both
//! the Sign Prime (-1) and Magnitude Primes (positive primes), with caching
//! for performance optimization.

use crate::core::sign_prime::{is_sign_prime, SIGN_PRIME};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use thiserror::Error;

/// Errors that can occur during P-prime operations
#[derive(Error, Debug, Clone, PartialEq)]
pub enum PPrimeError {
    /// The provided number is not a valid P-prime
    #[error("Invalid prime: {0}")]
    InvalidPrime(i64),
    /// An error occurred in the prime cache
    #[error("Cache error: {0}")]
    CacheError(String),
    /// Number is too large for efficient computation
    #[error("Number too large for efficient computation")]
    NumberTooLarge,
}

/// Types of P-primes in the PPF framework
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PPrimeType {
    /// The Sign Prime (-1)
    SignPrime,
    /// Positive magnitude primes (2, 3, 5, 7, ...)
    MagnitudePrime,
}

/// Represents a P-prime (Physics Prime) in the PPF framework
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PPrime {
    value: i64,
    prime_type: PPrimeType,
}

impl PPrime {
    /// Create a new P-prime
    /// 
    /// # Arguments
    /// * `value` - The prime value
    /// 
    /// # Returns
    /// * `Ok(PPrime)` if value is a valid P-prime
    /// * `Err(PPrimeError)` if value is not a P-prime
    /// 
    /// # Examples
    /// ```
    /// use ppflib::core::PPrime;
    /// 
    /// let sign_prime = PPrime::new(-1).unwrap();
    /// let magnitude_prime = PPrime::new(7).unwrap();
    /// assert!(PPrime::new(4).is_err()); // 4 is not prime
    /// ```
    pub fn new(value: i64) -> Result<Self, PPrimeError> {
        if is_sign_prime(value) {
            Ok(PPrime {
                value,
                prime_type: PPrimeType::SignPrime,
            })
        } else if value > 1 && is_magnitude_prime(value) {
            Ok(PPrime {
                value,
                prime_type: PPrimeType::MagnitudePrime,
            })
        } else {
            Err(PPrimeError::InvalidPrime(value))
        }
    }

    /// Get the value of this P-prime
    pub fn value(&self) -> i64 {
        self.value
    }

    /// Get the type of this P-prime
    pub fn prime_type(&self) -> PPrimeType {
        self.prime_type
    }

    /// Check if this is the Sign Prime
    pub fn is_sign_prime(&self) -> bool {
        self.prime_type == PPrimeType::SignPrime
    }

    /// Check if this is a Magnitude Prime
    pub fn is_magnitude_prime(&self) -> bool {
        self.prime_type == PPrimeType::MagnitudePrime
    }

    /// Create the Sign Prime
    pub fn sign_prime() -> Self {
        PPrime {
            value: SIGN_PRIME,
            prime_type: PPrimeType::SignPrime,
        }
    }

    /// Apply this P-prime to an integer (multiplication)
    pub fn apply_to(&self, n: i64) -> i64 {
        if self.is_sign_prime() {
            -n
        } else {
            self.value * n
        }
    }
}

/// Cache for storing computed primes
#[derive(Debug)]
pub struct PrimeCache {
    magnitude_primes: Arc<Mutex<Vec<i64>>>,
    primality_cache: Arc<Mutex<HashMap<i64, bool>>>,
    max_computed: Arc<Mutex<i64>>,
}

impl PrimeCache {
    /// Create a new prime cache
    pub fn new() -> Self {
        let initial_primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47];
        let mut cache = HashMap::new();
        
        // Pre-populate cache with small primes
        for &p in &initial_primes {
            cache.insert(p, true);
        }
        
        // Mark some composites
        for i in 4..=50 {
            if !initial_primes.contains(&i) {
                cache.insert(i, false);
            }
        }

        PrimeCache {
            magnitude_primes: Arc::new(Mutex::new(initial_primes)),
            primality_cache: Arc::new(Mutex::new(cache)),
            max_computed: Arc::new(Mutex::new(47)),
        }
    }

    /// Check if a number is a magnitude prime (uses cache)
    pub fn is_magnitude_prime(&self, n: i64) -> bool {
        if n <= 1 {
            return false;
        }

        // Check cache first
        {
            let cache = self.primality_cache.lock().unwrap();
            if let Some(&is_prime) = cache.get(&n) {
                return is_prime;
            }
        }

        // Compute if not in cache
        let is_prime = self.compute_primality(n);
        
        // Update cache
        {
            let mut cache = self.primality_cache.lock().unwrap();
            cache.insert(n, is_prime);
        }

        is_prime
    }

    /// Compute primality using trial division
    fn compute_primality(&self, n: i64) -> bool {
        if n <= 1 {
            return false;
        }
        if n <= 3 {
            return true;
        }
        if n % 2 == 0 || n % 3 == 0 {
            return false;
        }

        let sqrt_n = (n as f64).sqrt() as i64;
        let mut i = 5;
        while i <= sqrt_n {
            if n % i == 0 || n % (i + 2) == 0 {
                return false;
            }
            i += 6;
        }
        true
    }

    /// Get magnitude primes up to a limit
    pub fn magnitude_primes_up_to(&self, limit: i64) -> Vec<i64> {
        let mut primes = self.magnitude_primes.lock().unwrap();
        let max_computed = *self.max_computed.lock().unwrap();

        // Extend cache if needed
        if limit > max_computed {
            self.extend_prime_cache(limit, &mut primes);
        }

        primes.iter().filter(|&&p| p <= limit).copied().collect()
    }

    /// Extend the prime cache to include primes up to the limit
    fn extend_prime_cache(&self, limit: i64, primes: &mut Vec<i64>) {
        let start = primes.last().copied().unwrap_or(2) + 1;
        
        for candidate in start..=limit {
            if self.compute_primality(candidate) {
                primes.push(candidate);
            }
        }

        *self.max_computed.lock().unwrap() = limit;
    }

    /// Get the nth magnitude prime (0-indexed)
    pub fn nth_magnitude_prime(&self, n: usize) -> Option<i64> {
        // Ensure we have enough primes computed
        let mut primes = self.magnitude_primes.lock().unwrap();
        
        while primes.len() <= n {
            let next_candidate = primes.last().copied().unwrap_or(2) + 1;
            let mut candidate = next_candidate;
            
            // Find next prime
            while !self.compute_primality(candidate) {
                candidate += 1;
            }
            primes.push(candidate);
        }

        primes.get(n).copied()
    }
}

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

/// Global prime cache instance
static GLOBAL_CACHE: std::sync::OnceLock<PrimeCache> = std::sync::OnceLock::new();

/// Get the global prime cache
pub fn global_cache() -> &'static PrimeCache {
    GLOBAL_CACHE.get_or_init(PrimeCache::new)
}

/// Check if a number is a magnitude prime (using global cache)
pub fn is_magnitude_prime(n: i64) -> bool {
    global_cache().is_magnitude_prime(n)
}

/// Check if a number is any type of P-prime
/// 
/// # Arguments
/// * `n` - Number to check
/// 
/// # Returns
/// * `true` if n is either the Sign Prime (-1) or a Magnitude Prime
/// 
/// # Examples
/// ```
/// use ppflib::core::is_p_prime;
/// 
/// assert!(is_p_prime(-1));  // Sign Prime
/// assert!(is_p_prime(2));   // Magnitude Prime
/// assert!(is_p_prime(17));  // Magnitude Prime
/// assert!(!is_p_prime(4));  // Not prime
/// assert!(!is_p_prime(-2)); // Not a P-prime
/// ```
pub fn is_p_prime(n: i64) -> bool {
    is_sign_prime(n) || (n > 1 && is_magnitude_prime(n))
}

/// Iterator over P-primes
pub struct PPrimeIterator {
    cache: &'static PrimeCache,
    magnitude_index: usize,
    include_sign_prime: bool,
    returned_sign_prime: bool,
}

impl PPrimeIterator {
    /// Create a new P-prime iterator
    /// 
    /// # Arguments
    /// * `include_sign_prime` - Whether to include the Sign Prime (-1) in iteration
    /// 
    /// # Examples
    /// ```
    /// use ppflib::core::PPrimeIterator;
    /// 
    /// let mut iter = PPrimeIterator::new(true);
    /// assert_eq!(iter.next().unwrap().value(), -1); // Sign Prime first
    /// assert_eq!(iter.next().unwrap().value(), 2);  // Then magnitude primes
    /// ```
    pub fn new(include_sign_prime: bool) -> Self {
        PPrimeIterator {
            cache: global_cache(),
            magnitude_index: 0,
            include_sign_prime,
            returned_sign_prime: false,
        }
    }

    /// Create iterator for magnitude primes only
    pub fn magnitude_primes() -> Self {
        Self::new(false)
    }

    /// Create iterator for all P-primes (including Sign Prime)
    pub fn all_p_primes() -> Self {
        Self::new(true)
    }
}

impl Iterator for PPrimeIterator {
    type Item = PPrime;

    fn next(&mut self) -> Option<Self::Item> {
        // Return Sign Prime first if requested and not yet returned
        if self.include_sign_prime && !self.returned_sign_prime {
            self.returned_sign_prime = true;
            return Some(PPrime::sign_prime());
        }

        // Return next magnitude prime
        if let Some(prime_value) = self.cache.nth_magnitude_prime(self.magnitude_index) {
            self.magnitude_index += 1;
            Some(PPrime {
                value: prime_value,
                prime_type: PPrimeType::MagnitudePrime,
            })
        } else {
            None
        }
    }
}

/// Get P-primes up to a given limit
/// 
/// # Arguments
/// * `limit` - Upper bound (inclusive)
/// * `include_sign_prime` - Whether to include the Sign Prime (-1)
/// 
/// # Returns
/// * Vector of P-primes up to the limit
/// 
/// # Examples
/// ```
/// use ppflib::core::p_primes_up_to;
/// 
/// let primes = p_primes_up_to(10, true);
/// // Returns [-1, 2, 3, 5, 7] (Sign Prime + magnitude primes ≤ 10)
/// ```
pub fn p_primes_up_to(limit: i64, include_sign_prime: bool) -> Vec<PPrime> {
    let mut result = Vec::new();
    
    if include_sign_prime && limit >= -1 {
        result.push(PPrime::sign_prime());
    }
    
    let magnitude_primes = global_cache().magnitude_primes_up_to(limit);
    for prime in magnitude_primes {
        result.push(PPrime {
            value: prime,
            prime_type: PPrimeType::MagnitudePrime,
        });
    }
    
    result
}

/// Get the first n P-primes
/// 
/// # Arguments
/// * `n` - Number of P-primes to return
/// * `include_sign_prime` - Whether to include the Sign Prime (-1)
/// 
/// # Returns
/// * Vector of the first n P-primes
pub fn first_n_p_primes(n: usize, include_sign_prime: bool) -> Vec<PPrime> {
    PPrimeIterator::new(include_sign_prime).take(n).collect()
}

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

    #[test]
    fn test_pprime_creation() {
        let sign_prime = PPrime::new(-1).unwrap();
        assert!(sign_prime.is_sign_prime());
        assert_eq!(sign_prime.value(), -1);

        let magnitude_prime = PPrime::new(7).unwrap();
        assert!(magnitude_prime.is_magnitude_prime());
        assert_eq!(magnitude_prime.value(), 7);

        assert!(PPrime::new(4).is_err()); // 4 is not prime
        assert!(PPrime::new(-2).is_err()); // -2 is not a P-prime
    }

    #[test]
    fn test_is_p_prime() {
        assert!(is_p_prime(-1));  // Sign Prime
        assert!(is_p_prime(2));   // Magnitude Prime
        assert!(is_p_prime(17));  // Magnitude Prime
        assert!(!is_p_prime(4));  // Not prime
        assert!(!is_p_prime(-2)); // Not a P-prime
        assert!(!is_p_prime(0));  // Not prime
        assert!(!is_p_prime(1));  // Not prime
    }

    #[test]
    fn test_magnitude_prime_detection() {
        assert!(is_magnitude_prime(2));
        assert!(is_magnitude_prime(3));
        assert!(is_magnitude_prime(5));
        assert!(is_magnitude_prime(7));
        assert!(is_magnitude_prime(11));
        assert!(is_magnitude_prime(97));
        
        assert!(!is_magnitude_prime(1));
        assert!(!is_magnitude_prime(4));
        assert!(!is_magnitude_prime(6));
        assert!(!is_magnitude_prime(8));
        assert!(!is_magnitude_prime(9));
        assert!(!is_magnitude_prime(100));
    }

    #[test]
    fn test_prime_cache() {
        let cache = PrimeCache::new();
        
        assert!(cache.is_magnitude_prime(97));
        assert!(!cache.is_magnitude_prime(98));
        
        let primes = cache.magnitude_primes_up_to(20);
        assert_eq!(primes, vec![2, 3, 5, 7, 11, 13, 17, 19]);
        
        assert_eq!(cache.nth_magnitude_prime(0), Some(2));
        assert_eq!(cache.nth_magnitude_prime(1), Some(3));
        assert_eq!(cache.nth_magnitude_prime(4), Some(11));
    }

    #[test]
    fn test_pprime_iterator() {
        let primes: Vec<i64> = PPrimeIterator::magnitude_primes()
            .take(5)
            .map(|p| p.value())
            .collect();
        assert_eq!(primes, vec![2, 3, 5, 7, 11]);

        let all_primes: Vec<i64> = PPrimeIterator::all_p_primes()
            .take(6)
            .map(|p| p.value())
            .collect();
        assert_eq!(all_primes, vec![-1, 2, 3, 5, 7, 11]);
    }

    #[test]
    fn test_p_primes_up_to() {
        let primes = p_primes_up_to(10, false);
        let values: Vec<i64> = primes.iter().map(|p| p.value()).collect();
        assert_eq!(values, vec![2, 3, 5, 7]);

        let primes_with_sign = p_primes_up_to(10, true);
        let values_with_sign: Vec<i64> = primes_with_sign.iter().map(|p| p.value()).collect();
        assert_eq!(values_with_sign, vec![-1, 2, 3, 5, 7]);
    }

    #[test]
    fn test_pprime_application() {
        let sign_prime = PPrime::sign_prime();
        assert_eq!(sign_prime.apply_to(5), -5);
        assert_eq!(sign_prime.apply_to(-3), 3);

        let magnitude_prime = PPrime::new(7).unwrap();
        assert_eq!(magnitude_prime.apply_to(3), 21);
        assert_eq!(magnitude_prime.apply_to(-2), -14);
    }

    #[test]
    fn test_first_n_p_primes() {
        let primes = first_n_p_primes(4, false);
        let values: Vec<i64> = primes.iter().map(|p| p.value()).collect();
        assert_eq!(values, vec![2, 3, 5, 7]);

        let primes_with_sign = first_n_p_primes(4, true);
        let values_with_sign: Vec<i64> = primes_with_sign.iter().map(|p| p.value()).collect();
        assert_eq!(values_with_sign, vec![-1, 2, 3, 5]);
    }
}