/*
 * Matrices.java
 * Created on Apr 11, 2005
 */
package kernel;

import java.util.Random;

import javax.vecmath.GMatrix;
import javax.vecmath.GVector;

/**
 * Utility methods for matrices.
 */
public final class Matrices {
    
    private final static Random RAND = new Random();

    private Matrices() {}
    
    /**
     * Maps the given function to each column in the points
     * matrix and returns the vector of values.
     */
    public static GVector map(Function fun, GMatrix points) {
        int rows = points.getNumRow();
        int cols = points.getNumCol();
        GVector values = new GVector(cols);
        
        for(int i = 0; i < cols; i++) {
            GVector x = new GVector(rows);
            points.getColumn(i, x);
            values.setElement(i, fun.eval(x));
        }
        
        return values;
    }
    
    /**
     * Returns a matrix where each element is randomly chosen from
     * a normal distribution on the interval [0, 1].
     */
    public static GMatrix randomNormalMatrix(int rows, int cols) {
        GMatrix m = new GMatrix(rows, cols);
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < cols; j++) {
                m.setElement(i, j, RAND.nextDouble());
            }
        }
        return m;
    }
    
    /**
     * Returns a vector where each element is randomly chosen from
     * a Gaussian distribution with the given variance.
     */
    public static GVector randomGaussianVector(int size, double variance) {
        GVector v = new GVector(size);
        double stddev = Math.sqrt(variance);
        for(int i = 0; i < size; i++) {
            v.setElement(i, RAND.nextGaussian() * stddev);
        }
        return v;
    }

}
