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

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

Introduction

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

Prototype

public double[] toArray() 

Source Link

Document

Convert the vector to an array of double s.

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  . j ava 2s  . com
        G.setEntry(k, -t);
        RealVector ret_i = Jacob.operate(G).mapMultiply((2. / t2uu));
        ret = ret.add(ret_i);
    }

    return ret.toArray();
}

From source file:edu.stanford.cfuller.imageanalysistools.filter.LocalBackgroundEstimationFilter.java

/**
 * Applies the LocalBackgroundEstimationFilter to an Image.
 * @param im    The Image that will be replaced by the output Image.  This can be anything of the correct dimensions except a shallow copy of the reference Image.
 *//*  www.  ja v  a  2 s  .  co  m*/
@Override
public void apply(WritableImage im) {

    if (this.referenceImage == null) {
        throw new ReferenceImageRequiredException(
                "LocalBackgroundEstimationFilter requires a reference image.");
    }

    edu.stanford.cfuller.imageanalysistools.image.Histogram h = new edu.stanford.cfuller.imageanalysistools.image.Histogram(
            this.referenceImage);

    int numPixelsInBox = boxSize * boxSize;

    ImageCoordinate ic = this.referenceImage.getDimensionSizes();

    ImageCoordinate icnew = ImageCoordinate.createCoordXYZCT(ic.get(ImageCoordinate.X) + 2 * boxSize,
            ic.get(ImageCoordinate.Y) + 2 * boxSize, ic.get(ImageCoordinate.Z), ic.get(ImageCoordinate.C),
            ic.get(ImageCoordinate.T));

    WritableImage padded = ImageFactory.createWritable(icnew, -1.0f);

    float maxValue = 0;

    for (ImageCoordinate i : this.referenceImage) {

        icnew.quickSet(ImageCoordinate.X, i.quickGet(ImageCoordinate.X) + boxSize);
        icnew.quickSet(ImageCoordinate.Y, i.quickGet(ImageCoordinate.Y) + boxSize);
        icnew.quickSet(ImageCoordinate.Z, i.quickGet(ImageCoordinate.Z));
        icnew.quickSet(ImageCoordinate.C, i.quickGet(ImageCoordinate.C));
        icnew.quickSet(ImageCoordinate.T, i.quickGet(ImageCoordinate.T));

        padded.setValue(icnew, this.referenceImage.getValue(i));

        if (this.referenceImage.getValue(i) > maxValue)
            maxValue = this.referenceImage.getValue(i);

    }

    RealVector overallCounts = new org.apache.commons.math3.linear.ArrayRealVector(h.getMaxValue() + 1);

    RealMatrix countsByRow = new org.apache.commons.math3.linear.Array2DRowRealMatrix(2 * boxSize + 1,
            h.getMaxValue() + 1);

    //loop over columns

    for (int i = boxSize; i < im.getDimensionSizes().quickGet(ImageCoordinate.X) + boxSize; i++) {

        overallCounts.mapMultiplyToSelf(0.0);
        double[] overallCounts_a = overallCounts.toArray();
        countsByRow = countsByRow.scalarMultiply(0.0);
        double[][] countsByRow_a = countsByRow.getData();

        int countsByRow_rowZero_pointer = 0;

        for (int m = i - boxSize; m <= i + boxSize; m++) {
            for (int n = 0; n < 2 * boxSize + 1; n++) {
                icnew.quickSet(ImageCoordinate.X, m);
                icnew.quickSet(ImageCoordinate.Y, n);
                int value = (int) padded.getValue(icnew);

                if (value == -1)
                    continue;

                overallCounts_a[value]++;
                countsByRow_a[(n + countsByRow_rowZero_pointer) % countsByRow.getRowDimension()][value]++;

            }
        }

        int currMedian = 0;
        int runningSum = 0;
        int k = 0;

        while (runningSum < (numPixelsInBox >> 1)) {
            runningSum += overallCounts_a[k++];
        }

        runningSum -= overallCounts_a[k - 1];

        currMedian = k - 1;

        icnew.quickSet(ImageCoordinate.X, i - boxSize);
        icnew.quickSet(ImageCoordinate.Y, 0);

        im.setValue(icnew, currMedian);

        int num_rows = countsByRow.getRowDimension();

        for (int j = boxSize + 1; j < im.getDimensionSizes().quickGet(ImageCoordinate.Y) + boxSize; j++) {

            double[] toRemove = countsByRow_a[(countsByRow_rowZero_pointer) % num_rows];

            for (int oc_counter = 0; oc_counter < overallCounts_a.length; oc_counter++) {
                overallCounts_a[oc_counter] -= toRemove[oc_counter];
            }

            for (int c = 0; c < toRemove.length; c++) {
                if (c < currMedian) {
                    runningSum -= toRemove[c];
                }

                countsByRow_a[countsByRow_rowZero_pointer % num_rows][c] *= 0.0;
            }

            countsByRow_rowZero_pointer++;

            for (int c = i - boxSize; c <= i + boxSize; c++) {
                icnew.quickSet(ImageCoordinate.X, c);
                icnew.quickSet(ImageCoordinate.Y, j + boxSize);
                int value = (int) padded.getValue(icnew);

                if (value == -1)
                    continue;

                countsByRow_a[(countsByRow_rowZero_pointer + num_rows - 1) % num_rows][value] += 1;

                overallCounts_a[value]++;

                if (value < currMedian) {
                    runningSum++;
                }

            }

            //case 1: runningSum > half of box

            if (runningSum > (numPixelsInBox >> 1)) {

                k = currMedian - 1;
                while (runningSum > (numPixelsInBox >> 1)) {

                    runningSum -= overallCounts_a[k--];
                }

                currMedian = k + 1;

            } else if (runningSum < (numPixelsInBox >> 1)) { // case 2: runningSum < half of box

                k = currMedian;

                while (runningSum < (numPixelsInBox >> 1)) {

                    runningSum += overallCounts_a[k++];
                }

                currMedian = k - 1;

                runningSum -= overallCounts_a[k - 1];

            }

            //cast 3: spot on, do nothing

            icnew.quickSet(ImageCoordinate.X, i - boxSize);
            icnew.quickSet(ImageCoordinate.Y, j - boxSize);

            im.setValue(icnew, currMedian);

        }

    }

    icnew.recycle();

}

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

