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:gamlss.utilities.MatrixFunctions.java

/**
 * Write vector values to CSV file.//from  w w w  .  j  av a 2  s.c  o m
 * @param cmd - path to the file
 * @param v - vector to write
 */
public static void vectorWriteCSV(final String cmd, final RealVector v, boolean append) {
    try {
        // Create file 
        FileWriter fstream = new FileWriter(cmd, append);
        BufferedWriter out = new BufferedWriter(fstream);

        for (int j = 0; j < v.getDimension(); j++) {
            out.write(Double.toString(v.getEntry(j)));
            out.newLine();
        }
        out.close();
    } catch (Exception e) { //Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}

From source file:com.github.thorbenlindhauer.factor.CanonicalGaussianFactor.java

/**
 * mapping must have the size of the new vector; maps a vector to a new size by applying the mapping of the positions
 * and fills the remaining places with 0 values
 *///w w w  .jav a  2s . co m
protected static RealVector padVector(final RealVector vector, int newSize, final int[] mapping) {
    final RealVector newVector = new ArrayRealVector(newSize);

    newVector.walkInOptimizedOrder(new RealVectorChangingVisitor() {

        @Override
        public double visit(int index, double value) {
            if (mapping[index] >= 0) {
                return vector.getEntry(mapping[index]);
            } else {
                return 0;
            }
        }

        @Override
        public void start(int dimension, int start, int end) {
        }

        @Override
        public double end() {
            return 0;
        }
    });
    return newVector;
}

From source file:edu.tum.cs.vis.model.util.algorithm.ACCUM.java

/**
 * Calculate curvature for vertices of triangle
 * // w  ww  .  j  a v  a 2s  .co m
 * @param curvatures
 *            vertex curvature mapping
 * @param tri
 *            triangle to calculate curvature for
 */
static void calculateCurvatureForTriangle(HashMap<Vertex, Curvature> curvatures, Triangle tri) {
    // Edges
    Vector3f e[] = tri.getEdges();

    // N-T-B coordinate system per face
    Vector3f t = new Vector3f(e[0]);
    t.normalize();
    Vector3f n = new Vector3f();
    n.cross(e[0], e[1]);
    Vector3f b = new Vector3f();
    b.cross(n, t);
    b.normalize();

    // Estimate curvature based on variation of normals
    // along edges
    float m[] = { 0, 0, 0 };
    double w[][] = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } };
    for (int j = 0; j < 3; j++) {

        float u = e[j].dot(t);
        float v = e[j].dot(b);
        w[0][0] += u * u;
        w[0][1] += u * v;
        // w[1][1] += v*v + u*u;
        // w[1][2] += u*v;
        w[2][2] += v * v;
        Vector3f dn = new Vector3f(tri.getPosition()[(j + 2) % 3].getNormalVector());
        dn.sub(tri.getPosition()[(j + 1) % 3].getNormalVector());
        float dnu = dn.dot(t);
        float dnv = dn.dot(b);
        m[0] += dnu * u;
        m[1] += dnu * v + dnv * u;
        m[2] += dnv * v;
    }
    w[1][1] = w[0][0] + w[2][2];
    w[1][2] = w[0][1];

    RealMatrix coefficients = new Array2DRowRealMatrix(w, false);
    DecompositionSolver solver = new LUDecomposition(coefficients).getSolver();
    if (!solver.isNonSingular()) {
        return;
    }

    RealVector constants = new ArrayRealVector(new double[] { m[0], m[1], m[2] }, false);
    RealVector solution = solver.solve(constants);

    m[0] = (float) solution.getEntry(0);
    m[1] = (float) solution.getEntry(1);
    m[2] = (float) solution.getEntry(2);

    // Push it back out to the vertices
    for (int j = 0; j < 3; j++) {
        Vertex vj = tri.getPosition()[j];

        float c1, c12, c2;
        float ret[] = proj_curv(t, b, m[0], m[1], m[2], curvatures.get(vj).getPrincipleDirectionMax(),
                curvatures.get(vj).getPrincipleDirectionMin());
        c1 = ret[0];
        c12 = ret[1];
        c2 = ret[2];

        Curvature c = curvatures.get(vj);

        double wt;
        if (j == 0)
            wt = tri.getCornerarea().x / vj.getPointarea();
        else if (j == 1)
            wt = tri.getCornerarea().y / vj.getPointarea();
        else
            wt = tri.getCornerarea().z / vj.getPointarea();

        synchronized (c) {
            c.setCurvatureMax((float) (c.getCurvatureMax() + wt * c1));
            c.setCurvatureMinMax((float) (c.getCurvatureMinMax() + wt * c12));
            c.setCurvatureMin((float) (c.getCurvatureMin() + wt * c2));
        }
    }
}

