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

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

Introduction

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

Prototype

@Override
public void setEntry(final int row, final int column, final double value) throws OutOfRangeException 

Source Link

Usage

From source file:lanchester.TestEigen.java

public static Array2DRowRealMatrix getMat(int num) {
    Array2DRowRealMatrix mat = new Array2DRowRealMatrix(num, num);
    for (int i1 = 0; i1 < num; i1++) {
        for (int i2 = 0; i2 < num; i2++) {
            mat.setEntry(i1, i2, Math.random());
        }//from  w  w w. j a  v a  2s  . com
    }
    return mat;
}

From source file:edu.oregonstate.eecs.mcplan.util.Csv.java

public static RealMatrix readMatrix(final File f) {
    try {//from   w  ww. j a va  2 s.co m
        final BufferedReader r = new BufferedReader(new FileReader(f));
        String line;
        final ArrayList<String[]> rows = new ArrayList<String[]>();
        while (true) {
            line = r.readLine();
            if (line == null) {
                break;
            }
            rows.add(line.split(","));
        }
        final Array2DRowRealMatrix M = new Array2DRowRealMatrix(rows.size(), rows.get(0).length);
        for (int i = 0; i < rows.size(); ++i) {
            final String[] row = rows.get(i);
            for (int j = 0; j < row.length; ++j) {
                M.setEntry(i, j, Double.parseDouble(row[j]));
            }
        }

        return M;
    } catch (final Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:fp.overlapr.algorithmen.StressMajorization.java

/**
 * Fhrt die Stress-Majorization durch. siehe: Gansner, Koren, North: Graph
 * Drawing by Stress Majorization, 2004/* w w w .ja v  a 2s .co  m*/
 * 
 * @param graph
 *            Graph, dessen Knoten-Positionen neu berechnet werden sollen
 * @param d
 *            Matrix, die die idealen Distanzen (d_ij) zwischen den Knoten
 *            enthlt
 * @return Matrix, die die neuen x- und y-Werte der einzelnen Knoten enthlt
 */
public static double[][] doStressMajorization(Graph graph, double[][] d) {

    int iter = 0;

    // X holen
    Array2DRowRealMatrix X = new Array2DRowRealMatrix(graph.getKnotenAnzahl(), 2);
    for (int i = 0; i < graph.getKnotenAnzahl(); i++) {
        X.setEntry(i, 0, graph.getKnoten().get(i).getX());
        X.setEntry(i, 1, graph.getKnoten().get(i).getY());
    }

    // D holen
    Array2DRowRealMatrix D = new Array2DRowRealMatrix(d);

    // W berechnen
    Array2DRowRealMatrix W = new Array2DRowRealMatrix(D.getRowDimension(), D.getColumnDimension());
    W.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            if (D.getEntry(row, column) == 0) {
                return 0.0;
            } else {
                return 1.0 / (D.getEntry(row, column) * D.getEntry(row, column));
            }
        }
    });

    // LW berechnen
    Array2DRowRealMatrix LW = new Array2DRowRealMatrix(D.getRowDimension(), D.getColumnDimension());
    LW.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            if (row != column) {
                return (-1) * W.getEntry(row, column);
            } else {

                return value;
            }
        }
    });
    LW.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            if (row == column) {

                double sum = 0;

                for (int k = 0; k < LW.getColumnDimension(); k++) {
                    if (k != row) {
                        sum = sum + W.getEntry(row, k);
                    }
                }

                return sum;
            } else {

                return value;
            }
        }
    });

    double[][] x = null;

    while (iter < ITER) {

        iter++;

        // LX berechnen
        Array2DRowRealMatrix LX = new Array2DRowRealMatrix(D.getRowDimension(), D.getColumnDimension());
        LX.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
            @Override
            public double visit(int row, int column, double value) {
                if (row != column) {

                    // norm 2
                    double term1 = FastMath.pow((X.getEntry(row, 0) - X.getEntry(column, 0)), 2);
                    double term2 = FastMath.pow((X.getEntry(row, 1) - X.getEntry(column, 1)), 2);

                    double abst = Math.sqrt(term1 + term2);

                    return (-1) * W.getEntry(row, column) * D.getEntry(row, column) * inv(abst);
                } else {
                    return value;
                }
            }
        });
        LX.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
            @Override
            public double visit(int row, int column, double value) {
                if (row == column) {

                    double sum = 0;

                    for (int k = 0; k < LX.getColumnDimension(); k++) {
                        if (k != row) {
                            sum = sum + LX.getEntry(row, k);
                        }
                    }
                    return (-1) * sum;
                } else {
                    return value;
                }
            }
        });

        /*
         * Lineare Gleichungssysteme lsen
         */
        // x-Werte holen
        ArrayRealVector xWerte = new ArrayRealVector(X.getColumn(0));

        // y-Werte holen
        ArrayRealVector yWerte = new ArrayRealVector(X.getColumn(1));

        // b_x berechnen
        ArrayRealVector b_x = (ArrayRealVector) LX.operate(xWerte);

        // b_y berechnen
        ArrayRealVector b_y = (ArrayRealVector) LX.operate(yWerte);

        /*
         * CG-Verfahren anwenden
         */
        // neue x-Werte berechnen mittels PCG
        // xWerte = conjugateGradientsMethod(LW, b_x, xWerte);

        // neue y-Werte berechnen mittels PCG
        // yWerte = conjugateGradientsMethod(LW, b_y, yWerte);

        ConjugateGradient cg = new ConjugateGradient(Integer.MAX_VALUE, TOL, false);
        xWerte = (ArrayRealVector) cg.solve(LW, JacobiPreconditioner.create(LW), b_x);
        yWerte = (ArrayRealVector) cg.solve(LW, JacobiPreconditioner.create(LW), b_y);

        /*
         * neue Positiones-Werte zurckgeben
         */
        x = new double[X.getRowDimension()][2];
        for (int i = 0; i < x.length; i++) {

            x[i][0] = xWerte.getEntry(i);
            x[i][1] = yWerte.getEntry(i);

            X.setEntry(i, 0, xWerte.getEntry(i));
            X.setEntry(i, 1, yWerte.getEntry(i));

        }
    }

    return x;
}

