sankhya 1.0.0

sankhya — Ancient mathematical systems: Mayan, Babylonian, Egyptian, Vedic, Chinese, Greek, Roman, Islamic, and cross-civilizational epoch correlation
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
//! Greek mathematics.
//!
//! Implements the golden ratio, Fibonacci sequence, Sieve of Eratosthenes,
//! Euclidean algorithm, Archimedes' pi approximation, and the Antikythera
//! mechanism gear ratios.
//!
//! # Historical Context
//!
//! Greek mathematics (c. 600 BCE - 300 CE) emphasized deductive proof and
//! geometric construction. Euclid's Elements (c. 300 BCE) systematized
//! number theory and geometry. Eratosthenes' prime sieve and Archimedes'
//! polygon method for approximating pi are still taught today. The
//! Antikythera mechanism (c. 150-100 BCE) is the earliest known analog
//! computer, using bronze gears to predict astronomical positions.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

#[cfg(feature = "varna")]
use crate::error::{Result, SankhyaError};

// ---------------------------------------------------------------------------
// Golden ratio and Fibonacci
// ---------------------------------------------------------------------------

/// The golden ratio: phi = (1 + sqrt(5)) / 2.
///
/// Known to the ancient Greeks through the geometry of the regular
/// pentagon and appearing in Euclid's Elements (Book VI, Proposition 30)
/// as "extreme and mean ratio."
pub const PHI: f64 = 1.618_033_988_749_895;

/// Compute the ratio of consecutive Fibonacci numbers F(n+1)/F(n),
/// which approaches the golden ratio phi as n increases.
///
/// Returns the ratio for the given n (n >= 1). For n=0, returns 1.0.
#[must_use]
pub fn fibonacci_ratio(n: usize) -> f64 {
    if n == 0 {
        return 1.0;
    }

    let mut a: f64 = 1.0;
    let mut b: f64 = 1.0;
    for _ in 0..n {
        let temp = b;
        b += a;
        a = temp;
    }
    b / a
}

// ---------------------------------------------------------------------------
// Sieve of Eratosthenes
// ---------------------------------------------------------------------------

/// Find all primes up to `limit` using the Sieve of Eratosthenes.
///
/// Eratosthenes of Cyrene (c. 276-194 BCE) devised this algorithm
/// for finding prime numbers. It works by iteratively marking the
/// multiples of each prime starting from 2.
///
/// Returns an empty vec if limit < 2.
#[must_use]
pub fn sieve(limit: usize) -> Vec<usize> {
    if limit < 2 {
        return Vec::new();
    }

    let mut is_prime = vec![true; limit + 1];
    is_prime[0] = false;
    if limit >= 1 {
        is_prime[1] = false;
    }

    let mut p = 2;
    while p * p <= limit {
        if is_prime[p] {
            let mut multiple = p * p;
            while multiple <= limit {
                is_prime[multiple] = false;
                multiple += p;
            }
        }
        p += 1;
    }

    is_prime
        .iter()
        .enumerate()
        .filter_map(|(i, &prime)| if prime { Some(i) } else { None })
        .collect()
}

// ---------------------------------------------------------------------------
// Euclidean algorithm
// ---------------------------------------------------------------------------

/// Compute the greatest common divisor using Euclid's algorithm.
///
/// From Euclid's Elements, Book VII, Propositions 1-2 (c. 300 BCE).
/// This is one of the oldest known algorithms still in active use.
///
/// Returns 0 if both inputs are 0.
#[must_use]
#[inline]
pub fn gcd(mut a: u64, mut b: u64) -> u64 {
    while b != 0 {
        let t = b;
        b = a % b;
        a = t;
    }
    a
}

/// Compute the least common multiple.
#[must_use]
#[inline]
pub fn lcm(a: u64, b: u64) -> u64 {
    if a == 0 || b == 0 {
        return 0;
    }
    a / gcd(a, b) * b
}

// ---------------------------------------------------------------------------
// Archimedes' pi approximation
// ---------------------------------------------------------------------------

/// Approximate pi using Archimedes' method of exhaustion.
///
/// Archimedes (c. 287-212 BCE) bounded pi by computing the perimeters
/// of regular polygons inscribed in and circumscribed around a circle.
/// Starting with a hexagon (6 sides) and repeatedly doubling the number
/// of sides, he obtained:
///   3 + 10/71 < pi < 3 + 1/7
///   (3.14084... < pi < 3.14285...)
///
/// `iterations` controls the number of doublings starting from a hexagon.
/// Returns `(lower_bound, upper_bound)`.
#[must_use]
pub fn archimedes_pi(iterations: u32) -> (f64, f64) {
    // Start with a regular hexagon (6 sides)
    // Start with known values for hexagon (6 sides) in unit-radius circle:
    // - Inscribed semi-perimeter: n * sin(pi/n) where n=6: 6 * sin(30 deg) = 6 * 0.5 = 3
    // - Circumscribed semi-perimeter: n * tan(pi/n) where n=6: 6 * tan(30 deg) = 6/sqrt(3) = 2*sqrt(3)

    let mut inner = 3.0_f64; // n * sin(pi/n), initially 6 * sin(pi/6) = 3
    let mut outer = 2.0 * 3.0_f64.sqrt(); // n * tan(pi/n), initially 6 * tan(pi/6) = 2*sqrt(3)

    for _ in 0..iterations {
        // Double the number of sides.
        // Archimedes' recursion:
        // For doubling sides, the new outer (circumscribed) is the harmonic mean:
        //   outer_new = 2 * inner * outer / (inner + outer)
        // The new inner (inscribed) is the geometric mean:
        //   inner_new = sqrt(inner * outer_new)

        let outer_new = 2.0 * inner * outer / (inner + outer);
        let inner_new = (inner * outer_new).sqrt();

        inner = inner_new;
        outer = outer_new;
    }

    // inner < pi < outer
    (inner, outer)
}

