// CPython fournit les vrais estimateurs sklearn ; les métriques et figures restent natives.
#r "nuget: pythonnet, 3.1.0"
#load "../../../Config/PythonNetLoader.cs"
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Globalization;
using System.Security;
using Python.Runtime;
using Microsoft.DotNet.Interactive.Formatting;
public record EquitySvg(string Value);
Formatter.Register<EquitySvg>((value, writer) => writer.Write(value.Value), "image/svg+xml");
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
if (!PythonEngine.IsInitialized)
{
PythonNetLoader.Initialize(typeof(PythonEngine).Assembly, "sklearn");
PythonEngine.BeginAllowThreads();
}
JsonElement Backend(string code, object config)
{
// Le résultat JSON est détaché du scope avant libération sous le GIL.
using (Py.GIL())
{
using var scope = Py.CreateScope();
using var input = new PyString(JsonSerializer.Serialize(config));
scope.Set("config_json", input);
scope.Exec("import json, numpy as np\ncfg=json.loads(config_json)\n" + code);
using var result = scope.Get("result_json");
using var document = JsonDocument.Parse(result.As<string>());
return document.RootElement.Clone();
}
}
double[] Doubles(JsonElement x) => x.EnumerateArray().Select(v => v.GetDouble()).ToArray();
int[] Ints(JsonElement x) => x.EnumerateArray().Select(v => v.GetInt32()).ToArray();
double[][] Matrix(JsonElement x) => x.EnumerateArray().Select(Doubles).ToArray();
// SVG opaque : titres, unités, légende et graduations restent visibles sur GitHub.
EquitySvg SvgChart(string title, string xLabel, string yLabel, (string Name, double[] X, double[] Y, string Color)[] curves, double xMin = 0, double xMax = 1, double yMin = 0, double yMax = 1, bool bars = false)
{
string E(string s) => SecurityElement.Escape(s) ?? "";
double PX(double x) => 75 + 580 * (x - xMin) / (xMax - xMin);
double PY(double y) => 375 - 290 * (y - yMin) / (yMax - yMin);
var s = new StringBuilder("<svg xmlns='http://www.w3.org/2000/svg' width='760' height='470' viewBox='0 0 760 470'><rect width='760' height='470' fill='white'/><g font-family='sans-serif' font-size='12' fill='#202020'>");
s.Append($"<text x='380' y='24' text-anchor='middle' font-size='16'>{E(title)}</text>");
for (int k = 0; k <= 5; k++)
{
double x = xMin + k * (xMax - xMin) / 5;
double y = yMin + k * (yMax - yMin) / 5;
s.Append($"<path d='M75 {PY(y):F3}H655' stroke='#ddd'/><text x='67' y='{PY(y) + 4:F3}' text-anchor='end'>{y:G3}</text>");
s.Append($"<text x='{PX(x):F3}' y='395' text-anchor='middle'>{x:G3}</text>");
}
s.Append("<path d='M75 85V375H655' fill='none' stroke='#333'/>");
s.Append($"<text x='365' y='424' text-anchor='middle'>{E(xLabel)}</text><text transform='translate(18 230) rotate(-90)' text-anchor='middle'>{E(yLabel)}</text>");
for (int j = 0; j < curves.Length; j++)
{
var c = curves[j];
var points = Enumerable.Range(0, c.X.Length).Where(i => double.IsFinite(c.X[i]) && double.IsFinite(c.Y[i])).ToArray();
if (bars)
{
foreach (var i in points)
s.Append($"<rect x='{PX(c.X[i]) - 13:F3}' y='{PY(c.Y[i]):F3}' width='26' height='{375 - PY(c.Y[i]):F3}' fill='{c.Color}' stroke='white'/>");
}
else
{
var xy = string.Join(" ", points.Select(i => $"{PX(c.X[i]):F3},{PY(c.Y[i]):F3}"));
s.Append($"<polyline points='{xy}' fill='none' stroke='{c.Color}' stroke-width='2'/>");
if (c.X.Length <= 20)
foreach (var i in points)
s.Append($"<circle cx='{PX(c.X[i]):F3}' cy='{PY(c.Y[i]):F3}' r='3' fill='{c.Color}'/>");
}
s.Append($"<path d='M{85 + j * 210} 449h18' stroke='{c.Color}' stroke-width='3'/><text x='{110 + j * 210}' y='453'>{E(c.Name)}</text>");
}
return new EquitySvg(s.Append("</g></svg>").ToString());
}
Console.WriteLine($".NET {Environment.Version} ; Python.NET {typeof(PythonEngine).Assembly.GetName().Version}");
Console.WriteLine(Backend("import sklearn\nresult_json=json.dumps(dict(numpy=np.__version__,sklearn=sklearn.__version__))", new { }));- pythonnet
.NET 10.0.13 ; Python.NET 3.1.0.0
{"numpy": "2.4.2", "sklearn": "1.9.1"}