// Port C# de la partie statistique de `ict/basin_asym.py` : rangs moyennes,
// Pearson, correlation partielle FWL (residus de moindres carres sur les rangs ;
// equations normales k x k a pivot partiel -- numpy lstsq est en SVD, parite a
// ~1e-12 pres a ces conditionnements), stratification 2D, verdict ternaire,
// controle nul. Memes grilles, memes seuils, meme graine de tirage (0) pour la
// stratification que la source.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public sealed class AsymFamily
{
public double[] Sigma = Array.Empty<double>();
public double[] Width = Array.Empty<double>();
public double[] Barrier = Array.Empty<double>();
public double[] Asym = Array.Empty<double>();
public double[] Recovery = Array.Empty<double>();
}
public static class AsymStats
{
// Rangs MOYENNES (ex-aequo toleres), comme scipy.stats.rankdata : un vecteur
// constant rend des rangs constants (variance nulle -> Pearson garde 0).
public static double[] Rank(double[] xs)
{
int n = xs.Length;
int[] order = Enumerable.Range(0, n).OrderBy(i => xs[i]).ToArray(); // tri stable
double[] ranks = new double[n];
int i = 0;
while (i < n)
{
int j = i;
while (j + 1 < n && xs[order[j + 1]] == xs[order[i]]) j++;
double avg = 0.5 * (i + j) + 1.0; // rangs 1-indexes, moyenne du bloc
for (int k = i; k <= j; k++) ranks[order[k]] = avg;
i = j + 1;
}
return ranks;
}
public static double Pearson(double[] xs, double[] ys) // 0 si variance nulle
{
int n = xs.Length;
if (n < 2) return 0.0;
double mx = xs.Average(), my = ys.Average();
double sxx = 0.0, syy = 0.0, sxy = 0.0;
for (int i = 0; i < n; i++)
{ double dx = xs[i] - mx, dy = ys[i] - my; sxx += dx * dx; syy += dy * dy; sxy += dx * dy; }
if (Math.Sqrt(sxx / n) < 1e-12 || Math.Sqrt(syy / n) < 1e-12) return 0.0;
double denom = Math.Sqrt(sxx * syy);
return denom > 0.0 ? sxy / denom : 0.0;
}
// Residus de la regression de y sur [1, cov...] (equations normales, pivot
// partiel) -- la brique FWL de la source (numpy.linalg.lstsq).
public static double[] ResidualsAgainst(double[] y, double[][] covariates)
{
int n = y.Length, k = covariates.Length + 1;
double[][] Z = new double[k][];
Z[0] = Enumerable.Repeat(1.0, n).ToArray();
for (int j = 1; j < k; j++) Z[j] = covariates[j - 1];
double[,] A = new double[k, k]; double[] rhs = new double[k];
for (int r = 0; r < k; r++)
{
for (int c = 0; c < k; c++)
{ double s = 0.0; for (int t = 0; t < n; t++) s += Z[r][t] * Z[c][t]; A[r, c] = s; }
double sr = 0.0; for (int t = 0; t < n; t++) sr += Z[r][t] * y[t]; rhs[r] = sr;
}
for (int col = 0; col < k; col++) // elimination de Gauss, pivot partiel
{
int piv = col;
for (int r = col + 1; r < k; r++) if (Math.Abs(A[r, col]) > Math.Abs(A[piv, col])) piv = r;
if (piv != col)
{
for (int c = 0; c < k; c++) (A[col, c], A[piv, c]) = (A[piv, c], A[col, c]);
(rhs[col], rhs[piv]) = (rhs[piv], rhs[col]);
}
for (int r = col + 1; r < k; r++)
{ double f = A[r, col] / A[col, col]; for (int c = col; c < k; c++) A[r, c] -= f * A[col, c]; rhs[r] -= f * rhs[col]; }
}
double[] coef = new double[k];
for (int r = k - 1; r >= 0; r--)
{ double s = rhs[r]; for (int c = r + 1; c < k; c++) s -= A[r, c] * coef[c]; coef[r] = s / A[r, r]; }
double[] res = new double[n];
for (int t = 0; t < n; t++)
{ double s = y[t]; for (int j = 0; j < k; j++) s -= Z[j][t] * coef[j]; res[t] = s; }
return res;
}
public static double PartialSpearman(double[] x, double[] y, params double[][] covariates)
{
if (x.Length < 2) return 0.0;
var rx = Rank(x); var ry = Rank(y);
if (covariates.Length == 0) return Pearson(rx, ry);
var ex = ResidualsAgainst(rx, covariates.Select(Rank).ToArray());
var ey = ResidualsAgainst(ry, covariates.Select(Rank).ToArray());
return Pearson(ex, ey);
}
// Percentile lineaire (defaut de numpy.percentile).
public static double Percentile(double[] xs, double q)
{
var s = (double[])xs.Clone(); Array.Sort(s);
double pos = q / 100.0 * (s.Length - 1);
int lo = (int)Math.Floor(pos); int hi = Math.Min(lo + 1, s.Length - 1);
return s[lo] + (pos - lo) * (s[hi] - s[lo]);
}
// Echantillonnage de la famille : les DEUX minima (profond + peu profond)
// de chaque puits (a, b, c) ; l'asymetrie = depth_shallow - depth_deep.
public static AsymFamily GatherAsymFamily(double[] aGrid, double[] bGrid, double[] cGrid,
double noise, int nTrials, int T, double dt, double perturbFrac, ulong seed)
{
var rng = new Rng64(seed);
var sig = new List<double>(); var wid = new List<double>();
var bar = new List<double>(); var asy = new List<double>(); var rec = new List<double>();
foreach (double a in aGrid) foreach (double b in bGrid) foreach (double c in cGrid)
{
var prof = BasinAsym.AsymBasinProfile(a, b, c);
if (prof.Count != 2) continue;
var sorted = prof.OrderBy(p => p.Depth).ToList(); // profond d'abord
double asym = sorted[1].Depth - sorted[0].Depth;
foreach (var p in sorted)
{
double frac = BasinAsym.RecoverFractionAsymStochastic(
p.X, a, b, c, rng, noise, nTrials, T, dt, perturbFrac);
sig.Add(p.Sigma); wid.Add(p.Width); bar.Add(p.Barrier); asy.Add(asym); rec.Add(frac);
}
}
return new AsymFamily { Sigma = sig.ToArray(), Width = wid.ToArray(),
Barrier = bar.ToArray(), Asym = asy.ToArray(), Recovery = rec.ToArray() };
}
// Stratification 2D du plan (sigma, width) : grille n_bins x n_bins sur les
// rangs, nombre UNIFORME d'echantillons par cellule qualifiee ; tirage
// deterministe (graine 0), comme la source. Seuil minimal par cellule et
// repli identiques a _stratify_decouple.
public static AsymFamily StratifyDecouple(AsymFamily fam, int nBins = 5)
{
int n = fam.Sigma.Length;
if (n < nBins * nBins) return fam;
var rSig = Rank(fam.Sigma); var rWid = Rank(fam.Width);
double[] edges = BasinAsym.Linspace(0.5, n + 0.5, nBins + 1);
int BinOf(double r) { int i = 0; while (i < nBins && r >= edges[i + 1]) i++; return Math.Clamp(i, 0, nBins - 1); }
var cells = new Dictionary<long, List<int>>(); var cellOrder = new List<long>();
for (int k = 0; k < n; k++)
{
long key = (long)BinOf(rSig[k]) * 1000 + BinOf(rWid[k]);
if (!cells.ContainsKey(key)) { cells[key] = new List<int>(); cellOrder.Add(key); }
cells[key].Add(k);
}
var nonempty = cellOrder.Select(key => cells[key]).Where(l => l.Count > 0).ToList();
if (nonempty.Count < nBins) return fam;
int threshold = Math.Max(2, nonempty[0].Count / 4);
var qualified = nonempty.Where(l => l.Count >= threshold).ToList();
if (qualified.Count < nBins) qualified = nonempty;
int minPerCell = qualified.Min(l => l.Count);
var rngPick = new Rng64(0); // deterministe (reproductible), comme la source
var keep = new List<int>();
foreach (var idx in qualified) keep.AddRange(rngPick.Choose(idx.ToArray(), minPerCell));
keep.Sort();
return new AsymFamily
{
Sigma = keep.Select(i => fam.Sigma[i]).ToArray(),
Width = keep.Select(i => fam.Width[i]).ToArray(),
Barrier = keep.Select(i => fam.Barrier[i]).ToArray(),
Asym = keep.Select(i => fam.Asym[i]).ToArray(),
Recovery = keep.Select(i => fam.Recovery[i]).ToArray(),
};
}
public sealed record VerdictResult(
int NSamples, double RhoSigmaRecovery, double RhoWidthRecovery,
double RhoBarrierRecovery, double RhoAsymRecovery,
double RhoSigmaWidth, double RhoSigmaWidthRaw, double RhoSigmaBarrier,
double PartialRhoGivenWidth, double PartialRhoGivenWidthBarrier,
double Partial2CovNullP95, bool DecouplingOk, string Verdict);
public static VerdictResult AsymVerdict(
double[] aGrid = null, double[] bGrid = null, double[] cGrid = null,
double noise = 0.35, int nTrials = 60, int T = 3000, double dt = 0.02,
double perturbFrac = 0.75, int nShuffle = 200, int seed = 0, int nStratBins = 5)
{
var rng = new Rng64((ulong)seed);
aGrid ??= new[] { 0.3, 0.6, 1.0, 1.6, 2.5 }; // a pilote width ~ sqrt(b/2a)
bGrid ??= new[] { 0.5, 1.0, 1.5, 2.5, 3.5 }; // b pilote sigma ~ 4b
cGrid ??= new[] { -0.8, -0.4, 0.0, 0.4, 0.8 }; // axe d'asymetrie
var fam = GatherAsymFamily(aGrid, bGrid, cGrid, noise, nTrials, T, dt, perturbFrac, (ulong)seed);
double rhoRaw = Pearson(Rank(fam.Sigma), Rank(fam.Width)); // couplage BRUT
if (nStratBins > 1) fam = StratifyDecouple(fam, nStratBins);
var sig = fam.Sigma; var wid = fam.Width; var bar = fam.Barrier;
var asy = fam.Asym; var rec = fam.Recovery;
double rhoSR = Pearson(Rank(sig), Rank(rec));
double rhoWR = Pearson(Rank(wid), Rank(rec));
double rhoBR = Pearson(Rank(bar), Rank(rec));
double rhoAR = Pearson(Rank(asy), Rank(rec));
double rhoSW = Pearson(Rank(sig), Rank(wid)); // diagnostic decouplage
double rhoSB = Pearson(Rank(sig), Rank(bar));
double p1 = PartialSpearman(sig, rec, wid);
double p2 = PartialSpearman(sig, rec, wid, bar);
var nullPartial = new double[nShuffle];
for (int i = 0; i < nShuffle; i++)
{
var perm = (double[])sig.Clone(); rng.Shuffle(perm);
nullPartial[i] = PartialSpearman(perm, rec, wid, bar);
}
double p95 = Percentile(nullPartial.Select(Math.Abs).ToArray(), 95.0);
string verdict = p2 > p95 && p2 > 0.2 ? "SUBSTRATE-ARTIFACT"
: p2 < -0.2 ? "INCONCLUSIVE" : "CONFIRMED-NEGATIVE";
return new VerdictResult(sig.Length, rhoSR, rhoWR, rhoBR, rhoAR, rhoSW, rhoRaw, rhoSB,
p1, p2, p95, Math.Abs(rhoSW) < 0.2, verdict);
}
public sealed record NullResult(int NSamples, double RhoSigmaWidth,
double RhoWidthRecovery, double PartialRhoGivenWidth,
double PartialNullP95, bool ReproducesFroncePattern);
// Controle nul re-couple : limite symetrique c = 0, a fixe, b varie ->
// sigma et width monotones en b : couplage maximal, comme sur la fronce.
public static NullResult AsymRecoupledNull(double[] bGrid = null, double cFixed = 0.0,
double noise = 0.35, int nTrials = 60, int T = 3000, double dt = 0.02,
double perturbFrac = 0.75, int nShuffle = 200, int seed = 0)
{
var rng = new Rng64((ulong)seed);
bGrid ??= BasinAsym.Linspace(0.5, 3.5, 10);
double aFixed = 1.0;
var sig = new List<double>(); var wid = new List<double>();
var bar = new List<double>(); var rec = new List<double>();
foreach (double b in bGrid)
foreach (var p in BasinAsym.AsymBasinProfile(aFixed, b, cFixed))
{
double frac = BasinAsym.RecoverFractionAsymStochastic(
p.X, aFixed, b, cFixed, rng, noise, nTrials, T, dt, perturbFrac);
sig.Add(p.Sigma); wid.Add(p.Width); bar.Add(p.Barrier); rec.Add(frac);
}
var sigA = sig.ToArray(); var widA = wid.ToArray(); var recA = rec.ToArray();
double rhoSW = Pearson(Rank(sigA), Rank(widA));
double p1 = PartialSpearman(sigA, recA, widA);
var nullPartial = new double[nShuffle];
for (int i = 0; i < nShuffle; i++)
{
var perm = (double[])sigA.Clone(); rng.Shuffle(perm);
nullPartial[i] = PartialSpearman(perm, recA, widA);
}
double p95 = Percentile(nullPartial.Select(Math.Abs).ToArray(), 95.0);
return new NullResult(sigA.Length, rhoSW, Pearson(Rank(widA), Rank(recA)), p1, p95,
rhoSW > 0.6 && Math.Abs(p1) < 0.3);
}
}
// --- Couplage intra-puits : brut vs apres stratification 2D ------------------
var v0 = AsymStats.AsymVerdict(nShuffle: 50, nTrials: 60, T: 2000, seed: 0);
Console.WriteLine($"Couplage sigma-width BRUT : rho = {Fmt.S3(v0.RhoSigmaWidthRaw)}");
Console.WriteLine($"Couplage sigma-width apres stratif: rho = {Fmt.S3(v0.RhoSigmaWidth)} (reduit, residuel)");
Console.WriteLine($" -> la stratification retire environ {Fmt.F3(v0.RhoSigmaWidthRaw - v0.RhoSigmaWidth)} de couplage");
Console.WriteLine(" -> le seuil < 0.2 (chantier 1/3) n'est pas atteignable : le test decisif est la");
Console.WriteLine(" partielle a 2 covariables (FWL), valide SOUS couplage residuel.");