Example #1
0
        public void FourierBluesteinIsReversible(FourierOptions options)
        {
            var samples = Generate.RandomComplex(0x7FFF, GetUniform(1));
            var work    = new Complex[samples.Length];

            samples.CopyTo(work, 0);

            Fourier.BluesteinForward(work, options);
            Assert.IsFalse(work.ListAlmostEqual(samples, 6));

            Fourier.BluesteinInverse(work, options);
            AssertHelpers.AlmostEqual(samples, work, 10);
        }
Example #2
0
        private (double[] real, double[] imaginary) CalculateFFT()
        {
            const int roundDecimals = 2;
            var       real          = GetRealPart();
            var       imaginary     = GetImaginaryPart();

            Fourier.Forward(real, imaginary);

            Round(real, roundDecimals);
            Round(imaginary, roundDecimals);

            return(real, imaginary);
        }
        public void FourierRadix2IsReversible32(FourierOptions options)
        {
            var samples = Generate.RandomComplex32(0x8000, GetUniform(1));
            var work    = new Complex32[samples.Length];

            samples.CopyTo(work, 0);

            Fourier.Forward(work, options);
            Assert.IsFalse(work.ListAlmostEqual(samples, 6));

            Fourier.Inverse(work, options);
            AssertHelpers.AlmostEqual(samples, work, 12);
        }
Example #4
0
        public void FourierRealIsReversible(FourierOptions options)
        {
            var samples = Generate.Random(0x7FFF, GetUniform(1));
            var work    = new double[samples.Length + 2];

            samples.CopyTo(work, 0);

            Fourier.ForwardReal(work, samples.Length, options);
            Assert.IsFalse(work.ListAlmostEqual(samples, 6));

            Fourier.InverseReal(work, samples.Length, options);
            AssertHelpers.AlmostEqual(samples, work, 10);
        }
Example #5
0
        private void ComputeKernelTilde()
        {
            //Evaluate the kernel at the interpolation nodes and form the embedded generating kernel vector for a circulant matrix
            for (int i = 0; i < n_interpolation_points_1d; i++)
            {
                kernel_tilde[n_interpolation_points_1d + i]
                      = kernel_tilde[n_interpolation_points_1d - i]
                      = SquaredCauchy(tilde[0], tilde[i]);
            }

            // Precompute the FFT of the kernel generating matrix
            Fourier.ForwardReal(kernel_tilde, 2 * n_interpolation_points_1d, FourierOptions.NoScaling);
        }
Example #6
0
        public static void AnalyseGenerated(int frequency)
        {
            var samples = Generate.Sinusoidal(1024, 44100, frequency, 1.0)
                          .Select(sample => new Complex32((float)sample, 0))
                          .ToArray();

            Fourier.Forward(samples);
            var results = samples.Take(256).Select(result => result.Magnitude);

            Console.WriteLine($"FFT results: {FormatResults(results)}");
            Console.WriteLine(new String('-', 80));
            SaveResultsToCsvFile($"../js/signals/{frequency}_from_generated_data.csv", results);
        }
Example #7
0
        public void FourierNaiveIsReversible(FourierOptions options)
        {
            var samples = Generate.RandomComplex(0x80, GetUniform(1));
            var work    = new Complex[samples.Length];

            samples.CopyTo(work, 0);

            work = Fourier.NaiveForward(work, options);
            Assert.IsFalse(work.ListAlmostEqual(samples, 6));

            work = Fourier.NaiveInverse(work, options);
            AssertHelpers.AlmostEqual(samples, work, 12);
        }
Example #8
0
        public static IObservable <FftResult> AudioSampleFft(this IObservable <double[]> obs, double sampleRate)
        {
            return(obs.Select(x =>
            {
                var copy = x.Select(y => new Complex(y, 0)).ToArray();
                Fourier.Forward(copy, FourierOptions.AsymmetricScaling);

                return new FftResult(
                    Fourier.FrequencyScale(x.Length, sampleRate),
                    copy
                    );
            }));
        }
