Moteur : chances de gagner le match (table de gnubg), export SGF d'un match entier
Commande mwc d'engine-cli et engine_match_chances_of : chances au score (getMEAtScore) et conversion d'une équité (eq2mwc), comparées à gnubg de bureau. Export d'un match entier en SGF, relu par gnubg (load match). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
ee661661fd
commit
f9b8663afb
@@ -69,6 +69,12 @@ export interface Engine {
|
||||
points: number,
|
||||
): Promise<EngineMatchAfter>;
|
||||
|
||||
/** Les chances de gagner le match du joueur au trait (cube.match
|
||||
* obligatoire), d'après la table d'équité de match du moteur : au
|
||||
* score, avant la partie, et pour l'équité normalisée equity (une
|
||||
* évaluation, ou une perte d'équité), avec ce videau et ce score. */
|
||||
matchChances(cube: EngineCube, equity: number): Promise<MatchChances>;
|
||||
|
||||
/** L'analyse du coup joué (played : position après le coup, vue du joueur
|
||||
* qui l'a joué, comme Move.position), au niveau d'analyse ply ; null si
|
||||
* aucun coup n'était possible. */
|
||||
@@ -129,6 +135,23 @@ export interface MatchDescription {
|
||||
readonly jacoby: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Les chances de gagner le match d'un joueur, selon le moteur (table
|
||||
* d'équité de match de gnubg, Kazaross-XG2), de 0 à 1.
|
||||
*
|
||||
* Glossaire : docs/glossaire/chances-de-gagner-le-match.md
|
||||
*/
|
||||
export interface MatchChances {
|
||||
/** Au score du match, avant la partie (la table elle-même). */
|
||||
readonly atScore: number;
|
||||
/** Pour l'équité demandée (eq2mwc de gnubg). */
|
||||
readonly ofEquity: number;
|
||||
/** L'équité demandée vue comme une perte (ou un gain) : ses chances
|
||||
* moins celles d'une équité nulle, comme le coût d'une erreur dans
|
||||
* les statistiques de match de gnubg. */
|
||||
readonly ofLoss: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Niveau de jeu de l'ordinateur : un réglage prédéfini de GNU Backgammon
|
||||
* (aecSettings dans eval.c ; voir engine/include/engine.h). Les quatre
|
||||
|
||||
@@ -35,6 +35,9 @@ export interface SgfOptions {
|
||||
readonly computerName: string;
|
||||
/** Date de la partie, AAAA-MM-JJ (DT) ; absente si non fournie. */
|
||||
readonly date?: string;
|
||||
/** Dans un match exporté entier, l'indice de la partie (à partir de 0,
|
||||
* comme MI[game:…] dans gnubg) ; 0 par défaut. */
|
||||
readonly gameIndex?: number;
|
||||
}
|
||||
|
||||
/** Un nœud SGF et les variantes qui le suivent. */
|
||||
@@ -82,13 +85,14 @@ export async function exportSgf(
|
||||
// sa longueur et le score avant la partie (W, l'ordinateur, est le
|
||||
// joueur 0 de gnubg), et les règles comme gnubg les écrit (sgf.c) :
|
||||
// Crawford, et CrawfordGame pour la partie Crawford. Le numéro de la
|
||||
// partie dans le match n'est pas gardé : 0.
|
||||
// partie dans le match : celui que donne l'appelant (exportMatchSgf),
|
||||
// 0 pour une partie exportée seule.
|
||||
const { result, match } = replay(currentLine(journal));
|
||||
const root = [
|
||||
"FF[4]GM[6]CA[UTF-8]AP[Ustagammon]",
|
||||
match === null
|
||||
? "MI[length:0][game:0][ws:0][bs:0]"
|
||||
: `MI[length:${match.length}][game:0][ws:${match.score.computer}][bs:${match.score.player}]` +
|
||||
: `MI[length:${match.length}][game:${options.gameIndex ?? 0}][ws:${match.score.computer}][bs:${match.score.player}]` +
|
||||
`RU[Crawford${match.crawford ? ":CrawfordGame" : ""}]`,
|
||||
`PW[${escapeText(options.computerName)}]PB[${escapeText(options.playerName)}]`,
|
||||
options.date === undefined ? "" : `DT[${escapeText(options.date)}]`,
|
||||
@@ -103,6 +107,24 @@ export async function exportSgf(
|
||||
return `(;${root}${sequence(tree)})\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Un match entier au format SGF de GNU Backgammon : ses parties dans
|
||||
* l'ordre, chacune son arbre (MI porte son numéro et le score avant elle),
|
||||
* à la suite dans le même fichier, comme gnubg enregistre un match (« save
|
||||
* match ») et le relit (« load match »).
|
||||
*/
|
||||
export async function exportMatchSgf(
|
||||
engine: Engine,
|
||||
journals: readonly GameJournal[],
|
||||
options: Omit<SgfOptions, "gameIndex">,
|
||||
): Promise<string> {
|
||||
const games: string[] = [];
|
||||
for (const [gameIndex, journal] of journals.entries()) {
|
||||
games.push(await exportSgf(engine, journal, { ...options, gameIndex }));
|
||||
}
|
||||
return games.join("");
|
||||
}
|
||||
|
||||
/** Écrit des nœuds : une suite tant qu'il n'y a qu'une variante, puis
|
||||
* chaque variante entre parenthèses. */
|
||||
function sequence(nodes: readonly SgfNode[]): string {
|
||||
|
||||
@@ -24,6 +24,7 @@ import type {
|
||||
Level,
|
||||
Luck,
|
||||
LuckRating,
|
||||
MatchChances,
|
||||
MatchDescription,
|
||||
MatchId,
|
||||
Move,
|
||||
@@ -167,6 +168,18 @@ export function createWasmEngine(run: RunCommand): Engine {
|
||||
};
|
||||
},
|
||||
|
||||
async matchChances(cube: EngineCube, equity: number): Promise<MatchChances> {
|
||||
if (cube.match === undefined) {
|
||||
throw new Error("pas de match : pas de chances de gagner le match");
|
||||
}
|
||||
const answer = (await run(["mwc", await matchId(cube), String(equity)])) as {
|
||||
at_score: number;
|
||||
mwc: number;
|
||||
loss: number;
|
||||
};
|
||||
return { atScore: answer.at_score, ofEquity: answer.mwc, ofLoss: answer.loss };
|
||||
},
|
||||
|
||||
async analyseMove(
|
||||
position: PositionId,
|
||||
cube: EngineCube,
|
||||
|
||||
@@ -72,6 +72,11 @@ function fakeEngine(overrides: Partial<Engine> = {}): Engine {
|
||||
crawford: score[winner] === match.length - 1,
|
||||
};
|
||||
},
|
||||
matchChances: async (_cube, equity) => ({
|
||||
atScore: 0.5,
|
||||
ofEquity: 0.5 + equity / 4,
|
||||
ofLoss: equity / 4,
|
||||
}),
|
||||
analyseMove: async () => null,
|
||||
analyseCube: async () => ({
|
||||
analysed: false,
|
||||
|
||||
@@ -15,8 +15,9 @@
|
||||
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { Game } from "../../src/domain/game/game.js";
|
||||
import { exportSgf } from "../../src/domain/game/sgf.js";
|
||||
import { Game, type NewGame } from "../../src/domain/game/game.js";
|
||||
import { firstGameOf } from "../../src/domain/game/match.js";
|
||||
import { exportMatchSgf, exportSgf } from "../../src/domain/game/sgf.js";
|
||||
import { loadNodeEngine } from "../support/node-engine.js";
|
||||
import { playMoves, playToTheEnd, seededDice, step } from "../support/play.js";
|
||||
|
||||
@@ -133,6 +134,44 @@ async function main(): Promise<void> {
|
||||
}
|
||||
game.goBackTo(original.head as string);
|
||||
}
|
||||
// Un match entier en 3 points (étape 1l), exporté d'un seul fichier :
|
||||
// chaque partie à la suite, avec son numéro et le score avant elle. La
|
||||
// première graine dont le match compte au moins trois parties.
|
||||
for (let seed = 21; ; seed++) {
|
||||
const dice = seededDice(seed);
|
||||
const played: Game[] = [];
|
||||
let next: Game | null = Game.start(engine, {
|
||||
dice,
|
||||
level: "0ply",
|
||||
match: firstGameOf(3, "exemple"),
|
||||
});
|
||||
while (next !== null) {
|
||||
await playToTheEnd(next, engine);
|
||||
played.push(next);
|
||||
const following: NewGame | null = next.nextGame;
|
||||
next = following === null ? null : Game.start(engine, { ...following, dice });
|
||||
}
|
||||
if (played.length < 3) {
|
||||
continue;
|
||||
}
|
||||
const sgf = await exportMatchSgf(
|
||||
engine,
|
||||
played.map((g) => g.journal),
|
||||
{ playerName: "Vous", computerName: "Ordinateur", date: "2026-11-12" },
|
||||
);
|
||||
const expected = {
|
||||
length: 3,
|
||||
games: played.map((g) => ({
|
||||
after: g.events.flatMap((e) => (e.type === "MovePlayed" ? [e.position] : [])),
|
||||
result: g.state.result,
|
||||
score: g.state.match?.score,
|
||||
})),
|
||||
};
|
||||
writeFileSync(join(out, `match-${seed}.sgf`), sgf);
|
||||
writeFileSync(join(out, `match-${seed}.json`), `${JSON.stringify(expected)}\n`);
|
||||
files++;
|
||||
break;
|
||||
}
|
||||
console.log(`${files} parties exportées dans ${out}`);
|
||||
}
|
||||
|
||||
|
||||
+33
-1
@@ -50,6 +50,11 @@
|
||||
* no_double ou double (joueur au trait),
|
||||
* take ou pass (son adversaire)
|
||||
* luck POSITION_ID MATCH_ID DÉS chance du jet pour le joueur au trait
|
||||
* mwc MATCH_ID [ÉQUITÉ] chances de gagner le match du joueur
|
||||
* au trait : au score, avant la
|
||||
* partie, et pour une équité
|
||||
* normalisée (0 par défaut), en
|
||||
* chances et en perte
|
||||
*
|
||||
* --ply : niveau de gnubg, de 0 (défaut) à 4 (meilleur coup comme « hint »,
|
||||
* analyses comme l'analyse de partie de gnubg).
|
||||
@@ -83,7 +88,7 @@
|
||||
|
||||
/* Liste des commandes, pour les messages d'erreur. */
|
||||
#define COMMANDS "bestmove, moves, legal, cube, eval, position, halfmoves, matchid, reference, " \
|
||||
"levels, analysemove, analysecube, luck, double, take ou aftergame"
|
||||
"levels, analysemove, analysecube, luck, double, take, aftergame ou mwc"
|
||||
|
||||
/* Coups gardés dans le classement de la commande reference (comme hint). */
|
||||
#define REFERENCE_MAX_MOVES 10
|
||||
@@ -597,6 +602,31 @@ run_after_game_command(const options *opt)
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
/* mwc : chances de gagner le match (voir engine_match_chances_of). */
|
||||
static int
|
||||
run_mwc_command(const options *opt)
|
||||
{
|
||||
engine_match_chances chances;
|
||||
engine_status status;
|
||||
float equity = 0.0f;
|
||||
char *end;
|
||||
|
||||
if (opt->arg_count != 1 && opt->arg_count != 2)
|
||||
return usage_error("arguments attendus : MATCH_ID [ÉQUITÉ]");
|
||||
if (opt->arg_count == 2) {
|
||||
equity = strtof(opt->args[1], &end);
|
||||
if (end == opt->args[1] || *end != '\0')
|
||||
return usage_error("ÉQUITÉ attend un nombre");
|
||||
}
|
||||
status = engine_match_chances_of(opt->args[0], equity, &chances);
|
||||
if (status != ENGINE_OK)
|
||||
return print_engine_error(status);
|
||||
printf("{\"match_id\": \"%s\", \"equity\": " NUMBER ", \"at_score\": " NUMBER
|
||||
", \"mwc\": " NUMBER ", \"loss\": " NUMBER "}\n", opt->args[0], equity,
|
||||
chances.at_score, chances.mwc, chances.loss);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
/*
|
||||
* reference :un niveau d'un fichier de résultat de tests/reference/, de
|
||||
* même structure que plies["<n>"] (voir tests/reference/README.md).
|
||||
@@ -886,6 +916,8 @@ main(int argc, char **argv)
|
||||
result = run_analyse_cube_command(&opt);
|
||||
else if (strcmp(opt.command, "luck") == 0)
|
||||
result = run_luck_command(&opt);
|
||||
else if (strcmp(opt.command, "mwc") == 0)
|
||||
result = run_mwc_command(&opt);
|
||||
else
|
||||
result = usage_error("commande inconnue : " COMMANDS);
|
||||
|
||||
|
||||
@@ -838,6 +838,32 @@ engine_match_after_game(const char *match_id, int winner, int points,
|
||||
return ENGINE_OK;
|
||||
}
|
||||
|
||||
/* --------------------------------------- Chances de gagner le match */
|
||||
|
||||
engine_status
|
||||
engine_match_chances_of(const char *match_id, float equity, engine_match_chances *chances)
|
||||
{
|
||||
engine_match m;
|
||||
cubeinfo cube;
|
||||
engine_status status;
|
||||
|
||||
if (engine_state != READY)
|
||||
return ENGINE_ERROR_NOT_INITIALISED;
|
||||
status = engine_decode_match(match_id, &m);
|
||||
if (status != ENGINE_OK)
|
||||
return status;
|
||||
if (m.match_length == 0
|
||||
|| SetCubeInfo(&cube, m.cube_value, m.cube_owner, m.player_on_roll, m.match_length,
|
||||
m.score, m.crawford, m.jacoby, DEFAULT_BEAVERS, VARIATION_STANDARD) != 0)
|
||||
return ENGINE_ERROR_MATCH_ID;
|
||||
chances->at_score = getMEAtScore(m.score[0], m.score[1], m.match_length, m.player_on_roll,
|
||||
m.crawford, aafMET, aafMETPostCrawford);
|
||||
chances->mwc = eq2mwc(equity, &cube);
|
||||
/* analysis.c, updateStatcontext : « eq2mwc(rSkill, &ci) - eq2mwc(0.0f, &ci) ». */
|
||||
chances->loss = eq2mwc(equity, &cube) - eq2mwc(0.0f, &cube);
|
||||
return ENGINE_OK;
|
||||
}
|
||||
|
||||
/* -------------------------------------------- Analyse d'une décision de videau */
|
||||
|
||||
/* Le plus petit de deux nombres. */
|
||||
|
||||
@@ -452,6 +452,32 @@ typedef struct {
|
||||
engine_status engine_match_after_game(const char *match_id, int winner, int points,
|
||||
engine_match_after *after);
|
||||
|
||||
/* Chances de gagner le match, d'après la table d'équité de match de gnubg
|
||||
* (Kazaross-XG2, celle de gnubg de bureau par défaut). */
|
||||
typedef struct {
|
||||
float at_score; /* chances du joueur au trait de gagner le match
|
||||
* au score du Match ID, avant la partie
|
||||
* (getMEAtScore de gnubg, matchequity.c,
|
||||
* partie Crawford et suivantes comprises) */
|
||||
float mwc; /* l'équité normalisée donnée, pour ce videau et
|
||||
* ce score, convertie en chances de gagner le
|
||||
* match du joueur au trait (eq2mwc) */
|
||||
float loss; /* la même équité vue comme une perte : eq2mwc
|
||||
* de l'équité moins eq2mwc de 0, comme le coût
|
||||
* d'une erreur dans les statistiques de match de
|
||||
* gnubg (updateStatcontext, analysis.c) */
|
||||
} engine_match_chances;
|
||||
|
||||
/*
|
||||
* Chances de gagner le match : au score du Match ID (avant la partie), et
|
||||
* pour une équité normalisée (videau, score, joueur au trait et partie
|
||||
* Crawford du Match ID ; les dés et le propriétaire du videau sont
|
||||
* ignorés). ENGINE_ERROR_MATCH_ID en partie libre (longueur 0) : il n'y a
|
||||
* pas de match.
|
||||
*/
|
||||
engine_status engine_match_chances_of(const char *match_id, float equity,
|
||||
engine_match_chances *chances);
|
||||
|
||||
/* ------------------------------------------------------------- Analyse */
|
||||
|
||||
/* Appréciation de gnubg pour une perte d'équité (0 ou négative). */
|
||||
|
||||
@@ -279,5 +279,61 @@
|
||||
"match_id": "cAkAAAAAAAAA",
|
||||
"dice": null
|
||||
}
|
||||
],
|
||||
"chances": [
|
||||
{
|
||||
"id": "chances-5-0-0",
|
||||
"description": "Match en 5 points à 0-0 : table d'avant Crawford.",
|
||||
"match_id": "MAGgAAAAAAAE",
|
||||
"equities": [-0.25, -0.03, 0.4]
|
||||
},
|
||||
{
|
||||
"id": "chances-5-0-2",
|
||||
"description": "Match en 5 points, joueur au trait mené 0-2.",
|
||||
"match_id": "MAGgAAAAEAAE",
|
||||
"equities": [-0.25, -0.03, 0.4]
|
||||
},
|
||||
{
|
||||
"id": "chances-5-2-4-cube-2",
|
||||
"description": "Match en 5 points, 2-4, videau à 2 chez l'adversaire.",
|
||||
"match_id": "EQGgACAAIAAE",
|
||||
"equities": [-0.25, -0.03, 0.4]
|
||||
},
|
||||
{
|
||||
"id": "chances-5-4-3-crawford",
|
||||
"description": "Match en 5 points, 4-3, partie Crawford.",
|
||||
"match_id": "sAGgAEAAGAAE",
|
||||
"equities": [-0.25, -0.03, 0.4]
|
||||
},
|
||||
{
|
||||
"id": "chances-5-4-3-post-crawford",
|
||||
"description": "Match en 5 points, 4-3, après la partie Crawford.",
|
||||
"match_id": "MAGgAEAAGAAE",
|
||||
"equities": [-0.25, -0.03, 0.4]
|
||||
},
|
||||
{
|
||||
"id": "chances-5-3-4-post-crawford",
|
||||
"description": "Match en 5 points, 3-4, après la partie Crawford, joueur au trait mené.",
|
||||
"match_id": "MAGgADAAIAAE",
|
||||
"equities": [-0.25, -0.03, 0.4]
|
||||
},
|
||||
{
|
||||
"id": "chances-7-1-3-cube-4",
|
||||
"description": "Match en 7 points, 1-3, videau à 4 chez le joueur au trait.",
|
||||
"match_id": "AgHgABAAGAAE",
|
||||
"equities": [-0.25, -0.03, 0.4]
|
||||
},
|
||||
{
|
||||
"id": "chances-7-other-on-roll",
|
||||
"description": "Match en 7 points, l'autre joueur au trait (Match ID de match-7-cube).",
|
||||
"match_id": "cAngAFAAGAAE",
|
||||
"equities": [-0.25, -0.03, 0.4]
|
||||
},
|
||||
{
|
||||
"id": "chances-5-post-crawford-other-on-roll",
|
||||
"description": "Match en 5 points après Crawford, l'autre joueur au trait (Match ID de match-post-crawford-cube).",
|
||||
"match_id": "cAmgAEAAEAAE",
|
||||
"equities": [-0.25, -0.03, 0.4]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"id": "chances-5-0-0",
|
||||
"description": "Match en 5 points à 0-0 : table d'avant Crawford.",
|
||||
"match_id": "MAGgAAAAAAAE",
|
||||
"equities": [
|
||||
{
|
||||
"equity": -0.25,
|
||||
"mwc": 0.48067,
|
||||
"loss": -0.019329995
|
||||
},
|
||||
{
|
||||
"equity": -0.03,
|
||||
"mwc": 0.4976804,
|
||||
"loss": -0.0023196042
|
||||
},
|
||||
{
|
||||
"equity": 0.4,
|
||||
"mwc": 0.530928,
|
||||
"loss": 0.030928016
|
||||
}
|
||||
],
|
||||
"type": "chance",
|
||||
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
|
||||
"met": "Kazaross-XG2",
|
||||
"at_score": 0.5
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"id": "chances-5-0-2",
|
||||
"description": "Match en 5 points, joueur au trait mené 0-2.",
|
||||
"match_id": "MAGgAAAAEAAE",
|
||||
"equities": [
|
||||
{
|
||||
"equity": -0.25,
|
||||
"mwc": 0.32094374,
|
||||
"loss": -0.021511257
|
||||
},
|
||||
{
|
||||
"equity": -0.03,
|
||||
"mwc": 0.33987364,
|
||||
"loss": -0.002581358
|
||||
},
|
||||
{
|
||||
"equity": 0.4,
|
||||
"mwc": 0.376873,
|
||||
"loss": 0.034417987
|
||||
}
|
||||
],
|
||||
"type": "chance",
|
||||
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
|
||||
"met": "Kazaross-XG2",
|
||||
"at_score": 0.35205
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"id": "chances-5-2-4-cube-2",
|
||||
"description": "Match en 5 points, 2-4, videau à 2 chez l'adversaire.",
|
||||
"match_id": "EQGgACAAIAAE",
|
||||
"equities": [
|
||||
{
|
||||
"equity": -0.25,
|
||||
"mwc": 0.1875,
|
||||
"loss": -0.0625
|
||||
},
|
||||
{
|
||||
"equity": -0.03,
|
||||
"mwc": 0.2425,
|
||||
"loss": -0.007499993
|
||||
},
|
||||
{
|
||||
"equity": 0.4,
|
||||
"mwc": 0.35,
|
||||
"loss": 0.099999994
|
||||
}
|
||||
],
|
||||
"type": "chance",
|
||||
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
|
||||
"met": "Kazaross-XG2",
|
||||
"at_score": 0.32264
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"id": "chances-5-3-4-post-crawford",
|
||||
"description": "Match en 5 points, 3-4, après la partie Crawford, joueur au trait mené.",
|
||||
"match_id": "MAGgADAAIAAE",
|
||||
"equities": [
|
||||
{
|
||||
"equity": -0.25,
|
||||
"mwc": 0.1875,
|
||||
"loss": -0.0625
|
||||
},
|
||||
{
|
||||
"equity": -0.03,
|
||||
"mwc": 0.2425,
|
||||
"loss": -0.007499993
|
||||
},
|
||||
{
|
||||
"equity": 0.4,
|
||||
"mwc": 0.35,
|
||||
"loss": 0.099999994
|
||||
}
|
||||
],
|
||||
"type": "chance",
|
||||
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
|
||||
"met": "Kazaross-XG2",
|
||||
"at_score": 0.48803
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"id": "chances-5-4-3-crawford",
|
||||
"description": "Match en 5 points, 4-3, partie Crawford.",
|
||||
"match_id": "sAGgAEAAGAAE",
|
||||
"equities": [
|
||||
{
|
||||
"equity": -0.25,
|
||||
"mwc": 0.6875,
|
||||
"loss": -0.0625
|
||||
},
|
||||
{
|
||||
"equity": -0.03,
|
||||
"mwc": 0.7425,
|
||||
"loss": -0.007499993
|
||||
},
|
||||
{
|
||||
"equity": 0.4,
|
||||
"mwc": 0.85,
|
||||
"loss": 0.100000024
|
||||
}
|
||||
],
|
||||
"type": "chance",
|
||||
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
|
||||
"met": "Kazaross-XG2",
|
||||
"at_score": 0.67736
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"id": "chances-5-4-3-post-crawford",
|
||||
"description": "Match en 5 points, 4-3, après la partie Crawford.",
|
||||
"match_id": "MAGgAEAAGAAE",
|
||||
"equities": [
|
||||
{
|
||||
"equity": -0.25,
|
||||
"mwc": 0.6875,
|
||||
"loss": -0.0625
|
||||
},
|
||||
{
|
||||
"equity": -0.03,
|
||||
"mwc": 0.7425,
|
||||
"loss": -0.007499993
|
||||
},
|
||||
{
|
||||
"equity": 0.4,
|
||||
"mwc": 0.85,
|
||||
"loss": 0.100000024
|
||||
}
|
||||
],
|
||||
"type": "chance",
|
||||
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
|
||||
"met": "Kazaross-XG2",
|
||||
"at_score": 0.51197004
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"id": "chances-5-post-crawford-other-on-roll",
|
||||
"description": "Match en 5 points après Crawford, l'autre joueur au trait (Match ID de match-post-crawford-cube).",
|
||||
"match_id": "cAmgAEAAEAAE",
|
||||
"equities": [
|
||||
{
|
||||
"equity": -0.25,
|
||||
"mwc": 0.18301125,
|
||||
"loss": -0.061003745
|
||||
},
|
||||
{
|
||||
"equity": -0.03,
|
||||
"mwc": 0.23669454,
|
||||
"loss": -0.0073204488
|
||||
},
|
||||
{
|
||||
"equity": 0.4,
|
||||
"mwc": 0.34162098,
|
||||
"loss": 0.09760599
|
||||
}
|
||||
],
|
||||
"type": "chance",
|
||||
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
|
||||
"met": "Kazaross-XG2",
|
||||
"at_score": 0.32264
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"id": "chances-7-1-3-cube-4",
|
||||
"description": "Match en 7 points, 1-3, videau à 4 chez le joueur au trait.",
|
||||
"match_id": "AgHgABAAGAAE",
|
||||
"equities": [
|
||||
{
|
||||
"equity": -0.25,
|
||||
"mwc": 0.2507625,
|
||||
"loss": -0.0835875
|
||||
},
|
||||
{
|
||||
"equity": -0.03,
|
||||
"mwc": 0.32431948,
|
||||
"loss": -0.010030508
|
||||
},
|
||||
{
|
||||
"equity": 0.4,
|
||||
"mwc": 0.46809,
|
||||
"loss": 0.13374001
|
||||
}
|
||||
],
|
||||
"type": "chance",
|
||||
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
|
||||
"met": "Kazaross-XG2",
|
||||
"at_score": 0.35715
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"id": "chances-7-other-on-roll",
|
||||
"description": "Match en 7 points, l'autre joueur au trait (Match ID de match-7-cube).",
|
||||
"match_id": "cAngAFAAGAAE",
|
||||
"equities": [
|
||||
{
|
||||
"equity": -0.25,
|
||||
"mwc": 0.26622373,
|
||||
"loss": -0.02686125
|
||||
},
|
||||
{
|
||||
"equity": -0.03,
|
||||
"mwc": 0.28986162,
|
||||
"loss": -0.0032233596
|
||||
},
|
||||
{
|
||||
"equity": 0.4,
|
||||
"mwc": 0.33606297,
|
||||
"loss": 0.04297799
|
||||
}
|
||||
],
|
||||
"type": "chance",
|
||||
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
|
||||
"met": "Kazaross-XG2",
|
||||
"at_score": 0.33130002
|
||||
}
|
||||
@@ -255,6 +255,16 @@ def compare_cube_analysis(report, cli, case):
|
||||
expected["equity_loss"], SKILL_THRESHOLDS)
|
||||
|
||||
|
||||
def compare_chances(report, cli, case):
|
||||
"""Chances de gagner le match : table au score, conversion d'équités."""
|
||||
for item in case["equities"]:
|
||||
actual = run_cli(cli, ["mwc", case["match_id"], repr(item["equity"])])
|
||||
where = "%s, équité %s" % (case["id"], item["equity"])
|
||||
report.number(where, "at_score", case["at_score"], actual["at_score"])
|
||||
report.number(where, "mwc", item["mwc"], actual["mwc"])
|
||||
report.number(where, "loss", item["loss"], actual["loss"])
|
||||
|
||||
|
||||
def compare_levels(report, cli, case, settings):
|
||||
for name, expected in sorted(case["levels"].items()):
|
||||
where = "%s niveau %s" % (case["id"], name)
|
||||
@@ -280,6 +290,8 @@ def compare_analyses(report, cli, folder):
|
||||
compare_move_analysis(report, cli, case)
|
||||
elif case["type"] == "cube":
|
||||
compare_cube_analysis(report, cli, case)
|
||||
elif case["type"] == "chance":
|
||||
compare_chances(report, cli, case)
|
||||
else:
|
||||
compare_levels(report, cli, case, settings)
|
||||
return len(paths)
|
||||
|
||||
@@ -391,6 +391,53 @@ def level_cube(case, name):
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Chances de gagner le match (analyses.json, « chances ») : la table d'équité
|
||||
# de match de gnubg au score du Match ID, et la conversion d'une équité
|
||||
# normalisée en chances de gagner le match (eq2mwc), avec le coût d'une
|
||||
# erreur des statistiques de match (updateStatcontext, analysis.c :
|
||||
# « eq2mwc(rSkill, &ci) - eq2mwc(0.0f, &ci) »).
|
||||
|
||||
START_POSITION = "4HPwATDgc/ABMA"
|
||||
|
||||
|
||||
def single(x):
|
||||
"""x arrondi en simple précision, comme le calcul de gnubg en float."""
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def met_at_score(ci):
|
||||
"""getMEAtScore de gnubg (matchequity.c) pour le joueur au trait : une
|
||||
lecture de la table que gnubg donne (gnubg.met), sans autre calcul.
|
||||
Avant ou pendant la partie Crawford, la table d'avant Crawford ; après,
|
||||
la table d'après Crawford du joueur qui mène."""
|
||||
length = ci["matchto"]
|
||||
table = gnubg.met(length)
|
||||
away0 = length - ci["score"][0] - 1
|
||||
away1 = length - ci["score"][1] - 1
|
||||
if not ci["crawford"] and (away0 == 0 or away1 == 0):
|
||||
me0 = single(1.0 - table[2][away1]) if away0 == 0 else table[1][away0]
|
||||
else:
|
||||
me0 = table[0][away0][away1]
|
||||
return me0 if ci["move"] == 0 else single(1.0 - me0)
|
||||
|
||||
|
||||
def match_chances(case):
|
||||
gnubg.command("set gnubgid %s:%s" % (START_POSITION, case["match_id"]))
|
||||
if gnubg.matchid() != case["match_id"]:
|
||||
raise SystemExit("%s : gnubg relit %s" % (case["id"], gnubg.matchid()))
|
||||
ci = cube_info()
|
||||
zero = gnubg.eq2mwc(0.0, ci)
|
||||
return {
|
||||
"at_score": f32(met_at_score(ci)),
|
||||
"equities": [
|
||||
{"equity": equity, "mwc": f32(gnubg.eq2mwc(equity, ci)),
|
||||
"loss": f32(single(gnubg.eq2mwc(equity, ci) - zero))}
|
||||
for equity in case["equities"]
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def write_analysis(out_dir, result):
|
||||
with open(os.path.join(out_dir, result["id"] + ".json"), "w", encoding="utf-8") as f:
|
||||
json.dump(result, f, ensure_ascii=False, indent=2)
|
||||
@@ -408,10 +455,12 @@ def generate_analyses(commit):
|
||||
gnubg.command("set display off")
|
||||
gnubg.command("set automatic game off")
|
||||
gnubg.command("set automatic roll off")
|
||||
for kind in ("moves", "cubes", "levels"):
|
||||
for kind in ("moves", "cubes", "levels", "chances"):
|
||||
for case in cases[kind]:
|
||||
result = dict(case, type=kind[:-1], gnubg_commit=commit, met=MET)
|
||||
if kind == "moves":
|
||||
if kind == "chances":
|
||||
result.update(match_chances(case))
|
||||
elif kind == "moves":
|
||||
result["plies"] = {}
|
||||
for ply in PLIES:
|
||||
result["plies"][str(ply)], result["luck"] = analyse_move(case, ply)
|
||||
|
||||
+52
-1
@@ -67,10 +67,61 @@ def check(path):
|
||||
return errors
|
||||
|
||||
|
||||
def check_game_records(records, expected, where):
|
||||
"""Avance dans la partie courante de gnubg enregistrement par
|
||||
enregistrement : après chaque coup, sa position doit être celle du
|
||||
journal."""
|
||||
gnubg.command("first move")
|
||||
after = []
|
||||
for record in records:
|
||||
gnubg.command("next")
|
||||
if record["action"] == "move":
|
||||
after.append(gnubg.positionid())
|
||||
errors = []
|
||||
if len(after) != len(expected["after"]):
|
||||
errors.append("%s%d coups lus, %d attendus" % (where, len(after), len(expected["after"])))
|
||||
for i, (got, want) in enumerate(zip(after, expected["after"])):
|
||||
if got != want:
|
||||
errors.append("%saprès le coup %d : gnubg %s, journal %s" % (where, i + 1, got, want))
|
||||
break
|
||||
return errors
|
||||
|
||||
|
||||
def check_match(path):
|
||||
"""Un match entier (étape 1l) : gnubg charge le fichier (load match),
|
||||
y trouve la longueur du match, et pour chaque partie, dans l'ordre, le
|
||||
score avant elle, les positions après chaque coup et le résultat."""
|
||||
with open(path[:-4] + ".json") as f:
|
||||
expected = json.load(f)
|
||||
gnubg.command("load match " + path)
|
||||
match = gnubg.match(analysis=0, boards=0, statistics=0, verbose=0)
|
||||
games = match["games"]
|
||||
errors = []
|
||||
if match["match-info"].get("match-length") != expected["length"]:
|
||||
errors.append("longueur : gnubg %s" % match["match-info"])
|
||||
if len(games) != len(expected["games"]):
|
||||
return errors + ["%d parties lues, %d attendues" % (len(games), len(expected["games"]))]
|
||||
gnubg.command("first game")
|
||||
for index, (game, want) in enumerate(zip(games, expected["games"])):
|
||||
where = "partie %d : " % (index + 1)
|
||||
if index > 0:
|
||||
gnubg.command("next game")
|
||||
info = game["info"]
|
||||
score = (info.get("score-X"), info.get("score-O"))
|
||||
if score != (want["score"]["computer"], want["score"]["player"]):
|
||||
errors.append("%sscore avant la partie : gnubg %s, journal %s" % (where, score, want["score"]))
|
||||
errors += check_game_records(list(game["game"]), want, where)
|
||||
result = want["result"]
|
||||
winner = "O" if result["winner"] == "player" else "X"
|
||||
if (info.get("winner"), info.get("points-won")) != (winner, result["points"]):
|
||||
errors.append("%srésultat : gnubg %s, journal %s" % (where, info, result))
|
||||
return errors
|
||||
|
||||
|
||||
failures = 0
|
||||
paths = sorted(glob.glob(os.path.join(FOLDER, "*.sgf")))
|
||||
for path in paths:
|
||||
errors = check(path)
|
||||
errors = check_match(path) if os.path.basename(path).startswith("match-") else check(path)
|
||||
name = os.path.basename(path)
|
||||
if errors:
|
||||
failures += 1
|
||||
|
||||
Reference in New Issue
Block a user