Example usage for org.apache.commons.math3.linear ArrayRealVector ArrayRealVector

List of usage examples for org.apache.commons.math3.linear ArrayRealVector ArrayRealVector

Introduction

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

Prototype

public ArrayRealVector(ArrayRealVector v) throws NullArgumentException 

Source Link

Document

Construct a vector from another vector, using a deep copy.

Usage

From source file:edu.oregonstate.eecs.mcplan.abstraction.EvaluateSimilarityFunction.java

public static Instances transformInstances(final Instances src, final CoordinateTransform transform) {
    final ArrayList<Attribute> out_attributes = new ArrayList<Attribute>();
    for (int i = 0; i < transform.outDimension(); ++i) {
        out_attributes.add(new Attribute("x" + i));
    }//from  w  w w.  jav  a 2  s . c o m
    out_attributes.add((Attribute) src.classAttribute().copy());
    final Instances out = new Instances(src.relationName() + "_" + transform.name(), out_attributes, 0);
    for (int i = 0; i < src.size(); ++i) {
        final Instance inst = src.get(i);
        final RealVector flat = new ArrayRealVector(WekaUtil.unlabeledFeatures(inst));
        final RealVector transformed_vector = transform.encode(flat).x;
        final double[] transformed = new double[transformed_vector.getDimension() + 1];
        for (int j = 0; j < transformed_vector.getDimension(); ++j) {
            transformed[j] = transformed_vector.getEntry(j);
        }
        transformed[transformed.length - 1] = inst.classValue();
        final Instance transformed_instance = new DenseInstance(inst.weight(), transformed);
        out.add(transformed_instance);
        transformed_instance.setDataset(out);
    }
    out.setClassIndex(out.numAttributes() - 1);
    return out;
}

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

/**
 * Minimize x subject to //from   ww w .j a  va 2 s .  com
 * 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:monitor.processing.OLD.Drawing3D.java

public void drawTree(MonitorPerception p) {
    synchronized (p) {
        drawTree(p.getSceneGraph(), new ArrayRealVector(new double[] { 0, 0, 0, 1 }));
    }/*w  w  w.  ja  v  a2  s.  c  om*/
}

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

/**
 * Find a solution of the linear (equalities) system A.x = b.
 * @see "S.Boyd and L.Vandenberghe, Convex Optimization, p. 682"
 *///from   w w  w .j a  v  a  2s  . c  o  m
protected double[] findEqFeasiblePoint(double[][] A, double[] b) throws Exception {
    RealMatrix AT = new Array2DRowRealMatrix(A).transpose();
    int p = A.length;

    SingularValueDecomposition dFact1 = new SingularValueDecomposition(AT);
    int rangoAT = dFact1.getRank();
    if (rangoAT != p) {
        throw new RuntimeException("Equalities matrix A must have full rank");
    }

    QRDecomposition dFact = new QRDecomposition(AT);
    //A = QR
    RealMatrix Q1Q2 = dFact.getQ();
    RealMatrix R0 = dFact.getR();
    RealMatrix Q1 = Q1Q2.getSubMatrix(0, AT.getRowDimension() - 1, 0, p - 1);
    RealMatrix R = R0.getSubMatrix(0, p - 1, 0, p - 1);
    double[][] rData = R.copy().getData();
    //inversion
    double[][] rInvData = Utils.upperTriangularMatrixUnverse(rData);
    RealMatrix RInv = new Array2DRowRealMatrix(rInvData);

    //w = Q1 *   Inv([R]T) . b
    double[] w = Q1.operate(RInv.transpose().operate(new ArrayRealVector(b))).toArray();
    return w;
}

From source file:game.plugins.algorithms.RealFeaturesTree.java

private RealVector getProbabilities(Dataset dataset) {
    Map<String, Double> prob = new HashMap<>();
    Iterator<Instance> it = dataset.iterator();
    double sum = 0;
    while (it.hasNext()) {
        Instance i = it.next();/*  w  ww  . j  a v a 2 s  .c  o  m*/
        String key = i.getTarget().get().get(String.class);
        if (!prob.containsKey(key))
            prob.put(key, 0.0);
        prob.put(key, prob.get(key) + 1.0);
        sum++;
    }

    List<String> labels = dataset.getTemplate().targetTemplate.getSingleton().getContent("labels");

    RealVector ret = new ArrayRealVector(labels.size());
    for (String key : prob.keySet()) {
        ret.setEntry(labels.indexOf(key), prob.get(key) / sum);
    }
    return ret;
}

From source file:edu.oregonstate.eecs.mcplan.domains.blackjack.AbstractionDiscovery.java

