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.api.analysis.ScoreModelI;
25 import jalview.datamodel.AlignmentView;
26 import jalview.datamodel.BinaryNode;
27 import jalview.datamodel.CigarArray;
28 import jalview.datamodel.NodeTransformI;
29 import jalview.datamodel.SeqCigar;
30 import jalview.datamodel.Sequence;
31 import jalview.datamodel.SequenceI;
32 import jalview.datamodel.SequenceNode;
33 import jalview.io.NewickFile;
35 import java.util.Enumeration;
36 import java.util.List;
37 import java.util.Vector;
47 public static final String AVERAGE_DISTANCE = "AV";
49 public static final String NEIGHBOUR_JOINING = "NJ";
51 Vector<Cluster> cluster;
55 // SequenceData is a string representation of what the user
56 // sees. The display may contain hidden columns.
57 public AlignmentView seqData = null;
75 Vector<SequenceNode> groups = new Vector<SequenceNode>();
87 Vector<SequenceNode> node;
95 boolean hasDistances = true; // normal case for jalview trees
97 boolean hasBootstrap = false; // normal case for jalview trees
99 private boolean hasRootDistance = true;
102 * Create a new NJTree object with leaves associated with sequences in seqs,
103 * and original alignment data represented by Cigar strings.
112 public NJTree(SequenceI[] seqs, AlignmentView odata, NewickFile treefile)
114 this(seqs, treefile);
120 * sequenceString = new String[odata.length]; char gapChar =
121 * jalview.util.Comparison.GapChars.charAt(0); for (int i = 0; i <
122 * odata.length; i++) { SequenceI oseq_aligned = odata[i].getSeq(gapChar);
123 * sequenceString[i] = oseq_aligned.getSequence(); }
128 * Creates a new NJTree object from a tree from an external source
131 * SequenceI which should be associated with leafs of treefile
135 public NJTree(SequenceI[] seqs, NewickFile treefile)
137 this.sequence = seqs;
138 top = treefile.getTree();
141 * There is no dependent alignment to be recovered from an imported tree.
143 * if (sequenceString == null) { sequenceString = new String[seqs.length];
144 * for (int i = 0; i < seqs.length; i++) { sequenceString[i] =
145 * seqs[i].getSequence(); } }
148 hasDistances = treefile.HasDistances();
149 hasBootstrap = treefile.HasBootstrap();
150 hasRootDistance = treefile.HasRootDistance();
152 maxheight = findHeight(top);
154 SequenceIdMatcher algnIds = new SequenceIdMatcher(seqs);
156 Vector<SequenceNode> leaves = findLeaves(top);
159 int namesleft = seqs.length;
164 Vector<SequenceI> one2many = new Vector<SequenceI>();
165 int countOne2Many = 0;
166 while (i < leaves.size())
168 j = leaves.elementAt(i++);
169 realnam = j.getName();
174 nam = algnIds.findIdMatch(realnam);
180 if (one2many.contains(nam))
183 // if (jalview.bin.Cache.log.isDebugEnabled())
184 // jalview.bin.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 (jalview.bin.Cache.log.isDebugEnabled() && countOne2Many>0) {
200 // jalview.bin.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<SequenceNode>();
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(NEIGHBOUR_JOINING)))
246 type = AVERAGE_DISTANCE;
249 if (sm == null && !(pwtype.equals("PID")))
251 if (ScoreModels.getInstance().forName(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
287 public String toString()
289 jalview.io.NewickFile fout = new jalview.io.NewickFile(getTopNode());
291 return fout.print(isHasBootstrap(), isHasDistances(),
292 isHasRootDistance()); // output all data available for tree
297 * used when the alignment associated to a tree has changed.
300 * Sequence set to be associated with tree nodes
302 public void UpdatePlaceHolders(List<SequenceI> list)
304 Vector<SequenceNode> leaves = findLeaves(top);
306 int sz = leaves.size();
307 SequenceIdMatcher seqmatcher = null;
312 SequenceNode leaf = 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 nd)
375 Object el = nd.element();
376 if (el != null && el instanceof SequenceI)
378 nd.setName(((SequenceI) el).getName());
387 public void cluster()
391 if (type.equals(NEIGHBOUR_JOINING))
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 = (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.elementAt(i).value.length;
454 int noj = cluster.elementAt(j).value.length;
456 int[] value = new int[noi + noj];
458 for (int ii = 0; ii < noi; ii++)
460 value[ii] = cluster.elementAt(i).value[ii];
463 for (int ii = noi; ii < (noi + noj); ii++)
465 value[ii] = cluster.elementAt(j).value[ii - noi];
468 Cluster c = new Cluster(value);
473 if (type.equals(NEIGHBOUR_JOINING))
475 findClusterNJDistance(i, j);
479 findClusterDistance(i, j);
482 SequenceNode sn = new SequenceNode();
484 sn.setLeft((node.elementAt(i)));
485 sn.setRight((node.elementAt(j)));
487 SequenceNode tmpi = (node.elementAt(i));
488 SequenceNode tmpj = (node.elementAt(j));
490 if (type.equals(NEIGHBOUR_JOINING))
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.elementAt(i).value.length;
581 int noj = 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[][] dist = new float[noseqs][noseqs];
738 if (_pwmatrix == null)
740 // Resolve substitution model
741 _pwmatrix = ScoreModels.getInstance().forName(pwtype);
742 if (_pwmatrix == null)
744 _pwmatrix = ScoreModels.getInstance().forName("BLOSUM62");
747 dist = _pwmatrix.findDistances(seqData);
755 public void makeLeaves()
757 cluster = new Vector<Cluster>();
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 below (or at) the given node
779 * root node to search from
783 public Vector<SequenceNode> findLeaves(SequenceNode nd)
785 Vector<SequenceNode> leaves = new Vector<SequenceNode>();
786 findLeaves(nd, leaves);
791 * Search for leaf nodes.
794 * root node to search from
796 * Vector of leaves to add leaf node objects too.
798 * @return Vector of leaf nodes on binary tree
800 Vector<SequenceNode> findLeaves(SequenceNode nd,
801 Vector<SequenceNode> leaves)
808 if ((nd.left() == null) && (nd.right() == null)) // Interior node
811 leaves.addElement(nd);
818 * TODO: Identify internal nodes... if (node.isSequenceLabel()) {
819 * leaves.addElement(node); }
821 findLeaves((SequenceNode) nd.left(), leaves);
822 findLeaves((SequenceNode) nd.right(), leaves);
829 * Find the leaf node with a particular ycount
832 * initial point on tree to search from
834 * value to search for
836 * @return null or the node with ycound=count
838 public Object findLeaf(SequenceNode nd, int count)
840 found = _findLeaf(nd, count);
846 * #see findLeaf(SequenceNode node, count)
848 public Object _findLeaf(SequenceNode nd, int count)
855 if (nd.ycount == count)
857 found = nd.element();
863 _findLeaf((SequenceNode) nd.left(), count);
864 _findLeaf((SequenceNode) nd.right(), count);
871 * printNode is mainly for debugging purposes.
876 public void printNode(SequenceNode nd)
883 if ((nd.left() == null) && (nd.right() == null))
885 System.out.println("Leaf = " + ((SequenceI) nd.element()).getName());
886 System.out.println("Dist " + nd.dist);
887 System.out.println("Boot " + nd.getBootstrap());
891 System.out.println("Dist " + nd.dist);
892 printNode((SequenceNode) nd.left());
893 printNode((SequenceNode) nd.right());
903 public void findMaxDist(SequenceNode nd)
910 if ((nd.left() == null) && (nd.right() == null))
912 float dist = nd.dist;
914 if (dist > maxDistValue)
922 findMaxDist((SequenceNode) nd.left());
923 findMaxDist((SequenceNode) nd.right());
930 * @return DOCUMENT ME!
932 public Vector<SequenceNode> getGroups()
940 * @return DOCUMENT ME!
942 public float getMaxHeight()
955 public void groupNodes(SequenceNode nd, float threshold)
962 if ((nd.height / maxheight) > threshold)
964 groups.addElement(nd);
968 groupNodes((SequenceNode) nd.left(), threshold);
969 groupNodes((SequenceNode) nd.right(), threshold);
979 * @return DOCUMENT ME!
981 public float findHeight(SequenceNode nd)
988 if ((nd.left() == null) && (nd.right() == null))
990 nd.height = ((SequenceNode) nd.parent()).height + nd.dist;
992 if (nd.height > maxheight)
1003 if (nd.parent() != null)
1005 nd.height = ((SequenceNode) nd.parent()).height + nd.dist;
1010 nd.height = (float) 0.0;
1013 maxheight = findHeight((SequenceNode) (nd.left()));
1014 maxheight = findHeight((SequenceNode) (nd.right()));
1023 * @return DOCUMENT ME!
1025 public SequenceNode reRoot()
1027 if (maxdist != null)
1031 float tmpdist = maxdist.dist;
1034 SequenceNode sn = new SequenceNode();
1037 // New right hand of top
1038 SequenceNode snr = (SequenceNode) maxdist.parent();
1039 changeDirection(snr, maxdist);
1040 System.out.println("Printing reversed tree");
1042 snr.dist = tmpdist / 2;
1043 maxdist.dist = tmpdist / 2;
1046 maxdist.setParent(sn);
1049 sn.setLeft(maxdist);
1063 * @return true if original sequence data can be recovered
1065 public boolean hasOriginalSequenceData()
1067 return seqData != null;
1071 * Returns original alignment data used for calculation - or null where not
1074 * @return null or cut'n'pasteable alignment
1076 public String printOriginalSequenceData(char gapChar)
1078 if (seqData == null)
1083 StringBuffer sb = new StringBuffer();
1084 String[] seqdatas = seqData.getSequenceStrings(gapChar);
1085 for (int i = 0; i < seqdatas.length; i++)
1087 sb.append(new jalview.util.Format("%-" + 15 + "s").form(sequence[i]
1089 sb.append(" " + seqdatas[i] + "\n");
1091 return sb.toString();
1100 public void printN(SequenceNode nd)
1107 if ((nd.left() != null) && (nd.right() != null))
1109 printN((SequenceNode) nd.left());
1110 printN((SequenceNode) nd.right());
1114 System.out.println(" name = " + ((SequenceI) nd.element()).getName());
1117 System.out.println(" dist = " + nd.dist + " " + nd.count + " "
1127 public void reCount(SequenceNode nd)
1131 // _lylimit = this.node.size();
1135 private long _lycount = 0, _lylimit = 0;
1143 public void _reCount(SequenceNode nd)
1145 // if (_lycount<_lylimit)
1147 // System.err.println("Warning: depth of _recount greater than number of nodes.");
1155 if ((nd.left() != null) && (nd.right() != null))
1158 _reCount((SequenceNode) nd.left());
1159 _reCount((SequenceNode) nd.right());
1161 SequenceNode l = (SequenceNode) nd.left();
1162 SequenceNode r = (SequenceNode) nd.right();
1164 nd.count = l.count + r.count;
1165 nd.ycount = (l.ycount + r.ycount) / 2;
1170 nd.ycount = ycount++;
1181 public void swapNodes(SequenceNode nd)
1188 SequenceNode tmp = (SequenceNode) nd.left();
1190 nd.setLeft(nd.right());
1202 public void changeDirection(SequenceNode nd, SequenceNode dir)
1209 if (nd.parent() != top)
1211 changeDirection((SequenceNode) nd.parent(), nd);
1213 SequenceNode tmp = (SequenceNode) nd.parent();
1215 if (dir == nd.left())
1220 else if (dir == nd.right())
1228 if (dir == nd.left())
1230 nd.setParent(nd.left());
1232 if (top.left() == nd)
1234 nd.setRight(top.right());
1238 nd.setRight(top.left());
1243 nd.setParent(nd.right());
1245 if (top.left() == nd)
1247 nd.setLeft(top.right());
1251 nd.setLeft(top.left());
1260 * @return DOCUMENT ME!
1262 public SequenceNode getMaxDist()
1270 * @return DOCUMENT ME!
1272 public SequenceNode getTopNode()
1279 * @return true if tree has real distances
1281 public boolean isHasDistances()
1283 return hasDistances;
1288 * @return true if tree has real bootstrap values
1290 public boolean isHasBootstrap()
1292 return hasBootstrap;
1295 public boolean isHasRootDistance()
1297 return hasRootDistance;
1301 * apply the given transform to all the nodes in the tree.
1303 * @param nodeTransformI
1305 public void applyToNodes(NodeTransformI nodeTransformI)
1307 for (Enumeration<SequenceNode> nodes = node.elements(); nodes
1308 .hasMoreElements(); nodeTransformI.transform(nodes
1320 * @version $Revision$
1327 * Creates a new Cluster object.
1332 public Cluster(int[] value)