/**
 * Tests the presolving of a netlib problem.
 * If checkExpectedSolution, the presolving is checked step by step against 
 * a (beforehand) known solution of the problem. 
 * NOTE: this known solution might differ from the solution given by the presolver 
 * (e.g. in the presence of a weakly dominated column @see {@link LPPresolver#removeDominatedColumns}, 
 * or if it is calculated with simplex method 
 * or if bounds are not exactly the same), so sometimes it is not a good test. 
 *//*  w w w.  j av a2  s .  co m*/
public void doTesting(String problemName, boolean checkExpectedSolution, double myExpectedTolerance)
        throws Exception {
    log.debug("doTesting: " + problemName);

    int s = (int) Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator + problemName
            + File.separator + "standardS.txt")[0];
    double[] c = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardC.txt");
    double[][] A = Utils.loadDoubleMatrixFromFile(
            "lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardA.csv",
            ",".charAt(0));
    double[] b = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "standardB.txt");
    double[] lb = Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator + problemName
            + File.separator + "standardLB.txt");
    double[] ub = Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator + problemName
            + File.separator + "standardUB.txt");
    double[] expectedSolution = Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator
            + problemName + File.separator + "standardSolution.txt");
    double expectedValue = Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator
            + problemName + File.separator + "standardValue.txt")[0];
    double expectedTolerance = Utils.loadDoubleArrayFromFile("lp" + File.separator + "netlib" + File.separator
            + problemName + File.separator + "standardTolerance.txt")[0];

    //in order to compare with tha Math results, we must have the same bounds
    for (int i = 0; i < lb.length; i++) {
        if (Double.isNaN(lb[i])) {
            lb[i] = -9999999d; //the same as the notebook value
        }
    }
    for (int i = 0; i < ub.length; i++) {
        if (Double.isNaN(ub[i])) {
            ub[i] = +9999999d; //the same as the notebook value
        }
    }

    RealMatrix AMatrix = MatrixUtils.createRealMatrix(A);
    RealVector bVector = MatrixUtils.createRealVector(b);
    //expectedTolerance = Math.max(expectedTolerance,   AMatrix.operate(MatrixUtils.createRealVector(expectedSolution)).subtract(bVector).getNorm());
    expectedTolerance = Math.max(1.e-9, expectedTolerance);

    // must be: A pXn with rank(A)=p < n
    QRSparseFactorization qr = new QRSparseFactorization(new SparseDoubleMatrix2D(A));
    qr.factorize();
    log.debug("p        : " + AMatrix.getRowDimension());
    log.debug("n        : " + AMatrix.getColumnDimension());
    log.debug("full rank: " + qr.hasFullRank());

    LPPresolver lpPresolver = new LPPresolver();
    lpPresolver.setNOfSlackVariables((short) s);
    if (checkExpectedSolution) {
        lpPresolver.setExpectedSolution(expectedSolution);// this is just for test!
        lpPresolver.setExpectedTolerance(myExpectedTolerance);// this is just for test!
    }
    // lpPresolver.setAvoidFillIn(true);
    // lpPresolver.setZeroTolerance(1.e-13);
    lpPresolver.presolve(c, A, b, lb, ub);
    int n = lpPresolver.getPresolvedN();
    DoubleMatrix1D presolvedC = lpPresolver.getPresolvedC();
    DoubleMatrix2D presolvedA = lpPresolver.getPresolvedA();
    DoubleMatrix1D presolvedB = lpPresolver.getPresolvedB();
    DoubleMatrix1D presolvedLb = lpPresolver.getPresolvedLB();
    DoubleMatrix1D presolvedUb = lpPresolver.getPresolvedUB();
    DoubleMatrix1D presolvedYlb = lpPresolver.getPresolvedYlb();
    DoubleMatrix1D presolvedYub = lpPresolver.getPresolvedYub();
    DoubleMatrix1D presolvedZlb = lpPresolver.getPresolvedZlb();
    DoubleMatrix1D presolvedZub = lpPresolver.getPresolvedZub();
    log.debug("n  : " + n);
    if (log.isDebugEnabled() && n > 0) {
        log.debug("presolvedC  : " + ArrayUtils.toString(presolvedC.toArray()));
        log.debug("presolvedA  : " + ArrayUtils.toString(presolvedA.toArray()));
        log.debug("presolvedB  : " + ArrayUtils.toString(presolvedB.toArray()));
        log.debug("presolvedLb : " + ArrayUtils.toString(presolvedLb.toArray()));
        log.debug("presolvedUb : " + ArrayUtils.toString(presolvedUb.toArray()));
        log.debug("presolvedYlb: " + ArrayUtils.toString(presolvedYlb.toArray()));
        log.debug("presolvedYub: " + ArrayUtils.toString(presolvedYub.toArray()));
        log.debug("presolvedZlb: " + ArrayUtils.toString(presolvedZlb.toArray()));
        log.debug("presolvedZub: " + ArrayUtils.toString(presolvedZub.toArray()));
    }

    if (n == 0) {
        // deterministic problem
        double[] sol = lpPresolver.postsolve(new double[] {});
        assertEquals(expectedSolution.length, sol.length);
        for (int i = 0; i < sol.length; i++) {
            // log.debug("i: " + i);
            assertEquals(expectedSolution[i], sol[i], 1.e-9);
        }
    } else {

        Utils.writeDoubleArrayToFile(presolvedC.toArray(),
                "target" + File.separator + "presolvedC_" + problemName + ".txt");
        Utils.writeDoubleMatrixToFile(presolvedA.toArray(),
                "target" + File.separator + "presolvedA_" + problemName + ".csv");
        Utils.writeDoubleArrayToFile(presolvedB.toArray(),
                "target" + File.separator + "presolvedB_" + problemName + ".txt");
        Utils.writeDoubleArrayToFile(presolvedLb.toArray(),
                "target" + File.separator + "presolvedLB_" + problemName + ".txt");
        Utils.writeDoubleArrayToFile(presolvedUb.toArray(),
                "target" + File.separator + "presolvedUB_" + problemName + ".txt");

        // check objective function
        double delta = expectedTolerance;
        RealVector presolvedES = MatrixUtils.createRealVector(lpPresolver.presolve(expectedSolution));
        double presolvedEV = MatrixUtils.createRealVector(presolvedC.toArray()).dotProduct(presolvedES);// in general it is different from the optimal value
        log.debug("presolved expected value: " + presolvedEV);
        RealVector postsolvedES = MatrixUtils.createRealVector(lpPresolver.postsolve(presolvedES.toArray()));
        double postsolvedEV = MatrixUtils.createRealVector(c).dotProduct(postsolvedES);
        //assertEquals(expectedValue, postsolvedEV, delta);
        assertTrue(Math.abs((expectedValue - postsolvedEV) / expectedValue) < delta);

        // check postsolved constraints
        for (int i = 0; i < lb.length; i++) {
            double di = Double.isNaN(lb[i]) ? -Double.MAX_VALUE : lb[i];
            assertTrue(di <= postsolvedES.getEntry(i) + delta);
        }
        for (int i = 0; i < ub.length; i++) {
            double di = Double.isNaN(ub[i]) ? Double.MAX_VALUE : ub[i];
            assertTrue(di + delta >= postsolvedES.getEntry(i));
        }
        RealVector Axmb = AMatrix.operate(postsolvedES).subtract(bVector);
        assertEquals(0., Axmb.getNorm(), 1.5 * expectedTolerance);

        // check presolved constraints
        assertEquals(presolvedLb.size(), presolvedES.getDimension());
        assertEquals(presolvedUb.size(), presolvedES.getDimension());
        AMatrix = MatrixUtils.createRealMatrix(presolvedA.toArray());//reassigned to avoid memory consumption
        bVector = MatrixUtils.createRealVector(presolvedB.toArray());
        for (int i = 0; i < presolvedLb.size(); i++) {
            double di = Double.isNaN(presolvedLb.getQuick(i)) ? -Double.MAX_VALUE : presolvedLb.getQuick(i);
            assertTrue(di <= presolvedES.getEntry(i) + delta);
        }
        for (int i = 0; i < presolvedUb.size(); i++) {
            double di = Double.isNaN(presolvedUb.getQuick(i)) ? Double.MAX_VALUE : presolvedUb.getQuick(i);
            assertTrue(di + delta >= presolvedES.getEntry(i));
        }
        Axmb = AMatrix.operate(presolvedES).subtract(bVector);
        assertEquals(0., Axmb.getNorm(), 1.5 * expectedTolerance);

        //check for 0-rows
        List<Integer> zeroRows = new ArrayList<Integer>();
        for (int i = 0; i < presolvedA.rows(); i++) {
            boolean isNotZero = false;
            for (int j = 0; !isNotZero && j < presolvedA.columns(); j++) {
                isNotZero = Double.compare(0., presolvedA.getQuick(i, j)) != 0;
            }
            if (!isNotZero) {
                zeroRows.add(zeroRows.size(), i);
            }
        }
        if (!zeroRows.isEmpty()) {
            log.debug("All 0 entries in rows " + ArrayUtils.toString(zeroRows));
            fail();
        }

        //check for 0-columns
        List<Integer> zeroCols = new ArrayList<Integer>();
        for (int j = 0; j < presolvedA.columns(); j++) {
            boolean isNotZero = false;
            for (int i = 0; !isNotZero && i < presolvedA.rows(); i++) {
                isNotZero = Double.compare(0., presolvedA.getQuick(i, j)) != 0;
            }
            if (!isNotZero) {
                zeroCols.add(zeroCols.size(), j);
            }
        }
        if (!zeroCols.isEmpty()) {
            log.debug("All 0 entries in columns " + ArrayUtils.toString(zeroCols));
            fail();
        }

        // check rank(A): must be A pXn with rank(A)=p < n
        qr = new QRSparseFactorization(new SparseDoubleMatrix2D(presolvedA.toArray()));
        qr.factorize();
        boolean isFullRank = qr.hasFullRank();
        log.debug("p        : " + AMatrix.getRowDimension());
        log.debug("n        : " + AMatrix.getColumnDimension());
        log.debug("full rank: " + isFullRank);
        assertTrue(AMatrix.getRowDimension() < AMatrix.getColumnDimension());
        assertTrue(isFullRank);
    }
}

