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.api.analysis.ScoreModelI;
24 import jalview.datamodel.AlignmentView;
25 import jalview.datamodel.BinaryNode;
26 import jalview.datamodel.CigarArray;
27 import jalview.datamodel.NodeTransformI;
28 import jalview.datamodel.SeqCigar;
29 import jalview.datamodel.Sequence;
30 import jalview.datamodel.SequenceI;
31 import jalview.datamodel.SequenceNode;
32 import jalview.io.NewickFile;
33 import jalview.schemes.ResidueProperties;
34 import jalview.util.Format;
36 import java.util.Enumeration;
37 import java.util.List;
38 import java.util.Vector;
52 // SequenceData is a string representation of what the user
53 // sees. The display may contain hidden columns.
54 public AlignmentView seqData = null;
72 Vector groups = new Vector();
94 boolean hasDistances = true; // normal case for jalview trees
96 boolean hasBootstrap = false; // normal case for jalview trees
98 private boolean hasRootDistance = true;
101 * Create a new NJTree object with leaves associated with sequences in seqs,
102 * and original alignment data represented by Cigar strings.
111 public NJTree(SequenceI[] seqs, AlignmentView odata, NewickFile treefile)
113 this(seqs, treefile);
119 * sequenceString = new String[odata.length]; char gapChar =
120 * Comparison.GapChars.charAt(0); for (int i = 0; i <
121 * odata.length; i++) { SequenceI oseq_aligned = odata[i].getSeq(gapChar);
122 * sequenceString[i] = oseq_aligned.getSequence(); }
127 * Creates a new NJTree object from a tree from an external source
130 * SequenceI which should be associated with leafs of treefile
134 public NJTree(SequenceI[] seqs, NewickFile treefile)
136 this.sequence = seqs;
137 top = treefile.getTree();
140 * There is no dependent alignment to be recovered from an imported tree.
142 * if (sequenceString == null) { sequenceString = new String[seqs.length];
143 * for (int i = 0; i < seqs.length; i++) { sequenceString[i] =
144 * seqs[i].getSequence(); } }
147 hasDistances = treefile.HasDistances();
148 hasBootstrap = treefile.HasBootstrap();
149 hasRootDistance = treefile.HasRootDistance();
151 maxheight = findHeight(top);
153 SequenceIdMatcher algnIds = new SequenceIdMatcher(seqs);
155 Vector leaves = new Vector();
156 findLeaves(top, leaves);
159 int namesleft = seqs.length;
164 Vector one2many = new Vector();
165 int countOne2Many = 0;
166 while (i < leaves.size())
168 j = (SequenceNode) leaves.elementAt(i++);
169 realnam = j.getName();
174 nam = algnIds.findIdMatch(realnam);
180 if (one2many.contains(nam))
183 // if (Cache.log.isDebugEnabled())
184 // Cache.log.debug("One 2 many relationship for
189 one2many.addElement(nam);
195 j.setElement(new Sequence(realnam, "THISISAPLACEHLDER"));
196 j.setPlaceholder(true);
199 // if (Cache.log.isDebugEnabled() && countOne2Many>0) {
200 // Cache.log.debug("There were "+countOne2Many+" alignment
201 // sequence ids (out of "+one2many.size()+" unique ids) linked to two or
208 * Creates a new NJTree object.
221 public NJTree(SequenceI[] sequence, AlignmentView seqData, String type,
222 String pwtype, ScoreModelI sm, int start, int end)
224 this.sequence = sequence;
225 this.node = new Vector();
227 this.pwtype = pwtype;
230 this.seqData = seqData;
234 SeqCigar[] seqs = new SeqCigar[sequence.length];
235 for (int i = 0; i < sequence.length; i++)
237 seqs[i] = new SeqCigar(sequence[i], start, end);
239 CigarArray sdata = new CigarArray(seqs);
240 sdata.addOperation(CigarArray.M, end - start + 1);
241 this.seqData = new AlignmentView(sdata, start);
243 // System.err.println("Made seqData");// dbg
244 if (!(type.equals("NJ")))
249 if (sm == null && !(pwtype.equals("PID")))
251 if (ResidueProperties.getScoreMatrix(pwtype) == null)
259 done = new int[sequence.length];
261 while ((i < sequence.length) && (sequence[i] != null))
269 distance = findDistances(sm);
270 // System.err.println("Made distances");// dbg
272 // System.err.println("Made leaves");// dbg
274 noClus = cluster.size();
277 // System.err.println("Made clusters");// dbg
282 * Generate a string representation of the Tree
284 * @return Newick File with all tree data available
286 public String toString()
288 NewickFile fout = new NewickFile(getTopNode());
290 return fout.print(isHasBootstrap(), isHasDistances(),
291 isHasRootDistance()); // output all data available for tree
296 * used when the alignment associated to a tree has changed.
299 * Sequence set to be associated with tree nodes
301 public void UpdatePlaceHolders(List<SequenceI> list)
303 Vector leaves = new Vector();
304 findLeaves(top, leaves);
306 int sz = leaves.size();
307 SequenceIdMatcher seqmatcher = null;
312 SequenceNode leaf = (SequenceNode) leaves.elementAt(i++);
314 if (list.contains(leaf.element()))
316 leaf.setPlaceholder(false);
320 if (seqmatcher == null)
322 // Only create this the first time we need it
323 SequenceI[] seqs = new SequenceI[list.size()];
325 for (int j = 0; j < seqs.length; j++)
327 seqs[j] = list.get(j);
330 seqmatcher = new SequenceIdMatcher(seqs);
333 SequenceI nam = seqmatcher.findIdMatch(leaf.getName());
337 if (!leaf.isPlaceholder())
339 // remapping the node to a new sequenceI - should remove any refs to
341 // TODO - make many sequenceI to one leaf mappings possible!
344 leaf.setPlaceholder(false);
345 leaf.setElement(nam);
349 if (!leaf.isPlaceholder())
351 // Construct a new placeholder sequence object for this leaf
352 leaf.setElement(new Sequence(leaf.getName(),
353 "THISISAPLACEHLDER"));
355 leaf.setPlaceholder(true);
363 * rename any nodes according to their associated sequence. This will modify
364 * the tree's metadata! (ie the original NewickFile or newly generated
365 * BinaryTree's label data)
367 public void renameAssociatedNodes()
369 applyToNodes(new NodeTransformI()
373 public void transform(BinaryNode node)
375 Object el = node.element();
376 if (el != null && el instanceof SequenceI)
378 node.setName(((SequenceI) el).getName());
387 public void cluster()
391 if (type.equals("NJ"))
400 Cluster c = joinClusters(mini, minj);
404 cluster.setElementAt(null, minj);
405 cluster.setElementAt(c, mini);
410 boolean onefound = false;
415 for (int i = 0; i < noseqs; i++)
419 if (onefound == false)
431 joinClusters(one, two);
432 top = (SequenceNode) (node.elementAt(one));
447 * @return DOCUMENT ME!
449 public Cluster joinClusters(int i, int j)
451 float dist = distance[i][j];
453 int noi = ((Cluster) cluster.elementAt(i)).value.length;
454 int noj = ((Cluster) cluster.elementAt(j)).value.length;
456 int[] value = new int[noi + noj];
458 for (int ii = 0; ii < noi; ii++)
460 value[ii] = ((Cluster) cluster.elementAt(i)).value[ii];
463 for (int ii = noi; ii < (noi + noj); ii++)
465 value[ii] = ((Cluster) cluster.elementAt(j)).value[ii - noi];
468 Cluster c = new Cluster(value);
473 if (type.equals("NJ"))
475 findClusterNJDistance(i, j);
479 findClusterDistance(i, j);
482 SequenceNode sn = new SequenceNode();
484 sn.setLeft((SequenceNode) (node.elementAt(i)));
485 sn.setRight((SequenceNode) (node.elementAt(j)));
487 SequenceNode tmpi = (SequenceNode) (node.elementAt(i));
488 SequenceNode tmpj = (SequenceNode) (node.elementAt(j));
490 if (type.equals("NJ"))
492 findNewNJDistances(tmpi, tmpj, dist);
496 findNewDistances(tmpi, tmpj, dist);
502 node.setElementAt(sn, i);
517 public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj,
521 tmpi.dist = ((dist + ri) - rj) / 2;
522 tmpj.dist = (dist - tmpi.dist);
545 public void findNewDistances(SequenceNode tmpi, SequenceNode tmpj,
551 SequenceNode sni = tmpi;
552 SequenceNode snj = tmpj;
557 sni = (SequenceNode) sni.left();
563 snj = (SequenceNode) snj.left();
566 tmpi.dist = ((dist / 2) - ih);
567 tmpj.dist = ((dist / 2) - jh);
578 public void findClusterDistance(int i, int j)
580 int noi = ((Cluster) cluster.elementAt(i)).value.length;
581 int noj = ((Cluster) cluster.elementAt(j)).value.length;
583 // New distances from cluster to others
584 float[] newdist = new float[noseqs];
586 for (int l = 0; l < noseqs; l++)
588 if ((l != i) && (l != j))
590 newdist[l] = ((distance[i][l] * noi) + (distance[j][l] * noj))
599 for (int ii = 0; ii < noseqs; ii++)
601 distance[i][ii] = newdist[ii];
602 distance[ii][i] = newdist[ii];
614 public void findClusterNJDistance(int i, int j)
617 // New distances from cluster to others
618 float[] newdist = new float[noseqs];
620 for (int l = 0; l < noseqs; l++)
622 if ((l != i) && (l != j))
624 newdist[l] = ((distance[i][l] + distance[j][l]) - distance[i][j]) / 2;
632 for (int ii = 0; ii < noseqs; ii++)
634 distance[i][ii] = newdist[ii];
635 distance[ii][i] = newdist[ii];
647 * @return DOCUMENT ME!
649 public float findr(int i, int j)
653 for (int k = 0; k < noseqs; k++)
655 if ((k != i) && (k != j) && (done[k] != 1))
657 tmp = tmp + distance[i][k];
663 tmp = tmp / (noClus - 2);
672 * @return DOCUMENT ME!
674 public float findMinNJDistance()
678 for (int i = 0; i < (noseqs - 1); i++)
680 for (int j = i + 1; j < noseqs; j++)
682 if ((done[i] != 1) && (done[j] != 1))
684 float tmp = distance[i][j] - (findr(i, j) + findr(j, i));
703 * @return DOCUMENT ME!
705 public float findMinDistance()
709 for (int i = 0; i < (noseqs - 1); i++)
711 for (int j = i + 1; j < noseqs; j++)
713 if ((done[i] != 1) && (done[j] != 1))
715 if (distance[i][j] < min)
720 min = distance[i][j];
730 * Calculate a distance matrix given the sequence input data and score model
732 * @return similarity matrix used to compute tree
734 public float[][] findDistances(ScoreModelI _pwmatrix)
737 float[][] distance = new float[noseqs][noseqs];
738 if (_pwmatrix == null)
740 // Resolve substitution model
741 _pwmatrix = ResidueProperties.getScoreModel(pwtype);
742 if (_pwmatrix == null)
744 _pwmatrix = ResidueProperties.getScoreMatrix("BLOSUM62");
747 distance = _pwmatrix.findDistances(seqData);
755 public void makeLeaves()
757 cluster = new Vector();
759 for (int i = 0; i < noseqs; i++)
761 SequenceNode sn = new SequenceNode();
763 sn.setElement(sequence[i]);
764 sn.setName(sequence[i].getName());
767 int[] value = new int[1];
770 Cluster c = new Cluster(value);
771 cluster.addElement(c);
776 * Search for leaf nodes.
779 * root node to search from
781 * Vector of leaves to add leaf node objects too.
783 * @return Vector of leaf nodes on binary tree
785 public Vector findLeaves(SequenceNode node, Vector leaves)
792 if ((node.left() == null) && (node.right() == null)) // Interior node
795 leaves.addElement(node);
802 * TODO: Identify internal nodes... if (node.isSequenceLabel()) {
803 * leaves.addElement(node); }
805 findLeaves((SequenceNode) node.left(), leaves);
806 findLeaves((SequenceNode) node.right(), leaves);
813 * Find the leaf node with a particular ycount
816 * initial point on tree to search from
818 * value to search for
820 * @return null or the node with ycound=count
822 public Object findLeaf(SequenceNode node, int count)
824 found = _findLeaf(node, count);
830 * #see findLeaf(SequenceNode node, count)
832 public Object _findLeaf(SequenceNode node, int count)
839 if (node.ycount == count)
841 found = node.element();
847 _findLeaf((SequenceNode) node.left(), count);
848 _findLeaf((SequenceNode) node.right(), count);
855 * printNode is mainly for debugging purposes.
860 public void printNode(SequenceNode node)
867 if ((node.left() == null) && (node.right() == null))
870 .println("Leaf = " + ((SequenceI) node.element()).getName());
871 System.out.println("Dist " + node.dist);
872 System.out.println("Boot " + node.getBootstrap());
876 System.out.println("Dist " + node.dist);
877 printNode((SequenceNode) node.left());
878 printNode((SequenceNode) node.right());
888 public void findMaxDist(SequenceNode node)
895 if ((node.left() == null) && (node.right() == null))
897 float dist = node.dist;
899 if (dist > maxDistValue)
907 findMaxDist((SequenceNode) node.left());
908 findMaxDist((SequenceNode) node.right());
915 * @return DOCUMENT ME!
917 public Vector getGroups()
925 * @return DOCUMENT ME!
927 public float getMaxHeight()
940 public void groupNodes(SequenceNode node, float threshold)
947 if ((node.height / maxheight) > threshold)
949 groups.addElement(node);
953 groupNodes((SequenceNode) node.left(), threshold);
954 groupNodes((SequenceNode) node.right(), threshold);
964 * @return DOCUMENT ME!
966 public float findHeight(SequenceNode node)
973 if ((node.left() == null) && (node.right() == null))
975 node.height = ((SequenceNode) node.parent()).height + node.dist;
977 if (node.height > maxheight)
988 if (node.parent() != null)
990 node.height = ((SequenceNode) node.parent()).height + node.dist;
995 node.height = (float) 0.0;
998 maxheight = findHeight((SequenceNode) (node.left()));
999 maxheight = findHeight((SequenceNode) (node.right()));
1008 * @return DOCUMENT ME!
1010 public SequenceNode reRoot()
1012 if (maxdist != null)
1016 float tmpdist = maxdist.dist;
1019 SequenceNode sn = new SequenceNode();
1022 // New right hand of top
1023 SequenceNode snr = (SequenceNode) maxdist.parent();
1024 changeDirection(snr, maxdist);
1025 System.out.println("Printing reversed tree");
1027 snr.dist = tmpdist / 2;
1028 maxdist.dist = tmpdist / 2;
1031 maxdist.setParent(sn);
1034 sn.setLeft(maxdist);
1048 * @return true if original sequence data can be recovered
1050 public boolean hasOriginalSequenceData()
1052 return seqData != null;
1056 * Returns original alignment data used for calculation - or null where not
1059 * @return null or cut'n'pasteable alignment
1061 public String printOriginalSequenceData(char gapChar)
1063 if (seqData == null)
1068 StringBuffer sb = new StringBuffer();
1069 String[] seqdatas = seqData.getSequenceStrings(gapChar);
1070 for (int i = 0; i < seqdatas.length; i++)
1072 sb.append(new Format("%-" + 15 + "s").form(sequence[i].getName()));
1073 sb.append(" " + seqdatas[i] + "\n");
1075 return sb.toString();
1084 public void printN(SequenceNode node)
1091 if ((node.left() != null) && (node.right() != null))
1093 printN((SequenceNode) node.left());
1094 printN((SequenceNode) node.right());
1098 System.out.println(" name = "
1099 + ((SequenceI) node.element()).getName());
1102 System.out.println(" dist = " + node.dist + " "
1113 public void reCount(SequenceNode node)
1117 // _lylimit = this.node.size();
1121 private long _lycount = 0, _lylimit = 0;
1129 public void _reCount(SequenceNode node)
1131 // if (_lycount<_lylimit)
1133 // System.err.println("Warning: depth of _recount greater than number of nodes.");
1141 if ((node.left() != null) && (node.right() != null))
1144 _reCount((SequenceNode) node.left());
1145 _reCount((SequenceNode) node.right());
1147 SequenceNode l = (SequenceNode) node.left();
1148 SequenceNode r = (SequenceNode) node.right();
1150 node.count = l.count + r.count;
1151 node.ycount = (l.ycount + r.ycount) / 2;
1156 node.ycount = ycount++;
1167 public void swapNodes(SequenceNode node)
1174 SequenceNode tmp = (SequenceNode) node.left();
1176 node.setLeft(node.right());
1188 public void changeDirection(SequenceNode node, SequenceNode dir)
1195 if (node.parent() != top)
1197 changeDirection((SequenceNode) node.parent(), node);
1199 SequenceNode tmp = (SequenceNode) node.parent();
1201 if (dir == node.left())
1203 node.setParent(dir);
1206 else if (dir == node.right())
1208 node.setParent(dir);
1214 if (dir == node.left())
1216 node.setParent(node.left());
1218 if (top.left() == node)
1220 node.setRight(top.right());
1224 node.setRight(top.left());
1229 node.setParent(node.right());
1231 if (top.left() == node)
1233 node.setLeft(top.right());
1237 node.setLeft(top.left());
1246 * @return DOCUMENT ME!
1248 public SequenceNode getMaxDist()
1256 * @return DOCUMENT ME!
1258 public SequenceNode getTopNode()
1265 * @return true if tree has real distances
1267 public boolean isHasDistances()
1269 return hasDistances;
1274 * @return true if tree has real bootstrap values
1276 public boolean isHasBootstrap()
1278 return hasBootstrap;
1281 public boolean isHasRootDistance()
1283 return hasRootDistance;
1287 * apply the given transform to all the nodes in the tree.
1289 * @param nodeTransformI
1291 public void applyToNodes(NodeTransformI nodeTransformI)
1293 for (Enumeration nodes = node.elements(); nodes.hasMoreElements(); nodeTransformI
1294 .transform((BinaryNode) nodes.nextElement()))
1305 * @version $Revision$
1312 * Creates a new Cluster object.
1317 public Cluster(int[] value)