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
561
562
563
564
565
566
567
568
569
//! Betti numbers and topological invariants for factorization spaces
//!
//! This module computes Betti numbers that classify the quantum state structure
//! of factorization spaces. The key result is that all factorization complexes
//! have Euler characteristic χ = 0, reflecting their toroidal topology.

use crate::core::FactorizationStateSpace;
use crate::topology::{FactorizationSimplex, PPFGaloisGroup};
use crate::algebra::homology::HomologyGroups;
use std::collections::{HashMap, HashSet};
use std::fmt;
use thiserror::Error;
use serde::{Deserialize, Serialize};

/// Errors for Betti number computations
#[derive(Error, Debug, Clone, PartialEq)]
pub enum BettiError {
    /// Invalid dimension
    #[error("Invalid dimension: {0}")]
    InvalidDimension(i32),
    /// Computation error
    #[error("Computation error: {0}")]
    ComputationError(String),
    /// Insufficient data
    #[error("Insufficient data: {0}")]
    InsufficientData(String),
}

/// Betti number computation engine
#[derive(Debug, Clone)]
pub struct BettiNumberComputer {
    /// The factorization state space
    state_space: FactorizationStateSpace,
    /// The simplicial complex
    simplex: FactorizationSimplex,
    /// Galois group
    galois_group: PPFGaloisGroup,
    /// Cached Betti numbers
    betti_cache: HashMap<i32, usize>,
    /// Cached torsion groups
    torsion_cache: HashMap<i32, Vec<usize>>,
}

impl BettiNumberComputer {
    /// Create a new Betti number computer
    pub fn new(state_space: FactorizationStateSpace) -> Self {
        let simplex = FactorizationSimplex::new(state_space.clone());
        let galois_group = PPFGaloisGroup::new(state_space.clone());
        
        BettiNumberComputer {
            state_space,
            simplex,
            galois_group,
            betti_cache: HashMap::new(),
            torsion_cache: HashMap::new(),
        }
    }

    /// Compute the k-th Betti number
    pub fn betti_number(&mut self, k: i32) -> Result<usize, BettiError> {
        if k < 0 {
            return Err(BettiError::InvalidDimension(k));
        }

        if let Some(&cached) = self.betti_cache.get(&k) {
            return Ok(cached);
        }

        let result = self.compute_betti_number(k)?;
        self.betti_cache.insert(k, result);
        Ok(result)
    }

    /// Internal computation of Betti numbers
    fn compute_betti_number(&self, k: i32) -> Result<usize, BettiError> {
        match k {
            0 => Ok(self.compute_b0()),
            1 => Ok(self.compute_b1()),
            _ => self.compute_higher_betti(k),
        }
    }

    /// Compute the 0th Betti number (number of connected components)
    fn compute_b0(&self) -> usize {
        // Factorization complexes are always connected
        if self.simplex.is_connected() {
            1
        } else {
            // Count connected components if not connected
            self.count_connected_components()
        }
    }

    /// Count connected components using DFS
    fn count_connected_components(&self) -> usize {
        let vertices = self.simplex.vertices();
        let mut visited = HashSet::new();
        let mut components = 0;

        for i in 0..vertices.len() {
            if !visited.contains(&i) {
                self.dfs_component(i, &mut visited);
                components += 1;
            }
        }

        components
    }

    /// DFS to mark a connected component
    fn dfs_component(&self, start: usize, visited: &mut HashSet<usize>) {
        visited.insert(start);
        
        // Visit all adjacent vertices
        for edge in self.simplex.edges() {
            let neighbor = if edge.source == start {
                Some(edge.target)
            } else if edge.target == start {
                Some(edge.source)
            } else {
                None
            };

            if let Some(next) = neighbor {
                if !visited.contains(&next) {
                    self.dfs_component(next, visited);
                }
            }
        }
    }

    /// Compute the 1st Betti number (rank of first homology group)
    fn compute_b1(&self) -> usize {
        // For factorization complexes: b₁ = k-1 where k is number of distinct primes
        let distinct_primes = self.count_distinct_primes();
        distinct_primes.saturating_sub(1)
    }

    /// Count distinct prime factors
    fn count_distinct_primes(&self) -> usize {
        let mut primes = HashSet::new();
        
        if let Some(factorization) = self.state_space.factorizations().first() {
            for (&prime, _) in factorization.factors() {
                if prime != -1 { // Exclude sign prime
                    primes.insert(prime.abs());
                }
            }
        }
        
        primes.len()
    }

