基础小波降噪方法(Python)

news2024/11/15 11:16:38

主要内容包括:

Stationary wavelet Transform (translation invariant)

Haar wavelet

Hard thresholding of detail coefficients

Universal threshold

High-pass filtering by zero-ing approximation coefficients from a 5-level decomposition of a 16Khz sampling freq.

import numpy as np
import os
from scipy.signal import detrend
from sklearn.preprocessing import MinMaxScaler
from pywt import Wavelet, threshold, wavedec, waverec
import pywt
from matplotlib import pyplot as plt
from scipy import signal

Create custom functions

def NearestEvenInteger(n):
    """! Returns the nearest even integer to number n.


    @param n Input number for which one requires the nearest even integer


    @return The even nearest integer to the input number
    """
    if n % 2 == 0:
        res = n
    else:
        res = n - 1
    return res




def std(trace, nlevel=5):
    """Estimates the standard deviation of the input trace for rescaling
    the Wavelet's coefficients.


    Returns
        Standard deviation of the input trace as (1D ndarray)
    """
    sigma = np.array([1.4825 * np.median(np.abs(trace[i])) for i in range(nlevel)])
    return sigma




def mad(x):
    """Mean absolute deviation"""
    return 1.482579 * np.median(np.abs(x - np.median(x)))




def get_universal_threshold(trace):
    num_samples = len(trace)
    sd = mad(trace)
    return sd * np.sqrt(2 * np.log(num_samples))




def get_han_threshold(trace: np.array, sigma: np.array, coeffs: np.array, nlevels: int):


    # count samples
    num_samples = len(trace)


    # han et al threshold
    details_threshs = np.array([np.nan] * len(coeffs[1:]))


    # threshold for first detail coeff d_i=0
    details_threshs[0] = sigma[1] * np.sqrt(2 * np.log(num_samples))


    # threshold from 1 < d_i < NLEVELS
    for d_i in range(1, nlevels - 1):
        details_threshs[d_i] = (sigma[d_i] * np.sqrt(2 * np.log(num_samples))) / np.log(
            d_i + 1
        )
    # threhsold for d_i = nlevels
    details_threshs[nlevels - 1] = (
        sigma[nlevels - 1] * np.sqrt(2 * np.log(num_samples))
    ) / np.sqrt(nlevels - 1)
    return details_threshs




def determine_threshold(
    trace: np.array,
    threshold: str = "han",
    sigma: np.array = None,
    coeffs: np.array = None,
    nlevels: int = None,
):
    if threshold == "universal":
        thr = get_universal_threshold(trace)
    elif threshold == "han":
        thr = get_han_threshold(trace, sigma, coeffs, nlevels)
    else:
        raise NotImplementedError("Choose an implemented threshold!")
    return thr

Load Quiroga's dataset

# download simulated dataset 01
!curl -o ../dataset/data_01.txt http://www.spikesorting.com/Data/Sites/1/download/simdata/Quiroga/01%20Example%201%20-%200-05/data_01.txt


# get project path
os.chdir("../")
proj_path = os.getcwd()
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0100 37.0M  100 37.0M    0     0  26.1M      0  0:00:01  0:00:01 --:--:-- 26.1M# dataset parameters

SFREQ = 16000

nyquist = SFREQ / 2
# load dataset

trace_01 = np.loadtxt(proj_path + "/dataset/data_01.txt")

tmp_trace = trace_01.copy()




# describe

duration_secs = len(tmp_trace) / SFREQ

num_samples = len(tmp_trace)

print("duration:", duration_secs, "secs")

print("number of samples:", num_samples)




tmp_trace
duration: 90.0 secs
number of samples: 1440000

array([-0.05265172, -0.03124187, -0.00282162, ...,  0.01798155,
0.01678863,  0.0119459 ])1. Parametrize
# TODO:

# - implement Han et al., threshold

# - clear approximation threshold




WAVELET = "haar"

NLEVEL = 5

THRESH = "han"  # "universal"

THRESH_METHOD = "hard"  # 'soft'

RECON_MODE = "zero"  # 'smooth', "symmetric", "antisymmetric", "zero", "constant", "periodic", "reflect",




# calculate cutoff frequency

freq_cutoff = nyquist / 2**NLEVEL  # cutoff frequency (the max of lowest freq. band)

