public static async Task Aggregator(
            FPGA.OutputSignal <bool> LED1,
            FPGA.InputSignal <bool> RXD,
            FPGA.OutputSignal <bool> TXD
            )
        {
            Sequential handler = () =>
            {
                FPU.FPUScope();

                const int width = 10;
                const int baud  = 115200;

                ComplexFloat[] data = new ComplexFloat[GeneratorTools.ArrayLength(width)];

                while (true)
                {
                    RTX.ReadData(baud, RXD, data);

                    DFT.Transform(width, data, Direction.Forward);

                    RTX.WriteData(baud, TXD, data, 0);
                }
            };

            FPGA.Config.OnStartup(handler);

            Drivers.IsAlive.Blink(LED1);
        }
示例#2
0
        public void DFTReader(string file)
        {
            IsX  = false;
            DFTs = default;
            byte[] dftData = File.ReadAllBytes(file + ".dft");
            Struct _DOFT   = dftData.RSt(); dftData = null;

            if (_DOFT.Header.Signature != 0x54464F44)
            {
                return;
            }

            s      = File.OpenReader(_DOFT.Data);
            s.IsBE = _DOFT.Header.UseBigEndian;

            DFTs = s.RCPE <DFT>();
            if (DFTs.C < 1)
            {
                s.C(); DFTs.C = -1; return;
            }

            if (!(DFTs.C > 0 && DFTs.O == 0))
            {
                s.PI64 = DFTs.O - _DOFT.Header.Length;
                for (i = 0; i < DFTs.C; i++)
                {
                    ref DFT dft = ref DFTs.E[i];
                    dft.Flags        = (Flags)s.RI32E();
                    dft.Focus        = s.RF32E();
                    dft.FocusRange   = s.RF32E();
                    dft.FuzzingRange = s.RF32E();
                    dft.Ratio        = s.RF32E();
                    dft.Quality      = s.RF32E();
                }
            }
示例#3
0
        public static float[,] WStackIFFTFloat(List <Complex[, ]> grid, long visibilityCount)
        {
            var output = new float[grid[0].GetLength(0), grid[0].GetLength(1)];

            using (var imageSpace = new AlignedArrayComplex(16, grid[0].GetLength(0), grid[0].GetLength(1)))
                using (var fourierSpace = new AlignedArrayComplex(16, imageSpace.GetSize()))
                {
                    for (int k = 0; k < grid.Count; k++)
                    {
                        Parallel.For(0, grid[0].GetLength(0), (y) =>
                        {
                            for (int x = 0; x < grid[0].GetLength(1); x++)
                            {
                                fourierSpace[y, x] = grid[k][y, x];
                            }
                        });

                        DFT.IFFT(fourierSpace, imageSpace, PlannerFlags.Default, Environment.ProcessorCount);

                        Parallel.For(0, grid[0].GetLength(0), (y) =>
                        {
                            for (int x = 0; x < grid[0].GetLength(1); x++)
                            {
                                output[y, x] += (float)(imageSpace[y, x].Real / visibilityCount);
                            }
                        });
                    }
                }

            return(output);
        }
示例#4
0
        //public void ApplyLaplace(int apeturesize = 3)
        //{
        //    if (_ImageInput == null)
        //    {
        //        return;
        //    }
        //    Image<Gray, byte> imgGray = _ImageInput.Convert<Gray, byte>();
        //    Image<Gray, float> imgLaplace = new Image<Gray, float>(_ImageInput.Width, _ImageInput.Height, new Gray(0));
        //    imgLaplace = imgGray.Laplace(apeturesize);
        //    imageBox1.Image = imgLaplace;

        //}
        private void dFTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DFT dft = new DFT();

            dft.setDFTInput(_ImageInput);
            imageBox1.Image = dft.ApplyDFT();
        }
        private void btnTestFFT_Click(object sender, EventArgs e)
        {
            System.Numerics.Complex[] input  = new System.Numerics.Complex[4096];
            System.Numerics.Complex[] output = new System.Numerics.Complex[input.Length];
            double biggestMag = 0;

            //Generate an array of sine values
            for (int i = 0; i < input.Length; i++)
            {
                input[i] = Math.Sin(i * 2 * Math.PI * 128 / input.Length) + Math.Sin(i * 7 * Math.PI * 128 / input.Length);
            }

            //Run the Transfoamtion
            using (var pinIn = new PinnedArray <System.Numerics.Complex>(input))
                using (var pinOut = new PinnedArray <System.Numerics.Complex>(output)) {
                    DFT.FFT(pinIn, pinOut);
                }



            //Draw the output
            for (int i = 0; i < input.Length; i++)
            {
                using (Graphics g = picGraph.CreateGraphics()) {
                    g.DrawEllipse(Pens.Black, i, Convert.ToSingle(output[i].Magnitude), 4, 4);
                    txtFreqList.Text = txtFreqList.Text + output[i].Magnitude.ToString();
                }
            }
        }