Example #9
0
        private static Complex[] fourier(double[] data)
        {
            Complex[] complexData = new Complex[data.Length];
            int       count       = 0;

            foreach (double x in data)
            {
                complexData[count] = x;
                count++;
            }
            Fourier.Forward(complexData, FourierOptions.Default);//フーリエ変換
            return(complexData);
        }
Example #10
0
        public void FourierDefaultTransformSatisfiesParsevalsTheorem32(int count)
        {
            var samples         = Generate.RandomComplex32(count, GetUniform(1));
            var timeSpaceEnergy = (from s in samples select s.MagnitudeSquared()).Mean();

            var spectrum = new Complex32[samples.Length];

            samples.CopyTo(spectrum, 0);
            Fourier.Forward(spectrum);
            var frequencySpaceEnergy = (from s in spectrum select s.MagnitudeSquared()).Mean();

            Assert.AreEqual(timeSpaceEnergy, frequencySpaceEnergy, 1e-7);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (GlobalVar.refresh == 0)
            {
                button1_Click(sender, e); // Refresh first
                GlobalVar.refresh = 1;
                button2_Click(sender, e); // Try again
            }
            else
            {
                GFFT1.Series[0].Points.Clear();
                GFFT2.Series[0].Points.Clear();

                double dintervals = 1000;
                int    att        = 30;
                int    fs1        = 2700;
                int    fs2        = 3500;
                Fourier.Forward(GlobalVar.compoutputA1);
                for (int q = 0; q < dintervals; q++)
                {
                    GFFT1.ChartAreas[0].AxisX.Title   = "Frequency (Hz)";
                    GFFT1.ChartAreas[0].AxisY.Title   = "Amplitude";
                    GFFT1.Series[0].IsVisibleInLegend = false; // Saves space
                    GFFT1.ChartAreas[0].AxisY.Minimum = 0;
                    GFFT1.ChartAreas[0].AxisX.Minimum = 0;
                    GFFT1.ChartAreas[0].AxisX.Maximum = 5500;

                    GFFT2.ChartAreas[0].AxisX.Title   = "Frequency (Hz)";
                    GFFT2.ChartAreas[0].AxisY.Title   = "Amplitude";
                    GFFT2.Series[0].IsVisibleInLegend = false; // Saves space
                    GFFT2.ChartAreas[0].AxisY.Minimum = 0;
                    GFFT2.ChartAreas[0].AxisX.Minimum = 0;
                    GFFT2.ChartAreas[0].AxisX.Maximum = 5500;

                    if (GlobalVar.samplef / dintervals * q < fs2 && fs1 < GlobalVar.samplef / dintervals * q)
                    {
                        GFFT1.Series[0].Points.Add(new DataPoint(GlobalVar.samplef / dintervals * q, 15 * Math.Log10(GlobalVar.compoutputA1[q].Magnitude) - att));
                        GFFT2.Series[0].Points.Add(new DataPoint(GlobalVar.samplef / dintervals * q, 15 * Math.Log10(GlobalVar.compoutputA1[q].Magnitude) - att));
                    }
                    else if (20 * Math.Log10(GlobalVar.compoutputA1[q].Magnitude) > 0)
                    {
                        GFFT1.Series[0].Points.Add(new DataPoint(GlobalVar.samplef / dintervals * q, 15 * Math.Log10(GlobalVar.compoutputA1[q].Magnitude)));
                        GFFT2.Series[0].Points.Add(new DataPoint(GlobalVar.samplef / dintervals * q, 15 * Math.Log10(GlobalVar.compoutputA1[q].Magnitude)));
                    }
                    else
                    {
                        GFFT1.Series[0].Points.Add(new DataPoint(GlobalVar.samplef / dintervals * q, 0));
                    }
                }
            }
        }
