Elo: Add EAT_SIGMOID support
[pachi/derm.git] / timeinfo.c
blob46c3e9d51e7caad5f2f0d5c11d50f904362b4b17
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, 2 times in sudden death and 1.1 times in byoyomi. */
28 #define MAX_MAIN_TIME_EXTENSION 3.0
29 #define MAX_SUDDEN_DEATH_EXTENSION 2.0
30 #define MAX_BYOYOMI_TIME_EXTENSION 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 struct timespec now;
195 clock_gettime(CLOCK_REALTIME, &now);
196 return now.tv_sec + now.tv_nsec/1000000000.0;
199 /* Sleep for a given interval (in seconds). Return immediately if interval < 0. */
200 void
201 time_sleep(double interval)
203 struct timespec ts;
204 double sec;
205 ts.tv_nsec = (int)(modf(interval, &sec)*1000000000.0);
206 ts.tv_sec = (int)sec;
207 nanosleep(&ts, NULL); /* ignore error if interval was < 0 */
211 /* Returns true if we are in byoyomi (or should play as if in byo yomi
212 * because remaining time per move in main time is less than byoyomi time
213 * per move). */
214 static bool
215 time_in_byoyomi(struct time_info *ti) {
216 assert(ti->dim == TD_WALLTIME);
217 if (!ti->len.t.byoyomi_time)
218 return false; // there is no byoyomi!
219 assert(ti->len.t.byoyomi_stones > 0);
220 if (!ti->len.t.main_time)
221 return true; // we _are_ in byoyomi
222 if (ti->len.t.main_time <= ti->len.t.byoyomi_time / ti->len.t.byoyomi_stones + 0.001)
223 return true; // our basic time left is less than byoyomi time per move
224 return false;
227 /* Set worst.time to all available remaining time (main time plus usable
228 * byoyomi), to be spread over returned number of moves (expected game
229 * length minus moves to be played in final byoyomi - if we would not be
230 * able to spend more time on them in main time anyway). */
231 static int
232 time_stop_set_remaining(struct time_info *ti, struct board *b, double net_lag, struct time_stop *stop)
234 int moves_left = board_estimated_moves_left(b);
235 stop->worst.time = ti->len.t.main_time;
237 if (!ti->len.t.byoyomi_time)
238 return moves_left;
240 /* Time for one move in byoyomi. */
241 assert(ti->len.t.byoyomi_stones > 0);
242 double move_time = ti->len.t.byoyomi_time / ti->len.t.byoyomi_stones;
244 /* (i) Plan to extend our thinking time to make use of byoyom. */
246 /* For Japanese byoyomi with N>1 periods, we use N-1 periods
247 * as main time, keeping the last one as insurance against
248 * unexpected net lag. */
249 if (ti->len.t.byoyomi_periods > 2) {
250 stop->worst.time += (ti->len.t.byoyomi_periods - 2) * move_time;
251 // Will add 1 more byoyomi_time just below
254 /* In case of Canadian byoyomi, include time that can be spent
255 * on its first move. */
256 stop->worst.time += move_time;
258 /* (ii) Do not play faster in main time than we would in byoyomi. */
260 /* Maximize the number of moves played uniformly in main time,
261 * while not playing faster in main time than in byoyomi.
262 * At this point, the main time remaining is stop->worst.time and
263 * already includes the first (canadian) or N-1 byoyomi periods. */
264 double real_move_time = move_time - net_lag;
265 if (real_move_time > 0) {
266 int main_moves = stop->worst.time / real_move_time;
267 if (moves_left > main_moves) {
268 /* We plan to do too many moves in main time,
269 * do the rest in byoyomi. */
270 moves_left = main_moves;
272 if (moves_left <= 0) // possible if too much lag
273 moves_left = 1;
276 return moves_left;
279 /* Adjust the recommended per-move time based on the current game phase.
280 * We expect stop->worst to be total time available, stop->desired the current
281 * per-move time allocation, and set stop->desired to adjusted per-move time. */
282 static void
283 time_stop_phase_adjust(struct board *b, int fuseki_end, int yose_start, struct time_stop *stop)
285 int bsize = (board_size(b)-2)*(board_size(b)-2);
286 fuseki_end = fuseki_end * bsize / 100; // move nb at fuseki end
287 yose_start = yose_start * bsize / 100; // move nb at yose start
288 assert(fuseki_end < yose_start);
290 /* No adjustments in yose. */
291 if (b->moves >= yose_start)
292 return;
293 int moves_to_yose = (yose_start - b->moves) / 2;
294 // ^- /2 because we only consider the moves we have to play ourselves
295 int left_at_yose_start = board_estimated_moves_left(b) - moves_to_yose;
296 if (left_at_yose_start < MIN_MOVES_LEFT)
297 left_at_yose_start = MIN_MOVES_LEFT;
299 /* This particular value of middlegame_time will continuously converge
300 * to effective "yose_time" value as we approach yose_start. */
301 double middlegame_time = stop->worst.time / left_at_yose_start;
302 if (middlegame_time < stop->desired.time)
303 return;
305 if (b->moves < fuseki_end) {
306 assert(fuseki_end > 0);
307 /* At the game start, use stop->desired.time (rather
308 * conservative estimate), then gradually prolong it. */
309 double beta = b->moves / fuseki_end;
310 stop->desired.time = middlegame_time * beta + stop->desired.time * (1 - beta);
312 } else { assert(b->moves < yose_start);
313 /* Middlegame, start with relatively large value, then
314 * converge to the uniform-timeslice yose value. */
315 stop->desired.time = middlegame_time;
319 void
320 lag_adjust(double *time, double net_lag)
322 double nolag_time = *time;
323 *time -= net_lag;
324 if (*time < MIN_THINK_WITH_LAG && nolag_time > MIN_THINK_WITH_LAG)
325 *time = MIN_THINK_WITH_LAG;
328 /* Pre-process time_info for search control and sets the desired stopping conditions. */
329 void
330 time_stop_conditions(struct time_info *ti, struct board *b, int fuseki_end, int yose_start, struct time_stop *stop)
332 /* We must have _some_ limits by now, be it random default values! */
333 assert(ti->period != TT_NULL);
335 /* Special-case limit by number of simulations. */
336 if (ti->dim == TD_GAMES) {
337 if (ti->period == TT_TOTAL) {
338 ti->period = TT_MOVE;
339 ti->len.games /= board_estimated_moves_left(b);
342 stop->desired.playouts = ti->len.games;
343 /* We force worst == desired, so note that we will NOT loop
344 * until best == winner. */
345 stop->worst.playouts = ti->len.games;
346 return;
349 assert(ti->dim == TD_WALLTIME);
352 /* Minimum net lag (seconds) to be reserved in the time for move. */
353 double net_lag = MAX_NET_LAG;
354 if (!ti->len.t.timer_start) {
355 ti->len.t.timer_start = time_now(); // we're playing the first game move
356 } else {
357 net_lag += time_now() - ti->len.t.timer_start;
358 // TODO: keep statistics to get good estimate of lag not just current move
362 if (ti->period == TT_TOTAL && time_in_byoyomi(ti)) {
363 /* Technically, we are still in main time, but we can
364 * effectively switch to byoyomi scheduling since we
365 * have less time available than one byoyomi move takes. */
366 ti->period = TT_MOVE;
370 if (ti->period == TT_MOVE) {
371 /* We are in byoyomi, or almost! */
373 /* The period can still include some tiny remnant of main
374 * time if we are just switching to byoyomi. */
375 double period_len = ti->len.t.byoyomi_time + ti->len.t.main_time;
377 stop->worst.time = period_len;
378 assert(ti->len.t.byoyomi_stones > 0);
379 stop->desired.time = period_len / ti->len.t.byoyomi_stones;
381 /* Use a larger safety margin if we risk losing on time on
382 * this move; it makes no sense to have 30s byoyomi and wait
383 * until 28s to play our move). */
384 if (stop->desired.time >= period_len - net_lag) {
385 double safe_margin = RESERVED_BYOYOMI_PERCENT * stop->desired.time / 100;
386 if (safe_margin > net_lag)
387 net_lag = safe_margin;
390 /* Make recommended_old == average(recommended_new, max) */
391 double worst_time = stop->desired.time * MAX_BYOYOMI_TIME_EXTENSION;
392 if (worst_time < stop->worst.time)
393 stop->worst.time = worst_time;
394 stop->desired.time *= (2 - MAX_BYOYOMI_TIME_EXTENSION);
396 } else { assert(ti->period == TT_TOTAL);
397 /* We are in main time. */
399 assert(ti->len.t.main_time > 0);
400 /* Set worst.time to all available remaining time, to be spread
401 * over returned number of moves. */
402 int moves_left = time_stop_set_remaining(ti, b, net_lag, stop);
404 /* Allocate even slice of the remaining time for next move. */
405 stop->desired.time = stop->worst.time / moves_left;
406 assert(stop->desired.time > 0 && stop->worst.time > 0);
407 assert(stop->desired.time <= stop->worst.time + 0.001);
409 /* Furthermore, tweak the slice based on the game phase. */
410 time_stop_phase_adjust(b, fuseki_end, yose_start, stop);
412 /* Put final upper bound on maximal time spent on the move.
413 * Keep enough time for sudden death (or near SD) games. */
414 double worst_time = stop->desired.time;
415 if (ti->len.t.byoyomi_time_max > ti->len.t.byoyomi_stones_max) {
416 worst_time *= MAX_MAIN_TIME_EXTENSION;
417 } else {
418 worst_time *= MAX_SUDDEN_DEATH_EXTENSION;
420 if (worst_time < stop->worst.time)
421 stop->worst.time = worst_time;
422 if (stop->desired.time > stop->worst.time)
423 stop->desired.time = stop->worst.time;
426 if (DEBUGL(1))
427 fprintf(stderr, "desired %0.2f, worst %0.2f, clock [%d] %0.2f + %0.2f/%d*%d, lag %0.2f\n",
428 stop->desired.time, stop->worst.time,
429 ti->dim, ti->len.t.main_time,
430 ti->len.t.byoyomi_time, ti->len.t.byoyomi_stones,
431 ti->len.t.byoyomi_periods, net_lag);
433 /* Account for lag. */
434 lag_adjust(&stop->desired.time, net_lag);
435 lag_adjust(&stop->worst.time, net_lag);