using System;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
// Chemins relatifs au carnet : --cwd = repertoire de la serie ICT-Series
string FindTraces()
{
var dir = new DirectoryInfo(Directory.GetCurrentDirectory());
while (dir != null)
{
foreach (var candidate in new[] { Path.Combine(dir.FullName, "traces"), Path.Combine(dir.FullName, "MyIA.AI.Notebooks", "IIT", "ICT-Series", "traces") })
if (File.Exists(Path.Combine(candidate, "calib_jlens_qwen3-1-7b.npz"))) return candidate;
dir = dir.Parent;
}
throw new DirectoryNotFoundException("Répertoire des traces introuvable depuis le dossier courant.");
}
string TRACES = FindTraces();
// 5 echelles, servables en CPU
var SCALES = new Dictionary<string, string> {
["1.7B"] = "calib_jlens_qwen3-1-7b.npz",
["2B"] = "calib_jlens_qwen3-5-2b.npz",
["8B"] = "calib_jlens_qwen3-8b.npz",
["9B"] = "calib_jlens_qwen3-5-9b.npz",
["27B"] = "calib_jlens_qwen3-5-27b.npz"
};
string[] ORDER = { "1.7B", "2B", "8B", "9B", "27B" };
string[] METRICS = { "overlap10", "rel_l2", "kl" };
// Lecture bornée aux tableaux numériques NPY 1.0, sans interprétation de pickle.
double[] ReadNpy(ZipArchiveEntry entry)
{
using var stream = entry.Open();
using var reader = new BinaryReader(stream);
byte[] magic = reader.ReadBytes(6);
if (!magic.SequenceEqual(new byte[] { 0x93, 0x4e, 0x55, 0x4d, 0x50, 0x59 })) throw new InvalidDataException("Signature NPY invalide : " + entry.FullName);
byte major = reader.ReadByte(), minor = reader.ReadByte();
if (major != 1 || minor != 0) throw new InvalidDataException("Version NPY non prise en charge.");
int headerLength = reader.ReadUInt16();
string header = Encoding.ASCII.GetString(reader.ReadBytes(headerLength));
var descr = Regex.Match(header, "['\"]descr['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
var shape = Regex.Match(header, "['\"]shape['\"]\\s*:\\s*\\(([^)]*)\\)");
if (!descr.Success || !shape.Success || Regex.IsMatch(header, "['\"]fortran_order['\"]\\s*:\\s*True")) throw new InvalidDataException("En-tête NPY non pris en charge : " + header);
string dtype = descr.Groups[1].Value;
int count = 1;
foreach (string part in shape.Groups[1].Value.Split(','))
if (!string.IsNullOrWhiteSpace(part)) count = checked(count * int.Parse(part.Trim(), CultureInfo.InvariantCulture));
if (count < 0 || count > 1000000) throw new InvalidDataException("Taille NPY invalide.");
bool bigEndian = dtype.StartsWith(">");
string kind = dtype.TrimStart('<', '>', '=', '|');
int width = kind == "f8" || kind == "i8" || kind == "u8" ? 8 : kind == "f4" || kind == "i4" || kind == "u4" ? 4 : kind == "i2" || kind == "u2" ? 2 : kind == "i1" || kind == "u1" ? 1 : 0;
if (width == 0) throw new InvalidDataException("Type NPY non numérique : " + dtype);
var result = new double[count];
for (int i = 0; i < count; i++)
{
byte[] bytes = reader.ReadBytes(width);
if (bytes.Length != width) throw new EndOfStreamException(entry.FullName);
if (width > 1 && bigEndian == BitConverter.IsLittleEndian) Array.Reverse(bytes);
switch (kind)
{
case "f8": result[i] = BitConverter.ToDouble(bytes, 0); break;
case "f4": result[i] = BitConverter.ToSingle(bytes, 0); break;
case "i8": result[i] = BitConverter.ToInt64(bytes, 0); break;
case "u8": result[i] = BitConverter.ToUInt64(bytes, 0); break;
case "i4": result[i] = BitConverter.ToInt32(bytes, 0); break;
case "u4": result[i] = BitConverter.ToUInt32(bytes, 0); break;
case "i2": result[i] = BitConverter.ToInt16(bytes, 0); break;
case "u2": result[i] = BitConverter.ToUInt16(bytes, 0); break;
case "i1": result[i] = unchecked((sbyte)bytes[0]); break;
case "u1": result[i] = bytes[0]; break;
}
}
return result;
}
var rows = new List<(string scale, string concept, int layer, double frac_depth, double overlap10, double rel_l2, double kl)>();
foreach (string scale in ORDER)
{
using var archive = ZipFile.OpenRead(Path.Combine(TRACES, SCALES[scale]));
var layerEntry = archive.GetEntry("meta_layers.npy") ?? throw new InvalidDataException("meta_layers absent");
var layers = ReadNpy(layerEntry);
if (layers.Length != 2) throw new InvalidDataException("Deux couches attendues.");
double total = 2 * layers[layers.Length - 1]; // 2e couche en profondeur 0.50 -> total de couches
foreach (var entry in archive.Entries)
{
string key = entry.FullName.EndsWith(".npy", StringComparison.Ordinal) ? entry.FullName.Substring(0, entry.FullName.Length - 4) : entry.FullName;
if (key.StartsWith("meta", StringComparison.Ordinal)) continue;
int separator = key.IndexOf("__", StringComparison.Ordinal);
if (separator < 0) throw new InvalidDataException("Clé inattendue : " + key);
string concept = key.Substring(0, separator);
int ly = int.Parse(key.Substring(separator + 2), CultureInfo.InvariantCulture);
var v = ReadNpy(entry); // [overlap10, rel_l2, kl]
if (v.Length != 3 || v.Any(x => double.IsNaN(x) || double.IsInfinity(x))) throw new InvalidDataException("Métriques invalides : " + key);
rows.Add((scale, concept, ly, Math.Round(ly / total, 4), v[0], v[1], v[2]));
}
}
var concepts = rows.Select(r => r.concept).Distinct().OrderBy(x => x, StringComparer.Ordinal).ToArray();
var depths = rows.Select(r => r.frac_depth).Distinct().OrderBy(x => x).ToArray();
if (rows.Count != 50 || rows.Select(r => r.scale).Distinct().Count() != 5 || concepts.Length != 5 || !depths.SequenceEqual(new[] { 0.25, 0.5 })) throw new InvalidDataException("Structure de la table longue différente de la référence citée.");
if (rows.GroupBy(r => (r.scale, r.concept, r.frac_depth)).Any(g => g.Count() != 1)) throw new InvalidDataException("Observation dupliquée.");
Console.WriteLine($"Table longue : {rows.Count} lignes, {rows.Select(r => r.scale).Distinct().Count()} echelles, {concepts.Length} concepts");
Console.WriteLine("Profondeurs fractionnelles presentes : [" + string.Join(", ", depths.Select(x => x.ToString("0.##", CultureInfo.InvariantCulture))) + "]");
double Metric((string scale, string concept, int layer, double frac_depth, double overlap10, double rel_l2, double kl) row, string metric)
{
switch (metric) { case "overlap10": return row.overlap10; case "rel_l2": return row.rel_l2; case "kl": return row.kl; default: throw new ArgumentException("Métrique inconnue : " + metric); }
}