private static ArrayList<RealVector> enumerateStates(final BlackjackParameters params) {
    // FIXME: The proliferation of different state representations is
    // alarming. I'm using them here for convenience, but they are too
    // subtly different to be intermixed like this safely!

    final ArrayList<RealVector> states = new ArrayList<RealVector>();
    final BlackjackStateSpace ss = new BlackjackStateSpace(params);

    for (final BlackjackMdpState s : Fn.in(ss.generator())) {
        if (!s.player_passed) {
            states.add(new ArrayRealVector(
                    HandValueAbstraction.makePhi(params, s.player_value, s.player_high_aces, s.dealer_value)));
        }/*w  w  w .  j a  v a  2s.c o m*/
    }

    return states;
}

From source file:lambertmrev.Lambert.java

public ArrayRealVector dTdx(double x, double T, double m_lambda) {
    double l2 = m_lambda * m_lambda;
    double l3 = l2 * m_lambda;
    double umx2 = 1.0 - x * x;
    double y = FastMath.sqrt(1.0 - l2 * umx2);
    double y2 = y * y;
    double y3 = y2 * y;

    ArrayRealVector out = new ArrayRealVector(3);
    out.setEntry(0, 1.0 / umx2 * (3.0 * T * x - 2.0 + 2.0 * l3 * x / y));
    out.setEntry(1, 1.0 / umx2 * (3.0 * T + 5.0 * x * out.getEntry(0) + 2.0 * (1.0 - l2) * l3 / y3));
    out.setEntry(2, 1.0 / umx2/*  ww  w. j  a  v a  2 s  .  c om*/
            * (7.0 * x * out.getEntry(1) + 8.0 * out.getEntry(0) - 6.0 * (1.0 - l2) * l2 * l3 * x / y3 / y2));

    return out;
}

From source file:eagle.security.userprofile.model.eigen.UserProfileEigenModeler.java

private RealMatrix computeMaxDistanceOnPCs(int index) {

    RealMatrix pc = new Array2DRowRealMatrix(principalComponents[index].toArray());
    RealMatrix transposePC1 = pc.transpose();
    RealMatrix finalDataTranspose = finalMatrixWithoutLowVariantCmds.transpose();

    RealMatrix trainingData = pc.multiply(transposePC1).multiply(finalDataTranspose);
    RealMatrix trainingDataTranspose = trainingData.transpose();

    double maxDistance = 0.0;
    double minDistance = 0.0;
    RealVector p1 = null, p2 = null;// w  w  w .  jav a  2  s  .  c o m
    if (LOG.isDebugEnabled())
        LOG.debug("Training data transpose size: " + trainingDataTranspose.getRowDimension() + "x"
                + trainingDataTranspose.getColumnDimension());
    for (int i = 0; i < trainingDataTranspose.getRowDimension(); i++) {
        RealVector iRowVector = new ArrayRealVector(trainingDataTranspose.getRow(i));
        RealVector transposePC1Vect = transposePC1.getRowVector(0);
        double distance = iRowVector.getDistance(transposePC1Vect);
        if (distance > maxDistance) {
            maxDistance = distance;
            p1 = iRowVector;
            p2 = transposePC1Vect;
        }
        if (distance < minDistance)
            minDistance = distance;
        //}
    }
    maximumL2Norm.setEntry(index, maxDistance);
    minimumL2Norm.setEntry(index, minDistance);
    minVector = p1;
    maxVector = p2;
    return trainingDataTranspose;
}

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

@Override
public void run() {
    init();/*from ww  w .  java2s. com*/
    System.out.println("Init");
    for (int i = 0; i < mu().length; ++i) {
        System.out.println("Mu " + i + ": " + mu()[i]);
        System.out.println("Sigma " + i + ": " + Sigma()[i]);
    }

    int iterations = 0;
    while (!converged_ && iterations++ < max_iterations_) {
        // Expectation
        makeMixture();
        for (int i = 0; i < n_; ++i) {
            for (int j = 0; j < k_; ++j) {
                c_[i][j] = posterior(data_[i], j);
            }
            Fn.normalize_inplace(c_[i]);
        }

        // Maximization
        for (int j = 0; j < k_; ++j) {
            double Z = 0.0;
            final RealVector mu_j = new ArrayRealVector(d_);
            RealMatrix Sigma_j = new Array2DRowRealMatrix(d_, d_);
            for (int i = 0; i < n_; ++i) {
                final double c_ij = c_[i][j];
                Z += c_ij;
                final RealVector x_i = new ArrayRealVector(data_[i]);
                // mu_j += c_ij * x_i
                mu_j.combineToSelf(1.0, 1.0, x_i.mapMultiply(c_ij));
                final RealVector v = x_i.subtract(mu_[j]);
                // Sigma_j += c_ij * |v><v|
                Sigma_j = Sigma_j.add(v.outerProduct(v).scalarMultiply(c_ij));
            }
            final double Zinv = 1.0 / Z;
            final double pi_j = Z / n_;
            mu_j.mapMultiplyToSelf(Zinv);
            Sigma_j = Sigma_j.scalarMultiply(Zinv);
            //            converged &= hasConverged( j, pi_j, mu_j, Sigma_j );
            pi_[j] = pi_j;
            mu_[j] = mu_j;
            Sigma_[j] = Sigma_j;
        }
        //         debug();

        final double log_likelihood = logLikelihood();
        if (Math.abs(log_likelihood - old_log_likelihood_) < epsilon_) {
            converged_ = true;
        }
        old_log_likelihood_ = log_likelihood;
    }
}

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

