-
Notifications
You must be signed in to change notification settings - Fork 19
/
egttools.cpp
2351 lines (2087 loc) · 134 KB
/
egttools.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
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
263
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** Copyright (c) 2019-2023 Elias Fernandez
*
* This file is part of EGTtools.
*
* EGTtools 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, either version 3 of the License, or
* (at your option) any later version.
*
* EGTtools 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 EGTtools. If not, see <http://www.gnu.org/licenses/>
*/
#include "egttools.h"
#define XSTR(s) STR(s)
#define STR(s) #s
namespace py = pybind11;
using namespace std::string_literals;
using namespace egttools;
using PairwiseComparison = egttools::FinitePopulations::PairwiseMoran<egttools::Utils::LRUCache<std::string, double>>;
namespace egttools {
std::string call_get_action(const py::list &strategies, size_t time_step, int action) {
std::stringstream result;
result << "(";
for (py::handle strategy : strategies) {
result << py::cast<egttools::FinitePopulations::behaviors::AbstractNFGStrategy *>(strategy)->get_action(time_step, action) << ", ";
}
result << ")";
return result.str();
}
std::unique_ptr<egttools::FinitePopulations::NormalFormGame> init_normal_form_game_from_python_list(size_t nb_rounds,
const Eigen::Ref<const Matrix2D> &payoff_matrix, const py::list &strategies) {
egttools::FinitePopulations::NFGStrategyVector strategies_cpp;
for (py::handle strategy : strategies) {
strategies_cpp.push_back(py::cast<egttools::FinitePopulations::behaviors::AbstractNFGStrategy *>(strategy));
}
return std::make_unique<egttools::FinitePopulations::NormalFormGame>(nb_rounds, payoff_matrix, strategies_cpp);
}
std::unique_ptr<egttools::FinitePopulations::CRDGame> init_crd_game_from_python_list(int endowment,
int threshold,
int nb_rounds,
int group_size,
double risk,
double enhancement_factor,
const py::list &strategies) {
egttools::FinitePopulations::CRDStrategyVector strategies_cpp;
for (py::handle strategy : strategies) {
strategies_cpp.push_back(py::cast<egttools::FinitePopulations::behaviors::AbstractCRDStrategy *>(strategy));
}
return std::make_unique<egttools::FinitePopulations::CRDGame>(endowment, threshold, nb_rounds,
group_size, risk, enhancement_factor, strategies_cpp);
}
std::unique_ptr<egttools::FinitePopulations::games::CRDGameTU> init_crd_tu_game_from_python_list(int endowment,
int threshold,
int nb_rounds,
int group_size,
double risk,
egttools::utils::TimingUncertainty<> tu,
const py::list &strategies) {
egttools::FinitePopulations::games::CRDStrategyVector strategies_cpp;
for (py::handle strategy : strategies) {
strategies_cpp.push_back(py::cast<egttools::FinitePopulations::behaviors::AbstractCRDStrategy *>(strategy));
}
return std::make_unique<egttools::FinitePopulations::games::CRDGameTU>(endowment, threshold, nb_rounds,
group_size, risk, tu, strategies_cpp);
}
egttools::VectorXli sample_simplex_directly(int64_t nb_strategies, int64_t pop_size) {
std::mt19937_64 generator(egttools::Random::SeedGenerator::getInstance().getSeed());
egttools::VectorXli state = egttools::VectorXli::Zero(nb_strategies);
egttools::FinitePopulations::sample_simplex_direct_method<long int, long int, egttools::VectorXli, std::mt19937_64>(nb_strategies, pop_size, state, generator);
return state;
}
egttools::Vector sample_unit_simplex(int64_t nb_strategies) {
std::mt19937_64 generator(egttools::Random::SeedGenerator::getInstance().getSeed());
auto real_rand = std::uniform_real_distribution<double>(0, 1);
egttools::Vector state = egttools::Vector::Zero(nb_strategies);
egttools::FinitePopulations::sample_unit_simplex<int64_t, std::mt19937_64>(nb_strategies, state, real_rand, generator);
return state;
}
}// namespace egttools
//namespace {
//
//// inline std::string attr_doc(const py::module_ &m, const char *name, const char *doc) {
//// auto attr = m.attr(name);
//// return ".. data:: "s + name + "\n :annotation: = "s + py::cast<std::string>(py::repr(attr)) + "\n\n "s + doc + "\n\n"s;
//// }
//
//}// namespace
PYBIND11_MODULE(numerical, m) {
m.attr("__version__") = py::str(XSTR(EGTTOOLS_VERSION));
m.attr("VERSION") = py::str(XSTR(EGTTOOLS_VERSION));
m.attr("__init__") = py::str(
"The `numerical` module contains optimized "
"functions and classes to simulate evolutionary dynamics in large populations.");
m.doc() =
"The `numerical` module contains optimized functions and classes to simulate "
"evolutionary dynamics in large populations. This module is written in C++.";
// Use this function to get access to the singleton
py::class_<Random::SeedGenerator, std::unique_ptr<Random::SeedGenerator, py::nodelete>>(m, "Random", "Random seed generator.")
.def_static(
"init", []() {
return std::unique_ptr<Random::SeedGenerator, py::nodelete>(&Random::SeedGenerator::getInstance());
},
R"pbdoc(
This static method initializes the random seed generator from random_device
and returns an instance of egttools.Random which is used
to seed the random generators used across egttools.
Parameters
----------
Returns
-------
egttools.Random
An instance of the random seed generator.
)pbdoc")
.def_static(
"init", [](unsigned long int seed) {
auto instance = std::unique_ptr<Random::SeedGenerator, py::nodelete>(&Random::SeedGenerator::getInstance());
instance->setMainSeed(seed);
return instance;
},
R"pbdoc(
This static method initializes the random seed generator from seed
and returns an instance of `egttools.Random` which is used
to seed the random generators used across `egttools`.
Parameters
----------
seed : int
Integer value used to seed the random generator.
Returns
-------
egttools.Random
An instance of the random seed generator.
)pbdoc",
py::arg("seed"))
.def_property_readonly_static(
"_seed", [](const py::object &) {
return egttools::Random::SeedGenerator::getInstance().getMainSeed();
},
"The initial seed of `egttools.Random`.")
.def_static(
"generate", []() {
return egttools::Random::SeedGenerator::getInstance().getSeed();
},
R"pbdoc(
Generates a random seed.
The generated seed can be used to seed other pseudo-random generators,
so that the initial state of the simulation can always be tracked and
the simulation can be reproduced. This is very important both for debugging
purposes as well as for scientific research. However, this approach should
NOT be used in any cryptographic applications, it is NOT safe.
Returns
-------
int
A random seed which can be used to seed new random generators.
)pbdoc")
.def_static(
"seed", [](unsigned long int seed) {
egttools::Random::SeedGenerator::getInstance().setMainSeed(seed);
},
R"pbdoc(
This static methods changes the seed of `egttools.Random`.
Parameters
----------
int
The new seed for the `egttools.Random` module which is used to seed
every other pseudo-random generation in the `egttools` package.
)pbdoc",
py::arg("seed"));
// Now we define a submodule
auto mGames = m.def_submodule("games");
auto mBehaviors = m.def_submodule("behaviors");
auto mCRD = mBehaviors.def_submodule("CRD");
auto mNF = mBehaviors.def_submodule("NormalForm");
auto mNFTwoActions = mNF.def_submodule("TwoActions");
auto mData = m.def_submodule("DataStructures");
auto mDistributions = m.def_submodule("distributions");
mGames.attr("__init__") = py::str("The `egttools.numerical.games` submodule contains the available games.");
mBehaviors.attr("__init__") = py::str("The `egttools.numerical.behaviors` submodule contains the available strategies to evolve.");
mNF.attr("__init__") = py::str("The `egttools.numerical.behaviors.NormalForm` submodule contains the strategies for normal form games.");
mCRD.attr("__init__") = py::str("The `egttools.numerical.behaviors.CRD` submodule contains the strategies for the CRD.");
mNFTwoActions.attr("__init__") = py::str(
"The `TwoActions` submodule contains the strategies for "
"normal form games with 2 actions.");
mData.attr("__init__") = py::str("The `egttools.numerical.DataStructures` submodule contains helpful data structures.");
mDistributions.attr("__init__") = py::str(
"The `egttools.numerical.distributions` submodule contains "
"functions and classes that produce stochastic distributions.");
py::class_<egttools::utils::TimingUncertainty<>>(mDistributions, "TimingUncertainty")
.def(py::init<double, int>(),
R"pbdoc(
Timing uncertainty distribution container.
This class provides methods to calculate the final round of the game according to some predifined distribution, which is geometric by default.
Parameters
----------
p : float
Probability that the game will end after the minimum number of rounds.
max_rounds : int
maximum number of rounds that the game can take (if 0, there is no maximum).
)pbdoc",
py::arg("p"), py::arg("max_rounds") = 0)
.def("calculate_end", &egttools::utils::TimingUncertainty<>::calculate_end,
"Calculates the final round limiting by max_rounds, i.e., outputs a value between"
"[min_rounds, max_rounds].",
py::arg("min_rounds"), py::arg("random_generator"))
.def("calculate_full_end", &egttools::utils::TimingUncertainty<>::calculate_full_end,
"Calculates the final round, i.e., outputs a value between"
"[min_rounds, Inf].",
py::arg("min_rounds"), py::arg("random_generator"))
.def_property_readonly("p", &egttools::utils::TimingUncertainty<>::probability)
.def_property("max_rounds", &egttools::utils::TimingUncertainty<>::max_rounds,
&egttools::utils::TimingUncertainty<>::set_max_rounds);
py::class_<egttools::FinitePopulations::AbstractGame, stubs::PyAbstractGame>(mGames, "AbstractGame")
.def(py::init<>())
.def("play", &egttools::FinitePopulations::AbstractGame::play, R"pbdoc(
Updates the vector of payoffs with the payoffs of each player after playing the game.
This method will run the game using the players and player types defined in :param group_composition,
and will update the vector :param game_payoffs with the resulting payoff of each player.
Parameters
----------
group_composition : List[int]
A list with counts of the number of players of each strategy in the group.
game_payoffs : List[float]
A list used as container for the payoffs of each player
)pbdoc",
py::arg("group_composition"), py::arg("game_payoffs"))
.def("calculate_payoffs", &egttools::FinitePopulations::AbstractGame::calculate_payoffs,
R"pbdoc(
Estimates the payoffs for each strategy and returns the values in a matrix.
Each row of the matrix represents a strategy and each column a game state.
E.g., in case of a 2 player game, each entry a_ij gives the payoff for strategy
i against strategy j. In case of a group game, each entry a_ij gives the payoff
of strategy i for game state j, which represents the group composition.
Returns
-------
numpy.ndarray[numpy.float64[m, n]]
A matrix with the expected payoffs for each strategy given each possible game
state.
)pbdoc")
.def("calculate_fitness", &egttools::FinitePopulations::AbstractGame::calculate_fitness,
R"pbdoc(
Estimates the fitness for a player_type in the population with state :param strategies.
This function assumes that the player with strategy player_type is not included in
the vector of strategy counts strategies.
Parameters
----------
strategy_index : int
The index of the strategy used by the player.
pop_size : int
The size of the population.
strategies : numpy.ndarray[numpy.uint64[m, 1]]
A vector of counts of each strategy. The current state of the population.
Returns
-------
float
The fitness of the strategy in the population state given by strategies.
)pbdoc",
py::arg("strategy_index"), py::arg("pop_size"), py::arg("strategies"))
.def("__str__", &egttools::FinitePopulations::AbstractGame::toString)
.def("type", &egttools::FinitePopulations::AbstractGame::type, "returns the type of game.")
.def("payoffs", &egttools::FinitePopulations::AbstractGame::payoffs,
R"pbdoc(
Returns the payoff matrix of the game.
Returns
-------
numpy.ndarray
The payoff matrix.
)pbdoc")
.def("payoff", &egttools::FinitePopulations::AbstractGame::payoff,
R"pbdoc(
Returns the payoff of a strategy given a group composition.
If the group composition does not include the strategy, the payoff should be zero.
Parameters
----------
strategy : int
The index of the strategy used by the player.
group_composition : List[int]
List with the group composition. The structure of this list
depends on the particular implementation of this abstract method.
Returns
-------
float
The payoff value.
)pbdoc",
py::arg("strategy"), py::arg("group_composition"))
.def("nb_strategies", &egttools::FinitePopulations::AbstractGame::nb_strategies,
"Number of different strategies playing the game.")
.def("save_payoffs", &egttools::FinitePopulations::AbstractGame::save_payoffs,
R"pbdoc(
Stores the payoff matrix in a txt file.
Parameters
----------
file_name : str
Name of the file in which the data will be stored.
)pbdoc",
py::arg("file_name"));
py::class_<egttools::FinitePopulations::AbstractNPlayerGame, stubs::PyAbstractNPlayerGame, egttools::FinitePopulations::AbstractGame>(mGames, "AbstractNPlayerGame")
.def(py::init_alias<int, int>(),
R"pbdoc(
Abstract N-Player Game.
This abstract Game class can be used in most scenarios where the fitness of a strategy is calculated as its
expected payoff given the population state.
It assumes that the game is N player, since the fitness of a strategy given a population state is calculated
as the expected payoff of that strategy over all possible group combinations in the given state.
Notes
-----
It might be a good idea to overwrite the methods `__str__`, `type`, and `save_payoffs` to adapt to your
given game implementation
It assumes that you have at least the following attributes:
1. And an attribute `self.nb_strategies_` which contains the number of strategies
that you are going to analyse for the given game.
2. `self.payoffs_` which must be a numpy.ndarray and contain the payoff matrix of the game. This array
must be of shape (self.nb_strategies_, nb_group_configurations), where nb_group_configurations is the number
of possible combinations of strategies in the group. Thus, each row should give the (expected) payoff of the row
strategy when playing in a group with the column configuration. The `payoff` method provides an easy way to access
the payoffs for any group composition, by taking as arguments the index of the row strategy
and a List with the count of each possible strategy in the group.
You must still implement the methods `play` and `calculate_payoffs` which should define how the game assigns
payoffs to each strategy for each possible game context. In particular, `calculate_payoffs` should fill the
array `self.payoffs_` with the correct values as explained above. We recommend that you run this method in
the `__init__` (initialization of the object) since, these values must be set before passing the game object
to the numerical simulator (e.g., egttools.numerical.PairwiseComparisonNumerical).
Parameters
----------
nb_strategies: int
total number of possible strategies.
group_size: int
size of the group in which the game will take place.
)pbdoc",
py::arg("nb_strategies"), py::arg("group_size"), py::return_value_policy::reference_internal)
.def("play", &egttools::FinitePopulations::AbstractNPlayerGame::play, R"pbdoc(
Updates the vector of payoffs with the payoffs of each player after playing the game.
This method will run the game using the players and player types defined in :param group_composition,
and will update the vector :param game_payoffs with the resulting payoff of each player.
Parameters
----------
group_composition : List[int]
A list with counts of the number of players of each strategy in the group.
game_payoffs : List[float]
A list used as container for the payoffs of each player
)pbdoc",
py::arg("group_composition"), py::arg("game_payoffs"))
.def("calculate_payoffs", &egttools::FinitePopulations::AbstractNPlayerGame::calculate_payoffs,
R"pbdoc(
Estimates the payoffs for each strategy and returns the values in a matrix.
Each row of the matrix represents a strategy and each column a game state.
E.g., in case of a 2 player game, each entry a_ij gives the payoff for strategy
i against strategy j. In case of a group game, each entry a_ij gives the payoff
of strategy i for game state j, which represents the group composition.
Returns
-------
numpy.ndarray[numpy.float64[m, n]]
A matrix with the expected payoffs for each strategy given each possible game
state.
)pbdoc")
.def("calculate_fitness", &egttools::FinitePopulations::AbstractNPlayerGame::calculate_fitness,
R"pbdoc(
Estimates the fitness for a player_type in the population with state :param strategies.
This function assumes that the player with strategy player_type is not included in
the vector of strategy counts strategies.
Parameters
----------
strategy_index : int
The index of the strategy used by the player.
pop_size : int
The size of the population.
strategies : numpy.ndarray[numpy.uint64[m, 1]]
A vector of counts of each strategy. The current state of the population.
Returns
-------
float
The fitness of the strategy in the population state given by strategies.
)pbdoc",
py::arg("strategy_index"), py::arg("pop_size"), py::arg("strategies"))
.def("__str__", &egttools::FinitePopulations::AbstractNPlayerGame::toString)
.def("type", &egttools::FinitePopulations::AbstractNPlayerGame::type, "returns the type of game.")
.def("payoffs", &egttools::FinitePopulations::AbstractNPlayerGame::payoffs,
R"pbdoc(
Returns the payoff matrix of the game.
Returns
-------
numpy.ndarray
The payoff matrix.
)pbdoc")
.def("payoff", &egttools::FinitePopulations::AbstractNPlayerGame::payoff,
R"pbdoc(
Returns the payoff of a strategy given a group composition.
If the group composition does not include the strategy, the payoff should be zero.
Parameters
----------
strategy : int
The index of the strategy used by the player.
group_composition : List[int]
List with the group composition. The structure of this list
depends on the particular implementation of this abstract method.
Returns
-------
float
The payoff value.
)pbdoc",
py::arg("strategy"), py::arg("group_composition"))
.def("update_payoff", &egttools::FinitePopulations::AbstractNPlayerGame::update_payoff, "update an entry of the payoff matrix",
py::arg("strategy_index"), py::arg("group_configuration_index"), py::arg("value"))
.def("nb_strategies", &egttools::FinitePopulations::AbstractNPlayerGame::nb_strategies,
"Number of different strategies playing the game.")
.def("group_size", &egttools::FinitePopulations::AbstractNPlayerGame::group_size,
"Size of the group.")
.def("nb_group_configurations", &egttools::FinitePopulations::AbstractNPlayerGame::nb_group_configurations,
"Number of different group configurations.")
.def("save_payoffs", &egttools::FinitePopulations::AbstractNPlayerGame::save_payoffs,
R"pbdoc(
Stores the payoff matrix in a txt file.
Parameters
----------
file_name : str
Name of the file in which the data will be stored.
)pbdoc",
py::arg("file_name"));
m.def("calculate_state",
static_cast<size_t (*)(const size_t &, const egttools::Factors &)>(&egttools::FinitePopulations::calculate_state),
R"pbdoc(
This function converts a vector containing counts into an index.
This method was copied from @Svalorzen.
Parameters
----------
group_size : int
Maximum bin size (it can also be the population size).
group_composition : List[int]
The vector to convert from simplex coordinates to index.
Returns
-------
int
The unique index in [0, egttools.calculate_nb_states(group_size, len(group_composition))
representing the n-dimensional simplex.
See Also
--------
egttools.sample_simplex, egttools.calculate_nb_states
)pbdoc",
py::arg("group_size"), py::arg("group_composition"));
m.def("calculate_state",
static_cast<size_t (*)(const size_t &,
const Eigen::Ref<const egttools::VectorXui> &)>(&egttools::FinitePopulations::calculate_state),
R"pbdoc(
This function converts a vector containing counts into an index.
This method was copied from @Svalorzen.
Parameters
----------
group_size : int
Maximum bin size (it can also be the population size).
group_composition : numpy.ndarray[numpy.int64[m, 1]]
The vector to convert from simplex coordinates to index.
Returns
-------
int
The unique index in [0, egttools.calculate_nb_states(group_size, len(group_composition))
representing the n-dimensional simplex.
See Also
--------
egttools.sample_simplex, egttools.calculate_nb_states
)pbdoc",
py::arg("group_size"), py::arg("group_composition"));
m.def("sample_simplex",
static_cast<egttools::VectorXui (*)(size_t, const size_t &, const size_t &)>(&egttools::FinitePopulations::sample_simplex),
R"pbdoc(
Transforms a state index into a vector.
Parameters
----------
index : int
State index.
pop_size : int
Size of the population.
nb_strategies : int
Number of strategies.
Returns
-------
numpy.ndarray[numpy.int64[m, 1]]
Vector with the sampled state.
See Also
--------
egttools.numerical.calculate_state, egttools.numerical.calculate_nb_states
)pbdoc",
py::arg("index"), py::arg("pop_size"),
py::arg("nb_strategies"));
m.def("sample_simplex_directly",
&sample_simplex_directly,
R"pbdoc(
Samples an N-dimensional point directly from the simplex.
N is the number of strategies.
Parameters
----------
nb_strategies : int
Number of strategies.
pop_size : int
Size of the population.
Returns
-------
numpy.ndarray[numpy.int64[m, 1]]
Vector with the sampled state.
See Also
--------
egttools.numerical.calculate_state, egttools.numerical.calculate_nb_states, egttools.numerical.sample_simplex
)pbdoc",
py::arg("nb_strategies"),
py::arg("pop_size"));
m.def("sample_unit_simplex",
&sample_unit_simplex,
R"pbdoc(
Samples uniformly at random the unit simplex with nb_strategies dimensionse.
Parameters
----------
nb_strategies : int
Number of strategies.
Returns
-------
numpy.ndarray[numpy.int64[m, 1]]
Vector with the sampled state.
See Also
--------
egttools.numerical.calculate_state, egttools.numerical.calculate_nb_states, egttools.numerical.sample_simplex
)pbdoc",
py::arg("nb_strategies"));
#if (HAS_BOOST)
m.def(
"calculate_nb_states", [](size_t group_size, size_t nb_strategies) {
auto result = starsBars<size_t, mp::uint128_t>(group_size, nb_strategies);
return result.convert_to<size_t>();
},
R"pbdoc(
Calculates the number of states (combinations) of the members of a group in a subgroup.
It can be used to calculate the maximum number of states in a discrete simplex.
The implementation of this method follows the stars and bars algorithm (see Wikipedia).
Parameters
----------
group_size : int
Size of the group (maximum number of players/elements that can adopt each possible strategy).
nb_strategies : int
number of strategies that can be assigned to players.
Returns
-------
int
Number of states (possible combinations of strategies and players).
See Also
--------
egttools.numerical.calculate_state, egttools.numerical.sample_simplex
)pbdoc",
py::arg("group_size"), py::arg("nb_strategies"));
#else
m.def("calculate_nb_states",
&egttools::starsBars<size_t>,
R"pbdoc(
Calculates the number of states (combinations) of the members of a group in a subgroup.
It can be used to calculate the maximum number of states in a discrete simplex.
The implementation of this method follows the stars and bars algorithm (see Wikipedia).
Parameters
----------
group_size : int
Size of the group (maximum number of players/elements that can adopt each possible strategy).
nb_strategies : int
number of strategies that can be assigned to players.
Returns
-------
int
Number of states (possible combinations of strategies and players).
See Also
--------
egttools.numerical.calculate_state, egttools.numerical.sample_simplex
)pbdoc",
py::arg("group_size"), py::arg("nb_strategies"));
#endif
m.def("calculate_strategies_distribution",
static_cast<egttools::Vector (*)(size_t, size_t, egttools::SparseMatrix2D &)>(&egttools::utils::calculate_strategies_distribution),
R"pbdoc(
Calculates the average frequency of each strategy available in
the population given the stationary distribution.
Parameters
----------
pop_size : int
Size of the population.
nb_strategies : int
Number of strategies that can be assigned to players.
stationary_distribution : scipy.sparse.csr_matrix
A sparse matrix which contains the stationary distribution (the frequency with which the evolutionary system visits each
stationary state).
Returns
-------
numpy.ndarray[numpy.float64[m, 1]]
Average frequency of each strategy in the stationary evolutionary system.
See Also
--------
egttools.numerical.calculate_state, egttools.numerical.sample_simplex,
egttools.numerical.calculate_nb_states, egttools.numerical.PairwiseComparisonNumerical.estimate_stationary_distribution
egttools.numerical.calculate_nb_states, egttools.numerical.PairwiseComparisonNumerical.estimate_stationary_distribution_sparse
)pbdoc",
py::arg("pop_size"), py::arg("nb_strategies"), py::arg("stationary_distribution"));
py::class_<egttools::FinitePopulations::NormalFormGame, egttools::FinitePopulations::AbstractGame>(mGames, "NormalFormGame")
.def(py::init<size_t, const Eigen::Ref<const Matrix2D> &>(),
R"pbdoc(
Normal Form Game. This constructor assumes that there are only two possible strategies and two possible actions.
This class will run the game using the players and player types defined in :param group_composition,
and will update the vector :param game_payoffs with the resulting payoff of each player.
Parameters
----------
nb_rounds : int
Number of rounds of the game.
payoff_matrix : numpy.ndarray[numpy.float64[m, m]]
A payoff matrix of shape (nb_actions, nb_actions).
See Also
--------
egttools.games.AbstractGame,
egttools.games.CRDGame,
egttools.games.CRDGameTU,
egttools.behaviors.NormalForm.TwoActions
)pbdoc",
py::arg("nb_rounds"),
py::arg("payoff_matrix"), py::return_value_policy::reference_internal)
.def(py::init(&egttools::init_normal_form_game_from_python_list),
R"pbdoc(
Normal Form Game. This constructor allows you to define any number of strategies
by passing a list of pointers to them. All strategies must by of type AbstractNFGStrategy *.
Parameters
----------
nb_rounds : int
Number of rounds of the game.
payoff_matrix : numpy.ndarray[float]
A payoff matrix of shape (nb_actions, nb_actions).
strategies : List[egttools.behaviors.AbstractNFGStrategy]
A list containing references of AbstractNFGStrategy strategies (or child classes).
See Also
--------
egttools.games.AbstractGame
)pbdoc",
py::arg("nb_rounds"),
py::arg("payoff_matrix"), py::arg("strategies"), py::return_value_policy::reference_internal)
.def("play", &egttools::FinitePopulations::NormalFormGame::play,
R"pbdoc(
Updates the vector of payoffs with the payoffs of each player after playing the game.
This method will run the game using the players and player types defined in :param group_composition,
and will update the vector :param game_payoffs with the resulting payoff of each player.
Parameters
----------
group_composition : List[int]
A list with counts of the number of players of each strategy in the group.
game_payoffs : List[float]
A list used as container for the payoffs of each player
)pbdoc",
py::arg("group_composition"), py::arg("game_payoffs"))
.def("calculate_payoffs", &egttools::FinitePopulations::NormalFormGame::calculate_payoffs,
R"pbdoc(
Estimates the payoffs for each strategy and returns the values in a matrix.
Each row of the matrix represents a strategy and each column a game state.
E.g., in case of a 2 player game, each entry a_ij gives the payoff for strategy
i against strategy j. In case of a group game, each entry a_ij gives the payoff
of strategy i for game state j, which represents the group composition.
This method also updates a matrix that stores the cooperation level of each strategy
against any other.
Returns
-------
numpy.ndarray[numpy.float64[m, n]]
A matrix with the expected payoffs for each strategy given each possible game
state.
)pbdoc")
.def("calculate_fitness", &egttools::FinitePopulations::NormalFormGame::calculate_fitness,
R"pbdoc(
Estimates the fitness for a player_type in the population with state :param strategies.
This function assumes that the player with strategy player_type is not included in
the vector of strategy counts strategies.
Parameters
----------
player_type : int
The index of the strategy used by the player.
pop_size : int
The size of the population.
strategies : numpy.ndarray[numpy.uint64[m, 1]]
A vector of counts of each strategy. The current state of the population.
Returns
-------
float
The fitness of the strategy in the population state given by strategies.
)pbdoc",
py::arg("player_strategy"),
py::arg("population_size"), py::arg("population_state"))
.def("calculate_cooperation_rate", &egttools::FinitePopulations::NormalFormGame::calculate_cooperation_level,
R"pbdoc(
Calculates the rate/level of cooperation in the population at a given population state.
Parameters
----------
population_size : int
The size of the population.
population_state : numpy.ndarray[numpy.uint64[m, 1]]
A vector of counts of each strategy in the population.
The current state of the population.
Returns
-------
float
The level of cooperation at the population_state.
)pbdoc",
py::arg("population_size"), py::arg("population_state"))
.def("__str__", &egttools::FinitePopulations::NormalFormGame::toString)
.def("type", &egttools::FinitePopulations::NormalFormGame::type)
.def("payoffs", &egttools::FinitePopulations::NormalFormGame::payoffs,
R"pbdoc(
Returns the payoff matrix of the game.
Returns
-------
numpy.ndarray
The payoff matrix.
)pbdoc",
py::return_value_policy::reference_internal)
.def("payoff", &egttools::FinitePopulations::NormalFormGame::payoff,
R"pbdoc(
Returns the payoff of a strategy given a strategy pair.
If the group composition does not include the strategy, the payoff should be zero.
Parameters
----------
strategy : int
The index of the strategy used by the player.
strategy_pair : List[int]
List with the group composition. The structure of this list
depends on the particular implementation of this abstract method.
Returns
-------
float
The payoff value.
)pbdoc",
py::arg("strategy"),
py::arg("strategy_pair"))
.def("expected_payoffs", &egttools::FinitePopulations::NormalFormGame::expected_payoffs, "returns the expected payoffs of each strategy vs another", py::return_value_policy::reference_internal)
.def("nb_strategies", &egttools::FinitePopulations::NormalFormGame::nb_strategies,
"Number of different strategies which are playing the game.")
.def_property_readonly("nb_rounds", &egttools::FinitePopulations::NormalFormGame::nb_rounds,
"Number of rounds of the game.")
.def_property_readonly("nb_states", &egttools::FinitePopulations::NormalFormGame::nb_states,
"Number of combinations of 2 strategies that can be matched in the game.")
.def_property_readonly("strategies", &egttools::FinitePopulations::NormalFormGame::strategies,
"A list with pointers to the strategies that are playing the game.")
.def("save_payoffs", &egttools::FinitePopulations::NormalFormGame::save_payoffs,
R"pbdoc(
Stores the payoff matrix in a txt file.
Parameters
----------
file_name : str
Name of the file in which the data will be stored.
)pbdoc");
py::class_<egttools::FinitePopulations::CRDGame, egttools::FinitePopulations::AbstractGame>(mGames, "CRDGame")
.def(py::init(&egttools::init_crd_game_from_python_list),
R"pbdoc(
Collective Risk Dilemma. This allows you to define any number of strategies by passing them
as a list. All strategies must be of type AbstractCRDStrategy *.
The CRD dilemma implemented here follows the description of:
Milinski, M., Sommerfeld, R. D., Krambeck, H.-J., Reed, F. A.,
& Marotzke, J. (2008). The collective-risk social dilemma and the prevention of simulated
dangerous climate change. Proceedings of the National Academy of Sciences of the United States of America, 105(7),
2291–2294. https://doi.org/10.1073/pnas.0709546105
Parameters
----------
endowment : int
Initial endowment for all players.
threshold : int
Collective target that the group must reach.
nb_rounds : int
Number of rounds of the game.
group_size : int
Size of the group that will play the CRD.
risk : float
The probability that all members will lose their remaining endowment if the threshold is not achieved.
enhancement_factor: float
The payoffs of each strategy are multiplied by this factor if the target is reached
(this may enables the inclusion of a surplus for achieving the goal).
strategies : List[egttools.behaviors.CRD.AbstractCRDStrategy]
A list containing references of AbstractCRDStrategy strategies (or child classes).
See Also
--------
egttools.games.AbstractGame,
egttools.games.NormalFormGame,
egttools.behaviors.CRD.AbstractCRDStrategy
)pbdoc",
py::arg("endowment"),
py::arg("threshold"),
py::arg("nb_rounds"),
py::arg("group_size"),
py::arg("risk"),
py::arg("enhancement_factor"),
py::arg("strategies"), py::return_value_policy::reference_internal)
.def("play", &egttools::FinitePopulations::CRDGame::play,
R"pbdoc(
Updates the vector of payoffs with the payoffs of each player after playing the game.
This method will run the game using the players and player types defined in :param group_composition,
and will update the vector :param game_payoffs with the resulting payoff of each player.
Parameters
----------
group_composition : List[int]
A list with counts of the number of players of each strategy in the group.
game_payoffs : List[float]
A list used as container for the payoffs of each player
)pbdoc")
.def("calculate_payoffs", &egttools::FinitePopulations::CRDGame::calculate_payoffs,
R"pbdoc(
Estimates the payoffs for each strategy and returns the values in a matrix.
Each row of the matrix represents a strategy and each column a game state.
Therefore, each entry a_ij gives the payoff
of strategy i for game state j, which represents the group composition.
It also updates the coop_level matrices by calculating level of cooperation
at any given population state
Returns
-------
numpy.ndarray[numpy.float64[m, n]]
A matrix with the expected payoffs for each strategy given each possible game
state.
)pbdoc")
.def("calculate_fitness", &egttools::FinitePopulations::CRDGame::calculate_fitness,
R"pbdoc(
Estimates the fitness for a player_type in the population with state :param strategies.
This function assumes that the player with strategy player_type is not included in
the vector of strategy counts strategies.
Parameters
----------
player_strategy : int
The index of the strategy used by the player.
pop_size : int
The size of the population.
population_state : numpy.ndarray[numpy.uint64[m, 1]]
A vector of counts of each strategy. The current state of the population.
Returns
-------
float
The fitness of the strategy in the population state given by strategies.
)pbdoc",
py::arg("player_strategy"),
py::arg("pop_size"), py::arg("population_state"))
.def("calculate_population_group_achievement", &egttools::FinitePopulations::CRDGame::calculate_population_group_achievement,
"calculates the group achievement in the population at a given state.",
py::arg("population_size"), py::arg("population_state"))
.def("calculate_group_achievement", &egttools::FinitePopulations::CRDGame::calculate_group_achievement,
"calculates the group achievement for a given stationary distribution.",
py::arg("population_size"), py::arg("stationary_distribution"))
.def("calculate_polarization", &egttools::FinitePopulations::CRDGame::calculate_polarization,
"calculates the fraction of players that contribute above, below or equal to the fair contribution (E/2)"
"in a give population state.",
py::arg("population_size"), py::arg("population_state"))
.def("calculate_polarization_success", &egttools::FinitePopulations::CRDGame::calculate_polarization_success,
"calculates the fraction of players (from successful groups)) that contribute above, below or equal to the fair contribution (E/2)"
"in a give population state.",
py::arg("population_size"), py::arg("population_state"))
.def("__str__", &egttools::FinitePopulations::CRDGame::toString)
.def("type", &egttools::FinitePopulations::CRDGame::type)
.def("payoffs", &egttools::FinitePopulations::CRDGame::payoffs,
R"pbdoc(
Returns the expected payoffs of each strategy vs each possible game state.
Returns
-------
numpy.ndarray[np.float64[m,n]]
The payoff matrix.
)pbdoc")
.def("payoff", &egttools::FinitePopulations::CRDGame::payoff,
R"pbdoc(
Returns the payoff of a strategy given a group composition.
If the group composition does not include the strategy, the payoff should be zero.
Parameters
----------
strategy : int
The index of the strategy used by the player.
group_composition : List[int]
List with the group composition. The structure of this list
depends on the particular implementation of this abstract method.
Returns
-------
float
The payoff value.
)pbdoc",
py::arg("strategy"),
py::arg("group_composition"))
.def_property_readonly("group_achievement_per_group", &egttools::FinitePopulations::CRDGame::group_achievements)