Exemple #1
0
        /// <summary>
        ///     Convolves the specified finite signal with an infinite signal.
        /// </summary>
        /// <param name="s1">The finite signal.</param>
        /// <param name="s2">The infinite signal.</param>
        /// <returns></returns>
        /// <exception cref="SamplerateMismatchException"></exception>
        public static ISignal Convolve(this IFiniteSignal s1, ISignal s2)
        {
            if (s1.SampleRate != s2.SampleRate)
            {
                throw new SamplerateMismatchException();
            }

            return(new InfiniteSignal(
                       (start, length) =>
            {
                var l = s1.Length + Math.Max(s1.Length, length) - 1;
                var n = Fft.NextPowerOfTwo(l);

                var spectrum1 = Fft.RealFft(s1.Signal, n);

                var signal2A = s2.GetWindowedSignal(start - s1.Length - s1.Start, s1.Length);
                var spectrum2A = Fft.RealFft(signal2A, n);
                var signal2B = s2.GetWindowedSignal(start - s1.Start, length);
                var spectrum2B = Fft.RealFft(signal2B, n);

                var spectrumA = spectrum1.Multiply(spectrum2A);
                var spectrumB = spectrum1.Multiply(spectrum2B);

                var signalA = Fft.RealIfft(spectrumA).Skip(s1.Length).Take(Math.Min(length, s1.Length - 1));
                var signalB = Fft.RealIfft(spectrumB).Take(length);

                var signal = signalA.AddFull(signalB);

                return signal;
            },
                       s1.SampleRate)
            {
                DisplayName = "convolution result"
            });
        }
Exemple #2
0
        /// <summary>
        /// Pitch estimation: from spectral peaks
        /// </summary>
        /// <param name="signal"></param>
        /// <param name="startPos"></param>
        /// <param name="endPos"></param>
        /// <returns></returns>
        public static float FromSpectralPeaks(DiscreteSignal signal,
                                              int startPos = 0,
                                              int endPos   = -1,
                                              float low    = 80,
                                              float high   = 400,
                                              int fftSize  = 0)
        {
            if (endPos == -1)
            {
                endPos = signal.Length;
            }

            if (startPos != 0 || endPos != signal.Length)
            {
                signal = signal[startPos, endPos];
            }

            signal.ApplyWindow(WindowTypes.Hann);

            var size = fftSize > 0 ? fftSize : MathUtils.NextPowerOfTwo(signal.Length);
            var fft  = new Fft(size);

            var spectrum = fft.PowerSpectrum(signal, false).Samples;

            return(FromSpectralPeaks(spectrum, signal.SamplingRate, low, high));
        }
    /*
     * Computes the unscaled DCT type III on the specified array in place.
     * The array length must be a power of 2 or zero.
     * For the formula, see https://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-III .
     */
    public static void InverseTransform(double[] vector)
    {
        if (vector == null)
        {
            throw new NullReferenceException();
        }
        int len = vector.Length;

        if (len > 0)
        {
            vector[0] /= 2;
        }
        Complex[] temp = new Complex[len];
        for (int i = 0; i < len; i++)
        {
            temp[i] = vector[i] * Complex.Exp(new Complex(0, -i * Math.PI / (len * 2)));
        }
        Fft.Transform(temp, false);

        int halfLen = len / 2;

        for (int i = 0; i < halfLen; i++)
        {
            vector[i * 2 + 0] = temp[i].Real;
            vector[i * 2 + 1] = temp[len - 1 - i].Real;
        }
        if (len % 2 == 1)
        {
            vector[len - 1] = temp[halfLen].Real;
        }
    }
