Moggy group_atari_check(): Remove the rest of playout_data dependencies
[pachi.git] / playout / moggy.c
blobed763453e88456029b80c586b8ae0ce4b15658cc
1 /* Playout policy by stochastically applying a fixed set of decision
2 * rules in given order - modelled after the intelligent playouts
3 * in the Mogo engine. */
5 #include <assert.h>
6 #include <math.h>
7 #include <stdio.h>
8 #include <stdlib.h>
10 #define DEBUG
11 #include "board.h"
12 #include "debug.h"
13 #include "joseki/base.h"
14 #include "mq.h"
15 #include "pattern3.h"
16 #include "playout.h"
17 #include "playout/moggy.h"
18 #include "random.h"
19 #include "tactics/ladder.h"
20 #include "tactics/selfatari.h"
21 #include "uct/prior.h"
23 #define PLDEBUGL(n) DEBUGL_(p->debug_level, n)
25 /* Whether to avoid capturing/atariing doomed groups (this is big
26 * performance hit and may reduce playouts balance; it does increase
27 * the strength, but not quite proportionally to the performance). */
28 //#define NO_DOOMED_GROUPS
31 /* Move queue tags: */
32 enum mq_tag {
33 MQ_KO = 1,
34 MQ_LATARI,
35 MQ_L2LIB,
36 MQ_PAT3,
37 MQ_GATARI,
38 MQ_JOSEKI,
39 MQ_MAX
43 /* Note that the context can be shared by multiple threads! */
45 struct moggy_policy {
46 unsigned int lcapturerate, atarirate, capturerate, patternrate, korate, josekirate;
47 unsigned int selfatarirate, alwaysccaprate;
48 unsigned int fillboardtries;
49 int koage;
50 /* Whether to look for patterns around second-to-last move. */
51 bool pattern2;
52 /* Whether, when self-atari attempt is detected, to play the other
53 * group's liberty if that is non-self-atari. */
54 bool selfatari_other;
55 /* Whether to always pick from moves capturing all groups in
56 * global_atari_check(). */
57 bool capcheckall;
59 struct joseki_dict *jdict;
60 struct pattern3s patterns;
62 /* Gamma values for queue tags - correspond to probabilities. */
63 /* XXX: Tune. */
64 double mq_prob[MQ_MAX], tenuki_prob;
68 static char moggy_patterns_src[][11] = {
69 /* hane pattern - enclosing hane */
70 "XOX"
71 "..."
72 "???",
73 /* hane pattern - non-cutting hane */
74 "XO."
75 "..."
76 "?.?",
77 /* hane pattern - magari */
78 "XO?"
79 "X.."
80 "x.?",
81 /* hane pattern - thin hane */
82 "XOO"
83 "..."
84 "?.?" "X",
85 /* generic pattern - katatsuke or diagonal attachment; similar to magari */
86 ".O."
87 "X.."
88 "...",
89 /* cut1 pattern (kiri) - unprotected cut */
90 "XO?"
91 "O.o"
92 "?o?",
93 /* cut1 pattern (kiri) - peeped cut */
94 "XO?"
95 "O.X"
96 "???",
97 /* cut2 pattern (de) */
98 "?X?"
99 "O.O"
100 "ooo",
101 /* cut keima (not in Mogo) */
102 "OX?"
103 "o.O"
104 "???", /* o?? has some pathological tsumego cases */
105 /* side pattern - chase */
106 "X.?"
107 "O.?"
108 "##?",
109 /* side pattern - block side cut */
110 "OX?"
111 "X.O"
112 "###",
113 /* side pattern - block side connection */
114 "?X?"
115 "x.O"
116 "###",
117 /* side pattern - sagari (SUSPICIOUS) */
118 "?XO"
119 "x.x" /* Mogo has "x.?" */
120 "###" /* Mogo has "X" */,
121 /* side pattern - throw-in (SUSPICIOUS) */
122 #if 0
123 "?OX"
124 "o.O"
125 "?##" "X",
126 #endif
127 /* side pattern - cut (SUSPICIOUS) */
128 "?OX"
129 "X.O"
130 "###" /* Mogo has "X" */,
132 #define moggy_patterns_src_n sizeof(moggy_patterns_src) / sizeof(moggy_patterns_src[0])
134 static inline bool
135 test_pattern3_here(struct playout_policy *p, struct board *b, struct move *m)
137 struct moggy_policy *pp = p->data;
138 /* Check if 3x3 pattern is matched by given move... */
139 if (!pattern3_move_here(&pp->patterns, b, m))
140 return false;
141 /* ...and the move is not obviously stupid. */
142 if (is_bad_selfatari(b, m->color, m->coord))
143 return false;
144 /* Ladder moves are stupid. */
145 group_t atari_neighbor = board_get_atari_neighbor(b, m->coord, m->color);
146 if (atari_neighbor && is_ladder(b, m->coord, atari_neighbor))
147 return false;
148 return true;
151 static void
152 apply_pattern_here(struct playout_policy *p, struct board *b, coord_t c, enum stone color, struct move_queue *q)
154 struct move m2 = { .coord = c, .color = color };
155 if (board_is_valid_move(b, &m2) && test_pattern3_here(p, b, &m2))
156 mq_add(q, c, 1<<MQ_PAT3);
159 /* Check if we match any pattern around given move (with the other color to play). */
160 static void
161 apply_pattern(struct playout_policy *p, struct board *b, struct move *m, struct move *mm, struct move_queue *q)
163 /* Suicides do not make any patterns and confuse us. */
164 if (board_at(b, m->coord) == S_NONE || board_at(b, m->coord) == S_OFFBOARD)
165 return;
167 foreach_8neighbor(b, m->coord) {
168 apply_pattern_here(p, b, c, stone_other(m->color), q);
169 } foreach_8neighbor_end;
171 if (mm) { /* Second move for pattern searching */
172 foreach_8neighbor(b, mm->coord) {
173 if (coord_is_8adjecent(m->coord, c, b))
174 continue;
175 apply_pattern_here(p, b, c, stone_other(m->color), q);
176 } foreach_8neighbor_end;
179 if (PLDEBUGL(5))
180 mq_print(q, b, "Pattern");
184 static bool
185 can_play_on_lib(struct board *b, group_t g, enum stone to_play)
187 coord_t capture = board_group_info(b, g).lib[0];
188 if (DEBUGL(6))
189 fprintf(stderr, "can capture group %d (%s)?\n",
190 g, coord2sstr(capture, b));
191 /* Does playing on the liberty usefully capture the group? */
192 if (board_is_valid_play(b, to_play, capture)
193 && !is_bad_selfatari(b, to_play, capture))
194 return true;
196 return false;
199 /* For given position @c, decide if this is a group that is in danger from
200 * @capturer and @to_play can do anything about it (play at the last
201 * liberty to either capture or escape). */
202 /* Note that @to_play is important; e.g. consider snapback, it's good
203 * to play at the last liberty by attacker, but not defender. */
204 static __attribute__((always_inline)) bool
205 capturable_group(struct board *b, enum stone capturer, coord_t c,
206 enum stone to_play)
208 group_t g = group_at(b, c);
209 if (likely(board_at(b, c) != stone_other(capturer)
210 || board_group_info(b, g).libs > 1))
211 return false;
213 return can_play_on_lib(b, g, to_play);
216 /* For given atari group @group owned by @owner, decide if @to_play
217 * can save it / keep it in danger by dealing with one of the
218 * neighboring groups. */
219 static bool
220 can_countercapture(struct board *b, enum stone owner, group_t g,
221 enum stone to_play, struct move_queue *q, enum mq_tag tag)
223 if (b->clen < 2)
224 return false;
226 unsigned int qmoves_prev = q ? q->moves : 0;
228 foreach_in_group(b, g) {
229 foreach_neighbor(b, c, {
230 if (!capturable_group(b, owner, c, to_play))
231 continue;
233 if (!q) {
234 return true;
236 mq_add(q, board_group_info(b, group_at(b, c)).lib[0], 1<<tag);
237 mq_nodup(q);
239 } foreach_in_group_end;
241 bool can = q ? q->moves > qmoves_prev : false;
242 return can;
245 #ifdef NO_DOOMED_GROUPS
246 static bool
247 can_be_rescued(struct board *b, group_t group, enum stone color, enum mq_tag tag)
249 /* Does playing on the liberty rescue the group? */
250 if (can_play_on_lib(b, group, color))
251 return true;
253 /* Then, maybe we can capture one of our neighbors? */
254 return can_countercapture(b, color, group, color, NULL, tag);
256 #endif
258 /* ladder != NULL implies to always enqueue all relevant moves. */
259 static void
260 group_atari_check(unsigned int alwaysccaprate, struct board *b, group_t group, enum stone to_play,
261 struct move_queue *q, coord_t *ladder, enum mq_tag tag)
263 int qmoves_prev = q->moves;
265 /* We don't use @to_play almost anywhere since any moves here are good
266 * for both defender and attacker. */
268 enum stone color = board_at(b, group_base(group));
269 coord_t lib = board_group_info(b, group).lib[0];
271 assert(color != S_OFFBOARD && color != S_NONE);
272 if (DEBUGL(5))
273 fprintf(stderr, "[%s] atariiiiiiiii %s of color %d\n",
274 coord2sstr(group, b), coord2sstr(lib, b), color);
275 assert(board_at(b, lib) == S_NONE);
277 /* Can we capture some neighbor? */
278 bool ccap = can_countercapture(b, color, group, to_play, q, tag);
279 if (ccap && !ladder && alwaysccaprate > fast_random(100))
280 return;
282 /* Otherwise, do not save kos. */
283 if (group_is_onestone(b, group)
284 && neighbor_count_at(b, lib, color) + neighbor_count_at(b, lib, S_OFFBOARD) == 4)
285 return;
287 /* Do not suicide... */
288 if (!can_play_on_lib(b, group, to_play))
289 return;
290 #ifdef NO_DOOMED_GROUPS
291 /* Do not remove group that cannot be saved by the opponent. */
292 if (to_play != color && !can_be_rescued(b, group, color, tag))
293 return;
294 #endif
295 if (DEBUGL(6))
296 fprintf(stderr, "...escape route valid\n");
298 /* ...or play out ladders. */
299 if (is_ladder(b, lib, group)) {
300 /* Sometimes we want to keep the ladder move in the
301 * queue in order to discourage it. */
302 if (!ladder)
303 return;
304 else
305 *ladder = lib;
307 if (DEBUGL(6))
308 fprintf(stderr, "...no ladder\n");
310 if (to_play != color) {
311 /* We are the attacker! In that case, throw away the moves
312 * that defend our groups, since we can capture the culprit. */
313 q->moves = qmoves_prev;
316 mq_add(q, lib, 1<<tag);
317 mq_nodup(q);
320 static void
321 joseki_check(struct playout_policy *p, struct board *b, enum stone to_play, struct move_queue *q)
323 struct moggy_policy *pp = p->data;
324 if (!pp->jdict)
325 return;
327 for (int i = 0; i < 4; i++) {
328 hash_t h = b->qhash[i] & joseki_hash_mask;
329 coord_t *cc = pp->jdict->patterns[h].moves[to_play];
330 if (!cc) continue;
331 for (; !is_pass(*cc); cc++) {
332 if (coord_quadrant(*cc, b) != i)
333 continue;
334 mq_add(q, *cc, 1<<MQ_JOSEKI);
338 if (q->moves > 0 && PLDEBUGL(5))
339 mq_print(q, b, "Joseki");
342 static void
343 global_atari_check(struct playout_policy *p, struct board *b, enum stone to_play, struct move_queue *q)
345 if (b->clen == 0)
346 return;
348 struct moggy_policy *pp = p->data;
349 if (pp->capcheckall) {
350 for (int g = 0; g < b->clen; g++)
351 group_atari_check(pp->alwaysccaprate, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, MQ_GATARI);
352 if (PLDEBUGL(5))
353 mq_print(q, b, "Global atari");
354 return;
357 int g_base = fast_random(b->clen);
358 for (int g = g_base; g < b->clen; g++) {
359 group_atari_check(pp->alwaysccaprate, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, MQ_GATARI);
360 if (q->moves > 0) {
361 /* XXX: Try carrying on. */
362 if (PLDEBUGL(5))
363 mq_print(q, b, "Global atari");
364 return;
367 for (int g = 0; g < g_base; g++) {
368 group_atari_check(pp->alwaysccaprate, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, MQ_GATARI);
369 if (q->moves > 0) {
370 /* XXX: Try carrying on. */
371 if (PLDEBUGL(5))
372 mq_print(q, b, "Global atari");
373 return;
376 return;
379 static void
380 local_atari_check(struct playout_policy *p, struct board *b, struct move *m, struct move_queue *q)
382 struct moggy_policy *pp = p->data;
384 /* Did the opponent play a self-atari? */
385 if (board_group_info(b, group_at(b, m->coord)).libs == 1) {
386 group_atari_check(pp->alwaysccaprate, b, group_at(b, m->coord), stone_other(m->color), q, NULL, MQ_LATARI);
389 foreach_neighbor(b, m->coord, {
390 group_t g = group_at(b, c);
391 if (!g || board_group_info(b, g).libs != 1)
392 continue;
393 group_atari_check(pp->alwaysccaprate, b, g, stone_other(m->color), q, NULL, MQ_LATARI);
396 if (PLDEBUGL(5))
397 mq_print(q, b, "Local atari");
400 static bool
401 miai_2lib(struct board *b, group_t group, enum stone color)
403 bool can_connect = false, can_pull_out = false;
404 /* We have miai if we can either connect on both libs,
405 * or connect on one lib and escape on another. (Just
406 * having two escape routes can be risky.) We must make
407 * sure that we don't consider following as miai:
408 * X X X O
409 * X . . O
410 * O O X O - left dot would be pull-out, right dot connect */
411 foreach_neighbor(b, board_group_info(b, group).lib[0], {
412 enum stone cc = board_at(b, c);
413 if (cc == S_NONE && cc != board_at(b, board_group_info(b, group).lib[1])) {
414 can_pull_out = true;
415 } else if (cc != color) {
416 continue;
419 group_t cg = group_at(b, c);
420 if (cg && cg != group && board_group_info(b, cg).libs > 1)
421 can_connect = true;
423 foreach_neighbor(b, board_group_info(b, group).lib[1], {
424 enum stone cc = board_at(b, c);
425 if (c == board_group_info(b, group).lib[0])
426 continue;
427 if (cc == S_NONE && can_connect) {
428 return true;
429 } else if (cc != color) {
430 continue;
433 group_t cg = group_at(b, c);
434 if (cg && cg != group && board_group_info(b, cg).libs > 1)
435 return (can_connect || can_pull_out);
437 return false;
440 static void
441 check_group_atari(struct board *b, group_t group, enum stone owner,
442 enum stone to_play, struct move_queue *q)
444 for (int i = 0; i < 2; i++) {
445 coord_t lib = board_group_info(b, group).lib[i];
446 assert(board_at(b, lib) == S_NONE);
447 if (!board_is_valid_play(b, to_play, lib))
448 continue;
450 /* Don't play at the spot if it is extremely short
451 * of liberties... */
452 /* XXX: This looks harmful, could significantly
453 * prefer atari to throwin:
455 * XXXOOOOOXX
456 * .OO.....OX
457 * XXXOOOOOOX */
458 #if 0
459 if (neighbor_count_at(b, lib, stone_other(owner)) + immediate_liberty_count(b, lib) < 2)
460 continue;
461 #endif
463 /* If the move is too "lumpy", do not play it:
465 * #######
466 * ..O.X.X <- always play the left one!
467 * OXXXXXX */
468 if (neighbor_count_at(b, lib, stone_other(owner)) + neighbor_count_at(b, lib, S_OFFBOARD) == 3)
469 continue;
471 #ifdef NO_DOOMED_GROUPS
472 /* If the owner can't play at the spot, we don't want
473 * to bother either. */
474 if (is_bad_selfatari(b, owner, lib))
475 continue;
476 #endif
478 /* Of course we don't want to play bad selfatari
479 * ourselves, if we are the attacker... */
480 if (
481 #ifdef NO_DOOMED_GROUPS
482 to_play != owner &&
483 #endif
484 is_bad_selfatari(b, to_play, lib))
485 continue;
487 /* Tasty! Crispy! Good! */
488 mq_add(q, lib, 1<<MQ_L2LIB);
489 mq_nodup(q);
493 static void
494 group_2lib_check(struct playout_policy *p, struct board *b, group_t group, enum stone to_play,
495 struct move_queue *q)
497 enum stone color = board_at(b, group_base(group));
498 assert(color != S_OFFBOARD && color != S_NONE);
500 if (PLDEBUGL(5))
501 fprintf(stderr, "[%s] 2lib check of color %d\n",
502 coord2sstr(group, b), color);
504 /* Do not try to atari groups that cannot be harmed. */
505 if (miai_2lib(b, group, color))
506 return;
508 check_group_atari(b, group, color, to_play, q);
510 /* Can we counter-atari another group, if we are the defender? */
511 if (to_play != color)
512 return;
513 foreach_in_group(b, group) {
514 foreach_neighbor(b, c, {
515 if (board_at(b, c) != stone_other(color))
516 continue;
517 group_t g2 = group_at(b, c);
518 if (board_group_info(b, g2).libs == 1) {
519 /* We can capture a neighbor. */
520 mq_add(q, board_group_info(b, g2).lib[0], 1<<MQ_L2LIB);
521 mq_nodup(q);
522 continue;
524 if (board_group_info(b, g2).libs != 2)
525 continue;
526 check_group_atari(b, g2, color, to_play, q);
528 } foreach_in_group_end;
531 static void
532 local_2lib_check(struct playout_policy *p, struct board *b, struct move *m, struct move_queue *q)
534 /* Does the opponent have just two liberties? */
535 if (board_group_info(b, group_at(b, m->coord)).libs == 2) {
536 group_2lib_check(p, b, group_at(b, m->coord), stone_other(m->color), q);
537 #if 0
538 /* We always prefer to take off an enemy chain liberty
539 * before pulling out ourselves. */
540 /* XXX: We aren't guaranteed to return to that group
541 * later. */
542 if (q->moves)
543 return q->move[fast_random(q->moves)];
544 #endif
547 /* Then he took a third liberty from neighboring chain? */
548 foreach_neighbor(b, m->coord, {
549 group_t g = group_at(b, c);
550 if (!g || board_group_info(b, g).libs != 2)
551 continue;
552 group_2lib_check(p, b, g, stone_other(m->color), q);
555 if (PLDEBUGL(5))
556 mq_print(q, b, "Local 2lib");
559 coord_t
560 fillboard_check(struct playout_policy *p, struct board *b)
562 struct moggy_policy *pp = p->data;
563 unsigned int fbtries = b->flen / 8;
564 if (pp->fillboardtries < fbtries)
565 fbtries = pp->fillboardtries;
567 for (unsigned int i = 0; i < fbtries; i++) {
568 coord_t coord = b->f[fast_random(b->flen)];
569 if (immediate_liberty_count(b, coord) != 4)
570 continue;
571 foreach_diag_neighbor(b, coord) {
572 if (board_at(b, c) != S_NONE)
573 goto next_try;
574 } foreach_diag_neighbor_end;
575 return coord;
576 next_try:;
578 return pass;
581 coord_t
582 playout_moggy_partchoose(struct playout_policy *p, struct board *b, enum stone to_play)
584 struct moggy_policy *pp = p->data;
586 if (PLDEBUGL(5))
587 board_print(b, stderr);
589 /* Ko fight check */
590 if (!is_pass(b->last_ko.coord) && is_pass(b->ko.coord)
591 && b->moves - b->last_ko_age < pp->koage
592 && pp->korate > fast_random(100)) {
593 if (board_is_valid_play(b, to_play, b->last_ko.coord)
594 && !is_bad_selfatari(b, to_play, b->last_ko.coord))
595 return b->last_ko.coord;
598 /* Local checks */
599 if (!is_pass(b->last_move.coord)) {
600 /* Local group in atari? */
601 if (pp->lcapturerate > fast_random(100)) {
602 struct move_queue q; q.moves = 0;
603 local_atari_check(p, b, &b->last_move, &q);
604 if (q.moves > 0)
605 return mq_pick(&q);
608 /* Local group can be PUT in atari? */
609 if (pp->atarirate > fast_random(100)) {
610 struct move_queue q; q.moves = 0;
611 local_2lib_check(p, b, &b->last_move, &q);
612 if (q.moves > 0)
613 return mq_pick(&q);
616 /* Check for patterns we know */
617 if (pp->patternrate > fast_random(100)) {
618 struct move_queue q; q.moves = 0;
619 apply_pattern(p, b, &b->last_move,
620 pp->pattern2 && b->last_move2.coord >= 0 ? &b->last_move2 : NULL,
621 &q);
622 if (q.moves > 0)
623 return mq_pick(&q);
627 /* Global checks */
629 /* Any groups in atari? */
630 if (pp->capturerate > fast_random(100)) {
631 struct move_queue q; q.moves = 0;
632 global_atari_check(p, b, to_play, &q);
633 if (q.moves > 0)
634 return mq_pick(&q);
637 /* Joseki moves? */
638 if (pp->josekirate > fast_random(100)) {
639 struct move_queue q; q.moves = 0;
640 joseki_check(p, b, to_play, &q);
641 if (q.moves > 0)
642 return mq_pick(&q);
645 /* Fill board */
646 if (pp->fillboardtries > 0) {
647 coord_t c = fillboard_check(p, b);
648 if (!is_pass(c))
649 return c;
652 return pass;
655 /* Pick a move from queue q, giving different likelihoods to moves
656 * based on their tags. */
657 coord_t
658 mq_tagged_choose(struct playout_policy *p, struct board *b, enum stone to_play, struct move_queue *q)
660 struct moggy_policy *pp = p->data;
662 /* First, merge all entries for a move. */
663 /* We use a naive O(N^2) since the average length of the queue
664 * is about 1.4. */
665 for (unsigned int i = 0; i < q->moves; i++) {
666 for (unsigned int j = i + 1; j < q->moves; j++) {
667 if (q->move[i] != q->move[j])
668 continue;
669 q->tag[i] |= q->tag[j];
670 q->moves--;
671 q->tag[j] = q->tag[q->moves];
672 q->move[j] = q->move[q->moves];
676 /* Now, construct a probdist. */
677 fixp_t total = 0;
678 fixp_t pd[q->moves];
679 for (unsigned int i = 0; i < q->moves; i++) {
680 double val = 1.0;
681 assert(q->tag[i] != 0);
682 for (int j = 1; j < MQ_MAX; j++)
683 if (q->tag[i] & (1<<j)) {
684 //fprintf(stderr, "%s(%x) %d %f *= %f\n", coord2sstr(q->move[i], b), q->tag[i], j, val, pp->mq_prob[j]);
685 val *= pp->mq_prob[j];
687 pd[i] = double_to_fixp(val);
688 total += pd[i];
690 total += double_to_fixp(pp->tenuki_prob);
692 /* Finally, pick a move! */
693 fixp_t stab = fast_irandom(total);
694 for (unsigned int i = 0; i < q->moves; i++) {
695 //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));
696 if (stab < pd[i])
697 return q->move[i];
698 stab -= pd[i];
701 /* Tenuki. */
702 assert(stab < double_to_fixp(pp->tenuki_prob));
703 return pass;
706 coord_t
707 playout_moggy_fullchoose(struct playout_policy *p, struct board *b, enum stone to_play)
709 struct moggy_policy *pp = p->data;
710 struct move_queue q; q.moves = 0;
712 if (PLDEBUGL(5))
713 board_print(b, stderr);
715 /* Ko fight check */
716 if (!is_pass(b->last_ko.coord) && is_pass(b->ko.coord)
717 && b->moves - b->last_ko_age < pp->koage
718 && pp->korate > fast_random(100)) {
719 if (board_is_valid_play(b, to_play, b->last_ko.coord)
720 && !is_bad_selfatari(b, to_play, b->last_ko.coord))
721 mq_add(&q, b->last_ko.coord, 1<<MQ_KO);
724 /* Local checks */
725 if (!is_pass(b->last_move.coord)) {
726 /* Local group in atari? */
727 if (pp->lcapturerate > fast_random(100)) {
728 local_atari_check(p, b, &b->last_move, &q);
731 /* Local group can be PUT in atari? */
732 if (pp->atarirate > fast_random(100)) {
733 local_2lib_check(p, b, &b->last_move, &q);
736 /* Check for patterns we know */
737 if (pp->patternrate > fast_random(100)) {
738 apply_pattern(p, b, &b->last_move,
739 pp->pattern2 && b->last_move2.coord >= 0 ? &b->last_move2 : NULL,
740 &q);
744 /* Global checks */
746 /* Any groups in atari? */
747 if (pp->capturerate > fast_random(100)) {
748 global_atari_check(p, b, to_play, &q);
751 /* Joseki moves? */
752 if (pp->josekirate > fast_random(100)) {
753 joseki_check(p, b, to_play, &q);
756 #if 0
757 /* Average length of the queue is 1.4 move. */
758 printf("MQL %d ", q.moves);
759 for (unsigned int i = 0; i < q.moves; i++)
760 printf("%s ", coord2sstr(q.move[i], b));
761 printf("\n");
762 #endif
764 if (q.moves > 0)
765 return mq_tagged_choose(p, b, to_play, &q);
767 /* Fill board */
768 if (pp->fillboardtries > 0) {
769 coord_t c = fillboard_check(p, b);
770 if (!is_pass(c))
771 return c;
774 return pass;
778 static coord_t
779 selfatari_cousin(struct board *b, enum stone color, coord_t coord)
781 group_t groups[4]; int groups_n = 0;
782 foreach_neighbor(b, coord, {
783 enum stone s = board_at(b, c);
784 if (s != color) continue;
785 group_t g = group_at(b, c);
786 if (board_group_info(b, g).libs == 2)
787 groups[groups_n++] = g;
790 if (!groups_n)
791 return pass;
792 group_t group = groups[fast_random(groups_n)];
794 coord_t lib2 = board_group_other_lib(b, group, coord);
795 if (is_bad_selfatari(b, color, lib2))
796 return pass;
797 return lib2;
800 void
801 playout_moggy_assess_group(struct playout_policy *p, struct prior_map *map, group_t g, int games)
803 struct moggy_policy *pp = p->data;
804 struct board *b = map->b;
805 struct move_queue q; q.moves = 0;
807 if (board_group_info(b, g).libs > 2)
808 return;
810 if (PLDEBUGL(5)) {
811 fprintf(stderr, "ASSESS of group %s:\n", coord2sstr(g, b));
812 board_print(b, stderr);
815 if (board_group_info(b, g).libs == 2) {
816 if (!pp->atarirate)
817 return;
818 group_2lib_check(p, b, g, map->to_play, &q);
819 while (q.moves--) {
820 coord_t coord = q.move[q.moves];
821 if (PLDEBUGL(5))
822 fprintf(stderr, "1.0: 2lib %s\n", coord2sstr(coord, b));
823 int assess = games / 2;
824 add_prior_value(map, coord, 1, assess);
826 return;
829 /* This group, sir, is in atari! */
831 coord_t ladder = pass;
832 group_atari_check(pp->alwaysccaprate, b, g, map->to_play, &q, &ladder, 0);
833 while (q.moves--) {
834 coord_t coord = q.move[q.moves];
836 /* _Never_ play here if this move plays out
837 * a caught ladder. */
838 if (coord == ladder && !board_playing_ko_threat(b)) {
839 /* Note that the opposite is not guarded against;
840 * we do not advise against capturing a laddered
841 * group (but we don't encourage it either). Such
842 * a move can simplify tactical situations if we
843 * can afford it. */
844 if (map->to_play != board_at(b, g))
845 continue;
846 /* FIXME: We give the malus even if this move
847 * captures another group. */
848 if (PLDEBUGL(5))
849 fprintf(stderr, "0.0: ladder %s\n", coord2sstr(coord, b));
850 add_prior_value(map, coord, 0, games);
851 continue;
854 if (!pp->capturerate && !pp->lcapturerate)
855 continue;
857 if (PLDEBUGL(5))
858 fprintf(stderr, "1.0: atari %s\n", coord2sstr(coord, b));
859 int assess = games * 2;
860 add_prior_value(map, coord, 1, assess);
864 void
865 playout_moggy_assess_one(struct playout_policy *p, struct prior_map *map, coord_t coord, int games)
867 struct moggy_policy *pp = p->data;
868 struct board *b = map->b;
870 if (PLDEBUGL(5)) {
871 fprintf(stderr, "ASSESS of move %s:\n", coord2sstr(coord, b));
872 board_print(b, stderr);
875 /* Is this move a self-atari? */
876 if (pp->selfatarirate) {
877 if (!board_playing_ko_threat(b) && is_bad_selfatari(b, map->to_play, coord)) {
878 if (PLDEBUGL(5))
879 fprintf(stderr, "0.0: self-atari\n");
880 add_prior_value(map, coord, 0, games);
881 if (!pp->selfatari_other)
882 return;
883 /* If we can play on the other liberty of the
884 * endangered group, do! */
885 coord = selfatari_cousin(b, map->to_play, coord);
886 if (is_pass(coord))
887 return;
888 if (PLDEBUGL(5))
889 fprintf(stderr, "1.0: self-atari redirect %s\n", coord2sstr(coord, b));
890 add_prior_value(map, coord, 1.0, games);
891 return;
895 /* Pattern check */
896 if (pp->patternrate) {
897 struct move m = { .color = map->to_play, .coord = coord };
898 if (test_pattern3_here(p, b, &m)) {
899 if (PLDEBUGL(5))
900 fprintf(stderr, "1.0: pattern\n");
901 add_prior_value(map, coord, 1, games);
905 return;
908 void
909 playout_moggy_assess(struct playout_policy *p, struct prior_map *map, int games)
911 struct moggy_policy *pp = p->data;
913 /* First, go through all endangered groups. */
914 for (group_t g = 1; g < board_size2(map->b); g++)
915 if (group_at(map->b, g) == g)
916 playout_moggy_assess_group(p, map, g, games);
918 /* Then, assess individual moves. */
919 if (!pp->patternrate && !pp->selfatarirate)
920 return;
921 foreach_free_point(map->b) {
922 if (map->consider[c])
923 playout_moggy_assess_one(p, map, c, games);
924 } foreach_free_point_end;
927 bool
928 playout_moggy_permit(struct playout_policy *p, struct board *b, struct move *m)
930 struct moggy_policy *pp = p->data;
932 /* The idea is simple for now - never allow self-atari moves.
933 * They suck in general, but this also permits us to actually
934 * handle seki in the playout stage. */
936 if (fast_random(100) >= pp->selfatarirate) {
937 if (PLDEBUGL(5))
938 fprintf(stderr, "skipping sar test\n");
939 return true;
941 bool selfatari = is_bad_selfatari(b, m->color, m->coord);
942 if (selfatari) {
943 if (PLDEBUGL(5))
944 fprintf(stderr, "__ Prohibiting self-atari %s %s\n",
945 stone2str(m->color), coord2sstr(m->coord, b));
946 if (pp->selfatari_other) {
947 /* Ok, try the other liberty of the atari'd group. */
948 coord_t c = selfatari_cousin(b, m->color, m->coord);
949 if (is_pass(c)) return false;
950 if (PLDEBUGL(5))
951 fprintf(stderr, "___ Redirecting to other lib %s\n",
952 coord2sstr(c, b));
953 m->coord = c;
954 return true;
956 return false;
958 return true;
962 struct playout_policy *
963 playout_moggy_init(char *arg, struct board *b, struct joseki_dict *jdict)
965 struct playout_policy *p = calloc2(1, sizeof(*p));
966 struct moggy_policy *pp = calloc2(1, sizeof(*pp));
967 p->data = pp;
968 p->choose = playout_moggy_partchoose;
969 p->assess = playout_moggy_assess;
970 p->permit = playout_moggy_permit;
972 pp->jdict = jdict;
974 int rate = 90;
976 pp->lcapturerate = pp->atarirate = pp->capturerate = pp->patternrate
977 = pp->selfatarirate = pp->josekirate = -1U;
978 pp->korate = 0; pp->koage = 4;
979 pp->alwaysccaprate = 0;
980 pp->selfatari_other = true;
982 /* C is stupid. */
983 double mq_prob_default[MQ_MAX] = {
984 [MQ_KO] = 6.0,
985 [MQ_LATARI] = 5.0,
986 [MQ_L2LIB] = 4.0,
987 [MQ_PAT3] = 3.0,
988 [MQ_GATARI] = 2.0,
989 [MQ_JOSEKI] = 1.0,
991 memcpy(pp->mq_prob, mq_prob_default, sizeof(pp->mq_prob));
993 if (arg) {
994 char *optspec, *next = arg;
995 while (*next) {
996 optspec = next;
997 next += strcspn(next, ":");
998 if (*next) { *next++ = 0; } else { *next = 0; }
1000 char *optname = optspec;
1001 char *optval = strchr(optspec, '=');
1002 if (optval) *optval++ = 0;
1004 if (!strcasecmp(optname, "debug") && optval) {
1005 p->debug_level = atoi(optval);
1006 } else if (!strcasecmp(optname, "lcapturerate") && optval) {
1007 pp->lcapturerate = atoi(optval);
1008 } else if (!strcasecmp(optname, "atarirate") && optval) {
1009 pp->atarirate = atoi(optval);
1010 } else if (!strcasecmp(optname, "capturerate") && optval) {
1011 pp->capturerate = atoi(optval);
1012 } else if (!strcasecmp(optname, "patternrate") && optval) {
1013 pp->patternrate = atoi(optval);
1014 } else if (!strcasecmp(optname, "selfatarirate") && optval) {
1015 pp->selfatarirate = atoi(optval);
1016 } else if (!strcasecmp(optname, "korate") && optval) {
1017 pp->korate = atoi(optval);
1018 } else if (!strcasecmp(optname, "josekirate") && optval) {
1019 pp->josekirate = atoi(optval);
1020 } else if (!strcasecmp(optname, "alwaysccaprate") && optval) {
1021 pp->alwaysccaprate = atoi(optval);
1022 } else if (!strcasecmp(optname, "rate") && optval) {
1023 rate = atoi(optval);
1024 } else if (!strcasecmp(optname, "fillboardtries")) {
1025 pp->fillboardtries = atoi(optval);
1026 } else if (!strcasecmp(optname, "koage") && optval) {
1027 pp->koage = atoi(optval);
1028 } else if (!strcasecmp(optname, "pattern2")) {
1029 pp->pattern2 = optval && *optval == '0' ? false : true;
1030 } else if (!strcasecmp(optname, "selfatari_other")) {
1031 pp->selfatari_other = optval && *optval == '0' ? false : true;
1032 } else if (!strcasecmp(optname, "capcheckall")) {
1033 pp->capcheckall = optval && *optval == '0' ? false : true;
1034 } else if (!strcasecmp(optname, "fullchoose")) {
1035 p->choose = optval && *optval == '0' ? playout_moggy_partchoose : playout_moggy_fullchoose;
1036 } else if (!strcasecmp(optname, "mqprob") && optval) {
1037 /* KO%LATARI%L2LIB%PAT3%GATARI%JOSEKI */
1038 for (int i = 1; *optval && i < MQ_MAX; i++, optval += strcspn(optval, "%")) {
1039 optval++;
1040 pp->mq_prob[i] = atof(optval);
1042 } else if (!strcasecmp(optname, "tenukiprob") && optval) {
1043 pp->tenuki_prob = atof(optval);
1044 } else {
1045 fprintf(stderr, "playout-moggy: Invalid policy argument %s or missing value\n", optname);
1046 exit(1);
1050 if (pp->lcapturerate == -1U) pp->lcapturerate = rate;
1051 if (pp->atarirate == -1U) pp->atarirate = rate;
1052 if (pp->capturerate == -1U) pp->capturerate = rate;
1053 if (pp->patternrate == -1U) pp->patternrate = rate;
1054 if (pp->selfatarirate == -1U) pp->selfatarirate = rate;
1055 if (pp->korate == -1U) pp->korate = rate;
1056 if (pp->josekirate == -1U) pp->josekirate = rate;
1057 if (pp->alwaysccaprate == -1U) pp->alwaysccaprate = rate;
1059 pattern3s_init(&pp->patterns, moggy_patterns_src, moggy_patterns_src_n);
1061 return p;