import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from sklearn.metrics import r2_score
import warnings
import math
warnings.filterwarnings('ignore')

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

# 度数到弧度的转换常数
DEG_TO_RAD = math.pi / 180.0

# 读取CSV文件
csv_path = 'csv/各关节质量与运动角度相关数据表格.csv'
df = pd.read_csv(csv_path, encoding='utf-8')

# 提取数据（度数）
mcp_angles_deg = df.iloc[:, 0].values  # MCP角度（主动关节，度数）
finger_names = ['食指', '中指', '无名指', '尾指']
pip_angles_deg = {}
for i, name in enumerate(finger_names):
    pip_angles_deg[name] = df.iloc[:, i+1].values  # PIP角度（被动关节，度数）

# 转换为弧度（用于 MuJoCo）
mcp_angles_rad = mcp_angles_deg * DEG_TO_RAD
pip_angles_rad = {}
for name in finger_names:
    pip_angles_rad[name] = pip_angles_deg[name] * DEG_TO_RAD

print("="*60)
print("主动关节(MCP)与被动关节(PIP)函数关系拟合分析")
print("="*60)
print(f"\n数据点数量: {len(mcp_angles_deg)}")
print(f"MCP角度范围: {mcp_angles_deg.min():.2f}° ({mcp_angles_rad.min():.4f} rad) - {mcp_angles_deg.max():.2f}° ({mcp_angles_rad.max():.4f} rad)\n")

# 定义拟合函数（弧度）
def linear_func(x, a, b):
    """线性函数: y = a*x + b"""
    return a * x + b

def quadratic_func(x, a, b, c):
    """二次函数: y = a*x^2 + b*x + c"""
    return a * x**2 + b * x + c

def cubic_func(x, a, b, c, d):
    """三次函数: y = a*x^3 + b*x^2 + c*x + d"""
    return a * x**3 + b * x**2 + c * x + d

def quartic_func(x, a, b, c, d, e):
    """四次函数: y = a*x^4 + b*x^3 + c*x^2 + d*x + e"""
    return a * x**4 + b * x**3 + c * x**2 + d * x + e

# 存储拟合结果
fitting_results = {}

# 对每个手指进行拟合（使用弧度数据）
for finger_name in finger_names:
    print(f"\n{'='*60}")
    print(f"分析: {finger_name}")
    print(f"{'='*60}")
    
    y_data_rad = pip_angles_rad[finger_name]
    y_data_deg = pip_angles_deg[finger_name]
    
    # 尝试不同的拟合方法（使用弧度）
    fits = {}
    
    # 1. 线性拟合
    try:
        popt_linear, _ = curve_fit(linear_func, mcp_angles_rad, y_data_rad)
        y_pred_linear = linear_func(mcp_angles_rad, *popt_linear)
        r2_linear = r2_score(y_data_rad, y_pred_linear)
        fits['线性'] = {
            'params': popt_linear,
            'r2': r2_linear,
            'func': linear_func,
            'formula_deg': f"PIP(°) = {popt_linear[0]*180/math.pi:.6f} * MCP(°) + {popt_linear[1]*180/math.pi:.6f}",
            'formula_rad': f"PIP(rad) = {popt_linear[0]:.6f} * MCP(rad) + {popt_linear[1]:.6f}"
        }
        print(f"线性拟合: {fits['线性']['formula_rad']}")
        print(f"  R² = {r2_linear:.6f}")
    except:
        pass
    
    # 2. 二次拟合
    try:
        popt_quad, _ = curve_fit(quadratic_func, mcp_angles_rad, y_data_rad)
        y_pred_quad = quadratic_func(mcp_angles_rad, *popt_quad)
        r2_quad = r2_score(y_data_rad, y_pred_quad)
        fits['二次'] = {
            'params': popt_quad,
            'r2': r2_quad,
            'func': quadratic_func,
            'formula_rad': f"PIP(rad) = {popt_quad[0]:.6f} * MCP(rad)² + {popt_quad[1]:.6f} * MCP(rad) + {popt_quad[2]:.6f}"
        }
        print(f"二次拟合: {fits['二次']['formula_rad']}")
        print(f"  R² = {r2_quad:.6f}")
    except:
        pass
    
    # 3. 三次拟合
    try:
        popt_cubic, _ = curve_fit(cubic_func, mcp_angles_rad, y_data_rad)
        y_pred_cubic = cubic_func(mcp_angles_rad, *popt_cubic)
        r2_cubic = r2_score(y_data_rad, y_pred_cubic)
        fits['三次'] = {
            'params': popt_cubic,
            'r2': r2_cubic,
            'func': cubic_func,
            'formula_rad': f"PIP(rad) = {popt_cubic[0]:.6f} * MCP(rad)³ + {popt_cubic[1]:.6f} * MCP(rad)² + {popt_cubic[2]:.6f} * MCP(rad) + {popt_cubic[3]:.6f}"
        }
        print(f"三次拟合: {fits['三次']['formula_rad']}")
        print(f"  R² = {r2_cubic:.6f}")
    except:
        pass
    
    # 4. 四次拟合（MuJoCo 支持）
    try:
        popt_quartic, _ = curve_fit(quartic_func, mcp_angles_rad, y_data_rad)
        y_pred_quartic = quartic_func(mcp_angles_rad, *popt_quartic)
        r2_quartic = r2_score(y_data_rad, y_pred_quartic)
        fits['四次'] = {
            'params': popt_quartic,
            'r2': r2_quartic,
            'func': quartic_func,
            'formula_rad': f"PIP(rad) = {popt_quartic[0]:.6f} * MCP(rad)⁴ + {popt_quartic[1]:.6f} * MCP(rad)³ + {popt_quartic[2]:.6f} * MCP(rad)² + {popt_quartic[3]:.6f} * MCP(rad) + {popt_quartic[4]:.6f}"
        }
        print(f"四次拟合: {fits['四次']['formula_rad']}")
        print(f"  R² = {r2_quartic:.6f}")
    except:
        pass
    
    # 选择最佳拟合（R²最高）
    if fits:
        best_fit = max(fits.items(), key=lambda x: x[1]['r2'])
        best_name, best_data = best_fit
        fitting_results[finger_name] = {
            'best': best_name,
            'all_fits': fits,
            'best_fit': best_data
        }
        print(f"\n最佳拟合: {best_name} (R² = {best_data['r2']:.6f})")
        print(f"函数关系: {best_data['formula_rad']}")

