use of beast.core.parameter.RealParameter in project bacter by tgvaughan.
the class SkylinePopulationFunction method main.
/**
* Main method for testing.
*
* @param args command line arguments (unused)
*/
public static void main(String[] args) throws Exception {
String acgString = "[&15,0,1.3905355989030808,31,770,1.597708055397074] " + "[&30,931,2.4351280458424904,36,2486,3.78055549386568] " + "[&15,941,2.0439957300083322,38,2364,6.911056700367016] " + "[&36,1091,4.285505683622974,38,2589,9.867725913197855] " + "((((10:0.5385300170206817,(17:0.116794353049212," + "((3:0.039229346597297564,12:0.039229346597297564)23:0.04582913870888949," + "13:0.08505848530618705)24:0.03173586774302495)26:0.4217356639714697)28:1.8114199763246093," + "((8:0.10883006062265468,2:0.10883006062265468)25:0.556428062025291," + "(6:0.5393311342677402,11:0.5393311342677402)29:0.12592698838020555)31:1.6846918706973453)34:1.4536824928125807," + "(1:0.47184545557390367,14:0.47184545557390367)27:3.331787030583968)37:2.9704369411362554," + "(((15:2.0624287390593707,((16:0.01825347077733299,19:0.01825347077733299)21:0.7668749128372041," + "(7:0.008018731329538273,9:0.008018731329538273)20:0.7771096522849988)32:1.2773003554448337)33:0.7487092404613747," + "4:2.8111379795207454)35:0.1331794525400949,((0:0.0243537216663141," + "5:0.0243537216663141)22:0.5681537100482162,18:0.5925074317145304)30:2.35181000034631)36:3.829751995233287)38:0.0";
ConversionGraph acg = new ConversionGraph();
acg.initByName("siteCount", 10000, "fromString", acgString);
SkylinePopulationFunction skyline = new SkylinePopulationFunction();
skyline.initByName("acg", acg, "popSizes", new RealParameter("1.0 1.0 5.0 1.0 2.0"), "groupSizes", new IntegerParameter("0"), "piecewiseLinear", true);
try (PrintStream ps = new PrintStream("out.txt")) {
ps.println("t N intensity intensityInv");
double t = 0.0;
while (t < 10) {
ps.format("%g %g %g %g\n", t, skyline.getPopSize(t), skyline.getIntensity(t), skyline.getInverseIntensity(skyline.getIntensity(t)));
t += 0.001;
}
ps.close();
}
}
use of beast.core.parameter.RealParameter in project MultiTypeTree by tgvaughan.
the class MigrationModelInputEditor method init.
@Override
public void init(Input<?> input, BEASTInterface beastObject, int itemNr, ExpandOption bExpandOption, boolean bAddButtons) {
// Set up fields
m_bAddButtons = bAddButtons;
m_input = input;
m_beastObject = beastObject;
this.itemNr = itemNr;
// Adds label to left of input editor
addInputLabel();
// Create component models and fill them with data from input
migModel = (SCMigrationModel) input.get();
fullTypeListModel = new DefaultListModel<>();
additionalTypeListModel = new DefaultListModel<>();
popSizeModel = new DefaultTableModel();
rateMatrixModel = new DefaultTableModel() {
@Override
public boolean isCellEditable(int row, int column) {
return row != column && column != migModel.getNTypes();
}
};
popSizeEstCheckBox = new JCheckBox("estimate pop. sizes");
rateMatrixEstCheckBox = new JCheckBox("estimate mig. rates");
popSizeScaleFactorEstCheckBox = new JCheckBox("estimate scale factor");
rateMatrixScaleFactorEstCheckBox = new JCheckBox("estimate scale factor");
loadFromMigrationModel();
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(new EtchedBorder());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(3, 3, 3, 3);
c.weighty = 0.5;
// Type list:
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.0;
c.anchor = GridBagConstraints.LINE_END;
panel.add(new JLabel("<html><body>Type list:</body></html>"), c);
JList<String> jlist;
Box tlBox = Box.createHorizontalBox();
Box tlBoxLeft = Box.createVerticalBox();
JLabel labelLeft = new JLabel("All types");
tlBoxLeft.add(labelLeft);
jlist = new JList<>(fullTypeListModel);
jlist.setSelectionModel(new DefaultListSelectionModel() {
@Override
public void setSelectionInterval(int index0, int index1) {
super.setSelectionInterval(-1, -1);
}
});
JScrollPane listScrollPane = new JScrollPane(jlist);
listScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
tlBoxLeft.add(listScrollPane);
tlBox.add(tlBoxLeft);
Box tlBoxRight = Box.createVerticalBox();
JLabel labelRight = new JLabel("Additional types");
tlBoxRight.add(labelRight);
jlist = new JList<>(additionalTypeListModel);
additionalTypeListSelectionModel = jlist.getSelectionModel();
listScrollPane = new JScrollPane(jlist);
listScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
tlBoxRight.add(listScrollPane);
Box addRemBox = Box.createHorizontalBox();
addTypeButton = new JButton("+");
remTypeButton = new JButton("-");
remTypeButton.setEnabled(false);
addTypesFromFileButton = new JButton("Add from file...");
addRemBox.add(addTypeButton);
addRemBox.add(remTypeButton);
addRemBox.add(addTypesFromFileButton);
tlBoxRight.add(addRemBox);
tlBox.add(tlBoxRight);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.anchor = GridBagConstraints.LINE_START;
panel.add(tlBox, c);
// Population size table
c.gridx = 0;
c.gridy = 1;
c.weightx = 0.0;
c.anchor = GridBagConstraints.LINE_END;
Box psBox = Box.createVerticalBox();
psBox.add(new JLabel("Population sizes: "), c);
loadPopSizesFromFileButton = new JButton("Load from file...");
psBox.add(loadPopSizesFromFileButton);
panel.add(psBox, c);
JTable popSizeTable = new JTable(popSizeModel) {
@Override
public TableCellRenderer getCellRenderer(int row, int column) {
return new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setHorizontalAlignment(SwingConstants.CENTER);
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
};
}
};
popSizeTable.setShowVerticalLines(true);
popSizeTable.setCellSelectionEnabled(true);
popSizeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
popSizeTable.setMaximumSize(new Dimension(100, Short.MAX_VALUE));
c.gridx = 1;
c.gridy = 1;
c.weightx = 1.0;
c.anchor = GridBagConstraints.LINE_START;
panel.add(popSizeTable, c);
popSizeEstCheckBox.setSelected(((RealParameter) migModel.popSizesInput.get()).isEstimatedInput.get());
popSizeScaleFactorEstCheckBox.setSelected(((RealParameter) migModel.popSizesScaleFactorInput.get()).isEstimatedInput.get());
c.gridx = 2;
c.gridy = 1;
c.anchor = GridBagConstraints.LINE_END;
c.weightx = 1.0;
Box estBox = Box.createVerticalBox();
estBox.add(popSizeEstCheckBox);
estBox.add(popSizeScaleFactorEstCheckBox);
panel.add(estBox, c);
// Migration rate table
// (Uses custom cell renderer to grey out diagonal elements.)
c.gridx = 0;
c.gridy = 2;
c.weightx = 0.0;
c.anchor = GridBagConstraints.LINE_END;
Box mrBox = Box.createVerticalBox();
mrBox.add(new JLabel("Migration rates: "), c);
loadMigRatesFromFileButton = new JButton("Load from file...");
mrBox.add(loadMigRatesFromFileButton);
panel.add(mrBox, c);
JTable rateMatrixTable = new JTable(rateMatrixModel) {
@Override
public TableCellRenderer getCellRenderer(int row, int column) {
return new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (row == column) {
JLabel label = new JLabel();
label.setOpaque(true);
label.setBackground(Color.GRAY);
return label;
} else {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (column == migModel.getNTypes()) {
c.setBackground(panel.getBackground());
c.setForeground(Color.gray);
setHorizontalAlignment(SwingConstants.LEFT);
} else {
int l = 1, r = 1, t = 1, b = 1;
if (column > 0)
l = 0;
if (row > 0)
t = 0;
setBorder(BorderFactory.createMatteBorder(t, l, b, r, Color.GRAY));
setHorizontalAlignment(SwingConstants.CENTER);
}
return c;
}
}
};
}
};
rateMatrixTable.setShowGrid(false);
rateMatrixTable.setIntercellSpacing(new Dimension(0, 0));
rateMatrixTable.setCellSelectionEnabled(true);
rateMatrixTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
rateMatrixTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn col = rateMatrixTable.getColumnModel().getColumn(migModel.getNTypes());
FontMetrics metrics = new Canvas().getFontMetrics(getFont());
int maxWidth = 0;
for (String rowName : rowNames) maxWidth = Math.max(maxWidth, metrics.stringWidth(rowName + "M"));
col.setPreferredWidth(maxWidth);
c.gridx = 1;
c.gridy = 2;
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 1.0;
panel.add(rateMatrixTable, c);
rateMatrixEstCheckBox.setSelected(((RealParameter) migModel.rateMatrixInput.get()).isEstimatedInput.get());
rateMatrixScaleFactorEstCheckBox.setSelected(((RealParameter) migModel.rateMatrixScaleFactorInput.get()).isEstimatedInput.get());
c.gridx = 2;
c.gridy = 2;
c.anchor = GridBagConstraints.LINE_END;
c.weightx = 1.0;
estBox = Box.createVerticalBox();
estBox.add(rateMatrixEstCheckBox);
estBox.add(rateMatrixScaleFactorEstCheckBox);
panel.add(estBox, c);
c.gridx = 1;
c.gridy = 3;
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 1.0;
panel.add(new JLabel("Rows: sources, columns: sinks (backwards in time)"), c);
c.gridx = 1;
c.gridy = 4;
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 1.0;
JLabel multilineLabel = new JLabel();
multilineLabel.setText("<html><body>Correspondence between row/col indices<br>" + "and deme names shown to right of matrix.</body></html>");
panel.add(multilineLabel, c);
add(panel);
// Event handlers
popSizeModel.addTableModelListener(e -> {
if (e.getType() != TableModelEvent.UPDATE)
return;
if (!fileLoadInProgress)
saveToMigrationModel();
});
popSizeEstCheckBox.addItemListener(e -> saveToMigrationModel());
popSizeScaleFactorEstCheckBox.addItemListener(e -> saveToMigrationModel());
rateMatrixModel.addTableModelListener(e -> {
if (e.getType() != TableModelEvent.UPDATE)
return;
if (!fileLoadInProgress)
saveToMigrationModel();
});
rateMatrixEstCheckBox.addItemListener(e -> saveToMigrationModel());
rateMatrixScaleFactorEstCheckBox.addItemListener(e -> saveToMigrationModel());
addTypeButton.addActionListener(e -> {
String newTypeName = JOptionPane.showInputDialog("Name of type");
if (newTypeName != null) {
if (migModel.getTypeSet().containsTypeWithName(newTypeName)) {
JOptionPane.showMessageDialog(panel, "Type with this name already present.", "Error", JOptionPane.ERROR_MESSAGE);
} else {
additionalTypeListModel.add(additionalTypeListModel.size(), newTypeName);
saveToMigrationModel();
}
}
});
addTypesFromFileButton.addActionListener(e -> {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Choose file containing type names (one per line)");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setMultiSelectionEnabled(false);
int result = fc.showDialog(panel, "Load");
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty())
additionalTypeListModel.add(additionalTypeListModel.size(), line);
}
saveToMigrationModel();
} catch (IOException e1) {
JOptionPane.showMessageDialog(panel, "Error reading from file: " + e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
additionalTypeListSelectionModel.addListSelectionListener(e -> {
if (additionalTypeListSelectionModel.getMinSelectionIndex() < 0)
remTypeButton.setEnabled(false);
else
remTypeButton.setEnabled(true);
});
remTypeButton.addActionListener(e -> {
int selectionMin = additionalTypeListSelectionModel.getMinSelectionIndex();
int selectionMax = additionalTypeListSelectionModel.getMaxSelectionIndex();
additionalTypeListModel.removeRange(selectionMin, selectionMax);
additionalTypeListSelectionModel.clearSelection();
saveToMigrationModel();
});
loadPopSizesFromFileButton.addActionListener(e -> {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Choose file containing population sizes (one per line)");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setMultiSelectionEnabled(false);
int result = fc.showDialog(panel, "Load");
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
List<Double> popSizes = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty())
popSizes.add(Double.parseDouble(line));
}
if (popSizes.size() == migModel.getNTypes()) {
fileLoadInProgress = true;
for (int i = 0; i < popSizes.size(); i++) popSizeModel.setValueAt(popSizes.get(i), 0, i);
fileLoadInProgress = false;
saveToMigrationModel();
} else {
JOptionPane.showMessageDialog(panel, "<html>File must contain exactly one population<br> size for each type/deme.</html>", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(panel, "Error reading from file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(panel, "<html>File contains non-numeric line. " + "Every line must contain<br> exactly one population size.</html>", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
loadMigRatesFromFileButton.addActionListener(e -> {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Choose CSV file containing migration rate matrix (diagonal ignored)");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setMultiSelectionEnabled(false);
int result = fc.showDialog(panel, "Load");
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
List<Double> migRates = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
for (String field : line.split(",")) {
if (!field.isEmpty())
migRates.add(Double.parseDouble(field));
}
}
boolean diagonalsPresent = (migRates.size() == migModel.getNTypes() * migModel.getNTypes());
if (diagonalsPresent || migRates.size() == migModel.getNTypes() * (migModel.getNTypes() - 1)) {
fileLoadInProgress = true;
for (int i = 0; i < migModel.getNTypes(); i++) {
for (int j = 0; j < migModel.getNTypes(); j++) {
if (i == j)
continue;
int offset;
if (diagonalsPresent)
offset = i * migModel.getNTypes() + j;
else {
offset = i * (migModel.getNTypes() - 1) + j;
if (j > i)
offset -= 1;
}
rateMatrixModel.setValueAt(migRates.get(offset), i, j);
}
}
fileLoadInProgress = false;
saveToMigrationModel();
} else {
JOptionPane.showMessageDialog(panel, "<html>CSV file must contain a square matrix with exactly one<br>" + "row for each type/deme.</html>", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(panel, "Error reading from file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(panel, "<html>CSV file contains non-numeric element.</html", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
use of beast.core.parameter.RealParameter in project MultiTypeTree by tgvaughan.
the class ExcludablePrior method initAndValidate.
@Override
public void initAndValidate() {
super.initAndValidate();
Function x = m_x.get();
if (x instanceof RealParameter || x instanceof IntegerParameter) {
if (x.getDimension() != xIncludeInput.get().getDimension())
throw new IllegalArgumentException("Length of xInclude does " + "not match length of x.");
}
}
use of beast.core.parameter.RealParameter in project MultiTypeTree by tgvaughan.
the class ExcludablePrior method calculateLogP.
@Override
public double calculateLogP() {
Function x = m_x.get();
if (x instanceof RealParameter || x instanceof IntegerParameter) {
// test that parameter is inside its bounds
double l = 0.0;
double h = 0.0;
if (x instanceof RealParameter) {
l = ((RealParameter) x).getLower();
h = ((RealParameter) x).getUpper();
} else {
l = ((IntegerParameter) x).getLower();
h = ((IntegerParameter) x).getUpper();
}
for (int i = 0; i < x.getDimension(); i++) {
if (!xIncludeInput.get().getValue(i))
continue;
double value = x.getArrayValue(i);
if (value < l || value > h) {
return Double.NEGATIVE_INFINITY;
}
}
}
// Inline modified version of ParametricDistribution.calcLogP()
final double fOffset = distInput.get().offsetInput.get();
logP = 0;
for (int i = 0; i < x.getDimension(); i++) {
if (!xIncludeInput.get().getValue(i))
continue;
final double fX = x.getArrayValue(i) - fOffset;
logP += distInput.get().logDensity(fX);
}
return logP;
}
use of beast.core.parameter.RealParameter in project MultiTypeTree by tgvaughan.
the class StructuredCoalescentMultiTypeTree method main.
/**
* Generates an ensemble of trees from the structured coalescent for testing
* coloured tree-space samplers.
*
* @param argv
* @throws java.lang.Exception
*/
public static void main(String[] argv) throws Exception {
// Set up migration model.
RealParameter rateMatrix = new RealParameter();
rateMatrix.initByName("value", "0.05", "dimension", "12");
RealParameter popSizes = new RealParameter();
popSizes.initByName("value", "7.0", "dimension", "4");
SCMigrationModel migrationModel = new SCMigrationModel();
migrationModel.initByName("rateMatrix", rateMatrix, "popSizes", popSizes);
// Specify leaf types:
IntegerParameter leafTypes = new IntegerParameter();
leafTypes.initByName("value", "0 0 0");
// Generate ensemble:
int reps = 1000000;
double[] heights = new double[reps];
double[] changes = new double[reps];
long startTime = System.currentTimeMillis();
StructuredCoalescentMultiTypeTree sctree;
sctree = new StructuredCoalescentMultiTypeTree();
for (int i = 0; i < reps; i++) {
if (i % 1000 == 0)
System.out.format("%d reps done\n", i);
sctree.initByName("migrationModel", migrationModel, "leafTypes", leafTypes, "nTypes", 4);
heights[i] = sctree.getRoot().getHeight();
changes[i] = sctree.getTotalNumberOfChanges();
}
long time = System.currentTimeMillis() - startTime;
System.out.printf("E[T] = %1.4f +/- %1.4f\n", DiscreteStatistics.mean(heights), DiscreteStatistics.stdev(heights) / Math.sqrt(reps));
System.out.printf("V[T] = %1.4f\n", DiscreteStatistics.variance(heights));
System.out.printf("E[C] = %1.4f +/- %1.4f\n", DiscreteStatistics.mean(changes), DiscreteStatistics.stdev(changes) / Math.sqrt(reps));
System.out.printf("V[C] = %1.4f\n", DiscreteStatistics.variance(changes));
System.out.printf("Took %1.2f seconds\n", time / 1000.0);
try (PrintStream outStream = new PrintStream("heights.txt")) {
outStream.println("h c");
for (int i = 0; i < reps; i++) outStream.format("%g %g\n", heights[i], changes[i]);
}
}
Aggregations