示例#6
0
文件: DFTTest.cs 项目: Discretka/dis
        public void NextTest_AddFourItem_GetThirdItem()
        {
            BinarySeachTree <string> binarySeachTree = new BinarySeachTree <string>();

            binarySeachTree.Insert(2, "second");
            binarySeachTree.Insert(4, "third");
            binarySeachTree.Insert(-2, "first");
            binarySeachTree.Insert(6, "fourth");

            Iterator <string> iterator = new DFT <string>(binarySeachTree.GetRoot());

            string expected = "third";

            string actual = null;

            while (iterator.HasNext())
            {
                actual = iterator.Next().Item;

                if (actual == expected)
                {
                    break;
                }
            }

            Assert.AreEqual(expected, actual);
        }
        /// <summary>
        /// Performs FFT on a list of values returns a list of Frequencies associated with maximum magnitudes
        /// </summary>
        /// <param name="values">Values to perform FFT on</param>
        /// <param name="amount">Amount of maximum aplitudes to return</param>
        /// <returns></returns>
        public static IEnumerable <Tuple <int, Complex> > CalculateSalientMagnitudesOfOneSecond(double[] values, int amount)
        {
            Complex[] input  = ConvertToComplex(values);
            Complex[] output = new Complex[input.Length];

            using (var pinIn = new PinnedArray <Complex>(input))
                using (var pinOut = new PinnedArray <Complex>(output))
                {
                    DFT.FFT(pinIn, pinOut); //leave extra threads out as we are already multithreading
                }

            //only half the data is within the frequency domain
            //tuples appear to be faster than dictionaries for this particular use case (sorting, returning, etc.)
            Tuple <int, Complex>[] results = new Tuple <int, Complex> [output.Length / 2];
            for (int i = 0; i < output.Length / 2; i++)
            {
                results[i] = new Tuple <int, Complex>(i, output[i] / input[i]);
            }

            IEnumerable <Tuple <int, Complex> > max = (from result in results
                                                       where true
                                                       orderby result.Item2.Magnitude descending
                                                       select result).Take(amount);

            return(max);
        }
示例#8
0
        public static float[,] BackwardFloat(Complex[,] image, double norm)
        {
            var output = new float[image.GetLength(0), image.GetLength(1)];

            using (var imageSpace = new AlignedArrayComplex(16, image.GetLength(0), image.GetLength(1)))
                using (var fourierSpace = new AlignedArrayComplex(16, imageSpace.GetSize()))
                {
                    for (int y = 0; y < image.GetLength(0); y++)
                    {
                        for (int x = 0; x < image.GetLength(1); x++)
                        {
                            imageSpace[y, x] = image[y, x];
                        }
                    }

                    DFT.IFFT(imageSpace, fourierSpace, PlannerFlags.Default, Environment.ProcessorCount);

                    for (int y = 0; y < image.GetLength(0); y++)
                    {
                        for (int x = 0; x < image.GetLength(1); x++)
                        {
                            output[y, x] = (float)(fourierSpace[y, x].Real / norm);
                        }
                    }
                }

            return(output);
        }
