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.joptimizer.functions.SOCPLogarithmicBarrier.java

public double[] gradient(double[] X) {
    RealVector x = new ArrayRealVector(X);

    RealVector ret = new ArrayRealVector(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);
        RealMatrix Jacob = this.buildJ(param, x);
        int k = u.getDimension();
        RealVector G = new ArrayRealVector(k + 1);
        G.setSubVector(0, u);//from w  w  w.  ja  va  2 s  .  c om
        G.setEntry(k, -t);
        RealVector ret_i = Jacob.operate(G).mapMultiply((2. / t2uu));
        ret = ret.add(ret_i);
    }

    return ret.toArray();
}

From source file:com.joptimizer.functions.SOCPLogarithmicBarrier.java

public double value(double[] X) {
    RealVector x = new ArrayRealVector(X);

    double ret = 0;
    for (int i = 0; i < socpConstraintParametersList.size(); i++) {
        SOCPConstraintParameters param = socpConstraintParametersList.get(i);
        double t = this.buildT(param, x);
        if (t < 0) {
            return Double.NaN;
        }/* ww w .j  a v a2s  .  c  om*/
        RealVector u = this.buildU(param, x);
        double t2uu = t * t - u.dotProduct(u);
        if (t2uu <= 0) {
            return Double.NaN;
        }
        double ret_i = -Math.log(t2uu);
        ret += ret_i;
    }

    return ret;
}

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 w  ww  . jav a2  s  .  c  om*/
        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:com.mothsoft.alexis.engine.textual.DocumentFeatures.java

public double cosine(final RealVector v1, final RealVector v2) {
    final double norm = v1.getNorm();
    final double norm2 = v2.getNorm();
    final double divisor = norm * norm2;

    if (divisor == 0.0) {
        return 0;
    } else {//from www .j a  v a  2 s .c o m
        return v1.dotProduct(v2) / (divisor);
    }
}

From source file:com.opengamma.strata.math.impl.matrix.CommonsMatrixAlgebra.java

@Override
public double getInnerProduct(Matrix m1, Matrix m2) {
    ArgChecker.notNull(m1, "m1");
    ArgChecker.notNull(m2, "m2");
    if (m1 instanceof DoubleArray && m2 instanceof DoubleArray) {
        RealVector t1 = CommonsMathWrapper.wrap((DoubleArray) m1);
        RealVector t2 = CommonsMathWrapper.wrap((DoubleArray) m2);
        return t1.dotProduct(t2);
    }//from  w ww.  ja  va2 s  .  co m
    throw new IllegalArgumentException(
            "Can only find inner product of DoubleArray; have " + m1.getClass() + " and " + m2.getClass());
}

From source file:com.joptimizer.util.MPSParserNetlibTest.java

/**
 * Tests the parsing of a netlib problem.
 *//*from   w  w w  .j  a  v  a 2  s.c om*/
