"""Enumerate sample-variance estimates for independent draws from {0, 3, 6}."""

import json
from collections import Counter
from fractions import Fraction
from itertools import product
from math import sqrt
from platform import machine, mac_ver, python_version
from statistics import StatisticsError, mean, pvariance, variance

VALUES = (0, 3, 6)
EXACT_VALUES = tuple(map(Fraction, VALUES))
TRUE_MEAN = mean(EXACT_VALUES)
TRUE_VARIANCE = pvariance(EXACT_VALUES)


def squared_deviations(sample, center):
    return sum((value - center) ** 2 for value in sample)


def residual_sum(sample):
    sample_mean = Fraction(sum(sample), len(sample))
    return squared_deviations(sample, sample_mean)


def enumerate_independent(n):
    if n < 2:
        raise ValueError("The n-1 estimator requires at least two observations.")

    residuals = Counter()
    total_known_mean = 0
    total_wrong_mean = 0
    for sample in product(VALUES, repeat=n):
        residuals[residual_sum(sample)] += 1
        total_known_mean += squared_deviations(sample, TRUE_MEAN)
        total_wrong_mean += squared_deviations(sample, TRUE_MEAN + 1)

    count = sum(residuals.values())
    average_residual = sum(total * times for total, times in residuals.items()) / count
    average_known = total_known_mean / (count * n)
    average_wrong = total_wrong_mean / (count * n)
    assert average_residual == (n - 1) * TRUE_VARIANCE
    assert average_known == TRUE_VARIANCE
    assert average_wrong == TRUE_VARIANCE + 1
    return {
        "n": n,
        "ordered_sample_count": count,
        "mean_residual_sum": str(average_residual),
        "mean_divide_by_n": str(average_residual / n),
        "mean_divide_by_n_minus_1": str(average_residual / (n - 1)),
        "mean_using_true_center": str(average_known),
        "mean_using_center_one_unit_too_high": str(average_wrong),
    }, residuals


def two_draw_details(residuals):
    count = sum(residuals.values())
    mse = {}
    for divisor in (2, 1):
        total = sum(times * (value / divisor - TRUE_VARIANCE) ** 2
                    for value, times in residuals.items())
        mse[str(divisor)] = str(total / count)
    average_sd = sum(times * sqrt(value) for value, times in residuals.items()) / count
    assert mse == {"2": "81/4", "1": "45"}
    assert average_sd < sqrt(TRUE_VARIANCE)
    return {
        "residual_sum_counts": {str(value): times for value, times in sorted(residuals.items())},
        "mean_squared_error_by_divisor": mse,
        "mean_sqrt_of_divide_by_n_minus_1": round(average_sd, 8),
        "population_standard_deviation": round(sqrt(TRUE_VARIANCE), 8),
    }


def check_other_cases():
    # Draw once, then copy the draw as the second observation.
    dependent = [(value, value) for value in VALUES]
    dependent_average = sum(residual_sum(pair) for pair in dependent) / len(dependent)
    api_example = [0, 6]
    api_pair = {
        "pvariance": pvariance(api_example),
        "variance": variance(api_example),
    }
    assert api_pair == {"pvariance": 9, "variance": 18}
    known_center_singleton = pvariance([0], mu=3)
    assert known_center_singleton == 9
    assert pvariance([0]) == 0
    assert dependent_average == 0
    try:
        variance([0])
    except StatisticsError:
        singleton_error = "StatisticsError"
    else:
        raise AssertionError("variance([0]) should raise StatisticsError.")

    return {
        "python_sample": api_example,
        "python_sample_results": api_pair,
        "one_observation": {
            "sample": [0],
            "pvariance": pvariance([0]),
            "pvariance_with_true_mean": known_center_singleton,
            "variance_error": singleton_error,
        },
        "copied_observation_pairs": dependent,
        "mean_divide_by_n_minus_1_for_copied_pairs": str(dependent_average),
    }


def main():
    two_draws, residuals = enumerate_independent(2)
    independent = [two_draws]
    for n in (5, 10):
        row, _ = enumerate_independent(n)
        independent.append(row)

    report = {
        "environment": {
            "macOS": mac_ver()[0] or None,
            "machine": machine(),
            "python": python_version(),
        },
        "population": {
            "equiprobable_values": VALUES,
            "mean": str(TRUE_MEAN),
            "variance": str(TRUE_VARIANCE),
        },
        "independent_samples": independent,
        "n_2_details": two_draw_details(residuals),
        "boundary_cases": check_other_cases(),
    }
    print(json.dumps(report, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
