Example #1
0
 /// <summary>
 /// sum all elements of array A
 /// </summary>
 /// <param name="A">n-dim array</param>
 /// <returns><para>scalar sum of all elements of A.</para>
 /// <para>If A is empty, an empty array will be returned.</para></returns>
 /// <exception cref="ILNumerics.Exceptions.ILArgumentException">if A was null.</exception>
 /// <seealso cref="ILNumerics.BuiltInFunctions.ILMath.sum(ILArray&lt;double&gt;)"/>
 public static  ILArray<complex> sumall ( ILArray<complex> A) {
     if (object.Equals(A,null))
         throw new ILArgumentException("sumall: argument must not be null!");
     if (A.IsEmpty) {
         return  ILArray<complex> .empty(0,0); 
     } 
     complex retArr =  new complex(0.0,0.0) ; 
     if (A.m_indexOffset == null) {
         unsafe {
             fixed ( complex * inArrStart = A.m_data) {
                 complex * inArrWalk = inArrStart; 
                 complex * inArrEnd = inArrStart + A.Dimensions.NumberOfElements; 
                 while (inArrWalk < inArrEnd) {
                     retArr += *inArrWalk++; 
                 }
             }
         }
     } else {
         unsafe {
             fixed ( complex * inArrStart = A.m_data)  {
                 for (int i = A.Dimensions.NumberOfElements; i -->0;) {
                     retArr += *(inArrStart + A.getBaseIndex(i)); 
                 }
             }
         }
     }
     return new  ILArray<complex> (new  complex [1]{retArr},1,1);
 }
Example #2
0
    public static Tuple <List <complex>, List <complex> > cdrive_single(Func <complex, List <complex>, List <complex> > f, complex a, complex b, List <complex> ya, complex h = default(complex), double acc = 1e-4, double eps = 1e-4)
    {
        // Return lists. I use lists because arrays and vectors don't play nice with complex
        List <complex> zs = new List <complex>()
        {
            a
        };
        List <complex> ys = new List <complex>()
        {
            ya[0]
        };
        int nsteps = 0;

        if (h == default(complex))
        {
            h = (b - a) / 1000;              // Starting guesstimate of stepsize
        }
        while (true)
        {
            if (abs(b - a) < acc)
            {
                break;                 // End statement
            }
            nsteps++;
            List <complex> err    = new List <complex>();
            complex        y_next = crkstep45_single(f, a, ya, h, err);
            break;
        }

        return(Tuple.Create(zs, ys));
    }
Example #3
0
        /// <summary>
        /// Applys the function (delegate) given to all elements of the storage
        /// </summary>
        /// <param name="inArray">storage array to apply the function to</param>
        /// <param name="operation">operation to apply to the elements of inArray. This
        /// acts like a function pointer.</param>
        /// <returns>new <![CDATA[  ILArray<complex> ]]> with result of operation</returns>
        /// <remarks> the values of inArray will not be altered.</remarks>
        private static ILArray <complex> ComplexOperatorComplex(ILArray <complex> inArray,
                                                                ILComplexFunctionComplex operation)
        {
            ILDimension inDim = inArray.Dimensions;

            complex [] retDblArr;
            // build ILDimension
            int newLength = inDim.NumberOfElements;

            retDblArr = new  complex [newLength];
            int leadDimLen = inDim [0];

            unsafe
            {
                fixed(complex *pOutArr = retDblArr)
                fixed(complex * pInArr = inArray.m_data)
                {
                    complex *lastElement = pOutArr + retDblArr.Length;
                    complex *tmpOut      = pOutArr;
                    complex *tmpIn       = pInArr;

                    while (tmpOut < lastElement)
                    {
                        *tmpOut++ = operation(*tmpIn++);
                    }
                }
            }

            return(new  ILArray <complex> (retDblArr, inDim.ToIntArray()));
        }
Example #4
0
    static int Main()
    {
/*
 *              double x = 1;
 *              char c ='ø';
 *              string s = "hello";
 *              Write("sin{0}={1}\n",x,Sin(x));
 *              Write($"sin({x})={Sin(x)}\n");
 *              int i = 100;
 *              Write($"i={i}\n");
 */

        // complex i = new complex (complex.sqr(2),0);
        complex sqr_2 = sqrt(2);
        complex I     = new complex(0, 1);
        complex e     = E;
        complex ei    = e.pow(I);
        complex eipi  = e.pow(I * PI);
        complex ipowi = I.pow(I);
        complex sipi  = sin(I * PI);

        Write($"sqrt(2) ={sqr_2}\n ");
        Write($"i^i = {ipowi}\n ");
        Write($"sin(i*pi)={sipi}\n");
        Write($"e^i={ei}\n");
        Write($"e^(ipi)={eipi}\n");
        return(0);
    }
Example #5
0
    static int Main()
    {
        WriteLine("A)");
        complex I = new complex(0, 1);
        double  x = 2;

        Write($"sqrt({x})={Sqrt(x)}\n");
        Write($"exp(i)={exp(I)}\n");
        complex eipi = exp(I * PI);

        Write($"exp(i*pi)={eipi.Re}+{eipi.Im:f0}i\n"); /* The real part is rounded down to 0 */
        Write($"i^i={exp(-PI/2)}\n");                  /* According to wolfram-aplha, i^i = exp(-pi/2)*/
        Write($"sin(i*pi)={sin(I*PI)}\n");

        WriteLine("B)");
        complex sinhi = cfunctions.sinh(I);

        Write($"sinh(i)={sinhi}\n");
        complex coshi = cfunctions.cosh(I);

        Write($"cosh(i)={coshi}\n");
        complex sqrti = cfunctions.csqrt(I);

        Write($"sqrt(i)={sqrti}\n");
        complex sqrtminus1 = cfunctions.csqrt(-1);

        Write("sqrt(-1)={0:f0}+{1}i\n", sqrtminus1.Re, sqrtminus1.Im);       /* The real part is rounded down to 0 */
        return(0);
    }
Example #6
0
        public static void Main(string[] args)
        {
            complex c11 = new complex();

            c11.r = 0.0;
            c11.j = 0.0;

            Console.WriteLine("r={0},j={1}", c11.r, c11.j);

            complex c12 = new complex(3.0, 4.0);

            Console.WriteLine("{0:N}+j{1:N}", c12.r, c12.j);

            complex c13 = new complex(1.0, 4.0);

            Console.WriteLine("{0:N}+j{1:N}", c13.r, c13.j);

            // Create a complex number by calling its class constructor.
            Complex c1 = new Complex(12, 6); Console.WriteLine("{0:N}+j{0:N}", c1);
            // Assign a Double to a complex number.
            Complex c2 = 3.14; Console.WriteLine("c2=" + c2);
            // Cast a Decimal to a complex number.
            Complex c3 = (Complex)12.3m; Console.WriteLine(c3);
            // Assign the return value of a method to a Complex variable.
            Complex c4 = Complex.Pow(Complex.ImaginaryOne, 3); Console.WriteLine("c4=" + c4);
            // Assign the value returned by an operator to a Complex variable.
            Complex c5 = Complex.One - Complex.ImaginaryOne; Console.WriteLine(c5);
            // Instantiate a complex number from its polar coordinates.
            Complex c6 = Complex.FromPolarCoordinates(1, Math.PI / 4); Console.WriteLine(c6);

            Console.ReadLine();
        }
Example #7
0
    static int Main()
    {
        complex z = complex(0, 1);

        (z + z).print();
        return(0);
    }
Example #8
0
    public static void Main(string[] args)
    {
        using (StreamWriter file = new StreamWriter($"gammac.txt")) {
            file.WriteLine(string.Format("# {0, -8} {1, -10} {2, -10}", "x", "z", "Gamma(x+iz)"));
            double[] data = args.Select(x => double.Parse(x)).ToArray();
            double   rstart = data[0], rend = data[1], rstep = data[2];           // real range
            double   zstart = data[3], zend = data[4], zstep = data[5];           // complex range

            double[] a   = new double[(int)Ceiling((rend - rstart) / rstep)];
            double[] b   = new double[(int)Ceiling((zend - zstart) / zstep)];
            double[] res = new double[a.Length * b.Length];

            int     k = 0;         // result index
            complex q;             // complex number to be evaluated for each iteration
            for (int i = 0; i < a.Length; i++)
            {
                a[i] = rstart + i * rstep;
                for (int j = 0; j < b.Length; j++)
                {
                    b[j]   = zstart + j * zstep;
                    q      = new complex(a[i], b[j]);
                    q      = Gamma(q);                          // q now stores the result
                    k      = i * a.Length + j;                  // updating the result index
                    res[k] = Sqrt(Pow(q.Re, 2) + Pow(q.Im, 2)); // getting the magnitude
                    file.WriteLine($"{a[i], -10:F3} {b[j], -10:F3} {res[k], -10:F3}");
                }
            }
            return;
        }
    }
Example #9
0
    public complex hTilde_0(int n_prime, int m_prime)
    {
        complex r = GlobalMembers.gaussianRandomVariable();
        float   t = phillips(n_prime, m_prime) / 2.0f;

        return(r * Mathf.Sqrt(t));
    }
