/// <summary>
        /// Does a point wise add of two arrays <c>z = x + y</c>. This can be used
        /// to add vectors or matrices.
        /// </summary>
        /// <param name="x">The array x.</param>
        /// <param name="y">The array y.</param>
        /// <param name="result">The result of the addition.</param>
        /// <remarks>There is no equivalent BLAS routine, but many libraries
        /// provide optimized (parallel and/or vectorized) versions of this
        /// routine.</remarks>
        public virtual void AddArrays(Complex[] x, Complex[] y, Complex[] result)
        {
            if (y == null)
            {
                throw new ArgumentNullException("y");
            }

            if (x == null)
            {
                throw new ArgumentNullException("x");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            if (y.Length != x.Length || y.Length != result.Length)
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength);
            }

            CommonParallel.For(0, y.Length, 4096, (a, b) =>
            {
                for (int i = a; i < b; i++)
                {
                    result[i] = x[i] + y[i];
                }
            });
        }
        public void BackwardReal(double[] spectrum, int n, FourierTransformScaling scaling)
        {
            // TODO: backport proper, optimized implementation from Iridium

            Complex[] data = new Complex[n];
            data[0] = new Complex(spectrum[0], 0d);
            for (int i = 1, j = 2; i < data.Length/2; i++)
            {
                data[i] = new Complex(spectrum[j++], spectrum[j++]);
                data[data.Length - i] = data[i].Conjugate();
            }
            if (n.IsEven())
            {
                data[data.Length/2] = new Complex(spectrum[n], 0d);
            }
            else
            {
                data[data.Length/2] = new Complex(spectrum[n-1], spectrum[n]);
                data[data.Length/2 + 1] = data[data.Length/2].Conjugate();
            }

            Backward(data, scaling);

            for (int i = 0; i < data.Length; i++)
            {
                spectrum[i] = data[i].Real;
            }
            spectrum[n] = 0d;
        }
Example #3
0
        /// <summary>
        ///   Computes the absolute value of an array of complex numbers.
        /// </summary>
        /// 
        public static Complex[] Abs(this Complex[] x)
        {
            if (x == null) throw new ArgumentNullException("x");

            Complex[] r = new Complex[x.Length];
            for (int i = 0; i < x.Length; i++)
                r[i] = new Complex(x[i].Magnitude, 0);
            return r;
        }
Example #4
0
        public CompilerOutput(string input, Tokens tokens, System.Numerics.Complex returnVal, ParseTree parseTree, 
			PostfixedTokens postFixedTokens, string output)
        {
            this.Input = input;
                this.Tokens = tokens;
                this.ReturnValue = returnVal;
                this.ParseTree = parseTree;
                this.PostFixedTokens = postFixedTokens;
                this.Output = output;
        }
Example #5
0
        static int findRecurringCycleLength(int number)
        {
            //string numString = Decimal.Round((1 / (decimal)number), 28).ToString();
            string numString = (1 / (decimal)number).ToString();

            System.Numerics.Complex numerator = new System.Numerics.Complex(1, 1);
            System.Numerics.Complex denominator = new System.Numerics.Complex(number, number);

            System.Numerics.Complex muh = numerator / denominator;
            return 0;
        }
Example #6
0
        /// <summary>
        ///   Elementwise multiplication of two complex vectors.
        /// </summary>
        /// 
        public static Complex[] Multiply(this Complex[] a, Complex[] b)
        {
            if (a == null) throw new ArgumentNullException("a");
            if (b == null) throw new ArgumentNullException("b");

            Complex[] r = new Complex[a.Length];
            for (int i = 0; i < a.Length; i++)
            {
                r[i] = Complex.Multiply(a[i], b[i]);
            }
            return r;
        }
        /// <summary>
        /// Generate the bluestein sequence for the provided problem size.
        /// </summary>
        /// <param name="n">Number of samples.</param>
        /// <returns>Bluestein sequence exp(I*Pi*k^2/N)</returns>
        private static Complex[] BluesteinSequence(int n)
        {
            double s = Constants.Pi / n;
            var sequence = new Complex[n];

            for (int k = 0; k < sequence.Length; k++)
            {
                double t = s * (k * k);
                sequence[k] = new Complex(Math.Cos(t), Math.Sin(t));
            }

            return sequence;
        }
        /// <summary>
        /// Rescale FFT-the resulting vector according to the provided convention options.
        /// </summary>
        /// <param name="options">Fourier Transform Convention Options.</param>
        /// <param name="samples">Sample Vector.</param>
        private static void ForwardScaleByOptions(FourierOptions options, Complex[] samples)
        {
            if ((options & FourierOptions.NoScaling) == FourierOptions.NoScaling ||
                (options & FourierOptions.AsymmetricScaling) == FourierOptions.AsymmetricScaling)
            {
                return;
            }

            var scalingFactor = Math.Sqrt(1.0 / samples.Length);
            for (int i = 0; i < samples.Length; i++)
            {
                samples[i] *= scalingFactor;
            }
        }
        /// <summary>
        /// Convolution with the bluestein sequence (Parallel Version).
        /// </summary>
        /// <param name="samples">Sample Vector.</param>
        private static void BluesteinConvolutionParallel(Complex[] samples)
        {
            int n = samples.Length;
            Complex[] sequence = BluesteinSequence(n);

            // Padding to power of two >= 2N–1 so we can apply Radix-2 FFT.
            int m = ((n << 1) - 1).CeilingToPowerOfTwo();
            Complex[] b = new Complex[m];
            Complex[] a = new Complex[m];

            CommonParallel.Invoke(
                () =>
                {
                    // Build and transform padded sequence b_k = exp(I*Pi*k^2/N)
                    for (int i = 0; i < n; i++)
                    {
                        b[i] = sequence[i];
                    }

                    for (int i = m - n + 1; i < b.Length; i++)
                    {
                        b[i] = sequence[m - i];
                    }

                    Radix2(b, -1);
                },
                () =>
                {
                    // Build and transform padded sequence a_k = x_k * exp(-I*Pi*k^2/N)
                    for (int i = 0; i < samples.Length; i++)
                    {
                        a[i] = sequence[i].Conjugate() * samples[i];
                    }

                    Radix2(a, -1);
                });

            for (int i = 0; i < a.Length; i++)
            {
                a[i] *= b[i];
            }

            Radix2Parallel(a, 1);

            var nbinv = 1.0 / m;
            for (int i = 0; i < samples.Length; i++)
            {
                samples[i] = nbinv * sequence[i].Conjugate() * a[i];
            }
        }
 public void Backward(Complex[] spectrum, FourierTransformScaling scaling)
 {
     switch (scaling)
     {
         case FourierTransformScaling.SymmetricScaling:
             Fourier.BluesteinInverse(spectrum, FourierOptions.Default);
             break;
         case FourierTransformScaling.BackwardScaling:
             Fourier.BluesteinInverse(spectrum, FourierOptions.AsymmetricScaling);
             break;
         default:
             Fourier.BluesteinInverse(spectrum, FourierOptions.NoScaling);
             break;
     }
 }
Example #11
0
        static void Main(string [] args)
        {
            using (Lua lua = new Lua())
             		{
             lua.DebugHook += DebugHook;
             lua.SetDebugHook (NLua.Event.EventMasks.LUA_MASKLINE, 0);
             var a = new System.Numerics.Complex (10, 0);
             var b = new System.Numerics.Complex (0, 3);
             var x = a + b;

            // lua.LoadCLRPackage ();
             lua ["a"] = a;
             lua ["b"] = 1;
             var res = lua.DoString (@"return a + b")[0];

             		}
        }