From source file:lirmm.inria.fr.math.TestUtils.java

/**
 * Asserts that all entries of the specified vectors are equal to within a
 * positive {@code delta}.//w  w w .j  a  v  a 2s .c  o  m
 *
 * @param message the identifying message for the assertion error (can be
 * {@code null})
 * @param expected expected value
 * @param actual actual value
 * @param delta the maximum difference between the entries of the expected
 * and actual vectors for which both entries are still considered equal
 */
public static void assertEquals(final String message, final double[] expected, final RealVector actual,
        final double delta) {
    final String msgAndSep = message.equals("") ? "" : message + ", ";
    Assert.assertEquals(msgAndSep + "dimension", expected.length, actual.getDimension());
    for (int i = 0; i < expected.length; i++) {
        Assert.assertEquals(msgAndSep + "entry #" + i, expected[i], actual.getEntry(i), delta);
    }
}

From source file:lirmm.inria.fr.math.TestUtils.java

/**
 * Asserts that all entries of the specified vectors are equal to within a
 * positive {@code delta}./*  w  ww  . j  a  v a2 s .  c  o  m*/
 *
 * @param message the identifying message for the assertion error (can be
 * {@code null})
 * @param expected expected value
 * @param actual actual value
 * @param delta the maximum difference between the entries of the expected
 * and actual vectors for which both entries are still considered equal
 */
public static void assertEquals(final String message, final RealVector expected, final RealVector actual,
        final double delta) {
    final String msgAndSep = message.equals("") ? "" : message + ", ";
    Assert.assertEquals(msgAndSep + "dimension", expected.getDimension(), actual.getDimension());
    final int dim = expected.getDimension();
    for (int i = 0; i < dim; i++) {
        Assert.assertEquals(msgAndSep + "entry #" + i, expected.getEntry(i), actual.getEntry(i), delta);
    }
}

From source file:hivemall.utils.math.MatrixUtils.java

/**
 * Find the first singular vector/value of a matrix A based on the Power method.
 *
 * @see http//from   w  w  w.  j  av  a 2s  . co  m
 *      ://www.cs.yale.edu/homes/el327/datamining2013aFiles/07_singular_value_decomposition.pdf
 * @param A target matrix
 * @param x0 initial vector
 * @param nIter number of iterations for the Power method
 * @param u 1st left singular vector
 * @param v 1st right singular vector
 * @return 1st singular value
 */
public static double power1(@Nonnull final RealMatrix A, @Nonnull final double[] x0, final int nIter,
        @Nonnull final double[] u, @Nonnull final double[] v) {
    Preconditions.checkArgument(A.getColumnDimension() == x0.length,
            "Column size of A and length of x should be same");
    Preconditions.checkArgument(A.getRowDimension() == u.length,
            "Row size of A and length of u should be same");
    Preconditions.checkArgument(x0.length == v.length, "Length of x and u should be same");
    Preconditions.checkArgument(nIter >= 1, "Invalid number of iterations: " + nIter);

    RealMatrix AtA = A.transpose().multiply(A);

    RealVector x = new ArrayRealVector(x0);
    for (int i = 0; i < nIter; i++) {
        x = AtA.operate(x);
    }

    double xNorm = x.getNorm();
    for (int i = 0, n = v.length; i < n; i++) {
        v[i] = x.getEntry(i) / xNorm;
    }

    RealVector Av = new ArrayRealVector(A.operate(v));
    double s = Av.getNorm();

    for (int i = 0, n = u.length; i < n; i++) {
        u[i] = Av.getEntry(i) / s;
    }

    return s;
}

From source file:SGFilterModified.java

/**
 * Computes Savitzky-Golay coefficients for given parameters
 * /* w  w w .  ja  v  a 2  s  . c o m*/
 * @param nl
 *            numer of past data points filter will use
 * @param nr
 *            number of future data points filter will use
 * @param degree
 *            order of smoothin polynomial
 * @return Savitzky-Golay coefficients
 * @throws IllegalArgumentException
 *             if {@code nl < 0} or {@code nr < 0} or {@code nl + nr <
 *             degree}
 */
