Example usage for org.apache.commons.math3.linear RealVector dotProduct

List of usage examples for org.apache.commons.math3.linear RealVector dotProduct

Introduction

In this page you can find the example usage for org.apache.commons.math3.linear RealVector dotProduct.

Prototype

public double dotProduct(RealVector v) throws DimensionMismatchException 

Source Link

Document

Compute the dot product of this vector with v .

Usage

From source file:com.github.thorbenlindhauer.factor.CanonicalGaussianFactor.java

@Override
public double getValueForAssignment(double[] assignment) {
    RealVector assignmentVector = new ArrayRealVector(assignment);

    double exponent = -0.5d * assignmentVector.dotProduct(precisionMatrix.operate(assignmentVector))
            + scaledMeanVector.dotProduct(assignmentVector) + normalizationConstant;

    return Math.exp(exponent);
}

From source file:com.github.thorbenlindhauer.factor.CanonicalGaussianFactor.java

@Override
public GaussianFactor observation(Scope observationScope, double[] values) {
    if (observationScope.getVariables().size() != values.length) {
        throw new ModelStructureException("Observed variables and values do not match");
    }/*ww  w  .  ja  v  a  2 s.  c om*/

    if (scope.intersect(observationScope).isEmpty()) {
        return this;
    }

    RealVector observationVector = new ArrayRealVector(values);

    Scope newScope = scope.reduceBy(observationScope);

    // reduce K matrix to values that are in the scope to keep
    int[] scopeMapping = newScope.createContinuousVariableMapping(this.scope);
    RealMatrix scopeValuesMatrix = precisionMatrix.getSubMatrix(scopeMapping, scopeMapping);

    int[] observationScopeMapping = observationScope.createContinuousVariableMapping(this.scope);
    // xyMatrix
    RealMatrix scopeObservationMatrix = precisionMatrix.getSubMatrix(scopeMapping, observationScopeMapping);

    // h_x
    RealVector scopeMeanVector = getSubVector(scaledMeanVector, scopeMapping);
    RealVector newMeanVector = scopeMeanVector.subtract(scopeObservationMatrix.operate(observationVector));

    // g
    RealVector observationMeanVector = getSubVector(scaledMeanVector, observationScopeMapping);
    RealMatrix observationMatrix = precisionMatrix.getSubMatrix(observationScopeMapping,
            observationScopeMapping);
    double newNormalizationConstant = normalizationConstant
            + observationMeanVector.dotProduct(observationVector)
            - 0.5d * (observationVector.dotProduct(observationMatrix.operate(observationVector)));

    return new CanonicalGaussianFactor(newScope, scopeValuesMatrix, newMeanVector, newNormalizationConstant);
}

From source file:com.github.thorbenlindhauer.factor.CanonicalGaussianFactor.java

@Override
public GaussianFactor marginal(Scope marginalizationScope) {
    // the following assumes that the precision matrix (and mean vector) can be restructured as follows:
    // ( SUBMATRIX_XX SUBMATRIX_XY )
    // ( SUBMATRIX_YX SUBMATRIX_YY )
    // where X indicates the entries for the variables that are kept (i.e. in the scope argument) and
    // Y the variables that are marginalized out

    if (marginalizationScope.contains(scope)) {
        return this;
    }/*from w  w  w . j  a v  a  2 s . c  om*/

    Scope newScope = scope.intersect(marginalizationScope);
    Scope scopeToMarginalize = scope.reduceBy(newScope);

    int[] xMapping = newScope.createContinuousVariableMapping(scope);
    RealMatrix xxMatrix = precisionMatrix.getSubMatrix(xMapping, xMapping);

    int[] yMapping = scopeToMarginalize.createContinuousVariableMapping(scope);
    RealMatrix yyMatrix = precisionMatrix.getSubMatrix(yMapping, yMapping);

    RealMatrix xyMatrix = precisionMatrix.getSubMatrix(xMapping, yMapping);
    RealMatrix yxMatrix = precisionMatrix.getSubMatrix(yMapping, xMapping);

    MathUtil yyUtil = new MathUtil(yyMatrix);
    RealMatrix yyInverse = yyUtil.invert();
    RealMatrix newPrecisionMatrix = xxMatrix.subtract(xyMatrix.multiply(yyInverse.multiply(yxMatrix)));

    RealVector xVector = getSubVector(scaledMeanVector, xMapping);
    RealVector yVector = getSubVector(scaledMeanVector, yMapping);

    RealVector newScaledMeanVector = xVector.subtract(xyMatrix.operate(yyInverse.operate(yVector)));

    MathUtil inverseUtil = new MathUtil(yyInverse.scalarMultiply(2.0d * Math.PI));
    double newNormalizationConstant = normalizationConstant
            + 0.5d * (Math.log(inverseUtil.determinant()) + yVector.dotProduct(yyInverse.operate(yVector)));

    return new CanonicalGaussianFactor(newScope, newPrecisionMatrix, newScaledMeanVector,
            newNormalizationConstant);
}

