2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, 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
272 * @return DOCUMENT ME!
274 public String toString()
276 jalview.io.NewickFile fout = new jalview.io.NewickFile(getTopNode());
278 return fout.print(false, true); // distances only
283 * used when the alignment associated to a tree has changed.
288 public void UpdatePlaceHolders(Vector alignment)
290 Vector leaves = new Vector();
291 findLeaves(top, leaves);
293 int sz = leaves.size();
294 SequenceIdMatcher seqmatcher = null;
299 SequenceNode leaf = (SequenceNode) leaves.elementAt(i++);
301 if (alignment.contains(leaf.element()))
303 leaf.setPlaceholder(false);
307 if (seqmatcher == null)
309 // Only create this the first time we need it
310 SequenceI[] seqs = new SequenceI[alignment.size()];
312 for (int j = 0; j < seqs.length; j++)
314 seqs[j] = (SequenceI) alignment.elementAt(j);
317 seqmatcher = new SequenceIdMatcher(seqs);
320 SequenceI nam = seqmatcher.findIdMatch(leaf.getName());
324 if (!leaf.isPlaceholder())
326 // remapping the node to a new sequenceI - should remove any refs to
328 // TODO - make many sequenceI to one leaf mappings possible!
331 leaf.setPlaceholder(false);
332 leaf.setElement(nam);
336 if (!leaf.isPlaceholder())
338 // Construct a new placeholder sequence object for this leaf
339 leaf.setElement(new Sequence(leaf.getName(),
340 "THISISAPLACEHLDER"));
342 leaf.setPlaceholder(true);
352 public void cluster()
356 if (type.equals("NJ"))
365 Cluster c = joinClusters(mini, minj);
369 cluster.setElementAt(null, minj);
370 cluster.setElementAt(c, mini);
375 boolean onefound = false;
380 for (int i = 0; i < noseqs; i++)
384 if (onefound == false)
396 joinClusters(one, two);
397 top = (SequenceNode) (node.elementAt(one));
412 * @return DOCUMENT ME!
414 public Cluster joinClusters(int i, int j)
416 float dist = distance[i][j];
418 int noi = ((Cluster) cluster.elementAt(i)).value.length;
419 int noj = ((Cluster) cluster.elementAt(j)).value.length;
421 int[] value = new int[noi + noj];
423 for (int ii = 0; ii < noi; ii++)
425 value[ii] = ((Cluster) cluster.elementAt(i)).value[ii];
428 for (int ii = noi; ii < (noi + noj); ii++)
430 value[ii] = ((Cluster) cluster.elementAt(j)).value[ii - noi];
433 Cluster c = new Cluster(value);
438 if (type.equals("NJ"))
440 findClusterNJDistance(i, j);
444 findClusterDistance(i, j);
447 SequenceNode sn = new SequenceNode();
449 sn.setLeft((SequenceNode) (node.elementAt(i)));
450 sn.setRight((SequenceNode) (node.elementAt(j)));
452 SequenceNode tmpi = (SequenceNode) (node.elementAt(i));
453 SequenceNode tmpj = (SequenceNode) (node.elementAt(j));
455 if (type.equals("NJ"))
457 findNewNJDistances(tmpi, tmpj, dist);
461 findNewDistances(tmpi, tmpj, dist);
467 node.setElementAt(sn, i);
482 public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj,
486 tmpi.dist = ((dist + ri) - rj) / 2;
487 tmpj.dist = (dist - tmpi.dist);
510 public void findNewDistances(SequenceNode tmpi, SequenceNode tmpj,
516 SequenceNode sni = tmpi;
517 SequenceNode snj = tmpj;
522 sni = (SequenceNode) sni.left();
528 snj = (SequenceNode) snj.left();
531 tmpi.dist = ((dist / 2) - ih);
532 tmpj.dist = ((dist / 2) - jh);
543 public void findClusterDistance(int i, int j)
545 int noi = ((Cluster) cluster.elementAt(i)).value.length;
546 int noj = ((Cluster) cluster.elementAt(j)).value.length;
548 // New distances from cluster to others
549 float[] newdist = new float[noseqs];
551 for (int l = 0; l < noseqs; l++)
553 if ((l != i) && (l != j))
555 newdist[l] = ((distance[i][l] * noi) + (distance[j][l] * noj))
564 for (int ii = 0; ii < noseqs; ii++)
566 distance[i][ii] = newdist[ii];
567 distance[ii][i] = newdist[ii];
579 public void findClusterNJDistance(int i, int j)
582 // New distances from cluster to others
583 float[] newdist = new float[noseqs];
585 for (int l = 0; l < noseqs; l++)
587 if ((l != i) && (l != j))
589 newdist[l] = ((distance[i][l] + distance[j][l]) - distance[i][j]) / 2;
597 for (int ii = 0; ii < noseqs; ii++)
599 distance[i][ii] = newdist[ii];
600 distance[ii][i] = newdist[ii];
612 * @return DOCUMENT ME!
614 public float findr(int i, int j)
618 for (int k = 0; k < noseqs; k++)
620 if ((k != i) && (k != j) && (done[k] != 1))
622 tmp = tmp + distance[i][k];
628 tmp = tmp / (noClus - 2);
637 * @return DOCUMENT ME!
639 public float findMinNJDistance()
643 for (int i = 0; i < (noseqs - 1); i++)
645 for (int j = i + 1; j < noseqs; j++)
647 if ((done[i] != 1) && (done[j] != 1))
649 float tmp = distance[i][j] - (findr(i, j) + findr(j, i));
668 * @return DOCUMENT ME!
670 public float findMinDistance()
674 for (int i = 0; i < (noseqs - 1); i++)
676 for (int j = i + 1; j < noseqs; j++)
678 if ((done[i] != 1) && (done[j] != 1))
680 if (distance[i][j] < min)
685 min = distance[i][j];
697 * @return DOCUMENT ME!
699 public float[][] findDistances(String[] sequenceString)
701 float[][] distance = new float[noseqs][noseqs];
703 if (pwtype.equals("PID"))
705 for (int i = 0; i < (noseqs - 1); i++)
707 for (int j = i; j < noseqs; j++)
715 distance[i][j] = 100 - Comparison.PID(sequenceString[i],
718 distance[j][i] = distance[i][j];
725 // Pairwise substitution score (with no gap penalties)
726 ScoreMatrix pwmatrix = ResidueProperties.getScoreMatrix(pwtype);
727 if (pwmatrix == null)
729 pwmatrix = ResidueProperties.getScoreMatrix("BLOSUM62");
732 int end = sequenceString[0].length();
733 for (int i = 0; i < (noseqs - 1); i++)
735 for (int j = i; j < noseqs; j++)
739 for (int k = 0; k < end; k++)
743 score += pwmatrix.getPairwiseScore(sequenceString[i]
744 .charAt(k), sequenceString[j].charAt(k));
745 } catch (Exception ex)
747 System.err.println("err creating BLOSUM62 tree");
748 ex.printStackTrace();
752 distance[i][j] = (float) score;
754 if (score > maxscore)
761 for (int i = 0; i < (noseqs - 1); i++)
763 for (int j = i; j < noseqs; j++)
765 distance[i][j] = (float) maxscore - distance[i][j];
766 distance[j][i] = distance[i][j];
775 * else if (pwtype.equals("SW")) { float max = -1;
777 * for (int i = 0; i < (noseqs - 1); i++) { for (int j = i; j < noseqs; j++)
778 * { AlignSeq as = new AlignSeq(sequence[i], sequence[j], "pep");
779 * as.calcScoreMatrix(); as.traceAlignment(); as.printAlignment(System.out);
780 * distance[i][j] = (float) as.maxscore;
782 * if (max < distance[i][j]) { max = distance[i][j]; } } }
784 * for (int i = 0; i < (noseqs - 1); i++) { for (int j = i; j < noseqs; j++)
785 * { distance[i][j] = max - distance[i][j]; distance[j][i] = distance[i][j];
793 public void makeLeaves()
795 cluster = new Vector();
797 for (int i = 0; i < noseqs; i++)
799 SequenceNode sn = new SequenceNode();
801 sn.setElement(sequence[i]);
802 sn.setName(sequence[i].getName());
805 int[] value = new int[1];
808 Cluster c = new Cluster(value);
809 cluster.addElement(c);
814 * Search for leaf nodes.
817 * root node to search from
819 * Vector of leaves to add leaf node objects too.
821 * @return Vector of leaf nodes on binary tree
823 public Vector findLeaves(SequenceNode node, Vector leaves)
830 if ((node.left() == null) && (node.right() == null)) // Interior node
833 leaves.addElement(node);
840 * TODO: Identify internal nodes... if (node.isSequenceLabel()) {
841 * leaves.addElement(node); }
843 findLeaves((SequenceNode) node.left(), leaves);
844 findLeaves((SequenceNode) node.right(), leaves);
851 * Find the leaf node with a particular ycount
854 * initial point on tree to search from
856 * value to search for
858 * @return null or the node with ycound=count
860 public Object findLeaf(SequenceNode node, int count)
862 found = _findLeaf(node, count);
868 * #see findLeaf(SequenceNode node, count)
870 public Object _findLeaf(SequenceNode node, int count)
877 if (node.ycount == count)
879 found = node.element();
885 _findLeaf((SequenceNode) node.left(), count);
886 _findLeaf((SequenceNode) node.right(), count);
893 * printNode is mainly for debugging purposes.
898 public void printNode(SequenceNode node)
905 if ((node.left() == null) && (node.right() == null))
908 .println("Leaf = " + ((SequenceI) node.element()).getName());
909 System.out.println("Dist " + ((SequenceNode) node).dist);
910 System.out.println("Boot " + node.getBootstrap());
914 System.out.println("Dist " + ((SequenceNode) node).dist);
915 printNode((SequenceNode) node.left());
916 printNode((SequenceNode) node.right());
926 public void findMaxDist(SequenceNode node)
933 if ((node.left() == null) && (node.right() == null))
935 float dist = ((SequenceNode) node).dist;
937 if (dist > maxDistValue)
939 maxdist = (SequenceNode) node;
945 findMaxDist((SequenceNode) node.left());
946 findMaxDist((SequenceNode) node.right());
953 * @return DOCUMENT ME!
955 public Vector getGroups()
963 * @return DOCUMENT ME!
965 public float getMaxHeight()
978 public void groupNodes(SequenceNode node, float threshold)
985 if ((node.height / maxheight) > threshold)
987 groups.addElement(node);
991 groupNodes((SequenceNode) node.left(), threshold);
992 groupNodes((SequenceNode) node.right(), threshold);
1002 * @return DOCUMENT ME!
1004 public float findHeight(SequenceNode node)
1011 if ((node.left() == null) && (node.right() == null))
1013 node.height = ((SequenceNode) node.parent()).height + node.dist;
1015 if (node.height > maxheight)
1026 if (node.parent() != null)
1028 node.height = ((SequenceNode) node.parent()).height + node.dist;
1033 node.height = (float) 0.0;
1036 maxheight = findHeight((SequenceNode) (node.left()));
1037 maxheight = findHeight((SequenceNode) (node.right()));
1046 * @return DOCUMENT ME!
1048 public SequenceNode reRoot()
1050 if (maxdist != null)
1054 float tmpdist = maxdist.dist;
1057 SequenceNode sn = new SequenceNode();
1060 // New right hand of top
1061 SequenceNode snr = (SequenceNode) maxdist.parent();
1062 changeDirection(snr, maxdist);
1063 System.out.println("Printing reversed tree");
1065 snr.dist = tmpdist / 2;
1066 maxdist.dist = tmpdist / 2;
1069 maxdist.setParent(sn);
1072 sn.setLeft(maxdist);
1086 * @return true if original sequence data can be recovered
1088 public boolean hasOriginalSequenceData()
1090 return seqData != null;
1094 * Returns original alignment data used for calculation - or null where not
1097 * @return null or cut'n'pasteable alignment
1099 public String printOriginalSequenceData(char gapChar)
1101 if (seqData == null)
1106 StringBuffer sb = new StringBuffer();
1107 String[] seqdatas = seqData.getSequenceStrings(gapChar);
1108 for (int i = 0; i < seqdatas.length; i++)
1110 sb.append(new jalview.util.Format("%-" + 15 + "s").form(sequence[i]
1112 sb.append(" " + seqdatas[i] + "\n");
1114 return sb.toString();
1123 public void printN(SequenceNode node)
1130 if ((node.left() != null) && (node.right() != null))
1132 printN((SequenceNode) node.left());
1133 printN((SequenceNode) node.right());
1137 System.out.println(" name = "
1138 + ((SequenceI) node.element()).getName());
1141 System.out.println(" dist = " + ((SequenceNode) node).dist + " "
1142 + ((SequenceNode) node).count + " "
1143 + ((SequenceNode) node).height);
1152 public void reCount(SequenceNode node)
1156 // _lylimit = this.node.size();
1160 private long _lycount = 0, _lylimit = 0;
1168 public void _reCount(SequenceNode node)
1170 // if (_lycount<_lylimit)
1172 // System.err.println("Warning: depth of _recount greater than number of nodes.");
1180 if ((node.left() != null) && (node.right() != null))
1183 _reCount((SequenceNode) node.left());
1184 _reCount((SequenceNode) node.right());
1186 SequenceNode l = (SequenceNode) node.left();
1187 SequenceNode r = (SequenceNode) node.right();
1189 ((SequenceNode) node).count = l.count + r.count;
1190 ((SequenceNode) node).ycount = (l.ycount + r.ycount) / 2;
1194 ((SequenceNode) node).count = 1;
1195 ((SequenceNode) node).ycount = ycount++;
1206 public void swapNodes(SequenceNode node)
1213 SequenceNode tmp = (SequenceNode) node.left();
1215 node.setLeft(node.right());
1227 public void changeDirection(SequenceNode node, SequenceNode dir)
1234 if (node.parent() != top)
1236 changeDirection((SequenceNode) node.parent(), node);
1238 SequenceNode tmp = (SequenceNode) node.parent();
1240 if (dir == node.left())
1242 node.setParent(dir);
1245 else if (dir == node.right())
1247 node.setParent(dir);
1253 if (dir == node.left())
1255 node.setParent(node.left());
1257 if (top.left() == node)
1259 node.setRight(top.right());
1263 node.setRight(top.left());
1268 node.setParent(node.right());
1270 if (top.left() == node)
1272 node.setLeft(top.right());
1276 node.setLeft(top.left());
1285 * @return DOCUMENT ME!
1287 public SequenceNode getMaxDist()
1295 * @return DOCUMENT ME!
1297 public SequenceNode getTopNode()
1304 * @return true if tree has real distances
1306 public boolean isHasDistances()
1308 return hasDistances;
1313 * @return true if tree has real bootstrap values
1315 public boolean isHasBootstrap()
1317 return hasBootstrap;
1320 public boolean isHasRootDistance()
1322 return hasRootDistance;
1326 * apply the given transform to all the nodes in the tree.
1328 * @param nodeTransformI
1330 public void applyToNodes(NodeTransformI nodeTransformI)
1332 for (Enumeration nodes = node.elements(); nodes.hasMoreElements(); nodeTransformI
1333 .transform((BinaryNode) nodes.nextElement()))
1342 * @version $Revision$
1349 * Creates a new Cluster object.
1354 public Cluster(int[] value)