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

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

Introduction

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

Prototype

public abstract int getDimension();

Source Link

Document

Returns the size of the vector.

Usage

From source file:com.bolatu.gezkoncsvlogger.GyroOrientation.RotationKalmanFilter.java

/**
 * Correct the current state estimate with an actual measurement.
 *
 * @param z//from  w  w  w. j  av  a2 s. com
 *            the measurement vector
 * @throws NullArgumentException
 *             if the measurement vector is {@code null}
 * @throws DimensionMismatchException
 *             if the dimension of the measurement vector does not fit
 * @throws SingularMatrixException
 *             if the covariance matrix could not be inverted
 */
public void correct(final RealVector z)
        throws NullArgumentException, DimensionMismatchException, SingularMatrixException {

    // sanity checks
    MathUtils.checkNotNull(z);
    if (z.getDimension() != measurementMatrix.getRowDimension()) {
        throw new DimensionMismatchException(z.getDimension(), measurementMatrix.getRowDimension());
    }

    // S = H * P(k) * H' + R
    RealMatrix s = measurementMatrix.multiply(errorCovariance).multiply(measurementMatrixT)
            .add(measurementModel.getMeasurementNoise());

    // Inn = z(k) - H * xHat(k)-
    RealVector innovation = z.subtract(measurementMatrix.operate(stateEstimation));

    // calculate gain matrix
    // K(k) = P(k)- * H' * (H * P(k)- * H' + R)^-1
    // K(k) = P(k)- * H' * S^-1

    // instead of calculating the inverse of S we can rearrange the formula,
    // and then solve the linear equation A x X = B with A = S', X = K' and
    // B = (H * P)'

    // K(k) * S = P(k)- * H'
    // S' * K(k)' = H * P(k)-'
    RealMatrix kalmanGain = new CholeskyDecomposition(s).getSolver()
            .solve(measurementMatrix.multiply(errorCovariance.transpose())).transpose();

    // update estimate with measurement z(k)
    // xHat(k) = xHat(k)- + K * Inn
    stateEstimation = stateEstimation.add(kalmanGain.operate(innovation));

    // update covariance of prediction error
    // P(k) = (I - K * H) * P(k)-
    RealMatrix identity = MatrixUtils.createRealIdentityMatrix(kalmanGain.getRowDimension());
    errorCovariance = identity.subtract(kalmanGain.multiply(measurementMatrix)).multiply(errorCovariance);
}

From source file:edu.stanford.cfuller.imageanalysistools.fitting.BisquareLinearFit.java

/**
* Performs a weighted least squares fit with supplied weights to the supplied data.
* 
* @param indVarValues A RealVector containing the values of the independent variable.
* @param depVarValues A RealVector containing the values of the dependent variable.
* @param weights A RealVector containing the weights for the data points.
* @return a RealVector containing two elements: the slope of the fit and the y-intercept of the fit.
*//* w  w  w . j a  v  a 2 s.c  o m*/
public RealVector wlsFit(RealVector indVarValues, RealVector depVarValues, RealVector weights) {

    //initial guess for the fit: unweighted regression.

    SimpleRegression unweighted = new SimpleRegression(!this.noIntercept);

    for (int i = 0; i < indVarValues.getDimension(); i++) {
        unweighted.addData(indVarValues.getEntry(i), depVarValues.getEntry(i));
    }

    RealVector parameters = null;

    if (this.noIntercept) {
        parameters = new ArrayRealVector(1, 0.0);
    } else {
        parameters = new ArrayRealVector(2, 0.0);
    }

    parameters.setEntry(0, unweighted.getSlope());

    if (!this.noIntercept) {
        parameters.setEntry(1, unweighted.getIntercept());
    }

    NelderMeadMinimizer nmm = new NelderMeadMinimizer(1e-12);
    WlsObjectiveFunction wof = new WlsObjectiveFunction();
    wof.setIndVar(indVarValues);
    wof.setDepVar(depVarValues);
    wof.setWeights(weights);
    wof.setShouldFitIntercept(!this.noIntercept);

    parameters = nmm.optimize(wof, parameters);

    if (this.noIntercept) {
        RealVector output = new ArrayRealVector(2, 0.0);
        output.setEntry(0, parameters.getEntry(0));
        return output;
    }

    return parameters;

}

