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

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

Introduction

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

Prototype

public abstract double getEntry(int index) throws OutOfRangeException;

Source Link

Document

Return the entry at the specified index.

Usage

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   www.  j  a va  2  s .  com
        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.simiacryptus.mindseye.applications.ObjectLocationBase.java

/**
 * Run.//w ww  . ja v  a 2 s.  c om
 *
 * @param log the log
 */
public void run(@Nonnull final NotebookOutput log) {
    //    @Nonnull String logName = "cuda_" + log.getName() + ".log";
    //    log.p(log.file((String) null, logName, "GPU Log"));
    //    CudaSystem.addLog(new PrintStream(log.file(logName)));

    ImageClassifierBase classifier = getClassifierNetwork();
    Layer classifyNetwork = classifier.getNetwork();

    ImageClassifierBase locator = getLocatorNetwork();
    Layer locatorNetwork = locator.getNetwork();
    ArtistryUtil.setPrecision((DAGNetwork) classifyNetwork, Precision.Float);
    ArtistryUtil.setPrecision((DAGNetwork) locatorNetwork, Precision.Float);

    Tensor[][] inputData = loadImages_library();
    //    Tensor[][] inputData = loadImage_Caltech101(log);
    double alphaPower = 0.8;

    final AtomicInteger index = new AtomicInteger(0);
    Arrays.stream(inputData).limit(10).forEach(row -> {
        log.h3("Image " + index.getAndIncrement());
        final Tensor img = row[0];
        log.p(log.image(img.toImage(), ""));
        Result classifyResult = classifyNetwork.eval(new MutableResult(row));
        Result locationResult = locatorNetwork.eval(new MutableResult(row));
        Tensor classification = classifyResult.getData().get(0);
        List<CharSequence> categories = classifier.getCategories();
        int[] sortedIndices = IntStream.range(0, categories.size()).mapToObj(x -> x)
                .sorted(Comparator.comparing(i -> -classification.get(i))).mapToInt(x -> x).limit(10).toArray();
        logger.info(Arrays.stream(sortedIndices)
                .mapToObj(
                        i -> String.format("%s: %s = %s%%", i, categories.get(i), classification.get(i) * 100))
                .reduce((a, b) -> a + "\n" + b).orElse(""));
        LinkedHashMap<CharSequence, Tensor> vectors = new LinkedHashMap<>();
        List<CharSequence> predictionList = Arrays.stream(sortedIndices).mapToObj(categories::get)
                .collect(Collectors.toList());
        Arrays.stream(sortedIndices).limit(6).forEach(category -> {
            CharSequence name = categories.get(category);
            log.h3(name);
            Tensor alphaTensor = renderAlpha(alphaPower, img, locationResult, classification, category);
            log.p(log.image(img.toRgbImageAlphaMask(0, 1, 2, alphaTensor), ""));
            vectors.put(name, alphaTensor.unit());
        });

        Tensor avgDetection = vectors.values().stream().reduce((a, b) -> a.add(b)).get()
                .scale(1.0 / vectors.size());
        Array2DRowRealMatrix covarianceMatrix = new Array2DRowRealMatrix(predictionList.size(),
                predictionList.size());
        for (int x = 0; x < predictionList.size(); x++) {
            for (int y = 0; y < predictionList.size(); y++) {
                Tensor l = vectors.get(predictionList.get(x));
                Tensor r = vectors.get(predictionList.get(y));

                covarianceMatrix.setEntry(x, y,
                        null == l || null == r ? 0 : (l.minus(avgDetection)).dot(r.minus(avgDetection)));
            }
        }
        @Nonnull
        final EigenDecomposition decomposition = new EigenDecomposition(covarianceMatrix);

        for (int objectVector = 0; objectVector < 10; objectVector++) {
            log.h3("Eigenobject " + objectVector);
            double eigenvalue = decomposition.getRealEigenvalue(objectVector);
            RealVector eigenvector = decomposition.getEigenvector(objectVector);
            Tensor detectionRegion = IntStream.range(0, eigenvector.getDimension()).mapToObj(i -> {
                Tensor tensor = vectors.get(predictionList.get(i));
                return null == tensor ? null : tensor.scale(eigenvector.getEntry(i));
            }).filter(x -> null != x).reduce((a, b) -> a.add(b)).get();
            detectionRegion = detectionRegion.scale(255.0 / detectionRegion.rms());
            CharSequence categorization = IntStream.range(0, eigenvector.getDimension()).mapToObj(i -> {
                CharSequence category = predictionList.get(i);
                double component = eigenvector.getEntry(i);
                return String.format("<li>%s = %.4f</li>", category, component);
            }).reduce((a, b) -> a + "" + b).get();
            log.p(String.format("Object Detected: <ol>%s</ol>", categorization));
            log.p("Object Eigenvalue: " + eigenvalue);
            log.p("Object Region: " + log.image(img.toRgbImageAlphaMask(0, 1, 2, detectionRegion), ""));
            log.p("Object Region Compliment: "
                    + log.image(img.toRgbImageAlphaMask(0, 1, 2, detectionRegion.scale(-1)), ""));
        }

        //      final int[] orderedVectors = IntStream.range(0, 10).mapToObj(x -> x)
        //        .sorted(Comparator.comparing(x -> -decomposition.getRealEigenvalue(x))).mapToInt(x -> x).toArray();
        //      IntStream.range(0, orderedVectors.length)
        //        .mapToObj(i -> {
        //            //double realEigenvalue = decomposition.getRealEigenvalue(orderedVectors[i]);
        //            return decomposition.getEigenvector(orderedVectors[i]).toArray();
        //          }
        //        ).toArray(i -> new double[i][]);

        log.p(String.format(
                "<table><tr><th>Cosine Distance</th>%s</tr>%s</table>", Arrays.stream(sortedIndices).limit(10)
                        .mapToObj(col -> "<th>" + categories.get(col) + "</th>").reduce((a, b) -> a + b).get(),
                Arrays.stream(sortedIndices).limit(10).mapToObj(r -> {
                    return String.format("<tr><td>%s</td>%s</tr>", categories.get(r),
                            Arrays.stream(sortedIndices).limit(10).mapToObj(col -> {
                                Tensor l = vectors.get(categories.get(r));
                                Tensor r2 = vectors.get(categories.get(col));
                                return String.format("<td>%.4f</td>",
                                        (null == l || null == r2) ? 0 : Math.acos(l.dot(r2)));
                            }).reduce((a, b) -> a + b).get());
                }).reduce((a, b) -> a + b).orElse("")));
    });

    log.setFrontMatterProperty("status", "OK");
}

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