Example #10
0
        public ILArray <complex> FFTBackward(ILArray <complex> A, int firstDim, int nDims)
        {
            if (A == null || nDims < 0 || firstDim < 0)
            {
                throw new ILArgumentException("invalid parameter!");
            }
            if (A.IsEmpty)
            {
                return(ILArray <complex> .empty(A.Dimensions));
            }
            if (A.IsScalar || (A.Dimensions[firstDim] == 1 && nDims == 1))
            {
                return(A.C);
            }
            if (nDims > A.Dimensions.NumberOfDimensions)
            {
                nDims = A.Dimensions.NumberOfDimensions;
            }
            // prepare output array
            ILArray <complex> ret  = A.C;
            IntPtr            plan = IntPtr.Zero;
            int            hrank   = 2;
            FFTW_DIRECTION dir     = FFTW_DIRECTION.BACKWARDS;

            lock (_lockobject) {
                FFTW_PLANCREATION flags = FFTW_PLANCREATION.ESTIMATE;
                if (nDims > m_n.Length)
                {
                    resizeCache(nDims);
                }
                for (int i = 0; i < nDims; i++)
                {
                    m_n[i]  = A.Dimensions[i + firstDim];
                    m_is[i] = A.Dimensions.SequentialIndexDistance(i + firstDim);
                    m_os[i] = m_is[i];
                }
                m_hn[0]  = A.Dimensions.SequentialIndexDistance(firstDim);
                m_his[0] = 1;
                m_hos[0] = 1;
                m_his[1] = A.Dimensions.SequentialIndexDistance(nDims + firstDim);
                m_hn[1]  = A.Dimensions.NumberOfElements / m_his[1];
                m_hos[1] = m_his[1];
                fixed(complex *retArr = ret.m_data)
                {
                    dfftw_plan_guru_dft_(ref plan, ref nDims, m_n, m_is, m_os,
                                         ref hrank, m_hn, m_his, m_hos,
                                         retArr, retArr,
                                         ref dir, ref flags);
                }
            }
            if (plan == IntPtr.Zero)
            {
                throw new ILInvalidOperationException("error creating plan for fftw3 (guru interface)");
            }
            dfftw_execute_(ref plan);
            dfftw_destroy_plan_(ref plan);
            ret /= new complex(m_his[1] / m_hn[0], 0.0f);
            return(ret);
        }
Example #11
0
    public static complex csqrt(complex x)
    {
        complex I   = new complex(0, 1);
        double  r   = abs(x);
        double  phi = arg(x);

        return(sqrt(r) * exp((I * phi) / 2));  //according to Wikipedia
    }
Example #12
0
File: test.cs Project: Bakkedal/QSL
 public static void Main()
 {
     var a = new complex(1,2);
     var b = new complex(2,3);
     var c = a+b;
     if(c == new complex(3,5)) c.print("test complex addition passed");
     else c.print("test complex addition failed");
 }
Example #13
0
File: DFT.cs Project: kaury/MyTools
            //复数和复数相乘  重载上一个函数
            public static complex commul(complex x, complex y)
            {
                complex c = new complex();

                c.a = x.a * y.a - x.b * y.b;
                c.b = x.a * y.b + x.b * y.a;
                return(c);
            }
Example #14
0
            public complex AddComplex(complex s)
            {
                complex ts;

                ts.r = this.r + s.r;
                ts.i = this.i + s.i;
                return(ts);
            }
Example #15
0
File: DFT.cs Project: kaury/MyTools
            //复数和复数相减
            public static complex decrease(complex x, complex y)
            {
                complex c = new complex();

                c.a = x.a - y.a;
                c.b = x.b - y.b;
                return(c);
            }
Example #16
0
File: DFT.cs Project: kaury/MyTools
            public static complex decrease(double x, complex y)
            {
                complex c = new complex();

                c.a = x - y.a;
                c.b = 0 - y.b;
                return(c);
            }
Example #17
0
File: DFT.cs Project: kaury/MyTools
            //复数和复数相加
            public static complex comsum(complex x, complex y)
            {
                complex c = new complex();

                c.a = x.a + y.a;
                c.b = x.b + y.b;
                return(c);
            }
Example #18
0
File: DFT.cs Project: kaury/MyTools
            //实数和复数相加
            public static complex comsum(double x, complex y)
            {
                complex c = new complex();

                c.a = x + y.a;
                c.b = y.b;
                return(c);
            }
Example #19
0
            public complex SubComplex(complex s)
            {
                complex ts;

                ts.r = this.r - s.r;
                ts.i = this.i - s.i;
                return(ts);
            }
Example #20
0
File: DFT.cs Project: kaury/MyTools
            //实数和复数相乘
            public static complex commul(double x, complex y)
            {
                complex c = new complex();

                c.a = x * y.a;
                c.b = x * y.b;
                return(c);
            }
Example #21
0
 internal complex divide(complex in1, complex in2)
 {
     if (in2 != 0.0)
     {
         return((complex)(in1 / in2));
     }
     return(complex.INF);
 }
Example #22
0
            public complex MulComplex(complex s)
            {
                complex ts;

                ts.r = this.r * s.r - this.i * s.i;
                ts.i = this.i * s.r + this.r * s.i;
                return(ts);
            }
        private static void PerformFFT(double[] input_data, double y_limit, int sampleRate, double frequenzyCutoffMin, double frequenzyCutoffMax, out double[] x_freq, out double[] y_coof)
        {
            ILArray <double>  arr_in;
            ILArray <complex> arr_res;

            try
            {
                arr_in = new ILArray <double>(input_data);

                arr_res = ILNumerics.BuiltInFunctions.ILMath.fft(arr_in);
            }
            catch (Exception ex) {
                MessageBox.Show("Error performing FFT-operation: " + ex);
                throw;
            }

            double fftFreqMax   = arr_res.GetValue(arr_res.Length - 1).imag;
            double maxCutofFreq = (frequenzyCutoffMax * fftFreqMax) / sampleRate;
            double minCutofFreq = (frequenzyCutoffMin * fftFreqMax) / sampleRate;

            List <double> x_freq_ls = new List <double>();
            List <double> y_coof_ls = new List <double>();

            for (int i = 0; i < arr_res.Length; ++i)
            {
                complex c = arr_res.GetValue(i);

                double real = c.real;
                double imag = c.imag;

                if (Math.Abs(real) < y_limit)
                {
                    continue;
                }

                double abs_freq = Math.Abs(imag);

                if (abs_freq < minCutofFreq)
                {
                    continue;
                }
                if (abs_freq > maxCutofFreq)
                {
                    continue;
                }

                double freq = abs_freq / maxCutofFreq; // freq will now be 0-1
                System.Diagnostics.Debug.Assert(freq <= 1.0);
                x_freq_ls.Add(abs_freq);
                y_coof_ls.Add(Math.Abs(real) / 255.0);
            }

            x_freq = x_freq_ls.ToArray();
            y_coof = y_coof_ls.ToArray();

            arr_in  = null;
            arr_res = null;
        }
Example #24
0
            public complex DivComplex(complex s)
            {
                complex ts;

                ts.r = (this.r * s.r + this.i * s.i) / (s.r * s.r + s.i * s.i);
                ts.i = (this.i * s.r - this.r * s.i) / (s.r * s.r + s.i * s.i);

                return(ts);
            }
Example #25
0
        public static void fftc1d(ref complex[] a) {
            int n;


            n = ap.len(a);
            fft.fftc1d(ref a, n);

            return;
        }
Example #26
0
    }     // jacobian

    public static (complex, int) qnewton(
        Func <complex, complex> f,
        complex z,
        complex dz,
        double eps = 1e-3
        )
    {    // Calls newton 1D complex rootf, specifying no derivative df (so uses finite differences)
        return(newton(f, z, dz: dz, df: null, eps: eps));
    }
Example #27
0
    static int Main()
    {
        complex z = new complex(0, 1);

        (z + z).print("i+i=");


        return(0);
    }
