2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.analysis;
23 import jalview.analysis.scoremodels.ScoreModels;
24 import jalview.api.analysis.DistanceScoreModelI;
25 import jalview.api.analysis.ScoreModelI;
26 import jalview.api.analysis.SimilarityScoreModelI;
27 import jalview.datamodel.AlignmentView;
28 import jalview.datamodel.BinaryNode;
29 import jalview.datamodel.CigarArray;
30 import jalview.datamodel.NodeTransformI;
31 import jalview.datamodel.SeqCigar;
32 import jalview.datamodel.Sequence;
33 import jalview.datamodel.SequenceI;
34 import jalview.datamodel.SequenceNode;
35 import jalview.io.NewickFile;
36 import jalview.math.MatrixI;
38 import java.util.Enumeration;
39 import java.util.List;
40 import java.util.Vector;
53 public static final String AVERAGE_DISTANCE = "AV";
55 public static final String NEIGHBOUR_JOINING = "NJ";
57 public static final String FROM_FILE = "FromFile";
59 Vector<Cluster> cluster;
63 // SequenceData is a string representation of what the user
64 // sees. The display may contain hidden columns.
65 public AlignmentView seqData = null;
83 Vector<SequenceNode> groups = new Vector<SequenceNode>();
95 Vector<SequenceNode> node;
103 boolean hasDistances = true; // normal case for jalview trees
105 boolean hasBootstrap = false; // normal case for jalview trees
107 private boolean hasRootDistance = true;
110 * Create a new NJTree object with leaves associated with sequences in seqs,
111 * and original alignment data represented by Cigar strings.
120 public NJTree(SequenceI[] seqs, AlignmentView odata, NewickFile treefile)
122 this(seqs, treefile);
128 * sequenceString = new String[odata.length]; char gapChar =
129 * jalview.util.Comparison.GapChars.charAt(0); for (int i = 0; i <
130 * odata.length; i++) { SequenceI oseq_aligned = odata[i].getSeq(gapChar);
131 * sequenceString[i] = oseq_aligned.getSequence(); }
136 * Creates a new NJTree object from a tree from an external source
139 * SequenceI which should be associated with leafs of treefile
143 public NJTree(SequenceI[] seqs, NewickFile treefile)
145 this.sequence = seqs;
146 top = treefile.getTree();
149 * There is no dependent alignment to be recovered from an imported tree.
151 * if (sequenceString == null) { sequenceString = new String[seqs.length];
152 * for (int i = 0; i < seqs.length; i++) { sequenceString[i] =
153 * seqs[i].getSequence(); } }
156 hasDistances = treefile.HasDistances();
157 hasBootstrap = treefile.HasBootstrap();
158 hasRootDistance = treefile.HasRootDistance();
160 maxheight = findHeight(top);
162 SequenceIdMatcher algnIds = new SequenceIdMatcher(seqs);
164 Vector<SequenceNode> leaves = findLeaves(top);
167 int namesleft = seqs.length;
172 Vector<SequenceI> one2many = new Vector<SequenceI>();
173 int countOne2Many = 0;
174 while (i < leaves.size())
176 j = leaves.elementAt(i++);
177 realnam = j.getName();
182 nam = algnIds.findIdMatch(realnam);
188 if (one2many.contains(nam))
191 // if (jalview.bin.Cache.log.isDebugEnabled())
192 // jalview.bin.Cache.log.debug("One 2 many relationship for
197 one2many.addElement(nam);
203 j.setElement(new Sequence(realnam, "THISISAPLACEHLDER"));
204 j.setPlaceholder(true);
207 // if (jalview.bin.Cache.log.isDebugEnabled() && countOne2Many>0) {
208 // jalview.bin.Cache.log.debug("There were "+countOne2Many+" alignment
209 // sequence ids (out of "+one2many.size()+" unique ids) linked to two or
216 * Creates a new NJTree object.
229 public NJTree(SequenceI[] sqs, AlignmentView seqView, String treeType,
230 String modelType, ScoreModelI sm, int start, int end)
233 this.node = new Vector<SequenceNode>();
234 this.type = treeType;
235 this.pwtype = modelType;
238 this.seqData = seqView;
242 SeqCigar[] seqs = new SeqCigar[sequence.length];
243 for (int i = 0; i < sequence.length; i++)
245 seqs[i] = new SeqCigar(sequence[i], start, end);
247 CigarArray sdata = new CigarArray(seqs);
248 sdata.addOperation(CigarArray.M, end - start + 1);
249 this.seqData = new AlignmentView(sdata, start);
251 // System.err.println("Made seqData");// dbg
252 if (!(treeType.equals(NEIGHBOUR_JOINING)))
254 treeType = AVERAGE_DISTANCE;
257 if (sm == null && !(modelType.equals("PID")))
259 if (ScoreModels.getInstance().forName(modelType) == null)
261 modelType = "BLOSUM62";
267 done = new int[sequence.length];
269 while ((i < sequence.length) && (sequence[i] != null))
277 if (sm instanceof DistanceScoreModelI)
279 distance = ((DistanceScoreModelI) sm).findDistances(seqData);
281 else if (sm instanceof SimilarityScoreModelI)
284 * compute similarity and invert it to give a distance measure
286 MatrixI result = ((SimilarityScoreModelI) sm)
287 .findSimilarities(seqData);
288 result.reverseRange(true);
292 // System.err.println("Made distances");// dbg
294 // System.err.println("Made leaves");// dbg
296 noClus = cluster.size();
299 // System.err.println("Made clusters");// dbg
304 * Generate a string representation of the Tree
306 * @return Newick File with all tree data available
309 public String toString()
311 jalview.io.NewickFile fout = new jalview.io.NewickFile(getTopNode());
313 return fout.print(isHasBootstrap(), isHasDistances(),
314 isHasRootDistance()); // output all data available for tree
319 * used when the alignment associated to a tree has changed.
322 * Sequence set to be associated with tree nodes
324 public void UpdatePlaceHolders(List<SequenceI> list)
326 Vector<SequenceNode> leaves = findLeaves(top);
328 int sz = leaves.size();
329 SequenceIdMatcher seqmatcher = null;
334 SequenceNode leaf = leaves.elementAt(i++);
336 if (list.contains(leaf.element()))
338 leaf.setPlaceholder(false);
342 if (seqmatcher == null)
344 // Only create this the first time we need it
345 SequenceI[] seqs = new SequenceI[list.size()];
347 for (int j = 0; j < seqs.length; j++)
349 seqs[j] = list.get(j);
352 seqmatcher = new SequenceIdMatcher(seqs);
355 SequenceI nam = seqmatcher.findIdMatch(leaf.getName());
359 if (!leaf.isPlaceholder())
361 // remapping the node to a new sequenceI - should remove any refs to
363 // TODO - make many sequenceI to one leaf mappings possible!
366 leaf.setPlaceholder(false);
367 leaf.setElement(nam);
371 if (!leaf.isPlaceholder())
373 // Construct a new placeholder sequence object for this leaf
374 leaf.setElement(new Sequence(leaf.getName(),
375 "THISISAPLACEHLDER"));
377 leaf.setPlaceholder(true);
385 * rename any nodes according to their associated sequence. This will modify
386 * the tree's metadata! (ie the original NewickFile or newly generated
387 * BinaryTree's label data)
389 public void renameAssociatedNodes()
391 applyToNodes(new NodeTransformI()
395 public void transform(BinaryNode nd)
397 Object el = nd.element();
398 if (el != null && el instanceof SequenceI)
400 nd.setName(((SequenceI) el).getName());
409 public void cluster()
413 if (type.equals(NEIGHBOUR_JOINING))
422 Cluster c = joinClusters(mini, minj);
426 cluster.setElementAt(null, minj);
427 cluster.setElementAt(c, mini);
432 boolean onefound = false;
437 for (int i = 0; i < noseqs; i++)
441 if (onefound == false)
453 joinClusters(one, two);
454 top = (node.elementAt(one));
469 * @return DOCUMENT ME!
471 public Cluster joinClusters(int i, int j)
473 double dist = distance.getValue(i, j);
475 int noi = cluster.elementAt(i).value.length;
476 int noj = cluster.elementAt(j).value.length;
478 int[] value = new int[noi + noj];
480 for (int ii = 0; ii < noi; ii++)
482 value[ii] = cluster.elementAt(i).value[ii];
485 for (int ii = noi; ii < (noi + noj); ii++)
487 value[ii] = cluster.elementAt(j).value[ii - noi];
490 Cluster c = new Cluster(value);
495 if (type.equals(NEIGHBOUR_JOINING))
497 findClusterNJDistance(i, j);
501 findClusterDistance(i, j);
504 SequenceNode sn = new SequenceNode();
506 sn.setLeft((node.elementAt(i)));
507 sn.setRight((node.elementAt(j)));
509 SequenceNode tmpi = (node.elementAt(i));
510 SequenceNode tmpj = (node.elementAt(j));
512 if (type.equals(NEIGHBOUR_JOINING))
514 findNewNJDistances(tmpi, tmpj, dist);
518 findNewDistances(tmpi, tmpj, dist);
524 node.setElementAt(sn, i);
539 public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj,
543 tmpi.dist = ((dist + ri) - rj) / 2;
544 tmpj.dist = (dist - tmpi.dist);
567 public void findNewDistances(SequenceNode tmpi, SequenceNode tmpj,
573 SequenceNode sni = tmpi;
574 SequenceNode snj = tmpj;
579 sni = (SequenceNode) sni.left();
585 snj = (SequenceNode) snj.left();
588 tmpi.dist = ((dist / 2) - ih);
589 tmpj.dist = ((dist / 2) - jh);
600 public void findClusterDistance(int i, int j)
602 int noi = cluster.elementAt(i).value.length;
603 int noj = cluster.elementAt(j).value.length;
605 // New distances from cluster to others
606 double[] newdist = new double[noseqs];
608 for (int l = 0; l < noseqs; l++)
610 if ((l != i) && (l != j))
612 // newdist[l] = ((distance[i][l] * noi) + (distance[j][l] * noj))
614 newdist[l] = ((distance.getValue(i, l) * noi) + (distance.getValue(
624 for (int ii = 0; ii < noseqs; ii++)
626 // distance[i][ii] = newdist[ii];
627 // distance[ii][i] = newdist[ii];
628 distance.setValue(i, ii, newdist[ii]);
629 distance.setValue(ii, i, newdist[ii]);
641 public void findClusterNJDistance(int i, int j)
644 // New distances from cluster to others
645 double[] newdist = new double[noseqs];
647 for (int l = 0; l < noseqs; l++)
649 if ((l != i) && (l != j))
651 // newdist[l] = ((distance[i][l] + distance[j][l]) - distance[i][j]) /
653 newdist[l] = (distance.getValue(i, l) + distance.getValue(j, l) - distance
654 .getValue(i, j)) / 2;
662 for (int ii = 0; ii < noseqs; ii++)
664 // distance[i][ii] = newdist[ii];
665 // distance[ii][i] = newdist[ii];
666 distance.setValue(i, ii, newdist[ii]);
667 distance.setValue(ii, i, newdist[ii]);
679 * @return DOCUMENT ME!
681 public double findr(int i, int j)
685 for (int k = 0; k < noseqs; k++)
687 if ((k != i) && (k != j) && (done[k] != 1))
689 // tmp = tmp + distance[i][k];
690 tmp = tmp + distance.getValue(i, k);
696 tmp = tmp / (noClus - 2);
705 * @return DOCUMENT ME!
707 public double findMinNJDistance()
709 double min = Double.MAX_VALUE;
711 for (int i = 0; i < (noseqs - 1); i++)
713 for (int j = i + 1; j < noseqs; j++)
715 if ((done[i] != 1) && (done[j] != 1))
717 // float tmp = distance[i][j] - (findr(i, j) + findr(j, i));
718 double tmp = distance.getValue(i, j)
719 - (findr(i, j) + findr(j, i));
738 * @return DOCUMENT ME!
740 public double findMinDistance()
742 double min = Double.MAX_VALUE;
744 for (int i = 0; i < (noseqs - 1); i++)
746 for (int j = i + 1; j < noseqs; j++)
748 if ((done[i] != 1) && (done[j] != 1))
750 // if (distance[i][j] < min)
751 if (distance.getValue(i, j) < min)
756 // min = distance[i][j];
757 min = distance.getValue(i, j);
767 * Calculate a distance matrix given the sequence input data and score model
771 public MatrixI findDistances(ScoreModelI scoreModel)
773 MatrixI result = null;
775 if (scoreModel == null)
777 // Resolve substitution model
778 scoreModel = ScoreModels.getInstance().forName(pwtype);
779 if (scoreModel == null)
781 scoreModel = ScoreModels.getInstance().forName("BLOSUM62");
784 if (scoreModel instanceof DistanceScoreModelI)
786 result = ((DistanceScoreModelI) scoreModel).findDistances(seqData);
788 else if (scoreModel instanceof SimilarityScoreModelI)
791 * compute similarity and invert it to give a distance measure
793 result = ((SimilarityScoreModelI) scoreModel)
794 .findSimilarities(seqData);
795 result.reverseRange(true);
800 .println("Unexpected type of score model, can't compute distances");
809 public void makeLeaves()
811 cluster = new Vector<Cluster>();
813 for (int i = 0; i < noseqs; i++)
815 SequenceNode sn = new SequenceNode();
817 sn.setElement(sequence[i]);
818 sn.setName(sequence[i].getName());
821 int[] value = new int[1];
824 Cluster c = new Cluster(value);
825 cluster.addElement(c);
830 * Search for leaf nodes below (or at) the given node
833 * root node to search from
837 public Vector<SequenceNode> findLeaves(SequenceNode nd)
839 Vector<SequenceNode> leaves = new Vector<SequenceNode>();
840 findLeaves(nd, leaves);
845 * Search for leaf nodes.
848 * root node to search from
850 * Vector of leaves to add leaf node objects too.
852 * @return Vector of leaf nodes on binary tree
854 Vector<SequenceNode> findLeaves(SequenceNode nd,
855 Vector<SequenceNode> leaves)
862 if ((nd.left() == null) && (nd.right() == null)) // Interior node
865 leaves.addElement(nd);
872 * TODO: Identify internal nodes... if (node.isSequenceLabel()) {
873 * leaves.addElement(node); }
875 findLeaves((SequenceNode) nd.left(), leaves);
876 findLeaves((SequenceNode) nd.right(), leaves);
883 * Find the leaf node with a particular ycount
886 * initial point on tree to search from
888 * value to search for
890 * @return null or the node with ycound=count
892 public Object findLeaf(SequenceNode nd, int count)
894 found = _findLeaf(nd, count);
900 * #see findLeaf(SequenceNode node, count)
902 public Object _findLeaf(SequenceNode nd, int count)
909 if (nd.ycount == count)
911 found = nd.element();
917 _findLeaf((SequenceNode) nd.left(), count);
918 _findLeaf((SequenceNode) nd.right(), count);
925 * printNode is mainly for debugging purposes.
930 public void printNode(SequenceNode nd)
937 if ((nd.left() == null) && (nd.right() == null))
939 System.out.println("Leaf = " + ((SequenceI) nd.element()).getName());
940 System.out.println("Dist " + nd.dist);
941 System.out.println("Boot " + nd.getBootstrap());
945 System.out.println("Dist " + nd.dist);
946 printNode((SequenceNode) nd.left());
947 printNode((SequenceNode) nd.right());
957 public void findMaxDist(SequenceNode nd)
964 if ((nd.left() == null) && (nd.right() == null))
966 double dist = nd.dist;
968 if (dist > maxDistValue)
976 findMaxDist((SequenceNode) nd.left());
977 findMaxDist((SequenceNode) nd.right());
984 * @return DOCUMENT ME!
986 public Vector<SequenceNode> getGroups()
994 * @return DOCUMENT ME!
996 public double getMaxHeight()
1009 public void groupNodes(SequenceNode nd, float threshold)
1016 if ((nd.height / maxheight) > threshold)
1018 groups.addElement(nd);
1022 groupNodes((SequenceNode) nd.left(), threshold);
1023 groupNodes((SequenceNode) nd.right(), threshold);
1033 * @return DOCUMENT ME!
1035 public double findHeight(SequenceNode nd)
1042 if ((nd.left() == null) && (nd.right() == null))
1044 nd.height = ((SequenceNode) nd.parent()).height + nd.dist;
1046 if (nd.height > maxheight)
1057 if (nd.parent() != null)
1059 nd.height = ((SequenceNode) nd.parent()).height + nd.dist;
1064 nd.height = (float) 0.0;
1067 maxheight = findHeight((SequenceNode) (nd.left()));
1068 maxheight = findHeight((SequenceNode) (nd.right()));
1077 * @return DOCUMENT ME!
1079 public SequenceNode reRoot()
1081 if (maxdist != null)
1085 double tmpdist = maxdist.dist;
1088 SequenceNode sn = new SequenceNode();
1091 // New right hand of top
1092 SequenceNode snr = (SequenceNode) maxdist.parent();
1093 changeDirection(snr, maxdist);
1094 System.out.println("Printing reversed tree");
1096 snr.dist = tmpdist / 2;
1097 maxdist.dist = tmpdist / 2;
1100 maxdist.setParent(sn);
1103 sn.setLeft(maxdist);
1117 * @return true if original sequence data can be recovered
1119 public boolean hasOriginalSequenceData()
1121 return seqData != null;
1125 * Returns original alignment data used for calculation - or null where not
1128 * @return null or cut'n'pasteable alignment
1130 public String printOriginalSequenceData(char gapChar)
1132 if (seqData == null)
1137 StringBuffer sb = new StringBuffer();
1138 String[] seqdatas = seqData.getSequenceStrings(gapChar);
1139 for (int i = 0; i < seqdatas.length; i++)
1141 sb.append(new jalview.util.Format("%-" + 15 + "s").form(sequence[i]
1143 sb.append(" " + seqdatas[i] + "\n");
1145 return sb.toString();
1154 public void printN(SequenceNode nd)
1161 if ((nd.left() != null) && (nd.right() != null))
1163 printN((SequenceNode) nd.left());
1164 printN((SequenceNode) nd.right());
1168 System.out.println(" name = " + ((SequenceI) nd.element()).getName());
1171 System.out.println(" dist = " + nd.dist + " " + nd.count + " "
1181 public void reCount(SequenceNode nd)
1185 // _lylimit = this.node.size();
1189 private long _lycount = 0, _lylimit = 0;
1197 public void _reCount(SequenceNode nd)
1199 // if (_lycount<_lylimit)
1201 // System.err.println("Warning: depth of _recount greater than number of nodes.");
1209 if ((nd.left() != null) && (nd.right() != null))
1212 _reCount((SequenceNode) nd.left());
1213 _reCount((SequenceNode) nd.right());
1215 SequenceNode l = (SequenceNode) nd.left();
1216 SequenceNode r = (SequenceNode) nd.right();
1218 nd.count = l.count + r.count;
1219 nd.ycount = (l.ycount + r.ycount) / 2;
1224 nd.ycount = ycount++;
1235 public void swapNodes(SequenceNode nd)
1242 SequenceNode tmp = (SequenceNode) nd.left();
1244 nd.setLeft(nd.right());
1256 public void changeDirection(SequenceNode nd, SequenceNode dir)
1263 if (nd.parent() != top)
1265 changeDirection((SequenceNode) nd.parent(), nd);
1267 SequenceNode tmp = (SequenceNode) nd.parent();
1269 if (dir == nd.left())
1274 else if (dir == nd.right())
1282 if (dir == nd.left())
1284 nd.setParent(nd.left());
1286 if (top.left() == nd)
1288 nd.setRight(top.right());
1292 nd.setRight(top.left());
1297 nd.setParent(nd.right());
1299 if (top.left() == nd)
1301 nd.setLeft(top.right());
1305 nd.setLeft(top.left());
1314 * @return DOCUMENT ME!
1316 public SequenceNode getMaxDist()
1324 * @return DOCUMENT ME!
1326 public SequenceNode getTopNode()
1333 * @return true if tree has real distances
1335 public boolean isHasDistances()
1337 return hasDistances;
1342 * @return true if tree has real bootstrap values
1344 public boolean isHasBootstrap()
1346 return hasBootstrap;
1349 public boolean isHasRootDistance()
1351 return hasRootDistance;
1355 * apply the given transform to all the nodes in the tree.
1357 * @param nodeTransformI
1359 public void applyToNodes(NodeTransformI nodeTransformI)
1361 for (Enumeration<SequenceNode> nodes = node.elements(); nodes
1362 .hasMoreElements(); nodeTransformI.transform(nodes
1374 * @version $Revision$
1376 // TODO what does this class have that int[] doesn't have already?
1382 * Creates a new Cluster object.
1387 public Cluster(int[] value)