public static double[] computeSGCoefficients(int nl, int nr, int degree) {
    if (nl < 0 || nr < 0 || nl + nr < degree)
        throw new IllegalArgumentException("Bad arguments");
    //create a matrix 
    Array2DRowRealMatrix matrix = new Array2DRowRealMatrix(degree + 1, degree + 1);
    double[][] a = matrix.getDataRef();
    double sum;
    for (int i = 0; i <= degree; i++) {
        for (int j = 0; j <= degree; j++) {
            sum = (i == 0 && j == 0) ? 1 : 0;
            for (int k = 1; k <= nr; k++)
                sum += pow(k, i + j);
            for (int k = 1; k <= nl; k++)
                sum += pow(-k, i + j);
            a[i][j] = sum;
        }
    }
    double[] b = new double[degree + 1];
    b[0] = 1;
    // make a vector 
    RealVector bVec = new ArrayRealVector(b);
    // get LUDecompostion solver 
    DecompositionSolver solver = new LUDecomposition(matrix).getSolver();
    // Finally solve matrices
    bVec = solver.solve(bVec);
    double[] coeffs = new double[nl + nr + 1];
    for (int n = -nl; n <= nr; n++) {
        sum = bVec.getEntry(0);
        for (int m = 1; m <= degree; m++)
            sum += bVec.getEntry(m) * pow(n, m);
        coeffs[n + nl] = sum;
    }
    return coeffs;
}

From source file:ImageProc.java

public static float[][] colormapJet(int nClass) {
    int n;//from  ww w.  j a v a  2 s. c  o m
    n = (int) Math.ceil((float) nClass / 4);
    ArrayRealVector u, r, g, b;
    RealVector R, G, B;

    u = new ArrayRealVector(3 * n - 1);
    for (int i = 0; i < n; i++) {
        u.setEntry(i, (i + 1.0) / n);
        u.setEntry(u.getDimension() - i - 1, (i + 1.0) / n);
    }
    u.setSubVector(n, new ArrayRealVector(n, 1));

    g = new ArrayRealVector(u.getDimension());

    float m;
    m = (float) Math.ceil((float) n / 2);
    if (nClass % 4 == 1)
        m = m - 1;

    for (int i = 0; i < g.getDimension(); i++) {
        g.setEntry(i, (i + 1 + m));
    }

    r = g.add(new ArrayRealVector(g.getDimension(), n));
    b = g.subtract(new ArrayRealVector(g.getDimension(), n));

    R = new ArrayRealVector();
    G = new ArrayRealVector();
    B = new ArrayRealVector();

    for (int i = 0; i < r.getDimension(); i++) {
        if (r.getEntry(i) <= nClass)
            R = R.append(r.getEntry(i));
    }

    for (int i = 0; i < g.getDimension(); i++) {
        if (g.getEntry(i) <= nClass)
            G = G.append(g.getEntry(i));
    }

    for (int i = 0; i < b.getDimension(); i++) {
        if (b.getEntry(i) >= 1)
            B = B.append(b.getEntry(i));
    }

    float[][] J = new float[nClass][3];
    int index;
    for (int i = 0; i < R.getDimension(); i++) {
        index = (int) R.getEntry(i);
        J[index - 1][0] = (float) u.getEntry(i);
    }

    for (int i = 0; i < G.getDimension(); i++) {
        index = (int) G.getEntry(i);
        J[index - 1][1] = (float) u.getEntry(i);
    }

    for (int i = u.getDimension() - B.getDimension(), j = 0; i < u.getDimension(); i++, j++) {
        index = (int) B.getEntry(j);
        J[index - 1][2] = (float) u.getEntry(i);
    }

    /*
    System.out.println("\nRGB Matrix:");
    for(int i=0;i<nClass;i++){
    for(int j=0;j<3;j++){
        System.out.print(J[i][j]+"\t");
    }
    System.out.println();
    }
    */
    return J;
}

From source file:com.cloudera.oryx.kmeans.computation.covariance.CoMomentTracker.java

public void update(RealVector v) {
    for (int i = 0; i < v.getDimension(); i++) {
        double vi = v.getEntry(i);
        for (int j = i; j < v.getDimension(); j++) {
            Index idx = new Index(i, j);
            CoMoment cm = cache.get(idx);
            if (cm == null) {
                cm = new CoMoment();
                cache.put(idx, cm);/*from  www.j av a 2 s.co  m*/
            }
            cm.update(vi, v.getEntry(j));
        }
    }
}

From source file:edu.ucsf.valelab.saim.calculations.SaimParameterValidator.java

/**
 * Very simple validator that uses lower and upper bounds to restrict
 * parameter values/*from   ww w . j a v a 2s .  c o m*/
 * @param params
 * @return 
 */
@Override
public RealVector validate(RealVector params) {
    if (params.getDimension() != 3)
        throw new DimensionMismatchException(params.getDimension(), 3);
    RealVector n = params.copy();
    for (int i = 0; i < 3; i++) {
        if (n.getEntry(i) < lowerBounds_[i])
            n.setEntry(i, lowerBounds_[i]);
        if (n.getEntry(i) > upperBounds_[i])
            n.setEntry(i, upperBounds_[i]);
    }
    return n;
}