File: icm.cc

package info (click to toggle)
tigr-glimmer 3.02b-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 13,948 kB
  • sloc: cpp: 24,416; awk: 232; csh: 220; makefile: 147; sh: 51
file content (1998 lines) | stat: -rw-r--r-- 52,598 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
//  Programmers:   Arthur L. Delcher
//                 Doug Harmon
//
//  File:          icm.cc
//
//  Last Updated:  Mon Jun 12 15:34:00 EDT 2006
//
//  Purpose:  Routines for defining and manipulating the
//  Interpolated Context Model (ICM) used by Glimmer2
//
//
//  Copyright (c) 2006 University of Maryland Center for Bioinformatics
//  & Computational Biology


#include  "icm.hh"

using namespace std;

extern int  Verbose;



ICM_t :: ICM_t
    (int w, int d, int p)

//  Constructor for the ICM

  {
   int  i;

   model_len = w;
   model_depth = d;
   periodicity = p;
   num_nodes = (Int_Power (ALPHABET_SIZE, model_depth + 1) - 1) / (ALPHABET_SIZE - 1);
   score = (ICM_Score_Node_t * *)
                  Safe_calloc (periodicity, sizeof (ICM_Score_Node_t *),
                  __FILE__, __LINE__);
   for  (i = 0;  i < periodicity;  i ++)
     score [i] = (ICM_Score_Node_t *)
                   Safe_calloc (num_nodes, sizeof (ICM_Score_Node_t),
                   __FILE__, __LINE__);
   empty = true;
  }



ICM_t :: ~ ICM_t ()

//  Destroy this ICM

  {
   int  i;

   if  (score != NULL)
       {
        for  (i = 0;  i < periodicity;  i ++)
          free (score [i]);
        free (score);
       }
  }



void  ICM_t :: Build_Indep_WO_Stops
    (double gc_frac, const vector <const char *> & stop_codon)

//  Make this model represent generating codons with independent
//  nucleotides with GC-portion of  gc_frac  but without generating
//  any codons in  stop_codon .  The model is built in
//  reverse order of the strings in  stop_codon .

  {
   double  codon_prob [64], base_prob [4];
   double  sum;
   int  pattern [3];
   int  i, j, k, n;

   if  (model_len != 3 || model_depth != 2 || periodicity != 3
           || ALPHABET_SIZE != 4 || num_nodes != 21)
       {
        fprintf (stderr,
             "ERROR:  Incompatible ICM_Training_t for Build_Indep_WO_Stops\n");
        fprintf (stderr,
             "model_len = %d  model_depth = %d  periodicity = %d\n"
             "alphabet_size = %d  num_nodes = %d\n",
             model_len, model_depth, periodicity, ALPHABET_SIZE, num_nodes);
        fprintf (stderr,
             "Should be  %d ,  %d ,  %d ,  %d ,  %d  respectively\n",
             3, 2, 3, 4, 21);
        exit (EXIT_FAILURE);
       }

   // set base_prob to independent probability of a, c, g, t
   base_prob [1] = base_prob [2] = gc_frac / 2.0;        // c, g
   base_prob [0] = base_prob [3] = 0.5 - base_prob [1];  // a, t

   // set codon_prob to independent probabilities of all codons
   pattern [0] = pattern [1] = pattern [2] = 0;
   for  (i = 0;  i < 64;  i ++)
     {
      codon_prob [i] = base_prob [pattern [0]] * base_prob [pattern [1]]
                          * base_prob [pattern [2]];

      // increment pattern
      for  (j = 2;  j >= 0;  j --)
        {
         pattern [j] ++;
         if  (pattern [j] == 4)
             pattern [j] = 0;
           else
             break;
        }
     }

   // set  codon_prob  for all codons in  stop_codon  to near-zero value
   // Note:  Logically reverse  stop_codon  entries since scoring is done
   //  in the reverse direction (i.e., 3' to 5') of orfs
   n = stop_codon . size ();
   for  (i = 0;  i < n;  i ++)
     {
      j = Subscript (stop_codon [i] [0])
            + 4 * Subscript (stop_codon [i] [1])
            + 16 * Subscript (stop_codon [i] [2]);

      codon_prob [j] = 1e-20;
     }

   // normalize probability values
   sum = 0.0;
   for  (i = 0;  i < 64;  i ++)
     sum += codon_prob [i];
   for  (i = 0;  i < 64;  i ++)
     codon_prob [i] /= sum;

   // initialize  score  nodes
   for  (i = 0;  i < periodicity;  i ++)
     for  (j = 0;  j < num_nodes;  j ++)
       {
#if  STORE_MUT_INFO
        score [i] [j] . mut_info = 0.0;
#endif
        for  (k = 0;  k < 4;  k ++)
          score [i] [j] . prob [k] = 0.0;
       }

   // set root values of the ICM tree
   // these are the independent probabilities
   for  (i = 0;  i < periodicity;  i ++)
     {
      ICM_Score_Node_t  * p = score [i];
      int  d1 = Int_Power (4, (3 - i) % 3);

      if  (i == 1)
             // for frame i=1 this is independent of prior base which
             // is in the preceding codon
          p -> mut_info_pos = -1;
        else
          p -> mut_info_pos = 1;
      for  (j = 0;  j < 64;  j ++)
        p -> prob [(j / d1) % 4] += codon_prob [j];
     }

   // set level-1 values of the ICM tree
   for  (i = 0;  i < periodicity;  i ++)
     {
      ICM_Score_Node_t  * p = score [i] + 1;
      int  d1 = Int_Power (4, (3 - i) % 3);
      int  d2 = Int_Power (4, (4 - i) % 3);

      for  (j = 0;  j < 4;  j ++)
        if  (i == 2)
            p [j] . mut_info_pos = -1;
          else
            p [j] . mut_info_pos = 0;

      if  (i != 1)
          for  (j = 0;  j < 64;  j ++)
            p [(j / d2) % 4] . prob [(j / d1) % 4] += codon_prob [j];
     }

   // set level-2 values of the ICM tree
   // only need frame i=0 since other frames are stopped at
   // higher levels
   i = 0;
     {
      ICM_Score_Node_t  * p = score [i] + 5;
      int  d1 = Int_Power (4, (3 - i) % 3);
      int  d2 = Int_Power (4, (4 - i) % 3);
      int  d3 = Int_Power (4, (5 - i) % 3);

      for  (j = 0;  j < 16;  j ++)
        p [j] . mut_info_pos = -1;
      for  (j = 0;  j < 64;  j ++)
        {
         k = 4 * ((j / d2) % 4) + (j / d3) % 4;
         p [k] . prob [(j / d1) % 4] += codon_prob [j];
        }
     }

   // normalize and take logs of all prob values
   for  (i = 0;  i < periodicity;  i ++)
     for  (j = 0;  j < num_nodes;  j ++)
       {
        sum = 0.0;
        for  (k = 0;  k < 4;  k ++)
          sum += score [i] [j] . prob [k];
        for  (k = 0;  k < 4;  k ++)
          score [i] [j] . prob [k]
               = (sum == 0.0 ? 0.0 : log (score [i] [j] . prob [k] / sum));
       }
   
   empty = false;

   return;
  }



