# -*- coding: utf-8 -*-
# @Time    : 13/12/2024 16.53
# @Author  : ljc
# @FileName: convol.py
# @Software: PyCharm


# 1. 简介
"""
 Python conversion of the IDL convol .
目的:
    降低 TGM 光谱的分辨率.
函数:
    1) convol
解释:
    1) convol 函数: 降低 TGM 光谱的分辨率.
"""


# 2. 导库
import numpy as np
from scipy.signal import convolve
import warnings
warnings.filterwarnings("ignore")


# 3. 降低光谱分别率
def convol(models, losvd) -> np.ndarray:

    """
      降低 TGM 光谱的分辨率.

      输入参数:
      -----------
      models:
             TGM 光谱, 即待降低分辨率的光谱.
      losvd:
            由 losvd 参数生成的核, 用来与 TGM 光谱卷积.

      输出参数:
      -----------
      result:
             低分辨光谱.
    """

    # 3.1 判断 losvd 参数生成的核长度是偶数还是奇数
    # 1) 偶数: 对 TGM 光谱两端填充 1, 左侧填充 len(losvd) // 2 个 1、右侧填充 len(losvd) // 2 - 1 个 1
    # 2) 奇数: 对 TGM 光谱两端填充 1, 两侧均是 (len(losvd) - 1) // 2 个 1
    if len(losvd) % 2 == 0:
        # 3.1.1 偶数
        pad_left = len(losvd) // 2
        pad_right = len(losvd) // 2 - 1
    else:
        # 3.1.2 奇数
        pad_left = pad_right = (len(losvd) - 1) // 2
    
    # 3.2 TGM 光谱的两端填充 1
    padded = np.pad(models.reshape(-1), (pad_left, pad_right), mode='edge')
    
    # 3.3 使用 scipy 降低分辨率
    result = convolve(padded, losvd[::-1], mode='valid')

    # 3.4 返回低分辨率光谱
    return result.reshape(-1, 1)


# 4. 测试：与 IDL 结果一致
# models = np.arange(5)
# losvd = np.arange(3)
# result = convol(models, losvd)
# print(result)

# models = np.array([1.0, 2.0, 3.0, 4.0, 1])
# losvd = np.array([0.0, 1.0, 1.2])
# result = convol(models, losvd)
# print(result)

# models = np.array([2.0, 1.0, 1.1, 6.0, 2.1])
# losvd = np.array([1.0, 2.0, 1.2])
# result = convol(models, losvd)
# print(result)