"""Tests for encoder.py. Run with: python -m pytest -q""" from __future__ import annotations import numpy as np import pytest from encoder import (COUNTS_PER_REV, DEG_PER_COUNT, MAX_COUNT, average_reads, counts_to_degrees, degrees_to_counts, simulate_reads) def test_resolution_is_12_bit() -> None: assert COUNTS_PER_REV == 4096 assert MAX_COUNT == 4095 assert DEG_PER_COUNT == pytest.approx(0.087890625) def test_mid_count_is_zero_degrees() -> None: assert counts_to_degrees(2048) == pytest.approx(0.0) assert counts_to_degrees(2048 + 1024) == pytest.approx(90.0) assert counts_to_degrees(2048 - 1024) == pytest.approx(-90.0) def test_custom_mid() -> None: assert counts_to_degrees(2100, mid=2100) == pytest.approx(0.0) assert int(degrees_to_counts(0.0, mid=2100)) == 2100 def test_round_trip_within_half_a_count() -> None: angles = np.linspace(-170.0, 170.0, 1001) back = counts_to_degrees(degrees_to_counts(angles)) assert np.max(np.abs(back - angles)) <= DEG_PER_COUNT / 2 + 1e-12 def test_counts_are_clipped() -> None: assert int(degrees_to_counts(400.0)) == MAX_COUNT assert int(degrees_to_counts(-400.0)) == 0 def test_reads_are_integers_in_range() -> None: rng = np.random.default_rng(0) reads = simulate_reads(175.0, 500, noise_counts=5.0, rng=rng) assert reads.dtype == np.int64 assert reads.min() >= 0 and reads.max() <= MAX_COUNT def test_reads_are_reproducible_with_seed() -> None: a = simulate_reads(30.0, 50, 2.0, np.random.default_rng(42)) b = simulate_reads(30.0, 50, 2.0, np.random.default_rng(42)) assert np.array_equal(a, b) def test_noise_free_read_is_the_nearest_count() -> None: reads = simulate_reads(30.0, 10, noise_counts=0.0, rng=np.random.default_rng(1)) assert np.all(reads == degrees_to_counts(30.0)) def test_mean_is_unbiased_and_noise_matches() -> None: rng = np.random.default_rng(3) reads = simulate_reads(30.0, 20000, noise_counts=2.0, rng=rng) angles = counts_to_degrees(reads) assert angles.mean() == pytest.approx(30.0, abs=0.01) # 2 counts of Gaussian noise plus rounding (variance 1/12 count^2) expected_std = np.sqrt(2.0**2 + 1.0 / 12.0) * DEG_PER_COUNT assert angles.std(ddof=1) == pytest.approx(expected_std, rel=0.03) def test_averaging_reduces_std_by_sqrt_n() -> None: rng = np.random.default_rng(5) reads = simulate_reads(-45.0, 64000, noise_counts=3.0, rng=rng) single = counts_to_degrees(reads).std(ddof=1) avg16 = average_reads(reads, 16).std(ddof=1) assert avg16 == pytest.approx(single / 4.0, rel=0.05) def test_average_needs_a_full_window() -> None: with pytest.raises(ValueError): average_reads(np.array([2048, 2049]), window=4)