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

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

Introduction

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

Prototype

public abstract void setEntry(int index, double value) throws OutOfRangeException;

Source Link

Document

Set a single element.

Usage

From source file:net.liuxuan.temp.filterTest.java

public static void main(String[] args) {
    double constantVoltage = 10d;
    double measurementNoise = 0.1d;
    double processNoise = 1e-5d;

    // A = [ 1 ]/*from   ww  w.ja v a  2  s  . co  m*/
    RealMatrix A = new Array2DRowRealMatrix(new double[] { 1d });
    // B = null
    RealMatrix B = null;
    // H = [ 1 ]
    RealMatrix H = new Array2DRowRealMatrix(new double[] { 1d });
    // x = [ 10 ]
    RealVector x = new ArrayRealVector(new double[] { constantVoltage });
    // Q = [ 1e-5 ]
    RealMatrix Q = new Array2DRowRealMatrix(new double[] { processNoise });
    // P = [ 1 ]
    RealMatrix P0 = new Array2DRowRealMatrix(new double[] { 1d });
    // R = [ 0.1 ]
    RealMatrix R = new Array2DRowRealMatrix(new double[] { measurementNoise });

    ProcessModel pm = new DefaultProcessModel(A, B, Q, x, P0);
    MeasurementModel mm = new DefaultMeasurementModel(H, R);
    KalmanFilter filter = new KalmanFilter(pm, mm);

    // process and measurement noise vectors
    RealVector pNoise = new ArrayRealVector(1);
    RealVector mNoise = new ArrayRealVector(1);

    RandomGenerator rand = new JDKRandomGenerator();
    // iterate 60 steps
    for (int i = 0; i < 60; i++) {
        filter.predict();

        // simulate the process
        //            pNoise.setEntry(0, processNoise * rand.nextGaussian());
        pNoise.setEntry(0, Math.sin(Math.PI * 2 * i / 6));
        //            System.out.println("============");
        //            System.out.println(Math.sin(Math.PI*2*i/6));

        // x = A * x + p_noise
        x = A.operate(x).add(pNoise);
        // simulate the measurement
        //            mNoise.setEntry(0, measurementNoise * rand.nextGaussian());
        mNoise.setEntry(0, 0);

        // z = H * x + m_noise
        RealVector z = H.operate(x).add(mNoise);
        filter.correct(z);

        double voltage = filter.getStateEstimation()[0];
        System.out.println(voltage);

        // state estimate shouldn't be larger than the measurement noise
        double diff = Math.abs(x.getEntry(0) - filter.getStateEstimation()[0]);
        System.out.println("diff = " + diff);

    }
}

From source file:edu.byu.nlp.math.RealVectors.java

public static void incrementEntry(RealVector v, int index) {
    v.setEntry(index, v.getEntry(index) + 1);
}

From source file:edu.byu.nlp.math.RealVectors.java

public static void decrementEntry(RealVector v, int index) {
    v.setEntry(index, v.getEntry(index) - 1);
}

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

public static RealVector toRealVector(final Instance inst) {
    final RealVector v = new ArrayRealVector(inst.numAttributes());
    for (int i = 0; i < inst.numAttributes(); ++i) {
        v.setEntry(i, inst.value(i));
    }//from  w  w  w .  ja v a2  s  . co m
    return v;
}

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

/**
 * Computes a Newton-Raphson update in-place to alpha.
 *///from   ww w  .  j av a 2 s.  c  o m
