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 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
|
/* vcfnorm.c -- Left-align and normalize indels.
Copyright (C) 2013-2019 Genome Research Ltd.
Author: Petr Danecek <pd3@sanger.ac.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#include <stdio.h>
#include <strings.h>
#include <unistd.h>
#include <getopt.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <inttypes.h>
#include <htslib/vcf.h>
#include <htslib/synced_bcf_reader.h>
#include <htslib/faidx.h>
#include <htslib/khash_str2int.h>
#include "bcftools.h"
#include "rbuf.h"
#define CHECK_REF_EXIT 1
#define CHECK_REF_WARN 2
#define CHECK_REF_SKIP 4
#define CHECK_REF_FIX 8
#define MROWS_SPLIT 1
#define MROWS_MERGE 2
// for -m+, mapping from allele indexes of a single input record
// to allele indexes of output record
typedef struct
{
int nals, mals, *map;
}
map_t;
// primitive comparison of two records' alleles via hashes; normalized alleles assumed
typedef struct
{
int n; // number of alleles
char *ref, *alt;
void *hash;
}
cmpals1_t;
typedef struct
{
cmpals1_t *cmpals;
int ncmpals, mcmpals;
}
cmpals_t;
typedef struct
{
char *tseq, *seq;
int mseq;
bcf1_t **lines, **tmp_lines, **alines, **blines, *mrow_out;
int ntmp_lines, mtmp_lines, nalines, malines, nblines, mblines;
map_t *maps; // mrow map for each buffered record
char **als;
int mmaps, nals, mals;
uint8_t *tmp_arr1, *tmp_arr2, *diploid;
int32_t *int32_arr;
int ntmp_arr1, ntmp_arr2, nint32_arr;
kstring_t *tmp_str;
kstring_t *tmp_als, tmp_als_str;
int ntmp_als;
rbuf_t rbuf;
int buf_win; // maximum distance between two records to consider
int aln_win; // the realignment window size (maximum repeat size)
bcf_srs_t *files; // using the synced reader only for -r option
bcf_hdr_t *hdr;
cmpals_t cmpals_in, cmpals_out;
faidx_t *fai;
struct { int tot, set, swap; } nref;
char **argv, *output_fname, *ref_fname, *vcf_fname, *region, *targets;
int argc, rmdup, output_type, n_threads, check_ref, strict_filter, do_indels;
int nchanged, nskipped, nsplit, ntotal, mrows_op, mrows_collapse, parsimonious;
int record_cmd_line, force, force_warned;
}
args_t;
static inline int replace_iupac_codes(char *seq, int nseq)
{
// Replace ambiguity codes with N for now, it awaits to be seen what the VCF spec codifies in the end
int i, n = 0;
for (i=0; i<nseq; i++)
{
char c = toupper(seq[i]);
if ( c!='A' && c!='C' && c!='G' && c!='T' && c!='N' ) { seq[i] = 'N'; n++; }
}
return n;
}
static inline int has_non_acgtn(char *seq, int nseq)
{
char *end = seq + nseq;
while ( *seq && seq<end )
{
char c = toupper(*seq);
if ( c!='A' && c!='C' && c!='G' && c!='T' && c!='N' ) return 1;
seq++;
}
return 0;
}
static void seq_to_upper(char *seq, int len)
{
int i;
if ( len )
for (i=0; i<len; i++) seq[i] = nt_to_upper(seq[i]);
else
for (i=0; seq[i]; i++) seq[i] = nt_to_upper(seq[i]);
}
static void fix_ref(args_t *args, bcf1_t *line)
{
int reflen = strlen(line->d.allele[0]);
int i, maxlen = reflen, len;
for (i=1; i<line->n_allele; i++)
{
int len = strlen(line->d.allele[i]);
if ( maxlen < len ) maxlen = len;
}
char *ref = faidx_fetch_seq(args->fai, (char*)bcf_seqname(args->hdr,line), line->pos, line->pos+maxlen-1, &len);
if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
replace_iupac_codes(ref,len);
args->nref.tot++;
// is the REF different?
if ( !strncasecmp(line->d.allele[0],ref,reflen) ) { free(ref); return; }
// is the REF allele missing or N?
if ( reflen==1 && (line->d.allele[0][0]=='.' || line->d.allele[0][0]=='N' || line->d.allele[0][0]=='n') )
{
line->d.allele[0][0] = ref[0];
args->nref.set++;
free(ref);
bcf_update_alleles(args->hdr,line,(const char**)line->d.allele,line->n_allele);
return;
}
// does REF contain non-standard bases?
if ( replace_iupac_codes(line->d.allele[0],strlen(line->d.allele[0])) )
{
args->nref.set++;
bcf_update_alleles(args->hdr,line,(const char**)line->d.allele,line->n_allele);
if ( !strncasecmp(line->d.allele[0],ref,reflen) ) { free(ref); return; }
}
// is it swapped?
for (i=1; i<line->n_allele; i++)
{
int len = strlen(line->d.allele[i]);
if ( !strncasecmp(line->d.allele[i],ref,len) ) break;
}
kstring_t str = {0,0,0};
if ( i==line->n_allele )
{
// none of the alternate alleles matches the reference
if ( line->n_allele>1 )
args->nref.set++;
else
args->nref.swap++;
kputs(line->d.allele[0],&str);
kputc(',',&str);
for (i=1; i<line->n_allele; i++)
{
kputs(line->d.allele[i],&str);
kputc(',',&str);
}
kputc(ref[0],&str);
bcf_update_alleles_str(args->hdr,line,str.s);
str.l = 0;
}
else
args->nref.swap++;
free(ref);
// swap the alleles
int j;
kputs(line->d.allele[i],&str);
for (j=1; j<i; j++)
{
kputc(',',&str);
kputs(line->d.allele[j],&str);
}
kputc(',',&str);
kputs(line->d.allele[0],&str);
for (j=i+1; j<line->n_allele; j++)
{
kputc(',',&str);
kputs(line->d.allele[j],&str);
}
bcf_update_alleles_str(args->hdr,line,str.s);
// swap genotypes
int ntmp = args->ntmp_arr1 / sizeof(int32_t); // reuse tmp_arr declared as uint8_t
int ngts = bcf_get_genotypes(args->hdr, line, &args->tmp_arr1, &ntmp);
args->ntmp_arr1 = ntmp * sizeof(int32_t);
int32_t *gts = (int32_t*) args->tmp_arr1;
int ni = 0;
for (j=0; j<ngts; j++)
{
if ( gts[j]==bcf_gt_unphased(0) ) { gts[j] = bcf_gt_unphased(i); ni++; }
else if ( gts[j]==bcf_gt_phased(0) ) { gts[j] = bcf_gt_phased(i); ni++; }
else if ( gts[j]==bcf_gt_unphased(i) ) gts[j] = bcf_gt_unphased(0);
else if ( gts[j]==bcf_gt_phased(i) ) gts[j] = bcf_gt_phased(0);
}
bcf_update_genotypes(args->hdr,line,gts,ngts);
// update AC
int nac = bcf_get_info_int32(args->hdr, line, "AC", &args->tmp_arr1, &ntmp);
args->ntmp_arr1 = ntmp * sizeof(int32_t);
if ( i <= nac )
{
int32_t *ac = (int32_t*)args->tmp_arr1;
ac[i-1] = ni;
bcf_update_info_int32(args->hdr, line, "AC", ac, nac);
}
free(str.s);
}
static void fix_dup_alt(args_t *args, bcf1_t *line)
{
// update alleles, create a mapping between old and new indexes
hts_expand(uint8_t,line->n_allele,args->ntmp_arr1,args->tmp_arr1);
args->tmp_arr1[0] = 0; // ref always unchanged
int i, j, nals = line->n_allele, nals_ori = line->n_allele;
for (i=1, j=1; i<line->n_allele; i++)
{
if ( strcasecmp(line->d.allele[0],line->d.allele[i]) )
{
args->tmp_arr1[i] = j++;
continue;
}
args->tmp_arr1[i] = 0;
nals--;
}
for (i=1, j=1; i<line->n_allele; i++)
{
if ( !args->tmp_arr1[i] ) continue;
line->d.allele[j++] = line->d.allele[i];
}
bcf_update_alleles(args->hdr, line, (const char**)line->d.allele, nals);
// update genotypes
int ntmp = args->ntmp_arr2 / sizeof(int32_t); // reuse tmp_arr declared as uint8_t
int ngts = bcf_get_genotypes(args->hdr, line, &args->tmp_arr2, &ntmp);
args->ntmp_arr2 = ntmp * sizeof(int32_t);
int32_t *gts = (int32_t*) args->tmp_arr2;
int changed = 0;
for (i=0; i<ngts; i++)
{
if ( bcf_gt_is_missing(gts[i]) || gts[i]==bcf_int32_vector_end ) continue;
int ial = bcf_gt_allele(gts[i]);
if ( ial<nals_ori && ial==args->tmp_arr1[ial] ) continue;
int ial_new = ial<nals_ori ? args->tmp_arr1[ial] : 0;
gts[i] = bcf_gt_is_phased(gts[i]) ? bcf_gt_phased(ial_new) : bcf_gt_unphased(ial_new);
changed = 1;
}
if ( changed ) bcf_update_genotypes(args->hdr,line,gts,ngts);
}
#define ERR_DUP_ALLELE -2
#define ERR_REF_MISMATCH -1
#define ERR_OK 0
#define ERR_SYMBOLIC 1
#define ERR_SPANNING_DELETION 2
static int realign(args_t *args, bcf1_t *line)
{
bcf_unpack(line, BCF_UN_STR);
// Sanity check REF
int i, nref, reflen = strlen(line->d.allele[0]);
char *ref = faidx_fetch_seq(args->fai, (char*)args->hdr->id[BCF_DT_CTG][line->rid].key, line->pos, line->pos+reflen-1, &nref);
if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", args->hdr->id[BCF_DT_CTG][line->rid].key, (int64_t) line->pos+1);
seq_to_upper(ref,0);
replace_iupac_codes(ref,nref); // any non-ACGT character in fasta ref is replaced with N
// does VCF REF contain non-standard bases?
if ( has_non_acgtn(line->d.allele[0],reflen) )
{
if ( args->check_ref==CHECK_REF_EXIT )
error("Non-ACGTN reference allele at %s:%"PRId64" .. REF_SEQ:'%s' vs VCF:'%s'\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,ref,line->d.allele[0]);
if ( args->check_ref & CHECK_REF_WARN )
fprintf(stderr,"NON_ACGTN_REF\t%s\t%"PRId64"\t%s\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,line->d.allele[0]);
free(ref);
return ERR_REF_MISMATCH;
}
if ( strcasecmp(ref,line->d.allele[0]) )
{
if ( args->check_ref==CHECK_REF_EXIT )
error("Reference allele mismatch at %s:%"PRId64" .. REF_SEQ:'%s' vs VCF:'%s'\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,ref,line->d.allele[0]);
if ( args->check_ref & CHECK_REF_WARN )
fprintf(stderr,"REF_MISMATCH\t%s\t%"PRId64"\t%s\t%s\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,line->d.allele[0],ref);
free(ref);
return ERR_REF_MISMATCH;
}
free(ref);
ref = NULL;
if ( line->n_allele == 1 ) // a REF
{
if ( line->rlen > 1 )
{
line->d.allele[0][1] = 0;
bcf_update_alleles(args->hdr,line,(const char**)line->d.allele,line->n_allele);
}
return ERR_OK;
}
if ( bcf_get_variant_types(line)==VCF_BND ) return ERR_SYMBOLIC; // breakend, not an error
// make a copy of each allele for trimming
hts_expand0(kstring_t,line->n_allele,args->ntmp_als,args->tmp_als);
kstring_t *als = args->tmp_als;
for (i=0; i<line->n_allele; i++)
{
if ( line->d.allele[i][0]=='<' ) return ERR_SYMBOLIC; // symbolic allele
if ( line->d.allele[i][0]=='*' ) return ERR_SPANNING_DELETION; // spanning deletion
if ( has_non_acgtn(line->d.allele[i],line->shared.l) )
{
if ( args->check_ref==CHECK_REF_EXIT )
error("Non-ACGTN alternate allele at %s:%"PRId64" .. VCF:'%s'\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,line->d.allele[i]);
if ( args->check_ref & CHECK_REF_WARN )
fprintf(stderr,"NON_ACGTN_ALT\t%s\t%"PRId64"\t%s\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1,line->d.allele[i]);
return ERR_REF_MISMATCH;
}
als[i].l = 0;
kputs(line->d.allele[i], &als[i]);
seq_to_upper(als[i].s,0);
if ( i>0 && als[i].l==als[0].l && !strcasecmp(als[0].s,als[i].s) ) return ERR_DUP_ALLELE;
}
// trim from right
int ori_pos = line->pos;
while (1)
{
// is the rightmost base identical in all alleles?
int min_len = als[0].l;
for (i=1; i<line->n_allele; i++)
{
if ( toupper(als[0].s[ als[0].l-1 ])!=toupper(als[i].s[ als[i].l-1 ]) ) break;
if ( als[i].l < min_len ) min_len = als[i].l;
}
if ( i!=line->n_allele ) break; // there are differences, cannot be trimmed
if ( min_len<=1 && line->pos==0 ) break;
int pad_from_left = 0;
for (i=0; i<line->n_allele; i++) // trim all alleles
{
als[i].l--;
if ( !als[i].l ) pad_from_left = 1;
}
if ( pad_from_left )
{
int npad = line->pos >= args->aln_win ? args->aln_win : line->pos;
free(ref);
ref = faidx_fetch_seq(args->fai, (char*)args->hdr->id[BCF_DT_CTG][line->rid].key, line->pos-npad, line->pos-1, &nref);
if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", args->hdr->id[BCF_DT_CTG][line->rid].key, (int64_t) line->pos-npad+1);
replace_iupac_codes(ref,nref);
for (i=0; i<line->n_allele; i++)
{
ks_resize(&als[i], als[i].l + npad);
if ( als[i].l ) memmove(als[i].s+npad,als[i].s,als[i].l);
memcpy(als[i].s,ref,npad);
als[i].l += npad;
}
line->pos -= npad;
}
}
free(ref);
// trim from left
int ntrim_left = 0;
while (1)
{
// is the first base identical in all alleles?
int min_len = als[0].l - ntrim_left;
for (i=1; i<line->n_allele; i++)
{
if ( als[0].s[ntrim_left]!=als[i].s[ntrim_left] ) break;
if ( min_len > als[i].l - ntrim_left ) min_len = als[i].l - ntrim_left;
}
if ( i!=line->n_allele || min_len<=1 ) break; // there are differences, cannot be trimmed
ntrim_left++;
}
if ( ntrim_left )
{
for (i=0; i<line->n_allele; i++)
{
memmove(als[i].s,als[i].s+ntrim_left,als[i].l-ntrim_left);
als[i].l -= ntrim_left;
}
line->pos += ntrim_left;
}
// Have the alleles changed?
als[0].s[ als[0].l ] = 0; // in order for strcmp to work
if ( ori_pos==line->pos && !strcasecmp(line->d.allele[0],als[0].s) ) return ERR_OK;
// Create new block of alleles and update
args->tmp_als_str.l = 0;
for (i=0; i<line->n_allele; i++)
{
if (i>0) kputc(',',&args->tmp_als_str);
kputsn(als[i].s,als[i].l,&args->tmp_als_str);
}
args->tmp_als_str.s[ args->tmp_als_str.l ] = 0;
bcf_update_alleles_str(args->hdr,line,args->tmp_als_str.s);
args->nchanged++;
// Update INFO/END if necessary
int new_reflen = strlen(line->d.allele[0]);
if ( (ori_pos!=line->pos || reflen!=new_reflen) && bcf_get_info_int32(args->hdr, line, "END", &args->int32_arr, &args->nint32_arr)==1 )
{
// bcf_update_alleles_str() messed up rlen because line->pos changed. This will be fixed by bcf_update_info_int32()
args->int32_arr[0] = line->pos + new_reflen;
bcf_update_info_int32(args->hdr, line, "END", args->int32_arr, 1);
}
return ERR_OK;
}
static void split_info_numeric(args_t *args, bcf1_t *src, bcf_info_t *info, int ialt, bcf1_t *dst)
{
#define BRANCH_NUMERIC(type,type_t) \
{ \
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key); \
int ntmp = args->ntmp_arr1 / sizeof(type_t); \
int ret = bcf_get_info_##type(args->hdr,src,tag,&args->tmp_arr1,&ntmp); \
args->ntmp_arr1 = ntmp * sizeof(type_t); \
assert( ret>0 ); \
type_t *vals = (type_t*) args->tmp_arr1; \
int len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key); \
if ( len==BCF_VL_A ) \
{ \
if ( ret!=src->n_allele-1 ) \
{ \
if ( args->force && !args->force_warned ) \
{ \
fprintf(stderr, \
"Warning: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d\n" \
" (This warning is printed only once.)\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele-1,ret); \
args->force_warned = 1; \
} \
if ( args->force ) \
{ \
bcf_update_info_##type(args->hdr,dst,tag,NULL,0); \
return; \
} \
error("Error: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele-1,ret); \
} \
bcf_update_info_##type(args->hdr,dst,tag,vals+ialt,1); \
} \
else if ( len==BCF_VL_R ) \
{ \
if ( ret!=src->n_allele ) \
{ \
if ( args->force && !args->force_warned ) \
{ \
fprintf(stderr, \
"Warning: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d\n" \
" (This warning is printed only once.)\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele,ret); \
args->force_warned = 1; \
} \
if ( args->force ) \
{ \
bcf_update_info_##type(args->hdr,dst,tag,NULL,0); \
return; \
} \
error("Error: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele,ret); \
} \
if ( ialt!=0 ) vals[1] = vals[ialt+1]; \
bcf_update_info_##type(args->hdr,dst,tag,vals,2); \
} \
else if ( len==BCF_VL_G ) \
{ \
if ( ret!=src->n_allele*(src->n_allele+1)/2 ) \
{ \
if ( args->force && !args->force_warned ) \
{ \
fprintf(stderr, \
"Warning: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d\n" \
" (This warning is printed only once.)\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele*(src->n_allele+1)/2,ret); \
args->force_warned = 1; \
} \
if ( args->force ) \
{ \
bcf_update_info_##type(args->hdr,dst,tag,NULL,0); \
return; \
} \
error("Error: wrong number of fields in INFO/%s at %s:%"PRId64", expected %d, found %d\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele*(src->n_allele+1)/2,ret); \
} \
if ( ialt!=0 ) \
{ \
vals[1] = vals[bcf_alleles2gt(0,ialt+1)]; \
vals[2] = vals[bcf_alleles2gt(ialt+1,ialt+1)]; \
} \
bcf_update_info_##type(args->hdr,dst,tag,vals,3); \
} \
else \
bcf_update_info_##type(args->hdr,dst,tag,vals,ret); \
}
switch (bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key))
{
case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t); break;
case BCF_HT_REAL: BRANCH_NUMERIC(float, float); break;
}
#undef BRANCH_NUMERIC
}
// Find n-th field in a comma-separated list and move it to dst.
// The memory areas may overlap.
#define STR_MOVE_NTH(dst,src,end,nth,len) \
{ \
char *ss = src, *se = src; \
int j = 0; \
while ( *se && se<(end) ) \
{ \
if ( *se==',' ) \
{ \
if ( j==nth ) break; \
j++; \
ss = se+1; \
} \
se++; \
} \
if ( j==nth ) \
{ \
int n = se - ss; \
memmove((dst),ss,n); \
src = se; \
len += n; \
} \
else len = -1; \
}
static void split_info_string(args_t *args, bcf1_t *src, bcf_info_t *info, int ialt, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
int ret = bcf_get_info_string(args->hdr,src,tag,&args->tmp_arr1,&args->ntmp_arr1);
assert( ret>0 );
kstring_t str;
str.m = args->ntmp_arr1;
str.l = ret;
str.s = (char*) args->tmp_arr1;
int len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key);
if ( len==BCF_VL_A )
{
char *tmp = str.s;
int len = 0;
STR_MOVE_NTH(str.s,tmp,str.s+str.l,ialt,len);
if ( len<0 ) return; // wrong number of fields: skip
str.s[len] = 0;
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
else if ( len==BCF_VL_R )
{
char *tmp = str.s;
int len = 0;
STR_MOVE_NTH(str.s,tmp,str.s+str.l,0,len);
str.s[len]=','; tmp++; len++;
STR_MOVE_NTH(&str.s[len],tmp,str.s+str.l,ialt,len);
if ( len<0 ) return; // wrong number of fields: skip
str.s[len] = 0;
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
else if ( len==BCF_VL_G )
{
int i0a = bcf_alleles2gt(0,ialt+1), iaa = bcf_alleles2gt(ialt+1,ialt+1);
char *tmp = str.s;
int len = 0;
STR_MOVE_NTH(str.s,tmp,str.s+str.l,0,len);
str.s[len]=','; tmp++; len++;
STR_MOVE_NTH(&str.s[len],tmp,str.s+str.l,i0a-1,len);
if ( len<0 ) return; // wrong number of fields: skip
str.s[len]=','; tmp++; len++;
STR_MOVE_NTH(&str.s[len],tmp,str.s+str.l,iaa-i0a-1,len);
if ( len<0 ) return; // wrong number of fields: skip
str.s[len] = 0;
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
else
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
static void split_info_flag(args_t *args, bcf1_t *src, bcf_info_t *info, int ialt, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
int ret = bcf_get_info_flag(args->hdr,src,tag,&args->tmp_arr1,&args->ntmp_arr1);
bcf_update_info_flag(args->hdr,dst,tag,NULL,ret);
}
static void split_format_genotype(args_t *args, bcf1_t *src, bcf_fmt_t *fmt, int ialt, bcf1_t *dst)
{
int ntmp = args->ntmp_arr1 / 4;
int ngts = bcf_get_genotypes(args->hdr,src,&args->tmp_arr1,&ntmp);
args->ntmp_arr1 = ntmp * 4;
assert( ngts >0 );
int32_t *gt = (int32_t*) args->tmp_arr1;
int i, j, nsmpl = bcf_hdr_nsamples(args->hdr);
ngts /= nsmpl;
for (i=0; i<nsmpl; i++)
{
for (j=0; j<ngts; j++)
{
if ( gt[j]==bcf_int32_vector_end ) break;
if ( bcf_gt_is_missing(gt[j]) || bcf_gt_allele(gt[j])==0 ) continue; // missing allele or ref: leave as is
if ( bcf_gt_allele(gt[j])==ialt+1 )
gt[j] = bcf_gt_unphased(1) | bcf_gt_is_phased(gt[j]); // set to first ALT
else
gt[j] = bcf_gt_unphased(0) | bcf_gt_is_phased(gt[j]); // set to REF
}
gt += ngts;
}
bcf_update_genotypes(args->hdr,dst,args->tmp_arr1,ngts*nsmpl);
}
static void split_format_numeric(args_t *args, bcf1_t *src, bcf_fmt_t *fmt, int ialt, bcf1_t *dst)
{
#define BRANCH_NUMERIC(type,type_t,is_vector_end,set_vector_end) \
{ \
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id); \
int ntmp = args->ntmp_arr1 / sizeof(type_t); \
int nvals = bcf_get_format_##type(args->hdr,src,tag,&args->tmp_arr1,&ntmp); \
args->ntmp_arr1 = ntmp * sizeof(type_t); \
assert( nvals>0 ); \
type_t *vals = (type_t *) args->tmp_arr1; \
int len = bcf_hdr_id2length(args->hdr,BCF_HL_FMT,fmt->id); \
int i, nsmpl = bcf_hdr_nsamples(args->hdr); \
if ( nvals==nsmpl ) /* all values are missing */ \
{ \
bcf_update_format_##type(args->hdr,dst,tag,vals,nsmpl); \
return; \
} \
if ( len==BCF_VL_A ) \
{ \
if ( nvals!=(src->n_allele-1)*nsmpl ) \
{ \
if ( args->force && !args->force_warned ) \
{ \
fprintf(stderr, \
"Warning: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d, found %d. Removing the field.\n" \
" (This warning is printed only once.)\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,(src->n_allele-1)*nsmpl,nvals); \
args->force_warned = 1; \
} \
if ( args->force ) \
{ \
bcf_update_format_##type(args->hdr,dst,tag,NULL,0); \
return; \
} \
error("Error: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d, found %d\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,(src->n_allele-1)*nsmpl,nvals); \
} \
nvals /= nsmpl; \
type_t *src_vals = vals, *dst_vals = vals; \
for (i=0; i<nsmpl; i++) \
{ \
dst_vals[0] = src_vals[ialt]; \
dst_vals += 1; \
src_vals += nvals; \
} \
bcf_update_format_##type(args->hdr,dst,tag,vals,nsmpl); \
} \
else if ( len==BCF_VL_R ) \
{ \
if ( nvals!=src->n_allele*nsmpl ) \
{ \
if ( args->force && !args->force_warned ) \
{ \
fprintf(stderr, \
"Warning: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d, found %d. Removing the field.\n" \
" (This warning is printed only once.)\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,(src->n_allele-1)*nsmpl,nvals); \
args->force_warned = 1; \
} \
if ( args->force ) \
{ \
bcf_update_format_##type(args->hdr,dst,tag,NULL,0); \
return; \
} \
error("Error: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d, found %d\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele*nsmpl,nvals); \
} \
nvals /= nsmpl; \
type_t *src_vals = vals, *dst_vals = vals; \
for (i=0; i<nsmpl; i++) \
{ \
dst_vals[0] = src_vals[0]; \
dst_vals[1] = src_vals[ialt+1]; \
dst_vals += 2; \
src_vals += nvals; \
} \
bcf_update_format_##type(args->hdr,dst,tag,vals,nsmpl*2); \
} \
else if ( len==BCF_VL_G ) \
{ \
if ( nvals!=src->n_allele*(src->n_allele+1)/2*nsmpl && nvals!=src->n_allele*nsmpl ) \
{ \
if ( args->force && !args->force_warned ) \
{ \
fprintf(stderr, \
"Warning: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d, found %d. Removing the field.\n" \
" (This warning is printed only once.)\n", \
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,(src->n_allele-1)*nsmpl,nvals); \
args->force_warned = 1; \
} \
if ( args->force ) \
{ \
bcf_update_format_##type(args->hdr,dst,tag,NULL,0); \
return; \
} \
error("Error at %s:%"PRId64", the tag %s has wrong number of fields\n", bcf_seqname(args->hdr,src),(int64_t) src->pos+1,bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id)); \
} \
nvals /= nsmpl; \
int all_haploid = nvals==src->n_allele ? 1 : 0; \
type_t *src_vals = vals, *dst_vals = vals; \
for (i=0; i<nsmpl; i++) \
{ \
int haploid = all_haploid; \
if ( !haploid ) \
{ \
int j; \
for (j=0; j<nvals; j++) if ( is_vector_end ) break; \
if ( j!=nvals ) haploid = 1; \
} \
dst_vals[0] = src_vals[0]; \
if ( haploid ) \
{ \
dst_vals[1] = src_vals[ialt+1]; \
if ( !all_haploid ) set_vector_end; \
} \
else \
{ \
dst_vals[1] = src_vals[bcf_alleles2gt(0,ialt+1)]; \
dst_vals[2] = src_vals[bcf_alleles2gt(ialt+1,ialt+1)]; \
} \
dst_vals += all_haploid ? 2 : 3; \
src_vals += nvals; \
} \
bcf_update_format_##type(args->hdr,dst,tag,vals,all_haploid ? nsmpl*2 : nsmpl*3); \
} \
else \
bcf_update_format_##type(args->hdr,dst,tag,vals,nvals); \
}
switch (bcf_hdr_id2type(args->hdr,BCF_HL_FMT,fmt->id))
{
case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t, src_vals[j]==bcf_int32_vector_end, dst_vals[2]=bcf_int32_vector_end); break;
case BCF_HT_REAL: BRANCH_NUMERIC(float, float, bcf_float_is_vector_end(src_vals[j]), bcf_float_set_vector_end(dst_vals[2])); break;
}
#undef BRANCH_NUMERIC
}
static void squeeze_format_char(char *str, int src_blen, int dst_blen, int n)
{
int i, isrc = 0, idst = 0;
for (i=0; i<n; i++)
{
memmove(str+idst,str+isrc,dst_blen);
idst += dst_blen;
isrc += src_blen;
}
}
static void split_format_string(args_t *args, bcf1_t *src, bcf_fmt_t *fmt, int ialt, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id);
int ret = bcf_get_format_char(args->hdr,src,tag,&args->tmp_arr1,&args->ntmp_arr1);
if ( !ret ) return; // all values can be empty, leave out the tag, no need to panic
assert( ret>0 );
kstring_t str;
str.m = args->ntmp_arr1;
str.l = ret;
str.s = (char*) args->tmp_arr1;
int nsmpl = bcf_hdr_nsamples(args->hdr);
int len = bcf_hdr_id2length(args->hdr,BCF_HL_FMT,fmt->id);
if ( len==BCF_VL_A )
{
int i, blen = ret/nsmpl, maxlen = 0;
char *ptr = str.s;
for (i=0; i<nsmpl; i++)
{
char *tmp = ptr;
int len = 0;
STR_MOVE_NTH(tmp,tmp,ptr+blen,ialt,len);
if ( len<0 ) return; // wrong number of fields: skip
if ( maxlen < len ) maxlen = len;
ptr += blen;
}
if ( maxlen<blen ) squeeze_format_char(str.s,blen,maxlen,nsmpl);
bcf_update_format_char(args->hdr,dst,tag,str.s,nsmpl*maxlen);
}
else if ( len==BCF_VL_R )
{
int i, blen = ret/nsmpl, maxlen = 0;
char *ptr = str.s;
for (i=0; i<nsmpl; i++)
{
char *tmp = ptr;
int len = 0;
STR_MOVE_NTH(ptr,tmp,ptr+blen,0,len);
ptr[len]=','; tmp++; len++;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,ialt,len);
if ( len<0 ) return; // wrong number of fields: skip
if ( maxlen < len ) maxlen = len;
ptr += blen;
}
if ( maxlen<blen ) squeeze_format_char(str.s,blen,maxlen,nsmpl);
bcf_update_format_char(args->hdr,dst,tag,str.s,nsmpl*maxlen);
}
else if ( len==BCF_VL_G )
{
int i, blen = ret/nsmpl, maxlen = 0, i0a = bcf_alleles2gt(0,ialt+1), iaa = bcf_alleles2gt(ialt+1,ialt+1);
char *ptr = str.s;
for (i=0; i<nsmpl; i++)
{
char *se = ptr, *sx = ptr+blen;
int nfields = 1;
while ( *se && se<sx )
{
if ( *se==',' ) nfields++;
se++;
}
if ( nfields==1 && se-ptr==1 && *ptr=='.' ) continue; // missing value
if ( nfields!=src->n_allele*(src->n_allele+1)/2 && nfields!=src->n_allele )
{
if ( args->force && !args->force_warned )
{
fprintf(stderr,
"Warning: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d or %d, found %d. Removing the field.\n"
" (This warning is printed only once.)\n",
tag,bcf_seqname(args->hdr,src),(int64_t)src->pos+1,src->n_allele*(src->n_allele+1)/2,src->n_allele,nfields);
args->force_warned = 1;
}
if ( args->force )
{
bcf_update_format_char(args->hdr,dst,tag,NULL,0);
return;
}
error("Error: wrong number of fields in FMT/%s at %s:%"PRId64", expected %d or %d, found %d\n",
tag,bcf_seqname(args->hdr,src),(int64_t) src->pos+1,src->n_allele*(src->n_allele+1)/2,src->n_allele,nfields);
}
int len = 0;
if ( nfields==src->n_allele ) // haploid
{
char *tmp = ptr;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,0,len);
ptr[len]=','; tmp++; len++;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,ialt,len);
if ( len<0 ) return; // wrong number of fields: skip
}
else // diploid
{
char *tmp = ptr;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,0,len);
ptr[len]=','; tmp++; len++;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,i0a-1,len);
if ( len<0 ) return; // wrong number of fields: skip
ptr[len]=','; tmp++; len++;
STR_MOVE_NTH(&ptr[len],tmp,ptr+blen,iaa-i0a-1,len);
if ( len<0 ) return; // wrong number of fields: skip
}
if ( maxlen < len ) maxlen = len;
ptr += blen;
}
if ( maxlen<blen ) squeeze_format_char(str.s,blen,maxlen,nsmpl);
bcf_update_format_char(args->hdr,dst,tag,str.s,nsmpl*maxlen);
}
else
bcf_update_format_char(args->hdr,dst,tag,str.s,str.l);
}
static void split_multiallelic_to_biallelics(args_t *args, bcf1_t *line)
{
int i;
bcf_unpack(line, BCF_UN_ALL);
// Init the target biallelic lines
args->ntmp_lines = line->n_allele-1;
if ( args->mtmp_lines < args->ntmp_lines )
{
args->tmp_lines = (bcf1_t **)realloc(args->tmp_lines,sizeof(bcf1_t*)*args->ntmp_lines);
for (i=args->mtmp_lines; i<args->ntmp_lines; i++)
args->tmp_lines[i] = NULL;
args->mtmp_lines = args->ntmp_lines;
}
kstring_t tmp = {0,0,0};
kputs(line->d.allele[0], &tmp);
kputc(',', &tmp);
int rlen = tmp.l;
int gt_id = bcf_hdr_id2int(args->hdr,BCF_DT_ID,"GT");
for (i=0; i<args->ntmp_lines; i++) // for each ALT allele
{
if ( !args->tmp_lines[i] ) args->tmp_lines[i] = bcf_init1();
bcf1_t *dst = args->tmp_lines[i];
bcf_clear(dst);
dst->rid = line->rid;
dst->pos = line->pos;
dst->qual = line->qual;
// Not quite sure how to handle IDs, they can be assigned to a specific
// ALT. For now we leave the ID unchanged for all.
bcf_update_id(args->hdr, dst, line->d.id ? line->d.id : ".");
tmp.l = rlen;
kputs(line->d.allele[i+1],&tmp);
bcf_update_alleles_str(args->hdr,dst,tmp.s);
if ( line->d.n_flt ) bcf_update_filter(args->hdr, dst, line->d.flt, line->d.n_flt);
int j;
for (j=0; j<line->n_info; j++)
{
bcf_info_t *info = &line->d.info[j];
int type = bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key);
if ( type==BCF_HT_INT || type==BCF_HT_REAL ) split_info_numeric(args, line, info, i, dst);
else if ( type==BCF_HT_FLAG ) split_info_flag(args, line, info, i, dst);
else split_info_string(args, line, info, i, dst);
}
dst->n_sample = line->n_sample;
for (j=0; j<line->n_fmt; j++)
{
bcf_fmt_t *fmt = &line->d.fmt[j];
int type = bcf_hdr_id2type(args->hdr,BCF_HL_FMT,fmt->id);
if ( fmt->id==gt_id ) split_format_genotype(args, line, fmt, i, dst);
else if ( type==BCF_HT_INT || type==BCF_HT_REAL ) split_format_numeric(args, line, fmt, i, dst);
else split_format_string(args, line, fmt, i, dst);
}
}
free(tmp.s);
}
// Enlarge FORMAT array containing nsmpl samples each with nals_ori values
// to accommodate nvals values for each sample, filling the gaps with missing
// values. Works also for INFO arrays, with nsmpl set to 1.
#define ENLARGE_ARRAY(type_t,set_missing,arr,narr_bytes,nsmpl,nvals_ori,nvals) \
{ \
int nbytes_new = (nsmpl)*(nvals)*sizeof(type_t); \
hts_expand(uint8_t,nbytes_new,narr_bytes,arr); \
int ismpl, k; \
for (ismpl=nsmpl-1; ismpl>=0; ismpl--) \
{ \
type_t *dst_ptr = ((type_t*)arr) + ismpl*(nvals); \
type_t *src_ptr = ((type_t*)arr) + ismpl*nvals_ori; \
memmove(dst_ptr,src_ptr,sizeof(type_t)*nvals_ori); \
for (k=nvals_ori; k<nvals; k++) set_missing; \
} \
}
static void merge_info_numeric(args_t *args, bcf1_t **lines, int nlines, bcf_info_t *info, bcf1_t *dst)
{
#define BRANCH_NUMERIC(type,type_t,set_missing,is_vector_end) \
{ \
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key); \
int ntmp = args->ntmp_arr1 / sizeof(type_t); \
int nvals_ori = bcf_get_info_##type(args->hdr,lines[0],tag,&args->tmp_arr1,&ntmp); \
args->ntmp_arr1 = ntmp * sizeof(type_t); \
assert( nvals_ori>0 ); \
type_t *vals = (type_t*) args->tmp_arr1, *vals2; \
int i,k,len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key); \
if ( len==BCF_VL_A ) \
{ \
if (nvals_ori!=lines[0]->n_allele - 1) \
error("vcfnorm: number of fields in first record at position %s:%"PRId64" for INFO tag %s not as expected [found: %d vs expected:%d]\n", bcf_seqname(args->hdr,lines[0]),(int64_t) lines[0]->pos+1, tag, nvals_ori, lines[0]->n_allele-1); \
int nvals = dst->n_allele - 1; \
ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,1,nvals_ori,nvals); \
vals = (type_t*) args->tmp_arr1; \
for (i=1; i<nlines; i++) \
{ \
int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
int nvals2 = bcf_get_info_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
if (nvals2<0) continue; /* info tag does not exist in this record, skip */ \
args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
if (nvals2!=lines[i]->n_allele-1) \
error("vcfnorm: could not merge INFO tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
vals2 = (type_t*) args->tmp_arr2; \
for (k=0; k<nvals2; k++) \
{ \
if ( is_vector_end ) break; \
vals[ args->maps[i].map[k+1] - 1 ] = vals2[k]; \
} \
} \
bcf_update_info_##type(args->hdr,dst,tag,args->tmp_arr1,nvals); \
} \
else if ( len==BCF_VL_R ) \
{ \
if (nvals_ori!=lines[0]->n_allele) \
error("vcfnorm: number of fields in first record at position %s:%"PRId64" for INFO tag %s not as expected [found: %d vs expected:%d]\n", bcf_seqname(args->hdr,lines[0]),(int64_t) lines[0]->pos+1, tag, nvals_ori, lines[0]->n_allele); \
int nvals = dst->n_allele; \
ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,1,nvals_ori,nvals); \
vals = (type_t*) args->tmp_arr1; \
for (i=1; i<nlines; i++) \
{ \
int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
int nvals2 = bcf_get_info_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
if (nvals2<0) continue; /* info tag does not exist in this record, skip */ \
args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
if (nvals2!=lines[i]->n_allele) \
error("vcfnorm: could not merge INFO tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
vals2 = (type_t*) args->tmp_arr2; \
for (k=0; k<nvals2; k++) \
{ \
if ( is_vector_end ) break; \
vals[ args->maps[i].map[k] ] = vals2[k]; \
} \
} \
bcf_update_info_##type(args->hdr,dst,tag,args->tmp_arr1,nvals); \
} \
else if ( len==BCF_VL_G ) \
{ \
/* expecting diploid gt in INFO */ \
if (nvals_ori!=lines[0]->n_allele*(lines[0]->n_allele+1)/2) { \
fprintf(stderr, "todo: merge Number=G INFO fields for haploid sites\n"); \
error("vcfnorm: number of fields in first record at position %s:%"PRId64" for INFO tag %s not as expected [found: %d vs expected:%d]\n", bcf_seqname(args->hdr,lines[0]),(int64_t) lines[0]->pos+1, tag, nvals_ori, lines[0]->n_allele*(lines[0]->n_allele+1)/2); \
} \
int nvals = dst->n_allele*(dst->n_allele+1)/2; \
ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,1,nvals_ori,nvals); \
vals = (type_t*) args->tmp_arr1; \
for (i=1; i<nlines; i++) \
{ \
int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
int nvals2 = bcf_get_info_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
if (nvals2<0) continue; /* info tag does not exist in this record, skip */ \
args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
if (nvals2!=lines[i]->n_allele*(lines[i]->n_allele+1)/2) \
error("vcfnorm: could not merge INFO tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
vals2 = (type_t*) args->tmp_arr2; \
int ia,ib; \
k = 0; \
for (ia=0; ia<lines[i]->n_allele; ia++) \
{ \
for (ib=0; ib<=ia; ib++) \
{ \
if ( is_vector_end ) break; \
int l = bcf_alleles2gt(args->maps[i].map[ia],args->maps[i].map[ib]); \
vals[l] = vals2[k]; \
k++; \
} \
} \
} \
bcf_update_info_##type(args->hdr,dst,tag,args->tmp_arr1,nvals); \
} \
else \
bcf_update_info_##type(args->hdr,dst,tag,vals,nvals_ori); \
}
switch (bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key))
{
case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t, dst_ptr[k]=bcf_int32_missing, vals2[k]==bcf_int32_vector_end); break;
case BCF_HT_REAL: BRANCH_NUMERIC(float, float, bcf_float_set_missing(dst_ptr[k]), bcf_float_is_vector_end(vals2[k])); break;
}
#undef BRANCH_NUMERIC
}
static void merge_info_flag(args_t *args, bcf1_t **lines, int nlines, bcf_info_t *info, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
int ret = bcf_get_info_flag(args->hdr,lines[0],tag,&args->tmp_arr1,&args->ntmp_arr1);
bcf_update_info_flag(args->hdr,dst,tag,NULL,ret);
}
int copy_string_field(char *src, int isrc, int src_len, kstring_t *dst, int idst); // see vcfmerge.c
static void merge_info_string(args_t *args, bcf1_t **lines, int nlines, bcf_info_t *info, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,info->key);
kstring_t str;
str.m = args->ntmp_arr1;
str.l = 0;
str.s = (char*) args->tmp_arr1;
int i, j, len = bcf_hdr_id2length(args->hdr,BCF_HL_INFO,info->key);
if ( len==BCF_VL_A || len==BCF_VL_R )
{
int jfrom = len==BCF_VL_A ? 1 : 0;
kputc('.',&str);
for (i=jfrom+1; i<dst->n_allele; i++) kputs(",.",&str);
for (i=0; i<nlines; i++)
{
bcf_info_t *src = bcf_get_info(args->hdr,lines[i],tag);
if (!src) continue;
for (j=jfrom; j<lines[i]->n_allele; j++)
copy_string_field((char*)src->vptr, j-jfrom, src->len, &str, args->maps[i].map[j]-jfrom);
}
str.s[str.l] = 0;
args->tmp_arr1 = (uint8_t*) str.s;
args->ntmp_arr1 = str.m;
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
else if ( len==BCF_VL_G )
{
int ngts = dst->n_allele*(dst->n_allele+1)/2;
kputc('.',&str);
for (i=1; i<ngts; i++) kputs(",.",&str);
for (i=0; i<nlines; i++)
{
bcf_info_t *src = bcf_get_info(args->hdr,lines[i],tag);
if (!src) continue;
int iori, jori, kori = 0;
for (iori=0; iori<lines[i]->n_allele; iori++)
{
int inew = args->maps[i].map[iori];
for (jori=0; jori<=iori; jori++)
{
int jnew = args->maps[i].map[jori];
int knew = bcf_alleles2gt(inew,jnew);
copy_string_field((char*)src->vptr,kori,src->len,&str,knew);
kori++;
}
}
}
str.s[str.l] = 0;
args->tmp_arr1 = (uint8_t*) str.s;
args->ntmp_arr1 = str.m;
bcf_update_info_string(args->hdr,dst,tag,str.s);
}
else
{
bcf_get_info_string(args->hdr,lines[0],tag,&args->tmp_arr1,&args->ntmp_arr1);
bcf_update_info_string(args->hdr,dst,tag,args->tmp_arr1);
}
}
static void merge_format_genotype(args_t *args, bcf1_t **lines, int nlines, bcf_fmt_t *fmt, bcf1_t *dst)
{
// reusing int8_t arrays as int32_t arrays
int ntmp = args->ntmp_arr1 / 4;
int ngts = bcf_get_genotypes(args->hdr,lines[0],&args->tmp_arr1,&ntmp);
args->ntmp_arr1 = ntmp * 4;
assert( ngts >0 );
int nsmpl = bcf_hdr_nsamples(args->hdr);
ngts /= nsmpl;
int i, j, k;
for (i=1; i<nlines; i++)
{
int ntmp2 = args->ntmp_arr2 / 4;
int ngts2 = bcf_get_genotypes(args->hdr,lines[i],&args->tmp_arr2,&ntmp2);
args->ntmp_arr2 = ntmp2 * 4;
ngts2 /= nsmpl;
if ( ngts!=ngts2 ) error("Error at %s:%"PRId64": cannot combine diploid with haploid genotype\n", bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1);
int32_t *gt = (int32_t*) args->tmp_arr1;
int32_t *gt2 = (int32_t*) args->tmp_arr2;
for (j=0; j<nsmpl; j++)
{
for (k=0; k<ngts; k++)
{
if ( gt2[k]==bcf_int32_vector_end ) break;
if ( bcf_gt_is_missing(gt2[k]) || bcf_gt_allele(gt2[k])==0 ) continue;
if ( gt2[k]==0 ) gt[k] = 0; // missing genotype
else
{
int ial = bcf_gt_allele(gt2[k]);
if ( ial>=args->maps[i].nals ) error("Error at %s:%"PRId64": incorrect allele index %d\n",bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1,ial);
gt[k] = bcf_gt_unphased( args->maps[i].map[ial] ) | bcf_gt_is_phased(gt[k]);
}
}
gt += ngts;
gt2 += ngts;
}
}
bcf_update_genotypes(args->hdr,dst,args->tmp_arr1,ngts*nsmpl);
}
static int diploid_to_haploid(int size, int nsmpl, int nals, uint8_t *vals)
{
int i, dsrc = size*nals*(nals+1)/2, ddst = size*nals;
uint8_t *src_ptr = vals + dsrc, *dst_ptr = vals + ddst;
for (i=1; i<nsmpl; i++)
{
memmove(dst_ptr,src_ptr,ddst);
dst_ptr += ddst;
src_ptr += dsrc;
}
return nals;
}
static void merge_format_numeric(args_t *args, bcf1_t **lines, int nlines, bcf_fmt_t *fmt, bcf1_t *dst)
{
#define BRANCH_NUMERIC(type,type_t,set_missing,is_vector_end,set_vector_end) \
{ \
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id); \
int ntmp = args->ntmp_arr1 / sizeof(type_t); \
int nvals_ori = bcf_get_format_##type(args->hdr,lines[0],tag,&args->tmp_arr1,&ntmp); \
args->ntmp_arr1 = ntmp * sizeof(type_t); \
assert( nvals_ori>0 ); \
type_t *vals2, *vals = (type_t *) args->tmp_arr1; \
int len = bcf_hdr_id2length(args->hdr,BCF_HL_FMT,fmt->id); \
int i, j, k, nsmpl = bcf_hdr_nsamples(args->hdr); \
nvals_ori /= nsmpl; \
if ( len==BCF_VL_A ) \
{ \
int nvals = dst->n_allele - 1; \
ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,nsmpl,nvals_ori,nvals); \
for (i=1; i<nlines; i++) \
{ \
int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
int nvals2 = bcf_get_format_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
if (nvals2<0) continue; /* format tag does not exist in this record, skip */ \
args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
nvals2 /= nsmpl; \
if (nvals2!=lines[i]->n_allele-1) \
error("vcfnorm: could not merge FORMAT tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
vals = (type_t*) args->tmp_arr1; \
vals2 = (type_t*) args->tmp_arr2; \
for (j=0; j<nsmpl; j++) \
{ \
for (k=0; k<nvals2; k++) \
{ \
if ( is_vector_end ) break; \
vals[ args->maps[i].map[k+1] - 1 ] = vals2[k]; \
} \
vals += nvals; \
vals2 += nvals2; \
} \
} \
bcf_update_format_##type(args->hdr,dst,tag,args->tmp_arr1,nvals*nsmpl); \
} \
else if ( len==BCF_VL_R ) \
{ \
int nvals = dst->n_allele; \
ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,nsmpl,nvals_ori,nvals); \
for (i=1; i<nlines; i++) \
{ \
int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
int nvals2 = bcf_get_format_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
if (nvals2<0) continue; /* format tag does not exist in this record, skip */ \
args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
nvals2 /= nsmpl; \
if (nvals2!=lines[i]->n_allele) \
error("vcfnorm: could not merge FORMAT tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
vals = (type_t*) args->tmp_arr1; \
vals2 = (type_t*) args->tmp_arr2; \
for (j=0; j<nsmpl; j++) \
{ \
for (k=0; k<nvals2; k++) \
{ \
if ( is_vector_end ) break; \
vals[ args->maps[i].map[k] ] = vals2[k]; \
} \
vals += nvals; \
vals2 += nvals2; \
} \
} \
bcf_update_format_##type(args->hdr,dst,tag,args->tmp_arr1,nvals*nsmpl); \
} \
else if ( len==BCF_VL_G ) \
{ \
/* which samples are diploid */ \
memset(args->diploid,0,nsmpl); \
int all_haploid = 1; \
if ( nvals_ori > lines[0]->n_allele ) /* line possibly diploid */ \
{ \
vals2 = (type_t*) args->tmp_arr1; \
int ndiploid = lines[0]->n_allele*(lines[0]->n_allele+1)/2; \
for (i=0; i<nsmpl; i++) \
{ \
if ( !args->diploid[i] ) \
{ \
for (k=0; k<nvals_ori; k++) if ( is_vector_end ) break; \
if ( k==ndiploid ) { args->diploid[i] = 1; all_haploid = 0; }\
} \
vals2 += nvals_ori; \
} \
} \
int nvals = dst->n_allele*(dst->n_allele+1)/2; \
ENLARGE_ARRAY(type_t,set_missing,args->tmp_arr1,args->ntmp_arr1,nsmpl,nvals_ori,nvals); \
for (i=1; i<nlines; i++) \
{ \
int ntmp2 = args->ntmp_arr2 / sizeof(type_t); \
int nvals2 = bcf_get_format_##type(args->hdr,lines[i],tag,&args->tmp_arr2,&ntmp2); \
if (nvals2<0) continue; /* format tag does not exist in this record, skip */ \
args->ntmp_arr2 = ntmp2 * sizeof(type_t); \
nvals2 /= nsmpl; \
int ndiploid = lines[i]->n_allele*(lines[i]->n_allele+1)/2; \
int line_diploid = nvals2==ndiploid ? 1 : 0; \
if (!(nvals2==1 || nvals2==lines[i]->n_allele || nvals2==lines[i]->n_allele*(lines[i]->n_allele+1)/2)) \
error("vcfnorm: could not merge FORMAT tag %s at position %s:%"PRId64"\n", tag, bcf_seqname(args->hdr,lines[i]),(int64_t) lines[i]->pos+1); \
vals = (type_t*) args->tmp_arr1; \
vals2 = (type_t*) args->tmp_arr2; \
for (j=0; j<nsmpl; j++) \
{ \
int smpl_diploid = line_diploid; \
if ( smpl_diploid ) \
{ \
for (k=0; k<nvals2; k++) if ( is_vector_end ) break; \
if ( k!=ndiploid ) smpl_diploid = 0; \
} \
if ( smpl_diploid && !args->diploid[j] ) { args->diploid[j] = 1; all_haploid = 0; } \
if ( !smpl_diploid ) \
{ \
for (k=0; k<lines[i]->n_allele; k++) vals[args->maps[i].map[k]] = vals2[k]; \
} \
else \
{ \
k = 0; \
int ia,ib; \
for (ia=0; ia<lines[i]->n_allele; ia++) \
{ \
for (ib=0; ib<=ia; ib++) \
{ \
int l = bcf_alleles2gt(args->maps[i].map[ia],args->maps[i].map[ib]); \
vals[l] = vals2[k]; \
k++; \
} \
} \
} \
vals += nvals; \
vals2 += nvals2; \
} \
} \
if ( all_haploid ) \
nvals = diploid_to_haploid(sizeof(type_t),nsmpl,dst->n_allele,args->tmp_arr1); \
else \
{\
k = dst->n_allele;\
vals2 = (type_t*) args->tmp_arr1;\
for (i=0; i<nsmpl; i++)\
{\
if ( !args->diploid[i] ) set_vector_end;\
vals2 += nvals;\
}\
}\
bcf_update_format_##type(args->hdr,dst,tag,args->tmp_arr1,nvals*nsmpl); \
} \
else \
bcf_update_format_##type(args->hdr,dst,tag,args->tmp_arr1,nvals_ori*nsmpl); \
}
switch (bcf_hdr_id2type(args->hdr,BCF_HL_FMT,fmt->id))
{
case BCF_HT_INT: BRANCH_NUMERIC(int32, int32_t, dst_ptr[k]=bcf_int32_missing, vals2[k]==bcf_int32_vector_end, vals2[k]=bcf_int32_vector_end); break;
case BCF_HT_REAL: BRANCH_NUMERIC(float, float, bcf_float_set_missing(dst_ptr[k]), bcf_float_is_vector_end(vals2[k]), bcf_float_set_vector_end(vals2[k])); break;
}
#undef BRANCH_NUMERIC
}
static void merge_format_string(args_t *args, bcf1_t **lines, int nlines, bcf_fmt_t *fmt, bcf1_t *dst)
{
const char *tag = bcf_hdr_int2id(args->hdr,BCF_DT_ID,fmt->id);
int i, j, k, len = bcf_hdr_id2length(args->hdr,BCF_HL_FMT,fmt->id);
if ( len!=BCF_VL_A && len!=BCF_VL_R && len!=BCF_VL_G )
{
int nret = bcf_get_format_char(args->hdr,lines[0],tag,&args->tmp_arr1,&args->ntmp_arr1);
bcf_update_format_char(args->hdr,dst,tag,args->tmp_arr1,nret);
return;
}
int nsmpl = bcf_hdr_nsamples(args->hdr);
for (i=0; i<nsmpl; i++) args->tmp_str[i].l = 0;
if ( len==BCF_VL_A || len==BCF_VL_R )
{
int jfrom = len==BCF_VL_A ? 1 : 0;
for (i=0; i<nsmpl; i++)
{
kstring_t *tmp = &args->tmp_str[i];
kputc('.',tmp);
for (k=jfrom+1; k<dst->n_allele; k++) kputs(",.",tmp);
}
for (i=0; i<nlines; i++)
{
int nret = bcf_get_format_char(args->hdr,lines[i],tag,&args->tmp_arr1,&args->ntmp_arr1);
if (nret<0) continue; /* format tag does not exist in this record, skip */ \
nret /= nsmpl;
for (k=0; k<nsmpl; k++)
{
kstring_t *tmp = &args->tmp_str[k];
char *src = (char*)args->tmp_arr1 + k*nret;
for (j=jfrom; j<lines[i]->n_allele; j++)
copy_string_field(src, j-jfrom, nret, tmp, args->maps[i].map[j]-jfrom);
}
}
}
else if ( len==BCF_VL_G )
{
hts_expand(uint8_t,nsmpl,args->ntmp_arr2,args->tmp_arr2);
uint8_t *haploid = args->tmp_arr2;
int nret = bcf_get_format_char(args->hdr,lines[0],tag,&args->tmp_arr1,&args->ntmp_arr1);
nret /= nsmpl;
for (i=0; i<nsmpl; i++)
{
char *ss = (char*)args->tmp_arr1 + i*nret, *se = ss+nret;
int nfields = 1;
while ( *ss && ss<se )
{
if ( *ss==',' ) nfields++;
ss++;
}
if ( nfields==lines[0]->n_allele )
{
haploid[i] = 1;
nfields = dst->n_allele;
}
else if ( nfields==lines[0]->n_allele*(lines[0]->n_allele+1)/2 )
{
haploid[i] = 0;
nfields = dst->n_allele*(dst->n_allele+1)/2;
}
else error("The field %s at %s:%"PRId64" neither diploid nor haploid?\n", tag,bcf_seqname(args->hdr,dst),(int64_t) dst->pos+1);
kstring_t *tmp = &args->tmp_str[i];
kputc('.',tmp);
for (j=1; j<nfields; j++) kputs(",.",tmp);
}
for (i=0; i<nlines; i++)
{
if ( i ) // we already have a copy
{
nret = bcf_get_format_char(args->hdr,lines[i],tag,&args->tmp_arr1,&args->ntmp_arr1);
if (nret<0) continue; /* format tag does not exist in this record, skip */ \
nret /= nsmpl;
}
for (k=0; k<nsmpl; k++)
{
kstring_t *tmp = &args->tmp_str[k];
char *src = (char*)args->tmp_arr1 + k*nret;
if ( haploid[k] )
{
for (j=0; j<lines[i]->n_allele; j++)
copy_string_field(src,j,nret, tmp, args->maps[i].map[j]);
}
else
{
int iori, jori, kori = 0;
for (iori=0; iori<lines[i]->n_allele; iori++)
{
int inew = args->maps[i].map[iori];
for (jori=0; jori<=iori; jori++)
{
int jnew = args->maps[i].map[jori];
int knew = bcf_alleles2gt(inew,jnew);
copy_string_field(src,kori,nret,tmp,knew);
kori++;
}
}
}
}
}
}
kstring_t str;
str.m = args->ntmp_arr2;
str.l = 0;
str.s = (char*) args->tmp_arr2;
int max_len = 0;
for (i=0; i<nsmpl; i++)
if ( max_len < args->tmp_str[i].l ) max_len = args->tmp_str[i].l;
for (i=0; i<nsmpl; i++)
{
kstring_t *tmp = &args->tmp_str[i];
kputsn(tmp->s,tmp->l,&str);
for (j=tmp->l; j<max_len; j++) kputc('\0',&str);
}
args->ntmp_arr2 = str.m;
args->tmp_arr2 = (uint8_t*)str.s;
bcf_update_format_char(args->hdr,dst,tag,str.s,str.l);
}
char **merge_alleles(char **a, int na, int *map, char **b, int *nb, int *mb); // see vcfmerge.c
static void merge_biallelics_to_multiallelic(args_t *args, bcf1_t *dst, bcf1_t **lines, int nlines)
{
int i;
for (i=0; i<nlines; i++)
bcf_unpack(lines[i], BCF_UN_ALL);
dst->rid = lines[0]->rid;
dst->pos = lines[0]->pos;
// take max for QUAL
bcf_float_set_missing(dst->qual);
for (i=0; i<nlines; i++) {
if (bcf_float_is_missing(lines[i]->qual)) continue;
if (bcf_float_is_missing(dst->qual) || dst->qual<lines[i]->qual)
dst->qual = lines[i]->qual;
}
bcf_update_id(args->hdr, dst, lines[0]->d.id);
// Merge and set the alleles, create a mapping from source allele indexes to dst idxs
hts_expand0(map_t,nlines,args->mmaps,args->maps); // a mapping for each line
args->nals = args->maps[0].nals = lines[0]->n_allele;
hts_expand(int,args->maps[0].nals,args->maps[0].mals,args->maps[0].map);
hts_expand(char*,args->nals,args->mals,args->als);
for (i=0; i<args->maps[0].nals; i++)
{
args->maps[0].map[i] = i;
args->als[i] = strdup(lines[0]->d.allele[i]);
}
for (i=1; i<nlines; i++)
{
if (lines[i]->d.id[0]!='.' || lines[i]->d.id[1]) bcf_add_id(args->hdr, dst, lines[i]->d.id);
args->maps[i].nals = lines[i]->n_allele;
hts_expand(int,args->maps[i].nals,args->maps[i].mals,args->maps[i].map);
args->als = merge_alleles(lines[i]->d.allele, lines[i]->n_allele, args->maps[i].map, args->als, &args->nals, &args->mals);
if ( !args->als ) error("Failed to merge alleles at %s:%"PRId64"\n", bcf_seqname(args->hdr,dst),(int64_t) dst->pos+1);
}
bcf_update_alleles(args->hdr, dst, (const char**)args->als, args->nals);
for (i=0; i<args->nals; i++)
{
free(args->als[i]);
args->als[i] = NULL;
}
if ( lines[0]->d.n_flt ) bcf_update_filter(args->hdr, dst, lines[0]->d.flt, lines[0]->d.n_flt);
for (i=1; i<nlines; i++) {
int j;
for (j=0; j<lines[i]->d.n_flt; j++) {
// if strict_filter, set FILTER to PASS if any site PASS
// otherwise accumulate FILTERs
if (lines[i]->d.flt[j] == bcf_hdr_id2int(args->hdr, BCF_DT_ID, "PASS")) {
if (args->strict_filter) {
bcf_update_filter(args->hdr, dst, lines[i]->d.flt, lines[i]->d.n_flt);
break;
}
else
continue;
}
bcf_add_filter(args->hdr, dst, lines[i]->d.flt[j]);
}
}
// merge info
for (i=0; i<lines[0]->n_info; i++)
{
bcf_info_t *info = &lines[0]->d.info[i];
int type = bcf_hdr_id2type(args->hdr,BCF_HL_INFO,info->key);
if ( type==BCF_HT_INT || type==BCF_HT_REAL ) merge_info_numeric(args, lines, nlines, info, dst);
else if ( type==BCF_HT_FLAG ) merge_info_flag(args, lines, nlines, info, dst);
else merge_info_string(args, lines, nlines, info, dst);
}
// merge format
int gt_id = bcf_hdr_id2int(args->hdr,BCF_DT_ID,"GT");
dst->n_sample = lines[0]->n_sample;
for (i=0; i<lines[0]->n_fmt; i++)
{
bcf_fmt_t *fmt = &lines[0]->d.fmt[i];
int type = bcf_hdr_id2type(args->hdr,BCF_HL_FMT,fmt->id);
if ( fmt->id==gt_id ) merge_format_genotype(args, lines, nlines, fmt, dst);
else if ( type==BCF_HT_INT || type==BCF_HT_REAL ) merge_format_numeric(args, lines, nlines, fmt, dst);
else merge_format_string(args, lines, nlines, fmt, dst);
}
}
#define SWAP(type_t, a, b) { type_t t = a; a = b; b = t; }
static void mrows_schedule(args_t *args, bcf1_t **line)
{
int i,m;
if ( args->mrows_collapse==COLLAPSE_ANY // merge all record types together
|| bcf_get_variant_types(*line)&VCF_SNP // SNP, put into alines
|| bcf_get_variant_types(*line)==VCF_REF ) // ref
{
args->nalines++;
m = args->malines;
hts_expand(bcf1_t*,args->nalines,args->malines,args->alines);
for (i=m; i<args->malines; i++) args->alines[i] = bcf_init1();
SWAP(bcf1_t*, args->alines[args->nalines-1], *line);
}
else
{
args->nblines++;
m = args->mblines;
hts_expand(bcf1_t*,args->nblines,args->mblines,args->blines);
for (i=m; i<args->mblines; i++) args->blines[i] = bcf_init1();
SWAP(bcf1_t*, args->blines[args->nblines-1], *line);
}
}
static int mrows_ready_to_flush(args_t *args, bcf1_t *line)
{
if ( args->nalines && (args->alines[0]->rid!=line->rid || args->alines[0]->pos!=line->pos) ) return 1;
if ( args->nblines && (args->blines[0]->rid!=line->rid || args->blines[0]->pos!=line->pos) ) return 1;
return 0;
}
static bcf1_t *mrows_flush(args_t *args)
{
if ( args->nblines && args->nalines==1 && bcf_get_variant_types(args->alines[0])==VCF_REF )
{
// By default, REF lines are merged with SNPs if SNPs and indels are to be kept separately.
// However, if there are indels only and a single REF line, merge it with indels.
args->nblines++;
int i,m = args->mblines;
hts_expand(bcf1_t*,args->nblines,args->mblines,args->blines);
for (i=m; i<args->mblines; i++) args->blines[i] = bcf_init1();
SWAP(bcf1_t*, args->blines[args->nblines-1], args->alines[0]);
args->nalines--;
}
if ( args->nalines )
{
if ( args->nalines==1 )
{
args->nalines = 0;
return args->alines[0];
}
bcf_clear(args->mrow_out);
merge_biallelics_to_multiallelic(args, args->mrow_out, args->alines, args->nalines);
args->nalines = 0;
return args->mrow_out;
}
else if ( args->nblines )
{
if ( args->nblines==1 )
{
args->nblines = 0;
return args->blines[0];
}
bcf_clear(args->mrow_out);
merge_biallelics_to_multiallelic(args, args->mrow_out, args->blines, args->nblines);
args->nblines = 0;
return args->mrow_out;
}
return NULL;
}
static void cmpals_add(cmpals_t *ca, bcf1_t *rec)
{
ca->ncmpals++;
hts_expand0(cmpals1_t, ca->ncmpals, ca->mcmpals, ca->cmpals);
cmpals1_t *cmpals = ca->cmpals + ca->ncmpals - 1;
free(cmpals->ref);
cmpals->ref = strdup(rec->d.allele[0]);
cmpals->n = rec->n_allele;
if ( rec->n_allele==2 )
{
free(cmpals->alt);
cmpals->alt = strdup(rec->d.allele[1]);
}
else
{
if ( cmpals->hash ) khash_str2int_destroy_free(cmpals->hash);
cmpals->hash = khash_str2int_init();
int i;
for (i=1; i<rec->n_allele; i++)
khash_str2int_inc(cmpals->hash, strdup(rec->d.allele[i]));
}
}
static int cmpals_match(cmpals_t *ca, bcf1_t *rec)
{
int i, j;
for (i=0; i<ca->ncmpals; i++)
{
cmpals1_t *cmpals = ca->cmpals + i;
if ( rec->n_allele != cmpals->n ) continue;
// NB. assuming both are normalized
if ( strcasecmp(rec->d.allele[0], cmpals->ref) ) continue;
// the most frequent case
if ( rec->n_allele==2 )
{
if ( strcasecmp(rec->d.allele[1], cmpals->alt) ) continue;
return 1;
}
khash_t(str2int) *hash = (khash_t(str2int)*) cmpals->hash;
for (j=1; j<rec->n_allele; j++)
if ( !khash_str2int_has_key(hash, rec->d.allele[j]) ) break;
if ( j<rec->n_allele ) continue;
return 1;
}
return 0;
}
static void cmpals_reset(cmpals_t *ca) { ca->ncmpals = 0; }
static void cmpals_destroy(cmpals_t *ca)
{
int i;
for (i=0; i<ca->mcmpals; i++)
{
cmpals1_t *cmpals = ca->cmpals + i;
free(cmpals->ref);
free(cmpals->alt);
if ( cmpals->hash ) khash_str2int_destroy_free(cmpals->hash);
}
free(ca->cmpals);
}
static void flush_buffer(args_t *args, htsFile *file, int n)
{
bcf1_t *line;
int i, k;
int prev_rid = -1, prev_pos = -1, prev_type = 0;
for (i=0; i<n; i++)
{
k = rbuf_shift(&args->rbuf);
if ( args->mrows_op==MROWS_MERGE )
{
if ( mrows_ready_to_flush(args, args->lines[k]) )
{
while ( (line=mrows_flush(args)) )
if ( bcf_write1(file, args->hdr, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
}
int merge = 1;
if ( args->mrows_collapse!=COLLAPSE_BOTH && args->mrows_collapse!=COLLAPSE_ANY )
{
if ( !(bcf_get_variant_types(args->lines[k]) & args->mrows_collapse) ) merge = 0;
}
if ( merge )
{
mrows_schedule(args, &args->lines[k]);
continue;
}
}
else if ( args->rmdup )
{
int line_type = bcf_get_variant_types(args->lines[k]);
if ( prev_rid>=0 && prev_rid==args->lines[k]->rid && prev_pos==args->lines[k]->pos )
{
if ( args->rmdup & BCF_SR_PAIR_ANY ) continue; // rmdup by position only
if ( args->rmdup & BCF_SR_PAIR_SNPS && line_type&(VCF_SNP|VCF_MNP) && prev_type&(VCF_SNP|VCF_MNP) ) continue;
if ( args->rmdup & BCF_SR_PAIR_INDELS && line_type&(VCF_INDEL) && prev_type&(VCF_INDEL) ) continue;
if ( args->rmdup & BCF_SR_PAIR_EXACT && cmpals_match(&args->cmpals_out, args->lines[k]) ) continue;
}
else
{
prev_rid = args->lines[k]->rid;
prev_pos = args->lines[k]->pos;
prev_type = 0;
if ( args->rmdup & BCF_SR_PAIR_EXACT ) cmpals_reset(&args->cmpals_out);
}
prev_type |= line_type;
if ( args->rmdup & BCF_SR_PAIR_EXACT ) cmpals_add(&args->cmpals_out, args->lines[k]);
}
if ( bcf_write1(file, args->hdr, args->lines[k])!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
}
if ( args->mrows_op==MROWS_MERGE && !args->rbuf.n )
{
while ( (line=mrows_flush(args)) )
if ( bcf_write1(file, args->hdr, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
}
}
static void init_data(args_t *args)
{
args->hdr = args->files->readers[0].header;
rbuf_init(&args->rbuf, 100);
args->lines = (bcf1_t**) calloc(args->rbuf.m, sizeof(bcf1_t*));
if ( args->ref_fname )
{
args->fai = fai_load(args->ref_fname);
if ( !args->fai ) error("Failed to load the fai index: %s\n", args->ref_fname);
}
if ( args->mrows_op==MROWS_MERGE )
{
args->mrow_out = bcf_init1();
args->tmp_str = (kstring_t*) calloc(bcf_hdr_nsamples(args->hdr),sizeof(kstring_t));
args->diploid = (uint8_t*) malloc(bcf_hdr_nsamples(args->hdr));
}
}
static void destroy_data(args_t *args)
{
cmpals_destroy(&args->cmpals_in);
cmpals_destroy(&args->cmpals_out);
int i;
for (i=0; i<args->rbuf.m; i++)
if ( args->lines[i] ) bcf_destroy1(args->lines[i]);
free(args->lines);
for (i=0; i<args->mtmp_lines; i++)
if ( args->tmp_lines[i] ) bcf_destroy1(args->tmp_lines[i]);
free(args->tmp_lines);
for (i=0; i<args->malines; i++)
bcf_destroy1(args->alines[i]);
free(args->alines);
for (i=0; i<args->mblines; i++)
bcf_destroy1(args->blines[i]);
free(args->blines);
for (i=0; i<args->mmaps; i++)
free(args->maps[i].map);
for (i=0; i<args->ntmp_als; i++)
free(args->tmp_als[i].s);
free(args->tmp_als);
free(args->tmp_als_str.s);
if ( args->tmp_str )
{
for (i=0; i<bcf_hdr_nsamples(args->hdr); i++) free(args->tmp_str[i].s);
free(args->tmp_str);
}
free(args->maps);
free(args->als);
free(args->int32_arr);
free(args->tmp_arr1);
free(args->tmp_arr2);
free(args->diploid);
if ( args->mrow_out ) bcf_destroy1(args->mrow_out);
if ( args->fai ) fai_destroy(args->fai);
if ( args->mseq ) free(args->seq);
}
static void normalize_line(args_t *args, bcf1_t **line_ptr)
{
bcf1_t *line = *line_ptr;
if ( args->fai )
{
if ( args->check_ref & CHECK_REF_FIX ) fix_ref(args, line);
if ( args->do_indels )
{
int ret = realign(args, line);
// exclude broken VCF lines
if ( ret==ERR_REF_MISMATCH && args->check_ref & CHECK_REF_SKIP )
{
args->nskipped++;
return;
}
if ( ret==ERR_DUP_ALLELE )
{
if ( args->check_ref & CHECK_REF_FIX )
fix_dup_alt(args, line);
else if ( args->check_ref==CHECK_REF_EXIT )
error("Duplicate alleles at %s:%"PRId64"; run with -cw to turn the error into warning or with -cs to fix.\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
else if ( args->check_ref & CHECK_REF_WARN )
fprintf(stderr,"ALT_DUP\t%s\t%"PRId64"\n", bcf_seqname(args->hdr,line),(int64_t) line->pos+1);
}
}
}
// insert into sorted buffer
rbuf_expand0(&args->rbuf,bcf1_t*,args->rbuf.n+1,args->lines);
int i,j;
i = j = rbuf_append(&args->rbuf);
if ( !args->lines[i] ) args->lines[i] = bcf_init1();
SWAP(bcf1_t*, (*line_ptr), args->lines[i]);
while ( rbuf_prev(&args->rbuf,&i) )
{
if ( args->lines[i]->pos > args->lines[j]->pos ) SWAP(bcf1_t*, args->lines[i], args->lines[j]);
j = i;
}
}
static void normalize_vcf(args_t *args)
{
htsFile *out = hts_open(args->output_fname, hts_bcf_wmode(args->output_type));
if ( out == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno));
if ( args->n_threads )
hts_set_opt(out, HTS_OPT_THREAD_POOL, args->files->p);
if (args->record_cmd_line) bcf_hdr_append_version(args->hdr, args->argc, args->argv, "bcftools_norm");
if ( bcf_hdr_write(out, args->hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
int prev_rid = -1, prev_pos = -1, prev_type = 0;
while ( bcf_sr_next_line(args->files) )
{
args->ntotal++;
bcf1_t *line = args->files->readers[0].buffer[0];
if ( args->rmdup )
{
int line_type = bcf_get_variant_types(line);
if ( prev_rid>=0 && prev_rid==line->rid && prev_pos==line->pos )
{
if ( args->rmdup & BCF_SR_PAIR_ANY ) continue; // rmdup by position only
if ( args->rmdup & BCF_SR_PAIR_SNPS && line_type&(VCF_SNP|VCF_MNP) && prev_type&(VCF_SNP|VCF_MNP) ) continue;
if ( args->rmdup & BCF_SR_PAIR_INDELS && line_type&(VCF_INDEL) && prev_type&(VCF_INDEL) ) continue;
if ( args->rmdup & BCF_SR_PAIR_EXACT && cmpals_match(&args->cmpals_in, line) ) continue;
}
else
{
prev_rid = line->rid;
prev_pos = line->pos;
prev_type = 0;
if ( args->rmdup & BCF_SR_PAIR_EXACT ) cmpals_reset(&args->cmpals_in);
}
prev_type |= line_type;
if ( args->rmdup & BCF_SR_PAIR_EXACT ) cmpals_add(&args->cmpals_in, line);
}
// still on the same chromosome?
int i,j,ilast = rbuf_last(&args->rbuf);
if ( ilast>=0 && line->rid != args->lines[ilast]->rid ) flush_buffer(args, out, args->rbuf.n); // new chromosome
int split = 0;
if ( args->mrows_op==MROWS_SPLIT )
{
split = 1;
if ( args->mrows_collapse!=COLLAPSE_BOTH && args->mrows_collapse!=COLLAPSE_ANY )
{
if ( !(bcf_get_variant_types(line) & args->mrows_collapse) ) split = 0;
}
if ( split && line->n_allele>2 )
{
args->nsplit++;
split_multiallelic_to_biallelics(args, line);
for (j=0; j<args->ntmp_lines; j++)
normalize_line(args, &args->tmp_lines[j]);
}
else
split = 0;
}
if ( !split )
normalize_line(args, &args->files->readers[0].buffer[0]);
// find out how many sites to flush
ilast = rbuf_last(&args->rbuf);
j = 0;
for (i=-1; rbuf_next(&args->rbuf,&i); )
{
if ( args->lines[ilast]->pos - args->lines[i]->pos < args->buf_win ) break;
j++;
}
if ( j>0 ) flush_buffer(args, out, j);
}
flush_buffer(args, out, args->rbuf.n);
if ( hts_close(out)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname);
fprintf(stderr,"Lines total/split/realigned/skipped:\t%d/%d/%d/%d\n", args->ntotal,args->nsplit,args->nchanged,args->nskipped);
if ( args->check_ref & CHECK_REF_FIX )
fprintf(stderr,"REF/ALT total/modified/added: \t%d/%d/%d\n", args->nref.tot,args->nref.swap,args->nref.set);
}
static void usage(void)
{
fprintf(stderr, "\n");
fprintf(stderr, "About: Left-align and normalize indels; check if REF alleles match the reference;\n");
fprintf(stderr, " split multiallelic sites into multiple rows; recover multiallelics from\n");
fprintf(stderr, " multiple rows.\n");
fprintf(stderr, "Usage: bcftools norm [options] <in.vcf.gz>\n");
fprintf(stderr, "\n");
fprintf(stderr, "Options:\n");
fprintf(stderr, " -c, --check-ref <e|w|x|s> check REF alleles and exit (e), warn (w), exclude (x), or set (s) bad sites [e]\n");
fprintf(stderr, " -D, --remove-duplicates remove duplicate lines of the same type.\n");
fprintf(stderr, " -d, --rm-dup <type> remove duplicate snps|indels|both|all|exact\n");
fprintf(stderr, " -f, --fasta-ref <file> reference sequence\n");
fprintf(stderr, " --force try to proceed even if malformed tags are encountered. Experimental, use at your own risk\n");
fprintf(stderr, " -m, --multiallelics <-|+>[type] split multiallelics (-) or join biallelics (+), type: snps|indels|both|any [both]\n");
fprintf(stderr, " --no-version do not append version and command line to the header\n");
fprintf(stderr, " -N, --do-not-normalize do not normalize indels (with -m or -c s)\n");
fprintf(stderr, " -o, --output <file> write output to a file [standard output]\n");
fprintf(stderr, " -O, --output-type <type> 'b' compressed BCF; 'u' uncompressed BCF; 'z' compressed VCF; 'v' uncompressed VCF [v]\n");
fprintf(stderr, " -r, --regions <region> restrict to comma-separated list of regions\n");
fprintf(stderr, " -R, --regions-file <file> restrict to regions listed in a file\n");
fprintf(stderr, " -s, --strict-filter when merging (-m+), merged site is PASS only if all sites being merged PASS\n");
fprintf(stderr, " -t, --targets <region> similar to -r but streams rather than index-jumps\n");
fprintf(stderr, " -T, --targets-file <file> similar to -R but streams rather than index-jumps\n");
fprintf(stderr, " --threads <int> use multithreading with <int> worker threads [0]\n");
fprintf(stderr, " -w, --site-win <int> buffer for sorting lines which changed position during realignment [1000]\n");
fprintf(stderr, "\n");
fprintf(stderr, "Examples:\n");
fprintf(stderr, " # normalize and left-align indels\n");
fprintf(stderr, " bcftools norm -f ref.fa in.vcf\n");
fprintf(stderr, "\n");
fprintf(stderr, " # split multi-allelic sites\n");
fprintf(stderr, " bcftools norm -m- in.vcf\n");
fprintf(stderr, "\n");
exit(1);
}
int main_vcfnorm(int argc, char *argv[])
{
int c;
args_t *args = (args_t*) calloc(1,sizeof(args_t));
args->argc = argc; args->argv = argv;
args->files = bcf_sr_init();
args->output_fname = "-";
args->output_type = FT_VCF;
args->n_threads = 0;
args->record_cmd_line = 1;
args->aln_win = 100;
args->buf_win = 1000;
args->mrows_collapse = COLLAPSE_BOTH;
args->do_indels = 1;
int region_is_file = 0;
int targets_is_file = 0;
static struct option loptions[] =
{
{"help",no_argument,NULL,'h'},
{"force",no_argument,NULL,7},
{"fasta-ref",required_argument,NULL,'f'},
{"do-not-normalize",no_argument,NULL,'N'},
{"multiallelics",required_argument,NULL,'m'},
{"regions",required_argument,NULL,'r'},
{"regions-file",required_argument,NULL,'R'},
{"targets",required_argument,NULL,'t'},
{"targets-file",required_argument,NULL,'T'},
{"site-win",required_argument,NULL,'w'},
{"remove-duplicates",no_argument,NULL,'D'},
{"rm-dup",required_argument,NULL,'d'},
{"output",required_argument,NULL,'o'},
{"output-type",required_argument,NULL,'O'},
{"threads",required_argument,NULL,9},
{"check-ref",required_argument,NULL,'c'},
{"strict-filter",no_argument,NULL,'s'},
{"no-version",no_argument,NULL,8},
{NULL,0,NULL,0}
};
char *tmp;
while ((c = getopt_long(argc, argv, "hr:R:f:w:Dd:o:O:c:m:t:T:sN",loptions,NULL)) >= 0) {
switch (c) {
case 'N': args->do_indels = 0; break;
case 'd':
if ( !strcmp("snps",optarg) ) args->rmdup = BCF_SR_PAIR_SNPS;
else if ( !strcmp("indels",optarg) ) args->rmdup = BCF_SR_PAIR_INDELS;
else if ( !strcmp("both",optarg) ) args->rmdup = BCF_SR_PAIR_BOTH;
else if ( !strcmp("all",optarg) ) args->rmdup = BCF_SR_PAIR_ANY;
else if ( !strcmp("any",optarg) ) args->rmdup = BCF_SR_PAIR_ANY;
else if ( !strcmp("none",optarg) ) args->rmdup = BCF_SR_PAIR_EXACT;
else if ( !strcmp("exact",optarg) ) args->rmdup = BCF_SR_PAIR_EXACT;
else error("The argument to -d not recognised: %s\n", optarg);
break;
case 'm':
if ( optarg[0]=='-' ) args->mrows_op = MROWS_SPLIT;
else if ( optarg[0]=='+' ) args->mrows_op = MROWS_MERGE;
else error("Expected '+' or '-' with -m\n");
if ( optarg[1]!=0 )
{
if ( !strcmp("snps",optarg+1) ) args->mrows_collapse = COLLAPSE_SNPS;
else if ( !strcmp("indels",optarg+1) ) args->mrows_collapse = COLLAPSE_INDELS;
else if ( !strcmp("both",optarg+1) ) args->mrows_collapse = COLLAPSE_BOTH;
else if ( !strcmp("any",optarg+1) ) args->mrows_collapse = COLLAPSE_ANY;
else error("The argument to -m not recognised: %s\n", optarg);
}
break;
case 'c':
if ( strchr(optarg,'w') ) args->check_ref |= CHECK_REF_WARN;
if ( strchr(optarg,'x') ) args->check_ref |= CHECK_REF_SKIP;
if ( strchr(optarg,'s') ) args->check_ref |= CHECK_REF_FIX;
if ( strchr(optarg,'e') ) args->check_ref = CHECK_REF_EXIT; // overrides the above
break;
case 'O':
switch (optarg[0]) {
case 'b': args->output_type = FT_BCF_GZ; break;
case 'u': args->output_type = FT_BCF; break;
case 'z': args->output_type = FT_VCF_GZ; break;
case 'v': args->output_type = FT_VCF; break;
default: error("The output type \"%s\" not recognised\n", optarg);
}
break;
case 'o': args->output_fname = optarg; break;
case 'D':
fprintf(stderr,"Warning: `-D` is functional but deprecated, replaced by and alias of `-d none`.\n");
args->rmdup = BCF_SR_PAIR_EXACT;
break;
case 's': args->strict_filter = 1; break;
case 'f': args->ref_fname = optarg; break;
case 'r': args->region = optarg; break;
case 'R': args->region = optarg; region_is_file = 1; break;
case 't': args->targets = optarg; break;
case 'T': args->targets = optarg; targets_is_file = 1; break;
case 'w':
args->buf_win = strtol(optarg,&tmp,10);
if ( *tmp ) error("Could not parse argument: --site-win %s\n", optarg);
break;
case 9 : args->n_threads = strtol(optarg, 0, 0); break;
case 8 : args->record_cmd_line = 0; break;
case 7 : args->force = 1; break;
case 'h':
case '?': usage(); break;
default: error("Unknown argument: %s\n", optarg);
}
}
char *fname = NULL;
if ( optind>=argc )
{
if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
else usage();
}
else fname = argv[optind];
if ( !args->ref_fname && !args->mrows_op && !args->rmdup ) error("Expected -f, -m, -D or -d option\n");
if ( !args->check_ref && args->ref_fname ) args->check_ref = CHECK_REF_EXIT;
if ( args->check_ref && !args->ref_fname ) error("Expected --fasta-ref with --check-ref\n");
if ( args->region )
{
if ( bcf_sr_set_regions(args->files, args->region,region_is_file)<0 )
error("Failed to read the regions: %s\n", args->region);
}
if ( args->targets )
{
if ( bcf_sr_set_targets(args->files, args->targets,targets_is_file, 0)<0 )
error("Failed to read the targets: %s\n", args->targets);
}
if ( bcf_sr_set_threads(args->files, args->n_threads)<0 ) error("Failed to create threads\n");
if ( !bcf_sr_add_reader(args->files, fname) ) error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum));
if ( args->mrows_op&MROWS_SPLIT && args->rmdup ) error("Cannot combine -D and -m-\n");
init_data(args);
normalize_vcf(args);
destroy_data(args);
bcf_sr_destroy(args->files);
free(args);
return 0;
}
|