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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
import os
import re
import csv
import json
import math
import openai
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from tqdm import tqdm
from scipy import stats
from datetime import datetime
from collections import defaultdict, Counter
from matplotlib.ticker import FuncFormatter
from matplotlib.colors import ListedColormap
import panel as pn
import altair as alt

def choices_to_df(choices, hue):
    df = pd.DataFrame(choices, columns=['choices'])
    df['hue'] = hue
    df['hue'] = df['hue'].astype(str)
    return df

binrange = (0, 100)
moves = []
with open('dictator.csv', 'r') as f:
    reader = csv.reader(f)
    header = next(reader)
    col2idx = {col: idx for idx, col in enumerate(header)}
    for row in reader:
        record = {col: row[idx] for col, idx in col2idx.items()}

        if record['Role'] != 'first': continue
        if int(record['Round']) > 1: continue
        if int(record['Total']) != 100: continue
        if record['move'] == 'None': continue
        if record['gameType'] != 'dictator': continue

        move = float(record['move'])
        if move < binrange[0] or \
            move > binrange[1]: continue
        
        moves.append(move)

df_dictator_human = choices_to_df(moves, 'Human')

choices = [50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0]
df_dictator_gpt4 = choices_to_df(choices, hue=str('ChatGPT-4'))

choices = [25, 35, 70, 30, 20, 25, 40, 80, 30, 30, 40, 30, 30, 30, 30, 30, 40, 40, 30, 30, 40, 30, 60, 20, 40, 25, 30, 30, 30]
df_dictator_turbo = choices_to_df(choices, hue=str('ChatGPT-3'))

def extract_choices(recrods):
    choices = [extract_amout(
        messages[-1]['content'], 
        prefix='$', 
        print_except=True,
        type=float) for messages in records['messages']
    ]
    choices = [x for x in choices if x is not None]
    # print(choices)
    return choices

def extract_amout(
    message, 
    prefix='',
    print_except=True,
    type=float,
    brackets='[]'
):
    try:
        matches = extract_brackets(message, brackets=brackets)
        matches = [s[len(prefix):] \
            if s.startswith(prefix) \
            else s for s in matches]
        invalid = False
        if len(matches) == 0:
            invalid = True
        for i in range(len(matches)):
            if matches[i] != matches[0]:
                invalid = True
        if invalid:
            raise ValueError('Invalid answer: %s' % message)
        return type(matches[0])
    except Exception as e: 
        if print_except: print(e)
        return None

records = json.load(open('dictator_wo_ex_2023_03_13-11_24_07_PM.json', 'r'))
choices = extract_choices(records)