print("Cutoff frequency for high-pass filtering :", freq_cutoff, "Hz")
2. Preprocess# detrend

detrended = detrend(tmp_trace)




# normalize data

scaler = MinMaxScaler(feature_range=(0, 1), copy=True)

detrended = scaler.fit_transform(detrended.reshape(-1, 1))[:, 0]

normalized = detrended.copy()
3. Wavelet transform
# find the nearest even integer to input signal's length

size = NearestEvenInteger(normalized.shape[0])




# initialize filter

wavelet = Wavelet(WAVELET)




# compute Wavelet coefficients

# coeffs = wavedec(normalized[:size], wavelet, level=NLEVEL)




# translation-invariance modification of the Discrete Wavelet Transform

# that does not decimate coefficients at every transformation level.

coeffs = pywt.swt(normalized[:size], wavelet, level=NLEVEL, trim_approx=True)

coeffs_raw = coeffs.copy()




# print approximation and details coefficients

print("approximation coefficients:", coeffs_raw[0])

print("details coefficients:", coeffs_raw[1:])approximation coefficients: [2.83647772 2.84106911 2.84452235 ... 2.83109023 2.83292184 2.83465441]
details coefficients: [array([-0.00950856, -0.00603211, -0.00248562, ..., -0.01120825,
       -0.0104237 , -0.00988739]), array([-0.01276296,  0.00053794,  0.0101203 , ..., -0.03684457,
       -0.03087185, -0.02255869]), array([-0.0351023 , -0.02894606, -0.01932213, ..., -0.00506488,
       -0.019433  , -0.0299413 ]), array([-0.01386091, -0.01500663, -0.01406618, ...,  0.00959663,
        0.01430558, -0.00087641]), array([-0.00386154, -0.00512596, -0.00548882, ...,  0.00021516,
        0.00087345,  0.01160962])]4. Denoise
THRESH = "han"


# estimate the wavelet coefficients standard deviations
sigma = std(coeffs[1:], nlevel=NLEVEL)


# determine the thresholds of the coefficients per level ('universal')
# threshs = [
#     determine_threshold(
#         trace=coeffs[1 + level] / sigma[level],
#         threshold=THRESH,
#         sigma=sigma,
#         coeffs=coeffs,
#         nlevels=NLEVEL,
#     )
#     * sigma[level]
#     for level in range(NLEVEL)
# ]


# determine the thresholds of the coefficients per level ('han')
threshs = get_han_threshold(
    trace=tmp_trace,
    sigma=sigma,
    coeffs=coeffs,
    nlevels=NLEVEL,
)


# a list of 5 thresholds for "universal"
# apply the thresholds to the detail coeffs
coeffs[1:] = [
    threshold(coeff_i, value=threshs[i], mode=THRESH_METHOD)
    for i, coeff_i in enumerate(coeffs[1:])
]
# reconstruct and reverse normalize
# denoised_trace = waverec(coeffs, filter, mode=RECON_MODE)
# denoised_trace = scaler.inverse_transform(denoised_trace.reshape(-1, 1))[:, 0]


# reconstruct and reverse normalize
denoised_trace = pywt.iswt(coeffs, wavelet)
denoised_trace = scaler.inverse_transform(denoised_trace.reshape(-1, 1))[:, 0]

5. High-pass filter

# clear approximation coefficients (set to 0)
coeffs[0] = np.zeros(len(coeffs[0]))


# sanity check
assert sum(coeffs[0]) == 0, "not cleared"

6. Reconstruct trace

# reconstruct and reverse normalize
# denoised_trace = waverec(coeffs, filter, mode=RECON_MODE)
# denoised_trace = scaler.inverse_transform(denoised_trace.reshape(-1, 1))[:, 0]


# reconstruct and reverse normalize
denoised_trace = pywt.iswt(coeffs, wavelet)
denoised_trace = scaler.inverse_transform(denoised_trace.reshape(-1, 1))[:, 0]

Plot

fig = plt.figure(figsize=(10, 5))


# raw
ax = fig.add_subplot(211)
ax.plot(tmp_trace[200:800])
ax.set_title("Raw signal")


# denoised
ax = fig.add_subplot(212)
ax.plot(denoised_trace[200:800])
ax.set_title("Denoised signal")


plt.tight_layout()

Power spectrum

fs = 16e3  # 16 KHz sampling frequency


