Distributed engine: resend only partial command history when possible.
[pachi.git] / timeinfo.c
blobd618b04c9dd850cda6cf8fabcd695b4af58371c7
1 #include <assert.h>
2 #include <ctype.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <math.h>
6 #include <time.h>
8 #define DEBUG
10 #include "debug.h"
11 #include "tactics.h"
12 #include "timeinfo.h"
14 /* Max net lag in seconds. TODO: estimate dynamically. */
15 #define MAX_NET_LAG 2.0
16 /* Minimal thinking time; in case reserved time gets smaller than MAX_NET_LAG,
17 * this makes sure we play minimally sensible moves even in massive time
18 * pressure; we still keep MAX_NET_LAG-MIN_THINK_WITH_LAG safety margin.
19 * Note that this affects only lag adjustmnet - if reserved time *before*
20 * lag adjustment gets too small, we still respect it and don't apply
21 * MIN_THINK_WITH_LAG. */
22 #define MIN_THINK_WITH_LAG (MAX_NET_LAG / 2)
23 /* Reserve 15% of byoyomi time as safety margin if risk of losing on time */
24 #define RESERVED_BYOYOMI_PERCENT 15
26 /* For safety, use at most 3 times the desired time on a single move
27 * in main time, and 1.1 times in byoyomi. */
28 #define MAX_MAIN_TIME_EXTENSION 3.0
29 #define MAX_BYOYOMI_TIME_EXTENSION 1.1
31 bool
32 time_parse(struct time_info *ti, char *s)
34 switch (s[0]) {
35 case '_': ti->period = TT_TOTAL; s++; break;
36 default: ti->period = TT_MOVE; break;
38 switch (s[0]) {
39 case '=':
40 ti->dim = TD_GAMES;
41 ti->len.games = atoi(++s);
42 break;
43 default:
44 if (!isdigit(s[0]))
45 return false;
46 ti->dim = TD_WALLTIME;
47 ti->len.t.timer_start = 0;
48 if (ti->period == TT_TOTAL) {
49 ti->len.t.main_time = atof(s);
50 ti->len.t.byoyomi_time = 0.0;
51 ti->len.t.byoyomi_time_max = 0.0;
52 ti->len.t.byoyomi_periods = 0;
53 ti->len.t.byoyomi_stones = 0;
54 ti->len.t.byoyomi_stones_max = 0;
55 } else { assert(ti->period == TT_MOVE);
56 ti->len.t.main_time = 0.0;
57 ti->len.t.byoyomi_time = atof(s);
58 ti->len.t.byoyomi_time_max = ti->len.t.byoyomi_time;
59 ti->len.t.byoyomi_periods = 1;
60 ti->len.t.byoyomi_stones = 1;
61 ti->len.t.byoyomi_stones_max = 1;
63 break;
65 return true;
68 /* Update time settings according to gtp time_settings or kgs-time_settings command. */
69 void
70 time_settings(struct time_info *ti, int main_time, int byoyomi_time, int byoyomi_stones, int byoyomi_periods)
72 if (main_time < 0) {
73 ti->period = TT_NULL; // no time limit, rely on engine default
74 } else {
75 ti->period = main_time > 0 ? TT_TOTAL : TT_MOVE;
76 ti->dim = TD_WALLTIME;
77 ti->len.t.timer_start = 0;
78 ti->len.t.main_time = (double) main_time;
79 ti->len.t.byoyomi_time = (double) byoyomi_time;
80 ti->len.t.byoyomi_periods = byoyomi_periods;
81 ti->len.t.byoyomi_stones = byoyomi_stones;
82 ti->len.t.canadian = byoyomi_stones > 0;
83 if (byoyomi_time > 0) {
84 /* Normally, only one of byoyomi_periods and
85 * byoyomi_stones arguments will be > 0. However,
86 * our data structure uses generalized byoyomi
87 * specification that will assume "1 byoyomi period
88 * of N stones" for Canadian byoyomi and "N byoyomi
89 * periods of 1 stone" for Japanese byoyomi. */
90 if (ti->len.t.byoyomi_periods < 1)
91 ti->len.t.byoyomi_periods = 1;
92 if (ti->len.t.byoyomi_stones < 1)
93 ti->len.t.byoyomi_stones = 1;
94 } else {
95 assert(!ti->len.t.byoyomi_periods && !ti->len.t.byoyomi_stones);
97 ti->len.t.byoyomi_time_max = ti->len.t.byoyomi_time;
98 ti->len.t.byoyomi_stones_max = ti->len.t.byoyomi_stones;
102 /* Update time information according to gtp time_left command.
103 * kgs doesn't give time_left for the first move, so make sure
104 * that just time_settings + time_stop_conditions still work. */
105 void
106 time_left(struct time_info *ti, int time_left, int stones_left)
108 assert(ti->period != TT_NULL);
109 ti->dim = TD_WALLTIME;
111 if (!time_left && !stones_left) {
112 /* Some GTP peers send time_left 0 0 at the end of main time. */
113 ti->period = TT_MOVE;
114 ti->len.t.main_time = 0;
115 /* byoyomi_time kept fully charged. */
117 } else if (!stones_left) {
118 /* Main time */
119 ti->period = TT_TOTAL;
120 ti->len.t.main_time = time_left;
121 /* byoyomi_time kept fully charged. */
123 } else {
124 /* Byoyomi */
125 ti->period = TT_MOVE;
126 ti->len.t.main_time = 0;
127 ti->len.t.byoyomi_time = time_left;
128 if (ti->len.t.canadian) {
129 ti->len.t.byoyomi_stones = stones_left;
130 } else {
131 // field misused by kgs
132 ti->len.t.byoyomi_periods = stones_left;
137 /* Start our timer. kgs does this (correctly) on "play" not "genmove"
138 * unless we are making the first move of the game. */
139 void
140 time_start_timer(struct time_info *ti)
142 if (ti->period != TT_NULL && ti->dim == TD_WALLTIME)
143 ti->len.t.timer_start = time_now();
146 void
147 time_sub(struct time_info *ti, double interval)
149 assert(ti->dim == TD_WALLTIME && ti->period != TT_NULL);
151 if (ti->period == TT_TOTAL) {
152 ti->len.t.main_time -= interval;
153 if (ti->len.t.main_time >= 0)
154 return;
155 if (ti->len.t.byoyomi_time <= 0) {
156 /* No byoyomi to save us. */
157 fprintf(stderr, "*** LOST ON TIME internally! (%0.2f, spent %0.2fs on last move)\n",
158 ti->len.t.main_time, interval);
159 /* What can we do? Pretend this didn't happen. */
160 ti->len.t.main_time = 1.0f;
161 return;
163 /* Fall-through to byoyomi. */
164 ti->period = TT_MOVE;
165 interval = -ti->len.t.main_time;
166 ti->len.t.main_time = 0;
169 ti->len.t.byoyomi_time -= interval;
170 if (ti->len.t.byoyomi_time < 0) {
171 /* Lost a period. */
172 if (--ti->len.t.byoyomi_periods < 1) {
173 fprintf(stderr, "*** LOST ON TIME internally! (%0.2f, spent %0.2fs on last move)\n",
174 ti->len.t.byoyomi_time, interval);
175 /* Well, what can we do? Pretend this didn't happen. */
176 ti->len.t.byoyomi_periods = 1;
178 ti->len.t.byoyomi_time = ti->len.t.byoyomi_time_max;
179 ti->len.t.byoyomi_stones = ti->len.t.byoyomi_stones_max;
180 return;
182 if (--ti->len.t.byoyomi_stones < 1) {
183 /* Finished a period. */
184 ti->len.t.byoyomi_time = ti->len.t.byoyomi_time_max;
185 ti->len.t.byoyomi_stones = ti->len.t.byoyomi_stones_max;
189 /* Returns the current time. */
190 double
191 time_now(void)
193 struct timespec now;
194 clock_gettime(CLOCK_REALTIME, &now);
195 return now.tv_sec + now.tv_nsec/1000000000.0;
198 /* Sleep for a given interval (in seconds). Return immediately if interval < 0. */
199 void
200 time_sleep(double interval)
202 struct timespec ts;
203 double sec;
204 ts.tv_nsec = (int)(modf(interval, &sec)*1000000000.0);
205 ts.tv_sec = (int)sec;
206 nanosleep(&ts, NULL); /* ignore error if interval was < 0 */
210 /* Returns true if we are in byoyomi (or should play as if in byo yomi
211 * because remaining time per move in main time is less than byoyomi time
212 * per move). */
213 static bool
214 time_in_byoyomi(struct time_info *ti) {
215 assert(ti->dim == TD_WALLTIME);
216 if (!ti->len.t.byoyomi_time)
217 return false; // there is no byoyomi!
218 assert(ti->len.t.byoyomi_stones > 0);
219 if (!ti->len.t.main_time)
220 return true; // we _are_ in byoyomi
221 if (ti->len.t.main_time <= ti->len.t.byoyomi_time / ti->len.t.byoyomi_stones + 0.001)
222 return true; // our basic time left is less than byoyomi time per move
223 return false;
226 /* Set worst.time to all available remaining time (main time plus usable
227 * byoyomi), to be spread over returned number of moves (expected game
228 * length minus moves to be played in final byoyomi - if we would not be
229 * able to spend more time on them in main time anyway). */
230 static int
231 time_stop_set_remaining(struct time_info *ti, struct board *b, double net_lag, struct time_stop *stop)
233 int moves_left = board_estimated_moves_left(b);
234 stop->worst.time = ti->len.t.main_time;
236 if (!ti->len.t.byoyomi_time)
237 return moves_left;
239 /* Time for one move in byoyomi. */
240 assert(ti->len.t.byoyomi_stones > 0);
241 double move_time = ti->len.t.byoyomi_time / ti->len.t.byoyomi_stones;
243 /* (i) Plan to extend our thinking time to make use of byoyom. */
245 /* For Japanese byoyomi with N>1 periods, we use N-1 periods
246 * as main time, keeping the last one as insurance against
247 * unexpected net lag. */
248 if (ti->len.t.byoyomi_periods > 2) {
249 stop->worst.time += (ti->len.t.byoyomi_periods - 2) * move_time;
250 // Will add 1 more byoyomi_time just below
253 /* In case of Canadian byoyomi, include time that can be spent
254 * on its first move. */
255 stop->worst.time += move_time;
257 /* (ii) Do not play faster in main time than we would in byoyomi. */
259 /* Maximize the number of moves played uniformly in main time,
260 * while not playing faster in main time than in byoyomi.
261 * At this point, the main time remaining is stop->worst.time and
262 * already includes the first (canadian) or N-1 byoyomi periods. */
263 double real_move_time = move_time - net_lag;
264 if (real_move_time > 0) {
265 int main_moves = stop->worst.time / real_move_time;
266 if (moves_left > main_moves) {
267 /* We plan to do too many moves in main time,
268 * do the rest in byoyomi. */
269 moves_left = main_moves;
271 if (moves_left <= 0) // possible if too much lag
272 moves_left = 1;
275 return moves_left;
278 /* Adjust the recommended per-move time based on the current game phase.
279 * We expect stop->worst to be total time available, stop->desired the current
280 * per-move time allocation, and set stop->desired to adjusted per-move time. */
281 static void
282 time_stop_phase_adjust(struct board *b, int fuseki_end, int yose_start, struct time_stop *stop)
284 int bsize = (board_size(b)-2)*(board_size(b)-2);
285 fuseki_end = fuseki_end * bsize / 100; // move nb at fuseki end
286 yose_start = yose_start * bsize / 100; // move nb at yose start
287 assert(fuseki_end < yose_start);
289 /* No adjustments in yose. */
290 if (b->moves >= yose_start)
291 return;
292 int moves_to_yose = (yose_start - b->moves) / 2;
293 // ^- /2 because we only consider the moves we have to play ourselves
294 int left_at_yose_start = board_estimated_moves_left(b) - moves_to_yose;
295 if (left_at_yose_start < MIN_MOVES_LEFT)
296 left_at_yose_start = MIN_MOVES_LEFT;
298 /* This particular value of middlegame_time will continuously converge
299 * to effective "yose_time" value as we approach yose_start. */
300 double middlegame_time = stop->worst.time / left_at_yose_start;
301 if (middlegame_time < stop->desired.time)
302 return;
304 if (b->moves < fuseki_end) {
305 assert(fuseki_end > 0);
306 /* At the game start, use stop->desired.time (rather
307 * conservative estimate), then gradually prolong it. */
308 double beta = b->moves / fuseki_end;
309 stop->desired.time = middlegame_time * beta + stop->desired.time * (1 - beta);
311 } else { assert(b->moves < yose_start);
312 /* Middlegame, start with relatively large value, then
313 * converge to the uniform-timeslice yose value. */
314 stop->desired.time = middlegame_time;
318 void
319 lag_adjust(double *time, double net_lag)
321 double nolag_time = *time;
322 *time -= net_lag;
323 if (*time < MIN_THINK_WITH_LAG && nolag_time > MIN_THINK_WITH_LAG)
324 *time = MIN_THINK_WITH_LAG;
327 /* Pre-process time_info for search control and sets the desired stopping conditions. */
328 void
329 time_stop_conditions(struct time_info *ti, struct board *b, int fuseki_end, int yose_start, struct time_stop *stop)
331 /* We must have _some_ limits by now, be it random default values! */
332 assert(ti->period != TT_NULL);
334 /* Special-case limit by number of simulations. */
335 if (ti->dim == TD_GAMES) {
336 if (ti->period == TT_TOTAL) {
337 ti->period = TT_MOVE;
338 ti->len.games /= board_estimated_moves_left(b);
341 stop->desired.playouts = ti->len.games;
342 /* We force worst == desired, so note that we will NOT loop
343 * until best == winner. */
344 stop->worst.playouts = ti->len.games;
345 return;
348 assert(ti->dim == TD_WALLTIME);
351 /* Minimum net lag (seconds) to be reserved in the time for move. */
352 double net_lag = MAX_NET_LAG;
353 if (!ti->len.t.timer_start) {
354 ti->len.t.timer_start = time_now(); // we're playing the first game move
355 } else {
356 net_lag += time_now() - ti->len.t.timer_start;
357 // TODO: keep statistics to get good estimate of lag not just current move
361 if (ti->period == TT_TOTAL && time_in_byoyomi(ti)) {
362 /* Technically, we are still in main time, but we can
363 * effectively switch to byoyomi scheduling since we
364 * have less time available than one byoyomi move takes. */
365 ti->period = TT_MOVE;
369 if (ti->period == TT_MOVE) {
370 /* We are in byoyomi, or almost! */
372 /* The period can still include some tiny remnant of main
373 * time if we are just switching to byoyomi. */
374 double period_len = ti->len.t.byoyomi_time + ti->len.t.main_time;
376 stop->worst.time = period_len;
377 assert(ti->len.t.byoyomi_stones > 0);
378 stop->desired.time = period_len / ti->len.t.byoyomi_stones;
380 /* Use a larger safety margin if we risk losing on time on
381 * this move; it makes no sense to have 30s byoyomi and wait
382 * until 28s to play our move). */
383 if (stop->desired.time >= period_len - net_lag) {
384 double safe_margin = RESERVED_BYOYOMI_PERCENT * stop->desired.time / 100;
385 if (safe_margin > net_lag)
386 net_lag = safe_margin;
389 /* Make recommended_old == average(recommended_new, max) */
390 double worst_time = stop->desired.time * MAX_BYOYOMI_TIME_EXTENSION;
391 if (worst_time < stop->worst.time)
392 stop->worst.time = worst_time;
393 stop->desired.time *= (2 - MAX_BYOYOMI_TIME_EXTENSION);
395 } else { assert(ti->period == TT_TOTAL);
396 /* We are in main time. */
398 assert(ti->len.t.main_time > 0);
399 /* Set worst.time to all available remaining time, to be spread
400 * over returned number of moves. */
401 int moves_left = time_stop_set_remaining(ti, b, net_lag, stop);
403 /* Allocate even slice of the remaining time for next move. */
404 stop->desired.time = stop->worst.time / moves_left;
405 assert(stop->desired.time > 0 && stop->worst.time > 0);
406 assert(stop->desired.time <= stop->worst.time + 0.001);
408 /* Furthermore, tweak the slice based on the game phase. */
409 time_stop_phase_adjust(b, fuseki_end, yose_start, stop);
411 /* Put final upper bound on maximal time spent on the move. */
412 double worst_time = stop->desired.time * MAX_MAIN_TIME_EXTENSION;
413 if (worst_time < stop->worst.time)
414 stop->worst.time = worst_time;
415 if (stop->desired.time > stop->worst.time)
416 stop->desired.time = stop->worst.time;
419 if (DEBUGL(1))
420 fprintf(stderr, "desired %0.2f, worst %0.2f, clock [%d] %0.2f + %0.2f/%d*%d, lag %0.2f\n",
421 stop->desired.time, stop->worst.time,
422 ti->dim, ti->len.t.main_time,
423 ti->len.t.byoyomi_time, ti->len.t.byoyomi_stones,
424 ti->len.t.byoyomi_periods, net_lag);
426 /* Account for lag. */
427 lag_adjust(&stop->desired.time, net_lag);
428 lag_adjust(&stop->worst.time, net_lag);