tarot_perceptron_bootstrap.c 14.5 KB
Newer Older
Vivien Kraus's avatar
Vivien Kraus committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* tarot implements the rules of the tarot game
 * Copyright (C) 2019  Vivien Kraus
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "program_commons.h"

static size_t n_hidden_layers;
static size_t *hidden_sizes;
static double learning_rate;
static double exploration;
23
static double current_exploration = 1;
Vivien Kraus's avatar
Vivien Kraus committed
24
25
26
27
static struct yarrow256_ctx generator;

static void parse_options (int argc, char *argv[]);

Vivien Kraus's avatar
Vivien Kraus committed
28
static void self_learn (TarotPerceptron * perceptron);
Vivien Kraus's avatar
Vivien Kraus committed
29
30
31
32
33

int
main (int argc, char *argv[])
{
  TarotPerceptron *perceptron;
Vivien Kraus's avatar
Vivien Kraus committed
34
35
  size_t n_weights, i;
  double *weights;
Vivien Kraus's avatar
Vivien Kraus committed
36
37
  tarot_program_setup ();
  parse_options (argc, argv);
Vivien Kraus's avatar
Vivien Kraus committed
38
39
  perceptron =
    tarot_perceptron_alloc (n_hidden_layers, hidden_sizes, learning_rate);
40
  /* Initial weights are not initialized correctly */
Vivien Kraus's avatar
Vivien Kraus committed
41
42
43
  tarot_perceptron_save_alloc (perceptron, &n_weights, &weights);
  for (i = 0; i < n_weights; i++)
    {
44
45
      /* We also need to add some random noise, because the
       * initialization is weak */
46
47
      double mini = -2;
      double maxi = 2;
48
49
50
51
52
53
54
      size_t random_n;
      size_t random_max = (size_t) (-1);
      uint8_t random_data[sizeof (random_n)];
      double t = 0;
      yarrow256_random (&generator, sizeof (random_data), random_data);
      memcpy (&random_n, random_data, sizeof (random_data));
      t = ((double) random_n) / ((double) random_max);
55
      weights[i] = (mini * (1 - t) + maxi * t);
Vivien Kraus's avatar
Vivien Kraus committed
56
57
58
    }
  tarot_perceptron_load (perceptron, 0, n_weights, weights);
  free (weights);
59
60
61
  fprintf (stderr,
           _
           ("Current exploration\tMean update\tValidation score\tMaximum weight\n"));
Vivien Kraus's avatar
Vivien Kraus committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
  while (1)
    {
      self_learn (perceptron);
    }
  tarot_perceptron_free (perceptron);
  return EXIT_SUCCESS;
}