# 可视化结果
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
axes = axes.flatten()

for idx, finger_name in enumerate(finger_names):
    ax = axes[idx]
    
    # 绘制原始数据点（度数）
    ax.scatter(mcp_angles_deg, pip_angles_deg[finger_name], 
              alpha=0.6, s=30, label='原始数据', color='blue')
    
    # 绘制拟合曲线（转换为度数显示）
    if finger_name in fitting_results:
        result = fitting_results[finger_name]
        best_fit = result['best_fit']
        
        # 生成平滑曲线（使用弧度计算，转换为度数显示）
        x_smooth_rad = np.linspace(mcp_angles_rad.min(), mcp_angles_rad.max(), 200)
        y_smooth_rad = best_fit['func'](x_smooth_rad, *best_fit['params'])
        x_smooth_deg = x_smooth_rad / DEG_TO_RAD
        y_smooth_deg = y_smooth_rad / DEG_TO_RAD
        ax.plot(x_smooth_deg, y_smooth_deg, 'r-', linewidth=2, 
               label=f"{result['best']}拟合 (R²={best_fit['r2']:.4f})")
        
        # 显示所有拟合结果
        for fit_name, fit_data in result['all_fits'].items():
            if fit_name != result['best']:
                y_fit_rad = fit_data['func'](mcp_angles_rad, *fit_data['params'])
                y_fit_deg = y_fit_rad / DEG_TO_RAD
                ax.plot(mcp_angles_deg, y_fit_deg, '--', alpha=0.5, 
                       label=f"{fit_name} (R²={fit_data['r2']:.4f})")
    
    ax.set_xlabel('MCP角度 (°)', fontsize=12)
    ax.set_ylabel('PIP角度 (°)', fontsize=12)
    ax.set_title(f'{finger_name} - MCP vs PIP', fontsize=14, fontweight='bold')
    ax.legend(fontsize=9)
    ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.savefig('scripts/fitting_results.png', dpi=300, bbox_inches='tight')
print(f"\n\n可视化结果已保存到: scripts/fitting_results.png")

# 输出总结
print("\n" + "="*60)
print("拟合结果总结")
print("="*60)