void  ICM_t :: Build_Reverse_Codon_WO_Stops
    (double codon_prob [64], const vector <const char *> & stop_codon)

//  Make this model represent generating independent codons
//  with proportions in  codon_prob  but without generating
//  any codons in  stop_codon .  The model is built in
//  reverse order of the strings in  stop_codon  and the entries
//  in  codon_prob  must be in alphabetical order by *REVERSE*
//  (but not reverse-complement) codon string, i.e., forward codons aaa, caa,
//  gaa, taa, ata, ....

  {
   double  sum;
   int  i, j, k, n;

   if  (model_len != 3 || model_depth != 2 || periodicity != 3
           || ALPHABET_SIZE != 4 || num_nodes != 21)
       {
        fprintf (stderr,
             "ERROR:  Incompatible ICM_Training_t for Build_Reverse_Codon_WO_Stops\n");
        fprintf (stderr,
             "model_len = %d  model_depth = %d  periodicity = %d\n"
             "alphabet_size = %d  num_nodes = %d\n",
             model_len, model_depth, periodicity, ALPHABET_SIZE, num_nodes);
        fprintf (stderr,
             "Should be  %d ,  %d ,  %d ,  %d ,  %d  respectively\n",
             3, 2, 3, 4, 21);
        exit (EXIT_FAILURE);
       }

   // set  codon_prob  for all codons in  stop_codon  to near-zero value
   // Note:  Logically reverse  stop_codon  entries since scoring is done
   //  in the reverse direction (i.e., 3' to 5') of orfs
   n = stop_codon . size ();
   for  (i = 0;  i < n;  i ++)
     {
      j = Subscript (stop_codon [i] [0])
            + 4 * Subscript (stop_codon [i] [1])
            + 16 * Subscript (stop_codon [i] [2]);

      codon_prob [j] = 1e-20;
     }

   // normalize probability values
   sum = 0.0;
   for  (i = 0;  i < 64;  i ++)
     sum += codon_prob [i];
   for  (i = 0;  i < 64;  i ++)
     codon_prob [i] /= sum;

   // initialize  score  nodes
   for  (i = 0;  i < periodicity;  i ++)
     for  (j = 0;  j < num_nodes;  j ++)
       {
#if  STORE_MUT_INFO
        score [i] [j] . mut_info = 0.0;
#endif
        for  (k = 0;  k < 4;  k ++)
          score [i] [j] . prob [k] = 0.0;
       }

   // set root values of the ICM tree
   // these are the independent probabilities
   for  (i = 0;  i < periodicity;  i ++)
     {
      ICM_Score_Node_t  * p = score [i];
      int  d1 = Int_Power (4, (3 - i) % 3);

      if  (i == 1)
             // for frame i=1 this is independent of prior base which
             // is in the preceding codon
          p -> mut_info_pos = -1;
        else
          p -> mut_info_pos = 1;
      for  (j = 0;  j < 64;  j ++)
        p -> prob [(j / d1) % 4] += codon_prob [j];
     }

   // set level-1 values of the ICM tree
   for  (i = 0;  i < periodicity;  i ++)
     {
      ICM_Score_Node_t  * p = score [i] + 1;
      int  d1 = Int_Power (4, (3 - i) % 3);
      int  d2 = Int_Power (4, (4 - i) % 3);

      for  (j = 0;  j < 4;  j ++)
        if  (i == 2)
            p [j] . mut_info_pos = -1;
          else
            p [j] . mut_info_pos = 0;

      if  (i != 1)
          for  (j = 0;  j < 64;  j ++)
            p [(j / d2) % 4] . prob [(j / d1) % 4] += codon_prob [j];
     }

   // set level-2 values of the ICM tree
   // only need frame i=0 since other frames are stopped at
   // higher levels
   i = 0;
     {
      ICM_Score_Node_t  * p = score [i] + 5;
      int  d1 = Int_Power (4, (3 - i) % 3);
      int  d2 = Int_Power (4, (4 - i) % 3);
      int  d3 = Int_Power (4, (5 - i) % 3);

      for  (j = 0;  j < 16;  j ++)
        p [j] . mut_info_pos = -1;
      for  (j = 0;  j < 64;  j ++)
        {
         k = 4 * ((j / d2) % 4) + (j / d3) % 4;
         p [k] . prob [(j / d1) % 4] += codon_prob [j];
        }
     }

   // normalize and take logs of all prob values
   for  (i = 0;  i < periodicity;  i ++)
     for  (j = 0;  j < num_nodes;  j ++)
       {
        sum = 0.0;
        for  (k = 0;  k < 4;  k ++)
          sum += score [i] [j] . prob [k];
        for  (k = 0;  k < 4;  k ++)
          score [i] [j] . prob [k]
               = (sum == 0.0 ? 0.0 : log (score [i] [j] . prob [k] / sum));
       }
   
   empty = false;

   return;
  }



void  ICM_t :: Cumulative_Score
    (const string & s, vector <double> & score, int frame)  const

//  Set  score [i]  to be the score of substring  s [0 .. i]
//  for each position in  s .  Use this model with the first base
//  in frame  frame .

  {
   double  result, x;
   const char  * cstr = s . c_str ();
   int  start, stop;
   int  i, n;

   if  (periodicity == 1)
       frame = 0;
   assert (0 <= frame && frame < periodicity);

   n = s . length ();
   score . resize (n);

   result = 0.0;

   stop = Min (model_len - 1, n);
   for  (i = 0;  i < stop;  i ++)
     {
      x = Partial_Window_Prob (i, cstr, frame);
//**ALD
//printf ("Cumulative_Score:  i = %2d  ch = %c  prob = %6.4f\n", i, s [i], exp (x));
      result += x;
      if  (frame == periodicity - 1)
          frame = 0;
        else
          frame ++;
      score [i] = result;
     }

   for  (start = 0;  i < n;  start ++, i ++)
     {
      x = Full_Window_Prob (cstr + start, frame);
//**ALD
//printf ("Cumulative_Score:  %-.*s  start = %3d  i = %3d  ch = %c  prob = %6.4f\n",
//     model_len, cstr + start, start, i, s [i], exp (x));
      result += x;
      if  (frame == periodicity - 1)
          frame = 0;
        else
          frame ++;
      score [i] = result;
     }

   return;
  }



void  ICM_t :: Cumulative_Score_String
    (char * string, int len, int frame, double * cum_score)

//  Set entries in  cum_score  to cumulative score up to each respective base
//  of string  string [0 .. (len - 1)] .
//  Use this model with the first base in frame  frame .
//  Array  cum_score  is assumed to be large enough to hold the results.

  {
   double  result, x;
   int  start, stop = model_len - 1;
   int  i;
  
   if  (periodicity == 1)
       frame = 0;
   assert (0 <= frame && frame < periodicity);

   if  (Verbose > 0)
       printf ("Cumulative_Score_String  len = %d  frame = %d\n", len, frame);

   result = cum_score [0] = 0.0;

   for  (i = 0;  i < model_len - 1;  i ++)
     {
      x = Partial_Window_Prob (i, string, frame);
      if  (Verbose > 0)
          printf ("%7d: %8.3f\n", i, x);
      result += x;
      frame = (frame + 1) % periodicity;
      cum_score [i + 1] = result;
     }

   for  (start = 0;  stop < len;  start ++, stop ++)
     {
      x = Full_Window_Prob (string + start, frame);
      if  (Verbose > 0)
          printf ("%7d: %8.3f\n", start + model_len - 1, x);
      result += x;
      frame = (frame + 1) % periodicity;
      cum_score [stop + 1] = result;
     }

   return;
  }