Example #12
0
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            if (ClientRectangle.Width <= AxisMargin || ClientRectangle.Height <= AxisMargin)
            {
                return;
            }
            var temp = new byte[ClientRectangle.Width - 2 * AxisMargin];

            Fourier.SmoothCopy(_powerSpectrum, temp, _powerSpectrum.Length, (_temp.Length + temp.Length) / (float)_temp.Length, 0);
            _powerSpectrum = temp;
            _temp          = new byte[_powerSpectrum.Length];

            var oldBuffer = _buffer;

            _buffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
            var oldBuffer2 = _buffer2;

            _buffer2 = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);

            _graphics.Dispose();
            _graphics = Graphics.FromImage(_buffer);
            SpectrumAnalyzer.ConfigureGraphics(_graphics);

            _graphics2.Dispose();
            _graphics2 = Graphics.FromImage(_buffer2);
            SpectrumAnalyzer.ConfigureGraphics(_graphics2);

            _graphics.Clear(Color.Black);
            var rect = new Rectangle(AxisMargin, 0, _buffer.Width - 2 * AxisMargin, _buffer.Height);

            _graphics.DrawImage(oldBuffer, rect, AxisMargin, 0, oldBuffer.Width - 2 * AxisMargin, oldBuffer.Height, GraphicsUnit.Pixel);
            oldBuffer.Dispose();
            oldBuffer2.Dispose();
            if (_spectrumWidth > 0)
            {
                _xIncrement = _scale * (ClientRectangle.Width - 2 * AxisMargin) / _spectrumWidth;
            }
            _gradientBrush.Dispose();
            _gradientBrush  = new LinearGradientBrush(new Rectangle(AxisMargin / 2, AxisMargin / 2, Width - AxisMargin / 2, ClientRectangle.Height - AxisMargin / 2), Color.White, Color.Black, LinearGradientMode.Vertical);
            _gradientPixels = null;
            _gradientBrush.InterpolationColors = _gradientColorBlend;
            DrawGradient();
            BuildGradientVector();
            _performNeeded = true;
            var oldMouseIn = _mouseIn;

            _mouseIn = true;
            Perform();
            _mouseIn = oldMouseIn;
        }
Example #13
0
        public void ReverseFFT(Signal signalIn, out Signal signal)
        {
            if (signalIn.Length == 0)
            {
                signal = new Signal(0);
                return;
            }

            float[] values = new float[signalIn.Length + 2];
            Buffer.BlockCopy(signalIn.Values, 0, values, 0, signalIn.Length);
            Fourier.InverseReal(values, signalIn.Length);

            signal = new Signal(values);
        }
Example #14
0
    public static double[] padded_FFT(Complex[] complexSignal)
    {
        int N = complexSignal.Length;

        Fourier.FFT(complexSignal, N, FourierDirection.Forward);

        // get the result
        double[] fft_real = new double[N];
        for (int j = 0; j < N; j++)
        {
            fft_real[j] = complexSignal[j].Re;
        }
        return(fft_real);
    }
Example #15
0
 private static void     SyncLookupTableLength(int length)
 {
     Debug.Assert(length < 1024 * 10);
     Debug.Assert(length >= 0);
     if (length > _lookupTabletLength)
     {
         int level = (int)Math.Ceiling(Math.Log(length, 2));
         Fourier.InitializeReverseBits(level);
         Fourier.InitializeComplexRotations(level);
         //_cFFTData	= new Complex[ Math2.CeilingBase( length, 2 ) ];
         //_cFFTDataF	= new ComplexF[ Math2.CeilingBase( length, 2 ) ];
         _lookupTabletLength = length;
     }
 }
Example #16
0
        public static List <double> AutoCorr(List <double> input, int n)
        {
            double avg = input.Average();

            Complex[] inputAsComplex = input.Select(x => new Complex(x - avg, 0)).ToArray();
            Fourier.Forward(inputAsComplex, FourierOptions.Matlab);
            var conjugate = inputAsComplex.Select(Complex.Conjugate);
            var S         = conjugate.Select((x, i) => x * inputAsComplex[i]).ToArray();

            Fourier.Inverse(S, FourierOptions.Matlab);
            double first = S[0].Real;

            return(S.Take(n).Select(x => x.Real / first).ToList());
        }