From source file:com.simiacryptus.mindseye.applications.ArtistryUtil.java

/**
 * Pca tensor.//from   w ww.  j  a v  a2s .  c om
 *
 * @param cov   the cov
 * @param power the power
 * @return the tensor
 */
@Nonnull
public static Tensor pca(final Tensor cov, final double power) {
    final int inputbands = (int) Math.sqrt(cov.getDimensions()[2]);
    final int outputbands = inputbands;
    Array2DRowRealMatrix realMatrix = new Array2DRowRealMatrix(inputbands, inputbands);
    cov.coordStream(false).forEach(c -> {
        double v = cov.get(c);
        int x = c.getIndex() % inputbands;
        int y = (c.getIndex() - x) / inputbands;
        realMatrix.setEntry(x, y, v);
    });
    Tensor[] features = PCAUtil.pcaFeatures(realMatrix, outputbands, new int[] { 1, 1, inputbands }, power);
    Tensor kernel = new Tensor(1, 1, inputbands * outputbands);
    PCAUtil.populatePCAKernel_1(kernel, features);
    return kernel;
}

From source file:edu.cmu.sphinx.speakerid.SpeakerIdentification.java

/**
 * @param Clustering//from w  ww  .j  a  v  a 2 s . com
 *            The array of clusters
 * @param posi
 *            The index of the merged cluster
 * @param posj
 *            The index of the cluster that will be eliminated from the
 *            clustering
 * @param distance
 *            The distance matrix that will be updated
 */
void updateDistances(ArrayList<SpeakerCluster> clustering, int posi, int posj, Array2DRowRealMatrix distance) {
    int clusterCount = clustering.size();
    for (int i = 0; i < clusterCount; i++) {
        distance.setEntry(i, posi, computeDistance(clustering.get(i), clustering.get(posi)));
        distance.setEntry(posi, i, distance.getEntry(i, posi));
    }
    for (int i = posj; i < clusterCount - 1; i++)
        for (int j = 0; j < clusterCount; j++)
            distance.setEntry(i, j, distance.getEntry(i + 1, j));

    for (int i = 0; i < clusterCount; i++)
        for (int j = posj; j < clusterCount - 1; j++)
            distance.setEntry(i, j, distance.getEntry(i, j + 1));
}

From source file:edu.cmu.sphinx.speakerid.SpeakerIdentification.java

/**
 * @param Clustering//from  w  w  w .j  a v  a  2s .co  m
 *            The array of clusters
 */