示例#9
0
        public static double[,] Backward(Complex[,] grid, long visibilityCount)
        {
            double[,] output = new double[grid.GetLength(0), grid.GetLength(1)];
            using (var imageSpace = new AlignedArrayComplex(16, grid.GetLength(0), grid.GetLength(1)))
                using (var fourierSpace = new AlignedArrayComplex(16, imageSpace.GetSize()))
                {
                    for (int y = 0; y < grid.GetLength(0); y++)
                    {
                        for (int x = 0; x < grid.GetLength(1); x++)
                        {
                            fourierSpace[y, x] = grid[y, x];
                        }
                    }

                    DFT.IFFT(fourierSpace, imageSpace, PlannerFlags.Default, Environment.ProcessorCount);

                    for (int y = 0; y < grid.GetLength(0); y++)
                    {
                        for (int x = 0; x < grid.GetLength(1); x++)
                        {
                            output[y, x] = imageSpace[y, x].Real / visibilityCount;
                        }
                    }
                }

            return(output);
        }
        public double[] timeDelaySignal(short[] signalInput, double s)
        {
            double[] input = new double[signalInput.Length];
            for (int j = 0; j < signalInput.Length; j++)
            {
                input[j] = (double)signalInput[j];
            }

            Complex[] output = new Complex[input.GetLength(input.Rank - 1) / 2 + 1];
            double[]  inOut  = new double[input.Length];

            using (var pinIn = new PinnedArray <double>(input))
                using (var pinOut = new PinnedArray <Complex>(output))
                    using (var in1Out = new PinnedArray <double>(inOut))
                    {
                        DFT.FFT(pinIn, pinOut);
                        for (int j = 0; j < pinOut.Length; j++)
                        {
                            double angle = ((2 * Math.PI) / pinOut.Length) * SampleRate * j * s;
                            pinOut[j] = pinOut[j] * Complex.Exp(new Complex(0, -angle));
                        }

                        DFT.IFFT(pinOut, in1Out);
                        for (int j = 0; j < inOut.Length; j++)
                        {
                            inOut[j] = inOut[j] / input.Length;
                        }
                        return(inOut);
                    }
        }
示例#11
0
        public static Complex[,] Forward(float[,] image, double norm = 1.0)
        {
            Complex[,] output = new Complex[image.GetLength(0), image.GetLength(1)];
            using (var imageSpace = new AlignedArrayComplex(16, image.GetLength(0), image.GetLength(1)))
                using (var fourierSpace = new AlignedArrayComplex(16, imageSpace.GetSize()))
                {
                    for (int y = 0; y < image.GetLength(0); y++)
                    {
                        for (int x = 0; x < image.GetLength(1); x++)
                        {
                            imageSpace[y, x] = image[y, x];
                        }
                    }

                    DFT.FFT(imageSpace, fourierSpace);

                    for (int y = 0; y < image.GetLength(0); y++)
                    {
                        for (int x = 0; x < image.GetLength(1); x++)
                        {
                            output[y, x] = fourierSpace[y, x] / norm;
                        }
                    }
                }

            return(output);
        }
示例#12
0
        public void PhaseAnalysis()
        {
            // Generate a Phase Ramp between two signals
            double[] resultPhase = new double[360];

            // Instantiate & Initialize a new DFT
            DFT dft = new DFT();

            dft.Initialize(2048);

            for (Int32 phase = 0; phase < 360; phase++)
            {
                double[] inputSignalRef   = mdsplib.DSP.Generate.ToneCycles(7.0, 128, 2048);
                double[] inputSignalPhase = mdsplib.DSP.Generate.ToneCycles(7.0, 128, 2048, phaseDeg: phase);

                // Call the DFT and get the scaled spectrum back of a reference and a phase shifted signal.
                Complex[] cSpectrumRef   = dft.Execute(inputSignalRef);
                Complex[] cSpectrumPhase = dft.Execute(inputSignalPhase);

                // Magnitude Format - Just as a test point
                //double[] lmSpectrumTest = DSPLib.DSP.ConvertComplex.ToMagnitude(cSpectrumRef);
                //double[] lmSpectrumTestPhase = DSPLib.DSP.ConvertComplex.ToMagnitude(cSpectrumPhase);

                // Extract the phase of bin 128
                double[] resultArrayRef   = cSpectrumRef.PhaseDegrees();
                double[] resultArrayPhase = cSpectrumPhase.PhaseDegrees();
                resultPhase[phase] = resultArrayPhase[128] - resultArrayRef[128];
            }

            // resultPhase has a linear phase incrementing signal at this point.
            // Use UnwrapPhase() to remove phase jumps in output data.
        }