From source file:com.github.tteofili.looseen.yay.SGM.java

/**
 * predict network output given an input
 *
 * @param input the input/* w  w w.  jav a 2s .co m*/
 * @return the output
 * @throws Exception
 */
private double[] predictOutput(double[] input) throws Exception {

    RealMatrix hidden = rectifierFunction.applyMatrix(
            MatrixUtils.createRowRealMatrix(input).multiply(weights[0].transpose()).add(biases[0]));
    RealMatrix scores = hidden.multiply(weights[1].transpose()).add(biases[1]);

    RealMatrix probs = scores.copy();
    int len = scores.getColumnDimension() - 1;
    for (int d = 0; d < configuration.window - 1; d++) {
        int startColumn = d * len / (configuration.window - 1);
        RealMatrix subMatrix = scores.getSubMatrix(0, scores.getRowDimension() - 1, startColumn,
                startColumn + input.length);
        for (int sm = 0; sm < subMatrix.getRowDimension(); sm++) {
            probs.setSubMatrix(softmaxActivationFunction.applyMatrix(subMatrix.getRowMatrix(sm)).getData(), sm,
                    startColumn);
        }
    }

    RealVector d = probs.getRowVector(0);
    return d.toArray();
}

From source file:edu.duke.cs.osprey.tupexp.IterativeCGTupleFitter.java