/**
 * Standardization (to the strictly standard form) of a problem on the form:
 * min(c) s.t.//  ww  w. j  ava 2  s .  c o m
 * A.x = b
 * lb <= x <= ub
 * 
 * This is the presolved (with JOptimizer) pilot4 netlib problem.
 * @TODO: the strict conversion is net yet ready.
 */
public void xxxtestCAbLbUb5Strict() throws Exception {
    log.debug("testCAbLbUb5Strict");

    String problemId = "5";

    double[] c = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "c" + 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 expectedTol = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "tolerance" + problemId + ".txt")[0];

    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 = nOfSlackVariables;

    //standard form conversion
    boolean strictlyStandardForm = true;
    LPStandardConverter lpConverter = new LPStandardConverter(strictlyStandardForm);
    lpConverter.toStandardForm(c, null, null, 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 AStandard = new Array2DRowRealMatrix(A);
    RealVector bStandard = new ArrayRealVector(b);
    double[] expectedStandardSol = lpConverter.getStandardComponents(expectedSol);
    RealVector expectedStandardSolVector = new ArrayRealVector(expectedStandardSol);

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

    RealVector Axmb = AStandard.operate(expectedStandardSolVector).subtract(bStandard);
    for (int i = 0; i < Axmb.getDimension(); i++) {
        assertEquals(0., Axmb.getEntry(i), expectedTol);
    }

    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");
}

From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java

/**
 * Applies an existing correction to a single x-y position in the Image plane.
 *
 * @param x     The x-position at which to apply the correction.
 * @param y     The y-position at which to apply the correction.
 * @return      A RealVector containing 3 elements-- the magnitude of the correction in the x, y, and z dimensions, in that order.
 *//*ww w .j a va  2s.  c  om*/