void  ICM_t :: Display
    (FILE * fp)

//  Print an ASCII, human-readable version of this model to  fp
//  Assume  fp  is already open and that the caller will close it
//  if necessary.

  {
   int  i, period;

   fprintf (fp, "model_len = %d  periodicity = %d  depth = %d  num_nodes = %d\n",
            model_len, periodicity, model_depth, num_nodes);
            
   for  (period = 0;  period < periodicity;  period ++)
     {
      fprintf (fp, "period = %d\n", period);
      for  (i = 0;  i < num_nodes;  i ++)
        {
         int  j;

         fprintf (fp, "%3d:  %2d ", i, score [period] [i] . mut_info_pos);
         for  (j = 0;  j < ALPHABET_SIZE;  j ++)
           fprintf (fp, " %7.4f", exp (score [period] [i] . prob [j]));
         fputc ('\n', fp);
        }
     }
   return;
  }



void  ICM_t :: Full_Window_Distrib
    (char * string, int frame, float * dist)

//  Set  dist  to the probabilities of the possible characters
//  using  string  as the context and entries in  score [frame] .

  {
   int  num_node, i, pos, sub;

   num_node = 0;

   for  (i = 0;  i < model_depth;  i ++)
     {
      pos = score [frame] [num_node] . mut_info_pos;

      if  (pos == -1)
          break;

      if  (pos < -1)  // No information here or below in tree, go back up
                      // Shouldn't happen
          {
           num_node = PARENT (num_node);
           pos = score [frame] [num_node] . mut_info_pos;
           break;
          }

      sub = Subscript (string [pos]);

      num_node = (num_node * ALPHABET_SIZE) + sub + 1;
     }

   pos = score [frame] [num_node] . mut_info_pos;
   if  (pos < -1)
       {
        num_node = PARENT (num_node);
        pos = score [frame] [num_node] . mut_info_pos;
       }

   memcpy (dist, score [frame] [num_node] . prob, ALPHABET_SIZE * sizeof (float));

   return;
  }



double  ICM_t :: Full_Window_Prob
    (const char * string, int frame)  const

//  Return the log-probability of the last character in the first
//  model_len  bases of  string  conditioned on the preceding characters
//  using the entries in  score [frame] .

  {
   double  prob;
   int  num_node, i, pos, sub;

   num_node = 0;

   for  (i = 0;  i < model_depth;  i ++)
     {
      pos = score [frame] [num_node] . mut_info_pos;

      if  (pos == -1)
          break;

      if  (pos < -1)  // No information here or below in tree, go back up
                      // Shouldn't happen
          {
           num_node = PARENT (num_node);
           pos = score [frame] [num_node] . mut_info_pos;
           break;
          }

      sub = Subscript (string [pos]);

      num_node = (num_node * ALPHABET_SIZE) + sub + 1;
     }

   pos = score [frame] [num_node] . mut_info_pos;
   if  (pos < -1)
       {
        num_node = PARENT (num_node);
        pos = score [frame] [num_node] . mut_info_pos;
       }

   sub = Subscript (string [model_len - 1]);

   prob = (double) score [frame] [num_node] . prob [sub];

   if  (pos < -1)
       {
        fprintf (stderr, "WARNING:  prob = %.4f  pos = %d in  Full_Window_Prob\n",
                 prob, pos);
        fprintf (stderr, "num_node = %d\n",
                 num_node);
       }

   return  prob;
  }



void  ICM_t :: Input
    (FILE * fp)

//  Input the contents of this model from  fp , which has
//  already been opened.

  {
   char  line [ID_STRING_LEN];
   int  param [NUM_FIXED_LENGTH_PARAMS];
   int  node_id;
   int  prev_node;
   int  period;
   int  i;

   // free memory from previous version
   for  (i = 0;  i < periodicity;  i ++)
     free (score [i]);
   free (score);
   score = NULL;

   // skip the text header line
   if  (fread (line, sizeof (char), ID_STRING_LEN, fp) != unsigned (ID_STRING_LEN))
       {
        fprintf (stderr, "ERROR reading ICM header\n");
        exit (EXIT_FAILURE);
       };    

   if  (fread (param, sizeof (int), NUM_FIXED_LENGTH_PARAMS, fp) != NUM_FIXED_LENGTH_PARAMS)
       {
        fprintf (stderr, "ERROR reading parameters\n");
        exit (EXIT_FAILURE);
       }

   if  (ICM_VERSION_ID != param [0])
       {
        fprintf (stderr, "Bad ICM version = %d  should be %d\n",
                 param [0], ICM_VERSION_ID);
        exit (EXIT_FAILURE);
       }
   if  (ID_STRING_LEN != param [1])
       {
        fprintf (stderr, "Bad ID_STRING_LEN = %d  should be %d\n",
                 param [1], ID_STRING_LEN);
        exit (EXIT_FAILURE);
       }

   model_len = param [2];
   model_depth = param [3];
   periodicity = param [4];
   num_nodes = param [5];

   score = (ICM_Score_Node_t * *) Safe_malloc
             (periodicity * sizeof (ICM_Score_Node_t *), __FILE__, __LINE__);
   for  (i = 0;  i < periodicity;  i ++)
     score [i] = (ICM_Score_Node_t *) Safe_calloc
                   (num_nodes, sizeof (ICM_Score_Node_t), __FILE__, __LINE__);

   period = -1;
   prev_node = 0;
   while  (fread (& node_id, sizeof (int), 1, fp) != 0)
     {
      if  (node_id < 0)
          break;

      if  (node_id == 0)
          period ++;

      // read in the probabilities
      if  (fread (score [period] [node_id] . prob,
                  sizeof (float), ALPHABET_SIZE, fp) != unsigned (ALPHABET_SIZE))
          {
           fprintf (stderr, "ERROR reading icm node = %d  period = %d\n",
                    node_id, period); 
           exit (EXIT_FAILURE);
          }

      // read in the max mutual information position
      if  (fread (& (score [period] [node_id] . mut_info_pos), sizeof (short int), 1, fp)
             != 1)
          {
           fprintf (stderr, "ERROR reading mut_info_pos for node = %d  period = %d\n",
                    node_id, period);
           exit (EXIT_FAILURE);
          }

      // check for cut nodes
      if  (node_id != 0 && prev_node != node_id - 1)
          for  (i = prev_node + 1;  i < node_id;  i ++)
               score [period] [i] . mut_info_pos = -2;

      if  (node_id == 0 && period > 0)
          for  (i = prev_node + 1;  i < num_nodes;  i ++)
            score [period - 1] [i] . mut_info_pos = -2;

      prev_node = node_id;
     }

   if  (period != periodicity - 1)
       {
        fprintf (stderr, "ERROR:  Too few nodes for periodicity = %d\n",
                 periodicity);
        exit (EXIT_FAILURE);
       }

   // check for cut nodes in last period
   if  (prev_node != num_nodes - 1)
       for  (i = prev_node + 1;  i < num_nodes;  i ++)
            score [period] [i] . mut_info_pos = -2;

   empty = false;

   return;
  }



