-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathnode.ts
More file actions
455 lines (408 loc) · 11.5 KB
/
node.ts
File metadata and controls
455 lines (408 loc) · 11.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
import { Chess, Color } from 'chess.ts'
import { StockfishEvaluation, MaiaEvaluation } from '.'
import { MOVE_CLASSIFICATION_THRESHOLDS } from 'src/constants/analysis'
import { calculateMoveColor } from 'src/hooks/useAnalysisController/utils'
interface NodeAnalysis {
maia?: { [rating: string]: MaiaEvaluation }
stockfish?: StockfishEvaluation
}
export class GameNode {
private _fen: string
private _move: string | null
private _san: string | null
private _parent: GameNode | null
private _children: GameNode[]
private _mainChild: GameNode | null
private _mainline: boolean
private _analysis: NodeAnalysis
private _turn: Color
private _check: boolean
private _blunder: boolean
private _inaccuracy: boolean
private _excellentMove: boolean
private _bestMove: boolean
private _moveNumber: number
private _time: number | null
private _color: string | null
constructor(
fen: string,
move: string | null = null,
san: string | null = null,
parent: GameNode | null = null,
mainline = true,
time: number | null = null,
) {
this._fen = fen
this._move = move
this._san = san
this._parent = parent
this._children = []
this._mainChild = null
this._mainline = mainline
this._analysis = {}
this._blunder = false
this._inaccuracy = false
this._excellentMove = false
this._bestMove = false
this._turn = this.parseTurn(fen)
this._check = this.parseCheck(fen)
this._moveNumber = this.parseMoveNumber(fen, this._turn)
this._time = time
this._color = null
}
get fen(): string {
return this._fen
}
get move(): string | null {
return this._move
}
get san(): string | null {
return this._san
}
get parent(): GameNode | null {
return this._parent
}
get children(): GameNode[] {
return this._children
}
get isMainline(): boolean {
return this._mainline
}
get mainChild(): GameNode | null {
return this._mainChild
}
get analysis(): NodeAnalysis {
return this._analysis
}
get turn(): Color {
return this._turn
}
get check(): boolean {
return this._check
}
get blunder(): boolean {
return this._blunder
}
get inaccuracy(): boolean {
return this._inaccuracy
}
get excellentMove(): boolean {
return this._excellentMove
}
get bestMove(): boolean {
return this._bestMove
}
get moveNumber(): number {
return this._moveNumber
}
get time(): number | null {
return this._time
}
get color(): string | null {
return this._color
}
private parseTurn(fen: string): Color {
const parts = fen.split(' ')
if (parts[1] === 'w' || parts[1] === 'b') {
return parts[1]
}
return 'w'
}
private parseMoveNumber(fen: string, turn: string): number {
const parts = fen.split(' ')
const fullMoveNumber = parseInt(parts[5], 10)
if (Number.isNaN(fullMoveNumber)) {
return 1
}
return fullMoveNumber - (turn === 'w' ? 1 : 0)
}
private parseCheck(fen: string): boolean {
try {
const chess = new Chess(fen)
return chess.inCheck()
} catch {
return false
}
}
private performMoveClassification(
stockfishEval: StockfishEvaluation,
maiaEval: { [rating: string]: MaiaEvaluation } | undefined,
move: string,
activeModel?: string,
): {
blunder: boolean
inaccuracy: boolean
excellent: boolean
bestMove: boolean
} {
if (!stockfishEval || stockfishEval.depth < 12) {
return {
blunder: false,
inaccuracy: false,
excellent: false,
bestMove: false,
}
}
const bestMove = move === stockfishEval.model_move
let blunder = false
let inaccuracy = false
let excellent = false
if (stockfishEval.winrate_loss_vec) {
const winrateLoss = stockfishEval.winrate_loss_vec[move]
if (winrateLoss !== undefined) {
const absoluteWinrateLoss = Math.abs(winrateLoss)
// Blunder: More than 10% winrate loss
blunder =
absoluteWinrateLoss >=
MOVE_CLASSIFICATION_THRESHOLDS.BLUNDER_THRESHOLD
// Inaccuracy: More than 5% winrate loss (but not a blunder)
inaccuracy =
!blunder &&
absoluteWinrateLoss >=
MOVE_CLASSIFICATION_THRESHOLDS.INACCURACY_THRESHOLD
}
} else {
// Fallback to centipawn-based classification if winrate not available
const relative_eval = stockfishEval.cp_relative_vec?.[move]
if (relative_eval !== undefined) {
blunder = relative_eval < -150
}
}
// Excellent move criteria: Less than 10% Maia probability AND
// at least 10% higher winrate than weighted average
if (
maiaEval &&
activeModel &&
maiaEval[activeModel] &&
stockfishEval.winrate_vec
) {
const policy = maiaEval[activeModel].policy
if (policy && move in policy) {
const probability = policy[move]
// Check Maia probability threshold
const lowMaiaProbability =
probability <= MOVE_CLASSIFICATION_THRESHOLDS.MAIA_UNLIKELY_THRESHOLD
if (lowMaiaProbability) {
// Calculate weighted average winrate using Maia probabilities as weights
const weightedAverageWinrate = this.calculateWeightedAverageWinrate(
stockfishEval.winrate_vec,
policy,
)
const currentMoveWinrate = stockfishEval.winrate_vec[move]
if (
currentMoveWinrate !== undefined &&
weightedAverageWinrate !== null
) {
// Check if current move is at least x% higher than weighted average
excellent =
currentMoveWinrate >=
weightedAverageWinrate +
MOVE_CLASSIFICATION_THRESHOLDS.EXCELLENT_WINRATE_ADVANTAGE_THRESHOLD
}
}
}
}
return {
blunder,
inaccuracy,
excellent,
bestMove,
}
}
// Helper method to calculate weighted average winrate
private calculateWeightedAverageWinrate(
winrateVec: { [move: string]: number },
maiaPolicy: { [move: string]: number },
): number | null {
let totalWeight = 0
let weightedSum = 0
// Calculate weighted sum using Maia probabilities as weights
for (const move in maiaPolicy) {
const weight = maiaPolicy[move]
const winrate = winrateVec[move]
if (weight !== undefined && winrate !== undefined) {
weightedSum += weight * winrate
totalWeight += weight
}
}
// Return weighted average, or null if no valid data
return totalWeight > 0 ? weightedSum / totalWeight : null
}
private classifyMoveByWinrate(
node: GameNode,
move: string,
stockfishEval: StockfishEvaluation,
activeModel?: string,
): void {
const classification = this.performMoveClassification(
stockfishEval,
this._analysis.maia,
move,
activeModel,
)
node._bestMove = classification.bestMove
node._blunder = classification.blunder
node._inaccuracy = classification.inaccuracy
node._excellentMove = classification.excellent
}
addChild(
fen: string,
move: string,
san: string,
mainline = false,
activeModel?: string,
time?: number,
): GameNode {
const child = new GameNode(fen, move, san, this, mainline, time || null)
this._children.push(child)
if (mainline) {
this._mainChild = child
}
if (
this._analysis.stockfish &&
this._analysis.stockfish.depth >= 12 &&
move
) {
this.classifyMoveByWinrate(
child,
move,
this._analysis.stockfish,
activeModel,
)
child._color = calculateMoveColor(this._analysis.stockfish, move)
}
return child
}
addMaiaAnalysis(
maiaEval: { [rating: string]: MaiaEvaluation },
activeModel?: string,
): void {
this._analysis.maia = maiaEval
if (this._analysis.stockfish && this._analysis.stockfish.depth >= 12) {
for (const child of this._children) {
if (child.move) {
this.classifyMoveByWinrate(
child,
child.move,
this._analysis.stockfish,
activeModel,
)
}
}
}
}
addStockfishAnalysis(
stockfishEval: StockfishEvaluation,
activeModel?: string,
): void {
const existingStockfish = this._analysis.stockfish
if (existingStockfish) {
if (existingStockfish.depth > stockfishEval.depth) {
return
}
if (existingStockfish.depth === stockfishEval.depth) {
const existingDiagnostics = existingStockfish.diagnostics
const incomingDiagnostics = stockfishEval.diagnostics
const existingStrategy = existingStockfish.diagnostics?.strategy
const incomingStrategy = stockfishEval.diagnostics?.strategy
const existingPositionId = existingStockfish.diagnostics?.positionId
const incomingPositionId = stockfishEval.diagnostics?.positionId
const isSameRun =
!!incomingStrategy &&
!!existingStrategy &&
incomingStrategy === existingStrategy &&
!!incomingPositionId &&
!!existingPositionId &&
incomingPositionId === existingPositionId
const incomingIsLaterSameRunSnapshot =
isSameRun &&
!!incomingDiagnostics &&
!!existingDiagnostics &&
incomingDiagnostics.totalTimeMs >= existingDiagnostics.totalTimeMs
const shouldReplaceSameDepth =
(incomingStrategy &&
existingStrategy &&
incomingStrategy !== existingStrategy) ||
(incomingPositionId &&
existingPositionId &&
incomingPositionId !== existingPositionId) ||
(!!stockfishEval.diagnostics && !existingStockfish.diagnostics) ||
incomingIsLaterSameRunSnapshot
if (!shouldReplaceSameDepth) {
return
}
}
}
this._analysis.stockfish = stockfishEval
if (stockfishEval.depth >= 12) {
for (const child of this._children) {
if (child.move) {
this.classifyMoveByWinrate(
child,
child.move,
stockfishEval,
activeModel,
)
child._color = calculateMoveColor(stockfishEval, child.move)
}
}
}
}
getMainLine(): GameNode[] {
if (!this._mainChild) {
return [this]
}
return [this, ...this._mainChild.getMainLine()]
}
getVariations(): GameNode[] {
return this._children.filter((child) => !child.isMainline)
}
findVariation(move: string): GameNode | null {
return (
this._children.find(
(child) => child.move === move && !child.isMainline,
) || null
)
}
getPath(): GameNode[] {
if (!this._parent) {
return [this]
}
return [...this._parent.getPath(), this]
}
removeVariation(move: string): boolean {
const index = this._children.findIndex(
(child) => child.move === move && !child.isMainline,
)
if (index !== -1) {
this._children.splice(index, 1)
return true
}
return false
}
removeAllChildren(): void {
this._children = []
this._mainChild = null
}
setTime(time: number): void {
this._time = time
}
static classifyMove(
parentNode: GameNode,
move: string,
currentMaiaModel?: string,
): {
blunder: boolean
inaccuracy: boolean
excellent: boolean
bestMove: boolean
} {
const tempNode = new GameNode('temp')
return tempNode.performMoveClassification(
parentNode.analysis.stockfish || ({} as StockfishEvaluation),
parentNode.analysis.maia,
move,
currentMaiaModel,
)
}
}