Spaces:
Sleeping
Sleeping
File size: 4,704 Bytes
fe20038 | 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 | # mcp_tools.py
import numpy as np
import pingouin as pg
import matplotlib.pyplot as plt
import io
import base64
import json
def plot_group_distribution(groups_str):
groups = [np.array([float(x) for x in g.split(",")]) for g in groups_str.split(";")]
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
# Histogram
for g in groups:
axes[0].hist(g, alpha=0.5)
axes[0].set_title("Histogram")
# Boxplot
axes[1].boxplot(groups)
axes[1].set_title("Boxplot")
# QQ plot (first group)
pg.qqplot(groups[0], ax=axes[2])
axes[2].set_title("QQ Plot (Group 1)")
buf = io.BytesIO()
fig.savefig(buf, format="png")
buf.seek(0)
return base64.b64encode(buf.read()).decode()
def assumption_checks(groups_str):
import pandas as pd
groups = [np.array([float(x) for x in g.split(",")]) for g in groups_str.split(";")]
# Normality (Shapiro) with safety guard
normality = []
for i, g in enumerate(groups):
if len(g) < 4:
normality.append({
"group": f"G{i+1}",
"error": "Normality test requires at least 4 samples."
})
else:
result = pg.normality(g).to_dict(orient="records")[0]
normality.append({
"group": f"G{i+1}",
**result
})
# Homogeneity (Levene)
levene = pg.homoscedasticity(groups, method="levene").to_dict(orient="records")[0]
return {
"normality": normality,
"homogeneity": levene
}
def posthoc_tests(groups_str, method="games-howell"):
import pandas as pd
groups = [np.array([float(x) for x in g.split(",")]) for g in groups_str.split(";")]
data = []
for i, g in enumerate(groups):
for val in g:
data.append({"value": val, "group": f"G{i+1}"})
df = pd.DataFrame(data)
result = pg.pairwise_ttests(
dv="value",
between="group",
data=df,
padjust="bonf",
parametric=(method == "tukey"),
effsize="hedges"
)
return result.to_dict(orient="records")
# -----------------------------
# Helper: convert Pingouin DF → JSON
# -----------------------------
def pg_to_json(df):
"""Convert Pingouin single-row DataFrame to JSON dict."""
return df.to_dict(orient="records")[0]
# -----------------------------
# Welch t-test (independent, unequal variances)
# -----------------------------
def welch_t_test(group1_str, group2_str, alternative="two-sided"):
g1 = np.array([float(x) for x in group1_str.split(",")])
g2 = np.array([float(x) for x in group2_str.split(",")])
result = pg.ttest(g1, g2, paired=False, correction=True, alternative=alternative)
return pg_to_json(result)
# -----------------------------
# Student t-test (independent, equal variances)
# -----------------------------
def student_t_test(group1_str, group2_str, alternative="two-sided"):
g1 = np.array([float(x) for x in group1_str.split(",")])
g2 = np.array([float(x) for x in group2_str.split(",")])
result = pg.ttest(g1, g2, paired=False, correction=False, alternative=alternative)
return pg_to_json(result)
# -----------------------------
# Paired t-test (same subjects measured twice)
# -----------------------------
def paired_t_test(group1_str, group2_str, alternative="two-sided"):
g1 = np.array([float(x) for x in group1_str.split(",")])
g2 = np.array([float(x) for x in group2_str.split(",")])
result = pg.ttest(g1, g2, paired=True, alternative=alternative)
return pg_to_json(result)
# -----------------------------
# One-sample t-test (sample vs population mean)
# -----------------------------
def one_sample_t_test(group_str, population_mean, alternative="two-sided"):
g = np.array([float(x) for x in group_str.split(",")])
# Adjust sample for one-sample t-test
adjusted = g - float(population_mean)
# Pingouin one-sample t-test: y=None, popmean implicitly = 0
result = pg.ttest(adjusted, y=None, paired=False, alternative=alternative)
return pg_to_json(result)
# -----------------------------
# One-way ANOVA (multiple independent groups)
# -----------------------------
def one_way_anova(groups_str):
"""
groups_str format:
"1,2,3; 4,5,6; 7,8,9"
"""
groups = [np.array([float(x) for x in g.split(",")]) for g in groups_str.split(";")]
# Build DataFrame for Pingouin
import pandas as pd
data = []
for i, g in enumerate(groups):
for val in g:
data.append({"value": val, "group": f"G{i+1}"})
df = pd.DataFrame(data)
result = pg.anova(dv="value", between="group", data=df)
return pg_to_json(result)
|