Update app.py
Browse files
app.py
CHANGED
|
@@ -10,6 +10,35 @@ import matplotlib.pyplot as plt
|
|
| 10 |
import seaborn as sns
|
| 11 |
import gradio as gr
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
def compare_methods(data):
|
| 14 |
"""Realiza a comparação estatística entre dois métodos de medição."""
|
| 15 |
try:
|
|
@@ -30,66 +59,28 @@ def compare_methods(data):
|
|
| 30 |
data['Method_2_Mean'] = data[['Method_2_1', 'Method_2_2', 'Method_2_3']].mean(axis=1)
|
| 31 |
data['Difference'] = data['Method_1_Mean'] - data['Method_2_Mean']
|
| 32 |
|
| 33 |
-
# Teste t pareado
|
| 34 |
-
t_results = []
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
if len(subset) > 1:
|
| 38 |
-
t_stat, p_value = stats.ttest_rel(subset['Method_1_Mean'], subset['Method_2_Mean'])
|
| 39 |
-
t_results.append({'Concentration': conc, 't-statistic': round(t_stat, 4), 'p-value': round(p_value, 4)})
|
| 40 |
t_test_df = pd.DataFrame(t_results)
|
| 41 |
|
| 42 |
-
# Teste de Levene
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
levene_df = pd.DataFrame({'Levene Statistic': [round(levene_stat, 4)], 'p-value': [round(levene_p, 4)]})
|
| 46 |
-
else:
|
| 47 |
-
levene_df = pd.DataFrame({'Levene Statistic': ['N/A'], 'p-value': ['N/A']})
|
| 48 |
|
| 49 |
# ANOVA
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
anova_df = pd.DataFrame({'F-statistic': [round(anova_stat, 4)], 'p-value': [round(anova_p, 4)]})
|
| 53 |
-
else:
|
| 54 |
-
anova_df = pd.DataFrame({'F-statistic': ['N/A'], 'p-value': ['N/A']})
|
| 55 |
|
| 56 |
-
# Regressão
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
regression_results = {
|
| 60 |
-
'Slope': round(slope, 4), 'Intercept': round(intercept, 4), 'R²': round(r_value**2, 4),
|
| 61 |
-
'p-value': round(p_value, 4), 'Std Error': round(std_err, 4)
|
| 62 |
-
}
|
| 63 |
-
|
| 64 |
-
# Criando gráfico de regressão linear
|
| 65 |
-
fig_reg, ax_reg = plt.subplots(figsize=(6, 4))
|
| 66 |
-
sns.regplot(x=data['Method_1_Mean'], y=data['Method_2_Mean'], ax=ax_reg, scatter_kws={'color': 'blue'}, line_kws={'color': 'red'})
|
| 67 |
-
ax_reg.set_xlabel('Média Método 1')
|
| 68 |
-
ax_reg.set_ylabel('Média Método 2')
|
| 69 |
-
ax_reg.set_title('Gráfico de Regressão Linear')
|
| 70 |
-
else:
|
| 71 |
-
regression_results = {'Slope': 'N/A', 'Intercept': 'N/A', 'R²': 'N/A', 'p-value': 'N/A', 'Std Error': 'N/A'}
|
| 72 |
-
fig_reg = None
|
| 73 |
|
| 74 |
-
#
|
| 75 |
-
|
| 76 |
-
means = (data['Method_1_Mean'] + data['Method_2_Mean']) / 2
|
| 77 |
-
diffs = data['Method_1_Mean'] - data['Method_2_Mean']
|
| 78 |
-
mean_diff = np.mean(diffs)
|
| 79 |
-
std_diff = np.std(diffs, ddof=1)
|
| 80 |
-
fig_bland, ax_bland = plt.subplots(figsize=(6, 4))
|
| 81 |
-
ax_bland.scatter(means, diffs, color='blue', alpha=0.6)
|
| 82 |
-
ax_bland.axhline(mean_diff, color='red', linestyle='--', label=f'Média das Diferenças ({mean_diff:.2f})')
|
| 83 |
-
ax_bland.axhline(mean_diff + 1.96 * std_diff, color='gray', linestyle='--', label='Limite Superior (95%)')
|
| 84 |
-
ax_bland.axhline(mean_diff - 1.96 * std_diff, color='gray', linestyle='--', label='Limite Inferior (95%)')
|
| 85 |
-
ax_bland.set_xlabel('Média dos Métodos')
|
| 86 |
-
ax_bland.set_ylabel('Diferença Método 1 - Método 2')
|
| 87 |
-
ax_bland.set_title('Gráfico de Bland-Altman')
|
| 88 |
-
ax_bland.legend()
|
| 89 |
-
else:
|
| 90 |
-
fig_bland = None
|
| 91 |
|
| 92 |
-
return t_test_df, levene_df, anova_df, regression_results,
|
| 93 |
except Exception as e:
|
| 94 |
return f"Erro durante a análise: {str(e)}"
|
| 95 |
|
|
@@ -107,11 +98,10 @@ iface = gr.Interface(
|
|
| 107 |
gr.Dataframe(label="Teste de Levene"),
|
| 108 |
gr.Dataframe(label="ANOVA"),
|
| 109 |
gr.JSON(label="Regressão Linear"),
|
| 110 |
-
gr.
|
| 111 |
-
gr.Plot(label="Gráfico de Regressão Linear")
|
| 112 |
],
|
| 113 |
title="Comparação de Métodos de Medição",
|
| 114 |
-
description="Preencha a tabela com três concentrações e suas respectivas triplicatas para cada método. A ferramenta realizará a análise estatística automaticamente e apresentará os resultados
|
| 115 |
)
|
| 116 |
|
| 117 |
iface.launch(share=True)
|
|
@@ -119,3 +109,4 @@ iface.launch(share=True)
|
|
| 119 |
|
| 120 |
|
| 121 |
|
|
|
|
|
|
| 10 |
import seaborn as sns
|
| 11 |
import gradio as gr
|
| 12 |
|
| 13 |
+
def interpret_results(t_test_df, levene_df, anova_df, regression_results):
|
| 14 |
+
"""Gera interpretações automáticas dos resultados com base na ISO 5725."""
|
| 15 |
+
interpretations = []
|
| 16 |
+
|
| 17 |
+
# Interpretação do Teste t pareado
|
| 18 |
+
if not t_test_df.empty:
|
| 19 |
+
p_value = t_test_df['p-value'].mean()
|
| 20 |
+
if p_value < 0.05:
|
| 21 |
+
interpretations.append("O teste t indicou que há uma diferença estatisticamente significativa entre os métodos (p < 0.05).")
|
| 22 |
+
else:
|
| 23 |
+
interpretations.append("O teste t indicou que não há diferença estatisticamente significativa entre os métodos (p >= 0.05).")
|
| 24 |
+
|
| 25 |
+
# Interpretação do Teste de Levene
|
| 26 |
+
if not levene_df.empty:
|
| 27 |
+
p_value = levene_df['p-value'].values[0]
|
| 28 |
+
if p_value < 0.05:
|
| 29 |
+
interpretations.append("O teste de Levene indicou que as variâncias dos métodos são significativamente diferentes, sugerindo precisão diferente.")
|
| 30 |
+
else:
|
| 31 |
+
interpretations.append("O teste de Levene indicou que as variâncias dos métodos são equivalentes, sugerindo precisão similar.")
|
| 32 |
+
|
| 33 |
+
# Interpretação da Regressão Linear
|
| 34 |
+
if regression_results['R²'] != 'N/A':
|
| 35 |
+
if regression_results['Slope'] >= 0.95 and regression_results['Slope'] <= 1.05 and regression_results['R²'] > 0.95:
|
| 36 |
+
interpretations.append("A regressão linear sugere que os métodos são altamente correlacionados e podem ser considerados equivalentes.")
|
| 37 |
+
else:
|
| 38 |
+
interpretations.append("A regressão linear indica que os métodos não são equivalentes, pois o coeficiente angular está distante de 1 ou R² < 0.95.")
|
| 39 |
+
|
| 40 |
+
return "\n".join(interpretations)
|
| 41 |
+
|
| 42 |
def compare_methods(data):
|
| 43 |
"""Realiza a comparação estatística entre dois métodos de medição."""
|
| 44 |
try:
|
|
|
|
| 59 |
data['Method_2_Mean'] = data[['Method_2_1', 'Method_2_2', 'Method_2_3']].mean(axis=1)
|
| 60 |
data['Difference'] = data['Method_1_Mean'] - data['Method_2_Mean']
|
| 61 |
|
| 62 |
+
# Teste t pareado
|
| 63 |
+
t_results = [{'Concentration': conc, 't-statistic': stats.ttest_rel(subset['Method_1_Mean'], subset['Method_2_Mean'])[0],
|
| 64 |
+
'p-value': stats.ttest_rel(subset['Method_1_Mean'], subset['Method_2_Mean'])[1]}
|
| 65 |
+
for conc, subset in data.groupby('Concentration')]
|
|
|
|
|
|
|
|
|
|
| 66 |
t_test_df = pd.DataFrame(t_results)
|
| 67 |
|
| 68 |
+
# Teste de Levene
|
| 69 |
+
levene_stat, levene_p = stats.levene(data['Method_1_Mean'], data['Method_2_Mean'])
|
| 70 |
+
levene_df = pd.DataFrame({'Levene Statistic': [levene_stat], 'p-value': [levene_p]})
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
# ANOVA
|
| 73 |
+
anova_stat, anova_p = stats.f_oneway(data['Method_1_Mean'], data['Method_2_Mean'])
|
| 74 |
+
anova_df = pd.DataFrame({'F-statistic': [anova_stat], 'p-value': [anova_p]})
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
# Regressão Linear
|
| 77 |
+
slope, intercept, r_value, p_value, std_err = stats.linregress(data['Method_1_Mean'], data['Method_2_Mean'])
|
| 78 |
+
regression_results = {'Slope': slope, 'Intercept': intercept, 'R²': r_value**2, 'p-value': p_value, 'Std Error': std_err}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
# Interpretação automática
|
| 81 |
+
interpretation_text = interpret_results(t_test_df, levene_df, anova_df, regression_results)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
return t_test_df, levene_df, anova_df, regression_results, interpretation_text
|
| 84 |
except Exception as e:
|
| 85 |
return f"Erro durante a análise: {str(e)}"
|
| 86 |
|
|
|
|
| 98 |
gr.Dataframe(label="Teste de Levene"),
|
| 99 |
gr.Dataframe(label="ANOVA"),
|
| 100 |
gr.JSON(label="Regressão Linear"),
|
| 101 |
+
gr.Textbox(label="Interpretação dos Resultados")
|
|
|
|
| 102 |
],
|
| 103 |
title="Comparação de Métodos de Medição",
|
| 104 |
+
description="Preencha a tabela com três concentrações e suas respectivas triplicatas para cada método. A ferramenta realizará a análise estatística automaticamente e apresentará os resultados com uma interpretação baseada na ISO 5725."
|
| 105 |
)
|
| 106 |
|
| 107 |
iface.launch(share=True)
|
|
|
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
+
|