private static RealVector newtonRaphsonUpdate(final double[][] data, double[] alpha) {
    // We'll compute the gold-standard value the "long" way (taking the inverse of the Hessian)
    RealMatrix hessian = new Array2DRowRealMatrix(alpha.length, alpha.length);
    for (int r = 0; r < hessian.getRowDimension(); r++) {
        for (int c = 0; c < hessian.getColumnDimension(); c++) {
            hessian.addToEntry(r, c, data.length * Gamma.trigamma(DoubleArrays.sum(alpha)));
            if (r == c) {
                hessian.addToEntry(r, c, -data.length * Gamma.trigamma(alpha[r]));
            }
        }
    }
    RealVector derivative = new ArrayRealVector(alpha.length);
    for (int k = 0; k < alpha.length; k++) {
        derivative.setEntry(k,
                data.length * (Gamma.digamma(DoubleArrays.sum(alpha)) - Gamma.digamma(alpha[k])));
        for (double[] theta : data) {
            derivative.addToEntry(k, theta[k]);
        }
    }

    RealMatrix hessianInverse = new LUDecomposition(hessian).getSolver().getInverse();
    RealVector negDiff = hessianInverse.preMultiply(derivative);
    negDiff.mapMultiplyToSelf(-1.0);

    RealVector expected = new ArrayRealVector(alpha, true);
    return expected.add(negDiff);
}

From source file:com.cloudera.oryx.kmeans.common.pmml.KMeansPMML.java

private static RealVector createCenter(Array array, boolean sparse, int fieldCount) {
    if (array.getN() != fieldCount) {
        return null;
    }//from  w ww  .  jav  a 2s. c om
    RealVector v = sparse ? Vectors.sparse(fieldCount) : Vectors.dense(fieldCount);
    int i = 0;
    for (String token : SPACE.split(array.getValue())) {
        double t = Double.parseDouble(token);
        if (t != 0.0) {
            v.setEntry(i, t);
        }
        i++;
    }
    return v;
}

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

/**
 * Performs Gaussian mixture model clustering on the given inputs using a differential evolution algorithm for maximization of the likelihood of having observed the data.
 * @param singleCluster     An Image mask with each object to be clustered labeled with a unique greylevel value.  (Note that the name stems from this method's original use to recursively divide existing single clusters; this need not actually correspond to a single cluster).
 * @param clusterObjects    A Vector containing an initialized ClusterObject for each object present in the Image passed as singleCluster.
 * @param clusters          A Vector containing an initialized Cluster (guess) for each of the k clusters that will be determined.
 * @param k                 The number of clusters to end up with.
 * @param n                 The number of cluster objects.
 * @return                  The negative log likelihood of observing the objects at their locations, given the maximally likely clustering scheme found.  On return, clusterObjects and clusters will have been updated to reflect this maximally likely scheme.
 *///from w  w w .  ja  va  2  s  .  co  m
public static double go(Image singleCluster, java.util.Vector<ClusterObject> clusterObjects,
        java.util.Vector<Cluster> clusters, int k, int n) {

    final int numParametersEach = 5;

    int numParameters = k * numParametersEach;

    int populationSize = numParameters;

    double tol = 1.0e-3;
    double scaleFactor = 0.9;
    double crFrq = 0.05;
    int maxIterations = 10;

    RealVector parameterLowerBounds = new ArrayRealVector(numParameters);
    RealVector parameterUpperBounds = new ArrayRealVector(numParameters);

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

        parameterLowerBounds.setEntry(numParametersEach * i,
                -0.1 * singleCluster.getDimensionSizes().get(ImageCoordinate.X));
        parameterLowerBounds.setEntry(numParametersEach * i + 1,
                -0.1 * singleCluster.getDimensionSizes().get(ImageCoordinate.Y));
        parameterLowerBounds.setEntry(numParametersEach * i + 2, tol);
        parameterLowerBounds.setEntry(numParametersEach * i + 3, -1);
        parameterLowerBounds.setEntry(numParametersEach * i + 4, tol);

        parameterUpperBounds.setEntry(numParametersEach * i,
                1.1 * singleCluster.getDimensionSizes().get(ImageCoordinate.X));
        parameterUpperBounds.setEntry(numParametersEach * i + 1,
                1.1 * singleCluster.getDimensionSizes().get(ImageCoordinate.Y));
        parameterUpperBounds.setEntry(numParametersEach * i + 2,
                Math.pow(0.05 * singleCluster.getDimensionSizes().get(ImageCoordinate.X), 2));
        parameterUpperBounds.setEntry(numParametersEach * i + 3, 1);
        parameterUpperBounds.setEntry(numParametersEach * i + 4,
                Math.pow(0.05 * singleCluster.getDimensionSizes().get(ImageCoordinate.Y), 2));

    }

    ObjectiveFunction f = new GaussianLikelihoodObjectiveFunction(clusterObjects);

    DifferentialEvolutionMinimizer dem = new DifferentialEvolutionMinimizer();

    RealVector output = null;

    double L = Double.MAX_VALUE;

    while (L == Double.MAX_VALUE || output == null) {
        output = dem.minimize(f, parameterLowerBounds, parameterUpperBounds, populationSize, scaleFactor,
                maxIterations, crFrq, tol);
        L = f.evaluate(output);
    }

    //set up new clusters

    for (int i = 0; i < k; i++) {
        clusters.get(i).setCentroidComponents(output.getEntry(numParametersEach * i),
                output.getEntry(numParametersEach * i + 1), 0);
        clusters.get(i).setID(i + 1);
        clusters.get(i).getObjectSet().clear();
    }

    //assign objects to clusters

    for (ClusterObject c : clusterObjects) {
        c.setCurrentCluster(clusters.get(c.getMostProbableCluster()));
        c.getCurrentCluster().getObjectSet().add(c);
    }

    return L;

}

