List of usage examples for org.apache.commons.math3.linear RealMatrix setColumnVector
void setColumnVector(int column, RealVector vector) throws OutOfRangeException, MatrixDimensionMismatchException;
From source file:io.warp10.script.functions.TOMAT.java
@Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object o = stack.pop();//from w w w . j a v a2 s .c o m if (o instanceof RealVector) { RealMatrix matrix = MatrixUtils.createRealMatrix(((RealVector) o).getDimension(), 1); matrix.setColumnVector(0, (RealVector) o); stack.push(matrix); return stack; } if (!(o instanceof List)) { throw new WarpScriptException(getName() + " expects a 2D array onto the stack."); } int rows = ((List) o).size(); int cols = -1; for (Object oo : (List) o) { if (!(oo instanceof List)) { throw new WarpScriptException(getName() + " expects a 2D array onto the stack."); } if (-1 == cols) { cols = ((List) oo).size(); } else if (cols != ((List) oo).size()) { throw new WarpScriptException( getName() + " expects a common number of columns throughout the 2D array."); } } double[][] doubles = new double[rows][cols]; for (int i = 0; i < rows; i++) { List<Object> row = (List<Object>) ((List) o).get(i); for (int j = 0; j < cols; j++) { Object elt = row.get(j); if (!(elt instanceof Number)) { throw new WarpScriptException(getName() + " expects a numeric 2D array onto the stack."); } doubles[i][j] = ((Number) elt).doubleValue(); } } RealMatrix mat = MatrixUtils.createRealMatrix(doubles); stack.push(mat); return stack; }
From source file:com.github.thorbenlindhauer.factor.CanonicalGaussianFactor.java
/** * Transforms a conditional linear gaussian (i.e. a Gaussian of the form N(x; a + B^T * Y, C) into canonical form. * * @param meanVector a//from w w w . ja v a2 s. co m * @param weightMatrix B * @param covarianceMatrix C */ public static CanonicalGaussianFactor fromConditionalForm(Scope scope, Scope conditioningScope, RealVector meanVector, RealMatrix covarianceMatrix, RealMatrix weightMatrix) { // TODO: perform cardinality checks etc. // the following assumes that the resulting precision matrix (and mean vector) can be restructured as follows: // ( SUBMATRIX_XX SUBMATRIX_XY ) // ( SUBMATRIX_YX SUBMATRIX_YY ) // where X indicates variables that are part of the prediction scope and Y are variables being part of the conditioning scope // assuming // meanVector: a; |x| vector // covarianceMatrix: C; |x| cross |x| matrix // weightMatrix: B; |x| cross |y| matrix // XX = C^-1 // XY = -C^-1 * B // YX = -B^T * C^-1 // YY = B^T * C^-1 * B^T MathUtil mathUtil = new MathUtil(covarianceMatrix); // C^(-1) RealMatrix xxMatrix = null; xxMatrix = mathUtil.invert(); // if (!mathUtil.isZeroMatrix()) { // xxMatrix = mathUtil.invert(); // } else { // // // this is a special case for convolution in which the "summing" variable has no variance itself // // although a 0 variance is not valid in general // xxMatrix = covarianceMatrix; // } // B^T * C^(-1) RealMatrix weightedXXMatrix = weightMatrix.transpose().multiply(xxMatrix); // -B^T * C^(-1) RealMatrix yxMatrix = weightedXXMatrix.scalarMultiply(-1.0d); // -C^(-1)^T * B RealMatrix xyMatrix = xxMatrix.transpose().multiply(weightMatrix).scalarMultiply(-1.0d); // B^T * C^(-1) * B RealMatrix yyMatrix = weightedXXMatrix.multiply(weightMatrix); // K RealMatrix conditionedPrecisionMatrix = new Array2DRowRealMatrix(scope.size(), scope.size()); // Matrix to generate h RealMatrix conditionedMeanTransformationMatrix = new Array2DRowRealMatrix(scope.size(), scope.size()); Scope predictionScope = scope.reduceBy(conditioningScope); int[] predictionMapping = scope.createContinuousVariableMapping(predictionScope); int[] conditioningMapping = scope.createContinuousVariableMapping(conditioningScope); for (int i = 0; i < scope.size(); i++) { RealVector precisionColumn = conditionedPrecisionMatrix.getColumnVector(i); if (predictionMapping[i] >= 0) { precisionColumn = precisionColumn.add( padVector(xxMatrix.getColumnVector(predictionMapping[i]), scope.size(), predictionMapping)); conditionedMeanTransformationMatrix.setColumnVector(i, precisionColumn); precisionColumn = precisionColumn.add(padVector(yxMatrix.getColumnVector(predictionMapping[i]), scope.size(), conditioningMapping)); conditionedPrecisionMatrix.setColumnVector(i, precisionColumn); } if (conditioningMapping[i] >= 0) { precisionColumn = precisionColumn.add(padVector(xyMatrix.getColumnVector(conditioningMapping[i]), scope.size(), predictionMapping)); conditionedMeanTransformationMatrix.setColumnVector(i, precisionColumn); precisionColumn = precisionColumn.add(padVector(yyMatrix.getColumnVector(conditioningMapping[i]), scope.size(), conditioningMapping)); conditionedPrecisionMatrix.setColumnVector(i, precisionColumn); } } // h = (a, 0)^T * (XX, XY; 0, 0) RealMatrix scaledMeanMatrix = new Array2DRowRealMatrix(1, scope.size()); scaledMeanMatrix.setRowVector(0, padVector(meanVector, scope.size(), predictionMapping)); scaledMeanMatrix = scaledMeanMatrix.multiply(conditionedMeanTransformationMatrix); RealVector scaledMeanVector = scaledMeanMatrix.getRowVector(0); // g = a^T * C^-1 * a - log((2 * PI) ^ m/2 * det(C)^0.5) where m is the size of the prediction scope RealMatrix meanMatrix = new Array2DRowRealMatrix(predictionScope.size(), 1); meanMatrix.setColumnVector(0, meanVector); double normalizationConstant = -0.5d * meanVector.dotProduct(xxMatrix.operate(meanVector)) - Math.log( Math.pow(2 * Math.PI, (double) predictionScope.size() / 2.0d) * Math.sqrt(mathUtil.determinant())); return new CanonicalGaussianFactor(scope, conditionedPrecisionMatrix, scaledMeanVector, normalizationConstant); }
From source file:cooccurrence.Omer_Levy.java
/** * Method that will extract top D singular values from CoVariance Matrix * It will then identify the corresponding columns from U and V and add it to new matrices * @param U/*from w w w . ja v a 2s .c om*/ * @param V * @param coVariance * @param matrixUd * @param matrixVd * @param coVarD * @param indicesD */ private static void getTopD(RealMatrix U, RealMatrix V, RealMatrix coVariance, RealMatrix matrixUd, RealMatrix matrixVd, RealMatrix coVarD, ArrayList<Integer> indicesD) { TreeMap<Double, Set<Integer>> tmap = new TreeMap<>(); for (int i = 0; i < coVariance.getRowDimension(); i++) { double val = coVariance.getEntry(i, i); if (tmap.containsKey(val)) { Set<Integer> temp = tmap.get(val); temp.add(i); } else { Set<Integer> temp = new HashSet<>(); temp.add(i); tmap.put(val, temp); } } Iterator iter = tmap.keySet().iterator(); while (iter.hasNext()) { Double val = (Double) iter.next(); Set<Integer> indices = tmap.get(val); for (int i = 0; i < indices.size(); i++) { Iterator iterIndices = indices.iterator(); while (iterIndices.hasNext()) { int index = (Integer) iterIndices.next(); indicesD.add(index); coVarD.addToEntry(index, index, val); matrixUd.setColumnVector(index, U.getColumnVector(index)); matrixVd.setColumnVector(index, V.getColumnVector(index)); } } } }
From source file:com.joptimizer.functions.SOCPLogarithmicBarrier.java
private RealMatrix buildJ(SOCPConstraintParameters param, RealVector X) { RealMatrix J = new Array2DRowRealMatrix(dim, param.getA().getRowDimension() + 1); J.setSubMatrix(param.getA().transpose().getData(), 0, 0); J.setColumnVector(param.getA().getRowDimension(), param.getC()); return J;/* w ww . j a va2 s.c om*/ }
From source file:com.github.thorbenlindhauer.math.MathUtil.java
public RealMatrix invert() { if (!matrix.isSquare()) { throw new FactorOperationException("Cannot invert non-square matrix"); }//w w w . j ava 2 s . co m ensureLUDecompositionInitialized(); int matrixDimension = matrix.getRowDimension(); RealMatrix inverseMatrix = new Array2DRowRealMatrix(matrixDimension, matrixDimension); RealMatrix identityMatrix = MatrixUtils.createRealIdentityMatrix(matrixDimension); DecompositionSolver solver = luDecomposition.getSolver(); for (int i = 0; i < matrixDimension; i++) { RealVector identityColumn = identityMatrix.getColumnVector(i); RealVector inverseColumn = solver.solve(identityColumn); inverseMatrix.setColumnVector(i, inverseColumn); } return inverseMatrix; }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.BisquareLinearFit.java
/** * Calculates the leverages of data points for least squares fitting (assuming equal variances). * * @param indVarValues The values of the independent variable used for the fitting. * @return a RealVector containing a leverage value for each independent variable value. *///from www .j a v a 2 s . co m protected RealVector calculateLeverages(RealVector indVarValues) { RealMatrix indVarMatrix = null; if (this.noIntercept) { indVarMatrix = new Array2DRowRealMatrix(indVarValues.getDimension(), 1); } else { indVarMatrix = new Array2DRowRealMatrix(indVarValues.getDimension(), 2); } indVarMatrix.setColumnVector(0, indVarValues); if (!this.noIntercept) { indVarMatrix.setColumnVector(1, indVarValues.mapMultiply(0).mapAdd(1)); } RealVector leverages = new ArrayRealVector(indVarValues.getDimension()); QRDecomposition xQR = new QRDecomposition(indVarMatrix); RealMatrix xR = xQR.getR(); int smallerDim = xR.getRowDimension() < xR.getColumnDimension() ? xR.getRowDimension() : xR.getColumnDimension(); RealMatrix xRSq = xR.getSubMatrix(0, smallerDim - 1, 0, smallerDim - 1); QRDecomposition xRQR = new QRDecomposition(xRSq); RealMatrix xRInv = xRQR.getSolver().getInverse(); RealMatrix xxRInv = indVarMatrix.multiply(xRInv); for (int i = 0; i < indVarValues.getDimension(); i++) { double sum = 0; for (int j = 0; j < xxRInv.getColumnDimension(); j++) { sum += Math.pow(xxRInv.getEntry(i, j), 2); } leverages.setEntry(i, sum); } return leverages; }
From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java
/** * Applies an existing correction to a single x-y position in the Image plane. * * @param x The x-position at which to apply the correction. * @param y The y-position at which to apply the correction. * @return A RealVector containing 3 elements-- the magnitude of the correction in the x, y, and z dimensions, in that order. *///from ww w .ja v a2 s .co m public RealVector correctPosition(double x, double y) throws UnableToCorrectException { RealVector corrections = new ArrayRealVector(3, 0.0); RealVector distsToCentroids = this.getPositionsForCorrection().getColumnVector(0).mapSubtract(x) .mapToSelf(new Power(2)); distsToCentroids = distsToCentroids .add(this.getPositionsForCorrection().getColumnVector(1).mapSubtract(y).mapToSelf(new Power(2))); distsToCentroids.mapToSelf(new Sqrt()); RealVector distRatio = distsToCentroids.ebeDivide(this.getDistanceCutoffs()); RealVector distRatioBin = new ArrayRealVector(distRatio.getDimension(), 0.0); for (int i = 0; i < distRatio.getDimension(); i++) { if (distRatio.getEntry(i) <= 1) distRatioBin.setEntry(i, 1.0); } RealVector weights = distRatio.map(new Power(2.0)).mapMultiplyToSelf(-3).mapAddToSelf(1) .add(distRatio.map(new Power(3.0)).mapMultiplyToSelf(2)); weights = weights.ebeMultiply(distRatioBin); double sumWeights = 0; int countWeights = 0; for (int i = 0; i < weights.getDimension(); i++) { if (weights.getEntry(i) > 0) { sumWeights += weights.getEntry(i); countWeights++; } } if (countWeights == 0) { // this means there were no points in the correction dataset near the position being corrected. throw (new UnableToCorrectException( "Incomplete coverage in correction dataset at (x,y) = (" + x + ", " + y + ").")); } RealMatrix cX = new Array2DRowRealMatrix(countWeights, this.getCorrectionX().getColumnDimension()); RealMatrix cY = new Array2DRowRealMatrix(countWeights, this.getCorrectionX().getColumnDimension()); RealMatrix cZ = new Array2DRowRealMatrix(countWeights, this.getCorrectionX().getColumnDimension()); RealVector xVec = new ArrayRealVector(countWeights, 0.0); RealVector yVec = new ArrayRealVector(countWeights, 0.0); RealVector keptWeights = new ArrayRealVector(countWeights, 0.0); int keptCounter = 0; for (int i = 0; i < weights.getDimension(); i++) { if (weights.getEntry(i) > 0) { cX.setRowVector(keptCounter, this.getCorrectionX().getRowVector(i)); cY.setRowVector(keptCounter, this.getCorrectionY().getRowVector(i)); cZ.setRowVector(keptCounter, this.getCorrectionZ().getRowVector(i)); xVec.setEntry(keptCounter, x - this.getPositionsForCorrection().getEntry(i, 0)); yVec.setEntry(keptCounter, y - this.getPositionsForCorrection().getEntry(i, 1)); keptWeights.setEntry(keptCounter, weights.getEntry(i)); keptCounter++; } } double xCorr = 0; double yCorr = 0; double zCorr = 0; RealMatrix allCorrectionParameters = new Array2DRowRealMatrix(countWeights, numberOfCorrectionParameters); RealVector ones = new ArrayRealVector(countWeights, 1.0); allCorrectionParameters.setColumnVector(0, ones); allCorrectionParameters.setColumnVector(1, xVec); allCorrectionParameters.setColumnVector(2, yVec); allCorrectionParameters.setColumnVector(3, xVec.map(new Power(2))); allCorrectionParameters.setColumnVector(4, yVec.map(new Power(2))); allCorrectionParameters.setColumnVector(5, xVec.ebeMultiply(yVec)); for (int i = 0; i < countWeights; i++) { xCorr += allCorrectionParameters.getRowVector(i).dotProduct(cX.getRowVector(i)) * keptWeights.getEntry(i); yCorr += allCorrectionParameters.getRowVector(i).dotProduct(cY.getRowVector(i)) * keptWeights.getEntry(i); zCorr += allCorrectionParameters.getRowVector(i).dotProduct(cZ.getRowVector(i)) * keptWeights.getEntry(i); } xCorr /= sumWeights; yCorr /= sumWeights; zCorr /= sumWeights; corrections.setEntry(0, xCorr); corrections.setEntry(1, yCorr); corrections.setEntry(2, zCorr); return corrections; }
From source file:com.github.thorbenlindhauer.factor.CanonicalGaussianFactor.java
@Override public GaussianFactor division(GaussianFactor other) { if (!scope.contains(other.getVariables().getVariableIds())) { throw new FactorOperationException("Divisor scope " + other.getVariables() + " is not a subset of" + " this factor's scope " + scope); }// w w w . j a v a 2 s . co m int[] otherMapping = scope.createContinuousVariableMapping(other.getVariables()); RealMatrix newPrecisionMatrix = precisionMatrix.copy(); RealMatrix otherPrecisionMatrix = other.getPrecisionMatrix(); for (int i = 0; i < scope.size(); i++) { RealVector column = newPrecisionMatrix.getColumnVector(i); if (otherMapping[i] >= 0) { column = column.subtract(padVector(otherPrecisionMatrix.getColumnVector(otherMapping[i]), scope.size(), otherMapping)); newPrecisionMatrix.setColumnVector(i, column); } } RealVector newScaledMeanVector = scaledMeanVector.copy(); RealVector otherScaledMeanVector = other.getScaledMeanVector(); newScaledMeanVector = newScaledMeanVector .subtract(padVector(otherScaledMeanVector, scope.size(), otherMapping)); double newNormalizationConstant = normalizationConstant - other.getNormalizationConstant(); return new CanonicalGaussianFactor(scope, newPrecisionMatrix, newScaledMeanVector, newNormalizationConstant); }
From source file:com.github.thorbenlindhauer.factor.CanonicalGaussianFactor.java
@Override public GaussianFactor product(GaussianFactor other) { Scope newScope = scope.union(other.getVariables()); int newFactorSize = newScope.size(); int[] thisMapping = newScope.createContinuousVariableMapping(scope); int[] otherMapping = newScope.createContinuousVariableMapping(other.getVariables()); RealMatrix newPrecisionMatrix = new Array2DRowRealMatrix(newScope.size(), newScope.size()); RealMatrix otherPrecisionMatrix = other.getPrecisionMatrix(); for (int i = 0; i < newFactorSize; i++) { RealVector column = new ArrayRealVector(newFactorSize); if (thisMapping[i] >= 0) { column = column.add(//w w w . j a v a2 s . co m padVector(precisionMatrix.getColumnVector(thisMapping[i]), newFactorSize, thisMapping)); } if (otherMapping[i] >= 0) { column = column.add(padVector(otherPrecisionMatrix.getColumnVector(otherMapping[i]), newFactorSize, otherMapping)); } newPrecisionMatrix.setColumnVector(i, column); } RealVector newScaledMeanVector = padVector(scaledMeanVector, newScope.size(), thisMapping); RealVector otherScaledMeanVector = other.getScaledMeanVector(); newScaledMeanVector = newScaledMeanVector .add(padVector(otherScaledMeanVector, newFactorSize, otherMapping)); double newNormalizationConstant = normalizationConstant + other.getNormalizationConstant(); return new CanonicalGaussianFactor(newScope, newPrecisionMatrix, newScaledMeanVector, newNormalizationConstant); }
From source file:lirmm.inria.fr.math.BigSparseRealMatrixTest.java
@Test public void testSetColumnVector() { RealMatrix m = new BigSparseRealMatrix(subTestData); RealVector mColumn3 = columnToVector(subColumn3); Assert.assertNotSame(mColumn3, m.getColumnVector(1)); m.setColumnVector(1, mColumn3); Assert.assertEquals(mColumn3, m.getColumnVector(1)); try {//from w w w.j a v a2 s .c om m.setColumnVector(-1, mColumn3); Assert.fail("Expecting OutOfRangeException"); } catch (OutOfRangeException ex) { // expected } try { m.setColumnVector(0, new ArrayRealVector(5)); Assert.fail("Expecting MatrixDimensionMismatchException"); } catch (MatrixDimensionMismatchException ex) { // expected } }