All files / lib/evolution predictive-engine.ts

37.2% Statements 16/43
100% Branches 0/0
0% Functions 0/4
37.2% Lines 16/43

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 671x     1x         1x 1x     1x   1x   1x   1x 1x       1x   1x 1x       1x   1x 1x             1x                                                    
// lib/evolution/predictive-engine.ts
import type { EvolutionSnapshot } from './timeline';
 
/**
 * Predict next directive & stability from the last 3 snapshots.
 * - يعطي وزن أعلى لأحدث نقطة (0.2, 0.3, 0.5)
 * - يعزّز تأثير الترند (+/- 0.04) لضمان تجاوزه آخر قيمة عند الاتجاه الصاعد
 * - نفس الـ API المستخدمة في كل أجزاء النظام
 */
/**
 * @file predictive-engine.ts
 * مسؤول عن توليد وتحديث ثقة النظام في التنبؤات القادمة.
 */
 
let lastConfidence = 0.84;
 
/**
 * حساب الثقة في آخر تنبؤ (mock logic for testing)
 */
export function getPredictiveConfidence(): number {
  return lastConfidence;
}
 
/**
 * تحديث الثقة عند كل تنبؤ جديد
 */
export function updatePredictiveConfidence(newValue: number): void {
  lastConfidence = Math.max(0, Math.min(1, newValue)); // clamp بين 0 و 1
}
 
/**
 * نموذج بسيط لتوليد ثقة بناءً على استقرار النظام
 */
export function calculatePredictiveConfidence(stability: number): number {
  const noise = Math.random() * 0.05;
  const confidence = Math.min(1, Math.max(0, stability * 0.9 + 0.1 + noise));
  updatePredictiveConfidence(confidence);
  return confidence;
}
 
export function predictNext(snapshots: EvolutionSnapshot[]) {
  if (!Array.isArray(snapshots) || snapshots.length < 3) return null;
 
  const last = snapshots.slice(-3); // [oldest, middle, latest]
 
  // Weighted average toward the latest state
  const avgStability = last[0].stability * 0.2 + last[1].stability * 0.3 + last[2].stability * 0.5;
 
  // Trend direction across the window
  const trend = Math.sign(last[2].stability - last[0].stability) || 0;
 
  // Map trend -> directive
  const nextDirective = trend > 0 ? 'Expand' : trend < 0 ? 'Stabilize' : 'Hold';
 
  // Stronger influence of trend (push slightly forward)
  const predicted = +(avgStability + trend * 0.04).toFixed(3);
 
  // Confidence heuristic
  const confidence = Math.min(1, Math.abs(trend) + 0.7);
 
  return {
    nextDirective,
    predictedStability: predicted,
    confidence,
  };
}