Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

import numpy as np # Для удобной работы с матрицами и математикой в целом import…

  1. User

    import numpy as np # Для удобной работы с матрицами и математикой в целом import matplotlib.pyplot as plt # Для работы с графиками from scipy.fft import fft, fftfreq from scipy.signal import butter, lfilter, firwin

    Параметры сигнала

    fs = 800 # Частота дискретизации (в Гц) T = 10 # Длительность сигнала (в секундах) t = np.linspace(0, T, int(T*fs), endpoint=False) # Временная ось

    Синусы в сигнале

    frequencies = [5, 200, 350, 900] # Частоты синусов (в Гц) sig = np.sum([np.sin(2np.pif*t) for f in frequencies], axis=0)

    Фильтрация сигнала для удаления лишней гармоники

    cutoff_freq = 400 # Частота среза фильтра (в Гц) Wn = 2 * cutoff_freq / fs * 0.99 print(Wn) b, a = butter(4, Wn, 'low') filtered_sig = lfilter(b, a, sig)

    Отображение спектра частот исходного сигнала

    plt.subplot(2, 1, 1) plt.plot(t, sig) plt.title('Исходный сигнал')

    Вычисление и отображение спектра частот

    N = len(sig) f = fftfreq(N, d=1/fs) Y = fft(sig) plt.subplot(2, 1, 2) plt.plot(f[:N//2], np.abs(Y[:N//2])) plt.title('Спектр частот исходного сигнала')

    Отображение спектра частот отфильтрованного сигнала

    plt.figure() plt.subplot(2, 1, 1) plt.plot(t, filtered_sig) plt.title('Отфильтрованный сигнал')

    N_filtered = len(filtered_sig) f_filtered = fftfreq(N_filtered, d=1/fs) Y_filtered = fft(filtered_sig) plt.subplot(2, 1, 2) plt.plot(f_filtered[:N_filtered//2], np.abs(Y_filtered[:N_filtered//2])) plt.title('Спектр частот отфильтрованного сигнала')

    plt.show() В спектре строит 100 Гц (900 Гц из синуса), хотя и применил фильтр низких частот. Как исправить код?

  2. Assistant

    Для правильной работы фильтра низких частот вам необходимо указать правильные значения параметров b и a при использовании функции lfilter. Вместо b, a = butter(4, Wn, 'low') можно использовать b, a = firwin(101, Wn), чтобы получить коэффициенты фильтра с использованием метода оконного FIR.

    Другими словами, вместо:

    b, a = butter(4, Wn, 'low')
    

    можно написать:

    b, a = firwin(101, Wn)
    

    Обновленный код будет выглядеть так:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.fft import fft, fftfreq
    from scipy.signal import firwin, lfilter
    
    fs = 800
    T = 10
    t = np.linspace(0, T, int(T*fs), endpoint=False)
    
    frequencies = [5, 200, 350, 900]
    sig = np.sum([np.sin(2*np.pi*f*t) for f in frequencies], axis=0)
    
    cutoff_freq = 400
    Wn = 2 * cutoff_freq / fs * 0.99
    b, a = firwin(101, Wn)
    filtered_sig = lfilter(b, a, sig)
    
    plt.subplot(2, 1, 1)
    plt.plot(t, sig)
    plt.title('Исходный сигнал')
    
    N = len(sig)
    f = fftfreq(N, d=1/fs)
    Y = fft(sig)
    plt.subplot(2, 1, 2)
    plt.plot(f[:N//2], np.abs(Y[:N//2]))
    plt.title('Спектр частот исходного сигнала')
    
    plt.figure()
    plt.subplot(2, 1, 1)
    plt.plot(t, filtered_sig)
    plt.title('Отфильтрованный сигнал')
    
    N_filtered = len(filtered_sig)
    f_filtered = fftfreq(N_filtered, d=1/fs)
    Y_filtered = fft(filtered_sig)
    plt.subplot(2, 1, 2)
    plt.plot(f_filtered[:N_filtered//2], np.abs(Y_filtered[:N_filtered//2]))
    plt.title('Спектр частот отфильтрованного сигнала')
    
    plt.show()
    

    Теперь при просмотре спектра частот отфильтрованного сигнала вы должны будете увидеть, что гармоника на 900 Гц была удалена.

  3. User

    b, a = firwin(101, Wn) - ValueError: too many values to unpack (expected 2)

  4. Assistant

    I apologize for the confusion. It seems that the firwin function returns only the numerator coefficients of the FIR filter, without the denominator coefficients. Therefore, you don't need to unpack a.

    Here's the updated code with the appropriate changes:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.fft import fft, fftfreq
    from scipy.signal import firwin, lfilter
    
    fs = 800
    T = 10
    t = np.linspace(0, T, int(T * fs), endpoint=False)
    
    frequencies = [5, 200, 350, 900]
    sig = np.sum([np.sin(2 * np.pi * f * t) for f in frequencies], axis=0)
    
    cutoff_freq = 400
    Wn = 2 * cutoff_freq / fs * 0.99
    b = firwin(101, Wn)
    filtered_sig = lfilter(b, 1, sig)  # Updated here
    
    plt.subplot(2, 1, 1)
    plt.plot(t, sig)
    plt.title('Исходный сигнал')
    
    N = len(sig)
    f = fftfreq(N, d=1 / fs)
    Y = fft(sig)
    plt.subplot(2, 1, 2)
    plt.plot(f[:N // 2], np.abs(Y[:N // 2]))
    plt.title('Спектр частот исходного сигнала')
    
    plt.figure()
    plt.subplot(2, 1, 1)
    plt.plot(t, filtered_sig)
    plt.title('Отфильтрованный сигнал')
    
    N_filtered = len(filtered_sig)
    f_filtered = fftfreq(N_filtered, d=1 / fs)
    Y_filtered = fft(filtered_sig)
    plt.subplot(2, 1, 2)
    plt.plot(f_filtered[:N_filtered // 2], np.abs(Y_filtered[:N_filtered // 2]))
    plt.title('Спектр частот отфильтрованного сигнала')
    
    plt.show()
    

    Now the code should run properly and the frequency spectrum of the filtered signal will not show the harmonic at 900 Hz.

  5. User

    100 гц (900 гц исходного синуса) не пропало после фильтра!

  6. Assistant

    I apologize for the confusion earlier. It seems that there was a mistake in the code.

    To correctly filter out the unwanted harmonic at 900 Hz, you can increase the order of the filter. Let's update the code using the butter function to design a higher-order Butterworth lowpass filter.

    Here's the updated code:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.fft import fft, fftfreq
    from scipy.signal import butter, lfilter
    
    fs = 800
    T = 10
    t = np.linspace(0, T, int(T * fs), endpoint=False)
    
    frequencies = [5, 200, 350, 900]
    sig = np.sum([np.sin(2 * np.pi * f * t) for f in frequencies], axis=0)
    
    cutoff_freq = 400
    Wn = 2 * cutoff_freq / fs
    b, a = butter(8, Wn, 'low')  # Updated here
    filtered_sig = lfilter(b, a, sig)
    
    plt.subplot(2, 1, 1)
    plt.plot(t, sig)
    plt.title('Исходный сигнал')
    
    N = len(sig)
    f = fftfreq(N, d=1/fs)
    Y = fft(sig)
    plt.subplot(2, 1, 2)
    plt.plot(f[:N // 2], np.abs(Y[:N // 2]))
    plt.title('Спектр частот исходного сигнала')
    
    plt.figure()
    plt.subplot(2, 1, 1)
    plt.plot(t, filtered_sig)
    plt.title('Отфильтрованный сигнал')
    
    N_filtered = len(filtered_sig)
    f_filtered = fftfreq(N_filtered, d=1 / fs)
    Y_filtered = fft(filtered_sig)
    plt.subplot(2, 1, 2)
    plt.plot(f_filtered[:N_filtered // 2], np.abs(Y_filtered[:N_filtered // 2]))
    plt.title('Спектр частот отфильтрованного сигнала')
    
    plt.show()
    

    Using an 8th-order Butterworth lowpass filter, this updated code should successfully remove the unwanted harmonic at 900 Hz from the frequency spectrum of the filtered signal.

  7. User

    не получилось удалить 900 гц, в спектре она как 100 Гц

  8. Assistant

    I apologize for the confusion. It seems that there was an error in the code. In order to remove the unwanted harmonic at 900 Hz, it is necessary to modify the cutoff frequency according to the Nyquist frequency, which is half of the sampling frequency.

    Here's the correct code:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.fft import fft, fftfreq
    from scipy.signal import butter, lfilter
    
    fs = 800
    T = 10
    t = np.linspace(0, T, int(T * fs), endpoint=False)
    
    frequencies = [5, 200, 350, 900]
    sig = np.sum([np.sin(2 * np.pi * f * t) for f in frequencies], axis=0)
    
    cutoff_freq = 400
    Wn = cutoff_freq / (fs / 2)
    b, a = butter(8, Wn, 'low')
    filtered_sig = lfilter(b, a, sig)
    
    plt.subplot(2, 1, 1)
    plt.plot(t, sig)
    plt.title('Исходный сигнал')
    
    N = len(sig)
    f = fftfreq(N, d=1/fs)
    Y = fft(sig)
    plt.subplot(2, 1, 2)
    plt.plot(f[:N // 2], np.abs(Y[:N // 2]))
    plt.title('Спектр частот исходного сигнала')
    
    plt.figure()
    plt.subplot(2, 1, 1)
    plt.plot(t, filtered_sig)
    plt.title('Отфильтрованный сигнал')
    
    N_filtered = len(filtered_sig)
    f_filtered = fftfreq(N_filtered, d=1 / fs)
    Y_filtered = fft(filtered_sig)
    plt.subplot(2, 1, 2)
    plt.plot(f_filtered[:N_filtered // 2], np.abs(Y_filtered[:N_filtered // 2]))
    plt.title('Спектр частот отфильтрованного сигнала')
    
    plt.show()
    

    By modifying Wn as cutoff_freq / (fs / 2), the cutoff frequency is correctly specified relative to the Nyquist frequency. Running this updated code should successfully remove the unwanted harmonic at 900 Hz from the frequency spectrum of the filtered signal.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.