Example #17
0
 private double[] PrepareVerticalFouirier(double[][] source, int line = 0)
 {
     double[] oneLine;
     //take string x
     oneLine = new double[source.Length];
     for (int i = 0; i < source.Length; i++)
     {
         oneLine[i] = source[i][line];
     }
     //oneLine = Fourier.Derivative(oneLine);
     //oneLine = Fourier.AutoCrossCorrelation(oneLine, oneLine);
     oneLine = Fourier.FourierFunction(oneLine);
     return(oneLine);
 }
Example #18
0
        public void GenerateSignature()
        {
            int width  = Sprite.DefaultSize;
            int height = Sprite.DefaultSize;

            if (this.Width > 1 || this.Height > 1)
            {
                width  = Sprite.DefaultSize * 2;
                height = Sprite.DefaultSize * 2;
            }

            Bitmap   canvas = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            Graphics g      = Graphics.FromImage(canvas);

            // draw sprite
            for (int l = 0; l < this.Layers; l++)
            {
                for (int h = 0; h < this.Height; ++h)
                {
                    for (int w = 0; w < this.Width; ++w)
                    {
                        int    index  = w + h * this.Width + l * this.Width * this.Height;
                        Bitmap bitmap = ImageUtils.GetBitmap(this.SpriteList[index].GetRGBData(), PixelFormat.Format24bppRgb, Sprite.DefaultSize, Sprite.DefaultSize);

                        if (canvas.Width == Sprite.DefaultSize)
                        {
                            Rect.X      = 0;
                            Rect.Y      = 0;
                            Rect.Width  = bitmap.Width;
                            Rect.Height = bitmap.Height;
                        }
                        else
                        {
                            Rect.X      = Math.Max(Sprite.DefaultSize - w * Sprite.DefaultSize, 0);
                            Rect.Y      = Math.Max(Sprite.DefaultSize - h * Sprite.DefaultSize, 0);
                            Rect.Width  = bitmap.Width;
                            Rect.Height = bitmap.Height;
                        }

                        g.DrawImage(bitmap, Rect);
                    }
                }
            }

            g.Save();

            Bitmap ff2dBmp = Fourier.fft2dRGB(canvas, false);

            this.SpriteSignature = ImageUtils.CalculateEuclideanDistance(ff2dBmp, 1);
        }
Example #19
0
        protected override void _Initialize()
        {
            double factor = fftLength;

            for (int i = 0; i < Channels; i++)
            {
                Fourier.Forward(filterFD[i]);

                for (int j = 0; j < fftLength; j++)
                {
                    filterFD[i][j] *= factor;
                }
            }
        }
Example #20
0
        public override double[] Spectrum(double[] input, bool scale)
        {
            var data = ToComplex(input);

            Fourier.Forward(data, FourierOptions.Default);

            var spectrum = ComputeSpectrum(data);

            Fourier.Inverse(data, FourierOptions.Default);

            ToDouble(data, input);

            return(spectrum);
        }
Example #21
0
        public override double[] Spectrum(double[] input, bool scale)
        {
            var data = ToComplex(input);

            Fourier.FFT(data, data.Length, FourierDirection.Forward);

            var spectrum = ComputeSpectrum(data);

            Fourier.FFT(data, data.Length, FourierDirection.Backward);

            ToDouble(data, input);

            return(spectrum);
        }
