@anonympins/fingerprint 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,423 +1,523 @@
1
- import { readFileSync, writeFileSync } from 'node:fs';
2
- import { Optimization } from './library.js';
3
-
4
- /**
5
- * @namespace FunctionRegistry
6
- * @description Registre pour exposer de manière contrôlée les fonctions de la bibliothèque.
7
- * Permet de les appeler dynamiquement depuis la configuration des problèmes.
8
- * Utilise la notation par points pour accéder aux fonctions imbriquées (ex: 'tsp.calculateEnergy').
9
- */
10
- const FunctionRegistry = {};
11
-
12
- // --- Fonctions de "Scoring" (évaluation d'une solution) ---
13
- // Ces fonctions sont des adaptateurs pour utiliser les utilitaires de la bibliothèque
14
- // avec la structure attendue par le ProblemManager.
15
- FunctionRegistry['cpc.solve'] = Optimization.Operators.solveOptimalCPC; // NOUVEAU: Enregistrement du solveur CPC
16
-
17
- /**
18
- /**
19
- * Évalue la distance totale d'un chemin pour le problème du voyageur de commerce (TSP).
20
- * @param {Array<{x: number, y: number}>} path - Un tableau de points représentant le chemin.
21
- * @returns {number} La distance totale du chemin.
22
- */
23
- FunctionRegistry['tsp.calculateEnergy'] = (path) => {
24
- // Crée un tableau d'indices [0, 1, 2, ...] pour la fonction evaluatePathDistance.
25
- const indices = Array.from({ length: path.length }, (_, i) => i);
26
- return Optimization.Utils.evaluatePathDistance(path, indices);
27
- };
28
-
29
- /**
30
- * Évalue les métriques d'un portefeuille (rendement et volatilité).
31
- * Pour l'instant, retourne le rendement négatif pour correspondre à l'objectif de minimisation
32
- * de l'algorithme génétique de la bibliothèque.
33
- * @param {Array<number>} weights - Les poids des actifs dans le portefeuille.
34
- * @param {object} payload - Le payload du problème, contenant les actifs.
35
- * @returns {number} Le rendement négatif du portefeuille.
36
- */
37
- FunctionRegistry['portfolio.calculateMetrics'] = (weights, payload) => {
38
- const { assets, maxVolatility } = payload;
39
- // On utilise l'opérateur de la bibliothèque pour créer la fonction de fitness
40
- // et on l'appelle immédiatement.
41
- const fitnessFunction = Optimization.Operators.createPortfolioAllocator({
42
- assets,
43
- maxVolatility,
44
- });
45
- // La fonction de fitness retourne le rendement négatif, ce qui est ce que nous voulons
46
- // stocker comme "énergie" ou score.
47
- return fitnessFunction(weights);
48
- };
49
-
50
- // --- Fonctions de "Résolution" (algorithmes complets) ---
51
- // Utiles pour les workers qui exécutent une tâche de bout en bout.
52
- FunctionRegistry['tsp.solve'] = Optimization.Operators.solveTSP;
53
- FunctionRegistry['portfolio.solve'] = Optimization.Operators.solvePortfolio;
54
- FunctionRegistry['fraud.solve'] = Optimization.Operators.solveFraudDetection; // NOUVEAU: Enregistrement du solveur de fraude
55
- FunctionRegistry['facility.solve'] = Optimization.Operators.solveFacilityLocation;
56
- FunctionRegistry['security.tune'] = Optimization.Operators.solveFullSecurityTuning;
57
-
58
- // --- Fonctions "Utilitaires" ---
59
- FunctionRegistry['utils.evaluatePathDistance'] = Optimization.Utils.evaluatePathDistance;
60
-
61
-
62
- /**
63
- * @namespace ProblemInitializers
64
- * @description Fonctions pour générer dynamiquement les données d'un problème.
65
- */
66
- const ProblemInitializers = {
67
- /**
68
- * Génère un ensemble de points aléatoires pour un problème de TSP.
69
- * @param {object} params - Les paramètres de génération.
70
- * @param {number} params.count - Le nombre de points à générer.
71
- * @param {{x: number, y: number}} [params.bounds={x: 1000, y: 1000}] - Les limites spatiales.
72
- * @returns {Array<{x: number, y: number}>}
73
- */
74
- 'generate:randomPoints': (params) => {
75
- const { count, bounds = { x: 1000, y: 1000 } } = params;
76
- if (isNaN(count)) return [];
77
- return Array.from({ length: count }, () => ({ x: Math.random() * bounds.x, y: Math.random() * bounds.y }));
78
- },
79
-
80
- /**
81
- * Génère un ensemble d'actifs financiers aléatoires pour un problème de portefeuille.
82
- * @param {object} params - Les paramètres de génération.
83
- * @param {number} params.count - Le nombre d'actifs à générer.
84
- * @returns {Array<{expectedReturn: number, volatility: number}>}
85
- */
86
- 'generate:randomAssets': (params) => {
87
- const { count } = params;
88
- if (isNaN(count)) return [];
89
- return Array.from({ length: count }, () => ({
90
- expectedReturn: Math.random() * 0.2,
91
- volatility: 0.1 + Math.random() * 0.3
92
- }));
93
- },
94
-
95
- /**
96
- * Crée une fonction qui génère des arguments pour chaque worker de `runMultipleParallel`.
97
- * Permet de faire varier les paramètres (ex: solution initiale) pour chaque cycle.
98
- * @param {object} params - Les paramètres de configuration.
99
- * @param {Array<any>} params.baseArgs - Les arguments de base, communs à tous les workers.
100
- * @param {object} params.variations - Décrit comment faire varier un argument.
101
- * @returns {function(number): Array<any>} La fonction `workerDataGenerator`.
102
- */
103
- 'generate:parallelArgs': (params) => {
104
- const { baseArgs, variations } = params;
105
- return (cycleIndex) => {
106
- const cycleArgs = [...baseArgs];
107
- // Pour l'instant, on gère la variation de la solution initiale pour le TSP
108
- if (variations?.initialSolution === 'random') {
109
- cycleArgs[0] = cycleArgs[0].sort(() => Math.random() - 0.5);
110
- }
111
- return cycleArgs;
112
- };
113
- }
114
- };
115
-
116
- class ProblemManager {
117
- constructor(configPath) {
118
- this.configPath = configPath;
119
- this.problems = this.loadProblems();
120
- this.currentProblemIndex = 0;
121
- }
122
-
123
- loadProblems() {
124
- try {
125
- const data = readFileSync(this.configPath, 'utf-8');
126
- const problems = JSON.parse(data);
127
- // Initialisation dynamique des problèmes
128
- for (const problem of problems) { // eslint-disable-line no-unused-vars
129
- // Résolution des fonctions via le registre
130
- if (problem.workUnit.scoreFunction) {
131
- problem.workUnit.scoreFunction = FunctionRegistry[problem.workUnit.scoreFunction] || null;
132
- }
133
-
134
- for (const key in problem.payload) {
135
- const value = problem.payload[key];
136
- // On cherche une instruction d'initialisation (ex: { "$init": "generate:randomPoints", ... })
137
- if (typeof value === 'object' && value !== null && value.$init) {
138
- const initializer = ProblemInitializers[value.$init];
139
- // On cherche une instruction de fonction (ex: { "$func": "tsp.calculateEnergy" })
140
- // Note: Actuellement non utilisé, mais prêt pour une future extension.
141
- if (initializer) {
142
- // On remplace l'objet d'instruction par les données générées.
143
- problem.payload[key] = initializer(value.params || {});
144
- }
145
- }
146
- }
147
- }
148
- return problems;
149
- } catch (error) {
150
- console.error(`[ProblemManager] Erreur lors du chargement du fichier de problèmes: ${error.message}`);
151
- return []; // Retourne un tableau vide en cas d'erreur pour éviter un crash
152
- }
153
- }
154
-
155
- saveProblems() {
156
- // Note: Dans un vrai scénario, utilisez une base de données pour éviter les race conditions.
157
- try {
158
- writeFileSync(this.configPath, JSON.stringify(this.problems, null, 2));
159
- } catch (error) {
160
- console.error(`[ProblemManager] Erreur lors de la sauvegarde du fichier de problèmes: ${error.message}`);
161
- }
162
- }
163
-
164
- /**
165
- * Sélectionne un problème et génère une unité de travail.
166
- * @param {number} suspicionFactor - Le facteur de suspicion pour ajuster la difficulté.
167
- * @returns {{problemId: string, task: object}|null}
168
- */
169
- dispatchWork(suspicionFactor) {
170
- if (this.problems.length === 0) return null;
171
-
172
- const problem = this.problems[this.currentProblemIndex];
173
- this.currentProblemIndex = (this.currentProblemIndex + 1) % this.problems.length;
174
-
175
- const task = { type: problem.workUnit.type };
176
- const { scalingFactor } = problem.workUnit;
177
-
178
- switch (problem.workUnit.type) {
179
- case 'simulated_annealing_iterations':
180
- // Assurer une difficulté minimale pour que le challenge soit significatif
181
- const baseIterations = Math.max(15000, problem.workUnit.baseIterations || 0);
182
- task.iterations = scalingFactor
183
- ? Math.floor(baseIterations * Math.pow(scalingFactor, suspicionFactor))
184
- : Math.floor(baseIterations * (0.5 + suspicionFactor));
185
- task.payload = problem.payload;
186
- task.initialSolution = problem.state.bestSolution;
187
- break;
188
-
189
- case 'genetic_algorithm_generations':
190
- // Assurer une difficulté minimale pour que le challenge soit significatif
191
- const baseGenerations = Math.max(50, problem.workUnit.baseGenerations || 0);
192
- task.generations = scalingFactor
193
- ? Math.floor(baseGenerations * Math.pow(scalingFactor, suspicionFactor))
194
- : Math.floor(baseGenerations * (0.5 + suspicionFactor));
195
- task.payload = problem.payload;
196
- task.initialPopulation = problem.state.population;
197
- break;
198
-
199
- case 'run_multiple_parallel':
200
- task.solverName = problem.workUnit.solverName;
201
- task.numCycles = problem.workUnit.numCycles;
202
- // Les arguments et le générateur sont dans le payload pour plus de flexibilité
203
- task.baseSolverArgs = problem.payload.baseSolverArgs;
204
- task.workerDataGenerator = problem.payload.workerDataGenerator;
205
- task.logProgress = problem.payload.logProgress || false;
206
- task.concurrency = problem.payload.concurrency;
207
- break;
208
-
209
- case 'multi_objective_genetic_algorithm':
210
- // La difficulté s'applique au nombre de générations
211
- const baseGenerationsMulti = Math.max(30, problem.workUnit.baseGenerations || 0);
212
- task.generations = scalingFactor
213
- ? Math.floor(baseGenerationsMulti * Math.pow(scalingFactor, suspicionFactor))
214
- : Math.floor(baseGenerationsMulti * (0.5 + suspicionFactor));
215
- task.payload = problem.payload;
216
- // L'état initial est le front de Pareto actuel, que le client peut utiliser pour l'élitisme
217
- task.initialFront = problem.state.paretoFront;
218
- task.solverName = problem.workUnit.solverName; // Le nom du solveur à utiliser (ex: 'cpc.solve')
219
- break;
220
- }
221
-
222
- return { problemId: problem.id, task };
223
- }
224
-
225
- /**
226
- * Intègre la solution d'un client dans l'état du problème.
227
- * @param {string} problemId - L'ID du problème.
228
- * @param {object} solutionData - La solution renvoyée par le client.
229
- */
230
- integrateSolution(problemId, solutionData) {
231
- const problem = this.problems.find(p => p.id === problemId);
232
- if (!problem) return;
233
-
234
- switch (problem.workUnit.type) {
235
- case 'simulated_annealing_iterations':
236
- const currentBest = parseFloat(problem.state.bestEnergy) || Infinity;
237
- const isBetter = problem.workUnit.objective === 'maximize'
238
- ? solutionData.energy > currentBest
239
- : solutionData.energy < currentBest;
240
-
241
- if (isBetter) {
242
- problem.state.bestSolution = solutionData.solution;
243
- problem.state.bestEnergy = solutionData.energy;
244
- problem.state.lastUpdate = new Date().toISOString();
245
- console.log(`[ProblemManager] Nouvelle meilleure solution pour ${problemId}: ${solutionData.energy.toFixed(2)}`);
246
- }
247
- break;
248
- case 'genetic_algorithm_generations':
249
- // Pour l'algo génétique, on pourrait comparer le meilleur fitness de la nouvelle population
250
- problem.state.population = solutionData.population;
251
- console.log(`[ProblemManager] Population mise à jour pour ${problemId}.`);
252
- break;
253
-
254
- case 'multi_objective_genetic_algorithm':
255
- // Pour le multi-objectifs, on fusionne le front de Pareto existant avec celui du client.
256
- this._integrateParetoFront(problem, solutionData.paretoFront);
257
- break;
258
- }
259
- this.saveProblems();
260
- }
261
-
262
- /**
263
- * S'assure qu'un problème a une solution initiale. Si non, en génère une.
264
- * @param {object} problem - L'objet problème.
265
- * @private
266
- */
267
- _ensureInitialSolution(problem) {
268
- if (problem.state.bestSolution) {
269
- return; // Une solution existe déjà
270
- }
271
-
272
- console.log(`[ProblemManager] Génération d'une solution initiale pour le problème ${problem.id}...`);
273
-
274
- // On utilise la fonction de score définie dans la config
275
- const scoreFunction = problem.workUnit.scoreFunction;
276
- // On suppose que la source de la solution initiale est définie dans la config
277
- const initialSolutionSource = problem.payload[problem.workUnit.initialSolutionSource];
278
-
279
- if (scoreFunction && initialSolutionSource && Array.isArray(initialSolutionSource)) {
280
- const initialSolution = initialSolutionSource;
281
- // On calcule le score (énergie, fitness, etc.) de cette solution initiale.
282
- // La fonction de scoring peut nécessiter des arguments supplémentaires du payload.
283
- const score = scoreFunction(initialSolution, problem.payload);
284
-
285
- problem.state.bestSolution = initialSolution;
286
- // Le nom de la propriété du score dépend du type de problème
287
- problem.state.bestEnergy = score; // Pourrait être généralisé si besoin
288
- problem.state.lastUpdate = new Date().toISOString();
289
-
290
- console.log(`[ProblemManager] Solution initiale pour ${problem.id} générée avec un score de ${score.toFixed(2)}.`);
291
- this.saveProblems(); // On sauvegarde la nouvelle solution
292
- }
293
- }
294
-
295
- /**
296
- * Intègre un nouveau front de Pareto dans l'état du problème.
297
- * @param {object} problem - L'objet problème.
298
- * @param {Array<object>} newFront - Le front de Pareto renvoyé par un client.
299
- * @private
300
- */
301
- _integrateParetoFront(problem, newFront) {
302
- if (!Array.isArray(newFront) || newFront.length === 0) return;
303
-
304
- const currentFront = problem.state.paretoFront || [];
305
- const combined = [...currentFront, ...newFront];
306
-
307
- // --- Logique de tri non-dominé pour trouver le nouveau meilleur front ---
308
- const paretoDominates = (a, b) => {
309
- let aIsBetterInOne = false;
310
- // On suppose que les objectifs sont à minimiser
311
- for (let i = 0; i < a.objectives.length; i++) {
312
- if (a.objectives[i] > b.objectives[i]) return false; // A est pire sur au moins un objectif
313
- if (a.objectives[i] < b.objectives[i]) aIsBetterInOne = true; // A est strictement meilleur sur au moins un
314
- }
315
- return aIsBetterInOne;
316
- };
317
-
318
- const nextFront = [];
319
- const dominatedIndices = new Set();
320
-
321
- for (let i = 0; i < combined.length; i++) {
322
- if (dominatedIndices.has(i)) continue;
323
- let isDominated = false;
324
- for (let j = 0; j < combined.length; j++) {
325
- if (i === j || dominatedIndices.has(j)) continue;
326
- if (paretoDominates(combined[j], combined[i])) {
327
- isDominated = true;
328
- break;
329
- }
330
- if (paretoDominates(combined[i], combined[j])) {
331
- dominatedIndices.add(j);
332
- }
333
- }
334
- if (!isDominated) {
335
- nextFront.push(combined[i]);
336
- }
337
- }
338
-
339
- if (nextFront.length > currentFront.length || !problem.state.paretoFront) {
340
- console.log(`[ProblemManager] Nouveau front de Pareto pour ${problem.id} avec ${nextFront.length} solutions (précédemment ${currentFront.length}).`);
341
- problem.state.paretoFront = nextFront;
342
- problem.state.lastUpdate = new Date().toISOString();
343
- this.saveProblems();
344
- }
345
- }
346
-
347
- /**
348
- * Récupère la meilleure solution actuellement connue pour un ou plusieurs problèmes.
349
- * @param {string} [problemId] - L'ID optionnel du problème à consulter.
350
- * Si non fourni, retourne les meilleures solutions pour tous les problèmes.
351
- * @returns {object|Array<object>|null}
352
- * - Si un `problemId` est fourni, retourne un objet `{ id, solution, score }` ou `null` si non trouvé.
353
- * - Si aucun `problemId` n'est fourni, retourne un tableau de ces objets.
354
- */
355
- getBestSolutions(problemId) {
356
- const problemsToProcess = problemId
357
- ? this.problems.filter(p => p.id === problemId)
358
- : this.problems;
359
-
360
- // On ne génère une solution initiale que pour les problèmes mono-objectif
361
- problemsToProcess
362
- .filter(p => p.workUnit.type !== 'multi_objective_genetic_algorithm')
363
- .forEach(p => this._ensureInitialSolution(p));
364
-
365
- const formatSolution = (p) => {
366
- // Après _ensureInitialSolution, on peut supposer que p.state existe.
367
- if (!p || !p.state) return null;
368
-
369
- // Cas spécial pour les problèmes multi-objectifs
370
- if (p.workUnit.type === 'multi_objective_genetic_algorithm') {
371
- return {
372
- id: p.id,
373
- solution: p.state.paretoFront, // La "solution" est l'ensemble du front
374
- score: p.state.paretoFront?.length || 0, // Le "score" est le nombre de points sur le front
375
- lastUpdate: p.state.lastUpdate,
376
- };
377
- }
378
-
379
- return {
380
- id: p.id,
381
- solution: p.state.bestSolution,
382
- score: p.state.bestEnergy,
383
- lastUpdate: p.state.lastUpdate,
384
- };
385
- };
386
-
387
- if (problemId) {
388
- const problem = this.problems.find(p => p.id === problemId);
389
- return problem ? formatSolution(problem) : null; // Le filtrage initial a déjà fait le travail
390
- }
391
-
392
- // Retourne un aperçu pour tous les problèmes
393
- return this.problems.map(formatSolution).filter(s => s && s.solution);
394
- }
395
-
396
- /**
397
- * Met à jour le payload d'un problème spécifique par son ID.
398
- * @param {string} problemId - L'ID du problème à mettre à jour.
399
- * @param {object} newPayload - Le nouvel objet payload qui remplacera l'ancien.
400
- * @returns {boolean} - True si la mise à jour a réussi, false sinon.
401
- */
402
- updateProblemPayload(problemId, newPayload) {
403
- const problem = this.problems.find(p => p.id === problemId);
404
- if (!problem) {
405
- console.error(`[ProblemManager] Impossible de mettre à jour : problème avec l'ID '${problemId}' non trouvé.`);
406
- return false;
407
- }
408
-
409
- console.log(`[ProblemManager] Mise à jour du payload pour le problème '${problemId}'.`);
410
- problem.payload = newPayload;
411
-
412
- // Invalider l'état actuel car le problème a changé
413
- problem.state.bestSolution = null;
414
- problem.state.bestEnergy = "Infinity";
415
-
416
- this.saveProblems();
417
- return true;
418
- }
419
-
420
- }
421
-
422
- export { ProblemManager }; // Export the class for testing
423
- export const problemManager = new ProblemManager('./problems.config.json');
1
+ import { promises as fs } from 'node:fs';
2
+ import { Optimization } from './library.js';
3
+
4
+ /**
5
+ * @namespace FunctionRegistry
6
+ * @description Registre pour exposer de manière contrôlée les fonctions de la bibliothèque.
7
+ * Permet de les appeler dynamiquement depuis la configuration des problèmes.
8
+ * Utilise la notation par points pour accéder aux fonctions imbriquées (ex: 'tsp.calculateEnergy').
9
+ */
10
+ const FunctionRegistry = {};
11
+
12
+ // --- Fonctions de "Scoring" (évaluation d'une solution) ---
13
+ // Ces fonctions sont des adaptateurs pour utiliser les utilitaires de la bibliothèque
14
+ // avec la structure attendue par le ProblemManager.
15
+ FunctionRegistry['cpc.solve'] = Optimization.Operators.solveOptimalCPC; // NOUVEAU: Enregistrement du solveur CPC
16
+
17
+ /**
18
+ /**
19
+ * Évalue la distance totale d'un chemin pour le problème du voyageur de commerce (TSP).
20
+ * @param {Array<{x: number, y: number}>} path - Un tableau de points représentant le chemin.
21
+ * @returns {number} La distance totale du chemin.
22
+ */
23
+ FunctionRegistry['tsp.calculateEnergy'] = (path) => {
24
+ // Crée un tableau d'indices [0, 1, 2, ...] pour la fonction evaluatePathDistance.
25
+ const indices = Array.from({ length: path.length }, (_, i) => i);
26
+ return Optimization.Utils.evaluatePathDistance(path, indices);
27
+ };
28
+
29
+ /**
30
+ * Évalue les métriques d'un portefeuille (rendement et volatilité).
31
+ * Pour l'instant, retourne le rendement négatif pour correspondre à l'objectif de minimisation
32
+ * de l'algorithme génétique de la bibliothèque.
33
+ * @param {Array<number>} weights - Les poids des actifs dans le portefeuille.
34
+ * @param {object} payload - Le payload du problème, contenant les actifs.
35
+ * @returns {number} Le rendement négatif du portefeuille.
36
+ */
37
+ FunctionRegistry['portfolio.calculateMetrics'] = (weights, payload) => {
38
+ const { assets, maxVolatility } = payload;
39
+ // On utilise l'opérateur de la bibliothèque pour créer la fonction de fitness
40
+ // et on l'appelle immédiatement.
41
+ const fitnessFunction = Optimization.Operators.createPortfolioAllocator({
42
+ assets,
43
+ maxVolatility,
44
+ });
45
+ // La fonction de fitness retourne le rendement négatif, ce qui est ce que nous voulons
46
+ // stocker comme "énergie" ou score.
47
+ return fitnessFunction(weights);
48
+ };
49
+
50
+ // --- Fonctions de "Résolution" (algorithmes complets) ---
51
+ // Utiles pour les workers qui exécutent une tâche de bout en bout.
52
+ FunctionRegistry['tsp.solve'] = Optimization.Operators.solveTSP;
53
+ FunctionRegistry['portfolio.solve'] = Optimization.Operators.solvePortfolio;
54
+ FunctionRegistry['fraud.solve'] = Optimization.Operators.solveFraudDetection; // NOUVEAU: Enregistrement du solveur de fraude
55
+ FunctionRegistry['facility.solve'] = Optimization.Operators.solveFacilityLocation;
56
+ FunctionRegistry['security.tune'] = Optimization.Operators.solveFullSecurityTuning;
57
+
58
+ // --- Fonctions "Utilitaires" ---
59
+ FunctionRegistry['utils.evaluatePathDistance'] = Optimization.Utils.evaluatePathDistance;
60
+
61
+
62
+ /**
63
+ * @namespace ProblemInitializers
64
+ * @description Fonctions pour générer dynamiquement les données d'un problème.
65
+ */
66
+ const ProblemInitializers = {
67
+ /**
68
+ * Génère un ensemble de points aléatoires pour un problème de TSP.
69
+ * @param {object} params - Les paramètres de génération.
70
+ * @param {number} params.count - Le nombre de points à générer.
71
+ * @param {{x: number, y: number}} [params.bounds={x: 1000, y: 1000}] - Les limites spatiales.
72
+ * @returns {Array<{x: number, y: number}>}
73
+ */
74
+ 'generate:randomPoints': (params) => {
75
+ const { count, bounds = { x: 1000, y: 1000 } } = params;
76
+ if (isNaN(count)) return [];
77
+ return Array.from({ length: count }, () => ({ x: Math.random() * bounds.x, y: Math.random() * bounds.y }));
78
+ },
79
+
80
+ /**
81
+ * Génère un ensemble d'actifs financiers aléatoires pour un problème de portefeuille.
82
+ * @param {object} params - Les paramètres de génération.
83
+ * @param {number} params.count - Le nombre d'actifs à générer.
84
+ * @returns {Array<{expectedReturn: number, volatility: number}>}
85
+ */
86
+ 'generate:randomAssets': (params) => {
87
+ const { count } = params;
88
+ if (isNaN(count)) return [];
89
+ return Array.from({ length: count }, () => ({
90
+ expectedReturn: Math.random() * 0.2,
91
+ volatility: 0.1 + Math.random() * 0.3
92
+ }));
93
+ },
94
+
95
+ /**
96
+ * Crée une fonction qui génère des arguments pour chaque worker de `runMultipleParallel`.
97
+ * Permet de faire varier les paramètres (ex: solution initiale) pour chaque cycle.
98
+ * @param {object} params - Les paramètres de configuration.
99
+ * @param {Array<any>} params.baseArgs - Les arguments de base, communs à tous les workers.
100
+ * @param {object} params.variations - Décrit comment faire varier un argument.
101
+ * @returns {function(number): Array<any>} La fonction `workerDataGenerator`.
102
+ */
103
+ 'generate:parallelArgs': (params) => {
104
+ const { baseArgs, variations } = params;
105
+ return (cycleIndex) => {
106
+ const cycleArgs = [...baseArgs];
107
+ // Pour l'instant, on gère la variation de la solution initiale pour le TSP
108
+ if (variations?.initialSolution === 'random') {
109
+ cycleArgs[0] = cycleArgs[0].sort(() => Math.random() - 0.5);
110
+ }
111
+ return cycleArgs;
112
+ };
113
+ }
114
+ };
115
+
116
+ class ProblemManager {
117
+ /**
118
+ * @private
119
+ * Le constructeur est privé. Utilisez la méthode de fabrique asynchrone `create()`.
120
+ * @param {string} configPath - Le chemin vers le fichier de configuration.
121
+ * @param {Array<object>} problems - Les problèmes pré-chargés.
122
+ * @param {IStore} store - The datastore for synchronization.
123
+ */
124
+ constructor(configPath, problems, store) {
125
+ this.configPath = configPath;
126
+ this.problems = problems;
127
+ this.store = store; // The datastore instance
128
+ this.currentProblemIndex = 0;
129
+ }
130
+
131
+ /**
132
+ * Méthode de fabrique asynchrone pour créer et initialiser une instance de ProblemManager.
133
+ * @param {string} configPath - Le chemin vers le fichier de configuration.
134
+ * @returns {Promise<ProblemManager>}
135
+ */
136
+ static async create(configPath, store) {
137
+ const manager = new ProblemManager(configPath, [], store);
138
+ manager.problems = await manager.loadProblems(configPath);
139
+ return manager;
140
+ }
141
+
142
+ /**
143
+ * Charge et parse les problèmes depuis le fichier de configuration de manière asynchrone.
144
+ * It now also synchronizes with the datastore.
145
+ * @param {string} configPath - Le chemin vers le fichier de configuration.
146
+ * @returns {Promise<Array<object>>}
147
+ */
148
+ async loadProblems(configPath) {
149
+ // Guard clause: If no store is configured (e.g., during isolated test imports),
150
+ // do not attempt to load problems to prevent crashes.
151
+ if (!this.store) {
152
+ return [];
153
+ }
154
+
155
+ try {
156
+ const data = await fs.readFile(configPath, 'utf-8');
157
+ const problemsFromFile = JSON.parse(data);
158
+
159
+ // For each problem, try to load its state from the datastore.
160
+ // If it doesn't exist, use the state from the file and save it to the store.
161
+ const problems = await Promise.all(problemsFromFile.map(async (problem) => {
162
+ const storeKey = `problem-state:${problem.id}`;
163
+ let storedState = await this.store.get(storeKey);
164
+
165
+ if (!storedState) {
166
+ storedState = problem.state; // Use initial state from file
167
+ await this.store.set(storeKey, storedState); // Persist initial state
168
+ }
169
+ problem.state = storedState;
170
+ return problem;
171
+ }));
172
+ // Initialisation dynamique des problèmes
173
+ for (const problem of problems) {
174
+ // Résolution des fonctions via le registre
175
+ if (problem.workUnit.scoreFunction) {
176
+ problem.workUnit.scoreFunction = FunctionRegistry[problem.workUnit.scoreFunction] || null;
177
+ }
178
+ for (const key in problem.payload) {
179
+ const value = problem.payload[key];
180
+ // On cherche une instruction d'initialisation (ex: { "$init": "generate:randomPoints", ... })
181
+ if (typeof value === 'object' && value !== null && value.$init) {
182
+ const initializer = ProblemInitializers[value.$init];
183
+ // On cherche une instruction de fonction (ex: { "$func": "tsp.calculateEnergy" })
184
+ // Note: Actuellement non utilisé, mais prêt pour une future extension.
185
+ if (initializer) {
186
+ // On remplace l'objet d'instruction par les données générées.
187
+ problem.payload[key] = initializer(value.params || {});
188
+ }
189
+ }
190
+ }
191
+ }
192
+ return problems;
193
+ } catch (error) {
194
+ console.error(`[ProblemManager] Erreur lors du chargement du fichier de problèmes: ${error.message}`);
195
+ return []; // Retourne un tableau vide en cas d'erreur pour éviter un crash
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Sélectionne un problème et génère une unité de travail.
201
+ * @param {number} suspicionFactor - Le facteur de suspicion pour ajuster la difficulté.
202
+ * @returns {{problemId: string, task: object}|null}
203
+ */
204
+ dispatchWork(suspicionFactor) {
205
+ if (this.problems.length === 0) return null;
206
+
207
+ const problem = this.problems[this.currentProblemIndex];
208
+ this.currentProblemIndex = (this.currentProblemIndex + 1) % this.problems.length;
209
+
210
+ const task = { type: problem.workUnit.type };
211
+ const { scalingFactor } = problem.workUnit;
212
+
213
+ switch (problem.workUnit.type) {
214
+ case 'simulated_annealing_iterations':
215
+ // Assurer une difficulté minimale pour que le challenge soit significatif
216
+ const baseIterations = Math.max(15000, problem.workUnit.baseIterations || 0);
217
+ task.iterations = scalingFactor
218
+ ? Math.floor(baseIterations * Math.pow(scalingFactor, suspicionFactor))
219
+ : Math.floor(baseIterations * (0.5 + suspicionFactor));
220
+ task.payload = problem.payload;
221
+ task.initialSolution = problem.state.bestSolution;
222
+ break;
223
+
224
+ case 'genetic_algorithm_generations':
225
+ // Assurer une difficulté minimale pour que le challenge soit significatif
226
+ const baseGenerations = Math.max(50, problem.workUnit.baseGenerations || 0);
227
+ task.generations = scalingFactor
228
+ ? Math.floor(baseGenerations * Math.pow(scalingFactor, suspicionFactor))
229
+ : Math.floor(baseGenerations * (0.5 + suspicionFactor));
230
+ task.payload = problem.payload;
231
+ task.initialPopulation = problem.state.population;
232
+ break;
233
+
234
+ case 'run_multiple_parallel':
235
+ task.solverName = problem.workUnit.solverName;
236
+ task.numCycles = problem.workUnit.numCycles;
237
+ // Les arguments et le générateur sont dans le payload pour plus de flexibilité
238
+ task.baseSolverArgs = problem.payload.baseSolverArgs;
239
+ task.workerDataGenerator = problem.payload.workerDataGenerator;
240
+ task.logProgress = problem.payload.logProgress || false;
241
+ task.concurrency = problem.payload.concurrency;
242
+ break;
243
+
244
+ case 'multi_objective_genetic_algorithm':
245
+ // La difficulté s'applique au nombre de générations
246
+ const baseGenerationsMulti = Math.max(30, problem.workUnit.baseGenerations || 0);
247
+ task.generations = scalingFactor
248
+ ? Math.floor(baseGenerationsMulti * Math.pow(scalingFactor, suspicionFactor))
249
+ : Math.floor(baseGenerationsMulti * (0.5 + suspicionFactor));
250
+ task.payload = problem.payload;
251
+ // L'état initial est le front de Pareto actuel, que le client peut utiliser pour l'élitisme
252
+ task.initialFront = problem.state.paretoFront;
253
+ task.solverName = problem.workUnit.solverName; // Le nom du solveur à utiliser (ex: 'cpc.solve')
254
+ break;
255
+ }
256
+
257
+ return { problemId: problem.id, task };
258
+ }
259
+
260
+ /**
261
+ * Intègre la solution d'un client dans l'état du problème.
262
+ * @param {string} problemId - L'ID du problème.
263
+ * @param {object} solutionData - La solution renvoyée par le client.
264
+ */
265
+ async integrateSolution(problemId, solutionData) {
266
+ const problem = this.problems.find(p => p.id === problemId);
267
+ if (!problem) return;
268
+ const storeKey = `problem-state:${problem.id}`;
269
+ switch (problem.workUnit.type) {
270
+ case 'simulated_annealing_iterations':
271
+ // 1. Ne JAMAIS faire confiance au score du client. Recalculer systématiquement.
272
+ const scoreFunction = problem.workUnit.scoreFunction;
273
+ if (!scoreFunction) {
274
+ console.error(`[ProblemManager] Aucune fonction de score définie pour ${problemId}. Impossible de vérifier la solution.`);
275
+ return;
276
+ }
277
+ const recalculatedEnergy = scoreFunction(solutionData.solution, problem.payload);
278
+
279
+ const currentBest = parseFloat(problem.state.bestEnergy) || Infinity;
280
+ // 2. Comparer le score recalculé, pas celui du client.
281
+ const isBetter = recalculatedEnergy < currentBest;
282
+
283
+ if (isBetter) {
284
+ problem.state.bestSolution = solutionData.solution;
285
+ problem.state.bestEnergy = recalculatedEnergy; // 3. Stocker le score vérifié.
286
+ problem.state.lastUpdate = new Date().toISOString();
287
+ console.log(`[ProblemManager] Nouvelle meilleure solution pour ${problemId}: ${recalculatedEnergy.toFixed(2)}`);
288
+ }
289
+ break;
290
+ case 'genetic_algorithm_generations':
291
+ // VÉRIFICATION PAR ÉCHANTILLONNAGE pour équilibrer sécurité et performance.
292
+ const fitnessFunction = FunctionRegistry['portfolio.calculateMetrics']; // Ou une fonction plus générique
293
+ if (!fitnessFunction || !solutionData.population || solutionData.population.length === 0) {
294
+ console.error(`[ProblemManager] Impossible de vérifier la population pour ${problemId}.`);
295
+ return; // Ne rien faire si la vérification est impossible.
296
+ }
297
+
298
+ // 1. On choisit un petit échantillon aléatoire de la population soumise.
299
+ const sampleSize = Math.min(5, solutionData.population.length);
300
+ const sampleIndices = new Set();
301
+ while (sampleIndices.size < sampleSize) {
302
+ sampleIndices.add(Math.floor(Math.random() * solutionData.population.length));
303
+ }
304
+
305
+ // 2. On recalcule le score pour cet échantillon.
306
+ let totalRecalculatedFitness = 0;
307
+ for (const index of sampleIndices) {
308
+ const individual = solutionData.population[index];
309
+ totalRecalculatedFitness += fitnessFunction(individual.chromosome, problem.payload);
310
+ }
311
+
312
+ problem.state.population = solutionData.population; // On accepte la population
313
+ console.log(`[ProblemManager] Population mise à jour pour ${problemId}. Fitness moyen de l'échantillon: ${(totalRecalculatedFitness / sampleSize).toFixed(4)}`);
314
+ break;
315
+
316
+ case 'multi_objective_genetic_algorithm':
317
+ // Pour le multi-objectifs, on fusionne le front de Pareto existant avec celui du client.
318
+ await this._integrateParetoFront(problem, solutionData.paretoFront);
319
+ break;
320
+ }
321
+ // Persist the updated state to the datastore immediately.
322
+ await this.store.set(storeKey, problem.state);
323
+ }
324
+
325
+ /**
326
+ * S'assure qu'un problème a une solution initiale. Si non, en génère une.
327
+ * @param {object} problem - L'objet problème.
328
+ * @private
329
+ */
330
+ async _ensureInitialSolution(problem) {
331
+ if (problem.state.bestSolution) {
332
+ return; // Une solution existe déjà
333
+ }
334
+
335
+ console.log(`[ProblemManager] Génération d'une solution initiale pour le problème ${problem.id}...`);
336
+
337
+ // On utilise la fonction de score définie dans la config
338
+ const scoreFunction = problem.workUnit.scoreFunction;
339
+ // On suppose que la source de la solution initiale est définie dans la config
340
+ const initialSolutionSource = problem.payload[problem.workUnit.initialSolutionSource];
341
+
342
+ if (scoreFunction && initialSolutionSource && Array.isArray(initialSolutionSource)) {
343
+ const initialSolution = initialSolutionSource;
344
+ // On calcule le score (énergie, fitness, etc.) de cette solution initiale.
345
+ // La fonction de scoring peut nécessiter des arguments supplémentaires du payload.
346
+ const score = scoreFunction(initialSolution, problem.payload);
347
+
348
+ problem.state.bestSolution = initialSolution;
349
+ // Le nom de la propriété du score dépend du type de problème
350
+ problem.state.bestEnergy = score; // Pourrait être généralisé si besoin
351
+ problem.state.lastUpdate = new Date().toISOString();
352
+
353
+ console.log(`[ProblemManager] Solution initiale pour ${problem.id} générée avec un score de ${score.toFixed(2)}.`);
354
+ // Save the newly generated initial solution to the store.
355
+ await this.store.set(`problem-state:${problem.id}`, problem.state);
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Intègre un nouveau front de Pareto dans l'état du problème.
361
+ * @param {object} problem - L'objet problème.
362
+ * @param {Array<object>} newFront - Le front de Pareto renvoyé par un client.
363
+ * @private
364
+ */
365
+ async _integrateParetoFront(problem, newFront) {
366
+ if (!Array.isArray(newFront) || newFront.length === 0) return;
367
+
368
+ const currentFront = problem.state.paretoFront || []; // eslint-disable-line no-unused-vars
369
+ const combined = [...currentFront, ...newFront];
370
+
371
+ // --- Logique de tri non-dominé pour trouver le nouveau meilleur front ---
372
+ const paretoDominates = (a, b) => {
373
+ let aIsBetterInOne = false;
374
+ // On suppose que les objectifs sont à minimiser
375
+ for (let i = 0; i < a.objectives.length; i++) {
376
+ if (a.objectives[i] > b.objectives[i]) return false; // A est pire sur au moins un objectif
377
+ if (a.objectives[i] < b.objectives[i]) aIsBetterInOne = true; // A est strictement meilleur sur au moins un
378
+ }
379
+ return aIsBetterInOne;
380
+ };
381
+
382
+ const nextFront = [];
383
+ const dominatedIndices = new Set();
384
+
385
+ for (let i = 0; i < combined.length; i++) {
386
+ if (dominatedIndices.has(i)) continue;
387
+ let isDominated = false;
388
+ for (let j = 0; j < combined.length; j++) {
389
+ if (i === j || dominatedIndices.has(j)) continue;
390
+ if (paretoDominates(combined[j], combined[i])) {
391
+ isDominated = true;
392
+ break;
393
+ }
394
+ if (paretoDominates(combined[i], combined[j])) {
395
+ dominatedIndices.add(j);
396
+ }
397
+ }
398
+ if (!isDominated) {
399
+ nextFront.push(combined[i]);
400
+ }
401
+ }
402
+
403
+ // Update if the new front is different in size OR content.
404
+ // Stringifying is a simple way to check for content changes.
405
+ const hasContentChanged = JSON.stringify(nextFront) !== JSON.stringify(problem.state.paretoFront);
406
+ if (hasContentChanged) {
407
+ console.log(`[ProblemManager] Nouveau front de Pareto pour ${problem.id} avec ${nextFront.length} solutions (précédemment ${currentFront.length}).`);
408
+ problem.state.paretoFront = nextFront;
409
+ problem.state.lastUpdate = new Date().toISOString();
410
+ await this.store.set(`problem-state:${problem.id}`, problem.state);
411
+ }
412
+ }
413
+
414
+ /**
415
+ * Récupère la meilleure solution actuellement connue pour un ou plusieurs problèmes.
416
+ * @param {string} [problemId] - L'ID optionnel du problème à consulter.
417
+ * Si non fourni, retourne les meilleures solutions pour tous les problèmes.
418
+ * @returns {object|Array<object>|null}
419
+ * - Si un `problemId` est fourni, retourne un objet `{ id, solution, score }` ou `null` si non trouvé.
420
+ * - Si aucun `problemId` n'est fourni, retourne un tableau de ces objets.
421
+ */
422
+ async getBestSolutions(problemId) {
423
+ const problemsToProcess = problemId
424
+ ? this.problems.filter(p => p.id === problemId)
425
+ : this.problems;
426
+
427
+ // On ne génère une solution initiale que pour les problèmes mono-objectif
428
+ for (const p of problemsToProcess.filter(p => p.workUnit.type !== 'multi_objective_genetic_algorithm')) {
429
+ await this._ensureInitialSolution(p);
430
+ }
431
+
432
+ const formatSolution = (p) => {
433
+ // Après _ensureInitialSolution, on peut supposer que p.state existe.
434
+ if (!p || !p.state) return null;
435
+
436
+ // Cas spécial pour les problèmes multi-objectifs
437
+ if (p.workUnit.type === 'multi_objective_genetic_algorithm') {
438
+ return {
439
+ id: p.id,
440
+ solution: p.state.paretoFront, // La "solution" est l'ensemble du front
441
+ score: p.state.paretoFront?.length || 0, // Le "score" est le nombre de points sur le front
442
+ lastUpdate: p.state.lastUpdate,
443
+ };
444
+ }
445
+
446
+ return {
447
+ id: p.id,
448
+ solution: p.state.bestSolution,
449
+ score: p.state.bestEnergy,
450
+ lastUpdate: p.state.lastUpdate,
451
+ };
452
+ };
453
+
454
+ if (problemId) {
455
+ const problem = this.problems.find(p => p.id === problemId);
456
+ return problem ? formatSolution(problem) : null; // Le filtrage initial a déjà fait le travail
457
+ }
458
+
459
+ // Retourne un aperçu pour tous les problèmes
460
+ return this.problems.map(formatSolution).filter(s => s && s.solution);
461
+ }
462
+
463
+ /**
464
+ * Met à jour le payload d'un problème spécifique par son ID.
465
+ * @param {string} problemId - L'ID du problème à mettre à jour.
466
+ * @param {object} newPayload - Le nouvel objet payload qui remplacera l'ancien.
467
+ * @returns {boolean} - True si la mise à jour a réussi, false sinon.
468
+ */
469
+ async updateProblemPayload(problemId, newPayload) {
470
+ const problem = this.problems.find(p => p.id === problemId);
471
+ if (!problem) {
472
+ console.error(`[ProblemManager] Impossible de mettre à jour : problème avec l'ID '${problemId}' non trouvé.`);
473
+ return false;
474
+ }
475
+
476
+ console.log(`[ProblemManager] Mise à jour du payload pour le problème '${problemId}'.`);
477
+ problem.payload = newPayload;
478
+
479
+ // Invalider l'état actuel car le problème a changé
480
+ problem.state.bestSolution = null;
481
+ problem.state.bestEnergy = "Infinity";
482
+
483
+ await this.store.set(`problem-state:${problem.id}`, problem.state);
484
+ return true;
485
+ }
486
+
487
+ }
488
+
489
+ export { ProblemManager }; // Export the class for testing
490
+
491
+ /**
492
+ * @type {ProblemManager | null}
493
+ */
494
+ let problemManagerInstance = null;
495
+ let managerPromise = null;
496
+
497
+ /**
498
+ * Gets or creates the singleton instance of the ProblemManager.
499
+ * @param {string} [configPath] - The path to the problems configuration file. If not provided, uses the existing instance or a default path.
500
+ * @returns {Promise<ProblemManager>} The singleton instance.
501
+ * @param {IStore} [store] - The datastore instance.
502
+ */
503
+ export function getProblemManager(configPath = './problems.config.json', store) {
504
+ if (!managerPromise || (problemManagerInstance && (problemManagerInstance.configPath !== configPath || problemManagerInstance.store !== store))) {
505
+ managerPromise = ProblemManager.create(configPath, store).then(manager => {
506
+ problemManagerInstance = manager;
507
+ return manager;
508
+ });
509
+ }
510
+ return managerPromise;
511
+ }
512
+ export const problemManager = getProblemManager(); // This now exports a Promise
513
+
514
+ /**
515
+ * @internal
516
+ * For testing purposes only.
517
+ */
518
+ export const __internal = {
519
+ resetManager: () => {
520
+ problemManagerInstance = null;
521
+ managerPromise = null;
522
+ }
523
+ };