{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "uniform-000",
      "metadata": {},
      "source": [
        "# Обучение равномерного распределения\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-001",
      "metadata": {},
      "outputs": [],
      "source": [
        "%matplotlib inline\n",
        "from pathlib import Path\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "import scipy.stats as st\n",
        "from scipy.special import comb, gammaln, logsumexp\n",
        "\n",
        "SEED = 2026\n",
        "palette = ['#B04A22', '#34758D', '#60834B', '#95609A', '#CE952F']\n",
        "plt.rcParams.update({\n",
        "    'font.family': 'DejaVu Sans', 'font.size': 15,\n",
        "    'axes.labelsize': 16, 'axes.titlesize': 16,\n",
        "    'xtick.labelsize': 13, 'ytick.labelsize': 13, 'legend.fontsize': 13,\n",
        "    'figure.figsize': (10, 5.5), 'figure.dpi': 120,\n",
        "    'axes.spines.top': False, 'axes.spines.right': False,\n",
        "    'axes.grid': True, 'grid.alpha': .22,\n",
        "    'axes.prop_cycle': plt.cycler(color=palette),\n",
        "    'text.usetex': False, 'pdf.fonttype': 42,\n",
        "})\n",
        "FIG_DIR = (Path('SPSUML-2026') if Path('SPSUML-2026').is_dir() else Path('.')) / '09-uniform-figs'\n",
        "FIG_DIR.mkdir(parents=True, exist_ok=True)\n",
        "\n",
        "def show(name):\n",
        "    fig = plt.gcf()\n",
        "    for ax in fig.axes:\n",
        "        ax.set_ylim(bottom=0)\n",
        "    fig.tight_layout()\n",
        "    fig.savefig(FIG_DIR / (name + '.pdf'), bbox_inches='tight')\n",
        "    fig.savefig(FIG_DIR / (name + '.png'), dpi=180, bbox_inches='tight')\n",
        "    plt.show()\n",
        "    plt.close(fig)\n",
        "\n",
        "def log_binom(N, k):\n",
        "    N = np.asarray(N, dtype=float)\n",
        "    return gammaln(N + 1) - gammaln(k + 1) - gammaln(N - k + 1)\n",
        "\n",
        "def tank_posterior(N_values, M, k):\n",
        "    N_values = np.asarray(N_values)\n",
        "    result = np.zeros(N_values.shape, dtype=float)\n",
        "    valid = N_values >= M\n",
        "    result[valid] = (k - 1) / M * np.exp(log_binom(M, k) - log_binom(N_values[valid], k))\n",
        "    return result\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "uniform-002",
      "metadata": {},
      "source": [
        "## 1. Серийные номера: распределение максимума\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-003",
      "metadata": {},
      "outputs": [],
      "source": [
        "N, num_samples = 100, 150000\n",
        "k_values = [1, 2, 3, 5]\n",
        "rng = np.random.default_rng(SEED)\n",
        "serial_sample = np.array([rng.choice(N, size=max(k_values), replace=False) + 1\n",
        "                          for _ in range(num_samples)])\n",
        "\n",
        "fig, ax = plt.subplots()\n",
        "for i, k in enumerate(k_values):\n",
        "    maxima = serial_sample[:, :k].max(axis=1)\n",
        "    counts = np.bincount(maxima, minlength=N + 1)[1:]\n",
        "    ax.plot(np.arange(1, N + 1), counts / num_samples, color=palette[i], label=f'k = {k}')\n",
        "    ax.fill_between(np.arange(1, N + 1), counts / num_samples, color=palette[i], alpha=.15)\n",
        "ax.axvline(N, color='black', ls=':', label=f'Истинное N = {N}')\n",
        "ax.set(xlim=(1, N * 1.04), xlabel='Максимум выборки M', ylabel='Вероятность')\n",
        "ax.legend(loc='upper left')\n",
        "show('01-maximum-distribution')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "uniform-004",
      "metadata": {},
      "source": [
        "## 2. Несмещённая оценка\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-005",
      "metadata": {},
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots()\n",
        "for i, k in enumerate(k_values):\n",
        "    maxima = serial_sample[:, :k].max(axis=1)\n",
        "    values, counts = np.unique(maxima * (k + 1) / k - 1, return_counts=True)\n",
        "    ax.plot(np.r_[values, values[-1] + 1], np.r_[counts / num_samples, 0],\n",
        "            color=palette[i], label=f'k = {k}')\n",
        "    ax.fill_between(np.r_[values, values[-1] + 1], np.r_[counts / num_samples, 0],\n",
        "                    color=palette[i], alpha=.15)\n",
        "ax.axvline(N, color='black', ls=':', label=f'Истинное N = {N}')\n",
        "ax.set(xlim=(1, 2 * N), xlabel=r'Значение оценки $\\hat N$', ylabel='Вероятность')\n",
        "ax.legend(loc='upper left')\n",
        "show('02-unbiased-estimator')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "uniform-006",
      "metadata": {},
      "source": [
        "## 3. Три оценки на одних данных\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-007",
      "metadata": {},
      "outputs": [],
      "source": [
        "k_compare = 5\n",
        "assert 2 < k_compare <= serial_sample.shape[1]\n",
        "maxima = serial_sample[:, :k_compare].max(axis=1)\n",
        "estimates = {\n",
        "    'Максимум M': maxima,\n",
        "    'Несмещённая оценка': maxima * (k_compare + 1) / k_compare - 1,\n",
        "    'Апостериорное среднее': (k_compare - 1) / (k_compare - 2) * (maxima - 1),\n",
        "}\n",
        "fig, ax = plt.subplots()\n",
        "bins = np.linspace(0, max(v.max() for v in estimates.values()) * 1.03, 55)\n",
        "for i, (label, estimate) in enumerate(estimates.items()):\n",
        "    ax.hist(estimate, bins=bins, density=True, histtype='stepfilled', lw=2, alpha=.23,\n",
        "            color=palette[i], edgecolor=palette[i], label=f'{label}: среднее {estimate.mean():.1f}')\n",
        "    print(f'{label}: среднее {estimate.mean():.2f}; смещение {estimate.mean()-N:+.2f}; '\n",
        "          f'RMSE {np.sqrt(np.mean((estimate-N)**2)):.2f}')\n",
        "ax.axvline(N, color='black', ls=':', label=f'Истинное N = {N}')\n",
        "ax.set(xlabel=r'Значение оценки $\\hat N$', ylabel='Эмпирическая плотность', title=f'Одинаковые выборки, k = {k_compare}')\n",
        "ax.legend(loc='upper left')\n",
        "show('03-estimator-comparison')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "uniform-008",
      "metadata": {},
      "source": [
        "## 4. Апостериорное распределение числа танков\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-009",
      "metadata": {},
      "outputs": [],
      "source": [
        "M_fixed = 10\n",
        "N_grid = np.arange(2, 61)\n",
        "fig, axes = plt.subplots(1, 2, figsize=(12, 5))\n",
        "for i, k in enumerate([2, 3, 5]):\n",
        "    axes[0].plot(N_grid, tank_posterior(N_grid, M_fixed, k), 'o-', ms=3,\n",
        "                 color=palette[i], label=f'k = {k}')\n",
        "for i, M_observed in enumerate([10, 15, 20]):\n",
        "    axes[1].plot(N_grid, tank_posterior(N_grid, M_observed, 2), 'o-', ms=3,\n",
        "                 color=palette[i], label=f'M = {M_observed}')\n",
        "axes[0].set(title=f'Максимум M = {M_fixed}', xlim=(8, 40))\n",
        "axes[1].set(title='Размер выборки k = 2', xlim=(8, 50))\n",
        "for ax in axes:\n",
        "    ax.set(xlabel='Число танков N', ylabel='Апостериорная вероятность')\n",
        "    ax.legend()\n",
        "show('04-tank-posterior')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "uniform-010",
      "metadata": {},
      "source": [
        "## 5. Проверка формулы моделированием: конечный диапазон\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-011",
      "metadata": {},
      "outputs": [],
      "source": [
        "M_sim, k_sim, N_upper, repetitions_per_N = 10, 2, 40, 15000\n",
        "rng = np.random.default_rng(SEED + 1)\n",
        "N_candidates = np.arange(M_sim, N_upper + 1)\n",
        "counts = []\n",
        "for N_candidate in N_candidates:\n",
        "    maxima = np.array([rng.choice(N_candidate, size=k_sim, replace=False).max() + 1\n",
        "                       for _ in range(repetitions_per_N)])\n",
        "    counts.append(np.count_nonzero(maxima == M_sim))\n",
        "empirical = np.asarray(counts, dtype=float)\n",
        "empirical /= empirical.sum()\n",
        "infinite_posterior = tank_posterior(N_candidates, M_sim, k_sim)\n",
        "\n",
        "fig, ax = plt.subplots()\n",
        "ax.step(N_candidates, empirical, where='mid', label=f'Моделирование: N ≤ {N_upper}', color=palette[1])\n",
        "ax.fill_between(N_candidates, empirical, step='mid', alpha=.2, color=palette[1])\n",
        "ax.plot(N_candidates, infinite_posterior, 'o-', ms=4, color=palette[0], label='Формула: N без верхней границы')\n",
        "ax.set(xlim=(M_sim - 2, N_upper), xlabel='Число танков N', ylabel='Апостериорная вероятность')\n",
        "ax.legend()\n",
        "print(f'Вероятность N ≤ {N_upper} по бесконечной модели: {infinite_posterior.sum():.4f}')\n",
        "show('05-finite-infinite-prior')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "uniform-012",
      "metadata": {},
      "source": [
        "## 6. Одинаковая нормировка — одинаковый результат\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-013",
      "metadata": {},
      "outputs": [],
      "source": [
        "finite_posterior = infinite_posterior / infinite_posterior.sum()\n",
        "fig, ax = plt.subplots()\n",
        "ax.step(N_candidates, empirical, where='mid', label='Моделирование', color=palette[1])\n",
        "ax.fill_between(N_candidates, empirical, step='mid', alpha=.2, color=palette[1])\n",
        "ax.plot(N_candidates, finite_posterior, 'o-', ms=4, color=palette[0],\n",
        "        label=f'Формула с той же границей N ≤ {N_upper}')\n",
        "ax.set(xlim=(M_sim - 2, N_upper), xlabel='Число танков N', ylabel='Апостериорная вероятность')\n",
        "ax.legend()\n",
        "show('06-finite-prior-matched')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "uniform-014",
      "metadata": {},
      "source": [
        "## 7. Верхняя граница априорного распределения\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-015",
      "metadata": {},
      "outputs": [],
      "source": [
        "def finite_tank_posterior(M, k, upper):\n",
        "    values = np.arange(M, upper + 1)\n",
        "    log_weights = -log_binom(values, k)\n",
        "    return values, np.exp(log_weights - logsumexp(log_weights))\n",
        "\n",
        "M_bound, k_bound = 274, 10\n",
        "fig, axes = plt.subplots(1, 2, figsize=(12, 5))\n",
        "for i, upper in enumerate([450, 1000, 5000]):\n",
        "    values, mass = finite_tank_posterior(M_bound, k_bound, upper)\n",
        "    axes[0].plot(values, mass, color=palette[i], ls=['-', '--', ':'][i], lw=2,\n",
        "                 label=f'Ω = {upper}')\n",
        "    print(f'Ω = {upper}: E[N | данные] = {np.sum(values * mass):.2f}')\n",
        "for i, current_k in enumerate([1, 2, 3, 10]):\n",
        "    values, mass = finite_tank_posterior(M_bound, current_k, 5000)\n",
        "    axes[1].plot(values, mass, color=palette[i], label=f'k = {current_k}')\n",
        "axes[0].set(title=f'M = {M_bound}, k = {k_bound}', xlim=(260, 700))\n",
        "axes[1].set(title=f'M = {M_bound}, Ω = 5000', xlim=(260, 1200))\n",
        "for ax in axes:\n",
        "    ax.set(xlabel='Число танков N', ylabel='Апостериорная вероятность')\n",
        "    ax.legend()\n",
        "show('07-prior-upper-bound')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "uniform-016",
      "metadata": {},
      "source": [
        "## 8. Утки: распределение числа повторных поимок\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-017",
      "metadata": {},
      "outputs": [],
      "source": [
        "N_ducks, K_marked, n_caught, duck_repetitions = 300, 40, 60, 50000\n",
        "rng = np.random.default_rng(SEED + 2)\n",
        "recaptured = st.hypergeom.rvs(N_ducks, K_marked, n_caught, size=duck_repetitions, random_state=rng)\n",
        "k_grid = np.arange(max(0, K_marked + n_caught - N_ducks), min(K_marked, n_caught) + 1)\n",
        "duck_counts = np.bincount(recaptured, minlength=k_grid[-1] + 1)\n",
        "fig, ax = plt.subplots()\n",
        "ax.bar(k_grid, duck_counts[k_grid] / duck_repetitions, color=palette[0], alpha=.4, label='Моделирование')\n",
        "ax.plot(k_grid, st.hypergeom.pmf(k_grid, N_ducks, K_marked, n_caught), 'o-',\n",
        "        color=palette[1], label='Гипергеометрическое распределение')\n",
        "ax.axvline(K_marked * n_caught / N_ducks, color='black', ls=':', label='Среднее Kn/N')\n",
        "ax.set(xlim=(0, min(k_grid[-1], recaptured.max() + 2)), xlabel='Число повторно пойманных k', ylabel='Вероятность',\n",
        "       title=f'N = {N_ducks}, K = {K_marked}, n = {n_caught}')\n",
        "ax.legend()\n",
        "show('08-duck-recaptures')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "uniform-018",
      "metadata": {},
      "source": [
        "## 9. Утки: оценка Линкольна–Петерсена по повторным выборкам\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-019",
      "metadata": {},
      "outputs": [],
      "source": [
        "positive = recaptured > 0\n",
        "lp_estimates = K_marked * n_caught / recaptured[positive]\n",
        "values, counts = np.unique(lp_estimates, return_counts=True)\n",
        "fig, ax = plt.subplots()\n",
        "ax.fill_between(values, counts / positive.sum(), color=palette[0], alpha=.18)\n",
        "ax.vlines(values, 0, counts / positive.sum(), color=palette[0], alpha=.6)\n",
        "ax.plot(values, counts / positive.sum(), 'o', color=palette[0], ms=4, label='Оценки Kn/k при k > 0')\n",
        "ax.axvline(N_ducks, color='black', ls=':', label=f'Истинное N = {N_ducks}')\n",
        "ax.axvline(lp_estimates.mean(), color=palette[1], ls='--', label=f'Среднее оценок: {lp_estimates.mean():.1f}')\n",
        "ax.set(xlabel=r'Значение оценки $\\hat N$', ylabel='Вероятность при k > 0',\n",
        "       xlim=(0, np.quantile(lp_estimates, .999) * 1.08))\n",
        "ax.legend()\n",
        "print(f'Доля k = 0: {np.mean(~positive):.5f}; теория: {st.hypergeom.pmf(0,N_ducks,K_marked,n_caught):.5f}')\n",
        "print(f'Среднее оценок при k > 0: {lp_estimates.mean():.2f}; истинное N: {N_ducks}')\n",
        "show('09-duck-estimator')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "uniform-020",
      "metadata": {},
      "source": [
        "## 10. Утки: апостериорное распределение размера популяции\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "uniform-021",
      "metadata": {},
      "outputs": [],
      "source": [
        "K_observed, n_observed, k_observed, duck_upper = 40, 60, 8, 1800\n",
        "N_duck_grid = np.arange(K_observed + n_observed - k_observed, duck_upper + 1)\n",
        "log_likelihood = st.hypergeom.logpmf(k_observed, N_duck_grid, K_observed, n_observed)\n",
        "duck_posterior = np.exp(log_likelihood - logsumexp(log_likelihood))\n",
        "lp_observed = K_observed * n_observed / k_observed\n",
        "posterior_mean = np.sum(N_duck_grid * duck_posterior)\n",
        "fig, ax = plt.subplots()\n",
        "ax.plot(N_duck_grid, duck_posterior, color=palette[0], label=f'Апостериорное, N ≤ {duck_upper}')\n",
        "ax.axvline(lp_observed, color=palette[1], ls='--', label=f'Линкольн–Петерсен: {lp_observed:.0f}')\n",
        "ax.axvline(posterior_mean, color=palette[2], ls=':', label=f'Апостериорное среднее: {posterior_mean:.1f}')\n",
        "ax.set(xlabel='Размер популяции N', ylabel='Апостериорная вероятность',\n",
        "       title=f'Наблюдения: K = {K_observed}, n = {n_observed}, k = {k_observed}')\n",
        "ax.legend()\n",
        "print(f'Апостериорное среднее при N ≤ {duck_upper}: {posterior_mean:.2f}')\n",
        "if k_observed > 2:\n",
        "    print(f'Среднее при бесконечной верхней границе: {(K_observed-1)*(n_observed-1)/(k_observed-2):.2f}')\n",
        "show('10-duck-posterior')\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.13.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
