-
Notifications
You must be signed in to change notification settings - Fork 1
/
MHTest.java
91 lines (78 loc) · 1.95 KB
/
MHTest.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
89
90
91
package polya.mcmc;
import java.util.Collections;
import java.util.Random;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import tutorialj.Tutorial;
/**
*
* @author Alexandre Bouchard (alexandre.bouchard@gmail.com)
*
* TODO: Move to test directory.
*/
public class MHTest
{
/**
* #### Simple test case for the MH sampling code
*
* Here is a simple test case if you want to test the MH code
* without running the whole pipeline (this should output approximately
* 1/lambda):
*/
@Tutorial(showLink = true)
public static void main(String [] args)
{
final RealVariable variable = new RealVariableImpl(1.0);
final double lambda = 5.0;
final Factor exponentialDist = new Factor() {
@Override
public double logUnnormalizedPotential()
{
if (variable.getValue() < 0.0)
return Double.NEGATIVE_INFINITY;
return -lambda * variable.getValue();
}
};
RealVariableMHMove move = new RealVariableMHMove(variable, Collections.singleton(exponentialDist));
SummaryStatistics stat = new SummaryStatistics();
Random rand = new Random(1);
for (int i = 0; i < 100000; i++)
{
move.sample(rand);
stat.addValue(variable.getValue());
}
System.out.println("EX=" + stat.getMean());
System.out.println("acceptRate=" + move.acceptanceProbabilities.getMean());
}
/**
* A default implementation of RealVariable for simple test cases.
*
* @author Alexandre Bouchard (alexandre.bouchard@gmail.com)
*
*/
public static class RealVariableImpl implements RealVariable
{
private double value;
/**
*
* @param value
*/
public RealVariableImpl(double value)
{
this.value = value;
}
/**
*
*/
public double getValue()
{
return value;
}
/**
*
*/
public void setValue(double value)
{
this.value = value;
}
}
}