/**
 * Standardization (to the strictly standard form) of a problem on the form:
 * min(c) s.t.//from  w w w . ja  va  2 s  .  c  o m
 * G.x < h
 * A.x = b
 * lb <= x <= ub
 * @TODO: the strict conversion is net yet ready.
 */
public void xxxtestCGhAbLbUb1Strict() throws Exception {
    log.debug("testCGhAbLbUb1Strict");

    String problemId = "1";

    double[] c = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "c" + problemId + ".txt");
    double[][] G = Utils.loadDoubleMatrixFromFile(
            "lp" + File.separator + "standardization" + File.separator + "G" + problemId + ".csv",
            ",".charAt(0));
    double[] h = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "h" + problemId + ".txt");
    ;
    double[][] A = Utils.loadDoubleMatrixFromFile(
            "lp" + File.separator + "standardization" + File.separator + "A" + problemId + ".csv",
            ",".charAt(0));
    double[] b = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "b" + problemId + ".txt");
    double[] lb = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "lb" + problemId + ".txt");
    double[] ub = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "ub" + problemId + ".txt");
    double[] expectedSol = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "sol" + problemId + ".txt");
    double expectedValue = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "value" + problemId + ".txt")[0];
    double expectedTolerance = MatrixUtils.createRealMatrix(A)
            .operate(MatrixUtils.createRealVector(expectedSol)).subtract(MatrixUtils.createRealVector(b))
            .getNorm();

    int nOfSlackVariables = 0;
    for (int i = 0; i < c.length; i++) {
        double lbi = lb[i];
        int lbCompare = Double.compare(lbi, 0.);
        if (lbCompare != 0 && !Double.isNaN(lbi)) {
            nOfSlackVariables++;
        }
        if (!Double.isNaN(ub[i])) {
            nOfSlackVariables++;
        }
    }
    int expectedS = G.length + nOfSlackVariables;

    //standard form conversion
    boolean strictlyStandardForm = true;
    LPStandardConverter lpConverter = new LPStandardConverter(strictlyStandardForm);
    lpConverter.toStandardForm(c, G, h, A, b, lb, ub);

    int n = lpConverter.getStandardN();
    int s = lpConverter.getStandardS();
    c = lpConverter.getStandardC().toArray();
    A = lpConverter.getStandardA().toArray();
    b = lpConverter.getStandardB().toArray();
    lb = lpConverter.getStandardLB().toArray();
    ub = (lpConverter.getStandardUB() == null) ? null : ub;
    log.debug("n : " + n);
    log.debug("s : " + s);
    log.debug("c : " + ArrayUtils.toString(c));
    log.debug("A : " + ArrayUtils.toString(A));
    log.debug("b : " + ArrayUtils.toString(b));
    log.debug("lb : " + ArrayUtils.toString(lb));
    //log.debug("ub : " + ArrayUtils.toString(ub));

    //check consistency
    assertEquals(expectedS, s);
    assertEquals(lb.length, n);
    assertTrue(ub == null);

    //check constraints
    RealMatrix GOrig = new Array2DRowRealMatrix(G);
    RealVector hOrig = new ArrayRealVector(h);
    RealMatrix AStandard = new Array2DRowRealMatrix(A);
    RealVector bStandard = new ArrayRealVector(b);
    RealVector expectedSolVector = new ArrayRealVector(expectedSol);
    double[] expectedStandardSol = lpConverter.getStandardComponents(expectedSol);
    RealVector expectedStandardSolVector = new ArrayRealVector(expectedStandardSol);

    for (int i = 0; i < expectedStandardSolVector.getDimension(); i++) {
        assertTrue(expectedStandardSolVector.getEntry(i) >= 0.);
    }

    RealVector Axmb = AStandard.operate(expectedStandardSolVector).subtract(bStandard);
    assertEquals(0., Axmb.getNorm(), expectedTolerance);

    Utils.writeDoubleArrayToFile(new double[] { s },
            "target" + File.separator + "standardS_" + problemId + ".txt");
    Utils.writeDoubleArrayToFile(c, "target" + File.separator + "standardC_" + problemId + ".txt");
    Utils.writeDoubleMatrixToFile(A, "target" + File.separator + "standardA_" + problemId + ".csv");
    Utils.writeDoubleArrayToFile(b, "target" + File.separator + "standardB_" + problemId + ".txt");
    Utils.writeDoubleArrayToFile(lb, "target" + File.separator + "standardLB_" + problemId + ".txt");
    //ub is null Utils.writeDoubleArrayToFile(ub, "target" + File.separator   + "standardUB_"+problemId+".txt");
}