-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathchess_artist.py
2769 lines (2385 loc) · 123 KB
/
chess_artist.py
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Chess Artist
A python script and exe file that can analyze games in the pgn file,
annotate epd file, test engine on chess puzzles or problems and can
generate puzzles.
"""
__author__ = 'fsmosca'
__script_name__ = 'Chess Artist'
__version__ = 'v3.2.0'
__credits__ = ['aochoam', 'al75an', 'alxlk', 'ddugovic', 'drai8192', 'huytd', 'kennyfrc',
'PixelAim', 'python-chess']
import os
import subprocess
import argparse
import random
import logging
import time
from pathlib import Path # python 3.4 or later
import chess.pgn
import chess.polyglot
import chess.variant
# Constants
sr = random.SystemRandom()
BOOK_MOVE_LIMIT = 30
BOOK_SEARCH_TIME = 200
MAX_SCORE = 32000
TEST_SEARCH_SCORE = 100000
TEST_SEARCH_DEPTH = 1000
EPD_FILE = 1
PGN_FILE = 2
DRAW_SCORE = +0.15
SLIGHT_SCORE = +0.75
MODERATE_SCORE = +1.50
DECISIVE_SCORE = +3.0
COMPLEXITY_MINIMUM_TIME = 1000
DEFAULT_HASH = 32
DEFAULT_THREADS = 1
BEST = ['Excellent', 'Outstanding', 'Exceptional', 'Striking', 'Priceless',
'Marvellous', 'Terrific', 'Splendid', 'Magnificient', 'Admirable',
'Brilliant', 'Cool']
BETTER = ['Better', 'Preferable', 'More useful', 'Worthier', 'Superior',
'More valuable']
BOOK_COMMENT = 'Polyglot book'
PLAN_COMMENT = ['with the idea of', 'planning', 'followed by', 'threatening',
'intending to play', 'with a bad intent to play']
def DeleteFile(fn):
""" Delete fn file """
if os.path.isfile(fn):
os.remove(fn)
class Analyze():
""" An object that will read and annotate games in a pgn file """
def __init__(self, infn, outfn, eng, **opt):
""" Initialize """
self.infn = infn
self.outfn = outfn
self.eng = eng
self.evalType = opt['-eval']
self.moveTime = opt['-movetime']
self.analysisMoveStart = opt['-movestart']
self.analysisMoveEnd = opt['-moveend']
self.jobType = opt['-job']
self.engineOptions = opt['-engineoptions']
self.bookFile = opt['-bookfile']
self.depth = opt['-depth']
self.puzzlefn = opt['-puzzle']
self.wordyComment = opt['-wordy']
self.player = opt['-player']
self.playerAndOpp = opt['-player-and-opp']
self.color = opt['-color']
self.loss = opt['-loss']
self.draw = opt['-draw']
self.minScoreStopAnalysis = opt['-min-score-stop-analysis']
self.maxScoreStopAnalysis = opt['-max-score-stop-analysis']
self.engineName = opt['-enginename']
self.bookMove = None
self.passedPawnIsGood = False
self.whitePassedPawnCommentCnt = 0
self.blackPassedPawnCommentCnt = 0
self.kingSafetyIsGood = False
self.whiteKingSafetyCommentCnt = 0
self.blackKingSafetyCommentCnt = 0
self.mobilityIsGood = False
self.whiteMobilityCommentCnt = 0
self.blackMobilityCommentCnt = 0
self.writeCnt = 0
self.engIdName = self.GetEngineIdName()
self.matBal = []
self.matIsSacrificed = False
self.blunderCnt = {'w': 0, 'b': 0}
self.badCnt = {'w': 0, 'b': 0}
self.variantTag = None
self.game960 = opt['-game960']
self.puzzleScoreMargin = opt['-puzzle-score-margin']
def Send(self, p, msg):
""" Send msg to engine """
p.stdin.write('%s\n' % msg)
logging.debug('>> %s' % msg)
def ReadEngineReply(self, p, command):
""" Read reply from engine """
for eline in iter(p.stdout.readline, ''):
line = eline.strip()
logging.debug('<< %s' % line)
if command == 'uci' and 'uciok' in line:
break
if command == 'isready' and 'readyok' in line:
break
def GameOver(self, board):
"""
Todo: Study game ends of every variant. Check is_variant_end().
"""
if self.variantTag is None or self.variantTag.lower() == 'standard' or self.variantTag == 'chess960':
return board.is_checkmate() or board.is_stalemate()
else:
if self.variantTag == 'Atomic':
return board.is_variant_end()
return False
def Getboard(self, fen):
if self.variantTag is None or self.variantTag.lower() == 'standard' or self.variantTag == 'chess960':
return chess.Board(fen, chess960=True if self.variantTag == 'chess960' else False)
else:
if self.variantTag.lower() == 'atomic':
return chess.variant.AtomicBoard(fen, chess960=self.game960)
else:
raise Exception(f'Variant {self.variantTag} is not supported.')
def UciToSanMove(self, fen, uciMove):
""" Returns san move given fen and uci move """
board = self.Getboard(fen)
return board.san(chess.Move.from_uci(uciMove))
def PrintEngineIdName(self):
""" Prints engine id name """
print('Analyzing engine: %s' %(self.engIdName))
def GetGoodNag(self, side, posScore, engScore,
complexityNumber, moveChanges):
""" Returns !!, !, !? depending on the player score, analyzing
engine score, complexity number and pv move changes.
"""
# Convert the posScore and engScore to side POV
# to easier calculate the move NAG = Numeric Annotation Glyphs.
if not side:
posScore = -1 * posScore
engScore = -1 * engScore
# Set default NAG, GUI will not display this.
moveNag = '$0'
# Adjust !! move changes threshold
veryGoodMoveChangesThreshold = 4
if self.moveTime >= 180000:
veryGoodMoveChangesThreshold += 2
elif self.moveTime >= 60000:
veryGoodMoveChangesThreshold += 1
# (0) Position score after a move should not be winning
if posScore >= DECISIVE_SCORE:
return moveNag
# (0.1) Position score after a move should also not be inferior
if posScore < -SLIGHT_SCORE:
return moveNag
# (1) Very good !!
if (moveChanges >= veryGoodMoveChangesThreshold and
complexityNumber >= 15 * veryGoodMoveChangesThreshold):
moveNag = '$3'
# (1.1) Very good !!, also for very high move changes
elif moveChanges >= veryGoodMoveChangesThreshold + 2:
moveNag = '$3'
# (2) Good !
elif moveChanges >= 3 and complexityNumber >= 35:
moveNag = '$1'
# (3) Interesting !?
elif moveChanges >= 2:
moveNag = '$5'
# (3.1) Interesting !?, low pv move changes but has high
# complexity number, meaning the engine changes its best move once
# but at higher depths. The value 18 is applied with
# stockfish engine in mind.
elif moveChanges >= 1 and complexityNumber >= 18:
moveNag = '$5'
return moveNag
def GetBadNag(self, side, posScore, engScore):
""" Returns ??, ?, ?! depending on the player score and analyzing
engine score.
posScore is the score of the move in the game, in pawn unit.
engScore is the score of the move suggested by the engine,
in pawn unit.
Positive score is better for white and negative score is better
for black, (WPOV).
Scoring range from white's perspective:
Blunder: posScore < -1.50
Mistake: posScore >= -1.50 and posScore < -0.75
Dubious: posScore >= -0.75 and posScore < -0.15
Even : posScore >= -0.15 and posScore <= +0.15
Special condition:
1. If engine score is winning but player score is not winning,
consider this as a mistake.
Mistake: engScore > +1.50 and posScore < +1.50
"""
# Convert the posScore and engScore to side POV
# to easier calculate the move NAG = Numeric Annotation Glyphs.
if not side:
posScore = -1 * posScore
engScore = -1 * engScore
# Set default NAG, GUI will not display this.
moveNag = '$0'
# Blunder ??
if posScore < -MODERATE_SCORE and engScore >= -MODERATE_SCORE:
moveNag = '$4'
self.blunderCnt['w' if side else 'b'] += 1
# Mistake ?
elif posScore < -SLIGHT_SCORE and engScore >= -SLIGHT_SCORE:
moveNag = '$2'
self.badCnt['w' if side else 'b'] += 1
# Dubious ?!
elif posScore < -DRAW_SCORE and engScore >= -DRAW_SCORE:
moveNag = '$6'
# Mistake ? if engScore is winning and posScore is not winning
elif engScore > MODERATE_SCORE and posScore <= MODERATE_SCORE:
moveNag = '$2'
self.badCnt['w' if side else 'b'] += 1
# Mistake ? if posScore is too far from engScore by 0.50 or more
elif engScore >= -MODERATE_SCORE and engScore - posScore >= +0.50:
moveNag = '$2'
self.badCnt['w' if side else 'b'] += 1
# Exception, add ! if posScore > engScore
if posScore >= -SLIGHT_SCORE and posScore > engScore:
moveNag = '$1'
# Exception, add !? if posScore == engScore
elif posScore >= -SLIGHT_SCORE and posScore == engScore:
moveNag = '$5'
return moveNag
def PreComment(self, side, engScore, posScore):
""" returns a comment for the engine variation """
if not self.wordyComment:
return ''
if not side:
engScore = -1 * engScore
posScore = -1 * posScore
varComment = ''
if engScore - posScore > 5 * DRAW_SCORE:
varComment = '%s is' % sr.choice(BEST)
elif engScore - posScore > DRAW_SCORE:
varComment = '%s is' % sr.choice(BETTER)
return varComment
def WriteSanMove(self, side, moveNumber, sanMove):
""" Write moves only in the output file """
# Write the moves
with open(self.outfn, 'a+') as f:
self.writeCnt += 1
if side:
f.write('%d. %s ' %(moveNumber, sanMove))
else:
f.write('%s ' %(sanMove))
# Format output, don't write movetext in one long line.
if self.writeCnt >= 4:
self.writeCnt = 0
f.write('\n')
def WritePosScore(self, side, moveNumber, sanMove, posScore):
""" Write moves with score in the output file
This could be a case where the engine has no suggestion possibly
the game move is the same as the engine move
"""
# Write the move and comments
with open(self.outfn, 'a+') as f:
self.writeCnt += 1
# If side to move is white
if side:
if self.passedPawnIsGood:
f.write('%d. %s {%+0.2f, %s} ' % (moveNumber, sanMove,
posScore, 'with a better passer'))
self.whitePassedPawnCommentCnt += 1
elif self.kingSafetyIsGood:
f.write('%d. %s {%+0.2f, with a better king safety} ' %(
moveNumber, sanMove, posScore))
self.whiteKingSafetyCommentCnt += 1
elif self.mobilityIsGood:
f.write('%d. %s {%+0.2f, with a better piece mobility} ' %(
moveNumber, sanMove, posScore))
self.whiteMobilityCommentCnt += 1
elif self.matIsSacrificed:
f.write('%d. %s {%+0.2f, with compensation for the sacrificed material} ' %(
moveNumber, sanMove, posScore))
else:
f.write('%d. %s {%+0.2f} ' %(moveNumber, sanMove, posScore))
else:
if self.passedPawnIsGood:
f.write('%d... %s {%+0.2f, %s} ' % (moveNumber, sanMove,
posScore, 'with a better passer'))
self.blackPassedPawnCommentCnt += 1
elif self.kingSafetyIsGood:
f.write('%d... %s {%+0.2f, with a better king safety} ' %(
moveNumber, sanMove, posScore))
self.blackKingSafetyCommentCnt += 1
elif self.mobilityIsGood:
f.write('%d... %s {%+0.2f, with a better piece mobility} ' %(
moveNumber, sanMove, posScore))
self.blackMobilityCommentCnt += 1
elif self.matIsSacrificed:
f.write('%d... %s {%+0.2f, with compensation for the sacrificed material} ' %(
moveNumber, sanMove, posScore))
else:
f.write('%d... %s {%+0.2f} ' % (moveNumber, sanMove, posScore))
# Format output, don't write movetext in one long line.
if self.writeCnt >= 4:
self.writeCnt = 0
f.write('\n')
def WritePosScoreEngMove(self, side, moveNumber,
sanMove, posScore, engMove,
engScore, complexityNumber, moveChanges,
pvLine, threatMove):
""" Write moves with score and engMove in the output file """
# Write the move and comments
with open(self.outfn, 'a+') as f:
self.writeCnt += 1
# If side to move is white
if side:
if sanMove != engMove:
moveNag = self.GetBadNag(side, posScore, engScore)
# Add better is symbol before the engine variation, it can be empty.
varComment = self.PreComment(side, engScore, posScore)
if self.matIsSacrificed:
if moveNag == '$0':
if varComment == '':
f.write('%d. %s {%+0.2f, with compensation for the sacrificed material} (%s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, pvLine, engScore))
else:
f.write('%d. %s {%+0.2f, with compensation for the sacrificed material} ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, varComment,
pvLine, engScore))
else:
if varComment == '':
f.write('%d. %s %s {%+0.2f, with compensation for the sacrificed material} (%s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
pvLine, engScore))
else:
f.write('%d. %s %s {%+0.2f, with compensation for the sacrificed material} ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
varComment, pvLine, engScore))
else:
if moveNag == '$0':
if varComment == '':
f.write('%d. %s {%+0.2f} (%s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, pvLine, engScore))
else:
f.write('%d. %s {%+0.2f} ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, varComment,
pvLine, engScore))
else:
if varComment == '':
f.write('%d. %s %s {%+0.2f} (%s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
pvLine, engScore))
else:
f.write('%d. %s %s {%+0.2f} ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
varComment, pvLine, engScore))
# Else if game and engine move are the same
else:
moveNag = self.GetGoodNag(side, posScore, engScore,
complexityNumber, moveChanges)
if threatMove is None:
if self.passedPawnIsGood:
self.whitePassedPawnCommentCnt += 1
if moveNag == '$0':
f.write('%d. %s {%+0.2f, with a better passer} ' % (
moveNumber, sanMove, posScore))
else:
f.write('%d. %s %s {%+0.2f, with a better passer} ' % (
moveNumber, sanMove, moveNag, posScore))
elif self.kingSafetyIsGood:
self.whiteKingSafetyCommentCnt += 1
if moveNag == '$0':
f.write('%d. %s {%+0.2f, with a better king safety} ' % (
moveNumber, sanMove, posScore))
else:
f.write('%d. %s %s {%+0.2f, with a better king safety} ' % (
moveNumber, sanMove, moveNag, posScore))
elif self.mobilityIsGood:
self.whiteMobilityCommentCnt += 1
if moveNag == '$0':
f.write('%d. %s {%+0.2f, with a better piece mobility} ' % (
moveNumber, sanMove, posScore))
else:
f.write('%d. %s %s {%+0.2f, with a better piece mobility} ' % (
moveNumber, sanMove, moveNag, posScore))
elif self.matIsSacrificed:
if moveNag == '$0':
f.write('%d. %s {%+0.2f, with compensation for the sacrificed material} ' % (
moveNumber, sanMove, posScore))
else:
f.write('%d. %s %s {%+0.2f, with compensation for the sacrificed material} ' % (
moveNumber, sanMove, moveNag, posScore))
else:
if moveNag == '$0':
f.write('%d. %s {%+0.2f} ' %(
moveNumber, sanMove, posScore))
else:
f.write('%d. %s %s {%+0.2f} ' % (
moveNumber, sanMove, moveNag, posScore))
# Else if there is threat move
else:
if moveNag == '$0':
f.write('%d. %s {%+0.2f, %s %s} ' % (
moveNumber, sanMove, posScore,
sr.choice(PLAN_COMMENT), threatMove))
else:
f.write('%d. %s %s {%+0.2f, %s %s} ' % (
moveNumber, sanMove, moveNag, posScore,
sr.choice(PLAN_COMMENT), threatMove))
# Else if side to move is black
else:
if sanMove != engMove:
moveNag = self.GetBadNag(side, posScore, engScore)
# Add better is symbol before the engine variation, can be empty.
varComment = self.PreComment(side, engScore, posScore)
if self.matIsSacrificed:
if moveNag == '$0':
if varComment == '':
f.write('%d... %s {%+0.2f, with compensation for the sacrificed material} (%s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, pvLine,
engScore))
else:
f.write('%d... %s {%+0.2f, with compensation for the sacrificed material} ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, varComment,
pvLine, engScore))
else:
if varComment == '':
f.write('%d... %s %s {%+0.2f, with compensation for the sacrificed material} (%s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
pvLine, engScore))
else:
f.write('%d... %s %s {%+0.2f, with compensation for the sacrificed material} ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
varComment, pvLine, engScore))
else:
if moveNag == '$0':
if varComment == '':
f.write('%d... %s {%+0.2f} (%s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, pvLine,
engScore))
else:
f.write('%d... %s {%+0.2f} ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, varComment,
pvLine, engScore))
else:
if varComment == '':
f.write('%d... %s %s {%+0.2f} (%s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
pvLine, engScore))
else:
f.write('%d... %s %s {%+0.2f} ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
varComment, pvLine, engScore))
else:
moveNag = self.GetGoodNag(side, posScore, engScore,
complexityNumber, moveChanges)
if threatMove is None:
if self.passedPawnIsGood:
self.blackPassedPawnCommentCnt += 1
if moveNag == '$0':
f.write('%d... %s {%+0.2f, with a better passer} ' % (
moveNumber, sanMove, posScore))
else:
f.write('%d... %s %s {%+0.2f, with a better passer} ' % (
moveNumber, sanMove, moveNag, posScore))
elif self.kingSafetyIsGood:
self.blackKingSafetyCommentCnt += 1
if moveNag == '$0':
f.write('%d... %s {%+0.2f, with a better king safety} ' % (
moveNumber, sanMove, posScore))
else:
f.write('%d... %s %s {%+0.2f, with a better king safety} ' % (
moveNumber, sanMove, moveNag, posScore))
elif self.mobilityIsGood:
self.blackMobilityCommentCnt += 1
if moveNag == '$0':
f.write('%d... %s {%+0.2f, with a better piece mobility} ' % (
moveNumber, sanMove, posScore))
else:
f.write('%d... %s %s {%+0.2f, with a better piece mobility} ' % (
moveNumber, sanMove, moveNag, posScore))
elif self.matIsSacrificed:
if moveNag == '$0':
f.write('%d... %s {%+0.2f, with compensation for the sacrificed material} ' % (
moveNumber, sanMove, posScore))
else:
f.write('%d... %s %s {%+0.2f, with compensation for the sacrificed material} ' % (
moveNumber, sanMove, moveNag, posScore))
else:
if moveNag == '$0':
f.write('%d... %s {%+0.2f} ' % (
moveNumber, sanMove, posScore))
else:
f.write('%d... %s %s {%+0.2f} ' % (
moveNumber, sanMove, moveNag, posScore))
# Else if there is threat move
else:
if moveNag == '$0':
f.write('%d... %s {%+0.2f, %s %s} ' % (
moveNumber, sanMove, posScore,
sr.choice(PLAN_COMMENT), threatMove))
else:
f.write('%d... %s %s {%+0.2f, %s %s} ' % (
moveNumber, sanMove, moveNag, posScore,
sr.choice(PLAN_COMMENT), threatMove))
# Format output, don't write movetext in one long line.
if self.writeCnt >= 2:
self.writeCnt = 0
f.write('\n')
def WriteBookMove(self, side, moveNumber, sanMove, bookMove):
""" Write moves with book moves in the output file """
assert bookMove is not None
# Write the move and comments
with open(self.outfn, 'a+') as f:
self.writeCnt += 1
# If side to move is white
if side:
f.write('%d. %s (%d. %s {%s}) ' % (
moveNumber, sanMove, moveNumber, bookMove, BOOK_COMMENT))
else:
f.write('%d... %s (%d... %s {%s}) ' % (
moveNumber, sanMove, moveNumber, bookMove, BOOK_COMMENT))
# Format output, don't write movetext in one long line.
if self.writeCnt >= 2:
self.writeCnt = 0
f.write('\n')
def WritePosScoreBookMove(self, side, moveNumber, sanMove,
bookMove, posScore):
""" Write moves with score and book moves in the output file """
assert bookMove is not None
# Write the move and comments
with open(self.outfn, 'a+') as f:
self.writeCnt += 1
# If side to move is white
if side:
f.write('%d. %s {%+0.2f} (%d. %s {%s}) ' % (
moveNumber, sanMove, posScore, moveNumber, bookMove,
BOOK_COMMENT))
else:
f.write('%d... %s {%+0.2f} (%d... %s {%s}) ' % (
moveNumber, sanMove, posScore, moveNumber, bookMove,
BOOK_COMMENT))
# Format output, don't write movetext in one long line.
if self.writeCnt >= 2:
self.writeCnt = 0
f.write('\n')
def WritePosScoreBookMoveEngMove(
self, side, moveNumber, sanMove, bookMove, posScore, engMove,
engScore, complexityNumber, moveChanges, pvLine, threatMove):
""" Write moves with score and book moves in the output file """
# Write the move and comments
with open(self.outfn, 'a+') as f:
self.writeCnt += 1
# If side to move is white
if side:
if sanMove != engMove:
moveNag = self.GetBadNag(side, posScore, engScore)
moveNag = '$0' if self.moveTime < 20000 else moveNag
# Add better is symbol before the engine variation can be empty.
varComment = self.PreComment(side, engScore, posScore)
if moveNag == '$0':
if varComment == '':
f.write('%d. %s {%+0.2f} (%d. %s {%s}) (%s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, moveNumber,
bookMove, BOOK_COMMENT, pvLine, engScore))
else:
f.write('%d. %s {%+0.2f} (%d. %s {%s}) ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, moveNumber,
bookMove, BOOK_COMMENT, varComment, pvLine,
engScore))
else:
if varComment == '':
f.write('%d. %s %s {%+0.2f} (%d. %s {%s}) (%s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
moveNumber, bookMove, BOOK_COMMENT, pvLine,
engScore))
else:
f.write('%d. %s %s {%+0.2f} (%d. %s {%s}) ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
moveNumber, bookMove, BOOK_COMMENT,
varComment, pvLine, engScore))
# Else if game and engine move are the same
else:
moveNag = self.GetGoodNag(side, posScore, engScore,
complexityNumber, moveChanges)
if threatMove is not None:
if moveNag == '$0':
f.write('%d. %s {%+0.2f, %s %s} (%d. %s {%s}) ' % (
moveNumber, sanMove, posScore,
sr.choice(PLAN_COMMENT), threatMove,
moveNumber, bookMove, BOOK_COMMENT))
else:
f.write('%d. %s %s {%+0.2f, %s %s} (%d. %s {%s}) ' % (
moveNumber, sanMove, moveNag, posScore,
sr.choice(PLAN_COMMENT), threatMove,
moveNumber, bookMove, BOOK_COMMENT))
# Else if there is no threat move
else:
if moveNag == '$0':
f.write('%d. %s {%+0.2f} (%d. %s {%s}) ' %(
moveNumber, sanMove, posScore, moveNumber,
bookMove, BOOK_COMMENT))
else:
f.write('%d. %s %s {%+0.2f} (%d. %s {%s}) ' %(
moveNumber, sanMove, moveNag, posScore,
moveNumber, bookMove, BOOK_COMMENT))
else:
if sanMove != engMove:
moveNag = self.GetBadNag(side, posScore, engScore)
moveNag = '$0' if self.moveTime < 20000 else moveNag
# Add better is symbol before the engine variation can be empty.
varComment = self.PreComment(side, engScore, posScore)
if moveNag == '$0':
if varComment == '':
f.write('%d... %s {%+0.2f} (%d... %s {%s}) (%s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, moveNumber,
bookMove, BOOK_COMMENT, pvLine, engScore))
else:
f.write('%d... %s {%+0.2f} (%d... %s {%s}) ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, posScore, moveNumber,
bookMove, BOOK_COMMENT, varComment, pvLine,
engScore))
else:
if varComment == '':
f.write('%d... %s %s {%+0.2f} (%d... %s {%s}) (%s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
moveNumber, bookMove, BOOK_COMMENT, pvLine,
engScore))
else:
f.write('%d... %s %s {%+0.2f} (%d... %s {%s}) ({%s} %s {%+0.2f}) ' % (
moveNumber, sanMove, moveNag, posScore,
moveNumber, bookMove, BOOK_COMMENT,
varComment, pvLine, engScore))
# Else if game and engine move are the same
else:
moveNag = self.GetGoodNag(
side, posScore, engScore, complexityNumber,
moveChanges)
moveNag = '$0' if self.moveTime < 20000 else moveNag
if threatMove is not None:
if moveNag == '$0':
f.write('%d... %s {%+0.2f, %s %s} (%d... %s {%s}) ' % (
moveNumber, sanMove, posScore,
sr.choice(PLAN_COMMENT), threatMove,
moveNumber, bookMove, BOOK_COMMENT))
else:
f.write('%d... %s %s {%+0.2f, %s %s} (%d... %s {%s}) ' % (
moveNumber, sanMove, moveNag, posScore,
sr.choice(PLAN_COMMENT), threatMove,
moveNumber, bookMove, BOOK_COMMENT))
else:
if moveNag == '$0':
f.write('%d... %s {%+0.2f} (%d... %s {%s}) ' % (
moveNumber, sanMove, posScore, moveNumber,
bookMove, BOOK_COMMENT))
else:
f.write('%d... %s %s {%+0.2f} (%d... %s {%s}) ' % (
moveNumber, sanMove, moveNag, posScore,
moveNumber, bookMove, BOOK_COMMENT))
# Format output, don't write movetext in one long line.
if self.writeCnt >= 2:
self.writeCnt = 0
f.write('\n')
def WriteBookMoveEngMove(
self, side, moveNumber, sanMove, bookMove, engMove, engScore, pvLine):
""" Write moves with book moves and eng moves in the output file """
assert bookMove is not None
# Write the move and comments
with open(self.outfn, 'a+') as f:
self.writeCnt += 1
# If side to move is white
if side:
if sanMove != engMove:
# Write moves and comments
f.write('%d. %s (%d. %s {%s}) (%s {%+0.2f}) ' % (
moveNumber, sanMove, moveNumber, bookMove,
BOOK_COMMENT, pvLine, engScore))
else:
f.write('%d. %s (%d. %s {%s}) ' % (
moveNumber, sanMove, moveNumber, bookMove, BOOK_COMMENT))
else:
if sanMove != engMove:
# Write moves and comments
f.write('%d... %s (%d... %s {%s}) (%s {%+0.2f}) ' % (
moveNumber, sanMove, moveNumber, bookMove,
BOOK_COMMENT, pvLine, engScore))
else:
f.write('%d... %s (%d... %s {%s}) ' % (
moveNumber, sanMove, moveNumber, bookMove,
BOOK_COMMENT))
# Format output, don't write movetext in one long line.
if self.writeCnt >= 2:
self.writeCnt = 0
f.write('\n')
def WriteEngMove(self, side, moveNumber, sanMove, engMove, engScore, pvLine):
""" Write moves with eng moves in the output file """
# Write the move and comments
with open(self.outfn, 'a+') as f:
# If side to move is white
if side:
if sanMove != engMove:
# Write moves and comments
f.write('%d. %s (%s {%+0.2f}) ' % (
moveNumber, sanMove, pvLine, engScore))
else:
f.write('%d. %s ' % (moveNumber, sanMove))
else:
if sanMove != engMove:
# Write moves and comments
f.write('%d... %s (%s {%+0.2f}) ' % (
moveNumber, sanMove, pvLine, engScore))
else:
f.write('%d... %s ' % (moveNumber, sanMove))
def WritePosFromNoMoveGame(self, side, moveNumber, engMove, engScore, depth):
with open(self.outfn, 'a+') as f:
if side:
f.write(f'{moveNumber}. {engMove} {{{engScore}/{depth}}}')
else:
f.write(f'{moveNumber}... {engMove} {{{engScore}/{depth}}}')
def WriteNotation(self, side, fmvn, sanMove, bookMove, posScore,
isGameOver, engMove, engScore, complexityNumber,
moveChanges, pvLine, threatMove, depth=0):
""" Write moves and comments to the output file """
if isGameOver:
self.WriteSanMove(side, fmvn, sanMove)
return
# IF game has no move we write the pgn here.
if depth > 0:
self.WritePosFromNoMoveGame(side, fmvn, engMove, engScore, depth)
return
# (0) If game is over [mate, stalemate] just print the move.
if posScore is None and bookMove is None:
self.WriteSanMove(side, fmvn, sanMove)
return
# (1) Write sanMove, posScore
isWritePosScore = posScore is not None and bookMove is None and engMove is None
if isWritePosScore:
self.WritePosScore(side, fmvn, sanMove, posScore)
return
# (2) Write sanMove, posScore, bookMove
isWritePosScoreBook = posScore is not None and bookMove is not None and engMove is None
if isWritePosScoreBook:
self.WritePosScoreBookMove(side, fmvn, sanMove, bookMove, posScore)
return
# (3) Write sanMove, posScore and engMove
isWritePosScoreEngMove = posScore is not None and bookMove is None and engMove is not None
if isWritePosScoreEngMove:
self.WritePosScoreEngMove(
side, fmvn, sanMove, posScore, engMove, engScore, complexityNumber, moveChanges, pvLine, threatMove)
return
# (4) Write sanMove, posScore, bookMove and engMove
isWritePosScoreBookEngMove = (posScore is not None and
bookMove is not None and
engMove is not None)
if isWritePosScoreBookEngMove:
self.WritePosScoreBookMoveEngMove(
side, fmvn, sanMove, bookMove, posScore, engMove, engScore,
complexityNumber, moveChanges, pvLine, threatMove)
return
# (5) Write sanMove, bookMove
isWriteBook = (posScore is None and
bookMove is not None and
engMove is None)
if isWriteBook:
self.WriteBookMove(side, fmvn, sanMove, bookMove)
return
# (6) Write sanMove, bookMove and engMove
isWriteBookEngMove = (posScore is None and
bookMove is not None and
engMove is not None)
if isWriteBookEngMove:
self.WriteBookMoveEngMove(
side, fmvn, sanMove, bookMove, engMove, engScore, pvLine)
return
# (7) Write sanMove, engMove
isWriteEngMove = (posScore is None and
bookMove is None and
engMove is not None)
if isWriteEngMove:
self.WriteEngMove(side, fmvn, sanMove, engMove, engScore, pvLine)
return
def MateDistanceToValue(self, d):
""" Returns value given distance to mate """
value = 0
if d < 0:
value = -2*d - MAX_SCORE
elif d > 0:
value = MAX_SCORE - 2*d + 1
return value
@staticmethod
def GetMaterialInfo(fen):
""" Returns number of queens, pawns and white and
black material. Material is calculated based
on q=9, r=5, b=3, n=3
"""
# Get piece field of fen
pieces = fen.split()[0]
# Count pieces
Q = pieces.count('Q')
q = pieces.count('q')
R = pieces.count('R')
r = pieces.count('r')
B = pieces.count('B')
b = pieces.count('b')
N = pieces.count('N')
n = pieces.count('n')
P = pieces.count('P')
p = pieces.count('p')
# Get piece values except pawns
wmat = Q*9 + R*5 + B*3 + N*3
bmat = q*9 + r*5 + b*3 + n*3
# Get queen and pawn counts
queens = Q+q
pawns = P+p
return wmat, bmat, queens, pawns
@staticmethod
def GetMaterialBalance(fen):
"""
Returns material balance in wpov from a given fen.
"""
# Get piece field of fen
pieces = fen.split()[0]
# Count pieces
Q = pieces.count('Q')
q = pieces.count('q')
R = pieces.count('R')
r = pieces.count('r')
B = pieces.count('B')
b = pieces.count('b')
N = pieces.count('N')
n = pieces.count('n')
P = pieces.count('P')
p = pieces.count('p')
return 10*(Q - q) + 5*(R - r) + 3*(B - b) + 3*(N - n) + (P - p)
def GetEngineIdName(self):
""" Returns the engine id name """
if self.engineName is not None:
return self.engineName
engineIdName = self.eng[0:-4]
p = subprocess.Popen(self.eng, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, bufsize=1)
self.Send(p, 'uci')
for eline in iter(p.stdout.readline, ''):
line = eline.strip()
if 'id name ' in line:
idName = line.split()
engineIdName = ' '.join(idName[2:])
if 'uciok' in line:
break
self.Send(p, 'quit')
p.communicate()
return engineIdName
def IsKingSafetyGood(self, nextFen, side):
"""
Returns True if king safety of side not to move is bad. This is only
applicable for Stockfish or Brainfish engines.
Example line to be parsed:
King safety | 3.01 3.87 | 0.08 0.39 | 2.92 3.48
"""
logging.info('Check king safety')
p = subprocess.Popen(self.eng, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, bufsize=1)
self.Send(p, 'uci')
self.ReadEngineReply(p, 'uci')
self.Send(p, 'ucinewgame')
self.Send(p, 'position fen %s' % nextFen)
self.Send(p, 'eval')
# Parse the output
kingSafetyCommentNext = None
for eline in iter(p.stdout.readline, ''):
line = eline.strip()
if 'King safety ' in line:
kingSafetyCommentNext = line
break
if 'final evaluation' in line.lower():
break
self.Send(p, 'quit')
p.communicate()
if kingSafetyCommentNext is None:
return False
# Net score white POV
whiteMgKingSafetyNext = float(kingSafetyCommentNext.split()[9])
# Evaluate the king safety of side not to move based on curFen
sideToEvaluate = not side
# If white
if sideToEvaluate:
if whiteMgKingSafetyNext >= 1.0:
return True