Пример #1
0
        /// <summary>
        /// Outer product of two vectors; Returns a matrix with <i>A[i,j] = x[i] * y[j]</i>.
        /// </summary>
        /// <param name="x">the first source vector.</param>
        /// <param name="y">the second source vector.</param>
        /// <returns>the outer product </i>A</i>.</returns>
        private static DoubleMatrix2D XMultOuter(DoubleMatrix1D x, DoubleMatrix1D y)
        {
            DoubleMatrix2D A = x.Like2D(x.Size, y.Size);

            MultOuter(x, y, A);
            return(A);
        }
        public DoubleMatrix2D LowerTriangular(DoubleMatrix2D A)
        {
            int rows    = A.Rows;
            int columns = A.Columns;
            int min     = System.Math.Min(rows, columns);

            for (int r = min; --r >= 0;)
            {
                for (int c = min; --c >= 0;)
                {
                    if (r < c)
                    {
                        A[r, c] = 0;
                    }
                    else if (r == c)
                    {
                        A[r, c] = 1;
                    }
                }
            }
            if (columns > rows)
            {
                A.ViewPart(0, min, rows, columns - min).Assign(0);
            }

            return(A);
        }
Пример #3
0
        /// <summary>
        /// 9 point stencil operation.
        /// Applies a function to a moving <i>3 x 3</i> window.
        /// </summary>
        /// <param name="A">
        /// the matrix to operate on.
        /// </param>
        /// <param name="function">
        /// the function to be applied to each window.
        /// </param>
        /// <param name="maxIterations">
        /// the maximum number of times the stencil shall be applied to the matrixd
        /// Should be a multiple of 2 because two iterations are always done in one atomic step.
        /// </param>
        /// <param name="hasConverged">
        /// Convergence condition; will return before maxIterations are done when <i>hasConverged.apply(A)==true</i>.
        /// Set this parameter to <i>null</i> to indicate that no convergence checks shall be made.
        /// </param>
        /// <param name="convergenceIterations">
        /// the number of iterations to pass between each convergence check.
        /// (Since a convergence may be expensive, you may want to do it only every 2,4 or 8 iterationsd)
        /// </param>
        /// <returns><the number of iterations actually executedd /returns>
        public static int Stencil9(DoubleMatrix2D A, Cern.Colt.Function.Double9Function function, int maxIterations, DoubleMatrix2DProcedure hasConverged, int convergenceIterations)
        {
            DoubleMatrix2D B = A.Copy();

            if (convergenceIterations <= 1)
            {
                convergenceIterations = 2;
            }
            if (convergenceIterations % 2 != 0)
            {
                convergenceIterations++;                                 // odd -> make it even
            }
            int i = 0;

            while (i < maxIterations)
            { // do two steps at a time for efficiency
                A.ZAssign8Neighbors(B, function);
                B.ZAssign8Neighbors(A, function);
                i = i + 2;
                if (i % convergenceIterations == 0 && hasConverged != null)
                {
                    if (hasConverged(A))
                    {
                        return(i);
                    }
                }
            }
            return(i);
        }
        private Pair<int, int> max(DoubleMatrix2D matrix)
        {
            if (matrix == null)
            {
                return null;
            }

            int row = 0;
            int column = 0;
            double value = 0;

            for (int r = 0; r < matrix.rows(); r++)
            {
                for (int c = 0; c < matrix.columns(); c++)
                {
                    double currentValue = matrix.getQuick(r, c);
                    if (currentValue > value)
                    {
                        value = currentValue;
                        row = r;
                        column = c;
                    }
                }
            }

            if (value > 0)
            {
                return new Pair<int, int>(row, column);
            }
            else
            {
                return null;
            }
        }
Пример #5
0
        /// <summary>
        /// Outer product of two vectors; Sets <i>A[i,j] = x[i] * y[j]</i>.
        /// </summary>
        /// <param name="x">the first source vector.</param>
        /// <param name="y">the second source vector.</param>
        /// <param name="A">the matrix to hold the resultsd Set this parameter to <i>null</i> to indicate that a new result matrix shall be constructed.</param>
        /// <returns>A (for convenience only).</returns>
        public static DoubleMatrix2D MultOuter(DoubleMatrix1D x, DoubleMatrix1D y, DoubleMatrix2D A)
        {
            int rows    = x.Size;
            int columns = y.Size;

            if (A == null)
            {
                A = x.Like2D(rows, columns);
            }
            if (A.Rows != rows || A.Columns != columns)
            {
                throw new ArgumentException();
            }

            for (int row = rows; --row >= 0;)
            {
                A.ViewRow(row).Assign(y);
            }

            for (int column = columns; --column >= 0;)
            {
                A.ViewColumn(column).Assign(x, BinaryFunctions.Mult);
            }
            return(A);
        }
Пример #6
0
 /**
  * Sets the matrices to operate upon.
  */
 public virtual void SetParameters(DoubleMatrix2D A, DoubleMatrix2D B)
 {
     this.A = A;
     this.B = B;
     this.C = A.Copy();
     this.D = B.Copy();
 }