@Override
double[] doFit() {
    //return fit tuple coefficients

    ConjugateGradient cg = new ConjugateGradient(100000, 1e-6, false);//max_iter; delta; whether to check pos def
    //delta is target ratio of residual norm to true vals norm

    long startTime = System.currentTimeMillis();

    while (true) {
        double iterStartTime = System.currentTimeMillis();

        Atb = calcRHS();/*from  w w  w  .  ja v  a2 s  .c  o m*/
        RealVector ans = cg.solve(AtA, Atb);
        double[] newFitVals = calcFitVals(ans);

        System.out.println(
                "Conjugate gradient fitting time (ms): " + (System.currentTimeMillis() - iterStartTime));

        //boolean done = checkDone(curFitVals, newFitVals);
        double resid = calcResidual(newFitVals);
        System.out.println("Step residual: " + resid);

        if (resid > curResid) {//gotten worse...use previous vals
            System.out.println("Iterative conjugate gradient fitting time (ms): "
                    + (System.currentTimeMillis() - startTime));
            return curCoeffs.toArray();
        } else if (resid > curResid - 1e-4) {//basically converged
            System.out.println("Iterative conjugate gradient fitting time (ms): "
                    + (System.currentTimeMillis() - startTime));
            return ans.toArray();
        } else {//keep going
            curCoeffs = ans;
            curFitVals = newFitVals;
            curResid = resid;
        }
    }
}

