"""Reproducible analysis for: Wine Chemical Profile

Generated by thericerca on 2026-07-30 21:01 UTC.
Regenerate the same statistical output on the same data by running this script (or the
matching .ipynb) with the third-party libraries at the top installed.

Statement of the problem:
  This study explores the chemical composition of wines and the latent structure underlying the measured constituents.

Objectives:
  - To describe the alcohol, total_phenols, flavanoids, and color_intensity of the wines.
  - To determine the relationship between total_phenols and flavanoids.
  - To uncover the underlying factor structure among total_phenols, flavanoids, nonflavanoid_phenols, proanthocyanins, and hue.

"""

# Optional libraries used below (install with: pip install factor-analyzer).
import pandas as pd
import numpy as np
from scipy import stats
import statsmodels.api as sm
import statsmodels.formula.api as smf
from factor_analyzer import FactorAnalyzer
from factor_analyzer.factor_analyzer import calculate_bartlett_sphericity, calculate_kmo


# Load the dataset. Point this at your local copy of 'wine.csv'.
df = pd.read_csv('wine.csv')
print(f'Loaded {len(df)} rows, {len(df.columns)} columns.')
df.head()


# ------------------------------------------------------------------------------
# [1/3] Descriptive Statistics
#   Question: To describe the alcohol, total_phenols, flavanoids, and color_intensity of the wines.
# ------------------------------------------------------------------------------
cols = ['alcohol', 'total_phenols', 'flavanoids', 'color_intensity']
print(df[cols].describe(include='all').T)


# ------------------------------------------------------------------------------
# [2/3] Spearman Rank Correlation
#   Question: To determine the relationship between total_phenols and flavanoids.
# ------------------------------------------------------------------------------
a, b = df['total_phenols'].dropna(), df['flavanoids'].dropna()
pair = pd.concat([a, b], axis=1).dropna()
rho, p_value = stats.spearmanr(pair.iloc[:, 0], pair.iloc[:, 1])
print(f'rho = {rho:.3f}, p = {p_value:.4g}, n = {len(pair)}')


# ------------------------------------------------------------------------------
# [3/3] Exploratory Factor Analysis
#   Question: To uncover the underlying factor structure among total_phenols, flavanoids, nonflavanoid_phenols, proanthocyanins, and hue.
# ------------------------------------------------------------------------------
items = df[['total_phenols', 'flavanoids', 'nonflavanoid_phenols', 'proanthocyanins', 'hue']].dropna()
bartlett_chi2, bartlett_p = calculate_bartlett_sphericity(items)
kmo_per_item, kmo_total = calculate_kmo(items)
print(f'Bartlett chi2 = {bartlett_chi2:.3f}, p = {bartlett_p:.4g};  KMO = {kmo_total:.3f}')
# Fit with a parallel-analysis-style choice of factors (here: eigenvalues > 1 on the correlation matrix).
fa = FactorAnalyzer(rotation=None)
fa.fit(items)
eigenvalues, _ = fa.get_eigenvalues()
n_factors = int(sum(1 for e in eigenvalues if e > 1))
fa = FactorAnalyzer(n_factors=n_factors, rotation='varimax')
fa.fit(items)
loadings = pd.DataFrame(fa.loadings_, index=items.columns,
                         columns=[f'F{i+1}' for i in range(n_factors)])
print(loadings.round(3))


# ------------------------------------------------------------------------------
# End of thericerca reproducible analysis.
# ------------------------------------------------------------------------------
