基础小波降噪方法(Python)

主要内容包括:

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 = nelse:res = n - 1return resdef std(trace, nlevel=5):"""Estimates the standard deviation of the input trace for rescalingthe Wavelet's coefficients.ReturnsStandard 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 sigmadef 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 samplesnum_samples = len(trace)# han et al thresholddetails_threshs = np.array([np.nan] * len(coeffs[1:]))# threshold for first detail coeff d_i=0details_threshs[0] = sigma[1] * np.sqrt(2 * np.log(num_samples))# threshold from 1 < d_i < NLEVELSfor 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 = nlevelsdetails_threshs[nlevels - 1] = (sigma[nlevels - 1] * np.sqrt(2 * np.log(num_samples))) / np.sqrt(nlevels - 1)return details_threshsdef 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  CurrentDload  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 parametersSFREQ = 16000nyquist = SFREQ / 2
# load datasettrace_01 = np.loadtxt(proj_path + "/dataset/data_01.txt")tmp_trace = trace_01.copy()# describeduration_secs = len(tmp_trace) / SFREQnum_samples = len(tmp_trace)print("duration:", duration_secs, "secs")print("number of samples:", num_samples)tmp_trace
duration: 90.0 secs
number of samples: 1440000array([-0.05265172, -0.03124187, -0.00282162, ...,  0.01798155,
0.01678863,  0.0119459 ])1. Parametrize
# TODO:# - implement Han et al., threshold# - clear approximation thresholdWAVELET = "haar"NLEVEL = 5THRESH = "han"  # "universal"THRESH_METHOD = "hard"  # 'soft'RECON_MODE = "zero"  # 'smooth', "symmetric", "antisymmetric", "zero", "constant", "periodic", "reflect",# calculate cutoff frequencyfreq_cutoff = nyquist / 2**NLEVEL  # cutoff frequency (the max of lowest freq. band)print("Cutoff frequency for high-pass filtering :", freq_cutoff, "Hz")
2. Preprocess# detrenddetrended = detrend(tmp_trace)# normalize datascaler = 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 lengthsize = NearestEvenInteger(normalized.shape[0])# initialize filterwavelet = 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 coefficientsprint("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 frequencyfig, 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.rhkb.cn/news/375772.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

《昇思25天学习打卡营第14天|SSD目标检测》

SSD&#xff08;Single Shot MultiBox Detector&#xff09;是一种用于目标检测的深度学习算法。它的设计旨在同时检测多个对象&#xff0c;并确定它们在图像中的位置和类别。与其他目标检测算法相比&#xff0c;SSD具有速度快和精度高的特点&#xff0c;在实时检测应用中非常受…

[Spring] Spring Web MVC基础理论

&#x1f338;个人主页:https://blog.csdn.net/2301_80050796?spm1000.2115.3001.5343 &#x1f3f5;️热门专栏: &#x1f9ca; Java基本语法(97平均质量分)https://blog.csdn.net/2301_80050796/category_12615970.html?spm1001.2014.3001.5482 &#x1f355; Collection与…

介绍一款数据准实时复制(CDC)中间件 `Debezium`

简介 文章开头先介绍一下什么是CDC。数据准实时复制(CDC)是目前行内实时数据需求大量使用的技术。常用的中间件有Canal、Debezium、Flink CDC等 下面我们做一下对比 各有优缺点吧,本主要介绍一下Debezium中间件。 Debezium是什么 Debezium是一个为变更数据捕获(CDC)提供…

Android Gantt View 安卓实现项目甘特图

需要做一个项目管理工具&#xff0c;其中使用到了甘特图。发现全网甘特图解决方案比较少&#xff0c;于是自动动手丰衣足食。 前面我用 Python和 Node.js 前端都做过&#xff0c;这次仅仅是移植到 Android上面。 其实甘特图非常简单&#xff0c;开发也不难&#xff0c;如果我…

Emacs有什么优点,用Emacs写程序真的比IDE更方便吗?

GPT-4o (OpenAI) Emacs 是一种强大的文本编辑器&#xff0c;自1970年代以来一直在计算机领域中使用。它的优势以及在编程方面的便捷性取决于特定用户的需求和使用习惯。以下是一些 Emacs 的主要优点及其与 IDE 的比较&#xff1a; 优点 1. 灵活性和可扩展性&#xff1a; -…

端到端拥塞控制的本质

昨天整理了一篇 bbr 的微分方程组建模(参见 bbr 建模)&#xff0c;算是 bbr 算法终极意义上的一个总结&#xff0c;最后也顺带了对 aimd 的描述&#xff0c;算是我最近比较满意的一篇分享了。那么接下来的问题&#xff0c;脱离出具体算法&#xff0c;上升到宏观层面&#xff0c…

【游戏客户端】大话slg玩法架构(三)建筑控件

【游戏客户端】大话slg玩法架构&#xff08;三&#xff09;建筑控件 大家好&#xff0c;我是Lampard家杰~~ 今天我们继续给大家分享SLG玩法的实现架构&#xff0c;关于SLG玩法的介绍可以参考这篇上一篇文章&#xff1a;【游戏客户端】制作率土之滨Like玩法 PS&#xff1a;和之前…

JVM学习(day1)

JVM 运行时数据区 线程共享&#xff1a;方法区、堆 线程独享&#xff08;与个体“同生共死”&#xff09;&#xff1a;虚拟机栈、本地方法栈、程序计数器 程序计数器 作用&#xff1a;记录下次要执行的代码行的行号 特点&#xff1a;为一个没有OOM&#xff08;内存溢出&a…

电压反馈型运算放大器的增益和带宽

简介 本教程旨在考察标定运算放大器的增益和带宽的常用方法。需要指出的是&#xff0c;本讨论适用于电压反馈(VFB)型运算放大器。 开环增益 与理想的运算放大器不同&#xff0c;实际的运算放大器增益是有限的。开环直流增益(通常表示为AVOL)指放大器在反馈环路未闭合时的增益…

Python爬虫技术从去哪儿网获取旅游数据,对攻略进行可视化分析,提供全面的旅游攻略和个性化的出行建议

背景 随着信息技术的快速发展和互联网的普及&#xff0c;旅游行业也迎来了数字化和智能化的变革。去哪儿网作为中国领先的在线旅游平台之一&#xff0c;提供了丰富的旅游产品和服务&#xff0c;涵盖了机票、酒店、旅游度假等各个方面。用户通过去哪儿网可以方便地查询、预订和…

Mac下flutter运行iOS模拟器

上篇flutter环境安装&#xff08;Macvscode&#xff09;已经将vscode和xcode等开发环境都搭建起来了&#xff0c;vscode新建工程还是比较方便的&#xff0c;那么&#xff0c;建立好了之后&#xff0c;我们怎么看效果呢&#xff1f; 1. vscode新建项目 通过 vscode的命令命板(…

经典电影的高清修复是怎么实现的?

老片修复&#xff0c;主要分两种。精修版和流水线版。精修版比如像《星球大战》那种。基本就是一个专业团队花几年时间&#xff0c;不干别的就盯着这一个项目死磕。细致程度差不多就是一帧一帧进行修复。那对于我们普通人来说&#xff0c;想要修复视频高清&#xff0c;这种精修…

七天.NET 8操作SQLite入门到实战 - 第二天 在 Windows 上配置 SQLite环境

前言 SQLite的一个重要的特性是零配置的、无需服务器&#xff0c;这意味着不需要复杂的安装或管理。它跟微软的Access差不多&#xff0c;只是一个.db格式的文件。但是与Access不同的是&#xff0c;它不需要安装任何软件&#xff0c;非常轻巧。 七天.NET 8操作SQLite入门到实战…

Java常用的API_02(正则表达式、爬虫)

Java正则表达式 七、正则表达式7.1 格式7.1.1 字符类注意字符类示例代码1例2 7.1.2 预定义字符预定义字符示例代码例2 7.1.3 区别总结 7.2 使用Pattern和Matcher类与直接使用String类的matches方法的区别。&#xff08;1&#xff09; 使用Pattern和Matcher类示例代码 &#xff…

传输层协议之UDP

1、端口号 我们在应用层创建的套接字&#xff0c;是需要通过bind()接口绑定我们的IP地址与端口号的&#xff0c;这是因为数据从传输层向上交付到应用层时&#xff0c;需要用端口号来查找特定的服务进程。一般在网络通信时&#xff0c;用IP地址标识一台主机&#xff0c;用端口号…

el-table 动态添加删除 -- 鼠标移入移出显隐删除图标

<el-table class"list-box" :data"replaceDataList" border><el-table-column label"原始值" prop"original" align"center" ><template slot-scope"scope"><div mouseenter"showClick…

Kubelet 认证

当我们执行kubectl exec -it pod [podName] sh命令时&#xff0c;apiserver会向kubelet发起API请求。也就是说&#xff0c;kubelet会提供HTTP服务&#xff0c;而为了安全&#xff0c;kubelet必须提供HTTPS服务&#xff0c;且还要提供一定的认证与授权机制&#xff0c;防止任何知…

Bertopic环境安装与文本主题聚类

文章目录 1.环境配置(一)安装:anaconda1. 理解:为什么需要anaconda2. 下载anaconda3. 启动anaconda(二)安装:python环境(三)安装:依赖包hdbscan的安装问题解决方案1. 安装build-tools-for-visual-studio2. 安装hdbscan(四)安装transformers、BERTopic等重要依赖包2…

FlinkModule加载HiveModule异常

HiveModule这个模块加载不出来 加在不出来这个模块&#xff0c;网上查说是要加下面这个依赖 <dependency><groupId>org.apache.flink</groupId><artifactId>flink-connector-hive_${scala.binary.version}</artifactId><version>${flink.…

GPIO通用输入输出口

可配置八种输入输出模式&#xff1b; 引脚电平&#xff1a;0~3.3V&#xff0c;部分引脚可容忍5V&#xff1b;&#xff08;可以输入5V&#xff0c;输出最大只能是3.3V&#xff09; 带FT的是可以容忍5V的不带FT的就只能接入3.3V的电压。 输出模式下可以控制端口输出高低电平&am…