-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntensityModule.js
More file actions
553 lines (497 loc) · 22.5 KB
/
IntensityModule.js
File metadata and controls
553 lines (497 loc) · 22.5 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
// ============================================================================
// Intensity Module - Optional Practice Duration & Intensity Calculator
// Parallel module to Ebbinghaus SRS Core
// Copyright © 2025-2026 Frank De Baere - All Rights Reserved
// ============================================================================
/**
* IntensityModule - Optionele module voor oefenintensiteit
*
* ARCHITECTUUR:
* - Werkt PARALLEL aan de Ebbinghaus-kern (niet geïntegreerd)
* - De Ebbinghaus-kern bepaalt WANNEER (nextReviewDate, τ, Streak Reset)
* - Deze module bepaalt HOELANG en HOE INTENSIEF (duration, OLQ)
*
* METRICS (Optioneel):
* - Failed Attempts (FA): Technische moeilijkheid meten
* - Technical Difficulty Score (TDS): Leertrajectfase bepalen via Success Ratio
* - Overlearning Quotum (OLQ): Target aantal herhalingen instellen (Dr. Gebrian)
* - Gemiddelde Tijd (T̄_CR): Sessieduur voorspellen
*
* GEBRUIK:
* - Module AAN (nieuwe gebruikers/studenten): Voorspelt duur + geeft OLQ instructie
* - Module UIT (ervaren muzikanten): Vaste duur (bijv. 15min), geen OLQ instructie
*
* DATA MANAGEMENT:
* - Archiveert chunks bij CR=0 (onwerkbare data)
* - Nieuwe chunks beginnen schoon (CR=0, τ=standaard)
*/
class IntensityModule {
// Anti-Blocked Practice thresholds (minutes) — Molly Gebrian focus-block principles
static MAX_EFFECTIVE_BLOCK_DURATION = 12; // CRITICAL: above this, risk of mindless repetition
static WARNING_BLOCK_DURATION = 10; // WARNING: block is becoming long
static FRUSTRATION_GUARD_STABILITY_THRESHOLD = 2.5; // stabilityIndex above this triggers Frustration Guard
static FRUSTRATION_GUARD_ELAPSED_MINUTES = 8; // elapsed minutes above this triggers Frustration Guard
/**
* TDS thresholds voor leertrajectfasen (gebaseerd op Success Ratio)
* Pure Success Ratio: CR / (CR + FA)
*
* Fasen:
* 1. Initial Acquisition (0-40%): Veel fouten, steil leren
* 2. Refinement (40-70%): Afnemende fouten, techniek stabiliseert
* 3. Consolidation (70-85%): Weinig fouten, automatisering begint
* 4. Mastery (85-95%): Zeer weinig fouten, hoge consistentie
* 5. Overlearning (95-100%): Foutloos, ready voor performance
*/
static TDS_THRESHOLDS = {
INITIAL_ACQUISITION: 0.40, // 0-40%: Veel fouten
REFINEMENT: 0.70, // 40-70%: Afnemende fouten
CONSOLIDATION: 0.85, // 70-85%: Weinig fouten
MASTERY: 0.95, // 85-95%: Zeer weinig fouten
OVERLEARNING: 1.00 // 95-100%: Foutloos
};
/**
* OLQ mapping volgens Dr. Gebrian (leertrajectfase → target herhalingen)
* Minimum baseline = 6 correcte herhalingen, met oplopende ranges naargelang fase.
*
* Fasen:
* 1. Initial (0-40%): 6-8 CR's (begrip bevestigen met minimum 6 correcte)
* 2. Refinement (40-70%): 7-10 CR's (techniek stabiliseren)
* 3. Consolidation (70-85%): 8-12 CR's (automatisering opbouwen)
* 4. Mastery (85-95%): 9-14 CR's (diep consolideren)
* 5. Overlearning (95-100%): 10-18 CR's (performance-ready maken)
*/
static OLQ_MAPPING = {
INITIAL_ACQUISITION: { min: 6, max: 8 },
REFINEMENT: { min: 7, max: 10 },
CONSOLIDATION: { min: 8, max: 12 },
MASTERY: { min: 9, max: 14 },
OVERLEARNING: { min: 10, max: 18 }
};
/**
* Geschatte tijd per correcte herhaling (seconden) per fase
* Gebaseerd op empirische data - kan worden aangepast per gebruiker
*/
static TIME_PER_CR_ESTIMATES = {
INITIAL_ACQUISITION: 120, // 2 min per CR (veel proberen/leren)
REFINEMENT: 90, // 1.5 min per CR (techniek verfijnen)
CONSOLIDATION: 60, // 1 min per CR (automatisering)
MASTERY: 45, // 45s per CR (geautomatiseerd)
OVERLEARNING: 30 // 30s per CR (foutloos, snel)
};
/**
* Bereken Technical Difficulty Score (TDS) op basis van Success Ratio
* with optional Tempo Fluency Ratio for motor consolidation evaluation
*
* @param {number} correctRepetitions - CR (aantal succesvolle herhalingen)
* @param {number} failedAttempts - FA (aantal fouten/herhalingen)
* @param {number} achievedTempo - Achieved tempo in BPM (default 0 = not tracked)
* @param {number} targetTempo - Target tempo in BPM (default 0 = not tracked)
* @returns {number} TDS als percentage (0.0 - 1.0)
*/
static calculateTDS(correctRepetitions, failedAttempts, achievedTempo = 0, targetTempo = 0) {
// Pure Success Ratio: CR / (CR + FA)
const totalAttempts = correctRepetitions + failedAttempts;
if (totalAttempts === 0) {
return 0.0; // Geen data = TDS 0%
}
const baseTDS = correctRepetitions / totalAttempts;
// Apply Tempo Fluency Ratio if both tempo values are provided
let finalTDS = baseTDS;
if (targetTempo > 0 && achievedTempo > 0) {
// Calculate tempo ratio (capped at 1.0 so faster playing doesn't inflate score)
const tempoRatio = Math.min(1.0, achievedTempo / targetTempo);
finalTDS = baseTDS * tempoRatio;
}
// Clamp to [0.0, 1.0]
return Math.max(0.0, Math.min(1.0, finalTDS));
}
/**
* Bepaal leertrajectfase op basis van TDS
*
* @param {number} tds - Technical Difficulty Score (0.0 - 1.0)
* @returns {string} Fase naam
*/
static getLearningPhase(tds) {
if (tds < this.TDS_THRESHOLDS.INITIAL_ACQUISITION) {
return 'INITIAL_ACQUISITION';
} else if (tds < this.TDS_THRESHOLDS.REFINEMENT) {
return 'REFINEMENT';
} else if (tds < this.TDS_THRESHOLDS.CONSOLIDATION) {
return 'CONSOLIDATION';
} else if (tds < this.TDS_THRESHOLDS.MASTERY) {
return 'MASTERY';
} else {
return 'OVERLEARNING';
}
}
/**
* Bereken Overlearning Quotum (OLQ) op basis van TDS
* Dr. Gebrian's principe: aantal herhalingen schaalt met leertrajectfase
*
* @param {number} tds - Technical Difficulty Score (0.0 - 1.0)
* @returns {Object} { min, max, recommended, phase }
*/
static calculateOLQ(tds, metrics = {}) {
const {
failedAttempts = 0,
correctRepetitions = 0
} = metrics;
const phase = this.getLearningPhase(tds);
const range = this.OLQ_MAPPING[phase];
const baselineGoal = range.min;
const totalAttempts = failedAttempts + correctRepetitions;
const failuresBeforeSuccess = metrics.initialFailedAttempts ?? metrics.failedAttemptsBeforeSuccess ?? failedAttempts;
let failureRatio = 0;
let overlearningReps = 0;
if (failuresBeforeSuccess > 0) {
failureRatio = totalAttempts > 0 ? failedAttempts / totalAttempts : 1;
overlearningReps = Math.ceil(failuresBeforeSuccess * 0.5);
}
let recommended = baselineGoal + overlearningReps;
if (totalAttempts === 0) {
recommended = baselineGoal;
}
const adjustedMin = baselineGoal;
const adjustedMax = Math.max(range.max, recommended);
const adjustmentMultiplier = baselineGoal > 0 ? recommended / baselineGoal : 1;
return {
min: adjustedMin,
max: adjustedMax,
recommended: recommended,
phase: phase,
phaseDescription: this.getPhaseDescription(phase),
adjustmentMultiplier,
failureRatio,
overlearningReps
};
}
/**
* Voorspel sessieduur op basis van OLQ en leertrajectfase
*
* @param {number} olq - Overlearning Quotum (target aantal herhalingen)
* @param {number} tds - Technical Difficulty Score (0.0 - 1.0)
* @returns {Object} { durationSeconds, durationMinutes, phase }
*/
static predictSessionDuration(olq, tds) {
const phase = this.getLearningPhase(tds);
const timePerCR = this.TIME_PER_CR_ESTIMATES[phase];
// Total duration = OLQ × time per CR
const durationSeconds = olq * timePerCR;
const durationMinutes = Math.round(durationSeconds / 60);
return {
durationSeconds: durationSeconds,
durationMinutes: durationMinutes,
phase: phase,
timePerCR: timePerCR
};
}
/**
* Bereken gemiddelde tijd per correcte herhaling uit historische data
*
* @param {Array} sectionHistory - Praktijkhistorie voor deze sectie
* @returns {number} Gemiddelde tijd per CR in seconden (0 als geen data)
*/
static calculateAverageTimePerCR(sectionHistory) {
if (!sectionHistory || sectionHistory.length === 0) {
return 0;
}
// Filter sessies met geldige data
const validSessions = sectionHistory.filter(h =>
h.repetitions > 0 && h.duration > 0 && !h.isDeleted
);
if (validSessions.length === 0) {
return 0;
}
// Tel totale tijd en totale CR's
let totalTime = 0;
let totalCRs = 0;
validSessions.forEach(session => {
totalTime += session.duration / 1000; // Convert ms to seconds
totalCRs += session.repetitions;
});
if (totalCRs === 0) {
return 0;
}
return totalTime / totalCRs;
}
/**
* Bereken robuuste gemiddelde tijd per correcte herhaling (sec/CR)
* - Per sessie tijd-per-CR berekenen
* - Onrealistische waarden filteren (<5s of >600s per CR)
* - Trimmed mean (10% onder/boven) bij >=5 datapunten
*
* @param {Array} sectionHistory - Praktijkhistorie voor deze sectie
* @returns {number} Gemiddelde tijd per CR in seconden (0 als geen data)
*/
static calculateAverageTimePerCRRobust(sectionHistory) {
if (!sectionHistory || sectionHistory.length === 0) return 0;
const values = [];
for (const h of sectionHistory) {
if (!h || h.isDeleted) continue;
const reps = Number(h.repetitions || 0);
const durMs = Number(h.duration || 0);
if (reps > 0 && durMs > 0) {
const secPerCr = (durMs / 1000) / reps;
// Filter extreme outliers
if (secPerCr >= 5 && secPerCr <= 600) {
values.push(secPerCr);
}
}
}
if (values.length === 0) return 0;
values.sort((a, b) => a - b);
if (values.length >= 5) {
const trim = Math.floor(values.length * 0.10); // 10% trimming
const trimmed = values.slice(trim, values.length - trim);
const sum = trimmed.reduce((s, v) => s + v, 0);
return trimmed.length > 0 ? (sum / trimmed.length) : 0;
} else {
const sum = values.reduce((s, v) => s + v, 0);
return sum / values.length;
}
}
/**
* Genereer praktijkinstructie op basis van intensiteitsmodule status
*
* @param {boolean} moduleEnabled - Is de module ingeschakeld?
* @param {Object} olqData - OLQ berekening { min, max, recommended, phase }
* @param {Object} durationData - Duur voorspelling { durationMinutes, phase }
* @returns {Object} { instruction, duration, olq }
*/
static generatePracticeInstruction(moduleEnabled, olqData, durationData) {
if (!moduleEnabled) {
// Module UIT: Vaste duur, geen OLQ instructie
return {
instruction: 'Practice this section at your own pace.',
duration: 15, // Standaard 15 minuten
olq: null,
moduleStatus: 'disabled'
};
}
// Module AAN: Dynamische instructie
const phaseDesc = olqData.phaseDescription;
const instruction =
`${phaseDesc}\n\n` +
`Target: ${olqData.recommended} correct repetitions\n` +
`Range: ${olqData.min}-${olqData.max} repetitions\n` +
`Estimated duration: ${durationData.durationMinutes} minutes`;
return {
instruction: instruction,
duration: durationData.durationMinutes,
olq: olqData.recommended,
phase: olqData.phase,
moduleStatus: 'enabled'
};
}
/**
* Bepaal of chunk gearchiveerd moet worden (CR=0 regel)
*
* @param {number} correctRepetitions - CR (aantal succesvolle herhalingen)
* @returns {boolean} True als chunk onwerkbaar is en gearchiveerd moet worden
*/
static shouldArchiveChunk(correctRepetitions) {
// Archiveer als CR = 0 (planner kan niet werken met onwerkbare chunks)
return correctRepetitions === 0;
}
/**
* Krijg fase beschrijving voor UI
*
* @param {string} phase - Fase naam
* @returns {string} Menselijk leesbare beschrijving
*/
static getPhaseDescription(phase) {
const descriptions = {
'INITIAL_ACQUISITION': 'Initial Learning: Focus on understanding and basic execution',
'REFINEMENT': 'Refinement: Reducing errors and stabilizing technique',
'CONSOLIDATION': 'Consolidation: Building automaticity and consistency',
'MASTERY': 'Mastery: Achieving high consistency and reliability',
'OVERLEARNING': 'Overlearning: Performance-ready, minimal errors'
};
return descriptions[phase] || 'Unknown phase';
}
/**
* Genereer intensiteitsrapport voor debugging/logging
*
* @param {number} correctRepetitions - CR
* @param {number} failedAttempts - FA
* @param {Array} sectionHistory - Historische data
* @param {number} achievedTempo - Achieved tempo in BPM (default 0 = not tracked)
* @param {number} targetTempo - Target tempo in BPM (default 0 = not tracked)
* @returns {Object} Volledig rapport
*/
static generateIntensityReport(correctRepetitions, failedAttempts, sectionHistory = [], achievedTempo = 0, targetTempo = 0) {
const tds = this.calculateTDS(correctRepetitions, failedAttempts, achievedTempo, targetTempo);
const phase = this.getLearningPhase(tds);
const olq = this.calculateOLQ(tds, { failedAttempts, correctRepetitions });
const duration = this.predictSessionDuration(olq.recommended, tds);
const avgTimePerCR = this.calculateAverageTimePerCR(sectionHistory);
return {
// Metrics
metrics: {
correctRepetitions: correctRepetitions,
failedAttempts: failedAttempts,
totalAttempts: correctRepetitions + failedAttempts,
tds: tds,
tdsPercentage: Math.round(tds * 100)
},
// Leertrajectfase
phase: {
name: phase,
description: this.getPhaseDescription(phase)
},
// OLQ aanbeveling
olq: olq,
// Duur voorspelling
duration: duration,
// Historische data
history: {
sessionCount: sectionHistory.length,
avgTimePerCR: avgTimePerCR,
avgTimePerCRMinutes: avgTimePerCR > 0 ? (avgTimePerCR / 60).toFixed(1) : 0
},
// Archivering status
shouldArchive: this.shouldArchiveChunk(correctRepetitions)
};
}
/**
* Advanced session duration prediction using entryCost and stabilityIndex.
*
* Formula: EstimatedDuration = avgEntryCost + (targetReps × avgTimePerCR × stabilityIndex)
*
* This accounts for "searching time" during the Acquisition Phase and for the
* cognitive/motor resistance the learner shows across repetitions.
*
* @param {number} targetReps - Target number of correct repetitions
* @param {number} avgTimePerCR - Average seconds per correct repetition (from history)
* @param {number} avgEntryCost - Average seconds to first CR across sessions (0 = unknown)
* @param {number} stabilityIndex - totalAttempts/targetReps ratio (1.0 = perfect; default 1.0)
* @returns {{ durationSeconds: number, durationMinutes: number,
* entryCostSeconds: number, practiceTimeSeconds: number, stabilityIndex: number }}
*/
static predictSessionDurationAdvanced(targetReps, avgTimePerCR, avgEntryCost = 0, stabilityIndex = 1.0) {
const safeStability = Math.max(0.5, stabilityIndex); // never below 0.5
const practiceSeconds = targetReps * avgTimePerCR * safeStability;
const totalSeconds = avgEntryCost + practiceSeconds;
const durationMinutes = Math.max(1, Math.round(totalSeconds / 60));
let healthStatus = 'OPTIMAL';
if (durationMinutes > IntensityModule.MAX_EFFECTIVE_BLOCK_DURATION) {
healthStatus = 'CRITICAL';
} else if (durationMinutes > IntensityModule.WARNING_BLOCK_DURATION) {
healthStatus = 'WARNING';
}
return {
durationSeconds: Math.round(totalSeconds),
durationMinutes,
entryCostSeconds: Math.round(avgEntryCost),
practiceTimeSeconds: Math.round(practiceSeconds),
stabilityIndex: safeStability,
healthStatus
};
}
/**
* Calculates the average entry cost (seconds to first CR) from session history.
* Only sessions where a CR was achieved (entryCost > 0) are used.
*
* @param {Array} sectionHistory - Practice history array
* @returns {number} Average entry cost in seconds (0 if no data)
*/
static calculateAverageEntryCost(sectionHistory) {
if (!sectionHistory || sectionHistory.length === 0) return 0;
const values = sectionHistory
.filter(h => !h.isDeleted && typeof h.entryCost === 'number' && h.entryCost > 0 && h.entryCost <= 1800)
.map(h => h.entryCost);
if (values.length === 0) return 0;
return Math.round(values.reduce((s, v) => s + v, 0) / values.length);
}
/**
* Calculates the average stability index from session history.
* Sessions with no stabilityIndex stored are omitted.
*
* @param {Array} sectionHistory - Practice history array
* @returns {number} Average stability index (1.0 if no data)
*/
static calculateAverageStabilityIndex(sectionHistory) {
if (!sectionHistory || sectionHistory.length === 0) return 1.0;
const values = sectionHistory
.filter(h => !h.isDeleted && typeof h.stabilityIndex === 'number' && h.stabilityIndex > 0)
.map(h => h.stabilityIndex);
if (values.length === 0) return 1.0;
return parseFloat((values.reduce((s, v) => s + v, 0) / values.length).toFixed(3));
}
/**
* Determines whether the next session should be a quick Retention Check (3 reps).
*
* A Retention Check is appropriate when the musician demonstrated full Mastery in their
* last session: zero failures/resets, fast retrieval, and it was a full practice block
* (not already a previous retention check).
*
* Criteria:
* 1. stabilityIndex === 1.0 → no failures or streak resets (totalAttempts === targetReps)
* 2. entryCost <= avgEntryCost → retrieval was at least as fast as their historical average
* 3. targetReps >= 6 → it was a real consolidation block, not already a check
*
* @param {Object} lastSession - Most recent practice history entry for this chunk
* @param {number} avgEntryCost - Average entry cost in seconds across all sessions (from calculateAverageEntryCost)
* @returns {boolean} True when the next session should default to a 3-rep Retention Check
*/
static shouldApplyRetentionCheck(lastSession, avgEntryCost) {
if (!lastSession) return false;
const stabilityIndex = typeof lastSession.stabilityIndex === 'number'
? lastSession.stabilityIndex : null;
const entryCost = typeof lastSession.entryCost === 'number'
? lastSession.entryCost : null;
const targetReps = typeof lastSession.targetReps === 'number'
? lastSession.targetReps
: (typeof lastSession.targetRepetitions === 'number' ? lastSession.targetRepetitions : 0);
// Criterion 1: perfect session — no failures or resets
if (stabilityIndex === null || stabilityIndex !== 1.0) return false;
// Criterion 2: retrieval was not slower than their average
// If no historical avgEntryCost data is available, skip this check
if (entryCost !== null && avgEntryCost > 0 && entryCost > avgEntryCost) return false;
// Criterion 3: it was a real practice block, not already a 3-rep check
if (targetReps < 6) return false;
return true;
}
/**
* Log intensiteitsrapport naar console (voor debugging)
*
* @param {Object} report - Rapport van generateIntensityReport()
*/
static logIntensityReport(report) {
console.log(
`\n${'='.repeat(60)}\n` +
`📊 INTENSITY MODULE REPORT\n` +
`${'='.repeat(60)}\n` +
`METRICS:\n` +
` CR (Correct): ${report.metrics.correctRepetitions}\n` +
` FA (Failed): ${report.metrics.failedAttempts}\n` +
` Total Attempts: ${report.metrics.totalAttempts}\n` +
` TDS (Success Ratio): ${report.metrics.tdsPercentage}%\n` +
`\n` +
`LEARNING PHASE:\n` +
` Phase: ${report.phase.name}\n` +
` Description: ${report.phase.description}\n` +
`\n` +
`OLQ RECOMMENDATION:\n` +
` Recommended: ${report.olq.recommended} repetitions\n` +
` Range: ${report.olq.min}-${report.olq.max} repetitions\n` +
` Phase: ${report.olq.phase}\n` +
`\n` +
`DURATION PREDICTION:\n` +
` Estimated: ${report.duration.durationMinutes} minutes\n` +
` Time per CR: ${report.duration.timePerCR}s\n` +
`\n` +
`HISTORICAL DATA:\n` +
` Sessions: ${report.history.sessionCount}\n` +
` Avg Time/CR: ${report.history.avgTimePerCRMinutes} min\n` +
`\n` +
`ARCHIVING:\n` +
` Should Archive: ${report.shouldArchive ? 'YES (CR=0)' : 'NO'}\n` +
`${'='.repeat(60)}\n`
);
}
}
// Export voor gebruik in andere modules
if (typeof module !== 'undefined' && module.exports) {
module.exports = IntensityModule;
}