GraphPartition { public static <L extends Serializable> LabeledDenseMatrix<L> getSimilarityMatrix( LabeledMTJMatrix<L> labeledMatrix) { Matrix A = labeledMatrix.getMatrix(); SparseVector V = new SparseVector(A.numColumns()); A.forEach((entry) -> V.set(entry.row(), V.get(entry.row()) + entry.get())); DenseMatrix D = new DenseMatrix(V.size(), V.size()); for (int row = 0, column = 0; row < V.size(); row++, column++) { D.set(row, column, V.get(row)); } Matrix L = D.add(-1, A); DenseMatrix E; try { E = SymmDenseEVD.factorize(L).getEigenvectors(); } catch (NotConvergedException e) { throw new RuntimeException("Can't factorize matrix", e); } DenseVector E_2 = new DenseVector(E.numRows()); for (int i = 0; i < E.numRows(); i++) { E_2.set(i, E.get(i, 1)); } Integer[] indices = new Integer[E_2.size()]; for (int i = 0; i < E_2.size(); i++) { indices[i] = i; } Comparator<Integer> comp = (Integer i, Integer j) -> Double.compare(E_2.get(i), E_2.get(j)); Arrays.sort(indices, comp); int[] permutations = new int[indices.length]; for (int i = 0; i < indices.length; i++) { permutations[i] = indices[i]; } indices = null; Matrix R = getPermutedMatrix(A, permutations); List<L> labels = getPermutedLabels(labeledMatrix.getLabels(), permutations); return LabeledDenseMatrix.of(R, labels); }  static LabeledMTJMatrix<X> getMentionMatrix(List<T> data,
                                            Function<T, X> funcX,
                                            Function<T, Y> funcY); static LabeledDenseMatrix<L> getSimilarityMatrix(
            LabeledMTJMatrix<L> labeledMatrix); static Matrix getPermutedMatrix(Matrix A, int[] permutations); static List<L> getPermutedLabels(List<L> originalLabels,
                                                                     int[] permutations);  }
@Test public void testGetSimilarityMatrix() { Matrix M = new DenseMatrix(new double[][] { new double[] { 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }, new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0 }, new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0 }, new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }, new double[] { 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0 }, new double[] { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, new double[] { 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0 }, new double[] { 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0 }, new double[] { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 } }); List<String> labels = Lists.newArrayListWithCapacity(M.numRows()); for (int i = 0; i < M.numRows(); i++) { labels.add("L" + i); } LabeledMTJMatrix<String> M_l = LabeledMTJMatrix.of(M, labels); LabeledDenseMatrix<String> R = GraphPartition.getSimilarityMatrix(M_l); assertEquals(10, R.getMatrix().length); assertEquals(10, R.getMatrix()[0].length); assertEquals(10, R.getLabels().size()); }