コード例 #1
0
ファイル: DenseMatrixComplex.cs プロジェクト: meshdgp/MeshDGP
        public DenseMatrixComplex(int rows, int columns)
        {
            datas = new Complex[rows, columns];

            this.rowCount = rows;
            this.columnCount = columns;
        }
コード例 #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ComplexImage"/> class.
 /// </summary>
 /// 
 /// <param name="width">Image width.</param>
 /// <param name="height">Image height.</param>
 /// 
 /// <remarks>The constractor is protected, what makes it imposible to instantiate this
 /// class directly. To create an instance of this class <see cref="FromBitmap(Bitmap)"/> or
 /// <see cref="FromBitmap(BitmapData)"/> method should be used.</remarks>
 ///
 protected ComplexImage( int width, int height )
 {
     this.width = width;
     this.height = height;
     this.data = new Complex[height, width];
     this.fourierTransformed = false;
 }
コード例 #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ComplexImage"/> class
 /// </summary>
 /// 
 /// <param name="width">Image width</param>
 /// <param name="height">Image height</param>
 /// 
 protected ComplexImage( int width, int height )
 {
     this.width  = width;
     this.height = height;
     this.data   = new Complex[height, width];
     this.fmode = false;
 }
コード例 #4
0
ファイル: FilterBuilder.cs プロジェクト: SlimSalamin/FFTTools
 /// <summary>
 ///     Builder constructor
 /// </summary>
 /// <param name="filterKernel"></param>
 /// <param name="filterPower"></param>
 /// <param name="keepOption"></param>
 public FilterBuilder(Complex[,] filterKernel, double filterPower = 1,
     KeepOption keepOption = KeepOption.AverageAndDelta)
 {
     _filterMode = FilterMode.FilterKernel;
     _filterKernel = filterKernel;
     _filterPower = filterPower;
     _keepOption = keepOption;
 }
コード例 #5
0
ファイル: FourierTransform.cs プロジェクト: gpatho/Fourier
 private static void CreateMatrixes(int M, int N, CancellationToken ct)
 {
     if (!ct.IsCancellationRequested)
         phic = GetMatrixPhi(M, ct);
     if (!ct.IsCancellationRequested)
         phicC = GetMatrixPhiR(phic, ct);
     if (!ct.IsCancellationRequested)
         phir = GetMatrixPhi(N, ct);
     if (!ct.IsCancellationRequested)
         phirC = GetMatrixPhiR(phir, ct);
 }
