Example usage for org.apache.commons.math3.linear RealMatrix walkInRowOrder

List of usage examples for org.apache.commons.math3.linear RealMatrix walkInRowOrder

Introduction

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

Prototype

double walkInRowOrder(RealMatrixPreservingVisitor visitor);

Source Link

Document

Visit (but don't change) all matrix entries in row order.

Usage

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

@Nonnull
public static double[] flatten(@Nonnull final RealMatrix[] grid) {
    Preconditions.checkArgument(grid.length >= 1, "The number of rows must be greater than 1");

    final int rows = grid.length;
    RealMatrix grid0 = grid[0];/* w  w  w.  ja  v  a 2 s .co  m*/
    Preconditions.checkNotNull(grid0);
    int cellRows = grid0.getRowDimension();
    int cellCols = grid0.getColumnDimension();

    final DoubleArrayList list = new DoubleArrayList(rows * cellRows * cellCols);
    final RealMatrixPreservingVisitor visitor = new DefaultRealMatrixPreservingVisitor() {
        @Override
        public void visit(int row, int column, double value) {
            list.add(value);
        }
    };

    for (int row = 0; row < rows; row++) {
        RealMatrix cell = grid[row];
        cell.walkInRowOrder(visitor);
    }

    return list.toArray();
}

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

@Nonnull
public static double[] flatten(@Nonnull final RealMatrix[][] grid) {
    Preconditions.checkArgument(grid.length >= 1, "The number of rows must be greater than 1");
    Preconditions.checkArgument(grid[0].length >= 1, "The number of cols must be greater than 1");

    final int rows = grid.length;
    final int cols = grid[0].length;
    RealMatrix grid00 = grid[0][0];// w ww.ja v  a2s  . c  o  m
    Preconditions.checkNotNull(grid00);
    int cellRows = grid00.getRowDimension();
    int cellCols = grid00.getColumnDimension();

    final DoubleArrayList list = new DoubleArrayList(rows * cols * cellRows * cellCols);
    final RealMatrixPreservingVisitor visitor = new DefaultRealMatrixPreservingVisitor() {
        @Override
        public void visit(int row, int column, double value) {
            list.add(value);
        }
    };

    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            RealMatrix cell = grid[row][col];
            cell.walkInRowOrder(visitor);
        }
    }

    return list.toArray();
}

From source file:com.itemanalysis.psychometrics.factoranalysis.QuartiminCriteria.java

public void computeValues(RealMatrix L) {
    int k = L.getColumnDimension();
    int p = L.getRowDimension();
    RealMatrix I = new IdentityMatrix(p);
    RealMatrix L2 = MatrixUtils.multiplyElements(L, L);

    RealMatrix N = new Array2DRowRealMatrix(k, k);
    N.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override/*from   ww  w  .j a  v  a 2 s.c  o m*/
        public double visit(int row, int column, double value) {
            if (row == column)
                return 0.0;
            return 1.0;
        }
    });

    RealMatrix X = L2.multiply(N);
    double sum = MatrixUtils.sumMatrix(MatrixUtils.multiplyElements(L2, X));
    functionValue = sum / 4.0;
    gradient = MatrixUtils.multiplyElements(L, X);

}

From source file:com.itemanalysis.psychometrics.factoranalysis.ObliminCriteria.java

public void computeValues(RealMatrix L) {
    final int k = L.getColumnDimension();
    final int p = L.getRowDimension();
    RealMatrix I = new IdentityMatrix(p);
    RealMatrix L2 = MatrixUtils.multiplyElements(L, L);

    RealMatrix N = new Array2DRowRealMatrix(k, k);
    N.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override//from w  ww.  j a  v  a  2 s  . c o  m
        public double visit(int row, int column, double value) {
            if (row == column)
                return 0.0;
            return 1.0;
        }
    });

    RealMatrix C = new Array2DRowRealMatrix(p, p);
    C.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            return gam / (double) p;
        }
    });

    RealMatrix X = I.subtract(C).multiply(L2).multiply(N);
    double sum = MatrixUtils.sumMatrix(MatrixUtils.multiplyElements(L2, X));
    functionValue = sum / 4.0;
    gradient = MatrixUtils.multiplyElements(L, X);

}

From source file:com.itemanalysis.psychometrics.factoranalysis.GeominCriteria.java

