2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
18 package jalview.analysis;
22 import jalview.datamodel.*;
24 import jalview.schemes.*;
25 import jalview.util.*;
39 // SequenceData is a string representation of what the user
40 // sees. The display may contain hidden columns.
41 public AlignmentView seqData = null;
59 Vector groups = new Vector();
81 boolean hasDistances = true; // normal case for jalview trees
83 boolean hasBootstrap = false; // normal case for jalview trees
85 private boolean hasRootDistance = true;
88 * Create a new NJTree object with leaves associated with sequences in seqs,
89 * and original alignment data represented by Cigar strings.
98 public NJTree(SequenceI[] seqs, AlignmentView odata, NewickFile treefile)
100 this(seqs, treefile);
106 * sequenceString = new String[odata.length]; char gapChar =
107 * jalview.util.Comparison.GapChars.charAt(0); for (int i = 0; i <
108 * odata.length; i++) { SequenceI oseq_aligned = odata[i].getSeq(gapChar);
109 * sequenceString[i] = oseq_aligned.getSequence(); }
114 * Creates a new NJTree object from a tree from an external source
117 * SequenceI which should be associated with leafs of treefile
121 public NJTree(SequenceI[] seqs, NewickFile treefile)
123 this.sequence = seqs;
124 top = treefile.getTree();
127 * There is no dependent alignment to be recovered from an imported tree.
129 * if (sequenceString == null) { sequenceString = new String[seqs.length];
130 * for (int i = 0; i < seqs.length; i++) { sequenceString[i] =
131 * seqs[i].getSequence(); } }
134 hasDistances = treefile.HasDistances();
135 hasBootstrap = treefile.HasBootstrap();
136 hasRootDistance = treefile.HasRootDistance();
138 maxheight = findHeight(top);
140 SequenceIdMatcher algnIds = new SequenceIdMatcher(seqs);
142 Vector leaves = new Vector();
143 findLeaves(top, leaves);
146 int namesleft = seqs.length;
151 Vector one2many = new Vector();
152 int countOne2Many = 0;
153 while (i < leaves.size())
155 j = (SequenceNode) leaves.elementAt(i++);
156 realnam = j.getName();
161 nam = algnIds.findIdMatch(realnam);
167 if (one2many.contains(nam))
170 // if (jalview.bin.Cache.log.isDebugEnabled())
171 // jalview.bin.Cache.log.debug("One 2 many relationship for
176 one2many.addElement(nam);
182 j.setElement(new Sequence(realnam, "THISISAPLACEHLDER"));
183 j.setPlaceholder(true);
186 // if (jalview.bin.Cache.log.isDebugEnabled() && countOne2Many>0) {
187 // jalview.bin.Cache.log.debug("There were "+countOne2Many+" alignment
188 // sequence ids (out of "+one2many.size()+" unique ids) linked to two or
195 * Creates a new NJTree object.
208 public NJTree(SequenceI[] sequence, AlignmentView seqData, String type,
209 String pwtype, int start, int end)
211 this.sequence = sequence;
212 this.node = new Vector();
214 this.pwtype = pwtype;
217 this.seqData = seqData;
221 SeqCigar[] seqs = new SeqCigar[sequence.length];
222 for (int i = 0; i < sequence.length; i++)
224 seqs[i] = new SeqCigar(sequence[i], start, end);
226 CigarArray sdata = new CigarArray(seqs);
227 sdata.addOperation(CigarArray.M, end - start + 1);
228 this.seqData = new AlignmentView(sdata, start);
230 // System.err.println("Made seqData");// dbg
231 if (!(type.equals("NJ")))
236 if (!(pwtype.equals("PID")))
238 if (ResidueProperties.getScoreMatrix(pwtype) == null)
246 done = new int[sequence.length];
248 while ((i < sequence.length) && (sequence[i] != null))
256 distance = findDistances(this.seqData
257 .getSequenceStrings(Comparison.GapChars.charAt(0)));
258 // System.err.println("Made distances");// dbg
260 // System.err.println("Made leaves");// dbg
262 noClus = cluster.size();
265 // System.err.println("Made clusters");// dbg
270 * Generate a string representation of the Tree
272 * @return Newick File with all tree data available
274 public String toString()
276 jalview.io.NewickFile fout = new jalview.io.NewickFile(getTopNode());
278 return fout.print(isHasBootstrap(),
279 isHasDistances(), isHasRootDistance()); // output all data available for tree
284 * used when the alignment associated to a tree has changed.
289 public void UpdatePlaceHolders(Vector alignment)
291 Vector leaves = new Vector();
292 findLeaves(top, leaves);
294 int sz = leaves.size();
295 SequenceIdMatcher seqmatcher = null;
300 SequenceNode leaf = (SequenceNode) leaves.elementAt(i++);
302 if (alignment.contains(leaf.element()))
304 leaf.setPlaceholder(false);
308 if (seqmatcher == null)
310 // Only create this the first time we need it
311 SequenceI[] seqs = new SequenceI[alignment.size()];
313 for (int j = 0; j < seqs.length; j++)
315 seqs[j] = (SequenceI) alignment.elementAt(j);
318 seqmatcher = new SequenceIdMatcher(seqs);
321 SequenceI nam = seqmatcher.findIdMatch(leaf.getName());
325 if (!leaf.isPlaceholder())
327 // remapping the node to a new sequenceI - should remove any refs to
329 // TODO - make many sequenceI to one leaf mappings possible!
332 leaf.setPlaceholder(false);
333 leaf.setElement(nam);
337 if (!leaf.isPlaceholder())
339 // Construct a new placeholder sequence object for this leaf
340 leaf.setElement(new Sequence(leaf.getName(),
341 "THISISAPLACEHLDER"));
343 leaf.setPlaceholder(true);
350 * rename any nodes according to their associated sequence.
351 * This will modify the tree's metadata! (ie the original NewickFile or newly generated BinaryTree's label data)
353 public void renameAssociatedNodes() {
354 applyToNodes(new NodeTransformI() {
357 public void transform(BinaryNode node)
359 Object el = node.element();
360 if (el!=null && el instanceof SequenceI)
362 node.setName(((SequenceI)el).getName());
370 public void cluster()
374 if (type.equals("NJ"))
383 Cluster c = joinClusters(mini, minj);
387 cluster.setElementAt(null, minj);
388 cluster.setElementAt(c, mini);
393 boolean onefound = false;
398 for (int i = 0; i < noseqs; i++)
402 if (onefound == false)
414 joinClusters(one, two);
415 top = (SequenceNode) (node.elementAt(one));
430 * @return DOCUMENT ME!
432 public Cluster joinClusters(int i, int j)
434 float dist = distance[i][j];
436 int noi = ((Cluster) cluster.elementAt(i)).value.length;
437 int noj = ((Cluster) cluster.elementAt(j)).value.length;
439 int[] value = new int[noi + noj];
441 for (int ii = 0; ii < noi; ii++)
443 value[ii] = ((Cluster) cluster.elementAt(i)).value[ii];
446 for (int ii = noi; ii < (noi + noj); ii++)
448 value[ii] = ((Cluster) cluster.elementAt(j)).value[ii - noi];
451 Cluster c = new Cluster(value);
456 if (type.equals("NJ"))
458 findClusterNJDistance(i, j);
462 findClusterDistance(i, j);
465 SequenceNode sn = new SequenceNode();
467 sn.setLeft((SequenceNode) (node.elementAt(i)));
468 sn.setRight((SequenceNode) (node.elementAt(j)));
470 SequenceNode tmpi = (SequenceNode) (node.elementAt(i));
471 SequenceNode tmpj = (SequenceNode) (node.elementAt(j));
473 if (type.equals("NJ"))
475 findNewNJDistances(tmpi, tmpj, dist);
479 findNewDistances(tmpi, tmpj, dist);
485 node.setElementAt(sn, i);
500 public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj,
504 tmpi.dist = ((dist + ri) - rj) / 2;
505 tmpj.dist = (dist - tmpi.dist);
528 public void findNewDistances(SequenceNode tmpi, SequenceNode tmpj,
534 SequenceNode sni = tmpi;
535 SequenceNode snj = tmpj;
540 sni = (SequenceNode) sni.left();
546 snj = (SequenceNode) snj.left();
549 tmpi.dist = ((dist / 2) - ih);
550 tmpj.dist = ((dist / 2) - jh);
561 public void findClusterDistance(int i, int j)
563 int noi = ((Cluster) cluster.elementAt(i)).value.length;
564 int noj = ((Cluster) cluster.elementAt(j)).value.length;
566 // New distances from cluster to others
567 float[] newdist = new float[noseqs];
569 for (int l = 0; l < noseqs; l++)
571 if ((l != i) && (l != j))
573 newdist[l] = ((distance[i][l] * noi) + (distance[j][l] * noj))
582 for (int ii = 0; ii < noseqs; ii++)
584 distance[i][ii] = newdist[ii];
585 distance[ii][i] = newdist[ii];
597 public void findClusterNJDistance(int i, int j)
600 // New distances from cluster to others
601 float[] newdist = new float[noseqs];
603 for (int l = 0; l < noseqs; l++)
605 if ((l != i) && (l != j))
607 newdist[l] = ((distance[i][l] + distance[j][l]) - distance[i][j]) / 2;
615 for (int ii = 0; ii < noseqs; ii++)
617 distance[i][ii] = newdist[ii];
618 distance[ii][i] = newdist[ii];
630 * @return DOCUMENT ME!
632 public float findr(int i, int j)
636 for (int k = 0; k < noseqs; k++)
638 if ((k != i) && (k != j) && (done[k] != 1))
640 tmp = tmp + distance[i][k];
646 tmp = tmp / (noClus - 2);
655 * @return DOCUMENT ME!
657 public float findMinNJDistance()
661 for (int i = 0; i < (noseqs - 1); i++)
663 for (int j = i + 1; j < noseqs; j++)
665 if ((done[i] != 1) && (done[j] != 1))
667 float tmp = distance[i][j] - (findr(i, j) + findr(j, i));
686 * @return DOCUMENT ME!
688 public float findMinDistance()
692 for (int i = 0; i < (noseqs - 1); i++)
694 for (int j = i + 1; j < noseqs; j++)
696 if ((done[i] != 1) && (done[j] != 1))
698 if (distance[i][j] < min)
703 min = distance[i][j];
715 * @return DOCUMENT ME!
717 public float[][] findDistances(String[] sequenceString)
719 float[][] distance = new float[noseqs][noseqs];
721 if (pwtype.equals("PID"))
723 for (int i = 0; i < (noseqs - 1); i++)
725 for (int j = i; j < noseqs; j++)
733 distance[i][j] = 100 - Comparison.PID(sequenceString[i],
736 distance[j][i] = distance[i][j];
743 // Pairwise substitution score (with no gap penalties)
744 ScoreMatrix pwmatrix = ResidueProperties.getScoreMatrix(pwtype);
745 if (pwmatrix == null)
747 pwmatrix = ResidueProperties.getScoreMatrix("BLOSUM62");
750 int end = sequenceString[0].length();
751 for (int i = 0; i < (noseqs - 1); i++)
753 for (int j = i; j < noseqs; j++)
757 for (int k = 0; k < end; k++)
761 score += pwmatrix.getPairwiseScore(
762 sequenceString[i].charAt(k),
763 sequenceString[j].charAt(k));
764 } catch (Exception ex)
766 System.err.println("err creating BLOSUM62 tree");
767 ex.printStackTrace();
771 distance[i][j] = (float) score;
773 if (score > maxscore)
780 for (int i = 0; i < (noseqs - 1); i++)
782 for (int j = i; j < noseqs; j++)
784 distance[i][j] = (float) maxscore - distance[i][j];
785 distance[j][i] = distance[i][j];
794 * else if (pwtype.equals("SW")) { float max = -1;
796 * for (int i = 0; i < (noseqs - 1); i++) { for (int j = i; j < noseqs; j++)
797 * { AlignSeq as = new AlignSeq(sequence[i], sequence[j], "pep");
798 * as.calcScoreMatrix(); as.traceAlignment(); as.printAlignment(System.out);
799 * distance[i][j] = (float) as.maxscore;
801 * if (max < distance[i][j]) { max = distance[i][j]; } } }
803 * for (int i = 0; i < (noseqs - 1); i++) { for (int j = i; j < noseqs; j++)
804 * { distance[i][j] = max - distance[i][j]; distance[j][i] = distance[i][j];
812 public void makeLeaves()
814 cluster = new Vector();
816 for (int i = 0; i < noseqs; i++)
818 SequenceNode sn = new SequenceNode();
820 sn.setElement(sequence[i]);
821 sn.setName(sequence[i].getName());
824 int[] value = new int[1];
827 Cluster c = new Cluster(value);
828 cluster.addElement(c);
833 * Search for leaf nodes.
836 * root node to search from
838 * Vector of leaves to add leaf node objects too.
840 * @return Vector of leaf nodes on binary tree
842 public Vector findLeaves(SequenceNode node, Vector leaves)
849 if ((node.left() == null) && (node.right() == null)) // Interior node
852 leaves.addElement(node);
859 * TODO: Identify internal nodes... if (node.isSequenceLabel()) {
860 * leaves.addElement(node); }
862 findLeaves((SequenceNode) node.left(), leaves);
863 findLeaves((SequenceNode) node.right(), leaves);
870 * Find the leaf node with a particular ycount
873 * initial point on tree to search from
875 * value to search for
877 * @return null or the node with ycound=count
879 public Object findLeaf(SequenceNode node, int count)
881 found = _findLeaf(node, count);
887 * #see findLeaf(SequenceNode node, count)
889 public Object _findLeaf(SequenceNode node, int count)
896 if (node.ycount == count)
898 found = node.element();
904 _findLeaf((SequenceNode) node.left(), count);
905 _findLeaf((SequenceNode) node.right(), count);
912 * printNode is mainly for debugging purposes.
917 public void printNode(SequenceNode node)
924 if ((node.left() == null) && (node.right() == null))
927 .println("Leaf = " + ((SequenceI) node.element()).getName());
928 System.out.println("Dist " + ((SequenceNode) node).dist);
929 System.out.println("Boot " + node.getBootstrap());
933 System.out.println("Dist " + ((SequenceNode) node).dist);
934 printNode((SequenceNode) node.left());
935 printNode((SequenceNode) node.right());
945 public void findMaxDist(SequenceNode node)
952 if ((node.left() == null) && (node.right() == null))
954 float dist = ((SequenceNode) node).dist;
956 if (dist > maxDistValue)
958 maxdist = (SequenceNode) node;
964 findMaxDist((SequenceNode) node.left());
965 findMaxDist((SequenceNode) node.right());
972 * @return DOCUMENT ME!
974 public Vector getGroups()
982 * @return DOCUMENT ME!
984 public float getMaxHeight()
997 public void groupNodes(SequenceNode node, float threshold)
1004 if ((node.height / maxheight) > threshold)
1006 groups.addElement(node);
1010 groupNodes((SequenceNode) node.left(), threshold);
1011 groupNodes((SequenceNode) node.right(), threshold);
1021 * @return DOCUMENT ME!
1023 public float findHeight(SequenceNode node)
1030 if ((node.left() == null) && (node.right() == null))
1032 node.height = ((SequenceNode) node.parent()).height + node.dist;
1034 if (node.height > maxheight)
1045 if (node.parent() != null)
1047 node.height = ((SequenceNode) node.parent()).height + node.dist;
1052 node.height = (float) 0.0;
1055 maxheight = findHeight((SequenceNode) (node.left()));
1056 maxheight = findHeight((SequenceNode) (node.right()));
1065 * @return DOCUMENT ME!
1067 public SequenceNode reRoot()
1069 if (maxdist != null)
1073 float tmpdist = maxdist.dist;
1076 SequenceNode sn = new SequenceNode();
1079 // New right hand of top
1080 SequenceNode snr = (SequenceNode) maxdist.parent();
1081 changeDirection(snr, maxdist);
1082 System.out.println("Printing reversed tree");
1084 snr.dist = tmpdist / 2;
1085 maxdist.dist = tmpdist / 2;
1088 maxdist.setParent(sn);
1091 sn.setLeft(maxdist);
1105 * @return true if original sequence data can be recovered
1107 public boolean hasOriginalSequenceData()
1109 return seqData != null;
1113 * Returns original alignment data used for calculation - or null where not
1116 * @return null or cut'n'pasteable alignment
1118 public String printOriginalSequenceData(char gapChar)
1120 if (seqData == null)
1125 StringBuffer sb = new StringBuffer();
1126 String[] seqdatas = seqData.getSequenceStrings(gapChar);
1127 for (int i = 0; i < seqdatas.length; i++)
1129 sb.append(new jalview.util.Format("%-" + 15 + "s").form(sequence[i]
1131 sb.append(" " + seqdatas[i] + "\n");
1133 return sb.toString();
1142 public void printN(SequenceNode node)
1149 if ((node.left() != null) && (node.right() != null))
1151 printN((SequenceNode) node.left());
1152 printN((SequenceNode) node.right());
1156 System.out.println(" name = "
1157 + ((SequenceI) node.element()).getName());
1160 System.out.println(" dist = " + ((SequenceNode) node).dist + " "
1161 + ((SequenceNode) node).count + " "
1162 + ((SequenceNode) node).height);
1171 public void reCount(SequenceNode node)
1175 // _lylimit = this.node.size();
1179 private long _lycount = 0, _lylimit = 0;
1187 public void _reCount(SequenceNode node)
1189 // if (_lycount<_lylimit)
1191 // System.err.println("Warning: depth of _recount greater than number of nodes.");
1199 if ((node.left() != null) && (node.right() != null))
1202 _reCount((SequenceNode) node.left());
1203 _reCount((SequenceNode) node.right());
1205 SequenceNode l = (SequenceNode) node.left();
1206 SequenceNode r = (SequenceNode) node.right();
1208 ((SequenceNode) node).count = l.count + r.count;
1209 ((SequenceNode) node).ycount = (l.ycount + r.ycount) / 2;
1213 ((SequenceNode) node).count = 1;
1214 ((SequenceNode) node).ycount = ycount++;
1225 public void swapNodes(SequenceNode node)
1232 SequenceNode tmp = (SequenceNode) node.left();
1234 node.setLeft(node.right());
1246 public void changeDirection(SequenceNode node, SequenceNode dir)
1253 if (node.parent() != top)
1255 changeDirection((SequenceNode) node.parent(), node);
1257 SequenceNode tmp = (SequenceNode) node.parent();
1259 if (dir == node.left())
1261 node.setParent(dir);
1264 else if (dir == node.right())
1266 node.setParent(dir);
1272 if (dir == node.left())
1274 node.setParent(node.left());
1276 if (top.left() == node)
1278 node.setRight(top.right());
1282 node.setRight(top.left());
1287 node.setParent(node.right());
1289 if (top.left() == node)
1291 node.setLeft(top.right());
1295 node.setLeft(top.left());
1304 * @return DOCUMENT ME!
1306 public SequenceNode getMaxDist()
1314 * @return DOCUMENT ME!
1316 public SequenceNode getTopNode()
1323 * @return true if tree has real distances
1325 public boolean isHasDistances()
1327 return hasDistances;
1332 * @return true if tree has real bootstrap values
1334 public boolean isHasBootstrap()
1336 return hasBootstrap;
1339 public boolean isHasRootDistance()
1341 return hasRootDistance;
1345 * apply the given transform to all the nodes in the tree.
1347 * @param nodeTransformI
1349 public void applyToNodes(NodeTransformI nodeTransformI)
1351 for (Enumeration nodes = node.elements(); nodes.hasMoreElements(); nodeTransformI
1352 .transform((BinaryNode) nodes.nextElement()))
1361 * @version $Revision$
1368 * Creates a new Cluster object.
1373 public Cluster(int[] value)