# -*- coding: utf-8 -*- """ Ежедневный прогноз окончания российско-украинской войны (версия для сайта). Запуск: python3 war_forecast.py --inputs ../data/inputs.json --outdir ../data [--n 1000000] [--quick] Читает data/inputs.json (все текущие факты и сигналы с источниками), пересчитывает модель Монте-Карло и пишет: data/forecast.json — всё, что показывает сайт; data/history.json — добавляет/обновляет запись за дату asof. Слои модели (подробно — в отчёте): 1) базовая ставка: байесовская лог-логистическая модель длительности 23 затяжных войн; 2) скрытая марковская модель намерений Кремля (M — максимализм, F — готов к заморозке); 3) СДУ военного потенциала с прыжками, модель бюджета РФ (дефицит, ФНБ, нефть), помощь Украине; 4) теория игр (logit-QRE) -> модель пропорциональных рисков Кокса для перехода M->F; 5) байесовское обучение России на результатах фронта; 6) марковские режимы: переговоры, политика США (смена администрации 01.2029 и 01.2033); 7) перемирие / срыв / мирный договор; 8) логарифмический пул базовой ставки (w=0,4) и структурной модели. """ import argparse import json import os import sys import time from datetime import date, datetime, timezone import numpy as np HORIZON_END = (2040, 12) TRUNC = 1.0 # ---------------------------------------------------------------- историческая база (неизменна) WARS = [ ("Крымская война", "1853-10-23", "1856-02-29", "conv", 0), ("Парагвайская война", "1864-12-13", "1870-03-01", "conv", 0), ("Тихоокеанская война", "1879-04-05", "1883-10-20", "conv", 0), ("Русско-японская война", "1904-02-08", "1905-09-05", "conv", 0), ("Первая мировая война", "1914-07-28", "1918-11-11", "conv", 0), ("Греко-турецкая война", "1919-05-15", "1922-10-11", "conv", 0), ("Чакская война", "1932-06-15", "1935-06-12", "conv", 0), ("Японо-китайская война", "1937-07-07", "1945-09-02", "conv", 0), ("Вторая мировая (Европа)", "1939-09-01", "1945-05-08", "conv", 0), ("Первая Индокитайская", "1946-12-19", "1954-07-21", "mixed", 0), ("Корейская война", "1950-06-25", "1953-07-27", "conv", 0), ("Алжирская война", "1954-11-01", "1962-03-19", "mixed", 0), ("Вьетнам (фаза США)", "1965-03-08", "1973-01-27", "mixed", 0), ("Афганистан (СССР)", "1979-12-24", "1989-02-15", "mixed", 0), ("Ирано-иракская война", "1980-09-22", "1988-08-20", "conv", 0), ("Боснийская война", "1992-04-06", "1995-10-12", "mixed", 0), ("Эфиопо-эритрейская", "1998-05-06", "2000-06-18", "conv", 0), ("Афганистан (США)", "2001-10-07", "2021-08-30", "mixed", 0), ("Иракская война", "2003-03-20", "2011-12-18", "mixed", 0), ("Сирия", "2011-03-15", "2024-12-08", "mixed", 0), ("Йемен (интервенция)", "2015-03-26", "2022-04-02", "mixed", 0), ("Тыграй", "2020-11-04", "2022-11-02", "mixed", 0), ("Судан", "2023-04-15", None, "mixed", 1), # идёт: цензурировано на дату asof ] MU_GRID = np.linspace(0.0, 3.5, 351) S_GRID = np.linspace(0.05, 2.0, 196) def _logS(t, mu, s): return -np.logaddexp(0.0, (np.log(t) - mu) / s) def _logf(t, mu, s): z = (np.log(t) - mu) / s return -np.log(s) - np.log(t) + z - 2.0 * np.logaddexp(0.0, z) def war_durations(asof): out = [] for name, s, e, typ, cens in WARS: end = date.fromisoformat(e) if e else asof out.append((name, typ, cens, (end - date.fromisoformat(s)).days / 365.25)) return out def grid_posterior(durs, cens): M, S = np.meshgrid(MU_GRID, S_GRID, indexing="ij") ll = np.zeros_like(M) for d, c in zip(durs, cens): ll += (_logS(d, M, S) if c else _logf(d, M, S)) - _logS(TRUNC, M, S) post = ll - 0.5 * ((M - 1.3) / 1.0) ** 2 - 0.5 * S ** 2 w = np.exp(post - post.max()) return w / w.sum() def sample_posterior(w, n, rng): idx = rng.choice(w.size, size=n, p=w.ravel()) i, j = np.unravel_index(idx, w.shape) mu = MU_GRID[i] + (rng.random(n) - 0.5) * (MU_GRID[1] - MU_GRID[0]) s = np.clip(S_GRID[j] + (rng.random(n) - 0.5) * (S_GRID[1] - S_GRID[0]), 0.04, None) return mu, s def cond_cdf(t, tau, mu, s): F = lambda x: 1.0 / (1.0 + np.exp(-(np.log(x) - mu) / s)) Ft, Ftau = F(t), F(tau) return float(np.mean((Ft - Ftau) / (1.0 - Ftau))) # ---------------------------------------------------------------- календарь class Cal: """Месяц k=0 — месяц даты asof; горизонт — декабрь 2040.""" def __init__(self, asof, war_start): self.asof = asof self.y0, self.m0 = asof.year, asof.month self.K = (HORIZON_END[0] - self.y0) * 12 + (HORIZON_END[1] - self.m0) + 1 self.tau0 = (asof - war_start).days / 365.25 self.war_start = war_start def year(self, k): k = np.asarray(k) return self.y0 + (self.m0 - 1 + k) // 12 def label(self, k): k = int(k) y = self.y0 + (self.m0 - 1 + k) // 12 m = (self.m0 - 1 + k) % 12 + 1 return f"{m:02d}.{y}" def decimal(self, k): return self.y0 + (self.m0 - 1 + k + 0.5) / 12.0 def k_of(self, y, m): return (y - self.y0) * 12 + (m - self.m0) def months_between(a_ym, b_ym): return (b_ym[0] - a_ym[0]) * 12 + (b_ym[1] - a_ym[1]) # ---------------------------------------------------------------- HMM-фильтр def hmm_filter(pi0, q_mf, q_fm, lr_r, lr_p, signals, asof): pF = np.array(pi0, float) y, m = 2025, 1 while (y, m) <= (asof.year, asof.month): pF = pF * (1 - q_fm) + (1 - pF) * q_mf lf = np.ones_like(pF) for s_ in signals.get(f"{y}-{m:02d}", []): lf = lf * (lr_r if s_ == "R" else lr_p) pF = pF * lf / (pF * lf + (1 - pF)) m += 1 if m == 13: y, m = y + 1, 1 return pF # ---------------------------------------------------------------- параметры DEFAULTS = dict(w_base=0.4, pF_mult=1.0, pF_fixed=None, oil_bar_fixed=None, us_fixed=None, dfin_fixed=None, rho1_mean=0.22, kappa_scale=1.0) US_T = np.array([[0.93, 0.06, 0.01], [0.03, 0.95, 0.02], [0.01, 0.06, 0.93]]) US_NEWADMIN = np.array([0.35, 0.50, 0.15]) def draw_params(n, rng, cfg, post, inp): asof = inp["_asof"] n_win = max(months_between((2025, 2), (asof.year, asof.month)) - 1, 0) p = {} p["mu"], p["s"] = sample_posterior(post, n, rng) p["kappa0"] = rng.gamma(1.5, 1.0 / (75.0 + n_win), n) * cfg["kappa_scale"] p["kFM0"] = rng.uniform(0.02, 0.06, n) pi0 = rng.uniform(0.2, 0.4, n) lr_r = rng.uniform(0.35, 0.75, n) lr_p = rng.uniform(1.2, 2.0, n) pF = hmm_filter(pi0, p["kappa0"], p["kFM0"], lr_r, lr_p, inp["_signals"], asof) * cfg["pF_mult"] if cfg["pF_fixed"] is not None: pF = np.full(n, cfg["pF_fixed"]) p["pF_init"] = np.clip(pF, 0, 1) p["b_opt"] = np.clip(rng.normal(0.25, 0.12, n), 0, None) p["b_RS"] = np.clip(rng.normal(0.25, 0.12, n), 0, None) p["b_MP"] = np.clip(rng.normal(0.20, 0.10, n), 0, None) p["b_US0"] = np.clip(rng.normal(0.40, 0.20, n), 0, None) p["b_US2"] = np.clip(rng.normal(0.40, 0.20, n), 0, None) p["p_neg"] = rng.beta(4.5, 25.5, n) p["u_acc"] = rng.beta(17, 3, n) p["c0"] = rng.gamma(1.0, 1.0 / (200.0 + n_win), n) p["g_UA"] = np.clip(rng.normal(0.4, 0.2, n), 0, None) p["g_P2"] = np.clip(rng.normal(0.7, 0.3, n), 0, None) p["p_exh"] = rng.uniform(0.0005, 0.002, n) m = cfg["rho1_mean"] p["rho1"] = rng.beta(m * 25.0, (1 - m) * 25.0, n) p["rho2"] = rng.uniform(0.05, 0.15, n) p["psi"] = rng.uniform(0.3, 0.6, n) p["pi_peace"] = rng.uniform(0.01, 0.03, n) p["phi_F"] = rng.uniform(0.15, 0.45, n) p["phi_C"] = rng.uniform(0.4, 0.8, n) p["nU"] = rng.normal(-0.003, 0.003, n) p["iU"] = rng.normal(0.002, 0.0015, n) p["nR"] = rng.normal(-0.002, 0.003, n) p["iR"] = rng.normal(0.0015, 0.0015, n) p["lamJ"] = rng.uniform(0.002, 0.008, n) p["fR"] = rng.uniform(0.0003, 0.0012, n) p["bias"] = rng.uniform(0, 100, n) p["dtr"] = rng.normal(0.15, 0.30, n) / 12.0 p["eta"] = rng.uniform(2.0, 4.0, n) p["sD"] = rng.uniform(0.3, 0.9, n) p["Dfin"] = rng.uniform(2.0, 3.0, n) if cfg["dfin_fixed"] is None else np.full(n, cfg["dfin_fixed"]) p["Obar"] = rng.uniform(62, 78, n) if cfg["oil_bar_fixed"] is None else np.full(n, cfg["oil_bar_fixed"]) p["hl"] = rng.uniform(6, 18, n) p["Abar"] = rng.uniform(0.88, 1.0, n) ua = inp["ukraine"] p["A0"] = rng.uniform(ua["coverage_low"], ua["coverage_high"], n) p["lead_rate"] = rng.uniform(0.0015, 0.0035, n) p["HR_lead"] = rng.uniform(1.5, 4.0, n) return p def _markov_step(state, T, u): cum = np.cumsum(T, axis=1)[state] return np.minimum((u[:, None] > cum).sum(axis=1), 2).astype(np.int8) def russian_beliefs(front_months, lam=0.9): """Beta-убеждения РФ о шансе «успешного месяца» (прирост > порога) с забыванием.""" months = sorted(front_months, key=lambda x: x["month"]) a = b = 1.0 n = len(months) for i, fm in enumerate(months): age = n - 1 - i a += lam ** age * fm["success"] b += lam ** age * (1 - fm["success"]) return a, b def simulate(n, seed, cfg_over, post, inp, cal, keep_ts=0, keep_params=0): cfg = dict(DEFAULTS) if cfg_over: cfg.update(cfg_over) rng = np.random.default_rng(seed) p = draw_params(n, rng, cfg, post, inp) w = cfg["w_base"] K = cal.K ru = inp["russia"] Def0, L0, Dref = ru["deficit_gdp"], ru["nwf_liquid_gdp"], ru["deficit_ref"] O0 = inp["oil"]["brent_usd"] a0, b0 = russian_beliefs(inp["front_months"]) us_init = np.array(inp["us_policy_probs"], float) us_init = us_init / us_init.sum() admin_k = {cal.k_of(2029, 1), cal.k_of(2033, 1)} lnU = np.zeros(n); lnR = np.zeros(n) lnO0 = np.log(O0); lnO = np.full(n, lnO0) A = p["A0"].copy() eps = np.zeros(n); L = np.full(n, float(L0)); sanc = np.zeros(n) a_b = np.full(n, a0); b_b = np.full(n, b0) H = rng.random(n) < p["pF_init"] T = np.full(n, bool(inp["talks_active"])) P = np.minimum((rng.random(n)[:, None] > np.cumsum(us_init)[None, :]).sum(1), 2).astype(np.int8) if cfg["us_fixed"] is not None: P[:] = cfg["us_fixed"] lead = np.zeros(n, bool) status = np.zeros(n, np.int8) cf_age = np.zeros(n, np.int16); cf_start = np.full(n, -1, np.int16) cf_type = np.zeros(n, np.int8); cf_comp = np.zeros(n, bool); frozen = np.zeros(n, bool) shift_ever = np.zeros(n, bool); tS = np.full(n, -1, np.int16) tE = np.full(n, -1, np.int16); tA = np.full(n, -1, np.int16) tB = np.full(n, -1, np.int16); tC = np.full(n, -1, np.int16) typeB = np.zeros(n, np.int8); shiftB = np.zeros(n, bool) relapses = np.zeros(n, np.int16); peace = np.zeros(n, bool) cf = inp.get("ceasefire", {}) or {} if cf.get("active"): st = date.fromisoformat(cf["start"]) age0 = max(months_between((st.year, st.month), (cal.y0, cal.m0)), 0) status[:] = 1; cf_age[:] = age0; cf_start[:] = 0; cf_type[:] = 1 cf_comp[:] = bool(cf.get("comprehensive")); H[:] = True; tE[:] = 0 frozen[:] = rng.random(n) < p["psi"] if cf_comp.any(): tC[:] = 0; peace[:] = True if age0 >= 3: tA[:] = 0 if age0 >= 12: tB[:] = 0; typeB[:] = 1 sig = 0.02; rho = 0.3; thB = 0.03; lam_f = 0.9 ts = None if keep_ts: ts = {k_: np.zeros((K, keep_ts), np.float32) for k_ in ("lnU", "lnR", "Def", "L", "A", "Oil", "G", "war")} for k in range(K): tau = cal.tau0 + k / 12.0 war = status == 0 if cfg["us_fixed"] is None: if k in admin_k: P = np.minimum((rng.random(n)[:, None] > np.cumsum(US_NEWADMIN)[None, :]).sum(1), 2).astype(np.int8) else: P = _markov_step(P, US_T, rng.random(n)) lnO += (np.log(2) / p["hl"]) * (np.log(p["Obar"]) - lnO) + 0.09 * rng.standard_normal(n) targ = p["Abar"] - 0.10 * (P == 2) + 0.03 * (P == 0) u = rng.random(n) A = np.clip(A + 0.15 * (targ - A) + 0.03 * rng.standard_normal(n) - 0.15 * (u < 0.01) + 0.10 * (u > 0.99), 0.3, 1.2) sanc += 0.2 * (p["sD"] * (P == 0) - 0.3 * (P == 2) - sanc) eps = 0.8 * eps + 0.18 * rng.standard_normal(n) Def = np.clip(Def0 + p["dtr"] * min(k, 36) - p["eta"] * (lnO - lnO0) + sanc + eps, 0.5, 7.0) L = np.minimum(np.maximum(L - np.maximum(Def - p["Dfin"], 0) / 12.0 + 0.5 * np.maximum(p["Dfin"] - Def, 0) / 12.0, 0), 6.0) xRS = (Def - Dref) + 1.5 * (L <= 0) z1 = rng.standard_normal(n); z2 = rho * z1 + np.sqrt(1 - rho ** 2) * rng.standard_normal(n) B = lnU - lnR jump = rng.random(n) < p["lamJ"] jsize = rng.uniform(0.35, 0.6, n) against_ua = rng.random(n) < 0.5 calm = np.where(war, 1.0, 0.3) lnU += np.where(war, p["nU"] + p["iU"] - 0.02 * (0.95 - A), 0.003) - 0.5 * thB * B + sig * calm * z1 - jsize * (jump & against_ua & war) lnR += np.where(war, p["nR"] + p["iR"] - p["fR"] * np.maximum(xRS, 0), 0.003) + 0.5 * thB * B + sig * calm * z2 - jsize * (jump & ~against_ua & war) B = lnU - lnR G = -3000.0 * B + 60.0 * rng.standard_normal(n) ua_crisis = war & (B < -0.45); ru_crisis = war & (B > 0.45) newS = (ua_crisis | ru_crisis) & (tS < 0); tS[newS] = k shift_ever |= ua_crisis | ru_crisis succ = (G > 150.0 - p["bias"]).astype(float) a_b = np.where(war, lam_f * a_b + succ + (1 - lam_f), a_b) b_b = np.where(war, lam_f * b_b + (1 - succ) + (1 - lam_f), b_b) pihat = a_b / (a_b + b_b) x_opt = (0.55 - pihat) / 0.15 x_MP = np.maximum(-lnR, 0) / 0.1 x_US = p["b_US0"] * (P == 0) - p["b_US2"] * (P == 2) lead |= rng.random(n) < p["lead_rate"] W = np.clip(p["b_opt"] * x_opt + p["b_RS"] * xRS + p["b_MP"] * x_MP + x_US + lead * np.log(p["HR_lead"]), -4, 4) uH = rng.random(n) to_F = (~H) & war & ((uH < 1 - np.exp(-p["kappa0"] * np.exp(W))) | (ru_crisis & (uH > 0.65))) to_M = H & war & (uH < 1 - np.exp(-p["kFM0"] * np.exp(-0.5 * W))) H = (H | to_F) & ~to_M uT = rng.random(n) T = (T & ~(T & (uT < np.where(H, 0.05, 0.25)))) | ((~T) & (uT < np.where(H, 0.6, 0.2))) xUA = (0.92 - A) / 0.1 + np.maximum(-lnU, 0) / 0.1 uacc = 1 / (1 + np.exp(-(np.log(p["u_acc"] / (1 - p["u_acc"])) + 0.3 * xUA))) hF = -np.log(1 - p["p_neg"] * uacc) * (H & T) pc = 1 - np.exp(-p["c0"] * np.exp(np.clip(p["g_UA"] * xUA + p["g_P2"] * (P == 2), -5, 5))) hC = -np.log(1 - pc) * (~H) + 0.288 * ua_crisis hR = 0.431 * ru_crisis * (~H) h_struct = hF + hC + hR + p["p_exh"] h_base = (_logS(tau, p["mu"], p["s"]) - _logS(tau + 1 / 12, p["mu"], p["s"])) / (1 - 0.2) h = np.exp(w * np.log(np.maximum(h_base, 1e-12)) + (1 - w) * np.log(np.maximum(h_struct, 1e-12))) enter = war & (rng.random(n) < 1 - np.exp(-h)) if enter.any(): scale = np.minimum(h / np.maximum(h_struct, 1e-12), 1.0) uu = rng.random(n) * np.maximum(h, h_struct) typ = np.where(uu < hF * scale, 1, np.where(uu < (hF + hC) * scale, 2, np.where(uu < (hF + hC + hR) * scale, 5, 4))) typ = np.where((typ == 2) & ua_crisis, 3, typ).astype(np.int8) phi = np.where(typ == 1, p["phi_F"], np.where((typ == 2) | (typ == 3), p["phi_C"], 0.2)) comp = rng.random(n) < phi status[enter] = 1; cf_age[enter] = 0; cf_start[enter] = k cf_type[enter] = typ[enter]; cf_comp[enter] = comp[enter] frozen[enter] = (rng.random(n) < p["psi"])[enter] newC = enter & comp & (tC < 0); tC[newC] = k; peace |= enter & comp tE[enter & (tE < 0)] = k on = (status == 1) & ~enter cf_age = np.where(on, cf_age + 1, cf_age) r1 = 1 - (1 - p["rho1"]) ** (1 / 12); r2 = 1 - (1 - p["rho2"]) ** (1 / 24) r = np.where(cf_age <= 12, r1, np.where(cf_age <= 36, r2, 0.001)) r = r * np.where(cf_comp, 0.6, 1.0) * np.where(cf_type >= 2, 0.8, 1.0) * np.where(peace, 0.4, 1.0) rel = on & (rng.random(n) < r) status[rel] = 0; H[rel] = False; T[rel] = False; relapses += rel; peace[rel] = False a_b[rel] = 5.0; b_b[rel] = 5.0 hold = on & ~rel setA = hold & (cf_age == 3) & (tA < 0); tA[setA] = cf_start[setA] setB = hold & (cf_age == 12) & (tB < 0) tB[setB] = cf_start[setB]; typeB[setB] = cf_type[setB]; shiftB[setB] = shift_ever[setB] newpeace = hold & ~peace & ~frozen & (rng.random(n) < p["pi_peace"]) peace |= newpeace; tC[newpeace & (tC < 0)] = k if keep_ts: mm = keep_ts ts["lnU"][k] = lnU[:mm]; ts["lnR"][k] = lnR[:mm]; ts["Def"][k] = Def[:mm]; ts["L"][k] = L[:mm] ts["A"][k] = A[:mm]; ts["Oil"][k] = np.exp(lnO[:mm]); ts["G"][k] = G[:mm]; ts["war"][k] = (status[:mm] == 0) res = dict(tE=tE, tA=tA, tB=tB, tC=tC, tS=tS, typeB=typeB, shiftB=shiftB, relapses=relapses, pF_init=p["pF_init"], kappa0=p["kappa0"]) if keep_params: res["params"] = {k_: v[:keep_params] for k_, v in p.items()} if keep_ts: res["ts"] = ts return res # ---------------------------------------------------------------- агрегирование def cum(cal, t, years): t = np.asarray(t) yrs = np.where(t >= 0, cal.year(np.maximum(t, 0)), 9999) return [float(np.mean(yrs <= y)) for y in years] def qdate(cal, t, q): t = np.where(np.asarray(t) >= 0, np.asarray(t).astype(float), np.inf) v = np.quantile(t, q, method="inverted_cdf") return None if np.isinf(v) else cal.label(int(v)) def qdec(cal, t, q): t = np.where(np.asarray(t) >= 0, np.asarray(t).astype(float), np.inf) v = np.quantile(t, q, method="inverted_cdf") return None if np.isinf(v) else round(cal.decimal(int(v)), 3) SCEN_NAMES = { "S1": "Быстрое дипломатическое завершение", "S2": "Прекращение огня по линии фронта", "S3": "Война на истощение", "S4": "Резкое изменение военного баланса", "S5": "Длительная война", } def scenarios(cal, r): y = cal.y0 tB = r["tB"] yrs = np.where(tB >= 0, cal.year(np.maximum(tB, 0)), 9999) k_cut = cal.k_of(y + 7, 1) S4 = np.where(tB >= 0, r["shiftB"], (r["tS"] >= 0) & (r["tS"] < k_cut)) bands = {"S1": (~S4) & (yrs <= y + 1), "S2": (~S4) & (yrs >= y + 2) & (yrs <= y + 3), "S3": (~S4) & (yrs >= y + 4) & (yrs <= y + 6), "S4": S4, "S5": (~S4) & (yrs >= y + 7)} rules = {"S1": f"устойчивое перемирие начинается до конца {y + 1}", "S2": f"начало в {y + 2}–{y + 3}", "S3": f"начало в {y + 4}–{y + 6}", "S4": "до конца войны был обвал фронта одной из сторон", "S5": f"устойчивого перемирия нет до {y + 7}"} out = [] for key in ("S1", "S2", "S3", "S4", "S5"): msk = bands[key] sub = yrs[msk]; fin = sub[sub < 9999] tb = r["typeB"][msk & (tB >= 0)] out.append({"id": key, "name": SCEN_NAMES[key], "rule": rules[key], "p": float(msk.mean()), "median_year": int(np.median(fin)) if fin.size else None, "share_freeze": float(np.mean(np.isin(tb, (1, 4)))) if tb.size else 0.0, "share_ru_terms": float(np.mean(np.isin(tb, (2, 3)))) if tb.size else 0.0}) return out SENS_LABELS = { "kappa0": ("Риск смены курса Кремля", "kremlin"), "pF_init": ("Готовность Кремля к заморозке сейчас", "kremlin"), "kFM0": ("Откат Кремля к максимализму", "kremlin"), "c0": ("Склонность Украины к уступкам", "ua"), "p_neg": ("Скорость переговоров", "talks"), "rho1": ("Срыв перемирий в первый год", "talks"), "u_acc": ("Согласие Украины на заморозку", "ua"), "b_opt": ("Вес неудач РФ на фронте", "mil"), "b_RS": ("Вес бюджетного стресса РФ", "econ"), "b_MP": ("Вес людских потерь РФ", "mil"), "b_US0": ("Эффект давления США на РФ", "us"), "b_US2": ("Эффект давления США на Украину", "us"), "g_UA": ("Отклик на напряжение Украины", "ua"), "g_P2": ("Отклик на давление США на Украину", "us"), "nU": ("Баланс мобилизации и потерь Украины", "mil"), "nR": ("Баланс набора и потерь РФ", "mil"), "iU": ("Технологии и дроны Украины", "mil"), "iR": ("Технологии и дроны РФ", "mil"), "lamJ": ("Частота обвалов фронта", "mil"), "dtr": ("Тренд дефицита бюджета РФ", "econ"), "eta": ("Зависимость бюджета РФ от нефти", "econ"), "Obar": ("Долгосрочная цена нефти", "econ"), "Dfin": ("Запас заимствований РФ", "econ"), "Abar": ("Долгосрочная помощь Украине", "econ"), "A0": ("Покрытие нужд Украины сейчас", "econ"), "psi": ("Доля «вечных» заморозок", "talks"), "phi_F": ("Комплексный договор при заморозке", "talks"), "lead_rate": ("Вероятность смены руководства", "pol"), } def sensitivity(cal, r, params, top=10): from scipy.stats import spearmanr tB = r["tB"].astype(float); tBc = np.where(tB >= 0, tB, 999.0) yrs = np.where(r["tB"] >= 0, cal.year(np.maximum(r["tB"], 0)), 9999) by = yrs <= cal.y0 + 2 out = [] for name, v in params.items(): if name not in SENS_LABELS: continue v = np.asarray(v, float) q20, q80 = np.quantile(v, [0.2, 0.8]) d = (by[v >= q80].mean() - by[v <= q20].mean()) * 100 rho_, _ = spearmanr(v, tBc) out.append({"key": name, "name": SENS_LABELS[name][0], "group": SENS_LABELS[name][1], "delta_pp": round(float(d), 1), "spearman": round(float(rho_), 3)}) out.sort(key=lambda x: -abs(x["delta_pp"])) return out[:top], cal.y0 + 2 def dynamics(cal, ts): rows = [] for k in range(cal.K): if cal.label(k)[:2] != "12" and k != 0: continue war = ts["war"][k] > 0.5 sel = (lambda a: a[war]) if war.sum() > 200 else (lambda a: a) q = lambda a: [round(float(x), 3) for x in np.quantile(sel(a), [0.1, 0.5, 0.9])] rows.append({"year": int(cal.year(k)), "U": [round(100 * np.exp(x), 1) for x in q(ts["lnU"][k])], "R": [round(100 * np.exp(x), 1) for x in q(ts["lnR"][k])], "Def": q(ts["Def"][k]), "L": q(ts["L"][k]), "A": q(ts["A"][k]), "Oil": q(ts["Oil"][k]), "G": q(ts["G"][k]), "share_war": round(float(war.mean()), 4)}) if cal.year(k) >= cal.y0 + 9: break nwf = None for k in range(cal.K): war = ts["war"][k] > 0.5 v = ts["L"][k][war] if war.sum() > 200 else ts["L"][k] if np.median(v) <= 0: nwf = cal.label(k); break return rows, nwf # ---------------------------------------------------------------- главный расчёт def run(inputs_path, outdir, n_main=1_000_000, chunk=250_000, n_var=100_000, quick=False): t0 = time.time() with open(inputs_path, encoding="utf-8") as f: inp = json.load(f) asof = date.fromisoformat(inp["asof"]) war_start = date.fromisoformat(inp["war_start"]) cal = Cal(asof, war_start) sig = {} for s_ in inp["kremlin_signals"]: sig.setdefault(s_["month"], []).append(s_["type"]) inp["_asof"] = asof; inp["_signals"] = sig if quick: n_main, chunk, n_var = 50_000, 50_000, 10_000 rng = np.random.default_rng(20261201) wd = war_durations(asof) post = grid_posterior([x[3] for x in wd], [x[2] for x in wd]) mu, s = sample_posterior(post, 40000, rng) years = list(range(cal.y0, cal.y0 + 10)) base_cum = [cond_cdf((date(y, 12, 31) - war_start).days / 365.25, cal.tau0, mu, s) for y in years] chunks = []; ts = params = first = None for c in range(max(n_main // chunk, 1)): rr = simulate(chunk, 1000 + c, None, post, inp, cal, keep_ts=(20000 if c == 0 else 0), keep_params=(200000 if c == 0 else 0)) if c == 0: ts = rr.pop("ts"); params = rr.pop("params") npar = len(params["kappa0"]); first = {k_: v[:npar] for k_, v in rr.items()} chunks.append(rr) print(f"[main] {c + 1}/{n_main // chunk} {time.time() - t0:.0f}s", flush=True) R = {k_: np.concatenate([x[k_] for x in chunks]) for k_ in chunks[0]} N = len(R["tB"]) head = { "median_B": qdate(cal, R["tB"], 0.5), "q10_B": qdate(cal, R["tB"], 0.1), "q90_B": qdate(cal, R["tB"], 0.9), "q25_B": qdate(cal, R["tB"], 0.25), "q75_B": qdate(cal, R["tB"], 0.75), "q05_B": qdate(cal, R["tB"], 0.05), "q95_B": qdate(cal, R["tB"], 0.95), "median_B_dec": qdec(cal, R["tB"], 0.5), "median_A": qdate(cal, R["tA"], 0.5), "q10_A": qdate(cal, R["tA"], 0.1), "q90_A": qdate(cal, R["tA"], 0.9), "median_C": qdate(cal, R["tC"], 0.5), "median_E": qdate(cal, R["tE"], 0.5), "p_no_peace_2040": round(1 - cum(cal, R["tC"], [2040])[0], 4), "mean_pF": round(float(np.mean(R["pF_init"])), 4), "kappa_mean_month": round(float(np.mean(R["kappa0"])), 5), "mc_se_pp": round(float(np.sqrt(0.25 / N) * 100), 3), } tb = R["typeB"][R["tB"] >= 0] terms = {"freeze": float(np.mean(np.isin(tb, (1, 4)))), "ru_terms": float(np.mean(tb == 2)), "ua_collapse": float(np.mean(tb == 3)), "ru_collapse": float(np.mean(tb == 5))} dist_years = list(range(cal.y0, cal.y0 + 10)) yrsB = np.where(R["tB"] >= 0, cal.year(np.maximum(R["tB"], 0)), 9999) dist = [{"label": str(y), "p": float(np.mean(yrsB == y))} for y in dist_years] dist.append({"label": f"{cal.y0 + 10}–{HORIZON_END[0] - 1}", "p": float(np.mean((yrsB >= cal.y0 + 10) & (yrsB <= HORIZON_END[0] - 1)))}) dist.append({"label": "позже", "p": float(np.mean(yrsB >= HORIZON_END[0]))}) if cal.m0 != 1: dist[0]["note"] = "неполный год" sens, sens_year = sensitivity(cal, first, params) dyn, nwf = dynamics(cal, ts) variants = [("Только история (w = 1)", {"w_base": 1.0}), ("Только механизм (w = 0)", {"w_base": 0.0}), ("Кремль жёстче", {"pF_mult": 0.3}), ("Нефть остаётся по $90", {"oil_bar_fixed": 90.0}), ("США давят на Украину или выходят", {"us_fixed": 2}), ("США давят на РФ", {"us_fixed": 0}), ("Перемирия срываются чаще", {"rho1_mean": 0.40})] var_out = [] for i, (nm, cfgv) in enumerate(variants): rv = simulate(n_var, 5000 + i, cfgv, post, inp, cal) tbv = rv["typeB"][rv["tB"] >= 0] cv = cum(cal, rv["tB"], [cal.y0 + 2, cal.y0 + 4]) var_out.append({"name": nm, "median_B": qdate(cal, rv["tB"], 0.5), "p_y2": cv[0], "p_y4": cv[1], "ru_terms": float(np.mean(np.isin(tbv, (2, 3)))) if tbv.size else 0.0}) print(f"[var] {nm} {time.time() - t0:.0f}s", flush=True) fc = { "asof": inp["asof"], "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "n_paths": int(N), "war_days": (asof - war_start).days, "headline": head, "years": years, "cum": {"A": cum(cal, R["tA"], years), "B": cum(cal, R["tB"], years), "C": cum(cal, R["tC"], years), "E": cum(cal, R["tE"], years), "base": base_cum}, "dist_B": dist, "scenarios": scenarios(cal, R), "terms": terms, "sensitivity": sens, "sensitivity_year": sens_year, "dynamics": dyn, "nwf_zero": nwf, "variants": var_out, "variant_years": [cal.y0 + 2, cal.y0 + 4], "runtime_sec": round(time.time() - t0, 1), } os.makedirs(outdir, exist_ok=True) with open(os.path.join(outdir, "forecast.json"), "w", encoding="utf-8") as f: json.dump(fc, f, ensure_ascii=False, indent=1) # история hp = os.path.join(outdir, "history.json") hist = [] if os.path.exists(hp): with open(hp, encoding="utf-8") as f: hist = json.load(f) hist = [h for h in hist if h.get("date") != inp["asof"]] mk = next((m for m in inp.get("markets", []) if m.get("key") == "ceasefire_by_next_year"), None) hist.append({"date": inp["asof"], "median_B": head["median_B"], "median_B_dec": head["median_B_dec"], "p_B_next": fc["cum"]["B"][1], "p_B_y2": fc["cum"]["B"][2], "p_E_next": fc["cum"]["E"][1], "pF": head["mean_pF"], "market_next": (mk or {}).get("p")}) hist.sort(key=lambda h: h["date"]) with open(hp, "w", encoding="utf-8") as f: json.dump(hist, f, ensure_ascii=False, indent=1) print(f"DONE {time.time() - t0:.0f}s median_B={head['median_B']} pB={fc['cum']['B'][1]:.3f}/{fc['cum']['B'][2]:.3f}") return fc if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--inputs", default="../data/inputs.json") ap.add_argument("--outdir", default="../data") ap.add_argument("--n", type=int, default=1_000_000) ap.add_argument("--quick", action="store_true") a = ap.parse_args() run(a.inputs, a.outdir, n_main=a.n, quick=a.quick)