List of usage examples for org.apache.commons.math3.linear RealMatrix setEntry
void setEntry(int row, int column, double value) throws OutOfRangeException;
From source file:edu.cmu.tetrad.util.ApacheTetradMatrix.java
public ApacheTetradMatrix appendRows(ApacheTetradMatrix rows) { RealMatrix m1 = new BlockRealMatrix(apacheData.getRowDimension() + rows.apacheData.getRowDimension(), apacheData.getColumnDimension()); for (int i = 0; i < apacheData.getRowDimension(); i++) { for (int j = 0; j < apacheData.getColumnDimension(); j++) { m1.setEntry(i, j, apacheData.getEntry(i, j)); }//from w w w. ja v a 2s. c o m } for (int i = 0; i < rows.apacheData.getRowDimension(); i++) { for (int j = 0; j < rows.apacheData.getColumnDimension(); j++) { m1.setEntry(apacheData.getRowDimension() + i, j, rows.apacheData.getEntry(i, j)); } } return new ApacheTetradMatrix(m1); }
From source file:com.analog.lyric.dimple.solvers.sumproduct.customFactors.MutlivariateGaussianMatrixProduct.java
public MutlivariateGaussianMatrixProduct(double[][] A) { int i; //,m; M = A.length;//from w w w. j av a 2s. c om N = A[0].length; /* Here we precompute and store matrices for future message computations. * First, compute an SVD of the matrix A using EigenDecompositions of A*A^T and A^T*A * This way, we get nullspaces for free along with regularized inverse. */ RealMatrix Amat = wrapRealMatrix(A); SingularValueDecomposition svd = new SingularValueDecomposition(Amat); RealMatrix tmp = svd.getVT(); tmp = svd.getS().multiply(tmp); tmp = svd.getU().multiply(tmp); A_clean = matrixGetDataRef(tmp); RealMatrix ST = svd.getS().transpose(); int numS = Math.min(ST.getColumnDimension(), ST.getRowDimension()); for (i = 0; i < numS; i++) { double d = ST.getEntry(i, i); if (d < eps) d = eps; else if (d > 1 / eps) d = 1 / eps; ST.setEntry(i, i, 1.0 / d); } A_pinv = matrixGetDataRef(svd.getV().multiply(ST.multiply(svd.getUT()))); }
From source file:com.joptimizer.functions.SOCPLogarithmicBarrier.java
public double[][] hessian(double[] X) { RealVector x = new ArrayRealVector(X); RealMatrix ret = new Array2DRowRealMatrix(dim, dim); for (int i = 0; i < socpConstraintParametersList.size(); i++) { SOCPConstraintParameters param = socpConstraintParametersList.get(i); double t = this.buildT(param, x); RealVector u = this.buildU(param, x); double t2uu = t * t - u.dotProduct(u); RealVector t2u = u.mapMultiply(-2 * t); RealMatrix Jacob = this.buildJ(param, x); int k = u.getDimension(); RealMatrix H = new Array2DRowRealMatrix(k + 1, k + 1); RealMatrix ID = MatrixUtils.createRealIdentityMatrix(k); H.setSubMatrix(ID.scalarMultiply(t2uu).add(u.outerProduct(u).scalarMultiply(2)).getData(), 0, 0); H.setSubMatrix(new double[][] { t2u.toArray() }, k, 0); for (int j = 0; j < k; j++) { H.setEntry(j, k, t2u.getEntry(j)); }/* ww w. ja va 2s .com*/ H.setEntry(k, k, t * t + u.dotProduct(u)); RealMatrix ret_i = Jacob.multiply(H).multiply(Jacob.transpose()).scalarMultiply(2. / Math.pow(t2uu, 2)); ret = ret.add(ret_i); } return ret.getData(); }
From source file:edu.oregonstate.eecs.mcplan.ml.KulisLowRankKernelLearner.java
private void choleskyUpdate(final int r, final double alpha, final RealVector x, final RealMatrix B) { final double[] a = new double[r + 1]; final double[] h = new double[r]; a[0] = alpha;//from w w w . j a v a2s . c om for (int i = 0; i < r; ++i) { final double xi = x.getEntry(i); double t = 1 + a[i] * xi * xi; h[i] = Math.sqrt(t); a[i + 1] = a[i] / t; t = B.getEntry(i, i); double s = 0.0; B.setEntry(i, i, t * h[i]); // t == B_ii for (int j = i - 1; j >= 0; --j) { s += t * x.getEntry(j + 1); t = B.getEntry(i, j); B.setEntry(i, j, (t + a[j + 1] * x.getEntry(j) * s) * h[j]); // t == B_ij } } }
From source file:edu.oregonstate.eecs.mcplan.ml.LinearDiscriminantAnalysis.java
/** * @param data The elements of 'data' will be modified. * @param label/*from w ww. jav a 2s .c o m*/ * @param Nclasses * @param shrinkage_intensity */ public LinearDiscriminantAnalysis(final ArrayList<double[]> data, final int[] label, final int Nclasses, final double shrinkage) { assert (data.size() == label.length); final int Ndata = data.size(); final int Ndim = data.get(0).length; // Partition data by class final ArrayList<ArrayList<double[]>> classes = new ArrayList<ArrayList<double[]>>(Nclasses); for (int i = 0; i < Nclasses; ++i) { classes.add(new ArrayList<double[]>()); } for (int i = 0; i < data.size(); ++i) { classes.get(label[i]).add(data.get(i)); } // Mean center the data final VectorMeanVarianceAccumulator mv = new VectorMeanVarianceAccumulator(Ndim); for (int i = 0; i < Ndata; ++i) { mv.add(data.get(i)); } mean = mv.mean(); // Subtract global mean for (final double[] x : data) { Fn.vminus_inplace(x, mean); } // Calculate class means and covariances final double[][] class_mean = new double[Nclasses][Ndim]; final RealMatrix[] class_cov = new RealMatrix[Nclasses]; for (int i = 0; i < Nclasses; ++i) { final ArrayList<double[]> Xc = classes.get(i); final VectorMeanVarianceAccumulator mv_i = new VectorMeanVarianceAccumulator(Ndim); final StorelessCovariance cov = new StorelessCovariance(Ndim); for (int j = 0; j < Xc.size(); ++j) { final double[] x = Xc.get(j); mv_i.add(x); cov.increment(x); } class_mean[i] = mv_i.mean(); class_cov[i] = cov.getCovarianceMatrix(); } // Between-class scatter. // Note that 'data' is mean-centered, so the global mean is 0. RealMatrix Sb_builder = new Array2DRowRealMatrix(Ndim, Ndim); for (int i = 0; i < Nclasses; ++i) { final RealVector mu_i = new ArrayRealVector(class_mean[i]); final RealMatrix xxt = mu_i.outerProduct(mu_i); Sb_builder = Sb_builder.add(xxt.scalarMultiply(classes.get(i).size() / ((double) Ndata - 1))); } this.Sb = Sb_builder; Sb_builder = null; // Within-class scatter with shrinkage estimate: // Sw = (1.0 - shrinkage) * \sum Sigma_i + shrinkage * I RealMatrix Sw_builder = new Array2DRowRealMatrix(Ndim, Ndim); for (int i = 0; i < Nclasses; ++i) { final RealMatrix Sigma_i = class_cov[i]; final RealMatrix scaled = Sigma_i.scalarMultiply((1.0 - shrinkage) * (classes.get(i).size() - 1)); Sw_builder = Sw_builder.add(scaled); } for (int i = 0; i < Ndim; ++i) { Sw_builder.setEntry(i, i, Sw_builder.getEntry(i, i) + shrinkage); } this.Sw = Sw_builder; Sw_builder = null; // Invert Sw System.out.println("[LDA] Sw inverse"); final RealMatrix Sw_inv = new LUDecomposition(Sw).getSolver().getInverse(); final RealMatrix F = Sw_inv.multiply(Sb); System.out.println("[LDA] Eigendecomposition"); eigenvalues = new double[Nclasses - 1]; eigenvectors = new ArrayList<RealVector>(Nclasses - 1); final EigenDecomposition evd = new EigenDecomposition(F); for (int j = 0; j < Nclasses - 1; ++j) { final double eigenvalue = evd.getRealEigenvalue(j); eigenvalues[j] = eigenvalue; // final double scale = 1.0 / Math.sqrt( eigenvalue ); // eigenvectors.add( evd.getEigenvector( j ).mapMultiply( scale ) ); eigenvectors.add(evd.getEigenvector(j)); } }
From source file:eagle.security.userprofile.impl.UserProfileAnomalyEigenEvaluator.java
private RealMatrix normalizeData(RealMatrix matrix, UserProfileEigenModel model) { RealMatrix normalizedData = new Array2DRowRealMatrix(matrix.getRowDimension(), matrix.getColumnDimension()); if (LOG.isDebugEnabled()) LOG.debug("model statistics size: " + model.statistics().length); for (int i = 0; i < matrix.getRowDimension(); i++) { for (int j = 0; j < matrix.getColumnDimension(); j++) { double value = (matrix.getEntry(i, j) - model.statistics()[j].getMean()) / model.statistics()[j].getStddev(); normalizedData.setEntry(i, j, value); }/*w ww.j a v a2 s .c o m*/ } return normalizedData; }
From source file:hivemall.utils.math.MatrixUtils.java
/** * Lanczos tridiagonalization for a symmetric matrix C to make s * s tridiagonal matrix T. * * @see http://www.cas.mcmaster.ca/~qiao/publications/spie05.pdf * @param C target symmetric matrix/*from w w w. j a v a2 s .c o m*/ * @param a initial vector * @param T result is stored here */ public static void lanczosTridiagonalization(@Nonnull final RealMatrix C, @Nonnull final double[] a, @Nonnull final RealMatrix T) { Preconditions.checkArgument(Arrays.deepEquals(C.getData(), C.transpose().getData()), "Target matrix C must be a symmetric matrix"); Preconditions.checkArgument(C.getColumnDimension() == a.length, "Column size of A and length of a should be same"); Preconditions.checkArgument(T.getRowDimension() == T.getColumnDimension(), "T must be a square matrix"); int s = T.getRowDimension(); // initialize T with zeros T.setSubMatrix(new double[s][s], 0, 0); RealVector a0 = new ArrayRealVector(a.length); RealVector r = new ArrayRealVector(a); double beta0 = 1.d; for (int i = 0; i < s; i++) { RealVector a1 = r.mapDivide(beta0); RealVector Ca1 = C.operate(a1); double alpha1 = a1.dotProduct(Ca1); r = Ca1.add(a1.mapMultiply(-1.d * alpha1)).add(a0.mapMultiply(-1.d * beta0)); double beta1 = r.getNorm(); T.setEntry(i, i, alpha1); if (i - 1 >= 0) { T.setEntry(i, i - 1, beta0); } if (i + 1 < s) { T.setEntry(i, i + 1, beta1); } a0 = a1.copy(); beta0 = beta1; } }
From source file:edu.stanford.cfuller.imageanalysistools.metric.IntensityPerPixelMetric.java
/** * Quantifies the (area) average intensity for each region of interest in an image. * * If no regions of interest are present in the supplied mask, this will return null. * * @param mask A mask that specifies the region of interest. This should have regions of interest uniquely labeled consecutively, starting with the value 1, * as might be produced by a {@link edu.stanford.cfuller.imageanalysistools.filter.LabelFilter}. * @param images An ImageSet of Images to be quantified using the same masks (perhaps corresponding to different color channels, for example). * @return A RealMatrix containing the average intensity value for each region of interest in each input Image. A single column of the region labels preceeds a sub-matrix, the (i,j)th * entry of which will contain the quantification of ROI (i+1) in Image j. This will then be followed by a single column containing the pixel count for that region. *///from w w w. j a v a 2s . com @Override public Quantification quantify(Image mask, ImageSet images) { edu.stanford.cfuller.imageanalysistools.image.Histogram h = new edu.stanford.cfuller.imageanalysistools.image.Histogram( mask); if (h.getMaxValue() == 0) return null; RealMatrix channelIntensities = (new org.apache.commons.math3.linear.Array2DRowRealMatrix( images.getImageCount(), h.getMaxValue())).scalarMultiply(0); for (ImageCoordinate i : mask) { int regionNum = (int) mask.getValue(i); if (regionNum > 0) { for (int c = 0; c < images.getImageCount(); c++) { channelIntensities.addToEntry(c, regionNum - 1, images.getImageForIndex(c).getValue(i)); } } } for (int i = 0; i < h.getMaxValue(); i++) { for (int c = 0; c < images.getImageCount(); c++) { channelIntensities.setEntry(c, i, channelIntensities.getEntry(c, i) / h.getCounts(i + 1)); } } Quantification q = new Quantification(); for (int i = 0; i < h.getMaxValue(); i++) { for (int c = 0; c < images.getImageCount(); c++) { Measurement m = new Measurement(true, i + 1, channelIntensities.getEntry(c, i), "channel_" + c, Measurement.TYPE_INTENSITY, images.getMarkerImageName()); q.addMeasurement(m); } Measurement m = new Measurement(true, i + 1, h.getCounts(i + 1), "pixel_count", Measurement.TYPE_SIZE, images.getMarkerImageName()); q.addMeasurement(m); } return q; }
From source file:edu.cudenver.bios.matrix.DesignEssenceMatrix.java
/** * Fill a fixed column in the design matrix * * @param fixedColumn column index in fixed submatrix * @param fullColumn column index in full design matrix * @param fullDesign full design matrix//w w w.java2s. c om */ private void fillFixedColumn(int fixedColumn, int fullColumn, RealMatrix fullDesign) { int essenceRow = 0; int reps = groupSampleSize * rowMetaData[essenceRow].getRatio(); for (int row = 0; row < fullDesign.getRowDimension(); row++) { // check if we need to move on to the next row in the essence matrix if (reps <= 0) { essenceRow++; reps = groupSampleSize * rowMetaData[essenceRow].getRatio(); } // fill in the data fullDesign.setEntry(row, fullColumn, fixedMatrix.getEntry(essenceRow, fixedColumn)); // decrement the number of reps remain for this row reps--; } }
From source file:eagle.security.userprofile.model.eigen.UserProfileEigenModeler.java
private RealMatrix normalizeData(RealMatrix matrix) { RealMatrix normalizedData = new Array2DRowRealMatrix(matrix.getRowDimension(), matrix.getColumnDimension()); for (int i = 0; i < matrix.getRowDimension(); i++) { for (int j = 0; j < matrix.getColumnDimension(); j++) { // TODO: statistics[j].getStddev() == 0 what should the value be if stddev is o? double value = statistics[j].getStddev() == 0 ? 0 : (matrix.getEntry(i, j) - statistics[j].getMean()) / statistics[j].getStddev(); normalizedData.setEntry(i, j, value); }//w ww . j a v a2s . co m } return normalizedData; }