Example #28
0
File: DFT.cs Project: kaury/MyTools
        //实序列的FFT
        public static complex[] FFT(double[] input, int n)
        {
            //输入序列只有一个元素,输出这个元素并返回
            //输入序列的长度
            int length = n;

            //输入序列的长度的一半
            int half = length / 2;

            //有输入序列的长度确定输出序列的长度
            complex[] output = new complex[length];

            //序列中下标为偶数的点
            double[] evens = new double[half];

            for (int i = 0; i < half; i++)
            {
                evens[i] = input[2 * i];
            }

            //偶数列的DFT
            complex[] evenResult = dft(evens, half);

            //序列中下标为奇数的点
            double[] odds = new double[half];

            for (int i = 0; i < half; i++)
            {
                odds[i] = input[2 * i + 1];
            }
            //奇数列的DFT
            complex[] oddResult = dft(odds, half);

            complex w1;

            w1 = omega(n);                //ω=exp(j*2*pi/n)n为信号长度
            complex[] w = new complex[n]; //储存w N次方的数组
            for (int i = 0; i < n; i++)
            {
                w[i] = complex.powcc(w1, i);
            }
            for (int k = 0; k < half; k++)
            {
                //进行蝶形运算
                complex oddPart = complex.commul(oddResult[k], w[k]);
                output[k]   = complex.comsum(evenResult[k], oddPart);
                output[k].a = Math.Round(output[k].a, 2);
                output[k].b = Math.Round(output[k].b, 2);

                output[k + half]   = complex.decrease(evenResult[k], oddPart);
                output[k + half].a = Math.Round(output[k + half].a, 2);
                output[k + half].b = Math.Round(output[k + half].b, 2);
            }
            //返回FFT或IFFT的结果
            return(output);
        }
 public void AddTest()
 {
     IComplex compl = new complex();
       complex a = new complex(2, 3);
       complex b = new complex(3, 4);
       complex actual = compl.Add(a, b);
       complex expected = a + b;
       Assert.AreEqual(actual.im, expected.im);
       Assert.AreEqual(actual.re, expected.re);
 }
 public void SubtractTest()
 {
     IComplex compl = new complex();
       complex a = new complex(20, 30);
       complex b = new complex(30, 40);
       complex actual = compl.Subtract(a, b);
       complex expected = a - b;
       Assert.AreEqual(actual.im, expected.im);
       Assert.AreEqual(actual.re, expected.re);
 }
 public void MultiplyTest()
 {
     IComplex compl = new complex();
       complex a = new complex(20, 30);
       complex b = new complex(30, 40);
       complex actual = compl.Multiply(a, b);
       complex expected = a * b;
       Assert.AreEqual(actual.im, expected.im);
       Assert.AreEqual(actual.re, expected.re);
 }
 public void DivideTest()
 {
     IComplex compl = new complex();
       complex a = new complex(20, 30);
       complex b = new complex(30, 40);
       complex actual = compl.Divide(a, b);
       complex expected = a / b;
       Assert.AreEqual(actual.im, expected.im);
       Assert.AreEqual(actual.re, expected.re);
 }
Example #33
0
        public static complex operator -(complex a)
        {
            complex result = new complex
            {
                real      = -a.real,
                imaginary = -a.imaginary
            };

            return(result);
        }
Example #34
0
        public static complex operator ++(complex a)
        {
            complex result = new complex
            {
                real      = a.real / ((float)Math.Pow(a.real, 2) + (float)Math.Pow(a.imaginary, 2)),
                imaginary = -a.imaginary / ((float)Math.Pow(a.real, 2) + (float)Math.Pow(a.imaginary, 2))
            };

            return(result);
        }
Example #35
0
 public complex[] ILArray2Values(ILArray <complex> il, int width)
 {
     complex[] result = new complex[width];
     complex[] ila    = il.ToArray();
     for (int i = 0; i < width; i++)
     {
         result[i] = ila[i * width + i];
     }
     return(result);
 }
Example #36
0
        public static complex operator *(complex a, complex b)
        {
            complex result = new complex
            {
                real      = (a.real * b.real) - (a.imaginary * b.imaginary),
                imaginary = (a.real * b.imaginary) + (a.imaginary * b.real)
            };

            return(result);
        }
Example #37
0
        private void Test_conj() {
            // test for common matrix 4x3
            ILArray<complex> A = new complex[,] {
                {new complex(1,2), new complex(3,4), new complex(5,6)},
                {new complex(7,8), new complex(9,10), new complex(11,12)},
                {new complex(13,14), new complex(15,16), new complex(17,18)},
                {new complex(19,20), new complex(21,22), new complex(23,24)}};
            ILArray<fcomplex> Af = ILMath.tofcomplex(A); 
            Test_isConj(A,ILMath.conj(A)); 
            Test_isfConj(Af,ILMath.conj(Af));
            // test on reference matrix
            Test_isConj(A,ILMath.conj(A.R)); 
            Test_isfConj(Af,ILMath.conj(Af.R));
            // test on 2x2x3 matrix (reference)
            A = A.Reshape(new ILDimension(2,2,3)).R;
            if (!A.IsReference) 
                throw new Exception("Unable to test conj() for reference 2x2x3!"); 
            Af = Af.Reshape(new ILDimension(2,2,3)).R; 
            if (!Af.IsReference) 
                throw new Exception("Unable to test conj() for reference 2x2x3!"); 
            Test_isConj(A,ILMath.conj(A)); 
            Test_isfConj(Af,ILMath.conj(Af));
            // test those on dense array 
            Test_isConj(A,ILMath.conj(A.C)); 
            Test_isfConj(Af,ILMath.conj(Af.C));
            // test for empty
            A = ILArray<complex>.empty();
            Af = ILArray<fcomplex>.empty();
            Test_isConj(A,ILMath.conj(A)); 
            Test_isfConj(Af,ILMath.conj(Af)); 
            // test on vector
            A = new complex[] { new complex(1,2), new complex(3,4), new complex(5,6)}; 
            Af = ILMath.tofcomplex(A); 
            Test_isConj(A,ILMath.conj(A)); 
            Test_isfConj(Af,ILMath.conj(Af)); 
            // transpose 
            Test_isConj(A.T,ILMath.conj(A.T)); 
            Test_isfConj(Af.T,ILMath.conj(Af.T)); 
            // test on scalar 
            A = A[2]; Af = Af[2]; 
            Test_isConj(A,ILMath.conj(A)); 
            Test_isfConj(Af,ILMath.conj(Af)); 

        }
Example #38
0
        /*************************************************************************
        Dense solver. Same as RMatrixLUSolve(), but for  HPD matrices  represented
        by their Cholesky decomposition.

        Algorithm features:
        * automatic detection of degenerate cases
        * O(N^2) complexity
        * condition number estimation
        * matrix is represented by its upper or lower triangle

        No iterative refinement is provided because such partial representation of
        matrix does not allow efficient calculation of extra-precise  matrix-vector
        products for large matrices. Use RMatrixSolve or RMatrixMixedSolve  if  you
        need iterative refinement.

        INPUT PARAMETERS
            CHA     -   array[0..N-1,0..N-1], Cholesky decomposition,
                        SPDMatrixCholesky result
            N       -   size of A
            IsUpper -   what half of CHA is provided
            B       -   array[0..N-1], right part

        OUTPUT PARAMETERS
            Info    -   same as in RMatrixSolve
            Rep     -   same as in RMatrixSolve
            X       -   same as in RMatrixSolve

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        public static void hpdmatrixcholeskysolve(complex[,] cha,
            int n,
            bool isupper,
            complex[] b,
            ref int info,
            densesolverreport rep,
            ref complex[] x)
        {
            complex[,] bm = new complex[0,0];
            complex[,] xm = new complex[0,0];
            int i_ = 0;

            info = 0;
            x = new complex[0];

            if( n<=0 )
            {
                info = -1;
                return;
            }
            bm = new complex[n, 1];
            for(i_=0; i_<=n-1;i_++)
            {
                bm[i_,0] = b[i_];
            }
            hpdmatrixcholeskysolvem(cha, n, isupper, bm, 1, ref info, rep, ref xm);
            x = new complex[n];
            for(i_=0; i_<=n-1;i_++)
            {
                x[i_] = xm[i_,0];
            }
        }
Example #39
0
    /*************************************************************************
    Dense solver. Same as RMatrixSolveM(), but for complex matrices.

    Algorithm features:
    * automatic detection of degenerate cases
    * condition number estimation
    * iterative refinement
    * O(N^3+M*N^2) complexity

    COMMERCIAL EDITION OF ALGLIB:

      ! Commercial version of ALGLIB includes two  important  improvements  of
      ! this function, which can be used from C++ and C#:
      ! * Intel MKL support (lightweight Intel MKL is shipped with ALGLIB)
      ! * multicore support
      !
      ! Intel MKL gives approximately constant  (with  respect  to  number  of
      ! worker threads) acceleration factor which depends on CPU  being  used,
      ! problem  size  and  "baseline"  ALGLIB  edition  which  is  used   for
      ! comparison.
      !
      ! Say, on SSE2-capable CPU with N=1024, HPC ALGLIB will be:
      ! * about 2-3x faster than ALGLIB for C++ without MKL
      ! * about 7-10x faster than "pure C#" edition of ALGLIB
      ! Difference in performance will be more striking  on  newer  CPU's with
      ! support for newer SIMD instructions. Generally,  MKL  accelerates  any
      ! problem whose size is at least 128, with best  efficiency achieved for
      ! N's larger than 512.
      !
      ! Commercial edition of ALGLIB also supports multithreaded  acceleration
      ! of this function. We should note that LU decomposition  is  harder  to
      ! parallelize than, say, matrix-matrix  product  -  this  algorithm  has
      ! many internal synchronization points which can not be avoided. However
      ! parallelism starts to be profitable starting  from  N=1024,  achieving
      ! near-linear speedup for N=4096 or higher.
      !
      ! In order to use multicore features you have to:
      ! * use commercial version of ALGLIB
      ! * call  this  function  with  "smp_"  prefix,  which  indicates  that
      !   multicore code will be used (for multicore support)
      !
      ! We recommend you to read 'Working with commercial version' section  of
      ! ALGLIB Reference Manual in order to find out how to  use  performance-
      ! related features provided by commercial edition of ALGLIB.

    INPUT PARAMETERS
        A       -   array[0..N-1,0..N-1], system matrix
        N       -   size of A
        B       -   array[0..N-1,0..M-1], right part
        M       -   right part size
        RFS     -   iterative refinement switch:
                    * True - refinement is used.
                      Less performance, more precision.
                    * False - refinement is not used.
                      More performance, less precision.

    OUTPUT PARAMETERS
        Info    -   same as in RMatrixSolve
        Rep     -   same as in RMatrixSolve
        X       -   same as in RMatrixSolve

      -- ALGLIB --
         Copyright 27.01.2010 by Bochkanov Sergey
    *************************************************************************/
    public static void cmatrixsolvem(complex[,] a, int n, complex[,] b, int m, bool rfs, out int info, out densesolverreport rep, out complex[,] x)
    {
        info = 0;
        rep = new densesolverreport();
        x = new complex[0,0];
        densesolver.cmatrixsolvem(a, n, b, m, rfs, ref info, rep.innerobj, ref x);
        return;
    }
