List of usage examples for org.apache.commons.math3.linear ArrayRealVector ArrayRealVector
public ArrayRealVector(ArrayRealVector v) throws NullArgumentException
From source file:com.joptimizer.algebra.CholeskySparseFactorizationTest.java
public void testSimple1_norescaling() throws Exception { log.debug("testSimple1_norescaling"); double[][] A = new double[][] { { 4, 0, 2, 2 }, { 0, 4, 2, -2 }, { 2, 2, 6, 0 }, { 2, -2, 0, 6 } }; //expected L//from w ww . j a v a 2 s.com double[][] EL = new double[][] { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 1, 1, 2, 0 }, { 1, -1, 0, 2 } }; SparseDoubleMatrix2D ASparse = new SparseDoubleMatrix2D(A); CholeskySparseFactorization cs = new CholeskySparseFactorization(ASparse); cs.factorize(); DoubleMatrix2D L = cs.getL(); DoubleMatrix2D LT = cs.getLT(); log.debug("L : " + ArrayUtils.toString(L.toArray())); log.debug("LT: " + ArrayUtils.toString(LT.toArray())); RealMatrix ELMatrix = MatrixUtils.createRealMatrix(EL); RealMatrix LMatrix = MatrixUtils.createRealMatrix(L.toArray()); RealMatrix LTMatrix = MatrixUtils.createRealMatrix(LT.toArray()); assertEquals((ELMatrix.subtract(LMatrix).getNorm()), 0.); assertEquals((ELMatrix.subtract(LTMatrix.transpose()).getNorm()), 0.); //A.x = b double[] b = new double[] { 1, 2, 3, 4 }; double[] x = cs.solve(F1.make(b)).toArray(); //check the norm ||A.x-b|| double norm = new Array2DRowRealMatrix(A).operate(new ArrayRealVector(x)).subtract(new ArrayRealVector(b)) .getNorm(); log.debug("norm: " + norm); assertEquals(0., norm, Utils.getDoubleMachineEpsilon()); //check the scaled residual double residual = Utils.calculateScaledResidual(A, x, b); log.debug("residual: " + residual); assertEquals(0., residual, Utils.getDoubleMachineEpsilon()); }
From source file:hivemall.anomaly.SDAR2D.java
/** * @param x series of input in LIFO order * @param k AR window size//w ww . j a v a2 s. c o m * @return x_hat predicted x * @link https://en.wikipedia.org/wiki/Matrix_multiplication#Outer_product */ @Nonnull public RealVector update(@Nonnull final ArrayRealVector[] x, final int k) { Preconditions.checkArgument(x.length >= 1, "x.length MUST be greater than 1: " + x.length); Preconditions.checkArgument(k >= 0, "k MUST be greater than or equals to 0: ", k); Preconditions.checkArgument(k < _C.length, "k MUST be less than |C| but " + "k=" + k + ", |C|=" + _C.length); final ArrayRealVector x_t = x[0]; final int dims = x_t.getDimension(); if (_initialized == false) { this._mu = x_t.copy(); this._sigma = new BlockRealMatrix(dims, dims); assert (_sigma.isSquare()); this._initialized = true; return new ArrayRealVector(dims); } Preconditions.checkArgument(k >= 1, "k MUST be greater than 0: ", k); // old parameters are accessible to compute the Hellinger distance this._muOld = _mu.copy(); this._sigmaOld = _sigma.copy(); // update mean vector // \hat{mu} := (1-r) \hat{} + r x_t this._mu = _mu.mapMultiply(1.d - _r).add(x_t.mapMultiply(_r)); // compute residuals (x - \hat{}) final RealVector[] xResidual = new RealVector[k + 1]; for (int j = 0; j <= k; j++) { xResidual[j] = x[j].subtract(_mu); } // update covariance matrices // C_j := (1-r) C_j + r (x_t - \hat{}) (x_{t-j} - \hat{})' final RealMatrix[] C = this._C; final RealVector rxResidual0 = xResidual[0].mapMultiply(_r); // r (x_t - \hat{}) for (int j = 0; j <= k; j++) { RealMatrix Cj = C[j]; if (Cj == null) { C[j] = rxResidual0.outerProduct(x[j].subtract(_mu)); } else { C[j] = Cj.scalarMultiply(1.d - _r).add(rxResidual0.outerProduct(x[j].subtract(_mu))); } } // solve A in the following Yule-Walker equation // C_j = _{i=1}^{k} A_i C_{j-i} where j = 1..k, C_{-i} = C_i' /* * /C_1\ /A_1\ /C_0 |C_1' |C_2' | . . . |C_{k-1}' \ * |---| |---| |--------+--------+--------+ +---------| * |C_2| |A_2| |C_1 |C_0 |C_1' | . | * |---| |---| |--------+--------+--------+ . | * |C_3| = |A_3| |C_2 |C_1 |C_0 | . | * | . | | . | |--------+--------+--------+ | * | . | | . | | . . | * | . | | . | | . . | * |---| |---| |--------+ +--------| * \C_k/ \A_k/ \C_{k-1} | . . . |C_0 / */ RealMatrix[][] rhs = MatrixUtils.toeplitz(C, k); RealMatrix[] lhs = Arrays.copyOfRange(C, 1, k + 1); RealMatrix R = MatrixUtils.combinedMatrices(rhs, dims); RealMatrix L = MatrixUtils.combinedMatrices(lhs); RealMatrix A = MatrixUtils.solve(L, R, false); // estimate x // \hat{x} = \hat{} + _{i=1}^k A_i (x_{t-i} - \hat{}) RealVector x_hat = _mu.copy(); for (int i = 0; i < k; i++) { int offset = i * dims; RealMatrix Ai = A.getSubMatrix(offset, offset + dims - 1, 0, dims - 1); x_hat = x_hat.add(Ai.operate(xResidual[i + 1])); } // update model covariance // := (1-r) + r (x - \hat{x}) (x - \hat{x})' RealVector xEstimateResidual = x_t.subtract(x_hat); this._sigma = _sigma.scalarMultiply(1.d - _r) .add(xEstimateResidual.mapMultiply(_r).outerProduct(xEstimateResidual)); return x_hat; }
From source file:edu.oregonstate.eecs.mcplan.domains.racetrack.RacetrackState.java
public RealVector velocity() { return new ArrayRealVector(new double[] { car_dx, car_dy }); }
From source file:lucene.CosineDocumentSimilarity.java
RealVector toRealVector(Map<String, Integer> map) { RealVector vector = new ArrayRealVector(terms.size()); int i = 0;/*from w ww.j a v a2 s .c om*/ for (String term : terms) { int value = map.containsKey(term) ? map.get(term) : 0; vector.setEntry(i++, value); } return (RealVector) vector.mapDivide(vector.getL1Norm()); }
From source file:com.github.thorbenlindhauer.factor.CanonicalGaussianFactor.java
/** * mapping must have the size of the new vector; maps a vector to a new size by applying the mapping of the positions * and fills the remaining places with 0 values *//* w w w.j a va 2 s . com*/ protected static RealVector padVector(final RealVector vector, int newSize, final int[] mapping) { final RealVector newVector = new ArrayRealVector(newSize); newVector.walkInOptimizedOrder(new RealVectorChangingVisitor() { @Override public double visit(int index, double value) { if (mapping[index] >= 0) { return vector.getEntry(mapping[index]); } else { return 0; } } @Override public void start(int dimension, int start, int end) { } @Override public double end() { return 0; } }); return newVector; }
From source file:ir.project.helper.SVDecomposition.java
public TFIDFBookVector changeQuery(TFIDFBookVector query) { // Perform the necessary opperations to change the vector to the LSA space Matrix q = SparseMatrix.Factory.zeros(query.getVector().getDimension(), 1); for (int i = 0; i < query.getVector().getDimension(); i++) { q.setAsDouble(query.getVector().getEntry(i), i, 0); }//from w w w .java 2 s. com // Now change the query: // new q = S.inv * U.transpose * q Matrix new_q = this.Sk.inv().mtimes(Uk.transpose()).mtimes(q); // Reconstruct the TFIDF Vector RealVector r = new ArrayRealVector(query.getVector().getDimension()); // TODO Make sparse (Might not be neccessary if the vector has barely any zeroes for (int i = 0; i < new_q.getRowCount(); i++) { r.setEntry(i, new_q.getAsDouble(i, 0)); } query.setVector(r); return query; }
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)); }//from ww w . j ava 2 s. c o m 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.utexas.cs.tactex.BrokerUtilsTest.java
@Test public void test_rotateWeeklyRecordAndAppendTillEndOfDay() { // this test is very similar and is based on // EnergyPredictionTest.testEnergyPredictionOfAboutOneWeek() // we moved it here after refactoring a method to BrokersUtils ////from ww w . j av a 2 s . co m // initialize an record vector where the value of an // entry is its index ArrayRealVector record = new ArrayRealVector(7 * 24); for (int i = 0; i < record.getDimension(); ++i) { record.setEntry(i, i); } int currentTimeslot; ArrayRealVector expected; ArrayRealVector actual; currentTimeslot = 7 * 24 - 1; expected = new ArrayRealVector(record); actual = BrokerUtils.rotateWeeklyRecordAndAppendTillEndOfDay(record, currentTimeslot); assertArrayEquals("no rotation at the beginning of week", expected.toArray(), actual.toArray(), 1e-6); currentTimeslot = 1 * 24 - 1; // actual actual = BrokerUtils.rotateWeeklyRecordAndAppendTillEndOfDay(record, currentTimeslot); // prepare expected RealVector slice1 = record.getSubVector(1 * 24, 7 * 24 - 24); expected.setSubVector(0, slice1); expected.setSubVector(slice1.getDimension(), record.getSubVector(0, 24)); assertArrayEquals("end of first day results in days 2,...,7,1", expected.toArray(), actual.toArray(), 1e-6); currentTimeslot = 6 * 24 - 1; // actual actual = BrokerUtils.rotateWeeklyRecordAndAppendTillEndOfDay(record, currentTimeslot); // prepare expected slice1 = record.getSubVector(6 * 24, 7 * 24 - 6 * 24); expected.setSubVector(0, slice1); expected.setSubVector(slice1.getDimension(), record.getSubVector(0, 6 * 24)); assertArrayEquals("end of 6th day results in days 7,1,...,6", expected.toArray(), actual.toArray(), 1e-6); currentTimeslot = 0; // predict actual = BrokerUtils.rotateWeeklyRecordAndAppendTillEndOfDay(record, currentTimeslot); // prepare expected slice1 = record.getSubVector(1, 7 * 24 - 1); expected.setSubVector(0, slice1); expected.setSubVector(slice1.getDimension(), record.getSubVector(0, 1)); expected.append(record.getSubVector(1, 24 - 1)); assertArrayEquals("if not at day start, appending until the end of day", expected.toArray(), actual.toArray(), 1e-6); }
From source file:edu.utexas.cs.tactex.utils.BrokerUtils.java
/** * Rotates a weekly record to start from the next timeslot * and append the last day to continue until the end of the day * //from w w w . ja va2s . c o m * @param energy * @param currentTimeslot * @return */ public static ArrayRealVector rotateWeeklyRecordAndAppendTillEndOfDay(RealVector record, int currentTimeslot) { // sanity check if (record.getDimension() != 7 * 24) { log.error("record dimension is not 7*24, not sure if code robust to that?"); } int predictionStartWeeklyHour = (currentTimeslot + 1) % (record.getDimension()); ArrayRealVector copy = new ArrayRealVector(record.getDimension()); // rotate to start from current moment RealVector slice1 = record.getSubVector(predictionStartWeeklyHour, record.getDimension() - predictionStartWeeklyHour); RealVector slice2 = record.getSubVector(0, predictionStartWeeklyHour); copy.setSubVector(0, slice1); copy.setSubVector(slice1.getDimension(), slice2); return copy; }
From source file:com.opengamma.strata.math.impl.util.CommonsMathWrapper.java
/** * Wraps a vector./* w ww . java 2 s.co m*/ * * @param x an OG vector of doubles * @return a Commons vector */ public static RealVector wrap(DoubleArray x) { ArgChecker.notNull(x, "x"); return new ArrayRealVector(x.toArrayUnsafe()); // cloned in ArrayRealVector constructor }