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

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

Introduction

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

Prototype

public RealVector mapDivideToSelf(double d) 

Source Link

Document

Divide each entry by the argument.

Usage

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

private RealVector centerOfMass(final int c) {
    final RealVector com = new ArrayRealVector(m_, 0);
    int nelements = 0;
    for (int i = 0; i < n_; ++i) {
        if (c_[i] == c) {
            nelements += 1;// w  w  w . ja  va 2  s  .  c o m
            com.combineToSelf(1.0, 1.0, data_[i]); // Add in-place
        }
    }
    assert (nelements > 0);
    com.mapDivideToSelf(nelements);
    return com;
}

From source file:com.analog.lyric.dimple.test.solvers.sumproduct.TestSampledFactors.java

/**
 * Adapted from MATLAB test4 in tests/algoGaussian/testSampledFactors.m
 *///from  ww  w .java  2s  .c  o m
@Test
public void sampledComplexProduct() {
    // NOTE: test may fail if seed is changed! We keep the number of samples down so that the test doesn't
    // take too long. Increasing the samples produces better results.

    testRand.setSeed(42);

    try (CurrentModel cur = using(new FactorGraph())) {
        final Complex a = complex("a");
        final Complex b = complex("b");
        final Complex c = product(a, b);

        double[] aMean = new double[] { 10, 10 };
        RealMatrix aCovariance = randCovariance(2);
        a.setPrior(new MultivariateNormal(aMean, aCovariance.getData()));

        double[] bMean = new double[] { -20, 20 };
        RealMatrix bCovariance = randCovariance(2);
        b.setPrior(new MultivariateNormalParameters(bMean, bCovariance.getData()));

        GaussianRandomGenerator normalGenerator = new GaussianRandomGenerator(testRand);
        CorrelatedRandomVectorGenerator aGenerator = new CorrelatedRandomVectorGenerator(aMean, aCovariance,
                1e-12, normalGenerator);
        CorrelatedRandomVectorGenerator bGenerator = new CorrelatedRandomVectorGenerator(bMean, bCovariance,
                1e-12, normalGenerator);

        StorelessCovariance expectedCov = new StorelessCovariance(2);

        final int nSamples = 10000;

        RealVector expectedMean = MatrixUtils.createRealVector(new double[2]);
        double[] cSample = new double[2];

        for (int i = 0; i < nSamples; ++i) {
            double[] aSample = aGenerator.nextVector();
            double[] bSample = bGenerator.nextVector();

            // Compute complex product
            cSample[0] = aSample[0] * bSample[0] - aSample[1] * bSample[1];
            cSample[1] = aSample[0] * bSample[1] + aSample[1] * bSample[0];

            expectedMean.addToEntry(0, cSample[0]);
            expectedMean.addToEntry(1, cSample[1]);

            expectedCov.increment(cSample);
        }

        expectedMean.mapDivideToSelf(nSamples); // normalize

        SumProductSolverGraph sfg = requireNonNull(cur.graph.setSolverFactory(new SumProductSolver()));
        sfg.setOption(GibbsOptions.numSamples, nSamples);

        sfg.solve();

        MultivariateNormalParameters cBelief = requireNonNull(c.getBelief());

        RealVector observedMean = MatrixUtils.createRealVector(cBelief.getMean());
        double scaledMeanDistance = expectedMean.getDistance(observedMean) / expectedMean.getNorm();

        //         System.out.format("expectedMean = %s\n", expectedMean);
        //         System.out.format("observedMean = %s\n", observedMean);
        //         System.out.println(scaledMeanDistance);

        assertEquals(0.0, scaledMeanDistance, .02);

        RealMatrix expectedCovariance = expectedCov.getCovarianceMatrix();
        RealMatrix observedCovariance = MatrixUtils.createRealMatrix(cBelief.getCovariance());
        RealMatrix diffCovariance = expectedCovariance.subtract(observedCovariance);

        double scaledCovarianceDistance = diffCovariance.getNorm() / expectedCovariance.getNorm();

        //         System.out.println(expectedCovariance);
        //         System.out.println(expectedCovariance.getNorm());
        //         System.out.println(diffCovariance);
        //         System.out.println(diffCovariance.getNorm());
        //         System.out.println(diffCovariance.getNorm() / expectedCovariance.getNorm());

        assertEquals(0.0, scaledCovarianceDistance, .2);
    }
}

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