Array2DRowRealMatrix updateDistances(ArrayList<SpeakerCluster> clustering) {
    int clusterCount = clustering.size();
    Array2DRowRealMatrix distance = new Array2DRowRealMatrix(clusterCount, clusterCount);
    for (int i = 0; i < clusterCount; i++) {
        for (int j = 0; j <= i; j++) {
            distance.setEntry(i, j, computeDistance(clustering.get(i), clustering.get(j)));
            distance.setEntry(j, i, distance.getEntry(i, j));
        }
    }
    return distance;
}

From source file:lanchester.MultiArena.java

public Array2DRowRealMatrix getMat() {
    int numFoes = forces.size();
    AthenaForce f1;/*from w  w  w .j av  a  2  s. c  o  m*/
    AthenaForce f2;
    Array2DRowRealMatrix mat = new Array2DRowRealMatrix(numFoes, numFoes);
    for (int i1 = 0; i1 < numFoes - 1; i1++) {
        f1 = forces.get(i1);
        for (int i2 = i1 + 1; i2 < numFoes; i2++) {
            f2 = forces.get(i2);
            if (f1.isFriend(f2)) {
                f1.setStance(AthenaConstants.ALLIED_POSTURE);
                f2.setStance(AthenaConstants.ALLIED_POSTURE);
                mat.setEntry(i1, i2, 0.);
                mat.setEntry(i2, i1, 0.);
            } else {
                //                    int oldStance1=f1.getCurrentStance();
                //                    int oldStance2=f2.getCurrentStance();
                setStances(f1, f2);
                //                    int newStance1=f1.getCurrentStance();
                //                    int newStance2=f2.getCurrentStance();
                //                    if(oldStance1!=newStance1||oldStance2!=newStance2){
                //                        System.out.println("Stance change at time = "+currentTime);
                //                        System.out.println("F1 - "+oldStance1+" to "+newStance1);
                //                        System.out.println("F2 - "+oldStance2+" to "+newStance2);
                //                    }
                //                    double x0 = f1.getForceSize();
                //                    double y0 = f2.getForceSize();
                double a1 = f2.getForceMultiplier();
                double b2 = f1.getForceMultiplier();
                if (isBattle) {
                    a1 *= AthenaConstants.battle[stanceArray[i1][i2]][stanceArray[i2][i1]];
                    b2 *= AthenaConstants.battle[stanceArray[i2][i1]][stanceArray[i1][i2]];
                } else {
                    a1 *= AthenaConstants.skirmish[stanceArray[i1][i2]][stanceArray[i2][i1]];
                    b2 *= AthenaConstants.skirmish[stanceArray[i2][i1]][stanceArray[i1][i2]];
                }

                mat.setEntry(i1, i2, -a1);
                mat.setEntry(i2, i1, -b2);
            }
        }
    }
    return mat;
}

From source file:com.simiacryptus.mindseye.applications.ObjectLocationBase.java

/**
 * Run.//from  w w  w . j  a  v a 2s  .c o  m
 *
 * @param log the log
 */
