-
Notifications
You must be signed in to change notification settings - Fork 1
/
generator.py
751 lines (594 loc) · 27 KB
/
generator.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
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
import numpy as np
class Generator:
def __init__(
self
) -> None:
pass
def generate_scenario(
self,
config,
):
"""
Generates an graph meeting the scenario requirements
:arg scenario game theoretical setting desired
:arg config environment configuration contains haircut multiplier, etc
"""
scenario = config.get('scenario')
valid_scenarios = [
'debug',
'not enough money together',
'not in default',
'only agent 0 can rescue',
'only agent 1 can rescue',
'both agents can rescue',
'coordination game',
'volunteers dilemma',
'debug fixed coordination game',
'merged only agent 0 can rescue and only agent 1 can rescue',
'uniformly mixed',
]
if scenario not in valid_scenarios:
assert False, f"Scenario must be in {valid_scenarios}"
if scenario == 'debug':
return self.debug(config)
elif scenario == 'debug fixed coordination game':
return self.debug_fixed_coordination_game(config)
elif scenario == 'not enough money together':
return self.not_enough_money_together(config)
elif scenario == 'not in default':
return self.not_in_default(config)
elif scenario == 'only agent 0 can rescue':
return self.only_agent_0_can_rescue(config)
elif scenario == 'only agent 1 can rescue':
return self.only_agent_1_can_rescue(config)
elif scenario == 'both agents can rescue' or\
scenario == 'volunteers dilemma':
return self.both_agents_can_rescue(config)
elif scenario == 'coordination game':
return self.coordination_game(config)
elif scenario == 'merged only agent 0 can rescue and only agent 1 can rescue':
return self.merged_only_agent_0_can_rescue_and_only_agent_1_can_rescue(config)
elif scenario == 'uniformly mixed':
return self.uniformly_mixed(config)
def debug(
self,
config
):
"""
Debugging graph
In this case, the graphs contains the following situation
1. the defaulted bank can be rescued with an collective allocation of 2
:args config config containing common settings for the environment (i.e. haircut)
:output positions capital allocation to each entity
:output adjacency_matrix debt owed by each entity
"""
adjacency_matrix = [
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[16.0, 16.0, 0.0]
]
position = [35.0, 35.0, 30.0]
adjacency_matrix = np.asarray(adjacency_matrix)
position = np.asarray(position)
return position, adjacency_matrix
def debug_fixed_coordination_game(
self,
config
):
"""
Debugging graph for the fixed coordination case
In this case, the graphs contains the following situation
1. a fixed coordination situation is presented each turn
:args config config containing common settings for the environment (i.e. haircut)
:output positions capital allocation to each entity
:output adjacency_matrix debt owed by each entity
"""
adjacency_matrix = [
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[3.0, 3.0, 0.0]
]
position = [2.0, 2.0, 3.0]
adjacency_matrix = np.asarray(adjacency_matrix)
position = np.asarray(position)
return position, adjacency_matrix
def not_enough_money_together(
self,
config
):
"""
Generator for the case: 'not enough money together'
In this case, the graphs must satify the following conditions:
1. both agent has nonzero capital
2. the sum of both agent's capital is less than the amount for
a successful rescue
3. the debtor can be rescued with a transfer geq the 'rescue amount'
:args config config containing common settings for the environment (i.e. haircut)
:output positions capital allocation to each entity
:output adjacency_matrix debt owed by each entity
"""
# retrieve commonly used variables for readability
rescue_amount = config.get('rescue_amount')
n_agents = config.get('n_agents')
n_entities = config.get('n_entities')
max_system_value = config.get('max_system_value')
# If rescue amount is less than 2, than either agent can have 0
# Which descends to the case of only one can rescue, or neither can rescue.
assert rescue_amount > 2
generated = False
while not generated:
""" Generate positions """
# Allocate memory
position = np.zeros(n_entities)
# Sample an amount less than the rescue amount, but greater than 2
collective_capital = np.random.randint(2, rescue_amount)
# Allocate the sampled amount across the agents
position[:n_agents] = np.random.multinomial(
collective_capital,
np.ones(n_agents)/(n_agents),
size=1
)[0]
# Determine the remaining capital in the system
remaining_capital = max_system_value - position[:n_agents].sum()
# Sample an amount such that the sum capital across all agents
# is less than the total system value
position[2] = np.random.randint(remaining_capital)
""" Generate adjacency matrix """
# Allocate memory
adjacency_matrix = np.zeros(shape=(n_entities, n_entities))
# Compute the amount of debt owed
debt = position[2] + rescue_amount
# Allocate the debt across solvent banks
adjacency_matrix[-1,:n_agents] = np.random.multinomial(
debt,
np.ones(n_agents)/(n_agents),
size=1
)[0]
""" Graph Verification """
verifications = [
'all entries in adjacency matrix less than system max',
'check all positions greater than or equal to zero',
'not enough money together',
'both agents have positive incentives',
]
if self.verify(
config,
position,
adjacency_matrix,
verifications
):
generated = True
return position, adjacency_matrix
def not_in_default(
self,
config
):
"""
Generator for the case: 'not in default'
In this case, the graphs must satify the following conditions:
1. the rescue amount must equal 0
2. the sum of all agent's capital has to be less than the maximum system value
3. the agent which is normally the debtor, is not in default
:args config config containing common settings for the environment (i.e. haircut)
:output positions capital allocation to each entity
:output adjacency_matrix debt owed by each entity
"""
# retrieve commonly used variables for readability
rescue_amount = config.get('rescue_amount')
n_agents = config.get('n_agents')
n_entities = config.get('n_entities')
max_system_value = config.get('max_system_value')
# In order to not require a rescue, the rescue amount must equal 0
assert rescue_amount == 0
generated = False
while not generated:
""" Generate positions """
# Sample a capitalization for each agent
position = np.random.multinomial(
max_system_value,
np.ones(n_entities)/(n_entities),
size=1
)[0].astype(float)
""" Generate adjacency matrix """
# Allocate memory
adjacency_matrix = np.zeros(shape=(n_entities, n_entities))
# Compute the amount of debt owed (less than current capitalization)
debt = np.random.randint(position[2])
# Allocate the debt across solvent banks
adjacency_matrix[-1,:n_agents] = np.random.multinomial(
debt,
np.ones(n_agents)/(n_agents),
size=1
)[0].astype(float)
""" Graph Verification """
verifications = [
'all entries in adjacency matrix less than system max',
'check all positions greater than zero',
'no default occurred'
]
if self.verify(
config,
position,
adjacency_matrix,
verifications
):
generated = True
return position, adjacency_matrix
def only_agent_0_can_rescue(
self,
config
):
"""
Generator for the case: 'only agent 0 can rescue'
In this case, the graphs must satify the following conditions:
1. the rescue amount must be geq 1
2. agent 0's capitalization must be geq the rescue amount
3. agent 1's capitalization must be less than the rescue amount
:args config config containing common settings for the environment (i.e. haircut)
:output positions capital allocation to each entity
:output adjacency_matrix debt owed by each entity
"""
# retrieve commonly used variables for readability
rescue_amount = config.get('rescue_amount')
n_agents = config.get('n_agents')
n_entities = config.get('n_entities')
max_system_value = config.get('max_system_value')
# If rescue amount is less than 1, then it transformers into the 'not in default' case
assert rescue_amount >= 1
generated = False
while not generated:
""" Generate positions """
position = np.zeros(n_entities)
# Sample agent 1's capitalization which has to be less than the rescue amount
agent_1_capitalization = np.random.randint(rescue_amount)
position[1] = agent_1_capitalization
# Distribute the remaining system value to agent 0 and the distressed bank
remaining_capitalization = max_system_value - agent_1_capitalization
capitalization = np.random.multinomial(
remaining_capitalization,
np.ones(n_entities)/(n_entities),
size=1
)[0]
position[0] = capitalization[0]
position[2] = capitalization[1]
""" Generate adjacency matrix """
# Allocate memory
adjacency_matrix = np.zeros(shape=(n_entities, n_entities))
# Compute the amount of debt owed
debt = position[2] + rescue_amount
# Allocate the debt across solvent banks
adjacency_matrix[2,:n_agents] = np.random.multinomial(
debt,
np.ones(n_agents)/(n_agents),
size=1
)[0]
""" Graph Verification """
# NOTE: Assumption
# Assumes that agent 1 also has an incentive to rescue
# but is unable to complete a rescue alone
verifications = [
'all entries in adjacency matrix less than system max',
'check all positions greater than or equal to zero',
'both agents have positive incentives',
'only agent 0 can rescue'
]
if self.verify(
config,
position,
adjacency_matrix,
verifications
):
generated = True
return position, adjacency_matrix
def only_agent_1_can_rescue(
self,
config
):
"""
Generator for the case: 'only agent 1 can rescue'
In this case, the graphs must satify the following conditions:
1. the rescue amount must be geq 1
2. agent 1's capitalization must be geq the rescue amount
3. agent 0's capitalization must be less than the rescue amount
:args config config containing common settings for the environment (i.e. haircut)
:output positions capital allocation to each entity
:output adjacency_matrix debt owed by each entity
"""
# Generate the case of ' only agent 0 can rescue'
position, adjacency_matrix = self.only_agent_0_can_rescue(config)
# Swap the positions of agent 0 and agent 1
position[0], position[1] = position[1], position[0]
adjacency_matrix[2,0], adjacency_matrix[2,1] = adjacency_matrix[2,1], adjacency_matrix[2,0]
# NOTE: Verifications are conducted in self.only_agent_0_can_rescue.
# Successful validation there implies successful validation in this scenario due to symmetry
return position, adjacency_matrix
def both_agents_can_rescue(
self,
config
):
"""
Generator for the case: 'both agents can rescue'
In this case, the graphs must satify the following conditions:
1. both agent has nonzero capital
2. each agent's capitalization is greater than the rescue amount
3. the rescue amount must be geq 1
:args config config containing common settings for the environment (i.e. haircut)
:output positions capital allocation to each entity
:output adjacency_matrix debt owed by each entity
"""
# retrieve commonly used variables for readability
rescue_amount = config.get('rescue_amount')
n_agents = config.get('n_agents')
n_entities = config.get('n_entities')
max_system_value = config.get('max_system_value')
# The rescue amount must be geq to 1 to make sure it does not
# deteriorate into the case of 'no point in rescuing'
assert rescue_amount >= 1
generated = False
while not generated:
""" Generate positions """
position_generated = False
while not position_generated:
# Same a system amount
total_capital = np.random.randint(max_system_value)
# Allocate the sampled amount across the agents
position = np.random.multinomial(
total_capital,
np.ones(n_entities)/(n_entities),
size=1
)[0].astype(float)
if position[0] >= rescue_amount and\
position[1] >= rescue_amount:
position_generated = True
""" Generate adjacency matrix """
# Allocate memory
adjacency_matrix = np.zeros(shape=(n_entities, n_entities))
# Compute the amount of debt owed
debt = position[2] + rescue_amount
# Allocate the debt across solvent banks
adjacency_matrix[-1,:n_agents] = np.random.multinomial(
debt,
np.ones(n_agents)/(n_agents),
size=1
)[0]
""" Graph Verification """
verifications = [
'all entries in adjacency matrix less than system max',
'check all positions greater than or equal to zero',
'both agents have positive incentives',
'both agents can rescue'
]
if self.verify(
config,
position,
adjacency_matrix,
verifications
):
generated = True
return position, adjacency_matrix
def coordination_game(
self,
config,
):
"""
Generator for the case: 'coordination game'
In this case, the graphs must satify the following conditions:
1. both agent has nonzero capital
2. the sum of both agent's capitalization equals the rescue amount
3. the rescue amount must be geq 2
4. every agent is able to contribute, but does not have to contribute all their capital
:args config config containing common settings for the environment (i.e. haircut)
:output positions capital allocation to each entity
:output adjacency_matrix debt owed by each entity
"""
# retrieve commonly used variables for readability
rescue_amount = config.get('rescue_amount')
n_agents = config.get('n_agents')
n_entities = config.get('n_entities')
max_system_value = config.get('max_system_value')
commit_everything = config.get('commit_everything')
# The rescue amount must be geq to 2 such that each agent contributes at least 1
assert rescue_amount >= 2
generated = False
while not generated:
""" Generate positions """
position = np.zeros(n_entities)
if commit_everything:
# Allocate the sampled amount across the agents
position[:n_agents] = np.random.multinomial(
rescue_amount,
np.ones(n_agents)/(n_agents),
size=1
)[0]
else:
position[0] = np.random.randint(rescue_amount)
position[1] = np.random.randint(rescue_amount)
# Set the system amount
total_capital = np.random.randint(
position[:2].sum(),
max_system_value
)
# Allocate the remaining capitalization to the distressed bank
position[2] = total_capital - position[:n_agents].sum()
""" Generate adjacency matrix """
# Allocate memory
adjacency_matrix = np.zeros(shape=(n_entities, n_entities))
# Compute the amount of debt owed
debt = position[2] + rescue_amount
if debt == 0 :
print("Debt == 0 !")
# Allocate the debt across solvent banks
adjacency_matrix[-1,:n_agents] = np.random.multinomial(
debt,
np.ones(n_agents)/(n_agents),
size=1
)[0]
""" Graph Verification """
verifications = [
'all entries in adjacency matrix less than system max',
'check all positions greater than or equal to zero',
'both agents have positive incentives',
'the sum of both agents is geq than the rescue amount',
'both agents cannot rescue by themself'
]
if self.verify(
config,
position,
adjacency_matrix,
verifications
):
generated = True
return position, adjacency_matrix
def merged_only_agent_0_can_rescue_and_only_agent_1_can_rescue(
self,
config,
):
"""
Generator for the case: 'merged only agent 0 can rescue and only agent 1 can rescue'
In this case, the graphs must satify the following conditions:
1. The generator switches between uniformly
A. only agent 0 can rescue
B. only agent 1 can rescue
:args config config containing common settings for the environment (i.e. haircut)
:output positions capital allocation to each entity
:output adjacency_matrix debt owed by each entity
"""
# Randomly select which agent
scenario = np.random.randint(0,2)
# Return the appropriate scenario
if scenario == 0:
return self.only_agent_0_can_rescue(config)
else:
return self.only_agent_1_can_rescue(config)
def uniformly_mixed(
self,
config,
):
"""
Generator for the case: 'uniformly mixed'
In this case, the graphs must satify the following conditions:
1. The generator switches uniformly between all the scenarios
a. 'not enough money together',
b. 'not in default',
c. 'only agent 0 can rescue',
d. 'only agent 1 can rescue',
e. 'both agents can rescue',
f. 'coordination game',
g. 'volunteers dilemma',
If the rescue amount is 0, there is a 50% chance the agents will get
:args config config containing common settings for the environment (i.e. haircut)
:output positions capital allocation to each entity
:output adjacency_matrix debt owed by each entity
"""
# Select uniformly at random a scenario
scenario = np.random.randint(0,6)
#TODO: Save the sub scenario into the system and retrieve it in the environment
# Select uniformly at random a rescue amount from 3-6
config['rescue_amount'] = np.random.randint(
config['minimum_rescue_amount'],
config['maximum_rescue_amount']
)
# Return the appropriate scenario
if scenario == 0:
self.sub_scenario = 'not enough money together'
return self.not_enough_money_together(config)
elif scenario == 1:
config['rescue_amount'] = 0
self.sub_scenario = 'not in default'
return self.not_in_default(config)
elif scenario == 2:
self.sub_scenario = 'only agent 0 can rescue'
return self.only_agent_0_can_rescue(config)
elif scenario == 3:
self.sub_scenario = 'only agent 1 can rescue'
return self.only_agent_1_can_rescue(config)
elif scenario == 4:
self.sub_scenario = 'both agents can rescue'
return self.both_agents_can_rescue(config)
elif scenario == 5:
self.sub_scenario = 'coordination game'
return self.coordination_game(config)
def verify(
self,
config,
positions,
adjacency_matrix,
tests = None
):
"""
Conducts verificiation of the position and adjacency matrices
"""
def check_all_positions_greater_than_zero():
return ( positions > 0 ).all()
def check_all_positions_greater_than_or_equal_to_zero():
return ( positions >= 0 ).all()
def none():
pass
def all_entries_in_adjacency_matrix_greater_than_zero():
return ( adjacency_matrix > 0 ).all()
def all_entries_in_adjacency_matrix_less_than_system_max():
max_system_value = config.get('max_system_value')
return ( adjacency_matrix < max_system_value ).all()
def both_agents_have_positive_incentives():
"""Compute rewards if system is not saved"""
proportion_of_allocation = adjacency_matrix[2,:2]/ adjacency_matrix[2,:2].sum()
not_saved_rewards = positions[2] * config.get('haircut_multiplier') * proportion_of_allocation
"""Compute rewards if system is saved"""
# NOTE: Assumption
# Assumes the agent saves the distressed bank alone, they have to incur the full rescue amount alone
saved_rewards = adjacency_matrix[2,:2] - config.get('rescue_amount')
# Compute the incentives being the change in rewards
incentives = saved_rewards - not_saved_rewards
return ( incentives > 0 ).all()
def both_agents_can_rescue():
return ( positions[:2] > config.get('rescue_amount') ).all()
def no_default_occurred():
return positions[2] >= 0
def not_enough_money_together():
return positions[:2].sum() < config.get('rescue_amount')
def only_agent_0_can_rescue():
return positions[0] >= config.get('rescue_amount') and positions[1] < config.get('rescue_amount')
def only_agent_1_can_rescue():
return positions[1] >= config.get('rescue_amount') and positions[0] < config.get('rescue_amount')
def the_sum_of_both_agents_is_geq_than_the_rescue_amount():
return positions[:2].sum() >= config.get('rescue_amount')
def both_agents_cannot_rescue_by_themself():
return positions[0] < config.get('rescue_amount') and positions[1] < config.get('rescue_amount')
lookup = {
None: none,
'check all positions greater than zero' : check_all_positions_greater_than_zero,
'check all positions greater than or equal to zero': check_all_positions_greater_than_or_equal_to_zero,
'all entries in adjacency matrix greater than zero' : all_entries_in_adjacency_matrix_greater_than_zero,
'all entries in adjacency matrix less than system max': all_entries_in_adjacency_matrix_less_than_system_max,
'both agents have positive incentives': both_agents_have_positive_incentives,
'both agents can rescue': both_agents_can_rescue,
'no default occurred': no_default_occurred,
'not enough money together': not_enough_money_together,
'only agent 0 can rescue': only_agent_0_can_rescue,
'only agent 1 can rescue': only_agent_1_can_rescue,
'the sum of both agents is geq than the rescue amount':the_sum_of_both_agents_is_geq_than_the_rescue_amount,
'both agents cannot rescue by themself': both_agents_cannot_rescue_by_themself,
}
# Run the validation checks
for test in tests:
# Check that a valid test is requested
assert test in lookup.keys(), f'"{test}" is not a valid test'
# Return the output of the test
test_results = lookup.get(test)()
# Return false if any validation fails
if test_results == False:
return False
return True
if __name__ == "__main__":
from utils import get_args
args = get_args()
config = vars(args)
g = Generator()
for i in range(config['minimum_rescue_amount'], config['maximum_rescue_amount']):
config['rescue_amount'] = i
adjacency_matrix, position = g.generate_scenario(
config,
)
print(f'rescue amount: {i}')
print(adjacency_matrix)
print(position)