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:org.lenskit.predict.ordrec.OrdRecRatingPredictor.java

/**
 * The train function of OrdRec. Get all parameters after learning process.
 *//*www . ja v  a2 s .c o m*/
@SuppressWarnings("ConstantConditions")
private void trainModel(OrdRecModel model, SparseVector ratings, MutableSparseVector scores) {
    RealVector beta = model.getBeta();
    RealVector deltaBeta = new ArrayRealVector(beta.getDimension());
    double dt1;
    // n is the number of iteration;
    for (int j = 0; j < iterationCount; j++) {
        for (VectorEntry rating : ratings) {
            long iid = rating.getKey();
            double score = scores.get(iid);
            int r = quantizer.index(rating.getValue());

            double probEqualR = model.getProbEQ(score, r);
            double probLessR = model.getProbLE(score, r);
            double probLessR_1 = model.getProbLE(score, r - 1);

            double t1 = model.getT1();
            dt1 = learningRate / probEqualR * (probLessR * (1 - probLessR) * dBeta(r, 0, t1)
                    - probLessR_1 * (1 - probLessR_1) * dBeta(r - 1, 0, t1) - regTerm * t1);

            double dbetaK;
            for (int k = 0; k < beta.getDimension(); k++) {
                dbetaK = learningRate / probEqualR
                        * (probLessR * (1 - probLessR) * dBeta(r, k + 1, beta.getEntry(k))
                                - probLessR_1 * (1 - probLessR_1) * dBeta(r - 1, k + 1, beta.getEntry(k))
                                - regTerm * beta.getEntry(k));
                deltaBeta.setEntry(k, dbetaK);
            }
            model.update(dt1, deltaBeta);
        }
    }
}

From source file:org.lenskit.transform.quantize.PreferenceDomainQuantizerTest.java

@Test
public void testMakeValues() {
    RealVector vals = PreferenceDomainQuantizer.makeValues(domain);
    RealVector evals = new ArrayRealVector(new double[] { 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0 });
    assertThat(vals.getDimension(), equalTo(evals.getDimension()));
    for (int i = 0; i < vals.getDimension(); i++) {
        assertThat("element " + i, vals.getEntry(i), closeTo(evals.getEntry(i), 1.0e-6));
    }//from  w ww  .  ja v  a2s .c o m
}

From source file:org.meteoinfo.math.linalg.LinalgUtil.java

/**
 * Solve a linear matrix equation, or system of linear scalar equations.
 * @param a Coefficient matrix.//from www .  j  a  va2  s.c  om
 * @param b Ordinate or dependent variable? values.
 * @return Solution to the system a x = b. Returned shape is identical to b.
 */
public static Array solve(Array a, Array b) {
    Array r = Array.factory(DataType.DOUBLE, b.getShape());
    double[][] aa = (double[][]) ArrayUtil.copyToNDJavaArray(a);
    RealMatrix coefficients = new Array2DRowRealMatrix(aa, false);
    DecompositionSolver solver = new LUDecomposition(coefficients).getSolver();
    double[] bb = (double[]) ArrayUtil.copyToNDJavaArray(b);
    RealVector constants = new ArrayRealVector(bb, false);
    RealVector solution = solver.solve(constants);
    for (int i = 0; i < r.getSize(); i++) {
        r.setDouble(i, solution.getEntry(i));
    }

    return r;
}

From source file:org.meteoinfo.math.linalg.LinalgUtil.java

/**
 * Calculates the eigen decomposition of a real matrix.
 * The eigen decomposition of matrix A is a set of two matrices: V and D such that 
 * A = V  D  VT. A, V and D are all m  m matrices.
 * @param a Given matrix.//from  w  w w.j av  a  2 s .c om
 * @return Result W/V arrays.
 */
