source: tags/initial/GDE/PHYLIP/contml.c

Last change on this file was 2, checked in by oldcode, 24 years ago

Initial revision

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 44.6 KB
Line 
1#include "phylip.h"
2
3/* version 3.56c. (c) Copyright 1993 by Joseph Felsenstein.
4   Written by Joseph Felsenstein, Akiko Fuseki, Sean Lamont, and Andrew Keeffe.
5   Permission is granted to copy and use this program provided no fee is
6   charged for it and provided that this copyright notice is not removed. */
7
8
9#define epsilon1        0.000001   /* small number */
10#define epsilon2        0.02   /* not such a small number */
11#define point           "."
12
13#define smoothings      4   /* number of passes through smoothing algorithm */
14#define namelength      10   /* number of characters max. in species name */
15#define maxtrees        10   /* maximum number of user trees in KHT test */
16
17#define ibmpc0          false
18#define ansi0           true
19#define vt520           false
20
21
22typedef double *phenotype;
23typedef Char naym[namelength];
24typedef short longer[6];
25
26typedef struct node {
27  struct node *next, *back;
28  boolean tip, iter;
29  short number;
30  phenotype view;
31  naym nayme;
32  double v, deltav, bigv, dist, xcoord;
33  short ycoord, ymin, ymax;
34} node;
35
36typedef struct tree {
37  node **nodep;
38  double likelihood;
39  node *start;
40} tree;
41
42
43Static FILE *infile, *outfile, *treefile;
44Static short numsp, numsp1, numsp2, loci, inseed, totalleles, df, outgrno,
45             col, datasets, ith, i, j, l, jumb, njumble=0;
46Static short *alleles, *locus;
47Static phenotype *x;
48Static naym *nayms;
49Static boolean all, contchars, global, jumble, lengths, outgropt, trout,
50               usertree, printdata, progress, treeprint, mulsets, ibmpc,
51               vt52, ansi, firstset;
52Static longer seed;
53Static short *enterorder;
54Static tree curtree, priortree, bestree, bestree2;
55short nextsp,numtrees,which,maxwhich; /* From maketree, propogated to global */
56boolean succeeded;
57double maxlogl;
58double l0gl[maxtrees];
59double *l0gf[maxtrees];
60Char ch;
61
62
63
64openfile(fp,filename,mode,application,perm)
65FILE **fp;
66char *filename;
67char *mode;
68char *application;
69char *perm;
70{
71  FILE *of;
72  char file[100];
73  strcpy(file,filename);
74  while (1){
75    of = fopen(file,mode);
76    if (of)
77      break;
78    else {
79      switch (*mode){
80      case 'r':
81        printf("%s:  can't read %s\n",application,file);
82        file[0] = '\0';
83        while (file[0] =='\0'){
84          printf("Please enter a new filename>");
85          gets(file);}
86        break;
87      case 'w':
88        printf("%s: can't write %s\n",application,file);
89        file[0] = '\0';
90        while (file[0] =='\0'){
91          printf("Please enter a new filename>");
92          gets(file);}
93        break;
94      }
95    }
96  }
97  *fp=of;
98  if (perm != NULL)
99    strcpy(perm,file);
100}
101
102double randum(seed)
103short *seed;
104{
105  /* random number generator -- slow but machine independent */
106  short i, j, k, sum;
107  longer mult, newseed;
108  double x;
109
110  mult[0] = 13;
111  mult[1] = 24;
112  mult[2] = 22;
113  mult[3] = 6;
114  for (i = 0; i <= 5; i++)
115    newseed[i] = 0;
116  for (i = 0; i <= 5; i++) {
117    sum = newseed[i];
118    k = i;
119    if (i > 3)
120      k = 3;
121    for (j = 0; j <= k; j++)
122      sum += mult[j] * seed[i - j];
123    newseed[i] = sum;
124    for (j = i; j <= 4; j++) {
125      newseed[j + 1] += newseed[j] / 64;
126      newseed[j] &= 63;
127    }
128  }
129  memcpy(seed, newseed, sizeof(longer));
130  seed[5] &= 3;
131  x = 0.0;
132  for (i = 0; i <= 5; i++)
133    x = x / 64.0 + seed[i];
134  x /= 4.0;
135  return x;
136}  /* randum */
137
138
139void uppercase(ch)
140Char *ch;
141{
142  /* convert a character to upper case -- either ASCII or EBCDIC */
143   *ch = (islower(*ch) ?  toupper(*ch) : (*ch));
144}  /* uppercase */
145
146
147void getnums()
148{
149  /* read species numbers and number of characters or loci */
150  fscanf(infile, "%hd%hd", &numsp, &loci);
151  fprintf(outfile, "\n%4hd Populations, %4hd Loci\n", numsp, loci);
152  numsp1 = numsp + 1;
153  numsp2 = numsp * 2 - 2;
154}  /* getnums */
155
156void getoptions()
157{
158  /* interactively set options */
159  short i, inseed0;
160  Char ch;
161  boolean done, done1;
162
163  fprintf(outfile, "\nContinuous character Maximum Likelihood");
164  fprintf(outfile, " method version %s\n\n",VERSION);
165  putchar('\n');
166  global = false;
167  jumble = false;
168  njumble = 1;
169  lengths = false;
170  outgrno = 1;
171  outgropt = false;
172  all = false;
173  contchars = false;
174  trout = true;
175  usertree = false;
176  printdata = false;
177  progress = true;
178  treeprint = true;
179  do {
180    printf(ansi ?  "\033[2J\033[H" :
181           vt52 ?  "\033E\033H"    : "\n");
182    printf("\nContinuous character Maximum Likelihood");
183    printf(" method version %s\n\n",VERSION);
184    printf("Settings for this run:\n");
185    printf("  U                       Search for best tree?  %s\n",
186           (usertree ? "No, use user trees in input" : "Yes"));
187    if (usertree) {
188      printf("  L                Use lengths from user trees?%s\n",
189             (lengths ? "  Yes" : "  No"));
190    }
191    printf("  C  Gene frequencies or continuous characters?  %s\n",
192           (contchars ? "Continuous characters" : "Gene frequencies"));
193    if (!contchars)
194      printf("  A   Input file has all alleles at each locus?  %s\n",
195             (all ? "Yes" : "No, one allele missing at each"));
196    printf("  O                              Outgroup root?  %s %hd\n",
197           (outgropt ? "Yes, at species number" :
198                       "No, use as outgroup species"),outgrno);
199    if (!usertree) {
200      printf("  G                      Global rearrangements?  %s\n",
201             (global ? "Yes" : "No"));
202      printf("  J           Randomize input order of species?");
203      if (jumble)
204        printf("  Yes (seed =%8hd,%3hd times)\n", inseed0, njumble);
205      else
206        printf("  No. Use input order\n");
207    }
208    printf("  M                 Analyze multiple data sets?");
209    if (mulsets)
210      printf("  Yes, %2hd sets\n", datasets);
211    else
212      printf("  No\n");
213    printf("  0         Terminal type (IBM PC, VT52, ANSI)?  %s\n",
214           ibmpc ? "IBM PC" :
215           ansi  ? "ANSI"   :
216           vt52  ? "VT52"   : "(none");
217    printf("  1          Print out the data at start of run  %s\n",
218           (printdata ? "Yes" : "No"));
219    printf("  2        Print indications of progress of run  %s\n",
220           (progress ? "Yes" : "No"));
221    printf("  3                              Print out tree  %s\n",
222           (treeprint ? "Yes" : "No"));
223    printf("  4             Write out trees onto tree file?  %s\n",
224           (trout ? "Yes" : "No"));
225    printf("\nAre these settings correct?");
226    printf(" (type Y or the letter for one to change)\n");
227    scanf("%c%*[^\n]", &ch);
228    getchar();
229    uppercase(&ch);
230    done = (ch == 'Y');
231    if (!done) {
232      if (strchr("JLOUGACM12340",ch) != NULL){
233
234        switch (ch) {
235        case 'A':
236          if (!contchars)
237            all = !all;
238          break;
239
240        case 'C':
241          contchars = !contchars;
242          break;
243
244        case 'G':
245          global = !global;
246          break;
247
248        case 'J':
249          jumble = !jumble;
250          if (jumble) {
251            do {
252              printf("Random number seed (must be odd)?\n");
253              scanf("%hd%*[^\n]", &inseed);
254              getchar();
255            } while (!(inseed & 1));
256            inseed0 = inseed;
257            for (i = 0; i <= 5; i++)
258              seed[i] = 0;
259            i = 0;
260            do {
261              seed[i] = inseed & 63;
262              inseed /= 64;
263              i++;
264            } while (inseed != 0);
265            printf("Number of times to jumble?\n");
266            scanf("%hd%*[^\n]", &njumble);
267            getchar();
268          }
269          else njumble = 1;
270          break;
271
272        case 'L':
273          lengths = !lengths;
274          break;
275
276        case 'O':
277          outgropt = !outgropt;
278          if (outgropt) {
279            done1 = true;
280            do {
281              printf("Type number of the outgroup:\n");
282              scanf("%hd%*[^\n]", &outgrno);
283              getchar();
284              done1 = (outgrno >= 1 || outgrno <= numsp);
285              if (!done1) {
286                printf("BAD OUTGROUP NUMBER: %4hd\n", outgrno);
287                printf("  Must be in range 1 -%2hd\n", numsp);
288              }
289            } while (done1 != true);
290          }
291          break;
292
293        case 'U':
294          usertree = !usertree;
295          break;
296
297        case 'M':
298          mulsets = !mulsets;
299          if (mulsets) {
300            done1 = false;
301            do {
302              printf("How many data sets?\n");
303              scanf("%hd%*[^\n]", &datasets);
304              getchar();
305              done1 = (datasets >= 1);
306              if (!done1)
307                printf("BAD DATA SETS NUMBER:  it must be greater than 1\n");
308            } while (done1 != true);
309          }
310          break;
311
312        case '0':
313          if (ibmpc) {
314            ibmpc = false;
315            vt52 = true;
316          } else {
317            if (vt52) {
318              vt52 = false;
319              ansi = true;
320            } else if (ansi)
321              ansi = false;
322            else
323              ibmpc = true;
324          }
325          break;
326
327        case '1':
328          printdata = !printdata;
329          break;
330
331        case '2':
332          progress = !progress;
333          break;
334
335        case '3':
336          treeprint = !treeprint;
337          break;
338
339        case '4':
340          trout = !trout;
341          break;
342        }
343      } else
344        printf("Not a possible option!\n");
345    }
346  } while (!done);
347}  /* getoptions */
348
349
350void doinit()
351{
352  /* initializes variables */
353  short i, j, k, n;
354  node *p, *q;
355
356  getnums();
357  getoptions();
358  curtree.nodep = (node **)Malloc(numsp2*sizeof(node *));
359  for (i = 0; i < numsp; i++)
360    curtree.nodep[i] = (node *)Malloc(sizeof(node));
361
362  n = 1;
363  if (!usertree) {
364    bestree.nodep = (node **)Malloc(numsp2*sizeof(node *));
365    for (i = 0; i < numsp; i++)
366      bestree.nodep[i] = (node *)Malloc(sizeof(node));
367      if (!bestree.nodep[i])
368    priortree.nodep = (node **)Malloc(numsp2*sizeof(node *));
369    for (i = 0; i < numsp; i++)
370      priortree.nodep[i] = (node *)Malloc(sizeof(node));
371    n = 3;
372    if (njumble > 1) {
373      bestree2.nodep = (node **)Malloc(numsp2*sizeof(node *));
374      for (i = 0; i < numsp; i++)
375        bestree2.nodep[i] = (node *)Malloc(sizeof(node));
376      n = 4;
377    }
378  }
379  for (k = 1; k <= n; k++) {
380    for (i = numsp1 - 1; i < numsp2; i++) {
381      q = NULL;
382      for (j = 1; j <= 3; j++) {
383        p = (node *)Malloc(sizeof(node));
384        p->next = q;
385        q = p;
386      }
387      p->next->next->next = p;
388      if (k == 1)
389        curtree.nodep[i] = p;
390      else if (n > 1) {
391        if (k == 2)
392          bestree.nodep[i] = p;
393        else if (k == 3)
394          priortree.nodep[i] = p;
395        else
396          bestree2.nodep[i] = p;
397      }
398    }
399  }
400  alleles = (short *)Malloc(loci*sizeof(short));
401  if (contchars)
402    locus = (short *)Malloc(loci*sizeof(short));
403}  /* doinit */
404
405void getalleles()
406{
407  /* set up number of alleles at loci */
408  short i, j, k, n, cursp, curloc;
409  node *p;
410
411  if (!firstset) {
412    if (eoln(infile)) {
413      fscanf(infile, "%*[^\n]");
414      getc(infile);
415    }
416    fscanf(infile, "%hd%hd", &cursp, &curloc);
417    if (cursp != numsp) {
418      printf("\nERROR: INCONSISTENT NUMBER OF SPECIES IN DATA SET %4hd\n", ith);
419      exit(-1);
420    }
421    loci = curloc;
422  }
423  if (contchars ) {
424    totalleles = loci;
425    for (i = 1; i <= loci; i++) {
426      locus[i - 1] = i;
427      alleles[i - 1] = 2;
428    }
429    df = loci;
430  } else {
431    totalleles = 0;
432    fscanf(infile, "%*[^\n]");
433    getc(infile);
434    if (printdata) {
435      fprintf(outfile, "\nNumbers of alleles at the loci:\n");
436      fprintf(outfile, "------- -- ------- -- --- -----\n\n");
437    }
438    for (i = 1; i <= loci; i++) {
439      if (eoln(infile)) {
440        fscanf(infile, "%*[^\n]");
441        getc(infile);
442      }
443      fscanf(infile, "%hd", &alleles[i - 1]);
444      if (alleles[i - 1] <= 0) {
445        printf("BAD NUMBER OF ALLELES: %4hd AT LOCUS %3hd\n", alleles[i - 1], i);
446        exit(-1);
447      }
448      totalleles += alleles[i - 1];
449      if (printdata)
450        fprintf(outfile, "%4hd", alleles[i - 1]);
451    }
452    locus = (short *)Malloc(totalleles*sizeof(short));
453    totalleles = 0;
454    for (i = 1; i <= loci; i++) {
455      for (j = totalleles; j < (totalleles + alleles[i - 1]); j++)
456        locus[j] = i;
457      totalleles += alleles[i - 1];
458    }
459    df = totalleles - loci;
460  }
461  for (i = 0; i < numsp; i++)
462    curtree.nodep[i]->view = (phenotype)Malloc(totalleles*sizeof(double));
463  n = 1;
464  if (!usertree) {
465    for (i = 0; i < numsp; i++)
466      bestree.nodep[i]->view = (phenotype)Malloc(totalleles*sizeof(double));
467    for (i = 0; i < numsp; i++)
468      priortree.nodep[i]->view = (phenotype)Malloc(totalleles*sizeof(double));
469    n = 3;
470    if (njumble > 1) {
471      for (i = 0; i < numsp; i++)
472        bestree2.nodep[i]->view = (phenotype)Malloc(totalleles*sizeof(double));
473      n = 4;
474    }
475  }
476  for (k = 1; k <= n; k++) {
477    for (i = numsp1 - 1; i < numsp2; i++) {
478      if (k == 1)
479        p = curtree.nodep[i];
480      else if (n > 1) {
481        if (k == 2)
482          p = bestree.nodep[i];
483        else if (k == 3)
484          p = priortree.nodep[i];
485        else
486          p = bestree2.nodep[i];
487        }
488      for (j = 1; j <= 3; j++) {
489        p->view = (phenotype)Malloc(totalleles*sizeof(double));
490        p = p->next;
491      }
492    }
493  }
494  for (i = 0; i < numsp; i++)
495    x[i] = (phenotype)Malloc(totalleles*sizeof(double));
496  if (usertree)
497    for (i = 0; i < maxtrees; i++)
498      l0gf[i] = (double *)Malloc(totalleles*sizeof(double));
499  if (printdata)
500    putc('\n', outfile);
501}  /* getalleles */
502
503void getdata()
504{
505  /* read species data */
506  short i, j, k, l, m, n, p;
507  double sum;
508
509  if (printdata) {
510    fprintf(outfile, "\nName");
511    if (contchars)
512      fprintf(outfile, "                       Phenotypes\n");
513    else
514      fprintf(outfile, "                 Gene Frequencies\n");
515    fprintf(outfile, "----");
516    if (contchars)
517      fprintf(outfile, "                       ----------\n");
518    else
519      fprintf(outfile, "                 ---- -----------\n");
520    putc('\n', outfile);
521    if (!contchars) {
522      for (j = 1; j <= namelength - 8; j++)
523        putc(' ', outfile);
524      fprintf(outfile, "locus:");
525      p = 1;
526      for (j = 1; j <= loci; j++) {
527        if (all)
528          n = alleles[j - 1];
529        else
530          n = alleles[j - 1] - 1;
531        for (k = 1; k <= n; k++) {
532          fprintf(outfile, "%10hd", j);
533          if (p % 6 == 0 && (all || p < df)) {
534            putc('\n', outfile);
535            for (l = 1; l <= namelength - 2; l++)
536              putc(' ', outfile);
537          }
538          p++;
539        }
540      }
541      fprintf(outfile, "\n\n");
542    }
543  }
544  for (i = 0; i < numsp; i++) {
545    if (true) {
546      fscanf(infile, "%*[^\n]");
547      getc(infile);
548      for (j = 0; j < namelength; j++) {
549        nayms[i][j] = getc(infile);
550        if ( eof(infile) || eoln(infile)){
551          printf("ERROR: END-OF-LINE OR END-OF-FILE IN");
552          printf(" THE MIDDLE OF A SPECIES NAME\n");
553          exit(-1);}
554        else if (printdata)
555          putc(nayms[i][j], outfile);
556      }
557      m = 1;
558      p = 1;
559      for (j = 1; j <= loci; j++) {
560        sum = 0.0;
561        if (contchars)
562          n = 1;
563        else if (all)
564          n = alleles[j - 1];
565        else
566          n = alleles[j - 1] - 1;
567        for (k = 1; k <= n; k++) {
568          if (eoln(infile)) {
569            fscanf(infile, "%*[^\n]");
570            getc(infile);
571          }
572          fscanf(infile, "%lf", &x[i][m - 1]);
573          sum += x[i][m - 1];
574          if (!contchars && x[i][m - 1] < 0.0) {
575            printf("\nLOCUS%3hd IN SPECIES%3hd: AN ALLELE", j, i + 1);
576            printf(" FREQUENCY IS NEGATIVE\n");
577            exit(-1);
578          }
579          if (printdata) {
580            fprintf(outfile, "%10.5f", x[i][m - 1]);
581            if (p % 6 == 0 && (all || p < df)) {
582              putc('\n', outfile);
583              for (l = 1; l <= namelength; l++)
584                putc(' ', outfile);
585            }
586          }
587          if (!contchars) {
588            if (x[i][m - 1] >= epsilon1)
589              x[i][m - 1] = sqrt(x[i][m - 1]);
590          }
591          p++;
592          m++;
593        }
594        if (all && fabs(sum - 1.0) > epsilon2) {
595          printf("\nLOCUS%3hd IN SPECIES%3hd: FREQUENCIES DO NOT ADD UP TO 1\n",
596                   j, i + 1);
597          exit(-1);
598          }
599        if (!all && !contchars) {
600          x[i][m - 1] = 1.0 - sum;
601          if (x[i][m - 1] >= epsilon1)
602            x[i][m - 1] = sqrt(x[i][m - 1]);
603          if (x[i][m - 1] < 0.0) {
604            if (x[i][m - 1] > -epsilon2) {
605              for (l = 0; l <= m - 2; l++)
606                x[i][l] /= sqrt(sum);
607              x[i][m - 1] = 0.0;
608            } else {
609              printf("\n LOCUS%3hd IN SPECIES%3hd: ");
610              printf("FREQUENCIES ADD UP TO MORE THAN 1\n",j, i + 1);
611              exit(-1);
612            }
613          }
614          m++;
615        }
616      }
617      if (printdata)
618        putc('\n', outfile);
619    }
620  }
621  fscanf(infile, "%*[^\n]");
622  getc(infile);
623  if (printdata)
624    putc('\n', outfile);
625}  /* getdata */
626
627
628void getinput()
629{
630  /* reads the input data */
631  getalleles();
632  getdata();
633}  /* getinput */
634
635
636#define down            2
637#define over            60
638
639
640void setuptree(a)
641tree *a;
642{
643  /* initialize a tree */
644  short i, j;
645  node *p;
646  for (i = 1; i <= numsp; i++) {
647    a->nodep[i - 1]->tip = true;
648    a->nodep[i - 1]->iter = true;
649    a->nodep[i - 1]->number = i;
650  }
651  for (i = numsp1; i <= numsp2; i++) {
652    p = a->nodep[i - 1];
653    for (j = 1; j <= 3; j++) {
654      p->tip = false;
655      p->iter = true;
656      p->number = i;
657      p = p->next;
658    }
659  }
660  a->likelihood = -99999.0;
661  a->start = a->nodep[0];
662}  /* setuptree */
663
664void hookup(p, q)
665node *p, *q;
666{
667  /* hook together two nodes */
668  p->back = q;
669  q->back = p;
670}  /* hookup */
671
672
673void sumlikely(p, q, sum)
674node *p, *q;
675double *sum;
676{
677  /* sum contribution to likelihood over forks in tree */
678  short i;
679  double term, sumsq, vee;
680  double TEMP;
681
682  if (!p->tip)
683    sumlikely(p->next->back, p->next->next->back, sum);
684  if (!q->tip)
685    sumlikely(q->next->back, q->next->next->back, sum);
686  if (p->back == q)
687    vee = p->v;
688  else
689    vee = p->v + q->v;
690  vee += p->deltav + q->deltav;
691  if (vee <= 1.0e-10) {
692    printf("ERROR: CHECK FOR TWO IDENTICAL  SPECIES ");
693    printf("AND ELIMINATE ONE FROM THE DATA\n");
694    exit(-1);
695  }
696  sumsq = 0.0;
697  if (usertree && which <= maxtrees) {
698    for (i = 0; i < loci; i++)
699      l0gf[which - 1]
700        [i] += (1 - alleles[i]) * log(vee) / 2.0;
701  }
702  for (i = 0; i < totalleles; i++) {
703    TEMP = p->view[i] - q->view[i];
704    term = TEMP * TEMP;
705    if (usertree && which <= maxtrees)
706      l0gf[which - 1]
707        [locus[i] - 1] -= term / (2.0 * vee);
708    sumsq += term;
709  }
710  (*sum) += df * log(vee) / -2.0 - sumsq / (2.0 * vee);
711}  /* sumlikely */
712
713double evaluate(t)
714tree *t;
715{
716  /* evaluate likelihood of a tree */
717  short i;
718  double sum;
719
720  sum = 0.0;
721  if (usertree && which <= maxtrees) {
722    for (i = 0; i < loci; i++)
723      l0gf[which - 1][i] = 0.0;
724  }
725  sumlikely(t->start, t->start->back, &sum);
726  if (usertree) {
727    l0gl[which - 1] = sum;
728    if (which == 1) {
729      maxwhich = 1;
730      maxlogl = sum;
731    } else if (sum > maxlogl) {
732      maxwhich = which;
733      maxlogl = sum;
734    }
735  }
736  t->likelihood = sum;
737  return sum;
738}  /* evaluate */
739
740/* Local variables for update: */
741
742double distance(p, q)
743node *p, *q;
744{
745  /* distance between two nodes */
746  short i;
747  double sum;
748  double TEMP;
749
750  sum = 0.0;
751  for (i = 0; i < totalleles; i++) {
752    TEMP = p->view[i] - q->view[i];
753    sum += TEMP * TEMP;
754  }
755  return sum;
756}  /* distance */
757
758void makedists(p)
759node *p;
760{
761  short i;
762  node *q;
763  /* compute distances among three neighbors of a node */
764
765
766  for (i = 1; i <= 3; i++) {
767    q = p->next;
768    p->dist = distance(p->back, q->back);
769    p = q;
770  }
771}  /* makedists */
772
773void makebigv(p,negatives)
774node *p;
775boolean *negatives;
776{
777  /* make new branch length */
778  short i;
779  node *temp, *q, *r;
780
781  q = p->next;
782  r = q->next;
783  *negatives = false;
784  for (i = 1; i <= 3; i++) {
785    p->bigv = p->v + p->back->deltav;
786    if (p->iter) {
787      p->bigv = (p->dist + r->dist - q->dist) / (df * 2);
788      p->back->bigv = p->bigv;
789      if (p->bigv < p->back->deltav)
790        *negatives = true;
791    }
792    temp = p;
793    p = q;
794    q = r;
795    r = temp;
796  }
797}  /* makebigv */
798
799void correctv(p)
800node *p;
801{
802  /* iterate branch lengths if some are to be zero */
803  node *q, *r, *temp;
804  short i, j;
805  double f1, f2, vtot;
806
807  q = p->next;
808  r = q->next;
809  for (i = 1; i <= smoothings; i++) {
810    for (j = 1; j <= 3; j++) {
811      vtot = q->bigv + r->bigv;
812      if (vtot > 0.0)
813        f1 = q->bigv / vtot;
814      else
815        f1 = 0.5;
816      f2 = 1.0 - f1;
817      p->bigv = (f1 * r->dist + f2 * p->dist - f1 * f2 * q->dist) / df;
818      p->bigv -= vtot * f1 * f2;
819      if (p->bigv < p->back->deltav)
820        p->bigv = p->back->deltav;
821      p->back->bigv = p->bigv;
822      temp = p;
823      p = q;
824      q = r;
825      r = temp;
826    }
827  }
828}  /* correctv */
829
830void littlev(p)
831node *p;
832{
833  /* remove part of it that belongs to other branches */
834  short i;
835
836  for (i = 1; i <= 3; i++) {
837    if (p->iter)
838      p->v = p->bigv - p->back->deltav;
839    if (p->back->iter)
840      p->back->v = p->v;
841    p = p->next;
842  }
843}  /* littlev */
844
845void nuview(p)
846node *p;
847{
848  /* renew information about subtrees */
849  short i, j;
850  node *q, *r, *a, *b, *temp;
851  double v1, v2, vtot, f1, f2;
852
853  q = p->next;
854  r = q->next;
855  for (i = 1; i <= 3; i++) {
856    a = q->back;
857    b = r->back;
858    v1 = q->bigv;
859    v2 = r->bigv;
860    vtot = v1 + v2;
861    if (vtot > 0.0)
862      f1 = v2 / vtot;
863    else
864      f1 = 0.5;
865    f2 = 1.0 - f1;
866    for (j = 0; j <totalleles; j++)
867      p->view[j] = f1 * a->view[j] + f2 * b->view[j];
868    p->deltav = v1 * f1;
869    temp = p;
870    p = q;
871    q = r;
872    r = temp;
873  }
874}  /* nuview */
875
876void update(p)
877node *p;
878{
879  /* update branch lengths around a node */
880  boolean negatives;
881
882  if (p->tip)
883    return;
884  makedists(p);
885  makebigv(p,&negatives);
886  if (negatives)
887    correctv(p);
888  littlev(p);
889  nuview(p);
890}  /* update */
891
892void smooth(p)
893node *p;
894{
895  /* go through tree getting new branch lengths and views */
896  if (p->tip)
897    return;
898  update(p);
899  smooth(p->next->back);
900  smooth(p->next->next->back);
901}  /* smooth */
902
903void insert_(p, q)
904node *p, *q;
905{
906  /* put p and q together and iterate info. on resulting tree */
907  short i;
908
909  hookup(p->next->next, q->back);
910  hookup(p->next, q);
911  for (i = 1; i <= smoothings; i++) {
912    smooth(p);
913    smooth(p->back);
914  }
915}  /* insert */
916
917void copynode(c, d)
918node *c, *d;
919{
920  /* make a copy of a node */
921  memcpy(d->nayme, c->nayme, sizeof(naym));
922  memcpy(d->view, c->view, totalleles*sizeof(double));
923  d->v = c->v;
924  d->iter = c->iter;
925  d->deltav = c->deltav;
926  d->bigv = c->bigv;
927  d->dist = c->dist;
928  d->xcoord = c->xcoord;
929  d->ycoord = c->ycoord;
930  d->ymin = c->ymin;
931  d->ymax = c->ymax;
932}  /* copynode */
933
934void copy_(a, b)
935tree *a, *b;
936{
937  /* make a copy of a tree */
938  short i, j=0;
939  node *p, *q;
940
941  for (i = 0; i < numsp; i++) {
942    copynode(a->nodep[i], b->nodep[i]);
943    if (a->nodep[i]->back) {
944      if (a->nodep[i]->back == a->nodep[a->nodep[i]->back->number - 1])
945        b->nodep[i]->back = b->nodep[a->nodep[i]->back->number - 1];
946      else if (a->nodep[i]->back == a->nodep[a->nodep[i]->back->number - 1]->next)
947        b->nodep[i]->back = b->nodep[a->nodep[i]->back->number - 1]->next;
948      else
949        b->nodep[i]->back = b->nodep[a->nodep[i]->back->number - 1]->next->next;
950    }
951    else b->nodep[i]->back = NULL;
952  }
953  for (i = numsp; i < numsp2; i++) {
954    p = a->nodep[i];
955    q = b->nodep[i];
956    for (j = 1; j <= 3; j++) {
957      copynode(p, q);
958      if (p->back) {
959        if (p->back == a->nodep[p->back->number - 1])
960          q->back = b->nodep[p->back->number - 1];
961        else if (p->back == a->nodep[p->back->number - 1]->next)
962          q->back = b->nodep[p->back->number - 1]->next;
963        else
964          q->back = b->nodep[p->back->number - 1]->next->next;
965      }
966      else
967        q->back = NULL;
968      p = p->next;
969      q = q->next;
970    }
971  }
972  b->likelihood = a->likelihood;
973  b->start = a->start;
974}  /* copy */
975
976void setuptip(m, t)
977short m;
978tree *t;
979{
980  /* initialize branch lengths and views in a tip */
981  node *tmp;
982
983  tmp = t->nodep[m - 1];
984  memcpy(tmp->view, x[m - 1], totalleles*sizeof(double));
985  memcpy(tmp->nayme, nayms[m - 1], sizeof(naym));
986  tmp->deltav = 0.0;
987  tmp->v = 0.0;
988}  /* setuptip */
989
990void buildnewtip(m, t,nextsp)
991short m;
992tree *t;
993short nextsp;
994{
995  /* initialize and hook up a new tip */
996  node *p;
997
998  setuptip(m, t);
999  p = t->nodep[nextsp + numsp - 3];
1000  hookup(t->nodep[m - 1], p);
1001}  /* buildnewtip */
1002
1003void buildsimpletree(t)
1004tree *t;
1005{
1006  /* make and initialize a three-species tree */
1007  setuptip(enterorder[0], t);
1008  setuptip(enterorder[1], t);
1009  hookup(t->nodep[enterorder[0] - 1], t->nodep[enterorder[1] - 1]);
1010  buildnewtip(enterorder[2], t, nextsp);
1011  insert_(t->nodep[enterorder[2] - 1]->back, t->nodep[enterorder[0] - 1]);
1012}  /* buildsimpletree */
1013
1014void addtraverse(p, q, contin)
1015node *p, *q;
1016boolean contin;
1017{
1018  /* traverse through a tree, finding best place to add p */
1019  insert_(p, q);
1020  numtrees++;
1021  if (evaluate(&curtree) > bestree.likelihood)
1022    copy_(&curtree, &bestree);
1023  copy_(&priortree, &curtree);
1024  if (!q->tip && contin) {
1025    addtraverse(p, q->next->back, contin);
1026    addtraverse(p, q->next->next->back, contin);
1027  }
1028}  /* addtraverse */
1029
1030
1031void re_move(p, q)
1032node **p, **q;
1033{
1034  /* remove p and record in q where it was */
1035  *q = (*p)->next->back;
1036  hookup(*q, (*p)->next->next->back);
1037  (*p)->next->back = NULL;
1038  (*p)->next->next->back = NULL;
1039  update(*q);
1040  update((*q)->back);
1041}  /* re_move */
1042
1043void rearrange(p)
1044node *p;
1045{
1046  /* rearranges the tree, globally or locally */
1047  node *q, *r;
1048
1049  if (!p->tip && !p->back->tip) {
1050    r = p->next->next;
1051    re_move(&r, &q );
1052    copy_(&curtree, &priortree);
1053    addtraverse(r, q->next->back, global && nextsp == numsp);
1054    addtraverse(r, q->next->next->back, global && nextsp == numsp);
1055    copy_(&bestree, &curtree);
1056    if (global && nextsp == numsp && progress)
1057      putchar('.');
1058    if (global && nextsp == numsp && !succeeded) {
1059      if (r->back->tip) {
1060        r = r->next->next;
1061        re_move(&r, &q );
1062        q = q->back;
1063        copy_(&curtree, &priortree);
1064        if (!q->tip) {
1065          addtraverse(r, q->next->back, true);
1066          addtraverse(r, q->next->next->back, true);
1067        }
1068        q = q->back;
1069        if (!q->tip) {
1070          addtraverse(r, q->next->back, true);
1071          addtraverse(r, q->next->next->back, true);
1072        }
1073        copy_(&bestree, &curtree);
1074      }
1075    }
1076  }
1077  if (!p->tip) {
1078    rearrange(p->next->back);
1079    rearrange(p->next->next->back);
1080  }
1081}  /* rearrange */
1082
1083
1084void coordinates(p, lengthsum, tipy,tipmax)
1085node *p;
1086double lengthsum;
1087short *tipy;
1088double *tipmax;
1089{
1090  /* establishes coordinates of nodes */
1091  node *q, *first, *last;
1092
1093  if (p->tip) {
1094    p->xcoord = lengthsum;
1095    p->ycoord = *tipy;
1096    p->ymin = *tipy;
1097    p->ymax = *tipy;
1098    (*tipy) += down;
1099    if (lengthsum > (*tipmax))
1100      (*tipmax) = lengthsum;
1101    return;
1102  }
1103  q = p->next;
1104  do {
1105    coordinates(q->back, lengthsum + q->v, tipy,tipmax);
1106    q = q->next;
1107  } while ((p == curtree.start->back || p != q) &&
1108           (p != curtree.start->back || p->next != q));
1109  first = p->next->back;
1110  q = p;
1111  while (q->next != p)
1112    q = q->next;
1113  last = q->back;
1114  p->xcoord = lengthsum;
1115  if (p == curtree.start->back)
1116    p->ycoord = p->next->next->back->ycoord;
1117  else
1118    p->ycoord = (first->ycoord + last->ycoord) / 2;
1119  p->ymin = first->ymin;
1120  p->ymax = last->ymax;
1121}  /* coordinates */
1122
1123void drawline(i, scale)
1124short i;
1125double scale;
1126{
1127  /* draws one row of the tree diagram by moving up tree */
1128  node *p, *q;
1129  short n, j;
1130  boolean extra;
1131  node *r, *first, *last;
1132  boolean done;
1133
1134  p = curtree.start->back;
1135  q = curtree.start->back;
1136  extra = false;
1137  if (i == p->ycoord && p == curtree.start->back) {
1138    if (p->number - numsp >= 10)
1139      fprintf(outfile, "-%2hd", p->number - numsp);
1140    else
1141      fprintf(outfile, "--%hd", p->number - numsp);
1142    extra = true;
1143  } else
1144    fprintf(outfile, "  ");
1145  do {
1146    if (!p->tip) {
1147      r = p->next;
1148      done = false;
1149      do {
1150        if (i >= r->back->ymin && i <= r->back->ymax) {
1151          q = r->back;
1152          done = true;
1153        }
1154        r = r->next;
1155      } while (!(done || (p != curtree.start->back && r == p) ||
1156                 (p == curtree.start->back && r == p->next)));
1157      first = p->next->back;
1158      r = p;
1159      while (r->next != p)
1160        r = r->next;
1161      last = r->back;
1162      if (p == curtree.start->back)
1163        last = p->back;
1164    }
1165    done = (p->tip || p == q);
1166    n = (long)(scale * (q->xcoord - p->xcoord) + 0.5);
1167    if (n < 3 && !q->tip)
1168      n = 3;
1169    if (extra) {
1170      n--;
1171      extra = false;
1172    }
1173    if (q->ycoord == i && !done) {
1174      if (p->ycoord != q->ycoord)
1175        putc('+', outfile);
1176      else
1177        putc('-', outfile);
1178      if (!q->tip) {
1179        for (j = 1; j <= n - 2; j++)
1180          putc('-', outfile);
1181        if (q->number - numsp >= 10)
1182          fprintf(outfile, "%2hd", q->number - numsp);
1183        else
1184          fprintf(outfile, "-%hd", q->number - numsp);
1185        extra = true;
1186      } else {
1187        for (j = 1; j < n; j++)
1188          putc('-', outfile);
1189      }
1190    } else if (!p->tip) {
1191      if (last->ycoord > i && first->ycoord < i && i != p->ycoord) {
1192        putc('!', outfile);
1193        for (j = 1; j < n; j++)
1194          putc(' ', outfile);
1195      } else {
1196        for (j = 1; j <= n; j++)
1197          putc(' ', outfile);
1198      }
1199    } else {
1200      for (j = 1; j <= n; j++)
1201        putc(' ', outfile);
1202    }
1203    if (q != p)
1204      p = q;
1205  } while (!done);
1206  if (p->ycoord == i && p->tip) {
1207    for (j = 0; j < namelength; j++)
1208      putc(p->nayme[j], outfile);
1209  }
1210  putc('\n', outfile);
1211}  /* drawline */
1212
1213void printree()
1214{
1215  /* prints out diagram of the tree */
1216  short i;
1217  short tipy;
1218  double tipmax,scale;
1219
1220  if (!treeprint)
1221    return;
1222  putc('\n', outfile);
1223  tipy = 1;
1224  tipmax = 0.0;
1225  coordinates(curtree.start->back, 0.0, &tipy,&tipmax);
1226  scale = over / (tipmax + 0.0001);
1227  for (i = 1; i <= (tipy - down); i++)
1228    drawline(i,scale);
1229  putc('\n', outfile);
1230}  /* printree */
1231
1232#undef down
1233#undef over
1234
1235void treeout(p)
1236node *p;
1237{
1238  /* write out file with representation of final tree */
1239  short i, n, w;
1240  Char c;
1241  double x;
1242
1243  if (p->tip) {
1244    n = 0;
1245    for (i = 1; i <= namelength; i++) {
1246      if (p->nayme[i - 1] != ' ')
1247        n = i;
1248    }
1249    for (i = 0; i < n; i++) {
1250      c = p->nayme[i];
1251      if (c == ' ')
1252        c = '_';
1253      putc(c, treefile);
1254    }
1255    col += n;
1256  } else {
1257    putc('(', treefile);
1258    col++;
1259    treeout(p->next->back);
1260    putc(',', treefile);
1261    col++;
1262    if (col > 55) {
1263      putc('\n', treefile);
1264      col = 0;
1265    }
1266    treeout(p->next->next->back);
1267    if (p == curtree.start->back) {
1268      putc(',', treefile);
1269      col++;
1270      if (col > 45) {
1271        putc('\n', treefile);
1272        col = 0;
1273      }
1274      treeout(p->back);
1275    }
1276    putc(')', treefile);
1277    col++;
1278  }
1279  x = p->v;
1280  if (x > 0.0)
1281    w = (long)(0.43429448222 * log(x));
1282  else if (x == 0.0)
1283    w = 0;
1284  else
1285    w = (long)(0.43429448222 * log(-x)) + 1;
1286  if (w < 0)
1287    w = 0;
1288  if (p == curtree.start->back)
1289    fprintf(treefile, ";\n");
1290  else {
1291    fprintf(treefile, ":%*.5f", w + 7, x);
1292    col += w + 8;
1293  }
1294}  /* treeout */
1295
1296/* Local variables for summarize: */
1297
1298void describe(p, chilow,chihigh)
1299node *p;
1300double chilow,chihigh;
1301{
1302  /* print out information for one branch */
1303  short i;
1304  node *q;
1305  double bigv, delta;
1306
1307  q = p->back;
1308  fprintf(outfile, "%3hd       ", q->number - numsp);
1309  if (p->tip) {
1310    for (i = 0; i < namelength; i++)
1311      putc(p->nayme[i], outfile);
1312  } else
1313    fprintf(outfile, "%4hd      ", p->number - numsp);
1314  fprintf(outfile, "%15.5f", q->v);
1315  delta = p->deltav + p->back->deltav;
1316  bigv = p->v + delta;
1317  if (p->iter)
1318     fprintf(outfile, "   (%12.5f,%12.5f)",
1319             chilow * bigv - delta, chihigh * bigv - delta);
1320  fprintf(outfile, "\n");
1321  if (!p->tip) {
1322    describe(p->next->back, chilow,chihigh);
1323    describe(p->next->next->back, chilow,chihigh);
1324  }
1325}  /* describe */
1326
1327void summarize(numtrees)
1328short numtrees;
1329{
1330  /* print out branch lengths etc. */
1331  double chilow,chihigh;
1332
1333  fprintf(outfile, "\nremember: ");
1334  if (outgropt)
1335    fprintf(outfile, "(although rooted by outgroup) ");
1336  fprintf(outfile, "this is an unrooted tree!\n\n");
1337  fprintf(outfile, "Ln Likelihood = %11.5f\n", curtree.likelihood);
1338  if (!usertree)
1339    fprintf(outfile, "\nexamined %4hd trees\n", numtrees);
1340  if (df == 1) {
1341    chilow = 0.000982;
1342    chihigh = 5.02389;
1343  } else if (df == 2) {
1344    chilow = 0.05064;
1345    chihigh = 7.3777;
1346  } else {
1347    chilow = 1.0 - 2.0 / (df * 9);
1348    chihigh = chilow;
1349    chilow -= 1.95996 * sqrt(2.0 / (df * 9));
1350    chihigh += 1.95996 * sqrt(2.0 / (df * 9));
1351    chilow *= chilow * chilow;
1352    chihigh *= chihigh * chihigh;
1353  }
1354  fprintf(outfile, "\nBetween     And             Length");
1355  fprintf(outfile, "      Approx. Confidence Limits\n");
1356  fprintf(outfile, "-------     ---             ------");
1357  fprintf(outfile, "      ------- ---------- ------\n");
1358  describe(curtree.start->back->next->back, chilow,chihigh);
1359  describe(curtree.start->back->next->next->back, chilow,chihigh);
1360  describe(curtree.start, chilow,chihigh);
1361  fprintf(outfile, "\n\n");
1362  if (trout) {
1363    col = 0;
1364    treeout(curtree.start->back);
1365  }
1366}  /* summarize */
1367
1368void getch(c)
1369Char *c;
1370{
1371  /* get next nonblank character */
1372  do {
1373    if (eoln(infile)) {
1374      fscanf(infile, "%*[^\n]");
1375      getc(infile);
1376    }
1377    *c = getc(infile);
1378    if (*c == '\n')
1379      *c = ' ';
1380  } while (*c == ' ');
1381}  /* getch */
1382
1383void findch(c, lparens,rparens)
1384Char c;
1385short *lparens,*rparens;
1386{
1387  /* skip forward in user tree until find character c */
1388  boolean done;
1389
1390  done = false;
1391  while (!done) {
1392    if (c == ',') {
1393      if (ch == '(' || ch == ')' || ch == ':' || ch == ';') {
1394        printf("\nERROR IN USER TREE: ");
1395        printf("UNMATCHED PARENTHESIS OR MISSING COMMA\n");
1396        printf(" OR NON-TRIFURCATED BASE\n");
1397        exit(-1);
1398      } else if (ch == ',')
1399        done = true;
1400    } else if (c == ')') {
1401      if (ch == '(' || ch == ',' || ch == ':' || ch == ';') {
1402        printf("\nERROR IN USER TREE: UNMATCHED PARENTHESIS OR NON-BIFURCATED NODE\n");
1403        exit(-1);
1404      } else if (ch == ')') {
1405        (*rparens)++;
1406        if ((*lparens) > 0 && (*lparens) == (*rparens)) {
1407          if ((*lparens) == numsp - 2) {
1408            if (eoln(infile)) {
1409              fscanf(infile, "%*[^\n]");
1410              getc(infile);
1411            }
1412            ch = getc(infile);
1413            if (ch != ';') {
1414              printf( "\nERROR IN USER TREE: ");
1415              printf("UNMATCHED PARENTHESIS OR MISSING SEMICOLON\n");
1416              exit(-1);
1417            }
1418          }
1419        }
1420        done = true;
1421      }
1422    }
1423    if ((done && ch == ')') || (!done)) {
1424      if (eoln(infile)) {
1425        fscanf(infile, "%*[^\n]");
1426        getc(infile);
1427      }
1428      ch = getc(infile);
1429    }
1430  }
1431}  /* findch */
1432
1433void processlength(p)
1434node *p;
1435{
1436  long digit, ordzero;
1437  double valyew, divisor;
1438  boolean pointread;
1439
1440  ordzero = '0';
1441  pointread = false;
1442  valyew = 0.0;
1443  divisor = 1.0;
1444  getch(&ch);
1445  digit = ch - ordzero;
1446  while (((unsigned long)digit <= 9) | ch == '.'){
1447    if (ch == '.')
1448      pointread = true;
1449    else {
1450      valyew = valyew * 10.0 + digit;
1451      if (pointread)
1452        divisor *= 10.0;
1453    }
1454    getch(&ch);
1455    digit = ch - ordzero;
1456}
1457  if (lengths) {
1458    p->v = valyew / divisor;
1459    p->back->v = p->v;
1460    p->iter = false;
1461    p->back->iter = false;
1462  }
1463}  /* processlength */
1464
1465#undef point   /*   ??? Why is this necessary */
1466
1467void addelement(p, lparens,rparens,nextnode,names,nolengths)
1468node *p;
1469short *lparens,*rparens,*nextnode;
1470boolean *names, *nolengths;
1471{
1472  /* add one node to the user tree */
1473  node *q;
1474  short i, n;
1475  boolean found;
1476  Char str[namelength];
1477
1478  do {
1479    if (eoln(infile)) {
1480      fscanf(infile, "%*[^\n]");
1481      getc(infile);
1482    }
1483    ch = getc(infile);
1484  } while (ch == ' ');
1485 if (ch == '(') {
1486    (*lparens)++;
1487    if ((*lparens) > numsp - 2) {
1488      printf("\nERROR IN USER TREE: TOO MANY LEFT PARENTHESES\n");
1489      exit(-1);
1490    }
1491    (*nextnode)++;
1492    q = curtree.nodep[(*nextnode) - 1];
1493    hookup(p, q);
1494    addelement(q->next,lparens,rparens,nextnode,names,nolengths);
1495    findch(',', lparens,rparens);
1496    addelement(q->next->next, lparens,rparens,nextnode,names,nolengths);
1497    findch(')', lparens,rparens);
1498  }
1499  else {
1500    for (i = 0; i < namelength; i++)
1501      str[i] = ' ';
1502    n = 1;
1503    do {
1504      if (ch == '_')
1505        ch = ' ';
1506      str[n - 1] = ch;
1507      if (eoln(infile)) {
1508        fscanf(infile, "%*[^\n]");
1509        getc(infile);
1510      }
1511      ch = getc(infile);
1512      n++;
1513    } while (ch != ':' && ch != ',' && ch != ')' &&
1514             n <= namelength);
1515    n = 1;
1516    do {
1517      found = true;
1518      for (i = 0; i < namelength; i++)
1519        found = (found && str[i] == nayms[n - 1][i]);
1520      if (found) {
1521        if (names[n - 1] == false)
1522          names[n - 1] = true;
1523        else {
1524          printf("\nERROR IN USER TREE: DUPLICATE NAME FOUND -- ");
1525          for (i = 0; i < namelength; i++)
1526            putchar(curtree.nodep[n - 1]->nayme[i]);
1527          putchar('\n');
1528          exit(-1);
1529        }
1530      } else
1531        n++;
1532    } while (!(n > numsp || found));
1533    if (n > numsp) {
1534      printf("CANNOT FIND SPECIES: ");
1535      for (i = 0; i < namelength; i++)
1536        putchar(str[i]);
1537      putchar('\n');
1538    }
1539    hookup(curtree.nodep[n - 1], p);
1540    if (curtree.start->number > n)
1541      curtree.start = curtree.nodep[n - 1];
1542  }
1543  if (ch == ':') {
1544    processlength(p);
1545    *nolengths = false;
1546  }
1547}  /* addelement */
1548
1549void treeread()
1550{
1551  /* read in a user tree */
1552  node *p;
1553  short i;
1554  short nextnode=0,lparens=0,rparens=0;
1555  boolean *names, nolengths;
1556
1557  curtree.start = curtree.nodep[numsp - 1];
1558  do {
1559    ch = getc(infile);
1560  } while (ch == ' ');
1561  if (ch != '(')
1562    return;
1563  names = (boolean *)Malloc(numsp*sizeof(boolean));
1564  for (i = 0; i < numsp; i++)
1565    names[i] = false;
1566  lparens = 1;
1567  rparens = 0;
1568  nolengths = true;
1569  nextnode = numsp + 1;
1570  p = curtree.nodep[nextnode - 1];
1571  for (i = 1; i <= 2; i++) {
1572    addelement(p, &(lparens),&(rparens),&(nextnode),names,&nolengths);
1573    p = p->next;
1574    findch(',', &(lparens),&(rparens));
1575  }
1576  addelement(p, &lparens,&rparens,&nextnode,names,&nolengths);
1577  if (nolengths && lengths)
1578    printf("\nNO LENGTHS FOUND IN INPUT FILE WITH LENGTH OPTION CHOSEN\n");
1579  findch(')', &lparens,&rparens);
1580  fscanf(infile, "%*[^\n]");
1581  getc(infile);
1582  free(names);
1583}  /* treeread */
1584
1585void nodeinit(p)
1586node *p;
1587{
1588  /* initialize a node */
1589  node *q, *r;
1590  short i;
1591
1592  if (p->tip)
1593    return;
1594  q = p->next->back;
1595  r = p->next->next->back;
1596  nodeinit(q);
1597  nodeinit(r);
1598  for (i = 0; i < totalleles; i++)
1599    p->view[i] = 0.5 * q->view[i] + 0.5 * r->view[i];
1600  if (p->iter)
1601    p->v = 0.1;
1602  if (p->back->iter)
1603    p->back->v = 0.1;
1604}  /* nodeinit */
1605
1606void initrav(p)
1607node *p;
1608{
1609  /* traverse to initialize */
1610  if (p->tip)
1611    nodeinit(p->back);
1612  else {
1613    initrav(p->next->back);
1614    initrav(p->next->next->back);
1615  }
1616}  /* initrav */
1617
1618void treevaluate()
1619{
1620  /* evaluate user-defined tree, iterating branch lengths */
1621  short i;
1622  double dummy;
1623
1624  initrav(curtree.start);
1625  initrav(curtree.start->back);
1626  for (i = 1; i <= smoothings * 4; i++)
1627    smooth(curtree.start->back);
1628  dummy = evaluate(&curtree);
1629}  /* treevaluate */
1630
1631
1632void maketree()
1633{
1634  /* construct the tree */
1635  short i, j, k, n, num;
1636  double sum, sum2, sd;
1637  double TEMP;
1638  node *p;
1639
1640  if (usertree) {
1641    fscanf(infile, "%hd%*[^\n]", &numtrees);
1642    getc(infile);
1643    if (treeprint) {
1644      fprintf(outfile, "User-defined tree");
1645      if (numtrees > 1)
1646        putc('s', outfile);
1647      putc('\n', outfile);
1648    }
1649    setuptree(&curtree);
1650    for (which = 1; which <= numsp; which++)
1651      setuptip(which, &curtree);
1652    which = 1;
1653    while (which <= numtrees) {
1654      treeread();
1655      curtree.start = curtree.nodep[outgrno - 1];
1656      treevaluate();
1657      printree();
1658      summarize(numtrees);
1659      which++;
1660    }
1661    if (numtrees > 1 && loci > 1 ) {
1662      fprintf(outfile, "Tree    Ln L      Diff Ln L     Its S.D.");
1663      fprintf(outfile, "   Significantly worse?\n\n");
1664      num = (numtrees > maxtrees) ? maxtrees : numtrees;
1665      for (i = 1; i <= num; i++) {
1666        fprintf(outfile, "%3hd%12.5f", i, l0gl[i - 1]);
1667        if (maxwhich == i)
1668          fprintf(outfile, "  <------ best\n");
1669        else {
1670          sum = 0.0;
1671          sum2 = 0.0;
1672          for (j = 0; j < loci; j++) {
1673            sum += l0gf[maxwhich - 1][j] - l0gf[i - 1][j];
1674            TEMP = l0gf[maxwhich - 1][j] - l0gf[i - 1][j];
1675            sum2 += TEMP * TEMP;
1676          }
1677          sd = sqrt(loci / (loci - 1.0) * (sum2 - sum * sum / loci));
1678          fprintf(outfile, "%12.5f%12.4f", l0gl[i - 1] - maxlogl, sd);
1679          if (sum > 1.95996 * sd)
1680            fprintf(outfile, "           Yes\n");
1681          else
1682            fprintf(outfile, "            No\n");
1683        }
1684      }
1685      fprintf(outfile, "\n\n");
1686    }
1687  } else {
1688    if (jumb == 1) {
1689      setuptree(&curtree);
1690      setuptree(&priortree);
1691      setuptree(&bestree);
1692      if (njumble > 1) setuptree(&bestree2);
1693    }
1694    for (i = 1; i <= numsp; i++)
1695      enterorder[i - 1] = i;
1696    if (jumble) {
1697      for (i = 0; i < numsp; i++) {
1698        j = (long)(randum(seed) * numsp) + 1;
1699        k = enterorder[j - 1];
1700        enterorder[j - 1] = enterorder[i];
1701        enterorder[i] = k;
1702      }
1703    }
1704    nextsp = 3;
1705    buildsimpletree(&curtree);
1706    curtree.start = curtree.nodep[enterorder[0] - 1];
1707    if (jumb == 1) numtrees = 1;
1708    nextsp = 4;
1709    if (progress) {
1710      printf("\nAdding species:\n");
1711      printf("   ");
1712      for (i = 0; i < namelength; i++)
1713        putchar(nayms[enterorder[0] - 1][i]);
1714      printf("\n   ");
1715      for (i = 0; i < namelength; i++)
1716        putchar(nayms[enterorder[1] - 1][i]);
1717      printf("\n   ");
1718      for (i = 0; i < namelength; i++)
1719        putchar(nayms[enterorder[2] - 1][i]);
1720      putchar('\n');
1721    }
1722    while (nextsp <= numsp) {
1723      buildnewtip(enterorder[nextsp - 1], &curtree, nextsp);
1724      copy_(&curtree, &priortree);
1725      bestree.likelihood = -99999.0;
1726      addtraverse(curtree.nodep[enterorder[nextsp - 1] - 1]->back,
1727                  curtree.start->back, true );
1728      copy_(&bestree, &curtree);
1729      if (progress) {
1730        printf("   ");
1731        for (j = 0; j < namelength; j++)
1732          putchar(nayms[enterorder[nextsp - 1] - 1][j]);
1733        putchar('\n');
1734      }
1735      if (global && nextsp == numsp) {
1736        if (progress) {
1737          printf("\nDoing global rearrangements\n");
1738          printf("  !");
1739          for (i = 1; i <= numsp - 2; i++)
1740            putchar('-');
1741          printf("!\n");
1742          printf("   ");
1743        }
1744      }
1745      succeeded = true;
1746      while (succeeded) {
1747        succeeded = false;
1748        rearrange(curtree.start->back);
1749        if (global && nextsp == numsp)
1750          putc('\n', outfile);
1751      }
1752      if (njumble > 1) {
1753        if (jumb == 1 && nextsp == numsp)
1754          copy_(&bestree, &bestree2);
1755        else if (nextsp == numsp) {
1756          if (bestree2.likelihood < bestree.likelihood)
1757            copy_(&bestree, &bestree2);
1758        }
1759      }
1760      if (nextsp == numsp && jumb == njumble) {
1761        if (njumble > 1) copy_(&bestree2, &curtree);
1762        curtree.start = curtree.nodep[outgrno - 1];
1763        printree();
1764        summarize(numtrees);
1765      }
1766      nextsp++;
1767    }
1768  }
1769  if ( jumb < njumble)
1770    return;
1771  if (progress) {
1772    printf("\n\nOutput written to output file\n\n");
1773    if (trout)
1774      printf("Tree also written onto file\n\n");
1775  }
1776  for (i = 0; i < numsp; i++)
1777    free(curtree.nodep[i]->view);
1778  n = 1;
1779  if (!usertree) {
1780    for (i = 0; i < numsp; i++)
1781      free(bestree.nodep[i]->view);
1782    for (i = 0; i < numsp; i++)
1783      free(priortree.nodep[i]->view);
1784    n = 3;
1785  }
1786  for (k = 1; k <= n; k++) {
1787    for (i = numsp1 - 1; i < numsp2; i++) {
1788      if (k == 1)
1789        p = curtree.nodep[i];
1790      else if (n > 1) {
1791        if (k == 2)
1792          p = bestree.nodep[i];
1793        else
1794          p = priortree.nodep[i];
1795        }
1796      for (j = 1; j <= 3; j++) {
1797        free(p->view);
1798        p = p->next;
1799      }
1800    }
1801  }
1802  for (i = 0; i < numsp; i++)
1803    free(x[i]);
1804  if (!contchars)
1805    free(locus);
1806  if (usertree)
1807    for (i = 0; i < maxtrees; i++)
1808      free(l0gf[i]);
1809}  /* maketree */
1810
1811
1812main(argc, argv)
1813int argc;
1814Char *argv[];
1815{  /* main program */
1816  char infilename[100],outfilename[100],trfilename[100];
1817#ifdef MAC
1818  macsetup("Contml","");
1819#endif
1820  openfile(&infile,INFILE,"r",argv[0],infilename);
1821  openfile(&outfile,OUTFILE,"w",argv[0],outfilename);
1822  ibmpc = ibmpc0;
1823  ansi = ansi0;
1824  vt52 = vt520;
1825  mulsets = false;
1826  firstset = true;
1827  datasets = 1;
1828  doinit();
1829  if (trout)
1830    openfile(&treefile,TREEFILE,"w",argv[0],trfilename);
1831  x = (phenotype *)Malloc(numsp*sizeof(phenotype));
1832  nayms = (naym *)Malloc(numsp*sizeof(naym));
1833  enterorder = (short *)Malloc(numsp*sizeof(short));
1834  for (ith = 1; ith <= datasets; ith++) {
1835    getinput();
1836    if (ith == 1)
1837      firstset = false;
1838    if (datasets > 1) {
1839      fprintf(outfile, "Data set # %hd:\n\n", ith);
1840      if (progress)
1841        printf("\nData set # %hd:\n", ith);
1842    }
1843    for (jumb = 1; jumb <= njumble; jumb++)
1844      maketree();
1845  }
1846  FClose(outfile);
1847  FClose(treefile);
1848  FClose(infile);
1849#ifdef MAC
1850  fixmacfile(outfilename);
1851  fixmacfile(trfilename);
1852#endif
1853  exit(0);
1854}
1855
1856
1857int eof(f)
1858FILE *f;
1859{
1860    register int ch;
1861
1862    if (feof(f))
1863        return 1;
1864    if (f == stdin)
1865        return 0;
1866    ch = getc(f);
1867    if (ch == EOF)
1868        return 1;
1869    ungetc(ch, f);
1870    return 0;
1871}
1872
1873
1874int eoln(f)
1875FILE *f;
1876{
1877    register int ch;
1878
1879    ch = getc(f);
1880    if (ch == EOF)
1881        return 1;
1882    ungetc(ch, f);
1883    return (ch == '\n');
1884}
1885
1886void memerror()
1887{
1888printf("Error allocating memory\n");
1889exit(-1);
1890}
1891
1892MALLOCRETURN *mymalloc(x)
1893long x;
1894{
1895MALLOCRETURN *mem;
1896mem = (MALLOCRETURN *)calloc(1,x);
1897if (!mem)
1898  memerror();
1899else
1900  return (MALLOCRETURN *)mem;
1901}
Note: See TracBrowser for help on using the repository browser.