-
Notifications
You must be signed in to change notification settings - Fork 0
/
__all_functions.py
executable file
·1809 lines (1467 loc) · 75.9 KB
/
__all_functions.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
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
import matplotlib.pyplot as plt
import math
from pywaffle import Waffle
import umap
from rdkit import Chem
from rdkit.Chem import AllChem
import numpy as np
from matplotlib.ticker import LogFormatter
from scipy import stats
import re
from sklearn.decomposition import PCA
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
from scipy.stats import mode
import rdkit
from sklearn.cluster import KMeans
from matplotlib.colors import Normalize
from collections import Counter
from sklearn.metrics import auc
import pywaffle
from tqdm import tqdm
from matplotlib.colors import BoundaryNorm
from sklearn.manifold import TSNE
import matplotlib.patches as mpatches
from scipy.stats import ttest_ind
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
import scipy.ndimage
from rdkit.Chem import PandasTools
import matplotlib.patches as mpatches
def analyze_data(df):
"""
Analyzes data by computing the mean result and the most frequently given answer per slide.
Parameters:
- df: DataFrame containing the columns 'Slide_ID', 'Result', and 'Answer'.
Returns:
- DataFrame with the mean result and the most frequently given answer for each slide.
"""
grouped = df.groupby('Slide_ID')
success_rate = grouped['Result'].mean()
most_given_answer = grouped['Answer'].agg(lambda x: mode(x)[0][0])
analysis_result = pd.DataFrame({
'Success_Rate': success_rate,
'Most_Given_Answer': most_given_answer
}).reset_index()
analysis_result['Slide_ID'] = analysis_result['Slide_ID'].apply(lambda x: str(int(x)))
return analysis_result
def remove_consistent_chemists(df):
"""
Removes chemists from the dataset who have shown consistent answers and certitudes across all entries.
Parameters:
- df: DataFrame containing 'Chemist', 'Certitude', and 'Answer' columns.
Returns:
- DataFrame with inconsistent chemists.
"""
consistent_chemists = df.groupby('Chemist').filter(lambda x: x['Certitude'].nunique() == 1 and x['Answer'].nunique() == 1)
chemists_to_remove = consistent_chemists['Chemist'].unique()
return df[~df['Chemist'].isin(chemists_to_remove)]
def compute_most_frequent_combined_weight_Endpoint(df):
"""
Computes the most frequent answer for each endpoint and question, weighted by certitude and chemist level.
Parameters:
- df: DataFrame containing 'Endpoint', 'Question', 'Answer', 'Certitude', 'Chemist Level', and 'Correct_Answer'.
Returns:
- DataFrame with most frequent answers and their correctness for each question and endpoint.
"""
def weighted_combined_most_frequent(group):
answers = group['Answer'].unique()
max_weighted_answer = None
max_weight = -np.inf
for answer in answers:
subset = group[group['Answer'] == answer]
weight_sum = ((subset['Certitude'] + subset['Chemist Level']) / 10).sum()
if weight_sum > max_weight:
max_weight = weight_sum
max_weighted_answer = answer
return max_weighted_answer
grouped = df.groupby(['Endpoint', 'Question']).apply(weighted_combined_most_frequent).reset_index(name='Most_Frequent_Answer')
grouped = grouped.merge(df[['Question', 'Correct_Answer']].drop_duplicates(), on='Question', how='left')
grouped['Most_Frequent_Correct'] = (grouped['Most_Frequent_Answer'] == grouped['Correct_Answer']).astype(int)
return grouped
def compute_most_frequent_Endpoint(df, weighted=False):
"""
Computes the most frequent answer for each endpoint and question, optionally weighted by certitude.
Parameters:
- df: DataFrame containing 'Endpoint', 'Question', 'Answer', 'Certitude', and 'Correct_Answer'.
- weighted: Boolean indicating whether to weight answers by certitude levels (default is False).
Returns:
- DataFrame with most frequent answers and their correctness for each question and endpoint.
"""
weights = {1: 1/5, 2: 2/5, 3: 3/5, 4: 4/5, 5: 1}
def weighted_most_frequent(group):
answers = group['Answer'].unique()
max_weighted_answer = None
max_weight = -np.inf
for answer in answers:
subset = group[group['Answer'] == answer]
if weighted:
weight_sum = subset['Certitude'].map(weights).sum()
else:
weight_sum = len(subset)
if weight_sum > max_weight:
max_weight = weight_sum
max_weighted_answer = answer
return max_weighted_answer
grouped = df.groupby(['Endpoint', 'Question']).apply(weighted_most_frequent).reset_index(name='Most_Frequent_Answer')
grouped = grouped.merge(df[['Question', 'Correct_Answer']].drop_duplicates(), on='Question', how='left')
grouped['Most_Frequent_Correct'] = (grouped['Most_Frequent_Answer'] == grouped['Correct_Answer']).astype(int)
return grouped
def compute_scores(df):
score = df.groupby('Chemist')['Result'].mean().reset_index()
score.columns = ['Chemist', 'Score']
score = score.merge(df[['Chemist', 'Chemist Level', 'Certitude']].drop_duplicates(), on='Chemist')
return score
def assign_chemist_group(level):
if level < 3:
return 1 # non-expert
elif level >=3 and level <= 5:
return 2 # expert
else:
return 3 # al
# Function to reclassify chemists based on success rate
def reclassify_chemist_by_sr(df):
d_new = []
score_l = df["Score"].tolist()
score_k = df["Chemist Level"].tolist()
for r in range(len(df["Score"].tolist())):
if score_k[r]==6:
d_new.append(3)
else:
if score_l[r] > 0.5:
d_new.append(2)
else:
d_new.append(1)
return d_new
def columns_to_dict(df, key_column, value_column):
return df.set_index(key_column)[value_column].to_dict()
def transform_dataset_B_v2(df):
df = df.replace({"✓": 1, "": 0})
question_nums = sorted(set(int(col.split(":")[0][1:]) for col in df.columns if "Q" in col))
Qs = []
Answers = []
Certitudes = []
for q_num in question_nums:
q_cols = [col for col in df.columns if f"Q{q_num}:" in col]
answer_column = df[q_cols].idxmax(axis=1).fillna("None").astype(str).str.split(":").str[1].str.strip()
if q_num == 1:
Qs.append(answer_column)
elif q_num %2:
Answers.append(answer_column)
else:
Certitudes.append(answer_column)
df["Chemist Level"] = Qs[0]
for i, cert in enumerate(Answers, 1):
df[f"Answer Q{i}"] = cert
for i, cert in enumerate(Certitudes, 1):
df[f"Certitude Q{i}"] = cert
df["Chemist"] = ['Chemist_'+str(i+1) for i in range(len(df))]
inside = []
for c in df.columns.tolist():
if ":" not in c:
inside.append(c)
df = df[inside]
return df
def _merge_data_CI(CI_s1_path, CI_s2_path, CI_structures_path):
df_A = pd.read_csv(CI_structures_path, sep=',')
df_B = pd.read_csv(CI_s1_path, sep = ";")
df_B_transformed = transform_dataset_B_v2(df_B.copy())
# Melting the first dataframe
df1_melted = df_B_transformed.melt(id_vars=['Chemist Level', 'Chemist'], value_vars=[col for col in df_B_transformed.columns if 'Answer Q' in col], var_name='Question', value_name='Answer')
df1_melted['Slide_ID'] = df1_melted['Question'].str.extract('(\d+)').astype(float)
merged_df = df1_melted.merge(df_A, on='Slide_ID', how='left')
df1_melted_cert = df_B_transformed.melt(id_vars=['Chemist Level', 'Chemist'], value_vars=[col for col in df_B_transformed.columns if 'Certitude Q' in col], var_name='Question', value_name='Certitude')
df1_melted_cert['Slide_ID'] = df1_melted_cert['Question'].str.extract('(\d+)').astype(float)
merged_with_cert = merged_df.merge(df1_melted_cert[['Chemist', 'Chemist Level', 'Slide_ID', 'Certitude']], on=['Chemist', 'Chemist Level', 'Slide_ID'], how='left')
merged_with_cert = merged_with_cert.dropna().rename(columns = {"Certitude":"Answer", "Answer":"Certitude"})
merged_with_cert.to_csv('../data/CI_Answer_A.csv', index = None)
df_B = pd.read_csv(CI_s2_path, sep = ";")
df_B_transformed = transform_dataset_B_v2(df_B.copy())
col = []
for c in df_B_transformed.columns.tolist():
if "Q" in c:
if "Answer" in c:
col.append("Answer Q"+ str(int(c.replace("Answer Q", ""))+37))
if "Certitude" in c:
col.append("Certitude Q"+ str(int(c.replace("Certitude Q", ""))+37))
else:
col.append(c)
df_B_transformed.columns = col
df1_melted = df_B_transformed.melt(id_vars=['Chemist Level', 'Chemist'], value_vars=[col for col in df_B_transformed.columns if 'Answer Q' in col], var_name='Question', value_name='Answer')
df1_melted['Slide_ID'] = df1_melted['Question'].str.extract('(\d+)').astype(float)
merged_df = df1_melted.merge(df_A, on='Slide_ID', how='left')
df1_melted_cert = df_B_transformed.melt(id_vars=['Chemist Level', 'Chemist'], value_vars=[col for col in df_B_transformed.columns if 'Certitude Q' in col], var_name='Question', value_name='Certitude')
df1_melted_cert['Slide_ID'] = df1_melted_cert['Question'].str.extract('(\d+)').astype(float)
merged_with_cert = merged_df.merge(df1_melted_cert[['Chemist', 'Chemist Level', 'Slide_ID', 'Certitude']], on=['Chemist', 'Chemist Level', 'Slide_ID'], how='left')
merged_with_cert = merged_with_cert.dropna().rename(columns = {"Certitude":"Answer", "Answer":"Certitude"})
merged_with_cert.to_csv('../data/CI_Answer_B.csv', index = None)
df_A = pd.read_csv('../data/CI_Answer_A.csv', sep=',')
df_B = pd.read_csv('../data/CI_Answer_B.csv', sep=',')
df_B = remove_consistent_chemists(df_B)
df_A = remove_consistent_chemists(df_A)
df_A.to_csv('../data/CI_Answer_A.csv', index = None)
df_B.to_csv('../data/CI_Answer_B.csv', index = None)
# Creates new column
df_A['Result'] = np.where(df_A['Correct_Answer'] == df_A['Answer'], 1, 0)
df_B['Result'] = np.where(df_B['Correct_Answer'] == df_B['Answer'], 1, 0)
combined_df = pd.concat([df_A, df_B])
combined_df = combined_df[combined_df['Certitude'].isna()!=True]
df_A = pd.read_csv('../data/CI_Answer_A.csv', sep=',')
df_B = pd.read_csv('../data/CI_Answer_B.csv', sep=',')
df_A['Result'] = np.where(df_A['Correct_Answer'] == df_A['Answer'], 1, 0)
df_B['Result'] = np.where(df_B['Correct_Answer'] == df_B['Answer'], 1, 0)
combined_scores = pd.concat([compute_scores(df_A), compute_scores(df_B)], ignore_index=True)
combined_scores_all = combined_scores.copy()
combined_scores_all["Chemist Level"] = 6
combined_scores = pd.concat([combined_scores_all, combined_scores])
df_A_all = df_A.copy()
df_A_all["Chemist Level"] = 6
df_A = pd.concat([df_A_all, df_A])
df_B_all = df_B.copy()
df_B_all["Chemist Level"] = 6
df_B = pd.concat([df_B_all, df_B])
df_A["Chemist Group"] = df_A["Chemist Level"].apply(assign_chemist_group)
df_B["Chemist Group"] = df_B["Chemist Level"].apply(assign_chemist_group)
combined_scores["Chemist Group"] = combined_scores["Chemist Level"].apply(assign_chemist_group)
most_frequent_combined = pd.concat([compute_most_frequent(df_A, False), compute_most_frequent(df_B, False)])
most_frequent_combined = most_frequent_combined[most_frequent_combined["Chemist Group"]==3]
most_frequent_combined = most_frequent_combined[["Question","Most_Frequent_Answer"]]
most_frequent_combined.columns = ["Slide_ID","Most_Frequent_Answer"]
most_frequent_combined["Slide_ID"] = [i.split("Q")[-1] for i in most_frequent_combined["Slide_ID"].tolist()]
most_frequent_combined.to_csv("./data/CollectiveIntelligence/CI_Answer_v3-Response_Most_Frequent.csv", index = False)
df_A['Result'] = np.where(df_A['Correct_Answer'] == df_A['Answer'], 1, 0)
df_B['Result'] = np.where(df_B['Correct_Answer'] == df_B['Answer'], 1, 0)
combined_scores = pd.concat([compute_scores(df_A), compute_scores(df_B)], ignore_index=True)
combined_scores_all = combined_scores.copy()
combined_scores_all["Chemist Level"] = 6
combined_scores = pd.concat([combined_scores_all, combined_scores])
df_A_all = df_A.copy()
df_A_all["Chemist Level"] = 6
df_A = pd.concat([df_A_all, df_A])
df_B_all = df_B.copy()
df_B_all["Chemist Level"] = 6
df_B = pd.concat([df_B_all, df_B])
df_A["Chemist Group"] = df_A["Chemist Level"].apply(assign_chemist_group)
df_B["Chemist Group"] = df_B["Chemist Level"].apply(assign_chemist_group)
combined_scores["Chemist Group"] = combined_scores["Chemist Level"].apply(assign_chemist_group)
most_frequent_combined = pd.concat([compute_most_frequent(df_A, False), compute_most_frequent(df_B, False)])
most_frequent_combined = most_frequent_combined[most_frequent_combined["Chemist Group"]==3]
most_frequent_combined = most_frequent_combined[["Question","Most_Frequent_Answer"]]
most_frequent_combined.columns = ["Slide_ID","Most_Frequent_Answer"]
most_frequent_combined["Slide_ID"] = [i.split("Q")[-1] for i in most_frequent_combined["Slide_ID"].tolist()]
most_frequent_combined.to_csv("./data/CollectiveIntelligence/CI_Answer_v3-Response_Most_Frequent.csv", index = False)
return(combined_df)
def plot_aggregation_AM(ax, csv_file_paths, aggregation_methods, admet):
"""Plot aggregation of ADMET data using different methods.
Args:
ax (matplotlib.axis): The axis object to plot on.
csv_file_paths (list of str): List of CSV file paths containing data.
aggregation_methods (list of str): List of aggregation methods used.
admet (str): String specifying the ADMET endpoint.
"""
colors = ['grey', '#8c510a', '#01665e']
for csv_file_path, name_agg, color in zip(csv_file_paths, aggregation_methods, colors):
df_t = pd.read_csv(csv_file_path)
dt_all = df_t.copy()
dt_all['Mean_SR'] *= 100
dt_all['25th_Percentile_SR'] *= 100
dt_all['75th_Percentile_SR'] *= 100
dt_all['25th_Percentile_SR'] = dt_all['Mean_SR'] - abs(dt_all['25th_Percentile_SR'] - dt_all['Mean_SR'])/2
dt_all['75th_Percentile_SR'] = dt_all['Mean_SR'] + abs(dt_all['25th_Percentile_SR'] - dt_all['Mean_SR'])/2
dt_all['25th_Percentile_SR'].fillna(dt_all['Mean_SR'], inplace=True)
dt_all['75th_Percentile_SR'].fillna(dt_all['Mean_SR'], inplace=True)
# Filter for Chemist Group == 3
subset = dt_all[dt_all['Chemist Group'] == 3].drop_duplicates("Key")
keys_with_zero_n = np.insert([ik+1 for ik in range(len(subset))], 0, 0)
smoothed_data = scipy.ndimage.filters.gaussian_filter1d(subset['Mean_SR'], sigma=1)
smoothed_data = np.insert(smoothed_data, 0, subset["Mean_SR"].tolist()[0])
ax.plot(keys_with_zero_n, smoothed_data, label=name_agg, linewidth=2, color=color)
smoothed_data_up = scipy.ndimage.filters.gaussian_filter1d(subset['75th_Percentile_SR'], sigma=1)
smoothed_data_up = np.insert(smoothed_data_up, 0, subset["Mean_SR"].tolist()[0])
ax.plot(keys_with_zero_n, smoothed_data_up, linewidth=1, color=colors[aggregation_methods.index(name_agg)], linestyle='--')
smoothed_data_down = scipy.ndimage.filters.gaussian_filter1d(subset['25th_Percentile_SR'], sigma=1)
smoothed_data_down = np.insert(smoothed_data_down, 0, subset["Mean_SR"].tolist()[0])
ax.plot(keys_with_zero_n, smoothed_data_down, linewidth=1, color=colors[aggregation_methods.index(name_agg)], linestyle='--')
ax.fill_between(keys_with_zero_n, smoothed_data_up, smoothed_data_down, color=colors[aggregation_methods.index(name_agg)], alpha=0.1)
ax.set_xlabel('Number of participants', fontsize=14)
ax.set_ylabel('Success Rate (%)', fontsize=14)
ax.grid(axis='y', linestyle='--', color='silver', alpha=1)
ax.legend(fontsize=10, loc='lower right')
ax.set_xlim((0, 92))
ax.set_ylim((20, 100)) # Adjust as needed
ax.set_axisbelow(True)
plt.tight_layout()
def plot_aggregation_expert_group(csv_file_path, output_file_path, name_agg, admet):
"""Plot aggregation of ADMET data for expert groups.
Args:
csv_file_path (str): Path to the CSV file containing data.
output_file_path (str): Path to save the output plot.
name_agg (str): Aggregation method name.
admet (str): String specifying the ADMET endpoint.
"""
df = pd.read_csv(csv_file_path)
df *= 100 # Scale percentages
fig, ax = plt.subplots(figsize=(6, 6))
# Adjust percentiles to center around the mean
df['25th_Percentile_SR'] = df['Mean_SR'] - abs(df['25th_Percentile_SR'] - df['Mean_SR']) / 2
df['75th_Percentile_SR'] = df['Mean_SR'] + abs(df['25th_Percentile_SR'] - df['Mean_SR']) / 2
df[['25th_Percentile_SR', '75th_Percentile_SR']].fillna(df['Mean_SR'], inplace=True)
chemist_groups = df['Chemist Group'].unique()
colors = ['#8e0052', '#276319', '#6f9fc7'] # Color for each group
for i, group in enumerate(chemist_groups):
subset = df[df['Chemist Group'] == group].drop_duplicates("Key")
keys_with_zero_n = np.insert([j + 1 for j in range(len(subset))], 0, 0)
label = {1: "Non-Expert (1-2)", 2: "Expert (3-5)", 3: "All"}.get(group)
# Smooth data
for percentile in ['Mean_SR', '75th_Percentile_SR', '25th_Percentile_SR']:
smoothed_data = scipy.ndimage.filters.gaussian_filter1d(subset[percentile], sigma=1)
smoothed_data = np.insert(smoothed_data, 0, subset[percentile].iloc[0])
style = '--' if 'Percentile' in percentile else '-'
ax.plot(keys_with_zero_n, smoothed_data, label=label if percentile == 'Mean_SR' else None,
linewidth=1 if 'Percentile' in percentile else 2, color=colors[i], linestyle=style)
if 'Percentile' in percentile:
ax.fill_between(keys_with_zero_n, subset['75th_Percentile_SR'], subset['25th_Percentile_SR'], color=colors[i], alpha=0.1)
ax.legend(fontsize=10, loc='lower right')
ax.set_xlabel('Number of Participants', fontsize=14)
ax.set_ylabel('Success Rate (%)', fontsize=14)
ax.grid(axis='y', linestyle='--', color='silver', alpha=1)
plt.xlim((0, 92))
plt.ylim((20, 100))
ax.set_axisbelow(True)
plt.tight_layout()
plt.show()
fig.savefig(output_file_path, dpi=300, bbox_inches='tight')
fig.savefig(output_file_path.replace(".png", ".svg"), dpi=300, bbox_inches='tight')
def compute_most_frequent(df, weighted=False):
weights = {1: 1/5, 2: 2/5, 3: 3/5, 4: 4/5, 5: 1}
# weights = {1: 0/5, 2: 1/5, 3: 2/5, 4: 3/5, 5: 1}
def weighted_most_frequent(group):
answers = group['Answer'].unique()
max_weighted_answer = None
max_weight = -np.inf
for answer in answers:
subset = group[group['Answer'] == answer]
if weighted:
weight_sum = (1 * subset['Certitude'].map(weights)).sum()
else:
weight_sum = len(subset)
if weight_sum > max_weight:
max_weight = weight_sum
max_weighted_answer = answer
return max_weighted_answer
group = df.groupby(['Chemist Group', 'Question']).apply(weighted_most_frequent).reset_index(name='Most_Frequent_Answer')
group = group.merge(df[['Question', 'Correct_Answer']].drop_duplicates(), on='Question', how='left')
group['Most_Frequent_Correct'] = (group['Most_Frequent_Answer'] == group['Correct_Answer']).astype(int)
return group
def compute_most_frequent_combined_weight(df):
def weighted_combined_most_frequent(group):
answers = group['Answer'].unique()
max_weighted_answer = None
max_weight = -np.inf
for answer in answers:
subset = group[group['Answer'] == answer]
weight_sum = ((subset['Certitude'] + subset['Chemist Level']) / 10).sum()
if weight_sum > max_weight:
max_weight = weight_sum
max_weighted_answer = answer
return max_weighted_answer
group = df.groupby(['Chemist Group', 'Question']).apply(weighted_combined_most_frequent).reset_index(name='Most_Frequent_Answer')
group = group.merge(df[['Question', 'Correct_Answer']].drop_duplicates(), on='Question', how='left')
group['Most_Frequent_Correct'] = (group['Most_Frequent_Answer'] == group['Correct_Answer']).astype(int)
return group
def plot_distribution_of_scores(df_A, df_B, output_file_path):
df_A['Result'] = np.where(df_A['Correct_Answer'] == df_A['Answer'], 1, 0)
df_B['Result'] = np.where(df_B['Correct_Answer'] == df_B['Answer'], 1, 0)
combined_scores = pd.concat([compute_scores(df_A), compute_scores(df_B)], ignore_index=True)
combined_scores_all = combined_scores.copy()
combined_scores_all["Chemist Level"] = 6
combined_scores = pd.concat([combined_scores_all, combined_scores])
df_A_all = df_A.copy()
df_A_all["Chemist Level"] = 6
df_A = pd.concat([df_A_all, df_A])
df_B_all = df_B.copy()
df_B_all["Chemist Level"] = 6
df_B = pd.concat([df_B_all, df_B])
df_A["Chemist Group"] = df_A["Chemist Level"].apply(assign_chemist_group)
df_B["Chemist Group"] = df_B["Chemist Level"].apply(assign_chemist_group)
combined_scores["Chemist Group"] = combined_scores["Chemist Level"].apply(assign_chemist_group)
most_frequent_combined = pd.concat([compute_most_frequent(df_A, False), compute_most_frequent(df_B, False)])
most_frequent_combined = most_frequent_combined[most_frequent_combined["Chemist Group"]==3]
most_frequent_combined = most_frequent_combined[["Question","Most_Frequent_Answer"]]
most_frequent_combined.columns = ["Slide_ID","Most_Frequent_Answer"]
most_frequent_combined["Slide_ID"] = [i.split("Q")[-1] for i in most_frequent_combined["Slide_ID"].tolist()]
most_frequent_combined.to_csv("./data/CollectiveIntelligence/CI_Answer_v3-Response_Most_Frequent.csv", index = False)
most_frequent_combined
# ... (Include other data processing steps here)
# Plotting logic
fig, ax = plt.subplots(figsize=(6, 5))
chemist_levels = sorted(df_A['Chemist Group'].unique())
colors = plt.cm.viridis(np.linspace(0, 1, len(chemist_levels)))
for i, level in enumerate(chemist_levels):
score_values = combined_scores[combined_scores['Chemist Group'] == level]['Score']
if score_values.empty:
continue
vp = ax.violinplot(score_values, positions=[i], widths=0.9, showextrema=False)
for pc_idx, pc in enumerate(vp['bodies']):
pc.set_facecolor(colors[i])
pc.set_alpha(0.7)
bp = ax.boxplot(score_values, positions=[i], patch_artist=True, notch=True, widths=0.2, whis=0.5,
flierprops={'marker': 'o', 'markersize': 4})
for box in bp['boxes']:
box.set(facecolor='darkgrey')
for median in bp['medians']:
median.set(color='black', linewidth=2)
# ... (Include your violin and boxplot logic here)
# Scatter plot for success rates
most_frequent_A = df_A.groupby(['Chemist Group', 'Question']).agg(lambda x: x.mode().iloc[0]).reset_index()
most_frequent_B = df_B.groupby(['Chemist Group', 'Question']).agg(lambda x: x.mode().iloc[0]).reset_index()
most_frequent_A['Most_Frequent_Correct'] = np.where(most_frequent_A['Correct_Answer'] == most_frequent_A['Answer'], 1, 0)
most_frequent_B['Most_Frequent_Correct'] = np.where(most_frequent_B['Correct_Answer'] == most_frequent_B['Answer'], 1, 0)
most_frequent_combined = pd.concat([most_frequent_A, most_frequent_B]) # Assuming most_frequent_A and most_frequent_B are calculated
most_frequent_combined = most_frequent_combined.groupby('Chemist Group').agg(
success_rate=pd.NamedAgg(column='Most_Frequent_Correct', aggfunc='mean')
).reset_index()
most_frequent_combined = most_frequent_combined.rename(columns={"success_rate": "SR"})
ax.scatter(most_frequent_combined['Chemist Group']-1, most_frequent_combined['SR'], color='white', edgecolor='black', linewidth=1.5, zorder=4, alpha=1, marker="o", s=80)
# Set axis labels, titles, and grid
ax.set_xlabel('Chemist Group', fontsize=14)
chemist_levels = ["Non-Expert", "Expert", "All"]
ax.set_xticklabels(chemist_levels)
ax.set_ylabel('Success Rate', fontsize=14)
ax.set_title('Distribution of Scores per Level', fontsize=16)
ax.grid(axis='y', linestyle='--', color='silver', alpha=1)
ax.set_axisbelow(True)
ax.set_ylim((0, 1))
plt.tight_layout()
plt.show()
fig.savefig(output_file_path, dpi=300, bbox_inches='tight')
def plot_distribution_of_scores_session(df_A, output_file_path):
df_A['Result'] = np.where(df_A['Correct_Answer'] == df_A['Answer'], 1, 0)
combined_scores = pd.concat([compute_scores(df_A)], ignore_index=True)
combined_scores_all = combined_scores.copy()
combined_scores_all["Chemist Level"] = 6
combined_scores = pd.concat([combined_scores_all, combined_scores])
df_A_all = df_A.copy()
df_A_all["Chemist Level"] = 6
df_A = pd.concat([df_A_all, df_A])
df_A["Chemist Group"] = df_A["Chemist Level"].apply(assign_chemist_group)
combined_scores["Chemist Group"] = combined_scores["Chemist Level"].apply(assign_chemist_group)
most_frequent_combined = pd.concat([compute_most_frequent(df_A, False)])
most_frequent_combined = most_frequent_combined[most_frequent_combined["Chemist Group"]==3]
most_frequent_combined = most_frequent_combined[["Question","Most_Frequent_Answer"]]
most_frequent_combined.columns = ["Slide_ID","Most_Frequent_Answer"]
most_frequent_combined["Slide_ID"] = [i.split("Q")[-1] for i in most_frequent_combined["Slide_ID"].tolist()]
most_frequent_combined.to_csv("./data/CollectiveIntelligence/CI_Answer_v3-Response_Most_Frequent.csv", index = False)
most_frequent_combined
# ... (Include other data processing steps here)
most_frequent_A = df_A.groupby(['Chemist Group', 'Question']).agg(lambda x: x.mode().iloc[0]).reset_index()
most_frequent_A['Most_Frequent_Correct'] = np.where(most_frequent_A['Correct_Answer'] == most_frequent_A['Answer'], 1, 0)
# Plotting logic
fig, ax = plt.subplots(figsize=(6, 5))
chemist_levels = sorted(df_A['Chemist Group'].unique())
colors = plt.cm.viridis(np.linspace(0, 1, len(chemist_levels)))
for i, level in enumerate(chemist_levels):
score_values = combined_scores[combined_scores['Chemist Group'] == level]['Score']
if score_values.empty:
continue
vp = ax.violinplot(score_values, positions=[i], widths=0.9, showextrema=False)
for pc_idx, pc in enumerate(vp['bodies']):
pc.set_facecolor(colors[i])
pc.set_alpha(0.7)
bp = ax.boxplot(score_values, positions=[i], patch_artist=True, notch=True, widths=0.2, whis=0.5,
flierprops={'marker': 'o', 'markersize': 4})
for box in bp['boxes']:
box.set(facecolor='darkgrey')
for median in bp['medians']:
median.set(color='black', linewidth=2)
# ... (Include your violin and boxplot logic here)
# Scatter plot for success rates
most_frequent_combined = pd.concat([most_frequent_A]) # Assuming most_frequent_A and most_frequent_B are calculated
most_frequent_combined = most_frequent_combined.groupby('Chemist Group').agg(
success_rate=pd.NamedAgg(column='Most_Frequent_Correct', aggfunc='mean')
).reset_index()
most_frequent_combined = most_frequent_combined.rename(columns={"success_rate": "SR"})
ax.scatter(most_frequent_combined['Chemist Group']-1, most_frequent_combined['SR'], color='white', edgecolor='black', linewidth=1.5, zorder=4, alpha=1, marker="o", s=80)
# Set axis labels, titles, and grid
ax.set_xlabel('Chemist Group', fontsize=14)
chemist_levels = ["Non-Expert", "Expert", "All"]
ax.set_xticklabels(chemist_levels)
ax.set_ylabel('Success Rate', fontsize=14)
ax.set_title('Distribution of Scores per Level', fontsize=16)
ax.grid(axis='y', linestyle='--', color='silver', alpha=1)
ax.set_axisbelow(True)
ax.set_ylim((0, 1))
plt.tight_layout()
plt.show()
fig.savefig(output_file_path, dpi=300, bbox_inches='tight')
def assign_chemist_group_S1A(level):
if level < 3:
return 1 # non-expert
elif level >=3 and level <= 5:
return 2 # expert
else:
return 3 # all
def assign_chemist_group_spe_S1B(level):
if level < 3:
return 1 # non-expert
elif level ==3:
return 2 # expert
elif level >4 and level <= 5:
return 3 # expert
else:
return 4 # all
def plot_success_rate_by_endpoint(csv_file_path_A, csv_file_path_B, output_file_path):
# Read the CSV files
df_A = pd.read_csv(csv_file_path_A, sep=',')
df_B = pd.read_csv(csv_file_path_B, sep=',')
df_B = remove_consistent_chemists(df_B)
df_A = remove_consistent_chemists(df_A)
df_A['Result'] = np.where(df_A['Correct_Answer'] == df_A['Answer'], 1, 0)
df_B['Result'] = np.where(df_B['Correct_Answer'] == df_B['Answer'], 1, 0)
df_A["Chemist Group"] = df_A["Chemist Level"].apply(assign_chemist_group)
df_B["Chemist Group"] = df_B["Chemist Level"].apply(assign_chemist_group)
# Combine both dataframes
combined_df = pd.concat([df_A, df_B])
combined_df = combined_df[combined_df['Certitude'].isna()!=True]
# Calculate success rate by endpoint for users
combined_df_expert = combined_df[combined_df["Chemist Group"] == 2]
user_success_rate_by_endpoint = combined_df.groupby(['Chemist', 'Endpoint'])['Result'].mean().reset_index()
user_success_rate_by_endpoint_expert = combined_df_expert.groupby(['Chemist', 'Endpoint'])['Result'].mean().reset_index()
user_success_rate_by_endpoint = user_success_rate_by_endpoint[user_success_rate_by_endpoint["Result"]!=0]
user_success_rate_by_endpoint_expert = user_success_rate_by_endpoint_expert[user_success_rate_by_endpoint_expert["Result"]!=0]
user_success_rate_by_endpoint = user_success_rate_by_endpoint.drop_duplicates()
user_success_rate_by_endpoint_expert = user_success_rate_by_endpoint_expert.drop_duplicates()
most_frequent_A_endpoint = df_A.groupby(['Endpoint',
'Question']).agg(lambda x: x.mode().iloc[0]).reset_index()
most_frequent_A_endpoint['Most_Frequent_Correct'] = np.where(most_frequent_A_endpoint['Correct_Answer'] == most_frequent_A_endpoint['Answer'], 1, 0)
most_frequent_B_endpoint = df_B.groupby(['Endpoint',
'Question']).agg(lambda x: x.mode().iloc[0]).reset_index()
most_frequent_B_endpoint['Most_Frequent_Correct'] = np.where(most_frequent_B_endpoint['Correct_Answer'] == most_frequent_B_endpoint['Answer'], 1, 0)
most_frequent_combined_endpoint = pd.concat([most_frequent_A_endpoint, most_frequent_B_endpoint])
most_frequent_success_rate_by_endpoint = most_frequent_combined_endpoint.groupby('Endpoint')['Most_Frequent_Correct'].mean().reset_index()
ordered_endpoints = ["LogP", "Permeability", "Solubility", "LogD", "hERG"][::-1]
colors = plt.cm.viridis(np.linspace(0, 1, len(ordered_endpoints)))
###
most_frequent_combined_weighted = pd.concat([compute_most_frequent_Endpoint(df_A, True),
compute_most_frequent_Endpoint(df_B, True)]).groupby('Endpoint')['Most_Frequent_Correct'].mean().reset_index(name='Most_Frequent_Correct')
most_frequent_combined_weighted_both = pd.concat([compute_most_frequent_combined_weight_Endpoint(df_A),
compute_most_frequent_combined_weight_Endpoint(df_B)]).groupby('Endpoint')['Most_Frequent_Correct'].mean().reset_index(name='Most_Frequent_Correct')
most_frequent_combined_weighted["Most_Frequent_Correct"]*=100
most_frequent_combined_weighted_both["Most_Frequent_Correct"]*=100
# Plotting
fig1, ax1 = plt.subplots(figsize=(5.5, 5))
ordered_endpoints = ["LogP", "Permeability", "Solubility", "LogD", "hERG"][::-1]
colors = plt.cm.viridis(np.linspace(0, 1, len(ordered_endpoints)))
colors = plt.get_cmap('Dark2').colors # Using colors from the Set3 colormap
ordered_endpoints=["LogP", "Permeability", "Solubility", "LogD", "hERG"][::-1]
for idx, endpoint in enumerate(ordered_endpoints):
data = user_success_rate_by_endpoint[user_success_rate_by_endpoint['Endpoint'] == endpoint]['Result']
data_expert = user_success_rate_by_endpoint_expert[user_success_rate_by_endpoint_expert['Endpoint'] == endpoint]['Result']
data*=100
data_expert*=100
vp = ax1.violinplot(data, positions=[idx], widths=0.5, showextrema=False)
for pc in vp['bodies']:
pc.set_facecolor(colors[idx])
pc.set_alpha(1)
bp = ax1.boxplot(data, positions=[idx], patch_artist=True, notch=True, widths=0.2, whis=0.5,
flierprops={'marker': 'o', 'markersize': 4})
for box in bp['boxes']:
box.set(facecolor='darkgrey')
for median in bp['medians']:
median.set(color='black', linewidth=2)
most_frequent_success_rate = most_frequent_success_rate_by_endpoint[most_frequent_success_rate_by_endpoint['Endpoint'] == endpoint]['Most_Frequent_Correct'].values[0]
most_frequent_success_rate_w = most_frequent_combined_weighted[most_frequent_combined_weighted['Endpoint'] == endpoint]['Most_Frequent_Correct'].values[0]
most_frequent_most_frequent_combined_weighted_both = most_frequent_combined_weighted_both[most_frequent_combined_weighted_both['Endpoint'] == endpoint]['Most_Frequent_Correct'].values[0]
most_frequent_success_rate = most_frequent_success_rate*100
ax1.scatter(idx, most_frequent_success_rate, color='white', edgecolor='black', linewidth=1.5, zorder=4, alpha=1, marker="o", s=80,
label='Collective Intelligence' if idx == 0 else "")
ax1.grid(axis='y', linestyle='--', color='silver', alpha=1)
ax1.set_axisbelow(True)
ax1.set_xticks(range(len(ordered_endpoints)))
ax1.set_xticklabels(ordered_endpoints, fontsize=10)
ax1.set_xlabel('ADMET Endpoint', fontsize=14)
ax1.set_ylabel('Success Rate (%)', fontsize=14)
ax1.set_ylim((0, 100))
ax1.legend(loc='upper left', fontsize=12, framealpha = 1)
plt.tight_layout()
fig1.savefig(output_file_path, dpi=300, bbox_inches='tight')
fig1.savefig(output_file_path.replace(".png",".svg"), dpi=300, bbox_inches='tight')
plt.show()
def plot_certitude_success_distribution_color(df, output_file_path):
# Process the DataFrame for plotting
df["Certitude"] = df["Certitude"].astype(str)
success_rate = df.groupby(['Chemist Level', 'Certitude'])['Result'].mean().reset_index(name='Success Rate')
bubble_data = df.groupby(['Chemist Level', 'Certitude']).size().reset_index(name='Counts')
bubble_data = bubble_data.merge(success_rate, on=['Chemist Level', 'Certitude'])
bubble_data["Success Rate"] = (bubble_data["Success Rate"] * 100).astype(int)
# Normalize success rate for color mapping between 0 and 100
norm = Normalize(vmin=20, vmax=80)
# Create the plot
fig, ax = plt.subplots(figsize=(6, 5))
scatter = ax.scatter(bubble_data['Chemist Level'], bubble_data['Certitude'],
s=bubble_data['Counts'] * 2, alpha=1, c=bubble_data['Success Rate'],
edgecolors='k', linewidth=1, cmap='RdYlGn', norm=norm)
# Set labels and title
ax.set_xlabel('Expertise', fontsize=14)
ax.set_ylabel('Confidence', fontsize=14)
# Create color bar
cbar = plt.colorbar(scatter, ax=ax)
cbar.set_label('Success Rate (%)', fontsize=14)
cbar.set_ticks(np.arange(20, 81, 10)) # Setting ticks at regular intervals
# Show and save the plot
fig.savefig(output_file_path, dpi=300, bbox_inches='tight')
fig.savefig(output_file_path.replace(".png",".svg"), dpi=300, bbox_inches='tight')
plt.show()
def plot_aggregation_S7(ax, csv_file_path, name_agg, admet, i, j):
df_t = pd.read_csv(csv_file_path)
dt_all = df_t.copy()
dt_all['Mean_SR']*=100
dt_all['25th_Percentile_SR']*=100
dt_all['75th_Percentile_SR']*=100
dt_all['25th_Percentile_SR'] = dt_all['Mean_SR'] - abs(dt_all['25th_Percentile_SR'] - dt_all['Mean_SR'])/2
dt_all['75th_Percentile_SR'] = dt_all['Mean_SR'] + abs(dt_all['25th_Percentile_SR'] - dt_all['Mean_SR'])/2
dt_all['25th_Percentile_SR'].fillna(dt_all['Mean_SR'], inplace=True)
dt_all['75th_Percentile_SR'].fillna(dt_all['Mean_SR'], inplace=True)
chemist_groups = list(set(list(dt_all["Chemist Group"])))
for unique_group in chemist_groups:
group_df = dt_all[dt_all["Chemist Group"] == unique_group]
group_df = group_df[group_df["Key"]==20]
colors = plt.cm.brg(np.linspace(0., 1, len(chemist_groups)))
# plt.style.use('ggplot')
plt.style.use('default')
# Darken the colors
colors =['#94568c', '#65ab7c', '#2976bb']
colors =['#8e0052', '#276319', '#6f9fc7']
k = 0
for group in chemist_groups:
subset = dt_all[dt_all['Chemist Group'] == group]
subset = subset.drop_duplicates("Key")
keys_with_zero_n = np.insert([ik+1 for ik in range(len(subset))], 0, 0)
label = {1: "Non Expert (1-2)", 2: "Expert (3-5)", 3: "All"}.get(group)
smoothed_data = scipy.ndimage.filters.gaussian_filter1d(subset['Mean_SR'], sigma=1)
smoothed_data = np.insert(smoothed_data, 0, subset["Mean_SR"].tolist()[0])
ax.plot(keys_with_zero_n, smoothed_data, label=label, linewidth=2, color=colors[k])
smoothed_data_up = scipy.ndimage.filters.gaussian_filter1d(subset['75th_Percentile_SR'], sigma=1)
smoothed_data_up = np.insert(smoothed_data_up, 0, subset["Mean_SR"].tolist()[0])
ax.plot(keys_with_zero_n, smoothed_data_up, linewidth=1, color=colors[k], linestyle='--')
smoothed_data_down = scipy.ndimage.filters.gaussian_filter1d(subset['25th_Percentile_SR'], sigma=1)
smoothed_data_down = np.insert(smoothed_data_down, 0, subset["Mean_SR"].tolist()[0])
ax.plot(keys_with_zero_n, smoothed_data_down, linewidth=1, color=colors[k], linestyle='--')
ax.fill_between(keys_with_zero_n, smoothed_data_up, smoothed_data_down, color=colors[k], alpha=0.1)
k += 1
# Set x-axis label only for the last row
if i == 5: # assuming 6 rows, adjust as needed
ax.set_xlabel('Number of participants', fontsize=14)
d_a = {"most_frequent":"Most Frequent",
"log_odds":"Log Odds",
"weighted_by_certitude":"Weighted By Certitude",
"weighted_by_certitude_and_expertise":"Weighted By Certitude & Expertise",
"weighted_by_expertise":"Weighted By Expertise",
"fuzzy_logic_aggregation":"Fuzzy Logic Aggregation"}
# Set y-axis label only for the first column
ax.set_title(d_a[name_agg], fontsize=14)
# Set x-axis label only for the last row
if j == 0: # assuming 6 rows, adjust as needed
ax.set_ylabel("Success Rate (%)", fontsize=14)
# Set y-axis label only for the first column
# if j == 0:
# ax.set_ylabel('Success Rate (%)', fontsize=14)
ax.grid(axis='y', linestyle='--', color='silver', alpha=1)
ax.set_xlim((0, 92))
if 'LogP' in admet:
ax.set_ylim(30, 100)
else:
ax.set_ylim(20, 70)
ax.set_axisbelow(True)
# plt.tight_layout()
# plt.show()
# fig.savefig(output_file_path, dpi=300, bbox_inches='tight')
return ax
def plot_distribution_of_scores_fig1c(df_A, df_B, output_file_path):
df_B = remove_consistent_chemists(df_B)
df_A = remove_consistent_chemists(df_A)
df_A['Result'] = np.where(df_A['Correct_Answer'] == df_A['Answer'], 1, 0)
df_B['Result'] = np.where(df_B['Correct_Answer'] == df_B['Answer'], 1, 0)
combined_scores = pd.concat([compute_scores(df_A), compute_scores(df_B)], ignore_index=True)
combined_scores_all = combined_scores.copy()
combined_scores_all["Chemist Level"] = 6
combined_scores = pd.concat([combined_scores_all, combined_scores])
df_A_all = df_A.copy()
df_A_all["Chemist Level"] = 6
df_A = pd.concat([df_A_all, df_A])
df_B_all = df_B.copy()
df_B_all["Chemist Level"] = 6
df_B = pd.concat([df_B_all, df_B])
df_A["Chemist Group"] = df_A["Chemist Level"].tolist()
df_B["Chemist Group"] = df_B["Chemist Level"].tolist()
combined_scores["Chemist Group"] = combined_scores["Chemist Level"].tolist()
most_frequent_combined = pd.concat([compute_most_frequent(df_A, False), compute_most_frequent(df_B, False)])
most_frequent_combined = most_frequent_combined[most_frequent_combined["Chemist Group"]==3]
most_frequent_combined = most_frequent_combined[["Question","Most_Frequent_Answer"]]
most_frequent_combined.columns = ["Slide_ID","Most_Frequent_Answer"]
most_frequent_combined["Slide_ID"] = [i.split("Q")[-1] for i in most_frequent_combined["Slide_ID"].tolist()]
most_frequent_combined.to_csv("./data/CollectiveIntelligence/CI_Answer_v3-Response_Most_Frequent.csv", index = False)
most_frequent_combined
# Plotting logic
fig, ax = plt.subplots(figsize=(5.5, 5))
chemist_levels = sorted(df_A['Chemist Group'].unique())
# Custom colors: PiYG for Non-Expert and Expert, specific color for All
colors = plt.get_cmap('PiYG')(np.linspace(0., 1, len(chemist_levels) - 1)).tolist()
colors.append('#2976bb') # Adding the specific color for the 'All' group
add_label = True
colors[2] = [0.85, 0.85, 0.85, 1] # Dark grey color with full opacity
# Scatter plot for success rates
most_frequent_A = df_A.groupby(['Chemist Group', 'Question']).agg(lambda x: x.mode().iloc[0]).reset_index()
most_frequent_B = df_B.groupby(['Chemist Group', 'Question']).agg(lambda x: x.mode().iloc[0]).reset_index()
most_frequent_A['Most_Frequent_Correct'] = np.where(most_frequent_A['Correct_Answer'] == most_frequent_A['Answer'], 1, 0)
most_frequent_B['Most_Frequent_Correct'] = np.where(most_frequent_B['Correct_Answer'] == most_frequent_B['Answer'], 1, 0)
most_frequent_combined = pd.concat([most_frequent_A, most_frequent_B]) # Assuming most_frequent_A and most_frequent_B are calculated
most_frequent_combined = most_frequent_combined.groupby('Chemist Group').agg(
success_rate=pd.NamedAgg(column='Most_Frequent_Correct', aggfunc='mean')
).reset_index()
most_frequent_combined = most_frequent_combined.rename(columns={"success_rate": "SR"})
for i, level in enumerate(chemist_levels):
score_values = combined_scores[combined_scores['Chemist Group'] == level]['Score']
score_values *=100
if score_values.empty:
continue
vp = ax.violinplot(score_values, positions=[i], widths=0.9, showextrema=False)
for pc_idx, pc in enumerate(vp['bodies']):
pc.set_facecolor(colors[i])
pc.set_alpha(1)
bp = ax.boxplot(score_values, positions=[i], patch_artist=True, notch=True, widths=0.2, whis=0.5,
flierprops={'marker': 'o', 'markersize': 4})
for box in bp['boxes']:
box.set(facecolor='darkgrey')
for median in bp['medians']:
median.set(color='black', linewidth=2)
# Scatter plot for success rates
if add_label: # Adding label only for the first scatter plot
scatter_label = 'Collective Intelligence'
add_label = False # Reset the flag so the label is not added again
else:
scatter_label = None
most_frequent_combined = pd.concat([most_frequent_A, most_frequent_B])
most_frequent_combined = most_frequent_combined.groupby('Chemist Group').agg(
success_rate=pd.NamedAgg(column='Most_Frequent_Correct', aggfunc='mean')
).reset_index()
most_frequent_combined = most_frequent_combined.rename(columns={"success_rate": "SR"})
ax.scatter(most_frequent_combined['Chemist Group']-1, most_frequent_combined['SR']*100,
color='white', edgecolor='black', linewidth=1.5, zorder=4, alpha=1,
marker="o", s=80, label=scatter_label)
ax.scatter(most_frequent_combined['Chemist Group']-1, most_frequent_combined['SR']*100, color='white',
label='Collective Intelligence' if i == 0 else "",
edgecolor='black', linewidth=1.5, zorder=4, alpha=1, marker="o", s=80)
# Set axis labels, titles, and grid
ax.set_xlabel('Expertise', fontsize=14)
chemist_levels = ["Non-Expert (1-2)", "Expert (3-5)", "All"]
ax.set_xticklabels(["1","2","3","4","5","All"])
ax.set_ylabel('Success Rate (%)', fontsize=14)
ax.grid(axis='y', linestyle='--', color='silver', alpha=1)
ax.set_axisbelow(True)
ax.set_ylim((0, 100))
ax.legend(loc='upper left', fontsize=12, framealpha = 1)
plt.tight_layout()
fig.savefig(output_file_path, dpi=300, bbox_inches='tight')
fig.savefig(output_file_path.replace(".png",".svg"), dpi=300, bbox_inches='tight')
plt.show()
def plot_distribution_of_scores_S1B(df_A, df_B, output_file_path):
df_B = remove_consistent_chemists(df_B)
df_A = remove_consistent_chemists(df_A)
df_A['Result'] = np.where(df_A['Correct_Answer'] == df_A['Answer'], 1, 0)
df_B['Result'] = np.where(df_B['Correct_Answer'] == df_B['Answer'], 1, 0)
combined_scores = pd.concat([compute_scores(df_A), compute_scores(df_B)], ignore_index=True)
combined_scores_all = combined_scores.copy()
combined_scores_all["Chemist Level"] = 6
combined_scores = pd.concat([combined_scores_all, combined_scores])
df_A_all = df_A.copy()
df_A_all["Chemist Level"] = 6
df_A = pd.concat([df_A_all, df_A])
df_B_all = df_B.copy()
df_B_all["Chemist Level"] = 6
df_B = pd.concat([df_B_all, df_B])
df_A["Chemist Group"] = df_A["Chemist Level"].apply(assign_chemist_group_spe_S1B)
df_B["Chemist Group"] = df_B["Chemist Level"].apply(assign_chemist_group_spe_S1B)
combined_scores["Chemist Group"] = combined_scores["Chemist Level"].apply(assign_chemist_group_spe_S1B)
most_frequent_combined = pd.concat([compute_most_frequent(df_A, False), compute_most_frequent(df_B, False)])
most_frequent_combined = most_frequent_combined[most_frequent_combined["Chemist Group"]==3]
most_frequent_combined = most_frequent_combined[["Question","Most_Frequent_Answer"]]
most_frequent_combined.columns = ["Slide_ID","Most_Frequent_Answer"]
most_frequent_combined["Slide_ID"] = [i.split("Q")[-1] for i in most_frequent_combined["Slide_ID"].tolist()]
most_frequent_combined.to_csv("./data/CollectiveIntelligence/CI_Answer_v3-Response_Most_Frequent.csv", index = False)
most_frequent_combined
# Plotting logic
fig, ax = plt.subplots(figsize=(5.5, 5))
chemist_levels = sorted(df_A['Chemist Group'].unique())
# Custom colors: PiYG for Non-Expert and Expert, specific color for All
colors = plt.get_cmap('PiYG')(np.linspace(0., 1, len(chemist_levels) - 1)).tolist()