示例#13
0
 public virtual JsonResult DropList(string filterExpression, string pySearch)
 {
     try
     {
         ClearClientPageCache(Response);
         IEntry rep = EntryRepository;
         CacheInit.RefreshCache(HttpContext, rep, ControllerName + "DropList", DateTime.Now.AddMinutes(CacheExpiryMinute), CachePriority, CacheCreateType.IfNoThenGenerated);
         DataTable source = (DataTable)HttpContext.Cache[ControllerName + "DropList"];
         filterExpression = DFT.HandleExpress(filterExpression);
         List <DropListSource> dropList = rep.DropList(source, filterExpression);
         if (DataConvert.ToString(pySearch) != "")
         {
             List <DropListSource> filterDrop = new List <DropListSource>();
             foreach (var obj in dropList)
             {
                 string   pyf  = PinYin.GetFirstPinyin(DataConvert.ToString(obj.Text)).ToUpper();
                 string[] pyfs = pyf.Split(',');
                 foreach (string py in pyfs)
                 {
                     if (py.StartsWith(pySearch.ToUpper()) && !filterDrop.Contains(obj))
                     {
                         filterDrop.Add(obj);
                     }
                 }
             }
             return(DropListJson(filterDrop));
         }
         return(DropListJson(dropList));
     }
     catch (Exception ex)
     {
         AppLog.WriteLog(AppMember.AppText["SystemUser"], LogType.Error, "MasterController.DropList", ControllerName + "[Message]:" + ex.Message + " [StackTrace]:" + ex.StackTrace);
         return(new JsonResult());
     }
 }
示例#14
0
        public void BasicWnd()
        {
            // Same Input Signal as Example 1
            double amplitude = 1.0; double frequency = 20000;
            UInt32 length       = 1000;
            double samplingRate = 100000;

            double[] inputSignal = mdsplib.DSP.Generate.ToneSampling(amplitude, frequency, samplingRate, length);

            // Apply window to the Input Data & calculate Scale Factor
            double[] wCoefs       = mdsplib.DSP.Window.Coefficients(mdsplib.DSP.Window.Type.Hamming, length);
            double[] wInputData   = inputSignal.Multiply(wCoefs);
            double   wScaleFactor = mdsplib.DSP.Window.ScaleFactor.Signal(wCoefs);

            // Instantiate & Initialize a new DFT
            DFT dft = new DFT();

            dft.Initialize(length);

            // Call the DFT and get the scaled spectrum back
            Complex[] cSpectrum = dft.Execute(wInputData);

            // Convert the complex spectrum to note: Magnitude Format
            double[] lmSpectrum = cSpectrum.Magnitude();

            // Properly scale the spectrum for the added window
            lmSpectrum = lmSpectrum.Multiply(wScaleFactor);

            // For plotting on an XY Scatter plot generate the X Axis frequency Span
            double[] freqSpan = Util.FFT.FrequencySpan(samplingRate, length);

            // At this point a XY Scatter plot can be generated from,
            // X axis => freqSpan
            // Y axis => lmSpectrum
        }
示例#15
0
        static void Example2D()
        {
            using (var input = new AlignedArrayComplex(16, 64, 16))
                using (var output = new AlignedArrayComplex(16, input.GetSize()))
                {
                    for (int row = 0; row < input.GetLength(0); row++)
                    {
                        for (int col = 0; col < input.GetLength(1); col++)
                        {
                            input[row, col] = (double)row * col / input.Length;
                        }
                    }

                    DFT.FFT(input, output);
                    DFT.IFFT(output, output);

                    for (int row = 0; row < input.GetLength(0); row++)
                    {
                        for (int col = 0; col < input.GetLength(1); col++)
                        {
                            Console.Write((output[row, col].Real / input[row, col].Real / input.Length).ToString("F2").PadLeft(6));
                        }
                        Console.WriteLine();
                    }
                }
        }
示例#16
0
        public static Complex[,] Forward(double[,] image, double norm = 1.0)
        {
            Complex[,] output = new Complex[image.GetLength(0), image.GetLength(1)];
            using (var imageSpace = new AlignedArrayComplex(16, image.GetLength(0), image.GetLength(1)))
                using (var fourierSpace = new AlignedArrayComplex(16, imageSpace.GetSize()))
                {
                    for (int y = 0; y < image.GetLength(0); y++)
                    {
                        for (int x = 0; x < image.GetLength(1); x++)
                        {
                            imageSpace[y, x] = image[y, x];
                        }
                    }

                    DFT.FFT(imageSpace, fourierSpace, PlannerFlags.Default, Environment.ProcessorCount);

                    for (int y = 0; y < image.GetLength(0); y++)
                    {
                        for (int x = 0; x < image.GetLength(1); x++)
                        {
                            output[y, x] = fourierSpace[y, x] / norm;
                        }
                    }
                }

            return(output);
        }