From source file:com.cloudera.oryx.kmeans.computation.cluster.KSketchIndex.java

public Distance getDistance(RealVector vec, int id, boolean approx) {
    double distance = Double.POSITIVE_INFINITY;
    int closestPoint = -1;
    if (approx) {
        if (updated) {
            rebuildIndices();//from   www .  ja  v a  2  s .  c  o  m
        }

        BitSet q = index(vec);
        List<BitSet> index = indices.get(id);
        SortedSet<Idx> lookup = Sets.newTreeSet();
        for (int j = 0; j < index.size(); j++) {
            Idx idx = new Idx(hammingDistance(q, index.get(j)), j);
            if (lookup.size() < projectionSamples) {
                lookup.add(idx);
            } else if (idx.compareTo(lookup.last()) < 0) {
                lookup.add(idx);
                lookup.remove(lookup.last());
            }
        }

        List<RealVector> p = points.get(id);
        List<Double> lsq = lengthSquared.get(id);
        for (Idx idx : lookup) {
            double lenSq = lsq.get(idx.getIndex());
            double length = vec.getNorm();
            double d = length * length + lenSq - 2 * vec.dotProduct(p.get(idx.getIndex()));
            if (d < distance) {
                distance = d;
                closestPoint = idx.getIndex();
            }
        }
    } else { // More expensive exact computation
        List<RealVector> px = points.get(id);
        List<Double> lsq = lengthSquared.get(id);
        for (int j = 0; j < px.size(); j++) {
            RealVector p = px.get(j);
            double lenSq = lsq.get(j);
            double length = vec.getNorm();
            double d = length * length + lenSq - 2 * vec.dotProduct(p);
            if (d < distance) {
                distance = d;
                closestPoint = j;
            }
        }
    }

    return new Distance(distance, closestPoint);
}

From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java

/**
 * Minimize x subject to // w  w  w . j ava 2  s.  c  om
 * x+y=4, 
 * x-y=2. 
 * Should return (3,1).
 * This problem is the same as NewtonLEConstrainedISPTest.testOptimize2()
 * and can be solved only with the use of a linear presolving phase:
 * if passed directly to the solver, it will fail because JOptimizer
 * does not want rank-deficient inequalities matrices like that of this problem.
 */
public void testSimple4() throws Exception {
    log.debug("testSimple4");
    double[] c = new double[] { 1, 0 };
    double[][] A = new double[][] { { 1.0, 1.0 }, { 1.0, -1.0 } };
    double[] b = new double[] { 4.0, 2.0 };

    LPOptimizationRequest or = new LPOptimizationRequest();
    or.setC(c);
    or.setA(A);
    or.setB(b);
    or.setLb(new double[] { -100, -100 });
    or.setUb(new double[] { 100, 100 });
    or.setCheckKKTSolutionAccuracy(true);
    or.setDumpProblem(true);

    //optimization
    LPPrimalDualMethod opt = new LPPrimalDualMethod();
    opt.setLPOptimizationRequest(or);
    int returnCode = opt.optimize();
    if (returnCode == OptimizationResponse.FAILED) {
        fail();
    }
    LPOptimizationResponse response = opt.getLPOptimizationResponse();
    double[] sol = response.getSolution();
    RealVector cVector = new ArrayRealVector(c);
    RealVector solVector = new ArrayRealVector(sol);
    double value = cVector.dotProduct(solVector);
    log.debug("sol   : " + ArrayUtils.toString(sol));
    log.debug("value : " + value);

    assertEquals(2, sol.length);
    assertEquals(3.0, sol[0], or.getTolerance());
    assertEquals(1.0, sol[1], or.getTolerance());
}

From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java

/**
 * Simple problem in the form/*  w w  w .j ava 2 s  . com*/
 * min(-10*x -10*y) s.t.
 * 0 <= x <= 1
 * 0 <= y <= 1
 * NB: no equalities, no inequalities, just bounds    
 */