Example #12
0
        /// <summary>
        /// Numerically stable hypotenuse of a right angle triangle, i.e. <code>(a,b) -> sqrt(a^2 + b^2)</code>
        /// </summary>
        /// <param name="a">The length of side a of the triangle.</param>
        /// <param name="b">The length of side b of the triangle.</param>
        /// <returns>Returns <code>sqrt(a<sup>2</sup> + b<sup>2</sup>)</code> without underflow/overflow.</returns>
        public static Complex Hypotenuse(Complex a, Complex b)
        {
            if (a.Magnitude > b.Magnitude)
            {
                var r = b.Magnitude / a.Magnitude;
                return a.Magnitude * Math.Sqrt(1 + (r * r));
            }

            if (b != 0.0)
            {
                // NOTE (ruegg): not "!b.AlmostZero()" to avoid convergence issues (e.g. in SVD algorithm)
                var r = a.Magnitude / b.Magnitude;
                return b.Magnitude * Math.Sqrt(1 + (r * r));
            }

            return 0d;
        }
        /// <summary>
        /// Rescale the iFFT-resulting vector according to the provided convention options.
        /// </summary>
        /// <param name="options">Fourier Transform Convention Options.</param>
        /// <param name="samples">Sample Vector.</param>
        private static void InverseScaleByOptions(FourierOptions options, Complex[] samples)
        {
            if ((options & FourierOptions.NoScaling) == FourierOptions.NoScaling)
            {
                return;
            }

            var scalingFactor = 1.0 / samples.Length;
            if ((options & FourierOptions.AsymmetricScaling) != FourierOptions.AsymmetricScaling)
            {
                scalingFactor = Math.Sqrt(scalingFactor);
            }

            for (int i = 0; i < samples.Length; i++)
            {
                samples[i] *= scalingFactor;
            }
        }
        /// <summary>
        /// Bluestein generic FFT for arbitrary sized sample vectors.
        /// </summary>
        /// <param name="samples">Time-space sample vector.</param>
        /// <param name="exponentSign">Fourier series exponent sign.</param>
        internal static void Bluestein(Complex[] samples, int exponentSign)
        {
            int n = samples.Length;
            if (n.IsPowerOfTwo())
            {
                Radix2(samples, exponentSign);
                return;
            }

            if (exponentSign == 1)
            {
                SwapRealImaginary(samples);
            }

            BluesteinConvolutionParallel(samples);

            if (exponentSign == 1)
            {
                SwapRealImaginary(samples);
            }
        }
        /// <summary>
        /// Does a point wise add of two arrays <c>z = x + y</c>. This can be used 
        /// to add vectors or matrices.
        /// </summary>
        /// <param name="x">The array x.</param>
        /// <param name="y">The array y.</param>
        /// <param name="result">The result of the addition.</param>
        /// <remarks>There is no equivalent BLAS routine, but many libraries
        /// provide optimized (parallel and/or vectorized) versions of this
        /// routine.</remarks>
        public virtual void AddArrays(Complex[] x, Complex[] y, Complex[] result)
        {
            if (y == null)
            {
                throw new ArgumentNullException("y");
            }

            if (x == null)
            {
                throw new ArgumentNullException("x");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            if (y.Length != x.Length || y.Length != result.Length)
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength);
            }

            if (Control.ParallelizeOperation(x.Length))
            {
                CommonParallel.For(0, y.Length, 4096, (a, b) =>
                    {
                        for (int i = a; i < b; i++)
                        {
                            result[i] = x[i] + y[i];
                        }
                    });
            }
            else
            {
                for (var index = 0; index < x.Length; index++)
                {
                    result[index] = x[index] + y[index];
                }
            }
        }
        /// <summary>
        /// Naive generic DFT, useful e.g. to verify faster algorithms.
        /// </summary>
        /// <param name="samples">Time-space sample vector.</param>
        /// <param name="exponentSign">Fourier series exponent sign.</param>
        /// <returns>Corresponding frequency-space vector.</returns>
        internal static Complex[] Naive(Complex[] samples, int exponentSign)
        {
            var w0 = exponentSign*Constants.Pi2/samples.Length;
            var spectrum = new Complex[samples.Length];

            CommonParallel.For(0, samples.Length, (u, v) =>
                {
                    for (int i = u; i < v; i++)
                    {
                        var wk = w0*i;
                        var sum = Complex.Zero;
                        for (var n = 0; n < samples.Length; n++)
                        {
                            var w = n*wk;
                            sum += samples[n]*new Complex(Math.Cos(w), Math.Sin(w));
                        }

                        spectrum[i] = sum;
                    }
                });

            return spectrum;
        }
Example #17
0
        /// <summary>
        /// Find all three complex roots of the cubic equation d + c*x + b*x^2 + a*x^3 = 0.
        /// Note the special coefficient order ascending by exponent (consistent with polynomials).
        /// </summary>
        public static Tuple<Complex, Complex, Complex> Roots(double d, double c, double b, double a)
        {
            double A = b*b - 3*a*c;
            double B = 2*b*b*b - 9*a*b*c + 27*a*a*d;
            double s = -1/(3*a);

            double D = (B*B - 4*A*A*A)/(-27*a*a);
            if (D == 0d)
            {
                if (A == 0d)
                {
                    var u = new Complex(s*b, 0d);
                    return new Tuple<Complex, Complex, Complex>(u, u, u);
                }

                var v = new Complex((9*a*d - b*c)/(2*A), 0d);
                var w = new Complex((4*a*b*c - 9*a*a*d - b*b*b)/(a*A), 0d);
                return new Tuple<Complex, Complex, Complex>(v, v, w);
            }

            var C = (A == 0)
                ? new Complex(B, 0d).CubicRoots()
                : ((B + Complex.Sqrt(B*B - 4*A*A*A))/2).CubicRoots();

            return new Tuple<Complex, Complex, Complex>(
                s*(b + C.Item1 + A/C.Item1),
                s*(b + C.Item2 + A/C.Item2),
                s*(b + C.Item3 + A/C.Item3));
        }
Example #18
0
 /// <summary>
 /// Returns the Hankel function of the second kind.
 /// <para>HankelH2(n, z) is defined as BesselJ(n, z) - j * BesselY(n, z).</para>
 /// </summary>
 /// <param name="n">The order of the Hankel function.</param>
 /// <param name="z">The value to compute the Hankel function of.</param>
 /// <returns>The Hankel function of the second kind.</returns>
 public static Complex HankelH2(double n, Complex z)
 {
     return(Amos.Cbesh2(n, z));
 }
Example #19
0
		public void TestOperatorNotEqual ()
		{
			using (Lua lua = new Lua ()) {
				var a = new System.Numerics.Complex (10, 0);
				var b = new System.Numerics.Complex (0, 3);
				var x = a != b;

				lua ["a"] = a;
				lua ["b"] = b;
				var res = lua.DoString (@"return a ~= b") [0];
				Assert.AreEqual (x, res);
			}
		}
Example #20
0
 public static extern unsafe int lis_vector_set_value(
     SetValueFlag flag, int i, LisScalar value, NativeLisVector *v);
Example #21
0
 public static extern unsafe int lis_matrix_set_value_new(
     SetValueFlag flag, int i, int j, LisScalar value, NativeLisMatrix *A);
Example #22
0
 public static extern unsafe int lis_vector_set_all(LisScalar alpha, NativeLisVector *vx);
Example #23
0
 public static bool IsZero(this Complex self)
 {
     return(self.Equals(Complex.Zero));
 }
 internal static extern void z_scale(IntPtr blasHandle, int n, Complex alpha, [In, Out] Complex[] x);
Example #25
0
 public static System.Numerics.Complex Signum(this System.Numerics.Complex z)
 => z == 0 ? 0 : z / z.Magnitude;
 internal static extern void z_matrix_multiply(IntPtr blasHandle, int transA, int transB, int m, int n, int k, Complex alpha, Complex[] x, Complex[] y, Complex beta, [In, Out] Complex[] c);
 internal static extern void z_axpy(IntPtr blasHandle, int n, Complex alpha, Complex[] x, [In, Out] Complex[] y);
Example #28
0
 public static Scalar ToScalar(this System.Numerics.Complex value)
 {
     return(new Scalar(THSTorch_complex64_to_scalar(value)));
 }
Example #29
0
 extern static IntPtr THSTorch_complex64_to_scalar(System.Numerics.Complex value);
Example #30
0
 /// <summary>
 /// Returns the exponentially scaled Hankel function of the second kind.
 /// <para>ScaledHankelH2(n, z) is given by Exp(z * j) * HankelH2(n, z) where j = Sqrt(-1).</para>
 /// </summary>
 /// <param name="n">The order of the Hankel function.</param>
 /// <param name="z">The value to compute the Hankel function of.</param>
 /// <returns>The exponentially scaled Hankel function of the second kind.</returns>
 public static Complex HankelH2Scaled(double n, Complex z)
 {
     return(Amos.ScaledCbesh2(n, z));
 }
Example #31
0
 // x = Log(c)
 public static KrdLab.clapack.Complex complex_Log(KrdLab.clapack.Complex c)
 {
     System.Numerics.Complex work = new System.Numerics.Complex(c.Real, c.Imaginary);
     work = System.Numerics.Complex.Log(work);
     return new KrdLab.clapack.Complex(work.Real, work.Imaginary);
 }
Example #32
0
 public static System.Numerics.Complex Abs(this System.Numerics.Complex z)
 => System.Numerics.Complex.Abs(z);
 /// <summary>
 /// Bluestein forward FFT for arbitrary sized sample vectors.
 /// </summary>
 /// <param name="samples">Sample vector, where the FFT is evaluated in place.</param>
 /// <param name="options">Fourier Transform Convention Options.</param>
 public void BluesteinForward(Complex[] samples, FourierOptions options)
 {
     Bluestein(samples, SignByOptions(options));
     ForwardScaleByOptions(options, samples);
 }
Example #34
0
 public static double Abs(this Complex self)
 {
     return(Complex.Abs(self));
 }
