import numpy as np
from scipy import stats

def select_best_scaler(x):
    """选择最佳缩放器"""
    n = len(x)
    if n == 0:
        return "Z-score标准化"
    
    max_val = max(x)
    min_val = min(x)
    mean = np.mean(x)
    std = np.std(x)
    
    # 计算偏度和峰度
    skew = stats.skew(x)
    kurt = stats.kurtosis(x)
    
    # 计算四分位数
    q1 = np.percentile(x, 25)
    q3 = np.percentile(x, 75)
    iqr = q3 - q1
    total_range = max_val - min_val
    
    # 计算异常值比例
    outliers = []
    for val in x:
        if val < q1 - 1.5 * iqr or val > q3 + 1.5 * iqr:
            outliers.append(val)
    outlier_ratio = len(outliers) / n
    
    # 评分
    score_standard = abs(skew) + abs(kurt)  # 偏度和峰度越小越好
    score_minmax = 1.0 if total_range > 0 else 0.0  # 范围越大越好
    score_maxabs = 1.0 if max(abs(v) for v in x) > 0 else 0.0  # 绝对值越大越好
    score_robust = 1.0 - outlier_ratio  # 异常值越少，RobustScaler效果越好
    score_quantile = abs(skew)  # 偏度越大，QuantileTransformer效果越好
    
    # 计算均值归一化评分 - 基于数据的中心位置
    score_mean = 1.0 if abs(mean) > 0.1 else 0.0  # 均值不为零时效果更好
    
    # 计算单位长度归一化评分 - 基于数据的稀疏性
    non_zero_count = sum(1 for v in x if v != 0)
    score_unit = non_zero_count / n  # 非零值比例越高，效果越好
    
    # 计算自定义缩放评分 - 基于数据的整体分布
    score_custom = 1.0 - min(abs(skew), 1.0)  # 偏度越小，自定义缩放效果越好
    
    # 选择最佳评分
    scores = [score_standard, score_minmax, score_maxabs, score_robust, score_quantile, score_mean, score_unit, score_custom]
    best_index = scores.index(min(scores))  # 注意这里使用min，因为大多数评分越小越好
    
    scalers = ["Z-score标准化", "Min-Max标准化", "MaxAbs标准化", "RobustScaler标准化", "QuantileTransformer标准化", "均值归一化", "单位长度归一化", "自定义缩放"]
    return scalers[best_index]

def get_best_scaler(col):
    """获取最佳缩放器"""
    try:
        # 转换为数值类型
        data = [float(s) for s in col]
        return select_best_scaler(data)
    except ValueError:
        return "Z-score标准化"  # 默认值