public void testSimple5() throws Exception {
    log.debug("testSimple5");

    double[] c = new double[] { -10, -10 };
    double[] lb = new double[] { 0, 0 };
    double[] ub = new double[] { 1, 1 };
    double minLb = LPPrimalDualMethod.DEFAULT_MIN_LOWER_BOUND;
    double maxUb = LPPrimalDualMethod.DEFAULT_MAX_UPPER_BOUND;

    LPOptimizationRequest or = new LPOptimizationRequest();
    or.setC(c);
    or.setLb(lb);
    or.setUb(ub);
    or.setCheckKKTSolutionAccuracy(true);
    or.setToleranceFeas(1.E-7);
    or.setTolerance(1.E-7);
    or.setDumpProblem(true);
    //or.setPresolvingDisabled(true);
    or.setRescalingDisabled(true);

    //optimization
    LPPrimalDualMethod opt = new LPPrimalDualMethod(minLb, maxUb);

    opt.setLPOptimizationRequest(or);
    int returnCode = opt.optimize();

    if (returnCode == OptimizationResponse.FAILED) {
        fail();
    }

    LPOptimizationResponse response = opt.getLPOptimizationResponse();
    double[] sol = response.getSolution();
    RealVector cVector = new ArrayRealVector(c);
    RealVector solVector = new ArrayRealVector(sol);
    double value = cVector.dotProduct(solVector);
    log.debug("sol   : " + ArrayUtils.toString(sol));
    log.debug("value : " + value);

    assertEquals(2, sol.length);
    assertEquals(1, sol[0], or.getTolerance());
    assertEquals(1, sol[1], or.getTolerance());
    assertEquals(-20, value, or.getTolerance());
}

From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java

/**
 * Simple problem in the form// w  w  w.j  ava 2  s  . c om
 * min(c.x) s.t.
 * A.x = b
 * x >=0
 */
public void testSimple2() throws Exception {
    log.debug("testSimple2");

    double[] c = new double[] { -1, -2 };
    double[][] A = new double[][] { { 1, 1 } };
    double[] b = new double[] { 1 };

    LPOptimizationRequest or = new LPOptimizationRequest();
    or.setC(c);
    or.setA(A);
    or.setB(b);
    or.setLb(new double[] { 0, 0 });
    //or.setUb(new double[]{Double.NaN, Double.NaN});
    //or.setInitialPoint(new double[] { 0.9, 0.1 });
    //or.setNotFeasibleInitialPoint(new double[] { -0.5, 1.5 });
    or.setCheckKKTSolutionAccuracy(true);
    or.setToleranceFeas(1.E-7);
    or.setTolerance(1.E-7);
    or.setDumpProblem(true);
    //or.setPresolvingDisabled(true);

    //optimization
    LPPrimalDualMethod opt = new LPPrimalDualMethod();

    opt.setLPOptimizationRequest(or);
    int returnCode = opt.optimize();

    if (returnCode == OptimizationResponse.FAILED) {
        fail();
    }

    LPOptimizationResponse response = opt.getLPOptimizationResponse();
    double[] sol = response.getSolution();
    RealVector cVector = new ArrayRealVector(c);
    RealVector solVector = new ArrayRealVector(sol);
    double value = cVector.dotProduct(solVector);
    log.debug("sol   : " + ArrayUtils.toString(sol));
    log.debug("value : " + value);

    assertEquals(2, sol.length);
    assertEquals(0, sol[0], or.getTolerance());
    assertEquals(1, sol[1], or.getTolerance());
    assertEquals(-2, value, or.getTolerance());
}

From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java

/**
 * Simple problem in the form/*  w  w w.  j  av a 2s . com*/
 * min(c.x) s.t.
 * A.x = b
 * lb <= x <= ub
 * with a free variable.
 * This test shows that it is necessary to provide bounds for all the variables in order to avoid singular KKT systems.
 */
public void testSimple3() throws Exception {
    log.debug("testSimple3");

    double[] c = new double[] { -1, -2, 0 };
    double[][] A = new double[][] { { 1, 1, 0 } };
    double[] b = new double[] { 1 };
    //double minLb = LPPrimalDualMethod.DEFAULT_MIN_LOWER_BOUND;
    //double maxUb = LPPrimalDualMethod.DEFAULT_MAX_UPPER_BOUND;
    double minLb = -99;
    double maxUb = +99;

    LPOptimizationRequest or = new LPOptimizationRequest();
    or.setC(c);
    or.setA(A);
    or.setB(b);
    or.setLb(new double[] { -1, -1, -100 });//this will be limited to minLb
    or.setUb(new double[] { 1, 1, 100 });//this will be limited to maxUb
    or.setCheckKKTSolutionAccuracy(true);
    //      or.setToleranceFeas(1.E-7);
    //      or.setTolerance(1.E-7);
    or.setDumpProblem(true);
    //or.setPresolvingDisabled(true);
    //or.setRescalingDisabled(true);

    //optimization
    LPPrimalDualMethod opt = new LPPrimalDualMethod(minLb, maxUb);
    opt.setLPOptimizationRequest(or);
    int returnCode = opt.optimize();
    if (returnCode == OptimizationResponse.FAILED) {
        fail();
    }
    LPOptimizationResponse response = opt.getLPOptimizationResponse();
    double[] sol = response.getSolution();
    RealVector cVector = new ArrayRealVector(c);
    RealVector solVector = new ArrayRealVector(sol);
    double value = cVector.dotProduct(solVector);
    log.debug("sol   : " + ArrayUtils.toString(sol));
    log.debug("value : " + value);

    assertEquals(3, sol.length);
    assertEquals(0, sol[0], or.getTolerance());
    assertEquals(1, sol[1], or.getTolerance());
    assertEquals(-2, value, or.getTolerance());
}