fig, axes = plt.subplots(1, 2, figsize=(10, 3))


# Welch method
freqs, powers = signal.welch(tmp_trace, fs, nperseg=1024)
axes[0].plot(freqs, powers)
axes[0].semilogy(basex=10)
axes[0].semilogx(basey=10)
axes[0].set_xlabel("frequency [Hz]")
axes[0].set_ylabel("PSD [V**2/Hz]")




# Welch method
freqs, powers = signal.welch(denoised_trace, fs, nperseg=1024)
axes[1].plot(freqs, powers)
axes[1].semilogy(basex=10)
axes[1].semilogx(basey=10)
axes[1].set_ylim([1e-12, 1e-4])
axes[1].set_xlabel("frequency [Hz]")
axes[1].set_ylabel("PSD [V**2/Hz]")


plt.tight_layout()


擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。
知乎学术咨询:https://www.zhihu.com/consult/people/792359672131756032?isMe=1
擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1925019.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

win10系统更新后无法休眠待机或者唤醒,解决方法如下

是否使用鼠标唤醒 是否使用鼠标唤醒 是否使用键盘唤醒

【Java开发实训】day03——方法的注意事项

目录 一、方法的基本概念 二、void和return关键字 三、单一返回点原则 四、static方法使用说明 &#x1f308;嗨&#xff01;我是Filotimo__&#x1f308;。很高兴与大家相识&#xff0c;希望我的博客能对你有所帮助。 &#x1f4a1;本文由Filotimo__✍️原创&#xff0c;首发于…

《Windows API每日一练》9.25 系统菜单

/*------------------------------------------------------------------------ 060 WIN32 API 每日一练 第60个例子POORMENU.C&#xff1a;使用系统菜单 GetSystemMenu函数 AppendMenu函数 (c) www.bcdaren.com 编程达人 -------------------------------------------…

Java02--基础概念

一、注释 注释是在程序指定位置添加的说明性信息 简单理解&#xff0c;就是对代码的一种解释 1.单行注释 格式: //注释信息 2.多行注释 格式: /*注释信息*/ 3.文档注释 格式: /**注释信息*/ 注释使用的细节: 注释内容不会参与编译和运…

九盾安防丨如何判断叉车是否超速?

在现代物流和生产流程中&#xff0c;叉车是提高效率和降低成本的关键工具。然而&#xff0c;叉车的高速行驶也带来了安全隐患&#xff0c;这就要求我们对其进行严格的安全管理。九盾安防&#xff0c;作为业界领先的安防专家&#xff0c;今天就为大家揭晓如何判断叉车是否超速&a…

OpenCV距离变换函数distanceTransform的使用

操作系统&#xff1a;ubuntu22.04OpenCV版本&#xff1a;OpenCV4.9IDE:Visual Studio Code编程语言&#xff1a;C11 功能描述 distanceTransform是OpenCV库中的一个非常有用的函数&#xff0c;主要用于计算图像中每个像素到最近的背景&#xff08;通常是非零像素到零像素&…

VMware_centos8安装

目录 VMware Workstation Pro的安装 安装centos VMware Workstation Pro的安装 正版VMware 17百度网盘下载链接 (含秘钥) 链接&#xff1a;https://pan.baidu.com/s/16zB-7IAACM_1hwR1nsk12g?pwd1111 提取码&#xff1a;1111 第一次运行会要求输入秘钥 秘钥在上边的百度网盘…

【Leetcode】最小数字游戏

你有一个下标从 0 开始、长度为 偶数 的整数数组 nums &#xff0c;同时还有一个空数组 arr 。Alice 和 Bob 决定玩一个游戏&#xff0c;游戏中每一轮 Alice 和 Bob 都会各自执行一次操作。游戏规则如下&#xff1a; 每一轮&#xff0c;Alice 先从 nums 中移除一个 最小 元素&…

docker安装nginx并配置https

参考 docker安装nginx并配置https-腾讯云开发者社区-腾讯云 (tencent.com) 证书的生成 参见&#xff1a;SpringBoot项目配置HTTPS接口的安全访问&#xff08;openssl配置&#xff09;_配置接口访问-CSDN博客 步骤 1: 拉取Nginx镜像 docker pull nginx 好使的镜像如下&#x…

DockerCompose拉取DockerHub镜像,并部署OpenMetaData