Example #40
0
        /*************************************************************************
        1-dimensional real inverse FFT.

        Algorithm has O(N*logN) complexity for any N (composite or prime).

        INPUT PARAMETERS
            F   -   array[0..floor(N/2)] - frequencies from forward real FFT
            N   -   problem size

        OUTPUT PARAMETERS
            A   -   inverse DFT of a input array, array[0..N-1]

        NOTE:
            F[] should satisfy symmetry property F[k] = conj(F[N-k]), so just  one
        half of frequencies array is needed - elements from 0 to floor(N/2).  F[0]
        is ALWAYS real. If N is even F[floor(N/2)] is real too. If N is odd,  then
        F[floor(N/2)] has no special properties.

        Relying on properties noted above, FFTR1DInv subroutine uses only elements
        from 0th to floor(N/2)-th. It ignores imaginary part of F[0],  and in case
        N is even it ignores imaginary part of F[floor(N/2)] too.

        When you call this function using full arguments list - "FFTR1DInv(F,N,A)"
        - you can pass either either frequencies array with N elements or  reduced
        array with roughly N/2 elements - subroutine will  successfully  transform
        both.

        If you call this function using reduced arguments list -  "FFTR1DInv(F,A)"
        - you must pass FULL array with N elements (although higher  N/2 are still
        not used) because array size is used to automatically determine FFT length


          -- ALGLIB --
             Copyright 01.06.2009 by Bochkanov Sergey
        *************************************************************************/
        public static void fftr1dinv(complex[] f,
            int n,
            ref double[] a)
        {
            int i = 0;
            double[] h = new double[0];
            complex[] fh = new complex[0];

            a = new double[0];

            ap.assert(n>0, "FFTR1DInv: incorrect N!");
            ap.assert(ap.len(f)>=(int)Math.Floor((double)n/(double)2)+1, "FFTR1DInv: Length(F)<Floor(N/2)+1!");
            ap.assert(math.isfinite(f[0].x), "FFTR1DInv: F contains infinite or NAN values!");
            for(i=1; i<=(int)Math.Floor((double)n/(double)2)-1; i++)
            {
                ap.assert(math.isfinite(f[i].x) & math.isfinite(f[i].y), "FFTR1DInv: F contains infinite or NAN values!");
            }
            ap.assert(math.isfinite(f[(int)Math.Floor((double)n/(double)2)].x), "FFTR1DInv: F contains infinite or NAN values!");
            if( n%2!=0 )
            {
                ap.assert(math.isfinite(f[(int)Math.Floor((double)n/(double)2)].y), "FFTR1DInv: F contains infinite or NAN values!");
            }
            
            //
            // Special case: N=1, FFT is just identity transform.
            // After this block we assume that N is strictly greater than 1.
            //
            if( n==1 )
            {
                a = new double[1];
                a[0] = f[0].x;
                return;
            }
            
            //
            // inverse real FFT is reduced to the inverse real FHT,
            // which is reduced to the forward real FHT,
            // which is reduced to the forward real FFT.
            //
            // Don't worry, it is really compact and efficient reduction :)
            //
            h = new double[n];
            a = new double[n];
            h[0] = f[0].x;
            for(i=1; i<=(int)Math.Floor((double)n/(double)2)-1; i++)
            {
                h[i] = f[i].x-f[i].y;
                h[n-i] = f[i].x+f[i].y;
            }
            if( n%2==0 )
            {
                h[(int)Math.Floor((double)n/(double)2)] = f[(int)Math.Floor((double)n/(double)2)].x;
            }
            else
            {
                h[(int)Math.Floor((double)n/(double)2)] = f[(int)Math.Floor((double)n/(double)2)].x-f[(int)Math.Floor((double)n/(double)2)].y;
                h[(int)Math.Floor((double)n/(double)2)+1] = f[(int)Math.Floor((double)n/(double)2)].x+f[(int)Math.Floor((double)n/(double)2)].y;
            }
            fftr1d(h, n, ref fh);
            for(i=0; i<=n-1; i++)
            {
                a[i] = (fh[i].x-fh[i].y)/n;
            }
        }
Example #41
0
        /*************************************************************************
        Dense solver. Same as RMatrixLUSolveM(), but for HPD matrices  represented
        by their Cholesky decomposition.

        Algorithm features:
        * automatic detection of degenerate cases
        * O(M*N^2) complexity
        * condition number estimation
        * matrix is represented by its upper or lower triangle

        No iterative refinement is provided because such partial representation of
        matrix does not allow efficient calculation of extra-precise  matrix-vector
        products for large matrices. Use RMatrixSolve or RMatrixMixedSolve  if  you
        need iterative refinement.

        INPUT PARAMETERS
            CHA     -   array[0..N-1,0..N-1], Cholesky decomposition,
                        HPDMatrixCholesky result
            N       -   size of CHA
            IsUpper -   what half of CHA is provided
            B       -   array[0..N-1,0..M-1], right part
            M       -   right part size

        OUTPUT PARAMETERS
            Info    -   same as in RMatrixSolve
            Rep     -   same as in RMatrixSolve
            X       -   same as in RMatrixSolve

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        public static void hpdmatrixcholeskysolvem(complex[,] cha,
            int n,
            bool isupper,
            complex[,] b,
            int m,
            ref int info,
            densesolverreport rep,
            ref complex[,] x)
        {
            complex[,] emptya = new complex[0,0];
            double sqrtscalea = 0;
            int i = 0;
            int j = 0;
            int j1 = 0;
            int j2 = 0;

            info = 0;
            x = new complex[0,0];

            
            //
            // prepare: check inputs, allocate space...
            //
            if( n<=0 || m<=0 )
            {
                info = -1;
                return;
            }
            
            //
            // 1. scale matrix, max(|U[i,j]|)
            // 2. factorize scaled matrix
            // 3. solve
            //
            sqrtscalea = 0;
            for(i=0; i<=n-1; i++)
            {
                if( isupper )
                {
                    j1 = i;
                    j2 = n-1;
                }
                else
                {
                    j1 = 0;
                    j2 = i;
                }
                for(j=j1; j<=j2; j++)
                {
                    sqrtscalea = Math.Max(sqrtscalea, math.abscomplex(cha[i,j]));
                }
            }
            if( (double)(sqrtscalea)==(double)(0) )
            {
                sqrtscalea = 1;
            }
            sqrtscalea = 1/sqrtscalea;
            hpdmatrixcholeskysolveinternal(cha, sqrtscalea, n, isupper, emptya, false, b, m, ref info, rep, ref x);
        }
Example #42
0
 public static void smp_cmatrixsolve(complex[,] a, int n, complex[] b, out int info, out densesolverreport rep, out complex[] x)
 {
     info = 0;
     rep = new densesolverreport();
     x = new complex[0];
     densesolver._pexec_cmatrixsolve(a, n, b, ref info, rep.innerobj, ref x);
     return;
 }
Example #43
0
    /*************************************************************************
    Dense solver. Same as RMatrixMixedSolve(), but for complex matrices.

    Algorithm features:
    * automatic detection of degenerate cases
    * condition number estimation
    * iterative refinement
    * O(N^2) complexity

    INPUT PARAMETERS
        A       -   array[0..N-1,0..N-1], system matrix
        LUA     -   array[0..N-1,0..N-1], LU decomposition, CMatrixLU result
        P       -   array[0..N-1], pivots array, CMatrixLU result
        N       -   size of A
        B       -   array[0..N-1], right part

    OUTPUT PARAMETERS
        Info    -   same as in RMatrixSolveM
        Rep     -   same as in RMatrixSolveM
        X       -   same as in RMatrixSolveM

      -- ALGLIB --
         Copyright 27.01.2010 by Bochkanov Sergey
    *************************************************************************/
    public static void cmatrixmixedsolve(complex[,] a, complex[,] lua, int[] p, int n, complex[] b, out int info, out densesolverreport rep, out complex[] x)
    {
        info = 0;
        rep = new densesolverreport();
        x = new complex[0];
        densesolver.cmatrixmixedsolve(a, lua, p, n, b, ref info, rep.innerobj, ref x);
        return;
    }