Exemple #4
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="noise"></param>
        /// <param name="fftSize"></param>
        /// <param name="hopSize"></param>
        public SpectralSubtractor(DiscreteSignal noise, int fftSize = 1024, int hopSize = 128)
        {
            Guard.AgainstInvalidRange(hopSize, fftSize, "Hop size", "FFT size");

            _fftSize     = fftSize;
            _hopSize     = hopSize;
            _overlapSize = _fftSize - _hopSize;

            _fft    = new Fft(_fftSize);
            _window = Window.OfType(WindowTypes.Hann, _fftSize);

            _gain = 2 / (_fftSize * _window.Select(w => w * w).Sum() / _hopSize);

            _noiseAcc      = new float[_fftSize / 2 + 1];
            _noiseEstimate = new float[_fftSize / 2 + 1];

            _dl         = new float[_fftSize];
            _re         = new float[_fftSize];
            _im         = new float[_fftSize];
            _filteredRe = new float[_fftSize];
            _filteredIm = new float[_fftSize];
            _zeroblock  = new float[_fftSize];
            _lastSaved  = new float[_overlapSize];

            EstimateNoise(noise);

            Reset();
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="kernel"></param>
        /// <param name="fftSize"></param>
        public OlaBlockConvolver(IEnumerable <float> kernel, int fftSize)
        {
            _fftSize = MathUtils.NextPowerOfTwo(fftSize);

            if (kernel.Count() > _fftSize)
            {
                throw new ArgumentException("Kernel length must not exceed the size of FFT!");
            }

            _fft = new Fft(_fftSize);

            _kernel           = kernel.ToArray();
            _kernelSpectrumRe = _kernel.PadZeros(_fftSize);
            _kernelSpectrumIm = new float[_fftSize];
            _convRe           = new float[_fftSize];
            _convIm           = new float[_fftSize];
            _blockRe          = new float[_fftSize];
            _blockIm          = new float[_fftSize];
            _lastSaved        = new float[_kernel.Length - 1];
            _zeroblock        = new float[_fftSize];

            _fft.Direct(_kernelSpectrumRe, _kernelSpectrumIm);

            Reset();
        }
Exemple #6
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();

            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            using (var stream = new FileStream(ofd.FileName, FileMode.Open))
            {
                var waveFile = new WaveFile(stream);
                _signal = waveFile[Channels.Left];
            }

            _fft = new Fft(512);

            var lpcExtractor = new LpcExtractor(16, FrameSize, HopSize);

            _lpcVectors = lpcExtractor.ParallelComputeFrom(_signal);

            FillFeaturesList(_lpcVectors, lpcExtractor.FeatureDescriptions);
            lpcListView.Items[0].Selected = true;

            spectrumPanel.Line     = ComputeSpectrum(0);
            spectrumPanel.Markline = EstimateSpectrum(0);
            spectrumPanel.ToDecibel();

            lpcPanel.Line = _lpcVectors[0].Features.Skip(1).ToArray();
        }
Exemple #7
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="samplingRate"></param>
        /// <param name="shift"></param>
        /// <param name="fftSize"></param>
        /// <param name="hopSize"></param>
        public PitchShiftVocoderEffect(int samplingRate, double shift, int fftSize = 1024, int hopSize = 64)
        {
            _shift       = (float)shift;
            _fftSize     = fftSize;
            _hopSize     = hopSize;
            _overlapSize = _fftSize - _hopSize;

            Guard.AgainstInvalidRange(_hopSize, _fftSize, "Hop size", "FFT size");

            _fft    = new Fft(_fftSize);
            _window = Window.OfType(WindowTypes.Hann, _fftSize);

            _gain = (float)(2 * Math.PI / (_fftSize * _window.Select(w => w * w).Sum() / _hopSize));

            _freqResolution = samplingRate / _fftSize;

            _dl         = new float[_fftSize];
            _re         = new float[_fftSize];
            _im         = new float[_fftSize];
            _filteredRe = new float[_fftSize];
            _filteredIm = new float[_fftSize];
            _zeroblock  = new float[_fftSize];
            _lastSaved  = new float[_overlapSize];

            _mag        = new float[_fftSize / 2 + 1];
            _phase      = new float[_fftSize / 2 + 1];
            _prevPhase  = new float[_fftSize / 2 + 1];
            _phaseTotal = new float[_fftSize / 2 + 1];
        }