From source file:edu.stanford.cfuller.imageanalysistools.filter.LocalBackgroundEstimationFilter.java

protected static void swap(int first, int second, RealVector toProcess) {
    double value = toProcess.getEntry(first);
    toProcess.setEntry(first, toProcess.getEntry(second));
    toProcess.setEntry(second, value);//from  w  w w  .  ja  va 2 s .  c om
}

From source file:com.datumbox.common.dataobjects.MatrixDataset.java

public static RealVector parseRecord(Record r, Map<Object, Integer> featureIdsReference) {
    if (featureIdsReference.isEmpty()) {
        throw new RuntimeException("The featureIdsReference map should not be empty.");
    }//from w  w  w.j a  v a  2  s. c o  m

    int d = featureIdsReference.size();

    RealVector v = new ArrayRealVector(d);

    boolean addConstantColumn = featureIdsReference.containsKey(Dataset.constantColumnName);

    if (addConstantColumn) {
        v.setEntry(0, 1.0); //add the constant column
    }
    for (Map.Entry<Object, Object> entry : r.getX().entrySet()) {
        Object feature = entry.getKey();
        Double value = Dataset.toDouble(entry.getValue());
        if (value != null) {
            Integer featureId = featureIdsReference.get(feature);
            if (featureId != null) {//if the feature exists in our database
                v.setEntry(featureId, value);
            }
        } else {
            //else the X matrix maintains the 0.0 default value
        }
    }

    return v;
}

From source file:com.datumbox.framework.common.dataobjects.MatrixDataframe.java

/**
 * Parses a single Record and converts it to RealVector by using an already
 * existing mapping between feature names and column ids. 
 * //from  w  ww . j  a v  a  2s. co  m
 * @param r
 * @param featureIdsReference
 * @return 
 */
public static RealVector parseRecord(Record r, Map<Object, Integer> featureIdsReference) {
    if (featureIdsReference.isEmpty()) {
        throw new IllegalArgumentException("The featureIdsReference map should not be empty.");
    }

    int d = featureIdsReference.size();

    RealVector v = new ArrayRealVector(d);

    boolean addConstantColumn = featureIdsReference.containsKey(Dataframe.COLUMN_NAME_CONSTANT);

    if (addConstantColumn) {
        v.setEntry(0, 1.0); //add the constant column
    }
    for (Map.Entry<Object, Object> entry : r.getX().entrySet()) {
        Object feature = entry.getKey();
        Double value = TypeInference.toDouble(entry.getValue());
        if (value != null) {
            Integer featureId = featureIdsReference.get(feature);
            if (featureId != null) {//if the feature exists in our database
                v.setEntry(featureId, value);
            }
        } else {
            //else the X matrix maintains the 0.0 default value
        }
    }

    return v;
}