Example #44
0
        /*************************************************************************
        Dense solver. Same as RMatrixLUSolveM(), but for complex matrices.

        Algorithm features:
        * automatic detection of degenerate cases
        * O(M*N^2) complexity
        * condition number estimation

        No iterative refinement  is provided because exact form of original matrix
        is not known to subroutine. Use CMatrixSolve or CMatrixMixedSolve  if  you
        need iterative refinement.

        INPUT PARAMETERS
            LUA     -   array[0..N-1,0..N-1], LU decomposition, RMatrixLU result
            P       -   array[0..N-1], pivots array, RMatrixLU result
            N       -   size of A
            B       -   array[0..N-1,0..M-1], right part
            M       -   right part size

        OUTPUT PARAMETERS
            Info    -   same as in RMatrixSolve
            Rep     -   same as in RMatrixSolve
            X       -   same as in RMatrixSolve

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        public static void cmatrixlusolvem(complex[,] lua,
            int[] p,
            int n,
            complex[,] b,
            int m,
            ref int info,
            densesolverreport rep,
            ref complex[,] x)
        {
            complex[,] emptya = new complex[0,0];
            int i = 0;
            int j = 0;
            double scalea = 0;

            info = 0;
            x = new complex[0,0];

            
            //
            // prepare: check inputs, allocate space...
            //
            if( n<=0 || m<=0 )
            {
                info = -1;
                return;
            }
            
            //
            // 1. scale matrix, max(|U[i,j]|)
            //    we assume that LU is in its normal form, i.e. |L[i,j]|<=1
            // 2. solve
            //
            scalea = 0;
            for(i=0; i<=n-1; i++)
            {
                for(j=i; j<=n-1; j++)
                {
                    scalea = Math.Max(scalea, math.abscomplex(lua[i,j]));
                }
            }
            if( (double)(scalea)==(double)(0) )
            {
                scalea = 1;
            }
            scalea = 1/scalea;
            cmatrixlusolveinternal(lua, p, scalea, n, emptya, false, b, m, ref info, rep, ref x);
        }
Example #45
0
        /*************************************************************************
        Basic LU solver for ScaleA*PLU*x = y.

        This subroutine assumes that:
        * L is well-scaled, and it is U which needs scaling by ScaleA.
        * A=PLU is well-conditioned, so no zero divisions or overflow may occur

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        private static void cbasiclusolve(complex[,] lua,
            int[] p,
            double scalea,
            int n,
            ref complex[] xb,
            ref complex[] tmp)
        {
            int i = 0;
            complex v = 0;
            int i_ = 0;

            for(i=0; i<=n-1; i++)
            {
                if( p[i]!=i )
                {
                    v = xb[i];
                    xb[i] = xb[p[i]];
                    xb[p[i]] = v;
                }
            }
            for(i=1; i<=n-1; i++)
            {
                v = 0.0;
                for(i_=0; i_<=i-1;i_++)
                {
                    v += lua[i,i_]*xb[i_];
                }
                xb[i] = xb[i]-v;
            }
            xb[n-1] = xb[n-1]/(scalea*lua[n-1,n-1]);
            for(i=n-2; i>=0; i--)
            {
                for(i_=i+1; i_<=n-1;i_++)
                {
                    tmp[i_] = scalea*lua[i,i_];
                }
                v = 0.0;
                for(i_=i+1; i_<=n-1;i_++)
                {
                    v += tmp[i_]*xb[i_];
                }
                xb[i] = (xb[i]-v)/(scalea*lua[i,i]);
            }
        }
Example #46
0
 /*************************************************************************
 Single-threaded stub. HPC ALGLIB replaces it by multithreaded code.
 *************************************************************************/
 public static void _pexec_cmatrixsolvem(complex[,] a,
     int n,
     complex[,] b,
     int m,
     bool rfs,
     ref int info,
     densesolverreport rep,
     ref complex[,] x)
 {
     cmatrixsolvem(a,n,b,m,rfs,ref info,rep,ref x);
 }
Example #47
0
 /*************************************************************************
 Single-threaded stub. HPC ALGLIB replaces it by multithreaded code.
 *************************************************************************/
 public static void _pexec_cmatrixsolve(complex[,] a,
     int n,
     complex[] b,
     ref int info,
     densesolverreport rep,
     ref complex[] x)
 {
     cmatrixsolve(a,n,b,ref info,rep,ref x);
 }
Example #48
0
        /*************************************************************************
        Dense solver. Same as RMatrixSolveM(), but for complex matrices.

        Algorithm features:
        * automatic detection of degenerate cases
        * condition number estimation
        * iterative refinement
        * O(N^3+M*N^2) complexity

        COMMERCIAL EDITION OF ALGLIB:

          ! Commercial version of ALGLIB includes two  important  improvements  of
          ! this function, which can be used from C++ and C#:
          ! * Intel MKL support (lightweight Intel MKL is shipped with ALGLIB)
          ! * multicore support
          !
          ! Intel MKL gives approximately constant  (with  respect  to  number  of
          ! worker threads) acceleration factor which depends on CPU  being  used,
          ! problem  size  and  "baseline"  ALGLIB  edition  which  is  used   for
          ! comparison.
          !
          ! Say, on SSE2-capable CPU with N=1024, HPC ALGLIB will be:
          ! * about 2-3x faster than ALGLIB for C++ without MKL
          ! * about 7-10x faster than "pure C#" edition of ALGLIB
          ! Difference in performance will be more striking  on  newer  CPU's with
          ! support for newer SIMD instructions. Generally,  MKL  accelerates  any
          ! problem whose size is at least 128, with best  efficiency achieved for
          ! N's larger than 512.
          !
          ! Commercial edition of ALGLIB also supports multithreaded  acceleration
          ! of this function. We should note that LU decomposition  is  harder  to
          ! parallelize than, say, matrix-matrix  product  -  this  algorithm  has
          ! many internal synchronization points which can not be avoided. However
          ! parallelism starts to be profitable starting  from  N=1024,  achieving
          ! near-linear speedup for N=4096 or higher.
          !
          ! In order to use multicore features you have to:
          ! * use commercial version of ALGLIB
          ! * call  this  function  with  "smp_"  prefix,  which  indicates  that
          !   multicore code will be used (for multicore support)
          !
          ! We recommend you to read 'Working with commercial version' section  of
          ! ALGLIB Reference Manual in order to find out how to  use  performance-
          ! related features provided by commercial edition of ALGLIB.

        INPUT PARAMETERS
            A       -   array[0..N-1,0..N-1], system matrix
            N       -   size of A
            B       -   array[0..N-1,0..M-1], right part
            M       -   right part size
            RFS     -   iterative refinement switch:
                        * True - refinement is used.
                          Less performance, more precision.
                        * False - refinement is not used.
                          More performance, less precision.

        OUTPUT PARAMETERS
            Info    -   same as in RMatrixSolve
            Rep     -   same as in RMatrixSolve
            X       -   same as in RMatrixSolve

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        public static void cmatrixsolvem(complex[,] a,
            int n,
            complex[,] b,
            int m,
            bool rfs,
            ref int info,
            densesolverreport rep,
            ref complex[,] x)
        {
            complex[,] da = new complex[0,0];
            complex[,] emptya = new complex[0,0];
            int[] p = new int[0];
            double scalea = 0;
            int i = 0;
            int j = 0;
            int i_ = 0;

            info = 0;
            x = new complex[0,0];

            
            //
            // prepare: check inputs, allocate space...
            //
            if( n<=0 || m<=0 )
            {
                info = -1;
                return;
            }
            da = new complex[n, n];
            
            //
            // 1. scale matrix, max(|A[i,j]|)
            // 2. factorize scaled matrix
            // 3. solve
            //
            scalea = 0;
            for(i=0; i<=n-1; i++)
            {
                for(j=0; j<=n-1; j++)
                {
                    scalea = Math.Max(scalea, math.abscomplex(a[i,j]));
                }
            }
            if( (double)(scalea)==(double)(0) )
            {
                scalea = 1;
            }
            scalea = 1/scalea;
            for(i=0; i<=n-1; i++)
            {
                for(i_=0; i_<=n-1;i_++)
                {
                    da[i,i_] = a[i,i_];
                }
            }
            trfac.cmatrixlu(ref da, n, n, ref p);
            if( rfs )
            {
                cmatrixlusolveinternal(da, p, scalea, n, a, true, b, m, ref info, rep, ref x);
            }
            else
            {
                cmatrixlusolveinternal(da, p, scalea, n, emptya, false, b, m, ref info, rep, ref x);
            }
        }
Example #49
0
    /*************************************************************************
    Dense solver. Same as RMatrixLUSolve(), but for  HPD matrices  represented
    by their Cholesky decomposition.

    Algorithm features:
    * automatic detection of degenerate cases
    * O(N^2) complexity
    * condition number estimation
    * matrix is represented by its upper or lower triangle

    No iterative refinement is provided because such partial representation of
    matrix does not allow efficient calculation of extra-precise  matrix-vector
    products for large matrices. Use RMatrixSolve or RMatrixMixedSolve  if  you
    need iterative refinement.

    INPUT PARAMETERS
        CHA     -   array[0..N-1,0..N-1], Cholesky decomposition,
                    SPDMatrixCholesky result
        N       -   size of A
        IsUpper -   what half of CHA is provided
        B       -   array[0..N-1], right part

    OUTPUT PARAMETERS
        Info    -   same as in RMatrixSolve
        Rep     -   same as in RMatrixSolve
        X       -   same as in RMatrixSolve

      -- ALGLIB --
         Copyright 27.01.2010 by Bochkanov Sergey
    *************************************************************************/
    public static void hpdmatrixcholeskysolve(complex[,] cha, int n, bool isupper, complex[] b, out int info, out densesolverreport rep, out complex[] x)
    {
        info = 0;
        rep = new densesolverreport();
        x = new complex[0];
        densesolver.hpdmatrixcholeskysolve(cha, n, isupper, b, ref info, rep.innerobj, ref x);
        return;
    }
