优化温度序列波谷检测算法,精准计算波周期时长
优化温度序列主要波谷检测算法方案
核心问题
当前算法会误识别微小波谷,导致相邻波谷间时长计算引入噪声,需调整为仅识别能代表温度周期变化的主要波谷,最终输出包含波的起始时间、结束时间、时长的结构化数组。
现有代码示例
(模拟常见的简单波谷检测实现)
import numpy as np def detect_troughs(times, temps): troughs = [] for i in range(1, len(temps)-1): if temps[i] < temps[i-1] and temps[i] < temps[i+1]: troughs.append((times[i], temps[i])) return troughs # 计算相邻波谷间的波时长 def calculate_wave_durations(troughs): waves = [] for i in range(1, len(troughs)): start_time = troughs[i-1][0] end_time = troughs[i][0] duration = end_time - start_time waves.append({"start": start_time, "end": end_time, "duration": duration}) return waves
数据集示例
# 模拟温度序列:包含主要波谷和局部微小波动 times = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) temps = np.array([25, 23, 22, 24, 23, 21, 25, 24, 22, 23, 20, 24, 26])
优化方案:过滤次要波谷
1. 基于波谷深度过滤
设定最小深度阈值,仅保留比周围一定范围内温度低出阈值的波谷,过滤局部微小波动:
def detect_major_troughs(times, temps, depth_threshold=1.5, window_size=2): major_troughs = [] n = len(temps) for i in range(window_size, n - window_size): # 计算波谷前后window_size范围内的平均温度 surrounding_avg = np.mean(temps[i-window_size:i+window_size+1]) # 波谷深度 = 周围平均温度 - 当前波谷温度 trough_depth = surrounding_avg - temps[i] # 判断是否为局部最小值且深度达标 is_local_min = temps[i] < min(temps[i-window_size:i]) and temps[i] < min(temps[i+1:i+window_size+1]) if is_local_min and trough_depth >= depth_threshold: major_troughs.append((times[i], temps[i])) return major_troughs
2. 基于波谷间隔过滤
设定最小时间间隔阈值,过滤掉间隔过近的波谷,确保保留的波谷对应完整温度周期:
def filter_close_troughs(troughs, min_interval=3): filtered = [] last_time = -float('inf') for time, temp in troughs: if time - last_time >= min_interval: filtered.append((time, temp)) last_time = time return filtered
3. 完整优化流程
def get_major_waves(times, temps): # 1. 检测初步波谷 initial_troughs = detect_troughs(times, temps) # 2. 过滤深度不足的波谷 depth_filtered = detect_major_troughs(times, temps) # 3. 过滤间隔过近的波谷 final_troughs = filter_close_troughs(depth_filtered) # 4. 生成波的结构化数据 waves = calculate_wave_durations(final_troughs) return waves
期望输出样例
针对上述模拟数据集,优化后输出:
[ {"start": 2, "end": 5, "duration": 3}, {"start": 5, "end": 10, "duration": 5} ]
参数调整说明
depth_threshold:波谷深度阈值,可根据实际温度波动范围调整(如温度波动在5℃内,可设为1-2℃)window_size:计算周围平均温度的窗口大小,越大越能过滤局部微小波动min_interval:波谷最小时间间隔,根据业务中温度周期的大致时长设定
内容的提问来源于stack exchange,提问作者zahab
相关产品推荐
相关产品推荐