From source file:edu.stanford.cfuller.imageanalysistools.fitting.DifferentialEvolutionMinimizer.java

/**
 * Performs a minimization of a function starting with a given population.
 * //from w  ww .j  a  v a  2s  . c o m
 * @param population            The population of parameters to start from, one population entry per row, one parameter per column.
 * @param f                     The function to be minimized.
 * @param parameterLowerBounds  The lower bounds of each parameter.  This must have the same size as the column dimension of the population.  Generated parameter values less than these values will be discarded.
 * @param parameterUpperBounds  The upper bounds of each paraemter.  This must have the same size as the column dimension of the population.  Generated parameter values greater than these values will be discarded.
 * @param populationSize        The size of the population of parameters sets.  This must be equal to the row dimension of the population.
 * @param scaleFactor           Factor controlling the scale of crossed over entries during crossover events.
 * @param maxIterations         The maximum number of iterations to allow before returning a result.
 * @param crossoverFrequency    The frequency of crossover from 0 to 1.  At any given parameter, this is the probability of initiating a crossover as well as the probability of ending one after it has started.
 * @param tol                   Relative function value tolerance controlling termination; if the maximal and minimal population values differ by less than this factor times the maximal value, optimization will terminate.
 * @return                      The parameter values at the minimal function value found.
 */
public RealVector minimizeWithPopulation(RealMatrix population, ObjectiveFunction f,
        RealVector parameterLowerBounds, RealVector parameterUpperBounds, int populationSize,
        double scaleFactor, int maxIterations, double crossoverFrequency, double tol) {

    int numberOfParameters = parameterLowerBounds.getDimension();

    double currMinValue = Double.MAX_VALUE;
    double currMaxValue = -1.0 * Double.MAX_VALUE;
    int iterationCounter = maxIterations;

    double mutationProb = 0.01;

    //        int totalIterations =0;

    RealVector values = new ArrayRealVector(populationSize);

    boolean[] valuesChanged = new boolean[populationSize];

    java.util.Arrays.fill(valuesChanged, true);

    computeValues(f, population, values, valuesChanged);

    RealVector newVec = new ArrayRealVector(numberOfParameters);

    RealMatrix newPopulation = new Array2DRowRealMatrix(populationSize, numberOfParameters);

    while (iterationCounter > 0) {

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

            int i1 = RandomGenerator.getGenerator().randInt(populationSize);
            int i2 = RandomGenerator.getGenerator().randInt(populationSize);
            int i3 = RandomGenerator.getGenerator().randInt(populationSize);

            newVec.mapMultiplyToSelf(0.0);

            boolean inBounds = true;

            boolean isCrossingOver = false;

            for (int j = 0; j < numberOfParameters; j++) {

                if ((RandomGenerator.rand() < crossoverFrequency) ^ isCrossingOver) {

                    if (!isCrossingOver) {
                        isCrossingOver = true;
                    }

                    newVec.setEntry(j, scaleFactor * (population.getEntry(i2, j) - population.getEntry(i1, j))
                            + population.getEntry(i3, j));

                } else {

                    if (isCrossingOver) {
                        isCrossingOver = false;
                    }

                    newVec.setEntry(j, population.getEntry(i, j));

                }

                //random 10% range +/- mutation

                if ((RandomGenerator.rand() < mutationProb)) {

                    double magnitude = 0.2
                            * (parameterUpperBounds.getEntry(j) - parameterLowerBounds.getEntry(j));

                    newVec.setEntry(j, newVec.getEntry(j) + (RandomGenerator.rand() - 0.5) * magnitude);

                }

                if (newVec.getEntry(j) < parameterLowerBounds.getEntry(j)
                        || newVec.getEntry(j) > parameterUpperBounds.getEntry(j)) {

                    inBounds = false;

                }

            }

            double functionValue = Double.MAX_VALUE;

            if (inBounds)
                functionValue = f.evaluate(newVec);

            //if (inBounds) System.out.printf("in bounds candidate value: %1.2f  old value: %1.2f \n", functionValue, values.getEntry(i));

            if (functionValue < values.getEntry(i)) {

                newPopulation.setRowVector(i, newVec);
                valuesChanged[i] = true;
                values.setEntry(i, functionValue);

            } else {

                newPopulation.setRowVector(i, population.getRowVector(i));
                valuesChanged[i] = false;
            }

        }

        population = newPopulation;

        double tempMinValue = Double.MAX_VALUE;
        double tempMaxValue = -1.0 * Double.MAX_VALUE;

        //            double averageValue = 0;

        for (int i = 0; i < values.getDimension(); i++) {
            double value = values.getEntry(i);
            //                averageValue += value;
            if (value < tempMinValue) {
                tempMinValue = value;
            }
            if (value > tempMaxValue) {
                tempMaxValue = value;
            }

        }

        //            averageValue /= values.getDimension();

        currMinValue = tempMinValue;
        currMaxValue = tempMaxValue;

        //LoggingUtilities.getLogger().info("Iteration counter: " + Integer.toString(totalIterations) + "  best score: " + currMinValue + "  worst score: " + currMaxValue + " average score: " + averageValue);

        if (Math.abs(currMaxValue - currMinValue) < Math.abs(tol * currMaxValue)
                + Math.abs(tol * currMinValue)) {
            iterationCounter--;
        } else {
            iterationCounter = 1;
        }

        //            totalIterations++;

    }

    for (int i = 0; i < populationSize; i++) {
        valuesChanged[i] = true;
    }

    computeValues(f, population, values, valuesChanged);

    double tempMinValue = Double.MAX_VALUE;
    int tempMinIndex = 0;

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

        if (values.getEntry(i) < tempMinValue) {
            tempMinValue = values.getEntry(i);
            tempMinIndex = i;
        }
    }

    RealVector output = new ArrayRealVector(numberOfParameters);

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

        output.setEntry(i, population.getEntry(tempMinIndex, i));

    }

    return output;

}

