diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5ed4cf3 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + pip install -r requirements-dev.txt + + - name: Run test suite + run: | + python -m pytest + + - name: End-to-end calculation (1,000 digits) + 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 + run: | + python verify.py \ + --calculated /tmp/pi_1000_calculated.txt \ + --reference tests/fixtures/pi_1000_reference.txt diff --git a/.gitignore b/.gitignore index 335f186..616b5dc 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,10 @@ venv/ env/ *.log -*.tmp \ No newline at end of file +*.tmp + +# Generated pi output (can be tens of MB) — do not commit. +pi_*.txt + +# Downloaded reference file (10 MB) — do not commit. +reference_pi.txt \ No newline at end of file diff --git a/README.md b/README.md index 210c83d..688489c 100644 --- a/README.md +++ b/README.md @@ -58,21 +58,40 @@ pip install -r requirements.txt ## Usage -Run the latest π calculator: +### Recommended calculator: `pi_project_v4.py` + +Run the latest π calculator (Chudnovsky + binary splitting + GMPY2): ```bash python pi_project_v4.py ``` -The program calculates π using the Chudnovsky algorithm and saves the result to a text file. +The program prompts for the number of digits, calculates π, verifies it, and saves the result to `pi_.txt`. + +Non-interactive mode (useful for scripting and CI): + +```bash +python pi_project_v4.py --digits 1000 --output pi_1000.txt +``` + +Options: + +- `--digits N` number of decimal digits of π to calculate +- `--output FILE` output file (default: `pi_.txt`) + +### Verification -To verify the calculated result: +To verify a calculated result against a reference: ```bash python verify.py ``` -The verification tool compares the calculated digits against a reference and reports the number of matched and mismatched digits. +This downloads a 10,000,000-digit reference and compares it to `pi_10000000.txt`. Use `--reference` to supply a local reference file instead, and `--sha256` to validate the reference's integrity. The expected SHA-256 must be established from a trusted source. + +```bash +python verify.py --calculated pi_1000.txt --reference tests/fixtures/pi_1000_reference.txt --sha256 +``` ### Example @@ -98,6 +117,18 @@ Verification time: 0.0474 seconds The result contains **10,000,000 characters** including the `3` before the decimal point. +## Calculators compared + +PiProject ships three implementations. Use `pi_project_v4.py` unless you have a specific reason not to. + +| 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 much slower and heavier RAM than v4 at scale. | +| `pie.py` | Machin-like arctan | Python stdlib (`decimal`) | Small digit counts only | Legacy, O(digits²). Impractical beyond a few thousand digits. | + +`pi_v3.py` and `pie.py` are kept for reference and are not covered by the CI performance path. + ## Contributing Contributions are welcome! Please follow these steps: diff --git a/pi_project_v4.py b/pi_project_v4.py index 4b1be14..b58fbab 100644 --- a/pi_project_v4.py +++ b/pi_project_v4.py @@ -1,10 +1,9 @@ -import gmpy2 -import time +import argparse import sys +import time from pathlib import Path -gmpy2.get_context().precision = 128 - +import gmpy2 # ============================================================ # PiProject v4 @@ -12,16 +11,43 @@ # 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. + Returns P, Q, T for the range [a, b). """ if b - a == 1: @@ -62,25 +88,23 @@ def binary_split(a, b): 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 ≈ 14 digits / term + # Chudnovsky yields roughly 14 digits per term. terms = digits // 14 + 1 - print() - print(f"Terms required : {terms:,}") - print("Running binary splitting...") - P, Q, T = binary_split(0, terms) - print("Binary splitting complete.") - print("Calculating square root...") - # Scale factor: # pi = 426880 * sqrt(10005) * Q / T - # - # Use GMP integer arithmetic instead of Decimal. - + # 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( @@ -95,17 +119,26 @@ def calculate_pi(digits): pi_scaled = numerator // T - # Convert scaled integer into decimal representation + # 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) - # Remove guard digits - s = s[:-20] + # Discard the 20 guard digits from the fractional (right) end. + guard = 20 + if len(s) > guard: + s = s[:-guard] - if len(s) <= digits: - s = s.zfill(digits + 1) + # 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[:-digits] - decimal_part = s[-digits:] + integer_part = s[0] + decimal_part = s[1:] pi_string = integer_part + "." + decimal_part @@ -116,113 +149,144 @@ def calculate_pi(digits): def verify_pi(pi_string, digits): """ - Basic sanity verification: - - correct decimal length - - starts with known 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. """ - expected_prefix = ( - "3.14159265358979323846264338327950288419716939937510" - ) + if not isinstance(pi_string, str) or "." not in pi_string: + return False + + integer_part, _, decimal_part = pi_string.partition(".") - if not pi_string.startswith(expected_prefix): + if integer_part != "3": return False - if len(pi_string.split(".")[1]) != digits: + 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 = Path(f"pi_{digits}.txt") +def save_pi(pi_string, digits, filename=None): + output = Path(filename) if filename else Path(f"pi_{digits}.txt") - print(f"Saving: {filename}") + print(f"Saving: {output}") - with filename.open( + with output.open( "w", encoding="ascii", buffering=1024 * 1024, ) as f: f.write(pi_string) - return filename + return output -def main(): +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) - print("=" * 60) - print(" PiProject v4") - print(" Chudnovsky + Binary Splitting + GMP") - print("=" * 60) - try: - digits = int( - input("\nBerapa digit π yang ingin dihitung? ") - ) +def main(argv=None): + args = parse_args(argv) - except ValueError: - print("\n❌ Input harus berupa angka.") - return + 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("\n❌ Digit harus lebih dari 0.") - return + print("Number of digits must be greater than 0.") + return 1 if digits > 10_000_000: print( - "\n⚠️ Target lebih dari 10 juta digit " - "bisa membutuhkan RAM besar." + "Warning: more than 10 million digits " + "may require large RAM." ) - confirm = input( - "Tetap lanjut? (y/n): " - ).strip().lower() + try: + confirm = input("Continue? (y/n): ").strip().lower() + except EOFError: + print("Cancelled.") + return 1 if confirm != "y": - print("Dibatalkan.") - return + print("Cancelled.") + return 1 - print("\nCalculating π...") + print("\nCalculating pi...") print("Method: Chudnovsky + Binary Splitting + GMP") try: pi, elapsed = calculate_pi(digits) - except MemoryError: - print("\n❌ RAM tidak cukup.") - return - + print("\nNot enough RAM.") + return 1 except Exception as e: - print("\n❌ Calculation error:") + print("\nCalculation error:") print(type(e).__name__, e) - return + return 1 - print("\nCalculation complete.") + print("Calculation complete.") # -------------------------------------------------------- # Verification # -------------------------------------------------------- - print("\nVerifying...") - - verified = verify_pi(pi, digits) + print("Verifying...") - if not verified: - print("❌ Verification FAILED!") - return + if not verify_pi(pi, digits): + print("Verification FAILED!") + return 1 # -------------------------------------------------------- # Save # -------------------------------------------------------- try: - filename = save_pi(pi, digits) - + filename = save_pi(pi, digits, filename=args.output) except OSError as e: - print("\n❌ Gagal menyimpan file:") + print("Failed to save file:") print(e) - return + return 1 # -------------------------------------------------------- # Statistics @@ -239,7 +303,7 @@ def main(): print() print("=" * 60) - print(" RESULT") + print("RESULT") print("=" * 60) print(f"Digits requested : {digits:,}") @@ -253,13 +317,15 @@ def main(): print("=" * 60) - print("\nπ preview:") + print("\npi preview:") print(pi[:120] + "...") print("\n" + "=" * 60) - print("✅ VERIFIED!") + print("VERIFIED!") print("=" * 60) + return 0 + if __name__ == "__main__": - main() \ No newline at end of file + sys.exit(main()) diff --git a/pie.py b/pie.py index db3550e..7c7334d 100644 --- a/pie.py +++ b/pie.py @@ -1,9 +1,20 @@ 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 untuk mencegah error di digit terakhir + # Extra precision to avoid error in the last digits. getcontext().prec = digits + 20 start = time.perf_counter() @@ -39,56 +50,64 @@ def arctan_inverse(n): elapsed = time.perf_counter() - start - # Tepat jumlah digit yang diminta + # Exactly the requested number of digits. pi = format(pi, f".{digits}f") return pi, elapsed -# ========================= -# PiProject -# ========================= +def main(argv=None): -print("=== PiProject ===") -print("Real π Calculator\n") + print("=== PiProject ===") + print("Real π Calculator\n") -try: - digits = int(input("Berapa digit π? ")) + try: + digits = int(input("How many digits of pi? ")) - if digits <= 0: - raise ValueError("Jumlah digit harus lebih dari 0.") + if digits <= 0: + raise ValueError("Number of digits must be greater than 0.") -except ValueError: - print("Input tidak valid.") - exit() + except ValueError: + print("Invalid input.") + return 1 + except EOFError: + print("Input stream closed.") + return 1 + print("\nCalculating...") + print("Please wait...\n") -print("\nCalculating...") -print("Mohon tunggu...\n") + pi, elapsed = calculate_pi(digits) -pi, elapsed = calculate_pi(digits) + # ========================= + # Save result + # ========================= + filename = f"pi_{digits}.txt" -# ========================= -# Simpan hasil -# ========================= + with open(filename, "w", encoding="utf-8") as f: + f.write(pi) -filename = f"pi_{digits}.txt" + # ========================= + # Result + # ========================= -with open(filename, "w", encoding="utf-8") as f: - f.write(pi) + 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 # ========================= -# Hasil +# Start # ========================= -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("=========================") \ No newline at end of file +if __name__ == "__main__": + sys.exit(main()) diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..e144ed0 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1 @@ +pytest>=8.0.0 diff --git a/requirements.txt b/requirements.txt index 9e13c8f..9d42b33 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1 @@ -gmpy2 \ No newline at end of file +gmpy2==2.3.2 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..36b9d23 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,55 @@ +"""Shared fixtures and helpers for PiProject tests.""" + +from decimal import Decimal, getcontext + +import pytest + + +@pytest.fixture +def tmp_output(tmp_path): + """Provide a writable output path inside a temporary 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 _reference_pi_decimals diff --git a/tests/fixtures/pi_1000_reference.txt b/tests/fixtures/pi_1000_reference.txt new file mode 100644 index 0000000..9f301e2 --- /dev/null +++ b/tests/fixtures/pi_1000_reference.txt @@ -0,0 +1 @@ +3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989 \ No newline at end of file diff --git a/tests/test_pi_project_v4.py b/tests/test_pi_project_v4.py new file mode 100644 index 0000000..db067e9 --- /dev/null +++ b/tests/test_pi_project_v4.py @@ -0,0 +1,207 @@ +"""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 new file mode 100644 index 0000000..754ec22 --- /dev/null +++ b/tests/test_verify.py @@ -0,0 +1,125 @@ +"""Tests for verify.py (reference comparison).""" + +import hashlib + +import pytest + +import verify as v + + +# --------------------------------------------------------------------------- +# normalize_chunk +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize( + "raw, expected", + [ + (b"3.14159", b"314159"), + (b"3\n.14 15\r\n9\t", b"314159"), + (b"", b""), + (b" ", b""), + (b"..12..34..", b"1234"), + ], +) +def test_normalize_chunk(raw, expected): + assert v.normalize_chunk(raw) == expected + + +# --------------------------------------------------------------------------- +# count_digits +# --------------------------------------------------------------------------- + +def test_count_digits(tmp_path): + p = tmp_path / "digits.txt" + p.write_bytes(b"3.14159\n26535\n") + assert v.count_digits(p) == 11 # 31415926535 + + +# --------------------------------------------------------------------------- +# sha256_file +# --------------------------------------------------------------------------- + +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 + + +# --------------------------------------------------------------------------- +# verify_full +# --------------------------------------------------------------------------- + +def _write_digits(path, digits_str): + path.write_bytes(digits_str.encode("ascii")) + + +def test_verify_full_match(tmp_path): + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + digits = "314159265358979323846264338327950288419716939937510" + _write_digits(calc, digits) + _write_digits(ref, digits) + + ok = v.verify_full(calc, ref) + assert ok is True + + +def test_verify_full_mismatch(tmp_path): + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + _write_digits(calc, "314159") + _write_digits(ref, "314150") # last digit differs + + ok = v.verify_full(calc, ref) + assert ok is False + + +def test_verify_full_length_mismatch(tmp_path): + calc = tmp_path / "calc.txt" + ref = tmp_path / "ref.txt" + _write_digits(calc, "314159") # 6 digits + _write_digits(ref, "3141592653") # 10 digits + + ok = v.verify_full(calc, ref) + assert ok is False + + +def test_verify_full_formatting_insensitive(tmp_path): + 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") + + ok = v.verify_full(calc, ref) + assert ok is True + + +# --------------------------------------------------------------------------- +# main argument handling (no network) +# --------------------------------------------------------------------------- + +import sys + + +def _run_main(argv): + old_argv = sys.argv + sys.argv = argv + try: + return v.main() + finally: + sys.argv = old_argv + + +def test_main_missing_calculated_file(): + code = _run_main(["verify.py", "--calculated", "does_not_exist.txt"]) + assert code == 1 + + +def test_main_missing_local_reference(): + code = _run_main( + ["verify.py", "--calculated", "does_not_exist.txt", + "--reference", "no_such_ref.txt"] + ) + assert code == 1 diff --git a/verify.py b/verify.py index 1f00039..92eb85c 100644 --- a/verify.py +++ b/verify.py @@ -1,14 +1,16 @@ import argparse -import urllib.request -import urllib.error +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" @@ -17,143 +19,162 @@ 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 download_reference(filename=REFERENCE_FILE): - - print("\nDownloading reference...") - print(f"URL: {REFERENCE_URL}") - - start = time.perf_counter() - - request = urllib.request.Request( - REFERENCE_URL, - headers={ - "User-Agent": ( - "Mozilla/5.0 " - "(Windows NT 10.0; Win64; x64) " - "AppleWebKit/537.36 " - "(KHTML, like Gecko) " - "Chrome/138.0.0.0 " - "Safari/537.36" - ), - "Accept": "*/*", - "Connection": "keep-alive", - }, - ) - - try: - - with urllib.request.urlopen( - request, - timeout=120 - ) as response: +# ============================================================================ +# Download Reference +# ============================================================================ - total = response.headers.get("Content-Length") +def sha256_file(filename): + """Return the SHA-256 hex digest of a file (streamed, constant memory).""" - if total: - total = int(total) - print(f"Expected size : {total:,} bytes") + 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() - downloaded = 0 - with open( - filename, - "wb", - buffering=1024 * 1024 - ) as f: +def download_reference(filename=REFERENCE_FILE): + """Download the reference pi file with retries and backoff. - while True: + Reuses an existing local reference file instead of re-downloading. + Returns the local path on success, or None on failure. + """ - chunk = response.read(CHUNK_SIZE) + if Path(filename).exists(): + size = Path(filename).stat().st_size + print(f"\nUsing existing local reference: {filename} ({size:,} bytes)") + return filename - if not chunk: - break + print("\nDownloading reference...") + print(f"URL: {REFERENCE_URL}") - f.write(chunk) + last_error = None - downloaded += len(chunk) + for attempt in range(1, DOWNLOAD_RETRIES + 1): - if total: - percent = ( - downloaded / total - ) * 100 + start = time.perf_counter() - print( - f"\rDownloading: " - f"{percent:6.2f}% " - f"({downloaded:,} bytes)", - end="", - flush=True - ) - else: - print( - f"\rDownloaded: " - f"{downloaded:,} bytes", - end="", - flush=True - ) + request = urllib.request.Request( + REFERENCE_URL, + headers={ + "User-Agent": ( + "PiProject/1.0 (+https://github.com/zomop/PiProject)" + ), + "Accept": "*/*", + "Connection": "keep-alive", + }, + ) - print() + try: - except urllib.error.HTTPError as e: + with urllib.request.urlopen( + request, + timeout=DOWNLOAD_TIMEOUT, + ) as response: - print( - f"\n❌ HTTP Error {e.code}: " - f"{e.reason}" - ) + total = response.headers.get("Content-Length") + if total: + total = int(total) + print(f"Expected size : {total:,} bytes") - return None + downloaded = 0 - except urllib.error.URLError as e: + with open( + filename, + "wb", + buffering=CHUNK_SIZE, + ) as f: - print( - "\n❌ Connection error:" - ) + while True: - print(e.reason) + chunk = response.read(CHUNK_SIZE) - return None + if not chunk: + break - except TimeoutError: + f.write(chunk) + downloaded += len(chunk) - print( - "\n❌ Download timed out." - ) + 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, + ) - return None + print() - elapsed = time.perf_counter() - start + 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})") - size = Path(filename).stat().st_size + if Path(filename).exists(): + # A partial file may remain; remove it before retrying. + try: + Path(filename).unlink() + except OSError: + pass - print( - f"Reference saved : {filename}" - ) + if attempt < DOWNLOAD_RETRIES: + backoff = DOWNLOAD_BACKOFF_BASE ** attempt + print(f"Retrying in {backoff}s...") + time.sleep(backoff) - print( - f"File size : {size:,} bytes" - ) + elapsed = time.perf_counter() - start - print( - f"Download time : {elapsed:.4f} seconds" - ) + print(f"\n❌ Reference download failed after {DOWNLOAD_RETRIES} attempts.") + if last_error: + print(f"Last error: {last_error}") + print("Verification cancelled.") - return filename + return None -# ============================================================ +# ============================================================================ # Normalize a chunk -# ============================================================ +# ============================================================================ def normalize_chunk(data): """ - Remove formatting characters so both files can be - compared regardless of whether they contain: + Remove formatting characters so both files can be compared regardless of + whether they contain: 3.14159265... @@ -165,42 +186,29 @@ def normalize_chunk(data): """ 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"" - ) + 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 + buffering=CHUNK_SIZE, ) as f: while True: @@ -217,31 +225,21 @@ def count_digits(filename): return total -# ============================================================ +# ============================================================================ # Full Verification -# ============================================================ +# ============================================================================ -def verify_full( - calculated_file, - reference_file -): +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(f"Calculated file : {calculated_file}") + print(f"Reference file : {reference_file}") - print( - "\nComparing files..." - ) + print("\nComparing files...") start = time.perf_counter() @@ -252,234 +250,122 @@ def verify_full( calculated_digits = 0 reference_digits = 0 - # -------------------------------------------------------- - # Open both files - # -------------------------------------------------------- - - with open( - calculated_file, - "rb", - buffering=CHUNK_SIZE - ) as calculated: - - with open( - reference_file, - "rb", - buffering=CHUNK_SIZE - ) as reference: - - calculated_data = b"" - reference_data = b"" - - calculated_pos = 0 - reference_pos = 0 - - 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 - ) + with open(calculated_file, "rb", buffering=CHUNK_SIZE) as calculated, \ + open(reference_file, "rb", buffering=CHUNK_SIZE) as reference: - mismatched += extra + calculated_data = b"" + reference_data = b"" - 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 + while True: - if first_mismatch is None: + # Fill calculated buffer + if not calculated_data: + raw = calculated.read(CHUNK_SIZE) + if raw: + calculated_data = normalize_chunk(raw) - first_mismatch = ( - matched - + mismatched - - 1 - ) + # Fill reference buffer + if not reference_data: + raw = reference.read(CHUNK_SIZE) + if raw: + reference_data = normalize_chunk(raw) - calculated_digits += length - reference_digits += length + # Both ended + if not calculated_data and not reference_data: + break - calculated_data = ( - calculated_data[length:] - ) + # 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 - reference_data = ( - reference_data[length:] - ) + calculated_digits += length + reference_digits += length - # Progress every ~1 MB - total_processed = min( - calculated_digits, - reference_digits - ) + 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: " - f"{total_processed:,} digits", + f"\rCompared: {total_processed:,} digits", end="", - flush=True + flush=True, ) - elapsed = time.perf_counter() - start - print("\n") - print( - f"Calculated : {calculated_digits:,}" - ) - - print( - f"Reference : {reference_digits:,}" - ) - - print( - f"Matched : {matched:,}" - ) + print(f"Calculated : {calculated_digits:,}") + print(f"Reference : {reference_digits:,}") + print(f"Matched : {matched:,}") + print(f"Mismatched : {mismatched:,}") - print( - f"Mismatched : {mismatched:,}" - ) - - print( - f"\nVerification time: " - f"{elapsed:.4f} seconds" - ) + elapsed = time.perf_counter() - start + print(f"\nVerification time: {elapsed:.4f} seconds") # -------------------------------------------------------- # Result # -------------------------------------------------------- - if ( - mismatched == 0 - and calculated_digits == reference_digits - ): - + if mismatched == 0 and calculated_digits == reference_digits: print() print("✅ VERIFIED!") - - print( - f"Semua {matched:,} digit " - "cocok dengan reference." - ) - + 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: " - f"{first_mismatch:,}" - ) + print(f"First mismatch position: {first_mismatch:,}") if calculated_digits != reference_digits: - - print( - "\n⚠️ File memiliki jumlah digit " - "yang berbeda." - ) + 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." ) @@ -492,11 +378,14 @@ def parse_args(): "--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 @@ -509,68 +398,55 @@ def main(): # Check calculated file # -------------------------------------------------------- - if not Path( - calculated_file - ).exists(): - - print( - f"\n❌ File tidak ditemukan:" - ) - - print( - calculated_file - ) - - return + 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: " - f"{calculated_size:,} bytes" - ) + calculated_size = Path(calculated_file).stat().st_size + print(f"\nCalculated file size: {calculated_size:,} bytes") # -------------------------------------------------------- - # Download reference + # Resolve reference file # -------------------------------------------------------- if args.reference: reference_file = args.reference if not Path(reference_file).exists(): - print(f"\n❌ Reference file tidak ditemukan: {reference_file}") - return + 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 - print( - "\n❌ Reference gagal di-download." - ) - - print( - "Verification dibatalkan." - ) + # -------------------------------------------------------- + # Optional SHA-256 integrity check + # -------------------------------------------------------- - return + 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 # -------------------------------------------------------- - verify_full( - calculated_file, - reference_file - ) + ok = verify_full(calculated_file, reference_file) + return 0 if ok else 1 -# ============================================================ + +# ============================================================================ # Start -# ============================================================ +# ============================================================================ if __name__ == "__main__": - main() - + sys.exit(main())