-
Notifications
You must be signed in to change notification settings - Fork 2
/
study_stats_utils.py
195 lines (140 loc) · 7.24 KB
/
study_stats_utils.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
from bisect import bisect_left
import itertools
import pandas as pd
import numpy as np
from scipy import stats
import itertools
def check_all_identical(arrays):
"""
We define a function to check if all the given groups have identical values, which means we do not even have to run a statistical test.
"""
return all([np.array_equal(x, y) for x, y in itertools.combinations(arrays, 2)])
def multiple_groups_test_dataframe(dataframe, group_1, group_2, metrics, testfunc, check_identical=True):
"""
We define a function that builds a dataframe with the statistical tests results, based on two levels of grouping.
"""
group_1 = group_1 if isinstance(group_1, (tuple, list)) else [group_1]
# Create the result dataframe.
test_df = pd.DataFrame(columns=group_1 + ['metric', 'pvalue'])
# For each of the groups defined by "group_1", execute the test between samples defined by "group_2", for each of the metrics.
for name, group in dataframe.groupby(group_1):
name = name if isinstance(name, (tuple, list)) else [name]
for metric in metrics:
# Extract the samples.
samples = [_group[metric].values for _name, _group in group.groupby(group_2) if len(_group) > 0]
# Check if all the observations are equal between groups.
if check_identical and check_all_identical(samples):
pvalue = 1.0
else:
# Apply the test function to the groups.
_, pvalue = testfunc(*samples)
# Store the result.
test_df = test_df.append({
**{key: value for key, value in zip(group_1, name)},
**{'metric': metric, 'pvalue': pvalue}
}, ignore_index=True)
# Return the dataframe.
return test_df
def pairwise_multiple_groups_posthoc_test_dataframe(dataframe, group_1, group_2, metrics, testfunc):
"""
We define a function that build a dataframe with the statistical pairwise tests results, based on two levels of grouping.
"""
group_1 = group_1 if isinstance(group_1, (tuple, list)) else [group_1]
# Create the result dataframe.
test_df = pd.DataFrame(columns=group_1 + ['metric'] + [group_2] + ['comparison', 'pvalue'])
# For each of the groups defined by "group_1", execute the pairwise test between samples defined by "group_2", for each of the metrics.
for name, group in dataframe.groupby(group_1):
# Exclude empty groups.
if len(group) == 0:
continue
name = name if isinstance(name, (tuple, list)) else [name]
d_1 = {key: value for key, value in zip(group_1, name)}
for metric in metrics:
d_2 = {'metric': metric}
# Get the pairwise matrix of p-values.
pvalues = testfunc(group, val_col=metric, group_col=group_2)
# Transform the matrix dataframe into a long version.
pvalues_long = pvalues.unstack().reset_index()
pvalues_long.columns = ['first', 'second', 'value']
# Put -1 on the diagonal.
pvalues_long['value'] = np.where(pvalues_long['first'] == pvalues_long['second'], -1, pvalues_long['value'])
# Store the result composing the row for the dataframe.
for _, row in pvalues_long.iterrows():
test_df = test_df.append({
**d_1,
**d_2,
**{group_2: row['first'], 'comparison': row['second'], 'pvalue': row['value']},
}, ignore_index=True)
# Return the dataframe.
return test_df
def pairwise_multiple_groups_test_dataframe(dataframe, group_1, group_2, metrics, testfunc, check_identical=True):
"""
We define a function that build a dataframe with the statistical pairwise tests results, based on two levels of grouping.
"""
group_1 = group_1 if isinstance(group_1, (tuple, list)) else [group_1]
# Create the result dataframe.
test_df = pd.DataFrame(columns=group_1 + ['metric'] + [group_2] + ['comparison', 'pvalue'])
# For each of the groups defined by "group_1", execute the pairwise test between samples defined by "group_2", for each of the metrics.
for name, group in dataframe.groupby(group_1):
# Exclude empty groups.
if len(group) == 0:
continue
name = name if isinstance(name, (tuple, list)) else [name]
d_1 = {key: value for key, value in zip(group_1, name)}
for metric in metrics:
d_2 = {'metric': metric}
for x, y in itertools.product([(_name, _group[metric].values) for _name, _group in group.groupby(group_2) if len(_group) > 0], repeat=2):
# Check if all the observations are equal between groups.
if check_identical and check_all_identical([x[1], y[1]]):
pvalue = 1.0
else:
# Apply the test function to the groups.
_, pvalue = testfunc(x[1], y[1])
# Store the result composing the row for the dataframe.
test_df = test_df.append({
**d_1,
**d_2,
**{group_2: x[0], 'comparison': y[0], 'pvalue': pvalue},
}, ignore_index=True)
# Return the dataframe.
return test_df
def vargha_delaney(x, y):
x = x.tolist() if isinstance(x, (pd.Series, np.ndarray)) else x
y = y.tolist() if isinstance(y, (pd.Series, np.ndarray)) else y
# Compute the size of the samples.
n1, n2 = len(x), len(y)
# Assign ranks to data.
r = stats.rankdata(x + y)
r1 = sum(r[0:n1])
# Compute the effect size.
a = (2 * r1 - n1 * (n1 + 1)) / (2 * n2 * n1)
# Compute magnitude.
levels = [0.147, 0.33, 0.474]
magnitude = ['negligible', 'small', 'medium', 'large']
scaled_a = (a - 0.5) * 2
magnitude = magnitude[bisect_left(levels, abs(scaled_a))]
# Return the results.
return a, magnitude
def pairwise_multiple_groups_vda_dataframe(dataframe, group_1, group_2, metrics):
group_1 = group_1 if isinstance(group_1, (tuple, list)) else [group_1]
# Create the result dataframe.
test_df = pd.DataFrame(columns=group_1 + ['metric'] + [group_2] + ['comparison', 'a', 'magnitude'])
# For each of the groups defined by "group_1", execute the pairwise test between samples defined by "group_2", for each of the metrics.
for name, group in dataframe.groupby(group_1):
# Exclude empty groups.
if len(group) == 0:
continue
name = name if isinstance(name, (tuple, list)) else [name]
d_1 = {key: value for key, value in zip(group_1, name)}
for metric in metrics:
d_2 = {'metric': metric}
for x, y in itertools.product([(_name, _group[metric].values) for _name, _group in group.groupby(group_2) if len(_group) > 0], repeat=2):
a, magnitude = vargha_delaney(x[1], y[1])
# Store the result composing the row for the dataframe.
test_df = test_df.append({
**d_1,
**d_2,
**{group_2: x[0], 'comparison': y[0], 'a': a, 'magnitude': magnitude},
}, ignore_index=True)
# Return the dataframe.
return test_df