// ---------------------------------------------------------------------------
// Greek isopsephy (alphabetic numeral values)
// ---------------------------------------------------------------------------

/// Compute the isopsephy value of a Greek word.
///
/// Isopsephy (Greek: ἰσοψηφία, "equal pebbles") is the practice of assigning
/// numeric values to Greek letters and summing them for a word or phrase.
/// It was widely used in antiquity for numerology, word games, and even
/// cryptographic identification (e.g., the "number of the beast" in
/// Revelation uses Greek isopsephy).
///
/// Each letter maps to a value: α=1, β=2, ... θ=9, ι=10, κ=20, ... π=80,
/// ρ=100, σ=200, ... ω=800. The word value is the additive sum.
///
/// Requires the `varna` feature for the numeral system tables.
///
/// # Errors
///
/// Returns [`SankhyaError::InvalidBase`] if the input is empty or contains
/// characters with no isopsephy mapping.
#[cfg(feature = "varna")]
#[must_use = "returns the computed isopsephy value without side effects"]
pub fn isopsephy(word: &str) -> Result<u32> {
    if word.is_empty() {
        return Err(SankhyaError::InvalidBase(
            "empty string has no isopsephy value".into(),
        ));
    }
    let system = varna::script::numerals::greek_isopsephy();
    system.string_value(word).ok_or_else(|| {
        SankhyaError::InvalidBase(format!(
            "word contains characters with no isopsephy mapping: {word}"
        ))
    })
}

/// Convert a number to its Greek alphabetic numeral representation.
///
/// The Greek alphabetic numeral system represents numbers 1-800 using
/// the 24 letters of the Greek alphabet (plus archaic letters for 6, 90,
/// and 900 in the full system — this implementation covers the standard
/// 24-letter range).
///
/// Numbers are decomposed additively: 358 = τ (300) + ν (50) + η (8) = "τνη".
///
/// Requires the `varna` feature.
///
/// # Errors
///
/// Returns [`SankhyaError::InvalidBase`] if `n` is 0 or exceeds the
/// representable range.
#[cfg(feature = "varna")]
#[must_use = "returns the numeral string without side effects"]
pub fn to_greek_numeral(n: u32) -> Result<String> {
    if n == 0 {
        return Err(SankhyaError::InvalidBase(
            "zero has no Greek numeral representation".into(),
        ));
    }

    let system = varna::script::numerals::greek_isopsephy();

    // Decompose into hundreds, tens, units using available letter values.
    // Available values in descending order from the isopsephy table.
    let available: &[u32] = &[
        800, 700, 600, 500, 400, 300, 200, 100, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 5, 4, 3,
        2, 1,
    ];

    let mut remainder = n;
    let mut result = String::new();

    for &val in available {
        if remainder >= val
            && let Some(ch) = system.char_for(val)
        {
            result.push_str(ch);
            remainder -= val;
        }
        if remainder == 0 {
            break;
        }
    }

    if remainder > 0 {
        return Err(SankhyaError::InvalidBase(format!(
            "cannot represent {n} in Greek alphabetic numerals (remainder {remainder})"
        )));
    }

    Ok(result)
}

// ---------------------------------------------------------------------------
// Antikythera mechanism
// ---------------------------------------------------------------------------

/// An astronomical cycle tracked by the Antikythera mechanism.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AntikytheraCycle {
    /// Name of the astronomical cycle.
    pub name: &'static str,
    /// Period in years (approximate).
    pub period_years: &'static str,
    /// Gear tooth count used in the mechanism.
    pub gear_teeth: u32,
    /// Description of the cycle.
    pub description: &'static str,
}