Example #35
0
            /// <summary>
            /// Prints eigenvalues and eigenvectors of complex generalized eigen-problems.
            /// </summary>
            public static void Print(SparseMatrix A, SparseMatrix B, ArpackResult result, bool shift)
            {
                int n     = A.RowCount;
                int nconv = result.ConvergedEigenValues;

                Console.WriteLine();
                Console.WriteLine("Testing ARPACK++ class ARluCompGenEig");
                Console.WriteLine("Complex generalized eigenvalue problem: A*x - lambda*B*x");
                Console.WriteLine(shift ? "Shift and invert mode" : "Regular mode");
                Console.WriteLine();

                Console.WriteLine("Dimension of the system            : " + n);
                Console.WriteLine("Number of 'requested' eigenvalues  : " + result.Count);
                Console.WriteLine("Number of 'converged' eigenvalues  : " + nconv);
                Console.WriteLine("Number of Arnoldi vectors generated: " + result.ArnoldiCount);
                Console.WriteLine("Number of iterations taken         : " + result.IterationsTaken);
                Console.WriteLine();

                var evals = result.EigenValues;
                var evecs = result.EigenVectors;

                // Printing eigenvalues.

                Console.WriteLine("Eigenvalues:");

                for (int i = 0; i < nconv; i++)
                {
                    Console.WriteLine("  lambda[" + (i + 1) + "]: " + evals[i]);
                }

                Console.WriteLine();


                if (evecs != null)
                {
                    // Printing the residual norm || A*x - lambda*B*x ||
                    // for the nconv accurately computed eigenvectors.

                    var x = new Complex[n];
                    var y = new Complex[n];
                    var r = new double[nconv]; // residuals

                    for (int i = 0; i < nconv; i++)
                    {
                        var lambda = evals[i];

                        evecs.Column(i, x);

                        Vector.Copy(x, y);

                        // y = B*x
                        B.Multiply(x, y);

                        // y = A*x - lambda*B*x
                        A.Multiply(1.0, x, -lambda, y);

                        r[i] = Vector.Norm(y) / Complex.Abs(lambda);
                    }

                    for (int i = 0; i < nconv; i++)
                    {
                        Console.WriteLine("||A*x(" + (i + 1) + ") - lambda(" + (i + 1) + ")*B*x(" + (i + 1) + ")||: " + r[i]);
                    }

                    Console.WriteLine();
                }
            }
 /// <summary>
 /// Naive inverse DFT, useful e.g. to verify faster algorithms.
 /// </summary>
 /// <param name="frequencySpace">Frequency-space sample vector.</param>
 /// <param name="options">Fourier Transform Convention Options.</param>
 /// <returns>Corresponding time-space vector.</returns>
 public Complex[] NaiveInverse(Complex[] frequencySpace, FourierOptions options)
 {
     var timeSpace = Naive(frequencySpace, -SignByOptions(options));
     InverseScaleByOptions(options, timeSpace);
     return timeSpace;
 }
        /// <summary>
        /// Solves a system of linear equations, <b>Ax = b</b>, with A EVD factorized.
        /// </summary>
        /// <param name="input">The right hand side vector, <b>b</b>.</param>
        /// <param name="result">The left hand side <see cref="Matrix{T}"/>, <b>x</b>.</param>
        public override void Solve(Vector <System.Numerics.Complex> input, Vector <System.Numerics.Complex> result)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            // Ax=b where A is an m x m matrix
            // Check that b is a column vector with m entries
            if (VectorEv.Count != input.Count)
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength);
            }

            // Check that x is a column vector with n entries
            if (VectorEv.Count != result.Count)
            {
                throw Matrix.DimensionsDontMatch <ArgumentException>(VectorEv, result);
            }

            if (IsSymmetric)
            {
                // Symmetric case -> x = V * inv(λ) * VH * b;
                var order = VectorEv.Count;
                var tmp   = new System.Numerics.Complex[order];
                System.Numerics.Complex value;

                for (var j = 0; j < order; j++)
                {
                    value = 0;
                    if (j < order)
                    {
                        for (var i = 0; i < order; i++)
                        {
                            value += ((DenseMatrix)MatrixEv).Values[(j * order) + i].Conjugate() * input[i];
                        }

                        value /= VectorEv[j].Real;
                    }

                    tmp[j] = value;
                }

                for (var j = 0; j < order; j++)
                {
                    value = 0;
                    for (var i = 0; i < order; i++)
                    {
                        value += ((DenseMatrix)MatrixEv).Values[(i * order) + j] * tmp[i];
                    }

                    result[j] = value;
                }
            }
            else
            {
                throw new ArgumentException(Resources.ArgumentMatrixSymmetric);
            }
        }
Example #38
0
 /// <summary>
 /// Applies the forward Fast Fourier Transform (FFT) to arbitrary-length sample vectors.
 /// </summary>
 /// <param name="samples">Sample vector, where the FFT is evaluated in place.</param>
 /// <param name="options">Fourier Transform Convention Options.</param>
 public static void FourierForward(Complex[] samples, FourierOptions options)
 {
     _dft.BluesteinForward(samples, options);
 }
        /// <summary>
        /// Solves a system of linear equations, <b>AX = B</b>, with A SVD factorized.
        /// </summary>
        /// <param name="input">The right hand side <see cref="Matrix{T}"/>, <b>B</b>.</param>
        /// <param name="result">The left hand side <see cref="Matrix{T}"/>, <b>X</b>.</param>
        public override void Solve(Matrix <System.Numerics.Complex> input, Matrix <System.Numerics.Complex> result)
        {
            // Check for proper arguments.
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            // The solution X should have the same number of columns as B
            if (input.ColumnCount != result.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSameColumnDimension);
            }

            // The dimension compatibility conditions for X = A\B require the two matrices A and B to have the same number of rows
            if (VectorEv.Count != input.RowCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension);
            }

            // The solution X row dimension is equal to the column dimension of A
            if (VectorEv.Count != result.RowCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSameColumnDimension);
            }

            if (IsSymmetric)
            {
                var order = VectorEv.Count;
                var tmp   = new System.Numerics.Complex[order];

                for (var k = 0; k < order; k++)
                {
                    for (var j = 0; j < order; j++)
                    {
                        System.Numerics.Complex value = 0.0;
                        if (j < order)
                        {
                            for (var i = 0; i < order; i++)
                            {
                                value += ((DenseMatrix)MatrixEv).Values[(j * order) + i].Conjugate() * input.At(i, k);
                            }

                            value /= VectorEv[j].Real;
                        }

                        tmp[j] = value;
                    }

                    for (var j = 0; j < order; j++)
                    {
                        System.Numerics.Complex value = 0.0;
                        for (var i = 0; i < order; i++)
                        {
                            value += ((DenseMatrix)MatrixEv).Values[(i * order) + j] * tmp[i];
                        }

                        result.At(j, k, value);
                    }
                }
            }
            else
            {
                throw new ArgumentException(Resources.ArgumentMatrixSymmetric);
            }
        }
Example #40
0
        /// <summary>
        /// Creates a new Spectrogram object instance and performs a STFT on the given audio
        /// </summary>
        /// <param name="wav">a Wav object</param>
        /// <param name="windowSize">is the size for the window in samples</param>
        /// <param name="fps">is the desired frame rate</param>
        /// <param name="online">work in online mode (i.e. use only past audio information)</param>
        /// <param name="phase">include phase information</param>
        public Spectrogram(Wav wav, MemoryAllocator allocator, int windowSize=2048, int fps=200, bool online=true, bool phase=true)
        {
            _allocator = allocator;
            //init some variables
            _wav = wav;
            _fps = fps;
            //derive some variables
            HopSize = _wav.Samplerate / (float)_fps; //use floats so that seeking works properly
            _frames = (int)(_wav.Samples / HopSize);
            _ffts = windowSize / 2;
            Bins = windowSize / 2; //initial number equal to ffts, can change if filters are used

            //init STFT matrix
            _STFT = _allocator.GetComplex32Matrix(_frames, _ffts);
            //_STFT = DenseMatrix.Create(_frames, _ffts, Complex32.Zero);

            //create windowing function
            var cArray = wav.Audio.ToRowArrays()[0];

            var values = MathNet.Numerics.Window.Hann(windowSize).Select(d => (float)d).ToArray();
            Window = _allocator.GetFloatVector(values.Length);
            Window.SetValues(values);

            //Window = Vector<float>.Build.DenseOfArray(MathNet.Numerics.Window.Hann(windowSize).Select(d => (float)d).ToArray());

            //step through all frames
            System.Numerics.Complex[] result = new System.Numerics.Complex[Window.Count];
            foreach (var frame in Enumerable.Range(0, _frames))
            {
                int seek;
                Vector<float> signal;
                //seek to the right position in the audio signal
                if (online)
                    //step back a complete windowSize after moving forward 1 hopSize
                    //so that the current position is at the stop of the window
                    seek = (int)((frame + 1) * HopSize - windowSize);
                else
                    //step back half of the windowSize so that the frame represents the centre of the window
                    seek = (int)(frame * HopSize - windowSize / 2);
                //read in the right portion of the audio
                if (seek >= _wav.Samples)
                    //stop of file reached
                    break;
                else if (seek + windowSize > _wav.Samples)
                {
                    //stop behind the actual audio stop, append zeros accordingly
                    int zeroAmount = seek + windowSize - _wav.Samples;
                    //var zeros = Vector<float>.Build.Dense(zeroAmount, 0);

                    var t = PythonUtilities.Slice<float>(cArray, seek, cArray.Length).ToArray();

                    //t.AddRange(zeros.ToList());

                    signal = _allocator.GetFloatVector(t.Length + zeroAmount);
                    for (int i = 0; i < t.Length; i++)
                    {
                        signal[i] = t[i];
                    }
                    //signal.SetValues(t);
                    //signal = Vector<float>.Build.DenseOfEnumerable(t);
                }
                else if (seek < 0)
                {
                    //start before actual audio start, pad with zeros accordingly
                    int zeroAmount = -seek;
                    var zeros = Vector<float>.Build.Dense(zeroAmount, 0).ToList();

                    var t = PythonUtilities.Slice<float>(cArray, 0, seek + windowSize).ToArray();
                    zeros.AddRange(t);

                    signal = _allocator.GetFloatVector(t.Length + zeroAmount);
                    signal.SetValues(zeros.ToArray());
                    //signal = Vector<float>.Build.DenseOfEnumerable(zeros);
                }
                else
                {
                    //normal read operation
                    var slice = PythonUtilities.Slice<float>(cArray, seek, seek + windowSize).ToArray();
                    signal = _allocator.GetFloatVector(slice.Length);
                    signal.SetValues(slice);

                    //signal = Vector<float>.Build.DenseOfEnumerable(PythonUtilities.Slice<float>(cArray, seek, seek + windowSize));
                }
                //multiply the signal with the window function
                signal = signal.PointwiseMultiply(Window);
                //only shift and perform complex DFT if needed
                if (phase)
                {
                    //circular shift the signal (needed for correct phase)
                    signal = NumpyCompatibility.FFTShift(signal);
                }
                //perform DFT
                //sanity check
                Debug.Assert(result.Length == signal.Count);
                for (int i = 0; i < result.Length; i++)
                {
                    result[i] = signal[i];
                }
                MathNet.Numerics.IntegralTransforms.Fourier.BluesteinForward(result, MathNet.Numerics.IntegralTransforms.FourierOptions.NoScaling);
                _STFT.SetRow(frame, result.Select(r => new Complex32((float)r.Real, (float)r.Imaginary)).Take(_ffts).ToArray());
                //var _newSTFTRow = result.Select(r => new Complex32((float)r.Real, (float)r.Imaginary)).Take(_ffts).ToArray();
                //_STFT.SetRow(frame, _newSTFTRow);
                //next frame
                _allocator.ReturnFloatVectorStorage((MathNet.Numerics.LinearAlgebra.Storage.DenseVectorStorage<float>)signal.Storage);
            }
            //magnitude spectrogram

            Spec = _allocator.GetFloatMatrix(_STFT.RowCount, _STFT.ColumnCount);
            if (phase)
                Phase = _allocator.GetFloatMatrix(_STFT.RowCount, _STFT.ColumnCount);
            for (int i = 0; i < Spec.RowCount; i++)
            {
                for (int j = 0; j < Spec.ColumnCount; j++)
                {
                    Spec.At(i, j, _STFT.At(i, j).Magnitude);
                    if (phase)
                        Phase.At(i, j, _STFT.At(i, j).Phase);
                }
            }
            //Spec = _STFT.Map(c => (float)c.Magnitude);

            //phase
            //if (phase)
            //{
            //    var imag = _STFT.Map(c => (float)c.Imaginary);
            //    var real = _STFT.Map(c => (float)c.Real);
            //    Phase = real.Map2((r, i) => (float)Math.Atan2(i,r), imag);
            //}
        }
 internal static extern void z_matrix_multiply(Transpose transA, Transpose transB, int m, int n, int k, Complex alpha, Complex[] x, Complex[] y, Complex beta, [In, Out] Complex[] c);
