-
Notifications
You must be signed in to change notification settings - Fork 7
/
MVN.java
88 lines (69 loc) · 2.92 KB
/
MVN.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package lphy.base.distribution;
import lphy.core.model.RandomVariable;
import lphy.core.model.Value;
import lphy.core.model.annotation.GeneratorInfo;
import lphy.core.model.annotation.ParameterInfo;
import org.apache.commons.math3.distribution.MultivariateNormalDistribution;
import org.apache.commons.math3.random.RandomGenerator;
import java.util.Map;
import java.util.TreeMap;
import static lphy.base.distribution.DistributionConstants.meanParamName;
/**
* Multivariate Normal distribution.
*/
public class MVN extends ParametricDistribution<Double[]> {
private static final String covariancesParamName = "covariances";
private Value<Double[]> mean;
private Value<Double[][]> covariances;
MultivariateNormalDistribution multivariateNormalDistribution;
public MVN(@ParameterInfo(name = meanParamName, description = "the mean of the distribution.") Value<Double[]> mean,
@ParameterInfo(name = covariancesParamName, description = "the variance-covariance matrix of the distribution.") Value<Double[][]> covariances) {
super();
this.mean = mean;
this.covariances = covariances;
constructDistribution(random);
}
@Override
protected void constructDistribution(RandomGenerator random) {
if (mean == null) throw new IllegalArgumentException("The means can't be null!");
if (covariances == null) throw new IllegalArgumentException("The covariances can't be null!");
double[] means = new double[mean.value().length];
double[][] cv = new double[covariances.value().length][covariances.value().length];
for (int i = 0; i < means.length; i++) {
means[i] = mean.value()[i];
for (int j = 0; j < means.length; j++) {
cv[i][j] = this.covariances.value()[i][j];
}
}
multivariateNormalDistribution = new MultivariateNormalDistribution(random, means, cv);
}
@GeneratorInfo(name="MVN", description="The normal probability distribution.")
public RandomVariable<Double[]> sample() {
double[] sample = multivariateNormalDistribution.sample();
Double[] result= new Double[sample.length];
for (int i = 0; i < sample.length; i++) {
result[i] = sample[i];
}
return new RandomVariable<>("X", result, this);
}
@Override
public double density(Double[] x) {
double[] xx = new double[mean.value().length];
for (int i = 0; i < x.length; i++) {
xx[i] = x[i];
}
return multivariateNormalDistribution.density(xx);
}
public Map<String, Value> getParams() {
return new TreeMap<>() {{
put(meanParamName, mean);
put(covariancesParamName, covariances);
}};
}
public void setMean(Value<Double[]> mean) {
this.mean = mean;
}
public void setCovariances(Value<Double[][]> covariances) {
this.covariances = covariances;
}
}