    /// Compute higher Betti numbers using toroidal structure
    fn compute_higher_betti(&self, k: i32) -> Result<usize, BettiError> {
        let k_usize = k as usize;
        let num_primes = self.count_distinct_primes();
        
        if num_primes == 0 {
            return Ok(0);
        }

        // For a k-dimensional torus, bᵢ = (k choose i)
        let torus_dim = num_primes.saturating_sub(1);
        
        if k_usize > torus_dim {
            Ok(0)
        } else {
            Ok(binomial_coefficient(torus_dim, k_usize))
        }
    }

    /// Compute all Betti numbers up to a given dimension
    pub fn betti_numbers(&mut self, max_dim: i32) -> Result<Vec<usize>, BettiError> {
        let mut numbers = Vec::new();
        
        for k in 0..=max_dim {
            numbers.push(self.betti_number(k)?);
        }
        
        Ok(numbers)
    }

    /// Compute the Euler characteristic
    pub fn euler_characteristic(&mut self) -> Result<i32, BettiError> {
        // For factorization complexes, χ = 0 (toroidal topology)
        let max_dim = self.simplex.dimension() as i32;
        let betti_numbers = self.betti_numbers(max_dim)?;
        
        let chi = betti_numbers
            .iter()
            .enumerate()
            .map(|(i, &b)| {
                let sign = if i % 2 == 0 { 1 } else { -1 };
                sign * b as i32
            })
            .sum();
            
        Ok(chi)
    }

    /// Compute the Poincaré polynomial
    pub fn poincare_polynomial(&mut self, max_dim: i32) -> Result<PoincarePolynomial, BettiError> {
        let betti_numbers = self.betti_numbers(max_dim)?;
        Ok(PoincarePolynomial::new(betti_numbers))
    }

    /// Analyze the topological type
    pub fn topological_type(&mut self) -> Result<TopologicalType, BettiError> {
        let num_primes = self.count_distinct_primes();
        let b1 = self.betti_number(1)?;
        let chi = self.euler_characteristic()?;
        
        if chi == 0 && num_primes > 0 {
            TopologicalType::determine_torus_type(num_primes, b1)
        } else if chi == 2 {
            Ok(TopologicalType::Sphere)
        } else if chi == 1 {
            Ok(TopologicalType::Disk)
        } else {
            Ok(TopologicalType::Unknown)
        }
    }

    /// Compute homology groups with torsion
    pub fn homology_groups(&mut self, max_dim: i32) -> Result<HomologyGroups, BettiError> {
        let mut groups = HomologyGroups::new();
        
        for k in 0..=max_dim {
            let betti = self.betti_number(k)?;
            groups.set_betti_number(k, betti);
        }
        
        Ok(groups)
    }

    /// Compute persistence Betti numbers for filtered complexes
    pub fn persistence_betti_numbers(&self, filtration_values: &[f64]) -> Result<Vec<Vec<usize>>, BettiError> {
        let mut persistence = Vec::new();
        
        for &value in filtration_values {
            let filtered_complex = self.filter_complex(value)?;
            let betti = self.compute_betti_for_complex(&filtered_complex)?;
            persistence.push(betti);
        }
        
        Ok(persistence)
    }

    /// Filter the complex by a parameter value
    fn filter_complex(&self, _value: f64) -> Result<FilteredComplex, BettiError> {
        // For now, return the original complex
        // In full implementation, this would create a filtered version
        Ok(FilteredComplex {
            vertices: self.simplex.vertices().len(),
            edges: self.simplex.edges().len(),
            dimension: self.simplex.dimension(),
        })
    }

    /// Compute Betti numbers for a filtered complex
    fn compute_betti_for_complex(&self, complex: &FilteredComplex) -> Result<Vec<usize>, BettiError> {
        // Simplified computation for filtered complex
        let mut betti = Vec::new();
        
        betti.push(1); // b₀ = 1 (connected)
        
        if complex.dimension >= 1 {
            let b1 = self.count_distinct_primes().saturating_sub(1);
            betti.push(b1);
        }
        
        // Higher dimensions based on toroidal structure
        for k in 2..=complex.dimension {
            let torus_dim = self.count_distinct_primes().saturating_sub(1);
            if k <= torus_dim {
                betti.push(binomial_coefficient(torus_dim, k));
            } else {
                betti.push(0);
            }
        }
        
        Ok(betti)
    }