Пример #7
0
 /// <summary>
 /// Checks whether the given matrix <i>A</i> is <i>square</i>.
 /// </summary>
 /// <param name="A"></param>
 /// <exception cref="ArgumentException">if <i>A.Rows != A.Columns</i>.</exception>
 public void CheckSquare(DoubleMatrix2D A)
 {
     if (A.Rows != A.Columns)
     {
         throw new ArgumentException(Cern.LocalizedResources.Instance().Exception_MatrixMustBeSquare);
     }
 }
Пример #8
0
 /// <summary>
 /// Checks whether the given matrix <i>A</i> is <i>square</i>.
 /// </summary>
 /// <param name="A"></param>
 /// <exception cref="ArgumentException">if <i>A.Rows != A.Columns</i>.</exception>
 public void CheckSquare(DoubleMatrix2D A)
 {
     if (A.Rows != A.Columns)
     {
         throw new ArgumentException("Matrix must be square: " + Cern.Colt.Matrix.DoubleAlgorithms.Formatter.Shape(A));
     }
 }
Пример #9
0
        /// <summary>
        /// Returns a string representation of the given matrix.
        /// </summary>
        /// <param name="matrix">
        /// The matrix to convert.
        /// </param>
        /// <returns>
        /// A string representation of the given matrix.
        /// </returns>
        public string ToString(DoubleMatrix1D matrix)
        {
            DoubleMatrix2D easy = matrix.Like2D(1, matrix.Size);

            easy.ViewRow(0).Assign(matrix);
            return(ToString(easy));
        }
Пример #10
0
        /// <summary>
        /// Solves <i>A*X = B</i>; returns <i>X</i>.
        /// </summary>
        /// <param name="B">A Matrix with as many rows as <i>A</i> and any number of columns.</param>
        /// <returns><i>X</i> so that <i>L*L'*X = B</i>.</returns>
        /// <exception cref="ArgumentException">if <i>B.Rows != A.Rows</i>.</exception>
        /// <exception cref="ArgumentException">if <i>!isSymmetricPositiveDefinite()</i>.</exception>
        public DoubleMatrix2D Solve(DoubleMatrix2D B)
        {
            // Copy right hand side.
            DoubleMatrix2D X  = B.Copy();
            int            nx = B.Columns;

            // fix by MG Ferreira <*****@*****.**>
            // old code is in method xxxSolveBuggy()
            for (int c = 0; c < nx; c++)
            {
                // Solve L*Y = B;
                for (int i = 0; i < n; i++)
                {
                    double sum = B[i, c];
                    for (int k = i - 1; k >= 0; k--)
                    {
                        sum -= mL[i, k] * X[k, c];
                    }
                    X[i, c] = sum / mL[i, i];
                }

                // Solve L'*X = Y;
                for (int i = n - 1; i >= 0; i--)
                {
                    double sum = X[i, c];
                    for (int k = i + 1; k < n; k++)
                    {
                        sum -= mL[k, i] * X[k, c];
                    }
                    X[i, c] = sum / mL[i, i];
                }
            }

            return(X);
        }
Пример #11
0
        public void Dsymv(Boolean isUpperTriangular, double alpha, DoubleMatrix2D A, DoubleMatrix1D x, double beta, DoubleMatrix1D y)
        {
            if (isUpperTriangular)
            {
                A = A.ViewDice();
            }
            Property.DEFAULT.CheckSquare(A);
            int size = A.Rows;

            if (size != x.Size || size != y.Size)
            {
                throw new ArgumentException(A.ToStringShort() + ", " + x.ToStringShort() + ", " + y.ToStringShort());
            }
            DoubleMatrix1D tmp = x.Like();

            for (int i = 0; i < size; i++)
            {
                double sum = 0;
                for (int j = 0; j <= i; j++)
                {
                    sum += A[i, j] * x[j];
                }
                for (int j = i + 1; j < size; j++)
                {
                    sum += A[j, i] * x[j];
                }
                tmp[i] = alpha * sum + beta * y[i];
            }
            y.Assign(tmp);
        }
