hexbandit 1.0.1__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hexbandit/__init__.py +12 -0
- hexbandit/__main__.py +24 -0
- hexbandit/_environment.py +55 -0
- hexbandit/_lib/hexbandit_native.dll +0 -0
- hexbandit/_native.py +163 -0
- hexbandit/cli/__init__.py +7 -0
- hexbandit/cli/main.py +872 -0
- hexbandit/domain/__init__.py +51 -0
- hexbandit/domain/errors.py +53 -0
- hexbandit/domain/hexboard.py +172 -0
- hexbandit/domain/ports.py +75 -0
- hexbandit/domain/types.py +424 -0
- hexbandit/engine/__init__.py +8 -0
- hexbandit/engine/fake.py +146 -0
- hexbandit/engine/native.py +51 -0
- hexbandit/experiments/__init__.py +24 -0
- hexbandit/experiments/adaptive.py +380 -0
- hexbandit/experiments/analysis.py +505 -0
- hexbandit/experiments/campaign.py +521 -0
- hexbandit/experiments/elo.py +265 -0
- hexbandit/experiments/extended.py +222 -0
- hexbandit/experiments/models.py +421 -0
- hexbandit/experiments/plots.py +578 -0
- hexbandit/experiments/report.py +289 -0
- hexbandit/experiments/repository.py +184 -0
- hexbandit/experiments/stats.py +210 -0
- hexbandit/experiments/tournament.py +184 -0
- hexbandit/py.typed +0 -0
- hexbandit/viz/__init__.py +15 -0
- hexbandit/viz/board.py +233 -0
- hexbandit/viz/replay.py +177 -0
- hexbandit/viz/web/__init__.py +35 -0
- hexbandit/viz/web/viewer.html +425 -0
- hexbandit-1.0.1.dist-info/METADATA +35 -0
- hexbandit-1.0.1.dist-info/RECORD +38 -0
- hexbandit-1.0.1.dist-info/WHEEL +5 -0
- hexbandit-1.0.1.dist-info/entry_points.txt +2 -0
- hexbandit-1.0.1.dist-info/top_level.txt +1 -0
hexbandit/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""hexbandit : pilotage, analyse et visualisation du moteur Hex / MCTS / MC-RAVE.
|
|
2
|
+
|
|
3
|
+
Le calcul (règles, recherche, parties) est fait par la bibliothèque native
|
|
4
|
+
Rust ; Python orchestre les campagnes, analyse les résultats et les affiche.
|
|
5
|
+
Toute dépendance au moteur passe par le port :class:`hexbandit.domain.ports.EnginePort`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
__version__ = "0.2.0"
|
|
11
|
+
|
|
12
|
+
__all__ = ["__version__"]
|
hexbandit/__main__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Point d'entrée : ``python -m hexbandit``.
|
|
2
|
+
|
|
3
|
+
L'environnement est vérifié avant d'importer la ligne de commande, pour
|
|
4
|
+
afficher un message clair plutôt qu'une trace ``ModuleNotFoundError``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from hexbandit._environment import environment_problems, explain
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _run() -> int:
|
|
15
|
+
problems = environment_problems()
|
|
16
|
+
if problems:
|
|
17
|
+
print(explain(problems), file=sys.stderr)
|
|
18
|
+
return 3
|
|
19
|
+
from hexbandit.cli.main import main
|
|
20
|
+
|
|
21
|
+
return main()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
sys.exit(_run())
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Vérification de l'environnement Python avant d'importer le reste du paquet.
|
|
2
|
+
|
|
3
|
+
Ce module n'importe que la bibliothèque standard : il doit pouvoir expliquer
|
|
4
|
+
ce qui manque même quand numpy, pandas ou pydantic sont absents.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import importlib.util
|
|
10
|
+
import sys
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
|
|
13
|
+
MIN_PYTHON = (3, 11)
|
|
14
|
+
"""Plus ancienne version de Python prise en charge (``tomllib``, ``datetime.UTC``)."""
|
|
15
|
+
|
|
16
|
+
REQUIRED_MODULES = ("numpy", "pandas", "scipy", "matplotlib", "pydantic")
|
|
17
|
+
"""Modules importés par la ligne de commande et les campagnes."""
|
|
18
|
+
|
|
19
|
+
SETUP_HINT = (
|
|
20
|
+
"Créez l'environnement virtuel du projet, depuis la racine du dépôt :\n"
|
|
21
|
+
" bash scripts/hexlXtc03.sh\n"
|
|
22
|
+
" source .venv/bin/activate\n"
|
|
23
|
+
"puis relancez la commande (python désigne alors l'interpréteur de .venv)."
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def python_label() -> str:
|
|
28
|
+
"""Version et chemin de l'interpréteur courant."""
|
|
29
|
+
version = ".".join(str(part) for part in sys.version_info[:3])
|
|
30
|
+
return f"Python {version} ({sys.executable})"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def missing_modules(modules: Sequence[str] = REQUIRED_MODULES) -> list[str]:
|
|
34
|
+
"""Modules introuvables par l'interpréteur courant, sans les importer."""
|
|
35
|
+
return [name for name in modules if importlib.util.find_spec(name) is None]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def environment_problems() -> list[str]:
|
|
39
|
+
"""Liste des problèmes bloquants (vide si l'environnement convient)."""
|
|
40
|
+
problems: list[str] = []
|
|
41
|
+
if sys.version_info < MIN_PYTHON:
|
|
42
|
+
wanted = ".".join(str(part) for part in MIN_PYTHON)
|
|
43
|
+
problems.append(f"{python_label()} est trop ancien : Python >= {wanted} requis.")
|
|
44
|
+
missing = missing_modules()
|
|
45
|
+
if missing:
|
|
46
|
+
problems.append(f"modules absents pour {python_label()} : {', '.join(missing)}.")
|
|
47
|
+
return problems
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def explain(problems: Sequence[str]) -> str:
|
|
51
|
+
"""Message d'erreur destiné à l'utilisateur."""
|
|
52
|
+
lines = ["hexbandit : environnement Python incomplet."]
|
|
53
|
+
lines.extend(f" - {problem}" for problem in problems)
|
|
54
|
+
lines.append(SETUP_HINT)
|
|
55
|
+
return "\n".join(lines)
|
|
Binary file
|
hexbandit/_native.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Module natif ``hexbandit._native`` : accès bas niveau à la façade Rust.
|
|
2
|
+
|
|
3
|
+
La bibliothèque partagée (crate ``bindings``) expose une ABI C ; elle est
|
|
4
|
+
chargée par :mod:`ctypes`, qui libère le GIL pendant les appels.
|
|
5
|
+
Chaque appel est exécuté dans un thread auxiliaire : le thread principal
|
|
6
|
+
reste interruptible et transforme Ctrl-C en annulation propre du calcul.
|
|
7
|
+
|
|
8
|
+
Seul l'adaptateur :mod:`hexbandit.engine.native` utilise ce module ; le reste du
|
|
9
|
+
paquet dépend du port :class:`hexbandit.domain.ports.EnginePort`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import ctypes
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import sys
|
|
18
|
+
import threading
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from hexbandit.domain.errors import Cancelled, NativeLibraryNotFound, error_from_kind
|
|
24
|
+
|
|
25
|
+
_LIB_NAMES = {
|
|
26
|
+
"linux": "libhexbandit_native.so",
|
|
27
|
+
"darwin": "libhexbandit_native.dylib",
|
|
28
|
+
"win32": "hexbandit_native.dll",
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
_lock = threading.Lock()
|
|
32
|
+
_library: ctypes.CDLL | None = None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def library_path() -> Path:
|
|
36
|
+
"""Chemin de la bibliothèque : ``HEXBANDIT_NATIVE_LIB`` ou ``hexbandit/_lib``."""
|
|
37
|
+
override = os.environ.get("HEXBANDIT_NATIVE_LIB")
|
|
38
|
+
if override:
|
|
39
|
+
return Path(override)
|
|
40
|
+
name = _LIB_NAMES.get(sys.platform, _LIB_NAMES["linux"])
|
|
41
|
+
return Path(__file__).resolve().parent / "_lib" / name
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _load() -> ctypes.CDLL:
|
|
45
|
+
global _library
|
|
46
|
+
with _lock:
|
|
47
|
+
if _library is None:
|
|
48
|
+
path = library_path()
|
|
49
|
+
if not path.exists():
|
|
50
|
+
raise NativeLibraryNotFound(
|
|
51
|
+
f"bibliothèque native absente ({path}) : lancer scripts/hexlXtc01.sh"
|
|
52
|
+
)
|
|
53
|
+
lib = ctypes.CDLL(str(path))
|
|
54
|
+
for name in ("hexbandit_play_game", "hexbandit_search"):
|
|
55
|
+
fn = getattr(lib, name)
|
|
56
|
+
fn.argtypes = [ctypes.c_char_p]
|
|
57
|
+
fn.restype = ctypes.c_void_p
|
|
58
|
+
lib.hexbandit_play_batch.argtypes = [ctypes.c_char_p, ctypes.c_uint32]
|
|
59
|
+
lib.hexbandit_play_batch.restype = ctypes.c_void_p
|
|
60
|
+
lib.hexbandit_version.argtypes = []
|
|
61
|
+
lib.hexbandit_version.restype = ctypes.c_void_p
|
|
62
|
+
lib.hexbandit_cancel.argtypes = []
|
|
63
|
+
lib.hexbandit_cancel.restype = None
|
|
64
|
+
lib.hexbandit_free_string.argtypes = [ctypes.c_void_p]
|
|
65
|
+
lib.hexbandit_free_string.restype = None
|
|
66
|
+
_library = lib
|
|
67
|
+
return _library
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def is_available() -> bool:
|
|
71
|
+
"""Vrai si la bibliothèque native peut être chargée."""
|
|
72
|
+
try:
|
|
73
|
+
_load()
|
|
74
|
+
except (NativeLibraryNotFound, OSError):
|
|
75
|
+
return False
|
|
76
|
+
return True
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _decode(lib: ctypes.CDLL, pointer: int | None) -> Any:
|
|
80
|
+
if not pointer:
|
|
81
|
+
raise error_from_kind("internal", "réponse nulle de la bibliothèque native")
|
|
82
|
+
try:
|
|
83
|
+
text = ctypes.string_at(pointer).decode("utf-8")
|
|
84
|
+
finally:
|
|
85
|
+
lib.hexbandit_free_string(pointer)
|
|
86
|
+
envelope = json.loads(text)
|
|
87
|
+
if envelope.get("ok"):
|
|
88
|
+
return envelope["result"]
|
|
89
|
+
error = envelope.get("error", {})
|
|
90
|
+
raise error_from_kind(str(error.get("kind", "internal")), str(error.get("message", "")))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _run_interruptible(lib: ctypes.CDLL, call: Callable[[], int | None]) -> Any:
|
|
94
|
+
"""Exécute ``call`` dans un thread ; Ctrl-C demande l'annulation au moteur."""
|
|
95
|
+
if threading.current_thread() is not threading.main_thread():
|
|
96
|
+
return _decode(lib, call())
|
|
97
|
+
box: dict[str, Any] = {}
|
|
98
|
+
|
|
99
|
+
def worker() -> None:
|
|
100
|
+
try:
|
|
101
|
+
box["pointer"] = call()
|
|
102
|
+
except BaseException as exc: # pragma: no cover - remontée telle quelle
|
|
103
|
+
box["error"] = exc
|
|
104
|
+
|
|
105
|
+
thread = threading.Thread(target=worker, name="hexbandit-native", daemon=True)
|
|
106
|
+
thread.start()
|
|
107
|
+
interrupted = False
|
|
108
|
+
while thread.is_alive():
|
|
109
|
+
try:
|
|
110
|
+
thread.join(0.1)
|
|
111
|
+
except KeyboardInterrupt:
|
|
112
|
+
interrupted = True
|
|
113
|
+
lib.hexbandit_cancel()
|
|
114
|
+
if "error" in box:
|
|
115
|
+
raise box["error"]
|
|
116
|
+
try:
|
|
117
|
+
return _decode(lib, box.get("pointer"))
|
|
118
|
+
except Cancelled:
|
|
119
|
+
if interrupted:
|
|
120
|
+
raise KeyboardInterrupt from None
|
|
121
|
+
raise
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _encode(payload: dict[str, Any]) -> bytes:
|
|
125
|
+
return json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def version() -> dict[str, Any]:
|
|
129
|
+
"""Versions du moteur et des formats."""
|
|
130
|
+
lib = _load()
|
|
131
|
+
result: dict[str, Any] = _decode(lib, lib.hexbandit_version())
|
|
132
|
+
return result
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def play_game(config: dict[str, Any]) -> dict[str, Any]:
|
|
136
|
+
"""Joue une partie ; renvoie l'enregistrement JSON (dict)."""
|
|
137
|
+
lib = _load()
|
|
138
|
+
data = _encode(config)
|
|
139
|
+
result: dict[str, Any] = _run_interruptible(lib, lambda: lib.hexbandit_play_game(data))
|
|
140
|
+
return result
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def play_batch(request: dict[str, Any], threads: int) -> dict[str, Any]:
|
|
144
|
+
"""Joue un lot (``games`` ou ``match``) sur ``threads`` threads."""
|
|
145
|
+
lib = _load()
|
|
146
|
+
data = _encode(request)
|
|
147
|
+
result: dict[str, Any] = _run_interruptible(
|
|
148
|
+
lib, lambda: lib.hexbandit_play_batch(data, max(1, int(threads)))
|
|
149
|
+
)
|
|
150
|
+
return result
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def search(request: dict[str, Any]) -> dict[str, Any]:
|
|
154
|
+
"""Recherche sur une position ; renvoie le rapport complet."""
|
|
155
|
+
lib = _load()
|
|
156
|
+
data = _encode(request)
|
|
157
|
+
result: dict[str, Any] = _run_interruptible(lib, lambda: lib.hexbandit_search(data))
|
|
158
|
+
return result
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def cancel() -> None:
|
|
162
|
+
"""Demande l'interruption du calcul natif en cours."""
|
|
163
|
+
_load().hexbandit_cancel()
|