-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvolution-of-Trust.py
executable file
·593 lines (528 loc) · 18 KB
/
Evolution-of-Trust.py
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
# -*- coding: utf-8 -*-
"""Evolution of Trust python coding.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1NLja4F19_sU8InI9Ljn0fxLzqTgBhMCp
"""
import numpy as np
from numba import jit
from itertools import combinations
import statistics
import ctypes
import time
import sys
import random
import math
import cProfile
class Gamer:
__slots__ = ['former_round', 'output', 'points']
def __init__(self):
self.former_round = None
self.output = None
self.points = 0
def end_of_turns(self):
self.former_round, self.output = None, None
def make_decision(self):
raise NotImplementedError
class copycat(Gamer):
def __init__(self):
super().__init__()
def make_decision(self): #copycat copies the other's decision
if self.former_round == None:
self.output = 1
return self.output
else:
self.output = self.former_round
return self.output
class the_believer(Gamer):
def __init__(self):
super().__init__()
def make_decision(self): #the_believer always trusts
self.output = 1
return self.output
class the_selfish(Gamer):
def __init__(self):
super().__init__()
def make_decision(self): #the_selfish always betrays
self.output = 0
return self.output
class the_chaos(Gamer):
def __init__(self):
super().__init__()
def make_decision(self): #the_choas returns random value
self.output = random.randint(0, 1)
return self.output
class the_stubborn(Gamer):
__slots__ = ['is_betrayed']
def __init__(self):
super().__init__()
self.is_betrayed = 0
def make_decision(self): #trust until betrayed, and then always betray
if self.former_round == None or self.former_round == 1 and self.is_betrayed == 0:
self.output = 1
return self.output
self.is_betrayed = 1
self.output = 0
return self.output
def end_of_turns(self):
super().end_of_turns()
self.is_betrayed = 0
class the_generous_copycat(Gamer):
__slots__ = ['tolerance', 'betrayed_times']
def __init__(self):
super().__init__()
self.tolerance = 2
self.betrayed_times = 0
def make_decision(self): #trust unless betrayed for consecutive tolerance times
if self.former_round == 0:
self.betrayed_times += 1
else:
self.betrayed_times = 0
if self.former_round == None or self.betrayed_times < self.tolerance:
self.output = 1
return self.output
self.output = 0
return self.output
def end_of_turns(self):
super().end_of_turns()
self.betrayed_times = 0
class pavlov(Gamer):
__slots__ = ['default_output']
def __init__(self):
super().__init__()
self.default_output =1
def make_decision(self): #if former_round == output, cooperate, else defect
if self.former_round == None:
self.output = self.default_output
return self.output
if self.former_round == self.output:
self.output = 1
return self.output
self.output = 0
return self.output
class majority_follower(Gamer):
__slots__ = ['oppo_total', 'default_output']
def __init__(self):
super().__init__()
self.oppo_total = 0
self.default_output = 1
def make_decision(self):
if self.former_round == 1:
self.oppo_total += 1
elif self.former_round == 0:
self.oppo_total += -1
if self.former_round == None or self.oppo_total == 0:
self.output = self.default_output
return self.output
if self.oppo_total > 0:
self.output = 1
return self.output
self.output = 0
return self.output
def end_of_turns(self):
super().end_of_turns()
self.oppo_total = 0
class the_mean_copycat(Gamer):
__slots__ = ['revenge_times', 'revenge_count']
def __init__(self):
super().__init__()
self.revenge_times = 2 #default
self.revenge_count = 0
def make_decision(self):
if self.revenge_count > 0:
self.output = 0
self.revenge_count += 1
if self.revenge_count == self.revenge_times:
self.revenge_count =0
return self.output
if self.former_round == 0:
self.output = 0
self.revenge_count += 1
return self.output
self.output = 1
return self.output
def end_of_turns(self):
super().end_of_turns()
self.revenge_count = 0
class the_vicious_copycat(Gamer):
def __init__(self):
super().__init__()
def make_decision(self):
if self.former_round == None:
self.output = 0
return self.output
else:
self.output = self.former_round
return self.output
class operator_gamer(Gamer):
__slots__ = ['default_output' ,'operator']
def __init__(self):
super().__init__()
self.default_output = 1
self.operator = 10
# self.operator default value is 10, namely a copycat
# self.operator must be an integer in range(16), namely 0 to 15
def make_decision(self):
if self.operator > 15 or self.operator < 0:
raise ValueError('operator must be an integer in range(16)')
if self.former_round == None:
self.output = self.default_output
return self.output
temp1 = self.output
temp2 = self.former_round
if temp1 and temp2:
self.output = (self.operator >> 3) & 1
elif not (temp1 or temp2):
self.output = self.operator & 1
elif temp1:
self.output = (self.operator >> 2) & 1
else:
self.output = (self.operator >> 1) & 1
return self.output
class the_tricker(Gamer):
__slots__ = ['cooperate_times']
def __init__(self):
super().__init__()
self.cooperate_times = 1
def make_decision(self):
if self.cooperate_times > 0:
self.output = 1
self.cooperate_times -= 1
return self.output
self.output = 0
return self.output
def end_of_turns(self):
super().end_of_turns()
self.cooperate_times = 1
class detective(Gamer):
__slots__ = ['sequence_deci', 'is_betrayed', 'count_turns']
def __init__(self):
super().__init__()
self.sequence_deci = 13 #default is 13, namely [1, 1, 0, 1]
self.is_betrayed = 0
self.count_turns = 0
def make_decision(self):
if len(format(self.sequence_deci, 'b')) > self.count_turns:
self.output = self.sequence_deci>>(len(format(self.sequence_deci, 'b'))-self.count_turns-1) & 1
self.count_turns += 1
if self.former_round == 0:
self.is_betrayed = 1
return self.output
if self.is_betrayed == 1:
temp = copycat()
temp.former_round, temp.output = self.former_round, self.output
self.output = temp.make_decision()
return self.output
self.output = the_selfish().make_decision() #the_selfish is independent on former_round so no updating
return self.output
def end_of_turns(self):
super().end_of_turns()
self.count_turns = 0
self.is_betrayed = 0
class remote_controller(Gamer):
def __init__(self):
super().__init__()
def make_decision(self):
print('former output:', self.output)
print('former return:', self.former_round)
self.output = int(input('Enter your decision: '))
self.output = 0 if self.output == 0 else 1
return self.output
def end_of_turns(self):
super().end_of_turns()
"""# The following five columns are the old game_type_list currently abandoned"""
class type_list:
def __init__(self, type):
self.type = type
self.list = []
def get_pairs(listx):
return [(i, j) for i in range(len(listx)) for j in range(i+1, len(listx))]
print(get_pairs([1, 2, 3, 4, 5]))
class game_type_list():
def __init__(self):
attributes_game = {'gamers': [], 'num_of_gamers': 0, 'num_of_turns': 10,
'TT': [2,2], 'TB': [-1, 3], 'BB': [0, 0]}
for name, value in attributes_game.items():
setattr(self, name, value)
# use list of lists to store gamers instead of a plain list
def one_round(self, input1, input2):
if input1 == input2 == 1: #(1, 1)
return self.TT
elif input1 == 1: #(1, 0)
return self.TB
elif input2 == 1: #(0, 1)
return [self.TB[1], self.TB[0]]
else: #(0, 0)
return self.BB
def add_gamer(self, gamer_type, n):
for type_listx in self.gamers:
if type(gamer_type()) == type_listx.type:
for i in range(n):
type_listx.list.append(gamer_type())
self.num_of_gamers += n
return
self.gamers.append(type_list(type(gamer_type())))
for i in range(n):
self.gamers[-1].list.append(gamer_type())
self.num_of_gamers += n
def remove_gamer_a(self, gamer_type, n):
for type_listx in self.gamers:
if type_listx.type == type(gamer_type()):
if n > len(type_listx.list):
print('removals out of range')
return
else:
del type_listx.list[-n:]
self.num_of_gamers -= n
return
print('No such gamer')
def run_matches(self):
for type_listx in self.gamers:
self.game_iteration(type_listx)
pairs_x = get_pairs(self.gamers)
for l in pairs_x:
for gamer1 in self.gamers[l[0]].list:
for gamer2 in self.gamers[l[1]].list:
self.play_match(gamer1, gamer2)
def play_match(self, gamer1, gamer2):
for i in range(self.num_of_turns):
outcome = self.one_round(gamer1.make_decision(), gamer2.make_decision())
gamer1.points += outcome[0]
gamer2.points += outcome[1]
gamer1.former_round = gamer2.output
gamer2.former_round = gamer1.output
gamer1.end_of_turns()
gamer2.end_of_turns()
def game_iteration(self, type_listx):
pairs = get_pairs(type_listx.list)
for l in pairs:
self.play_match(type_listx.list[l[0]], type_listx.list[l[1]])
def old_test_case():
game2 = game_type_list()
game2.num_of_turns = 10
game2.add_gamer(copycat, 100)
game2.add_gamer(the_believer, 100)
game2.add_gamer(the_selfish, 100)
game2.add_gamer(pavlov, 100)
game2.add_gamer(the_stubborn, 100)
game2.add_gamer(the_generous_copycat, 100)
game2.add_gamer(majority_follower, 100)
game2.add_gamer(the_tricker, 100)
game2.add_gamer(the_vicious_copycat, 0)
print(game2.num_of_gamers)
game2.run_matches()
for i in game2.gamers:
if len(i.list) > 0:
print(i.type, ': ', i.list[0].points, end='\n')
print('\n')
game2.remove_gamer_a(the_selfish, 10)
print(game2.num_of_gamers, len(game2.gamers[4].list))
print(len(game2.gamers))
for i in game2.gamers:
print(i.type, ':', len(i.list), end='\n')
print('\n')
print(game2.gamers[0].type)
old_test_case()
"""# **The following are the new game() definition with a dctionary to store types and gamers**"""
class IncoherenceError(Exception):
def __init__(self, message):
super().__init__(message)
from collections import Counter
from collections import defaultdict
def round_half_up(n):
return math.floor(n + 0.5)
#for those to be replaced, collect their gamer_type and list_index
#for those to be duplicated. collect their gamer_type and nums
def get_replacement(tuples, t):
sorted_tuples = sorted(tuples, key=lambda x: x[2])
top_border_value = sorted_tuples[-t][2]
bottom_border_value = sorted_tuples[t-1][2]
top_tied_tuples = [i for i in sorted_tuples if i[2] == top_border_value]
bottom_tied_tuples = [j for j in sorted_tuples if j[2] == bottom_border_value]
temp_a = len(bottom_tied_tuples)
temp_b = len(top_tied_tuples)
to_be_replaced = [i for i in sorted_tuples if i[2] < bottom_border_value]
to_be_duplicated = [j for j in sorted_tuples if j[2] > top_border_value]
# count to_be_duplicated but not to_be_replaced
to_be_duplicated_count = Counter(i[0] for i in to_be_duplicated)
bottom_tied_counts = list(Counter(i[0] for i in bottom_tied_tuples).items())
top_tied_counts = list(Counter(i[0] for i in top_tied_tuples).items())
bottom_true_counts = []
for i in top_tied_counts:
to_be_duplicated_count[i[0]] += round_half_up((t-len(to_be_duplicated))*(i[1]/temp_b))
for j in bottom_tied_counts:
bottom_true_counts.append((j[0], round_half_up((t-len(to_be_replaced))*(j[1]/temp_a))))
grouped_bottom_tuples = defaultdict(list)
for l in bottom_tied_tuples:
grouped_bottom_tuples[l[0]].append(l)
for n in bottom_true_counts:
if n[0] in grouped_bottom_tuples:
if len(grouped_bottom_tuples[n[0]]) > n[1]:
for j in range(n[1]):
to_be_replaced.append(grouped_bottom_tuples[n[0]][j])
else:
to_be_replaced.extend(grouped_bottom_tuples[n[0]])
to_be_replaced = sorted(to_be_replaced, key=lambda x: x[1], reverse=True)
#reverse the order so the obj of list_index can be deleted from the rear
return to_be_replaced, to_be_duplicated_count
class game():
__slots__ = ['num_of_gamers', 'num_of_turns', 'TT', 'TB', 'BB', 'gamers_dict', 'dict_keys', 'clear_points', 'replacement_n', 'mistake_rate']
def __init__(self):
attributes_game = {'num_of_gamers': 0, 'num_of_turns': 10,
'TT': [2,2], 'TB': [-1, 3], 'BB': [0, 0],
'gamers_dict': {}, 'dict_keys': [], 'clear_points': 1,
'replacement_n': 30, 'mistake_rate': 0}
for name, value in attributes_game.items():
setattr(self, name, value)
def one_round(self, input1, input2):
if input1 == input2 == 1: #(1, 1)
return self.TT
elif input1 == 1: #(1, 0)
return self.TB
elif input2 == 1: #(0, 1)
return [self.TB[1], self.TB[0]]
else: #(0, 0)
return self.BB
def add_gamer(self, gamer_type, n):
if n <= 0:
return
if gamer_type not in self.dict_keys:
self.dict_keys.append(type(gamer_type()))
self.gamers_dict[type(gamer_type())] = []
for _ in range(n):
self.gamers_dict[type(gamer_type())].append(gamer_type())
self.num_of_gamers += n
return
def remove_gamer_back(self, gamer_type, n):
if n <= 0:
return
if type(gamer_type()) not in self.dict_keys:
print('No such gamer')
return
if n > len(self.gamers_dict[type(gamer_type())]):
print('Removal out of range')
return
del self.gamers_dict[type(gamer_type())][-n:]
self.num_of_gamers -= n
return
def remove_gamer_index(self, gamer_type, n):
if gamer_type not in self.dict_keys:
print('No such gamer')
return
if n >= len(self.gamers_dict[gamer_type]) or n < -(len(self.gamers_dict[gamer_type])):
print('Removal out of range')
return
del self.gamers_dict[gamer_type][n]
self.num_of_gamers -= 1
return
def perturb(self, value): #mistake_rate_function
if random.random() < self.mistake_rate:
return 1 if value ==0 else 0
return value
def run_matches(self):
#check if self.dict_keys is correct
if self.dict_keys != list(self.gamers_dict.keys()):
raise IncoherenceError('dict_keys isn\'t coherent with real keys')
for list_x in self.gamers_dict.values():
pairs = list(combinations(range(len(list_x)), 2))
for pair in pairs:
self.play_match(list_x[pair[0]], list_x[pair[1]])
pairs = list(combinations(range(len(self.dict_keys)), 2))
for pair in pairs:
for gamer1 in self.gamers_dict[self.dict_keys[pair[0]]]:
for gamer2 in self.gamers_dict[self.dict_keys[pair[1]]]:
self.play_match(gamer1, gamer2)
return
def play_match(self, gamer1, gamer2):
for i in range(self.num_of_turns):
if self.mistake_rate == 0:
outcome = self.one_round(gamer1.make_decision(), gamer2.make_decision())
else:
gamer1.output = self.perturb(gamer1.make_decision())
gamer2.output = self.perturb(gamer2.make_decision())
outcome = self.one_round(gamer1.output, gamer2.output)
gamer1.points += outcome[0]
gamer2.points += outcome[1]
gamer1.former_round = gamer2.output
gamer2.former_round = gamer1.output
gamer1.end_of_turns()
gamer2.end_of_turns()
def print_points(self, n):
for key in self.gamers_dict:
print(f"{key}[{n}] value: {self.gamers_dict[key][n].points}")
def print_points_extreme(self, max_or_min):
if max_or_min:
for key in self.gamers_dict:
print(key, 'max_value:', max([i.points for i in self.gamers_dict[key]]))
else:
for key in self.gamers_dict:
print(key, 'max_value:', min([i.points for i in self.gamers_dict[key]]))
return
def print_points_avg(self):
for key in self.gamers_dict:
print(key, 'avg: ', round(sum([i.points for i in self.gamers_dict[key]])/len(self.gamers_dict[key])))
def print_points_stdev(self):
for key in self.gamers_dict:
print(key, ' stdev: ', np.std([i.points for i in self.gamers_dict[key]]))
def print_gamer_nums(self):
for key in self.gamers_dict:
print(key, ':', len(self.gamers_dict[key]))
def replacement_process(self):
gamer_tuples = []
for listx in self.gamers_dict.values():
for i in range(len(listx)):
gamer_tuples.append((type(listx[i]), i, listx[i].points))
if self.clear_points:
listx[i].points = 0
to_be_replaced, to_be_duplicated = get_replacement(gamer_tuples, self.replacement_n)
for i in to_be_replaced:
self.remove_gamer_index(i[0], i[1])
for key, value in to_be_duplicated.items():
self.add_gamer(key, value)
for key in list(self.gamers_dict.keys()):
if self.gamers_dict[key] == []:
del self.gamers_dict[key]
self.dict_keys = list(self.gamers_dict.keys())
return
def complete_round(self):
self.run_matches()
self.replacement_process()
return
def new_test_case():
game1 = game()
game1.num_of_turns = 10
game1.mistake_rate = 0.05
game1.add_gamer(copycat, 100)
game1.add_gamer(the_believer, 100)
game1.add_gamer(the_selfish, 100)
game1.add_gamer(pavlov, 100)
game1.add_gamer(the_stubborn, 100)
game1.add_gamer(the_generous_copycat, 100)
game1.add_gamer(majority_follower, 100)
game1.add_gamer(the_tricker, 100)
game1.add_gamer(the_mean_copycat, 100)
game1.add_gamer(detective, 100)
tmp_round = 10
for i in range(tmp_round):
if i == tmp_round-1:
game1.clear_points = 0
game1.complete_round()
print(game1.num_of_gamers)
game1.print_gamer_nums()
print('\n')
game1.print_points(0)
print('\n')
game1.print_points_stdev()
print('\n')
game1.print_points_avg()
import time
start_time = time.time()
new_test_case()
end_time = time.time()
print(f"Time taken: {end_time - start_time} seconds")
k = game()
k.add_gamer(the_mean_copycat, 1)
k.add_gamer(copycat, 1)
k.run_matches()
k.print_points(0)
cProfile.run('new_test_case()')