public void run(@Nonnull final NotebookOutput log) {
    //    @Nonnull String logName = "cuda_" + log.getName() + ".log";
    //    log.p(log.file((String) null, logName, "GPU Log"));
    //    CudaSystem.addLog(new PrintStream(log.file(logName)));

    ImageClassifierBase classifier = getClassifierNetwork();
    Layer classifyNetwork = classifier.getNetwork();

    ImageClassifierBase locator = getLocatorNetwork();
    Layer locatorNetwork = locator.getNetwork();
    ArtistryUtil.setPrecision((DAGNetwork) classifyNetwork, Precision.Float);
    ArtistryUtil.setPrecision((DAGNetwork) locatorNetwork, Precision.Float);

    Tensor[][] inputData = loadImages_library();
    //    Tensor[][] inputData = loadImage_Caltech101(log);
    double alphaPower = 0.8;

    final AtomicInteger index = new AtomicInteger(0);
    Arrays.stream(inputData).limit(10).forEach(row -> {
        log.h3("Image " + index.getAndIncrement());
        final Tensor img = row[0];
        log.p(log.image(img.toImage(), ""));
        Result classifyResult = classifyNetwork.eval(new MutableResult(row));
        Result locationResult = locatorNetwork.eval(new MutableResult(row));
        Tensor classification = classifyResult.getData().get(0);
        List<CharSequence> categories = classifier.getCategories();
        int[] sortedIndices = IntStream.range(0, categories.size()).mapToObj(x -> x)
                .sorted(Comparator.comparing(i -> -classification.get(i))).mapToInt(x -> x).limit(10).toArray();
        logger.info(Arrays.stream(sortedIndices)
                .mapToObj(
                        i -> String.format("%s: %s = %s%%", i, categories.get(i), classification.get(i) * 100))
                .reduce((a, b) -> a + "\n" + b).orElse(""));
        LinkedHashMap<CharSequence, Tensor> vectors = new LinkedHashMap<>();
        List<CharSequence> predictionList = Arrays.stream(sortedIndices).mapToObj(categories::get)
                .collect(Collectors.toList());
        Arrays.stream(sortedIndices).limit(6).forEach(category -> {
            CharSequence name = categories.get(category);
            log.h3(name);
            Tensor alphaTensor = renderAlpha(alphaPower, img, locationResult, classification, category);
            log.p(log.image(img.toRgbImageAlphaMask(0, 1, 2, alphaTensor), ""));
            vectors.put(name, alphaTensor.unit());
        });

        Tensor avgDetection = vectors.values().stream().reduce((a, b) -> a.add(b)).get()
                .scale(1.0 / vectors.size());
        Array2DRowRealMatrix covarianceMatrix = new Array2DRowRealMatrix(predictionList.size(),
                predictionList.size());
        for (int x = 0; x < predictionList.size(); x++) {
            for (int y = 0; y < predictionList.size(); y++) {
                Tensor l = vectors.get(predictionList.get(x));
                Tensor r = vectors.get(predictionList.get(y));

                covarianceMatrix.setEntry(x, y,
                        null == l || null == r ? 0 : (l.minus(avgDetection)).dot(r.minus(avgDetection)));
            }
        }
        @Nonnull
        final EigenDecomposition decomposition = new EigenDecomposition(covarianceMatrix);

        for (int objectVector = 0; objectVector < 10; objectVector++) {
            log.h3("Eigenobject " + objectVector);
            double eigenvalue = decomposition.getRealEigenvalue(objectVector);
            RealVector eigenvector = decomposition.getEigenvector(objectVector);
            Tensor detectionRegion = IntStream.range(0, eigenvector.getDimension()).mapToObj(i -> {
                Tensor tensor = vectors.get(predictionList.get(i));
                return null == tensor ? null : tensor.scale(eigenvector.getEntry(i));
            }).filter(x -> null != x).reduce((a, b) -> a.add(b)).get();
            detectionRegion = detectionRegion.scale(255.0 / detectionRegion.rms());
            CharSequence categorization = IntStream.range(0, eigenvector.getDimension()).mapToObj(i -> {
                CharSequence category = predictionList.get(i);
                double component = eigenvector.getEntry(i);
                return String.format("<li>%s = %.4f</li>", category, component);
            }).reduce((a, b) -> a + "" + b).get();
            log.p(String.format("Object Detected: <ol>%s</ol>", categorization));
            log.p("Object Eigenvalue: " + eigenvalue);
            log.p("Object Region: " + log.image(img.toRgbImageAlphaMask(0, 1, 2, detectionRegion), ""));
            log.p("Object Region Compliment: "
                    + log.image(img.toRgbImageAlphaMask(0, 1, 2, detectionRegion.scale(-1)), ""));
        }

        //      final int[] orderedVectors = IntStream.range(0, 10).mapToObj(x -> x)
        //        .sorted(Comparator.comparing(x -> -decomposition.getRealEigenvalue(x))).mapToInt(x -> x).toArray();
        //      IntStream.range(0, orderedVectors.length)
        //        .mapToObj(i -> {
        //            //double realEigenvalue = decomposition.getRealEigenvalue(orderedVectors[i]);
        //            return decomposition.getEigenvector(orderedVectors[i]).toArray();
        //          }
        //        ).toArray(i -> new double[i][]);

        log.p(String.format(
                "<table><tr><th>Cosine Distance</th>%s</tr>%s</table>", Arrays.stream(sortedIndices).limit(10)
                        .mapToObj(col -> "<th>" + categories.get(col) + "</th>").reduce((a, b) -> a + b).get(),
                Arrays.stream(sortedIndices).limit(10).mapToObj(r -> {
                    return String.format("<tr><td>%s</td>%s</tr>", categories.get(r),
                            Arrays.stream(sortedIndices).limit(10).mapToObj(col -> {
                                Tensor l = vectors.get(categories.get(r));
                                Tensor r2 = vectors.get(categories.get(col));
                                return String.format("<td>%.4f</td>",
                                        (null == l || null == r2) ? 0 : Math.acos(l.dot(r2)));
                            }).reduce((a, b) -> a + b).get());
                }).reduce((a, b) -> a + b).orElse("")));
    });

    log.setFrontMatterProperty("status", "OK");
}