public void computeValues(RealMatrix L) {
    //        vgQ.geomin <- function(L, delta=.01){
    //            k <- ncol(L)
    //            p <- nrow(L)
    //            L2 <- L^2 + delta
    //            pro <- exp(rowSums(log(L2))/k)
    //            list(Gq=(2/k)*(L/L2)*matrix(rep(pro,k),p),
    //                    f= sum(pro),
    //                    Method="Geomin")
    //        }//from  w ww . ja va 2s . com

    int p = L.getRowDimension();
    int k = L.getColumnDimension();
    final RealMatrix L2 = MatrixUtils.multiplyElements(L, L).scalarAdd(delta);
    final double[] rowSums = new double[p];

    L2.walkInRowOrder(new DefaultRealMatrixPreservingVisitor() {
        @Override
        public void visit(int row, int column, double value) {
            rowSums[row] += Math.log(value);
        }
    });

    double sum = 0.0;
    for (int i = 0; i < p; i++) {
        rowSums[i] = Math.exp(rowSums[i] / (double) k);
        sum += rowSums[i];
    }
    functionValue = sum;

    final RealMatrix M = new Array2DRowRealMatrix(p, k);
    M.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            return rowSums[row];
        }
    });

    final double c = (2.0 / (double) k);
    gradient = L.copy();
    gradient.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            return c * (value / L2.getEntry(row, column)) * M.getEntry(row, column);
        }
    });

}

From source file:com.itemanalysis.psychometrics.factoranalysis.GPArotation.java

/**
 * Conducts orthogonal rotation of factor loadings.
 *
 * @param A matrix of orthogonal factor loadings
 * @return a matrix of rotated factor loadings.
 * @throws ConvergenceException/*from   ww w.  j a v  a  2  s . com*/
 */
private RotationResults GPForth(RealMatrix A, boolean normalize, int maxIter, double eps)
        throws ConvergenceException {
    int ncol = A.getColumnDimension();

    if (normalize) {
        //elementwise division by normalizing weights
        final RealMatrix W = getNormalizingWeights(A, true);
        A.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
            @Override
            public double visit(int row, int column, double value) {
                return value / W.getEntry(row, column);
            }
        });
    }

    RealMatrix Tmat = new IdentityMatrix(ncol);
    double alpha = 1;
    RealMatrix L = A.multiply(Tmat);

    gpFunction.computeValues(L);

    double f = gpFunction.getValue();
    RealMatrix VgQ = gpFunction.getGradient();
    RealMatrix G = A.transpose().multiply(VgQ);
    double VgQtF = gpFunction.getValue();
    RealMatrix VgQt = gpFunction.getGradient();
    RealMatrix Tmatt = null;

    int iter = 0;
    double s = eps + 0.5;
    double s2 = 0;
    int innnerIter = 11;

    while (iter < maxIter) {
        RealMatrix M = Tmat.transpose().multiply(G);
        RealMatrix S = (M.add(M.transpose()));
        S = S.scalarMultiply(0.5);
        RealMatrix Gp = G.subtract(Tmat.multiply(S));
        s = Math.sqrt((Gp.transpose().multiply(Gp)).getTrace());
        s2 = Math.pow(s, 2);

        if (s < eps)
            break;
        alpha *= 2.0;

        for (int j = 0; j < innnerIter; j++) {
            Gp = Gp.scalarMultiply(alpha);
            RealMatrix X = (Tmat.subtract(Gp));
            SingularValueDecomposition SVD = new SingularValueDecomposition(X);

            Tmatt = SVD.getU().multiply(SVD.getV().transpose());
            L = A.multiply(Tmatt);
            gpFunction.computeValues(L);
            VgQt = gpFunction.getGradient();
            VgQtF = gpFunction.getValue();

            if (VgQtF < f - 0.5 * s2 * alpha) {
                break;
            }
            alpha /= 2.0;
        }

        Tmat = Tmatt;
        f = VgQtF;
        G = A.transpose().multiply(VgQt);
        iter++;
    }

    boolean convergence = s < eps;
    if (!convergence) {
        throw new ConvergenceException();
    }

    if (normalize) {
        //elementwise multiplication by normalizing weights
        final RealMatrix W = getNormalizingWeights(A, true);
        A.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
            @Override
            public double visit(int row, int column, double value) {
                return value * W.getEntry(row, column);
            }
        });
    }

    RealMatrix Phi = Tmat.transpose().multiply(Tmat);
    RotationResults result = new RotationResults(gpFunction.getValue(), L, Phi, Tmat, rotationMethod);
    return result;

}

From source file:com.itemanalysis.psychometrics.factoranalysis.GPArotation.java

