-
Notifications
You must be signed in to change notification settings - Fork 3
/
GameProcessor.ts
267 lines (233 loc) · 6.94 KB
/
GameProcessor.ts
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
import { createReadStream } from 'node:fs';
import { Interface, createInterface } from 'node:readline';
import { EventEmitter } from 'node:events';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import os from 'node:os';
import type {
Game,
AnalysisConfig,
MultithreadConfig,
GameAndMoveCount,
WorkerMessage,
GameProcessorAnalysisConfigFull,
GameProcessorConfig
} from '../interfaces/index.js';
import GameParser from './GameParser.js';
import WorkerPool from './WorkerPool.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
/**
* Class that processes games.
*/
class GameProcessor {
configs: GameProcessorAnalysisConfigFull[];
lineReader: Interface;
readInHeader: boolean;
multithreadConfig: MultithreadConfig | null;
constructor(
configs: AnalysisConfig[],
multithreadCfg: MultithreadConfig | null
) {
this.readInHeader = false;
this.configs = [];
this.multithreadConfig = multithreadCfg;
// convert AnalysisConfigs to GameProcessorAnalysisConfigFull
for (const cfg of configs) {
const tempCfg: GameProcessorAnalysisConfigFull = {
analyzers: {
move: [],
game: []
},
analyzerData: [],
config: this.checkConfig(cfg.config || {}),
processedMoves: 0,
processedGames: 0,
cntReadGames: 0,
isDone: false
};
if (cfg.trackers) {
for (const tracker of cfg.trackers) {
if (tracker.type === 'move') {
tempCfg.analyzers.move.push(tracker);
} else if (tracker.type === 'game') {
tempCfg.analyzers.game.push(tracker);
// we need to read in the header if at least one game tracker is attached
this.readInHeader = true;
}
tempCfg.analyzerData.push({
name: tracker.constructor.name,
cfg: tracker.cfg,
path: tracker.path
});
}
}
this.configs.push(tempCfg);
}
}
/**
* Main function for parsing and analyzing.
* @param path Path to the PGN file.
* @returns Count of processed games and moves.
*/
async processPGN(path: string): Promise<GameAndMoveCount[]> {
const isMultithreaded = this.multithreadConfig !== null;
let workerPool: WorkerPool;
if (isMultithreaded)
workerPool = new WorkerPool(
os.availableParallelism(),
`${__dirname}/ChessWorker.js`
);
// create gamestore for each config
const gameStore: Game[][] = [];
this.configs.forEach(() => {
gameStore.push([]);
});
let game: Game = { moves: [] };
const gameParser = new GameParser();
// init line reader
this.lineReader = createInterface({
input: createReadStream(path),
crlfDelay: Infinity
});
// on new line
this.lineReader.on('line', (line) => {
// data tag
if (this.readInHeader && line.startsWith('[')) {
const key = line.match(/\[(.*?)\s/)[1];
const value = line.match(/"(.*?)"/)[1];
game[key] = value;
// moves
} else if (line.match(/^\d/)) {
// add current move line
game.moves = game.moves.concat(
line
.replace(/(\d+\.{1,3}\s)|(\s?\{(.*?)\})/g, '')
.split(' ')
);
// only if the result marker is in the line, all moves have been read -> start analyzing
if (line.match(/((1-0)|(0-1)|(1\/2-1\/2)|(\*))$/)) {
// remove the result from the moves array
game.moves.pop();
for (
let idxCfg = 0;
idxCfg < this.configs.length;
idxCfg += 1
) {
const cfg = this.configs[idxCfg];
if (
!cfg.isDone &&
(!cfg.config.hasFilter || cfg.config.filter(game))
) {
cfg.cntReadGames += 1;
if (isMultithreaded) {
gameStore[idxCfg].push(game);
// if enough games have been read in, start worker threads and let them analyze
if (
gameStore[idxCfg].length ===
this.multithreadConfig.batchSize
) {
workerPool.runTask(
{
games: gameStore[idxCfg],
analyzerData:
this.configs[idxCfg]
.analyzerData,
idxConfig: idxCfg
},
(err: Error, result: WorkerMessage) =>
this.addDataFromWorker(err, result)
);
gameStore[idxCfg] = [];
}
} else {
gameParser.processGame(game, cfg);
}
if (cfg.cntReadGames >= cfg.config.cntGames)
cfg.isDone = true;
}
}
game = { moves: [] };
}
}
const allDone = this.configs.reduce((a, c) => a && c.isDone, true);
if (allDone) {
this.lineReader.close();
}
});
// since the line reader reads in lines async, we need to wait here until
// all lines have been read in
await EventEmitter.once(this.lineReader, 'close');
if (isMultithreaded) {
// if on end there are still unprocessed games, start a last worker batch
for (const [idx, games] of gameStore.entries()) {
if (games.length > 0) {
const { batchSize } = this.multithreadConfig;
const nEndForks = Math.ceil(games.length / batchSize);
for (let i = 0; i < nEndForks; i += 1) {
workerPool.runTask(
{
games: games.slice(
i * batchSize,
i * batchSize + batchSize
),
analyzerData: this.configs[idx].analyzerData,
idxConfig: idx
},
(err: Error, result: WorkerMessage) =>
this.addDataFromWorker(err, result)
);
}
}
}
workerPool.flagNotifyWhenDone = true;
await EventEmitter.once(workerPool, 'done');
await workerPool.close();
}
// trigger finish events on trackers
for (const { analyzers } of this.configs) {
for (const tracker of analyzers.game) {
tracker.finish?.();
}
for (const tracker of analyzers.move) {
tracker.finish?.();
}
}
const returnVals: GameAndMoveCount[] = this.configs.map((cfg) => ({
cntGames: cfg.processedGames,
cntMoves: cfg.processedMoves
}));
return returnVals;
}
/**
* If configured for multithreading, this function adds the result from a worker
* thread to the main thread.
* @param err Error object, if an error occured.
* @param result The result of the PGN parsing from the worker thread.
*/
private addDataFromWorker(err: Error, result: WorkerMessage) {
if (err) throw err;
const { idxConfig, gameAnalyzers, moveAnalyzers, cntMoves, cntGames } =
result;
// add tracker data from this worker
for (let i = 0; i < gameAnalyzers.length; i += 1) {
this.configs[idxConfig].analyzers.game[i].add(gameAnalyzers[i]);
}
for (let i = 0; i < moveAnalyzers.length; i += 1) {
this.configs[idxConfig].analyzers.move[i].add(moveAnalyzers[i]);
}
this.configs[idxConfig].processedMoves += cntMoves;
this.configs[idxConfig].processedGames += cntGames;
}
private checkConfig(config: AnalysisConfig['config']): GameProcessorConfig {
const hasFilter = !!config.filter;
// if we need to filter the games, we need the header informations
if (hasFilter) this.readInHeader = true;
const cfg: GameProcessorConfig = {
hasFilter,
filter: hasFilter ? config.filter : () => true,
cntGames: config.cntGames || Infinity
};
return cfg;
}
}
export default GameProcessor;