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
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! State space operations and quantum collapse modeling
//!
//! This module implements state space operations IS(a)·IS(b) = IS(c),
//! superposition handling for negative integers, and collapse operations
//! that model quantum mechanical phenomena.

use crate::core::{FactorizationStateSpace, FactorizationError};
use std::fmt;
use thiserror::Error;
use serde::{Deserialize, Serialize};

/// Errors that can occur during state space operations
#[derive(Error, Debug, Clone, PartialEq)]
pub enum StateSpaceError {
    /// An error occurred during factorization
    #[error("Factorization error: {0}")]
    FactorizationError(#[from] FactorizationError),
    /// An invalid state space operation was attempted
    #[error("Invalid state space operation: {0}")]
    InvalidOperation(String),
    /// The provided state spaces are incompatible
    #[error("Incompatible state spaces")]
    IncompatibleSpaces,
    /// The operation result is too large
    #[error("Operation result too large")]
    ResultTooLarge,
}

/// Represents the result of a state space multiplication
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StateSpaceMultiplicationResult {
    /// The resulting state space IS(c) = IS(a) · IS(b)
    pub result_space: FactorizationStateSpace,
    /// Information about the collapse (if any)
    pub collapse_info: CollapseInfo,
}

/// Information about quantum collapse during state space operations
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CollapseInfo {
    /// Whether a collapse occurred (unobserved → observed)
    pub collapsed: bool,
    /// Size of input state spaces
    pub input_sizes: (usize, usize),
    /// Size of output state space
    pub output_size: usize,
    /// Collapse ratio (output_size / max(input_sizes))
    pub collapse_ratio: f64,
    /// Type of operation
    pub operation_type: OperationType,
}

/// Types of state space operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum OperationType {
    /// Both operands positive (Classical × Classical = Classical)
    ClassicalClassical,
    /// One positive, one negative (Classical × Quantum = Quantum)
    ClassicalQuantum,
    /// Both negative (Quantum × Quantum = Classical) - COLLAPSE
    QuantumQuantum,
    /// Other combinations
    Other,
}

/// State space operations implementation
pub struct StateSpaceOperations;

impl StateSpaceOperations {
    /// Multiply two state spaces: IS(a) · IS(b) = IS(c)
    /// 
    /// This is the fundamental operation in PPF that models quantum collapse.
    /// When two "unobserved" states (negative integers) interact, they produce
    /// an "observed" state (positive integer) with reduced state space.
    /// 
    /// # Arguments
    /// * `space_a` - First state space IS(a)
    /// * `space_b` - Second state space IS(b)
    /// 
    /// # Returns
    /// * `Ok(StateSpaceMultiplicationResult)` containing IS(a·b) and collapse info
    /// * `Err(StateSpaceError)` if operation fails
    /// 
    /// # Examples
    /// ```
    /// use ppflib::core::{FactorizationStateSpace, StateSpaceOperations};
    /// 
    /// let s_neg2 = FactorizationStateSpace::new(-2).unwrap();
    /// let s_neg3 = FactorizationStateSpace::new(-3).unwrap();
    /// 
    /// let result = StateSpaceOperations::multiply(&s_neg2, &s_neg3).unwrap();
    /// assert_eq!(result.result_space.value(), 6); // (-2) × (-3) = 6
    /// assert!(result.collapse_info.collapsed); // Quantum collapse occurred
    /// ```
    pub fn multiply(
        space_a: &FactorizationStateSpace,
        space_b: &FactorizationStateSpace,
    ) -> Result<StateSpaceMultiplicationResult, StateSpaceError> {
        let a = space_a.value();
        let b = space_b.value();
        let c = a.checked_mul(b)
            .ok_or(StateSpaceError::ResultTooLarge)?;

        // Determine operation type
        let operation_type = Self::classify_operation(a, b);
        
        // Create result state space
        let result_space = FactorizationStateSpace::new(c)?;
        
        // Analyze collapse
        let input_sizes = (space_a.size(), space_b.size());
        let output_size = result_space.size();
        let max_input_size = input_sizes.0.max(input_sizes.1);
        
        let collapsed = matches!(operation_type, OperationType::QuantumQuantum);
        let collapse_ratio = if max_input_size > 0 {
            output_size as f64 / max_input_size as f64
        } else {
            1.0
        };

        let collapse_info = CollapseInfo {
            collapsed,
            input_sizes,
            output_size,
            collapse_ratio,
            operation_type,
        };

        Ok(StateSpaceMultiplicationResult {
            result_space,
            collapse_info,
        })
    }

