-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizer.html
More file actions
1463 lines (1280 loc) · 53 KB
/
Copy pathvisualizer.html
File metadata and controls
1463 lines (1280 loc) · 53 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prisoner's Dilemma Strategy Visualizer</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.5/babel.min.js"></script>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'JetBrains Mono', 'Fira Code', 'SF Mono', 'Consolas', monospace;
background: linear-gradient(145deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
min-height: 100vh;
color: #e2e8f0;
}
.container {
padding: 24px;
}
header {
text-align: center;
margin-bottom: 32px;
padding-bottom: 24px;
border-bottom: 1px solid #334155;
}
h1 {
font-size: 1.75rem;
font-weight: 600;
letter-spacing: -0.02em;
background: linear-gradient(135deg, #60a5fa, #4ade80);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin-bottom: 8px;
}
.subtitle {
color: #94a3b8;
font-size: 0.875rem;
}
.main-grid {
display: grid;
grid-template-columns: minmax(500px, 700px) 1fr;
gap: 32px;
max-width: 1500px;
margin: 0 auto;
}
@media (max-width: 1100px) {
.main-grid {
grid-template-columns: 1fr;
}
}
.matrix-section {
background: rgba(30, 41, 59, 0.6);
border: 1px solid #334155;
border-radius: 12px;
padding: 24px;
}
.matrix-section h2 {
font-size: 1rem;
font-weight: 500;
margin-bottom: 16px;
color: #f1f5f9;
}
.matrices-grid {
display: grid;
grid-template-columns: auto auto auto auto;
gap: 12px;
margin-bottom: 20px;
justify-content: start;
}
@media (max-width: 700px) {
.matrices-grid {
grid-template-columns: auto auto;
}
}
@media (max-width: 450px) {
.matrices-grid {
grid-template-columns: 1fr;
}
}
.matrix-panel {
background: rgba(15, 23, 42, 0.5);
border: 1px solid #334155;
border-radius: 8px;
padding: 12px;
}
.matrix-panel h3 {
font-size: 0.8rem;
font-weight: 500;
margin-bottom: 6px;
color: #cbd5e1;
}
.matrix-panel .matrix-hint {
font-size: 0.65rem;
margin-bottom: 8px;
}
.matrix-full {
margin-top: 4px;
}
.matrix-small {
font-size: 0.8rem;
}
.matrix-small th, .matrix-small td {
padding: 8px 12px;
min-width: 40px;
}
.first-move-panel {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-width: 120px;
}
.first-move-display {
display: flex;
align-items: center;
justify-content: center;
margin-top: 8px;
}
.first-move-value {
font-size: 1.5rem;
font-weight: 700;
padding: 16px 24px;
border-radius: 8px;
border: 1px solid #475569;
}
.decay-panel {
min-width: 160px;
}
.decay-info {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 8px;
}
.decay-rate {
display: flex;
justify-content: space-between;
align-items: center;
}
.decay-rate .label {
font-size: 0.7rem;
color: #94a3b8;
}
.decay-rate .value {
font-size: 1rem;
font-weight: 600;
color: #60a5fa;
}
.weights-display .label {
font-size: 0.7rem;
color: #94a3b8;
display: block;
margin-bottom: 6px;
}
.weight-bars {
display: flex;
justify-content: space-around;
align-items: flex-end;
height: 60px;
padding-top: 10px;
}
.weight-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
}
.weight-bar {
width: 16px;
border-radius: 2px 2px 0 0;
min-height: 2px;
}
.weight-label {
font-size: 0.6rem;
color: #64748b;
}
.weight-value {
font-size: 0.6rem;
color: #94a3b8;
}
.matrix-hint {
font-size: 0.75rem;
color: #64748b;
margin-bottom: 16px;
}
.table-wrapper {
overflow-x: auto;
}
table {
border-collapse: collapse;
width: 100%;
font-size: 0.8rem;
}
th, td {
padding: 10px 8px;
text-align: center;
border: 1px solid #334155;
min-width: 48px;
}
thead th {
background: #1e293b;
color: #94a3b8;
font-weight: 500;
position: sticky;
top: 0;
}
tbody th {
background: #1e293b;
color: #94a3b8;
font-weight: 500;
}
td {
font-weight: 600;
transition: all 0.15s ease;
}
.legend {
display: flex;
gap: 20px;
margin-top: 16px;
font-size: 0.75rem;
color: #94a3b8;
justify-content: center;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 16px;
height: 16px;
border-radius: 3px;
border: 1px solid #475569;
display: inline-block;
}
.controls-section {
display: flex;
flex-direction: column;
gap: 20px;
}
.presets {
background: rgba(30, 41, 59, 0.6);
border: 1px solid #334155;
border-radius: 12px;
padding: 16px;
}
.presets h3 {
font-size: 0.85rem;
font-weight: 500;
margin-bottom: 12px;
color: #f1f5f9;
}
.preset-buttons {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.preset-buttons button {
font-family: inherit;
font-size: 0.75rem;
padding: 8px 14px;
border: 1px solid #475569;
border-radius: 6px;
background: #1e293b;
color: #e2e8f0;
cursor: pointer;
transition: all 0.15s ease;
}
.preset-buttons button:hover {
background: #334155;
border-color: #60a5fa;
color: #fff;
}
.control-group {
background: rgba(30, 41, 59, 0.6);
border: 1px solid #334155;
border-radius: 12px;
padding: 16px;
}
.control-group h3 {
font-size: 0.85rem;
font-weight: 500;
margin-bottom: 14px;
color: #f1f5f9;
}
.slider-row {
display: grid;
grid-template-columns: 140px 1fr 50px;
align-items: center;
gap: 12px;
margin-bottom: 10px;
}
.slider-row:last-child {
margin-bottom: 0;
}
.slider-row label {
font-size: 0.75rem;
color: #94a3b8;
}
.slider-row .value {
font-size: 0.75rem;
color: #60a5fa;
text-align: right;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 6px;
background: #334155;
border-radius: 3px;
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 16px;
height: 16px;
border-radius: 50%;
background: var(--slider-color, #4ade80);
cursor: pointer;
box-shadow: 0 2px 6px rgba(0,0,0,0.3);
transition: transform 0.1s ease;
}
input[type="range"]::-webkit-slider-thumb:hover {
transform: scale(1.15);
}
input[type="range"]::-moz-range-thumb {
width: 16px;
height: 16px;
border-radius: 50%;
background: var(--slider-color, #4ade80);
cursor: pointer;
border: none;
box-shadow: 0 2px 6px rgba(0,0,0,0.3);
}
footer {
max-width: 1500px;
margin: 32px auto 0;
padding-top: 24px;
border-top: 1px solid #334155;
}
footer p {
font-size: 0.75rem;
color: #64748b;
line-height: 1.6;
margin-bottom: 8px;
}
footer p:last-child {
margin-bottom: 0;
}
footer strong {
color: #94a3b8;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState, useMemo } = React;
// Sigmoid function: maps score to probability [0, 1]
function sigmoid(score) {
return 1 / (1 + Math.exp(-score));
}
// Clamp utility
function clamp(val, min, max) {
return Math.min(max, Math.max(min, val));
}
// Contextual valence: evaluate action given what preceded it
// priorContext can be discrete (-1, 0, +1) or continuous [-1, +1]
// Returns valence in roughly [-1.5, +1.5]
function contextualValence(action, priorContext) {
if (action === 0) return 0.0;
// No prior context: moderate valence
if (priorContext === 0) {
return action === 1 ? 0.5 : -0.8;
}
// For continuous priorContext, interpolate between extremes
// priorContext in [-1, 1]: -1 = defection, +1 = cooperation
// Map to interpolation factor t in [0, 1] where 0 = defection context, 1 = coop context
const t = (priorContext + 1) / 2;
if (action === 1) { // Cooperation
// Interpolate between forgiveness (1.5) and mutual coop (1.0)
return 1.5 * (1 - t) + 1.0 * t;
} else { // Defection (action === -1)
// Interpolate between retaliation (-0.3) and betrayal (-1.5)
return -0.3 * (1 - t) + -1.5 * t;
}
}
// Geometric series sum: decay^start + decay^(start+1) + ... + decay^(start+count-1)
function geometricSeriesSum(decay, start, count) {
if (count <= 0) return 0;
if (Math.abs(decay - 1) < 1e-9) return count;
return Math.pow(decay, start) * (1 - Math.pow(decay, count)) / (1 - decay);
}
// Compute weights with proper geometric series for pre-history
function computeWeights(decayRate, recentDepth, nPre) {
// Recent weights
const recentRaw = [];
for (let i = 0; i < recentDepth; i++) {
recentRaw.push(Math.pow(decayRate, i));
}
// Pre-history weight: sum from decay^recentDepth to decay^(recentDepth+nPre-1)
const preRaw = nPre > 0 ? geometricSeriesSum(decayRate, recentDepth, nPre) : 0;
// Normalize
const total = recentRaw.reduce((a, b) => a + b, 0) + preRaw;
if (total < 1e-9) {
return { recent: recentRaw.map(() => 1 / recentDepth), pre: 0 };
}
return {
recent: recentRaw.map(w => w / total),
pre: preRaw / total
};
}
// Evaluate opponent actions with N-based negativity bias
// N is centered at 0.5: N=0 dampens negative/amplifies positive, N=1 does opposite
function evaluateOpponentActions(opp, own, oppAvg, ownAvg, N, recentDepth, nPre) {
// Pre-history active when nPre > 0 (avgs are in [-1,1], not sentinels)
const hasPreHistory = nPre > 0;
const nEffect = N - 0.5; // range [-0.5, 0.5]
// Apply N-based asymmetry to valence
function applyNeuroticismBias(valence) {
if (valence < 0) {
return valence * (1 + 1.2 * nEffect);
} else {
return valence * (1 - 0.8 * nEffect);
}
}
const recentValences = [];
for (let i = 0; i < recentDepth; i++) {
const oppAction = opp[i];
if (oppAction === 0) {
recentValences.push(0);
continue;
}
// What did I do before this opponent action?
let priorContext = 0;
if (i + 1 < own.length && own[i + 1] !== 0) {
priorContext = own[i + 1];
} else if (hasPreHistory) {
// ownAvg is already in [-1, 1]
priorContext = ownAvg;
}
let valence = contextualValence(oppAction, priorContext);
valence = applyNeuroticismBias(valence);
recentValences.push(valence);
}
// Pre-history valence: continuous expected value based on averages
let preValence = null;
if (hasPreHistory) {
// Averages are in [-1, 1], map to probabilities for expected value calc
// avg = -1 → p=0 (always defect), avg = +1 → p=1 (always coop)
const pOppCoop = (oppAvg + 1) / 2;
const pOwnCoop = (ownAvg + 1) / 2;
const pCC = pOppCoop * pOwnCoop;
const pCD = pOppCoop * (1 - pOwnCoop);
const pDC = (1 - pOppCoop) * pOwnCoop;
const pDD = (1 - pOppCoop) * (1 - pOwnCoop);
const vCC = 1.0;
const vCD = 1.5;
const vDC = -1.5;
const vDD = -0.3;
let valence = pCC * vCC + pCD * vCD + pDC * vDC + pDD * vDD;
valence = applyNeuroticismBias(valence);
preValence = valence;
}
return { recent: recentValences, pre: preValence };
}
// Conscientiousness-based principled adjustment
// C = justice/fairness: high C reacts strongly to fairness violations
// Forgiveness = A * (1-C): agreeable + unprincipled = forgiving
function computePrincipledAdjustment(C, A, own, opp, ownAvg, oppAvg, weights, recentDepth, nPre) {
let adjustment = 0;
const hasPreHistory = nPre > 0;
const forgivenessTendency = A * (1 - C); // high A + low C = forgiving
// Evaluate own action given opponent's prior action
// priorOpp can be discrete (-1, +1) or continuous [-1, +1]
function evaluateOwnAction(ownAction, priorOpp) {
if (priorOpp === null) return 0;
// t = 0 means opponent defected, t = 1 means opponent cooperated
const t = (priorOpp + 1) / 2;
if (ownAction < 0) { // I defected
// Interpolate: justified retaliation (priorOpp=-1) vs unprovoked defection (priorOpp=+1)
const vRetaliation = 0.6 * C; // justified by justice
const vUnprovoked = -2.5 * C; // penalized by justice
return vRetaliation * (1 - t) + vUnprovoked * t;
} else { // I cooperated
// After opponent defected: forgiveness (driven by A*(1-C), not C)
// After opponent cooperated: neutral/positive
const vAfterDefect = forgivenessTendency * 1.2 - C * 0.3; // forgiveness vs weakness
const vAfterCoop = 0.1; // slight positive for mutual cooperation maintenance
return vAfterDefect * (1 - t) + vAfterCoop * t;
}
}
// Recent history
for (let i = 0; i < recentDepth; i++) {
const ownAction = own[i];
if (ownAction === 0) continue;
let priorOpp = null;
if (i + 1 < opp.length && opp[i + 1] !== 0) {
priorOpp = opp[i + 1];
} else if (hasPreHistory) {
// oppAvg is already in [-1, 1]
priorOpp = oppAvg;
}
adjustment += weights.recent[i] * evaluateOwnAction(ownAction, priorOpp);
}
// Pre-history: continuous expected value based on averages
if (hasPreHistory && weights.pre > 0) {
// Map avgs from [-1,1] to probabilities [0,1]
const pOwnCoop = (ownAvg + 1) / 2;
const pOppCoop = (oppAvg + 1) / 2;
const pCD = pOwnCoop * (1 - pOppCoop); // I coop after opp defect
const pDD = (1 - pOwnCoop) * (1 - pOppCoop); // I defect after opp defect
const pDC = (1 - pOwnCoop) * pOppCoop; // I defect after opp coop
const pCC = pOwnCoop * pOppCoop; // I coop after opp coop
const vCD = forgivenessTendency * 1.2 - C * 0.3; // forgiveness vs weakness
const vDD = 0.6 * C; // justified retaliation
const vDC = -2.5 * C; // unprovoked defection
const vCC = 0.1; // mutual cooperation maintenance
const expectedAdj = pCD * vCD + pDD * vDD + pDC * vDC + pCC * vCC;
adjustment += weights.pre * expectedAdj;
}
return adjustment;
}
// Apply extraversion as transparency multiplier (transparent behavior is amplified by E)
function applyTransparency(score, E) {
const multiplier = 0.5 + 0.8 * E; // range: [0.5, 1.3]
return score * multiplier;
}
// Deviousness term: low E × low C enables strategic exploitation of trust
// High deviousness:
// - Depress cooperation after mutual cooperation (exploit established trust)
// - Boost cooperation after mutual defection (reset for future exploitation)
// - Depress cooperation when successfully exploiting (own D, opp C) - "sucker" pattern
// NOTE: Deviousness only considers RECENT history, not pre-history.
function computeDeviousnessTerm(E, C, own, opp, weights, recentDepth) {
const deviousness = (1 - E) * (1 - C);
if (deviousness < 0.05) return 0;
let mutualCoopWeight = 0;
let mutualDefectWeight = 0;
let suckerExploitWeight = 0; // I defected, they cooperated
// Only consider recent history for deviousness
for (let i = 0; i < recentDepth; i++) {
if (own[i] === 1 && opp[i] === 1) {
mutualCoopWeight += weights.recent[i];
} else if (own[i] === -1 && opp[i] === -1) {
mutualDefectWeight += weights.recent[i];
} else if (own[i] === -1 && opp[i] === 1) {
suckerExploitWeight += weights.recent[i];
}
}
// Normalize to recent-only weights
const recentTotal = weights.recent.reduce((a, b) => a + b, 0);
if (recentTotal > 0) {
mutualCoopWeight /= recentTotal;
mutualDefectWeight /= recentTotal;
suckerExploitWeight /= recentTotal;
}
// Exploit accumulated trust (mild superlinearity)
const exploitTrustEffect = -mutualCoopWeight * (1 + 0.3 * mutualCoopWeight);
// Reset/reconciliation after mutual defection
const resetEffect = mutualDefectWeight * 0.4;
// Continue exploiting suckers - why stop when it's working?
const suckerEffect = -suckerExploitWeight * 1.2;
return deviousness * (exploitTrustEffect + resetEffect + suckerEffect) * 3.5;
}
// Identity modifier: kin altruism and xenophobia effects
// kinAltruism, xenophobia: 0.5 = neutral, >0.5 = ingroup preference, <0.5 = outgroup preference
// Outgroup preference (values < 0.5) has weaker slope as it's "unnatural"
// geneticDistance, culturalDistance: squared Euclidean distance, range [0, 75], capped
function identityModifier(genetics, context) {
const { kinAltruism, xenophobia, openness } = genetics;
const { relatedness, geneticDistance, culturalDistance } = context;
let modifier = 0;
// === KIN ALTRUISM ===
// Reacts to relatedness (inbreeding coefficient, typically 0-0.5)
const kinEffect = kinAltruism - 0.5; // range [-0.5, 0.5]
if (kinEffect >= 0) {
// Ingroup preference: higher relatedness -> more cooperation
modifier += kinEffect * 2 * relatedness * 3.0;
} else {
// Outgroup preference: higher relatedness -> less cooperation (weaker slope)
modifier += kinEffect * 2 * relatedness * 1.5;
}
// === XENOPHOBIA ===
// Reacts to genetic distance (squared, capped at 75)
const cappedGenDist = Math.min(geneticDistance, 75);
const xenoEffect = xenophobia - 0.2; // range [-0.2, 0.8]
const opennessMod = 1 - 0.3 * openness; // O slightly reduces xenophobic effect
if (xenoEffect >= 0) {
// Ingroup preference: higher genetic distance -> less cooperation
// Max effect: 0.5 * 2 * 1 * 75 / 25 = 3.0
modifier -= xenoEffect * 4 * opennessMod * cappedGenDist / 25;
} else {
// Outgroup preference: higher genetic distance -> more cooperation (weaker slope)
modifier -= xenoEffect * 4 * cappedGenDist / 50;
}
// === CULTURAL DISTANCE ===
// Cultural preference is average of kin altruism and xenophobia
// (cultural tribalism blends clannishness and ethnic preference)
if (culturalDistance >= 0) {
const cappedCultDist = Math.min(culturalDistance, 75);
const culturalPref = (kinAltruism + xenophobia) / 2;
const cultEffect = culturalPref - 0.2; // range [-0.2, 0.8]
const cultOpennessMod = 1 - 0.3 * openness; // O reduces cultural penalty
if (cultEffect >= 0) {
// Ingroup preference: higher cultural distance -> less cooperation
modifier -= cultEffect * 4 * cultOpennessMod * cappedCultDist / 25;
} else {
// Outgroup preference (weaker slope)
modifier -= cultEffect * 4 * cappedCultDist / 50;
}
}
return modifier;
}
// Demographic modifier: age-tier based effects
// Tiers: children (7-14), juveniles (14-21), adults (21-65), elderly (>65)
// Effects scaled by C (except F-F penalty scaled by N)
// Note: Effects are on pre-sigmoid score; near 50% prob, slope ~0.25, so ±1.0 score ≈ ±25% prob
function computeDemographicModifier(ownSex, oppSex, ownAge, oppAge, genetics) {
const { conscientiousness: C, neuroticism: N } = genetics;
let modifier = 0;
// Age tier classification
const getTier = (age) => {
if (age < 14) return 'child';
if (age < 21) return 'juvenile';
if (age <= 65) return 'adult';
return 'elderly';
};
const ownTier = getTier(ownAge);
const oppTier = getTier(oppAge);
const sameSex = ownSex === oppSex;
const cScale = 0.5 + C; // range [0.5, 1.5] - scales but doesn't negate
// === CHILDREN (7-14) ===
if (ownTier === 'child') {
// No sex modifiers for children
// Cooperation boost for older opponents (capped at 10 years diff)
const ageDiff = Math.min(oppAge - ownAge, 10);
if (ageDiff > 0) {
modifier += (ageDiff / 10) * 1.2 * cScale; // max +1.2 to +1.8
}
}
// === JUVENILES (14-21) ===
else if (ownTier === 'juvenile') {
// Boost for opposite sex juveniles
if (oppTier === 'juvenile' && !sameSex) {
modifier += 2.0 * cScale; // +1.0 to +3.0
}
// Rebelliousness toward adults/elderly fades with age, C shifts from penalty to respect
// Age 14: baseline -0.80, Age 21: baseline 0
// C=0 adds -0.80, C=1 adds +0.80
if (oppTier === 'adult' || oppTier === 'elderly') {
const ageProgress = (ownAge - 14) / 7; // 0 at 14, 1 at 21
const baseline = -0.80 * (1 - ageProgress); // fades from -0.80 to 0
const cMod = (C - 0.5) * 1.6; // -0.80 at C=0, +0.80 at C=1
modifier += baseline + cMod;
}
}
// === ADULTS (21-65) ===
else if (ownTier === 'adult') {
// Boost for elderly and children
if (oppTier === 'elderly' || oppTier === 'child') {
modifier += 1.0 * cScale; // +0.5 to +1.5
}
// Boost for adult males playing against adult females
if (ownSex === 'm' && oppSex === 'f' && oppTier === 'adult') {
modifier += 0.8 * cScale; // +0.4 to +1.2
}
// Reduction for adult females playing adult females (scaled by N)
if (ownSex === 'f' && oppSex === 'f' && oppTier === 'adult') {
const nScale = 0.5 + N; // range [0.5, 1.5]
modifier -= 1.0 * nScale; // -0.5 to -1.5
}
}
// === ELDERLY (>65) ===
// No specific modifiers for elderly actors (they're generally more agreeable via A)
return modifier;
}
// Global state modifier: happiness only (world trust reserved for future use)
// Slight linear impact centered at 0.5
function computeStateModifier(hap) {
const hapDev = hap - 0.5; // range: [-0.5, 0.5]
return hapDev * 0.8; // slight effect: ±0.4 at extremes
}
// ============================================
// MAIN DECISION FUNCTION
// ============================================
function computeCoopProbability(genetics, state, context, demographics, own, opp, ownAvg, oppAvg, nPre) {
const { openness: O, conscientiousness: C, extraversion: E,
agreeableness: A, neuroticism: N } = genetics;
// Pre-compute identity modifier
const idMod = identityModifier(genetics, context);
// Pre-compute state modifier
const stateMod = computeStateModifier(state.happiness);
// Pre-compute demographic modifier
const demoMod = computeDemographicModifier(
demographics.ownSex, demographics.oppSex,
demographics.ownAge, demographics.oppAge,
genetics
);
// ============================================
// FIRST MOVE (no history)
// ============================================
if (own[0] === 0) {
// Base: A drives initial cooperation
let firstMoveScore = 8.0 * A * A - 2.0;
// C gives principled baseline (linear, mild)
firstMoveScore += 1.5 * C;
// High C (above 0.5) gives additional "principled cooperator" boost
// This represents: highly conscientious people start with good faith
// Superlinear: really takes off as C approaches 1
// At C=0.5: 0, at C=0.75: +1.5, at C=1: +6
const cAboveHalf = Math.max(0, C - 0.5);
firstMoveScore += 6 * cAboveHalf * cAboveHalf * 4;
firstMoveScore = applyTransparency(firstMoveScore, E);
firstMoveScore += idMod + stateMod + demoMod;
return sigmoid(firstMoveScore) * 100;
}
// ============================================
// DETERMINE ACTUAL HISTORY DEPTH
// ============================================
let recentDepth = 1;
if (own[1] !== 0) recentDepth = 2;
if (own[1] !== 0 && own[2] !== 0) recentDepth = 3;
// Pre-history is active when nPre > 0 (only meaningful with full 3-turn history)
const hasPreHistory = recentDepth === 3 && nPre > 0;
const effectiveNPre = hasPreHistory ? nPre : 0;
// ============================================
// TIME DECAY WEIGHTS (proper geometric series)
// ============================================
let decayRate = 0.4 + 0.8 * C - 0.5 * N;
decayRate = clamp(decayRate, 0.1, 1.1);
const weights = computeWeights(decayRate, recentDepth, effectiveNPre);
// ============================================
// OPPONENT ACTION EVALUATION (with N-asymmetry)
// ============================================
const oppValences = evaluateOpponentActions(opp, own, oppAvg, ownAvg, N, recentDepth, effectiveNPre);
// ============================================
// RECIPROCITY TERM
// ============================================
const reciprocityStrength = 4.0;
let oppTerm = 0;
for (let i = 0; i < recentDepth; i++) {
oppTerm += weights.recent[i] * oppValences.recent[i];
}
if (oppValences.pre !== null && weights.pre > 0) {
oppTerm += weights.pre * oppValences.pre;
}
oppTerm *= reciprocityStrength;
// ============================================
// CONSCIENTIOUSNESS TERM (principled behavior)
// ============================================
const principledTerm = computePrincipledAdjustment(C, A, own, opp, ownAvg, oppAvg, weights, recentDepth, effectiveNPre);
// ============================================
// AGREEABLENESS BASELINE
// ============================================
const baseline = 4.0 * A - 1.5;
// ============================================
// DEVIOUSNESS TERM (low E × low C)
// ============================================
const deviousTerm = computeDeviousnessTerm(E, C, own, opp, weights, recentDepth);
// ============================================
// COMBINE SCORE
// ============================================
// "Transparent" behavior (reciprocity, principles, baseline) modulated by E
let transparentScore = baseline + oppTerm + principledTerm;
transparentScore = applyTransparency(transparentScore, E);
// Devious term added separately (not dampened by low E - that's the point)
let score = transparentScore + deviousTerm;
score += idMod + stateMod + demoMod;
return sigmoid(score) * 100;
}
// History patterns for different depths
const PATTERNS_3 = ['CCC', 'CCD', 'CDC', 'CDD', 'DCC', 'DCD', 'DDC', 'DDD'];
const PATTERNS_2 = ['CC', 'CD', 'DC', 'DD'];
const PATTERNS_1 = ['C', 'D'];
function patternToArray(pattern, depth = 3) {
const arr = pattern.split('').map(c => c === 'C' ? 1 : -1);
while (arr.length < depth) {
arr.push(0);
}
return arr;
}
// Compute for no history case
function computeFirstMoveProbability(genetics, state, context, demographics) {
return computeCoopProbability(
genetics, state, context, demographics,
[0, 0, 0], [0, 0, 0], 0, 0, 0
);
}
// Slider component
function Slider({ label, value, onChange, min = 0, max = 1, step = 0.01, color = '#4ade80' }) {
return (
<div className="slider-row">
<label>{label}</label>
<input
type="range"
min={min}
max={max}
step={step}
value={value}
onChange={e => onChange(parseFloat(e.target.value))}
style={{ '--slider-color': color }}
/>
<span className="value">{value.toFixed(2)}</span>
</div>
);
}
// Probability cell with color gradient
function ProbCell({ value }) {
const hue = (value / 100) * 120;
const bg = `hsl(${hue}, 70%, 25%)`;
const text = value > 50 ? '#fff' : '#ddd';
return (
<td style={{ backgroundColor: bg, color: text }}>
{Math.round(value)}
</td>
);
}
function PDVisualizer() {
// Genetic parameters (Big 5 + social)
const [genetics, setGenetics] = useState({
openness: 0.5,
conscientiousness: 0.5,
extraversion: 0.5,
agreeableness: 0.5,
neuroticism: 0.5,
kinAltruism: 0.5, // 0.5 = neutral, >0.5 = ingroup preference
xenophobia: 0.5 // 0.5 = neutral, >0.5 = ingroup preference
});
// Global state (happiness + world trust, both [0,1])
const [state, setState] = useState({
happiness: 0.5, // 0 (distressed) to 1 (satisfied), 0.5 = neutral
worldTrust: 0.5 // 0 (cynical) to 1 (trusting), 0.5 = neutral
});
// Environmental context
const [context, setContext] = useState({