/// Return the known gear ratios of the Antikythera mechanism.
///
/// The Antikythera mechanism (c. 150-100 BCE) is an ancient Greek
/// analog computer found in a shipwreck off the island of Antikythera.
/// It used a system of at least 30 bronze gears to predict:
/// - Solar and lunar positions
/// - Lunar phases
/// - Eclipse predictions (Saros and Exeligmos cycles)
/// - Dates of the Olympic games
///
/// Returns a map from cycle name to gear tooth count and description.
#[must_use]
pub fn antikythera_gear_ratios() -> BTreeMap<&'static str, AntikytheraCycle> {
    let cycles = vec![
        AntikytheraCycle {
            name: "Metonic",
            period_years: "19",
            gear_teeth: 235,
            description: "19 tropical years = 235 synodic months (Meton of Athens, 432 BCE)",
        },
        AntikytheraCycle {
            name: "Saros",
            period_years: "18.03",
            gear_teeth: 223,
            description: "223 synodic months — eclipse repeat cycle",
        },
        AntikytheraCycle {
            name: "Exeligmos",
            period_years: "54.09",
            gear_teeth: 669,
            description: "3 Saros cycles = 669 synodic months (exact eclipse repeat)",
        },
        AntikytheraCycle {
            name: "Callippic",
            period_years: "76",
            gear_teeth: 940,
            description: "4 Metonic cycles - 1 day = 940 synodic months (Callippus, 330 BCE)",
        },
        AntikytheraCycle {
            name: "Olympiad",
            period_years: "4",
            gear_teeth: 57,
            description: "4-year cycle of Panhellenic games (Olympic, Nemean, Isthmian, Pythian)",
        },
        AntikytheraCycle {
            name: "Synodic Month",
            period_years: "0.0809",
            gear_teeth: 127,
            description: "Lunar month: 29.53059 days — ratio 127/223 encodes month count",
        },
        AntikytheraCycle {
            name: "Sidereal Year",
            period_years: "1",
            gear_teeth: 365,
            description: "Solar year: 365.25 days — primary input gear",
        },
    ];

    let mut map = BTreeMap::new();
    for cycle in cycles {
        map.insert(cycle.name, cycle);
    }
    map
}

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

    #[test]
    fn golden_ratio_value() {
        let expected = (1.0_f64 + 5.0_f64.sqrt()) / 2.0;
        assert!((PHI - expected).abs() < 1e-15);
    }

    #[test]
    fn fibonacci_ratio_converges_to_phi() {
        let ratio = fibonacci_ratio(30);
        assert!((ratio - PHI).abs() < 1e-10);
    }

    #[test]
    fn sieve_small() {
        let primes = sieve(30);
        assert_eq!(primes, vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
    }

    #[test]
    fn sieve_below_2() {
        assert!(sieve(0).is_empty());
        assert!(sieve(1).is_empty());
    }

    #[test]
    fn gcd_basic() {
        assert_eq!(gcd(48, 18), 6);
        assert_eq!(gcd(0, 5), 5);
        assert_eq!(gcd(7, 0), 7);
        assert_eq!(gcd(13, 13), 13);
    }

    #[test]
    fn lcm_basic() {
        assert_eq!(lcm(4, 6), 12);
        assert_eq!(lcm(0, 5), 0);
    }

    #[test]
    fn archimedes_pi_bounds() {
        let (lower, upper) = archimedes_pi(10);
        assert!(lower < std::f64::consts::PI);
        assert!(upper > std::f64::consts::PI);
        // After 10 iterations (6 * 2^10 = 6144 sides), should be close
        assert!((lower - std::f64::consts::PI).abs() < 1e-6);
        assert!((upper - std::f64::consts::PI).abs() < 1e-6);
    }

    #[test]
    fn antikythera_metonic() {
        let ratios = antikythera_gear_ratios();
        let metonic = ratios.get("Metonic").unwrap();
        assert_eq!(metonic.gear_teeth, 235);
        assert_eq!(metonic.period_years, "19");
    }

    #[cfg(feature = "varna")]
    mod isopsephy_tests {
        use super::*;

        #[test]
        fn isopsephy_single_letter() {
            assert_eq!(isopsephy("α").unwrap(), 1);
            assert_eq!(isopsephy("ω").unwrap(), 800);
        }

        #[test]
        fn isopsephy_word() {
            // "πι" = 80 + 10 = 90
            assert_eq!(isopsephy("πι").unwrap(), 90);
            // "αω" = 1 + 800 = 801
            assert_eq!(isopsephy("αω").unwrap(), 801);
        }

        #[test]
        fn isopsephy_empty_errors() {
            assert!(isopsephy("").is_err());
        }

        #[test]
        fn isopsephy_non_greek_errors() {
            assert!(isopsephy("hello").is_err());
        }

        #[test]
        fn to_greek_numeral_basic() {
            // 1 = α
            assert_eq!(to_greek_numeral(1).unwrap(), "α");
            // 10 = ι
            assert_eq!(to_greek_numeral(10).unwrap(), "ι");
            // 100 = ρ
            assert_eq!(to_greek_numeral(100).unwrap(), "ρ");
        }

        #[test]
        fn to_greek_numeral_compound() {
            // 358 = τ(300) + ν(50) + η(8) = "τνη"
            assert_eq!(to_greek_numeral(358).unwrap(), "τνη");
        }

        #[test]
        fn to_greek_numeral_roundtrip() {
            // Encode then decode
            let numeral = to_greek_numeral(358).unwrap();
            let value = isopsephy(&numeral).unwrap();
            assert_eq!(value, 358);
        }

        #[test]
        fn to_greek_numeral_zero_errors() {
            assert!(to_greek_numeral(0).is_err());
        }
    }
}