From source file:edu.stanford.cfuller.imageanalysistools.clustering.ObjectClustering.java

/**
 * Applies basic clustering to an Image with objects.
 *
 * This will use the long-range gaussian filtering approach to assign clusters; objects sufficiently near to each other will be smeared into a single object and assigned to the same cluster.
 *
 * @param input             An Image mask labeled such that each object in the Image is assigned a unique nonzero greylevel value.  These should start at 1 and be consecutive.
 * @param original          The original image (not currently used... this is here to maintain the interface with a previous version that used this image)
 * @param gaussianFiltered  The mask with a long range Gaussian filter applied (as from {@link #gaussianFilterMask}).  This is an optional parameter;
 *                          input null to have this automatically generated by the method.  This parameter is
 *                          chiefly useful to save computation time when running the clutering multiple times.
 *                          This will be modified, so if planning to reuse the Gaussian filtered image, pass in a copy.
 *//*from w w w . j a  va 2  s  .  c om*/
public static Image doBasicClustering(WritableImage input, Image original, Image gaussianFiltered) {

    RelabelFilter rlf = new RelabelFilter();
    LabelFilter lf = new LabelFilter();
    MaskFilter mf = new MaskFilter();

    mf.setReferenceImage(input);

    Histogram h_individualCentromeres = new Histogram(input);

    WritableImage origCopy = null;

    if (gaussianFiltered == null) {

        origCopy = gaussianFilterMask(input).getWritableInstance();

    } else {
        origCopy = gaussianFiltered.getWritableInstance();
    }

    lf.apply(origCopy);

    WritableImage mapped = ImageFactory.createWritable(origCopy);

    Histogram h_mapped_0 = new Histogram(origCopy);

    //first, find the centroid of each cluster

    org.apache.commons.math3.linear.RealVector centroids_x = new ArrayRealVector(h_mapped_0.getMaxValue() + 1);
    org.apache.commons.math3.linear.RealVector centroids_y = new ArrayRealVector(h_mapped_0.getMaxValue() + 1);

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

    centroids_x.mapMultiplyToSelf(0.0);
    centroids_y.mapMultiplyToSelf(0.0);
    counts.mapMultiplyToSelf(0.0);

    for (ImageCoordinate i : origCopy) {
        if (origCopy.getValue(i) > 0) {
            int value = (int) origCopy.getValue(i);
            centroids_x.setEntry(value, centroids_x.getEntry(value) + i.get(ImageCoordinate.X));
            centroids_y.setEntry(value, centroids_y.getEntry(value) + i.get(ImageCoordinate.Y));
            counts.setEntry(value, counts.getEntry(value) + 1);
        }
    }
    for (int i = 0; i < counts.getDimension(); i++) {
        if (counts.getEntry(i) == 0) {
            counts.setEntry(i, 1);
            centroids_x.setEntry(i, -1 * origCopy.getDimensionSizes().get(ImageCoordinate.X));
            centroids_y.setEntry(i, -1 * origCopy.getDimensionSizes().get(ImageCoordinate.Y));
        }
        centroids_x.setEntry(i, centroids_x.getEntry(i) / counts.getEntry(i));
        centroids_y.setEntry(i, centroids_y.getEntry(i) / counts.getEntry(i));

    }

    for (ImageCoordinate i : origCopy) {

        if (mapped.getValue(i) > 0 || input.getValue(i) == 0)
            continue;

        double minDistance = Double.MAX_VALUE;
        int minIndex = 0;

        for (int j = 0; j < centroids_x.getDimension(); j++) {
            double dist = Math.hypot(centroids_x.getEntry(j) - i.get(ImageCoordinate.X),
                    centroids_y.getEntry(j) - i.get(ImageCoordinate.Y));
            if (dist < minDistance) {
                minDistance = dist;
                minIndex = j;
            }
        }

        mapped.setValue(i, minIndex);

    }

    int[] centromereAssignments = new int[h_individualCentromeres.getMaxValue() + 1];
    java.util.Arrays.fill(centromereAssignments, 0);

    for (ImageCoordinate i : mapped) {

        if (input.getValue(i) > 0) {

            int value = (int) input.getValue(i);

            if (centromereAssignments[value] > 0) {
                mapped.setValue(i, centromereAssignments[value]);
            } else {
                centromereAssignments[value] = (int) mapped.getValue(i);
            }

        }
    }

    mf.apply(mapped);
    origCopy.copy(mapped);
    mf.setReferenceImage(origCopy);

    mf.apply(input);
    rlf.apply(input);
    rlf.apply(origCopy);

    return origCopy;
}

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.
 *///w  w w.ja  va  2 s.com
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  .  com
 * 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:com.joptimizer.optimizers.LPStandardConverterTest.java