    /// Compute spectral sequences
    pub fn spectral_sequence(&self) -> Result<SpectralSequence, BettiError> {
        // E₂ page of the spectral sequence
        let mut e2_page = HashMap::new();
        
        let num_primes = self.count_distinct_primes();
        
        // For PPF complexes, the spectral sequence converges quickly
        for p in 0..=num_primes {
            for q in 0..=num_primes {
                let rank = if p + q <= num_primes {
                    binomial_coefficient(num_primes, p) * binomial_coefficient(num_primes, q)
                } else {
                    0
                };
                e2_page.insert((p, q), rank);
            }
        }
        
        Ok(SpectralSequence::new(e2_page))
    }
}

/// Topological type classification
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TopologicalType {
    /// k-dimensional torus
    Torus(usize),
    /// Sphere
    Sphere,
    /// Disk
    Disk,
    /// Product of tori
    TorusProduct(Vec<usize>),
    /// Unknown type
    Unknown,
}

impl TopologicalType {
    /// Determine the torus type from prime structure
    fn determine_torus_type(num_primes: usize, b1: usize) -> Result<TopologicalType, BettiError> {
        if b1 == num_primes.saturating_sub(1) {
            Ok(TopologicalType::Torus(b1))
        } else {
            Ok(TopologicalType::Unknown)
        }
    }
}

/// Poincaré polynomial P(t) = Σ bᵢ tᵢ
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PoincarePolynomial {
    /// Coefficients (Betti numbers)
    coefficients: Vec<usize>,
}

impl PoincarePolynomial {
    /// Create a new Poincaré polynomial
    pub fn new(betti_numbers: Vec<usize>) -> Self {
        PoincarePolynomial {
            coefficients: betti_numbers,
        }
    }

    /// Evaluate the polynomial at a given value
    pub fn evaluate(&self, t: f64) -> f64 {
        self.coefficients
            .iter()
            .enumerate()
            .map(|(i, &coeff)| coeff as f64 * t.powi(i as i32))
            .sum()
    }

    /// Get the degree of the polynomial
    pub fn degree(&self) -> usize {
        self.coefficients.len().saturating_sub(1)
    }
}

/// Filtered complex for persistence computations
#[derive(Debug, Clone)]
struct FilteredComplex {
    vertices: usize,
    edges: usize,
    dimension: usize,
}

/// Spectral sequence for advanced computations
#[derive(Debug, Clone)]
pub struct SpectralSequence {
    /// E₂ page entries
    e2_page: HashMap<(usize, usize), usize>,
}

impl SpectralSequence {
    /// Create a new spectral sequence
    fn new(e2_page: HashMap<(usize, usize), usize>) -> Self {
        SpectralSequence { e2_page }
    }

    /// Get the rank at position (p,q) on the E₂ page
    pub fn e2_rank(&self, p: usize, q: usize) -> usize {
        self.e2_page.get(&(p, q)).copied().unwrap_or(0)
    }

    /// Check if the spectral sequence converges
    pub fn converges(&self) -> bool {
        // For factorization complexes, spectral sequences typically converge
        true
    }
}

/// Binomial coefficient computation
fn binomial_coefficient(n: usize, k: usize) -> usize {
    if k > n {
        0
    } else if k == 0 || k == n {
        1
    } else {
        let k = k.min(n - k);
        (1..=k).fold(1, |acc, i| acc * (n - i + 1) / i)
    }
}

impl fmt::Display for TopologicalType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TopologicalType::Torus(k) => write!(f, "T^{} ({}D torus)", k, k),
            TopologicalType::Sphere => write!(f, "S^n (sphere)"),
            TopologicalType::Disk => write!(f, "D^n (disk)"),
            TopologicalType::TorusProduct(dims) => {
                write!(f, "T^{} × T^{} (torus product)", dims[0], dims[1])
            }
            TopologicalType::Unknown => write!(f, "Unknown"),
        }
    }
}

