Moggy test_pattern3_here(): Disable spurious debug print
[pachi.git] / uct / dynkomi.c
blob2dec7a6b9152a218ea0cd7dd40cab155c16091fa
1 #define DEBUG
2 #include <assert.h>
3 #include <math.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 #include "board.h"
9 #include "debug.h"
10 #include "tactics/util.h"
11 #include "uct/dynkomi.h"
12 #include "uct/internal.h"
13 #include "uct/tree.h"
16 static void
17 generic_done(struct uct_dynkomi *d)
19 if (d->data) free(d->data);
20 free(d);
24 /* NONE dynkomi strategy - never fiddle with komi values. */
26 struct uct_dynkomi *
27 uct_dynkomi_init_none(struct uct *u, char *arg, struct board *b)
29 struct uct_dynkomi *d = calloc2(1, sizeof(*d));
30 d->uct = u;
31 d->permove = NULL;
32 d->persim = NULL;
33 d->done = generic_done;
34 d->data = NULL;
36 if (arg) {
37 fprintf(stderr, "uct: Dynkomi method none accepts no arguments\n");
38 exit(1);
41 return d;
45 /* LINEAR dynkomi strategy - Linearly Decreasing Handicap Compensation. */
46 /* At move 0, we impose extra komi of handicap_count*handicap_value, then
47 * we linearly decrease this extra komi throughout the game down to 0
48 * at @moves moves. Towards the end of the game the linear compensation
49 * becomes zero but we increase the extra komi when winning big. This reduces
50 * the number of point-wasting moves and makes the game more enjoyable for humans. */
52 struct dynkomi_linear {
53 int handicap_value[S_MAX];
54 int moves[S_MAX];
55 bool rootbased;
56 /* Increase the extra komi if my win ratio > green_zone but always
57 * keep extra_komi <= komi_ratchet. komi_ratchet starts infinite but decreases
58 * when we give too much extra komi and this puts us back < orange_zone.
59 * This is meant only to increase the territory margin when playing against
60 * weaker opponents. We never take negative komi when losing. The ratchet helps
61 * avoiding oscillations and keeping us above orange_zone.
62 * To disable the adaptive phase, set green_zone=2. */
63 floating_t komi_ratchet;
64 floating_t green_zone;
65 floating_t orange_zone;
66 floating_t drop_step;
69 static floating_t
70 linear_simple(struct dynkomi_linear *l, struct board *b, enum stone color)
72 int lmoves = l->moves[color];
73 floating_t base_komi = board_effective_handicap(b, l->handicap_value[color]);
74 return base_komi * (lmoves - b->moves) / lmoves;
77 static floating_t
78 linear_permove(struct uct_dynkomi *d, struct board *b, struct tree *tree)
80 struct dynkomi_linear *l = d->data;
81 enum stone color = d->uct->pondering ? tree->root_color : stone_other(tree->root_color);
82 int lmoves = l->moves[color];
84 if (b->moves < lmoves)
85 return linear_simple(l, b, color);
87 /* Allow simple adaptation in extreme endgame situations. */
89 floating_t extra_komi = floor(tree->extra_komi);
91 /* Do not take decisions on unstable value. */
92 if (tree->root->u.playouts < GJ_MINGAMES)
93 return extra_komi;
95 floating_t my_value = tree_node_get_value(tree, 1, tree->root->u.value);
96 /* We normalize komi as in komi_by_value(), > 0 when winning. */
97 extra_komi = komi_by_color(extra_komi, color);
98 if (extra_komi < 0 && DEBUGL(3))
99 fprintf(stderr, "XXX: extra_komi %.3f < 0 (color %s tree ek %.3f)\n", extra_komi, stone2str(color), tree->extra_komi);
100 // assert(extra_komi >= 0);
101 floating_t orig_komi = extra_komi;
103 if (my_value < 0.5 && l->komi_ratchet > 0 && l->komi_ratchet != INFINITY) {
104 if (DEBUGL(0))
105 fprintf(stderr, "losing %f extra komi %.1f ratchet %.1f -> 0\n",
106 my_value, extra_komi, l->komi_ratchet);
107 /* Disable dynkomi completely, too dangerous in this game. */
108 extra_komi = l->komi_ratchet = 0;
110 } else if (my_value < l->orange_zone && extra_komi > 0) {
111 extra_komi = l->komi_ratchet = fmax(extra_komi - l->drop_step, 0.0);
112 if (extra_komi != orig_komi && DEBUGL(3))
113 fprintf(stderr, "dropping to %f, extra komi %.1f -> %.1f\n",
114 my_value, orig_komi, extra_komi);
116 } else if (my_value > l->green_zone && extra_komi + 1 <= l->komi_ratchet) {
117 extra_komi += 1;
118 if (extra_komi != orig_komi && DEBUGL(3))
119 fprintf(stderr, "winning %f extra_komi %.1f -> %.1f, ratchet %.1f\n",
120 my_value, orig_komi, extra_komi, l->komi_ratchet);
122 return komi_by_color(extra_komi, color);
125 static floating_t
126 linear_persim(struct uct_dynkomi *d, struct board *b, struct tree *tree, struct tree_node *node)
128 struct dynkomi_linear *l = d->data;
129 if (l->rootbased)
130 return tree->extra_komi;
132 /* We don't reuse computed value from tree->extra_komi,
133 * since we want to use value correct for this node depth.
134 * This also means the values will stay correct after
135 * node promotion. */
137 enum stone color = d->uct->pondering ? tree->root_color : stone_other(tree->root_color);
138 int lmoves = l->moves[color];
139 if (b->moves < lmoves)
140 return linear_simple(l, b, color);
141 return tree->extra_komi;
144 struct uct_dynkomi *
145 uct_dynkomi_init_linear(struct uct *u, char *arg, struct board *b)
147 struct uct_dynkomi *d = calloc2(1, sizeof(*d));
148 d->uct = u;
149 d->permove = linear_permove;
150 d->persim = linear_persim;
151 d->done = generic_done;
153 struct dynkomi_linear *l = calloc2(1, sizeof(*l));
154 d->data = l;
156 /* Force white to feel behind and try harder, but not to the
157 * point of resigning immediately in high handicap games.
158 * By move 100 white should still be behind but should have
159 * caught up enough to avoid resigning. */
160 int moves = board_large(b) ? 100 : 50;
161 if (!board_small(b)) {
162 l->moves[S_BLACK] = moves;
163 l->moves[S_WHITE] = moves;
166 /* The real value of one stone is twice the komi so about 15 points.
167 * But use a lower value to avoid being too pessimistic as black
168 * or too optimistic as white. */
169 l->handicap_value[S_BLACK] = 8;
170 l->handicap_value[S_WHITE] = 1;
172 l->komi_ratchet = INFINITY;
173 l->green_zone = 0.85;
174 l->orange_zone = 0.8;
175 l->drop_step = 4.0;
177 if (arg) {
178 char *optspec, *next = arg;
179 while (*next) {
180 optspec = next;
181 next += strcspn(next, ":");
182 if (*next) { *next++ = 0; } else { *next = 0; }
184 char *optname = optspec;
185 char *optval = strchr(optspec, '=');
186 if (optval) *optval++ = 0;
188 if (!strcasecmp(optname, "moves") && optval) {
189 /* Dynamic komi in handicap game; linearly
190 * decreases to basic settings until move
191 * #optval. moves=blackmoves%whitemoves */
192 for (int i = S_BLACK; *optval && i <= S_WHITE; i++) {
193 l->moves[i] = atoi(optval);
194 optval += strcspn(optval, "%");
195 if (*optval) optval++;
197 } else if (!strcasecmp(optname, "handicap_value") && optval) {
198 /* Point value of single handicap stone,
199 * for dynkomi computation. */
200 for (int i = S_BLACK; *optval && i <= S_WHITE; i++) {
201 l->handicap_value[i] = atoi(optval);
202 optval += strcspn(optval, "%");
203 if (*optval) optval++;
205 } else if (!strcasecmp(optname, "rootbased")) {
206 /* If set, the extra komi applied will be
207 * the same for all simulations within a move,
208 * instead of being same for all simulations
209 * within the tree node. */
210 l->rootbased = !optval || atoi(optval);
211 } else if (!strcasecmp(optname, "green_zone") && optval) {
212 /* Increase komi when win ratio is above green_zone */
213 l->green_zone = atof(optval);
214 } else if (!strcasecmp(optname, "orange_zone") && optval) {
215 /* Decrease komi when > 0 and win ratio is below orange_zone */
216 l->orange_zone = atof(optval);
217 } else if (!strcasecmp(optname, "drop_step") && optval) {
218 /* Decrease komi by drop_step points */
219 l->drop_step = atof(optval);
220 } else {
221 fprintf(stderr, "uct: Invalid dynkomi argument %s or missing value\n", optname);
222 exit(1);
227 return d;
231 /* ADAPTIVE dynkomi strategy - Adaptive Situational Compensation */
232 /* We adapt the komi based on current situation:
233 * (i) score-based: We maintain the average score outcome of our
234 * games and adjust the komi by a fractional step towards the expected
235 * score;
236 * (ii) value-based: While winrate is above given threshold, adjust
237 * the komi by a fixed step in the appropriate direction.
238 * These adjustments can be
239 * (a) Move-stepped, new extra komi value is always set only at the
240 * beginning of the tree search for next move;
241 * (b) Continuous, new extra komi value is periodically re-determined
242 * and adjusted throughout a single tree search. */
244 struct dynkomi_adaptive {
245 /* Do not take measured average score into regard for
246 * first @lead_moves - the variance is just too much.
247 * (Instead, we consider the handicap-based komi provided
248 * by linear dynkomi.) */
249 int lead_moves;
250 /* Maximum komi to pretend the opponent to give. */
251 floating_t max_losing_komi;
252 /* Game portion at which losing komi is not allowed anymore. */
253 floating_t losing_komi_stop;
254 /* Turn off dynkomi at the (perceived) closing of the game
255 * (last few moves). */
256 bool no_komi_at_game_end;
257 /* Alternative game portion determination. */
258 bool adapt_aport;
259 floating_t (*indicator)(struct uct_dynkomi *d, struct board *b, struct tree *tree, enum stone color);
261 /* Value-based adaptation. */
262 floating_t zone_red, zone_green;
263 int score_step;
264 floating_t score_step_byavg; // use portion of average score as increment
265 bool use_komi_ratchet;
266 bool losing_komi_ratchet; // ratchet even losing komi
267 int komi_ratchet_maxage;
268 // runtime, not configuration:
269 int komi_ratchet_age;
270 floating_t komi_ratchet;
272 /* Score-based adaptation. */
273 floating_t (*adapter)(struct uct_dynkomi *d, struct board *b);
274 floating_t adapt_base; // [0,1)
275 /* Sigmoid adaptation rate parameter; see below for details. */
276 floating_t adapt_phase; // [0,1]
277 floating_t adapt_rate; // [1,infty)
278 /* Linear adaptation rate parameter. */
279 int adapt_moves;
280 floating_t adapt_dir; // [-1,1]
282 #define TRUSTWORTHY_KOMI_PLAYOUTS 200
284 static floating_t
285 board_game_portion(struct dynkomi_adaptive *a, struct board *b)
287 if (!a->adapt_aport) {
288 int total_moves = b->moves + 2 * board_estimated_moves_left(b);
289 return (floating_t) b->moves / total_moves;
290 } else {
291 int brsize = board_size(b) - 2;
292 return 1.0 - (floating_t) b->flen / (brsize * brsize);
296 static floating_t
297 adapter_sigmoid(struct uct_dynkomi *d, struct board *b)
299 struct dynkomi_adaptive *a = d->data;
300 /* Figure out how much to adjust the komi based on the game
301 * stage. The adaptation rate is 0 at the beginning,
302 * at game stage a->adapt_phase crosses though 0.5 and
303 * approaches 1 at the game end; the slope is controlled
304 * by a->adapt_rate. */
305 floating_t game_portion = board_game_portion(a, b);
306 floating_t l = game_portion - a->adapt_phase;
307 return 1.0 / (1.0 + exp(-a->adapt_rate * l));
310 static floating_t
311 adapter_linear(struct uct_dynkomi *d, struct board *b)
313 struct dynkomi_adaptive *a = d->data;
314 /* Figure out how much to adjust the komi based on the game
315 * stage. We just linearly increase/decrease the adaptation
316 * rate for first N moves. */
317 if (b->moves > a->adapt_moves)
318 return 0;
319 if (a->adapt_dir < 0)
320 return 1 - (- a->adapt_dir) * b->moves / a->adapt_moves;
321 else
322 return a->adapt_dir * b->moves / a->adapt_moves;
325 static floating_t
326 komi_by_score(struct uct_dynkomi *d, struct board *b, struct tree *tree, enum stone color)
328 struct dynkomi_adaptive *a = d->data;
329 if (d->score.playouts < TRUSTWORTHY_KOMI_PLAYOUTS)
330 return tree->extra_komi;
332 struct move_stats score = d->score;
333 /* Almost-reset tree->score to gather fresh stats. */
334 d->score.playouts = 1;
336 /* Look at average score and push extra_komi in that direction. */
337 floating_t p = a->adapter(d, b);
338 p = a->adapt_base + p * (1 - a->adapt_base);
339 if (p > 0.9) p = 0.9; // don't get too eager!
340 floating_t extra_komi = tree->extra_komi + p * score.value;
341 if (DEBUGL(3))
342 fprintf(stderr, "mC += %f * %f\n", p, score.value);
343 return extra_komi;
346 static floating_t
347 komi_by_value(struct uct_dynkomi *d, struct board *b, struct tree *tree, enum stone color)
349 struct dynkomi_adaptive *a = d->data;
350 if (d->value.playouts < TRUSTWORTHY_KOMI_PLAYOUTS)
351 return tree->extra_komi;
353 struct move_stats value = d->value;
354 /* Almost-reset tree->value to gather fresh stats. */
355 d->value.playouts = 1;
356 /* Correct color POV. */
357 if (color == S_WHITE)
358 value.value = 1 - value.value;
360 /* We have three "value zones":
361 * red zone | yellow zone | green zone
362 * ~45% ~60%
363 * red zone: reduce komi
364 * yellow zone: do not touch komi
365 * green zone: enlage komi.
367 * Also, at some point komi will be tuned in such way
368 * that it will be in green zone but increasing it will
369 * be unfeasible. Thus, we have a _ratchet_ - we will
370 * remember the last komi that has put us into the
371 * red zone, and not use it or go over it. We use the
372 * ratchet only when giving extra komi, we always want
373 * to try to reduce extra komi we take.
375 * TODO: Make the ratchet expire after a while. */
377 /* We use komi_by_color() first to normalize komi
378 * additions/subtractions, then apply it again on
379 * return value to restore original komi parity. */
380 /* Positive extra_komi means that we are _giving_
381 * komi (winning), negative extra_komi is _taking_
382 * komi (losing). */
383 floating_t extra_komi = komi_by_color(tree->extra_komi, color);
384 int score_step_red = -a->score_step;
385 int score_step_green = a->score_step;
387 if (a->score_step_byavg != 0) {
388 struct move_stats score = d->score;
389 /* Almost-reset tree->score to gather fresh stats. */
390 d->score.playouts = 1;
391 /* Correct color POV. */
392 if (color == S_WHITE)
393 score.value = - score.value;
394 if (score.value > 0)
395 score_step_green = round(score.value * a->score_step_byavg);
396 else
397 score_step_red = round(-score.value * a->score_step_byavg);
398 if (score_step_green < 0 || score_step_red > 0) {
399 /* The steps are in bad direction - keep still. */
400 return komi_by_color(extra_komi, color);
404 /* Wear out the ratchet. */
405 if (a->use_komi_ratchet && a->komi_ratchet_maxage > 0) {
406 a->komi_ratchet_age += value.playouts;
407 if (a->komi_ratchet_age > a->komi_ratchet_maxage) {
408 a->komi_ratchet = 1000;
409 a->komi_ratchet_age = 0;
413 if (value.value < a->zone_red) {
414 /* Red zone. Take extra komi. */
415 if (DEBUGL(3))
416 fprintf(stderr, "[red] %f, step %d | komi ratchet %f age %d/%d -> %f\n",
417 value.value, score_step_red, a->komi_ratchet, a->komi_ratchet_age, a->komi_ratchet_maxage, extra_komi);
418 if (a->losing_komi_ratchet || extra_komi > 0) {
419 a->komi_ratchet = extra_komi;
420 a->komi_ratchet_age = 0;
422 extra_komi += score_step_red;
423 return komi_by_color(extra_komi, color);
425 } else if (value.value < a->zone_green) {
426 /* Yellow zone, do nothing. */
427 return komi_by_color(extra_komi, color);
429 } else {
430 /* Green zone. Give extra komi. */
431 if (DEBUGL(3))
432 fprintf(stderr, "[green] %f, step %d | komi ratchet %f age %d/%d\n",
433 value.value, score_step_green, a->komi_ratchet, a->komi_ratchet_age, a->komi_ratchet_maxage);
434 extra_komi += score_step_green;
435 if (a->use_komi_ratchet && extra_komi >= a->komi_ratchet)
436 extra_komi = a->komi_ratchet - 1;
437 return komi_by_color(extra_komi, color);
441 static floating_t
442 bounded_komi(struct dynkomi_adaptive *a, struct board *b,
443 enum stone color, floating_t komi, floating_t max_losing_komi)
445 /* At the end of game, disallow losing komi. */
446 if (komi_by_color(komi, color) < 0
447 && board_game_portion(a, b) > a->losing_komi_stop)
448 return 0;
450 /* Get lower bound on komi we take so that we don't underperform
451 * too much. */
452 floating_t min_komi = komi_by_color(- max_losing_komi, color);
454 if (komi_by_color(komi - min_komi, color) > 0)
455 return komi;
456 else
457 return min_komi;
460 static floating_t
461 adaptive_permove(struct uct_dynkomi *d, struct board *b, struct tree *tree)
463 struct dynkomi_adaptive *a = d->data;
464 enum stone color = stone_other(tree->root_color);
466 /* We do not use extra komi at the game end - we are not
467 * to fool ourselves at this point. */
468 if (a->no_komi_at_game_end && board_estimated_moves_left(b) <= MIN_MOVES_LEFT) {
469 tree->use_extra_komi = false;
470 return 0;
473 if (DEBUGL(4))
474 fprintf(stderr, "m %d/%d ekomi %f permove %f/%d\n",
475 b->moves, a->lead_moves, tree->extra_komi,
476 d->score.value, d->score.playouts);
478 if (b->moves <= a->lead_moves)
479 return bounded_komi(a, b, color,
480 board_effective_handicap(b, 7 /* XXX */),
481 a->max_losing_komi);
483 floating_t komi = a->indicator(d, b, tree, color);
484 if (DEBUGL(4))
485 fprintf(stderr, "dynkomi: %f -> %f\n", tree->extra_komi, komi);
486 return bounded_komi(a, b, color, komi, a->max_losing_komi);
489 static floating_t
490 adaptive_persim(struct uct_dynkomi *d, struct board *b, struct tree *tree, struct tree_node *node)
492 return tree->extra_komi;
495 struct uct_dynkomi *
496 uct_dynkomi_init_adaptive(struct uct *u, char *arg, struct board *b)
498 struct uct_dynkomi *d = calloc2(1, sizeof(*d));
499 d->uct = u;
500 d->permove = adaptive_permove;
501 d->persim = adaptive_persim;
502 d->done = generic_done;
504 struct dynkomi_adaptive *a = calloc2(1, sizeof(*a));
505 d->data = a;
507 a->lead_moves = board_large(b) ? 20 : 4; // XXX
508 a->max_losing_komi = 30;
509 a->losing_komi_stop = 1.0f;
510 a->no_komi_at_game_end = true;
511 a->indicator = komi_by_value;
513 a->adapter = adapter_sigmoid;
514 a->adapt_rate = -18;
515 a->adapt_phase = 0.65;
516 a->adapt_moves = 200;
517 a->adapt_dir = -0.5;
519 a->zone_red = 0.45;
520 a->zone_green = 0.50;
521 a->score_step = 1;
522 a->use_komi_ratchet = true;
523 a->komi_ratchet_maxage = 0;
524 a->komi_ratchet = 1000;
526 if (arg) {
527 char *optspec, *next = arg;
528 while (*next) {
529 optspec = next;
530 next += strcspn(next, ":");
531 if (*next) { *next++ = 0; } else { *next = 0; }
533 char *optname = optspec;
534 char *optval = strchr(optspec, '=');
535 if (optval) *optval++ = 0;
537 if (!strcasecmp(optname, "lead_moves") && optval) {
538 /* Do not adjust komi adaptively for first
539 * N moves. */
540 a->lead_moves = atoi(optval);
541 } else if (!strcasecmp(optname, "max_losing_komi") && optval) {
542 a->max_losing_komi = atof(optval);
543 } else if (!strcasecmp(optname, "losing_komi_stop") && optval) {
544 a->losing_komi_stop = atof(optval);
545 } else if (!strcasecmp(optname, "no_komi_at_game_end")) {
546 a->no_komi_at_game_end = !optval || atoi(optval);
547 } else if (!strcasecmp(optname, "indicator")) {
548 /* Adaptatation indicator - how to decide
549 * the adaptation rate and direction. */
550 if (!strcasecmp(optval, "value")) {
551 /* Winrate w/ komi so far. */
552 a->indicator = komi_by_value;
553 } else if (!strcasecmp(optval, "score")) {
554 /* Expected score w/ current komi. */
555 a->indicator = komi_by_score;
556 } else {
557 fprintf(stderr, "UCT: Invalid indicator %s\n", optval);
558 exit(1);
561 /* value indicator settings */
562 } else if (!strcasecmp(optname, "zone_red") && optval) {
563 a->zone_red = atof(optval);
564 } else if (!strcasecmp(optname, "zone_green") && optval) {
565 a->zone_green = atof(optval);
566 } else if (!strcasecmp(optname, "score_step") && optval) {
567 a->score_step = atoi(optval);
568 } else if (!strcasecmp(optname, "score_step_byavg") && optval) {
569 a->score_step_byavg = atof(optval);
570 } else if (!strcasecmp(optname, "use_komi_ratchet")) {
571 a->use_komi_ratchet = !optval || atoi(optval);
572 } else if (!strcasecmp(optname, "losing_komi_ratchet")) {
573 a->losing_komi_ratchet = !optval || atoi(optval);
574 } else if (!strcasecmp(optname, "komi_ratchet_age") && optval) {
575 a->komi_ratchet_maxage = atoi(optval);
577 /* score indicator settings */
578 } else if (!strcasecmp(optname, "adapter") && optval) {
579 /* Adaptatation method. */
580 if (!strcasecmp(optval, "sigmoid")) {
581 a->adapter = adapter_sigmoid;
582 } else if (!strcasecmp(optval, "linear")) {
583 a->adapter = adapter_linear;
584 } else {
585 fprintf(stderr, "UCT: Invalid adapter %s\n", optval);
586 exit(1);
588 } else if (!strcasecmp(optname, "adapt_base") && optval) {
589 /* Adaptation base rate; see above. */
590 a->adapt_base = atof(optval);
591 } else if (!strcasecmp(optname, "adapt_rate") && optval) {
592 /* Adaptation slope; see above. */
593 a->adapt_rate = atof(optval);
594 } else if (!strcasecmp(optname, "adapt_phase") && optval) {
595 /* Adaptation phase shift; see above. */
596 a->adapt_phase = atof(optval);
597 } else if (!strcasecmp(optname, "adapt_moves") && optval) {
598 /* Adaptation move amount; see above. */
599 a->adapt_moves = atoi(optval);
600 } else if (!strcasecmp(optname, "adapt_aport")) {
601 a->adapt_aport = !optval || atoi(optval);
602 } else if (!strcasecmp(optname, "adapt_dir") && optval) {
603 /* Adaptation direction vector; see above. */
604 a->adapt_dir = atof(optval);
606 } else {
607 fprintf(stderr, "uct: Invalid dynkomi argument %s or missing value\n", optname);
608 exit(1);
613 return d;