/**
 * Standardization (to the strictly standard form) of a problem on the form:
 * min(c) s.t.//  w  w  w .  ja  va  2 s .c om
 * 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:edu.utexas.cs.tactex.servercustomers.factoredcustomer.DefaultCapacityOriginator.java

/**
 * NOTE: subtle conversion that caused a bug - we use predictions
 * starting next time-step, but forecastCapacities are assumed
 * to be from current - so to return data to broker we need to
 * offset the record by 1//from  www  . j a v a2s .c o m
 */
@Override
public void convertEnergyProfileFromBrokerToServer(RealVector originatorEnergy, int currentTimeslot) {

    final int brokerEnergyRecordLength = originatorEnergy.getDimension();
    for (int i = 0; i < CapacityProfile.NUM_TIMESLOTS; ++i) {
        //log.info("updateForecastCapacities(" + (currentTimeslot + i) + ")=" +  originatorEnergy.getEntry(i));
        int i_minus_1_that_will_work_for_modulo = CapacityProfile.NUM_TIMESLOTS + i - 1;
        forecastCapacities.put(currentTimeslot + i,
                originatorEnergy.getEntry(i_minus_1_that_will_work_for_modulo % CapacityProfile.NUM_TIMESLOTS));
    }
}

From source file:com.cloudera.oryx.common.math.OpenMapRealVector.java

/**
 * Generic copy constructor.//  ww  w .  ja  v a  2s .  c o  m
 *
 * @param v Instance to copy from.
 */
public OpenMapRealVector(RealVector v) {
    virtualSize = v.getDimension();
    entries = new OpenIntToDoubleHashMap(0.0);
    epsilon = DEFAULT_ZERO_TOLERANCE;
    for (int key = 0; key < virtualSize; key++) {
        double value = v.getEntry(key);
        if (!isDefaultValue(value)) {
            entries.put(key, value);
        }
    }
}

From source file:com.cloudera.oryx.common.math.OpenMapRealVector.java

@Override
public RealVector add(RealVector v) {
    checkVectorDimensions(v.getDimension());
    if (v instanceof OpenMapRealVector) {
        return add((OpenMapRealVector) v);
    } else {/* w  w  w  .  jav a 2s  . c o m*/
        return super.add(v);
    }
}