Example #42
0
 /// <summary>
 /// Evaluate a polynomial at point x.
 /// </summary>
 /// <param name="z">The location where to evaluate the polynomial at.</param>
 public Complex Evaluate(Complex z)
 {
     return(Evaluate(z, Coefficients));
 }
 /// <summary>
 /// Naive forward DFT, useful e.g. to verify faster algorithms.
 /// </summary>
 /// <param name="timeSpace">Time-space sample vector.</param>
 /// <param name="options">Fourier Transform Convention Options.</param>
 /// <returns>Corresponding frequency-space vector.</returns>
 public Complex[] NaiveForward(Complex[] timeSpace, FourierOptions options)
 {
     var frequencySpace = Naive(timeSpace, SignByOptions(options));
     ForwardScaleByOptions(options, frequencySpace);
     return frequencySpace;
 }
 internal static extern void z_axpy(int n, Complex alpha, Complex[] x, [In, Out] Complex[] y);
 internal static extern void z_scale(int n, Complex alpha, [In, Out] Complex[] x);
Example #46
0
        private static double[] getRoadRectangle(SaveRoad.RoadInfo value, Dictionary <int, SaveRoad.RoadInfo> result)
        {
            double KofPointStretchFirstAndSecond = 1;
            double KofPointStretchThirdAndFourth = 1;

            if (value.CarInOpposeDirection == 0)
            {
                KofPointStretchFirstAndSecond = 0.1;
                KofPointStretchThirdAndFourth = 1.5;
            }

            double[] point1, point2, point3, point4;
            var      vec = new double[] { value.endLongitude - value.startLongitude, value.endLatitude - value.startLatitude };

            vec = setToOne(vec);
            System.Numerics.Complex c = new System.Numerics.Complex(vec[0], vec[1]);
            if (!result.ContainsKey(value.RoadOrder - 1))
            {
                var c2 = new System.Numerics.Complex(0, 1);
                var c3 = c * c2;

                point1 = new double[] {
                    value.startLongitude + c3.Real * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond,
                    value.startLatitude + c3.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond
                };
                var c5 = c / c2;
                point2 = new double[] {
                    value.startLongitude + c5.Real * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond,
                    value.startLatitude + c5.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond
                };
            }
            else
            {
                var valueP = result[value.RoadOrder - 1];//previows
                var vecP   = new double[] { valueP.endLongitude - valueP.startLongitude, valueP.endLatitude - valueP.startLatitude };
                vecP = setToOne(vecP);
                System.Numerics.Complex cP = new System.Numerics.Complex(-vecP[0], -vecP[1]);
                var vecDiv2 = c + cP;
                {
                    if (Math.Abs((vecDiv2 / c).Imaginary) < 1e-6)
                    {
                        var c2 = new System.Numerics.Complex(0, 1);
                        var c3 = c * c2;
                        point1 = new double[] {
                            value.startLongitude + c3.Real * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond,
                            value.startLatitude + c3.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond
                        };
                        var c5 = c / c2;
                        point2 = new double[] {
                            value.startLongitude + c5.Real * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond,
                            value.startLatitude + c5.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond
                        };
                    }
                    else
                    {
                        var k = 1 / (vecDiv2 / c).Imaginary;
                        var s = Math.Sqrt(k * k + 1 / k / k);

                        {
                            var vecDivOperate = s / k * setToOne(vecDiv2);
                            point1 = new double[] {
                                value.startLongitude + vecDivOperate.Real * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond,
                                value.startLatitude + vecDivOperate.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond
                            };
                        }
                        {
                            var vecDiv2_opp_diretion = -1 * (vecDiv2);
                            var vecDivOperate        = s / k * setToOne(vecDiv2_opp_diretion);
                            point2 = new double[] {
                                value.startLongitude + vecDivOperate.Real * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond,
                                value.startLatitude + vecDivOperate.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchFirstAndSecond
                            };
                        }
                    }
                }
            }
            c = new System.Numerics.Complex(-vec[0], -vec[1]);
            if (!result.ContainsKey(value.RoadOrder + 1))
            {
                var c2 = new System.Numerics.Complex(0, 1);
                var c3 = c * c2;
                point3 = new double[] {
                    value.endLongitude + c3.Real * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth,
                    value.endLatitude + c3.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth
                };
                var c5 = c / c2;
                point4 = new double[] {
                    value.endLongitude + c5.Real * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth,
                    value.endLatitude + c5.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth
                };
            }
            else
            {
                var valueN = result[value.RoadOrder + 1];//next
                var vecN   = new double[] {
                    valueN.endLongitude - valueN.startLongitude,
                    valueN.endLatitude - valueN.startLatitude
                };
                vecN = setToOne(vecN);
                System.Numerics.Complex cP = new System.Numerics.Complex(vecN[0], vecN[1]);
                var vecDiv2 = c + cP;
                if (Math.Abs((vecDiv2 / c).Imaginary) < 1e-6)
                {
                    var c2 = new System.Numerics.Complex(0, 1);
                    var c3 = c * c2;
                    point3 = new double[] {
                        value.endLongitude + c3.Real * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth,
                        value.endLatitude + c3.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth
                    };
                    var c5 = c / c2;
                    point4 = new double[] {
                        value.endLongitude + c5.Real * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth,
                        value.endLatitude + c5.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth
                    };
                }
                else
                {
                    var k = 1 / (vecDiv2 / c).Imaginary;
                    var s = Math.Sqrt(k * k + 1 / k / k);
                    {
                        var vecDivOperate = s / k * setToOne(vecDiv2);
                        point3 = new double[] {
                            value.endLongitude + vecDivOperate.Real * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth,
                            value.endLatitude + vecDivOperate.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth
                        };
                    }
                    {
                        var vecDiv2_opp_diretion = -1 * vecDiv2;
                        var vecDivOperate        = s / k * setToOne(vecDiv2_opp_diretion);
                        point4 = new double[] {
                            value.endLongitude + vecDivOperate.Real * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth,
                            value.endLatitude + vecDivOperate.Imaginary * value.MaxSpeed * roadZoomValue * KofPointStretchThirdAndFourth
                        };
                    }
                }
            }
            return(new double[]
            {
                Math.Round(point1[0], 9), Math.Round(point1[1], 9),
                Math.Round(point2[0], 9), Math.Round(point2[1], 9),
                Math.Round(point3[0], 9), Math.Round(point3[1], 9),
                Math.Round(point4[0], 9), Math.Round(point4[1], 9)
            });
        }
