playout/moggy.c: Repair whitespace damage
[pachi.git] / playout / moggy.c
bloba4908c713ffc62a01c486c1fc5c5b51eb2135c8a
1 /* Heuristical playout (and tree prior) policy modelled primarily after
2 * the description of the Mogo engine. */
4 #include <assert.h>
5 #include <math.h>
6 #include <stdio.h>
7 #include <stdlib.h>
9 #define DEBUG
10 #include "board.h"
11 #include "debug.h"
12 #include "joseki/base.h"
13 #include "mq.h"
14 #include "pattern3.h"
15 #include "patternprob.h"
16 #include "playout.h"
17 #include "playout/moggy.h"
18 #include "random.h"
19 #include "tactics/1lib.h"
20 #include "tactics/2lib.h"
21 #include "tactics/nlib.h"
22 #include "tactics/ladder.h"
23 #include "tactics/nakade.h"
24 #include "tactics/selfatari.h"
25 #include "uct/prior.h"
27 #define PLDEBUGL(n) DEBUGL_(p->debug_level, n)
30 /* In case "seqchoose" move picker is enabled (i.e. no "fullchoose"
31 * parameter passed), we stochastically apply fixed set of decision
32 * rules in given order.
34 * In "fullchoose" mode, we instead build a move queue of variously
35 * tagged candidates, then consider a probability distribution over
36 * them and pick a move from that. */
38 /* Move queue tags. Some may be even undesirable - these moves then
39 * receive a penalty; penalty tags should be used only when it is
40 * certain the move would be considered anyway. */
41 enum mq_tag {
42 MQ_KO = 0,
43 MQ_LATARI,
44 MQ_L2LIB,
45 #define MQ_LADDER MQ_L2LIB /* XXX: We want to fit in char still! */
46 MQ_LNLIB,
47 MQ_PAT3,
48 MQ_GATARI,
49 MQ_JOSEKI,
50 MQ_NAKADE,
51 MQ_MAX
55 /* Note that the context can be shared by multiple threads! */
57 struct moggy_policy {
58 unsigned int lcapturerate, atarirate, nlibrate, ladderrate, capturerate, patternrate, korate, josekirate, nakaderate;
59 unsigned int selfatarirate, eyefillrate, alwaysccaprate;
60 unsigned int fillboardtries;
61 int koage;
62 /* Whether to look for patterns around second-to-last move. */
63 bool pattern2;
64 /* Whether, when self-atari attempt is detected, to play the other
65 * group's liberty if that is non-self-atari. */
66 bool selfatari_other;
68 /* Large pattern settings. */
69 /* Use large patterns locally inst. of 3x3 patterns. */
70 bool local_lpattern;
72 /* 1lib settings: */
73 /* Whether to always pick from moves capturing all groups in
74 * global_atari_check(). */
75 bool capcheckall;
76 /* Prior stone weighting. Weight of each stone between
77 * cap_stone_min and cap_stone_max is (assess*100)/cap_stone_denom. */
78 int cap_stone_min, cap_stone_max;
79 int cap_stone_denom;
81 /* 2lib settings: */
82 bool atari_def_no_hopeless;
83 bool atari_miaisafe;
85 /* nlib settings: */
86 int nlib_count;
88 struct joseki_dict *jdict;
89 struct pattern3s patterns;
91 /* Gamma values for queue tags - correspond to probabilities. */
92 /* XXX: Tune. */
93 double mq_prob[MQ_MAX], tenuki_prob;
97 static char moggy_patterns_src[][11] = {
98 /* hane pattern - enclosing hane */
99 "XOX"
100 "..."
101 "???",
102 /* hane pattern - non-cutting hane */
103 "YO."
104 "..."
105 "?.?",
106 /* hane pattern - magari */
107 "XO?"
108 "X.."
109 "x.?",
110 /* hane pattern - thin hane */
111 "XOO"
112 "..."
113 "?.?" "X",
114 /* generic pattern - katatsuke or diagonal attachment; similar to magari */
115 ".Q."
116 "Y.."
117 "...",
118 /* cut1 pattern (kiri) - unprotected cut */
119 "XO?"
120 "O.o"
121 "?o?",
122 /* cut1 pattern (kiri) - peeped cut */
123 "XO?"
124 "O.X"
125 "???",
126 /* cut2 pattern (de) */
127 "?X?"
128 "O.O"
129 "ooo",
130 /* cut keima (not in Mogo) */
131 "OX?"
132 "o.O"
133 "???", /* o?? has some pathological tsumego cases */
134 /* side pattern - chase */
135 "X.?"
136 "O.?"
137 "##?",
138 /* side pattern - block side cut */
139 "OX?"
140 "X.O"
141 "###",
142 /* side pattern - block side connection */
143 "?X?"
144 "x.O"
145 "###",
146 /* side pattern - sagari (SUSPICIOUS) */
147 "?XQ"
148 "x.x" /* Mogo has "x.?" */
149 "###" /* Mogo has "X" */,
150 /* side pattern - throw-in (SUSPICIOUS) */
151 #if 0
152 "?OX"
153 "o.O"
154 "?##" "X",
155 #endif
156 /* side pattern - cut (SUSPICIOUS) */
157 "?OY"
158 "Y.O"
159 "###" /* Mogo has "X" */,
160 /* side pattern - eye piercing:
161 * # O O O .
162 * # O . O .
163 * # . . . .
164 * # # # # # */
165 /* side pattern - make eye */
166 "?X."
167 "Q.X"
168 "###",
169 #if 0
170 "Oxx"
171 "..."
172 "###",
173 #endif
175 #define moggy_patterns_src_n sizeof(moggy_patterns_src) / sizeof(moggy_patterns_src[0])
177 static inline bool
178 test_pattern3_here(struct playout_policy *p, struct board *b, struct move *m)
180 struct moggy_policy *pp = p->data;
181 /* Check if 3x3 pattern is matched by given move... */
182 if (!pattern3_move_here(&pp->patterns, b, m))
183 return false;
184 /* ...and the move is not obviously stupid. */
185 if (is_bad_selfatari(b, m->color, m->coord))
186 return false;
187 /* Ladder moves are stupid. */
188 group_t atari_neighbor = board_get_atari_neighbor(b, m->coord, m->color);
189 if (atari_neighbor && is_ladder(b, m->coord, atari_neighbor)
190 && !can_countercapture(b, board_at(b, group_base(atari_neighbor)),
191 atari_neighbor, m->color, NULL, 0))
192 return false;
193 return true;
196 static void
197 apply_pattern_here(struct playout_policy *p, struct board *b, coord_t c, enum stone color, struct move_queue *q)
199 struct move m2 = { .coord = c, .color = color };
200 if (board_is_valid_move(b, &m2) && test_pattern3_here(p, b, &m2))
201 mq_add(q, c, 1<<MQ_PAT3);
204 /* Check if we match any pattern around given move (with the other color to play). */
205 static void
206 apply_pattern(struct playout_policy *p, struct board *b, struct move *m, struct move *mm, struct move_queue *q)
208 /* Suicides do not make any patterns and confuse us. */
209 if (board_at(b, m->coord) == S_NONE || board_at(b, m->coord) == S_OFFBOARD)
210 return;
212 foreach_8neighbor(b, m->coord) {
213 apply_pattern_here(p, b, c, stone_other(m->color), q);
214 } foreach_8neighbor_end;
216 if (mm) { /* Second move for pattern searching */
217 foreach_8neighbor(b, mm->coord) {
218 if (coord_is_8adjecent(m->coord, c, b))
219 continue;
220 apply_pattern_here(p, b, c, stone_other(m->color), q);
221 } foreach_8neighbor_end;
224 if (PLDEBUGL(5))
225 mq_print(q, b, "Pattern");
228 /* Check if we match any large pattern around given move (with the other color to play). */
229 static void
230 apply_lpattern(struct playout_policy *p, struct board *b, struct move *m, struct move *mm, struct move_queue *q)
232 struct moggy_policy *pp = p->data;
233 if (!p->pat || !p->pat->pd)
234 return;
236 /* Suicides do not make any patterns and confuse us. */
237 if (board_at(b, m->coord) == S_NONE || board_at(b, m->coord) == S_OFFBOARD)
238 return;
240 struct move_queue pq; pq.moves = 0;
241 foreach_8neighbor(b, m->coord) {
242 if (board_at(b, c) == S_NONE)
243 mq_add(&pq, c, 0);
244 } foreach_8neighbor_end;
246 if (mm) { /* Second move for pattern searching */
247 foreach_8neighbor(b, mm->coord) {
248 if (coord_is_8adjecent(m->coord, c, b))
249 continue;
250 if (board_at(b, c) == S_NONE)
251 mq_add(&pq, c, 0);
252 } foreach_8neighbor_end;
255 struct pattern pats[pq.moves];
256 floating_t probs[pq.moves];
257 floating_t total = pattern_rate_some_moves(p->pat, b, stone_other(m->color), pq.move, pq.moves, pats, probs);
258 if (PLDEBUGL(5)) fprintf(stderr, "Pattern moves: ");
259 for (unsigned int i = 0; i < pq.moves; i++) {
260 if (PLDEBUGL(5)) fprintf(stderr, "%s(%.3f) ", coord2sstr(pq.move[i], b), probs[i]/total);
262 if (PLDEBUGL(5)) fprintf(stderr, "\n");
263 total += pp->tenuki_prob;
265 floating_t stab = fast_frandom() * total;
266 for (unsigned int i = 0; i < pq.moves; i++) {
267 if (isnan(probs[i]))
268 continue;
269 stab -= probs[i];
270 if (stab < 0) {
271 mq_add(q, pq.move[i], 1<<MQ_PAT3);
272 return;
278 static void
279 joseki_check(struct playout_policy *p, struct board *b, enum stone to_play, struct move_queue *q)
281 struct moggy_policy *pp = p->data;
282 if (!pp->jdict)
283 return;
285 for (int i = 0; i < 4; i++) {
286 hash_t h = b->qhash[i] & joseki_hash_mask;
287 coord_t *cc = pp->jdict->patterns[h].moves[to_play];
288 if (!cc) continue;
289 for (; !is_pass(*cc); cc++) {
290 if (coord_quadrant(*cc, b) != i)
291 continue;
292 mq_add(q, *cc, 1<<MQ_JOSEKI);
296 if (q->moves > 0 && PLDEBUGL(5))
297 mq_print(q, b, "Joseki");
300 static void
301 global_atari_check(struct playout_policy *p, struct board *b, enum stone to_play, struct move_queue *q)
303 if (b->clen == 0)
304 return;
306 struct moggy_policy *pp = p->data;
307 if (pp->capcheckall) {
308 for (int g = 0; g < b->clen; g++)
309 group_atari_check(pp->alwaysccaprate, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, 1<<MQ_GATARI);
310 if (PLDEBUGL(5))
311 mq_print(q, b, "Global atari");
312 return;
315 int g_base = fast_random(b->clen);
316 for (int g = g_base; g < b->clen; g++) {
317 group_atari_check(pp->alwaysccaprate, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, 1<<MQ_GATARI);
318 if (q->moves > 0) {
319 /* XXX: Try carrying on. */
320 if (PLDEBUGL(5))
321 mq_print(q, b, "Global atari");
322 return;
325 for (int g = 0; g < g_base; g++) {
326 group_atari_check(pp->alwaysccaprate, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, 1<<MQ_GATARI);
327 if (q->moves > 0) {
328 /* XXX: Try carrying on. */
329 if (PLDEBUGL(5))
330 mq_print(q, b, "Global atari");
331 return;
334 return;
337 static void
338 local_atari_check(struct playout_policy *p, struct board *b, struct move *m, struct move_queue *q)
340 struct moggy_policy *pp = p->data;
342 /* Did the opponent play a self-atari? */
343 if (board_group_info(b, group_at(b, m->coord)).libs == 1) {
344 group_atari_check(pp->alwaysccaprate, b, group_at(b, m->coord), stone_other(m->color), q, NULL, 1<<MQ_LATARI);
347 foreach_neighbor(b, m->coord, {
348 group_t g = group_at(b, c);
349 if (!g || board_group_info(b, g).libs != 1)
350 continue;
351 group_atari_check(pp->alwaysccaprate, b, g, stone_other(m->color), q, NULL, 1<<MQ_LATARI);
354 if (PLDEBUGL(5))
355 mq_print(q, b, "Local atari");
359 static void
360 local_ladder_check(struct playout_policy *p, struct board *b, struct move *m, struct move_queue *q)
362 group_t group = group_at(b, m->coord);
364 if (board_group_info(b, group).libs != 2)
365 return;
367 for (int i = 0; i < 2; i++) {
368 coord_t chase = board_group_info(b, group).lib[i];
369 coord_t escape = board_group_info(b, group).lib[1 - i];
370 if (wouldbe_ladder(b, escape, chase, board_at(b, group)))
371 mq_add(q, chase, 1<<MQ_LADDER);
374 if (q->moves > 0 && PLDEBUGL(5))
375 mq_print(q, b, "Ladder");
379 static void
380 local_2lib_check(struct playout_policy *p, struct board *b, struct move *m, struct move_queue *q)
382 struct moggy_policy *pp = p->data;
383 group_t group = group_at(b, m->coord), group2 = 0;
385 /* Does the opponent have just two liberties? */
386 if (board_group_info(b, group).libs == 2) {
387 group_2lib_check(b, group, stone_other(m->color), q, 1<<MQ_L2LIB, pp->atari_miaisafe, pp->atari_def_no_hopeless);
388 #if 0
389 /* We always prefer to take off an enemy chain liberty
390 * before pulling out ourselves. */
391 /* XXX: We aren't guaranteed to return to that group
392 * later. */
393 if (q->moves)
394 return q->move[fast_random(q->moves)];
395 #endif
398 /* Then he took a third liberty from neighboring chain? */
399 foreach_neighbor(b, m->coord, {
400 group_t g = group_at(b, c);
401 if (!g || g == group || g == group2 || board_group_info(b, g).libs != 2)
402 continue;
403 group_2lib_check(b, g, stone_other(m->color), q, 1<<MQ_L2LIB, pp->atari_miaisafe, pp->atari_def_no_hopeless);
404 group2 = g; // prevent trivial repeated checks
407 if (PLDEBUGL(5))
408 mq_print(q, b, "Local 2lib");
411 static void
412 local_nlib_check(struct playout_policy *p, struct board *b, struct move *m, struct move_queue *q)
414 struct moggy_policy *pp = p->data;
415 enum stone color = stone_other(m->color);
417 /* Attacking N-liberty groups in general is probably
418 * not feasible. What we are primarily concerned about is
419 * counter-attacking groups that have two physical liberties,
420 * but three effective liberties:
422 * . O . . . . #
423 * O O X X X X #
424 * . X O O X . #
425 * . X O . O X #
426 * . X O O . X #
427 * # # # # # # #
429 * The time for this to come is when the opponent took a liberty
430 * of ours, making a few-liberty group. Therefore, we focus
431 * purely on defense.
433 * There is a tradeoff - down to how many liberties we need to
434 * be to start looking? nlib_count=3 will work for the left black
435 * group (2lib-solver will suggest connecting the false eye), but
436 * not for top black group (it is too late to start playing 3-3
437 * capturing race). Also, we cannot prevent stupidly taking an
438 * outside liberty ourselves; the higher nlib_count, the higher
439 * the chance we withstand this.
441 * However, higher nlib_count means that we will waste more time
442 * checking non-urgent or alive groups, and we will play silly
443 * or wasted moves around alive groups. */
445 group_t group2 = 0;
446 foreach_8neighbor(b, m->coord) {
447 group_t g = group_at(b, c);
448 if (!g || group2 == g || board_at(b, c) != color)
449 continue;
450 if (board_group_info(b, g).libs < 3 || board_group_info(b, g).libs > pp->nlib_count)
451 continue;
452 group_nlib_defense_check(b, g, color, q, 1<<MQ_LNLIB);
453 group2 = g; // prevent trivial repeated checks
454 } foreach_8neighbor_end;
456 if (PLDEBUGL(5))
457 mq_print(q, b, "Local nlib");
460 static coord_t
461 nakade_check(struct playout_policy *p, struct board *b, struct move *m, enum stone to_play)
463 coord_t empty = pass;
464 foreach_neighbor(b, m->coord, {
465 if (board_at(b, c) != S_NONE)
466 continue;
467 if (is_pass(empty)) {
468 empty = c;
469 continue;
471 if (!coord_is_8adjecent(c, empty, b)) {
472 /* Seems like impossible nakade
473 * shape! */
474 return pass;
477 assert(!is_pass(empty));
479 coord_t nakade = nakade_point(b, empty, stone_other(to_play));
480 if (PLDEBUGL(5) && !is_pass(nakade))
481 fprintf(stderr, "Nakade: %s\n", coord2sstr(nakade, b));
482 return nakade;
485 coord_t
486 fillboard_check(struct playout_policy *p, struct board *b)
488 struct moggy_policy *pp = p->data;
489 unsigned int fbtries = b->flen / 8;
490 if (pp->fillboardtries < fbtries)
491 fbtries = pp->fillboardtries;
493 for (unsigned int i = 0; i < fbtries; i++) {
494 coord_t coord = b->f[fast_random(b->flen)];
495 if (immediate_liberty_count(b, coord) != 4)
496 continue;
497 foreach_diag_neighbor(b, coord) {
498 if (board_at(b, c) != S_NONE)
499 goto next_try;
500 } foreach_diag_neighbor_end;
501 return coord;
502 next_try:
505 return pass;
508 coord_t
509 playout_moggy_seqchoose(struct playout_policy *p, struct playout_setup *s, struct playout_amafmap *amafmap, struct board *b, enum stone to_play)
511 struct moggy_policy *pp = p->data;
513 if (PLDEBUGL(5))
514 board_print(b, stderr);
516 /* Ko fight check */
517 if (!is_pass(b->last_ko.coord) && is_pass(b->ko.coord)
518 && b->moves - b->last_ko_age < pp->koage
519 && pp->korate > fast_random(100)) {
520 if (board_is_valid_play(b, to_play, b->last_ko.coord)
521 && !is_bad_selfatari(b, to_play, b->last_ko.coord))
522 return b->last_ko.coord;
525 /* Local checks */
526 if (!is_pass(b->last_move.coord)) {
527 /* Nakade check */
528 if (pp->nakaderate > fast_random(100)
529 && immediate_liberty_count(b, b->last_move.coord) > 0) {
530 coord_t nakade = nakade_check(p, b, &b->last_move, to_play);
531 if (!is_pass(nakade))
532 return nakade;
535 /* Local group in atari? */
536 if (pp->lcapturerate > fast_random(100)) {
537 struct move_queue q; q.moves = 0;
538 local_atari_check(p, b, &b->last_move, &q);
539 if (q.moves > 0)
540 return mq_pick(&q);
543 /* Local group trying to escape ladder? */
544 if (pp->ladderrate > fast_random(100)) {
545 struct move_queue q; q.moves = 0;
546 local_ladder_check(p, b, &b->last_move, &q);
547 if (q.moves > 0)
548 return mq_pick(&q);
551 /* Local group can be PUT in atari? */
552 if (pp->atarirate > fast_random(100)) {
553 struct move_queue q; q.moves = 0;
554 local_2lib_check(p, b, &b->last_move, &q);
555 if (q.moves > 0)
556 return mq_pick(&q);
559 /* Local group reduced some of our groups to 3 libs? */
560 if (pp->nlibrate > fast_random(100)) {
561 struct move_queue q; q.moves = 0;
562 local_nlib_check(p, b, &b->last_move, &q);
563 if (q.moves > 0)
564 return mq_pick(&q);
567 /* Check for patterns we know */
568 if (pp->patternrate > fast_random(100)) {
569 struct move_queue q; q.moves = 0;
570 if (pp->local_lpattern) {
571 apply_lpattern(p, b, &b->last_move, pp->pattern2 && b->last_move2.coord >= 0 ? &b->last_move2 : NULL, &q);
572 } else {
573 apply_pattern(p, b, &b->last_move,
574 pp->pattern2 && b->last_move2.coord >= 0 ? &b->last_move2 : NULL,
575 &q);
577 if (q.moves > 0)
578 return mq_pick(&q);
582 /* Global checks */
584 /* Any groups in atari? */
585 if (pp->capturerate > fast_random(100)) {
586 struct move_queue q; q.moves = 0;
587 global_atari_check(p, b, to_play, &q);
588 if (q.moves > 0)
589 return mq_pick(&q);
592 /* Joseki moves? */
593 if (pp->josekirate > fast_random(100)) {
594 struct move_queue q; q.moves = 0;
595 joseki_check(p, b, to_play, &q);
596 if (q.moves > 0)
597 return mq_pick(&q);
600 /* Fill board */
601 if (pp->fillboardtries > 0) {
602 coord_t c = fillboard_check(p, b);
603 if (!is_pass(c))
604 return c;
607 return pass;
610 /* Pick a move from queue q, giving different likelihoods to moves
611 * based on their tags. */
612 coord_t
613 mq_tagged_choose(struct playout_policy *p, struct board *b, enum stone to_play, struct move_queue *q)
615 struct moggy_policy *pp = p->data;
617 /* First, merge all entries for a move. */
618 /* We use a naive O(N^2) since the average length of the queue
619 * is about 1.4. */
620 for (unsigned int i = 0; i < q->moves; i++) {
621 for (unsigned int j = i + 1; j < q->moves; j++) {
622 if (q->move[i] != q->move[j])
623 continue;
624 q->tag[i] |= q->tag[j];
625 q->moves--;
626 q->tag[j] = q->tag[q->moves];
627 q->move[j] = q->move[q->moves];
631 /* Now, construct a probdist. */
632 fixp_t total = 0;
633 fixp_t pd[q->moves];
634 for (unsigned int i = 0; i < q->moves; i++) {
635 double val = 1.0;
636 assert(q->tag[i] != 0);
637 for (int j = 0; j < MQ_MAX; j++)
638 if (q->tag[i] & (1<<j)) {
639 //fprintf(stderr, "%s(%x) %d %f *= %f\n", coord2sstr(q->move[i], b), q->tag[i], j, val, pp->mq_prob[j]);
640 val *= pp->mq_prob[j];
642 pd[i] = double_to_fixp(val);
643 total += pd[i];
645 total += double_to_fixp(pp->tenuki_prob);
647 /* Finally, pick a move! */
648 fixp_t stab = fast_irandom(total);
649 for (unsigned int i = 0; i < q->moves; i++) {
650 //fprintf(stderr, "%s(%x) %f (%f/%f)\n", coord2sstr(q->move[i], b), q->tag[i], fixp_to_double(stab), fixp_to_double(pd[i]), fixp_to_double(total));
651 if (stab < pd[i])
652 return q->move[i];
653 stab -= pd[i];
656 /* Tenuki. */
657 assert(stab < double_to_fixp(pp->tenuki_prob));
658 return pass;
661 coord_t
662 playout_moggy_fullchoose(struct playout_policy *p, struct playout_setup *s, struct playout_amafmap *amafmap, struct board *b, enum stone to_play)
664 struct moggy_policy *pp = p->data;
665 struct move_queue q; q.moves = 0;
667 if (PLDEBUGL(5))
668 board_print(b, stderr);
670 /* Ko fight check */
671 if (!is_pass(b->last_ko.coord) && is_pass(b->ko.coord)
672 && b->moves - b->last_ko_age < pp->koage) {
673 if (board_is_valid_play(b, to_play, b->last_ko.coord)
674 && !is_bad_selfatari(b, to_play, b->last_ko.coord))
675 mq_add(&q, b->last_ko.coord, 1<<MQ_KO);
678 /* Local checks */
679 if (!is_pass(b->last_move.coord)) {
680 /* Nakade check */
681 if (immediate_liberty_count(b, b->last_move.coord) > 0) {
682 coord_t nakade = nakade_check(p, b, &b->last_move, to_play);
683 if (!is_pass(nakade))
684 mq_add(&q, nakade, 1<<MQ_NAKADE);
687 /* Local group in atari? */
688 local_atari_check(p, b, &b->last_move, &q);
690 /* Local group trying to escape ladder? */
691 local_ladder_check(p, b, &b->last_move, &q);
693 /* Local group can be PUT in atari? */
694 local_2lib_check(p, b, &b->last_move, &q);
696 /* Local group reduced some of our groups to 3 libs? */
697 local_nlib_check(p, b, &b->last_move, &q);
699 /* Check for patterns we know */
700 apply_pattern(p, b, &b->last_move,
701 pp->pattern2 && b->last_move2.coord >= 0 ? &b->last_move2 : NULL,
702 &q);
705 /* Global checks */
707 /* Any groups in atari? */
708 global_atari_check(p, b, to_play, &q);
710 /* Joseki moves? */
711 joseki_check(p, b, to_play, &q);
713 #if 0
714 /* Average length of the queue is 1.4 move. */
715 printf("MQL %d ", q.moves);
716 for (unsigned int i = 0; i < q.moves; i++)
717 printf("%s ", coord2sstr(q.move[i], b));
718 printf("\n");
719 #endif
721 if (q.moves > 0)
722 return mq_tagged_choose(p, b, to_play, &q);
724 /* Fill board */
725 if (pp->fillboardtries > 0) {
726 coord_t c = fillboard_check(p, b);
727 if (!is_pass(c))
728 return c;
731 return pass;
735 void
736 playout_moggy_assess_group(struct playout_policy *p, struct prior_map *map, group_t g, int games)
738 struct moggy_policy *pp = p->data;
739 struct board *b = map->b;
740 struct move_queue q; q.moves = 0;
742 if (board_group_info(b, g).libs > pp->nlib_count)
743 return;
745 if (PLDEBUGL(5)) {
746 fprintf(stderr, "ASSESS of group %s:\n", coord2sstr(g, b));
747 board_print(b, stderr);
750 if (board_group_info(b, g).libs > 2) {
751 if (!pp->nlibrate)
752 return;
753 if (board_at(b, g) != map->to_play)
754 return; // we do only defense
755 group_nlib_defense_check(b, g, map->to_play, &q, 0);
756 while (q.moves--) {
757 coord_t coord = q.move[q.moves];
758 if (PLDEBUGL(5))
759 fprintf(stderr, "1.0: nlib %s\n", coord2sstr(coord, b));
760 int assess = games / 2;
761 add_prior_value(map, coord, 1, assess);
763 return;
766 if (board_group_info(b, g).libs == 2) {
767 if (pp->ladderrate) {
768 /* Make sure to play the correct liberty in case
769 * this is a group that can be caught in a ladder. */
770 bool ladderable = false;
771 for (int i = 0; i < 2; i++) {
772 coord_t chase = board_group_info(b, g).lib[i];
773 coord_t escape = board_group_info(b, g).lib[1 - i];
774 if (wouldbe_ladder(b, escape, chase, board_at(b, g))) {
775 add_prior_value(map, chase, 1, games);
776 ladderable = true;
779 if (ladderable)
780 return; // do not suggest the other lib at all
783 if (!pp->atarirate)
784 return;
785 group_2lib_check(b, g, map->to_play, &q, 0, pp->atari_miaisafe, pp->atari_def_no_hopeless);
786 while (q.moves--) {
787 coord_t coord = q.move[q.moves];
788 if (PLDEBUGL(5))
789 fprintf(stderr, "1.0: 2lib %s\n", coord2sstr(coord, b));
790 int assess = games / 2;
791 add_prior_value(map, coord, 1, assess);
793 return;
796 /* This group, sir, is in atari! */
798 coord_t ladder = pass;
799 group_atari_check(pp->alwaysccaprate, b, g, map->to_play, &q, &ladder, 0);
800 while (q.moves--) {
801 coord_t coord = q.move[q.moves];
803 /* _Never_ play here if this move plays out
804 * a caught ladder. */
805 if (coord == ladder && !board_playing_ko_threat(b)) {
806 /* Note that the opposite is not guarded against;
807 * we do not advise against capturing a laddered
808 * group (but we don't encourage it either). Such
809 * a move can simplify tactical situations if we
810 * can afford it. */
811 if (map->to_play != board_at(b, g))
812 continue;
813 /* FIXME: We give the malus even if this move
814 * captures another group. */
815 if (PLDEBUGL(5))
816 fprintf(stderr, "0.0: ladder %s\n", coord2sstr(coord, b));
817 add_prior_value(map, coord, 0, games);
818 continue;
821 if (!pp->capturerate && !pp->lcapturerate)
822 continue;
824 int assess = games * 2;
825 if (pp->cap_stone_denom > 0) {
826 int stones = group_stone_count(b, g, pp->cap_stone_max) - (pp->cap_stone_min-1);
827 assess += (stones > 0 ? stones : 0) * games * 100 / pp->cap_stone_denom;
829 if (PLDEBUGL(5))
830 fprintf(stderr, "1.0 (%d): atari %s\n", assess, coord2sstr(coord, b));
831 add_prior_value(map, coord, 1, assess);
835 void
836 playout_moggy_assess_one(struct playout_policy *p, struct prior_map *map, coord_t coord, int games)
838 struct moggy_policy *pp = p->data;
839 struct board *b = map->b;
841 if (PLDEBUGL(5)) {
842 fprintf(stderr, "ASSESS of move %s:\n", coord2sstr(coord, b));
843 board_print(b, stderr);
846 /* Is this move a self-atari? */
847 if (pp->selfatarirate) {
848 if (!board_playing_ko_threat(b) && is_bad_selfatari(b, map->to_play, coord)) {
849 if (PLDEBUGL(5))
850 fprintf(stderr, "0.0: self-atari\n");
851 add_prior_value(map, coord, 0, games);
852 if (!pp->selfatari_other)
853 return;
854 /* If we can play on the other liberty of the
855 * endangered group, do! */
856 coord = selfatari_cousin(b, map->to_play, coord, NULL);
857 if (is_pass(coord))
858 return;
859 if (PLDEBUGL(5))
860 fprintf(stderr, "1.0: self-atari redirect %s\n", coord2sstr(coord, b));
861 add_prior_value(map, coord, 1.0, games);
862 return;
866 /* Pattern check */
867 if (pp->patternrate) {
868 struct move m = { .color = map->to_play, .coord = coord };
869 if (test_pattern3_here(p, b, &m)) {
870 if (PLDEBUGL(5))
871 fprintf(stderr, "1.0: pattern\n");
872 add_prior_value(map, coord, 1, games);
876 return;
879 void
880 playout_moggy_assess(struct playout_policy *p, struct prior_map *map, int games)
882 struct moggy_policy *pp = p->data;
884 /* First, go through all endangered groups. */
885 for (group_t g = 1; g < board_size2(map->b); g++)
886 if (group_at(map->b, g) == g)
887 playout_moggy_assess_group(p, map, g, games);
889 /* Then, assess individual moves. */
890 if (!pp->patternrate && !pp->selfatarirate)
891 return;
892 foreach_free_point(map->b) {
893 if (map->consider[c])
894 playout_moggy_assess_one(p, map, c, games);
895 } foreach_free_point_end;
898 bool
899 playout_moggy_permit(struct playout_policy *p, struct board *b, struct move *m)
901 struct moggy_policy *pp = p->data;
903 /* The idea is simple for now - never allow self-atari moves.
904 * They suck in general, but this also permits us to actually
905 * handle seki in the playout stage. */
907 if (fast_random(100) >= pp->selfatarirate) {
908 if (PLDEBUGL(5))
909 fprintf(stderr, "skipping sar test\n");
910 goto sar_skip;
912 bool selfatari = is_bad_selfatari(b, m->color, m->coord);
913 if (selfatari) {
914 if (PLDEBUGL(5))
915 fprintf(stderr, "__ Prohibiting self-atari %s %s\n",
916 stone2str(m->color), coord2sstr(m->coord, b));
917 if (pp->selfatari_other) {
918 /* Ok, try the other liberty of the atari'd group. */
919 coord_t c = selfatari_cousin(b, m->color, m->coord, NULL);
920 if (is_pass(c)) return false;
921 if (PLDEBUGL(5))
922 fprintf(stderr, "___ Redirecting to other lib %s\n",
923 coord2sstr(c, b));
924 m->coord = c;
925 return true;
927 return false;
929 sar_skip:
931 /* Check if we don't seem to be filling our eye. This should
932 * happen only for false eyes, but some of them are in fact
933 * real eyes with diagonal filled by a dead stone. Prefer
934 * to counter-capture in that case. */
935 if (fast_random(100) >= pp->eyefillrate) {
936 if (PLDEBUGL(5))
937 fprintf(stderr, "skipping eyefill test\n");
938 goto eyefill_skip;
940 bool eyefill = board_is_eyelike(b, m->coord, m->color);
941 if (eyefill) {
942 foreach_diag_neighbor(b, m->coord) {
943 if (board_at(b, c) != stone_other(m->color))
944 continue;
945 switch (board_group_info(b, group_at(b, c)).libs) {
946 case 1: /* Capture! */
947 c = board_group_info(b, group_at(b, c)).lib[0];
948 if (PLDEBUGL(5))
949 fprintf(stderr, "___ Redirecting to capture %s\n",
950 coord2sstr(c, b));
951 m->coord = c;
952 return true;
953 case 2: /* Try to switch to some 2-lib neighbor. */
954 for (int i = 0; i < 2; i++) {
955 coord_t l = board_group_info(b, group_at(b, c)).lib[i];
956 if (board_is_one_point_eye(b, l, board_at(b, c)))
957 continue;
958 if (is_bad_selfatari(b, m->color, l))
959 continue;
960 m->coord = l;
961 return true;
963 break;
965 } foreach_diag_neighbor_end;
968 eyefill_skip:
969 return true;
973 struct playout_policy *
974 playout_moggy_init(char *arg, struct board *b, struct joseki_dict *jdict)
976 struct playout_policy *p = calloc2(1, sizeof(*p));
977 struct moggy_policy *pp = calloc2(1, sizeof(*pp));
978 p->data = pp;
979 p->choose = playout_moggy_seqchoose;
980 p->assess = playout_moggy_assess;
981 p->permit = playout_moggy_permit;
983 pp->jdict = jdict;
985 /* These settings are tuned for 19x19 play with several threads
986 * on reasonable time limits (i.e., rather large number of playouts).
987 * XXX: no 9x9 tuning has been done recently. */
988 int rate = board_large(b) ? 80 : 90;
990 pp->lcapturerate = pp->atarirate = pp->nlibrate = pp->patternrate
991 = pp->selfatarirate = pp->eyefillrate = pp->josekirate = pp->ladderrate = -1U;
992 if (board_large(b)) {
993 pp->lcapturerate = 90;
994 pp->patternrate = 100;
995 pp->nlibrate = 20;
996 pp->nakaderate = 20;
997 pp->pattern2 = true;
999 pp->korate = 20; pp->koage = 4;
1000 pp->alwaysccaprate = 20;
1001 pp->selfatari_other = true;
1003 pp->cap_stone_min = 2;
1004 pp->cap_stone_max = 15;
1005 pp->cap_stone_denom = 200;
1007 pp->atari_def_no_hopeless = !board_large(b);
1008 pp->atari_miaisafe = true;
1009 pp->nlib_count = 4;
1011 /* C is stupid. */
1012 double mq_prob_default[MQ_MAX] = {
1013 [MQ_KO] = 6.0,
1014 [MQ_NAKADE] = 5.5,
1015 [MQ_LATARI] = 5.0,
1016 [MQ_L2LIB] = 4.0,
1017 [MQ_LNLIB] = 3.5,
1018 [MQ_PAT3] = 3.0,
1019 [MQ_GATARI] = 2.0,
1020 [MQ_JOSEKI] = 1.0,
1022 memcpy(pp->mq_prob, mq_prob_default, sizeof(pp->mq_prob));
1024 if (arg) {
1025 char *optspec, *next = arg;
1026 while (*next) {
1027 optspec = next;
1028 next += strcspn(next, ":");
1029 if (*next) { *next++ = 0; } else { *next = 0; }
1031 char *optname = optspec;
1032 char *optval = strchr(optspec, '=');
1033 if (optval) *optval++ = 0;
1035 if (!strcasecmp(optname, "debug") && optval) {
1036 p->debug_level = atoi(optval);
1037 } else if (!strcasecmp(optname, "lcapturerate") && optval) {
1038 pp->lcapturerate = atoi(optval);
1039 } else if (!strcasecmp(optname, "ladderrate") && optval) {
1040 pp->ladderrate = atoi(optval);
1041 } else if (!strcasecmp(optname, "atarirate") && optval) {
1042 pp->atarirate = atoi(optval);
1043 } else if (!strcasecmp(optname, "nlibrate") && optval) {
1044 pp->nlibrate = atoi(optval);
1045 } else if (!strcasecmp(optname, "capturerate") && optval) {
1046 pp->capturerate = atoi(optval);
1047 } else if (!strcasecmp(optname, "patternrate") && optval) {
1048 pp->patternrate = atoi(optval);
1049 } else if (!strcasecmp(optname, "selfatarirate") && optval) {
1050 pp->selfatarirate = atoi(optval);
1051 } else if (!strcasecmp(optname, "eyefillrate") && optval) {
1052 pp->eyefillrate = atoi(optval);
1053 } else if (!strcasecmp(optname, "korate") && optval) {
1054 pp->korate = atoi(optval);
1055 } else if (!strcasecmp(optname, "josekirate") && optval) {
1056 pp->josekirate = atoi(optval);
1057 } else if (!strcasecmp(optname, "nakaderate") && optval) {
1058 pp->nakaderate = atoi(optval);
1059 } else if (!strcasecmp(optname, "alwaysccaprate") && optval) {
1060 pp->alwaysccaprate = atoi(optval);
1061 } else if (!strcasecmp(optname, "rate") && optval) {
1062 rate = atoi(optval);
1063 } else if (!strcasecmp(optname, "fillboardtries")) {
1064 pp->fillboardtries = atoi(optval);
1065 } else if (!strcasecmp(optname, "koage") && optval) {
1066 pp->koage = atoi(optval);
1067 } else if (!strcasecmp(optname, "pattern2")) {
1068 pp->pattern2 = optval && *optval == '0' ? false : true;
1069 } else if (!strcasecmp(optname, "selfatari_other")) {
1070 pp->selfatari_other = optval && *optval == '0' ? false : true;
1071 } else if (!strcasecmp(optname, "capcheckall")) {
1072 pp->capcheckall = optval && *optval == '0' ? false : true;
1073 } else if (!strcasecmp(optname, "cap_stone_min") && optval) {
1074 pp->cap_stone_min = atoi(optval);
1075 } else if (!strcasecmp(optname, "cap_stone_max") && optval) {
1076 pp->cap_stone_max = atoi(optval);
1077 } else if (!strcasecmp(optname, "cap_stone_denom") && optval) {
1078 pp->cap_stone_denom = atoi(optval);
1079 } else if (!strcasecmp(optname, "atari_miaisafe")) {
1080 pp->atari_miaisafe = optval && *optval == '0' ? false : true;
1081 } else if (!strcasecmp(optname, "atari_def_no_hopeless")) {
1082 pp->atari_def_no_hopeless = optval && *optval == '0' ? false : true;
1083 } else if (!strcasecmp(optname, "nlib_count") && optval) {
1084 pp->nlib_count = atoi(optval);
1085 } else if (!strcasecmp(optname, "fullchoose")) {
1086 p->choose = optval && *optval == '0' ? playout_moggy_seqchoose : playout_moggy_fullchoose;
1087 } else if (!strcasecmp(optname, "mqprob") && optval) {
1088 /* KO%LATARI%L2LIB%LNLIB%PAT3%GATARI%JOSEKI%NAKADE */
1089 for (int i = 0; *optval && i < MQ_MAX; i++) {
1090 pp->mq_prob[i] = atof(optval);
1091 optval += strcspn(optval, "%");
1092 if (*optval) optval++;
1094 } else if (!strcasecmp(optname, "tenukiprob") && optval) {
1095 pp->tenuki_prob = atof(optval);
1096 } else if (!strcasecmp(optname, "local_lpattern")) {
1097 pp->local_lpattern = !optval || atoi(optval);
1098 p->want_pat = true;
1099 } else {
1100 fprintf(stderr, "playout-moggy: Invalid policy argument %s or missing value\n", optname);
1101 exit(1);
1105 if (pp->lcapturerate == -1U) pp->lcapturerate = rate;
1106 if (pp->atarirate == -1U) pp->atarirate = rate;
1107 if (pp->nlibrate == -1U) pp->nlibrate = rate;
1108 if (pp->capturerate == -1U) pp->capturerate = rate;
1109 if (pp->patternrate == -1U) pp->patternrate = rate;
1110 if (pp->selfatarirate == -1U) pp->selfatarirate = rate;
1111 if (pp->eyefillrate == -1U) pp->eyefillrate = rate;
1112 if (pp->korate == -1U) pp->korate = rate;
1113 if (pp->josekirate == -1U) pp->josekirate = rate;
1114 if (pp->ladderrate == -1U) pp->ladderrate = rate;
1115 if (pp->nakaderate == -1U) pp->nakaderate = rate;
1116 if (pp->alwaysccaprate == -1U) pp->alwaysccaprate = rate;
1118 pattern3s_init(&pp->patterns, moggy_patterns_src, moggy_patterns_src_n);
1120 return p;