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:de.termininistic.serein.examples.benchmarks.functions.unimodal.ZakharovFunction.java

@Override
public double map(RealVector v) {
    double[] x = v.toArray();
    int n = x.length;
    double sum1 = 0.0;
    double sum2 = 0.0;

    for (int i = 0; i < n; i++) {
        sum1 += x[i] * x[i];//from ww  w  .  j  a va 2 s.  com
        sum2 += 0.5 * i * x[i];
    }
    double result = sum1 + Math.pow(sum2, 2) + Math.pow(sum2, 4);
    return result;
}

From source file:de.termininistic.serein.examples.benchmarks.functions.unimodal.SphereFunction.java

@Override
public double map(RealVector v) {
    double result = 0.0;
    for (double d : v.toArray()) {
        result = result + d * d;/*from  ww w .j av a2s  .c om*/
    }

    return result;
}

From source file:de.termininistic.serein.examples.benchmarks.functions.unimodal.PermFunction.java

@Override
public double map(RealVector v) {
    double sum = 0.0;
    double[] x = v.toArray();
    for (int i = 0; i < x.length; i++) {
        double innerSum = 0.0;
        for (int j = 0; j < x.length; j++) {
            innerSum += (j + 1 + beta) * (Math.pow(x[j], i + 1) - 1 / Math.pow(j + 1, i + 1));
        }//www  . j av a  2  s.  com
        sum += innerSum * innerSum;
    }
    return sum;
}

From source file:de.termininistic.serein.examples.benchmarks.functions.unimodal.RosenbrockFunction.java

@Override
public double map(RealVector v) {
    double fx = Double.MAX_VALUE;
    double[] x = v.toArray();
    int n = x.length;
    fx = 0.0;/*from ww  w .  jav  a  2s  .c o  m*/
    for (int i = 0; i < n - 1; i++) {
        double term1 = (x[i + 1] - x[i] * x[i]);
        fx += 100 * term1 * term1 + (x[i] - 1) * (x[i] - 1);
    }
    return fx;
}

From source file:iocomms.subpos.TrilaterationFunction.java

/**
 * Calculate and return Jacobian function Actually return initialized function
 * // ww  w  .  j  av a 2  s  .c  o m
 * Jacobian matrix, [i][j] at 
 * J[i][0] = delta_[(x0-xi)^2 + (y0-yi)^2 - ri^2]/delta_[x0] at 
 * J[i][1] = delta_[(x0-xi)^2 + (y0-yi)^2 - ri^2]/delta_[y0] partial derivative with respect to the parameters passed to value() method
 * 
 */
public RealMatrix jacobian(RealVector point) {
    double[] pointArray = point.toArray();

    double[][] jacobian = new double[distances.length][pointArray.length];
    for (int i = 0; i < jacobian.length; i++) {
        for (int j = 0; j < pointArray.length; j++) {
            jacobian[i][j] = 2 * pointArray[j] - 2 * positions[i][j];
        }
    }

    return new Array2DRowRealMatrix(jacobian);
}

From source file:iocomms.subpos.TrilaterationFunction.java

@Override
public Pair<RealVector, RealMatrix> value(RealVector point) {

    // input/*from  w w  w  .  j  a  v a  2 s  .c  om*/
    double[] pointArray = point.toArray();

    // output
    double[] resultPoint = new double[this.distances.length];

    // compute least squares
    for (int i = 0; i < resultPoint.length; i++) {
        resultPoint[i] = 0.0;
        // calculate sum, add to overall
        for (int j = 0; j < pointArray.length; j++) {
            resultPoint[i] += (pointArray[j] - this.getPositions()[i][j])
                    * (pointArray[j] - this.getPositions()[i][j]);
        }
        resultPoint[i] -= (this.getDistances()[i]) * (this.getDistances()[i]);
    }

    RealMatrix jacobian = jacobian(point);
    return new Pair<RealVector, RealMatrix>(new ArrayRealVector(resultPoint), jacobian);
}

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

/**
 * Solve the KKT system as a whole.//from  w  w  w. j a  va2 s  .c  om
 * Useful only if A not null.
 * @see "S.Boyd and L.Vandenberghe, Convex Optimization, p. 547"
 */
protected double[][] solveFullKKT(KKTSolver kktSolver) throws Exception {
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "solveFullKKT");

    //if the KKT matrix is nonsingular, then H + [A]T.A > 0.
    RealMatrix HATA = H.add(AT.multiply(A));
    try {
        CholeskyDecomposition cFact = new CholeskyDecomposition(HATA);
        cFact.getSolver().getInverse();
    } catch (Exception e) {
        throw new Exception("singular KKT system");
    }

    kktSolver.setHMatrix(HATA.getData());//this is positive
    kktSolver.setAMatrix(A.getData());
    kktSolver.setATMatrix(AT.getData());
    kktSolver.setGVector(g.toArray());

    if (h != null) {
        RealVector ATQh = AT.operate(MatrixUtils.createRealIdentityMatrix(A.getRowDimension()).operate(h));
        RealVector gATQh = g.add(ATQh);
        kktSolver.setGVector(gATQh.toArray());
        kktSolver.setHVector(h.toArray());
    }

    return kktSolver.solve();
}

From source file:edu.byu.nlp.stats.DirichletMLEOptimizableTest.java

/**
 * Test method for {@link edu.byu.nlp.stats.DirichletMLEOptimizable#computeNext(double[])}.
 *//*from  ww w. j  av  a  2  s .c  o m*/