示例#17
0
        // ---- メソッド ---------------------------------------
        /// <summary>
        /// 特徴ベクトルを返す
        /// </summary>
        /// <returns>特徴ベクトル</returns>
        public override PatternRecognition.Feature GetFeature()
        {
            if (this.Ready)
            {
                // 最大のパワーとなった帯域を探すとその最大値を求める
                double maxPSDofBand = this._sumOfPSDbyBand.Max();                                           // 最大値を取得
                int    indexOfMax   = -1;                                                                   // -1としておくことで、↓2行のアルゴリズムにより最大となる帯域のインデックス-1を得る
                for (int i = 0; i < this._sumOfPSDbyBand.Length && this._sumOfPSDbyBand[i] != maxPSDofBand; i++)
                {
                    indexOfMax = i;                                                                         // 最大となった帯域のインデックス-1を取得する
                }
                indexOfMax++;                                                                               // 等しいと代入の前にループを抜けるので、抜けた後で加算してインデックスとする
                // SN比を求める。求まればよいが。
                double noiseLevelPSD = this._timeSeriesPSD[0][indexOfMax];                                  // フレームの初めはノイズレベルに近いはず
                double maxPSDofFlame = double.MinValue;
                for (int i = 0; i < this._timeSeriesPSD.Count; i++)
                {
                    if (maxPSDofFlame < this._timeSeriesPSD[i][indexOfMax])
                    {
                        maxPSDofFlame = this._timeSeriesPSD[i][indexOfMax];
                    }
                }
                this._SNratio = 10.0 * Math.Log10(maxPSDofFlame / noiseLevelPSD);
                // 帯域パワーの最大値が1になるように正規化
                var fea1 = new PatternRecognition.Feature(this._sumOfPSDbyBand);
                fea1.Normalizing();

                // 変調スペクトルをもとめる
                double[] modulatedSongAtUniBand = new double[this._timeSeriesPSD.Count];
                for (int i = 0; i < modulatedSongAtUniBand.Length; i++)
                {
                    modulatedSongAtUniBand[i] = this._timeSeriesPSD[i][indexOfMax];                         // 最大であった帯域のパワーを取得する(変調されたパワー)
                }
                DFT       fft = new DFT(modulatedSongAtUniBand.Length, Window.WindowKind.Hanning);          // FFTを実施する準備
                FFTresult modulationSpectrum = fft.FFT(modulatedSongAtUniBand, this._condition.FrequencyOfFFT);
                double[]  spectrum           = new double[this._condition.MaxModulationSpectrumFrequency * 10];
                //for (int i = 0; i < spectrum.Length; i++)
                Parallel.For(0, spectrum.Length, i =>
                {
                    double minFrequency = (double)i * 0.1;
                    double maxFrequency = minFrequency + 0.1;
                    spectrum[i]         = modulationSpectrum.GetPSD(minFrequency, maxFrequency);            // 帯域毎にコピー
                });
                // コピーした変調スペクトルを正規化
                var fea2 = new PatternRecognition.Feature(spectrum);
                fea2.Normalizing();

                // 特徴ベクトルとしてまとめる
                var ans = new PatternRecognition.Feature(fea1.ToArray());
                ans.Add(fea2.ToArray());
                ans.Normalizing();

                return(ans);
            }
            else
            {
                return(null);
            }
        }
示例#18
0
        public void Initialize(GraphicsDevice graphics)
        {
            _graphics = graphics;

            _spriteBatch = new SpriteBatch(graphics);

            dftFunction = new DFT();
        }
