lphy.base.distribution.Categorical Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of lphy-base Show documentation
Show all versions of lphy-base Show documentation
The standard library of LPhy, which contains the required generative distributions and basic functions.
The newest version!
package lphy.base.distribution;
import lphy.core.model.RandomVariable;
import lphy.core.model.Value;
import lphy.core.model.annotation.GeneratorCategory;
import lphy.core.model.annotation.GeneratorInfo;
import lphy.core.model.annotation.ParameterInfo;
import org.apache.commons.math3.random.RandomGenerator;
import java.util.Collections;
import java.util.Map;
//TODO
public class Categorical extends ParametricDistribution {
Value probs;
public Categorical(@ParameterInfo(name = DistributionConstants.pParamName, description = "the probability distribution over integer states 1 to K.") Value probs) {
super();
this.probs = probs;
}
@Override
protected void constructDistribution(RandomGenerator random) { }
@GeneratorInfo(name = "Categorical", verbClause = "has", narrativeName = "Categorical distribution prior",
category = GeneratorCategory.PRIOR, description = "The categorical distribution.")
public RandomVariable sample() {
int i = sample(probs.value(), random);
return new RandomVariable<>("X", i, this);
}
public static int sample(Double[] p, RandomGenerator random) {
double U = random.nextDouble();
// TODO slow implementation! Should create cumulative probability distribution and use binary search!
double sum = p[0];
int i = 0;
while (U > sum) {
sum += p[i+1];
i += 1;
}
return i;
}
@Override
public Map getParams() {
return Collections.singletonMap(DistributionConstants.pParamName, probs);
}
}