stats_add_result_decay(): Fix division by zero in case of decay==1
[pachi.git] / uct / dynkomi.c
blob8085007289bf38fcffb83b3336833acf097ed5f2
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_permove(struct uct_dynkomi *d, struct board *b, struct tree *tree)
72 struct dynkomi_linear *l = d->data;
73 enum stone color = d->uct->pondering ? tree->root_color : stone_other(tree->root_color);
74 int lmoves = l->moves[color];
75 floating_t extra_komi;
77 if (b->moves < lmoves) {
78 floating_t base_komi = board_effective_handicap(b, l->handicap_value[color]);
79 extra_komi = base_komi * (lmoves - b->moves) / lmoves;
80 } else {
81 extra_komi = 0;
84 /* Do not adjust values in the game beginning. */
85 if (b->moves < lmoves) return extra_komi;
87 /* Do not take decisions on unstable value. */
88 if (tree->root->u.playouts < GJ_MINGAMES) return extra_komi;
90 floating_t my_value = tree_node_get_value(tree, 1, tree->root->u.value);
91 /* We normalize komi as in komi_by_value(), > 0 when winning. */
92 extra_komi = komi_by_color(extra_komi, color);
93 assert(extra_komi >= 0);
95 if (my_value < 0.5 && l->komi_ratchet > 0 && l->komi_ratchet != INFINITY) {
96 if (DEBUGL(0))
97 fprintf(stderr, "losing %f extra %.1f ratchet %.1f -> 0\n",
98 my_value, extra_komi, l->komi_ratchet);
99 /* Disable dynkomi completely, too dangerous in this game. */
100 extra_komi = l->komi_ratchet = 0;
102 } else if (my_value < l->orange_zone && extra_komi > 0) {
103 extra_komi = l->komi_ratchet = fmax(extra_komi - l->drop_step, 0.0);
104 if (DEBUGL(3))
105 fprintf(stderr, "dropping to %f ratchet -> %.1f\n",
106 my_value, extra_komi);
108 } else if (my_value > l->green_zone && extra_komi +1 <= l->komi_ratchet) {
109 extra_komi += 1;
110 if (DEBUGL(3))
111 fprintf(stderr, "winning %f extra_komi -> %.1f, ratchet %.1f\n",
112 my_value, extra_komi, l->komi_ratchet);
114 return komi_by_color(extra_komi, color);
117 static floating_t
118 linear_persim(struct uct_dynkomi *d, struct board *b, struct tree *tree, struct tree_node *node)
120 struct dynkomi_linear *l = d->data;
121 if (l->rootbased)
122 return tree->extra_komi;
123 /* We don't reuse computed value from tree->extra_komi,
124 * since we want to use value correct for this node depth.
125 * This also means the values will stay correct after
126 * node promotion. */
127 return linear_permove(d, b, tree);
130 struct uct_dynkomi *
131 uct_dynkomi_init_linear(struct uct *u, char *arg, struct board *b)
133 struct uct_dynkomi *d = calloc2(1, sizeof(*d));
134 d->uct = u;
135 d->permove = linear_permove;
136 d->persim = linear_persim;
137 d->done = generic_done;
139 struct dynkomi_linear *l = calloc2(1, sizeof(*l));
140 d->data = l;
142 /* Force white to feel behind and try harder, but not to the
143 * point of resigning immediately in high handicap games.
144 * By move 100 white should still be behind but should have
145 * caught up enough to avoid resigning. */
146 if (board_large(b)) {
147 l->moves[S_BLACK] = 100;
148 l->moves[S_WHITE] = 50;
150 /* The real value of one stone is twice the komi so about 15 points.
151 * But use a lower value to avoid being too pessimistic as black
152 * or too optimistic as white. */
153 l->handicap_value[S_BLACK] = 8;
154 l->handicap_value[S_WHITE] = 1;
156 l->komi_ratchet = INFINITY;
157 l->green_zone = 0.85;
158 l->orange_zone = 0.8;
159 l->drop_step = 4.0;
161 if (arg) {
162 char *optspec, *next = arg;
163 while (*next) {
164 optspec = next;
165 next += strcspn(next, ":");
166 if (*next) { *next++ = 0; } else { *next = 0; }
168 char *optname = optspec;
169 char *optval = strchr(optspec, '=');
170 if (optval) *optval++ = 0;
172 if (!strcasecmp(optname, "moves") && optval) {
173 /* Dynamic komi in handicap game; linearly
174 * decreases to basic settings until move
175 * #optval. moves=blackmoves%whitemoves */
176 for (int i = S_BLACK; *optval && i <= S_WHITE; i++) {
177 l->moves[i] = atoi(optval);
178 optval += strcspn(optval, "%");
179 if (*optval) optval++;
181 } else if (!strcasecmp(optname, "handicap_value") && optval) {
182 /* Point value of single handicap stone,
183 * for dynkomi computation. */
184 for (int i = S_BLACK; *optval && i <= S_WHITE; i++) {
185 l->handicap_value[i] = atoi(optval);
186 optval += strcspn(optval, "%");
187 if (*optval) optval++;
189 } else if (!strcasecmp(optname, "rootbased")) {
190 /* If set, the extra komi applied will be
191 * the same for all simulations within a move,
192 * instead of being same for all simulations
193 * within the tree node. */
194 l->rootbased = !optval || atoi(optval);
195 } else if (!strcasecmp(optname, "green_zone") && optval) {
196 /* Increase komi when win ratio is above green_zone */
197 l->green_zone = atof(optval);
198 } else if (!strcasecmp(optname, "orange_zone") && optval) {
199 /* Decrease komi when > 0 and win ratio is below orange_zone */
200 l->orange_zone = atof(optval);
201 } else if (!strcasecmp(optname, "drop_step") && optval) {
202 /* Decrease komi by drop_step points */
203 l->drop_step = atof(optval);
204 } else {
205 fprintf(stderr, "uct: Invalid dynkomi argument %s or missing value\n", optname);
206 exit(1);
211 return d;
215 /* ADAPTIVE dynkomi strategy - Adaptive Situational Compensation */
216 /* We adapt the komi based on current situation:
217 * (i) score-based: We maintain the average score outcome of our
218 * games and adjust the komi by a fractional step towards the expected
219 * score;
220 * (ii) value-based: While winrate is above given threshold, adjust
221 * the komi by a fixed step in the appropriate direction.
222 * These adjustments can be
223 * (a) Move-stepped, new extra komi value is always set only at the
224 * beginning of the tree search for next move;
225 * (b) Continuous, new extra komi value is periodically re-determined
226 * and adjusted throughout a single tree search. */
228 struct dynkomi_adaptive {
229 /* Do not take measured average score into regard for
230 * first @lead_moves - the variance is just too much.
231 * (Instead, we consider the handicap-based komi provided
232 * by linear dynkomi.) */
233 int lead_moves;
234 /* Maximum komi to pretend the opponent to give. */
235 floating_t max_losing_komi;
236 /* Game portion at which losing komi is not allowed anymore. */
237 floating_t losing_komi_stop;
238 /* Alternative game portion determination. */
239 bool adapt_aport;
240 floating_t (*indicator)(struct uct_dynkomi *d, struct board *b, struct tree *tree, enum stone color);
242 /* Value-based adaptation. */
243 floating_t zone_red, zone_green;
244 int score_step;
245 floating_t score_step_byavg; // use portion of average score as increment
246 bool use_komi_ratchet;
247 bool losing_komi_ratchet; // ratchet even losing komi
248 int komi_ratchet_maxage;
249 // runtime, not configuration:
250 int komi_ratchet_age;
251 floating_t komi_ratchet;
253 /* Score-based adaptation. */
254 floating_t (*adapter)(struct uct_dynkomi *d, struct board *b);
255 floating_t adapt_base; // [0,1)
256 /* Sigmoid adaptation rate parameter; see below for details. */
257 floating_t adapt_phase; // [0,1]
258 floating_t adapt_rate; // [1,infty)
259 /* Linear adaptation rate parameter. */
260 int adapt_moves;
261 floating_t adapt_dir; // [-1,1]
263 #define TRUSTWORTHY_KOMI_PLAYOUTS 200
265 static floating_t
266 board_game_portion(struct dynkomi_adaptive *a, struct board *b)
268 if (!a->adapt_aport) {
269 int total_moves = b->moves + 2 * board_estimated_moves_left(b);
270 return (floating_t) b->moves / total_moves;
271 } else {
272 int brsize = board_size(b) - 2;
273 return 1.0 - (floating_t) b->flen / (brsize * brsize);
277 static floating_t
278 adapter_sigmoid(struct uct_dynkomi *d, struct board *b)
280 struct dynkomi_adaptive *a = d->data;
281 /* Figure out how much to adjust the komi based on the game
282 * stage. The adaptation rate is 0 at the beginning,
283 * at game stage a->adapt_phase crosses though 0.5 and
284 * approaches 1 at the game end; the slope is controlled
285 * by a->adapt_rate. */
286 floating_t game_portion = board_game_portion(a, b);
287 floating_t l = game_portion - a->adapt_phase;
288 return 1.0 / (1.0 + exp(-a->adapt_rate * l));
291 static floating_t
292 adapter_linear(struct uct_dynkomi *d, struct board *b)
294 struct dynkomi_adaptive *a = d->data;
295 /* Figure out how much to adjust the komi based on the game
296 * stage. We just linearly increase/decrease the adaptation
297 * rate for first N moves. */
298 if (b->moves > a->adapt_moves)
299 return 0;
300 if (a->adapt_dir < 0)
301 return 1 - (- a->adapt_dir) * b->moves / a->adapt_moves;
302 else
303 return a->adapt_dir * b->moves / a->adapt_moves;
306 static floating_t
307 komi_by_score(struct uct_dynkomi *d, struct board *b, struct tree *tree, enum stone color)
309 struct dynkomi_adaptive *a = d->data;
310 if (d->score.playouts < TRUSTWORTHY_KOMI_PLAYOUTS)
311 return tree->extra_komi;
313 struct move_stats score = d->score;
314 /* Almost-reset tree->score to gather fresh stats. */
315 d->score.playouts = 1;
317 /* Look at average score and push extra_komi in that direction. */
318 floating_t p = a->adapter(d, b);
319 p = a->adapt_base + p * (1 - a->adapt_base);
320 if (p > 0.9) p = 0.9; // don't get too eager!
321 floating_t extra_komi = tree->extra_komi + p * score.value;
322 if (DEBUGL(3))
323 fprintf(stderr, "mC += %f * %f\n", p, score.value);
324 return extra_komi;
327 static floating_t
328 komi_by_value(struct uct_dynkomi *d, struct board *b, struct tree *tree, enum stone color)
330 struct dynkomi_adaptive *a = d->data;
331 if (d->value.playouts < TRUSTWORTHY_KOMI_PLAYOUTS)
332 return tree->extra_komi;
334 struct move_stats value = d->value;
335 /* Almost-reset tree->value to gather fresh stats. */
336 d->value.playouts = 1;
337 /* Correct color POV. */
338 if (color == S_WHITE)
339 value.value = 1 - value.value;
341 /* We have three "value zones":
342 * red zone | yellow zone | green zone
343 * ~45% ~60%
344 * red zone: reduce komi
345 * yellow zone: do not touch komi
346 * green zone: enlage komi.
348 * Also, at some point komi will be tuned in such way
349 * that it will be in green zone but increasing it will
350 * be unfeasible. Thus, we have a _ratchet_ - we will
351 * remember the last komi that has put us into the
352 * red zone, and not use it or go over it. We use the
353 * ratchet only when giving extra komi, we always want
354 * to try to reduce extra komi we take.
356 * TODO: Make the ratchet expire after a while. */
358 /* We use komi_by_color() first to normalize komi
359 * additions/subtractions, then apply it again on
360 * return value to restore original komi parity. */
361 /* Positive extra_komi means that we are _giving_
362 * komi (winning), negative extra_komi is _taking_
363 * komi (losing). */
364 floating_t extra_komi = komi_by_color(tree->extra_komi, color);
365 int score_step_red = -a->score_step;
366 int score_step_green = a->score_step;
368 if (a->score_step_byavg != 0) {
369 struct move_stats score = d->score;
370 /* Almost-reset tree->score to gather fresh stats. */
371 d->score.playouts = 1;
372 /* Correct color POV. */
373 if (color == S_WHITE)
374 score.value = - score.value;
375 if (score.value > 0)
376 score_step_green = round(score.value * a->score_step_byavg);
377 else
378 score_step_red = round(-score.value * a->score_step_byavg);
379 if (score_step_green < 0 || score_step_red > 0) {
380 /* The steps are in bad direction - keep still. */
381 return komi_by_color(extra_komi, color);
385 /* Wear out the ratchet. */
386 if (a->use_komi_ratchet && a->komi_ratchet_maxage > 0) {
387 a->komi_ratchet_age += value.playouts;
388 if (a->komi_ratchet_age > a->komi_ratchet_maxage) {
389 a->komi_ratchet = 1000;
390 a->komi_ratchet_age = 0;
394 if (value.value < a->zone_red) {
395 /* Red zone. Take extra komi. */
396 if (DEBUGL(3))
397 fprintf(stderr, "[red] %f, step %d | komi ratchet %f age %d/%d -> %f\n",
398 value.value, score_step_red, a->komi_ratchet, a->komi_ratchet_age, a->komi_ratchet_maxage, extra_komi);
399 if (a->losing_komi_ratchet || extra_komi > 0) {
400 a->komi_ratchet = extra_komi;
401 a->komi_ratchet_age = 0;
403 extra_komi += score_step_red;
404 return komi_by_color(extra_komi, color);
406 } else if (value.value < a->zone_green) {
407 /* Yellow zone, do nothing. */
408 return komi_by_color(extra_komi, color);
410 } else {
411 /* Green zone. Give extra komi. */
412 if (DEBUGL(3))
413 fprintf(stderr, "[green] %f, step %d | komi ratchet %f age %d/%d\n",
414 value.value, score_step_green, a->komi_ratchet, a->komi_ratchet_age, a->komi_ratchet_maxage);
415 extra_komi += score_step_green;
416 if (a->use_komi_ratchet && extra_komi >= a->komi_ratchet)
417 extra_komi = a->komi_ratchet - 1;
418 return komi_by_color(extra_komi, color);
422 static floating_t
423 bounded_komi(struct dynkomi_adaptive *a, struct board *b,
424 enum stone color, floating_t komi, floating_t max_losing_komi)
426 /* At the end of game, disallow losing komi. */
427 if (komi_by_color(komi, color) < 0
428 && board_game_portion(a, b) > a->losing_komi_stop)
429 return 0;
431 /* Get lower bound on komi we take so that we don't underperform
432 * too much. */
433 floating_t min_komi = komi_by_color(- max_losing_komi, color);
435 if (komi_by_color(komi - min_komi, color) > 0)
436 return komi;
437 else
438 return min_komi;
441 static floating_t
442 adaptive_permove(struct uct_dynkomi *d, struct board *b, struct tree *tree)
444 /* We do not use extra komi at the game end - we are not
445 * to fool ourselves at this point. */
446 if (board_estimated_moves_left(b) <= MIN_MOVES_LEFT) {
447 tree->use_extra_komi = false;
448 return 0;
450 struct dynkomi_adaptive *a = d->data;
451 enum stone color = stone_other(tree->root_color);
452 if (DEBUGL(3))
453 fprintf(stderr, "m %d/%d ekomi %f permove %f/%d\n",
454 b->moves, a->lead_moves, tree->extra_komi,
455 d->score.value, d->score.playouts);
457 if (b->moves <= a->lead_moves)
458 return bounded_komi(a, b, color,
459 board_effective_handicap(b, 7 /* XXX */),
460 a->max_losing_komi);
462 floating_t komi = a->indicator(d, b, tree, color);
463 if (DEBUGL(3))
464 fprintf(stderr, "dynkomi: %f -> %f\n", tree->extra_komi, komi);
465 return bounded_komi(a, b, color, komi, a->max_losing_komi);
468 static floating_t
469 adaptive_persim(struct uct_dynkomi *d, struct board *b, struct tree *tree, struct tree_node *node)
471 return tree->extra_komi;
474 struct uct_dynkomi *
475 uct_dynkomi_init_adaptive(struct uct *u, char *arg, struct board *b)
477 struct uct_dynkomi *d = calloc2(1, sizeof(*d));
478 d->uct = u;
479 d->permove = adaptive_permove;
480 d->persim = adaptive_persim;
481 d->done = generic_done;
483 struct dynkomi_adaptive *a = calloc2(1, sizeof(*a));
484 d->data = a;
486 a->lead_moves = board_large(b) ? 20 : 4; // XXX
487 a->max_losing_komi = 30;
488 a->losing_komi_stop = 1.0f;
489 a->indicator = komi_by_value;
491 a->adapter = adapter_sigmoid;
492 a->adapt_rate = -18;
493 a->adapt_phase = 0.65;
494 a->adapt_moves = 200;
495 a->adapt_dir = -0.5;
497 a->zone_red = 0.45;
498 a->zone_green = 0.50;
499 a->score_step = 1;
500 a->use_komi_ratchet = true;
501 a->komi_ratchet_maxage = 0;
502 a->komi_ratchet = 1000;
504 if (arg) {
505 char *optspec, *next = arg;
506 while (*next) {
507 optspec = next;
508 next += strcspn(next, ":");
509 if (*next) { *next++ = 0; } else { *next = 0; }
511 char *optname = optspec;
512 char *optval = strchr(optspec, '=');
513 if (optval) *optval++ = 0;
515 if (!strcasecmp(optname, "lead_moves") && optval) {
516 /* Do not adjust komi adaptively for first
517 * N moves. */
518 a->lead_moves = atoi(optval);
519 } else if (!strcasecmp(optname, "max_losing_komi") && optval) {
520 a->max_losing_komi = atof(optval);
521 } else if (!strcasecmp(optname, "losing_komi_stop") && optval) {
522 a->losing_komi_stop = atof(optval);
523 } else if (!strcasecmp(optname, "indicator")) {
524 /* Adaptatation indicator - how to decide
525 * the adaptation rate and direction. */
526 if (!strcasecmp(optval, "value")) {
527 /* Winrate w/ komi so far. */
528 a->indicator = komi_by_value;
529 } else if (!strcasecmp(optval, "score")) {
530 /* Expected score w/ current komi. */
531 a->indicator = komi_by_score;
532 } else {
533 fprintf(stderr, "UCT: Invalid indicator %s\n", optval);
534 exit(1);
537 /* value indicator settings */
538 } else if (!strcasecmp(optname, "zone_red") && optval) {
539 a->zone_red = atof(optval);
540 } else if (!strcasecmp(optname, "zone_green") && optval) {
541 a->zone_green = atof(optval);
542 } else if (!strcasecmp(optname, "score_step") && optval) {
543 a->score_step = atoi(optval);
544 } else if (!strcasecmp(optname, "score_step_byavg") && optval) {
545 a->score_step_byavg = atof(optval);
546 } else if (!strcasecmp(optname, "use_komi_ratchet")) {
547 a->use_komi_ratchet = !optval || atoi(optval);
548 } else if (!strcasecmp(optname, "losing_komi_ratchet")) {
549 a->losing_komi_ratchet = !optval || atoi(optval);
550 } else if (!strcasecmp(optname, "komi_ratchet_age") && optval) {
551 a->komi_ratchet_maxage = atoi(optval);
553 /* score indicator settings */
554 } else if (!strcasecmp(optname, "adapter") && optval) {
555 /* Adaptatation method. */
556 if (!strcasecmp(optval, "sigmoid")) {
557 a->adapter = adapter_sigmoid;
558 } else if (!strcasecmp(optval, "linear")) {
559 a->adapter = adapter_linear;
560 } else {
561 fprintf(stderr, "UCT: Invalid adapter %s\n", optval);
562 exit(1);
564 } else if (!strcasecmp(optname, "adapt_base") && optval) {
565 /* Adaptation base rate; see above. */
566 a->adapt_base = atof(optval);
567 } else if (!strcasecmp(optname, "adapt_rate") && optval) {
568 /* Adaptation slope; see above. */
569 a->adapt_rate = atof(optval);
570 } else if (!strcasecmp(optname, "adapt_phase") && optval) {
571 /* Adaptation phase shift; see above. */
572 a->adapt_phase = atof(optval);
573 } else if (!strcasecmp(optname, "adapt_moves") && optval) {
574 /* Adaptation move amount; see above. */
575 a->adapt_moves = atoi(optval);
576 } else if (!strcasecmp(optname, "adapt_aport")) {
577 a->adapt_aport = !optval || atoi(optval);
578 } else if (!strcasecmp(optname, "adapt_dir") && optval) {
579 /* Adaptation direction vector; see above. */
580 a->adapt_dir = atof(optval);
582 } else {
583 fprintf(stderr, "uct: Invalid dynkomi argument %s or missing value\n", optname);
584 exit(1);
589 return d;