public RealVector correctPosition(double x, double y) throws UnableToCorrectException {

    RealVector corrections = new ArrayRealVector(3, 0.0);

    RealVector distsToCentroids = this.getPositionsForCorrection().getColumnVector(0).mapSubtract(x)
            .mapToSelf(new Power(2));
    distsToCentroids = distsToCentroids
            .add(this.getPositionsForCorrection().getColumnVector(1).mapSubtract(y).mapToSelf(new Power(2)));
    distsToCentroids.mapToSelf(new Sqrt());

    RealVector distRatio = distsToCentroids.ebeDivide(this.getDistanceCutoffs());

    RealVector distRatioBin = new ArrayRealVector(distRatio.getDimension(), 0.0);

    for (int i = 0; i < distRatio.getDimension(); i++) {
        if (distRatio.getEntry(i) <= 1)
            distRatioBin.setEntry(i, 1.0);
    }

    RealVector weights = distRatio.map(new Power(2.0)).mapMultiplyToSelf(-3).mapAddToSelf(1)
            .add(distRatio.map(new Power(3.0)).mapMultiplyToSelf(2));

    weights = weights.ebeMultiply(distRatioBin);

    double sumWeights = 0;

    int countWeights = 0;

    for (int i = 0; i < weights.getDimension(); i++) {
        if (weights.getEntry(i) > 0) {
            sumWeights += weights.getEntry(i);
            countWeights++;
        }
    }

    if (countWeights == 0) { // this means there were no points in the correction dataset near the position being corrected.
        throw (new UnableToCorrectException(
                "Incomplete coverage in correction dataset at (x,y) = (" + x + ", " + y + ")."));
    }

    RealMatrix cX = new Array2DRowRealMatrix(countWeights, this.getCorrectionX().getColumnDimension());
    RealMatrix cY = new Array2DRowRealMatrix(countWeights, this.getCorrectionX().getColumnDimension());
    RealMatrix cZ = new Array2DRowRealMatrix(countWeights, this.getCorrectionX().getColumnDimension());

    RealVector xVec = new ArrayRealVector(countWeights, 0.0);
    RealVector yVec = new ArrayRealVector(countWeights, 0.0);

    RealVector keptWeights = new ArrayRealVector(countWeights, 0.0);

    int keptCounter = 0;

    for (int i = 0; i < weights.getDimension(); i++) {
        if (weights.getEntry(i) > 0) {

            cX.setRowVector(keptCounter, this.getCorrectionX().getRowVector(i));
            cY.setRowVector(keptCounter, this.getCorrectionY().getRowVector(i));
            cZ.setRowVector(keptCounter, this.getCorrectionZ().getRowVector(i));

            xVec.setEntry(keptCounter, x - this.getPositionsForCorrection().getEntry(i, 0));
            yVec.setEntry(keptCounter, y - this.getPositionsForCorrection().getEntry(i, 1));

            keptWeights.setEntry(keptCounter, weights.getEntry(i));

            keptCounter++;
        }
    }

    double xCorr = 0;
    double yCorr = 0;
    double zCorr = 0;

    RealMatrix allCorrectionParameters = new Array2DRowRealMatrix(countWeights, numberOfCorrectionParameters);

    RealVector ones = new ArrayRealVector(countWeights, 1.0);

    allCorrectionParameters.setColumnVector(0, ones);
    allCorrectionParameters.setColumnVector(1, xVec);
    allCorrectionParameters.setColumnVector(2, yVec);
    allCorrectionParameters.setColumnVector(3, xVec.map(new Power(2)));
    allCorrectionParameters.setColumnVector(4, yVec.map(new Power(2)));
    allCorrectionParameters.setColumnVector(5, xVec.ebeMultiply(yVec));

    for (int i = 0; i < countWeights; i++) {

        xCorr += allCorrectionParameters.getRowVector(i).dotProduct(cX.getRowVector(i))
                * keptWeights.getEntry(i);
        yCorr += allCorrectionParameters.getRowVector(i).dotProduct(cY.getRowVector(i))
                * keptWeights.getEntry(i);
        zCorr += allCorrectionParameters.getRowVector(i).dotProduct(cZ.getRowVector(i))
                * keptWeights.getEntry(i);

    }

    xCorr /= sumWeights;
    yCorr /= sumWeights;
    zCorr /= sumWeights;

    corrections.setEntry(0, xCorr);
    corrections.setEntry(1, yCorr);
    corrections.setEntry(2, zCorr);

    return corrections;
}

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

/**
 * Standardization (to the strictly standard form) of a problem on the form:
 * min(c) s.t.// w  w  w. j a v a2  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");
}

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

/**
 * Standardization of a problem on the form:
 * min(c) s.t./* w  w w. j a  v a2  s.c o m*/
 * G.x < h
 * A.x = b
 */