    /// Classify the type of operation based on operand signs
    fn classify_operation(a: i64, b: i64) -> OperationType {
        match (a > 0, b > 0) {
            (true, true) => OperationType::ClassicalClassical,
            (true, false) | (false, true) => OperationType::ClassicalQuantum,
            (false, false) => OperationType::QuantumQuantum,
        }
    }

    /// Compute the power of a state space: IS(a)^n = IS(a^n)
    /// 
    /// # Arguments
    /// * `space` - The state space to raise to a power
    /// * `exponent` - The exponent (must be positive)
    /// 
    /// # Returns
    /// * `Ok(StateSpaceMultiplicationResult)` containing IS(a^n)
    /// * `Err(StateSpaceError)` if operation fails
    pub fn power(
        space: &FactorizationStateSpace,
        exponent: u32,
    ) -> Result<StateSpaceMultiplicationResult, StateSpaceError> {
        if exponent == 0 {
            // a^0 = 1 for any non-zero a
            let unity_space = FactorizationStateSpace::new(1)?;
            return Ok(StateSpaceMultiplicationResult {
                result_space: unity_space,
                collapse_info: CollapseInfo {
                    collapsed: false,
                    input_sizes: (space.size(), 1),
                    output_size: 1,
                    collapse_ratio: 1.0,
                    operation_type: OperationType::Other,
                },
            });
        }

        if exponent == 1 {
            return Ok(StateSpaceMultiplicationResult {
                result_space: space.clone(),
                collapse_info: CollapseInfo {
                    collapsed: false,
                    input_sizes: (space.size(), space.size()),
                    output_size: space.size(),
                    collapse_ratio: 1.0,
                    operation_type: OperationType::Other,
                },
            });
        }

        let a = space.value();
        let result = a.checked_pow(exponent)
            .ok_or(StateSpaceError::ResultTooLarge)?;

        let result_space = FactorizationStateSpace::new(result)?;
        
        // For even powers of negative numbers, we get collapse to positive
        let collapsed = a < 0 && exponent % 2 == 0;
        let input_sizes = (space.size(), space.size());
        let output_size = result_space.size();
        let collapse_ratio = if space.size() > 0 {
            output_size as f64 / space.size() as f64
        } else {
            1.0
        };

        let collapse_info = CollapseInfo {
            collapsed,
            input_sizes,
            output_size,
            collapse_ratio,
            operation_type: OperationType::Other,
        };

        Ok(StateSpaceMultiplicationResult {
            result_space,
            collapse_info,
        })
    }

    /// Apply a sign flip to a state space (multiply by Sign Prime)
    /// 
    /// This operation changes IS(a) to IS(-a), modeling the application
    /// of the Sign Prime to change the quantum state.
    /// 
    /// # Arguments
    /// * `space` - The state space to flip
    /// 
    /// # Returns
    /// * `Ok(FactorizationStateSpace)` containing IS(-a)
    /// * `Err(StateSpaceError)` if operation fails
    pub fn sign_flip(
        space: &FactorizationStateSpace,
    ) -> Result<FactorizationStateSpace, StateSpaceError> {
        let flipped_value = -space.value();
        Ok(FactorizationStateSpace::new(flipped_value)?)
    }

    /// Check if two state spaces can be combined
    /// 
    /// This validates that the state spaces are compatible for operations
    /// and that the resulting integer won't overflow.
    pub fn can_multiply(
        space_a: &FactorizationStateSpace,
        space_b: &FactorizationStateSpace,
    ) -> bool {
        space_a.value().checked_mul(space_b.value()).is_some()
    }