void  ICM_t :: Output
    (FILE * fp, bool binary_form)

//  Output the contents of this model to  fp .
//  If  binary_form  is true, then do it in binary; otherwise,
//  write an ascii text version.

  {
   int  end_marker = -1;
   int  i, frame;

   Write_Header (fp, binary_form);

   for  (frame = 0;  frame < periodicity;  frame ++)
     {
      Output_Node (fp, score [frame] + 0, 0, frame, binary_form);
      for  (i = 1;  i < num_nodes;  i ++)
        if  (score [frame] [i] . mut_info_pos >= -1)
            Output_Node (fp, score [frame] + i, i, frame, binary_form);
     }
   if  (binary_form)
       fwrite (& end_marker, sizeof (int), 1, fp);

   return;
  }



void  ICM_t :: Output_Node
    (FILE * fp, ICM_Score_Node_t * node, int id, int frame, bool binary_form)

//  Output  id  and then contents of  node  to  fp , in binary or ascii text
//  depending on whether  binary_form  is true or not, resp.
//  frame  is the frame within the periodic rotation of this node

  {
   if  (Verbose > 1)
       fprintf (stderr, "output node %d  frame %d\n", id, frame);

   if  (binary_form)
       {
        fwrite (& id, sizeof (int), 1, fp);
        fwrite (node -> prob, sizeof (float), ALPHABET_SIZE, fp);
        fwrite (& node -> mut_info_pos, sizeof (short int), 1, fp);
       }
     else
       {
        char  label [2 * 100];
          // allow extra positions to insert vertical separators
        int  i;

        assert (model_len <= 100);
        for  (i = 0;  i < model_len;  i ++)
          label [i] = '-';
        label [model_len - 1] = '?';
        label [model_len] = '\0';
        
        // put characters in label that represent the restrictions
        // on context positions for this node
        Set_Label_String (label, id, frame);

        if  (Verbose > 1)
            fprintf (stderr, "Label set to %s\n", label);

        fprintf (fp, "%6d  %s", id, label);
#if  STORE_MUT_INFO
        fprintf (fp, " %7.4f", node -> mut_info);
#endif
        for  (i = 0;  i < ALPHABET_SIZE;  i ++)
          fprintf (fp, " %6.3f", exp (node -> prob [i]));
        fputc ('\n', fp);
       }

   return;
  }



double  ICM_t :: Partial_Window_Prob
    (int predict_pos, const char * string, int frame)  const

//  Return the log-probability of character  string [predict_pos]  using
//  only the preceding  (predict_pos - 1)  characters  using the
//  entries in  score [frame] .

  {
   double  prob;
   int  num_node, i, start, pos, sub;

   start = predict_pos - (model_len - 1);
     // Negative position in  string  where this window would start
   num_node = 0;

   for  (i = 0;  i < model_depth;  i ++)
     {
      pos = start + score [frame] [num_node] . mut_info_pos;

      if  (pos < 0)
          break;

      sub = Subscript (string [pos]);

      num_node = (num_node * ALPHABET_SIZE) + sub + 1;
     }

   if  (score [frame] [num_node] . mut_info_pos == -2)
       num_node = PARENT (num_node);

   sub = Subscript (string [predict_pos]);

   prob = (double) score [frame] [num_node] . prob [sub];

   return  prob;
  }



void  ICM_t :: Read
    (char * path)

//  Read this model in from the file specified in  path

  {
   FILE  * fp;

   fp = File_Open (path, "r");     // Should be "rb"?

   Input (fp);

   fclose (fp);

   return;
  }



double  ICM_t :: Score_String
    (const char * string, int len, int frame)  const

//  Return the log-probability score of  string [0 .. (len - 1)]
//  in frame  frame  of this model.

  {
   double  result, x;
   int  start, stop = model_len - 1;
   int  i;
  
   if  (periodicity == 1)
       frame = 0;
   assert (0 <= frame && frame < periodicity);

   if  (Verbose > 0)
       printf ("Score_String  len = %d  frame = %d\n", len, frame);

   result = 0.0;

   for  (i = 0;  i < len && i < model_len - 1;  i ++)
     {
      x = Partial_Window_Prob (i, string, frame);
      if  (Verbose > 0)
          printf ("%7d: %8.3f\n", i, x);
      result += x;
      frame = (frame + 1) % periodicity;
     }

   for  (start = 0;  stop < len;  start ++, stop ++)
     {
      x = Full_Window_Prob (string + start, frame);
      if  (Verbose > 0)
          printf ("%7d: %8.3f\n", start + model_len - 1, x);
      result += x;
      frame = (frame + 1) % periodicity;
     }

   return  result;
  }



void  ICM_t :: Set_Label_String
    (char * label, int id, int frame)

//  Fill in characters of  label  with characters representing the
//  context matches for node  id  based on the ancestors of
//  this node in the tree in frame  frame .

  {
   int  last_separator, separator_ct;
   int  i, parent, mip;

   mip = score [frame] [id]. mut_info_pos;
   if  (mip >= 0)
       label [score [frame] [id]. mut_info_pos] = MAX_MI_CHAR;

   while  (id > 0)
     {
      parent = PARENT (id);
      label [score [frame] [parent] . mut_info_pos]
          = ALPHA_STRING [id - ALPHABET_SIZE * parent - 1];
      id = parent;
     }

   // add separators

   if  (periodicity == 1)
       last_separator = separator_ct = 0;
     else
       {
        if  (frame == 0)
            last_separator = model_len - periodicity;
          else
            last_separator = model_len - frame;
        if  (last_separator < 0)
            last_separator = 0;
        separator_ct = (last_separator + periodicity - 1) / periodicity;
       }

   for  (i = model_len;  i > 0;  i --)
     {
      label [i + separator_ct] = label [i];
      if  (i == last_separator)
          {
           separator_ct --;
           label [i + separator_ct] = SEPARATOR_CHAR;
           last_separator -= periodicity;
          }
     }

   return;
  }



void  ICM_t :: Write_Header
    (FILE * fp, bool binary_form)

//  Send to  fp  the parameter information for this model.
//  binary_form  determines whether the format is binary or
//  Ascii readable (for debugging purposes only)

  {

   if  (! binary_form)
       fprintf (fp, "ver = %.2f  len = %d  depth = %d"
                "  periodicity = %d  nodes = %d\n",
                ICM_VERSION_ID / 100.0, model_len, model_depth,
                periodicity, num_nodes);
     else
       {
        char  line [ID_STRING_LEN] = {'\0'};
        int  param [NUM_FIXED_LENGTH_PARAMS];

        sprintf (line, ">ver = %.2f  len = %d  depth = %d"
                 "  periodicity = %d  nodes = %d\n", 
                 ICM_VERSION_ID / 100.0, model_len, model_depth,
                 periodicity, num_nodes);
        assert (int (strlen (line)) < ID_STRING_LEN);
        fwrite (line, sizeof (char), ID_STRING_LEN, fp);

        param [0] = ICM_VERSION_ID;
        param [1] = ID_STRING_LEN;
        param [2] = model_len;
        param [3] = model_depth;
        param [4] = periodicity;
        param [5] = num_nodes;

        fwrite (param, sizeof (int), NUM_FIXED_LENGTH_PARAMS, fp);
       }

   return;
  }



