1

so I've been trying to implement a low pass filter in C# with the Mathnet filtering library. I have a problem because I don't know how to use the method to create coefficients for the filter. Can someone tell me how to specify the cutoff frequency(it has to be in samples per unit)? For example, if I want the cutoff frequency to be 400Hz, how much is that in samples per unit? Thanks.

public Filter(ISampleProvider _source, long Length, int _cutoff)
    {
        source = _source;
        cutoffFrequency = _cutoff;

        float[] s = new float[Length];
        _source.Read(s, 0, (int)Length);
        Normalize(s);

        var coefficients = MathNet.Filtering.FIR.FirCoefficients.LowPass(_source.WaveFormat.SampleRate, (double)400/ ((double)source.WaveFormat.SampleRate/(double)Length), 2);
        MathNet.Filtering.FIR.OnlineFirFilter filter = new MathNet.Filtering.FIR.OnlineFirFilter(coefficients);
        double[] output = Array.ConvertAll(s, x => (double)x);

        double[] output2 = filter.ProcessSamples(output);

        output1 = new float[output2.Length];
        for (int i = 0; i < output2.Length; i++)
        {
            output1[i] = Convert.ToSingle(output2[i]);
        }

    }

I've tried to divide my wanted frequncy by the frequency resolution of my signal but this way the signal doesn't seem to change at all.

xxm0dxx
  • 115
  • 1
  • 10

1 Answers1

0

I've been experimenting with this library recently. Here is a simple example of setting up a fir filter with a windowing function to improve it (for a 2 MSPS input and 125 kHz cutoff frequency):

            double samplingRate = 2000000;
            double cutoffFreq = 125000;
            int filterWidth = 130;

            var mathNetCoeffs = MathNet.Filtering.FIR.FirCoefficients.LowPass(samplingRate, cutoffFreq, filterWidth/2);
            MathNet.Filtering.Windowing.BlackmanWindow blackmanWindow = new MathNet.Filtering.Windowing.BlackmanWindow();
            blackmanWindow.Width = mathNetCoeffs.Length;
            var windowArr = blackmanWindow.CopyToArray();
            for (int i = 0; i < mathNetCoeffs.Length; i++) mathNetCoeffs[i] *= windowArr[i];
            MathNet.Filtering.FIR.OnlineFirFilter mathNetFilter = new MathNet.Filtering.FIR.OnlineFirFilter(mathNetCoeffs);

The windowing function is very important for making a working filter. Hamming is another popular choice, but I'm using Blackman here. Then use the filter by calling ProcessSample or ProcessSamples:

double mathNetFiltered = mathNetFilter.ProcessSample(value);

Also note that the actual filter width will be filterWidth + 1. You want the actual filter width to be odd (for good filter symmetry), so set filterWidth to an even value.

bobasaurus
  • 129
  • 1
  • 9