public static Array[] eigen(Array a) {
    int m = a.getShape()[0];
    Array Wa;
    Array Va = Array.factory(DataType.DOUBLE, new int[] { m, m });
    double[][] aa = (double[][]) ArrayUtil.copyToNDJavaArray(a);
    RealMatrix matrix = new Array2DRowRealMatrix(aa, false);
    EigenDecomposition decomposition = new EigenDecomposition(matrix);
    double[] rev = decomposition.getRealEigenvalues();
    double[] iev = decomposition.getImagEigenvalues();
    if (decomposition.hasComplexEigenvalues()) {
        Wa = Array.factory(DataType.OBJECT, new int[] { m });
        for (int i = 0; i < m; i++) {
            Wa.setObject(i, new Complex(rev[i], iev[i]));
            RealVector v = decomposition.getEigenvector(i);
            for (int j = 0; j < v.getDimension(); j++) {
                Va.setDouble(i * m + j, v.getEntry(j));
            }
        }
    } else {
        Wa = Array.factory(DataType.DOUBLE, new int[] { m });
        for (int i = 0; i < m; i++) {
            Wa.setDouble(i, rev[i]);
            RealVector v = decomposition.getEigenvector(i);
            for (int j = 0; j < v.getDimension(); j++) {
                Va.setDouble(i * m + j, v.getEntry(j));
            }
        }
    }

    return new Array[] { Wa, Va };
}

From source file:org.opentestsystem.airose.regression.orderedprobit.LinearEquationSolver.java

public static double[][] SolveLinear(double[][] XpX, double[][] XpY) {

    RealMatrix coefficients = new Array2DRowRealMatrix(XpX, false);
    LUDecomposition luDecomposition = new LUDecomposition(coefficients);

    DecompositionSolver solver = luDecomposition.getSolver();

    double[] yRowVector = new double[XpY.length];
    for (int counter1 = 0; counter1 < XpY.length; ++counter1) {
        yRowVector[counter1] = XpY[counter1][0];
    }//  w  w  w  .  j ava 2 s.co  m

    RealVector constants = new ArrayRealVector(yRowVector, false);
    RealVector solution = solver.solve(constants);

    double[][] result = new double[solution.getDimension()][1];
    for (int counter1 = 0; counter1 < solution.getDimension(); ++counter1) {
        result[counter1][0] = solution.getEntry(counter1);
    }
    return result;
}

From source file:org.orekit.utils.AngularCoordinates.java

/** Find a vector from two known cross products.
 * <p>// w  w w  .j a  v  a  2  s  . co m
 * We want to find  such that:   v? = c? and   v = c
 * </p>
 * <p>
 * The first equation (  v? = c?) will always be fulfilled exactly,
 * and the second one will be fulfilled if possible.
 * </p>
 * @param v1 vector forming the first known cross product
 * @param c1 know vector for cross product   v?
 * @param v2 vector forming the second known cross product
 * @param c2 know vector for cross product   v
 * @param tolerance relative tolerance factor used to check singularities
 * @return vector  such that:   v? = c? and   v = c
 * @exception MathIllegalArgumentException if vectors are inconsistent and
 * no solution can be found
 */