ICM_Training_t :: ICM_Training_t
    (int w, int d, int p)  :  ICM_t (w, d, p)

//  Constructor for the ICM

  {
   int  (* ptr) [ALPHA_SQUARED];
   int  i, j;

   train = (ICM_Training_Node_t * *)
                  Safe_calloc (periodicity, sizeof (ICM_Training_Node_t *),
                  __FILE__, __LINE__);

   if  (model_depth == 0)
       ptr = NULL;
     else
       ptr = count_memory = (int (*) [ALPHA_SQUARED])
               Safe_calloc (periodicity * num_nodes * (model_len - 1),
                            sizeof (int [ALPHA_SQUARED]), __FILE__, __LINE__);

   for  (i = 0;  i < periodicity;  i ++)
     {
      train [i] = (ICM_Training_Node_t *)
                    Safe_calloc (num_nodes, sizeof (ICM_Training_Node_t),
                    __FILE__, __LINE__);

      for  (j = 0;  j < num_nodes;  j ++)
        {
         train [i] [j] . count = ptr;
         ptr += model_len - 1;
        }
     }
  }



ICM_Training_t :: ~ ICM_Training_t ()

//  Destroy this ICM

  {
   int  i;

   free (count_memory);
   for  (i = 0;  i < periodicity;  i ++)
     free (train [i]);
   free (train);
  }



void  ICM_Training_t :: Complete_Tree
    (const vector <char *> & data)

//  Fill in the remaining nodes below the root in this model.
//  Starting with the root, restrict each character at the
//  mutual-information position to generate the child nodes.
//  For each child count how many times the sequence with the
//  designated characters occurs and from those counts
//  calculate the max mutual-information position for each child.
//  Keep doing this for every node until either  model_depth  is
//  reached or there is not enough data to go any deeper.
//  Use the IMM interpolation scheme to set probabilities
//  in the low-count case.

  {
   int  sub, max_pos, string_ct;
   double  best_info, next_info, used_info;
   int  sum;
   int  symbol;
     // subscript of character in alphabet
   int  first_node, last_node, nodes_on_level;
   int  frame, level;
   int  i, j, k;

   string_ct = int (data . size ());

   first_node = 1;
   nodes_on_level = ALPHABET_SIZE;

   for  (level = 1;  level <= model_depth;  level ++)
     {
      for  (i = 0;  i < string_ct;  i ++)
        Count_Char_Pairs_Restricted (data [i], level);

      last_node = first_node + nodes_on_level - 1;

      for  (frame = 0;  frame < periodicity;  frame ++)
        {
         symbol = 0;
         for  (sub = first_node;  sub <= last_node;
                 sub ++, symbol = (symbol + 1) % ALPHABET_SIZE)
           {
            int  final_char_ct [ALPHABET_SIZE] = {0};
              // number of occurrences of each symbol in the last position

            train [frame] [sub] . mut_info_seq = (short int) symbol;

            if  (score [frame] [PARENT (sub)] . mut_info_pos < 0)
                // Don't process this node; stopped at parent
                {
                 score [frame] [sub] . mut_info_pos = -2;
                 continue;
                }

            // sum over k of  count [i] [k]  is same for any i
            sum = 0;
            for  (i = k = 0;  i < ALPHABET_SIZE;  i ++)
              for  (j = 0;  j < ALPHABET_SIZE;  j ++)
                {
                 sum += train [frame] [sub] . count [0] [k];
                 final_char_ct [j] += train [frame] [sub] . count [0] [k];
                 k ++;
                }

            // find the position pair with the max mutual information
            max_pos = 0;
            best_info = Get_Mutual_Info (train [frame] [sub] . count [0],
                                         ALPHABET_SIZE, sum);
            used_info = best_info;

            for  (i = 1;  i < model_len - 1;  i ++)
              {
               next_info = Get_Mutual_Info (train [frame] [sub] . count [i],
                                            ALPHABET_SIZE, sum);
               if  (next_info >= best_info)
                   {
                    used_info = best_info = next_info;
                    max_pos = i;
                   }
               else if  (next_info >= (best_info / (1.0 + MUT_INFO_BIAS)))
                   {
                    // prefer positions to the right (i.e., closer to the
                    // predicted base) if mutual-information values are
                    // close enough
                    max_pos = i;
                    used_info = next_info;
                   }
              }

            if  (best_info <= MUT_INFO_EPSILON && sum < SAMPLE_SIZE_BOUND)
                // Not enough information gain; don't go down tree any further
                max_pos = -1;

            score [frame] [sub] . mut_info_pos = (short int) max_pos;
#if  STORE_MUT_INFO
            score [frame] [sub] . mut_info = float (used_info);
#endif

            if  (Verbose > 1)
                {
                 fprintf (stderr,
                      "frame = %d  node = %d  mut_info_pos = %d  mut_info = %.3f  cts: ",
                          frame, sub, max_pos, best_info);
                 for  (i = 0;  i < ALPHABET_SIZE;  i ++)
                   fprintf (stderr, " %4d", final_char_ct [i]);
                 fputc ('\n', stderr);
                }

            Interpolate_Probs (frame, sub, final_char_ct);

#if  0
// Should be in a separate method
            print_node (print_string, level, sub, mut_info[max_pos],frame, ending_sum);
#endif
           }
        }

      first_node = last_node + 1;
      nodes_on_level *= ALPHABET_SIZE;

      if  (Verbose > 0)
          fprintf (stderr, "Training done for level %d\n", level);
     }

   return;
  }



void  ICM_Training_t :: Count_Char_Pairs_Restricted
    (const char * string, int level)

//  For each complete window of length  model_len  in  string
//  determine the appropriate frame of the model and the node
//  at level  level  to which it should contribute counts.  Then
//  for each position  j = 0 .. (model_len - 2)  add 1 to
//  ct [j] [p]  where  p  is the index of the character
//  pair at positions  j  and  (model_len - 1)  in the window.

  {
   ICM_Training_Node_t  * node;
   int  start, stop, end, frame, last_char_sub;
   int  i, j;

   start = 0;
   end = int (strlen (string));
   frame = model_len % periodicity;

   for  (stop = model_len - 1;  stop < end;  start ++, stop ++)
     {
      node = Get_Training_Node (string + start, frame, level);
      if  (node != NULL)
          {
           last_char_sub = Subscript (string [stop]);
           for  (i = 0;  i < model_len - 1;  i ++)
             {
              j = ALPHABET_SIZE * Subscript (string [start + i])
                      + last_char_sub;
              node -> count [i] [j] ++;
             }
          }

      frame ++;
      if  (frame == periodicity)
          frame = 0;
     }

   return;
  }



ICM_Training_Node_t *  ICM_Training_t :: Get_Training_Node
    (const char * w, int frame, int level)

