use of beast.core.parameter.RealParameter in project beast2 by CompEvol.
the class UCRelaxedClockModel method initAndValidate.
@Override
public void initAndValidate() {
tree = treeInput.get();
branchCount = tree.getNodeCount() - 1;
categories = categoryInput.get();
usingQuantiles = (categories == null);
if (!usingQuantiles) {
LATTICE_SIZE_FOR_DISCRETIZED_RATES = numberOfDiscreteRates.get();
if (LATTICE_SIZE_FOR_DISCRETIZED_RATES <= 0)
LATTICE_SIZE_FOR_DISCRETIZED_RATES = branchCount;
Log.info.println(" UCRelaxedClockModel: using " + LATTICE_SIZE_FOR_DISCRETIZED_RATES + " rate " + "categories to approximate rate distribution across branches.");
} else {
if (numberOfDiscreteRates.get() != -1) {
throw new RuntimeException("Can't specify both numberOfDiscreteRates and rateQuantiles inputs.");
}
Log.info.println(" UCRelaxedClockModel: using quantiles for rate distribution across branches.");
}
if (usingQuantiles) {
quantiles = quantileInput.get();
quantiles.setDimension(branchCount);
Double[] initialQuantiles = new Double[branchCount];
for (int i = 0; i < branchCount; i++) {
initialQuantiles[i] = Randomizer.nextDouble();
}
RealParameter other = new RealParameter(initialQuantiles);
quantiles.assignFromWithoutID(other);
quantiles.setLower(0.0);
quantiles.setUpper(1.0);
} else {
categories.setDimension(branchCount);
Integer[] initialCategories = new Integer[branchCount];
for (int i = 0; i < branchCount; i++) {
initialCategories[i] = Randomizer.nextInt(LATTICE_SIZE_FOR_DISCRETIZED_RATES);
}
// set initial values of rate categories
IntegerParameter other = new IntegerParameter(initialCategories);
categories.assignFromWithoutID(other);
categories.setLower(0);
categories.setUpper(LATTICE_SIZE_FOR_DISCRETIZED_RATES - 1);
}
distribution = rateDistInput.get();
if (!usingQuantiles) {
// rates are initially zero and are computed by getRawRate(int i) as needed
rates = new double[LATTICE_SIZE_FOR_DISCRETIZED_RATES];
storedRates = new double[LATTICE_SIZE_FOR_DISCRETIZED_RATES];
// System.arraycopy(rates, 0, storedRates, 0, rates.length);
}
normalize = normalizeInput.get();
meanRate = meanRateInput.get();
if (meanRate == null) {
meanRate = new RealParameter("1.0");
}
try {
double mean = rateDistInput.get().getMean();
if (Math.abs(mean - 1.0) > 1e-6) {
Log.warning.println("WARNING: mean of distribution for relaxed clock model is not 1.0.");
}
} catch (RuntimeException e) {
// ignore
}
}
use of beast.core.parameter.RealParameter in project beast2 by CompEvol.
the class SliceOperator method proposal.
/**
* override this for proposals,
* returns log of hastingRatio, or Double.NEGATIVE_INFINITY if proposal should not be accepted *
*/
@Override
public double proposal(Evaluator E) {
int m = 100;
RealParameter X = parameterInput.get();
// Find the density at the current point
Double gx0 = evaluate(E);
// System.err.println("gx0 = " + gx0);
// Get the 1st element
Double x0 = X.getValue(0);
// System.err.println("x0 = " + x0);
// Determine the slice level, in log terms.
double logy = gx0 - Randomizer.nextExponential(1);
// Find the initial interval to sample from.
Double[] range = find_slice_boundaries_stepping_out(E, X, logy, windowSize, m);
Double L = range[0];
Double R = range[1];
// Sample from the interval, shrinking it on each rejection
double x_new = search_interval(E, x0, X, L, R, logy);
X.setValue(x_new);
if (n_learning_iterations > 0) {
n_learning_iterations--;
totalDelta += Math.abs(x_new - x0);
totalNumber++;
double W_predicted = totalDelta / totalNumber * 4.0;
if (totalNumber > 3) {
W = 0.95 * W + 0.05 * W_predicted;
windowSize = W;
}
// System.err.println("W = " + W);
}
return Double.POSITIVE_INFINITY;
}
use of beast.core.parameter.RealParameter in project beast2 by CompEvol.
the class UpDownOperator method proposal.
/**
* override this for proposals,
*
* @return log of Hastings Ratio, or Double.NEGATIVE_INFINITY if proposal
* should not be accepted
*/
@Override
public final double proposal() {
final double scale = (scaleFactor + (Randomizer.nextDouble() * ((1.0 / scaleFactor) - scaleFactor)));
int goingUp = 0, goingDown = 0;
if (elementWiseInput.get()) {
int size = 0;
for (StateNode up : upInput.get()) {
if (size == 0)
size = up.getDimension();
if (size > 0 && up.getDimension() != size) {
throw new RuntimeException("elementWise=true but parameters of differing lengths!");
}
goingUp += 1;
}
for (StateNode down : downInput.get()) {
if (size == 0)
size = down.getDimension();
if (size > 0 && down.getDimension() != size) {
throw new RuntimeException("elementWise=true but parameters of differing lengths!");
}
goingDown += 1;
}
int index = Randomizer.nextInt(size);
for (StateNode up : upInput.get()) {
if (up instanceof RealParameter) {
RealParameter p = (RealParameter) up;
p.setValue(p.getValue(index) * scale);
}
if (outsideBounds(up)) {
return Double.NEGATIVE_INFINITY;
}
}
for (StateNode down : downInput.get()) {
if (down instanceof RealParameter) {
RealParameter p = (RealParameter) down;
p.setValue(p.getValue(index) / scale);
}
if (outsideBounds(down)) {
return Double.NEGATIVE_INFINITY;
}
}
} else {
try {
for (StateNode up : upInput.get()) {
up = up.getCurrentEditable(this);
goingUp += up.scale(scale);
}
// Same below for down
for (StateNode up : upInput.get()) {
if (outsideBounds(up)) {
return Double.NEGATIVE_INFINITY;
}
}
for (StateNode down : downInput.get()) {
down = down.getCurrentEditable(this);
goingDown += down.scale(1.0 / scale);
}
for (StateNode down : downInput.get()) {
if (outsideBounds(down)) {
return Double.NEGATIVE_INFINITY;
}
}
} catch (Exception e) {
// scale resulted in invalid StateNode, abort proposal
return Double.NEGATIVE_INFINITY;
}
}
return (goingUp - goingDown - 2) * Math.log(scale);
}
use of beast.core.parameter.RealParameter in project beast2 by CompEvol.
the class SiteModel method initAndValidate.
@Override
public void initAndValidate() {
// useBeast1StyleGammaInput.get();
useBeast1StyleGamma = true;
muParameter = muParameterInput.get();
if (muParameter == null) {
muParameter = new RealParameter("1.0");
}
shapeParameter = shapeParameterInput.get();
invarParameter = invarParameterInput.get();
if (invarParameter == null) {
invarParameter = new RealParameter("0.0");
invarParameter.setBounds(Math.max(0.0, invarParameter.getLower()), Math.min(1.0, invarParameter.getUpper()));
}
// if (muParameter != null) {
muParameter.setBounds(Math.max(muParameter.getLower(), 0.0), Math.min(muParameter.getUpper(), Double.POSITIVE_INFINITY));
// }
if (shapeParameter != null) {
// The quantile calculator fails when the shape parameter goes much below
// 1E-3 so we have put a hard lower bound on it. If this is not there then
// the category rates can go to 0 and cause a -Inf likelihood (whilst this
// is not a problem as the state will be rejected, it could mask other issues
// and this seems the better approach.
shapeParameter.setBounds(Math.max(shapeParameter.getLower(), 1.0E-3), Math.min(shapeParameter.getUpper(), 1.0E3));
}
if (/*invarParameter != null && */
(invarParameter.getValue() < 0 || invarParameter.getValue() > 1)) {
throw new IllegalArgumentException("proportion invariant should be between 0 and 1");
}
refresh();
addCondition(muParameterInput);
addCondition(invarParameterInput);
addCondition(shapeParameterInput);
}
use of beast.core.parameter.RealParameter in project beast2 by CompEvol.
the class Input method setStringValue.
// determineClass
/**
* Try to parse value of string into Integer, Double or Boolean,
* or it this types differs, just assign as string.
*
* @param stringValue value representation
* @throws IllegalArgumentException when all conversions fail
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private void setStringValue(final String stringValue, final BEASTInterface beastObject) {
// figure out the type of T and create object based on T=Integer, T=Double, T=Boolean, T=Valuable
if (value instanceof List<?>) {
List list = (List) value;
list.clear();
// remove start and end spaces
String stringValue2 = stringValue.replaceAll("^\\s+", "");
stringValue2 = stringValue2.replaceAll("\\s+$", "");
// split into space-separated bits
String[] stringValues = stringValue2.split("\\s+");
for (int i = 0; i < stringValues.length; i++) {
if (theClass.equals(Integer.class)) {
list.add(new Integer(stringValues[i % stringValues.length]));
} else if (theClass.equals(Double.class)) {
list.add(new Double(stringValues[i % stringValues.length]));
} else if (theClass.equals(Boolean.class)) {
String str = stringValues[i % stringValues.length].toLowerCase();
list.add(str.equals("1") || str.equals("true") || str.equals("yes"));
} else if (theClass.equals(String.class)) {
list.add(new String(stringValues[i % stringValues.length]));
}
}
return;
}
if (theClass.equals(Integer.class)) {
value = (T) new Integer(stringValue);
return;
}
if (theClass.equals(Long.class)) {
value = (T) new Long(stringValue);
return;
}
if (theClass.equals(Double.class)) {
value = (T) new Double(stringValue);
return;
}
if (theClass.equals(Float.class)) {
value = (T) new Float(stringValue);
return;
}
if (theClass.equals(Boolean.class)) {
// RRB why the local parsing instead of using the Boolean c'tor?
// final String valueString2 = stringValue.toLowerCase();
// if (valueString2.equals("yes") || valueString2.equals("true")) {
// value = (T) Boolean.TRUE;
// return;
// } else if (valueString2.equals("no") || valueString2.equals("false")) {
// value = (T) Boolean.FALSE;
// return;
// }
value = (T) new Boolean(stringValue);
return;
}
if (theClass.equals(Function.class)) {
final RealParameter param = new RealParameter();
param.initByName("value", stringValue, "upper", 0.0, "lower", 0.0, "dimension", 1);
param.initAndValidate();
if (value != null && value instanceof List) {
((List) value).add(param);
} else {
value = (T) param;
}
param.getOutputs().add(beastObject);
return;
}
if (theClass.isEnum()) {
if (possibleValues == null) {
possibleValues = (T[]) theClass.getDeclaringClass().getEnumConstants();
}
for (final T t : possibleValues) {
if (stringValue.equals(t.toString())) {
value = t;
return;
}
}
throw new IllegalArgumentException("Input 104: value " + stringValue + " not found. Select one of " + Arrays.toString(possibleValues));
}
// call a string constructor of theClass
try {
Constructor ctor;
Object v = stringValue;
try {
ctor = theClass.getDeclaredConstructor(String.class);
} catch (NoSuchMethodException e) {
// try integer constructor instead
try {
if (stringValue.startsWith("0x")) {
v = Integer.parseInt(stringValue.substring(2), 16);
} else {
v = Integer.parseInt(stringValue);
}
ctor = theClass.getDeclaredConstructor(int.class);
} catch (NumberFormatException e2) {
// could not parse as integer, try double instead
v = Double.parseDouble(stringValue);
ctor = theClass.getDeclaredConstructor(double.class);
}
}
ctor.setAccessible(true);
final Object o = ctor.newInstance(v);
if (value != null && value instanceof List) {
((List) value).add(o);
} else {
value = (T) o;
}
if (o instanceof BEASTInterface) {
((BEASTInterface) o).getOutputs().add(beastObject);
}
} catch (Exception e) {
throw new IllegalArgumentException("Input 103: type mismatch, cannot initialize input '" + getName() + "' with value '" + stringValue + "'.\nExpected something of type " + getType().getName() + ". " + (e.getMessage() != null ? e.getMessage() : ""));
}
}
Aggregations