Example #50
0
 public static void smp_hpdmatrixsolvem(complex[,] a, int n, bool isupper, complex[,] b, int m, out int info, out densesolverreport rep, out complex[,] x)
 {
     info = 0;
     rep = new densesolverreport();
     x = new complex[0,0];
     densesolver._pexec_hpdmatrixsolvem(a, n, isupper, b, m, ref info, rep.innerobj, ref x);
     return;
 }
Example #51
0
        /*************************************************************************
        Internal LU solver

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        private static void cmatrixlusolveinternal(complex[,] lua,
            int[] p,
            double scalea,
            int n,
            complex[,] a,
            bool havea,
            complex[,] b,
            int m,
            ref int info,
            densesolverreport rep,
            ref complex[,] x)
        {
            int i = 0;
            int j = 0;
            int k = 0;
            int rfs = 0;
            int nrfs = 0;
            complex[] xc = new complex[0];
            complex[] y = new complex[0];
            complex[] bc = new complex[0];
            complex[] xa = new complex[0];
            complex[] xb = new complex[0];
            complex[] tx = new complex[0];
            double[] tmpbuf = new double[0];
            complex v = 0;
            double verr = 0;
            double mxb = 0;
            double scaleright = 0;
            bool smallerr = new bool();
            bool terminatenexttime = new bool();
            int i_ = 0;

            info = 0;
            x = new complex[0,0];

            alglib.ap.assert((double)(scalea)>(double)(0));
            
            //
            // prepare: check inputs, allocate space...
            //
            if( n<=0 || m<=0 )
            {
                info = -1;
                return;
            }
            for(i=0; i<=n-1; i++)
            {
                if( p[i]>n-1 || p[i]<i )
                {
                    info = -1;
                    return;
                }
            }
            x = new complex[n, m];
            y = new complex[n];
            xc = new complex[n];
            bc = new complex[n];
            tx = new complex[n];
            xa = new complex[n+1];
            xb = new complex[n+1];
            tmpbuf = new double[2*n+2];
            
            //
            // estimate condition number, test for near singularity
            //
            rep.r1 = rcond.cmatrixlurcond1(lua, n);
            rep.rinf = rcond.cmatrixlurcondinf(lua, n);
            if( (double)(rep.r1)<(double)(rcond.rcondthreshold()) || (double)(rep.rinf)<(double)(rcond.rcondthreshold()) )
            {
                for(i=0; i<=n-1; i++)
                {
                    for(j=0; j<=m-1; j++)
                    {
                        x[i,j] = 0;
                    }
                }
                rep.r1 = 0;
                rep.rinf = 0;
                info = -3;
                return;
            }
            info = 1;
            
            //
            // solve
            //
            for(k=0; k<=m-1; k++)
            {
                
                //
                // copy B to contiguous storage
                //
                for(i_=0; i_<=n-1;i_++)
                {
                    bc[i_] = b[i_,k];
                }
                
                //
                // Scale right part:
                // * MX stores max(|Bi|)
                // * ScaleRight stores actual scaling applied to B when solving systems
                //   it is chosen to make |scaleRight*b| close to 1.
                //
                mxb = 0;
                for(i=0; i<=n-1; i++)
                {
                    mxb = Math.Max(mxb, math.abscomplex(bc[i]));
                }
                if( (double)(mxb)==(double)(0) )
                {
                    mxb = 1;
                }
                scaleright = 1/mxb;
                
                //
                // First, non-iterative part of solution process.
                // We use separate code for this task because
                // XDot is quite slow and we want to save time.
                //
                for(i_=0; i_<=n-1;i_++)
                {
                    xc[i_] = scaleright*bc[i_];
                }
                cbasiclusolve(lua, p, scalea, n, ref xc, ref tx);
                
                //
                // Iterative refinement of xc:
                // * calculate r = bc-A*xc using extra-precise dot product
                // * solve A*y = r
                // * update x:=x+r
                //
                // This cycle is executed until one of two things happens:
                // 1. maximum number of iterations reached
                // 2. last iteration decreased error to the lower limit
                //
                if( havea )
                {
                    nrfs = densesolverrfsmax(n, rep.r1, rep.rinf);
                    terminatenexttime = false;
                    for(rfs=0; rfs<=nrfs-1; rfs++)
                    {
                        if( terminatenexttime )
                        {
                            break;
                        }
                        
                        //
                        // generate right part
                        //
                        smallerr = true;
                        for(i_=0; i_<=n-1;i_++)
                        {
                            xb[i_] = xc[i_];
                        }
                        for(i=0; i<=n-1; i++)
                        {
                            for(i_=0; i_<=n-1;i_++)
                            {
                                xa[i_] = scalea*a[i,i_];
                            }
                            xa[n] = -1;
                            xb[n] = scaleright*bc[i];
                            xblas.xcdot(xa, xb, n+1, ref tmpbuf, ref v, ref verr);
                            y[i] = -v;
                            smallerr = smallerr && (double)(math.abscomplex(v))<(double)(4*verr);
                        }
                        if( smallerr )
                        {
                            terminatenexttime = true;
                        }
                        
                        //
                        // solve and update
                        //
                        cbasiclusolve(lua, p, scalea, n, ref y, ref tx);
                        for(i_=0; i_<=n-1;i_++)
                        {
                            xc[i_] = xc[i_] + y[i_];
                        }
                    }
                }
                
                //
                // Store xc.
                // Post-scale result.
                //
                v = scalea*mxb;
                for(i_=0; i_<=n-1;i_++)
                {
                    x[i_,k] = v*xc[i_];
                }
            }
        }
Example #52
0
        /*************************************************************************
        Dense solver. Same as RMatrixMixedSolveM(), but for complex matrices.

        Algorithm features:
        * automatic detection of degenerate cases
        * condition number estimation
        * iterative refinement
        * O(M*N^2) complexity

        INPUT PARAMETERS
            A       -   array[0..N-1,0..N-1], system matrix
            LUA     -   array[0..N-1,0..N-1], LU decomposition, CMatrixLU result
            P       -   array[0..N-1], pivots array, CMatrixLU result
            N       -   size of A
            B       -   array[0..N-1,0..M-1], right part
            M       -   right part size

        OUTPUT PARAMETERS
            Info    -   same as in RMatrixSolveM
            Rep     -   same as in RMatrixSolveM
            X       -   same as in RMatrixSolveM

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        public static void cmatrixmixedsolvem(complex[,] a,
            complex[,] lua,
            int[] p,
            int n,
            complex[,] b,
            int m,
            ref int info,
            densesolverreport rep,
            ref complex[,] x)
        {
            double scalea = 0;
            int i = 0;
            int j = 0;

            info = 0;
            x = new complex[0,0];

            
            //
            // prepare: check inputs, allocate space...
            //
            if( n<=0 || m<=0 )
            {
                info = -1;
                return;
            }
            
            //
            // 1. scale matrix, max(|A[i,j]|)
            // 2. factorize scaled matrix
            // 3. solve
            //
            scalea = 0;
            for(i=0; i<=n-1; i++)
            {
                for(j=0; j<=n-1; j++)
                {
                    scalea = Math.Max(scalea, math.abscomplex(a[i,j]));
                }
            }
            if( (double)(scalea)==(double)(0) )
            {
                scalea = 1;
            }
            scalea = 1/scalea;
            cmatrixlusolveinternal(lua, p, scalea, n, a, true, b, m, ref info, rep, ref x);
        }
Example #53
0
        /*************************************************************************
        Internal Cholesky solver

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        private static void hpdmatrixcholeskysolveinternal(complex[,] cha,
            double sqrtscalea,
            int n,
            bool isupper,
            complex[,] a,
            bool havea,
            complex[,] b,
            int m,
            ref int info,
            densesolverreport rep,
            ref complex[,] x)
        {
            int i = 0;
            int j = 0;
            int k = 0;
            complex[] xc = new complex[0];
            complex[] y = new complex[0];
            complex[] bc = new complex[0];
            complex[] xa = new complex[0];
            complex[] xb = new complex[0];
            complex[] tx = new complex[0];
            double v = 0;
            double mxb = 0;
            double scaleright = 0;
            int i_ = 0;

            info = 0;
            x = new complex[0,0];

            alglib.ap.assert((double)(sqrtscalea)>(double)(0));
            
            //
            // prepare: check inputs, allocate space...
            //
            if( n<=0 || m<=0 )
            {
                info = -1;
                return;
            }
            x = new complex[n, m];
            y = new complex[n];
            xc = new complex[n];
            bc = new complex[n];
            tx = new complex[n+1];
            xa = new complex[n+1];
            xb = new complex[n+1];
            
            //
            // estimate condition number, test for near singularity
            //
            rep.r1 = rcond.hpdmatrixcholeskyrcond(cha, n, isupper);
            rep.rinf = rep.r1;
            if( (double)(rep.r1)<(double)(rcond.rcondthreshold()) )
            {
                for(i=0; i<=n-1; i++)
                {
                    for(j=0; j<=m-1; j++)
                    {
                        x[i,j] = 0;
                    }
                }
                rep.r1 = 0;
                rep.rinf = 0;
                info = -3;
                return;
            }
            info = 1;
            
            //
            // solve
            //
            for(k=0; k<=m-1; k++)
            {
                
                //
                // copy B to contiguous storage
                //
                for(i_=0; i_<=n-1;i_++)
                {
                    bc[i_] = b[i_,k];
                }
                
                //
                // Scale right part:
                // * MX stores max(|Bi|)
                // * ScaleRight stores actual scaling applied to B when solving systems
                //   it is chosen to make |scaleRight*b| close to 1.
                //
                mxb = 0;
                for(i=0; i<=n-1; i++)
                {
                    mxb = Math.Max(mxb, math.abscomplex(bc[i]));
                }
                if( (double)(mxb)==(double)(0) )
                {
                    mxb = 1;
                }
                scaleright = 1/mxb;
                
                //
                // First, non-iterative part of solution process.
                // We use separate code for this task because
                // XDot is quite slow and we want to save time.
                //
                for(i_=0; i_<=n-1;i_++)
                {
                    xc[i_] = scaleright*bc[i_];
                }
                hpdbasiccholeskysolve(cha, sqrtscalea, n, isupper, ref xc, ref tx);
                
                //
                // Store xc.
                // Post-scale result.
                //
                v = math.sqr(sqrtscalea)*mxb;
                for(i_=0; i_<=n-1;i_++)
                {
                    x[i_,k] = v*xc[i_];
                }
            }
        }
Example #54
0
        /*************************************************************************
        Dense solver. Same as RMatrixMixedSolve(), but for complex matrices.

        Algorithm features:
        * automatic detection of degenerate cases
        * condition number estimation
        * iterative refinement
        * O(N^2) complexity

        INPUT PARAMETERS
            A       -   array[0..N-1,0..N-1], system matrix
            LUA     -   array[0..N-1,0..N-1], LU decomposition, CMatrixLU result
            P       -   array[0..N-1], pivots array, CMatrixLU result
            N       -   size of A
            B       -   array[0..N-1], right part

        OUTPUT PARAMETERS
            Info    -   same as in RMatrixSolveM
            Rep     -   same as in RMatrixSolveM
            X       -   same as in RMatrixSolveM

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        public static void cmatrixmixedsolve(complex[,] a,
            complex[,] lua,
            int[] p,
            int n,
            complex[] b,
            ref int info,
            densesolverreport rep,
            ref complex[] x)
        {
            complex[,] bm = new complex[0,0];
            complex[,] xm = new complex[0,0];
            int i_ = 0;

            info = 0;
            x = new complex[0];

            if( n<=0 )
            {
                info = -1;
                return;
            }
            bm = new complex[n, 1];
            for(i_=0; i_<=n-1;i_++)
            {
                bm[i_,0] = b[i_];
            }
            cmatrixmixedsolvem(a, lua, p, n, bm, 1, ref info, rep, ref xm);
            x = new complex[n];
            for(i_=0; i_<=n-1;i_++)
            {
                x[i_] = xm[i_,0];
            }
        }
Example #55
0
        /*************************************************************************
        Basic Cholesky solver for ScaleA*Cholesky(A)'*x = y.

        This subroutine assumes that:
        * A*ScaleA is well scaled
        * A is well-conditioned, so no zero divisions or overflow may occur

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        private static void hpdbasiccholeskysolve(complex[,] cha,
            double sqrtscalea,
            int n,
            bool isupper,
            ref complex[] xb,
            ref complex[] tmp)
        {
            int i = 0;
            complex v = 0;
            int i_ = 0;

            
            //
            // A = L*L' or A=U'*U
            //
            if( isupper )
            {
                
                //
                // Solve U'*y=b first.
                //
                for(i=0; i<=n-1; i++)
                {
                    xb[i] = xb[i]/(sqrtscalea*math.conj(cha[i,i]));
                    if( i<n-1 )
                    {
                        v = xb[i];
                        for(i_=i+1; i_<=n-1;i_++)
                        {
                            tmp[i_] = sqrtscalea*math.conj(cha[i,i_]);
                        }
                        for(i_=i+1; i_<=n-1;i_++)
                        {
                            xb[i_] = xb[i_] - v*tmp[i_];
                        }
                    }
                }
                
                //
                // Solve U*x=y then.
                //
                for(i=n-1; i>=0; i--)
                {
                    if( i<n-1 )
                    {
                        for(i_=i+1; i_<=n-1;i_++)
                        {
                            tmp[i_] = sqrtscalea*cha[i,i_];
                        }
                        v = 0.0;
                        for(i_=i+1; i_<=n-1;i_++)
                        {
                            v += tmp[i_]*xb[i_];
                        }
                        xb[i] = xb[i]-v;
                    }
                    xb[i] = xb[i]/(sqrtscalea*cha[i,i]);
                }
            }
            else
            {
                
                //
                // Solve L*y=b first
                //
                for(i=0; i<=n-1; i++)
                {
                    if( i>0 )
                    {
                        for(i_=0; i_<=i-1;i_++)
                        {
                            tmp[i_] = sqrtscalea*cha[i,i_];
                        }
                        v = 0.0;
                        for(i_=0; i_<=i-1;i_++)
                        {
                            v += tmp[i_]*xb[i_];
                        }
                        xb[i] = xb[i]-v;
                    }
                    xb[i] = xb[i]/(sqrtscalea*cha[i,i]);
                }
                
                //
                // Solve L'*x=y then.
                //
                for(i=n-1; i>=0; i--)
                {
                    xb[i] = xb[i]/(sqrtscalea*math.conj(cha[i,i]));
                    if( i>0 )
                    {
                        v = xb[i];
                        for(i_=0; i_<=i-1;i_++)
                        {
                            tmp[i_] = sqrtscalea*math.conj(cha[i,i_]);
                        }
                        for(i_=0; i_<=i-1;i_++)
                        {
                            xb[i_] = xb[i_] - v*tmp[i_];
                        }
                    }
                }
            }
        }
Example #56
0
        /*************************************************************************
        Dense solver. Same as RMatrixSolveM(), but for Hermitian positive definite
        matrices.

        Algorithm features:
        * automatic detection of degenerate cases
        * condition number estimation
        * O(N^3+M*N^2) complexity
        * matrix is represented by its upper or lower triangle

        No iterative refinement is provided because such partial representation of
        matrix does not allow efficient calculation of extra-precise  matrix-vector
        products for large matrices. Use RMatrixSolve or RMatrixMixedSolve  if  you
        need iterative refinement.

        COMMERCIAL EDITION OF ALGLIB:

          ! Commercial version of ALGLIB includes two  important  improvements  of
          ! this function, which can be used from C++ and C#:
          ! * Intel MKL support (lightweight Intel MKL is shipped with ALGLIB)
          ! * multicore support
          !
          ! Intel MKL gives approximately constant  (with  respect  to  number  of
          ! worker threads) acceleration factor which depends on CPU  being  used,
          ! problem  size  and  "baseline"  ALGLIB  edition  which  is  used   for
          ! comparison.
          !
          ! Say, on SSE2-capable CPU with N=1024, HPC ALGLIB will be:
          ! * about 2-3x faster than ALGLIB for C++ without MKL
          ! * about 7-10x faster than "pure C#" edition of ALGLIB
          ! Difference in performance will be more striking  on  newer  CPU's with
          ! support for newer SIMD instructions. Generally,  MKL  accelerates  any
          ! problem whose size is at least 128, with best  efficiency achieved for
          ! N's larger than 512.
          !
          ! Commercial edition of ALGLIB also supports multithreaded  acceleration
          ! of this function. We should note that Cholesky decomposition is harder
          ! to parallelize than, say, matrix-matrix product - this  algorithm  has
          ! several synchronization points which  can  not  be  avoided.  However,
          ! parallelism starts to be profitable starting from N=500.
          !
          ! In order to use multicore features you have to:
          ! * use commercial version of ALGLIB
          ! * call  this  function  with  "smp_"  prefix,  which  indicates  that
          !   multicore code will be used (for multicore support)
          !
          ! We recommend you to read 'Working with commercial version' section  of
          ! ALGLIB Reference Manual in order to find out how to  use  performance-
          ! related features provided by commercial edition of ALGLIB.

        INPUT PARAMETERS
            A       -   array[0..N-1,0..N-1], system matrix
            N       -   size of A
            IsUpper -   what half of A is provided
            B       -   array[0..N-1,0..M-1], right part
            M       -   right part size

        OUTPUT PARAMETERS
            Info    -   same as in RMatrixSolve.
                        Returns -3 for non-HPD matrices.
            Rep     -   same as in RMatrixSolve
            X       -   same as in RMatrixSolve

          -- ALGLIB --
             Copyright 27.01.2010 by Bochkanov Sergey
        *************************************************************************/
        public static void hpdmatrixsolvem(complex[,] a,
            int n,
            bool isupper,
            complex[,] b,
            int m,
            ref int info,
            densesolverreport rep,
            ref complex[,] x)
        {
            complex[,] da = new complex[0,0];
            double sqrtscalea = 0;
            int i = 0;
            int j = 0;
            int j1 = 0;
            int j2 = 0;
            int i_ = 0;

            info = 0;
            x = new complex[0,0];

            
            //
            // prepare: check inputs, allocate space...
            //
            if( n<=0 || m<=0 )
            {
                info = -1;
                return;
            }
            da = new complex[n, n];
            
            //
            // 1. scale matrix, max(|A[i,j]|)
            // 2. factorize scaled matrix
            // 3. solve
            //
            sqrtscalea = 0;
            for(i=0; i<=n-1; i++)
            {
                if( isupper )
                {
                    j1 = i;
                    j2 = n-1;
                }
                else
                {
                    j1 = 0;
                    j2 = i;
                }
                for(j=j1; j<=j2; j++)
                {
                    sqrtscalea = Math.Max(sqrtscalea, math.abscomplex(a[i,j]));
                }
            }
            if( (double)(sqrtscalea)==(double)(0) )
            {
                sqrtscalea = 1;
            }
            sqrtscalea = 1/sqrtscalea;
            sqrtscalea = Math.Sqrt(sqrtscalea);
            for(i=0; i<=n-1; i++)
            {
                if( isupper )
                {
                    j1 = i;
                    j2 = n-1;
                }
                else
                {
                    j1 = 0;
                    j2 = i;
                }
                for(i_=j1; i_<=j2;i_++)
                {
                    da[i,i_] = a[i,i_];
                }
            }
            if( !trfac.hpdmatrixcholesky(ref da, n, isupper) )
            {
                x = new complex[n, m];
                for(i=0; i<=n-1; i++)
                {
                    for(j=0; j<=m-1; j++)
                    {
                        x[i,j] = 0;
                    }
                }
                rep.r1 = 0;
                rep.rinf = 0;
                info = -3;
                return;
            }
            info = 1;
            hpdmatrixcholeskysolveinternal(da, sqrtscalea, n, isupper, a, true, b, m, ref info, rep, ref x);
        }
