All files / lib/evolution ab_simulator.ts

0% Statements 0/39
0% Branches 0/1
0% Functions 0/1
0% Lines 0/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                                                                                                       
/**
 * Phase 6.3 — A/B Simulation Engine
 * إنشاء نسخ تجريبية (mutations) من كل policy وتجربتها افتراضيًا.
 */
 
import { mutateWeight } from './mutation_utils';
import { selectImproved } from './selection_utils';
import { EvolutionConfig } from '../../config/evolution.config';
 
/**
 * تجري محاكاة لعدة نسخ من Policy واحدة وتعيد نتائجها.
 */
export function runABSimulation(policy, metrics) {
  const results = [];
  const { populationSize, mutationRate, selectionThreshold, simulationIterations } =
    EvolutionConfig;
 
  for (let i = 0; i < populationSize; i++) {
    const mutated = { ...policy };
    mutated.weight = mutateWeight(policy.weight, mutationRate);
 
    // نحاكي الأداء الافتراضي للنسخة الجديدة
    const simulatedScores = [];
    for (let j = 0; j < simulationIterations; j++) {
      const perf = simulatePerformance(mutated.weight, metrics.evolutionScore);
      simulatedScores.push(perf);
    }
 
    const avgScore = simulatedScores.reduce((a, b) => a + b, 0) / simulatedScores.length;
    const isBetter = selectImproved(metrics.evolutionScore, avgScore, selectionThreshold);
 
    results.push({
      policyId: policy.policyId,
      baseWeight: policy.weight,
      newWeight: mutated.weight,
      avgScore,
      accepted: isBetter,
    });
  }
 
  return results;
}
 
/**
 * محاكاة أداء النسخة التجريبية بناءً على الوزن والتطور العام.
 */
function simulatePerformance(weight: number, evolutionScore: number): number {
  const randomness = Math.random() * 0.02 - 0.01; // ±1% ضوضاء
  const bias = (weight - 0.5) * 0.1; // الوزن الأعلى يميل للتحسن
  return evolutionScore + bias + randomness;
}