Merge branch 'master' of git+ssh://repo.or.cz/srv/git/pachi
[pachi/ann.git] / timeinfo.c
blob6c4542b08c433a04268a3e34114ef4f1264e9354
1 #include <assert.h>
2 #include <ctype.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <math.h>
6 #include <time.h>
7 #include <sys/time.h>
9 #define DEBUG
11 #include "debug.h"
12 #include "tactics/util.h"
13 #include "timeinfo.h"
15 /* Max net lag in seconds. TODO: estimate dynamically. */
16 #define MAX_NET_LAG 2.0
17 /* Minimal thinking time; in case reserved time gets smaller than MAX_NET_LAG,
18 * this makes sure we play minimally sensible moves even in massive time
19 * pressure; we still keep MAX_NET_LAG-MIN_THINK_WITH_LAG safety margin.
20 * Note that this affects only lag adjustmnet - if reserved time *before*
21 * lag adjustment gets too small, we still respect it and don't apply
22 * MIN_THINK_WITH_LAG. */
23 #define MIN_THINK_WITH_LAG (MAX_NET_LAG / 2)
24 /* Reserve 15% of byoyomi time as safety margin if risk of losing on time */
25 #define RESERVED_BYOYOMI_PERCENT 15
27 /* For safety, use at most 2 times the desired time on a single move
28 * in sudden death and 1.1 times in byoyomi. */
29 #define MAX_SUDDEN_DEATH_RATIO 2.0
30 #define MAX_BYOYOMI_TIME_RATIO 1.1
32 bool
33 time_parse(struct time_info *ti, char *s)
35 switch (s[0]) {
36 case '_': ti->period = TT_TOTAL; s++; break;
37 default: ti->period = TT_MOVE; break;
39 switch (s[0]) {
40 case '=':
41 ti->dim = TD_GAMES;
42 ti->len.games = atoi(++s);
43 break;
44 default:
45 if (!isdigit(s[0]))
46 return false;
47 ti->dim = TD_WALLTIME;
48 ti->len.t.timer_start = 0;
49 if (ti->period == TT_TOTAL) {
50 ti->len.t.main_time = atof(s);
51 ti->len.t.byoyomi_time = 0.0;
52 ti->len.t.byoyomi_time_max = 0.0;
53 ti->len.t.byoyomi_periods = 0;
54 ti->len.t.byoyomi_stones = 0;
55 ti->len.t.byoyomi_stones_max = 0;
56 } else { assert(ti->period == TT_MOVE);
57 ti->len.t.main_time = 0.0;
58 ti->len.t.byoyomi_time = atof(s);
59 ti->len.t.byoyomi_time_max = ti->len.t.byoyomi_time;
60 ti->len.t.byoyomi_periods = 1;
61 ti->len.t.byoyomi_stones = 1;
62 ti->len.t.byoyomi_stones_max = 1;
64 break;
66 return true;
69 /* Update time settings according to gtp time_settings or kgs-time_settings command. */
70 void
71 time_settings(struct time_info *ti, int main_time, int byoyomi_time, int byoyomi_stones, int byoyomi_periods)
73 if (main_time < 0) {
74 ti->period = TT_NULL; // no time limit, rely on engine default
75 } else {
76 ti->period = main_time > 0 ? TT_TOTAL : TT_MOVE;
77 ti->dim = TD_WALLTIME;
78 ti->len.t.timer_start = 0;
79 ti->len.t.main_time = (double) main_time;
80 ti->len.t.byoyomi_time = (double) byoyomi_time;
81 ti->len.t.byoyomi_periods = byoyomi_periods;
82 ti->len.t.byoyomi_stones = byoyomi_stones;
83 ti->len.t.canadian = byoyomi_stones > 0;
84 if (byoyomi_time > 0) {
85 /* Normally, only one of byoyomi_periods and
86 * byoyomi_stones arguments will be > 0. However,
87 * our data structure uses generalized byoyomi
88 * specification that will assume "1 byoyomi period
89 * of N stones" for Canadian byoyomi and "N byoyomi
90 * periods of 1 stone" for Japanese byoyomi. */
91 if (ti->len.t.byoyomi_periods < 1)
92 ti->len.t.byoyomi_periods = 1;
93 if (ti->len.t.byoyomi_stones < 1)
94 ti->len.t.byoyomi_stones = 1;
95 } else {
96 assert(!ti->len.t.byoyomi_periods && !ti->len.t.byoyomi_stones);
98 ti->len.t.byoyomi_time_max = ti->len.t.byoyomi_time;
99 ti->len.t.byoyomi_stones_max = ti->len.t.byoyomi_stones;
103 /* Update time information according to gtp time_left command.
104 * kgs doesn't give time_left for the first move, so make sure
105 * that just time_settings + time_stop_conditions still work. */
106 void
107 time_left(struct time_info *ti, int time_left, int stones_left)
109 assert(ti->period != TT_NULL);
110 ti->dim = TD_WALLTIME;
112 if (!time_left && !stones_left) {
113 /* Some GTP peers send time_left 0 0 at the end of main time. */
114 ti->period = TT_MOVE;
115 ti->len.t.main_time = 0;
116 /* byoyomi_time kept fully charged. */
118 } else if (!stones_left) {
119 /* Main time */
120 ti->period = TT_TOTAL;
121 ti->len.t.main_time = time_left;
122 /* byoyomi_time kept fully charged. */
124 } else {
125 /* Byoyomi */
126 ti->period = TT_MOVE;
127 ti->len.t.main_time = 0;
128 ti->len.t.byoyomi_time = time_left;
129 if (ti->len.t.canadian) {
130 ti->len.t.byoyomi_stones = stones_left;
131 } else {
132 // field misused by kgs
133 ti->len.t.byoyomi_periods = stones_left;
138 /* Start our timer. kgs does this (correctly) on "play" not "genmove"
139 * unless we are making the first move of the game. */
140 void
141 time_start_timer(struct time_info *ti)
143 if (ti->period != TT_NULL && ti->dim == TD_WALLTIME)
144 ti->len.t.timer_start = time_now();
147 void
148 time_sub(struct time_info *ti, double interval, bool new_move)
150 assert(ti->dim == TD_WALLTIME && ti->period != TT_NULL);
152 if (ti->period == TT_TOTAL) {
153 ti->len.t.main_time -= interval;
154 if (ti->len.t.main_time >= 0)
155 return;
156 if (ti->len.t.byoyomi_time <= 0) {
157 /* No byoyomi to save us. */
158 fprintf(stderr, "*** LOST ON TIME internally! (%0.2f, spent %0.2fs on last move)\n",
159 ti->len.t.main_time, interval);
160 /* What can we do? Pretend this didn't happen. */
161 ti->len.t.main_time = 1.0f;
162 return;
164 /* Fall-through to byoyomi. */
165 ti->period = TT_MOVE;
166 interval = -ti->len.t.main_time;
167 ti->len.t.main_time = 0;
170 ti->len.t.byoyomi_time -= interval;
171 if (ti->len.t.byoyomi_time < 0) {
172 /* Lost a period. */
173 if (--ti->len.t.byoyomi_periods < 1) {
174 fprintf(stderr, "*** LOST ON TIME internally! (%0.2f, spent %0.2fs on last move)\n",
175 ti->len.t.byoyomi_time, interval);
176 /* Well, what can we do? Pretend this didn't happen. */
177 ti->len.t.byoyomi_periods = 1;
179 ti->len.t.byoyomi_time = ti->len.t.byoyomi_time_max;
180 ti->len.t.byoyomi_stones = ti->len.t.byoyomi_stones_max;
181 return;
183 if (new_move && --ti->len.t.byoyomi_stones < 1) {
184 /* Finished a period. */
185 ti->len.t.byoyomi_time = ti->len.t.byoyomi_time_max;
186 ti->len.t.byoyomi_stones = ti->len.t.byoyomi_stones_max;
190 /* Returns the current time. */
191 double
192 time_now(void)
194 #if _POSIX_TIMERS > 0
195 struct timespec now;
196 clock_gettime(CLOCK_REALTIME, &now);
197 return now.tv_sec + now.tv_nsec/1000000000.0;
198 #else
199 struct timeval now;
200 gettimeofday(&now, NULL);
201 return now.tv_sec + now.tv_usec/1000000.0;
202 #endif
205 /* Sleep for a given interval (in seconds). Return immediately if interval < 0. */
206 void
207 time_sleep(double interval)
209 struct timespec ts;
210 double sec;
211 ts.tv_nsec = (int)(modf(interval, &sec)*1000000000.0);
212 ts.tv_sec = (int)sec;
213 nanosleep(&ts, NULL); /* ignore error if interval was < 0 */
217 /* Returns true if we are in byoyomi (or should play as if in byo yomi
218 * because remaining time per move in main time is less than byoyomi time
219 * per move). */
220 static bool
221 time_in_byoyomi(struct time_info *ti) {
222 assert(ti->dim == TD_WALLTIME);
223 if (!ti->len.t.byoyomi_time)
224 return false; // there is no byoyomi!
225 assert(ti->len.t.byoyomi_stones > 0);
226 if (!ti->len.t.main_time)
227 return true; // we _are_ in byoyomi
228 if (ti->len.t.main_time <= ti->len.t.byoyomi_time / ti->len.t.byoyomi_stones + 0.001)
229 return true; // our basic time left is less than byoyomi time per move
230 return false;
233 /* Set worst.time to all available remaining time (main time plus usable
234 * byoyomi), to be spread over returned number of moves (expected game
235 * length minus moves to be played in final byoyomi - if we would not be
236 * able to spend more time on them in main time anyway). */
237 static int
238 time_stop_set_remaining(struct time_info *ti, struct board *b, double net_lag, struct time_stop *stop)
240 int moves_left = board_estimated_moves_left(b);
241 stop->worst.time = ti->len.t.main_time;
243 if (!ti->len.t.byoyomi_time)
244 return moves_left;
246 /* Time for one move in byoyomi. */
247 assert(ti->len.t.byoyomi_stones > 0);
248 double move_time = ti->len.t.byoyomi_time / ti->len.t.byoyomi_stones;
250 /* (i) Plan to extend our thinking time to make use of byoyom. */
252 /* For Japanese byoyomi with N>1 periods, we use N-1 periods
253 * as main time, keeping the last one as insurance against
254 * unexpected net lag. */
255 if (ti->len.t.byoyomi_periods > 2) {
256 stop->worst.time += (ti->len.t.byoyomi_periods - 2) * move_time;
257 // Will add 1 more byoyomi_time just below
260 /* In case of Canadian byoyomi, include time that can be spent
261 * on its first move. */
262 stop->worst.time += move_time;
264 /* (ii) Do not play faster in main time than we would in byoyomi. */
266 /* Maximize the number of moves played uniformly in main time,
267 * while not playing faster in main time than in byoyomi.
268 * At this point, the main time remaining is stop->worst.time and
269 * already includes the first (canadian) or N-1 byoyomi periods. */
270 double real_move_time = move_time - net_lag;
271 if (real_move_time > 0) {
272 int main_moves = stop->worst.time / real_move_time;
273 if (moves_left > main_moves) {
274 /* We plan to do too many moves in main time,
275 * do the rest in byoyomi. */
276 moves_left = main_moves;
278 if (moves_left <= 0) // possible if too much lag
279 moves_left = 1;
282 return moves_left;
285 /* Adjust the recommended per-move time based on the current game phase.
286 * We expect stop->worst to be total time available, stop->desired the current
287 * per-move time allocation, and set stop->desired to adjusted per-move time. */
288 static void
289 time_stop_phase_adjust(struct board *b, int fuseki_end, int yose_start, struct time_stop *stop)
291 int bsize = (board_size(b)-2)*(board_size(b)-2);
292 fuseki_end = fuseki_end * bsize / 100; // move nb at fuseki end
293 yose_start = yose_start * bsize / 100; // move nb at yose start
294 assert(fuseki_end < yose_start);
296 /* No adjustments in yose. */
297 if (b->moves >= yose_start)
298 return;
299 int moves_to_yose = (yose_start - b->moves) / 2;
300 // ^- /2 because we only consider the moves we have to play ourselves
301 int left_at_yose_start = board_estimated_moves_left(b) - moves_to_yose;
302 if (left_at_yose_start < MIN_MOVES_LEFT)
303 left_at_yose_start = MIN_MOVES_LEFT;
305 /* This particular value of middlegame_time will continuously converge
306 * to effective "yose_time" value as we approach yose_start. */
307 double middlegame_time = stop->worst.time / left_at_yose_start;
308 if (middlegame_time < stop->desired.time)
309 return;
311 if (b->moves < fuseki_end) {
312 assert(fuseki_end > 0);
313 /* At the game start, use stop->desired.time (rather
314 * conservative estimate), then gradually prolong it. */
315 double beta = b->moves / fuseki_end;
316 stop->desired.time = middlegame_time * beta + stop->desired.time * (1 - beta);
318 } else { assert(b->moves < yose_start);
319 /* Middlegame, start with relatively large value, then
320 * converge to the uniform-timeslice yose value. */
321 stop->desired.time = middlegame_time;
325 void
326 lag_adjust(double *time, double net_lag)
328 double nolag_time = *time;
329 *time -= net_lag;
330 if (*time < MIN_THINK_WITH_LAG && nolag_time > MIN_THINK_WITH_LAG)
331 *time = MIN_THINK_WITH_LAG;
334 /* Pre-process time_info for search control and sets the desired stopping conditions. */
335 void
336 time_stop_conditions(struct time_info *ti, struct board *b, int fuseki_end, int yose_start,
337 floating_t max_maintime_ratio, struct time_stop *stop)
339 /* We must have _some_ limits by now, be it random default values! */
340 assert(ti->period != TT_NULL);
342 /* Special-case limit by number of simulations. */
343 if (ti->dim == TD_GAMES) {
344 if (ti->period == TT_TOTAL) {
345 ti->period = TT_MOVE;
346 ti->len.games /= board_estimated_moves_left(b);
349 stop->desired.playouts = ti->len.games;
350 /* We force worst == desired, so note that we will NOT loop
351 * until best == winner. */
352 stop->worst.playouts = ti->len.games;
353 return;
356 assert(ti->dim == TD_WALLTIME);
359 /* Minimum net lag (seconds) to be reserved in the time for move. */
360 double net_lag = MAX_NET_LAG;
361 net_lag += time_now() - ti->len.t.timer_start;
362 // TODO: keep statistics to get good estimate of lag not just current move
365 if (ti->period == TT_TOTAL && time_in_byoyomi(ti)) {
366 /* Technically, we are still in main time, but we can
367 * effectively switch to byoyomi scheduling since we
368 * have less time available than one byoyomi move takes. */
369 ti->period = TT_MOVE;
373 if (ti->period == TT_MOVE) {
374 /* We are in byoyomi, or almost! */
376 /* The period can still include some tiny remnant of main
377 * time if we are just switching to byoyomi. */
378 double period_len = ti->len.t.byoyomi_time + ti->len.t.main_time;
380 stop->worst.time = period_len;
381 assert(ti->len.t.byoyomi_stones > 0);
382 stop->desired.time = period_len / ti->len.t.byoyomi_stones;
384 /* Use a larger safety margin if we risk losing on time on
385 * this move; it makes no sense to have 30s byoyomi and wait
386 * until 28s to play our move). */
387 if (stop->desired.time >= period_len - net_lag) {
388 double safe_margin = RESERVED_BYOYOMI_PERCENT * stop->desired.time / 100;
389 if (safe_margin > net_lag)
390 net_lag = safe_margin;
393 /* Make recommended_old == average(recommended_new, max) */
394 double worst_time = stop->desired.time * MAX_BYOYOMI_TIME_RATIO;
395 if (worst_time < stop->worst.time)
396 stop->worst.time = worst_time;
397 stop->desired.time *= (2 - MAX_BYOYOMI_TIME_RATIO);
399 } else { assert(ti->period == TT_TOTAL);
400 /* We are in main time. */
402 assert(ti->len.t.main_time > 0);
403 /* Set worst.time to all available remaining time, to be spread
404 * over returned number of moves. */
405 int moves_left = time_stop_set_remaining(ti, b, net_lag, stop);
407 /* Allocate even slice of the remaining time for next move. */
408 stop->desired.time = stop->worst.time / moves_left;
409 assert(stop->desired.time > 0 && stop->worst.time > 0);
410 assert(stop->desired.time <= stop->worst.time + 0.001);
412 /* Furthermore, tweak the slice based on the game phase. */
413 time_stop_phase_adjust(b, fuseki_end, yose_start, stop);
415 /* Put final upper bound on maximal time spent on the move.
416 * Keep enough time for sudden death (or near SD) games. */
417 double worst_time = stop->desired.time;
418 if (ti->len.t.byoyomi_time_max > ti->len.t.byoyomi_stones_max) {
419 worst_time *= max_maintime_ratio;
420 } else {
421 worst_time *= MAX_SUDDEN_DEATH_RATIO;
423 if (worst_time < stop->worst.time)
424 stop->worst.time = worst_time;
425 if (stop->desired.time > stop->worst.time)
426 stop->desired.time = stop->worst.time;
429 if (DEBUGL(1))
430 fprintf(stderr, "desired %0.2f, worst %0.2f, clock [%d] %0.2f + %0.2f/%d*%d, lag %0.2f\n",
431 stop->desired.time, stop->worst.time,
432 ti->dim, ti->len.t.main_time,
433 ti->len.t.byoyomi_time, ti->len.t.byoyomi_stones,
434 ti->len.t.byoyomi_periods, net_lag);
436 /* Account for lag. */
437 lag_adjust(&stop->desired.time, net_lag);
438 lag_adjust(&stop->worst.time, net_lag);