Moggy middle_ladder: Fix interaction of priors and test_pattern3_here()
[pachi/nmclean.git] / playout / moggy.c
blobb9c6acc1f28c4287f470e9ee22677799675dae21
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 "playout.h"
16 #include "playout/moggy.h"
17 #include "random.h"
18 #include "tactics/1lib.h"
19 #include "tactics/2lib.h"
20 #include "tactics/nlib.h"
21 #include "tactics/ladder.h"
22 #include "tactics/nakade.h"
23 #include "tactics/selfatari.h"
24 #include "uct/prior.h"
26 #define PLDEBUGL(n) DEBUGL_(p->debug_level, n)
29 /* In case "seqchoose" move picker is enabled (i.e. no "fullchoose"
30 * parameter passed), we stochastically apply fixed set of decision
31 * rules in given order.
33 * In "fullchoose" mode, we instead build a move queue of variously
34 * tagged candidates, then consider a probability distribution over
35 * them and pick a move from that. */
37 /* Move queue tags. Some may be even undesirable - these moves then
38 * receive a penalty; penalty tags should be used only when it is
39 * certain the move would be considered anyway. */
40 enum mq_tag {
41 MQ_KO = 0,
42 MQ_LATARI,
43 MQ_L2LIB,
44 #define MQ_LADDER MQ_L2LIB /* XXX: We want to fit in char still! */
45 MQ_LNLIB,
46 MQ_PAT3,
47 MQ_GATARI,
48 MQ_JOSEKI,
49 MQ_NAKADE,
50 MQ_MAX
54 /* Note that the context can be shared by multiple threads! */
56 struct moggy_policy {
57 unsigned int lcapturerate, atarirate, nlibrate, ladderrate, capturerate, patternrate, korate, josekirate, nakaderate;
58 unsigned int selfatarirate, eyefillrate, alwaysccaprate;
59 unsigned int fillboardtries;
60 int koage;
61 /* Whether to look for patterns around second-to-last move. */
62 bool pattern2;
63 /* Whether, when self-atari attempt is detected, to play the other
64 * group's liberty if that is non-self-atari. */
65 bool selfatari_other;
66 /* Whether to read out ladders elsewhere than near the board
67 * in the playouts. */
68 bool middle_ladder;
70 /* 1lib settings: */
71 /* Whether to always pick from moves capturing all groups in
72 * global_atari_check(). */
73 bool capcheckall;
74 /* Prior stone weighting. Weight of each stone between
75 * cap_stone_min and cap_stone_max is (assess*100)/cap_stone_denom. */
76 int cap_stone_min, cap_stone_max;
77 int cap_stone_denom;
79 /* 2lib settings: */
80 bool atari_def_no_hopeless;
81 bool atari_miaisafe;
83 /* nlib settings: */
84 int nlib_count;
86 struct joseki_dict *jdict;
87 struct pattern3s patterns;
89 /* Gamma values for queue tags - correspond to probabilities. */
90 /* XXX: Tune. */
91 double mq_prob[MQ_MAX], tenuki_prob;
95 static char moggy_patterns_src[][11] = {
96 /* hane pattern - enclosing hane */
97 "XOX"
98 "..."
99 "???",
100 /* hane pattern - non-cutting hane */
101 "YO."
102 "..."
103 "?.?",
104 /* hane pattern - magari */
105 "XO?"
106 "X.."
107 "x.?",
108 /* hane pattern - thin hane */
109 "XOO"
110 "..."
111 "?.?" "X",
112 /* generic pattern - katatsuke or diagonal attachment; similar to magari */
113 ".Q."
114 "Y.."
115 "...",
116 /* cut1 pattern (kiri) - unprotected cut */
117 "XO?"
118 "O.o"
119 "?o?",
120 /* cut1 pattern (kiri) - peeped cut */
121 "XO?"
122 "O.X"
123 "???",
124 /* cut2 pattern (de) */
125 "?X?"
126 "O.O"
127 "ooo",
128 /* cut keima (not in Mogo) */
129 "OX?"
130 "o.O"
131 "???", /* o?? has some pathological tsumego cases */
132 /* side pattern - chase */
133 "X.?"
134 "O.?"
135 "##?",
136 /* side pattern - block side cut */
137 "OX?"
138 "X.O"
139 "###",
140 /* side pattern - block side connection */
141 "?X?"
142 "x.O"
143 "###",
144 /* side pattern - sagari (SUSPICIOUS) */
145 "?XQ"
146 "x.x" /* Mogo has "x.?" */
147 "###" /* Mogo has "X" */,
148 /* side pattern - throw-in (SUSPICIOUS) */
149 #if 0
150 "?OX"
151 "o.O"
152 "?##" "X",
153 #endif
154 /* side pattern - cut (SUSPICIOUS) */
155 "?OY"
156 "Y.O"
157 "###" /* Mogo has "X" */,
158 /* side pattern - eye piercing:
159 * # O O O .
160 * # O . O .
161 * # . . . .
162 * # # # # # */
163 #if 0
164 "Oxx"
165 "..."
166 "###",
167 #endif
169 #define moggy_patterns_src_n sizeof(moggy_patterns_src) / sizeof(moggy_patterns_src[0])
171 static inline bool
172 test_pattern3_here(struct playout_policy *p, struct board *b, struct move *m, bool middle_ladder)
174 struct moggy_policy *pp = p->data;
175 /* Check if 3x3 pattern is matched by given move... */
176 if (!pattern3_move_here(&pp->patterns, b, m))
177 return false;
178 /* ...and the move is not obviously stupid. */
179 if (is_bad_selfatari(b, m->color, m->coord))
180 return false;
181 /* Ladder moves are stupid. */
182 group_t atari_neighbor = board_get_atari_neighbor(b, m->coord, m->color);
183 if (atari_neighbor && is_ladder(b, m->coord, atari_neighbor, middle_ladder)
184 && !can_countercapture(b, board_at(b, group_base(atari_neighbor)),
185 atari_neighbor, m->color, NULL, 0))
186 return false;
187 return true;
190 static void
191 apply_pattern_here(struct playout_policy *p, struct board *b, coord_t c, enum stone color, struct move_queue *q)
193 struct moggy_policy *pp = p->data;
194 struct move m2 = { .coord = c, .color = color };
195 if (board_is_valid_move(b, &m2) && test_pattern3_here(p, b, &m2, pp->middle_ladder))
196 mq_add(q, c, 1<<MQ_PAT3);
199 /* Check if we match any pattern around given move (with the other color to play). */
200 static void
201 apply_pattern(struct playout_policy *p, struct board *b, struct move *m, struct move *mm, struct move_queue *q)
203 /* Suicides do not make any patterns and confuse us. */
204 if (board_at(b, m->coord) == S_NONE || board_at(b, m->coord) == S_OFFBOARD)
205 return;
207 foreach_8neighbor(b, m->coord) {
208 apply_pattern_here(p, b, c, stone_other(m->color), q);
209 } foreach_8neighbor_end;
211 if (mm) { /* Second move for pattern searching */
212 foreach_8neighbor(b, mm->coord) {
213 if (coord_is_8adjecent(m->coord, c, b))
214 continue;
215 apply_pattern_here(p, b, c, stone_other(m->color), q);
216 } foreach_8neighbor_end;
219 if (PLDEBUGL(5))
220 mq_print(q, b, "Pattern");
224 static void
225 joseki_check(struct playout_policy *p, struct board *b, enum stone to_play, struct move_queue *q)
227 struct moggy_policy *pp = p->data;
228 if (!pp->jdict)
229 return;
231 for (int i = 0; i < 4; i++) {
232 hash_t h = b->qhash[i] & joseki_hash_mask;
233 coord_t *cc = pp->jdict->patterns[h].moves[to_play];
234 if (!cc) continue;
235 for (; !is_pass(*cc); cc++) {
236 if (coord_quadrant(*cc, b) != i)
237 continue;
238 mq_add(q, *cc, 1<<MQ_JOSEKI);
242 if (q->moves > 0 && PLDEBUGL(5))
243 mq_print(q, b, "Joseki");
246 static void
247 global_atari_check(struct playout_policy *p, struct board *b, enum stone to_play, struct move_queue *q)
249 if (b->clen == 0)
250 return;
252 struct moggy_policy *pp = p->data;
253 if (pp->capcheckall) {
254 for (int g = 0; g < b->clen; g++)
255 group_atari_check(pp->alwaysccaprate, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, pp->middle_ladder, 1<<MQ_GATARI);
256 if (PLDEBUGL(5))
257 mq_print(q, b, "Global atari");
258 return;
261 int g_base = fast_random(b->clen);
262 for (int g = g_base; g < b->clen; g++) {
263 group_atari_check(pp->alwaysccaprate, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, pp->middle_ladder, 1<<MQ_GATARI);
264 if (q->moves > 0) {
265 /* XXX: Try carrying on. */
266 if (PLDEBUGL(5))
267 mq_print(q, b, "Global atari");
268 return;
271 for (int g = 0; g < g_base; g++) {
272 group_atari_check(pp->alwaysccaprate, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, pp->middle_ladder, 1<<MQ_GATARI);
273 if (q->moves > 0) {
274 /* XXX: Try carrying on. */
275 if (PLDEBUGL(5))
276 mq_print(q, b, "Global atari");
277 return;
280 return;
283 static void
284 local_atari_check(struct playout_policy *p, struct board *b, struct move *m, struct move_queue *q)
286 struct moggy_policy *pp = p->data;
288 /* Did the opponent play a self-atari? */
289 if (board_group_info(b, group_at(b, m->coord)).libs == 1) {
290 group_atari_check(pp->alwaysccaprate, b, group_at(b, m->coord), stone_other(m->color), q, NULL, pp->middle_ladder, 1<<MQ_LATARI);
293 foreach_neighbor(b, m->coord, {
294 group_t g = group_at(b, c);
295 if (!g || board_group_info(b, g).libs != 1)
296 continue;
297 group_atari_check(pp->alwaysccaprate, b, g, stone_other(m->color), q, NULL, pp->middle_ladder, 1<<MQ_LATARI);
300 if (PLDEBUGL(5))
301 mq_print(q, b, "Local atari");
305 static void
306 local_ladder_check(struct playout_policy *p, struct board *b, struct move *m, struct move_queue *q)
308 group_t group = group_at(b, m->coord);
310 if (board_group_info(b, group).libs != 2)
311 return;
313 for (int i = 0; i < 2; i++) {
314 coord_t chase = board_group_info(b, group).lib[i];
315 coord_t escape = board_group_info(b, group).lib[1 - i];
316 if (wouldbe_ladder(b, group, escape, chase, board_at(b, group)))
317 mq_add(q, chase, 1<<MQ_LADDER);
320 if (q->moves > 0 && PLDEBUGL(5))
321 mq_print(q, b, "Ladder");
325 static void
326 local_2lib_check(struct playout_policy *p, struct board *b, struct move *m, struct move_queue *q)
328 struct moggy_policy *pp = p->data;
329 group_t group = group_at(b, m->coord), group2 = 0;
331 /* Does the opponent have just two liberties? */
332 if (board_group_info(b, group).libs == 2) {
333 group_2lib_check(b, group, stone_other(m->color), q, 1<<MQ_L2LIB, pp->atari_miaisafe, pp->atari_def_no_hopeless);
334 #if 0
335 /* We always prefer to take off an enemy chain liberty
336 * before pulling out ourselves. */
337 /* XXX: We aren't guaranteed to return to that group
338 * later. */
339 if (q->moves)
340 return q->move[fast_random(q->moves)];
341 #endif
344 /* Then he took a third liberty from neighboring chain? */
345 foreach_neighbor(b, m->coord, {
346 group_t g = group_at(b, c);
347 if (!g || g == group || g == group2 || board_group_info(b, g).libs != 2)
348 continue;
349 group_2lib_check(b, g, stone_other(m->color), q, 1<<MQ_L2LIB, pp->atari_miaisafe, pp->atari_def_no_hopeless);
350 group2 = g; // prevent trivial repeated checks
353 if (PLDEBUGL(5))
354 mq_print(q, b, "Local 2lib");
357 static void
358 local_nlib_check(struct playout_policy *p, struct board *b, struct move *m, struct move_queue *q)
360 struct moggy_policy *pp = p->data;
361 enum stone color = stone_other(m->color);
363 /* Attacking N-liberty groups in general is probably
364 * not feasible. What we are primarily concerned about is
365 * counter-attacking groups that have two physical liberties,
366 * but three effective liberties:
368 * . O . . . . #
369 * O O X X X X #
370 * . X O O X . #
371 * . X O . O X #
372 * . X O O . X #
373 * # # # # # # #
375 * The time for this to come is when the opponent took a liberty
376 * of ours, making a few-liberty group. Therefore, we focus
377 * purely on defense.
379 * There is a tradeoff - down to how many liberties we need to
380 * be to start looking? nlib_count=3 will work for the left black
381 * group (2lib-solver will suggest connecting the false eye), but
382 * not for top black group (it is too late to start playing 3-3
383 * capturing race). Also, we cannot prevent stupidly taking an
384 * outside liberty ourselves; the higher nlib_count, the higher
385 * the chance we withstand this.
387 * However, higher nlib_count means that we will waste more time
388 * checking non-urgent or alive groups, and we will play silly
389 * or wasted moves around alive groups. */
391 group_t group2 = 0;
392 foreach_8neighbor(b, m->coord) {
393 group_t g = group_at(b, c);
394 if (!g || group2 == g || board_at(b, c) != color)
395 continue;
396 if (board_group_info(b, g).libs < 3 || board_group_info(b, g).libs > pp->nlib_count)
397 continue;
398 group_nlib_defense_check(b, g, color, q, 1<<MQ_LNLIB);
399 group2 = g; // prevent trivial repeated checks
400 } foreach_8neighbor_end;
402 if (PLDEBUGL(5))
403 mq_print(q, b, "Local nlib");
406 static coord_t
407 nakade_check(struct playout_policy *p, struct board *b, struct move *m, enum stone to_play)
409 coord_t empty = pass;
410 foreach_neighbor(b, m->coord, {
411 if (board_at(b, c) != S_NONE)
412 continue;
413 if (is_pass(empty)) {
414 empty = c;
415 continue;
417 if (!coord_is_8adjecent(c, empty, b)) {
418 /* Seems like impossible nakade
419 * shape! */
420 return pass;
423 assert(!is_pass(empty));
425 coord_t nakade = nakade_point(b, empty, stone_other(to_play));
426 if (PLDEBUGL(5) && !is_pass(nakade))
427 fprintf(stderr, "Nakade: %s\n", coord2sstr(nakade, b));
428 return nakade;
431 coord_t
432 fillboard_check(struct playout_policy *p, struct board *b)
434 struct moggy_policy *pp = p->data;
435 unsigned int fbtries = b->flen / 8;
436 if (pp->fillboardtries < fbtries)
437 fbtries = pp->fillboardtries;
439 for (unsigned int i = 0; i < fbtries; i++) {
440 coord_t coord = b->f[fast_random(b->flen)];
441 if (immediate_liberty_count(b, coord) != 4)
442 continue;
443 foreach_diag_neighbor(b, coord) {
444 if (board_at(b, c) != S_NONE)
445 goto next_try;
446 } foreach_diag_neighbor_end;
447 return coord;
448 next_try:
451 return pass;
454 coord_t
455 playout_moggy_seqchoose(struct playout_policy *p, struct playout_setup *s, struct board *b, enum stone to_play)
457 struct moggy_policy *pp = p->data;
459 if (PLDEBUGL(5))
460 board_print(b, stderr);
462 /* Ko fight check */
463 if (!is_pass(b->last_ko.coord) && is_pass(b->ko.coord)
464 && b->moves - b->last_ko_age < pp->koage
465 && pp->korate > fast_random(100)) {
466 if (board_is_valid_play(b, to_play, b->last_ko.coord)
467 && !is_bad_selfatari(b, to_play, b->last_ko.coord))
468 return b->last_ko.coord;
471 /* Local checks */
472 if (!is_pass(b->last_move.coord)) {
473 /* Nakade check */
474 if (pp->nakaderate > fast_random(100)
475 && immediate_liberty_count(b, b->last_move.coord) > 0) {
476 coord_t nakade = nakade_check(p, b, &b->last_move, to_play);
477 if (!is_pass(nakade))
478 return nakade;
481 /* Local group in atari? */
482 if (pp->lcapturerate > fast_random(100)) {
483 struct move_queue q; q.moves = 0;
484 local_atari_check(p, b, &b->last_move, &q);
485 if (q.moves > 0)
486 return mq_pick(&q);
489 /* Local group trying to escape ladder? */
490 if (pp->ladderrate > fast_random(100)) {
491 struct move_queue q; q.moves = 0;
492 local_ladder_check(p, b, &b->last_move, &q);
493 if (q.moves > 0)
494 return mq_pick(&q);
497 /* Local group can be PUT in atari? */
498 if (pp->atarirate > fast_random(100)) {
499 struct move_queue q; q.moves = 0;
500 local_2lib_check(p, b, &b->last_move, &q);
501 if (q.moves > 0)
502 return mq_pick(&q);
505 /* Local group reduced some of our groups to 3 libs? */
506 if (pp->nlibrate > fast_random(100)) {
507 struct move_queue q; q.moves = 0;
508 local_nlib_check(p, b, &b->last_move, &q);
509 if (q.moves > 0)
510 return mq_pick(&q);
513 /* Check for patterns we know */
514 if (pp->patternrate > fast_random(100)) {
515 struct move_queue q; q.moves = 0;
516 apply_pattern(p, b, &b->last_move,
517 pp->pattern2 && b->last_move2.coord >= 0 ? &b->last_move2 : NULL,
518 &q);
519 if (q.moves > 0)
520 return mq_pick(&q);
524 /* Global checks */
526 /* Any groups in atari? */
527 if (pp->capturerate > fast_random(100)) {
528 struct move_queue q; q.moves = 0;
529 global_atari_check(p, b, to_play, &q);
530 if (q.moves > 0)
531 return mq_pick(&q);
534 /* Joseki moves? */
535 if (pp->josekirate > fast_random(100)) {
536 struct move_queue q; q.moves = 0;
537 joseki_check(p, b, to_play, &q);
538 if (q.moves > 0)
539 return mq_pick(&q);
542 /* Fill board */
543 if (pp->fillboardtries > 0) {
544 coord_t c = fillboard_check(p, b);
545 if (!is_pass(c))
546 return c;
549 return pass;
552 /* Pick a move from queue q, giving different likelihoods to moves
553 * based on their tags. */
554 coord_t
555 mq_tagged_choose(struct playout_policy *p, struct board *b, enum stone to_play, struct move_queue *q)
557 struct moggy_policy *pp = p->data;
559 /* First, merge all entries for a move. */
560 /* We use a naive O(N^2) since the average length of the queue
561 * is about 1.4. */
562 for (unsigned int i = 0; i < q->moves; i++) {
563 for (unsigned int j = i + 1; j < q->moves; j++) {
564 if (q->move[i] != q->move[j])
565 continue;
566 q->tag[i] |= q->tag[j];
567 q->moves--;
568 q->tag[j] = q->tag[q->moves];
569 q->move[j] = q->move[q->moves];
573 /* Now, construct a probdist. */
574 fixp_t total = 0;
575 fixp_t pd[q->moves];
576 for (unsigned int i = 0; i < q->moves; i++) {
577 double val = 1.0;
578 assert(q->tag[i] != 0);
579 for (int j = 0; j < MQ_MAX; j++)
580 if (q->tag[i] & (1<<j)) {
581 //fprintf(stderr, "%s(%x) %d %f *= %f\n", coord2sstr(q->move[i], b), q->tag[i], j, val, pp->mq_prob[j]);
582 val *= pp->mq_prob[j];
584 pd[i] = double_to_fixp(val);
585 total += pd[i];
587 total += double_to_fixp(pp->tenuki_prob);
589 /* Finally, pick a move! */
590 fixp_t stab = fast_irandom(total);
591 for (unsigned int i = 0; i < q->moves; i++) {
592 //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));
593 if (stab < pd[i])
594 return q->move[i];
595 stab -= pd[i];
598 /* Tenuki. */
599 assert(stab < double_to_fixp(pp->tenuki_prob));
600 return pass;
603 coord_t
604 playout_moggy_fullchoose(struct playout_policy *p, struct playout_setup *s, struct board *b, enum stone to_play)
606 struct moggy_policy *pp = p->data;
607 struct move_queue q; q.moves = 0;
609 if (PLDEBUGL(5))
610 board_print(b, stderr);
612 /* Ko fight check */
613 if (!is_pass(b->last_ko.coord) && is_pass(b->ko.coord)
614 && b->moves - b->last_ko_age < pp->koage) {
615 if (board_is_valid_play(b, to_play, b->last_ko.coord)
616 && !is_bad_selfatari(b, to_play, b->last_ko.coord))
617 mq_add(&q, b->last_ko.coord, 1<<MQ_KO);
620 /* Local checks */
621 if (!is_pass(b->last_move.coord)) {
622 /* Nakade check */
623 if (immediate_liberty_count(b, b->last_move.coord) > 0) {
624 coord_t nakade = nakade_check(p, b, &b->last_move, to_play);
625 if (!is_pass(nakade))
626 mq_add(&q, nakade, 1<<MQ_NAKADE);
629 /* Local group in atari? */
630 local_atari_check(p, b, &b->last_move, &q);
632 /* Local group trying to escape ladder? */
633 local_ladder_check(p, b, &b->last_move, &q);
635 /* Local group can be PUT in atari? */
636 local_2lib_check(p, b, &b->last_move, &q);
638 /* Local group reduced some of our groups to 3 libs? */
639 local_nlib_check(p, b, &b->last_move, &q);
641 /* Check for patterns we know */
642 apply_pattern(p, b, &b->last_move,
643 pp->pattern2 && b->last_move2.coord >= 0 ? &b->last_move2 : NULL,
644 &q);
647 /* Global checks */
649 /* Any groups in atari? */
650 global_atari_check(p, b, to_play, &q);
652 /* Joseki moves? */
653 joseki_check(p, b, to_play, &q);
655 #if 0
656 /* Average length of the queue is 1.4 move. */
657 printf("MQL %d ", q.moves);
658 for (unsigned int i = 0; i < q.moves; i++)
659 printf("%s ", coord2sstr(q.move[i], b));
660 printf("\n");
661 #endif
663 if (q.moves > 0)
664 return mq_tagged_choose(p, b, to_play, &q);
666 /* Fill board */
667 if (pp->fillboardtries > 0) {
668 coord_t c = fillboard_check(p, b);
669 if (!is_pass(c))
670 return c;
673 return pass;
677 void
678 playout_moggy_assess_group(struct playout_policy *p, struct prior_map *map, group_t g, int games)
680 struct moggy_policy *pp = p->data;
681 struct board *b = map->b;
682 struct move_queue q; q.moves = 0;
684 if (board_group_info(b, g).libs > pp->nlib_count)
685 return;
687 if (PLDEBUGL(5)) {
688 fprintf(stderr, "ASSESS of group %s:\n", coord2sstr(g, b));
689 board_print(b, stderr);
692 if (board_group_info(b, g).libs > 2) {
693 if (!pp->nlibrate)
694 return;
695 if (board_at(b, g) != map->to_play)
696 return; // we do only defense
697 group_nlib_defense_check(b, g, map->to_play, &q, 0);
698 while (q.moves--) {
699 coord_t coord = q.move[q.moves];
700 if (PLDEBUGL(5))
701 fprintf(stderr, "1.0: nlib %s\n", coord2sstr(coord, b));
702 int assess = games / 2;
703 add_prior_value(map, coord, 1, assess);
705 return;
708 if (board_group_info(b, g).libs == 2) {
709 if (pp->ladderrate) {
710 /* Make sure to play the correct liberty in case
711 * this is a group that can be caught in a ladder. */
712 bool ladderable = false;
713 for (int i = 0; i < 2; i++) {
714 coord_t chase = board_group_info(b, g).lib[i];
715 coord_t escape = board_group_info(b, g).lib[1 - i];
716 if (wouldbe_ladder(b, g, escape, chase, board_at(b, g))) {
717 add_prior_value(map, chase, 1, games);
718 ladderable = true;
721 if (ladderable)
722 return; // do not suggest the other lib at all
725 if (!pp->atarirate)
726 return;
727 group_2lib_check(b, g, map->to_play, &q, 0, pp->atari_miaisafe, pp->atari_def_no_hopeless);
728 while (q.moves--) {
729 coord_t coord = q.move[q.moves];
730 if (PLDEBUGL(5))
731 fprintf(stderr, "1.0: 2lib %s\n", coord2sstr(coord, b));
732 int assess = games / 2;
733 add_prior_value(map, coord, 1, assess);
735 return;
738 /* This group, sir, is in atari! */
740 coord_t ladder = pass;
741 group_atari_check(pp->alwaysccaprate, b, g, map->to_play, &q, &ladder, true, 0);
742 while (q.moves--) {
743 coord_t coord = q.move[q.moves];
745 /* _Never_ play here if this move plays out
746 * a caught ladder. */
747 if (coord == ladder && !board_playing_ko_threat(b)) {
748 /* Note that the opposite is not guarded against;
749 * we do not advise against capturing a laddered
750 * group (but we don't encourage it either). Such
751 * a move can simplify tactical situations if we
752 * can afford it. */
753 if (map->to_play != board_at(b, g))
754 continue;
755 /* FIXME: We give the malus even if this move
756 * captures another group. */
757 if (PLDEBUGL(5))
758 fprintf(stderr, "0.0: ladder %s\n", coord2sstr(coord, b));
759 add_prior_value(map, coord, 0, games);
760 continue;
763 if (!pp->capturerate && !pp->lcapturerate)
764 continue;
766 int assess = games * 2;
767 if (pp->cap_stone_denom > 0) {
768 int stones = group_stone_count(b, g, pp->cap_stone_max) - (pp->cap_stone_min-1);
769 assess += (stones > 0 ? stones : 0) * games * 100 / pp->cap_stone_denom;
771 if (PLDEBUGL(5))
772 fprintf(stderr, "1.0 (%d): atari %s\n", assess, coord2sstr(coord, b));
773 add_prior_value(map, coord, 1, assess);
777 void
778 playout_moggy_assess_one(struct playout_policy *p, struct prior_map *map, coord_t coord, int games)
780 struct moggy_policy *pp = p->data;
781 struct board *b = map->b;
783 if (PLDEBUGL(5)) {
784 fprintf(stderr, "ASSESS of move %s:\n", coord2sstr(coord, b));
785 board_print(b, stderr);
788 /* Is this move a self-atari? */
789 if (pp->selfatarirate) {
790 if (!board_playing_ko_threat(b) && is_bad_selfatari(b, map->to_play, coord)) {
791 if (PLDEBUGL(5))
792 fprintf(stderr, "0.0: self-atari\n");
793 add_prior_value(map, coord, 0, games);
794 if (!pp->selfatari_other)
795 return;
796 /* If we can play on the other liberty of the
797 * endangered group, do! */
798 coord = selfatari_cousin(b, map->to_play, coord, NULL);
799 if (is_pass(coord))
800 return;
801 if (PLDEBUGL(5))
802 fprintf(stderr, "1.0: self-atari redirect %s\n", coord2sstr(coord, b));
803 add_prior_value(map, coord, 1.0, games);
804 return;
808 /* Pattern check */
809 if (pp->patternrate) {
810 struct move m = { .color = map->to_play, .coord = coord };
811 if (test_pattern3_here(p, b, &m, true)) {
812 if (PLDEBUGL(5))
813 fprintf(stderr, "1.0: pattern\n");
814 add_prior_value(map, coord, 1, games);
818 return;
821 void
822 playout_moggy_assess(struct playout_policy *p, struct prior_map *map, int games)
824 struct moggy_policy *pp = p->data;
826 /* First, go through all endangered groups. */
827 for (group_t g = 1; g < board_size2(map->b); g++)
828 if (group_at(map->b, g) == g)
829 playout_moggy_assess_group(p, map, g, games);
831 /* Then, assess individual moves. */
832 if (!pp->patternrate && !pp->selfatarirate)
833 return;
834 foreach_free_point(map->b) {
835 if (map->consider[c])
836 playout_moggy_assess_one(p, map, c, games);
837 } foreach_free_point_end;
840 bool
841 playout_moggy_permit(struct playout_policy *p, struct board *b, struct move *m)
843 struct moggy_policy *pp = p->data;
845 /* The idea is simple for now - never allow self-atari moves.
846 * They suck in general, but this also permits us to actually
847 * handle seki in the playout stage. */
849 if (fast_random(100) >= pp->selfatarirate) {
850 if (PLDEBUGL(5))
851 fprintf(stderr, "skipping sar test\n");
852 goto sar_skip;
854 bool selfatari = is_bad_selfatari(b, m->color, m->coord);
855 if (selfatari) {
856 if (PLDEBUGL(5))
857 fprintf(stderr, "__ Prohibiting self-atari %s %s\n",
858 stone2str(m->color), coord2sstr(m->coord, b));
859 if (pp->selfatari_other) {
860 /* Ok, try the other liberty of the atari'd group. */
861 coord_t c = selfatari_cousin(b, m->color, m->coord, NULL);
862 if (is_pass(c)) return false;
863 if (PLDEBUGL(5))
864 fprintf(stderr, "___ Redirecting to other lib %s\n",
865 coord2sstr(c, b));
866 m->coord = c;
867 return true;
869 return false;
871 sar_skip:
873 /* Check if we don't seem to be filling our eye. This should
874 * happen only for false eyes, but some of them are in fact
875 * real eyes with diagonal filled by a dead stone. Prefer
876 * to counter-capture in that case. */
877 if (fast_random(100) >= pp->eyefillrate) {
878 if (PLDEBUGL(5))
879 fprintf(stderr, "skipping eyefill test\n");
880 goto eyefill_skip;
882 bool eyefill = board_is_eyelike(b, m->coord, m->color);
883 if (eyefill) {
884 foreach_diag_neighbor(b, m->coord) {
885 if (board_at(b, c) != stone_other(m->color))
886 continue;
887 switch (board_group_info(b, group_at(b, c)).libs) {
888 case 1: /* Capture! */
889 c = board_group_info(b, group_at(b, c)).lib[0];
890 if (PLDEBUGL(5))
891 fprintf(stderr, "___ Redirecting to capture %s\n",
892 coord2sstr(c, b));
893 m->coord = c;
894 return true;
895 case 2: /* Try to switch to some 2-lib neighbor. */
896 for (int i = 0; i < 2; i++) {
897 coord_t l = board_group_info(b, group_at(b, c)).lib[i];
898 if (board_is_one_point_eye(b, l, board_at(b, c)))
899 continue;
900 if (is_bad_selfatari(b, m->color, l))
901 continue;
902 m->coord = l;
903 return true;
905 break;
907 } foreach_diag_neighbor_end;
910 eyefill_skip:
911 return true;
915 struct playout_policy *
916 playout_moggy_init(char *arg, struct board *b, struct joseki_dict *jdict)
918 struct playout_policy *p = calloc2(1, sizeof(*p));
919 struct moggy_policy *pp = calloc2(1, sizeof(*pp));
920 p->data = pp;
921 p->choose = playout_moggy_seqchoose;
922 p->assess = playout_moggy_assess;
923 p->permit = playout_moggy_permit;
925 pp->jdict = jdict;
927 /* These settings are tuned for 19x19 play with several threads
928 * on reasonable time limits (i.e., rather large number of playouts).
929 * XXX: no 9x9 tuning has been done recently. */
930 int rate = board_large(b) ? 80 : 90;
932 pp->lcapturerate = pp->atarirate = pp->nlibrate = pp->patternrate
933 = pp->selfatarirate = pp->eyefillrate = pp->josekirate = pp->ladderrate = -1U;
934 if (board_large(b)) {
935 pp->lcapturerate = 90;
936 pp->patternrate = 100;
937 pp->nlibrate = 20;
938 pp->nakaderate = 20;
939 pp->pattern2 = true;
941 pp->korate = 20; pp->koage = 4;
942 pp->alwaysccaprate = 20;
943 pp->selfatari_other = true;
944 pp->middle_ladder = true;
946 pp->cap_stone_min = 2;
947 pp->cap_stone_max = 15;
948 pp->cap_stone_denom = 200;
950 pp->atari_def_no_hopeless = !board_large(b);
951 pp->atari_miaisafe = true;
952 pp->nlib_count = 4;
954 /* C is stupid. */
955 double mq_prob_default[MQ_MAX] = {
956 [MQ_KO] = 6.0,
957 [MQ_NAKADE] = 5.5,
958 [MQ_LATARI] = 5.0,
959 [MQ_L2LIB] = 4.0,
960 [MQ_LNLIB] = 3.5,
961 [MQ_PAT3] = 3.0,
962 [MQ_GATARI] = 2.0,
963 [MQ_JOSEKI] = 1.0,
965 memcpy(pp->mq_prob, mq_prob_default, sizeof(pp->mq_prob));
967 if (arg) {
968 char *optspec, *next = arg;
969 while (*next) {
970 optspec = next;
971 next += strcspn(next, ":");
972 if (*next) { *next++ = 0; } else { *next = 0; }
974 char *optname = optspec;
975 char *optval = strchr(optspec, '=');
976 if (optval) *optval++ = 0;
978 if (!strcasecmp(optname, "debug") && optval) {
979 p->debug_level = atoi(optval);
980 } else if (!strcasecmp(optname, "lcapturerate") && optval) {
981 pp->lcapturerate = atoi(optval);
982 } else if (!strcasecmp(optname, "ladderrate") && optval) {
983 pp->ladderrate = atoi(optval);
984 } else if (!strcasecmp(optname, "atarirate") && optval) {
985 pp->atarirate = atoi(optval);
986 } else if (!strcasecmp(optname, "nlibrate") && optval) {
987 pp->nlibrate = atoi(optval);
988 } else if (!strcasecmp(optname, "capturerate") && optval) {
989 pp->capturerate = atoi(optval);
990 } else if (!strcasecmp(optname, "patternrate") && optval) {
991 pp->patternrate = atoi(optval);
992 } else if (!strcasecmp(optname, "selfatarirate") && optval) {
993 pp->selfatarirate = atoi(optval);
994 } else if (!strcasecmp(optname, "eyefillrate") && optval) {
995 pp->eyefillrate = atoi(optval);
996 } else if (!strcasecmp(optname, "korate") && optval) {
997 pp->korate = atoi(optval);
998 } else if (!strcasecmp(optname, "josekirate") && optval) {
999 pp->josekirate = atoi(optval);
1000 } else if (!strcasecmp(optname, "nakaderate") && optval) {
1001 pp->nakaderate = atoi(optval);
1002 } else if (!strcasecmp(optname, "alwaysccaprate") && optval) {
1003 pp->alwaysccaprate = atoi(optval);
1004 } else if (!strcasecmp(optname, "rate") && optval) {
1005 rate = atoi(optval);
1006 } else if (!strcasecmp(optname, "fillboardtries")) {
1007 pp->fillboardtries = atoi(optval);
1008 } else if (!strcasecmp(optname, "koage") && optval) {
1009 pp->koage = atoi(optval);
1010 } else if (!strcasecmp(optname, "pattern2")) {
1011 pp->pattern2 = optval && *optval == '0' ? false : true;
1012 } else if (!strcasecmp(optname, "selfatari_other")) {
1013 pp->selfatari_other = optval && *optval == '0' ? false : true;
1014 } else if (!strcasecmp(optname, "capcheckall")) {
1015 pp->capcheckall = optval && *optval == '0' ? false : true;
1016 } else if (!strcasecmp(optname, "cap_stone_min") && optval) {
1017 pp->cap_stone_min = atoi(optval);
1018 } else if (!strcasecmp(optname, "cap_stone_max") && optval) {
1019 pp->cap_stone_max = atoi(optval);
1020 } else if (!strcasecmp(optname, "cap_stone_denom") && optval) {
1021 pp->cap_stone_denom = atoi(optval);
1022 } else if (!strcasecmp(optname, "atari_miaisafe")) {
1023 pp->atari_miaisafe = optval && *optval == '0' ? false : true;
1024 } else if (!strcasecmp(optname, "atari_def_no_hopeless")) {
1025 pp->atari_def_no_hopeless = optval && *optval == '0' ? false : true;
1026 } else if (!strcasecmp(optname, "nlib_count") && optval) {
1027 pp->nlib_count = atoi(optval);
1028 } else if (!strcasecmp(optname, "middle_ladder")) {
1029 pp->middle_ladder = optval && *optval == '0' ? false : true;
1030 } else if (!strcasecmp(optname, "fullchoose")) {
1031 p->choose = optval && *optval == '0' ? playout_moggy_seqchoose : playout_moggy_fullchoose;
1032 } else if (!strcasecmp(optname, "mqprob") && optval) {
1033 /* KO%LATARI%L2LIB%LNLIB%PAT3%GATARI%JOSEKI%NAKADE */
1034 for (int i = 0; *optval && i < MQ_MAX; i++) {
1035 pp->mq_prob[i] = atof(optval);
1036 optval += strcspn(optval, "%");
1037 if (*optval) optval++;
1039 } else if (!strcasecmp(optname, "tenukiprob") && optval) {
1040 pp->tenuki_prob = atof(optval);
1041 } else {
1042 fprintf(stderr, "playout-moggy: Invalid policy argument %s or missing value\n", optname);
1043 exit(1);
1047 if (pp->lcapturerate == -1U) pp->lcapturerate = rate;
1048 if (pp->atarirate == -1U) pp->atarirate = rate;
1049 if (pp->nlibrate == -1U) pp->nlibrate = rate;
1050 if (pp->capturerate == -1U) pp->capturerate = rate;
1051 if (pp->patternrate == -1U) pp->patternrate = rate;
1052 if (pp->selfatarirate == -1U) pp->selfatarirate = rate;
1053 if (pp->eyefillrate == -1U) pp->eyefillrate = rate;
1054 if (pp->korate == -1U) pp->korate = rate;
1055 if (pp->josekirate == -1U) pp->josekirate = rate;
1056 if (pp->ladderrate == -1U) pp->ladderrate = rate;
1057 if (pp->nakaderate == -1U) pp->nakaderate = rate;
1058 if (pp->alwaysccaprate == -1U) pp->alwaysccaprate = rate;
1060 pattern3s_init(&pp->patterns, moggy_patterns_src, moggy_patterns_src_n);
1062 return p;