/**
* Applies an existing correction to the positions of a set of objects, using a specified reference
* and correction channel.// ww w  .  j a va 2  s  . c  o  m
* 
* @param imageObjects                  A Vector containing all the ImageObjects to be corrected.
* @param c                             The Correction object to be used, which could have been generated with determineCorrection, or loaded from disk.
* @return                              A RealVector with one entry per ImageObject, containing the corrected scalar distance between the object in the reference channel and the channel being corrected.
*/
public RealVector applyCorrection(Correction c, java.util.List<ImageObject> imageObjects) {

    int referenceChannel = this.parameters.getIntValueForKey(REF_CH_PARAM);

    int channelToCorrect = this.parameters.getIntValueForKey(CORR_CH_PARAM);

    RealVector diffs = new ArrayRealVector(imageObjects.size(), 0.0);
    RealVector averageVectorDiffs = null;

    for (int i = 0; i < imageObjects.size(); i++) {

        diffs.setEntry(i, imageObjects.get(i).getScalarDifferenceBetweenChannels(referenceChannel,
                channelToCorrect, this.pixelToDistanceConversions));

        if (i == 0) {
            averageVectorDiffs = imageObjects.get(i)
                    .getVectorDifferenceBetweenChannels(referenceChannel, channelToCorrect).copy();

        } else {
            averageVectorDiffs = averageVectorDiffs.add(imageObjects.get(i)
                    .getVectorDifferenceBetweenChannels(referenceChannel, channelToCorrect).map(new Abs()));
        }

    }

    averageVectorDiffs.mapDivideToSelf(imageObjects.size());
    averageVectorDiffs = averageVectorDiffs.ebeMultiply(this.pixelToDistanceConversions);

    java.util.logging.Logger.getLogger("edu.stanford.cfuller.colocalization3d")
            .info("mean separation uncorrected = " + diffs.getL1Norm() / diffs.getDimension());
    java.util.logging.Logger.getLogger("edu.stanford.cfuller.colocalization3d")
            .info("mean separation components uncorrected = " + averageVectorDiffs.toString());

    RealVector newDiffs = new ArrayRealVector(imageObjects.size(), 0.0);

    if (this.parameters.getBooleanValueForKey("correct_images")) {

        for (int i = 0; i < imageObjects.size(); i++) {

            try {

                newDiffs.setEntry(i, this.correctSingleObjectVectorDifference(c, imageObjects.get(i),
                        referenceChannel, channelToCorrect).getNorm());

                imageObjects.get(i).setCorrectionSuccessful(true);

            } catch (UnableToCorrectException e) {

                newDiffs.setEntry(i, -1.0 * Double.MAX_VALUE);

                imageObjects.get(i).setCorrectionSuccessful(false);

            }

        }

        java.util.logging.Logger.getLogger("edu.stanford.cfuller.colocalization3d")
                .info("mean separation corrected = " + newDiffs.getL1Norm() / newDiffs.getDimension());

    } else {
        newDiffs = diffs;
    }

    return newDiffs;
}

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

/**
 * Runs the minimization of the specified function starting from an initial simplex.
 * @param f                 The ObjectiveFunction to be minimized.
 * @param initialSimplex    The initial simplex to use to start optimization, as might be returned from {@link #generateInitialSimplex}
 * @return                  The parameters at the function minimum in the same order as specified for each point on the simplex.
 *///w  ww. ja  v  a2s  .  c  o m