Пример #12
0
        /// <summary>
        /// Returns whether all cells of the given matrix <i>A</i> are equal to the given value.
        /// </summary>
        /// <param name="a">
        /// The first matrix to compare.
        /// </param>
        /// <param name="value">
        /// The value to compare against.
        /// </param>
        /// <returns>
        /// <i>true</i> if the matrix is equal to the value;
        /// <i>false</i> otherwise.
        /// </returns>
        public bool Equals(DoubleMatrix2D a, double value)
        {
            if (a == null)
            {
                return(false);
            }
            int rows    = a.Rows;
            int columns = a.Columns;

            double epsilon = Tolerance;

            for (int row = rows; --row >= 0;)
            {
                for (int column = columns; --column >= 0;)
                {
                    double x    = a[row, column];
                    double diff = System.Math.Abs(value - x);
                    if ((Double.IsNaN(diff)) && ((Double.IsNaN(value) && Double.IsNaN(x)) || value == x))
                    {
                        diff = 0;
                    }
                    if (!(diff <= epsilon))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Пример #13
0
        /// <summary>
        /// A matrix <i>A</i> is an <i>identity</i> matrix if <i>A[i,i] == 1</i> and all other cells are zero.
        /// Matrix may but need not be square.
        /// <summary>
        public Boolean IsIdentity(DoubleMatrix2D A)
        {
            double epsilon = Tolerance;
            int    rows    = A.Rows;
            int    columns = A.Columns;

            for (int row = rows; --row >= 0;)
            {
                for (int column = columns; --column >= 0;)
                {
                    double v = A[row, column];
                    if (row == column)
                    {
                        if (!(System.Math.Abs(1 - v) < epsilon))
                        {
                            return(false);
                        }
                    }
                    else if (!(System.Math.Abs(v) <= epsilon))
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Пример #14
0
 /// <summary>
 /// Checks whether the given matrix <i>A</i> is <i>rectangular</i>.
 /// </summary>
 /// <param name="a">
 /// The matrix.
 /// </param>
 /// <exception cref="ArgumentOutOfRangeException">
 /// If <i>A.Rows &lt; A.Columns</i>.
 /// </exception>
 public void CheckRectangular(DoubleMatrix2D a)
 {
     if (a.Rows < a.Columns)
     {
         throw new ArgumentOutOfRangeException(String.Format(Cern.LocalizedResources.Instance().Exception_MatrixMustBeRectangular, AbstractFormatter.Shape(a)));
     }
 }
Пример #15
0
        /// <summary>
        /// Constructs and returns the covariance matrix of the given matrix.
        /// The covariance matrix is a square, symmetric matrix consisting of nothing but covariance coefficientsd
        /// The rows and the columns represent the variables, the cells represent covariance coefficientsd
        /// The diagonal cells (i.ed the covariance between a variable and itself) will equal the variances.
        /// The covariance of two column vectors x and y is given by <i>cov(x,y) = (1/n) * Sum((x[i]-mean(x)) * (y[i]-mean(y)))</i>.
        /// See the <A HREF="http://www.cquest.utoronto.ca/geog/ggr270y/notes/not05efg.html"> math definition</A>.
        /// Compares two column vectors at a timed Use dice views to compare two row vectors at a time.
        /// </summary>
        /// <param name="matrix">any matrix; a column holds the values of a given variable.</param>
        /// <returns>the covariance matrix (<i>n x n, n=matrix.Columns</i>).</returns>
        public static DoubleMatrix2D Covariance(DoubleMatrix2D matrix)
        {
            int            rows       = matrix.Rows;
            int            columns    = matrix.Columns;
            DoubleMatrix2D covariance = new DenseDoubleMatrix2D(columns, columns);

            double[]         sums = new double[columns];
            DoubleMatrix1D[] cols = new DoubleMatrix1D[columns];
            for (int i = columns; --i >= 0;)
            {
                cols[i] = matrix.ViewColumn(i);
                sums[i] = cols[i].ZSum();
            }

            for (int i = columns; --i >= 0;)
            {
                for (int j = i + 1; --j >= 0;)
                {
                    double sumOfProducts = cols[i].ZDotProduct(cols[j]);
                    double cov           = (sumOfProducts - sums[i] * sums[j] / rows) / rows;
                    covariance[i, j] = cov;
                    covariance[j, i] = cov; // symmetric
                }
            }
            return(covariance);
        }
Пример #16
0
        /// <summary>
        /// Same as <see cref="Cern.Colt.Partitioning.Partition(int[], int, int, int[], int, int, int[])"/>
        /// except that it <i>synchronously</i> partitions the rows of the given matrix by the values of the given matrix column;
        /// This is essentially the same as partitioning a list of composite objects by some instance variable;
        /// In other words, two entire rows of the matrix are swapped, whenever two column values indicate so.
        /// <p>
        /// Let's say, a "row" is an "object" (tuple, d-dimensional point).
        /// A "column" is the list of "object" values of a given variable (field, dimension).
        /// A "matrix" is a list of "objects" (tuples, points).
        /// <p>
        /// Now, rows (objects, tuples) are partially sorted according to their values in one given variable (dimension).
        /// Two entire rows of the matrix are swapped, whenever two column values indicate so.
        /// <p>
        /// Note that arguments are not checked for validity.
        /// </summary>
        /// <param name="matrix">
        /// the matrix to be partitioned.
        /// </param>
        /// <param name="column">
        /// the index of the column to partition on.
        /// </param>
        /// <param name="splitters">
        /// the values at which the rows shall be split into intervals.
        ///             Must be sorted ascending and must not contain multiple identical values.
        ///             These preconditions are not checked; be sure that they are met.
        /// </param>
        /// <param name="splitIndexes">
        /// a list into which this method fills the indexes of rows delimiting intervals.
        /// Therefore, must satisfy <i>splitIndexes.Length >= splitters.Length</i>.
        /// </param>
        /// <returns>a new matrix view having rows partitioned by the given column and splitters.</returns>
        /// <example>
        /// <table border="1" cellspacing="0">
        ///           <tr nowrap>
        ///             <td valign="top"><i>8 x 3 matrix:<br>
        ///               23, 22, 21<br>
        ///               20, 19, 18<br>
        ///               17, 16, 15<br>
        ///               14, 13, 12<br>
        ///               11, 10, 9<br>
        ///               8,  7,  6<br>
        ///               5,  4,  3<br>
        ///               2,  1,  0 </i></td>
        ///             <td align="left" valign="top">
        ///                 <i>column = 0;<br>
        ///                 splitters = {5,10,12}<br>
        ///                 partition(matrix,column,splitters,splitIndexes);<br>
        ///                 ==><br>
        ///                 splitIndexes == {0, 2, 3}</i></p>
        ///               </td>
        ///             <td valign="top">
        ///               The matrix IS NOT REORDERED.<br>
        ///               The new VIEW IS REORDERED:<br>
        ///               <i>8 x 3 matrix:<br>
        ///               2,  1,  0<br>
        ///               5,  4,  3<br>
        ///               8,  7,  6<br>
        ///               11, 10, 9<br>
        ///               23, 22, 21<br>
        ///               20, 19, 18<br>
        ///               17, 16, 15<br>
        ///               14, 13, 12 </i></td>
        ///           </tr>
        /// </table>
        /// </example>
        public static DoubleMatrix2D Partition(DoubleMatrix2D matrix, int column, double[] splitters, int[] splitIndexes)
        {
            int rowFrom   = 0;
            int rowTo     = matrix.Rows - 1;
            int splitFrom = 0;
            int splitTo   = splitters.Length - 1;

            int[] rowIndexes = new int[matrix.Rows]; // row indexes to reorder instead of matrix itself
            for (int i = rowIndexes.Length; --i >= 0;)
            {
                rowIndexes[i] = i;
            }

            Partition(matrix, rowIndexes, rowFrom, rowTo, column, splitters, splitFrom, splitTo, splitIndexes);

            // take all columns in the original order
            int[] columnIndexes = new int[matrix.Columns];
            for (int i = columnIndexes.Length; --i >= 0;)
            {
                columnIndexes[i] = i;
            }

            // view the matrix according to the reordered row indexes
            return(matrix.ViewSelection(rowIndexes, columnIndexes));
        }
Пример #17
0
        /// <summary>
        ///         Returns the<i>semi-bandwidth</i> of the given square matrix <i>A</i>.
        ///         A<i> banded</i> matrix has a "band" about the diagonal.
        ///         It is a matrix with all cells equal to zero,
        ///         with the possible exception of the cells along the diagonal line,
        ///         the<i> k</i> diagonal lines above the diagonal, and the <i>k</i> diagonal lines below the diagonal.
        /// The<i> semi-bandwith l</i> is the number <i>k+1</i>.
        /// The<i> bandwidth p</i> is the number <i>2*k + 1</i>.
        /// For example, a tridiagonal matrix corresponds to<i> k = 1, l= 2, p= 3 </ i >,
        ///         a diagonal or zero matrix corresponds to<i> k = 0, l= 1, p= 1 </ i >,
        ///         <p>
        /// The<i> upper bandwidth</i> is the maximum <i>j-i</i> for which<i> A[i, j]</i> is nonzero and <i>j &gt; i</i>.
        ///  The<i> lower bandwidth</i> is the maximum<i>i-j</i> for which<i> A[i, j]</i> is nonzero and <i>i &gt; j</i> d
        /// Diagonal, tridiagonal and triangular matrices are special cases.
        /// <p>
        /// Examples:
        /// <table border = "1" cellspacing="0">
        ///           <tr align = "left" valign="top">
        ///             <td valign = "middle" align="left"><i>matrix</i></td>
        ///             <td> <i>4&nbsp;x&nbsp;4&nbsp;<br>
        ///               0&nbsp;0&nbsp;0&nbsp;0<br>
        ///               0&nbsp;0&nbsp;0&nbsp;0<br>
        ///               0&nbsp;0&nbsp;0&nbsp;0<br>
        ///               0&nbsp;0&nbsp;0&nbsp;0 </i></td>
        ///             <td><i>4&nbsp;x&nbsp;4<br>
        ///               1&nbsp;0&nbsp;0&nbsp;0<br>
        ///               0&nbsp;0&nbsp;0&nbsp;0<br>
        ///               0&nbsp;0&nbsp;0&nbsp;0<br>
        ///               0&nbsp;0&nbsp;0&nbsp;1 </i></td>
        ///             <td><i>4&nbsp;x&nbsp;4<br>
        ///               1&nbsp;1&nbsp;0&nbsp;0<br>
        ///               1&nbsp;1&nbsp;1&nbsp;0<br>
        ///               0&nbsp;1&nbsp;1&nbsp;1<br>
        ///               0&nbsp;0&nbsp;1&nbsp;1 </i></td>
        ///             <td><i> 4&nbsp;x&nbsp;4<br>
        ///               0&nbsp;1&nbsp;1&nbsp;1<br>
        ///               0&nbsp;1&nbsp;1&nbsp;1<br>
        ///               0&nbsp;0&nbsp;0&nbsp;1<br>
        ///               0&nbsp;0&nbsp;0&nbsp;1 </i></td>
        ///             <td><i> 4&nbsp;x&nbsp;4<br>
        ///               0&nbsp;0&nbsp;0&nbsp;0<br>
        ///               1&nbsp;1&nbsp;0&nbsp;0<br>
        ///               1&nbsp;1&nbsp;0&nbsp;0<br>
        ///               1&nbsp;1&nbsp;1&nbsp;1 </i></td>
        ///             <td><i>4&nbsp;x&nbsp;4<br>
        ///               1&nbsp;1&nbsp;0&nbsp;0<br>
        ///               0&nbsp;1&nbsp;1&nbsp;0<br>
        ///               0&nbsp;1&nbsp;0&nbsp;1<br>
        ///               1&nbsp;0&nbsp;1&nbsp;1 </i><i> </i> </td>
        ///             <td><i>4&nbsp;x&nbsp;4<br>
        ///               1&nbsp;1&nbsp;1&nbsp;0<br>
        ///               0&nbsp;1&nbsp;0&nbsp;0<br>
        ///               1&nbsp;1&nbsp;0&nbsp;1<br>
        ///               0&nbsp;0&nbsp;1&nbsp;1 </i> </td>
        ///           </tr>
        ///           <tr align = "center" valign="middle">
        ///             <td><i>upperBandwidth</i></td>
        ///             <td>
        ///               <div align = "center" >< i > 0 </ i ></ div >
        ///             </ td >
        ///             < td >
        ///               < div align="center"><i>0</i></div>
        ///             </td>
        ///             <td>
        ///               <div align = "center" >< i > 1 </ i ></ div >
        ///             </ td >
        ///             < td >< i > 3 </ i ></ td >
        ///             < td align="center" valign="middle"><i>0</i></td>
        ///             <td align = "center" valign="middle">
        ///               <div align = "center" >< i > 1 </ i ></ div >
        ///             </ td >
        ///             < td align="center" valign="middle">
        ///               <div align = "center" >< i > 2 </ i ></ div >
        ///             </ td >
        ///           </ tr >
        ///           < tr align="center" valign="middle">
        ///             <td><i>lowerBandwidth</i></td>
        ///             <td>
        ///               <div align = "center" >< i > 0 </ i ></ div >
        ///             </ td >
        ///             < td >
        ///               < div align="center"><i>0</i></div>
        ///             </td>
        ///             <td>
        ///               <div align = "center" >< i > 1 </ i ></ div >
        ///             </ td >
        ///             < td >< i > 0 </ i ></ td >
        ///             < td align="center" valign="middle"><i>3</i></td>
        ///             <td align = "center" valign="middle">
        ///               <div align = "center" >< i > 3 </ i ></ div >
        ///             </ td >
        ///             < td align="center" valign="middle">
        ///               <div align = "center" >< i > 2 </ i ></ div >
        ///             </ td >
        ///           </ tr >
        ///           < tr align="center" valign="middle">
        ///             <td><i>semiBandwidth</i></td>
        ///             <td>
        ///               <div align = "center" >< i > 1 </ i ></ div >
        ///             </ td >
        ///             < td >
        ///               < div align="center"><i>1</i></div>
        ///             </td>
        ///             <td>
        ///               <div align = "center" >< i > 2 </ i ></ div >
        ///             </ td >
        ///             < td >< i > 4 </ i ></ td >
        ///             < td align="center" valign="middle"><i>4</i></td>
        ///             <td align = "center" valign="middle">
        ///               <div align = "center" >< i > 4 </ i ></ div >
        ///             </ td >
        ///             < td align="center" valign="middle">
        ///               <div align = "center" >< i > 3 </ i ></ div >
        ///             </ td >
        ///           </ tr >
        ///           < tr align="center" valign="middle">
        ///             <td><i>description</i></td>
        ///             <td>
        ///               <div align = "center" >< i > zero </ i ></ div >
        ///             </ td >
        ///             < td >
        ///               < div align="center"><i>diagonal</i></div>
        ///             </td>
        ///             <td>
        ///               <div align = "center" >< i > tridiagonal </ i ></ div >
        ///             </ td >
        ///             < td >< i > upper triangular</i></td>
        ///             <td align = "center" valign="middle"><i>lower triangular</i></td>
        ///             <td align = "center" valign= "middle" >
        ///                 < div align= "center" >< i > unstructured </ i ></ div >
        ///               </ td >
        ///               < td align= "center" valign= "middle" >
        ///                 < div align= "center" >< i > unstructured </ i ></ div >
        ///               </ td >
        ///             </ tr >
        ///   </ table >
        /// <summary>
        ///<param name= "A" > the square matrix to analyze.</param>
        ///<returns>the semi-bandwith<i> l</i>.</returns>
        ///<exception cref = "ArgumentException" >if <i>!isSquare(A)</i>. </exception>
        ///<see cref = "#lowerBandwidth(DoubleMatrix2D)" ></see>
        ///<see cref= "#upperBandwidth(DoubleMatrix2D)" ></see>
        public int SemiBandwidth(DoubleMatrix2D A)
        {
            CheckSquare(A);
            double epsilon = Tolerance;
            int    rows    = A.Rows;

            for (int k = rows; --k >= 0;)
            {
                for (int i = rows - k; --i >= 0;)
                {
                    int j = i + k;
                    //if (A.getQuick(j,i) != 0) return k+1;
                    //if (A.getQuick(i,j) != 0) return k+1;
                    if (!(System.Math.Abs(A[j, i]) <= epsilon))
                    {
                        return(k + 1);
                    }
                    if (!(System.Math.Abs(A[i, j]) <= epsilon))
                    {
                        return(k + 1);
                    }
                }
            }
            return(1);
        }
Пример #18
0
        /// <summary>
        /// Sorts the matrix rows into ascending order, according to the <i>natural ordering</i> of the matrix values in the given column.
        /// </summary>
        /// <param name="matrix">
        /// The matrix to be sorted.
        /// </param>
        /// <param name="column">
        /// The index of the column inducing the order.
        /// </param>
        /// <returns>
        /// A new matrix view having rows sorted by the given column.
        /// </returns>
        /// <exception cref="IndexOutOfRangeException">
        /// If <i>column &lt; 0 || column &gt;= matrix.columns()</i>.
        /// </exception>
        public DoubleMatrix2D Sort(DoubleMatrix2D matrix, int column)
        {
            if (column < 0 || column >= matrix.Columns)
            {
                throw new IndexOutOfRangeException("column=" + column + ", matrix=" + AbstractFormatter.Shape(matrix));
            }

            var rowIndexes = new int[matrix.Rows]; // row indexes to reorder instead of matrix itself

            for (int i = rowIndexes.Length; --i >= 0;)
            {
                rowIndexes[i] = i;
            }

            DoubleMatrix1D col = matrix.ViewColumn(column);

            RunSort(
                rowIndexes,
                0,
                rowIndexes.Length,
                (a, b) =>
            {
                double av = col[a];
                double bv = col[b];
                if (Double.IsNaN(av) || Double.IsNaN(bv))
                {
                    return(CompareNaN(av, bv));                                          // swap NaNs to the end
                }
                return(av < bv ? -1 : (av == bv ? 0 : 1));
            });

            // view the matrix according to the reordered row indexes
            // take all columns in the original order
            return(matrix.ViewSelection(rowIndexes, null));
        }
        /// <summary>
        /// Replaces all cell values of the receiver with the values of another matrix.
        /// Both matrices must have the same number of rows and columns.
        /// If both matrices share the same cells (as is the case if they are views derived from the same matrix) and intersect in an ambiguous way, then replaces <i>as if</i> using an intermediate auxiliary deep copy of <i>other</i>.
        /// </summary>
        /// <param name="source">the source matrix to copy from (may be identical to the receiver).</param>
        /// <returns><i>this</i> (for convenience only).</returns>
        /// <exception cref="ArgumentException">if <i>columns() != source.columns() || rows() != source.rows()</i></exception>
        public override DoubleMatrix2D Assign(DoubleMatrix2D source)
        {
            // overriden for performance only
            if (source == this)
            {
                return(this);                // nothing to do
            }
            CheckShape(source);

            if (source is TridiagonalDoubleMatrix2D)
            {
                // quickest
                TridiagonalDoubleMatrix2D other = (TridiagonalDoubleMatrix2D)source;

                Array.Copy(other.Values, 0, this.Values, 0, this.Values.Length);
                Array.Copy(other.dims, 0, this.dims, 0, this.dims.Length);
                return(this);
            }

            if (source is RCDoubleMatrix2D || source is SparseDoubleMatrix2D)
            {
                Assign(0);
                source.ForEachNonZero(
                    new Cern.Colt.Function.IntIntDoubleFunction((i, j, value) =>
                {
                    this[i, j] = value;
                    return(value);
                }
                                                                ));
                return(this);
            }

            return(base.Assign(source));
        }
Пример #20
0
        public static DoubleMatrix2D Solve(DoubleMatrix2D A, DoubleMatrix2D B)
        {
            LUDecomposition lu = new LUDecomposition(A);
            QRDecomposition qr = new QRDecomposition(B);

            return(A.Rows == A.Columns ? (lu.Solve(B)) : (qr.Solve(B)));
        }
Пример #21
0
 /// <summary>
 /// Checks whether the given matrix <i>A</i> is <i>rectangular</i>.
 /// </summary>
 /// <param name="a">
 /// The matrix.
 /// </param>
 /// <exception cref="ArgumentOutOfRangeException">
 /// If <i>A.Rows &lt; A.Columns</i>.
 /// </exception>
 public void CheckRectangular(DoubleMatrix2D a)
 {
     if (a.Rows < a.Columns)
     {
         throw new ArgumentOutOfRangeException("Matrix must be rectangular: " + AbstractFormatter.Shape(a));
     }
 }
        /// <summary>
        /// Update the SVD with the addition of a new column.
        /// </summary>
        /// <param name="c">
        /// The new column.
        /// </param>
        /// <param name="wantV">
        /// Whether the matrix V is needed.
        /// </param>
        public void Update(DoubleMatrix1D c, bool wantV)
        {
            int nRows = c.Size - _m;

            if (nRows > 0)
            {
                _u = DoubleFactory2D.Dense.AppendRows(_u, new SparseDoubleMatrix2D(nRows, _n));
                _m = c.Size;
            }
            else if (nRows < 0)
            {
                c = DoubleFactory1D.Sparse.AppendColumns(c, DoubleFactory1D.Sparse.Make(-nRows));
            }

            var d = DoubleFactory2D.Dense.Make(c.ToArray(), c.Size);

            // l = U'd is the eigencoding of d
            var l = _u.ViewDice().ZMult(d, null);

            ////var uu = _u.ZMult(_u.ViewDice(), null);

            // Ul = UU'd
            ////var ul = uu.ZMult(d, null);
            var ul = _u.ZMult(l, null);

            // h = d - UU'd = d - Ul is the component of d orthogonal to the subspace spanned by U
            ////var h = d.Copy().Assign(uu.ZMult(d, null), BinaryFunctions.Minus);
            ////var h = d.Copy().Assign(ul, BinaryFunctions.Minus);

            // k is the projection of d onto the subspace othogonal to U
            var k = Math.Sqrt(d.Aggregate(BinaryFunctions.Plus, a => a * a) - (2 * l.Aggregate(BinaryFunctions.Plus, a => a * a)) + ul.Aggregate(BinaryFunctions.Plus, a => a * a));

            // truncation
            if (k == 0 || double.IsNaN(k))
            {
                return;
            }

            _n++;

            // j = d - UU'd = d - Ul is an orthogonal basis for the component of d orthogonal to the subspace spanned by U
            ////var j = h.Assign(UnaryFunctions.Div(k));
            var j = d.Assign(ul, BinaryFunctions.Minus).Assign(UnaryFunctions.Div(k));

            // Q = [ S, l; 0, ||h||]
            var q =
                DoubleFactory2D.Sparse.Compose(
                    new[] { new[] { S, l }, new[] { null, DoubleFactory2D.Dense.Make(1, 1, k) } });

            var svdq = new SingularValueDecomposition(q, true, wantV, true);

            _u = DoubleFactory2D.Dense.AppendColumns(_u, j).ZMult(svdq.U, null);
            _s = svdq.SingularValues;
            if (wantV)
            {
                _v = DoubleFactory2D.Dense.ComposeDiagonal(_v, DoubleFactory2D.Dense.Identity(1)).ZMult(
                    svdq.V, null);
            }
        }
Пример #23
0
 public void Assign(DoubleMatrix2D x, DoubleMatrix2D y, DoubleDoubleFunction function)
 {
     run(x, y, false, new Matrix2DMatrix2DFunction((AA, BB) =>
     {
         seqBlas.Assign(AA, BB, function);
         return(0);
     }));
 }
Пример #24
0
 /// <summary>
 /// Assigns the result of a function to each cell; <tt>x[row,col] = function(x[row,col],y[row,col])</tt>.
 /// </summary>
 /// <param name="y">
 /// The secondary matrix to operate on.
 /// </param>
 /// <param name="function">
 /// The function taking as first argument the current cell's value of <tt>this</tt>,
 /// and as second argument the current cell's value of <tt>y</tt>.
 /// </param>
 /// <returns>
 /// <tt>this</tt> (for convenience only).
 /// </returns>
 /// <exception cref="ArgumentException">
 /// If <tt>columns() != other.columns() || rows() != other.rows()</tt>
 /// </exception>
 public override DoubleMatrix2D Assign(DoubleMatrix2D y, DoubleDoubleFunction function)
 {
     if (!IsView)
     {
         CheckShape(y);
     }
     return(base.Assign(y, function));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SingularValueDecomposition"/> class from a previous decomposition.
 /// </summary>
 /// <param name="u">
 /// The matrix U.
 /// </param>
 /// <param name="s">
 /// The vector of singular values.
 /// </param>
 /// <param name="v">
 /// The matrix V. Can be <code>null</code>.
 /// </param>
 public SingularValueDecomposition(DoubleMatrix2D u, double[] s, DoubleMatrix2D v)
 {
     _u = u;
     _s = s;
     _v = v;
     _m = u.Rows;
     _n = s.Length;
 }
Пример #26
0
 /// <summary>
 /// Returns the Frobenius norm of matrix <i>A</i>, which is <i>Sqrt(Sum(A[i,j]<sup>2</sup>))</i>.
 /// </summary>
 /// <param name="A"></param>
 /// <returns></returns>
 public static double NormF(DoubleMatrix2D A)
 {
     if (A.Size == 0)
     {
         return(0);
     }
     return(A.Aggregate(HypotFunction(), Cern.Jet.Math.Functions.DoubleFunctions.Identity));
 }
 public WrapperDoubleMatrix2D(DoubleMatrix2D newContent)
 {
     if (newContent != null)
     {
         Setup(newContent.Rows, newContent.Columns);
     }
     this._content = newContent;
 }
Пример #28
0
 public void Dswap(DoubleMatrix2D A, DoubleMatrix2D B)
 {
     //B.Swap(A); not yet implemented
     A.CheckShape(B);
     for (int i = A.Rows; --i >= 0;)
     {
         A.ViewRow(i).Swap(B.ViewRow(i));
     }
 }
Пример #29
0
 public void Dger(double alpha, DoubleMatrix1D x, DoubleMatrix1D y, DoubleMatrix2D A)
 {
     Cern.Jet.Math.PlusMult fun = new Cern.Jet.Math.PlusMult(0);
     for (int i = A.Rows; --i >= 0;)
     {
         fun.Multiplicator = alpha * x[i];
         A.ViewRow(i).Assign(y, fun);
     }
 }
 public DelegateDoubleMatrix1D(DoubleMatrix2D newContent, int row) : base(null)
 {
     if (row < 0 || row >= newContent.Rows)
     {
         throw new ArgumentException();
     }
     Setup(newContent.Columns);
     this.row       = row;
     this.content2D = newContent;
 }
Пример #31
0
        /// <summary>
        /// Returns a string representations of all cells; no alignment considered.
        /// </summary>
        /// <param name="matrix">
        /// The matrix.
        /// </param>
        /// <returns>
        /// A string representation of all cells.
        /// </returns>
        public string[][] Format(DoubleMatrix2D matrix)
        {
            var strings = new string[matrix.Rows][];

            for (int row = matrix.Rows; --row >= 0;)
            {
                strings[row] = FormatRow(matrix.ViewRow(row));
            }
            return(strings);
        }
        public void assignLabels( LingoProcessingContext context, DoubleMatrix2D stemCos, IntIntOpenHashMap filteredRowToStemIndex, DoubleMatrix2D phraseCos )
        {
            PreprocessingContext preprocessingContext = context.preprocessingContext;
            int firstPhraseIndex = preprocessingContext.allLabels.firstPhraseIndex;
            int [] labelsFeatureIndex = preprocessingContext.allLabels.featureIndex;
            int [] mostFrequentOriginalWordIndex = preprocessingContext.allStems.mostFrequentOriginalWordIndex;
            int desiredClusterCount = stemCos.columns();

            IntArrayList clusterLabelFeatureIndex = new IntArrayList(
                desiredClusterCount);
            DoubleArrayList clusterLabelScore = new DoubleArrayList(desiredClusterCount);
            for (int label = 0; label < desiredClusterCount; label++)
            {
                Pair<int, int> stemMax = max(stemCos);
                Pair<int, int> phraseMax = max(phraseCos);

                if (stemMax == null && phraseMax == null)
                {
                    break;
                }

                double stemScore = stemMax != null ? stemCos.getQuick(stemMax.objectA,
                    stemMax.objectB) : -1;
                double phraseScore = phraseMax != null ? phraseCos.getQuick(
                    phraseMax.objectA, phraseMax.objectB) : -1;

                if (phraseScore > stemScore)
                {
                    phraseCos.viewRow(phraseMax.objectA).assign(0);
                    phraseCos.viewColumn(phraseMax.objectB).assign(0);
                    stemCos.viewColumn(phraseMax.objectB).assign(0);

                    clusterLabelFeatureIndex.add(labelsFeatureIndex[phraseMax.objectA
                        + firstPhraseIndex]);
                    clusterLabelScore.add(phraseScore);
                }
                else
                {
                    stemCos.viewRow(stemMax.objectA).assign(0);
                    stemCos.viewColumn(stemMax.objectB).assign(0);
                    if (phraseCos != null)
                    {
                        phraseCos.viewColumn(stemMax.objectB).assign(0);
                    }

                    clusterLabelFeatureIndex
                        .add(mostFrequentOriginalWordIndex[filteredRowToStemIndex
                            .get(stemMax.objectA)]);
                    clusterLabelScore.add(stemScore);
                }
            }

            context.clusterLabelFeatureIndex = clusterLabelFeatureIndex.toArray();
            context.clusterLabelScore = clusterLabelScore.toArray();
        }
        public void assignLabels( LingoProcessingContext context, DoubleMatrix2D stemCos, IntIntOpenHashMap filteredRowToStemIndex, DoubleMatrix2D phraseCos )
        {
            PreprocessingContext preprocessingContext = context.preprocessingContext;
            int firstPhraseIndex = preprocessingContext.allLabels.firstPhraseIndex;
            int[] labelsFeatureIndex = preprocessingContext.allLabels.featureIndex;
            int[] mostFrequentOriginalWordIndex = preprocessingContext.allStems.mostFrequentOriginalWordIndex;
            int desiredClusterCount = stemCos.columns();
            int[] candidateStemIndices = new int[desiredClusterCount];
            double[] candidateStemScores = new double[desiredClusterCount];

            int[] candidatePhraseIndices = new int[desiredClusterCount];
            for ( int i = 0; i < desiredClusterCount; i++ )
            {
                candidatePhraseIndices[i] = -1;
            }
            double[] candidatePhraseScores = new double[desiredClusterCount];
            MatrixUtils.maxInColumns( stemCos, candidateStemIndices, candidateStemScores,
                Functions.ABS );
            if ( phraseCos != null )
            {
                MatrixUtils.maxInColumns( phraseCos, candidatePhraseIndices,
                    candidatePhraseScores, Functions.ABS );
            }
            int[] clusterLabelFeatureIndex = new int[desiredClusterCount];
            double [] clusterLabelScore = new double [desiredClusterCount];
            for (int i = 0; i < desiredClusterCount; i++)
            {
                int phraseFeatureIndex = candidatePhraseIndices[i];
                int stemIndex = filteredRowToStemIndex.get(candidateStemIndices[i]);

                double phraseScore = candidatePhraseScores[i];
                if (phraseFeatureIndex >= 0 && phraseScore > candidateStemScores[i])
                {
                    clusterLabelFeatureIndex[i] = labelsFeatureIndex[phraseFeatureIndex
                        + firstPhraseIndex];
                    clusterLabelScore[i] = phraseScore;
                }
                else
                {
                    clusterLabelFeatureIndex[i] = mostFrequentOriginalWordIndex[stemIndex];
                    clusterLabelScore[i] = candidateStemScores[i];
                }
            }
            context.clusterLabelFeatureIndex = clusterLabelFeatureIndex;
            context.clusterLabelScore = clusterLabelScore;
        }