Debian Codegraph @

csrc/phylip.c

raw symbols SCIP
1
2 /* version 3.696.
3 Written by Joseph Felsenstein, Akiko Fuseki, Sean Lamont, Andrew Keeffe,
4 and Dan Fineman.
5
6 Copyright (c) 1993-2014, Joseph Felsenstein
7 All rights reserved.
8
9 Redistribution and use in source and binary forms, with or without
10 modification, are permitted provided that the following conditions are met:
11
12 1. Redistributions of source code must retain the above copyright notice,
13 this list of conditions and the following disclaimer.
14
15 2. Redistributions in binary form must reproduce the above copyright notice,
16 this list of conditions and the following disclaimer in the documentation
17 and/or other materials provided with the distribution.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include <stdio.h>
33 #include <signal.h>
34 extern double next_random(void);
35
36 #include "phylip.h"
37
38 #ifdef _WIN32
39 #include <windows.h>
40 /* for console code (clear screen, text color settings) */
41 CONSOLE_SCREEN_BUFFER_INFO savecsbi;
42 boolean savecsbi_valid = false;
43 HANDLE hConsoleOutput;
44
45 void phyClearScreen();
46 void phySaveConsoleAttributes();
47 void phySetConsoleAttributes();
48 void phyRestoreConsoleAttributes();
49 void phyFillScreenColor();
50 #endif /* _WIN32 */
51
52 #ifndef OLDC
53 static void crash_handler(int signum);
54
55 #endif
56 /*
57 #if defined(OSX_CARBON) && defined(__MWERKS__)
58 boolean fixedpath = false;
59 #endif
60 */
61 FILE *outfile, *infile, *intree, *intree2, *outtree, *weightfile, *catfile, *ancfile, *mixfile, *factfile;
62 long spp, words, bits;
63 boolean ibmpc, ansi, tranvsp;
64 //naym *nayme; /* names of species */
65 char **nayme; /* names of species */
66
67 static void crash_handler(int sig_num)
68 { /* when we crash, lets print out something usefull */
69 printf("ERROR: ");
70 switch(sig_num) {
71 #ifdef SIGSEGV
72 case SIGSEGV:
73 puts("This program has caused a Segmentation fault.");
74 break;
75 #endif /* SIGSEGV */
76 #ifdef SIGFPE
77 case SIGFPE:
78 puts("This program has caused a Floating Point Exception");
79 break;
80 #endif /* SIGFPE */
81 #ifdef SIGILL
82 case SIGILL:
83 puts("This program has attempted an illegal instruction");
84 break;
85 #endif /* SIGILL */
86 #ifdef SIGPIPE
87 case SIGPIPE:
88 puts("This program tried to write to a broken pipe");
89 break;
90 #endif /* SIGPIPE */
91 #ifdef SIGBUS
92 case SIGBUS:
93 puts("This program had a bus error");
94 break;
95 #endif /* SIGBUS */
96 }
97 if (sig_num == SIGSEGV) {
98 puts(
99 " This may have been caused by an incorrectly formatted input file");
100 puts(
101 " or input tree file. You should check those files carefully.");
102 puts(" If this seems to be a bug, please mail [email protected]");
103 }
104 else {
105 puts(" Most likely, you have encountered a bug in the program.");
106 puts(" Since this seems to be a bug, please mail [email protected]");
107 }
108 puts(" with the name of the program, your computer system type,");
109 puts(" a full description of the problem, and with the input data file.");
110 puts(" (which should be in the body of the message, not as an Attachment).");
111
112 #ifdef _WIN32
113 phyRestoreConsoleAttributes();
114 #endif
115 abort();
116 }
117
118
119 void init(int argc, char** argv)
120 { /* initialization routine for all programs
121 * anything done at the beginning for every program should be done here */
122
123 /* set up signal handler for
124 * segfault, floating point exception, illeagal instruction, bad pipe, bus error
125 * there are more signals that can cause a crash, but these are the most common
126 * even these aren't found on all machines. */
127 #ifdef SIGSEGV
128 signal(SIGSEGV, crash_handler);
129 #endif /* SIGSEGV */
130 #ifdef SIGFPE
131 signal(SIGFPE, crash_handler);
132 #endif /* SIGFPE */
133 #ifdef SIGILL
134 signal(SIGILL, crash_handler);
135 #endif /* SIGILL */
136 #ifdef SIGPIPE
137 signal(SIGPIPE, crash_handler);
138 #endif /* SIGPIPE */
139 #ifdef SIGBUS
140 signal(SIGBUS, crash_handler);
141 #endif /* SIGBUS */
142
143 /* Set default terminal characteristics */
144 ibmpc = IBMCRT;
145 ansi = ANSICRT;
146 //javarun = false;
147
148 /* Clear the screen */
149 cleerhome();
150
151 #ifdef _WIN32
152 /* Perform DOS console configuration */
153 phySetConsoleAttributes();
154 phyClearScreen();
155 #endif /* _WIN32 */
156
157 }
158
159 void scan_eoln(FILE *f)
160 { /* Eat everything up to EOF or newline, including newline */
161 char ch;
162 while (!eoff(f) && !eoln(f))
163 gettc(f);
164 if (!eoff(f))
165 ch = gettc(f);
166 }
167
168
169 boolean eoff(FILE *f)
170 { /* Return true iff next getc() is EOF */
171 int ch;
172 if (feof(f))
173 return true;
174 ch = getc(f);
175 if (ch == EOF) {
176 ungetc(ch, f);
177 return true;
178 }
179 ungetc(ch, f);
180 return false;
181 } /*eoff*/
182
183
184 boolean eoln(FILE *f)
185 { /* Return true iff next getc() is EOL or EOF */
186 register int ch;
187 ch = getc(f);
188 if (ch == EOF)
189 return true;
190 ungetc(ch, f);
191 return ((ch == '\n') || (ch == '\r'));
192 } /*eoln*/
193
194
195 int filexists(char *filename)
196 { /* Return true iff file already exists */
197 FILE *fp;
198 fp = fopen(filename,"r");
199 if (fp) {
200 fclose(fp);
201 return 1;
202 } else
203 return 0;
204 } /*filexists*/
205
206
207 const char* get_command_name (const char *vektor)
208 { /* returns the name of the program from vektor without the whole path */
209 char *last_slash;
210
211 /* Point to the last slash... */
212 last_slash = strrchr (vektor, DELIMITER);
213
214 if (last_slash)
215 /* If there was a last slash, return the character after it */
216 return last_slash + 1;
217 else
218 /* If not, return the vector */
219 return vektor;
220
221 } /* get_command_name */
222
223
224 void EOF_error()
225 { /* Print a message and exit when EOF is reached prematurely. */
226 puts("\n\nERROR: Unexpected end-of-file.\n");
227 exxit(-1);
228 } /* EOF_error */
229
230
231 void getstryng(char *fname)
232 { /* read in a file name from stdin and take off newline if any */
233 char *end;
234
235 fflush(stdout);
236 fname = fgets(fname, FNMLNGTH, stdin);
237 if ( fname == NULL )
238 EOF_error();
239
240 if ( (end = strpbrk(fname, "\n\r")) != NULL)
241 *end = '\0';
242
243 } /* getstryng */
244
245
246 void countup(long *loopcount, long maxcount)
247 { /* count how many times this loop has tried to read data, bail out
248 if exceeds maxcount */
249
250 (*loopcount)++;
251 if ((*loopcount) >= maxcount) {
252 printf("\nERROR: Made %ld attempts to read input in loop. Aborting run.\n",
253 *loopcount);
254 exxit(-1);
255 }
256 } /* countup */
257
258
259 void openfile(FILE **fp,const char *filename,const char *filedesc,
260 const char *mode,const char *application, char *perm)
261 { /* open a file, testing whether it exists etc. */
262 FILE *of;
263 char file[FNMLNGTH];
264 char filemode[3];
265 char input[FNMLNGTH];
266 char ch;
267 const char *progname_without_path;
268 long loopcount, loopcount2;
269 /*
270 #if defined(OSX_CARBON) && defined(__MWERKS__)
271 ProcessSerialNumber myProcess;
272 FSRef bundleLocation;
273 unsigned char bundlePath[FNMLNGTH];
274
275 if(!fixedpath){
276 // change path to the bundle location instead of root directory
277 GetCurrentProcess(&myProcess);
278 GetProcessBundleLocation(&myProcess, &bundleLocation);
279 FSRefMakePath(&bundleLocation, bundlePath, FNMLNGTH);
280 chdir((const char*)bundlePath);
281 chdir(".."); // get out of the .app directory
282
283 fixedpath = true;
284 }
285 #endif
286 */
287 progname_without_path = get_command_name(application);
288
289 strcpy(file, filename);
290 strcpy(filemode, mode);
291 loopcount = 0;
292 while (1){
293 #if ! OVERWRITE_FILES
294 if (filemode[0] == 'w' && filexists(file)){
295 printf("\n%s: the file \"%s\" that you wanted to\n",
296 progname_without_path, file);
297 printf(" use as %s already exists.\n", filedesc);
298 printf(" Do you want to Replace it, Append to it,\n");
299 printf(" write to a new File, or Quit?\n");
300 loopcount2 = 0;
301 do {
302 printf(" (please type R, A, F, or Q) \n");
303 #ifdef _WIN32
304 phyFillScreenColor();
305 #endif
306 fflush(stdout);
307 if ( fgets(input, sizeof(input), stdin) == NULL )
308 EOF_error();
309 ch = input[0];
310 uppercase(&ch);
311 countup(&loopcount2, 10);
312 } while (ch != 'A' && ch != 'R' && ch != 'F' && ch != 'Q');
313 if (ch == 'Q')
314 exxit(-1);
315 if (ch == 'A') {
316 strcpy(filemode,"a");
317 continue;
318 }
319 else if (ch == 'F') {
320 file[0] = '\0';
321 loopcount2 = 0;
322 while (file[0] =='\0') {
323 printf("Please enter a new file name> ");
324 fflush(stdout);
325 getstryng(file);
326 countup(&loopcount2, 10);
327 }
328 strcpy(filemode,"w");
329 continue;
330 }
331 }
332 #endif /* ! OVERWRITE_FILES */
333 of = fopen(file,filemode);
334 if (of)
335 break;
336 else {
337 switch (filemode[0]){
338
339 case 'r':
340 printf("%s: can't find %s \"%s\"\n", progname_without_path,
341 filedesc, file);
342 file[0] = '\0';
343 loopcount2 = 0;
344 while ( file[0] =='\0' ) {
345 printf("Please enter a new file name> ");
346 fflush(stdout);
347 countup(&loopcount2, 10);
348 getstryng(file);
349 }
350 break;
351
352 case 'w':
353 case 'a':
354 printf("%s: can't write %s \"%s\"\n", progname_without_path,
355 filedesc, file);
356 file[0] = '\0';
357 loopcount2 = 0;
358 while (file[0] =='\0') {
359 printf("Please enter a new file name> ");
360 fflush(stdout);
361 countup(&loopcount2, 10);
362 getstryng(file);
363 }
364 continue;
365
366 default:
367 printf("There is some error in the call of openfile. Unknown mode.\n");
368 exxit(-1);
369 }
370 }
371 countup(&loopcount, 20);
372 }
373 *fp = of;
374 if (perm != NULL)
375 strcpy(perm,file);
376 } /* openfile */
377
378
379 void cleerhome()
380 { /* home cursor and clear screen, if possible */
381 #ifdef _WIN32
382 if(ibmpc || ansi){
383 phyClearScreen();
384 } else {
385 printf("\n\n");
386 }
387 #else
388 printf("%s", ((ibmpc || ansi) ? ("\033[2J\033[H") : "\n\n"));
389 #endif
390 } /* cleerhome */
391
392
393 double randum(longer seed)
394 { /* random number generator -- slow but machine independent
395 This is a multiplicative congruential 32-bit generator
396 x(t+1) = 1664525 * x(t) mod 2^32, one that passes the
397 Coveyou-Macpherson and Lehmer tests, see Knuth ACP vol. 2
398 We here implement it representing each integer in base-64
399 notation -- i.e. as an array of 6 six-bit chunks */
400
401 long i, j, k, sum;
402 longer mult, newseed;
403 double x;
404
405 mult[0] = 13; /* these four statements set the multiplier */
406 mult[1] = 24; /* -- they are its "digits" in a base-64 */
407 mult[2] = 22; /* notation: 1664525 = 6*64^3+22*64^2 */
408 mult[3] = 6; /* +24*64+13 */
409 for (i = 0; i <= 5; i++)
410 newseed[i] = 0;
411 for (i = 0; i <= 5; i++) { /* do the multiplication piecewise */
412 sum = newseed[i];
413 k = i;
414 if (i > 3)
415 k = 3;
416 for (j = 0; j <= k; j++)
417 sum += mult[j] * seed[i - j];
418 newseed[i] = sum;
419 for (j = i; j <= 4; j++) {
420 newseed[j + 1] += newseed[j] / 64;
421 newseed[j] &= 63;
422 }
423 }
424 memcpy(seed, newseed, sizeof(longer)); /* new seed replaces old one */
425 seed[5] &= 3; /* from the new seed, get a floating point fraction */
426 x = 0.0;
427 for (i = 0; i <= 5; i++)
428 x = x / 64.0 + seed[i];
429 x /= 4.0;
430 return x;
431 } /* randum */
432
433
434 void randumize(longer seed, long *enterorder)
435 { /* randomize input order of species -- randomly permute array enterorder */
436 long i, j, k;
437
438 for (i = 0; i < spp; i++) {
439 //j = (long)(randum(seed) * (i+1));
440 j = (long)(next_random() * (i+1));
441 k = enterorder[j];
442 enterorder[j] = enterorder[i];
443 enterorder[i] = k;
444 }
445 } /* randumize */
446
447
448 double normrand(longer seed)
449 {/* standardized Normal random variate */
450 double x;
451 x = randum(seed)+randum(seed)+randum(seed)+randum(seed)
452 + randum(seed)+randum(seed)+randum(seed)+randum(seed)
453 + randum(seed)+randum(seed)+randum(seed)+randum(seed)-6.0;
454 return(x);
455 } /* normrand */
456
457
458 long readlong(const char *prompt)
459 { /* read a long */
460 long res, loopcount;
461 char string[FNMLNGTH];
462
463 loopcount = 0;
464 do {
465 printf("%s", prompt);
466 fflush(stdout);
467 getstryng(string);
468 if (sscanf(string,"%ld",&res) == 1)
469 break;
470 countup(&loopcount, 10);
471 } while (1);
472 return res;
473 } /* readlong */
474
475
476 void uppercase(Char *ch)
477 { /* convert ch to upper case */
478 *ch = (islower (*ch) ? toupper(*ch) : (*ch));
479 } /* uppercase */
480
481
482 void initseed(long *inseed, long *inseed0, longer seed)
483 { /* input random number seed */
484 long i, loopcount;
485
486 assert(inseed);
487 assert(inseed0);
488 loopcount = 0;
489 for (;;) {
490 printf("\nRandom number seed (must be odd)?\n");
491 fflush(stdout);
492 if (scanf("%ld%*[^\n]", inseed) == 1) {
493 getchar();
494 if (*inseed > 0 && (*inseed & 0x1))
495 break;
496 }
497 countup(&loopcount, 10);
498 }
499 *inseed0 = *inseed;
500 for (i = 0; i <= 5; i++)
501 seed[i] = 0;
502 i = 0;
503 do {
504 seed[i] = *inseed & 63;
505 *inseed /= 64;
506 i++;
507 } while (*inseed != 0);
508 } /*initseed*/
509
510
511 void initjumble(long *inseed, long *inseed0, longer seed, long *njumble)
512 { /* input number of jumblings for jumble option */
513 long loopcount;
514 initseed(inseed, inseed0, seed);
515 loopcount = 0;
516 for (;;) {
517 printf("Number of times to jumble?\n");
518 fflush(stdout);
519 if (scanf("%ld%*[^\n]", njumble) == 1) {
520 getchar();
521 if (*njumble >= 1)
522 break;
523 }
524 countup(&loopcount, 10);
525 }
526 } /*initjumble*/
527
528
529 void initoutgroup(long *outgrno, long spp)
530 { /* input outgroup number */
531 long loopcount;
532
533 loopcount = 0;
534 for (;;) {
535 printf("Type number of the outgroup:\n");
536 fflush(stdout);
537 if (scanf("%ld%*[^\n]", outgrno) == 1) {
538 getchar();
539 if (*outgrno >= 1 && *outgrno <= spp)
540 break;
541 else {
542 printf("BAD OUTGROUP NUMBER: %ld\n", *outgrno);
543 printf(" Must be in range 1 - %ld\n", spp);
544 }
545 }
546 countup(&loopcount, 10);
547 }
548 } /*initoutgroup*/
549
550
551 void initthreshold(double *threshold)
552 { /* input threshold for threshold parsimony option */
553 long loopcount;
554
555 loopcount = 0;
556 for (;;) {
557 printf("What will be the threshold value?\n");
558 fflush(stdout);
559 if (scanf("%lf%*[^\n]", threshold) == 1) {
560 getchar();
561 if (*threshold >= 1.0)
562 break;
563 else
564 printf("BAD THRESHOLD VALUE: it must be greater than 1\n");
565 }
566 countup(&loopcount, 10);
567 }
568 *threshold = (long)(*threshold * 10.0 + 0.5) / 10.0;
569 } /*initthreshold*/
570
571
572 void initcatn(long *categs)
573 { /* initialize category number for rate categories */
574 long loopcount;
575
576 loopcount = 0;
577 *categs = 0;
578 for (;;) {
579 printf("Number of categories (1-%d)?\n", maxcategs);
580 fflush(stdout);
581 if (scanf("%ld%*[^\n]", categs) == 1) {
582 getchar();
583 if (*categs > maxcategs || *categs < 1)
584 continue;
585 else
586 break;
587 }
588 countup(&loopcount, 10);
589 }
590 } /*initcatn*/
591
592
593 void initcategs(long categs, double *rate)
594 { /* initialize category rates for HMM rates */
595 long i, loopcount, scanned;
596 char line[FNMLNGTH], rest[100];
597 boolean done;
598
599 loopcount = 0;
600 for (;;){
601 printf("Rate for each category? (use a space to separate)\n");
602 fflush(stdout);
603 getstryng(line);
604 done = true;
605 for (i = 0; i < categs; i++){
606 scanned = sscanf(line,"%lf %[^\n]", &rate[i], rest);
607 if ((scanned < 2 && i < (categs - 1))
608 || (scanned < 1 && i == (categs - 1)))
609 {
610 printf("Please enter exactly %ld values.\n", categs);
611 done = false;
612 break;
613 }
614 strcpy(line, rest);
615 }
616 if (done)
617 break;
618 countup(&loopcount, 100);
619 }
620 } /*initcategs*/
621
622
623 void initprobcat(long categs, double *probsum, double *probcat)
624 { /* input probabilities of rate categores for HMM rates */
625 long i, loopcount, scanned;
626 boolean done;
627 char line[FNMLNGTH], rest[100];
628
629 loopcount = 0;
630 do {
631 printf("Probability for each category?");
632 printf(" (use a space to separate)\n");
633 fflush(stdout);
634 getstryng(line);
635 done = true;
636 for (i = 0; i < categs; i++) {
637 scanned = sscanf(line, "%lf %[^\n]", &probcat[i], rest);
638 if ((scanned < 2 && i < (categs - 1)) ||
639 (scanned < 1 && i == (categs - 1))) {
640 done = false;
641 printf("Please enter exactly %ld values.\n", categs);
642 break;
643 }
644 strcpy(line, rest);
645 }
646 if (!done)
647 continue;
648 *probsum = 0.0;
649 for (i = 0; i < categs; i++)
650 *probsum += probcat[i];
651 if (fabs(1.0 - (*probsum)) > 0.001) {
652 done = false;
653 printf("Probabilities must add up to");
654 printf(" 1.0, plus or minus 0.001.\n");
655 }
656 countup(&loopcount, 100);
657 } while (!done);
658 } /*initprobcat*/
659
660
661 void lgr(long m, double b, raterootarray lgroot)
662 { /* For use by initgammacat. Get roots of m-th Generalized Laguerre
663 polynomial, given roots of (m-1)-th, these are to be
664 stored in lgroot[m][] */
665 long i;
666 double upper, lower, x, y;
667 boolean dwn; /* is function declining in this interval? */
668
669 if (m == 1) {
670 lgroot[1][1] = 1.0+b;
671 } else {
672 dwn = true;
673 for (i=1; i<=m; i++) {
674 if (i < m) {
675 if (i == 1)
676 lower = 0.0;
677 else
678 lower = lgroot[m-1][i-1];
679 upper = lgroot[m-1][i];
680 } else { /* i == m, must search above */
681 lower = lgroot[m-1][i-1];
682 x = lgroot[m-1][m-1];
683 do {
684 x = 2.0*x;
685 y = glaguerre(m, b, x);
686 } while ((dwn && (y > 0.0)) || ((!dwn) && (y < 0.0)));
687 upper = x;
688 }
689 while (upper-lower > 0.000000001) {
690 x = (upper+lower)/2.0;
691 if (glaguerre(m, b, x) > 0.0) {
692 if (dwn)
693 lower = x;
694 else
695 upper = x;
696 } else {
697 if (dwn)
698 upper = x;
699 else
700 lower = x;
701 }
702 }
703 lgroot[m][i] = (lower+upper)/2.0;
704 dwn = !dwn; /* switch for next one */
705 }
706 }
707 } /* lgr */
708
709
710 double logfac (long n)
711 { /* log(n!) values were calculated with Mathematica
712 with a precision of 30 digits */
713 long i;
714 double x;
715
716 switch (n)
717 {
718 case 0:
719 return 0.;
720 case 1:
721 return 0.;
722 case 2:
723 return 0.693147180559945309417232121458;
724 case 3:
725 return 1.791759469228055000812477358381;
726 case 4:
727 return 3.1780538303479456196469416013;
728 case 5:
729 return 4.78749174278204599424770093452;
730 case 6:
731 return 6.5792512120101009950601782929;
732 case 7:
733 return 8.52516136106541430016553103635;
734 case 8:
735 return 10.60460290274525022841722740072;
736 case 9:
737 return 12.80182748008146961120771787457;
738 case 10:
739 return 15.10441257307551529522570932925;
740 case 11:
741 return 17.50230784587388583928765290722;
742 case 12:
743 return 19.98721449566188614951736238706;
744 default:
745 x = 19.98721449566188614951736238706;
746 for (i = 13; i <= n; i++)
747 x += log(i);
748 return x;
749 }
750 } /* logfac */
751
752
753 double glaguerre(long m, double b, double x)
754 { /* Generalized Laguerre polynomial computed recursively.
755 For use by initgammacat */
756 long i;
757 double gln, glnm1, glnp1; /* L_n, L_(n-1), L_(n+1) */
758
759 if (m == 0)
760 return 1.0;
761 else {
762 if (m == 1)
763 return 1.0 + b - x;
764 else {
765 gln = 1.0+b-x;
766 glnm1 = 1.0;
767 for (i=2; i <= m; i++) {
768 glnp1 = ((2*(i-1)+b+1.0-x)*gln - (i-1+b)*glnm1)/i;
769 glnm1 = gln;
770 gln = glnp1;
771 }
772 return gln;
773 }
774 }
775 } /* glaguerre */
776
777
778 void initlaguerrecat(long categs, double alpha, double *rate, double *probcat)
779 { /* calculate rates and probabilities to approximate Gamma distribution
780 of rates with "categs" categories and shape parameter "alpha" using
781 rates and weights from Generalized Laguerre quadrature */
782 long i;
783 raterootarray lgroot; /* roots of GLaguerre polynomials */
784 double f, x, xi, y;
785
786 alpha = alpha - 1.0;
787 lgroot[1][1] = 1.0+alpha;
788 for (i = 2; i <= categs; i++)
789 lgr(i, alpha, lgroot); /* get roots for L^(a)_n */
790 /* here get weights */
791 /* Gamma weights are (1+a)(1+a/2) ... (1+a/n)*x_i/((n+1)^2 [L_{n+1}^a(x_i)]^2) */
792 f = 1;
793 for (i = 1; i <= categs; i++)
794 f *= (1.0+alpha/i);
795 for (i = 1; i <= categs; i++) {
796 xi = lgroot[categs][i];
797 y = glaguerre(categs+1, alpha, xi);
798 x = f*xi/((categs+1)*(categs+1)*y*y);
799 rate[i-1] = xi/(1.0+alpha);
800 probcat[i-1] = x;
801 }
802 } /* initlaguerrecat */
803
804
805 double hermite(long n, double x)
806 { /* calculates hermite polynomial with degree n and parameter x */
807 /* seems to be unprecise for n>13 -> root finder does not converge*/
808 double h1 = 1.;
809 double h2 = 2. * x;
810 double xx = 2. * x;
811 long i;
812
813 for (i = 1; i < n; i++) {
814 xx = 2. * x * h2 - 2. * (i) * h1;
815 h1 = h2;
816 h2 = xx;
817 }
818 return xx;
819 } /* hermite */
820
821
822 void root_hermite(long n, double *hroot)
823 { /* find roots of Hermite polynmials */
824 long z;
825 long ii;
826 long start;
827
828 if (n % 2 == 0) {
829 start = n/2;
830 z = 1;
831 } else {
832 start = n/2 + 1;
833 z=2;
834 hroot[start-1] = 0.0;
835 }
836 for (ii = start; ii < n; ii++) { /* search only upwards*/
837 hroot[ii] = halfroot(hermite, n, hroot[ii-1]+EPSILON, 1./n);
838 hroot[start - z] = -hroot[ii];
839 z++;
840 }
841 } /* root_hermite */
842
843
844 double halfroot(double (*func)(long m, double x), long n, double startx,
845 double delta)
846 { /* searches from the bound (startx) only in one direction
847 (by positive or negative delta, which results in
848 other-bound=startx+delta)
849 delta should be small.
850 (*func) is a function with two arguments */
851 double xl;
852 double xu;
853 double xm = 0;
854 double fu;
855 double fl;
856 double fm = 100000.;
857 double gradient;
858 boolean dwn = false;
859
860 /* decide if we search above or below startx and escapes to trace back
861 to the starting point that most often will be
862 the root from the previous calculation */
863 if (delta < 0) {
864 xu = startx;
865 xl = xu + delta;
866 } else {
867 xl = startx;
868 xu = xl + delta;
869 }
870 delta = fabs(delta);
871 fu = (*func)(n, xu);
872 fl = (*func)(n, xl);
873 gradient = (fl-fu)/(xl-xu);
874 while(fabs(fm) > EPSILON) { /* is root outside of our bracket?*/
875 if ((fu<0.0 && fl<0.0) || (fu>0.0 && fl > 0.0)) {
876 xu += delta;
877 fu = (*func)(n, xu);
878 fl = (*func)(n, xl);
879 gradient = (fl-fu)/(xl-xu);
880 dwn = (gradient < 0.0) ? true : false;
881 } else {
882 xm = xl - fl / gradient;
883 fm = (*func)(n, xm);
884 if (dwn) {
885 if (fm > 0.) {
886 xl = xm;
887 fl = fm;
888 } else {
889 xu = xm;
890 fu = fm;
891 }
892 } else {
893 if (fm > 0.) {
894 xu = xm;
895 fu = fm;
896 } else {
897 xl = xm;
898 fl = fm;
899 }
900 }
901 gradient = (fl-fu)/(xl-xu);
902 }
903 }
904 return xm;
905 } /* halfroot */
906
907
908 void hermite_weight(long n, double * hroot, double * weights)
909 {
910 /* calculate the weights for the hermite polynomial at the roots
911 using formula from Abramowitz and Stegun chapter 25.4.46 p.890 */
912 long i;
913 double hr2;
914 double numerator;
915
916 numerator = exp(0.6931471805599 * ( n-1.) + logfac(n)) / (n*n);
917 for (i = 0; i < n; i++) {
918 hr2 = hermite(n-1, hroot[i]);
919 weights[i] = numerator / (hr2*hr2);
920 }
921 } /* hermiteweight */
922
923
924 void inithermitcat(long categs, double alpha, double *rate, double *probcat)
925 { /* calculates rates and probabilities */
926 long i;
927 double *hroot;
928 double std;
929
930 std = SQRT2 /sqrt(alpha);
931 hroot = (double *) Malloc((categs+1) * sizeof(double));
932 root_hermite(categs, hroot); /* calculate roots */
933 hermite_weight(categs, hroot, probcat); /* set weights */
934 for (i=0; i<categs; i++) { /* set rates */
935 rate[i] = 1.0 + std * hroot[i];
936 probcat[i] = probcat[i];
937 }
938 free(hroot);
939 } /* inithermitcat */
940
941
942 void initgammacat (long categs, double alpha, double *rate, double *probcat)
943 { /* calculate rates and probabilities to approximate Gamma distribution
944 of rates with "categs" categories and shape parameter "alpha" using
945 rates and weights from Generalized Laguerre quadrature or from
946 Hermite quadrature */
947
948 if (alpha >= 100.0)
949 inithermitcat(categs, alpha, rate, probcat);
950 else
951 initlaguerrecat(categs, alpha, rate, probcat);
952 } /* initgammacat */
953
954
955 void inithowmany(long *howmanny, long howoften)
956 {/* input how many cycles */
957 long loopcount;
958
959 loopcount = 0;
960 for (;;) {
961 printf("How many cycles of %4ld trees?\n", howoften);
962 fflush(stdout);
963 if (scanf("%ld%*[^\n]", howmanny) == 1) {
964 getchar();
965 if (*howmanny >= 1)
966 break;
967 }
968 countup(&loopcount, 10);
969 }
970 } /*inithowmany*/
971
972
973 void inithowoften(long *howoften)
974 { /* input how many trees per cycle */
975 long loopcount;
976
977 loopcount = 0;
978 for (;;) {
979 printf("How many trees per cycle?\n");
980 fflush(stdout);
981 if (scanf("%ld%*[^\n]", howoften) == 1) {
982 getchar();
983 if (*howoften >= 1)
984 break;
985 }
986 countup(&loopcount, 10);
987 }
988 } /*inithowoften*/
989
990
991 void initlambda(double *lambda)
992 { /* input patch length parameter for autocorrelated HMM rates */
993
994 long loopcount;
995
996 loopcount = 0;
997 for (;;) {
998 printf("Mean block length of sites having the same rate (greater than 1)?\n");
999 fflush(stdout);
1000 if (scanf("%lf%*[^\n]", lambda) == 1) {
1001 getchar();
1002 if (*lambda > 1.0)
1003 break;
1004 }
1005 countup(&loopcount, 10);
1006 }
1007 *lambda = 1.0 / *lambda;
1008 } /* initlambda */
1009
1010
1011
1012 void initfreqs(double *freqa, double *freqc, double *freqg, double *freqt)
1013 { /* input frequencies of the four bases */
1014 char input[FNMLNGTH];
1015 long scanned, loopcount;
1016
1017 printf("Base frequencies for A, C, G, T/U (use blanks to separate)?\n");
1018 loopcount = 0;
1019 do {
1020 fflush(stdout);
1021 getstryng(input);
1022 scanned = sscanf(input,"%lf%lf%lf%lf%*[^\n]", freqa, freqc, freqg, freqt);
1023 if (scanned == 4)
1024 break;
1025 else
1026 printf("Please enter exactly 4 values.\n");
1027 countup(&loopcount, 100);
1028 } while (1);
1029 } /* initfreqs */
1030
1031
1032 void initratio(double *ttratio)
1033 { /* input transition/transversion ratio */
1034 long loopcount;
1035
1036 loopcount = 0;
1037 for (;;) {
1038 printf("Transition/transversion ratio?\n");
1039 fflush(stdout);
1040 if (scanf("%lf%*[^\n]", ttratio) == 1) {
1041 getchar();
1042 if (*ttratio >= 0.0)
1043 break;
1044 else
1045 printf("Transition/transversion ratio cannot be negative.\n");
1046 }
1047 countup(&loopcount, 10);
1048 }
1049 } /* initratio */
1050
1051
1052 void initpower(double *power)
1053 {
1054 for (;;) {
1055 printf("New power?\n");
1056 fflush(stdout);
1057 if (scanf("%lf%*[^\n]", power) == 1) {
1058 getchar();
1059 break;
1060 }
1061 }
1062 } /*initpower*/
1063
1064
1065 void initdatasets(long *datasets)
1066 {
1067 /* handle multi-data set option */
1068 long loopcount;
1069
1070 loopcount = 0;
1071 for (;;) {
1072 printf("How many data sets?\n");
1073 fflush(stdout);
1074 if (scanf("%ld%*[^\n]", datasets) == 1) {
1075 getchar();
1076 if (*datasets > 1)
1077 break;
1078 else
1079 printf("Bad data sets number: it must be greater than 1\n");
1080 }
1081 countup(&loopcount, 10);
1082 }
1083 } /* initdatasets */
1084
1085
1086 void justweights(long *datasets)
1087 {
1088 /* handle multi-data set option by weights */
1089 long loopcount;
1090
1091 loopcount = 0;
1092 for (;;) {
1093 printf("How many sets of weights?\n");
1094 fflush(stdout);
1095 if (scanf("%ld%*[^\n]", datasets) == 1) {
1096 getchar();
1097 if (*datasets >= 1)
1098 break;
1099 else
1100 printf("BAD NUMBER: it must be greater than 1\n");
1101 }
1102 countup(&loopcount, 10);
1103 }
1104 } /* justweights */
1105
1106
1107 void initterminal(boolean *ibmpc, boolean *ansi)
1108 {
1109 /* handle terminal option */
1110 if (*ibmpc) {
1111 *ibmpc = false;
1112 *ansi = true;
1113 } else if (*ansi)
1114 *ansi = false;
1115 else
1116 *ibmpc = true;
1117 } /*initterminal*/
1118
1119
1120 void initnumlines(long *screenlines)
1121 {
1122 long loopcount;
1123
1124 loopcount = 0;
1125 do {
1126 *screenlines = readlong("Number of lines on screen?\n");
1127 countup(&loopcount, 10);
1128 } while (*screenlines <= 12);
1129 } /*initnumlines*/
1130
1131
1132 void initbestrees(bestelm *bestrees, long maxtrees, boolean glob)
1133 {
1134 /* initializes either global or local field of each array in bestrees */
1135 long i;
1136
1137 if (glob)
1138 for (i = 0; i < maxtrees; i++)
1139 bestrees[i].gloreange = false;
1140 else
1141 for (i = 0; i < maxtrees; i++)
1142 bestrees[i].locreange = false;
1143 } /* initbestrees */
1144
1145
1146 void newline(FILE *filename, long i, long j, long k)
1147 {
1148 /* go to new line if i is a multiple of j, indent k spaces */
1149 long m;
1150
1151 if ((i - 1) % j != 0 || i <= 1)
1152 return;
1153 putc('\n', filename);
1154 for (m = 1; m <= k; m++)
1155 putc(' ', filename);
1156 } /* newline */
1157
1158
1159 void inputnumbersold(long *spp, long *chars, long *nonodes, long n)
1160 {
1161 /* input the numbers of species and of characters */
1162
1163 if (fscanf(infile, "%ld%ld", spp, chars) != 2 || *spp <= 0 || *chars <= 0) {
1164 printf(
1165 "ERROR: Unable to read the number of species or characters in data set\n");
1166 printf(
1167 "The input file is incorrect (perhaps it was not saved text only).\n");
1168 }
1169 *nonodes = *spp * 2 - n;
1170 } /* inputnumbersold */
1171
1172
1173 void inputnumbers(long *spp, long *chars, long *nonodes, long n)
1174 {
1175 /* Read numbers of species and characters from first line of a data set.
1176 * Return the results in *spp and *chars, respectively. Also returns
1177 * (*spp * 2 - n) in *nonodes */
1178
1179 if (fscanf(infile, "%ld%ld", spp, chars) != 2 || *spp <= 0 || *chars <= 0) {
1180 printf(
1181 "ERROR: Unable to read the number of species or characters in data set\n");
1182 printf(
1183 "The input file is incorrect (perhaps it was not saved text only).\n");
1184 }
1185 *nonodes = *spp * 2 - n;
1186 } /* inputnumbers */
1187
1188
1189 void inputnumbers2(long *spp, long *nonodes, long n)
1190 {
1191 /* read species number */
1192
1193 if (fscanf(infile, "%ld", spp) != 1 || *spp <= 0) {
1194 printf("ERROR: Unable to read the number of species in data set\n");
1195 printf(
1196 "The input file is incorrect (perhaps it was not saved text only).\n");
1197 }
1198 fprintf(outfile, "\n%4ld Populations\n", *spp);
1199 *nonodes = *spp * 2 - n;
1200 } /* inputnumbers2 */
1201
1202
1203 void inputnumbers3(long *spp, long *chars)
1204 {
1205 /* input the numbers of species and of characters */
1206
1207 if (fscanf(infile, "%ld%ld", spp, chars) != 2 || *spp <= 0 || *chars <= 0) {
1208 printf(
1209 "ERROR: Unable to read the number of species or characters in data set\n");
1210 printf(
1211 "The input file is incorrect (perhaps it was not saved text only).\n");
1212 exxit(-1);
1213 }
1214 } /* inputnumbers3 */
1215
1216
1217 void samenumsp(long *chars, long ith)
1218 {
1219 /* check if spp is same as the first set in other data sets */
1220 long cursp, curchs;
1221
1222 if (eoln(infile))
1223 scan_eoln(infile);
1224 if (fscanf(infile, "%ld%ld", &cursp, &curchs) == 2) {
1225 if (cursp != spp) {
1226 printf(
1227 "\n\nERROR: Inconsistent number of species in data set %ld\n\n", ith);
1228 exxit(-1);
1229 }
1230 }
1231 else {
1232 printf(
1233 "Unable to read number of species and sites from data set %ld\n\n", ith);
1234 exxit(-1);
1235 }
1236 *chars = curchs;
1237 } /* samenumsp */
1238
1239
1240 void samenumsp2(long ith)
1241 {
1242 /* check if spp is same as the first set in other data sets */
1243 long cursp;
1244
1245 if (eoln(infile))
1246 scan_eoln(infile);
1247 if (fscanf(infile, "%ld", &cursp) != 1) {
1248 printf("\n\nERROR: Unable to read number of species in data set %ld\n",
1249 ith);
1250 printf(
1251 "The input file is incorrect (perhaps it was not saved text only).\n");
1252 exxit(-1);
1253 }
1254 if (cursp != spp) {
1255 printf(
1256 "\n\nERROR: Inconsistent number of species in data set %ld\n\n", ith);
1257 exxit(-1);
1258 }
1259 } /* samenumsp2 */
1260
1261
1262 void readoptions(long *extranum, const char *options)
1263 { /* read option characters from input file */
1264 Char ch;
1265
1266 while (!(eoln(infile))) {
1267 ch = gettc(infile);
1268 uppercase(&ch);
1269 if (strchr(options, ch) != NULL)
1270 (* extranum)++;
1271 else if (!(ch == ' ' || ch == '\t')) {
1272 printf("BAD OPTION CHARACTER: %c\n", ch);
1273 exxit(-1);
1274 }
1275 }
1276 scan_eoln(infile);
1277 } /* readoptions */
1278
1279
1280 void matchoptions(Char *ch, const char *options)
1281 { /* match option characters to those in auxiliary options line */
1282
1283 *ch = gettc(infile);
1284 uppercase(ch);
1285 if (strchr(options, *ch) == NULL) {
1286 printf("ERROR: Incorrect auxiliary options line");
1287 printf(" which starts with %c\n", *ch);
1288 exxit(-1);
1289 }
1290 } /* matchoptions */
1291
1292
1293 /*void inputweightsold(long chars, steptr weight, boolean *weights)
1294 {
1295 Char ch;
1296 int i;
1297 for (i = 1; i < nmlngth ; i++)
1298 getc(infile);
1299
1300 for (i = 0; i < chars; i++) {
1301 do {
1302 if (eoln(infile))
1303 scan_eoln(infile);
1304 ch = gettc(infile);
1305 if (ch == '\n')
1306 ch = ' ';
1307 } while (ch == ' ');
1308 weight[i] = 1;
1309 if (isdigit(ch))
1310 weight[i] = ch - '0';
1311 else if (isalpha(ch)) {
1312 uppercase(&ch);
1313 weight[i] = ch - 'A' + 10;
1314 } else {
1315 printf("\n\nERROR: Bad weight character: %c\n\n", ch);
1316 exxit(-1);
1317 }
1318 }
1319 scan_eoln(infile);
1320 *weights = true;
1321 } *inputweightsold*/
1322
1323
1324 void inputweights(long chars, steptr weight, boolean *weights)
1325 {
1326 /* input the character weights, 0-9 and A-Z for weights 0 - 35 */
1327 Char ch;
1328 long i;
1329
1330 for (i = 0; i < chars; i++) {
1331 do {
1332 if (eoln(weightfile))
1333 scan_eoln(weightfile);
1334 ch = gettc(weightfile);
1335 if (ch == '\n')
1336 ch = ' ';
1337 } while (ch == ' ');
1338 weight[i] = 1;
1339 if (isdigit(ch))
1340 weight[i] = ch - '0';
1341 else if (isalpha(ch)) {
1342 uppercase(&ch);
1343 weight[i] = ch - 'A' + 10;
1344 } else {
1345 printf("\n\nERROR: Bad weight character: %c\n\n", ch);
1346 exxit(-1);
1347 }
1348 }
1349 scan_eoln(weightfile);
1350 *weights = true;
1351 } /* inputweights */
1352
1353
1354 void inputweights2(long a, long b, long *weightsum,
1355 steptr weight, boolean *weights, const char *prog)
1356 {
1357 /* input the character weights, 0 or 1 */
1358 Char ch;
1359 long i;
1360
1361 *weightsum = 0;
1362 for (i = a; i < b; i++) {
1363 do {
1364 if (eoln(weightfile))
1365 scan_eoln(weightfile);
1366 ch = gettc(weightfile);
1367 } while (ch == ' ');
1368 weight[i] = 1;
1369 if (ch == '0' || ch == '1')
1370 weight[i] = ch - '0';
1371 else {
1372 printf("\n\nERROR: Bad weight character: %c -- ", ch);
1373 printf("weights in %s must be 0 or 1\n", prog);
1374 exxit(-1);
1375 }
1376 *weightsum += weight[i];
1377 }
1378 *weights = true;
1379 scan_eoln(weightfile);
1380 } /* inputweights2 */
1381
1382
1383 /*void printweights(FILE *filename, long inc, long chars,
1384 steptr weight, const char *letters)
1385 {
1386 * print out the weights of sites *
1387 long i, j;
1388 boolean letterweights;
1389
1390 letterweights = false;
1391 for (i = 0; i < chars; i++)
1392 if (weight[i] > 9)
1393 letterweights = true;
1394 fprintf(filename, "\n %s are weighted as follows:", letters);
1395 if (letterweights)
1396 fprintf(filename, " (A = 10, B = 11, etc.)\n");
1397 else
1398 putc('\n', filename);
1399 for (i = 0; i < chars; i++) {
1400 if (i % 60 == 0) {
1401 putc('\n', filename);
1402 for (j = 1; j <= nmlngth + 3; j++)
1403 putc(' ', filename);
1404 }
1405 if (weight[i+inc] < 10)
1406 fprintf(filename, "%ld", weight[i + inc]);
1407 else
1408 fprintf(filename, "%c", 'A'-10+(int)weight[i + inc]);
1409 if ((i+1) % 5 == 0 && (i+1) % 60 != 0)
1410 putc(' ', filename);
1411 }
1412 fprintf(filename, "\n\n");
1413 } * printweights */
1414
1415
1416 void inputcategs(long a, long b, steptr category, long categs, const char *prog)
1417 {
1418 /* input the categories, 1-9 */
1419 Char ch;
1420 long i;
1421
1422 for (i = a; i < b; i++) {
1423 do {
1424 if (eoln(catfile))
1425 scan_eoln(catfile);
1426 ch = gettc(catfile);
1427 } while (ch == ' ');
1428 if ((ch >= '1') && (ch <= ('0'+categs)))
1429 category[i] = ch - '0';
1430 else {
1431 printf("\n\nERROR: Bad category character: %c", ch);
1432 printf(" -- categories in %s are currently 1-%ld\n", prog, categs);
1433 exxit(-1);
1434 }
1435 }
1436 scan_eoln(catfile);
1437 } /* inputcategs */
1438
1439
1440 /*void printcategs(FILE *filename, long chars, steptr category,
1441 const char *letters)
1442 {
1443 * print out the sitewise categories *
1444 long i, j;
1445
1446 fprintf(filename, "\n %s are:\n", letters);
1447 for (i = 0; i < chars; i++) {
1448 if (i % 60 == 0) {
1449 putc('\n', filename);
1450 for (j = 1; j <= nmlngth + 3; j++)
1451 putc(' ', filename);
1452 }
1453 fprintf(filename, "%ld", category[i]);
1454 if ((i+1) % 10 == 0 && (i+1) % 60 != 0)
1455 putc(' ', filename);
1456 }
1457 fprintf(filename, "\n\n");
1458 } * printcategs */
1459
1460
1461 void inputfactors(long chars, Char *factor, boolean *factors)
1462 {
1463 /* reads the factor symbols */
1464 long i;
1465
1466 for (i = 0; i < (chars); i++) {
1467 if (eoln(factfile))
1468 scan_eoln(factfile);
1469 factor[i] = gettc(factfile);
1470 if (factor[i] == '\n')
1471 factor[i] = ' ';
1472 }
1473 scan_eoln(factfile);
1474 *factors = true;
1475 } /* inputfactors */
1476
1477
1478 /*void printfactors(FILE *filename, long chars, Char *factor, const char *letters)
1479 {
1480 * print out list of factor symbols *
1481 long i;
1482
1483 fprintf(filename, "Factors%s:\n\n", letters);
1484 for (i = 1; i <= nmlngth - 5; i++)
1485 putc(' ', filename);
1486 for (i = 1; i <= (chars); i++) {
1487 newline(filename, i, 55, nmlngth + 3);
1488 putc(factor[i - 1], filename);
1489 if (i % 5 == 0)
1490 putc(' ', filename);
1491 }
1492 putc('\n', filename);
1493 } * printfactors *
1494
1495
1496 void headings(long chars, const char *letters1, const char *letters2)
1497 {
1498 long i, j;
1499
1500 putc('\n', outfile);
1501 j = nmlngth + (chars + (chars - 1) / 10) / 2 - 5;
1502 if (j < nmlngth - 1)
1503 j = nmlngth - 1;
1504 if (j > 37)
1505 j = 37;
1506 fprintf(outfile, "Name");
1507 for (i = 1; i <= j; i++)
1508 putc(' ', outfile);
1509 fprintf(outfile, "%s\n", letters1);
1510 fprintf(outfile, "----");
1511 for (i = 1; i <= j; i++)
1512 putc(' ', outfile);
1513 fprintf(outfile, "%s\n\n", letters2);
1514 } * headings */
1515
1516
1517 /*void initname(long i)
1518 {
1519 * read in species name *
1520 long j;
1521
1522 for (j = 0; j < nmlngth; j++) {
1523 if (eoff(infile) | eoln(infile)){
1524 printf("\n\nERROR: end-of-line or end-of-file");
1525 printf(" in the middle of species name for species %ld\n\n", i+1);
1526 exxit(-1);
1527 }
1528 nayme[i][j] = gettc(infile);
1529 if ((nayme[i][j] == '(') || (nayme[i][j] == ')') || (nayme[i][j] == ':')
1530 || (nayme[i][j] == ',') || (nayme[i][j] == ';') || (nayme[i][j] == '[')
1531 || (nayme[i][j] == ']')) {
1532 printf("\nERROR: Species name may not contain characters ( ) : ; , [ ] \n");
1533 printf(" In name of species number %ld there is character %c\n\n",
1534 i+1, nayme[i][j]);
1535 exxit(-1);
1536 }
1537 }
1538 } * initname */
1539
1540
1541 void findtree(boolean *found, long *pos, long nextree, long *place, bestelm *bestrees)
1542 {
1543 /* finds tree given by array place in array bestrees by binary search */
1544 /* used by dnacomp, dnapars, dollop, mix, & protpars */
1545 long i, lower, upper;
1546 boolean below, done;
1547
1548 below = false;
1549 lower = 1;
1550 upper = nextree - 1;
1551 (*found) = false;
1552 while (!(*found) && lower <= upper) {
1553 (*pos) = (lower + upper) / 2;
1554 i = 3;
1555 done = false;
1556 while (!done) {
1557 done = (i > spp);
1558 if (!done)
1559 done = (place[i - 1] != bestrees[(*pos) - 1].btree[i - 1]);
1560 if (!done)
1561 i++;
1562 }
1563 (*found) = (i > spp);
1564 if (*found)
1565 break;
1566 below = (place[i - 1] < bestrees[(*pos )- 1].btree[i - 1]);
1567 if (below)
1568 upper = (*pos) - 1;
1569 else
1570 lower = (*pos) + 1;
1571 }
1572 if (!(*found) && !below)
1573 (*pos)++;
1574 } /* findtree */
1575
1576
1577 void addtree(long pos, long *nextree, boolean collapse, long *place, bestelm *bestrees)
1578 {
1579 /* puts tree from array place in its proper position in array bestrees */
1580 /* used by dnacomp, dnapars, dollop, mix, & protpars */
1581 long i;
1582
1583 for (i = *nextree - 1; i >= pos; i--){
1584 memcpy(bestrees[i].btree, bestrees[i - 1].btree, spp * sizeof(long));
1585 bestrees[i].gloreange = bestrees[i - 1].gloreange;
1586 bestrees[i - 1].gloreange = false;
1587 bestrees[i].locreange = bestrees[i - 1].locreange;
1588 bestrees[i - 1].locreange = false;
1589 bestrees[i].collapse = bestrees[i - 1].collapse;
1590 }
1591 for (i = 0; i < spp; i++)
1592 bestrees[pos - 1].btree[i] = place[i];
1593 bestrees[pos - 1].collapse = collapse;
1594 (*nextree)++;
1595 } /* addtree */
1596
1597
1598 long findunrearranged(bestelm *bestrees, long nextree, boolean glob)
1599 {
1600 /* finds bestree with either global or local field false */
1601 long i;
1602
1603 if (glob) {
1604 for (i = 0; i < nextree - 1; i++)
1605 if (!bestrees[i].gloreange)
1606 return i;
1607 } else {
1608 for (i = 0; i < nextree - 1; i++)
1609 if (!bestrees[i].locreange)
1610 return i;
1611 }
1612 return -1;
1613 } /* findunrearranged */
1614
1615
1616 boolean torearrange(bestelm *bestrees, long nextree)
1617 { /* sees if any best tree is yet to be rearranged */
1618
1619 if (findunrearranged(bestrees, nextree, true) >= 0)
1620 return true;
1621 else if (findunrearranged(bestrees, nextree, false) >= 0)
1622 return true;
1623 else
1624 return false;
1625 } /* torearrange */
1626
1627
1628 void reducebestrees(bestelm *bestrees, long *nextree)
1629 {
1630 /* finds best trees with collapsible branches and deletes them */
1631 long i, j;
1632 i = 0;
1633 j = *nextree - 2;
1634 do {
1635 while (!bestrees[i].collapse && i < *nextree - 1) i++;
1636 while (bestrees[j].collapse && j >= 0) j--;
1637 if (i < j) {
1638 memcpy(bestrees[i].btree, bestrees[j].btree, spp * sizeof(long));
1639 bestrees[i].gloreange = bestrees[j].gloreange;
1640 bestrees[i].locreange = bestrees[j].locreange;
1641 bestrees[i].collapse = false;
1642 bestrees[j].collapse = true;
1643 }
1644 } while (i < j);
1645 *nextree = i + 1;
1646 } /* reducebestrees */
1647
1648
1649 void shellsort(double *a, long *b, long n)
1650 { /* Shell sort keeping a, b in same order */
1651 /* used by dnapenny, dolpenny, & penny */
1652 long gap, i, j, itemp;
1653 double rtemp;
1654
1655 gap = n / 2;
1656 while (gap > 0) {
1657 for (i = gap + 1; i <= n; i++) {
1658 j = i - gap;
1659 while (j > 0) {
1660 if (a[j - 1] > a[j + gap - 1]) {
1661 rtemp = a[j - 1];
1662 a[j - 1] = a[j + gap - 1];
1663 a[j + gap - 1] = rtemp;
1664 itemp = b[j - 1];
1665 b[j - 1] = b[j + gap - 1];
1666 b[j + gap - 1] = itemp;
1667 }
1668 j -= gap;
1669 }
1670 }
1671 gap /= 2;
1672 }
1673 } /* shellsort */
1674
1675
1676 void getch(Char *c, long *parens, FILE *treefile)
1677 { /* get next nonblank character */
1678
1679 do {
1680 if (eoln(treefile))
1681 scan_eoln(treefile);
1682 (*c) = gettc(treefile);
1683
1684 if ((*c) == '\n' || (*c) == '\t')
1685 (*c) = ' ';
1686 } while ( *c == ' ' && !eoff(treefile) );
1687 if ((*c) == '(')
1688 (*parens)++;
1689 if ((*c) == ')')
1690 (*parens)--;
1691 } /* getch */
1692
1693
1694 void getch2(Char *c, long *parens)
1695 { /* get next nonblank character */
1696 do {
1697 if (eoln(intree))
1698 scan_eoln(intree);
1699 *c = gettc(intree);
1700 if (*c == '\n' || *c == '\t')
1701 *c = ' ';
1702 } while (!(*c != ' ' || eoff(intree)));
1703 if (*c == '(')
1704 (*parens)++;
1705 if (*c == ')')
1706 (*parens)--;
1707 } /* getch2 */
1708
1709
1710 void findch(Char c, Char *ch, long which)
1711 { /* scan forward until find character c */
1712 boolean done;
1713 long dummy_parens;
1714 done = false;
1715 while (!done) {
1716 if (c == ',') {
1717 if (*ch == '(' || *ch == ')' || *ch == ';') {
1718 printf(
1719 "\n\nERROR in user tree %ld: unmatched parenthesis or missing comma\n\n",
1720 which);
1721 exxit(-1);
1722 } else if (*ch == ',')
1723 done = true;
1724 } else if (c == ')') {
1725 if (*ch == '(' || *ch == ',' || *ch == ';') {
1726 printf("\n\nERROR in user tree %ld: ", which);
1727 printf("unmatched parenthesis or non-bifurcated node\n\n");
1728 exxit(-1);
1729 } else {
1730 if (*ch == ')')
1731 done = true;
1732 }
1733 } else if (c == ';') {
1734 if (*ch != ';') {
1735 printf("\n\nERROR in user tree %ld: ", which);
1736 printf("unmatched parenthesis or missing semicolon\n\n");
1737 exxit(-1);
1738 } else
1739 done = true;
1740 }
1741 if (*ch != ')' && done)
1742 continue;
1743 getch(ch, &dummy_parens, intree);
1744 }
1745 } /* findch */
1746
1747
1748 void findch2(Char c, long *lparens, long *rparens, Char *ch)
1749 { /* skip forward in user tree until find character c */
1750 boolean done;
1751 long dummy_parens;
1752 done = false;
1753
1754 while (!done) {
1755 if (c == ',') {
1756 if (*ch == '(' || *ch == ')' || *ch == ':' || *ch == ';') {
1757 printf("\n\nERROR in user tree: ");
1758 printf("unmatched parenthesis, missing comma");
1759 printf(" or non-trifurcated base\n\n");
1760 exxit(-1);
1761 } else if (*ch == ',')
1762 done = true;
1763 } else if (c == ')') {
1764 if (*ch == '(' || *ch == ',' || *ch == ':' || *ch == ';') {
1765 printf(
1766 "\n\nERROR in user tree: unmatched parenthesis or non-bifurcated node\n\n");
1767 exxit(-1);
1768 } else if (*ch == ')') {
1769 (*rparens)++;
1770 if ((*lparens) > 0 && (*lparens) == (*rparens)) {
1771 if ((*lparens) == spp - 2) {
1772 getch(ch, &dummy_parens, intree);
1773 if (*ch != ';') {
1774 printf( "\n\nERROR in user tree: ");
1775 printf("unmatched parenthesis or missing semicolon\n\n");
1776 exxit(-1);
1777 }
1778 }
1779 }
1780 done = true;
1781 }
1782 }
1783 if (*ch != ')' && done)
1784 continue;
1785 if (*ch == ')')
1786 getch(ch, &dummy_parens, intree);
1787 }
1788 } /* findch2 */
1789
1790 void processlength(double *valyew, double *divisor, Char *ch,
1791 boolean *lengthIsNegative, FILE *treefile, long *parens)
1792 { /* read a branch length from a treefile */
1793 long digit, ordzero, exponent, exponentIsNegative;
1794 boolean pointread, hasExponent;
1795
1796 ordzero = '0';
1797 *lengthIsNegative = false;
1798 pointread = false;
1799 hasExponent = false;
1800 exponentIsNegative = -1; /* 3 states: -1 = unassigned, 1 = true, 0 = false */
1801 exponent = 0;
1802 *valyew = 0.0;
1803 *divisor = 1.0;
1804 getch(ch, parens, treefile);
1805 if ('+' == *ch)
1806 getch(ch, parens, treefile); /* ignore leading '+', because "+1.2345" == "1.2345" */
1807 else if ('-' == *ch)
1808 {
1809 *lengthIsNegative = true;
1810 getch(ch, parens, treefile);
1811 }
1812 digit = (long)(*ch - ordzero);
1813 while ( ((digit <= 9) && (digit >= 0)) || '.' == *ch || '-' == *ch
1814 || '+' == *ch || 'E' == *ch || 'e' == *ch) {
1815 if ('.' == *ch)
1816 {
1817 if (!pointread)
1818 pointread = true;
1819 else
1820 {
1821 printf("\n\nERROR: Branch length found with more than one \'.\' in it.\n\n");
1822 exxit(-1);
1823 }
1824 }
1825 else if ('+' == *ch)
1826 {
1827 if (hasExponent && -1 == exponentIsNegative)
1828 exponentIsNegative = 0; /* 3 states: -1 = unassigned, 1 = true, 0 = false */
1829 else
1830 {
1831 printf("\n\nERROR: Branch length found with \'+\' in an unexpected place.\n\n");
1832 exxit(-1);
1833 }
1834 }
1835 else if ('-' == *ch)
1836 {
1837 if (hasExponent && -1 == exponentIsNegative)
1838 exponentIsNegative = 1; /* 3 states: -1 = unassigned, 1 = true, 0 = false */
1839 else
1840 {
1841 printf("\n\nERROR: Branch length found with \'-\' in an unexpected place.\n\n");
1842 exxit(-1);
1843 }
1844 }
1845 else if ('E' == *ch || 'e' == *ch)
1846 {
1847 if (!hasExponent)
1848 hasExponent = true;
1849 else
1850 {
1851 printf("\n\nERROR: Branch length found with more than one \'E\' in it.\n\n");
1852 exxit(-1);
1853 }
1854 }
1855 else {
1856 if (!hasExponent)
1857 {
1858 *valyew = *valyew * 10.0 + digit;
1859 if (pointread)
1860 *divisor *= 10.0;
1861 }
1862 else
1863 exponent = 10*exponent + digit;
1864 }
1865 getch(ch, parens, treefile);
1866 digit = (long)(*ch - ordzero);
1867 }
1868 if (hasExponent)
1869 {
1870 if (exponentIsNegative)
1871 *divisor *= pow(10.,(double)exponent);
1872 else
1873 *divisor /= pow(10.,(double)exponent);
1874 }
1875 if (*lengthIsNegative)
1876 *valyew = -(*valyew);
1877 } /* processlength */
1878
1879 /*void writename(long start, long n, long *enterorder)
1880 { * write species name and number in entry order *
1881 long i, j;
1882
1883 for (i = start; i < start+n; i++) {
1884 printf(" %3ld. ", i+1);
1885 for (j = 0; j < nmlngth; j++)
1886 putchar(nayme[enterorder[i] - 1][j]);
1887 putchar('\n');
1888 fflush(stdout);
1889 }
1890 } * writename */
1891
1892
1893 void memerror()
1894 {
1895 printf("Error allocating memory\n");
1896 exxit(-1);
1897 } /* memerror */
1898
1899
1900 void odd_malloc(long x)
1901 { /* error message if attempt to malloc too little or too much memory */
1902 printf ("ERROR: a function asked for an inappropriate amount of memory:");
1903 printf (" %ld bytes\n", x);
1904 printf (" This can mean one of two things:\n");
1905 printf (" 1. The input file is incorrect");
1906 printf (" (perhaps it was not saved as Text Only),\n");
1907 printf (" 2. There is a bug in the program.\n");
1908 printf (" Please check your input file carefully.\n");
1909 printf (" If it seems to be a bug, please mail joe (at) gs.washington.edu\n");
1910 printf (" with the name of the program, your computer system type,\n");
1911 printf (" a full description of the problem, and with the input data file.\n");
1912 printf (" (which should be in the body of the message, not as an Attachment).\n");
1913
1914 /* abort() can be used to crash */
1915
1916 exxit(-1);
1917 }
1918
1919
1920 MALLOCRETURN *mymalloc(long x)
1921 { /* wrapper for malloc, allowing error message if too little, too much */
1922 MALLOCRETURN *new_block;
1923
1924 if ((x <= 0) ||
1925 (x > TOO_MUCH_MEMORY))
1926 odd_malloc(x);
1927
1928 new_block = (MALLOCRETURN *)calloc(1, x);
1929
1930 if (!new_block) {
1931 memerror();
1932 return (MALLOCRETURN *) new_block;
1933 } else
1934 return (MALLOCRETURN *) new_block;
1935 } /* mymalloc */
1936
1937
1938 void gnu(node **grbg, node **p)
1939 { /* this and the following are do-it-yourself garbage collectors.
1940 Make a new node or pull one off the garbage list */
1941
1942 if (*grbg != NULL) {
1943 *p = *grbg;
1944 *grbg = (*grbg)->next;
1945 } else
1946 *p = (node *)Malloc(sizeof(node));
1947
1948 (*p)->back = NULL;
1949 (*p)->next = NULL;
1950 (*p)->tip = false;
1951 (*p)->times_in_tree = 0.0;
1952 (*p)->r = 0.0;
1953 (*p)->theta = 0.0;
1954 (*p)->x = NULL;
1955 (*p)->protx = NULL; /* for the sake of proml */
1956 } /* gnu */
1957
1958
1959 void chuck(node **grbg, node *p)
1960 {
1961 /* collect garbage on p -- put it on front of garbage list */
1962
1963 p->back = NULL;
1964 p->next = *grbg;
1965 *grbg = p;
1966 } /* chuck */
1967
1968
1969 void zeronumnuc(node *p, long endsite)
1970 {
1971 long i,j;
1972
1973 for (i = 0; i < endsite; i++)
1974 for (j = (long)A; j <= (long)O; j++)
1975 p->numnuc[i][j] = 0;
1976 } /* zeronumnuc */
1977
1978
1979 void zerodiscnumnuc(node *p, long endsite)
1980 {
1981 long i,j;
1982
1983 for (i = 0; i < endsite; i++)
1984 for (j = (long)zero; j <= (long)seven; j++)
1985 p->discnumnuc[i][j] = 0;
1986 } /* zerodiscnumnuc */
1987
1988
1989 void allocnontip(node *p, long *zeros, long endsite)
1990 { /* allocate an interior node */
1991 /* used by dnacomp, dnapars, & dnapenny */
1992
1993 p->numsteps = (steptr)Malloc(endsite*sizeof(long));
1994 p->oldnumsteps = (steptr)Malloc(endsite*sizeof(long));
1995 p->base = (baseptr)Malloc(endsite*sizeof(long));
1996 p->oldbase = (baseptr)Malloc(endsite*sizeof(long));
1997 p->numnuc = (nucarray *)Malloc(endsite*sizeof(nucarray));
1998 memcpy(p->base, zeros, endsite*sizeof(long));
1999 memcpy(p->numsteps, zeros, endsite*sizeof(long));
2000 memcpy(p->oldbase, zeros, endsite*sizeof(long));
2001 memcpy(p->oldnumsteps, zeros, endsite*sizeof(long));
2002 zeronumnuc(p, endsite);
2003 } /* allocnontip */
2004
2005
2006 void allocdiscnontip(node *p, long *zeros, unsigned char *zeros2, long endsite)
2007 { /* allocate an interior node */
2008 /* used by pars */
2009
2010 p->numsteps = (steptr)Malloc(endsite*sizeof(long));
2011 p->oldnumsteps = (steptr)Malloc(endsite*sizeof(long));
2012 p->discbase = (discbaseptr)Malloc(endsite*sizeof(unsigned char));
2013 p->olddiscbase = (discbaseptr)Malloc(endsite*sizeof(unsigned char));
2014 p->discnumnuc = (discnucarray *)Malloc(endsite*sizeof(discnucarray));
2015 memcpy(p->discbase, zeros2, endsite*sizeof(unsigned char));
2016 memcpy(p->numsteps, zeros, endsite*sizeof(long));
2017 memcpy(p->olddiscbase, zeros2, endsite*sizeof(unsigned char));
2018 memcpy(p->oldnumsteps, zeros, endsite*sizeof(long));
2019 zerodiscnumnuc(p, endsite);
2020 } /* allocdiscnontip */
2021
2022
2023 void allocnode(node **anode, long *zeros, long endsite)
2024 { /* allocate a node */
2025 /* used by dnacomp, dnapars, & dnapenny */
2026 *anode = (node *)Malloc(sizeof(node));
2027 allocnontip(*anode, zeros, endsite);
2028 } /* allocnode */
2029
2030
2031 void allocdiscnode(node **anode, long *zeros, unsigned char *zeros2,
2032 long endsite)
2033 { /* allocate a node */
2034 /* used by pars */
2035 *anode = (node *)Malloc(sizeof(node));
2036 allocdiscnontip(*anode, zeros, zeros2, endsite);
2037 } /* allocdiscnontip */
2038
2039
2040 void gnutreenode(node **grbg, node **p, long i, long endsite, long *zeros)
2041 { /* this and the following are do-it-yourself garbage collectors.
2042 Make a new node or pull one off the garbage list */
2043 if (*grbg != NULL) {
2044 *p = *grbg;
2045 *grbg = (*grbg)->next;
2046 memcpy((*p)->numsteps, zeros, endsite*sizeof(long));
2047 memcpy((*p)->oldnumsteps, zeros, endsite*sizeof(long));
2048 memcpy((*p)->base, zeros, endsite*sizeof(long));
2049 memcpy((*p)->oldbase, zeros, endsite*sizeof(long));
2050 zeronumnuc(*p, endsite);
2051 } else
2052 allocnode(p, zeros, endsite);
2053 (*p)->back = NULL;
2054 (*p)->next = NULL;
2055 (*p)->tip = false;
2056 (*p)->visited = false;
2057 (*p)->index = i;
2058 (*p)->numdesc = 0;
2059 (*p)->sumsteps = 0.0;
2060 } /* gnutreenode */
2061
2062
2063 void gnudisctreenode(node **grbg, node **p, long i,
2064 long endsite, long *zeros, unsigned char *zeros2)
2065 { /* this and the following are do-it-yourself garbage collectors.
2066 Make a new node or pull one off the garbage list */
2067
2068 if (*grbg != NULL) {
2069 *p = *grbg;
2070 *grbg = (*grbg)->next;
2071 memcpy((*p)->numsteps, zeros, endsite*sizeof(long));
2072 memcpy((*p)->oldnumsteps, zeros, endsite*sizeof(long));
2073 memcpy((*p)->discbase, zeros2, endsite*sizeof(unsigned char));
2074 memcpy((*p)->olddiscbase, zeros2, endsite*sizeof(unsigned char));
2075 zerodiscnumnuc(*p, endsite);
2076 } else
2077 allocdiscnode(p, zeros, zeros2, endsite);
2078 (*p)->back = NULL;
2079 (*p)->next = NULL;
2080 (*p)->tip = false;
2081 (*p)->visited = false;
2082 (*p)->index = i;
2083 (*p)->numdesc = 0;
2084 (*p)->sumsteps = 0.0;
2085 } /* gnudisctreenode */
2086
2087
2088 void setupnode(node *p, long i)
2089 { /* initialization of node pointers, variables */
2090
2091 p->next = NULL;
2092 p->back = NULL;
2093 p->times_in_tree = (double) i * 1.0;
2094 p->index = i;
2095 p->tip = false;
2096 } /* setupnode */
2097
2098
2099 node *pnode(tree *t, node *p) {
2100 /* Get the "parent nodelet" of p's node group */
2101 return t->nodep[p->index - 1];
2102 }
2103
2104
2105 long count_sibs (node *p)
2106 { /* Count the number of nodes in a ring, return the total number of */
2107 /* nodes excluding the one passed into the function (siblings) */
2108 node *q;
2109 long return_int = 0;
2110
2111 if (p->tip) {
2112 printf ("Error: the function count_sibs called on a tip. This is a bug.\n");
2113 exxit (-1);
2114 }
2115
2116 q = p->next;
2117 while (q != p) {
2118 if (q == NULL) {
2119 printf ("Error: a loop of nodes was not closed.\n");
2120 exxit (-1);
2121 } else {
2122 return_int++;
2123 q = q->next;
2124 }
2125 }
2126
2127 return return_int;
2128 } /* count_sibs */
2129
2130
2131 void inittrav (node *p)
2132 { /* traverse to set pointers uninitialized on inserting */
2133 long i, num_sibs;
2134 node *sib_ptr;
2135
2136 if (p == NULL)
2137 return;
2138 if (p->tip)
2139 return;
2140 num_sibs = count_sibs (p);
2141 sib_ptr = p;
2142 for (i=0; i < num_sibs; i++) {
2143 sib_ptr = sib_ptr->next;
2144 sib_ptr->initialized = false;
2145 inittrav(sib_ptr->back);
2146 }
2147 } /* inittrav */
2148
2149
2150 void commentskipper(FILE ***intree, long *bracket)
2151 { /* skip over comment bracket contents in reading tree */
2152 char c;
2153
2154 c = gettc(**intree);
2155
2156 while (c != ']') {
2157
2158 if(feof(**intree)) {
2159 printf("\n\nERROR: Unmatched comment brackets\n\n");
2160 exxit(-1);
2161 }
2162
2163 if(c == '[') {
2164 (*bracket)++;
2165 commentskipper(intree, bracket);
2166 }
2167 c = gettc(**intree);
2168 }
2169 (*bracket)--;
2170 } /* commentskipper */
2171
2172
2173 long countcomma(FILE **treefile, long *comma)
2174 {
2175 /* Modified by Dan F. 11/10/96 */
2176
2177 /* countcomma rewritten so it passes back both lparen+comma to allocate nodep
2178 and a pointer to the comma variable. This allows the tree to know how many
2179 species exist, and the tips to be placed in the front of the nodep array */
2180 /* The next line inserted so this function leaves the file pointing
2181 to where it found it, not just re-winding it. */
2182 /* long orig_position = ftell (*treefile); */
2183
2184 fpos_t orig_position;
2185 Char c;
2186 long lparen = 0;
2187 long bracket = 0;
2188
2189 /* Save the file position */
2190 if ( fgetpos(*treefile, &orig_position) != 0 ) {
2191 printf("\n\nERROR: Could not save file position!\n\n");
2192 exxit(-1);
2193 }
2194
2195 (*comma) = 0;
2196
2197 for (;;){
2198 c = getc(*treefile);
2199 if (feof(*treefile))
2200 break;
2201 if (c == ';')
2202 break;
2203 if (c == ',')
2204 (*comma)++;
2205 if (c == '(')
2206 lparen++;
2207 if (c == '[') {
2208 bracket++;
2209 commentskipper(&treefile, &bracket);
2210 }
2211 }
2212
2213 /* Don't just rewind, */
2214 /* rewind (*treefile); */
2215 /* Re-set to where it pointed when the function was called */
2216
2217 /* fseek (*treefile, orig_position, SEEK_SET); */
2218
2219 fsetpos(*treefile, &orig_position);
2220
2221 return lparen + (*comma);
2222 } /*countcomma*/
2223
2224
2225 long countsemic(FILE **treefile)
2226 { /* Used to determine the number of user trees. Return
2227 either a: the number of semicolons in the file outside comments
2228 or b: the first integer in the file */
2229 Char c;
2230 long return_val, semic = 0;
2231 long bracket = 0;
2232
2233 /* Eat all whitespace */
2234 c = gettc(*treefile);
2235 while ((c == ' ') ||
2236 (c == '\t') ||
2237 (c == '\n')) {
2238 c = gettc(*treefile);
2239 }
2240
2241 /* Then figure out if the first non-white character is a digit; if
2242 so, return it */
2243 if (isdigit (c)) {
2244 ungetc(c, *treefile);
2245 if (fscanf((*treefile), "%ld", &return_val) != 1) {
2246 printf("Error reading number of trees in tree file.\n\n");
2247 exxit(-1);
2248 }
2249 } else {
2250
2251 /* Loop past all characters, count the number of semicolons
2252 outside of comments */
2253 for (;;){
2254 c = fgetc(*treefile);
2255 if (feof(*treefile))
2256 break;
2257 if (c == ';')
2258 semic++;
2259 if (c == '[') {
2260 bracket++;
2261 commentskipper(&treefile, &bracket);
2262 }
2263 }
2264 return_val = semic;
2265 }
2266
2267 rewind (*treefile);
2268 return return_val;
2269 } /* countsemic */
2270
2271
2272 void hookup(node *p, node *q)
2273 { /* hook together two nodes */
2274 assert(p != NULL);
2275 assert(q != NULL);
2276 p->back = q;
2277 q->back = p;
2278 } /* hookup */
2279
2280
2281 void unhookup(node *p, node *q)
2282 {
2283 /* unhook two nodes. Not strictly required, but helps check assumptions */
2284 assert(p != NULL);
2285 assert(q != NULL);
2286 assert(p->back != NULL);
2287 assert(q->back != NULL);
2288 assert(p->back == q);
2289 assert(q->back == p);
2290 p->back = NULL;
2291 q->back = NULL;
2292 }
2293
2294
2295 void link_trees(long local_nextnum, long nodenum, long local_nodenum,
2296 pointarray nodep)
2297 {
2298 if(local_nextnum == 0)
2299 hookup(nodep[nodenum], nodep[local_nodenum]);
2300 else if(local_nextnum == 1)
2301 hookup(nodep[nodenum], nodep[local_nodenum]->next);
2302 else if(local_nextnum == 2)
2303 hookup(nodep[nodenum], nodep[local_nodenum]->next->next);
2304 else
2305 printf("Error in Link_Trees()");
2306 } /* link_trees() */
2307
2308
2309 void allocate_nodep(pointarray *nodep, FILE **treefile, long *precalc_tips)
2310 { /* pre-compute space and allocate memory for nodep */
2311
2312 long numnodes; /* returns number commas & ( */
2313 long numcom = 0; /* returns number commas */
2314
2315 numnodes = countcomma(treefile, &numcom) + 1;
2316 *nodep = (pointarray)Malloc(2*numnodes*sizeof(node *));
2317
2318 (*precalc_tips) = numcom + 1; /* this will be used in placing the
2319 tip nodes in the front region of
2320 nodep. Used for species check? */
2321 } /* allocate_nodep -plc */
2322
2323
2324 void malloc_pheno (node *p, long endsite, long rcategs)
2325 { /* Allocate the phenotype arrays; used by dnaml */
2326 long i;
2327
2328 p->x = (phenotype)Malloc(endsite*sizeof(ratelike));
2329 p->underflows = (double *)Malloc(endsite * sizeof(double));
2330 for (i = 0; i < endsite; i++)
2331 p->x[i] = (ratelike)Malloc(rcategs*sizeof(sitelike));
2332 } /* malloc_pheno */
2333
2334
2335 void malloc_ppheno (node *p,long endsite, long rcategs)
2336 {
2337 /* Allocate the phenotype arrays; used by proml */
2338 long i;
2339
2340 p->protx = (pphenotype)Malloc(endsite*sizeof(pratelike));
2341 p->underflows = (double *)Malloc(endsite*sizeof(double));
2342
2343 for (i = 0; i < endsite; i++)
2344 p->protx[i] = (pratelike)Malloc(rcategs*sizeof(psitelike));
2345 } /* malloc_ppheno */
2346
2347
2348 long take_name_from_tree (Char *ch, Char *str, FILE *treefile)
2349 {
2350 /* This loop reads a name from treefile and stores it in *str.
2351 Returns the length of the name string. str must be at
2352 least MAXNCH bytes, but no effort is made to null-terminate
2353 the string. Underscores and newlines are converted to spaces.
2354 Characters beyond MAXNCH are discarded. */
2355
2356 long name_length = 0;
2357
2358 do {
2359 /*if ((*ch) == '_')
2360 (*ch) = ' ';*/
2361 //if ( name_length < MAXNCH )
2362 str[name_length++] = (*ch);
2363 if (eoln(treefile))
2364 scan_eoln(treefile);
2365 (*ch) = gettc(treefile);
2366 if (*ch == '\n') (*ch) = gettc(treefile);
2367 // *ch = ' ';
2368 } while ( strchr(":,)[;", *ch) == NULL );
2369
2370 str[name_length] = 0;
2371 return name_length;
2372 } /* take_name_from_tree */
2373
2374
2375 void match_names_to_data (Char *str, pointarray treenode, node **p, long spp)
2376 {
2377 /* This loop matches names taken from treefile to indexed names in
2378 the data file */
2379
2380 boolean found;
2381 long i, n;
2382 int l;
2383
2384 n = 1;
2385 do {
2386 found = true;
2387 //for (i = 0; i < nmlngth; i++) {
2388 l = strlen(str) + 1;
2389 for (i = 0; i < l; i++) {
2390 found = (found && ((str[i] == nayme[n - 1][i]) ||
2391 (((nayme[n - 1][i] == '_') && (str[i] == ' ')) ||
2392 ((nayme[n - 1][i] == ' ') && (str[i] == '\0')))));
2393 }
2394
2395 if (found)
2396 *p = treenode[n - 1];
2397 else
2398 n++;
2399
2400 } while (!(n > spp || found));
2401
2402 if (n > spp) {
2403 printf("\n\nERROR: Cannot find species: ");
2404 for (i = 0; (str[i] != '\0') && (i < MAXNCH); i++)
2405 putchar(str[i]);
2406 printf(" in data file\n\n");
2407 exxit(-1);
2408 }
2409 } /* match_names_to_data */
2410
2411
2412 void addelement(node **p, node *q, Char *ch, long *parens, FILE *treefile,
2413 pointarray treenode, boolean *goteof, boolean *first, pointarray nodep,
2414 long *nextnode, long *ntips, boolean *haslengths, node **grbg,
2415 initptr initnode, boolean unifok, long maxnodes)
2416 {
2417 /* Recursive procedure adds nodes to user-defined tree
2418 This is the main (new) tree-reading procedure */
2419
2420 node *pfirst;
2421 long i, len = 0, nodei = 0;
2422 boolean notlast;
2423 //Char str[MAXNCH+1];
2424 Char str[500+1];
2425 node *r;
2426 long furs = 0;
2427
2428
2429 if ((*ch) == '(') {
2430 (*nextnode)++; /* get ready to use new interior node */
2431 nodei = *nextnode; /* do what needs to be done at bottom */
2432 if ( maxnodes != -1 && nodei > maxnodes) {
2433 printf("ERROR in input tree file: Attempting to allocate too\n");
2434 printf("many nodes. This is usually caused by a unifurcation.\n");
2435 printf("To use this tree with this program use Retree to read\n");
2436 printf("and write this tree.\n");
2437 exxit(-1);
2438 }
2439
2440 /* do what needs to be done at bottom */
2441 (*initnode)(p, grbg, q, len, nodei, ntips,
2442 parens, bottom, treenode, nodep, str, ch, treefile);
2443 pfirst = (*p);
2444 notlast = true;
2445 while (notlast) { /* loop through immediate descendants */
2446 furs++;
2447 (*initnode)(&(*p)->next, grbg, q,
2448 len, nodei, ntips, parens, nonbottom, treenode,
2449 nodep, str, ch, treefile);
2450 /* ... doing what is done before each */
2451 r = (*p)->next;
2452 getch(ch, parens, treefile); /* look for next character */
2453
2454 /* handle blank names */
2455 if((*ch) == ',' || (*ch) == ':'){
2456 ungetc((*ch), treefile);
2457 *ch = 0;
2458 } else if((*ch)==')'){
2459 ungetc((*ch), treefile);
2460 (*parens)++;
2461 *ch = 0;
2462 }
2463
2464 addelement(&(*p)->next->back, (*p)->next, ch, parens, treefile,
2465 treenode, goteof, first, nodep, nextnode, ntips,
2466 haslengths, grbg, initnode, unifok, maxnodes);
2467
2468 (*initnode)(&r, grbg, q, len, nodei, ntips,
2469 parens, hslength, treenode, nodep, str, ch, treefile);
2470 /* do what is done after each about length */
2471 pfirst->numdesc++; /* increment number of descendants */
2472 *p = r; /* make r point back to p */
2473
2474 if ((*ch) == ')') {
2475 notlast = false;
2476 do {
2477 getch(ch, parens, treefile);
2478 } while ((*ch) != ',' && (*ch) != ')' &&
2479 (*ch) != '[' && (*ch) != ';' && (*ch) != ':');
2480 }
2481 }
2482 if ( furs <= 1 && !unifok ) {
2483 printf("ERROR in input tree file: A Unifurcation was detetected.\n");
2484 printf("To use this tree with this program use retree to read and");
2485 printf(" write this tree\n");
2486 exxit(-1);
2487 }
2488
2489 (*p)->next = pfirst;
2490 (*p) = pfirst;
2491
2492 } else if ((*ch) != ')') { /* if it's a species name */
2493 for (i = 0; i < MAXNCH+1; i++) /* fill string with nulls */
2494 str[i] = '\0';
2495
2496 len = take_name_from_tree (ch, str, treefile); /* get the name */
2497
2498 if ((*ch) == ')')
2499 (*parens)--; /* decrement count of open parentheses */
2500 (*initnode)(p, grbg, q, len, nodei, ntips,
2501 parens, tip, treenode, nodep, str, ch, treefile);
2502 /* do what needs to be done at a tip */
2503 } else
2504 getch(ch, parens, treefile);
2505 if (q != NULL)
2506 hookup(q, (*p)); /* now hook up */
2507 (*initnode)(p, grbg, q, len, nodei, ntips,
2508 parens, iter, treenode, nodep, str, ch, treefile);
2509 /* do what needs to be done to variable iter */
2510 if ((*ch) == ':')
2511 (*initnode)(p, grbg, q, len, nodei, ntips,
2512 parens, length, treenode, nodep, str, ch, treefile);
2513 /* do what needs to be done with length */
2514 else if ((*ch) != ';' && (*ch) != '[')
2515 (*initnode)(p, grbg, q, len, nodei, ntips,
2516 parens, hsnolength, treenode, nodep, str, ch, treefile);
2517 /* ... or what needs to be done when no length */
2518 if ((*ch) == '[')
2519 (*initnode)(p, grbg, q, len, nodei, ntips,
2520 parens, treewt, treenode, nodep, str, ch, treefile);
2521 /* ... for processing a tree weight */
2522 else if ((*ch) == ';') /* ... and at end of tree */
2523 (*initnode)(p, grbg, q, len, nodei, ntips,
2524 parens, unittrwt, treenode, nodep, str, ch, treefile);
2525 } /* addelement */
2526
2527
2528 void treeread (FILE *treefile, node **root, pointarray treenode,
2529 boolean *goteof, boolean *first, pointarray nodep,
2530 long *nextnode, boolean *haslengths, node **grbg, initptr initnode,
2531 boolean unifok, long maxnodes)
2532 {
2533 /* read in user-defined tree and set it up */
2534 /* Eats blank lines and everything up to the first open paren, then
2535 * calls the recursive function addelement, which builds the
2536 * tree and calls back to initnode. */
2537 char ch;
2538 long parens = 0;
2539 long ntips = 0;
2540
2541 (*goteof) = false;
2542 (*nextnode) = spp;
2543
2544 /* eat blank lines */
2545 while (eoln(treefile) && !eoff(treefile))
2546 scan_eoln(treefile);
2547
2548 if (eoff(treefile)) {
2549 (*goteof) = true;
2550 return;
2551 }
2552
2553 getch(&ch, &parens, treefile);
2554
2555 while (ch != '(') {
2556 /* Eat everything in the file (i.e. digits, tabs) until you
2557 encounter an open-paren */
2558 getch(&ch, &parens, treefile);
2559 }
2560 if (haslengths != NULL)
2561 *haslengths = true;
2562 addelement(root, NULL, &ch, &parens, treefile,
2563 treenode, goteof, first, nodep, nextnode, &ntips,
2564 haslengths, grbg, initnode, unifok, maxnodes);
2565
2566 /* Eat blank lines and end of current line*/
2567 do {
2568 scan_eoln(treefile);
2569 }
2570 while (eoln(treefile) && !eoff(treefile));
2571
2572 if (first)
2573 *first = false;
2574 if (parens != 0) {
2575 printf("\n\nERROR in tree file: unmatched parentheses\n\n");
2576 exxit(-1);
2577 }
2578 } /* treeread */
2579
2580
2581 void addelement2(node *q, Char *ch, long *parens, FILE *treefile,
2582 pointarray treenode, boolean lngths, double *trweight, boolean *goteof,
2583 long *nextnode, long *ntips, long no_species, boolean *haslengths,
2584 boolean unifok, long maxnodes)
2585 {
2586 /* recursive procedure adds nodes to user-defined tree
2587 -- old-style bifurcating-only version */
2588
2589 node *pfirst = NULL, *p;
2590 long i, len, current_loop_index;
2591 boolean notlast, minusread;
2592 Char str[MAXNCH];
2593 double valyew, divisor;
2594 long furs = 0;
2595
2596 if ((*ch) == '(') {
2597
2598 current_loop_index = (*nextnode) + spp;
2599 (*nextnode)++;
2600
2601 if ( maxnodes != -1 && current_loop_index > maxnodes) {
2602 printf("ERROR in intree file: Attempting to allocate too many nodes\n");
2603 printf("This is usually caused by a unifurcation. To use this\n");
2604 printf("intree with this program use retree to read and write\n");
2605 printf("this tree.\n");
2606 exxit(-1);
2607 }
2608 /* This is an assignment of an interior node */
2609 p = treenode[current_loop_index];
2610 pfirst = p;
2611 notlast = true;
2612 while (notlast) {
2613 furs++;
2614 /* This while loop goes through a circle (triad for
2615 bifurcations) of nodes */
2616 p = p->next;
2617 /* added to ensure that non base nodes in loops have indices */
2618 p->index = current_loop_index + 1;
2619
2620 getch(ch, parens, treefile);
2621
2622 addelement2(p, ch, parens, treefile, treenode, lngths, trweight,
2623 goteof, nextnode, ntips, no_species, haslengths, unifok, maxnodes);
2624
2625 if ((*ch) == ')') {
2626 notlast = false;
2627 do {
2628 getch(ch, parens, treefile);
2629 } while ((*ch) != ',' && (*ch) != ')' &&
2630 (*ch) != '[' && (*ch) != ';' && (*ch) != ':');
2631 }
2632 }
2633 if ( furs <= 1 && !unifok ) {
2634 printf("ERROR in intree file: A Unifurcation was detected.\n");
2635 printf("To use this intree with this program use retree to read and");
2636 printf(" write this tree\n");
2637 exxit(-1);
2638 }
2639
2640 } else if ((*ch) != ')') {
2641 for (i = 0; i < MAXNCH; i++)
2642 str[i] = '\0';
2643 len = take_name_from_tree (ch, str, treefile);
2644 match_names_to_data (str, treenode, &p, spp);
2645 pfirst = p;
2646 if ((*ch) == ')')
2647 (*parens)--;
2648 (*ntips)++;
2649 strncpy (p->nayme, str, len);
2650 } else
2651 getch(ch, parens, treefile);
2652
2653 if ((*ch) == '[') { /* getting tree weight from last comment field */
2654 if (!eoln(treefile)) {
2655 if (fscanf(treefile, "%lf", trweight) == 1) {
2656 getch(ch, parens, treefile);
2657 if (*ch != ']') {
2658 printf("\n\nERROR: Missing right square bracket\n\n");
2659 exxit(-1);
2660 }
2661 else {
2662 getch(ch, parens, treefile);
2663 if (*ch != ';') {
2664 printf("\n\nERROR: Missing semicolon after square brackets\n\n");
2665 exxit(-1);
2666 }
2667 }
2668 }
2669 else {
2670 printf("\n\nERROR: Expecting tree weight in last comment field.\n\n");
2671 exxit(-1);
2672 }
2673 }
2674 }
2675 else if ((*ch) == ';') {
2676 (*trweight) = 1.0 ;
2677 if (!eoln(treefile))
2678 printf("WARNING: tree weight set to 1.0\n");
2679 }
2680 else if (haslengths != NULL)
2681 (*haslengths) = ((*haslengths) && q == NULL);
2682
2683 if (q != NULL)
2684 hookup(q, pfirst);
2685
2686 if ((*ch) == ':') {
2687 processlength(&valyew, &divisor, ch,
2688 &minusread, treefile, parens);
2689 if (q != NULL) {
2690 if (!minusread)
2691 q->oldlen = valyew / divisor;
2692 else
2693 q->oldlen = 0.0;
2694 if (lngths) {
2695 q->v = valyew / divisor;
2696 q->back->v = q->v;
2697 q->iter = false;
2698 q->back->iter = false;
2699 }
2700 }
2701 }
2702
2703 } /* addelement2 */
2704
2705
2706 void treeread2 (FILE *treefile, node **root, pointarray treenode,
2707 boolean lngths, double *trweight, boolean *goteof,
2708 boolean *haslengths, long *no_species, boolean unifok, long maxnodes)
2709 {
2710 /* read in user-defined tree and set it up
2711 -- old-style bifurcating-only version */
2712 char ch;
2713 long parens = 0;
2714 long ntips = 0;
2715 long nextnode;
2716
2717 (*goteof) = false;
2718 nextnode = 0;
2719
2720 /* Eats all blank lines at start of file */
2721 while (eoln(treefile) && !eoff(treefile))
2722 scan_eoln(treefile);
2723
2724 if (eoff(treefile)) {
2725 (*goteof) = true;
2726 return;
2727 }
2728
2729 getch(&ch, &parens, treefile);
2730
2731 while (ch != '(') {
2732 /* Eat everything in the file (i.e. digits, tabs) until you
2733 encounter an open-paren */
2734 getch(&ch, &parens, treefile);
2735 }
2736
2737 addelement2(NULL, &ch, &parens, treefile, treenode, lngths, trweight,
2738 goteof, &nextnode, &ntips, (*no_species), haslengths, unifok, maxnodes);
2739 (*root) = treenode[*no_species];
2740
2741 /*eat blank lines */
2742 while (eoln(treefile) && !eoff(treefile))
2743 scan_eoln(treefile);
2744
2745 (*root)->oldlen = 0.0;
2746
2747 if (parens != 0) {
2748 printf("\n\nERROR in tree file: unmatched parentheses\n\n");
2749 exxit(-1);
2750 }
2751 } /* treeread2 */
2752
2753
2754 void exxit(int exitcode)
2755 { /* Terminate the program with exit code exitcode.
2756 * On Windows, supplying a nonzero exitcode will print a message and wait
2757 * for the user to hit enter. */
2758
2759 #ifdef _WIN32
2760 phyRestoreConsoleAttributes();
2761 #endif
2762
2763 exit (exitcode);
2764 } /* exxit */
2765
2766
2767 char gettc(FILE* file)
2768 { /* Return the next character in file.
2769 * If EOF is reached, print an error and die.
2770 * DOS ('\r\n') and Mac ('\r') newlines are returned as a single '\n'. */
2771 int ch;
2772
2773 ch=getc(file);
2774
2775 if ( ch == EOF )
2776 EOF_error();
2777
2778 if ( ch == '\r' ) {
2779 ch = getc(file);
2780 if ( ch != '\n' )
2781 ungetc(ch, file);
2782 ch = '\n';
2783 }
2784 return ch;
2785 } /* gettc */
2786
2787 void unroot(tree *t, long nonodes)
2788 {
2789 /* used by fitch, restml and contml */
2790 if (t->start->back == NULL) {
2791 if (t->start->next->back->tip)
2792 t->start = t->start->next->next->back;
2793 else t->start = t->start->next->back;
2794 }
2795 if (t->start->next->back == NULL) {
2796 if (t->start->back->tip)
2797 t->start = t->start->next->next->back;
2798 else t->start = t->start->back;
2799 }
2800 if (t->start->next->next->back == NULL) {
2801 if (t->start->back->tip)
2802 t->start = t->start->next->back;
2803 else t->start = t->start->back;
2804 }
2805
2806
2807 unroot_r(t->start,t->nodep,nonodes);
2808 unroot_r(t->start->back, t->nodep, nonodes);
2809 }
2810
2811
2812 void unroot_here(node* root, node** nodep, long nonodes)
2813 {
2814 node* tmpnode;
2815 double newl;
2816 /* used by unroot */
2817 /* assumes bifurcation this is ok in the programs that use it */
2818
2819 newl = root->next->oldlen + root->next->next->oldlen;
2820 root->next->back->oldlen = newl;
2821 root->next->next->back->oldlen = newl;
2822
2823 newl = root->next->v + root->next->next->v;
2824 root->next->back->v = newl;
2825 root->next->next->back->v = newl;
2826
2827 root->next->back->back=root->next->next->back;
2828 root->next->next->back->back = root->next->back;
2829
2830 while ( root->index != nonodes ) {
2831 tmpnode = nodep[ root->index ];
2832 nodep[root->index] = root;
2833 root->index++;
2834 root->next->index++;
2835 root->next->next->index++;
2836 nodep[root->index - 2] = tmpnode;
2837 tmpnode->index--;
2838 tmpnode->next->index--;
2839 tmpnode->next->next->index--;
2840 }
2841 }
2842
2843
2844 void unroot_r(node* p, node** nodep, long nonodes)
2845 {
2846 /* used by unroot */
2847 node *q;
2848
2849 if ( p->tip) return;
2850
2851 q = p->next;
2852 while ( q != p ) {
2853 if (q->back == NULL)
2854 unroot_here(q, nodep, nonodes);
2855 else unroot_r(q->back, nodep, nonodes);
2856 q = q->next;
2857 }
2858 }
2859
2860 void clear_connections(tree *t, long nonodes)
2861 {
2862 long i;
2863 node *p;
2864 for ( i = 0 ; i < nonodes ; i++) {
2865 p = t->nodep[i];
2866 if (p != NULL) {
2867 p->back = NULL;
2868 p->v = 0;
2869 for (p = p->next; p && p != t->nodep[i]; p = p->next) {
2870 p->next->back = NULL;
2871 p->next->v = 0;
2872 }
2873 }
2874 }
2875 }
2876
2877 #ifdef _WIN32
2878 void phySaveConsoleAttributes()
2879 {
2880 if ( GetConsoleScreenBufferInfo(hConsoleOutput, &savecsbi) )
2881 savecsbi_valid = true;
2882 } /* PhySaveConsoleAttributes */
2883
2884
2885 void phySetConsoleAttributes()
2886 {
2887 hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2888
2889 if ( hConsoleOutput == INVALID_HANDLE_VALUE )
2890 hConsoleOutput = NULL;
2891
2892 if ( hConsoleOutput != NULL ) {
2893 phySaveConsoleAttributes();
2894
2895 SetConsoleTextAttribute(hConsoleOutput,
2896 BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
2897 }
2898 } /* phySetConsoleAttributes */
2899
2900
2901 void phyRestoreConsoleAttributes()
2902 {
2903 COORD coordScreen = { 0, 0 };
2904 DWORD cCharsWritten;
2905 DWORD dwConSize;
2906
2907 printf("Press enter to quit.\n");
2908 fflush(stdout);
2909 getchar();
2910
2911 if ( savecsbi_valid ) {
2912 dwConSize = savecsbi.dwSize.X * savecsbi.dwSize.Y;
2913
2914 SetConsoleTextAttribute(hConsoleOutput, savecsbi.wAttributes);
2915
2916 FillConsoleOutputAttribute( hConsoleOutput, savecsbi.wAttributes,
2917 dwConSize, coordScreen, &cCharsWritten );
2918 }
2919 } /* phyRestoreConsoleAttributes */
2920
2921
2922 void phyFillScreenColor()
2923 {
2924 COORD coordScreen = { 0, 0 };
2925 DWORD cCharsWritten;
2926 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
2927 DWORD dwConSize;
2928
2929 if ( GetConsoleScreenBufferInfo( hConsoleOutput, &csbi ) ) {
2930 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
2931
2932 FillConsoleOutputAttribute( hConsoleOutput, csbi.wAttributes,
2933 dwConSize, coordScreen, &cCharsWritten );
2934 }
2935 } /* phyFillScreenColor */
2936
2937
2938 void phyClearScreen()
2939 {
2940 COORD coordScreen = { 0, 0 }; /* here's where we'll home the
2941 cursor */
2942 DWORD cCharsWritten;
2943 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
2944 DWORD dwConSize; /* number of character cells in
2945 the current buffer */
2946
2947 /* get the number of character cells in the current buffer */
2948
2949 if ( GetConsoleScreenBufferInfo(hConsoleOutput, &csbi) ) {
2950 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
2951
2952 /* fill the entire screen with blanks */
2953
2954 FillConsoleOutputCharacter( hConsoleOutput, (TCHAR) ' ',
2955 dwConSize, coordScreen, &cCharsWritten );
2956
2957 /* get the current text attribute */
2958 GetConsoleScreenBufferInfo( hConsoleOutput, &csbi );
2959
2960 /* now set the buffer's attributes accordingly */
2961 FillConsoleOutputAttribute( hConsoleOutput, csbi.wAttributes,
2962 dwConSize, coordScreen, &cCharsWritten );
2963
2964 /* put the cursor at (0, 0) */
2965 SetConsoleCursorPosition( hConsoleOutput, coordScreen );
2966 }
2967 } /* phyClearScreen */
2968 #endif /* _WIN32 */
2969
2970 /* These functions are temporarily used for translating the fixed-width
2971 * space-padded nayme array to an array of null-terminated char *. */
2972 char **stringnames_new(void)
2973 {
2974 /* Copy nayme array to null terminated strings and return array of char *.
2975 * Spaces are stripped from end of naym's.
2976 * Returned array size is spp+1; last element is NULL. */
2977
2978 char **names;
2979 char *ch;
2980 long len, i;
2981
2982 names = (char **)Malloc((spp+1) * sizeof(char *));
2983
2984 for ( i = 0; i < spp; i++ ) {
2985 len = strlen(nayme[i]);
2986 names[i] = (char *)Malloc((MAXNCH+1) * sizeof(char));
2987 strncpy(names[i], nayme[i], MAXNCH);
2988 names[i][MAXNCH] = '\0';
2989 /* Strip trailing spaces */
2990 for ( ch = names[i] + MAXNCH - 1; *ch == ' ' || *ch == '\0'; ch-- )
2991 *ch = '\0';
2992 }
2993 names[spp] = NULL;
2994
2995 return names;
2996 }
2997
2998 void stringnames_delete(char **names)
2999 {
3000 /* Free a string array returned by stringnames_new() */
3001 long i;
3002
3003 assert( names != NULL );
3004 for ( i = 0; i < spp; i++ ) {
3005 assert( names[i] != NULL );
3006 free(names[i]);
3007 }
3008 free(names);
3009 }
3010
3011 int fieldwidth_double(double val, unsigned int precision)
3012 {
3013 /* Printf a double to a temporary buffer with specified precision using %g
3014 * and return its length. Precision must not be greater than 999,999 */
3015
3016 char format[10];
3017 char buf[0x200]; /* TODO: What's the largest possible? */
3018
3019 if (precision > 999999)
3020 abort();
3021
3022 snprintf(format, 10, "%%.%uf", precision); /* %.Nf */
3023 /* snprintf() would be better, but is it avaliable on all systems? */
3024 return snprintf(buf, sizeof(buf), format, val);
3025 }
3026
3027 void output_matrix_d(FILE *fp, double **matrix,
3028 unsigned long rows, unsigned long cols,
3029 char **row_head, char **col_head, int flags)
3030 {
3031 /*
3032 * Print a matrix of double to file. Headings are given in row_head and
3033 * col_head, either of which may be NULL to indicate that headings should not
3034 * be printed. Otherwise, they must be null-terminated arrays of pointers to
3035 * null-terminalted character arrays.
3036 *
3037 * The macro OUTPUT_PRECISION defines the number of significant figures to
3038 * print, and OUTPUT_TEXTWIDTH defines the maximum length of each line.
3039 *
3040 * Optional formatting is specified by flags argument, using macros MAT_*
3041 * defined in phylip.h.
3042 */
3043
3044 unsigned *colwidth; /* [0..spp-1] min width of each column */
3045 unsigned headwidth; /* min width of row header column */
3046 unsigned long linelen; /* length of current printed line */
3047 unsigned fw;
3048 unsigned long row, col;
3049 unsigned long i;
3050 unsigned long cstart, cend;
3051 unsigned long textwidth = OUTPUT_TEXTWIDTH;
3052 const unsigned int gutter = 1;
3053 boolean do_block;
3054 boolean lower_triangle;
3055 boolean border;
3056 boolean output_cols;
3057 boolean pad_row_head;
3058
3059 if ( flags & MAT_NOHEAD )
3060 col_head = NULL;
3061 if ( flags & MAT_NOBREAK )
3062 textwidth = 0;
3063 do_block = (flags & MAT_BLOCK) && (textwidth > 0);
3064 lower_triangle = flags & MAT_LOWER;
3065 border = flags & MAT_BORDER;
3066 output_cols = flags & MAT_PCOLS;
3067 pad_row_head = flags & MAT_PADHEAD;
3068
3069 /* Determine minimal width for row headers, if given */
3070 headwidth = 0;
3071 if ( row_head != NULL ) {
3072 for (row = 0; row < rows; row++) {
3073 fw = strlen(row_head[row]);
3074 if ( headwidth < fw )
3075 headwidth = fw;
3076 }
3077 }
3078
3079 /* Enforce minimum of 10 ch for machine-readable output */
3080 if ( (pad_row_head) && (headwidth < 10) )
3081 headwidth = 10;
3082
3083 /* Determine minimal width for each matrix col */
3084 colwidth = (unsigned int *)Malloc(spp * sizeof(int));
3085 for (col = 0; col < cols; col++) {
3086 if ( col_head != NULL )
3087 colwidth[col] = strlen(col_head[col]);
3088 else
3089 colwidth[col] = 0;
3090 for (row = 0; row < rows; row++) {
3091 fw = fieldwidth_double(matrix[row][col], PRECISION);
3092 if ( colwidth[col] < fw )
3093 colwidth[col] = fw;
3094 }
3095 }
3096
3097 /*** Print the matrix ***/
3098 /* Number of columns if requested */
3099 if ( output_cols ) {
3100 fprintf(fp, "%5lu\n", cols);
3101 }
3102
3103 /* Omit last column for lower triangle */
3104 if ( lower_triangle )
3105 cols--;
3106
3107 /* Blocks */
3108 cstart = cend = 0;
3109 while ( cend != cols ) {
3110 if ( do_block ) {
3111 linelen = headwidth;
3112 for ( col = cstart; col < cols; col++ ) {
3113 if ( linelen + colwidth[col] + gutter > textwidth ) {
3114 break;
3115 }
3116 linelen += colwidth[col] + gutter;
3117 }
3118 cend = col;
3119 /* Always print at least one, regardless of line len */
3120 if ( cend == cstart )
3121 cend++;
3122 } else {
3123 cend = cols;
3124 }
3125
3126
3127 /* Column headers */
3128 if ( col_head != NULL ) {
3129 /* corner space */
3130 for ( i = 0; i < headwidth; i++ )
3131 putc(' ', fp);
3132 if ( border ) {
3133 for ( i = 0; i < gutter+1; i++ )
3134 putc(' ', fp);
3135 }
3136 /* Names */
3137 for ( col = cstart; col < cend; col++ ) {
3138 for ( i = 0; i < gutter; i++ )
3139 putc(' ', fp);
3140 /* right justify */
3141 fw = strlen(col_head[col]);
3142 for ( i = 0; i < colwidth[col] - fw; i++ )
3143 putc(' ', fp);
3144 fputs(col_head[col], fp);
3145 }
3146 putc('\n', fp);
3147 }
3148
3149 /* Top border */
3150 if ( border ) {
3151 for ( i = 0; i < headwidth + gutter; i++ )
3152 putc(' ', fp);
3153 putc('\\', fp);
3154 for ( col = cstart; col < cend; col++ ) {
3155 for ( i = 0; i < colwidth[col] + gutter; i++ )
3156 putc('-', fp);
3157 }
3158 putc('\n', fp);
3159 }
3160
3161 /* Rows */
3162 for (row = 0; row < rows; row++) {
3163 /* Row header, if given */
3164 if ( row_head != NULL ) {
3165 /* right-justify for non-machine-readable */
3166 if ( !pad_row_head ) {
3167 for ( i = strlen(row_head[row]); i < headwidth; i++ )
3168 putc(' ', fp);
3169 }
3170 fputs(row_head[row], fp);
3171 /* left-justify for machine-readable */
3172 if ( pad_row_head ) {
3173 for ( i = strlen(row_head[row]); i < headwidth; i++ )
3174 putc(' ', fp);
3175 }
3176 }
3177 linelen = headwidth;
3178
3179 /* Left border */
3180 if ( border ) {
3181 for ( i = 0; i < gutter; i++ )
3182 putc(' ', fp);
3183 putc('|', fp);
3184 linelen += 2;
3185 }
3186
3187 /* Row data */
3188 for (col = cstart; col < cend; col++) { /* cols */
3189 /* Stop after col == row for lower triangle */
3190 if ( lower_triangle && col >= row )
3191 break;
3192 /* Break line if going over max text width */
3193 if ( !do_block && textwidth > 0 ) {
3194 if ( linelen + colwidth[col] > textwidth ) {
3195 putc('\n', fp);
3196 linelen = 0;
3197 }
3198 linelen += colwidth[col] + gutter;
3199 }
3200
3201 for ( i = 0; i < gutter; i++ )
3202 putc(' ', fp);
3203
3204 /* Print the datum */
3205 fprintf(fp, "%*.6f", colwidth[col], matrix[row][col]);
3206 }
3207 putc('\n', fp);
3208 } /* End of row */
3209 if (col_head != NULL)
3210 putc('\n', fp); /* blank line */
3211 cstart = cend;
3212 } /* End of block */
3213 free(colwidth);
3214 } /* output_matrix_d */
3215