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);
294 noClus = cluster.size();
300 * Generate a string representation of the Tree
302 * @return Newick File with all tree data available
305 public String toString()
307 jalview.io.NewickFile fout = new jalview.io.NewickFile(getTopNode());
309 return fout.print(isHasBootstrap(), isHasDistances(),
310 isHasRootDistance()); // output all data available for tree
315 * used when the alignment associated to a tree has changed.
318 * Sequence set to be associated with tree nodes
320 public void UpdatePlaceHolders(List<SequenceI> list)
322 Vector<SequenceNode> leaves = findLeaves(top);
324 int sz = leaves.size();
325 SequenceIdMatcher seqmatcher = null;
330 SequenceNode leaf = leaves.elementAt(i++);
332 if (list.contains(leaf.element()))
334 leaf.setPlaceholder(false);
338 if (seqmatcher == null)
340 // Only create this the first time we need it
341 SequenceI[] seqs = new SequenceI[list.size()];
343 for (int j = 0; j < seqs.length; j++)
345 seqs[j] = list.get(j);
348 seqmatcher = new SequenceIdMatcher(seqs);
351 SequenceI nam = seqmatcher.findIdMatch(leaf.getName());
355 if (!leaf.isPlaceholder())
357 // remapping the node to a new sequenceI - should remove any refs to
359 // TODO - make many sequenceI to one leaf mappings possible!
362 leaf.setPlaceholder(false);
363 leaf.setElement(nam);
367 if (!leaf.isPlaceholder())
369 // Construct a new placeholder sequence object for this leaf
370 leaf.setElement(new Sequence(leaf.getName(),
371 "THISISAPLACEHLDER"));
373 leaf.setPlaceholder(true);
381 * rename any nodes according to their associated sequence. This will modify
382 * the tree's metadata! (ie the original NewickFile or newly generated
383 * BinaryTree's label data)
385 public void renameAssociatedNodes()
387 applyToNodes(new NodeTransformI()
391 public void transform(BinaryNode nd)
393 Object el = nd.element();
394 if (el != null && el instanceof SequenceI)
396 nd.setName(((SequenceI) el).getName());
405 public void cluster()
409 if (type.equals(NEIGHBOUR_JOINING))
418 Cluster c = joinClusters(mini, minj);
422 cluster.setElementAt(null, minj);
423 cluster.setElementAt(c, mini);
428 boolean onefound = false;
433 for (int i = 0; i < noseqs; i++)
437 if (onefound == false)
449 joinClusters(one, two);
450 top = (node.elementAt(one));
465 * @return DOCUMENT ME!
467 public Cluster joinClusters(int i, int j)
469 double dist = distance.getValue(i, j);
471 int noi = cluster.elementAt(i).value.length;
472 int noj = cluster.elementAt(j).value.length;
474 int[] value = new int[noi + noj];
476 for (int ii = 0; ii < noi; ii++)
478 value[ii] = cluster.elementAt(i).value[ii];
481 for (int ii = noi; ii < (noi + noj); ii++)
483 value[ii] = cluster.elementAt(j).value[ii - noi];
486 Cluster c = new Cluster(value);
491 if (type.equals(NEIGHBOUR_JOINING))
493 findClusterNJDistance(i, j);
497 findClusterDistance(i, j);
500 SequenceNode sn = new SequenceNode();
502 sn.setLeft((node.elementAt(i)));
503 sn.setRight((node.elementAt(j)));
505 SequenceNode tmpi = (node.elementAt(i));
506 SequenceNode tmpj = (node.elementAt(j));
508 if (type.equals(NEIGHBOUR_JOINING))
510 findNewNJDistances(tmpi, tmpj, dist);
514 findNewDistances(tmpi, tmpj, dist);
520 node.setElementAt(sn, i);
535 public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj,
539 tmpi.dist = ((dist + ri) - rj) / 2;
540 tmpj.dist = (dist - tmpi.dist);
563 public void findNewDistances(SequenceNode tmpi, SequenceNode tmpj,
569 SequenceNode sni = tmpi;
570 SequenceNode snj = tmpj;
575 sni = (SequenceNode) sni.left();
581 snj = (SequenceNode) snj.left();
584 tmpi.dist = ((dist / 2) - ih);
585 tmpj.dist = ((dist / 2) - jh);
596 public void findClusterDistance(int i, int j)
598 int noi = cluster.elementAt(i).value.length;
599 int noj = cluster.elementAt(j).value.length;
601 // New distances from cluster to others
602 double[] newdist = new double[noseqs];
604 for (int l = 0; l < noseqs; l++)
606 if ((l != i) && (l != j))
608 // newdist[l] = ((distance[i][l] * noi) + (distance[j][l] * noj))
610 newdist[l] = ((distance.getValue(i, l) * noi) + (distance.getValue(
620 for (int ii = 0; ii < noseqs; ii++)
622 // distance[i][ii] = newdist[ii];
623 // distance[ii][i] = newdist[ii];
624 distance.setValue(i, ii, newdist[ii]);
625 distance.setValue(ii, i, newdist[ii]);
637 public void findClusterNJDistance(int i, int j)
640 // New distances from cluster to others
641 double[] newdist = new double[noseqs];
643 for (int l = 0; l < noseqs; l++)
645 if ((l != i) && (l != j))
647 // newdist[l] = ((distance[i][l] + distance[j][l]) - distance[i][j]) /
649 newdist[l] = (distance.getValue(i, l) + distance.getValue(j, l) - distance
650 .getValue(i, j)) / 2;
658 for (int ii = 0; ii < noseqs; ii++)
660 // distance[i][ii] = newdist[ii];
661 // distance[ii][i] = newdist[ii];
662 distance.setValue(i, ii, newdist[ii]);
663 distance.setValue(ii, i, newdist[ii]);
675 * @return DOCUMENT ME!
677 public double findr(int i, int j)
681 for (int k = 0; k < noseqs; k++)
683 if ((k != i) && (k != j) && (done[k] != 1))
685 // tmp = tmp + distance[i][k];
686 tmp = tmp + distance.getValue(i, k);
692 tmp = tmp / (noClus - 2);
701 * @return DOCUMENT ME!
703 public double findMinNJDistance()
705 double min = Double.MAX_VALUE;
707 for (int i = 0; i < (noseqs - 1); i++)
709 for (int j = i + 1; j < noseqs; j++)
711 if ((done[i] != 1) && (done[j] != 1))
713 // float tmp = distance[i][j] - (findr(i, j) + findr(j, i));
714 double tmp = distance.getValue(i, j)
715 - (findr(i, j) + findr(j, i));
734 * @return DOCUMENT ME!
736 public double findMinDistance()
738 double min = Double.MAX_VALUE;
740 for (int i = 0; i < (noseqs - 1); i++)
742 for (int j = i + 1; j < noseqs; j++)
744 if ((done[i] != 1) && (done[j] != 1))
746 // if (distance[i][j] < min)
747 if (distance.getValue(i, j) < min)
752 // min = distance[i][j];
753 min = distance.getValue(i, j);
765 public void makeLeaves()
767 cluster = new Vector<Cluster>();
769 for (int i = 0; i < noseqs; i++)
771 SequenceNode sn = new SequenceNode();
773 sn.setElement(sequence[i]);
774 sn.setName(sequence[i].getName());
777 int[] value = new int[1];
780 Cluster c = new Cluster(value);
781 cluster.addElement(c);
786 * Search for leaf nodes below (or at) the given node
789 * root node to search from
793 public Vector<SequenceNode> findLeaves(SequenceNode nd)
795 Vector<SequenceNode> leaves = new Vector<SequenceNode>();
796 findLeaves(nd, leaves);
801 * Search for leaf nodes.
804 * root node to search from
806 * Vector of leaves to add leaf node objects too.
808 * @return Vector of leaf nodes on binary tree
810 Vector<SequenceNode> findLeaves(SequenceNode nd,
811 Vector<SequenceNode> leaves)
818 if ((nd.left() == null) && (nd.right() == null)) // Interior node
821 leaves.addElement(nd);
828 * TODO: Identify internal nodes... if (node.isSequenceLabel()) {
829 * leaves.addElement(node); }
831 findLeaves((SequenceNode) nd.left(), leaves);
832 findLeaves((SequenceNode) nd.right(), leaves);
839 * Find the leaf node with a particular ycount
842 * initial point on tree to search from
844 * value to search for
846 * @return null or the node with ycound=count
848 public Object findLeaf(SequenceNode nd, int count)
850 found = _findLeaf(nd, count);
856 * #see findLeaf(SequenceNode node, count)
858 public Object _findLeaf(SequenceNode nd, int count)
865 if (nd.ycount == count)
867 found = nd.element();
873 _findLeaf((SequenceNode) nd.left(), count);
874 _findLeaf((SequenceNode) nd.right(), count);
881 * printNode is mainly for debugging purposes.
886 public void printNode(SequenceNode nd)
893 if ((nd.left() == null) && (nd.right() == null))
895 System.out.println("Leaf = " + ((SequenceI) nd.element()).getName());
896 System.out.println("Dist " + nd.dist);
897 System.out.println("Boot " + nd.getBootstrap());
901 System.out.println("Dist " + nd.dist);
902 printNode((SequenceNode) nd.left());
903 printNode((SequenceNode) nd.right());
913 public void findMaxDist(SequenceNode nd)
920 if ((nd.left() == null) && (nd.right() == null))
922 double dist = nd.dist;
924 if (dist > maxDistValue)
932 findMaxDist((SequenceNode) nd.left());
933 findMaxDist((SequenceNode) nd.right());
940 * @return DOCUMENT ME!
942 public Vector<SequenceNode> getGroups()
950 * @return DOCUMENT ME!
952 public double getMaxHeight()
965 public void groupNodes(SequenceNode nd, float threshold)
972 if ((nd.height / maxheight) > threshold)
974 groups.addElement(nd);
978 groupNodes((SequenceNode) nd.left(), threshold);
979 groupNodes((SequenceNode) nd.right(), threshold);
989 * @return DOCUMENT ME!
991 public double findHeight(SequenceNode nd)
998 if ((nd.left() == null) && (nd.right() == null))
1000 nd.height = ((SequenceNode) nd.parent()).height + nd.dist;
1002 if (nd.height > maxheight)
1013 if (nd.parent() != null)
1015 nd.height = ((SequenceNode) nd.parent()).height + nd.dist;
1020 nd.height = (float) 0.0;
1023 maxheight = findHeight((SequenceNode) (nd.left()));
1024 maxheight = findHeight((SequenceNode) (nd.right()));
1033 * @return DOCUMENT ME!
1035 public SequenceNode reRoot()
1037 if (maxdist != null)
1041 double tmpdist = maxdist.dist;
1044 SequenceNode sn = new SequenceNode();
1047 // New right hand of top
1048 SequenceNode snr = (SequenceNode) maxdist.parent();
1049 changeDirection(snr, maxdist);
1050 System.out.println("Printing reversed tree");
1052 snr.dist = tmpdist / 2;
1053 maxdist.dist = tmpdist / 2;
1056 maxdist.setParent(sn);
1059 sn.setLeft(maxdist);
1073 * @return true if original sequence data can be recovered
1075 public boolean hasOriginalSequenceData()
1077 return seqData != null;
1081 * Returns original alignment data used for calculation - or null where not
1084 * @return null or cut'n'pasteable alignment
1086 public String printOriginalSequenceData(char gapChar)
1088 if (seqData == null)
1093 StringBuffer sb = new StringBuffer();
1094 String[] seqdatas = seqData.getSequenceStrings(gapChar);
1095 for (int i = 0; i < seqdatas.length; i++)
1097 sb.append(new jalview.util.Format("%-" + 15 + "s").form(sequence[i]
1099 sb.append(" " + seqdatas[i] + "\n");
1101 return sb.toString();
1110 public void printN(SequenceNode nd)
1117 if ((nd.left() != null) && (nd.right() != null))
1119 printN((SequenceNode) nd.left());
1120 printN((SequenceNode) nd.right());
1124 System.out.println(" name = " + ((SequenceI) nd.element()).getName());
1127 System.out.println(" dist = " + nd.dist + " " + nd.count + " "
1137 public void reCount(SequenceNode nd)
1141 // _lylimit = this.node.size();
1145 private long _lycount = 0, _lylimit = 0;
1153 public void _reCount(SequenceNode nd)
1155 // if (_lycount<_lylimit)
1157 // System.err.println("Warning: depth of _recount greater than number of nodes.");
1165 if ((nd.left() != null) && (nd.right() != null))
1168 _reCount((SequenceNode) nd.left());
1169 _reCount((SequenceNode) nd.right());
1171 SequenceNode l = (SequenceNode) nd.left();
1172 SequenceNode r = (SequenceNode) nd.right();
1174 nd.count = l.count + r.count;
1175 nd.ycount = (l.ycount + r.ycount) / 2;
1180 nd.ycount = ycount++;
1191 public void swapNodes(SequenceNode nd)
1198 SequenceNode tmp = (SequenceNode) nd.left();
1200 nd.setLeft(nd.right());
1212 public void changeDirection(SequenceNode nd, SequenceNode dir)
1219 if (nd.parent() != top)
1221 changeDirection((SequenceNode) nd.parent(), nd);
1223 SequenceNode tmp = (SequenceNode) nd.parent();
1225 if (dir == nd.left())
1230 else if (dir == nd.right())
1238 if (dir == nd.left())
1240 nd.setParent(nd.left());
1242 if (top.left() == nd)
1244 nd.setRight(top.right());
1248 nd.setRight(top.left());
1253 nd.setParent(nd.right());
1255 if (top.left() == nd)
1257 nd.setLeft(top.right());
1261 nd.setLeft(top.left());
1270 * @return DOCUMENT ME!
1272 public SequenceNode getMaxDist()
1280 * @return DOCUMENT ME!
1282 public SequenceNode getTopNode()
1289 * @return true if tree has real distances
1291 public boolean isHasDistances()
1293 return hasDistances;
1298 * @return true if tree has real bootstrap values
1300 public boolean isHasBootstrap()
1302 return hasBootstrap;
1305 public boolean isHasRootDistance()
1307 return hasRootDistance;
1311 * apply the given transform to all the nodes in the tree.
1313 * @param nodeTransformI
1315 public void applyToNodes(NodeTransformI nodeTransformI)
1317 for (Enumeration<SequenceNode> nodes = node.elements(); nodes
1318 .hasMoreElements(); nodeTransformI.transform(nodes
1330 * @version $Revision$
1332 // TODO what does this class have that int[] doesn't have already?
1338 * Creates a new Cluster object.
1343 public Cluster(int[] value)