public void testCGhAb3() throws Exception {
    log.debug("testCGhAb3");

    String problemId = "3";

    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[] 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();

    //standard form conversion
    LPStandardConverter lpConverter = new LPStandardConverter();
    lpConverter.toStandardForm(c, G, h, A, b, null, null);

    int n = lpConverter.getStandardN();
    int s = lpConverter.getStandardS();
    c = lpConverter.getStandardC().toArray();
    A = lpConverter.getStandardA().toArray();
    b = lpConverter.getStandardB().toArray();
    double[] lb = lpConverter.getStandardLB().toArray();
    double[] ub = lpConverter.getStandardUB().toArray();
    log.debug("n : " + n);
    log.debug("s : " + s);

    //check consistency
    assertEquals(G.length, s);
    assertEquals(A[0].length, n);
    assertEquals(s + lpConverter.getOriginalN(), n);
    assertEquals(lb.length, n);
    assertEquals(ub.length, n);

    //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);
    RealVector Gxh = GOrig.operate(expectedSolVector).subtract(hOrig);//G.x - h
    RealVector slackVariables = new ArrayRealVector(s);
    for (int i = 0; i < s; i++) {
        slackVariables.setEntry(i, 0. - Gxh.getEntry(i));//the difference from 0
        assertTrue(slackVariables.getEntry(i) >= 0.);
    }
    RealVector sol = slackVariables.append(expectedSolVector);
    RealVector Axmb = AStandard.operate(sol).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+".txt");
    //      Utils.writeDoubleArrayToFile(b, "target" + File.separator   + "standardB"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(lb, "target" + File.separator   + "standardLB"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(ub, "target" + File.separator   + "standardUB"+problemId+".txt");
}

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

RealVector applyAtA(RealVector rv) {
    //first apply A
    double Arv[] = calcFitVals(rv);

    //then apply A^T to Arv
    double ans[] = new double[numTup];
    for (int s = 0; s < numSamp; s++) {
        if (isSampleRestrained(s)) {
            ArrayList<Integer> sampTup = tupIndMat.calcSampleTuples(samples.get(s));
            for (int t : sampTup)
                ans[t] += Arv[s];/* w ww. j a v a  2 s .c  o m*/
        }
    }

    //damping
    if (curCoeffs != null) {//not first iteration
        for (int t = 0; t < numTup; t++)
            ans[t] += damperLambda * rv.getEntry(t);
    }

    return new ArrayRealVector(ans, false);//make RealVector without copying ans
}

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

/**
 * Standardization of a problem on the form:
 * min(c) s.t.//  w w w  .  j  av a 2 s .c o m
 * G.x < h
 * A.x = b
 */
public void testCGhAb2() throws Exception {
    log.debug("testCGhAb2");

    String problemId = "2";

    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[] 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();

    //standard form conversion
    double unboundedLBValue = Double.NEGATIVE_INFINITY;
    double unboundedUBValue = Double.POSITIVE_INFINITY;
    LPStandardConverter lpConverter = new LPStandardConverter(unboundedLBValue, unboundedUBValue);
    lpConverter.toStandardForm(c, G, h, A, b, null, null);

    int n = lpConverter.getStandardN();
    int s = lpConverter.getStandardS();
    c = lpConverter.getStandardC().toArray();
    A = lpConverter.getStandardA().toArray();
    b = lpConverter.getStandardB().toArray();
    double[] lb = lpConverter.getStandardLB().toArray();
    double[] ub = lpConverter.getStandardUB().toArray();
    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(G.length, s);
    assertEquals(A[0].length, n);
    assertEquals(s + lpConverter.getOriginalN(), n);
    assertEquals(lb.length, n);
    assertEquals(ub.length, n);

    //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);
    RealVector Gxh = GOrig.operate(expectedSolVector).subtract(hOrig);//G.x - h
    RealVector slackVariables = new ArrayRealVector(s);
    for (int i = 0; i < s; i++) {
        slackVariables.setEntry(i, 0. - Gxh.getEntry(i));//the difference from 0
        assertTrue(slackVariables.getEntry(i) >= 0.);
    }
    RealVector sol = slackVariables.append(expectedSolVector);
    RealVector Axmb = AStandard.operate(sol).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+".txt");
    //      Utils.writeDoubleArrayToFile(b, "target" + File.separator   + "standardB"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(lb, "target" + File.separator   + "standardLB"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(ub, "target" + File.separator   + "standardUB"+problemId+".txt");
}

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

