You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何快速测量numpy数组中信号的上升时间(含失败判定)

高效计算Numpy数组的上升时间(含回落判断)

直接用Numpy的向量化操作替代Python循环,能大幅提升处理数千个数组的效率,以下是实现方案:

核心逻辑

我们需要:

  1. 定位信号首次接近0(起始阈值)的时刻
  2. 定位信号首次达到0.9的时刻
  3. 判断信号是否出现回落至接近0(如≤0.5)的情况,满足则标记为-1
  4. 正常情况返回上升时间(索引差×1ps)

实现代码

import numpy as np

def calculate_rise_time(voltage, start_thresh=0.05, rise_thresh=0.9, fall_thresh=0.5):
    # 找到首次超过起始阈值的索引(避开初始噪声)
    start_indices = np.where(voltage >= start_thresh)[0]
    if len(start_indices) == 0:
        return -1
    
    start_idx = start_indices[0]
    # 找起始点之后首次达到0.9的索引
    rise_segment = voltage[start_idx:]
    rise_indices = np.where(rise_segment >= rise_thresh)[0]
    
    # 未达到0.9,直接标记失败
    if len(rise_indices) == 0:
        return -1
    
    rise_idx = start_idx + rise_indices[0]
    # 检查达到0.9后是否回落至阈值以下
    if np.any(voltage[rise_idx:] <= fall_thresh):
        return -1
    
    # 计算上升时间(时间步长1ps,索引差即为时间)
    return (rise_idx - start_idx) * 1

批量处理数千个数组

如果你的数组是二维结构(每行对应一个信号数组),可以用np.apply_along_axis批量计算:

# 示例:生成1000个信号数组,每个含100个时间步
voltages = np.random.rand(1000, 100)
# 手动构造部分异常数据模拟回落情况
voltages[0] = np.linspace(0, 1, 100)  # 正常上升
voltages[1] = np.concatenate([np.linspace(0, 0.6, 50), np.linspace(0.6, 0, 50)])  # 未到0.9就回落
voltages[2] = np.concatenate([np.linspace(0, 0.9, 60), np.linspace(0.9, 0.4, 40)])  # 到0.9后回落

# 批量计算所有数组的上升时间
rise_times = np.apply_along_axis(calculate_rise_time, axis=1, arr=voltages)

关键优化点

  • 向量化操作:np.where和np.any都是底层C实现的向量化函数,比Python循环快10~100倍
  • 避免冗余计算:只在起始点之后的片段中查找0.9阈值,减少计算量
  • 灵活阈值:可以根据实际信号噪声调整start_thresh(起始阈值)和fall_thresh(回落阈值)

测试示例

# 正常信号
normal_volt = np.array([0, 0.1, 0.3, 0.6, 0.9, 0.95, 1.0])
print(calculate_rise_time(normal_volt))  # 输出3(对应3ps)

# 未到0.9就回落
fall_early = np.array([0, 0.2, 0.4, 0.3, 0.1, 0.0])
print(calculate_rise_time(fall_early))  # 输出-1

# 到0.9后回落
fall_late = np.array([0, 0.2, 0.5, 0.8, 0.9, 0.8, 0.4, 0.1])
print(calculate_rise_time(fall_late))  # 输出-1

内容的提问来源于stack exchange,提问作者User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 01:52:10