From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java

/**
 * Simple problem in the form/*from w w w .jav a 2  s  .  co m*/
 * min(-100x + y) s.t.
 * x - y = 0
 * 0 <= x <= 1
 * 0 <= y <= 1
 * 
 */
public void testSimple1() throws Exception {
    log.debug("testSimple1");

    double[] c = new double[] { -100, 1 };
    double[][] A = new double[][] { { 1, -1 } };
    double[] b = new double[] { 0 };
    double[] lb = new double[] { 0, 0 };
    double[] ub = new double[] { 1, 1 };
    double minLb = LPPrimalDualMethod.DEFAULT_MIN_LOWER_BOUND;
    double maxUb = LPPrimalDualMethod.DEFAULT_MAX_UPPER_BOUND;

    LPOptimizationRequest or = new LPOptimizationRequest();
    or.setC(c);
    or.setA(A);
    or.setB(b);
    or.setLb(lb);
    or.setUb(ub);
    or.setCheckKKTSolutionAccuracy(true);
    or.setToleranceFeas(1.E-7);
    or.setTolerance(1.E-7);
    or.setDumpProblem(true);
    //or.setPresolvingDisabled(true);
    or.setRescalingDisabled(true);

    //optimization
    LPPrimalDualMethod opt = new LPPrimalDualMethod(minLb, maxUb);

    opt.setLPOptimizationRequest(or);
    int returnCode = opt.optimize();

    if (returnCode == OptimizationResponse.FAILED) {
        fail();
    }

    LPOptimizationResponse response = opt.getLPOptimizationResponse();
    double[] sol = response.getSolution();
    RealVector cVector = new ArrayRealVector(c);
    RealVector solVector = new ArrayRealVector(sol);
    double value = cVector.dotProduct(solVector);
    log.debug("sol   : " + ArrayUtils.toString(sol));
    log.debug("value : " + value);

    assertEquals(2, sol.length);
    assertEquals(1, sol[0], or.getTolerance());
    assertEquals(1, sol[1], or.getTolerance());
    assertEquals(-99, value, or.getTolerance());
}

From source file:com.joptimizer.optimizers.LPPrimalDualMethodTest.java

/**
 * Linear programming in 2D in LP form.//w  ww  .  ja  va 2  s  .com
 * This is the same problem as {@link JOptimizerTest#testLinearProgramming2D()} solved with LPPrimalDualMethod.
 */
public void testLPLinearProgramming2D() throws Exception {
    log.debug("testLPLinearProgramming2D");

    // START SNIPPET: LPLinearProgramming-1

    //Objective function
    double[] c = new double[] { -1., -1. };

    //Inequalities constraints
    double[][] G = new double[][] { { 4. / 3., -1 }, { -1. / 2., 1. }, { -2., -1. }, { 1. / 3., 1. } };
    double[] h = new double[] { 2., 1. / 2., 2., 1. / 2. };

    //Bounds on variables
    double[] lb = new double[] { 0, 0 };
    double[] ub = new double[] { 10, 10 };

    //optimization problem
    LPOptimizationRequest or = new LPOptimizationRequest();
    or.setC(c);
    or.setG(G);
    or.setH(h);
    or.setLb(lb);
    or.setUb(ub);
    or.setDumpProblem(true);

    //optimization
    LPPrimalDualMethod opt = new LPPrimalDualMethod();

    opt.setLPOptimizationRequest(or);
    int returnCode = opt.optimize();

    // END SNIPPET: LPLinearProgramming-1

    if (returnCode == OptimizationResponse.FAILED) {
        fail();
    }

    OptimizationResponse response = opt.getOptimizationResponse();
    double[] sol = response.getSolution();
    RealVector cVector = new ArrayRealVector(c);
    RealVector solVector = new ArrayRealVector(sol);
    double value = cVector.dotProduct(solVector);
    log.debug("sol   : " + ArrayUtils.toString(sol));
    log.debug("value : " + value);
    assertEquals(1.5, sol[0], or.getTolerance());
    assertEquals(0.0, sol[1], or.getTolerance());
}