コード例 #6
0
        public Processor()
        {
            dim = DEFAULT_DIM;
            pic = new Complex[dim, dim];

            for (int j = 0; j < dim; ++j)
            {
                for (int i = 0; i < dim; ++i)
                {
                    pic[i, j] = new Complex(1, 0);
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// New ComplexImage, from a greyscale double array.
        /// The values are not re-normalized.
        /// </summary>
        /// <param name="grayscale"></param>
        public ComplexImage(double[,] grayscale)
        {
            int width = grayscale.GetLength(0);
            int height = grayscale.GetLength(1);
            _elemns = new Complex[width, height];

            for (int x = 0; x < width; ++x)
            {
                for (int y = 0; y < height; ++y)
                {
                    _elemns[x, y] = new Complex(grayscale[x, y], 0);
                }
            }
        }
コード例 #8
0
        public Processor(int dim, params Gaussian[] gaussians)
        {
            this.dim = dim;
            pic = new Complex[dim, dim];

            for (int j = 0; j < dim; ++j)
            {
                for (int i = 0; i < dim; ++i)
                {
                    pic[i, j] = new Complex(0, 0);
                    foreach (Gaussian gaussian in gaussians)
                    {
                        pic[i, j].Re += gaussian.Amplitude *
                            Math.Exp(
                            -(MathUtils.Sqr(i - gaussian.Center.X) / gaussian.SigmaX)
                            -(MathUtils.Sqr(j - gaussian.Center.Y) / gaussian.SigmaY));
                    }
                }
            }
        }
コード例 #9
0
        Complex[,] Inverse(Complex[,] m)
        {
            int n = m.GetLength(0);

            if (m.GetLength(1) != n)
            {
                throw new ArgumentException("Matrix must be square");
            }

            Complex[,] a = (Complex[, ])m.Clone();
            Complex[,] b = Identity(n);

            for (int p = 0; p < n; p++)
            {
                int    maxI  = p;
                double maxAI = Complex.Abs(a[p, p]);
                for (int i = p + 1; i < n; i++)
                {
                    double maxAICand = Complex.Abs(a[i, p]);
                    if (maxAICand > maxAI)
                    {
                        maxI  = i;
                        maxAI = maxAICand;
                    }
                }
                if (maxAI == 0.0)
                {
                    return(null);
                }
                if (maxI != p)
                {
                    for (int j = 0; j < n; j++)
                    {
                        Complex temp = a[p, j];
                        a[p, j]    = a[maxI, j];
                        a[maxI, j] = temp;
                        temp       = b[p, j];
                        b[p, j]    = b[maxI, j];
                        b[maxI, j] = temp;
                    }
                }

                Complex x = a[p, p];
                for (int j = 0; j < n; j++)
                {
                    a[p, j] /= x;
                    b[p, j] /= x;
                }

                for (int i = 0; i < n; i++)
                {
                    if (i == p)
                    {
                        continue;
                    }
                    x = a[i, p];
                    for (int j = 0; j < n; j++)
                    {
                        a[i, j] -= a[p, j] * x;
                        b[i, j] -= b[p, j] * x;
                    }
                }
            }

            return(b);
        }
コード例 #10
0
 public static Complex[,] GetInverseFourier(Complex[,] x)
 {
     Complex[,] DN = GetDN(x.GetLength(0), true);
     Complex[,] DM = GetDN(x.GetLength(1), true);
     return(Complex.Multiply(Complex.Multiply(DM, x), DN));
 }
コード例 #11
0
        /// <summary>
        /// Two dimensional Discrete Fourier Transform.
        /// </summary>
        ///
        /// <param name="data">Data to transform.</param>
        /// <param name="direction">Transformation direction.</param>
        ///
        public static void DFT2(Complex[,] data, Direction direction)
        {
            int    n = data.GetLength(0);                                       // rows
            int    m = data.GetLength(1);                                       // columns
            double arg, cos, sin;

            Complex[] dst = new Complex[System.Math.Max(n, m)];

            // process rows
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    dst[j] = Complex.Zero;

                    arg = -(int)direction * 2.0 * System.Math.PI * (double)j / (double)m;

                    // sum source elements
                    for (int k = 0; k < m; k++)
                    {
                        cos = System.Math.Cos(k * arg);
                        sin = System.Math.Sin(k * arg);

                        dst[j].Re += (data[i, k].Re * cos - data[i, k].Im * sin);
                        dst[j].Im += (data[i, k].Re * sin + data[i, k].Im * cos);
                    }
                }

                // copy elements
                if (direction == Direction.Forward)
                {
                    // devide also for forward transform
                    for (int j = 0; j < m; j++)
                    {
                        data[i, j].Re = dst[j].Re / m;
                        data[i, j].Im = dst[j].Im / m;
                    }
                }
                else
                {
                    for (int j = 0; j < m; j++)
                    {
                        data[i, j].Re = dst[j].Re;
                        data[i, j].Im = dst[j].Im;
                    }
                }
            }

            // process columns
            for (int j = 0; j < m; j++)
            {
                for (int i = 0; i < n; i++)
                {
                    dst[i] = Complex.Zero;

                    arg = -(int)direction * 2.0 * System.Math.PI * (double)i / (double)n;

                    // sum source elements
                    for (int k = 0; k < n; k++)
                    {
                        cos = System.Math.Cos(k * arg);
                        sin = System.Math.Sin(k * arg);

                        dst[i].Re += (data[k, j].Re * cos - data[k, j].Im * sin);
                        dst[i].Im += (data[k, j].Re * sin + data[k, j].Im * cos);
                    }
                }

                // copy elements
                if (direction == Direction.Forward)
                {
                    // devide also for forward transform
                    for (int i = 0; i < n; i++)
                    {
                        data[i, j].Re = dst[i].Re / n;
                        data[i, j].Im = dst[i].Im / n;
                    }
                }
                else
                {
                    for (int i = 0; i < n; i++)
                    {
                        data[i, j].Re = dst[i].Re;
                        data[i, j].Im = dst[i].Im;
                    }
                }
            }
        }
コード例 #12
0
 public static extern af_err af_device_array(out IntPtr array_arr, [In] Complex[,] data, uint ndims, [In] long[] dim_dims, DataType type);
コード例 #13
0
ファイル: ComplexSignal.cs プロジェクト: sujitzzz/framework
 /// <summary>
 ///   Create complex signal from complex array.
 /// </summary>
 ///
 /// <param name="signal">Source complex array.</param>
 /// <param name="sampleRate">Sample rate of the signal.</param>
 ///
 /// <returns>Returns an instance of complex signal.</returns>
 ///
 public static ComplexSignal FromArray(Complex[,] signal, int sampleRate)
 {
     return(ComplexSignal.FromArray(signal, sampleRate, ComplexSignalStatus.Normal));
 }
コード例 #14
0
ファイル: Matrix.cs プロジェクト: erashid/Extensions
 /// <summary>
 ///   Constructs a matrix and assigns value to diagonal elements.
 /// </summary>
 /// <param name="m"> Number of rows. </param>
 /// <param name="n"> Number of columns. </param>
 /// <param name="diagonal"> Value to assign to the diagnoal elements. </param>
 public Matrix(uint m, uint n, Complex diagonal)
 {
     _matrix = new Complex[m, n];
     for (var i = 0; i < m; ++i) for (var j = 0; j < n; ++j) _matrix[i, j] = (i == j) ? diagonal : Complex.Zero;
 }
コード例 #15
0
 /// <summary>
 /// Creates a matrix from a 2D array.
 /// </summary>
 /// <param name="data">The 2D array to create this matrix from.</param>
 /// <returns>A matrix with the given values.</returns>
 protected override Matrix <Complex> CreateMatrix(Complex[,] data)
 {
     return(new UserDefinedMatrix(data));
 }
コード例 #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserDefinedMatrix"/> class from a 2D array.
 /// </summary>
 /// <param name="data">The 2D array to create this matrix from.</param>
 public UserDefinedMatrix(Complex[,] data)
     : base(new UserDefinedMatrixStorage(data.GetLength(0), data.GetLength(1), (Complex[, ])data.Clone()))
 {
 }
コード例 #17
0
ファイル: VMD.cs プロジェクト: paul-fsk/VMD-cs
        public static void Compute(ref double[,] u, ref Complex[,] u_hat, ref double[,] omega, double[] signal, double alpha, double tau, int K, int DC, int init, double tol)
        {
            int    save_T = signal.Length;
            double fs     = 1 / (double)save_T;

            //int T = save_T;

            double[] f_mirrow = new double[2 * save_T];

            Array.Copy(signal, 0, f_mirrow, (int)(save_T / 2), save_T);

            for (int i = 0; i < save_T / 2; ++i)
            {
                f_mirrow[i] = signal[save_T / 2 - 1 - i];
            }
            for (int i = 3 * save_T / 2; i < 2 * save_T; i++)
            {
                f_mirrow[i] = signal[save_T + 3 * save_T / 2 - 1 - i];
            }

            double[] f = f_mirrow;

            int T = f.Length;

            Complex[] freqs   = Vector.Zeros <Complex>(T);
            double[]  timevec = Vector.Zeros <double>(T);

            for (int i = 0; i < T; i++)
            {
                timevec[i] = (double)(i + 1.0) / T;
                freqs[i]   = (timevec[i] - 0.5) - (double)(1 / T);
            }

            int N = 500;

            double[] Alpha = Vector.Create <double>(K, alpha);

            Complex[] freqvec = new Complex[T];

            for (int i = 0; i < freqvec.Length; i++)
            {
                freqvec[i] = f[i];
            }

            FourierTransform2.FFT(freqvec, FourierTransform.Direction.Forward);

            Complex[] f_hat      = circshift(freqvec, T / 2);
            Complex[] f_hat_plus = Vector.Zeros <Complex>(f_hat.Length);

            Array.Copy(f_hat, T / 2, f_hat_plus, T / 2, T / 2);

            Complex[,,] u_hat_plus = new Complex[N, K, T];

            Complex[,] omega_plus = Matrix.Zeros <Complex>(N, K);

            double[] tmp;

            switch (init)
            {
            case 1:
                for (int i = 0; i < K; i++)
                {
                    omega_plus[0, i] = (double)(0.5 / K) * i;
                }
                break;

            case 2:
                tmp = omega_init_method2(K, fs);
                for (int i = 0; i < K; i++)
                {
                    omega_plus[0, i] = tmp[i];
                }
                break;

            default:
                break;
            }

            if (DC != 0)
            {
                omega_plus[0, 0] = 0;
            }

            Complex[,] lambda_hat = new Complex[N, T];

            double uDiff = tol + eps_for_VMD;

            int n = 1;// loop counter

            Complex[] sum_uk = new Complex[T];

            int k;

            while (uDiff > tol && n < N)
            {
                k = 1;

                for (int i = 0; i < sum_uk.Length; ++i)
                {
                    sum_uk[i] = u_hat_plus[n - 1, K - 1, i] + sum_uk[i] - u_hat_plus[n - 1, 0, i];
                }

                //update spectrum of first mode through Wiener filter of residuals
                Complex[] Dividend_vec = new Complex[T];
                Complex[] Divisor_vec  = new Complex[T];

                for (int i = 0; i < sum_uk.Length; ++i)
                {
                    Dividend_vec[i]         = f_hat_plus[i] - sum_uk[i] - (lambda_hat[n - 1, i] / 2.0);
                    Divisor_vec[i]          = (1 + Alpha[k - 1] * (freqs[i] - omega_plus[n - 1, k - 1]) * (freqs[i] - omega_plus[n - 1, k - 1]));
                    u_hat_plus[n, k - 1, i] = Dividend_vec[i] / Divisor_vec[i];
                }

                if (DC == 0)
                {
                    Complex Dividend = new Complex(0, 0), Divisor = new Complex(0, 0), Addend;
                    for (int i = 0; i < T - T / 2; i++)
                    {
                        Addend    = u_hat_plus[n, k - 1, T / 2 + i].Magnitude * u_hat_plus[n, k - 1, T / 2 + i].Magnitude;
                        Divisor  += Addend;
                        Dividend += freqs[T / 2 + i] * Addend;
                    }
                    omega_plus[n, k - 1] = Dividend / Divisor;
                }

                for (k = 1; k < K; k++)
                {
                    for (int i = 0; i < u_hat_plus.GetLength(2); i++)
                    {
                        sum_uk[i] = u_hat_plus[n, k - 1, i] + sum_uk[i] - u_hat_plus[n - 1, k, i];
                    }

                    Complex[] Dividend_vec1 = new Complex[T];
                    Complex[] Divisor_vec1  = new Complex[T];

                    for (int i = 0; i < sum_uk.Length; ++i)
                    {
                        Dividend_vec1[i]    = f_hat_plus[i] - sum_uk[i] - (lambda_hat[n - 1, i] / 2.0);
                        Divisor_vec1[i]     = (1 + Alpha[k] * (freqs[i] - omega_plus[n - 1, k]) * (freqs[i] - omega_plus[n - 1, k]));
                        u_hat_plus[n, k, i] = Dividend_vec1[i] / Divisor_vec1[i];
                    }

                    Complex Dividend = new Complex(0, 0), Divisor = new Complex(0, 0), Addend;
                    for (int i = 0; i < T - T / 2; i++)
                    {
                        Addend    = u_hat_plus[n, k, T / 2 + i].Magnitude * u_hat_plus[n, k, T / 2 + i].Magnitude;
                        Divisor  += Addend;
                        Dividend += freqs[T / 2 + i] * Addend;
                    }
                    omega_plus[n, k] = Dividend / Divisor;
                }

                Complex[] sumv = sum(u_hat_plus, n);
                for (int i = 0; i < lambda_hat.GetLength(1); ++i)
                {
                    lambda_hat[n, i] = lambda_hat[n - 1, i] + tau * (sumv[i] - f_hat_plus[i]);
                }

                n++;

                Complex acc = new Complex(eps_for_VMD, 0);
                for (int i = 0; i < K; i++)
                {
                    Complex[] temp     = new Complex[u_hat_plus.GetLength(2)];
                    Complex[] conjtemp = new Complex[u_hat_plus.GetLength(2)];
                    for (int j = 0; j < u_hat_plus.GetLength(2); j++)
                    {
                        temp[j]     = u_hat_plus[n - 1, i, j] - u_hat_plus[n - 2, i, j];
                        conjtemp[j] = Complex.Conjugate(temp[j]);
                    }

                    var dottemp = Dot(temp, conjtemp);
                    acc = acc + dottemp / (double)T;
                }
                uDiff = acc.Magnitude;
            }

            N = Math.Min(N, n);

            omega = new double[N, omega_plus.GetLength(1)];

            for (int i = 0; i < omega_plus.GetLength(1); ++i)
            {
                for (int j = 0; j < N; j++)
                {
                    omega[j, i] = omega_plus[j, i].Real;
                }
            }

            u_hat = Matrix.Zeros <Complex>(T, K);

            for (int i = T / 2; i < T; i++)
            {
                for (int j = 0; j < K; j++)
                {
                    //var v = u_hat_plus[N - 1, j, i];
                    u_hat[i, j] = u_hat_plus[N - 1, j, i];
                }
            }

            for (int i = 0; i < T / 2; i++)
            {
                for (int j = 0; j < K; j++)
                {
                    //u_hat[i, j] = Complex.Conjugate(u_hat_plus[N - 1, j, T - i - 1]);
                    u_hat[i, j] = Complex.Conjugate(u_hat_plus[N - 1, j, i]);
                }
            }
            //for (int i = T / 2 - 1; i >= 0; i--)
            //    for (int j = 0; j < K; j++)
            //    {
            //        var v = Complex.Conjugate(u_hat_plus[N - 1, j, T - i - 1]);
            //        u_hat[i, j] = Complex.Conjugate(u_hat_plus[N - 1, j, T - i - 1]);
            //    }

            for (int i = 0; i < u_hat.GetLength(1); i++)
            {
                u_hat[0, i] = Complex.Conjugate(u_hat[u_hat.GetLength(1) - 1, i]); //Complex.Conjugate( u_hat[N - 1, i]);
            }

            u = Matrix.Zeros <double>(K, save_T);

            for (k = 0; k < K; k++)
            {
                Complex[] u_hat_col = ExtractColFromMatrixXcd(u_hat, k, T);
                u_hat_col = circshift(u_hat_col, (int)(Math.Floor((double)T / 2)));
                FourierTransform2.FFT(u_hat_col, FourierTransform.Direction.Backward);

                for (int t = 0; t < save_T; t++)
                {
                    u[k, t] = u_hat_col[t + T / 4].Real;
                }
            }

            //u_hat = Matrix.Zeros<Complex>(T, K);

            //double[] result_timevec = Vector.Zeros<double>(save_T);

            //for (int i = 0; i < save_T; i += 1)
            //{
            //    result_timevec[i] = (double)(i + 1) / save_T;
            //}

            //for (k = 0; k < K; k++)
            //{
            //    Complex[] u_row = ExtractRowFromMatrixXd(u, k, save_T);
            //    FourierTransform2.FFT(u_row,FourierTransform.Direction.Backward);
            //    u_row = circshift(u_row, save_T / 2);
            //    for (int t = 0; t < save_T; t++)
            //        u[k, t] = u_row[t].Real;
            //}
        }
コード例 #18
0
 public UserDefinedMatrixStorage(int rowCount, int columnCount)
     : base(rowCount, columnCount)
 {
     Data = new Complex[rowCount, columnCount];
 }
コード例 #19
0
 public UserDefinedMatrixStorage(int rowCount, int columnCount, Complex[,] data)
     : base(rowCount, columnCount)
 {
     Data = data;
 }
コード例 #20
0
ファイル: DenseMatrixComplex.cs プロジェクト: meshdgp/MeshDGP
 public void AppendColumns(int columns)
 {
     columnCount += columns;
     datas = (Complex[,])ResizeArray(datas, new int[] { this.rowCount, this.columnCount });
 }
コード例 #21
0
ファイル: DenseMatrixComplex.cs プロジェクト: meshdgp/MeshDGP
 public void AppendRows(int rows)
 {
     rowCount += rows;
     datas = (Complex[,])ResizeArray(datas, new int[] { this.rowCount, this.columnCount });
 }
コード例 #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserDefinedMatrix"/> class from a 2D array. 
 /// </summary>
 /// <param name="data">The 2D array to create this matrix from.</param>
 public UserDefinedMatrix(Complex[,] data) : base(data.GetLength(0), data.GetLength(1))
 {
     _data = (Complex[,])data.Clone();
 }
コード例 #23
0
        /// <summary>
        /// Reduces a complex Hermitian matrix to a real symmetric tridiagonal matrix using unitary similarity transformations.
        /// </summary>
        /// <param name="matrixA">Source matrix to reduce</param>
        /// <param name="d">Output: Arrays for internal storage of real parts of eigenvalues</param>
        /// <param name="e">Output: Arrays for internal storage of imaginary parts of eigenvalues</param>
        /// <param name="tau">Output: Arrays that contains further information about the transformations.</param>
        /// <param name="order">Order of initial matrix</param>
        /// <remarks>This is derived from the Algol procedures HTRIDI by
        /// Smith, Boyle, Dongarra, Garbow, Ikebe, Klema, Moler, and Wilkinson, Handbook for
        /// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
        /// Fortran subroutine in EISPACK.</remarks>
        static void SymmetricTridiagonalize(Complex[,] matrixA, double[] d, double[] e, Complex[] tau, int order)
        {
            double hh;

            tau[order - 1] = Complex.One;

            for (var i = 0; i < order; i++)
            {
                d[i] = matrixA[i, i].Real;
            }

            // Householder reduction to tridiagonal form.
            for (var i = order - 1; i > 0; i--)
            {
                // Scale to avoid under/overflow.
                var scale = 0.0;
                var h     = 0.0;

                for (var k = 0; k < i; k++)
                {
                    scale = scale + Math.Abs(matrixA[i, k].Real) + Math.Abs(matrixA[i, k].Imaginary);
                }

                if (scale == 0.0)
                {
                    tau[i - 1] = Complex.One;
                    e[i]       = 0.0;
                }
                else
                {
                    for (var k = 0; k < i; k++)
                    {
                        matrixA[i, k] /= scale;
                        h             += matrixA[i, k].MagnitudeSquared();
                    }

                    Complex g = Math.Sqrt(h);
                    e[i] = scale * g.Real;

                    Complex temp;
                    var     f = matrixA[i, i - 1];
                    if (f.Magnitude != 0)
                    {
                        temp = -(matrixA[i, i - 1].Conjugate() * tau[i].Conjugate()) / f.Magnitude;
                        h   += f.Magnitude * g.Real;
                        g    = 1.0 + (g / f.Magnitude);
                        matrixA[i, i - 1] *= g;
                    }
                    else
                    {
                        temp = -tau[i].Conjugate();
                        matrixA[i, i - 1] = g;
                    }

                    if ((f.Magnitude == 0) || (i != 1))
                    {
                        f = Complex.Zero;
                        for (var j = 0; j < i; j++)
                        {
                            var tmp = Complex.Zero;

                            // Form element of A*U.
                            for (var k = 0; k <= j; k++)
                            {
                                tmp += matrixA[j, k] * matrixA[i, k].Conjugate();
                            }

                            for (var k = j + 1; k <= (i - 1); k++)
                            {
                                tmp += matrixA[k, j].Conjugate() * matrixA[i, k].Conjugate();
                            }

                            // Form element of P
                            tau[j] = tmp / h;
                            f     += (tmp / h) * matrixA[i, j];
                        }

                        hh = f.Real / (h + h);

                        // Form the reduced A.
                        for (var j = 0; j < i; j++)
                        {
                            f      = matrixA[i, j].Conjugate();
                            g      = tau[j] - (hh * f);
                            tau[j] = g.Conjugate();

                            for (var k = 0; k <= j; k++)
                            {
                                matrixA[j, k] -= (f * tau[k]) + (g * matrixA[i, k]);
                            }
                        }
                    }

                    for (var k = 0; k < i; k++)
                    {
                        matrixA[i, k] *= scale;
                    }

                    tau[i - 1] = temp.Conjugate();
                }

                hh            = d[i];
                d[i]          = matrixA[i, i].Real;
                matrixA[i, i] = new Complex(hh, scale * Math.Sqrt(h));
            }

            hh            = d[0];
            d[0]          = matrixA[0, 0].Real;
            matrixA[0, 0] = hh;
            e[0]          = 0.0;
        }
コード例 #24
0
        public V2DataOnGrid(string filename) : base()
        {
            /* ФОРМАТ ВХОДНОГО ФАЙЛА
             * 1 строка - Info      - информация о таблице
             * 2 строка - Freq      - значение частоты
             * 3 строка - Grid1D Ox - значения Num и Step через пробел
             * 4 строка - Grid1D Oy - значения Num и Step через пробел
             *
             * 5 строка и дальше - таблица
             * Узел таблицы разделяется пробелом
             * Поля комлексного числа (действительная и мнимая части) нижним подчеркиванием
             *
             */

            /********* Пример входного файла *********/

            /*
             * Information
             * 100
             * 3 10
             * 5 10
             * 12,0_5,23 11,67_7,78 7,16_4,00 8,34_-7,55 1,09_1,09
             * 2,44_-5,43 16,11_7,90 -2,33_4,55 8,76_-7,10 1,01_-1,40
             * 1,67_5,29 1,10_7,36 7,18_-44,44 4,89_-1,10 1,09_1,34
             *
             */
            CultureInfo CIru = new CultureInfo("RU-ru");        // исправлена локализация

            FileStream fs = null;

            try
            {
                //Directory.SetCurrentDirectory()
                Directory.SetCurrentDirectory("..\\..\\..\\");  // путь к исходным файлам проекта
                fs = new FileStream(filename, FileMode.Open);
                StreamReader reader = new StreamReader(fs);

                Info = reader.ReadLine();
                Freq = double.Parse(reader.ReadLine(), CIru);
                string[] str;
                Grids = new Grid1D[2];

                for (int i = 0; i < 2; i++)
                {
                    str           = reader.ReadLine().Split(' ');
                    Grids[i].Num  = int.Parse(str[0], CIru);
                    Grids[i].Step = float.Parse(str[1], CIru);
                }

                Node = new Complex[Grids[0].Num, Grids[1].Num];
                string[] strnode;
                string[] strcompl;

                for (int i = 0; i < Grids[0].Num; i++)
                {
                    strnode = reader.ReadLine().Split(' ');
                    for (int j = 0; j < Grids[1].Num; j++)
                    {
                        strcompl   = strnode[j].Split('_');             // исправлен разделитель
                        Node[i, j] = new Complex(double.Parse(strcompl[0], CIru), double.Parse(strcompl[1], CIru));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
コード例 #25
0
        /// <summary>
        /// Nonsymmetric reduction from Hessenberg to real Schur form.
        /// </summary>
        /// <param name="eigenVectors">The eigen vectors to work on.</param>
        /// <param name="eigenValues">The eigen values to work on.</param>
        /// <param name="matrixH">Array for internal storage of nonsymmetric Hessenberg form.</param>
        /// <param name="order">Order of initial matrix</param>
        /// <remarks>This is derived from the Algol procedure hqr2,
        /// by Martin and Wilkinson, Handbook for Auto. Comp.,
        /// Vol.ii-Linear Algebra, and the corresponding
        /// Fortran subroutine in EISPACK.</remarks>
        static void NonsymmetricReduceHessenberToRealSchur(Matrix <Complex> eigenVectors, Vector <Complex> eigenValues, Complex[,] matrixH, int order)
        {
            // Initialize
            var n   = order - 1;
            var eps = Precision.DoublePrecision;

            double  norm;
            Complex x, y, z, exshift = Complex.Zero;

            // Outer loop over eigenvalue index
            var iter = 0;

            while (n >= 0)
            {
                // Look for single small sub-diagonal element
                var l = n;
                while (l > 0)
                {
                    var tst1 = Math.Abs(matrixH[l - 1, l - 1].Real) + Math.Abs(matrixH[l - 1, l - 1].Imaginary) + Math.Abs(matrixH[l, l].Real) + Math.Abs(matrixH[l, l].Imaginary);
                    if (Math.Abs(matrixH[l, l - 1].Real) < (eps * tst1))
                    {
                        break;
                    }

                    l--;
                }

                // Check for convergence
                // One root found
                if (l == n)
                {
                    matrixH[n, n] += exshift;
                    eigenValues[n] = matrixH[n, n];
                    n--;
                    iter = 0;
                }
                else
                {
                    // Form shift
                    Complex s;
                    if ((iter != 10) && (iter != 20))
                    {
                        s = matrixH[n, n];
                        x = matrixH[n - 1, n] * matrixH[n, n - 1].Real;

                        if ((x.Real != 0.0) || (x.Imaginary != 0.0))
                        {
                            y = (matrixH[n - 1, n - 1] - s) / 2.0;
                            z = ((y * y) + x).SquareRoot();
                            if (((y.Real * z.Real) + (y.Imaginary * z.Imaginary)) < 0.0)
                            {
                                z *= -1.0;
                            }

                            x /= y + z;
                            s  = s - x;
                        }
                    }
                    else
                    {
                        // Form exceptional shift
                        s = Math.Abs(matrixH[n, n - 1].Real) + Math.Abs(matrixH[n - 1, n - 2].Real);
                    }

                    for (var i = 0; i <= n; i++)
                    {
                        matrixH[i, i] -= s;
                    }

                    exshift += s;
                    iter++;

                    // Reduce to triangle (rows)
                    for (var i = l + 1; i <= n; i++)
                    {
                        s    = matrixH[i, i - 1].Real;
                        norm = SpecialFunctions.Hypotenuse(matrixH[i - 1, i - 1].Magnitude, s.Real);
                        x    = matrixH[i - 1, i - 1] / norm;
                        eigenValues[i - 1]    = x;
                        matrixH[i - 1, i - 1] = norm;
                        matrixH[i, i - 1]     = new Complex(0.0, s.Real / norm);

                        for (var j = i; j < order; j++)
                        {
                            y = matrixH[i - 1, j];
                            z = matrixH[i, j];
                            matrixH[i - 1, j] = (x.Conjugate() * y) + (matrixH[i, i - 1].Imaginary * z);
                            matrixH[i, j]     = (x * z) - (matrixH[i, i - 1].Imaginary * y);
                        }
                    }

                    s = matrixH[n, n];
                    if (s.Imaginary != 0.0)
                    {
                        s            /= matrixH[n, n].Magnitude;
                        matrixH[n, n] = matrixH[n, n].Magnitude;

                        for (var j = n + 1; j < order; j++)
                        {
                            matrixH[n, j] *= s.Conjugate();
                        }
                    }

                    // Inverse operation (columns).
                    for (var j = l + 1; j <= n; j++)
                    {
                        x = eigenValues[j - 1];
                        for (var i = 0; i <= j; i++)
                        {
                            z = matrixH[i, j];
                            if (i != j)
                            {
                                y = matrixH[i, j - 1];
                                matrixH[i, j - 1] = (x * y) + (matrixH[j, j - 1].Imaginary * z);
                            }
                            else
                            {
                                y = matrixH[i, j - 1].Real;
                                matrixH[i, j - 1] = new Complex(((x.Real * y.Real) - (x.Imaginary * y.Imaginary)) + (matrixH[j, j - 1].Imaginary * z.Real), matrixH[i, j - 1].Imaginary);
                            }

                            matrixH[i, j] = (x.Conjugate() * z) - (matrixH[j, j - 1].Imaginary * y);
                        }

                        for (var i = 0; i < order; i++)
                        {
                            y = eigenVectors.At(i, j - 1);
                            z = eigenVectors.At(i, j);
                            eigenVectors.At(i, j - 1, (x * y) + (matrixH[j, j - 1].Imaginary * z));
                            eigenVectors.At(i, j, (x.Conjugate() * z) - (matrixH[j, j - 1].Imaginary * y));
                        }
                    }

                    if (s.Imaginary != 0.0)
                    {
                        for (var i = 0; i <= n; i++)
                        {
                            matrixH[i, n] *= s;
                        }

                        for (var i = 0; i < order; i++)
                        {
                            eigenVectors.At(i, n, eigenVectors.At(i, n) * s);
                        }
                    }
                }
            }

            // All roots found.
            // Backsubstitute to find vectors of upper triangular form
            norm = 0.0;
            for (var i = 0; i < order; i++)
            {
                for (var j = i; j < order; j++)
                {
                    norm = Math.Max(norm, Math.Abs(matrixH[i, j].Real) + Math.Abs(matrixH[i, j].Imaginary));
                }
            }

            if (order == 1)
            {
                return;
            }

            if (norm == 0.0)
            {
                return;
            }

            for (n = order - 1; n > 0; n--)
            {
                x             = eigenValues[n];
                matrixH[n, n] = 1.0;

                for (var i = n - 1; i >= 0; i--)
                {
                    z = 0.0;
                    for (var j = i + 1; j <= n; j++)
                    {
                        z += matrixH[i, j] * matrixH[j, n];
                    }

                    y = x - eigenValues[i];
                    if ((y.Real == 0.0) && (y.Imaginary == 0.0))
                    {
                        y = eps * norm;
                    }

                    matrixH[i, n] = z / y;

                    // Overflow control
                    var tr = Math.Abs(matrixH[i, n].Real) + Math.Abs(matrixH[i, n].Imaginary);
                    if (((eps * tr) * tr) > 1)
                    {
                        for (var j = i; j <= n; j++)
                        {
                            matrixH[j, n] = matrixH[j, n] / tr;
                        }
                    }
                }
            }

            // Back transformation to get eigenvectors of original matrix
            for (var j = order - 1; j > 0; j--)
            {
                for (var i = 0; i < order; i++)
                {
                    z = Complex.Zero;
                    for (var k = 0; k <= j; k++)
                    {
                        z += eigenVectors.At(i, k) * matrixH[k, j];
                    }

                    eigenVectors.At(i, j, z);
                }
            }
        }
コード例 #26
0
        public static Complex[,] createEdgeDetectionFilter(Complex[,] fourierTAB, int rows, int cols,
                                                           double angleRadians, double cosPhiOffset, double minDistanceToCenter)
        {
            Complex[,] edgeDetectionFilterMask = new Complex[fourierTAB.GetLength(0), fourierTAB.GetLength(1)];

            for (int i = 0; i < fourierTAB.GetLength(0); i++)
            {
                for (int j = 0; j < fourierTAB.GetLength(1); j++)
                {
                    edgeDetectionFilterMask[i, j] = new Complex(0, 0);
                }
            }

            double  rowsByTwo   = rows / 2.0;
            double  colsByTwo   = cols / 2.0;
            Complex coefficient = fourierTAB[rows / 2, cols / 2];

            Vector2D right = new Vector2D(1, 0);

            right.rotate(angleRadians);

            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    if (i == rowsByTwo && j == colsByTwo)
                    {
                        continue;
                    }
                    if (j == colsByTwo)
                    {
                        float f = 5;
                    }

                    Vector2D vec           = new Vector2D(j - colsByTwo, i - rowsByTwo);
                    Vector2D normalizedVec = vec.getNormalized();

                    bool   validDirection = false;
                    double currentCosPhi  = Vector2D.dot(normalizedVec, right);
                    if (currentCosPhi >= 0)
                    {
                        if (1.0 - currentCosPhi <= cosPhiOffset)  // both vectors point to the same direction
                        {
                            validDirection = true;
                        }
                    }
                    else
                    {
                        if (1.0 + currentCosPhi <= cosPhiOffset)  // currentVec points in the opposite direction
                        {
                            validDirection = true;
                        }
                    }

                    if (validDirection)
                    {
                        if (minDistanceToCenter < vec.length())
                        {
                            edgeDetectionFilterMask[i, j] = fourierTAB[i, j];
                        }
                    }
                }
            }

            edgeDetectionFilterMask[rows / 2, cols / 2] = coefficient;
            return(edgeDetectionFilterMask);
        }
コード例 #27
0
ファイル: ComplexMatrix.cs プロジェクト: unhammer/gimp-sharp
 public ComplexMatrix(int size)
 {
     _size = size;
       _matrix = new Complex[size, size];
 }
コード例 #28
0
ファイル: Class1.cs プロジェクト: DenisFuryaev/3_course_HW
 public V2DataOnGrid() : base("", 0)
 {
     grid_settings = null;
     EM_array      = null;
 }
コード例 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserDefinedMatrix"/> class.
 /// </summary>
 /// <param name="rows">The number of rows.</param>
 /// <param name="columns">The number of columns.</param>
 public UserDefinedMatrix(int rows, int columns) : base(rows, columns)
 {
     _data = new Complex[rows, columns];
 }
コード例 #30
0
 public PaddedConvolver(Complex[,] kernel, Rectangle kernelSize)
 {
     fft             = new FFT(kernel.GetLength(0), kernel.GetLength(1));
     this.kernel     = kernel;
     this.kernelSize = kernelSize;
 }
コード例 #31
0
 public static extern af_err af_free_device([Out] Complex[,] ptr);
コード例 #32
0
        private static List <Minutia> SearchMinutiae(Complex[,] psi, Complex[,] lsEnhanced, Complex[,] ps)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            var size = new Size(psi.GetLength(0), psi.GetLength(1));

            for (int x = 0; x < size.Width; x++)
            {
                for (int y = 0; y < size.Height; y++)
                {
                    if (psi[x, y].Magnitude < tauPS)
                    {
                        psi[x, y] = 0;
                    }
                }
            }

            var grid = new int[psi.GetLength(0), psi.GetLength(1)];

            var maxs = psi.Select2D((x, row, column) =>
            {
                Point maxP  = new Point();
                double maxM = tauPS;
                for (int dRow = -NeighborhoodSize / 2; dRow <= NeighborhoodSize / 2; dRow++)
                {
                    for (int dColumn = -NeighborhoodSize / 2; dColumn <= NeighborhoodSize / 2; dColumn++)
                    {
                        var correctRow    = row + dRow;
                        var correctColumn = column + dColumn;

                        if (correctRow > 9 && correctColumn > 9 &&
                            correctColumn < psi.GetLength(1) - 10 && correctRow < psi.GetLength(0) - 10)
                        {
                            var value = psi[correctRow, correctColumn];
                            if (value.Magnitude > maxM)
                            {
                                maxM = value.Magnitude;
                                maxP = new Point(correctRow, correctColumn);
                            }
                        }
                    }
                }
                if (!maxP.IsEmpty)
                {
                    grid[maxP.X, maxP.Y]++;
                }
                return(maxP);
            });

            Dictionary <Point, int> responses = new Dictionary <Point, int>();

            foreach (var point in maxs)
            {
                if (!responses.ContainsKey(point))
                {
                    responses[point] = 0;
                }
                responses[point]++;
            }


            ImageHelper.SaveArrayAsBinary(grid, "C:\\temp\\grid.bin");
            var orderedListOfCandidates =
                responses.Where(x => x.Value >= 20 && x.Key.X > 0 && x.Key.Y > 0 && x.Key.X < psi.GetLength(0) - 1 && x.Key.Y < psi.GetLength(1) - 1)
                .OrderByDescending(x => x.Value)
                .Select(x => x.Key)
                .Where(x => psi[x.X, x.Y].Magnitude >= tauPS);
            List <Minutia> minutiae = new List <Minutia>();
            int            cnt      = 0;

            foreach (var candidate in orderedListOfCandidates)
            {
                int    count = 0;
                double sum   = 0;
                for (int dx = -ringOuterRadius; dx <= ringOuterRadius; dx++)
                {
                    for (int dy = -ringOuterRadius; dy <= ringOuterRadius; dy++)
                    {
                        if (Math.Abs(dx) < ringInnerRadius && Math.Abs(dy) < ringInnerRadius)
                        {
                            continue;
                        }
                        count++;
                        int xx = candidate.X + dx;
                        if (xx < 0)
                        {
                            xx = 0;
                        }
                        if (xx >= size.Width)
                        {
                            xx = size.Width - 1;
                        }
                        int yy = candidate.Y + dy;
                        if (yy < 0)
                        {
                            yy = 0;
                        }
                        if (yy >= size.Height)
                        {
                            yy = size.Height - 1;
                        }
                        sum += lsEnhanced[xx, yy].Magnitude;
                    }
                }
                if (sum / count > tauLS)
                {
                    cnt++;
                    if (!minutiae.Any(pt => (pt.X - candidate.X) * (pt.X - candidate.X) + (pt.Y - candidate.Y) * (pt.Y - candidate.Y) < 30))
                    {
                        minutiae.Add(new Minutia()
                        {
                            X = candidate.X, Y = candidate.Y, Angle = ps[candidate.X, candidate.Y].Phase
                        });
                    }
                }
            }

            var endList = minutiae.OrderByDescending(x =>
                                                     ps[x.X, x.Y].Magnitude)
                          .Take(MaxMinutiaeCount)
                          .ToList();

            sw.Stop();
            return(endList);
        }
コード例 #33
0
 public static Complex[] GetFourier(Complex[] x)
 {
     Complex[,] DN = GetDN(x.Length);
     return(Complex.Multiply(DN, x));
 }
コード例 #34
0
 /// <summary>
 /// Creates a matrix from a 2D array.
 /// </summary>
 /// <param name="data">The 2D array to create this matrix from.</param>
 /// <returns>A matrix with the given values.</returns>
 protected override Matrix <Complex> CreateMatrix(Complex[,] data)
 {
     return(SparseMatrix.OfArray(data));
 }
コード例 #35
0
 /// <summary>
 /// Create a new diagonal matrix as a copy of the given two-dimensional array.
 /// This new matrix will be independent from the provided array.
 /// The array to copy from must be diagonal as well.
 /// A new memory block will be allocated for storing the matrix.
 /// </summary>
 public static DiagonalMatrix OfArray(Complex[,] array)
 {
     return(new DiagonalMatrix(DiagonalMatrixStorage <Complex> .OfArray(array)));
 }
コード例 #36
0
 public static void CalcEta(Complex[,] eta, int i, double[] lambdas, Complex value)
 {
     fixed(Complex *etaPtr = &eta[i, 0])
     fixed(double *lambdasPtr = &lambdas[0])
     CalcEta(lambdas.Length, lambdasPtr, etaPtr, value);
 }
コード例 #37
0
        public byte[] Detect(short[] signal, List <double> bitLevels, out double?snr, out double?mer)
        {
            if (signal.Length == 0)
            {
                throw new SignalException("No data");
            }

            bool debug = false;

            double[] d1 = SignalStoD(signal);

            double bandwidth = (1 + rrcBeta) * bitrate;
            double freq      = carrierFreq;
            double freq1     = (freq - bandwidth / 2.0) * (1.0 - maxFreqDeviation);
            double freq2     = (freq + bandwidth / 2.0) * (1.0 + maxFreqDeviation);
            int    f1size    = (int)(4.0 * sampleRate / (freq2 - freq1)) | 1;

            double[] f1 = Mul(MakeBandPassFilter(freq1, freq2, f1size), MakeHannWindow(f1size));
            double[] d2 = Convolve(f1, d1);
            if (debug)
            {
                SaveWav("d2.wav", SignalDtoS(d2));
            }

            double bitLen = sampleRate / bitrate;

            int integrateBitLen1 = Convert.ToInt32(bitLen * 2);
            int integrateBitLen2 = Convert.ToInt32(bitLen * 32);

            double[] d21 = Abs(d2);
            double[] d22 = Integrate(d21, integrateBitLen1);
            if (debug)
            {
                SaveWav("d22.wav", SignalDtoS(d22));
            }
            double[] d23 = Integrate(d21, integrateBitLen2);
            if (debug)
            {
                SaveWav("d23.wav", SignalDtoS(d23));
            }

            int d24len = d22.Length - integrateBitLen2;

            if (d24len <= 0)
            {
                throw new SignalException("Not enough samples");
            }
            double[] d24 = new double[d24len];
            double[] d25 = new double[d24len];
            MinMax(d22, integrateBitLen2, d24, d25);

            if (debug)
            {
                SaveWav("d24.wav", SignalDtoS(d24));
            }
            if (debug)
            {
                SaveWav("d25.wav", SignalDtoS(d25));
            }


            double noiseLevel        = 0.0;
            int    signalStartCoarse = 0;
            int    signalEndCoarse   = 0;

            for (int i = integrateBitLen2; i < d24.Length; i++)
            {
                if ((signalStartCoarse == 0) &&
                    (d24[i] > 2.0 * d23[i]))
                {
                    noiseLevel        = d23[i - integrateBitLen1];
                    signalStartCoarse = i;
                }
                if ((signalStartCoarse != 0) &&
                    (signalEndCoarse == 0) &&
                    (d25[i] <= 2.0 * noiseLevel))
                {
                    signalEndCoarse = i;
                    break;
                }
            }

            if (signalStartCoarse == 0)
            {
                throw new SignalException("Signal start is not found");
            }
            if (signalEndCoarse == 0)
            {
                throw new SignalException("Signal end is not found");
            }

            signalStartCoarse -= Convert.ToInt32(bitLen);
            signalEndCoarse   += Convert.ToInt32(bitLen);
            if (signalStartCoarse < 0)
            {
                signalStartCoarse = 0;
            }
            if (signalEndCoarse > d24.Length)
            {
                signalEndCoarse = d24.Length;
            }

            int signalCenter = (signalStartCoarse + signalEndCoarse) / 2;

            int    signalStartFine = 0;
            int    signalEndFine   = 0;
            double signalAvgMin    = d24[signalCenter - integrateBitLen2 / 2];

            for (int i = signalStartCoarse; i < signalEndCoarse; i++)
            {
                if ((signalStartFine == 0) &&
                    (d24[i] > 0.25 * signalAvgMin))
                {
                    signalStartFine = i;
                }
                if ((signalStartFine != 0) &&
                    (signalEndFine == 0) &&
                    (d25[i] < 0.5 * signalAvgMin))
                {
                    signalEndFine = i;
                    break;
                }
            }
            if (signalEndFine == 0)
            {
                signalEndFine = signalEndCoarse;
            }

            if (signalStartFine == 0)
            {
                throw new SignalException("Signal fine start is not found");
            }

            // Adjustments are needed to correct shifts, which were made by integration
            // Signal positions are offsets from d1 of the peaks for first and last bits
            signalStartFine = Convert.ToInt32(signalStartFine + f1size / 2 + 0.1 * bitLen);
            signalEndFine   = Convert.ToInt32(signalEndFine + f1size / 2 - 1.7 * bitLen);

            // SNR calculation layout:
            // 16 bits of noise, 32 + 4 bits skipped, 24 bits of train sequence
            int    noisePowerStart = Convert.ToInt32(signalStartFine - (32 + 16) * bitLen - f1size / 2);
            int    trainPowerStart = Convert.ToInt32(signalStartFine + 4 * bitLen - f1size / 2);
            int    noisePowerEnd   = Convert.ToInt32(noisePowerStart + 16 * bitLen);
            int    trainPowerEnd   = Convert.ToInt32(trainPowerStart + 24 * bitLen);
            double noisePower      = 0.0;
            double trainPower      = 0.0;

            if (noisePowerStart < 0 || trainPowerEnd >= d2.Length)
            {
                throw new SignalException("Not enough samples for SNR calculation");
            }
            for (int i = noisePowerStart; i < noisePowerEnd; i++)
            {
                noisePower += d2[i] * d2[i];
            }
            for (int i = trainPowerStart; i < trainPowerEnd; i++)
            {
                trainPower += d2[i] * d2[i];
            }
            noisePower /= 16;
            trainPower /= 24;
            if (noisePower != 0.0 && trainPower > noisePower)
            {
                snr = 10 * Math.Log10((trainPower - noisePower) / noisePower);
            }
            else
            {
                snr = null;
            }

            double[] d2s = new double[signalEndFine - signalStartFine];
            for (int i = 0; i < d2s.Length; i++)
            {
                double d2v = d2[i + signalStartFine - f1size / 2];
                d2s[i] = d2v * d2v;
            }

            if (debug)
            {
                SaveWav("d2s.wav", SignalDtoS(Normalize(d2s)));
            }

            freq1 = (freq - freq * maxFreqDeviation) * 2;
            freq2 = (freq + freq * maxFreqDeviation) * 2;
            double estFreq = EstimateFrequency(d2s, freq1, freq2) / 2;


            double estBitrate    = bitrate * estFreq / freq;
            int    decFactor     = (int)(sampleRate / estBitrate / 3);
            int    decFilterSize = decFactor == 1 ? 0 : (int)(8 * sampleRate / estBitrate) | 1;
            double decSampleRate = (double)sampleRate / decFactor;
            double estBitlen     = decSampleRate / estBitrate;



            double[] trainSignal = MakePulsesShape(
                equalizerTrainSequence, decSampleRate, estBitrate, rrcBeta, sendRrcBitCount);
            if (debug)
            {
                SaveWav("trainSignal.wav", SignalDtoS(Mul(trainSignal, 0.67)), Convert.ToInt32(decSampleRate));
            }

            double[] rrc = Mul(MakeRootRaisedCosine(
                                   (int)(recvRrcBitCount * estBitlen) | 1,
                                   estBitlen, rrcBeta), 1 / estBitlen);

            if (debug)
            {
                SaveWav("rrc.wav", SignalDtoS(rrc));
            }



            int deltaRange = Convert.ToInt32(estBitlen * 2);

            int eqSize = (int)(10 * estBitlen) | 1;

            Complex[] d3 = new Complex[signalEndFine - signalStartFine +
                                       (rrc.Length + eqSize + deltaRange * 2) * decFactor + decFilterSize];
            int d3offset = signalStartFine - deltaRange * decFactor -
                           (rrc.Length + eqSize) * decFactor / 2 - decFilterSize / 2;
            double phaseScale = 2 * Math.PI * estFreq / sampleRate;

            for (int i = 0; i < d3.Length; i++)
            {
                double d1v   = d1[d3offset + i];
                double phase = i * phaseScale;
                d3[i] = new Complex(
                    d1v * Math.Cos(phase),
                    -d1v * Math.Sin(phase));
            }

            if (decFactor != 1)
            {
                double[] flt = MakeLowPassFilter(sampleRate / 2.0 / decFactor, decFilterSize);
                d3 = Decimate(flt, d3, decFactor);
            }

            if (debug)
            {
                double[] d3i = d3.Select(x => x.Real).ToArray();
                double[] d3q = d3.Select(x => x.Imaginary).ToArray();

                double maxAbsI  = MaxAbs(d3i);
                double maxAbsQ  = MaxAbs(d3q);
                double maxAbsIQ = Math.Max(maxAbsI, maxAbsQ);

                SaveWav("d3i.wav", SignalDtoS(Mul(d3i, 1.0 / maxAbsIQ)), (int)decSampleRate);
                SaveWav("d3q.wav", SignalDtoS(Mul(d3q, 1.0 / maxAbsIQ)), (int)decSampleRate);
            }

            int trainOffset1 = rrc.Length / 2;
            int trainOffset2 = (int)(sendRrcBitCount * estBitlen) / 2;
            int trainSize    = Convert.ToInt32(estBitlen * (equalizerTrainSequence.Length - 1));

            int bestDelta = 0;

            Complex[] bestEq = null;
            double    ajMin  = double.MaxValue;

            Complex[,] s = Transpose(ToComplex(
                                         trainSignal.Skip(trainOffset2).Take(trainSize).ToArray()));
            Complex[,] sct = ConjugateTranspose(s);
            Complex scts = Mul(sct, s)[0, 0];

            if (trainOffset1 + deltaRange * 2 + eqSize - 1 + trainSize > d3.Length)
            {
                throw new SignalException("Equalizer construction failed");
            }

            Parallel.For(0, deltaRange * 2 + 1, d =>
            {
                Complex[,] r = ToeplitzMatrix(
                    d3.Skip(trainOffset1 + d + eqSize - 1).Take(trainSize).ToArray(),
                    d3.Skip(trainOffset1 + d).Take(eqSize).Reverse().ToArray());
                Complex[,] rct  = ConjugateTranspose(r);
                Complex[,] rctr = Mul(rct, r);
                Complex[,] rcts = Mul(rct, s);
                Complex[,] sctr = Mul(sct, r);
                Complex[,] f    = Mul(Inverse(rctr), rcts);
                double aj       = Complex.Abs(scts - Mul(sctr, f)[0, 0]);
                lock (s)
                {
                    if (aj < ajMin)
                    {
                        ajMin     = aj;
                        bestEq    = GetColumn(f, 0);
                        bestDelta = d;
                    }
                }
            });

            var d3f = Convolve(bestEq, d3);

            double[]     d4 = null;
            int          debugSampleRate          = 0;
            const double d3scale                  = 0.25;
            const int    debugInterpolationFactor = 8;

            if (debug)
            {
                double[] debugRrc = Mul(MakeRootRaisedCosine(
                                            (rrc.Length - 1) * debugInterpolationFactor + 1,
                                            estBitlen * debugInterpolationFactor,
                                            rrcBeta), 1 / estBitlen);

                var d3if = d3f.Select(x => x.Real).ToArray();
                var d3qf = d3f.Select(x => x.Imaginary).ToArray();
                SaveWav("d3if.wav", SignalDtoS(Mul(d3if, d3scale)), (int)decSampleRate);
                SaveWav("d3qf.wav", SignalDtoS(Mul(d3qf, d3scale)), (int)decSampleRate);

                debugSampleRate = (int)(decSampleRate * debugInterpolationFactor);
                var d3if2 = Convolve(debugRrc, StuffZeroes(d3if, debugInterpolationFactor));
                var d3qf2 = Convolve(debugRrc, StuffZeroes(d3qf, debugInterpolationFactor));
                SaveWav("d3if2.wav", SignalDtoS(Mul(d3if2, d3scale)), debugSampleRate);
                SaveWav("d3qf2.wav", SignalDtoS(Mul(d3qf2, d3scale)), debugSampleRate);

                d4 = new double[d3if2.Length];
            }

            var bits   = new List <bool>();
            var bitMER = new List <double>();

            for (double tf = bestDelta; tf < d3f.Length - rrc.Length + 1; tf += estBitlen)
            {
                int    ti = (int)tf;
                double ts = tf - ti;

                double[] rrcSubsample = MakeRootRaisedCosine(
                    (int)(recvRrcBitCount * estBitlen) | 1,
                    estBitlen, rrcBeta, ts);

                Complex sample = Convolve(rrcSubsample, d3f, ti) / estBitlen;

                double di = 1.0 - Math.Abs(sample.Real);
                double dq = 0.0 - sample.Imaginary;
                bitMER.Add(di * di + dq * dq);

                bits.Add(sample.Real > 0.0);
                bitLevels.Add(Math.Abs(sample.Real));

                if (debug)
                {
                    int ti2 = Convert.ToInt32(tf * debugInterpolationFactor);
                    if (ti2 == d4.Length)
                    {
                        ti2--;
                    }
                    d4[ti2] = sample.Real;
                }
            }

            if (debug)
            {
                SaveWav("d4.wav", SignalDtoS(Mul(d4, d3scale)), debugSampleRate);
            }

            if (bits.Count < equalizerTrainSequence.Length + payloadSizeLsbSize)
            {
                throw new SignalException("Wrong packet format");
            }

            bool[] plszlsbb = bits.Skip(equalizerTrainSequence.Length).Take(payloadSizeLsbSize).ToArray();
            int    plszlsb  = 0;

            for (int i = 0; i < payloadSizeLsbSize; i++)
            {
                plszlsb |= plszlsbb[i] ? (1 << payloadSizeLsbSize - i - 1) : 0;
            }

            int plszEst    = (bits.Count - equalizerTrainSequence.Length - payloadSizeLsbSize) / 8;
            int plsz       = plszEst;
            int lsbMask    = (1 << payloadSizeLsbSize) - 1;
            int plszEstLsb = plszEst & lsbMask;

            if (plszEstLsb != plszlsb)
            {
                plsz &= ~lsbMask;
                plsz |= plszlsb;
                if (plszEstLsb < plszlsb)
                {
                    plsz -= 1 << payloadSizeLsbSize;
                    if (plsz < 0)
                    {
                        throw new SignalException("Wrong payload size");
                    }
                }
            }

            int skippedBitCount = bits.Count -
                                  equalizerTrainSequence.Length - payloadSizeLsbSize - plsz * 8;

            bits.RemoveRange(bitLevels.Count - skippedBitCount, skippedBitCount);
            bitMER.RemoveRange(bitLevels.Count - skippedBitCount, skippedBitCount);
            bitLevels.RemoveRange(bitLevels.Count - skippedBitCount, skippedBitCount);
            bitMER.RemoveRange(0, equalizerTrainSequence.Length);
            bitLevels.RemoveRange(0, equalizerTrainSequence.Length);

            mer = Math.Log10(bitMER.Count() / bitMER.Sum()) * 10;

            if (!bits.Take(equalizerTrainSequence.Length).
                SequenceEqual(equalizerTrainSequence.Select(b => b == 1)))
            {
                throw new SignalException("Signal start marker is not found");
            }

            bits.RemoveRange(0, equalizerTrainSequence.Length + payloadSizeLsbSize);

            byte[] data = new byte[plsz];
            for (int i = 0; i < plsz * 8; i++)
            {
                data[i / 8] |= (byte)((bits[i] ? 1 : 0) << (7 - i % 8));
            }

            return(data);
        }
コード例 #38
0
 public static Complex[] CalculateCTop(NativeEnvelop ne, Complex[,] eta)
 => Calculate(ne, eta, CalculateCTop);
コード例 #39
0
 /// <summary>
 /// Creates a matrix from a 2D array.
 /// </summary>
 /// <param name="data">The 2D array to create this matrix from.</param>
 /// <returns>A matrix with the given values.</returns>
 protected override Matrix CreateMatrix(Complex[,] data)
 {
     return(new DenseMatrix(data));
 }
コード例 #40
0
 public static Complex[] CalculateDBot(NativeEnvelop ne, Complex[,] eta)
 => Calculate(ne, eta, CalculateDBot);
コード例 #41
0
        /// <summary>
        /// Nonsymmetric reduction to Hessenberg form.
        /// </summary>
        /// <param name="eigenVectors">The eigen vectors to work on.</param>
        /// <param name="matrixH">Array for internal storage of nonsymmetric Hessenberg form.</param>
        /// <param name="order">Order of initial matrix</param>
        /// <remarks>This is derived from the Algol procedures orthes and ortran,
        /// by Martin and Wilkinson, Handbook for Auto. Comp.,
        /// Vol.ii-Linear Algebra, and the corresponding
        /// Fortran subroutines in EISPACK.</remarks>
        static void NonsymmetricReduceToHessenberg(Matrix <Complex> eigenVectors, Complex[,] matrixH, int order)
        {
            var ort = new Complex[order];

            for (var m = 1; m < (order - 1); m++)
            {
                // Scale column.
                var scale = 0.0;
                for (var i = m; i < order; i++)
                {
                    scale += Math.Abs(matrixH[i, m - 1].Real) + Math.Abs(matrixH[i, m - 1].Imaginary);
                }

                if (scale != 0.0)
                {
                    // Compute Householder transformation.
                    var h = 0.0;
                    for (var i = order - 1; i >= m; i--)
                    {
                        ort[i] = matrixH[i, m - 1] / scale;
                        h     += ort[i].MagnitudeSquared();
                    }

                    var g = Math.Sqrt(h);
                    if (ort[m].Magnitude != 0)
                    {
                        h      = h + (ort[m].Magnitude * g);
                        g     /= ort[m].Magnitude;
                        ort[m] = (1.0 + g) * ort[m];
                    }
                    else
                    {
                        ort[m]            = g;
                        matrixH[m, m - 1] = scale;
                    }

                    // Apply Householder similarity transformation
                    // H = (I-u*u'/h)*H*(I-u*u')/h)
                    for (var j = m; j < order; j++)
                    {
                        var f = Complex.Zero;
                        for (var i = order - 1; i >= m; i--)
                        {
                            f += ort[i].Conjugate() * matrixH[i, j];
                        }

                        f = f / h;
                        for (var i = m; i < order; i++)
                        {
                            matrixH[i, j] -= f * ort[i];
                        }
                    }

                    for (var i = 0; i < order; i++)
                    {
                        var f = Complex.Zero;
                        for (var j = order - 1; j >= m; j--)
                        {
                            f += ort[j] * matrixH[i, j];
                        }

                        f = f / h;
                        for (var j = m; j < order; j++)
                        {
                            matrixH[i, j] -= f * ort[j].Conjugate();
                        }
                    }

                    ort[m]             = scale * ort[m];
                    matrixH[m, m - 1] *= -g;
                }
            }

            // Accumulate transformations (Algol's ortran).
            for (var i = 0; i < order; i++)
            {
                for (var j = 0; j < order; j++)
                {
                    eigenVectors.At(i, j, i == j ? Complex.One : Complex.Zero);
                }
            }

            for (var m = order - 2; m >= 1; m--)
            {
                if ((matrixH[m, m - 1] != Complex.Zero) && (ort[m] != Complex.Zero))
                {
                    var norm = (matrixH[m, m - 1].Real * ort[m].Real) + (matrixH[m, m - 1].Imaginary * ort[m].Imaginary);

                    for (var i = m + 1; i < order; i++)
                    {
                        ort[i] = matrixH[i, m - 1];
                    }

                    for (var j = m; j < order; j++)
                    {
                        var g = Complex.Zero;
                        for (var i = m; i < order; i++)
                        {
                            g += ort[i].Conjugate() * eigenVectors.At(i, j);
                        }

                        // Double division avoids possible underflow
                        g /= norm;
                        for (var i = m; i < order; i++)
                        {
                            eigenVectors.At(i, j, eigenVectors.At(i, j) + (g * ort[i]));
                        }
                    }
                }
            }

            // Create real subdiagonal elements.
            for (var i = 1; i < order; i++)
            {
                if (matrixH[i, i - 1].Imaginary != 0.0)
                {
                    var y = matrixH[i, i - 1] / matrixH[i, i - 1].Magnitude;
                    matrixH[i, i - 1] = matrixH[i, i - 1].Magnitude;
                    for (var j = i; j < order; j++)
                    {
                        matrixH[i, j] *= y.Conjugate();
                    }

                    for (var j = 0; j <= Math.Min(i + 1, order - 1); j++)
                    {
                        matrixH[j, i] *= y;
                    }

                    for (var j = 0; j < order; j++)
                    {
                        eigenVectors.At(j, i, eigenVectors.At(j, i) * y);
                    }
                }
            }
        }
コード例 #42
0
 public Processor(Image img)
 {
     pic = MathUtils.BmpToArray((Bitmap)img, out dim);
 }
コード例 #43
0
ファイル: Matrix.cs プロジェクト: erashid/Extensions
 private void ReSize(int m, int n, bool preserve = false)
 {
     if (default(Complex[,]) != _matrix && m == Rows && n == Cols) return;
     var rows = Rows;
     var cols = Cols;
     if (0 == m && 0 == n) _matrix = new Complex[0, 0];
     else
     {
         var martix = default(Complex[,]);
         if (default(Complex[,]) != _matrix)
         {
             if (preserve)
             {
                 martix = new Complex[rows, cols];
                 for (uint i = 0; i < rows; ++i) for (uint j = 0; j < cols; ++j) martix[i, j] = _matrix[i, j];
             }
         }
         _matrix = new Complex[m, n];
         if (default(Complex[,]) != martix)
         {
             var rowLim = Math.Min((int) rows, m);
             var colLim = Math.Min((int) cols, n);
             for (var i = 0; i < rowLim; ++i) for (var j = 0; j < colLim; ++j) _matrix[i, j] = martix[i, j];
         }
     }
 }
コード例 #44
0
        public void Rollback()
        {
            this.data = new Complex[this.databackup.GetLength(0), this.databackup.GetLength(1)];

            for (int i = 0; i < this.data.GetLength(0); i++)
                for (int j = 0; j < this.data.GetLength(1); j++)
                    this.data[i, j] = this.databackup[i, j];
        }
コード例 #45
0
 /// <summary>
 /// New ComplexImage, from a Complex[,].
 /// </summary>
 /// <param name="greyscale"></param>
 public ComplexImage(Complex[,] complexArray)
 {
     _elemns = complexArray;
 }
コード例 #46
0
ファイル: SU3.cs プロジェクト: dptph/lat-qcd
 public Link(bool identity)
 {
     A = new Complex[SU3.d,SU3.d];
         for (int i = 0; i < SU3.d; i++)
             for (int j = 0; j < SU3.d; j++)
                 A[i, j] = new Complex();
         if (identity) for (int i = 0; i < SU3.d; i++) A[i, i].x = 1;
 }
コード例 #47
0
 public V4DataOnGrid(string measure, double frequency, Grid2D new_net) : base(measure, frequency)
 {
     this.net            = new_net;
     this.complex_massiv = new Complex[net.OX_net_counter, net.OY_net_counter];
 }
コード例 #48
0
        /// <summary>
        /// Creates a copy of a ComplexImage.
        /// </summary>
        /// <param name="copy">The ComplexImage to copy.</param>
        public ComplexImage(ComplexImage copy)
        {
            int width = copy.Width;
            int height = copy.Height;

            _elemns = new Complex[width, height];

            for (int x = 0; x < width; ++x)
            {
                for (int y = 0; y < height; ++y)
                {
                    _elemns[x, y] = copy[x, y].Clone();
                }
            }
        }
コード例 #49
0
 /// <summary>
 /// Clean ComplexImage of size width x height
 /// </summary>
 /// <param name="width"></param>
 /// <param name="height"></param>
 public ComplexImage(int width, int height)
 {
     _elemns = new Complex[width, height];
 }
コード例 #50
0
 public static extern af_err af_free_pinned([Out] Complex[,] ptr);
コード例 #51
0
 private void RefreshUnitaryPane(Complex[,] matrix)
 {
     if (matrix != null)
     {
         _matrix = matrix;
         _selectedType = SelectedType.UnitaryGate;
         _a00Text = string.Format(_complexFormatter, "{0:K10}", _matrix[0, 0]);
         _a01Text = string.Format(_complexFormatter, "{0:K10}", _matrix[0, 1]);
         _a10Text = string.Format(_complexFormatter, "{0:K10}", _matrix[1, 0]);
         _a11Text = string.Format(_complexFormatter, "{0:K10}", _matrix[1, 1]);
         ValidateMatrix();
         OnPropertyChanged("A00Text");
         OnPropertyChanged("A01Text");
         OnPropertyChanged("A10Text");
         OnPropertyChanged("A11Text");
     }
 }
コード例 #52
0
 public static extern af_err af_free_host([Out] Complex[,] ptr);
コード例 #53
0
 public UnitaryGate(Complex[,] matrix, RegisterRefModel target, RegisterRefModel? control = null)
     : base(target, control)
 {
     _matrix = matrix;
 }
コード例 #54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserDefinedMatrix"/> class. This matrix is square with a given size.
 /// </summary>
 /// <param name="order">the size of the square matrix.</param>
 public UserDefinedMatrix(int order) : base(order, order)
 {
     _data = new Complex[order, order];
 }