# Plot 1 - Dictator (altruism)
def plot_facet(
    df_list,
    x='choices',
    hue='hue',
    palette=None,
    binrange=None,
    bins=10,
    # binwidth=10,
    stat='count',
    x_label='',
    sharex=True,
    sharey=False,
    subplot=sns.histplot,
    xticks_locs=None,
    # kde=False,
    **kwargs
):
    data = pd.concat(df_list)
    if binrange is None:
        binrange = (data[x].min(), data[x].max())
    g = sns.FacetGrid(
        data, row=hue, hue=hue, 
        palette=palette,
        aspect=2, height=2, 
        sharex=sharex, sharey=sharey,
        despine=True,
    )
    g.map_dataframe(
        subplot, 
        x=x, 
        # kde=kde, 
        binrange=binrange, 
        bins=bins,
        stat=stat,
        **kwargs
    )
    # g.add_legend(title='hue')
    g.set_axis_labels(x_label, stat.title())
    g.set_titles(row_template="{row_name}")
    for ax in g.axes.flat:
        ax.yaxis.set_major_formatter(
            FuncFormatter(lambda y, pos: '{:.2f}'.format(y))
        )
    
    binwidth = (binrange[1] - binrange[0]) / bins
    if xticks_locs is None:
        locs = np.linspace(binrange[0], binrange[1], bins//2+1)
        locs = [loc + binwidth for loc in locs]
    else: 
        locs = xticks_locs
    labels = [str(int(loc)) for loc in locs]
    locs = [loc + 0.5*binwidth for loc in locs]
    plt.xticks(locs, labels)
    
    g.set(xlim=binrange)
    return g

df = df_dictator_human
bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart1 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10), axis=None),
    y='density:Q',
    color=alt.value('steelblue'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()

df = df_dictator_gpt4
bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart2 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10), axis=None),
    y='density:Q',
    color=alt.value('orange'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()

df = df_dictator_turbo

bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart3 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10)),
    y='density:Q',
    color=alt.value('green'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()

final = alt.vconcat(chart1, chart2, chart3).resolve_scale(x='shared')

#Plot 2 - - Ultimatum (Fairness)
df = pd.read_csv('ultimatum_strategy.csv')
df = df[df['gameType'] == 'ultimatum_strategy']
df = df[df['Role'] == 'player']
df = df[df['Round'] == 1]
df = df[df['Total'] == 100]
df = df[df['move'] != 'None']
df['propose'] = df['move'].apply(lambda x: eval(x)[0])
df['accept'] = df['move'].apply(lambda x: eval(x)[1])
df = df[(df['propose'] >= 0) & (df['propose'] <= 100)]
df = df[(df['accept'] >= 0) & (df['accept'] <= 100)]

df_ultimatum_1_human = choices_to_df(list(df['propose']), 'Human')
df_ultimatum_2_human = choices_to_df(list(df['accept']), 'Human')

choices = [50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0]
df_ultimatum_1_gpt4 = choices_to_df(choices, hue=str('ChatGPT-4'))

choices = [40, 40, 40, 30, 70, 70, 50, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 30, 30, 35, 50, 40, 70, 40, 60, 60, 70, 40, 50]
df_ultimatum_1_turbo = choices_to_df(choices, hue=str('ChatGPT-3'))

choices = [50.0, 50.0, 50.0, 1.0, 1.0, 1.0, 50.0, 25.0, 50.0, 1.0, 1.0, 20.0, 50.0, 50.0, 50.0, 20.0, 50.0, 1.0, 1.0, 1.0, 50.0, 50.0, 50.0, 1.0, 1.0, 1.0, 20.0, 1.0] + [0, 1]
df_ultimatum_2_gpt4 = choices_to_df(choices, hue=str('ChatGPT-4'))

choices = [None, 50, 50, 50, 50, 30, None, None, 30, 33.33, 40, None, 50, 40, None, 1, 30, None, 10, 50, 30, 10, 30, None, 30, None, 10, 30, 30, 30]
df_ultimatum_2_turbo = choices_to_df(choices, hue=str('ChatGPT-3'))

choices = [50.0, 50.0, 10.0, 40.0, 20.0, 50.0, 1.0, 1.0, 50.0, 1.0, 50.0, 50.0, 20.0, 10.0, 50.0, 20.0, 1.0, 1.0, 50.0, 1.0, 20.0, 1.0, 50.0, 50.0, 20.0, 20.0, 50.0, 20.0, 1.0, 50.0]
df_ultimatum_2_gpt4_female = choices_to_df(choices, hue='ChatGPT-4 Female')

choices = [1.0, 1.0, 1.0, 20.0, 1.0, 1.0, 50.0, 1.0, 1.0, 50.0, 50.0, 50.0, 20.0, 20.0, 1.0, 50.0, 1.0, 1.0, 1.0, 50.0, 20.0, 1.0, 50.0, 20.0, 20.0, 10.0, 50.0, 1.0, 1.0, 1.0]
df_ultimatum_2_gpt4_male = choices_to_df(choices, hue='ChatGPT-4 Male')

choices = [40.0, 1.0, 1.0, 20.0, 1.0, 20.0, 50.0, 50.0, 1.0, 1.0, 1.0, 50.0, 1.0, 20.0, 50.0, 10.0, 50.0, 1.0, 1.0, 20.0, 1.0, 50.0, 20.0, 20.0, 20.0, 1.0, 1.0, 1.0, 1.0, 40.0]
df_ultimatum_2_gpt4_US = choices_to_df(choices, hue='ChatGPT-4 US')

choices = [1.0, 1.0, 20.0, 50.0, 1.0, 1.0, 1.0, 1.0, 20.0, 20.0, 50.0, 20.0, 20.0, 50.0, 20.0, 1.0, 40.0, 50.0, 1.0, 1.0, 1.0, 20.0, 1.0, 1.0, 50.0, 50.0, 1.0, 1.0, 1.0, 1.0]
df_ultimatum_2_gpt4_Poland = choices_to_df(choices, hue='ChatGPT-4 Poland')

choices = [50.0, 1.0, 20.0, 50.0, 50.0, 50.0, 50.0, 1.0, 1.0, 50.0, 1.0, 50.0, 1.0, 50.0, 1.0, 20.0, 1.0, 1.0, 20.0, 50.0, 0.0, 20.0, 1.0, 1.0, 1.0, 1.0, 20.0, 20.0, 50.0, 20.0]
df_ultimatum_2_gpt4_China = choices_to_df(choices, hue='ChatGPT-4 China')

choices = [1.0, 1.0, 1.0, 50.0, 1.0, 1.0, 50.0, 40.0, 1.0, 1.0, 1.0, 1.0, 20.0, 1.0, 1.0, 50.0, 1.0, 50.0, 1.0, 20.0, 1.0, 20.0, 1.0, 50.0, 1.0, 50.0, 20.0, 1.0, 1.0, 50.0]
df_ultimatum_2_gpt4_UK = choices_to_df(choices, hue='ChatGPT-4 UK')

choices = [50.0, 1.0, 20.0, 50.0, 50.0, 50.0, 50.0, 10.0, 1.0, 40.0, 50.0, 20.0, 1.0, 1.0, 1.0, 50.0, 50.0, 20.0, 20.0, 1.0, 1.0, 50.0, 20.0, 50.0, 50.0, 20.0, 1.0, 20.0, 50.0, 1]
df_ultimatum_2_gpt4_Columbia = choices_to_df(choices, hue='ChatGPT-4 Columbia')

choices = [50.0, 1.0, 50.0, 20.0, 20.0, 20.0, 50.0, 20.0, 20.0, 1.0, 1.0, 1.0, 1.0, 20.0, 1.0, 50.0, 1.0, 20.0, 20.0, 50.0, 1.0, 50.0, 1.0, 40.0, 1.0, 20.0, 1.0, 20.0, 1.0, 1.0]
df_ultimatum_2_gpt4_under = choices_to_df(choices, hue='ChatGPT-4 Undergrad')

choices = [1.0, 20.0, 1.0, 40.0, 50.0, 1.0, 1.0, 1.0, 25.0, 20.0, 50.0, 20.0, 50.0, 50.0, 1.0, 50.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 50.0, 20.0, 1.0, 1.0, 1.0, 50.0, 20.0, 20.0]
df_ultimatum_2_gpt4_grad = choices_to_df(choices, hue='ChatGPT-4 Graduate')

df = df_ultimatum_1_human
bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart1 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10), axis=None),
    y='density:Q',
    color=alt.value('steelblue'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()

df = df_ultimatum_1_gpt4
bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart2 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10), axis=None),
    y='density:Q',
    color=alt.value('orange'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()

df = df_ultimatum_1_turbo
bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart3 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10)),
    y='density:Q',
    color=alt.value('green'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()

final2 = alt.vconcat(chart1, chart2, chart3).resolve_scale(x='shared')

#Plot 3 - - Ultimatum (Responder) (spite)
df = df_ultimatum_2_human
bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart1 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10), axis=None),
    y='density:Q',
    color=alt.value('steelblue'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()

df = df_ultimatum_2_gpt4
bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart2 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10), axis=None),
    y='density:Q',
    color=alt.value('orange'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()

df = df_ultimatum_2_turbo
bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart3 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10), axis=None),
    y='density:Q',
    color=alt.value('green'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()

final3 = alt.vconcat(chart1, chart2, chart3).resolve_scale(x='shared')

#Plot 4 - - Trust (as Investor) (trust)
binrange = (0, 100)
moves_1 = []
moves_2 = defaultdict(list)
with open('trust_investment.csv', 'r') as f:
    reader = csv.reader(f)
    header = next(reader)
    col2idx = {col: idx for idx, col in enumerate(header)}
    for row in reader:
        record = {col: row[idx] for col, idx in col2idx.items()}

        # if record['Role'] != 'first': continue
        if int(record['Round']) > 1: continue
        # if int(record['Total']) != 100: continue
        if record['move'] == 'None': continue
        if record['gameType'] != 'trust_investment': continue

        if record['Role'] == 'first':
            move = float(record['move'])
            if move < binrange[0] or \
                move > binrange[1]: continue
            moves_1.append(move)
        elif record['Role'] == 'second':
            inv, ret = eval(record['roundResult'])
            if ret < 0 or \
                ret > inv * 3: continue
            moves_2[inv].append(ret)
        else: continue

df_trust_1_human = choices_to_df(moves_1, 'Human')
df_trust_2_human = choices_to_df(moves_2[10], 'Human')
df_trust_3_human = choices_to_df(moves_2[50], 'Human')
df_trust_4_human = choices_to_df(moves_2[100], 'Human')

choices = [50.0, 50.0, 40.0, 30.0, 50.0, 50.0, 40.0, 50.0, 50.0, 50.0, 50.0, 50.0, 30.0, 30.0, 50.0, 50.0, 50.0, 40.0, 40.0, 50.0, 50.0, 50.0, 50.0, 40.0, 50.0, 50.0, 50.0, 50.0] 
df_trust_1_gpt4 = choices_to_df(choices, hue=str('ChatGPT-4'))

choices = [50.0, 50.0, 30.0, 30.0, 30.0, 60.0, 50.0, 40.0, 20.0, 20.0, 50.0, 40.0, 30.0, 20.0, 30.0, 20.0, 30.0, 60.0, 50.0, 30.0, 50.0, 20.0, 20.0, 30.0, 50.0, 30.0, 30.0, 50.0, 40.0] + [30]
df_trust_1_turbo = choices_to_df(choices, hue=str('ChatGPT-3'))

choices = [20.0, 20.0, 20.0, 20.0, 15.0, 15.0, 15.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 15.0, 20.0, 20.0, 20.0, 20.0, 20.0, 15.0, 15.0, 20.0, 15.0, 15.0, 15.0, 15.0, 15.0, 20.0, 20.0, 15.0]
df_trust_2_gpt4 = choices_to_df(choices, hue=str('ChatGPT-4'))

choices = [20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 15.0, 25.0, 30.0, 30.0, 20.0, 25.0, 30.0, 20.0, 20.0, 18.0] + [20, 20, 20, 25, 25, 25, 30]
df_trust_2_turbo = choices_to_df(choices, hue=str('ChatGPT-3'))

choices = [100.0, 75.0, 75.0, 75.0, 75.0, 75.0, 100.0, 75.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 75.0, 100.0, 75.0, 75.0, 75.0, 100.0, 100.0, 100.0, 75.0, 100.0, 100.0, 100.0, 100.0, 75.0, 100.0, 75.0]
df_trust_3_gpt4 = choices_to_df(choices, hue=str('ChatGPT-4'))

choices = [150.0, 100.0, 150.0, 150.0, 50.0, 150.0, 100.0, 150.0, 100.0, 100.0, 100.0, 150.0] + [100, 100, 100, 100, 100, 100, 100, 100]
df_trust_3_turbo = choices_to_df(choices, hue=str('ChatGPT-3'))

choices = [200.0, 200.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 200.0, 200.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0, 150.0]
df_trust_4_gpt4 = choices_to_df(choices, hue=str('ChatGPT-4'))

choices = [225.0, 225.0, 300.0, 300.0, 220.0, 300.0, 250.0] + [200, 200, 250, 200, 200]
df_trust_4_turbo = choices_to_df(choices, hue=str('ChatGPT-3'))

df = df_trust_1_human

bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart1 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10), axis=None),
    y='density:Q',
    color=alt.value('steelblue'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()



df = df_trust_1_gpt4

bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart2 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10), axis=None),
    y='density:Q',
    color=alt.value('orange'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()


df = df_trust_1_turbo

bin_ranges = [0, 10, 30, 50, 70]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart3 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(extent=[0, 70], step=10), axis=None),
    y='density:Q',
    color=alt.value('green'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()
    
    
final4 = alt.vconcat(chart1, chart2, chart3).resolve_scale(x='shared')

#Plot 5 - Trust (as Banker) (fairness, altruism, reciprocity)
df = df_trust_3_human

bin_ranges = [0, 25, 50, 75, 100, 125, 150]

custom_ticks = [2, 6, 10, 14, 18]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart1 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(step=10), axis=None),
    y='density:Q',
    color=alt.value('steelblue')
).properties(
    width=500,
    title='Density of Choices'
).interactive()



