source: branches/profile/GDE/RAxML/treeIO.c

Last change on this file was 10409, checked in by aboeckma, 11 years ago

Updated raxml to current version

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 48.4 KB
Line 
1/*  RAxML-VI-HPC (version 2.2) a program for sequential and parallel estimation of phylogenetic trees
2 *  Copyright August 2006 by Alexandros Stamatakis
3 *
4 *  Partially derived from
5 *  fastDNAml, a program for estimation of phylogenetic trees from sequences by Gary J. Olsen
6 * 
7 *  and
8 *
9 *  Programs of the PHYLIP package by Joe Felsenstein.
10 *
11 *  This program is free software; you may redistribute it and/or modify its
12 *  under the terms of the GNU General Public License as published by the Free
13 *  Software Foundation; either version 2 of the License, or (at your option)
14 *  any later version.
15 *
16 *  This program is distributed in the hope that it will be useful, but
17 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 *  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
19 *  for more details.
20 *
21 *
22 *  For any other enquiries send an Email to Alexandros Stamatakis
23 *  Alexandros.Stamatakis@epfl.ch
24 *
25 *  When publishing work that is based on the results from RAxML-VI-HPC please cite:
26 *
27 *  Alexandros Stamatakis:"RAxML-VI-HPC: maximum likelihood-based phylogenetic analyses with thousands of taxa and mixed models".
28 *  Bioinformatics 2006; doi: 10.1093/bioinformatics/btl446
29 */
30
31#ifndef WIN32
32#include <sys/times.h>
33#include <sys/types.h>
34#include <sys/time.h>
35#include <unistd.h>
36#endif
37
38#include <math.h>
39#include <time.h>
40#include <stdlib.h>
41#include <stdio.h>
42#include <ctype.h>
43#include <string.h>
44
45#include "axml.h"
46
47extern FILE *INFILE;
48extern char infoFileName[1024];
49extern char tree_file[1024];
50extern char *likelihood_key;
51extern char *ntaxa_key;
52extern char *smoothed_key;
53extern int partCount;
54extern double masterTime;
55
56
57
58
59
60stringHashtable *initStringHashTable(hashNumberType n)
61{
62  /*
63     init with primes
64  */
65   
66  static const hashNumberType initTable[] = {53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317,
67                                             196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843,
68                                             50331653, 100663319, 201326611, 402653189, 805306457, 1610612741};
69 
70
71  /* init with powers of two
72
73  static const  hashNumberType initTable[] = {64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
74                                              32768, 65536, 131072, 262144, 524288, 1048576, 2097152,
75                                              4194304, 8388608, 16777216, 33554432, 67108864, 134217728,
76                                              268435456, 536870912, 1073741824, 2147483648U};
77  */
78 
79  stringHashtable *h = (stringHashtable*)rax_malloc(sizeof(stringHashtable));
80 
81  hashNumberType
82    tableSize,
83    i,
84    primeTableLength = sizeof(initTable)/sizeof(initTable[0]),
85    maxSize = (hashNumberType)-1;   
86
87  assert(n <= maxSize);
88
89  i = 0;
90
91  while(initTable[i] < n && i < primeTableLength)
92    i++;
93
94  assert(i < primeTableLength);
95
96  tableSize = initTable[i]; 
97
98  h->table = (stringEntry**)rax_calloc(tableSize, sizeof(stringEntry*));
99  h->tableSize = tableSize;   
100
101  return h;
102}
103
104
105static hashNumberType  hashString(char *p, hashNumberType tableSize)
106{
107  hashNumberType h = 0;
108 
109  for(; *p; p++)
110    h = 31 * h + *p;
111 
112  return (h % tableSize);
113}
114
115 
116
117void addword(char *s, stringHashtable *h, int nodeNumber)
118{
119  hashNumberType position = hashString(s, h->tableSize);
120  stringEntry *p = h->table[position];
121 
122  for(; p!= NULL; p = p->next)
123    {
124      if(strcmp(s, p->word) == 0)               
125        return;         
126    }
127
128  p = (stringEntry *)rax_malloc(sizeof(stringEntry));
129
130  assert(p);
131 
132  p->nodeNumber = nodeNumber;
133  p->word = (char *)rax_malloc((strlen(s) + 1) * sizeof(char));
134
135  strcpy(p->word, s);
136 
137  p->next =  h->table[position];
138 
139  h->table[position] = p;
140}
141
142int lookupWord(char *s, stringHashtable *h)
143{
144  hashNumberType position = hashString(s, h->tableSize);
145  stringEntry *p = h->table[position];
146 
147  for(; p!= NULL; p = p->next)
148    {
149      if(strcmp(s, p->word) == 0)               
150        return p->nodeNumber;           
151    }
152
153  return -1;
154}
155
156
157int countTips(nodeptr p, int numsp)
158{
159  if(isTip(p->number, numsp)) 
160    return 1;   
161  {
162    nodeptr q;
163    int tips = 0;
164
165    q = p->next;
166    while(q != p)
167      { 
168        tips += countTips(q->back, numsp);
169        q = q->next;
170      } 
171   
172    return tips;
173  }
174}
175
176
177static double getBranchLength(tree *tr, int perGene, nodeptr p)
178{
179  double 
180    z = 0.0,
181    x = 0.0;
182
183  assert(perGene != NO_BRANCHES);
184             
185  if(!tr->multiBranch)
186    {
187      assert(tr->fracchange != -1.0);
188      z = p->z[0];
189      if (z < zmin) 
190        z = zmin;       
191     
192      x = -log(z) * tr->fracchange;           
193    }
194  else
195    {
196      if(perGene == SUMMARIZE_LH)
197        {
198          int 
199            i;
200         
201          double 
202            avgX = 0.0;
203                     
204          for(i = 0; i < tr->numBranches; i++)
205            {
206              assert(tr->partitionContributions[i] != -1.0);
207              assert(tr->fracchanges[i] != -1.0);
208              z = p->z[i];
209              if(z < zmin) 
210                z = zmin;       
211              x = -log(z) * tr->fracchanges[i];
212              avgX += x * tr->partitionContributions[i];
213            }
214
215          x = avgX;
216        }
217      else
218        {       
219          assert(tr->fracchanges[perGene] != -1.0);
220          assert(perGene >= 0 && perGene < tr->numBranches);
221         
222          z = p->z[perGene];
223         
224          if(z < zmin) 
225            z = zmin;           
226         
227          x = -log(z) * tr->fracchanges[perGene];         
228        }
229    }
230
231  return x;
232}
233
234
235 
236
237
238static char *Tree2StringREC(char *treestr, tree *tr, nodeptr p, boolean printBranchLengths, boolean printNames, 
239                            boolean printLikelihood, boolean rellTree, boolean finalPrint, int perGene, boolean branchLabelSupport, boolean printSHSupport, boolean printIC, boolean printSHSupports)
240{
241  char  *nameptr;           
242     
243  if(isTip(p->number, tr->rdta->numsp)) 
244    {             
245      if(printNames)
246        {
247          nameptr = tr->nameList[p->number];     
248          sprintf(treestr, "%s", nameptr);
249        }
250      else
251        sprintf(treestr, "%d", p->number);   
252       
253      while (*treestr) treestr++;
254    }
255  else 
256    {                   
257      *treestr++ = '(';
258      treestr = Tree2StringREC(treestr, tr, p->next->back, printBranchLengths, printNames, printLikelihood, rellTree, 
259                               finalPrint, perGene, branchLabelSupport, printSHSupport, printIC, printSHSupports);
260      *treestr++ = ',';
261      treestr = Tree2StringREC(treestr, tr, p->next->next->back, printBranchLengths, printNames, printLikelihood, rellTree, 
262                               finalPrint, perGene, branchLabelSupport, printSHSupport, printIC, printSHSupports);
263      if(p == tr->start->back) 
264        {
265          *treestr++ = ',';
266          treestr = Tree2StringREC(treestr, tr, p->back, printBranchLengths, printNames, printLikelihood, rellTree, 
267                                   finalPrint, perGene, branchLabelSupport, printSHSupport, printIC, printSHSupports);
268        }
269      *treestr++ = ')';                   
270    }
271
272  if(p == tr->start->back) 
273    {           
274      if(printBranchLengths && !rellTree)
275        sprintf(treestr, ":0.0;\n");
276      else
277        sprintf(treestr, ";\n");                       
278    }
279  else 
280    {                   
281      if(rellTree || branchLabelSupport || printSHSupport || printIC || printSHSupports)
282        {               
283          if(( !isTip(p->number, tr->rdta->numsp)) && 
284             ( !isTip(p->back->number, tr->rdta->numsp)))
285            {                         
286              assert(p->bInf != (branchInfo *)NULL);               
287             
288              assert(rellTree + branchLabelSupport + printSHSupport + printSHSupports == 1);
289
290              if(rellTree)
291                {
292                  if(printIC)
293                    sprintf(treestr, "%1.2f:%8.20f", p->bInf->ic, p->z[0]);
294                  else
295                    sprintf(treestr, "%d:%8.20f", p->bInf->support, p->z[0]);
296                }
297             
298              if(branchLabelSupport)
299                {
300                  if(printIC)
301                    sprintf(treestr, ":%8.20f[%1.2f,%1.2f]", p->z[0], p->bInf->ic, p->bInf->icAll);
302                  else             
303                    sprintf(treestr, ":%8.20f[%d]", p->z[0], p->bInf->support);
304                }
305             
306              if(printSHSupport)
307                sprintf(treestr, ":%8.20f[%d]", getBranchLength(tr, perGene, p), p->bInf->support);
308
309              if(printSHSupports)
310                {
311                  int 
312                    model;
313                 
314                  sprintf(treestr, ":%8.20f[", getBranchLength(tr, perGene, p));
315                  while(*treestr) 
316                    treestr++;
317                 
318                  for(model = 0; model < tr->NumberOfModels - 1; model++)                   
319                    {
320                      sprintf(treestr, "%d,", p->bInf->supports[model]);
321                       while(*treestr) 
322                         treestr++;
323                    }
324
325                  sprintf(treestr, "%d]", p->bInf->supports[model]);
326                }
327             
328            }
329          else         
330            {
331              if(rellTree || branchLabelSupport)
332                sprintf(treestr, ":%8.20f", p->z[0]);   
333              if(printSHSupport || printSHSupports)
334                sprintf(treestr, ":%8.20f", getBranchLength(tr, perGene, p));
335            }
336        }
337      else
338        {
339          if(printBranchLengths)           
340            sprintf(treestr, ":%8.20f", getBranchLength(tr, perGene, p));                 
341          else     
342            sprintf(treestr, "%s", "\0");           
343        }     
344    }
345 
346  while (*treestr) treestr++;
347  return  treestr;
348}
349
350
351static void collectSubtrees(tree *tr, nodeptr *subtrees, int *count, int ogn)
352{
353  int i;
354  for(i = tr->mxtips + 1; i <= tr->mxtips + tr->mxtips - 2; i++)
355    {
356      nodeptr p, q;
357      p = tr->nodep[i];
358      if(countTips(p, tr->rdta->numsp) == ogn)
359        {
360          subtrees[*count] = p;
361          *count = *count + 1;
362        }
363      q = p->next;
364      while(q != p)
365        {
366          if(countTips(q, tr->rdta->numsp) == ogn)
367            {
368              subtrees[*count] = q;
369              *count = *count + 1;
370            }
371          q = q->next;
372        }
373    }
374}
375
376static void checkOM(nodeptr p, int *n, int *c, tree *tr)
377{
378  if(isTip(p->number, tr->rdta->numsp))
379    {
380      n[*c] = p->number;
381      *c = *c + 1;     
382    }
383  else
384    {
385      nodeptr q = p->next;
386
387      while(q != p)
388        {
389          checkOM(q->back, n, c, tr);
390          q = q->next;
391        }
392    }
393}
394   
395static char *rootedTreeREC(char *treestr, tree *tr, nodeptr p, boolean printBranchLengths, boolean printNames, 
396                           boolean printLikelihood, boolean rellTree, 
397                           boolean finalPrint, analdef *adef, int perGene, boolean branchLabelSupport, boolean printSHSupport)
398{
399  char  *nameptr;
400
401  if(isTip(p->number, tr->rdta->numsp)) 
402    {       
403      if(printNames)
404        {
405          nameptr = tr->nameList[p->number];     
406          sprintf(treestr, "%s", nameptr);
407        }
408      else
409        sprintf(treestr, "%d", p->number);
410     
411      while (*treestr) treestr++;
412    }
413  else 
414    {
415      *treestr++ = '(';
416      treestr = rootedTreeREC(treestr, tr, p->next->back, printBranchLengths, printNames, printLikelihood, 
417                              rellTree, finalPrint, adef, perGene, branchLabelSupport, printSHSupport);
418      *treestr++ = ',';
419      treestr = rootedTreeREC(treestr, tr, p->next->next->back, printBranchLengths, printNames, printLikelihood, 
420                              rellTree, finalPrint, adef, perGene, branchLabelSupport, printSHSupport);     
421      *treestr++ = ')';           
422    }
423
424  if(rellTree || branchLabelSupport || printSHSupport)
425    {           
426      if(( !isTip(p->number, tr->rdta->numsp)) && 
427         ( !isTip(p->back->number, tr->rdta->numsp)))
428        {                             
429          assert(p->bInf != (branchInfo *)NULL);
430             
431          if(rellTree)
432            sprintf(treestr, "%d:%8.20f", p->bInf->support, p->z[0]);     
433          if(branchLabelSupport)
434            sprintf(treestr, ":%8.20f[%d]", p->z[0], p->bInf->support);
435          if(printSHSupport)
436            sprintf(treestr, ":%8.20f[%d]", getBranchLength(tr, perGene, p), p->bInf->support);       
437        }
438      else             
439        {
440          if(rellTree || branchLabelSupport)
441            sprintf(treestr, ":%8.20f", p->z[0]);       
442          if(printSHSupport)
443            sprintf(treestr, ":%8.20f", getBranchLength(tr, perGene, p));
444        }
445    }
446  else
447    {
448      if(printBranchLengths)       
449        sprintf(treestr, ":%8.20f", getBranchLength(tr, perGene, p));             
450      else         
451        sprintf(treestr, "%s", "\0");       
452    }     
453
454  while (*treestr) treestr++;
455  return  treestr;
456}
457
458static char *rootedTree(char *treestr, tree *tr, nodeptr p, boolean printBranchLengths, boolean printNames, 
459                        boolean printLikelihood, boolean rellTree, 
460                        boolean finalPrint, analdef *adef, int perGene, boolean branchLabelSupport, boolean printSHSupport)
461{
462  double oldz[NUM_BRANCHES];
463  int i;
464 
465  for(i = 0; i < tr->numBranches; i++)
466    oldz[i] = p->z[i];
467
468  if(rellTree)   
469    {   
470      p->z[0] = p->back->z[0] = oldz[0] * 0.5;
471      /*printf("%f\n",  p->z[0]);*/
472    }
473  else
474    {
475      if(printBranchLengths)
476        {
477          double rz, z;
478          assert(perGene != NO_BRANCHES);
479
480          if(!tr->multiBranch)
481            {
482              assert(tr->fracchange != -1.0);
483              z = -log(p->z[0]) * tr->fracchange;
484              rz = exp(-(z * 0.5)/ tr->fracchange);
485              p->z[0] = p->back->z[0] = rz;
486            }
487          else
488            {
489              if(perGene == SUMMARIZE_LH)
490                {                                               
491                  int i;             
492                 
493                  for(i = 0; i < tr->numBranches; i++)
494                    {   
495                      assert(tr->fracchanges[i] != -1.0);
496                      z    = -log(p->z[i]) * tr->fracchanges[i];                     
497                      rz   = exp(-(z * 0.5)/ tr->fracchanges[i]);
498                      p->z[i] = p->back->z[i] = rz;                 
499                    }           
500                }                   
501              else
502                {               
503                  assert(tr->fracchanges[perGene] != -1.0);
504                  assert(perGene >= 0 && perGene < tr->numBranches);
505                  z = -log(p->z[perGene]) * tr->fracchanges[perGene];
506                  rz = exp(-(z * 0.5)/ tr->fracchanges[perGene]);
507                  p->z[perGene] = p->back->z[perGene] = rz;                           
508                }
509            }
510        }
511    }
512
513  *treestr = '(';
514  treestr++;
515  treestr = rootedTreeREC(treestr, tr, p,  printBranchLengths, printNames, printLikelihood, rellTree, finalPrint, 
516                          adef, perGene, branchLabelSupport, printSHSupport);
517  *treestr = ',';
518  treestr++;
519  treestr = rootedTreeREC(treestr, tr, p->back,  printBranchLengths, printNames, printLikelihood, rellTree, finalPrint, 
520                          adef, perGene, branchLabelSupport, printSHSupport);
521  sprintf(treestr, ");\n");
522  while (*treestr) treestr++;
523
524
525  for(i = 0; i < tr->numBranches; i++)
526    p->z[i] = p->back->z[i] = oldz[i]; 
527   
528  return  treestr;
529}
530
531
532
533char *Tree2String(char *treestr, tree *tr, nodeptr p, boolean printBranchLengths, boolean printNames, boolean printLikelihood, 
534                  boolean rellTree, 
535                  boolean finalPrint, analdef *adef, int perGene, boolean branchLabelSupport, boolean printSHSupport, boolean printIC, boolean printSHSupports)
536{ 
537
538  if(rellTree)
539    assert(!branchLabelSupport && !printSHSupport);
540
541  if(branchLabelSupport)
542    assert(!rellTree && !printSHSupport);
543
544  if(printSHSupport)
545    assert(!branchLabelSupport && !rellTree);
546
547  if(finalPrint && adef->outgroup)
548    {
549      nodeptr startNode = tr->start;
550
551      if(tr->numberOfOutgroups > 1)
552        {
553          nodeptr root;
554          nodeptr *subtrees = (nodeptr *)rax_malloc(sizeof(nodeptr) * tr->mxtips);
555          int i, k, count = 0;
556          int *nodeNumbers = (int*)rax_malloc(sizeof(int) * tr->numberOfOutgroups);
557          int *foundVector = (int*)rax_malloc(sizeof(int) * tr->numberOfOutgroups);
558          boolean monophyletic = FALSE;
559
560          collectSubtrees(tr, subtrees, &count, tr->numberOfOutgroups);
561
562          /*printf("Found %d subtrees of size  %d\n", count, tr->numberOfOutgroups);*/
563         
564          for(i = 0; (i < count) && (!monophyletic); i++)
565            {
566              int l, sum, nc = 0;
567              for(k = 0; k <  tr->numberOfOutgroups; k++)
568                {
569                  nodeNumbers[k] = -1;
570                  foundVector[k] = 0;
571                }
572
573              checkOM(subtrees[i], nodeNumbers, &nc, tr);             
574             
575              for(l = 0; l < tr->numberOfOutgroups; l++)
576                for(k = 0; k < tr->numberOfOutgroups; k++)
577                  {
578                    if(nodeNumbers[l] == tr->outgroupNums[k])
579                      foundVector[l] = 1;
580                  }
581             
582              sum = 0;
583              for(l = 0; l < tr->numberOfOutgroups; l++)
584                sum += foundVector[l];
585             
586              if(sum == tr->numberOfOutgroups)
587                {                         
588                  root = subtrees[i];
589                  tr->start = root;             
590                  /*printf("outgroups are monphyletic!\n");*/
591                  monophyletic = TRUE;           
592                }
593              else
594                {
595                  if(sum > 0)
596                    {
597                      /*printf("outgroups are NOT monophyletic!\n");*/
598                      monophyletic = FALSE;
599                    }       
600                }       
601            }
602         
603          if(!monophyletic)
604            {
605              printf("WARNING, outgroups are not monophyletic, using first outgroup \"%s\"\n", tr->nameList[tr->outgroupNums[0]]);
606              printf("from the list to root the tree!\n");
607             
608
609              {
610                FILE *infoFile = myfopen(infoFileName, "ab");
611
612                fprintf(infoFile, "\nWARNING, outgroups are not monophyletic, using first outgroup \"%s\"\n", tr->nameList[tr->outgroupNums[0]]);
613                fprintf(infoFile, "from the list to root the tree!\n");
614               
615                fclose(infoFile);
616              }
617
618
619              tr->start = tr->nodep[tr->outgroupNums[0]];
620             
621              rootedTree(treestr, tr, tr->start->back, printBranchLengths, printNames, printLikelihood, rellTree, 
622                         finalPrint, adef, perGene, branchLabelSupport, printSHSupport);
623            }
624          else
625            {       
626              if(isTip(tr->start->number, tr->rdta->numsp))
627                {
628                  printf("Outgroup-Monophyly ERROR; tr->start is a tip \n");
629                  errorExit(-1);
630                }
631              if(isTip(tr->start->back->number, tr->rdta->numsp))
632                {
633                  printf("Outgroup-Monophyly ERROR; tr->start is a tip \n");
634                  errorExit(-1);
635                }
636                     
637              rootedTree(treestr, tr, tr->start->back, printBranchLengths, printNames, printLikelihood, rellTree, 
638                         finalPrint, adef, perGene, branchLabelSupport, printSHSupport);
639            }
640         
641          rax_free(foundVector);
642          rax_free(nodeNumbers);
643          rax_free(subtrees);
644        }
645      else
646        {         
647          tr->start = tr->nodep[tr->outgroupNums[0]];   
648          rootedTree(treestr, tr, tr->start->back, printBranchLengths, printNames, printLikelihood, rellTree, 
649                     finalPrint, adef, perGene, branchLabelSupport, printSHSupports);
650        }     
651
652      tr->start = startNode;
653    }
654  else   
655    Tree2StringREC(treestr, tr, p, printBranchLengths, printNames, printLikelihood, rellTree, 
656                   finalPrint, perGene, branchLabelSupport, printSHSupport, printIC, printSHSupports); 
657   
658 
659  while (*treestr) treestr++;
660 
661  return treestr;
662}
663
664
665void printTreePerGene(tree *tr, analdef *adef, char *fileName, char *permission)
666{ 
667  FILE *treeFile;
668  char extendedTreeFileName[1024];
669  char buf[16];
670  int i;
671
672  assert(adef->perGeneBranchLengths);
673     
674  for(i = 0; i < tr->numBranches; i++) 
675    {
676      strcpy(extendedTreeFileName, fileName);
677      sprintf(buf,"%d", i);
678      strcat(extendedTreeFileName, ".PARTITION.");
679      strcat(extendedTreeFileName, buf);
680      /*printf("Partitiuon %d file %s\n", i, extendedTreeFileName);*/
681      Tree2String(tr->tree_string, tr, tr->start->back, TRUE, TRUE, FALSE, FALSE, TRUE, adef, i, FALSE, FALSE, FALSE, FALSE);
682      treeFile = myfopen(extendedTreeFileName, permission);
683      fprintf(treeFile, "%s", tr->tree_string);
684      fclose(treeFile);
685    } 
686   
687}
688
689
690
691/*=======================================================================*/
692/*                         Read a tree from a file                       */
693/*=======================================================================*/
694
695
696/*  1.0.A  Processing of quotation marks in comment removed
697 */
698
699static int treeFinishCom (FILE *fp, char **strp)
700{
701  int  ch;
702 
703  while ((ch = getc(fp)) != EOF && ch != ']') {
704    if (strp != NULL) *(*strp)++ = ch;    /* save character  */
705    if (ch == '[') {                      /* nested comment; find its end */
706      if ((ch = treeFinishCom(fp, strp)) == EOF)  break;
707      if (strp != NULL) *(*strp)++ = ch;  /* save closing ]  */
708    }
709  }
710 
711  if (strp != NULL) **strp = '\0';        /* terminate string  */
712  return  ch;
713} /* treeFinishCom */
714
715
716static int treeGetCh (FILE *fp)         /* get next nonblank, noncomment character */
717{ /* treeGetCh */
718  int  ch;
719
720  while ((ch = getc(fp)) != EOF) {
721    if (whitechar(ch)) ;
722    else if (ch == '[') {                   /* comment; find its end */
723      if ((ch = treeFinishCom(fp, (char **) NULL)) == EOF)  break;
724    }
725    else  break;
726  }
727 
728  return  ch;
729} /* treeGetCh */
730
731
732static boolean treeLabelEnd (int ch)
733{
734  switch (ch) 
735    {
736    case EOF: 
737    case '\0': 
738    case '\t': 
739    case '\n': 
740    case '\r': 
741    case ' ':
742    case ':': 
743    case ',':   
744    case '(':   
745    case ')': 
746    case ';':
747      return TRUE;
748    default:
749      break;
750    }
751  return FALSE;
752} 
753
754
755static boolean  treeGetLabel (FILE *fp, char *lblPtr, int maxlen)
756{
757  int      ch;
758  boolean  done, quoted, lblfound;
759
760  if (--maxlen < 0) 
761    lblPtr = (char *) NULL; 
762  else 
763    if (lblPtr == NULL) 
764      maxlen = 0;
765
766  ch = getc(fp);
767  done = treeLabelEnd(ch);
768
769  lblfound = ! done;
770  quoted = (ch == '\'');
771  if (quoted && ! done) 
772    {
773      ch = getc(fp); 
774      done = (ch == EOF);
775    }
776
777  while (! done) 
778    {
779      if (quoted) 
780        {
781          if (ch == '\'') 
782            {
783              ch = getc(fp); 
784              if (ch != '\'') 
785                break;
786            }
787        }
788      else 
789        if (treeLabelEnd(ch)) break;     
790
791      if (--maxlen >= 0) *lblPtr++ = ch;
792      ch = getc(fp);
793      if (ch == EOF) break;
794    }
795
796  if (ch != EOF)  (void) ungetc(ch, fp);
797
798  if (lblPtr != NULL) *lblPtr = '\0';
799
800  return lblfound;
801}
802
803
804static boolean  treeFlushLabel (FILE *fp)
805{ 
806  return  treeGetLabel(fp, (char *) NULL, (int) 0);
807} 
808
809
810
811
812static int treeFindTipByLabelString(char  *str, tree *tr, boolean check)                   
813{
814  int 
815    lookup = lookupWord(str, tr->nameHash);
816
817  if(lookup > 0)
818    {
819      if(check)
820        assert(! tr->nodep[lookup]->back);
821      return lookup;
822    }
823  else
824    { 
825      printf("ERROR: Cannot find tree species: %s\n", str);
826      return  0;
827    }
828}
829
830
831int treeFindTipName(FILE *fp, tree *tr, boolean check)
832{
833  char    str[nmlngth+2];
834  int      n;
835
836  if(treeGetLabel(fp, str, nmlngth+2))
837    n = treeFindTipByLabelString(str, tr, check);
838  else
839    n = 0;
840   
841
842  return  n;
843} 
844
845
846
847static void  treeEchoContext (FILE *fp1, FILE *fp2, int n)
848{ /* treeEchoContext */
849  int      ch;
850  boolean  waswhite;
851 
852  waswhite = TRUE;
853 
854  while (n > 0 && ((ch = getc(fp1)) != EOF)) {
855    if (whitechar(ch)) {
856      ch = waswhite ? '\0' : ' ';
857      waswhite = TRUE;
858    }
859    else {
860      waswhite = FALSE;
861    }
862   
863    if (ch > '\0') {putc(ch, fp2); n--;}
864  }
865} /* treeEchoContext */
866
867static boolean treeNeedCh (FILE *fp, int c1, char *where);
868
869
870static boolean treeProcessLength (FILE *fp, double *dptr, int *branchLabel, boolean storeBranchLabels, tree *tr)
871{
872  int
873    ch;
874 
875  if((ch = treeGetCh(fp)) == EOF) 
876    return FALSE;    /*  Skip comments */
877  (void) ungetc(ch, fp);
878 
879  if(fscanf(fp, "%lf", dptr) != 1) 
880    {
881      printf("ERROR: treeProcessLength: Problem reading branch length\n");
882      treeEchoContext(fp, stdout, 40);
883      printf("\n");
884      return  FALSE;
885    }
886   
887  if((ch = getc(fp)) != EOF)
888    {
889      if(ch == '[')
890        {
891          if(fscanf(fp, "%d", branchLabel) != 1)
892            goto handleError;         
893
894          //printf("Branch label: %d\n", *branchLabel);
895         
896          if((ch = getc(fp)) != ']')
897            {
898            handleError:
899              printf("ERROR: treeProcessLength: Problem reading branch label\n");
900              treeEchoContext(fp, stdout, 40);
901              printf("\n");
902              return FALSE;
903            }       
904
905          if(storeBranchLabels)
906            tr->branchLabelCounter = tr->branchLabelCounter + 1;
907
908        }
909      else
910        (void)ungetc(ch, fp);
911    }
912 
913  return  TRUE;
914}
915
916
917static int treeFlushLen (FILE  *fp, tree *tr)
918{
919  double 
920    dummy; 
921  int 
922    dummyLabel,     
923    ch;
924 
925  ch = treeGetCh(fp);
926 
927  if (ch == ':') 
928    {
929      ch = treeGetCh(fp);
930     
931      ungetc(ch, fp);
932      if(!treeProcessLength(fp, &dummy, &dummyLabel, FALSE, tr)) 
933        return 0;
934      return 1;   
935    }
936 
937 
938 
939  if (ch != EOF) (void) ungetc(ch, fp);
940  return 1;
941} 
942
943
944
945
946
947static boolean treeNeedCh (FILE *fp, int c1, char *where)
948{
949  int  c2;
950 
951  if ((c2 = treeGetCh(fp)) == c1)  return TRUE;
952 
953  printf("ERROR: Expecting '%c' %s tree; found:", c1, where);
954  if (c2 == EOF) 
955    {
956      printf("End-of-File");
957    }
958  else 
959    {           
960      ungetc(c2, fp);
961      treeEchoContext(fp, stdout, 40);
962    }
963  putchar('\n');
964   
965  printf("RAxML may be expecting to read a tree that contains branch lengths\n");
966
967  return FALSE;
968} 
969
970
971
972static boolean addElementLen (FILE *fp, tree *tr, nodeptr p, boolean readBranchLengths, boolean readNodeLabels, int *lcount, analdef *adef, boolean storeBranchLabels)
973{   
974  nodeptr  q;
975  int      n, ch, fres;
976 
977  if ((ch = treeGetCh(fp)) == '(') 
978    { 
979      n = (tr->nextnode)++;
980      if (n > 2*(tr->mxtips) - 2) 
981        {
982          if (tr->rooted || n > 2*(tr->mxtips) - 1) 
983            {
984              printf("ERROR: Too many internal nodes.  Is tree rooted?\n");
985              printf("       Deepest splitting should be a trifurcation.\n");
986              return FALSE;
987            }
988          else 
989            {
990              if(readNodeLabels)
991                {
992                  printf("The program will exit with an error in the next source code line\n");
993                  printf("You are probably trying to read in rooted trees with a RAxML option \n");
994                  printf("that for some reason expects unrooted binary trees\n\n");
995                }
996
997              assert(!readNodeLabels);
998              tr->rooted = TRUE;
999            }
1000        }
1001     
1002      q = tr->nodep[n];
1003
1004      if (! addElementLen(fp, tr, q->next, readBranchLengths, readNodeLabels, lcount, adef, storeBranchLabels))        return FALSE;
1005      if (! treeNeedCh(fp, ',', "in"))             return FALSE;
1006      if (! addElementLen(fp, tr, q->next->next, readBranchLengths, readNodeLabels, lcount, adef, storeBranchLabels))  return FALSE;
1007      if (! treeNeedCh(fp, ')', "in"))             return FALSE;
1008     
1009      if(readNodeLabels)
1010        {
1011          char label[64];
1012          int support;
1013
1014          if(treeGetLabel (fp, label, 10))
1015            {   
1016              int val = sscanf(label, "%d", &support);
1017     
1018              assert(val == 1);
1019
1020              /*printf("LABEL %s Number %d\n", label, support);*/
1021              p->support = q->support = support;
1022              /*printf("%d %d %d %d\n", p->support, q->support, p->number, q->number);*/
1023              assert(p->number > tr->mxtips && q->number > tr->mxtips);
1024              *lcount = *lcount + 1;
1025            }
1026        }
1027      else     
1028        (void) treeFlushLabel(fp);
1029    }
1030  else 
1031    {   
1032      ungetc(ch, fp);
1033      if ((n = treeFindTipName(fp, tr, TRUE)) <= 0)          return FALSE;
1034      q = tr->nodep[n];
1035      if (tr->start->number > n)  tr->start = q;
1036      (tr->ntips)++;
1037    }
1038 
1039  if(readBranchLengths)
1040    {
1041      double 
1042        branch;
1043     
1044      int 
1045        startCounter = tr->branchLabelCounter,
1046        endCounter,
1047        branchLabel = -1;
1048     
1049      if (! treeNeedCh(fp, ':', "in"))                 return FALSE;
1050      if (! treeProcessLength(fp, &branch, &branchLabel, storeBranchLabels, tr))           
1051        return FALSE;
1052
1053      endCounter = tr->branchLabelCounter;
1054     
1055      /*printf("Branch %8.20f %d\n", branch, tr->numBranches);*/
1056      if(adef->mode == CLASSIFY_ML)
1057        {
1058          double 
1059            x[NUM_BRANCHES];
1060         
1061          assert(tr->NumberOfModels == 1);
1062          assert(adef->useBinaryModelFile);
1063          assert(tr->numBranches == 1);
1064
1065          x[0] = exp(-branch / tr->fracchange);           
1066
1067          hookup(p, q, x, tr->numBranches);
1068        }
1069      else
1070        hookup(p, q, &branch, tr->numBranches);
1071
1072      if(storeBranchLabels && (endCounter > startCounter))
1073        {
1074          assert(!isTip(p->number, tr->mxtips) && !isTip(q->number, tr->mxtips));
1075          assert(branchLabel >= 0);
1076          p->support = q->support = branchLabel;
1077        }
1078    }
1079  else
1080    {
1081      fres = treeFlushLen(fp, tr);
1082      if(!fres) return FALSE;
1083     
1084      hookupDefault(p, q, tr->numBranches);
1085    }
1086  return TRUE;         
1087} 
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099static nodeptr uprootTree (tree *tr, nodeptr p, boolean readBranchLengths, boolean readConstraint)
1100{
1101  nodeptr  q, r, s, start;
1102  int      n, i;             
1103
1104  for(i = tr->mxtips + 1; i < 2 * tr->mxtips - 1; i++)
1105    assert(i == tr->nodep[i]->number);
1106
1107 
1108 
1109
1110  if(isTip(p->number, tr->mxtips) || p->back) 
1111    {
1112      printf("ERROR: Unable to uproot tree.\n");
1113      printf("       Inappropriate node marked for removal.\n");
1114      assert(0);
1115    }
1116 
1117  assert(p->back == (nodeptr)NULL);
1118 
1119  tr->nextnode = tr->nextnode - 1;
1120
1121  assert(tr->nextnode < 2 * tr->mxtips);
1122 
1123  n = tr->nextnode;               
1124 
1125  assert(tr->nodep[tr->nextnode]);
1126
1127  if (n != tr->mxtips + tr->ntips - 1) 
1128    {
1129      printf("ERROR: Unable to uproot tree.  Inconsistent\n");
1130      printf("       number of tips and nodes for rooted tree.\n");
1131      assert(0);
1132    }
1133
1134  q = p->next->back;                  /* remove p from tree */
1135  r = p->next->next->back;
1136  assert(p->back == (nodeptr)NULL);
1137   
1138  if(readBranchLengths)
1139    {
1140      double b[NUM_BRANCHES];
1141      int i;
1142      for(i = 0; i < tr->numBranches; i++)
1143        {
1144          b[i] = (r->z[i] + q->z[i]);     
1145        }
1146      hookup (q, r, b, tr->numBranches);
1147    }
1148  else   
1149    hookupDefault(q, r, tr->numBranches);   
1150
1151  tr->leftRootNode = p->next->back;
1152  tr->rightRootNode = p->next->next->back;
1153
1154  if(readConstraint && tr->grouped)
1155    {   
1156      if(tr->constraintVector[p->number] != 0)
1157        {
1158          printf("Root node to remove should have top-level grouping of 0\n");
1159          assert(0);
1160        }
1161    } 
1162 
1163  assert(!(isTip(r->number, tr->mxtips) && isTip(q->number, tr->mxtips))); 
1164
1165  assert(p->number > tr->mxtips);
1166
1167  if(tr->ntips > 2 && p->number != n) 
1168    {               
1169      q = tr->nodep[n];            /* transfer last node's conections to p */
1170      r = q->next;
1171      s = q->next->next;
1172           
1173      if(readConstraint && tr->grouped) 
1174        tr->constraintVector[p->number] = tr->constraintVector[q->number];       
1175     
1176      hookup(p,             q->back, q->z, tr->numBranches);   /* move connections to p */
1177      hookup(p->next,       r->back, r->z, tr->numBranches);
1178      hookup(p->next->next, s->back, s->z, tr->numBranches); 
1179
1180      if(q == tr->leftRootNode || q == tr->rightRootNode)
1181        {
1182          if(q == tr->leftRootNode)
1183            {
1184              if(p->back == tr->rightRootNode)
1185                tr->leftRootNode = p;
1186              else
1187                {
1188                   if(p->next->back == tr->rightRootNode)
1189                     tr->leftRootNode = p->next;
1190                   else
1191                     {
1192                       if(p->next->next->back == tr->rightRootNode)
1193                         tr->leftRootNode = p->next->next;
1194                       else
1195                         assert(0);
1196                     }
1197                }
1198            }
1199          else
1200            {
1201              assert(q == tr->rightRootNode);
1202
1203              if(p->back == tr->leftRootNode)
1204                tr->rightRootNode = p;
1205              else
1206                {
1207                   if(p->next->back == tr->leftRootNode)
1208                     tr->rightRootNode = p->next;
1209                   else
1210                     {
1211                       if(p->next->next->back == tr->leftRootNode)
1212                         tr->rightRootNode = p->next->next;
1213                       else
1214                         assert(0);
1215                     }
1216                }
1217            }
1218        }
1219     
1220      q->back = q->next->back = q->next->next->back = (nodeptr) NULL;
1221    }
1222  else   
1223    {
1224      assert(tr->ntips > 2);     
1225      p->back = p->next->back = p->next->next->back = (nodeptr) NULL;
1226    }
1227
1228 
1229 
1230  assert(tr->ntips > 2);
1231 
1232  start = findAnyTip(tr->nodep[tr->mxtips + 1], tr->mxtips);
1233 
1234  assert(isTip(start->number, tr->mxtips));
1235  tr->rooted = FALSE;
1236  return  start;
1237}
1238
1239
1240int treeReadLen (FILE *fp, tree *tr, boolean readBranches, boolean readNodeLabels, boolean topologyOnly, analdef *adef, boolean completeTree, boolean storeBranchLabels)
1241{
1242  nodeptr 
1243    p;
1244 
1245  int 
1246    i, 
1247    ch, 
1248    lcount = 0; 
1249
1250  tr->branchLabelCounter = 0;
1251
1252  for (i = 1; i <= tr->mxtips; i++) 
1253    {
1254      tr->nodep[i]->back = (node *) NULL; 
1255      if(topologyOnly)
1256        tr->nodep[i]->support = -1;
1257    }
1258
1259  for(i = tr->mxtips + 1; i < 2 * tr->mxtips; i++)
1260    {
1261      tr->nodep[i]->back = (nodeptr)NULL;
1262      tr->nodep[i]->next->back = (nodeptr)NULL;
1263      tr->nodep[i]->next->next->back = (nodeptr)NULL;
1264      tr->nodep[i]->number = i;
1265      tr->nodep[i]->next->number = i;
1266      tr->nodep[i]->next->next->number = i;
1267
1268      if(topologyOnly)
1269        {
1270          tr->nodep[i]->support = -2;
1271          tr->nodep[i]->next->support = -2;
1272          tr->nodep[i]->next->next->support = -2;
1273        }
1274    }
1275
1276  if(topologyOnly)
1277    tr->start       = tr->nodep[tr->mxtips];
1278  else
1279    tr->start       = tr->nodep[1];
1280
1281  tr->ntips       = 0;
1282  tr->nextnode    = tr->mxtips + 1;     
1283 
1284  for(i = 0; i < tr->numBranches; i++)
1285    tr->partitionSmoothed[i] = FALSE;
1286 
1287  tr->rooted      = FALSE; 
1288  tr->wasRooted   = FALSE;
1289
1290  p = tr->nodep[(tr->nextnode)++]; 
1291 
1292  while((ch = treeGetCh(fp)) != '(');
1293     
1294  if(!topologyOnly)
1295    {
1296      if(adef->mode != CLASSIFY_ML)
1297        {
1298          if(adef->mode != OPTIMIZE_BR_LEN_SCALER)
1299            assert(readBranches == FALSE && readNodeLabels == FALSE);
1300          else           
1301            assert(readBranches == TRUE && readNodeLabels == FALSE);           
1302        }
1303      else
1304        {
1305          if(adef->useBinaryModelFile)
1306            assert(readBranches == TRUE && readNodeLabels == FALSE);           
1307          else
1308            assert(readBranches == FALSE && readNodeLabels == FALSE);
1309        }
1310    }
1311 
1312       
1313  if (! addElementLen(fp, tr, p, readBranches, readNodeLabels, &lcount, adef, storeBranchLabels))                 
1314    assert(0);
1315  if (! treeNeedCh(fp, ',', "in"))               
1316    assert(0);
1317  if (! addElementLen(fp, tr, p->next, readBranches, readNodeLabels, &lcount, adef, storeBranchLabels))
1318    assert(0);
1319  if (! tr->rooted) 
1320    {
1321      if ((ch = treeGetCh(fp)) == ',') 
1322        { 
1323          if (! addElementLen(fp, tr, p->next->next, readBranches, readNodeLabels, &lcount, adef, storeBranchLabels))
1324            assert(0);     
1325        }
1326      else 
1327        {         
1328          /*  A rooted format */
1329         
1330          tr->rooted = TRUE;
1331          tr->wasRooted     = TRUE;
1332         
1333          if (ch != EOF)  (void) ungetc(ch, fp);
1334        }       
1335    }
1336  else 
1337    {           
1338      p->next->next->back = (nodeptr) NULL;
1339      tr->wasRooted     = TRUE;   
1340    }
1341
1342  if(!tr->rooted && adef->mode == ANCESTRAL_STATES)
1343    {
1344      printf("Error: The ancestral state computation mode requires a rooted tree as input, exiting ....\n");
1345      exit(0);
1346    }
1347
1348  if (! treeNeedCh(fp, ')', "in"))               
1349    assert(0);
1350
1351  if(topologyOnly)
1352    assert(!(tr->rooted && readNodeLabels));
1353
1354  (void) treeFlushLabel(fp);
1355 
1356  if (! treeFlushLen(fp, tr))                         
1357    assert(0);
1358 
1359  if (! treeNeedCh(fp, ';', "at end of"))       
1360    assert(0);
1361 
1362  if (tr->rooted) 
1363    {     
1364      assert(!readNodeLabels);
1365
1366      p->next->next->back = (nodeptr) NULL;     
1367      tr->start = uprootTree(tr, p->next->next, readBranches, FALSE);     
1368
1369       
1370      /*tr->leftRootNode  = p->back;
1371        tr->rightRootNode = p->next->back;   
1372      */
1373
1374      if (! tr->start)                             
1375        {
1376          printf("FATAL ERROR UPROOTING TREE\n");
1377          assert(0);
1378        }   
1379    }
1380  else   
1381    tr->start = findAnyTip(p, tr->rdta->numsp);   
1382 
1383   if(!topologyOnly || adef->mode == CLASSIFY_MP)
1384    {     
1385      assert(tr->ntips <= tr->mxtips);
1386     
1387
1388      if(tr->ntips < tr->mxtips)
1389        {
1390          if(completeTree)
1391            {
1392              printBothOpen("Hello this is your friendly RAxML tree parsing routine\n");
1393              printBothOpen("The RAxML option you are uisng requires to read in only complete trees\n");
1394              printBothOpen("with %d taxa, there is at least one tree with %d taxa though ... exiting\n", tr->mxtips, tr->ntips);
1395              exit(-1);
1396            }
1397          else
1398            {
1399              if(adef->computeDistance)
1400                {
1401                  printBothOpen("Error: pairwise distance computation only allows for complete, i.e., containing all taxa\n");
1402                  printBothOpen("bifurcating starting trees\n");
1403                  exit(-1);
1404                }     
1405              if(adef->mode == CLASSIFY_ML || adef->mode == CLASSIFY_MP)
1406                {       
1407                  printBothOpen("RAxML placement algorithm: You provided a reference tree with %d taxa; alignmnet has %d taxa\n", tr->ntips, tr->mxtips);                 
1408                  printBothOpen("%d query taxa will be placed using %s\n", tr->mxtips - tr->ntips, (adef->mode == CLASSIFY_ML)?"maximum likelihood":"parsimony");
1409                  if(adef->mode == CLASSIFY_ML)
1410                    classifyML(tr, adef);         
1411                  else
1412                    {
1413                      assert(adef->mode == CLASSIFY_MP);
1414                      classifyMP(tr, adef);
1415                    }
1416                }
1417              else
1418                {
1419                  printBothOpen("You provided an incomplete starting tree %d alignmnet has %d taxa\n", tr->ntips, tr->mxtips);   
1420                  makeParsimonyTreeIncomplete(tr, adef);                         
1421                }   
1422            }
1423        }
1424      else
1425        {
1426          if(adef->mode == PARSIMONY_ADDITION)
1427            {
1428              printBothOpen("Error you want to add sequences to a trees via MP stepwise addition, but \n");
1429              printBothOpen("you have provided an input tree that already contains all taxa\n");
1430              exit(-1);
1431            }
1432          if(adef->mode == CLASSIFY_ML || adef->mode == CLASSIFY_MP)
1433            {
1434              printBothOpen("Error you want to place query sequences into a tree using %s, but\n", tr->mxtips - tr->ntips, (adef->mode == CLASSIFY_ML)?"maximum likelihood":"parsimony");
1435              printBothOpen("you have provided an input tree that already contains all taxa\n");
1436              exit(-1);
1437            }
1438        }
1439   
1440      onlyInitrav(tr, tr->start);
1441    }
1442 
1443 
1444  return lcount;
1445}
1446
1447
1448
1449/********************************MULTIFURCATIONS************************************************/
1450
1451
1452static boolean  addElementLenMULT (FILE *fp, tree *tr, nodeptr p, int partitionCounter)
1453{ 
1454  nodeptr  q, r, s;
1455  int      n, ch, fres, rn;
1456  double randomResolution;
1457  int old;
1458   
1459  tr->constraintVector[p->number] = partitionCounter; 
1460
1461  if ((ch = treeGetCh(fp)) == '(') 
1462    {
1463      partCount++;
1464      old = partCount;       
1465     
1466      n = (tr->nextnode)++;
1467      if (n > 2*(tr->mxtips) - 2) 
1468        {
1469          if (tr->rooted || n > 2*(tr->mxtips) - 1) 
1470            {
1471              printf("ERROR: Too many internal nodes.  Is tree rooted?\n");
1472              printf("       Deepest splitting should be a trifurcation.\n");
1473              return FALSE;
1474            }
1475          else 
1476            {
1477              tr->rooted = TRUE;           
1478            }
1479        }
1480      q = tr->nodep[n];
1481      tr->constraintVector[q->number] = partCount;
1482      if (! addElementLenMULT(fp, tr, q->next, old))        return FALSE;
1483      if (! treeNeedCh(fp, ',', "in"))             return FALSE;
1484      if (! addElementLenMULT(fp, tr, q->next->next, old))  return FALSE;
1485                 
1486      hookupDefault(p, q, tr->numBranches);
1487
1488      while((ch = treeGetCh(fp)) == ',')
1489        { 
1490          n = (tr->nextnode)++;
1491          if (n > 2*(tr->mxtips) - 2) 
1492            {
1493              if (tr->rooted || n > 2*(tr->mxtips) - 1) 
1494                {
1495                  printf("ERROR: Too many internal nodes.  Is tree rooted?\n");
1496                  printf("       Deepest splitting should be a trifurcation.\n");
1497                  return FALSE;
1498                }
1499              else 
1500                {
1501                  tr->rooted = TRUE;
1502                }
1503            }
1504          r = tr->nodep[n];
1505          tr->constraintVector[r->number] = partCount;   
1506
1507          rn = randomInt(10000);
1508          if(rn == 0) 
1509            randomResolution = 0;
1510          else 
1511            randomResolution = ((double)rn)/10000.0;
1512                 
1513           if(randomResolution < 0.5)
1514            {       
1515              s = q->next->back;             
1516              r->back = q->next;
1517              q->next->back = r;             
1518              r->next->back = s;
1519              s->back = r->next;             
1520              addElementLenMULT(fp, tr, r->next->next, old);         
1521            }
1522          else
1523            {     
1524              s = q->next->next->back;       
1525              r->back = q->next->next;
1526              q->next->next->back = r;       
1527              r->next->back = s;
1528              s->back = r->next;             
1529              addElementLenMULT(fp, tr, r->next->next, old);         
1530            }                     
1531        }       
1532
1533      if(ch != ')')
1534        {
1535          printf("Missing /) in treeReadLenMULT\n");
1536          exit(-1);             
1537        }
1538       
1539
1540
1541      (void) treeFlushLabel(fp);
1542    }
1543  else 
1544    {                             
1545      ungetc(ch, fp);
1546      if ((n = treeFindTipName(fp, tr, TRUE)) <= 0)          return FALSE;
1547      q = tr->nodep[n];     
1548      tr->constraintVector[q->number] = partitionCounter;
1549
1550      if (tr->start->number > n)  tr->start = q;
1551      (tr->ntips)++;
1552      hookupDefault(p, q, tr->numBranches);
1553    }
1554 
1555  fres = treeFlushLen(fp, tr);
1556  if(!fres) return FALSE;
1557   
1558  return TRUE;         
1559} 
1560
1561
1562
1563
1564
1565boolean treeReadLenMULT (FILE *fp, tree *tr, analdef *adef)
1566{
1567  nodeptr  p, r, s;
1568  int      i, ch, n, rn;
1569  int partitionCounter = 0;
1570  double randomResolution;
1571
1572  srand((unsigned int) time(NULL));
1573 
1574  for(i = 0; i < 2 * tr->mxtips; i++)
1575    tr->constraintVector[i] = -1;
1576
1577  for (i = 1; i <= tr->mxtips; i++) 
1578    tr->nodep[i]->back = (node *) NULL;
1579
1580  for(i = tr->mxtips + 1; i < 2 * tr->mxtips; i++)
1581    {
1582      tr->nodep[i]->back = (nodeptr)NULL;
1583      tr->nodep[i]->next->back = (nodeptr)NULL;
1584      tr->nodep[i]->next->next->back = (nodeptr)NULL;
1585      tr->nodep[i]->number = i;
1586      tr->nodep[i]->next->number = i;
1587      tr->nodep[i]->next->next->number = i;
1588    }
1589
1590
1591  tr->start       = tr->nodep[tr->mxtips];
1592  tr->ntips       = 0;
1593  tr->nextnode    = tr->mxtips + 1;
1594 
1595  for(i = 0; i < tr->numBranches; i++)
1596    tr->partitionSmoothed[i] = FALSE;
1597
1598  tr->rooted      = FALSE;
1599 
1600  p = tr->nodep[(tr->nextnode)++]; 
1601  while((ch = treeGetCh(fp)) != '(');
1602     
1603  if (! addElementLenMULT(fp, tr, p, partitionCounter))                 return FALSE;
1604  if (! treeNeedCh(fp, ',', "in"))                return FALSE;
1605  if (! addElementLenMULT(fp, tr, p->next, partitionCounter))           return FALSE;
1606  if (! tr->rooted) 
1607    {
1608      if ((ch = treeGetCh(fp)) == ',') 
1609        {       
1610          if (! addElementLenMULT(fp, tr, p->next->next, partitionCounter)) return FALSE;
1611
1612          while((ch = treeGetCh(fp)) == ',')
1613            { 
1614              n = (tr->nextnode)++;
1615              assert(n <= 2*(tr->mxtips) - 2);
1616       
1617              r = tr->nodep[n]; 
1618              tr->constraintVector[r->number] = partitionCounter;         
1619             
1620              rn = randomInt(10000);
1621              if(rn == 0) 
1622                randomResolution = 0;
1623              else 
1624                randomResolution = ((double)rn)/10000.0;
1625
1626
1627              if(randomResolution < 0.5)
1628                {       
1629                  s = p->next->next->back;               
1630                  r->back = p->next->next;
1631                  p->next->next->back = r;               
1632                  r->next->back = s;
1633                  s->back = r->next;             
1634                  addElementLenMULT(fp, tr, r->next->next, partitionCounter);   
1635                }
1636              else
1637                {
1638                  s = p->next->back;             
1639                  r->back = p->next;
1640                  p->next->back = r;             
1641                  r->next->back = s;
1642                  s->back = r->next;             
1643                  addElementLenMULT(fp, tr, r->next->next, partitionCounter);
1644                }
1645            }                             
1646
1647          if(ch != ')')
1648            {
1649              printf("Missing /) in treeReadLenMULT\n");
1650              exit(-1);                               
1651            }
1652          else
1653            ungetc(ch, fp);
1654        }
1655      else 
1656        { 
1657          tr->rooted = TRUE;
1658          if (ch != EOF)  (void) ungetc(ch, fp);
1659        }       
1660    }
1661  else 
1662    {
1663      p->next->next->back = (nodeptr) NULL;
1664    }
1665   
1666  if (! treeNeedCh(fp, ')', "in"))                return FALSE;
1667  (void) treeFlushLabel(fp);
1668  if (! treeFlushLen(fp, tr))                         return FALSE;
1669   
1670  if (! treeNeedCh(fp, ';', "at end of"))       return FALSE;
1671 
1672
1673  if (tr->rooted) 
1674    {       
1675      p->next->next->back = (nodeptr) NULL;
1676      tr->start = uprootTree(tr, p->next->next, FALSE, TRUE);
1677      if (! tr->start)                              return FALSE;
1678    }
1679  else 
1680    {     
1681      tr->start = findAnyTip(p, tr->rdta->numsp);
1682    }
1683
1684 
1685 
1686
1687  if(tr->ntips < tr->mxtips)         
1688    makeParsimonyTreeIncomplete(tr, adef);         
1689
1690
1691  if(!adef->rapidBoot)
1692    onlyInitrav(tr, tr->start);
1693  return TRUE; 
1694}
1695
1696
1697
1698
1699
1700
1701void getStartingTree(tree *tr, analdef *adef)
1702{
1703  tr->likelihood = unlikely;
1704 
1705  if(adef->restart) 
1706    {                       
1707      INFILE = myfopen(tree_file, "rb");       
1708                               
1709      if(!adef->grouping)       
1710        {
1711          switch(adef->mode)
1712            {
1713            case ANCESTRAL_STATES:         
1714              assert(!tr->saveMemory);
1715
1716              tr->leftRootNode  = (nodeptr)NULL;
1717              tr->rightRootNode = (nodeptr)NULL;
1718
1719              treeReadLen(INFILE, tr, FALSE, FALSE, FALSE, adef, TRUE, FALSE);
1720
1721              assert(tr->leftRootNode && tr->rightRootNode);
1722              break;
1723            case CLASSIFY_MP:
1724              treeReadLen(INFILE, tr, TRUE, FALSE, TRUE, adef, FALSE, FALSE);
1725              break;
1726            case OPTIMIZE_BR_LEN_SCALER:
1727              treeReadLen(INFILE, tr, TRUE, FALSE, FALSE, adef, TRUE, FALSE);
1728              break;
1729            case CLASSIFY_ML:
1730              if(adef->useBinaryModelFile)
1731                {
1732                  if(tr->saveMemory)                             
1733                    treeReadLen(INFILE, tr, TRUE, FALSE, TRUE, adef, FALSE, FALSE);                           
1734                  else             
1735                    treeReadLen(INFILE, tr, TRUE, FALSE, FALSE, adef, FALSE, FALSE);
1736                }
1737              else
1738                {
1739                  if(tr->saveMemory)                             
1740                    treeReadLen(INFILE, tr, FALSE, FALSE, TRUE, adef, FALSE, FALSE);                           
1741                  else             
1742                    treeReadLen(INFILE, tr, FALSE, FALSE, FALSE, adef, FALSE, FALSE);
1743                }
1744              break;
1745            default:         
1746              if(tr->saveMemory)                                 
1747                treeReadLen(INFILE, tr, FALSE, FALSE, TRUE, adef, FALSE, FALSE);                               
1748              else                 
1749                treeReadLen(INFILE, tr, FALSE, FALSE, FALSE, adef, FALSE, FALSE);
1750              break;
1751            }
1752        }
1753      else
1754        {
1755          assert(adef->mode != ANCESTRAL_STATES);
1756
1757          partCount = 0;
1758          if (! treeReadLenMULT(INFILE, tr, adef))
1759            exit(-1);
1760        }                                                                         
1761
1762      if(adef->mode == PARSIMONY_ADDITION)
1763        return; 
1764
1765      if(adef->mode != CLASSIFY_MP)
1766        {
1767          if(adef->mode == OPTIMIZE_BR_LEN_SCALER)
1768            {
1769              assert(tr->numBranches == tr->NumberOfModels);
1770              scaleBranches(tr, TRUE);
1771              evaluateGenericInitrav(tr, tr->start);                                 
1772            }
1773          else
1774            {
1775              evaluateGenericInitrav(tr, tr->start); 
1776              treeEvaluate(tr, 1);
1777            }
1778        }
1779               
1780      fclose(INFILE);
1781    }
1782  else
1783    { 
1784      assert(adef->mode != PARSIMONY_ADDITION &&
1785             adef->mode != MORPH_CALIBRATOR   &&
1786             adef->mode != ANCESTRAL_STATES   &&
1787             adef->mode != OPTIMIZE_BR_LEN_SCALER);
1788
1789      if(adef->randomStartingTree)       
1790        makeRandomTree(tr, adef);                                         
1791      else
1792        makeParsimonyTree(tr, adef);                                           
1793     
1794      if(adef->startingTreeOnly)
1795        {
1796          printStartingTree(tr, adef, TRUE);
1797          exit(0);
1798        }
1799      else               
1800        printStartingTree(tr, adef, FALSE);                     
1801           
1802     
1803      evaluateGenericInitrav(tr, tr->start);   
1804
1805     
1806     
1807      treeEvaluate(tr, 1);               
1808
1809     
1810     
1811    }         
1812
1813  tr->start = tr->nodep[1];
1814}
1815
1816
1817
1818/****** functions for reading true multi-furcating trees *****/
1819
1820/****************************************************************************/
1821
1822static boolean addMultifurcation (FILE *fp, tree *tr, nodeptr _p, analdef *adef, int *nextnode)
1823{   
1824  nodeptr 
1825    p, 
1826    initial_p;
1827 
1828  int     
1829    n, 
1830    ch, 
1831    fres;
1832 
1833  if ((ch = treeGetCh(fp)) == '(') 
1834    { 
1835      int 
1836        i = 0;     
1837     
1838      initial_p = p = tr->nodep[*nextnode];     
1839      *nextnode = *nextnode + 1;
1840
1841      do
1842        {                 
1843          p->next = tr->nodep[*nextnode];       
1844          *nextnode = *nextnode + 1;
1845          p = p->next;
1846       
1847          addMultifurcation(fp, tr, p, adef, nextnode);   
1848          i++;
1849        } 
1850      while((ch = treeGetCh(fp)) == ',');
1851
1852      ungetc(ch, fp);
1853
1854      p->next = initial_p;
1855           
1856      if (! treeNeedCh(fp, ')', "in"))               
1857        assert(0);                   
1858
1859      treeFlushLabel(fp);
1860    }
1861  else 
1862    {   
1863      ungetc(ch, fp);
1864      if ((n = treeFindTipName(fp, tr, FALSE)) <= 0)         
1865        return FALSE;
1866      p = tr->nodep[n];
1867      initial_p = p;
1868      tr->start = p;
1869      (tr->ntips)++;
1870    }
1871 
1872 
1873  fres = treeFlushLen(fp, tr);
1874  if(!fres) 
1875    return FALSE;
1876     
1877  hookupDefault(initial_p, _p, tr->numBranches);
1878 
1879  return TRUE;         
1880} 
1881
1882static void printMultiFurc(nodeptr p, tree *tr)
1883{ 
1884  if(isTip(p->number, tr->mxtips))   
1885    printf("%s", tr->nameList[p->number]);   
1886  else
1887    {
1888      nodeptr
1889        q = p->next;     
1890     
1891      printf("(");
1892
1893      while(q != p)
1894        {       
1895          printMultiFurc(q->back, 
1896                         tr);
1897          q = q->next;
1898          if(q != p)
1899            printf(",");
1900        }
1901
1902      printf(")");
1903    }
1904}
1905
1906void allocateMultifurcations(tree *tr, tree *smallTree)
1907{ 
1908  int
1909    i,
1910    tips,
1911    inter; 
1912
1913  smallTree->numBranches = tr->numBranches;
1914
1915  smallTree->mxtips = tr->mxtips;
1916
1917  smallTree->nameHash = tr->nameHash;
1918
1919  tips  = tr->mxtips;
1920  inter = tr->mxtips - 1;
1921 
1922  smallTree->nodep = (nodeptr *)rax_malloc((tips + 3 * inter) * sizeof(nodeptr));
1923
1924  smallTree->nodep[0] = (node *) NULL;
1925
1926  for (i = 1; i <= tips; i++)
1927    {
1928      smallTree->nodep[i] = (nodeptr)rax_malloc(sizeof(node));     
1929      memcpy(smallTree->nodep[i], tr->nodep[i], sizeof(node));
1930      smallTree->nodep[i]->back = (node *) NULL;
1931      smallTree->nodep[i]->next = (node *) NULL;
1932    }
1933
1934  for(i = tips + 1; i < tips + 3 * inter; i++)
1935    {     
1936      smallTree->nodep[i] = (nodeptr)rax_malloc(sizeof(node));
1937      smallTree->nodep[i]->number = i;     
1938      smallTree->nodep[i]->back = (node *) NULL;
1939      smallTree->nodep[i]->next = (node *) NULL;
1940    }
1941 
1942}
1943
1944void freeMultifurcations(tree *tr)
1945{
1946  int
1947    i,
1948    tips  = tr->mxtips,
1949    inter = tr->mxtips - 1; 
1950
1951  for (i = 1; i < tips + 3 * inter; i++)
1952    rax_free(tr->nodep[i]);
1953 
1954  rax_free(tr->nodep);
1955}
1956
1957static void relabelInnerNodes(nodeptr p, tree *tr, int n, int *nodeCounter)
1958{
1959  if(isTip(p->number, tr->mxtips))
1960    {
1961      assert(0);
1962    }
1963  else
1964    {
1965      nodeptr
1966        q = p->next;
1967
1968      int 
1969        _n = n;
1970
1971      tr->nodep[p->number]->number = n;
1972      p->x = 1;
1973     
1974      while(q != p)
1975        {
1976          tr->nodep[q->number]->number = n;     
1977          q->x = 0;
1978         
1979          if(!isTip(q->back->number, tr->mxtips))
1980            {
1981              _n++;
1982              *nodeCounter = *nodeCounter + 1;
1983              relabelInnerNodes(q->back, tr, _n, nodeCounter);
1984            }
1985          q = q->next;
1986        } 
1987    }
1988}
1989
1990
1991int readMultifurcatingTree(FILE *fp, tree *tr, analdef *adef)
1992{
1993  nodeptr 
1994    p,
1995    initial_p;
1996 
1997  int   
1998    innerBranches = 0,
1999    nextnode,
2000    i, 
2001    ch,
2002    tips  = tr->mxtips,
2003    inter = tr->mxtips - 1; 
2004 
2005  //clean up before parsing !
2006   
2007  for (i = 1; i < tips + 3 * inter; i++)     
2008    {     
2009      tr->nodep[i]->back = (node *) NULL;
2010      tr->nodep[i]->next = (node *) NULL;   
2011      tr->nodep[i]->x = 0;
2012    }
2013 
2014  for(i = tips + 1; i < tips + 3 * inter; i++)   
2015    tr->nodep[i]->number = i;
2016
2017  tr->ntips = 0;
2018  nextnode  = tr->mxtips + 1;         
2019
2020  while((ch = treeGetCh(fp)) != '(');           
2021
2022  i = 0;
2023
2024  do
2025    {         
2026      if(i == 0)
2027        {
2028          initial_p = p = tr->nodep[nextnode];   
2029          nextnode++;
2030        }
2031      else
2032        {
2033          p->next = tr->nodep[nextnode];                 
2034          p = p->next; 
2035          nextnode++;
2036        }
2037     
2038      addMultifurcation(fp, tr, p, adef, &nextnode);       
2039                   
2040      i++;
2041    } 
2042  while((ch = treeGetCh(fp)) == ',');
2043   
2044  if(i < 3)
2045    {
2046      printBothOpen("You need to provide unrooted input trees!\n");
2047      assert(0);
2048    }
2049 
2050  ungetc(ch, fp);
2051 
2052  p->next = initial_p;
2053 
2054  if (! treeNeedCh(fp, ')', "in"))               
2055    assert(0); 
2056
2057  (void)treeFlushLabel(fp);
2058 
2059  if (! treeFlushLen(fp, tr))                         
2060    assert(0);
2061 
2062  if (! treeNeedCh(fp, ';', "at end of"))       
2063    assert(0);
2064   
2065  //printf("%d tips found, %d inner nodes used start %d maxtips %d\n", tr->ntips, tr->nextnode - tr->mxtips, tr->start->number, tr->mxtips);
2066
2067  assert(isTip(tr->start->number, tr->mxtips));
2068
2069  relabelInnerNodes(tr->start->back, tr, tr->mxtips + 1, &innerBranches);
2070
2071  //printf("Inner branches %d\n", innerBranches);
2072
2073  if(0)
2074    {
2075      printf("(");
2076      printMultiFurc(tr->start, tr);
2077      printf(",");
2078      printMultiFurc(tr->start->back, tr);
2079      printf(");\n");
2080    }
2081
2082  return innerBranches;
2083}
2084
Note: See TracBrowser for help on using the repository browser.