    /// Analyze the superposition characteristics of a state space
    /// 
    /// # Arguments
    /// * `space` - The state space to analyze
    /// 
    /// # Returns
    /// * `SuperpositionAnalysis` containing quantum vs classical characteristics
    pub fn analyze_superposition(space: &FactorizationStateSpace) -> SuperpositionAnalysis {
        let value = space.value();
        let size = space.size();
        
        let is_quantum = value < 0;
        let is_classical = value > 0;
        
        // Compute superposition measure (larger state space = more quantum-like)
        let theoretical_max_size = if value.abs() == 1 {
            1
        } else {
            // Rough estimate of maximum possible state space size
            let abs_val = value.abs();
            let log_estimate = (abs_val as f64).log2().ceil() as usize;
            1 << log_estimate.min(10) // Cap at 2^10 to avoid overflow
        };
        
        let superposition_measure = size as f64 / theoretical_max_size as f64;
        
        // Count factorizations with sign prime
        let sign_prime_factorizations = space.factorizations().iter()
            .filter(|f| f.has_sign_prime())
            .count();
        
        SuperpositionAnalysis {
            is_quantum,
            is_classical,
            state_space_size: size,
            superposition_measure,
            sign_prime_factorizations,
            complexity_distribution: Self::compute_complexity_distribution(space),
        }
    }

    /// Compute the distribution of complexity measures across factorizations
    fn compute_complexity_distribution(space: &FactorizationStateSpace) -> Vec<u32> {
        space.factorizations().iter()
            .map(|f| f.complexity())
            .collect()
    }
}

/// Analysis of superposition characteristics
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SuperpositionAnalysis {
    /// Whether this represents a quantum state (negative integer)
    pub is_quantum: bool,
    /// Whether this represents a classical state (positive integer)
    pub is_classical: bool,
    /// Size of the state space
    pub state_space_size: usize,
    /// Measure of superposition (0.0 = fully collapsed, 1.0 = maximum superposition)
    pub superposition_measure: f64,
    /// Number of factorizations involving the Sign Prime
    pub sign_prime_factorizations: usize,
    /// Distribution of complexity measures across factorizations
    pub complexity_distribution: Vec<u32>,
}

impl SuperpositionAnalysis {
    /// Get the average complexity of factorizations in this state space
    pub fn average_complexity(&self) -> f64 {
        if self.complexity_distribution.is_empty() {
            0.0
        } else {
            let sum: u32 = self.complexity_distribution.iter().sum();
            sum as f64 / self.complexity_distribution.len() as f64
        }
    }

    /// Get the entropy measure of the state space
    /// Higher entropy indicates more quantum-like behavior
    pub fn entropy(&self) -> f64 {
        if self.state_space_size <= 1 {
            0.0
        } else {
            (self.state_space_size as f64).log2()
        }
    }
}

impl fmt::Display for SuperpositionAnalysis {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Superposition Analysis:")?;
        writeln!(f, "  Type: {}", if self.is_quantum { "Quantum" } else { "Classical" })?;
        writeln!(f, "  State space size: {}", self.state_space_size)?;
        writeln!(f, "  Superposition measure: {:.3}", self.superposition_measure)?;
        writeln!(f, "  Sign prime factorizations: {}", self.sign_prime_factorizations)?;
        writeln!(f, "  Average complexity: {:.2}", self.average_complexity())?;
        writeln!(f, "  Entropy: {:.3}", self.entropy())?;
        Ok(())
    }
}

impl fmt::Display for CollapseInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Collapse Information:")?;
        writeln!(f, "  Operation type: {:?}", self.operation_type)?;
        writeln!(f, "  Collapsed: {}", self.collapsed)?;
        writeln!(f, "  Input sizes: {:?}", self.input_sizes)?;
        writeln!(f, "  Output size: {}", self.output_size)?;
        writeln!(f, "  Collapse ratio: {:.3}", self.collapse_ratio)?;
        Ok(())
    }
}

