-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsortbymates.py
More file actions
56 lines (48 loc) · 2 KB
/
Copy pathsortbymates.py
File metadata and controls
56 lines (48 loc) · 2 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
import argparse, re
def sort_key(t, stable, multiPV):
_, bm, _ = t
if multiPV:
key = (1, 0) if bm is None else (2, -bm) if bm > 0 else (0, -bm)
return key if stable else (*key, t[0] or "")
key = float("inf") if bm is None else abs(bm) + (0.5 if bm < 0 else 0)
return key if stable else (key, t[0] or "")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Sort the mate puzzles in ascending order, preserving comment boundaries. Output is to stdout.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("source", help="The .epd file to be sorted.")
parser.add_argument(
"--stable",
action="store_true",
help="Use stable sort; default sorts same-mate entries by FEN.",
)
parser.add_argument(
"--multiPV",
action="store_true",
help="Sort by quality of move leading to FEN: losing mates (shortest first), unknown, winning mates (longest first).",
)
args = parser.parse_args()
p = re.compile(r"^([1-8a-zA-Z/]+ [wb] [a-zA-Z\-]+ [a-h1-8\-]+)( bm #(-?\d+);)?")
segments = [] # list of (comment_or_None, [fens_upto_comment])
current_fens = []
with open(args.source) as f:
for line in f:
if line.startswith("#"):
segments.append((None, current_fens))
current_fens = []
segments.append((line, []))
else:
m = p.match(line)
assert m, f"error for line '{line}' in file {args.source}"
fen = m.group(1)
bm = int(m.group(3)) if m.group(2) is not None else None
current_fens.append((fen, bm, line))
segments.append((None, current_fens))
for header, fens in segments:
if header is not None:
print(header, end="")
if fens:
fens.sort(key=lambda t: sort_key(t, args.stable, args.multiPV))
for _, _, line in fens:
print(line, end="")