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
finger_names = ['食指', '中指', '无名指', '尾指']
pip_angles_deg = {}
for i, name in enumerate(finger_names):
    pip_angles_deg[name] = df.iloc[:, i+1].values

# 转换为弧度
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_deg.max():.2f}°\n")

# 获取MCP=0时的实际PIP值（弧度）
pip_at_zero_rad = {}
for name in finger_names:
    pip_at_zero_rad[name] = pip_angles_rad[name][0]

print("MCP=0时的实际PIP值（弧度）:")
for name in finger_names:
    print(f"  {name}: PIP = {pip_at_zero_rad[name]:.6f} rad = {pip_at_zero_rad[name]/DEG_TO_RAD:.2f}°")
print()

# 定义带固定截距的线性拟合函数
def linear_func_fixed_intercept(x, a, b_fixed):
    """线性函数: y = a*x + b_fixed (截距固定)"""
    return a * x + b_fixed

# 存储拟合结果
fitting_results = {}

# 对每个手指进行拟合（固定截距为MCP=0时的实际值）
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]
    x_data_rad = mcp_angles_rad
    b_fixed = pip_at_zero_rad[finger_name]  # 固定截距为MCP=0时的实际值
    
    # 只拟合斜率，截距固定
    # PIP = a*MCP + b_fixed
    # 转换为: PIP - b_fixed = a*MCP
    y_adjusted = y_data_rad - b_fixed
    
    # 使用最小二乘法直接计算斜率
    # a = sum((x - x_mean) * (y - y_mean)) / sum((x - x_mean)^2)
    x_mean = np.mean(x_data_rad)
    y_mean = np.mean(y_adjusted)
    numerator = np.sum((x_data_rad - x_mean) * (y_adjusted - y_mean))
    denominator = np.sum((x_data_rad - x_mean) ** 2)
    
    if denominator > 0:
        a = numerator / denominator
    else:
        a = 0.0
    
    # 计算拟合结果
    y_pred_rad = a * x_data_rad + b_fixed
    r2 = r2_score(y_data_rad, y_pred_rad)
    mae = np.mean(np.abs(y_data_rad - y_pred_rad))
    
    # 计算比例关系
    pip_change = y_data_rad[-1] - y_data_rad[0]
    mcp_change = x_data_rad[-1] - x_data_rad[0]
    ratio = pip_change / mcp_change if mcp_change > 0 else 0
    
    fitting_results[finger_name] = {
        'slope': a,
        'intercept': b_fixed,
        'r2': r2,
        'mae': mae,
        'ratio': ratio,
        'formula_rad': f"PIP(rad) = {a:.6f} * MCP(rad) + {b_fixed:.6f}"
    }
    
    print(f"线性拟合（固定截距）: {fitting_results[finger_name]['formula_rad']}")
    print(f"  R² = {r2:.6f}, MAE = {mae:.6f} rad")
    print(f"  比例关系: PIP变化/MCP变化 = {ratio:.6f}")
    print(f"  验证: 当MCP=0时, PIP = {b_fixed:.6f} rad = {b_fixed/DEG_TO_RAD:.2f}° (实际值)")

# 可视化结果
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]
        a = result['slope']
        b = result['intercept']
        
        # 生成平滑曲线
        x_smooth_rad = np.linspace(mcp_angles_rad.min(), mcp_angles_rad.max(), 200)
        y_smooth_rad = a * x_smooth_rad + b
        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"线性拟合 (R²={result['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")

# 生成用于MuJoCo XML的polycoef格式（4个系数）
print("\n" + "="*60)
print("MuJoCo XML格式的polycoef系数（4个值）")
print("="*60)
print("MuJoCo公式: PIP = a₀ + a₁*MCP + a₂*MCP² + a₃*MCP³")
print("polycoef格式: [a₀, a₁, a₂, a₃] (4个系数，弧度)")
print("注意: a₀固定为MCP=0时的实际PIP值\n")

# 输出XML格式的代码片段
print("<equality>")
print("  <!--  mimic distal -> proximal  -->")
print("  <!-- 基于实际数据拟合的线性关系（弧度）: PIP = a₀ + a₁*MCP -->")
print("  <!-- a₀固定为MCP=0时的实际PIP值，a₁为拟合斜率 -->")

for finger_name in finger_names:
    if finger_name in fitting_results:
        result = fitting_results[finger_name]
        a = result['slope']
        b = result['intercept']
        
        # 线性: PIP(rad) = a*MCP(rad) + b
        # polycoef = [b, a, 0, 0] (4个系数)
        polycoef = [b, a, 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(f"    <!-- {finger_name}: PIP = {b:.6f} + {a:.6f}*MCP, 比例={result['ratio']:.4f}, R²={result['r2']:.4f} -->")

print("</equality>")

print("\n" + "="*60)
print("系数验证（MCP=0时的PIP值）")
print("="*60)
for finger_name in finger_names:
    if finger_name in fitting_results:
        result = fitting_results[finger_name]
        pip_at_zero_rad = result['intercept']
        pip_at_zero_deg = pip_at_zero_rad / DEG_TO_RAD
        actual_pip_at_zero_deg = pip_angles_deg[finger_name][0]
        print(f"{finger_name}: 拟合值={pip_at_zero_deg:.2f}°, 实际值={actual_pip_at_zero_deg:.2f}° (应该完全一致)")

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