source: tags/arb_5.2/GDE/AxML/axml.c

Last change on this file was 5909, checked in by westram, 15 years ago
  • use strchr and strstr from standard lib
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 157.0 KB
Line 
1#define programName        "AxMl"
2#define programVersion     "1.1.0"
3#define programVersionInt   10202
4#define programDate        "February, 2002"
5#define programDateInt      20000212
6
7/*Time measurment */
8#include  <sys/times.h>
9#include  <sys/types.h>
10#include <sys/time.h>
11#include <time.h>
12double accTime = 0.0;
13double globTime = 0.0;
14struct timeval ttime;
15
16long flopBlocks = 0;
17
18double gettime()
19{
20  gettimeofday(&ttime , NULL);
21  return ttime.tv_sec + ttime.tv_usec * 0.000001;
22}
23/*Time measurment*/
24
25/* AxMl, a program for estimation of phylogenetic trees from sequences
26 * implementing SEVs (Subtree Equality Vectors) Copyright (C) 2002 by
27 * Alexandros P. Stamatakis.
28 *  Derived from:
29 *  fastDNAml, a program for estimation of phylogenetic trees from sequences.
30 *  Copyright (C) 1998, 1999, 2000 by Gary J. Olsen
31 *
32 *  This program is free software; you may redistribute it and/or modify it
33 *  under the terms of the GNU General Public License as published by the Free
34 *  Software Foundation; either version 2 of the License, or (at your option)
35 *  any later version.
36 *
37 *  This program is distributed in the hope that it will be useful, but
38 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
39 *  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
40 *  for more details.
41 *
42 *  You should have received a copy of the GNU General Public License along
43 *  with this program; if not, write to the Free Software Foundation, Inc.,
44 *  59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
45 *
46 *  For any other enquiries write to Gary J. Olsen, Department of Microbiology,
47 *  University of Illinois, Urbana, IL  61801, USA
48 *
49 *  Or send E-mail to gary@phylo.life.uiuc.edu
50 *
51 *
52 *  fastDNAml is based in part on the program dnaml by Joseph Felsenstein.
53 *
54 *  Copyright notice from dnaml:
55 *
56 *     version 3.3. (c) Copyright 1986, 1990 by the University of Washington
57 *     and Joseph Felsenstein.  Written by Joseph Felsenstein.  Permission is
58 *     granted to copy and use this program provided no fee is charged for it
59 *     and provided that this copyright notice is not removed.
60 *
61 *
62 *  When publishing work that based on results from fastDNAml please cite:
63 *
64 *  Felsenstein, J.  1981.  Evolutionary trees from DNA sequences:
65 *  A maximum likelihood approach.  J. Mol. Evol. 17: 368-376.
66 *
67 *  and
68 *
69 *  Olsen, G. J., Matsuda, H., Hagstrom, R., and Overbeek, R.  1994.
70 *  fastDNAml:  A tool for construction of phylogenetic trees of DNA
71 *  sequences using maximum likelihood.  Comput. Appl. Biosci. 10: 41-48.
72 */
73
74/*  Conversion to C and changes in sequential code by Gary Olsen, 1991-1994
75 *
76 *  p4 version by Hideo Matsuda and Ross Overbeek, 1991-1993
77 */
78
79/*
80 *  1.0    March 14, 1992
81 *         Initial "release" version
82 *
83 *  1.0.1  March 18, 1992
84 *         Add ntaxa to tree comments
85 *         Set minimum branch length on reading tree
86 *         Add blanks around operators in treeString (for prolog parsing)
87 *         Add program version to treeString comments
88 *
89 *  1.0.2  April 6, 1992
90 *         Improved option line diagnostics
91 *         Improved auxiliary line diagnostics
92 *         Removed some trailing blanks from output
93 *
94 *  1.0.3  April 6, 1992
95 *         Checkpoint trees that do not need any optimization
96 *         Print restart tree likelihood before optimizing
97 *         Fix treefile option so that it really toggles
98 *
99 *  1.0.4  July 13, 1992
100 *         Add support for tree fact (instead of true Newick tree) in
101 *            processTreeCom, treeReadLen, str_processTreeCom and
102 *            str_treeReadLen
103 *         Use bit operations in randum
104 *         Correct error in bootstrap mask used with weighting mask
105 *
106 *  1.0.5  August 22, 1992
107 *         Fix reading of underscore as first nonblank character in name
108 *         Add strchr and strstr functions to source code
109 *         Add output treefile name to message "Tree also written ..."
110 *
111 *  1.0.6  November 20, 1992
112 *         Change (! nsites) test in setupTopol to (nsites == 0) for MIPS R4000
113 *         Add vectorizing compiler directives for CRAY
114 *         Include updates and corrections to parallel code from H. Matsuda
115 *
116 *  1.0.7  March 25, 1993
117 *         Remove translation of underlines in taxon names
118 *
119 *  1.0.8  April 30, 1993
120 *         Remove version number from fastDNAml.h file name
121 *
122 *  1.0.9  August 12, 1993
123 *         Version was never released.
124 *         Redefine treefile formats and default:
125 *             0  None
126 *             1  Newick
127 *             2  Prolog
128 *             3  PHYLIP (Default)
129 *         Remove quote marks and comment from PHYLIP treefile format.
130 *
131 *  1.1.0  September 3-5, 1993
132 *         Arrays of size maxpatterns moved from stack to heap (mallocs) in
133 *            evaluateslope, makenewz, and cmpBestTrees.
134 *         Correct [maxsites] to [maxpatterns] in temporary array definitions
135 *            in Vectorize code of newview and evaluate.  (These should also
136 *            get converted to use malloc() at some point.)
137 *         Change randum to use 12 bit segments, not 6.  Change its seed
138 *            parameter to long *.
139 *         Remove the code that took the absolute value of random seeds.
140 *         Correct integer divide artifact in setting default transition/
141 *            transversion parameter values.
142 *         When transition/transversion ratio is "reset", change to small
143 *            value, not the program default.
144 *         Report the "reset" transition/transversion ratio in the output.
145 *         Move global data into analdef, rawDNA, and crunchedDNA structures.
146 *         Change names of routines white and digit to whitechar and digitchar.
147 *         Convert y[] to yType, which is normally char, but is int if the
148 *            Vectorize flag is set.
149 *         Split option line reading out of getoptions routine.
150 *
151 *  1.1.1  September 30, 1994
152 *         Incorporate changes made in 1.0.A (Feb. 11, 1994):
153 *            Remove processing of quotation marks within comments.
154 *            Break label finding into copy to string and find tip.
155 *            Generalize tree reading to read trees when names are and are not
156 *               already known.
157 *            Remove absolute value from randum seed reading.
158 *         Include integer version number and program date.
159 *         Remove maxsite, maxpatterns and maxsp limitations.
160 *         Incorporate code for retaining multiple trees.
161 *         Activate code for Hasegawa & Kishino test of tree differences.
162 *         Make quick add the default, with Q turning it off.
163 *         Make emperical frequencies the option with F turning it off.
164 *         Allow a residue frequency option line anywhere in the options.
165 *         Increase string length passed to treeString (should be length
166 *               checked, but ...)
167 *         Introduce (Sept.30) and fix (Oct. 26) bug in bootstrap sampling.
168 *         Fix error when user frequencies are last line and start with F.
169 *
170 *  1.2    September 5, 1997
171 *         Move likelihood components into structure.
172 *         Change rawDNA to rawdata.
173 *         Change crunchedDNA to cruncheddata.
174 *         Recast the likelihoods per site into an array of stuctures,
175 *               where each stucture (likelivector) includes the likelihoods
176 *               of each residue type at the site, and a magnitude scale
177 *               factor (exp).  This requires changing the space allocation,
178 *               newview, makenewz, evaluate, and sigma.
179 *         Change code of newview to rescale likelihoods up by 2**256 when
180 *               the largest value falls below 2**-256.  This should solve
181 *               floating point underflow for all practical sized trees.
182 *               No changes are necessary in makenewz or sigma, since only
183 *               relative likelihoods are necessary.
184 *
185 *  1.2.1  March 9, 1998
186 *         Convert likelihood adjustment factor (2**256) to a constant.
187 *         Fix vectorized calculation of likelihood (error introduced in 1.2)
188 *
189 *  1.2.2  December 23, 1998
190 *         General code clean-up.
191 *         Convert to function definitions with parameter type lists
192 *
193 *  1.2.2  January 3, 2000
194 *         Add copyright and license information
195 *         Make this the current release version
196 */
197
198#ifdef Master
199#  undef  Master
200#  define Master     1
201#  define Slave      0
202#  define Sequential 0
203#else
204#  ifdef Slave
205#    undef Slave
206#    define Master     0
207#    define Slave      1
208#    define Sequential 0
209#  else
210#    ifdef Sequential
211#      undef Sequential
212#    endif
213#    define Master     0
214#    define Slave      0
215#    define Sequential 1
216#  endif
217#endif
218
219#ifdef  CRAY
220#  define  Vectorize
221#endif
222
223#ifdef  Vectorize
224#  define maxpatterns  10000  /* maximum number of different site patterns */
225#endif
226
227#include <stdio.h>
228#include <math.h>
229#include "axml.h"  /*  Requires version 1.2  */
230
231#if Master || Slave
232#  include "p4.h"
233#  include "comm_link.h"
234#endif
235
236/*  Global variables */
237
238xarray       *usedxtip, *freextip;
239
240#ifdef FLOP_BLOCK_COUNTER
241unsigned long flopBlock = 0;
242#endif
243
244#if Sequential     /*  Use standard input */
245#  undef   DNAML_STEP
246#  define  DNAML_STEP  0
247#  define  INFILE  stdin
248#endif
249
250#if Master
251#  define MAX_SEND_AHEAD 400
252  char   *best_tr_recv = NULL;     /* these are used for flow control */
253  double  best_lk_recv;
254  int     send_ahead = 0;          /* number of outstanding sends */
255
256#  ifdef DNAML_STEP
257#    define  DNAML_STEP  1
258#  endif
259#  define  INFILE   Seqf
260#  define  OUTFILE  Outf
261  FILE  *INFILE, *OUTFILE;
262  comm_block comm_slave;
263#endif
264
265#if Slave
266#  undef   DNAML_STEP
267#  define  DNAML_STEP  0
268#  define  INFILE   Seqf
269#  define  OUTFILE  Outf
270  FILE  *INFILE, *OUTFILE;
271  comm_block comm_master;
272#endif
273
274#if Debug
275  FILE *debug;
276#endif
277
278#if DNAML_STEP
279  int begin_step_time, end_step_time;
280#  define  REPORT_ADD_SPECS  p4_send(DNAML_ADD_SPECS, DNAML_HOST_ID, NULL, 0)
281#  define  REPORT_SEND_TREE  p4_send(DNAML_SEND_TREE, DNAML_HOST_ID, NULL, 0)
282#  define  REPORT_RECV_TREE  p4_send(DNAML_RECV_TREE, DNAML_HOST_ID, NULL, 0)
283#  define  REPORT_STEP_TIME \
284   {\
285       char send_buf[80]; \
286       end_step_time = p4_clock(); \
287       (void) sprintf(send_buf, "%d", end_step_time-begin_step_time); \
288       p4_send(DNAML_STEP_TIME, DNAML_HOST_ID, send_buf,strlen(send_buf)+1); \
289       begin_step_time = end_step_time; \
290   }
291#else
292#  define  REPORT_ADD_SPECS
293#  define  REPORT_SEND_TREE
294#  define  REPORT_RECV_TREE
295#  define  REPORT_STEP_TIME
296#endif
297
298/*=======================================================================*/
299/*                              PROGRAM                                  */
300/*=======================================================================*/
301/*                    Best tree handling for dnaml                       */
302/*=======================================================================*/
303
304/*  Tip value comparisons
305 *
306 *  Use void pointers to hide type from other routines.  Only tipValPtr and
307 *  cmpTipVal need to be changed to alter the nature of the values compared
308 *  (e.g., names instead of node numbers).
309 *
310 *    cmpTipVal(tipValPtr(nodeptr p), tipValPtr(nodeptr q)) == -1, 0 or 1.
311 *
312 *  This provides direct comparison of tip values (for example, for
313 *  definition of tr->start).
314 */
315
316
317void  *tipValPtr (nodeptr p)
318  { return  (void *) & p->number;
319    }
320
321
322int  cmpTipVal (void *v1, void *v2)
323  { /* cmpTipVal */
324    int  i1, i2;
325
326    i1 = *((int *) v1);
327    i2 = *((int *) v2);
328    return  (i1 < i2) ? -1 : ((i1 == i2) ? 0 : 1);
329  } /* cmpTipVal */
330
331
332/*  These are the only routines that need to UNDERSTAND topologies */
333
334
335topol  *setupTopol (int maxtips, int nsites)
336  { /* setupTopol */
337    topol   *tpl;
338
339    if (! (tpl = (topol *) Malloc(sizeof(topol))) || 
340        ! (tpl->links = (connptr) Malloc((2*maxtips-3) * sizeof(connect))) || 
341        (nsites && ! (tpl->log_f
342                = (double *) Malloc(nsites * sizeof(double))))) {
343      printf("ERROR: Unable to get topology memory");
344      tpl = (topol *) NULL;
345      }
346
347    else {
348      if (nsites == 0)  tpl->log_f = (double *) NULL;
349      tpl->likelihood  = unlikely;
350      tpl->start       = (node *) NULL;
351      tpl->nextlink    = 0;
352      tpl->ntips       = 0;
353      tpl->nextnode    = 0;
354      tpl->opt_level   = 0;     /* degree of branch swapping explored */
355      tpl->scrNum      = 0;     /* position in sorted list of scores */
356      tpl->tplNum      = 0;     /* position in sorted list of trees */
357      tpl->log_f_valid = 0;     /* log_f value sites */
358      tpl->prelabeled  = TRUE;
359      tpl->smoothed    = FALSE; /* branch optimization converged? */
360      }
361
362    return  tpl;
363  } /* setupTopol */
364
365
366void  freeTopol (topol *tpl)
367  { /* freeTopol */
368    Free(tpl->links);
369    if (tpl->log_f)  Free(tpl->log_f);
370    Free(tpl);
371  } /* freeTopol */
372
373
374int  saveSubtree (nodeptr p, topol *tpl)
375    /*  Save a subtree in a standard order so that earlier branches
376     *  from a node contain lower value tips than do second branches from
377     *  the node.  This code works with arbitrary furcations in the tree.
378     */
379  { /* saveSubtree */
380    connptr  r, r0;
381    nodeptr  q, s;
382    int      t, t0, t1;
383
384    r0 = tpl->links;
385    r = r0 + (tpl->nextlink)++;
386    r->p = p;
387    r->q = q = p->back;
388    r->z = p->z;
389    r->descend = 0;                     /* No children (yet) */
390
391    if (q->tip) {
392      r->valptr = tipValPtr(q);         /* Assign value */
393      }
394
395    else {                              /* Internal node, look at children */
396      s = q->next;                      /* First child */
397      do {
398        t = saveSubtree(s, tpl);        /* Generate child's subtree */
399
400        t0 = 0;                         /* Merge child into list */
401        t1 = r->descend;
402        while (t1 && (cmpTipVal(r0[t1].valptr, r0[t].valptr) < 0)) {
403          t0 = t1;
404          t1 = r0[t1].sibling;
405          }
406        if (t0) r0[t0].sibling = t;  else  r->descend = t;
407        r0[t].sibling = t1;
408
409        s = s->next;                    /* Next child */
410        } while (s != q);
411
412      r->valptr = r0[r->descend].valptr;   /* Inherit first child's value */
413      }                                 /* End of internal node processing */
414
415    return  r - r0;
416  } /* saveSubtree */
417
418
419nodeptr  minSubtreeTip (nodeptr  p0)
420  { /* minTreeTip */
421    nodeptr  minTip, p, testTip;
422
423    if (p0->tip) return p0;
424
425    p = p0->next;
426    minTip = minSubtreeTip(p->back);
427    while ((p = p->next) != p0) {
428      testTip = minSubtreeTip(p->back);
429      if (cmpTipVal(tipValPtr(testTip), tipValPtr(minTip)) < 0)
430        minTip = testTip;
431      }
432    return minTip;
433  } /* minTreeTip */
434
435
436nodeptr  minTreeTip (nodeptr  p)
437  { /* minTreeTip */
438    nodeptr  minp, minpb;
439
440    minp  = minSubtreeTip(p);
441    minpb = minSubtreeTip(p->back);
442    return cmpTipVal(tipValPtr(minp), tipValPtr(minpb)) < 0 ? minp : minpb;
443  } /* minTreeTip */
444
445
446void saveTree (tree *tr, topol *tpl)
447    /*  Save a tree topology in a standard order so that first branches
448     *  from a node contain lower value tips than do second branches from
449     *  the node.  The root tip should have the lowest value of all.
450     */
451  { /* saveTree */
452    connptr  r;
453    double  *tr_log_f, *tpl_log_f;
454    int  i;
455
456    tpl->nextlink = 0;                             /* Reset link pointer */
457    r = tpl->links + saveSubtree(minTreeTip(tr->start), tpl);  /* Save tree */
458    r->sibling = 0;
459
460    tpl->likelihood = tr->likelihood;
461    tpl->start      = tr->start;
462    tpl->ntips      = tr->ntips;
463    tpl->nextnode   = tr->nextnode;
464    tpl->opt_level  = tr->opt_level;
465    tpl->prelabeled = tr->prelabeled;
466    tpl->smoothed   = tr->smoothed;
467
468    if (tpl_log_f = tpl->log_f) {
469      tr_log_f  = tr->log_f;
470      i = tpl->log_f_valid = tr->log_f_valid;
471      while (--i >= 0)  *tpl_log_f++ = *tr_log_f++;
472      }
473    else {
474      tpl->log_f_valid = 0;
475      }
476  } /* saveTree */
477
478
479void copyTopol (topol *tpl1, topol *tpl2)
480  { /* copyTopol */
481    connptr  r1, r2, r10, r20;
482    double  *tpl1_log_f, *tpl2_log_f;
483    int  i;
484
485    r10 = tpl1->links;
486    r20 = tpl2->links;
487    tpl2->nextlink = tpl1->nextlink; 
488
489    r1 = r10;
490    r2 = r20;
491    i = 2 * tpl1->ntips - 3;
492    while (--i >= 0) {
493      r2->z = r1->z;
494      r2->p = r1->p;
495      r2->q = r1->q;
496      r2->valptr = r1->valptr;
497      r2->descend = r1->descend; 
498      r2->sibling = r1->sibling; 
499      r1++;
500      r2++;
501      }
502
503    if (tpl1->log_f_valid && tpl2->log_f) {
504      tpl1_log_f = tpl1->log_f;
505      tpl2_log_f = tpl2->log_f;
506      tpl2->log_f_valid = i = tpl1->log_f_valid;
507      while (--i >= 0)  *tpl2_log_f++ = *tpl1_log_f++;
508      }
509    else {
510      tpl2->log_f_valid = 0;
511      }
512
513    tpl2->likelihood = tpl1->likelihood;
514    tpl2->start      = tpl1->start;
515    tpl2->ntips      = tpl1->ntips;
516    tpl2->nextnode   = tpl1->nextnode;
517    tpl2->opt_level  = tpl1->opt_level;
518    tpl2->prelabeled = tpl1->prelabeled;
519    tpl2->scrNum     = tpl1->scrNum;
520    tpl2->tplNum     = tpl1->tplNum;
521    tpl2->smoothed   = tpl1->smoothed;
522  } /* copyTopol */
523
524
525boolean restoreTree (topol *tpl, tree *tr)
526  { /* restoreTree */
527    void  hookup();
528    boolean  initrav();
529
530    connptr  r;
531    nodeptr  p, p0;
532    double  *tr_log_f, *tpl_log_f;
533    int  i;
534
535/*  Clear existing connections */
536
537    for (i = 1; i <= 2*(tr->mxtips) - 2; i++) {  /* Uses p = p->next at tip */
538      p0 = p = tr->nodep[i];
539      do {
540        p->back = (nodeptr) NULL;
541        p = p->next;
542        } while (p != p0);
543      }
544
545/*  Copy connections from topology */
546
547    for (r = tpl->links, i = 0; i < tpl->nextlink; r++, i++) {
548      hookup(r->p, r->q, r->z);
549      }
550
551    tr->likelihood = tpl->likelihood;
552    tr->start      = tpl->start;
553    tr->ntips      = tpl->ntips;
554    tr->nextnode   = tpl->nextnode;
555    tr->opt_level  = tpl->opt_level;
556    tr->prelabeled = tpl->prelabeled;
557    tr->smoothed   = tpl->smoothed;
558
559    if (tpl_log_f = tpl->log_f) {
560      tr_log_f = tr->log_f;
561      i = tr->log_f_valid = tpl->log_f_valid;
562      while (--i >= 0)  *tr_log_f++ = *tpl_log_f++;
563      }
564    else {
565      tr->log_f_valid = 0;
566      }
567
568    return (initrav(tr, tr->start) && initrav(tr, tr->start->back));
569  } /* restoreTree */
570
571
572int initBestTree (bestlist *bt, int newkeep, int numsp, int sites)
573  { /* initBestTree */
574    int  i, nlogf;
575
576
577    bt->nkeep = 0;
578
579    if (bt->ninit <= 0) {
580      if (! (bt->start = setupTopol(numsp, sites)))  return  0;
581      bt->ninit = -1;
582      bt->nvalid = 0;
583      bt->numtrees = 0;
584      bt->best = unlikely;
585      bt->improved = FALSE;
586      bt->byScore = (topol **) Malloc((newkeep+1) * sizeof(topol *));
587      bt->byTopol = (topol **) Malloc((newkeep+1) * sizeof(topol *));
588      if (! bt->byScore || ! bt->byTopol) {
589        fprintf(stderr, "initBestTree: Malloc failure\n");
590        return 0;
591        }
592      }
593    else if (ABS(newkeep) > bt->ninit) {
594      if (newkeep <  0) newkeep = -(bt->ninit);
595      else newkeep = bt->ninit;
596      }
597
598    if (newkeep < 1) {    /*  Use negative newkeep to clear list  */
599      newkeep = -newkeep;
600      if (newkeep < 1) newkeep = 1;
601      bt->nvalid = 0;
602      bt->best = unlikely;
603      }
604
605    if (bt->nvalid >= newkeep) {
606      bt->nvalid = newkeep;
607      bt->worst = bt->byScore[newkeep]->likelihood;
608      }
609    else {
610      bt->worst = unlikely;
611      }
612
613    for (i = bt->ninit + 1; i <= newkeep; i++) {
614      nlogf = (i <= maxlogf) ? sites : 0;
615      if (! (bt->byScore[i] = setupTopol(numsp, nlogf)))  break;
616      bt->byTopol[i] = bt->byScore[i];
617      bt->ninit = i;
618      }
619
620    return  (bt->nkeep = MIN(newkeep, bt->ninit));
621  } /* initBestTree */
622
623
624
625int resetBestTree (bestlist *bt)
626  { /* resetBestTree */
627    bt->best     = unlikely;
628    bt->worst    = unlikely;
629    bt->nvalid   = 0;
630    bt->improved = FALSE;
631  } /* resetBestTree */
632
633
634boolean  freeBestTree(bestlist *bt)
635  { /* freeBestTree */
636    while (bt->ninit >= 0)  freeTopol(bt->byScore[(bt->ninit)--]);
637    freeTopol(bt->start);
638    return TRUE;
639  } /* freeBestTree */
640
641
642/*  Compare two trees, assuming that each is in standard order.  Return
643 *  -1 if first preceeds second, 0 if they are identical, or +1 if first
644 *  follows second in standard order.  Lower number tips preceed higher
645 *  number tips.  A tip preceeds a corresponding internal node.  Internal
646 *  nodes are ranked by their lowest number tip.
647 */
648
649int  cmpSubtopol (connptr p10, connptr p1, connptr p20, connptr p2)
650  { /* cmpSubtopol */
651    connptr  p1d, p2d;
652    int  cmp;
653
654    if (! p1->descend && ! p2->descend)          /* Two tips */
655      return cmpTipVal(p1->valptr, p2->valptr);
656
657    if (! p1->descend) return -1;                /* p1 = tip, p2 = node */
658    if (! p2->descend) return  1;                /* p2 = tip, p1 = node */
659
660    p1d = p10 + p1->descend;
661    p2d = p20 + p2->descend;
662    while (1) {                                  /* Two nodes */
663      if (cmp = cmpSubtopol(p10, p1d, p20, p2d))  return cmp; /* Subtrees */
664      if (! p1d->sibling && ! p2d->sibling)  return  0; /* Lists done */
665      if (! p1d->sibling) return -1;             /* One done, other not */
666      if (! p2d->sibling) return  1;             /* One done, other not */
667      p1d = p10 + p1d->sibling;                  /* Neither done */
668      p2d = p20 + p2d->sibling;
669      }
670  } /* cmpSubtopol */
671
672
673
674int  cmpTopol (void *tpl1, void *tpl2)
675  { /* cmpTopol */
676    connptr  r1, r2;
677    int      cmp;
678
679    r1 = ((topol *) tpl1)->links;
680    r2 = ((topol *) tpl2)->links;
681    cmp = cmpTipVal(tipValPtr(r1->p), tipValPtr(r2->p));
682    if (cmp) return cmp;
683    return  cmpSubtopol(r1, r1, r2, r2);
684  } /* cmpTopol */
685
686
687
688int  cmpTplScore (void *tpl1, void *tpl2)
689  { /* cmpTplScore */
690    double  l1, l2;
691
692    l1 = ((topol *) tpl1)->likelihood;
693    l2 = ((topol *) tpl2)->likelihood;
694    return  (l1 > l2) ? -1 : ((l1 == l2) ? 0 : 1);
695  } /* cmpTplScore */
696
697
698
699/*  Find an item in a sorted list of n items.  If the item is in the list,
700 *  return its index.  If it is not in the list, return the negative of the
701 *  position into which it should be inserted.
702 */
703
704int  findInList (void *item, void *list[], int n, int (* cmpFunc)())
705  { /* findInList */
706    int  mid, hi, lo, cmp;
707
708    if (n < 1) return  -1;                    /*  No match; first index  */
709
710    lo = 1;
711    mid = 0;
712    hi = n;
713    while (lo < hi) {
714      mid = (lo + hi) >> 1;
715      cmp = (* cmpFunc)(item, list[mid-1]);
716      if (cmp) {
717        if (cmp < 0) hi = mid;
718        else lo = mid + 1;
719        }
720      else  return  mid;                        /*  Exact match  */
721      }
722
723    if (lo != mid) {
724       cmp = (* cmpFunc)(item, list[lo-1]);
725       if (cmp == 0) return lo;
726       }
727    if (cmp > 0) lo++;                         /*  Result of step = 0 test  */
728    return  -lo;
729  } /* findInList */
730
731
732
733int  findTreeInList (bestlist *bt, tree *tr)
734  { /* findTreeInList */
735    topol  *tpl;
736
737    tpl = bt->byScore[0];
738    saveTree(tr, tpl);
739    return  findInList((void *) tpl, (void **) (& (bt->byTopol[1])),
740                       bt->nvalid, cmpTopol);
741  } /* findTreeInList */
742
743
744int  saveBestTree (bestlist *bt, tree *tr)
745  { /* saveBestTree */
746    double *tr_log_f, *tpl_log_f;
747    topol  *tpl, *reuse;
748    int  tplNum, scrNum, reuseScrNum, reuseTplNum, i, oldValid, newValid;
749
750    tplNum = findTreeInList(bt, tr);
751    tpl = bt->byScore[0];
752    oldValid = newValid = bt->nvalid;
753
754    if (tplNum > 0) {                      /* Topology is in list  */
755      reuse = bt->byTopol[tplNum];         /* Matching topol  */
756      reuseScrNum = reuse->scrNum;
757      reuseTplNum = reuse->tplNum;
758      }
759                                           /* Good enough to keep? */
760    else if (tr->likelihood < bt->worst)  return 0;
761
762    else {                                 /* Topology is not in list */
763      tplNum = -tplNum;                    /* Add to list (not replace) */
764      if (newValid < bt->nkeep) bt->nvalid = ++newValid;
765      reuseScrNum = newValid;              /* Take worst tree */
766      reuse = bt->byScore[reuseScrNum];
767      reuseTplNum = (newValid > oldValid) ? newValid : reuse->tplNum;
768      if (tr->likelihood > bt->start->likelihood) bt->improved = TRUE;
769      }
770
771    scrNum = findInList((void *) tpl, (void **) (& (bt->byScore[1])),
772                         oldValid, cmpTplScore);
773    scrNum = ABS(scrNum);
774
775    if (scrNum < reuseScrNum)
776      for (i = reuseScrNum; i > scrNum; i--)
777        (bt->byScore[i] = bt->byScore[i-1])->scrNum = i;
778
779    else if (scrNum > reuseScrNum) {
780      scrNum--;
781      for (i = reuseScrNum; i < scrNum; i++)
782        (bt->byScore[i] = bt->byScore[i+1])->scrNum = i;
783      }
784
785    if (tplNum < reuseTplNum)
786      for (i = reuseTplNum; i > tplNum; i--)
787        (bt->byTopol[i] = bt->byTopol[i-1])->tplNum = i;
788
789    else if (tplNum > reuseTplNum) {
790      tplNum--;
791      for (i = reuseTplNum; i < tplNum; i++)
792        (bt->byTopol[i] = bt->byTopol[i+1])->tplNum = i;
793      }
794
795    if (tpl_log_f = tpl->log_f) {
796      tr_log_f  = tr->log_f;
797      i = tpl->log_f_valid = tr->log_f_valid;
798      while (--i >= 0)  *tpl_log_f++ = *tr_log_f++;
799      }
800    else {
801      tpl->log_f_valid = 0;
802      }
803
804    tpl->scrNum = scrNum;
805    tpl->tplNum = tplNum;
806    bt->byTopol[tplNum] = bt->byScore[scrNum] = tpl;
807    bt->byScore[0] = reuse;
808
809    if (scrNum == 1)  bt->best = tr->likelihood;
810    if (newValid == bt->nkeep) bt->worst = bt->byScore[newValid]->likelihood;
811
812    return  scrNum;
813  } /* saveBestTree */
814
815
816int  startOpt (bestlist *bt, tree *tr)
817  { /* startOpt */
818    int  scrNum;
819
820    scrNum = saveBestTree(bt, tr);
821    copyTopol(bt->byScore[scrNum], bt->start);
822    bt->improved = FALSE;
823    return  scrNum;
824  } /* startOpt */
825
826
827int  setOptLevel (bestlist *bt, int opt_level)
828  { /* setOptLevel */
829    int  tplNum, scrNum;
830
831    tplNum = findInList((void *) bt->start, (void **) (&(bt->byTopol[1])),
832                        bt->nvalid, cmpTopol);
833    if (tplNum > 0) {
834      bt->byTopol[tplNum]->opt_level = opt_level;
835      scrNum = bt->byTopol[tplNum]->scrNum;
836      }
837    else {
838      scrNum = 0;
839      }
840
841    return  scrNum;
842  } /* setOptLevel */
843
844
845int  recallBestTree (bestlist *bt, int rank, tree *tr)
846  { /* recallBestTree */
847    if (rank < 1)  rank = 1;
848    if (rank > bt->nvalid)  rank = bt->nvalid;
849    if (rank > 0)  if (! restoreTree(bt->byScore[rank], tr)) return FALSE;
850    return  rank;
851  } /* recallBestTree */
852
853
854/*=======================================================================*/
855/*                       End of best tree routines                       */
856/*=======================================================================*/
857
858
859#if 0
860  void hang(char *msg)
861   { printf("Hanging around: %s\n", msg);
862     while(1);
863     }
864#endif
865
866
867boolean getnums (rawdata *rdta)
868    /* input number of species, number of sites */
869  { /* getnums */
870    printf("\n%s, version %s, %s,\nCopyright (C) 2002 by Alexandros P. Stamatakis\n\n",
871            programName,
872            programVersion,
873            programDate);
874    printf("Based in part on Joseph Felsenstein's\n\n");
875    printf("   Nucleic acid sequence Maximum Likelihood method, version 3.3\n\n\n");
876
877    if (fscanf(INFILE, "%d %d", & rdta->numsp, & rdta->sites) != 2) {
878      printf("ERROR: Problem reading number of species and sites\n");
879      return FALSE;
880      }
881    printf("%d Species, %d Sites\n\n", rdta->numsp, rdta->sites);
882
883    if (rdta->numsp < 4) {
884      printf("TOO FEW SPECIES\n");
885      return FALSE;
886      }
887
888    if (rdta->sites < 1) {
889      printf("TOO FEW SITES\n");
890      return FALSE;
891      }
892
893    return TRUE;
894  } /* getnums */
895
896
897boolean digitchar (int ch) {return (ch >= '0' && ch <= '9'); }
898
899
900boolean whitechar (int ch)
901   { return (ch == ' ' || ch == '\n' || ch == '\t');
902     }
903
904
905void uppercase (int *chptr)
906    /* convert character to upper case -- either ASCII or EBCDIC */
907  { /* uppercase */
908    int  ch;
909
910    ch = *chptr;
911    if ((ch >= 'a' && ch <= 'i') || (ch >= 'j' && ch <= 'r')
912                                 || (ch >= 's' && ch <= 'z'))
913      *chptr = ch + 'A' - 'a';
914  } /* uppercase */
915
916
917int base36 (int ch)
918  { /* base36 */
919    if      (ch >= '0' && ch <= '9') return (ch - '0');
920    else if (ch >= 'A' && ch <= 'I') return (ch - 'A' + 10);
921    else if (ch >= 'J' && ch <= 'R') return (ch - 'J' + 19);
922    else if (ch >= 'S' && ch <= 'Z') return (ch - 'S' + 28);
923    else if (ch >= 'a' && ch <= 'i') return (ch - 'a' + 10);
924    else if (ch >= 'j' && ch <= 'r') return (ch - 'j' + 19);
925    else if (ch >= 's' && ch <= 'z') return (ch - 's' + 28);
926    else return -1;
927  } /* base36 */
928
929
930int itobase36 (int i)
931  { /* itobase36 */
932    if      (i <  0) return '?';
933    else if (i < 10) return (i      + '0');
934    else if (i < 19) return (i - 10 + 'A');
935    else if (i < 28) return (i - 19 + 'J');
936    else if (i < 36) return (i - 28 + 'S');
937    else return '?';
938  } /* itobase36 */
939
940
941int findch (int c)
942  { /* findch */
943    int ch;
944
945    while ((ch = getc(INFILE)) != EOF && ch != c) ;
946    return  ch;
947  } /* findch */
948
949
950#if Master || Slave
951int str_findch (char **treestrp, int c)
952  { /* str_findch */
953    int ch;
954
955    while ((ch = *(*treestrp)++) != NULL && ch != c) ;
956    return  ch;
957  } /* str_findch */
958#endif
959
960
961boolean inputboot(analdef *adef)
962    /* read the bootstrap auxilliary info */
963  { /* inputboot */
964    if (! adef->boot) {
965      printf("ERROR: Unexpected Bootstrap auxiliary data line\n");
966      return FALSE;
967      }
968    else if (fscanf(INFILE, "%ld", & adef->boot) != 1 ||
969             findch('\n') == EOF) {
970      printf("ERROR: Problem reading boostrap random seed value\n");
971      return FALSE;
972      }
973
974    return TRUE;
975  } /* inputboot */
976
977
978boolean inputcategories (rawdata *rdta)
979    /* read the category rates and the categories for each site */
980  { /* inputcategories */
981    int  i, j, ch, ci;
982
983    if (rdta->categs >= 0) {
984      printf("ERROR: Unexpected Categories auxiliary data line\n");
985      return FALSE;
986      }
987    if (fscanf(INFILE, "%d", & rdta->categs) != 1) {
988      printf("ERROR: Problem reading number of rate categories\n");
989      return FALSE;
990      }
991    if (rdta->categs < 1 || rdta->categs > maxcategories) {
992      printf("ERROR: Bad number of categories: %d\n", rdta->categs);
993      printf("Must be in range 1 - %d\n", maxcategories);
994      return FALSE;
995      }
996
997    for (j = 1; j <= rdta->categs
998           && fscanf(INFILE, "%lf", &(rdta->catrat[j])) == 1; j++) ;
999
1000    if ((j <= rdta->categs) || (findch('\n') == EOF)) {
1001      printf("ERROR: Problem reading rate values\n");
1002      return FALSE;
1003      }
1004
1005    for (i = 1; i <= nmlngth; i++)  (void) getc(INFILE);
1006
1007    i = 1;
1008    while (i <= rdta->sites) {
1009      ch = getc(INFILE);
1010      ci = base36(ch);
1011      if (ci >= 0 && ci <= rdta->categs)
1012        rdta->sitecat[i++] = ci;
1013      else if (! whitechar(ch)) {
1014        printf("ERROR: Bad category character (%c) at site %d\n", ch, i);
1015        return FALSE;
1016        }
1017      }
1018
1019    if (findch('\n') == EOF) {      /* skip to end of line */
1020      printf("ERROR: Missing newline at end of category data\n");
1021      return FALSE;
1022      }
1023
1024    return TRUE;
1025  } /* inputcategories */
1026
1027
1028boolean inputextra (analdef *adef)
1029  { /* inputextra */
1030    if (fscanf(INFILE,"%d", & adef->extra) != 1 ||
1031        findch('\n') == EOF) {
1032      printf("ERROR: Problem reading extra info value\n");
1033      return FALSE;
1034      }
1035
1036    return TRUE;
1037  } /* inputextra */
1038
1039
1040boolean inputfreqs (rawdata *rdta)
1041  { /* inputfreqs */
1042    if (fscanf(INFILE, "%lf%lf%lf%lf",
1043               & rdta->freqa, & rdta->freqc,
1044               & rdta->freqg, & rdta->freqt) != 4 ||
1045        findch('\n') == EOF) {
1046      printf("ERROR: Problem reading user base frequencies data\n");
1047      return  FALSE;
1048      }
1049
1050    rdta->freqread = TRUE;
1051    return TRUE;
1052  } /* inputfreqs */
1053
1054
1055boolean inputglobal (tree *tr)
1056    /* input the global option information */
1057  { /* inputglobal */
1058    int  ch;
1059
1060    if (tr->global != -2) {
1061      printf("ERROR: Unexpected Global auxiliary data line\n");
1062      return FALSE;
1063      }
1064    if (fscanf(INFILE, "%d", &(tr->global)) != 1) {
1065      printf("ERROR: Problem reading rearrangement region size\n");
1066      return FALSE;
1067      }
1068    if (tr->global < 0) {
1069      printf("WARNING: Global region size too small;\n");
1070      printf("         value reset to local\n\n");
1071      tr->global = 1;
1072      }
1073    else if (tr->global == 0)  tr->partswap = 0;
1074    else if (tr->global > tr->mxtips - 3) {
1075      tr->global = tr->mxtips - 3;
1076      }
1077
1078    while ((ch = getc(INFILE)) != '\n') {  /* Scan for second value */
1079      if (! whitechar(ch)) {
1080        if (ch != EOF)  (void) ungetc(ch, INFILE);
1081        if (ch == EOF || fscanf(INFILE, "%d", &(tr->partswap)) != 1
1082                      || findch('\n') == EOF) {
1083          printf("ERROR: Problem reading insert swap region size\n");
1084          return FALSE;
1085          }
1086        else if (tr->partswap < 0)  tr->partswap = 1;
1087        else if (tr->partswap > tr->mxtips - 3) {
1088          tr->partswap = tr->mxtips - 3;
1089          }
1090
1091        if (tr->partswap > tr->global)  tr->global = tr->partswap;
1092        break;   /*  Break while loop */
1093        }
1094      }
1095
1096    return TRUE;
1097  } /* inputglobal */
1098
1099
1100boolean inputjumble (analdef *adef)
1101  { /* inputjumble */
1102    if (! adef->jumble) {
1103      printf("ERROR: Unexpected Jumble auxiliary data line\n");
1104      return FALSE;
1105      }
1106    else if (fscanf(INFILE, "%ld", & adef->jumble) != 1 ||
1107             findch('\n') == EOF) {
1108      printf("ERROR: Problem reading jumble random seed value\n");
1109      return FALSE;
1110      }
1111    else if (adef->jumble == 0) {
1112      printf("WARNING: Jumble random number seed is zero\n\n");
1113      }
1114
1115    return TRUE;
1116  } /* inputjumble */
1117
1118
1119boolean inputkeep (analdef *adef)
1120  { /* inputkeep */
1121    if (fscanf(INFILE, "%d", & adef->nkeep) != 1 ||
1122        findch('\n') == EOF || adef->nkeep < 1) {
1123      printf("ERROR: Problem reading number of kept trees\n");
1124      return FALSE;
1125      }
1126
1127    return TRUE;
1128  } /* inputkeep */
1129
1130
1131boolean inputoutgroup (analdef *adef, tree *tr)
1132  { /* inputoutgroup */
1133    if (! adef->root || tr->outgr > 0) {
1134      printf("ERROR: Unexpected Outgroup auxiliary data line\n");
1135      return FALSE;
1136      }
1137    else if (fscanf(INFILE, "%d", &(tr->outgr)) != 1 ||
1138             findch('\n') == EOF) {
1139      printf("ERROR: Problem reading outgroup number\n");
1140      return FALSE;
1141      }
1142    else if ((tr->outgr < 1) || (tr->outgr > tr->mxtips)) {
1143      printf("ERROR: Bad outgroup: '%d'\n", tr->outgr);
1144      return FALSE;
1145      }
1146
1147    return TRUE;
1148  } /* inputoutgroup */
1149
1150
1151boolean inputratio (rawdata *rdta)
1152  { /* inputratio */
1153    if (rdta->ttratio >= 0.0) {
1154      printf("ERROR: Unexpected Transition/transversion auxiliary data\n");
1155      return FALSE;
1156      }
1157    else if (fscanf(INFILE,"%lf", & rdta->ttratio)!=1 ||
1158             findch('\n') == EOF) {
1159      printf("ERROR: Problem reading transition/transversion ratio\n");
1160      return FALSE;
1161      }
1162
1163    return TRUE;
1164  } /* inputratio */
1165
1166
1167/*  Y 0 is treeNone   (no tree)
1168    Y 1 is treeNewick
1169    Y 2 is treeProlog
1170    Y 3 is treePHYLIP
1171 */
1172
1173boolean inputtreeopt (analdef *adef)
1174  { /* inputtreeopt */
1175    if (! adef->trout) {
1176      printf("ERROR: Unexpected Treefile auxiliary data\n");
1177      return FALSE;
1178      }
1179    else if (fscanf(INFILE,"%d", & adef->trout) != 1 ||
1180             findch('\n') == EOF) {
1181      printf("ERROR: Problem reading output tree-type number\n");
1182      return FALSE;
1183      }
1184    else if ((adef->trout < 0) || (adef->trout > treeMaxType)) {
1185      printf("ERROR: Bad output tree-type number: '%d'\n", adef->trout);
1186      return FALSE;
1187      }
1188
1189    return TRUE;
1190  } /* inputtreeopt */
1191
1192
1193boolean inputweights (analdef *adef, rawdata *rdta, cruncheddata *cdta)
1194    /* input the character weights 0, 1, 2 ... 9, A, B, ... Y, Z */
1195  { /* inputweights */
1196    int i, ch, wi;
1197
1198    if (! adef->userwgt || cdta->wgtsum > 0) {
1199      printf("ERROR: Unexpected Weights auxiliary data\n");
1200      return FALSE;
1201      }
1202
1203    for (i = 2; i <= nmlngth; i++)  (void) getc(INFILE);
1204    cdta->wgtsum = 0;
1205    i = 1;
1206    while (i <= rdta->sites) {
1207      ch = getc(INFILE);
1208      wi = base36(ch);
1209      if (wi >= 0)
1210        cdta->wgtsum += rdta->wgt[i++] = wi;
1211      else if (! whitechar(ch)) {
1212        printf("ERROR: Bad weight character: '%c'", ch);
1213        printf("       Weights in dnaml must be a digit or a letter.\n");
1214        return FALSE;
1215        }
1216      }
1217
1218    if (findch('\n') == EOF) {      /* skip to end of line */
1219      printf("ERROR: Missing newline at end of weight data\n");
1220      return FALSE;
1221      }
1222
1223    return TRUE;
1224  } /* inputweights */
1225
1226boolean inputdepth (tree *tr)
1227  { 
1228    if (fscanf(INFILE, "%d", & tr->eqDepth) != 1 ||
1229        findch('\n') == EOF || tr->eqDepth < 0) {
1230      printf("Depth (H - option) has to be greater than 0 \n ");
1231     
1232      return FALSE;
1233      }
1234    fprintf(stderr,"set to: %d\n",  tr->eqDepth);
1235    return TRUE;
1236  } 
1237
1238
1239boolean getoptions (analdef *adef, rawdata *rdta, cruncheddata *cdta, tree *tr)
1240  { /* getoptions */
1241    int     ch, i, extranum;
1242
1243    adef->boot    =           0;  /* Don't bootstrap column weights */
1244    adef->empf    =        TRUE;  /* Use empirical base frequencies */
1245    adef->extra   =           0;  /* No extra runtime info unless requested */
1246    adef->interleaved =    TRUE;  /* By default, data format is interleaved */
1247    adef->jumble  =       FALSE;  /* Use random addition sequence */
1248    adef->nkeep   =           0;  /* Keep only the one best tree */
1249    adef->prdata  =       FALSE;  /* Don't echo data to output stream */
1250    adef->qadd    =        TRUE;  /* Smooth branches globally in add */
1251    adef->restart =       FALSE;  /* Restart from user tree */
1252    adef->root    =       FALSE;  /* User-defined outgroup rooting */
1253    adef->trout   = treeDefType;  /* Output tree file */
1254    adef->trprint =        TRUE;  /* Print tree to output stream */
1255    rdta->categs  =           0;  /* No rate categories */
1256    rdta->catrat[1] =       1.0;  /* Rate values */
1257    rdta->freqread =      FALSE;  /* User-defined frequencies not read yet */
1258    rdta->ttratio =         2.0;  /* Transition/transversion rate ratio */
1259    tr->global    =          -1;  /* Default search locale for optimum */
1260    tr->mxtips    = rdta->numsp;
1261    tr->outgr     =           1;  /* Outgroup number */
1262    tr->partswap  =           1;  /* Default to swap locally after insert */
1263    tr->userlen   =       FALSE;  /* User-supplied branch lengths */
1264    tr->eqDepth   =           0;
1265    adef->usertree =      FALSE;  /* User-defined tree topologies */
1266    adef->userwgt =       FALSE;  /* User-defined position weights */
1267    extranum      =           0;
1268
1269    while ((ch = getc(INFILE)) != '\n' && ch != EOF) {
1270      uppercase(& ch);
1271      switch (ch) {
1272          case '1' : adef->prdata  = ! adef->prdata; break;
1273          case '3' : adef->trprint = ! adef->trprint; break;
1274          case '4' : adef->trout   = treeDefType - adef->trout; break;
1275          case 'B' : adef->boot    =  1; extranum++; break;
1276          case 'C' : rdta->categs  = -1; extranum++; break;
1277          case 'E' : adef->extra   = -1; break;
1278          case 'F' : adef->empf    = ! adef->empf; break;
1279          case 'G' : tr->global    = -2; break;
1280            //stm
1281      case 'H' : extranum++;break; 
1282            //stm
1283
1284
1285          case 'I' : adef->interleaved = ! adef->interleaved; break;
1286          case 'J' : adef->jumble  = 1; extranum++; break;
1287          case 'K' : extranum++; break;
1288          case 'L' : tr->userlen   = TRUE; break;
1289          case 'O' : adef->root    = TRUE; tr->outgr = 0; extranum++; break;
1290          case 'Q' : adef->qadd    = FALSE; break;
1291          case 'R' : adef->restart = TRUE; break;
1292          case 'T' : rdta->ttratio = -1.0; extranum++; break;
1293          case 'U' : adef->usertree = TRUE; break;
1294          case 'W' : adef->userwgt = TRUE; cdta->wgtsum = 0; extranum++; break;
1295          case 'Y' : adef->trout   = treeDefType - adef->trout; break;
1296          case ' ' : break;
1297          case '\t': break;
1298          default  :
1299              printf("ERROR: Bad option character: '%c'\n", ch);
1300              return FALSE;
1301          }
1302      }
1303
1304    if (ch == EOF) {
1305      printf("ERROR: End-of-file in options list\n");
1306      return FALSE;
1307      }
1308
1309    if (adef->usertree && adef->restart) {
1310      printf("ERROR:  The restart and user-tree options conflict:\n");
1311      printf("        Restart adds rest of taxa to a starting tree;\n");
1312      printf("        User-tree does not add any taxa.\n\n");
1313      return FALSE;
1314      }
1315
1316    if (adef->usertree && adef->jumble) {
1317      printf("WARNING:  The jumble and user-tree options conflict:\n");
1318      printf("          Jumble adds taxa to a tree in random order;\n");
1319      printf("          User-tree does not use taxa addition.\n");
1320      printf("          Jumble option cancelled for this run.\n\n");
1321      adef->jumble = FALSE;
1322      }
1323
1324    if (tr->userlen && tr->global != -1) {
1325      printf("ERROR:  The global and user-lengths options conflict:\n");
1326      printf("        Global optimizes a starting tree;\n");
1327      printf("        User-lengths constrain the starting tree.\n\n");
1328      return FALSE;
1329      }
1330
1331    if (tr->userlen && ! adef->usertree) {
1332      printf("WARNING:  User lengths required user tree option.\n");
1333      printf("          User-tree option set for this run.\n\n");
1334      adef->usertree = TRUE;
1335      }
1336
1337    rdta->wgt      = (int *)    Malloc((rdta->sites + 1) * sizeof(int));
1338    rdta->wgt2     = (int *)    Malloc((rdta->sites + 1) * sizeof(int));
1339    rdta->sitecat  = (int *)    Malloc((rdta->sites + 1) * sizeof(int));
1340    cdta->alias    = (int *)    Malloc((rdta->sites + 1) * sizeof(int));
1341    cdta->aliaswgt = (int *)    Malloc((rdta->sites + 1) * sizeof(int));
1342    cdta->patcat   = (int *)    Malloc((rdta->sites + 1) * sizeof(int));
1343    cdta->patrat   = (double *) Malloc((rdta->sites + 1) * sizeof(double));
1344    cdta->wr       = (double *) Malloc((rdta->sites + 1) * sizeof(double));
1345    cdta->wr2      = (double *) Malloc((rdta->sites + 1) * sizeof(double));
1346    if ( ! rdta->wgt || ! rdta->wgt2     || ! rdta->sitecat || ! cdta->alias
1347                     || ! cdta->aliaswgt || ! cdta->patcat  || ! cdta->patrat
1348                     || ! cdta->wr       || ! cdta->wr2) {
1349      fprintf(stderr, "getoptions: Malloc failure\n");
1350      return 0;
1351      }
1352
1353    /*  process lines with auxiliary data */
1354
1355    while (extranum--) {
1356      ch = getc(INFILE);
1357      uppercase(& ch);
1358      switch (ch) {
1359        case 'B':  if (! inputboot(adef)) return FALSE; break;
1360        case 'C':  if (! inputcategories(rdta)) return FALSE; break;
1361        case 'E':  if (! inputextra(adef)) return FALSE; extranum++; break;
1362        case 'F':  if (! inputfreqs(rdta)) return FALSE; break;
1363        case 'G':  if (! inputglobal(tr)) return FALSE; extranum++; break;
1364          //stm
1365      case 'H':    if(!inputdepth(tr)) return FALSE; break;
1366        //stm
1367        case 'J':  if (! inputjumble(adef)) return FALSE; break;
1368        case 'K':  if (! inputkeep(adef)) return FALSE; break;
1369        case 'O':  if (! inputoutgroup(adef, tr)) return FALSE; break;
1370        case 'T':  if (! inputratio(rdta)) return FALSE; break;
1371        case 'W':  if (! inputweights(adef, rdta, cdta)) return FALSE; break;
1372        case 'Y':  if (! inputtreeopt(adef)) return FALSE; extranum++; break;
1373
1374        default:
1375            printf("ERROR: Auxiliary options line starts with '%c'\n", ch);
1376            return FALSE;
1377        }
1378      }
1379
1380    if (! adef->userwgt) {
1381      for (i = 1; i <= rdta->sites; i++) rdta->wgt[i] = 1;
1382      cdta->wgtsum = rdta->sites;
1383      }
1384
1385    if (adef->userwgt && cdta->wgtsum < 1) {
1386      printf("ERROR:  Missing or bad user-supplied weight data.\n");
1387      return FALSE;
1388      }
1389
1390    if (adef->boot) {
1391      printf("Bootstrap random number seed = %ld\n\n", adef->boot);
1392      }
1393
1394    if (adef->jumble) {
1395      printf("Jumble random number seed = %ld\n\n", adef->jumble);
1396      }
1397
1398    if (adef->qadd) {
1399      printf("Quick add (only local branches initially optimized) in effect\n\n");
1400      }
1401
1402    if (rdta->categs > 0) {
1403      printf("Site category   Rate of change\n\n");
1404      for (i = 1; i <= rdta->categs; i++)
1405        printf("           %c%13.3f\n", itobase36(i), rdta->catrat[i]);
1406      putchar('\n');
1407      for (i = 1; i <= rdta->sites; i++) {
1408        if ((rdta->wgt[i] > 0) && (rdta->sitecat[i] < 1)) {
1409          printf("ERROR: Bad category (%c) at site %d\n",
1410                  itobase36(rdta->sitecat[i]), i);
1411          return FALSE;
1412          }
1413        }
1414      }
1415    else if (rdta->categs < 0) {
1416      printf("ERROR: Category auxiliary data missing from input\n");
1417      return FALSE;
1418      }
1419    else {                                        /* rdta->categs == 0 */
1420      for (i = 1; i <= rdta->sites; i++) rdta->sitecat[i] = 1;
1421      rdta->categs = 1;
1422      }
1423
1424    if (tr->outgr < 1) {
1425      printf("ERROR: Outgroup auxiliary data missing from input\n");
1426      return FALSE;
1427      }
1428
1429    if (rdta->ttratio < 0.0) {
1430      printf("ERROR: Transition/transversion auxiliary data missing from input\n");
1431      return FALSE;
1432      }
1433
1434    if (tr->global < 0) {
1435      if (tr->global == -2) tr->global = tr->mxtips - 3;  /* Default global */
1436      else                  tr->global = adef->usertree ? 0 : 1;/* No global */
1437      }
1438
1439    if (adef->restart) {
1440      printf("Restart option in effect.  ");
1441      printf("Sequence addition will start from appended tree.\n\n");
1442      }
1443
1444    if (adef->usertree && ! tr->global) {
1445      printf("User-supplied tree topology%swill be used.\n\n",
1446        tr->userlen ? " and branch lengths " : " ");
1447      }
1448    else {
1449      if (! adef->usertree) {
1450        printf("Rearrangements of partial trees may cross %d %s.\n",
1451               tr->partswap, tr->partswap == 1 ? "branch" : "branches");
1452        }
1453      printf("Rearrangements of full tree may cross %d %s.\n\n",
1454             tr->global, tr->global == 1 ? "branch" : "branches");
1455      }
1456
1457    if (! adef->usertree && adef->nkeep == 0) adef->nkeep = 1;
1458
1459    return TRUE;
1460  } /* getoptions */
1461
1462
1463boolean getbasefreqs (rawdata *rdta)
1464  { /* getbasefreqs */
1465    int  ch;
1466
1467    if (rdta->freqread) return TRUE;
1468
1469    ch = getc(INFILE);
1470    if (! ((ch == 'F') || (ch == 'f')))  (void) ungetc(ch, INFILE);
1471
1472    if (fscanf(INFILE, "%lf%lf%lf%lf",
1473               & rdta->freqa, & rdta->freqc,
1474               & rdta->freqg, & rdta->freqt) != 4 ||
1475        findch('\n') == EOF) {
1476      printf("ERROR: Problem reading user base frequencies\n");
1477      return  FALSE;
1478      }
1479
1480    return TRUE;
1481  } /* getbasefreqs */
1482
1483
1484boolean getyspace (rawdata *rdta)
1485  { /* getyspace */
1486    long   size;
1487    int    i;
1488    yType *y0;
1489
1490    if (! (rdta->y = (yType **) Malloc((rdta->numsp + 1) * sizeof(yType *)))) {
1491      printf("ERROR: Unable to obtain space for data array pointers\n");
1492      return  FALSE;
1493      }
1494
1495    size = 4 * (rdta->sites / 4 + 1);
1496    if (! (y0 = (yType *) Malloc((rdta->numsp + 1) * size * sizeof(yType)))) {
1497      printf("ERROR: Unable to obtain space for data array\n");
1498      return  FALSE;
1499      }
1500
1501    for (i = 0; i <= rdta->numsp; i++) {
1502      rdta->y[i] = y0;
1503      y0 += size;
1504      }
1505
1506    return  TRUE;
1507  } /* getyspace */
1508
1509
1510
1511boolean setupTree (tree *tr, int nsites)
1512  { /* setupTree */
1513    nodeptr  p0, p, q;
1514    int      i, j, tips, inter;
1515
1516    tips  = tr->mxtips;
1517    inter = tr->mxtips - 1;
1518
1519    if (!(p0 = (nodeptr) Malloc((tips + 3*inter) * sizeof(node)))) {
1520      printf("ERROR: Unable to obtain sufficient tree memory\n");
1521      return  FALSE;
1522      }
1523
1524
1525    if (!(tr->nodep = (nodeptr *) Malloc((2*tr->mxtips) * sizeof(nodeptr)))) {
1526      printf("ERROR: Unable to obtain sufficient tree memory, too\n");
1527      return  FALSE;
1528      }
1529
1530   
1531    tr->nodep[0] = (node *) NULL;    /* Use as 1-based array */
1532
1533    for (i = 1; i <= tips; i++) {    /* Set-up tips */
1534      p = p0++;
1535      p->x      = (xarray *) NULL;
1536      p->tip    = (yType *) NULL;
1537     
1538      /* AxML modification start*/
1539
1540      p->equalityVector = (char *) NULL; /*initialize eq vector with zero */
1541     
1542      /* AxML modification end*/
1543
1544
1545      p->number = i;
1546      p->next   = p;
1547      p->back   = (node *) NULL;
1548
1549      tr->nodep[i] = p;
1550      }
1551
1552    for (i = tips + 1; i <= tips + inter; i++) { /* Internal nodes */
1553      q = (node *) NULL;
1554      for (j = 1; j <= 3; j++) {
1555        p = p0++;
1556        p->x      = (xarray *) NULL;
1557        p->tip    = (yType *) NULL;
1558        p->number = i;
1559
1560        /* AxML modification start*/
1561
1562        p->equalityVector = (char *) NULL; /*initialize eq vector with zero */ 
1563        /* AxML modification end*/
1564
1565
1566        p->next   = q;
1567        p->back   = (node *) NULL;
1568        q = p;
1569        }
1570      p->next->next->next = p;
1571      tr->nodep[i] = p;
1572      }
1573
1574    tr->likelihood  = unlikely;
1575    tr->start       = (node *) NULL;
1576    tr->outgrnode   = tr->nodep[tr->outgr];
1577    tr->ntips       = 0;
1578    tr->nextnode    = 0;
1579    tr->opt_level   = 0;
1580    tr->prelabeled  = TRUE;
1581    tr->smoothed    = FALSE;
1582    tr->log_f_valid = 0;
1583
1584    tr->log_f = (double *) Malloc(nsites * sizeof(double));
1585    if (! tr->log_f) {
1586      printf("ERROR: Unable to obtain sufficient tree memory, trey\n");
1587      return  FALSE;
1588      }
1589
1590    return TRUE;
1591  } /* setupTree */
1592
1593void freeTreeNode (nodeptr p)   /* Free tree node (sector) associated data */
1594  { /* freeTreeNode */
1595    if (p) {
1596      if (p->x) {
1597        if (p->x->lv) Free(p->x->lv);
1598        Free(p->x);
1599        }
1600      /* AxML modification start*/
1601 
1602      Free(p->equalityVector); /*free equality vector of node*/
1603     
1604      /* AxML modification end*/
1605      }
1606  } /* freeTree */
1607
1608
1609
1610/* AxML modification start*/
1611
1612
1613boolean setupEqualityVector(tree *tr) /* new function for initializing and mapping equality vectors */
1614{
1615  int siteNum = tr->cdta->endsite;
1616  nodeptr upper = tr->nodep[tr->mxtips * 2 - 1];
1617  nodeptr p = tr->nodep[1];
1618  char *ev, *end;
1619  char *tip;   
1620 
1621  likelivector *l;
1622  int i, j;
1623  homType *mlvP;
1624  int ref[EQUALITIES];
1625  int code;
1626 
1627  for(; p < upper; p++)
1628    {     
1629      if( ! (p->equalityVector = 
1630             (ev = (char *)malloc(siteNum * sizeof(char)))))
1631        {
1632          printf("ERROR: Failure to get node equality vector  memory\n");
1633          return  FALSE; 
1634        }     
1635         
1636      end = & ev[siteNum];
1637     
1638      if(p->tip)
1639        {       
1640          int i;
1641          tip = p->tip; 
1642       
1643          for(i = 0; i < equalities; i++)
1644            ref[i] = -1;
1645
1646          for(i = 0; i < siteNum; i++)
1647            {       
1648              ev[i] = map[tip[i]];                           
1649              if(ref[ev[i]] == -1)
1650                ref[ev[i]] = 1;
1651            }
1652          for(i = 0; i < equalities; i++)
1653            {         
1654              for(j = 1; j <= tr->rdta->categs; j++)
1655                {
1656                  mlvP = &p->mlv[i][j];
1657                  code = map2[i];
1658                  //  if(ref[i] == 1)
1659                  //{
1660                  mlvP->a =  code       & 1;
1661                  mlvP->c = (code >> 1) & 1;   
1662                  mlvP->g = (code >> 2) & 1;
1663                  mlvP->t = (code >> 3) & 1;
1664                  mlvP->exp = 0;
1665                  mlvP->set = TRUE;
1666                  //}
1667                  //else
1668                  //mlvP->set = FALSE;
1669                         
1670                }
1671            }     
1672           
1673        }
1674      else
1675        {               
1676          for(; ev < end; ev++)
1677            {
1678              *ev = 0;       
1679            }
1680        }
1681    } 
1682 
1683  return TRUE;
1684}
1685
1686  /* AxML modification end*/
1687
1688
1689
1690
1691
1692
1693
1694void freeTree (tree *tr)
1695  { /* freeTree */
1696    nodeptr  p, q;
1697    int  i, tips, inter;
1698
1699    tips  = tr->mxtips;
1700    inter = tr->mxtips - 1;
1701
1702    for (i = 1; i <= tips; i++) freeTreeNode(tr->nodep[i]);
1703
1704    for (i = tips + 1; i <= tips + inter; i++) {
1705      if (p = tr->nodep[i]) {
1706        if (q = p->next) {
1707          freeTreeNode(q->next);
1708          freeTreeNode(q);
1709          }
1710        freeTreeNode(p);
1711        }
1712      }
1713
1714    Free(tr->nodep[1]);       /* Free the actual nodes */
1715  } /* freeTree */
1716
1717
1718boolean getdata (analdef *adef, rawdata *rdta, tree *tr)
1719    /* read sequences */
1720  { /* getdata */
1721    int   i, j, k, l, basesread, basesnew, ch;
1722    int   meaning[256];          /*  meaning of input characters */ 
1723    char *nameptr;
1724    boolean  allread, firstpass;
1725
1726    for (i = 0; i <= 255; i++) meaning[i] = 0;
1727    meaning['A'] =  1;
1728    meaning['B'] = 14;
1729    meaning['C'] =  2;
1730    meaning['D'] = 13;
1731    meaning['G'] =  4;
1732    meaning['H'] = 11;
1733    meaning['K'] = 12;
1734    meaning['M'] =  3;
1735    meaning['N'] = 15;
1736    meaning['O'] = 15;
1737    meaning['R'] =  5;
1738    meaning['S'] =  6;
1739    meaning['T'] =  8;
1740    meaning['U'] =  8;
1741    meaning['V'] =  7;
1742    meaning['W'] =  9;
1743    meaning['X'] = 15;
1744    meaning['Y'] = 10;
1745    meaning['?'] = 15;
1746    meaning['-'] = 15;
1747
1748    basesread = basesnew = 0;
1749
1750    allread = FALSE;
1751    firstpass = TRUE;
1752    ch = ' ';
1753
1754    while (! allread) {
1755      for (i = 1; i <= tr->mxtips; i++) {     /*  Read data line */
1756
1757        if (firstpass) {                      /*  Read species names */
1758          j = 1;
1759          while (whitechar(ch = getc(INFILE))) {  /*  Skip blank lines */
1760            if (ch == '\n')  j = 1;  else  j++;
1761            }
1762
1763          if (j > nmlngth) {
1764            printf("ERROR: Blank name for species %d; ", i);
1765            printf("check number of species,\n");
1766            printf("       number of sites, and interleave option.\n");
1767            return  FALSE;
1768            }
1769
1770          nameptr = tr->nodep[i]->name;
1771          for (k = 1; k < j; k++)  *nameptr++ = ' ';
1772
1773          while (ch != '\n' && ch != EOF) {
1774            if (whitechar(ch))  ch = ' ';
1775            *nameptr++ = ch;
1776            if (++j > nmlngth) break;
1777            ch = getc(INFILE);
1778            }
1779
1780          while (*(--nameptr) == ' ') ;          /*  remove trailing blanks */
1781          *(++nameptr) = '\0';                   /*  add null termination */
1782
1783          if (ch == EOF) {
1784            printf("ERROR: End-of-file in name of species %d\n", i);
1785            return  FALSE;
1786            }
1787          }    /* if (firstpass) */
1788
1789        j = basesread;
1790        while ((j < rdta->sites)
1791               && ((ch = getc(INFILE)) != EOF)
1792               && ((! adef->interleaved) || (ch != '\n'))) {
1793          uppercase(& ch);
1794          if (meaning[ch] || ch == '.') {
1795            j++;
1796            if (ch == '.') {
1797              if (i != 1) ch = rdta->y[1][j];
1798              else {
1799                printf("ERROR: Dot (.) found at site %d of sequence 1\n", j);
1800                return  FALSE;
1801                }
1802              }
1803            rdta->y[i][j] = ch;
1804            }
1805          else if (whitechar(ch) || digitchar(ch)) ;
1806          else {
1807            printf("ERROR: Bad base (%c) at site %d of sequence %d\n",
1808                    ch, j, i);
1809            return  FALSE;
1810            }
1811          }
1812
1813        if (ch == EOF) {
1814          printf("ERROR: End-of-file at site %d of sequence %d\n", j, i);
1815          return  FALSE;
1816          }
1817
1818        if (! firstpass && (j == basesread)) i--;        /* no data on line */
1819        else if (i == 1) basesnew = j;
1820        else if (j != basesnew) {
1821          printf("ERROR: Sequences out of alignment\n");
1822          printf("%d (instead of %d) residues read in sequence %d\n",
1823                  j - basesread, basesnew - basesread, i);
1824          return  FALSE;
1825          }
1826
1827        while (ch != '\n' && ch != EOF) ch = getc(INFILE);  /* flush line */
1828        }                                                  /* next sequence */
1829      firstpass = FALSE;
1830      basesread = basesnew;
1831      allread = (basesread >= rdta->sites);
1832      }
1833
1834    /*  Print listing of sequence alignment */
1835
1836    if (adef->prdata) {
1837      j = nmlngth - 5 + ((rdta->sites + ((rdta->sites - 1)/10))/2);
1838      if (j < nmlngth - 1) j = nmlngth - 1;
1839      if (j > 37) j = 37;
1840      printf("Name"); for (i=1;i<=j;i++) putchar(' '); printf("Sequences\n");
1841      printf("----"); for (i=1;i<=j;i++) putchar(' '); printf("---------\n");
1842      putchar('\n');
1843
1844      for (i = 1; i <= rdta->sites; i += 60) {
1845        l = i + 59;
1846        if (l > rdta->sites) l = rdta->sites;
1847
1848        if (adef->userwgt) {
1849          printf("Weights   ");
1850          for (j = 11; j <= nmlngth+3; j++) putchar(' ');
1851          for (k = i; k <= l; k++) {
1852            putchar(itobase36(rdta->wgt[k]));
1853            if (((k % 10) == 0) && (k < l)) putchar(' ');
1854            }
1855          putchar('\n');
1856          }
1857
1858        if (rdta->categs > 1) {
1859          printf("Categories");
1860          for (j = 11; j <= nmlngth+3; j++) putchar(' ');
1861          for (k = i; k <= l; k++) {
1862            putchar(itobase36(rdta->sitecat[k]));
1863            if (((k % 10) == 0) && (k < l)) putchar(' ');
1864            }
1865          putchar('\n');
1866          }
1867
1868        for (j = 1; j <= tr->mxtips; j++) {
1869          nameptr = tr->nodep[j]->name;
1870          k = nmlngth+3;
1871          while (ch = *nameptr++) {putchar(ch); k--;}
1872          while (--k >= 0) putchar(' ');
1873
1874          for (k = i; k <= l; k++) {
1875            ch = rdta->y[j][k];
1876            if ((j > 1) && (ch == rdta->y[1][k])) ch = '.';
1877            putchar(ch);
1878            if (((k % 10) == 0) && (k < l)) putchar(' ');
1879            }
1880          putchar('\n');
1881          }
1882        putchar('\n');
1883        }
1884      }
1885
1886    for (j = 1; j <= tr->mxtips; j++)    /* Convert characters to meanings */
1887      for (i = 1; i <= rdta->sites; i++) {
1888        rdta->y[j][i] = meaning[rdta->y[j][i]];
1889        }
1890
1891    return  TRUE;
1892  } /* getdata */
1893
1894
1895boolean  getntrees (analdef *adef)
1896  { /* getntrees */
1897
1898    if (fscanf(INFILE, "%d", &(adef->numutrees)) != 1 || findch('\n') == EOF) {
1899      printf("ERROR: Problem reading number of user trees\n");
1900      return  FALSE;
1901      }
1902
1903    if (adef->nkeep == 0) adef->nkeep = adef->numutrees;
1904
1905    return  TRUE;
1906  } /* getntrees */
1907
1908
1909boolean getinput (analdef *adef, rawdata *rdta, cruncheddata *cdta, tree *tr)
1910  { /* getinput */
1911    if (! getnums(rdta))                       return FALSE;
1912    if (! getoptions(adef, rdta, cdta, tr))    return FALSE;
1913    if (! adef->empf && ! getbasefreqs(rdta))  return FALSE;
1914    if (! getyspace(rdta))                     return FALSE;
1915    if (! setupTree(tr, rdta->sites))          return FALSE;
1916    if (! getdata(adef, rdta, tr))             return FALSE;
1917    if (adef->usertree && ! getntrees(adef))   return FALSE;
1918
1919    return TRUE;
1920  } /* getinput */
1921
1922
1923void makeboot (analdef *adef, rawdata *rdta, cruncheddata *cdta)
1924  { /* makeboot */
1925    int  i, j, nonzero;
1926    double  randum();
1927
1928    nonzero = 0;
1929    for (i = 1; i <= rdta->sites; i++)  if (rdta->wgt[i] > 0) nonzero++;
1930
1931    for (j = 1; j <= nonzero; j++) cdta->aliaswgt[j] = 0;
1932    for (j = 1; j <= nonzero; j++)
1933      cdta->aliaswgt[(int) (nonzero*randum(& adef->boot)) + 1]++;
1934
1935    j = 0;
1936    cdta->wgtsum = 0;
1937    for (i = 1; i <= rdta->sites; i++) {
1938      if (rdta->wgt[i] > 0)
1939        cdta->wgtsum += (rdta->wgt2[i] = rdta->wgt[i] * cdta->aliaswgt[++j]);
1940      else
1941        rdta->wgt2[i] = 0;
1942      }
1943  } /* makeboot */
1944
1945
1946void sitesort (rawdata *rdta, cruncheddata *cdta)
1947    /* Shell sort keeping sites with identical residues and weights in
1948     * the original order (i.e., a stable sort).
1949     * The index created in cdta->alias is 1 based.  The
1950     * sitecombcrunch routine packs it to a 0 based index.
1951     */
1952  { /* sitesort */
1953    int  gap, i, j, jj, jg, k, n, nsp;
1954    int  *index, *category;
1955    boolean  flip, tied;
1956    yType  **data;
1957
1958    index    = cdta->alias;
1959    category = rdta->sitecat;
1960    data     = rdta->y;
1961    n        = rdta->sites;
1962    nsp      = rdta->numsp;
1963
1964    for (gap = n / 2; gap > 0; gap /= 2) {
1965      for (i = gap + 1; i <= n; i++) {
1966        j = i - gap;
1967
1968        do {
1969          jj = index[j];
1970          jg = index[j+gap];
1971          flip = (category[jj] >  category[jg]);
1972          tied = (category[jj] == category[jg]);
1973          for (k = 1; (k <= nsp) && tied; k++) {
1974            flip = (data[k][jj] >  data[k][jg]);
1975            tied = (data[k][jj] == data[k][jg]);
1976            }
1977          if (flip) {
1978            index[j]     = jg;
1979            index[j+gap] = jj;
1980            j -= gap;
1981            }
1982          } while (flip && (j > 0));
1983
1984        }  /* for (i ...   */
1985      }    /* for (gap ... */
1986  } /* sitesort */
1987
1988
1989void sitecombcrunch (rawdata *rdta, cruncheddata *cdta)
1990    /* combine sites that have identical patterns (and nonzero weight) */
1991  { /* sitecombcrunch */
1992    int  i, sitei, j, sitej, k;
1993    boolean  tied;
1994
1995    i = 0;
1996    cdta->alias[0] = cdta->alias[1];
1997    cdta->aliaswgt[0] = 0;
1998
1999    for (j = 1; j <= rdta->sites; j++) {
2000      sitei = cdta->alias[i];
2001      sitej = cdta->alias[j];
2002      tied = (rdta->sitecat[sitei] == rdta->sitecat[sitej]);
2003
2004      for (k = 1; tied && (k <= rdta->numsp); k++)
2005        tied = (rdta->y[k][sitei] == rdta->y[k][sitej]);
2006
2007      if (tied) {
2008        cdta->aliaswgt[i] += rdta->wgt2[sitej];
2009        }
2010      else {
2011        if (cdta->aliaswgt[i] > 0) i++;
2012        cdta->aliaswgt[i] = rdta->wgt2[sitej];
2013        cdta->alias[i] = sitej;
2014        }
2015      }
2016
2017    cdta->endsite = i;
2018    if (cdta->aliaswgt[i] > 0) cdta->endsite++;
2019  } /* sitecombcrunch */
2020
2021
2022boolean makeweights (analdef *adef, rawdata *rdta, cruncheddata *cdta)
2023    /* make up weights vector to avoid duplicate computations */
2024  { /* makeweights */
2025    int  i;
2026
2027    if (adef->boot)  makeboot(adef, rdta, cdta);
2028    else  for (i = 1; i <= rdta->sites; i++)  rdta->wgt2[i] = rdta->wgt[i];
2029
2030    for (i = 1; i <= rdta->sites; i++)  cdta->alias[i] = i;
2031    sitesort(rdta, cdta);
2032    sitecombcrunch(rdta, cdta);
2033
2034    printf("Total weight of positions in analysis = %d\n", cdta->wgtsum);
2035    printf("There are %d distinct data patterns (columns)\n\n", cdta->endsite);
2036
2037    return TRUE;
2038  } /* makeweights */
2039
2040
2041
2042
2043
2044
2045boolean makevalues (rawdata *rdta, cruncheddata *cdta)
2046    /* set up fractional likelihoods at tips */
2047  { /* makevalues */
2048    double  temp, wtemp;
2049    int  i, j;
2050
2051    for (i = 1; i <= rdta->numsp; i++) {    /* Pack and move tip data */
2052      for (j = 0; j < cdta->endsite; j++) {
2053        rdta->y[i-1][j] = rdta->y[i][cdta->alias[j]];
2054        }
2055      }
2056
2057    for (j = 0; j < cdta->endsite; j++) {
2058      cdta->patcat[j] = i = rdta->sitecat[cdta->alias[j]];
2059      cdta->patrat[j] = temp = rdta->catrat[i];
2060      cdta->wr[j]  = wtemp = temp * cdta->aliaswgt[j];
2061      cdta->wr2[j] = temp * wtemp;
2062      }
2063
2064   
2065
2066    return TRUE;
2067  } /* makevalues */
2068
2069
2070boolean empiricalfreqs (rawdata *rdta, cruncheddata *cdta)
2071    /* Get empirical base frequencies from the data */
2072  { /* empiricalfreqs */
2073    double  sum, suma, sumc, sumg, sumt, wj, fa, fc, fg, ft;
2074    int     i, j, k, code;
2075    yType  *yptr;
2076
2077    rdta->freqa = 0.25;
2078    rdta->freqc = 0.25;
2079    rdta->freqg = 0.25;
2080    rdta->freqt = 0.25;
2081    for (k = 1; k <= 8; k++) {
2082      suma = 0.0;
2083      sumc = 0.0;
2084      sumg = 0.0;
2085      sumt = 0.0;
2086      for (i = 0; i < rdta->numsp; i++) {
2087        yptr = rdta->y[i];
2088        for (j = 0; j < cdta->endsite; j++) {
2089          code = *yptr++;
2090          fa = rdta->freqa * ( code       & 1);
2091          fc = rdta->freqc * ((code >> 1) & 1);
2092          fg = rdta->freqg * ((code >> 2) & 1);
2093          ft = rdta->freqt * ((code >> 3) & 1);
2094          wj = cdta->aliaswgt[j] / (fa + fc + fg + ft);
2095          suma += wj * fa;
2096          sumc += wj * fc;
2097          sumg += wj * fg;
2098          sumt += wj * ft;
2099          }
2100        }
2101      sum = suma + sumc + sumg + sumt;
2102      rdta->freqa = suma / sum;
2103      rdta->freqc = sumc / sum;
2104      rdta->freqg = sumg / sum;
2105      rdta->freqt = sumt / sum;
2106      }
2107
2108    return TRUE;
2109  } /* empiricalfreqs */
2110
2111
2112void reportfreqs (analdef *adef, rawdata *rdta)
2113  { /* reportfreqs */
2114    double  suma, sumb;
2115
2116    if (adef->empf) printf("Empirical ");
2117    printf("Base Frequencies:\n\n");
2118    printf("   A    %10.5f\n",   rdta->freqa);
2119    printf("   C    %10.5f\n",   rdta->freqc);
2120    printf("   G    %10.5f\n",   rdta->freqg);
2121    printf("  T(U)  %10.5f\n\n", rdta->freqt);
2122    rdta->freqr = rdta->freqa + rdta->freqg;
2123    rdta->invfreqr = 1.0/rdta->freqr;
2124    rdta->freqar = rdta->freqa * rdta->invfreqr;
2125    rdta->freqgr = rdta->freqg * rdta->invfreqr;
2126    rdta->freqy = rdta->freqc + rdta->freqt;
2127    rdta->invfreqy = 1.0/rdta->freqy;
2128    rdta->freqcy = rdta->freqc * rdta->invfreqy;
2129    rdta->freqty = rdta->freqt * rdta->invfreqy;
2130    printf("Transition/transversion ratio = %10.6f\n\n", rdta->ttratio);
2131    suma = rdta->ttratio*rdta->freqr*rdta->freqy
2132         - (rdta->freqa*rdta->freqg + rdta->freqc*rdta->freqt);
2133    sumb = rdta->freqa*rdta->freqgr + rdta->freqc*rdta->freqty;
2134    rdta->xi = suma/(suma+sumb);
2135    rdta->xv = 1.0 - rdta->xi;
2136    if (rdta->xi <= 0.0) {
2137      printf("WARNING: This transition/transversion ratio\n");
2138      printf("         is impossible with these base frequencies!\n");
2139      printf("Transition/transversion parameter reset\n\n");
2140      rdta->xi = 0.000001;
2141      rdta->xv = 1.0 - rdta->xi;
2142      rdta->ttratio = (sumb * rdta->xi / rdta->xv
2143                       + rdta->freqa * rdta->freqg
2144                       + rdta->freqc * rdta->freqt)
2145                    / (rdta->freqr * rdta->freqy);
2146      printf("Transition/transversion ratio = %10.6f\n\n", rdta->ttratio);
2147      }
2148    printf("(Transition/transversion parameter = %10.6f)\n\n",
2149            rdta->xi/rdta->xv);
2150    rdta->fracchange = 2.0 * rdta->xi * (rdta->freqa * rdta->freqgr
2151                                       + rdta->freqc * rdta->freqty)
2152                     + rdta->xv * (1.0 - rdta->freqa * rdta->freqa
2153                                       - rdta->freqc * rdta->freqc
2154                                       - rdta->freqg * rdta->freqg
2155                                       - rdta->freqt * rdta->freqt);
2156  } /* reportfreqs */
2157
2158
2159boolean linkdata2tree (rawdata *rdta, cruncheddata *cdta, tree *tr)
2160    /* Link data array to the tree tips */
2161  { /* linkdata2tree */
2162    int  i;
2163    int  j;
2164    yType *tip;
2165    int ref[EQUALITIES];
2166    tr->rdta       = rdta;
2167    tr->cdta       = cdta;
2168
2169    for(i = 0; i < EQUALITIES; i++)
2170      ref[i] = 0;
2171    equalities = 0;
2172
2173
2174    for (i = 1; i <= tr->mxtips; i++) {    /* Associate data with tips */
2175      tr->nodep[i]->tip = &(rdta->y[i-1][0]);
2176      tip =  tr->nodep[i]->tip;
2177      for(j = 0; j < tr->cdta->endsite; j++)
2178        {
2179          if(ref[tip[j]] == 0)
2180            ref[tip[j]] = 1; 
2181        }
2182      }
2183
2184     for(i = 0; i < EQUALITIES; i++)
2185       {
2186         if(ref[i] == 1) 
2187           {
2188             map[i] = equalities++;               
2189           }
2190         else
2191           map[i] = -1;
2192       }
2193     
2194     map2 = (char *)malloc(equalities * sizeof(char));
2195
2196     j = 0;
2197
2198     for(i = 0; i < EQUALITIES; i++)
2199       {
2200         if(ref[i] == 1)
2201           {
2202             map2[j] = i;
2203             j++;
2204           }
2205       }
2206 
2207   
2208
2209    return TRUE;
2210  } /* linkdata2tree */
2211
2212
2213xarray *setupxarray (int npat)
2214  { /* setupxarray */
2215    xarray        *x;
2216    likelivector  *data;
2217
2218    x = (xarray *) Malloc(sizeof(xarray));
2219    if (x) {
2220      data = (likelivector *) Malloc(npat * sizeof(likelivector));
2221      if (data) {
2222        x->lv = data;
2223        x->prev = x->next = x;
2224        x->owner = (node *) NULL;
2225        }
2226      else {
2227        Free(x);
2228        return (xarray *) NULL;
2229        }
2230      }
2231    return x;
2232  } /* setupxarray */
2233
2234
2235boolean linkxarray (int req, int min, int npat,
2236                    xarray **freexptr, xarray **usedxptr)
2237    /*  Link a set of xarrays */
2238  { /* linkxarray */
2239    xarray  *first, *prev, *x;
2240    int  i;
2241
2242    first = prev = (xarray *) NULL;
2243    i = 0;
2244
2245    do {
2246      x = setupxarray(npat);
2247      if (x) {
2248        if (! first) first = x;
2249        else {
2250          prev->next = x;
2251          x->prev = prev;
2252          }
2253        prev = x;
2254        i++;
2255        }
2256      else {
2257        printf("ERROR: Failure to get requested xarray memory\n");
2258        if (i < min)  return  FALSE;
2259        }
2260      } while ((i < req) && x);
2261
2262    if (first) {
2263      first->prev = prev;
2264      prev->next = first;
2265      }
2266
2267    *freexptr = first;
2268    *usedxptr = (xarray *) NULL;
2269
2270    return  TRUE;
2271  } /* linkxarray */
2272
2273
2274boolean setupnodex (tree *tr)
2275  { /* setupnodex */
2276    nodeptr  p;
2277    int  i;
2278
2279    for (i = tr->mxtips + 1; (i <= 2*(tr->mxtips) - 2); i++) {
2280      p = tr->nodep[i];
2281      if (! (p->x = setupxarray(tr->cdta->endsite))) {
2282        printf("ERROR: Failure to get internal node xarray memory\n");
2283        return  FALSE;
2284        }
2285      }
2286
2287    return  TRUE;
2288  } /* setupnodex */
2289
2290
2291xarray *getxtip (nodeptr p)
2292  { /* getxtip */
2293    xarray  *new;
2294    boolean  splice;
2295
2296    if (! p) return (xarray *) NULL;
2297
2298    splice = FALSE;
2299
2300    if (p->x) {                  /* array is there; move to tail of list */
2301      new = p->x;
2302      if (new == new->prev) ;             /* linked to self; leave it */
2303      else if (new == usedxtip) usedxtip = usedxtip->next; /* at head */
2304      else if (new == usedxtip->prev) ;   /* already at tail */
2305      else {                              /* move to tail of list */
2306        new->prev->next = new->next;
2307        new->next->prev = new->prev;
2308        splice = TRUE;
2309        }
2310      }
2311
2312    else if (freextip) {                 /* take from unused list */
2313      p->x = new = freextip;
2314      new->owner = p;
2315      if (new->prev != new) {            /* not only member of freelist */
2316        new->prev->next = new->next;
2317        new->next->prev = new->prev;
2318        freextip = new->next;
2319        }
2320      else
2321        freextip = (xarray *) NULL;
2322
2323      splice = TRUE;
2324      }
2325
2326    else if (usedxtip) {                 /* take from head of used list */
2327      usedxtip->owner->x = (xarray *) NULL;
2328      p->x = new = usedxtip;
2329      new->owner = p;
2330      usedxtip = usedxtip->next;
2331      }
2332
2333    else {
2334      printf("ERROR: Unable to locate memory for tip %d.\n", p->number);
2335      return  (xarray *) NULL;
2336      }
2337
2338    if (splice) {
2339      if (usedxtip) {                  /* list is not empty */
2340        usedxtip->prev->next = new;
2341        new->prev = usedxtip->prev;
2342        usedxtip->prev = new;
2343        new->next = usedxtip;
2344        }
2345      else
2346        usedxtip = new->prev = new->next = new;
2347      }
2348
2349    return  new;
2350  } /* getxtip */
2351
2352
2353xarray *getxnode (nodeptr p)
2354    /* Ensure that internal node p has memory */
2355  { /* getxnode */
2356    nodeptr  s;
2357
2358    if (! (p->x)) {  /*  Move likelihood array on this node to sector p */
2359      if ((s = p->next)->x || (s = s->next)->x) {
2360        p->x = s->x;
2361        s->x = (xarray *) NULL;
2362        }
2363      else {
2364        printf("ERROR: Unable to locate memory at node %d.\n", p->number);
2365        exit(1);
2366        }
2367      }
2368    return  p->x;
2369  } /* getxnode */
2370
2371
2372 /* AxML modification start*/
2373 /* optimized version of function newview(), implementing homogeneous and */
2374 /* partially heterogeneous subtree equality vectors */
2375
2376
2377printhq(long *hq, tree *tr)
2378{
2379  int i;
2380  for(i = 0; i < tr->cdta->endsite; i++)
2381    fprintf(stderr,"%ld ", hq[i]);
2382  fprintf(stderr,"\n");
2383}
2384
2385
2386
2387boolean newviewOptimized(tree *tr, nodeptr p)        /*  Update likelihoods at node */
2388  { /* newviewOptimized */
2389    double   zq, lzq, xvlzq, zr, lzr, xvlzr;
2390    nodeptr  q, r, realP;
2391    likelivector *lp, *lq, *lr;
2392    homType *mlvP;
2393    int  i, j;
2394           
2395    if (p->tip) {             /*  Make sure that data are at tip */
2396   
2397      if (p->x) return TRUE;  /*  They are already there */
2398
2399      if (! getxtip(p)) return FALSE; /*  They are not, so get memory */     
2400     
2401      return TRUE;
2402      }
2403
2404/*  Internal node needs update */
2405
2406    q = p->next->back;
2407    r = p->next->next->back;
2408
2409    while ((! p->x) || (! q->x) || (! r->x)) {
2410      /* rekursiver aufruf */
2411      if (! q->x) if (! newviewOptimized(tr, q))  return FALSE;
2412      if (! r->x) if (! newviewOptimized(tr, r))  return FALSE;
2413      if (! p->x) if (! getxnode(p)) return FALSE;
2414      }
2415
2416
2417
2418    lp = p->x->lv;
2419
2420    lq = q->x->lv;
2421    zq = q->z;
2422    lzq = (zq > zmin) ? log(zq) : log(zmin);
2423    xvlzq = tr->rdta->xv * lzq;
2424
2425    lr = r->x->lv;
2426    zr = r->z;
2427    lzr = (zr > zmin) ? log(zr) : log(zmin);
2428    xvlzr = tr->rdta->xv * lzr;
2429
2430    { double  zzq, zvq,
2431        zzr, zvr, rp;
2432    double  zzqtable[maxcategories+1], zvqtable[maxcategories+1],
2433              zzrtable[maxcategories+1], zvrtable[maxcategories+1],
2434             *zzqptr, *zvqptr, *zzrptr, *zvrptr, *rptr;
2435      double  fxqr, fxqy, fxqn, sumaq, sumgq, sumcq, sumtq,
2436              fxrr, fxry, fxrn, ki, tempi, tempj;               
2437      register  char *s1; 
2438      register  char *s2;
2439      register char *eqptr;
2440      int  *cptr;
2441      int cat;
2442      homType *mlvR, *mlvQ;
2443      poutsa calc[EQUALITIES][maxcategories],calcR[EQUALITIES][maxcategories], *calcptr, *calcptrR;
2444      long ref, ref2, mexp;     
2445      nodeptr realQ, realR;
2446
2447     
2448      rptr   = &(tr->rdta->catrat[1]);
2449      zzqptr = &(zzqtable[1]);
2450      zvqptr = &(zvqtable[1]);
2451      zzrptr = &(zzrtable[1]);
2452      zvrptr = &(zvrtable[1]);
2453      /* get equality vectors of p, q, and r */
2454     
2455      realP =  tr->nodep[p->number];
2456   
2457     
2458      realQ =  tr->nodep[q->number];
2459      realR =  tr->nodep[r->number];
2460
2461      eqptr = realP->equalityVector; 
2462      s1 = realQ->equalityVector;
2463      s2 = realR->equalityVector;
2464                 
2465   
2466       for (j = 1; j <= tr->rdta->categs; j++) 
2467         {       
2468           ki = *rptr++;
2469           *zzqptr++ = zzq = exp(ki *   lzq);
2470           *zvqptr++ = zvq = exp(ki * xvlzq);
2471           *zzrptr++ = zzr = exp(ki *   lzr);
2472           *zvrptr++ = zvr = exp(ki * xvlzr);     
2473                 
2474           for(i = 0; i < equalities; i++)
2475             {
2476               
2477               mlvQ = &realQ->mlv[i][j];
2478
2479               if(mlvQ->set)
2480                 {
2481                   calcptr = &calc[i][j];               
2482                   fxqr = tr->rdta->freqa * mlvQ->a + tr->rdta->freqg * mlvQ->g;
2483                   fxqy = tr->rdta->freqc * mlvQ->c + tr->rdta->freqt * mlvQ->t;
2484                   fxqn = fxqr + fxqy;
2485                   tempi = fxqr * tr->rdta->invfreqr;
2486                   tempj = zvq * (tempi-fxqn) + fxqn;
2487                   calcptr->sumaq = zzq * (mlvQ->a - tempi) + tempj;
2488                   calcptr->sumgq = zzq * (mlvQ->g - tempi) + tempj;
2489                   tempi = fxqy * tr->rdta->invfreqy;
2490                   tempj = zvq * (tempi-fxqn) + fxqn;
2491                   calcptr->sumcq = zzq * (mlvQ->c - tempi) + tempj;
2492                   calcptr->sumtq = zzq * (mlvQ->t - tempi) + tempj;
2493                   calcptr->exp = mlvQ->exp;
2494                 }
2495               
2496               mlvR = &realR->mlv[i][j];
2497
2498               if(mlvR->set)
2499                 {
2500                   calcptrR = &calcR[i][j];             
2501                   fxrr = tr->rdta->freqa * mlvR->a + tr->rdta->freqg * mlvR->g;
2502                   fxry = tr->rdta->freqc * mlvR->c + tr->rdta->freqt * mlvR->t;
2503                   fxrn = fxrr + fxry;
2504                   tempi = fxrr * tr->rdta->invfreqr;
2505                   tempj = zvr * (tempi-fxrn) + fxrn;
2506                   calcptrR->sumaq = zzr * (mlvR->a - tempi) + tempj;
2507                   calcptrR->sumgq = zzr * (mlvR->g - tempi) + tempj;
2508                   tempi = fxry * tr->rdta->invfreqy;
2509                   tempj = zvr * (tempi-fxrn) + fxrn;
2510                   calcptrR->sumcq = zzr * (mlvR->c - tempi) + tempj;
2511                   calcptrR->sumtq = zzr * (mlvR->t - tempi) + tempj;                                   
2512                   calcptrR->exp = mlvR->exp;                   
2513                 }
2514               
2515               if(mlvR->set && mlvQ->set)
2516                 {
2517                   mlvP = &realP->mlv[i][j];
2518
2519                   mlvP->a = calcptrR->sumaq * calcptr->sumaq;
2520                   mlvP->g = calcptrR->sumgq * calcptr->sumgq;             
2521                   mlvP->c = calcptrR->sumcq * calcptr->sumcq; 
2522                   mlvP->t = calcptrR->sumtq * calcptr->sumtq;
2523                   mlvP->exp = calcptrR->exp + calcptr->exp;
2524                   if (mlvP->a < minlikelihood && mlvP->g < minlikelihood
2525                       && mlvP->c < minlikelihood && mlvP->t < minlikelihood) {
2526                     mlvP->a   *= twotothe256;
2527                     mlvP->g   *= twotothe256;
2528                     mlvP->c   *= twotothe256;
2529                     mlvP->t   *= twotothe256;
2530                     mlvP->exp += 1;
2531                   }
2532                   
2533                   mlvP->set = TRUE;
2534                 }
2535               else
2536                 mlvP->set = FALSE;
2537               
2538             }
2539         }
2540
2541       cptr = &(tr->cdta->patcat[0]);
2542
2543      if(r->tip && q->tip)
2544        {
2545           for (i = 0; i < tr->cdta->endsite; i++) 
2546            {
2547              ref = *s2++;
2548              ref2 = *s1++;
2549              cat = *cptr++;
2550
2551                       
2552              if(ref2 != ref)
2553                {
2554                  *eqptr++ = -1;
2555                  calcptrR = &calcR[ref][cat];
2556                  calcptr = &calc[ref2][cat];
2557                  lp->a = calcptrR->sumaq * calcptr->sumaq;
2558                  lp->g = calcptrR->sumgq * calcptr->sumgq;                 
2559                  lp->c = calcptrR->sumcq * calcptr->sumcq; 
2560                  lp->t = calcptrR->sumtq * calcptr->sumtq;
2561                  lp->exp = calcptrR->exp + calcptr->exp;
2562                  if (lp->a < minlikelihood && lp->g < minlikelihood
2563                      && lp->c < minlikelihood && lp->t < minlikelihood) {
2564                    lp->a   *= twotothe256;
2565                    lp->g   *= twotothe256;
2566                    lp->c   *= twotothe256;
2567                    lp->t   *= twotothe256;
2568                    lp->exp += 1;
2569                  }
2570                   
2571                }
2572              else
2573                {
2574                  *eqptr++ = ref;                               
2575                }
2576              lp++;
2577                           
2578            }         
2579        }
2580      else
2581        {
2582                 
2583         
2584          for (i = 0; i < tr->cdta->endsite; i++) 
2585            {
2586              ref = *s2++;
2587              ref2 = *s1++;
2588              cat = *cptr++;
2589             
2590              if(ref2 >= 0)
2591                {                       
2592                  if(ref2 == ref)
2593                    {
2594                      *eqptr++ = ref;                             
2595                      goto incTip;                                                                                     
2596                    }
2597                  calcptr = &calc[ref2][cat];
2598                  sumaq = calcptr->sumaq;
2599                  sumgq = calcptr->sumgq;
2600                  sumcq = calcptr->sumcq;
2601                  sumtq = calcptr->sumtq;                                       
2602                  mexp = calcptr->exp;         
2603                 
2604                }                                       
2605              else
2606                {               
2607                  zzq = zzqtable[cat];
2608                  zvq = zvqtable[cat];
2609                  fxqr = tr->rdta->freqa * lq->a + tr->rdta->freqg * lq->g;
2610                  fxqy = tr->rdta->freqc * lq->c + tr->rdta->freqt * lq->t;
2611                  fxqn = fxqr + fxqy;
2612                  tempi = fxqr * tr->rdta->invfreqr;
2613                  tempj = zvq * (tempi-fxqn) + fxqn;
2614                  sumaq = zzq * (lq->a - tempi) + tempj;
2615                  sumgq = zzq * (lq->g - tempi) + tempj;
2616                  tempi = fxqy * tr->rdta->invfreqy;
2617                  tempj = zvq * (tempi-fxqn) + fxqn;
2618                  sumcq = zzq * (lq->c - tempi) + tempj;
2619                  sumtq = zzq * (lq->t - tempi) + tempj;
2620                  mexp = lq->exp;
2621                }
2622             
2623             
2624              if(ref >= 0)
2625                {
2626                  calcptr = &calcR[ref][cat];                       
2627                  lp->a = sumaq * calcptr->sumaq;
2628                  lp->g = sumgq * calcptr->sumgq;                   
2629                  lp->c = sumcq * calcptr->sumcq; 
2630                  lp->t = sumtq * calcptr->sumtq;
2631                  lp->exp = mexp + calcptr->exp;                         
2632                }
2633              else
2634                {
2635                  zzr = zzrtable[cat];
2636                  zvr = zvrtable[cat];
2637                  fxrr = tr->rdta->freqa * lr->a + tr->rdta->freqg * lr->g;
2638                  fxry = tr->rdta->freqc * lr->c + tr->rdta->freqt * lr->t;
2639                  fxrn = fxrr + fxry;
2640                  tempi = fxrr * tr->rdta->invfreqr;
2641                  tempj = zvr * (tempi-fxrn) + fxrn;
2642                  lp->a = sumaq * (zzr * (lr->a - tempi) + tempj);
2643                  lp->g = sumgq * (zzr * (lr->g - tempi) + tempj);
2644                  tempi = fxry * tr->rdta->invfreqy;
2645                  tempj = zvr * (tempi-fxrn) + fxrn;
2646                  lp->c = sumcq * (zzr * (lr->c - tempi) + tempj);
2647                  lp->t = sumtq * (zzr * (lr->t - tempi) + tempj);
2648                  lp->exp = mexp + lr->exp;
2649                }
2650             
2651              if (lp->a < minlikelihood && lp->g < minlikelihood
2652                  && lp->c < minlikelihood && lp->t < minlikelihood) {
2653                lp->a   *= twotothe256;
2654                lp->g   *= twotothe256;
2655                lp->c   *= twotothe256;
2656                lp->t   *= twotothe256;
2657                lp->exp += 1;
2658              }
2659             
2660              *eqptr++ = -1;
2661            incTip:
2662              lp++;
2663              lq++;
2664              lr++;     
2665            }         
2666        }
2667    }
2668                 
2669
2670    return TRUE; 
2671  } /* newviewOptimized */
2672
2673 /* AxML modification end*/
2674
2675double evaluate (tree *tr, nodeptr p)
2676  { /* evaluate */
2677    double   sum, z, lz, xvlz,
2678             ki, fx1a, fx1c, fx1g, fx1t, fx1r, fx1y, fx2r, fx2y,
2679             suma, sumb, sumc, term;
2680
2681
2682    double   zz, zv;
2683    double        zztable[maxcategories+1], zvtable[maxcategories+1],
2684       *zzptr, *zvptr;   
2685    double       *log_f, *rptr;
2686    likelivector *lp, *lq;
2687    homType *mlvP, *mlvQ;
2688    nodeptr       q, realQ, realP;
2689    int           i, *wptr, cat, *cptr, j;
2690    register  char *sQ; 
2691    register  char *sP;
2692    long refQ, refP;
2693    memP calcP[EQUALITIES][maxcategories], *calcptrP;
2694    memQ calcQ[EQUALITIES][maxcategories], *calcptrQ;
2695
2696    q = p->back;
2697
2698    while ((! p->x) || (! q->x)) {
2699      if (! (p->x)) if (! newviewOptimized(tr, p)) return badEval;
2700      if (! (q->x)) if (! newviewOptimized(tr, q)) return badEval;
2701    }
2702
2703    lp = p->x->lv;
2704    lq = q->x->lv;
2705
2706    z = p->z;
2707    if (z < zmin) z = zmin;
2708    lz = log(z);
2709    xvlz = tr->rdta->xv * lz;
2710
2711    rptr  = &(tr->rdta->catrat[1]);
2712    zzptr = &(zztable[1]);
2713    zvptr = &(zvtable[1]);
2714   
2715   
2716    cptr = &(tr->cdta->patcat[0]); 
2717    wptr = &(tr->cdta->aliaswgt[0]);
2718    log_f = tr->log_f;
2719    tr->log_f_valid = tr->cdta->endsite;
2720    sum = 0.0;
2721   
2722    realQ =  tr->nodep[q->number];
2723    realP =  tr->nodep[p->number];
2724    sQ = realQ->equalityVector;
2725    sP = realP->equalityVector; 
2726   
2727
2728    for (j = 1; j <= tr->rdta->categs; j++) 
2729      { 
2730        ki = *rptr++;
2731        *zzptr++ = exp(ki *   lz);
2732        *zvptr++ = exp(ki * xvlz); 
2733
2734        for(i = 0; i < equalities; i++)
2735          { 
2736           
2737            mlvP = &realP->mlv[i][j];
2738            if(mlvP->set)
2739              {
2740                calcptrP = &calcP[i][j];                 
2741                calcptrP->fx1a = tr->rdta->freqa * mlvP->a;
2742                calcptrP->fx1g = tr->rdta->freqg * mlvP->g;
2743                calcptrP->fx1c = tr->rdta->freqc * mlvP->c;
2744                calcptrP->fx1t = tr->rdta->freqt * mlvP->t;
2745                calcptrP->sumag = calcptrP->fx1a + calcptrP->fx1g;
2746                calcptrP->sumct = calcptrP->fx1c + calcptrP->fx1t;
2747                calcptrP->sumagct = calcptrP->sumag + calcptrP->sumct;       
2748                calcptrP->exp = mlvP->exp;
2749              }
2750            mlvQ = &realQ->mlv[i][j]; 
2751            if(mlvQ->set)
2752              {
2753                calcptrQ = &calcQ[i][j];
2754                calcptrQ->fx2r = tr->rdta->freqa * mlvQ->a + tr->rdta->freqg * mlvQ->g;     
2755                calcptrQ->fx2y  = tr->rdta->freqc * mlvQ->c + tr->rdta->freqt * mlvQ->t;             
2756                calcptrQ->sumfx2rfx2y = calcptrQ->fx2r + calcptrQ->fx2y;             
2757                calcptrQ->exp = mlvQ->exp;
2758                calcptrQ->a = mlvQ->a;
2759                calcptrQ->c = mlvQ->c;
2760                calcptrQ->g = mlvQ->g;
2761                calcptrQ->t = mlvQ->t;
2762              }
2763         
2764          }
2765      }
2766
2767
2768
2769
2770      for (i = 0; i < tr->cdta->endsite; i++) {
2771         refQ = *sQ++;
2772         refP = *sP++;
2773         cat  = *cptr++;
2774         zz   = zztable[cat];
2775         zv   = zvtable[cat];
2776         if(refP >= 0)
2777           {
2778             if(refQ >= 0)
2779               {
2780                 calcptrP = &calcP[refP][cat];
2781                 calcptrQ = &calcQ[refQ][cat];
2782                 suma = calcptrP->fx1a * calcptrQ->a + 
2783                   calcptrP->fx1c * calcptrQ->c + 
2784                   calcptrP->fx1g * calcptrQ->g + calcptrP->fx1t * calcptrQ->t;                         
2785                 
2786                 sumc = calcptrP->sumagct * calcptrQ->sumfx2rfx2y;
2787                 sumb = calcptrP->sumag * calcptrQ->fx2r * tr->rdta->invfreqr + calcptrP->sumct * calcptrQ->fx2y * tr->rdta->invfreqy;
2788                 suma -= sumb;
2789                 sumb -= sumc;
2790                 term = log(zz * suma + zv * sumb + sumc) + 
2791                   (calcptrP->exp + calcptrQ->exp)*log(minlikelihood);
2792                 sum += *wptr++ * term;
2793               
2794                 *log_f++ = term;
2795                 lp++;
2796                 lq++;
2797               }
2798             else
2799               {
2800                 calcptrP = &calcP[refP][cat];
2801                 suma = calcptrP->fx1a * lq->a + calcptrP->fx1c * lq->c + 
2802                   calcptrP->fx1g * lq->g + calcptrP->fx1t * lq->t;
2803                 
2804                 fx2r = tr->rdta->freqa * lq->a + tr->rdta->freqg * lq->g;
2805                 fx2y = tr->rdta->freqc * lq->c + tr->rdta->freqt * lq->t;
2806                 
2807                 sumc = calcptrP->sumagct * (fx2r + fx2y);
2808                 sumb       = calcptrP->sumag * fx2r * tr->rdta->invfreqr + calcptrP->sumct * fx2y * tr->rdta->invfreqy;
2809                 suma -= sumb;
2810                 sumb -= sumc;
2811                 term = log(zz * suma + zv * sumb + sumc) + 
2812                   (calcptrP->exp + lq->exp)*log(minlikelihood);
2813                 sum += *wptr++ * term;
2814                 
2815                 *log_f++ = term;
2816                 lp++;
2817                 lq++;
2818               }
2819           }
2820         else
2821           {
2822             if(refQ >= 0)
2823               {
2824                calcptrQ = &calcQ[refQ][cat];
2825                fx1a = tr->rdta->freqa * lp->a;
2826                fx1g = tr->rdta->freqg * lp->g;
2827                fx1c = tr->rdta->freqc * lp->c;
2828                fx1t = tr->rdta->freqt * lp->t;
2829                suma = fx1a * calcptrQ->a + fx1c * calcptrQ->c + 
2830                  fx1g * calcptrQ->g + fx1t * calcptrQ->t;       
2831                fx1r = fx1a + fx1g;
2832                fx1y = fx1c + fx1t;
2833                sumc = (fx1r + fx1y) * calcptrQ->sumfx2rfx2y; 
2834                sumb = fx1r * calcptrQ->fx2r * tr->rdta->invfreqr + fx1y * calcptrQ->fx2y * tr->rdta->invfreqy;
2835                suma -= sumb;
2836                sumb -= sumc;   
2837                term = log(zz * suma + zv * sumb + sumc) + 
2838                  (lp->exp + calcptrQ->exp)*log(minlikelihood);         
2839                sum += *wptr++ * term; 
2840                *log_f++ = term;
2841                lp++;
2842                lq++;
2843               }
2844             else
2845               {
2846                 fx1a = tr->rdta->freqa * lp->a;
2847                 fx1g = tr->rdta->freqg * lp->g;
2848                 fx1c = tr->rdta->freqc * lp->c;
2849                 fx1t = tr->rdta->freqt * lp->t;
2850                 suma = fx1a * lq->a + fx1c * lq->c + fx1g * lq->g + fx1t * lq->t;
2851                 fx2r = tr->rdta->freqa * lq->a + tr->rdta->freqg * lq->g;
2852                 fx2y = tr->rdta->freqc * lq->c + tr->rdta->freqt * lq->t;
2853                 fx1r = fx1a + fx1g;
2854                 fx1y = fx1c + fx1t;
2855                 sumc = (fx1r + fx1y) * (fx2r + fx2y);
2856                 sumb = fx1r * fx2r * tr->rdta->invfreqr + fx1y * fx2y * tr->rdta->invfreqy;
2857                 suma -= sumb;
2858                 sumb -= sumc;
2859                 term = log(zz * suma + zv * sumb + sumc) + 
2860                   (lp->exp + lq->exp)*log(minlikelihood);
2861                 sum += *wptr++ * term;         
2862                 *log_f++ = term;
2863                 lp++;
2864                 lq++;
2865               }
2866           }
2867        }
2868
2869     
2870    tr->likelihood = sum;   
2871    return  sum;
2872  } /* evaluate */
2873
2874
2875long countEQ = 0, countNEQ = 0;
2876
2877double makenewz (tree *tr, nodeptr p, nodeptr q, double z0, int maxiter)
2878  { /* makenewz */
2879    likelivector *lp, *lq, *mlv[EQUALITIES][maxcategories];
2880    double   *abi, *bci, *sumci, *abptr, *bcptr, *sumcptr;
2881    double   dlnLidlz, dlnLdlz, d2lnLdlz2, z, zprev, zstep, lz, xvlz,
2882             ki, suma, sumb, sumc, ab, bc, inv_Li, t1, t2,
2883             fx1a, fx1c, fx1g, fx1t, fx1r, fx1y, fx2r, fx2y;
2884    double   zzp, zvp;
2885    double   *wrptr, w, *wr2ptr, *rptr;
2886    int      i, curvatOK, j , cat, *cptr;
2887    memP calcP[EQUALITIES][maxcategories], *calcptrP;
2888    memQ calcQ[EQUALITIES][maxcategories], *calcptrQ;
2889    homType *mlvP, *mlvQ; 
2890    register  char *sQ; 
2891    register  char *sP;
2892    nodeptr realQ, realP;
2893    long refQ, refP;
2894    double   zztable[maxcategories+1], zvtable[maxcategories+1],
2895            *zzptr, *zvptr;
2896
2897
2898    while ((! p->x) || (! q->x)) {
2899      if (! (p->x)) if (! newviewOptimized(tr, p)) return badZ;
2900      if (! (q->x)) if (! newviewOptimized(tr, q)) return badZ;
2901      }
2902
2903    realQ =  tr->nodep[q->number];
2904    realP =  tr->nodep[p->number];   
2905    sQ = realQ->equalityVector;
2906    sP = realP->equalityVector; 
2907    lp = p->x->lv;
2908    lq = q->x->lv;
2909
2910   
2911
2912    { 
2913      unsigned scratch_size;
2914      scratch_size = sizeof(double) * tr->cdta->endsite;
2915      if ((abi   = (double *) Malloc(scratch_size)) &&
2916          (bci   = (double *) Malloc(scratch_size)) &&
2917          (sumci = (double *) Malloc(scratch_size))) ;
2918      else {
2919        printf("ERROR: makenewz unable to obtain space for arrays\n");
2920        return badZ;
2921        }
2922     
2923      }
2924    abptr   = abi;
2925    bcptr   = bci;
2926    sumcptr = sumci;
2927
2928#   ifdef Vectorize
2929#     pragma IVDEP
2930#   endif
2931
2932
2933   
2934    for (j = 1; j <= tr->rdta->categs; j++) 
2935      { 
2936        for(i = 0; i < equalities; i++)
2937          {
2938            mlvP = &realP->mlv[i][j];
2939            if(mlvP->set)
2940              {
2941                calcptrP = &calcP[i][j];                 
2942                calcptrP->fx1a = tr->rdta->freqa * mlvP->a;
2943                calcptrP->fx1g = tr->rdta->freqg * mlvP->g;
2944                calcptrP->fx1c = tr->rdta->freqc * mlvP->c;
2945                calcptrP->fx1t = tr->rdta->freqt * mlvP->t;
2946                calcptrP->sumag = calcptrP->fx1a + calcptrP->fx1g;
2947                calcptrP->sumct = calcptrP->fx1c + calcptrP->fx1t;
2948                calcptrP->sumagct = calcptrP->sumag + calcptrP->sumct;       
2949              }
2950            mlvQ = &realQ->mlv[i][j]; 
2951            if(mlvQ->set)
2952              {
2953                calcptrQ = &calcQ[i][j];
2954                calcptrQ->fx2r = tr->rdta->freqa * mlvQ->a + tr->rdta->freqg * mlvQ->g;     
2955                calcptrQ->fx2y = tr->rdta->freqc * mlvQ->c + tr->rdta->freqt * mlvQ->t;             
2956                calcptrQ->sumfx2rfx2y =  calcptrQ->fx2r +  calcptrQ->fx2y;           
2957                calcptrQ->a = mlvQ->a;
2958                calcptrQ->c = mlvQ->c;
2959                calcptrQ->g = mlvQ->g;
2960                calcptrQ->t = mlvQ->t;       
2961              }     
2962          }
2963      }
2964    cptr    = &(tr->cdta->patcat[0]);
2965
2966    for (i = 0; i < tr->cdta->endsite; i++) {
2967      refQ = *sQ++;
2968      refP = *sP++;
2969
2970      cat = *cptr++;
2971     
2972      if(refP >= 0)
2973        {
2974          calcptrP = &calcP[refP][cat];
2975
2976          if(refQ >= 0)
2977            {
2978             
2979              calcptrQ = &calcQ[refQ][cat];
2980              suma = calcptrP->fx1a * calcptrQ->a + calcptrP->fx1c * calcptrQ->c + 
2981                calcptrP->fx1g * calcptrQ->g + calcptrP->fx1t * calcptrQ->t;
2982                     
2983             
2984              *sumcptr++ = sumc = calcptrP->sumagct * calcptrQ->sumfx2rfx2y;
2985              sumb       = calcptrP->sumag * calcptrQ->fx2r * tr->rdta->invfreqr + calcptrP->sumct * calcptrQ->fx2y * tr->rdta->invfreqy;
2986              *abptr++   = suma - sumb;
2987              *bcptr++   = sumb - sumc;
2988              lp++;
2989              lq++;     
2990            }
2991          else
2992            {       
2993              suma = calcptrP->fx1a * lq->a + calcptrP->fx1c * lq->c + 
2994                calcptrP->fx1g * lq->g + calcptrP->fx1t * lq->t;
2995             
2996              fx2r = tr->rdta->freqa * lq->a + tr->rdta->freqg * lq->g;
2997              fx2y = tr->rdta->freqc * lq->c + tr->rdta->freqt * lq->t;
2998             
2999              *sumcptr++ = sumc = calcptrP->sumagct * (fx2r + fx2y);
3000              sumb       = calcptrP->sumag * fx2r  * tr->rdta->invfreqr + calcptrP->sumct * fx2y * tr->rdta->invfreqy ;
3001              *abptr++   = suma - sumb;
3002              *bcptr++   = sumb - sumc;
3003              lp++;
3004              lq++;       
3005            }
3006        }
3007      else
3008        {
3009          if(refQ >= 0)
3010            {
3011              calcptrQ = &calcQ[refQ][cat];
3012              fx1a = tr->rdta->freqa * lp->a;
3013              fx1g = tr->rdta->freqg * lp->g;
3014              fx1c = tr->rdta->freqc * lp->c;
3015              fx1t = tr->rdta->freqt * lp->t;
3016              suma = fx1a * calcptrQ->a + fx1c * calcptrQ->c + 
3017                fx1g * calcptrQ->g + fx1t * calcptrQ->t;         
3018              fx1r = fx1a + fx1g;
3019              fx1y = fx1c + fx1t;
3020              *sumcptr++ = sumc = (fx1r + fx1y) * calcptrQ->sumfx2rfx2y; 
3021              sumb       = fx1r * calcptrQ->fx2r  * tr->rdta->invfreqr + fx1y * calcptrQ->fx2y * tr->rdta->invfreqy;
3022              *abptr++   = suma - sumb;
3023              *bcptr++   = sumb - sumc;
3024              lp++;
3025              lq++;
3026            }
3027          else
3028            {
3029
3030              fx1a = tr->rdta->freqa * lp->a;
3031              fx1g = tr->rdta->freqg * lp->g;
3032              fx1c = tr->rdta->freqc * lp->c;
3033              fx1t = tr->rdta->freqt * lp->t;
3034              suma = fx1a * lq->a + fx1c * lq->c + fx1g * lq->g + fx1t * lq->t;
3035              fx2r = tr->rdta->freqa * lq->a + tr->rdta->freqg * lq->g;
3036              //nur von q abh
3037              fx2y = tr->rdta->freqc * lq->c + tr->rdta->freqt * lq->t; 
3038              //nur von q abh
3039              fx1r = fx1a + fx1g;
3040              fx1y = fx1c + fx1t;
3041              *sumcptr++ = sumc = (fx1r + fx1y) * (fx2r + fx2y); 
3042              //zweiter term nur von q abh
3043              sumb       = fx1r * fx2r * tr->rdta->invfreqr + fx1y * fx2y * tr->rdta->invfreqy;
3044
3045
3046   
3047              *abptr++   = suma - sumb;
3048              *bcptr++   = sumb - sumc;
3049              lp++;
3050              lq++;
3051            }
3052        }
3053
3054      }
3055
3056    z = z0;
3057    do {
3058      zprev = z;
3059      zstep = (1.0 - zmax) * z + zmin;
3060      curvatOK = FALSE;
3061
3062      do {
3063        if (z < zmin) z = zmin;
3064        else if (z > zmax) z = zmax;
3065
3066        lz    = log(z);
3067        xvlz  = tr->rdta->xv * lz;
3068        rptr  = &(tr->rdta->catrat[1]);
3069        zzptr = &(zztable[1]);
3070        zvptr = &(zvtable[1]);
3071
3072#       ifdef Vectorize
3073#         pragma IVDEP
3074#       endif
3075
3076        for (i = 1; i <= tr->rdta->categs; i++) {
3077          ki = *rptr++;
3078          *zzptr++ = exp(ki *   lz);
3079          *zvptr++ = exp(ki * xvlz);
3080          }
3081
3082        abptr   = abi;
3083        bcptr   = bci;
3084        sumcptr = sumci;
3085        cptr    = &(tr->cdta->patcat[0]);
3086        wrptr   = &(tr->cdta->wr[0]);
3087        wr2ptr  = &(tr->cdta->wr2[0]);
3088        dlnLdlz = 0.0;                 /*  = d(ln(likelihood))/d(lz) */
3089        d2lnLdlz2 = 0.0;               /*  = d2(ln(likelihood))/d(lz)2 */
3090
3091#       ifdef Vectorize
3092#         pragma IVDEP
3093#       endif
3094
3095        for (i = 0; i < tr->cdta->endsite; i++) {
3096          cat    = *cptr++;              /*  ratecategory(i) */
3097          ab     = *abptr++ * zztable[cat];
3098          bc     = *bcptr++ * zvtable[cat];
3099          sumc   = *sumcptr++;
3100          inv_Li = 1.0/(ab + bc + sumc);
3101          t1     = ab * inv_Li;
3102          t2     = tr->rdta->xv * bc * inv_Li;
3103          dlnLidlz   = t1 + t2;
3104          dlnLdlz   += *wrptr++  * dlnLidlz;
3105          d2lnLdlz2 += *wr2ptr++ * (t1 + tr->rdta->xv * t2 - dlnLidlz * dlnLidlz);
3106          }
3107
3108        if ((d2lnLdlz2 >= 0.0) && (z < zmax))
3109          zprev = z = 0.37 * z + 0.63;  /*  Bad curvature, shorten branch */
3110        else
3111          curvatOK = TRUE;
3112
3113        } while (! curvatOK);
3114
3115      if (d2lnLdlz2 < 0.0) {
3116        z *= exp(-dlnLdlz / d2lnLdlz2);
3117        if (z < zmin) z = zmin;
3118        if (z > 0.25 * zprev + 0.75)    /*  Limit steps toward z = 1.0 */
3119          z = 0.25 * zprev + 0.75;
3120        }
3121
3122      if (z > zmax) z = zmax;
3123
3124      } while ((--maxiter > 0) && (ABS(z - zprev) > zstep));
3125
3126   
3127    Free(abi);
3128    Free(bci);
3129    Free(sumci);
3130
3131   
3132 
3133    return  z;
3134  } /* makenewz */
3135
3136
3137boolean update (tree *tr, nodeptr p)
3138  { /* update */
3139    nodeptr  q;
3140    double   z0, z;
3141
3142    q = p->back;
3143    z0 = q->z;
3144    if ((z = makenewz(tr, p, q, z0, newzpercycle)) == badZ) return FALSE;
3145    p->z = q->z = z;
3146    if (ABS(z - z0) > deltaz)  tr->smoothed = FALSE;
3147    return TRUE;
3148  } /* update */
3149
3150
3151boolean smooth (tree *tr, nodeptr p)
3152  { /* smooth */
3153    nodeptr  q;
3154
3155    if (! update(tr, p))               return FALSE; /*  Adjust branch */
3156    if (! p->tip) {                                  /*  Adjust descendants */
3157        q = p->next;
3158        while (q != p) {
3159          if (! smooth(tr, q->back))   return FALSE;
3160          q = q->next;
3161          }
3162
3163#     if ReturnSmoothedView
3164
3165        if (! newviewOptimized(tr, p)) return FALSE;
3166#     endif
3167      }
3168
3169    return TRUE;
3170  } /* smooth */
3171
3172
3173boolean smoothTree (tree *tr, int maxtimes)
3174  { /* smoothTree */
3175    nodeptr  p, q;
3176
3177    p = tr->start;
3178
3179    while (--maxtimes >= 0) {
3180      tr->smoothed = TRUE;
3181      if (! smooth(tr, p->back))       return FALSE;
3182      if (! p->tip) {
3183        q = p->next;
3184        while (q != p) {
3185          if (! smooth(tr, q->back))   return FALSE;
3186          q = q->next;
3187          }
3188        }
3189      if (tr->smoothed)  break;
3190      }
3191
3192    return TRUE;
3193  } /* smoothTree */
3194
3195
3196boolean localSmooth (tree *tr, nodeptr p, int maxtimes)
3197  { /* localSmooth -- Smooth branches around p */
3198    nodeptr  q;
3199
3200    if (p->tip) return FALSE;            /* Should be an error */
3201
3202    while (--maxtimes >= 0) {
3203      tr->smoothed = TRUE;
3204      q = p;
3205      do {
3206        if (! update(tr, q)) return FALSE;
3207        q = q->next;
3208        } while (q != p);
3209      if (tr->smoothed)  break;
3210      }
3211
3212    tr->smoothed = FALSE;             /* Only smooth locally */
3213    return TRUE;
3214  } /* localSmooth */
3215
3216
3217void hookup (nodeptr p, nodeptr q, double z)
3218  { /* hookup */
3219    p->back = q;
3220    q->back = p;
3221    p->z = q->z = z;
3222  } /* hookup */
3223
3224
3225/* Insert node p into branch q <-> q->back */
3226
3227
3228boolean insert (tree *tr, nodeptr p, nodeptr q, boolean glob)
3229/* glob -- Smooth tree globally? */
3230
3231/*                q
3232                 /.
3233             add/ .
3234               /  .
3235             pn   .
3236    s ---- p      .remove
3237             pnn  .
3238               \  .
3239             add\ .
3240                 \.      pn  = p->next;
3241                  r      pnn = p->next->next;
3242 */
3243
3244  { /* insert */
3245    nodeptr  r, s;
3246
3247    r = q->back;
3248    s = p->back;
3249
3250#   if BestInsertAverage && ! Master
3251    { double  zqr, zqs, zrs, lzqr, lzqs, lzrs, lzsum, lzq, lzr, lzs, lzmax;
3252
3253      if ((zqr = makenewz(tr, q, r, q->z,     iterations)) == badZ) return FALSE;
3254      if ((zqs = makenewz(tr, q, s, defaultz, iterations)) == badZ) return FALSE;
3255      if ((zrs = makenewz(tr, r, s, defaultz, iterations)) == badZ) return FALSE;
3256
3257     
3258 
3259
3260      lzqr = (zqr > zmin) ? log(zqr) : log(zmin);  /* long branches */
3261      lzqs = (zqs > zmin) ? log(zqs) : log(zmin);
3262      lzrs = (zrs > zmin) ? log(zrs) : log(zmin);
3263      lzsum = 0.5 * (lzqr + lzqs + lzrs);
3264
3265      lzq = lzsum - lzrs;
3266      lzr = lzsum - lzqs;
3267      lzs = lzsum - lzqr;
3268      lzmax = log(zmax);
3269
3270      if      (lzq > lzmax) {lzq = lzmax; lzr = lzqr; lzs = lzqs;} /* short */
3271      else if (lzr > lzmax) {lzr = lzmax; lzq = lzqr; lzs = lzrs;}
3272      else if (lzs > lzmax) {lzs = lzmax; lzq = lzqs; lzr = lzrs;}
3273
3274      hookup(p->next,       q, exp(lzq));
3275      hookup(p->next->next, r, exp(lzr));
3276      hookup(p,             s, exp(lzs));
3277      }
3278
3279#   else
3280    { double  z;
3281      z = sqrt(q->z);
3282      hookup(p->next,       q, z);
3283      hookup(p->next->next, r, z);
3284      }
3285
3286#   endif
3287
3288
3289    if (! newviewOptimized(tr, p)) return FALSE;
3290   
3291   
3292
3293    tr->opt_level = 0;
3294
3295#   if ! Master         /*  Smoothings are done by slave */
3296      if (glob) {                                    /* Smooth whole tree */
3297        if (! smoothTree(tr, smoothings)) return FALSE;
3298        }
3299      else {                                         /* Smooth locale of p */
3300        if (! localSmooth(tr, p, smoothings)) return FALSE;
3301        }
3302
3303#   else
3304      tr->likelihood = unlikely;
3305#   endif
3306     
3307    return  TRUE;
3308  } /* insert */
3309
3310
3311nodeptr  removeNode (tree *tr, nodeptr p)
3312
3313/*                q
3314                 .|
3315          remove. |
3316               .  |
3317             pn   |
3318    s ---- p      |add
3319             pnn  |
3320               .  |
3321          remove. |
3322                 .|      pn  = p->next;
3323                  r      pnn = p->next->next;
3324 */
3325
3326    /* remove p and return where it was */
3327  { /* removeNode */
3328    double   zqr;
3329    nodeptr  q, r;
3330
3331    q = p->next->back;
3332    r = p->next->next->back;
3333    zqr = q->z * r->z;
3334#   if ! Master
3335      if ((zqr = makenewz(tr, q, r, zqr, iterations)) == badZ) return (node *) NULL;
3336#   endif
3337    hookup(q, r, zqr);
3338
3339    p->next->next->back = p->next->back = (node *) NULL;
3340    return  q;
3341  } /* removeNode */
3342
3343
3344boolean initrav (tree *tr, nodeptr p)
3345  { /* initrav */
3346    nodeptr  q;
3347
3348    if (! p->tip) {
3349      q = p->next;
3350      do {
3351        if (! initrav(tr, q->back))  return FALSE;
3352        q = q->next;
3353        } while (q != p);
3354
3355      if (! newviewOptimized(tr, p)) return FALSE;
3356
3357      }
3358
3359    return TRUE;
3360  } /* initrav */
3361
3362
3363nodeptr buildNewTip (tree *tr, nodeptr p)
3364  { /* buildNewTip */
3365    nodeptr  q;
3366
3367    q = tr->nodep[(tr->nextnode)++];
3368    hookup(p, q, defaultz);
3369    return  q;
3370  } /* buildNewTip */
3371
3372
3373boolean buildSimpleTree (tree *tr, int ip, int iq, int ir)
3374  { /* buildSimpleTree */
3375    /* p, q and r are tips meeting at s */
3376    nodeptr  p, s;
3377    int  i;
3378
3379    i = MIN(ip, iq);
3380    if (ir < i)  i = ir; 
3381    tr->start = tr->nodep[i];
3382    tr->ntips = 3;
3383    p = tr->nodep[ip];
3384    hookup(p, tr->nodep[iq], defaultz);
3385    s = buildNewTip(tr, tr->nodep[ir]);
3386
3387    return insert(tr, s, p, FALSE);  /* Smoothing is local to s */
3388  } /* buildSimpleTree */
3389
3390#if 0
3391char * strchr (char *str, int chr)
3392 { /* strchr */
3393    int  c;
3394
3395    while (c = *str)  {if (c == chr) return str; str++;}
3396    return  (char *) NULL;
3397 } /* strchr */
3398
3399
3400char * strstr (char *str1, char *str2)
3401 { /* strstr */
3402    char *s1, *s2;
3403    int  c;
3404
3405    while (*(s1 = str1)) {
3406      s2 = str2;
3407      do {
3408        if (! (c = *s2++))  return str1;
3409        }
3410        while (*s1++ == c);
3411      str1++;
3412      }
3413    return  (char *) NULL;
3414 } /* strstr */
3415#endif
3416
3417boolean readKeyValue (char *string, char *key, char *format, void *value)
3418  { /* readKeyValue */
3419
3420    if (! (string = strstr(string, key)))  return FALSE;
3421    string += strlen(key);
3422    if (! (string = strchr(string, '=')))  return FALSE;
3423    string++;
3424    return  sscanf(string, format, value);  /* 1 if read, otherwise 0 */
3425  } /* readKeyValue */
3426
3427
3428#if Master || Slave
3429
3430double str_readTreeLikelihood (char *treestr)
3431  { /* str_readTreeLikelihood */
3432    double lk1;
3433    char    *com, *com_end;
3434    boolean  readKeyValue();
3435
3436    if ((com = strchr(treestr, '[')) && (com < strchr(treestr, '('))
3437                                     && (com_end = strchr(com, ']'))) {
3438      com++;
3439      *com_end = 0;
3440      if (readKeyValue(com, likelihood_key, "%lg", (void *) &(lk1))) {
3441        *com_end = ']';
3442        return lk1;
3443        }
3444      }
3445
3446    fprintf(stderr, "ERROR reading likelihood in receiveTree\n");
3447    return  badEval;
3448  } /* str_readTreeLikelihood */
3449
3450
3451boolean sendTree (comm_block *comm, tree *tr)
3452  { /* sendTree */
3453    char  *treestr;
3454    char  *treeString();
3455#   if Master
3456      void sendTreeNum();
3457#   endif
3458
3459    comm->done_flag = tr->likelihood > 0.0;
3460    if (comm->done_flag)
3461      write_comm_msg(comm, NULL);
3462
3463    else {
3464      treestr = (char *) Malloc((tr->ntips * (nmlngth+32)) + 256);
3465      if (! treestr) {
3466        fprintf(stderr, "sendTree: Malloc failure\n");
3467        return 0;
3468        }
3469
3470#     if Master
3471        if (send_ahead >= MAX_SEND_AHEAD) {
3472          double new_likelihood;
3473          int  n_to_get;
3474
3475          n_to_get = (send_ahead+1)/2;
3476          sendTreeNum(n_to_get);
3477          send_ahead -= n_to_get;
3478          read_comm_msg(& comm_slave, treestr);
3479          new_likelihood = str_readTreeLikelihood(treestr);
3480          if (new_likelihood == badEval)  return FALSE;
3481          if (! best_tr_recv || (new_likelihood > best_lk_recv)) {
3482            if (best_tr_recv)  Free(best_tr_recv);
3483            best_tr_recv = Malloc(strlen(treestr) + 1);
3484            strcpy(best_tr_recv, treestr);
3485            best_lk_recv = new_likelihood;
3486            }
3487          }
3488        send_ahead++;
3489#     endif           /*  End #if Master  */
3490
3491      REPORT_SEND_TREE;
3492      (void) treeString(treestr, tr, tr->start->back, 1);
3493      write_comm_msg(comm, treestr);
3494
3495      Free(treestr);
3496      }
3497
3498    return TRUE;
3499  } /* sendTree */
3500
3501
3502boolean  receiveTree (comm_block *comm, tree *tr)
3503  { /* receiveTree */
3504    char   *treestr;
3505    boolean status;
3506    boolean str_treeReadLen();
3507
3508    treestr = (char *) Malloc((tr->ntips * (nmlngth+32)) + 256);
3509    if (! treestr) {
3510      fprintf(stderr, "receiveTree: Malloc failure\n");
3511      return 0;
3512      }
3513
3514    read_comm_msg(comm, treestr);
3515    if (comm->done_flag) {
3516      tr->likelihood = 1.0;
3517      status = TRUE;
3518      }
3519
3520    else {
3521#     if Master
3522        if (best_tr_recv) {
3523          if (str_readTreeLikelihood(treestr) < best_lk_recv) {
3524            strcpy(treestr, best_tr_recv);  /* Overwrite new tree with best */
3525            }
3526          Free(best_tr_recv);
3527          best_tr_recv = NULL;
3528          }
3529#     endif           /*  End #if Master  */
3530
3531      status = str_treeReadLen(treestr, tr);
3532      }
3533
3534    Free(treestr);
3535    return status;
3536  } /* receiveTree */
3537
3538
3539void requestForWork (void)
3540  { /* requestForWork */
3541    p4_send(DNAML_REQUEST, DNAML_DISPATCHER_ID, NULL, 0);
3542  } /* requestForWork */
3543#endif                  /* End #if Master || Slave  */
3544
3545
3546#if Master
3547void sendTreeNum(int n_to_get)
3548  { /* sendTreeNum */
3549    char scr[512];
3550
3551    sprintf(scr, "%d", n_to_get);
3552    p4_send(DNAML_NUM_TREE, DNAML_MERGER_ID, scr, strlen(scr)+1);
3553  } /* sendTreeNum */
3554
3555
3556boolean  getReturnedTrees (tree *tr, bestlist *bt, int n_tree_sent)
3557 /* n_tree_sent -- number of trees sent to slaves */
3558  { /* getReturnedTrees */
3559    void sendTreeNum();
3560    boolean receiveTree();
3561
3562    sendTreeNum(send_ahead);
3563    send_ahead = 0;
3564
3565    if (! receiveTree(& comm_slave, tr))  return FALSE;
3566    tr->smoothed = TRUE;
3567    (void) saveBestTree(bt, tr);
3568
3569    return TRUE;
3570  } /* getReturnedTrees */
3571#endif
3572
3573
3574void cacheZ (tree *tr)
3575  { /* cacheZ */
3576    nodeptr  p;
3577    int  nodes;
3578
3579    nodes = tr->mxtips  +  3 * (tr->mxtips - 2);
3580    p = tr->nodep[1];
3581    while (nodes-- > 0) {p->z0 = p->z; p++;}
3582  } /* cacheZ */
3583
3584
3585void restoreZ (tree *tr)
3586  { /* restoreZ */
3587    nodeptr  p;
3588    int  nodes;
3589
3590    nodes = tr->mxtips  +  3 * (tr->mxtips - 2);
3591    p = tr->nodep[1];
3592    while (nodes-- > 0) {p->z = p->z0; p++;}
3593  } /* restoreZ */
3594
3595
3596boolean testInsert (tree *tr, nodeptr p, nodeptr q, bestlist *bt, boolean  fast)
3597  { /* testInsert */
3598    double  qz;
3599    nodeptr  r;
3600
3601    r = q->back;             /* Save original connection */
3602    qz = q->z;
3603    if (! insert(tr, p, q, ! fast)) return FALSE;
3604
3605#   if ! Master
3606      if (evaluate(tr, fast ? p->next->next : tr->start) == badEval) return FALSE;
3607      (void) saveBestTree(bt, tr);
3608#   else  /* Master */
3609      tr->likelihood = unlikely;
3610      if (! sendTree(& comm_slave, tr))  return FALSE;
3611#   endif
3612
3613    /* remove p from this branch */
3614
3615    hookup(q, r, qz);
3616    p->next->next->back = p->next->back = (nodeptr) NULL;
3617    if (! fast) {            /* With fast add, other values are still OK */
3618      restoreZ(tr);          /*   Restore branch lengths */
3619#     if ! Master            /*   Regenerate x values */
3620        if (! initrav(tr, p->back))  return FALSE;
3621        if (! initrav(tr, q))        return FALSE;
3622        if (! initrav(tr, r))        return FALSE;
3623#     endif
3624      }
3625
3626    return TRUE;
3627  } /* testInsert */
3628
3629
3630int addTraverse (tree *tr, nodeptr p, nodeptr q,
3631                 int mintrav, int maxtrav, bestlist *bt, boolean fast)
3632  { /* addTraverse */
3633    int  tested, newtested;
3634
3635    tested = 0;
3636    if (--mintrav <= 0) {           /* Moved minimum distance? */
3637      if (! testInsert(tr, p, q, bt, fast))  return badRear;
3638      tested++;
3639      }
3640
3641    if ((! q->tip) && (--maxtrav > 0)) {    /* Continue traverse? */
3642      newtested = addTraverse(tr, p, q->next->back,
3643                              mintrav, maxtrav, bt, fast);
3644      if (newtested == badRear) return badRear;
3645      tested += newtested;
3646      newtested = addTraverse(tr, p, q->next->next->back,
3647                              mintrav, maxtrav, bt, fast);
3648      if (newtested == badRear) return badRear;
3649      tested += newtested;
3650      }
3651
3652    return tested;
3653  } /* addTraverse */
3654
3655
3656int  rearrange (tree *tr, nodeptr p, int mintrav, int maxtrav, bestlist *bt)
3657    /* rearranges the tree, globally or locally */
3658  { /* rearrange */
3659    double   p1z, p2z, q1z, q2z;
3660    nodeptr  p1, p2, q, q1, q2;
3661    int      tested, mintrav2, newtested;
3662
3663    tested = 0;
3664    if (maxtrav < 1 || mintrav > maxtrav)  return tested;
3665
3666/* Moving subtree forward in tree. */
3667
3668    if (! p->tip) {
3669      p1 = p->next->back;
3670      p2 = p->next->next->back;
3671      if (! p1->tip || ! p2->tip) {
3672        p1z = p1->z;
3673        p2z = p2->z;
3674        if (! removeNode(tr, p)) return badRear;
3675        cacheZ(tr);
3676        if (! p1->tip) {
3677          newtested = addTraverse(tr, p, p1->next->back,
3678                                  mintrav, maxtrav, bt, FALSE);
3679          if (newtested == badRear) return badRear;
3680          tested += newtested;
3681          newtested = addTraverse(tr, p, p1->next->next->back,
3682                                  mintrav, maxtrav, bt, FALSE);
3683          if (newtested == badRear) return badRear;
3684          tested += newtested;
3685          }
3686
3687        if (! p2->tip) {
3688          newtested = addTraverse(tr, p, p2->next->back,
3689                                  mintrav, maxtrav, bt, FALSE);
3690          if (newtested == badRear) return badRear;
3691          tested += newtested;
3692          newtested = addTraverse(tr, p, p2->next->next->back,
3693                                  mintrav, maxtrav, bt, FALSE);
3694          if (newtested == badRear) return badRear;
3695          tested += newtested;
3696          }
3697
3698        hookup(p->next,       p1, p1z);  /*  Restore original tree */
3699        hookup(p->next->next, p2, p2z);
3700        if (! (initrav(tr, tr->start)
3701            && initrav(tr, tr->start->back))) return badRear;
3702        }
3703      }   /* if (! p->tip) */
3704
3705/* Moving subtree backward in tree.  Minimum move is 2 to avoid duplicates */
3706
3707    q = p->back;
3708    if (! q->tip && maxtrav > 1) {
3709      q1 = q->next->back;
3710      q2 = q->next->next->back;
3711      if (! q1->tip && (!q1->next->back->tip || !q1->next->next->back->tip) ||
3712          ! q2->tip && (!q2->next->back->tip || !q2->next->next->back->tip)) {
3713        q1z = q1->z;
3714        q2z = q2->z;
3715        if (! removeNode(tr, q)) return badRear;
3716        cacheZ(tr);
3717        mintrav2 = mintrav > 2 ? mintrav : 2;
3718
3719        if (! q1->tip) {
3720          newtested = addTraverse(tr, q, q1->next->back,
3721                                  mintrav2 , maxtrav, bt, FALSE);
3722          if (newtested == badRear) return badRear;
3723          tested += newtested;
3724          newtested = addTraverse(tr, q, q1->next->next->back,
3725                                  mintrav2 , maxtrav, bt, FALSE);
3726          if (newtested == badRear) return badRear;
3727          tested += newtested;
3728          }
3729
3730        if (! q2->tip) {
3731          newtested = addTraverse(tr, q, q2->next->back,
3732                                  mintrav2 , maxtrav, bt, FALSE);
3733          if (newtested == badRear) return badRear;
3734          tested += newtested;
3735          newtested = addTraverse(tr, q, q2->next->next->back,
3736                                  mintrav2 , maxtrav, bt, FALSE);
3737          if (newtested == badRear) return badRear;
3738          tested += newtested;
3739          }
3740
3741        hookup(q->next,       q1, q1z);  /*  Restore original tree */
3742        hookup(q->next->next, q2, q2z);
3743        if (! (initrav(tr, tr->start)
3744            && initrav(tr, tr->start->back))) return badRear;
3745        }
3746      }   /* if (! q->tip && maxtrav > 1) */
3747
3748/* Move other subtrees */
3749
3750    if (! p->tip) {
3751      newtested = rearrange(tr, p->next->back,       mintrav, maxtrav, bt);
3752      if (newtested == badRear) return badRear;
3753      tested += newtested;
3754      newtested = rearrange(tr, p->next->next->back, mintrav, maxtrav, bt);
3755      if (newtested == badRear) return badRear;
3756      tested += newtested;
3757      }
3758
3759    return  tested;
3760  } /* rearrange */
3761
3762
3763FILE *fopen_pid (char *filenm, char *mode, char *name_pid)
3764  { /* fopen_pid */
3765
3766    (void) sprintf(name_pid, "%s.%d", filenm, getpid());
3767    return  fopen(name_pid, mode);
3768  } /* fopen_pid */
3769
3770
3771#if DeleteCheckpointFile
3772void  unlink_pid (char *filenm)
3773  { /* unlink_pid */
3774    char scr[512];
3775
3776    (void) sprintf(scr, "%s.%d", filenm, getpid());
3777    unlink(scr);
3778  } /* unlink_pid */
3779#endif
3780
3781
3782void  writeCheckpoint (tree *tr)
3783  { /* writeCheckpoint */
3784    char   filename[128];
3785    FILE  *checkpointf;
3786    void   treeOut();
3787
3788    checkpointf = fopen_pid(checkpointname, "a", filename);
3789    if (checkpointf) {
3790      treeOut(checkpointf, tr, treeNewick);
3791      (void) fclose(checkpointf);
3792      }
3793  } /* writeCheckpoint */
3794
3795
3796node * findAnyTip(nodeptr p)
3797  { /* findAnyTip */
3798    return  p->tip ? p : findAnyTip(p->next->back);
3799  } /* findAnyTip */
3800
3801
3802boolean  optimize (tree *tr, int maxtrav, bestlist *bt)
3803  { /* optimize */
3804    nodeptr  p;
3805    int    mintrav, tested;
3806
3807    if (tr->ntips < 4)  return  TRUE;
3808
3809    writeCheckpoint(tr);                    /* checkpoint the starting tree */
3810
3811    if (maxtrav > tr->ntips - 3)  maxtrav = tr->ntips - 3;
3812    if (maxtrav <= tr->opt_level)  return  TRUE;
3813
3814    printf("      Doing %s rearrangements\n",
3815             (maxtrav == 1)            ? "local" :
3816             (maxtrav < tr->ntips - 3) ? "regional" : "global");
3817
3818    /* loop while tree gets better  */
3819
3820    do {
3821      (void) startOpt(bt, tr);
3822      mintrav = tr->opt_level + 1;
3823
3824      /* rearrange must start from a tip or it will miss some trees */
3825
3826      p = findAnyTip(tr->start);
3827      tested = rearrange(tr, p->back, mintrav, maxtrav, bt);
3828      if (tested == badRear)  return FALSE;
3829
3830#     if Master
3831        if (! getReturnedTrees(tr, bt, tested)) return FALSE;
3832#     endif
3833
3834      bt->numtrees += tested;
3835      (void) setOptLevel(bt, maxtrav);
3836      if (! recallBestTree(bt, 1, tr)) return FALSE;   /* recover best tree */
3837
3838      printf("      Tested %d alternative trees\n", tested);
3839     
3840      if (bt->improved) {
3841        printf("      Ln Likelihood =%14.5f\n", tr->likelihood);
3842        }
3843     
3844      writeCheckpoint(tr);                  /* checkpoint the new tree */
3845      } while (maxtrav > tr->opt_level);
3846
3847    return TRUE;
3848  } /* optimize */
3849
3850
3851void coordinates (tree *tr, nodeptr p, double lengthsum, drawdata *tdptr)
3852  { /* coordinates */
3853    /* establishes coordinates of nodes */
3854    double  x, z;
3855    nodeptr  q, first, last;
3856
3857    if (p->tip) {
3858      p->xcoord = NINT(over * lengthsum);
3859      p->ymax = p->ymin = p->ycoord = tdptr->tipy;
3860      tdptr->tipy += down;
3861      if (lengthsum > tdptr->tipmax) tdptr->tipmax = lengthsum;
3862      }
3863
3864    else {
3865      q = p->next;
3866      do {
3867        z = q->z;
3868        if (z < zmin) z = zmin;
3869        x = lengthsum - tr->rdta->fracchange * log(z);
3870        coordinates(tr, q->back, x, tdptr);
3871        q = q->next;
3872        } while (p == tr->start->back ? q != p->next : q != p);
3873
3874      first = p->next->back;
3875      q = p;
3876      while (q->next != p) q = q->next;
3877      last = q->back;
3878      p->xcoord = NINT(over * lengthsum);
3879      p->ycoord = (first->ycoord + last->ycoord)/2;
3880      p->ymin = first->ymin;
3881      p->ymax = last->ymax;
3882      }
3883  } /* coordinates */
3884
3885
3886void drawline (tree *tr, int i, double scale)
3887    /* draws one row of the tree diagram by moving up tree */
3888    /* Modified to handle 1000 taxa, October 16, 1991 */
3889  { /* drawline */
3890    nodeptr  p, q, r, first, last;
3891    int  n, j, k, l, extra;
3892    boolean  done;
3893
3894    p = q = tr->start->back;
3895    extra = 0;
3896
3897    if (i == p->ycoord) {
3898      k = q->number - tr->mxtips;
3899      for (j = k; j < 1000; j *= 10) putchar('-');
3900      printf("%d", k);
3901      extra = 1;
3902      }
3903    else printf("   ");
3904
3905    do {
3906      if (! p->tip) {
3907        r = p->next;
3908        done = FALSE;
3909        do {
3910          if ((i >= r->back->ymin) && (i <= r->back->ymax)) {
3911            q = r->back;
3912            done = TRUE;
3913            }
3914          r = r->next;
3915          } while (! done && (p == tr->start->back ? r != p->next : r != p));
3916
3917        first = p->next->back;
3918        r = p;
3919        while (r->next != p) r = r->next;
3920        last = r->back;
3921        if (p == tr->start->back) last = p->back;
3922        }
3923
3924      done = (p->tip) || (p == q);
3925      n = NINT(scale*(q->xcoord - p->xcoord));
3926      if ((n < 3) && (! q->tip)) n = 3;
3927      n -= extra;
3928      extra = 0;
3929
3930      if ((q->ycoord == i) && (! done)) {
3931        if (p->ycoord != q->ycoord) putchar('+');
3932        else                        putchar('-');
3933
3934        if (! q->tip) {
3935          k = q->number - tr->mxtips;
3936          l = n - 3;
3937          for (j = k; j < 100; j *= 10)  l++;
3938          for (j = 1; j <= l; j++) putchar('-');
3939          printf("%d", k);
3940          extra = 1;
3941          }
3942        else for (j = 1; j <= n-1; j++) putchar('-');
3943        }
3944
3945      else if (! p->tip) {
3946        if ((last->ycoord > i) && (first->ycoord < i) && (i != p->ycoord)) {
3947          putchar('!');
3948          for (j = 1; j <= n-1; j++) putchar(' ');
3949          }
3950        else for (j = 1; j <= n; j++) putchar(' ');
3951        }
3952
3953      else
3954        for (j = 1; j <= n; j++) putchar(' ');
3955
3956      p = q;
3957      } while (! done);
3958
3959    if ((p->ycoord == i) && p->tip) {
3960      printf(" %s", p->name);
3961      }
3962
3963    putchar('\n');
3964  } /* drawline */
3965
3966
3967void printTree (tree *tr, analdef *adef)
3968    /* prints out diagram of the tree */
3969  { /* printTree */
3970    drawdata  tipdata;
3971    double  scale;
3972    int  i, imax;
3973
3974    if (adef->trprint) {
3975      putchar('\n');
3976      tipdata.tipy = 1;
3977      tipdata.tipmax = 0.0;
3978      coordinates(tr, tr->start->back, (double) 0.0, & tipdata);
3979      scale = 1.0 / tipdata.tipmax;
3980      imax = tipdata.tipy - down;
3981      for (i = 1; i <= imax; i++)  drawline(tr, i, scale);
3982      printf("\nRemember: ");
3983      if (adef->root) printf("(although rooted by outgroup) ");
3984      printf("this is an unrooted tree!\n\n");
3985      }
3986  } /* printTree */
3987
3988
3989double sigma (tree *tr, nodeptr p, double *sumlrptr)
3990    /* compute standard deviation */
3991  { /* sigma */
3992    likelivector *lp, *lq;
3993    homType *mlvP, *mlvQ;
3994    double  slope, sum, sumlr, z, zv, zz, lz,
3995            rat, suma, sumb, sumc, d2, d, li, temp, abzz, bczv, t3,
3996            fx1a, fx1c, fx1g, fx1t, fx1r, fx1y, fx2r, fx2y, w;
3997    double  *rptr;
3998    nodeptr  q, realQ, realP;
3999    int  i, *wptr, j, cat, *cptr;
4000    register  char *sQ; 
4001    register  char *sP;
4002    long refQ, refP;
4003    memP calcP[EQUALITIES][maxcategories], *calcptrP;
4004    memQ calcQ[EQUALITIES][maxcategories], *calcptrQ;
4005   
4006    q = p->back;
4007    while ((! p->x) || (! q->x)) {
4008      /*stamatak*/
4009
4010      if (! (p->x)) if (! newviewOptimized(tr, p)) return -1.0;
4011      if (! (q->x)) if (! newviewOptimized(tr, q)) return -1.0;
4012      }
4013
4014    lp = p->x->lv;
4015    lq = q->x->lv;
4016
4017    z = p->z;
4018    if (z < zmin) z = zmin;
4019    lz = log(z);
4020    cptr    = &(tr->cdta->patcat[0]);
4021    wptr = &(tr->cdta->aliaswgt[0]);
4022    rptr = &(tr->cdta->patrat[0]);
4023    sum = sumlr = slope = 0.0;
4024
4025#   ifdef Vectorize
4026#     pragma IVDEP
4027#   endif
4028
4029    realQ =  tr->nodep[q->number];
4030    realP =  tr->nodep[p->number];
4031    sQ = realQ->equalityVector;
4032    sP = realP->equalityVector; 
4033
4034     for (j = 1; j <= tr->rdta->categs; j++) 
4035       { 
4036
4037         for(i = 0; i < equalities; i++)
4038           {
4039             mlvP = &realP->mlv[i][j];
4040             if(mlvP->set)
4041               {
4042                 calcptrP = &calcP[i][j];               
4043                 calcptrP->fx1a = tr->rdta->freqa * mlvP->a;
4044                 calcptrP->fx1g = tr->rdta->freqg * mlvP->g;
4045                 calcptrP->fx1c = tr->rdta->freqc * mlvP->c;
4046                 calcptrP->fx1t = tr->rdta->freqt * mlvP->t;
4047                 calcptrP->sumag = calcptrP->fx1a + calcptrP->fx1g;
4048                 calcptrP->sumct = calcptrP->fx1c + calcptrP->fx1t;
4049                 calcptrP->sumagct = calcptrP->sumag + calcptrP->sumct;       
4050                 calcptrP->exp = mlvP->exp;
4051               }
4052             mlvQ = &realQ->mlv[i][j]; 
4053             if(mlvQ->set)
4054               {
4055                 calcptrQ = &calcQ[i][j];
4056                 calcptrQ->fx2r = tr->rdta->freqa * mlvQ->a + tr->rdta->freqg * mlvQ->g;             
4057                 calcptrQ->fx2y  = tr->rdta->freqc * mlvQ->c + tr->rdta->freqt * mlvQ->t;           
4058                 calcptrQ->sumfx2rfx2y = calcptrQ->fx2r + calcptrQ->fx2y;           
4059                 calcptrQ->exp = mlvQ->exp;
4060                 calcptrQ->a = mlvQ->a;
4061                 calcptrQ->c = mlvQ->c;
4062                 calcptrQ->g = mlvQ->g;
4063                 calcptrQ->t = mlvQ->t;
4064               }             
4065           }
4066       }
4067   
4068
4069   
4070   
4071
4072    for (i = 0; i < tr->cdta->endsite; i++) {
4073      rat  = *rptr++;
4074      cat = *cptr++;
4075      refQ = *sQ++;
4076      refP = *sP++;
4077
4078      zz   = exp(rat                * lz);
4079      zv   = exp(rat * tr->rdta->xv * lz);
4080
4081     
4082      if(refP >= 0)
4083        {
4084          if(refQ >= 0)
4085            {
4086              calcptrP = &calcP[refP][cat];
4087              calcptrQ = &calcQ[refQ][cat];
4088              suma = calcptrP->fx1a * calcptrQ->a + 
4089                calcptrP->fx1c * calcptrQ->c + 
4090                calcptrP->fx1g * calcptrQ->g + calcptrP->fx1t * calcptrQ->t;
4091                     
4092             
4093              sumc = calcptrP->sumagct * calcptrQ->sumfx2rfx2y;
4094              sumb       = calcptrP->sumag * calcptrQ->fx2r * tr->rdta->invfreqr + calcptrP->sumct * calcptrQ->fx2y * tr->rdta->invfreqy;
4095               
4096            }
4097          else
4098            {
4099              calcptrP = &calcP[refP][cat];
4100              suma = calcptrP->fx1a * lq->a + calcptrP->fx1c * lq->c + 
4101                calcptrP->fx1g * lq->g + calcptrP->fx1t * lq->t;
4102             
4103              fx2r = tr->rdta->freqa * lq->a + tr->rdta->freqg * lq->g;
4104              fx2y = tr->rdta->freqc * lq->c + tr->rdta->freqt * lq->t;
4105                 
4106              sumc = calcptrP->sumagct * (fx2r + fx2y);
4107              sumb       = calcptrP->sumag * fx2r * tr->rdta->invfreqr + calcptrP->sumct * fx2y * tr->rdta->invfreqy;
4108               
4109            }
4110        }
4111      else
4112        {
4113          if(refQ >= 0)
4114            {
4115              calcptrQ = &calcQ[refQ][cat];
4116              fx1a = tr->rdta->freqa * lp->a;
4117              fx1g = tr->rdta->freqg * lp->g;
4118              fx1c = tr->rdta->freqc * lp->c;
4119              fx1t = tr->rdta->freqt * lp->t;
4120              suma = fx1a * calcptrQ->a + fx1c * calcptrQ->c + 
4121                fx1g * calcptrQ->g + fx1t * calcptrQ->t;         
4122              fx1r = fx1a + fx1g;
4123              fx1y = fx1c + fx1t;
4124              sumc = (fx1r + fx1y) * calcptrQ->sumfx2rfx2y; 
4125              sumb = fx1r * calcptrQ->fx2r * tr->rdta->invfreqr + fx1y * calcptrQ->fx2y * tr->rdta->invfreqy;
4126             
4127            }
4128          else
4129            {
4130              fx1a = tr->rdta->freqa * lp->a;
4131              fx1g = tr->rdta->freqg * lp->g;
4132              fx1c = tr->rdta->freqc * lp->c;
4133              fx1t = tr->rdta->freqt * lp->t;
4134              suma = fx1a * lq->a + fx1c * lq->c + fx1g * lq->g + fx1t * lq->t;
4135              fx2r = tr->rdta->freqa * lq->a + tr->rdta->freqg * lq->g;
4136              fx2y = tr->rdta->freqc * lq->c + tr->rdta->freqt * lq->t;
4137              fx1r = fx1a + fx1g;
4138              fx1y = fx1c + fx1t;
4139              sumc = (fx1r + fx1y) * (fx2r + fx2y);
4140              sumb = fx1r * fx2r * tr->rdta->invfreqr + fx1y * fx2y * tr->rdta->invfreqy;
4141             
4142            }
4143        }
4144
4145
4146
4147      abzz = zz * (suma - sumb);
4148      bczv = zv * (sumb - sumc);
4149      li = sumc + abzz + bczv;
4150      t3 = tr->rdta->xv * bczv;
4151      d  = abzz + t3;
4152      d2 = rat * (abzz*(rat-1.0) + t3*(rat * tr->rdta->xv - 1.0));
4153     
4154      temp = rat * d / li;
4155      w = *wptr++;
4156      slope += w *  temp;
4157      sum   += w * (temp * temp - d2/li);
4158      sumlr += w * log(li / (suma + 1.0E-300));
4159      lp++;
4160      lq++;
4161    }
4162
4163    *sumlrptr = sumlr;
4164    return (sum > 1.0E-300) ? z*(-slope + sqrt(slope*slope + 3.841*sum))/sum
4165                            : 1.0;
4166  } /* sigma */
4167
4168
4169void describe (tree *tr, nodeptr p)
4170    /* print out information for one branch */
4171  { /* describe */
4172    double   z, s, sumlr;
4173    nodeptr  q;
4174    char    *nameptr;
4175    int      k, ch;
4176
4177    q = p->back;
4178    printf("%4d          ", q->number - tr->mxtips);
4179    if (p->tip) {
4180      nameptr = p->name;
4181      k = nmlngth;
4182      while (ch = *nameptr++) {putchar(ch); k--;}
4183      while (--k >= 0) putchar(' ');
4184      }
4185    else {
4186      printf("%4d", p->number - tr->mxtips);
4187      for (k = 4; k < nmlngth; k++) putchar(' ');
4188      }
4189
4190    z = q->z;
4191    if (z <= zmin) printf("    infinity");
4192    else printf("%15.5f", -log(z) * tr->rdta->fracchange);
4193
4194    s = sigma(tr, q, & sumlr);
4195    printf("     (");
4196    if (z + s >= zmax) printf("     zero");
4197    else printf("%9.5f", (double) -log(z + s) * tr->rdta->fracchange);
4198    putchar(',');
4199    if (z - s <= zmin) printf("    infinity");
4200    else printf("%12.5f", (double) -log(z - s) * tr->rdta->fracchange);
4201    putchar(')');
4202
4203    if      (sumlr > 2.995 ) printf(" **");
4204    else if (sumlr > 1.9205) printf(" *");
4205    putchar('\n');
4206
4207    if (! p->tip) {
4208      describe(tr, p->next->back);
4209      describe(tr, p->next->next->back);
4210      }
4211  } /* describe */
4212
4213
4214void summarize (tree *tr)
4215    /* print out branch length information and node numbers */
4216  { /* summarize */
4217    printf("Ln Likelihood =%14.5f\n", tr->likelihood);
4218    putchar('\n');
4219    printf(" Between        And             Length");
4220    printf("      Approx. Confidence Limits\n");
4221    printf(" -------        ---             ------");
4222    printf("      ------- ---------- ------\n");
4223
4224    describe(tr, tr->start->back->next->back);
4225    describe(tr, tr->start->back->next->next->back);
4226    describe(tr, tr->start);
4227    putchar('\n');
4228    printf("     *  = significantly positive, P < 0.05\n");
4229    printf("     ** = significantly positive, P < 0.01\n\n\n");   
4230    globTime = gettime() - globTime;
4231    fprintf(stderr, "Acc time global: %f\n", globTime);
4232    printf("Acc time global: %f\n", globTime);
4233    fprintf(stderr, "FLOPBS: %ld\n", flopBlocks);   
4234    fprintf(stderr,"depth: %d\n", tr->eqDepth);
4235    printf("FLOPPBS: %ld\n", flopBlocks);
4236    fprintf(stderr,"countEQ: %ld, countNEQ: %ld\n", countEQ, countNEQ);
4237   
4238  } /* summarize */
4239
4240
4241/*===========  This is a problem if tr->start->back is a tip!  ===========*/
4242/*  All routines should be contrived so that tr->start->back is not a tip */
4243
4244char *treeString (char *treestr, tree *tr, nodeptr p, int form)
4245    /* write string with representation of tree */
4246    /*   form == 1 -> Newick tree */
4247    /*   form == 2 -> Prolog fact */
4248    /*   form == 3 -> PHYLIP tree */
4249  { /* treeString */
4250    double  x, z;
4251    char  *nameptr;
4252    int    c;
4253
4254    if (p == tr->start->back) {
4255      if (form != treePHYLIP) {
4256        if (form == treeProlog) {
4257          (void) sprintf(treestr, "phylip_tree(");
4258          while (*treestr) treestr++;            /* move pointer to null */
4259          }
4260
4261        (void) sprintf(treestr, "[&&%s: version = '%s'",
4262                                 programName, programVersion);
4263        while (*treestr) treestr++;
4264
4265        (void) sprintf(treestr, ", %s = %15.13g",
4266                                 likelihood_key, tr->likelihood);
4267        while (*treestr) treestr++;
4268
4269        (void) sprintf(treestr, ", %s = %d", ntaxa_key, tr->ntips);
4270        while (*treestr) treestr++;
4271
4272        (void) sprintf(treestr,", %s = %d", opt_level_key, tr->opt_level);
4273        while (*treestr) treestr++;
4274
4275        (void) sprintf(treestr, ", %s = %d", smoothed_key, tr->smoothed);
4276        while (*treestr) treestr++;
4277
4278        (void) sprintf(treestr, "]%s", form == treeProlog ? ", " : " ");
4279        while (*treestr) treestr++;
4280        }
4281      }
4282
4283    if (p->tip) {
4284      if (form != treePHYLIP) *treestr++ = '\'';
4285      nameptr = p->name;
4286      while (c = *nameptr++) {
4287        if (form != treePHYLIP) {if (c == '\'') *treestr++ = '\'';}
4288        else if (c == ' ') {c = '_';}
4289        *treestr++ = c;
4290        }
4291      if (form != treePHYLIP) *treestr++ = '\'';
4292      }
4293
4294    else {
4295      *treestr++ = '(';
4296      treestr = treeString(treestr, tr, p->next->back, form);
4297      *treestr++ = ',';
4298      treestr = treeString(treestr, tr, p->next->next->back, form);
4299      if (p == tr->start->back) {
4300        *treestr++ = ',';
4301        treestr = treeString(treestr, tr, p->back, form);
4302        }
4303      *treestr++ = ')';
4304      }
4305
4306    if (p == tr->start->back) {
4307      (void) sprintf(treestr, ":0.0%s\n", (form != treeProlog) ? ";" : ").");
4308      }
4309    else {
4310      z = p->z;
4311      if (z < zmin) z = zmin;
4312      x = -log(z) * tr->rdta->fracchange;
4313      (void) sprintf(treestr, ": %8.6f", x);  /* prolog needs the space */
4314      }
4315
4316    while (*treestr) treestr++;     /* move pointer up to null termination */
4317    return  treestr;
4318  } /* treeString */
4319
4320
4321void treeOut (FILE *treefile, tree *tr, int form)
4322    /* write out file with representation of final tree */
4323  { /* treeOut */
4324    int    c;
4325    char  *cptr, *treestr;
4326
4327    treestr = (char *) Malloc((tr->ntips * (nmlngth+32)) + 256);
4328    if (! treestr) {
4329      fprintf(stderr, "treeOut: Malloc failure\n");
4330      exit(1);
4331      }
4332
4333    (void) treeString(treestr, tr, tr->start->back, form);
4334    cptr = treestr;
4335    while (c = *cptr++) putc(c, treefile);
4336
4337    Free(treestr);
4338  } /* treeOut */
4339
4340
4341/*=======================================================================*/
4342/*                         Read a tree from a file                       */
4343/*=======================================================================*/
4344
4345
4346/*  1.0.A  Processing of quotation marks in comment removed
4347 */
4348
4349int treeFinishCom (FILE *fp, char **strp)
4350  { /* treeFinishCom */
4351    int  ch;
4352
4353    while ((ch = getc(fp)) != EOF && ch != ']') {
4354      if (strp != NULL) *(*strp)++ = ch;    /* save character  */
4355      if (ch == '[') {                      /* nested comment; find its end */
4356        if ((ch = treeFinishCom(fp, strp)) == EOF)  break;
4357        if (strp != NULL) *(*strp)++ = ch;  /* save closing ]  */
4358        }
4359      }
4360
4361    if (strp != NULL) **strp = '\0';        /* terminate string  */
4362    return  ch;
4363  } /* treeFinishCom */
4364
4365
4366int treeGetCh (FILE *fp)         /* get next nonblank, noncomment character */
4367  { /* treeGetCh */
4368    int  ch;
4369
4370    while ((ch = getc(fp)) != EOF) {
4371      if (whitechar(ch)) ;
4372      else if (ch == '[') {                   /* comment; find its end */
4373        if ((ch = treeFinishCom(fp, (char **) NULL)) == EOF)  break;
4374        }
4375      else  break;
4376      }
4377
4378    return  ch;
4379  } /* treeGetCh */
4380
4381
4382boolean  treeLabelEnd (int ch)
4383  { /* treeLabelEnd */
4384    switch (ch) {
4385        case EOF:  case '\0':  case '\t':  case '\n':  case ' ':
4386        case ':':  case ',':   case '(':   case ')':   case '[':
4387        case ';':
4388          return TRUE;
4389        default:
4390          break;
4391        }
4392    return FALSE;
4393  } /* treeLabelEnd */
4394
4395
4396boolean  treeGetLabel (FILE *fp, char *lblPtr, int maxlen)
4397  { /* treeGetLabel */
4398    int      ch;
4399    boolean  done, quoted, lblfound;
4400
4401    if (--maxlen < 0) lblPtr = (char *) NULL;  /* reserves space for '\0' */
4402    else if (lblPtr == NULL) maxlen = 0;
4403
4404    ch = getc(fp);
4405    done = treeLabelEnd(ch);
4406
4407    lblfound = ! done;
4408    quoted = (ch == '\'');
4409    if (quoted && ! done) {ch = getc(fp); done = (ch == EOF);}
4410
4411    while (! done) {
4412      if (quoted) {
4413        if (ch == '\'') {ch = getc(fp); if (ch != '\'') break;}
4414        }
4415
4416      else if (treeLabelEnd(ch)) break;
4417
4418      else if (ch == '_') ch = ' ';  /* unquoted _ goes to space */
4419
4420      if (--maxlen >= 0) *lblPtr++ = ch;
4421      ch = getc(fp);
4422      if (ch == EOF) break;
4423      }
4424
4425    if (ch != EOF)  (void) ungetc(ch, fp);
4426
4427    if (lblPtr != NULL) *lblPtr = '\0';
4428
4429    return lblfound;
4430  } /* treeGetLabel */
4431
4432
4433boolean  treeFlushLabel (FILE *fp)
4434  { /* treeFlushLabel */
4435    return  treeGetLabel(fp, (char *) NULL, (int) 0);
4436  } /* treeFlushLabel */
4437
4438
4439int  treeFindTipByLabel (char  *str, tree *tr)
4440                     /*  str -- label string pointer */
4441  { /* treeFindTipByLabel */
4442    nodeptr  q;
4443    char    *nameptr;
4444    int      ch, i, n;
4445    boolean  found;
4446
4447    for (n = 1; n <= tr->mxtips; n++) {
4448      q = tr->nodep[n];
4449      if (! (q->back)) {          /*  Only consider unused tips */
4450        i = 0;
4451        nameptr = q->name;
4452        while ((found = (str[i++] == (ch = *nameptr++))) && ch) ;
4453        if (found) return n;
4454        }
4455      }
4456
4457    printf("ERROR: Cannot find tree species: %s\n", str);
4458
4459    return  0;
4460  } /* treeFindTipByLabel */
4461
4462
4463int  treeFindTipName (FILE *fp, tree *tr)
4464  { /* treeFindTipName */
4465    char    *nameptr, str[nmlngth+2];
4466    int      n;
4467
4468    if (tr->prelabeled) {
4469      if (treeGetLabel(fp, str, nmlngth+2))
4470        n = treeFindTipByLabel(str, tr);
4471      else
4472        n = 0;
4473      }
4474
4475    else if (tr->ntips < tr->mxtips) {
4476      n = tr->ntips + 1;
4477      nameptr = tr->nodep[n]->name;
4478      if (! treeGetLabel(fp, nameptr, nmlngth+1)) n = 0;
4479      }
4480
4481    else {
4482      n = 0;
4483      }
4484
4485    return  n;
4486  } /* treeFindTipName */
4487
4488
4489void  treeEchoContext (FILE *fp1, FILE *fp2, int n)
4490 { /* treeEchoContext */
4491   int      ch;
4492   boolean  waswhite;
4493
4494   waswhite = TRUE;
4495
4496   while (n > 0 && ((ch = getc(fp1)) != EOF)) {
4497     if (whitechar(ch)) {
4498       ch = waswhite ? '\0' : ' ';
4499       waswhite = TRUE;
4500       }
4501     else {
4502       waswhite = FALSE;
4503       }
4504
4505     if (ch > '\0') {putc(ch, fp2); n--;}
4506     }
4507 } /* treeEchoContext */
4508
4509
4510boolean treeProcessLength (FILE *fp, double *dptr)
4511  { /* treeProcessLength */
4512    int  ch;
4513
4514    if ((ch = treeGetCh(fp)) == EOF)  return FALSE;    /*  Skip comments */
4515    (void) ungetc(ch, fp);
4516
4517    if (fscanf(fp, "%lf", dptr) != 1) {
4518      printf("ERROR: treeProcessLength: Problem reading branch length\n");
4519      treeEchoContext(fp, stdout, 40);
4520      printf("\n");
4521      return  FALSE;
4522      }
4523
4524    return  TRUE;
4525  } /* treeProcessLength */
4526
4527
4528boolean  treeFlushLen (FILE  *fp)
4529  { /* treeFlushLen */
4530    double  dummy;
4531    int     ch;
4532
4533    if ((ch = treeGetCh(fp)) == ':') return treeProcessLength(fp, & dummy);
4534
4535    if (ch != EOF) (void) ungetc(ch, fp);
4536    return TRUE;
4537  } /* treeFlushLen */
4538
4539
4540boolean  treeNeedCh (FILE *fp, int c1, char *where)
4541  { /* treeNeedCh */
4542    int  c2;
4543
4544    if ((c2 = treeGetCh(fp)) == c1)  return TRUE;
4545
4546    printf("ERROR: Expecting '%c' %s tree; found:", c1, where);
4547    if (c2 == EOF) {
4548      printf("End-of-File");
4549      }
4550    else {
4551      ungetc(c2, fp);
4552      treeEchoContext(fp, stdout, 40);
4553      }
4554    putchar('\n');
4555    return FALSE;
4556  } /* treeNeedCh */
4557
4558
4559boolean  addElementLen (FILE *fp, tree *tr, nodeptr p)
4560  { /* addElementLen */
4561    double   z, branch;
4562    nodeptr  q;
4563    int      n, ch;
4564
4565    if ((ch = treeGetCh(fp)) == '(') {     /*  A new internal node */
4566      n = (tr->nextnode)++;
4567      if (n > 2*(tr->mxtips) - 2) {
4568        if (tr->rooted || n > 2*(tr->mxtips) - 1) {
4569          printf("ERROR: Too many internal nodes.  Is tree rooted?\n");
4570          printf("       Deepest splitting should be a trifurcation.\n");
4571          return FALSE;
4572          }
4573        else {
4574          tr->rooted = TRUE;
4575          }
4576        }
4577      q = tr->nodep[n];
4578      if (! addElementLen(fp, tr, q->next))        return FALSE;
4579      if (! treeNeedCh(fp, ',', "in"))             return FALSE;
4580      if (! addElementLen(fp, tr, q->next->next))  return FALSE;
4581      if (! treeNeedCh(fp, ')', "in"))             return FALSE;
4582      (void) treeFlushLabel(fp);
4583      }
4584
4585    else {                               /*  A new tip */
4586      ungetc(ch, fp);
4587      if ((n = treeFindTipName(fp, tr)) <= 0)          return FALSE;
4588      q = tr->nodep[n];
4589      if (tr->start->number > n)  tr->start = q;
4590      (tr->ntips)++;
4591      }                                  /* End of tip processing */
4592
4593    if (tr->userlen) {
4594      if (! treeNeedCh(fp, ':', "in"))             return FALSE;
4595      if (! treeProcessLength(fp, & branch))       return FALSE;
4596      z = exp(-branch / tr->rdta->fracchange);
4597      if (z > zmax)  z = zmax;
4598      hookup(p, q, z);
4599      }
4600    else {
4601      if (! treeFlushLen(fp))                       return FALSE;
4602      hookup(p, q, defaultz);
4603      }
4604
4605    return TRUE;
4606  } /* addElementLen */
4607
4608
4609int saveTreeCom (char  **comstrp)
4610  { /* saveTreeCom */
4611    int  ch;
4612    boolean  inquote;
4613
4614    inquote = FALSE;
4615    while ((ch = getc(INFILE)) != EOF && (inquote || ch != ']')) {
4616      *(*comstrp)++ = ch;                        /* save character  */
4617      if (ch == '[' && ! inquote) {              /* comment; find its end */
4618        if ((ch = saveTreeCom(comstrp)) == EOF)  break;
4619        *(*comstrp)++ = ch;                      /* add ] */
4620        }
4621      else if (ch == '\'') inquote = ! inquote;  /* start or end of quote */
4622      }
4623
4624    return  ch;
4625  } /* saveTreeCom */
4626
4627
4628boolean processTreeCom (FILE *fp, tree *tr)
4629  { /* processTreeCom */
4630    int   text_started, functor_read, com_open;
4631
4632    /*  Accept prefatory "phylip_tree(" or "pseudoNewick("  */
4633
4634    functor_read = text_started = 0;
4635    (void) fscanf(fp, " p%nhylip_tree(%n", & text_started, & functor_read);
4636    if (text_started && ! functor_read) {
4637      (void) fscanf(fp, "seudoNewick(%n", & functor_read);
4638      if (! functor_read) {
4639        printf("Start of tree 'p...' not understood.\n");
4640        return FALSE;
4641        }
4642      }
4643
4644    com_open = 0;
4645    (void) fscanf(fp, " [%n", & com_open);
4646
4647    if (com_open) {                                  /* comment; read it */
4648      char  com[1024], *com_end;
4649
4650      com_end = com;
4651      if (treeFinishCom(fp, & com_end) == EOF) {     /* omits enclosing []s */
4652        printf("Missing end of tree comment\n");
4653        return FALSE;
4654        }
4655
4656      (void) readKeyValue(com, likelihood_key, "%lg",
4657                               (void *) &(tr->likelihood));
4658      (void) readKeyValue(com, opt_level_key,  "%d",
4659                               (void *) &(tr->opt_level));
4660      (void) readKeyValue(com, smoothed_key,   "%d",
4661                               (void *) &(tr->smoothed));
4662
4663      if (functor_read) (void) fscanf(fp, " ,");   /* remove trailing comma */
4664      }
4665
4666    return (functor_read > 0);
4667  } /* processTreeCom */
4668
4669
4670nodeptr uprootTree (tree *tr, nodeptr p)
4671  { /* uprootTree */
4672    nodeptr  q, r, s, start;
4673    int      n;
4674
4675    if (p->tip || p->back) {
4676      printf("ERROR: Unable to uproot tree.\n");
4677      printf("       Inappropriate node marked for removal.\n");
4678      return (nodeptr) NULL;
4679      }
4680
4681    n = --(tr->nextnode);               /* last internal node added */
4682    if (n != tr->mxtips + tr->ntips - 1) {
4683      printf("ERROR: Unable to uproot tree.  Inconsistent\n");
4684      printf("       number of tips and nodes for rooted tree.\n");
4685      return (nodeptr) NULL;
4686      }
4687
4688    q = p->next->back;                  /* remove p from tree */
4689    r = p->next->next->back;
4690    hookup(q, r, tr->userlen ? (q->z * r->z) : defaultz);
4691
4692    start = (r->tip || (! q->tip)) ? r : r->next->next->back;
4693
4694    if (tr->ntips > 2 && p->number != n) {
4695      q = tr->nodep[n];            /* transfer last node's conections to p */
4696      r = q->next;
4697      s = q->next->next;
4698      hookup(p,             q->back, q->z);   /* move connections to p */
4699      hookup(p->next,       r->back, r->z);
4700      hookup(p->next->next, s->back, s->z);
4701      if (start->number == q->number) start = start->back->back;
4702      q->back = r->back = s->back = (nodeptr) NULL;
4703      }
4704    else {
4705      p->back = p->next->back = p->next->next->back = (nodeptr) NULL;
4706      }
4707
4708    tr->rooted = FALSE;
4709    return  start;
4710  } /* uprootTree */
4711
4712
4713boolean treeReadLen (FILE *fp, tree *tr)
4714  { /* treeReadLen */
4715    nodeptr  p;
4716    int      i, ch;
4717    boolean  is_fact;
4718
4719    for (i = 1; i <= tr->mxtips; i++) tr->nodep[i]->back = (node *) NULL;
4720    tr->start       = tr->nodep[tr->mxtips];
4721    tr->ntips       = 0;
4722    tr->nextnode    = tr->mxtips + 1;
4723    tr->opt_level   = 0;
4724    tr->log_f_valid = 0;
4725    tr->smoothed    = FALSE;
4726    tr->rooted      = FALSE;
4727
4728    is_fact = processTreeCom(fp, tr);
4729
4730    p = tr->nodep[(tr->nextnode)++];
4731    if (! treeNeedCh(fp, '(', "at start of"))       return FALSE;
4732    if (! addElementLen(fp, tr, p))                 return FALSE;
4733    if (! treeNeedCh(fp, ',', "in"))                return FALSE;
4734    if (! addElementLen(fp, tr, p->next))           return FALSE;
4735    if (! tr->rooted) {
4736      if ((ch = treeGetCh(fp)) == ',') {        /*  An unrooted format */
4737        if (! addElementLen(fp, tr, p->next->next)) return FALSE;
4738        }
4739      else {                                    /*  A rooted format */
4740        tr->rooted = TRUE;
4741        if (ch != EOF)  (void) ungetc(ch, fp);
4742        }
4743      }
4744    else {
4745      p->next->next->back = (nodeptr) NULL;
4746      }
4747    if (! treeNeedCh(fp, ')', "in"))                return FALSE;
4748    (void) treeFlushLabel(fp);
4749    if (! treeFlushLen(fp))                         return FALSE;
4750    if (is_fact) {
4751      if (! treeNeedCh(fp, ')', "at end of"))       return FALSE;
4752      if (! treeNeedCh(fp, '.', "at end of"))       return FALSE;
4753      }
4754    else {
4755      if (! treeNeedCh(fp, ';', "at end of"))       return FALSE;
4756      }
4757
4758    if (tr->rooted) {
4759      p->next->next->back = (nodeptr) NULL;
4760      tr->start = uprootTree(tr, p->next->next);
4761      if (! tr->start)                              return FALSE;
4762      }
4763    else {
4764      tr->start = p->next->next->back;  /* This is start used by treeString */
4765      }
4766
4767    return  (initrav(tr, tr->start) && initrav(tr, tr->start->back));
4768  } /* treeReadLen */
4769
4770
4771/*=======================================================================*/
4772/*                        Read a tree from a string                      */
4773/*=======================================================================*/
4774
4775
4776#if Master || Slave
4777int str_treeFinishCom (char **treestrp, char **strp)
4778                      /* treestrp -- tree string pointer */
4779                      /* strp -- comment string pointer */
4780  { /* str_treeFinishCom */
4781    int  ch;
4782
4783    while ((ch = *(*treestrp)++) != NULL && ch != ']') {
4784      if (strp != NULL) *(*strp)++ = ch;    /* save character  */
4785      if (ch == '[') {                      /* nested comment; find its end */
4786        if ((ch = str_treeFinishCom(treestrp)) == NULL)  break;
4787        if (strp != NULL) *(*strp)++ = ch;  /* save closing ]  */
4788        }
4789      }
4790    if (strp != NULL) **strp = '\0';        /* terminate string  */
4791    return  ch;
4792  } /* str_treeFinishCom */
4793
4794
4795int str_treeGetCh (char **treestrp)
4796    /* get next nonblank, noncomment character */
4797  { /* str_treeGetCh */
4798    int  ch;
4799   
4800    while ((ch = *(*treestrp)++) != NULL) {
4801      if (whitechar(ch)) ;
4802      else if (ch == '[') {                  /* comment; find its end */
4803        if ((ch = str_treeFinishCom(treestrp, (char *) NULL)) == NULL)  break;
4804        }
4805      else  break;
4806      }
4807
4808    return  ch;
4809  } /* str_treeGetCh */
4810
4811
4812boolean  str_treeGetLabel (char **treestrp, char *lblPtr, int maxlen)
4813  { /* str_treeGetLabel */
4814    int      ch;
4815    boolean  done, quoted, lblfound;
4816
4817    if (--maxlen < 0) lblPtr = (char *) NULL;  /* reserves space for '\0' */
4818    else if (lblPtr == NULL) maxlen = 0;
4819
4820    ch = *(*treestrp)++;
4821    done = treeLabelEnd(ch);
4822
4823    lblfound = ! done;
4824    quoted = (ch == '\'');
4825    if (quoted && ! done) {ch = *(*treestrp)++; done = (ch == '\0');}
4826
4827    while (! done) {
4828      if (quoted) {
4829        if (ch == '\'') {ch = *(*treestrp)++; if (ch != '\'') break;}
4830        }
4831
4832      else if (treeLabelEnd(ch)) break;
4833
4834      else if (ch == '_') ch = ' ';  /* unquoted _ goes to space */
4835
4836      if (--maxlen >= 0) *lblPtr++ = ch;
4837      ch = *(*treestrp)++;
4838      if (ch == '\0') break;
4839      }
4840
4841    (*treestrp)--;
4842
4843    if (lblPtr != NULL) *lblPtr = '\0';
4844
4845    return lblfound;
4846  } /* str_treeGetLabel */
4847
4848
4849boolean  str_treeFlushLabel (char **treestrp)
4850  { /* str_treeFlushLabel */
4851    return  str_treeGetLabel(treestrp, (char *) NULL, (int) 0);
4852  } /* str_treeFlushLabel */
4853
4854
4855int  str_treeFindTipName (char **treestrp, tree *tr)
4856  { /* str_treeFindTipName */
4857    nodeptr  q;
4858    char    *nameptr, str[nmlngth+2];
4859    int      ch, i, n;
4860
4861    if (tr->prelabeled) {
4862      if (str_treeGetLabel(treestrp, str, nmlngth+2))
4863        n = treeFindTipByLabel(str, tr);
4864      else
4865        n = 0;
4866      }
4867
4868    else if (tr->ntips < tr->mxtips) {
4869      n = tr->ntips + 1;
4870      nameptr = tr->nodep[n]->name;
4871      if (! str_treeGetLabel(treestrp, nameptr, nmlngth+1)) n = 0;
4872      }
4873
4874    else {
4875      n = 0;
4876      }
4877
4878    return  n;
4879  } /* str_treeFindTipName */
4880
4881
4882boolean str_treeProcessLength (char **treestrp, double *dptr)
4883  { /* str_treeProcessLength */
4884    int     used;
4885
4886    if(! str_treeGetCh(treestrp))  return FALSE;    /*  Skip comments */
4887    (*treestrp)--;
4888
4889    if (sscanf(*treestrp, "%lf%n", dptr, & used) != 1) {
4890      printf("ERROR: str_treeProcessLength: Problem reading branch length\n");
4891      printf("%40s\n", *treestrp);
4892      *dptr = 0.0;
4893      return FALSE;
4894      }
4895    else {
4896      *treestrp += used;
4897      }
4898
4899    return  TRUE;
4900  } /* str_treeProcessLength */
4901
4902
4903boolean  str_treeFlushLen (char **treestrp)
4904  { /* str_treeFlushLen */
4905    int  ch;
4906
4907    if ((ch = str_treeGetCh(treestrp)) == ':')
4908      return str_treeProcessLength(treestrp, (double *) NULL);
4909    else {
4910      (*treestrp)--;
4911      return TRUE;
4912      }
4913  } /* str_treeFlushLen */
4914
4915
4916boolean  str_treeNeedCh (char **treestrp, int c1, char *where)
4917  { /* str_treeNeedCh */
4918    int  c2, i;
4919
4920    if ((c2 = str_treeGetCh(treestrp)) == c1)  return TRUE;
4921
4922    printf("ERROR: Missing '%c' %s tree; ", c1, where);
4923    if (c2 == '\0') 
4924      printf("end-of-string");
4925    else {
4926      putchar('"');
4927      for (i = 24; i-- && (c2 != '\0'); c2 = *(*treestrp)++)  putchar(c2);
4928      putchar('"');
4929      }
4930
4931    printf(" found instead\n");
4932    return FALSE;
4933  } /* str_treeNeedCh */
4934
4935
4936boolean  str_addElementLen (char **treestrp, tree *tr, nodeptr p)
4937  { /* str_addElementLen */
4938    double   z, branch;
4939    nodeptr  q;
4940    int      n, ch;
4941
4942    if ((ch = str_treeGetCh(treestrp)) == '(') { /*  A new internal node */
4943      n = (tr->nextnode)++;
4944      if (n > 2*(tr->mxtips) - 2) {
4945        if (tr->rooted || n > 2*(tr->mxtips) - 1) {
4946          printf("ERROR: too many internal nodes.  Is tree rooted?\n");
4947          printf("Deepest splitting should be a trifurcation.\n");
4948          return  FALSE;
4949          }
4950        else {
4951          tr->rooted = TRUE;
4952          }
4953        }
4954      q = tr->nodep[n];
4955      if (! str_addElementLen(treestrp, tr, q->next))          return FALSE;
4956      if (! str_treeNeedCh(treestrp, ',', "in"))               return FALSE;
4957      if (! str_addElementLen(treestrp, tr, q->next->next))    return FALSE;
4958      if (! str_treeNeedCh(treestrp, ')', "in"))               return FALSE;
4959      if (! str_treeFlushLabel(treestrp))                      return FALSE;
4960      }
4961
4962    else {                           /*  A new tip */
4963      n = str_treeFindTipName(treestrp, tr, ch);
4964      if (n <= 0) return FALSE;
4965      q = tr->nodep[n];
4966      if (tr->start->number > n)  tr->start = q;
4967      (tr->ntips)++;
4968      }                              /* End of tip processing */
4969
4970    /*  Master and Slave always use lengths */
4971
4972    if (! str_treeNeedCh(treestrp, ':', "in"))                 return FALSE;
4973    if (! str_treeProcessLength(treestrp, & branch))           return FALSE;
4974    z = exp(-branch / tr->rdta->fracchange);
4975    if (z > zmax)  z = zmax;
4976    hookup(p, q, z);
4977
4978    return  TRUE;
4979  } /* str_addElementLen */
4980
4981
4982boolean str_processTreeCom(tree *tr, char **treestrp)
4983  { /* str_processTreeCom */
4984    char  *com, *com_end;
4985    int  text_started, functor_read, com_open;
4986
4987    com = *treestrp;
4988
4989    functor_read = text_started = 0;
4990    sscanf(com, " p%nhylip_tree(%n", & text_started, & functor_read);
4991    if (functor_read) {
4992      com += functor_read;
4993      }
4994    else if (text_started) {
4995      com += text_started;
4996      sscanf(com, "seudoNewick(%n", & functor_read);
4997      if (! functor_read) {
4998        printf("Start of tree 'p...' not understood.\n");
4999        return  FALSE;
5000        }
5001      else {
5002        com += functor_read;
5003        }
5004      }
5005
5006    com_open = 0;
5007    sscanf(com, " [%n", & com_open);
5008    com += com_open;
5009
5010    if (com_open) {                              /* comment; read it */
5011        if (!(com_end = strchr(com, ']'))) {
5012        printf("Missing end of tree comment.\n");
5013        return  FALSE;
5014        }
5015
5016      *com_end = 0;
5017      (void) readKeyValue(com, likelihood_key, "%lg",
5018                               (void *) &(tr->likelihood));
5019      (void) readKeyValue(com, opt_level_key,  "%d",
5020                               (void *) &(tr->opt_level));
5021      (void) readKeyValue(com, smoothed_key,   "%d",
5022                               (void *) &(tr->smoothed));
5023      *com_end = ']';
5024      com_end++;
5025
5026      if (functor_read) {                          /* remove trailing comma */
5027        text_started = 0;
5028        sscanf(com_end, " ,%n", & text_started);
5029        com_end += text_started;
5030        }
5031
5032      *treestrp = com_end;
5033      }
5034
5035    return (functor_read > 0);
5036  } /* str_processTreeCom */
5037
5038
5039boolean str_treeReadLen (char *treestr, tree *tr)
5040    /* read string with representation of tree */
5041  { /* str_treeReadLen */
5042    nodeptr  p;
5043    int  i;
5044    boolean  is_fact, found;
5045
5046    for (i = 1; i <= tr->mxtips; i++) tr->nodep[i]->back = (node *) NULL;
5047    tr->start       = tr->nodep[tr->mxtips];
5048    tr->ntips       = 0;
5049    tr->nextnode    = tr->mxtips + 1;
5050    tr->opt_level   = 0;
5051    tr->log_f_valid = 0;
5052    tr->smoothed    = Master;
5053    tr->rooted      = FALSE;
5054
5055    is_fact = str_processTreeCom(tr, & treestr);
5056
5057    p = tr->nodep[(tr->nextnode)++];
5058    if (! str_treeNeedCh(& treestr, '(', "at start of"))       return FALSE;
5059    if (! str_addElementLen(& treestr, tr, p))                 return FALSE;
5060    if (! str_treeNeedCh(& treestr, ',', "in"))                return FALSE;
5061    if (! str_addElementLen(& treestr, tr, p->next))           return FALSE;
5062    if (! tr->rooted) {
5063      if (str_treeGetCh(& treestr) == ',') {        /*  An unrooted format */
5064        if (! str_addElementLen(& treestr, tr, p->next->next)) return FALSE;
5065        }
5066      else {                                       /*  A rooted format */
5067        p->next->next->back = (nodeptr) NULL;
5068        tr->rooted = TRUE;
5069        treestr--;
5070        }
5071      }
5072    if (! str_treeNeedCh(& treestr, ')', "in"))                return FALSE;
5073    if (! str_treeFlushLabel(& treestr))                       return FALSE;
5074    if (! str_treeFlushLen(& treestr))                         return FALSE;
5075    if (is_fact) {
5076      if (! str_treeNeedCh(& treestr, ')', "at end of"))       return FALSE;
5077      if (! str_treeNeedCh(& treestr, '.', "at end of"))       return FALSE;
5078      }
5079    else {
5080      if (! str_treeNeedCh(& treestr, ';', "at end of"))       return FALSE;
5081      }
5082
5083    if (tr->rooted)  if (! uprootTree(tr, p->next->next))     return FALSE;
5084    tr->start = p->next->next->back;  /* This is start used by treeString */
5085
5086    return  (initrav(tr, tr->start) && initrav(tr, tr->start->back));
5087  } /* str_treeReadLen */
5088#endif
5089
5090
5091boolean treeEvaluate (tree *tr, bestlist *bt)       /* Evaluate a user tree */
5092  { /* treeEvaluate */
5093
5094    if (Slave || ! tr->userlen) {
5095      if (! smoothTree(tr, 4 * smoothings)) return FALSE;
5096      }
5097
5098    if (evaluate(tr, tr->start) == badEval)  return FALSE;
5099
5100#   if ! Slave
5101      (void) saveBestTree(bt, tr);
5102#   endif
5103    return TRUE;
5104  } /* treeEvaluate */
5105
5106
5107#if Master || Slave
5108FILE *freopen_pid (char *filenm, char *mode, FILE *stream)
5109  { /* freopen_pid */
5110    char scr[512];
5111
5112    (void) sprintf(scr, "%s.%d", filenm, getpid());
5113    return  freopen(scr, mode, stream);
5114  } /* freopen_pid */
5115#endif
5116
5117
5118boolean  showBestTrees (bestlist *bt, tree *tr, analdef *adef, FILE *treefile)
5119  { /* showBestTrees */
5120    int     rank;
5121
5122    for (rank = 1; rank <= bt->nvalid; rank++) {
5123      if (rank > 1) {
5124        if (rank != recallBestTree(bt, rank, tr))  break;
5125        }
5126      if (evaluate(tr, tr->start) == badEval) return FALSE;
5127      if (tr->outgrnode->back)  tr->start = tr->outgrnode;
5128      printTree(tr, adef);
5129      summarize(tr);
5130      if (treefile)  treeOut(treefile, tr, adef->trout);
5131      }
5132
5133    return TRUE;
5134  } /* showBestTrees */
5135
5136
5137boolean cmpBestTrees (bestlist *bt, tree *tr)
5138  { /* cmpBestTrees */
5139    double  sum, sum2, sd, temp, wtemp, bestscore;
5140    double *log_f0, *log_f0_ptr;      /* Save a copy of best log_f */
5141    double *log_f_ptr;
5142    int     i, j, num, besttips;
5143
5144    num = bt->nvalid;
5145    if ((num <= 1) || (tr->cdta->wgtsum <= 1)) return TRUE;
5146
5147    if (! (log_f0 = (double *) Malloc(sizeof(double) * tr->cdta->endsite))) {
5148      printf("ERROR: cmpBestTrees unable to obtain space for log_f0\n");
5149      return FALSE;
5150      }
5151
5152    printf("Tree      Ln L        Diff Ln L       Its S.D.");
5153    printf("   Significantly worse?\n\n");
5154
5155    for (i = 1; i <= num; i++) {
5156      if (i != recallBestTree(bt, i, tr))  break;
5157      if (! (tr->log_f_valid))  {
5158        if (evaluate(tr, tr->start) == badEval) return FALSE;
5159        }
5160
5161      printf("%3d%14.5f", i, tr->likelihood);
5162      if (i == 1) {
5163        printf("  <------ best\n");
5164        besttips = tr->ntips;
5165        bestscore = tr->likelihood;
5166        log_f0_ptr = log_f0;
5167        log_f_ptr  = tr->log_f;
5168        for (j = 0; j < tr->cdta->endsite; j++)  *log_f0_ptr++ = *log_f_ptr++;
5169        }
5170      else if (tr->ntips != besttips)
5171        printf("  (different number of species)\n");
5172      else {
5173        sum = sum2 = 0.0;
5174        log_f0_ptr = log_f0;
5175        log_f_ptr  = tr->log_f;
5176        for (j = 0; j < tr->cdta->endsite; j++) {
5177          temp  = *log_f0_ptr++ - *log_f_ptr++;
5178          wtemp = tr->cdta->aliaswgt[j] * temp;
5179          sum  += wtemp;
5180          sum2 += wtemp * temp;
5181          }
5182        sd = sqrt( tr->cdta->wgtsum * (sum2 - sum*sum / tr->cdta->wgtsum)
5183                                    / (tr->cdta->wgtsum - 1) );
5184        printf("%14.5f%14.4f", tr->likelihood - bestscore, sd);
5185        printf("           %s\n", (sum > 1.95996 * sd) ? "Yes" : " No");
5186        }
5187      }
5188
5189    Free(log_f0);
5190    printf("\n\n");
5191
5192    return TRUE;
5193  } /* cmpBestTrees */
5194
5195
5196boolean  makeUserTree (tree *tr, bestlist *bt, analdef *adef)
5197  { /* makeUserTree */
5198    char   filename[128];
5199    FILE  *treefile;
5200    int    nusertrees, which;
5201
5202    nusertrees = adef->numutrees;
5203
5204    printf("User-defined %s:\n\n", (nusertrees == 1) ? "tree" : "trees");
5205
5206    treefile = adef->trout ? fopen_pid("treefile", "w", filename) : (FILE *) NULL;
5207
5208    for (which = 1; which <= nusertrees; which++) {
5209      if (! treeReadLen(INFILE, tr)) return FALSE;
5210      if (! treeEvaluate(tr, bt))    return FALSE;
5211      if (tr->global <= 0) {
5212        if (tr->outgrnode->back)  tr->start = tr->outgrnode;
5213        printTree(tr, adef);
5214        summarize(tr);
5215        if (treefile)  treeOut(treefile, tr, adef->trout);
5216        }
5217      else {
5218        printf("%6d:  Ln Likelihood =%14.5f\n", which, tr->likelihood);
5219        }
5220      }
5221
5222    if (tr->global > 0) {
5223      putchar('\n');
5224      if (! recallBestTree(bt, 1, tr))  return FALSE;
5225      printf("      Ln Likelihood =%14.5f\n", tr->likelihood);
5226      if (! optimize(tr, tr->global, bt))  return FALSE;
5227      if (tr->outgrnode->back)  tr->start = tr->outgrnode;
5228      printTree(tr, adef);
5229      summarize(tr);
5230      if (treefile)  treeOut(treefile, tr, adef->trout);
5231      }
5232
5233    if (treefile) {
5234      (void) fclose(treefile);
5235      printf("Tree also written to %s\n", filename);
5236      }
5237
5238    putchar('\n');
5239
5240    (void) cmpBestTrees(bt, tr);
5241    return TRUE;
5242  } /* makeUserTree */
5243
5244
5245#if Slave
5246boolean slaveTreeEvaluate (tree *tr, bestlist *bt)
5247  { /* slaveTreeEvaluate */
5248    boolean done;
5249
5250    do {
5251       requestForWork();
5252       if (! receiveTree(& comm_master, tr))        return FALSE;
5253       done = tr->likelihood > 0.0;
5254       if (! done) {
5255         if (! treeEvaluate(tr, bt))                return FALSE;
5256         if (! sendTree(& comm_master, tr))         return FALSE;
5257         }
5258       } while (! done);
5259
5260    return TRUE;
5261  } /* slaveTreeEvaluate */
5262#endif
5263
5264
5265double randum (long  *seed)
5266    /* random number generator, modified to use 12 bit chunks */
5267  { /* randum */
5268    long  sum, mult0, mult1, seed0, seed1, seed2, newseed0, newseed1, newseed2;
5269
5270    mult0 = 1549;
5271    seed0 = *seed & 4095;
5272    sum  = mult0 * seed0;
5273    newseed0 = sum & 4095;
5274    sum >>= 12;
5275    seed1 = (*seed >> 12) & 4095;
5276    mult1 =  406;
5277    sum += mult0 * seed1 + mult1 * seed0;
5278    newseed1 = sum & 4095;
5279    sum >>= 12;
5280    seed2 = (*seed >> 24) & 255;
5281    sum += mult0 * seed2 + mult1 * seed1;
5282    newseed2 = sum & 255;
5283
5284    *seed = newseed2 << 24 | newseed1 << 12 | newseed0;
5285    return  0.00390625 * (newseed2
5286                          + 0.000244140625 * (newseed1
5287                                              + 0.000244140625 * newseed0));
5288  } /* randum */
5289
5290
5291boolean makeDenovoTree (tree *tr, bestlist *bt, analdef *adef)
5292  { /* makeDenovoTree */
5293    char   filename[128];
5294    FILE  *treefile;
5295    nodeptr  p;
5296    int  *enterorder;      /*  random entry order */
5297    int  i, j, k, nextsp, newsp, maxtrav, tested;
5298
5299    double randum();
5300
5301
5302    enterorder = (int *) Malloc(sizeof(int) * (tr->mxtips + 1));
5303    if (! enterorder) {
5304       fprintf(stderr, "makeDenovoTree: Malloc failure for enterorder\n");
5305       return 0;
5306       }
5307
5308    if (adef->restart) {
5309      printf("Restarting from tree with the following sequences:\n");
5310      tr->userlen = TRUE;
5311      if (! treeReadLen(INFILE, tr))          return FALSE;
5312      if (! smoothTree(tr, smoothings))       return FALSE;
5313      if (evaluate(tr, tr->start) == badEval) return FALSE;
5314      if (saveBestTree(bt, tr) < 1)           return FALSE;
5315
5316      for (i = 1, j = tr->ntips; i <= tr->mxtips; i++) { /* find loose tips */
5317        if (! tr->nodep[i]->back) {
5318          enterorder[++j] = i;
5319          }
5320        else {
5321          printf("   %s\n", tr->nodep[i]->name);
5322
5323#         if Master
5324            if (i>3) REPORT_ADD_SPECS;
5325#         endif
5326          }
5327        }
5328      putchar('\n');
5329      }
5330
5331    else {                                           /* start from scratch */
5332      tr->ntips = 0;
5333      for (i = 1; i <= tr->mxtips; i++) enterorder[i] = i;
5334      }
5335
5336    if (adef->jumble) for (i = tr->ntips + 1; i <= tr->mxtips; i++) {
5337      j = randum(&(adef->jumble))*(tr->mxtips - tr->ntips) + tr->ntips + 1;
5338      k = enterorder[j];
5339      enterorder[j] = enterorder[i];
5340      enterorder[i] = k;
5341      }
5342
5343    bt->numtrees = 1;
5344    if (tr->ntips < tr->mxtips)  printf("Adding species:\n");
5345
5346    if (tr->ntips == 0) {
5347      for (i = 1; i <= 3; i++) {
5348        printf("   %s\n", tr->nodep[enterorder[i]]->name);
5349        }
5350      tr->nextnode = tr->mxtips + 1;
5351      if (! buildSimpleTree(tr, enterorder[1], enterorder[2], enterorder[3]))
5352        return FALSE;
5353      }
5354
5355    while (tr->ntips < tr->mxtips || tr->opt_level < tr->global) {
5356      maxtrav = (tr->ntips == tr->mxtips) ? tr->global : tr->partswap;
5357      if (maxtrav > tr->ntips - 3)  maxtrav = tr->ntips - 3;
5358
5359      if (tr->opt_level >= maxtrav) {
5360        nextsp = ++(tr->ntips);
5361        newsp = enterorder[nextsp];
5362        p = tr->nodep[newsp];
5363        printf("   %s\n", p->name);
5364
5365#       if Master
5366          if (nextsp % DNAML_STEP_TIME_COUNT == 1) {
5367            REPORT_STEP_TIME;
5368            }
5369          REPORT_ADD_SPECS;
5370#       endif
5371
5372        (void) buildNewTip(tr, p);
5373
5374        resetBestTree(bt);
5375        cacheZ(tr);
5376        tested = addTraverse(tr, p->back, findAnyTip(tr->start)->back,
5377                             1, tr->ntips - 2, bt, adef->qadd);
5378        if (tested == badRear) return FALSE;
5379        bt->numtrees += tested;
5380
5381#       if Master
5382          getReturnedTrees(tr, bt, tested);
5383#       endif
5384
5385        printf("      Tested %d alternative trees\n", tested);
5386       
5387
5388
5389        (void) recallBestTree(bt, 1, tr);
5390        if (! tr->smoothed) {
5391          if (! smoothTree(tr, smoothings))        return FALSE;
5392          if (evaluate(tr, tr->start) == badEval)  return FALSE;
5393          (void) saveBestTree(bt, tr);
5394          }
5395
5396        if (tr->ntips == 4)  tr->opt_level = 1;  /* All 4 taxon trees done */
5397        maxtrav = (tr->ntips == tr->mxtips) ? tr->global : tr->partswap;
5398        if (maxtrav > tr->ntips - 3)  maxtrav = tr->ntips - 3;
5399        }
5400
5401      printf("      Ln Likelihood =%14.5f\n", tr->likelihood);
5402      if (! optimize(tr, maxtrav, bt)) return FALSE;
5403      }
5404
5405    printf("\nExamined %d %s\n", bt->numtrees,
5406                                 bt->numtrees != 1 ? "trees" : "tree");
5407
5408    treefile = adef->trout ? fopen_pid("treefile", "w", filename) : (FILE *) NULL;
5409    (void) showBestTrees(bt, tr, adef, treefile);
5410    if (treefile) {
5411      (void) fclose(treefile);
5412      printf("Tree also written to %s\n\n", filename);
5413      }
5414
5415    (void) cmpBestTrees(bt, tr);
5416
5417#   if DeleteCheckpointFile
5418      unlink_pid(checkpointname);
5419#   endif
5420
5421    Free(enterorder);
5422
5423    return TRUE;
5424  } /* makeDenovoTree */
5425
5426/*==========================================================================*/
5427/*                             "main" routine                               */
5428/*==========================================================================*/
5429
5430#if Sequential
5431  main ()
5432#else
5433  slave ()
5434#endif
5435  { /* DNA Maximum Likelihood */
5436#   if Master
5437      int starttime, inputtime, endtime;
5438#   endif
5439
5440#   if Master || Slave
5441      int my_id, nprocs, type, from, sz;
5442      char *msg;
5443#   endif
5444
5445    analdef      *adef;
5446    rawdata      *rdta;
5447    cruncheddata  *cdta;
5448    tree         *tr;    /*  current tree */
5449    bestlist     *bt;    /*  topology of best found tree */
5450
5451    globTime = gettime();
5452
5453#   if Debug
5454      {
5455        char debugfilename[128];
5456        debug = fopen_pid("dnaml_debug", "w", debugfilename);
5457        }
5458#   endif
5459
5460#   if Master
5461      starttime = p4_clock();
5462      nprocs = p4_num_total_slaves();
5463
5464      if ((OUTFILE = freopen_pid("master.out", "w", stdout)) == NULL) {
5465        fprintf(stderr, "Could not open output file\n");
5466        exit(1);
5467        }
5468
5469      /* Receive input file name from host */
5470      type = DNAML_FILE_NAME;
5471      from = DNAML_HOST_ID;
5472      msg  = NULL;
5473      p4_recv(& type, & from, & msg, & sz);
5474      if ((INFILE = fopen(msg, "r")) == NULL) {
5475        fprintf(stderr, "master could not open input file %s\n", msg);
5476        exit(1);
5477        }
5478      p4_msg_free(msg);
5479
5480      open_link(& comm_slave);
5481#   endif
5482
5483#  if DNAML_STEP
5484      begin_step_time = starttime;
5485#  endif
5486
5487#   if Slave
5488      my_id = p4_get_my_id();
5489      nprocs = p4_num_total_slaves();
5490
5491      /* Receive input file name from host */
5492      type = DNAML_FILE_NAME;
5493      from = DNAML_HOST_ID;
5494      msg  = NULL;
5495      p4_recv(& type, & from, & msg, & sz);
5496      if ((INFILE = fopen(msg, "r")) == NULL) {
5497        fprintf(stderr, "slave could not open input file %s\n",msg);
5498        exit(1);
5499        }
5500      p4_msg_free(msg);
5501
5502#     ifdef P4DEBUG
5503        if ((OUTFILE = freopen_pid("slave.out", "w", stdout)) == NULL) {
5504          fprintf(stderr, "Could not open output file\n");
5505          exit(1);
5506          }
5507#     else
5508        if ((OUTFILE = freopen("/dev/null", "w", stdout)) == NULL) {
5509          fprintf(stderr, "Could not open output file\n");
5510          exit(1);
5511          }
5512#     endif
5513
5514      open_link(& comm_master);
5515#   endif
5516
5517
5518/*  Get data structure memory  */
5519
5520    if (! (adef = (analdef *) Malloc(sizeof(analdef)))) {
5521      printf("ERROR: Unable to get memory for analysis definition\n\n");
5522      return 1;
5523      }
5524
5525    if (! (rdta = (rawdata *) Malloc(sizeof(rawdata)))) {
5526      printf("ERROR: Unable to get memory for raw DNA\n\n");
5527      return 1;
5528      }
5529
5530    if (! (cdta = (cruncheddata *) Malloc(sizeof(cruncheddata)))) {
5531      printf("ERROR: Unable to get memory for crunched DNA\n\n");
5532      return 1;
5533      }
5534
5535    if ((tr = (tree *)     Malloc(sizeof(tree))) &&
5536        (bt = (bestlist *) Malloc(sizeof(bestlist)))) ;
5537    else {
5538      printf("ERROR: Unable to get memory for trees\n\n");
5539      return 1;
5540      }
5541    bt->ninit = 0;
5542
5543    if (! getinput(adef, rdta, cdta, tr))                            return 1;
5544
5545#   if Master
5546      inputtime = p4_clock();
5547      printf("Input time %d milliseconds\n", inputtime - starttime);
5548      REPORT_STEP_TIME;
5549#   endif
5550
5551#   if Slave
5552      (void) fclose(INFILE);
5553#   endif
5554
5555/*  The material below would be a loop over jumbles and/or boots */
5556
5557    if (! makeweights(adef, rdta, cdta))                             return 1;
5558    if (! makevalues(rdta, cdta))                                    return 1;
5559    if (adef->empf && ! empiricalfreqs(rdta, cdta))                  return 1;
5560    reportfreqs(adef, rdta);
5561    if (! linkdata2tree(rdta, cdta, tr))                             return 1;
5562
5563    if (! linkxarray(3, 3, cdta->endsite, & freextip, & usedxtip))   return 1;
5564    if (! setupnodex(tr))                                            return 1;
5565
5566
5567    /* AxML modification start*/
5568
5569    if( ! setupEqualityVector(tr))                                    return 1;
5570
5571    /* initialize equality vectors */     
5572
5573
5574    /* AxML modification end*/
5575
5576#   if Slave
5577      if (! slaveTreeEvaluate(tr, bt))                               return 1;
5578#   else
5579      if (! initBestTree(bt, adef->nkeep, tr->mxtips, tr->cdta->endsite))    return 1;
5580      if (! adef->usertree) {
5581        if (! makeDenovoTree(tr, bt, adef))                          return 1;
5582        }
5583      else {
5584        if (! makeUserTree(tr, bt, adef))                            return 1;
5585        }
5586      if (! freeBestTree(bt))                                        return 1;
5587#   endif
5588
5589/*  Endpoint for jumble and/or boot loop */
5590
5591#   if Master
5592      tr->likelihood = 1.0;             /* terminate slaves */
5593      (void) sendTree(& comm_slave, tr);
5594#   endif
5595
5596    freeTree(tr);
5597
5598#   if Master
5599      close_link(& comm_slave);
5600      (void) fclose(INFILE);
5601
5602      REPORT_STEP_TIME;
5603      endtime = p4_clock();
5604      printf("Execution time %d milliseconds\n", endtime - inputtime);
5605      (void) fclose(OUTFILE);
5606#   endif
5607
5608#   if Slave
5609      close_link(& comm_master);
5610      (void) fclose(OUTFILE);
5611#   endif
5612
5613#   if Debug
5614      (void) fclose(debug);
5615#   endif
5616
5617#   if Master || Slave
5618      p4_send(DNAML_DONE, DNAML_HOST_ID, NULL, 0);
5619#   else
5620      return 0;
5621#   endif
5622  } /* DNA Maximum Likelihood */
Note: See TracBrowser for help on using the repository browser.