-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmichi.go
1921 lines (1781 loc) · 53.8 KB
/
michi.go
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
// A minimalistic Go-playing engine attempting to strike a balance between
// brevity, educational value and strength.
// Based on michi.py by Petr Baudis <[email protected]> (https://github.com/pasky/michi)
package main
import (
"bufio"
"bytes"
"fmt"
"math"
"math/rand"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"unicode"
xxhash "github.com/OneOfOne/xxhash"
mt64 "github.com/bszcz/mt19937_64"
)
// Given a board of size NxN (N=9, 19, ...), we represent the position
// as an (N+1)*(N+2) string, with '.' (empty), 'X' (to-play player),
// 'x' (other player), and whitespace (off-board border to make rules
// implementation easier). Coordinates are just indices in this string.
// You can simply print(board) when debugging.
const (
N = 13 // boardsize
W = N + 2 // arraysize including buffer for board edge
columnString = "ABCDEFGHJKLMNOPQRST" // labels for columns
MAX_GAME_LEN = N * N * 3
)
// emptyBoard is a byte slice representing an empty board
var emptyBoard []byte
const (
PASS = -1346458457 // 'P','A','S','S' 0x50415353
NONE = -1313820229 // 'N','O','N','E' 0x4e4f4e45
)
// constants related to the operation of the MCTS move selection
const (
N_SIMS = 1400 // number of playouts for Monte-Carlo Search
RAVE_EQUIV = 3500
EXPAND_VISITS = 8
PRIOR_EVEN = 10 // should be even number; 0.5 prior
PRIOR_SELFATARI = 10 // negative prior
PRIOR_CAPTURE_ONE = 15
PRIOR_CAPTURE_MANY = 30
PRIOR_PAT3 = 10
PRIOR_LARGEPATTERN = 100 // most moves have relatively small probability
PRIOR_EMPTYAREA = 10
REPORT_PERIOD = 200
PROB_SSAREJECT = 0.9 // probability of rejecting suggested self-atari in playout
PROB_RSAREJECT = 0.5 // probability of rejecting random self-atari in playout; this is lower than above to allow nakade
RESIGN_THRES = 0.2
FASTPLAY20_THRES = 0.8 // if at 20% playouts winrate is >this, stop reading
FASTPLAY5_THRES = 0.95 // if at 5% playouts winrate is >this, stop reading
)
var PRIOR_CFG = [...]int{24, 22, 8} // priors for moves in cfg dist. 1, 2, 3
// probability of heuristic suggestions being taken in playout
var PROB_HEURISTIC = map[string]float64{
"capture": 0.9,
"pat3": 0.95,
}
// filenames for the large patterns from the Pachi Go engine
const (
spatPatternDictFile = "patterns.spat"
largePatternsFile = "patterns.prob"
)
// 3x3 playout patterns; X,O are colors, x,o are their inverses
var pattern3x3Source = [...][][]byte{
{{'X', 'O', 'X'}, // hane pattern - enclosing hane
{'.', '.', '.'},
{'?', '?', '?'}},
{{'X', 'O', '.'}, // hane pattern - non-cutting hane
{'.', '.', '.'},
{'?', '.', '?'}},
{{'X', 'O', '?'}, // hane pattern - magari
{'X', '.', '.'},
{'x', '.', '?'}},
// {{'X','O','O'}, // hane pattern - thin hane
// {'.','.','.'},
// {'?','.','?'}} "X", - only for the X player
{{'.', 'O', '.'}, // generic pattern - katatsuke or diagonal attachment; similar to magari
{'X', '.', '.'},
{'.', '.', '.'}},
{{'X', 'O', '?'}, // cut1 pattern (kiri] - unprotected cut
{'O', '.', 'o'},
{'?', 'o', '?'}},
{{'X', 'O', '?'}, // cut1 pattern (kiri] - peeped cut
{'O', '.', 'X'},
{'?', '?', '?'}},
{{'?', 'X', '?'}, // cut2 pattern (de]
{'O', '.', 'O'},
{'o', 'o', 'o'}},
{{'O', 'X', '?'}, // cut keima
{'o', '.', 'O'},
{'?', '?', '?'}},
{{'X', '.', '?'}, // side pattern - chase
{'O', '.', '?'},
{' ', ' ', ' '}},
{{'O', 'X', '?'}, // side pattern - block side cut
{'X', '.', 'O'},
{' ', ' ', ' '}},
{{'?', 'X', '?'}, // side pattern - block side connection
{'x', '.', 'O'},
{' ', ' ', ' '}},
{{'?', 'X', 'O'}, // side pattern - sagari
{'x', '.', 'x'},
{' ', ' ', ' '}},
{{'?', 'O', 'X'}, // side pattern - cut
{'X', '.', 'O'},
{' ', ' ', ' '}},
}
// 3x3 pattern routines (those patterns stored in pattern3x3Source above)
// All possible neighborhood configurations matching a given pattern;
// used just for a combinatoric explosion when loading them in an
// in-memory set.
func pat3_expand(pat [][]byte) [][]byte {
pat_rot90 := func(p [][]byte) [][]byte {
return [][]byte{{p[2][0], p[1][0], p[0][0]},
{p[2][1], p[1][1], p[0][1]},
{p[2][2], p[1][2], p[0][2]}}
}
pat_vertflip := func(p [][]byte) [][]byte {
return [][]byte{p[2], p[1], p[0]}
}
pat_horizflip := func(p [][]byte) [][]byte {
return [][]byte{{p[0][2], p[0][1], p[0][0]},
{p[1][2], p[1][1], p[1][0]},
{p[2][2], p[2][1], p[2][0]}}
}
pat_swapcolors := func(p [][]byte) [][]byte {
l := [][]byte{}
for _, s := range p {
s = bytes.Replace(s, []byte{'X'}, []byte{'Z'}, -1)
s = bytes.Replace(s, []byte{'x'}, []byte{'z'}, -1)
s = bytes.Replace(s, []byte{'O'}, []byte{'X'}, -1)
s = bytes.Replace(s, []byte{'o'}, []byte{'x'}, -1)
s = bytes.Replace(s, []byte{'Z'}, []byte{'O'}, -1)
s = bytes.Replace(s, []byte{'z'}, []byte{'o'}, -1)
l = append(l, s)
}
return l
}
var pat_wildexp func(p []byte, c byte, to []byte) [][]byte
pat_wildexp = func(p []byte, c byte, to []byte) [][]byte {
i := bytes.Index(p, []byte{c})
if i == -1 {
return append([][]byte{}, p)
}
l := [][]byte{}
for _, t := range bytes.Split(to, []byte{}) {
l = append(l, pat_wildexp(append(append(append([]byte{}, p[:i]...), t[0]), p[i+1:]...), c, to)...)
}
return l
}
pat_wildcards := func(pat []byte) [][]byte {
l := [][]byte{}
for _, p1 := range pat_wildexp(pat, '?', []byte{'.', 'X', 'O', ' '}) {
for _, p2 := range pat_wildexp(p1, 'x', []byte{'.', 'O', ' '}) {
for _, p3 := range pat_wildexp(p2, 'o', []byte{'.', 'X', ' '}) {
l = append(l, p3)
}
}
}
return l
}
rl := [][]byte{}
for _, p1 := range [][][]byte{pat, pat_rot90(pat)} {
for _, p2 := range [][][]byte{p1, pat_vertflip(p1)} {
for _, p3 := range [][][]byte{p2, pat_horizflip(p2)} {
for _, p4 := range [][][]byte{p3, pat_swapcolors(p3)} {
for _, p5 := range pat_wildcards(bytes.Join(p4, []byte{})) {
rl = append(rl, p5)
}
}
}
}
}
return rl
}
func pat3set_func() map[string]struct{} {
m := make(map[string]struct{})
for _, p := range pattern3x3Source {
for _, s := range pat3_expand(p) {
s = bytes.Replace(s, []byte{'O'}, []byte{'x'}, -1)
m[string(s)] = struct{}{}
}
}
return m
}
var pat3set map[string]struct{}
var patternGridcularSequence = [][][]int{ // Sequence of coordinate offsets of progressively wider diameters in gridcular metric
{{0, 0},
{0, 1}, {0, -1}, {1, 0}, {-1, 0},
{1, 1}, {-1, 1}, {1, -1}, {-1, -1}}, // d=1,2 is not considered separately
{{0, 2}, {0, -2}, {2, 0}, {-2, 0}},
{{1, 2}, {-1, 2}, {1, -2}, {-1, -2}, {2, 1}, {-2, 1}, {2, -1}, {-2, -1}},
{{0, 3}, {0, -3}, {2, 2}, {-2, 2}, {2, -2}, {-2, -2}, {3, 0}, {-3, 0}},
{{1, 3}, {-1, 3}, {1, -3}, {-1, -3}, {3, 1}, {-3, 1}, {3, -1}, {-3, -1}},
{{0, 4}, {0, -4}, {2, 3}, {-2, 3}, {2, -3}, {-2, -3}, {3, 2}, {-3, 2}, {3, -2}, {-3, -2}, {4, 0}, {-4, 0}},
{{1, 4}, {-1, 4}, {1, -4}, {-1, -4}, {3, 3}, {-3, 3}, {3, -3}, {-3, -3}, {4, 1}, {-4, 1}, {4, -1}, {-4, -1}},
{{0, 5}, {0, -5}, {2, 4}, {-2, 4}, {2, -4}, {-2, -4}, {4, 2}, {-4, 2}, {4, -2}, {-4, -2}, {5, 0}, {-5, 0}},
{{1, 5}, {-1, 5}, {1, -5}, {-1, -5}, {3, 4}, {-3, 4}, {3, -4}, {-3, -4}, {4, 3}, {-4, 3}, {4, -3}, {-4, -3}, {5, 1}, {-5, 1}, {5, -1}, {-5, -1}},
{{0, 6}, {0, -6}, {2, 5}, {-2, 5}, {2, -5}, {-2, -5}, {4, 4}, {-4, 4}, {4, -4}, {-4, -4}, {5, 2}, {-5, 2}, {5, -2}, {-5, -2}, {6, 0}, {-6, 0}},
{{1, 6}, {-1, 6}, {1, -6}, {-1, -6}, {3, 5}, {-3, 5}, {3, -5}, {-3, -5}, {5, 3}, {-5, 3}, {5, -3}, {-5, -3}, {6, 1}, {-6, 1}, {6, -1}, {-6, -1}},
{{0, 7}, {0, -7}, {2, 6}, {-2, 6}, {2, -6}, {-2, -6}, {4, 5}, {-4, 5}, {4, -5}, {-4, -5}, {5, 4}, {-5, 4}, {5, -4}, {-5, -4}, {6, 2}, {-6, 2}, {6, -2}, {-6, -2}, {7, 0}, {-7, 0}},
}
//######################
// Initialization
// collect all dynamic initializations into a callable function
// performInitialization() collects all the runtime initializations together
// so they can be called from main() allowing better control
func performInitialization() {
emptyBoard = append(append(append(bytes.Repeat([]byte{' '}, N+1), '\n'),
bytes.Repeat(append([]byte{' '}, append(bytes.Repeat([]byte{'.'}, N), '\n')...), N)...),
bytes.Repeat([]byte{' '}, N+2)...)
pat3set = pat3set_func()
spatPatternDict = make(map[int]uint64) // hash(neighborhoodGridcular()) <- spatial id
largePatterns = make(map[uint64]float64) // hash(neighborhoodGridcular()) -> probability
}
//######################
// board string routines
// generator of coordinates for all neighbors of c
func neighbors(c int) []int {
return []int{c - 1, c + 1, c - W, c + W}
}
// generator of coordinates for all diagonal neighbors of c
func diagonalNeighbors(c int) []int {
return []int{c - W - 1, c - W + 1, c + W - 1, c + W + 1}
}
func boardPut(board []byte, c int, p byte) []byte {
board[c] = p
return board
}
// replace continuous-color area starting at c with special color #
func floodfill(board []byte, c int) []byte {
localBoard := make([]byte, len(board))
copy(localBoard, board)
// XXX: Use bytearray to speed things up? (still needed in golang?)
p := localBoard[c]
localBoard = boardPut(localBoard, c, '#')
fringe := []int{c}
for len(fringe) > 0 {
c, fringe = fringe[len(fringe)-1], fringe[:len(fringe)-1]
for _, d := range neighbors(c) {
if localBoard[d] == p {
localBoard = boardPut(localBoard, d, '#')
fringe = append(fringe, d)
}
}
}
return localBoard
}
// test if point of color p is adjecent to color # anywhere
// on the board; use in conjunction with floodfill for reachability
func contact(board []byte, p byte) int {
for i := W; i < len(board)-W-1; i++ {
if board[i] == '#' {
for _, j := range neighbors(i) {
if board[j] == p {
return j
}
}
}
}
return NONE
}
// Use Mersenne Twister as Random Number Generator in place of default
// Use multiple RNG sources to reduce contention
var rng *rand.Rand
func newRNG() *rand.Rand {
rng := rand.New(mt64.New())
rng.Seed(time.Now().UnixNano())
return rng
}
// mapping function to swap individual characters
func swapCase(r rune) rune {
switch {
case 'a' <= r && r <= 'z':
return r - 'a' + 'A'
case 'A' <= r && r <= 'Z':
return r - 'A' + 'a'
default:
return r
}
}
// function to apply mapping to string
func SwapCase(str []byte) []byte {
b := make([]byte, len(str))
for i, c := range str {
r := rune(c)
if unicode.IsUpper(r) {
b[i] = byte(unicode.ToLower(r))
} else {
b[i] = byte(unicode.ToUpper(r))
}
}
return b
}
// shuffle slice elements
func shuffleInt(a []int, rng *rand.Rand) {
for i := len(a) - 1; i > 0; i-- {
j := rng.Intn(i + 1)
a[i], a[j] = a[j], a[i]
}
}
func shuffleTree(a []*TreeNode, rng *rand.Rand) {
for i := len(a) - 1; i > 0; i-- {
j := rng.Intn(i + 1)
a[i], a[j] = a[j], a[i]
}
}
// create routine to test existence of element in slice
func intInSlice(intSlice []int, intTest int) bool {
for _, i := range intSlice {
if i == intTest {
return true
}
}
return false
}
func patternInSet(strSlice map[string]struct{}, strTest []byte) bool {
_, exists := strSlice[string(strTest)]
return exists
}
// test for edge of board
func isSpace(b byte) bool {
return bytes.Contains([]byte{' ', '\n'}, []byte{b})
}
// End of functions added to replace Python functions and methods
// test if c is inside a single-color diamond and return the diamond
// color or None; this could be an eye, but also a false one
func isEyeish(board []byte, c int) byte {
var eyeColor, otherColor byte
for _, d := range neighbors(c) {
if isSpace(board[d]) {
continue
}
if board[d] == '.' {
return 0
}
if eyeColor == 0 {
eyeColor = board[d]
otherColor = byte(swapCase(rune(eyeColor)))
} else {
if board[d] == otherColor {
return 0
}
}
}
return eyeColor
}
// test if c is an eye and return its color or None
func isEye(board []byte, c int) byte {
eyeColor := isEyeish(board, c)
if eyeColor == 0 {
return 0
}
// Eye-like shape, but it could be a falsified eye
falseColor := byte(swapCase(rune(eyeColor)))
falseCount := 0
atEdge := false
for _, d := range diagonalNeighbors(c) {
if isSpace(board[d]) {
atEdge = true
} else {
if board[d] == falseColor {
falseCount += 1
}
}
}
if atEdge {
falseCount += 1
}
if falseCount >= 2 {
return 0
}
return eyeColor
}
// Implementation of simple Chinese Go rules
// Position holds the current state of a the game including the stones on the
// board, the captured stones, the current Ko state, the last 2 moves, and the
// komi used.
type Position struct {
board []byte // string representation of board state
cap []int // holds total captured stones for each player
n int // n is how many moves were played so far
ko int // location of prohibited move under simple ko rules
last int // previous move
last2 int // antepenultimate move
komi float64
}
// play as player X at the given coord c, return the new position
func (p Position) move(c int) (Position, string) {
// Test for ko
if c == p.ko {
return p, "ko"
}
// Are we trying to play in enemy's eye?
inEnemyEye := isEyeish(p.board, c) == 'x'
board := make([]byte, len(p.board))
copy(board, p.board)
board = boardPut(board, c, 'X')
// Test for captures, and track ko
capX := p.cap[0]
singleCaps := []int{}
for _, d := range neighbors(c) {
if board[d] != 'x' {
continue
}
// XXX: The following is an extremely naive and SLOW approach
// at things - to do it properly, we should maintain some per-group
// data structures tracking liberties.
fillBoard := floodfill(board, d) // get a board with the adjacent group replaced by '#'
if contact(fillBoard, '.') != NONE {
continue // some liberties left
}
// no liberties left for this group, remove the stones!
captureCount := bytes.Count(fillBoard, []byte{'#'})
if captureCount == 1 {
singleCaps = append(singleCaps, d)
}
capX += captureCount
board = bytes.Replace(fillBoard, []byte{'#'}, []byte{'.'}, -1) // capture the group
}
// set ko
ko := NONE
if inEnemyEye && len(singleCaps) == 1 {
ko = singleCaps[0]
}
// Test for suicide
if contact(floodfill(board, c), '.') == NONE {
return p, "suicide"
}
// Update the position and return
p.board = SwapCase(board)
p.cap = []int{p.cap[1], capX}
p.n = p.n + 1
p.ko = ko
p.last2 = p.last // must copy first
p.last = c
p.komi = p.komi
return p, "ok"
}
// pass - i.e. return simply a flipped position
func (p Position) passMove() (Position, string) {
p.board = SwapCase(p.board)
p.cap = []int{p.cap[1], p.cap[0]}
p.n = p.n + 1
p.ko = NONE
p.last2 = p.last // must copy first
p.last = PASS
p.komi = p.komi
return p, "ok"
}
// Generate a list of moves (includes false positives - suicide moves;
// does not include true-eye-filling moves), starting from a given board
// index (that can be used for randomization)
func (p Position) moves(i0 int, done chan struct{}) chan int {
c := make(chan int)
go func() {
defer close(c)
i := i0 - 1
passes := 0
for {
index := bytes.Index(p.board[i+1:], []byte{'.'})
if passes > 0 && (index == -1 || i+index+1 >= i0) {
return // we have looked through the whole board
}
if index == -1 {
i = 0
passes += 1
continue // go back and start from the beginning
}
i += index + 1
// Test for to-play player's one-point eye
if isEye(p.board, i) == 'X' {
continue
}
select {
case c <- i:
case <-done:
return
}
}
// close(c) defer'd
}()
return c
}
// generate a randomly shuffled list of points including and
// surrounding the last two moves (but with the last move having
// priority)
func (p Position) lastMovesNeighbors(rng *rand.Rand) []int {
cList := []int{}
dList := []int{}
for _, c := range []int{p.last, p.last2} {
if c < 0 { // if there was no last move, or pass
continue
}
dList = append([]int{c}, append(neighbors(c), diagonalNeighbors(c)...)...)
shuffleInt(dList, rng)
for _, d := range dList {
if intInSlice(cList, d) {
continue
}
cList = append(cList, d)
}
}
return cList
}
// compute score for to-play player; this assumes a final position
// with all dead stones captured; if owner_map is passed, it is assumed
// to be an array of statistics with average owner at the end of the game
// (+1 black, -1 white)
func (p Position) score(owner_map []float64) float64 {
board := make([]byte, len(p.board))
copy(board, p.board)
var fillBoard []byte
var touches_X, touches_x bool
var komi float64
var n float64
i := 0
for {
index := bytes.Index(p.board[i+1:], []byte{'.'})
if index == -1 {
break
}
i += index + 1
fillBoard = floodfill(board, i)
// fillBoard is board with some continuous area of empty space replaced by #
touches_X = contact(fillBoard, 'X') != NONE
touches_x = contact(fillBoard, 'x') != NONE
if touches_X && !touches_x {
board = bytes.Replace(fillBoard, []byte{'#'}, []byte{'X'}, -1)
} else if touches_x && !touches_X {
board = bytes.Replace(fillBoard, []byte{'#'}, []byte{'x'}, -1)
} else {
board = bytes.Replace(fillBoard, []byte{'#'}, []byte{':'}, -1) // seki, rare
}
}
// now that area is replaced either by X, x or :
if p.n%2 == 1 {
komi = p.komi
} else {
komi = -p.komi
}
if len(owner_map) > 0 {
for c := 0; c < W*W; c++ {
if board[c] == 'X' {
n = 1
} else if board[c] == 'x' {
n = -1
} else {
n = 0
}
if p.n%2 == 1 {
n = -n
}
owner_map[c] += n
}
}
return float64(bytes.Count(board, []byte{'X'})-bytes.Count(board, []byte{'x'})) + komi
}
// Return an initial board position
func emptyPosition() Position {
var p Position
p.board = emptyBoard
p.cap = []int{0, 0}
p.n = 0
p.ko = NONE
p.last = NONE
p.last2 = NONE
p.komi = 7.5
return p
}
//##############
// go heuristics
// An atari/capture analysis routine that checks the group at c,
// determining whether (i) it is in atari (ii) if it can escape it,
// either by playing on its liberty or counter-capturing another group.
// N.B. this is maybe the most complicated part of the whole program (sadly);
// feel free to just TREAT IT AS A BLACK-BOX, it's not really that
// interesting!
// The return value is a tuple of (boolean, [coord..]), indicating whether
// the group is in atari and how to escape/capture (or [] if impossible).
// (Note that (False, [...]) is possible in case the group can be captured
// in a ladder - it is not in atari but some capture attack/defense moves
// are available.)
// singlePointOK means that we will not try to save one-point groups;
// twoLibertyTest means that we will check for 2-liberty groups which are
// threatened by a ladder
// twoLibertyTestAtEdgeOnly means that we will check the 2-liberty groups only
// at the board edge, allowing check of the most common short ladders
// even in the playouts
func fixAtari(pos Position, c int, singlePointOK, twoLibertyTest, twoLibertyTestAtEdgeOnly bool) (bool, []int) {
// check if a capturable ladder is being pulled out at c and return
// a move that continues it in that case; expects its two liberties as
// l1, l2 (in fact, this is a general 2-lib capture exhaustive solver)
readLadderAttack := func(pos Position, c, l1, l2 int) int {
for _, l := range []int{l1, l2} {
pos_l, pos_err := pos.move(l)
if pos_err != "ok" {
continue
}
// fixAtari() will recursively call readLadderAttack() back;
// however, ignore 2lib groups as we don't have time to chase them
isAtari, atariEscape := fixAtari(pos_l, c, false, false, false)
if isAtari && len(atariEscape) == 0 {
return l
}
}
return NONE
}
fillBoard := floodfill(pos.board, c)
groupSize := bytes.Count(fillBoard, []byte{'#'})
if singlePointOK && groupSize == 1 {
return false, []int{}
}
// Find a liberty
l := contact(fillBoard, '.')
// Ok, any other liberty?
fillBoard = boardPut(fillBoard, l, 'L')
l2 := contact(fillBoard, '.')
if l2 != NONE {
// At least two liberty group...
if twoLibertyTest && groupSize > 1 &&
(!twoLibertyTestAtEdgeOnly || lineHeight(l) == 0 && lineHeight(l2) == 0) &&
contact(boardPut(fillBoard, l2, 'L'), '.') == NONE {
// Exactly two liberty group with more than one stone. Check
// that it cannot be caught in a working ladder; if it can,
// that's as good as in atari, a capture threat.
// (Almost - N/A for countercaptures.)
ladderAttack := readLadderAttack(pos, c, l, l2)
if ladderAttack >= 0 {
return false, []int{ladderAttack}
}
}
return false, []int{}
}
// In atari! If it's the opponent's group, that's enough...
if pos.board[c] == 'x' {
return true, []int{l}
}
solutions := []int{}
// Before thinking about defense, what about counter-capturing
// a neighboring group?
counterCaptureBoard := fillBoard
for {
otherGroup := contact(counterCaptureBoard, 'x')
if otherGroup == NONE {
break
}
a, ccls := fixAtari(pos, otherGroup, false, false, false)
if a && len(ccls) > 0 {
solutions = append(solutions, ccls...)
}
// XXX: floodfill is better for big groups
counterCaptureBoard = boardPut(counterCaptureBoard, otherGroup, '%')
}
// We are escaping. Will playing our last liberty gain
// at least two liberties? Re-floodfill to account for connecting
escpos, escerr := pos.move(l)
if escerr != "ok" {
return true, solutions // oops, suicidal move
}
fillBoard = floodfill(escpos.board, l)
l_new := contact(fillBoard, '.')
fillBoard = boardPut(fillBoard, l_new, 'L')
l_new_2 := contact(fillBoard, '.')
if l_new_2 != NONE {
if len(solutions) > 0 ||
!(contact(boardPut(fillBoard, l_new_2, 'L'), '.') == NONE &&
readLadderAttack(escpos, l, l_new, l_new_2) != NONE) {
solutions = append(solutions, l)
}
}
return true, solutions
}
// return a board map listing common fate graph distances from
// a given point - this corresponds to the concept of locality while
// contracting groups to single points
func cfgDistance(board []byte, c int) []int {
cfg_map := []int{}
for i := 0; i < W*W; i++ {
cfg_map = append(cfg_map, NONE)
}
cfg_map[c] = 0
// flood-fill like mechanics
fringe := []int{c}
for len(fringe) > 0 {
c, fringe = fringe[len(fringe)-1], fringe[:len(fringe)-1]
for _, d := range neighbors(c) {
if isSpace(board[d]) ||
(0 <= cfg_map[d] && cfg_map[d] <= cfg_map[c]) {
continue
}
cfg_before := cfg_map[d]
if board[d] != '.' && board[d] == board[c] {
cfg_map[d] = cfg_map[c]
} else {
cfg_map[d] = cfg_map[c] + 1
}
if cfg_before < 0 || cfg_before > cfg_map[d] {
fringe = append(fringe, d)
}
}
}
return cfg_map
}
// Return the line number above nearest board edge
func lineHeight(c int) int {
row, col := (c-(W+1))/W, (c-(W+1))%W
minVal := row
for _, testVal := range []int{col, N - 1 - row, N - 1 - col} {
if testVal < minVal {
minVal = testVal
}
}
return minVal
}
// Check whether there are any stones in Manhattan distance up to dist
func emptyArea(board []byte, c, dist int) bool {
for d := range neighbors(c) {
if bytes.Contains([]byte{'X', 'x'}, []byte{board[d]}) {
return false
}
if board[d] == '.' && dist > 1 && !emptyArea(board, d, dist-1) {
return false
}
}
return true
}
// return a string containing the 9 points forming 3x3 square around
// certain move candidate
func neighborhood3x3(board []byte, c int) []byte {
localBoard := append([]byte{}, board[c-W-1:c-W+2]...)
localBoard = append(localBoard, board[c-1:c+2]...)
localBoard = append(localBoard, board[c+W-1:c+W+2]...)
return bytes.Replace(localBoard, []byte{'\n'}, []byte{' '}, -1)
}
// large-scale pattern routines (those patterns living in patterns.{spat,prob} files)
// are you curious how these patterns look in practice? get
// https://github.com/pasky/pachi/blob/master/tools/pattern_spatial_show.pl
// and try e.g. ./pattern_spatial_show.pl 71
var spatPatternDict map[int]uint64 // hash(neighborhoodGridcular()) <- spatial id
// load dictionary of positions, translating them to numeric ids
func loadSpatPatternDict(f *os.File) {
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
// line: 71 6 ..X.X..OO.O..........#X...... 33408f5e 188e9d3e 2166befe aa8ac9e 127e583e 1282462e 5e3d7fe 51fc9ee
if strings.HasPrefix(line, "#") {
continue
}
lineFields := strings.SplitN(line, " ", 4)
id, err := strconv.ParseInt(string(lineFields[0]), 10, 0)
if err != nil {
continue
}
neighborhood := strings.Replace(strings.Replace(lineFields[2], "#", " ", -1), "O", "x", -1)
spatPatternDict[int(id)] = xxhash.Checksum64([]byte(neighborhood))
}
}
var largePatterns map[uint64]float64 // hash(neighborhoodGridcular()) -> probability
// dictionary of numeric pattern ids, translating them to probabilities
// that a move matching such move will be played when it is available
func loadLargePatterns(f *os.File) {
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
// line: 0.004 14 3842 (capture:17 border:0 s:784)
lineFields := strings.SplitN(line, " ", 4)
prob, err := strconv.ParseFloat(lineFields[0], 64)
if err != nil {
continue
}
targetData := strings.SplitN(lineFields[3], "s:", 2)
if len(targetData) < 2 {
continue
}
dataStrings := strings.SplitN(targetData[1], ")", 2)
if dataStrings == nil {
continue
}
id, err := strconv.ParseInt(dataStrings[0], 10, 0)
if err != nil {
continue
}
patternHash, goodHash := spatPatternDict[int(id)]
if !goodHash {
continue
}
largePatterns[patternHash] = prob
}
}
// Yield progressively wider-diameter gridcular board neighborhood
// stone configuration strings, in all possible rotations
func neighborhoodGridcular(board []byte, c int, done chan struct{}) chan []byte {
ch := make(chan []byte)
go func() {
defer close(ch)
// Each rotations element is (xyindex, xymultiplier)
rotations := [][][]int{
{{0, 1}, {1, 1}},
{{0, 1}, {-1, 1}},
{{0, 1}, {1, -1}},
{{0, 1}, {-1, -1}},
{{1, 0}, {1, 1}},
{{1, 0}, {-1, 1}},
{{1, 0}, {1, -1}},
{{1, 0}, {-1, -1}},
}
neighborhood := [][]byte{}
for ri := 0; ri < len(rotations); ri++ {
neighborhood = append(neighborhood, []byte{})
}
wboard := bytes.Replace(board, []byte{'\n'}, []byte{' '}, -1)
for _, dseq := range patternGridcularSequence {
for ri := 0; ri < len(rotations); ri++ {
r := rotations[ri]
for _, o := range dseq {
y, x := (c-(W+1))/W, (c-(W+1))%W
y += o[r[0][0]] * r[1][0]
x += o[r[0][1]] * r[1][1]
if y >= 0 && y < N && x >= 0 && x < N {
si := (y+1)*W + x + 1
neighborhood[ri] = append(neighborhood[ri], wboard[si])
} else {
neighborhood[ri] = append(neighborhood[ri], byte(' '))
}
}
select {
case ch <- neighborhood[ri]:
case <-done:
return
}
}
}
// close(ch) deferred on entry to go func()
}()
return ch
}
// return probability of large-scale pattern at coordinate c.
// Multiple progressively wider patterns may match a single coordinate,
// we consider the largest one.
func largePatternProbability(board []byte, c int) float64 {
probability := float64(NONE)
matchedLength := 0
nonMatchedLength := 0
done := make(chan struct{})
for n := range neighborhoodGridcular(board, c, done) {
prob, good_prob := largePatterns[xxhash.Checksum64(n)]
if good_prob {
probability = prob
matchedLength = len(n)
continue
}
if matchedLength < nonMatchedLength && nonMatchedLength < len(n) {
// stop when we did not match any pattern with a certain
// diameter - it ain't going to get any better!
break
}
nonMatchedLength = len(n)
}
close(done)
return probability
}
//##########################
// montecarlo playout policy
// Yield candidate next moves in the order of preference; this is one
// of the main places where heuristics dwell, try adding more!
//
// heuristicSet is the set of coordinates considered for applying heuristics;
// this is the immediate neighborhood of last two moves in the playout, but
// the whole board while prioring the tree.
type Result struct {
intResult int
strResult string
}
func generatePlayoutMoves(pos Position, heuristicSet []int, probs map[string]float64, expensiveOK bool, done chan struct{}) chan Result {
ch := make(chan Result)
var r Result
go func() {
defer close(ch)
rng := newRNG()
// Check whether any local group is in atari and fill that liberty
if rng.Float64() <= probs["capture"] {
alreadySuggested := []int{}
for _, c := range heuristicSet {
if bytes.Contains([]byte{'X', 'x'}, []byte{pos.board[c]}) {
_, ds := fixAtari(pos, c, false, true, !(expensiveOK))
shuffleInt(ds, rng)
for _, d := range ds {
if !(intInSlice(alreadySuggested, d)) {
r.intResult = d
r.strResult = "capture " + strconv.FormatInt(int64(c), 10)
select {
case ch <- r:
case <-done:
return
}
alreadySuggested = append(alreadySuggested, d)
}
}
}
}
}
// Try to apply a 3x3 pattern on the local neighborhood
if rng.Float64() <= probs["pat3"] {
alreadySuggested := []int{}
for _, c := range heuristicSet {
if pos.board[c] == '.' && !(intInSlice(alreadySuggested, c)) && patternInSet(pat3set, neighborhood3x3(pos.board, c)) {
r.intResult = c
r.strResult = "pat3"
select {