private RotationResults GPFoblq(RealMatrix A, boolean normalize, int maxIter, double eps)
        throws ConvergenceException {
    int ncol = A.getColumnDimension();

    RealMatrix Tinner = null;/*from   w  w w . j ava2s. c om*/
    RealMatrix TinnerInv = null;
    RealMatrix Tmat = new IdentityMatrix(ncol);

    if (normalize) {
        //elementwise division by normalizing weights
        final RealMatrix W = getNormalizingWeights(A, true);
        A.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
            @Override
            public double visit(int row, int column, double value) {
                return value / W.getEntry(row, column);
            }
        });
    }

    RealMatrix TmatInv = new LUDecomposition(Tmat).getSolver().getInverse();
    RealMatrix L = A.multiply(TmatInv.transpose());

    //compute gradientAt and function value
    gpFunction.computeValues(L);
    RealMatrix VgQ = gpFunction.getGradient();
    RealMatrix VgQt = VgQ;
    double f = gpFunction.getValue();
    double ft = f;
    RealMatrix G = ((L.transpose().multiply(VgQ).multiply(TmatInv)).transpose()).scalarMultiply(-1.0);

    int iter = 0;
    double alpha = 1.0;
    double s = eps + 0.5;
    double s2 = Math.pow(s, 2);
    int innerMaxIter = 10;
    int innerCount = 0;

    IdentityMatrix I = new IdentityMatrix(G.getRowDimension());
    RealMatrix V1 = MatrixUtils.getVector(ncol, 1.0);

    while (iter < maxIter) {
        RealMatrix M = MatrixUtils.multiplyElements(Tmat, G);
        RealMatrix diagP = new DiagonalMatrix(V1.multiply(M).getRow(0));
        RealMatrix Gp = G.subtract(Tmat.multiply(diagP));
        s = Math.sqrt(Gp.transpose().multiply(Gp).getTrace());
        s2 = Math.pow(s, 2);

        if (s < eps) {
            break;
        }
        alpha = 2.0 * alpha;

        innerCount = 0;
        for (int i = 0; i < innerMaxIter; i++) {
            RealMatrix X = Tmat.subtract(Gp.scalarMultiply(alpha));
            RealMatrix X2 = MatrixUtils.multiplyElements(X, X);
            RealMatrix V = V1.multiply(X2);
            V.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
                @Override
                public double visit(int row, int column, double value) {
                    return 1.0 / Math.sqrt(value);
                }
            });

            //compute new value of T, its inverse, and the rotated loadings
            RealMatrix diagV = new DiagonalMatrix(V.getRow(0));
            Tinner = X.multiply(diagV);
            TinnerInv = new LUDecomposition(Tinner).getSolver().getInverse();
            L = A.multiply(TinnerInv.transpose());

            //compute new values of the gradientAt and the rotation criteria
            gpFunction.computeValues(L);
            VgQt = gpFunction.getGradient();
            ft = gpFunction.getValue();

            innerCount++;
            if (ft < f - 0.5 * s2 * alpha) {
                break;
            }
            alpha = alpha / 2.0;
        }

        //            System.out.println(iter + "  " + f + "  " + s + "  " + Math.log10(s) + "  " + alpha + "  " + innerCount);

        Tmat = Tinner;
        f = ft;
        G = (L.transpose().multiply(VgQt).multiply(TinnerInv)).transpose().scalarMultiply(-1.0);
        iter++;
    }

    boolean convergence = s < eps;
    if (!convergence) {
        throw new ConvergenceException();
    }

    if (normalize) {
        //elementwise multiplication by normalizing weights
        final RealMatrix W = getNormalizingWeights(A, true);
        A.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
            @Override
            public double visit(int row, int column, double value) {
                return value * W.getEntry(row, column);
            }
        });
    }

    RealMatrix Phi = Tmat.transpose().multiply(Tmat);
    RotationResults result = new RotationResults(gpFunction.getValue(), L, Phi, Tmat, rotationMethod);
    return result;

}

From source file:com.itemanalysis.psychometrics.factoranalysis.GPArotation.java

private RealMatrix getNormalizingWeights(RealMatrix A, boolean normalize) {
    int nrow = A.getRowDimension();
    int ncol = A.getColumnDimension();
    final double[] w = new double[nrow];

    RealMatrix W = new Array2DRowRealMatrix(nrow, ncol);
    if (!normalize) {
        W.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
            @Override//from   w  w w .ja  va2s .co  m
            public double visit(int row, int column, double value) {
                return 1.0;
            }
        });
        return W;
    }

    //compute row sum of squared loadings
    A.walkInRowOrder(new DefaultRealMatrixPreservingVisitor() {
        @Override
        public void visit(int row, int column, double value) {
            w[row] += value * value;
        }
    });

    //compute normalizing weights for the matrix
    W.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            return Math.sqrt(w[row]);
        }
    });
    return W;
}

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