/**
 * Standardization of a problem on the form:
 * min(c) s.t.//w  w  w . ja v  a2s.  c  o  m
 * G.x < h
 * A.x = b
 * lb <= x <= ub
 */
public void testCGhAbLbUb1() throws Exception {
    log.debug("testCGhAbLbUb1");

    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 = Utils.loadDoubleArrayFromFile("lp"+File.separator+"standardization"+File.separator+"tolerance"+problemId+".txt")[0];
    double expectedTolerance = MatrixUtils.createRealMatrix(A)
            .operate(MatrixUtils.createRealVector(expectedSol)).subtract(MatrixUtils.createRealVector(b))
            .getNorm();

    //standard form conversion
    double unboundedLBValue = Double.NEGATIVE_INFINITY;//this is because in the file the unbounded lb are -Infinity values (not the default value) 
    double unboundedUBValue = Double.POSITIVE_INFINITY;//this is because in the file the unbounded ub are +Infinity values
    LPStandardConverter lpConverter = new LPStandardConverter(unboundedLBValue, unboundedUBValue);
    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().toArray();
    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(G.length, s);
    assertEquals(s + lpConverter.getOriginalN(), n);
    assertEquals(lb.length, n);
    assertEquals(ub.length, n);

    //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);
    RealVector Gxh = GOrig.operate(expectedSolVector).subtract(hOrig);//G.x - h
    RealVector slackVariables = new ArrayRealVector(s);
    for (int i = 0; i < s; i++) {
        slackVariables.setEntry(i, 0. - Gxh.getEntry(i));//the difference from 0
        assertTrue(slackVariables.getEntry(i) >= 0.);
    }
    RealVector sol = slackVariables.append(expectedSolVector);
    RealVector Axmb = AStandard.operate(sol).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+".txt");
    //      Utils.writeDoubleArrayToFile(b, "target" + File.separator   + "standardB"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(lb, "target" + File.separator   + "standardLB"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(ub, "target" + File.separator   + "standardUB"+problemId+".txt");
}

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

/**
 * Standardization of a problem on the form:
 * min(c) s.t./*  w w  w  .ja  va2 s  .c o m*/
 * G.x < h
 * A.x = b
 * lb <= x <= ub
 */
public void testCGhAbLbUb4() throws Exception {
    log.debug("testCGhAbLbUb4");

    String problemId = "4";

    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 nOsSplittingVariables = 0;
    //      for(int i=0; i<lb.length; i++){
    //         if(Double.compare(lb[i], 0.) != 0){
    //            nOsSplittingVariables++;
    //         }
    //      }

    //standard form conversion
    double unboundedLBValue = Double.NaN;//this is because in the file the unbounded lb are NaN values (and also the default value) 
    double unboundedUBValue = Double.NaN;//this is because in the file the unbounded ub are NaN values
    LPStandardConverter lpConverter = new LPStandardConverter(unboundedLBValue, unboundedUBValue);
    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().toArray();
    log.debug("n : " + n);
    log.debug("s : " + s);

    //check consistency
    assertEquals(G.length, s);
    assertEquals(s + lpConverter.getOriginalN() + nOsSplittingVariables, n);
    assertEquals(lb.length, n);
    assertEquals(ub.length, n);

    //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);
    RealVector Gxh = GOrig.operate(expectedSolVector).subtract(hOrig);//G.x - h
    RealVector slackVariables = new ArrayRealVector(s);
    for (int i = 0; i < s; i++) {
        slackVariables.setEntry(i, 0. - Gxh.getEntry(i));//the difference from 0
        assertTrue(slackVariables.getEntry(i) >= 0.);
    }
    RealVector sol = slackVariables.append(expectedSolVector);
    RealVector Axmb = AStandard.operate(sol).subtract(bStandard);
    assertEquals(0., Axmb.getNorm(), expectedTolerance * 1.001);

    //      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+".txt");
    //      Utils.writeDoubleArrayToFile(b, "target" + File.separator   + "standardB"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(lb, "target" + File.separator   + "standardLB"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(ub, "target" + File.separator   + "standardUB"+problemId+".txt");
}