using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.DotNet.Interactive;
using Microsoft.DotNet.Interactive.Formatting;
// Figure : le type PlotSvg porte la balise SVG. Le formateur est enregistre pour le
// MIME image/svg+xml et ce MIME est declare prefere, afin que la figure soit
// restituee comme une image (et non comme un SVG echappe dans une sortie texte).
public record PlotSvg(string Markup);
Formatter.Register(typeof(PlotSvg), (obj, writer) => ((TextWriter)writer).Write(((PlotSvg)obj).Markup), "image/svg+xml");
Formatter.SetPreferredMimeTypesFor(typeof(PlotSvg), new[] { "image/svg+xml" });
// Parametres du protocole : meme taille de nuage, meme nombre d'injections,
// meme seuil de detection et meme marge de separation que la source.
const int CloudSize = 2000;
const int InjectedSize = 60;
const int OffRayBinCount = 60;
const int OnRayBinCount = 30;
const double DetectionThreshold = 0.01;
const double InjectionNoise = 1e-4;
const double SeparationMarginDecades = 0.2;
const double SourceOffRayMinimumTolerance = 0.30;
const double SourceOnRayMaximumTolerance = 0.30;
// Attentes du protocole reproductible du port, avec la graine xorshift64* 42.
// Chaque effectif histogramme est compare exactement ; chaque borne affichee
// est comparee a une unite de son dernier chiffre imprime.
var expectedOffRayCounts = new[] { 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 2, 1, 2, 2, 4, 5, 4, 2, 3, 7, 9, 8, 8, 13, 7, 26, 18, 24, 33, 44, 37, 47, 49, 64, 64, 76, 93, 85, 98, 121, 111, 106, 133, 122, 128, 106, 87, 70, 51, 57, 25, 20, 12, 6, 4, 1 };
var expectedOnRayCounts = new[] { 1, 0, 0, 2, 0, 1, 0, 1, 1, 0, 1, 3, 3, 1, 3, 2, 5, 1, 3, 5, 6, 3, 7, 4, 0, 1, 3, 1, 1, 1 };
const double ExpectedOffRayLow = -1.03;
const double ExpectedOffRayHigh = 0.70;
const double ExpectedOnRayLow = -4.40;
const double ExpectedOnRayHigh = -3.39;
// Une unite du dernier chiffre affiche a deux decimales : tolerance de 0.01.
const double DisplayedBoundTolerance = 0.01;
// Format d'affichage invariant : le point decimal ne depend pas de la machine.
string Inv(double value) => value.ToString("0.00", CultureInfo.InvariantCulture);
// Nuage hors-rayon : 2000 points tires (loi normale), t rendu positif ;
// meme graine declaree et meme protocole que la source, RNG cible different de torch.
var kernelRng = new Xorshift64Star(42);
var cloud = new Point4[CloudSize];
for (var k = 0; k < CloudSize; k++)
cloud[k] = new Point4(
Math.Abs(kernelRng.NextNormal()) + 0.5,
kernelRng.NextNormal(),
kernelRng.NextNormal(),
kernelRng.NextNormal());
// Points injectes sur le rayon : 60 positions reparties sur le segment [-1.5, 1.5],
// bruitees avec le meme niveau de bruit (1e-4) que la source.
var injected = new Point4[InjectedSize];
for (var k = 0; k < InjectedSize; k++)
{
var step = -1.5 + 3.0 * k / (InjectedSize - 1);
injected[k] = new Point4(
passagePoint.T + step * direction.T + InjectionNoise * kernelRng.NextNormal(),
passagePoint.X + step * direction.X + InjectionNoise * kernelRng.NextNormal(),
passagePoint.Y + step * direction.Y + InjectionNoise * kernelRng.NextNormal(),
passagePoint.Z + step * direction.Z + InjectionNoise * kernelRng.NextNormal());
}
// Scene complete : nuage puis injections, comme la concatenation de la source.
var scene = cloud.Concat(injected).ToArray();
// Residus d'incidence de toute la scene, puis prediction par seuil.
var residuals = RayKernel.Residuals(M2.PointsToHermitian(scene), omegaRay, piRay);
// Comptage des vrais/faux positifs et des manques, comme les quatre compteurs de la source.
var truePositives = 0;
var falsePositives = 0;
var falseNegatives = 0;
var trueNegatives = 0;
for (var k = 0; k < residuals.Length; k++)
{
var predicted = residuals[k] < DetectionThreshold;
var onRay = k >= CloudSize;
if (predicted && onRay) truePositives++;
else if (predicted && !onRay) falsePositives++;
else if (!predicted && onRay) falseNegatives++;
else trueNegatives++;
}
// Recoupement des effectifs : les injectes et le nuage doivent etre complets.
if (truePositives + falseNegatives != InjectedSize)
throw new InvalidOperationException("Recoupement des effectifs du rayon incorrect.");
if (falsePositives + trueNegatives != CloudSize)
throw new InvalidOperationException("Recoupement des effectifs du nuage incorrect.");
// Passage en echelle logarithmique (base 10) des deux populations.
var logResiduals = residuals.Select(r => Math.Log10(Math.Max(r, 1e-300))).ToArray();
var logsOffRay = logResiduals.Take(CloudSize).ToArray();
var logsOnRay = logResiduals.Skip(CloudSize).ToArray();
var offRayMin = logsOffRay.Min();
var onRayMax = logsOnRay.Max();
var thresholdLog = Math.Log10(DetectionThreshold);
// Separabilite : le seuil doit laisser une marge en decades entre les deux populations.
if (offRayMin - thresholdLog < SeparationMarginDecades)
throw new InvalidOperationException($"Le nuage touche le seuil : {Inv(offRayMin)} vs {Inv(thresholdLog)}");
if (thresholdLog - onRayMax < SeparationMarginDecades)
throw new InvalidOperationException($"Les points injectes touchent le seuil : {Inv(onRayMax)} vs {Inv(thresholdLog)}");
// Bornes stochastiques du port : intervalle large autour des valeurs affichees par la source,
// car le generateur cible n'est pas torch (graine 42 declaree, protocole identique).
if (Math.Abs(offRayMin - (-1.14)) > SourceOffRayMinimumTolerance)
throw new InvalidOperationException($"Minimum hors-rayon hors intervalle stochastique : {Inv(offRayMin)}");
if (Math.Abs(onRayMax - (-3.34)) > SourceOnRayMaximumTolerance)
throw new InvalidOperationException($"Maximum sur-rayon hors intervalle stochastique : {Inv(onRayMax)}");
// Verdict de detection au seuil.
Console.WriteLine($"seuil = {DetectionThreshold} : {truePositives}/{InjectedSize} points du rayon detectes, {falsePositives} faux positifs, {falseNegatives} manques");
// Histogrammes : 60 classes pour le nuage, 30 classes pour les points du rayon.
int[] Bins(double[] values, int binCount, out double lo, out double hi)
{
lo = values.Min();
hi = values.Max();
if (hi <= lo)
hi = lo + 1.0;
var counts = new int[binCount];
foreach (var value in values)
{
var index = (int)((value - lo) / (hi - lo) * binCount);
if (index < 0) index = 0;
if (index >= binCount) index = binCount - 1;
counts[index]++;
}
return counts;
}
var offCounts = Bins(logsOffRay, OffRayBinCount, out double offLo, out double offHi);
var onCounts = Bins(logsOnRay, OnRayBinCount, out double onLo, out double onHi);
// Assertions individuelles sur toutes les valeurs reellement tracees.
if (offCounts.Length != OffRayBinCount || onCounts.Length != OnRayBinCount)
throw new InvalidOperationException("Nombre de classes incorrect.");
if (offCounts.Sum() != CloudSize)
throw new InvalidOperationException("Somme des effectifs hors-rayon incorrecte.");
if (onCounts.Sum() != InjectedSize)
throw new InvalidOperationException("Somme des effectifs sur-rayon incorrecte.");
for (var k = 0; k < offCounts.Length; k++)
if (offCounts[k] != expectedOffRayCounts[k])
throw new InvalidOperationException($"Effectif hors-rayon[{k}] inattendu : {offCounts[k]} au lieu de {expectedOffRayCounts[k]}");
for (var k = 0; k < onCounts.Length; k++)
if (onCounts[k] != expectedOnRayCounts[k])
throw new InvalidOperationException($"Effectif sur-rayon[{k}] inattendu : {onCounts[k]} au lieu de {expectedOnRayCounts[k]}");
if (Math.Abs(offLo - ExpectedOffRayLow) > DisplayedBoundTolerance)
throw new InvalidOperationException($"Borne hors-rayon basse inattendue : {Inv(offLo)}");
if (Math.Abs(offHi - ExpectedOffRayHigh) > DisplayedBoundTolerance)
throw new InvalidOperationException($"Borne hors-rayon haute inattendue : {Inv(offHi)}");
if (Math.Abs(onLo - ExpectedOnRayLow) > DisplayedBoundTolerance)
throw new InvalidOperationException($"Borne sur-rayon basse inattendue : {Inv(onLo)}");
if (Math.Abs(onHi - ExpectedOnRayHigh) > DisplayedBoundTolerance)
throw new InvalidOperationException($"Borne sur-rayon haute inattendue : {Inv(onHi)}");
// Effectifs par classe et bornes des deux histogrammes.
Console.WriteLine("effectifs hors-rayon (60 classes) : [" + string.Join(", ", offCounts) + "]");
Console.WriteLine("effectifs sur-rayon (30 classes) : [" + string.Join(", ", onCounts) + "]");
Console.WriteLine($"bornes hors-rayon : [{Inv(offLo)}, {Inv(offHi)}]");
Console.WriteLine($"bornes sur-rayon : [{Inv(onLo)}, {Inv(onHi)}]");
// Cadre de la figure : meme format que la source (700 x 320), axes et legende inclus.
var xMin = Math.Min(offLo, onLo);
var xMax = Math.Max(offHi, onHi);
var yMax = (double)Math.Max(offCounts.Max(), onCounts.Max());
const double FigureWidth = 700;
const double FigureHeight = 320;
const double PlotLeft = 70;
const double PlotRight = 670;
const double PlotTop = 20;
const double PlotBottom = 265;
// Echelles lineaires vers le repere du dessin.
double XScale(double value) => PlotLeft + (value - xMin) / (xMax - xMin) * (PlotRight - PlotLeft);
double YScale(double count) => PlotBottom - count / yMax * (PlotBottom - PlotTop);
// Construction de la balise SVG.
var svg = new StringBuilder();
svg.AppendLine($"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{FigureWidth}\" height=\"{FigureHeight}\" viewBox=\"0 0 {FigureWidth} {FigureHeight}\">");
svg.AppendLine("<rect x=\"0\" y=\"0\" width=\"700\" height=\"320\" fill=\"white\"/>");
// Une serie d'histogramme : une barre par classe non vide.
void DrawSeries(double lo, double hi, int[] counts, string color)
{
for (var i = 0; i < counts.Length; i++)
{
if (counts[i] == 0)
continue;
var binLo = lo + (hi - lo) * i / counts.Length;
var binHi = lo + (hi - lo) * (i + 1) / counts.Length;
var x1 = XScale(binLo);
var x2 = XScale(binHi);
var y = YScale(counts[i]);
svg.AppendLine($"<rect x=\"{x1:F2}\" y=\"{y:F2}\" width=\"{Math.Max(x2 - x1, 0.6):F2}\" height=\"{PlotBottom - y:F2}\" fill=\"{color}\" fill-opacity=\"0.6\"/>");
}
}
// Les deux populations, puis le seuil en pointilles et le cadre des axes.
DrawSeries(offLo, offHi, offCounts, "#1f77b4");
DrawSeries(onLo, onHi, onCounts, "#ff7f0e");
var thresholdX = XScale(thresholdLog);
svg.AppendLine($"<line x1=\"{thresholdX:F2}\" y1=\"{PlotTop}\" x2=\"{thresholdX:F2}\" y2=\"{PlotBottom}\" stroke=\"black\" stroke-width=\"1\" stroke-dasharray=\"5,4\"/>");
svg.AppendLine($"<line x1=\"{PlotLeft}\" y1=\"{PlotBottom}\" x2=\"{PlotRight}\" y2=\"{PlotBottom}\" stroke=\"black\" stroke-width=\"1\"/>");
svg.AppendLine($"<line x1=\"{PlotLeft}\" y1=\"{PlotTop}\" x2=\"{PlotLeft}\" y2=\"{PlotBottom}\" stroke=\"black\" stroke-width=\"1\"/>");
// Graduations et titres des axes.
svg.AppendLine($"<text x=\"{PlotLeft}\" y=\"{PlotBottom + 16}\" font-size=\"11\" font-family=\"sans-serif\" text-anchor=\"start\">{xMin:F2}</text>");
svg.AppendLine($"<text x=\"{PlotRight}\" y=\"{PlotBottom + 16}\" font-size=\"11\" font-family=\"sans-serif\" text-anchor=\"end\">{xMax:F2}</text>");
svg.AppendLine($"<text x=\"{(PlotLeft + PlotRight) / 2:F0}\" y=\"{PlotBottom + 36}\" font-size=\"12\" font-family=\"sans-serif\" text-anchor=\"middle\">log10(residu d'incidence)</text>");
svg.AppendLine($"<text x=\"18\" y=\"{(PlotTop + PlotBottom) / 2:F0}\" font-size=\"12\" font-family=\"sans-serif\" text-anchor=\"middle\" transform=\"rotate(-90 18 {(PlotTop + PlotBottom) / 2:F0})\">nombre de points</text>");
// Legende : hors rayon, sur le rayon, seuil.
svg.AppendLine($"<rect x=\"{PlotRight - 130}\" y=\"{PlotTop + 4}\" width=\"12\" height=\"12\" fill=\"#1f77b4\" fill-opacity=\"0.6\"/>");
svg.AppendLine($"<text x=\"{PlotRight - 112}\" y=\"{PlotTop + 14}\" font-size=\"11\" font-family=\"sans-serif\">hors rayon</text>");
svg.AppendLine($"<rect x=\"{PlotRight - 130}\" y=\"{PlotTop + 20}\" width=\"12\" height=\"12\" fill=\"#ff7f0e\" fill-opacity=\"0.6\"/>");
svg.AppendLine($"<text x=\"{PlotRight - 112}\" y=\"{PlotTop + 30}\" font-size=\"11\" font-family=\"sans-serif\">sur le rayon</text>");
svg.AppendLine($"<line x1=\"{PlotRight - 130}\" y1=\"{PlotTop + 41}\" x2=\"{PlotRight - 114}\" y2=\"{PlotTop + 41}\" stroke=\"black\" stroke-dasharray=\"5,4\"/>");
svg.AppendLine($"<text x=\"{PlotRight - 112}\" y=\"{PlotTop + 45}\" font-size=\"11\" font-family=\"sans-serif\">seuil</text>");
svg.AppendLine("</svg>");
// Restitution de la figure via le formateur SVG enregistre plus haut.
display(new PlotSvg(svg.ToString()));
// Lecture : extremites des deux populations en echelle log10, puis note de parite
// (graine 42, meme protocole ; RNG different de torch, effectifs et bornes propres au port).
Console.WriteLine($"log10 residus : hors-rayon min = {Inv(offRayMin)} | sur-rayon max = {Inv(onRayMax)}");
Console.WriteLine("Note de parite : graine 42, meme protocole (2000 points, 60 injections bruitees, seuil 0.01) ; RNG different de torch, effectifs et bornes propres au port.");