@Test
public void testComputeNextInPlace() {
    final double[][] data = DirichletTestUtils.sampleDataset();

    DirichletMLEOptimizable o = DirichletMLEOptimizable.newOptimizable(data, true);
    double[] alpha = new double[] { 2.0, 3.0, 4.0 };
    // Guard against bugs in the test
    assertThat(alpha.length).isEqualTo(data[0].length);

    double[] alphaCopy = alpha.clone();
    ValueAndObject<double[]> vao = o.computeNext(alphaCopy);

    // Ensure that it was performed in place
    assertThat(vao.getObject()).isSameAs(alphaCopy);

    // Ensure that the update was computed correctly
    RealVector expected = DirichletMLEOptimizableTest.newtonRaphsonUpdate(data, alpha);
    assertThat(alphaCopy).isEqualTo(expected.toArray(), delta);

    // TODO : check value
}

From source file:eagle.security.userprofile.model.kde.UserProfileKDEModeler.java

private void computeStats(RealMatrix m) {
    if (m.getColumnDimension() != this.cmdTypes.length) {
        LOG.error("Please fix the commands list in config file");
    }//w w w .ja va  2  s .  c o m

    statistics = new UserCommandStatistics[m.getColumnDimension()];

    for (int i = 0; i < m.getColumnDimension(); i++) {
        UserCommandStatistics stats = new UserCommandStatistics();
        stats.setCommandName(this.cmdTypes[i]);
        RealVector colData = m.getColumnVector(i);
        StandardDeviation deviation = new StandardDeviation();
        double stddev = deviation.evaluate(colData.toArray());

        if (LOG.isDebugEnabled())
            LOG.debug("Stddev is NAN ? " + (Double.isNaN(stddev) ? "yes" : "no"));
        if (stddev <= lowVarianceVal)
            stats.setLowVariant(true);
        else
            stats.setLowVariant(false);

        stats.setStddev(stddev);
        Mean mean = new Mean();
        double mu = mean.evaluate(colData.toArray());
        if (LOG.isDebugEnabled())
            LOG.debug("mu is NAN ? " + (Double.isNaN(mu) ? "yes" : "no"));

        stats.setMean(mu);
        statistics[i] = stats;
    }
}

From source file:edu.utexas.cs.tactex.tariffoptimization.OptimizerWrapperGradientAscent.java

@Override
public TreeMap<Double, TariffSpecification> findOptimum(TariffUtilityEstimate tariffUtilityEstimate,
        int NUM_RATES, int numEval) {

    double[] startingVertex = new double[NUM_RATES]; // start from the fixed-rate tariff's offset
    Arrays.fill(startingVertex, 0.0);

    // temporary solution - getting fixed rate tariff to determine step size and scaling STEP_SIZE proportionally
    TariffSpecification bestFixedRateSpec = tariffUtilityEstimate.getCorrespondingSpec(startingVertex);
    double bestFixedRate = bestFixedRateSpec.getRates().get(0).getValue();
    double rateRatio = bestFixedRate / REFERENCE_RATE;
    // Note: using rateRatio has not been good enough, so trying powers of it (remember it's > 1)
    //STEP_SIZE = Math.max(REFERENCE_STEP_SIZE, (rateRatio * rateRatio) * REFERENCE_STEP_SIZE);
    STEP_SIZE = Math.max(REFERENCE_STEP_SIZE, Math.abs(rateRatio) * REFERENCE_STEP_SIZE);
    log.debug("STEP_SIZE = " + STEP_SIZE + " REFERENCE_STEP_SIZE=" + REFERENCE_STEP_SIZE + " bestFixedRate="
            + bestFixedRate + " REFERENCE_RATE=" + REFERENCE_RATE);

    evaluations = 0;/* w w w. j a v a  2s .  c  o m*/
    TreeMap<Double, TariffSpecification> eval2TOUTariff = new TreeMap<Double, TariffSpecification>();

    // OUTER LOOP
    //for( STEP_SIZE = 0.005; STEP_SIZE < 0.100; STEP_SIZE += 0.005) {
    //  log.info("STARTING A LOOP: STEP_SIZE=" + STEP_SIZE);

    // first compute numerical gradient
    RealVector gradient = new ArrayRealVector(NUM_RATES);
    for (int i = 0; i < NUM_RATES; ++i) {
        gradient.setEntry(i, computePartialDerivative(i, tariffUtilityEstimate, NUM_RATES, eval2TOUTariff));
    }
    gradient = gradient.unitVector();

    // taking steps in the gradient direction
    double previousPointValue = -Double.MAX_VALUE;
    final double alpha = STEP_SIZE;
    RealVector rateOffsets = new ArrayRealVector(NUM_RATES); // initializes with 0s?
    double currentPointValue = evaluatePoint(tariffUtilityEstimate, rateOffsets.toArray());
    eval2TOUTariff.put(currentPointValue, tariffUtilityEstimate.getCorrespondingSpec(rateOffsets.toArray()));
    while (!converged(currentPointValue, previousPointValue) && evaluations < MAX_EVALUATIONS) {
        previousPointValue = currentPointValue;
        rateOffsets = rateOffsets.add(gradient.mapMultiply(alpha));
        currentPointValue = evaluatePoint(tariffUtilityEstimate, rateOffsets.toArray());
        eval2TOUTariff.put(currentPointValue,
                tariffUtilityEstimate.getCorrespondingSpec(rateOffsets.toArray()));
    }

    log.info("gradient ascent finished after " + evaluations + " evaluations");

    //}

    // return map
    return eval2TOUTariff;
}