/// Convenience functions for common operations
impl FactorizationStateSpace {
    /// Multiply this state space with another
    pub fn multiply(&self, other: &FactorizationStateSpace) -> Result<StateSpaceMultiplicationResult, StateSpaceError> {
        StateSpaceOperations::multiply(self, other)
    }

    /// Raise this state space to a power
    pub fn power(&self, exponent: u32) -> Result<StateSpaceMultiplicationResult, StateSpaceError> {
        StateSpaceOperations::power(self, exponent)
    }

    /// Apply sign flip to this state space
    pub fn sign_flip(&self) -> Result<FactorizationStateSpace, StateSpaceError> {
        StateSpaceOperations::sign_flip(self)
    }

    /// Analyze superposition characteristics
    pub fn analyze_superposition(&self) -> SuperpositionAnalysis {
        StateSpaceOperations::analyze_superposition(self)
    }

    /// Check if this is a quantum state (negative integer)
    pub fn is_quantum(&self) -> bool {
        self.value() < 0
    }

    /// Check if this is a classical state (positive integer)
    pub fn is_classical(&self) -> bool {
        self.value() > 0
    }
}

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

    #[test]
    fn test_classical_classical_multiplication() {
        let s2 = FactorizationStateSpace::new(2).unwrap();
        let s3 = FactorizationStateSpace::new(3).unwrap();
        
        let result = StateSpaceOperations::multiply(&s2, &s3).unwrap();
        
        assert_eq!(result.result_space.value(), 6);
        assert!(!result.collapse_info.collapsed);
        assert_eq!(result.collapse_info.operation_type, OperationType::ClassicalClassical);
    }

    #[test]
    fn test_quantum_quantum_collapse() {
        let s_neg2 = FactorizationStateSpace::new(-2).unwrap();
        let s_neg3 = FactorizationStateSpace::new(-3).unwrap();
        
        let result = StateSpaceOperations::multiply(&s_neg2, &s_neg3).unwrap();
        
        assert_eq!(result.result_space.value(), 6);
        assert!(result.collapse_info.collapsed);
        assert_eq!(result.collapse_info.operation_type, OperationType::QuantumQuantum);
        
        // State space should be smaller (collapse)
        let max_input_size = s_neg2.size().max(s_neg3.size());
        assert!(result.result_space.size() <= max_input_size);
    }

    #[test]
    fn test_classical_quantum_interaction() {
        let s2 = FactorizationStateSpace::new(2).unwrap();
        let s_neg3 = FactorizationStateSpace::new(-3).unwrap();
        
        let result = StateSpaceOperations::multiply(&s2, &s_neg3).unwrap();
        
        assert_eq!(result.result_space.value(), -6);
        assert!(!result.collapse_info.collapsed);
        assert_eq!(result.collapse_info.operation_type, OperationType::ClassicalQuantum);
    }

    #[test]
    fn test_power_operations() {
        let s_neg2 = FactorizationStateSpace::new(-2).unwrap();
        
        // Even power should cause collapse
        let result_even = StateSpaceOperations::power(&s_neg2, 2).unwrap();
        assert_eq!(result_even.result_space.value(), 4);
        assert!(result_even.collapse_info.collapsed);
        
        // Odd power should preserve quantum nature
        let result_odd = StateSpaceOperations::power(&s_neg2, 3).unwrap();
        assert_eq!(result_odd.result_space.value(), -8);
        assert!(!result_odd.collapse_info.collapsed);
        
        // Power 0 should give unity
        let result_zero = StateSpaceOperations::power(&s_neg2, 0).unwrap();
        assert_eq!(result_zero.result_space.value(), 1);
    }

    #[test]
    fn test_sign_flip() {
        let s6 = FactorizationStateSpace::new(6).unwrap();
        let s_neg6 = StateSpaceOperations::sign_flip(&s6).unwrap();
        
        assert_eq!(s_neg6.value(), -6);
        assert!(s_neg6.is_quantum());
        
        // Sign flip back
        let s6_again = StateSpaceOperations::sign_flip(&s_neg6).unwrap();
        assert_eq!(s6_again.value(), 6);
        assert!(s6_again.is_classical());
    }

    #[test]
    fn test_superposition_analysis() {
        let s6 = FactorizationStateSpace::new(6).unwrap();
        let analysis = StateSpaceOperations::analyze_superposition(&s6);
        
        assert!(analysis.is_classical);
        assert!(!analysis.is_quantum);
        assert_eq!(analysis.state_space_size, 2);
        assert_eq!(analysis.sign_prime_factorizations, 0);
        
        let s_neg6 = FactorizationStateSpace::new(-6).unwrap();
        let quantum_analysis = StateSpaceOperations::analyze_superposition(&s_neg6);
        
        assert!(!quantum_analysis.is_classical);
        assert!(quantum_analysis.is_quantum);
        assert!(quantum_analysis.state_space_size > analysis.state_space_size);
        assert!(quantum_analysis.sign_prime_factorizations > 0);
        assert!(quantum_analysis.entropy() > analysis.entropy());
    }

    #[test]
    fn test_can_multiply() {
        let s2 = FactorizationStateSpace::new(2).unwrap();
        let s3 = FactorizationStateSpace::new(3).unwrap();
        
        assert!(StateSpaceOperations::can_multiply(&s2, &s3));
        
        // Test overflow detection with numbers that can actually be factorized
        // Both numbers must be ≤ 10000 for our factorization to work
        // Let's just verify the can_multiply logic with a simple calculation
        let space_small = FactorizationStateSpace::new(1000).unwrap();
        let space_large = FactorizationStateSpace::new(9000).unwrap();
        
        // These should multiply fine (1000 * 9000 = 9,000,000 which is well within i64)
        assert!(StateSpaceOperations::can_multiply(&space_small, &space_large));
        
        // For a true overflow test, we'd need numbers that our factorization can't handle,
        // so let's just verify the logic works for reasonable numbers
    }

    #[test]
    fn test_convenience_methods() {
        let s2 = FactorizationStateSpace::new(2).unwrap();
        let s3 = FactorizationStateSpace::new(3).unwrap();
        
        let result = s2.multiply(&s3).unwrap();
        assert_eq!(result.result_space.value(), 6);
        
        let power_result = s2.power(3).unwrap();
        assert_eq!(power_result.result_space.value(), 8);
        
        let flipped = s2.sign_flip().unwrap();
        assert_eq!(flipped.value(), -2);
        
        assert!(s2.is_classical());
        assert!(!s2.is_quantum());
        
        assert!(!flipped.is_classical());
        assert!(flipped.is_quantum());
    }

    #[test]
    fn test_collapse_ratios() {
        // Test various collapse scenarios
        let s_neg6 = FactorizationStateSpace::new(-6).unwrap(); // Size 3
        let s_neg2 = FactorizationStateSpace::new(-2).unwrap(); // Size 2
        
        let result = s_neg6.multiply(&s_neg2).unwrap();
        assert_eq!(result.result_space.value(), 12);
        assert!(result.collapse_info.collapsed);
        
        // Collapse ratio should be <= 1.0 (size reduction)
        assert!(result.collapse_info.collapse_ratio <= 1.0);
    }

    #[test]
    fn test_display_formatting() {
        let s_neg6 = FactorizationStateSpace::new(-6).unwrap();
        let analysis = s_neg6.analyze_superposition();
        
        let analysis_str = format!("{}", analysis);
        assert!(analysis_str.contains("Quantum"));
        assert!(analysis_str.contains("State space size"));
        
        let s2 = FactorizationStateSpace::new(2).unwrap();
        let s3 = FactorizationStateSpace::new(3).unwrap();
        let result = s2.multiply(&s3).unwrap();
        
        let collapse_str = format!("{}", result.collapse_info);
        assert!(collapse_str.contains("ClassicalClassical"));
        assert!(collapse_str.contains("Collapsed: false"));
    }
}