df = df_trust_3_gpt4

bin_ranges = [0, 25, 50, 75, 100, 125, 150]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart2 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(step=10), axis=None),
    y='density:Q',
    color=alt.value('orange')
).properties(
    width=500,
    title='Density of Choices'
).interactive()


df = df_trust_3_turbo

bin_ranges = [0, 25, 50, 75, 100, 125, 150]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart3 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(step=10)),
    y='density:Q',
    color=alt.value('green')
).properties(
    width=500,
    title='Density of Choices'
).interactive()

# chart1
final5 = alt.vconcat(chart1, chart2, chart3).resolve_scale(x='shared')

#Plot 6 - Public Goods (Free-Riding, altruism, cooperation)
df = pd.read_csv('public_goods_linear_water.csv')
df = df[df['Role'] == 'contributor']
df = df[df['Round'] <= 3]
df = df[df['Total'] == 20]
df = df[df['groupSize'] == 4]
df = df[df['move'] != None]
df = df[(df['move'] >= 0) & (df['move'] <= 20)]
df = df[df['gameType'] == 'public_goods_linear_water']

round_1 = df[df['Round'] == 1]['move']
round_2 = df[df['Round'] == 2]['move']
round_3 = df[df['Round'] == 3]['move']
print(len(round_1), len(round_2), len(round_3))
df_PG_human = pd.DataFrame({
    'choices': list(round_1)
})
df_PG_human['hue'] = 'Human'
# df_PG_human

