#r "nuget: ScottPlot, 5.0.55"
// Appareil du jumeau C# : RNG deterministe, substrats, organes spectral et de
// sensibilite, plus la cochaîne de Cech. Le RNG numpy (PCG64) n'est pas
// reproductible en .NET : on le remplace par un xorshift64* seede (meme choix
// que les jumeaux ICT-15 et ICT-15c), lui aussi deterministe par graine.
// Les grandeurs deterministes sont identiques a la source ; les grandeurs
// stochastiques sont comparees a tolerance de Monte-Carlo (cf.
// twin_pairs.d/ict-15d-cechobstruction.yaml).
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using ScottPlot;
using Microsoft.DotNet.Interactive;
// ---------------------------------------------------------------------------
// RNG : xorshift64*
// ---------------------------------------------------------------------------
public sealed class Rng64
{
private ulong _x;
private double _spare;
private bool _hasSpare;
public Rng64(ulong seed)
{
_x = seed == 0UL ? 0x9E3779B97F4A7C15UL : seed;
}
public ulong NextUInt64()
{
ulong x = _x;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
_x = x;
return x * 0x2545F4914F6CDD1DUL;
}
public double NextDouble() => (NextUInt64() >> 11) * (1.0 / 9007199254740992.0);
public int NextInt(int lo, int hi)
{
if (hi <= lo) return lo;
return lo + (int)(NextDouble() * (hi - lo));
}
// Box-Muller avec reserve (equivalent de Generator.standard_normal)
public double NextNormal()
{
if (_hasSpare) { _hasSpare = false; return _spare; }
double u1, u2, s;
do
{
u1 = 2.0 * NextDouble() - 1.0;
u2 = 2.0 * NextDouble() - 1.0;
s = u1 * u1 + u2 * u2;
} while (s >= 1.0 || s == 0.0);
double f = Math.Sqrt(-2.0 * Math.Log(s) / s);
_spare = u2 * f;
_hasSpare = true;
return u1 * f;
}
}
// ---------------------------------------------------------------------------
// Statistiques (conventions numpy : quantile 'linear', digitize a droite exclue,
// ecart-type de population ddof=0)
// ---------------------------------------------------------------------------
public static class Stats
{
public static double[] Linspace(double a, double b, int n)
{
var r = new double[n];
if (n <= 0) return r;
if (n == 1) { r[0] = a; return r; }
double step = (b - a) / (n - 1);
for (int i = 0; i < n - 1; i++) r[i] = a + i * step;
r[n - 1] = b;
return r;
}
public static double[] Quantiles(IEnumerable<double> data, double[] qs)
{
var sorted = data.ToArray();
Array.Sort(sorted);
int n = sorted.Length;
var res = new double[qs.Length];
if (n == 0) return res;
for (int k = 0; k < qs.Length; k++)
{
double pos = qs[k] * (n - 1);
int lo = (int)Math.Floor(pos);
if (lo < 0) lo = 0;
if (lo > n - 1) lo = n - 1;
int hi = Math.Min(lo + 1, n - 1);
double frac = pos - lo;
res[k] = sorted[lo] + frac * (sorted[hi] - sorted[lo]);
}
return res;
}
// np.digitize(x, bins) : index i tel que bins[i-1] <= x < bins[i]
public static int[] Digitize(double[] x, double[] bins)
{
var r = new int[x.Length];
for (int i = 0; i < x.Length; i++)
{
int idx = 0;
while (idx < bins.Length && x[i] >= bins[idx]) idx++;
r[i] = idx;
}
return r;
}
public static double[] Flatten(double[,] a)
{
int n = a.GetLength(0), m = a.GetLength(1);
var r = new double[n * m];
int k = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) r[k++] = a[i, j];
return r;
}
public static double Mean(IReadOnlyList<double> v)
{
if (v.Count == 0) return 0.0;
double s = 0.0;
for (int i = 0; i < v.Count; i++) s += v[i];
return s / v.Count;
}
public static double StdPop(IReadOnlyList<double> v)
{
if (v.Count == 0) return 0.0;
double m = Mean(v);
double s = 0.0;
for (int i = 0; i < v.Count; i++) { double d = v[i] - m; s += d * d; }
return Math.Sqrt(s / v.Count);
}
public static double Percentile(double[] v, double p)
=> v.Length == 0 ? 0.0 : Quantiles(v, new[] { p })[0];
public static double Max(IReadOnlyList<double> v)
{
if (v.Count == 0) return 0.0;
double m = v[0];
for (int i = 1; i < v.Count; i++) if (v[i] > m) m = v[i];
return m;
}
public static double Min(IReadOnlyList<double> v)
{
if (v.Count == 0) return 0.0;
double m = v[0];
for (int i = 1; i < v.Count; i++) if (v[i] < m) m = v[i];
return m;
}
}
// ---------------------------------------------------------------------------
// Substrat 1 : Gray-Scott (port de ict.reaction_diffusion)
// ---------------------------------------------------------------------------
public sealed class GrayScott
{
public double F { get; }
public double Kill { get; }
public double Du { get; }
public double Dv { get; }
public double Dt { get; }
public GrayScott(double feed = 0.0367, double kill = 0.0649, double du = 0.16, double dv = 0.08, double step = 1.0)
{
F = feed; Kill = kill; Du = du; Dv = dv; Dt = step;
}
// Stencil 5 points a bords periodiques. L'ordre d'association reproduit
// celui de ict.reaction_diffusion.laplacian :
// roll(+1, axe0) + roll(-1, axe0) + roll(+1, axe1) + roll(-1, axe1) - 4*f
public static double[,] Laplacian(double[,] field)
{
int n = field.GetLength(0), m = field.GetLength(1);
var r = new double[n, m];
for (int i = 0; i < n; i++)
{
int im = (i - 1 + n) % n;
int ip = (i + 1) % n;
for (int j = 0; j < m; j++)
{
int jm = (j - 1 + m) % m;
int jp = (j + 1) % m;
r[i, j] = field[im, j] + field[ip, j] + field[i, jm] + field[i, jp] - 4.0 * field[i, j];
}
}
return r;
}
public (double[,] U, double[,] V) Seed(int n = 96, int block = 12, double noise = 0.02, Rng64 rng = null)
{
var U = new double[n, n];
var V = new double[n, n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) U[i, j] = 1.0;
int lo = n / 2 - block / 2;
int hi = lo + block;
for (int i = lo; i < hi; i++)
for (int j = lo; j < hi; j++) { U[i, j] = 0.50; V[i, j] = 0.25; }
if (noise > 0.0)
{
var g = rng ?? new Rng64(0UL);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
U[i, j] += noise * g.NextNormal();
V[i, j] += noise * g.NextNormal();
}
}
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
U[i, j] = Math.Clamp(U[i, j], 0.0, 1.0);
V[i, j] = Math.Clamp(V[i, j], 0.0, 1.0);
}
return (U, V);
}
public (double[,] U, double[,] V) Step(double[,] U, double[,] V)
{
var lapU = Laplacian(U);
var lapV = Laplacian(V);
int n = U.GetLength(0), m = U.GetLength(1);
var Un = new double[n, m];
var Vn = new double[n, m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
double reaction = U[i, j] * V[i, j] * V[i, j];
Un[i, j] = Math.Clamp(U[i, j] + Dt * (Du * lapU[i, j] - reaction + F * (1.0 - U[i, j])), 0.0, 1.0);
Vn[i, j] = Math.Clamp(V[i, j] + Dt * (Dv * lapV[i, j] + reaction - (F + Kill) * V[i, j]), 0.0, 1.0);
}
return (Un, Vn);
}
public (double[,] U, double[,] V) Run(double[,] U, double[,] V, int steps)
{
for (int t = 0; t < steps; t++)
{
var s = Step(U, V);
U = s.U; V = s.V;
}
return (U, V);
}
}
// ---------------------------------------------------------------------------
// Substrat 2 : Axelrod (port de ict.strategic_morphodynamics)
// ---------------------------------------------------------------------------
public delegate int StrategyFn(IReadOnlyList<int> own, IReadOnlyList<int> opp, Rng64 rng);
public static class Ipd
{
public const int C = 0;
public const int D = 1;
public static readonly double T = 5.0;
public static readonly double R = 3.0;
public static readonly double P = 1.0;
public static readonly double S = 0.0;
public static (double a, double b) PayoffPair(int a, int b)
{
if (a == C && b == C) return (R, R);
if (a == C && b == D) return (S, T);
if (a == D && b == C) return (T, S);
return (P, P);
}
public static int AllC(IReadOnlyList<int> own, IReadOnlyList<int> opp, Rng64 rng) => C;
public static int AllD(IReadOnlyList<int> own, IReadOnlyList<int> opp, Rng64 rng) => D;
public static int Tft(IReadOnlyList<int> own, IReadOnlyList<int> opp, Rng64 rng)
=> opp.Count == 0 ? C : opp[opp.Count - 1];
// Seule strategie consommatrice du RNG (protocole etendu #13322).
public static int GTft(IReadOnlyList<int> own, IReadOnlyList<int> opp, Rng64 rng)
{
if (opp.Count == 0) return C;
if (opp[opp.Count - 1] == C) return C;
return rng.NextDouble() < 1.0 / 3.0 ? C : D;
}
public static int Pavlov(IReadOnlyList<int> own, IReadOnlyList<int> opp, Rng64 rng)
{
if (own.Count == 0) return C;
int last = own[own.Count - 1];
int oppLast = opp[opp.Count - 1];
var (pa, _) = PayoffPair(last, oppLast);
bool won = pa >= R;
return won ? last : 1 - last;
}
public static int Grim(IReadOnlyList<int> own, IReadOnlyList<int> opp, Rng64 rng)
{
for (int i = 0; i < opp.Count; i++) if (opp[i] == D) return D;
return C;
}
// Ordre d'insertion identique au dict Python (dict preserve l'ordre).
public static List<KeyValuePair<string, StrategyFn>> MakeStrategies()
{
var l = new List<KeyValuePair<string, StrategyFn>>();
l.Add(new KeyValuePair<string, StrategyFn>("allc", AllC));
l.Add(new KeyValuePair<string, StrategyFn>("alld", AllD));
l.Add(new KeyValuePair<string, StrategyFn>("tft", Tft));
l.Add(new KeyValuePair<string, StrategyFn>("gtft", GTft));
l.Add(new KeyValuePair<string, StrategyFn>("pavlov", Pavlov));
l.Add(new KeyValuePair<string, StrategyFn>("grim", Grim));
return l;
}
public static (double g1, double g2) PlayMatch(StrategyFn s1, StrategyFn s2, int nRounds, double noise, Rng64 rng)
{
var own1 = new List<int>();
var own2 = new List<int>();
double g1 = 0.0, g2 = 0.0;
for (int t = 0; t < nRounds; t++)
{
int a = s1(own1, own2, rng);
int b = s2(own2, own1, rng);
if (noise > 0.0)
{
if (rng.NextDouble() < noise) a = 1 - a;
if (rng.NextDouble() < noise) b = 1 - b;
}
var (pa, pb) = PayoffPair(a, b);
g1 += pa; g2 += pb;
own1.Add(a); own2.Add(b);
}
return (g1 / nRounds, g2 / nRounds);
}
public static double[,] PayoffMatrix(List<KeyValuePair<string, StrategyFn>> strategies,
int nRounds, int nReps, Rng64 rng)
{
int n = strategies.Count;
var A = new double[n, n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
double sum = 0.0;
for (int r = 0; r < nReps; r++)
{
var (gi, _) = PlayMatch(strategies[i].Value, strategies[j].Value, nRounds, 0.0, rng);
sum += gi;
}
A[i, j] = sum / nReps;
}
return A;
}
public static double[,] ReplicatorTrajectory(double[,] A, double[] x0, int nSteps)
{
int n = x0.Length;
var x = (double[])x0.Clone();
double total = 0.0;
for (int i = 0; i < n; i++) total += x[i];
for (int i = 0; i < n; i++) x[i] /= total;
var traj = new double[nSteps + 1, n];
for (int i = 0; i < n; i++) traj[0, i] = x[i];
for (int t = 0; t < nSteps; t++)
{
var f = new double[n];
for (int i = 0; i < n; i++)
{
double s = 0.0;
for (int j = 0; j < n; j++) s += A[i, j] * x[j];
f[i] = s;
}
double avg = 0.0;
for (int i = 0; i < n; i++) avg += f[i] * x[i];
if (avg < 1e-12) break;
double tot = 0.0;
for (int i = 0; i < n; i++)
{
x[i] = Math.Max(0.0, x[i] * f[i] / avg);
tot += x[i];
}
if (tot > 1e-12)
for (int i = 0; i < n; i++) x[i] /= tot;
for (int i = 0; i < n; i++) traj[t + 1, i] = x[i];
}
return traj;
}
}
// ---------------------------------------------------------------------------
// Substrat 4 : May (port de ict.bistable.GrazingModel.simulate_sde)
// ---------------------------------------------------------------------------
public sealed class Grazing
{
public double R { get; }
public double K { get; }
public double H { get; }
public Grazing(double r = 1.0, double k = 10.0, double h = 1.0) { R = r; K = k; H = h; }
public double Rate(double x, double c)
=> R * x * (1.0 - x / K) - c * x * x / (x * x + H * H);
public double[] SimulateSde(double c, double x0, double sigma, double dt, int T, ulong seed)
{
var g = new Rng64(seed);
double sq = Math.Sqrt(dt);
double x = x0;
var xs = new double[T];
for (int t = 0; t < T; t++)
{
x = x + dt * Rate(x, c) + sigma * sq * g.NextNormal();
if (x < 0.0) x = 0.0;
xs[t] = x;
}
return xs;
}
}
// ---------------------------------------------------------------------------
// Organe spectral (port de ict.spectral : matrice de transition, graphe
// symetrique sans boucle, Laplacien, gap)
// ---------------------------------------------------------------------------
public static class Spectral
{
// P[s, t] += 1 seulement si les deux indices sont dans [0, n) ; les paires
// hors bornes sont silencieusement ignorees (convention de la source).
public static double[,] TransitionMatrix(IReadOnlyList<int> states, int nSymbols, double eps = 1e-9)
{
var P = new double[nSymbols, nSymbols];
for (int i = 0; i < nSymbols; i++)
for (int j = 0; j < nSymbols; j++) P[i, j] = eps;
for (int t = 0; t + 1 < states.Count; t++)
{
int s = states[t], u = states[t + 1];
if (s >= 0 && s < nSymbols && u >= 0 && u < nSymbols) P[s, u] += 1.0;
}
for (int i = 0; i < nSymbols; i++)
{
double sum = 0.0;
for (int j = 0; j < nSymbols; j++) sum += P[i, j];
if (sum > 0.0)
for (int j = 0; j < nSymbols; j++) P[i, j] /= sum;
}
return P;
}
public static double[,] TransitionGraph(IReadOnlyList<int> states, int nSymbols)
{
var P = TransitionMatrix(states, nSymbols);
var W = new double[nSymbols, nSymbols];
for (int i = 0; i < nSymbols; i++)
for (int j = 0; j < nSymbols; j++) W[i, j] = (P[i, j] + P[j, i]) / 2.0;
for (int i = 0; i < nSymbols; i++) W[i, i] = 0.0;
return W;
}
// Valeurs propres par Jacobi cyclique (matrice symetrique reelle).
public static double[] SymmetricEigenvalues(double[,] A, int maxSweeps = 100)
{
int n = A.GetLength(0);
var a = (double[,])A.Clone();
for (int sweep = 0; sweep < maxSweeps; sweep++)
{
double off = 0.0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) off += a[i, j] * a[i, j];
if (off < 1e-30) break;
for (int p = 0; p < n - 1; p++)
for (int q = p + 1; q < n; q++)
{
if (Math.Abs(a[p, q]) < 1e-18) continue;
double theta = (a[q, q] - a[p, p]) / (2.0 * a[p, q]);
double t = theta == 0.0
? 1.0
: Math.Sign(theta) / (Math.Abs(theta) + Math.Sqrt(theta * theta + 1.0));
double c = 1.0 / Math.Sqrt(t * t + 1.0);
double s = t * c;
for (int k = 0; k < n; k++)
{
double akp = a[k, p], akq = a[k, q];
a[k, p] = c * akp - s * akq;
a[k, q] = s * akp + c * akq;
}
for (int k = 0; k < n; k++)
{
double apk = a[p, k], aqk = a[q, k];
a[p, k] = c * apk - s * aqk;
a[q, k] = s * apk + c * aqk;
}
}
}
var eigs = new double[n];
for (int i = 0; i < n; i++) eigs[i] = a[i, i];
Array.Sort(eigs);
return eigs;
}
public static double[] LaplacianSpectrum(double[,] W)
{
int n = W.GetLength(0);
var L = new double[n, n];
for (int i = 0; i < n; i++)
{
double d = 0.0;
for (int j = 0; j < n; j++) d += W[i, j];
for (int j = 0; j < n; j++) L[i, j] = -W[i, j];
L[i, i] = d; // D - W, et W_ii = 0
}
return SymmetricEigenvalues(L);
}
public static double SpectralGap(double[,] W)
{
var eigs = LaplacianSpectrum(W);
if (eigs.Length < 2) return double.NaN;
return eigs[1] - eigs[0];
}
public static double SpectralGapOf(IReadOnlyList<int> states, int nSymbols)
=> SpectralGap(TransitionGraph(states, nSymbols));
}
// ---------------------------------------------------------------------------
// Organe de sensibilite (port de ict.sensitivity, correctif #9764 : voisinage
// lu sur les transitions OBSERVEES, pas sur le graphe lisse)
// ---------------------------------------------------------------------------
public sealed class SensitivitySummary
{
public double max;
public double mean;
public double std;
public double p95;
public int n_visited;
}
public static class Sensitivity
{
// Ids compacts par ordre de PREMIERE APPARITION ; leve si un nouveau label
// apparait alors que n_symbols est deja atteint.
public static int[] EncodeLabels(IReadOnlyList<int> states, int nSymbols)
{
var map = new Dictionary<int, int>();
var ids = new int[states.Count];
for (int i = 0; i < states.Count; i++)
{
int lab = states[i];
if (!map.TryGetValue(lab, out int id))
{
if (map.Count >= nSymbols)
throw new InvalidOperationException(
$"trop de labels distincts pour n_symbols={nSymbols}");
id = map.Count;
map[lab] = id;
}
ids[i] = id;
}
return ids;
}
// Adjacence OBSERVEE : booleenne, symetrique, boucles exclues, paires hors
// bornes ignorees, aucun lissage.
public static bool[,] ObservedAdjacency(IReadOnlyList<int> states, int nSymbols)
{
var A = new bool[nSymbols, nSymbols];
for (int t = 0; t + 1 < states.Count; t++)
{
int s = states[t], u = states[t + 1];
if (s == u) continue;
if (s < 0 || s >= nSymbols || u < 0 || u >= nSymbols) continue;
A[s, u] = true;
A[u, s] = true;
}
return A;
}
public static int[] Local(IReadOnlyList<int> states, int nSymbols, Func<int, int> f)
{
var ids = EncodeLabels(states, nSymbols);
var A = ObservedAdjacency(ids, nSymbols);
var fVals = new int[nSymbols];
for (int i = 0; i < nSymbols; i++) fVals[i] = f(i);
var s = new int[nSymbols];
for (int x = 0; x < nSymbols; x++)
{
int count = 0;
for (int y = 0; y < nSymbols; y++)
if (A[x, y] && fVals[y] != fVals[x]) count++;
s[x] = count;
}
return s;
}
// Les noeuds visites occupent les ids 0..n_visited-1 (encodage compact par
// premiere apparition) : le prefixe suffit.
public static SensitivitySummary Distribution(IReadOnlyList<int> states, int nSymbols, Func<int, int> f)
{
var s = Local(states, nSymbols, f);
var distinct = new HashSet<int>(states);
int nVisited = distinct.Count;
var visited = new List<double>();
for (int i = 0; i < Math.Min(nVisited, s.Length); i++) visited.Add(s[i]);
return new SensitivitySummary
{
max = visited.Count == 0 ? 0.0 : Stats.Max(visited),
mean = visited.Count == 0 ? 0.0 : Stats.Mean(visited),
std = visited.Count == 0 ? 0.0 : Stats.StdPop(visited),
p95 = visited.Count == 0 ? 0.0 : Stats.Percentile(visited.ToArray(), 95),
n_visited = nVisited
};
}
}
// ---------------------------------------------------------------------------
// Cochaine de Cech (port de ict.cech_obstruction) : chaque proxy devient une
// section locale ; le cobord mesure le desaccord residuel apres ajustement
// affine par paire, le cocycle mesure l'holonomie cyclique sur les triplets.
// Un desaccord purement affine est absorbe par le cobord et n'est pas une
// obstruction ; seule une holonomie stable signale un defaut de recollement.
// ---------------------------------------------------------------------------
public sealed class TransportResidual
{
public double[] Residual;
public double A;
public double B;
public double Norm;
public double Cosine;
}
public sealed class HolonomySummary
{
public double Holonomy;
public double MaxAbs;
public double SignConsistency;
}
public sealed class CechReport
{
public int NProxies;
public int NWindows;
public Dictionary<string, double> PairwiseResiduals = new();
public double MeanCoboundary;
public Dictionary<string, double> TripleHolonomies = new();
public double MeanCocycle;
public double ObstructionRatio;
public double SignConsistency;
public int EffectiveRank;
public double S2OverS1;
}
public static class Cech
{
// proxy_sections : fenetres contigues NON recouvrantes de `windowSize`
// transitions, donc `windowSize + 1` etats par fenetre. Un decoupage
// glissant correlerait les sections par construction et masquerait
// l'obstruction que l'on cherche a mesurer.
public static Dictionary<string, double[]> ProxySections(
IReadOnlyList<int> states,
int nSymbols,
int windowSize,
IReadOnlyList<KeyValuePair<string, Func<IReadOnlyList<int>, int, double>>> proxies)
{
if (nSymbols < 2) throw new ArgumentException($"n_symbols >= 2 requis (recu {nSymbols}).");
if (windowSize < 1) throw new ArgumentException($"window_size >= 1 requis (recu {windowSize}).");
if (proxies.Count < 2) throw new ArgumentException($">= 2 proxys requis pour un recouvrement (recu {proxies.Count}).");
if (states.Count < windowSize + 1)
throw new ArgumentException($"trajectoire trop courte ({states.Count} etats) pour window_size={windowSize}.");
// np.arange(0, N - windowSize, windowSize) : autant de departs que
// ceil((N - windowSize) / windowSize), soit (N - 1) / windowSize en
// division entiere.
int nWin = (states.Count - 1) / windowSize;
var sections = new Dictionary<string, double[]>();
foreach (var kv in proxies)
{
var vals = new double[nWin];
for (int k = 0; k < nWin; k++)
{
int s0 = k * windowSize;
var window = new int[windowSize + 1];
for (int t = 0; t <= windowSize; t++) window[t] = states[s0 + t];
vals[k] = kv.Value(window, nSymbols);
}
sections[kv.Key] = vals;
}
return sections;
}
// Centre-reduit chaque section : on ne compare pas les niveaux bruts mais
// la structure relative. Une section constante (proxy insensible aux
// fenetres) devient un vecteur nul -- elle ne contribue ni au cobord ni au
// cocycle, plutot que d'injecter une division par zero.
public static Dictionary<string, double[]> NormalizeSections(
IReadOnlyDictionary<string, double[]> sections)
{
var output = new Dictionary<string, double[]>();
foreach (var kv in sections)
{
var s = kv.Value;
double mu = Stats.Mean(s);
double sigma = Stats.StdPop(s);
var norm = new double[s.Length];
if (sigma >= 1e-12)
for (int i = 0; i < s.Length; i++) norm[i] = (s[i] - mu) / sigma;
output[kv.Key] = norm;
}
return output;
}
// Dimensionnalite effective du faisceau : valeurs singulieres de la matrice
// (une ligne par proxy). Sur une matrice a peu de lignes et beaucoup de
// colonnes, elles s'obtiennent exactement comme racines des valeurs propres
// de la matrice de Gram M M^T -- de taille n_proxies carree.
public static (double s1, double s2, double s3, double s2OverS1, int rank)
EffectiveDimensionality(IReadOnlyDictionary<string, double[]> sections, bool normalize = true)
{
var secs = normalize ? NormalizeSections(sections) : sections;
int m = secs.Count;
if (m == 0) return (0.0, 0.0, 0.0, 0.0, 0);
var rows = new List<double[]>();
foreach (var kv in secs) rows.Add(kv.Value);
int n = rows[0].Length;
var gram = new double[m, m];
for (int i = 0; i < m; i++)
for (int j = i; j < m; j++)
{
double acc = 0.0;
for (int k = 0; k < n; k++) acc += rows[i][k] * rows[j][k];
gram[i, j] = acc;
gram[j, i] = acc;
}
// Spectral.SymmetricEigenvalues trie par ordre croissant : on relit a
// l'envers pour obtenir s1 >= s2 >= s3.
var ev = Spectral.SymmetricEigenvalues(gram);
var sv = new double[ev.Length];
for (int i = 0; i < ev.Length; i++)
sv[i] = Math.Sqrt(Math.Max(ev[ev.Length - 1 - i], 0.0));
for (int i = 0; i < sv.Length; i++) sv[i] = Math.Max(sv[i], 1e-12);
double s1 = sv.Length > 0 ? sv[0] : 0.0;
double s2 = sv.Length > 1 ? sv[1] : 0.0;
double s3 = sv.Length > 2 ? sv[2] : 0.0;
// Une valeur singuliere sous 10 % de s1 est tenue pour negligeable.
const double rankFloor = 0.1;
int rank = 0;
for (int i = 0; i < sv.Length; i++) if (sv[i] >= rankFloor * s1) rank++;
return (s1, s2, s3, s1 > 0 ? s2 / s1 : 0.0, rank);
}
// Cobord (1-cochaine) : moindres carres de s_i ~ a*s_j + b, residu
// r = s_i - (a*s_j + b). Ce qui reste apres avoir retire la meilleure
// relation affine est exactement ce qui n'est pas un simple changement
// d'echelle ou de niveau.
public static TransportResidual TransportResidual(double[] si, double[] sj)
{
if (si.Length != sj.Length)
throw new ArgumentException($"sections de formes differentes : {si.Length} vs {sj.Length}");
if (si.Length < 2)
throw new ArgumentException(">= 2 fenetres requis pour un ajustement affine.");
double mi = Stats.Mean(si);
double mj = Stats.Mean(sj);
double sdj = Stats.StdPop(sj);
double varj = sdj * sdj;
double a, b;
if (varj < 1e-12)
{
// s_j constante : aucune relation affine n'est definie, rien n'est
// explique par s_j, le residu est s_i lui-meme (centre).
a = 0.0;
b = mi;
}
else
{
double cov = 0.0;
for (int k = 0; k < si.Length; k++) cov += (si[k] - mi) * (sj[k] - mj);
cov /= si.Length;
a = cov / varj;
b = mi - a * mj;
}
var residual = new double[si.Length];
for (int k = 0; k < si.Length; k++) residual[k] = si[k] - (a * sj[k] + b);
double acc = 0.0;
for (int k = 0; k < residual.Length; k++) acc += residual[k] * residual[k];
double norm = Math.Sqrt(acc / residual.Length);
double sci = 0.0, scj = 0.0, scij = 0.0;
for (int k = 0; k < si.Length; k++)
{
double ci = si[k] - mi;
double cj = sj[k] - mj;
sci += ci * ci;
scj += cj * cj;
scij += ci * cj;
}
double denom = Math.Sqrt(sci / si.Length) * Math.Sqrt(scj / sj.Length);
double cosine = denom > 1e-12 ? (scij / si.Length) / denom : 0.0;
return new TransportResidual { Residual = residual, A = a, B = b, Norm = norm, Cosine = cosine };
}
// Cocycle (2-cochaine) : holonomie h = r_ij + r_jk + r_ki mesuree par
// fenetre. Si les sections proviennent d'une mesure globale coherente, la
// somme cyclique s'annule. La coherence de signe distingue une obstruction
// directionnelle d'un residu de bruit qui oscille autour de zero.
public static HolonomySummary Holonomy(double[] rIJ, double[] rJK, double[] rKI)
{
int n = rIJ.Length;
var h = new double[n];
for (int k = 0; k < n; k++) h[k] = rIJ[k] + rJK[k] + rKI[k];
double acc = 0.0, maxAbs = 0.0;
int pos = 0, neg = 0;
for (int k = 0; k < n; k++)
{
acc += h[k] * h[k];
double a = Math.Abs(h[k]);
if (a > maxAbs) maxAbs = a;
if (h[k] > 1e-9) pos++;
else if (h[k] < -1e-9) neg++;
}
double rms = n > 0 ? Math.Sqrt(acc / n) : 0.0;
double sign = n > 0 ? Math.Max((double)pos / n, (double)neg / n) : 0.0;
return new HolonomySummary { Holonomy = rms, MaxAbs = maxAbs, SignConsistency = sign };
}
// Classe d'obstruction : tous les cobords par paires, tous les cocycles par
// triplets, puis le rapport cocycle/cobord -- la fraction du desaccord qui
// n'est PAS expliquee par les relations affines par paires.
public static CechReport ObstructionClass(
IReadOnlyDictionary<string, double[]> sections, bool normalize = true)
{
var secs = normalize ? NormalizeSections(sections) : sections;
var names = new List<string>(secs.Keys);
int n = names.Count;
var residuals = new Dictionary<string, double[]>();
var pairwise = new Dictionary<string, double>();
for (int a = 0; a < n; a++)
for (int b = a + 1; b < n; b++)
{
var res = TransportResidual(secs[names[a]], secs[names[b]]);
string key = names[a] + "|" + names[b];
pairwise[key] = res.Norm;
residuals[key] = res.Residual;
}
double meanCoboundary = pairwise.Count > 0 ? pairwise.Values.Average() : 0.0;
var triples = new Dictionary<string, double>();
var signCons = new List<double>();
if (n >= 3)
{
for (int a = 0; a < n; a++)
for (int b = a + 1; b < n; b++)
for (int c = b + 1; c < n; c++)
{
string kAB = names[a] + "|" + names[b];
string kBC = names[b] + "|" + names[c];
string kAC = names[a] + "|" + names[c];
// Le triplet (a,b,c) est parcouru dans l'ordre cyclique
// a -> b -> c -> a. La paire (c,a) n'est jamais stockee
// dans cet ordre : on prend l'oppose du residu (a,c),
// ce qui est la meme chose au signe pres, et c'est
// precisement le signe que l'holonomie somme.
var rCA = new double[residuals[kAC].Length];
for (int k = 0; k < rCA.Length; k++) rCA[k] = -residuals[kAC][k];
var h = Holonomy(residuals[kAB], residuals[kBC], rCA);
triples[names[a] + "|" + names[b] + "|" + names[c]] = h.Holonomy;
signCons.Add(h.SignConsistency);
}
}
double meanCocycle = triples.Count > 0 ? triples.Values.Average() : 0.0;
double signConsistency = signCons.Count > 0 ? signCons.Average() : 0.0;
// Les sections sont deja normalisees : on demande la dimensionnalite
// sans re-normaliser, pour ne pas ecraser une structure deja centree.
var dim = EffectiveDimensionality(secs, normalize: false);
return new CechReport
{
NProxies = n,
NWindows = secs.Count > 0 ? secs[names[0]].Length : 0,
PairwiseResiduals = pairwise,
MeanCoboundary = meanCoboundary,
TripleHolonomies = triples,
MeanCocycle = meanCocycle,
ObstructionRatio = meanCocycle / (meanCoboundary + 1e-12),
SignConsistency = signConsistency,
EffectiveRank = dim.rank,
S2OverS1 = dim.s2OverS1
};
}
// Verdict falsifiable. La mesure decisive est le cocycle triple : c'est lui
// qui porte le defaut de recollement, pas la dimension du nuage. Le rang
// SVD reste un temoin de forme, il ne decide pas. Sur ce banc le temoin
// negatif axelrod porte un cocycle nul ET un rang 1 : les deux lectures y
// concordent, le banc ne les departage pas (cf Lecture 4).
public static string Verdict(
CechReport report, double cocycleFloor = 0.05, double ratioFloor = 0.05, double signFloor = 0.5)
{
if (report.NProxies < 3) return "INCONCLUSIVE";
if (report.MeanCocycle <= cocycleFloor || report.ObstructionRatio <= ratioFloor) return "TRIVIAL";
if (report.SignConsistency < signFloor) return "INCONCLUSIVE";
return "NON_TRIVIAL";
}
// Banc falsifiable : un jeu affine (trois proxys = transformations affines
// d'un meme latent, donc recollables) et un jeu multi-dimensionnel (deux
// latents independants, donc non recollables). L'instrument ne vaut que
// s'il separe les deux.
public static Dictionary<string, double> Test(int nWindows = 60, ulong seed = 0UL)
{
var rng = new Rng64(seed);
var latent = new double[nWindows];
for (int i = 0; i < nWindows; i++) latent[i] = rng.NextNormal();
var affine = new Dictionary<string, double[]>
{
["A"] = latent.Select(v => 2.5 * v + 10.0).ToArray(),
["B"] = latent.Select(v => -0.8 * v - 3.0).ToArray(),
["C"] = latent.Select(v => 1.3 * v + 7.0).ToArray()
};
var repAff = ObstructionClass(affine);
string verdictAff = Verdict(repAff);
var x = new double[nWindows];
var y = new double[nWindows];
for (int i = 0; i < nWindows; i++) { x[i] = rng.NextNormal(); y[i] = rng.NextNormal(); }
var multi = new Dictionary<string, double[]>
{
["A"] = x,
["B"] = y,
["C"] = x.Select((v, i) => v + y[i]).ToArray()
};
var repMul = ObstructionClass(multi);
string verdictMul = Verdict(repMul);
bool passes = verdictAff == "TRIVIAL" && verdictMul == "NON_TRIVIAL";
return new Dictionary<string, double>
{
["affine_s2_over_s1"] = repAff.S2OverS1,
["affine_coboundary"] = repAff.MeanCoboundary,
["affine_cocycle"] = repAff.MeanCocycle,
["affine_sign_consistency"] = repAff.SignConsistency,
["multi_s2_over_s1"] = repMul.S2OverS1,
["multi_coboundary"] = repMul.MeanCoboundary,
["multi_cocycle"] = repMul.MeanCocycle,
["multi_sign_consistency"] = repMul.SignConsistency,
["multi_effective_rank"] = repMul.EffectiveRank,
["passes"] = passes ? 1.0 : 0.0
};
}
}
// ---------------------------------------------------------------------------
// Palette viridis locale (rendu de la heatmap sans dependre de l'API
// Colormaps de ScottPlot, dont la surface varie d'une version a l'autre)
// ---------------------------------------------------------------------------
public static class Palette
{
private static readonly byte[][] Stops =
{
new byte[] { 68, 1, 84 },
new byte[] { 72, 40, 120 },
new byte[] { 62, 74, 137 },
new byte[] { 49, 104, 142 },
new byte[] { 38, 130, 142 },
new byte[] { 31, 158, 137 },
new byte[] { 53, 183, 121 },
new byte[] { 109, 205, 89 },
new byte[] { 180, 222, 44 },
new byte[] { 253, 231, 37 }
};
public static readonly ScottPlot.Color Blanc = new ScottPlot.Color(255, 255, 255);
public static readonly ScottPlot.Color Noir = new ScottPlot.Color(0, 0, 0);
public static ScottPlot.Color Viridis(double t)
{
t = Math.Clamp(t, 0.0, 1.0);
double pos = t * (Stops.Length - 1);
int i0 = (int)Math.Floor(pos);
if (i0 >= Stops.Length - 1) i0 = Stops.Length - 2;
double f = pos - i0;
byte R = (byte)Math.Round(Stops[i0][0] + f * (Stops[i0 + 1][0] - Stops[i0][0]));
byte G = (byte)Math.Round(Stops[i0][1] + f * (Stops[i0 + 1][1] - Stops[i0][1]));
byte B = (byte)Math.Round(Stops[i0][2] + f * (Stops[i0 + 1][2] - Stops[i0][2]));
return new ScottPlot.Color(R, G, B);
}
}
// ---------------------------------------------------------------------------
// Culture (c.94 : les TROIS setters, sinon separateur decimal virgule)
// ---------------------------------------------------------------------------
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
Console.WriteLine("cech_obstruction porte en C#. Substrats pilotes : Gray-Scott, Axelrod, Grokking, May (ICT-8).");