/// <summary> /// /// Fills all cell values of the given vector into a bin from which statistics measures can be retrieved efficiently. /// Cells values are copied. /// </summary> /// <param name="vector">the vector to analyze.</param> /// <returns>a bin holding the statistics measures of the vector.</returns> /// <example> /// Tip: Use <i>Console.WriteLine(bin(vector))</i> to print most measures computed by the bind Example: /// <table> /// <td class="PRE"> /// <pre> /// Size: 20000 /// Sum: 299858.02350278624 /// SumOfSquares: 5399184.154095971 /// Min: 0.8639113139711261 /// Max: 59.75331890541892 /// Mean: 14.992901175139313 /// RMS: 16.43043540825375 /// Variance: 45.17438077634358 /// Standard deviation: 6.721188940681818 /// Standard error: 0.04752598277592142 /// Geometric mean: 13.516615397064466 /// Product: Infinity /// Harmonic mean: 11.995174297952191 /// Sum of inversions: 1667.337172700724 /// Skew: 0.8922838940067878 /// Kurtosis: 1.1915828121825598 /// Sum of powers(3): 1.1345828465808412E8 /// Sum of powers(4): 2.7251055344494686E9 /// Sum of powers(5): 7.367125643433887E10 /// Sum of powers(6): 2.215370909100143E12 /// Moment(0,0): 1.0 /// Moment(1,0): 14.992901175139313 /// Moment(2,0): 269.95920770479853 /// Moment(3,0): 5672.914232904206 /// Moment(4,0): 136255.27672247344 /// Moment(5,0): 3683562.8217169433 /// Moment(6,0): 1.1076854545500715E8 /// Moment(0,mean()): 1.0 /// Moment(1,mean()): -2.0806734113421045E-14 /// Moment(2,mean()): 45.172122057305664 /// Moment(3,mean()): 270.92018671421 /// Moment(4,mean()): 8553.8664869067 /// Moment(5,mean()): 153357.41712233616 /// Moment(6,mean()): 4273757.570142922 /// 25%, 50% and 75% Quantiles: 10.030074811938091, 13.977982089912224, /// 18.86124362967137 /// quantileInverse(mean): 0.559163335012079 /// Distinct elements & frequencies not printed (too many). /// </pre> /// </td> /// </table> /// </example> public static DynamicBin1D Bin(DoubleMatrix1D vector) { DynamicBin1D bin = new DynamicBin1D(); bin.AddAllOf(new DoubleArrayList(DoubleFactory1D.Dense.ToList(vector).ToArray())); return(bin); }
/// <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 < 0 || column >= 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> /// Sorts the vector into ascending order, according to the <i>natural ordering</i>. /// </summary> /// <param name="vector"> /// The vector to be sorted. /// </param> /// <returns> /// A new sorted vector (matrix) viewd /// </returns> public DoubleMatrix1D Sort(DoubleMatrix1D vector) { var indexes = new int[vector.Size]; // row indexes to reorder instead of matrix itself for (int i = indexes.Length; --i >= 0;) { indexes[i] = i; } RunSort( indexes, 0, indexes.Length, (a, b) => { double av = vector[a]; double bv = vector[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)); }); return(vector.ViewSelection(indexes)); }
/// <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); }
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); }
public void TestViewColumn() { var a = DoubleFactory2D.Dense.Ascending(5, 4); DoubleMatrix1D d = a.ViewColumn(0); Assert.AreEqual(5, d.Size); Assert.AreEqual(1, d[0]); Assert.AreEqual(5, d[1]); Assert.AreEqual(9, d[2]); Assert.AreEqual(13, d[3]); Assert.AreEqual(17, d[4]); var b = new DenseDoubleMatrix2D(new[] { new[] { 1d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d }, new[] { 1d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d }, new[] { 1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d }, new[] { 0d, 1d, 1d, 0d, 1d, 0d, 0d, 0d, 0d }, new[] { 0d, 1d, 1d, 2d, 0d, 0d, 0d, 0d, 0d }, new[] { 0d, 1d, 0d, 0d, 1d, 0d, 0d, 0d, 0d }, new[] { 0d, 1d, 0d, 0d, 1d, 0d, 0d, 0d, 0d }, new[] { 0d, 0d, 1d, 1d, 0d, 0d, 0d, 0d, 0d }, new[] { 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 1d }, new[] { 0d, 0d, 0d, 0d, 0d, 1d, 1d, 1d, 0d }, new[] { 0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 1d }, new[] { 0d, 0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d }, }); d = b.ViewColumn(0); Assert.AreEqual(1, d[0]); Assert.AreEqual(1, d[1]); Assert.AreEqual(1, d[2]); Assert.AreEqual(0, d[3]); }
/// <summary> /// /// </summary> /// <param name="A"></param> /// <param name="indexes"></param> /// <param name="work"></param> /// <returns></returns> public static DoubleMatrix1D Permute(DoubleMatrix1D A, int[] indexes, double[] work) { // check validity int size = A.Size; if (indexes.Length != size) { throw new IndexOutOfRangeException("invalid permutation"); } /* * int i=size; * int a; * while (--i >= 0 && (a=indexes[i])==i) if (a < 0 || a >= size) throw new IndexOutOfRangeException("invalid permutation"); * if (i<0) return; // nothing to permute */ if (work == null || size > work.Length) { work = A.ToArray(); } else { A.ToArray(ref work); } for (int i = size; --i >= 0;) { A[i] = work[indexes[i]]; } return(A); }
/// <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)); }
/// <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); }
/// <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); }
/// <summary> /// Assigns the result of a function to each cell; <tt>x[i] = function(x[i],y[i])</tt>. /// (Iterates downwards from <tt>[size()-1]</tt> to <tt>[0]</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="ArgumentOutOfRangeException"> /// If <tt>size() != y.size()</tt>. /// </exception> public override DoubleMatrix1D Assign(DoubleMatrix1D y, DoubleDoubleFunction function) { // overriden for performance only if (!(y is DenseDoubleMatrix1D)) { return(base.Assign(y, function)); } var other = (DenseDoubleMatrix1D)y; CheckSize(y); double[] elems = Elements; double[] otherElems = other.Elements; if (elems == null || otherElems == null) { throw new ApplicationException(); } int s = Stride; int ys = other.Stride; int index = this.Index(0); int otherIndex = other.Index(0); // specialized for speed for (int k = Size; --k >= 0;) { elems[index] = function(elems[index], otherElems[otherIndex]); index += s; otherIndex += ys; } return(this); }
/// <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); } }
public WrapperDoubleMatrix1D(DoubleMatrix1D newContent) { if (newContent != null) { Setup(newContent.Count()); } this.Content = newContent; }
/// <summary> /// Fills all cells of the given vector into the given histogram. /// </summary> /// <param name="histo"></param> /// <param name="vector"></param> /// <returns><i>histo</i> (for convenience only).</returns> public static Hep.Aida.IHistogram1D Histogram(Hep.Aida.IHistogram1D histo, DoubleMatrix1D vector) { for (int i = vector.Size; --i >= 0;) { histo.Fill(vector[i]); } return(histo); }
/// <summary> /// Returns the one-norm of vector <i>x</i>, which is <i>Sum(abs(x[i]))</i>. /// </summary> /// <param name="x"> /// The vector x. /// </param> /// <returns> /// The one-norm of x. /// </returns> public static double Norm1(DoubleMatrix1D x) { if (x.Size == 0) { return(0); } return(x.Aggregate(BinaryFunctions.Plus, Math.Abs)); }
/// <summary> /// Returns the dot product of two vectors x and y, which is <tt>Sum(x[i]*y[i])</tt>. /// Where <tt>x == this</tt>. /// Operates on cells at indexes <tt>from .. Min(size(),y.size(),from+length)-1</tt>. /// </summary> /// <param name="y"> /// The second vector. /// </param> /// <param name="from"> /// The first index to be considered. /// </param> /// <param name="length"> /// The number of cells to be considered. /// </param> /// <returns> /// The sum of products; zero if <tt>from < 0 || length < 0</tt>. /// </returns> public override double ZDotProduct(DoubleMatrix1D y, int from, int length) { if (!(y is DenseDoubleMatrix1D)) { return(base.ZDotProduct(y, from, length)); } var yy = (DenseDoubleMatrix1D)y; int tail = from + length; if (from < 0 || length < 0) { return(0); } if (Size < tail) { tail = Size; } if (y.Size < tail) { tail = y.Size; } int min = tail - from; int i = Index(from); int j = yy.Index(from); int s = Stride; int ys = yy.Stride; double[] elems = Elements; double[] yElems = yy.Elements; if (elems == null || yElems == null) { throw new ApplicationException(); } double sum = 0; // optimized // loop unrolling i -= s; j -= ys; for (int k = min / 4; --k >= 0;) { sum += (elems[i += s] * yElems[j += ys]) + (elems[i += s] * yElems[j += ys]) + (elems[i += s] * yElems[j += ys]) + (elems[i += s] * yElems[j += ys]); } for (int k = min % 4; --k >= 0;) { sum += elems[i += s] * yElems[j += ys]; } return(sum); }
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); } }
/// <summary> /// Replaces all cell values of the receiver with the values of another matrix. /// </summary> /// <param name="source"> /// The source matrix to copy from (may be identical to the receiver). /// </param> /// <returns> /// <tt>this</tt> (for convenience only). /// </returns> /// <exception cref="ArgumentException"> /// If <tt>size() != other.size()</tt>. /// </exception> public override DoubleMatrix1D Assign(DoubleMatrix1D source) { // overriden for performance only if (!(source is DenseDoubleMatrix1D)) { return(base.Assign(source)); } var other = (DenseDoubleMatrix1D)source; if (other == this) { return(this); } CheckSize(other); if (!IsView && !other.IsView) { // quickest Array.Copy(other.Elements, 0, Elements, 0, Elements.Length); return(this); } if (HaveSharedCells(other)) { DoubleMatrix1D c = other.Copy(); if (!(c is DenseDoubleMatrix1D)) { // should not happen return(Assign(source)); } other = (DenseDoubleMatrix1D)c; } double[] elems = Elements; double[] otherElems = other.Elements; if (Elements == null || otherElems == null) { throw new ArgumentException(); } int s = Stride; int ys = other.Stride; int index = this.Index(0); int otherIndex = other.Index(0); for (int k = Size; --k >= 0;) { elems[index] = otherElems[otherIndex]; index += s; otherIndex += ys; } return(this); }
public void Drot(DoubleMatrix1D x, DoubleMatrix1D y, double c, double s) { x.CheckSize(y); DoubleMatrix1D tmp = x.Copy(); x.Assign(F1.Mult(c)); x.Assign(y, F2.PlusMult(s)); y.Assign(F1.Mult(c)); y.Assign(tmp, F2.MinusMult(s)); }
/// <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="rowIndexes"> /// the index of the i-th row; is modified by this method to reflect partitioned indexes. /// </param> /// <param name="rowFrom"> /// the index of the first row (inclusive). /// </param> /// <param name="rowTo"> /// the index of the last row (inclusive). /// </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="splitFrom"> /// the index of the first splitter element to be considered. /// </param> /// <param name="splitTo"> /// the index of the last splitter element to be considered. /// The method considers the splitter elements<i>splitters[splitFrom] .d splitters[splitTo]</i>. /// </param> /// <param name="splitIndexes"> /// a list into which this method fills the indexes of rows delimiting intervals. /// Upon return <i>splitIndexes[splitFrom..splitTo]</i> will be set accordingly. /// Therefore, must satisfy <i>splitIndexes.Length >= splitters.Length</i>. /// </param> /// <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"> /// <p><i>column = 0;<br> /// rowIndexes = {0,1,2,.d,matrix.Rows-1}; /// rowFrom = 0;<br> /// rowTo = matrix.Rows-1;<br> /// splitters = {5,10,12}<br> /// c = 0; <br> /// d = splitters.Length-1;<br> /// partition(matrix,rowIndexes,rowFrom,rowTo,column,splitters,c,d,splitIndexes);<br> /// ==><br> /// splitIndexes == {0, 2, 3}<br> /// rowIndexes == {7, 6, 5, 4, 0, 1, 2, 3}</i></p> /// </td> /// <td valign="top"> /// The matrix IS NOT REORDERED.<br> /// Here is how it would look<br> /// like, if it would be reordered<br> /// accoring to <i>rowIndexes</i>.<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 void Partition(DoubleMatrix2D matrix, int[] rowIndexes, int rowFrom, int rowTo, int column, double[] splitters, int splitFrom, int splitTo, int[] splitIndexes) { if (rowFrom < 0 || rowTo >= matrix.Rows || rowTo >= rowIndexes.Length) { throw new ArgumentException(); } if (column < 0 || column >= matrix.Columns) { throw new ArgumentException(); } if (splitFrom < 0 || splitTo >= splitters.Length) { throw new ArgumentException(); } if (splitIndexes.Length < splitters.Length) { throw new ArgumentException(); } // this one knows how to swap two row indexes (a,b) int[] g = rowIndexes; Swapper swapper = new Swapper((b, c) => { int tmp = g[b]; g[b] = g[c]; g[c] = tmp; }); // compare splitter[a] with columnView[rowIndexes[b]] DoubleMatrix1D columnView = matrix.ViewColumn(column); IntComparator comp = new IntComparator((a, b) => { double av = splitters[a]; double bv = columnView[g[b]]; return(av < bv ? -1 : (av == bv ? 0 : 1)); }); // compare columnView[rowIndexes[a]] with columnView[rowIndexes[b]] IntComparator comp2 = new IntComparator((a, b) => { double av = columnView[g[a]]; double bv = columnView[g[b]]; return(av < bv ? -1 : (av == bv ? 0 : 1)); }); // compare splitter[a] with splitter[b] IntComparator comp3 = new IntComparator((a, b) => { double av = splitters[a]; double bv = splitters[b]; return(av < bv ? -1 : (av == bv ? 0 : 1)); }); // generic partitioning does the main work of reordering row indexes Cern.Colt.Partitioning.GenericPartition(rowFrom, rowTo, splitFrom, splitTo, splitIndexes, comp, comp2, comp3, swapper); }
/// <summary> /// Returns a string <i>s</i> such that <i>Object[] m = s</i> is a legal C# statement. /// </summary> /// <param name="matrix">the matrix to format.</param> /// <returns></returns> public String ToSourceCode(DoubleMatrix1D matrix) { Formatter copy = (Formatter)this.Clone(); copy.SetPrintShape(false); copy.SetColumnSeparator(", "); String lead = "{"; String trail = "};"; return(lead + copy.ToString(matrix) + trail); }
public void Dtrmv(Boolean isUpperTriangular, Boolean transposeA, Boolean isUnitTriangular, DoubleMatrix2D A, DoubleMatrix1D x) { if (transposeA) { A = A.ViewDice(); isUpperTriangular = !isUpperTriangular; } Property.DEFAULT.CheckSquare(A); int size = A.Rows; if (size != x.Size) { throw new ArgumentException(A.ToStringShort() + ", " + x.ToStringShort()); } DoubleMatrix1D b = x.Like(); DoubleMatrix1D y = x.Like(); if (isUnitTriangular) { y.Assign(1); } else { for (int i = 0; i < size; i++) { y[i] = A[i, i]; } } for (int i = 0; i < size; i++) { double sum = 0; if (!isUpperTriangular) { for (int j = 0; j < i; j++) { sum += A[i, j] * x[j]; } sum += y[i] * x[i]; } else { sum += y[i] * x[i]; for (int j = i + 1; j < size; j++) { sum += A[i, j] * x[j]; } } b[i] = sum; } x.Assign(b); }
/// <summary> /// Fills all cells of the given vectors into the given histogram. /// </summary> /// <param name="histo"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> /// <param name="weights"></param> /// <returns><i>histo</i> (for convenience only).</returns> /// <exception cref="ArgumentException">if <i>x.Count != y.Count || x.Count != z.Count || x.Count != weights.Count</i>.</exception> public static Hep.Aida.IHistogram3D Histogram(Hep.Aida.IHistogram3D histo, DoubleMatrix1D x, DoubleMatrix1D y, DoubleMatrix1D z, DoubleMatrix1D weights) { if (x.Size != y.Size || x.Size != z.Size || x.Size != weights.Size) { throw new ArgumentException(Cern.LocalizedResources.Instance().Matrix_VectorsMustHaveSameSize); } for (int i = x.Size; --i >= 0;) { histo.Fill(x[i], y[i], z[i], weights[i]); } return(histo); }
/// <summary> /// Fills all cells of the given vectors into the given histogram. /// </summary> /// <param name="histo"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> /// <param name="weights"></param> /// <returns><i>histo</i> (for convenience only).</returns> /// <exception cref="ArgumentException">if <i>x.Count != y.Count || x.Count != z.Count || x.Count != weights.Count</i>.</exception> public static Hep.Aida.IHistogram3D Histogram(Hep.Aida.IHistogram3D histo, DoubleMatrix1D x, DoubleMatrix1D y, DoubleMatrix1D z, DoubleMatrix1D weights) { if (x.Size != y.Size || x.Size != z.Size || x.Size != weights.Size) { throw new ArgumentException("vectors must have same size"); } for (int i = x.Size; --i >= 0;) { histo.Fill(x[i], y[i], z[i], weights[i]); } return(histo); }
public void TestMain() { DoubleMatrix1D x1 = DoubleFactory1D.Dense.Make(new double[] { 1.0, 2.0 }); DoubleMatrix1D x2 = DoubleFactory1D.Dense.Make(new double[] { 1.0, -2.0 }); DoubleMatrix1D x3 = DoubleFactory1D.Dense.Make(new double[] { -1.0, -2.0 }); DoubleMatrix1D x4 = DoubleFactory1D.Dense.Make(new double[] { 4.0, 5.0 }); Assert.AreEqual(2, Algebra.NormInfinity(x1)); Assert.AreEqual(2, Algebra.NormInfinity(x2)); Assert.AreEqual(2, Algebra.NormInfinity(x3)); Assert.AreEqual(5, Algebra.NormInfinity(x4)); }
/// <summary> /// Sorts the vector into ascending order, according to the order induced by the specified comparator. /// </summary> /// <param name="vector"> /// The vector to be sorted. /// </param> /// <param name="c"> /// The comparator to determine the order. /// </param> /// <returns> /// A new matrix view sorted as specified. /// </returns> public DoubleMatrix1D Sort(DoubleMatrix1D vector, DoubleComparator c) { var indexes = new int[vector.Size]; // row indexes to reorder instead of matrix itself for (int i = indexes.Length; --i >= 0;) { indexes[i] = i; } RunSort(indexes, 0, indexes.Length, (a, b) => c(vector[a], vector[b])); return(vector.ViewSelection(indexes)); }
/// <summary> /// 3-d OLAP cube operator; Fills all cells of the given vectors into the given histogram. /// If you use Hep.Aida.Ref.Converter.ToString(histo) on the result, the OLAP cube of x-"column" vsd y-"column" vsd z-"column", summing the weights "column" will be printed. /// For example, aggregate sales by product by region by time. /// <p> /// Computes the distinct values of x and y and z, yielding histogram axes that capture one distinct value per bin. /// Then fills the histogram. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> /// <param name="weights"></param> /// <returns>the histogram containing the cube.</returns> /// <excption cref="ArgumentException">if <i>x.Count != y.Count || x.Count != z.Count || x.Count != weights.Count</i>.</excption> public static Hep.Aida.IHistogram3D cube(DoubleMatrix1D x, DoubleMatrix1D y, DoubleMatrix1D z, DoubleMatrix1D weights) { if (x.Size != y.Size || x.Size != z.Size || x.Size != weights.Size) { throw new ArgumentException("vectors must have same size"); } var epsilon = 1.0E-9; var distinct = new DoubleArrayList(); var vals = new double[x.Size]; var sorted = new DoubleArrayList(vals); // compute distinct values of x vals = x.ToArray(); // copy x into vals sorted.Sort(); Cern.Jet.Stat.Descriptive.Frequencies(sorted, distinct, null); // since bins are right-open [from,to) we need an additional dummy bin so that the last distinct value does not fall into the overflow bin if (distinct.Count > 0) { distinct.Add(distinct[distinct.Count - 1] + epsilon); } distinct.TrimToSize(); Hep.Aida.IAxis xaxis = new Hep.Aida.Ref.VariableAxis(distinct.ToArray()); // compute distinct values of y vals = y.ToArray(); sorted.Sort(); Cern.Jet.Stat.Descriptive.Frequencies(sorted, distinct, null); // since bins are right-open [from,to) we need an additional dummy bin so that the last distinct value does not fall into the overflow bin if (distinct.Count > 0) { distinct.Add(distinct[distinct.Count - 1] + epsilon); } distinct.TrimToSize(); Hep.Aida.IAxis yaxis = new Hep.Aida.Ref.VariableAxis(distinct.ToArray()); // compute distinct values of z vals = z.ToArray(); sorted.Sort(); Cern.Jet.Stat.Descriptive.Frequencies(sorted, distinct, null); // since bins are right-open [from,to) we need an additional dummy bin so that the last distinct value does not fall into the overflow bin if (distinct.Count > 0) { distinct.Add(distinct[distinct.Count - 1] + epsilon); } distinct.TrimToSize(); Hep.Aida.IAxis zaxis = new Hep.Aida.Ref.VariableAxis(distinct.ToArray()); Hep.Aida.IHistogram3D histo = new Hep.Aida.Ref.Histogram3D("Cube", xaxis, yaxis, zaxis); return(Histogram(histo, x, y, z, weights)); }
/// <summary> /// Constructs and returns a new Cholesky decomposition object for a symmetric and positive definite matrix; /// The decomposed matrices can be retrieved via instance methods of the returned decomposition object. /// /// Return a structure to access <i>L</i> and <i>isSymmetricPositiveDefinite</i> flag. /// </summary> /// <param name="A">Square, symmetric matrix.</param> /// <exception cref="ArgumentException">if <i>A</i> is not square.</exception> public CholeskyDecomposition(DoubleMatrix2D A) { Property.DEFAULT.CheckSquare(A); // Initialize. //double[][] A = Arg.getArray(); n = A.Rows; //L = new double[n][n]; mL = A.Like(n, n); isSymmetricPositiveDefinite = (A.Columns == n); //precompute and cache some views to avoid regenerating them time and again DoubleMatrix1D[] Lrows = new DoubleMatrix1D[n]; for (int j = 0; j < n; j++) { Lrows[j] = mL.ViewRow(j); } // Main loop. for (int j = 0; j < n; j++) { //double[] Lrowj = L[j]; //DoubleMatrix1D Lrowj = L.ViewRow(j); double d = 0.0; for (int k = 0; k < j; k++) { //double[] Lrowk = L[k]; double s = Lrows[k].ZDotProduct(Lrows[j], 0, k); /* * DoubleMatrix1D Lrowk = L.ViewRow(k); * double s = 0.0; * for (int i = 0; i < k; i++) { * s += Lrowk.getQuick(i)*Lrowj.getQuick(i); * } */ s = (A[j, k] - s) / mL[k, k]; Lrows[j][k] = s; d = d + s * s; isSymmetricPositiveDefinite = isSymmetricPositiveDefinite && (A[k, j] == A[j, k]); } d = A[j, j] - d; isSymmetricPositiveDefinite = isSymmetricPositiveDefinite && (d > 0.0); mL[j, j] = System.Math.Sqrt(System.Math.Max(d, 0.0)); for (int k = j + 1; k < n; k++) { mL[j, k] = 0.0; } } }
/// <summary> /// Returns <tt>true</tt> if both matrices share at least one identical cell. /// </summary> /// <param name="other"> /// The other matrix. /// </param> /// <returns> /// <tt>true</tt> if both matrices share at least one identical cell. /// </returns> protected override bool HaveSharedCellsRaw(DoubleMatrix1D other) { if (other is SelectedDenseDoubleMatrix1D) { var otherMatrix = (SelectedDenseDoubleMatrix1D)other; return(this.Elements == otherMatrix.Elements); } if (other is DenseDoubleMatrix1D) { var otherMatrix = (DenseDoubleMatrix1D)other; return(this.Elements == otherMatrix.Elements); } return(false); }
/// <summary> /// Same as <see cref="partition(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> /// Of course, the column must not be a column of a different matrix. /// More formally, there must hold: <br> /// There exists an <i>i</i> such that <i>matrix.ViewColumn(i)==column</i>. /// /// Note that arguments are not checked for validity. /// </summary> /// <param name="matrix"></param> /// <param name="column"></param> /// <param name="from"></param> /// <param name="to"></param> /// <param name="splitter"></param> /// <returns></returns> private static int xPartitionOld(DoubleMatrix2D matrix, DoubleMatrix1D column, int from, int to, double splitter) { /* * double element; // int, double --> template type dependent * for (int i=from-1; ++i<=to; ) { * element = column.getQuick(i); * if (element < splitter) { * // swap x[i] with x[from] * matrix.swapRows(i,from); * from++; * } * } * return from-1; */ return(0); }