Example #22
0
        public static double Estimate(double[] Samples, int Decimate, out double Phase)
        {
            Complex[] data = DecimateSignal(Samples, Decimate);
            int       N    = data.Length;

            Fourier.Forward(data);
            // Zero the DC bin.
            data[0] = 0.0;

            double f   = 0.0;
            double max = 0.0;

            Phase = 0.0;

            // Find largest frequency in FFT.
            for (int i = 1; i < N / 2 - 1; ++i)
            {
                double  x;
                Complex m = LogParabolaMax(data[i - 1], data[i], data[i + 1], out x);

                if (m.Magnitude > max)
                {
                    max   = m.Magnitude;
                    f     = i + x;
                    Phase = m.Phase;
                }
            }

            // Check if this is a harmonic of another frequency (the fundamental frequency).
            double f0 = f;

            for (int h = 2; h < 5; ++h)
            {
                int i = (int)Math.Round(f / h);
                if (i >= 1)
                {
                    double  x;
                    Complex m = LogParabolaMax(data[i - 1], data[i], data[i + 1], out x);

                    if (m.Magnitude * 5.0 > max)
                    {
                        f0    = f / h;
                        Phase = m.Phase;
                    }
                }
            }

            return(f0);
        }
Example #23
0
    public override void _Process(float delta)
    {
        long amountOfFramesPassed = (long)(stopwatch.Elapsed.TotalSeconds * sampleRate);

        stopwatch.Restart();

        //Delta time might not be entirely accurate. Using stopwatch instead.

        for (int i = 0; i < amountOfFramesPassed; i++)
        {
            frameBuffer.Enqueue(samplesFrames[framePointer]);
            framePointer = (framePointer + 1) % samplesFrames.LongLength;

            if (frameBuffer.Count > MaxFFTSize)
            {
                frameBuffer.Dequeue();
            }
        }

        if (frameBuffer.Count == 0)
        {
            return;
        }

        //Apply Hann window on the frames
        var frameBufferArray = frameBuffer.ToArray();

        for (int i = 0; i < frameBufferArray.Length; i++)
        {
            frameBufferArray[i] *= (float)hann[i];
        }

        //Convert frames to complex numbers
        var framesComplex = FramesToComplex(frameBufferArray);

        Complex[] samplesComplexLeft  = framesComplex.Item1;
        Complex[] samplesComplexRight = framesComplex.Item2;

        //Do FFT
        Fourier.Forward(samplesComplexLeft);
        Fourier.Forward(samplesComplexRight);

        //Convert to magnitudes
        float[] freqMagnitudesLeft  = Array.ConvertAll(samplesComplexLeft, x => (float)x.Magnitude);
        float[] freqMagnitudesRight = Array.ConvertAll(samplesComplexRight, x => (float)x.Magnitude);

        //Convert to cubes
        GetNode <Meshes>("Meshes").PlaceCubes(freqMagnitudesLeft, freqMagnitudesRight, sampleRate);
    }
Example #24
0
        public void CalculatePuls(List <double> dataList)
        {
            foreach (var value in dataList)
            {
                analysisList.Add(value);
            }

            if (analysisList.Count == 6 * _daqDTO.SampleRate)
            {
                Complex[] complexAnalysisListWithoutWindow = new Complex[6 * _daqDTO.SampleRate];
                for (int i = 0; i < analysisList.Count; i++)
                {
                    complexAnalysisListWithoutWindow[i] = new Complex(analysisList[i], 0);
                }

                Complex[] complexAnalysisListWithWindow = new Complex[6 * _daqDTO.SampleRate];
                double[]  hammingWindow = MathNet.Numerics.Window.Hamming(complexAnalysisListWithWindow.Length);

                for (int i = 0; i < complexAnalysisListWithoutWindow.Length; i++)
                {
                    complexAnalysisListWithWindow[i] = hammingWindow[i] * complexAnalysisListWithoutWindow[i];
                }
                Fourier.Forward(complexAnalysisListWithWindow, FourierOptions.NoScaling);

                double[] magnitudes = new double[complexAnalysisListWithWindow.Length / 2]; //vi kigger kun på den første halvdel af frekvensspekteret fordi efter nyquist frekvensen gentager spekteret sig.

                for (int i = 2; i < complexAnalysisListWithWindow.Length / 2; i++)
                {
                    magnitudes[i] = complexAnalysisListWithWindow[i].Magnitude;
                }

                int maxIndex = 0;

                for (int i = 0; i < magnitudes.Length; i++)
                {
                    if (magnitudes[i] == magnitudes.Max())
                    {
                        maxIndex = i;
                    }
                }

                double frequenceForMaxMagnitude = maxIndex * 1000.0 / complexAnalysisListWithWindow.Length;
                double bpm = 60 * frequenceForMaxMagnitude;

                _puls = bpm;
                Notify();
                analysisList.Clear();
            }
        }