From source file:com.caseystella.analytics.outlier.batch.rpca.AugmentedDickeyFuller.java

private void computeADFStatistics() {
    double[] y = diff(ts);
    RealMatrix designMatrix = null;/*w ww.j  a v  a  2 s  . c  o m*/
    int k = lag + 1;
    int n = ts.length - 1;

    RealMatrix z = MatrixUtils.createRealMatrix(laggedMatrix(y, k)); //has rows length(ts) - 1 - k + 1
    RealVector zcol1 = z.getColumnVector(0); //has length length(ts) - 1 - k + 1
    double[] xt1 = subsetArray(ts, k - 1, n - 1); //ts[k:(length(ts) - 1)], has length length(ts) - 1 - k + 1
    double[] trend = sequence(k, n); //trend k:n, has length length(ts) - 1 - k + 1
    if (k > 1) {
        RealMatrix yt1 = z.getSubMatrix(0, ts.length - 1 - k, 1, k - 1); //same as z but skips first column
        //build design matrix as cbind(xt1, 1, trend, yt1)
        designMatrix = MatrixUtils.createRealMatrix(ts.length - 1 - k + 1, 3 + k - 1);
        designMatrix.setColumn(0, xt1);
        designMatrix.setColumn(1, ones(ts.length - 1 - k + 1));
        designMatrix.setColumn(2, trend);
        designMatrix.setSubMatrix(yt1.getData(), 0, 3);

    } else {
        //build design matrix as cbind(xt1, 1, tt)
        designMatrix = MatrixUtils.createRealMatrix(ts.length - 1 - k + 1, 3);
        designMatrix.setColumn(0, xt1);
        designMatrix.setColumn(1, ones(ts.length - 1 - k + 1));
        designMatrix.setColumn(2, trend);
    }
    /*OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
    regression.setNoIntercept(true);
    regression.newSampleData(zcol1.toArray(), designMatrix.getData());
    double[] beta = regression.estimateRegressionParameters();
    double[] sd = regression.estimateRegressionParametersStandardErrors();
    */
    RidgeRegression regression = new RidgeRegression(designMatrix.getData(), zcol1.toArray());
    regression.updateCoefficients(.0001);
    double[] beta = regression.getCoefficients();
    double[] sd = regression.getStandarderrors();

    double t = beta[0] / sd[0];
    if (t <= PVALUE_THRESHOLD) {
        this.needsDiff = true;
    } else {
        this.needsDiff = false;
    }
}

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

