Example #1
0
        public void Test_AcquireSignal()
        {
            // Arrange
            double[] h        = { 1, 1, 1 };
            double[] x        = { 3, -1, 0, 1, 3, 2, 0, 1, 2, 1 };
            double[] expected = { 3, 2, 2, 0, 4, 6, 5, 3, 3, 4, 3, 1 };
            int      M        = h.Length;
            int      N        = this.Signal.MinBlockLength(h.Length);
            int      L        = N - M + 1;

            Complex[] appendSequence = new Complex[L - 1];
            Array.Clear(appendSequence, 0, L - 1);
            // FIR filter frequency response
            List <Complex> hComplex = this.ToComplex(h).ToList();

            Complex[] hFFT  = Signal.ComputePaddedFFT(ref hComplex, N, appendSequence.ToList());
            double    phase = 0;

            // Act
            foreach (double dataPoint in x)
            {
                Signal.AcquireSignal(dataPoint, phase, 0, 0, L, ref hFFT);
            }
            Signal.LastSamplesConvolution(ref hFFT, L);
            double[] xhConvRe  = this.RealPart(Signal.baseBandSignal.ToArray());
            double[] xhConvImg = this.ImaginaryPart(Signal.baseBandSignal.ToArray());

            // Assert
            for (int i = 0; i < xhConvRe.Length; i++)
            {
                Assert.True(Math.Abs(xhConvRe[i] - expected[i]) < 1e-12);
                Assert.True(Math.Abs(xhConvImg[i]) < 1e-12);
            }
        }
Example #2
0
        private List <Complex> Connect(List <Complex> evenPoints, List <Complex> oddPoints, bool reverse)
        {
            int N = oddPoints.Count * 2;

            Complex[] result = new Complex[N];
            for (int i = 0; i < oddPoints.Count; i++)
            {
                if (reverse)
                {
                    if (!_factorsReverse.ContainsKey($"{i}, {N}"))
                    {
                        _factorsReverse[$"{i}, {N}"] = CalculateReverseFactor(i, 1, N);
                    }
                    result[i] = evenPoints[i] + (_factorsReverse[$"{i}, {N}"] * oddPoints[i]);
                    result[i + oddPoints.Count] = evenPoints[i] - (_factorsReverse[$"{i}, {N}"] * oddPoints[i]);
                }
                else
                {
                    if (!_factors.ContainsKey($"{i}, {N}"))
                    {
                        _factors[$"{i}, {N}"] = CalculateFactor(i, 1, N);
                    }
                    result[i] = evenPoints[i] + (_factors[$"{i}, {N}"] * oddPoints[i]);
                    result[i + oddPoints.Count] = evenPoints[i] - (_factors[$"{i}, {N}"] * oddPoints[i]);
                }
            }
            return(result.ToList());
        }
Example #3
0
File: Bezier.cs Project: rAum/mmgk
        public Bezier(Complex[] init, int degreeRaising = 0)
        {
            points = init.ToList();

            for (int i = 0; i < degreeRaising; ++i)
            {
                DegreeElevate();
            }
        }
Example #4
0
        public List <Complex> FFT(List <Complex> input_list, int Num_Samples)
        {
            int N = Num_Samples;

            if (Num_Samples == 2)
            {
                List <Complex> result_list = new List <Complex>();
                result_list.Add(input_list[0] + input_list[1]);
                result_list.Add(input_list[0] - input_list[1]);
                return(result_list);
            }
            else
            {
                List <Complex> even_list = new List <Complex>();
                List <Complex> odd_list  = new List <Complex>();
                List <Complex> out_list  = new List <Complex>();
                Complex[]      arr       = new Complex[Num_Samples];

                for (int i = 0; i < input_list.Count; i++)
                {
                    if (i % 2 == 0)
                    {
                        even_list.Add(input_list[i]);
                    }
                    else
                    {
                        odd_list.Add(input_list[i]);
                    }
                }

                List <Complex> FFT1 = new List <Complex>();
                List <Complex> FFT2 = new List <Complex>();


                FFT1 = FFT(even_list, Num_Samples / 2);
                FFT2 = FFT(odd_list, Num_Samples / 2);
                Tuple <Complex, Complex> L;
                Complex W;
                for (int k = 0; k < Num_Samples / 2; k++)
                {
                    W      = new Complex(Math.Cos((2 * Math.PI * k) / Num_Samples), Math.Sin((2 * Math.PI * k) / Num_Samples));
                    arr[k] = (FFT1[k] + W * FFT2[k]);
                    arr[k + Num_Samples / 2] = (FFT1[k] - W * FFT2[k]);
                }


                out_list = arr.ToList();



                return(out_list);
            }
        }
