#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
// Illustration 1 — la boite de PR et l'obstruction minimale.
//
// Le module Python `ict/proxy_contextuality.py` est rejoue ici en BCL pur : un
// contexte est un support extensionnel, une section globale est une affectation
// dont la restriction a chaque contexte tombe dans le support de ce contexte.
// Deux voies independantes repondent a la meme question : l'enumeration
// exhaustive bornee (l'oracle deterministe, qui canonicalise les temoins) et
// une resolution par propagation (le solveur CSP, qui ne rend aucun temoin).
public sealed class Contexte
{
public string[] Proxies { get; }
public int[][] Support { get; }
public Contexte(string[] proxies, int[][] support)
{
if (proxies == null || proxies.Length == 0)
throw new ArgumentException("un contexte doit porter au moins un proxy");
if (proxies.Distinct(StringComparer.Ordinal).Count() != proxies.Length)
throw new ArgumentException("proxys dupliques dans un contexte");
if (support == null || support.Length == 0)
throw new ArgumentException("support vide : un contexte non mesure n'est pas un contexte sans contrainte");
foreach (var t in support)
if (t.Length != proxies.Length)
throw new ArgumentException("tuple d'arite incorrecte dans un contexte");
Proxies = proxies;
Support = support;
}
public int[] Restreint(int[] affectation, Dictionary<string, int> position)
=> Proxies.Select(p => affectation[position[p]]).ToArray();
public bool Admet(int[] affectation, Dictionary<string, int> position)
{
var tup = Restreint(affectation, position);
foreach (var s in Support)
{
bool egal = true;
for (int j = 0; j < s.Length; j++)
if (s[j] != tup[j]) { egal = false; break; }
if (egal) return true;
}
return false;
}
}
public sealed class ModeleEmpirique
{
public List<Contexte> Contextes { get; }
public int[] Issues { get; }
public string[] Mesures { get; }
public Dictionary<string, int> Position { get; }
public BigInteger EspaceRecherche => BigInteger.Pow(Issues.Length, Mesures.Length);
public ModeleEmpirique(List<Contexte> contextes, int[] issues)
{
Contextes = contextes;
Issues = issues;
var vus = new List<string>();
foreach (var c in contextes)
foreach (var p in c.Proxies)
if (!vus.Contains(p)) vus.Add(p);
Mesures = vus.OrderBy(p => p, StringComparer.Ordinal).ToArray();
Position = new Dictionary<string, int>(StringComparer.Ordinal);
for (int j = 0; j < Mesures.Length; j++) Position[Mesures[j]] = j;
}
public static ModeleEmpirique FromContexts(IEnumerable<Contexte> contextes, int[]? issues = null)
{
var liste = contextes.ToList();
if (liste.Count == 0)
throw new ArgumentException("un modele empirique doit contenir au moins un contexte");
var observes = new SortedSet<int>();
foreach (var c in liste)
foreach (var t in c.Support)
foreach (var v in t) observes.Add(v);
int[] alphabet = (issues ?? observes.ToArray()).Distinct().OrderBy(o => o).ToArray();
if (alphabet.Length < 2)
throw new ArgumentException("alphabet d'issues trivial : toute assignation serait forcee");
foreach (var v in observes)
if (!alphabet.Contains(v))
throw new ArgumentException("issues hors alphabet dans les supports");
return new ModeleEmpirique(liste, alphabet);
}
}
public sealed class RapportRecouvrement
{
public Dictionary<string, int> Multiplicite { get; } = new Dictionary<string, int>(StringComparer.Ordinal);
public List<string> ProxysPartages { get; } = new List<string>();
public int NRecouvrementsDistincts { get; set; }
public List<int> TaillesSupport { get; } = new List<int>();
public int MinTailleSupport { get; set; }
public int MaxTailleSupport { get; set; }
public string? Degenerescence { get; set; }
public string RaisonDegenerescence { get; set; } = "";
}
public sealed class ResultatVerdict
{
public RapportRecouvrement Rapport { get; set; } = new RapportRecouvrement();
public bool? Satisfiable { get; set; }
public string Verdict { get; set; } = "";
public string Rationale { get; set; } = "";
public bool SolveurDisponible { get; set; }
public bool? SolveurSatisfiable { get; set; }
public string StatutSolveur { get; set; } = "";
public int SectionsGlobales { get; set; }
public int SectionsLocales { get; set; }
public int SansExtension { get; set; }
public int[]? ObstructionMinimale { get; set; }
}
public static class Csp
{
public static RapportRecouvrement Rapport(ModeleEmpirique m)
{
var r = new RapportRecouvrement();
foreach (var c in m.Contextes)
foreach (var p in c.Proxies)
r.Multiplicite[p] = r.Multiplicite.TryGetValue(p, out var n) ? n + 1 : 1;
foreach (var kv in r.Multiplicite.OrderBy(kv => kv.Key, StringComparer.Ordinal))
if (kv.Value >= 2) r.ProxysPartages.Add(kv.Key);
foreach (var c in m.Contextes) r.TaillesSupport.Add(c.Support.Length);
r.MinTailleSupport = r.TaillesSupport.Min();
r.MaxTailleSupport = r.TaillesSupport.Max();
var couvertures = new HashSet<string>(StringComparer.Ordinal);
foreach (var c in m.Contextes)
couvertures.Add(string.Join("|", c.Proxies.OrderBy(p => p, StringComparer.Ordinal)));
r.NRecouvrementsDistincts = couvertures.Count;
if (r.NRecouvrementsDistincts == 1)
{
r.Degenerescence = "degenerate_single_cover";
r.RaisonDegenerescence = "tous les contextes co-mesurent le meme ensemble de proxys : le recouvrement est trivial et la question se reduit a l'intersection des supports (accord entre protocoles). La contextualite exige un recouvrement PARTIEL, donc des proxys non conjointement mesurables";
}
else if (r.ProxysPartages.Count == 0)
{
r.Degenerescence = "degenerate_no_overlap";
r.RaisonDegenerescence = "aucun proxy n'est co-mesure dans deux contextes : les contextes sont independants, une section globale existe par construction";
}
else if (r.TaillesSupport.All(s => s == 1))
{
r.Degenerescence = "degenerate_rigid";
r.RaisonDegenerescence = "tous les supports sont des singletons : un UNSAT signifierait seulement qu'un proxy change de valeur d'un contexte a l'autre (dissociation), pas une obstruction de structure";
}
return r;
}
public static List<int[]> SectionsGlobales(ModeleEmpirique m, int maxSearch = 1 << 22, int? limit = null)
{
if (m.EspaceRecherche > maxSearch)
throw new OverflowException("espace de recherche " + m.EspaceRecherche + " > max_search " + maxSearch);
var trouvees = new List<int[]>();
int n = m.Mesures.Length;
var combinaison = new int[n];
void Explorer(int idx)
{
if (limit.HasValue && trouvees.Count >= limit.Value) return;
if (idx == n)
{
if (Compatible(m, combinaison)) trouvees.Add((int[])combinaison.Clone());
return;
}
foreach (var o in m.Issues)
{
combinaison[idx] = o;
Explorer(idx + 1);
if (limit.HasValue && trouvees.Count >= limit.Value) return;
}
}
Explorer(0);
return trouvees;
}
private static bool Compatible(ModeleEmpirique m, int[] affectation)
{
foreach (var ctx in m.Contextes)
if (!ctx.Admet(affectation, m.Position)) return false;
return true;
}
public static bool? ResoudreParPropagation(ModeleEmpirique m)
{
int n = m.Mesures.Length;
var affectation = new int[n];
var assignes = new bool[n];
bool Resoudre(int idx)
{
if (idx == n) return true;
foreach (var o in m.Issues)
{
affectation[idx] = o;
assignes[idx] = true;
if (PrefixeCompatible(m, affectation, assignes) && Resoudre(idx + 1)) return true;
assignes[idx] = false;
}
return false;
}
return Resoudre(0);
}
private static bool PrefixeCompatible(ModeleEmpirique m, int[] affectation, bool[] assignes)
{
foreach (var ctx in m.Contextes)
{
bool auMoinsUn = false;
foreach (var s in ctx.Support)
{
bool ok = true;
for (int j = 0; j < ctx.Proxies.Length; j++)
{
int idx = m.Position[ctx.Proxies[j]];
if (assignes[idx] && s[j] != affectation[idx]) { ok = false; break; }
}
if (ok) { auMoinsUn = true; break; }
}
if (!auMoinsUn) return false;
}
return true;
}
public static (int nLocal, int nSansExtension) SectionsLocales(ModeleEmpirique m, List<int[]> sections)
{
int nLocal = 0, nSans = 0;
foreach (var ctx in m.Contextes)
foreach (var tup in ctx.Support)
{
nLocal++;
bool etendue = sections.Any(s => ctx.Restreint(s, m.Position).SequenceEqual(tup));
if (!etendue) nSans++;
}
return (nLocal, nSans);
}
public static int[]? ObstructionMinimale(ModeleEmpirique m)
{
if (SectionsGlobales(m, limit: 1).Count > 0) return null;
var keep = Enumerable.Range(0, m.Contextes.Count).ToList();
bool changed = true;
while (changed)
{
changed = false;
foreach (int ci in keep.ToList())
{
if (keep.Count == 1) break;
var trial = keep.Where(idx => idx != ci).ToList();
var sous = new ModeleEmpirique(trial.Select(idx => m.Contextes[idx]).ToList(), m.Issues);
if (SectionsGlobales(sous, limit: 1).Count == 0)
{
keep = trial;
changed = true;
}
}
}
return keep.ToArray();
}
public static ResultatVerdict Verdict(ModeleEmpirique m)
{
var resultat = new ResultatVerdict();
var rapport = Rapport(m);
resultat.Rapport = rapport;
var sections = SectionsGlobales(m);
resultat.SectionsGlobales = sections.Count;
bool satExhaustive = sections.Count > 0;
// Les sections locales sont comptees meme lorsque le modele est
// insatisfaisable : elles servent alors a caracteriser l'obstruction.
var local = SectionsLocales(m, sections);
resultat.SectionsLocales = local.nLocal;
resultat.SansExtension = local.nSansExtension;
bool? satSolveur = ResoudreParPropagation(m);
resultat.SolveurDisponible = true;
resultat.SolveurSatisfiable = satSolveur;
resultat.StatutSolveur = satSolveur == true ? "SAT" : (satSolveur == false ? "INFEASIBLE" : "UNKNOWN");
if (satSolveur.HasValue && satSolveur.Value != satExhaustive)
throw new InvalidOperationException("desaccord solveur CSP / enumeration exhaustive : bug d'encodage, pas un resultat");
resultat.Satisfiable = satExhaustive;
if (rapport.Degenerescence != null)
{
resultat.Verdict = rapport.Degenerescence;
resultat.Rationale = rapport.RaisonDegenerescence;
return resultat;
}
if (!satExhaustive)
{
resultat.Verdict = "strongly_contextual";
resultat.Rationale = "aucune assignation globale ne se restreint dans le support de tous les contextes : obstruction au recollement (cran KS)";
resultat.ObstructionMinimale = ObstructionMinimale(m);
return resultat;
}
if (local.nSansExtension > 0)
{
resultat.Verdict = "logically_contextual";
resultat.Rationale = local.nSansExtension.ToString(CultureInfo.InvariantCulture) + " section(s) locale(s) observee(s) ne s'etendent a aucune section globale : obstruction partielle, localisee sur ces evenements";
}
else
{
resultat.Verdict = "non_contextual";
resultat.Rationale = sections.Count.ToString(CultureInfo.InvariantCulture) + " section(s) globale(s), et toute section locale observee s'etend : le modele est non contextuel, l'analogie KS meurt proprement";
}
return resultat;
}
}
public static class Fixtures
{
public static ModeleEmpirique BoitePr()
{
int[][] xor0 = { new[] { 0, 0 }, new[] { 1, 1 } };
int[][] xor1 = { new[] { 0, 1 }, new[] { 1, 0 } };
return ModeleEmpirique.FromContexts(new[]
{
new Contexte(new[] { "a1", "b1" }, xor0),
new Contexte(new[] { "a1", "b2" }, xor0),
new Contexte(new[] { "a2", "b1" }, xor0),
new Contexte(new[] { "a2", "b2" }, xor1),
}, new[] { 0, 1 });
}
public static ModeleEmpirique LogiqueMaisPasForte()
{
int[][] xor0 = { new[] { 0, 0 }, new[] { 1, 1 } };
int[][] elargi = { new[] { 0, 0 }, new[] { 0, 1 }, new[] { 1, 0 } };
return ModeleEmpirique.FromContexts(new[]
{
new Contexte(new[] { "a1", "b1" }, xor0),
new Contexte(new[] { "a1", "b2" }, xor0),
new Contexte(new[] { "a2", "b1" }, xor0),
new Contexte(new[] { "a2", "b2" }, elargi),
}, new[] { 0, 1 });
}
public static ModeleEmpirique NonContextuel()
{
int[][] plein = { new[] { 0, 0 }, new[] { 0, 1 }, new[] { 1, 0 }, new[] { 1, 1 } };
return ModeleEmpirique.FromContexts(new[]
{
new Contexte(new[] { "a1", "b1" }, plein),
new Contexte(new[] { "a1", "b2" }, plein),
new Contexte(new[] { "a2", "b1" }, plein),
new Contexte(new[] { "a2", "b2" }, plein),
}, new[] { 0, 1 });
}
}
public static class Verifs
{
public static void Entier(string nom, long calcule, long attendu)
{
bool ok = calcule == attendu;
Console.WriteLine((ok ? "CONFORME" : "ECART") + " — " + nom + " : calcule = "
+ calcule.ToString(CultureInfo.InvariantCulture) + " | attendu = "
+ attendu.ToString(CultureInfo.InvariantCulture));
if (!ok) throw new InvalidOperationException("Ecart sur le controle « " + nom + " »");
}
public static void Entier(string nom, BigInteger calcule, BigInteger attendu)
{
bool ok = calcule == attendu;
Console.WriteLine((ok ? "CONFORME" : "ECART") + " — " + nom + " : calcule = "
+ calcule.ToString(CultureInfo.InvariantCulture) + " | attendu = "
+ attendu.ToString(CultureInfo.InvariantCulture));
if (!ok) throw new InvalidOperationException("Ecart sur le controle « " + nom + " »");
}
public static void Vrai(string nom, bool condition)
{
Console.WriteLine((condition ? "CONFORME" : "ECART") + " — " + nom);
if (!condition) throw new InvalidOperationException("Ecart sur le controle « " + nom + " »");
}
}
var pr = Fixtures.BoitePr();
Console.WriteLine("contextes :");
foreach (var ctx in pr.Contextes)
Console.WriteLine(" (" + string.Join(", ", ctx.Proxies.Select(p => "'" + p + "'")) + ") support = ["
+ string.Join(", ", ctx.Support.Select(t => "(" + string.Join(", ", t.Select(v => v.ToString(CultureInfo.InvariantCulture))) + ")")) + "]");
Console.WriteLine();
Console.WriteLine("observables : (" + string.Join(", ", pr.Mesures.Select(m => "'" + m + "'")) + ")");
Console.WriteLine("espace de recherche : " + pr.EspaceRecherche.ToString(CultureInfo.InvariantCulture));
var verdict = Csp.Verdict(pr);
Console.WriteLine();
Console.WriteLine("satisfiable : " + (verdict.Satisfiable == true ? "True" : "False"));
Console.WriteLine("VERDICT : " + verdict.Verdict);
Console.WriteLine("solveur CSP : disponible = True | satisfiable = " + (verdict.SolveurSatisfiable == true ? "True" : "False")
+ " | statut = " + verdict.StatutSolveur);
Console.WriteLine("obstruction minimale : (" + string.Join(", ", verdict.ObstructionMinimale ?? Array.Empty<int>()) + ")");
Verifs.Entier("nombre de contextes de la boite PR", pr.Contextes.Count, 4);
Verifs.Entier("espace de recherche (2 issues ^ 4 observables)", pr.EspaceRecherche, BigInteger.Pow(2, 4));
Verifs.Entier("sections globales (enumeration exhaustive)", verdict.SectionsGlobales, 0);
Verifs.Vrai("les deux voies (enumeration exhaustive et solveur CSP) sont d'accord", verdict.SolveurSatisfiable == verdict.Satisfiable);
int nAffectations = 0;
bool gaucheToujoursPair = true;
foreach (var v1 in pr.Issues)
foreach (var v2 in pr.Issues)
foreach (var v3 in pr.Issues)
foreach (var v4 in pr.Issues)
{
int a1 = v1, a2 = v2, b1 = v3, b2 = v4;
int gauche = (a1 ^ b1) + (a1 ^ b2) + (a2 ^ b1) + (a2 ^ b2);
if (gauche % 2 != 0) gaucheToujoursPair = false;
nAffectations++;
}
Verifs.Vrai("parite : le membre de gauche est pair sur les " + nAffectations.ToString(CultureInfo.InvariantCulture) + " affectations, le membre de droite est impair", gaucheToujoursPair);
var minimale = verdict.ObstructionMinimale ?? Array.Empty<int>();
bool tousRetraitsSatisfiables = minimale.All(ci =>
Csp.SectionsGlobales(new ModeleEmpirique(pr.Contextes.Where((_, idx) => idx != ci).ToList(), pr.Issues), limit: 1).Count > 0);
Verifs.Entier("taille de l'obstruction minimale", minimale.Length, 4);
Verifs.Vrai("l'obstruction minimale est irreductible (chaque contexte retiré rend le modele satisfiable)", tousRetraitsSatisfiables);