/**
 * Quadratic objective, no constraints.//  ww w .  jav a  2s . com
 */
public void testNewtownUnconstrained() throws Exception {
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "testNewtownUnconstrained");
    RealMatrix PMatrix = new Array2DRowRealMatrix(
            new double[][] { { 1.68, 0.34, 0.38 }, { 0.34, 3.09, -1.59 }, { 0.38, -1.59, 1.54 } });
    RealVector qVector = new ArrayRealVector(new double[] { 0.018, 0.025, 0.01 });

    // Objective function.
    double theta = 0.01522;
    RealMatrix P = PMatrix.scalarMultiply(theta);
    RealVector q = qVector.mapMultiply(-1);
    PDQuadraticMultivariateRealFunction objectiveFunction = new PDQuadraticMultivariateRealFunction(P.getData(),
            q.toArray(), 0);

    OptimizationRequest or = new OptimizationRequest();
    or.setF0(objectiveFunction);
    or.setInitialPoint(new double[] { 0.04, 0.50, 0.46 });

    //optimization
    JOptimizer opt = new JOptimizer();
    opt.setOptimizationRequest(or);
    int returnCode = opt.optimize();

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

    OptimizationResponse response = opt.getOptimizationResponse();
    double[] sol = response.getSolution();
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "sol   : " + ArrayUtils.toString(sol));
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "value : " + objectiveFunction.value(sol));

    // we already know the analytic solution of the problem
    // sol = -invQ * C
    RealMatrix QInv = Utils.squareMatrixInverse(P);
    RealVector benchSol = QInv.operate(q).mapMultiply(-1);
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "benchSol   : " + ArrayUtils.toString(benchSol.toArray()));
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "benchValue : " + objectiveFunction.value(benchSol.toArray()));

    assertEquals(benchSol.getEntry(0), sol[0], 0.000000000000001);
    assertEquals(benchSol.getEntry(1), sol[1], 0.000000000000001);
    assertEquals(benchSol.getEntry(2), sol[2], 0.000000000000001);
}