示例#19
0
        static void Main(string[] args)
        {
            string argument;

            // script python a executer pour ploter les resultats
            //-------------------------------------------------
            argument = "C:\\C#\\MathsLib\\Test_sysarg-v4.py" + " ";

            //test de plusieurs fonctionnalites
            //-------------------------------------------------

            int    nbechant;
            double Fe;

            Fe = 1000.0;   //1000 Hz



            //calcul du nombre de points a echantillonner
            //sur un crénau de 0.25 secondes (250 milisecondes) avec une fréquence d'échantillonnage de 1000 Hz
            // échantillonnage a 1 points toutes les 1/1000 = 0.001 secondes

            nbechant = SiTest.Nbechant(1000, 0.25);

            Console.WriteLine("nbechant = {0}", nbechant);

            decimal[] S2 = new decimal[nbechant];
            double[]  S1 = new double[nbechant];

            //Form a signal containing a 50 Hz sinusoid of amplitude 4
            //S2 = 4*sin(2*pi*50*t)

            S2 = SiTest.GenSin2piF(nbechant, 50.0, 4.0, Fe);

            // resultat de la DFT (Discret Fourier Transform) dans le tableau de complexe : Ts[]
            //----------------------------------------------------------------------------------
            Complex[] Ts = new Complex[nbechant];
            Ts = DFT.DFTv2(S2);

            //Recuperation du module de la DFT
            decimal[] Module = new decimal[nbechant];
            //Module = DFT.Dsdec(Ts);

            //Densite spectrale de puissance du signal
            //---------------------------------------------------------------------------
            decimal[] Module1 = new decimal[nbechant];
            Module1 = DSP.Dspdeci(Ts);

            //plot signal de test : Tableau Ti1[]
            //-------------------------------------------------------------------
            PlotPython.Plot1(S2, argument);


            //plot Densite spectrale de puissance du sgignal
            //------------------------------------------------------------------
            PlotPython.Plot1(Module1, argument);
        }
示例#20
0
        private void btnFindPitch_Click(object sender, EventArgs e)
        {
            System.Numerics.Complex[] input  = new System.Numerics.Complex[4096];
            System.Numerics.Complex[] output = new System.Numerics.Complex[input.Length];
            double biggestPitch         = 0;
            int    biggestPitchLocation = 0;

            byte[] bufferCopy = buffer;

            //convert the byte array to the short array
            for (int i = 1; i < bufferCopy.Length - 1; i += 2)
            {
                input[i / 2] = (short)(Convert.ToUInt16((bufferCopy[i]) | bufferCopy[i + 1] << 8));
            }



            //Do the transformation
            using (var pinIn = new PinnedArray <System.Numerics.Complex>(input))
                using (var pinOut = new PinnedArray <System.Numerics.Complex>(output)) {
                    DFT.FFT(pinIn, pinOut);
                }

            //miss half of the values cuz they repeated
            for (int i = 0; i < output.Length / 2; i++)
            {
                if (output[i].Magnitude > biggestPitch)
                {
                    biggestPitch         = output[i].Magnitude;
                    biggestPitchLocation = i;
                }
            }

            lblBiggestPitch.Text = biggestPitchLocation.ToString();

            //fft(bufferCopy);


            double biggestMag = 0;

            foreach (var currentNum in output)
            {
                if (currentNum.Magnitude > biggestMag)
                {
                    biggestMag = currentNum.Magnitude;
                }
            }

            using (Graphics g = picGraph.CreateGraphics()) {
                g.DrawLine(Pens.Blue, biggestPitchLocation / 2 + 2, 500, biggestPitchLocation / 2 + 2, 500 - Convert.ToSingle(biggestPitch * 500 / biggestMag));
            }
        }
        /// <summary>
        /// Calculate the frequency domain of one second of data
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static Span <Complex> CalculateFrequencyDomainOfOneSecond(double[] values)
        {
            Complex[] input  = ConvertToComplex(values);
            Complex[] output = new Complex[input.Length];

            using (var pinIn = new PinnedArray <Complex>(input))
                using (var pinOut = new PinnedArray <Complex>(output))
                {
                    DFT.FFT(pinIn, pinOut); //leave extra threads out as we are already multithreading
                }

            //only half the data is within the frequency domain
            return(output.AsSpan().Slice(0, (input.Length / 2) - 1));
        }
示例#22
0
        public void NoiseAnalysis()
        {
            // Setup parameters to generate noise test signal of 5 nVrms / rt-Hz
            double amplitude = 5.0e-9;
            UInt32 length = 1000; double samplingRate = 2000;

            // Generate window & calculate Scale Factor for NOISE!
            double[] wCoefs       = mdsplib.DSP.Window.Coefficients(mdsplib.DSP.Window.Type.Hamming, length);
            double   wScaleFactor = mdsplib.DSP.Window.ScaleFactor.Noise(wCoefs, samplingRate);

            // Instantiate & Initialize a new DFT
            DFT dft = new DFT();

            dft.Initialize(length);

            // Average the noise 'N' times
            Int32 N = 1000;

            double[] noiseSum = new double[(length / 2) + 1];
            for (Int32 i = 0; i < N; i++)
            {
                // Generate the noise signal & apply window
                double[] inputSignal = mdsplib.DSP.Generate.NoisePsd(amplitude, samplingRate, length);
                inputSignal = inputSignal.Multiply(wCoefs);

                // DFT the noise -> Convert -> Sum
                Complex[] cSpectrum = dft.Execute(inputSignal);
                double[]  mag2      = cSpectrum.MagnitudeSquared();
                noiseSum = (N == 0) ? noiseSum : noiseSum = noiseSum.Add(mag2);
            }

            // Calculate Average, convert to magnitude format
            // See text for the reasons to use Mag^2 format.
            double[] averageNoise = noiseSum.Divide(N);
            double[] lmSpectrum   = averageNoise.Magnitude();

            // Properly scale the spectrum for the added window
            lmSpectrum = lmSpectrum.Multiply(wScaleFactor);

            // For plotting on an XY Scatter plot generate the X Axis frequency Span
            double[] freqSpan = Util.FFT.FrequencySpan(samplingRate, length);

            // At this point a XY Scatter plot can be generated from,
            // X axis => freqSpan
            // Y axis => lmSpectrum as a Power Spectral Density Value

            // Extra Credit - Analyze Plot Data Ignoring the first and last 20 Bins
            // Average value should be what we generated = 5.0e-9 Vrms / rt-Hz
            double averageValue = mdsplib.DSP.Analyze.FindMean(lmSpectrum, 20, 20);
        }
示例#23
0
文件: DFTTest.cs 项目: Discretka/dis
        public void NextTest_AddTwoItems_GetSecondItem()
        {
            BinarySeachTree <string> binarySeachTree = new BinarySeachTree <string>();

            binarySeachTree.Insert(2, "second");
            binarySeachTree.Insert(-1, "first");

            Iterator <string> iterator = new DFT <string>(binarySeachTree.GetRoot());

            string expected = "second";

            string actual = iterator.Next().Item;

            Assert.AreEqual(expected, actual);
        }
示例#24
0
        public JsonResult UserDropList(string filterExpression)
        {
            UserRepository rep = new UserRepository();

            if (HttpContext.Cache["UserDropList"] == null)
            {
                DataTable list = rep.GetDropListSource();
                HttpContext.Cache.Add("UserDropList", list, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, CacheItemPriority.High, null);
            }
            DataTable source = (DataTable)HttpContext.Cache["UserDropList"];

            filterExpression = DFT.HandleExpress(filterExpression);
            List <DropListSource> dropList = rep.DropList(source, filterExpression);

            return(DropListJson(dropList));
        }
        public void DFTController()
        {
            using (var port = new COMPort())
            {
                var sourceSignal = _bp.TestSignal();
                port.Send(sourceSignal);
                DFT.Transform(_bp.Bits, sourceSignal, Direction.Forward);

                port.WaitForData(TimeSpan.FromMinutes(1));

                var receiverSignal = _bp.ZeroSignal;
                port.Receive(receiverSignal, out uint duration);

                Validation.AssertSpectres(sourceSignal, receiverSignal, true, true);
            }
        }
示例#26
0
        public void GetSpectre(List <double> values, double samplingRate, out double[] spectrum, out double[] freqSpan)
        {
            // Instantiate a new DFT
            DFT dft = new DFT();

            // Initialize the DFT
            // You only need to do this once or if you change any of the DFT parameters.
            dft.Initialize((uint)values.Count);

            // Call the DFT and get the scaled spectrum back
            Complex[] cSpectrum = dft.Execute(values.ToArray());

            // Convert the complex spectrum to magnitude
            spectrum = DSP.ConvertComplex.ToMagnitude(cSpectrum);
            freqSpan = dft.FrequencySpan(samplingRate);
        }
