Skip to content

Commit fc64c78

Browse files
fix: stockfish analysis for tournament games
1 parent daa12d5 commit fc64c78

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/api/analysis/analysis.ts

+52
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
Player,
44
MoveMap,
55
GameTree,
6+
GameNode,
67
AnalyzedGame,
78
MaiaEvaluation,
89
LegacyAnalyzedGame,
@@ -35,6 +36,37 @@ function buildGameTree(moves: any[], initialFen: string) {
3536
return tree
3637
}
3738

39+
function convertMoveMapToStockfishEval(
40+
moveMap: MoveMap,
41+
moveKey: string,
42+
): StockfishEvaluation {
43+
const cp_vec: { [key: string]: number } = {}
44+
const cp_relative_vec: { [key: string]: number } = {}
45+
let model_optimal_cp = -Infinity
46+
let model_move = ''
47+
48+
for (const move in moveMap) {
49+
cp_vec[move] = moveMap[move]
50+
if (moveMap[move] > model_optimal_cp) {
51+
model_optimal_cp = moveMap[move]
52+
model_move = move
53+
}
54+
}
55+
56+
for (const move in cp_vec) {
57+
cp_relative_vec[move] = model_optimal_cp - cp_vec[move]
58+
}
59+
60+
return {
61+
sent: true,
62+
depth: 20,
63+
model_move: model_move,
64+
model_optimal_cp: model_optimal_cp,
65+
cp_vec: cp_vec,
66+
cp_relative_vec: cp_relative_vec,
67+
}
68+
}
69+
3870
const readStream = (processLine: (data: any) => void) => (response: any) => {
3971
const stream = response.body.getReader()
4072
const matcher = /\r?\n/
@@ -482,6 +514,26 @@ export const getAnalyzedTournamentGame = async (gameId = ['FkgYSri1']) => {
482514

483515
const tree = buildGameTree(moves, moves[0].board)
484516

517+
let currentNode = tree.getRoot() as GameNode
518+
for (let i = 0; i < moves.length; i++) {
519+
const move = moves[i]
520+
521+
if (move.lastMove) {
522+
const [from, to] = move.lastMove
523+
const moveKey = from + to
524+
const stockfishEval = stockfishEvaluations[i]
525+
? convertMoveMapToStockfishEval(stockfishEvaluations[i], moveKey)
526+
: undefined
527+
528+
if (stockfishEval) {
529+
currentNode = currentNode.mainChild
530+
if (currentNode) {
531+
currentNode.addStockfishAnalysis(stockfishEval)
532+
}
533+
}
534+
}
535+
}
536+
485537
return {
486538
id,
487539
blackPlayer,

0 commit comments

Comments
 (0)