//  Find the node at level  level  in the  frame 'th segment
//  of the model that matches the string window  w .
//  Return a pointer to that node if it's valid; otherwise,
//  return  NULL;

  {
   int  i, j, sub;

   sub = 0;

   for  (i = 0;  i < level;  i ++)
     {
      j = score [frame] [sub] . mut_info_pos;
      if  (j < 0)
          return  NULL;

      sub = sub * ALPHABET_SIZE + Subscript (w [j]) + 1;
     }

   return  train [frame] + sub;
  }



void  ICM_Training_t :: Interpolate_Probs
    (int frame, int sub, int ct [])

//  Set the probabilities for node at subscript  sub  in the
//  frame 'th segment of the model using the frequencies in  ct
//  and interpolating with the probabilities in this node's
//  parent if the sum of the counts is sufficiently small

  {
   double  expected, chi2_stat, lambda, total_sum;
   int  parent;
   int  i;

   parent = PARENT (sub);

   total_sum = 0.0;
   for  (i = 0;  i < ALPHABET_SIZE;  i ++)
     total_sum += ct [i];

   // set probabilities directly including small bias from parent probabilities
   // to prevent zero probabilities
   for (i = 0;  i < ALPHABET_SIZE;  i ++)
     score [frame] [sub] . prob [i]
         = (ct [i] + PSEUDO_COUNT * score [frame] [parent] . prob [i])
               / (total_sum + PSEUDO_COUNT);

   // if there are enough samples those probabilities are OK and there
   // is no interpolation
   if  (total_sum >= SAMPLE_SIZE_BOUND)
       return;

   // calculate the chi-squared statistic
   chi2_stat = 0.0;
   for  (i = 0;  i < ALPHABET_SIZE;  i ++)
     {
      expected = total_sum * score [frame] [parent] . prob [i];
      if  (expected > 0.0)
          chi2_stat += pow (ct [i] - expected, 2.0) / expected;
     }
  
   // search for chi2_stat in table to get corresponding significance value
   for  (i = 0;  i < NUM_CHI2_ENTRIES && CHI2_VAL [i] < chi2_stat;  i ++)
     ;

   // determine interpolation coefficient lambda.  The assigned probs will be
   // lambda of this node's plus (1 - lambda) of the parent's
   if  (i == 0)
       lambda = 0.0;
   else if  (i == NUM_CHI2_ENTRIES)
       lambda = 1.0;
     else 
       lambda = CHI2_SIGNIFICANCE [i-1]
                  + ((chi2_stat - CHI2_VAL [i - 1])
                          / (CHI2_VAL [i] - CHI2_VAL [i - 1])) 
                      * (CHI2_SIGNIFICANCE [i] - CHI2_SIGNIFICANCE [i - 1]);

   // further weight lambda by the number of sample windows at this node
   lambda *= total_sum / SAMPLE_SIZE_BOUND;
   if  (lambda > 1.0)
       lambda = 1.0;

   // do the interpolation
   for  (i = 0;  i < ALPHABET_SIZE;  i ++)
     {
      score [frame] [sub] . prob [i] *= lambda;
      score [frame] [sub] . prob [i]
          += (1.0 - lambda) * score [frame] [parent] . prob [i];
     }

   return;
  }



void  ICM_Training_t :: Take_Logs
    (void)

//  Take natural logarithms of all probabilities in this model

  {
   int  i, j, frame;

   for  (frame = 0;  frame < periodicity;  frame ++)
     for  (i = 0;  i < num_nodes;  i ++)
       for  (j = 0;  j < ALPHABET_SIZE;  j ++)
         if  (score [frame] [i] . prob [j] > 0.0)
             score [frame] [i] . prob [j]
                 = float (log (score [frame] [i] . prob [j]));
           else
             score [frame] [i] . prob [j] = - FLT_MAX;

   return;
  }



void  ICM_Training_t :: Train_Model
    (const vector <char *> & data)

//  Calculate the probabilities for this model based on the
//  strings in  data .

  {
   int  frame, string_ct;
   
   string_ct = int (data . size ());

   for  (frame = 0;  frame < periodicity;  frame ++)
     {
      int  offset;
        // where first window should start in the string
      int  final_char_ct [ALPHABET_SIZE] = {0};
        // number of occurrences of each character as last in window
      double  best_info, next_info;
      int  max_pos, sum;
      int  i, j, k;

      offset = frame - (model_len % periodicity);
      if  (offset < 0)
          offset += periodicity;

      if  (model_depth == 0)
          {
           for  (i = 0;  i < string_ct;  i ++)
             Count_Single_Chars (final_char_ct, data [i] + offset,
                                 model_len, periodicity);
           sum = 0;
           for  (i = 0;  i < ALPHABET_SIZE;  i ++)
             sum+= final_char_ct [i];
           for  (i = 0;  i < ALPHABET_SIZE;  i ++)
             score [frame] [0] . prob [i]
               = (final_char_ct [i] + float (PSEUDO_COUNT / ALPHABET_SIZE))
                   / (sum + PSEUDO_COUNT);
           score [frame] [0] . mut_info_pos = -1;
          }
        else
          {
           for  (i = 0;  i < string_ct;  i ++)
             Count_Char_Pairs (train [frame] [0] . count,
                               data [i] + offset, model_len, periodicity);

           // sum over k of  count [i] [k]  is same for any i
           sum = 0;
           for  (i = k = 0;  i < ALPHABET_SIZE;  i ++)
             for  (j = 0;  j < ALPHABET_SIZE;  j ++)
               {
                sum += train [frame] [0] . count [0] [k];
                final_char_ct [j] += train [frame] [0] . count [0] [k];
                k ++;
               }
           for  (j = 0;  j < ALPHABET_SIZE;  j ++)
             score [frame] [0] . prob [j]
               = (final_char_ct [j] + float (PSEUDO_COUNT / ALPHABET_SIZE))
                   / float (sum + PSEUDO_COUNT);

           // find the position pair with the max mutual information
           max_pos = 0;
           best_info = Get_Mutual_Info (train [frame] [0] . count [0],
                                        ALPHABET_SIZE, sum);

           for  (i = 1;  i < model_len - 1;  i ++)
             {
              next_info = Get_Mutual_Info (train [frame] [0] . count [i],
                                           ALPHABET_SIZE, sum);
              if  (next_info >= best_info)
                  {
                   best_info = next_info;
                   max_pos = i;
                  }
              else if  (next_info >= (best_info / (1.0 + MUT_INFO_BIAS)))
                  max_pos = i;
                  // prefer positions to the right (i.e., closer to the
                  // predicted base) if mutual-information values are
                  // close enough
             }

           score [frame] [0] . mut_info_pos = (short int) max_pos;
#if  STORE_MUT_INFO
           score [frame] [0] . mut_info = float (best_info);
#endif
          }
      if  (Verbose > 1)
          {
           fprintf (stderr, "frame = %d  node = %d  mut_info_pos = %d  mut_info = %.3f  cts: ",
                    frame, 0, max_pos, best_info);
           for  (i = 0;  i < ALPHABET_SIZE;  i ++)
             fprintf (stderr, " %4d", final_char_ct [i]);
           fputc ('\n', stderr);
          }

#if  0
// Should be in a separate method
      print_node (print_string, 0, 0, mut_info [Node [frame] [0] . mut_info_pos],
                  frame, final_char_ct);
#endif
     }

   Complete_Tree (data);

   Take_Logs ();

   return;
  }