file_names = [
    'PG_basic_turbo_2023_05_09-02_49_09_AM.json',
    'PG_basic_turbo_loss_2023_05_09-03_59_49_AM.json',
    'PG_basic_gpt4_2023_05_09-11_15_42_PM.json',
    'PG_basic_gpt4_loss_2023_05_09-10_44_38_PM.json',
]

choices = []
for file_name in file_names:
    with open(file_name, 'r') as f:
        choices += json.load(f)['choices']
choices_baseline = choices

choices = [tuple(x)[0] for x in choices]
df_PG_turbo = choices_to_df(choices, hue=str('ChatGPT-3'))
# df_PG_turbo.head()
df_PG_gpt4 = choices_to_df(choices, hue=str('ChatGPT-4'))
# df_PG_gpt4.head()

df = df_PG_human

bin_ranges = [0, 25, 50, 75, 100, 125, 150]

custom_ticks = [2, 6, 10, 14, 18]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart1 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(step=2), axis=None),
    y='density:Q',
    color=alt.value('steelblue'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()



df = df_PG_gpt4

bin_ranges = [0, 25, 50, 75, 100, 125, 150]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart2 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(step=2), axis=None),
    y='density:Q',
    color=alt.value('orange'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()


df = df_PG_turbo

bin_ranges = [0, 25, 50, 75, 100, 125, 150]

# Calculate density as a percentage
density_percentage = df['choices'].value_counts(normalize=True)

# Create a DataFrame with the density percentages
density_df = pd.DataFrame({'choices': density_percentage.index, 'density': density_percentage.values})

# Create the bar chart using Altair
chart3 = alt.Chart(density_df).mark_bar().encode(
    x=alt.X('choices:O', bin=alt.Bin(step=2)),
    y='density:Q',
    color=alt.value('green'),
    tooltip=['density']
).properties(
    width=500,
    title='Density of Choices'
).interactive()
    
# chart1
final6 = alt.vconcat(chart1, chart2, chart3).resolve_scale(x='shared')

#Final_Final
final_final = (final | final2 | final3 ) & (final4 | final5 | final6)

#Dashboard
import panel as pn
import vega_datasets

# Enable Panel extensions
pn.extension(design='bootstrap')
pn.extension('vega')

template = pn.template.BootstrapTemplate(
    title='SI649 Project2',
)

# the main column will hold our key content
maincol = pn.Column()

options1 = ['ALL', 'Choose Your Own', 'Based On Category']
select0 = pn.widgets.Select(options=options1, name='Choose what to compare')
# maincol.append(select0)

# Charts
charts = []
charts.append(final)
charts.append(final2)
charts.append(final3)
charts.append(final4)
charts.append(final5)
charts.append(final6)

# Define options for dropdown
options = [f'Chart {i+1}' for i in range(len(charts))]

# Panel widgets
select1 = pn.widgets.Select(options=options, name='Select Chart 1')
select2 = pn.widgets.Select(options=options, name='Select Chart 2')

options = ['Altruism', 'Fairness', 'spite', 'trust', 'reciprocity', 'free-riding', 'cooperation']
select_widget = pn.widgets.Select(options=options, name='Select a category')


# Define function to update chart
def update_chart(value):
    if value:
        index = int(value.split()[-1]) - 1
        return charts[index]
    else:
        return None

# Combine dropdown and chart
@pn.depends(select1.param.value, select2.param.value)
def update_plots(value1, value2):
    selected_chart1 = update_chart(value1)
    selected_chart2 = update_chart(value2)
    if selected_chart1 and selected_chart2:
        return pn.Row(selected_chart1, selected_chart2)
    elif selected_chart1:
        return selected_chart1
    elif selected_chart2:
        return selected_chart2
    else:
        return None
    
# Define functions for each category
def update_plots_altruism():
    return pn.Row(final, final5)

def update_plots_fairness():
    return pn.Row(final2, final5)

def update_plots_spite():
    return final

def update_plots_trust():
    return final4

def update_plots_reciprocity():
    return final5

def update_plots_freeriding():
    return final6

def update_plots_cooperation():
    return final6

# Define a dictionary to map categories to update functions
update_functions = {
    'Altruism': update_plots_altruism,
    'Fairness': update_plots_fairness,
    'spite': update_plots_spite,
    'trust': update_plots_trust,
    'reciprocity': update_plots_reciprocity,
    'freeriding': update_plots_freeriding,
    'cooperation': update_plots_cooperation
}


# # Define function to update chart based on selected category
# def update_plots_category(event):
#     selected_category = event.new
#     maincol.clear()  # Clear existing content in main column
    
#     if selected_category in update_functions:
#         update_function = update_functions[selected_category]
#         maincol.append(update_function())
#     else:
#         maincol.append(pn.pane.Markdown(f"No update function found for category: {selected_category}"))

# Define function to update chart based on selected category
def update_plots_category(event):
    selected_category = event.new
    maincol.clear()  # Clear existing content in main column
    
    if selected_category in update_functions:
        update_function = update_functions[selected_category]
        maincol.append(update_function())
    else:
        maincol.append(pn.pane.Markdown(f"No update function found for category: {selected_category}"))
    
    # Append select_widget again to allow changing the category selection
    maincol.append(select_widget)


# Callback function to handle select widget events
def select_callback(event):
    selected_value = event.new
    maincol.clear()  # Clear existing content in main column
    
    if selected_value == 'Choose Your Own':
        maincol.append(select1)
        maincol.append(select2)
        maincol.append(update_plots)

    elif selected_value == 'Based On Category':
        maincol.append(select_widget)
        select_widget.param.watch(update_plots_category, 'value')
        
#         # Bind the update_plots_category function to the select widget's 'value' parameter
#         select.param.watch
        # maincol.append(update_plots_category())

# Bind the callback function to the select widget's 'value' parameter
select0.param.watch(select_callback, 'value')

maincol.append(select0)

template.main.append(maincol)
template.servable()