ABalytics 3.0.4__tar.gz → 4.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: abalytics
3
- Version: 3.0.4
3
+ Version: 4.0.1
4
4
  Summary: Advanced A/B Testing Statistical Analytics
5
5
  Author: Janis Berneker
6
6
  License: LICENSE
@@ -8,12 +8,21 @@ Project-URL: Repository, https://github.com/BigBerny/abalytics
8
8
  Requires-Python: >=3.8
9
9
  Description-Content-Type: text/markdown
10
10
  License-File: LICENSE
11
- Requires-Dist: pandas>=1.5.2
12
- Requires-Dist: scipy>=1.10.1
13
- Requires-Dist: statsmodels>=0.14.1
14
- Requires-Dist: scikit-posthocs>=0.8.1
15
- Requires-Dist: pingouin>=0.5.4
11
+ Requires-Dist: pandas>=2.2.0
12
+ Requires-Dist: scipy>=1.12.0
13
+ Requires-Dist: statsmodels>=0.14.6
14
+ Requires-Dist: scikit-posthocs>=0.12.0
15
+ Requires-Dist: pingouin>=0.5.5
16
16
  Requires-Dist: tabulate>=0.9.0
17
+ Dynamic: author
18
+ Dynamic: description
19
+ Dynamic: description-content-type
20
+ Dynamic: license
21
+ Dynamic: license-file
22
+ Dynamic: project-url
23
+ Dynamic: requires-dist
24
+ Dynamic: requires-python
25
+ Dynamic: summary
17
26
 
18
27
  # ABalytics: Advanced A/B Testing Statistical Analytics
19
28
 
@@ -1,3 +1,4 @@
1
+ import warnings
1
2
  from typing import Optional, List
2
3
 
3
4
  import pandas as pd