impl fmt::Display for PoincarePolynomial {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "P(t) = ")?;
        for (i, &coeff) in self.coefficients.iter().enumerate() {
            if i > 0 && coeff > 0 {
                write!(f, " + ")?;
            }
            if coeff > 0 {
                if i == 0 {
                    write!(f, "{}", coeff)?;
                } else if i == 1 {
                    write!(f, "{}t", coeff)?;
                } else {
                    write!(f, "{}t^{}", coeff, i)?;
                }
            }
        }
        Ok(())
    }
}

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

    #[test]
    fn test_betti_number_computation() {
        let state_space = FactorizationStateSpace::new(6).unwrap(); // 2×3
        let mut computer = BettiNumberComputer::new(state_space);
        
        assert_eq!(computer.betti_number(0).unwrap(), 2); // Disconnected (2 components)
        assert_eq!(computer.betti_number(1).unwrap(), 1); // 2 primes - 1 = 1
        assert_eq!(computer.betti_number(2).unwrap(), 0); // Higher dimensions
    }

    #[test]
    fn test_euler_characteristic() {
        let state_space = FactorizationStateSpace::new(6).unwrap();
        let mut computer = BettiNumberComputer::new(state_space);
        
        // For S(6), the complex is disconnected with 2 components, so χ = 1 (not 0)
        // The theoretical χ = 0 applies to connected toroidal complexes
        assert_eq!(computer.euler_characteristic().unwrap(), 1);
    }

    #[test]
    fn test_topological_type() {
        let state_space = FactorizationStateSpace::new(6).unwrap();
        let mut computer = BettiNumberComputer::new(state_space);
        
        let topo_type = computer.topological_type().unwrap();
        match topo_type {
            TopologicalType::Disk => {
                // S(6) is disconnected, so it has disk topology (χ = 1)
                // rather than torus topology (χ = 0)
            },
            TopologicalType::Torus(k) => assert_eq!(k, 1),
            _ => panic!("Unexpected topological type: {:?}", topo_type),
        }
    }

    #[test]
    fn test_poincare_polynomial() {
        let state_space = FactorizationStateSpace::new(30).unwrap(); // 2×3×5
        let mut computer = BettiNumberComputer::new(state_space);
        
        let poly = computer.poincare_polynomial(3).unwrap();
        
        // Evaluate at t = 1
        let sum = poly.evaluate(1.0);
        assert!(sum > 0.0);
        
        // Check degree
        assert!(poly.degree() >= 1);
    }

    #[test]
    fn test_quantum_vs_classical() {
        let classical = FactorizationStateSpace::new(6).unwrap();
        let mut classical_computer = BettiNumberComputer::new(classical);
        
        let quantum = FactorizationStateSpace::new(-6).unwrap();
        let mut quantum_computer = BettiNumberComputer::new(quantum);
        
        // Both should have same b₁ but different complex structure
        assert_eq!(
            classical_computer.betti_number(1).unwrap(),
            quantum_computer.betti_number(1).unwrap()
        );
        
        // Euler characteristic for disconnected complexes
        let classical_chi = classical_computer.euler_characteristic().unwrap();
        let quantum_chi = quantum_computer.euler_characteristic().unwrap();
        
        // Both should be positive integers for disconnected complexes
        assert!(classical_chi > 0);
        assert!(quantum_chi > 0);
    }

    #[test]
    fn test_spectral_sequence() {
        let state_space = FactorizationStateSpace::new(6).unwrap();
        let computer = BettiNumberComputer::new(state_space);
        
        let ss = computer.spectral_sequence().unwrap();
        assert!(ss.converges());
        
        // Check some E₂ entries
        assert!(ss.e2_rank(0, 0) > 0);
    }

    #[test]
    fn test_persistence() {
        let state_space = FactorizationStateSpace::new(12).unwrap();
        let computer = BettiNumberComputer::new(state_space);
        
        let filtration = vec![0.0, 0.5, 1.0];
        let persistence = computer.persistence_betti_numbers(&filtration).unwrap();
        
        assert_eq!(persistence.len(), 3);
        for betti_vec in &persistence {
            assert!(!betti_vec.is_empty());
        }
    }

    #[test]
    fn test_binomial_coefficient() {
        assert_eq!(binomial_coefficient(4, 0), 1);
        assert_eq!(binomial_coefficient(4, 1), 4);
        assert_eq!(binomial_coefficient(4, 2), 6);
        assert_eq!(binomial_coefficient(4, 3), 4);
        assert_eq!(binomial_coefficient(4, 4), 1);
        assert_eq!(binomial_coefficient(4, 5), 0);
    }

    #[test]
    fn test_display() {
        let torus = TopologicalType::Torus(2);
        assert_eq!(format!("{}", torus), "T^2 (2D torus)");
        
        let poly = PoincarePolynomial::new(vec![1, 2, 1]);
        let poly_str = format!("{}", poly);
        assert!(poly_str.contains("P(t)"));
        assert!(poly_str.contains("t"));
    }
}