Example #47
0
 /// <summary>
 /// Applies the inverse Fast Fourier Transform (iFFT) to arbitrary-length sample vectors.
 /// </summary>
 /// <param name="samples">Sample vector, where the FFT is evaluated in place.</param>
 /// <param name="options">Fourier Transform Convention Options.</param>
 public static void FourierInverse(Complex[] samples, FourierOptions options)
 {
     _dft.BluesteinInverse(samples, options);
 }
Example #48
0
 public static Complex Conjugate(this Complex self)
 {
     return(new Complex(self.Real, -self.Imaginary));
 }
        /// <summary>
        /// Computes the eigenvalues and eigenvectors of a matrix.
        /// </summary>
        /// <param name="isSymmetric">Wether the matrix is symmetric or not.</param>
        /// <param name="order">The order of the matrix.</param>
        /// <param name="matrix">The matrix to decompose. The lenth of the array must be order * order.</param>
        /// <param name="matrixEv">On output, the matrix contains the eigen vectors. The lenth of the array must be order * order.</param>
        /// <param name="vectorEv">On output, the eigen values (λ) of matrix in ascending value. The length of the arry must <paramref name="order"/>.</param>
        /// <param name="matrixD">On output, the block diagonal eigenvalue matrix. The lenth of the array must be order * order.</param>
        public virtual void EigenDecomp(bool isSymmetric, int order, float[] matrix, float[] matrixEv, Complex[] vectorEv, float[] matrixD)
        {
            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if (matrix.Length != order*order)
            {
                throw new ArgumentException(String.Format(Resources.ArgumentArrayWrongLength, order*order), "matrix");
            }

            if (matrixEv == null)
            {
                throw new ArgumentNullException("matrixEv");
            }

            if (matrixEv.Length != order*order)
            {
                throw new ArgumentException(String.Format(Resources.ArgumentArrayWrongLength, order*order), "matrixEv");
            }

            if (vectorEv == null)
            {
                throw new ArgumentNullException("vectorEv");
            }

            if (vectorEv.Length != order)
            {
                throw new ArgumentException(String.Format(Resources.ArgumentArrayWrongLength, order), "vectorEv");
            }

            if (matrixD == null)
            {
                throw new ArgumentNullException("matrixD");
            }

            if (matrixD.Length != order*order)
            {
                throw new ArgumentException(String.Format(Resources.ArgumentArrayWrongLength, order*order), "matrixD");
            }

            var d = new float[order];
            var e = new float[order];

            if (isSymmetric)
            {
                Buffer.BlockCopy(matrix, 0, matrixEv, 0, matrix.Length*Constants.SizeOfFloat);
                var om1 = order - 1;
                for (var i = 0; i < order; i++)
                {
                    d[i] = matrixEv[i*order + om1];
                }

                Numerics.LinearAlgebra.Single.Factorization.DenseEvd.SymmetricTridiagonalize(matrixEv, d, e, order);
                Numerics.LinearAlgebra.Single.Factorization.DenseEvd.SymmetricDiagonalize(matrixEv, d, e, order);
            }
            else
            {
                var matrixH = new float[matrix.Length];
                Buffer.BlockCopy(matrix, 0, matrixH, 0, matrix.Length*Constants.SizeOfFloat);
                Numerics.LinearAlgebra.Single.Factorization.DenseEvd.NonsymmetricReduceToHessenberg(matrixEv, matrixH, order);
                Numerics.LinearAlgebra.Single.Factorization.DenseEvd.NonsymmetricReduceHessenberToRealSchur(matrixEv, matrixH, d, e, order);
            }

            for (var i = 0; i < order; i++)
            {
                vectorEv[i] = new Complex(d[i], e[i]);

                var io = i*order;
                matrixD[io + i] = d[i];

                if (e[i] > 0)
                {
                    matrixD[io + order + i] = e[i];
                }
                else if (e[i] < 0)
                {
                    matrixD[io - order + i] = e[i];
                }
            }
        }
        protected void CalcOgdenRivlinHyperelasticElementAB(
            uint feId, IvyFEM.Linear.DoubleSparseMatrix A, double[] B)
        {
            uint uQuantityId = 0;
            uint lQuantityId = 1;

            System.Diagnostics.Debug.Assert(World.GetDof(uQuantityId) == 2);
            System.Diagnostics.Debug.Assert(World.GetDof(lQuantityId) == 1);
            int uDof     = 2;
            int lDof     = 1;
            int uNodeCnt = (int)World.GetNodeCount(uQuantityId);
            int lNodeCnt = (int)World.GetNodeCount(lQuantityId);
            //System.Diagnostics.Debug.Assert(uNodeCnt * uDof + lNodeCnt * lDof == A.RowLength);
            int offset = GetOffset(lQuantityId);

            System.Diagnostics.Debug.Assert(offset == uNodeCnt * uDof);

            double dt    = TimeStep;
            double beta  = NewmarkBeta;
            double gamma = NewmarkGamma;
            var    uFV   = World.GetFieldValue(UValueId);

            TriangleFE uTriFE = World.GetTriangleFE(uQuantityId, feId);
            TriangleFE lTriFE = World.GetTriangleFE(lQuantityId, feId);
            Material   ma0    = World.GetMaterial(uTriFE.MaterialId);

            if (!(ma0 is OgdenHyperelasticMaterial))
            {
                return;
            }

            uint vertexCnt = uTriFE.VertexCount;

            for (int iVertex = 0; iVertex < vertexCnt; iVertex++)
            {
                System.Diagnostics.Debug.Assert(uTriFE.VertexCoordIds[iVertex] == lTriFE.VertexCoordIds[iVertex]);
            }
            int[] uCoIds       = uTriFE.NodeCoordIds;
            uint  uElemNodeCnt = uTriFE.NodeCount;

            int[] uNodes = new int[uElemNodeCnt];
            for (int iNode = 0; iNode < uElemNodeCnt; iNode++)
            {
                int coId   = uCoIds[iNode];
                int nodeId = World.Coord2Node(uQuantityId, coId);
                uNodes[iNode] = nodeId;
            }
            int[] lCoIds       = lTriFE.NodeCoordIds;
            uint  lElemNodeCnt = lTriFE.NodeCount;

            int[] lNodes = new int[lElemNodeCnt];
            for (int iNode = 0; iNode < lElemNodeCnt; iNode++)
            {
                int coId   = lCoIds[iNode];
                int nodeId = World.Coord2Node(lQuantityId, coId);
                lNodes[iNode] = nodeId;
            }

            var    ma             = ma0 as OgdenHyperelasticMaterial;
            bool   isCompressible = ma.IsCompressible;
            double d1             = ma.D1;
            int    oOrder         = ma.Order;

            double[] oMus    = ma.Mus;
            double[] oAlphas = ma.Alphas;
            double   rho     = ma.MassDensity;

            double[] g = { ma.GravityX, ma.GravityY };

            double[] uSN = uTriFE.CalcSN();
            double[,] uSNN = uTriFE.CalcSNN();
            double[,] lSNN = lTriFE.CalcSNN();
            System.Diagnostics.Debug.Assert((int)World.TriIntegrationPointCount >= 3);
            IntegrationPoints ip = TriangleFE.GetIntegrationPoints(World.TriIntegrationPointCount);

            System.Diagnostics.Debug.Assert(ip.Ls.Length == (int)World.TriIntegrationPointCount);

            double[,] qu = new double[uElemNodeCnt, uDof];
            double[] ql = new double[lElemNodeCnt];

            for (int ipPt = 0; ipPt < ip.PointCount; ipPt++)
            {
                double[]   L          = ip.Ls[ipPt];
                double[]   uN         = uTriFE.CalcN(L);
                double[]   lN         = lTriFE.CalcN(L);
                double[][] uNu        = uTriFE.CalcNu(L);
                double     detJ       = uTriFE.GetDetJacobian(L);
                double     weight     = ip.Weights[ipPt];
                double     detJWeight = (1.0 / 2.0) * weight * detJ;

                // 変位の微分
                double[,] uu = new double[uDof, uDof];
                for (int iDof = 0; iDof < uDof; iDof++)
                {
                    for (int jDof = 0; jDof < uDof; jDof++)
                    {
                        for (int iNode = 0; iNode < uElemNodeCnt; iNode++)
                        {
                            int iNodeId = uNodes[iNode];
                            if (iNodeId == -1)
                            {
                                continue;
                            }
                            uu[iDof, jDof] += U[iNodeId * uDof + iDof] * uNu[jDof][iNode];
                        }
                    }
                }

                // ラグランジュの未定乗数
                double l = 0;
                for (int iNode = 0; iNode < lElemNodeCnt; iNode++)
                {
                    int iNodeId = lNodes[iNode];
                    if (iNodeId == -1)
                    {
                        continue;
                    }
                    l += U[offset + iNodeId] * lN[iNode];
                }

                // Green-Lagrangeのひずみ
                double[,] e = new double[uDof, uDof];
                for (int iDof = 0; iDof < uDof; iDof++)
                {
                    for (int jDof = 0; jDof < uDof; jDof++)
                    {
                        e[iDof, jDof] = (1.0 / 2.0) * (uu[iDof, jDof] + uu[jDof, iDof]);
                        for (int kDof = 0; kDof < uDof; kDof++)
                        {
                            e[iDof, jDof] += (1.0 / 2.0) * uu[kDof, iDof] * uu[kDof, jDof];
                        }
                    }
                }

                // 変形勾配テンソル
                double[,] f = new double[uDof, uDof];
                for (int iDof = 0; iDof < uDof; iDof++)
                {
                    for (int jDof = 0; jDof < uDof; jDof++)
                    {
                        f[iDof, jDof] = uu[iDof, jDof];
                    }
                    f[iDof, iDof] += 1.0;
                }

                // 右Cauchy-Green変形テンソル
                double[,] c = new double[uDof, uDof];
                for (int iDof = 0; iDof < uDof; iDof++)
                {
                    for (int jDof = 0; jDof < uDof; jDof++)
                    {
                        c[iDof, jDof] = uu[iDof, jDof] + uu[jDof, iDof];
                        for (int kDof = 0; kDof < uDof; kDof++)
                        {
                            c[iDof, jDof] += uu[kDof, iDof] * uu[kDof, jDof];
                        }
                    }
                    c[iDof, iDof] += 1.0;
                }

                // Cのテンソル不変量
                double I1      = c[0, 0] + c[1, 1] + 1.0;
                double I2      = c[0, 0] * c[1, 1] + c[0, 0] + c[1, 1] - c[0, 1] * c[1, 0];
                double I3      = c[0, 0] * c[1, 1] - c[0, 1] * c[1, 0];
                double inv13I3 = 1.0 / Math.Pow(I3, 1.0 / 3.0);
                double inv23I3 = 1.0 / Math.Pow(I3, 2.0 / 3.0);
                double[,] invC = new double[uDof, uDof];
                {
                    double invI3 = 1.0 / I3;
                    invC[0, 0] = invI3 * c[1, 1];
                    invC[0, 1] = -invI3 * c[0, 1];
                    invC[1, 0] = -invI3 * c[1, 0];
                    invC[1, 1] = invI3 * c[0, 0];
                }

                // Cの主値の1/2乗と主軸
                // Note: これらは3次元
                int dim3 = 3;
                System.Numerics.Complex[]   fLambdas;
                System.Numerics.Complex[][] cNormals;
                SolvePrincipalValues(c, out fLambdas, out cNormals);
                double inv16I3 = 1.0 / Math.Pow(I3, 1.0 / 6.0);
                // 修正Cの主値
                System.Numerics.Complex[] barFLambdas = fLambdas.Select(a => a * inv16I3).ToArray();

                // 主第2Piola-Kirchhoff応力
                System.Numerics.Complex[] principalS = new System.Numerics.Complex[uDof];

                /*
                 * for (int kDof = 0; kDof < uDof; kDof++)
                 * {
                 *  for (int r = 0; r < oOrder; r++)
                 *  {
                 *      double mu = oMus[r];
                 *      double alpha = oAlphas[r];
                 *      principalS[kDof] += (mu / (fLambdas[kDof] * fLambdas[kDof])) * (
                 *          System.Numerics.Complex.Pow(barFLambdas[kDof], alpha) -
                 *          (1.0 / 3.0) * (
                 *          System.Numerics.Complex.Pow(barFLambdas[0], alpha) +
                 *          System.Numerics.Complex.Pow(barFLambdas[1], alpha) +
                 *          System.Numerics.Complex.Pow(barFLambdas[2], alpha)
                 *          ));
                 *  }
                 * }
                 */
                for (int kDof = 0; kDof < uDof; kDof++)
                {
                    for (int r = 0; r < oOrder; r++)
                    {
                        double mu    = oMus[r];
                        double alpha = oAlphas[r];
                        principalS[kDof] += (mu / (fLambdas[kDof] * fLambdas[kDof])) * (
                            System.Numerics.Complex.Pow(barFLambdas[kDof], alpha) -
                            (1.0 / 3.0) * (
                                System.Numerics.Complex.Pow(barFLambdas[0], alpha) +
                                System.Numerics.Complex.Pow(barFLambdas[1], alpha) +
                                Math.Pow(I3, -alpha / 6.0)
                                ));
                    }
                }

                // 第2Piola-Kirchhoff応力
                double[,] s = new double[uDof, uDof];
                for (int iDof = 0; iDof < uDof; iDof++)
                {
                    for (int jDof = 0; jDof < uDof; jDof++)
                    {
                        for (int kDof = 0; kDof < uDof; kDof++)
                        {
                            System.Numerics.Complex sij =
                                principalS[kDof] * cNormals[kDof][iDof] * cNormals[kDof][jDof];
                            s[iDof, jDof] += sij.Real;
                            //System.Diagnostics.Debug.Assert(
                            //    Math.Abs(sij.Imaginary) < IvyFEM.Constants.PrecisionLowerLimit);
                        }
                    }
                }
                // Lagrangeの未定乗数の寄与項
                {
                    double tmp = 2.0 * l * I3;
                    for (int iDof = 0; iDof < uDof; iDof++)
                    {
                        for (int jDof = 0; jDof < uDof; jDof++)
                        {
                            s[iDof, jDof] += tmp * invC[iDof, jDof];
                        }
                    }
                }

                // 主軸構成則テンソル(オリジナルの方)
                System.Numerics.Complex[,] principalC21st = new System.Numerics.Complex[uDof, uDof];
                System.Numerics.Complex[,] principalC22nd = new System.Numerics.Complex[uDof, uDof];

                /*
                 * for (int pDof = 0; pDof < uDof; pDof++)
                 * {
                 *  for (int qDof = 0; qDof < uDof; qDof++)
                 *  {
                 *      for (int r = 0; r < oOrder; r++)
                 *      {
                 *          double mu = oMus[r];
                 *          double alpha = oAlphas[r];
                 *          System.Numerics.Complex tmp1 = 0;
                 *          if (pDof == qDof)
                 *          {
                 *              tmp1 = -2.0 * (
                 *                  System.Numerics.Complex.Pow(barFLambdas[qDof], alpha) -
                 *                  (1.0 / 3.0) * (
                 *                  System.Numerics.Complex.Pow(barFLambdas[0], alpha) +
                 *                  System.Numerics.Complex.Pow(barFLambdas[1], alpha) +
                 *                  System.Numerics.Complex.Pow(barFLambdas[2], alpha)
                 *                  ));
                 *          }
                 *          System.Numerics.Complex tmp2 = 0;
                 *          for (int mDof = 0; mDof < dim3; mDof++)
                 *          {
                 *              double dmp = mDof == pDof ? 1 : 0;
                 *              double dmq = mDof == qDof ? 1 : 0;
                 *              tmp2 += alpha *
                 *                  System.Numerics.Complex.Pow(barFLambdas[mDof], alpha) *
                 *                  (dmp - 1.0 / 3.0) *
                 *                  (dmq - 1.0 / 3.0);
                 *          }
                 *          principalC21st[pDof, qDof] +=
                 *              (mu / (fLambdas[pDof] * fLambdas[pDof] * fLambdas[qDof] * fLambdas[qDof])) *
                 *              (tmp1 + tmp2);
                 *      }
                 *  }
                 * }
                 * for (int pDof = 0; pDof < uDof; pDof++)
                 * {
                 *  for (int qDof = 0; qDof < uDof; qDof++)
                 *  {
                 *      for (int r = 0; r < oOrder; r++)
                 *      {
                 *          double mu = oMus[r];
                 *          double alpha = oAlphas[r];
                 *          System.Numerics.Complex tmp = 0;
                 *          if (pDof != qDof)
                 *          {
                 *              System.Numerics.Complex diffFLambda = fLambdas[pDof] - fLambdas[qDof];
                 *              if (diffFLambda.Magnitude >= IvyFEM.Constants.PrecisionLowerLimit)
                 *              {
                 *                  // λp != λq
                 *                  System.Numerics.Complex squareFLambdaP = fLambdas[pDof] * fLambdas[pDof];
                 *                  System.Numerics.Complex squareFLambdaQ = fLambdas[qDof] * fLambdas[qDof];
                 *                  tmp = (mu / (squareFLambdaP * squareFLambdaQ)) * (
                 *                      (
                 *                      squareFLambdaQ * System.Numerics.Complex.Pow(barFLambdas[pDof], alpha) -
                 *                      squareFLambdaP * System.Numerics.Complex.Pow(barFLambdas[qDof], alpha)
                 *                      ) / (squareFLambdaP - squareFLambdaQ) +
                 *                      (1.0 / 3.0) *
                 *                      (
                 *                      System.Numerics.Complex.Pow(barFLambdas[0], alpha) +
                 *                      System.Numerics.Complex.Pow(barFLambdas[1], alpha) +
                 *                      System.Numerics.Complex.Pow(barFLambdas[2], alpha)
                 *                      ));
                 *              }
                 *              else
                 *              {
                 *                  // λp == λq
                 *                  tmp = (mu /
                 *                      (fLambdas[pDof] * fLambdas[pDof] * fLambdas[pDof] * fLambdas[pDof])) * (
                 *                      -((2.0 - alpha) / 2.0) *
                 *                      System.Numerics.Complex.Pow(barFLambdas[pDof], alpha) +
                 *                      (1.0 / 3.0) * (
                 *                      System.Numerics.Complex.Pow(barFLambdas[0], alpha) +
                 *                      System.Numerics.Complex.Pow(barFLambdas[1], alpha) +
                 *                      System.Numerics.Complex.Pow(barFLambdas[2], alpha)
                 *                      ));
                 *              }
                 *              principalC22nd[pDof, qDof] += tmp;
                 *          }
                 *      }
                 *  }
                 * }
                 */
                uint dim2 = 2;
                for (int pDof = 0; pDof < uDof; pDof++)
                {
                    for (int qDof = 0; qDof < uDof; qDof++)
                    {
                        for (int r = 0; r < oOrder; r++)
                        {
                            double mu    = oMus[r];
                            double alpha = oAlphas[r];
                            System.Numerics.Complex tmp1 = 0;
                            if (pDof == qDof)
                            {
                                tmp1 = -2.0 * (
                                    System.Numerics.Complex.Pow(barFLambdas[qDof], alpha) -
                                    (1.0 / 3.0) * (
                                        System.Numerics.Complex.Pow(barFLambdas[0], alpha) +
                                        System.Numerics.Complex.Pow(barFLambdas[1], alpha) +
                                        Math.Pow(I3, -alpha / 6.0)
                                        ));
                            }
                            System.Numerics.Complex tmp2 = 0;
                            for (int mDof = 0; mDof < dim2; mDof++)
                            {
                                double dmp = mDof == pDof ? 1 : 0;
                                double dmq = mDof == qDof ? 1 : 0;
                                tmp2 += alpha *
                                        System.Numerics.Complex.Pow(barFLambdas[mDof], alpha) *
                                        (dmp - 1.0 / 3.0) *
                                        (dmq - 1.0 / 3.0);
                            }
                            tmp2 += (alpha / 9.0) * Math.Pow(I3, -alpha / 6.0);
                            principalC21st[pDof, qDof] +=
                                (mu / (fLambdas[pDof] * fLambdas[pDof] * fLambdas[qDof] * fLambdas[qDof])) *
                                (tmp1 + tmp2);
                        }
                    }
                }
                for (int pDof = 0; pDof < uDof; pDof++)
                {
                    for (int qDof = 0; qDof < uDof; qDof++)
                    {
                        for (int r = 0; r < oOrder; r++)
                        {
                            double mu    = oMus[r];
                            double alpha = oAlphas[r];
                            if (pDof != qDof)
                            {
                                System.Numerics.Complex tmp         = 0;
                                System.Numerics.Complex diffFLambda = fLambdas[pDof] - fLambdas[qDof];
                                if (diffFLambda.Magnitude >= IvyFEM.Constants.PrecisionLowerLimit)
                                {
                                    // λp != λq
                                    System.Numerics.Complex squareFLambdaP = fLambdas[pDof] * fLambdas[pDof];
                                    System.Numerics.Complex squareFLambdaQ = fLambdas[qDof] * fLambdas[qDof];
                                    tmp = (mu / (squareFLambdaP * squareFLambdaQ)) * (
                                        (
                                            squareFLambdaQ * System.Numerics.Complex.Pow(barFLambdas[pDof], alpha) -
                                            squareFLambdaP * System.Numerics.Complex.Pow(barFLambdas[qDof], alpha)
                                        ) / (squareFLambdaP - squareFLambdaQ) +
                                        (1.0 / 3.0) *
                                        (
                                            System.Numerics.Complex.Pow(barFLambdas[0], alpha) +
                                            System.Numerics.Complex.Pow(barFLambdas[1], alpha) +
                                            System.Numerics.Complex.Pow(I3, -alpha / 6.0)
                                        ));
                                }
                                else
                                {
                                    // λp == λq
                                    tmp = (mu /
                                           (fLambdas[pDof] * fLambdas[pDof] * fLambdas[pDof] * fLambdas[pDof])) * (
                                        -((2.0 - alpha) / 2.0) *
                                        System.Numerics.Complex.Pow(barFLambdas[pDof], alpha) +
                                        (1.0 / 3.0) * (
                                            System.Numerics.Complex.Pow(barFLambdas[0], alpha) +
                                            System.Numerics.Complex.Pow(barFLambdas[1], alpha) +
                                            System.Numerics.Complex.Pow(I3, -alpha / 6.0)
                                            ));
                                }
                                principalC22nd[pDof, qDof] += tmp;
                            }
                        }
                    }
                }

                // 構成則テンソル(オリジナルの方)
                double[,,,] c4 = new double[uDof, uDof, uDof, uDof];
                for (int gDof = 0; gDof < uDof; gDof++)
                {
                    for (int hDof = 0; hDof < uDof; hDof++)
                    {
                        for (int eDof = 0; eDof < uDof; eDof++)
                        {
                            for (int fDof = 0; fDof < uDof; fDof++)
                            {
                                for (int pDof = 0; pDof < uDof; pDof++)
                                {
                                    for (int qDof = 0; qDof < uDof; qDof++)
                                    {
                                        System.Numerics.Complex c4ghef =
                                            principalC21st[pDof, qDof] *
                                            cNormals[pDof][gDof] * cNormals[pDof][hDof] *
                                            cNormals[qDof][eDof] * cNormals[qDof][fDof] +
                                            principalC22nd[pDof, qDof] *
                                            cNormals[pDof][gDof] * cNormals[qDof][hDof] *
                                            (
                                                cNormals[pDof][eDof] * cNormals[qDof][fDof] +
                                                cNormals[qDof][eDof] * cNormals[pDof][fDof]
                                            );
                                        c4[gDof, hDof, eDof, fDof] += c4ghef.Real;
                                        //System.Diagnostics.Debug.Assert(
                                        //    Math.Abs(c4ghef.Imaginary) < IvyFEM.Constants.PrecisionLowerLimit);
                                    }
                                }
                            }
                        }
                    }
                }
                // 構成則テンソル
                double[,,,] barC4 = new double[uDof, uDof, uDof, uDof];
                // 圧力構成則テンソル
                for (int gDof = 0; gDof < uDof; gDof++)
                {
                    for (int hDof = 0; hDof < uDof; hDof++)
                    {
                        for (int eDof = 0; eDof < uDof; eDof++)
                        {
                            for (int fDof = 0; fDof < uDof; fDof++)
                            {
                                barC4[gDof, hDof, eDof, fDof] +=
                                    4.0 * l * I3 * invC[gDof, hDof] * invC[eDof, fDof] -
                                    2.0 * l * I3 * (
                                        invC[gDof, eDof] * invC[fDof, hDof] +
                                        invC[gDof, fDof] * invC[eDof, hDof]);
                            }
                        }
                    }
                }
                // 変位構成則テンソル
                for (int gDof = 0; gDof < uDof; gDof++)
                {
                    for (int hDof = 0; hDof < uDof; hDof++)
                    {
                        for (int eDof = 0; eDof < uDof; eDof++)
                        {
                            for (int fDof = 0; fDof < uDof; fDof++)
                            {
                                barC4[gDof, hDof, eDof, fDof] +=
                                    (1.0 / 2.0) * (c4[gDof, hDof, eDof, fDof] + c4[gDof, hDof, fDof, eDof]);
                            }
                        }
                    }
                }

                double[,,,] b = new double[uElemNodeCnt, uDof, uDof, uDof];
                {
                    for (int iNode = 0; iNode < uElemNodeCnt; iNode++)
                    {
                        for (int iDof = 0; iDof < uDof; iDof++)
                        {
                            for (int gDof = 0; gDof < uDof; gDof++)
                            {
                                for (int hDof = 0; hDof < uDof; hDof++)
                                {
                                    b[iNode, iDof, gDof, hDof] = uNu[hDof][iNode] * f[iDof, gDof];
                                }
                            }
                        }
                    }
                }

                for (int row = 0; row < uElemNodeCnt; row++)
                {
                    int rowNodeId = uNodes[row];
                    if (rowNodeId == -1)
                    {
                        continue;
                    }
                    for (int col = 0; col < uElemNodeCnt; col++)
                    {
                        int colNodeId = uNodes[col];
                        if (colNodeId == -1)
                        {
                            continue;
                        }

                        double[,] kuu = new double[uDof, uDof];
                        for (int rowDof = 0; rowDof < uDof; rowDof++)
                        {
                            for (int colDof = 0; colDof < uDof; colDof++)
                            {
                                double tmp1 = 0.0;
                                for (int gDof = 0; gDof < uDof; gDof++)
                                {
                                    for (int hDof = 0; hDof < uDof; hDof++)
                                    {
                                        for (int eDof = 0; eDof < uDof; eDof++)
                                        {
                                            for (int fDof = 0; fDof < uDof; fDof++)
                                            {
                                                tmp1 += barC4[gDof, hDof, eDof, fDof] *
                                                        b[row, rowDof, eDof, fDof] *
                                                        b[col, colDof, gDof, hDof];
                                            }
                                        }
                                    }
                                }
                                kuu[rowDof, colDof] += detJWeight * tmp1;
                            }
                        }
                        {
                            double tmp = 0.0;
                            for (int gDof = 0; gDof < uDof; gDof++)
                            {
                                for (int hDof = 0; hDof < uDof; hDof++)
                                {
                                    tmp += s[gDof, hDof] * uNu[gDof][row] * uNu[hDof][col];
                                }
                            }
                            for (int rowDof = 0; rowDof < uDof; rowDof++)
                            {
                                kuu[rowDof, rowDof] += detJWeight * tmp;
                            }
                        }

                        for (int rowDof = 0; rowDof < uDof; rowDof++)
                        {
                            for (int colDof = 0; colDof < uDof; colDof++)
                            {
                                A[rowNodeId * uDof + rowDof, colNodeId *uDof + colDof] +=
                                    kuu[rowDof, colDof];
                                B[rowNodeId * uDof + rowDof] +=
                                    kuu[rowDof, colDof] * U[colNodeId * uDof + colDof];
                            }
                        }
                    }
                }
                for (int row = 0; row < uElemNodeCnt; row++)
                {
                    int rowNodeId = uNodes[row];
                    if (rowNodeId == -1)
                    {
                        continue;
                    }
                    for (int col = 0; col < lElemNodeCnt; col++)
                    {
                        int colNodeId = lNodes[col];
                        if (colNodeId == -1)
                        {
                            continue;
                        }

                        double[,] kul = new double[uDof, lDof];
                        double[,] klu = new double[lDof, uDof];
                        for (int rowDof = 0; rowDof < uDof; rowDof++)
                        {
                            double tmp = 0.0;
                            for (int gDof = 0; gDof < uDof; gDof++)
                            {
                                for (int hDof = 0; hDof < uDof; hDof++)
                                {
                                    tmp += invC[gDof, hDof] * b[row, rowDof, gDof, hDof];
                                }
                            }

                            kul[rowDof, 0] +=
                                detJWeight * tmp * 2.0 * lN[col] * I3;
                            klu[0, rowDof] +=
                                detJWeight * tmp * 2.0 * lN[col] * I3;
                        }

                        for (int rowDof = 0; rowDof < uDof; rowDof++)
                        {
                            A[rowNodeId * uDof + rowDof, offset + colNodeId] += kul[rowDof, 0];
                            A[offset + colNodeId, rowNodeId *uDof + rowDof]  += klu[0, rowDof];
                            B[rowNodeId * uDof + rowDof] +=
                                kul[rowDof, 0] * U[offset + colNodeId];
                            B[offset + colNodeId] +=
                                klu[0, rowDof] * U[rowNodeId * uDof + rowDof];
                        }
                    }
                }

                // Note: kllは数値積分しなくて求められる

                for (int iNode = 0; iNode < uElemNodeCnt; iNode++)
                {
                    for (int iDof = 0; iDof < uDof; iDof++)
                    {
                        for (int gDof = 0; gDof < uDof; gDof++)
                        {
                            for (int hDof = 0; hDof < uDof; hDof++)
                            {
                                qu[iNode, iDof] += detJWeight * s[gDof, hDof] * b[iNode, iDof, gDof, hDof];
                            }
                        }
                    }
                }
                for (int iNode = 0; iNode < lElemNodeCnt; iNode++)
                {
                    if (isCompressible)
                    {
                        ql[iNode] += detJWeight * lN[iNode] * ((I3 - 1) - l / d1);
                    }
                    else
                    {
                        ql[iNode] += detJWeight * lN[iNode] * (I3 - 1);
                    }
                }
            }

            for (int row = 0; row < uElemNodeCnt; row++)
            {
                int rowNodeId = uNodes[row];
                if (rowNodeId == -1)
                {
                    continue;
                }
                for (int col = 0; col < uElemNodeCnt; col++)
                {
                    int colNodeId = uNodes[col];
                    if (colNodeId == -1)
                    {
                        continue;
                    }

                    int      colCoId = uCoIds[col];
                    double[] u       = uFV.GetDoubleValue(colCoId, FieldDerivativeType.Value);
                    double[] velU    = uFV.GetDoubleValue(colCoId, FieldDerivativeType.Velocity);
                    double[] accU    = uFV.GetDoubleValue(colCoId, FieldDerivativeType.Acceleration);
                    double[,] m = new double[2, 2];

                    m[0, 0] = rho * uSNN[row, col];
                    m[1, 0] = 0.0;
                    m[0, 1] = 0.0;
                    m[1, 1] = rho * uSNN[row, col];
                    for (int rowDof = 0; rowDof < uDof; rowDof++)
                    {
                        for (int colDof = 0; colDof < uDof; colDof++)
                        {
                            A[rowNodeId * uDof + rowDof, colNodeId *uDof + colDof] +=
                                (1.0 / (beta * dt * dt)) * m[rowDof, colDof];
                            B[rowNodeId * uDof + rowDof] +=
                                m[rowDof, colDof] * (
                                    (1.0 / (beta * dt * dt)) * u[colDof] +
                                    (1.0 / (beta * dt)) * velU[colDof] +
                                    (1.0 / (2.0 * beta) - 1.0) * accU[colDof]);
                        }
                    }
                }
            }

            if (isCompressible)
            {
                for (int row = 0; row < lElemNodeCnt; row++)
                {
                    int rowNodeId = lNodes[row];
                    if (rowNodeId == -1)
                    {
                        continue;
                    }
                    for (int col = 0; col < lElemNodeCnt; col++)
                    {
                        int colNodeId = lNodes[col];
                        if (colNodeId == -1)
                        {
                            continue;
                        }

                        double kll = -(1.0 / d1) * lSNN[row, col];
                        A[offset + rowNodeId, offset + colNodeId] += kll;
                        B[offset + rowNodeId] += kll * U[offset + colNodeId];
                    }
                }
            }

            double[,] fg = new double[uElemNodeCnt, uDof];
            for (int iNode = 0; iNode < uElemNodeCnt; iNode++)
            {
                for (int iDof = 0; iDof < uDof; iDof++)
                {
                    fg[iNode, iDof] = rho * g[iDof] * uSN[iNode];
                }
            }

            for (int row = 0; row < uElemNodeCnt; row++)
            {
                int rowNodeId = uNodes[row];
                if (rowNodeId == -1)
                {
                    continue;
                }
                for (int rowDof = 0; rowDof < uDof; rowDof++)
                {
                    B[rowNodeId * uDof + rowDof] += fg[row, rowDof] - qu[row, rowDof];
                }
            }
            for (int row = 0; row < lElemNodeCnt; row++)
            {
                int rowNodeId = lNodes[row];
                if (rowNodeId == -1)
                {
                    continue;
                }
                B[offset + rowNodeId] += -ql[row];
            }
        }