static void
parse_options (int argc, char *argv[])
{
  int c;
  char default_seed[] = "default";
  uint8_t *seed;
  char *end;
Vivien Kraus's avatar
Vivien Kraus committed
77
  exploration = 0.05;
Vivien Kraus's avatar
Vivien Kraus committed
78
  learning_rate = 1e-8;
Vivien Kraus's avatar
Vivien Kraus committed
79
80
81
82
  yarrow256_init (&generator, 0, NULL);
  yarrow256_seed (&generator, strlen (default_seed), (void *) default_seed);
  while (1)
    {
Vivien Kraus's avatar
Vivien Kraus committed
83
84
85
86
87
88
89
90
      static struct option long_options[] = {
        {N_("help"), no_argument, 0, 'h'},
        {N_("version"), no_argument, 0, 'v'},
        {N_("learning-rate"), required_argument, 0, 'r'},
        {N_("exploration"), required_argument, 0, 'e'},
        {N_("seed"), required_argument, 0, 's'},
        {0, 0, 0, 0}
      };
Vivien Kraus's avatar
Vivien Kraus committed
91
      int option_index = 0;
Vivien Kraus's avatar
Vivien Kraus committed
92
93
94
95
96
97
      for (option_index = 0; long_options[option_index].name != NULL;
           option_index++)
        {
          long_options[option_index].name =
            _(long_options[option_index].name);
        }
Vivien Kraus's avatar
Vivien Kraus committed
98
99
100
101
102
103
104
105
106
      option_index = 0;
      c = getopt_long (argc, argv, "hvr:e:s:", long_options, &option_index);
      if (c == -1)
        break;
      switch (c)
        {
        case 0:
          break;

Vivien Kraus's avatar
Vivien Kraus committed
107
108
109
        case 'h':
          printf (_
                  ("Usage: tarot-perceptron-bootstrap [OPTIONS]... [HIDDEN_SIZE]...\n\
Vivien Kraus's avatar
Vivien Kraus committed
110
111
112
113
114
115
116
117
Learn to play by trial and error.  Options:\n\
- -h, --help: print this message and exit;\n\
- -v, --version: print the program version and exit;\n\
- -r, --learning-rate=LR: define the learning rate;\n\
- -e, --exploration=FRAC: define the probability to play at random;\n\
- -s SEED, --seed=\"SEED\": set the seed for the random deal.  SEED\n\
   must not be empty.\n\
"));
Vivien Kraus's avatar
Vivien Kraus committed
118
119
          exit (EXIT_SUCCESS);
          break;
Vivien Kraus's avatar
Vivien Kraus committed
120

Vivien Kraus's avatar
Vivien Kraus committed
121
122
        case 'v':
          printf (_("%s (libtarot %s)\n\
Vivien Kraus's avatar
Vivien Kraus committed
123
\n\
Vivien Kraus's avatar
Vivien Kraus committed
124
125
126
Copyright © 2019 Vivien Kraus\nThis is free software; see the source for copying conditions.  There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"), "tarot-perceptron-bootstrap", tarot_libtarot_version ());
          exit (EXIT_SUCCESS);
          break;
Vivien Kraus's avatar
Vivien Kraus committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

        case 'r':
          learning_rate = strtod (optarg, &end);
          if (learning_rate <= 0)
            {
              fprintf (stderr,
                       _
                       ("Error: the learning rate should be a positive number, not '%s'.\n"),
                       optarg);
              exit (EXIT_FAILURE);
            }
          break;

        case 'e':
          exploration = strtod (optarg, &end);
          if (exploration < 0 || exploration > 1)
            {
              fprintf (stderr,
                       _
                       ("Error: the exploration probability should be a probability (between 0 and 1), not '%s'.\n"),
                       optarg);
              exit (EXIT_FAILURE);
            }
          break;

        case 's':
Vivien Kraus's avatar
Vivien Kraus committed
153
154
          seed = xmalloc (strlen (optarg) + 1);
          memcpy (seed, optarg, strlen (optarg) + 1);
Vivien Kraus's avatar
Vivien Kraus committed
155
156
157
158
159
160
161
162
163
164
165
          if (strlen (optarg) == 0)
            {
              fprintf (stderr, _("Error: the seed must not be empty.\n"));
              exit (EXIT_FAILURE);
            }
          yarrow256_seed (&generator, strlen (optarg), seed);
          free (seed);
          break;

        case '?':
          /* getopt_long already printed an error message. */
Vivien Kraus's avatar
Vivien Kraus committed
166
          exit (EXIT_FAILURE);
Vivien Kraus's avatar
Vivien Kraus committed
167
168
169
170
171
172
173
174
175
176
177
178
          break;

        default:
          abort ();
        }
    }
  n_hidden_layers = argc - optind;
  hidden_sizes = xmalloc (n_hidden_layers * sizeof (size_t));
  for (c = 0; (size_t) c < n_hidden_layers; c++)
    {
      hidden_sizes[c] = strtoul (argv[optind + c], &end, 10);
      if (strcmp (end, "") != 0)
Vivien Kraus's avatar
Vivien Kraus committed
179
180
181
        {
          hidden_sizes[c] = 0;
        }
Vivien Kraus's avatar
Vivien Kraus committed
182
      if (hidden_sizes[c] == 0)
Vivien Kraus's avatar
Vivien Kraus committed
183
184
185
186
187
188
189
        {
          fprintf (stderr,
                   _
                   ("Error: the %d-th dimension should be a strictly positive integer, not '%s'.\n"),
                   c, argv[optind + c]);
          exit (EXIT_FAILURE);
        }
Vivien Kraus's avatar
Vivien Kraus committed
190
191
192
    }
}

Vivien Kraus's avatar
Vivien Kraus committed
193
194
static TarotGameEvent *
random_move (const TarotGame * game)
Vivien Kraus's avatar
Vivien Kraus committed
195
{
Vivien Kraus's avatar
Vivien Kraus committed
196
197
198
199
200
201
202
203
204
205
  TarotBid mini_bid;
  int decl_allowed;
  TarotPlayer next;
  TarotNumber mini_call;
  size_t n_cards;
  size_t n_prio;
  size_t n_additional;
  TarotCard *prio;
  TarotCard *additional;
  if (tarot_game_get_hint_bid (game, &next, &mini_bid) == TAROT_GAME_OK)
Vivien Kraus's avatar
Vivien Kraus committed
206
    {
207
      TarotBid bids[] = {
208
209
210
211
212
213
214
        TAROT_PASS,
        TAROT_TAKE,
        TAROT_TAKE,
        TAROT_TAKE,
        TAROT_PUSH,
        TAROT_PUSH,
        TAROT_STRAIGHT_KEEP,
215
216
        TAROT_DOUBLE_KEEP
      };
Vivien Kraus's avatar
Vivien Kraus committed
217
      size_t position;
Vivien Kraus's avatar
Vivien Kraus committed
218
      uint8_t position_data[sizeof (position)];
Vivien Kraus's avatar
Vivien Kraus committed
219
      yarrow256_random (&generator, sizeof (position_data), position_data);
Vivien Kraus's avatar
Vivien Kraus committed
220
      memcpy (&position, position_data, sizeof (position));
221
222
223
224
225
226
227
228
229
      position %= (sizeof (bids) / sizeof (bids[0]));
      if (bids[position] >= mini_bid)
        {
          return tarot_game_event_alloc_bid (bids[position]);
        }
      else
        {
          return tarot_game_event_alloc_bid (TAROT_PASS);
        }
Vivien Kraus's avatar
Vivien Kraus committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
    }
  else if (tarot_game_get_hint_decl (game, &next, &decl_allowed) ==
           TAROT_GAME_OK)
    {
      uint8_t no_decl;
      /* Even in high-exploration scenarios, we want to avoid slam
       * declarations. */
      yarrow256_random (&generator, sizeof (no_decl), &no_decl);
      no_decl %= 16;
      if (no_decl == 0 && decl_allowed)
        {
          return tarot_game_event_alloc_decl (1);
        }
      else
        {
          return tarot_game_event_alloc_decl (0);
        }
    }
  else if (tarot_game_get_hint_call (game, &next, &mini_call) ==
           TAROT_GAME_OK)
    {
      static const TarotSuit suits[] = {
        TAROT_HEARTS, TAROT_CLUBS, TAROT_DIAMONDS, TAROT_SPADES
      };
      uint8_t suit_i;
      TarotCard c;
      yarrow256_random (&generator, sizeof (suit_i), &suit_i);
      suit_i %= (sizeof (suits) / sizeof (suits[0]));
      if (tarot_of (mini_call, suits[suit_i], &c) != 0)
        {
          assert (0);
        }
      return tarot_game_event_alloc_call (c);
Vivien Kraus's avatar
Vivien Kraus committed
263
    }
Vivien Kraus's avatar
Vivien Kraus committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
  else
    if (tarot_game_get_hint_discard_alloc
        (game, &next, &n_cards, &n_prio, &prio, &n_additional,
         &additional) == TAROT_GAME_OK)
    {
      TarotCard selected[78];
      size_t n_selected = 0;
      size_t n_selectable = n_prio;
      TarotCard *selectable = prio;
      size_t i;
      if (n_prio < n_cards)
        {
          n_selectable = n_additional;
          selectable = additional;
          for (n_selected = 0; n_selected < n_prio; n_selected++)
            {
              selected[n_selected] = prio[n_selected];
            }
        }
      for (i = n_selected; i < n_cards; i++)
        {
          size_t position;
          uint8_t position_data[sizeof (position)];
          yarrow256_random (&generator, sizeof (position), position_data);
          memcpy (&position, position_data, sizeof (position));
          position %= n_selectable;
          selected[i] = selectable[position];
          selectable[position] = selectable[--n_selectable];
        }
      free (prio);
      free (additional);
      return tarot_game_event_alloc_discard (n_cards, selected);
    }
  else if (tarot_game_get_hint_card_alloc (game, &next, &n_prio, &prio) ==
           TAROT_GAME_OK)
    {
      TarotCard selected;
      size_t position;
      uint8_t position_data[sizeof (position)];
      yarrow256_random (&generator, sizeof (position), position_data);
      memcpy (&position, position_data, sizeof (position));
      position %= n_prio;
      selected = prio[position];
      free (prio);
      return tarot_game_event_alloc_card (selected);
    }
  assert (0);
  return NULL;
Vivien Kraus's avatar
Vivien Kraus committed
312
313
}

314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
static int
is_empty_game (const TarotGame * game)
{
  size_t i_bid;
  size_t n_bids;
  TarotBid *bids;
  if (tarot_game_get_bids_alloc (game, &n_bids, &bids) != TAROT_GAME_OK)
    {
      assert (0);
    }
  for (i_bid = 0; i_bid < n_bids; i_bid++)
    {
      if (bids[i_bid] != TAROT_PASS)
        {
          free (bids);
          return 0;
        }
    }
  free (bids);
  return 1;
}

Vivien Kraus's avatar
Vivien Kraus committed
336
static void
Vivien Kraus's avatar
Vivien Kraus committed
337
self_learn (TarotPerceptron * perceptron)
Vivien Kraus's avatar
Vivien Kraus committed
338
339
340
341
342
343
344
345
346
{
  uint8_t option = 0;
  size_t n_players;
  int with_call;
  TarotGame *game = tarot_game_alloc ();
  TarotGameEvent *setup_event, *deal_event;
  uint8_t sub_seed[256];
  size_t n_scores;
  double metric;
347
  static int until_print_game = 100;
348
  double exploration_reduction_remaining = current_exploration - exploration;
349
350
351
352
353
  TarotPlayer forced_taker;
  TarotCard forced_call;
  size_t n_owners;
  TarotPlayer owners[78];
  double confidence;
354
  exploration_reduction_remaining *= 0.9999;
355
  current_exploration = exploration + exploration_reduction_remaining;
Vivien Kraus's avatar
Vivien Kraus committed
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
  yarrow256_random (&generator, sizeof (option), &option);
  yarrow256_random (&generator, sizeof (sub_seed), sub_seed);
  if (option % 4 == 0)
    {
      n_players = 3;
      with_call = 0;
    }
  else if (option % 4 == 1)
    {
      n_players = 4;
      with_call = 0;
    }
  else if (option % 4 == 2)
    {
      n_players = 5;
      with_call = 0;
    }
  else
    {
      n_players = 5;
      with_call = 1;
    }
  setup_event = tarot_game_event_alloc_setup (n_players, with_call);
  if (tarot_game_add_event (game, setup_event) != TAROT_GAME_OK)
    {
      assert (0);
    }
  tarot_game_event_free (setup_event);
  deal_event =
    tarot_game_event_alloc_deal_all_random (n_players, sizeof (sub_seed),
                                            sub_seed);
  if (tarot_game_add_event (game, deal_event) != TAROT_GAME_OK)
    {
      tarot_game_event_free (deal_event);
      tarot_game_free (game);
      return;
    }
393
394
395
396
397
398
399
400
401
  if (tarot_game_event_get_deal_all (deal_event, &n_owners, 0, 78, owners) !=
      TAROT_EVENT_OK)
    {
      assert (0);
    }
  assert (n_owners == 78);
  forced_taker =
    tarot_features_strongest_player (n_players, with_call, n_owners, owners,
                                     &confidence, &forced_call);
Vivien Kraus's avatar
Vivien Kraus committed
402
  tarot_game_event_free (deal_event);
403
404
405
406
407
408
409
410
411
412
413
  if (tarot_game_duplicate_set_taker (game, forced_taker) != TAROT_GAME_OK)
    {
      assert (0);
    }
  if (with_call)
    {
      if (tarot_game_duplicate_set_call (game, forced_call) != TAROT_GAME_OK)
        {
          assert (0);
        }
    }
Vivien Kraus's avatar
Vivien Kraus committed
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
  while (tarot_game_get_scores (game, &n_scores, 0, 0, NULL) != TAROT_GAME_OK)
    {
      TarotCard *dog;
      size_t n_dog;
      if (tarot_game_can_autoreveal_alloc (game, &n_dog, &dog))
        {
          TarotGameEvent *dog_event = tarot_game_event_alloc_dog (n_dog, dog);
          free (dog);
          if (tarot_game_add_event (game, dog_event) != TAROT_GAME_OK)
            {
              assert (0);
            }
          tarot_game_event_free (dog_event);
        }
      else
        {
          uint8_t behavior_data[sizeof (unsigned long)];
          unsigned long behavior;
          unsigned long behavior_max = (unsigned long) (-1);
          double behavior_dbl;
          double max_dbl = behavior_max;
          double score;
Vivien Kraus's avatar
Vivien Kraus committed
436
          TarotGameEvent *next;
Vivien Kraus's avatar
Vivien Kraus committed
437
438
439
440
          yarrow256_random (&generator, sizeof (behavior_data),
                            behavior_data);
          memcpy (&behavior, behavior_data, sizeof (behavior));
          behavior_dbl = behavior;
441
          if (behavior_dbl / max_dbl < current_exploration)
Vivien Kraus's avatar
Vivien Kraus committed
442
            {
Vivien Kraus's avatar
Vivien Kraus committed
443
              next = random_move (game);
Vivien Kraus's avatar
Vivien Kraus committed
444
            }
Vivien Kraus's avatar
Vivien Kraus committed
445
          else
Vivien Kraus's avatar
Vivien Kraus committed
446
            {
Vivien Kraus's avatar
Vivien Kraus committed
447
448
449
              next =
                tarot_game_event_dup (tarot_perceptron_best
                                      (perceptron, game, &score));
Vivien Kraus's avatar
Vivien Kraus committed
450
            }
Vivien Kraus's avatar
Vivien Kraus committed
451
          if (tarot_game_add_event (game, next) != TAROT_GAME_OK)
Vivien Kraus's avatar
Vivien Kraus committed
452
            {
Vivien Kraus's avatar
Vivien Kraus committed
453
              assert (0);
Vivien Kraus's avatar
Vivien Kraus committed
454
            }
Vivien Kraus's avatar
Vivien Kraus committed
455
          tarot_game_event_free (next);
Vivien Kraus's avatar
Vivien Kraus committed
456
457
458
        }
    }
  metric = tarot_perceptron_validate (perceptron, game);
459
460
  if (--until_print_game == 0)
    {
Vivien Kraus's avatar
Vivien Kraus committed
461
      if (!is_empty_game (game))
Vivien Kraus's avatar
Vivien Kraus committed
462
463
464
465
466
467
	{
	  double *weights = NULL, max_weight = 0;
	  size_t n = 0, w;
	  double update = tarot_perceptron_learn_game (perceptron, game);
          char *xml = tarot_game_save_to_xml_alloc (game);
	  tarot_perceptron_save_alloc (perceptron, &n, &weights);
468
	  setlocale (LC_NUMERIC, "C");
Vivien Kraus's avatar
Vivien Kraus committed
469
470
471
472
	  for (w = 0; w < n; w++)
	    {
	      if (w != 0)
		{
473
		  printf (",");
Vivien Kraus's avatar
Vivien Kraus committed
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
		}
	      printf ("%f", weights[w]);
	      if (weights[w] > max_weight || -weights[w] > max_weight)
		{
		  if (weights[w] > max_weight)
		    {
		      max_weight = weights[w];
		    }
		  else
		    {
		      max_weight = -weights[w];
		    }
		}
	    }
	  printf ("\n");
489
	  setlocale (LC_NUMERIC, "");
Vivien Kraus's avatar
Vivien Kraus committed
490
491
492
493
494
495
	  fprintf (stderr, "%g\t%g\t%g\t%g\n", current_exploration, update,
		   metric, max_weight);
	  free (weights);
          fprintf (stderr, "%s\n", xml);
          free (xml);
	}
496
497
      until_print_game = 100;
    }
Vivien Kraus's avatar
Vivien Kraus committed
498
499
  tarot_game_free (game);
}