Exemplo n.º 1
0
  /**
   * Randomly sample a matrix from Wishart Distribution with the given parameters.
   *
   * @param scale scale parameter for Wishart Distribution.
   * @param df degree of freedom for Wishart Distribution.
   * @return the sample randomly drawn from the given distribution.
   */
  protected DenseMatrix wishart(DenseMatrix scale, double df) {
    DenseMatrix A = scale.cholesky();
    if (A == null) return null;

    int p = scale.numRows();
    DenseMatrix z = new DenseMatrix(p, p);

    for (int i = 0; i < p; i++) {
      for (int j = 0; j < p; j++) {
        z.set(i, j, Randoms.gaussian(0, 1));
      }
    }

    SparseVector y = new SparseVector(p);
    for (int i = 0; i < p; i++) y.set(i, Randoms.gamma((df - (i + 1)) / 2, 2));

    DenseMatrix B = new DenseMatrix(p, p);
    B.set(0, 0, y.get(0));

    if (p > 1) {
      // rest of diagonal:
      for (int j = 1; j < p; j++) {
        SparseVector zz = new SparseVector(j);
        for (int k = 0; k < j; k++) zz.set(k, z.get(k, j));

        B.set(j, j, y.get(j) + zz.inner(zz));
      }

      // first row and column:
      for (int j = 1; j < p; j++) {
        B.set(0, j, z.get(0, j) * Math.sqrt(y.get(0)));
        B.set(j, 0, B.get(0, j)); // mirror
      }
    }

    if (p > 2) {
      for (int j = 2; j < p; j++) {
        for (int i = 1; i <= j - 1; i++) {
          SparseVector zki = new SparseVector(i);
          SparseVector zkj = new SparseVector(i);

          for (int k = 0; k <= i - 1; k++) {
            zki.set(k, z.get(k, i));
            zkj.set(k, z.get(k, j));
          }
          B.set(i, j, z.get(i, j) * Math.sqrt(y.get(i)) + zki.inner(zkj));
          B.set(j, i, B.get(i, j)); // mirror
        }
      }
    }

    return A.transpose().mult(B).mult(A);
  }