From source file:lanchester.MultiArena3.java

public Array2DRowRealMatrix getMat() {
    int numFoes = forces.size();
    MultiForce f1;//from  w w  w .  j  av a 2  s  .co m
    MultiForce f2;
    Array2DRowRealMatrix mat = new Array2DRowRealMatrix(numFoes, numFoes);
    for (int i1 = 0; i1 < numFoes - 1; i1++) {
        f1 = forces.get(i1);
        for (int i2 = i1 + 1; i2 < numFoes; i2++) {
            f2 = forces.get(i2);
            if (f1.isFriend(f2)) {
                //                    f1.setStance(AthenaConstants.ALLIED_POSTURE);
                //                    f2.setStance(AthenaConstants.ALLIED_POSTURE);
                stanceArray[i1][i2] = (AthenaConstants.ALLIED_POSTURE);
                stanceArray[i2][i1] = (AthenaConstants.ALLIED_POSTURE);
                mat.setEntry(i1, i2, 0.);
                mat.setEntry(i2, i1, 0.);
            } else {
                //                    setStances(f1, f2);
                setStances(i1, i2);
                double a1 = f2.getForceMultiplier();
                double b2 = f1.getForceMultiplier();
                if (isBattle) {
                    a1 *= AthenaConstants.battle[stanceArray[i1][i2]][stanceArray[i2][i1]];
                    b2 *= AthenaConstants.battle[stanceArray[i2][i1]][stanceArray[i1][i2]];
                } else {
                    a1 *= AthenaConstants.skirmish[stanceArray[i1][i2]][stanceArray[i2][i1]];
                    b2 *= AthenaConstants.skirmish[stanceArray[i2][i1]][stanceArray[i1][i2]];
                }

                mat.setEntry(i1, i2, -a1);
                mat.setEntry(i2, i1, -b2);
            }
        }
    }
    return mat;
}

From source file:lanchester.MultiArena4.java

public Array2DRowRealMatrix getMat() {
    int numFoes = forces.size();
    MultiForce f1;/*from w w w .  j  a va 2  s.  co m*/
    MultiForce f2;
    Array2DRowRealMatrix mat = new Array2DRowRealMatrix(numFoes, numFoes);
    for (int i1 = 0; i1 < numFoes - 1; i1++) {
        f1 = forces.get(i1);
        for (int i2 = i1 + 1; i2 < numFoes; i2++) {
            f2 = forces.get(i2);
            if (f1.isFriend(f2)) {
                //                    f1.setStance(AthenaConstants.ALLIED_POSTURE);
                //                    f2.setStance(AthenaConstants.ALLIED_POSTURE);
                //                    stanceArray[i1][i2] = (AthenaConstants.ALLIED_POSTURE);
                //                    stanceArray[i2][i1] = (AthenaConstants.ALLIED_POSTURE);
                mat.setEntry(i1, i2, 0.);
                mat.setEntry(i2, i1, 0.);
            } else {
                //                    setStances(f1, f2);
                setStances(i1, i2);
                double a1 = f2.getForceMultiplier();
                double b2 = f1.getForceMultiplier();
                if (isBattle) {
                    a1 *= AthenaConstants.battle[stanceArray[i1][i2]][stanceArray[i2][i1]];
                    b2 *= AthenaConstants.battle[stanceArray[i2][i1]][stanceArray[i1][i2]];
                } else {
                    a1 *= AthenaConstants.skirmish[stanceArray[i1][i2]][stanceArray[i2][i1]];
                    b2 *= AthenaConstants.skirmish[stanceArray[i2][i1]][stanceArray[i1][i2]];
                }

                mat.setEntry(i1, i2, -a1);
                mat.setEntry(i2, i1, -b2);
            }
        }
    }
    return mat;
}