source: branches/profile/GDE/PHYML20130708/phyml/src/utilities.c

Last change on this file was 10307, checked in by aboeckma, 12 years ago

added most recent version of phyml

File size: 250.5 KB
Line 
1/*
2
3PhyML:  a program that  computes maximum likelihood phylogenies from
4DNA or AA homologous sequences.
5
6Copyright (C) Stephane Guindon. Oct 2003 onward.
7
8All parts of the source except where indicated are distributed under
9the GNU public licence. See http://www.opensource.org for details.
10
11*/
12
13#include "utilities.h"
14
15//////////////////////////////////////////////////////////////
16//////////////////////////////////////////////////////////////
17
18phydbl String_To_Dbl(char *string)
19{
20  phydbl buff;
21  char *endptr;
22
23  if(!string)
24    {
25      PhyML_Printf("\n== String object empty.");
26      PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);     
27      Exit("\n");
28    }
29
30
31  buff = strtod(string,&endptr);
32  if(string == endptr || errno == ERANGE)
33    {
34      PhyML_Printf("\n== Error in translating string '%s' to double.",string);
35      Exit("\n");
36    }
37  return buff;
38}
39
40//////////////////////////////////////////////////////////////
41//////////////////////////////////////////////////////////////
42
43void Unroot_Tree(char **subtrees)
44{
45  char **tmp_sub;
46  int degree,i,j;
47
48  PhyML_Printf("\n. Removing the root...\n");
49 
50  tmp_sub = Sub_Trees(subtrees[0],&degree);
51  if(degree >= 2)
52    {
53      strcpy(subtrees[2],subtrees[1]);
54      Clean_Multifurcation(tmp_sub,degree,2);
55      For(j,2) strcpy(subtrees[j],tmp_sub[j]);
56    }
57  else
58    {
59      tmp_sub = Sub_Trees(subtrees[1],&degree);
60      strcpy(subtrees[2],subtrees[0]);
61      Clean_Multifurcation(tmp_sub,degree,2);
62      For(j,2) strcpy(subtrees[j],tmp_sub[j]);
63    }
64
65  For(i,degree) Free(tmp_sub[i]);
66  Free(tmp_sub);
67}
68
69//////////////////////////////////////////////////////////////
70//////////////////////////////////////////////////////////////
71
72void Make_Edge_Dirs(t_edge *b, t_node *a, t_node *d, t_tree *tree)
73{
74  int i;
75 
76  if(a == b->rght)
77    {
78      PhyML_Printf("\n== a->num = %3d ; d->num = %3d",a->num,d->num);
79      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
80      Exit("\n");
81    }
82
83  if(d == b->left)
84    {
85      PhyML_Printf("\n== a->num = %3d ; d->num = %3d",a->num,d->num);
86      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
87      Exit("\n");
88    }
89
90  b->l_r = b->r_l = -1;
91  For(i,3)
92    {
93      /* if((a->v[i]) && ((a->v[i] == d) || (e_root && a->b[i] == e_root))) */
94      if((a->v[i]) && ((a->v[i] == d)))
95        {
96          b->l_r  = i; /* we consider here that 'a' is on the left handside of 'b'*/
97          a->b[i] = b;
98        }
99      /* if((d->v[i]) && ((d->v[i] == a) || (e_root && d->b[i] == e_root))) */
100      if((d->v[i]) && ((d->v[i] == a)))
101        {
102          b->r_l  = i; /* we consider here that 'd' is on the right handside of 'b'*/
103          d->b[i] = b;
104        }
105    }
106
107  if(a->tax) {b->r_l = 0; For(i,3) if(d->v[i]==a) {b->l_r = i; break;}}
108
109  b->l_v1 = b->l_v2 = b->r_v1 = b->r_v2 = -1;
110  For(i,3)
111    {
112      if(b->left->v[i] != b->rght)
113        {
114          if(b->l_v1 < 0) b->l_v1 = i;
115          else            b->l_v2 = i;
116        }
117
118      if(b->rght->v[i] != b->left)
119        {
120          if(b->r_v1 < 0) b->r_v1 = i;
121          else            b->r_v2 = i;
122        }
123    }
124}
125
126//////////////////////////////////////////////////////////////
127//////////////////////////////////////////////////////////////
128
129//////////////////////////////////////////////////////////////
130//////////////////////////////////////////////////////////////
131
132//////////////////////////////////////////////////////////////
133//////////////////////////////////////////////////////////////
134
135
136void Restrict_To_Coding_Position(align **data, option *io)
137{
138  int i,j,curr_pos;
139 
140  if(io->codpos != -1)
141    {
142      For(i,io->n_otu) 
143        {
144          curr_pos = 0; 
145          for(j=io->codpos-1;j<data[i]->len;j+=3) 
146            {
147              data[i]->state[curr_pos] = data[i]->state[j]; 
148              curr_pos++; 
149            }
150          data[i]->len /= 3;
151        }
152    } 
153}
154
155
156
157void Uppercase(char *ch)
158{
159  /* convert ch to upper case -- either ASCII or EBCDIC */
160   *ch = isupper((int)*ch) ? *ch : toupper((int)*ch);
161}
162
163//////////////////////////////////////////////////////////////
164//////////////////////////////////////////////////////////////
165
166
167void Lowercase(char *ch)
168{
169  /* convert ch to upper case -- either ASCII or EBCDIC */
170  *ch = isupper((int)*ch) ? tolower((int)*ch) : *ch;
171}
172
173//////////////////////////////////////////////////////////////
174//////////////////////////////////////////////////////////////
175
176calign *Compact_Data(align **data, option *io)
177{
178  calign *cdata_tmp,*cdata;
179  int i,j,k,site;
180  int n_patt,which_patt,n_invar;
181  char **sp_names;
182  int n_otu, n_sites;
183  pnode *proot;
184  int compress;
185  int n_ambigu,is_ambigu;
186
187  n_otu      = io->n_otu;
188  n_patt     = 0;
189  which_patt = 0;
190
191  sp_names = (char **)mCalloc(n_otu,sizeof(char *));
192  For(i,n_otu)
193    {
194      sp_names[i] = (char *)mCalloc(T_MAX_NAME,sizeof(char));
195      strcpy(sp_names[i],data[i]->name);
196    }
197
198  cdata_tmp = Make_Cseq(n_otu,data[0]->len,io->state_len,data[0]->len,sp_names);
199  proot     = (pnode *)Create_Pnode(T_MAX_ALPHABET);
200 
201  For(i,n_otu) Free(sp_names[i]);
202  Free(sp_names);
203 
204  if(data[0]->len%io->state_len)
205    {
206      PhyML_Printf("\n== Sequence length is not a multiple of %d\n",io->state_len);
207      Exit("\n");
208    }
209 
210  compress = io->colalias;
211  n_ambigu = 0;
212  is_ambigu = 0;
213
214  if(!io->quiet && !compress) 
215    { 
216      PhyML_Printf("\n== WARNING: sequences are not compressed !\n");
217    }
218
219  Fors(site,data[0]->len,io->state_len)
220    {
221      if(io->rm_ambigu)
222        {
223          is_ambigu = 0;
224          For(j,n_otu) if(Is_Ambigu(data[j]->state+site,io->datatype,io->state_len)) break;
225          if(j != n_otu)
226            {
227              is_ambigu = 1;
228              n_ambigu++;
229            }
230        }
231
232      if(!is_ambigu)
233        {
234          if(compress)
235            {
236              which_patt = -1;
237
238              Traverse_Prefix_Tree(site,-1,&which_patt,&n_patt,data,io,proot);
239              if(which_patt == n_patt-1) /* New pattern found */
240                {
241                  n_patt--;
242                  k=n_patt;
243                }
244              else
245                {
246                  k = n_patt-10;
247                }
248            }
249          else
250            {
251              k = n_patt;
252            }
253         
254          if(k == n_patt) /* add a new site pattern */
255            {
256              For(j,n_otu)
257                Copy_One_State(data[j]->state+site,
258                               cdata_tmp->c_seq[j]->state+n_patt*io->state_len,
259                               io->state_len);
260                     
261              For(i,n_otu)
262                {
263                  For(j,n_otu)
264                    {
265                      if(!(Are_Compatible(cdata_tmp->c_seq[i]->state+n_patt*io->state_len,
266                                          cdata_tmp->c_seq[j]->state+n_patt*io->state_len,
267                                          io->state_len,
268                                          io->datatype))) break;
269                    }
270                  if(j != n_otu) break;
271                }
272             
273              if((j == n_otu) && (i == n_otu)) /* all characters at that site are compatible with one another:
274                                                  the site may be invariant */
275                {
276                  For(j,n_otu)
277                    {
278                      cdata_tmp->invar[n_patt] = Assign_State(cdata_tmp->c_seq[j]->state+n_patt*io->state_len,
279                                                              io->datatype,
280                                                              io->state_len);
281
282                      if(cdata_tmp->invar[n_patt] > -1.) break;
283                    }
284                }
285              else cdata_tmp->invar[n_patt] = -1;
286             
287              cdata_tmp->sitepatt[site] = n_patt;
288              cdata_tmp->wght[n_patt]  += 1;
289              n_patt                   += 1;
290            }
291          else
292            {
293              cdata_tmp->sitepatt[site]    = which_patt;
294              cdata_tmp->wght[which_patt] += 1;
295            }
296        }
297    }
298 
299  data[0]->len -= n_ambigu;
300 
301  cdata_tmp->init_len                   = data[0]->len;
302  cdata_tmp->crunch_len                 = n_patt;
303  For(i,n_otu) cdata_tmp->c_seq[i]->len = n_patt;
304 
305  if(!io->quiet) PhyML_Printf("\n. %d patterns found (out of a total of %d sites). \n",n_patt,data[0]->len);
306
307  if((io->rm_ambigu) && (n_ambigu)) PhyML_Printf("\n. Removed %d columns of the alignment as they contain ambiguous characters (e.g., gaps) \n",n_ambigu);
308
309/*   For(i,n_otu) */
310/*     { */
311/*       For(j,cdata_tmp->crunch_len) */
312/*      { */
313/*        printf("%c",cdata_tmp->c_seq[i]->state[j*io->state_len+1]); */
314/*      } */
315/*       printf("\n"); */
316/*     } */
317
318  n_invar=0;
319  For(i,cdata_tmp->crunch_len) 
320    {
321      if(cdata_tmp->invar[i] > -1.) n_invar+=(int)cdata_tmp->wght[i];
322    }
323
324  if(!io->quiet) PhyML_Printf("\n. %d sites without polymorphism (%.2f%c).\n",n_invar,100.*(phydbl)n_invar/data[0]->len,'%');
325 
326  cdata_tmp->obs_pinvar = (phydbl)n_invar/data[0]->len;
327
328  n_sites = 0;
329  For(i,cdata_tmp->crunch_len) n_sites += cdata_tmp->wght[i];
330  if(n_sites != data[0]->len / io->state_len)
331    {
332      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
333      Warn_And_Exit("");
334    }
335
336
337
338  if(io->datatype == NT)      Get_Base_Freqs(cdata_tmp);
339  else if(io->datatype == AA) Get_AA_Freqs(cdata_tmp);
340  else {/* Uniform state frequency distribution.*/}
341
342  cdata = Copy_Cseq(cdata_tmp,io);
343 
344  Free_Cseq(cdata_tmp);
345  Free_Prefix_Tree(proot,T_MAX_ALPHABET);
346
347  Check_Ambiguities(cdata,io->datatype,io->state_len);
348  Set_D_States(cdata,io->datatype,io->state_len);
349
350  return cdata;
351}
352
353//////////////////////////////////////////////////////////////
354//////////////////////////////////////////////////////////////
355
356
357calign *Compact_Cdata(calign *data, option *io)
358{
359  calign *cdata;
360  int i,j,k,site;
361  int n_patt,which_patt;
362  int n_otu;
363
364  n_otu = data->n_otu;
365
366  cdata         = (calign *)mCalloc(1,sizeof(calign));
367  cdata->n_otu  = n_otu;
368  cdata->c_seq  = (align **)mCalloc(n_otu,sizeof(align *));
369  cdata->wght   = (int *)mCalloc(data->crunch_len,sizeof(int));
370  cdata->b_frq  = (phydbl *)mCalloc(io->mod->ns,sizeof(phydbl));
371  cdata->ambigu = (short int *)mCalloc(data->crunch_len,sizeof(short int));
372  cdata->invar  = (short int *)mCalloc(data->crunch_len,sizeof(short int));
373
374  cdata->crunch_len = cdata->init_len = -1;
375  For(j,n_otu)
376    {
377      cdata->c_seq[j]            = (align *)mCalloc(1,sizeof(align));
378      cdata->c_seq[j]->name      = (char *)mCalloc(T_MAX_NAME,sizeof(char));
379      strcpy(cdata->c_seq[j]->name,data->c_seq[j]->name);
380      cdata->c_seq[j]->state     = (char *)mCalloc(data->crunch_len,sizeof(char));
381      cdata->c_seq[j]->is_ambigu = (short int *)mCalloc(data->crunch_len,sizeof(short int));
382      cdata->c_seq[j]->state[0]  = data->c_seq[j]->state[0];
383    }
384
385
386  n_patt = which_patt =  0;
387
388  For(site,data->crunch_len)
389    {
390      if(data->wght[site])
391        {
392          For(k,n_patt)
393            {
394              For(j,n_otu)
395                {
396                  if(strncmp(cdata->c_seq[j]->state+k*io->state_len,
397                             data->c_seq[j]->state+site*io->state_len,
398                             io->state_len))
399                    break;
400                }
401             
402              if(j == n_otu)
403                {
404                  which_patt = k;
405                  break;
406                }
407            }
408         
409          /*       /\* TO DO *\/ */
410          /*       k = n_patt; */
411         
412          if(k == n_patt)
413            {
414              For(j,n_otu) Copy_One_State(data->c_seq[j]->state+site*io->state_len,
415                                          cdata->c_seq[j]->state+n_patt*io->state_len,
416                                          io->state_len);
417             
418              For(i,n_otu)
419                {
420                  For(j,n_otu)
421                    {
422                      if(!(Are_Compatible(cdata->c_seq[i]->state+n_patt*io->state_len,
423                                          cdata->c_seq[j]->state+n_patt*io->state_len,
424                                          io->state_len,
425                                          io->datatype))) break;
426                    }
427                  if(j != n_otu) break;
428                }
429             
430              if((j == n_otu) && (i == n_otu)) 
431                {
432                  For(j,n_otu)
433                    {
434                      cdata->invar[n_patt] = Assign_State(cdata->c_seq[j]->state+n_patt*io->state_len,
435                                                          io->datatype,
436                                                          io->state_len);
437
438                      if(cdata->invar[n_patt] > -1.) break;
439                    }
440                }
441              else cdata->invar[n_patt] = -1;
442             
443              cdata->wght[n_patt] += data->wght[site];
444              n_patt+=1;
445            }
446          else cdata->wght[which_patt] += data->wght[site];
447         
448          /*       Print_Site(cdata,k,n_otu,"\n",io->stepsize); */
449        }
450    }
451 
452  cdata->init_len   = data->crunch_len;
453  cdata->crunch_len = n_patt;
454  For(i,n_otu) cdata->c_seq[i]->len = n_patt;
455
456  if(io->datatype == NT)      Get_Base_Freqs(cdata);
457  else if(io->datatype == AA) Get_AA_Freqs(cdata);
458  else {/* Not implemented yet */}
459
460  return cdata;
461}
462
463//////////////////////////////////////////////////////////////
464//////////////////////////////////////////////////////////////
465
466
467void Traverse_Prefix_Tree(int site, int seqnum, int *patt_num, int *n_patt, align **data, option *io, pnode *n)
468{       
469  if(seqnum == io->n_otu-1)
470    {   
471      n->weight++;
472      if(n->weight == 1)
473        {
474          n->num = *n_patt;
475          (*n_patt) += 1;
476        }
477      (*patt_num) = n->num;
478      return;
479    }
480  else
481    {
482      int next_state;
483
484      next_state = -1;
485      next_state = Assign_State_With_Ambiguity(data[seqnum+1]->state+site,
486                                               io->datatype,
487                                               io->state_len);
488
489      if(!n->next[next_state]) n->next[next_state] = Create_Pnode(T_MAX_ALPHABET);
490      Traverse_Prefix_Tree(site,seqnum+1,patt_num,n_patt,data,io,n->next[next_state]);
491    }
492               
493}
494
495//////////////////////////////////////////////////////////////
496//////////////////////////////////////////////////////////////
497
498
499pnode *Create_Pnode(int size)
500{
501  pnode *n;
502  int i;
503
504  n = (pnode *)mCalloc(1,sizeof(pnode ));
505  n->next = (pnode **)mCalloc(size,sizeof(pnode *));
506  For(i,size) n->next[i] = NULL;
507  n->weight = 0;
508  n->num = -1;
509  return n;
510}
511//////////////////////////////////////////////////////////////
512//////////////////////////////////////////////////////////////
513
514//////////////////////////////////////////////////////////////
515//////////////////////////////////////////////////////////////
516
517
518void Get_Base_Freqs(calign *data)
519{
520  int i,j,k;
521  phydbl A,C,G,T;
522  phydbl fA,fC,fG,fT;
523  int w;
524
525  fA = fC = fG = fT = .25;
526
527  For(k,8)
528    {
529      A = C = G = T = .0;
530      For(i,data->n_otu)
531        {
532          For(j,data->crunch_len)
533            {
534              w = data->wght[j];
535              if(w)
536                {
537                  switch(data->c_seq[i]->state[j])
538                    {
539                    case 'A' : A+=w;
540                      break;
541                    case 'C' : C+=w;
542                      break;
543                    case 'G' : G+=w;
544                      break;
545                    case 'T' : T+=w;
546                      break;
547                    case 'U' : T+=w;
548                      break;
549                    case 'M' : C+=w*fC/(fC+fA); A+=w*fA/(fA+fC);
550                      break;
551                    case 'R' : G+=w*fG/(fA+fG); A+=w*fA/(fA+fG);
552                      break;
553                    case 'W' : T+=w*fT/(fA+fT); A+=w*fA/(fA+fT);
554                      break;
555                    case 'S' : C+=w*fC/(fC+fG); G+=w*fG/(fC+fG);
556                      break;
557                    case 'Y' : C+=w*fC/(fC+fT); T+=w*fT/(fT+fC);
558                      break;
559                    case 'K' : G+=w*fG/(fG+fT); T+=w*fT/(fT+fG);
560                      break;
561                    case 'B' : C+=w*fC/(fC+fG+fT); G+=w*fG/(fC+fG+fT); T+=w*fT/(fC+fG+fT);
562                      break;
563                    case 'D' : A+=w*fA/(fA+fG+fT); G+=w*fG/(fA+fG+fT); T+=w*fT/(fA+fG+fT);
564                      break;
565                    case 'H' : A+=w*fA/(fA+fC+fT); C+=w*fC/(fA+fC+fT); T+=w*fT/(fA+fC+fT);
566                      break;
567                    case 'V' : A+=w*fA/(fA+fC+fG); C+=w*fC/(fA+fC+fG); G+=w*fG/(fA+fC+fG);
568                      break;
569                    case 'N' : case 'X' : case '?' : case 'O' : case '-' :
570                      A+=w*fA; C+=w*fC; G+=w*fG; T+=w*fT; break;
571                    default : break;
572                    }
573                }
574            }
575        }
576      fA = A/(A+C+G+T);
577      fC = C/(A+C+G+T);
578      fG = G/(A+C+G+T);
579      fT = T/(A+C+G+T);
580    }
581 
582  data->b_frq[0] = fA;
583  data->b_frq[1] = fC;
584  data->b_frq[2] = fG;
585  data->b_frq[3] = fT;
586}
587
588//////////////////////////////////////////////////////////////
589//////////////////////////////////////////////////////////////
590
591
592void Get_AA_Freqs(calign *data)
593{
594  int i,j,k;
595  phydbl A,C,D,E,F,G,H,I,K,L,M,N,P,Q,R,S,T,V,W,Y;
596  phydbl fA,fC,fD,fE,fF,fG,fH,fI,fK,fL,fM,fN,fP,fQ,fR,fS,fT,fV,fW,fY;
597  int w;
598  phydbl sum;
599 
600  fA = fC = fD = fE = fF = fG = fH = fI = fK = fL =
601  fM = fN = fP = fQ = fR = fS = fT = fV = fW = fY = 1./20.;
602 
603  For(k,8)
604    {
605      A = C = D = E = F = G = H = I = K = L =
606      M = N = P = Q = R = S = T = V = W = Y = .0;
607
608      For(i,data->n_otu)
609        {
610          For(j,data->crunch_len)
611            {
612              w = data->wght[j];
613              if(w)
614                {
615                  switch(data->c_seq[i]->state[j])
616                    {
617                    case 'A' : A+=w;            break;
618                    case 'C' : C+=w;            break;
619                    case 'D' : D+=w;            break;
620                    case 'E' : E+=w;            break;
621                    case 'F' : F+=w;            break;
622                    case 'G' : G+=w;            break;
623                    case 'H' : H+=w;            break;
624                    case 'I' : I+=w;            break;
625                    case 'K' : K+=w;            break;
626                    case 'L' : L+=w;            break;
627                    case 'M' : M+=w;            break;
628                    case 'N' : N+=w;            break;
629                    case 'P' : P+=w;            break;
630                    case 'Q' : Q+=w;            break;
631                    case 'R' : R+=w;            break;
632                    case 'S' : S+=w;            break;
633                    case 'T' : T+=w;            break;
634                    case 'V' : V+=w;            break;
635                    case 'W' : W+=w;            break;
636                    case 'Y' : Y+=w;            break;
637                    case 'Z' : Q+=w;            break;
638                    case 'X' : case '?' : case 'O' : case '-' :
639                      A+=w*fA;
640                      C+=w*fC;
641                      D+=w*fD;
642                      E+=w*fE;
643                      F+=w*fF;
644                      G+=w*fG;
645                      H+=w*fH;
646                      I+=w*fI;
647                      K+=w*fK;
648                      L+=w*fL;
649                      M+=w*fM;
650                      N+=w*fN;
651                      P+=w*fP;
652                      Q+=w*fQ;
653                      R+=w*fR;
654                      S+=w*fS;
655                      T+=w*fT;
656                      V+=w*fV;
657                      W+=w*fW;
658                      Y+=w*fY;
659                      break;
660                    default : break;
661                    }
662                }
663            }
664        }
665      sum = (A+C+D+E+F+G+H+I+K+L+M+N+P+Q+R+S+T+V+W+Y);
666      fA = A/sum;      fC = C/sum;      fD = D/sum;      fE = E/sum;
667      fF = F/sum;      fG = G/sum;      fH = H/sum;      fI = I/sum;
668      fK = K/sum;      fL = L/sum;      fM = M/sum;      fN = N/sum;
669      fP = P/sum;      fQ = Q/sum;      fR = R/sum;      fS = S/sum;
670      fT = T/sum;      fV = V/sum;      fW = W/sum;      fY = Y/sum;
671    }
672
673  data->b_frq[0]  = fA;  data->b_frq[1]  = fR;  data->b_frq[2]  = fN;  data->b_frq[3]  = fD;
674  data->b_frq[4]  = fC;  data->b_frq[5]  = fQ;  data->b_frq[6]  = fE;  data->b_frq[7]  = fG;
675  data->b_frq[8]  = fH;  data->b_frq[9]  = fI;  data->b_frq[10] = fL;  data->b_frq[11] = fK;
676  data->b_frq[12] = fM;  data->b_frq[13] = fF;  data->b_frq[14] = fP;  data->b_frq[15] = fS;
677  data->b_frq[16] = fT;  data->b_frq[17] = fW;  data->b_frq[18] = fY;  data->b_frq[19] = fV;
678
679}
680
681//////////////////////////////////////////////////////////////
682//////////////////////////////////////////////////////////////
683
684
685// Swap the nodes on the left and right of e1 with the nodes
686// on the left and right of e2 respectively, or on the
687// right and left of e2 if swap == YES
688
689void Swap_Nodes_On_Edges(t_edge *e1, t_edge *e2, int swap, t_tree *tree)
690{
691  t_node *buff;
692
693  e1->left->l[e1->l_r] = e1->l->v;
694  e1->rght->l[e1->r_l] = e1->l->v;
695
696  e2->left->l[e2->l_r] = e2->l->v;
697  e2->rght->l[e2->r_l] = e2->l->v;
698
699  printf("\n. Swap edge %d (%d %d) with %d (%d %d)",e1->num,e1->left->num,e1->rght->num,e2->num,e2->left->num,e2->rght->num);
700
701  if(swap == NO)
702    {
703      buff = e1->left;
704      e1->left = e2->left;
705      e2->left = buff;
706     
707      buff = e1->rght;
708      e1->rght = e2->rght;
709      e2->rght = buff;
710
711    }
712  else
713    {
714      buff = e1->left;
715      e1->left = e2->rght;
716      e2->rght = buff;
717     
718      buff = e1->rght;
719      e1->rght = e2->left;
720      e2->left = buff;
721    }
722     
723  Connect_One_Edge_To_Two_Nodes(e1->left,e1->rght,e1,tree);
724  Connect_One_Edge_To_Two_Nodes(e2->left,e2->rght,e2,tree);
725}
726
727//////////////////////////////////////////////////////////////
728//////////////////////////////////////////////////////////////
729
730void Connect_Edges_To_Nodes_Recur(t_node *a, t_node *d, t_tree *tree)
731{
732  int i;
733
734  Connect_One_Edge_To_Two_Nodes(a,d,tree->a_edges[tree->num_curr_branch_available],tree);
735
736  if(d->tax) return;
737  else For(i,3) if(d->v[i] != a) Connect_Edges_To_Nodes_Recur(d,d->v[i],tree);
738}
739
740//////////////////////////////////////////////////////////////
741//////////////////////////////////////////////////////////////
742
743void Connect_One_Edge_To_Two_Nodes(t_node *a, t_node *d, t_edge *b, t_tree *tree)
744{
745  int i,dir_a_d,dir_d_a;
746
747  dir_a_d = -1;
748  For(i,3) if(a->v[i] == d) {dir_a_d = i; break;}
749
750  dir_d_a = -1;
751  For(i,3) if(d->v[i] == a) {dir_d_a = i; break;}
752
753  if(dir_a_d == -1 || dir_d_a == -1)
754    {
755      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
756      Warn_And_Exit("");
757    }
758
759  a->b[dir_a_d] = b;
760  d->b[dir_d_a] = b;
761  b->num        = tree->num_curr_branch_available;
762  b->left       = a;
763  b->rght       = d;
764  if(a->tax) {b->rght = a; b->left = d;} /* root */
765  /* a tip is necessary on the right hand side of the t_edge */
766
767  tree->num_curr_branch_available += 1;
768 
769  (b->left == a)?
770    (Make_Edge_Dirs(b,a,d,tree)):
771    (Make_Edge_Dirs(b,d,a,tree));
772
773  b->l->v                    = a->l[b->l_r];
774  if(a->tax) b->l->v         = a->l[b->r_l];
775  b->l_old->v                = b->l->v;
776}
777
778//////////////////////////////////////////////////////////////
779//////////////////////////////////////////////////////////////
780
781void Update_Dirs(t_tree *tree)
782{
783  int i;
784  int buff;
785  t_edge *b;
786
787  b = NULL;
788  buff = -1;
789  For(i,2*tree->n_otu-3)
790    {
791      b = tree->a_edges[i];
792     
793      if((!b->left->tax) && (b->left->v[b->l_v1]->num < b->left->v[b->l_v2]->num))
794        {
795          buff    = b->l_v1;
796          b->l_v1 = b->l_v2;
797          b->l_v2 = buff;
798        }
799      if((!b->rght->tax) && (b->rght->v[b->r_v1]->num < b->rght->v[b->r_v2]->num))
800        {
801          buff    = b->r_v1;
802          b->r_v1 = b->r_v2;
803          b->r_v2 = buff;
804        }
805    }
806
807}
808
809//////////////////////////////////////////////////////////////
810//////////////////////////////////////////////////////////////
811
812void Exit(char *message)
813{
814  fflush(NULL);
815  PhyML_Fprintf(stderr,"%s",message);
816  exit(1);
817}
818
819//////////////////////////////////////////////////////////////
820//////////////////////////////////////////////////////////////
821
822
823void *mCalloc(int nb, size_t size)
824{
825  void *allocated;
826
827  if((allocated = calloc((size_t)nb,size)) != NULL)
828/*   if((allocated = malloc((size_t)nb*(size_t)size)) != NULL) */
829    {
830      return allocated;
831    }
832  else
833    Exit("\n== Err: low memory\n");
834
835  return NULL;
836}
837
838//////////////////////////////////////////////////////////////
839//////////////////////////////////////////////////////////////
840
841void *mRealloc(void *p,int nb, size_t size)
842{
843  if((p = realloc(p,(size_t)nb*size)) != NULL)
844        return p;
845  else
846    Exit("\n== Err: low memory\n");
847
848  return NULL;
849}
850
851//////////////////////////////////////////////////////////////
852//////////////////////////////////////////////////////////////
853
854
855/* t_tree *Make_Light_Tree_Struct(int n_otu) */
856/* { */
857/*   t_tree *tree; */
858/*   int i; */
859
860/*   tree          = (t_tree *)mCalloc(1,sizeof(t_tree )); */
861/*   tree->a_edges = (t_edge **)mCalloc(2*n_otu-3,sizeof(t_edge *)); */
862/*   tree->a_nodes   = (t_node **)mCalloc(2*n_otu-2,sizeof(t_node *)); */
863/*   tree->n_otu   = n_otu; */
864
865/*   For(i,2*n_otu-3) */
866/*     tree->a_edges[i] = Make_Edge_Light(NULL,NULL,i); */
867
868/*   For(i,2*n_otu-2) */
869/*     tree->a_nodes[i] = Make_Node_Light(i); */
870
871/*   return tree; */
872/* } */
873
874//////////////////////////////////////////////////////////////
875//////////////////////////////////////////////////////////////
876
877
878int Sort_Phydbl_Decrease(const void *a, const void *b)
879{
880    if((*(phydbl *)(a)) >= (*(phydbl *)(b))) return -1;
881    else return 1;
882}
883
884//////////////////////////////////////////////////////////////
885//////////////////////////////////////////////////////////////
886
887
888void Qksort_Int(int *A, int *B, int ilo, int ihi)
889{
890    phydbl pivot;       // pivot value for partitioning array
891    int ulo, uhi;       // indices at ends of unpartitioned region
892    int ieq;            // least index of array entry with value equal to pivot
893    int tempEntry;      // temporary entry used for swapping
894
895    if (ilo >= ihi) {
896        return;
897    }
898    // Select a pivot value.
899    pivot = A[(ilo + ihi)/2];
900    // Initialize ends of unpartitioned region and least index of entry
901    // with value equal to pivot.
902    ieq = ulo = ilo;
903    uhi = ihi;
904    // While the unpartitioned region is not empty, try to reduce its size.
905    while (ulo <= uhi) {
906      if (A[uhi] > pivot) {
907            // Here, we can reduce the size of the unpartitioned region and
908            // try again.
909            uhi--;
910        } else {
911            // Here, A[uhi] <= pivot, so swap entries at indices ulo and
912            // uhi.
913            tempEntry = A[ulo];
914            A[ulo]    = A[uhi];
915            A[uhi]    = tempEntry;
916
917            if(B)
918              {
919                tempEntry = B[ulo];
920                B[ulo]    = B[uhi];
921                B[uhi]    = tempEntry;
922              }
923
924
925
926            // After the swap, A[ulo] <= pivot.
927            if (A[ulo] < pivot) {
928                // Swap entries at indices ieq and ulo.
929                tempEntry = A[ieq];
930                A[ieq] = A[ulo];
931                A[ulo] = tempEntry;
932
933
934                if(B)
935                  {
936                    tempEntry = B[ieq];
937                    B[ieq] = B[ulo];
938                    B[ulo] = tempEntry;
939                  }
940
941
942                // After the swap, A[ieq] < pivot, so we need to change
943                // ieq.
944                ieq++;
945                // We also need to change ulo, but we also need to do
946                // that when A[ulo] = pivot, so we do it after this if
947                // statement.
948            }
949            // Once again, we can reduce the size of the unpartitioned
950            // region and try again.
951            ulo++;
952        }
953    }
954    // Now, all entries from index ilo to ieq - 1 are less than the pivot
955    // and all entries from index uhi to ihi + 1 are greater than the
956    // pivot.  So we have two regions of the array that can be sorted
957    // recursively to put all of the entries in order.
958    Qksort_Int(A, B, ilo, ieq - 1);
959    Qksort_Int(A, B, uhi + 1, ihi);
960
961}
962
963//////////////////////////////////////////////////////////////
964//////////////////////////////////////////////////////////////
965
966
967/* Sort in ascending order. Elements in B (if provided) are also re-ordered according to the ordering of A  */
968void Qksort(phydbl *A, phydbl *B, int ilo, int ihi)
969{
970    phydbl pivot;       // pivot value for partitioning array
971    int ulo, uhi;       // indices at ends of unpartitioned region
972    int ieq;            // least index of array entry with value equal to pivot
973    phydbl tempEntry;   // temporary entry used for swapping
974
975    if (ilo >= ihi) {
976        return;
977    }
978    // Select a pivot value.
979    pivot = A[(ilo + ihi)/2];
980    // Initialize ends of unpartitioned region and least index of entry
981    // with value equal to pivot.
982    ieq = ulo = ilo;
983    uhi = ihi;
984    // While the unpartitioned region is not empty, try to reduce its size.
985    while (ulo <= uhi) {
986      if (A[uhi] > pivot) {
987            // Here, we can reduce the size of the unpartitioned region and
988            // try again.
989            uhi--;
990        } else {
991            // Here, A[uhi] <= pivot, so swap entries at indices ulo and
992            // uhi.
993            tempEntry = A[ulo];
994            A[ulo]    = A[uhi];
995            A[uhi]    = tempEntry;
996
997            if(B)
998              {
999                tempEntry = B[ulo];
1000                B[ulo]    = B[uhi];
1001                B[uhi]    = tempEntry;
1002              }
1003
1004
1005
1006            // After the swap, A[ulo] <= pivot.
1007            if (A[ulo] < pivot) {
1008                // Swap entries at indices ieq and ulo.
1009                tempEntry = A[ieq];
1010                A[ieq] = A[ulo];
1011                A[ulo] = tempEntry;
1012
1013
1014                if(B)
1015                  {
1016                    tempEntry = B[ieq];
1017                    B[ieq] = B[ulo];
1018                    B[ulo] = tempEntry;
1019                  }
1020
1021
1022                // After the swap, A[ieq] < pivot, so we need to change
1023                // ieq.
1024                ieq++;
1025                // We also need to change ulo, but we also need to do
1026                // that when A[ulo] = pivot, so we do it after this if
1027                // statement.
1028            }
1029            // Once again, we can reduce the size of the unpartitioned
1030            // region and try again.
1031            ulo++;
1032        }
1033    }
1034    // Now, all entries from index ilo to ieq - 1 are less than the pivot
1035    // and all entries from index uhi to ihi + 1 are greater than the
1036    // pivot.  So we have two regions of the array that can be sorted
1037    // recursively to put all of the entries in order.
1038    Qksort(A, B, ilo, ieq - 1);
1039    Qksort(A, B, uhi + 1, ihi);
1040}
1041
1042/********************************************************/
1043
1044void Qksort_Matrix(phydbl **A, int col, int ilo, int ihi)
1045{
1046    phydbl pivot;       // pivot value for partitioning array
1047    int ulo, uhi;       // indices at ends of unpartitioned region
1048    int ieq;            // least index of array entry with value equal to pivot
1049    phydbl *tempEntry;  // temporary entry used for swapping
1050
1051    tempEntry = NULL;
1052
1053    if (ilo >= ihi) {
1054        return;
1055    }
1056    // Select a pivot value.
1057    pivot = A[(ilo + ihi)/2][col];
1058    // Initialize ends of unpartitioned region and least index of entry
1059    // with value equal to pivot.
1060    ieq = ulo = ilo;
1061    uhi = ihi;
1062    // While the unpartitioned region is not empty, try to reduce its size.
1063    while (ulo <= uhi) {
1064        if (A[uhi][col] > pivot) {
1065            // Here, we can reduce the size of the unpartitioned region and
1066            // try again.
1067            uhi--;
1068        } else {
1069            // Here, A[uhi] <= pivot, so swap entries at indices ulo and
1070            // uhi.
1071            tempEntry = A[ulo];
1072            A[ulo] = A[uhi];
1073            A[uhi] = tempEntry;
1074            // After the swap, A[ulo] <= pivot.
1075            if (A[ulo][col] < pivot) {
1076                // Swap entries at indices ieq and ulo.
1077                tempEntry = A[ieq];
1078                A[ieq] = A[ulo];
1079                A[ulo] = tempEntry;
1080                // After the swap, A[ieq] < pivot, so we need to change
1081                // ieq.
1082                ieq++;
1083                // We also need to change ulo, but we also need to do
1084                // that when A[ulo] = pivot, so we do it after this if
1085                // statement.
1086            }
1087            // Once again, we can reduce the size of the unpartitioned
1088            // region and try again.
1089            ulo++;
1090        }
1091    }
1092    // Now, all entries from index ilo to ieq - 1 are less than the pivot
1093    // and all entries from index uhi to ihi + 1 are greater than the
1094    // pivot.  So we have two regions of the array that can be sorted
1095    // recursively to put all of the entries in order.
1096    Qksort_Matrix(A, col, ilo, ieq - 1);
1097    Qksort_Matrix(A, col, uhi + 1, ihi);
1098}
1099
1100
1101//////////////////////////////////////////////////////////////
1102//////////////////////////////////////////////////////////////
1103
1104char *Add_Taxa_To_Constraint_Tree(FILE *fp, calign *cdata)
1105{
1106  char *line,*long_line;
1107  t_tree *tree;
1108  int i,j;
1109
1110  rewind(fp);
1111
1112  line = Return_Tree_String_Phylip(fp);
1113  tree = Read_Tree(&line);
1114
1115  long_line = (char *)mCalloc(T_MAX_LINE,sizeof(char));
1116  strcpy(long_line,line);
1117
1118  long_line[strlen(line)-1] = '\0';
1119
1120  For(i,cdata->n_otu)
1121    {
1122      For(j,tree->n_otu)
1123        {
1124          if(!strcmp(tree->a_nodes[j]->name,cdata->c_seq[i]->name))
1125            break;
1126        }
1127
1128      if(j == tree->n_otu)
1129        {
1130          strcat(long_line,",");
1131          strcat(long_line,cdata->c_seq[i]->name);
1132        }
1133     
1134    }
1135
1136  strcat(long_line,");");
1137 
1138  Free_Tree(tree);
1139  Free(line);
1140
1141
1142  return long_line;
1143}
1144
1145//////////////////////////////////////////////////////////////
1146//////////////////////////////////////////////////////////////
1147
1148void Check_Constraint_Tree_Taxa_Names(t_tree *tree, calign *cdata)
1149{
1150  int i,j,n_otu_tree,n_otu_cdata;
1151 
1152  n_otu_tree  = tree->n_otu;
1153  n_otu_cdata = cdata->n_otu;
1154 
1155  For(i,n_otu_tree)
1156    {
1157      For(j,n_otu_cdata)
1158        {
1159          if(!strcmp(tree->a_nodes[i]->name,cdata->c_seq[j]->name))
1160            break;
1161        }
1162     
1163      if(j==n_otu_cdata)
1164        {
1165          PhyML_Printf("\n. '%s' was not found in sequence data set\n",tree->a_nodes[i]->name);
1166          Warn_And_Exit("");
1167        }
1168    }
1169}
1170
1171//////////////////////////////////////////////////////////////
1172//////////////////////////////////////////////////////////////
1173
1174void Copy_Tax_Names_To_Tip_Labels(t_tree *tree, calign *data)
1175{
1176  int i;
1177
1178  For(i,tree->n_otu)
1179    {
1180      tree->a_nodes[i]->name = (char *)mCalloc((int)strlen(data->c_seq[i]->name)+1,sizeof(char));
1181      tree->a_nodes[i]->ori_name = tree->a_nodes[i]->name;
1182      strcpy(tree->a_nodes[i]->name,data->c_seq[i]->name);
1183      tree->a_nodes[i]->tax = 1;
1184      tree->a_nodes[i]->num = i;
1185    }
1186}
1187
1188//////////////////////////////////////////////////////////////
1189//////////////////////////////////////////////////////////////
1190
1191void Share_Lk_Struct(t_tree *t_full, t_tree *t_empt)
1192{
1193  int i,j,n_otu;
1194  t_edge *b_e,*b_f;
1195  t_node *n_e, *n_f;
1196
1197  n_otu                   = t_full->n_otu;
1198  t_empt->n_root          = t_full->n_root;
1199  t_empt->e_root          = t_full->e_root;
1200  t_empt->c_lnL_sorted    = t_full->c_lnL_sorted;
1201  t_empt->log_site_lk_cat = t_full->log_site_lk_cat;
1202  t_empt->cur_site_lk   = t_full->cur_site_lk;
1203  t_empt->old_site_lk   = t_full->old_site_lk;
1204  t_empt->triplet_struct  = t_full->triplet_struct;
1205  t_empt->log_lks_aLRT    = t_full->log_lks_aLRT;
1206  t_empt->site_lk_cat     = t_full->site_lk_cat;
1207
1208  For(i,2*n_otu-3)
1209    {
1210      b_f = t_full->a_edges[i];
1211      b_e = t_empt->a_edges[i];
1212
1213      b_e->Pij_rr = b_f->Pij_rr;
1214
1215      b_e->nni = b_f->nni;
1216    }
1217
1218
1219  for(i=n_otu;i<2*n_otu-2;i++)
1220    {
1221      n_f = t_full->a_nodes[i];
1222      n_e = t_empt->a_nodes[i];
1223           
1224      For(j,3)
1225        {
1226          if(n_f->b[j]->left == n_f)
1227            {
1228              if(n_e->b[j]->left == n_e)
1229                {
1230                  n_e->b[j]->p_lk_left          = n_f->b[j]->p_lk_left;
1231                  n_e->b[j]->p_lk_loc_left      = n_f->b[j]->p_lk_loc_left;
1232                  n_e->b[j]->patt_id_left       = n_f->b[j]->patt_id_left;
1233                  n_e->b[j]->sum_scale_left     = n_f->b[j]->sum_scale_left;
1234                  n_e->b[j]->sum_scale_left_cat = n_f->b[j]->sum_scale_left_cat;
1235                  n_e->b[j]->p_lk_tip_l         = n_f->b[j]->p_lk_tip_l;
1236                }
1237              else
1238                {
1239                  n_e->b[j]->p_lk_rght          = n_f->b[j]->p_lk_left;
1240                  n_e->b[j]->p_lk_loc_rght      = n_f->b[j]->p_lk_loc_left;
1241                  n_e->b[j]->patt_id_rght       = n_f->b[j]->patt_id_left;
1242                  n_e->b[j]->sum_scale_rght     = n_f->b[j]->sum_scale_left;
1243                  n_e->b[j]->sum_scale_rght_cat = n_f->b[j]->sum_scale_left_cat;
1244                  n_e->b[j]->p_lk_tip_r         = n_f->b[j]->p_lk_tip_l;
1245                }
1246            }
1247          else
1248            {
1249              if(n_e->b[j]->rght == n_e)
1250                {
1251                  n_e->b[j]->p_lk_rght          = n_f->b[j]->p_lk_rght;
1252                  n_e->b[j]->p_lk_loc_rght      = n_f->b[j]->p_lk_loc_rght;
1253                  n_e->b[j]->patt_id_rght       = n_f->b[j]->patt_id_rght;
1254                  n_e->b[j]->sum_scale_rght     = n_f->b[j]->sum_scale_rght;
1255                  n_e->b[j]->sum_scale_rght_cat = n_f->b[j]->sum_scale_rght_cat;
1256                  n_e->b[j]->p_lk_tip_r         = n_f->b[j]->p_lk_tip_r;
1257                }
1258              else
1259                {
1260                  n_e->b[j]->p_lk_left          = n_f->b[j]->p_lk_rght;
1261                  n_e->b[j]->p_lk_loc_left      = n_f->b[j]->p_lk_loc_rght;
1262                  n_e->b[j]->patt_id_left       = n_f->b[j]->patt_id_rght;
1263                  n_e->b[j]->sum_scale_left     = n_f->b[j]->sum_scale_rght;
1264                  n_e->b[j]->sum_scale_left_cat = n_f->b[j]->sum_scale_rght_cat;
1265                  n_e->b[j]->p_lk_tip_l         = n_f->b[j]->p_lk_tip_r;
1266                }
1267            }
1268        }
1269    }
1270
1271  For(i,n_otu)
1272    {
1273      n_f = t_full->a_nodes[i];
1274      n_e = t_empt->a_nodes[i];
1275
1276      if(n_f->b[0]->rght == n_f)
1277        {
1278          n_e->b[0]->p_lk_rght          = n_f->b[0]->p_lk_rght;
1279          n_e->b[0]->p_lk_loc_rght      = n_f->b[0]->p_lk_loc_rght;
1280          n_e->b[0]->patt_id_rght       = n_f->b[0]->patt_id_rght;
1281          n_e->b[0]->sum_scale_rght     = n_f->b[0]->sum_scale_rght;
1282          n_e->b[0]->sum_scale_rght_cat = n_f->b[0]->sum_scale_rght_cat;
1283          n_e->b[0]->p_lk_tip_r         = n_f->b[0]->p_lk_tip_r;
1284        }
1285      else
1286        {
1287          PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
1288          Warn_And_Exit("");
1289        }
1290    }
1291}
1292
1293//////////////////////////////////////////////////////////////
1294//////////////////////////////////////////////////////////////
1295
1296void Share_Spr_Struct(t_tree *t_full, t_tree *t_empt)
1297{
1298  t_empt->size_spr_list = t_full->size_spr_list;
1299  t_empt->spr_list      = t_full->spr_list;
1300  t_empt->best_spr      = t_full->best_spr;
1301}
1302
1303//////////////////////////////////////////////////////////////
1304//////////////////////////////////////////////////////////////
1305
1306
1307void Share_Pars_Struct(t_tree *t_full, t_tree *t_empt)
1308{
1309  int i;
1310
1311  t_empt->site_pars = t_full->site_pars;
1312  t_empt->step_mat  = t_full->step_mat;
1313
1314  For(i,2*t_full->n_otu-3)
1315    {
1316      t_empt->a_edges[i]->ui_l     = t_full->a_edges[i]->ui_l;
1317      t_empt->a_edges[i]->ui_r     = t_full->a_edges[i]->ui_r;
1318
1319      t_empt->a_edges[i]->pars_l   = t_full->a_edges[i]->pars_l;
1320      t_empt->a_edges[i]->pars_r   = t_full->a_edges[i]->pars_r;
1321
1322      t_empt->a_edges[i]->p_pars_l = t_full->a_edges[i]->p_pars_l;
1323      t_empt->a_edges[i]->p_pars_r = t_full->a_edges[i]->p_pars_r;
1324    }
1325}
1326
1327//////////////////////////////////////////////////////////////
1328//////////////////////////////////////////////////////////////
1329
1330
1331
1332int Sort_Edges_NNI_Score(t_tree *tree, t_edge **sorted_edges, int n_elem)
1333{
1334  int i,j;
1335  t_edge *buff;
1336
1337  For(i,n_elem-1)
1338    {
1339      for(j=i+1;j<n_elem;j++)
1340        {
1341          if(sorted_edges[j]->nni->score  < sorted_edges[i]->nni->score)
1342            {
1343              buff = sorted_edges[j];
1344              sorted_edges[j] = sorted_edges[i];
1345              sorted_edges[i] = buff;
1346            }
1347        }
1348    }
1349  return 1;
1350}
1351
1352//////////////////////////////////////////////////////////////
1353//////////////////////////////////////////////////////////////
1354
1355int Sort_Edges_Depth(t_tree *tree, t_edge **sorted_edges, int n_elem)
1356{
1357  int i,j;
1358  t_edge *buff;
1359  phydbl *depth,buff_depth;
1360 
1361  depth = (phydbl *)mCalloc(n_elem,sizeof(phydbl));
1362
1363  For(i,n_elem) 
1364    depth[i] = 
1365    sorted_edges[i]->left->bip_size[sorted_edges[i]->l_r] * 
1366    sorted_edges[i]->rght->bip_size[sorted_edges[i]->r_l] ;
1367
1368
1369  For(i,n_elem-1)
1370    {
1371      for(j=i+1;j<n_elem;j++)
1372        {
1373          if(depth[i] > depth[j])
1374            {
1375              buff = sorted_edges[i];
1376              sorted_edges[i] = sorted_edges[j];
1377              sorted_edges[j] = buff;
1378
1379              buff_depth = depth[i];
1380              depth[i] = depth[j];
1381              depth[j] = buff_depth;
1382            }
1383        }
1384    }
1385
1386  Free(depth);
1387
1388  return 1;
1389}
1390
1391//////////////////////////////////////////////////////////////
1392//////////////////////////////////////////////////////////////
1393
1394void NNI(t_tree *tree, t_edge *b_fcus, int do_swap)
1395{
1396  t_node *v1,*v2,*v3,*v4;
1397  phydbl lk0, lk1, lk2;
1398  phydbl lk0_init, lk1_init, lk2_init;
1399  phydbl *l0,*l1,*l2;
1400  phydbl l_infa, l_infb;
1401  phydbl lk_init;
1402  t_edge *b;
1403  int i;
1404
1405  if(tree->prev)
1406    {
1407      PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);
1408      Exit("\n");
1409    }
1410
1411  lk_init                = tree->c_lnL;
1412  b_fcus->nni->init_l    = b_fcus->l->v;
1413  b_fcus->nni->init_lk   = tree->c_lnL;;
1414  b_fcus->nni->best_conf = 0;
1415  b_fcus->nni->score     = +1.0;
1416  lk0 = lk1 = lk2        = UNLIKELY;
1417  v1 = v2 = v3 = v4      = NULL;
1418
1419
1420  v1                     = b_fcus->left->v[b_fcus->l_v1];
1421  v2                     = b_fcus->left->v[b_fcus->l_v2];
1422  v3                     = b_fcus->rght->v[b_fcus->r_v1];
1423  v4                     = b_fcus->rght->v[b_fcus->r_v2];
1424
1425  Record_Br_Len(tree);
1426
1427  if(v1->num < v2->num)
1428    {
1429      PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);
1430      Exit("\n");
1431    }
1432  if(v3->num < v4->num)
1433    {
1434      PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);
1435      Exit("\n");
1436    }
1437
1438
1439  /***********/
1440  Swap(v2,b_fcus->left,b_fcus->rght,v3,tree);
1441  Set_Both_Sides(YES,tree);
1442
1443  MIXT_Set_Alias_Subpatt(YES,tree);
1444  lk1_init = Update_Lk_At_Given_Edge(b_fcus,tree);
1445  MIXT_Set_Alias_Subpatt(NO,tree);
1446
1447  l_infa = 10.;
1448  l_infb = tree->mod->l_min/b_fcus->l->v;
1449
1450  if(tree->mod->s_opt->fast_nni)
1451    {
1452      Fast_Br_Len(b_fcus,tree,1);
1453      lk1 = Lk(b_fcus,tree);
1454    }
1455  else
1456    {
1457      lk1 = Br_Len_Brent(l_infb,l_infa,b_fcus,tree);
1458    }
1459
1460  if(lk1 < lk1_init - tree->mod->s_opt->min_diff_lk_local)
1461    {
1462      PhyML_Printf("\n== %f %f %G",l_infa,l_infb,b_fcus->l->v);
1463      PhyML_Printf("\n== %f -- %f",lk1_init,lk1);
1464      PhyML_Printf("\n== Err. in NNI (1)");
1465    }
1466
1467  /* l1  = b_fcus->l->v; */
1468  l1  = MIXT_Get_Lengths_Of_This_Edge(b_fcus,tree);
1469  Swap(v3,b_fcus->left,b_fcus->rght,v2,tree);
1470  /***********/
1471
1472
1473  /***********/
1474  Swap(v2,b_fcus->left,b_fcus->rght,v4,tree);
1475  Restore_Br_Len(tree);
1476  Set_Both_Sides(YES,tree);
1477
1478  MIXT_Set_Alias_Subpatt(YES,tree);
1479  lk2_init = Update_Lk_At_Given_Edge(b_fcus,tree);
1480  MIXT_Set_Alias_Subpatt(NO,tree);
1481
1482  l_infa = 10.;
1483  l_infb = tree->mod->l_min/b_fcus->l->v;
1484
1485  if(tree->mod->s_opt->fast_nni)
1486    {
1487      Fast_Br_Len(b_fcus,tree,1);
1488      lk2 = Lk(b_fcus,tree);
1489    }
1490  else
1491    {
1492      lk2 = Br_Len_Brent(l_infb,l_infa,b_fcus,tree);
1493    }
1494
1495  if(lk2 < lk2_init - tree->mod->s_opt->min_diff_lk_local)
1496    {
1497      PhyML_Printf("\n== %f %f %G",l_infa,l_infb,b_fcus->l->v);
1498      PhyML_Printf("\n== %f -- %f",lk2_init,lk2);
1499      PhyML_Printf("\n== Err. in NNI (2)");
1500   }
1501
1502  /* l2  = b_fcus->l->v; */
1503  l2  = MIXT_Get_Lengths_Of_This_Edge(b_fcus,tree);
1504  Swap(v4,b_fcus->left,b_fcus->rght,v2,tree);
1505  /***********/
1506
1507
1508 
1509  /***********/
1510  Restore_Br_Len(tree);
1511  Set_Both_Sides(YES,tree);
1512
1513  MIXT_Set_Alias_Subpatt(YES,tree);
1514  lk0_init = Update_Lk_At_Given_Edge(b_fcus,tree);
1515  MIXT_Set_Alias_Subpatt(NO,tree);
1516
1517  if(FABS(lk0_init - lk_init) > tree->mod->s_opt->min_diff_lk_local)
1518    {
1519      PhyML_Printf("\n== lk_init = %f; lk = %f diff = %f l = %G",
1520                   lk_init,
1521                   lk0_init,
1522                   lk_init-lk0_init,
1523                   b_fcus->l->v);
1524      PhyML_Printf("\n== Curr_lnL = %f",Lk(NULL,tree));
1525      Exit("\n== Err. in NNI (3)");
1526    }
1527 
1528  l_infa = 10.;
1529  l_infb = tree->mod->l_min/b_fcus->l->v;
1530 
1531  if(tree->mod->s_opt->fast_nni)
1532    {
1533      Fast_Br_Len(b_fcus,tree,1);
1534      lk0 = Lk(b_fcus,tree);
1535    }
1536  else
1537    {
1538       lk0 = Br_Len_Brent(l_infb,l_infa,b_fcus,tree);
1539    }
1540 
1541 if(lk0 < lk_init - tree->mod->s_opt->min_diff_lk_local)
1542    {
1543      PhyML_Printf("\n== %f %f %f",l_infa,l_infb,b_fcus->l->v);
1544      PhyML_Printf("\n== %f -- %f",lk0_init,lk0);
1545      PhyML_Printf("\n== Err. in NNI (3)\n");
1546      Exit("\n");
1547    }
1548 
1549  /* l0 = b_fcus->l->v; */
1550  l0  = MIXT_Get_Lengths_Of_This_Edge(b_fcus,tree);
1551  /***********/
1552 
1553  b_fcus->nni->lk0 = lk0;
1554  b_fcus->nni->lk1 = lk1;
1555  b_fcus->nni->lk2 = lk2;
1556 
1557  b = b_fcus;
1558  i = 0;
1559  do
1560    {
1561      b->nni->l0 = l0[i];
1562      b->nni->l1 = l1[i];
1563      b->nni->l2 = l2[i];
1564      b = b->next;
1565      i++;
1566    }
1567  while(b);
1568
1569  b_fcus->nni->score = lk0 - MAX(lk1,lk2); 
1570
1571  if((b_fcus->nni->score <  tree->mod->s_opt->min_diff_lk_local) &&
1572     (b_fcus->nni->score > -tree->mod->s_opt->min_diff_lk_local))
1573    {
1574      b_fcus->nni->score = .0;
1575      b_fcus->nni->lk1 = b_fcus->nni->lk0;
1576      b_fcus->nni->lk2 = b_fcus->nni->lk0;
1577    }
1578 
1579  if(lk0 > MAX(lk1,lk2))
1580    {
1581      b_fcus->nni->best_conf    = 0;
1582      b_fcus->nni->swap_node_v1 = NULL;
1583      b_fcus->nni->swap_node_v2 = NULL;
1584      b_fcus->nni->swap_node_v3 = NULL;
1585      b_fcus->nni->swap_node_v4 = NULL;
1586
1587      b = b_fcus;
1588      i = 0;
1589      do
1590        {
1591          b->nni->best_l = l0[i];
1592          b = b->next;
1593          i++;
1594        }
1595      while(b);
1596
1597
1598    }
1599  else if(lk1 > MAX(lk0,lk2))
1600    {
1601      b_fcus->nni->best_conf    = 1;
1602      b_fcus->nni->swap_node_v1 = v2;
1603      b_fcus->nni->swap_node_v2 = b_fcus->left;
1604      b_fcus->nni->swap_node_v3 = b_fcus->rght;
1605      b_fcus->nni->swap_node_v4 = v3;
1606
1607      b = b_fcus;
1608      i = 0;
1609      do
1610        {
1611          b->nni->best_l = l1[i];
1612          b = b->next;
1613          i++;
1614        }
1615      while(b);
1616
1617
1618    }
1619  else if(lk2 > MAX(lk0,lk1))
1620    {
1621      b_fcus->nni->best_conf    = 2;
1622      b_fcus->nni->swap_node_v1 = v2;
1623      b_fcus->nni->swap_node_v2 = b_fcus->left;
1624      b_fcus->nni->swap_node_v3 = b_fcus->rght;
1625      b_fcus->nni->swap_node_v4 = v4;
1626
1627      b = b_fcus;
1628      i = 0;
1629      do
1630        {
1631          b->nni->best_l = l2[i];
1632          b = b->next;
1633          i++;
1634        }
1635      while(b);
1636
1637
1638
1639    }
1640  else
1641    {
1642      b_fcus->nni->score        = +1.0;
1643      b_fcus->nni->best_conf    = 0;
1644      b_fcus->nni->swap_node_v1 = NULL;
1645      b_fcus->nni->swap_node_v2 = NULL;
1646      b_fcus->nni->swap_node_v3 = NULL;
1647      b_fcus->nni->swap_node_v4 = NULL;
1648
1649
1650      b = b_fcus;
1651      i = 0;
1652      do
1653        {
1654          b->nni->best_l = l0[i];
1655          b = b->next;
1656          i++;
1657        }
1658      while(b);
1659
1660
1661    }
1662 
1663  if((do_swap) && ((lk1 > lk0) || (lk2 > lk0)))
1664    {
1665      tree->n_swap++;
1666      PhyML_Printf("\n. Swap t_edge %d -> %f",b_fcus->num,MAX(lk1,lk2));
1667     
1668      if(lk1 > lk2)
1669        {
1670          tree->best_lnL = lk1;
1671          Swap(v2,b_fcus->left,b_fcus->rght,v3,tree);
1672
1673          b = b_fcus;
1674          i = 0;
1675          do
1676            {
1677              b->l->v = l1[i];
1678              b = b->next;
1679              i++;
1680            }
1681          while(b);
1682
1683          Set_Both_Sides(YES,tree);
1684          Lk(NULL,tree);
1685        }
1686      else
1687        {
1688          tree->best_lnL = lk2;
1689          Swap(v2,b_fcus->left,b_fcus->rght,v4,tree);
1690
1691          b = b_fcus;
1692          i = 0;
1693          do
1694            {
1695              b->l->v = l2[i];
1696              b = b->next;
1697              i++;
1698            }
1699          while(b);
1700
1701          Set_Both_Sides(YES,tree);
1702          Lk(NULL,tree);
1703        }
1704    }
1705  else
1706    {
1707      Restore_Br_Len(tree);
1708      Update_PMat_At_Given_Edge(b_fcus,tree);
1709      tree->c_lnL = lk_init;
1710    }
1711
1712  Free(l0);
1713  Free(l1);
1714  Free(l2);
1715}
1716
1717//////////////////////////////////////////////////////////////
1718//////////////////////////////////////////////////////////////
1719
1720
1721void NNI_Pars(t_tree *tree, t_edge *b_fcus, int do_swap)
1722{
1723  t_node *v1,*v2,*v3,*v4;
1724  int pars0, pars1, pars2;
1725  int pars_init;
1726
1727  pars_init              = tree->c_pars;
1728  b_fcus->nni->best_conf = 0;
1729  b_fcus->nni->score     = +1.0;
1730
1731  pars0 = pars1 = pars2  = 0;
1732  v1 = v2 = v3 = v4      = NULL;
1733
1734
1735  v1                     = b_fcus->left->v[b_fcus->l_v1];
1736  v2                     = b_fcus->left->v[b_fcus->l_v2];
1737  v3                     = b_fcus->rght->v[b_fcus->r_v1];
1738  v4                     = b_fcus->rght->v[b_fcus->r_v2];
1739
1740  if(v1->num < v2->num)
1741    {
1742      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
1743      Warn_And_Exit("");
1744    }
1745  if(v3->num < v4->num)
1746    {
1747      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
1748      Warn_And_Exit("");
1749    }
1750
1751 
1752  /***********/
1753  Swap(v2,b_fcus->left,b_fcus->rght,v3,tree);
1754  Set_Both_Sides(YES,tree);
1755  pars1 = Update_Pars_At_Given_Edge(b_fcus,tree);
1756  Swap(v3,b_fcus->left,b_fcus->rght,v2,tree);
1757  /***********/
1758
1759  /***********/
1760  Swap(v2,b_fcus->left,b_fcus->rght,v4,tree);
1761  Set_Both_Sides(YES,tree);
1762  pars2 = Update_Pars_At_Given_Edge(b_fcus,tree);
1763  Swap(v4,b_fcus->left,b_fcus->rght,v2,tree);
1764  /***********/
1765
1766 
1767  /***********/
1768  Set_Both_Sides(YES,tree);
1769  pars0 = Update_Pars_At_Given_Edge(b_fcus,tree);
1770 
1771  if(pars0 != pars_init)
1772     {
1773       PhyML_Printf("\n. pars_init = %d; pars0 = %d\n",
1774              pars_init,
1775              pars0);
1776       Warn_And_Exit("\n. Err. in NNI (3)\n");
1777     }
1778   /***********/
1779
1780   tree->c_pars = pars0;
1781
1782   b_fcus->nni->score = MIN(pars1,pars2) - pars0;
1783
1784   if(pars0 < MIN(pars1,pars2))
1785     {
1786       b_fcus->nni->best_conf    = 0;
1787       b_fcus->nni->swap_node_v1 = NULL;
1788       b_fcus->nni->swap_node_v2 = NULL;
1789       b_fcus->nni->swap_node_v3 = NULL;
1790       b_fcus->nni->swap_node_v4 = NULL;
1791      }
1792   else if(pars1 < MIN(pars0,pars2))
1793     {
1794       b_fcus->nni->best_conf    = 1;
1795       b_fcus->nni->swap_node_v1 = v2;
1796       b_fcus->nni->swap_node_v2 = b_fcus->left;
1797       b_fcus->nni->swap_node_v3 = b_fcus->rght;
1798       b_fcus->nni->swap_node_v4 = v3;
1799     }
1800   else if(pars2 > MIN(pars0,pars1))
1801     {
1802       b_fcus->nni->best_conf    = 2;
1803       b_fcus->nni->swap_node_v1 = v2;
1804       b_fcus->nni->swap_node_v2 = b_fcus->left;
1805       b_fcus->nni->swap_node_v3 = b_fcus->rght;
1806       b_fcus->nni->swap_node_v4 = v4;
1807     }
1808   else
1809     {
1810       b_fcus->nni->score        = +1.0;
1811       b_fcus->nni->swap_node_v1 = NULL;
1812       b_fcus->nni->swap_node_v2 = NULL;
1813       b_fcus->nni->swap_node_v3 = NULL;
1814       b_fcus->nni->swap_node_v4 = NULL;
1815     }
1816}
1817
1818//////////////////////////////////////////////////////////////
1819//////////////////////////////////////////////////////////////
1820
1821
1822void Swap(t_node *a, t_node *b, t_node *c, t_node *d, t_tree *tree)
1823{
1824  int ab, ba, cd, dc, bc;
1825  int i;
1826
1827  /* \             /d      \             /a
1828   *  \           /         \           /
1829   *   \b__...__c/    ->     \b__...__c/
1830   *   /         \           /          \
1831   *  /           \         /            \
1832   * /a            \       /d             \
1833   *
1834   * nodes b and c are not necessarily on the same branch
1835   */
1836
1837  if(!tree) return;
1838
1839#ifdef DEBUG
1840  if(!a || !b || !c || !d)
1841    {
1842      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
1843      Warn_And_Exit("");
1844    }
1845#endif
1846
1847  ab = ba = cd = dc = bc = -1;
1848
1849  For(i,3) if(a->v[i] == b) { ab = i; break; }
1850  For(i,3) if(b->v[i] == a) { ba = i; break; }
1851  For(i,3) if(c->v[i] == d) { cd = i; break; }
1852  For(i,3) if(d->v[i] == c) { dc = i; break; }
1853  For(i,3) if(b->v[i] == c) { bc = i; break; }
1854
1855#ifdef DEBUG
1856  if(ab < 0 || ba < 0 || cd < 0 || dc < 0)
1857    {
1858      PhyML_Printf("\n== Nodes %d %d %d %d\n",a->num,b->num,c->num,d->num);
1859      PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);
1860      Exit("\n");
1861    }
1862#endif
1863
1864  a->v[ab] = c;
1865  d->v[dc] = b;
1866  b->v[ba] = d;
1867  c->v[cd] = a;
1868  b->b[ba] = d->b[dc];
1869  c->b[cd] = a->b[ab];
1870
1871  (a->b[ab]->left == b)?
1872  (a->b[ab]->left = c):
1873  (a->b[ab]->rght = c);
1874
1875  (d->b[dc]->left == c)?
1876  (d->b[dc]->left = b):
1877  (d->b[dc]->rght = b);
1878
1879  For(i,3)
1880    {
1881      if(a->b[ab]->left->v[i] == a->b[ab]->rght) a->b[ab]->l_r = i;
1882      if(a->b[ab]->rght->v[i] == a->b[ab]->left) a->b[ab]->r_l = i;
1883      if(d->b[dc]->left->v[i] == d->b[dc]->rght) d->b[dc]->l_r = i;
1884      if(d->b[dc]->rght->v[i] == d->b[dc]->left) d->b[dc]->r_l = i;
1885    }
1886
1887  a->b[ab]->l_v1 = a->b[ab]->l_v2 =
1888  a->b[ab]->r_v1 = a->b[ab]->r_v2 =
1889  d->b[dc]->l_v1 = d->b[dc]->l_v2 =
1890  d->b[dc]->r_v1 = d->b[dc]->r_v2 = -1;
1891
1892  For(i,3)
1893    {
1894      if(i != a->b[ab]->l_r)
1895        {
1896          if(a->b[ab]->l_v1 < 0) a->b[ab]->l_v1 = i;
1897          else a->b[ab]->l_v2 = i;
1898        }
1899      if(i != a->b[ab]->r_l)
1900        {
1901          if(a->b[ab]->r_v1 < 0) a->b[ab]->r_v1 = i;
1902          else a->b[ab]->r_v2 = i;
1903        }
1904      if(i != d->b[dc]->l_r)
1905        {
1906          if(d->b[dc]->l_v1 < 0) d->b[dc]->l_v1 = i;
1907          else d->b[dc]->l_v2 = i;
1908        }
1909      if(i != d->b[dc]->r_l)
1910        {
1911          if(d->b[dc]->r_v1 < 0) d->b[dc]->r_v1 = i;
1912          else d->b[dc]->r_v2 = i;
1913        }
1914    }
1915  Update_Dirs(tree);
1916 
1917  if(tree->next) 
1918    Swap(a->next,b->next,c->next,d->next,tree->next);
1919}
1920
1921//////////////////////////////////////////////////////////////
1922//////////////////////////////////////////////////////////////
1923
1924
1925void Update_All_Partial_Lk(t_edge *b_fcus, t_tree *tree)
1926{
1927
1928  Update_SubTree_Partial_Lk(b_fcus->left->b[b_fcus->l_v1],
1929                            b_fcus->left,
1930                            b_fcus->left->v[b_fcus->l_v1],
1931                            tree);
1932
1933  Update_SubTree_Partial_Lk(b_fcus->left->b[b_fcus->l_v2],
1934                            b_fcus->left,
1935                            b_fcus->left->v[b_fcus->l_v2],
1936                            tree);
1937
1938  Update_SubTree_Partial_Lk(b_fcus->rght->b[b_fcus->r_v1],
1939                            b_fcus->rght,
1940                            b_fcus->rght->v[b_fcus->r_v1],
1941                            tree);
1942
1943  Update_SubTree_Partial_Lk(b_fcus->rght->b[b_fcus->r_v2],
1944                            b_fcus->rght,
1945                            b_fcus->rght->v[b_fcus->r_v2],
1946                            tree);
1947
1948  tree->c_lnL = Lk(b_fcus,tree);
1949
1950
1951  if(tree->next) Update_All_Partial_Lk(tree->next->a_edges[b_fcus->num],
1952                                       tree->next);
1953}
1954
1955//////////////////////////////////////////////////////////////
1956//////////////////////////////////////////////////////////////
1957
1958
1959void Update_SubTree_Partial_Lk(t_edge *b_fcus, t_node *a, t_node *d, t_tree *tree)
1960{
1961  int i;
1962
1963  Update_P_Lk(tree,b_fcus,a);
1964  if(d->tax) return;
1965  else For(i,3) if(d->v[i] != a)
1966    Update_SubTree_Partial_Lk(d->b[i],d,d->v[i],tree);
1967}
1968
1969//////////////////////////////////////////////////////////////
1970//////////////////////////////////////////////////////////////
1971
1972
1973
1974//////////////////////////////////////////////////////////////
1975//////////////////////////////////////////////////////////////
1976
1977
1978void Copy_Seq_Names_To_Tip_Labels(t_tree *tree, calign *data)
1979{
1980  int i;
1981  For(i,tree->n_otu)
1982    {
1983      strcpy(tree->a_nodes[i]->name,data->c_seq[i]->name);
1984    }
1985}
1986
1987//////////////////////////////////////////////////////////////
1988//////////////////////////////////////////////////////////////
1989
1990calign *Copy_Cseq(calign *ori, option *io)
1991{
1992  calign *new;
1993  int i,j,k,n_otu,c_len;
1994  char **sp_names;
1995
1996  n_otu = ori->n_otu;
1997  c_len = ori->crunch_len;
1998
1999
2000  sp_names = (char **)mCalloc(n_otu,sizeof(char *));
2001  For(i,n_otu)
2002    {
2003      sp_names[i] = (char *)mCalloc(strlen(ori->c_seq[i]->name)+1,sizeof(char));
2004      strcpy(sp_names[i],ori->c_seq[i]->name);
2005    }
2006
2007  new = Make_Cseq(n_otu,c_len+1,io->state_len,ori->init_len,sp_names);
2008
2009  new->obs_pinvar = ori->obs_pinvar;
2010
2011  For(i,ori->init_len) new->sitepatt[i] = ori->sitepatt[i];
2012
2013  For(j,ori->crunch_len)
2014    {
2015      For(i,ori->n_otu) 
2016        {
2017          For(k,io->state_len) 
2018            {
2019              new->c_seq[i]->state[j*io->state_len+k] = 
2020                ori->c_seq[i]->state[j*io->state_len+k];
2021            }
2022          new->c_seq[i]->is_ambigu[j] = ori->c_seq[i]->is_ambigu[j];
2023        }
2024
2025      new->wght[j]   = ori->wght[j];
2026      new->ambigu[j] = ori->ambigu[j];
2027      new->invar[j]  = ori->invar[j];
2028    }
2029
2030  For(i,ori->n_otu)
2031    {
2032      new->c_seq[i]->len = ori->c_seq[i]->len;
2033      strcpy(new->c_seq[i]->name,ori->c_seq[i]->name);
2034    }
2035
2036  For(i,ori->n_otu) new->c_seq[i]->state[c_len*io->state_len] = '\0';
2037
2038  For(i,T_MAX_ALPHABET) new->b_frq[i] = ori->b_frq[i];
2039
2040  new->init_len           = ori->init_len;
2041  new->clean_len          = ori->clean_len;
2042  new->crunch_len         = ori->crunch_len;
2043  new->n_otu              = ori->n_otu;
2044
2045
2046  For(i,n_otu) Free(sp_names[i]);
2047  Free(sp_names);
2048
2049  return new;
2050}
2051
2052//////////////////////////////////////////////////////////////
2053//////////////////////////////////////////////////////////////
2054
2055
2056int Filexists(char *filename)
2057{
2058  FILE *fp;
2059  fp =fopen(filename,"r");
2060  if (fp) {
2061    fclose(fp);
2062    return 1;
2063  } else
2064    return 0;
2065}
2066
2067//////////////////////////////////////////////////////////////
2068//////////////////////////////////////////////////////////////
2069
2070matrix *K80_dist(calign *data, phydbl g_shape)
2071{
2072  int i,j,k;
2073  int diff;
2074  matrix *mat;
2075  phydbl **len;
2076
2077  len = (phydbl **)mCalloc(data->n_otu,sizeof(phydbl *));
2078  For(i,data->n_otu)
2079    len[i] = (phydbl *)mCalloc(data->n_otu,sizeof(phydbl));
2080
2081  mat = Make_Mat(data->n_otu);
2082 
2083  Init_Mat(mat,data);
2084
2085  For(i,data->c_seq[0]->len)
2086    {
2087      For(j,data->n_otu-1)
2088        {
2089          for(k=j+1;k<data->n_otu;k++)
2090            {
2091              if(((data->c_seq[j]->state[i] == 'A' || data->c_seq[j]->state[i] == 'G') &&
2092                  (data->c_seq[k]->state[i] == 'C' || data->c_seq[k]->state[i] == 'T'))||
2093                 ((data->c_seq[j]->state[i] == 'C' || data->c_seq[j]->state[i] == 'T') &&
2094                  (data->c_seq[k]->state[i] == 'A' || data->c_seq[k]->state[i] == 'G')))
2095                {
2096                  diff++;
2097                  mat->Q[j][k]+=data->wght[i];
2098                  len[j][k]+=data->wght[i];
2099                  len[k][j]=len[j][k];
2100                }
2101             
2102              else
2103                if(((data->c_seq[j]->state[i] == 'A' && data->c_seq[k]->state[i] == 'G') ||
2104                    (data->c_seq[j]->state[i] == 'G' && data->c_seq[k]->state[i] == 'A'))||
2105                   ((data->c_seq[j]->state[i] == 'C' && data->c_seq[k]->state[i] == 'T') ||
2106                    (data->c_seq[j]->state[i] == 'T' && data->c_seq[k]->state[i] == 'C')))
2107                  {
2108                    diff++;
2109                    mat->P[j][k]+=data->wght[i];
2110                    len[j][k]+=data->wght[i];
2111                    len[k][j]=len[j][k];
2112                  }
2113                else
2114                  if((data->c_seq[j]->state[i] == 'A' ||
2115                      data->c_seq[j]->state[i] == 'C' ||
2116                      data->c_seq[j]->state[i] == 'G' ||
2117                      data->c_seq[j]->state[i] == 'T')&&
2118                     (data->c_seq[k]->state[i] == 'A' ||
2119                      data->c_seq[k]->state[i] == 'C' ||
2120                      data->c_seq[k]->state[i] == 'G' ||
2121                      data->c_seq[k]->state[i] == 'T'))
2122                    {
2123                      len[j][k]+=data->wght[i];
2124                      len[k][j]=len[j][k];
2125                    }
2126            }
2127        }
2128    }
2129
2130
2131  For(i,data->n_otu-1)
2132    for(j=i+1;j<data->n_otu;j++)
2133      {
2134        if(len[i][j] > .0)
2135          {
2136            mat->P[i][j] /= len[i][j];
2137            mat->Q[i][j] /= len[i][j];
2138          }
2139        else
2140          {
2141            mat->P[i][j] = .5;
2142            mat->Q[i][j] = .5;
2143          }
2144
2145        mat->P[j][i] = mat->P[i][j];
2146        mat->Q[j][i] = mat->Q[i][j];
2147
2148
2149        if((1-2*mat->P[i][j]-mat->Q[i][j] <= .0) || (1-2*mat->Q[i][j] <= .0))
2150          {
2151            mat->dist[i][j] = -1.;
2152            mat->dist[j][i] = -1.;
2153            continue;
2154          }
2155
2156        mat->dist[i][j] = (g_shape/2)*
2157          (POW(1-2*mat->P[i][j]-mat->Q[i][j],-1./g_shape) +
2158           0.5*POW(1-2*mat->Q[i][j],-1./g_shape) - 1.5);
2159
2160        if(mat->dist[i][j] > DIST_MAX) mat->dist[i][j] = DIST_MAX;
2161
2162        mat->dist[j][i] = mat->dist[i][j];
2163      }
2164
2165  For(i,data->n_otu) free(len[i]);
2166  free(len);
2167  return mat;
2168}
2169
2170//////////////////////////////////////////////////////////////
2171//////////////////////////////////////////////////////////////
2172
2173
2174matrix *JC69_Dist(calign *data, t_mod *mod)
2175{
2176  int site,i,j,k;
2177  matrix *mat;
2178  phydbl **len;
2179  int datatype;
2180
2181
2182  len = (phydbl **)mCalloc(data->n_otu,sizeof(phydbl *));
2183  For(i,data->n_otu)
2184    len[i] = (phydbl *)mCalloc(data->n_otu,sizeof(phydbl));
2185
2186  mat = Make_Mat(data->n_otu);
2187  Init_Mat(mat,data);
2188
2189  datatype = mod->io->datatype;
2190
2191  For(site,data->c_seq[0]->len)
2192    {
2193      For(j,data->n_otu-1)
2194        {
2195          for(k=j+1;k<data->n_otu;k++)
2196            {
2197              if((!Is_Ambigu(data->c_seq[j]->state+site*mod->io->state_len,datatype,mod->io->state_len)) &&
2198                 (!Is_Ambigu(data->c_seq[k]->state+site*mod->io->state_len,datatype,mod->io->state_len)))
2199                {
2200                  len[j][k]+=data->wght[site];
2201                  len[k][j]=len[j][k];
2202
2203
2204                  if(strncmp(data->c_seq[j]->state+site*mod->io->state_len,
2205                             data->c_seq[k]->state+site*mod->io->state_len,mod->io->state_len))
2206/*                if(!Are_Compatible(data->c_seq[j]->state+site*mod->io->state_len, */
2207/*                                   data->c_seq[k]->state+site*mod->io->state_len, */
2208/*                                   mod->io->state_len, */
2209/*                                   mod->io->datatype)) */
2210                    mat->P[j][k]+=data->wght[site];
2211                }
2212            }
2213        }
2214    }
2215 
2216
2217  For(i,data->n_otu-1)
2218    for(j=i+1;j<data->n_otu;j++)
2219      {
2220        if(len[i][j] > .0) mat->P[i][j] /= len[i][j];
2221        else               mat->P[i][j] = 1.;
2222
2223        mat->P[j][i] = mat->P[i][j];
2224
2225        if((1.-(mod->ns)/(mod->ns-1.)*mat->P[i][j]) < .0) mat->dist[i][j] = -1.;
2226        else
2227          mat->dist[i][j] = -(mod->ns-1.)/(mod->ns)*(phydbl)LOG(1.-(mod->ns)/(mod->ns-1.)*mat->P[i][j]);
2228
2229/*      PhyML_Printf("\n. Incorrect JC distances"); */
2230/*      mat->dist[i][j] = len[i][j]; */
2231
2232        if(mat->dist[i][j] > DIST_MAX) mat->dist[i][j] = DIST_MAX;
2233
2234        mat->dist[j][i] = mat->dist[i][j];
2235      }
2236
2237  For(i,data->n_otu) free(len[i]);
2238  free(len);
2239
2240  return mat;
2241}
2242
2243//////////////////////////////////////////////////////////////
2244//////////////////////////////////////////////////////////////
2245
2246
2247matrix *Hamming_Dist(calign *data, t_mod *mod)
2248{
2249  int i,j,k;
2250  matrix *mat;
2251  phydbl **len;
2252  int datatype;
2253
2254  len = (phydbl **)mCalloc(data->n_otu,sizeof(phydbl *));
2255  For(i,data->n_otu)
2256    len[i] = (phydbl *)mCalloc(data->n_otu,sizeof(phydbl));
2257
2258  mat = Make_Mat(data->n_otu);
2259  Init_Mat(mat,data);
2260 
2261  datatype = mod->io->datatype;
2262
2263  For(i,data->crunch_len)
2264    {
2265      For(j,data->n_otu-1)
2266        {
2267          for(k=j+1;k<data->n_otu;k++)
2268            {
2269              if((!Is_Ambigu(data->c_seq[j]->state+i*mod->io->state_len,datatype,mod->io->state_len)) &&
2270                 (!Is_Ambigu(data->c_seq[k]->state+i*mod->io->state_len,datatype,mod->io->state_len)))
2271                {
2272                  len[j][k]+=data->wght[i];
2273                  len[k][j]=len[j][k];
2274/*                if(data->c_seq[j]->state[i] != data->c_seq[k]->state[i]) */
2275                  if(!Are_Compatible(data->c_seq[j]->state+i*mod->io->state_len,
2276                                     data->c_seq[k]->state+i*mod->io->state_len,
2277                                     mod->io->state_len,
2278                                     mod->io->datatype))
2279                    {
2280                      mat->P[j][k]+=data->wght[i];
2281                    }
2282                }
2283            }
2284        }
2285    }
2286
2287  For(i,data->n_otu-1)
2288    for(j=i+1;j<data->n_otu;j++)
2289      {
2290        if(len[i][j] > .0)
2291          {
2292            mat->P[i][j] /= len[i][j];
2293          }
2294        else
2295          {
2296            mat->P[i][j] = 1.;
2297          }
2298
2299        mat->P[j][i] = mat->P[i][j];
2300
2301        mat->dist[i][j] = mat->P[i][j];
2302
2303
2304        if(mat->dist[i][j] > DIST_MAX)
2305          {
2306            mat->dist[i][j] = DIST_MAX;
2307          }
2308        mat->dist[j][i] = mat->dist[i][j];
2309      }
2310
2311  For(i,data->n_otu) free(len[i]);
2312  free(len);
2313
2314  return mat;
2315}
2316
2317//////////////////////////////////////////////////////////////
2318//////////////////////////////////////////////////////////////
2319
2320/* Test if the given site pattern is invariant. Does not handle ambiguities */
2321
2322int Is_Invar(int patt_num, int stepsize, int datatype, calign *data)
2323{
2324  int i, j;
2325
2326  For(i,data->n_otu)
2327    {
2328      For(j,data->n_otu)
2329        {
2330          if(!(Are_Compatible(data->c_seq[i]->state+patt_num,
2331                              data->c_seq[j]->state+patt_num,
2332                              stepsize,
2333                              datatype))) 
2334            {
2335              break;
2336            }
2337        }
2338      if(j != data->n_otu) break;
2339    }
2340 
2341  if(i == data->n_otu) return 1;
2342  else                 return 0;
2343}
2344
2345
2346//////////////////////////////////////////////////////////////
2347//////////////////////////////////////////////////////////////
2348
2349
2350int Is_Ambigu(char *state, int datatype, int stepsize)
2351{
2352  int val,i;
2353
2354  val = -1;
2355  if(datatype == NT)
2356    {
2357      For(i,stepsize)
2358        {
2359          switch(state[i])
2360            {
2361            case 'A' : case 'C' : case 'G' : case 'T' : case 'U' : { val=NO; break; }
2362            default : { val=YES; break; }
2363            }
2364          if(val == YES) break;
2365        }
2366    }
2367  else if(datatype == AA)
2368    {
2369      switch(state[0])
2370        {
2371        case 'X' : case '?' : case '-' : case '.' : {val=YES; break; }
2372        default : { val=NO; break; }
2373        }
2374    }
2375  else if(datatype == GENERIC)
2376    {
2377      int i;
2378      For(i,stepsize) if(!isdigit(state[i])) break;
2379      if(i == stepsize) val = NO;
2380      else              val = YES;
2381    }
2382
2383  return val;
2384}
2385
2386//////////////////////////////////////////////////////////////
2387//////////////////////////////////////////////////////////////
2388
2389void Check_Ambiguities(calign *data, int datatype, int stepsize)
2390{
2391  int i,j;
2392
2393  For(j,data->crunch_len) 
2394    {
2395      data->ambigu[j] = NO;
2396      For(i,data->n_otu)
2397        {
2398          data->c_seq[i]->is_ambigu[j] = NO;
2399        }
2400
2401      For(i,data->n_otu)
2402        {
2403          if(Is_Ambigu(data->c_seq[i]->state+j*stepsize,
2404                       datatype,
2405                       stepsize))
2406            {
2407              data->ambigu[j]              = YES;
2408              data->c_seq[i]->is_ambigu[j] = YES;
2409            }
2410        }
2411    }
2412}
2413
2414//////////////////////////////////////////////////////////////
2415//////////////////////////////////////////////////////////////
2416
2417void Set_D_States(calign *data, int datatype, int stepsize)
2418{
2419  int i,j;
2420
2421  For(j,data->crunch_len) 
2422    {
2423      For(i,data->n_otu)
2424        {
2425          if(data->c_seq[i]->is_ambigu[j] == NO)
2426            {
2427              data->c_seq[i]->d_state[j] = Assign_State(data->c_seq[i]->state+j, 
2428                                                        datatype, 
2429                                                        stepsize);
2430            }
2431        }
2432    }
2433}
2434
2435//////////////////////////////////////////////////////////////
2436//////////////////////////////////////////////////////////////
2437
2438int Get_State_From_Ui(int ui, int datatype)
2439{
2440  if(datatype == NT)
2441    {
2442      switch(ui)
2443        {
2444        case 1 : {return 0; break;}
2445        case 2 : {return 1; break;}
2446        case 4 : {return 2; break;}
2447        case 8 : {return 3; break;}
2448        default : 
2449          {
2450            PhyML_Printf("\n. ui=%d",ui);
2451            PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
2452            Warn_And_Exit("");
2453            break;
2454          }
2455        }
2456    }
2457  else if(datatype == AA)
2458    {
2459      switch(ui)
2460        {
2461        case 1 :      {return 0;  break;}
2462        case 2 :      {return 1;  break;} 
2463        case 4 :      {return 2;  break;} 
2464        case 8 :      {return 3;  break;} 
2465        case 16 :     {return 4;  break;} 
2466        case 32 :     {return 5;  break;} 
2467        case 64 :     {return 6;  break;} 
2468        case 128 :    {return 7;  break;} 
2469        case 256 :    {return 8;  break;} 
2470        case 512 :    {return 9;  break;} 
2471        case 1024 :   {return 10; break;} 
2472        case 2048 :   {return 11; break;} 
2473        case 4096 :   {return 12; break;} 
2474        case 8192 :   {return 13; break;} 
2475        case 16384 :  {return 14; break;} 
2476        case 32768 :  {return 15; break;} 
2477        case 65536 :  {return 16; break;} 
2478        case 131072 : {return 17; break;} 
2479        case 262144 : {return 18; break;} 
2480        case 524288 : {return 19; break;} 
2481        default : 
2482          {
2483            PhyML_Printf("\n. ui=%d",ui);
2484            PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
2485            Warn_And_Exit("");
2486          }
2487        }
2488    }
2489  else
2490    {
2491      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
2492      Warn_And_Exit("");
2493    }
2494  return -1;
2495}
2496
2497//////////////////////////////////////////////////////////////
2498//////////////////////////////////////////////////////////////
2499
2500
2501int Assign_State(char *c, int datatype, int stepsize)
2502{
2503  int state[3];
2504  int i;
2505
2506  state[0] = state[1] = state[2] = -1;
2507  if(datatype == NT)
2508    {
2509      For(i,stepsize)
2510        {
2511          switch(c[i])
2512            {
2513            case 'A' : {state[i]=0;  break;}
2514            case 'C' : {state[i]=1;  break;}
2515            case 'G' : {state[i]=2;  break;}
2516            case 'T' : {state[i]=3;  break;}
2517            case 'U' : {state[i]=3;  break;}
2518            default  : {state[i]=-1; break;}
2519            }
2520        }
2521      return (stepsize>1)?(state[0]*16+state[1]*4+state[2]):(state[0]);
2522    }
2523  else if(datatype == AA)
2524    {
2525      switch(c[0])
2526        {
2527        case 'A' : {state[0]=0 ; break;}
2528        case 'R' : {state[0]=1 ; break;}
2529        case 'N' : {state[0]=2 ; break;}
2530        case 'D' : {state[0]=3 ; break;}
2531        case 'C' : {state[0]=4 ; break;}
2532        case 'Q' : {state[0]=5 ; break;}
2533        case 'E' : {state[0]=6 ; break;}
2534        case 'G' : {state[0]=7 ; break;}
2535        case 'H' : {state[0]=8 ; break;}
2536        case 'I' : {state[0]=9 ; break;}
2537        case 'L' : {state[0]=10; break;}
2538        case 'K' : {state[0]=11; break;}
2539        case 'M' : {state[0]=12; break;}
2540        case 'F' : {state[0]=13; break;}
2541        case 'P' : {state[0]=14; break;}
2542        case 'S' : {state[0]=15; break;}
2543        case 'T' : {state[0]=16; break;}
2544        case 'W' : {state[0]=17; break;}
2545        case 'Y' : {state[0]=18; break;}
2546        case 'V' : {state[0]=19; break;}
2547
2548        case 'B' : {state[0] = 2; break;}
2549        case 'Z' : {state[0] = 5; break;}
2550        default  : {state[0]=-1;  break;}
2551        }
2552      return state[0];
2553    }
2554  else if(datatype == GENERIC)
2555    {
2556      char format[6];
2557      int ret;
2558
2559      sprintf(format,"%%%dd",stepsize);
2560      ret = sscanf(c,format,state);
2561      if(!ret) state[0] = -1;     
2562      return state[0];
2563    }
2564  else
2565    {
2566      PhyML_Printf("\n. Not implemented yet.\n");
2567      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
2568      Warn_And_Exit("");
2569    }
2570
2571  return -1;
2572}
2573
2574//////////////////////////////////////////////////////////////
2575//////////////////////////////////////////////////////////////
2576
2577
2578char Reciproc_Assign_State(int i_state, int datatype)
2579{
2580 
2581  if(datatype == NT)
2582    {
2583      i_state = i_state%4;
2584      switch(i_state)
2585        {
2586        case 0 :   {return 'A';  break;}
2587        case 1 :   {return 'C';  break;}
2588        case 2 :   {return 'G';  break;}
2589        case 3 :   {return 'T';  break;}
2590        default  : 
2591          {
2592            PhyML_Printf("\n. i_state = %d",i_state);
2593            PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
2594            Warn_And_Exit("");
2595            break;
2596          }
2597        }
2598    }
2599  else if(datatype == AA)
2600    {
2601      i_state = i_state%20;
2602      switch(i_state)
2603        {
2604        case 0  : {return 'A' ; break;}
2605        case 1  : {return 'R' ; break;}
2606        case 2  : {return 'N' ; break;}
2607        case 3  : {return 'D' ; break;}
2608        case 4  : {return 'C' ; break;}
2609        case 5  : {return 'Q' ; break;}
2610        case 6  : {return 'E' ; break;}
2611        case 7  : {return 'G' ; break;}
2612        case 8  : {return 'H' ; break;}
2613        case 9  : {return 'I' ; break;}
2614        case 10 : {return 'L';  break;}
2615        case 11 : {return 'K';  break;}
2616        case 12 : {return 'M';  break;}
2617        case 13 : {return 'F';  break;}
2618        case 14 : {return 'P';  break;}
2619        case 15 : {return 'S';  break;}
2620        case 16 : {return 'T';  break;}
2621        case 17 : {return 'W';  break;}
2622        case 18 : {return 'Y';  break;}
2623        case 19 : {return 'V';  break;}
2624        default  : 
2625          {
2626            PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
2627            Warn_And_Exit("");
2628            break;
2629          }
2630        }
2631    }
2632  else if(datatype == GENERIC)
2633    {
2634      return (char)i_state;
2635    }
2636  return -1;
2637}
2638
2639//////////////////////////////////////////////////////////////
2640//////////////////////////////////////////////////////////////
2641
2642
2643int Assign_State_With_Ambiguity(char *c, int datatype, int stepsize)
2644{
2645  int state[3];
2646  int i;
2647
2648  state[0] = state[1] = state[2] = -1;
2649  if(datatype == NT)
2650    {
2651      For(i,stepsize)
2652        {
2653          switch(c[i])
2654            {
2655            case 'A' : {state[i]= 0;  break;}
2656            case 'C' : {state[i]= 1;  break;}
2657            case 'G' : {state[i]= 2;  break;}
2658            case 'T' : {state[i]= 3;  break;}
2659            case 'U' : {state[i]= 3;  break;}
2660            case 'M' : {state[i]= 4;  break;}
2661            case 'R' : {state[i]= 5;  break;}
2662            case 'W' : {state[i]= 6;  break;}
2663            case 'S' : {state[i]= 7;  break;}
2664            case 'Y' : {state[i]= 8;  break;}
2665            case 'K' : {state[i]= 9;  break;}
2666            case 'B' : {state[i]=10;  break;}
2667            case 'D' : {state[i]=11;  break;}
2668            case 'H' : {state[i]=12;  break;}
2669            case 'V' : {state[i]=13;  break;}
2670            case 'N' : case 'X' : case '?' : case 'O' : case '-' : {state[i]=T_MAX_ALPHABET-1;  break;}
2671            default :
2672              {
2673                PhyML_Printf("\n. Unknown character state : '%c'\n",c[i]);
2674                Warn_And_Exit("\n. Init failed (check the data type)\n");
2675                break;
2676              }
2677            }
2678          return (stepsize>1)?(state[0]*16+state[1]*4+state[2]):(state[0]);
2679        }
2680    }
2681  else if(datatype == AA)
2682    {
2683      switch(c[0])
2684        {
2685        case 'A' : {state[0]= 0; break;}
2686        case 'R' : {state[0]= 1; break;}
2687        case 'N' : {state[0]= 2; break;}
2688        case 'D' : {state[0]= 3; break;}
2689        case 'C' : {state[0]= 4; break;}
2690        case 'Q' : {state[0]= 5; break;}
2691        case 'E' : {state[0]= 6; break;}
2692        case 'G' : {state[0]= 7; break;}
2693        case 'H' : {state[0]= 8; break;}
2694        case 'I' : {state[0]= 9; break;}
2695        case 'L' : {state[0]=10; break;}
2696        case 'K' : {state[0]=11; break;}
2697        case 'M' : {state[0]=12; break;}
2698        case 'F' : {state[0]=13; break;}
2699        case 'P' : {state[0]=14; break;}
2700        case 'S' : {state[0]=15; break;}
2701        case 'T' : {state[0]=16; break;}
2702        case 'W' : {state[0]=17; break;}
2703        case 'Y' : {state[0]=18; break;}
2704        case 'V' : {state[0]=19; break;}
2705        case 'B' : {state[0]= 2; break;}
2706        case 'Z' : {state[0]= 5; break;}
2707        case 'X' : case '?' : case '-' : {state[0]=T_MAX_ALPHABET-1; break;}
2708        default  : 
2709          {
2710            PhyML_Printf("\n. Unknown character state : %c\n",state[0]);
2711            Warn_And_Exit("\n. Init failed (check the data type)\n");
2712            break;
2713          }
2714        }
2715      return state[0];
2716    }
2717  else if(datatype == GENERIC)
2718    {
2719      if(Is_Ambigu(c,GENERIC,stepsize)) state[0] = T_MAX_ALPHABET-1;
2720      else
2721        {
2722          char format[6];
2723          sprintf(format,"%%%dd",stepsize);
2724          if(!sscanf(c,format,state))
2725            {
2726              PhyML_Printf("\n. Error reading character. Was expecting an integer, got '%c' instead.\n",c[0]);
2727              PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
2728              Warn_And_Exit("");
2729            }
2730        }
2731      return state[0];
2732    }
2733
2734  return -1;
2735}
2736
2737//////////////////////////////////////////////////////////////
2738//////////////////////////////////////////////////////////////
2739
2740
2741void Clean_Tree_Connections(t_tree *tree)
2742{
2743
2744  int i;
2745  For(i,2*tree->n_otu-2)
2746    {
2747      tree->a_nodes[i]->v[0] = NULL;
2748      tree->a_nodes[i]->v[1] = NULL;
2749      tree->a_nodes[i]->v[2] = NULL;
2750      tree->a_nodes[i]->b[0] = NULL;
2751      tree->a_nodes[i]->b[1] = NULL;
2752      tree->a_nodes[i]->b[2] = NULL;
2753    }
2754}
2755
2756//////////////////////////////////////////////////////////////
2757//////////////////////////////////////////////////////////////
2758
2759
2760void Bootstrap(t_tree *tree)
2761{
2762  int *site_num, n_site;
2763  int replicate,j,k;
2764  int position,init_len;
2765  calign *boot_data;
2766  t_tree *boot_tree;
2767  t_mod *boot_mod;
2768  matrix *boot_mat;
2769  char *s;
2770/*   phydbl rf; */
2771
2772  tree->print_boot_val = 1;
2773  tree->print_alrt_val = 0;
2774  boot_tree            = NULL;
2775
2776  site_num = (int *)mCalloc(tree->data->init_len,sizeof(int));
2777
2778  Free_Bip(tree);
2779  Alloc_Bip(tree);
2780  Get_Bip(tree->a_nodes[0],tree->a_nodes[0]->v[0],tree);
2781
2782  n_site = 0;
2783  For(j,tree->data->crunch_len) For(k,tree->data->wght[j])
2784    {
2785      site_num[n_site] = j;
2786      n_site++;
2787    }
2788
2789  boot_data = Copy_Cseq(tree->data,tree->io);
2790
2791  PhyML_Printf("\n\n. Non parametric bootstrap analysis \n\n");
2792  PhyML_Printf("  ["); 
2793 
2794  For(replicate,tree->mod->bootstrap)
2795    {
2796      For(j,boot_data->crunch_len) boot_data->wght[j] = 0;
2797
2798      init_len = 0;
2799      For(j,boot_data->init_len)
2800        {
2801          position = Rand_Int(0,(int)(tree->data->init_len-1.0));
2802          boot_data->wght[site_num[position]] += 1;
2803          init_len++;
2804        }
2805     
2806      Set_D_States(boot_data,tree->io->datatype,tree->io->state_len);
2807
2808      if(init_len != tree->data->init_len) Exit("\n== Pb when copying sequences\n");
2809
2810      init_len = 0;
2811      For(j,boot_data->crunch_len) init_len += boot_data->wght[j];
2812
2813      if(init_len != tree->data->init_len) Exit("\n== Pb when copying sequences\n");
2814
2815      if(tree->io->datatype == NT)      Get_Base_Freqs(boot_data);
2816      else if(tree->io->datatype == AA) Get_AA_Freqs(boot_data);
2817
2818      if(tree->io->random_boot_seq_order) Randomize_Sequence_Order(boot_data);
2819
2820      boot_mod        = Copy_Model(tree->mod);
2821         
2822      boot_mod->s_opt = tree->mod->s_opt; /* WARNING: re-using the same address here instead of creating a copying
2823                                             requires to leave the value of s_opt unchanged during the boostrap. */
2824      boot_mod->io    = tree->io; /* WARNING: re-using the same address here instead of creating a copying
2825                                     requires to leave the value of io unchanged during the boostrap. */
2826
2827      Init_Model(boot_data,boot_mod,tree->io);
2828
2829      if(tree->io->mod->use_m4mod) M4_Init_Model(boot_mod->m4mod,boot_data,boot_mod);
2830
2831      if(tree->io->in_tree == 2)
2832        {
2833          rewind(tree->io->fp_in_tree);
2834          boot_tree = Read_Tree_File_Phylip(tree->io->fp_in_tree);
2835        }
2836      else
2837        {
2838          boot_mat = ML_Dist(boot_data,boot_mod);
2839          boot_mat->tree = Make_Tree_From_Scratch(boot_data->n_otu,boot_data);
2840          Fill_Missing_Dist(boot_mat);
2841          Bionj(boot_mat);
2842          boot_tree = boot_mat->tree;
2843          boot_tree->mat = boot_mat;
2844        }
2845
2846      boot_tree->mod                = boot_mod;
2847      boot_tree->io                 = tree->io;
2848      boot_tree->data               = boot_data;
2849      boot_tree->mod->s_opt->print  = NO;
2850      boot_tree->n_pattern          = boot_tree->data->crunch_len;
2851      boot_tree->io->print_site_lnl = 0;
2852      boot_tree->io->print_trace    = 0;
2853
2854      Set_Both_Sides(YES,boot_tree);
2855
2856      if((boot_tree->mod->s_opt->random_input_tree) && (boot_tree->mod->s_opt->topo_search == SPR_MOVE)) Random_Tree(boot_tree);
2857
2858      Connect_CSeqs_To_Nodes(boot_data,boot_tree);
2859
2860      Check_Br_Lens(boot_tree);
2861      Share_Lk_Struct(tree,boot_tree);
2862      Share_Spr_Struct(tree,boot_tree);
2863      Share_Pars_Struct(tree,boot_tree);
2864      Fill_Dir_Table(boot_tree);
2865      Update_Dirs(boot_tree);
2866
2867      if(tree->mod->s_opt->greedy) Init_P_Lk_Tips_Double(boot_tree);
2868      else                         Init_P_Lk_Tips_Int(boot_tree);
2869      Init_Ui_Tips(boot_tree);
2870      Init_P_Pars_Tips(boot_tree);
2871      Br_Len_Not_Involving_Invar(boot_tree);
2872
2873
2874      if(boot_tree->io->do_alias_subpatt)
2875        {
2876          MIXT_Set_Alias_Subpatt(YES,boot_tree);
2877          Lk(NULL,boot_tree);
2878          MIXT_Set_Alias_Subpatt(NO,boot_tree);
2879        }
2880     
2881
2882      if(boot_tree->mod->s_opt->opt_topo)
2883        {
2884          if(boot_tree->mod->s_opt->topo_search == NNI_MOVE) 
2885            {
2886              Simu_Loop(boot_tree);
2887            }
2888          else if((boot_tree->mod->s_opt->topo_search == SPR_MOVE) ||
2889                  (boot_tree->mod->s_opt->topo_search == BEST_OF_NNI_AND_SPR))
2890            {
2891              Speed_Spr_Loop(boot_tree);
2892            }
2893        }
2894      else
2895        {
2896          if(boot_tree->mod->s_opt->opt_subst_param || boot_tree->mod->s_opt->opt_bl)
2897            Round_Optimize(boot_tree,boot_tree->data,ROUND_MAX);
2898          else
2899            Lk(NULL,boot_tree);
2900        }
2901     
2902
2903      Free_Bip(boot_tree);
2904
2905      Alloc_Bip(boot_tree);
2906
2907      Match_Tip_Numbers(tree,boot_tree);
2908     
2909      Get_Bip(boot_tree->a_nodes[0],
2910              boot_tree->a_nodes[0]->v[0],
2911              boot_tree);
2912
2913      Compare_Bip(tree,boot_tree,NO);
2914
2915      Check_Br_Lens(boot_tree);
2916      Br_Len_Involving_Invar(boot_tree);
2917
2918      if(tree->io->print_boot_trees)
2919        {
2920          s = Write_Tree(boot_tree,NO);
2921          PhyML_Fprintf(tree->io->fp_out_boot_tree,"%s\n",s);
2922          Free(s);
2923          Print_Fp_Out_Lines(tree->io->fp_out_boot_stats,0,0,boot_tree,tree->io,replicate+1);
2924        }
2925
2926      /*       rf = .0; */
2927      /*       For(j,2*tree->n_otu-3)  */
2928      /*        rf += tree->a_edges[j]->bip_score; */
2929
2930
2931      PhyML_Printf("."); 
2932#ifndef QUIET
2933fflush(stdout);
2934#endif
2935      if(!((replicate+1)%tree->io->boot_prog_every))
2936        {
2937          PhyML_Printf("] %4d/%4d\n  ",replicate+1,tree->mod->bootstrap);
2938          if(replicate != tree->mod->bootstrap-1) PhyML_Printf("[");
2939        }
2940
2941      Free_Tree(boot_tree);     
2942      Free_Model(boot_mod);
2943    }
2944
2945  if(((replicate)%tree->io->boot_prog_every)) PhyML_Printf("] %4d/%4d\n ",replicate,tree->mod->bootstrap);
2946
2947  tree->lock_topo = YES; /* Topology should not be modified afterwards */
2948
2949  if(tree->io->print_boot_trees)
2950    {
2951      fclose(tree->io->fp_out_boot_tree);
2952      fclose(tree->io->fp_out_boot_stats);
2953    }
2954
2955  Free_Cseq(boot_data);
2956  Free(site_num);
2957}
2958
2959//////////////////////////////////////////////////////////////
2960//////////////////////////////////////////////////////////////
2961
2962void Br_Len_Involving_Invar(t_tree *tree)
2963{
2964  int i;
2965
2966  if(tree->is_mixt_tree) 
2967    {
2968      MIXT_Br_Len_Involving_Invar(tree);
2969      return;
2970    }
2971
2972  For(i,2*tree->n_otu-1) tree->a_edges[i]->l->v *= (1.0-tree->mod->ras->pinvar->v);
2973}
2974
2975//////////////////////////////////////////////////////////////
2976//////////////////////////////////////////////////////////////
2977
2978void Br_Len_Not_Involving_Invar(t_tree *tree)
2979{
2980  int i;
2981 
2982  if(tree->is_mixt_tree) 
2983    {
2984      MIXT_Br_Len_Not_Involving_Invar(tree);
2985      return;
2986    }
2987
2988  For(i,2*tree->n_otu-1) tree->a_edges[i]->l->v /= (1.0-tree->mod->ras->pinvar->v);
2989}
2990
2991//////////////////////////////////////////////////////////////
2992//////////////////////////////////////////////////////////////
2993
2994
2995void Getstring_Stdin(char *s)
2996{
2997  if(!fgets(s,T_MAX_LINE,stdin)) Exit("");
2998  if (strchr(s, '\n') != NULL)
2999    *strchr(s, '\n') = '\0';
3000}
3001
3002//////////////////////////////////////////////////////////////
3003//////////////////////////////////////////////////////////////
3004
3005phydbl Num_Derivatives_One_Param(phydbl (*func)(t_tree *tree), t_tree *tree,
3006                                 phydbl f0, phydbl *param, int which, int n_param, phydbl stepsize, int logt,
3007                                 phydbl *err, int precise, int is_positive)
3008{
3009  int i,j;
3010  phydbl errt,fac,hh,**a,ans,*sign;
3011  int n_iter;
3012
3013  sign = (phydbl *)mCalloc(n_param,sizeof(phydbl));
3014
3015  a = (phydbl **)mCalloc(11,sizeof(phydbl *));
3016  For(i,11) a[i] = (phydbl *)mCalloc(11,sizeof(phydbl));
3017
3018  n_iter = 10; /* */
3019
3020  ans  = .0;
3021
3022  if(stepsize < SMALL) Warn_And_Exit("\n== h must be nonzero in Dfridr.");
3023
3024  hh=stepsize;
3025
3026  if(!precise)
3027    {
3028      param[which]   = param[which]+hh;
3029
3030      if(logt == YES) For(i,n_param) param[i] = EXP(MIN(1.E+2,param[i]));
3031      For(i,n_param) sign[i] = param[i] > .0 ? 1. : -1.;
3032      if(is_positive == YES) For(i,n_param) param[i] = FABS(param[i]);
3033      a[0][0]  = (*func)(tree);
3034      if(is_positive == YES) For(i,n_param) param[i] *= sign[i];
3035      if(logt == YES) For(i,n_param) param[i] = LOG(param[i]);
3036
3037      /* printf("\n. f0=%f f1=%f hh=%G %f",f0,a[0][0],hh,param[which]); */
3038
3039      a[0][0]  -= f0;
3040      a[0][0]  /= hh;
3041      param[which]   = param[which]-hh;
3042
3043      ans =  a[0][0];
3044    }
3045  else
3046    {
3047      param[which]   = param[which]+hh;
3048
3049      if(logt == YES) For(i,n_param) param[i] = EXP(MIN(1.E+2,param[i]));
3050      For(i,n_param) sign[i] = param[i] > .0 ? 1. : -1.;
3051      if(is_positive == YES) For(i,n_param) param[i] = FABS(param[i]);
3052      a[0][0]  = (*func)(tree);
3053      if(is_positive == YES) For(i,n_param) param[i] *= sign[i];
3054      if(logt == YES) For(i,n_param) param[i] = LOG(param[i]);
3055
3056      /*   param[which]   = param[which]-2*hh; */
3057      /*   a[0][0] -= (*func)(tree); */
3058      /*   a[0][0] /= (2.0*hh); */
3059      /*   param[which]   = param[which]+hh; */
3060      a[0][0]  -= f0;
3061      a[0][0]  /= hh;
3062      param[which]   = param[which]-hh;
3063
3064      *err=1e30;
3065      for(i=1;i<n_iter;i++)
3066        {
3067          hh /= 1.4;
3068
3069          /*       param[which]   = param[which]+hh; */
3070          /*       a[0][i]  = (*func)(tree); */
3071          /*       param[which]   = param[which]-2*hh; */
3072          /*       a[0][i] -= (*func)(tree); */
3073          /*       a[0][i] /= (2.0*hh); */
3074          /*       param[which]   = param[which]+hh; */
3075
3076          param[which]   = param[which]+hh;
3077
3078          if(logt == YES) For(j,n_param) param[j] = EXP(MIN(1.E+2,param[j]));
3079          For(i,n_param) sign[i] = param[i] > .0 ? 1. : -1.;
3080          if(is_positive == YES) For(i,n_param) param[i] = FABS(param[i]);
3081          a[0][i]  = (*func)(tree);
3082          if(is_positive == YES) For(i,n_param) param[i] *= sign[i];
3083          if(logt == YES) For(j,n_param) param[j] = LOG(param[j]);
3084
3085          /*   param[which]   = param[which]-2*hh; */
3086          /*   a[0][i] -= (*func)(tree); */
3087          /*   a[0][i] /= (2.0*hh); */
3088          /*   param[which]   = param[which]+hh; */
3089          a[0][i]  -= f0;
3090          a[0][i]  /= hh;
3091          param[which]   = param[which]-hh;
3092
3093
3094          fac=1.4*1.4;
3095          for (j=1;j<=i;j++)
3096            {
3097              a[j][i]=(a[j-1][i]*fac-a[j-1][i-1])/(fac-1.0);
3098              fac=1.4*1.4*fac;
3099
3100              errt=MAX(FABS(a[j][i]-a[j-1][i]),FABS(a[j][i]-a[j-1][i-1]));
3101
3102              if (errt <= *err)
3103                {
3104                  *err=errt;
3105                  ans=a[j][i];
3106                }
3107            }
3108
3109          if(FABS(a[i][i]-a[i-1][i-1]) >= 2.0*(*err)) break;
3110        }
3111    }
3112  For(i,11) Free(a[i]);
3113  Free(a);
3114  Free(sign);
3115
3116  return ans;
3117}
3118
3119//////////////////////////////////////////////////////////////
3120//////////////////////////////////////////////////////////////
3121
3122phydbl Num_Derivatives_One_Param_Nonaligned(phydbl (*func)(t_tree *tree), t_tree *tree,
3123                                            phydbl f0, phydbl **param, int which, int n_param, phydbl stepsize, int logt,
3124                                            phydbl *err, int precise, int is_positive)
3125{
3126  int i,j;
3127  phydbl errt,fac,hh,**a,ans,*sign;
3128  int n_iter;
3129
3130  sign = (phydbl *)mCalloc(n_param,sizeof(phydbl));
3131
3132  a = (phydbl **)mCalloc(11,sizeof(phydbl *));
3133  For(i,11) a[i] = (phydbl *)mCalloc(11,sizeof(phydbl));
3134
3135  n_iter = 10; /* */
3136
3137  ans  = .0;
3138
3139  if(stepsize < SMALL) Warn_And_Exit("\n== h must be nonzero in Dfridr.");
3140
3141  hh=stepsize;
3142
3143  if(!precise)
3144    {
3145      *(param[which])   = *(param[which])+hh;
3146
3147      if(logt == YES) For(i,n_param) *(param[i]) = EXP(MIN(1.E+2,*(param[i])));
3148      For(i,n_param) sign[i] = (*(param[i])) > .0 ? 1. : -1.;
3149      if(is_positive == YES) For(i,n_param) (*(param[i])) = FABS(*(param[i]));
3150      a[0][0]  = (*func)(tree);
3151      if(is_positive == YES) For(i,n_param) (*(param[i])) *= sign[i];
3152      if(logt == YES) For(i,n_param) *(param[i]) = LOG(*(param[i]));
3153
3154      /* printf("\n. f0=%f f1=%f hh=%G %f",f0,a[0][0],hh,*(param[which])); */
3155
3156      a[0][0]  -= f0;
3157      a[0][0]  /= hh;
3158      *(param[which]) = *(param[which])-hh;
3159
3160      ans =  a[0][0];
3161    }
3162  else
3163    {
3164      *(param[which])   = *(param[which])+hh;
3165
3166      if(logt == YES) For(i,n_param) *(param[i]) = EXP(MIN(1.E+2,*(param[i])));
3167      For(i,n_param) sign[i] = (*(param[i])) > .0 ? 1. : -1.;
3168      if(is_positive == YES) For(i,n_param) (*(param[i])) = FABS(*(param[i]));
3169      a[0][0]  = (*func)(tree);
3170      if(is_positive == YES) For(i,n_param) (*(param[i])) *= sign[i];
3171      if(logt == YES) For(i,n_param) *(param[i]) = LOG(*(param[i]));
3172
3173      /*   *(param[which]   = *(param[which]-2*hh; */
3174      /*   a[0][0] -= (*func)(tree); */
3175      /*   a[0][0] /= (2.0*hh); */
3176      /*   *(param[which]   = *(param[which]+hh; */
3177      a[0][0]  -= f0;
3178      a[0][0]  /= hh;
3179      *(param[which])   = *(param[which])-hh;
3180
3181      *err=1e30;
3182      for(i=1;i<n_iter;i++)
3183        {
3184          hh /= 1.4;
3185
3186          /*       *(param[which]   = *(param[which]+hh; */
3187          /*       a[0][i]  = (*func)(tree); */
3188          /*       *(param[which]   = *(param[which]-2*hh; */
3189          /*       a[0][i] -= (*func)(tree); */
3190          /*       a[0][i] /= (2.0*hh); */
3191          /*       *(param[which]   = *(param[which]+hh; */
3192
3193          *(param[which])   = *(param[which])+hh;
3194
3195          if(logt == YES) For(j,n_param) *(param[j]) = EXP(MIN(1.E+2,*(param[j])));
3196          For(i,n_param) sign[i] = (*(param[i])) > .0 ? 1. : -1.;
3197          if(is_positive == YES) For(i,n_param) (*(param[i])) = FABS(*(param[i]));
3198          a[0][i]  = (*func)(tree);
3199          if(is_positive == YES) For(i,n_param) (*(param[i])) *= sign[i];
3200          if(logt == YES) For(j,n_param) *(param[j]) = LOG(*(param[j]));
3201
3202          /*   *(param[which]   = *(param[which]-2*hh; */
3203          /*   a[0][i] -= (*func)(tree); */
3204          /*   a[0][i] /= (2.0*hh); */
3205          /*   *(param[which]   = *(param[which]+hh; */
3206          a[0][i]  -= f0;
3207          a[0][i]  /= hh;
3208          *(param[which])   = *(param[which])-hh;
3209
3210
3211          fac=1.4*1.4;
3212          for (j=1;j<=i;j++)
3213            {
3214              a[j][i]=(a[j-1][i]*fac-a[j-1][i-1])/(fac-1.0);
3215              fac=1.4*1.4*fac;
3216
3217              errt=MAX(FABS(a[j][i]-a[j-1][i]),FABS(a[j][i]-a[j-1][i-1]));
3218
3219              if (errt <= *err)
3220                {
3221                  *err=errt;
3222                  ans=a[j][i];
3223                }
3224            }
3225
3226          if(FABS(a[i][i]-a[i-1][i-1]) >= 2.0*(*err)) break;
3227        }
3228    }
3229  For(i,11) Free(a[i]);
3230  Free(a);
3231  Free(sign);
3232  return ans;
3233}
3234
3235//////////////////////////////////////////////////////////////
3236//////////////////////////////////////////////////////////////
3237
3238int Num_Derivative_Several_Param(t_tree *tree, phydbl *param, int n_param, phydbl stepsize, int logt,
3239                                 phydbl (*func)(t_tree *tree), phydbl *derivatives, int is_positive)
3240{
3241  int i;
3242  phydbl err,f0,*sign;
3243
3244  sign = (phydbl *)mCalloc(n_param,sizeof(phydbl));
3245
3246  if(logt == YES)   For(i,n_param) param[i] = EXP(MIN(1.E+2,param[i]));
3247  For(i,n_param) sign[i] = (param[i]) > .0 ? 1. : -1.;
3248  if(is_positive == YES) For(i,n_param) param[i] = FABS(param[i]);
3249  f0 = (*func)(tree);
3250  if(is_positive == YES) For(i,n_param) param[i] *= sign[i];
3251  if(logt == YES)   For(i,n_param) param[i] = LOG(param[i]);
3252
3253  For(i,n_param)
3254    {
3255      derivatives[i] = Num_Derivatives_One_Param(func,
3256                                                 tree,
3257                                                 f0,
3258                                                 param,
3259                                                 i,
3260                                                 n_param,
3261                                                 stepsize,
3262                                                 logt,
3263                                                 &err,
3264                                                 0,
3265                                                 is_positive
3266                                                 );
3267    }
3268 
3269  Free(sign);
3270
3271  return 1;
3272}
3273
3274//////////////////////////////////////////////////////////////
3275//////////////////////////////////////////////////////////////
3276
3277int Num_Derivative_Several_Param_Nonaligned(t_tree *tree, phydbl **param, int n_param, phydbl stepsize, int logt, 
3278                                            phydbl (*func)(t_tree *tree), phydbl *derivatives, int is_positive)
3279{
3280  int i;
3281  phydbl err,f0,*sign;
3282
3283  sign = (phydbl *)mCalloc(n_param,sizeof(phydbl));
3284
3285  if(logt == YES)   For(i,n_param) (*(param[i])) = EXP(MIN(1.E+2,*(param[i])));
3286  For(i,n_param) sign[i] = (*(param[i])) > .0 ? 1. : -1.;
3287  if(is_positive == YES) For(i,n_param) *(param[i]) = FABS(*(param[i]));
3288  f0 = (*func)(tree);
3289  if(is_positive == YES) For(i,n_param) *(param[i]) *= sign[i];
3290  if(logt == YES)   For(i,n_param) (*(param[i])) = LOG(*(param[i]));
3291
3292
3293  For(i,n_param)
3294    {
3295
3296      derivatives[i] = Num_Derivatives_One_Param_Nonaligned(func,
3297                                                            tree,
3298                                                            f0,
3299                                                            param,
3300                                                            i,
3301                                                            n_param,
3302                                                            stepsize,
3303                                                            logt,
3304                                                            &err,
3305                                                            0,
3306                                                            is_positive
3307                                                            );
3308    }
3309
3310  Free(sign);
3311
3312  return 1;
3313}
3314
3315//////////////////////////////////////////////////////////////
3316//////////////////////////////////////////////////////////////
3317
3318
3319int Compare_Two_States(char *state1, char *state2, int state_size)
3320{                                                 
3321
3322  /* 1 the two states are identical */
3323  /* 0 the two states are different */
3324  int i;
3325
3326  For(i,state_size) if(state1[i] != state2[i]) break;
3327
3328  return (i==state_size)?(1):(0);
3329}
3330
3331//////////////////////////////////////////////////////////////
3332//////////////////////////////////////////////////////////////
3333
3334
3335void Copy_One_State(char *from, char *to, int state_size)
3336{
3337  int i;
3338  For(i,state_size) to[i] = from[i];
3339}
3340
3341//////////////////////////////////////////////////////////////
3342//////////////////////////////////////////////////////////////
3343
3344void Copy_Dist(phydbl **cpy, phydbl **orig, int n)
3345{
3346  int i,j;
3347  For(i,n) For(j,n) cpy[i][j] = orig[i][j];
3348}
3349
3350//////////////////////////////////////////////////////////////
3351//////////////////////////////////////////////////////////////
3352
3353t_mod *Copy_Model(t_mod *ori)
3354{
3355  t_mod *cpy;
3356
3357  cpy             = Make_Model_Basic();
3358
3359  cpy->ns          = ori->ns;
3360  cpy->ras->n_catg = ori->ras->n_catg;
3361  cpy->whichmodel  = ori->whichmodel;
3362
3363  Make_Model_Complete(cpy);
3364  Record_Model(ori,cpy);
3365  cpy->m4mod = M4_Copy_M4_Model(ori, ori->m4mod);
3366
3367  return cpy;
3368}
3369
3370//////////////////////////////////////////////////////////////
3371//////////////////////////////////////////////////////////////
3372
3373void Record_Model(t_mod *ori, t_mod *cpy)
3374{
3375  int i;
3376 
3377  cpy->ns          = ori->ns;
3378  cpy->ras->n_catg = ori->ras->n_catg;
3379 
3380  cpy->kappa->v             = ori->kappa->v;
3381  cpy->ras->alpha->v        = ori->ras->alpha->v;
3382  cpy->lambda->v            = ori->lambda->v;
3383  cpy->ras->pinvar->v            = ori->ras->pinvar->v;
3384  cpy->br_len_multiplier->v = ori->br_len_multiplier->v;
3385
3386  strcpy(cpy->modelname->s,ori->modelname->s);
3387  strcpy(cpy->custom_mod_string->s,ori->custom_mod_string->s);
3388 
3389  cpy->mod_num              = ori->mod_num;
3390  cpy->whichmodel           = ori->whichmodel;
3391  cpy->update_eigen         = ori->update_eigen;
3392  cpy->bootstrap            = ori->bootstrap;
3393  cpy->ras->invar           = ori->ras->invar;
3394  cpy->r_mat->n_diff_rr     = ori->r_mat->n_diff_rr;
3395  cpy->l_min                = ori->l_min;
3396  cpy->l_max                = ori->l_max;
3397  cpy->log_l                = ori->log_l;
3398  cpy->ras->free_mixt_rates = ori->ras->free_mixt_rates;
3399  cpy->ras->gamma_median    = ori->ras->gamma_median;
3400 
3401 
3402  if((ori->whichmodel == CUSTOM) || (ori->whichmodel == GTR))
3403    {
3404      For(i,ori->ns*(ori->ns-1)/2)
3405        {
3406          cpy->r_mat->rr_num->v[i]       = ori->r_mat->rr_num->v[i];
3407          cpy->r_mat->rr_val->v[i]       = ori->r_mat->rr_val->v[i];
3408          cpy->r_mat->rr->v[i]           = ori->r_mat->rr->v[i];
3409          cpy->r_mat->n_rr_per_cat->v[i] = ori->r_mat->n_rr_per_cat->v[i];
3410        }
3411    }
3412 
3413  For(i,cpy->ns)
3414    {
3415      cpy->e_frq->pi->v[i]          = ori->e_frq->pi->v[i];
3416      cpy->e_frq->pi_unscaled->v[i] = ori->e_frq->pi_unscaled->v[i];
3417      cpy->user_b_freq->v[i] = ori->user_b_freq->v[i];
3418    }
3419 
3420  For(i,cpy->ns*cpy->ns) cpy->r_mat->qmat->v[i] = ori->r_mat->qmat->v[i];
3421
3422  For(i,cpy->ras->n_catg)
3423    {
3424      cpy->ras->gamma_r_proba->v[i]          = ori->ras->gamma_r_proba->v[i];
3425      cpy->ras->gamma_rr->v[i]               = ori->ras->gamma_rr->v[i];
3426      cpy->ras->gamma_r_proba_unscaled->v[i] = ori->ras->gamma_r_proba_unscaled->v[i];
3427      cpy->ras->gamma_rr_unscaled->v[i]      = ori->ras->gamma_rr_unscaled->v[i];
3428    }
3429 
3430  cpy->use_m4mod = ori->use_m4mod;
3431
3432  cpy->eigen->size = ori->eigen->size;
3433  For(i,2*ori->ns)       cpy->eigen->space[i]       = ori->eigen->space[i];
3434  For(i,2*ori->ns)       cpy->eigen->space_int[i]   = ori->eigen->space_int[i];
3435  For(i,ori->ns)         cpy->eigen->e_val[i]       = ori->eigen->e_val[i];
3436  For(i,ori->ns)         cpy->eigen->e_val_im[i]    = ori->eigen->e_val_im[i];
3437  For(i,ori->ns*ori->ns) cpy->eigen->r_e_vect[i]    = ori->eigen->r_e_vect[i];
3438  For(i,ori->ns*ori->ns) cpy->eigen->r_e_vect[i]    = ori->eigen->r_e_vect[i];
3439  For(i,ori->ns*ori->ns) cpy->eigen->r_e_vect_im[i] = ori->eigen->r_e_vect_im[i];
3440  For(i,ori->ns*ori->ns) cpy->eigen->l_e_vect[i]    = ori->eigen->l_e_vect[i];
3441  For(i,ori->ns*ori->ns) cpy->eigen->q[i]           = ori->eigen->q[i];
3442}
3443
3444//////////////////////////////////////////////////////////////
3445//////////////////////////////////////////////////////////////
3446
3447//////////////////////////////////////////////////////////////
3448//////////////////////////////////////////////////////////////
3449
3450
3451
3452
3453void Test_Node_Table_Consistency(t_tree *tree)
3454{
3455  int i;
3456
3457  For(i,2*tree->n_otu-2)
3458    {
3459      if(tree->a_nodes[i]->num != i)
3460        {
3461          PhyML_Printf("\n. Node table is not consistent with node numbers.");
3462          PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
3463          Warn_And_Exit("");
3464        }
3465    }
3466}
3467
3468//////////////////////////////////////////////////////////////
3469//////////////////////////////////////////////////////////////
3470
3471
3472void Get_Bip(t_node *a, t_node *d, t_tree *tree)
3473{
3474  int i,j;
3475  t_node *tmp;
3476  int swapped;
3477
3478  if(!d || !a || !tree)
3479    {
3480      PhyML_Printf("\n== d: %p a: %p tree: %p",d,a,tree);
3481      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
3482      Exit("\n");
3483    }
3484
3485  if(d->tax)
3486    {
3487      if(d->common)
3488        {
3489          d->bip_node[0] = (t_node **)mCalloc(1,sizeof(t_node *));
3490          d->bip_node[0][0] = d;
3491          d->bip_size[0]    = 1;
3492          d->bip_size[1]    = -1;
3493          d->bip_size[2]    = -1;
3494
3495          For(i,3)
3496            {
3497              if(a->v[i] == d)
3498                {
3499                  a->bip_size[i] = 0;
3500                  For(j,tree->n_otu)
3501                    {
3502                      if(strcmp(tree->a_nodes[j]->name,d->name))
3503                        {
3504                          a->bip_node[i] = (t_node **)realloc(a->bip_node[i],(a->bip_size[i]+1)*sizeof(t_node *));
3505                          a->bip_node[i][a->bip_size[i]] = tree->a_nodes[j];
3506                          a->bip_size[i]++;
3507                        }
3508                    }
3509                 
3510                  /* Sort bipartition */
3511                  do
3512                    {
3513                      swapped = NO;
3514                      For(j,a->bip_size[i]-1)
3515                        {
3516                          if(a->bip_node[i][j]->num > a->bip_node[i][j+1]->num)
3517                            {
3518                              swapped = YES;
3519                              tmp                 = a->bip_node[i][j];
3520                              a->bip_node[i][j]   = a->bip_node[i][j+1];
3521                              a->bip_node[i][j+1] = tmp;
3522                            }
3523                        }
3524                    }while(swapped == YES);
3525                 
3526                  break;
3527                 
3528                }
3529            }
3530        }
3531      return;
3532    }
3533  else
3534    {
3535      int k;
3536      int d_a;
3537
3538      d_a = -1;
3539
3540      For(i,3)
3541        {
3542          if(d->v[i] != a) Get_Bip(d,d->v[i],tree);
3543          else if(d->v[i] == a) d_a = i;
3544        }
3545
3546      d->bip_size[d_a] = 0;
3547      For(i,3)
3548        if(d->v[i] != a)
3549          {
3550            For(j,3)
3551              {
3552                if(d->v[i]->v[j] == d)
3553                  {
3554                    For(k,d->v[i]->bip_size[j])
3555                      {
3556                        d->bip_node[d_a] = (t_node **)realloc(d->bip_node[d_a],(d->bip_size[d_a]+1)*sizeof(t_node *));
3557                        d->bip_node[d_a][d->bip_size[d_a]] = d->v[i]->bip_node[j][k];
3558                        d->bip_size[d_a]++;
3559                      }
3560                    break;
3561                  }
3562              }
3563          }
3564     
3565      do
3566        {
3567          swapped = NO;
3568          For(j,d->bip_size[d_a]-1)
3569            {
3570              if(d->bip_node[d_a][j]->num > d->bip_node[d_a][j+1]->num)
3571                {
3572                  swapped = YES;
3573                  tmp                   = d->bip_node[d_a][j];
3574                  d->bip_node[d_a][j]   = d->bip_node[d_a][j+1];
3575                  d->bip_node[d_a][j+1] = tmp;
3576                }
3577            }
3578        }while(swapped == YES);
3579       
3580     
3581      For(i,3)
3582        if(a->v[i] == d)
3583          {
3584            a->bip_size[i] = 0;
3585            For(j,tree->n_otu)
3586              {
3587                For(k,d->bip_size[d_a])
3588                  {
3589                    if(d->bip_node[d_a][k] == tree->a_nodes[j])
3590                      break;
3591                  }
3592               
3593                if((k == d->bip_size[d_a]) && (tree->a_nodes[j]->common))
3594                  {
3595                    a->bip_node[i] = (t_node **)realloc(a->bip_node[i],(a->bip_size[i]+1)*sizeof(t_node *));
3596                    a->bip_node[i][a->bip_size[i]] = tree->a_nodes[j];
3597                    a->bip_size[i]++;
3598                  }
3599              }
3600
3601            do
3602              {
3603                swapped = NO;
3604                For(j,a->bip_size[i]-1)
3605                  {
3606                    if(a->bip_node[i][j]->num > a->bip_node[i][j+1]->num)
3607                      {
3608                        swapped = YES;
3609                        tmp                 = a->bip_node[i][j];
3610                        a->bip_node[i][j]   = a->bip_node[i][j+1];
3611                        a->bip_node[i][j+1] = tmp;
3612                      }
3613                  }
3614              }while(swapped == YES);
3615           
3616            if(a->bip_size[i] != tree->n_otu - d->bip_size[d_a])
3617              {
3618                PhyML_Printf("%d %d \n",a->bip_size[i],tree->n_otu - d->bip_size[d_a]);
3619                Warn_And_Exit("\n. Problem in counting bipartitions \n");
3620              }
3621            break;
3622          }
3623    }
3624}
3625
3626//////////////////////////////////////////////////////////////
3627//////////////////////////////////////////////////////////////
3628
3629
3630void Alloc_Bip(t_tree *tree)
3631{
3632  int i;
3633
3634  if(tree->has_bip) return;
3635
3636  tree->has_bip = YES;
3637
3638  For(i,2*tree->n_otu-2)
3639    {
3640      tree->a_nodes[i]->bip_size = (int *)mCalloc(3,sizeof(int));
3641      tree->a_nodes[i]->bip_node = (t_node ***)mCalloc(3,sizeof(t_node **));
3642
3643/*       For(j,3) */
3644/*      { */
3645/*        tree->a_nodes[i]->bip_node[j] = (t_node **)mCalloc(tree->n_otu,sizeof(t_node *)); */
3646/*      } */
3647    }
3648}
3649
3650//////////////////////////////////////////////////////////////
3651//////////////////////////////////////////////////////////////
3652
3653
3654int Sort_Phydbl_Increase(const void *a, const void *b)
3655{
3656  if((*(phydbl *)(a)) <= (*(phydbl *)(b))) return -1;
3657  else return 1;
3658}
3659
3660//////////////////////////////////////////////////////////////
3661//////////////////////////////////////////////////////////////
3662
3663
3664int Sort_String(const void *a, const void *b)
3665{
3666  return(strcmp((*(const char **)(a)), (*(const char **)(b))));
3667}
3668
3669//////////////////////////////////////////////////////////////
3670//////////////////////////////////////////////////////////////
3671
3672int Compare_Bip(t_tree *tree1, t_tree *tree2, int on_existing_edges_only)
3673{
3674  int i,j,k;
3675  t_edge *b1,*b2;
3676/*   char **bip1,**bip2; */
3677/*   int *bip1,*bip2; */
3678  t_node **bip1, **bip2;
3679  int bip_size1, bip_size2, bip_size;
3680  int different,identical;
3681  int n_edges;
3682
3683  /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
3684  /* WARNING: call Match_Tip_Numbers and Get_Bip before using this function. */
3685  /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
3686 
3687  if(on_existing_edges_only == YES)
3688    {
3689      n_edges = 0;
3690      For(i,2*tree1->n_otu-3) 
3691        if(tree1->a_edges[i]->does_exist && tree2->a_edges[i]->does_exist) n_edges++;
3692      n_edges -= tree1->n_otu;
3693    }
3694  else
3695    {
3696      n_edges = tree1->n_otu-3;
3697    }
3698 
3699  identical = 0;
3700  different = 0;
3701  For(i,2*tree1->n_otu-3)
3702    {
3703      b1 = tree1->a_edges[i];     
3704      bip_size1 = MIN(b1->left->bip_size[b1->l_r],b1->rght->bip_size[b1->r_l]);
3705     
3706      if(bip_size1 > 1 && ((on_existing_edges_only == YES && b1->does_exist) || (on_existing_edges_only == NO)))
3707        {
3708          For(j,2*tree2->n_otu-3)
3709            {
3710              b2 = tree2->a_edges[j];
3711              bip_size2 = MIN(b2->left->bip_size[b2->l_r],b2->rght->bip_size[b2->r_l]);
3712
3713              if(bip_size2 > 1 && ((on_existing_edges_only == YES && b2->does_exist) || (on_existing_edges_only == NO)))
3714                {                 
3715                  if(bip_size1 == bip_size2)
3716                    {
3717                      bip_size = bip_size1;
3718                     
3719                      if(b1->left->bip_size[b1->l_r] == b1->rght->bip_size[b1->r_l])
3720                        {
3721/*                        if(b1->left->bip_name[b1->l_r][0][0] < b1->rght->bip_name[b1->r_l][0][0]) */
3722                          if(b1->left->bip_node[b1->l_r][0]->num < b1->rght->bip_node[b1->r_l][0]->num)
3723                            {
3724/*                            bip1 = b1->left->bip_name[b1->l_r]; */
3725                              bip1 = b1->left->bip_node[b1->l_r];
3726                            }
3727                          else
3728                            {
3729/*                            bip1 = b1->rght->bip_name[b1->r_l]; */
3730                              bip1 = b1->rght->bip_node[b1->r_l];
3731                            }
3732                        }
3733                      else if(b1->left->bip_size[b1->l_r] < b1->rght->bip_size[b1->r_l])
3734                        {
3735/*                        bip1 = b1->left->bip_name[b1->l_r]; */
3736                          bip1 = b1->left->bip_node[b1->l_r];
3737                        }
3738                      else
3739                        {
3740/*                        bip1 = b1->rght->bip_name[b1->r_l]; */
3741                          bip1 = b1->rght->bip_node[b1->r_l];
3742                        }
3743
3744
3745                      if(b2->left->bip_size[b2->l_r] == b2->rght->bip_size[b2->r_l])
3746                        {
3747/*                        if(b2->left->bip_name[b2->l_r][0][0] < b2->rght->bip_name[b2->r_l][0][0]) */
3748                          if(b2->left->bip_node[b2->l_r][0]->num < b2->rght->bip_node[b2->r_l][0]->num)
3749                            {
3750/*                            bip2 = b2->left->bip_name[b2->l_r]; */
3751                              bip2 = b2->left->bip_node[b2->l_r];
3752                            }
3753                          else
3754                            {
3755/*                            bip2 = b2->rght->bip_name[b2->r_l]; */
3756                              bip2 = b2->rght->bip_node[b2->r_l];
3757                            }
3758                        }
3759                      else if(b2->left->bip_size[b2->l_r] < b2->rght->bip_size[b2->r_l])
3760                        {
3761/*                        bip2 = b2->left->bip_name[b2->l_r]; */
3762                          bip2 = b2->left->bip_node[b2->l_r];
3763                        }
3764                      else
3765                        {
3766/*                        bip2 = b2->rght->bip_name[b2->r_l]; */
3767                          bip2 = b2->rght->bip_node[b2->r_l];
3768                        }
3769
3770                      if(bip_size == 1) Warn_And_Exit("\n. Problem in Compare_Bip\n");
3771
3772                      For(k,bip_size)
3773                        {
3774/*                        if(strcmp(bip1[k],bip2[k])) break; */
3775                          if(bip1[k]->num != bip2[k]->num) break;
3776                        }
3777
3778                      if(k == bip_size) /* Branches b1 and b2 define the same bipartition */
3779                        {
3780                          b1->bip_score++;
3781                          b2->bip_score++;
3782                          identical++;                   
3783                          goto out;
3784                        }
3785                      else 
3786                        {
3787                          different++; // Bipartitions have identical sizes but distinct elements
3788                        }
3789                    }
3790                  else different++; // Biparition have different sizes
3791                }
3792            }
3793        }
3794    out: ;
3795    }
3796  return n_edges - identical;
3797  /* return different; */
3798}
3799
3800//////////////////////////////////////////////////////////////
3801//////////////////////////////////////////////////////////////
3802
3803/* Modifiy the tip numbering in tree2 so that tips in
3804   tree1 and tree2 corresponding to the same taxon name
3805   also have the same tip numbering */
3806void Match_Tip_Numbers(t_tree *tree1, t_tree *tree2)
3807{
3808  int i,j;
3809
3810  if(tree1->n_otu != tree2->n_otu)
3811    {
3812      PhyML_Printf("\n. tree1 and tree2 must have the same number of tips.");
3813      /* Otherwise, if tree2->n_otu < tree->n_otu, then some tips in tree2
3814         will have a number (->num) that is the same as the number of an
3815         internal node in this tree */
3816      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
3817      Warn_And_Exit("");     
3818    }
3819
3820  For(i,tree1->n_otu)
3821    {
3822      For(j,tree2->n_otu)
3823        {
3824          if(!strcmp(tree1->a_nodes[i]->name,tree2->a_nodes[j]->name))
3825            {
3826              tree2->a_nodes[j]->num = tree1->a_nodes[i]->num;
3827              break;
3828            }
3829        }
3830    }
3831
3832}
3833
3834//////////////////////////////////////////////////////////////
3835//////////////////////////////////////////////////////////////
3836
3837void Test_Multiple_Data_Set_Format(option *io)
3838{
3839  char *line;
3840
3841  line = (char *)mCalloc(T_MAX_LINE,sizeof(char));
3842
3843  io->n_trees = 0;
3844
3845  while(fgets(line,T_MAX_LINE,io->fp_in_tree)) if(strstr(line,";")) io->n_trees++;
3846
3847  Free(line);
3848
3849  if((io->mod->bootstrap > 1) && (io->n_trees > 1))
3850    Warn_And_Exit("\n. Bootstrap option is not allowed with multiple input trees !\n");
3851
3852  rewind(io->fp_in_tree);
3853
3854  return;
3855}
3856
3857//////////////////////////////////////////////////////////////
3858//////////////////////////////////////////////////////////////
3859
3860
3861int Are_Compatible(char *statea, char *stateb, int stepsize, int datatype)
3862{
3863  int i,j;
3864  char a,b;
3865
3866  if(datatype == NT)
3867    {
3868      For(i,stepsize)
3869        {
3870          a = statea[i];
3871          For(j,stepsize)
3872            {
3873              b = stateb[j];
3874
3875              switch(a)
3876                {
3877                case 'A':
3878                  {
3879                    switch(b)
3880                      {
3881                      case 'A' :
3882                      case 'M' :
3883                      case 'R' :
3884                      case 'W' :
3885                      case 'D' :
3886                      case 'H' :
3887                      case 'V' :
3888                      case 'X' : {b=b; break;}
3889                      default : return 0;
3890                      }
3891                    break;
3892                  }
3893                case 'G':
3894                  {
3895                    switch(b)
3896                      {
3897                      case 'G' :
3898                      case 'R' :
3899                      case 'S' :
3900                      case 'K' :
3901                      case 'B' :
3902                      case 'D' :
3903                      case 'V' :
3904                      case 'X' : {b=b; break;}
3905                      default : return 0;
3906                      }
3907                    break;
3908                  }
3909                case 'C':
3910                  {
3911                    switch(b)
3912                      {
3913                      case 'C' :
3914                      case 'M' :
3915                      case 'S' :
3916                      case 'Y' :
3917                      case 'B' :
3918                      case 'H' :
3919                      case 'V' :
3920                      case 'X' : {b=b; break;}
3921                      default : return 0;
3922                      }
3923                    break;
3924                  }
3925                case 'T':
3926                  {
3927                    switch(b)
3928                      {
3929                      case 'T' :
3930                      case 'W' :
3931                      case 'Y' :
3932                      case 'K' :
3933                      case 'B' :
3934                      case 'D' :
3935                      case 'H' :
3936                      case 'X' :
3937                        {b=b; break;}
3938                      default : return 0;
3939                      }
3940                    break;
3941                  }
3942                case 'M' :
3943                  {
3944                    switch(b)
3945                      {
3946                      case 'M' :
3947                      case 'A' :
3948                      case 'C' :
3949                      case 'R' :
3950                      case 'W' :
3951                      case 'S' :
3952                      case 'Y' :
3953                      case 'B' :
3954                      case 'D' :
3955                      case 'H' :
3956                      case 'V' :
3957                      case 'X' :
3958                        {b=b; break;}
3959                      default : return 0;
3960                      }
3961                    break;
3962                  }
3963                case 'R' :
3964                  {
3965                    switch(b)
3966                      {
3967                      case 'R' :
3968                      case 'A' :
3969                      case 'G' :
3970                      case 'M' :
3971                      case 'W' :
3972                      case 'S' :
3973                      case 'K' :
3974                      case 'B' :
3975                      case 'D' :
3976                      case 'H' :
3977                      case 'V' :
3978                      case 'X' : {b=b; break;}
3979                      default : return 0;
3980                      }
3981                    break;
3982                  }
3983
3984                case 'W' :
3985                  {
3986                    switch(b)
3987                      {
3988                      case 'W' :
3989                      case 'A' :
3990                      case 'T' :
3991                      case 'M' :
3992                      case 'R' :
3993                      case 'Y' :
3994                      case 'K' :
3995                      case 'B' :
3996                      case 'D' :
3997                      case 'H' :
3998                      case 'V' :
3999                      case 'X' : {b=b; break;}
4000                      default : return 0;
4001                      }
4002                    break;
4003                  }
4004
4005                case 'S' :
4006                  {
4007                    switch(b)
4008                      {
4009                      case 'S' :
4010                      case 'C' :
4011                      case 'G' :
4012                      case 'M' :
4013                      case 'R' :
4014                      case 'Y' :
4015                      case 'K' :
4016                      case 'B' :
4017                      case 'D' :
4018                      case 'H' :
4019                      case 'V' :
4020                      case 'X' : {b=b; break;}
4021                      default : return 0;
4022                      }
4023                    break;
4024                  }
4025
4026                case 'Y' :
4027                  {
4028                    switch(b)
4029                      {
4030                      case 'Y' :
4031                      case 'C' :
4032                      case 'T' :
4033                      case 'M' :
4034                      case 'W' :
4035                      case 'S' :
4036                      case 'K' :
4037                      case 'B' :
4038                      case 'D' :
4039                      case 'H' :
4040                      case 'V' :
4041                      case 'X' : {b=b; break;}
4042                      default : return 0;
4043                      }
4044                    break;
4045                  }
4046
4047                case 'K' :
4048                  {
4049                    switch(b)
4050                      {
4051                      case 'K' :
4052                      case 'G' :
4053                      case 'T' :
4054                      case 'R' :
4055                      case 'W' :
4056                      case 'S' :
4057                      case 'Y' :
4058                      case 'B' :
4059                      case 'D' :
4060                      case 'H' :
4061                      case 'V' :
4062                      case 'X' : {b=b; break;}
4063                      default : return 0;
4064                      }
4065                    break;
4066                  }
4067                case 'B' :
4068                  {
4069                    switch(b)
4070                      {
4071                      case 'B' :
4072                      case 'C' :
4073                      case 'G' :
4074                      case 'T' :
4075                      case 'M' :
4076                      case 'R' :
4077                      case 'W' :
4078                      case 'S' :
4079                      case 'Y' :
4080                      case 'K' :
4081                      case 'D' :
4082                      case 'H' :
4083                      case 'V' :
4084                      case 'X' : {b=b; break;}
4085                      default : return 0;
4086                      }
4087                    break;
4088                  }
4089                case 'D' :
4090                  {
4091                    switch(b)
4092                      {
4093                      case 'D' :
4094                      case 'A' :
4095                      case 'G' :
4096                      case 'T' :
4097                      case 'M' :
4098                      case 'R' :
4099                      case 'W' :
4100                      case 'S' :
4101                      case 'Y' :
4102                      case 'K' :
4103                      case 'B' :
4104                      case 'H' :
4105                      case 'V' :
4106                      case 'X' : {b=b; break;}
4107                      default : return 0;
4108                      }
4109                    break;
4110                  }
4111                case 'H' :
4112                  {
4113                    switch(b)
4114                      {
4115                      case 'H' :
4116                      case 'A' :
4117                      case 'C' :
4118                      case 'T' :
4119                      case 'M' :
4120                      case 'R' :
4121                      case 'W' :
4122                      case 'S' :
4123                      case 'Y' :
4124                      case 'K' :
4125                      case 'B' :
4126                      case 'D' :
4127                      case 'V' :
4128                      case 'X' : {b=b; break;}
4129                      default : return 0;
4130                      }
4131                    break;
4132                  }
4133                case 'V' :
4134                  {
4135                    switch(b)
4136                      {
4137                      case 'V' :
4138                      case 'A' :
4139                      case 'C' :
4140                      case 'G' :
4141                      case 'M' :
4142                      case 'R' :
4143                      case 'W' :
4144                      case 'S' :
4145                      case 'Y' :
4146                      case 'K' :
4147                      case 'B' :
4148                      case 'D' :
4149                      case 'H' :
4150                      case 'X' : {b=b; break;}
4151                      default : return 0;
4152                      }
4153                    break;
4154                  }
4155                case 'X' :
4156                  {
4157                    switch(b)
4158                      {
4159                      case 'X' :
4160                      case 'A' :
4161                      case 'C' :
4162                      case 'G' :
4163                      case 'T' :
4164                      case 'M' :
4165                      case 'R' :
4166                      case 'W' :
4167                      case 'S' :
4168                      case 'Y' :
4169                      case 'K' :
4170                      case 'B' :
4171                      case 'D' :
4172                      case 'H' :
4173                      case 'V' : {b=b; break;}
4174                      default : return 0;
4175                      }
4176                    break;
4177                  }
4178                default :
4179                  {
4180                      PhyML_Printf("\n. Err. in Are_Compatible\n");
4181                      PhyML_Printf("\n. Please check that characters `%c` and `%c`\n",a,b);
4182                      PhyML_Printf("  correspond to existing nucleotides.\n");
4183                      Warn_And_Exit("\n");
4184                      return 0;
4185                  }
4186                }
4187            }
4188        }
4189    }
4190  else if(datatype == AA)
4191    {
4192      a = statea[0]; b = stateb[0];
4193      switch(a)
4194        {
4195        case 'A' :
4196          {
4197            switch(b)
4198              {
4199              case 'A' :
4200              case 'X' : {b=b; break;}
4201              default : return 0;
4202              }
4203            break;
4204          }
4205        case 'R' :
4206          {
4207            switch(b)
4208              {
4209              case 'R' :
4210              case 'X' : {b=b; break;}
4211              default : return 0;
4212              }
4213            break;
4214          }
4215        case 'N' :
4216          {
4217            switch(b)
4218              {
4219              case 'N' :
4220              case 'B' :
4221              case 'X' : {b=b; break;}
4222              default : return 0;
4223              }
4224            break;
4225          }
4226        case 'B' :
4227          {
4228            switch(b)
4229              {
4230              case 'N' :
4231              case 'B' :
4232              case 'X' : {b=b; break;}
4233              default : return 0;
4234              }
4235            break;
4236          }
4237        case 'D' :
4238          {
4239            switch(b)
4240              {
4241              case 'D' :
4242              case 'X' : {b=b; break;}
4243              default : return 0;
4244              }
4245            break;
4246          }
4247        case 'C' :
4248          {
4249            switch(b)
4250              {
4251              case 'C' :
4252              case 'X' : {b=b; break;}
4253              default : return 0;
4254              }
4255            break;
4256          }
4257        case 'Q' :
4258          {
4259            switch(b)
4260              {
4261              case 'Q' :
4262              case 'Z' :
4263              case 'X' : {b=b; break;}
4264              default : return 0;
4265              }
4266            break;
4267          }
4268        case 'Z' :
4269          {
4270            switch(b)
4271              {
4272              case 'Q' :
4273              case 'Z' :
4274              case 'X' : {b=b; break;}
4275              default : return 0;
4276              }
4277            break;
4278          }
4279        case 'E' :
4280          {
4281            switch(b)
4282              {
4283              case 'E' :
4284              case 'X' : {b=b; break;}
4285              default : return 0;
4286              }
4287            break;
4288          }
4289        case 'G' :
4290          {
4291            switch(b)
4292              {
4293              case 'G' :
4294              case 'X' : {b=b; break;}
4295              default : return 0;
4296              }
4297            break;
4298          }
4299        case 'H' :
4300          {
4301            switch(b)
4302              {
4303              case 'H' :
4304              case 'X' : {b=b; break;}
4305              default : return 0;
4306              }
4307            break;
4308          }
4309        case 'I' :
4310          {
4311            switch(b)
4312              {
4313              case 'I' :
4314              case 'X' : {b=b; break;}
4315              default : return 0;
4316              }
4317            break;
4318          }
4319        case 'L' :
4320          {
4321            switch(b)
4322              {
4323              case 'L' :
4324              case 'X' : {b=b; break;}
4325              default : return 0;
4326              }
4327            break;
4328          }
4329        case 'K' :
4330          {
4331            switch(b)
4332              {
4333              case 'K' :
4334              case 'X' : {b=b; break;}
4335              default : return 0;
4336              }
4337            break;
4338          }
4339        case 'M' :
4340          {
4341            switch(b)
4342              {
4343              case 'M' :
4344              case 'X' : {b=b; break;}
4345              default : return 0;
4346              }
4347            break;
4348          }
4349        case 'F' :
4350          {
4351            switch(b)
4352              {
4353              case 'F' :
4354              case 'X' : {b=b; break;}
4355              default : return 0;
4356              }
4357            break;
4358          }
4359        case 'P' :
4360          {
4361            switch(b)
4362              {
4363              case 'P' :
4364              case 'X' : {b=b; break;}
4365              default : return 0;
4366              }
4367            break;
4368          }
4369        case 'S' :
4370          {
4371            switch(b)
4372              {
4373              case 'S' :
4374              case 'X' : {b=b; break;}
4375              default : return 0;
4376              }
4377            break;
4378          }
4379        case 'T' :
4380          {
4381            switch(b)
4382              {
4383              case 'T' :
4384              case 'X' : {b=b; break;}
4385              default : return 0;
4386              }
4387            break;
4388          }
4389        case 'W' :
4390          {
4391            switch(b)
4392              {
4393              case 'W' :
4394              case 'X' : {b=b; break;}
4395              default : return 0;
4396              }
4397            break;
4398          }
4399        case 'Y' :
4400          {
4401            switch(b)
4402              {
4403              case 'Y' :
4404              case 'X' : {b=b; break;}
4405              default : return 0;
4406              }
4407            break;
4408          }
4409        case 'V' :
4410          {
4411            switch(b)
4412              {
4413              case 'V' :
4414              case 'X' : {b=b; break;}
4415              default : return 0;
4416              }
4417            break;
4418          }
4419        case 'X' :
4420          {
4421            switch(b)
4422              {
4423              case 'A':case 'R':case 'N' :case 'B' :case 'D' :
4424              case 'C':case 'Q':case 'Z' :case 'E' :case 'G' :
4425              case 'H':case 'I':case 'L' :case 'K' :case 'M' :
4426              case 'F':case 'P':case 'S' :case 'T' :case 'W' :
4427              case 'Y':case 'V': case 'X' : {b=b; break;}
4428              default : return 0;
4429              }
4430            break;
4431          }
4432        default :
4433          {
4434            PhyML_Printf("\n. Err. in Are_Compatible\n");
4435            PhyML_Printf("\n. Please check that characters `%c` and `%c`\n",a,b);
4436            PhyML_Printf("  correspond to existing amino-acids.\n");
4437            Warn_And_Exit("\n");
4438            return 0;
4439          }
4440        }
4441    }
4442  else if(datatype == GENERIC)   
4443    {
4444      if(Is_Ambigu(statea,GENERIC,stepsize) || Is_Ambigu(stateb,GENERIC,stepsize)) return 1;
4445      else
4446        {
4447          int a,b;
4448          char format[6];     
4449         
4450          sprintf(format,"%%%dd",stepsize);     
4451
4452          if(!sscanf(statea,format,&a))
4453            {       
4454              PhyML_Printf("\n. statea = %s",statea);
4455              PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
4456              Warn_And_Exit("");
4457            }
4458          if(!sscanf(stateb,format,&b))
4459            {       
4460              PhyML_Printf("\n. statea = %s",stateb);
4461              PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
4462              Warn_And_Exit("");
4463            }
4464         
4465/*        PhyML_Printf("\n. %s %d a=%d b=%d ",__FILE__,__LINE__,a,b);  */
4466
4467          if(a == b) return 1;
4468        }
4469      return 0;
4470    }
4471
4472  return 1;
4473}
4474
4475//////////////////////////////////////////////////////////////
4476//////////////////////////////////////////////////////////////
4477
4478
4479void Hide_Ambiguities(calign *data)
4480{
4481  int i;
4482  For(i,data->crunch_len) if(data->ambigu[i]) data->wght[i] = 0;
4483}
4484
4485//////////////////////////////////////////////////////////////
4486//////////////////////////////////////////////////////////////
4487
4488void Copy_Tree(t_tree *ori, t_tree *cpy)
4489{
4490  int i,j;
4491 
4492  For(i,2*ori->n_otu-2)
4493    {
4494      For(j,3)
4495        {
4496          if(ori->a_nodes[i]->v[j])
4497            {
4498              cpy->a_nodes[i]->v[j] = cpy->a_nodes[ori->a_nodes[i]->v[j]->num];
4499              cpy->a_nodes[i]->l[j] = ori->a_nodes[i]->l[j];
4500              cpy->a_nodes[i]->b[j] = cpy->a_edges[ori->a_nodes[i]->b[j]->num];
4501            }
4502          else
4503            {
4504              cpy->a_nodes[i]->v[j] = NULL;
4505              cpy->a_nodes[i]->b[j] = NULL;
4506            }
4507        }
4508    }
4509
4510  For(i,2*ori->n_otu-3) 
4511    {
4512      cpy->a_edges[i]->l->v             = ori->a_edges[i]->l->v;
4513      cpy->a_edges[i]->left             = cpy->a_nodes[ori->a_edges[i]->left->num];
4514      cpy->a_edges[i]->rght             = cpy->a_nodes[ori->a_edges[i]->rght->num];
4515      cpy->a_edges[i]->l_v1             = ori->a_edges[i]->l_v1;
4516      cpy->a_edges[i]->l_v2             = ori->a_edges[i]->l_v2;
4517      cpy->a_edges[i]->r_v1             = ori->a_edges[i]->r_v1;
4518      cpy->a_edges[i]->r_v2             = ori->a_edges[i]->r_v2;
4519      cpy->a_edges[i]->l_r              = ori->a_edges[i]->l_r;
4520      cpy->a_edges[i]->r_l              = ori->a_edges[i]->r_l;
4521      cpy->a_edges[i]->does_exist       = ori->a_edges[i]->does_exist;
4522    }
4523
4524
4525  For(i,ori->n_otu)
4526    {
4527      cpy->a_nodes[i]->tax = YES;
4528     
4529      Free(cpy->a_nodes[i]->name);
4530
4531      cpy->a_nodes[i]->name = (char *)mCalloc(strlen(ori->a_nodes[i]->name)+1,sizeof(char));
4532      cpy->a_nodes[i]->ori_name = cpy->a_nodes[i]->name ;
4533
4534      strcpy(cpy->a_nodes[i]->name,ori->a_nodes[i]->name);
4535    }
4536
4537  if(ori->n_root)
4538    {
4539      cpy->e_root = cpy->a_edges[ori->e_root->num];
4540      cpy->n_root = cpy->a_nodes[ori->n_root->num];
4541      Add_Root(cpy->e_root,cpy);
4542    }
4543
4544  cpy->num_curr_branch_available = 0;
4545  cpy->t_beg = ori->t_beg;
4546
4547/*   Connect_Edges_To_Nodes_Recur(cpy->a_nodes[0],cpy->a_nodes[0]->v[0],cpy); */
4548/*   Update_Dirs(cpy); */
4549}
4550
4551//////////////////////////////////////////////////////////////
4552//////////////////////////////////////////////////////////////
4553
4554void Prune_Subtree(t_node *a, t_node *d, t_edge **target, t_edge **residual, t_tree *tree)
4555{
4556  t_node *v1, *v2;
4557  t_edge *b1, *b2;
4558  int dir_v1, dir_v2;
4559  int i;
4560/*   phydbl ***buff_p_lk; */
4561  phydbl *buff_p_lk;
4562  int *buff_scale;
4563  int *buff_p_pars, *buff_pars, *buff_p_lk_loc, *buff_patt_id;
4564  unsigned int *buff_ui;
4565  short int *buff_p_lk_tip;
4566
4567
4568  if(a->tax)
4569    {
4570      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
4571      Exit("\n");
4572    }
4573
4574  dir_v1 = dir_v2 = -1;
4575  For(i,3)
4576    {
4577      if(a->v[i] != d)
4578        {
4579          if(dir_v1 < 0) dir_v1 = i;
4580          else           dir_v2 = i;
4581        }
4582    }
4583
4584  if(a->v[dir_v1]->num < a->v[dir_v2]->num)
4585    {
4586      v1 = a->v[dir_v1];
4587      v2 = a->v[dir_v2];
4588      b1 = a->b[dir_v1];
4589      b2 = a->b[dir_v2];
4590    }
4591  else
4592    {
4593      v1 = a->v[dir_v2];
4594      v2 = a->v[dir_v1];
4595      b1 = a->b[dir_v2];
4596      b2 = a->b[dir_v1];
4597    }
4598
4599  /* if(v1->tax && v2->tax) PhyML_Printf("\n. Pruning is meaningless here.\n"); */
4600
4601  a->v[dir_v1] = NULL;
4602  a->v[dir_v2] = NULL;
4603  a->b[dir_v1] = NULL;
4604  a->b[dir_v2] = NULL;
4605
4606  if(v1 == b1->left)
4607    {
4608      b1->rght = v2;
4609
4610      if(v2 == b2->left)
4611        {
4612          buff_p_lk            = b1->p_lk_rght;
4613          b1->p_lk_rght        = b2->p_lk_left;
4614          b2->p_lk_left        = buff_p_lk;
4615
4616          buff_p_lk_tip        = b1->p_lk_tip_r;
4617          b1->p_lk_tip_r       = b2->p_lk_tip_l;
4618          b2->p_lk_tip_l       = buff_p_lk_tip;
4619
4620          buff_scale           = b1->sum_scale_rght;
4621          b1->sum_scale_rght   = b2->sum_scale_left;
4622          b2->sum_scale_left   = buff_scale;
4623
4624          buff_scale             = b1->sum_scale_rght_cat;
4625          b1->sum_scale_rght_cat = b2->sum_scale_left_cat;
4626          b2->sum_scale_left_cat = buff_scale;
4627
4628          buff_pars            = b1->pars_r;
4629          b1->pars_r           = b2->pars_l;
4630          b2->pars_l           = buff_pars;
4631
4632          buff_ui              = b1->ui_r;
4633          b1->ui_r             = b2->ui_l;
4634          b2->ui_l             = buff_ui;
4635
4636          buff_p_pars          = b1->p_pars_r;
4637          b1->p_pars_r         = b2->p_pars_l;
4638          b2->p_pars_l         = buff_p_pars;
4639
4640          buff_p_lk_loc        = b1->p_lk_loc_rght;
4641          b1->p_lk_loc_rght    = b2->p_lk_loc_left;
4642          b2->p_lk_loc_left    = buff_p_lk_loc;
4643
4644          buff_patt_id         = b1->patt_id_rght;
4645          b1->patt_id_rght     = b2->patt_id_left;
4646          b2->patt_id_left     = buff_patt_id;
4647
4648        }
4649      else
4650        {
4651          buff_p_lk            = b1->p_lk_rght; /* b1->p_lk_rght = NULL if b1->rght->tax */
4652          b1->p_lk_rght        = b2->p_lk_rght; /* b2->p_lk_rght = NULL if b2->rght->tax */ 
4653          b2->p_lk_rght        = buff_p_lk;
4654
4655          buff_p_lk_tip        = b1->p_lk_tip_r;
4656          b1->p_lk_tip_r       = b2->p_lk_tip_r;
4657          b2->p_lk_tip_r       = buff_p_lk_tip;
4658
4659          buff_scale           = b1->sum_scale_rght;
4660          b1->sum_scale_rght = b2->sum_scale_rght;
4661          b2->sum_scale_rght = buff_scale;
4662
4663          buff_pars            = b1->pars_r;
4664          b1->pars_r           = b2->pars_r;
4665          b2->pars_r           = buff_pars;
4666
4667          buff_ui              = b1->ui_r;
4668          b1->ui_r             = b2->ui_r;
4669          b2->ui_r             = buff_ui;
4670
4671          buff_p_pars          = b1->p_pars_r;
4672          b1->p_pars_r         = b2->p_pars_r;
4673          b2->p_pars_r         = buff_p_pars;
4674
4675          buff_p_lk_loc        = b1->p_lk_loc_rght;
4676          b1->p_lk_loc_rght    = b2->p_lk_loc_rght;
4677          b2->p_lk_loc_rght    = buff_p_lk_loc;
4678
4679          buff_patt_id         = b1->patt_id_rght;
4680          b1->patt_id_rght     = b2->patt_id_rght;
4681          b2->patt_id_rght     = buff_patt_id;
4682
4683        }
4684    }
4685  else
4686    {
4687      b1->left = v2;
4688
4689      if(v2 == b2->left)
4690        {
4691          buff_p_lk            = b1->p_lk_left;
4692          b1->p_lk_left        = b2->p_lk_left;
4693          b2->p_lk_left        = buff_p_lk;
4694
4695          buff_p_lk_tip        = b1->p_lk_tip_l;
4696          b1->p_lk_tip_l       = b2->p_lk_tip_l;
4697          b2->p_lk_tip_l       = buff_p_lk_tip;
4698
4699          buff_scale           = b1->sum_scale_left;
4700          b1->sum_scale_left = b2->sum_scale_left;
4701          b2->sum_scale_left = buff_scale;
4702
4703          buff_scale             = b1->sum_scale_left_cat;
4704          b1->sum_scale_left_cat = b2->sum_scale_left_cat;
4705          b2->sum_scale_left_cat = buff_scale;
4706
4707          buff_pars            = b1->pars_l;
4708          b1->pars_l           = b2->pars_l;
4709          b2->pars_l           = buff_pars;
4710
4711          buff_ui              = b1->ui_l;
4712          b1->ui_l             = b2->ui_l;
4713          b2->ui_l             = buff_ui;
4714
4715          buff_p_pars          = b1->p_pars_l;
4716          b1->p_pars_l         = b2->p_pars_l;
4717          b2->p_pars_l         = buff_p_pars;
4718
4719          buff_p_lk_loc        = b1->p_lk_loc_left;
4720          b1->p_lk_loc_left    = b2->p_lk_loc_left;
4721          b2->p_lk_loc_left    = buff_p_lk_loc;
4722
4723          buff_patt_id         = b1->patt_id_left;
4724          b1->patt_id_left     = b2->patt_id_left;
4725          b2->patt_id_left     = buff_patt_id;
4726
4727        }
4728      else
4729        {
4730          buff_p_lk            = b1->p_lk_left;
4731          b1->p_lk_left        = b2->p_lk_rght; /* b2->p_lk_rght = NULL if b2->rght->tax */
4732          b2->p_lk_rght        = buff_p_lk;
4733
4734          buff_p_lk_tip        = b1->p_lk_tip_l;
4735          b1->p_lk_tip_l       = b2->p_lk_tip_r;
4736          b2->p_lk_tip_r       = buff_p_lk_tip;
4737
4738          buff_scale           = b1->sum_scale_left;
4739          b1->sum_scale_left = b2->sum_scale_rght;
4740          b2->sum_scale_rght = buff_scale;
4741
4742          buff_scale             = b1->sum_scale_left_cat;
4743          b1->sum_scale_left_cat = b2->sum_scale_rght_cat;
4744          b2->sum_scale_rght_cat = buff_scale;
4745
4746          buff_pars            = b1->pars_l;
4747          b1->pars_l           = b2->pars_r;
4748          b2->pars_r           = buff_pars;
4749
4750          buff_ui              = b1->ui_l;
4751          b1->ui_l             = b2->ui_r;
4752          b2->ui_r             = buff_ui;
4753
4754          buff_p_pars          = b1->p_pars_l;
4755          b1->p_pars_l         = b2->p_pars_r;
4756          b2->p_pars_r         = buff_p_pars;
4757
4758          buff_p_lk_loc        = b1->p_lk_loc_left;
4759          b1->p_lk_loc_left    = b2->p_lk_loc_rght;
4760          b2->p_lk_loc_rght    = buff_p_lk_loc;
4761
4762          buff_patt_id         = b1->patt_id_left;
4763          b1->patt_id_left     = b2->patt_id_rght;
4764          b2->patt_id_rght     = buff_patt_id;
4765        }
4766    }
4767 
4768  For(i,3)
4769    if(v2->v[i] == a)
4770      {
4771        v2->v[i] = v1;
4772        v2->b[i] = b1;
4773        break;
4774      }
4775
4776#ifdef DEBUG
4777  if(i == 3)
4778    {
4779      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
4780      Warn_And_Exit("");
4781    }
4782#endif
4783
4784  For(i,3)
4785    if(v1->v[i] == a)
4786      {
4787        v1->v[i] = v2;
4788        break;
4789      }
4790
4791#ifdef DEBUG
4792  if(i == 3)
4793    {
4794      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
4795      Warn_And_Exit("");
4796    }
4797#endif
4798
4799  if(b1->l->onoff == ON) 
4800    {
4801      b1->l->v += b2->l->v;
4802    }
4803
4804  (v1 == b1->left)?
4805    (Make_Edge_Dirs(b1,v1,v2,tree)):
4806    (Make_Edge_Dirs(b1,v2,v1,tree));
4807
4808  if(target)   (*target)   = b1;
4809  if(residual) (*residual) = b2;
4810
4811  if(tree->n_root)
4812    {
4813      if(tree->n_root->v[1] == a) tree->n_root->v[1] = NULL;
4814      if(tree->n_root->v[2] == a) tree->n_root->v[2] = NULL;
4815    }
4816
4817  /* if(tree->n_root) */
4818  /*   { */
4819  /*     tree->n_root->v[1]       = tree->e_root->left; */
4820  /*     tree->n_root->v[2]       = tree->e_root->rght; */
4821  /*     tree->n_root->b[1]->rght = tree->e_root->left; */
4822  /*     tree->n_root->b[2]->rght = tree->e_root->rght; */
4823  /*   } */
4824 
4825#ifdef DEBUG
4826  if(b1->left->tax == YES && b1->rght->tax == NO)
4827    {
4828      PhyML_Printf("\n== b1->left->num = %d",b1->left->num);
4829      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
4830      Warn_And_Exit("");
4831    }
4832#endif
4833
4834  if(tree->is_mixt_tree == YES) MIXT_Prune_Subtree(a,d,target,residual,tree);
4835
4836}
4837
4838//////////////////////////////////////////////////////////////
4839//////////////////////////////////////////////////////////////
4840
4841void Graft_Subtree(t_edge *target, t_node *link, t_edge *residual, t_tree *tree)
4842{
4843  t_node *v1, *v2;
4844  int i, dir_v1, dir_v2;
4845  phydbl *buff_p_lk;
4846  int *buff_scale;
4847  int *buff_p_pars, *buff_pars, *buff_p_lk_loc, *buff_patt_id; 
4848  short int *buff_p_lk_tip;
4849  unsigned int *buff_ui;
4850  t_edge *b_up;
4851
4852  dir_v1 = dir_v2 = -1;
4853  b_up = NULL;
4854  For(i,3)
4855    {
4856      if(!link->v[i])
4857        {
4858          if(dir_v1 < 0) dir_v1 = i;
4859          else           dir_v2 = i;
4860        }
4861      else b_up = link->b[i];
4862    }
4863
4864  if(target->left->num < target->rght->num)
4865    {
4866      v1                           = target->left;
4867      v2                           = target->rght;
4868
4869      buff_p_lk                    = residual->p_lk_rght;
4870      residual->p_lk_rght          = target->p_lk_rght;
4871      target->p_lk_rght            = buff_p_lk;
4872
4873      buff_p_lk_tip                = residual->p_lk_tip_r;
4874      residual->p_lk_tip_r         = target->p_lk_tip_r;
4875      target->p_lk_tip_r           = buff_p_lk_tip;
4876
4877      buff_scale                   = residual->sum_scale_rght;
4878      residual->sum_scale_rght     = target->sum_scale_rght;
4879      target->sum_scale_rght       = buff_scale;
4880
4881      buff_pars                    = residual->pars_r;
4882      residual->pars_r             = target->pars_r;
4883      target->pars_r               = buff_pars;
4884
4885      buff_ui                      = residual->ui_r;
4886      residual->ui_r               = target->ui_r;
4887      target->ui_r                 = buff_ui;
4888
4889      buff_p_pars                  = residual->p_pars_r;
4890      residual->p_pars_r           = target->p_pars_r;
4891      target->p_pars_r             = buff_p_pars;
4892
4893      buff_p_lk_loc                = residual->p_lk_loc_rght;
4894      residual->p_lk_loc_rght      = target->p_lk_loc_rght;
4895      target->p_lk_loc_rght        = buff_p_lk_loc;
4896
4897      buff_patt_id                 = residual->patt_id_rght;
4898      residual->patt_id_rght       = target->patt_id_rght;
4899      target->patt_id_rght         = buff_patt_id;
4900    }
4901  else
4902    {
4903      v1                           = target->rght;
4904      v2                           = target->left;
4905
4906      buff_p_lk                    = residual->p_lk_rght;
4907      residual->p_lk_rght          = target->p_lk_left;
4908      target->p_lk_left            = buff_p_lk;
4909
4910      buff_p_lk_tip                = residual->p_lk_tip_r;
4911      residual->p_lk_tip_r         = target->p_lk_tip_l;
4912      target->p_lk_tip_l           = buff_p_lk_tip;
4913
4914      buff_scale                   = residual->sum_scale_rght;
4915      residual->sum_scale_rght     = target->sum_scale_left;
4916      target->sum_scale_left       = buff_scale;
4917
4918      buff_scale                   = residual->sum_scale_rght_cat;
4919      residual->sum_scale_rght_cat = target->sum_scale_left_cat;
4920      target->sum_scale_left_cat   = buff_scale;
4921
4922      buff_pars                    = residual->pars_r;
4923      residual->pars_r             = target->pars_l;
4924      target->pars_l               = buff_pars;
4925
4926      buff_ui                      = residual->ui_r;
4927      residual->ui_r               = target->ui_l;
4928      target->ui_l                 = buff_ui;
4929
4930      buff_p_pars                  = residual->p_pars_r;
4931      residual->p_pars_r           = target->p_pars_l;
4932      target->p_pars_l             = buff_p_pars;
4933
4934      buff_p_lk_loc                = residual->p_lk_loc_rght;
4935      residual->p_lk_loc_rght      = target->p_lk_loc_left;
4936      target->p_lk_loc_left        = buff_p_lk_loc;
4937
4938      buff_patt_id                 = residual->patt_id_rght;
4939      residual->patt_id_rght       = target->patt_id_left;
4940      target->patt_id_left         = buff_patt_id;
4941    }
4942
4943
4944  For(i,3)
4945    if(v2->b[i] == target)
4946      {
4947        v2->v[i] = link;
4948        v2->b[i] = residual;
4949        break;
4950      }
4951
4952  link->v[dir_v2] = v2;
4953  link->b[dir_v2] = residual;
4954
4955  residual->left  = link;
4956  residual->rght  = v2;
4957
4958  (v1 == target->left)?(target->rght = link):(target->left = link);
4959
4960  link->v[dir_v1] = v1;
4961  link->b[dir_v1] = target;
4962
4963  For(i,3)
4964    if(v1->v[i] == v2)
4965      {
4966        v1->v[i] = link;
4967        break;
4968      }
4969 
4970  if(target->l->onoff == ON)   
4971    target->l->v /= 2.;
4972
4973  if(residual->l->onoff == ON) 
4974    residual->l->v = target->l->v;
4975 
4976  Make_Edge_Dirs(target,target->left,target->rght,tree);
4977  Make_Edge_Dirs(residual,residual->left,residual->rght,tree);
4978  Make_Edge_Dirs(b_up,b_up->left,b_up->rght,tree);
4979 
4980  /* if(tree->n_root) */
4981  /*   { */
4982  /*     tree->n_root->v[1]       = tree->e_root->left; */
4983  /*     tree->n_root->v[2]       = tree->e_root->rght; */
4984  /*     tree->n_root->b[1]->rght = tree->e_root->left; */
4985  /*     tree->n_root->b[2]->rght = tree->e_root->rght; */
4986  /*   } */
4987
4988
4989  if(tree->is_mixt_tree == YES) MIXT_Graft_Subtree(target,link,residual,tree);
4990
4991}
4992
4993//////////////////////////////////////////////////////////////
4994//////////////////////////////////////////////////////////////
4995
4996
4997void Reassign_Node_Nums(t_node *a, t_node *d, int *curr_ext_node, int *curr_int_node, t_tree *tree)
4998{
4999  t_node *buff;
5000  int i;
5001
5002  if(a->tax)
5003    {
5004      buff = tree->a_nodes[*curr_ext_node];
5005      tree->a_nodes[*curr_ext_node] = a;
5006      tree->a_nodes[a->num] = buff;
5007      buff->num = a->num;
5008      a->num = *curr_ext_node;
5009      (*curr_ext_node)++;
5010    }
5011
5012  if(d->tax)
5013    {
5014      buff = tree->a_nodes[*curr_ext_node];
5015      tree->a_nodes[*curr_ext_node] = d;
5016      tree->a_nodes[d->num] = buff;
5017      buff->num = d->num;
5018      d->num = *curr_ext_node;
5019      (*curr_ext_node)++;
5020      return;
5021    }
5022  else
5023    {
5024      buff = tree->a_nodes[*curr_int_node];
5025      tree->a_nodes[*curr_int_node] = d;
5026      tree->a_nodes[d->num] = buff;
5027      buff->num = d->num;
5028      d->num = *curr_int_node;
5029      (*curr_int_node)++;
5030    }
5031
5032  For(i,3)
5033    {
5034      if(d->v[i] != a)
5035        Reassign_Node_Nums(d,d->v[i],curr_ext_node,curr_int_node,tree);
5036    }
5037}
5038
5039//////////////////////////////////////////////////////////////
5040//////////////////////////////////////////////////////////////
5041
5042
5043void Reassign_Edge_Nums(t_node *a, t_node *d, int *curr_br, t_tree *tree)
5044{
5045  t_edge *buff;
5046  int i,j;
5047
5048  For(i,3)
5049    if(a->v[i] == d)
5050      {
5051        buff = tree->a_edges[*curr_br];
5052        For(j,2*N_MAX_OTU-3) if(tree->a_edges[j] == a->b[i]) break;
5053        if(j == 2*N_MAX_OTU-3)
5054          {
5055            PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
5056            Warn_And_Exit("");
5057          }
5058        tree->a_edges[*curr_br] = a->b[i];
5059        tree->a_edges[j] = buff;
5060        a->b[i]->num = *curr_br;
5061        (*curr_br)++;
5062        break;
5063      }
5064
5065  if(d->tax) return;
5066  else
5067    {
5068      For(i,3)
5069        if(d->v[i] != a)
5070          Reassign_Edge_Nums(d,d->v[i],curr_br,tree);
5071    }
5072}
5073
5074//////////////////////////////////////////////////////////////
5075//////////////////////////////////////////////////////////////
5076
5077
5078void Find_Mutual_Direction(t_node *n1, t_node *n2, short int *dir_n1_to_n2, short int *dir_n2_to_n1)
5079{
5080  int scores[3][3];
5081  int i,j,k,l;
5082
5083  if(n1 == n2) return;
5084
5085
5086  For(i,3)
5087    {
5088      For(j,3)
5089        {
5090          scores[i][j] = 0;
5091
5092          For(k,n1->bip_size[i])
5093            {
5094              For(l,n2->bip_size[j])
5095                {
5096                  if(n1->bip_node[i][k] == n2->bip_node[j][l])
5097                    {
5098                      scores[i][j]++;
5099                      break;
5100                    }
5101                }
5102            }
5103        }
5104    }
5105
5106  For(i,3)
5107    {
5108      For(j,3)
5109        {
5110          if(!scores[i][j]) 
5111            {
5112              *dir_n1_to_n2 = i; 
5113              *dir_n2_to_n1 = j; 
5114              return;
5115            } 
5116        }
5117    }
5118
5119  PhyML_Printf("\n. n1=%d n2=%d",n1->num,n2->num);
5120  PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
5121  Warn_And_Exit("");
5122
5123 
5124
5125/*   For(i,3) */
5126/*     { */
5127/*       n_zero_line = 0; */
5128/*       For(j,3) */
5129/*      { */
5130/*        if(!scores[i][j]) n_zero_line++; */
5131/*      } */
5132/*       if(n_zero_line != 2) {*dir_n1_to_n2 = i; break;} */
5133/*     } */
5134
5135
5136/*   For(i,3) */
5137/*     { */
5138/*       n_zero_col = 0; */
5139/*       For(j,3) */
5140/*      { */
5141/*        if(!scores[j][i]) n_zero_col++; */
5142/*      } */
5143/*       if(n_zero_col != 2) {*dir_n2_to_n1 = i; break;} */
5144/*     } */
5145
5146}
5147
5148//////////////////////////////////////////////////////////////
5149//////////////////////////////////////////////////////////////
5150
5151
5152void Update_Dir_To_Tips(t_node *a, t_node *d, t_tree *tree)
5153{
5154  int i,j,k;
5155  short int *inout;
5156  int d_a;
5157  int dim;
5158
5159  dim = 2*tree->n_otu-2;
5160
5161  inout = (short int *)mCalloc(tree->n_otu,sizeof(short int));
5162
5163  For(i,3)
5164    {
5165      if(a->v[i] == d)
5166        {
5167          For(j,tree->n_otu) inout[j] = 1;
5168          For(k,a->bip_size[i]) inout[a->bip_node[i][k]->num] = 0;
5169          For(j,tree->n_otu) if(inout[tree->a_nodes[j]->num]) tree->t_dir[a->num*dim+tree->a_nodes[j]->num] = i;
5170          break;
5171        }
5172    }
5173
5174
5175  if(!d->tax)
5176    {
5177
5178      d_a = -1;
5179
5180      For(i,3)
5181        {
5182          if(d->v[i] != a) Update_Dir_To_Tips(d,d->v[i],tree);
5183          else if(d->v[i] == a) d_a = i;
5184        }
5185
5186      For(j,tree->n_otu) inout[j] = 1;
5187      For(k,d->bip_size[d_a]) inout[d->bip_node[d_a][k]->num] = 0;
5188      For(j,tree->n_otu) if(inout[tree->a_nodes[j]->num]) tree->t_dir[d->num*dim+tree->a_nodes[j]->num] = d_a;
5189    }
5190
5191  Free(inout);
5192
5193}
5194
5195//////////////////////////////////////////////////////////////
5196//////////////////////////////////////////////////////////////
5197
5198
5199void Fill_Dir_Table(t_tree *tree)
5200{
5201  int i,j;
5202  int dim;
5203
5204  dim = 2*tree->n_otu-2;
5205  For(i,dim*dim) tree->t_dir[i] = 0;
5206  Free_Bip(tree);
5207  Alloc_Bip(tree);
5208  Get_Bip(tree->a_nodes[0],tree->a_nodes[0]->v[0],tree);
5209  Update_Dir_To_Tips(tree->a_nodes[0],tree->a_nodes[0]->v[0],tree);
5210
5211
5212  for(i=tree->n_otu;i<2*tree->n_otu-2;i++)
5213    for(j=i;j<2*tree->n_otu-2;j++)
5214      {
5215        Find_Mutual_Direction(tree->a_nodes[i],tree->a_nodes[j],
5216                              &(tree->t_dir[i*dim+j]),
5217                              &(tree->t_dir[j*dim+i]));
5218      }
5219}
5220
5221//////////////////////////////////////////////////////////////
5222//////////////////////////////////////////////////////////////
5223
5224//////////////////////////////////////////////////////////////
5225//////////////////////////////////////////////////////////////
5226
5227//////////////////////////////////////////////////////////////
5228//////////////////////////////////////////////////////////////
5229
5230//////////////////////////////////////////////////////////////
5231//////////////////////////////////////////////////////////////
5232
5233
5234int Get_Subtree_Size(t_node *a, t_node *d)
5235{
5236  int size,i;
5237
5238  if(d->tax) return 1;
5239  else
5240    {
5241      size = 0;
5242      For(i,3)
5243        if(d->v[i] != a)
5244          size += Get_Subtree_Size(d,d->v[i]);
5245    }
5246  return size;
5247}
5248
5249//////////////////////////////////////////////////////////////
5250//////////////////////////////////////////////////////////////
5251
5252void Fast_Br_Len(t_edge *b, t_tree *tree, int approx)
5253{
5254  /* phydbl sum; */
5255  /* phydbl *prob, *F; */
5256  /* int i, j, k, site; */
5257  /* phydbl *v_rght; */
5258  /* int dim1,dim2,dim3; */
5259  /* int n_iter; */
5260  /* phydbl scale_rght; */
5261
5262  if(tree->is_mixt_tree) 
5263    {
5264      if(approx == NO)
5265        MIXT_Br_Len_Brent(0.001,100.,b,tree);
5266      else
5267        {
5268          tree->mod->s_opt->brent_it_max = 10;
5269          MIXT_Br_Len_Brent(0.0001,1000.,b,tree);
5270          tree->mod->s_opt->brent_it_max = BRENT_IT_MAX;
5271        }
5272      return;
5273    }
5274
5275  /* n_iter = 0; */
5276  /* dim1   = tree->mod->ns * tree->mod->ras->n_catg; */
5277  /* dim2   = tree->mod->ns ; */
5278  /* dim3   = tree->mod->ns * tree->mod->ns; */
5279
5280  /* F    = tree->triplet_struct->F_bc; */
5281  /* prob = tree->triplet_struct->F_cd; */
5282
5283  /* Update_PMat_At_Given_Edge(b,tree); */
5284 
5285  /* For(i,dim1*dim2) F[i] = .0; */
5286 
5287  /* v_rght = (phydbl *)mCalloc(tree->mod->ns,sizeof(phydbl)); */
5288
5289  /* For(site,tree->n_pattern) */
5290  /*   { */
5291  /*     /\* Joint probabilities of the states at the two ends of the t_edge *\/ */
5292
5293  /*     For(k,tree->mod->ras->n_catg) */
5294  /*       { */
5295  /*         if(b->rght->tax == YES) */
5296  /*           For(i,tree->mod->ns) v_rght[i] = (phydbl)(b->p_lk_tip_r[site*dim2+i]); */
5297  /*         else */
5298  /*           For(i,tree->mod->ns) v_rght[i] = (phydbl)(b->p_lk_rght[site*dim1+k*dim2+i]); */
5299
5300  /*         scale_rght = (b->rght->tax)?(0.0):(b->sum_scale_rght[k*tree->n_pattern+site]); */
5301
5302  /*         Joint_Proba_States_Left_Right(b->Pij_rr + k*dim3, */
5303  /*                                    b->p_lk_left + site*dim1+k*dim2, */
5304  /*                                    v_rght, */
5305  /*                                    tree->mod->e_frq->pi, */
5306  /*                                    b->sum_scale_left[k*tree->n_pattern+site], */
5307  /*                                    scale_rght, */
5308  /*                                    prob + dim3*k, */
5309  /*                                    tree->mod->ns,site,tree); */
5310         
5311  /*         /\* Scaling *\/ */
5312  /*         sum = .0; */
5313  /*         For(i,tree->mod->ns) For(j,tree->mod->ns) sum += prob[dim3*k+dim2*i+j]; */
5314  /*         For(i,tree->mod->ns) For(j,tree->mod->ns) prob[dim3*k+dim2*i+j] /= sum; */
5315  /*         For(i,tree->mod->ns) For(j,tree->mod->ns) prob[dim3*k+dim2*i+j] *= tree->mod->ras->gamma_r_proba->v[k]; */
5316  /*       } */
5317     
5318  /*     /\* Expected number of each pair of states *\/ */
5319  /*     For(i,tree->mod->ns) For(j,tree->mod->ns) For(k,tree->mod->ras->n_catg) */
5320  /*       F[dim3*k+dim2*i+j] += tree->data->wght[site] * prob[dim3*k+dim2*i+j]; */
5321 
5322  /* } */
5323 
5324  /* Free(v_rght); */
5325 
5326  /* Opt_Dist_F(&(b->l->v),F,tree->mod); */
5327  /* n_iter++; */
5328
5329  if(approx == NO)
5330    Br_Len_Brent(0.001,100.,b,tree);
5331  else
5332    {
5333      tree->mod->s_opt->brent_it_max = 10;
5334      Br_Len_Brent(0.001,1000.,b,tree);
5335      tree->mod->s_opt->brent_it_max = BRENT_IT_MAX;
5336    }
5337}
5338
5339//////////////////////////////////////////////////////////////
5340//////////////////////////////////////////////////////////////
5341/*!
5342  Calculate the joint probability of states (nt or aa) at the
5343  two extremities of a given edge given the matrix of transition
5344  probabilities, the vector of conditional likelihoods on each
5345  side of the branch and the vector of equilibrium frequencies.
5346*/
5347void Joint_Proba_States_Left_Right(phydbl *Pij, phydbl *p_lk_left, phydbl *p_lk_rght, 
5348                                   vect_dbl *pi, int scale_left, int scale_rght, 
5349                                   phydbl *F, int n, int site, t_tree *tree)
5350{
5351  int i,j;
5352  phydbl sum = 0.0;
5353
5354  For(i,n) F[i] = .0;
5355 
5356  For(i,n)
5357    {
5358      For(j,n)
5359        {         
5360          F[i*n+j] =
5361            pi->v[i] *
5362            Pij[i*n+j] *
5363            p_lk_left[i] *
5364            p_lk_rght[j] *
5365            POW(2.,-(scale_left + scale_rght));
5366         
5367          sum += F[i*n+j];
5368        }
5369    }
5370 
5371  For(i,n*n) 
5372    {
5373      F[i] /= sum;
5374      if(isnan(F[i]) || isinf(F[i]))
5375        {
5376          For(i,n) For(j,n)
5377            PhyML_Printf("\n== %15G %15G %15G %15G %15G",
5378                         pi->v[i] ,
5379                         Pij[i*n+j] ,
5380                         p_lk_left[i] ,
5381                         p_lk_rght[j] ,
5382                         POW(2.,-(scale_left + scale_rght)));
5383         
5384          PhyML_Printf("\n== sum = %G",sum);
5385          Print_Site(tree->data,site,tree->n_otu,"\n",1,stderr);
5386          PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
5387          Exit("\n");
5388        }
5389    }
5390
5391}
5392
5393//////////////////////////////////////////////////////////////
5394//////////////////////////////////////////////////////////////
5395
5396phydbl Triple_Dist(t_node *a, t_tree *tree, int approx)
5397{
5398  if(a->tax) return UNLIKELY;
5399  else
5400    {
5401
5402      Update_PMat_At_Given_Edge(a->b[1],tree);
5403      Update_PMat_At_Given_Edge(a->b[2],tree);
5404
5405      Update_P_Lk(tree,a->b[0],a);
5406      Fast_Br_Len(a->b[0],tree,approx);
5407
5408      Update_P_Lk(tree,a->b[1],a);
5409      Fast_Br_Len(a->b[1],tree,approx);
5410
5411      Update_P_Lk(tree,a->b[2],a);
5412      Fast_Br_Len(a->b[2],tree,approx);
5413
5414      Update_P_Lk(tree,a->b[1],a);
5415      Update_P_Lk(tree,a->b[0],a);
5416    }
5417
5418  return tree->c_lnL;
5419
5420}
5421
5422
5423//////////////////////////////////////////////////////////////
5424//////////////////////////////////////////////////////////////
5425
5426
5427void Make_Symmetric(phydbl **F, int size)
5428{
5429  int i,j;
5430
5431  For(i,size)
5432    {
5433      for(j=i+1;j<size;j++)
5434        {
5435          (*F)[size*i+j] = ((*F)[size*i+j] + (*F)[size*j+i])/2.;
5436          (*F)[size*j+i] = (*F)[size*i+j];
5437        }
5438    }
5439}
5440
5441//////////////////////////////////////////////////////////////
5442//////////////////////////////////////////////////////////////
5443
5444
5445void Round_Down_Freq_Patt(phydbl **F, t_tree *tree)
5446{
5447  int i,j;
5448
5449  For(i,tree->mod->ns)
5450    {
5451      For(j,tree->mod->ns)
5452        {
5453          (*F)[tree->mod->ns*i+j] = RINT((*F)[tree->mod->ns*i+j]);
5454        }
5455    }
5456}
5457
5458//////////////////////////////////////////////////////////////
5459//////////////////////////////////////////////////////////////
5460
5461
5462phydbl Get_Sum_Of_Cells(phydbl *F, t_tree *tree)
5463{
5464  int i,j;
5465  phydbl sum = .0;
5466
5467  For(i,tree->mod->ns)
5468    For(j,tree->mod->ns)
5469    sum += F[tree->mod->ns*i+j];
5470
5471  return sum;
5472}
5473
5474
5475//////////////////////////////////////////////////////////////
5476//////////////////////////////////////////////////////////////
5477
5478
5479void Divide_Cells(phydbl **F, phydbl div, t_tree *tree)
5480{
5481  int i,j;
5482
5483  For(i,tree->mod->ns)
5484    For(j,tree->mod->ns)
5485    (*F)[tree->mod->ns*i+j] /= div;
5486}
5487
5488//////////////////////////////////////////////////////////////
5489//////////////////////////////////////////////////////////////
5490
5491
5492void Divide_Mat_By_Vect(phydbl **F, phydbl *vect, int size)
5493{
5494  int i,j;
5495  For(i,size)
5496    For(j,size)
5497    (*F)[size*i+j] = (*F)[size*i+j] / vect[j];
5498}
5499
5500//////////////////////////////////////////////////////////////
5501//////////////////////////////////////////////////////////////
5502
5503
5504void Multiply_Mat_By_Vect(phydbl **F, phydbl *vect, int size)
5505{
5506  int i,j;
5507  For(i,size)
5508    For(j,size)
5509    (*F)[size*i+j] = (*F)[size*i+j] * vect[j];
5510}
5511
5512//////////////////////////////////////////////////////////////
5513//////////////////////////////////////////////////////////////
5514
5515
5516void Found_In_Subtree(t_node *a, t_node *d, t_node *target, int *match, t_tree *tree)
5517{
5518  if(d->tax) return;
5519  else
5520    {
5521      int i;
5522      if(d == target) *match =  1;
5523      For(i,3)
5524        {
5525          if(d->v[i] != a)
5526            Found_In_Subtree(d,d->v[i],target,match,tree);
5527        }
5528    }
5529}
5530
5531//////////////////////////////////////////////////////////////
5532//////////////////////////////////////////////////////////////
5533
5534
5535void Get_List_Of_Target_Edges(t_node *a, t_node *d, t_edge **list, int *list_size, t_tree *tree)
5536{
5537  int i;
5538
5539  For(i,3)
5540    {
5541      if(a->v[i] && a->v[i] == d)
5542        {
5543          list[*list_size] = a->b[i];
5544          (*list_size)++;
5545        }
5546    }
5547
5548  if(d->tax) return;
5549  else
5550    {
5551      For(i,3)
5552        {
5553          if(d->v[i] != a)
5554            Get_List_Of_Target_Edges(d,d->v[i],list,list_size,tree);
5555        }
5556    }
5557}
5558
5559//////////////////////////////////////////////////////////////
5560//////////////////////////////////////////////////////////////
5561
5562
5563void Fix_All(t_tree *tree)
5564{
5565  int i;
5566
5567  for(i=tree->n_otu;i<2*tree->n_otu-2;i++)
5568    {
5569      tree->a_nodes[i]->b[0]->l_old->v = tree->a_nodes[i]->b[0]->l->v;
5570      tree->a_nodes[i]->b[1]->l_old->v = tree->a_nodes[i]->b[1]->l->v;
5571      tree->a_nodes[i]->b[2]->l_old->v = tree->a_nodes[i]->b[2]->l->v;
5572    }
5573}
5574
5575//////////////////////////////////////////////////////////////
5576//////////////////////////////////////////////////////////////
5577
5578
5579void Record_Br_Len(t_tree *mixt_tree)
5580{
5581  int i;
5582  t_tree *tree;
5583
5584  if(mixt_tree->br_len_recorded == YES)
5585    {
5586      PhyML_Printf("\n== Overwriting recorded edge lengths.\n");
5587      PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);
5588      Exit("\n");   
5589    }
5590
5591  tree = mixt_tree;
5592 
5593  do
5594    {
5595      For(i,2*tree->n_otu-1) tree->a_edges[i]->l_old->v     = tree->a_edges[i]->l->v;
5596      For(i,2*tree->n_otu-1) tree->a_edges[i]->l_var_old->v = tree->a_edges[i]->l_var->v;
5597      tree = tree->next;
5598    }
5599  while(tree);
5600}
5601
5602//////////////////////////////////////////////////////////////
5603//////////////////////////////////////////////////////////////
5604
5605
5606void Restore_Br_Len(t_tree *mixt_tree)
5607{
5608  int i;
5609  t_tree *tree;
5610
5611  mixt_tree->br_len_recorded = NO;
5612 
5613  tree = mixt_tree;
5614
5615  do
5616    {
5617      For(i,2*tree->n_otu-1) tree->a_edges[i]->l->v     = tree->a_edges[i]->l_old->v;
5618      For(i,2*tree->n_otu-1) tree->a_edges[i]->l_var->v = tree->a_edges[i]->l_var_old->v;
5619      tree = tree->next;
5620    }
5621  while(tree);
5622}
5623
5624//////////////////////////////////////////////////////////////
5625//////////////////////////////////////////////////////////////
5626
5627
5628void Get_Dist_Btw_Edges(t_node *a, t_node *d, t_tree *tree)
5629{
5630  int i;
5631  t_edge *b_fcus;
5632
5633  b_fcus = NULL;
5634  For(i,3) if(a->v[i] == d) {b_fcus = a->b[i]; break;}
5635
5636  if(d->tax) return;
5637  else
5638    {
5639      For(i,3)
5640        if(d->v[i] != a)
5641          {
5642            d->b[i]->topo_dist_btw_edges = b_fcus->topo_dist_btw_edges + 1;
5643            d->b[i]->dist_btw_edges      = b_fcus->dist_btw_edges + d->b[i]->l->v / 2.;
5644            Get_Dist_Btw_Edges(d,d->v[i],tree);
5645          }
5646    }
5647
5648
5649}
5650
5651//////////////////////////////////////////////////////////////
5652//////////////////////////////////////////////////////////////
5653
5654
5655void Detect_Polytomies(t_edge *b, phydbl l_thresh, t_tree *tree)
5656{
5657  if((b->l->v < l_thresh) && (!b->left->tax) && (!b->rght->tax))
5658    {
5659      b->l->v               = 0.0;
5660      b->has_zero_br_len = YES;
5661    }
5662  else b->has_zero_br_len = NO;
5663}
5664
5665//////////////////////////////////////////////////////////////
5666//////////////////////////////////////////////////////////////
5667
5668
5669void Get_List_Of_Nodes_In_Polytomy(t_node *a, t_node *d, t_node ***list, int *size_list)
5670{
5671  if(d->tax) return;
5672  else
5673    {
5674      int i;
5675
5676      For(i,3)
5677        {
5678          if(d->v[i] != a)
5679            {
5680              if(!d->b[i]->has_zero_br_len)
5681                {
5682                  (*list)[*size_list] = d->v[i];
5683                  (*size_list)++;
5684                }
5685
5686              if(d->b[i]->has_zero_br_len)
5687                Get_List_Of_Nodes_In_Polytomy(d,d->v[i],list,size_list);
5688            }
5689        }
5690    }
5691
5692}
5693
5694
5695//////////////////////////////////////////////////////////////
5696//////////////////////////////////////////////////////////////
5697
5698void Path_Length(t_node *dep, t_node *arr, phydbl *len, t_tree *tree)
5699{
5700  if(dep==arr) return;
5701  else 
5702    {
5703      t_edge *next;
5704
5705      next = dep->b[tree->t_dir[dep->num*(2*tree->n_otu-2)+arr->num]];
5706
5707      if(next == tree->e_root)
5708        {
5709          (*len) += (tree->n_root->l[1] + tree->n_root->l[2]);
5710        }
5711      else
5712        {
5713          (*len) += next->l->v;
5714        }
5715      Path_Length(dep->v[tree->t_dir[dep->num*(2*tree->n_otu-2)+arr->num]],arr,len,tree);
5716      return;
5717    }
5718}
5719
5720
5721//////////////////////////////////////////////////////////////
5722//////////////////////////////////////////////////////////////
5723
5724
5725void Check_Path(t_node *a, t_node *d, t_node *target, t_tree *tree)
5726{
5727  PhyML_Printf("path---------\n");
5728  if(d==target) return;
5729  else Check_Path(d,d->v[tree->t_dir[d->num*(2*tree->n_otu-2)+target->num]],target,tree);
5730}
5731
5732
5733//////////////////////////////////////////////////////////////
5734//////////////////////////////////////////////////////////////
5735
5736
5737void Connect_Two_Nodes(t_node *a, t_node *d)
5738{
5739  a->v[0] = d;
5740  d->v[0] = a;
5741}
5742
5743//////////////////////////////////////////////////////////////
5744//////////////////////////////////////////////////////////////
5745
5746
5747void Get_List_Of_Adjacent_Targets(t_node *a, t_node *d, t_node ***node_list, t_edge ***edge_list, int *list_size)
5748{
5749  int i;
5750
5751  For(i,3)
5752    if(a->v[i] == d)
5753      {
5754        (*node_list)[*list_size] = a;
5755        (*edge_list)[*list_size] = a->b[i];
5756        (*list_size)++;
5757      }
5758  if(d->tax) return;
5759  else
5760    For(i,3)
5761      if(d->v[i] != a) Get_List_Of_Adjacent_Targets(d,d->v[i],node_list,edge_list,list_size);
5762}
5763
5764//////////////////////////////////////////////////////////////
5765//////////////////////////////////////////////////////////////
5766
5767
5768void Sort_List_Of_Adjacent_Targets(t_edge ***list, int list_size)
5769{
5770  t_edge *buff_edge;
5771  int i,j;
5772
5773  buff_edge = NULL;
5774
5775  For(i,list_size-1)
5776    {
5777      for(j=i+1;j<list_size;j++)
5778        if((*list)[j]->topo_dist_btw_edges < (*list)[i]->topo_dist_btw_edges)
5779          {
5780            buff_edge = (*list)[j];
5781            (*list)[j] = (*list)[i];
5782            (*list)[i] = buff_edge;
5783          }
5784    }
5785}
5786
5787//////////////////////////////////////////////////////////////
5788//////////////////////////////////////////////////////////////
5789
5790t_node *Common_Nodes_Btw_Two_Edges(t_edge *a, t_edge *b)
5791{
5792  if(a->left == b->left)      return b->left;
5793  else if(a->left == b->rght) return b->rght;
5794  else if(a->rght == b->left) return b->left;
5795  else if(a->rght == b->rght) return b->rght;
5796
5797  PhyML_Printf("\n. First t_edge = %d (%d %d); Second t_edge = %d (%d %d)\n",
5798         a->num,a->left->num,a->rght->num,
5799         b->num,b->left->num,b->rght->num);
5800  PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
5801  Warn_And_Exit("");
5802
5803  return NULL;
5804}
5805
5806//////////////////////////////////////////////////////////////
5807//////////////////////////////////////////////////////////////
5808
5809
5810int KH_Test(phydbl *site_lk_M1, phydbl *site_lk_M2, t_tree *tree)
5811{
5812  phydbl *delta,mean,sd,obs_stat,threshold;
5813  int i;
5814
5815 
5816  delta = (phydbl *)mCalloc(tree->data->init_len,sizeof(phydbl));
5817
5818  threshold = .0;
5819  mean = .0;
5820  obs_stat = .0;
5821  For(i,tree->n_pattern)
5822    {
5823      delta[i] = site_lk_M1[i] - site_lk_M2[i];
5824      mean += ((int)tree->data->wght[i])*delta[i];
5825    }
5826
5827  obs_stat = mean;
5828
5829  mean /= tree->data->init_len;
5830
5831  For(i,tree->data->init_len) delta[i] -= mean;
5832
5833  sd = .0;
5834  For(i,tree->data->init_len) sd += POW(delta[i],2);
5835  sd /= (phydbl)(tree->data->init_len-1.);
5836
5837/*   threshold = tree->dnorm_thresh*SQRT(sd*tree->data->init_len); */
5838
5839
5840/*   PhyML_Printf("\nObs stat = %f Threshold = %f\n",obs_stat,threshold); */
5841  Free(delta);
5842
5843  if(obs_stat > threshold) return 1;
5844  else                     return 0;
5845}
5846
5847//////////////////////////////////////////////////////////////
5848//////////////////////////////////////////////////////////////
5849
5850
5851//////////////////////////////////////////////////////////////
5852//////////////////////////////////////////////////////////////
5853
5854
5855void Random_Tree(t_tree *tree)
5856{
5857  int *is_available,*list_of_nodes;
5858  int i,node_num,step,n_available;
5859  phydbl min_edge_len;
5860
5861  min_edge_len = 1.E-3;
5862
5863  if(tree->mod->s_opt && tree->mod->s_opt->print == YES) 
5864    PhyML_Printf("\n\n. Randomising the tree...\n");
5865
5866  is_available  = (int *)mCalloc(2*tree->n_otu-2,sizeof(int));
5867  list_of_nodes = (int *)mCalloc(tree->n_otu,    sizeof(int));
5868
5869  For(i,tree->n_otu) is_available[i]  = 1;
5870  For(i,tree->n_otu) list_of_nodes[i] = i;
5871
5872  step = 0;
5873  do
5874    {
5875/*       node_num = (int)RINT(rand()/(phydbl)(RAND_MAX+1.0)*(tree->n_otu-1-step)); */
5876      node_num = Rand_Int(0,tree->n_otu-1-step);
5877      node_num = list_of_nodes[node_num];
5878      is_available[node_num] = 0;
5879      For(i,tree->n_otu) list_of_nodes[i] = -1;
5880      n_available = 0;
5881      For(i,2*tree->n_otu-2) if(is_available[i]) {list_of_nodes[n_available++] = i;}
5882
5883      tree->a_nodes[node_num]->v[0] = tree->a_nodes[tree->n_otu+step];
5884      tree->a_nodes[tree->n_otu+step]->v[1] = tree->a_nodes[node_num];
5885
5886/*       node_num = (int)RINT(rand()/(phydbl)(RAND_MAX+1.0)*(tree->n_otu-2-step)); */
5887      node_num = Rand_Int(0,tree->n_otu-2-step);
5888      node_num = list_of_nodes[node_num];
5889      is_available[node_num] = 0;
5890      For(i,tree->n_otu) list_of_nodes[i] = -1;
5891      n_available = 0;
5892      For(i,2*tree->n_otu-2) if(is_available[i]) {list_of_nodes[n_available++] = i;}
5893
5894      tree->a_nodes[node_num]->v[0] = tree->a_nodes[tree->n_otu+step];
5895      tree->a_nodes[tree->n_otu+step]->v[2] = tree->a_nodes[node_num];
5896
5897      is_available[tree->n_otu+step] = 1;
5898      For(i,tree->n_otu) list_of_nodes[i] = -1;
5899      n_available = 0;
5900      For(i,2*tree->n_otu-2) if(is_available[i]) list_of_nodes[n_available++] = i;
5901
5902      step++;
5903    }while(step < tree->n_otu-2);
5904
5905  tree->a_nodes[list_of_nodes[0]]->v[0] = tree->a_nodes[list_of_nodes[1]];
5906  tree->a_nodes[list_of_nodes[1]]->v[0] = tree->a_nodes[list_of_nodes[0]];
5907
5908  tree->num_curr_branch_available = 0;
5909  Connect_Edges_To_Nodes_Recur(tree->a_nodes[0],tree->a_nodes[0]->v[0],tree);
5910 
5911  For(i,2*tree->n_otu-3) if(tree->a_edges[i]->l->v < min_edge_len) tree->a_edges[i]->l->v = min_edge_len;
5912
5913  Fill_Dir_Table(tree);
5914  Update_Dirs(tree);
5915 
5916  Free(is_available);
5917  Free(list_of_nodes);
5918}
5919
5920//////////////////////////////////////////////////////////////
5921//////////////////////////////////////////////////////////////
5922// Make sure internal edges have likelihood vectors on both
5923// sides and external edges have one likelihood vector on the
5924// lefthand side only
5925
5926void Reorganize_Edges_Given_Lk_Struct(t_tree *tree)
5927{
5928  int j,i;
5929 
5930  For(i,2*tree->n_otu-3)
5931    {
5932      if(tree->a_edges[i]->p_lk_left && tree->a_edges[i]->left->tax == YES)
5933        {
5934          For(j,2*tree->n_otu-3)
5935            {
5936              if(!tree->a_edges[j]->p_lk_left && tree->a_edges[j]->left->tax == NO)
5937                {
5938                  Swap_Nodes_On_Edges(tree->a_edges[i],tree->a_edges[j],NO,tree);                 
5939                  break;
5940                }
5941              if(!tree->a_edges[j]->p_lk_rght && tree->a_edges[j]->rght->tax == NO)
5942                {
5943                  Swap_Nodes_On_Edges(tree->a_edges[i],tree->a_edges[j],YES,tree);
5944                  break;
5945                }
5946            }
5947        }
5948     
5949      if(tree->a_edges[i]->p_lk_rght && tree->a_edges[i]->rght->tax == YES)
5950        {
5951          For(j,2*tree->n_otu-3)
5952            {
5953              if(!tree->a_edges[j]->p_lk_left && tree->a_edges[j]->left->tax == NO)
5954                {
5955                  Swap_Nodes_On_Edges(tree->a_edges[i],tree->a_edges[j],YES,tree);
5956                  break;
5957                }
5958              if(!tree->a_edges[j]->p_lk_rght && tree->a_edges[j]->rght->tax == NO)
5959                {
5960                  Swap_Nodes_On_Edges(tree->a_edges[i],tree->a_edges[j],NO,tree);
5961                  break;
5962                }
5963            }
5964        }
5965    }
5966}
5967
5968//////////////////////////////////////////////////////////////
5969//////////////////////////////////////////////////////////////
5970
5971void Random_NNI(int n_moves, t_tree *tree)
5972{
5973  int i,j;
5974  t_edge *b;
5975  t_node *n1,*n2,*n_target;
5976
5977  n1 = n2 = NULL;
5978  b = NULL;
5979  For(i,n_moves)
5980    {
5981      n_target  = tree->a_nodes[tree->n_otu + (int)((phydbl)rand()/RAND_MAX * (2*tree->n_otu-3-tree->n_otu))];
5982      For(j,3) if(!n_target->v[j]->tax) {b = n_target->b[j]; break;}
5983
5984
5985      For(j,3) if(b->left->v[j] != b->rght) {n1 = b->left->v[j]; break;}
5986      For(j,3) if(b->rght->v[j] != b->left) {n2 = b->rght->v[j]; break;}
5987
5988
5989      Swap(n1,b->left,b->rght,n2,tree);
5990    }
5991}
5992
5993//////////////////////////////////////////////////////////////
5994//////////////////////////////////////////////////////////////
5995
5996
5997//////////////////////////////////////////////////////////////
5998//////////////////////////////////////////////////////////////
5999
6000
6001void Fill_Missing_Dist(matrix *mat)
6002{
6003  int i,j;
6004  For(i,mat->n_otu)
6005    {
6006      for(j=i+1;j<mat->n_otu;j++)
6007        {
6008          if(i != j)
6009            {
6010              if(mat->dist[i][j] < .0) 
6011                {
6012                  Fill_Missing_Dist_XY(i,j,mat);
6013                  mat->dist[j][i] = mat->dist[i][j];
6014                }
6015            }
6016        }
6017    }
6018}
6019
6020//////////////////////////////////////////////////////////////
6021//////////////////////////////////////////////////////////////
6022
6023
6024void Fill_Missing_Dist_XY(int x, int y, matrix *mat)
6025{
6026
6027  int i,j;
6028  phydbl *local_mins,**S1S2;
6029  int cpt;
6030  int pos_best_estimate;
6031  phydbl min_crit, curr_crit;
6032
6033  local_mins = (phydbl *)mCalloc(mat->n_otu*mat->n_otu,sizeof(phydbl ));
6034  S1S2       = (phydbl **)mCalloc(mat->n_otu*mat->n_otu,sizeof(phydbl *));
6035  For(i,mat->n_otu*mat->n_otu) S1S2[i] = (phydbl *)mCalloc(2,sizeof(phydbl));
6036
6037  cpt = 0;
6038  For(i,mat->n_otu)
6039    {
6040      if((mat->dist[i][x] > .0) && (mat->dist[i][y] > .0))
6041        {
6042          For(j,mat->n_otu)
6043            {
6044              if((mat->dist[j][x] > .0) && (mat->dist[j][y] > .0))
6045                {
6046                  if((i != j) && (i != x) && (i != y) && (j != x) && (j != y))
6047                    {
6048                      S1S2[cpt][0] = MIN(mat->dist[i][x] + mat->dist[j][y] - mat->dist[i][j] , mat->dist[i][y] + mat->dist[j][x] - mat->dist[i][j]);
6049                      S1S2[cpt][1] = MAX(mat->dist[i][x] + mat->dist[j][y] - mat->dist[i][j] , mat->dist[i][y] + mat->dist[j][x] - mat->dist[i][j]);
6050                      cpt++;
6051                    }
6052                }
6053            }
6054        }
6055    }
6056
6057  Qksort_Matrix(S1S2,0,0,cpt-1);
6058
6059  local_mins[0] = S1S2[0][1];
6060  for(i=1;i<cpt;i++) local_mins[i] = (i*local_mins[i-1] + S1S2[i][1])/(phydbl)(i+1);
6061 
6062  pos_best_estimate = 0;
6063  min_crit = curr_crit = BIG;
6064       
6065  For(i,cpt-1)
6066    {
6067      if((local_mins[i] < S1S2[i+1][0]) && (local_mins[i] > S1S2[i][0]))
6068        {
6069          curr_crit = Least_Square_Missing_Dist_XY(x,y,local_mins[i],mat);
6070          if(curr_crit < min_crit)
6071            {
6072              min_crit = curr_crit;
6073              pos_best_estimate = i;
6074            }
6075        }
6076    }
6077
6078  mat->dist[x][y] = local_mins[pos_best_estimate];
6079  mat->dist[y][x] = mat->dist[x][y];
6080
6081  For(i,mat->n_otu*mat->n_otu) Free(S1S2[i]);
6082  Free(S1S2);
6083  Free(local_mins);
6084}
6085
6086//////////////////////////////////////////////////////////////
6087//////////////////////////////////////////////////////////////
6088
6089
6090phydbl Least_Square_Missing_Dist_XY(int x, int y, phydbl dxy, matrix *mat)
6091{
6092  int i,j;
6093  phydbl fit;
6094
6095  fit = .0;
6096  For(i,mat->n_otu)
6097    {
6098      if((mat->dist[i][x] > .0) && (mat->dist[i][y] > .0))
6099        {
6100          For(j,mat->n_otu)
6101            {
6102              if((mat->dist[j][x] > .0) && (mat->dist[j][y] > .0))
6103                {
6104                  if((i != j) && (i != x) && (i != y) && (j != x) && (j != y))
6105                    {
6106                      if(dxy < MIN(mat->dist[i][x] + mat->dist[j][y] - mat->dist[i][j] , mat->dist[i][y] + mat->dist[j][x] - mat->dist[i][j]))
6107                        {
6108                          fit += POW((mat->dist[i][x] + mat->dist[j][y]) - (mat->dist[i][y] + mat->dist[j][x]),2);
6109                        }
6110                      else if((mat->dist[i][x] + mat->dist[j][y]) < (mat->dist[i][y] + mat->dist[j][x]))
6111                        {
6112                          fit += POW(dxy - (mat->dist[i][y] + mat->dist[j][x] - mat->dist[i][j]),2);
6113                        }
6114                      else
6115                        {
6116                          fit += POW(dxy - (mat->dist[i][x] + mat->dist[j][y] - mat->dist[i][j]),2);
6117                        }
6118                    }
6119                }
6120            }
6121        }
6122    }
6123  return fit;
6124}
6125
6126//////////////////////////////////////////////////////////////
6127//////////////////////////////////////////////////////////////
6128
6129void Check_Memory_Amount(t_tree *tree)
6130{
6131  /* Rough estimate of the amount of memory that has to be used */
6132
6133  long int nbytes;
6134  int n_otu;
6135  t_mod *mod;
6136
6137  mod    = tree->mod;
6138  n_otu  = tree->io->n_otu;
6139  nbytes = 0;
6140
6141  /* Partial Pars */
6142  nbytes += (2*n_otu-3) * 2 * tree->data->crunch_len * sizeof(int);
6143  nbytes += (2*n_otu-3) * 2 * tree->data->crunch_len * sizeof(unsigned int);
6144  nbytes += (2*n_otu-3) * 2 * tree->data->crunch_len * mod->ns * sizeof(int);
6145
6146  /* Pmat */
6147  nbytes += (2*n_otu-3) * mod->ras->n_catg * mod->ns * mod->ns * sizeof(phydbl);
6148 
6149
6150  /* Partial Lk */
6151  nbytes += ((2*n_otu-3) * 2 - tree->n_otu) * tree->data->crunch_len * mod->ras->n_catg * mod->ns * sizeof(phydbl);
6152
6153
6154  /* Scaling factors */
6155  nbytes += ((2*n_otu-3) * 2 - tree->n_otu) * tree->data->crunch_len * sizeof(int);
6156 
6157     
6158   
6159  if(((phydbl)nbytes/(1.E+06)) > 256.)
6160/*   if(((phydbl)nbytes/(1.E+06)) > 0.) */
6161    {
6162      PhyML_Printf("\n\n. WARNING: this analysis requires at least %.0f MB of memory space.\n",(phydbl)nbytes/(1.E+06));
6163#ifndef BATCH
6164
6165      char answer;
6166      if((!tree->io->quiet) && (tree->io->mem_question == YES)) 
6167        {
6168          PhyML_Printf("\n. Do you really want to proceed? [Y/n] ");
6169          if(scanf("%c", &answer))
6170            {
6171              if(answer == '\n') answer = 'Y';
6172              else if(answer == 'n' || answer == 'N') Warn_And_Exit("\n");
6173              else getchar();
6174            }
6175          else
6176            {
6177              Warn_And_Exit("\n\n");
6178            }
6179        }
6180#endif
6181    }
6182  else if(((phydbl)nbytes/(1.E+06)) > 100.)
6183    {
6184      if(!tree->io->quiet) PhyML_Printf("\n\n. WARNING: this analysis will use at least %.0f Mo of memory space...\n",(phydbl)nbytes/(1.E+06));
6185    }
6186  else if(((phydbl)nbytes/(1.E+06)) > 1.)
6187    {
6188      if(!tree->io->quiet) PhyML_Printf("\n\n. This analysis requires at least %.0f Mo of memory space.\n",(phydbl)nbytes/(1.E+06));
6189    }
6190}
6191
6192//////////////////////////////////////////////////////////////
6193//////////////////////////////////////////////////////////////
6194
6195
6196int Get_State_From_P_Lk(phydbl *p_lk, int pos, t_tree *tree)
6197{
6198  int i;
6199  For(i,tree->mod->ns) if(p_lk[pos+i] > .0) return i;
6200  return -1;
6201}
6202
6203//////////////////////////////////////////////////////////////
6204//////////////////////////////////////////////////////////////
6205
6206
6207int Get_State_From_P_Pars(short int *p_pars, int pos, t_tree *tree)
6208{
6209  int i;
6210  For(i,tree->mod->ns) if(p_pars[pos+i] > .0) return i;
6211  return -1;
6212}
6213
6214//////////////////////////////////////////////////////////////
6215//////////////////////////////////////////////////////////////
6216
6217
6218//////////////////////////////////////////////////////////////
6219//////////////////////////////////////////////////////////////
6220
6221void Check_Dirs(t_tree *tree)
6222{
6223  int i;
6224
6225  For(i,2*tree->n_otu-3)
6226    {
6227      if(!tree->a_edges[i]->left->tax)
6228        {
6229          if(tree->a_edges[i]->left->v[tree->a_edges[i]->l_v1]->num <
6230             tree->a_edges[i]->left->v[tree->a_edges[i]->l_v2]->num)
6231            {
6232              PhyML_Printf("\n. Edge %d ; v1=%d v2=%d",
6233                     tree->a_edges[i]->num,
6234                     tree->a_edges[i]->left->v[tree->a_edges[i]->l_v1]->num,
6235                     tree->a_edges[i]->left->v[tree->a_edges[i]->l_v2]->num);
6236              PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
6237              Exit("\n");
6238            }
6239        }
6240
6241      if(!tree->a_edges[i]->rght->tax)
6242        {
6243          if(tree->a_edges[i]->rght->v[tree->a_edges[i]->r_v1]->num <
6244             tree->a_edges[i]->rght->v[tree->a_edges[i]->r_v2]->num)
6245            {
6246              PhyML_Printf("\n. Edge %d ; v3=%d v4=%d",
6247                     tree->a_edges[i]->num,
6248                     tree->a_edges[i]->rght->v[tree->a_edges[i]->r_v1]->num,
6249                     tree->a_edges[i]->rght->v[tree->a_edges[i]->r_v2]->num);
6250              PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
6251              Warn_And_Exit("");
6252            }
6253        }
6254    }
6255}
6256
6257//////////////////////////////////////////////////////////////
6258//////////////////////////////////////////////////////////////
6259
6260void Warn_And_Exit(char *s)
6261{
6262  PhyML_Fprintf(stdout,"%s",s);
6263  fflush(NULL);
6264#ifndef BATCH
6265  /* if (! tree->io->quiet) { */
6266  /* char c; */
6267  PhyML_Fprintf(stdout,"\n. Type enter to exit.\n");
6268  /*     if(!fscanf(stdin,"%c",&c))  */
6269  Exit("");
6270  /* } */
6271#endif
6272  Exit("\n");
6273}
6274
6275//////////////////////////////////////////////////////////////
6276//////////////////////////////////////////////////////////////
6277
6278void Randomize_Sequence_Order(calign *cdata)
6279{
6280  int i,exchange_with;
6281  phydbl buff_dbl;
6282  char *buff_name,*buff_state;
6283  short int *buff_ambigu;
6284 
6285  exchange_with = -1;
6286  For(i,cdata->n_otu)
6287    {
6288      buff_dbl  = rand();
6289      buff_dbl /= (RAND_MAX+1.);
6290      buff_dbl *= cdata->n_otu;
6291      exchange_with = (int)FLOOR(buff_dbl);
6292     
6293      buff_name                         = cdata->c_seq[i]->name;
6294      cdata->c_seq[i]->name             = cdata->c_seq[exchange_with]->name;
6295      cdata->c_seq[exchange_with]->name = buff_name;
6296
6297      buff_state                         = cdata->c_seq[i]->state;
6298      cdata->c_seq[i]->state             = cdata->c_seq[exchange_with]->state;
6299      cdata->c_seq[exchange_with]->state = buff_state;
6300
6301      buff_ambigu                            = cdata->c_seq[i]->is_ambigu;
6302      cdata->c_seq[i]->is_ambigu             = cdata->c_seq[exchange_with]->is_ambigu;
6303      cdata->c_seq[exchange_with]->is_ambigu = buff_ambigu;
6304    }
6305}
6306
6307//////////////////////////////////////////////////////////////
6308//////////////////////////////////////////////////////////////
6309
6310
6311void Update_Root_Pos(t_tree *tree)
6312{
6313  if(tree->n_root_pos > -1.0)
6314    {
6315      tree->n_root->l[2] = tree->e_root->l->v * tree->n_root_pos;
6316      tree->n_root->l[1] = tree->e_root->l->v * (1.-tree->n_root_pos);
6317    }
6318  else
6319    {
6320/*       tree->n_root->l[0] = tree->e_root->l->v / 2.; */
6321/*       tree->n_root->l[1] = tree->e_root->l->v / 2.; */
6322    }
6323}
6324
6325//////////////////////////////////////////////////////////////
6326//////////////////////////////////////////////////////////////
6327
6328
6329void Add_Root(t_edge *target, t_tree *tree)
6330{
6331  t_edge *b1, *b2;
6332 
6333  #ifndef PHYML
6334  PhyML_Printf("\n. Adding root on t_edge %d left = %d right = %d\n.",target->num,target->left->num,target->rght->num); fflush(NULL);
6335  #endif
6336
6337  tree->e_root = target;
6338
6339  /* Create the root t_node if it does not exist yet */
6340  if(!tree->a_nodes[2*tree->n_otu-2])
6341    {     
6342      tree->n_root = (t_node *)Make_Node_Light(2*tree->n_otu-2);
6343    }
6344  else
6345    {
6346      tree->n_root = tree->a_nodes[2*tree->n_otu-2];
6347    }
6348
6349  tree->a_nodes[2*tree->n_otu-2] = tree->n_root;
6350
6351  tree->n_root->tax = 0;
6352
6353  /* Set the position of the root */
6354  tree->n_root->v[0] = NULL;
6355  tree->n_root->v[1] = tree->e_root->left;
6356  tree->n_root->v[2] = tree->e_root->rght;
6357
6358  /* tree->n_root->b[2] = tree->e_root; */
6359  /* tree->n_root->b[1] = tree->e_root; */
6360
6361  if(tree->n_root_pos > -1.0)
6362    {
6363      if(tree->n_root_pos < 1.E-6 &&  tree->n_root_pos > -1.E-6)
6364        printf("\n. WARNING: you put the root at a weird position...");
6365
6366/*       tree->n_root->l[0] = tree->e_root->l->v * (tree->n_root_pos/(1.+tree->n_root_pos)); */
6367/*       tree->n_root->l[1] = tree->e_root->l->v - tree->n_root->l[0]; */
6368
6369      tree->n_root->l[2] = tree->e_root->l->v * tree->n_root_pos;
6370      tree->n_root->l[1] = tree->e_root->l->v * (1. - tree->n_root_pos);
6371    }
6372  else
6373    {
6374      tree->n_root->l[2] = tree->e_root->l->v / 2.;
6375      tree->n_root->l[1] = tree->e_root->l->v / 2.;
6376      tree->n_root_pos = 0.5;
6377    }
6378 
6379  b1 = tree->a_edges[2*tree->n_otu-3];
6380  b2 = tree->a_edges[2*tree->n_otu-2];
6381
6382  tree->n_root->b[0] = NULL;
6383  tree->n_root->b[1] = b1;
6384  tree->n_root->b[2] = b2;
6385
6386  b1->num  = tree->num_curr_branch_available;
6387  b2->num  = tree->num_curr_branch_available+1;
6388  b1->left = tree->n_root;
6389  b1->rght = tree->n_root->v[1];
6390  b2->left = tree->n_root;
6391  b2->rght = tree->n_root->v[2];
6392
6393  b1->l->v     = tree->n_root->l[1];
6394  b2->l->v     = tree->n_root->l[2];
6395  b1->l_old->v = tree->n_root->l[1];
6396  b2->l_old->v = tree->n_root->l[2];
6397
6398  b1->l_r = 1;
6399  b2->l_r = 2;
6400
6401  b1->r_l = 0;
6402  b2->r_l = 0;
6403
6404  b1->l_v1 = 0;
6405  b1->l_v2 = 2;
6406
6407  b2->l_v1 = 0;
6408  b2->l_v2 = 1;
6409
6410  b1->r_v1 = 1;
6411  b1->r_v2 = 2;
6412
6413  b2->r_v1 = 1;
6414  b2->r_v2 = 2;
6415
6416
6417  /* WARNING: make sure you have freed the memory for p_lk_rght on b1 and b2 */
6418
6419  b1->p_lk_rght = tree->e_root->p_lk_left;
6420  b2->p_lk_rght = tree->e_root->p_lk_rght;
6421 
6422  b1->p_lk_tip_r = tree->e_root->p_lk_tip_l;
6423  b2->p_lk_tip_r = tree->e_root->p_lk_tip_r;
6424 
6425  b1->sum_scale_rght = tree->e_root->sum_scale_left;
6426  b2->sum_scale_rght = tree->e_root->sum_scale_rght;
6427 
6428  b1->sum_scale_rght_cat = tree->e_root->sum_scale_left_cat;
6429  b2->sum_scale_rght_cat = tree->e_root->sum_scale_rght_cat;
6430 
6431  b1->p_lk_loc_rght = tree->e_root->p_lk_loc_left;
6432  b2->p_lk_loc_rght = tree->e_root->p_lk_loc_rght;
6433 
6434  b1->pars_r = tree->e_root->pars_l;
6435  b2->pars_r = tree->e_root->pars_r;
6436 
6437  b1->ui_r = tree->e_root->ui_l;
6438  b2->ui_r = tree->e_root->ui_r;
6439 
6440  b1->p_pars_r = tree->e_root->p_pars_l;
6441  b2->p_pars_r = tree->e_root->p_pars_r;
6442 
6443  b1->p_lk_loc_rght = tree->e_root->p_lk_loc_left;
6444  b2->p_lk_loc_rght = tree->e_root->p_lk_loc_rght;
6445 
6446  b1->patt_id_rght = tree->e_root->patt_id_left;
6447  b2->patt_id_rght = tree->e_root->patt_id_rght;
6448 
6449  Update_Ancestors(tree->n_root,tree->n_root->v[2],tree);
6450  Update_Ancestors(tree->n_root,tree->n_root->v[1],tree);
6451  tree->n_root->anc = NULL;
6452}
6453
6454//////////////////////////////////////////////////////////////
6455//////////////////////////////////////////////////////////////
6456
6457
6458void Update_Ancestors(t_node *a, t_node *d, t_tree *tree)
6459{
6460  if(a == tree->n_root) a->anc = NULL;
6461  d->anc = a;
6462  if(d->tax) return;
6463  else
6464    {
6465      int i;
6466      For(i,3) 
6467        if((d->v[i] != d->anc) && (d->b[i] != tree->e_root)) 
6468          Update_Ancestors(d,d->v[i],tree);
6469    }
6470}
6471
6472//////////////////////////////////////////////////////////////
6473//////////////////////////////////////////////////////////////
6474
6475/* Generate a random unrooted tree with 'n_otu' OTUs */
6476#if (defined PHYTIME || defined SERGEII)
6477t_tree *Generate_Random_Tree_From_Scratch(int n_otu, int rooted)
6478{
6479  t_tree *tree;
6480  int *connected,*nonconnected,*available_nodes;
6481  int i,n_connected,n_nonconnected,n1,n2,new_n,n_internal,n_external,n_available;
6482  t_node *root,*curr_n,**internal_nodes, **external_nodes;
6483  phydbl *t,*tmp;
6484
6485  tree = Make_Tree_From_Scratch(n_otu,NULL);
6486
6487  tree->rates = RATES_Make_Rate_Struct(tree->n_otu);
6488  RATES_Init_Rate_Struct(tree->rates,tree->io->rates,tree->n_otu);
6489
6490  For(i,2*tree->n_otu-2) 
6491    {
6492      tree->a_nodes[i]->v[1] = NULL;
6493      tree->a_nodes[i]->v[2] = NULL;
6494    }
6495 
6496  root = (t_node *)Make_Node_Light(2*tree->n_otu-2);
6497
6498  connected       = (int *)mCalloc(2*tree->n_otu-2,sizeof(int));
6499  nonconnected    = (int *)mCalloc(2*tree->n_otu-2,sizeof(int));
6500  available_nodes = (int *)mCalloc(2*tree->n_otu-2,sizeof(int));
6501  internal_nodes  = (t_node **)mCalloc(tree->n_otu-2,sizeof(t_node *));
6502  external_nodes  = (t_node **)mCalloc(tree->n_otu,  sizeof(t_node *));
6503  t               = (phydbl *)mCalloc(tree->n_otu-1,sizeof(phydbl ));
6504  tmp             = (phydbl *)mCalloc(2*tree->n_otu-2,sizeof(phydbl ));
6505
6506  n_nonconnected = 2*n_otu-2;
6507
6508  For(i,2*tree->n_otu-2) nonconnected[i] = i;
6509
6510  available_nodes[0] = 2*n_otu-2;
6511
6512  /* Node times are generated according to a Birth-death process.
6513     Formulae are as described by Yang and Rannala (1997) */
6514  phydbl    phi;
6515  phydbl    rho; /* sampling intensity */
6516  phydbl     mu; /* birth rate */
6517  phydbl lambda; /* death rate */
6518  phydbl      u; /* random U[0,1] */
6519  phydbl expval;
6520
6521  /* rho = 1.0 and mu = 0.0 correspond to the Yule process */
6522
6523  lambda = 6.7;
6524  mu     = 2.5;
6525  rho    = 9./150.;
6526
6527  expval = EXP(MIN(1.E+2,mu-lambda));
6528  phi = (rho*lambda*(expval-1.) + (mu-lambda)*expval)/(expval-1.); /* Equation 16 */
6529
6530  For(i,tree->n_otu-1)
6531    {
6532      u = rand();
6533      u /= RAND_MAX;
6534
6535      if(FABS(lambda - mu) > 1.E-4)
6536        t[i] = (LOG(phi-u*rho*lambda) - LOG(phi-u*rho*lambda + u*(lambda-mu)))/(mu-lambda); /* Equation 15 */
6537      else
6538        t[i] = u / (1.+lambda*rho*(1-u)); /* Equation 17 */
6539    }
6540
6541  Qksort(t,NULL,0,tree->n_otu-2); /* Node times ordering in ascending order */
6542
6543  For(i,tree->n_otu-1) tmp[i] =  t[tree->n_otu-2-i];
6544  For(i,tree->n_otu-1) t[i]   = -tmp[i];
6545 
6546
6547  /* Rescale t_node times such that the time at the root t_node is -100 */
6548  for(i=1;i<tree->n_otu-1;i++) 
6549    { 
6550      t[i] /= -t[0]; 
6551      t[i] *= 1.E+02;
6552    }
6553  t[0] = -1.E+02;
6554
6555
6556  n_available = 1;
6557  curr_n = root;
6558  n_connected = 0;
6559  do
6560    {
6561      n1 = Rand_Int(0,n_nonconnected-1);
6562      n1 = nonconnected[n1];
6563      connected[n1] = 1;
6564
6565      n_nonconnected = 0;
6566      For(i,2*tree->n_otu-2) if(!connected[i]) {nonconnected[n_nonconnected++] = i;}
6567
6568      n2 = Rand_Int(0,n_nonconnected-1);
6569      n2 = nonconnected[n2];
6570      connected[n2] = 1;
6571
6572      n_nonconnected = 0;
6573      For(i,2*tree->n_otu-2) if(!connected[i]) {nonconnected[n_nonconnected++] = i;}
6574
6575      curr_n->v[1] = tree->a_nodes[n1];
6576      curr_n->v[2] = tree->a_nodes[n2];
6577      tree->a_nodes[n1]->v[0] = curr_n;
6578      tree->a_nodes[n2]->v[0] = curr_n;
6579     
6580      tree->rates->nd_t[curr_n->num] = t[n_connected/2];
6581
6582      available_nodes[n_available] = tree->a_nodes[n1]->num; 
6583      For(i,n_available)
6584        if(available_nodes[i] == curr_n->num) 
6585          {
6586            available_nodes[i] = tree->a_nodes[n2]->num;
6587            break;
6588          }
6589      n_available++;
6590     
6591      new_n = Rand_Int(0,n_available-1);
6592      curr_n = tree->a_nodes[available_nodes[new_n]];
6593     
6594      n_connected+=2;
6595
6596    }while(n_connected < 2*tree->n_otu-2);
6597
6598  For(i,2*tree->n_otu-2) tmp[i] = tree->rates->nd_t[i];
6599
6600  /* Unroot the tree */
6601  root->v[2]->v[0] = root->v[2];
6602  root->v[1]->v[0] = root->v[1];
6603
6604  n_internal = n_external = 0;
6605  For(i,2*tree->n_otu-2)
6606    {
6607      if(tree->a_nodes[i]->v[1]) internal_nodes[n_internal++] = tree->a_nodes[i];
6608      else                     external_nodes[n_external++] = tree->a_nodes[i];
6609    }
6610
6611
6612  n_internal = n_external = 0; 
6613  For(i,2*tree->n_otu-2) 
6614    { 
6615      if(i < tree->n_otu)
6616        {
6617          tree->a_nodes[i]      = external_nodes[n_external++];
6618          tree->a_nodes[i]->tax = 1;     
6619        }
6620      else
6621        {
6622          tree->rates->nd_t[i] = tmp[internal_nodes[n_internal]->num];
6623          tree->a_nodes[i]        = internal_nodes[n_internal++];
6624          tree->a_nodes[i]->tax   = 0;
6625        }
6626
6627      tree->a_nodes[i]->num = i;
6628    }
6629
6630  For(i,tree->n_otu) tree->rates->nd_t[i] = 0.0;
6631 
6632  For(i,tree->n_otu) 
6633    {
6634      if(!tree->a_nodes[i]->name) tree->a_nodes[i]->name = (char *)mCalloc(T_MAX_NAME,sizeof(char));
6635      strcpy(tree->a_nodes[i]->name,"x");
6636      sprintf(tree->a_nodes[i]->name+1,"%d",i);
6637    }
6638
6639
6640  tree->num_curr_branch_available = 0;
6641  Connect_Edges_To_Nodes_Recur(tree->a_nodes[0],tree->a_nodes[0]->v[0],tree);
6642  Fill_Dir_Table(tree);
6643  Update_Dirs(tree);
6644
6645
6646  /* Add root */
6647  if(rooted)
6648    {
6649      For(i,2*tree->n_otu-3) 
6650        {
6651          if(((tree->a_edges[i]->left == root->v[1]) || (tree->a_edges[i]->rght == root->v[1])) &&
6652             ((tree->a_edges[i]->left == root->v[2]) || (tree->a_edges[i]->rght == root->v[2])))
6653            {
6654              Add_Root(tree->a_edges[i],tree);
6655              break;
6656            }
6657        }
6658    }
6659  /* Or not... */
6660  else
6661    {
6662      Free_Node(root);
6663    }
6664
6665  RATES_Random_Branch_Lengths(tree);
6666 
6667  Free(available_nodes);
6668  Free(connected);
6669  Free(nonconnected);
6670  Free(external_nodes);
6671  Free(internal_nodes);
6672  Free(t);
6673  Free(tmp);
6674
6675  return tree;
6676}
6677#endif
6678//////////////////////////////////////////////////////////////
6679//////////////////////////////////////////////////////////////
6680
6681
6682void Random_Lineage_Rates(t_node *a, t_node *d, t_edge *b, phydbl stick_prob, phydbl *rates, int curr_rate, int n_rates, t_tree *tree)
6683{
6684  phydbl uni;
6685  int new_rate;
6686  int i;
6687
6688
6689  if(b)
6690    {
6691      uni  = rand();
6692      uni /= RAND_MAX;
6693     
6694      if(uni > stick_prob) /* Randomly pick a new rate */
6695        {
6696          uni  = rand();
6697          uni /= RAND_MAX;
6698          uni = (phydbl)(uni * (n_rates-1));     
6699          if(uni-(int)(uni) > 0.5-BIG) new_rate = (int)(uni)+1;
6700          else new_rate = (int)(uni);     
6701        }
6702      else
6703        {
6704          new_rate = curr_rate;
6705        }
6706
6707      For(i,3) 
6708        if(a->v[i] == d) 
6709          {
6710            a->b[i]->l->v *= rates[new_rate];
6711            break;
6712          }
6713
6714      For(i,3)
6715        if(a->v[i] == d)
6716          {
6717            if(!(a->b[i]->n_labels%BLOCK_LABELS)) Make_New_Edge_Label(a->b[i]);
6718            if(rates[new_rate] > 1.0)      strcpy(a->b[i]->labels[a->b[i]->n_labels],"FAST");
6719            else if(rates[new_rate] < 1.0) strcpy(a->b[i]->labels[a->b[i]->n_labels],"SLOW");
6720            else                           strcpy(a->b[i]->labels[a->b[i]->n_labels],"MEDIUM");
6721            a->b[i]->n_labels++;
6722            break;
6723          }
6724      curr_rate = new_rate;
6725    }
6726 
6727  if(d->tax) return;
6728  else
6729    {
6730      For(i,3) 
6731        if(d->v[i] != a) 
6732          Random_Lineage_Rates(d,d->v[i],d->b[i],stick_prob,rates,curr_rate,n_rates,tree);
6733    }
6734}
6735
6736//////////////////////////////////////////////////////////////
6737//////////////////////////////////////////////////////////////
6738
6739
6740t_edge *Find_Edge_With_Label(char *label, t_tree *tree)
6741{
6742  int i,j;
6743
6744  For(i,2*tree->n_otu-3)
6745    {
6746      For(j,tree->a_edges[i]->n_labels)
6747        {
6748          if(!strcmp(tree->a_edges[i]->labels[j],label)) return tree->a_edges[i];
6749        }
6750    }
6751  return NULL;
6752}
6753
6754//////////////////////////////////////////////////////////////
6755//////////////////////////////////////////////////////////////
6756
6757void Evolve(calign *data, t_mod *mod, t_tree *tree)
6758{
6759  int root_state, root_rate_class;
6760  int site,i;
6761  phydbl *orig_l;
6762  phydbl shape,scale,var,mean;
6763
6764  orig_l = (phydbl *)mCalloc(2*tree->n_otu-3,sizeof(phydbl));
6765  For(i,2*tree->n_otu-3) orig_l[i] = tree->a_edges[i]->l->v;
6766
6767  data->n_otu = tree->n_otu;
6768
6769  if(mod->use_m4mod) tree->write_labels = YES;
6770 
6771
6772  For(site,data->init_len)
6773    {
6774      /* Get the change probability matrices */
6775      For(i,2*tree->n_otu-3)       
6776        {
6777          /* var   = mod->l_var ; */
6778
6779          /* shape = POW(MAX(orig_l[i],1.E-6),2) / var; */
6780          /* scale = var / MAX(orig_l[i],1.E-6); */
6781
6782          /* tree->a_edges[i]->l->v = Rgamma(shape,scale); */
6783
6784          var   = mod->l_var_sigma;
6785          mean  = 1.0;
6786         
6787          shape = mean * mean / var;
6788          scale = var / mean;
6789         
6790          tree->a_edges[i]->l->v = orig_l[i] * Rgamma(shape,scale);
6791        }
6792
6793      Set_Model_Parameters(mod);     
6794      For(i,2*tree->n_otu-3) Update_PMat_At_Given_Edge(tree->a_edges[i],tree);
6795
6796      root_state = root_rate_class = -1;
6797
6798      /* Pick the root nucleotide/aa */
6799      root_state = Pick_State(mod->ns,mod->e_frq->pi->v);
6800      data->c_seq[0]->state[site] = Reciproc_Assign_State(root_state,tree->io->datatype);
6801
6802      /* Pick the rate class */
6803      root_rate_class = Pick_State(mod->ras->n_catg,mod->ras->gamma_r_proba->v);
6804
6805      /* tree->a_nodes[0] is considered as the root t_node */
6806      Evolve_Recur(tree->a_nodes[0],
6807                   tree->a_nodes[0]->v[0],
6808                   tree->a_nodes[0]->b[0],
6809                   root_state,
6810                   root_rate_class,
6811                   site,
6812                   data,
6813                   mod,
6814                   tree);
6815
6816/*       PhyML_Printf("%s\n",Write_Tree(tree,NO)); */
6817     
6818      data->wght[site] = 1;
6819    }
6820  data->crunch_len = data->init_len;
6821  Print_CSeq(stdout,NO,data);
6822}
6823
6824//////////////////////////////////////////////////////////////
6825//////////////////////////////////////////////////////////////
6826
6827
6828int Pick_State(int n, phydbl *prob)
6829{
6830  int pos;
6831  phydbl uni;
6832
6833  do
6834    {
6835      pos  = rand();
6836      pos  = (pos % n);
6837      uni  = (phydbl)rand();
6838      uni /= (phydbl)RAND_MAX;
6839      if(uni < prob[pos]) break;
6840    }
6841  while(1);
6842 
6843  return (int)pos;
6844}
6845
6846//////////////////////////////////////////////////////////////
6847//////////////////////////////////////////////////////////////
6848
6849
6850void Evolve_Recur(t_node *a, t_node *d, t_edge *b, int a_state, int r_class, int site_num, calign *gen_data, t_mod *mod, t_tree *tree)
6851{
6852  int d_state;
6853  int dim1,dim2;
6854
6855  dim1 = tree->mod->ns * tree->mod->ns;
6856  dim2 = tree->mod->ns;
6857
6858  d_state = Pick_State(mod->ns,b->Pij_rr+r_class*dim1+a_state*dim2);
6859 
6860/*   PhyML_Printf("\n>> %c (%d,%d)",Reciproc_Assign_State(d_state,mod->io->datatype),d_state,(int)d_state/mod->m4mod->n_o); */
6861
6862  if(mod->use_m4mod) 
6863    {
6864      phydbl rrate; /* relative rate of substitutions */
6865     
6866      rrate = mod->m4mod->multipl[(int)d_state/mod->m4mod->n_o];
6867      if(!(b->n_labels%BLOCK_LABELS)) Make_New_Edge_Label(b);
6868      if(rrate > 1.0) strcpy(b->labels[b->n_labels],"FASTER");
6869      else strcpy(b->labels[b->n_labels],"SLOWER");
6870      b->n_labels++;
6871    }
6872
6873  if(d->tax) 
6874    {
6875      gen_data->c_seq[d->num]->state[site_num] = Reciproc_Assign_State(d_state,tree->io->datatype);
6876      return;
6877    }
6878  else
6879    {
6880      int i;
6881      For(i,3)
6882        if(d->v[i] != a)
6883          Evolve_Recur(d,d->v[i],d->b[i],
6884                       d_state,r_class,site_num,gen_data,
6885                       mod,tree);
6886    }
6887}
6888
6889//////////////////////////////////////////////////////////////
6890//////////////////////////////////////////////////////////////
6891
6892
6893void Site_Diversity(t_tree *tree)
6894{
6895  int i,j,k,ns;
6896  int *div,sum;
6897
6898  ns = tree->mod->ns;
6899
6900  div = (int *)mCalloc(ns,sizeof(int));
6901
6902  Site_Diversity_Post(tree->a_nodes[0],tree->a_nodes[0]->v[0],tree->a_nodes[0]->b[0],tree);
6903  Site_Diversity_Pre (tree->a_nodes[0],tree->a_nodes[0]->v[0],tree->a_nodes[0]->b[0],tree);
6904
6905  For(i,2*tree->n_otu-3)
6906    {
6907      For(j,ns)
6908        {
6909          tree->a_edges[i]->div_post_pred_left[j] = 0;
6910          tree->a_edges[i]->div_post_pred_rght[j] = 0;
6911        }
6912    }
6913
6914  For(i,tree->n_pattern)
6915    {
6916      For(j,2*tree->n_otu-3)
6917        {
6918          Binary_Decomposition(tree->a_edges[j]->ui_l[i],div,ns);
6919          sum = 0;
6920          For(k,ns) sum += div[k];
6921          tree->a_edges[j]->div_post_pred_left[sum-1] += tree->data->wght[i];
6922
6923          Binary_Decomposition(tree->a_edges[j]->ui_r[i],div,ns);
6924          sum = 0;
6925          For(k,ns) sum += div[k];
6926          tree->a_edges[j]->div_post_pred_rght[sum-1] += tree->data->wght[i];
6927        }
6928    }
6929
6930/*   For(j,2*tree->n_otu-3) */
6931/*     { */
6932/*       PhyML_Printf("\n. Edge %4d   div_left = %4d %4d %4d %4d -- div_rght = %4d %4d %4d %4d", */
6933/*           j, */
6934/*           tree->a_edges[j]->div_post_pred_left[0], */
6935/*           tree->a_edges[j]->div_post_pred_left[1], */
6936/*           tree->a_edges[j]->div_post_pred_left[2], */
6937/*           tree->a_edges[j]->div_post_pred_left[3], */
6938/*           tree->a_edges[j]->div_post_pred_rght[0], */
6939/*           tree->a_edges[j]->div_post_pred_rght[1], */
6940/*           tree->a_edges[j]->div_post_pred_rght[2], */
6941/*           tree->a_edges[j]->div_post_pred_rght[3]); */
6942/*     } */
6943 
6944  Free(div);
6945}
6946
6947//////////////////////////////////////////////////////////////
6948//////////////////////////////////////////////////////////////
6949
6950
6951void Site_Diversity_Post(t_node *a, t_node *d, t_edge *b, t_tree *tree)
6952{
6953  if(d->tax) return;
6954  else
6955    {
6956      int i;
6957
6958      For(i,3)
6959        if(d->v[i] != a)
6960          Site_Diversity_Post(d,d->v[i],d->b[i],tree);
6961
6962      Subtree_Union(d,b,tree);
6963    }
6964}
6965
6966//////////////////////////////////////////////////////////////
6967//////////////////////////////////////////////////////////////
6968
6969
6970void Site_Diversity_Pre(t_node *a, t_node *d, t_edge *b, t_tree *tree)
6971{
6972  if(d->tax) return;
6973  else
6974    {
6975      int i;
6976     
6977      For(i,3)
6978        if(d->v[i] != a)
6979          {
6980            Subtree_Union(d,d->b[i],tree);
6981            Site_Diversity_Pre(d,d->v[i],d->b[i],tree);
6982          }
6983    }
6984}
6985
6986//////////////////////////////////////////////////////////////
6987//////////////////////////////////////////////////////////////
6988
6989
6990void Subtree_Union(t_node *n, t_edge *b_fcus, t_tree *tree)
6991{
6992/* 
6993           |
6994           |<- b_cus
6995           |
6996           n
6997          / \
6998         /   \
6999        /     \
7000*/
7001
7002  int site;
7003  unsigned int *ui, *ui_v1, *ui_v2;
7004 
7005  ui = ui_v1 = ui_v2 = NULL;
7006
7007  if(n == b_fcus->left)
7008    {       
7009      ui = b_fcus->ui_l;
7010
7011      ui_v1 = 
7012      (n == n->b[b_fcus->l_v1]->left)?
7013      (n->b[b_fcus->l_v1]->ui_r):
7014      (n->b[b_fcus->l_v1]->ui_l);
7015
7016      ui_v2 = 
7017      (n == n->b[b_fcus->l_v2]->left)?
7018      (n->b[b_fcus->l_v2]->ui_r):
7019      (n->b[b_fcus->l_v2]->ui_l);
7020    }
7021  else
7022    {
7023      ui = b_fcus->ui_r;
7024     
7025      ui_v1 = 
7026      (n == n->b[b_fcus->r_v1]->left)?
7027      (n->b[b_fcus->r_v1]->ui_r):
7028      (n->b[b_fcus->r_v1]->ui_l);
7029
7030      ui_v2 = 
7031      (n == n->b[b_fcus->r_v2]->left)?
7032      (n->b[b_fcus->r_v2]->ui_r):
7033      (n->b[b_fcus->r_v2]->ui_l);
7034    }
7035
7036  For(site,tree->n_pattern) ui[site] = ui_v1[site] | ui_v2[site];
7037
7038}
7039
7040//////////////////////////////////////////////////////////////
7041//////////////////////////////////////////////////////////////
7042
7043
7044void Binary_Decomposition(int value, int *bit_vect, int size)
7045{
7046  int i,cumul;
7047
7048  For(i,size) bit_vect[i] = 0;
7049 
7050  cumul = 0;
7051  for(i=size-1;i>=0;i--)
7052    {
7053      if(value - cumul < (int)POW(2,i))
7054        {
7055          bit_vect[i] = 0;
7056        }
7057      else
7058        {
7059          bit_vect[i] = 1;
7060          cumul += (int)POW(2,i);
7061        }
7062    }
7063}
7064
7065//////////////////////////////////////////////////////////////
7066//////////////////////////////////////////////////////////////
7067
7068
7069void Print_Diversity_Header(FILE *fp, t_tree *tree)
7070{
7071/*   PhyML_Fprintf(fp,"t_edge side mean\n");  */
7072  PhyML_Fprintf(fp,"t_edge side diversity count\n"); 
7073}
7074
7075//////////////////////////////////////////////////////////////
7076//////////////////////////////////////////////////////////////
7077
7078
7079
7080//////////////////////////////////////////////////////////////
7081//////////////////////////////////////////////////////////////
7082
7083/* Estimation of density using kernel smoothing.
7084- where : point where I want to estimate the density,
7085- x : data vector,
7086- sample_size :  number of data points in x
7087*/
7088phydbl Univariate_Kernel_Density_Estimate(phydbl where, phydbl *x, int sample_size)
7089{
7090  phydbl sd,h;
7091  phydbl density,sqrt2pi,cons;
7092  int i;
7093
7094  sqrt2pi = 2.506628;
7095
7096  sd = SQRT(Var(x,sample_size));
7097  h = 1.06 * sd * POW(sample_size,-1./5.); /* Quick and dirty way to set the bandwidth */
7098 
7099  cons = (1./sample_size) * (1./h) * (1./sqrt2pi);
7100
7101  density = .0;
7102  For(i,sample_size) density += EXP(-0.5 * POW((x[i] - where)/h,2));
7103  density *= cons;
7104
7105  return density;
7106}
7107
7108//////////////////////////////////////////////////////////////
7109//////////////////////////////////////////////////////////////
7110
7111
7112/* Estimation of a multivariate density using kernel smoothing.
7113
7114- where : vector where I want to estimate the density,
7115- x : data matrix, i.e., sample of vectors,
7116- sample_size : number of vectors,
7117- vect_size : vector length.
7118
7119See "Multivariate Density Estimation" by David Scott. pp 150.
7120*/
7121phydbl Multivariate_Kernel_Density_Estimate(phydbl *where, phydbl **x, int sample_size, int vect_size)
7122{
7123  phydbl sd,*h,cons,density,tmp;
7124  phydbl _2pi;
7125  int i,j;
7126
7127  h = (phydbl *)mCalloc(vect_size,sizeof(phydbl));
7128
7129  _2pi = 6.283185;
7130 
7131  For(i,vect_size)
7132    {
7133      sd = SQRT(Var(x[i],sample_size));
7134/*       h[i] = POW(4./(vect_size+2.),1./(vect_size+4)) * sd * POW(sample_size,-1./(vect_size+4)); */
7135      h[i] = sd * POW(sample_size,-1./(vect_size+4));
7136/*       PhyML_Printf("\n. sd = %f, h[i] = %f",sd,h[i]); */
7137    }
7138
7139  cons = sample_size;
7140  For(i,vect_size) cons *= h[i];
7141  cons *= POW(_2pi,vect_size/2.);
7142  cons = 1./cons;
7143
7144  density = .0;
7145  For(i,sample_size)
7146    {
7147      tmp = 1.0;
7148      For(j,vect_size) 
7149        {
7150          tmp *= EXP(-0.5 * POW((x[j][i] - where[j])/h[j],2));
7151        }
7152      density += tmp;
7153    }
7154 
7155  density *= cons;
7156
7157  Free(h);
7158
7159  return density;
7160}
7161
7162//////////////////////////////////////////////////////////////
7163//////////////////////////////////////////////////////////////
7164
7165
7166phydbl Var(phydbl *x, int n)
7167{
7168  phydbl mean, sum2;
7169  int i;
7170
7171  mean = Mean(x,n);
7172
7173  sum2 = .0;
7174  For(i,n) sum2 += x[i] * x[i];
7175 
7176  return (1./n) * (sum2 - n * POW(mean,2));
7177}
7178
7179//////////////////////////////////////////////////////////////
7180//////////////////////////////////////////////////////////////
7181
7182
7183phydbl Mean(phydbl *x, int n)
7184{
7185  int i;
7186  phydbl sum;
7187
7188  sum = .0;
7189
7190  For(i,n) sum += x[i];
7191
7192  return sum / n;
7193}
7194
7195//////////////////////////////////////////////////////////////
7196//////////////////////////////////////////////////////////////
7197
7198
7199void Best_Of_NNI_And_SPR(t_tree *tree)
7200{
7201  if(tree->mod->s_opt->random_input_tree) Speed_Spr_Loop(tree); /* Don't do simultaneous NNIs if starting tree is random */
7202  else
7203    {
7204      t_tree *ori_tree,*best_tree;
7205      t_mod *ori_mod,*best_mod;
7206      phydbl *ori_bl,*best_bl;
7207      phydbl best_lnL,ori_lnL,nni_lnL,spr_lnL;
7208      int i;
7209
7210      ori_bl = (phydbl *)mCalloc(2*tree->n_otu-3,sizeof(phydbl));
7211      best_bl = (phydbl *)mCalloc(2*tree->n_otu-3,sizeof(phydbl));
7212     
7213      ori_mod   = Copy_Model(tree->mod);
7214      best_mod  = Copy_Model(tree->mod);
7215     
7216      ori_tree = Make_Tree_From_Scratch(tree->n_otu,tree->data);
7217
7218/*       ori_tree = Make_Tree(tree->n_otu); */
7219/*       Init_Tree(ori_tree,ori_tree->n_otu); */
7220/*       Make_All_Tree_Nodes(ori_tree); */
7221/*       Make_All_Tree_Edges(ori_tree); */
7222     
7223      best_tree = Make_Tree_From_Scratch(tree->n_otu,tree->data);
7224
7225/*       best_tree = Make_Tree(tree->n_otu); */
7226/*       Init_Tree(best_tree,best_tree->n_otu); */
7227/*       Make_All_Tree_Nodes(best_tree); */
7228/*       Make_All_Tree_Edges(best_tree); */
7229
7230      Copy_Tree(tree,ori_tree);
7231      Record_Br_Len(tree);
7232      For(i,2*tree->n_otu-3) ori_bl[i] = tree->a_edges[i]->l->v;
7233
7234
7235      best_lnL = UNLIKELY;
7236      Lk(NULL,tree);
7237      ori_lnL = tree->c_lnL; /* Record likelihood of the starting tree */
7238
7239
7240
7241      Simu_Loop(tree); /* Perform simultaneous NNIs */
7242      best_lnL = tree->c_lnL; /* Record the likelihood */
7243      nni_lnL = tree->c_lnL;
7244      Copy_Tree(tree,best_tree); /* Record the tree topology and branch lengths */
7245      Record_Br_Len(tree);
7246      For(i,2*tree->n_otu-3) best_bl[i] = tree->a_edges[i]->l->v;
7247      For(i,2*tree->n_otu-3) best_tree->a_edges[i]->l->v = best_bl[i];
7248      Record_Model(tree->mod,best_mod);
7249     
7250      Copy_Tree(ori_tree,tree); /* Back to the original tree topology */
7251      For(i,2*tree->n_otu-3) tree->a_edges[i]->l->v = ori_bl[i]; /* Back to the original branch lengths */
7252      Record_Model(ori_mod,tree->mod); /* Back to the original model */
7253     
7254      /* Make sure the tree is in its original form */
7255      Lk(NULL,tree);
7256
7257
7258      if(FABS(tree->c_lnL - ori_lnL) > tree->mod->s_opt->min_diff_lk_local)
7259        {
7260          PhyML_Printf("\n== ori_lnL = %f, c_lnL = %f",ori_lnL,tree->c_lnL);
7261          PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);
7262          Warn_And_Exit("");
7263        }
7264
7265      Speed_Spr_Loop(tree);
7266      spr_lnL = tree->c_lnL;
7267      if(tree->c_lnL > best_lnL)
7268        {
7269          best_lnL = tree->c_lnL;
7270          Copy_Tree(tree,best_tree); /* Record tree topology, branch lengths and model parameters */
7271          Record_Br_Len(tree);
7272          For(i,2*tree->n_otu-3) best_bl[i] = tree->a_edges[i]->l->v;
7273          For(i,2*tree->n_otu-3) best_tree->a_edges[i]->l->v = best_bl[i];
7274          Record_Model(tree->mod,best_mod);
7275        }
7276     
7277      Copy_Tree(best_tree,tree);
7278      Fill_Dir_Table(tree);
7279      Update_Dirs(tree);
7280      Init_P_Lk_Tips_Int(tree);
7281      Init_Ui_Tips(tree);
7282      Init_P_Pars_Tips(tree);
7283      For(i,2*tree->n_otu-3) tree->a_edges[i]->l->v = best_bl[i];
7284      Record_Model(best_mod,tree->mod);
7285     
7286      /* Make sure the current tree has the best topology, branch lengths and model parameters */
7287      Lk(NULL,tree);
7288      if(FABS(tree->c_lnL - best_lnL) > tree->mod->s_opt->min_diff_lk_local)
7289        {
7290          PhyML_Printf("\n. best_lnL = %f, c_lnL = %f",best_lnL,tree->c_lnL);
7291          PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
7292          Warn_And_Exit("");
7293        }
7294     
7295      if(tree->mod->s_opt->print)
7296        {
7297          PhyML_Printf("\n\n. Log likelihood obtained after NNI moves : %f",nni_lnL);
7298          PhyML_Printf("\n. Log likelihood obtained after SPR moves : %f",spr_lnL);
7299        }
7300     
7301      Free(ori_bl);
7302      Free(best_bl);
7303     
7304      Free_Tree(ori_tree);
7305      Free_Tree(best_tree);
7306     
7307      Free_Model_Complete(ori_mod);
7308      Free_Model_Complete(best_mod);
7309
7310      M4_Free_M4_Model(ori_mod->m4mod);
7311      M4_Free_M4_Model(best_mod->m4mod);
7312
7313      Free_Model_Basic(ori_mod);
7314      Free_Model_Basic(best_mod);
7315    }
7316}
7317
7318//////////////////////////////////////////////////////////////
7319//////////////////////////////////////////////////////////////
7320
7321
7322/* Polynomial interpolation. Adapted from "Numerical Recipes in C".
7323Press, Flannery, Teukolsky, Vetterling, 1988.
7324*/
7325int Polint(phydbl *xa, phydbl *ya, int n, phydbl x, phydbl *y, phydbl *dy)
7326{
7327   int i,m,ns=1;
7328   phydbl den,dif,dift,ho,hp,w;
7329   phydbl *c,*d;
7330
7331   dif=FABS(x-xa[1]);
7332
7333   c = (phydbl *)mCalloc(n,sizeof(phydbl));
7334   d = (phydbl *)mCalloc(n,sizeof(phydbl));
7335
7336   for(i=1;i<=n;i++) 
7337     {
7338       if((dift=FABS(x-xa[i])) < dif) 
7339         {
7340           ns=i;
7341           dif=dift;
7342         }
7343       c[i]=ya[i];
7344       d[i]=ya[i];
7345     }
7346   
7347   *y=ya[ns--];
7348   
7349   for (m=1;m<n;m++) 
7350     {
7351       for (i=1;i<=n-m;i++) 
7352         {
7353           ho=xa[i]-x;
7354           hp=xa[i+m]-x;
7355           w=c[i+1]-d[i];
7356           if((den=ho-hp) < SMALL && (den=ho-hp) > -SMALL )
7357             {
7358/*             Rprintf("\n. Error in routine POLINT.\n"); */
7359               Exit("\n. Error in routine POLINT.\n");
7360               return(-1);
7361             }
7362           den=w/den;
7363           d[i]=hp*den;
7364           c[i]=ho*den;
7365         }
7366       *y += (*dy=(2*ns < (n-m) ? c[ns+1] : d[ns--]));
7367     }
7368
7369   Free(d);
7370   Free(c);
7371   return(0);
7372}
7373
7374//////////////////////////////////////////////////////////////
7375//////////////////////////////////////////////////////////////
7376
7377
7378void JF(t_tree *tree)
7379{
7380  //printing loglk for each site, to compute SH-like tests */
7381  phydbl sum=0.0;
7382  PhyML_Printf("\n\nSITES LKS:\n");
7383  int n_patterns = (int)FLOOR(tree->n_pattern);
7384  int site=0;
7385  For(site,n_patterns) {
7386    int wei=0;
7387    For(wei,tree->data->wght[site]) {
7388      PhyML_Printf("%f\n",tree->c_lnL_sorted[site] / tree->data->wght[site]);
7389      sum+=tree->c_lnL_sorted[site] / tree->data->wght[site];
7390    }
7391  }
7392 
7393  PhyML_Printf("\n\nsum=%f\n\n",sum);
7394  int i=0;
7395  For(i,2*tree->n_otu-3)
7396    {
7397      if((!tree->a_edges[i]->left->tax) && (!tree->a_edges[i]->rght->tax))
7398        {
7399          PhyML_Printf("%3d %f %f %f\n",
7400                 tree->a_edges[i]->bip_score,tree->a_edges[i]->alrt_statistic, tree->a_edges[i]->ratio_test,tree->a_edges[i]->l->v);
7401        }
7402    }
7403 
7404 
7405/*   //printing loglk for each site, to compute SH-like tests */
7406/*   phydbl sum=0.0; */
7407/*   PhyML_Printf("\n\nSITES LKS:\n"); */
7408/*   int n_patterns = (int)FLOOR(tree->n_pattern); */
7409/*   int site=0; */
7410/*   For(site,n_patterns) { */
7411/*     int wei=0; */
7412/*     For(wei,tree->data->wght[site]) { */
7413/*       PhyML_Printf("%f\n",tree->c_lnL_sorted[site] / tree->data->wght[site]); */
7414/*       sum+=tree->c_lnL_sorted[site] / tree->data->wght[site]; */
7415/*     } */
7416/*   } */
7417 
7418/*   PhyML_Printf("\n\nsum=%f\n\n",sum); */
7419 
7420/*   int i=0; */
7421/*   For(i,2*tree->n_otu-3) */
7422/*     { */
7423/*       if((!tree->a_edges[i]->left->tax) && (!tree->a_edges[i]->rght->tax)) */
7424/*      { */
7425/*        PhyML_Printf("%3d %f %f %f\n", */
7426/*               tree->a_edges[i]->bip_score,tree->a_edges[i]->alrt_statistic, tree->a_edges[i]->ratio_test,tree->a_edges[i]->l->v); */
7427/*      } */
7428/*     } */
7429}
7430
7431//////////////////////////////////////////////////////////////
7432//////////////////////////////////////////////////////////////
7433
7434
7435t_tree *Dist_And_BioNJ(calign *cdata, t_mod *mod, option *io)
7436{
7437  t_tree *tree;
7438  matrix *mat;
7439
7440  if(!io->quiet) PhyML_Printf("\n. Computing pairwise distances...");
7441
7442  mat = ML_Dist(cdata,mod);
7443  Fill_Missing_Dist(mat);
7444 
7445  if(!io->quiet) PhyML_Printf("\n\n. Building BioNJ tree...");
7446
7447  mat->tree = Make_Tree_From_Scratch(cdata->n_otu,cdata);
7448
7449  Bionj(mat);
7450  tree      = mat->tree;
7451  tree->mat = mat;
7452
7453  return tree;
7454}
7455
7456//////////////////////////////////////////////////////////////
7457//////////////////////////////////////////////////////////////
7458
7459
7460void Add_BioNJ_Branch_Lengths(t_tree *tree, calign *cdata, t_mod *mod)
7461{
7462  matrix *mat;
7463 
7464  PhyML_Printf("\n");
7465  PhyML_Printf("\n. Computing branch length estimates...\n");
7466
7467  Connect_CSeqs_To_Nodes(cdata,tree);
7468  mat = ML_Dist(cdata,mod);
7469  mat->tree = tree;
7470  mat->method = 0;
7471  Bionj_Br_Length(mat);
7472
7473  Free_Mat(mat);
7474}
7475
7476//////////////////////////////////////////////////////////////
7477//////////////////////////////////////////////////////////////
7478
7479char *Bootstrap_From_String(char *s_tree, calign *cdata, t_mod *mod, option *io)
7480{
7481  t_tree *tree;
7482
7483  tree = Read_Tree(&s_tree);
7484 
7485  tree->n_root = NULL;
7486  tree->e_root = NULL;
7487
7488  if(!tree)
7489    {
7490      PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);
7491      Exit("");
7492    }
7493
7494  tree->mod         = mod;
7495  tree->io          = io;
7496  tree->data        = cdata;
7497  tree->n_pattern   = tree->data->crunch_len;
7498
7499  Connect_CSeqs_To_Nodes(cdata,tree);
7500  if(tree->mod->s_opt->random_input_tree) Random_Tree(tree);
7501  Fill_Dir_Table(tree);
7502  Update_Dirs(tree);
7503  Make_Tree_4_Pars(tree,cdata,cdata->init_len);
7504  Make_Tree_4_Lk(tree,cdata,cdata->init_len);
7505  tree->triplet_struct = Make_Triplet_Struct(mod); 
7506  Init_Triplet_Struct(tree->triplet_struct);
7507  Unscale_Br_Len_Multiplier_Tree(tree);
7508  Br_Len_Not_Involving_Invar(tree);
7509  Make_Spr_List(tree);
7510  Make_Best_Spr(tree);
7511
7512
7513  Set_Both_Sides(YES,tree);
7514  Lk(NULL,tree);
7515
7516#ifdef MPI
7517  Bootstrap_MPI(tree);
7518#else
7519  Bootstrap(tree);
7520#endif
7521
7522  Free(s_tree); 
7523  s_tree = Write_Tree(tree,NO);
7524 
7525  Free_Spr_List(tree);
7526  Free_Triplet(tree->triplet_struct);
7527  Free_Tree_Pars(tree);
7528  Free_Tree_Lk(tree);
7529  Free_Tree(tree);
7530
7531  return s_tree;
7532}
7533
7534//////////////////////////////////////////////////////////////
7535//////////////////////////////////////////////////////////////
7536
7537
7538char *aLRT_From_String(char *s_tree, calign *cdata, t_mod *mod, option *io)
7539{
7540  t_tree *tree;
7541
7542  tree = Read_Tree(&s_tree);
7543
7544  tree->n_root = NULL;
7545  tree->e_root = NULL;
7546
7547  if(!tree)
7548    {
7549      PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);
7550      Warn_And_Exit("");
7551    }
7552
7553  tree->mod         = mod;
7554  tree->io          = io;
7555  tree->data        = cdata;
7556  tree->n_pattern   = tree->data->crunch_len;
7557
7558  Connect_CSeqs_To_Nodes(cdata,tree);
7559  if(tree->mod->s_opt->random_input_tree) Random_Tree(tree);
7560  Fill_Dir_Table(tree);
7561  Update_Dirs(tree);
7562  Make_Tree_4_Pars(tree,cdata,cdata->init_len);
7563  Make_Tree_4_Lk(tree,cdata,cdata->init_len);
7564  tree->triplet_struct = Make_Triplet_Struct(mod);
7565  Init_Triplet_Struct(tree->triplet_struct);
7566  Make_Spr_List(tree);
7567  Make_Best_Spr(tree);
7568
7569  Set_Both_Sides(YES,tree);
7570  Lk(NULL,tree);
7571
7572
7573  aLRT(tree);
7574 
7575
7576  Free(s_tree);
7577  s_tree = Write_Tree(tree,NO);
7578
7579  Free_Spr_List(tree);
7580  Free_Triplet(tree->triplet_struct);
7581  Free_Tree_Pars(tree);
7582  Free_Tree_Lk(tree);
7583  Free_Tree(tree);
7584 
7585  return s_tree;
7586}
7587
7588//////////////////////////////////////////////////////////////
7589//////////////////////////////////////////////////////////////
7590
7591void Prepare_Tree_For_Lk(t_tree *tree)
7592{
7593  Connect_CSeqs_To_Nodes(tree->data,tree);
7594  Fill_Dir_Table(tree);
7595  Update_Dirs(tree);
7596  Make_Tree_4_Pars(tree,tree->data,tree->data->init_len);
7597  Make_Tree_4_Lk(tree,tree->data,tree->data->init_len); 
7598  tree->triplet_struct = Make_Triplet_Struct(tree->mod);
7599  Init_Triplet_Struct(tree->triplet_struct);
7600  Make_Spr_List(tree);
7601  Make_Best_Spr(tree);   
7602
7603  if(tree->is_mixt_tree) MIXT_Prepare_Tree_For_Lk(tree);
7604}
7605
7606//////////////////////////////////////////////////////////////
7607//////////////////////////////////////////////////////////////
7608
7609void Find_Common_Tips(t_tree *tree1, t_tree *tree2)
7610{
7611  int i,j;
7612
7613  For(i,tree1->n_otu) tree1->a_nodes[i]->common = 0;
7614  For(i,tree2->n_otu) tree2->a_nodes[i]->common = 0;
7615
7616  For(i,tree1->n_otu)
7617    {
7618      For(j,tree2->n_otu)
7619        {
7620          if(!strcmp(tree1->a_nodes[i]->name,tree2->a_nodes[j]->name))
7621            {
7622              tree1->a_nodes[i]->common = 1;
7623              tree2->a_nodes[j]->common = 1;
7624              break;
7625            }
7626        }
7627    }
7628}
7629
7630//////////////////////////////////////////////////////////////
7631//////////////////////////////////////////////////////////////
7632
7633phydbl Get_Tree_Size(t_tree *tree)
7634{
7635  int i;
7636  phydbl tree_size;
7637
7638  tree_size = 0.0;
7639  For(i,2*tree->n_otu-3) tree_size += tree->a_edges[i]->l->v;
7640
7641  if(tree->n_root)
7642    {
7643      tree_size += tree->n_root->b[1]->l->v;
7644      tree_size += tree->n_root->b[2]->l->v;
7645    }
7646
7647
7648/*   For(i,2*tree->n_otu-3)  */
7649/*     tree_size +=  */
7650/*     FABS(tree->rates->nd_t[tree->a_edges[i]->left->num] -  */
7651/*       tree->rates->nd_t[tree->a_edges[i]->rght->num]); */
7652
7653  tree->size = tree_size;
7654  return tree_size;
7655}
7656
7657//////////////////////////////////////////////////////////////
7658//////////////////////////////////////////////////////////////
7659
7660
7661void Dist_To_Root_Pre(t_node *a, t_node *d, t_edge *b, t_tree *tree)
7662{
7663  int i;
7664
7665  if(b) d->dist_to_root = a->dist_to_root + b->l->v;
7666  /* if(b) d->dist_to_root = a->dist_to_root + tree->rates->cur_l[d->num]; */
7667
7668  if(d->tax) return;
7669  else
7670    {
7671      For(i,3)
7672        if((d->v[i] != a) && (d->b[i] != tree->e_root)) 
7673          Dist_To_Root_Pre(d,d->v[i],d->b[i],tree);
7674    }
7675}
7676
7677//////////////////////////////////////////////////////////////
7678//////////////////////////////////////////////////////////////
7679
7680
7681void Dist_To_Root(t_node *n_root, t_tree *tree)
7682{ 
7683  /* n_root->v[2]->dist_to_root = tree->rates->cur_l[n_root->v[2]->num]; */
7684  /* n_root->v[1]->dist_to_root = tree->rates->cur_l[n_root->v[1]->num]; */
7685  n_root->v[2]->dist_to_root = tree->e_root->l->v * tree->n_root_pos;
7686  n_root->v[1]->dist_to_root = tree->e_root->l->v * (1. - tree->n_root_pos);
7687  Dist_To_Root_Pre(n_root,n_root->v[2],NULL,tree);
7688  Dist_To_Root_Pre(n_root,n_root->v[1],NULL,tree);
7689}
7690
7691//////////////////////////////////////////////////////////////
7692//////////////////////////////////////////////////////////////
7693
7694/* 'Borrowed' fromn libgen */
7695char *Basename(char *path)
7696{
7697  char *p;
7698 
7699  if( path == NULL || *path == '\0' ) return ".";
7700
7701  p = path + strlen(path) - 1;
7702 
7703  while( *p == '/' ) 
7704    {
7705      if( p == path ) return path;
7706      *p-- = '\0';
7707    }
7708
7709  while( p >= path && *p != '/' ) p--;
7710
7711  return p + 1;
7712}
7713
7714//////////////////////////////////////////////////////////////
7715//////////////////////////////////////////////////////////////
7716
7717/* Find the Last Common Ancestor of n1 and n2 */
7718t_node *Find_Lca_Pair_Of_Nodes(t_node *n1, t_node *n2, t_tree *tree)
7719{
7720  t_node **list1, **list2, *lca;
7721  int size1, size2;
7722
7723  if(!tree->n_root)
7724    {
7725      PhyML_Printf("\n. The tree must be rooted in this function.");
7726      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
7727      Warn_And_Exit("");
7728    }
7729
7730  list1 = (t_node **)mCalloc(2*tree->n_otu-1,sizeof(t_node *));
7731  list2 = (t_node **)mCalloc(2*tree->n_otu-1,sizeof(t_node *));
7732
7733  Get_List_Of_Ancestors(n1,list1,&size1,tree);
7734  Get_List_Of_Ancestors(n2,list2,&size2,tree);
7735
7736  while(list1[size1] == list2[size2])
7737    {
7738      size1--;
7739      size2--;
7740
7741      if(size1 < 0 || size2 < 0) break;
7742    }
7743 
7744  lca = list1[size1+1];
7745
7746  Free(list1);
7747  Free(list2);
7748
7749  return lca;
7750}
7751
7752//////////////////////////////////////////////////////////////
7753//////////////////////////////////////////////////////////////
7754
7755/* Find the Last Common Ancestor of all the nodes in node_list */
7756t_node *Find_Lca_Clade(t_node **node_list, int node_list_size, t_tree *tree)
7757{
7758  t_node ***list, *lca;
7759  int *size;
7760  int i;
7761
7762  if(!tree->n_root)
7763    {
7764      PhyML_Printf("\n== The tree must be rooted in this function.");
7765      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
7766      Warn_And_Exit("");
7767    }
7768
7769  list = (t_node ***)mCalloc(node_list_size,sizeof(t_node **));
7770  For(i,node_list_size) list[i] = (t_node **)mCalloc(2*tree->n_otu-1,sizeof(t_node *));
7771  size = (int *)mCalloc(node_list_size,sizeof(int));
7772
7773  For(i,node_list_size) 
7774    {
7775      if(!Get_List_Of_Ancestors(node_list[i],list[i],size+i,tree))
7776        {
7777          For(i,node_list_size) PhyML_Printf("\n== %s",node_list[i]->name);
7778          PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
7779          Exit("\n");
7780        }
7781    }
7782  do
7783    {
7784      For(i,node_list_size-1) 
7785        if(list[i][size[i]] != list[i+1][size[i+1]])
7786          break;
7787     
7788      if(i != node_list_size-1) break;
7789     
7790      For(i,node_list_size) 
7791        {
7792          size[i]--; 
7793          if(size[i] == 1) break; // We have reached the tip corresponding to node_list[i]
7794        }
7795
7796      if(node_list_size == 1) break;
7797
7798    }while(1);
7799 
7800 
7801  lca = list[0][size[0]+1];
7802 
7803  For(i,node_list_size) Free(list[i]);
7804  Free(list);
7805  Free(size);
7806   
7807  return lca;
7808}
7809
7810//////////////////////////////////////////////////////////////
7811//////////////////////////////////////////////////////////////
7812
7813/* Returns the list of the ancestors of ref_t_node from ref_t_node to the root included */
7814int Get_List_Of_Ancestors(t_node *ref_node, t_node **list, int *size, t_tree *tree)
7815{
7816  t_node *n;
7817
7818  *size = 1;
7819  n = ref_node;
7820  list[0] = n;
7821
7822  if(!n)
7823    {
7824      PhyML_Printf("\n== There seems to be a problem with the calibration file.\n");
7825      return 0;
7826    }
7827 
7828  while(n != tree->n_root)
7829    {
7830      n = n->anc;
7831      if(!n)
7832        {
7833          PhyML_Printf("\n== n->anc has not been set properly (call Update_Ancestors first...)\n");
7834          return 0;
7835        }
7836      *size = *size+1;
7837      list[*size] = n;
7838    }
7839  return 1;
7840}
7841
7842//////////////////////////////////////////////////////////////
7843//////////////////////////////////////////////////////////////
7844
7845
7846int Edge_Num_To_Node_Num(int edge_num, t_tree *tree)
7847{
7848  int node_num;
7849  t_edge *b;
7850
7851  b = tree->a_edges[edge_num];
7852
7853  node_num = (b->left == b->rght->anc)?(b->rght->num):(b->left->num);
7854 
7855  return node_num;
7856}
7857
7858//////////////////////////////////////////////////////////////
7859//////////////////////////////////////////////////////////////
7860
7861void Time_To_Branch(t_tree *tree)
7862{
7863  Time_To_Branch_Pre(tree->n_root,tree->n_root->v[2],tree);
7864  Time_To_Branch_Pre(tree->n_root,tree->n_root->v[1],tree);
7865  tree->n_root->l[1] = tree->rates->nd_t[tree->n_root->v[1]->num] - tree->rates->nd_t[tree->n_root->num];
7866  tree->n_root->l[2] = tree->rates->nd_t[tree->n_root->v[1]->num] - tree->rates->nd_t[tree->n_root->num];
7867  tree->e_root->l->v = tree->n_root->l[1] + tree->n_root->l[2]; 
7868
7869}
7870
7871//////////////////////////////////////////////////////////////
7872//////////////////////////////////////////////////////////////
7873
7874
7875void Time_To_Branch_Pre(t_node *a, t_node *d, t_tree *tree)
7876{
7877  int i;
7878
7879  /* tree->rates->cur_l[d->num] = FABS(tree->rates->nd_t[d->num] - tree->rates->nd_t[a->num]); */
7880  tree->rates->cur_l[d->num] = tree->rates->nd_t[d->num] - tree->rates->nd_t[a->num];
7881
7882  if(d->tax) return;
7883  else
7884    {
7885      For(i,3)
7886        if((d->v[i] != a) && (d->b[i] != tree->e_root))
7887          Time_To_Branch_Pre(d,d->v[i],tree);     
7888    }
7889}
7890
7891//////////////////////////////////////////////////////////////
7892//////////////////////////////////////////////////////////////
7893
7894//////////////////////////////////////////////////////////////
7895//////////////////////////////////////////////////////////////
7896
7897// Assume an ultrametric tree.
7898void Branch_To_Time(t_tree *tree)
7899{
7900  Branch_To_Time_Pre(tree->n_root,tree->n_root->v[2],tree);
7901  Branch_To_Time_Pre(tree->n_root,tree->n_root->v[1],tree);
7902
7903  tree->rates->nd_t[tree->n_root->num] = 
7904    tree->rates->nd_t[tree->n_root->v[1]->num] -
7905    tree->n_root->l[1];
7906}
7907
7908//////////////////////////////////////////////////////////////
7909//////////////////////////////////////////////////////////////
7910
7911void Branch_To_Time_Pre(t_node *a, t_node *d, t_tree *tree)
7912{
7913  int i;
7914 
7915  if(d->tax) 
7916    {
7917      tree->rates->nd_t[d->num] = 0.0;
7918      return;
7919    }
7920  else
7921    {
7922      For(i,3)
7923        if((d->v[i] != a) && (d->b[i] != tree->e_root))
7924          {
7925            Branch_To_Time_Pre(d,d->v[i],tree);           
7926          }             
7927
7928      For(i,3)
7929        if((d->v[i] != a) && (d->b[i] != tree->e_root))
7930          {
7931            tree->rates->nd_t[d->num] = tree->rates->nd_t[d->v[i]->num] - d->b[i]->l->v;
7932            break;
7933          }
7934    }
7935}
7936
7937//////////////////////////////////////////////////////////////
7938//////////////////////////////////////////////////////////////
7939
7940
7941void Branch_Lengths_To_Rate_Lengths(t_tree *tree)
7942{
7943  Branch_Lengths_To_Rate_Lengths_Pre(tree->n_root,tree->n_root->v[2],tree);
7944  Branch_Lengths_To_Rate_Lengths_Pre(tree->n_root,tree->n_root->v[1],tree);
7945}
7946
7947//////////////////////////////////////////////////////////////
7948//////////////////////////////////////////////////////////////
7949
7950
7951void Branch_Lengths_To_Rate_Lengths_Pre(t_node *a, t_node *d, t_tree *tree)
7952{
7953  int i;
7954
7955  tree->rates->cur_l[d->num] = 
7956    tree->rates->br_r[d->num] * 
7957    tree->rates->clock_r *
7958    tree->rates->norm_fact;
7959
7960  if(d->tax) return;
7961  else
7962    {
7963      For(i,3)
7964        if((d->v[i] != a) && (d->b[i] != tree->e_root))
7965          Branch_Lengths_To_Rate_Lengths_Pre(d,d->v[i],tree);     
7966    }
7967}
7968
7969//////////////////////////////////////////////////////////////
7970//////////////////////////////////////////////////////////////
7971
7972
7973int Find_Clade(char **tax_name_list, int list_size, t_tree *tree)
7974{
7975  int *tax_num_list;
7976  t_node **tax_node_list;
7977  int i,j;
7978  int n_matches;
7979  t_node *lca;
7980
7981  tax_num_list = (int *)mCalloc(list_size,sizeof(int));
7982  tax_node_list = (t_node **)mCalloc(list_size,sizeof(t_node *));
7983
7984  For(i,list_size) tax_num_list[i] = -1;
7985 
7986  n_matches = 0;
7987
7988  For(i,list_size)
7989    {
7990      For(j,tree->n_otu)
7991        {
7992          if(!strcmp(tax_name_list[i],tree->a_nodes[j]->name))
7993            {
7994              tax_num_list[i] = tree->a_nodes[j]->num;
7995              tax_node_list[i] = tree->a_nodes[j];
7996              n_matches++;
7997              break;
7998            }
7999        }
8000      if(j == tree->n_otu)
8001        {
8002          PhyML_Printf("\n== Problem with the calibration file.");
8003          PhyML_Printf("\n== Could not find taxon with name '%s' in the sequence or tree file.",tax_name_list[i]);
8004          Exit("\n");
8005        }
8006    }
8007
8008  lca = Find_Lca_Clade(tax_node_list,n_matches,tree);
8009  if(lca) return lca->num;
8010  else    return -1;
8011
8012/*   if(list_size == tree->n_otu) /\* Root node *\/ */
8013/*     { */
8014/*       int i,j; */
8015/*       int score; */
8016     
8017/*       score = 0; */
8018/*       For(i,list_size) */
8019/*      { */
8020/*        For(j,tree->n_otu) */
8021/*          { */
8022/* /\*        if(!strcmp(tax_name_list[i],tree->a_nodes[j]->name)) score++; *\/ */
8023/*            if(tax_num_list[i] == tree->a_nodes[j]->num) score++; */
8024/*          } */
8025/*      } */
8026
8027/*       Free(tax_num_list); */
8028/*       if(score == tree->n_otu) return tree->n_root->num; */
8029/*       else return -1; */
8030/*     } */
8031/*   else */
8032/*     { */
8033/*       int num; */
8034/*       num = -1; */
8035/*       Free_Bip(tree); */
8036/*       Alloc_Bip(tree); */
8037/*       Get_Bip(tree->a_nodes[0],tree->a_nodes[0]->v[0],tree); */
8038/*       Find_Clade_Pre(tree->n_root,tree->n_root->v[2],tax_num_list,list_size,&num,tree); */
8039/*       Find_Clade_Pre(tree->n_root,tree->n_root->v[1],tax_num_list,list_size,&num,tree); */
8040/*       Free(tax_num_list); */
8041/*       return num; */
8042/*     } */
8043
8044  Free(tax_node_list);
8045  Free(tax_num_list);
8046  return -1;
8047}
8048
8049//////////////////////////////////////////////////////////////
8050//////////////////////////////////////////////////////////////
8051
8052
8053void Find_Clade_Pre(t_node *a, t_node *d, int *tax_num_list, int list_size, int *num, t_tree *tree)
8054{
8055  int i,j,k;
8056  int score;
8057 
8058 
8059  For(i,3)
8060    if((d->v[i] == a) || (d->b[i] == tree->e_root))
8061      {
8062        if(list_size == d->bip_size[i])
8063          {
8064            score = 0;
8065            For(j,d->bip_size[i])
8066              {
8067                For(k,list_size)
8068                  {
8069                    if(tax_num_list[k] == d->bip_node[i][j]->num)
8070                      {
8071                        score++;
8072                        break;
8073                      }
8074                  }
8075              }
8076            if(score == list_size) *num = d->num;
8077          }
8078        break;
8079      }
8080
8081  if(d->tax) return;
8082  else
8083    For(i,3)
8084      if((d->v[i] != a) && (d->b[i] != tree->e_root))
8085        Find_Clade_Pre(d,d->v[i],tax_num_list,list_size,num,tree);
8086}
8087
8088//////////////////////////////////////////////////////////////
8089//////////////////////////////////////////////////////////////
8090
8091t_edge *Find_Root_Edge(FILE *fp_input_tree, t_tree *tree)
8092{
8093  char **subs;
8094  int degree;
8095  int i,j;
8096  t_node *left, *rght;
8097  int l_r, r_l;
8098  int score;
8099  char *line;
8100  char c;
8101  t_edge *root_edge;
8102
8103  line = (char *)mCalloc(T_MAX_LINE,sizeof(char));
8104
8105  rewind(fp_input_tree);
8106
8107  do c=fgetc(fp_input_tree);
8108  while((c != '(') && (c != EOF));
8109 
8110  if(c==EOF)
8111    {
8112      Free(line);
8113      return NULL;
8114    }
8115 
8116  i=0;
8117  for(;;)
8118    {
8119      if((c == ' ') || (c == '\n'))
8120        {
8121          c=fgetc(fp_input_tree);
8122          if(c==EOF) break;
8123          else continue;
8124        }
8125     
8126      line[i]=c;
8127      i++;
8128      c=fgetc(fp_input_tree);
8129      if(c==EOF || c==';') break;
8130    }
8131 
8132
8133  Free_Bip(tree);
8134  Alloc_Bip(tree);
8135  Get_Bip(tree->a_nodes[0],tree->a_nodes[0]->v[0],tree);
8136
8137  subs = Sub_Trees(line,&degree);
8138  Clean_Multifurcation(subs,degree,3);
8139  if(degree != 2) 
8140    {
8141      PhyML_Printf("\n== The tree does not seem to be rooted...");
8142      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
8143      Warn_And_Exit("");
8144    }
8145
8146  left = rght = NULL;
8147  l_r = r_l = -1;
8148
8149  For(i,2*tree->n_otu-3)
8150    {
8151      left = tree->a_edges[i]->left;
8152      rght = tree->a_edges[i]->rght;
8153      l_r  = tree->a_edges[i]->l_r;
8154      r_l  = tree->a_edges[i]->r_l;
8155     
8156      score = 0;
8157      For(j,left->bip_size[l_r]) if(strstr(subs[1],left->bip_node[l_r][j]->name)) score++;
8158      if(score == left->bip_size[l_r]) break;
8159
8160      score = 0;
8161      For(j,rght->bip_size[r_l]) if(strstr(subs[1],rght->bip_node[r_l][j]->name)) score++;
8162      if(score == rght->bip_size[r_l]) break;
8163    }
8164
8165  root_edge = tree->a_edges[i];
8166
8167  For(i,NODE_DEG_MAX) Free(subs[i]);
8168  Free(subs);
8169  Free(line);
8170
8171  if(i == 2*tree->n_otu-3)
8172    {
8173      PhyML_Printf("\n== Could not find the root edge...");
8174      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
8175      Warn_And_Exit("");
8176    }
8177 
8178  return root_edge;
8179}
8180
8181//////////////////////////////////////////////////////////////
8182//////////////////////////////////////////////////////////////
8183
8184void Copy_Tree_Topology_With_Labels(t_tree *ori, t_tree *cpy)
8185{
8186  int i,j;
8187
8188  For(i,2*ori->n_otu-2)
8189    {
8190      For(j,3)
8191        {
8192          if(ori->a_nodes[i]->v[j])
8193            {
8194              cpy->a_nodes[i]->v[j] = cpy->a_nodes[ori->a_nodes[i]->v[j]->num];
8195              cpy->a_nodes[i]->l[j] = ori->a_nodes[i]->l[j];
8196            }
8197          else
8198            cpy->a_nodes[i]->v[j] = NULL;
8199        }
8200      cpy->a_nodes[i]->num = ori->a_nodes[i]->num;
8201      cpy->a_nodes[i]->tax = 0;
8202    }
8203
8204  For(i,2*ori->n_otu-3)
8205    {
8206      cpy->a_edges[i]->l->v = ori->a_edges[i]->l->v;
8207    }
8208
8209  For(i,ori->n_otu)
8210    {
8211      cpy->a_nodes[i]->tax = 1;
8212      strcpy(cpy->a_nodes[i]->name,ori->a_nodes[i]->name);
8213    }
8214
8215}
8216
8217//////////////////////////////////////////////////////////////
8218//////////////////////////////////////////////////////////////
8219
8220void Set_Model_Name(t_mod *mod)
8221{
8222  switch(mod->whichmodel)
8223    {
8224    case JC69:
8225      {
8226        strcpy(mod->modelname->s, "JC69");
8227        break;
8228      }
8229    case K80:
8230      {
8231        strcpy(mod->modelname->s, "K80");
8232        break;
8233      }
8234    case F81:
8235      {
8236        strcpy(mod->modelname->s, "F81");
8237        break;
8238      }
8239    case HKY85:
8240      {
8241        strcpy(mod->modelname->s, "HKY85");
8242        break;
8243      }
8244    case F84:
8245      {
8246        strcpy(mod->modelname->s, "F84");
8247        break;
8248      }
8249    case TN93:
8250      {
8251        strcpy(mod->modelname->s, "TN93");
8252        break;
8253      }
8254    case GTR:
8255      {
8256        strcpy(mod->modelname->s, "GTR");
8257        break;
8258      }
8259    case CUSTOM:
8260      {
8261        strcpy(mod->modelname->s, "Custom");
8262        break;
8263      }
8264    case DAYHOFF:
8265      {
8266        strcpy(mod->modelname->s, "Dayhoff");
8267        break;
8268      }
8269    case JTT:
8270      {
8271        strcpy(mod->modelname->s, "JTT");
8272        break;
8273      }
8274    case MTREV:
8275      {
8276        strcpy(mod->modelname->s, "MtREV");
8277        break;
8278      }
8279    case LG:
8280      {
8281        strcpy(mod->modelname->s, "LG");
8282        break;
8283      }
8284    case WAG:
8285      {
8286        strcpy(mod->modelname->s, "WAG");
8287        break;
8288      }
8289    case DCMUT:
8290      {
8291        strcpy(mod->modelname->s, "DCMut");
8292        break;
8293      }
8294    case RTREV:
8295      {
8296        strcpy(mod->modelname->s, "RtREV");
8297        break;
8298      }
8299    case CPREV:
8300      {
8301        strcpy(mod->modelname->s, "CpREV");
8302        break;
8303      }
8304    case VT:
8305      {
8306        strcpy(mod->modelname->s, "VT");
8307        break;
8308      }
8309    case BLOSUM62:
8310      {
8311        strcpy(mod->modelname->s, "Blosum62");
8312        break;
8313      }
8314    case MTMAM:
8315      {
8316        strcpy(mod->modelname->s, "MtMam");
8317        break;
8318      }
8319    case MTART:
8320      {
8321        strcpy(mod->modelname->s, "MtArt");
8322        break;
8323      }
8324    case HIVW:
8325      {
8326        strcpy(mod->modelname->s, "HIVw");
8327        break;
8328      }
8329    case HIVB:
8330      {
8331        strcpy(mod->modelname->s, "HIVb");
8332        break;
8333      }
8334    case CUSTOMAA:
8335      {
8336        strcpy(mod->modelname->s, "Custom");
8337        break;
8338      }
8339    default:
8340      {
8341        PhyML_Printf("\n== Unknown model name.\n");
8342        PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
8343        Warn_And_Exit("");
8344        break;
8345      }   
8346    }
8347}
8348
8349//////////////////////////////////////////////////////////////
8350//////////////////////////////////////////////////////////////
8351
8352
8353void Adjust_Min_Diff_Lk(t_tree *tree)
8354{
8355  int exponent;
8356 
8357  exponent = (int)FLOOR(log10(FABS(tree->c_lnL)));
8358
8359  if(sizeof(phydbl) == 4)
8360    {
8361      tree->mod->s_opt->min_diff_lk_local = POW(10.,exponent - FLT_DIG + 1);
8362      tree->mod->s_opt->min_diff_lk_local  = tree->mod->s_opt->min_diff_lk_local;
8363      tree->mod->s_opt->min_diff_lk_move   = tree->mod->s_opt->min_diff_lk_local;
8364    }
8365/*   PhyML_Printf("\n. Exponent = %d Precision = %E DIG = %d",exponent,tree->mod->s_opt->min_diff_lk_local,FLT_DIG); */
8366}
8367
8368//////////////////////////////////////////////////////////////
8369//////////////////////////////////////////////////////////////
8370
8371
8372/*!
8373  tree->a_nodes[i]->name is initially a number. It is translated into
8374  a string of characters using the names provided in the tax_name
8375  array.
8376 */
8377void Translate_Tax_Names(char **tax_names, t_tree *tree)
8378{
8379  int i;
8380  int tax_num;
8381
8382  For(i,tree->n_otu)
8383    {
8384      tax_num = strtol(tree->a_nodes[i]->name,NULL,10);
8385      tree->a_nodes[i]->name = tax_names[tax_num-1];
8386    }
8387}
8388
8389//////////////////////////////////////////////////////////////
8390//////////////////////////////////////////////////////////////
8391
8392
8393/*!
8394  Skip coment in NEXUS file.
8395 */
8396void Skip_Comment(FILE *fp)
8397{
8398  int in_comment;
8399  char c;
8400
8401  in_comment = 1;
8402  do
8403    {
8404      c = fgetc(fp);
8405      if(c == EOF) break;
8406      if(c == '[')      in_comment++;
8407      else if(c == ']') in_comment--;
8408    }
8409  while(in_comment);
8410}
8411
8412//////////////////////////////////////////////////////////////
8413//////////////////////////////////////////////////////////////
8414
8415/*!
8416  Determine the most appropriate position of the root if outgroup taxa are specified.
8417 */
8418
8419void Get_Best_Root_Position(t_tree *tree)
8420{
8421  int i,j;
8422  phydbl eps;
8423  phydbl s, s_max;
8424  t_edge *best_edge;
8425  int has_outgrp;
8426 
8427  best_edge = NULL;
8428
8429  if(tree->n_root)
8430    {
8431      PhyML_Printf("\n== Tree already has a root.");
8432      PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);
8433      Warn_And_Exit("");
8434    }
8435
8436  if(strstr(tree->a_nodes[0]->name,"*"))
8437    {
8438      /* PhyML_Printf("\n. Found outgroup taxon: %s",tree->a_nodes[0]->name); */
8439      tree->a_nodes[0]->s_ingrp[0]  = 0;
8440      tree->a_nodes[0]->s_outgrp[0] = 1;
8441    }
8442  else
8443    {
8444      tree->a_nodes[0]->s_ingrp[0]  = 1;
8445      tree->a_nodes[0]->s_outgrp[0] = 0;
8446    }
8447
8448  has_outgrp = NO;
8449  Get_Best_Root_Position_Post(tree->a_nodes[0],tree->a_nodes[0]->v[0],&has_outgrp,tree); 
8450  Get_Best_Root_Position_Pre(tree->a_nodes[0],tree->a_nodes[0]->v[0],tree); 
8451
8452  if(has_outgrp == YES)
8453    {
8454      eps = 1.E-10;
8455      s = s_max = 0.0;
8456      For(i,2*tree->n_otu-2)
8457        {
8458          For(j,3)
8459            {
8460              s = (tree->a_nodes[i]->s_outgrp[j]+eps) / (tree->a_nodes[i]->s_ingrp[j] + eps) ;
8461              /* printf("\n. [%d %d] %d %d",i,j,tree->a_nodes[i]->s_outgrp[j],tree->a_nodes[i]->s_ingrp[j]); */
8462              if(s > s_max) 
8463                {
8464                  s_max = s;
8465                  best_edge = tree->a_nodes[i]->b[j];
8466                }
8467            }
8468        }
8469     
8470      Add_Root(best_edge,tree);
8471    }
8472}
8473
8474//////////////////////////////////////////////////////////////
8475//////////////////////////////////////////////////////////////
8476
8477
8478/*!
8479  Determine the most appropriate position of the root if outgroup taxa are specified.
8480  Post-traversal.
8481 */
8482void Get_Best_Root_Position_Post(t_node *a, t_node *d, int *has_outgrp, t_tree *tree)
8483{
8484  if(d->tax) 
8485    {
8486      if(strstr(d->name,"*"))
8487        {
8488          *has_outgrp = YES;
8489          /* PhyML_Printf("\n. Found outgroup taxon: %s",d->name); */
8490          d->s_ingrp[0]  = 0;
8491          d->s_outgrp[0] = 1;
8492        }
8493      else
8494        {
8495          d->s_ingrp[0]  = 1;
8496          d->s_outgrp[0] = 0;
8497        }
8498      return;
8499    }
8500  else
8501    {
8502      int i;
8503
8504      For(i,3)
8505        if(d->v[i] != a && (d->b[i] != tree->e_root))
8506          Get_Best_Root_Position_Post(d,d->v[i],has_outgrp,tree);
8507
8508      Get_OutIn_Scores(a,d);
8509
8510    }
8511}
8512
8513//////////////////////////////////////////////////////////////
8514//////////////////////////////////////////////////////////////
8515
8516
8517/*!
8518  Determine the most appropriate position of the root if outgroup taxa are specified.
8519  Pre-traversal.
8520 */
8521void Get_Best_Root_Position_Pre(t_node *a, t_node *d, t_tree *tree)
8522{
8523  if(d->tax) 
8524    {
8525      return;
8526    }
8527  else
8528    {
8529      int i;
8530
8531      For(i,3)
8532        if(d->v[i] != a && (d->b[i] != tree->e_root))
8533          {
8534            Get_OutIn_Scores(d->v[i],d);
8535            Get_Best_Root_Position_Pre(d,d->v[i],tree);
8536          }
8537    }
8538}
8539
8540//////////////////////////////////////////////////////////////
8541//////////////////////////////////////////////////////////////
8542
8543
8544/*!
8545  Determine the most appropriate position of the root if outgroup taxa are specified.
8546  Core.
8547 */
8548void Get_OutIn_Scores(t_node *a, t_node *d)
8549{
8550  int i,d_v1,d_v2,v1_d,v2_d,d_a;
8551 
8552  d_a = v1_d = v2_d = -1;
8553  d_v1 = d_v2 = -1;
8554  For(i,3)
8555    {
8556      if(d->v[i] != a)
8557        {
8558          if(d_v1 < 0) d_v1 = i;
8559          else         d_v2 = i;
8560        }
8561    }
8562 
8563  For(i,3) if(d->v[i] == a) { d_a = i; break; }
8564  For(i,3) if(d->v[d_v1]->v[i] == d) { v1_d = i; break; }
8565  For(i,3) if(d->v[d_v2]->v[i] == d) { v2_d = i; break; }
8566 
8567  d->s_ingrp[d_a] = 
8568    d->v[d_v1]->s_ingrp[v1_d] +
8569    d->v[d_v2]->s_ingrp[v2_d] ;
8570 
8571  d->s_outgrp[d_a] = 
8572    d->v[d_v1]->s_outgrp[v1_d] +
8573    d->v[d_v2]->s_outgrp[v2_d] ;
8574}
8575
8576//////////////////////////////////////////////////////////////
8577//////////////////////////////////////////////////////////////
8578
8579int Check_Sequence_Name(char *s)
8580{
8581  int i;
8582  /* if(rindex(s,':')) */
8583  For(i,strlen(s))
8584    {
8585      if(s[i] == ':')
8586        {
8587          PhyML_Printf("\n== Character ':' is not permitted in sequence name (%s).",s);
8588          PhyML_Printf("\n== Err. in file %s at line %d",__FILE__,__LINE__);
8589          Warn_And_Exit("");
8590        }
8591    }
8592  /* if(rindex(s,',')) */
8593  For(i,strlen(s))
8594    {
8595      if(s[i] == ',')
8596        {
8597          PhyML_Printf("\n== Character ',' is not permitted in sequence name (%s).",s);
8598          PhyML_Printf("\n== Err in file %s at line %d",__FILE__,__LINE__);
8599          Warn_And_Exit("");
8600        }
8601    }
8602  /* if(rindex(s,' ')) */
8603  For(i,strlen(s))
8604    {
8605      if(s[i] == ' ')
8606        {
8607          PhyML_Printf("\n== Character ' ' is not permitted in sequence name (%s).",s);
8608          PhyML_Printf("\n== Err in file %s at line %d",__FILE__,__LINE__);
8609          Warn_And_Exit("");
8610        }
8611    }
8612
8613  return 1;
8614}
8615
8616//////////////////////////////////////////////////////////////
8617//////////////////////////////////////////////////////////////
8618
8619
8620int Scale_Subtree_Height(t_node *a, phydbl K, phydbl floor, int *n_nodes, t_tree *tree)
8621{
8622  phydbl new_height;
8623
8624  *n_nodes = 0;
8625 
8626  new_height = .0;
8627
8628
8629  if(!(tree->rates->nd_t[a->num] > floor))
8630    new_height = K*(tree->rates->nd_t[a->num]-floor)+floor;
8631 
8632  if(a == tree->n_root)
8633    {
8634      tree->rates->nd_t[tree->n_root->num] = new_height;
8635      *n_nodes = 1;
8636
8637      Scale_Node_Heights_Post(tree->n_root,tree->n_root->v[2],K,floor,n_nodes,tree);
8638      Scale_Node_Heights_Post(tree->n_root,tree->n_root->v[1],K,floor,n_nodes,tree);
8639    }
8640  else
8641    {
8642      int i;
8643     
8644      if(new_height < tree->rates->nd_t[a->anc->num]) return 0;
8645      else 
8646        {
8647          tree->rates->nd_t[a->num] = new_height;
8648          *n_nodes = 1;
8649        }
8650
8651      For(i,3)
8652        if(a->v[i] != a->anc && a->b[i] != tree->e_root)
8653          {
8654            Scale_Node_Heights_Post(a,a->v[i],K,floor,n_nodes,tree);
8655          }
8656    }
8657 
8658  return 1;
8659}
8660
8661//////////////////////////////////////////////////////////////
8662//////////////////////////////////////////////////////////////
8663
8664
8665void Scale_Node_Heights_Post(t_node *a, t_node *d, phydbl K, phydbl floor, int *n_nodes, t_tree *tree)
8666{
8667  if(d == tree->n_root)
8668    {
8669      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
8670      Warn_And_Exit("");
8671    }
8672
8673  if(d->tax) 
8674    {     
8675      if(!(tree->rates->nd_t[d->num] > floor)) 
8676        {
8677          /* Scaling does not change the node height here
8678             but, in theory this tip is among the scaled
8679             nodes. Therefore needs to count it in for
8680             working out correct Hastings ratios
8681          */
8682          /* *n_nodes = *n_nodes+1; */
8683        }
8684      return;
8685    }
8686  else
8687    {
8688      int i;
8689     
8690      /* It is tempting to set floor = tree->rates->t_prior_max[d->num]; but
8691         it then becomes possible for nodes with different floor values
8692         to have their orders interverted (i.e., ancestor below descendant)
8693      */
8694      if(!(tree->rates->nd_t[d->num] > floor))
8695        {
8696          tree->rates->nd_t[d->num] = K*(tree->rates->nd_t[d->num]-floor)+floor;
8697          *n_nodes = *n_nodes+1;
8698        }
8699
8700      if(tree->rates->nd_t[d->num] < tree->rates->nd_t[a->num])
8701        {
8702          PhyML_Printf("\n. K = %f floor = %f t_prior_max(a) = %f t_prior_max(d) = %f a->t = %f d->t %f",
8703                       K,floor,tree->rates->t_prior_max[a->num],tree->rates->t_prior_max[d->num],
8704                       tree->rates->nd_t[a->num],tree->rates->nd_t[d->num]);
8705          PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
8706          Warn_And_Exit("");
8707        }
8708
8709      For(i,3)
8710        if(d->v[i] != a && d->b[i] != tree->e_root)
8711          Scale_Node_Heights_Post(d,d->v[i],K,floor,n_nodes,tree);
8712
8713    }
8714}
8715
8716//////////////////////////////////////////////////////////////
8717//////////////////////////////////////////////////////////////
8718
8719int Scale_Subtree_Rates(t_node *a, phydbl mult, int *n_nodes, t_tree *tree)
8720{
8721  int res;
8722  int i;
8723
8724  *n_nodes = 0;
8725  res      = 1;
8726
8727  if(a == tree->n_root)
8728    {
8729      res = Scale_Subtree_Rates_Post(a,a->v[2],mult,n_nodes,tree);
8730      if(res) res = Scale_Subtree_Rates_Post(a,a->v[1],mult,n_nodes,tree);
8731      return res;
8732    }
8733  else
8734    {
8735      For(i,3) if((a->v[i] != a->anc) && 
8736                  (a->b[i] != tree->e_root) && 
8737                  (res == 1)) res = Scale_Subtree_Rates_Post(a,a->v[i],mult,n_nodes,tree);
8738      return res;
8739    }
8740}
8741
8742//////////////////////////////////////////////////////////////
8743//////////////////////////////////////////////////////////////
8744
8745int Scale_Subtree_Rates_Post(t_node *a, t_node *d, phydbl mult, int *n_nodes, t_tree *tree)
8746{
8747
8748  if(tree->rates->model_log_rates == YES)
8749    {
8750      tree->rates->br_r[d->num] += LOG(mult);
8751    }
8752  else
8753    {
8754      tree->rates->br_r[d->num] *= mult;
8755    }
8756
8757  *n_nodes = *n_nodes+1;
8758
8759  if(tree->rates->br_r[d->num] < tree->rates->min_rate) return 0;
8760  if(tree->rates->br_r[d->num] > tree->rates->max_rate) return 0;
8761
8762  if(d->tax) return 1;
8763  else
8764    {
8765      int i,res;
8766
8767      res = 1;
8768      For(i,3)
8769        {
8770          if((d->v[i] != a) && 
8771             (d->b[i] != tree->e_root) && 
8772             (res == 1))
8773            {
8774              res = Scale_Subtree_Rates_Post(d,d->v[i],mult,n_nodes,tree);
8775            }
8776        }
8777      return res;
8778    }
8779}
8780
8781//////////////////////////////////////////////////////////////
8782//////////////////////////////////////////////////////////////
8783
8784//////////////////////////////////////////////////////////////
8785//////////////////////////////////////////////////////////////
8786
8787void Get_Node_Ranks(t_tree *tree)
8788{
8789  tree->n_root->rank = 1;
8790  Get_Node_Ranks_Pre(tree->n_root,tree->n_root->v[2],tree);
8791  Get_Node_Ranks_Pre(tree->n_root,tree->n_root->v[1],tree);
8792}
8793
8794//////////////////////////////////////////////////////////////
8795//////////////////////////////////////////////////////////////
8796
8797
8798void Get_Node_Ranks_Pre(t_node *a, t_node *d,t_tree *tree)
8799{
8800  d->rank = a->rank+1;
8801
8802  if(d->tax) return;
8803  else
8804    {
8805      int i;
8806     
8807      For(i,3)
8808        {
8809          if(d->v[i] != a && d->b[i] != tree->e_root)
8810            {
8811              Get_Node_Ranks_Pre(d,d->v[i],tree);
8812            }
8813        }
8814    }
8815}
8816
8817//////////////////////////////////////////////////////////////
8818//////////////////////////////////////////////////////////////
8819
8820void Log_Br_Len(t_tree *tree)
8821{
8822  int i;
8823  For(i,2*tree->n_otu-3) tree->a_edges[i]->l->v = LOG(tree->a_edges[i]->l->v);
8824}
8825
8826//////////////////////////////////////////////////////////////
8827//////////////////////////////////////////////////////////////
8828
8829phydbl Diff_Lk_Norm_At_Given_Edge(t_edge *b, t_tree *tree)
8830{
8831  int i,dim,err;
8832  phydbl lk_exact,lk_norm,sum;
8833
8834  Record_Br_Len(tree);
8835
8836  dim = 2*tree->n_otu-3;
8837  sum = 0.0;
8838
8839  For(i,tree->n_short_l)
8840    {
8841      b->l->v = tree->short_l[i];
8842
8843      lk_exact = Lk(b,tree);
8844      lk_norm = tree->norm_scale + Log_Dnorm(b->l->v,tree->rates->mean_l[b->num],
8845                                             tree->rates->cov_l[b->num*dim+b->num],&err);
8846
8847      if(err)
8848        {
8849          PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
8850          Warn_And_Exit("");
8851        }
8852
8853      sum += pow(lk_exact - lk_norm,2);     
8854    }
8855
8856  Restore_Br_Len(tree);
8857  Lk(b,tree);
8858
8859  return(sum);
8860}
8861
8862
8863//////////////////////////////////////////////////////////////
8864//////////////////////////////////////////////////////////////
8865
8866
8867void Adjust_Variances(t_tree *tree)
8868{
8869  int i;
8870  phydbl new_diff,curr_diff;
8871
8872  Make_Short_L(tree);
8873  For(i,tree->n_short_l)
8874    {
8875      tree->short_l[i] = tree->mod->l_min + i*(0.1 - tree->mod->l_min)/tree->n_short_l;
8876    }
8877 
8878
8879  For(i,2*tree->n_otu-3)
8880    {
8881      if(tree->a_edges[i]->l->v < 1.1*tree->mod->l_min)
8882        {
8883          tree->rates->mean_l[i]                     = -1.00;
8884          tree->rates->cov_l[i*(2*tree->n_otu-3)+i]  =  0.1;
8885          tree->norm_scale                           = -100;
8886         
8887         
8888          new_diff = curr_diff = 10.0;
8889          do
8890            {
8891              curr_diff = new_diff;
8892             
8893              Generic_Brent_Lk(&(tree->norm_scale),
8894                               -1E+6,
8895                               0.0,
8896                               1.E-10,
8897                               10000,
8898                               NO,
8899                               Wrap_Diff_Lk_Norm_At_Given_Edge,tree->a_edges[i],tree,NULL,NO);
8900             
8901              /*                      Generic_Brent_Lk(&(tree->rates->mean_l[0]), */
8902              /*                                       -100., */
8903              /*                                       10*tree->mod->l_min, */
8904              /*                                       1.E-3, */
8905              /*                                       10000, */
8906              /*                                       NO, */
8907              /*                                       Wrap_Diff_Lk_Norm_At_Given_Edge,tree->a_edges[0],tree,NULL); */
8908             
8909              Generic_Brent_Lk(&(tree->rates->cov_l[i*(2*tree->n_otu-3)+i]),
8910                               0.0,
8911                               10.0,
8912                               1.E-10,
8913                               10000,
8914                               NO,
8915                               Wrap_Diff_Lk_Norm_At_Given_Edge,tree->a_edges[i],tree,NULL,NO);
8916                 
8917              new_diff = Diff_Lk_Norm_At_Given_Edge(tree->a_edges[i],tree);
8918            }while(FABS(new_diff-curr_diff) > 1.E-3);
8919        }
8920    }
8921}
8922
8923//////////////////////////////////////////////////////////////
8924//////////////////////////////////////////////////////////////
8925
8926
8927phydbl Effective_Sample_Size(phydbl first_val, phydbl last_val, phydbl sum, phydbl sumsq, phydbl sumcurnext, int n)
8928{
8929  phydbl numerator,denom;
8930  phydbl mean;
8931  phydbl r;
8932
8933  mean = sum / n;
8934  denom = sumsq - n * POW(mean,2);
8935  numerator = sumcurnext - (n+1.)*POW(mean,2) + (first_val+last_val)*mean;
8936
8937  r = numerator/denom;
8938 
8939  return (phydbl)n * (1.-r)/(1.+r);
8940}
8941
8942//////////////////////////////////////////////////////////////
8943//////////////////////////////////////////////////////////////
8944
8945phydbl Rescale_Br_Len_Multiplier_Tree(t_tree *tree)
8946{
8947  int i;
8948
8949  if(tree->is_mixt_tree) 
8950    {
8951      MIXT_Rescale_Br_Len_Multiplier_Tree(tree);
8952      return(-1.);
8953    }
8954
8955  For(i,2*tree->n_otu-1) tree->a_edges[i]->l->v *= tree->mod->br_len_multiplier->v;
8956  return(-1.);
8957}
8958
8959//////////////////////////////////////////////////////////////
8960//////////////////////////////////////////////////////////////
8961
8962phydbl Unscale_Br_Len_Multiplier_Tree(t_tree *tree)
8963{
8964  int i;
8965 
8966  if(tree->is_mixt_tree) 
8967    {
8968      MIXT_Unscale_Br_Len_Multiplier_Tree(tree);
8969      return(-1.);
8970    }
8971
8972  For(i,2*tree->n_otu-1) tree->a_edges[i]->l->v /= tree->mod->br_len_multiplier->v;
8973  return(-1.);
8974}
8975
8976//////////////////////////////////////////////////////////////
8977//////////////////////////////////////////////////////////////
8978
8979
8980phydbl Reflect(phydbl x, phydbl l, phydbl u)
8981{
8982  int rounds;
8983  phydbl tmp;
8984  int k;
8985
8986  if(u < l)
8987    {
8988      tmp = u;
8989      u   = l;
8990      l   = tmp;
8991    }
8992
8993  if(x < l) x = x + 2.*(l - x);
8994 
8995  if(((x-u) > (u-l)) && (x > u))
8996    {
8997      k = (x - (2.*u-l))/(2.*(u-l));
8998      x = x - 2.*k*(u-l);
8999    }
9000
9001  rounds = 0;
9002  do
9003    {
9004      rounds++;
9005      /* printf("\n. l=%f u=%f x=%f",l,u,x); */
9006      if(x > u || x < l) 
9007        {
9008          if(x > u) x = x - 2.*(x - u);   
9009          else      x = x + 2.*(l - x);
9010        }
9011      else break;
9012      /* printf(" x'=%f",x); */
9013    }
9014  while(rounds < 100);
9015   
9016  if(rounds == 100 && (x > u || x < l))
9017    {
9018      PhyML_Printf("\n. u=%f l=%f x=%f",u,l,x);
9019      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
9020      Exit("\n");
9021    }
9022
9023  return x;
9024}
9025
9026//////////////////////////////////////////////////////////////
9027//////////////////////////////////////////////////////////////
9028
9029
9030int Are_Equal(phydbl a, phydbl b, phydbl eps)
9031{
9032  if(FABS(a-b) < eps) return TRUE; /* a==b */
9033  else return FALSE;
9034}
9035
9036//////////////////////////////////////////////////////////////
9037//////////////////////////////////////////////////////////////
9038
9039/* Returns 1 if small_tree is displayed by big_tree, 0 otherwise
9040   Does not account for the root positions, if any.
9041*/
9042int Check_Topo_Constraints(t_tree *big_tree, t_tree *small_tree)
9043{
9044  if(!small_tree) return 1;
9045 
9046  if(small_tree->n_otu < 4) return 1;
9047 
9048  if(small_tree->n_otu > big_tree->n_otu)
9049    {
9050      PhyML_Printf("\n");
9051      PhyML_Printf("\n. The tree that defines the topological constraints can not");
9052      PhyML_Printf("\n. display more taxa than %d",big_tree->n_otu);
9053      Exit("\n");
9054    }
9055 
9056  t_tree *big_tree_cpy;
9057  int diffs,i;
9058
9059  big_tree_cpy = Make_Tree_From_Scratch(big_tree->n_otu,NULL);
9060  Copy_Tree(big_tree,big_tree_cpy);
9061
9062  Prune_Tree(big_tree_cpy,small_tree);
9063 
9064  /* For(i,2*small_tree->n_otu-3) printf("\nz %d . %d . %d", */
9065  /*                                  big_tree->a_edges[i]->does_exist, */
9066  /*                                  big_tree_cpy->a_edges[i]->does_exist, */
9067  /*                                  small_tree->a_edges[i]->does_exist); */
9068
9069  Free_Bip(small_tree);
9070  Alloc_Bip(small_tree);
9071  Get_Bip(small_tree->a_nodes[0],small_tree->a_nodes[0]->v[0],small_tree);
9072
9073  Free_Bip(big_tree_cpy);
9074  Alloc_Bip(big_tree_cpy); 
9075  Match_Tip_Numbers(small_tree,big_tree_cpy);
9076  Get_Bip(big_tree_cpy->a_nodes[0],big_tree_cpy->a_nodes[0]->v[0],big_tree_cpy);
9077
9078  For(i,2*big_tree_cpy->n_otu-3) big_tree_cpy->a_edges[i]->bip_score = 0;
9079  For(i,2*small_tree->n_otu-3) small_tree->a_edges[i]->bip_score = 0;
9080
9081  diffs = Compare_Bip(small_tree,big_tree_cpy,YES);
9082
9083  /* printf("\n"); */
9084  /* printf("\n. %s",Write_Tree(big_tree_cpy,NO)); */
9085  /* printf("\n. %s",Write_Tree(small_tree,NO)); */
9086  /* printf("\n. diffs=%d",diffs); */
9087
9088  Free_Tree(big_tree_cpy);
9089
9090  t_tree *big_tree_cpy_bis;
9091  big_tree_cpy_bis = Make_Tree_From_Scratch(big_tree->n_otu,NULL);
9092  Copy_Tree(big_tree,big_tree_cpy_bis);
9093  Free_Tree(big_tree_cpy_bis);
9094
9095  if(diffs == 0) return 1; /* Constraint is satisfied */
9096  else           return 0;
9097}
9098
9099//////////////////////////////////////////////////////////////
9100//////////////////////////////////////////////////////////////
9101
9102void Prune_Tree(t_tree *big_tree, t_tree *small_tree)
9103{
9104  int i,j;
9105  int curr_ext_node, curr_int_node, curr_br, n_pruned_nodes;;
9106  t_node **pruned_nodes;
9107  t_edge **residual_edges;
9108
9109  pruned_nodes   = (t_node **)mCalloc(big_tree->n_otu,sizeof(t_node *));
9110  residual_edges = (t_edge **)mCalloc(big_tree->n_otu,sizeof(t_edge *));
9111 
9112  n_pruned_nodes = 0;
9113  For(i,big_tree->n_otu)
9114    {
9115      For(j,small_tree->n_otu)
9116        if(!strcmp(small_tree->a_nodes[j]->name,big_tree->a_nodes[i]->name))
9117          break;
9118     
9119      if(j == small_tree->n_otu)
9120        {
9121          Prune_Subtree(big_tree->a_nodes[i]->v[0],
9122                        big_tree->a_nodes[i],
9123                        NULL,&(residual_edges[n_pruned_nodes]),
9124                        big_tree);
9125
9126          pruned_nodes[n_pruned_nodes] = big_tree->a_nodes[i];
9127          n_pruned_nodes++;
9128        }
9129    }
9130
9131  if(!n_pruned_nodes)
9132    {
9133      Free(pruned_nodes);
9134      Free(residual_edges);
9135      return;
9136    }
9137
9138  Free(big_tree->t_dir);
9139
9140  big_tree->n_otu -= n_pruned_nodes;
9141
9142  curr_ext_node = 0;
9143  curr_int_node = big_tree->n_otu; 
9144  curr_br = 0;
9145  For(i,big_tree->n_otu+n_pruned_nodes)
9146    {
9147      For(j,n_pruned_nodes)
9148        if(!strcmp(pruned_nodes[j]->name,big_tree->a_nodes[i]->name))
9149          break;
9150     
9151      if(j == n_pruned_nodes) /* That t_node still belongs to the tree */
9152        {
9153          Reassign_Node_Nums(big_tree->a_nodes[i],big_tree->a_nodes[i]->v[0], 
9154                             &curr_ext_node,&curr_int_node,big_tree);
9155          break;
9156        }   
9157    }
9158
9159  Reassign_Edge_Nums(big_tree->a_nodes[0],big_tree->a_nodes[0]->v[0],&curr_br,big_tree);
9160
9161  big_tree->t_dir = (short int *)mCalloc((2*big_tree->n_otu-2)*(2*big_tree->n_otu-2),sizeof(short int));
9162
9163  For(i,n_pruned_nodes) 
9164    {
9165      Free_Edge(residual_edges[i]);
9166      Free_Edge(pruned_nodes[i]->b[0]);
9167      Free_Node(pruned_nodes[i]->v[0]);
9168      Free_Node(pruned_nodes[i]);
9169    }
9170
9171  Free(pruned_nodes);
9172  Free(residual_edges);
9173  big_tree->a_edges[2*big_tree->n_otu-3] = big_tree->a_edges[2*(big_tree->n_otu+n_pruned_nodes)-3];
9174  big_tree->a_nodes[2*big_tree->n_otu-2] = big_tree->a_nodes[2*(big_tree->n_otu+n_pruned_nodes)-2];
9175
9176}
9177
9178//////////////////////////////////////////////////////////////
9179//////////////////////////////////////////////////////////////
9180
9181/* For every node in small_tree, find which node in big_tree
9182   it corresponds to and initialize the variable match_node
9183   accordingly (vice versa for big_tree)
9184*/
9185void Match_Nodes_In_Small_Tree(t_tree *small_tree, t_tree *big_tree)
9186{
9187  int i,j,k,l,m,n,identical;
9188  int *score;
9189
9190  if(small_tree->n_otu > big_tree->n_otu)
9191    {
9192      PhyML_Printf("\n. small_tree->n_otu=%d big_tree->n_otu=%d",small_tree->n_otu,big_tree->n_otu);
9193      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
9194      Exit("\n");
9195    }
9196
9197  Free_Bip(big_tree);
9198  Alloc_Bip(big_tree); 
9199  Get_Bip(big_tree->a_nodes[0],big_tree->a_nodes[0]->v[0],big_tree);
9200
9201  Free_Bip(small_tree);
9202  Alloc_Bip(small_tree);
9203  Get_Bip(small_tree->a_nodes[0],small_tree->a_nodes[0]->v[0],small_tree);
9204
9205  if(!Check_Topo_Constraints(big_tree,small_tree))
9206    {
9207      PhyML_Printf("\n. small_tree and big_tree cannot have distinct topologies.");
9208      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
9209      Exit("\n");
9210    }
9211
9212  For(i,2*small_tree->n_otu-1) small_tree->a_nodes[i]->match_node = NULL;
9213  For(i,2*big_tree->n_otu-1)   big_tree->a_nodes[i]->match_node   = NULL;
9214
9215  score = (int *)mCalloc(3,sizeof(int));
9216
9217  For(i,small_tree->n_otu)
9218    {
9219      For(j,big_tree->n_otu)
9220        {
9221          if(!strcmp(small_tree->a_nodes[i]->name,big_tree->a_nodes[j]->name))
9222            {
9223              small_tree->a_nodes[i]->match_node = big_tree->a_nodes[j];
9224              big_tree->a_nodes[j]->match_node   = small_tree->a_nodes[i];
9225              break;
9226            }
9227        }
9228    }
9229
9230  For(i,2*small_tree->n_otu-2)
9231    {
9232      if(small_tree->a_nodes[i]->tax == NO)
9233        {
9234          For(j,2*big_tree->n_otu-2)
9235            {
9236              if(big_tree->a_nodes[j]->tax == NO)
9237                {
9238                  For(k,3) score[k] = 0;
9239                         
9240                  For(k,3)
9241                    {
9242                      For(l,3)
9243                        {
9244                          identical = 0;
9245                          For(m,small_tree->a_nodes[i]->bip_size[k])
9246                            {
9247                              For(n,big_tree->a_nodes[j]->bip_size[l])
9248                                {
9249                                  if(!strcmp(small_tree->a_nodes[i]->bip_node[k][m]->name,big_tree->a_nodes[j]->bip_node[l][n]->name))
9250                                    {
9251                                      identical++;
9252                                      break;
9253                                    }
9254                                }
9255                            }
9256                          if(identical == small_tree->a_nodes[i]->bip_size[k])
9257                            {
9258                              score[k]++;
9259                            }
9260                        }
9261                    }
9262
9263                  /* printf("\n. [%d] [%d] %d %d %d -- %d %d %d",i,j, */
9264                  /*     score[0],score[1],score[2], */
9265                  /*     small_tree->a_nodes[i]->bip_size[0], */
9266                  /*     small_tree->a_nodes[i]->bip_size[1], */
9267                  /*     small_tree->a_nodes[i]->bip_size[2]); */
9268
9269                  if(
9270                     score[0] == 1 && 
9271                     score[1] == 1 &&
9272                     score[2] == 1 
9273                     )
9274                    {
9275                      small_tree->a_nodes[i]->match_node = big_tree->a_nodes[j];
9276                      big_tree->a_nodes[j]->match_node   = small_tree->a_nodes[i];
9277                      break;
9278                    }
9279                }
9280            }     
9281        }
9282    }
9283 
9284  Free(score);
9285}
9286
9287//////////////////////////////////////////////////////////////
9288//////////////////////////////////////////////////////////////
9289
9290
9291void Find_Surviving_Edges_In_Small_Tree(t_tree *small_tree, t_tree *big_tree)
9292{
9293  int i;
9294
9295  Match_Nodes_In_Small_Tree(small_tree,big_tree);
9296
9297  For(i,2*small_tree->n_otu-1) small_tree->rates->has_survived[i] = NO;
9298 
9299  Find_Surviving_Edges_In_Small_Tree_Post(big_tree->n_root,big_tree->n_root->v[2],small_tree,big_tree);
9300  Find_Surviving_Edges_In_Small_Tree_Post(big_tree->n_root,big_tree->n_root->v[1],small_tree,big_tree);
9301}
9302
9303//////////////////////////////////////////////////////////////
9304//////////////////////////////////////////////////////////////
9305
9306
9307void Find_Surviving_Edges_In_Small_Tree_Post(t_node *a, t_node *d, t_tree *small_tree, t_tree *big_tree)
9308{
9309  if(d->match_node && !a->match_node)
9310    {
9311      small_tree->rates->has_survived[d->match_node->num] = YES;
9312    }
9313
9314  if(d->tax == YES) return;
9315  else
9316    {
9317      int i;
9318     
9319      For(i,3)
9320        {
9321          if(d->v[i] != a && d->b[i] != big_tree->e_root)
9322            {
9323              Find_Surviving_Edges_In_Small_Tree_Post(d,d->v[i],small_tree,big_tree);
9324            }
9325        }
9326    }
9327}
9328
9329//////////////////////////////////////////////////////////////
9330//////////////////////////////////////////////////////////////
9331
9332
9333void Set_Taxa_Id_Ranking(t_tree *tree)
9334{
9335  int i,j;
9336
9337  For(i,tree->n_otu) tree->a_nodes[i]->id_rank = 0;
9338
9339  For(i,tree->n_otu)
9340    {
9341      for(j=i+1;j<tree->n_otu;j++)
9342        {
9343          if(strcmp(tree->a_nodes[i]->name,tree->a_nodes[j]->name) > 0)
9344            tree->a_nodes[i]->id_rank++;
9345          else
9346            tree->a_nodes[j]->id_rank++;
9347        }
9348    }
9349  /* For(i,tree->n_otu) PhyML_Printf("\n. %20s %4d",tree->a_nodes[i]->name,tree->a_nodes[i]->id_rank); */
9350}
9351
9352//////////////////////////////////////////////////////////////
9353//////////////////////////////////////////////////////////////
9354
9355
9356void Get_Edge_Binary_Coding_Number(t_tree *tree)
9357{
9358  int i,j;
9359  int list_size;
9360  t_node **list;
9361  t_edge *b;
9362  int max_left,max_rght;
9363
9364  if(tree->n_otu > 1000)
9365    {
9366      PhyML_Printf("\n. Can't work out edge binary code if the number of taxa >1000.");
9367      PhyML_Printf("\n. Err in file %s at line %d\n",__FILE__,__LINE__);
9368      Warn_And_Exit("");
9369    }
9370
9371  Free_Bip(tree);
9372  Alloc_Bip(tree);
9373  Get_Bip(tree->a_nodes[0],tree->a_nodes[0]->v[0],tree);
9374 
9375  Set_Taxa_Id_Ranking(tree);
9376
9377  b = NULL;
9378  For(i,2*tree->n_otu-3)
9379    {
9380      b = tree->a_edges[i];
9381
9382      max_left = 0;
9383      For(j,b->left->bip_size[b->l_r])
9384        if(b->left->bip_node[b->l_r][j]->id_rank > max_left)
9385          max_left = b->left->bip_node[b->l_r][j]->id_rank;
9386
9387      max_rght = 0;
9388      For(j,b->rght->bip_size[b->r_l])
9389        if(b->rght->bip_node[b->r_l][j]->id_rank > max_rght)
9390          max_rght = b->rght->bip_node[b->r_l][j]->id_rank;
9391     
9392         
9393      if(max_left < max_rght)
9394        {
9395          list = b->left->bip_node[b->l_r];
9396          list_size = b->left->bip_size[b->l_r];
9397        }
9398      else
9399        {
9400          list = b->rght->bip_node[b->r_l];
9401          list_size = b->rght->bip_size[b->r_l];
9402        }
9403
9404      b->bin_cod_num = 0.;
9405      For(j,list_size) b->bin_cod_num += POW(2,list[j]->id_rank);
9406      /* printf("\n. %f",b->bin_cod_num); */
9407    }
9408}
9409
9410//////////////////////////////////////////////////////////////
9411//////////////////////////////////////////////////////////////
9412
9413
9414void Make_Ancestral_Seq(t_tree *tree)
9415{
9416  int i;
9417  char **sp_names;
9418
9419  sp_names = (char **)mCalloc(tree->n_otu,sizeof(char *));
9420  For(i,tree->n_otu-1)
9421    {
9422      sp_names[i] = (char *)mCalloc(10,sizeof(char));
9423      sprintf(sp_names[i],"anc%d",i+tree->n_otu);
9424    }
9425
9426  tree->anc_data = Make_Cseq(tree->n_otu-1,
9427                             tree->data->init_len,
9428                             tree->mod->io->state_len,
9429                             tree->data->init_len,
9430                             sp_names);
9431
9432  For(i,tree->n_otu-1) Free(sp_names[i]);
9433  Free(sp_names);
9434}
9435
9436//////////////////////////////////////////////////////////////
9437//////////////////////////////////////////////////////////////
9438
9439void Make_MutMap(t_tree *tree)
9440{
9441  // (# of edges) X (# of sites) X (# mutation types: A<->C A<->G A<->T C<->G C<->T G<->T) 
9442  tree->mutmap = (int *)mCalloc((2*tree->n_otu-3)*(tree->n_pattern)*6,sizeof(int));
9443}
9444
9445//////////////////////////////////////////////////////////////
9446//////////////////////////////////////////////////////////////
9447
9448int Get_Mutmap_Val(int edge, int site, int mut, t_tree *tree)
9449{
9450  int dim1,dim2;
9451
9452  dim1 = (tree->n_pattern)*(2*tree->n_otu-3);
9453  dim2 = (tree->n_pattern);
9454
9455  return tree->mutmap[mut*dim1 + edge*dim2 + site];
9456}
9457
9458//////////////////////////////////////////////////////////////
9459//////////////////////////////////////////////////////////////
9460
9461void Get_Mutmap_Coord(int idx, int *edge, int *site, int *mut, t_tree *tree)
9462{
9463  int dim1,dim2;
9464
9465  dim1 = (tree->n_pattern)*(2*tree->n_otu-3);
9466  dim2 = (tree->n_pattern);
9467
9468  (*mut) =  (int)idx/dim1;
9469  (*edge) = (int)(idx - (*mut)*dim1)/dim2;
9470  (*site) = (int)(idx - (*mut)*dim1 - (*edge)*dim2);
9471}
9472
9473//////////////////////////////////////////////////////////////
9474//////////////////////////////////////////////////////////////
9475
9476//////////////////////////////////////////////////////////////
9477//////////////////////////////////////////////////////////////
9478
9479void Copy_Edge_Lengths(t_tree *to, t_tree *from)
9480{
9481  int i;
9482  For(i,2*from->n_otu-1) to->a_edges[i]->l->v = from->a_edges[i]->l->v;
9483}
9484
9485//////////////////////////////////////////////////////////////
9486//////////////////////////////////////////////////////////////
9487//////////////////////////////////////////////////////////////
9488//////////////////////////////////////////////////////////////
9489
9490char *To_Lower_String(char *in)
9491{
9492  char *out;
9493  int i;
9494  int len;
9495
9496  len = (int)strlen(in);
9497
9498  out = (char *)mCalloc(len+1,sizeof(char));
9499 
9500  For(i,len) out[i] = (char)tolower(in[i]);
9501
9502  out[len] = '\0';
9503  return(out);
9504}
9505
9506//////////////////////////////////////////////////////////////
9507//////////////////////////////////////////////////////////////
9508
9509char *To_Upper_String(char *in)
9510{
9511  char *out;
9512  int i;
9513  int len;
9514
9515  len = (int)strlen(in);
9516
9517  out = (char *)mCalloc(len+1,sizeof(char));
9518 
9519  For(i,len)
9520    {
9521      out[i] = (char)toupper(in[i]);
9522    }
9523
9524  out[len] = '\0';
9525  return(out);
9526}
9527
9528//////////////////////////////////////////////////////////////
9529//////////////////////////////////////////////////////////////
9530
9531void Connect_CSeqs_To_Nodes(calign *cdata, t_tree *tree)
9532{
9533  int i,j,n_otu_tree,n_otu_cdata;
9534
9535  n_otu_tree  = tree->n_otu;
9536  n_otu_cdata = cdata->n_otu;
9537 
9538  if((n_otu_tree != n_otu_cdata) && (tree->io->fp_in_constraint_tree == NULL)) 
9539    {
9540      PhyML_Printf("\n== Number of taxa in the tree: %d, number of sequences: %d.",n_otu_tree,n_otu_cdata);
9541      Warn_And_Exit("\n== The number of tips in the tree is not the same as the number of sequences\n");
9542    }
9543 
9544  For(i,MAX(n_otu_tree,n_otu_cdata))
9545    {
9546      For(j,MIN(n_otu_tree,n_otu_cdata))
9547        {
9548          if(!strcmp(tree->a_nodes[i]->name,cdata->c_seq[j]->name))
9549            break;
9550        }
9551     
9552      if(j==MIN(n_otu_tree,n_otu_cdata))
9553        {
9554          PhyML_Printf("\n== Taxon '%s' was not found in sequence file '%s'.\n",
9555                       tree->a_nodes[i]->name,
9556                       tree->io->in_align_file);
9557          Exit("\n");
9558        }
9559     
9560      tree->a_nodes[i]->c_seq = cdata->c_seq[j];
9561
9562    }
9563}
9564
9565//////////////////////////////////////////////////////////////
9566//////////////////////////////////////////////////////////////
9567
9568void Switch_Eigen(int state, t_mod *mod)
9569{
9570  t_mod *buff;
9571 
9572  buff = mod;
9573  do
9574    {
9575      buff->update_eigen = state;
9576      buff = buff->next;
9577      if(!buff) break;
9578    }
9579  while(1);
9580}
9581
9582//////////////////////////////////////////////////////////////
9583//////////////////////////////////////////////////////////////
9584
9585void Set_Both_Sides(int yesno, t_tree *mixt_tree)
9586{
9587  t_tree *tree;
9588
9589  tree = mixt_tree;
9590
9591  do
9592    {
9593      tree->both_sides = yesno;
9594      tree = tree->next;
9595    }
9596  while(tree);
9597
9598}
9599
9600//////////////////////////////////////////////////////////////
9601//////////////////////////////////////////////////////////////
9602// Returns the matrix of pairwise distances between tips
9603phydbl *Dist_Btw_Tips(t_tree *tree)
9604{
9605  int i,j;
9606  phydbl *dist;
9607
9608  dist = (phydbl *)mCalloc(tree->n_otu*tree->n_otu,sizeof(phydbl));
9609
9610  Fill_Dir_Table(tree);
9611  Update_Dirs(tree);
9612
9613  For(i,tree->n_otu-1)
9614    {
9615      for(j=i+1;j<tree->n_otu;j++)
9616        {
9617          Path_Length(tree->a_nodes[i],tree->a_nodes[j],dist+i*tree->n_otu+j,tree); 
9618          dist[j*tree->n_otu+i] = dist[i*tree->n_otu+j];
9619        }
9620    }
9621 
9622
9623  return(dist);
9624
9625}
9626
9627//////////////////////////////////////////////////////////////
9628//////////////////////////////////////////////////////////////
9629
9630void Random_SPRs_On_Rooted_Tree(t_tree *tree)
9631{
9632  int i,j;
9633  t_node *a, *d, *v1, *v2,*target_nd;
9634  phydbl u;
9635  phydbl lim_sup,lim_inf;
9636  t_edge *residual,*nouse;
9637  phydbl new_t;
9638  int err;
9639  int ok_dir,dir12,dir21;
9640
9641  /* printf("\n. >>>>>>>>>>>>>>.\n"); */
9642  /* Print_Node(tree->n_root,tree->n_root->v[1],tree); */
9643  /* Print_Node(tree->n_root,tree->n_root->v[2],tree); */
9644  /* printf("\n. >>>>>>>>>>>>>>."); */
9645  /* GEO_Update_Occup(tree->geo,tree); */
9646  /* GEO_Lk(tree->geo,tree); */
9647  /* PhyML_Printf("\n>> Init loglk: %f",tree->geo->c_lnL); */
9648 
9649
9650  target_nd = NULL;
9651  residual = NULL;
9652  nouse = NULL;
9653  a = d = v1 = v2 = NULL;
9654  For(i,tree->n_otu) // We will perform tree->n_otu random SPRs
9655    {
9656      a = tree->a_nodes[Rand_Int(tree->n_otu,2*tree->n_otu-3)];
9657     
9658      if(a == tree->n_root)
9659        {
9660          PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);     
9661          Exit("\n");
9662        }
9663      /* if(a == tree->n_root->v[1] || a == tree->n_root->v[2]) continue; */
9664
9665      v1 = v2 = NULL;
9666      For(j,3)
9667        {
9668          if(a->v[j] != a->anc && a->b[j] != tree->e_root)
9669            {
9670              if(!v1) v1 = a->v[j];
9671              else    v2 = a->v[j];
9672            }
9673        }
9674
9675      u = Uni();
9676      if(u < .5) d = v1;
9677      else       d = v2;
9678     
9679
9680      For(j,3) if(a->v[j] == d && a->b[j] == tree->e_root) break;
9681      if(j != 3) continue;
9682
9683      lim_sup = tree->rates->nd_t[d->num];
9684      lim_inf = tree->rates->nd_t[tree->n_root->num];
9685
9686      phydbl scale = Uni()*(50.-5.)+5.;
9687      scale = 50;
9688      err = NO;
9689      new_t = Rnorm_Trunc(tree->rates->nd_t[a->num],
9690                          FABS(tree->rates->nd_t[tree->n_root->num]/scale),
9691                          lim_inf,
9692                          lim_sup,
9693                          &err);
9694     
9695
9696      if(err == YES)
9697        {
9698          PhyML_Printf("\n== Err in file %s at line %d\n",__FILE__,__LINE__);     
9699          Exit("\n");
9700        }
9701     
9702      if(new_t < tree->rates->nd_t[a->num])
9703        {
9704          target_nd = a;
9705          do
9706            {
9707              if(tree->rates->nd_t[target_nd->anc->num] < new_t) 
9708                {
9709                  if(target_nd == a)
9710                    {
9711                      if(v1 == d) target_nd = v2;
9712                      else        target_nd = v1;
9713                    }
9714                  break;
9715                }
9716              else
9717                {
9718                  target_nd = target_nd->anc;
9719                }
9720            }
9721          while(1);
9722        }
9723      else
9724        {
9725          if(v1 == d) target_nd = v2;
9726          else        target_nd = v1;
9727
9728          do
9729            {
9730              if(tree->rates->nd_t[target_nd->num] > new_t)
9731                {
9732                  break;
9733                }
9734              else
9735                {
9736                  v1 = v2 = NULL;
9737                  For(j,3)
9738                    {
9739                      if(target_nd->v[j] != target_nd->anc)
9740                        {
9741                          if(!v1) v1 = target_nd->v[j];
9742                          else    v2 = target_nd->v[j];
9743                        }
9744                    }
9745                  u = Uni();
9746                  if(u < 0.5) target_nd = v1;
9747                  else        target_nd = v2;
9748                }
9749            }while(1);
9750        }
9751
9752      ok_dir = -1;
9753      For(j,3) if(target_nd->v[j] == target_nd->anc || target_nd->b[j] == tree->e_root) ok_dir = j;
9754     
9755      dir12 = -1;
9756      For(j,3) if(tree->n_root->v[1]->v[j] == tree->n_root->v[2]) dir12 = j;
9757
9758      if(dir12 == -1)
9759        {
9760          PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);     
9761          Exit("\n");
9762        }
9763
9764      dir21 = -1;
9765      For(j,3) if(tree->n_root->v[2]->v[j] == tree->n_root->v[1]) dir21 = j;
9766
9767      if(dir21 == -1)
9768        {
9769          PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);     
9770          Exit("\n");
9771        }
9772
9773
9774
9775      /* a = tree->a_nodes[101]; */
9776      /* d = tree->a_nodes[105]; */
9777      /* target_nd = tree->a_nodes[105]; */
9778      /* printf("\n pull %d %d target %d",a->num,d->num,target_nd->num); */
9779      /* printf("\n. %d %d %d",tree->n_root->num,tree->n_root->v[1]->num,tree->n_root->v[2]->num); */
9780      /* printf("\n. %d %d",tree->e_root->num,target_nd->b[ok_dir]->num); */
9781
9782      Prune_Subtree(a,d,&nouse,&residual,tree);
9783
9784      Graft_Subtree(target_nd->b[ok_dir],a,residual,tree);
9785     
9786      tree->rates->nd_t[a->num] = new_t;
9787     
9788      if(target_nd == tree->n_root->v[1])
9789        {
9790          tree->n_root->v[1] = a;
9791          tree->e_root = tree->n_root->v[2]->b[dir21];         
9792        }
9793
9794      if(target_nd == tree->n_root->v[2])
9795        {
9796          tree->n_root->v[2] = a;
9797          tree->e_root = tree->n_root->v[1]->b[dir12];         
9798        }
9799
9800      if(tree->n_root->v[1] == NULL)
9801        {
9802          tree->n_root->v[1] = tree->n_root->v[2]->v[dir21];
9803          tree->e_root = tree->n_root->v[2]->b[dir21];
9804        }
9805     
9806      if(tree->n_root->v[2] == NULL)
9807        {
9808          tree->n_root->v[2] = tree->n_root->v[1]->v[dir12];
9809          tree->e_root = tree->n_root->v[1]->b[dir12];
9810        }
9811
9812      Update_Ancestors(tree->n_root,tree->n_root->v[2],tree);
9813      Update_Ancestors(tree->n_root,tree->n_root->v[1],tree);
9814      tree->n_root->anc = NULL;
9815
9816      /* Print_Node(tree->n_root,tree->n_root->v[1],tree); */
9817      /* Print_Node(tree->n_root,tree->n_root->v[2],tree); */
9818
9819      Time_To_Branch(tree);
9820
9821      /* GEO_Update_Occup(tree->geo,tree); */
9822      /* GEO_Lk(tree->geo,tree); */
9823      /* PhyML_Printf("\nxx Init loglk: %f",tree->geo->c_lnL); */
9824
9825    }
9826
9827
9828}
9829
9830//////////////////////////////////////////////////////////////
9831//////////////////////////////////////////////////////////////
9832
9833/*     |
9834       |
9835       |d
9836      /  \
9837     /    \
9838    /      \b
9839   /        \
9840  /          \x
9841           
9842  Returns p_lk and sum_scale for subtree with x as root, Pij for edge b
9843*/
9844
9845void Set_P_Lk_One_Side(phydbl **Pij, phydbl **p_lk,  int **sum_scale, t_node *d, t_edge *b, t_tree *tree)
9846{
9847  if(Pij) *Pij = b->Pij_rr;
9848
9849  if(!d->tax)
9850    {
9851      if(d == b->left)
9852        {
9853          *p_lk      = b->p_lk_rght;
9854          *sum_scale = b->sum_scale_rght;
9855        }
9856      else
9857        {
9858          *p_lk      = b->p_lk_left;
9859          *sum_scale = b->sum_scale_left;
9860        }
9861    }
9862  else
9863    {
9864
9865      *p_lk        = NULL;
9866      *sum_scale   = NULL;
9867    }
9868}
9869
9870//////////////////////////////////////////////////////////////
9871//////////////////////////////////////////////////////////////
9872
9873/*     |
9874       |
9875       |b
9876       |
9877       |d
9878      /  \
9879     /    \
9880    /      \
9881   /        \
9882  /v1        \v2
9883           
9884  Set p_lk and sum_scale for subtrees with d, v1 and v2 as root,
9885  Pij for edges b, and the two edges connecting d to v1 and d to
9886  v2;
9887  Account for rooted trees.
9888*/
9889
9890void Set_All_P_Lk(t_node **n_v1, t_node **n_v2,
9891                                 phydbl **p_lk   , int **sum_scale   , int **p_lk_loc,
9892                  phydbl **Pij1, phydbl **p_lk_v1, int **sum_scale_v1,
9893                  phydbl **Pij2, phydbl **p_lk_v2, int **sum_scale_v2,
9894                  t_node *d, t_edge *b, t_tree *tree)
9895{
9896  int i;
9897 
9898
9899  if(!tree->n_root)
9900    {
9901      if(d == b->left)
9902        {
9903          *p_lk      = b->p_lk_left;
9904          *sum_scale = b->sum_scale_left;
9905          *p_lk_loc  = b->p_lk_loc_left;
9906        }
9907      else
9908        {
9909          *p_lk      = b->p_lk_rght;
9910          *sum_scale = b->sum_scale_rght;
9911          *p_lk_loc  = b->p_lk_loc_rght;
9912        }
9913
9914      *n_v1 = *n_v2 = NULL;
9915      For(i,3)
9916        {
9917          if(d->b[i] != b)
9918            {
9919              if(!(*n_v1)) 
9920                { 
9921                  *n_v1 = d->v[i]; 
9922                  Set_P_Lk_One_Side(Pij1,p_lk_v1,sum_scale_v1,d,d->b[i],tree); 
9923                }
9924              else     
9925                { 
9926                  *n_v2 = d->v[i]; 
9927                  Set_P_Lk_One_Side(Pij2,p_lk_v2,sum_scale_v2,d,d->b[i],tree); 
9928                }
9929            }
9930        }     
9931    }
9932  else
9933    {
9934      if(b == tree->e_root)
9935        {
9936          if(d == tree->n_root->v[1])      b = tree->n_root->b[1];
9937          else if(d == tree->n_root->v[2]) b = tree->n_root->b[2];
9938          else
9939            {
9940              PhyML_Printf("\n== Err. in file %s at line %d.",__FILE__,__LINE__);
9941              Warn_And_Exit("\n");
9942            }
9943        }
9944
9945      if(d == tree->n_root)
9946        {
9947          if(b == tree->n_root->b[1]) 
9948            {
9949              *p_lk      = tree->n_root->b[1]->p_lk_left;
9950              *sum_scale = tree->n_root->b[1]->sum_scale_left;
9951              *p_lk_loc  = tree->n_root->b[1]->p_lk_loc_left;
9952            }
9953          else
9954            {
9955              *p_lk      = tree->n_root->b[2]->p_lk_left;
9956              *sum_scale = tree->n_root->b[2]->sum_scale_left;
9957              *p_lk_loc  = tree->n_root->b[2]->p_lk_loc_left;
9958            }
9959         
9960          *n_v1         = NULL;
9961          *Pij1         = NULL;
9962          *p_lk_v1      = NULL;
9963          *sum_scale_v1 = NULL;
9964         
9965          if(b == tree->n_root->b[1])
9966            {
9967              *n_v2         = tree->n_root->v[2];
9968              *Pij2         = tree->n_root->b[2]->Pij_rr;
9969              *p_lk_v2      = tree->n_root->b[2]->p_lk_rght;
9970              *sum_scale_v2 = tree->n_root->b[2]->sum_scale_rght;
9971            }
9972          else if(b == tree->n_root->b[2])
9973            {
9974              *n_v2         = tree->n_root->v[1];
9975              *Pij2         = tree->n_root->b[1]->Pij_rr;
9976              *p_lk_v2      = tree->n_root->b[1]->p_lk_rght;
9977              *sum_scale_v2 = tree->n_root->b[1]->sum_scale_rght;
9978            }
9979          else
9980            {
9981              PhyML_Printf("\n== Err. in file %s at line %d.",__FILE__,__LINE__);
9982              Warn_And_Exit("\n");
9983            }
9984        }
9985      else if(d == tree->n_root->v[1] || d == tree->n_root->v[2])
9986        {             
9987          if(b == tree->n_root->b[1] || b == tree->n_root->b[2])
9988            {
9989              if(b == tree->n_root->b[1]) 
9990                {
9991                  *p_lk      = tree->n_root->b[1]->p_lk_rght;
9992                  *sum_scale = tree->n_root->b[1]->sum_scale_rght;
9993                  *p_lk_loc  = tree->n_root->b[1]->p_lk_loc_left;
9994                }
9995              else
9996                {
9997                  *p_lk      = tree->n_root->b[2]->p_lk_rght;
9998                  *sum_scale = tree->n_root->b[2]->sum_scale_rght;
9999                  *p_lk_loc  = tree->n_root->b[2]->p_lk_loc_rght;
10000                }
10001             
10002             
10003              *n_v1 = *n_v2 = NULL;
10004              For(i,3)
10005                {
10006                  if(d->b[i] != tree->e_root)
10007                    {
10008                      if(!(*n_v1)) 
10009                        { 
10010                          *n_v1 = d->v[i]; 
10011                          Set_P_Lk_One_Side(Pij1,p_lk_v1,sum_scale_v1,d,d->b[i],tree); 
10012                        }
10013                      else     
10014                        { 
10015                          *n_v2 = d->v[i]; 
10016                          Set_P_Lk_One_Side(Pij2,p_lk_v2,sum_scale_v2,d,d->b[i],tree); 
10017                        }
10018                    }
10019                }
10020            }
10021          else
10022            {
10023              if(d == b->left)
10024                {
10025                  *p_lk      = b->p_lk_left;
10026                  *sum_scale = b->sum_scale_left;
10027                  *p_lk_loc  = b->p_lk_loc_left;
10028                }
10029              else
10030                {
10031                  *p_lk      = b->p_lk_rght;
10032                  *sum_scale = b->sum_scale_rght;
10033                  *p_lk_loc  = b->p_lk_loc_rght;
10034                }
10035             
10036             
10037              *n_v1 = tree->n_root;
10038              Set_P_Lk_One_Side(Pij1,p_lk_v1,sum_scale_v1,d,
10039                                (d == tree->n_root->v[1])?
10040                                (tree->n_root->b[1]):
10041                                (tree->n_root->b[2]),
10042                                tree);
10043             
10044              For(i,3)
10045                {
10046                  if(d->b[i] != tree->e_root && d->b[i] != b)
10047                    {
10048                      *n_v2 = d->v[i]; 
10049                      Set_P_Lk_One_Side(Pij2,p_lk_v2,sum_scale_v2,d,d->b[i],tree); 
10050                      break;
10051                    }
10052                }
10053             
10054            }
10055        }
10056      else
10057        {
10058          if(d == b->left)
10059            {
10060              *p_lk      = b->p_lk_left;
10061              *sum_scale = b->sum_scale_left;
10062              *p_lk_loc  = b->p_lk_loc_left;
10063            }
10064          else
10065            {
10066              *p_lk      = b->p_lk_rght;
10067              *sum_scale = b->sum_scale_rght;
10068              *p_lk_loc  = b->p_lk_loc_rght;
10069            }
10070         
10071          *n_v1 = *n_v2 = NULL;
10072          For(i,3)
10073            {
10074              if(d->b[i] != b)
10075                {
10076                  if(!(*n_v1)) 
10077                    { 
10078                      *n_v1 = d->v[i]; 
10079                      Set_P_Lk_One_Side(Pij1,p_lk_v1,sum_scale_v1,d,d->b[i],tree); 
10080                    }
10081                  else     
10082                    { 
10083                      *n_v2 = d->v[i]; 
10084                      Set_P_Lk_One_Side(Pij2,p_lk_v2,sum_scale_v2,d,d->b[i],tree); 
10085                    }
10086                }
10087            }     
10088        }
10089    }
10090}
10091
10092//////////////////////////////////////////////////////////////
10093//////////////////////////////////////////////////////////////
10094
10095void Optimum_Root_Position_IL_Model(t_tree *tree)
10096{
10097
10098  if(tree->n_root)
10099    {
10100      PhyML_Printf("\n== The tree already has a root node");
10101      PhyML_Printf("\n== Err. in file %s at line %d\n",__FILE__,__LINE__);     
10102      Exit("\n");
10103    }
10104  else
10105    {
10106      int i;
10107      t_edge *best_edge;
10108      phydbl best_lnL;
10109
10110      Free_Edge_Lk_Rght(tree->a_edges[2*tree->n_otu-3]);
10111      Free_Edge_Lk_Rght(tree->a_edges[2*tree->n_otu-2]);
10112      Free_Edge_Pars_Rght(tree->a_edges[2*tree->n_otu-3]);
10113      Free_Edge_Pars_Rght(tree->a_edges[2*tree->n_otu-2]);
10114     
10115      best_edge = NULL;
10116      best_lnL  = UNLIKELY;
10117      For(i,2*tree->n_otu-3)
10118        {
10119          PhyML_Printf("\n. Positionning root node on edge %4d",tree->a_edges[i]->num);
10120          Add_Root(tree->a_edges[i],tree);
10121          Set_Both_Sides(YES,tree);
10122          Lk(NULL,tree);
10123
10124          /* Optimize_Br_Len_Serie(tree); */
10125
10126          Update_P_Lk(tree,tree->n_root->b[1],tree->n_root);
10127          Br_Len_Brent(tree->mod->l_min,tree->mod->l_max,tree->n_root->b[1],tree);
10128          Update_P_Lk(tree,tree->n_root->b[2],tree->n_root);
10129          Br_Len_Brent(tree->mod->l_min,tree->mod->l_max,tree->n_root->b[2],tree);
10130
10131          PhyML_Printf(" -- lnL: %20f",tree->c_lnL);
10132          if(tree->c_lnL > best_lnL)
10133            {
10134              best_lnL  = tree->c_lnL;
10135              best_edge = tree->a_edges[i];
10136            }
10137        }
10138
10139      Add_Root(best_edge,tree);
10140      Set_Both_Sides(YES,tree);
10141      Lk(NULL,tree);
10142      Update_P_Lk(tree,tree->n_root->b[1],tree->n_root);
10143      Br_Len_Brent(tree->mod->l_min,tree->mod->l_max,tree->n_root->b[1],tree);
10144      Update_P_Lk(tree,tree->n_root->b[2],tree->n_root);
10145      Br_Len_Brent(tree->mod->l_min,tree->mod->l_max,tree->n_root->b[2],tree);
10146    }
10147}
10148
10149//////////////////////////////////////////////////////////////
10150//////////////////////////////////////////////////////////////
10151
10152void Set_Br_Len_Var(t_tree *tree)
10153{
10154  if(tree->is_mixt_tree)
10155    {
10156      MIXT_Set_Br_Len_Var(tree);
10157      return;
10158    }
10159
10160  if(!tree->rates)
10161    {
10162      int i;
10163      phydbl len;
10164
10165      For(i,2*tree->n_otu-1) 
10166        {
10167          /* len = MAX(tree->mod->l_min,tree->a_edges[i]->l->v); */
10168          /* len = MIN(tree->mod->l_max,len); */
10169          len = MAX(0.0,tree->a_edges[i]->l->v);
10170          tree->a_edges[i]->l_var->v = POW(len,2)*tree->mod->l_var_sigma; 
10171        }
10172    }   
10173}
10174
10175//////////////////////////////////////////////////////////////
10176//////////////////////////////////////////////////////////////
10177
10178void Check_Br_Lens(t_tree *tree)
10179{
10180  int i;
10181  scalar_dbl *l;
10182
10183  For(i,2*tree->n_otu-1)
10184    {
10185      l = tree->a_edges[i]->l;
10186      do
10187        {
10188          /* if(l->v < tree->mod->l_min) l->v = tree->mod->l_min; */
10189          /* if(l->v > tree->mod->l_max) l->v = tree->mod->l_max; */
10190          if(l->v < 0.0) l->v = 0.0;
10191          l = l->next;
10192        }
10193      while(l);
10194    }
10195}
10196
10197//////////////////////////////////////////////////////////////
10198//////////////////////////////////////////////////////////////
10199
10200//////////////////////////////////////////////////////////////
10201//////////////////////////////////////////////////////////////
10202
10203//////////////////////////////////////////////////////////////
10204//////////////////////////////////////////////////////////////
10205
10206//////////////////////////////////////////////////////////////
10207//////////////////////////////////////////////////////////////
10208
10209//////////////////////////////////////////////////////////////
10210//////////////////////////////////////////////////////////////
10211
10212//////////////////////////////////////////////////////////////
10213//////////////////////////////////////////////////////////////
10214
10215//////////////////////////////////////////////////////////////
10216//////////////////////////////////////////////////////////////
10217
10218
Note: See TracBrowser for help on using the repository browser.