@@ -8,6 +9,7 @@ from .significance_tests import (
8
9
  is_numeric,
9
10
  is_levene_significant,
10
11
  is_gaussian,
12
+ are_differences_gaussian,
11
13
  get_chi_square_significance,
12
14
  get_chi_square_posthoc_results,
13
15
  get_welch_anova_significance,
@@ -16,6 +18,7 @@ from .significance_tests import (
16
18
  get_games_howell_posthoc_results,
17
19
  get_tukeyhsd_posthoc_results,
18
20
  get_dunn_posthoc_results,
21
+ get_cochrans_q_significance,
19
22
  get_mcnemar_results,
20
23
  get_repeated_measures_anova_significance,
21
24
  get_repeated_measures_anova_posthoc_results,
@@ -83,24 +86,27 @@ def analyze_independent_groups(
83
86
  - gaussian_flag: A boolean flag indicating if the data has a Gaussian distribution.
84
87
  """
85
88
  if p_value_threshold > 0.05:
86
- print(
87
- "Warning: p_value_threshold is set to a value higher than the conventional alpha level of 0.05."
89
+ warnings.warn(
90
+ "p_value_threshold is set to a value higher than the conventional alpha level of 0.05.",
91
+ UserWarning,
92
+ stacklevel=2,
88
93
  )
89
94
 
90
95
  if variable_to_analyze not in df.columns or group_column not in df.columns:
91
- print(
92
- f"Both columns {variable_to_analyze} and {group_column} have to be present in the DataFrame."
96
+ raise ValueError(
97
+ f"Both columns '{variable_to_analyze}' and '{group_column}' must be present in the DataFrame."
93
98
  )
94
- return None
95
99
 
96
100
  df = df.dropna(subset=[variable_to_analyze])
97
101
  sample_size = len(df)
98
102
  pvalue = None
99
103
  info = None
100
104
  a_priori_test = None
105
+ results = None
101
106
  dichotomous_flag = False
102
107
  levene_flag = None
103
108
  gaussian_flag = None
109
+
104
110
  # Check if any group has less than the minimum sample size
105
111
  if (
106
112
  df.groupby(group_column)[variable_to_analyze]
@@ -109,8 +115,8 @@ def analyze_independent_groups(
109
115
  ):
110
116
  info = "not enough data"
111
117
  # Check if the variable is dichotomous (e.g. boolean)
112
- elif dichotomous_flag := is_dichotomous(df, variable_to_analyze):
113
- # Perform chi-square test
118
+ elif is_dichotomous(df, variable_to_analyze):
119
+ dichotomous_flag = True
114
120
  pvalue = get_chi_square_significance(df, group_column, variable_to_analyze)
115
121
  a_priori_test = f"Chi-square, p-value = {pvalue:.3f}"
116
122
  if pvalue < p_value_threshold:
@@ -118,29 +124,39 @@ def analyze_independent_groups(
118
124
  df, group_column, variable_to_analyze, p_value_threshold
119
125
  )
120
126
  elif is_numeric(df, variable_to_analyze):
121
- # Check homogeneity of variances. If significant, use non-parametric tests
122
- if levene_flag := is_levene_significant(
123
- df, group_column, variable_to_analyze, p_value_threshold
124
- ):
125
- pvalue = get_welch_anova_significance(df, group_column, variable_to_analyze)
126
- a_priori_test = f"Welch's ANOVA, p-value = {pvalue:.3f}"
127
- if pvalue < p_value_threshold:
128
- results = get_games_howell_posthoc_results(
129
- df, group_column, variable_to_analyze, p_value_threshold
130
- )
131
- # Check if the data has Gaussian distribution, if not use non-parametric tests
132
- elif gaussian_flag := is_gaussian(
127
+ # Step 1: Check normality first
128
+ gaussian_flag = is_gaussian(
133
129
  df, variable_to_analyze, p_value_threshold, group_column
134
- ):
135
- pvalue = get_oneway_anova_significance(
136
- df, group_column, variable_to_analyze
130
+ )
131
+
132
+ if gaussian_flag:
133
+ # Data is normal — check variance homogeneity
134
+ levene_flag = is_levene_significant(
135
+ df, group_column, variable_to_analyze, p_value_threshold
137
136
  )
138
- a_priori_test = f"One-way ANOVA, p-value = {pvalue:.3f}"
139
- if pvalue < p_value_threshold:
140
- results = get_tukeyhsd_posthoc_results(
141
- df, group_column, variable_to_analyze, p_value_threshold
137
+
138
+ if levene_flag:
139
+ # Normal but unequal variances — Welch's ANOVA + Games-Howell
140
+ pvalue = get_welch_anova_significance(
141
+ df, group_column, variable_to_analyze
142
+ )
143
+ a_priori_test = f"Welch's ANOVA, p-value = {pvalue:.3f}"
144
+ if pvalue < p_value_threshold:
145
+ results = get_games_howell_posthoc_results(
146
+ df, group_column, variable_to_analyze, p_value_threshold
147
+ )
148
+ else:
149
+ # Normal and equal variances — One-way ANOVA + Tukey HSD
150
+ pvalue = get_oneway_anova_significance(
151
+ df, group_column, variable_to_analyze
142
152
  )
153
+ a_priori_test = f"One-way ANOVA, p-value = {pvalue:.3f}"
154
+ if pvalue < p_value_threshold:
155
+ results = get_tukeyhsd_posthoc_results(
156
+ df, group_column, variable_to_analyze, p_value_threshold
157
+ )
143
158
  else:
159
+ # Non-normal — non-parametric regardless of variance
144
160
  pvalue = get_kruskal_wallis_significance(
145
161
  df, group_column, variable_to_analyze
146
162
  )
@@ -150,18 +166,16 @@ def analyze_independent_groups(
150
166
  df, group_column, variable_to_analyze, p_value_threshold
151
167
  )
152
168
  else:
153
- print("Variable has to be dichotomous (e.g. boolean) or numeric")
154
- info = "Variable has to be dichotomous (e.g. boolean) or numeric"
169
+ raise ValueError(
170
+ f"Variable '{variable_to_analyze}' must be dichotomous (e.g. boolean) or numeric."
171
+ )
155
172
 
156
173
  # If no results were found, return a message
157
- if not "results" in locals() or len(results.significant_results) == 0:
174
+ if results is None or len(results.significant_results) == 0:
158
175
  if pvalue is not None:
159
- info = f"n.s. (p={pvalue:.3f})"
160
- # If results were found, return them
161
- if "results" in locals():
162
- significant_results = results.significant_results
163
- else:
164
- significant_results = []
176
+ info = f"not significant (p={pvalue:.3f})"
177
+
178
+ significant_results = results.significant_results if results else []
165
179
 
166
180
  return AnalysisResults(
167
181
  significant_results=significant_results,
@@ -199,21 +213,25 @@ def analyze_dependent_groups(
199
213
  - gaussian_flag: A boolean flag indicating if the data has a Gaussian distribution.
200
214
  """
201
215
  if p_value_threshold > 0.05:
202
- print(
203
- "Warning: p_value_threshold is set to a value higher than the conventional alpha level of 0.05."
216
+ warnings.warn(
217
+ "p_value_threshold is set to a value higher than the conventional alpha level of 0.05.",
218
+ UserWarning,
219
+ stacklevel=2,
204
220
  )
205
221
 
206
222
  missing_columns = [
207
223
  variable for variable in variables_to_compare if variable not in df.columns
208
224
  ]
209
225
  if missing_columns:
210
- print(f"Columns not found in DataFrame: {', '.join(missing_columns)}")
211
- return None
226
+ raise ValueError(
227
+ f"Columns not found in DataFrame: {', '.join(missing_columns)}"
228
+ )
212
229
 
213
230
  df = df.dropna(subset=variables_to_compare)
214
231
  sample_size = len(df)
215
232
  pvalue = None
216
233
  info = None
234
+ a_priori_test = None
217
235
  dichotomous_flag = False
218
236
  levene_flag = False
219
237
  gaussian_flag = False
@@ -225,19 +243,29 @@ def analyze_dependent_groups(
225
243
  # Check if the variables are dichotomous (e.g. boolean)
226
244
  elif all(is_dichotomous(df, variable) for variable in variables_to_compare):
227
245
  dichotomous_flag = True
228
- # Perform McNemar's test or its extension for more than two groups
229
- pvalue, results = get_mcnemar_results(
246
+ if len(variables_to_compare) > 2:
247
+ # Use Cochran's Q as omnibus test, then McNemar posthoc
248
+ pvalue = get_cochrans_q_significance(df, variables_to_compare)
249
+ a_priori_test = f"Cochran's Q, p-value = {pvalue:.3f}"
250
+ if pvalue < p_value_threshold:
251
+ _, results = get_mcnemar_results(
252
+ df, variables_to_compare, p_value_threshold
253
+ )
254
+ else:
255
+ # Two variables: McNemar directly
256
+ pvalue, results = get_mcnemar_results(
257
+ df, variables_to_compare, p_value_threshold
258
+ )
259
+ a_priori_test = f"McNemar, p-value = {pvalue:.3f}"
260
+ elif all(is_numeric(df, variable) for variable in variables_to_compare):
261
+ # Check if pairwise differences follow a Gaussian distribution
262
+ gaussian_flag = are_differences_gaussian(
230
263
  df, variables_to_compare, p_value_threshold
231
264
  )
232
- elif all(is_numeric(df, variable) for variable in variables_to_compare):
233
- # Check if the data has Gaussian distribution, if not use non-parametric tests
234
- if gaussian_flag := all(
235
- is_gaussian(df, variable, p_value_threshold)
236
- for variable in variables_to_compare
237
- ):
265
+ if gaussian_flag:
238
266
  pvalue = get_repeated_measures_anova_significance(df, variables_to_compare)
267
+ a_priori_test = f"Repeated measures ANOVA, p-value = {pvalue:.3f}"
239
268
  if pvalue < p_value_threshold:
240
- info = f"A priori test: Repeated measures ANOVA, p-value = {pvalue:.3f}"
241
269
  results = get_repeated_measures_anova_posthoc_results(
242
270
  df, variables_to_compare, p_value_threshold
243
271
  )
@@ -245,27 +273,30 @@ def analyze_dependent_groups(
245
273
  pvalue, results = get_wilcoxon_results(
246
274
  df, variables_to_compare, p_value_threshold
247
275
  )
276
+ a_priori_test = f"Wilcoxon, p-value = {pvalue:.3f}"
248
277
  else:
249
278
  pvalue = get_friedman_significance(df, variables_to_compare)
279
+ a_priori_test = f"Friedman, p-value = {pvalue:.3f}"
250
280
  if pvalue < p_value_threshold:
251
- info = f"A priori test: Friedman, p-value = {pvalue:.3f}"
252
281
  results = get_nemenyi_results(
253
282
  df, variables_to_compare, p_value_threshold
254
283
  )
255
284
  else:
256
- print("All variables have to be dichotomous (e.g. boolean) or numeric")
257
- info = "All variables have to be dichotomous (e.g. boolean) or numeric"
285
+ raise ValueError(
286
+ "All variables must be dichotomous (e.g. boolean) or numeric."
287
+ )
258
288
 
259
289
  # If no results were found, return a message
260
290
  if not results or len(results.significant_results) == 0:
261
291
  if pvalue is not None:
262
292
  info = f"not significant (p={pvalue:.3f})"
263
- # If results were found, return them
293
+
264
294
  significant_results = results.significant_results if results else []
265
295
 
266
296
  return AnalysisResults(
267
297
  significant_results=significant_results,
268
298
  info=info,
299
+ a_priori_test=a_priori_test,
269
300
  sample_size=sample_size,
270
301
  dichotomous_flag=dichotomous_flag,
271
302
  levene_flag=levene_flag,
@@ -5,19 +5,19 @@ from typing import List, Optional
5
5
  from typing import Tuple
6
6
 
7
7
  import pandas as pd
8
- from pingouin import pairwise_gameshowell, welch_anova
8
+ from pingouin import pairwise_gameshowell, rm_anova, welch_anova
9
9
  from pydantic import BaseModel
10
10
  from scikit_posthocs import posthoc_dunn, posthoc_nemenyi_friedman
11
11
  from scipy import stats
12
12
  from scipy.stats import (
13
13
  normaltest,
14
14
  chi2_contingency,
15
+ fisher_exact,
15
16
  wilcoxon,
16
17
  friedmanchisquare,
17
18
  )
18
19
  from statsmodels.sandbox.stats.multicomp import multipletests
19
- from statsmodels.stats.anova import AnovaRM
20
- from statsmodels.stats.contingency_tables import mcnemar
20
+ from statsmodels.stats.contingency_tables import cochrans_q, mcnemar
21
21
  from statsmodels.stats.multicomp import pairwise_tukeyhsd
22
22
  from statsmodels.stats.proportion import proportions_ztest
23
23
 
@@ -79,21 +79,46 @@ def is_gaussian(
79
79
  p_value_threshold: float,
80
80
  group_column: str = None,
81
81
  ) -> bool:
82
- """Check if a variable or grouped variables in a DataFrame follow a Gaussian distribution."""
82
+ """Check if a variable or grouped variables in a DataFrame follow a Gaussian distribution.
83
+ Returns False for samples with n < 20 as a conservative policy choice:
84
+ normality tests are unreliable with small samples, so we default to non-parametric."""
85
+ MIN_NORMALTEST_N = 20
86
+
83
87
  if group_column:
84
- return all(
85
- normaltest(df[df[group_column] == group][variable])[1] >= p_value_threshold
86
- for group in df[group_column].unique()
87
- )
88
- return normaltest(df[variable])[1] >= p_value_threshold
88
+ for group in df[group_column].unique():
89
+ group_data = df[df[group_column] == group][variable].dropna()
90
+ if len(group_data) < MIN_NORMALTEST_N:
91
+ return False
92
+ if normaltest(group_data)[1] < p_value_threshold:
93
+ return False
94
+ return True
95
+
96
+ data = df[variable].dropna()
97
+ if len(data) < MIN_NORMALTEST_N:
98
+ return False
99
+ return normaltest(data)[1] >= p_value_threshold
89
100
 
90
101
 
91
102
  def get_chi_square_significance(
92
103
  df: pd.DataFrame, group_column: str, variable: str
93
104
  ) -> float:
94
- """Calculate the chi-square test significance for a given variable and group."""
105
+ """Calculate the chi-square test significance for a given variable and group.
106
+ Falls back to Fisher's exact test for 2x2 tables with expected frequencies < 5."""
95
107
  contingency_table = pd.crosstab(df[group_column], df[variable])
96
- return chi2_contingency(contingency_table)[1]
108
+ chi2, p_value, dof, expected_freq = chi2_contingency(contingency_table)
109
+
110
+ if not (expected_freq >= 5).all():
111
+ if contingency_table.shape == (2, 2):
112
+ _, p_value = fisher_exact(contingency_table)
113
+ else:
114
+ import logging
115
+
116
+ logging.warning(
117
+ "Chi-square expected frequencies < 5 in some cells. "
118
+ "Results may be unreliable. Consider collecting more data."
119
+ )
120
+
121
+ return p_value
97
122
 
98
123
 
99
124
  def get_chi_square_posthoc_results(
@@ -105,15 +130,21 @@ def get_chi_square_posthoc_results(
105
130
  group_combinations = list(combinations(contingency_table.index, 2))
106
131
  p_values = []
107
132
 
108
- # Determine whether to use True/False or 0/1 based on the columns present in the contingency table
109
- true_or_one = 1 if 1 in contingency_table.columns else True
133
+ # Determine the "positive" column dynamically
134
+ truthy_values = [True, 1, 1.0, "true", "True", "yes", "Yes", "Y", "y"]
135
+ positive_col = None
136
+ for col in contingency_table.columns:
137
+ if col in truthy_values:
138
+ positive_col = col
139
+ break
140
+ if positive_col is None:
141
+ # Fallback: use the column with the higher overall count
142
+ positive_col = contingency_table.sum().idxmax()
110
143
 
111
144
  for group_a, group_b in group_combinations:
112
- if true_or_one not in contingency_table.columns:
113
- continue
114
145
  count = [
115
- contingency_table.loc[group_a, true_or_one],
116
- contingency_table.loc[group_b, true_or_one],
146
+ contingency_table.loc[group_a, positive_col],
147
+ contingency_table.loc[group_b, positive_col],
117
148
  ]
118
149
  nobs = [
119
150
  contingency_table.loc[group_a].sum(),
@@ -149,6 +180,23 @@ def get_chi_square_posthoc_results(
149
180
  return posthoc_results
150
181
 
151
182
 
183
+ def are_differences_gaussian(
184
+ df: pd.DataFrame, variables: List[str], p_value_threshold: float
185
+ ) -> bool:
186
+ """Check if the pairwise differences between variables follow a Gaussian distribution.
187
+ This is the correct assumption to test for repeated measures ANOVA."""
188
+ MIN_NORMALTEST_N = 20
189
+ for v1, v2 in combinations(variables, 2):
190
+ diff = df[v1] - df[v2]
191
+ diff = diff.dropna()
192
+ if len(diff) < MIN_NORMALTEST_N:
193
+ return False
194
+ _, p = normaltest(diff)
195
+ if p < p_value_threshold:
196
+ return False
197
+ return True
198
+
199
+
152
200
  def is_levene_significant(
153
201
  df: pd.DataFrame, group_column: str, variable: str, p_value_threshold: float
154
202
  ) -> bool:
@@ -242,7 +290,7 @@ def get_games_howell_posthoc_results(
242
290
  key=lambda x: x["mean"],
243
291
  reverse=True,
244
292
  )
245
- result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.2f})"
293
+ result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.3f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.3f})"
246
294
  posthoc_results.add_result(
247
295
  "Games-Howell", result_pretty_text, row["pval"], groups_info
248
296
  )
@@ -315,9 +363,10 @@ def get_tukeyhsd_posthoc_results(
315
363
  df.groupby(group_column)[variable].agg(["mean", "median", "size"]).reset_index()
316
364
  )
317
365
 
318
- significant_results = tukey._results_df[tukey._results_df["reject"]]
319
- for _, row in significant_results.iterrows():
320
- group_a, group_b = row["group1"], row["group2"]
366
+ pairs = list(combinations(tukey.groupsunique, 2))
367
+ for i, (group_a, group_b) in enumerate(pairs):
368
+ if not tukey.reject[i]:
369
+ continue
321
370
  group_a_stats = group_stats.loc[group_stats[group_column] == group_a].iloc[0]
322
371
  group_b_stats = group_stats.loc[group_stats[group_column] == group_b].iloc[0]
323
372
  groups_info = sorted(
@@ -338,9 +387,9 @@ def get_tukeyhsd_posthoc_results(
338
387
  key=lambda x: x["mean"],
339
388
  reverse=True,
340
389
  )
341
- result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.2f})"
390
+ result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.3f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.3f})"
342
391
  posthoc_results.add_result(
343
- "Tukey HSD", result_pretty_text, row["p-adj"], groups_info
392
+ "Tukey HSD", result_pretty_text, tukey.pvalues[i], groups_info
344
393
  )
345
394
 
346
395
  return posthoc_results
@@ -394,11 +443,11 @@ def get_dunn_posthoc_results(
394
443
  "median": group_b_stats["median"],
395
444
  },
396
445
  ],
397
- key=lambda x: x["mean"],
446
+ key=lambda x: x["median"],
398
447
  reverse=True,
399
448
  )
400
449
 
401
- result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.2f})"
450
+ result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['median']:.3f}) > {groups_info[1]['name']} ({groups_info[1]['median']:.3f})"
402
451
  posthoc_results.add_result(
403
452
  "Dunn", result_pretty_text, p_value, groups_info
404
453
  )