public RealVector optimize(ObjectiveFunction f, RealMatrix initialSimplex) {

    RealMatrix currentSimplex = initialSimplex.copy();

    double currTolVal = 1.0e6;

    RealVector values = new ArrayRealVector(initialSimplex.getRowDimension(), 0.0);

    RealVector centerOfMass = new ArrayRealVector(initialSimplex.getColumnDimension(), 0.0);

    boolean shouldEvaluate = false;

    long iterCounter = 0;

    while (Math.abs(currTolVal) > this.tol) {

        int maxIndex = 0;
        int minIndex = 0;
        double maxValue = -1.0 * Double.MAX_VALUE;
        double minValue = Double.MAX_VALUE;
        double secondMaxValue = -1.0 * Double.MAX_VALUE;

        centerOfMass.mapMultiplyToSelf(0.0);

        if (shouldEvaluate) {

            for (int i = 0; i < currentSimplex.getRowDimension(); i++) {
                RealVector currRow = currentSimplex.getRowVector(i);
                values.setEntry(i, f.evaluate(currRow));
            }

        }

        for (int i = 0; i < currentSimplex.getRowDimension(); i++) {

            double currValue = values.getEntry(i);

            if (currValue < minValue) {
                minValue = currValue;
                minIndex = i;
            }
            if (currValue > maxValue) {
                secondMaxValue = maxValue;
                maxValue = currValue;
                maxIndex = i;
            } else if (currValue > secondMaxValue) {
                secondMaxValue = currValue;
            }
        }

        for (int i = 0; i < currentSimplex.getRowDimension(); i++) {
            if (i == maxIndex)
                continue;

            centerOfMass = centerOfMass.add(currentSimplex.getRowVector(i));

        }

        centerOfMass.mapDivideToSelf(currentSimplex.getRowDimension() - 1);

        RealVector oldPoint = currentSimplex.getRowVector(maxIndex);

        RealVector newPoint = centerOfMass.subtract(oldPoint).mapMultiplyToSelf(a).add(centerOfMass); // newpoint = COM + a*(COM-oldpoint)

        double newValue = f.evaluate(newPoint);

        if (newValue < secondMaxValue) { // success

            if (newValue < minValue) { // best found so far

                //expansion

                RealVector expPoint = centerOfMass.subtract(oldPoint).mapMultiplyToSelf(g).add(centerOfMass);

                double expValue = f.evaluate(expPoint);

                if (expValue < newValue) {
                    currentSimplex.setRowVector(maxIndex, expPoint);
                    currTolVal = 2.0 * (expValue - maxValue) / (1.0e-20 + expValue + maxValue);

                    values.setEntry(maxIndex, expValue);
                    shouldEvaluate = false;
                    continue;
                }

            }

            //reflection

            currentSimplex.setRowVector(maxIndex, newPoint);
            currTolVal = 2.0 * (newValue - maxValue) / (1.0e-20 + newValue + maxValue);
            values.setEntry(maxIndex, newValue);
            shouldEvaluate = false;
            continue;

        }

        //contraction

        RealVector conPoint = centerOfMass.subtract(oldPoint).mapMultiplyToSelf(r).add(centerOfMass);
        double conValue = f.evaluate(conPoint);

        if (conValue < maxValue) {
            currentSimplex.setRowVector(maxIndex, conPoint);
            currTolVal = 2.0 * (conValue - maxValue) / (1.0e-20 + conValue + maxValue);
            values.setEntry(maxIndex, conValue);
            shouldEvaluate = false;
            continue;
        }

        //reduction

        for (int i = 0; i < currentSimplex.getRowDimension(); i++) {
            if (i == minIndex)
                continue;

            currentSimplex.setRowVector(i,
                    currentSimplex.getRowVector(i).subtract(currentSimplex.getRowVector(minIndex))
                            .mapMultiplyToSelf(s).add(currentSimplex.getRowVector(minIndex)));

        }

        double redValue = f.evaluate(currentSimplex.getRowVector(maxIndex));

        currTolVal = 2.0 * (redValue - maxValue) / (1.0e-20 + redValue + maxValue);

        shouldEvaluate = true;

        if (iterCounter++ > 100000) {
            System.out.println("stalled?  tol: " + currTolVal + "  minValue: " + minValue);
        }

    }

    double minValue = Double.MAX_VALUE;

    RealVector minVector = null;

    for (int i = 0; i < currentSimplex.getRowDimension(); i++) {
        values.setEntry(i, f.evaluate(currentSimplex.getRowVector(i)));
        if (values.getEntry(i) < minValue) {
            minValue = values.getEntry(i);
            minVector = currentSimplex.getRowVector(i);
        }
    }

    return minVector;

}