参考博主&#xff1a;http://t.csdnimg.cn/i49ET 一、DockerCompose拉取DockerHub镜像 方法一&#xff08;不太行&#xff09;&#xff1a; 在daemon.json文件中添加一些国内还在服务的镜像站&#xff08;可能某些镜像会没有&#xff09; ([ -f /etc/docker/daemon.json ] ||…

RK3568笔记三十五:LED驱动开发测试

若该文为原创文章&#xff0c;转载请注明原文出处。 字符设备驱动程序的基本框架&#xff0c;主要是如何申请及释放设备号、添加以及注销设备&#xff0c;初始化、添加与删除 cdev 结构体&#xff0c;并通过 cdev_init 函数建立 cdev 和 file_operations 之间的关联&#xff0c…

每日一练:奇怪的TTL字段(python实现图片操作实战)

打开图片&#xff0c;只有四种数字&#xff1a;127&#xff0c;191&#xff0c;63&#xff0c;255 最大数字为255&#xff0c;想到进制转换 将其均转换为二进制&#xff1a; 发现只有前2位不一样 想着把每个数的前俩位提取出来&#xff0c;组成新的二进制&#xff0c;然后每…

Python中的数据容器及其在大数据开发中的应用

在Python编程中&#xff0c;数据容器是存储和组织数据的基本工具。作为大数据开发者&#xff0c;了解并灵活运用各种容器类型对于高效处理大规模数据至关重要。今天&#xff0c;我们将从Set出发&#xff0c;探讨Python中的各种数据容器&#xff0c;以及它们在大数据处理中的应用…

社交App iOS审核中的4.3问题:深入分析与解决策略

社交App审核中的4.3问题&#xff1a;深入分析与解决策略 在iOS应用开发和审核过程中&#xff0c;开发者经常会遇到苹果审核4.3问题。这一问题往往涉及应用的设计和内容重复性&#xff0c;导致应用被拒绝上架。为了帮助开发者更好地理解和解决这一问题&#xff0c;本文将对4.3问…

基于复旦微JFMQL100TAI的全国产化FPGA+AI人工智能异构计算平台,兼容XC7Z045-2FFG900I

基于上海复旦微电子FMQL45T900的全国产化ARM核心板。该核心板将复旦微的FMQL45T900&#xff08;与XILINX的XC7Z045-2FFG900I兼容&#xff09;的最小系统集成在了一个87*117mm的核心板上&#xff0c;可以作为一个核心模块&#xff0c;进行功能性扩展&#xff0c;能够快速的搭建起…

C语言操作符优先级

1 C语言操作符优先级 熟悉操作符的优先级&#xff0c;避免意外的求值顺序。 2. 运算符优先级记忆方法 利用优先级表或常见记忆口诀来记忆运算符的优先级。

嵌入式人工智能应用-篇外-烧写说明

1 外部接线 1.1 前期准备 需要准备的工具 ⚫ 一根 Mini USB 线 ⚫ 嵌入式人工智能教学科研平台 ⚫ 12V DC 电源 ⚫ 一台电脑 1.2 接线 12V DC 电源接入 12V IN&#xff1b;Mini USB 线连接 USB OTG&#xff1b;如果有两条 Mini USB 线&#xff0c;可以接入 UART2 to USB 口…

python2

一、条件语句 具体有如下&#xff1a;if、if......elif、if......elif......else 注意格式&#xff1a; if后面的条件表达式没有&#xff08;&#xff09;&#xff0c;以&#xff1a;作为结尾对于多分支的条件&#xff0c;不是写成else if 而是elif注意条件下一行要有缩进 …

Stable Diffusion 使用

目录 背景 最简单用法 进阶用法 高手用法 safetensor 一、概述 二、主要特点 背景 Stable Diffusion 开源后&#xff0c;确实比较火&#xff0c;上次介绍了下 Stable Diffusion 最简单的concept。今天继续介绍下&#xff0c;以Liblib 为例&#xff0c;介绍下如何使用参…

排序——交换排序

在上篇文章我们详细介绍了排序的概念与插入排序&#xff0c;大家可以通过下面这个链接去看&#xff1a; 排序的概念及插入排序 这篇文章就介绍一下一种排序方式&#xff1a;交换排序。 一&#xff0c;交换排序 基本思想&#xff1a;两两比较&#xff0c;如果发生逆序则交换…