@@ -406,6 +455,23 @@ def get_dunn_posthoc_results(
406
455
  return posthoc_results
407
456
 
408
457
 
458
+ def get_cochrans_q_significance(
459
+ df: pd.DataFrame, variables_to_compare: List[str]
460
+ ) -> float:
461
+ """Performs Cochran's Q test as an omnibus test for >2 dependent dichotomous variables.
462
+
463
+ Parameters:
464
+ - df (pd.DataFrame): The dataframe containing the data.
465
+ - variables_to_compare (List[str]): The column names of dichotomous variables.
466
+
467
+ Returns:
468
+ - float: The p-value from Cochran's Q test.
469
+ """
470
+ data = df[variables_to_compare].values.astype(int)
471
+ result = cochrans_q(data)
472
+ return result.pvalue
473
+
474
+
409
475
  def get_mcnemar_results(
410
476
  df: pd.DataFrame, variables_to_compare: List[str], p_value_threshold: float
411
477
  ) -> Tuple[float, PosthocResults]:
@@ -422,13 +488,19 @@ def get_mcnemar_results(
422
488
  - Tuple[float, PosthocResults]: A tuple containing the p-value of the McNemar's test and the posthoc results.
423
489
  """
424
490
  posthoc_results = PosthocResults()
491
+ p_values = []
492
+
425
493
  # Iterate over all pairs of variables to compare
426
494
  for var1, var2 in combinations(variables_to_compare, 2):
427
495
  # Create a contingency table for the pair of variables
428
496
  contingency_table = pd.crosstab(df[var1], df[var2])
429
- # Perform McNemar's test
430
- result = mcnemar(contingency_table, exact=False)
497
+ # Use exact test when discordant cell counts are small
498
+ b = contingency_table.iloc[0, 1]
499
+ c = contingency_table.iloc[1, 0]
500
+ use_exact = (b + c) < 25
501
+ result = mcnemar(contingency_table, exact=use_exact)
431
502
  p_value = result.pvalue
503
+ p_values.append(p_value)
432
504
 
433
505
  # If the result is significant, add it to the posthoc results
434
506
  if p_value < p_value_threshold:
@@ -445,13 +517,21 @@ def get_mcnemar_results(
445
517
  # Sort groups by mean for consistent presentation
446
518
  groups_info.sort(key=lambda x: x["mean"], reverse=True)
447
519
  # Format the result text
448
- result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.2f})"
520
+ result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.3f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.3f})"
449
521
  # Add the result to posthoc results
450
522
  posthoc_results.add_result(
451
523
  "McNemar", result_pretty_text, p_value, groups_info
452
524
  )
453
525
 
454
- return posthoc_results
526
+ # Apply Bonferroni correction for multiple pairwise comparisons
527
+ if len(p_values) > 1:
528
+ corrected_alpha = p_value_threshold / len(p_values)
529
+ posthoc_results.significant_results = [
530
+ r for r in posthoc_results.significant_results if r.p_value < corrected_alpha
531
+ ]
532
+
533
+ omnibus_pvalue = min(p_values) if p_values else 1.0
534
+ return omnibus_pvalue, posthoc_results
455
535
 
456
536
 
457
537
  def get_repeated_measures_anova_significance(
@@ -459,6 +539,7 @@ def get_repeated_measures_anova_significance(
459
539
  ) -> float:
460
540
  """
461
541
  Calculates the significance of differences between conditions using repeated measures ANOVA.
542
+ Applies Greenhouse-Geisser correction when sphericity is violated.
462
543
 
463
544
  Parameters:
464
545
  - df (pd.DataFrame): The dataframe containing the data.
@@ -476,11 +557,22 @@ def get_repeated_measures_anova_significance(
476
557
  value_name="value",
477
558
  )
478
559
  df_long.rename(columns={"index": "subject_id"}, inplace=True)
479
- # Perform repeated measures ANOVA
480
- aovrm = AnovaRM(df_long, "value", "subject_id", within=["conditions"])
481
- anova_results = aovrm.fit()
482
- # Extract and return the p-value
483
- p_value = anova_results.anova_table["Pr > F"]["conditions"]
560
+
561
+ # Use pingouin's rm_anova which handles sphericity testing and GG correction
562
+ aov = rm_anova(
563
+ data=df_long,
564
+ dv="value",
565
+ within="conditions",
566
+ subject="subject_id",
567
+ correction=True,
568
+ )
569
+
570
+ # Use GG-corrected p-value if sphericity is violated, otherwise uncorrected
571
+ if len(variables_to_compare) > 2 and not aov["sphericity"].iloc[0]:
572
+ p_value = aov["p-GG-corr"].iloc[0]
573
+ else:
574
+ p_value = aov["p-unc"].iloc[0]
575
+
484
576
  return p_value
485
577
 
486
578
 
@@ -528,7 +620,7 @@ def get_repeated_measures_anova_posthoc_results(
528
620
  ]
529
621
  # Sort groups by mean for consistent presentation
530
622
  groups_info.sort(key=lambda x: x["mean"], reverse=True)
531
- result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.2f})"
623
+ result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.3f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.3f})"
532
624
  posthoc_results.add_result(
533
625
  "Repeated Measures ANOVA",
534
626
  result_pretty_text,
@@ -574,10 +666,11 @@ def get_wilcoxon_results(
574
666
  }
575
667
  for var in variables_to_compare
576
668
  ]