From source file:org.apache.predictionio.examples.java.recommendations.tutorial4.FeatureBasedAlgorithm.java

public FeatureBasedModel train(PreparedData data) {
    Map<Integer, RealVector> userFeatures = new HashMap<Integer, RealVector>();
    Map<Integer, Integer> userActions = new HashMap<Integer, Integer>();

    for (Integer uid : data.userInfo.keySet()) {
        userFeatures.put(uid, new ArrayRealVector(data.featureCount));
        userActions.put(uid, 0);/*from   w ww .  j ava  2s .  c  o  m*/
    }

    for (TrainingData.Rating rating : data.ratings) {
        final int uid = rating.uid;
        final int iid = rating.iid;
        final double rate = rating.rating;

        // Skip features outside the range.
        if (!(params.min <= rate && rate <= params.max))
            continue;

        final double actualRate = (rate - params.drift) * params.scale;
        final RealVector userFeature = userFeatures.get(uid);
        final RealVector itemFeature = data.itemFeatures.get(iid);
        userFeature.combineToSelf(1, actualRate, itemFeature);

        userActions.put(uid, userActions.get(uid) + 1);
    }

    // Normalize userFeatures by l-inf-norm
    for (Integer uid : userFeatures.keySet()) {
        final RealVector feature = userFeatures.get(uid);
        feature.mapDivideToSelf(feature.getLInfNorm());
    }

    // Normalize itemFeatures by weight
    Map<Integer, RealVector> itemFeatures = new HashMap<Integer, RealVector>();
    for (Integer iid : data.itemFeatures.keySet()) {
        final RealVector feature = data.itemFeatures.get(iid);
        final RealVector normalizedFeature = feature.mapDivide(feature.getL1Norm());
        itemFeatures.put(iid, normalizedFeature);
    }

    return new FeatureBasedModel(userFeatures, userActions, itemFeatures);
}

From source file:org.grouplens.samantha.modeler.solver.RandomInitializer.java

public void randInitVector(RealVector vec, boolean normalize) {
    int len = vec.getDimension();
    double sum = 0.0;
    for (int i = 0; i < len; i++) {
        double val;
        if (normalize) {
            val = rand.nextDouble();
        } else {/* w  w w  .ja va 2 s .com*/
            val = (rand.nextDouble() - subtract) * multi;
        }
        vec.setEntry(i, val);
        if (normalize) {
            sum += val;
        }
    }
    if (normalize) {
        vec.mapDivideToSelf(sum);
    }
}

From source file:org.lambda3.indra.composition.AveragedVectorComposer.java

@Override
public RealVector compose(List<RealVector> vectors) {
    RealVector res = super.compose(vectors);

    if (vectors != null && vectors.size() > 1) {
        res.mapDivideToSelf(vectors.size());
    }//from  w  ww .  j  a  va2s.  c o m

    return res;
}

From source file:org.lambda3.indra.composition.L2NormSumVectorComposer.java

@Override
public RealVector compose(List<RealVector> vectors) {
    RealVector sum = super.compose(vectors);
    if (vectors.size() > 1) {
        //norm is not calculated for single vectors.
        double norm = sum.getNorm();
        return sum.mapDivideToSelf(norm);
    }//from   w  ww .j a v  a 2 s .com

    return sum;
}