From source file:com.joptimizer.solvers.BasicKKTSolver.java

/**
 * Returns the two vectors v and w.//from ww  w .  j  a  v  a2s  . c  o  m
 */
@Override
public double[][] solve() throws Exception {

    RealVector v = null;// dim equals cols of A
    RealVector w = null;// dim equals rank of A

    if (Log.isLoggable(MainActivity.JOPTIMIZER_LOGTAG, Log.DEBUG)) {
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, "H: " + ArrayUtils.toString(H.getData()));
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, "g: " + ArrayUtils.toString(g.toArray()));
    }
    RealMatrix HInv;
    try {
        HInv = Utils.squareMatrixInverse(H);
    } catch (SingularMatrixException e) {
        HInv = null;
    }

    if (HInv != null) {
        // Solving KKT system via elimination
        if (A != null) {
            if (Log.isLoggable(MainActivity.JOPTIMIZER_LOGTAG, Log.DEBUG)) {
                Log.d(MainActivity.JOPTIMIZER_LOGTAG, "A: " + ArrayUtils.toString(A.getData()));
                if (h != null) {
                    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "h: " + ArrayUtils.toString(h.toArray()));
                }
            }
            RealMatrix AHInv = A.multiply(HInv);
            RealMatrix MenoS = AHInv.multiply(AT);
            RealMatrix MenoSInv = Utils.squareMatrixInverse(MenoS);
            if (h == null || Double.compare(h.getNorm(), 0.) == 0) {
                w = MenoSInv.operate(AHInv.operate(g)).mapMultiply(-1.);
            } else {
                w = MenoSInv.operate(h.subtract(AHInv.operate(g)));
            }
            v = HInv.operate(g.add(AT.operate(w)).mapMultiply(-1.));
        } else {
            w = null;
            v = HInv.operate(g).mapMultiply(-1.);
        }
    } else {
        // Solving the full KKT system
        if (A != null) {
            KKTSolver kktSolver = new BasicKKTSolver();
            kktSolver.setCheckKKTSolutionAccuracy(false);
            double[][] fullSol = this.solveFullKKT(new BasicKKTSolver());
            v = new ArrayRealVector(fullSol[0]);
            w = new ArrayRealVector(fullSol[1]);
        } else {
            //@TODO: try with rescaled H
            throw new Exception("KKT solution failed");
        }
    }

    // solution checking
    if (this.checkKKTSolutionAccuracy && !this.checkKKTSolutionAccuracy(v, w)) {
        Log.e(MainActivity.JOPTIMIZER_LOGTAG, "KKT solution failed");
        throw new Exception("KKT solution failed");
    }

    double[][] ret = new double[2][];
    ret[0] = v.toArray();
    ret[1] = (w != null) ? w.toArray() : null;
    return ret;
}

From source file:network.NodeUnits.java

public String eString(RealVector rv) {
    double[] v = rv.toArray();
    int len = v.length;
    String tmpS = " ";
    for (int i1 = 0; i1 < len; i1++) {
        tmpS += v[i1] + " , ";
    }//from  w  w  w .j  a v  a  2 s.co m
    return tmpS;
}

From source file:org.apache.eagle.security.userprofile.model.UserProfileEigenModel.java

public void print_RealVector(RealVector v) {
    double[] tmp = v.toArray();
    for (double x : tmp)
        System.out.print(" " + x);
    System.out.println(" ");
}