Example #5
0
        public static double[] FFT(double[] sound)
        {
            Complex[] complexInput = new Complex[sound.Length];
            for (int i = 0; i < complexInput.Length; i++)
            {
                Complex tmp = new Complex(sound[i], 0);
                complexInput[i] = tmp;
            }

            MathNet.Numerics.IntegralTransforms.Fourier.Forward(complexInput);

            return(complexInput.ToList().Select(x => x.Magnitude).ToArray());
        }
Example #6
0
        public ActionResult fftC1(Data[] json)
        {
            Complex[] data = new Complex[json.Length];

            for (int i = 0; i < json.Length; i++)
            {
                var com = new Complex(json[i].Re, json[i].Im);
                data[i] = com;
            }

            FourierTransform.DFT(data, FourierTransform.Direction.Backward);

            var result = data.ToList().Select(s => new
            {
                Im        = s.Im,
                Re        = s.Re,
                Magnitude = s.Magnitude
            }).ToArray();

            return(new OkObjectResult(result));
        }
Example #7
0
 /// <summary>
 /// Computes convolution for remaining sequence samples
 /// </summary>
 /// <param name="firFilter">= Filter finite impulse response</param>
 /// <param name="L">= Length of window sequence</param>
 public void LastSamplesConvolution(ref Complex[] firFilter, int L)
 {
     if (complexSignal.Count > 0)
     {
         int M = firFilter.Length - L + 1;
         overlapSamples = oldComplexSamples.GetRange(0, M - 1).ToArray();
         Complex[] appendSamples = new Complex[L - complexSignal.Count];
         Array.Clear(appendSamples, 0, L - complexSignal.Count);
         List <Complex> firFilterList = firFilter.ToList();
         List <Complex> baseBandSig   = CircularConvolution(ref firFilterList, ref complexSignal, ref overlapSamples, appendSamples.ToList());
         baseBandSignal.AddRange(baseBandSig.GetRange(M - 1, L));
         // Remove all collected samples once the data points are collected and processed
         complexSignal.Clear();
     }
 }
Example #8
0
File: Bezier.cs Project: rAum/mmgk
        private void DegreeReduction(ref List<Complex> pt)
        {
            int m = pt.Count - 1;
            if (m < 3)
                return;
            int n = m - 1;
            Complex[] p = new Complex[n+1];

            if (n % 2 == 1)
            {
                int h = (n - 1) / 2;
                p[0] = pt[0];
                for (int i = 1; i <= h; ++i)
                {
                    double mi = m - i;
                    p[i] = (m/mi)*pt[i] - (i/mi)*p[i-1];
                }

                p[n] = pt[m];

                for (int i = n; i >= h + 2; --i)
                {
                    double ii = i;
                    p[i-1] = (m/i)*pt[i] - ((m-i)/i) * p[i];
                }
            }
            else
            {
                int h = n / 2;
                p[0] = pt[0];
                for (int i = 1; i <= h; ++i)
                {
                    double mi = m - i;
                    p[i] = (m/mi)*pt[i] - (i/mi)*p[i-1];
                }

                Complex q = new Complex(p[h].x, p[h].y);
                p[n] = pt[m];
                for (int i = n; i >= h+1; --i)
                {
                    double ii = i;
                    p[i - 1] = (m/ii)*pt[i] - ((m-i)/ii) * p[i];
                }

                p[h] = (p[h] + q) * 0.5;
            }

            pt = p.ToList();
        }