577
- groups_info.sort(key=lambda x: x["mean"], reverse=True)
669
+ groups_info.sort(key=lambda x: x["median"], reverse=True)
578
670
 
579
- result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.2f})"
580
- posthoc_results.add_result("Wilcoxon", result_pretty_text, p_value, groups_info)
671
+ if p_value < p_value_threshold:
672
+ result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['median']:.3f}) > {groups_info[1]['name']} ({groups_info[1]['median']:.3f})"
673
+ posthoc_results.add_result("Wilcoxon", result_pretty_text, p_value, groups_info)
581
674
 
582
675
  return p_value, posthoc_results
583
676
 
@@ -631,9 +724,9 @@ def get_nemenyi_results(
631
724
  }
632
725
  for var in [var1, var2]
633
726
  ]
634
- groups_info.sort(key=lambda x: x["mean"], reverse=True)
727
+ groups_info.sort(key=lambda x: x["median"], reverse=True)
635
728
 
636
- result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.2f})"
729
+ result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['median']:.3f}) > {groups_info[1]['name']} ({groups_info[1]['median']:.3f})"
637
730
  posthoc_results.add_result(
638
731
  "Nemenyi", result_pretty_text, posthoc_p_value, groups_info
639
732
  )
@@ -35,7 +35,7 @@ def format_results_as_table(
35
35
  identifiers (list of str, optional): A list of strings that are to be used for identifying the data. Defaults to [].
36
36
  show_only_significant_results (bool, optional): A boolean flag indicating if only significant results should be shown. Defaults to False.
37
37
  show_details (bool, optional): A boolean flag indicating if the details of the statistical tests should be shown. Defaults to False.
38
- output_format (str, optional): A string indicating the format of the output. Defaults to "simple". Checl the tabulate documentation: https://github.com/astanin/python-tabulate#table-format
38
+ output_format (str, optional): A string indicating the format of the output. Defaults to "simple". Check the tabulate documentation: https://github.com/astanin/python-tabulate#table-format
39
39
 
40
40
  Returns:
41
41
  str: A formatted text string with the results of the statistical significance tests.
@@ -64,7 +64,7 @@ def format_results_as_table(
64
64
  row = identifiers_list[idx].copy()
65
65
  row["n"] = sample_size
66
66
  row["Result"] = result.result_pretty_text
67
- row["p-value"] = result.p_value # round(result.p_value,3)
67
+ row["p-value"] = result.p_value
68
68
  if show_details:
69
69
  row["Analysis method"] = result.analysis_method
70
70
  if info:
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: abalytics
3
- Version: 3.0.4
3
+ Version: 4.0.1
4
4
  Summary: Advanced A/B Testing Statistical Analytics
5
5
  Author: Janis Berneker
6
6
  License: LICENSE
@@ -8,12 +8,21 @@ Project-URL: Repository, https://github.com/BigBerny/abalytics
8
8
  Requires-Python: >=3.8
9
9
  Description-Content-Type: text/markdown
10
10
  License-File: LICENSE
11
- Requires-Dist: pandas>=1.5.2
12
- Requires-Dist: scipy>=1.10.1
13
- Requires-Dist: statsmodels>=0.14.1
14
- Requires-Dist: scikit-posthocs>=0.8.1
15
- Requires-Dist: pingouin>=0.5.4
11
+ Requires-Dist: pandas>=2.2.0
12
+ Requires-Dist: scipy>=1.12.0
13
+ Requires-Dist: statsmodels>=0.14.6
14
+ Requires-Dist: scikit-posthocs>=0.12.0
15
+ Requires-Dist: pingouin>=0.5.5
16
16
  Requires-Dist: tabulate>=0.9.0
17
+ Dynamic: author
18
+ Dynamic: description
19
+ Dynamic: description-content-type
20
+ Dynamic: license
21
+ Dynamic: license-file
22
+ Dynamic: project-url
23
+ Dynamic: requires-dist
24
+ Dynamic: requires-python
25
+ Dynamic: summary
17
26
 
18
27
  # ABalytics: Advanced A/B Testing Statistical Analytics
19
28
 
@@ -0,0 +1,6 @@
1
+ pandas>=2.2.0
2
+ scipy>=1.12.0
3
+ statsmodels>=0.14.6
4
+ scikit-posthocs>=0.12.0
5
+ pingouin>=0.5.5
6
+ tabulate>=0.9.0
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name='abalytics',
5
- version='3.0.4',
5
+ version='4.0.1',
6
6
  author='Janis Berneker',
7
7
  packages=find_packages(),
8
8
  license='LICENSE',
@@ -10,11 +10,11 @@ setup(
10
10
  long_description=open('README.md').read(),
11
11
  long_description_content_type='text/markdown',
12
12
  install_requires=[
13
- 'pandas>=1.5.2',
14
- 'scipy>=1.10.1',
15
- 'statsmodels>=0.14.1',
16
- 'scikit-posthocs>=0.8.1',
17
- 'pingouin>=0.5.4',
13
+ 'pandas>=2.2.0',
14
+ 'scipy>=1.12.0',
15
+ 'statsmodels>=0.14.6',
16
+ 'scikit-posthocs>=0.12.0',
17
+ 'pingouin>=0.5.5',
18
18
  'tabulate>=0.9.0'
19
19
  ],
20
20
  python_requires='>=3.8',
@@ -1,6 +0,0 @@
1
- pandas>=1.5.2
2
- scipy>=1.10.1
3
- statsmodels>=0.14.1
4
- scikit-posthocs>=0.8.1
5
- pingouin>=0.5.4
6
- tabulate>=0.9.0
File without changes
File without changes
File without changes