private static Vector3D inverseCrossProducts(final Vector3D v1, final Vector3D c1, final Vector3D v2,
        final Vector3D c2, final double tolerance) throws MathIllegalArgumentException {

    final double v12 = v1.getNormSq();
    final double v1n = FastMath.sqrt(v12);
    final double v22 = v2.getNormSq();
    final double v2n = FastMath.sqrt(v22);
    final double threshold = tolerance * FastMath.max(v1n, v2n);

    Vector3D omega;

    try {
        // create the over-determined linear system representing the two cross products
        final RealMatrix m = MatrixUtils.createRealMatrix(6, 3);
        m.setEntry(0, 1, v1.getZ());
        m.setEntry(0, 2, -v1.getY());
        m.setEntry(1, 0, -v1.getZ());
        m.setEntry(1, 2, v1.getX());
        m.setEntry(2, 0, v1.getY());
        m.setEntry(2, 1, -v1.getX());
        m.setEntry(3, 1, v2.getZ());
        m.setEntry(3, 2, -v2.getY());
        m.setEntry(4, 0, -v2.getZ());
        m.setEntry(4, 2, v2.getX());
        m.setEntry(5, 0, v2.getY());
        m.setEntry(5, 1, -v2.getX());

        final RealVector rhs = MatrixUtils.createRealVector(
                new double[] { c1.getX(), c1.getY(), c1.getZ(), c2.getX(), c2.getY(), c2.getZ() });

        // find the best solution we can
        final DecompositionSolver solver = new QRDecomposition(m, threshold).getSolver();
        final RealVector v = solver.solve(rhs);
        omega = new Vector3D(v.getEntry(0), v.getEntry(1), v.getEntry(2));

    } catch (SingularMatrixException sme) {

        // handle some special cases for which we can compute a solution
        final double c12 = c1.getNormSq();
        final double c1n = FastMath.sqrt(c12);
        final double c22 = c2.getNormSq();
        final double c2n = FastMath.sqrt(c22);

        if (c1n <= threshold && c2n <= threshold) {
            // simple special case, velocities are cancelled
            return Vector3D.ZERO;
        } else if (v1n <= threshold && c1n >= threshold) {
            // this is inconsistent, if v? is zero, c? must be 0 too
            throw new NumberIsTooLargeException(c1n, 0, true);
        } else if (v2n <= threshold && c2n >= threshold) {
            // this is inconsistent, if v is zero, c must be 0 too
            throw new NumberIsTooLargeException(c2n, 0, true);
        } else if (Vector3D.crossProduct(v1, v2).getNorm() <= threshold && v12 > threshold) {
            // simple special case, v is redundant with v?, we just ignore it
            // use the simplest : orthogonal to both v? and c?
            omega = new Vector3D(1.0 / v12, Vector3D.crossProduct(v1, c1));
        } else {
            throw sme;
        }

    }

    // check results
    final double d1 = Vector3D.distance(Vector3D.crossProduct(omega, v1), c1);
    if (d1 > threshold) {
        throw new NumberIsTooLargeException(d1, 0, true);
    }

    final double d2 = Vector3D.distance(Vector3D.crossProduct(omega, v2), c2);
    if (d2 > threshold) {
        throw new NumberIsTooLargeException(d2, 0, true);
    }

    return omega;

}

From source file:org.rhwlab.BHC.LogNode.java

public String vectorAsString(RealVector v) {
    boolean first = true;
    StringBuilder builder = new StringBuilder();
    builder.append("(");
    for (int i = 0; i < v.getDimension(); ++i) {

        if (!first) {
            builder.append(",");
        }/*from   w  ww  .j ava2  s . c o  m*/
        builder.append(String.format("%.2f", v.getEntry(i)));
        first = false;
    }
    builder.append(")");
    return builder.toString();
}

From source file:org.rhwlab.BHC.NodeBase.java