Example #9
0
        /// <summary>
        /// Main entry point
        /// </summary>
        /// <param name="args">= Input program arguments</param>
        static void Main(string[] args)
        {
            try
            {
                Dictionary <string, string> progArgs = Parse(args);
                // Program arguments
                double fs            = Convert.ToDouble(progArgs["sampling"]);
                double Ts            = 1.0 / fs;
                double fc            = Convert.ToDouble(progArgs["carrier"]);
                double passBand      = Convert.ToDouble(progArgs["passband"]);
                double stopBand      = Convert.ToDouble(progArgs["cutoffband"]);
                double gainDeviation = Convert.ToDouble(progArgs["gaindev"]);
                int    peakLag       = Convert.ToInt32(progArgs["peaklag"]);
                double peakThreshold = Convert.ToDouble(progArgs["peakthreshold"]);
                double peakInfluence = Convert.ToDouble(progArgs["peakinfluence"]);
                double tiThreshold   = Convert.ToDouble(progArgs["tithreshold"]);
                Dsp    Signal        = new Dsp();

                // Low pass FIR filter
                List <Complex> firImpulseResponse = Signal.KaiserWindowFir(gainDeviation, passBand, stopBand, fs);
                // FIR filter length
                int M = firImpulseResponse.Count;
                // Block length
                int N = Signal.MinBlockLength(M);
                // FFT input sequence length
                int       L = N - M + 1;
                Complex[] appendSequence = new Complex[L - 1];
                Array.Clear(appendSequence, 0, L - 1);
                // FIR filter frequency response
                Complex[] firFFT = Signal.ComputePaddedFFT(ref firImpulseResponse, N, appendSequence.ToList());
                // Main class output values
                List <double> timeStamps                 = new List <double>();
                List <double> peakTimeStamps             = new List <double>();
                List <double> peakTimeIntervals          = new List <double>();
                List <double> timeIntervalsMovingAverage = new List <double>();
                List <int>    peakIndexes                = new List <int>();
                List <int>    outliersTimeIntervals      = null;

                // Read data from input file
                using StreamReader inputFile = new StreamReader(progArgs["inputfile"]);
                WriteToFile outFile          = new WriteToFile(progArgs["outputfile"]);
                WriteToFile timeIntervalFile = new WriteToFile(progArgs["tifile"]);
                inputFile.BaseStream.Seek(0, SeekOrigin.Begin);
                string str                       = inputFile.ReadLine();
                double dLSBValue                 = -1;
                double dVoltageValue             = -1;
                double dValue                    = 0.0;
                double dAverage                  = 0.0;
                double dTimeStamp                = 0.0;
                double dPhase                    = 0.0;
                double timeIntervalsMoveAverage  = 0.0;
                double timeIntervalsMoveVariance = 0.0;
                double lastPeakTimeStamp         = 0.0;
                int    iNumSamples               = 1;
                int    numDetections             = 0;
                int    numMovingAverageSamples   = 0;
                while (str != null)
                {
                    string[] sDataValues = str.Split(',');
                    try
                    {
                        dTimeStamp    = ((double)iNumSamples - 1.0) * Ts;
                        dLSBValue     = Convert.ToDouble(sDataValues[0]);
                        dVoltageValue = Convert.ToDouble(sDataValues[1]);
                        dAverage      = ((double)iNumSamples - 1.0) / ((double)iNumSamples) * dAverage + dVoltageValue / ((double)iNumSamples);
                        // Remove DC offset
                        dValue = dVoltageValue - dAverage;
                        // Extract I and Q from signal and get base band signal
                        bool bPeakDetection = Signal.AcquireSignal(dValue, dPhase, dTimeStamp, fc, L, ref firFFT);
                        // Perform peak detection every L samples of the input sequence found from FFT transform
                        if (bPeakDetection)
                        {
                            PeakDetectionOutput detector = PeakDetection.PeakDetectionAlgorithm(
                                Signal.baseBandSignal.GetRange(numDetections * L, L),
                                Signal.timeStamp.GetRange(numDetections * L, L),
                                peakLag,
                                peakThreshold,
                                peakInfluence,
                                lastPeakTimeStamp,
                                numDetections * L
                                );
                            // Shift by L samples
                            numDetections += 1;
                            // Compute moving average of time intervals
                            numMovingAverageSamples += detector.peakTimeIntervals.Count;
                            outliersTimeIntervals    = PeakDetection.TimeIntervalOutlierDetection(
                                detector.peakTimeIntervals,
                                numMovingAverageSamples,
                                timeIntervalsMoveAverage,
                                ref timeIntervalsMoveVariance,
                                tiThreshold
                                );
                            double currentWindowSum = detector.peakTimeIntervals.Sum();
                            timeIntervalsMoveAverage =
                                (numMovingAverageSamples - detector.peakTimeIntervals.Count) *
                                timeIntervalsMoveAverage / numMovingAverageSamples +
                                currentWindowSum / numMovingAverageSamples;
                            // Time stamp for the next block of data to find the time intervals
                            if (detector.peakTimeStamps.Count > 0)
                            {
                                lastPeakTimeStamp = detector.peakTimeStamps.Last();
                            }
                            // Store outputs either list or write to a file
                            timeIntervalFile.SummaryOutliers(
                                detector,
                                outliersTimeIntervals,
                                timeIntervalsMoveAverage,
                                Math.Sqrt(timeIntervalsMoveVariance),
                                tiThreshold
                                );
                            timeIntervalsMovingAverage.Add(timeIntervalsMoveAverage);
                            peakTimeStamps.AddRange(detector.peakTimeStamps);
                            peakIndexes.AddRange(detector.peakIndexes);
                            peakTimeIntervals.AddRange(detector.peakTimeIntervals);
                        }
                        timeStamps.Add(dTimeStamp);
                        iNumSamples += 1;
                    }
                    catch (FormatException)
                    {
                    }
                    catch (IndexOutOfRangeException)
                    {
                    }
                    str = inputFile.ReadLine();
                }
                Signal.LastSamplesConvolution(ref firFFT, L);
                SignalOutput(outFile, Signal.baseBandSignal);
                outFile.outFileHandler.Close();
                timeIntervalFile.outFileHandler.Close();
                Console.WriteLine("End of Test");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }