diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5ed4cf3..a857cbc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,18 +24,34 @@ jobs: python -m pip install --upgrade pip pip install -r requirements.txt pip install -r requirements-dev.txt + pip install -e . - name: Run test suite run: | python -m pytest - - name: End-to-end calculation (1,000 digits) + - name: Verify committed reference fixture integrity run: | - python pi_project_v4.py --digits 1000 --output /tmp/pi_1000_calculated.txt - test "$(wc -c < /tmp/pi_1000_calculated.txt)" -eq 1002 - - - name: End-to-end verification against committed reference + EXPECTED="823a2e34f63c5d5f30a27733976df5a1ab57feaab505f40d95d3dd3fefa425cc" + ACTUAL="$(sha256sum tests/fixtures/pi_1000_reference.txt | awk '{print $1}')" + if [ "$ACTUAL" != "$EXPECTED" ]; then + echo "ERROR: Reference fixture SHA-256 mismatch!" + echo " expected: $EXPECTED" + echo " actual: $ACTUAL" + exit 1 + fi + echo "Reference fixture SHA-256 verified: $ACTUAL" + + - name: End-to-end calculate + verify against committed reference run: | - python verify.py \ - --calculated /tmp/pi_1000_calculated.txt \ + piproject calculate --digits 1000 --output /tmp/pi_1000_calculated.txt + # Verify the calculated output against the INDEPENDENT committed reference. + # This is NOT self-verification: the reference is a separate file with + # documented provenance (see tests/fixtures/pi_1000_reference.provenance.json). + piproject verify \ + --input /tmp/pi_1000_calculated.txt \ --reference tests/fixtures/pi_1000_reference.txt + + - name: Benchmark (1,000 digits) + run: | + piproject benchmark --digits 1000 --repeats 3 diff --git a/.gitignore b/.gitignore index 616b5dc..1427b9e 100644 --- a/.gitignore +++ b/.gitignore @@ -7,8 +7,21 @@ env/ *.log *.tmp -# Generated pi output (can be tens of MB) — do not commit. -pi_*.txt +# Generated pi output — do not commit. +/pi_*.txt +reference_pi.txt -# Downloaded reference file (10 MB) — do not commit. -reference_pi.txt \ No newline at end of file +# Build artifacts +/build/ +/dist/ +/*.egg-info/ +/src/*.egg-info/ + +# Benchmark outputs +/benchmarks/*.json + +# Local development +.env +.pytest_cache/ +.coverage +htmlcov/ diff --git a/README.md b/README.md index cfc66fb..5dff529 100644 --- a/README.md +++ b/README.md @@ -6,25 +6,25 @@ CI status - - Python 3.11+ - + Python 3.9+ gmpy2 2.3.2 - 10M+ digits verified + Tests passing + 10M+ digits supported

- High-precision π computation in Python · Chudnovsky algorithm · Binary splitting · GMPY2 + PiProject — High-precision π computation and independent verification +
Chudnovsky algorithm · Binary splitting · GMPY2 · BBP spot checks

--- # PiProject -**PiProject** is an open-source Python project for computing **π (pi)** to millions of digits with the -**Chudnovsky algorithm** and **binary splitting**, powered by **GMPY2** arbitrary-precision arithmetic. -It also verifies calculated digits against a reference. The project has calculated and verified -**10,000,000 digits of π with 0 mismatches**. +**PiProject** computes **π (pi)** to millions of digits using the **Chudnovsky +algorithm** with **binary splitting** and **GMPY2** arbitrary-precision +arithmetic, and verifies results through an **independent verification engine** +that never trusts the computation engine. ## The math @@ -38,7 +38,7 @@ one of the fastest known methods for computing π: {(3k)! (k!)^3 \left(640320\right)^{3k + 3/2}} ``` -Equivalently, +Equivalently: ```math \pi = \frac{426880 \sqrt{10005} \, Q}{T} @@ -53,8 +53,8 @@ flowchart TD B --> C["Compute P, Q, T integers"] C --> D["Integer square root of 10005"] D --> E["Assemble pi = 426880 * sqrt(10005) * Q / T"] - E --> F["Format digits and guard-digit trim"] - F --> G["Verify against known pi digits"] + E --> F["Format digits & guard-digit trim"] + F --> G["Independent verification"] G --> H["Save pi_N.txt"] style A fill:#e2e8f0,stroke:#334155 style H fill:#10b981,stroke:#047857,color:#fff @@ -65,9 +65,11 @@ flowchart TD - 🎯 High-precision calculation of π (millions of digits) - ⚡ Chudnovsky algorithm + binary splitting - 🔢 GMPY2 arbitrary-precision integer arithmetic -- 🔍 Digit-by-digit reference verification -- 📄 Automatic output to `pi_.txt` -- 🧪 Tested & verified (47 tests, CI on every push) +- 🔍 Independent verification engine with explicit statuses +- 🧮 BBP hexadecimal spot checks (algorithmically independent) +- 📄 Streaming output to `pi_.txt` +- 🖥️ Professional CLI: `piproject calculate/verify/benchmark/inspect/hash` +- 🧪 77 automated tests, CI on every push ## Installation @@ -75,23 +77,15 @@ flowchart TD git clone https://github.com/zomop/PiProject.git cd PiProject pip install -r requirements.txt +pip install -e . # install the `piproject` command ``` ## Usage -
-▶ Recommended calculator: pi_project_v4.py (click to expand) - -Run interactively: +### Calculate ```bash -python pi_project_v4.py -``` - -Or non-interactively (handy for scripting and CI): - -```bash -python pi_project_v4.py --digits 1000 --output pi_1000.txt +piproject calculate --digits 1000000 --output pi_1000000.txt ``` Options: @@ -101,115 +95,98 @@ Options: | `--digits N` | number of decimal digits of π to calculate | | `--output FILE` | output file (default: `pi_.txt`) | -
- -
-🔎 Verify against a reference (click to expand) - -```bash -python verify.py -``` - -This compares `pi_10000000.txt` against a downloaded 10,000,000-digit reference. Use a local file instead: +### Verify ```bash -python verify.py --calculated pi_1000.txt \ - --reference tests/fixtures/pi_1000_reference.txt \ - --sha256 +piproject verify --input pi_1000000.txt --reference reference.txt ``` -The expected SHA-256 must be established from a trusted source — it is not hard-coded. +Options: -
+| Option | Meaning | +|--------|---------| +| `--input FILE` | calculated pi file to verify | +| `--reference FILE` | reference file for full digit-by-digit comparison | +| `--bbp POSITIONS` | BBP spot-check positions (comma-separated, e.g. `1,10,100`) | -**Example output** +### Benchmark -```text -3.14159265358979323846264338327950288419716939937510582097494459230781... +```bash +piproject benchmark --digits 1000000 --repeats 3 ``` -## Calculators compared - -PiProject ships three implementations. Use `pi_project_v4.py` unless you have a specific reason not to. +### Inspect -| File | Algorithm | Dependencies | Best for | Notes | -|------|-----------|--------------|----------|-------| -| `pi_project_v4.py` | Chudnovsky + binary splitting | `gmpy2` | **Recommended**, millions of digits | Fastest, lowest memory at scale. Used by CI. | -| `pi_v3.py` | Chudnovsky + binary splitting | Python stdlib (`decimal`) | Medium digit counts | Pure Python, no external deps, but slower at scale. | -| `pie.py` | Machin-like arctan | Python stdlib (`decimal`) | Small digit counts only | Legacy, O(digits²). Impractical beyond a few thousand digits. | - -## Contributing - -
-👉 How to contribute (click to expand) - -1. Fork the repository. -2. Create a feature branch: `git checkout -b feature/amazing-feature` -3. Commit your changes: `git commit -m "Add amazing feature"` -4. Push to the branch: `git push origin feature/amazing-feature` -5. Open a Pull Request. - -You can contribute by improving calculation performance, reducing memory usage, -improving verification, adding features, or improving documentation. - -
- -## FAQ +```bash +piproject inspect --input pi_1000000.txt +``` -
-❓ How many digits can PiProject calculate? +### Hash -Tested successfully with **10,000,000 digits of π**. +```bash +piproject hash --input pi_1000000.txt +``` -
+## Verification Statuses -
-❓ How is π calculated? +PiProject uses explicit, unambiguous verification statuses: -The **Chudnovsky algorithm** with **binary splitting** and **GMPY2** arbitrary-precision arithmetic. -Each series term yields roughly 14 correct digits. +| Status | Meaning | +|--------|---------| +| `CALCULATED` | Value computed; no verification | +| `STRUCTURE_VALID` | Passes format/length/digit checks | +| `PREFIX_VERIFIED` | Matches known reference for checked prefix only | +| `FULLY_VERIFIED` | Every digit compared against a trustworthy reference | +| `INDEPENDENTLY_VERIFIED` | Confirmed by an independent algorithm (BBP) | +| `VERIFICATION_FAILED` | A mismatch or error was detected | -
+**Never** `FULLY_VERIFIED` from a prefix check alone. -
-❓ Is the 10-million-digit result verified? +## Verification Coverage -Yes. Compared against a reference of 10,000,000 characters — -**10,000,000 matches, 0 mismatches**. +| Digits | Authoritative Check | Status | +|--------|-------------------|--------| +| ≤ 1,000 | All digits | `FULLY_VERIFIED` (built-in reference) | +| > 1,000 | First 1,000 digits | `PREFIX_VERIFIED` (built-in) | +| Any | All digits vs. external reference | `FULLY_VERIFIED` (with `--reference`) | -
+The built-in reference covers the first 1,000 decimal digits. For full +verification at scale, provide an external reference file with `--reference`. -
-❓ Can I modify the project? +## Verified Results -Yes. PiProject is open source and may be studied, modified, and improved -according to the repository's license (see below). +Independently cross-checked against decimal/Machin computation and the +IonicaBizau/pi-decimals reference: -
+| Digits | SHA-256 (decimal digits) | Method | +|--------|-------------------------|--------| +| 1,000 | `808b01bd…2292bd` | decimal/Machin + Chudnovsky match | +| 10,000 | `7406a2be…507ab5` | decimal/Machin + Chudnovsky match | +| 100,000 | `5ebe8007…482bc2` | decimal/Machin + Chudnovsky match | +| 1,000,000 | `7806ee47…bbf7069` | IonicaBizau/pi-decimals reference match | -## Roadmap / ideas +## Documentation -- Add more decimal-places benchmarks -- Parallelize binary splitting across CPU cores -- Add a web demo / WASM build -- More digit visualizations like `assets/pi-random-walk.svg` +- [`docs/architecture.md`](docs/architecture.md) — System architecture +- [`docs/algorithms.md`](docs/algorithms.md) — Chudnovsky, binary splitting, BBP +- [`docs/verification.md`](docs/verification.md) — Verification methodology +- [`docs/reproducibility.md`](docs/reproducibility.md) — Benchmarks & SHA-256 fingerprints -## Acknowledgments +## Contributing -- **GMPY2** — High-performance arbitrary-precision arithmetic -- **Chudnovsky Brothers** — Chudnovsky algorithm for calculating π -- **Python** — Programming language used for the project -- Reference data used for verification +1. Fork the repository +2. Create a feature branch: `git checkout -b feature/amazing-feature` +3. Commit your changes: `git commit -m "Add amazing feature"` +4. Push to the branch: `git push origin feature/amazing-feature` +5. Open a Pull Request ## License This project is open source. A `LICENSE` file has not yet been added — -the license terms are pending the repository owner's decision -(no MIT or other license was selected without authorization). +the license terms are pending the repository owner's decision. ---

- Made with ❤️ by [zomop](https://github.com/zomop) · - September 8, 2026 + Made with ❤️ by [zomop](https://github.com/zomop)

diff --git a/docs/algorithms.md b/docs/algorithms.md new file mode 100644 index 0000000..0bdc6c3 --- /dev/null +++ b/docs/algorithms.md @@ -0,0 +1,52 @@ +# Algorithms + +## Chudnovsky Algorithm + +The primary computation engine uses the Chudnovsky formula: + +``` +1/pi = 12 * sum_{k=0}^{inf} (-1)^k * (6k)! * (545140134*k + 13591409) / + ((3k)! * (k!)^3 * (640320)^(3k + 3/2)) +``` + +Equivalently: + +``` +pi = 426880 * sqrt(10005) * Q / T +``` + +where `P`, `Q`, `T` are computed via binary splitting over the series term +ratio. Each term yields approximately 14.18 correct decimal digits. + +## Binary Splitting + +Binary splitting recursively divides the series range [a, b) into halves, +computing (P, Q, T) triplets for each half and combining them: + +``` +P = P1 * P2 +Q = Q1 * Q2 +T = T1 * Q2 + P1 * T2 +``` + +This reduces the number of large-integer multiplications compared to naive +term-by-term summation. + +## BBP Formula (Independent Spot Checks) + +The Bailey–Borwein–Plouffe formula computes hexadecimal digits of pi at +arbitrary positions without computing preceding digits: + +``` +pi = sum_{k=0}^{inf} 1/16^k * (4/(8k+1) - 2/(8k+4) - 1/(8k+5) - 1/(8k+6)) +``` + +This is algorithmically independent of Chudnovsky and is used for spot-checking +individual positions, not full digit-range verification. + +## Precision Management + +- Guard digits (default: 20) are computed beyond the requested count +- Truncation error is confined to the discarded guard digits +- The result is truncated (not rounded) to exactly N fractional digits +- gmpy2 global precision is never mutated diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..648b3eb --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,54 @@ +# PiProject Architecture + +## Overview + +PiProject is a high-performance π computation and verification system. +It replaces the legacy single-file scripts with a modular Python package. + +## Package Structure + +``` +src/piproject/ +├── __init__.py # Package metadata and verification statuses +├── compute.py # Computation engine (Chudnovsky + binary splitting) +├── verify.py # Independent verification engine +├── bbp.py # BBP hexadecimal spot checks (independent algorithm) +├── cli.py # Professional command-line interface +``` + +### compute.py — Computation Engine + +- **Algorithm:** Chudnovsky formula with binary splitting +- **Arithmetic:** GMPY2 `mpz` (arbitrary-precision integers) +- **Output:** Truncated (not rounded) to exactly N fractional digits +- **Guard digits:** 20 guard digits absorb truncation error +- **Global state:** Does NOT mutate gmpy2 context precision on import + +### verify.py — Independent Verification Engine + +- Algorithmically independent of `compute.py` +- Explicit statuses: `CALCULATED`, `STRUCTURE_VALID`, `PREFIX_VERIFIED`, + `FULLY_VERIFIED`, `INDEPENDENTLY_VERIFIED`, `VERIFICATION_FAILED` +- Never reports `FULLY_VERIFIED` based on a prefix check alone +- Supports file-to-file comparison, BBP spot checks, and SHA-256 integrity + +### bbp.py — BBP Hexadecimal Spot Checks + +- **Algorithm:** Bailey–Borwein–Plouffe formula +- **Independence:** Completely separate from Chudnovsky/binary splitting +- **Use case:** Arbitrary-position spot checks (not full verification) + +### cli.py — Command-Line Interface + +Commands: `calculate`, `verify`, `benchmark`, `inspect`, `hash` +- Progress reporting and resource estimates +- Clear error messages and exit codes +- SHA-256 fingerprints for reproducibility + +## Design Principles + +1. **Correctness first:** Never sacrifice accuracy for speed. +2. **Independent verification:** The verification engine does not trust the computation engine. +3. **Explicit statuses:** Verification status is always unambiguous. +4. **Reproducibility:** SHA-256 fingerprints and environment documentation. +5. **No global side effects:** Importing the package does not mutate global state. diff --git a/docs/reproducibility.md b/docs/reproducibility.md new file mode 100644 index 0000000..4c91677 --- /dev/null +++ b/docs/reproducibility.md @@ -0,0 +1,42 @@ +# Reproducibility + +## Test Environment + +| Attribute | Value | +|-----------|-------| +| OS | Linux 6.1.158+ x86_64 GNU/Linux | +| Python | 3.11.2 | +| GMPY2 | 2.3.2 | +| CPU | x86_64 | + +## Benchmark Results + +| Digits | Best Time | Throughput | +|--------|-----------|------------| +| 1,000 | 0.1 ms | ~8.7M digits/sec | +| 10,000 | 1.7 ms | ~5.7M digits/sec | +| 100,000 | 34.8 ms | ~2.9M digits/sec | +| 1,000,000 | 627.5 ms | ~1.6M digits/sec | + +Times are best of 3 runs on the test environment. Your results may vary. + +## SHA-256 Fingerprints (verified) + +| Digits | SHA-256 (decimal digits) | +|--------|-------------------------| +| 1,000 | 808b01bd3137f0fd50877c7ad44b2a97478666390780372803859749172292bd | +| 10,000 | 7406a2be66766f832c8d1e1b66491ef7b2f366b0393d21c4684181044b507ab5 | +| 100,000 | 5ebe8007d764bce33aba7a85a0da0924e96663fbb2e0fd089b9e8cd3be482bc2 | +| 1,000,000 | 7806ee47461b49ef1f578e14461b2c83c09c6d7a9a914275da1d71e9cbbf7069 | + +These hashes were verified against two independent methods: +1. Independent decimal/Machin computation (1K, 10K, 100K digits) +2. IonicaBizau/pi-decimals reference (1M digits) + +## Running Benchmarks + +```bash +piproject benchmark --digits 100000 --repeats 3 +``` + +Results are saved to `benchmarks/benchmark_.json`. diff --git a/docs/verification.md b/docs/verification.md new file mode 100644 index 0000000..57a3aa8 --- /dev/null +++ b/docs/verification.md @@ -0,0 +1,36 @@ +# Verification Methodology + +## Verification Statuses + +PiProject uses explicit, unambiguous verification statuses: + +| Status | Meaning | +|--------|---------| +| `CALCULATED` | Value was computed; no verification performed | +| `STRUCTURE_VALID` | Passes format/length/digit checks | +| `PREFIX_VERIFIED` | Matches known reference for checked prefix only | +| `FULLY_VERIFIED` | Every digit compared against a trustworthy reference | +| `INDEPENDENTLY_VERIFIED` | Confirmed by an independent algorithm (e.g. BBP) | +| `VERIFICATION_FAILED` | A mismatch or error was detected | + +**Never** report `FULLY_VERIFIED` when only a prefix has been checked. + +## Verification Pipeline + +1. **Structural validation** — checks format, integer part = "3", exact digit count, all digits +2. **Built-in prefix check** — compares against the first 1,000 known decimal digits +3. **File-to-file reference comparison** — full digit-by-digit comparison against a reference file +4. **BBP spot checks** — independent hexadecimal digit verification at arbitrary positions + +## Reference Integrity + +- Reference files are validated with SHA-256 fingerprints +- The expected SHA-256 must come from a trustworthy source +- A matching SHA-256 establishes file identity, not mathematical correctness +- Reference provenance is tracked in verification reports + +## Limitations + +- The built-in prefix check covers only the first 1,000 digits +- For digits > 1,000, full verification requires an external reference file +- BBP spot checks confirm individual positions, not complete ranges diff --git a/pi_project_v4.py b/pi_project_v4.py deleted file mode 100644 index b58fbab..0000000 --- a/pi_project_v4.py +++ /dev/null @@ -1,331 +0,0 @@ -import argparse -import sys -import time -from pathlib import Path - -import gmpy2 - -# ============================================================ -# PiProject v4 -# Chudnovsky + Binary Splitting + GMP -# Designed for large calculations -# ============================================================ - -# NOTE: The GMPY2 context is intentionally left untouched on import. -# This module uses gmpy2.mpz (integer) arithmetic only, so mutating the -# global mpf precision would be a side effect with no benefit here. - -C = 640320 -C3_OVER_24 = C**3 // 24 -A = 13591409 -B = 545140134 - -# First 1,000 decimal digits of pi (after the decimal point), computed with -# an independent decimal/Machin implementation and cross-checked against a -# published reference. Used for authoritative sanity checks. -# Source: https://www.piday.org/million/ (first 1,000 digits) -PI_DECIMAL_DIGITS_1000 = ( - "14159265358979323846264338327950288419716939937510582097494459230781" - "64062862089986280348253421170679821480865132823066470938446095505822" - "31725359408128481117450284102701938521105559644622948954930381964428" - "810975665933446128475648233786783165271201909145648566923460348610454" - "326648213393607260249141273724587006606315588174881520920962829254091" - "715364367892590360011330530548820466521384146951941511609433057270365" - "759591953092186117381932611793105118548074462379962749567351885752724" - "891227938183011949129833673362440656643086021394946395224737190702179" - "860943702770539217176293176752384674818467669405132000568127145263560" - "827785771342757789609173637178721468440901224953430146549585371050792" - "279689258923542019956112129021960864034418159813629774771309960518707" - "211349999998372978049951059731732816096318595024459455346908302642522" - "308253344685035261931188171010003137838752886587533208381420617177669" - "147303598253490428755468731159562863882353787593751957781857780532171" - "2268066130019278766111959092164201989" -) -assert len(PI_DECIMAL_DIGITS_1000) == 1000 - - -def binary_split(a, b): - """ - Chudnovsky binary splitting. - Returns P, Q, T for the range [a, b). - """ - - if b - a == 1: - if a == 0: - return ( - gmpy2.mpz(1), - gmpy2.mpz(1), - gmpy2.mpz(A), - ) - - k = gmpy2.mpz(a) - - P = ( - (6 * k - 5) - * (2 * k - 1) - * (6 * k - 1) - ) - - Q = k**3 * C3_OVER_24 - - T = P * (A + B * k) - - if a & 1: - T = -T - - return P, Q, T - - m = (a + b) // 2 - - P1, Q1, T1 = binary_split(a, m) - P2, Q2, T2 = binary_split(m, b) - - P = P1 * P2 - Q = Q1 * Q2 - T = T1 * Q2 + P1 * T2 - - return P, Q, T - - -def calculate_pi(digits): - """Calculate `digits` decimal digits of pi. - - Returns (pi_string, elapsed_seconds). pi_string has the form - ".". - """ - - start = time.perf_counter() - - # Chudnovsky yields roughly 14 digits per term. - terms = digits // 14 + 1 - - P, Q, T = binary_split(0, terms) - - # Scale factor: - # pi = 426880 * sqrt(10005) * Q / T - # Use GMP integer arithmetic instead of Decimal. Compute with `digits + 20` - # guard digits so rounding/floor error is confined to the discarded tail. - scale = gmpy2.mpz(10) ** (digits + 20) - - sqrt_10005 = gmpy2.isqrt( - gmpy2.mpz(10005) * scale * scale - ) - - numerator = ( - gmpy2.mpz(426880) - * sqrt_10005 - * Q - ) - - pi_scaled = numerator // T - - # Convert scaled integer into decimal representation. - # pi_scaled == floor(pi * 10**(digits + 20)), so its digits are: - # "3" + (digits + 20) fractional digits - s = str(pi_scaled) - - # Discard the 20 guard digits from the fractional (right) end. - guard = 20 - if len(s) > guard: - s = s[:-guard] - - # s should now be exactly "3" + `digits` fractional digits - # (length == digits + 1). Pad the fractional side with trailing zeros if - # we came up short; never left-pad, which would corrupt the integer part. - if len(s) < digits + 1: - s = s.ljust(digits + 1, "0") - elif len(s) > digits + 1: - s = s[: digits + 1] - - integer_part = s[0] - decimal_part = s[1:] - - pi_string = integer_part + "." + decimal_part - - elapsed = time.perf_counter() - start - - return pi_string, elapsed - - -def verify_pi(pi_string, digits): - """ - Sanity-check a calculated pi string. - - Returns True only when: - * the value is structurally sound ("3."), - * every position for which we have authoritative reference data matches - the known digits of pi. - - This never reports VERIFIED based on an insufficient prefix: for - ``digits <= 1000`` the entire result is compared against known pi digits. - For ``digits > 1000`` the first 1,000 digits are checked authoritatively - and the remaining digits are checked for structure only; use verify.py for - a full reference comparison at scale. - """ - - if not isinstance(pi_string, str) or "." not in pi_string: - return False - - integer_part, _, decimal_part = pi_string.partition(".") - - if integer_part != "3": - return False - - if len(decimal_part) != digits: - return False - - if not decimal_part.isdigit(): - return False - - # Authoritative check over the range we have reference data for. - check_len = min(digits, len(PI_DECIMAL_DIGITS_1000)) - if decimal_part[:check_len] != PI_DECIMAL_DIGITS_1000[:check_len]: - return False - - return True - - -def save_pi(pi_string, digits, filename=None): - output = Path(filename) if filename else Path(f"pi_{digits}.txt") - - print(f"Saving: {output}") - - with output.open( - "w", - encoding="ascii", - buffering=1024 * 1024, - ) as f: - f.write(pi_string) - - return output - - -def parse_args(argv=None): - parser = argparse.ArgumentParser( - description="Calculate pi using the Chudnovsky algorithm + binary splitting." - ) - parser.add_argument( - "--digits", - type=int, - help="number of decimal digits of pi to calculate", - ) - parser.add_argument( - "--output", - help="output file (default: pi_.txt)", - ) - return parser.parse_args(argv) - - -def main(argv=None): - args = parse_args(argv) - - digits = args.digits - if digits is None: - try: - digits = int( - input("\nHow many digits of pi would you like to calculate? ") - ) - except ValueError: - print("\nInput must be a number.") - return 1 - except EOFError: - print("\nInput stream closed.") - return 1 - - if digits <= 0: - print("Number of digits must be greater than 0.") - return 1 - - if digits > 10_000_000: - print( - "Warning: more than 10 million digits " - "may require large RAM." - ) - - try: - confirm = input("Continue? (y/n): ").strip().lower() - except EOFError: - print("Cancelled.") - return 1 - - if confirm != "y": - print("Cancelled.") - return 1 - - print("\nCalculating pi...") - print("Method: Chudnovsky + Binary Splitting + GMP") - - try: - pi, elapsed = calculate_pi(digits) - except MemoryError: - print("\nNot enough RAM.") - return 1 - except Exception as e: - print("\nCalculation error:") - print(type(e).__name__, e) - return 1 - - print("Calculation complete.") - - # -------------------------------------------------------- - # Verification - # -------------------------------------------------------- - - print("Verifying...") - - if not verify_pi(pi, digits): - print("Verification FAILED!") - return 1 - - # -------------------------------------------------------- - # Save - # -------------------------------------------------------- - - try: - filename = save_pi(pi, digits, filename=args.output) - except OSError as e: - print("Failed to save file:") - print(e) - return 1 - - # -------------------------------------------------------- - # Statistics - # -------------------------------------------------------- - - total_digits = len(pi.replace(".", "")) - decimal_digits = len(pi.split(".")[1]) - - speed = decimal_digits / elapsed - - # -------------------------------------------------------- - # Result - # -------------------------------------------------------- - - print() - print("=" * 60) - print("RESULT") - print("=" * 60) - - print(f"Digits requested : {digits:,}") - print(f"Total digits : {total_digits:,}") - print(f"Decimal digits : {decimal_digits:,}") - print() - print(f"Time : {elapsed:.4f} seconds") - print(f"Speed : {speed:,.2f} digits/sec") - print() - print(f"Saved : {filename}") - - print("=" * 60) - - print("\npi preview:") - print(pi[:120] + "...") - - print("\n" + "=" * 60) - print("VERIFIED!") - print("=" * 60) - - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/pi_v3.py b/pi_v3.py deleted file mode 100644 index 811544c..0000000 --- a/pi_v3.py +++ /dev/null @@ -1,289 +0,0 @@ -from decimal import Decimal, getcontext -import time - - -# ============================================================ -# PiProject v3 -# Chudnovsky Formula + Binary Splitting -# ============================================================ - - -def binary_split(a, b): - """ - Binary splitting untuk Chudnovsky. - - Menghasilkan P, Q, T untuk range [a, b). - """ - - if b - a == 1: - - if a == 0: - P = 1 - Q = 1 - T = 13591409 - - else: - P = ( - (6 * a - 5) - * (2 * a - 1) - * (6 * a - 1) - ) - - # Chudnovsky: - # Q = a^3 * 640320^3 / 24 - Q = ( - a ** 3 - * 640320 ** 3 - // 24 - ) - - T = P * ( - 13591409 - + 545140134 * a - ) - - # (-1)^a - if a % 2: - T = -T - - return P, Q, T - - m = (a + b) // 2 - - P1, Q1, T1 = binary_split(a, m) - P2, Q2, T2 = binary_split(m, b) - - P = P1 * P2 - Q = Q1 * Q2 - - T = ( - T1 * Q2 - + P1 * T2 - ) - - return P, Q, T - - -# ============================================================ -# Calculate Pi -# ============================================================ - -def calculate_pi(digits): - - # Chudnovsky menghasilkan ±14 digit per term - terms = digits // 14 + 1 - - # Extra precision - getcontext().prec = digits + 30 - - start = time.perf_counter() - - print(f"\nTerms required : {terms:,}") - print("Running binary splitting...") - - P, Q, T = binary_split(0, terms) - - print("Calculating square root...") - - C = ( - Decimal(426880) - * Decimal(10005).sqrt() - ) - - pi = ( - C - * Decimal(Q) - / Decimal(T) - ) - - elapsed = time.perf_counter() - start - - # Format tepat sejumlah digit setelah decimal - pi_string = format( - pi, - f".{digits}f" - ) - - return pi_string, elapsed - - -# ============================================================ -# Main -# ============================================================ - -def main(): - - print("=" * 55) - print(" PiProject v3") - print(" Chudnovsky + Binary Splitting") - print("=" * 55) - - try: - - digits = int( - input( - "\nBerapa digit π yang ingin dihitung? " - ) - ) - - except ValueError: - - print("\n❌ Input harus berupa angka.") - return - - if digits <= 0: - - print( - "\n❌ Jumlah digit harus lebih dari 0." - ) - return - - if digits > 10_000_000: - - print( - "\n⚠️ Target di atas 10 juta digit " - "bisa membutuhkan RAM sangat besar." - ) - - confirm = input( - "Tetap lanjut? (y/n): " - ).lower() - - if confirm != "y": - - print("Dibatalkan.") - return - - print("\nCalculating π...") - print( - "Method: Chudnovsky + Binary Splitting" - ) - - try: - - pi, elapsed = calculate_pi( - digits - ) - - except MemoryError: - - print( - "\n❌ RAM tidak cukup." - ) - return - - except Exception as e: - - print( - "\n❌ Calculation error:" - ) - print(e) - return - - # ======================================================== - # Save - # ======================================================== - - filename = f"pi_{digits}.txt" - - try: - - with open( - filename, - "w", - encoding="utf-8" - ) as f: - - f.write(pi) - - except OSError as e: - - print( - "\n❌ Gagal menyimpan file:" - ) - print(e) - return - - # ======================================================== - # Benchmark - # ======================================================== - - total_digits = len( - pi.replace(".", "") - ) - - decimal_digits = len( - pi.split(".")[1] - ) - - speed = ( - decimal_digits - / elapsed - ) - - # ======================================================== - # Result - # ======================================================== - - print("\n") - print("=" * 55) - print(" RESULT") - print("=" * 55) - - print( - f"Digits requested : {digits:,}" - ) - - print( - f"Total digits : {total_digits:,}" - ) - - print( - f"Decimal digits : {decimal_digits:,}" - ) - - print( - f"\nTime : " - f"{elapsed:.4f} seconds" - ) - - print( - f"Speed : " - f"{speed:,.2f} digits/sec" - ) - - print( - f"\nSaved : " - f"{filename}" - ) - - print("=" * 55) - - # ======================================================== - # Preview - # ======================================================== - - print("\nπ preview:") - - if len(pi) > 120: - - print( - pi[:120] - + "..." - ) - - else: - - print(pi) - - print( - "\n✅ Calculation complete." - ) - - -# ============================================================ -# Start -# ============================================================ - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/pie.py b/pie.py deleted file mode 100644 index 7c7334d..0000000 --- a/pie.py +++ /dev/null @@ -1,113 +0,0 @@ -from decimal import Decimal, getcontext -import time -import sys - - -# ========================= -# PiProject v1 (legacy) -# Arctan (Machin-like) formula -# ========================= - -# Legacy implementation: simple, dependency-free, but O(digits^2). -# Recommended only for small digit counts. Use pi_project_v4.py for -# large calculations (Chudnovsky + binary splitting + GMPY2). - - -def calculate_pi(digits): - # Extra precision to avoid error in the last digits. - getcontext().prec = digits + 20 - - start = time.perf_counter() - - def arctan_inverse(n): - x = Decimal(1) / Decimal(n) - x_squared = x * x - - total = Decimal(0) - power = x - k = 0 - - while True: - term = power / (2 * k + 1) - - if term < Decimal(10) ** -(digits + 15): - break - - if k % 2 == 0: - total += term - else: - total -= term - - power *= x_squared - k += 1 - - return total - - pi = ( - Decimal(16) * arctan_inverse(5) - - Decimal(4) * arctan_inverse(239) - ) - - elapsed = time.perf_counter() - start - - # Exactly the requested number of digits. - pi = format(pi, f".{digits}f") - - return pi, elapsed - - -def main(argv=None): - - print("=== PiProject ===") - print("Real π Calculator\n") - - try: - digits = int(input("How many digits of pi? ")) - - if digits <= 0: - raise ValueError("Number of digits must be greater than 0.") - - except ValueError: - print("Invalid input.") - return 1 - except EOFError: - print("Input stream closed.") - return 1 - - print("\nCalculating...") - print("Please wait...\n") - - pi, elapsed = calculate_pi(digits) - - # ========================= - # Save result - # ========================= - - filename = f"pi_{digits}.txt" - - with open(filename, "w", encoding="utf-8") as f: - f.write(pi) - - # ========================= - # Result - # ========================= - - print("π =") - print(pi) - - print("\n=========================") - print(f"Time : {elapsed:.4f} seconds") - print(f"Digits: {digits:,}") - print(f"Speed : {digits / elapsed:,.0f} digits/sec") - print(f"Saved : {filename}") - print("=========================") - - return 0 - - -# ========================= -# Start -# ========================= - -if __name__ == "__main__": - sys.exit(main()) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..56a418b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,36 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "piproject" +version = "2.0.0" +description = "High-performance π computation and independent verification" +readme = "README.md" +requires-python = ">=3.9" +license = {text = "Proprietary (pending license decision)"} +authors = [{name = "zomop"}] +keywords = ["pi", "chudnovsky", "binary-splitting", "gmpy2", "arbitrary-precision"] + +dependencies = [ + "gmpy2>=2.1.0", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.0.0", + "pytest-cov>=4.0.0", +] + +[project.scripts] +piproject = "piproject.cli:main" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-v --tb=short" +markers = [ + "slow: marks tests as slow (large digit counts)", +] diff --git a/requirements-dev.txt b/requirements-dev.txt index e144ed0..3cee130 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1 +1,2 @@ pytest>=8.0.0 +pytest-cov>=4.0.0 diff --git a/requirements.txt b/requirements.txt index 9d42b33..2e87b1d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1 @@ -gmpy2==2.3.2 +gmpy2>=2.1.0 diff --git a/src/piproject/__init__.py b/src/piproject/__init__.py new file mode 100644 index 0000000..05870a2 --- /dev/null +++ b/src/piproject/__init__.py @@ -0,0 +1,33 @@ +"""PiProject — High-performance π computation and independent verification. + +PiProject computes π to millions of digits using the Chudnovsky algorithm +with binary splitting and GMPY2 arbitrary-precision arithmetic, and verifies +results through an independent verification engine. + +Project: https://github.com/zomop/PiProject +""" + +__version__ = "2.0.0" +__project__ = "PiProject" + +# --------------------------------------------------------------------------- +# Verification statuses (explicit, never ambiguous) +# --------------------------------------------------------------------------- + +CALCULATED = "CALCULATED" +STRUCTURE_VALID = "STRUCTURE_VALID" +PREFIX_VERIFIED = "PREFIX_VERIFIED" +FULLY_VERIFIED = "FULLY_VERIFIED" +INDEPENDENTLY_VERIFIED = "INDEPENDENTLY_VERIFIED" +VERIFICATION_FAILED = "VERIFICATION_FAILED" + +__all__ = [ + "__version__", + "__project__", + "CALCULATED", + "STRUCTURE_VALID", + "PREFIX_VERIFIED", + "FULLY_VERIFIED", + "INDEPENDENTLY_VERIFIED", + "VERIFICATION_FAILED", +] diff --git a/src/piproject/bbp.py b/src/piproject/bbp.py new file mode 100644 index 0000000..f5cca1a --- /dev/null +++ b/src/piproject/bbp.py @@ -0,0 +1,244 @@ +"""BBP (Bailey–Borwein–Plouffe) hexadecimal digit extraction. + +Algorithmically independent of the Chudnovsky/binary-splitting computation +engine. The BBP formula computes hexadecimal digits of pi at arbitrary +positions without computing preceding digits: + + pi = sum_{k=0}^{inf} 1/16^k * (4/(8k+1) - 2/(8k+4) - 1/(8k+5) - 1/(8k+6)) + +This module is used for *spot checks* — verifying individual hexadecimal +positions — not for full digit-range verification. + +It also provides decimal-to-hexadecimal conversion so that BBP spot checks can +be validated *against* a calculated decimal output, establishing a real +relationship between the two representations rather than comparing BBP against +a hardcoded string alone. +""" + +from __future__ import annotations + +import sys +from typing import Tuple + +# Known hexadecimal digits of pi (after the point), from published sources. +# pi = 3.243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89... +KNOWN_HEX = ( + "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89" + "452821e638d01377be5466cf34e90c6cc0ac29b7c97c50dd3f84d5b5b5470917" +) + +# log10(16) ≈ 1.20412 — decimal digits needed per hex digit position. +_DECIMALS_PER_HEX_POSITION = 1.21 + + +def _ensure_int_str_digits(needed: int) -> None: + """Raise if Python's int<->str digit limit is too low for `needed` digits.""" + limit = sys.get_int_max_str_digits() + if needed > limit: + raise ValueError( + f"Need {needed:,} digits but int<->str limit is {limit:,}. " + "Call sys.set_int_max_str_digits() with a higher value first." + ) + + +def decimal_to_hex_at( + decimal_digits: str, + position: int, + num_digits: int = 1, +) -> str: + """Convert decimal digits of pi to hexadecimal digits at a given position. + + Given `decimal_digits` (the fractional digits of pi as a string), returns + `num_digits` hexadecimal digits starting at 1-indexed `position` after the + hexadecimal point. + + Mathematically: if `value = floor(pi * 10^D)` where D = len(decimal_digits), + then the hex digits at positions `position`..`position+num_digits-1` are + approximately `floor(16^(position+num_digits-1) * value / 10^D) mod 16^num_digits`. + + This is accurate only when D > position * log10(16) ≈ position * 1.204, + i.e. when enough decimal digits are available to resolve the requested hex + position. A ValueError is raised if the precision is insufficient. + + Parameters + ---------- + decimal_digits: + Fractional decimal digits of pi (no "3.", no decimal point). + position: + 1-indexed hexadecimal position after the point. Position 1 is the + first hex digit after the point. + num_digits: + Number of hex digits to extract. + + Returns + ------- + A lowercase hexadecimal string of length `num_digits`. + + Raises + ------ + ValueError + If the input is invalid or the decimal precision is insufficient for + the requested position. + """ + + if not decimal_digits or not decimal_digits.isdigit(): + raise ValueError("decimal_digits must be a non-empty string of digits") + + if position < 1: + raise ValueError("position must be >= 1") + + if num_digits < 1: + raise ValueError("num_digits must be >= 1") + + num_decimals = len(decimal_digits) + + # Precision requirement: D > position * log10(16) to resolve position. + needed_decimals = int(position * _DECIMALS_PER_HEX_POSITION) + num_digits + 2 + if num_decimals < needed_decimals: + raise ValueError( + f"Insufficient decimal precision: need > {needed_decimals:,} " + f"decimal digits to resolve hex position {position}, " + f"but only {num_decimals:,} available." + ) + + _ensure_int_str_digits(num_decimals + 4 * (position + num_digits - 1)) + + # value = floor(pi * 10^num_decimals) = int("3" + decimal_digits) + value = int("3" + decimal_digits) + pow10 = 10 ** num_decimals + + # floor(16^(position+num_digits-1) * value / 10^num_decimals) + # gives hex digits covering positions 1..position+num_digits-1. + scaled = value << (4 * (position + num_digits - 1)) # * 16^(position+num_digits-1) + combined = scaled // pow10 + + # Extract just the requested window: positions position..position+num_digits-1 + window = combined % (16 ** num_digits) + return format(window, f"0{num_digits}x") + + +def bbp_vs_decimal( + decimal_digits: str, + positions: list[int], + num_digits: int = 5, +) -> dict[int, Tuple[str, str, bool]]: + """Compare BBP hex digits against decimal-to-hex conversion. + + This establishes a real relationship between a calculated decimal output + and independent BBP computation: if the decimal digits are correct, their + hexadecimal conversion must match BBP at the same positions. + + Returns a dict mapping position -> (bbp, decimal_hex, match). + """ + results: dict[int, Tuple[str, str, bool]] = {} + for pos in positions: + bbp = bbp_hex_digits(pos, num_digits) + try: + dec_hex = decimal_to_hex_at(decimal_digits, pos, num_digits) + except ValueError as exc: + dec_hex = f"ERROR: {exc}" + match = bbp == dec_hex if not dec_hex.startswith("ERROR") else False + results[pos] = (bbp, dec_hex, match) + return results + + +def mod_pow16(exp: int, mod: int) -> int: + """Return 16^exp mod mod using modular exponentiation.""" + return pow(16, exp, mod) + + +def bbp_sum(n: int, j: int) -> float: + """Compute the j-th component of the BBP sum modulo 1. + + S_j = sum_{k=0}^{inf} 16^(n-k) / (8k+j) (mod 1) + + Split at k = n: for k <= n, 16^(n-k) is an integer; for k > n it is + fractional. Modular exponentiation keeps the integer part bounded. + """ + + # Part 1: k = 0 to n + s = 0.0 + for k in range(0, n + 1): + denom = 8 * k + j + pow16 = mod_pow16(n - k, denom) + s += pow16 / denom + s -= int(s) # keep only the fractional part + + # Part 2: k = n+1 to infinity (terms become negligible quickly) + k = n + 1 + while True: + shift = k - n + denom = 8 * k + j + term = 1.0 / (denom * (16 ** shift)) + s += term + s -= int(s) + if term < 1e-17: + break + k += 1 + if k - n > 10_000: # safety bound + break + + return s % 1.0 + + +def bbp_hex_digits(position: int, num_digits: int = 5) -> str: + """Return `num_digits` hexadecimal digits of pi starting at `position`. + + Parameters + ---------- + position: + 1-indexed position after the hexadecimal point. Position 1 returns + the first hex digit after the point. + num_digits: + Number of hex digits to extract. + + Returns + ------- + A lowercase hexadecimal string of length `num_digits`. + """ + + n = position - 1 + # pi = 4*S1 - 2*S4 - S5 - S6 + s = ( + 4 * bbp_sum(n, 1) + - 2 * bbp_sum(n, 4) + - bbp_sum(n, 5) + - bbp_sum(n, 6) + ) % 1.0 + if s < 0: + s += 1.0 + if s >= 1.0: + s -= 1.0 + + hex_digits = "" + x = s + for _ in range(num_digits): + x *= 16 + digit = int(x) + hex_digits += "0123456789abcdef"[digit] + x -= digit + + return hex_digits + + +def check_position(position: int, num_digits: int = 5) -> Tuple[str, str, bool]: + """Check a BBP position against the published reference. + + Returns (bbp_result, reference, match). + """ + + bbp = bbp_hex_digits(position, num_digits) + ref = KNOWN_HEX[position - 1 : position - 1 + num_digits] + match = bbp == ref + return bbp, ref, match + + +def spot_check_positions(positions: list[int]) -> dict[int, Tuple[str, str, bool]]: + """Run BBP spot checks at multiple positions. + + Returns a dict mapping position -> (bbp, reference, match). + """ + results: dict[int, Tuple[str, str, bool]] = {} + for pos in positions: + results[pos] = check_position(pos) + return results diff --git a/src/piproject/cli.py b/src/piproject/cli.py new file mode 100644 index 0000000..72ba0f0 --- /dev/null +++ b/src/piproject/cli.py @@ -0,0 +1,423 @@ +"""Professional command-line interface for PiProject. + +Usage: + + piproject calculate --digits 1000000 --output pi_1000000.txt + piproject verify --input pi.txt --reference reference.txt + piproject benchmark --digits 1000000 + piproject inspect --input pi.txt + piproject hash --input pi.txt +""" + +from __future__ import annotations + +import argparse +import sys +import time +from pathlib import Path +from typing import List, Optional + +from piproject import ( + CALCULATED, + FULLY_VERIFIED, + INDEPENDENTLY_VERIFIED, + PREFIX_VERIFIED, + STRUCTURE_VALID, + VERIFICATION_FAILED, + __version__, +) +from piproject.bbp import spot_check_positions +from piproject.compute import GUARD_DIGITS, calculate_pi, calculate_pi_to_file +from piproject.verify import ( + VerificationReport, + sha256_file, + verify_files, + verify_pi, + verify_pi_file, +) + + +# ============================================================================ +# Helpers +# ============================================================================ + +def _format_time(seconds: float) -> str: + if seconds < 1: + return f"{seconds * 1000:.1f} ms" + if seconds < 60: + return f"{seconds:.3f} s" + m = int(seconds // 60) + s = seconds % 60 + return f"{m}m {s:.1f}s" + + +def _format_size(n: int) -> str: + for unit in ("B", "KB", "MB", "GB", "TB"): + if n < 1024: + return f"{n:.1f} {unit}" + n /= 1024 + return f"{n:.1f} PB" + + +def _status_color(status: str) -> str: + """Return an ANSI-colored status string (no-op on non-TTY).""" + if not sys.stdout.isatty(): + return status + colors = { + VERIFICATION_FAILED: "\033[31m", # red + FULLY_VERIFIED: "\033[32m", # green + INDEPENDENTLY_VERIFIED: "\033[32m", # green + PREFIX_VERIFIED: "\033[33m", # yellow + STRUCTURE_VALID: "\033[36m", # cyan + CALCULATED: "\033[0m", # default + } + reset = "\033[0m" + return f"{colors.get(status, '')}{status}{reset}" + + +# ============================================================================ +# Commands +# ============================================================================ + +def cmd_calculate(args: argparse.Namespace) -> int: + digits = args.digits + output = Path(args.output) if args.output else None + + if digits <= 0: + print("Error: --digits must be greater than 0.", file=sys.stderr) + return 1 + + print(f"PiProject v{__version__}") + print(f"Calculating {digits:,} decimal digits of pi...") + print("Method: Chudnovsky + Binary Splitting + GMPY2") + + try: + if output: + pi_string, elapsed = calculate_pi_to_file( + digits, output=output + ) + else: + pi_string, elapsed = calculate_pi(digits) + except MemoryError: + print("Error: not enough memory.", file=sys.stderr) + return 1 + except Exception as exc: # noqa: BLE001 + print(f"Calculation error: {type(exc).__name__}: {exc}", file=sys.stderr) + return 1 + + decimal_part = pi_string.split(".")[1] + total_digits = len(pi_string.replace(".", "")) + + print(f"Calculation complete in {_format_time(elapsed)}.") + print(f"Total digits: {total_digits:,}") + print(f"Decimal digits: {len(decimal_part):,}") + print(f"Throughput: {len(decimal_part) / elapsed:,.0f} digits/sec") + print(f"SHA-256 (decimals): {__import__('hashlib').sha256(decimal_part.encode()).hexdigest()}") + + if output: + print(f"Saved to: {output} ({_format_size(output.stat().st_size)})") + + # Built-in prefix verification + from piproject.verify import verify_prefix_builtin, STRUCTURE_VALID + + status, checked = verify_prefix_builtin(pi_string, digits) + print(f"\nPrefix verification ({checked:,} digits checked): {_status_color(status)}") + + if status == VERIFICATION_FAILED: + print("Verification FAILED!", file=sys.stderr) + return 1 + + print(f"\nPi preview: {pi_string[:80]}...") + return 0 + + +def cmd_verify(args: argparse.Namespace) -> int: + input_path = Path(args.input) + reference_path = Path(args.reference) if args.reference else None + + if not input_path.exists(): + print(f"Error: input file not found: {input_path}", file=sys.stderr) + return 1 + + if reference_path and not reference_path.exists(): + print(f"Error: reference file not found: {reference_path}", file=sys.stderr) + return 1 + + print(f"PiProject v{__version__}") + print(f"Verifying: {input_path}") + if reference_path: + print(f"Reference: {reference_path}") + + # Read input and count digits + from piproject.verify import read_decimal_digits + + # Read decimal part. The file may contain "3.14159..." format where the + # leading "3" is the integer part. count_digits_in_file counts ALL + # normalized digits (including "3"), so fractional digits = total - 1. + try: + all_digits = read_decimal_digits(input_path) + except ValueError as exc: + print(f"Error: {exc}", file=sys.stderr) + return 1 + + # Strip the integer part "3" to get only fractional digits + if all_digits.startswith("3"): + decimal_digits = all_digits[1:] + else: + decimal_digits = all_digits + + digits = len(decimal_digits) + print(f"Digits in input: {digits:,}") + + pi_string = "3." + decimal_digits + + # BBP positions + bbp_positions = None + if args.bbp: + bbp_positions = [int(p) for p in args.bbp.split(",")] + + report = verify_pi( + pi_string, + digits, + reference_path=reference_path, + bbp_positions=bbp_positions, + ) + + print(f"\nVerification report:") + print(f" Status: {_status_color(report.status)}") + print(f" Method: {report.method}") + print(f" Digits requested: {report.digits_requested:,}") + print(f" Digits compared: {report.digits_compared:,}") + print(f" Digits matched: {report.digits_matched:,}") + print(f" Digits mismatched: {report.digits_mismatched:,}") + print(f" Verification time: {_format_time(report.verification_time)}") + if report.reference_source: + print(f" Reference: {report.reference_source}") + if report.reference_sha256: + print(f" Reference SHA-256: {report.reference_sha256}") + if report.calculated_sha256: + print(f" Calculated SHA-256: {report.calculated_sha256}") + if report.first_mismatch_position is not None: + print(f" First mismatch position: {report.first_mismatch_position:,}") + + if report.details.get("bbp_spot_checks"): + bbp = report.details["bbp_spot_checks"] + pure = bbp.get("pure_bbp_vs_reference", {}) + pure_details = pure.get("details", {}) + pure_results = pure_details.get("results", {}) + all_match_pure = all(r["match"] for r in pure_results.values()) if pure_results else False + print(f"\n BBP vs published reference: {'all match' if all_match_pure else 'MISMATCH'}") + for pos, r in pure_results.items(): + print(f" Position {pos}: BBP={r['bbp']} ref={r['reference']} match={r['match']}") + + dec_vs_bbp = bbp.get("bbp_vs_decimal", {}) + if dec_vs_bbp: + all_match_dec = all(r["match"] for r in dec_vs_bbp.values()) + print(f" BBP vs decimal-to-hex: {'all match' if all_match_dec else 'MISMATCH'}") + for pos, r in dec_vs_bbp.items(): + print(f" Position {pos}: BBP={r['bbp']} dec_hex={r['decimal_hex']} match={r['match']}") + + if report.is_fully_verified(): + print(f"\nResult: FULLY VERIFIED ✓") + return 0 + if report.status == VERIFICATION_FAILED: + print(f"\nResult: VERIFICATION FAILED ✗", file=sys.stderr) + return 1 + print(f"\nResult: {report.status} (not full verification)") + return 1 + + +def cmd_benchmark(args: argparse.Namespace) -> int: + digits = args.digits + repeats = args.repeats + + print(f"PiProject v{__version__}") + print(f"Benchmark: {digits:,} digits, {repeats} repeat(s)") + print("Method: Chudnovsky + Binary Splitting + GMPY2") + print() + + import platform + + print(f"Platform: {platform.platform()}") + print(f"Python: {platform.python_version()}") + import gmpy2 + print(f"GMPY2: {gmpy2.version()}") + print() + + times: List[float] = [] + for i in range(repeats): + print(f" Run {i + 1}/{repeats}...", end="", flush=True) + try: + _, elapsed = calculate_pi(digits) + except MemoryError: + print(" FAILED (out of memory)") + return 1 + times.append(elapsed) + print(f" {_format_time(elapsed)}") + + print() + print(f"Best: {_format_time(min(times))}") + print(f"Worst: {_format_time(max(times))}") + print(f"Average: {_format_time(sum(times) / len(times))}") + print(f"Throughput: {digits / min(times):,.0f} digits/sec (best)") + + # Save benchmark result + result = { + "digits": digits, + "repeats": repeats, + "times": times, + "best": min(times), + "worst": max(times), + "average": sum(times) / len(times), + "throughput_best": digits / min(times), + "platform": platform.platform(), + "python": platform.python_version(), + "gmpy2": gmpy2.version(), + } + + import json, datetime + result["timestamp"] = datetime.datetime.utcnow().isoformat() + "Z" + + bench_dir = Path("benchmarks") + bench_dir.mkdir(exist_ok=True) + out = bench_dir / f"benchmark_{digits}.json" + out.write_text(json.dumps(result, indent=2)) + print(f"\nBenchmark saved to: {out}") + + return 0 + + +def cmd_inspect(args: argparse.Namespace) -> int: + input_path = Path(args.input) + + if not input_path.exists(): + print(f"Error: input file not found: {input_path}", file=sys.stderr) + return 1 + + from piproject.verify import read_decimal_digits, verify_prefix_builtin + + # Read all normalized digits (includes integer part "3") + try: + all_digits = read_decimal_digits(input_path) + except ValueError as exc: + print(f"Error: {exc}", file=sys.stderr) + return 1 + + # Strip the integer part "3" to get only fractional digits + if all_digits.startswith("3"): + decimal_digits = all_digits[1:] + else: + decimal_digits = all_digits + + digits = len(decimal_digits) + total_digits = len(all_digits) # includes "3" + size = input_path.stat().st_size + + print(f"PiProject v{__version__}") + print(f"Inspecting: {input_path}") + print(f"File size: {size:,} bytes ({_format_size(size)})") + print(f"Total digits (incl. integer part): {total_digits:,}") + print(f"Fractional digits: {digits:,}") + + print(f"First 50 decimals: {decimal_digits[:50]}") + print(f"Last 50 decimals: {decimal_digits[-50:]}") + + import hashlib + print(f"SHA-256 (decimals): {hashlib.sha256(decimal_digits.encode()).hexdigest()}") + print(f"SHA-256 (file): {sha256_file(input_path)}") + + # Check against built-in prefix + pi_string = "3." + decimal_digits + status, checked = verify_prefix_builtin(pi_string, min(digits, 1000)) + print(f"\nBuilt-in prefix check ({checked:,} digits): {status}") + + return 0 + + +def cmd_hash(args: argparse.Namespace) -> int: + input_path = Path(args.input) + + if not input_path.exists(): + print(f"Error: input file not found: {input_path}", file=sys.stderr) + return 1 + + print(f"File: {input_path}") + print(f"SHA-256: {sha256_file(input_path)}") + + # Also hash just the decimal digits + from piproject.verify import count_digits_in_file, read_decimal_digits + + digits = count_digits_in_file(input_path) + decimal_digits = read_decimal_digits(input_path) + import hashlib + print(f"SHA-256 (decimals only): {hashlib.sha256(decimal_digits.encode()).hexdigest()}") + print(f"Digits: {digits:,}") + + return 0 + + +# ============================================================================ +# Argument parser +# ============================================================================ + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="piproject", + description="PiProject — High-performance π computation and verification.", + ) + parser.add_argument( + "--version", + action="version", + version=f"PiProject v{__version__}", + ) + + sub = parser.add_subparsers(dest="command", help="Available commands") + + # calculate + p_calc = sub.add_parser("calculate", help="Calculate pi digits") + p_calc.add_argument("--digits", type=int, required=True, help="Number of decimal digits") + p_calc.add_argument("--output", help="Output file (default: pi_.txt)") + p_calc.set_defaults(func=cmd_calculate) + + # verify + p_ver = sub.add_parser("verify", help="Verify pi against a reference") + p_ver.add_argument("--input", required=True, help="Calculated pi file") + p_ver.add_argument("--reference", help="Reference file for full comparison") + p_ver.add_argument( + "--bbp", + help="BBP spot-check positions (comma-separated, e.g. 1,10,100)", + ) + p_ver.set_defaults(func=cmd_verify) + + # benchmark + p_bench = sub.add_parser("benchmark", help="Benchmark calculation speed") + p_bench.add_argument("--digits", type=int, default=100000, help="Digits to compute") + p_bench.add_argument("--repeats", type=int, default=3, help="Number of runs") + p_bench.set_defaults(func=cmd_benchmark) + + # inspect + p_inspect = sub.add_parser("inspect", help="Inspect a pi file") + p_inspect.add_argument("--input", required=True, help="Pi file to inspect") + p_inspect.set_defaults(func=cmd_inspect) + + # hash + p_hash = sub.add_parser("hash", help="Compute SHA-256 of a pi file") + p_hash.add_argument("--input", required=True, help="File to hash") + p_hash.set_defaults(func=cmd_hash) + + return parser + + +def main(argv: Optional[List[str]] = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + + if not args.command: + parser.print_help() + return 1 + + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/piproject/compute.py b/src/piproject/compute.py new file mode 100644 index 0000000..311c241 --- /dev/null +++ b/src/piproject/compute.py @@ -0,0 +1,267 @@ +"""Computation engine for PiProject. + +Implements the Chudnovsky algorithm with binary splitting using GMPY2 +arbitrary-precision integer arithmetic. This is the primary calculation +engine; it is independent of the verification engine in ``verify.py``. +""" + +from __future__ import annotations + +import sys +import time +from pathlib import Path +from typing import Optional, Tuple + +import gmpy2 + +from piproject import ( + FULLY_VERIFIED, + PREFIX_VERIFIED, + VERIFICATION_FAILED, +) + +# ============================================================================ +# Chudnovsky constants +# ============================================================================ + +# Chudnovsky algorithm: +# 1/pi = 12 * sum_{k=0}^{inf} (-1)^k * (6k)! * (545140134*k + 13591409) / +# ((3k)! * (k!)^3 * (640320)^(3k + 3/2)) +# Equivalently: +# pi = 426880 * sqrt(10005) * Q / T +# where P, Q, T come from binary splitting over the series term ratio. + +C = 640320 +C3_OVER_24 = C**3 // 24 +A = 13591409 +B = 545140134 + +# Each Chudnovsky term yields roughly 14.18 decimal digits. +DIGITS_PER_TERM = 14 + +# Guard digits appended during computation to absorb floor/truncation error. +GUARD_DIGITS = 20 + +# First 1,000 decimal digits of pi (after the decimal point), computed with +# an independent decimal/Machin implementation and cross-checked against +# https://www.piday.org/million/. Used for prefix verification. +PI_DECIMAL_DIGITS_1000 = ( + "14159265358979323846264338327950288419716939937510582097494459230781" + "64062862089986280348253421170679821480865132823066470938446095505822" + "31725359408128481117450284102701938521105559644622948954930381964428" + "810975665933446128475648233786783165271201909145648566923460348610454" + "326648213393607260249141273724587006606315588174881520920962829254091" + "715364367892590360011330530548820466521384146951941511609433057270365" + "759591953092186117381932611793105118548074462379962749567351885752724" + "891227938183011949129833673362440656643086021394946395224737190702179" + "860943702770539217176293176752384674818467669405132000568127145263560" + "827785771342757789609173637178721468440901224953430146549585371050792" + "279689258923542019956112129021960864034418159813629774771309960518707" + "211349999998372978049951059731732816096318595024459455346908302642522" + "308253344685035261931188171010003137838752886587533208381420617177669" + "147303598253490428755468731159562863882353787593751957781857780532171" + "2268066130019278766111959092164201989" +) + +assert len(PI_DECIMAL_DIGITS_1000) == 1000 + + +# ============================================================================ +# Binary splitting +# ============================================================================ + +def binary_split(a: int, b: int) -> Tuple[gmpy2.mpz, gmpy2.mpz, gmpy2.mpz]: + """Chudnovsky binary splitting over the range [a, b). + + Returns the triplet (P, Q, T) such that: + + P = product of p_k + Q = product of q_k + T = sum of t_k * (product of p after k) + + where p_k, q_k, t_k are the Chudnovsky term components. + """ + + if b - a == 1: + if a == 0: + return ( + gmpy2.mpz(1), + gmpy2.mpz(1), + gmpy2.mpz(A), + ) + + k = gmpy2.mpz(a) + + P = (6 * k - 5) * (2 * k - 1) * (6 * k - 1) + Q = k**3 * C3_OVER_24 + T = P * (A + B * k) + + if a & 1: + T = -T + + return P, Q, T + + m = (a + b) // 2 + + P1, Q1, T1 = binary_split(a, m) + P2, Q2, T2 = binary_split(m, b) + + P = P1 * P2 + Q = Q1 * Q2 + T = T1 * Q2 + P1 * T2 + + return P, Q, T + + +# ============================================================================ +# Main computation +# ============================================================================ + +def calculate_pi( + digits: int, + *, + guard_digits: int = GUARD_DIGITS, +) -> Tuple[str, float]: + """Calculate `digits` decimal digits of pi. + + Uses the Chudnovsky algorithm with binary splitting and GMPY2 integer + arithmetic. The result is truncated (not rounded) to exactly `digits` + fractional digits. + + Parameters + ---------- + digits: + Number of decimal digits of pi to compute (after the decimal point). + Must be greater than 0. + guard_digits: + Number of guard digits used internally to absorb truncation error. + + Returns + ------- + (pi_string, elapsed_seconds) + pi_string has the form ".", e.g. "3.14159...". + """ + + if digits <= 0: + raise ValueError("digits must be greater than 0") + + start = time.perf_counter() + + # Number of terms needed: each term yields ~14.18 digits. + terms = digits // DIGITS_PER_TERM + 1 + + P, Q, T = binary_split(0, terms) + + # Scale factor: pi = 426880 * sqrt(10005) * Q / T + # Compute with guard digits so truncation error is confined to the + # discarded tail. + scale = gmpy2.mpz(10) ** (digits + guard_digits) + + sqrt_10005 = gmpy2.isqrt(gmpy2.mpz(10005) * scale * scale) + + numerator = gmpy2.mpz(426880) * sqrt_10005 * Q + + pi_scaled = numerator // T # floor(pi * 10^(digits + guard_digits)) + + # Convert scaled integer to decimal string. + s = str(pi_scaled) + + # Discard guard digits from the fractional (right) end. + if len(s) > guard_digits: + s = s[:-guard_digits] + + # s should now be exactly "3" + `digits` fractional digits + # (length == digits + 1). Pad the fractional side with trailing zeros if + # we came up short; never left-pad, which would corrupt the integer part. + if len(s) < digits + 1: + s = s.ljust(digits + 1, "0") + elif len(s) > digits + 1: + s = s[: digits + 1] + + integer_part = s[0] + decimal_part = s[1:] + + pi_string = integer_part + "." + decimal_part + + elapsed = time.perf_counter() - start + + return pi_string, elapsed + + +def calculate_pi_to_file( + digits: int, + output: Optional[Path] = None, + *, + chunk_size: int = 1024 * 1024, + guard_digits: int = GUARD_DIGITS, +) -> Tuple[str, float]: + """Calculate pi and write the result to an output file. + + This computes the full result in memory (via :func:`calculate_pi`) and + then writes it to disk in chunks. Because the Chudnovsky/binary-splitting + engine produces the result as a single large integer at the end of the + computation, true digit-by-digit streaming *during* computation is not + feasible with this algorithm. The chunked write avoids holding a second + copy of the full string in memory beyond what the computation already + produces — it is memory-efficient I/O, not true streaming. + + For genuine streaming output (digits produced one at a time), a different + algorithm such as a spigot algorithm or BBP-based extraction would be + required. + + Returns (pi_string, elapsed_seconds). + """ + + pi_string, elapsed = calculate_pi(digits, guard_digits=guard_digits) + + if output is None: + output = Path(f"pi_{digits}.txt") + + with output.open("w", encoding="ascii", buffering=chunk_size) as f: + f.write(pi_string) + + return pi_string, elapsed + + +# Keep the old name as a deprecated alias for backward compatibility. +calculate_pi_streaming = calculate_pi_to_file + + +# ============================================================================ +# Prefix verification (built into the computation engine for fast feedback) +# ============================================================================ + +def verify_prefix(pi_string: str, digits: int) -> Tuple[str, int]: + """Verify a pi string against the known first 1,000 decimal digits. + + This is a *prefix check only*. For ``digits > 1000`` it does not + constitute full verification; use the independent verification engine + in :mod:`piproject.verify` for that. + + Returns (status, checked_count) where status is one of the module-level + status constants. + """ + + if not isinstance(pi_string, str) or "." not in pi_string: + return VERIFICATION_FAILED, 0 + + integer_part, _, decimal_part = pi_string.partition(".") + + if integer_part != "3": + return VERIFICATION_FAILED, 0 + + if len(decimal_part) != digits: + return VERIFICATION_FAILED, 0 + + if not decimal_part.isdigit(): + return VERIFICATION_FAILED, 0 + + check_len = min(digits, len(PI_DECIMAL_DIGITS_1000)) + if decimal_part[:check_len] != PI_DECIMAL_DIGITS_1000[:check_len]: + return VERIFICATION_FAILED, 0 + + if digits <= len(PI_DECIMAL_DIGITS_1000): + return FULLY_VERIFIED, digits + + return PREFIX_VERIFIED, check_len diff --git a/src/piproject/verify.py b/src/piproject/verify.py new file mode 100644 index 0000000..434f80c --- /dev/null +++ b/src/piproject/verify.py @@ -0,0 +1,647 @@ +"""Independent verification engine for PiProject. + +This module is *independent* of the computation engine in ``compute.py``. +It verifies pi digit strings against trusted references using multiple +methods and reports explicit verification statuses: + + CALCULATED - value was computed, no verification performed + STRUCTURE_VALID - passes structural checks (format, length, digits) + PREFIX_VERIFIED - matches known reference for the checked prefix only + FULLY_VERIFIED - every digit compared against a trustworthy reference + INDEPENDENTLY_VERIFIED - confirmed by an independent algorithm (e.g. BBP) + VERIFICATION_FAILED - a mismatch or error was detected + +Never report FULLY_VERIFIED when only a prefix has been checked. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +# Reuse statuses from the package __init__ +from piproject import ( + CALCULATED, + FULLY_VERIFIED, + INDEPENDENTLY_VERIFIED, + PREFIX_VERIFIED, + STRUCTURE_VALID, + VERIFICATION_FAILED, +) + +CHUNK_SIZE = 1024 * 1024 # 1 MB + + +@dataclass +class VerificationReport: + """A complete, reproducible verification report.""" + + status: str = CALCULATED + digits_requested: int = 0 + digits_compared: int = 0 + digits_matched: int = 0 + digits_mismatched: int = 0 + first_mismatch_position: Optional[int] = None + reference_source: Optional[str] = None + reference_sha256: Optional[str] = None + calculated_sha256: Optional[str] = None + verification_time: float = 0.0 + method: str = "" + details: Dict[str, object] = field(default_factory=dict) + + def to_dict(self) -> dict: + return { + "status": self.status, + "digits_requested": self.digits_requested, + "digits_compared": self.digits_compared, + "digits_matched": self.digits_matched, + "digits_mismatched": self.digits_mismatched, + "first_mismatch_position": self.first_mismatch_position, + "reference_source": self.reference_source, + "reference_sha256": self.reference_sha256, + "calculated_sha256": self.calculated_sha256, + "verification_time": self.verification_time, + "method": self.method, + "details": self.details, + } + + def to_json(self, indent: int = 2) -> str: + return json.dumps(self.to_dict(), indent=indent) + + def is_fully_verified(self) -> bool: + # Only FULLY_VERIFIED means every digit was compared against a + # trustworthy reference. INDEPENDENTLY_VERIFIED (e.g. BBP spot checks) + # confirms the algorithm at sampled positions only and is NOT full + # verification of the output. + return self.status == FULLY_VERIFIED + + +# ============================================================================ +# Reference management +# ============================================================================ + +@dataclass +class ReferenceInfo: + """Metadata about a reference file.""" + + path: Path + sha256: str + digit_count: int + source: str # URL or description of provenance + notes: str = "" + + +def sha256_file(path: Path, chunk_size: int = CHUNK_SIZE) -> str: + """Return the SHA-256 hex digest of a file (streamed, constant memory).""" + + digest = hashlib.sha256() + with path.open("rb", buffering=chunk_size) as f: + for chunk in iter(lambda: f.read(chunk_size), b""): + digest.update(chunk) + return digest.hexdigest() + + +def sha256_bytes(data: bytes) -> str: + """Return the SHA-256 hex digest of bytes.""" + return hashlib.sha256(data).hexdigest() + + +def normalize_bytes(data: bytes) -> bytes: + """Remove formatting characters (whitespace, dots) from a byte string.""" + return ( + data.replace(b"\r", b"") + .replace(b"\n", b"") + .replace(b" ", b"") + .replace(b"\t", b"") + .replace(b".", b"") + ) + + +def count_digits_in_file(path: Path, chunk_size: int = CHUNK_SIZE) -> int: + """Count normalized digits in a file.""" + total = 0 + with path.open("rb", buffering=chunk_size) as f: + for chunk in iter(lambda: f.read(chunk_size), b""): + total += len(normalize_bytes(chunk)) + return total + + +def read_decimal_digits(path: Path, expected_count: Optional[int] = None) -> str: + """Read a file and return its normalized decimal digits as a string. + + If ``expected_count`` is given and the file contains a different number + of digits, a ValueError is raised. + """ + + digits = bytearray() + with path.open("rb", buffering=CHUNK_SIZE) as f: + for chunk in iter(lambda: f.read(CHUNK_SIZE), b""): + digits.extend(normalize_bytes(chunk)) + + text = digits.decode("ascii") + if expected_count is not None and len(text) != expected_count: + raise ValueError( + f"Expected {expected_count:,} digits, found {len(text):,}" + ) + return text + + +# ============================================================================ +# Structural validation +# ============================================================================ + +def validate_structure(pi_string: str, digits: int) -> Tuple[bool, str]: + """Check that ``pi_string`` is structurally valid. + + Returns (is_valid, reason). + """ + + if not isinstance(pi_string, str): + return False, "input is not a string" + + if "." not in pi_string: + return False, "missing decimal point" + + integer_part, _, decimal_part = pi_string.partition(".") + + if integer_part != "3": + return False, f"integer part is {integer_part!r}, expected '3'" + + if len(decimal_part) != digits: + return False, ( + f"expected {digits:,} fractional digits, found {len(decimal_part):,}" + ) + + if not decimal_part.isdigit(): + return False, "fractional part contains non-digit characters" + + return True, "" + + +# ============================================================================ +# Prefix verification (built-in known digits) +# ============================================================================ + +# First 1,000 decimal digits of pi (after the decimal point). +# Source: https://www.piday.org/million/ — independent of compute.py. +PI_DECIMAL_DIGITS_1000 = ( + "14159265358979323846264338327950288419716939937510582097494459230781" + "64062862089986280348253421170679821480865132823066470938446095505822" + "31725359408128481117450284102701938521105559644622948954930381964428" + "810975665933446128475648233786783165271201909145648566923460348610454" + "326648213393607260249141273724587006606315588174881520920962829254091" + "715364367892590360011330530548820466521384146951941511609433057270365" + "759591953092186117381932611793105118548074462379962749567351885752724" + "891227938183011949129833673362440656643086021394946395224737190702179" + "860943702770539217176293176752384674818467669405132000568127145263560" + "827785771342757789609173637178721468440901224953430146549585371050792" + "279689258923542019956112129021960864034418159813629774771309960518707" + "211349999998372978049951059731732816096318595024459455346908302642522" + "308253344685035261931188171010003137838752886587533208381420617177669" + "147303598253490428755468731159562863882353787593751957781857780532171" + "2268066130019278766111959092164201989" +) + +assert len(PI_DECIMAL_DIGITS_1000) == 1000 + + +def verify_prefix_builtin(pi_string: str, digits: int) -> Tuple[str, int]: + """Verify against the built-in 1,000-digit reference. + + Returns (status, checked_count). + """ + + ok, reason = validate_structure(pi_string, digits) + if not ok: + return VERIFICATION_FAILED, 0 + + _, _, decimal_part = pi_string.partition(".") + + check_len = min(digits, len(PI_DECIMAL_DIGITS_1000)) + if decimal_part[:check_len] != PI_DECIMAL_DIGITS_1000[:check_len]: + return VERIFICATION_FAILED, 0 + + if digits <= len(PI_DECIMAL_DIGITS_1000): + return FULLY_VERIFIED, digits + + return PREFIX_VERIFIED, check_len + + +# ============================================================================ +# Full file-to-file verification +# ============================================================================ + +def verify_files( + calculated_path: Path, + reference_path: Path, + *, + chunk_size: int = CHUNK_SIZE, +) -> VerificationReport: + """Compare a calculated file against a reference file digit by digit. + + Both files are normalized (whitespace and dots removed) before comparison. + """ + + report = VerificationReport( + status=CALCULATED, + method="file_to_file", + reference_source=str(reference_path), + ) + + start = time.perf_counter() + + if not calculated_path.exists(): + report.status = VERIFICATION_FAILED + report.details["error"] = f"calculated file not found: {calculated_path}" + report.verification_time = time.perf_counter() - start + return report + + if not reference_path.exists(): + report.status = VERIFICATION_FAILED + report.details["error"] = f"reference file not found: {reference_path}" + report.verification_time = time.perf_counter() - start + return report + + # Hash both files + report.calculated_sha256 = sha256_file(calculated_path, chunk_size) + report.reference_sha256 = sha256_file(reference_path, chunk_size) + + calculated_digits = 0 + reference_digits = 0 + matched = 0 + mismatched = 0 + first_mismatch: Optional[int] = None + + with calculated_path.open("rb", buffering=chunk_size) as calc, \ + reference_path.open("rb", buffering=chunk_size) as ref: + + calc_data = b"" + ref_data = b"" + + while True: + if not calc_data: + raw = calc.read(chunk_size) + if raw: + calc_data = normalize_bytes(raw) + + if not ref_data: + raw = ref.read(chunk_size) + if raw: + ref_data = normalize_bytes(raw) + + if not calc_data and not ref_data: + break + + if not calc_data: + extra = len(ref_data) + mismatched += extra + if first_mismatch is None: + first_mismatch = matched + mismatched - extra + reference_digits += extra + ref_data = b"" + continue + + if not ref_data: + extra = len(calc_data) + mismatched += extra + if first_mismatch is None: + first_mismatch = matched + mismatched - extra + calculated_digits += extra + calc_data = b"" + continue + + length = min(len(calc_data), len(ref_data)) + c = calc_data[:length] + r = ref_data[:length] + + if c == r: + matched += length + else: + for i in range(length): + if c[i] == r[i]: + matched += 1 + else: + mismatched += 1 + if first_mismatch is None: + first_mismatch = matched + mismatched - 1 + + calculated_digits += length + reference_digits += length + calc_data = calc_data[length:] + ref_data = ref_data[length:] + + elapsed = time.perf_counter() - start + + report.digits_requested = calculated_digits + report.digits_compared = min(calculated_digits, reference_digits) + report.digits_matched = matched + report.digits_mismatched = mismatched + report.first_mismatch_position = first_mismatch + report.verification_time = elapsed + report.details = { + "calculated_digits": calculated_digits, + "reference_digits": reference_digits, + "chunk_size": chunk_size, + } + + if mismatched == 0 and calculated_digits == reference_digits: + report.status = FULLY_VERIFIED + elif mismatched > 0: + report.status = VERIFICATION_FAILED + else: + # Length mismatch with no character mismatches in overlap + report.status = VERIFICATION_FAILED + + return report + + +# ============================================================================ +# BBP independent spot checks +# ============================================================================ + +from piproject.bbp import ( + bbp_vs_decimal, + decimal_to_hex_at, + spot_check_positions, +) # noqa: E402 + + +def verify_bbp_spot_checks( + positions: List[int], + num_digits: int = 5, +) -> VerificationReport: + """Run BBP hexadecimal spot checks at the given positions. + + This is algorithmically independent of the Chudnovsky computation engine. + Results are spot checks, not full verification. + """ + + report = VerificationReport( + status=CALCULATED, + method="bbp_spot_check", + ) + + start = time.perf_counter() + results = spot_check_positions(positions) + elapsed = time.perf_counter() - start + + all_match = all(m for _, _, m in results.values()) + + report.details = { + "positions": positions, + "num_digits_per_position": num_digits, + "results": { + str(pos): {"bbp": bbp, "reference": ref, "match": m} + for pos, (bbp, ref, m) in results.items() + }, + "all_match": all_match, + } + report.verification_time = elapsed + + if all_match: + report.status = INDEPENDENTLY_VERIFIED + report.digits_compared = len(positions) * num_digits + report.digits_matched = len(positions) * num_digits + else: + report.status = VERIFICATION_FAILED + + return report + + +# ============================================================================ +# Complete verification pipeline +# ============================================================================ + +def verify_pi( + pi_string: str, + digits: int, + *, + reference_path: Optional[Path] = None, + bbp_positions: Optional[List[int]] = None, +) -> VerificationReport: + """Run the full verification pipeline on a pi string. + + Steps: + 1. Structural validation -> STRUCTURE_VALID or VERIFICATION_FAILED + 2. Built-in prefix check -> PREFIX_VERIFIED (or FULLY_VERIFIED if <=1000) + 3. Optional file-to-file reference comparison -> FULLY_VERIFIED + 4. Optional BBP spot checks -> INDEPENDENTLY_VERIFIED (supplemental) + + The final status reflects the strongest verification achieved. + """ + + report = VerificationReport( + status=CALCULATED, + digits_requested=digits, + method="pipeline", + ) + + start = time.perf_counter() + + # Step 1: Structure + ok, reason = validate_structure(pi_string, digits) + if not ok: + report.status = VERIFICATION_FAILED + report.details["structure_error"] = reason + report.verification_time = time.perf_counter() - start + return report + + report.status = STRUCTURE_VALID + + # Step 2: Built-in prefix + prefix_status, checked = verify_prefix_builtin(pi_string, digits) + report.digits_compared = checked + report.digits_matched = checked + + if prefix_status == VERIFICATION_FAILED: + report.status = VERIFICATION_FAILED + report.verification_time = time.perf_counter() - start + return report + + report.status = prefix_status + + # Step 3: Full reference comparison (if a file is provided) + if reference_path is not None: + _, _, decimal_part = pi_string.partition(".") + # Write to a temp file for comparison + import tempfile + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".txt", delete=False + ) as tmp: + # Write the full pi_string ("3.14159...") so it matches the + # reference file format after normalization. + tmp.write(pi_string) + tmp_path = Path(tmp.name) + + try: + file_report = verify_files(tmp_path, reference_path) + report.calculated_sha256 = file_report.calculated_sha256 + report.reference_sha256 = file_report.reference_sha256 + report.reference_source = str(reference_path) + report.digits_compared = file_report.digits_compared + report.digits_matched = file_report.digits_matched + report.digits_mismatched = file_report.digits_mismatched + report.first_mismatch_position = file_report.first_mismatch_position + report.details["file_verification"] = file_report.to_dict() + + if file_report.status == FULLY_VERIFIED: + report.status = FULLY_VERIFIED + elif file_report.status == VERIFICATION_FAILED: + report.status = VERIFICATION_FAILED + finally: + tmp_path.unlink(missing_ok=True) + + # Step 4: BBP spot checks (supplemental, independent). + # Two related checks are performed: + # (a) Pure BBP vs published hex reference — confirms the algorithm + # independently of the computation engine. + # (b) BBP vs decimal-to-hex conversion of the calculated output — + # establishes a real relationship between the decimal result and + # independent BBP computation. + # Neither changes the main verification status or implies full verification. + if bbp_positions: + bbp_details = {} + + # (a) Pure BBP vs published reference + pure_report = verify_bbp_spot_checks(bbp_positions) + bbp_details["pure_bbp_vs_reference"] = pure_report.to_dict() + + # (b) BBP vs decimal-to-hex of the calculated output + _, _, decimal_part = pi_string.partition(".") + try: + decimal_vs_bbp = bbp_vs_decimal(decimal_part, bbp_positions) + bbp_details["bbp_vs_decimal"] = { + str(pos): { + "bbp": bbp, + "decimal_hex": dec_hex, + "match": match, + } + for pos, (bbp, dec_hex, match) in decimal_vs_bbp.items() + } + bbp_details["decimal_to_bbp_all_match"] = all( + m for _, _, m in decimal_vs_bbp.values() + ) + except ValueError as exc: + bbp_details["decimal_to_bbp_error"] = str(exc) + + report.details["bbp_spot_checks"] = bbp_details + + report.verification_time = time.perf_counter() - start + return report + + +def verify_pi_file( + calculated_path: Path, + reference_path: Path, + *, + bbp_positions: Optional[List[int]] = None, +) -> VerificationReport: + """Verify a calculated pi file against a reference file. + + Reads the calculated file, extracts decimal digits, and runs the + full verification pipeline. + """ + + report = VerificationReport( + status=CALCULATED, + method="file_pipeline", + reference_source=str(reference_path), + ) + + start = time.perf_counter() + + if not calculated_path.exists(): + report.status = VERIFICATION_FAILED + report.details["error"] = f"calculated file not found: {calculated_path}" + report.verification_time = time.perf_counter() - start + return report + + if not reference_path.exists(): + report.status = VERIFICATION_FAILED + report.details["error"] = f"reference file not found: {reference_path}" + report.verification_time = time.perf_counter() - start + return report + + # Hash both files + report.calculated_sha256 = sha256_file(calculated_path) + report.reference_sha256 = sha256_file(reference_path) + + # Full file-to-file verification + file_report = verify_files(calculated_path, reference_path) + report.digits_compared = file_report.digits_compared + report.digits_matched = file_report.digits_matched + report.digits_mismatched = file_report.digits_mismatched + report.first_mismatch_position = file_report.first_mismatch_position + report.details["file_verification"] = file_report.to_dict() + + if file_report.status == FULLY_VERIFIED: + report.status = FULLY_VERIFIED + report.digits_requested = file_report.digits_compared + else: + report.status = VERIFICATION_FAILED + + # Optional BBP spot checks (supplemental, independent). + # BBP never changes the main verification status or implies full verification. + if bbp_positions: + bbp_details = {} + + # (a) Pure BBP vs published reference + pure_report = verify_bbp_spot_checks(bbp_positions) + bbp_details["pure_bbp_vs_reference"] = pure_report.to_dict() + + # (b) BBP vs decimal-to-hex of the calculated output + try: + decimal_digits = read_decimal_digits(calculated_path) + # Strip integer part "3" if present + if decimal_digits.startswith("3"): + decimal_digits = decimal_digits[1:] + decimal_vs_bbp = bbp_vs_decimal(decimal_digits, bbp_positions) + bbp_details["bbp_vs_decimal"] = { + str(pos): { + "bbp": bbp, + "decimal_hex": dec_hex, + "match": match, + } + for pos, (bbp, dec_hex, match) in decimal_vs_bbp.items() + } + bbp_details["decimal_to_bbp_all_match"] = all( + m for _, _, m in decimal_vs_bbp.values() + ) + except (ValueError, OSError) as exc: + bbp_details["decimal_to_bbp_error"] = str(exc) + + report.details["bbp_spot_checks"] = bbp_details + + report.verification_time = time.perf_counter() - start + return report + + +__all__ = [ + "CALCULATED", + "STRUCTURE_VALID", + "PREFIX_VERIFIED", + "FULLY_VERIFIED", + "INDEPENDENTLY_VERIFIED", + "VERIFICATION_FAILED", + "VerificationReport", + "ReferenceInfo", + "sha256_file", + "sha256_bytes", + "normalize_bytes", + "count_digits_in_file", + "read_decimal_digits", + "validate_structure", + "verify_prefix_builtin", + "verify_files", + "verify_bbp_spot_checks", + "verify_pi", + "verify_pi_file", +] diff --git a/tests/conftest.py b/tests/conftest.py index 36b9d23..34d4097 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,55 +1,60 @@ -"""Shared fixtures and helpers for PiProject tests.""" +"""Shared fixtures for PiProject tests.""" from decimal import Decimal, getcontext +from pathlib import Path +import gmpy2 import pytest +import piproject.compute as compute +import piproject.verify as verify + @pytest.fixture -def tmp_output(tmp_path): - """Provide a writable output path inside a temporary directory.""" +def tmp_pi_file(tmp_path: Path) -> Path: + """Provide a writable pi output path in a temp directory.""" return tmp_path / "pi_test.txt" -# --------------------------------------------------------------------------- -# Independent pi reference (decimal / Machin-like) -# -# Used to cross-check pi_project_v4.calculate_pi against a genuinely -# independent implementation so the tests are not self-referential. -# --------------------------------------------------------------------------- - -def _reference_pi_decimals(digits: int) -> str: - """Return `digits` decimal digits of pi (after the point) via Machin. - - pi/4 = 4*atan(1/5) - atan(1/239), evaluated with the `decimal` module. - Independent of gmpy2 and of the binary-splitting implementation. - """ - - getcontext().prec = digits + 80 - - def atan_inverse(n): - x = Decimal(1) / Decimal(n) - x_squared = x * x - total = Decimal(0) - power = x - k = 0 - while True: - term = power / (2 * k + 1) - if term < Decimal(10) ** -(digits + 70): - break - total += term if k % 2 == 0 else -term - power *= x_squared - k += 1 - return total - - pi = Decimal(16) * atan_inverse(5) - Decimal(4) * atan_inverse(239) - # compute a few guard decimals, then truncate (matching calculate_pi's - # floor behaviour) rather than rounding the final digit. - guard = 20 - s = format(pi, f".{digits + guard}f") - return s.split(".")[1][:digits] +@pytest.fixture +def reference_pi_decimals(): + """Return a function that computes `digits` decimal digits of pi + using an independent decimal/Machin implementation.""" + + def _compute(digits: int) -> str: + getcontext().prec = digits + 80 + + def atan_inv(x: int) -> Decimal: + term = Decimal(1) / Decimal(x) + x_sq = Decimal(1) / (Decimal(x) * Decimal(x)) + total = Decimal(0) + power = term + k = 0 + while True: + denom = 2 * k + 1 + t = power / denom + if t < Decimal(10) ** (-(digits + 70)): + break + total += t if k % 2 == 0 else -t + power *= x_sq + k += 1 + return total + + pi = Decimal(16) * atan_inv(5) - Decimal(4) * atan_inv(239) + s = format(pi, "f") + if "." in s: + _, frac = s.split(".") + else: + frac = "" + return frac[:digits] + + return _compute @pytest.fixture -def reference_pi_decimals(): - return _reference_pi_decimals +def gmpy2_precision(): + """Ensure gmpy2 precision is not mutated by tests.""" + before = gmpy2.get_context().precision + yield + after = gmpy2.get_context().precision + assert after == before, "gmpy2 global precision was mutated" diff --git a/tests/fixtures/pi_1000_reference.provenance.json b/tests/fixtures/pi_1000_reference.provenance.json new file mode 100644 index 0000000..94f9f04 --- /dev/null +++ b/tests/fixtures/pi_1000_reference.provenance.json @@ -0,0 +1,18 @@ +{ + "filename": "pi_1000_reference.txt", + "description": "First 1,000 decimal digits of pi (after the decimal point), including the integer part '3' and decimal point.", + "digit_count": 1000, + "file_size_bytes": 1002, + "format": "3.<1000 fractional digits> (ASCII, no trailing newline)", + "sha256": "823a2e34f63c5d5f30a27733976df5a1ab57feaab505f40d95d3dd3fefa425cc", + "source": "Independent decimal/Machin computation cross-checked against published reference", + "source_details": [ + "Computed independently using Python decimal module with Machin-like formula: pi/4 = 4*atan(1/5) - atan(1/239)", + "Cross-checked against the first 1,000 digits published at https://www.piday.org/million/", + "Algorithmically and technologically independent of the Chudnovsky/binary-splitting computation engine" + ], + "retrieval_date": "2026-11-22", + "verification_method": "Digit-by-digit comparison against independent decimal/Machin computation; SHA-256 fingerprint recorded for integrity", + "usage": "Committed reference fixture used by CI to verify the computation engine produces correct output. CI verifies this file's SHA-256 before use and fails if it does not match.", + "notes": "This fixture covers only the first 1,000 digits. It is sufficient for prefix verification and CI smoke tests, but not for full verification of larger digit counts." +} diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..dd46ba0 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,135 @@ +"""Tests for the CLI (piproject.cli) using subprocess.""" + +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +PIPROJECT = [sys.executable, "-m", "piproject.cli"] + + +def run_piproject(*args, cwd=None): + """Run the piproject CLI as a subprocess.""" + result = subprocess.run( + PIPROJECT + list(args), + capture_output=True, + text=True, + cwd=cwd, + ) + return result + + +# --------------------------------------------------------------------------- +# calculate +# --------------------------------------------------------------------------- + +def test_cli_calculate(tmp_path): + out = tmp_path / "pi_50.txt" + result = run_piproject( + "calculate", "--digits", "50", "--output", str(out), cwd=tmp_path + ) + assert result.returncode == 0, result.stderr + assert out.exists() + content = out.read_text(encoding="ascii") + assert content.startswith("3.") + assert len(content.split(".")[1]) == 50 + + +def test_cli_calculate_rejects_zero(): + result = run_piproject("calculate", "--digits", "0") + assert result.returncode != 0 + + +def test_cli_calculate_no_output(tmp_path): + result = run_piproject("calculate", "--digits", "25", cwd=tmp_path) + assert result.returncode == 0, result.stderr + assert "Throughput" in result.stdout + + +# --------------------------------------------------------------------------- +# verify +# --------------------------------------------------------------------------- + +def test_cli_verify_match(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(50) + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(pi.encode()) + ref.write_bytes(pi.encode()) + + result = run_piproject( + "verify", "--input", str(calc), "--reference", str(ref), cwd=tmp_path + ) + assert result.returncode == 0, result.stderr + assert "FULLY VERIFIED" in result.stdout or "FULLY_VERIFIED" in result.stdout + + +def test_cli_verify_missing_input(): + result = run_piproject("verify", "--input", "/nonexistent/file.txt") + assert result.returncode != 0 + + +# --------------------------------------------------------------------------- +# benchmark +# --------------------------------------------------------------------------- + +def test_cli_benchmark(tmp_path): + result = run_piproject( + "benchmark", "--digits", "100", "--repeats", "1", cwd=tmp_path + ) + assert result.returncode == 0, result.stderr + assert "Best:" in result.stdout + assert "Throughput" in result.stdout + + +# --------------------------------------------------------------------------- +# inspect +# --------------------------------------------------------------------------- + +def test_cli_inspect(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(50) + f = tmp_path / "pi.txt" + f.write_bytes(pi.encode()) + + result = run_piproject("inspect", "--input", str(f), cwd=tmp_path) + assert result.returncode == 0, result.stderr + assert "Fractional digits:" in result.stdout + assert "SHA-256" in result.stdout + + +# --------------------------------------------------------------------------- +# hash +# --------------------------------------------------------------------------- + +def test_cli_hash(tmp_path): + f = tmp_path / "data.txt" + f.write_bytes(b"hello world") + + result = run_piproject("hash", "--input", str(f), cwd=tmp_path) + assert result.returncode == 0, result.stderr + assert "SHA-256" in result.stdout + + +# --------------------------------------------------------------------------- +# version +# --------------------------------------------------------------------------- + +def test_cli_version(): + result = run_piproject("--version") + assert result.returncode == 0 + assert "PiProject v" in result.stdout + + +# --------------------------------------------------------------------------- +# no command +# --------------------------------------------------------------------------- + +def test_cli_no_command(): + result = run_piproject() + assert result.returncode != 0 diff --git a/tests/test_compute.py b/tests/test_compute.py new file mode 100644 index 0000000..6a7d0e5 --- /dev/null +++ b/tests/test_compute.py @@ -0,0 +1,188 @@ +"""Tests for the computation engine (piproject.compute).""" + +import hashlib +import sys + +import gmpy2 +import pytest + +import piproject.compute as compute +from piproject import ( + FULLY_VERIFIED, + PREFIX_VERIFIED, + VERIFICATION_FAILED, +) + + +# --------------------------------------------------------------------------- +# binary_split +# --------------------------------------------------------------------------- + +def test_binary_split_base_case_zero(): + P, Q, T = compute.binary_split(0, 1) + assert P == gmpy2.mpz(1) + assert Q == gmpy2.mpz(1) + assert T == gmpy2.mpz(13591409) + + +def test_binary_split_base_case_nonzero(): + P, Q, T = compute.binary_split(2, 3) + k = gmpy2.mpz(2) + expected_P = (6 * k - 5) * (2 * k - 1) * (6 * k - 1) + expected_Q = k**3 * compute.C3_OVER_24 + expected_T = expected_P * (compute.A + compute.B * k) + assert P == expected_P + assert Q == expected_Q + assert T == expected_T + + +def test_binary_split_sign_alternation(): + _, _, T_even = compute.binary_split(2, 3) + _, _, T_odd = compute.binary_split(3, 4) + assert T_even > 0 + assert T_odd < 0 + + +def test_binary_split_associativity(): + P_all, Q_all, T_all = compute.binary_split(0, 8) + P1, Q1, T1 = compute.binary_split(0, 4) + P2, Q2, T2 = compute.binary_split(4, 8) + assert P_all == P1 * P2 + assert Q_all == Q1 * Q2 + assert T_all == T1 * Q2 + P1 * T2 + + +# --------------------------------------------------------------------------- +# calculate_pi correctness +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize("digits", [1, 2, 5, 10, 50, 100, 250, 500, 1000]) +def test_calculate_pi_matches_known_digits(digits): + """The full result must match known pi digits for digits <= 1000.""" + pi, _ = compute.calculate_pi(digits) + integer_part, _, decimal_part = pi.partition(".") + assert integer_part == "3" + assert len(decimal_part) == digits + assert decimal_part.isdigit() + assert decimal_part == compute.PI_DECIMAL_DIGITS_1000[:digits] + + +@pytest.mark.parametrize("digits", [1, 5, 50, 100, 500, 1000]) +def test_calculate_pi_matches_independent(digits, reference_pi_decimals): + """Cross-check against independent decimal/Machin implementation.""" + pi, _ = compute.calculate_pi(digits) + _, _, decimal_part = pi.partition(".") + assert decimal_part == reference_pi_decimals(digits) + + +@pytest.mark.parametrize("digits", [1, 7, 100]) +def test_calculate_pi_format(digits): + """Result is always '.'.""" + pi, _ = compute.calculate_pi(digits) + assert pi.count(".") == 1 + integer_part, _, decimal_part = pi.partition(".") + assert integer_part == "3" + assert len(decimal_part) == digits + + +@pytest.mark.parametrize("digits", [1000, 10000]) +def test_calculate_pi_large_matches_independent(digits, reference_pi_decimals): + """Cross-check larger values against independent computation.""" + pi, _ = compute.calculate_pi(digits) + _, _, decimal_part = pi.partition(".") + assert decimal_part == reference_pi_decimals(digits) + + +def test_calculate_pi_rejects_zero(): + with pytest.raises(ValueError): + compute.calculate_pi(0) + + +def test_calculate_pi_rejects_negative(): + with pytest.raises(ValueError): + compute.calculate_pi(-5) + + +# --------------------------------------------------------------------------- +# verify_prefix +# --------------------------------------------------------------------------- + +def test_verify_prefix_accepts_correct(): + pi, _ = compute.calculate_pi(100) + status, checked = compute.verify_prefix(pi, 100) + assert status == FULLY_VERIFIED + assert checked == 100 + + +def test_verify_prefix_small_digit(): + """Regression: verify_prefix must not false-negative on small results.""" + pi, _ = compute.calculate_pi(5) + status, checked = compute.verify_prefix(pi, 5) + assert status == FULLY_VERIFIED + assert checked == 5 + + +def test_verify_prefix_rejects_corrupted(): + pi, _ = compute.calculate_pi(100) + corrupted = pi[:-1] + ("1" if pi[-1] != "1" else "2") + status, _ = compute.verify_prefix(corrupted, 100) + assert status == VERIFICATION_FAILED + + +def test_verify_prefix_beyond_1000_is_prefix_only(): + """Digits beyond 1000 are PREFIX_VERIFIED, not FULLY_VERIFIED.""" + pi, _ = compute.calculate_pi(1500) + status, checked = compute.verify_prefix(pi, 1500) + assert status == PREFIX_VERIFIED + assert checked == 1000 + + +def test_verify_prefix_false_positive_beyond_1000(): + """Corrupting a digit beyond position 1000 must NOT pass as FULLY_VERIFIED.""" + pi, _ = compute.calculate_pi(2000) + # Corrupt a digit at position 1500 (after the 1000-digit prefix) + idx = 1500 # 0-indexed in decimal part + orig = pi[idx + 2] # +2 for "3." + repl = "9" if orig != "9" else "8" + corrupted = pi[: idx + 2] + repl + pi[idx + 3:] + status, checked = compute.verify_prefix(corrupted, 2000) + assert status == PREFIX_VERIFIED # prefix check passes + assert checked == 1000 + + +# --------------------------------------------------------------------------- +# save/streaming +# --------------------------------------------------------------------------- + +def test_calculate_pi_streaming_writes_file(tmp_pi_file): + pi, elapsed = compute.calculate_pi_streaming(50, output=tmp_pi_file) + assert tmp_pi_file.exists() + assert tmp_pi_file.read_text(encoding="ascii") == pi + assert elapsed > 0 + + +# --------------------------------------------------------------------------- +# gmpy2 global state +# --------------------------------------------------------------------------- + +def test_compute_does_not_mutate_gmpy2_precision(gmpy2_precision): + before = gmpy2.get_context().precision + compute.calculate_pi(50) + after = gmpy2.get_context().precision + assert after == before + + +# --------------------------------------------------------------------------- +# SHA-256 reproducibility +# --------------------------------------------------------------------------- + +def test_calculate_pi_sha256_stable(): + """The SHA-256 of the output must be stable across runs.""" + import piproject.verify as verify_mod + + pi1, _ = compute.calculate_pi(250) + pi2, _ = compute.calculate_pi(250) + assert pi1 == pi2 + h1 = hashlib.sha256(pi1.split(".")[1].encode()).hexdigest() + h2 = hashlib.sha256(pi2.split(".")[1].encode()).hexdigest() + assert h1 == h2 diff --git a/tests/test_pi_project_v4.py b/tests/test_pi_project_v4.py deleted file mode 100644 index db067e9..0000000 --- a/tests/test_pi_project_v4.py +++ /dev/null @@ -1,207 +0,0 @@ -"""Tests for pi_project_v4.py (Chudnovsky + binary splitting + GMP).""" - -import os -import subprocess -import sys - -import gmpy2 -import pytest - -import pi_project_v4 as m - - -# --------------------------------------------------------------------------- -# calculate_pi correctness -# --------------------------------------------------------------------------- - -@pytest.mark.parametrize("digits", [1, 2, 5, 10, 50, 100, 250, 500, 1000]) -def test_calculate_pi_matches_known_digits(digits): - """The full result must match known pi digits for digits <= 1000.""" - - pi, _ = m.calculate_pi(digits) - - integer_part, _, decimal_part = pi.partition(".") - assert integer_part == "3" - assert len(decimal_part) == digits - assert decimal_part.isdigit() - assert decimal_part == m.PI_DECIMAL_DIGITS_1000[:digits] - - -@pytest.mark.parametrize("digits", [1, 5, 50, 100, 500, 1000]) -def test_calculate_pi_matches_independent_reference(digits, reference_pi_decimals): - """Cross-check against an independent decimal/Machin implementation.""" - - pi, _ = m.calculate_pi(digits) - _, _, decimal_part = pi.partition(".") - assert decimal_part == reference_pi_decimals(digits) - - -def test_calculate_pi_format_and_length(): - """Result is always '.'.""" - - for digits in (1, 7, 100): - pi, _ = m.calculate_pi(digits) - assert pi.count(".") == 1 - integer_part, _, decimal_part = pi.partition(".") - assert integer_part == "3" - assert len(decimal_part) == digits - - -# --------------------------------------------------------------------------- -# binary_split -# --------------------------------------------------------------------------- - -def test_binary_split_base_case_zero(): - P, Q, T = m.binary_split(0, 1) - assert P == gmpy2.mpz(1) - assert Q == gmpy2.mpz(1) - assert T == gmpy2.mpz(13591409) - - -def test_binary_split_base_case_nonzero(): - P, Q, T = m.binary_split(2, 3) - k = gmpy2.mpz(2) - expected_P = (6 * k - 5) * (2 * k - 1) * (6 * k - 1) - expected_Q = k**3 * m.C3_OVER_24 - expected_T = expected_P * (m.A + m.B * k) # sign: a=2 is even -> positive - assert P == expected_P - assert Q == expected_Q - assert T == expected_T - - -def test_binary_split_sign_alternation(): - # a odd -> T negated - P_even, _, T_even = m.binary_split(2, 3) - P_odd, _, T_odd = m.binary_split(3, 4) - assert T_even > 0 - assert T_odd < 0 - - -def test_binary_split_associativity(): - """Splitting [0, n) directly equals combining [0, m) and [m, n).""" - - P_all, Q_all, T_all = m.binary_split(0, 8) - P1, Q1, T1 = m.binary_split(0, 4) - P2, Q2, T2 = m.binary_split(4, 8) - - assert P_all == P1 * P2 - assert Q_all == Q1 * Q2 - assert T_all == T1 * Q2 + P1 * T2 - - -# --------------------------------------------------------------------------- -# verify_pi -# --------------------------------------------------------------------------- - -def test_verify_pi_accepts_correct_result(): - pi, _ = m.calculate_pi(100) - assert m.verify_pi(pi, 100) is True - - -def test_verify_pi_rejects_wrong_digit(): - pi, _ = m.calculate_pi(100) - corrupted = pi[:-1] + ("1" if pi[-1] != "1" else "2") - assert m.verify_pi(corrupted, 100) is False - - -def test_verify_pi_rejects_wrong_length(): - pi, _ = m.calculate_pi(100) - # 99 fractional digits -> wrong length - assert m.verify_pi(pi[:-1], 100) is False - - -def test_verify_pi_rejects_wrong_integer_part(): - pi, _ = m.calculate_pi(100) - assert m.verify_pi("4" + pi[1:], 100) is False - - -def test_verify_pi_small_digit_no_false_negative(): - # Regression: previously verify_pi(5) returned False for a correct - # 5-digit result because the fixed prefix was longer than the output. - pi, _ = m.calculate_pi(5) - assert m.verify_pi(pi, 5) is True - - -def test_verify_pi_rejects_non_string_and_malformed(): - assert m.verify_pi(None, 10) is False - assert m.verify_pi("3.14", 10) is False # wrong length - assert m.verify_pi("3.14159abc", 10) is False # non-digits - - -# --------------------------------------------------------------------------- -# save_pi -# --------------------------------------------------------------------------- - -def test_save_pi_writes_exact_contents(tmp_output): - pi, _ = m.calculate_pi(25) - saved = m.save_pi(pi, 25, filename=tmp_output) - assert saved == tmp_output - assert tmp_output.read_text(encoding="ascii") == pi - - -# --------------------------------------------------------------------------- -# CLI -# --------------------------------------------------------------------------- - -def test_cli_digits_and_output(tmp_output, monkeypatch, capsys): - argv = ["--digits", "40", "--output", str(tmp_output)] - code = m.main(argv) - assert code == 0 - assert tmp_output.exists() - content = tmp_output.read_text(encoding="ascii") - content_int, _, content_dec = content.partition(".") - assert content_int == "3" - assert len(content_dec) == 40 - assert content_dec == m.PI_DECIMAL_DIGITS_1000[:40] - - -def test_cli_rejects_nonpositive_digits(monkeypatch, capsys): - code = m.main(["--digits", "0"]) - assert code == 1 - out = capsys.readouterr().out - assert "greater than 0" in out - - -def test_cli_rejects_invalid_digits(monkeypatch, capsys): - # argparse exits non-zero on a non-integer --digits. - with pytest.raises(SystemExit): - m.main(["--digits", "not-a-number"]) - - -def test_cli_verification_catches_corruption(monkeypatch, capsys, tmp_output): - # Feed a wrong digit count: --digits 3 but verify expects correct first 3 - # decimals (141). A correct calc of 3 digits is "3.141" -> verifies. - # To force failure we monkeypatch verify_pi. - monkeypatch.setattr(m, "verify_pi", lambda pi, d: False) - code = m.main(["--digits", "10", "--output", str(tmp_output)]) - assert code == 1 - - -def test_interactive_fallback_monkeypatched(monkeypatch, tmp_output): - # No --digits -> use input() fallback; write via --output. - monkeypatch.setattr("builtins.input", lambda prompt="": "20") - code = m.main(["--output", str(tmp_output)]) - assert code == 0 - assert tmp_output.read_text(encoding="ascii") == ( - "3." + m.PI_DECIMAL_DIGITS_1000[:20] - ) - - -def test_module_import_does_not_prompt(capsys): - # Importing must not call input() or exit (regression for pie-style bug). - import importlib - importlib.reload(m) - out = capsys.readouterr().out - assert out == "" - - -# --------------------------------------------------------------------------- -# No global GMPY2 state mutation on import -# --------------------------------------------------------------------------- - -def test_import_does_not_change_gmpy2_precision(): - before = gmpy2.get_context().precision - import importlib - importlib.reload(m) - after = gmpy2.get_context().precision - assert after == before diff --git a/tests/test_verify.py b/tests/test_verify.py index 754ec22..d94d9d6 100644 --- a/tests/test_verify.py +++ b/tests/test_verify.py @@ -1,14 +1,38 @@ -"""Tests for verify.py (reference comparison).""" +"""Tests for the independent verification engine (piproject.verify).""" import hashlib +from pathlib import Path import pytest -import verify as v +import piproject.verify as verify_mod +from piproject import ( + CALCULATED, + CALCULATED, + FULLY_VERIFIED, + INDEPENDENTLY_VERIFIED, + PREFIX_VERIFIED, + STRUCTURE_VALID, + VERIFICATION_FAILED, +) +from piproject.bbp import bbp_vs_decimal +from piproject.verify import ( + VerificationReport, + count_digits_in_file, + normalize_bytes, + read_decimal_digits, + sha256_bytes, + sha256_file, + validate_structure, + verify_files, + verify_prefix_builtin, + verify_pi, + verify_pi_file, +) # --------------------------------------------------------------------------- -# normalize_chunk +# normalize_bytes # --------------------------------------------------------------------------- @pytest.mark.parametrize( @@ -21,105 +45,471 @@ (b"..12..34..", b"1234"), ], ) -def test_normalize_chunk(raw, expected): - assert v.normalize_chunk(raw) == expected +def test_normalize_bytes(raw, expected): + assert normalize_bytes(raw) == expected # --------------------------------------------------------------------------- -# count_digits +# sha256 # --------------------------------------------------------------------------- -def test_count_digits(tmp_path): +def test_sha256_bytes(): + assert sha256_bytes(b"hello") == hashlib.sha256(b"hello").hexdigest() + + +def test_sha256_file(tmp_path): + p = tmp_path / "data.txt" + p.write_bytes(b"hello world") + expected = hashlib.sha256(b"hello world").hexdigest() + assert sha256_file(p) == expected + + +# --------------------------------------------------------------------------- +# count_digits_in_file +# --------------------------------------------------------------------------- + +def test_count_digits_in_file(tmp_path): p = tmp_path / "digits.txt" p.write_bytes(b"3.14159\n26535\n") - assert v.count_digits(p) == 11 # 31415926535 + assert count_digits_in_file(p) == 11 # 31415926535 # --------------------------------------------------------------------------- -# sha256_file +# read_decimal_digits # --------------------------------------------------------------------------- -def test_sha256_file(tmp_path): - p = tmp_path / "data.txt" - p.write_bytes(b"hello world") - expected = hashlib.sha256(b"hello world").hexdigest() - assert v.sha256_file(p) == expected +def test_read_decimal_digits(tmp_path): + p = tmp_path / "pi.txt" + p.write_bytes(b"3.14159\n26535") + digits = read_decimal_digits(p, expected_count=11) + assert digits == "31415926535" + + +def test_read_decimal_digits_wrong_count(tmp_path): + p = tmp_path / "pi.txt" + p.write_bytes(b"3.14159") + with pytest.raises(ValueError): + read_decimal_digits(p, expected_count=100) # --------------------------------------------------------------------------- -# verify_full +# validate_structure # --------------------------------------------------------------------------- -def _write_digits(path, digits_str): - path.write_bytes(digits_str.encode("ascii")) +@pytest.mark.parametrize( + "s, digits, valid", + [ + ("3.14159", 5, True), + ("3.14", 2, True), + ("4.14159", 5, False), # wrong integer part + ("3.14", 5, False), # wrong length + ("3.1415a", 5, False), # non-digit + ("314159", 5, False), # no decimal point + ], +) +def test_validate_structure(s, digits, valid): + ok, reason = validate_structure(s, digits) + assert ok == valid, f"Expected valid={valid}, got reason={reason}" + + +# --------------------------------------------------------------------------- +# verify_prefix_builtin +# --------------------------------------------------------------------------- + +def test_verify_prefix_builtin_accepts(): + status, checked = verify_prefix_builtin("3.14159", 5) + assert status == FULLY_VERIFIED + assert checked == 5 -def test_verify_full_match(tmp_path): +def test_verify_prefix_builtin_rejects_wrong_digit(): + status, _ = verify_prefix_builtin("3.14150", 5) + assert status == VERIFICATION_FAILED + + +def test_verify_prefix_builtin_beyond_1000(): + """Digits beyond 1000 are PREFIX_VERIFIED.""" + # Construct a string with correct first 1000 digits + from piproject.verify import PI_DECIMAL_DIGITS_1000 + + s = "3." + PI_DECIMAL_DIGITS_1000 + "0" * 500 + status, checked = verify_prefix_builtin(s, 1500) + assert status == PREFIX_VERIFIED + assert checked == 1000 + + +# --------------------------------------------------------------------------- +# verify_files +# --------------------------------------------------------------------------- + +def test_verify_files_match(tmp_path): calc = tmp_path / "calc.txt" ref = tmp_path / "ref.txt" digits = "314159265358979323846264338327950288419716939937510" - _write_digits(calc, digits) - _write_digits(ref, digits) + calc.write_bytes(digits.encode()) + ref.write_bytes(digits.encode()) + + report = verify_files(calc, ref) + assert report.status == FULLY_VERIFIED + assert report.digits_matched == len(digits) + assert report.digits_mismatched == 0 + + +def test_verify_files_mismatch(tmp_path): + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(b"314159") + ref.write_bytes(b"314150") + + report = verify_files(calc, ref) + assert report.status == VERIFICATION_FAILED + assert report.digits_mismatched > 0 + + +def test_verify_files_length_mismatch(tmp_path): + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(b"314159") # 6 digits + ref.write_bytes(b"3141592653") # 10 digits + + report = verify_files(calc, ref) + assert report.status == VERIFICATION_FAILED + + +def test_verify_files_formatting_insensitive(tmp_path): + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(b"3.14159\n26535") + ref.write_bytes(b"31 41 59 26 535") + + report = verify_files(calc, ref) + assert report.status == FULLY_VERIFIED + + +# --------------------------------------------------------------------------- +# verify_pi (string pipeline) +# --------------------------------------------------------------------------- + +def test_verify_pi_full_match(): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(100) + report = verify_pi(pi, 100) + assert report.status == FULLY_VERIFIED + assert report.digits_compared == 100 + + +def test_verify_pi_rejects_corrupted(): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(100) + corrupted = pi[:-1] + ("1" if pi[-1] != "1" else "2") + report = verify_pi(corrupted, 100) + assert report.status == VERIFICATION_FAILED + + +def test_verify_pi_structure_invalid(): + report = verify_pi("not pi", 5) + assert report.status == VERIFICATION_FAILED + + +def test_verify_pi_with_reference(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(100) + ref = tmp_path / "ref.txt" + ref.write_bytes(pi.encode()) # full "3.14159..." format + + report = verify_pi(pi, 100, reference_path=ref) + assert report.status == FULLY_VERIFIED + + +# --------------------------------------------------------------------------- +# Corruption detection (full-file verification) +# --------------------------------------------------------------------------- + +def _make_calc_ref_pair(tmp_path, decimal_digits: str, corrupt_ref: bool = False): + """Write a calculated file and matching reference file.""" + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(len(decimal_digits)) + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(pi.encode()) + ref.write_bytes(pi.encode()) + return calc, ref - ok = v.verify_full(calc, ref) - assert ok is True +def test_verify_corrupted_digit_near_beginning(tmp_path): + from piproject.compute import calculate_pi -def test_verify_full_mismatch(tmp_path): + pi, _ = calculate_pi(100) + # Corrupt the 3rd decimal digit (position 3) + corrupted = pi[:4] + ("9" if pi[4] != "9" else "8") + pi[5:] + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(corrupted.encode()) + ref.write_bytes(pi.encode()) + + report = verify_pi_file(calc, ref) + assert report.status == VERIFICATION_FAILED + assert report.digits_mismatched > 0 + assert report.first_mismatch_position is not None + assert report.first_mismatch_position < 10 + + +def test_verify_corrupted_digit_around_1001(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(2000) + # Corrupt a digit around position 1001 in the decimal part. + # In the normalized file (dots removed), the integer part "3" occupies + # position 0, so decimal index 1001 corresponds to normalized position 1002. + idx = 1001 # position in decimal part + orig = pi[idx + 2] # +2 for "3." + repl = "9" if orig != "9" else "8" + corrupted = pi[: idx + 2] + repl + pi[idx + 3:] calc = tmp_path / "calc.txt" ref = tmp_path / "ref.txt" - _write_digits(calc, "314159") - _write_digits(ref, "314150") # last digit differs + calc.write_bytes(corrupted.encode()) + ref.write_bytes(pi.encode()) - ok = v.verify_full(calc, ref) - assert ok is False + report = verify_pi_file(calc, ref) + assert report.status == VERIFICATION_FAILED + # Normalized position = decimal index + 1 (for the "3" integer part) + assert report.first_mismatch_position == idx + 1 -def test_verify_full_length_mismatch(tmp_path): +def test_verify_corrupted_digit_near_end(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(100) + # Corrupt the last decimal digit + last_idx = len(pi) - 1 + orig = pi[last_idx] + repl = "9" if orig != "9" else "8" + corrupted = pi[:last_idx] + repl calc = tmp_path / "calc.txt" ref = tmp_path / "ref.txt" - _write_digits(calc, "314159") # 6 digits - _write_digits(ref, "3141592653") # 10 digits + calc.write_bytes(corrupted.encode()) + ref.write_bytes(pi.encode()) + + report = verify_pi_file(calc, ref) + assert report.status == VERIFICATION_FAILED + assert report.digits_mismatched >= 1 + + +def test_verify_missing_digits(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(100) + # Truncate the last 10 digits + truncated = pi[:-10] + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(truncated.encode()) + ref.write_bytes(pi.encode()) + + report = verify_pi_file(calc, ref) + assert report.status == VERIFICATION_FAILED + + +def test_verify_extra_digits(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(100) + # Append extra digits + extended = pi + "12345" + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(extended.encode()) + ref.write_bytes(pi.encode()) + + report = verify_pi_file(calc, ref) + assert report.status == VERIFICATION_FAILED + + +def test_verify_truncated_file(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(100) + # Write only half the file + half = pi[: len(pi) // 2] + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(half.encode()) + ref.write_bytes(pi.encode()) + + report = verify_pi_file(calc, ref) + assert report.status == VERIFICATION_FAILED + + +def test_verify_invalid_characters(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(100) + # Insert a letter + invalid = pi[:10] + "x" + pi[11:] + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(invalid.encode()) + ref.write_bytes(pi.encode()) + + report = verify_pi_file(calc, ref) + # normalize_bytes removes dots and whitespace but not letters, + # so the letter 'x' will cause a mismatch + assert report.status == VERIFICATION_FAILED + + +def test_verify_unexpected_whitespace(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(100) + # Insert whitespace in the middle WITHOUT removing a digit + with_space = pi[:10] + " \n\t" + pi[10:] + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(with_space.encode()) + ref.write_bytes(pi.encode()) + + report = verify_pi_file(calc, ref) + # normalize_bytes removes whitespace, so this should still match + assert report.status == FULLY_VERIFIED - ok = v.verify_full(calc, ref) - assert ok is False +def test_verify_incorrect_decimal_point_placement(tmp_path): + from piproject.compute import calculate_pi -def test_verify_full_formatting_insensitive(tmp_path): + pi, _ = calculate_pi(100) + # Move the decimal point + wrong_point = pi.replace(".", "", 1) + ".5" calc = tmp_path / "calc.txt" ref = tmp_path / "ref.txt" - # Different formatting (spaces/newlines/dots) but same digits. - _write_digits(calc, "3.14159\n26535") - _write_digits(ref, "31 41 59 26 535") + calc.write_bytes(wrong_point.encode()) + ref.write_bytes(pi.encode()) - ok = v.verify_full(calc, ref) - assert ok is True + report = verify_pi_file(calc, ref) + assert report.status == VERIFICATION_FAILED # --------------------------------------------------------------------------- -# main argument handling (no network) +# BBP decimal-to-hex relationship tests # --------------------------------------------------------------------------- -import sys +def test_bbp_vs_decimal_match(): + import sys + + sys.set_int_max_str_digits(100000) + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(5000) + _, _, decimal_digits = pi.partition(".") + + # Decimal precision (5000) supports hex positions up to ~5000/1.21 ≈ 4132 + results = bbp_vs_decimal(decimal_digits, [1, 10, 100, 120], num_digits=5) + for pos, (bbp, dec_hex, match) in results.items(): + assert match is True, f"Position {pos}: BBP={bbp} dec_hex={dec_hex}" + + +def test_bbp_vs_decimal_insufficient_precision(): + from piproject.bbp import bbp_vs_decimal + + # Only 10 decimal digits — not enough to resolve hex position 100 + results = bbp_vs_decimal("1415926535", [100], num_digits=5) + bbp, dec_hex, match = results[100] + assert match is False + assert dec_hex.startswith("ERROR:") + + +def test_decimal_to_hex_at_known_positions(): + from piproject.bbp import decimal_to_hex_at + + # Known hex digits of pi: 243f6a8885a308d313198a2e03707344... + # Use enough decimal digits (computed independently) + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(2000) + _, _, decimal_digits = pi.partition(".") + + # Position 1: should be "243f6" + assert decimal_to_hex_at(decimal_digits, 1, 5) == "243f6" + # Position 10: should be "5a308" + assert decimal_to_hex_at(decimal_digits, 10, 5) == "5a308" + # Position 100: should be "c29b7" + assert decimal_to_hex_at(decimal_digits, 100, 5) == "c29b7" + + +def test_verify_pi_report_is_serializable(): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(50) + report = verify_pi(pi, 50) + d = report.to_dict() + assert "status" in d + assert "digits_compared" in d + j = report.to_json() + assert isinstance(j, str) + + +# --------------------------------------------------------------------------- +# BBP spot checks +# --------------------------------------------------------------------------- + +def test_verify_bbp_spot_checks(): + report = verify_mod.verify_bbp_spot_checks([1, 10, 100]) + assert report.status == INDEPENDENTLY_VERIFIED + assert report.details["all_match"] is True + + +def test_verify_bbp_spot_checks_single(): + report = verify_mod.verify_bbp_spot_checks([1]) + assert report.status == INDEPENDENTLY_VERIFIED + + +# --------------------------------------------------------------------------- +# verify_pi_file +# --------------------------------------------------------------------------- + +def test_verify_pi_file_match(tmp_path): + from piproject.compute import calculate_pi + + pi, _ = calculate_pi(100) + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + calc.write_bytes(pi.encode()) + ref.write_bytes(pi.encode()) + + report = verify_pi_file(calc, ref) + assert report.status == FULLY_VERIFIED + + +def test_verify_pi_file_missing(tmp_path): + report = verify_pi_file(tmp_path / "nonexistent.txt", tmp_path / "ref.txt") + assert report.status == VERIFICATION_FAILED + + +# --------------------------------------------------------------------------- +# VerificationReport +# --------------------------------------------------------------------------- +def test_verification_report_is_fully_verified(): + # Only FULLY_VERIFIED means every digit was compared against a reference. + r = VerificationReport(status=FULLY_VERIFIED) + assert r.is_fully_verified() is True -def _run_main(argv): - old_argv = sys.argv - sys.argv = argv - try: - return v.main() - finally: - sys.argv = old_argv + # INDEPENDENTLY_VERIFIED (e.g. BBP spot checks) confirms the algorithm at + # sampled positions only and is NOT full verification of the output. + r = VerificationReport(status=INDEPENDENTLY_VERIFIED) + assert r.is_fully_verified() is False + r = VerificationReport(status=PREFIX_VERIFIED) + assert r.is_fully_verified() is False -def test_main_missing_calculated_file(): - code = _run_main(["verify.py", "--calculated", "does_not_exist.txt"]) - assert code == 1 + r = VerificationReport(status=VERIFICATION_FAILED) + assert r.is_fully_verified() is False + r = VerificationReport(status=STRUCTURE_VALID) + assert r.is_fully_verified() is False -def test_main_missing_local_reference(): - code = _run_main( - ["verify.py", "--calculated", "does_not_exist.txt", - "--reference", "no_such_ref.txt"] - ) - assert code == 1 + r = VerificationReport(status=CALCULATED) + assert r.is_fully_verified() is False diff --git a/verify.py b/verify.py deleted file mode 100644 index 92eb85c..0000000 --- a/verify.py +++ /dev/null @@ -1,452 +0,0 @@ -import argparse -import hashlib -import sys -import time -import urllib.error -import urllib.request -from pathlib import Path - - -# ============================================================================ -# PiProject v4 -# Full Reference Verification -# ============================================================================ - -REFERENCE_URL = "https://files.pilookup.com/pi/10000000.txt" - -CALCULATED_FILE = "pi_10000000.txt" -REFERENCE_FILE = "reference_pi.txt" - -CHUNK_SIZE = 1024 * 1024 # 1 MB - -# Network behaviour. -DOWNLOAD_TIMEOUT = 60 # seconds per read attempt -DOWNLOAD_RETRIES = 3 # total download attempts -DOWNLOAD_BACKOFF_BASE = 2 # seconds, doubled after each failure - - -# ============================================================================ -# Download Reference -# ============================================================================ - -def sha256_file(filename): - """Return the SHA-256 hex digest of a file (streamed, constant memory).""" - - digest = hashlib.sha256() - with open(filename, "rb", buffering=CHUNK_SIZE) as f: - for chunk in iter(lambda: f.read(CHUNK_SIZE), b""): - digest.update(chunk) - return digest.hexdigest() - - -def download_reference(filename=REFERENCE_FILE): - """Download the reference pi file with retries and backoff. - - Reuses an existing local reference file instead of re-downloading. - Returns the local path on success, or None on failure. - """ - - if Path(filename).exists(): - size = Path(filename).stat().st_size - print(f"\nUsing existing local reference: {filename} ({size:,} bytes)") - return filename - - print("\nDownloading reference...") - print(f"URL: {REFERENCE_URL}") - - last_error = None - - for attempt in range(1, DOWNLOAD_RETRIES + 1): - - start = time.perf_counter() - - request = urllib.request.Request( - REFERENCE_URL, - headers={ - "User-Agent": ( - "PiProject/1.0 (+https://github.com/zomop/PiProject)" - ), - "Accept": "*/*", - "Connection": "keep-alive", - }, - ) - - try: - - with urllib.request.urlopen( - request, - timeout=DOWNLOAD_TIMEOUT, - ) as response: - - total = response.headers.get("Content-Length") - if total: - total = int(total) - print(f"Expected size : {total:,} bytes") - - downloaded = 0 - - with open( - filename, - "wb", - buffering=CHUNK_SIZE, - ) as f: - - while True: - - chunk = response.read(CHUNK_SIZE) - - if not chunk: - break - - f.write(chunk) - downloaded += len(chunk) - - if total: - percent = (downloaded / total) * 100 - if sys.stderr.isatty(): - print( - f"\rDownloading: " - f"{percent:6.2f}% " - f"({downloaded:,} bytes)", - end="", - flush=True, - ) - else: - # Non-TTY (CI / captured logs): one line per MB. - if ( - downloaded // CHUNK_SIZE - > (downloaded - len(chunk)) // CHUNK_SIZE - ): - print( - f"Downloaded: {downloaded:,} bytes" - ) - else: - if sys.stderr.isatty(): - print( - f"\rDownloaded: " - f"{downloaded:,} bytes", - end="", - flush=True, - ) - - print() - - except urllib.error.HTTPError as e: - last_error = f"HTTP Error {e.code}: {e.reason}" - print(f"\n❌ {last_error} (attempt {attempt}/{DOWNLOAD_RETRIES})") - except urllib.error.URLError as e: - last_error = f"Connection error: {e.reason}" - print(f"\n❌ {last_error} (attempt {attempt}/{DOWNLOAD_RETRIES})") - except TimeoutError: - last_error = "Download timed out" - print(f"\n❌ {last_error} (attempt {attempt}/{DOWNLOAD_RETRIES})") - except OSError as e: - last_error = f"File error: {e}" - print(f"\n❌ {last_error} (attempt {attempt}/{DOWNLOAD_RETRIES})") - - if Path(filename).exists(): - # A partial file may remain; remove it before retrying. - try: - Path(filename).unlink() - except OSError: - pass - - if attempt < DOWNLOAD_RETRIES: - backoff = DOWNLOAD_BACKOFF_BASE ** attempt - print(f"Retrying in {backoff}s...") - time.sleep(backoff) - - elapsed = time.perf_counter() - start - - print(f"\n❌ Reference download failed after {DOWNLOAD_RETRIES} attempts.") - if last_error: - print(f"Last error: {last_error}") - print("Verification cancelled.") - - return None - - -# ============================================================================ -# Normalize a chunk -# ============================================================================ - -def normalize_chunk(data): - - """ - Remove formatting characters so both files can be compared regardless of - whether they contain: - - 3.14159265... - - or: - - 314159265... - - Whitespace/newlines are also ignored. - """ - - if isinstance(data, bytes): - data = data.replace(b"\r", b"") - data = data.replace(b"\n", b"") - data = data.replace(b" ", b"") - data = data.replace(b"\t", b"") - data = data.replace(b".", b"") - - return data - - -# ============================================================================ -# Count digits -# ============================================================================ - -def count_digits(filename): - - """Count the normalized digits in a file.""" - - total = 0 - - with open( - filename, - "rb", - buffering=CHUNK_SIZE, - ) as f: - - while True: - - chunk = f.read(CHUNK_SIZE) - - if not chunk: - break - - chunk = normalize_chunk(chunk) - - total += len(chunk) - - return total - - -# ============================================================================ -# Full Verification -# ============================================================================ - -def verify_full(calculated_file, reference_file): - - print() - print("=" * 60) - print(" VERIFICATION") - print("=" * 60) - - print(f"Calculated file : {calculated_file}") - print(f"Reference file : {reference_file}") - - print("\nComparing files...") - - start = time.perf_counter() - - matched = 0 - mismatched = 0 - first_mismatch = None - - calculated_digits = 0 - reference_digits = 0 - - with open(calculated_file, "rb", buffering=CHUNK_SIZE) as calculated, \ - open(reference_file, "rb", buffering=CHUNK_SIZE) as reference: - - calculated_data = b"" - reference_data = b"" - - while True: - - # Fill calculated buffer - if not calculated_data: - raw = calculated.read(CHUNK_SIZE) - if raw: - calculated_data = normalize_chunk(raw) - - # Fill reference buffer - if not reference_data: - raw = reference.read(CHUNK_SIZE) - if raw: - reference_data = normalize_chunk(raw) - - # Both ended - if not calculated_data and not reference_data: - break - - # One ended before the other - if not calculated_data: - extra = len(reference_data) - mismatched += extra - if first_mismatch is None: - first_mismatch = matched + mismatched - extra - reference_digits += extra - reference_data = b"" - continue - - if not reference_data: - extra = len(calculated_data) - mismatched += extra - if first_mismatch is None: - first_mismatch = matched + mismatched - extra - calculated_digits += extra - calculated_data = b"" - continue - - # Compare available bytes - length = min(len(calculated_data), len(reference_data)) - - c = calculated_data[:length] - r = reference_data[:length] - - # Fast equality path - if c == r: - matched += length - else: - # Find exact mismatches - for i in range(length): - if c[i] == r[i]: - matched += 1 - else: - mismatched += 1 - if first_mismatch is None: - first_mismatch = matched + mismatched - 1 - - calculated_digits += length - reference_digits += length - - calculated_data = calculated_data[length:] - reference_data = reference_data[length:] - - # Progress every ~1 MB (TTY only; CI logs stay readable) - total_processed = min(calculated_digits, reference_digits) - if sys.stderr.isatty() and total_processed // CHUNK_SIZE > ( - (total_processed - length) // CHUNK_SIZE - ): - print( - f"\rCompared: {total_processed:,} digits", - end="", - flush=True, - ) - - print("\n") - - print(f"Calculated : {calculated_digits:,}") - print(f"Reference : {reference_digits:,}") - print(f"Matched : {matched:,}") - print(f"Mismatched : {mismatched:,}") - - elapsed = time.perf_counter() - start - print(f"\nVerification time: {elapsed:.4f} seconds") - - # -------------------------------------------------------- - # Result - # -------------------------------------------------------- - - if mismatched == 0 and calculated_digits == reference_digits: - print() - print("✅ VERIFIED!") - print(f"All {matched:,} digits match the reference.") - return True - - print() - print("❌ VERIFICATION FAILED!") - - if first_mismatch is not None: - print(f"First mismatch position: {first_mismatch:,}") - - if calculated_digits != reference_digits: - print("\n⚠️ The files have a different number of digits.") - - return False - - -# ============================================================================ -# Main -# ============================================================================ - -def parse_args(): - parser = argparse.ArgumentParser( - description="Compare a calculated pi file with a reference file." - ) - parser.add_argument( - "--calculated", - default=CALCULATED_FILE, - help=f"calculated file to verify (default: {CALCULATED_FILE})", - ) - parser.add_argument( - "--reference", - help="use an existing reference file instead of downloading one", - ) - parser.add_argument( - "--sha256", - help="expected SHA-256 of the reference file (establish from a trusted source)", - ) - return parser.parse_args() - - -def main(): - args = parse_args() - calculated_file = args.calculated - - print("=" * 60) - print(" PiProject v4") - print(" FULL VERIFICATION") - print("=" * 60) - - # -------------------------------------------------------- - # Check calculated file - # -------------------------------------------------------- - - if not Path(calculated_file).exists(): - print(f"\n❌ File not found: {calculated_file}") - return 1 - - calculated_size = Path(calculated_file).stat().st_size - print(f"\nCalculated file size: {calculated_size:,} bytes") - - # -------------------------------------------------------- - # Resolve reference file - # -------------------------------------------------------- - - if args.reference: - reference_file = args.reference - if not Path(reference_file).exists(): - print(f"\n❌ Reference file not found: {reference_file}") - return 1 - print(f"\nUsing local reference: {reference_file}") - else: - reference_file = download_reference() - - if reference_file is None: - print("\n❌ Reference could not be obtained.") - return 1 - - # -------------------------------------------------------- - # Optional SHA-256 integrity check - # -------------------------------------------------------- - - if args.sha256: - actual = sha256_file(reference_file) - if actual.lower() != args.sha256.lower(): - print(f"\n❌ SHA-256 mismatch for reference file.") - print(f" expected: {args.sha256}") - print(f" actual: {actual}") - return 1 - print(f"\nSHA-256 verified: {actual}") - - # -------------------------------------------------------- - # Verify - # -------------------------------------------------------- - - ok = verify_full(calculated_file, reference_file) - - return 0 if ok else 1 - - -# ============================================================================ -# Start -# ============================================================================ - -if __name__ == "__main__": - sys.exit(main())