1 package jalview.ext.forester;
3 import jalview.datamodel.Sequence;
4 import jalview.math.MatrixI;
6 import java.io.IOException;
8 import java.text.DecimalFormat;
9 import java.text.NumberFormat;
10 import java.util.stream.IntStream;
12 import org.forester.evoinference.matrix.distance.DistanceMatrix;
13 import org.forester.util.ForesterUtil;
14 import org.forester.util.IllegalFormatUseException;
16 public class ForesterMatrix implements DistanceMatrix
18 private final static NumberFormat PHYLIP_FORMATTER = new DecimalFormat(
19 "0.000000"); // straight from forester
21 private final MatrixI jalviewMatrix;
23 private Sequence[] sequences;
25 private final String[] identifiers;
27 public ForesterMatrix(final MatrixI jalviewInputMatrix,
28 final Sequence[] matrixSequences)
30 this.jalviewMatrix = jalviewInputMatrix;
31 this.sequences = matrixSequences;
32 this.identifiers = new String[sequences.length];
36 for (Sequence sequence : sequences)
38 identifiers[i] = sequence.getName();
44 public ForesterMatrix(final MatrixI jalviewInputMatrix,
45 final String[] matrixIdentifiers)
47 this.jalviewMatrix = jalviewInputMatrix;
48 this.identifiers = matrixIdentifiers;
53 public String getIdentifier(final int i)
55 return identifiers[i];
59 public int getIndex(final String identifier)
61 return IntStream.range(0, identifiers.length)
62 .filter(x -> identifier.equals(identifiers[x])).findFirst()
67 * Returns the length of whichever is longest, columns or rows
72 return jalviewMatrix.getValues().length;
76 * See {@link MatrixI#getValue(int,int)} except that the order of column, row
77 * in the parameters is inverted here (as that is how forester demands it)
80 public double getValue(final int col, final int row)
82 return jalviewMatrix.getValue(row, col);
86 public void setIdentifier(final int i, final String identifier)
88 identifiers[i] = identifier;
93 * See {@link MatrixI#setValue()} except that the order of column, row in the
94 * parameters is inverted here (as that is how forester demands it)
97 public void setValue(final int col, final int row, final double distance)
99 jalviewMatrix.setValue(row, col, distance);
104 public StringBuffer toStringBuffer(Format format)
106 // TODO Auto-generated method stub
111 * See {@link MatrixI#getValues()}
114 public double[][] getValues()
116 return jalviewMatrix.getValues();
120 public void write(final Writer w) throws IOException // directly copied from
124 w.write(getSize() + "");
125 w.write(ForesterUtil.LINE_SEPARATOR);
126 for (int row = 0; row < getSize(); ++row)
128 if (!ForesterUtil.isEmpty(getIdentifier(row)))
130 w.write(ForesterUtil.pad(getIdentifier(row), 10, ' ', false)
137 throw new IllegalFormatUseException(
138 "Phylip format does not allow empty identifiers");
140 for (int col = 0; col < getSize(); ++col)
142 w.write(PHYLIP_FORMATTER.format(getValue(col, row)));
143 if (col < (getSize() - 1))
149 if (row < (getSize() - 1))
151 w.write(ForesterUtil.LINE_SEPARATOR);