Exemple #8
0
        public void GetAmpSpectrumAndMax_ShortVec_sameResult()
        {
            List <double> Vector = CreateVector(1, 13, -10, 10);
            FftResult     fft    = new FftResult();
            FftResult     result = Fft.GetAmpSpectrumAndMax(1, Vector);

            for (int i = 0; i < result.Values.Count; i++)
            {
                result.Values[i] *= 1e13;
                result.Values[i]  = Math.Round(result.Values[i], 2, MidpointRounding.AwayFromZero);
            }
            List <(double, double)> valFreqTuple = new List <(double, double)>()
            {
                (0d, 0d), (3.25, 0.05), (1.49, 0.1), (0.16, 0.15), (1.36, 0.2), (1.27, 0.25), (0.03, 0.3), (1.46, 0.35), (1.92, 0.4), (1.31, 0.45), (0.54, 0.5)
            };

            valFreqTuple.ForEach(x => { fft.Values.Add(x.Item1); fft.Frequencies.Add(x.Item2); });
            fft.MaxIndex = 1;

            Assert.Equal(result.Frequencies, fft.Frequencies);
            Assert.Equal(result.Values, fft.Values);
            Assert.Equal(result.MaxIndex, fft.MaxIndex);

            /*Hodnoty nejsou přesně shodné s matlabem(Matlab zaokrouhluje jinak než Math.Net)
             * Math.Net počítá s větší přesností (e-21, matlab to zaokrouhlí na nulu)*/
        }
Exemple #9
0
        public void GetAmpSpectrumAndMax_ShortVec1_sameResult()
        {
            List <double> vecX = new List <double>()
            {
                319.5, 319.570564104974, 319.570564104974, 319.387187167831
            };
            List <double> vecY = new List <double>()
            {
                239.5, 239.690534471355, 239.690534471355, 239.447377199610
            };
            FftResult resultX = Fft.GetAmpSpectrumAndMax(29.966, vecX);
            FftResult resultY = Fft.GetAmpSpectrumAndMax(29.966, vecY);

            resultY.Values = resultY.Values.Select(x => Math.Round(x, 7)).ToList();
            resultX.Values = resultX.Values.Select(x => Math.Round(x, 7)).ToList();
            List <double> matlabValuesX = new List <double>()
            {
                0, 0.1964851
            };
            List <double> matlabValuesY = new List <double>()
            {
                0, 0.3089156
            };

            Assert.Equal(matlabValuesX, resultX.Values);
            Assert.Equal(matlabValuesY, resultY.Values);
        }
Exemple #10
0
        public void GetAmpSpectrumAndMax_EmptyInputList_returnsNull()
        {
            List <double> vector = new List <double>();
            var           result = Fft.GetAmpSpectrumAndMax(100, vector);

            Assert.Null(result);
        }
Exemple #11
0
        /// <summary>
        /// Fast convolution via FFT for arrays of samples (maximally in-place).
        /// This version is best suited for block processing when memory needs to be reused.
        /// Input arrays must have size equal to the size of FFT.
        /// </summary>
        /// <param name="real1">Real parts of the 1st signal (zero-padded)</param>
        /// <param name="imag1">Imaginary parts of the 1st signal (zero-padded)</param>
        /// <param name="real2">Real parts of the 2nd signal (zero-padded)</param>
        /// <param name="imag2">Imaginary parts of the 2nd signal (zero-padded)</param>
        /// <param name="res">Real parts of resulting convolution (zero-padded if center == 0)</param>
        /// <param name="center">
        /// Position of central sample for the case of 2*M-1 convolution
        /// (if it is set then resulting array has length of M)
        /// </param>
        public static void Convolve(float[] real1, float[] imag1, float[] real2, float[] imag2, float[] res, int center = 0)
        {
            var fftSize = real1.Length;
            var fft     = new Fft(fftSize);

            // 1) do FFT of both signals

            fft.Direct(real1, imag1);
            fft.Direct(real2, imag2);

            // 2) do complex multiplication of spectra and normalize

            for (var i = 0; i < fftSize; i++)
            {
                var re = real1[i] * real2[i] - imag1[i] * imag2[i];
                var im = real1[i] * imag2[i] + imag1[i] * real2[i];
                real1[i] = re / fftSize;
                imag1[i] = im / fftSize;
            }

            // 3) do inverse FFT of resulting spectrum

            fft.Inverse(real1, imag1);

            // 4) return output array

            if (center > 0)
            {
                real1.FastCopyTo(res, center, center - 1);
            }
            else
            {
                real1.FastCopyTo(res, fftSize);
            }
        }