Fixed_Length_ICM_t :: Fixed_Length_ICM_t
    (int len, int sp, int * perm, ICM_Model_t mt)

//  Construct a  Fixed_Length_ICM_t  of length  len  using
//  perm  for the order of bases

  {
   length = len;
   if  (perm == NULL)
       permutation = NULL;
     else
       {
        int  i;

        permutation = new int [len];
        for  (i = 0;  i < len;  i ++)
          permutation [i] = perm [i];
       }
   special_position = sp;
   model_type = mt;
  }



Fixed_Length_ICM_t :: ~ Fixed_Length_ICM_t
    ()

//  Destroy this  Fixed_Length_ICM_t

  {
   if  (permutation != NULL)
       delete [] permutation;
  }



void  Fixed_Length_ICM_t :: read
    (const char * path)

//  Read the  Fixed_Length_ICM_t  in from the file at  path .

  {
   FILE  * fp;
   char  line [ID_STRING_LEN];
   int  param [NUM_FIXED_LENGTH_PARAMS];
   int  i, n;

   // free memory from previous version
   n = sub_model . size ();
   for  (i = 0;  i < n;  i ++)
     delete sub_model [i];

   fp = File_Open (path, "r");     // Should be "rb"?

   fread (line, sizeof (char), ID_STRING_LEN, fp);    // skip the text header line

   if  (fread (param, sizeof (int), NUM_FIXED_LENGTH_PARAMS, fp)
          != NUM_FIXED_LENGTH_PARAMS)
       {
        fprintf (stderr, "ERROR reading file \"%s\"\n", path);
        exit (EXIT_FAILURE);
       }

   if  (ICM_VERSION_ID != param [0])
       {
        fprintf (stderr, "Bad ICM version = %d  should be %d\n",
                 param [0], ICM_VERSION_ID);
        exit (EXIT_FAILURE);
       }
   if  (ID_STRING_LEN != param [1])
       {
        fprintf (stderr, "Bad ID_STRING_LEN = %d  should be %d\n",
                 param [1], ID_STRING_LEN);
        exit (EXIT_FAILURE);
       }

   length = param [2];
   max_depth = param [3];
   special_position = param [4];
   model_type = ICM_Model_t (param [5]);

   permutation = new int [length];
   fread (permutation, sizeof (int), length, fp);

   for  (i = 0;  i < length;  i ++)
     {
      ICM_t  * p;

      p = new  ICM_t (1, 0, 1);
      p -> Input (fp);

      sub_model . push_back (p);
     }

   return;
  }



double  Fixed_Length_ICM_t :: Score_Window
    (char * w)

//  Return the score of this model on string  w

  {
   static char  * buff = NULL;
   static int  buff_len = 0;
   double  score = 0.0;
   int  i;

   if  (length > buff_len)
       {
        buff = (char *) Safe_realloc (buff, length, __FILE__, __LINE__);
        buff_len = length;
       }

   strncpy (buff, w, length);
   if  (permutation != NULL)
       Permute_String (buff, permutation, length);

   for  (i = 0;  i < length;  i ++)
     {
      if  (buff [i] == '\0')
          {
           fprintf (stderr, "ERROR:  String \"%s\" too short in Score_Window\n",
                    buff);
           exit (EXIT_FAILURE);
          }
      score += sub_model [i] -> Full_Window_Prob (buff, 0);
     }

   return  score;
  }



double  Fixed_Length_ICM_t :: subrange_score
    (char * w, int lo, int hi)

//  Return the score of this model on the portion of window
//  w  between positions  lo  and  hi .   lo  and  hi  are
//  in gap-based coordinates and  w  should point to the beginning
//  of the full-window (i.e., not to where  lo  is).

  {
   static char  * buff = NULL;
   static int  buff_len = 0;
   double  score = 0.0;
   int  i;

   if  (lo < 0 || length < hi || hi < lo)
       {
        fprintf (stderr, "ERROR:  Bad range  lo = %d  hi = %d  in subrange_score\n",
                lo, hi);

        exit (EXIT_FAILURE);
       }

   if  (length > buff_len)
       {
        buff = (char *) Safe_realloc (buff, length, __FILE__, __LINE__);
        buff_len = length;
       }

   strncpy (buff, w, length);
   if  (permutation != NULL)
       Permute_String (buff, permutation, length);

   for  (i = lo;  i < hi;  i ++)
     {
      if  (buff [i] == '\0')
          {
           fprintf (stderr, "ERROR:  String \"%s\" too short in Score_Window\n",
                    buff);
           exit (EXIT_FAILURE);
          }
      score += sub_model [i] -> Full_Window_Prob (buff, 0);
     }

   return  score;
  }



Fixed_Length_ICM_Training_t :: Fixed_Length_ICM_Training_t
    (int len, int md, int sp, int * perm, ICM_Model_t mt)

//  Construct a  Fixed_Length_ICM_Training_t  of length  len  using
//  perm  for the order of bases

  {
   length = len;
   max_depth = md;
   special_position = sp;
   if  (perm == NULL)
       permutation = NULL;
     else
       {
        int  i;

        permutation = new int [len];
        for  (i = 0;  i < len;  i ++)
          permutation [i] = perm [i];
       }
   model_type = mt;
  }



Fixed_Length_ICM_Training_t :: ~ Fixed_Length_ICM_Training_t
       ()

//  Destroy this  Fixed_Length_ICM_Training_t

  {
   int  i, n;

   if  (permutation != NULL)
       delete [] permutation;

   n = int (sub_model . size ());
   for  (i = 0;  i < n;  i ++)
     delete sub_model [i];
  }



void  Fixed_Length_ICM_Training_t :: Output
    (FILE * fp, bool binary_form)

//  Output the contents of this model to  fp .
//  If  binary_form  is true, then do it in binary; otherwise,
//  write an ascii text version.

  {
   int  i;

   Write_Header (fp, binary_form);

   for  (i = 0;  i < length;  i ++)
     sub_model [i] -> Output (fp, binary_form);

   return;
  }



void  Fixed_Length_ICM_Training_t :: Train_Model
    (vector <char *> & data)

//  Calculate the probabilities for this model based on the
//  strings in  data .

  {
   vector <char *>  sub_data;
   ICM_Training_t  * mp;
   int  depth, string_ct;
   int  i, j;
   
   string_ct = int (data . size ());

   if  (permutation != NULL)
       Permute_Data (data, permutation);

   // Make a vector with enough room to hold the substrings
   // of data used to build the sub-models

   for  (j = 0;  j < string_ct;  j ++)
     {
      char  * tmp;

      tmp = (char *) Safe_malloc (length + 1, __FILE__, __LINE__);
      sub_data . push_back (tmp);
     }

   for  (i = 1;  i <= length;  i ++)
     {
      for  (j = 0;  j < string_ct;  j ++)
        {
         strncpy (sub_data [j], data [j], i);
         sub_data [j] [i] = '\0';
        }

      depth = i - 1;
      if  (depth > max_depth)
          depth = max_depth;
      mp = new ICM_Training_t (i, depth, 1);
      mp -> Train_Model (sub_data);
      sub_model . push_back (mp);
     }

   // Free string memory allocated for  sub_data

   for  (j = 0;  j < string_ct;  j ++)
     free (sub_data [j]);

   return;
  }



