2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
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);
349 * rename any nodes according to their associated sequence.
350 * This will modify the tree's metadata! (ie the original NewickFile or newly generated BinaryTree's label data)
352 public void renameAssociatedNodes() {
353 applyToNodes(new NodeTransformI() {
356 public void transform(BinaryNode node)
358 Object el = node.element();
359 if (el!=null && el instanceof SequenceI)
361 node.setName(((SequenceI)el).getName());
369 public void cluster()
373 if (type.equals("NJ"))
382 Cluster c = joinClusters(mini, minj);
386 cluster.setElementAt(null, minj);
387 cluster.setElementAt(c, mini);
392 boolean onefound = false;
397 for (int i = 0; i < noseqs; i++)
401 if (onefound == false)
413 joinClusters(one, two);
414 top = (SequenceNode) (node.elementAt(one));
429 * @return DOCUMENT ME!
431 public Cluster joinClusters(int i, int j)
433 float dist = distance[i][j];
435 int noi = ((Cluster) cluster.elementAt(i)).value.length;
436 int noj = ((Cluster) cluster.elementAt(j)).value.length;
438 int[] value = new int[noi + noj];
440 for (int ii = 0; ii < noi; ii++)
442 value[ii] = ((Cluster) cluster.elementAt(i)).value[ii];
445 for (int ii = noi; ii < (noi + noj); ii++)
447 value[ii] = ((Cluster) cluster.elementAt(j)).value[ii - noi];
450 Cluster c = new Cluster(value);
455 if (type.equals("NJ"))
457 findClusterNJDistance(i, j);
461 findClusterDistance(i, j);
464 SequenceNode sn = new SequenceNode();
466 sn.setLeft((SequenceNode) (node.elementAt(i)));
467 sn.setRight((SequenceNode) (node.elementAt(j)));
469 SequenceNode tmpi = (SequenceNode) (node.elementAt(i));
470 SequenceNode tmpj = (SequenceNode) (node.elementAt(j));
472 if (type.equals("NJ"))
474 findNewNJDistances(tmpi, tmpj, dist);
478 findNewDistances(tmpi, tmpj, dist);
484 node.setElementAt(sn, i);
499 public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj,
503 tmpi.dist = ((dist + ri) - rj) / 2;
504 tmpj.dist = (dist - tmpi.dist);
527 public void findNewDistances(SequenceNode tmpi, SequenceNode tmpj,
533 SequenceNode sni = tmpi;
534 SequenceNode snj = tmpj;
539 sni = (SequenceNode) sni.left();
545 snj = (SequenceNode) snj.left();
548 tmpi.dist = ((dist / 2) - ih);
549 tmpj.dist = ((dist / 2) - jh);
560 public void findClusterDistance(int i, int j)
562 int noi = ((Cluster) cluster.elementAt(i)).value.length;
563 int noj = ((Cluster) cluster.elementAt(j)).value.length;
565 // New distances from cluster to others
566 float[] newdist = new float[noseqs];
568 for (int l = 0; l < noseqs; l++)
570 if ((l != i) && (l != j))
572 newdist[l] = ((distance[i][l] * noi) + (distance[j][l] * noj))
581 for (int ii = 0; ii < noseqs; ii++)
583 distance[i][ii] = newdist[ii];
584 distance[ii][i] = newdist[ii];
596 public void findClusterNJDistance(int i, int j)
599 // New distances from cluster to others
600 float[] newdist = new float[noseqs];
602 for (int l = 0; l < noseqs; l++)
604 if ((l != i) && (l != j))
606 newdist[l] = ((distance[i][l] + distance[j][l]) - distance[i][j]) / 2;
614 for (int ii = 0; ii < noseqs; ii++)
616 distance[i][ii] = newdist[ii];
617 distance[ii][i] = newdist[ii];
629 * @return DOCUMENT ME!
631 public float findr(int i, int j)
635 for (int k = 0; k < noseqs; k++)
637 if ((k != i) && (k != j) && (done[k] != 1))
639 tmp = tmp + distance[i][k];
645 tmp = tmp / (noClus - 2);
654 * @return DOCUMENT ME!
656 public float findMinNJDistance()
660 for (int i = 0; i < (noseqs - 1); i++)
662 for (int j = i + 1; j < noseqs; j++)
664 if ((done[i] != 1) && (done[j] != 1))
666 float tmp = distance[i][j] - (findr(i, j) + findr(j, i));
685 * @return DOCUMENT ME!
687 public float findMinDistance()
691 for (int i = 0; i < (noseqs - 1); i++)
693 for (int j = i + 1; j < noseqs; j++)
695 if ((done[i] != 1) && (done[j] != 1))
697 if (distance[i][j] < min)
702 min = distance[i][j];
714 * @return DOCUMENT ME!
716 public float[][] findDistances(String[] sequenceString)
718 float[][] distance = new float[noseqs][noseqs];
720 if (pwtype.equals("PID"))
722 for (int i = 0; i < (noseqs - 1); i++)
724 for (int j = i; j < noseqs; j++)
732 distance[i][j] = 100 - Comparison.PID(sequenceString[i],
735 distance[j][i] = distance[i][j];
742 // Pairwise substitution score (with no gap penalties)
743 ScoreMatrix pwmatrix = ResidueProperties.getScoreMatrix(pwtype);
744 if (pwmatrix == null)
746 pwmatrix = ResidueProperties.getScoreMatrix("BLOSUM62");
749 int end = sequenceString[0].length();
750 for (int i = 0; i < (noseqs - 1); i++)
752 for (int j = i; j < noseqs; j++)
756 for (int k = 0; k < end; k++)
760 score += pwmatrix.getPairwiseScore(
761 sequenceString[i].charAt(k),
762 sequenceString[j].charAt(k));
763 } catch (Exception ex)
765 System.err.println("err creating BLOSUM62 tree");
766 ex.printStackTrace();
770 distance[i][j] = (float) score;
772 if (score > maxscore)
779 for (int i = 0; i < (noseqs - 1); i++)
781 for (int j = i; j < noseqs; j++)
783 distance[i][j] = (float) maxscore - distance[i][j];
784 distance[j][i] = distance[i][j];
793 * else if (pwtype.equals("SW")) { float max = -1;
795 * for (int i = 0; i < (noseqs - 1); i++) { for (int j = i; j < noseqs; j++)
796 * { AlignSeq as = new AlignSeq(sequence[i], sequence[j], "pep");
797 * as.calcScoreMatrix(); as.traceAlignment(); as.printAlignment(System.out);
798 * distance[i][j] = (float) as.maxscore;
800 * if (max < distance[i][j]) { max = distance[i][j]; } } }
802 * for (int i = 0; i < (noseqs - 1); i++) { for (int j = i; j < noseqs; j++)
803 * { distance[i][j] = max - distance[i][j]; distance[j][i] = distance[i][j];
811 public void makeLeaves()
813 cluster = new Vector();
815 for (int i = 0; i < noseqs; i++)
817 SequenceNode sn = new SequenceNode();
819 sn.setElement(sequence[i]);
820 sn.setName(sequence[i].getName());
823 int[] value = new int[1];
826 Cluster c = new Cluster(value);
827 cluster.addElement(c);
832 * Search for leaf nodes.
835 * root node to search from
837 * Vector of leaves to add leaf node objects too.
839 * @return Vector of leaf nodes on binary tree
841 public Vector findLeaves(SequenceNode node, Vector leaves)
848 if ((node.left() == null) && (node.right() == null)) // Interior node
851 leaves.addElement(node);
858 * TODO: Identify internal nodes... if (node.isSequenceLabel()) {
859 * leaves.addElement(node); }
861 findLeaves((SequenceNode) node.left(), leaves);
862 findLeaves((SequenceNode) node.right(), leaves);
869 * Find the leaf node with a particular ycount
872 * initial point on tree to search from
874 * value to search for
876 * @return null or the node with ycound=count
878 public Object findLeaf(SequenceNode node, int count)
880 found = _findLeaf(node, count);
886 * #see findLeaf(SequenceNode node, count)
888 public Object _findLeaf(SequenceNode node, int count)
895 if (node.ycount == count)
897 found = node.element();
903 _findLeaf((SequenceNode) node.left(), count);
904 _findLeaf((SequenceNode) node.right(), count);
911 * printNode is mainly for debugging purposes.
916 public void printNode(SequenceNode node)
923 if ((node.left() == null) && (node.right() == null))
926 .println("Leaf = " + ((SequenceI) node.element()).getName());
927 System.out.println("Dist " + ((SequenceNode) node).dist);
928 System.out.println("Boot " + node.getBootstrap());
932 System.out.println("Dist " + ((SequenceNode) node).dist);
933 printNode((SequenceNode) node.left());
934 printNode((SequenceNode) node.right());
944 public void findMaxDist(SequenceNode node)
951 if ((node.left() == null) && (node.right() == null))
953 float dist = ((SequenceNode) node).dist;
955 if (dist > maxDistValue)
957 maxdist = (SequenceNode) node;
963 findMaxDist((SequenceNode) node.left());
964 findMaxDist((SequenceNode) node.right());
971 * @return DOCUMENT ME!
973 public Vector getGroups()
981 * @return DOCUMENT ME!
983 public float getMaxHeight()
996 public void groupNodes(SequenceNode node, float threshold)
1003 if ((node.height / maxheight) > threshold)
1005 groups.addElement(node);
1009 groupNodes((SequenceNode) node.left(), threshold);
1010 groupNodes((SequenceNode) node.right(), threshold);
1020 * @return DOCUMENT ME!
1022 public float findHeight(SequenceNode node)
1029 if ((node.left() == null) && (node.right() == null))
1031 node.height = ((SequenceNode) node.parent()).height + node.dist;
1033 if (node.height > maxheight)
1044 if (node.parent() != null)
1046 node.height = ((SequenceNode) node.parent()).height + node.dist;
1051 node.height = (float) 0.0;
1054 maxheight = findHeight((SequenceNode) (node.left()));
1055 maxheight = findHeight((SequenceNode) (node.right()));
1064 * @return DOCUMENT ME!
1066 public SequenceNode reRoot()
1068 if (maxdist != null)
1072 float tmpdist = maxdist.dist;
1075 SequenceNode sn = new SequenceNode();
1078 // New right hand of top
1079 SequenceNode snr = (SequenceNode) maxdist.parent();
1080 changeDirection(snr, maxdist);
1081 System.out.println("Printing reversed tree");
1083 snr.dist = tmpdist / 2;
1084 maxdist.dist = tmpdist / 2;
1087 maxdist.setParent(sn);
1090 sn.setLeft(maxdist);
1104 * @return true if original sequence data can be recovered
1106 public boolean hasOriginalSequenceData()
1108 return seqData != null;
1112 * Returns original alignment data used for calculation - or null where not
1115 * @return null or cut'n'pasteable alignment
1117 public String printOriginalSequenceData(char gapChar)
1119 if (seqData == null)
1124 StringBuffer sb = new StringBuffer();
1125 String[] seqdatas = seqData.getSequenceStrings(gapChar);
1126 for (int i = 0; i < seqdatas.length; i++)
1128 sb.append(new jalview.util.Format("%-" + 15 + "s").form(sequence[i]
1130 sb.append(" " + seqdatas[i] + "\n");
1132 return sb.toString();
1141 public void printN(SequenceNode node)
1148 if ((node.left() != null) && (node.right() != null))
1150 printN((SequenceNode) node.left());
1151 printN((SequenceNode) node.right());
1155 System.out.println(" name = "
1156 + ((SequenceI) node.element()).getName());
1159 System.out.println(" dist = " + ((SequenceNode) node).dist + " "
1160 + ((SequenceNode) node).count + " "
1161 + ((SequenceNode) node).height);
1170 public void reCount(SequenceNode node)
1174 // _lylimit = this.node.size();
1178 private long _lycount = 0, _lylimit = 0;
1186 public void _reCount(SequenceNode node)
1188 // if (_lycount<_lylimit)
1190 // System.err.println("Warning: depth of _recount greater than number of nodes.");
1198 if ((node.left() != null) && (node.right() != null))
1201 _reCount((SequenceNode) node.left());
1202 _reCount((SequenceNode) node.right());
1204 SequenceNode l = (SequenceNode) node.left();
1205 SequenceNode r = (SequenceNode) node.right();
1207 ((SequenceNode) node).count = l.count + r.count;
1208 ((SequenceNode) node).ycount = (l.ycount + r.ycount) / 2;
1212 ((SequenceNode) node).count = 1;
1213 ((SequenceNode) node).ycount = ycount++;
1224 public void swapNodes(SequenceNode node)
1231 SequenceNode tmp = (SequenceNode) node.left();
1233 node.setLeft(node.right());
1245 public void changeDirection(SequenceNode node, SequenceNode dir)
1252 if (node.parent() != top)
1254 changeDirection((SequenceNode) node.parent(), node);
1256 SequenceNode tmp = (SequenceNode) node.parent();
1258 if (dir == node.left())
1260 node.setParent(dir);
1263 else if (dir == node.right())
1265 node.setParent(dir);
1271 if (dir == node.left())
1273 node.setParent(node.left());
1275 if (top.left() == node)
1277 node.setRight(top.right());
1281 node.setRight(top.left());
1286 node.setParent(node.right());
1288 if (top.left() == node)
1290 node.setLeft(top.right());
1294 node.setLeft(top.left());
1303 * @return DOCUMENT ME!
1305 public SequenceNode getMaxDist()
1313 * @return DOCUMENT ME!
1315 public SequenceNode getTopNode()
1322 * @return true if tree has real distances
1324 public boolean isHasDistances()
1326 return hasDistances;
1331 * @return true if tree has real bootstrap values
1333 public boolean isHasBootstrap()
1335 return hasBootstrap;
1338 public boolean isHasRootDistance()
1340 return hasRootDistance;
1344 * apply the given transform to all the nodes in the tree.
1346 * @param nodeTransformI
1348 public void applyToNodes(NodeTransformI nodeTransformI)
1350 for (Enumeration nodes = node.elements(); nodes.hasMoreElements(); nodeTransformI
1351 .transform((BinaryNode) nodes.nextElement()))
1360 * @version $Revision$
1367 * Creates a new Cluster object.
1372 public Cluster(int[] value)