@Test
public void testWalk() {
    int rows = 150;
    int columns = 75;

    RealMatrix m = new BigSparseRealMatrix(rows, columns);
    m.walkInRowOrder(new SetVisitor());
    GetVisitor getVisitor = new GetVisitor();
    m.walkInOptimizedOrder(getVisitor);/*w w w.j a v  a2s  .co m*/
    Assert.assertEquals(rows * columns, getVisitor.getCount());

    m = new BigSparseRealMatrix(rows, columns);
    m.walkInRowOrder(new SetVisitor(), 1, rows - 2, 1, columns - 2);
    getVisitor = new GetVisitor();
    m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2);
    Assert.assertEquals((rows - 2) * (columns - 2), getVisitor.getCount());
    for (int i = 0; i < rows; ++i) {
        Assert.assertEquals(0.0, m.getEntry(i, 0), 0);
        Assert.assertEquals(0.0, m.getEntry(i, columns - 1), 0);
    }
    for (int j = 0; j < columns; ++j) {
        Assert.assertEquals(0.0, m.getEntry(0, j), 0);
        Assert.assertEquals(0.0, m.getEntry(rows - 1, j), 0);
    }

    m = new BigSparseRealMatrix(rows, columns);
    m.walkInColumnOrder(new SetVisitor());
    getVisitor = new GetVisitor();
    m.walkInOptimizedOrder(getVisitor);
    Assert.assertEquals(rows * columns, getVisitor.getCount());

    m = new BigSparseRealMatrix(rows, columns);
    m.walkInColumnOrder(new SetVisitor(), 1, rows - 2, 1, columns - 2);
    getVisitor = new GetVisitor();
    m.walkInOptimizedOrder(getVisitor, 1, rows - 2, 1, columns - 2);
    Assert.assertEquals((rows - 2) * (columns - 2), getVisitor.getCount());
    for (int i = 0; i < rows; ++i) {
        Assert.assertEquals(0.0, m.getEntry(i, 0), 0);
        Assert.assertEquals(0.0, m.getEntry(i, columns - 1), 0);
    }
    for (int j = 0; j < columns; ++j) {
        Assert.assertEquals(0.0, m.getEntry(0, j), 0);
        Assert.assertEquals(0.0, m.getEntry(rows - 1, j), 0);
    }

    m = new BigSparseRealMatrix(rows, columns);
    m.walkInOptimizedOrder(new SetVisitor());
    getVisitor = new GetVisitor();
    m.walkInRowOrder(getVisitor);
    Assert.assertEquals(rows * columns, getVisitor.getCount());

    m = new BigSparseRealMatrix(rows, columns);
    m.walkInOptimizedOrder(new SetVisitor(), 1, rows - 2, 1, columns - 2);
    getVisitor = new GetVisitor();
    m.walkInRowOrder(getVisitor, 1, rows - 2, 1, columns - 2);
    Assert.assertEquals((rows - 2) * (columns - 2), getVisitor.getCount());
    for (int i = 0; i < rows; ++i) {
        Assert.assertEquals(0.0, m.getEntry(i, 0), 0);
        Assert.assertEquals(0.0, m.getEntry(i, columns - 1), 0);
    }
    for (int j = 0; j < columns; ++j) {
        Assert.assertEquals(0.0, m.getEntry(0, j), 0);
        Assert.assertEquals(0.0, m.getEntry(rows - 1, j), 0);
    }

    m = new BigSparseRealMatrix(rows, columns);
    m.walkInOptimizedOrder(new SetVisitor());
    getVisitor = new GetVisitor();
    m.walkInColumnOrder(getVisitor);
    Assert.assertEquals(rows * columns, getVisitor.getCount());

    m = new BigSparseRealMatrix(rows, columns);
    m.walkInOptimizedOrder(new SetVisitor(), 1, rows - 2, 1, columns - 2);
    getVisitor = new GetVisitor();
    m.walkInColumnOrder(getVisitor, 1, rows - 2, 1, columns - 2);
    Assert.assertEquals((rows - 2) * (columns - 2), getVisitor.getCount());
    for (int i = 0; i < rows; ++i) {
        Assert.assertEquals(0.0, m.getEntry(i, 0), 0);
        Assert.assertEquals(0.0, m.getEntry(i, columns - 1), 0);
    }
    for (int j = 0; j < columns; ++j) {
        Assert.assertEquals(0.0, m.getEntry(0, j), 0);
        Assert.assertEquals(0.0, m.getEntry(rows - 1, j), 0);
    }
}