import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator

# 1. 数据加载和预处理
def load_and_preprocess(file_path):
    """加载数据并计算采样间隔"""
    data = pd.read_csv(file_path, header=None, names=['depth', 'logFe'])
    
    # 计算采样间隔(相邻深度的差值)
    depth_diff = np.diff(data['depth'])
    avg_sample_interval = np.mean(depth_diff)
    
    # 修正：在开头添加一个NaN使长度匹配
    data['sample_interval'] = np.insert(depth_diff, 0, np.nan)
    
    return data, avg_sample_interval

# 2. 创建带采样率标注的图表
def plot_depth_logFe(data, avg_interval):
    """绘制深度-logFe关系图并标注采样特性"""
    fig, ax = plt.subplots(figsize=(10, 8))
    
    # 主数据曲线
    # ax.plot(data['depth'], data['sample_interval'], 'b-', linewidth=1, label='logFe')

     # 梯形线绘制（阶梯状）
    ax.step(data['depth'], data['sample_interval'], 
           where='mid',
           color='b',
           linewidth=1.5,
           label='logFe (step)')
    
    # 标注采样点
    # ax.plot(data['logFe'], data['depth'], 'ro', markersize=4, alpha=0.5, label='Samples')
    
    # 设置坐标轴
    ax.set_xlabel('logFe Value', fontsize=12)
    ax.set_ylabel('Depth (ft)', fontsize=12)
    ax.set_title('Svalbard PETM - logFe Profile\nSampling Characteristics', fontsize=14, pad=20)
    ax.grid(True, linestyle='--', alpha=0.6)
    
    # 反转深度轴(地质常用表示方式)
    # ax.invert_yaxis()
    
    # 添加采样率信息
    textstr = '\n'.join((
        f'Total Samples: {len(data)}',
        f'Depth Range: {data["depth"].min():.1f} - {data["depth"].max():.1f} ft',
        f'Avg. Sampling Interval: {avg_interval:.2f} ft',
        f'Avg. Sampling Rate: {1/avg_interval:.2f} samples/ft'
    ))
    
    props = dict(boxstyle='round', facecolor='wheat', alpha=0.8)
    ax.text(0.05, 0.95, textstr, transform=ax.transAxes, 
            verticalalignment='center_baseline', bbox=props, fontsize=10)
    
    # 添加图例
    ax.legend(loc='lower right')
    
    # 美化坐标轴
    ax.xaxis.set_minor_locator(AutoMinorLocator())
    ax.yaxis.set_minor_locator(AutoMinorLocator())
    
    plt.tight_layout()
    return fig

# 主程序
if __name__ == "__main__":
    # 文件路径
    file_path = 'D:\\git\\acycle\\acyclePy\\Example-SvalbardPETM-logFe.txt'
    
    # 加载数据
    data, avg_interval = load_and_preprocess(file_path)
    
    # 检查长度是否匹配
    print(f"数据长度: {len(data)}")
    print(f"采样间隔长度: {len(data['sample_interval'].dropna())}")
    
    # 生成图表
    fig = plot_depth_logFe(data, avg_interval)
    
    # 保存和显示
    fig.savefig('SvalbardPETM_logFe_profile.png', dpi=300)
    plt.show()