Example #25
0
    public static double[] padded_IFFT(double[] signal)
    {
        int N = signal.Length;

        Complex[] complexSignal = FFTUtils.DoubleToComplex(signal);
        Fourier.FFT(complexSignal, N, FourierDirection.Backward);

        // get the result
        double[] fft_real = new double[N];
        for (int j = 0; j < N; j++)
        {
            fft_real[j] = complexSignal[j].Re;
        }
        return(fft_real);
    }
        public override void Load()
        {
            if (Fetched)
            {
                return;
            }

            var images = DoFetchImages(FileNames);

            _fft        = Fourier.FFT2(Images[0], false);
            ViewColumns = 9;
            ViewRows    = 9;
            Images      = images;
            Rearrange(0, 0, 300, 150, 9);
        }
Example #27
0
        public FrequencyChart AnalyzeSound(Complex[] sound, int offset)
        {
            var sample = new Complex[window.Length];

            Array.Copy(sound, offset, sample, 0, window.Length);

            Fourier.Radix2Forward(sample, FourierOptions.Default);
            var chart = new FrequencyChart(
                sample.Select(k => k.Magnitude * 2 / (sample.Length))
                .Zip(frqs, (a, f) => new FrequencyPair(f, a))
                .Where(k => k.Frequency > 0)
                .ToArray());

            return(chart);
        }
Example #28
0
        private static double[] Analyse(double[] sliver)
        {
            var extra   = sliver.Length - FFT_SIZE;
            var samples = sliver.Skip(extra).Select(sample => new Complex(sample, 0)).ToArray();

            Fourier.Forward(samples);
            var results = samples.Select(result => result.Magnitude).Take(FFT_SIZE / 2).ToArray();

            // The first result always looks massive and skews everything else so force it to 0.
            // TODO: figure out why
            // - something to do with the ffmpeg conversion from .mp3 to .pcm ?
            // - as comparison, FFT of generated sine wave looks fine
            // results[0] = 0;
            return(results);
        }
Example #29
0
        private void DoApply(UnmanagedImage image, UnmanagedImage output)
        {
            var fimg = Fourier.FFT2(image);

            if (Width != fimg.Width ||
                Height != fimg.Height)
            {
                throw new DimensionMismatchException();
            }

            fimg.C0.MultiplyWith(C0);
            fimg.C1.MultiplyWith(C1);
            fimg.C2.MultiplyWith(C2);
            output.Draw(fimg.InverseFFT2(false));
        }
        private void CreateSpectrum(ref float[] data)
        {
            for (int i = 0; i < data.Length; i++)
            {
                _complexBuffer[i] = new Complex32(data[i], 0);
            }

            Fourier.Forward(_complexBuffer, FourierOptions.NoScaling);

            for (int i = 0; i < _spectrum.Length; i++)
            {
                Complex32 fourierData = _complexBuffer[i];
                _spectrum[i] = (float)Math.Sqrt(fourierData.Real * fourierData.Real) + (fourierData.Imaginary * fourierData.Imaginary);
            }
        }
Example #31
0
    public static void BenchFourier()
    {
        Setup();
        FourierStruct t = new Fourier();
        t.adjust = 0;

        foreach (var iteration in Benchmark.Iterations)
        {
            using (iteration.StartMeasurement())
            {
                for (int i = 0; i < FourierIterations; i++) 
                {
                    t.Run();
                }
            }
        }
    }