for finger_name in finger_names:
    if finger_name in fitting_results:
        result = fitting_results[finger_name]
        print(f"\n{finger_name}:")
        print(f"  最佳拟合方法: {result['best']}")
        print(f"  函数关系: {result['best_fit']['formula_rad']}")
        print(f"  拟合优度 (R²): {result['best_fit']['r2']:.6f}")

# 生成用于MuJoCo XML的polycoef格式（修正版）
print("\n" + "="*60)
print("MuJoCo XML格式的polycoef系数（修正版）")
print("="*60)
print("根据 MuJoCo 定义: PIP - PIP₀ = a₀ + a₁(MCP - MCP₀) + a₂(MCP - MCP₀)² + a₃(MCP - MCP₀)³ + a₄(MCP - MCP₀)⁴")
print("假设初始配置: MCP₀ = 0, PIP₀ = 0 (弧度)")
print("因此: PIP = a₀ + a₁·MCP + a₂·MCP² + a₃·MCP³ + a₄·MCP⁴")
print("polycoef格式: [a₀, a₁, a₂, a₃, a₄] (5个系数，弧度)\n")

for finger_name in finger_names:
    if finger_name in fitting_results:
        result = fitting_results[finger_name]
        best_fit = result['best_fit']
        params = best_fit['params']
        
        # 根据拟合类型生成polycoef（5个系数）
        if result['best'] == '线性':
            # 线性: PIP = a*MCP + b -> polycoef = [b, a, 0, 0, 0]
            polycoef = [params[1], params[0], 0.0, 0.0, 0.0]
        elif result['best'] == '二次':
            # 二次: PIP = a*MCP² + b*MCP + c -> polycoef = [c, b, a, 0, 0]
            polycoef = [params[2], params[1], params[0], 0.0, 0.0]
        elif result['best'] == '三次':
            # 三次: PIP = a*MCP³ + b*MCP² + c*MCP + d -> polycoef = [d, c, b, a, 0]
            polycoef = [params[3], params[2], params[1], params[0], 0.0]
        elif result['best'] == '四次':
            # 四次: PIP = a*MCP⁴ + b*MCP³ + c*MCP² + d*MCP + e -> polycoef = [e, d, c, b, a]
            polycoef = [params[4], params[3], params[2], params[1], params[0]]
        else:
            polycoef = [0.0, 1.0, 0.0, 0.0, 0.0]  # 默认
        
        # 格式化输出（保留足够精度）
        polycoef_str = ' '.join([f"{coef:.10f}" for coef in polycoef])
        print(f"{finger_name}:")
        print(f"  polycoef=\"{polycoef_str}\"")
        print(f"  公式: PIP = {polycoef[0]:.6f} + {polycoef[1]:.6f}*MCP + {polycoef[2]:.6f}*MCP² + {polycoef[3]:.6f}*MCP³ + {polycoef[4]:.6f}*MCP⁴")

# 输出XML格式的代码片段
print("\n" + "="*60)
print("XML代码片段（可直接复制）")
print("="*60)
print("<equality>")
print("  <!--  mimic distal -> proximal  -->")
print("  <!-- 基于实际数据拟合的函数关系（弧度）: PIP = a₀ + a₁*MCP + a₂*MCP² + a₃*MCP³ + a₄*MCP⁴ -->")
for finger_name in finger_names:
    if finger_name in fitting_results:
        result = fitting_results[finger_name]
        best_fit = result['best_fit']
        params = best_fit['params']
        
        # 生成polycoef
        if result['best'] == '线性':
            polycoef = [params[1], params[0], 0.0, 0.0, 0.0]
        elif result['best'] == '二次':
            polycoef = [params[2], params[1], params[0], 0.0, 0.0]
        elif result['best'] == '三次':
            polycoef = [params[3], params[2], params[1], params[0], 0.0]
        elif result['best'] == '四次':
            polycoef = [params[4], params[3], params[2], params[1], params[0]]
        else:
            polycoef = [0.0, 1.0, 0.0, 0.0, 0.0]
        
        polycoef_str = ' '.join([f"{coef:.10f}" for coef in polycoef])
        
        # 映射手指名称到关节名称
        joint_map = {
            '食指': 'index',
            '中指': 'middle',
            '无名指': 'ring',
            '尾指': 'little'
        }
        joint_name = joint_map.get(finger_name, finger_name)
        print(f"  <joint joint1=\"{joint_name}MCP\" joint2=\"{joint_name}PIP\" polycoef=\"{polycoef_str}\"/>")
print("</equality>")

print("\n分析完成！")