2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3 * Copyright (C) 2014 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 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/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
19 package jalview.analysis;
23 import jalview.datamodel.*;
25 import jalview.schemes.*;
26 import jalview.util.*;
40 // SequenceData is a string representation of what the user
41 // sees. The display may contain hidden columns.
42 public AlignmentView seqData = null;
60 Vector groups = new Vector();
82 boolean hasDistances = true; // normal case for jalview trees
84 boolean hasBootstrap = false; // normal case for jalview trees
86 private boolean hasRootDistance = true;
89 * Create a new NJTree object with leaves associated with sequences in seqs,
90 * and original alignment data represented by Cigar strings.
99 public NJTree(SequenceI[] seqs, AlignmentView odata, NewickFile treefile)
101 this(seqs, treefile);
107 * sequenceString = new String[odata.length]; char gapChar =
108 * jalview.util.Comparison.GapChars.charAt(0); for (int i = 0; i <
109 * odata.length; i++) { SequenceI oseq_aligned = odata[i].getSeq(gapChar);
110 * sequenceString[i] = oseq_aligned.getSequence(); }
115 * Creates a new NJTree object from a tree from an external source
118 * SequenceI which should be associated with leafs of treefile
122 public NJTree(SequenceI[] seqs, NewickFile treefile)
124 this.sequence = seqs;
125 top = treefile.getTree();
128 * There is no dependent alignment to be recovered from an imported tree.
130 * if (sequenceString == null) { sequenceString = new String[seqs.length];
131 * for (int i = 0; i < seqs.length; i++) { sequenceString[i] =
132 * seqs[i].getSequence(); } }
135 hasDistances = treefile.HasDistances();
136 hasBootstrap = treefile.HasBootstrap();
137 hasRootDistance = treefile.HasRootDistance();
139 maxheight = findHeight(top);
141 SequenceIdMatcher algnIds = new SequenceIdMatcher(seqs);
143 Vector leaves = new Vector();
144 findLeaves(top, leaves);
147 int namesleft = seqs.length;
152 Vector one2many = new Vector();
153 int countOne2Many = 0;
154 while (i < leaves.size())
156 j = (SequenceNode) leaves.elementAt(i++);
157 realnam = j.getName();
162 nam = algnIds.findIdMatch(realnam);
168 if (one2many.contains(nam))
171 // if (jalview.bin.Cache.log.isDebugEnabled())
172 // jalview.bin.Cache.log.debug("One 2 many relationship for
177 one2many.addElement(nam);
183 j.setElement(new Sequence(realnam, "THISISAPLACEHLDER"));
184 j.setPlaceholder(true);
187 // if (jalview.bin.Cache.log.isDebugEnabled() && countOne2Many>0) {
188 // jalview.bin.Cache.log.debug("There were "+countOne2Many+" alignment
189 // sequence ids (out of "+one2many.size()+" unique ids) linked to two or
196 * Creates a new NJTree object.
209 public NJTree(SequenceI[] sequence, AlignmentView seqData, String type,
210 String pwtype, int start, int end)
212 this.sequence = sequence;
213 this.node = new Vector();
215 this.pwtype = pwtype;
218 this.seqData = seqData;
222 SeqCigar[] seqs = new SeqCigar[sequence.length];
223 for (int i = 0; i < sequence.length; i++)
225 seqs[i] = new SeqCigar(sequence[i], start, end);
227 CigarArray sdata = new CigarArray(seqs);
228 sdata.addOperation(CigarArray.M, end - start + 1);
229 this.seqData = new AlignmentView(sdata, start);
231 // System.err.println("Made seqData");// dbg
232 if (!(type.equals("NJ")))
237 if (!(pwtype.equals("PID")))
239 if (ResidueProperties.getScoreMatrix(pwtype) == null)
247 done = new int[sequence.length];
249 while ((i < sequence.length) && (sequence[i] != null))
257 distance = findDistances(this.seqData
258 .getSequenceStrings(Comparison.GapChars.charAt(0)));
259 // System.err.println("Made distances");// dbg
261 // System.err.println("Made leaves");// dbg
263 noClus = cluster.size();
266 // System.err.println("Made clusters");// dbg
271 * Generate a string representation of the Tree
273 * @return Newick File with all tree data available
275 public String toString()
277 jalview.io.NewickFile fout = new jalview.io.NewickFile(getTopNode());
279 return fout.print(isHasBootstrap(), isHasDistances(),
280 isHasRootDistance()); // output all data available for tree
285 * used when the alignment associated to a tree has changed.
288 * Sequence set to be associated with tree nodes
290 public void UpdatePlaceHolders(List<SequenceI> list)
292 Vector leaves = new Vector();
293 findLeaves(top, leaves);
295 int sz = leaves.size();
296 SequenceIdMatcher seqmatcher = null;
301 SequenceNode leaf = (SequenceNode) leaves.elementAt(i++);
303 if (list.contains(leaf.element()))
305 leaf.setPlaceholder(false);
309 if (seqmatcher == null)
311 // Only create this the first time we need it
312 SequenceI[] seqs = new SequenceI[list.size()];
314 for (int j = 0; j < seqs.length; j++)
316 seqs[j] = (SequenceI) list.get(j);
319 seqmatcher = new SequenceIdMatcher(seqs);
322 SequenceI nam = seqmatcher.findIdMatch(leaf.getName());
326 if (!leaf.isPlaceholder())
328 // remapping the node to a new sequenceI - should remove any refs to
330 // TODO - make many sequenceI to one leaf mappings possible!
333 leaf.setPlaceholder(false);
334 leaf.setElement(nam);
338 if (!leaf.isPlaceholder())
340 // Construct a new placeholder sequence object for this leaf
341 leaf.setElement(new Sequence(leaf.getName(),
342 "THISISAPLACEHLDER"));
344 leaf.setPlaceholder(true);
352 * rename any nodes according to their associated sequence. This will modify
353 * the tree's metadata! (ie the original NewickFile or newly generated
354 * BinaryTree's label data)
356 public void renameAssociatedNodes()
358 applyToNodes(new NodeTransformI()
362 public void transform(BinaryNode node)
364 Object el = node.element();
365 if (el != null && el instanceof SequenceI)
367 node.setName(((SequenceI) el).getName());
376 public void cluster()
380 if (type.equals("NJ"))
389 Cluster c = joinClusters(mini, minj);
393 cluster.setElementAt(null, minj);
394 cluster.setElementAt(c, mini);
399 boolean onefound = false;
404 for (int i = 0; i < noseqs; i++)
408 if (onefound == false)
420 joinClusters(one, two);
421 top = (SequenceNode) (node.elementAt(one));
436 * @return DOCUMENT ME!
438 public Cluster joinClusters(int i, int j)
440 float dist = distance[i][j];
442 int noi = ((Cluster) cluster.elementAt(i)).value.length;
443 int noj = ((Cluster) cluster.elementAt(j)).value.length;
445 int[] value = new int[noi + noj];
447 for (int ii = 0; ii < noi; ii++)
449 value[ii] = ((Cluster) cluster.elementAt(i)).value[ii];
452 for (int ii = noi; ii < (noi + noj); ii++)
454 value[ii] = ((Cluster) cluster.elementAt(j)).value[ii - noi];
457 Cluster c = new Cluster(value);
462 if (type.equals("NJ"))
464 findClusterNJDistance(i, j);
468 findClusterDistance(i, j);
471 SequenceNode sn = new SequenceNode();
473 sn.setLeft((SequenceNode) (node.elementAt(i)));
474 sn.setRight((SequenceNode) (node.elementAt(j)));
476 SequenceNode tmpi = (SequenceNode) (node.elementAt(i));
477 SequenceNode tmpj = (SequenceNode) (node.elementAt(j));
479 if (type.equals("NJ"))
481 findNewNJDistances(tmpi, tmpj, dist);
485 findNewDistances(tmpi, tmpj, dist);
491 node.setElementAt(sn, i);
506 public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj,
510 tmpi.dist = ((dist + ri) - rj) / 2;
511 tmpj.dist = (dist - tmpi.dist);
534 public void findNewDistances(SequenceNode tmpi, SequenceNode tmpj,
540 SequenceNode sni = tmpi;
541 SequenceNode snj = tmpj;
546 sni = (SequenceNode) sni.left();
552 snj = (SequenceNode) snj.left();
555 tmpi.dist = ((dist / 2) - ih);
556 tmpj.dist = ((dist / 2) - jh);
567 public void findClusterDistance(int i, int j)
569 int noi = ((Cluster) cluster.elementAt(i)).value.length;
570 int noj = ((Cluster) cluster.elementAt(j)).value.length;
572 // New distances from cluster to others
573 float[] newdist = new float[noseqs];
575 for (int l = 0; l < noseqs; l++)
577 if ((l != i) && (l != j))
579 newdist[l] = ((distance[i][l] * noi) + (distance[j][l] * noj))
588 for (int ii = 0; ii < noseqs; ii++)
590 distance[i][ii] = newdist[ii];
591 distance[ii][i] = newdist[ii];
603 public void findClusterNJDistance(int i, int j)
606 // New distances from cluster to others
607 float[] newdist = new float[noseqs];
609 for (int l = 0; l < noseqs; l++)
611 if ((l != i) && (l != j))
613 newdist[l] = ((distance[i][l] + distance[j][l]) - distance[i][j]) / 2;
621 for (int ii = 0; ii < noseqs; ii++)
623 distance[i][ii] = newdist[ii];
624 distance[ii][i] = newdist[ii];
636 * @return DOCUMENT ME!
638 public float findr(int i, int j)
642 for (int k = 0; k < noseqs; k++)
644 if ((k != i) && (k != j) && (done[k] != 1))
646 tmp = tmp + distance[i][k];
652 tmp = tmp / (noClus - 2);
661 * @return DOCUMENT ME!
663 public float findMinNJDistance()
667 for (int i = 0; i < (noseqs - 1); i++)
669 for (int j = i + 1; j < noseqs; j++)
671 if ((done[i] != 1) && (done[j] != 1))
673 float tmp = distance[i][j] - (findr(i, j) + findr(j, i));
692 * @return DOCUMENT ME!
694 public float findMinDistance()
698 for (int i = 0; i < (noseqs - 1); i++)
700 for (int j = i + 1; j < noseqs; j++)
702 if ((done[i] != 1) && (done[j] != 1))
704 if (distance[i][j] < min)
709 min = distance[i][j];
721 * @return DOCUMENT ME!
723 public float[][] findDistances(String[] sequenceString)
725 float[][] distance = new float[noseqs][noseqs];
727 if (pwtype.equals("PID"))
729 for (int i = 0; i < (noseqs - 1); i++)
731 for (int j = i; j < noseqs; j++)
739 distance[i][j] = 100 - Comparison.PID(sequenceString[i],
742 distance[j][i] = distance[i][j];
749 // Pairwise substitution score (with no gap penalties)
750 ScoreMatrix pwmatrix = ResidueProperties.getScoreMatrix(pwtype);
751 if (pwmatrix == null)
753 pwmatrix = ResidueProperties.getScoreMatrix("BLOSUM62");
756 int end = sequenceString[0].length();
757 for (int i = 0; i < (noseqs - 1); i++)
759 for (int j = i; j < noseqs; j++)
763 for (int k = 0; k < end; k++)
767 score += pwmatrix.getPairwiseScore(
768 sequenceString[i].charAt(k),
769 sequenceString[j].charAt(k));
770 } catch (Exception ex)
772 System.err.println("err creating BLOSUM62 tree");
773 ex.printStackTrace();
777 distance[i][j] = (float) score;
779 if (score > maxscore)
786 for (int i = 0; i < (noseqs - 1); i++)
788 for (int j = i; j < noseqs; j++)
790 distance[i][j] = (float) maxscore - distance[i][j];
791 distance[j][i] = distance[i][j];
800 * else if (pwtype.equals("SW")) { float max = -1;
802 * for (int i = 0; i < (noseqs - 1); i++) { for (int j = i; j < noseqs; j++)
803 * { AlignSeq as = new AlignSeq(sequence[i], sequence[j], "pep");
804 * as.calcScoreMatrix(); as.traceAlignment(); as.printAlignment(System.out);
805 * distance[i][j] = (float) as.maxscore;
807 * if (max < distance[i][j]) { max = distance[i][j]; } } }
809 * for (int i = 0; i < (noseqs - 1); i++) { for (int j = i; j < noseqs; j++)
810 * { distance[i][j] = max - distance[i][j]; distance[j][i] = distance[i][j];
818 public void makeLeaves()
820 cluster = new Vector();
822 for (int i = 0; i < noseqs; i++)
824 SequenceNode sn = new SequenceNode();
826 sn.setElement(sequence[i]);
827 sn.setName(sequence[i].getName());
830 int[] value = new int[1];
833 Cluster c = new Cluster(value);
834 cluster.addElement(c);
839 * Search for leaf nodes.
842 * root node to search from
844 * Vector of leaves to add leaf node objects too.
846 * @return Vector of leaf nodes on binary tree
848 public Vector findLeaves(SequenceNode node, Vector leaves)
855 if ((node.left() == null) && (node.right() == null)) // Interior node
858 leaves.addElement(node);
865 * TODO: Identify internal nodes... if (node.isSequenceLabel()) {
866 * leaves.addElement(node); }
868 findLeaves((SequenceNode) node.left(), leaves);
869 findLeaves((SequenceNode) node.right(), leaves);
876 * Find the leaf node with a particular ycount
879 * initial point on tree to search from
881 * value to search for
883 * @return null or the node with ycound=count
885 public Object findLeaf(SequenceNode node, int count)
887 found = _findLeaf(node, count);
893 * #see findLeaf(SequenceNode node, count)
895 public Object _findLeaf(SequenceNode node, int count)
902 if (node.ycount == count)
904 found = node.element();
910 _findLeaf((SequenceNode) node.left(), count);
911 _findLeaf((SequenceNode) node.right(), count);
918 * printNode is mainly for debugging purposes.
923 public void printNode(SequenceNode node)
930 if ((node.left() == null) && (node.right() == null))
933 .println("Leaf = " + ((SequenceI) node.element()).getName());
934 System.out.println("Dist " + ((SequenceNode) node).dist);
935 System.out.println("Boot " + node.getBootstrap());
939 System.out.println("Dist " + ((SequenceNode) node).dist);
940 printNode((SequenceNode) node.left());
941 printNode((SequenceNode) node.right());
951 public void findMaxDist(SequenceNode node)
958 if ((node.left() == null) && (node.right() == null))
960 float dist = ((SequenceNode) node).dist;
962 if (dist > maxDistValue)
964 maxdist = (SequenceNode) node;
970 findMaxDist((SequenceNode) node.left());
971 findMaxDist((SequenceNode) node.right());
978 * @return DOCUMENT ME!
980 public Vector getGroups()
988 * @return DOCUMENT ME!
990 public float getMaxHeight()
1003 public void groupNodes(SequenceNode node, float threshold)
1010 if ((node.height / maxheight) > threshold)
1012 groups.addElement(node);
1016 groupNodes((SequenceNode) node.left(), threshold);
1017 groupNodes((SequenceNode) node.right(), threshold);
1027 * @return DOCUMENT ME!
1029 public float findHeight(SequenceNode node)
1036 if ((node.left() == null) && (node.right() == null))
1038 node.height = ((SequenceNode) node.parent()).height + node.dist;
1040 if (node.height > maxheight)
1051 if (node.parent() != null)
1053 node.height = ((SequenceNode) node.parent()).height + node.dist;
1058 node.height = (float) 0.0;
1061 maxheight = findHeight((SequenceNode) (node.left()));
1062 maxheight = findHeight((SequenceNode) (node.right()));
1071 * @return DOCUMENT ME!
1073 public SequenceNode reRoot()
1075 if (maxdist != null)
1079 float tmpdist = maxdist.dist;
1082 SequenceNode sn = new SequenceNode();
1085 // New right hand of top
1086 SequenceNode snr = (SequenceNode) maxdist.parent();
1087 changeDirection(snr, maxdist);
1088 System.out.println("Printing reversed tree");
1090 snr.dist = tmpdist / 2;
1091 maxdist.dist = tmpdist / 2;
1094 maxdist.setParent(sn);
1097 sn.setLeft(maxdist);
1111 * @return true if original sequence data can be recovered
1113 public boolean hasOriginalSequenceData()
1115 return seqData != null;
1119 * Returns original alignment data used for calculation - or null where not
1122 * @return null or cut'n'pasteable alignment
1124 public String printOriginalSequenceData(char gapChar)
1126 if (seqData == null)
1131 StringBuffer sb = new StringBuffer();
1132 String[] seqdatas = seqData.getSequenceStrings(gapChar);
1133 for (int i = 0; i < seqdatas.length; i++)
1135 sb.append(new jalview.util.Format("%-" + 15 + "s").form(sequence[i]
1137 sb.append(" " + seqdatas[i] + "\n");
1139 return sb.toString();
1148 public void printN(SequenceNode node)
1155 if ((node.left() != null) && (node.right() != null))
1157 printN((SequenceNode) node.left());
1158 printN((SequenceNode) node.right());
1162 System.out.println(" name = "
1163 + ((SequenceI) node.element()).getName());
1166 System.out.println(" dist = " + ((SequenceNode) node).dist + " "
1167 + ((SequenceNode) node).count + " "
1168 + ((SequenceNode) node).height);
1177 public void reCount(SequenceNode node)
1181 // _lylimit = this.node.size();
1185 private long _lycount = 0, _lylimit = 0;
1193 public void _reCount(SequenceNode node)
1195 // if (_lycount<_lylimit)
1197 // System.err.println("Warning: depth of _recount greater than number of nodes.");
1205 if ((node.left() != null) && (node.right() != null))
1208 _reCount((SequenceNode) node.left());
1209 _reCount((SequenceNode) node.right());
1211 SequenceNode l = (SequenceNode) node.left();
1212 SequenceNode r = (SequenceNode) node.right();
1214 ((SequenceNode) node).count = l.count + r.count;
1215 ((SequenceNode) node).ycount = (l.ycount + r.ycount) / 2;
1219 ((SequenceNode) node).count = 1;
1220 ((SequenceNode) node).ycount = ycount++;
1231 public void swapNodes(SequenceNode node)
1238 SequenceNode tmp = (SequenceNode) node.left();
1240 node.setLeft(node.right());
1252 public void changeDirection(SequenceNode node, SequenceNode dir)
1259 if (node.parent() != top)
1261 changeDirection((SequenceNode) node.parent(), node);
1263 SequenceNode tmp = (SequenceNode) node.parent();
1265 if (dir == node.left())
1267 node.setParent(dir);
1270 else if (dir == node.right())
1272 node.setParent(dir);
1278 if (dir == node.left())
1280 node.setParent(node.left());
1282 if (top.left() == node)
1284 node.setRight(top.right());
1288 node.setRight(top.left());
1293 node.setParent(node.right());
1295 if (top.left() == node)
1297 node.setLeft(top.right());
1301 node.setLeft(top.left());
1310 * @return DOCUMENT ME!
1312 public SequenceNode getMaxDist()
1320 * @return DOCUMENT ME!
1322 public SequenceNode getTopNode()
1329 * @return true if tree has real distances
1331 public boolean isHasDistances()
1333 return hasDistances;
1338 * @return true if tree has real bootstrap values
1340 public boolean isHasBootstrap()
1342 return hasBootstrap;
1345 public boolean isHasRootDistance()
1347 return hasRootDistance;
1351 * apply the given transform to all the nodes in the tree.
1353 * @param nodeTransformI
1355 public void applyToNodes(NodeTransformI nodeTransformI)
1357 for (Enumeration nodes = node.elements(); nodes.hasMoreElements(); nodeTransformI
1358 .transform((BinaryNode) nodes.nextElement()))
1367 * @version $Revision$
1374 * Creates a new Cluster object.
1379 public Cluster(int[] value)