public Element formElementXML() {
    List<MicroCluster> micros = new ArrayList<>();
    this.getDataAsMicroCluster(micros);
    int voxels = 0;
    long intensity = 0;

    for (MicroCluster micro : micros) {
        voxels = voxels + micro.getPointCount();
        intensity = intensity + micro.getTotalIntensity();
    }/* ww  w.  ja  v  a 2 s. c  om*/
    RealVector mu = MicroCluster.mean(micros);
    RealMatrix W = MicroCluster.precision(micros, mu);
    if (W != null) {
        Element clusterEle = new Element("GaussianMixtureModel");
        //clusterEle.setAttribute("id", String.format("%d", id));
        //           clusterEle.setAttribute("parent", "-1");
        clusterEle.setAttribute("count", String.format("%d", micros.size()));
        clusterEle.setAttribute("voxels", String.format("%d", voxels));
        clusterEle.setAttribute("intensity", String.format("%d", intensity));

        clusterEle.setAttribute("intensityRSD", Double.toString(getIntensityRSD()));
        clusterEle.setAttribute("sourceNode", String.format("%d", label));

        clusterEle.setAttribute("posterior", Double.toString(lnR));

        clusterEle.setAttribute("x", Double.toString(mu.getEntry(0)));
        clusterEle.setAttribute("y", Double.toString(mu.getEntry(1)));
        clusterEle.setAttribute("z", Double.toString(mu.getEntry(2)));

        StringBuilder builder = new StringBuilder();
        for (int row = 0; row < W.getRowDimension(); ++row) {
            for (int col = 0; col < W.getColumnDimension(); ++col) {
                if (row > 0 || col > 0) {
                    builder.append(" ");
                }
                builder.append(W.getEntry(row, col));
            }
        }
        clusterEle.setAttribute("precision", builder.toString());
        return clusterEle;
    } else {
        return null;
    }
}

From source file:org.rhwlab.BHCnotused.Algorithm.java

public void init(int seg) {
    clusters = new ArrayList<>();
    for (int n = 0; n < source.getClusterCount(); ++n) {
        RealVector v = source.getCenter(n);
        Dfp[] z = new Dfp[v.getDimension()];
        for (int i = 0; i < z.length; ++i) {
            z[i] = field.newDfp(v.getEntry(i));
        }//from   w  ww  . j av a 2s  .  co  m
        LabeledFieldVector fv = new LabeledFieldVector(z, n);
        Cluster cluster = new Cluster(new GaussianGIWPrior(fv));
        clusters.add(cluster);
    }
    pairs = new HashMap<>();
    for (int i = 0; i < clusters.size() - 1; ++i) {
        Cluster clusterI = clusters.get(i);
        HashMap<Cluster, Cluster> map = new HashMap<>();
        for (int j = i + 1; j < clusters.size(); ++j) {
            Cluster clusterJ = clusters.get(j);
            Cluster T = new Cluster(clusterI, clusterJ);
            map.put(clusterJ, T);
        }
        pairs.put(clusterI, map);
    }
}

From source file:org.rhwlab.BHCnotused.GaussianGIWPrior.java

static public void main(String[] args) throws Exception {
    System.out.println("GaussianGIWPrior");
    field = new DfpField(20); // 20 decimal digits
    Cluster.setDfpField(field);/*from   w w  w  .  j a va 2  s .  c o m*/
    ThreadedAlgorithm.setDfpField(field);
    GaussianGIWPrior.setDfpField(field);

    //        SegmentedTiffDataSource source = new SegmentedTiffDataSource("/nfs/waterston/pete/Segmentation/Cherryimg75.tif",
    //                "/nfs/waterston/pete/Segmentation/Cherryimg75_SimpleSegmentation.tiff",1);  // background is seg=1
    //       source = new MicroClusterDataSource("/nfs/waterston/pete/Segmentation/Cherryimg_SimpleSegmentationMulti0350.xml");
    source = new MicroClusterDataSource(
            "/nfs/waterston/pete/Segmentation/Cherryimg_SimpleSegmentation0075.save");
    RealVector mean = source.getDataMean();
    Dfp[] mu = new Dfp[mean.getDimension()];
    for (int i = 0; i < mu.length; ++i) {
        mu[i] = field.newDfp(mean.getEntry(i));
    }
    GaussianGIWPrior.setParameters(4.0, 0.001, mu, 200.0);
    Cluster.setAlpha(30);
    ThreadedAlgorithm alg = new ThreadedAlgorithm();
    alg.setSource(source);
    alg.init(2);
    alg.run();
    alg.saveResultAsXML("/nfs/waterston/pete/Segmentation/Cherryimg_SimpleSegmentation0075_BHC.xml");
    int hfuis = 0;
}