Example #57
0
    /*************************************************************************
    Dense solver. Same as RMatrixLUSolveM(), but for complex matrices.

    Algorithm features:
    * automatic detection of degenerate cases
    * O(M*N^2) complexity
    * condition number estimation

    No iterative refinement  is provided because exact form of original matrix
    is not known to subroutine. Use CMatrixSolve or CMatrixMixedSolve  if  you
    need iterative refinement.

    INPUT PARAMETERS
        LUA     -   array[0..N-1,0..N-1], LU decomposition, RMatrixLU result
        P       -   array[0..N-1], pivots array, RMatrixLU result
        N       -   size of A
        B       -   array[0..N-1,0..M-1], right part
        M       -   right part size

    OUTPUT PARAMETERS
        Info    -   same as in RMatrixSolve
        Rep     -   same as in RMatrixSolve
        X       -   same as in RMatrixSolve

      -- ALGLIB --
         Copyright 27.01.2010 by Bochkanov Sergey
    *************************************************************************/
    public static void cmatrixlusolvem(complex[,] lua, int[] p, int n, complex[,] b, int m, out int info, out densesolverreport rep, out complex[,] x)
    {
        info = 0;
        rep = new densesolverreport();
        x = new complex[0,0];
        densesolver.cmatrixlusolvem(lua, p, n, b, m, ref info, rep.innerobj, ref x);
        return;
    }
