scipy 在C#中使用高通滤波器

wbrvyc0a  于 2023-08-05  发布在  C#
关注(0)|答案(1)|浏览(185)

我生成了10秒的1 Hz正弦波形。我把它通过一个截止频率为3 Hz的二阶高通滤波器。我把它们保存到CSV。我用Python把它们画出来了。但它几乎没有减弱。我做错了什么?我在Python中尝试了一个类似的过程,它被削弱了。
我用这个。
https://filtering.mathdotnet.com/api/MathNet.Filtering/OnlineFilter.htm#CreateHighpass
也许我应该使用ImpulseResponse.Infinite而不是ImpulseResponse.Finite。但是当我使用它时,值不断增加,我没有得到衰减的正弦波形。
但也许我应该用这个。
https://filtering.mathdotnet.com/api/MathNet.Filtering.Butterworth/IirCoefficients.htm#HighPass
如果我给予以下每个参数,我应该如何替换当前代码?

stopbandFreq = 1.0
passbandFreq = 4.0
passbandRipple = 1.0
stopbandAttenuation = -20.0

字符串

用C#编码

using System;
using MathNet.Filtering;
using MathNet.Numerics;
using System.IO;
using System.Globalization;

class Program
{
    const double sampleFreq = 600;
    const double amplitude = 100;
    const double frequency = 1;
    const double duration = 10;
    const double samplePeriod = 1.0 / sampleFreq;
    const double cutOffFrequency = 3;
    const int filterOrder = 2;

    static void Main(string[] args)
    {
        var sampleCount = sampleFreq * duration;
        var signal = Generate.Sinusoidal((int)sampleCount, sampleFreq, frequency, amplitude);

        var filter = OnlineFilter.CreateHighpass(ImpulseResponse.Finite, sampleFreq, cutOffFrequency, filterOrder);
        var filteredSignal = filter.ProcessSamples(signal);

        string path = "data_csharp.csv";
        string header = "Time,RawData_uV,FilteredRawData_uV";

        using (StreamWriter sw = new StreamWriter(path))
        {
            sw.WriteLine(header);
            for (int i = 0; i < sampleCount; i++)
            {
                DateTime datetime = DateTime.Now.AddSeconds(i * samplePeriod);
                sw.WriteLine(String.Format("{0},{1},{2}", datetime.ToString("yyyy/MM/dd HH:mm:ss.fff", CultureInfo.CurrentCulture), signal[i], filteredSignal[i]));
            }
        }
    }
}

Python代码

import numpy as np
from scipy import signal
import pandas as pd
from datetime import datetime, timedelta
# from matplotlib import pyplot as plt

def generate_dummy_signal(frequency, amplitude, duration, sample_rate):
    time = np.arange(0, duration, 1/sample_rate)
    signal = amplitude * np.sin(2 * np.pi * frequency * time)
    return time, signal

def apply_hpf(input_signal, cutoff_frequency, sample_rate, order):
    b, a = signal.butter(order, cutoff_frequency, btype='high', analog=False, fs=sample_rate)
    filtered_signal = signal.lfilter(b, a, input_signal)
    return filtered_signal

# Constants
FREQUENCY = 1  # in Hz
AMPLITUDE = 100  # in µV
DURATION = 10  # in seconds
SAMPLE_RATE = 600  # in Hz
CUTOFF_FREQUENCY = 3  # in Hz
ORDER = 2  # order of the filter

# Generate the dummy signal
time, raw_signal = generate_dummy_signal(FREQUENCY, AMPLITUDE, DURATION, SAMPLE_RATE)

# Apply the HPF
filtered_signal = apply_hpf(raw_signal, CUTOFF_FREQUENCY, SAMPLE_RATE, ORDER)

# Generate time-series starting from current timestamp
timestamps = [datetime.now() + timedelta(seconds=time[i]) for i in range(len(time))]

# Create dictionary for creating DataFrame
data_dict = {
    'Time': timestamps,
    'RawData_uV': raw_signal,
    'FilteredRawData_uV': filtered_signal
}

# Create DataFrame
data_df = pd.DataFrame(data_dict)

# Write DataFrame to CSV
data_df.to_csv('data.csv', index=False)

C生成csv #Python图形


的数据

C#生成csv(Infinite)用Python绘制


Python生成的csv用Python绘制


e37o9pze

e37o9pze1#

最后,我使用以下方法完成了HPF。有点太弱了,但我能减弱它。

//var filter = OnlineFilter.CreateHighpass(ImpulseResponse.Infinite, sampleFreq, cutOffFrequency, filterOrder);
        //var filteredSignal = filter.ProcessSamples(signal);

        var passBandFreq = 4 / (sampleFreq / 2.0);
        var stopBandFreq = 1 / (sampleFreq / 2.0);
        var passBandRipple = 1.0;
        var stopBandAttenuation = 20.0;
        var coefficients = MathNet.Filtering.Butterworth.IirCoefficients.HighPass(stopBandFreq, passBandFreq, passBandRipple, stopBandAttenuation);

        var coeffs = new List<double>();
        foreach (var numerator in coefficients.numerator)
        {
            coeffs.Add(numerator);
        }
        foreach (var denominator in coefficients.denominator)
        {
            coeffs.Add(denominator);
        }
        var filter = new MathNet.Filtering.IIR.OnlineIirFilter(coeffs.ToArray());
        var filteredSignal = filter.ProcessSamples(signal);

字符串

相关问题