Exemple #12
0
        public double[] Spectrum(double[] input, bool scale)
        {
            int length = input.Length;

            var fft = new Fft(length);

            var re = new float[length];
            var im = new float[length];

            for (int i = 0; i < length; i++)
            {
                re[i] = (float)input[i];
                im[i] = 0f;
            }

            fft.Direct(re, im);

            var spectrum = Helper.ComputeSpectrum(length, re, im);

            fft.Inverse(re, im);

            for (int i = 0; i < length; i++)
            {
                input[i] = re[i];
            }

            return(spectrum);
        }
Exemple #13
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="stretch"></param>
        /// <param name="hopAnalysis"></param>
        /// <param name="fftSize"></param>
        /// <param name="phaseLocking"></param>
        public PhaseLockingVocoder(double stretch, int hopAnalysis, int fftSize = 0, bool phaseLocking = true)
        {
            _stretch      = stretch;
            _hopAnalysis  = hopAnalysis;
            _hopSynthesis = (int)(hopAnalysis * stretch);
            _fftSize      = (fftSize > 0) ? fftSize : 8 * Math.Max(_hopAnalysis, _hopSynthesis);
            _phaseLocking = phaseLocking;

            _fft    = new Fft(_fftSize);
            _window = Window.OfType(WindowTypes.Hann, _fftSize);

            _gain = 2 / (_fftSize * _window.Select(w => w * w).Sum() / _hopSynthesis);

            _omega = Enumerable.Range(0, _fftSize / 2 + 1)
                     .Select(f => 2 * Math.PI * f / _fftSize)
                     .ToArray();

            _mag   = new double[_fftSize / 2 + 1];
            _phase = new double[_fftSize / 2 + 1];

            _prevPhase  = new double[_fftSize / 2 + 1];
            _phaseTotal = new double[_fftSize / 2 + 1];

            _delta = new double[_fftSize / 2 + 1];
            _peaks = new int[_fftSize / 4];

            _re        = new float[_fftSize];
            _im        = new float[_fftSize];
            _zeroblock = new float[_fftSize];
        }
Exemple #14
0
 public FftArrayVsSpan()
 {
     _fft        = new RealFft(FrameSize);
     _fft64      = new RealFft64(FrameSize);
     _complexFft = new Fft(FrameSize);
     _samples    = new WhiteNoiseBuilder().OfLength(N).Build().Samples;
     _samples64  = _samples.ToDoubles();
 }