void  Fixed_Length_ICM_Training_t :: Write_Header
    (FILE * fp, bool binary_form)

//  Send to  fp  the parameter information for this model.
//  binary_form  determines whether the format is binary or
//  Ascii readable (for debugging purposes only)

  {
   int  i;

   if  (! binary_form)
       {
        fprintf (fp, "ver=%.2f  len=%d  depth=%d  special=%d  type=%d",
                 ICM_VERSION_ID / 100.0, length, max_depth, special_position,
                 int (model_type));
        for  (i = 0;  i < length;  i ++)
          {
           if  (i == 0)
               fprintf (fp, "  %d", permutation == NULL ? i : permutation [i]);
             else
               fprintf (fp, ",%d", permutation == NULL ? i : permutation [i]);
          }
        fprintf (fp, "\n");
       }
     else
       {
        char  line [ID_STRING_LEN] = {'\0'};
        char  perm [ID_STRING_LEN] = {'\0'};
        int  param [NUM_FIXED_LENGTH_PARAMS];

        sprintf (line, ">ver=%.2f  len=%d  depth=%d  special=%d  type=%d",
                 ICM_VERSION_ID / 100.0, length, max_depth,
                 special_position, int (model_type));
        for  (i = 0;  i < length;  i ++)
          {
           if  (i == 0)
               sprintf (perm, "  %d", permutation == NULL ? i : permutation [i]);
             else
               sprintf (perm, ",%d", permutation == NULL ? i : permutation [i]);
           strcat (line, perm);
          }
        strcat (line, "\n");

        assert (int (strlen (line)) < ID_STRING_LEN);
        fwrite (line, sizeof (char), ID_STRING_LEN, fp);

        param [0] = ICM_VERSION_ID;
        param [1] = ID_STRING_LEN;
        param [2] = length;
        param [3] = max_depth;
        param [4] = special_position;
        param [5] = int (model_type);

        fwrite (param, sizeof (int), NUM_FIXED_LENGTH_PARAMS, fp);

        if  (permutation != NULL)
             fwrite (permutation, sizeof (int), length, fp);
          else
            {
             int  * tmp;

             tmp = new int [length];
             for  (i = 0;  i < length;  i ++)
               tmp [i] = i;
             fwrite (tmp, sizeof (int), length, fp);
             delete [] tmp;
            }
       }

   return;
  }



void  Count_Char_Pairs
    (int ct [] [ALPHA_SQUARED], char * string, int w, int period)

//  For each complete window of length  w  in  string
//  and for each position  j = 0 .. (w - 2)  add 1 to
//  ct [j] [p]  where  p  is the index of the character
//  pair at positions  j  and  (w - 1)  in the window.
//  The first window starts at the beginning of  string ,
//  and the window advances by  period positions each step
//  as it moves down the string

  {
   int  start, stop, end, i, j, last_char_sub;

   start = 0;
   end = int (strlen (string));

   for  (stop = w - 1;  stop < end;  start += period, stop += period)
     {
      last_char_sub = Subscript (string [stop]);
      for  (i = 0;  i < w - 1;  i ++)
        {
         j = ALPHABET_SIZE * Subscript (string [start + i])
                 + last_char_sub;
         ct [i] [j] ++;
        }
     }

   return;
  }



void  Count_Single_Chars
    (int ct [ALPHABET_SIZE], char * string, int w, int period)

//  For each complete window of length  w  in  string
//  add 1 to  ct [p]  where  p  is the index of the character
//  at the end of the window.
//  The first window starts at the beginning of  string ,
//  and the window advances by  period positions each step
//  as it moves down the string

  {
   int  pos, end, last_char_sub;

   end = int (strlen (string));

   for  (pos = w - 1;  pos < end;  pos += period)
     {
      last_char_sub = Subscript (string [pos]);
      ct [last_char_sub] ++;
     }

   return;
  }



double  Get_Mutual_Info
    (int ct [], int n, int sum)

//  Calculate and return the mutual information for the  n^2
//  counts in  ct  representing frequency of occurrence of
//  pairs of events, where each event has  n  possibilities
//  sum  is the sum of all entries in  ct []

  {
   double  mut_info = 0.0;
   double  * left_prob;
     // probability of each first event in pair
   double  * right_prob;
     // probability of each second event in pair
   int  i, j, k;

   if  (sum == 0)
       return  0.0;

   left_prob = (double * ) Safe_malloc (n * sizeof (double), __FILE__, __LINE__);
   right_prob = (double * ) Safe_malloc (n * sizeof (double), __FILE__, __LINE__);

   for  (i = 0;  i < n;  i ++)
     left_prob [i] = right_prob [i] = 0.0;

   // Calculate  left_prob  and  right_prob
   for  (i = k = 0;  i < n;  i ++)
     for  (j = 0;  j < n;  j ++)
       {
        left_prob [i] += ct [k];
        right_prob [j] += ct [k];
        k ++;
       }
    for  (i = 0;  i < n;  i ++)
      {
       left_prob [i] /= sum;
       right_prob [i] /= sum;
      }

   for  (i = k = 0;  i < n;  i ++)
     for  (j = 0;  j < n;  j ++)
       {
        double  prob = double (ct [k]) / sum;

        if  (prob != 0.0 && left_prob [i] != 0.0 && right_prob [j] != 0.0)
            mut_info += prob * log (prob / (left_prob [i] * right_prob [j]));

        k ++;
       }

   free (left_prob);
   free (right_prob);

   return mut_info;
  }



void  Permute_Data
    (vector <char *> & data, int * perm)

//  Rearrange the characters in each string in  data  according
//  to the permutation in  perm .

  {
   int  len;
   int  i, n;

   n = data . size ();
   if  (n == 0)
       return;

   len = strlen (data [0]);

   for  (i = 0;  i < n;  i ++)
     Permute_String (data [i], perm, len);

   return;
  }



void  Permute_String
    (char * s, int * perm, int n)

//  Rearrange the characters in  s  according
//  to the permutation in  perm .

  {
   static char  * buff = NULL;
   static int  buff_len = 0;
   int  i;

   if  (n > buff_len)
       {
        buff = (char *) Safe_realloc (buff, n, __FILE__, __LINE__);
        buff_len = n;
       }

   for  (i = 0;  i < n;  i ++)
     buff [i] = s [perm [i]];
   strncpy (s, buff, n);

   return;
  }



int  Subscript
    (char ch)

//  Return the subscript equivalent (used in offsets of the
//  model) for character  ch .

  {
   const char  * p;

   p = strchr (ALPHA_STRING, tolower (Filter (ch)));
   if  (p == NULL)
       {
        fprintf (stderr, "ERROR:  Bad character %c in subscript conversion",
                 ch);
        exit (EXIT_FAILURE);
       }

   return  int (p - ALPHA_STRING);
  }