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.analysis.scoremodels.ScoreModels;
24 import jalview.analysis.scoremodels.SimilarityParams;
25 import jalview.api.analysis.DistanceScoreModelI;
26 import jalview.api.analysis.ScoreModelI;
27 import jalview.api.analysis.SimilarityScoreModelI;
28 import jalview.datamodel.AlignmentView;
29 import jalview.datamodel.BinaryNode;
30 import jalview.datamodel.CigarArray;
31 import jalview.datamodel.NodeTransformI;
32 import jalview.datamodel.SeqCigar;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceI;
35 import jalview.datamodel.SequenceNode;
36 import jalview.io.NewickFile;
37 import jalview.math.MatrixI;
39 import java.util.Enumeration;
40 import java.util.List;
41 import java.util.Vector;
54 public static final String AVERAGE_DISTANCE = "AV";
56 public static final String NEIGHBOUR_JOINING = "NJ";
58 public static final String FROM_FILE = "FromFile";
60 Vector<Cluster> cluster;
64 // SequenceData is a string representation of what the user
65 // sees. The display may contain hidden columns.
66 public AlignmentView seqData = null;
84 Vector<SequenceNode> groups = new Vector<SequenceNode>();
96 Vector<SequenceNode> node;
104 boolean hasDistances = true; // normal case for jalview trees
106 boolean hasBootstrap = false; // normal case for jalview trees
108 private boolean hasRootDistance = true;
111 * Create a new NJTree object with leaves associated with sequences in seqs,
112 * and original alignment data represented by Cigar strings.
121 public NJTree(SequenceI[] seqs, AlignmentView odata, NewickFile treefile)
123 this(seqs, treefile);
129 * sequenceString = new String[odata.length]; char gapChar =
130 * jalview.util.Comparison.GapChars.charAt(0); for (int i = 0; i <
131 * odata.length; i++) { SequenceI oseq_aligned = odata[i].getSeq(gapChar);
132 * sequenceString[i] = oseq_aligned.getSequence(); }
137 * Creates a new NJTree object from a tree from an external source
140 * SequenceI which should be associated with leafs of treefile
144 public NJTree(SequenceI[] seqs, NewickFile treefile)
146 this.sequence = seqs;
147 top = treefile.getTree();
150 * There is no dependent alignment to be recovered from an imported tree.
152 * if (sequenceString == null) { sequenceString = new String[seqs.length];
153 * for (int i = 0; i < seqs.length; i++) { sequenceString[i] =
154 * seqs[i].getSequence(); } }
157 hasDistances = treefile.HasDistances();
158 hasBootstrap = treefile.HasBootstrap();
159 hasRootDistance = treefile.HasRootDistance();
161 maxheight = findHeight(top);
163 SequenceIdMatcher algnIds = new SequenceIdMatcher(seqs);
165 Vector<SequenceNode> leaves = findLeaves(top);
168 int namesleft = seqs.length;
173 Vector<SequenceI> one2many = new Vector<SequenceI>();
174 int countOne2Many = 0;
175 while (i < leaves.size())
177 j = leaves.elementAt(i++);
178 realnam = j.getName();
183 nam = algnIds.findIdMatch(realnam);
189 if (one2many.contains(nam))
192 // if (jalview.bin.Cache.log.isDebugEnabled())
193 // jalview.bin.Cache.log.debug("One 2 many relationship for
198 one2many.addElement(nam);
204 j.setElement(new Sequence(realnam, "THISISAPLACEHLDER"));
205 j.setPlaceholder(true);
208 // if (jalview.bin.Cache.log.isDebugEnabled() && countOne2Many>0) {
209 // jalview.bin.Cache.log.debug("There were "+countOne2Many+" alignment
210 // sequence ids (out of "+one2many.size()+" unique ids) linked to two or
217 * Creates a new NJTree object.
230 public NJTree(SequenceI[] sqs, AlignmentView seqView, String treeType,
231 String modelType, ScoreModelI sm, int start, int end)
234 this.node = new Vector<SequenceNode>();
235 if (!(treeType.equals(NEIGHBOUR_JOINING)))
237 treeType = AVERAGE_DISTANCE;
239 this.type = treeType;
240 this.pwtype = modelType;
243 this.seqData = seqView;
247 SeqCigar[] seqs = new SeqCigar[sequence.length];
248 for (int i = 0; i < sequence.length; i++)
250 seqs[i] = new SeqCigar(sequence[i], start, end);
252 CigarArray sdata = new CigarArray(seqs);
253 sdata.addOperation(CigarArray.M, end - start + 1);
254 this.seqData = new AlignmentView(sdata, start);
257 if (sm == null && !(modelType.equals("PID")))
259 if (ScoreModels.getInstance().forName(modelType) == null)
261 modelType = "BLOSUM62";
267 done = new int[sequence.length];
269 while ((i < sequence.length) && (sequence[i] != null))
277 // TODO pass choice of params from GUI in constructo
278 if (sm instanceof DistanceScoreModelI)
280 distance = ((DistanceScoreModelI) sm).findDistances(seqData,
281 SimilarityParams.Jalview);
283 else if (sm instanceof SimilarityScoreModelI)
286 * compute similarity and invert it to give a distance measure
288 MatrixI result = ((SimilarityScoreModelI) sm).findSimilarities(
289 seqData, SimilarityParams.Jalview);
290 result.reverseRange(true);
296 noClus = cluster.size();
302 * Generate a string representation of the Tree
304 * @return Newick File with all tree data available
307 public String toString()
309 jalview.io.NewickFile fout = new jalview.io.NewickFile(getTopNode());
311 return fout.print(isHasBootstrap(), isHasDistances(),
312 isHasRootDistance()); // output all data available for tree
317 * used when the alignment associated to a tree has changed.
320 * Sequence set to be associated with tree nodes
322 public void UpdatePlaceHolders(List<SequenceI> list)
324 Vector<SequenceNode> leaves = findLeaves(top);
326 int sz = leaves.size();
327 SequenceIdMatcher seqmatcher = null;
332 SequenceNode leaf = leaves.elementAt(i++);
334 if (list.contains(leaf.element()))
336 leaf.setPlaceholder(false);
340 if (seqmatcher == null)
342 // Only create this the first time we need it
343 SequenceI[] seqs = new SequenceI[list.size()];
345 for (int j = 0; j < seqs.length; j++)
347 seqs[j] = list.get(j);
350 seqmatcher = new SequenceIdMatcher(seqs);
353 SequenceI nam = seqmatcher.findIdMatch(leaf.getName());
357 if (!leaf.isPlaceholder())
359 // remapping the node to a new sequenceI - should remove any refs to
361 // TODO - make many sequenceI to one leaf mappings possible!
364 leaf.setPlaceholder(false);
365 leaf.setElement(nam);
369 if (!leaf.isPlaceholder())
371 // Construct a new placeholder sequence object for this leaf
372 leaf.setElement(new Sequence(leaf.getName(),
373 "THISISAPLACEHLDER"));
375 leaf.setPlaceholder(true);
383 * rename any nodes according to their associated sequence. This will modify
384 * the tree's metadata! (ie the original NewickFile or newly generated
385 * BinaryTree's label data)
387 public void renameAssociatedNodes()
389 applyToNodes(new NodeTransformI()
393 public void transform(BinaryNode nd)
395 Object el = nd.element();
396 if (el != null && el instanceof SequenceI)
398 nd.setName(((SequenceI) el).getName());
407 public void cluster()
411 if (type.equals(NEIGHBOUR_JOINING))
420 Cluster c = joinClusters(mini, minj);
424 cluster.setElementAt(null, minj);
425 cluster.setElementAt(c, mini);
430 boolean onefound = false;
435 for (int i = 0; i < noseqs; i++)
439 if (onefound == false)
451 joinClusters(one, two);
452 top = (node.elementAt(one));
467 * @return DOCUMENT ME!
469 public Cluster joinClusters(int i, int j)
471 double dist = distance.getValue(i, j);
473 int noi = cluster.elementAt(i).value.length;
474 int noj = cluster.elementAt(j).value.length;
476 int[] value = new int[noi + noj];
478 for (int ii = 0; ii < noi; ii++)
480 value[ii] = cluster.elementAt(i).value[ii];
483 for (int ii = noi; ii < (noi + noj); ii++)
485 value[ii] = cluster.elementAt(j).value[ii - noi];
488 Cluster c = new Cluster(value);
493 if (type.equals(NEIGHBOUR_JOINING))
495 findClusterNJDistance(i, j);
499 findClusterDistance(i, j);
502 SequenceNode sn = new SequenceNode();
504 sn.setLeft((node.elementAt(i)));
505 sn.setRight((node.elementAt(j)));
507 SequenceNode tmpi = (node.elementAt(i));
508 SequenceNode tmpj = (node.elementAt(j));
510 if (type.equals(NEIGHBOUR_JOINING))
512 findNewNJDistances(tmpi, tmpj, dist);
516 findNewDistances(tmpi, tmpj, dist);
522 node.setElementAt(sn, i);
537 public void findNewNJDistances(SequenceNode tmpi, SequenceNode tmpj,
541 tmpi.dist = ((dist + ri) - rj) / 2;
542 tmpj.dist = (dist - tmpi.dist);
565 public void findNewDistances(SequenceNode tmpi, SequenceNode tmpj,
571 SequenceNode sni = tmpi;
572 SequenceNode snj = tmpj;
577 sni = (SequenceNode) sni.left();
583 snj = (SequenceNode) snj.left();
586 tmpi.dist = ((dist / 2) - ih);
587 tmpj.dist = ((dist / 2) - jh);
598 public void findClusterDistance(int i, int j)
600 int noi = cluster.elementAt(i).value.length;
601 int noj = cluster.elementAt(j).value.length;
603 // New distances from cluster to others
604 double[] newdist = new double[noseqs];
606 for (int l = 0; l < noseqs; l++)
608 if ((l != i) && (l != j))
610 // newdist[l] = ((distance[i][l] * noi) + (distance[j][l] * noj))
612 newdist[l] = ((distance.getValue(i, l) * noi) + (distance.getValue(
622 for (int ii = 0; ii < noseqs; ii++)
624 // distance[i][ii] = newdist[ii];
625 // distance[ii][i] = newdist[ii];
626 distance.setValue(i, ii, newdist[ii]);
627 distance.setValue(ii, i, newdist[ii]);
639 public void findClusterNJDistance(int i, int j)
642 // New distances from cluster to others
643 double[] newdist = new double[noseqs];
645 for (int l = 0; l < noseqs; l++)
647 if ((l != i) && (l != j))
649 // newdist[l] = ((distance[i][l] + distance[j][l]) - distance[i][j]) /
651 newdist[l] = (distance.getValue(i, l) + distance.getValue(j, l) - distance
652 .getValue(i, j)) / 2;
660 for (int ii = 0; ii < noseqs; ii++)
662 // distance[i][ii] = newdist[ii];
663 // distance[ii][i] = newdist[ii];
664 distance.setValue(i, ii, newdist[ii]);
665 distance.setValue(ii, i, newdist[ii]);
677 * @return DOCUMENT ME!
679 public double findr(int i, int j)
683 for (int k = 0; k < noseqs; k++)
685 if ((k != i) && (k != j) && (done[k] != 1))
687 // tmp = tmp + distance[i][k];
688 tmp = tmp + distance.getValue(i, k);
694 tmp = tmp / (noClus - 2);
703 * @return DOCUMENT ME!
705 public double findMinNJDistance()
707 double min = Double.MAX_VALUE;
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 // float tmp = distance[i][j] - (findr(i, j) + findr(j, i));
716 double tmp = distance.getValue(i, j)
717 - (findr(i, j) + findr(j, i));
736 * @return DOCUMENT ME!
738 public double findMinDistance()
740 double min = Double.MAX_VALUE;
742 for (int i = 0; i < (noseqs - 1); i++)
744 for (int j = i + 1; j < noseqs; j++)
746 if ((done[i] != 1) && (done[j] != 1))
748 // if (distance[i][j] < min)
749 if (distance.getValue(i, j) < min)
754 // min = distance[i][j];
755 min = distance.getValue(i, j);
767 public void makeLeaves()
769 cluster = new Vector<Cluster>();
771 for (int i = 0; i < noseqs; i++)
773 SequenceNode sn = new SequenceNode();
775 sn.setElement(sequence[i]);
776 sn.setName(sequence[i].getName());
779 int[] value = new int[1];
782 Cluster c = new Cluster(value);
783 cluster.addElement(c);
788 * Search for leaf nodes below (or at) the given node
791 * root node to search from
795 public Vector<SequenceNode> findLeaves(SequenceNode nd)
797 Vector<SequenceNode> leaves = new Vector<SequenceNode>();
798 findLeaves(nd, leaves);
803 * Search for leaf nodes.
806 * root node to search from
808 * Vector of leaves to add leaf node objects too.
810 * @return Vector of leaf nodes on binary tree
812 Vector<SequenceNode> findLeaves(SequenceNode nd,
813 Vector<SequenceNode> leaves)
820 if ((nd.left() == null) && (nd.right() == null)) // Interior node
823 leaves.addElement(nd);
830 * TODO: Identify internal nodes... if (node.isSequenceLabel()) {
831 * leaves.addElement(node); }
833 findLeaves((SequenceNode) nd.left(), leaves);
834 findLeaves((SequenceNode) nd.right(), leaves);
841 * Find the leaf node with a particular ycount
844 * initial point on tree to search from
846 * value to search for
848 * @return null or the node with ycound=count
850 public Object findLeaf(SequenceNode nd, int count)
852 found = _findLeaf(nd, count);
858 * #see findLeaf(SequenceNode node, count)
860 public Object _findLeaf(SequenceNode nd, int count)
867 if (nd.ycount == count)
869 found = nd.element();
875 _findLeaf((SequenceNode) nd.left(), count);
876 _findLeaf((SequenceNode) nd.right(), count);
883 * printNode is mainly for debugging purposes.
888 public void printNode(SequenceNode nd)
895 if ((nd.left() == null) && (nd.right() == null))
897 System.out.println("Leaf = " + ((SequenceI) nd.element()).getName());
898 System.out.println("Dist " + nd.dist);
899 System.out.println("Boot " + nd.getBootstrap());
903 System.out.println("Dist " + nd.dist);
904 printNode((SequenceNode) nd.left());
905 printNode((SequenceNode) nd.right());
915 public void findMaxDist(SequenceNode nd)
922 if ((nd.left() == null) && (nd.right() == null))
924 double dist = nd.dist;
926 if (dist > maxDistValue)
934 findMaxDist((SequenceNode) nd.left());
935 findMaxDist((SequenceNode) nd.right());
942 * @return DOCUMENT ME!
944 public Vector<SequenceNode> getGroups()
952 * @return DOCUMENT ME!
954 public double getMaxHeight()
967 public void groupNodes(SequenceNode nd, float threshold)
974 if ((nd.height / maxheight) > threshold)
976 groups.addElement(nd);
980 groupNodes((SequenceNode) nd.left(), threshold);
981 groupNodes((SequenceNode) nd.right(), threshold);
991 * @return DOCUMENT ME!
993 public double findHeight(SequenceNode nd)
1000 if ((nd.left() == null) && (nd.right() == null))
1002 nd.height = ((SequenceNode) nd.parent()).height + nd.dist;
1004 if (nd.height > maxheight)
1015 if (nd.parent() != null)
1017 nd.height = ((SequenceNode) nd.parent()).height + nd.dist;
1022 nd.height = (float) 0.0;
1025 maxheight = findHeight((SequenceNode) (nd.left()));
1026 maxheight = findHeight((SequenceNode) (nd.right()));
1035 * @return DOCUMENT ME!
1037 public SequenceNode reRoot()
1039 if (maxdist != null)
1043 double tmpdist = maxdist.dist;
1046 SequenceNode sn = new SequenceNode();
1049 // New right hand of top
1050 SequenceNode snr = (SequenceNode) maxdist.parent();
1051 changeDirection(snr, maxdist);
1052 System.out.println("Printing reversed tree");
1054 snr.dist = tmpdist / 2;
1055 maxdist.dist = tmpdist / 2;
1058 maxdist.setParent(sn);
1061 sn.setLeft(maxdist);
1075 * @return true if original sequence data can be recovered
1077 public boolean hasOriginalSequenceData()
1079 return seqData != null;
1083 * Returns original alignment data used for calculation - or null where not
1086 * @return null or cut'n'pasteable alignment
1088 public String printOriginalSequenceData(char gapChar)
1090 if (seqData == null)
1095 StringBuffer sb = new StringBuffer();
1096 String[] seqdatas = seqData.getSequenceStrings(gapChar);
1097 for (int i = 0; i < seqdatas.length; i++)
1099 sb.append(new jalview.util.Format("%-" + 15 + "s").form(sequence[i]
1101 sb.append(" " + seqdatas[i] + "\n");
1103 return sb.toString();
1112 public void printN(SequenceNode nd)
1119 if ((nd.left() != null) && (nd.right() != null))
1121 printN((SequenceNode) nd.left());
1122 printN((SequenceNode) nd.right());
1126 System.out.println(" name = " + ((SequenceI) nd.element()).getName());
1129 System.out.println(" dist = " + nd.dist + " " + nd.count + " "
1139 public void reCount(SequenceNode nd)
1143 // _lylimit = this.node.size();
1147 private long _lycount = 0, _lylimit = 0;
1155 public void _reCount(SequenceNode nd)
1157 // if (_lycount<_lylimit)
1159 // System.err.println("Warning: depth of _recount greater than number of nodes.");
1167 if ((nd.left() != null) && (nd.right() != null))
1170 _reCount((SequenceNode) nd.left());
1171 _reCount((SequenceNode) nd.right());
1173 SequenceNode l = (SequenceNode) nd.left();
1174 SequenceNode r = (SequenceNode) nd.right();
1176 nd.count = l.count + r.count;
1177 nd.ycount = (l.ycount + r.ycount) / 2;
1182 nd.ycount = ycount++;
1193 public void swapNodes(SequenceNode nd)
1200 SequenceNode tmp = (SequenceNode) nd.left();
1202 nd.setLeft(nd.right());
1214 public void changeDirection(SequenceNode nd, SequenceNode dir)
1221 if (nd.parent() != top)
1223 changeDirection((SequenceNode) nd.parent(), nd);
1225 SequenceNode tmp = (SequenceNode) nd.parent();
1227 if (dir == nd.left())
1232 else if (dir == nd.right())
1240 if (dir == nd.left())
1242 nd.setParent(nd.left());
1244 if (top.left() == nd)
1246 nd.setRight(top.right());
1250 nd.setRight(top.left());
1255 nd.setParent(nd.right());
1257 if (top.left() == nd)
1259 nd.setLeft(top.right());
1263 nd.setLeft(top.left());
1272 * @return DOCUMENT ME!
1274 public SequenceNode getMaxDist()
1282 * @return DOCUMENT ME!
1284 public SequenceNode getTopNode()
1291 * @return true if tree has real distances
1293 public boolean isHasDistances()
1295 return hasDistances;
1300 * @return true if tree has real bootstrap values
1302 public boolean isHasBootstrap()
1304 return hasBootstrap;
1307 public boolean isHasRootDistance()
1309 return hasRootDistance;
1313 * apply the given transform to all the nodes in the tree.
1315 * @param nodeTransformI
1317 public void applyToNodes(NodeTransformI nodeTransformI)
1319 for (Enumeration<SequenceNode> nodes = node.elements(); nodes
1320 .hasMoreElements(); nodeTransformI.transform(nodes
1332 * @version $Revision$
1334 // TODO what does this class have that int[] doesn't have already?
1340 * Creates a new Cluster object.
1345 public Cluster(int[] value)