Exemple #15
0
        public void TestFftShift()
        {
            float[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

            Fft.Shift(array);

            Assert.That(array, Is.EqualTo(new float[] { 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7 }));
        }
Exemple #16
0
        private void UpdateSpectrumAndCepstrum()
        {
            var fftSize      = int.Parse(fftSizeTextBox.Text);
            var cepstrumSize = int.Parse(cepstrumSizeTextBox.Text);

            _hopSize = int.Parse(hopSizeTextBox.Text);

            if (fftSize != _fftSize)
            {
                _fftSize           = fftSize;
                _fft               = new Fft(fftSize);
                _cepstralTransform = new CepstralTransform(cepstrumSize, _fftSize);
            }

            if (cepstrumSize != _cepstrumSize)
            {
                _cepstrumSize      = cepstrumSize;
                _cepstralTransform = new CepstralTransform(_cepstrumSize, _fftSize);
            }

            var pos   = _hopSize * _specNo;
            var block = _signal[pos, pos + _fftSize];

            //block.ApplyWindow(WindowTypes.Hamming);

            var cepstrum = _cepstralTransform.Direct(block);

            var pitch = Pitch.FromCepstrum(block);

            // ************************************************************************
            //      just visualize spectrum estimated from cepstral coefficients:
            // ************************************************************************

            var real = new float[_fftSize];
            var imag = new float[_fftSize];

            for (var i = 0; i < 32; i++)
            {
                real[i] = cepstrum[i];
            }

            _fft.Direct(real, imag);

            var spectrum = _fft.PowerSpectrum(block, normalize: false).Samples;
            var avg      = spectrum.Average(s => LevelScale.ToDecibel(s));

            var spectrumEstimate = real.Take(_fftSize / 2 + 1)
                                   .Select(s => (float)LevelScale.FromDecibel(s * 40 / _fftSize - avg))
                                   .ToArray();

            spectrumPanel.Line     = spectrum;
            spectrumPanel.Markline = spectrumEstimate;
            spectrumPanel.ToDecibel();

            cepstrumPanel.Line = cepstrum.Samples;
            cepstrumPanel.Mark = (int)(_signal.SamplingRate / pitch);
        }
Exemple #17
0
        /// <summary>
        /// Main constructor
        /// </summary>
        /// <param name="samplingRate"></param>
        /// <param name="featureCount"></param>
        /// <param name="frameDuration"></param>
        /// <param name="hopDuration"></param>
        /// <param name="filterbankSize"></param>
        /// <param name="lowFreq"></param>
        /// <param name="highFreq"></param>
        /// <param name="fftSize"></param>
        /// <param name="filterbank"></param>
        /// <param name="lifterSize"></param>
        /// <param name="preEmphasis"></param>
        /// <param name="window"></param>
        public MfccExtractor(int samplingRate,
                             int featureCount,
                             double frameDuration = 0.0256 /*sec*/,
                             double hopDuration   = 0.010 /*sec*/,
                             int filterbankSize   = 20,
                             double lowFreq       = 0,
                             double highFreq      = 0,
                             int fftSize          = 0,
                             float[][] filterbank = null,
                             int lifterSize       = 22,
                             double preEmphasis   = 0.0,
                             WindowTypes window   = WindowTypes.Hamming)

            : base(samplingRate, frameDuration, hopDuration)
        {
            FeatureCount = featureCount;

            if (filterbank == null)
            {
                _fftSize        = fftSize > FrameSize ? fftSize : MathUtils.NextPowerOfTwo(FrameSize);
                _filterbankSize = filterbankSize;

                _lowFreq  = lowFreq;
                _highFreq = highFreq;

                FilterBank = FilterBanks.Triangular(_fftSize, SamplingRate,
                                                    FilterBanks.MelBands(_filterbankSize, _fftSize, SamplingRate, _lowFreq, _highFreq));
            }
            else
            {
                FilterBank      = filterbank;
                _filterbankSize = filterbank.Length;
                _fftSize        = 2 * (filterbank[0].Length - 1);
            }

            _fft = new Fft(_fftSize);
            _dct = new Dct2(_filterbankSize, FeatureCount);

            _window = window;
            if (_window != WindowTypes.Rectangular)
            {
                _windowSamples = Window.OfType(_window, FrameSize);
            }

            _lifterSize   = lifterSize;
            _lifterCoeffs = _lifterSize > 0 ? Window.Liftering(FeatureCount, _lifterSize) : null;

            _preEmphasis = (float)preEmphasis;

            // reserve memory for reusable blocks

            _spectrum       = new float[_fftSize / 2 + 1];
            _logMelSpectrum = new float[_filterbankSize];
            _block          = new float[_fftSize];
            _zeroblock      = new float[_fftSize];
        }
Exemple #18
0
        private static void Main(string[] args)
        {
            /*var files = new List<string>();
             * var data = new List<(List<double>, string)>();
             * var percent = 0.0;
             * Console.WriteLine($"Percent: {percent * 100}%");
             * foreach (var genre in Genres)
             * {
             *  for (var i = 0; i < 5; i++)
             *  {
             *      var file = $@"C:\Users\Ale\Licenta-master\Licenta-master\PopulateDatabase\music\genres\{genre}\{genre}.0000{i}.wav";
             *      var sound = SoundReader.ReadFromFile(file);
             *      var fftResult = Fft.CalculateFft(sound, keepAll: true);
             *      foreach (var res in fftResult.Result)
             *          data.Add((res.Points.Select(x => (double)x).ToList(), genre));
             *      percent += 1.0 / 50;
             *      Console.Clear();
             *
             *      Console.WriteLine($"Percent: {percent * 100}%");
             *  }
             * }*/

            var ann = new RNA(null, AnnMode.Training, ActivationFunctions.Tahn);
            var net = Utils.ReadFromBinaryFile <List <List <Neuron> > >("net");

            //var net = ann.NetInit(10, 9);
            //ann.Training(ref net, 10, 0.001, 1000);

            var sound2 = SoundReader.ReadFromFile(
                @"C:\Users\Ale\Licenta-master\Licenta-master\PopulateDatabase\music\genres\disco\disco.00001.wav");

            var result2 = Fft.CalculateFft(sound2, keepAll: true);


            //var realOutputs = ann.TestData.Select(x => x.Item2).ToList();
            ann.TestData = result2.Result.Select(x => (x.HighScores, "disco")).ToList();
            ann.TestData.Shuffle();

            var computedOutputs = ann.Evaluate(ref net, 10);

            var genres = ann.GetGeneres();

            foreach (var result in computedOutputs)
            {
                genres[ann.GetValueFromLabelVector(result)] += 1;
            }

            var s = genres.ToDictionary(x => x.Key, x => x.Value * 100.0 / computedOutputs.Count);

            //Console.Write(ann.ComputePerformance(computedOutputs, realOutputs));


            Utils.WriteToBinaryFile("net", net);

            Console.ReadKey();
        }
        /// <summary>
        /// Prepare all necessary arrays for calculations
        /// </summary>
        /// <param name="fftSize"></param>
        private void PrepareMemory(int fftSize)
        {
            _fftSize = fftSize;
            _fft     = new Fft(_fftSize);

            _real1     = new float[_fftSize];
            _imag1     = new float[_fftSize];
            _real2     = new float[_fftSize];
            _imag2     = new float[_fftSize];
            _zeroblock = new float[_fftSize];
        }
Exemple #20
0
    private static void TestConvolution(int size)
    {
        Complex[] input0vector = RandomComplexes(size);
        Complex[] input1vector = RandomComplexes(size);
        Complex[] refoutvector = new Complex[size];
        NaiveConvolve(input0vector, input1vector, refoutvector);

        Complex[] actualoutvector = new Complex[size];
        Fft.Convolve(input0vector, input1vector, actualoutvector);
        Console.WriteLine("convsize={0,4}  logerr={1,5:F1}", size, Log10RmsErr(refoutvector, actualoutvector));
    }
Exemple #21
0
        /// <summary>
        /// Constuctor
        /// </summary>
        /// <param name="hopSize"></param>
        /// <param name="fftSize"></param>
        public WhisperEffect(int hopSize, int fftSize = 0)
        {
            _hopSize = hopSize;
            _fftSize = (fftSize > 0) ? fftSize : 8 * hopSize;

            _fft    = new Fft(_fftSize);
            _window = Window.OfType(WindowTypes.Hann, _fftSize);

            _re        = new float[_fftSize];
            _im        = new float[_fftSize];
            _zeroblock = new float[_fftSize];
        }
Exemple #22
0
        public void TestInverseFftNormalized()
        {
            float[] re = { 1, 5, 3, 7, 2, 3, 0, 7 };
            float[] im = new float[re.Length];

            var fft = new Fft(8);

            fft.Direct(re, im);
            fft.InverseNorm(re, im);

            Assert.That(re, Is.EqualTo(new[] { 1, 5, 3, 7, 2, 3, 0, 7 }).Within(1e-5));
        }
Exemple #23
0
        public void TestComplexFft()
        {
            float[] re = { 0, 1, 2, 3, 4, 5, 6, 7 };
            float[] im = new float[8];

            var fft = new Fft(8);

            fft.Direct(re, im);

            Assert.That(re, Is.EqualTo(new float[] { 28, -4, -4, -4, -4, -4, -4, -4 }).Within(1e-5));
            Assert.That(im, Is.EqualTo(new float[] { 0, 9.65685f, 4, 1.65685f, 0, -1.65685f, -4, -9.65685f }).Within(1e-5));
        }
Exemple #24
0
        /// <summary>
        /// Compute the sequence of feature vectors from some fragment of a signal
        /// </summary>
        /// <param name="signal">Signal</param>
        /// <param name="startSample">The number (position) of the first sample for processing</param>
        /// <param name="endSample">The number (position) of last sample for processing</param>
        /// <returns>Sequence of feature vectors</returns>
        public override List <FeatureVector> ComputeFrom(DiscreteSignal signal, int startSample, int endSample)
        {
            var frameSize = (int)(signal.SamplingRate * FrameSize);
            var hopSize   = (int)(signal.SamplingRate * HopSize);
            var fftSize   = _fftSize >= frameSize ? _fftSize : MathUtils.NextPowerOfTwo(frameSize);

            var resolution = (float)signal.SamplingRate / fftSize;

            var frequencies = Enumerable.Range(0, fftSize + 1)
                              .Select(f => f * resolution)
                              .ToArray();

            var featureVectors = new List <FeatureVector>();
            var featureCount   = FeatureCount;

            var fft = new Fft(fftSize);

            // reserve memory for reusable blocks

            var spectrum  = new float[fftSize / 2 + 1]; // buffer for magnitude spectrum
            var block     = new float[fftSize];         // buffer for currently processed block
            var zeroblock = new float[fftSize];         // just a buffer of zeros for quick memset

            var i = startSample;

            while (i + frameSize < endSample)
            {
                // prepare all blocks in memory for the current step:

                zeroblock.FastCopyTo(block, fftSize);
                signal.Samples.FastCopyTo(block, frameSize, i);

                fft.MagnitudeSpectrum(block, spectrum);

                var featureVector = new float[featureCount];

                for (var j = 0; j < featureCount; j++)
                {
                    featureVector[j] = _extractors[j](spectrum, frequencies);
                }

                featureVectors.Add(new FeatureVector
                {
                    Features     = featureVector,
                    TimePosition = (double)i / signal.SamplingRate
                });

                i += hopSize;
            }

            return(featureVectors);
        }
Exemple #25
0
        public void TestInverseFft()
        {
            float[] re = { 1, 5, 3, 7, 2, 3, 0, 7 };
            float[] im = new float[re.Length];

            var fft = new Fft(8);

            fft.Direct(re, im);
            fft.Inverse(re, im);

            Assert.That(re, Is.EqualTo(new[] { 8, 40, 24, 56, 16, 24, 0, 56 }).Within(1e-5));
            // re[i] * 8,  i = 0..7
        }
Exemple #26
0
        /// <summary>
        /// Constuctor
        /// </summary>
        /// <param name="hopSize"></param>
        /// <param name="fftSize"></param>
        public RobotEffect(int hopSize, int fftSize = 0)
        {
            _hopSize = hopSize;
            _fftSize = (fftSize > 0) ? fftSize : 8 * hopSize;

            _fft    = new Fft(_fftSize);
            _window = Window.OfType(WindowTypes.Hann, _fftSize);

            _gain = (float)(2 * Math.PI / (_fftSize * _window.Select(w => w * w).Sum() / _hopSize));

            _re        = new float[_fftSize];
            _im        = new float[_fftSize];
            _zeroblock = new float[_fftSize];
        }
Exemple #27
0
        public void ComputeFftDuringSignalForTwoSignals_BasicTests_GetCorectResult()
        {
            double        fs       = 30;
            List <double> vector1  = Enumerable.Range(0, 256).Select(x => (double)x).ToList();
            List <double> vector2  = Enumerable.Range(5, 256).Select(x => (double)x).ToList();
            List <double> expected = new List <double>();
            List <double> vys      = Fft.ComputeFftDuringSignalForTwoSignals(fs, vector1, vector2, 256, 1, false);

            for (int i = 0; i < 1040; i++)
            {
                expected.Add(7);
            }
            Assert.Equal(expected, vys);
        }
Exemple #28
0
        // Update spectra after filter
        private void UpdateSpectraAfterFilter()
        {
            var fftSize      = int.Parse(fftSizeTextBox.Text);
            var cepstrumSize = int.Parse(cepstrumSizeTextBox.Text);

            _hopSize = int.Parse(hopSizeTextBox.Text);

            if (fftSize != _fftSize)
            {
                _fftSize           = fftSize;
                _fft               = new Fft(fftSize);
                _cepstralTransform = new CepstralTransform(cepstrumSize, _fftSize);
            }

            if (cepstrumSize != _cepstrumSize)
            {
                _cepstrumSize      = cepstrumSize;
                _cepstralTransform = new CepstralTransform(_cepstrumSize, _fftSize);
            }

            var pos   = _hopSize * _specNo;
            var block = _signal[pos, pos + _fftSize];

            block.ApplyWindow(WindowTypes.Hamming);

            var cepstrum = _cepstralTransform.Direct(block);

            var real = new float[_fftSize];
            var imag = new float[_fftSize];

            for (var i = 0; i < 32; i++)
            {
                real[i] = cepstrum[i];
            }

            _fft.Direct(real, imag);

            var spectrum = _fft.PowerSpectrum(block, normalize: false).Samples;
            var avg      = spectrum.Average(s => LevelScale.ToDecibel(s));

            var spectrumEstimate = real.Take(_fftSize / 2 + 1)
                                   .Select(s => (float)LevelScale.FromDecibel(s * 40 / _fftSize - avg))
                                   .ToArray();

            spectrumPanelAfterFilter.Line     = spectrum;
            spectrumPanelAfterFilter.Markline = spectrumEstimate;
            spectrumPanelAfterFilter.ToDecibel();
            spectrumPanelAfterFilter.max_freq_value = spectrum.Length * _signal.SamplingRate / fftSize;
        }
Exemple #29
0
        public void GetAmpSpectrumAndMax_MultipleMaxIndexes_SameMaxIndexes()
        {
            List <double> freq_matlab      = new List <double>();
            List <double> freq_math_dotnet = new List <double>();
            double        f;

            for (int i = 1; i <= 45; i++)
            {
                f = i * 20;
                freq_matlab.Add(f);
                List <double> Vector = CreateVector(100, i, -10, 10);
                freq_math_dotnet.Add(Fft.GetAmpSpectrumAndMax(i, Vector).MaxIndex);
            }
            Assert.Equal(freq_matlab, freq_math_dotnet);
        }
Exemple #30
0
        public void Initialize(double[] data)
        {
            int length = Size = data.Length;

            fft = new Fft(length);

            re = new float[length];
            im = new float[length];

            for (int i = 0; i < length; i++)
            {
                re[i] = (float)data[i];
                im[i] = 0f;
            }
        }
Exemple #31
0
 void Awake()
 {
     m_transFourrier = new Fft();
 }