Example #58
0
 /*************************************************************************
 Single-threaded stub. HPC ALGLIB replaces it by multithreaded code.
 *************************************************************************/
 public static void _pexec_hpdmatrixsolve(complex[,] a,
     int n,
     bool isupper,
     complex[] b,
     ref int info,
     densesolverreport rep,
     ref complex[] x)
 {
     hpdmatrixsolve(a,n,isupper,b,ref info,rep,ref x);
 }
Example #59
0
        /*************************************************************************
        Polynomial root finding.

        This function returns all roots of the polynomial
            P(x) = a0 + a1*x + a2*x^2 + ... + an*x^n
        Both real and complex roots are returned (see below).

        INPUT PARAMETERS:
            A       -   array[N+1], polynomial coefficients:
                        * A[0] is constant term
                        * A[N] is a coefficient of X^N
            N       -   polynomial degree

        OUTPUT PARAMETERS:
            X       -   array of complex roots:
                        * for isolated real root, X[I] is strictly real: IMAGE(X[I])=0
                        * complex roots are always returned in pairs - roots occupy
                          positions I and I+1, with:
                          * X[I+1]=Conj(X[I])
                          * IMAGE(X[I]) > 0
                          * IMAGE(X[I+1]) = -IMAGE(X[I]) < 0
                        * multiple real roots may have non-zero imaginary part due
                          to roundoff errors. There is no reliable way to distinguish
                          real root of multiplicity 2 from two  complex  roots  in
                          the presence of roundoff errors.
            Rep     -   report, additional information, following fields are set:
                        * Rep.MaxErr - max( |P(xi)| )  for  i=0..N-1.  This  field
                          allows to quickly estimate "quality" of the roots  being
                          returned.

        NOTE:   this function uses companion matrix method to find roots. In  case
                internal EVD  solver  fails  do  find  eigenvalues,  exception  is
                generated.

        NOTE:   roots are not "polished" and  no  matrix  balancing  is  performed
                for them.

          -- ALGLIB --
             Copyright 24.02.2014 by Bochkanov Sergey
        *************************************************************************/
        public static void polynomialsolve(double[] a,
            int n,
            ref complex[] x,
            polynomialsolverreport rep)
        {
            double[,] c = new double[0,0];
            double[,] vl = new double[0,0];
            double[,] vr = new double[0,0];
            double[] wr = new double[0];
            double[] wi = new double[0];
            int i = 0;
            int j = 0;
            bool status = new bool();
            int nz = 0;
            int ne = 0;
            complex v = 0;
            complex vv = 0;

            a = (double[])a.Clone();
            x = new complex[0];

            alglib.ap.assert(n>0, "PolynomialSolve: N<=0");
            alglib.ap.assert(alglib.ap.len(a)>=n+1, "PolynomialSolve: Length(A)<N+1");
            alglib.ap.assert(apserv.isfinitevector(a, n+1), "PolynomialSolve: A contains infitite numbers");
            alglib.ap.assert((double)(a[n])!=(double)(0), "PolynomialSolve: A[N]=0");
            
            //
            // Prepare
            //
            x = new complex[n];
            
            //
            // Normalize A:
            // * analytically determine NZ zero roots
            // * quick exit for NZ=N
            // * make residual NE-th degree polynomial monic
            //   (here NE=N-NZ)
            //
            nz = 0;
            while( nz<n && (double)(a[nz])==(double)(0) )
            {
                nz = nz+1;
            }
            ne = n-nz;
            for(i=nz; i<=n; i++)
            {
                a[i-nz] = a[i]/a[n];
            }
            
            //
            // For NZ<N, build companion matrix and find NE non-zero roots
            //
            if( ne>0 )
            {
                c = new double[ne, ne];
                for(i=0; i<=ne-1; i++)
                {
                    for(j=0; j<=ne-1; j++)
                    {
                        c[i,j] = 0;
                    }
                }
                c[0,ne-1] = -a[0];
                for(i=1; i<=ne-1; i++)
                {
                    c[i,i-1] = 1;
                    c[i,ne-1] = -a[i];
                }
                status = evd.rmatrixevd(c, ne, 0, ref wr, ref wi, ref vl, ref vr);
                alglib.ap.assert(status, "PolynomialSolve: inernal error - EVD solver failed");
                for(i=0; i<=ne-1; i++)
                {
                    x[i].x = wr[i];
                    x[i].y = wi[i];
                }
            }
            
            //
            // Remaining NZ zero roots
            //
            for(i=ne; i<=n-1; i++)
            {
                x[i] = 0;
            }
            
            //
            // Rep
            //
            rep.maxerr = 0;
            for(i=0; i<=ne-1; i++)
            {
                v = 0;
                vv = 1;
                for(j=0; j<=ne; j++)
                {
                    v = v+a[j]*vv;
                    vv = vv*x[i];
                }
                rep.maxerr = Math.Max(rep.maxerr, math.abscomplex(v));
            }
        }
Example #60
0
    /*************************************************************************
    1-dimensional complex inverse FFT.

    Array size N may be arbitrary number (composite or prime).  Algorithm  has
    O(N*logN) complexity for any N (composite or prime).

    See FFTC1D() description for more information about algorithm performance.

    INPUT PARAMETERS
        A   -   array[0..N-1] - complex array to be transformed
        N   -   problem size

    OUTPUT PARAMETERS
        A   -   inverse DFT of a input array, array[0..N-1]
                A_out[j] = SUM(A_in[k]/N*exp(+2*pi*sqrt(-1)*j*k/N), k = 0..N-1)


      -- ALGLIB --
         Copyright 29.05.2009 by Bochkanov Sergey
    *************************************************************************/
    public static void fftc1dinv(ref complex[] a, int n)
    {

        fft.fftc1dinv(ref a, n);
        return;
    }