示例#27
0
        public static List <List <Complex[, ]> > Forward(GriddingConstants c, List <List <Complex[, ]> > subgrids)
        {
            var output = new List <List <Complex[, ]> >(subgrids.Count);

            for (int baseline = 0; baseline < subgrids.Count; baseline++)
            {
                var blSubgrids = subgrids[baseline];
                var blOutput   = new List <Complex[, ]>(blSubgrids.Count);
                for (int subgrid = 0; subgrid < blSubgrids.Count; subgrid++)
                {
                    var sub        = blSubgrids[subgrid];
                    var outFourier = new Complex[c.SubgridSize, c.SubgridSize];
                    using (var imageSpace = new AlignedArrayComplex(16, c.SubgridSize, c.SubgridSize))
                        using (var fourierSpace = new AlignedArrayComplex(16, imageSpace.GetSize()))
                        {
                            //copy
                            for (int i = 0; i < c.SubgridSize; i++)
                            {
                                for (int j = 0; j < c.SubgridSize; j++)
                                {
                                    imageSpace[i, j] = sub[i, j];
                                }
                            }

                            /*
                             * This is not a bug
                             * The original IDG implementation uses the inverse Fourier transform here, even though the
                             * Subgrids are already in image space.
                             */
                            DFT.IFFT(imageSpace, fourierSpace);
                            var norm = 1.0 / (c.SubgridSize * c.SubgridSize);

                            for (int i = 0; i < c.SubgridSize; i++)
                            {
                                for (int j = 0; j < c.SubgridSize; j++)
                                {
                                    outFourier[i, j] = fourierSpace[i, j] * norm;
                                }
                            }
                        }
                    blOutput.Add(outFourier);
                }
                output.Add(blOutput);
            }

            return(output);
        }
示例#28
0
        public void UpdateDFT(int N)
        {
            DFT            dft       = new DFT();
            List <Complex> input     = new List <Complex>(Signal.GetArray(N));
            List <Complex> dftResult = new List <Complex>(dft.GetResult(input.ToArray(), true));
            List <Complex> dftInvert = new List <Complex>(dft.GetResult(dftResult.ToArray(), false));
            double         step      = 2 * Math.PI / N;
            Complex        x         = 0;

            (plotModelDFT.Series[0] as LineSeries).Points.Clear();
            for (int i = 0; i < N; i++)
            {
                (plotModelDFT.Series[0] as LineSeries).Points.Add(new DataPoint(x.Real, dftInvert[i].Real));
                x += step;
            }
            plotModelDFT.InvalidatePlot(true);
        }
示例#29
0
    /**********************************************************************************************
    * Auxiliary Method: TimeIt
    *   Measure execution time through repeated calls to a (Fast) Fourier Transform function.
    *
    * Parameters:
    *  f
    *    Function to be called, with the given prototype. The parameter is a complex vector to be
    *    transformed, and the return value is a complex vector with the coefficients of the
    *    transform;
    *  size
    *    Number of elements in the vector on which the transform will be applied;
    *  repeat
    *    Number of times the function will be called.
    *
    * Returns:
    *   The average execution time for that function with a vector of the given size.
    **********************************************************************************************/
    public static double TimeIt(DFT f, int size, int repeat)
    {
        Complex[] x = new Complex[size];

        for (int i = 0; i < size; i++)                      // Initialize the vector;
        {
            x[i] = new Complex(i, 0);
        }
        Stopwatch dsw = Stopwatch.StartNew();          // Start a timer;

        for (int j = 0; j < repeat; j++)               // Repeated calls;
        {
            f(x);
        }
        dsw.Stop();
        return(((double)dsw.ElapsedMilliseconds) / ((double)(1000 * repeat)));
    }
示例#30
0
        private void Form6_Load(object sender, EventArgs e)
        {
            const int N = 64;

            double[] foo = new double[N];
            //Формирование массива действительных чисел.
            for (int i = 0; i < N; i++)
            {
                foo[i] = Math.Sin((2 * Math.PI * i) / N);
            }

            Complex[] X = DFT.Calculate(foo);
            DrawRe(X);
            DrawIm(X);
            DrawMg(X);
            DrawPh(X);
        }