public void xxxtestSingleNetlib() throws Exception {
    log.debug("testSingleNetlib");
    //String problemName = "afiro";
    //String problemName = "afiroPresolved";
    //String problemName = "adlittle";
    //String problemName = "kb2";
    //String problemName = "sc50a";
    //String problemName = "sc50b";
    //String problemName = "blend";
    //String problemName = "scorpion";
    //String problemName = "recipe";
    //String problemName = "recipePresolved";
    //String problemName = "sctap1";
    //String problemName = "fit1d";
    //String problemName = "israel";
    //String problemName = "grow15";
    //String problemName = "etamacro";
    //String problemName = "pilot";
    //String problemName = "pilot4";
    //String problemName = "osa-14";
    //String problemName = "brandyPresolved";
    String problemName = "maros";

    File f = Utils.getClasspathResourceAsFile("lp" + File.separator + "netlib" + File.separator + problemName
            + File.separator + problemName + ".mps");
    MPSParser mpsParser = new MPSParser();
    mpsParser.parse(f);

    Properties expectedSolProps = null;
    try {
        //this is the solution of the mps problem given by Mathematica
        expectedSolProps = load(Utils.getClasspathResourceAsFile(
                "lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "sol.txt"));
    } catch (Exception e) {
    }

    log.debug("name: " + mpsParser.getName());
    log.debug("n   : " + mpsParser.getN());
    log.debug("meq : " + mpsParser.getMeq());
    log.debug("mieq: " + mpsParser.getMieq());
    log.debug("meq+mieq: " + (mpsParser.getMeq() + mpsParser.getMieq()));
    List<String> variablesNames = mpsParser.getVariablesNames();
    log.debug("x: " + ArrayUtils.toString(variablesNames));
    //      log.debug("c: " + ArrayUtils.toString(p.getC()));
    //      log.debug("G: " + ArrayUtils.toString(p.getG()));
    //      log.debug("h: " + ArrayUtils.toString(p.getH()));
    //      log.debug("A: " + ArrayUtils.toString(p.getA()));
    //      log.debug("b: " + ArrayUtils.toString(p.getB()));
    //      log.debug("lb:" + ArrayUtils.toString(p.getLb()));
    //      log.debug("ub:" + ArrayUtils.toString(p.getUb()));

    //check consistency: if the problem was correctly parsed, the expectedSol must be its solution
    double delta = 1.e-7;
    if (expectedSolProps != null) {
        //key = variable name
        //value = sol value
        assertEquals(expectedSolProps.size(), variablesNames.size());
        RealVector expectedSol = new ArrayRealVector(variablesNames.size());
        for (int i = 0; i < variablesNames.size(); i++) {
            expectedSol.setEntry(i, Double.parseDouble(expectedSolProps.getProperty(variablesNames.get(i))));
        }
        log.debug("expectedSol: " + ArrayUtils.toString(expectedSol.toArray()));

        //check objective function value
        Map<String, LPNetlibProblem> problemsMap = LPNetlibProblem.loadAllProblems();
        LPNetlibProblem problem = problemsMap.get(problemName);
        RealVector c = new ArrayRealVector(mpsParser.getC().toArray());
        double value = c.dotProduct(expectedSol);
        log.debug("optimalValue: " + problem.optimalValue);
        log.debug("value       : " + value);
        assertEquals(problem.optimalValue, value, delta);

        //check G.x < h
        if (mpsParser.getG() != null) {
            RealMatrix G = new Array2DRowRealMatrix(mpsParser.getG().toArray());
            RealVector h = new ArrayRealVector(mpsParser.getH().toArray());
            RealVector Gxh = G.operate(expectedSol).subtract(h);
            double maxGxh = -Double.MAX_VALUE;
            for (int i = 0; i < Gxh.getDimension(); i++) {
                //log.debug(i);
                maxGxh = Math.max(maxGxh, Gxh.getEntry(i));
                assertTrue(Gxh.getEntry(i) <= 0);
            }
            log.debug("max(G.x - h): " + maxGxh);
        }

        //check A.x = b
        if (mpsParser.getA() != null) {
            RealMatrix A = new Array2DRowRealMatrix(mpsParser.getA().toArray());
            RealVector b = new ArrayRealVector(mpsParser.getB().toArray());
            RealVector Axb = A.operate(expectedSol).subtract(b);
            double norm = Axb.getNorm();
            log.debug("||A.x -b||: " + norm);
            assertEquals(0., norm, delta * mpsParser.getN());//some more tolerance
        }

        //check upper and lower bounds
        for (int i = 0; i < mpsParser.getLb().size(); i++) {
            double di = Double.isNaN(mpsParser.getLb().getQuick(i)) ? -Double.MAX_VALUE
                    : mpsParser.getLb().getQuick(i);
            assertTrue(di <= expectedSol.getEntry(i));
        }
        for (int i = 0; i < mpsParser.getUb().size(); i++) {
            double di = Double.isNaN(mpsParser.getUb().getQuick(i)) ? Double.MAX_VALUE
                    : mpsParser.getUb().getQuick(i);
            assertTrue(di >= expectedSol.getEntry(i));
        }
    }

    Utils.writeDoubleArrayToFile(mpsParser.getC().toArray(), "target" + File.separator + "c.txt");
    Utils.writeDoubleMatrixToFile(mpsParser.getG().toArray(), "target" + File.separator + "G.csv");
    Utils.writeDoubleArrayToFile(mpsParser.getH().toArray(), "target" + File.separator + "h.txt");
    Utils.writeDoubleMatrixToFile(mpsParser.getA().toArray(), "target" + File.separator + "A.csv");
    Utils.writeDoubleArrayToFile(mpsParser.getB().toArray(), "target" + File.separator + "b.txt");
    Utils.writeDoubleArrayToFile(mpsParser.getLb().toArray(), "target" + File.separator + "lb.txt");
    Utils.writeDoubleArrayToFile(mpsParser.getUb().toArray(), "target" + File.separator + "ub.txt");
}

From source file:edu.oregonstate.eecs.mcplan.ml.KulisLowRankKernelLearner.java

@Override
public void run() {
    System.out.println("\tKLRKL run()");

    final RealMatrix B = MatrixUtils.createRealIdentityMatrix(r_);
    final double[] nu = new double[Nc_];
    final int[] idx = Fn.range(0, Nc_);

    int iter_count = 0;
    while (iter_count++ < iteration_limit_) {
        System.out.println("\tIteration " + iter_count);
        Fn.shuffle(rng_, idx);/* ww w  . ja  v a2s .c  o m*/
        double update_magnitude = 0.0;
        for (int c = 0; c < Nc_; ++c) {
            final int[] constraint;
            final int delta;
            if (c < S_.size()) {
                constraint = S_.get(c);
                delta = 1;
            } else {
                constraint = D_.get(c - S_.size());
                delta = -1;
            }
            final int i = constraint[0];
            final int j = constraint[1];
            final RealVector v = G0_.getRowVector(i).subtract(G0_.getRowVector(j));
            final RealVector w = B.transpose().operate(v);
            final double p = w.dotProduct(w);
            //            if( p == 0.0 ) {
            //               System.out.println( "! p == 0.0" );
            //            }
            //            if( xi_[c] == 0.0 ) {
            //               System.out.println( "! xi_[c] == 0.0" );
            //            }
            final double alpha;
            if (p == 0.0) {
                alpha = nu[c];
            } else {
                // FIXME: The paper didn't include cannot-link constraints
                // in their pseudocode. I'm NOT HANDLING THEM right now, because
                // to do so would require re-deriving part of the algorithm.
                alpha = Math.min(nu[c], (gamma_ / (1.0 + gamma_) * ((1.0 / p) - (1.0 / u_))));
            }
            nu[c] -= alpha;
            final double beta = alpha / (1.0 - (alpha * p));
            choleskyUpdate(r_, alpha, w, B);
            update_magnitude += alpha * alpha; //update.getFrobeniusNorm();
        }
        // Declare convergence if all updates were small.
        if (Math.sqrt(update_magnitude) < convergence_tolerance_) {
            break;
        }
    }

    G_ = G0_.multiply(B);
    A_ = G_.transpose().multiply(G_);
    System.out.println("Metric:");
    System.out.println(A_);
}

From source file:com.joptimizer.functions.SOCPLogarithmicBarrier.java

/**
 * Calculates the initial value for the s parameter in Phase I.
 * Return s = max(||Ai.x+bi|| - (ci.x+di))
 * @see "S.Boyd and L.Vandenberghe, Convex Optimization, 11.6.2"
 *///from  w w  w .ja  va2s  .c om
public double calculatePhase1InitialFeasiblePoint(double[] originalNotFeasiblePoint, double tolerance) {
    double s = -Double.MAX_VALUE;
    RealVector x = new ArrayRealVector(originalNotFeasiblePoint);
    for (int i = 0; i < socpConstraintParametersList.size(); i++) {
        SOCPConstraintParameters param = socpConstraintParametersList.get(i);
        RealMatrix A = param.getA();
        RealVector b = param.getB();
        RealVector c = param.getC();
        double d = param.getD();
        s = Math.max(s,
                (A.operate(x).subtract(b).getNorm() - (c.dotProduct(x) + d)) * Math.pow(tolerance, -0.5));
    }
    return s;
}

From source file:gamlss.utilities.WLSMultipleLinearRegression.java

/**
* <p>Calculates the variance of the error term.</p>
* Uses the formula <pre>//  w ww .  j av a 2  s .co  m
* var(u) = u &middot; u / (n - k)
* </pre>
* where n and k are the row and column dimensions of the design
* matrix X.
*
* @return error variance estimate or Double.NaN if no applicable
* @since 2.2
*/
@Override
protected double calculateErrorVariance() {
    if (copyOriginal) {
        RealVector residuals = calculateResiduals();
        return residuals.dotProduct(residuals) / (X.getRowDimension() - X.getColumnDimension());
    }
    return Double.NaN;
}

From source file:gamlss.utilities.WLSMultipleLinearRegression.java

/**
* {@inheritDoc}//from w  ww.  j  ava2s.c  o  m
* returns Double.NaN if no applicable 
*/
@Override
public double calculateResidualSumOfSquares() {
    if (this.copyOriginal) {
        final RealVector residuals = calculateResiduals();
        return residuals.dotProduct(residuals);
    }
    return Double.NaN;
}