Example #51
0
		public void TestUnaryMinus ()
		{
			using (Lua lua = new Lua ()) {

				lua.LoadCLRPackage ();
				lua.DoString (@" import ('System.Numerics')
							  c = Complex (10, 5) 
							  c = -c ");

				var expected = new System.Numerics.Complex (-10, -5);

				var res = lua ["c"];
				Assert.AreEqual (expected, res);
			}
		}
        public void MatrixMultiplyWithUpdate(Transpose transposeA, Transpose transposeB, Complex alpha, Complex[] a, int rowsA, int columnsA, Complex[] b, int rowsB, int columnsB, Complex beta, Complex[] c)
        {
            if (a == null)
            {
                throw new ArgumentNullException(nameof(a));
            }

            if (b == null)
            {
                throw new ArgumentNullException(nameof(b));
            }

            if (c == null)
            {
                throw new ArgumentNullException(nameof(c));
            }

            var m = transposeA == Transpose.DontTranspose ? rowsA : columnsA;
            var n = transposeB == Transpose.DontTranspose ? columnsB : rowsB;
            var k = transposeA == Transpose.DontTranspose ? columnsA : rowsA;
            var l = transposeB == Transpose.DontTranspose ? rowsB : columnsB;

            if (c.Length != m * n)
            {
                throw new ArgumentException("Matrix dimensions must agree.");
            }

            if (k != l)
            {
                throw new ArgumentException("Matrix dimensions must agree.");
            }

            SafeNativeMethods.z_matrix_multiply(transposeA, transposeB, m, n, k, alpha, a, b, beta, c);
        }
Example #53
0
 public static Complex Pow(this Complex self, Complex power) {
     return Complex.Pow(self, power);
 }
Example #54
0
 public static System.Numerics.Complex random(System.Numerics.Complex z1, System.Numerics.Complex z2)
 {
     return(z1 + (z2 - z1) * m_random.NextDouble());
 }
 /// <summary>
 /// Swap the real and imaginary parts of each sample.
 /// </summary>
 /// <param name="samples">Sample Vector.</param>
 private static void SwapRealImaginary(Complex[] samples)
 {
     for (int i = 0; i < samples.Length; i++)
     {
         samples[i] = new Complex(samples[i].Imaginary, samples[i].Real);
     }
 }
Example #56
0
 public static System.Numerics.Complex random(System.Numerics.Complex z)
 {
     //return z * m_random.NextDouble();
     return(new System.Numerics.Complex(z.Real * m_random.NextDouble(), z.Imaginary * m_random.NextDouble()));
 }
 /// <summary>
 /// Bluestein inverse FFT for arbitrary sized sample vectors.
 /// </summary>
 /// <param name="samples">Sample vector, where the FFT is evaluated in place.</param>
 /// <param name="options">Fourier Transform Convention Options.</param>
 public void BluesteinInverse(Complex[] samples, FourierOptions options)
 {
     Bluestein(samples, -SignByOptions(options));
     InverseScaleByOptions(options, samples);
 }
Example #58
0
 public static double Imaginary(this Complex self)
 {
     return(self.Imaginary);
 }
Example #59
0
        private static System.Numerics.Complex setToOne(System.Numerics.Complex vecRes)
        {
            var data = setToOne(new double[] { vecRes.Real, vecRes.Imaginary });

            return(new System.Numerics.Complex(data[0], data[1]));
        }
Example #60
0
 public static Complex Pow(this Complex self, Complex power)
 {
     return(Complex.Pow(self, power));
 }